diff --git a/example/example.js b/example/example.js index c82bfe5..f00cee9 100644 --- a/example/example.js +++ b/example/example.js @@ -4,6 +4,7 @@ function main() { const status = document.getElementById("status"); const startButton = document.getElementById("start"); const onlyEmphasisCheckbox = document.getElementById("only-emphasis"); + const onlyParagraphsCheckbox = document.getElementById("only-paragraphs"); const setElement = (el) => { const tags = []; @@ -27,6 +28,10 @@ function main() { onlyEmphasisCheckbox.onchange = (ev) => { onlyEmphasis = ev.target.checked; } + let onlyParagraphs = onlyParagraphsCheckbox.checked; + onlyParagraphsCheckbox.onchange = (ev) => { + onlyParagraphs = ev.target.checked; + } const start = () => { startButton.disabled = true; picker.start({ @@ -36,10 +41,14 @@ function main() { startButton.disabled = false; }, elementFilter: (el) => { - if (!onlyEmphasis) { - return true; + if (onlyEmphasis) { + return ['I', 'B'].includes(el.tagName); + } + else if (onlyParagraphs) { + const paragraph = el.closest("p, h1") + return paragraph ?? false } - return ['I', 'B'].includes(el.tagName); + return true; } }); }; diff --git a/example/index.html b/example/index.html index c7a2b55..a179993 100644 --- a/example/index.html +++ b/example/index.html @@ -23,5 +23,6 @@

Element Picker example

Click "start" to activate the picker.
+ diff --git a/src/element-picker.ts b/src/element-picker.ts index bb01f4a..e454ba8 100644 --- a/src/element-picker.ts +++ b/src/element-picker.ts @@ -7,7 +7,7 @@ type ElementPickerOptions = { useShadowDOM?: boolean; onClick?: ElementCallback; onHover?: ElementCallback; - elementFilter?: ElementCallback; + elementFilter?: ElementCallback; }; export default class ElementPicker { @@ -85,7 +85,7 @@ export default class ElementPicker { // Peek through the overlay to find the new target this.overlay.ignoreCursor(); const elAtCursor = document.elementFromPoint(this.mouseX, this.mouseY); - const newTarget = elAtCursor as HTMLElement; + let newTarget = elAtCursor as HTMLElement; this.overlay.captureCursor(); // If the target hasn't changed, there's nothing to do @@ -96,11 +96,19 @@ export default class ElementPicker { // If we have an element filter and the new target doesn't match, // clear out the target if (this.options?.elementFilter) { - if (!this.options.elementFilter(newTarget)) { + const filterResult = this.options.elementFilter(newTarget) + if (filterResult === false) { this.target = undefined; this.overlay.setBounds({ x: 0, y: 0, width: 0, height: 0 }); return; } + // If the filter returns an element, use that element as new target + else if (typeof filterResult !== "boolean") { + if (filterResult === this.target) { + return; + } + newTarget = filterResult + } } this.target = newTarget;