1 /**
2 * Copyright © DiamondMVC 2019
3 * License: MIT (https://github.com/DiamondMVC/Diamond/blob/master/LICENSE)
4 * Author: Jacob Jensen (bausshf)
5 */
6 module diamond.web.elements.select;
7 
8 import diamond.web.elements.input;
9 
10 /// Wrapper around a select input.
11 final class Select : Input
12 {
13   private:
14   /// The associated form.
15   string _form;
16 
17   /// The options.
18   string[string] _options;
19 
20   public:
21   final:
22   /// Creates a new select input.
23   this()
24   {
25     super("select");
26   }
27 
28   @property
29   {
30     /// Gets the form.
31     string form() { return _form; }
32 
33     /// Sets the form.
34     void form(string newForm)
35     {
36       _form = newForm;
37 
38       addAttribute("form", _form);
39     }
40   }
41 
42   /**
43   * Adds an option.
44   * Params:
45   *   value = The value of the option.
46   *   text =  The text of the option.
47   */
48   void addOption(string value, string text)
49   {
50     _options[value] = text;
51   }
52 
53   /**
54   * Gets an option.
55   * Params:
56   *   value = The value of the option.
57   * Returns:
58   *   The text of the option if found, null otherwise.
59   */
60   string getOption(string value)
61   {
62     return _options.get(value, null);
63   }
64 
65   /**
66   * Removes an option.
67   * Params:
68   *   value = The value of the option to remove.
69   */
70   void removeOption(string value)
71   {
72     _options.remove(value);
73   }
74 
75   protected:
76   /// Generates the appropriate html for the element.
77   override string generateHtml()
78   {
79     import std..string : format;
80     import std.array : join;
81 
82     string[] options;
83 
84     foreach (value,text; _options)
85     {
86       options ~= "<option value=\"%s\">%s</option>".format(value,text);
87     }
88 
89     auto optionsHtml = options ? options.join("\n") : "";
90 
91     return "%3$s<%1$s %2$s>%4$s</%1$s>".format
92     (
93       super.tagName, super.attributeHtml(),
94       super.label && super.label.length && super.id && super.id.length ?
95       "<label for=\"%s\">%s</label>".format(super.id, super.label) : "",
96       optionsHtml
97     );
98   }
99 }