diff options
author | (quasar) nebula <qznebula@protonmail.com> | 2024-12-11 17:07:58 -0400 |
---|---|---|
committer | (quasar) nebula <qznebula@protonmail.com> | 2024-12-11 17:07:58 -0400 |
commit | a1d61014c37ccbfe26fee18abab221a7ef2f0583 (patch) | |
tree | 4200a21827cf922ee2a03760581bc9bcd8c34fd7 /src/static/js/client/dragged-link.js | |
parent | 5735f48c3b5caa22c42ae5190df47e8416fbbad8 (diff) |
client: dragged-link helper module
Diffstat (limited to 'src/static/js/client/dragged-link.js')
-rw-r--r-- | src/static/js/client/dragged-link.js | 62 |
1 files changed, 62 insertions, 0 deletions
diff --git a/src/static/js/client/dragged-link.js b/src/static/js/client/dragged-link.js new file mode 100644 index 00000000..56021e7f --- /dev/null +++ b/src/static/js/client/dragged-link.js @@ -0,0 +1,62 @@ +/* eslint-env browser */ + +export const info = { + id: `draggedLinkInfo`, + + state: { + latestDraggedLink: null, + observedLinks: new WeakSet(), + }, +}; + +export function getPageReferences() { + // First start handling all the links that currently exist. + + for (const a of document.getElementsByTagName('a')) { + observeLink(a); + addDragListener(a); + } + + // Then add a mutation observer to track new links. + + const observer = new MutationObserver(records => { + for (const record of records) { + for (const node of record.addedNodes) { + if (node.nodeName !== 'A') continue; + observeLink(node); + } + } + }); + + observer.observe(document.body, { + subtree: true, + childList: true, + }); +} + +export function getLatestDraggedLink() { + const {state} = info; + + if (state.latestDraggedLink) { + return state.latestDraggedLink.deref() ?? null; + } else { + return null; + } +} + +function observeLink(link) { + const {state} = info; + + if (state.observedLinks.has(link)) return; + + state.observedLinks.add(link); + addDragListener(link); +} + +function addDragListener(link) { + const {state} = info; + + link.addEventListener('dragstart', _domEvent => { + state.latestDraggedLink = new WeakRef(link); + }); +} |