@thedatagrid/docs-kit 0.2.2 → 0.3.0

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/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@thedatagrid/docs-kit",
3
- "version": "0.2.2",
4
- "description": "Docs tooling: type-checked file snippets with regions and highlights, prebuilt and editable live demos, CodeSandbox forks",
3
+ "version": "0.3.0",
4
+ "description": "Docs tooling: type-checked file snippets with regions and highlights, prebuilt and editable live demos, CodeSandbox forks, scripted showcase demos",
5
5
  "type": "module",
6
6
  "license": "MIT",
7
7
  "author": "TheDataGrid",
@@ -40,6 +40,11 @@
40
40
  "types": "./dist/fork/index.d.ts",
41
41
  "default": "./dist/fork/index.js"
42
42
  },
43
+ "./showcase": {
44
+ "types": "./dist/showcase/index.d.ts",
45
+ "default": "./dist/showcase/index.js"
46
+ },
47
+ "./showcase/styles.css": "./dist/showcase/styles.css",
43
48
  "./package.json": "./package.json"
44
49
  },
45
50
  "typesVersions": {
@@ -0,0 +1,266 @@
1
+ 'use client';
2
+
3
+ import {
4
+ useCallback,
5
+ useEffect,
6
+ useRef,
7
+ useState,
8
+ type CSSProperties,
9
+ type ReactNode,
10
+ } from 'react';
11
+
12
+ import { canRunScriptedShow } from './hooks.ts';
13
+ import {
14
+ createScriptedCursor,
15
+ ScriptCancelled,
16
+ sleep,
17
+ waitFor,
18
+ type ScriptedCursor,
19
+ } from './scripted.ts';
20
+
21
+ export type AutomatedDemoStatus =
22
+ /** Not animating: offscreen, before ready, or unsupported device. */
23
+ | 'idle'
24
+ /** The show is running (fake cursor visible). */
25
+ | 'running'
26
+ /** The user interacted — the demo is theirs until they hit replay. */
27
+ | 'user';
28
+
29
+ export type ShowcaseScriptContext = {
30
+ /** Wrapper element containing the live demo (and its in-demo portals). */
31
+ root: HTMLElement;
32
+ cursor: ScriptedCursor;
33
+ signal: AbortSignal;
34
+ };
35
+
36
+ export type AutomatedDemoProps = {
37
+ children: ReactNode;
38
+ /** The product demo is mounted and can be driven. */
39
+ ready: boolean;
40
+ /** One full pass of the show. Must honour `signal` (use the toolkit helpers). */
41
+ run: (context: ShowcaseScriptContext) => Promise<void>;
42
+ /** Put the demo back to its initial state; called before every pass. */
43
+ reset?: (context: ShowcaseScriptContext) => void | Promise<void>;
44
+ /** Wait for this selector inside the root before the first pass. */
45
+ waitForSelector?: string;
46
+ /** Pause between passes, in ms. */
47
+ loopPause?: number;
48
+ /** No show below this viewport width (and never on touch / reduced motion). */
49
+ minViewportWidth?: number;
50
+ /** IntersectionObserver threshold for "in view". */
51
+ threshold?: number;
52
+ runningLabel?: ReactNode;
53
+ userLabel?: ReactNode;
54
+ className?: string;
55
+ style?: CSSProperties;
56
+ onStatusChange?: (status: AutomatedDemoStatus) => void;
57
+ };
58
+
59
+ /**
60
+ * Wraps a live demo in an automated show: a scripted cursor drives the LIVE
61
+ * component while it's in view, and the first real interaction (click /
62
+ * wheel / touch / key) hands control to the user instantly, leaving the demo
63
+ * where the script left it. A broken script ends quietly — it must never
64
+ * break the page.
65
+ */
66
+ export function AutomatedDemo({
67
+ children,
68
+ ready,
69
+ run,
70
+ reset,
71
+ waitForSelector,
72
+ loopPause = 2600,
73
+ minViewportWidth = 768,
74
+ threshold = 0.35,
75
+ runningLabel = 'live demo — click anywhere to take over',
76
+ userLabel = 'you’re in control — replay demo ↻',
77
+ className,
78
+ style,
79
+ onStatusChange,
80
+ }: AutomatedDemoProps) {
81
+ const wrapperRef = useRef<HTMLDivElement | null>(null);
82
+ const overlayRef = useRef<HTMLDivElement | null>(null);
83
+ const cursorRef = useRef<ScriptedCursor | null>(null);
84
+ const abortRef = useRef<AbortController | null>(null);
85
+ const intersectingRef = useRef(false);
86
+ const readyRef = useRef(ready);
87
+ const statusRef = useRef<AutomatedDemoStatus>('idle');
88
+ const [status, setStatusState] = useState<AutomatedDemoStatus>('idle');
89
+
90
+ // latest callbacks without restarting the observers
91
+ const runRef = useRef(run);
92
+ const resetRef = useRef(reset);
93
+ const onStatusChangeRef = useRef(onStatusChange);
94
+ runRef.current = run;
95
+ resetRef.current = reset;
96
+ onStatusChangeRef.current = onStatusChange;
97
+
98
+ const setStatus = useCallback((next: AutomatedDemoStatus) => {
99
+ statusRef.current = next;
100
+ setStatusState(next);
101
+ onStatusChangeRef.current?.(next);
102
+ }, []);
103
+
104
+ const stop = useCallback(
105
+ (next: AutomatedDemoStatus) => {
106
+ abortRef.current?.abort();
107
+ abortRef.current = null;
108
+ cursorRef.current?.hide();
109
+ setStatus(next);
110
+ },
111
+ [setStatus],
112
+ );
113
+
114
+ const tryStart = useCallback(() => {
115
+ if (statusRef.current !== 'idle') return;
116
+ if (!intersectingRef.current || !readyRef.current) return;
117
+ if (document.visibilityState === 'hidden') return;
118
+ const root = wrapperRef.current;
119
+ const overlay = overlayRef.current;
120
+ if (!root || !overlay) return;
121
+ // the show is pointless (and annoying) on touch / small / reduced-motion
122
+ if (!canRunScriptedShow(minViewportWidth)) return;
123
+
124
+ if (!cursorRef.current) cursorRef.current = createScriptedCursor(overlay);
125
+ const cursor = cursorRef.current;
126
+ const controller = new AbortController();
127
+ abortRef.current = controller;
128
+ setStatus('running');
129
+
130
+ void (async () => {
131
+ const { signal } = controller;
132
+ const context: ShowcaseScriptContext = { root, cursor, signal };
133
+ try {
134
+ if (waitForSelector) {
135
+ const found = await waitFor(
136
+ () => root.querySelector(waitForSelector),
137
+ signal,
138
+ {
139
+ timeout: 20000,
140
+ },
141
+ );
142
+ if (!found) throw new ScriptCancelled();
143
+ }
144
+ for (;;) {
145
+ await resetRef.current?.(context);
146
+ await sleep(700, signal);
147
+ await runRef.current(context);
148
+ cursor.hide();
149
+ await sleep(loopPause, signal);
150
+ }
151
+ } catch (error) {
152
+ cursor.hide();
153
+ if (!(error instanceof ScriptCancelled)) {
154
+ // a broken show must never break the page — just end it quietly
155
+ console.warn('[automated-demo]', error);
156
+ if (statusRef.current === 'running') stop('user');
157
+ }
158
+ }
159
+ })();
160
+ }, [loopPause, minViewportWidth, setStatus, stop, waitForSelector]);
161
+
162
+ useEffect(() => {
163
+ readyRef.current = ready;
164
+ if (ready) tryStart();
165
+ else if (statusRef.current === 'running') stop('idle');
166
+ }, [ready, tryStart, stop]);
167
+
168
+ // start/pause with viewport visibility
169
+ useEffect(() => {
170
+ const root = wrapperRef.current;
171
+ if (!root) return;
172
+ const observer = new IntersectionObserver(
173
+ (entries) => {
174
+ const isIntersecting = entries.some((entry) => entry.isIntersecting);
175
+ intersectingRef.current = isIntersecting;
176
+ if (isIntersecting) tryStart();
177
+ else if (statusRef.current === 'running') stop('idle');
178
+ },
179
+ { threshold },
180
+ );
181
+ observer.observe(root);
182
+ return () => observer.disconnect();
183
+ }, [threshold, tryStart, stop]);
184
+
185
+ // a hidden tab is as good as off-screen
186
+ useEffect(() => {
187
+ const onVisibility = () => {
188
+ if (document.visibilityState === 'hidden') {
189
+ if (statusRef.current === 'running') stop('idle');
190
+ } else {
191
+ tryStart();
192
+ }
193
+ };
194
+ document.addEventListener('visibilitychange', onVisibility);
195
+ return () => document.removeEventListener('visibilitychange', onVisibility);
196
+ }, [tryStart, stop]);
197
+
198
+ // first REAL interaction anywhere on the demo = takeover. The script's own
199
+ // dispatched events are untrusted, which is how we tell them apart.
200
+ useEffect(() => {
201
+ const root = wrapperRef.current;
202
+ if (!root) return;
203
+ const onInteract = (event: Event) => {
204
+ if (!event.isTrusted) return;
205
+ if (statusRef.current === 'running') stop('user');
206
+ // touched before the show got going: don't start it under the user
207
+ else if (
208
+ statusRef.current === 'idle' &&
209
+ canRunScriptedShow(minViewportWidth)
210
+ ) {
211
+ stop('user');
212
+ }
213
+ };
214
+ const events = ['pointerdown', 'wheel', 'touchstart', 'keydown'] as const;
215
+ for (const type of events) {
216
+ root.addEventListener(type, onInteract, { capture: true, passive: true });
217
+ }
218
+ return () => {
219
+ for (const type of events)
220
+ root.removeEventListener(type, onInteract, { capture: true });
221
+ };
222
+ }, [stop, minViewportWidth]);
223
+
224
+ useEffect(() => {
225
+ return () => {
226
+ abortRef.current?.abort();
227
+ cursorRef.current?.destroy();
228
+ cursorRef.current = null;
229
+ };
230
+ }, []);
231
+
232
+ const replay = useCallback(() => {
233
+ if (statusRef.current === 'running') return;
234
+ setStatus('idle');
235
+ // let the status flip settle before the loop re-checks it
236
+ requestAnimationFrame(() => tryStart());
237
+ }, [setStatus, tryStart]);
238
+
239
+ return (
240
+ <div
241
+ ref={wrapperRef}
242
+ className={['showcase-demo', className].filter(Boolean).join(' ')}
243
+ data-showcase-status={status}
244
+ style={style}
245
+ >
246
+ {children}
247
+ {/* cursor layer: above the demo AND its in-demo popups, but transparent to input */}
248
+ <div ref={overlayRef} aria-hidden className="showcase-demo__overlay" />
249
+ {status === 'running' ? (
250
+ <div className="showcase-pill showcase-pill--running" role="status">
251
+ <span className="showcase-pill__dot" />
252
+ {runningLabel}
253
+ </div>
254
+ ) : null}
255
+ {status === 'user' ? (
256
+ <button
257
+ type="button"
258
+ onClick={replay}
259
+ className="showcase-pill showcase-pill--user"
260
+ >
261
+ {userLabel}
262
+ </button>
263
+ ) : null}
264
+ </div>
265
+ );
266
+ }
@@ -0,0 +1,111 @@
1
+ 'use client';
2
+
3
+ import {
4
+ useEffect,
5
+ useRef,
6
+ useState,
7
+ type ComponentType,
8
+ type CSSProperties,
9
+ type ReactNode,
10
+ } from 'react';
11
+
12
+ import { whenIdle } from './hooks.ts';
13
+
14
+ export type LazyShowcaseLoadedProps = {
15
+ /** Call once the live demo has painted its real content. */
16
+ onReady?: () => void;
17
+ };
18
+
19
+ export type LazyShowcaseProps<P extends object> = {
20
+ /** Dynamic import of the live demo, e.g. `() => import('./HeroDemo')`. */
21
+ load: () => Promise<{ default: ComponentType<P & LazyShowcaseLoadedProps> }>;
22
+ props: P;
23
+ /** Static first paint (an <img> screenshot, a skeleton…). Fades out once live. */
24
+ poster: ReactNode;
25
+ /**
26
+ * Fixed height, so swapping poster → live never shifts layout. Omit it when
27
+ * `className` sets a (responsive) height instead.
28
+ */
29
+ height?: number | string;
30
+ /** Start loading this far before the container scrolls into view. */
31
+ rootMargin?: string;
32
+ className?: string;
33
+ style?: CSSProperties;
34
+ };
35
+
36
+ /**
37
+ * Poster first, live demo later: the import starts when the container is
38
+ * near the viewport AND the main thread is idle, and the live demo cross-fades
39
+ * in over the poster once it reports `onReady`. Height is fixed up front, so
40
+ * there is no layout shift.
41
+ */
42
+ export function LazyShowcase<P extends object>({
43
+ load,
44
+ props,
45
+ poster,
46
+ height,
47
+ rootMargin = '200px',
48
+ className,
49
+ style,
50
+ }: LazyShowcaseProps<P>) {
51
+ const ref = useRef<HTMLDivElement | null>(null);
52
+ const loadRef = useRef(load);
53
+ loadRef.current = load;
54
+ const [Live, setLive] = useState<ComponentType<
55
+ P & LazyShowcaseLoadedProps
56
+ > | null>(null);
57
+ const [ready, setReady] = useState(false);
58
+ const [failed, setFailed] = useState(false);
59
+
60
+ useEffect(() => {
61
+ const node = ref.current;
62
+ if (!node) return;
63
+ let cancelIdle: (() => void) | undefined;
64
+ let disposed = false;
65
+ const observer = new IntersectionObserver(
66
+ (entries) => {
67
+ if (!entries.some((entry) => entry.isIntersecting)) return;
68
+ observer.disconnect();
69
+ cancelIdle = whenIdle(() => {
70
+ loadRef
71
+ .current()
72
+ .then((mod) => {
73
+ if (!disposed) setLive(() => mod.default);
74
+ })
75
+ .catch((error) => {
76
+ console.warn(
77
+ '[lazy-showcase] failed to load the live demo',
78
+ error,
79
+ );
80
+ if (!disposed) setFailed(true);
81
+ });
82
+ });
83
+ },
84
+ { rootMargin },
85
+ );
86
+ observer.observe(node);
87
+ return () => {
88
+ disposed = true;
89
+ observer.disconnect();
90
+ cancelIdle?.();
91
+ };
92
+ }, [rootMargin]);
93
+
94
+ return (
95
+ <div
96
+ ref={ref}
97
+ className={['showcase-lazy', className].filter(Boolean).join(' ')}
98
+ style={{ height, ...style }}
99
+ data-showcase-ready={ready ? 'true' : 'false'}
100
+ >
101
+ <div className="showcase-lazy__poster" aria-hidden={ready}>
102
+ {poster}
103
+ </div>
104
+ {Live && !failed ? (
105
+ <div className="showcase-lazy__live">
106
+ <Live {...props} onReady={() => setReady(true)} />
107
+ </div>
108
+ ) : null}
109
+ </div>
110
+ );
111
+ }
@@ -0,0 +1,84 @@
1
+ 'use client';
2
+
3
+ import { useEffect, useState, type RefObject } from 'react';
4
+
5
+ /** Subscribes to a media query; `false` during SSR. */
6
+ export function useMediaQuery(query: string) {
7
+ const [matches, setMatches] = useState(false);
8
+ useEffect(() => {
9
+ const mql = window.matchMedia(query);
10
+ const update = () => setMatches(mql.matches);
11
+ update();
12
+ mql.addEventListener('change', update);
13
+ return () => mql.removeEventListener('change', update);
14
+ }, [query]);
15
+ return matches;
16
+ }
17
+
18
+ export function usePrefersReducedMotion() {
19
+ return useMediaQuery('(prefers-reduced-motion: reduce)');
20
+ }
21
+
22
+ /** `true` while the document is visible (tab focused / not minimized). */
23
+ export function usePageVisible() {
24
+ const [visible, setVisible] = useState(true);
25
+ useEffect(() => {
26
+ const update = () => setVisible(document.visibilityState !== 'hidden');
27
+ update();
28
+ document.addEventListener('visibilitychange', update);
29
+ return () => document.removeEventListener('visibilitychange', update);
30
+ }, []);
31
+ return visible;
32
+ }
33
+
34
+ /** `true` while any part of the element (by `threshold`) is in the viewport. */
35
+ export function useInView(
36
+ ref: RefObject<Element | null>,
37
+ {
38
+ threshold = 0,
39
+ rootMargin = '0px',
40
+ }: { threshold?: number; rootMargin?: string } = {},
41
+ ) {
42
+ const [inView, setInView] = useState(false);
43
+ useEffect(() => {
44
+ const node = ref.current;
45
+ if (!node) return;
46
+ const observer = new IntersectionObserver(
47
+ (entries) => setInView(entries.some((entry) => entry.isIntersecting)),
48
+ { threshold, rootMargin },
49
+ );
50
+ observer.observe(node);
51
+ return () => observer.disconnect();
52
+ }, [ref, threshold, rootMargin]);
53
+ return inView;
54
+ }
55
+
56
+ /**
57
+ * Should a scripted show run on this device at all? Not on touch-only
58
+ * devices, small viewports, or with reduced motion.
59
+ */
60
+ export function canRunScriptedShow(minViewportWidth = 768) {
61
+ if (typeof window === 'undefined') return false;
62
+ return (
63
+ window.matchMedia('(pointer: fine)').matches &&
64
+ !window.matchMedia('(prefers-reduced-motion: reduce)').matches &&
65
+ window.innerWidth >= minViewportWidth
66
+ );
67
+ }
68
+
69
+ /** requestIdleCallback with a timeout fallback (Safari has no rIC). */
70
+ export function whenIdle(callback: () => void, timeout = 1500) {
71
+ const w = window as Window & {
72
+ requestIdleCallback?: (
73
+ cb: () => void,
74
+ opts?: { timeout: number },
75
+ ) => number;
76
+ cancelIdleCallback?: (id: number) => void;
77
+ };
78
+ if (w.requestIdleCallback) {
79
+ const id = w.requestIdleCallback(callback, { timeout });
80
+ return () => w.cancelIdleCallback?.(id);
81
+ }
82
+ const id = window.setTimeout(callback, Math.min(timeout, 300));
83
+ return () => window.clearTimeout(id);
84
+ }
@@ -0,0 +1,23 @@
1
+ /**
2
+ * Showcase kit: product-agnostic building blocks for live, scripted
3
+ * marketing demos — a fake cursor toolkit, the automated "take over" shell,
4
+ * and a poster-first lazy loader.
5
+ *
6
+ * BOUNDARY RULE: nothing in this folder may import product code or the rest
7
+ * of the kit — only React and sibling files (test/showcase.test.ts checks it).
8
+ *
9
+ * Styles: import `@thedatagrid/docs-kit/showcase/styles.css` once.
10
+ */
11
+ export * from './scripted.ts';
12
+ export * from './hooks.ts';
13
+ export { AutomatedDemo } from './AutomatedDemo.tsx';
14
+ export type {
15
+ AutomatedDemoProps,
16
+ AutomatedDemoStatus,
17
+ ShowcaseScriptContext,
18
+ } from './AutomatedDemo.tsx';
19
+ export { LazyShowcase } from './LazyShowcase.tsx';
20
+ export type {
21
+ LazyShowcaseProps,
22
+ LazyShowcaseLoadedProps,
23
+ } from './LazyShowcase.tsx';