From a1d61014c37ccbfe26fee18abab221a7ef2f0583 Mon Sep 17 00:00:00 2001 From: "(quasar) nebula" Date: Wed, 11 Dec 2024 17:07:58 -0400 Subject: client: dragged-link helper module --- src/static/js/client/dragged-link.js | 62 ++++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 src/static/js/client/dragged-link.js (limited to 'src/static/js/client/dragged-link.js') 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); + }); +} -- cgit 1.3.0-6-gf8a5