Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
73 changes: 73 additions & 0 deletions demo/shadow-dom.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Gleap tours inside a shadow root</title>
<style>
body { font-family: sans-serif; margin: 0; }
#widget-container { height: 100vh; }
</style>
</head>
<body>
<!-- Mirrors a widget mounted with attachShadow (Vue defineCustomElement, Lit, ...). -->
<div id="widget-container"></div>
<script src="build/cjs/index.js"></script>
<script>
const host = document.createElement('div');
document.getElementById('widget-container').appendChild(host);
const shadow = host.attachShadow({ mode: 'open' });
shadow.innerHTML = `
<style>
.app { display: grid; grid-template-columns: 180px 1fr; height: 100vh; }
.catalog { display: flex; flex-direction: column; gap: 12px; padding: 16px; background: #f3f4f6; }
.viewport { position: relative; background: #dfe6ee; }
.toolbar { position: absolute; right: 24px; bottom: 24px; display: flex; gap: 8px; }
button { padding: 12px; cursor: pointer; }
#log { position: absolute; left: 24px; top: 24px; font-family: monospace; }
</style>
<div class="app">
<div class="catalog">
<button class="box" data-testid="catalog-conveyor">Conveyor</button>
<button class="box" data-testid="catalog-profile">Profile</button>
</div>
<div class="viewport">
<div id="log">clicks: 0</div>
<div class="toolbar">
<button data-gleap-tour="fence">Fence</button>
<button class="measure">Measure</button>
</div>
</div>
</div>`;

window.clicks = [];
shadow.addEventListener('click', (e) => {
window.clicks.push(e.target.textContent);
shadow.getElementById('log').textContent = 'clicks: ' + window.clicks.join(', ');
});

// No project is initialized on this page; this only injects the SDK stylesheet.
Gleap.setStyles('#485bff', '#485bff', '#485bff');

const step = (selector, message, mode) => ({ selector, message: `<p>${message}</p>`, type: 'pointer', mode });
window.startDemoTour = () =>
Gleap.startProductTourWithConfig(
'shadow-demo',
{
type: 'tour',
tourType: 'tour',
nextText: 'Next',
doneText: 'Done',
prevText: 'Previous',
allowClose: true,
backButton: true,
steps: [
step('#widget-container > div >>> [data-testid="catalog-conveyor"]', 'Catalog entry (Next button)', 'BUTTON'),
step('#widget-container > div >>> [data-gleap-tour="fence"]', 'Click the fence tool to continue', 'CLICK'),
step('#widget-container > div >>> button.measure', 'Last step', 'BUTTON'),
],
},
true
);
</script>
</body>
</html>
25 changes: 23 additions & 2 deletions src/ElementPicker.js
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*/
Expand Down Expand Up @@ -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;
}
Expand Down Expand Up @@ -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();

Expand Down
4 changes: 2 additions & 2 deletions src/GleapAdminHelper.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import ElementPicker from './ElementPicker';
import { buildStableSelector } from './GleapTourSelector';
import { buildStableSelector, withShadowHosts } from './GleapTourSelector';

class GleapAdminHelper {
picker = null;
Expand Down Expand Up @@ -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);
}
Expand Down
10 changes: 10 additions & 0 deletions src/GleapAdminManager.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
}
}
}
Expand Down
10 changes: 6 additions & 4 deletions src/GleapProductTours.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -281,7 +283,7 @@ export default class GleapProductTours {
this.storeUncompletedTour();
},
onElementNotFound: (step) => {
document.removeEventListener('click', onDocumentClick);
document.removeEventListener('click', onDocumentClick, true);

this.onComplete(false);
},
Expand All @@ -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.
Expand Down
60 changes: 58 additions & 2 deletions src/GleapSafeSelector.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
};
Expand All @@ -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;
};
85 changes: 85 additions & 0 deletions src/GleapShadowSelector.test.js
Original file line number Diff line number Diff line change
@@ -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 = '<div id="widget-container"><div></div></div><button class="save">Outside</button>';
const host = document.querySelector('#widget-container > div');
const shadow = host.attachShadow({ mode: 'open' });
shadow.innerHTML =
'<div class="app"><button class="save">Save</button><button data-gleap-tour="undo">Undo</button>' +
'<div class="nested-host"></div></div>';
const nestedShadow = shadow.querySelector('.nested-host').attachShadow({ mode: 'open' });
nestedShadow.innerHTML = '<span class="deep">Deep</span>';
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);
});
});
Loading
Loading