diff options
author | (quasar) nebula <qznebula@protonmail.com> | 2024-10-15 23:18:02 -0300 |
---|---|---|
committer | (quasar) nebula <qznebula@protonmail.com> | 2024-11-02 22:12:48 -0300 |
commit | 53eb9d679e9b43f59320b39a52421cb33a15f9de (patch) | |
tree | 25ee1742a8558494097f37d37222d59ca70a1140 /src/static/js/client/intrapage-dot-switcher.js | |
parent | b657f641c89ceee7676dc6d29fe4b9a168a97266 (diff) |
content, client: generateIntrapageDotSwitcher
Diffstat (limited to 'src/static/js/client/intrapage-dot-switcher.js')
-rw-r--r-- | src/static/js/client/intrapage-dot-switcher.js | 82 |
1 files changed, 82 insertions, 0 deletions
diff --git a/src/static/js/client/intrapage-dot-switcher.js b/src/static/js/client/intrapage-dot-switcher.js new file mode 100644 index 00000000..d06bc5a6 --- /dev/null +++ b/src/static/js/client/intrapage-dot-switcher.js @@ -0,0 +1,82 @@ +/* eslint-env browser */ + +import {stitchArrays} from '../../shared-util/sugar.js'; + +import {cssProp} from '../client-util.js'; + +export const info = { + id: 'intrapageDotSwitcherInfo', + + // Each is a two-level array, by switcher. + // This is an evil data structure. + switcherSpans: null, + switcherLinks: null, + switcherTargets: null, +}; + +export function getPageReferences() { + const switchers = + Array.from(document.querySelectorAll('.dot-switcher.intrapage')); + + info.switcherSpans = + switchers + .map(switcher => switcher.querySelectorAll(':scope > span')) + .map(spans => Array.from(spans)); + + info.switcherLinks = + info.switcherSpans + .map(spans => spans + .map(span => span.querySelector(':scope > a'))); + + info.switcherTargets = + info.switcherLinks + .map(links => links + .map(link => { + const targetID = link.getAttribute('data-target-id'); + const target = document.getElementById(targetID); + if (target) { + return target; + } else { + console.warn( + `An intrapage dot switcher option is targetting an ID that doesn't exist, #${targetID}`, + link); + link.setAttribute('inert', ''); + return null; + } + })); +} + +export function addPageListeners() { + for (const {links, spans, targets} of stitchArrays({ + spans: info.switcherSpans, + links: info.switcherLinks, + targets: info.switcherTargets, + })) { + for (const [index, {span, link, target}] of stitchArrays({ + span: spans, + link: links, + target: targets, + }).entries()) { + const otherSpans = + [...spans.slice(0, index), ...spans.slice(index + 1)]; + + const otherTargets = + [...targets.slice(0, index), ...targets.slice(index + 1)]; + + link.addEventListener('click', domEvent => { + domEvent.preventDefault(); + + for (const otherSpan of otherSpans) { + otherSpan.classList.remove('current'); + } + + for (const otherTarget of otherTargets) { + cssProp(otherTarget, 'display', 'none'); + } + + span.classList.add('current'); + cssProp(target, 'display', 'block'); + }); + } + } +} |