@pablo2410/shared-ui 0.23.0 → 0.25.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.
@@ -0,0 +1,1145 @@
1
+ import {
2
+ portalUrl
3
+ } from "./chunk-7LI4Y6WT.js";
4
+ import {
5
+ cn
6
+ } from "./chunk-JT3XLKKD.js";
7
+
8
+ // src/tour/tourStore.ts
9
+ var MAX_STEP_ID_LENGTH = 120;
10
+ var MAX_TOUR_ID_LENGTH = 60;
11
+ var TOUR_ID_PATTERN = /^[a-z0-9][a-z0-9-]*$/;
12
+ var STEP_KINDS = ["intro", "service", "outro"];
13
+ var InvalidTourDefinitionError = class extends Error {
14
+ problems;
15
+ constructor(tourId, problems) {
16
+ super(`Invalid tour definition "${tourId}": ${problems.join("; ")}`);
17
+ this.name = "InvalidTourDefinitionError";
18
+ this.problems = problems;
19
+ }
20
+ };
21
+ function validateTourDefinition(def) {
22
+ const problems = [];
23
+ if (typeof def.id !== "string" || def.id.length === 0) {
24
+ problems.push("id is required");
25
+ } else {
26
+ if (def.id.length > MAX_TOUR_ID_LENGTH) {
27
+ problems.push(`id is longer than ${MAX_TOUR_ID_LENGTH} characters`);
28
+ }
29
+ if (!TOUR_ID_PATTERN.test(def.id)) {
30
+ problems.push("id must be lowercase letters, digits and hyphens");
31
+ }
32
+ }
33
+ if (!Array.isArray(def.steps) || def.steps.length === 0) {
34
+ problems.push("at least one step is required");
35
+ return problems;
36
+ }
37
+ const seen = /* @__PURE__ */ new Set();
38
+ def.steps.forEach((step, i) => {
39
+ const at = `step ${i + 1}`;
40
+ if (!step.id) {
41
+ problems.push(`${at} has no id`);
42
+ } else {
43
+ if (step.id.length > MAX_STEP_ID_LENGTH) {
44
+ problems.push(
45
+ `${at} id is longer than ${MAX_STEP_ID_LENGTH} characters`
46
+ );
47
+ }
48
+ if (seen.has(step.id)) problems.push(`duplicate step id "${step.id}"`);
49
+ seen.add(step.id);
50
+ }
51
+ if (!STEP_KINDS.includes(step.kind)) {
52
+ problems.push(`${at} has an unknown kind "${String(step.kind)}"`);
53
+ }
54
+ if (!step.label) problems.push(`${at} has no label`);
55
+ if (!step.fallbackText) problems.push(`${at} has no fallbackText`);
56
+ if (step.spotlight && !step.spotlight.selector) {
57
+ problems.push(`${at} has a spotlight with no selector`);
58
+ }
59
+ });
60
+ return problems;
61
+ }
62
+ function createTourStore() {
63
+ const tours = /* @__PURE__ */ new Map();
64
+ let session = null;
65
+ let state = { active: null, session: null };
66
+ const listeners = /* @__PURE__ */ new Set();
67
+ const recompute = () => {
68
+ const last = [...tours.values()].pop() ?? null;
69
+ if (state.active && last?.id !== state.active.id) session = null;
70
+ if (last !== state.active || session !== state.session) {
71
+ state = { active: last, session };
72
+ }
73
+ listeners.forEach((l) => l());
74
+ };
75
+ return {
76
+ register(def) {
77
+ const problems = validateTourDefinition(def);
78
+ if (problems.length > 0) {
79
+ throw new InvalidTourDefinitionError(def?.id ?? "(no id)", problems);
80
+ }
81
+ tours.delete(def.id);
82
+ tours.set(def.id, def);
83
+ recompute();
84
+ return () => {
85
+ if (tours.get(def.id) === def) {
86
+ tours.delete(def.id);
87
+ recompute();
88
+ }
89
+ };
90
+ },
91
+ open(next = { restart: true }) {
92
+ if (!state.active) return;
93
+ session = next;
94
+ recompute();
95
+ },
96
+ close() {
97
+ if (session === null) return;
98
+ session = null;
99
+ recompute();
100
+ },
101
+ getState: () => state,
102
+ subscribe(listener) {
103
+ listeners.add(listener);
104
+ return () => {
105
+ listeners.delete(listener);
106
+ };
107
+ }
108
+ };
109
+ }
110
+ var defaultTourStore = createTourStore();
111
+
112
+ // src/tour/tourProgress.ts
113
+ var SERVICE_HUB_TOUR_ID = "service-hub";
114
+ var TourProgressError = class extends Error {
115
+ status;
116
+ constructor(message, status) {
117
+ super(message);
118
+ this.name = "TourProgressError";
119
+ this.status = status;
120
+ }
121
+ };
122
+ var UNSEEN = () => ({
123
+ status: "unseen",
124
+ lastStepId: null,
125
+ updatedAt: (/* @__PURE__ */ new Date(0)).toISOString()
126
+ });
127
+ function unwrapTrpc(body) {
128
+ const data = body?.result?.data;
129
+ if (data === void 0 || data.json === void 0) {
130
+ throw new TourProgressError("Unexpected response from Portal");
131
+ }
132
+ return data.json;
133
+ }
134
+ var STATUSES = [
135
+ "unseen",
136
+ "in-progress",
137
+ "done",
138
+ "dismissed"
139
+ ];
140
+ function createPortalTourProgressTransport(opts = {}) {
141
+ const doFetch = opts.fetchImpl ?? ((input, init) => fetch(input, init));
142
+ const base = () => (opts.baseUrl ?? portalUrl("")).replace(/\/$/, "");
143
+ let perTourSupported;
144
+ const read = async (tourId) => {
145
+ const input = encodeURIComponent(JSON.stringify({ json: { tourId } }));
146
+ const res = await doFetch(
147
+ `${base()}/api/trpc/onboarding.userTourState?input=${input}`,
148
+ { method: "GET", credentials: "include" }
149
+ );
150
+ if (!res.ok) {
151
+ throw new TourProgressError(
152
+ `Couldn't read tour progress (${res.status})`,
153
+ res.status
154
+ );
155
+ }
156
+ const json = unwrapTrpc(await res.json());
157
+ perTourSupported = json.tourId === tourId;
158
+ if (tourId !== SERVICE_HUB_TOUR_ID && !perTourSupported) {
159
+ throw new TourProgressError(
160
+ "Portal does not store per-tour progress yet"
161
+ );
162
+ }
163
+ return {
164
+ status: STATUSES.includes(json.status) ? json.status : "unseen",
165
+ lastStepId: json.lastStepId ?? null,
166
+ updatedAt: json.updatedAt ?? UNSEEN().updatedAt
167
+ };
168
+ };
169
+ return {
170
+ read,
171
+ async write(tourId, update) {
172
+ if (tourId !== SERVICE_HUB_TOUR_ID) {
173
+ if (perTourSupported === void 0) await read(tourId);
174
+ if (!perTourSupported) return;
175
+ }
176
+ const res = await doFetch(
177
+ `${base()}/api/trpc/onboarding.setUserTourState`,
178
+ {
179
+ method: "POST",
180
+ credentials: "include",
181
+ headers: { "Content-Type": "application/json" },
182
+ body: JSON.stringify({ json: { tourId, ...update } })
183
+ }
184
+ );
185
+ if (!res.ok) {
186
+ throw new TourProgressError(
187
+ `Couldn't save tour progress (${res.status})`,
188
+ res.status
189
+ );
190
+ }
191
+ }
192
+ };
193
+ }
194
+ function createTourProgressController(transport, tourId) {
195
+ let snapshot = {
196
+ phase: "loading",
197
+ progress: UNSEEN(),
198
+ error: null
199
+ };
200
+ const listeners = /* @__PURE__ */ new Set();
201
+ let writeChain = Promise.resolve();
202
+ let recordedLocally = false;
203
+ const set = (next) => {
204
+ snapshot = next;
205
+ listeners.forEach((l) => l());
206
+ };
207
+ return {
208
+ getSnapshot: () => snapshot,
209
+ subscribe(listener) {
210
+ listeners.add(listener);
211
+ return () => {
212
+ listeners.delete(listener);
213
+ };
214
+ },
215
+ async load() {
216
+ try {
217
+ const progress = await transport.read(tourId);
218
+ if (recordedLocally) return;
219
+ set({ phase: "ready", progress, error: null });
220
+ } catch (err) {
221
+ if (recordedLocally) return;
222
+ set({
223
+ phase: "error",
224
+ progress: UNSEEN(),
225
+ error: err instanceof Error ? err : new Error(String(err))
226
+ });
227
+ }
228
+ },
229
+ record(update) {
230
+ recordedLocally = true;
231
+ set({
232
+ phase: snapshot.phase === "loading" ? "ready" : snapshot.phase,
233
+ progress: { ...update, updatedAt: (/* @__PURE__ */ new Date()).toISOString() },
234
+ error: snapshot.error
235
+ });
236
+ writeChain = writeChain.then(() => transport.write(tourId, update)).catch((err) => {
237
+ set({
238
+ ...snapshot,
239
+ error: err instanceof Error ? err : new Error(String(err))
240
+ });
241
+ });
242
+ return writeChain;
243
+ }
244
+ };
245
+ }
246
+ function shouldAutoOpen(status) {
247
+ return status === "unseen" || status === "in-progress";
248
+ }
249
+ function decideAutoOpen(autoStart, snapshot) {
250
+ return autoStart === true && snapshot.phase === "ready" && shouldAutoOpen(snapshot.progress.status);
251
+ }
252
+
253
+ // src/tour/tourNarration.ts
254
+ var ONBOARDING_NARRATION_SERVICE = "onboarding";
255
+ var NARRATION_PROMPT = "Narrate this onboarding step for me in 2-3 sentences.";
256
+ function buildNarrationInput(step) {
257
+ return {
258
+ service: ONBOARDING_NARRATION_SERVICE,
259
+ insights: {
260
+ hook: step.fallbackText,
261
+ highlights: step.highlights,
262
+ features: step.features
263
+ },
264
+ messages: [{ role: "user", content: NARRATION_PROMPT }]
265
+ };
266
+ }
267
+ function createPortalNarrator(opts = {}) {
268
+ const doFetch = opts.fetchImpl ?? ((input, init) => fetch(input, init));
269
+ return async (step) => {
270
+ const base = (opts.baseUrl ?? portalUrl("")).replace(/\/$/, "");
271
+ const res = await doFetch(`${base}/api/trpc/ai.askOpi`, {
272
+ method: "POST",
273
+ credentials: "include",
274
+ headers: { "Content-Type": "application/json" },
275
+ body: JSON.stringify({ json: buildNarrationInput(step) })
276
+ });
277
+ if (!res.ok) throw new Error(`Opi narration failed (${res.status})`);
278
+ const body = await res.json();
279
+ const content = body.result?.data?.json?.content;
280
+ if (typeof content !== "string" || content.trim() === "") {
281
+ throw new Error("Opi narration returned no text");
282
+ }
283
+ return content;
284
+ };
285
+ }
286
+
287
+ // src/tour/TourProvider.tsx
288
+ import {
289
+ createContext,
290
+ useContext,
291
+ useEffect,
292
+ useMemo,
293
+ useSyncExternalStore
294
+ } from "react";
295
+ import { jsx } from "react/jsx-runtime";
296
+ var defaultTransport;
297
+ var defaultNarrator;
298
+ var TourContext = createContext({});
299
+ function useTourContext() {
300
+ const ctx = useContext(TourContext);
301
+ return {
302
+ store: ctx.store ?? defaultTourStore,
303
+ // The default transport is shared app-wide: it remembers whether Portal
304
+ // supports per-tour storage after the first read.
305
+ transport: ctx.transport ?? (defaultTransport ??= createPortalTourProgressTransport()),
306
+ narrator: ctx.narrator ?? (defaultNarrator ??= createPortalNarrator())
307
+ };
308
+ }
309
+ function TourProvider({
310
+ store,
311
+ transport,
312
+ narrator,
313
+ children
314
+ }) {
315
+ const value = useMemo(
316
+ () => ({ store, transport, narrator }),
317
+ [store, transport, narrator]
318
+ );
319
+ return /* @__PURE__ */ jsx(TourContext.Provider, { value, children });
320
+ }
321
+ function useRegisterTour(def) {
322
+ const { store } = useTourContext();
323
+ useEffect(() => {
324
+ if (!def) return;
325
+ try {
326
+ return store.register(def);
327
+ } catch (err) {
328
+ if (err instanceof InvalidTourDefinitionError) {
329
+ console.error(err.message);
330
+ return;
331
+ }
332
+ throw err;
333
+ }
334
+ }, [store, def]);
335
+ }
336
+ function useTourState() {
337
+ const { store } = useTourContext();
338
+ return useSyncExternalStore(store.subscribe, store.getState, store.getState);
339
+ }
340
+ function useActiveTour() {
341
+ return useTourState().active;
342
+ }
343
+ function useTourLauncher() {
344
+ const { store } = useTourContext();
345
+ const available = useTourState().active !== null;
346
+ return {
347
+ start: () => store.open({ restart: true }),
348
+ open: (session) => store.open(session),
349
+ close: () => store.close(),
350
+ available
351
+ };
352
+ }
353
+ function useTourProgress(tourId) {
354
+ const { transport } = useTourContext();
355
+ const controller = useMemo(
356
+ () => createTourProgressController(transport, tourId),
357
+ [transport, tourId]
358
+ );
359
+ useEffect(() => {
360
+ void controller.load();
361
+ }, [controller]);
362
+ const snapshot = useSyncExternalStore(
363
+ controller.subscribe,
364
+ controller.getSnapshot,
365
+ controller.getSnapshot
366
+ );
367
+ return { ...snapshot, record: controller.record };
368
+ }
369
+ function useTourNarrator() {
370
+ return useTourContext().narrator;
371
+ }
372
+
373
+ // src/tour/TakeTheTourButton.tsx
374
+ import { Sparkles } from "lucide-react";
375
+ import { jsx as jsx2, jsxs } from "react/jsx-runtime";
376
+ function TakeTheTourButton({
377
+ label = "Take the tour",
378
+ className
379
+ }) {
380
+ const { available, start } = useTourLauncher();
381
+ if (!available) return null;
382
+ return /* @__PURE__ */ jsxs(
383
+ "button",
384
+ {
385
+ type: "button",
386
+ onClick: start,
387
+ title: label,
388
+ "aria-label": label,
389
+ className: cn(
390
+ "flex items-center gap-1 px-2 py-1 rounded-md text-[10px]",
391
+ "text-[#8890A0] hover:text-[#E2E8F0] hover:bg-[#1E2738] transition-colors cursor-pointer",
392
+ "focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-[#8C34E9]",
393
+ className
394
+ ),
395
+ children: [
396
+ /* @__PURE__ */ jsx2(Sparkles, { className: "h-3 w-3 text-[#8C34E9]" }),
397
+ /* @__PURE__ */ jsx2("span", { className: "shell-hidden shell-sm:inline", children: label })
398
+ ]
399
+ }
400
+ );
401
+ }
402
+
403
+ // src/tour/useSpotlight.ts
404
+ import { useEffect as useEffect2, useRef, useState } from "react";
405
+ var RESIZE_DEBOUNCE_MS = 100;
406
+ function useSpotlight(selector) {
407
+ const [rect, setRect] = useState(null);
408
+ const [found, setFound] = useState(false);
409
+ const scrolledForSelector = useRef(null);
410
+ useEffect2(() => {
411
+ if (!selector) {
412
+ setRect(null);
413
+ setFound(false);
414
+ return;
415
+ }
416
+ let resizeTimer;
417
+ let cancelled = false;
418
+ const measure = () => {
419
+ if (cancelled) return;
420
+ const el = document.querySelector(
421
+ `[data-tour-target="${selector}"]`
422
+ );
423
+ if (!el) {
424
+ setRect(null);
425
+ setFound(false);
426
+ return;
427
+ }
428
+ const domRect = el.getBoundingClientRect();
429
+ setRect({
430
+ top: domRect.top,
431
+ left: domRect.left,
432
+ width: domRect.width,
433
+ height: domRect.height
434
+ });
435
+ setFound(true);
436
+ if (scrolledForSelector.current !== selector) {
437
+ scrolledForSelector.current = selector;
438
+ el.scrollIntoView({ block: "center", behavior: "smooth" });
439
+ }
440
+ };
441
+ measure();
442
+ const initialFrame = requestAnimationFrame(measure);
443
+ const onResize = () => {
444
+ if (resizeTimer) clearTimeout(resizeTimer);
445
+ resizeTimer = setTimeout(measure, RESIZE_DEBOUNCE_MS);
446
+ };
447
+ const onScroll = () => measure();
448
+ window.addEventListener("resize", onResize);
449
+ window.addEventListener("scroll", onScroll, { capture: true });
450
+ const observer = new MutationObserver(measure);
451
+ observer.observe(document.body, {
452
+ childList: true,
453
+ subtree: true,
454
+ attributes: true
455
+ });
456
+ return () => {
457
+ cancelled = true;
458
+ cancelAnimationFrame(initialFrame);
459
+ if (resizeTimer) clearTimeout(resizeTimer);
460
+ window.removeEventListener("resize", onResize);
461
+ window.removeEventListener("scroll", onScroll, { capture: true });
462
+ observer?.disconnect();
463
+ };
464
+ }, [selector]);
465
+ return { rect, found };
466
+ }
467
+
468
+ // src/tour/spotlightMath.ts
469
+ function computeSpotlightFrame(target, viewport) {
470
+ const targetBottom = target.top + target.height;
471
+ const targetRight = target.left + target.width;
472
+ return {
473
+ // Full-width strip above the target.
474
+ top: {
475
+ top: 0,
476
+ left: 0,
477
+ width: viewport.width,
478
+ height: Math.max(0, target.top)
479
+ },
480
+ // Full-width strip below the target.
481
+ bottom: {
482
+ top: targetBottom,
483
+ left: 0,
484
+ width: viewport.width,
485
+ height: Math.max(0, viewport.height - targetBottom)
486
+ },
487
+ // Strip to the left of the target, spanning only the target's own row
488
+ // (the top/bottom strips already cover the rest of those rows).
489
+ left: {
490
+ top: target.top,
491
+ left: 0,
492
+ width: Math.max(0, target.left),
493
+ height: target.height
494
+ },
495
+ // Strip to the right of the target, same row-only span as `left`.
496
+ right: {
497
+ top: target.top,
498
+ left: targetRight,
499
+ width: Math.max(0, viewport.width - targetRight),
500
+ height: target.height
501
+ }
502
+ };
503
+ }
504
+ var FALLBACK_ORDER = {
505
+ bottom: ["bottom", "top", "right", "left"],
506
+ top: ["top", "bottom", "right", "left"],
507
+ right: ["right", "left", "bottom", "top"],
508
+ left: ["left", "right", "bottom", "top"]
509
+ };
510
+ var AUTO_ORDER = FALLBACK_ORDER.bottom;
511
+ var PANEL_GAP = 12;
512
+ function computePanelPosition(target, panelSize, viewport, placement = "auto") {
513
+ const order = placement === "auto" ? AUTO_ORDER : FALLBACK_ORDER[placement];
514
+ for (const candidate of order) {
515
+ const pos2 = placeAt(candidate, target, panelSize);
516
+ if (fits(pos2, panelSize, viewport)) {
517
+ return { ...pos2, placement: candidate };
518
+ }
519
+ }
520
+ const fallback = order[0];
521
+ const pos = placeAt(fallback, target, panelSize);
522
+ return {
523
+ top: clamp(pos.top, 0, Math.max(0, viewport.height - panelSize.height)),
524
+ left: clamp(pos.left, 0, Math.max(0, viewport.width - panelSize.width)),
525
+ placement: fallback
526
+ };
527
+ }
528
+ function placeAt(side, target, panelSize) {
529
+ const targetCenterX = target.left + target.width / 2;
530
+ const targetCenterY = target.top + target.height / 2;
531
+ switch (side) {
532
+ case "bottom":
533
+ return {
534
+ top: target.top + target.height + PANEL_GAP,
535
+ left: targetCenterX - panelSize.width / 2
536
+ };
537
+ case "top":
538
+ return {
539
+ top: target.top - panelSize.height - PANEL_GAP,
540
+ left: targetCenterX - panelSize.width / 2
541
+ };
542
+ case "right":
543
+ return {
544
+ top: targetCenterY - panelSize.height / 2,
545
+ left: target.left + target.width + PANEL_GAP
546
+ };
547
+ case "left":
548
+ return {
549
+ top: targetCenterY - panelSize.height / 2,
550
+ left: target.left - panelSize.width - PANEL_GAP
551
+ };
552
+ }
553
+ }
554
+ function fits(pos, panelSize, viewport) {
555
+ return pos.top >= 0 && pos.left >= 0 && pos.top + panelSize.height <= viewport.height && pos.left + panelSize.width <= viewport.width;
556
+ }
557
+ function clamp(value, min, max) {
558
+ return Math.min(Math.max(value, min), max);
559
+ }
560
+
561
+ // src/tour/TourShell.tsx
562
+ import { useEffect as useEffect3, useRef as useRef2 } from "react";
563
+ import {
564
+ X,
565
+ ChevronLeft,
566
+ ChevronRight,
567
+ ArrowRight,
568
+ ExternalLink
569
+ } from "lucide-react";
570
+ import { Fragment, jsx as jsx3, jsxs as jsxs2 } from "react/jsx-runtime";
571
+ var defaultSkin = {
572
+ accent: "#8C34E9",
573
+ overlayBg: "rgba(10,14,26,0.72)",
574
+ panelBg: "#0e1624",
575
+ panelBorder: "1px solid #1e2738",
576
+ mutedText: "#596475",
577
+ bodyText: "#c0c6d0",
578
+ softText: "#8890a0"
579
+ };
580
+ var SPOTLIGHT_PANEL_SIZE = { width: 320, height: 280 };
581
+ function TourShell({
582
+ step,
583
+ index,
584
+ total,
585
+ isFirst,
586
+ isLast,
587
+ onNext,
588
+ onBack,
589
+ onDismiss,
590
+ narration,
591
+ narrationPending,
592
+ children,
593
+ skin = defaultSkin,
594
+ orb,
595
+ onSpotlightTargetActivated
596
+ }) {
597
+ const panelRef = useRef2(null);
598
+ const { rect, found } = useSpotlight(step.spotlight?.selector ?? null);
599
+ const isSpotlight = Boolean(step.spotlight) && found && rect !== null;
600
+ useEffect3(() => {
601
+ const onKeyDown = (e) => {
602
+ if (e.key === "Escape") onDismiss();
603
+ };
604
+ document.addEventListener("keydown", onKeyDown);
605
+ return () => document.removeEventListener("keydown", onKeyDown);
606
+ }, [onDismiss]);
607
+ useEffect3(() => {
608
+ panelRef.current?.focus();
609
+ }, [step.id]);
610
+ useEffect3(() => {
611
+ if (!isSpotlight || !onSpotlightTargetActivated || !step.spotlight) return;
612
+ const selector = step.spotlight.selector;
613
+ const onClickCapture = (e) => {
614
+ const target = e.target;
615
+ if (target?.closest(`[data-tour-target="${selector}"]`)) {
616
+ onSpotlightTargetActivated();
617
+ }
618
+ };
619
+ document.addEventListener("click", onClickCapture, { capture: true });
620
+ return () => document.removeEventListener("click", onClickCapture, {
621
+ capture: true
622
+ });
623
+ }, [isSpotlight, onSpotlightTargetActivated, step.spotlight]);
624
+ if (isSpotlight && rect) {
625
+ const viewport = { width: window.innerWidth, height: window.innerHeight };
626
+ const frame = computeSpotlightFrame(rect, viewport);
627
+ const panelPos = computePanelPosition(
628
+ rect,
629
+ SPOTLIGHT_PANEL_SIZE,
630
+ viewport,
631
+ step.spotlight?.placement ?? "auto"
632
+ );
633
+ return /* @__PURE__ */ jsxs2(Fragment, { children: [
634
+ ["top", "bottom", "left", "right"].map((side) => {
635
+ const segment = frame[side];
636
+ if (segment.width <= 0 || segment.height <= 0) return null;
637
+ return /* @__PURE__ */ jsx3(
638
+ "div",
639
+ {
640
+ className: "fixed z-50",
641
+ style: {
642
+ top: segment.top,
643
+ left: segment.left,
644
+ width: segment.width,
645
+ height: segment.height,
646
+ background: skin.overlayBg
647
+ },
648
+ onClick: onDismiss
649
+ },
650
+ side
651
+ );
652
+ }),
653
+ /* @__PURE__ */ jsx3(
654
+ "div",
655
+ {
656
+ className: "fixed z-50 rounded-xl pointer-events-none transition-all",
657
+ style: {
658
+ top: rect.top - 4,
659
+ left: rect.left - 4,
660
+ width: rect.width + 8,
661
+ height: rect.height + 8,
662
+ boxShadow: `0 0 0 2px ${skin.accent}, 0 0 24px 4px ${skin.accent}66`
663
+ }
664
+ }
665
+ ),
666
+ /* @__PURE__ */ jsxs2(
667
+ "div",
668
+ {
669
+ ref: panelRef,
670
+ tabIndex: -1,
671
+ role: "dialog",
672
+ "aria-modal": "true",
673
+ "aria-label": step.label,
674
+ className: "fixed z-50 rounded-xl overflow-hidden flex flex-col outline-none",
675
+ style: {
676
+ top: panelPos.top,
677
+ left: panelPos.left,
678
+ width: SPOTLIGHT_PANEL_SIZE.width,
679
+ maxHeight: SPOTLIGHT_PANEL_SIZE.height,
680
+ background: skin.panelBg,
681
+ border: skin.panelBorder
682
+ },
683
+ children: [
684
+ /* @__PURE__ */ jsx3(TourShellHeader, { step, orb, onDismiss }),
685
+ /* @__PURE__ */ jsx3(TourShellStepDots, { total, index, skin }),
686
+ /* @__PURE__ */ jsx3("div", { className: "overflow-y-auto px-4 py-3 space-y-3", children: /* @__PURE__ */ jsx3(
687
+ TourShellBody,
688
+ {
689
+ step,
690
+ narration,
691
+ narrationPending,
692
+ skin,
693
+ children
694
+ }
695
+ ) }),
696
+ /* @__PURE__ */ jsx3(
697
+ TourShellFooter,
698
+ {
699
+ isFirst,
700
+ isLast,
701
+ onNext,
702
+ onBack,
703
+ onDismiss,
704
+ skin
705
+ }
706
+ )
707
+ ]
708
+ }
709
+ )
710
+ ] });
711
+ }
712
+ return /* @__PURE__ */ jsx3(
713
+ "div",
714
+ {
715
+ className: "fixed inset-0 z-50 flex items-center justify-center p-4",
716
+ style: { background: skin.overlayBg },
717
+ onClick: (e) => {
718
+ if (e.target === e.currentTarget) onDismiss();
719
+ },
720
+ children: /* @__PURE__ */ jsxs2(
721
+ "div",
722
+ {
723
+ ref: panelRef,
724
+ tabIndex: -1,
725
+ role: "dialog",
726
+ "aria-modal": "true",
727
+ "aria-label": step.label,
728
+ className: "w-full max-w-md rounded-xl overflow-hidden flex flex-col max-h-[85vh] outline-none",
729
+ style: { background: skin.panelBg, border: skin.panelBorder },
730
+ children: [
731
+ /* @__PURE__ */ jsx3(TourShellHeader, { step, orb, onDismiss }),
732
+ /* @__PURE__ */ jsx3(TourShellStepDots, { total, index, skin }),
733
+ /* @__PURE__ */ jsx3("div", { className: "overflow-y-auto px-5 py-4 space-y-4", children: /* @__PURE__ */ jsx3(
734
+ TourShellBody,
735
+ {
736
+ step,
737
+ narration,
738
+ narrationPending,
739
+ skin,
740
+ children
741
+ }
742
+ ) }),
743
+ /* @__PURE__ */ jsx3(
744
+ TourShellFooter,
745
+ {
746
+ isFirst,
747
+ isLast,
748
+ onNext,
749
+ onBack,
750
+ onDismiss,
751
+ skin
752
+ }
753
+ )
754
+ ]
755
+ }
756
+ )
757
+ }
758
+ );
759
+ }
760
+ function TourShellHeader({
761
+ step,
762
+ orb,
763
+ onDismiss
764
+ }) {
765
+ return /* @__PURE__ */ jsxs2(
766
+ "div",
767
+ {
768
+ className: "flex items-center justify-between gap-3 px-5 py-4 shrink-0",
769
+ style: {
770
+ background: "linear-gradient(135deg, #2a1450 0%, #1a0e33 100%)"
771
+ },
772
+ children: [
773
+ /* @__PURE__ */ jsxs2("div", { className: "flex items-center gap-2.5 min-w-0", children: [
774
+ orb,
775
+ /* @__PURE__ */ jsx3("span", { className: "text-sm font-bold text-white truncate", children: step.label })
776
+ ] }),
777
+ /* @__PURE__ */ jsx3(
778
+ "button",
779
+ {
780
+ onClick: onDismiss,
781
+ className: "p-1 rounded hover:bg-white/10 transition-colors shrink-0",
782
+ title: "Skip tour",
783
+ children: /* @__PURE__ */ jsx3(X, { size: 16, className: "text-white/70" })
784
+ }
785
+ )
786
+ ]
787
+ }
788
+ );
789
+ }
790
+ function TourShellStepDots({
791
+ total,
792
+ index,
793
+ skin
794
+ }) {
795
+ return /* @__PURE__ */ jsx3(
796
+ "div",
797
+ {
798
+ className: "flex items-center gap-1.5 px-5 py-3 shrink-0",
799
+ style: { borderBottom: skin.panelBorder },
800
+ children: Array.from({ length: total }, (_, i) => /* @__PURE__ */ jsx3(
801
+ "span",
802
+ {
803
+ className: "h-1.5 rounded-full transition-all",
804
+ style: {
805
+ width: i === index ? 20 : 8,
806
+ background: i === index ? skin.accent : skin.mutedText,
807
+ opacity: i === index ? 1 : 0.4
808
+ }
809
+ },
810
+ i
811
+ ))
812
+ }
813
+ );
814
+ }
815
+ function TourShellBody({
816
+ step,
817
+ narration,
818
+ narrationPending,
819
+ skin,
820
+ children
821
+ }) {
822
+ return /* @__PURE__ */ jsxs2(Fragment, { children: [
823
+ /* @__PURE__ */ jsx3(
824
+ "p",
825
+ {
826
+ className: "text-[13px] leading-relaxed transition-opacity",
827
+ style: {
828
+ color: skin.bodyText,
829
+ opacity: narrationPending ? 0.7 : 1
830
+ },
831
+ children: narration
832
+ }
833
+ ),
834
+ step.features && step.features.length > 0 ? /* @__PURE__ */ jsx3("ul", { className: "space-y-2", children: step.features.map((f, i) => /* @__PURE__ */ jsxs2("li", { className: "text-[12.5px] leading-relaxed", children: [
835
+ /* @__PURE__ */ jsx3("span", { className: "font-semibold", style: { color: skin.accent }, children: f.name }),
836
+ /* @__PURE__ */ jsxs2("span", { style: { color: skin.softText }, children: [
837
+ " \u2014 ",
838
+ f.detail
839
+ ] })
840
+ ] }, i)) }) : step.highlights && step.highlights.length > 0 && /* @__PURE__ */ jsx3("ul", { className: "space-y-1.5", children: step.highlights.map((h, i) => /* @__PURE__ */ jsxs2(
841
+ "li",
842
+ {
843
+ className: "text-[12.5px] leading-relaxed pl-3 relative",
844
+ style: { color: skin.softText },
845
+ children: [
846
+ /* @__PURE__ */ jsx3(
847
+ "span",
848
+ {
849
+ className: "absolute left-0",
850
+ style: { color: skin.mutedText },
851
+ children: "\u2022"
852
+ }
853
+ ),
854
+ h
855
+ ]
856
+ },
857
+ i
858
+ )) }),
859
+ step.action && /* @__PURE__ */ jsxs2(
860
+ "a",
861
+ {
862
+ href: step.action.href,
863
+ target: step.action.external ? "_blank" : void 0,
864
+ rel: step.action.external ? "noopener noreferrer" : void 0,
865
+ className: "inline-flex items-center gap-1.5 px-3.5 py-2 rounded-lg text-[13px] font-semibold transition-opacity hover:opacity-90",
866
+ style: { background: `${skin.accent}20`, color: skin.accent },
867
+ children: [
868
+ step.action.label,
869
+ step.action.external ? /* @__PURE__ */ jsx3(ExternalLink, { size: 13 }) : /* @__PURE__ */ jsx3(ArrowRight, { size: 13 })
870
+ ]
871
+ }
872
+ ),
873
+ children
874
+ ] });
875
+ }
876
+ function TourShellFooter({
877
+ isFirst,
878
+ isLast,
879
+ onNext,
880
+ onBack,
881
+ onDismiss,
882
+ skin
883
+ }) {
884
+ return /* @__PURE__ */ jsxs2(
885
+ "div",
886
+ {
887
+ className: "flex items-center justify-between gap-2 px-5 py-3.5 shrink-0",
888
+ style: { borderTop: skin.panelBorder },
889
+ children: [
890
+ /* @__PURE__ */ jsx3(
891
+ "button",
892
+ {
893
+ onClick: onDismiss,
894
+ className: "text-[12px] font-medium transition-colors hover:underline",
895
+ style: { color: skin.mutedText },
896
+ children: "Skip tour"
897
+ }
898
+ ),
899
+ /* @__PURE__ */ jsxs2("div", { className: "flex items-center gap-2", children: [
900
+ !isFirst && /* @__PURE__ */ jsxs2(
901
+ "button",
902
+ {
903
+ onClick: onBack,
904
+ className: "flex items-center gap-1 px-3 py-1.5 rounded-md text-[12.5px] font-medium transition-colors",
905
+ style: { color: skin.bodyText, border: skin.panelBorder },
906
+ children: [
907
+ /* @__PURE__ */ jsx3(ChevronLeft, { size: 13 }),
908
+ "Back"
909
+ ]
910
+ }
911
+ ),
912
+ /* @__PURE__ */ jsxs2(
913
+ "button",
914
+ {
915
+ onClick: onNext,
916
+ className: "flex items-center gap-1 px-3.5 py-1.5 rounded-md text-[12.5px] font-bold text-white transition-opacity hover:opacity-90",
917
+ style: {
918
+ background: "linear-gradient(135deg, #8C34E9 0%, #5B1FA6 100%)"
919
+ },
920
+ children: [
921
+ isLast ? "Done" : "Next",
922
+ !isLast && /* @__PURE__ */ jsx3(ChevronRight, { size: 13 })
923
+ ]
924
+ }
925
+ )
926
+ ] })
927
+ ]
928
+ }
929
+ );
930
+ }
931
+
932
+ // src/tour/useTour.ts
933
+ import { useCallback, useState as useState2 } from "react";
934
+
935
+ // src/tour/tourMachine.ts
936
+ function resolveInitialIndex(steps, initialStepId) {
937
+ if (!initialStepId) return 0;
938
+ const found = steps.findIndex((s) => s.id === initialStepId);
939
+ return found === -1 ? 0 : found;
940
+ }
941
+ function nextIndex(steps, current) {
942
+ if (current >= steps.length - 1) {
943
+ return { index: current, completed: true };
944
+ }
945
+ return { index: current + 1, completed: false };
946
+ }
947
+ function backIndex(current) {
948
+ return Math.max(0, current - 1);
949
+ }
950
+ function gotoIndex(steps, stepId, current) {
951
+ const target = steps.findIndex((s) => s.id === stepId);
952
+ return target === -1 ? current : target;
953
+ }
954
+
955
+ // src/tour/useTour.ts
956
+ function useTour(steps, opts = {}) {
957
+ if (steps.length === 0) {
958
+ throw new Error("useTour requires at least one step");
959
+ }
960
+ const [index, setIndex] = useState2(
961
+ () => resolveInitialIndex(steps, opts.initialStepId)
962
+ );
963
+ const next = useCallback(() => {
964
+ const result = nextIndex(steps, index);
965
+ if (result.completed) {
966
+ opts.onComplete?.();
967
+ return;
968
+ }
969
+ setIndex(result.index);
970
+ opts.onStepChange?.(steps[result.index], result.index);
971
+ }, [index, steps]);
972
+ const back = useCallback(() => {
973
+ const target = backIndex(index);
974
+ if (target === index) return;
975
+ setIndex(target);
976
+ opts.onStepChange?.(steps[target], target);
977
+ }, [index, steps]);
978
+ const goto = useCallback(
979
+ (stepId) => {
980
+ const target = gotoIndex(steps, stepId, index);
981
+ if (target === index) return;
982
+ setIndex(target);
983
+ opts.onStepChange?.(steps[target], target);
984
+ },
985
+ [steps, index]
986
+ );
987
+ const dismiss = useCallback(() => {
988
+ opts.onDismiss?.();
989
+ }, []);
990
+ return {
991
+ step: steps[index],
992
+ index,
993
+ total: steps.length,
994
+ isFirst: index === 0,
995
+ isLast: index === steps.length - 1,
996
+ next,
997
+ back,
998
+ goto,
999
+ dismiss
1000
+ };
1001
+ }
1002
+
1003
+ // src/tour/OpiTourHost.tsx
1004
+ import { useEffect as useEffect4, useRef as useRef3, useState as useState3 } from "react";
1005
+ import { Sparkles as Sparkles2 } from "lucide-react";
1006
+ import { jsx as jsx4 } from "react/jsx-runtime";
1007
+ function OpiTourHost(props) {
1008
+ const { active } = useTourState();
1009
+ if (!active) return null;
1010
+ return /* @__PURE__ */ jsx4(ActiveTourHost, { tour: active, ...props }, active.id);
1011
+ }
1012
+ function ActiveTourHost({
1013
+ tour,
1014
+ orb,
1015
+ skin
1016
+ }) {
1017
+ const { session } = useTourState();
1018
+ const { open } = useTourLauncher();
1019
+ const { phase, progress, record } = useTourProgress(tour.id);
1020
+ const decided = useRef3(false);
1021
+ useEffect4(() => {
1022
+ if (phase === "loading" || decided.current) return;
1023
+ decided.current = true;
1024
+ if (decideAutoOpen(tour.autoStart, { phase, progress })) {
1025
+ open({ restart: false });
1026
+ }
1027
+ }, [phase, progress, tour.autoStart, open]);
1028
+ if (!session || phase === "loading") return null;
1029
+ return /* @__PURE__ */ jsx4(
1030
+ TourRunner,
1031
+ {
1032
+ steps: tour.steps,
1033
+ initialStepId: session.restart ? null : progress.lastStepId,
1034
+ onProgress: record,
1035
+ orb: orb ?? /* @__PURE__ */ jsx4(DefaultOrb, {}),
1036
+ skin
1037
+ }
1038
+ );
1039
+ }
1040
+ function DefaultOrb() {
1041
+ return /* @__PURE__ */ jsx4(
1042
+ "span",
1043
+ {
1044
+ className: "flex h-9 w-9 shrink-0 items-center justify-center rounded-full",
1045
+ style: {
1046
+ background: "linear-gradient(135deg, #8C34E9 0%, #5B1FA6 100%)"
1047
+ },
1048
+ children: /* @__PURE__ */ jsx4(Sparkles2, { className: "h-4 w-4 text-white" })
1049
+ }
1050
+ );
1051
+ }
1052
+ function TourRunner({
1053
+ steps,
1054
+ initialStepId,
1055
+ onProgress,
1056
+ orb,
1057
+ skin
1058
+ }) {
1059
+ const { close } = useTourLauncher();
1060
+ const narrate = useTourNarrator();
1061
+ const [narrationByStep, setNarrationByStep] = useState3({});
1062
+ const [pendingStepId, setPendingStepId] = useState3(null);
1063
+ const requested = useRef3(/* @__PURE__ */ new Set());
1064
+ const currentStepId = useRef3(
1065
+ steps.find((s) => s.id === initialStepId)?.id ?? steps[0].id
1066
+ );
1067
+ const requestNarration = (step) => {
1068
+ if (requested.current.has(step.id)) return;
1069
+ requested.current.add(step.id);
1070
+ setPendingStepId(step.id);
1071
+ narrate(step).then((text) => setNarrationByStep((prev) => ({ ...prev, [step.id]: text }))).catch(() => {
1072
+ }).finally(() => setPendingStepId((cur) => cur === step.id ? null : cur));
1073
+ };
1074
+ const tour = useTour(steps, {
1075
+ initialStepId,
1076
+ onStepChange: (step) => {
1077
+ currentStepId.current = step.id;
1078
+ void onProgress({ status: "in-progress", lastStepId: step.id });
1079
+ requestNarration(step);
1080
+ },
1081
+ onComplete: () => {
1082
+ void onProgress({ status: "done", lastStepId: null });
1083
+ close();
1084
+ },
1085
+ onDismiss: () => {
1086
+ void onProgress({
1087
+ status: "dismissed",
1088
+ lastStepId: currentStepId.current
1089
+ });
1090
+ close();
1091
+ }
1092
+ });
1093
+ useEffect4(() => {
1094
+ requestNarration(tour.step);
1095
+ }, []);
1096
+ return /* @__PURE__ */ jsx4(
1097
+ TourShell,
1098
+ {
1099
+ step: tour.step,
1100
+ index: tour.index,
1101
+ total: tour.total,
1102
+ isFirst: tour.isFirst,
1103
+ isLast: tour.isLast,
1104
+ onNext: tour.next,
1105
+ onBack: tour.back,
1106
+ onDismiss: tour.dismiss,
1107
+ narration: narrationByStep[tour.step.id] ?? tour.step.fallbackText,
1108
+ narrationPending: pendingStepId === tour.step.id,
1109
+ orb,
1110
+ skin
1111
+ }
1112
+ );
1113
+ }
1114
+
1115
+ export {
1116
+ InvalidTourDefinitionError,
1117
+ validateTourDefinition,
1118
+ createTourStore,
1119
+ defaultTourStore,
1120
+ SERVICE_HUB_TOUR_ID,
1121
+ TourProgressError,
1122
+ createPortalTourProgressTransport,
1123
+ createTourProgressController,
1124
+ shouldAutoOpen,
1125
+ decideAutoOpen,
1126
+ ONBOARDING_NARRATION_SERVICE,
1127
+ NARRATION_PROMPT,
1128
+ buildNarrationInput,
1129
+ createPortalNarrator,
1130
+ TourProvider,
1131
+ useRegisterTour,
1132
+ useTourState,
1133
+ useActiveTour,
1134
+ useTourLauncher,
1135
+ useTourProgress,
1136
+ useTourNarrator,
1137
+ TakeTheTourButton,
1138
+ useSpotlight,
1139
+ computeSpotlightFrame,
1140
+ computePanelPosition,
1141
+ TourShell,
1142
+ useTour,
1143
+ OpiTourHost
1144
+ };
1145
+ //# sourceMappingURL=chunk-T3W42HMO.js.map