auth

Main authentication module for my projects
git clone git://git.finwo.net/app/auth
Log | Files | Refs

shell.js (14290B)


      1 (() => {
      2   const root = document.documentElement;
      3   const nav = document.getElementById('mobile-navigation');
      4   const toggle = document.getElementById('mobile-nav-toggle');
      5   const main = document.querySelector('.main');
      6   const desktop = window.matchMedia('(min-width: 60em)');
      7 
      8   if (nav && toggle) {
      9     const setOpen = (open) => {
     10       nav.classList.toggle('is-open', open);
     11       nav.setAttribute('aria-hidden', open ? 'false' : 'true');
     12       toggle.classList.toggle('is-open', open);
     13       toggle.setAttribute('aria-expanded', open ? 'true' : 'false');
     14       toggle.setAttribute('aria-label', open ? 'Close navigation' : 'Open navigation');
     15       root.classList.toggle('mobile-nav-open', open);
     16 
     17       if (main) main.inert = open;
     18     };
     19 
     20     const isOpen = () => toggle.getAttribute('aria-expanded') === 'true';
     21 
     22     toggle.addEventListener('click', () => setOpen(!isOpen()));
     23 
     24     nav.addEventListener('click', (event) => {
     25       const target = event.target;
     26       if (!(target instanceof Element)) return;
     27 
     28       if (target.closest('.nav-item')) {
     29         setOpen(false);
     30         return;
     31       }
     32 
     33       if (!target.closest('.menu-item, button, a')) setOpen(false);
     34     });
     35 
     36     document.addEventListener('keydown', (event) => {
     37       if (event.key === 'Escape' && isOpen()) {
     38         setOpen(false);
     39         toggle.focus();
     40       }
     41     });
     42 
     43     desktop.addEventListener('change', (event) => {
     44       if (event.matches) setOpen(false);
     45     });
     46 
     47     if (desktop.matches) setOpen(false);
     48   }
     49 
     50   const selects = [];
     51   let selectId = 0;
     52 
     53   const nextId = (prefix) => {
     54     selectId += 1;
     55     return `${prefix}-${selectId}`;
     56   };
     57 
     58   const fontSize = () => {
     59     const size = Number.parseFloat(window.getComputedStyle(root).fontSize);
     60 
     61     return Number.isFinite(size) && size > 0 ? size : 16;
     62   };
     63 
     64   const toRem = (value) => {
     65     const rounded = Math.round((value / fontSize()) * 100) / 100;
     66 
     67     return `${rounded < 0 ? 0 : rounded}rem`;
     68   };
     69 
     70   const fitSelectWidth = (select) => {
     71     const previousHidden = select.list.hidden;
     72     select.list.hidden = false;
     73     select.list.classList.add('is-measuring');
     74 
     75     const containerWidth = select.container.getBoundingClientRect().width;
     76 
     77     if (containerWidth > 0) {
     78       const measuredWidth = Math.max(containerWidth, select.list.getBoundingClientRect().width);
     79       const allowedWidth = Math.min(measuredWidth, window.innerWidth - fontSize());
     80 
     81       select.container.style.minWidth = `${allowedWidth / fontSize()}rem`;
     82     }
     83 
     84     select.list.classList.remove('is-measuring');
     85     select.list.hidden = previousHidden;
     86   };
     87 
     88   const activeOption = (select) => {
     89     if (select.activeIndex < 0) return null;
     90 
     91     return select.options[select.activeIndex] || null;
     92   };
     93 
     94   const setActive = (select, index, scroll) => {
     95     const options = select.options;
     96     if (!options.length) return;
     97 
     98     const nextIndex = Math.max(0, Math.min(index, options.length - 1));
     99 
    100     if (select.activeIndex === nextIndex) {
    101       if (scroll) scrollActiveOption(select);
    102 
    103       return;
    104     }
    105 
    106     options.forEach((option, optionIndex) => {
    107       option.classList.toggle('is-active', optionIndex === nextIndex);
    108     });
    109 
    110     select.activeIndex = nextIndex;
    111 
    112     const option = options[nextIndex];
    113     if (!option) return;
    114 
    115     select.trigger.setAttribute('aria-activedescendant', option.id);
    116     if (scroll) scrollActiveOption(select);
    117   };
    118 
    119   const scrollActiveOption = (select) => {
    120     const option = activeOption(select);
    121     if (!option) return;
    122 
    123     const optionTop = option.offsetTop;
    124     const optionBottom = optionTop + option.offsetHeight;
    125 
    126     if (optionTop < select.list.scrollTop) {
    127       select.list.scrollTop = optionTop;
    128       return;
    129     }
    130 
    131     if (optionBottom > select.list.scrollTop + select.list.clientHeight) {
    132       select.list.scrollTop = optionBottom - select.list.clientHeight;
    133     }
    134   };
    135 
    136   const positionSelect = (select) => {
    137     if (!select.open) return;
    138 
    139     const triggerRect = select.trigger.getBoundingClientRect();
    140     const rootFontSize = fontSize();
    141     const viewportWidth = window.innerWidth / rootFontSize;
    142     const triggerLeft = triggerRect.left / rootFontSize;
    143     const listWidth = Math.min(triggerRect.width / rootFontSize, viewportWidth - 1);
    144     const spaceBelow = (window.innerHeight - triggerRect.bottom) / rootFontSize - 0.5;
    145     const spaceAbove = triggerRect.top / rootFontSize - 0.5;
    146     const openBelow = spaceBelow >= spaceAbove;
    147     const availableHeight = openBelow ? spaceBelow : spaceAbove;
    148     const listHeight = Math.max(5, Math.min(18, availableHeight));
    149 
    150     select.list.style.width = `${listWidth}rem`;
    151     select.list.style.maxHeight = `${listHeight}rem`;
    152     select.list.style.right = 'auto';
    153     select.list.style.left = `${Math.max(0, Math.min(triggerLeft, viewportWidth - listWidth))}rem`;
    154 
    155     if (openBelow) {
    156       select.list.style.top = `${triggerRect.bottom / rootFontSize}rem`;
    157       select.list.style.bottom = 'auto';
    158     } else {
    159       select.list.style.top = 'auto';
    160       select.list.style.bottom = `${(window.innerHeight - triggerRect.top) / rootFontSize}rem`;
    161     }
    162   };
    163 
    164   const openSelect = (select, index) => {
    165     if (select.open || select.trigger.disabled || !select.options.length) return;
    166 
    167     select.open = true;
    168     select.list.hidden = false;
    169     select.trigger.setAttribute('aria-expanded', 'true');
    170     setActive(select, index, false);
    171     positionSelect(select);
    172   };
    173 
    174   const closeSelect = (select, focusTrigger) => {
    175     if (!select.open) return;
    176 
    177     select.open = false;
    178     select.list.hidden = true;
    179     select.list.style.width = '';
    180     select.list.style.maxHeight = '';
    181     select.list.style.left = '';
    182     select.list.style.right = '';
    183     select.list.style.top = '';
    184     select.list.style.bottom = '';
    185     select.trigger.removeAttribute('aria-activedescendant');
    186     select.trigger.setAttribute('aria-expanded', 'false');
    187     select.activeIndex = -1;
    188     select.typeahead = '';
    189     select.options.forEach((option) => option.classList.remove('is-active'));
    190 
    191     if (focusTrigger) select.trigger.focus();
    192   };
    193 
    194   const selectOption = (select, index) => {
    195     const option = select.options[index];
    196     if (!option) return;
    197 
    198     const value = option.dataset.value || option.textContent.trim();
    199     const label = option.querySelector('.select-option-label').textContent;
    200 
    201     select.container.dataset.value = value;
    202     select.value.textContent = label;
    203     select.options.forEach((candidate, candidateIndex) => {
    204       const selected = candidateIndex === index;
    205       candidate.classList.toggle('is-selected', selected);
    206       candidate.setAttribute('aria-selected', selected ? 'true' : 'false');
    207     });
    208 
    209     closeSelect(select, true);
    210   };
    211 
    212   const findSelected = (select) => {
    213     const index = select.options.findIndex((option) => option.classList.contains('is-selected'));
    214 
    215     return index >= 0 ? index : 0;
    216   };
    217 
    218   const findMatch = (select, query) => {
    219     const start = select.activeIndex + 1;
    220 
    221     for (let offset = 0; offset < select.options.length; offset += 1) {
    222       const index = (start + offset) % select.options.length;
    223       const label = select.options[index].dataset.label || '';
    224       if (label.toLowerCase().startsWith(query.toLowerCase())) return index;
    225     }
    226 
    227     return -1;
    228   };
    229 
    230   document.querySelectorAll('[data-select]').forEach((container) => {
    231     const trigger = container.querySelector('.select-trigger');
    232     const list = container.querySelector('.select-list');
    233     const options = Array.from(container.querySelectorAll('.select-option'));
    234     if (!trigger || !list || !options.length) return;
    235 
    236     if (!trigger.id) trigger.id = nextId('select-trigger');
    237     if (!list.id) list.id = nextId('select-list');
    238     options.forEach((option, index) => {
    239       if (!option.id) option.id = `${list.id}-option-${index + 1}`;
    240       if (!option.dataset.label) option.dataset.label = option.textContent.trim();
    241     });
    242 
    243     const select = {
    244       container,
    245       trigger,
    246       list,
    247       options,
    248       value: trigger.querySelector('.select-value'),
    249       open: false,
    250       activeIndex: -1,
    251       typeahead: '',
    252       typeaheadTimer: 0,
    253     };
    254 
    255     selects.push(select);
    256 
    257     trigger.setAttribute('role', 'combobox');
    258     trigger.setAttribute('aria-haspopup', 'listbox');
    259     trigger.setAttribute('aria-expanded', 'false');
    260     trigger.setAttribute('aria-controls', list.id);
    261     list.setAttribute('role', 'listbox');
    262     if (!list.getAttribute('aria-labelledby')) {
    263       list.setAttribute('aria-labelledby', trigger.getAttribute('aria-labelledby') || trigger.id);
    264     }
    265 
    266     if (!container.dataset.value) {
    267       const selected = options.find((option) => option.classList.contains('is-selected'));
    268       container.dataset.value = selected ? selected.dataset.value || selected.textContent.trim() : '';
    269     }
    270 
    271     options.forEach((option) => {
    272       option.setAttribute('role', 'option');
    273       option.tabIndex = -1;
    274     });
    275 
    276     trigger.addEventListener('click', (event) => {
    277       event.preventDefault();
    278       if (select.open) closeSelect(select, true);
    279       else openSelect(select, findSelected(select));
    280     });
    281 
    282     trigger.addEventListener('keydown', (event) => {
    283       const keys = ['ArrowDown', 'ArrowUp', 'Home', 'End', 'Enter', ' '];
    284       if (event.altKey || event.ctrlKey || event.metaKey) return;
    285 
    286       if (event.key === 'Escape') {
    287         if (!select.open) return;
    288         event.preventDefault();
    289         event.stopPropagation();
    290         closeSelect(select, true);
    291         return;
    292       }
    293 
    294       if (event.key === 'Tab') {
    295         closeSelect(select, false);
    296         return;
    297       }
    298 
    299       if (!keys.includes(event.key) && event.key.length === 1) {
    300         event.preventDefault();
    301         if (!select.open) openSelect(select, 0);
    302         select.typeahead += event.key;
    303         window.clearTimeout(select.typeaheadTimer);
    304         select.typeaheadTimer = window.setTimeout(() => {
    305           select.typeahead = '';
    306         }, 500);
    307 
    308         const match = findMatch(select, select.typeahead);
    309         if (match >= 0) setActive(select, match, true);
    310 
    311         return;
    312       }
    313 
    314       if (!keys.includes(event.key)) return;
    315 
    316       event.preventDefault();
    317 
    318       if (!select.open) {
    319         openSelect(select, event.key === 'ArrowUp' ? select.options.length - 1 : 0);
    320         return;
    321       }
    322 
    323       if (event.key === 'Home') setActive(select, 0, true);
    324       else if (event.key === 'End') setActive(select, select.options.length - 1, true);
    325       else if (event.key === 'ArrowDown') setActive(select, select.activeIndex + 1, true);
    326       else if (event.key === 'ArrowUp') setActive(select, select.activeIndex - 1, true);
    327       else if (event.key === 'Enter' || event.key === ' ') selectOption(select, select.activeIndex);
    328     });
    329 
    330     options.forEach((option, index) => {
    331       option.addEventListener('click', (event) => {
    332         event.stopPropagation();
    333         selectOption(select, index);
    334       });
    335     });
    336 
    337     fitSelectWidth(select);
    338     closeSelect(select, false);
    339   });
    340 
    341   const refitSelectWidths = () => {
    342     selects.forEach((select) => fitSelectWidth(select));
    343     repositionOpenSelects();
    344   };
    345 
    346   document.addEventListener('click', (event) => {
    347     const target = event.target;
    348 
    349     selects.forEach((select) => {
    350       if (select.open && (!(target instanceof Node) || !select.container.contains(target))) {
    351         closeSelect(select, false);
    352       }
    353     });
    354   });
    355 
    356   const repositionOpenSelects = () => {
    357     selects.forEach((select) => positionSelect(select));
    358   };
    359 
    360   window.addEventListener('resize', refitSelectWidths);
    361   window.addEventListener('scroll', repositionOpenSelects, true);
    362 
    363   /* Paged table: mockup mirror of the server pagination contract.
    364      Filters rows by data-search, pages the matched set, count = page object. */
    365   document.querySelectorAll('[data-pager]').forEach((pager) => {
    366     const table = document.getElementById(pager.dataset.pagerTable);
    367     if (!table) return;
    368     const rows = Array.from(table.querySelectorAll('tbody tr'));
    369     const count = pager.querySelector('[data-pager-count]');
    370     const prev = pager.querySelector('[data-pager-prev]');
    371     const next = pager.querySelector('[data-pager-next]');
    372     const search = pager.dataset.pagerSearch
    373       ? document.getElementById(pager.dataset.pagerSearch)
    374       : null;
    375     const empty = document.querySelector('[data-pager-empty]');
    376     const pageSize = Math.max(1, parseInt(pager.dataset.pageSize, 10) || 5);
    377     let page = 1;
    378 
    379     const matched = () => {
    380       const term = search ? search.value.trim().toLowerCase() : '';
    381       return rows.filter((row) => !term || row.dataset.search.includes(term));
    382     };
    383 
    384     const render = () => {
    385       const list = matched();
    386       const pages = Math.max(1, Math.ceil(list.length / pageSize));
    387       if (page > pages) page = pages;
    388       const start = (page - 1) * pageSize;
    389       rows.forEach((row) => { row.hidden = true; });
    390       list.slice(start, start + pageSize).forEach((row) => { row.hidden = false; });
    391       if (count) {
    392         count.textContent = list.length
    393           ? `Showing ${start + 1}-${Math.min(start + pageSize, list.length)} of ${list.length}`
    394           : 'Showing 0 of 0';
    395       }
    396       if (prev) prev.disabled = page <= 1;
    397       if (next) next.disabled = page >= pages;
    398       pager.hidden = list.length <= pageSize;
    399       if (empty) empty.hidden = list.length > 0;
    400     };
    401 
    402     if (search) search.addEventListener('input', () => { page = 1; render(); });
    403     if (prev) prev.addEventListener('click', () => { page -= 1; render(); });
    404     if (next) next.addEventListener('click', () => { page += 1; render(); });
    405     render();
    406   });
    407 
    408   /* Row -> dialog: copies data-session-* to [data-session-field] targets. */
    409   document.querySelectorAll('tr[data-row-dialog]').forEach((row) => {
    410     row.addEventListener('click', () => {
    411       const dialog = document.getElementById(row.dataset.rowDialog);
    412       if (!dialog) return;
    413       Object.entries(row.dataset).forEach(([key, value]) => {
    414         if (!key.startsWith('session')) return;
    415         const field = key.slice('session'.length).toLowerCase();
    416         const target = dialog.querySelector(`[data-session-field="${field}"]`);
    417         if (target) target.textContent = value || 'None';
    418       });
    419       dialog.hidden = false;
    420       dialog.querySelector('.modal-close')?.focus();
    421     });
    422   });
    423 })();