( element: Element, value: ?string, defaultValue: ?string, multiple: ?boolean, )
| 159 | } |
| 160 | |
| 161 | export function hydrateSelect( |
| 162 | element: Element, |
| 163 | value: ?string, |
| 164 | defaultValue: ?string, |
| 165 | multiple: ?boolean, |
| 166 | ): void { |
| 167 | const node: HTMLSelectElement = (element: any); |
| 168 | const options: HTMLOptionsCollection = node.options; |
| 169 | |
| 170 | const propValue: any = value != null ? value : defaultValue; |
| 171 | |
| 172 | let changed = false; |
| 173 | |
| 174 | if (multiple) { |
| 175 | const selectedValues = (propValue: ?Array<string>); |
| 176 | const selectedValue: {[string]: boolean} = {}; |
| 177 | if (selectedValues != null) { |
| 178 | for (let i = 0; i < selectedValues.length; i++) { |
| 179 | // Prefix to avoid chaos with special keys. |
| 180 | selectedValue['$' + selectedValues[i]] = true; |
| 181 | } |
| 182 | } |
| 183 | for (let i = 0; i < options.length; i++) { |
| 184 | const expectedSelected = selectedValue.hasOwnProperty( |
| 185 | '$' + options[i].value, |
| 186 | ); |
| 187 | if (options[i].selected !== expectedSelected) { |
| 188 | changed = true; |
| 189 | break; |
| 190 | } |
| 191 | } |
| 192 | } else { |
| 193 | let selectedValue = |
| 194 | propValue == null ? null : toString(getToStringValue(propValue)); |
| 195 | for (let i = 0; i < options.length; i++) { |
| 196 | if (selectedValue == null && !options[i].disabled) { |
| 197 | // We expect the first non-disabled option to be selected if the selected is null. |
| 198 | selectedValue = options[i].value; |
| 199 | } |
| 200 | const expectedSelected = options[i].value === selectedValue; |
| 201 | if (options[i].selected !== expectedSelected) { |
| 202 | changed = true; |
| 203 | break; |
| 204 | } |
| 205 | } |
| 206 | } |
| 207 | if (changed) { |
| 208 | // If the current selection is different than our initial that suggests that the user |
| 209 | // changed it before hydration. Queue a replay of the change event. |
| 210 | queueChangeEvent(node); |
| 211 | } |
| 212 | } |
| 213 | |
| 214 | export function updateSelect( |
| 215 | element: Element, |
no test coverage detected