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 ++++++++++++++++++++++++++++++++++++ src/static/js/client/index.js | 2 ++ 2 files changed, 64 insertions(+) create mode 100644 src/static/js/client/dragged-link.js (limited to 'src/static/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); + }); +} diff --git a/src/static/js/client/index.js b/src/static/js/client/index.js index e2e5b75b..52d2afd6 100644 --- a/src/static/js/client/index.js +++ b/src/static/js/client/index.js @@ -7,6 +7,7 @@ import * as albumCommentarySidebarModule from './album-commentary-sidebar.js'; import * as artistExternalLinkTooltipModule from './artist-external-link-tooltip.js'; import * as cssCompatibilityAssistantModule from './css-compatibility-assistant.js'; import * as datetimestampTooltipModule from './datetimestamp-tooltip.js'; +import * as draggedLinkModule from './dragged-link.js'; import * as hashLinkModule from './hash-link.js'; import * as hoverableTooltipModule from './hoverable-tooltip.js'; import * as imageOverlayModule from './image-overlay.js'; @@ -26,6 +27,7 @@ export const modules = [ artistExternalLinkTooltipModule, cssCompatibilityAssistantModule, datetimestampTooltipModule, + draggedLinkModule, hashLinkModule, hoverableTooltipModule, imageOverlayModule, -- cgit 1.3.0-6-gf8a5