@panyam/tsappkit 0.7.6 → 0.7.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +88 -61
- package/dist/index.d.mts +170 -1
- package/dist/index.d.ts +170 -1
- package/dist/index.js +375 -2
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +375 -3
- package/dist/index.mjs.map +1 -1
- package/package.json +2 -2
- package/src/index.ts +15 -0
- package/src/tour/Tour.ts +316 -0
- package/src/tour/geometry.ts +113 -0
- package/src/tour/overlay.ts +178 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@panyam/tsappkit",
|
|
3
|
-
"version": "0.7.
|
|
3
|
+
"version": "0.7.7",
|
|
4
4
|
"description": "TypeScript application toolkit with component lifecycle management, event system, UI utilities, and documentation site components",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"module": "dist/index.mjs",
|
|
@@ -38,7 +38,7 @@
|
|
|
38
38
|
"clean": "rm -rf dist",
|
|
39
39
|
"prepublishOnly": "npm run build",
|
|
40
40
|
"typecheck": "tsc --noEmit",
|
|
41
|
-
"test": "vitest run",
|
|
41
|
+
"test": "tsc --noEmit && vitest run",
|
|
42
42
|
"test:watch": "vitest"
|
|
43
43
|
},
|
|
44
44
|
"keywords": [
|
package/src/index.ts
CHANGED
|
@@ -30,6 +30,21 @@ export { MobileBottomDrawer } from './MobileBottomDrawer';
|
|
|
30
30
|
// Presenter ports (one presenter driving several views)
|
|
31
31
|
export { Port } from './Port';
|
|
32
32
|
|
|
33
|
+
// Guided tours (steps that advance on app events, over a dimmed page with holes)
|
|
34
|
+
export { Tour } from './tour/Tour';
|
|
35
|
+
export type {
|
|
36
|
+
AppTrigger,
|
|
37
|
+
DomTrigger,
|
|
38
|
+
TourEndReason,
|
|
39
|
+
TourEventSource,
|
|
40
|
+
TourOptions,
|
|
41
|
+
TourStep,
|
|
42
|
+
TourTarget,
|
|
43
|
+
TourTrigger,
|
|
44
|
+
} from './tour/Tour';
|
|
45
|
+
export type { TourLabels } from './tour/overlay';
|
|
46
|
+
export type { Rect as TourRect } from './tour/geometry';
|
|
47
|
+
|
|
33
48
|
// Island pages (islands mounted from a server-written page spec)
|
|
34
49
|
export { IslandPage } from './page/IslandPage';
|
|
35
50
|
export { readSpec, SPEC_ELEMENT_ID } from './page/spec';
|
package/src/tour/Tour.ts
ADDED
|
@@ -0,0 +1,316 @@
|
|
|
1
|
+
import { pad, type Rect } from "./geometry";
|
|
2
|
+
import { DEFAULT_LABELS, TourOverlay, type TourLabels } from "./overlay";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* What a step lets the reader reach: one element, several (a NodeList or an array), a rectangle in
|
|
6
|
+
* viewport coordinates, or a mix. Each becomes a hole in the overlay. Nothing (null, or an empty
|
|
7
|
+
* list) leaves the whole page dimmed, which is how a target that hasn't rendered yet looks until
|
|
8
|
+
* it does: the tour re-reads `target` every frame.
|
|
9
|
+
*/
|
|
10
|
+
export type TourTarget =
|
|
11
|
+
| Element
|
|
12
|
+
| DOMRectReadOnly
|
|
13
|
+
| Rect
|
|
14
|
+
| Iterable<Element | DOMRectReadOnly | Rect>
|
|
15
|
+
| null
|
|
16
|
+
| undefined;
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* An app event, by its name in the app's event map E, with an optional test of its payload. `where`
|
|
20
|
+
* is typed from the event named, so a payload field the event doesn't carry is a type error.
|
|
21
|
+
*/
|
|
22
|
+
export type AppTrigger<E> = {
|
|
23
|
+
[K in keyof E & string]: { event: K; where?: (data: E[K]) => boolean };
|
|
24
|
+
}[keyof E & string];
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* A DOM event on the step's own target elements, for steps that teach the UI rather than the app
|
|
28
|
+
* (hover for a tooltip, drag a splitter). It matches when an event of this type passes through a
|
|
29
|
+
* target and infers nothing more. It sees nothing on a rectangle target, since a rectangle has no
|
|
30
|
+
* element to pass through.
|
|
31
|
+
*/
|
|
32
|
+
export interface DomTrigger {
|
|
33
|
+
dom: keyof HTMLElementEventMap;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** Something a step waits for: an app event (`event`) or a DOM event on its target (`dom`). */
|
|
37
|
+
export type TourTrigger<E> = AppTrigger<E> | DomTrigger;
|
|
38
|
+
|
|
39
|
+
/** One step of a tour, written as data. */
|
|
40
|
+
export interface TourStep<E> {
|
|
41
|
+
/** Names the step in callbacks and in the overlay's `data-tour-step`. */
|
|
42
|
+
id: string;
|
|
43
|
+
/** Shown above the text, when given. */
|
|
44
|
+
title?: string;
|
|
45
|
+
/** What the reader should do, or what they're looking at. Set as text, never parsed as HTML. */
|
|
46
|
+
text: string;
|
|
47
|
+
/** The regions the reader can reach during the step. Called every frame while the step is live. */
|
|
48
|
+
target?: () => TourTarget;
|
|
49
|
+
/**
|
|
50
|
+
* What finishes the step. Without one the step is something to look at, and the panel shows Next
|
|
51
|
+
* (Done on the last step).
|
|
52
|
+
*/
|
|
53
|
+
advanceOn?: TourTrigger<E>;
|
|
54
|
+
/**
|
|
55
|
+
* Events that mean the reader went somewhere else. One that matches `offPath` and not
|
|
56
|
+
* `advanceOn` applies `onOffPath`; naming the same event as `advanceOn` without its `where`
|
|
57
|
+
* catches every other payload of it.
|
|
58
|
+
*/
|
|
59
|
+
offPath?: TourTrigger<E> | readonly TourTrigger<E>[];
|
|
60
|
+
/**
|
|
61
|
+
* `"end"` (the default) removes the overlay and leaves the app doing what it does with that
|
|
62
|
+
* input, so the reader has simply left the tour. `"stay"` keeps waiting for `advanceOn`.
|
|
63
|
+
*/
|
|
64
|
+
onOffPath?: "end" | "stay";
|
|
65
|
+
/**
|
|
66
|
+
* Does the step's action for the reader, behind a "Show me" button. It should act through the app
|
|
67
|
+
* as a reader would, so the step still advances on the app's event rather than on the button.
|
|
68
|
+
*/
|
|
69
|
+
doItForMe?: () => void;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** Why a tour ended: its last step finished, the reader closed it, or the reader went off path. */
|
|
73
|
+
export type TourEndReason = "done" | "cancelled" | "offPath";
|
|
74
|
+
|
|
75
|
+
/** Hooks and settings for a tour. */
|
|
76
|
+
export interface TourOptions<E> {
|
|
77
|
+
/** Runs as each step goes live, the first one included. */
|
|
78
|
+
onStep?: (step: TourStep<E>, index: number) => void;
|
|
79
|
+
/** Runs once when the tour ends, with the step it was on. */
|
|
80
|
+
onEnd?: (reason: TourEndReason, step: TourStep<E>, index: number) => void;
|
|
81
|
+
/** How far each hole extends past its target, in px. Defaults to 4. */
|
|
82
|
+
padding?: number;
|
|
83
|
+
/** The panel's button labels. */
|
|
84
|
+
labels?: Partial<TourLabels>;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* The part of an event bus a tour needs: tsappkit's EventBus has it, and so can anything else.
|
|
89
|
+
*/
|
|
90
|
+
export interface TourEventSource {
|
|
91
|
+
on(type: string, handler: (data?: any) => void): void;
|
|
92
|
+
off(type: string, handler: (data?: any) => void): void;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
type Seen = { kind: "app"; type: string; data: unknown } | { kind: "dom"; type: string };
|
|
96
|
+
|
|
97
|
+
const raf: (cb: () => void) => number =
|
|
98
|
+
typeof requestAnimationFrame === "function" ? (cb) => requestAnimationFrame(cb) : (cb) => setTimeout(cb, 16) as unknown as number;
|
|
99
|
+
const caf: (id: number) => void =
|
|
100
|
+
typeof cancelAnimationFrame === "function" ? (id) => cancelAnimationFrame(id) : (id) => clearTimeout(id);
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* A guided walk over an app in which the reader does each step. The page is dimmed, the step's
|
|
104
|
+
* targets stay reachable through holes in the dimming, and the step advances when the app reports
|
|
105
|
+
* that the reader did the thing: an app event matched by `advanceOn`, not a click inferred from a
|
|
106
|
+
* selector. E is the app's event map (event name to payload), so a step naming an event the app
|
|
107
|
+
* doesn't have, or a payload field the event doesn't carry, fails to compile:
|
|
108
|
+
*
|
|
109
|
+
* interface ViewerEvents { checksRun: void; cellSelected: { table: string; row: number } }
|
|
110
|
+
* const tour = new Tour<ViewerEvents>([
|
|
111
|
+
* { id: "run", text: "Run the checks.", target: () => runButton, advanceOn: { event: "checksRun" } },
|
|
112
|
+
* { id: "cell", text: "Click a part in the first row.", target: () => rows,
|
|
113
|
+
* advanceOn: { event: "cellSelected", where: (d) => d.row === 0 },
|
|
114
|
+
* offPath: { event: "cellSelected" } },
|
|
115
|
+
* ]);
|
|
116
|
+
* tour.attach(bus); // or call tour.notify(type, data) from the app's own channels
|
|
117
|
+
* tour.start();
|
|
118
|
+
*
|
|
119
|
+
* An action the app reports no event for can't be a step, and the fix is an app event rather than
|
|
120
|
+
* a cleverer listener: an action nothing outside the app can observe can't be checked by a tour, a
|
|
121
|
+
* browser test or an agent either. The `dom` trigger is the narrow exception, for steps about the
|
|
122
|
+
* UI itself.
|
|
123
|
+
*
|
|
124
|
+
* Esc and the panel's close button end any tour. Input outside the holes (pointer and wheel) is
|
|
125
|
+
* blocked; keyboard input isn't, so a reader can still Tab to the rest of the page.
|
|
126
|
+
*/
|
|
127
|
+
export class Tour<E extends object = Record<string, any>> {
|
|
128
|
+
private at = -1;
|
|
129
|
+
private overlay: TourOverlay | null = null;
|
|
130
|
+
private frame = 0;
|
|
131
|
+
private domTypes: string[] = [];
|
|
132
|
+
private readonly labels: TourLabels;
|
|
133
|
+
|
|
134
|
+
/** @param steps the steps, in order. A tour with no steps never starts. */
|
|
135
|
+
constructor(
|
|
136
|
+
readonly steps: readonly TourStep<E>[],
|
|
137
|
+
private readonly options: TourOptions<E> = {},
|
|
138
|
+
) {
|
|
139
|
+
this.labels = { ...DEFAULT_LABELS, ...options.labels };
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/** Whether the tour is showing a step. */
|
|
143
|
+
get running(): boolean {
|
|
144
|
+
return this.at >= 0;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/** The live step's index, or -1 when the tour isn't running. */
|
|
148
|
+
get index(): number {
|
|
149
|
+
return this.at;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** The live step, or undefined when the tour isn't running. */
|
|
153
|
+
get step(): TourStep<E> | undefined {
|
|
154
|
+
return this.steps[this.at];
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/**
|
|
158
|
+
* Shows the overlay and step `at` (0 by default). On a running tour it moves to that step. A tour
|
|
159
|
+
* can be started again after it ends.
|
|
160
|
+
*/
|
|
161
|
+
start(at = 0): void {
|
|
162
|
+
if (at < 0 || at >= this.steps.length) return;
|
|
163
|
+
if (!this.overlay) {
|
|
164
|
+
this.overlay = new TourOverlay(document, this.labels, {
|
|
165
|
+
close: () => this.end("cancelled"),
|
|
166
|
+
next: () => this.next(),
|
|
167
|
+
showMe: () => this.step?.doItForMe?.(),
|
|
168
|
+
});
|
|
169
|
+
document.addEventListener("keydown", this.onKey, true);
|
|
170
|
+
}
|
|
171
|
+
this.go(at);
|
|
172
|
+
if (!this.frame) this.frame = raf(this.tick);
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/** Moves to the next step, or ends the tour as `"done"` after the last one. */
|
|
176
|
+
next(): void {
|
|
177
|
+
if (!this.running) return;
|
|
178
|
+
if (this.at + 1 >= this.steps.length) this.end("done");
|
|
179
|
+
else this.go(this.at + 1);
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/** Removes the overlay and runs `onEnd`. Does nothing on a tour that isn't running. */
|
|
183
|
+
end(reason: TourEndReason = "cancelled"): void {
|
|
184
|
+
if (!this.running) return;
|
|
185
|
+
const index = this.at;
|
|
186
|
+
this.listenDom([]);
|
|
187
|
+
this.at = -1;
|
|
188
|
+
caf(this.frame);
|
|
189
|
+
this.frame = 0;
|
|
190
|
+
document.removeEventListener("keydown", this.onKey, true);
|
|
191
|
+
this.overlay?.destroy();
|
|
192
|
+
this.overlay = null;
|
|
193
|
+
this.options.onEnd?.(reason, this.steps[index], index);
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/**
|
|
197
|
+
* Tells the tour an app event happened, for an app that keeps its own channels rather than an
|
|
198
|
+
* EventBus. Ignored while the tour isn't running. The live step advances when it matches
|
|
199
|
+
* `advanceOn`, and otherwise applies `onOffPath` when it matches `offPath`. An event whose payload
|
|
200
|
+
* is `void` takes no data.
|
|
201
|
+
*/
|
|
202
|
+
notify<K extends keyof E & string>(type: K, ...data: E[K] extends void ? [data?: E[K]] : [data: E[K]]): void {
|
|
203
|
+
this.seen({ kind: "app", type, data: data[0] });
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/**
|
|
207
|
+
* Subscribes to every app event any step names (in `advanceOn` or `offPath`) and passes each to
|
|
208
|
+
* `notify`. The subscriptions last until the returned function is called, across ends and
|
|
209
|
+
* restarts; events arriving while the tour isn't running are ignored.
|
|
210
|
+
*/
|
|
211
|
+
attach(source: TourEventSource): () => void {
|
|
212
|
+
const names = new Set<string>();
|
|
213
|
+
for (const s of this.steps) {
|
|
214
|
+
for (const t of [s.advanceOn, ...triggers(s.offPath)]) if (t && "event" in t) names.add(t.event);
|
|
215
|
+
}
|
|
216
|
+
const handlers = [...names].map((type) => {
|
|
217
|
+
const h = (data?: any) => this.seen({ kind: "app", type, data });
|
|
218
|
+
source.on(type, h);
|
|
219
|
+
return [type, h] as const;
|
|
220
|
+
});
|
|
221
|
+
return () => handlers.forEach(([type, h]) => source.off(type, h));
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
private go(at: number): void {
|
|
225
|
+
this.at = at;
|
|
226
|
+
const step = this.steps[at];
|
|
227
|
+
this.listenDom(
|
|
228
|
+
[step.advanceOn, ...triggers(step.offPath)].flatMap((t) => (t && "dom" in t ? [t.dom] : [])),
|
|
229
|
+
);
|
|
230
|
+
this.overlay!.show(step.id, {
|
|
231
|
+
index: at,
|
|
232
|
+
count: this.steps.length,
|
|
233
|
+
title: step.title,
|
|
234
|
+
text: step.text,
|
|
235
|
+
next: !step.advanceOn,
|
|
236
|
+
showMe: !!step.doItForMe,
|
|
237
|
+
});
|
|
238
|
+
this.measure();
|
|
239
|
+
this.options.onStep?.(step, at);
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
private seen(e: Seen): void {
|
|
243
|
+
const step = this.step;
|
|
244
|
+
if (!step) return;
|
|
245
|
+
if (step.advanceOn && matches(step.advanceOn, e)) this.next();
|
|
246
|
+
else if (triggers(step.offPath).some((t) => matches(t, e)) && (step.onOffPath ?? "end") === "end") {
|
|
247
|
+
this.end("offPath");
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
// DOM triggers listen on the document in the capture phase and check the event's path against the
|
|
252
|
+
// step's targets as they are now, so a target that re-renders between frames still counts, and a
|
|
253
|
+
// non-bubbling event (pointerenter) is still seen.
|
|
254
|
+
private listenDom(types: string[]): void {
|
|
255
|
+
for (const t of this.domTypes) document.removeEventListener(t, this.onDom, true);
|
|
256
|
+
this.domTypes = [...new Set(types)];
|
|
257
|
+
for (const t of this.domTypes) document.addEventListener(t, this.onDom, true);
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
private readonly onDom = (e: Event): void => {
|
|
261
|
+
const path = e.composedPath();
|
|
262
|
+
if (this.resolve().elements.some((el) => path.includes(el))) this.seen({ kind: "dom", type: e.type });
|
|
263
|
+
};
|
|
264
|
+
|
|
265
|
+
private readonly onKey = (e: KeyboardEvent): void => {
|
|
266
|
+
if (e.key !== "Escape") return;
|
|
267
|
+
e.stopPropagation();
|
|
268
|
+
this.end("cancelled");
|
|
269
|
+
};
|
|
270
|
+
|
|
271
|
+
private readonly tick = (): void => {
|
|
272
|
+
if (!this.running) return;
|
|
273
|
+
this.measure();
|
|
274
|
+
this.frame = raf(this.tick);
|
|
275
|
+
};
|
|
276
|
+
|
|
277
|
+
// Re-measured every frame while a step is live, which covers a resize, a scroll and a layout that
|
|
278
|
+
// moves under the overlay alike; the overlay only touches the DOM when something changed.
|
|
279
|
+
private measure(): void {
|
|
280
|
+
const by = this.options.padding ?? 4;
|
|
281
|
+
this.overlay?.setHoles(this.resolve().rects.map((r) => pad(r, by)));
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
private resolve(): { elements: Element[]; rects: Rect[] } {
|
|
285
|
+
const elements: Element[] = [];
|
|
286
|
+
const rects: Rect[] = [];
|
|
287
|
+
const add = (t: Element | DOMRectReadOnly | Rect) => {
|
|
288
|
+
if (isElement(t)) {
|
|
289
|
+
elements.push(t);
|
|
290
|
+
const r = t.getBoundingClientRect();
|
|
291
|
+
if (r.width > 0 && r.height > 0) rects.push({ x: r.x, y: r.y, width: r.width, height: r.height });
|
|
292
|
+
} else {
|
|
293
|
+
rects.push({ x: t.x, y: t.y, width: t.width, height: t.height });
|
|
294
|
+
}
|
|
295
|
+
};
|
|
296
|
+
const target = this.step?.target?.();
|
|
297
|
+
if (target == null) return { elements, rects };
|
|
298
|
+
if (isElement(target) || !isIterable(target)) add(target as Element | Rect);
|
|
299
|
+
else for (const t of target) add(t);
|
|
300
|
+
return { elements, rects };
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
function triggers<E>(t: TourTrigger<E> | readonly TourTrigger<E>[] | undefined): readonly TourTrigger<E>[] {
|
|
305
|
+
if (!t) return [];
|
|
306
|
+
return Array.isArray(t) ? t : [t as TourTrigger<E>];
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
function matches<E>(t: TourTrigger<E>, e: Seen): boolean {
|
|
310
|
+
if ("dom" in t) return e.kind === "dom" && e.type === t.dom;
|
|
311
|
+
const app = t as { event: string; where?: (data: unknown) => boolean };
|
|
312
|
+
return e.kind === "app" && e.type === app.event && (!app.where || app.where(e.data));
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
const isElement = (t: unknown): t is Element => typeof Element !== "undefined" && t instanceof Element;
|
|
316
|
+
const isIterable = (t: object): t is Iterable<Element | Rect> => Symbol.iterator in t;
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
// The tour overlay's geometry, kept free of the DOM so it can be tested without layout: the holes
|
|
2
|
+
// as one clip path, and where the step's panel goes so it covers none of them.
|
|
3
|
+
|
|
4
|
+
/** A rectangle in viewport (client) coordinates. */
|
|
5
|
+
export interface Rect {
|
|
6
|
+
x: number;
|
|
7
|
+
y: number;
|
|
8
|
+
width: number;
|
|
9
|
+
height: number;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Splits the union of rects into disjoint rects. The overlay's clip path is even-odd, so two holes
|
|
14
|
+
* that overlap (padded table rows always do) would dim their overlap again; disjoint pieces don't.
|
|
15
|
+
*/
|
|
16
|
+
export function unionRects(rects: readonly Rect[]): Rect[] {
|
|
17
|
+
const rs = rects.filter((r) => r.width > 0 && r.height > 0);
|
|
18
|
+
if (rs.length <= 1) return rs.map((r) => ({ ...r }));
|
|
19
|
+
const edges = (pick: (r: Rect) => [number, number]) =>
|
|
20
|
+
[...new Set(rs.flatMap(pick))].sort((a, b) => a - b);
|
|
21
|
+
const xs = edges((r) => [r.x, r.x + r.width]);
|
|
22
|
+
const ys = edges((r) => [r.y, r.y + r.height]);
|
|
23
|
+
const covered = (cx: number, cy: number) =>
|
|
24
|
+
rs.some((r) => cx > r.x && cx < r.x + r.width && cy > r.y && cy < r.y + r.height);
|
|
25
|
+
|
|
26
|
+
const out: Rect[] = [];
|
|
27
|
+
for (let j = 0; j + 1 < ys.length; j++) {
|
|
28
|
+
const y = ys[j], height = ys[j + 1] - ys[j], cy = y + height / 2;
|
|
29
|
+
let start: number | null = null;
|
|
30
|
+
for (let i = 0; i + 1 < xs.length; i++) {
|
|
31
|
+
const inside = covered((xs[i] + xs[i + 1]) / 2, cy);
|
|
32
|
+
if (inside && start === null) start = xs[i];
|
|
33
|
+
if (!inside && start !== null) {
|
|
34
|
+
out.push({ x: start, y, width: xs[i] - start, height });
|
|
35
|
+
start = null;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
if (start !== null) out.push({ x: start, y, width: xs[xs.length - 1] - start, height });
|
|
39
|
+
}
|
|
40
|
+
return mergeBands(out);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
// Joins a piece to the one directly above it when they span the same columns, so a column of
|
|
44
|
+
// table rows becomes one rect rather than one per row.
|
|
45
|
+
function mergeBands(rs: Rect[]): Rect[] {
|
|
46
|
+
const out: Rect[] = [];
|
|
47
|
+
for (const r of rs) {
|
|
48
|
+
const above = out.find((o) => o.x === r.x && o.width === r.width && o.y + o.height === r.y);
|
|
49
|
+
if (above) above.height += r.height;
|
|
50
|
+
else out.push({ ...r });
|
|
51
|
+
}
|
|
52
|
+
return out;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** The even-odd path for a layer of width w and height h with one hole per (disjoint) rect. */
|
|
56
|
+
export function holePath(w: number, h: number, holes: readonly Rect[]): string {
|
|
57
|
+
const n = (v: number) => Math.round(v * 10) / 10;
|
|
58
|
+
let d = `M0 0H${n(w)}V${n(h)}H0Z`;
|
|
59
|
+
for (const r of holes) d += `M${n(r.x)} ${n(r.y)}h${n(r.width)}v${n(r.height)}h${n(-r.width)}Z`;
|
|
60
|
+
return d;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** Grows a rect by pad on every side. */
|
|
64
|
+
export function pad(r: Rect, by: number): Rect {
|
|
65
|
+
return { x: r.x - by, y: r.y - by, width: r.width + 2 * by, height: r.height + 2 * by };
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
const overlap = (a: Rect, b: Rect) =>
|
|
69
|
+
Math.max(0, Math.min(a.x + a.width, b.x + b.width) - Math.max(a.x, b.x)) *
|
|
70
|
+
Math.max(0, Math.min(a.y + a.height, b.y + b.height) - Math.max(a.y, b.y));
|
|
71
|
+
|
|
72
|
+
/** Viewports narrower than this get the panel pinned across the top or bottom. */
|
|
73
|
+
export const NARROW = 600;
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Where the panel (pw by ph) goes in a vw by vh viewport: beside the holes (below, above, right,
|
|
77
|
+
* left of their bounding box, in that order), else a viewport corner, else whichever of those covers
|
|
78
|
+
* the least of them. Under NARROW it's pinned to the bottom, or the top when the bottom is taken.
|
|
79
|
+
* Every spot keeps gutter from the viewport's edges.
|
|
80
|
+
*/
|
|
81
|
+
export function placePanel(
|
|
82
|
+
holes: readonly Rect[],
|
|
83
|
+
vw: number,
|
|
84
|
+
vh: number,
|
|
85
|
+
pw: number,
|
|
86
|
+
ph: number,
|
|
87
|
+
gutter = 16,
|
|
88
|
+
gap = 12,
|
|
89
|
+
): { x: number; y: number } {
|
|
90
|
+
const clampX = (x: number) => Math.max(gutter, Math.min(x, vw - pw - gutter));
|
|
91
|
+
const clampY = (y: number) => Math.max(gutter, Math.min(y, vh - ph - gutter));
|
|
92
|
+
const spots: { x: number; y: number }[] = [];
|
|
93
|
+
if (vw < NARROW) {
|
|
94
|
+
spots.push({ x: gutter, y: vh - ph - gutter }, { x: gutter, y: gutter });
|
|
95
|
+
} else if (holes.length === 0) {
|
|
96
|
+
return { x: clampX((vw - pw) / 2), y: clampY((vh - ph) / 2) };
|
|
97
|
+
} else {
|
|
98
|
+
const left = Math.min(...holes.map((r) => r.x));
|
|
99
|
+
const top = Math.min(...holes.map((r) => r.y));
|
|
100
|
+
const right = Math.max(...holes.map((r) => r.x + r.width));
|
|
101
|
+
const bottom = Math.max(...holes.map((r) => r.y + r.height));
|
|
102
|
+
// Beside the box only when it fits on that side; the other axis slides to stay in view.
|
|
103
|
+
if (bottom + gap + ph <= vh - gutter) spots.push({ x: clampX(left), y: bottom + gap });
|
|
104
|
+
if (top - gap - ph >= gutter) spots.push({ x: clampX(left), y: top - gap - ph });
|
|
105
|
+
if (right + gap + pw <= vw - gutter) spots.push({ x: right + gap, y: clampY(top) });
|
|
106
|
+
if (left - gap - pw >= gutter) spots.push({ x: left - gap - pw, y: clampY(top) });
|
|
107
|
+
const [x0, x1, y0, y1] = [gutter, vw - pw - gutter, gutter, vh - ph - gutter];
|
|
108
|
+
spots.push({ x: x1, y: y1 }, { x: x0, y: y1 }, { x: x1, y: y0 }, { x: x0, y: y0 });
|
|
109
|
+
}
|
|
110
|
+
const covers = (s: { x: number; y: number }) =>
|
|
111
|
+
holes.reduce((sum, r) => sum + overlap(r, { x: s.x, y: s.y, width: pw, height: ph }), 0);
|
|
112
|
+
return spots.find((s) => covers(s) === 0) ?? spots.reduce((a, b) => (covers(b) < covers(a) ? b : a));
|
|
113
|
+
}
|
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
// The tour's DOM: a dimmed layer with holes cut by an even-odd clip-path, a ring round each target,
|
|
2
|
+
// and the step's panel. A clipped-away area isn't hit-tested, so input in a hole reaches the element
|
|
3
|
+
// under it untouched (hover, focus, drag), and input anywhere else lands on the layer and stops there.
|
|
4
|
+
import { holePath, placePanel, type Rect, unionRects } from "./geometry";
|
|
5
|
+
|
|
6
|
+
/** The panel's button labels, for an app that isn't in English. */
|
|
7
|
+
export interface TourLabels {
|
|
8
|
+
next: string;
|
|
9
|
+
done: string;
|
|
10
|
+
showMe: string;
|
|
11
|
+
close: string;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export const DEFAULT_LABELS: TourLabels = { next: "Next", done: "Done", showMe: "Show me", close: "End tour" };
|
|
15
|
+
|
|
16
|
+
/** What the panel shows for one step. */
|
|
17
|
+
export interface PanelView {
|
|
18
|
+
index: number;
|
|
19
|
+
count: number;
|
|
20
|
+
title?: string;
|
|
21
|
+
text: string;
|
|
22
|
+
next: boolean;
|
|
23
|
+
showMe: boolean;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
const STYLE_ATTR = "data-tsappkit-tour-style";
|
|
27
|
+
|
|
28
|
+
// Every color and size is a custom property with a fallback, so an app themes the tour by setting
|
|
29
|
+
// them on :root (or on .tsappkit-tour) without fighting this sheet's specificity.
|
|
30
|
+
const CSS = `
|
|
31
|
+
.tsappkit-tour { position: fixed; inset: 0; z-index: var(--tsappkit-tour-z, 2147483000); pointer-events: none; }
|
|
32
|
+
.tsappkit-tour-dim { position: absolute; inset: 0; pointer-events: auto; background: var(--tsappkit-tour-dim, rgba(2, 6, 23, .6)); }
|
|
33
|
+
.tsappkit-tour-ring { position: absolute; pointer-events: none; border-radius: var(--tsappkit-tour-ring-radius, 6px);
|
|
34
|
+
box-shadow: 0 0 0 2px var(--tsappkit-tour-accent, #3b82f6); }
|
|
35
|
+
.tsappkit-tour-panel { position: absolute; pointer-events: auto; box-sizing: border-box;
|
|
36
|
+
width: min(var(--tsappkit-tour-panel-width, 360px), calc(100vw - 32px)); padding: 12px 16px 14px;
|
|
37
|
+
border-radius: var(--tsappkit-tour-panel-radius, 10px); font: var(--tsappkit-tour-font, 14px/1.5 system-ui, sans-serif);
|
|
38
|
+
background: var(--tsappkit-tour-panel-bg, #ffffff); color: var(--tsappkit-tour-panel-fg, #0f172a);
|
|
39
|
+
box-shadow: 0 12px 32px rgba(0, 0, 0, .35); }
|
|
40
|
+
.tsappkit-tour-head { display: flex; align-items: center; justify-content: space-between; gap: 8px;
|
|
41
|
+
font-size: .85em; opacity: .75; }
|
|
42
|
+
.tsappkit-tour-close { all: unset; cursor: pointer; font-size: 1.4em; line-height: 1; padding: 0 4px; }
|
|
43
|
+
.tsappkit-tour-close:focus-visible, .tsappkit-tour-actions button:focus-visible {
|
|
44
|
+
outline: 2px solid var(--tsappkit-tour-accent, #3b82f6); outline-offset: 2px; }
|
|
45
|
+
.tsappkit-tour-title { font-weight: 600; margin: 4px 0 0; }
|
|
46
|
+
.tsappkit-tour-text { margin: 4px 0 0; }
|
|
47
|
+
.tsappkit-tour-actions { display: flex; justify-content: flex-end; gap: 8px; margin-top: 10px; }
|
|
48
|
+
.tsappkit-tour-actions:empty { display: none; }
|
|
49
|
+
.tsappkit-tour-actions button { font: inherit; cursor: pointer; padding: 4px 12px; border-radius: 6px;
|
|
50
|
+
border: 1px solid var(--tsappkit-tour-accent, #3b82f6); background: transparent; color: inherit; }
|
|
51
|
+
.tsappkit-tour-actions .tsappkit-tour-next { background: var(--tsappkit-tour-accent, #3b82f6); color: var(--tsappkit-tour-accent-fg, #ffffff); }
|
|
52
|
+
@media (prefers-color-scheme: dark) {
|
|
53
|
+
.tsappkit-tour-panel { background: var(--tsappkit-tour-panel-bg, #1e293b); color: var(--tsappkit-tour-panel-fg, #e2e8f0); }
|
|
54
|
+
}
|
|
55
|
+
`;
|
|
56
|
+
|
|
57
|
+
// Pointer input that misses the holes stops at the overlay, so an app's document-level listeners
|
|
58
|
+
// (close-on-outside-click, say) don't see it either.
|
|
59
|
+
const SWALLOWED = ["pointerdown", "pointerup", "mousedown", "mouseup", "click", "dblclick", "contextmenu"];
|
|
60
|
+
|
|
61
|
+
export class TourOverlay {
|
|
62
|
+
readonly root: HTMLElement;
|
|
63
|
+
private readonly dim: HTMLElement;
|
|
64
|
+
private readonly rings: HTMLElement;
|
|
65
|
+
readonly panel: HTMLElement;
|
|
66
|
+
private readonly count: HTMLElement;
|
|
67
|
+
private readonly title: HTMLElement;
|
|
68
|
+
private readonly text: HTMLElement;
|
|
69
|
+
private readonly actions: HTMLElement;
|
|
70
|
+
private key = "";
|
|
71
|
+
|
|
72
|
+
constructor(
|
|
73
|
+
private readonly doc: Document,
|
|
74
|
+
private readonly labels: TourLabels,
|
|
75
|
+
private readonly on: { close(): void; next(): void; showMe(): void },
|
|
76
|
+
) {
|
|
77
|
+
if (!doc.head.querySelector(`style[${STYLE_ATTR}]`)) {
|
|
78
|
+
const style = doc.createElement("style");
|
|
79
|
+
style.setAttribute(STYLE_ATTR, "");
|
|
80
|
+
style.textContent = CSS;
|
|
81
|
+
doc.head.prepend(style);
|
|
82
|
+
}
|
|
83
|
+
const el = (tag: string, cls: string, parent?: HTMLElement) => {
|
|
84
|
+
const e = doc.createElement(tag);
|
|
85
|
+
e.className = cls;
|
|
86
|
+
parent?.append(e);
|
|
87
|
+
return e;
|
|
88
|
+
};
|
|
89
|
+
this.root = el("div", "tsappkit-tour");
|
|
90
|
+
this.dim = el("div", "tsappkit-tour-dim", this.root);
|
|
91
|
+
this.rings = el("div", "tsappkit-tour-rings", this.root);
|
|
92
|
+
this.panel = el("div", "tsappkit-tour-panel", this.root);
|
|
93
|
+
this.panel.setAttribute("role", "dialog");
|
|
94
|
+
this.panel.setAttribute("aria-label", "Tour");
|
|
95
|
+
const head = el("div", "tsappkit-tour-head", this.panel);
|
|
96
|
+
this.count = el("span", "tsappkit-tour-count", head);
|
|
97
|
+
const close = el("button", "tsappkit-tour-close", head) as HTMLButtonElement;
|
|
98
|
+
close.type = "button";
|
|
99
|
+
close.textContent = "×";
|
|
100
|
+
close.setAttribute("aria-label", labels.close);
|
|
101
|
+
close.addEventListener("click", () => this.on.close());
|
|
102
|
+
this.title = el("div", "tsappkit-tour-title", this.panel);
|
|
103
|
+
this.text = el("p", "tsappkit-tour-text", this.panel);
|
|
104
|
+
this.text.setAttribute("aria-live", "polite");
|
|
105
|
+
this.actions = el("div", "tsappkit-tour-actions", this.panel);
|
|
106
|
+
|
|
107
|
+
for (const type of SWALLOWED) this.root.addEventListener(type, (e) => e.stopPropagation());
|
|
108
|
+
// Scrolling outside the holes would move the page under a reader who can't otherwise reach it.
|
|
109
|
+
const block = (e: Event) => e.preventDefault();
|
|
110
|
+
this.dim.addEventListener("wheel", block, { passive: false });
|
|
111
|
+
this.dim.addEventListener("touchmove", block, { passive: false });
|
|
112
|
+
doc.body.append(this.root);
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** Puts a step's text and buttons in the panel. */
|
|
116
|
+
show(step: string, view: PanelView): void {
|
|
117
|
+
this.root.dataset.tourStep = step;
|
|
118
|
+
this.count.textContent = `${view.index + 1} of ${view.count}`;
|
|
119
|
+
this.title.textContent = view.title ?? "";
|
|
120
|
+
this.title.hidden = !view.title;
|
|
121
|
+
this.text.textContent = view.text;
|
|
122
|
+
this.actions.replaceChildren();
|
|
123
|
+
const button = (label: string, cls: string, click: () => void) => {
|
|
124
|
+
const b = this.doc.createElement("button");
|
|
125
|
+
b.type = "button";
|
|
126
|
+
b.className = cls;
|
|
127
|
+
b.textContent = label;
|
|
128
|
+
b.addEventListener("click", click);
|
|
129
|
+
this.actions.append(b);
|
|
130
|
+
};
|
|
131
|
+
if (view.showMe) button(this.labels.showMe, "tsappkit-tour-showme", () => this.on.showMe());
|
|
132
|
+
if (view.next) {
|
|
133
|
+
const last = view.index + 1 === view.count;
|
|
134
|
+
button(last ? this.labels.done : this.labels.next, "tsappkit-tour-next", () => this.on.next());
|
|
135
|
+
}
|
|
136
|
+
this.key = "";
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* Cuts one hole per rect (already padded, in viewport coordinates) and places the panel clear of
|
|
141
|
+
* them. Cheap to call every frame: it only touches the DOM when the holes, the viewport or the
|
|
142
|
+
* panel's size changed.
|
|
143
|
+
*/
|
|
144
|
+
setHoles(rects: readonly Rect[]): void {
|
|
145
|
+
const vw = this.doc.documentElement.clientWidth;
|
|
146
|
+
const vh = this.doc.documentElement.clientHeight;
|
|
147
|
+
const pw = this.panel.offsetWidth;
|
|
148
|
+
const ph = this.panel.offsetHeight;
|
|
149
|
+
const key = `${vw}x${vh} ${pw}x${ph} ` + rects.map((r) => `${r.x},${r.y},${r.width},${r.height}`).join(" ");
|
|
150
|
+
if (key === this.key) return;
|
|
151
|
+
this.key = key;
|
|
152
|
+
|
|
153
|
+
const holes = unionRects(rects);
|
|
154
|
+
this.dim.style.clipPath = `path(evenodd, "${holePath(vw, vh, holes)}")`;
|
|
155
|
+
this.root.dataset.tourHoles = String(holes.length);
|
|
156
|
+
// One ring per hole after the union, so padded rows that overlap get one outline, not one each.
|
|
157
|
+
while (this.rings.children.length > holes.length) this.rings.lastElementChild!.remove();
|
|
158
|
+
while (this.rings.children.length < holes.length) {
|
|
159
|
+
const ring = this.doc.createElement("div");
|
|
160
|
+
ring.className = "tsappkit-tour-ring";
|
|
161
|
+
this.rings.append(ring);
|
|
162
|
+
}
|
|
163
|
+
holes.forEach((r, i) => {
|
|
164
|
+
const s = (this.rings.children[i] as HTMLElement).style;
|
|
165
|
+
s.left = `${r.x}px`;
|
|
166
|
+
s.top = `${r.y}px`;
|
|
167
|
+
s.width = `${r.width}px`;
|
|
168
|
+
s.height = `${r.height}px`;
|
|
169
|
+
});
|
|
170
|
+
const at = placePanel(rects, vw, vh, pw, ph);
|
|
171
|
+
this.panel.style.left = `${at.x}px`;
|
|
172
|
+
this.panel.style.top = `${at.y}px`;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
destroy(): void {
|
|
176
|
+
this.root.remove();
|
|
177
|
+
}
|
|
178
|
+
}
|