* Checks if a given mutation record is relevant for resyncing a ` `. * In general it's relevant if: * - Non comment nodes were added to / removed from the select * - The text of an option without a value attribute changed * - The value attribute of an option changed. * * @param mutation
(mutation: MutationRecord)
| 54 | * @returns Whether the mutation is relevant for resyncing the `<select>`. |
| 55 | */ |
| 56 | function isRelevantSelectMutation(mutation: MutationRecord): boolean { |
| 57 | // Consider changes that may add / remove options. |
| 58 | if (mutation.type === 'childList') { |
| 59 | // If any non-comment nodes were added / removed it is relevant. |
| 60 | for (const node of mutation.addedNodes) { |
| 61 | if (!(node instanceof Comment)) { |
| 62 | return true; |
| 63 | } |
| 64 | } |
| 65 | for (const node of mutation.removedNodes) { |
| 66 | if (!(node instanceof Comment)) { |
| 67 | return true; |
| 68 | } |
| 69 | } |
| 70 | // Otherwise it's not relevant. |
| 71 | return false; |
| 72 | } |
| 73 | // If the text of an option changed, it's only relevant if the option has no value attribute, |
| 74 | // because only then is the text used as its value. |
| 75 | if (mutation.type === 'characterData') { |
| 76 | // If the target is a comment it's not relevant. |
| 77 | if (mutation.target instanceof Comment) { |
| 78 | return false; |
| 79 | } |
| 80 | // The target is the text node. Its option is the parent or a further ancestor: |
| 81 | // `<option>{{ x }}</option>` or `<option><span>{{ x }}</span></option>` |
| 82 | const option = mutation.target.parentElement?.closest('option'); |
| 83 | return option instanceof HTMLOptionElement && !option.hasAttribute('value'); |
| 84 | } |
| 85 | // If the value attribute of an option changed, it's relevant. |
| 86 | if (mutation.type === 'attributes' && mutation.target instanceof HTMLOptionElement) { |
| 87 | return true; |
| 88 | } |
| 89 | // Everything else is not relevant. |
| 90 | return false; |
| 91 | } |
no test coverage detected