@panyam/tsappkit 0.7.6 → 0.7.8
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 +90 -61
- package/dist/index.d.mts +209 -90
- package/dist/index.d.ts +209 -90
- package/dist/index.js +377 -4
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +377 -5
- package/dist/index.mjs.map +1 -1
- package/package.json +2 -2
- package/src/LCMComponent.ts +24 -77
- package/src/LifecycleController.ts +16 -13
- 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.8",
|
|
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/LCMComponent.ts
CHANGED
|
@@ -1,100 +1,47 @@
|
|
|
1
1
|
/**
|
|
2
|
-
*
|
|
2
|
+
* A LifeCycle Managed Component: one that a LifecycleController starts in
|
|
3
|
+
* phases, so a component can rely on every other component being set up
|
|
4
|
+
* before it activates.
|
|
3
5
|
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
* 2. bindToDOM() - Basic DOM setup, discover child components
|
|
10
|
-
* 3. injectDependencies() - Receive references to other components
|
|
11
|
-
* 4. activate() - Final setup when all dependencies are ready
|
|
12
|
-
*
|
|
13
|
-
* Key Benefits:
|
|
14
|
-
* - Order Independence: Components can be created in any sequence
|
|
15
|
-
* - Async Safety: Each phase waits for all components before proceeding
|
|
16
|
-
* - Clear Dependencies: Explicit injection points prevent race conditions
|
|
17
|
-
* - Error Isolation: Component failures don't cascade to others
|
|
18
|
-
*/
|
|
19
|
-
|
|
20
|
-
/**
|
|
21
|
-
* LCM Component - Short for LifeCycle Managed Component
|
|
22
|
-
* enable components to be declared first and their loading be managed by a
|
|
23
|
-
* LifecycleController so that we have layered creation, dependency injection and setup
|
|
24
|
-
* in a breadth first way.
|
|
25
|
-
*
|
|
26
|
-
* A key constraint on LCMComponents are that they should not perform any initialization
|
|
27
|
-
* in the constructor. This is because a LifecycleController should be used to load/setup
|
|
28
|
-
* these components and they will follow a layered approach. Performing these actions in
|
|
29
|
-
* the constructor could violate the idempotency guarantees.
|
|
6
|
+
* Keep the constructor to storing its arguments. The controller decides when
|
|
7
|
+
* the real work happens, phase by phase over the whole tree:
|
|
8
|
+
* performLocalInit, then setupDependencies, then activate. deactivate runs
|
|
9
|
+
* when the controller is torn down, leaves first.
|
|
10
|
+
* See https://panyam.github.io/goapplib/guide/components/.
|
|
30
11
|
*/
|
|
31
12
|
export interface LCMComponent {
|
|
32
13
|
/**
|
|
33
|
-
* Phase 1:
|
|
34
|
-
*
|
|
35
|
-
* In this phase the component initializes itself and returns any children it might
|
|
36
|
-
* want initialized as part of the lifecycled loading.
|
|
37
|
-
*
|
|
38
|
-
* This phase should:
|
|
39
|
-
* - Set up basic DOM elements and event listeners
|
|
40
|
-
* - Create child components (but don't initialize them) and return them
|
|
41
|
-
* - Return array of child components for lifecycle controller discovery
|
|
14
|
+
* Phase 1: set the component itself up, and return its children.
|
|
42
15
|
*
|
|
43
|
-
*
|
|
44
|
-
*
|
|
45
|
-
*
|
|
46
|
-
*
|
|
47
|
-
*
|
|
48
|
-
* @returns Array of child components to be managed by lifecycle controller
|
|
16
|
+
* Bind to the DOM and create child components here, without starting
|
|
17
|
+
* them. The children returned become the next level of the tree. Other
|
|
18
|
+
* components may not be set up yet, so don't reach for them. A Promise is
|
|
19
|
+
* awaited before the next component in the level starts.
|
|
49
20
|
*/
|
|
50
21
|
performLocalInit(): Promise<LCMComponent[]> | LCMComponent[];
|
|
51
22
|
|
|
52
23
|
/**
|
|
53
|
-
* Phase 2:
|
|
54
|
-
*
|
|
55
|
-
* This phase should:
|
|
56
|
-
* - Receive and store references to required dependencies
|
|
57
|
-
* - Validate that required dependencies are provided
|
|
58
|
-
* - Set up internal state based on dependencies
|
|
24
|
+
* Phase 2: take references to other components.
|
|
59
25
|
*
|
|
60
|
-
*
|
|
61
|
-
*
|
|
62
|
-
*
|
|
63
|
-
*
|
|
64
|
-
*
|
|
65
|
-
* @param deps Record of dependency name to dependency instance
|
|
66
|
-
* @returns Promise<void> or void - can be async
|
|
26
|
+
* Every component in the tree has finished performLocalInit by now, so a
|
|
27
|
+
* parent can hand its children their siblings, or itself. The controller
|
|
28
|
+
* doesn't await a Promise returned here: activate can start before it
|
|
29
|
+
* resolves, so do async work in activate instead.
|
|
67
30
|
*/
|
|
68
31
|
setupDependencies(): Promise<void> | void;
|
|
69
32
|
|
|
70
33
|
/**
|
|
71
|
-
* Phase 3:
|
|
72
|
-
*
|
|
73
|
-
* This phase should:
|
|
74
|
-
* - Complete final initialization
|
|
75
|
-
* - Enable component functionality
|
|
76
|
-
* - Start listening for external events
|
|
77
|
-
* - Begin normal operation
|
|
34
|
+
* Phase 3: start working. Subscribe to events, load data, render.
|
|
78
35
|
*
|
|
79
|
-
*
|
|
80
|
-
*
|
|
81
|
-
* - Load initial data
|
|
82
|
-
* - Emit ready notifications
|
|
83
|
-
*
|
|
84
|
-
* @returns Promise<void> or void - can be async
|
|
36
|
+
* Every component has finished setupDependencies. A level's activate
|
|
37
|
+
* calls run together, and the next level starts once all of them resolve.
|
|
85
38
|
*/
|
|
86
39
|
activate(): Promise<void> | void;
|
|
87
40
|
|
|
88
41
|
/**
|
|
89
|
-
*
|
|
90
|
-
*
|
|
91
|
-
*
|
|
92
|
-
* - Stop all ongoing operations
|
|
93
|
-
* - Remove event listeners
|
|
94
|
-
* - Clean up external connections
|
|
95
|
-
* - Dispose of child components
|
|
96
|
-
*
|
|
97
|
-
* @returns Promise<void> or void - can be async
|
|
42
|
+
* Stop working and release what activate took: subscriptions, listeners,
|
|
43
|
+
* connections. LifecycleController.deactivateAll calls it on the children
|
|
44
|
+
* before the parent, so a component doesn't deactivate its children itself.
|
|
98
45
|
*/
|
|
99
46
|
deactivate(): Promise<void> | void;
|
|
100
47
|
}
|
|
@@ -8,19 +8,22 @@ import { EventBus, LifecycleEventTypes, LifecycleEventType } from './EventBus';
|
|
|
8
8
|
import { ComponentLifecycleEvent } from './events';
|
|
9
9
|
|
|
10
10
|
/**
|
|
11
|
-
*
|
|
11
|
+
* Starts a tree of LCMComponents, one phase at a time over the whole tree.
|
|
12
12
|
*
|
|
13
|
-
*
|
|
14
|
-
*
|
|
13
|
+
* initializeFromRoot runs three phases, and each one finishes for every
|
|
14
|
+
* component before the next one starts:
|
|
15
|
+
* 1. performLocalInit, breadth-first from the root. Each component returns its
|
|
16
|
+
* children, which become the next level. Within a level, one component's
|
|
17
|
+
* call finishes (its Promise included) before the next one's starts.
|
|
18
|
+
* 2. setupDependencies, in the same order. A Promise it returns isn't awaited.
|
|
19
|
+
* 3. activate, level by level. A level's calls run together, and the next
|
|
20
|
+
* level starts once all of them have resolved.
|
|
15
21
|
*
|
|
16
|
-
*
|
|
17
|
-
*
|
|
18
|
-
*
|
|
19
|
-
*
|
|
20
|
-
*
|
|
21
|
-
*
|
|
22
|
-
* Each phase acts as a synchronization barrier - no component can proceed
|
|
23
|
-
* to the next phase until ALL components have completed the current phase.
|
|
22
|
+
* deactivateAll runs deactivate the other way, leaves first. A component
|
|
23
|
+
* returned by two parents is an error, and so is a second initializeFromRoot
|
|
24
|
+
* on the same controller. A phase that throws or rejects rejects
|
|
25
|
+
* initializeFromRoot, and the phases after it don't run.
|
|
26
|
+
* See https://panyam.github.io/goapplib/guide/components/.
|
|
24
27
|
*/
|
|
25
28
|
export class LifecycleController {
|
|
26
29
|
private allComponents: LCMComponent[];
|
|
@@ -47,8 +50,7 @@ export class LifecycleController {
|
|
|
47
50
|
* Initialize component tree starting from root component
|
|
48
51
|
*
|
|
49
52
|
* @param rootComponent The root component to start initialization from
|
|
50
|
-
* @
|
|
51
|
-
* @returns Promise that resolves when all components are fully initialized
|
|
53
|
+
* @returns Promise that resolves when every component has activated
|
|
52
54
|
*/
|
|
53
55
|
public async initializeFromRoot(rootComponent: LCMComponent): Promise<void> {
|
|
54
56
|
// Phase 1 - Performance post-load setup where each parent will have the change
|
|
@@ -87,6 +89,7 @@ export class LifecycleController {
|
|
|
87
89
|
`Component hierarchies must form a tree structure where each component has exactly one parent.`
|
|
88
90
|
);
|
|
89
91
|
}
|
|
92
|
+
visited.add(component);
|
|
90
93
|
|
|
91
94
|
this.emitEvent(LifecycleEventTypes.LOCAL_INIT_STARTED, component, level)
|
|
92
95
|
const result = component.performLocalInit()
|
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
|
+
}
|