diff --git a/demo/shadow-dom.html b/demo/shadow-dom.html
new file mode 100644
index 00000000..7a2d9caf
--- /dev/null
+++ b/demo/shadow-dom.html
@@ -0,0 +1,73 @@
+
+
+
+
+ Gleap tours inside a shadow root
+
+
+
+
+
+
+
+
+
diff --git a/src/ElementPicker.js b/src/ElementPicker.js
index 32c6b506..7bac2728 100644
--- a/src/ElementPicker.js
+++ b/src/ElementPicker.js
@@ -13,6 +13,27 @@ function getElementBounds(el) {
};
}
+/**
+ * `document.elementFromPoint` that keeps going into open shadow roots. The
+ * document only ever reports the shadow host, which would make everything
+ * inside a web component pick as one element.
+ * @param {number} x - The x-coordinate.
+ * @param {number} y - The y-coordinate.
+ * @returns {Element|null} The innermost element at that point.
+ */
+function deepElementFromPoint(x, y) {
+ let el = document.elementFromPoint(x, y);
+ while (el && el.shadowRoot && typeof el.shadowRoot.elementFromPoint === 'function') {
+ const inner = el.shadowRoot.elementFromPoint(x, y);
+ // Browsers may answer with an element outside of the shadow tree.
+ if (!inner || inner === el || inner.getRootNode() !== el.shadowRoot) {
+ break;
+ }
+ el = inner;
+ }
+ return el;
+}
+
/**
* Class representing an overlay element.
*/
@@ -193,7 +214,7 @@ class ElementPicker {
* @param {MouseEvent} event - The click event.
*/
handleClick(event) {
- const clickedEl = document.elementFromPoint(event.clientX, event.clientY);
+ const clickedEl = deepElementFromPoint(event.clientX, event.clientY);
if (this.options && this.options.elementFilter && clickedEl && !this.options.elementFilter(clickedEl)) {
return;
}
@@ -225,7 +246,7 @@ class ElementPicker {
// Temporarily ignore the overlay's pointer events to detect the underlying element.
this.overlay.ignoreCursor();
- const elAtCursor = document.elementFromPoint(this.mouseX, this.mouseY);
+ const elAtCursor = deepElementFromPoint(this.mouseX, this.mouseY);
const newTarget = elAtCursor;
this.overlay.captureCursor();
diff --git a/src/GleapAdminHelper.js b/src/GleapAdminHelper.js
index f1f1c5d9..8d9fc8b5 100644
--- a/src/GleapAdminHelper.js
+++ b/src/GleapAdminHelper.js
@@ -1,5 +1,5 @@
import ElementPicker from './ElementPicker';
-import { buildStableSelector } from './GleapTourSelector';
+import { buildStableSelector, withShadowHosts } from './GleapTourSelector';
class GleapAdminHelper {
picker = null;
@@ -45,7 +45,7 @@ class GleapAdminHelper {
}
if (anchor) {
const tourId = anchor.getAttribute('data-gleap-tour');
- selector = `[data-gleap-tour="${tourId}"]`;
+ selector = withShadowHosts(anchor, `[data-gleap-tour="${tourId}"]`);
} else {
selector = buildStableSelector(el);
}
diff --git a/src/GleapAdminManager.js b/src/GleapAdminManager.js
index 1feba577..27feb966 100644
--- a/src/GleapAdminManager.js
+++ b/src/GleapAdminManager.js
@@ -156,12 +156,22 @@ export default class GleapAdminManager {
document.querySelectorAll('.gleap-admin-highlight').forEach((el) => {
el.classList.remove('gleap-admin-highlight');
});
+ if (self.shadowHighlight) {
+ self.shadowHighlight.style.removeProperty('box-shadow');
+ self.shadowHighlight = null;
+ }
// Find the element and highlight it.
if (data?.data?.selector) {
const element = querySelectorSafe(data?.data?.selector);
if (element) {
element.classList.add('gleap-admin-highlight');
+ // The class is styled in the document, which does not apply inside a shadow root.
+ const root = element.getRootNode();
+ if (root !== document && root.host) {
+ element.style.setProperty('box-shadow', '0px 0px 0px 4px red');
+ self.shadowHighlight = element;
+ }
}
}
}
diff --git a/src/GleapProductTours.js b/src/GleapProductTours.js
index b545359f..04a99aeb 100644
--- a/src/GleapProductTours.js
+++ b/src/GleapProductTours.js
@@ -235,13 +235,15 @@ export default class GleapProductTours {
function onDocumentClick(evnt) {
try {
var gleapTourPopover = document.querySelector('.gleap-tour-popover');
+ // Inside a shadow root `evnt.target` is the host; the path has the real element.
+ const clickTarget = (typeof evnt?.composedPath === 'function' && evnt.composedPath()[0]) || evnt?.target;
if (gleapTourPopover && !gleapTourPopover.contains(evnt.target)) {
const stepIndex = self.gleapTourObj.getActiveIndex();
const step = steps[stepIndex];
const element = self.gleapTourObj.getActiveElement();
- if (step?.mode === 'CLICK' && evnt?.target !== element) {
- const isInsideElement = element.contains(evnt?.target);
+ if (step?.mode === 'CLICK' && clickTarget !== element) {
+ const isInsideElement = element.contains(clickTarget);
if (!isInsideElement) {
// Ignore clicks outside of the actual element.
return;
@@ -281,7 +283,7 @@ export default class GleapProductTours {
this.storeUncompletedTour();
},
onElementNotFound: (step) => {
- document.removeEventListener('click', onDocumentClick);
+ document.removeEventListener('click', onDocumentClick, true);
this.onComplete(false);
},
@@ -294,7 +296,7 @@ export default class GleapProductTours {
this.onComplete(false);
}
- document.removeEventListener('click', onDocumentClick);
+ document.removeEventListener('click', onDocumentClick, true);
},
onPopoverRender: (popoverElement) => {
// Fix for images and videos.
diff --git a/src/GleapSafeSelector.js b/src/GleapSafeSelector.js
index c0210ab7..c4378df3 100644
--- a/src/GleapSafeSelector.js
+++ b/src/GleapSafeSelector.js
@@ -42,11 +42,53 @@ const runFirstValid = (selector, fn) => {
return null;
};
+// `host >>> inner` continues inside the open shadow root of `host`. Plain CSS
+// cannot cross that boundary, so web components (a Vue or Lit widget mounted in
+// a shadow root) would otherwise be unreachable for tours.
+export const SHADOW_SEPARATOR = '>>>';
+
+const hasShadowPath = (selector) => typeof selector === 'string' && selector.indexOf(SHADOW_SEPARATOR) >= 0;
+
+const queryAllIn = (selector, root) => {
+ const found = runFirstValid(selector, (variant) => root.querySelectorAll(variant));
+ return found ? found.result : [];
+};
+
+const queryShadowPath = (selector, root) => {
+ const parts = selector.split(SHADOW_SEPARATOR);
+ let roots = [root];
+
+ for (let i = 0; i < parts.length - 1; i++) {
+ const nextRoots = [];
+ for (let j = 0; j < roots.length; j++) {
+ const hosts = queryAllIn(parts[i], roots[j]);
+ for (let k = 0; k < hosts.length; k++) {
+ if (hosts[k].shadowRoot) {
+ nextRoots.push(hosts[k].shadowRoot);
+ }
+ }
+ }
+ roots = nextRoots;
+ }
+
+ const matches = [];
+ for (let j = 0; j < roots.length; j++) {
+ const found = queryAllIn(parts[parts.length - 1], roots[j]);
+ for (let k = 0; k < found.length; k++) {
+ matches.push(found[k]);
+ }
+ }
+ return matches;
+};
+
/**
* `document.querySelector` for stored selectors. Never throws: an invalid
* selector resolves to `null`, like one that matches nothing.
*/
export const querySelectorSafe = (selector, root = document) => {
+ if (hasShadowPath(selector)) {
+ return queryShadowPath(selector, root)[0] || null;
+ }
const found = runFirstValid(selector, (variant) => root.querySelector(variant));
return found ? found.result : null;
};
@@ -55,14 +97,28 @@ export const querySelectorSafe = (selector, root = document) => {
* `document.querySelectorAll` for stored selectors. Never throws.
*/
export const querySelectorAllSafe = (selector, root = document) => {
- const found = runFirstValid(selector, (variant) => root.querySelectorAll(variant));
- return found ? found.result : [];
+ if (hasShadowPath(selector)) {
+ return queryShadowPath(selector, root);
+ }
+ return queryAllIn(selector, root);
};
/**
* `element.matches` for stored selectors. Never throws.
*/
export const matchesSelectorSafe = (element, selector) => {
+ if (hasShadowPath(selector)) {
+ const parts = selector.split(SHADOW_SEPARATOR);
+ let current = element;
+ for (let i = parts.length - 1; i >= 0; i--) {
+ if (!current || !matchesSelectorSafe(current, parts[i])) {
+ return false;
+ }
+ const root = typeof current.getRootNode === 'function' ? current.getRootNode() : null;
+ current = root && root.host ? root.host : null;
+ }
+ return true;
+ }
const found = runFirstValid(selector, (variant) => element.matches(variant));
return found ? found.result : false;
};
diff --git a/src/GleapShadowSelector.test.js b/src/GleapShadowSelector.test.js
new file mode 100644
index 00000000..7ee556e5
--- /dev/null
+++ b/src/GleapShadowSelector.test.js
@@ -0,0 +1,85 @@
+/**
+ * @jest-environment jsdom
+ */
+import { querySelectorSafe, querySelectorAllSafe, matchesSelectorSafe } from './GleapSafeSelector';
+import { buildStableSelector, withShadowHosts } from './GleapTourSelector';
+
+// A widget mounted the way Vue's `defineCustomElement` or a manual
+// `attachShadow` mount does it: an anonymous host with the app in its shadow root.
+const mountWidget = () => {
+ document.body.innerHTML = '';
+ const host = document.querySelector('#widget-container > div');
+ const shadow = host.attachShadow({ mode: 'open' });
+ shadow.innerHTML =
+ '';
+ const nestedShadow = shadow.querySelector('.nested-host').attachShadow({ mode: 'open' });
+ nestedShadow.innerHTML = 'Deep';
+ return { host, shadow, nestedShadow };
+};
+
+describe('shadow DOM selectors', () => {
+ it('does not find shadow content with a plain selector', () => {
+ mountWidget();
+ expect(querySelectorSafe('.app')).toBe(null);
+ expect(querySelectorAllSafe('button.save').length).toBe(1);
+ });
+
+ it('resolves `host >>> inner` through an open shadow root', () => {
+ const { shadow } = mountWidget();
+ const save = shadow.querySelector('.save');
+ expect(querySelectorSafe('#widget-container > div >>> button.save')).toBe(save);
+ expect(querySelectorAllSafe('#widget-container > div >>> button')).toHaveLength(2);
+ expect(querySelectorAllSafe('#widget-container>div>>>button.save')[0]).toBe(save);
+ });
+
+ it('resolves nested shadow roots', () => {
+ const { nestedShadow } = mountWidget();
+ expect(querySelectorSafe('#widget-container > div >>> .nested-host >>> .deep')).toBe(
+ nestedShadow.querySelector('.deep')
+ );
+ });
+
+ it('returns nothing for a missing host, a host without shadow root or a broken part', () => {
+ mountWidget();
+ expect(querySelectorSafe('#nope >>> .save')).toBe(null);
+ expect(querySelectorSafe('#widget-container >>> .save')).toBe(null);
+ expect(querySelectorAllSafe('#widget-container > div >>> ')).toEqual([]);
+ expect(querySelectorAllSafe('>>> .save')).toEqual([]);
+ });
+
+ it('matches an element against a shadow path', () => {
+ const { shadow } = mountWidget();
+ const save = shadow.querySelector('.save');
+ expect(matchesSelectorSafe(save, '#widget-container > div >>> .save')).toBe(true);
+ expect(matchesSelectorSafe(save, '#other >>> .save')).toBe(false);
+ expect(matchesSelectorSafe(document.querySelector('body > .save'), '#widget-container > div >>> .save')).toBe(false);
+ });
+
+ it('builds a selector for a picked shadow element that resolves back to it', () => {
+ const { shadow, nestedShadow } = mountWidget();
+ [shadow.querySelector('.save'), shadow.querySelector('.app'), nestedShadow.querySelector('.deep')].forEach(
+ (element) => {
+ const selector = buildStableSelector(element);
+ expect(selector).toContain('>>>');
+ expect(querySelectorAllSafe(selector)).toEqual([element]);
+ }
+ );
+ });
+
+ it('leaves selectors for regular elements untouched', () => {
+ mountWidget();
+ const outside = document.querySelector('body > .save');
+ const selector = buildStableSelector(outside);
+ expect(selector).not.toContain('>>>');
+ expect(document.querySelector(selector)).toBe(outside);
+ });
+
+ it('prefixes a data-gleap-tour anchor with its shadow hosts', () => {
+ const { shadow } = mountWidget();
+ const undo = shadow.querySelector('[data-gleap-tour="undo"]');
+ const selector = withShadowHosts(undo, '[data-gleap-tour="undo"]');
+ expect(selector).toBe('#widget-container > div >>> [data-gleap-tour="undo"]');
+ expect(querySelectorSafe(selector)).toBe(undo);
+ });
+});
diff --git a/src/GleapTourSelector.js b/src/GleapTourSelector.js
index 29524e99..9eb3222e 100644
--- a/src/GleapTourSelector.js
+++ b/src/GleapTourSelector.js
@@ -1,4 +1,5 @@
import unique from './unique-selector/src/unique-selector';
+import { SHADOW_SEPARATOR } from './GleapSafeSelector';
/**
* Ids and class names that frameworks generate at runtime or at build time.
@@ -75,13 +76,20 @@ export const UNSTABLE_SELECTOR_PATTERN = new RegExp(
/**
* Checks that a selector points at exactly the element it was built for.
*/
+// The tree a selector for this element is resolved in: its shadow root when it
+// lives in one, the document otherwise.
+const rootOf = (element) => {
+ const root = element && typeof element.getRootNode === 'function' ? element.getRootNode() : null;
+ return root && typeof root.querySelectorAll === 'function' ? root : document;
+};
+
const resolvesToElement = (selector, element) => {
if (!selector || selector === '*') {
return false;
}
try {
- const matches = document.querySelectorAll(selector);
+ const matches = rootOf(element).querySelectorAll(selector);
return matches.length === 1 && matches[0] === element;
} catch (e) {
return false;
@@ -105,11 +113,11 @@ const escapeForRegExp = (value) => value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
* number is being handed out at runtime and will differ on the next mount.
* This is what catches generators the pattern list above has never heard of.
*
- * @return { Array } the generated ids currently in the document
+ * @return { Array } the generated ids currently in the document (or shadow root)
*/
-const collectGeneratedIds = () => {
+const collectGeneratedIds = (root = document) => {
const idsByShape = {};
- const elements = document.querySelectorAll('[id]');
+ const elements = root.querySelectorAll('[id]');
for (let i = 0; i < elements.length; i++) {
const id = elements[i].getAttribute('id');
@@ -164,12 +172,12 @@ const semanticCandidates = (element) => {
* @param { Function } uniqueFn selector generator, injectable for tests
* @return { String } selector
*/
-export const buildStableSelector = (element, uniqueFn = unique) => {
+const buildSelectorInRoot = (element, uniqueFn) => {
const fallback = uniqueFn(element);
const candidates = [];
try {
- const generatedIds = collectGeneratedIds();
+ const generatedIds = collectGeneratedIds(rootOf(element));
const id = typeof element.getAttribute === 'function' ? element.getAttribute('id') : null;
if (id && generatedIds.indexOf(id) < 0 && !UNSTABLE_SELECTOR_PATTERN.test(idFragment(id))) {
@@ -198,3 +206,23 @@ export const buildStableSelector = (element, uniqueFn = unique) => {
return fallback;
};
+
+/**
+ * Prefixes a selector with the shadow hosts above the element, so it can be
+ * resolved from the document: `#widget > div >>> button.save`.
+ *
+ * @param { Element } element the element the selector was built for
+ * @param { String } selector selector valid inside the element's own tree
+ * @param { Function } uniqueFn selector generator, injectable for tests
+ * @return { String } selector
+ */
+export const withShadowHosts = (element, selector, uniqueFn = unique) => {
+ const root = rootOf(element);
+ if (root === document || !root.host) {
+ return selector;
+ }
+ return `${buildStableSelector(root.host, uniqueFn)} ${SHADOW_SEPARATOR} ${selector}`;
+};
+
+export const buildStableSelector = (element, uniqueFn = unique) =>
+ withShadowHosts(element, buildSelectorInRoot(element, uniqueFn), uniqueFn);
diff --git a/src/GleapTours.js b/src/GleapTours.js
index 6918d8aa..3a1161a0 100644
--- a/src/GleapTours.js
+++ b/src/GleapTours.js
@@ -87,6 +87,45 @@ const GleapTours = (function () {
}
return null;
}
+ // The interaction lockout is CSS in the document stylesheet. It cannot reach
+ // into a shadow root: the host gets `pointer-events: none` and everything in
+ // its tree inherits that, the active element included. So for an element in
+ // a shadow root the same rules are applied inline.
+ let shadowInteraction = null;
+ function isInShadowRoot(element) {
+ const root = element && typeof element.getRootNode === 'function' ? element.getRootNode() : null;
+ return !!(root && root !== document && root.host);
+ }
+ function restoreShadowInteraction() {
+ if (!shadowInteraction) {
+ return;
+ }
+ const { element, value, priority } = shadowInteraction;
+ shadowInteraction = null;
+ if (value) {
+ element.style.setProperty('pointer-events', value, priority);
+ } else {
+ element.style.removeProperty('pointer-events');
+ }
+ }
+ function applyShadowInteraction(element, disabled) {
+ restoreShadowInteraction();
+ if (!isInShadowRoot(element) || !element.style) {
+ return;
+ }
+ shadowInteraction = {
+ element,
+ value: element.style.getPropertyValue('pointer-events'),
+ priority: element.style.getPropertyPriority('pointer-events'),
+ };
+ element.style.setProperty('pointer-events', disabled ? 'none' : 'auto', 'important');
+ }
+ function clearActiveElement(element) {
+ element.classList.remove('gleap-tour-active-element', 'gleap-tour-no-interaction');
+ element.removeAttribute('aria-haspopup');
+ element.removeAttribute('aria-expanded');
+ element.removeAttribute('aria-controls');
+ }
let currentState = {};
function setState(key, value) {
currentState[key] = value;
@@ -284,7 +323,7 @@ const GleapTours = (function () {
}
// Re-query the element if the cached reference is no longer in the DOM.
- if (!document.body.contains(activeHighlight) && activeStep.element && typeof activeStep.element === 'string') {
+ if (!activeHighlight.isConnected && activeStep.element && typeof activeStep.element === 'string') {
try {
var freshEl = findRenderedElement(activeStep.element);
if (freshEl) {
@@ -292,6 +331,10 @@ const GleapTours = (function () {
setState('__activeElement', freshEl);
setState('activeElement', freshEl);
freshEl.classList.add('gleap-tour-active-element');
+ applyShadowInteraction(
+ freshEl,
+ activeStep.disableActiveInteraction ?? getConfig('disableActiveInteraction') ?? false
+ );
}
} catch (e) {}
}
@@ -378,6 +421,7 @@ const GleapTours = (function () {
toElement.classList.add('gleap-tour-no-interaction');
}
toElement.classList.add('gleap-tour-active-element');
+ applyShadowInteraction(toElement, disableActiveInteraction);
toElement.setAttribute('aria-haspopup', 'dialog');
toElement.setAttribute('aria-expanded', 'true');
toElement.setAttribute('aria-controls', 'gleap-tour-popover-content');
@@ -385,12 +429,12 @@ const GleapTours = (function () {
function destroyHighlight() {
var _a;
(_a = document.getElementById('gleap-tour-dummy-element')) == null ? void 0 : _a.remove();
- document.querySelectorAll('.gleap-tour-active-element').forEach((element) => {
- element.classList.remove('gleap-tour-active-element', 'gleap-tour-no-interaction');
- element.removeAttribute('aria-haspopup');
- element.removeAttribute('aria-expanded');
- element.removeAttribute('aria-controls');
- });
+ document.querySelectorAll('.gleap-tour-active-element').forEach(clearActiveElement);
+ // Not reachable by the query above.
+ if (shadowInteraction) {
+ clearActiveElement(shadowInteraction.element);
+ restoreShadowInteraction();
+ }
}
function requireRefresh() {
const resizeTimeout = getState('__resizeTimeout');
diff --git a/src/unique-selector/src/isUnique.js b/src/unique-selector/src/isUnique.js
index 03ac689b..310d6c82 100644
--- a/src/unique-selector/src/isUnique.js
+++ b/src/unique-selector/src/isUnique.js
@@ -6,6 +6,8 @@
*/
export function isUnique(el, selector) {
if (!Boolean(selector)) return false;
- const elems = el.ownerDocument.querySelectorAll(selector);
+ // The element's own tree: its shadow root when it lives in one.
+ const root = typeof el.getRootNode === 'function' ? el.getRootNode() : el.ownerDocument;
+ const elems = (root && root.querySelectorAll ? root : el.ownerDocument).querySelectorAll(selector);
return elems.length === 1 && elems[0] === el;
}