|
| 1 | +import $ from 'jquery'; |
| 2 | +import {generateAriaId} from './base.js'; |
| 3 | + |
| 4 | +const ariaPatchKey = '_giteaAriaPatchCheckbox'; |
| 5 | +const fomanticCheckboxFn = $.fn.checkbox; |
| 6 | + |
| 7 | +// use our own `$.fn.checkbox` to patch Fomantic's checkbox module |
| 8 | +export function initAriaCheckboxPatch() { |
| 9 | + if ($.fn.checkbox === ariaCheckboxFn) throw new Error('initAriaCheckboxPatch could only be called once'); |
| 10 | + $.fn.checkbox = ariaCheckboxFn; |
| 11 | + ariaCheckboxFn.settings = fomanticCheckboxFn.settings; |
| 12 | +} |
| 13 | + |
| 14 | +// the patched `$.fn.checkbox` checkbox function |
| 15 | +// * it does the one-time attaching on the first call |
| 16 | +function ariaCheckboxFn(...args) { |
| 17 | + const ret = fomanticCheckboxFn.apply(this, args); |
| 18 | + for (const el of this) { |
| 19 | + if (el[ariaPatchKey]) continue; |
| 20 | + attachInit(el); |
| 21 | + } |
| 22 | + return ret; |
| 23 | +} |
| 24 | + |
| 25 | +function attachInit(el) { |
| 26 | + // Fomantic UI checkbox needs to be something like: <div class="ui checkbox"><label /><input /></div> |
| 27 | + // It doesn't work well with <label><input />...</label> |
| 28 | + // To make it work with aria, the "id"/"for" attributes are necessary, so add them automatically if missing. |
| 29 | + // In the future, refactor to use native checkbox directly, then this patch could be removed. |
| 30 | + el[ariaPatchKey] = {}; // record that this element has been patched |
| 31 | + const label = el.querySelector('label'); |
| 32 | + const input = el.querySelector('input'); |
| 33 | + if (!label || !input || input.getAttribute('id')) return; |
| 34 | + |
| 35 | + const id = generateAriaId(); |
| 36 | + input.setAttribute('id', id); |
| 37 | + label.setAttribute('for', id); |
| 38 | +} |
0 commit comments