-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhoff-tour.js
More file actions
459 lines (415 loc) · 15.7 KB
/
Copy pathhoff-tour.js
File metadata and controls
459 lines (415 loc) · 15.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
// Hoff — Tour Logic (driver.js integration with glass theming)
// Exposes global HoffTour object
(function () {
"use strict";
const TOUR_STORAGE_KEY = "hoff_tour_state";
let activeDriverObj = null;
let isNavigating = false;
let injectedStyle = null;
let tourGeneration = 0; // Incremented on each start(), used to cancel stale async handlers
/** Detect if page background is light or dark */
function detectTheme() {
const bg = window.getComputedStyle(document.body).backgroundColor;
const match = bg.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*([\d.]+))?\)/);
if (!match) return "light"; // no background set → browser default is white
const [, r, g, b] = match.map(Number);
const alpha = match[4] !== undefined ? parseFloat(match[4]) : 1;
if (alpha < 0.1) return "light"; // transparent → browser default white
const luminance = (0.299 * r + 0.587 * g + 0.114 * b) / 255;
return luminance > 0.5 ? "light" : "dark";
}
/** Generate liquid glass CSS for tour popovers */
function generateGlassCSS() {
const isDark = detectTheme() === "dark";
const textColor = isDark ? "#fff" : "#111";
const glassBg = isDark ? "rgba(255, 255, 255, 0.12)" : "rgba(0, 0, 0, 0.06)";
const glassBorder = isDark ? "rgba(255, 255, 255, 0.18)" : "rgba(0, 0, 0, 0.18)";
const arrowBg = isDark ? "rgba(255, 255, 255, 0.15)" : "rgba(0, 0, 0, 0.15)";
const btnBg = isDark ? "rgba(255, 255, 255, 0.15)" : "rgba(0, 0, 0, 0.1)";
const btnHoverBg = isDark ? "rgba(255, 255, 255, 0.25)" : "rgba(0, 0, 0, 0.18)";
const shadow = isDark ? "0 8px 32px rgba(0, 0, 0, 0.25)" : "0 8px 32px rgba(0, 0, 0, 0.12), 0 0 0 0.5px rgba(0, 0, 0, 0.08)";
return `
.driver-popover.hoff-theme {
background-color: ${glassBg} !important;
color: ${textColor};
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
border-radius: 18px;
backdrop-filter: blur(16px) !important;
-webkit-backdrop-filter: blur(16px) !important;
border: 1px solid ${glassBorder} !important;
box-shadow: ${shadow} !important;
animation: hoffFadeScale 0.25s ease-out;
}
.driver-popover.hoff-theme .driver-popover-title {
color: ${textColor};
font-size: 17px;
font-weight: 600;
}
.driver-popover.hoff-theme .driver-popover-description {
color: ${textColor};
opacity: 0.85;
}
.driver-popover.hoff-theme .driver-popover-progress-text {
color: ${textColor};
opacity: 0.6;
}
.driver-popover.hoff-theme .driver-popover-close-btn {
color: ${textColor};
opacity: 0.5;
}
.driver-popover.hoff-theme .driver-popover-close-btn:hover {
color: ${textColor};
opacity: 1;
}
.driver-popover.hoff-theme .driver-popover-navigation-btns {
gap: 6px;
}
.driver-popover.hoff-theme button:not(.driver-popover-close-btn) {
background-color: ${btnBg};
color: ${textColor};
border: 1px solid ${glassBorder};
border-radius: 14px;
padding: 6px 14px;
font-size: 13px;
font-weight: 500;
text-shadow: none;
cursor: pointer;
backdrop-filter: blur(8px);
-webkit-backdrop-filter: blur(8px);
transition: background 0.2s ease, transform 0.15s ease;
}
.driver-popover.hoff-theme button:not(.driver-popover-close-btn):hover {
background-color: ${btnHoverBg};
transform: scale(1.03);
}
.driver-popover.hoff-theme .driver-popover-arrow-side-top.driver-popover-arrow {
border-top-color: ${arrowBg};
}
.driver-popover.hoff-theme .driver-popover-arrow-side-bottom.driver-popover-arrow {
border-bottom-color: ${arrowBg};
}
.driver-popover.hoff-theme .driver-popover-arrow-side-left.driver-popover-arrow {
border-left-color: ${arrowBg};
}
.driver-popover.hoff-theme .driver-popover-arrow-side-right.driver-popover-arrow {
border-right-color: ${arrowBg};
}
`;
}
/** Inject a <style> tag into the page <head>. */
function injectStyles(css) {
if (injectedStyle) injectedStyle.remove();
const style = document.createElement("style");
style.textContent = css;
document.head.appendChild(style);
injectedStyle = style;
}
/** Save tour state to survive navigations. */
function saveTourState(payload, stepIndex, lastUrl) {
return chrome.storage.local.set({
[TOUR_STORAGE_KEY]: { payload, stepIndex, lastUrl: lastUrl || window.location.href },
});
}
/** Clear saved tour state. */
function clearTourState() {
chrome.storage.local.remove(TOUR_STORAGE_KEY);
}
/** Collapse all whitespace runs into a single space for fuzzy text matching. */
function normalizeWS(str) {
return str.replace(/\s+/g, " ").trim();
}
/**
* Find a DOM element for a step.
* Uses CSS selector (step.element) when no text field is set.
* Falls back to tag + textContent matching when step.text is present.
*/
function findElement(step) {
if (step.text) {
const needle = normalizeWS(step.text);
return [...document.querySelectorAll(step.element)].find(
(el) => normalizeWS(el.textContent).includes(needle)
) || null;
}
return document.querySelector(step.element);
}
/** Check if element is inside an ephemeral container (dropdown, popover, menu) */
function isInsideEphemeral(el) {
let node = el.parentElement;
while (node && node !== document.body) {
const role = node.getAttribute("role");
if (role === "listbox" || role === "menu" || role === "dialog" ||
node.hasAttribute("data-radix-popper-content-wrapper") ||
node.getAttribute("data-state") === "open") {
return true;
}
node = node.parentElement;
}
return false;
}
/** Reset an element corrupted by driver.js by detaching/reattaching it.
* This forces React to reconcile and reset Radix's internal state.
* For ephemeral elements (inside dropdowns), use pointer events instead.
* For simple elements, just click directly. */
function resetAndClick(el) {
// Elements inside dropdowns/popovers: can't detach, use pointer events
if (isInsideEphemeral(el)) {
el.dispatchEvent(new PointerEvent("pointerdown", { bubbles: true, cancelable: true }));
el.dispatchEvent(new PointerEvent("pointerup", { bubbles: true, cancelable: true }));
el.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true }));
return Promise.resolve();
}
// Elements with Radix state (triggers): detach/reattach to reset React state
if (el.hasAttribute("aria-haspopup") || el.hasAttribute("data-state")) {
return new Promise((resolve) => {
const parent = el.parentElement;
const next = el.nextSibling;
parent.removeChild(el);
requestAnimationFrame(() => {
parent.insertBefore(el, next);
setTimeout(() => {
el.click();
resolve();
}, 100);
});
});
}
// Simple elements: plain click
el.click();
return Promise.resolve();
}
/** Wait for an element to appear in the DOM. */
function waitForElement(step, timeout = 5000) {
return new Promise((resolve) => {
const el = findElement(step);
if (el) return resolve(el);
const observer = new MutationObserver(() => {
const el = findElement(step);
if (el) {
observer.disconnect();
resolve(el);
}
});
observer.observe(document.body, { childList: true, subtree: true });
setTimeout(() => {
observer.disconnect();
resolve(findElement(step));
}, timeout);
});
}
/** Map payload steps to driver.js step format. */
function mapSteps(payload, startIndex) {
const rawSteps = payload.workflow.steps;
return rawSteps.map((s, i) => {
const step = {
// Text-based steps: use a function so driver.js finds the right element
element: s.text
? () => findElement(s)
: s.element,
popover: {
title: s.title,
description: s.description,
side: s.side || "bottom",
align: "start",
},
};
// Disable "Previous" on the step we resumed at after a navigation
if (i === startIndex && startIndex > 0) {
step.popover.disableButtons = ["previous"];
}
// preClick: open dropdowns etc before highlighting
if (s.preClick) {
step.onHighlightStarted = () => {
document.body.style.pointerEvents = "none";
const target = document.querySelector(s.preClick);
if (target) {
target.style.pointerEvents = "auto";
target.click();
}
};
}
// When highlighted, attach click-to-advance on the element
step.onHighlighted = (el) => {
// Re-enable pointer events if preClick was used
if (s.preClick) {
setTimeout(() => {
document.body.style.pointerEvents = "";
const target = document.querySelector(s.preClick);
if (target) target.style.pointerEvents = "";
}, 300);
}
// Attach click-to-advance (skip inputs)
const highlightedEl = el || findElement(s);
const isInput =
highlightedEl &&
(highlightedEl.tagName === "INPUT" ||
highlightedEl.tagName === "TEXTAREA" ||
highlightedEl.isContentEditable ||
highlightedEl.getAttribute("role") === "textbox");
if (highlightedEl && !isInput) {
const gen = tourGeneration;
const handler = async (e) => {
highlightedEl.removeEventListener("click", handler, true);
if (gen !== tourGeneration) return; // stale handler
const isLastStep = i === rawSteps.length - 1;
if (s.navigates) {
e.preventDefault();
e.stopPropagation();
isNavigating = true;
if (!isLastStep) {
await saveTourState(payload, i + 1, null);
} else {
clearTourState();
}
if (activeDriverObj) activeDriverObj.destroy();
if (highlightedEl.tagName === "A" && highlightedEl.href) {
window.location.href = highlightedEl.href;
} else {
highlightedEl.click();
}
} else {
// Let the user's click go through naturally (no preventDefault)
isNavigating = true;
if (activeDriverObj) activeDriverObj.destroy();
if (isLastStep) {
clearTourState();
if (window.HoffTour.onComplete) window.HoffTour.onComplete();
} else {
const nextStep = rawSteps[i + 1];
if (nextStep) {
const nextEl = await waitForElement(nextStep, 10000);
if (gen !== tourGeneration) return; // stale
if (nextEl) {
await new Promise((r) => setTimeout(r, 400));
isNavigating = false;
window.HoffTour.start(payload, i + 1);
}
}
}
}
};
highlightedEl.addEventListener("click", handler, true);
}
};
// Handle the "Next" button
step.popover.onNextClick = async () => {
const gen = tourGeneration;
const isLastStep = i === rawSteps.length - 1;
const target = findElement(s);
if (s.navigates) {
isNavigating = true;
if (!isLastStep) {
await saveTourState(payload, i + 1, null);
} else {
clearTourState();
}
if (activeDriverObj) activeDriverObj.destroy();
if (target) {
if (target.tagName === "A" && target.href) {
window.location.href = target.href;
} else {
target.click();
}
}
} else {
isNavigating = true;
if (activeDriverObj) activeDriverObj.destroy();
// Re-find element after destroy (driver.js overlay is gone now)
const freshTarget = findElement(s);
const isInput =
freshTarget &&
(freshTarget.tagName === "INPUT" ||
freshTarget.tagName === "TEXTAREA" ||
freshTarget.isContentEditable ||
freshTarget.getAttribute("role") === "textbox");
if (isLastStep) {
clearTourState();
if (freshTarget && !isInput) await resetAndClick(freshTarget);
if (window.HoffTour.onComplete) window.HoffTour.onComplete();
} else {
if (freshTarget && !isInput) {
await resetAndClick(freshTarget);
}
const nextStep = rawSteps[i + 1];
if (nextStep) {
const nextEl = await waitForElement(nextStep, 10000);
if (gen !== tourGeneration) return; // stale
if (nextEl) {
await new Promise((r) => setTimeout(r, 400));
isNavigating = false;
window.HoffTour.start(payload, i + 1);
}
}
}
}
};
return step;
});
}
// --- Public API ---
window.HoffTour = {
onCollapse: null, // (payload, stepIndex, lastUrl) => {}
onComplete: null, // () => {}
/** Start or resume a branded tour. */
start(payload, startIndex = 0) {
tourGeneration++; // Cancel any stale async handlers from previous start()
injectStyles(generateGlassCSS());
const driverConstructor = window.driver.js.driver;
const steps = mapSteps(payload, startIndex);
const isDark = detectTheme() === "dark";
const driverObj = driverConstructor({
popoverClass: "hoff-theme",
animate: true,
showProgress: true,
allowClose: true,
overlayClickBehavior: "close",
allowKeyboardControl: true,
overlayColor: isDark ? "#000" : "#000",
overlayOpacity: isDark ? 0.5 : 0.3,
stagePadding: 8,
stageRadius: 6,
steps: steps,
onDestroyStarted: () => {
if (isNavigating) {
isNavigating = false;
driverObj.destroy();
return;
}
// Overlay click or Escape — collapse
const currentIndex = driverObj.getActiveIndex();
const stepIndex = currentIndex != null ? currentIndex : startIndex;
const currentUrl = window.location.href;
saveTourState(payload, stepIndex, currentUrl);
driverObj.destroy();
activeDriverObj = null;
if (window.HoffTour.onCollapse) {
window.HoffTour.onCollapse(payload, stepIndex, currentUrl);
}
},
onDestroyed: () => {
activeDriverObj = null;
},
});
activeDriverObj = driverObj;
driverObj.drive(startIndex);
// Fix Radix aria-hidden conflict: when driver.js takes focus,
// Radix sets aria-hidden on dialogs. Remove it so elements stay accessible.
requestAnimationFrame(() => {
document.querySelectorAll('[role="dialog"][aria-hidden="true"]').forEach((dialog) => {
dialog.removeAttribute("aria-hidden");
dialog.removeAttribute("data-aria-hidden");
});
});
},
/** Check storage for an in-progress tour. Returns state or null. */
async getStoredState() {
return new Promise((resolve) => {
chrome.storage.local.get(TOUR_STORAGE_KEY, (result) => {
resolve(result[TOUR_STORAGE_KEY] || null);
});
});
},
clearState: clearTourState,
findElement: findElement,
waitForElement: waitForElement,
};
})();