@open-slide/core 0.0.8 → 0.0.9

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.
Files changed (30) hide show
  1. package/dist/{build-CXY2DSzy.js → build-pqF4W1Yi.js} +1 -1
  2. package/dist/cli/bin.js +3 -3
  3. package/dist/{config-BYTf0qVz.js → config-CtwxMYv9.js} +365 -44
  4. package/dist/{dev-BxCKugi3.js → dev-CJX97uiy.js} +1 -1
  5. package/dist/{preview-C1F-rHfx.js → preview-IuLPcL5y.js} +1 -1
  6. package/dist/vite/index.js +1 -1
  7. package/package.json +3 -1
  8. package/src/app/App.tsx +2 -0
  9. package/src/app/components/PdfProgressToast.tsx +23 -0
  10. package/src/app/components/inspector/CommentWidget.tsx +1 -1
  11. package/src/app/components/inspector/InspectOverlay.tsx +81 -41
  12. package/src/app/components/inspector/InspectorPanel.tsx +805 -0
  13. package/src/app/components/inspector/InspectorProvider.tsx +199 -13
  14. package/src/app/components/inspector/SaveBar.tsx +77 -0
  15. package/src/app/components/ui/input.tsx +21 -0
  16. package/src/app/components/ui/label.tsx +24 -0
  17. package/src/app/components/ui/progress.tsx +31 -0
  18. package/src/app/components/ui/select.tsx +190 -0
  19. package/src/app/components/ui/slider.tsx +61 -0
  20. package/src/app/components/ui/sonner.tsx +38 -0
  21. package/src/app/components/ui/textarea.tsx +18 -0
  22. package/src/app/components/ui/toggle-group.tsx +83 -0
  23. package/src/app/components/ui/toggle.tsx +45 -0
  24. package/src/app/components/ui/tooltip.tsx +55 -0
  25. package/src/app/lib/export-pdf.ts +197 -0
  26. package/src/app/lib/inspector/fiber.ts +40 -5
  27. package/src/app/lib/inspector/useEditor.ts +61 -0
  28. package/src/app/lib/print-ready.ts +58 -0
  29. package/src/app/routes/Slide.tsx +47 -3
  30. package/src/app/components/inspector/CommentPopover.tsx +0 -94
@@ -0,0 +1,18 @@
1
+ import * as React from "react"
2
+
3
+ import { cn } from "@/lib/utils"
4
+
5
+ function Textarea({ className, ...props }: React.ComponentProps<"textarea">) {
6
+ return (
7
+ <textarea
8
+ data-slot="textarea"
9
+ className={cn(
10
+ "flex field-sizing-content min-h-16 w-full rounded-md border border-input bg-transparent px-3 py-2 text-base shadow-xs transition-[color,box-shadow] outline-none placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 md:text-sm dark:bg-input/30 dark:aria-invalid:ring-destructive/40",
11
+ className
12
+ )}
13
+ {...props}
14
+ />
15
+ )
16
+ }
17
+
18
+ export { Textarea }
@@ -0,0 +1,83 @@
1
+ "use client"
2
+
3
+ import * as React from "react"
4
+ import { type VariantProps } from "class-variance-authority"
5
+ import { ToggleGroup as ToggleGroupPrimitive } from "radix-ui"
6
+
7
+ import { cn } from "@/lib/utils"
8
+ import { toggleVariants } from "@/components/ui/toggle"
9
+
10
+ const ToggleGroupContext = React.createContext<
11
+ VariantProps<typeof toggleVariants> & {
12
+ spacing?: number
13
+ }
14
+ >({
15
+ size: "default",
16
+ variant: "default",
17
+ spacing: 0,
18
+ })
19
+
20
+ function ToggleGroup({
21
+ className,
22
+ variant,
23
+ size,
24
+ spacing = 0,
25
+ children,
26
+ ...props
27
+ }: React.ComponentProps<typeof ToggleGroupPrimitive.Root> &
28
+ VariantProps<typeof toggleVariants> & {
29
+ spacing?: number
30
+ }) {
31
+ return (
32
+ <ToggleGroupPrimitive.Root
33
+ data-slot="toggle-group"
34
+ data-variant={variant}
35
+ data-size={size}
36
+ data-spacing={spacing}
37
+ style={{ "--gap": spacing } as React.CSSProperties}
38
+ className={cn(
39
+ "group/toggle-group flex w-fit items-center gap-[--spacing(var(--gap))] rounded-md data-[spacing=default]:data-[variant=outline]:shadow-xs",
40
+ className
41
+ )}
42
+ {...props}
43
+ >
44
+ <ToggleGroupContext.Provider value={{ variant, size, spacing }}>
45
+ {children}
46
+ </ToggleGroupContext.Provider>
47
+ </ToggleGroupPrimitive.Root>
48
+ )
49
+ }
50
+
51
+ function ToggleGroupItem({
52
+ className,
53
+ children,
54
+ variant,
55
+ size,
56
+ ...props
57
+ }: React.ComponentProps<typeof ToggleGroupPrimitive.Item> &
58
+ VariantProps<typeof toggleVariants>) {
59
+ const context = React.useContext(ToggleGroupContext)
60
+
61
+ return (
62
+ <ToggleGroupPrimitive.Item
63
+ data-slot="toggle-group-item"
64
+ data-variant={context.variant || variant}
65
+ data-size={context.size || size}
66
+ data-spacing={context.spacing}
67
+ className={cn(
68
+ toggleVariants({
69
+ variant: context.variant || variant,
70
+ size: context.size || size,
71
+ }),
72
+ "w-auto min-w-0 shrink-0 px-3 focus:z-10 focus-visible:z-10",
73
+ "data-[spacing=0]:rounded-none data-[spacing=0]:shadow-none data-[spacing=0]:first:rounded-l-md data-[spacing=0]:last:rounded-r-md data-[spacing=0]:data-[variant=outline]:border-l-0 data-[spacing=0]:data-[variant=outline]:first:border-l",
74
+ className
75
+ )}
76
+ {...props}
77
+ >
78
+ {children}
79
+ </ToggleGroupPrimitive.Item>
80
+ )
81
+ }
82
+
83
+ export { ToggleGroup, ToggleGroupItem }
@@ -0,0 +1,45 @@
1
+ import * as React from "react"
2
+ import { cva, type VariantProps } from "class-variance-authority"
3
+ import { Toggle as TogglePrimitive } from "radix-ui"
4
+
5
+ import { cn } from "@/lib/utils"
6
+
7
+ const toggleVariants = cva(
8
+ "inline-flex items-center justify-center gap-2 rounded-md text-sm font-medium whitespace-nowrap transition-[color,box-shadow] outline-none hover:bg-muted hover:text-muted-foreground focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 data-[state=on]:bg-accent data-[state=on]:text-accent-foreground dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
9
+ {
10
+ variants: {
11
+ variant: {
12
+ default: "bg-transparent",
13
+ outline:
14
+ "border border-input bg-transparent shadow-xs hover:bg-accent hover:text-accent-foreground",
15
+ },
16
+ size: {
17
+ default: "h-9 min-w-9 px-2",
18
+ sm: "h-8 min-w-8 px-1.5",
19
+ lg: "h-10 min-w-10 px-2.5",
20
+ },
21
+ },
22
+ defaultVariants: {
23
+ variant: "default",
24
+ size: "default",
25
+ },
26
+ }
27
+ )
28
+
29
+ function Toggle({
30
+ className,
31
+ variant,
32
+ size,
33
+ ...props
34
+ }: React.ComponentProps<typeof TogglePrimitive.Root> &
35
+ VariantProps<typeof toggleVariants>) {
36
+ return (
37
+ <TogglePrimitive.Root
38
+ data-slot="toggle"
39
+ className={cn(toggleVariants({ variant, size, className }))}
40
+ {...props}
41
+ />
42
+ )
43
+ }
44
+
45
+ export { Toggle, toggleVariants }
@@ -0,0 +1,55 @@
1
+ import * as React from "react"
2
+ import { Tooltip as TooltipPrimitive } from "radix-ui"
3
+
4
+ import { cn } from "@/lib/utils"
5
+
6
+ function TooltipProvider({
7
+ delayDuration = 0,
8
+ ...props
9
+ }: React.ComponentProps<typeof TooltipPrimitive.Provider>) {
10
+ return (
11
+ <TooltipPrimitive.Provider
12
+ data-slot="tooltip-provider"
13
+ delayDuration={delayDuration}
14
+ {...props}
15
+ />
16
+ )
17
+ }
18
+
19
+ function Tooltip({
20
+ ...props
21
+ }: React.ComponentProps<typeof TooltipPrimitive.Root>) {
22
+ return <TooltipPrimitive.Root data-slot="tooltip" {...props} />
23
+ }
24
+
25
+ function TooltipTrigger({
26
+ ...props
27
+ }: React.ComponentProps<typeof TooltipPrimitive.Trigger>) {
28
+ return <TooltipPrimitive.Trigger data-slot="tooltip-trigger" {...props} />
29
+ }
30
+
31
+ function TooltipContent({
32
+ className,
33
+ sideOffset = 0,
34
+ children,
35
+ ...props
36
+ }: React.ComponentProps<typeof TooltipPrimitive.Content>) {
37
+ return (
38
+ <TooltipPrimitive.Portal>
39
+ <TooltipPrimitive.Content
40
+ data-slot="tooltip-content"
41
+ sideOffset={sideOffset}
42
+ className={cn(
43
+ "z-50 w-fit origin-(--radix-tooltip-content-transform-origin) animate-in rounded-md bg-foreground px-3 py-1.5 text-xs text-balance text-background fade-in-0 zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95",
44
+ className
45
+ )}
46
+ {...props}
47
+ >
48
+ {children}
49
+ <TooltipPrimitive.Arrow className="z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px] bg-foreground fill-foreground" />
50
+ </TooltipPrimitive.Content>
51
+ </TooltipPrimitive.Portal>
52
+ )
53
+ }
54
+
55
+ export { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider }
@@ -0,0 +1,197 @@
1
+ // Exports a slide as a PDF via the browser's native print engine.
2
+ // Each page in `slide.default` becomes one PDF page at 1920×1080.
3
+ // Text stays selectable and inline SVG remains vector — `window.print()`
4
+ // preserves both. The user picks "Save as PDF" in the print dialog.
5
+
6
+ import { createElement } from 'react';
7
+ import { createRoot, type Root } from 'react-dom/client';
8
+ import { isFrameAnimationSettled, waitForDataWaitfor, waitForFonts } from './print-ready';
9
+ import type { SlideModule } from './sdk';
10
+
11
+ const PRINT_ROOT_ID = 'os-print-root';
12
+ const PRINT_STYLE_ID = 'os-print-style';
13
+
14
+ const PRINT_STYLES = `
15
+ @page { size: 1920px 1080px; margin: 0; }
16
+
17
+ @media screen {
18
+ #${PRINT_ROOT_ID} {
19
+ position: fixed !important;
20
+ left: -99999px !important;
21
+ top: 0 !important;
22
+ pointer-events: none !important;
23
+ }
24
+ }
25
+
26
+ @media print {
27
+ html, body {
28
+ margin: 0 !important;
29
+ padding: 0 !important;
30
+ background: #fff !important;
31
+ }
32
+ body > *:not(#${PRINT_ROOT_ID}) { display: none !important; }
33
+ #${PRINT_ROOT_ID} {
34
+ position: static !important;
35
+ left: 0 !important;
36
+ top: 0 !important;
37
+ pointer-events: auto !important;
38
+ display: block !important;
39
+ background: #fff !important;
40
+ }
41
+ #${PRINT_ROOT_ID} .os-print-frame {
42
+ width: 1920px !important;
43
+ height: 1080px !important;
44
+ background: #fff;
45
+ color: #000;
46
+ overflow: hidden;
47
+ page-break-after: always;
48
+ break-after: page;
49
+ -webkit-print-color-adjust: exact;
50
+ print-color-adjust: exact;
51
+ }
52
+ #${PRINT_ROOT_ID} .os-print-frame:last-child {
53
+ page-break-after: auto;
54
+ break-after: auto;
55
+ }
56
+ /* Supersample: Chrome rasterizes filtered/composited layers (e.g. filter:
57
+ blur, mix-blend-mode) at the layer's CSS-pixel size, so a blurred
58
+ gradient on a 1920×1080 page bakes in at ~1× DPI and bands when the PDF
59
+ is viewed scaled up. zoom:2 doubles the layer raster size; scale(0.5)
60
+ composites it back to 1920×1080. Vector content (text, plain CSS
61
+ gradients, SVG) stays vector through both transforms. */
62
+ #${PRINT_ROOT_ID} .os-print-supersample {
63
+ width: 1920px !important;
64
+ height: 1080px !important;
65
+ zoom: 2;
66
+ transform: scale(0.5);
67
+ transform-origin: top left;
68
+ }
69
+ }
70
+ `;
71
+
72
+ export type PdfExportProgress = {
73
+ phase: 'processing' | 'printing' | 'done';
74
+ /** Number of pages whose intro animations have finished (0..total). */
75
+ current: number;
76
+ total: number;
77
+ /** 0–99 while processing, 99 during printing, 100 when done. */
78
+ percent: number;
79
+ };
80
+
81
+ const ANIMATION_TIMEOUT_MS = 15_000;
82
+ const POLL_INTERVAL_MS = 100;
83
+
84
+ export async function exportSlideAsPdf(
85
+ slide: SlideModule,
86
+ slideId: string,
87
+ onProgress?: (progress: PdfExportProgress) => void,
88
+ ): Promise<void> {
89
+ const pages = slide.default ?? [];
90
+ if (pages.length === 0) return;
91
+
92
+ const total = pages.length;
93
+
94
+ const style = document.createElement('style');
95
+ style.id = PRINT_STYLE_ID;
96
+ style.textContent = PRINT_STYLES;
97
+ document.head.appendChild(style);
98
+
99
+ const root = document.createElement('div');
100
+ root.id = PRINT_ROOT_ID;
101
+ root.setAttribute('aria-hidden', 'true');
102
+ document.body.appendChild(root);
103
+
104
+ onProgress?.({ phase: 'processing', current: 0, total, percent: 0 });
105
+
106
+ const reactRoots: Root[] = [];
107
+ const frames: HTMLElement[] = [];
108
+ for (const Page of pages) {
109
+ const host = document.createElement('div');
110
+ host.className = 'os-print-frame';
111
+ host.style.width = '1920px';
112
+ host.style.height = '1080px';
113
+ const inner = document.createElement('div');
114
+ inner.className = 'os-print-supersample';
115
+ inner.style.width = '1920px';
116
+ inner.style.height = '1080px';
117
+ host.appendChild(inner);
118
+ root.appendChild(host);
119
+ frames.push(host);
120
+ const r = createRoot(inner);
121
+ r.render(createElement(Page));
122
+ reactRoots.push(r);
123
+ }
124
+ // Yield once so React commits all pages and CSS animations actually start
125
+ // (queued via Web Animations API on the first paint after mount).
126
+ await nextPaint();
127
+
128
+ const previousTitle = document.title;
129
+ document.title = slide.meta?.title ?? slideId;
130
+
131
+ try {
132
+ await waitForFonts();
133
+
134
+ // Poll per-page animation completion. The bar tracks how many pages have
135
+ // settled, which matches "page X of N is being processed" mental model.
136
+ const deadline = performance.now() + ANIMATION_TIMEOUT_MS;
137
+ while (performance.now() < deadline) {
138
+ const settled = frames.reduce(
139
+ (n, frame) => (isFrameAnimationSettled(frame) ? n + 1 : n),
140
+ 0,
141
+ );
142
+ onProgress?.({
143
+ phase: 'processing',
144
+ current: settled,
145
+ total,
146
+ percent: Math.min(99, (settled / total) * 99),
147
+ });
148
+ if (settled === total) break;
149
+ await sleep(POLL_INTERVAL_MS);
150
+ }
151
+
152
+ await waitForDataWaitfor(root);
153
+ await sleep(100); // flush layout
154
+
155
+ onProgress?.({ phase: 'printing', current: total, total, percent: 99 });
156
+ const printDone = waitForAfterPrint();
157
+ window.print();
158
+ await printDone;
159
+ } finally {
160
+ onProgress?.({ phase: 'done', current: total, total, percent: 100 });
161
+ document.title = previousTitle;
162
+ for (const r of reactRoots) r.unmount();
163
+ root.remove();
164
+ style.remove();
165
+ }
166
+ }
167
+
168
+ function sleep(ms: number): Promise<void> {
169
+ return new Promise((resolve) => setTimeout(resolve, ms));
170
+ }
171
+
172
+ function nextPaint(): Promise<void> {
173
+ // rAF in real tabs; setTimeout fallback for hidden/throttled headless tabs.
174
+ return new Promise((resolve) => {
175
+ let settled = false;
176
+ const settle = () => {
177
+ if (settled) return;
178
+ settled = true;
179
+ resolve();
180
+ };
181
+ requestAnimationFrame(settle);
182
+ setTimeout(settle, 50);
183
+ });
184
+ }
185
+
186
+ function waitForAfterPrint(timeoutMs = 60_000): Promise<void> {
187
+ return new Promise((resolve) => {
188
+ const cleanup = () => {
189
+ window.removeEventListener('afterprint', onAfter);
190
+ clearTimeout(timer);
191
+ resolve();
192
+ };
193
+ const onAfter = () => cleanup();
194
+ const timer = setTimeout(cleanup, timeoutMs);
195
+ window.addEventListener('afterprint', onAfter, { once: true });
196
+ });
197
+ }
@@ -4,6 +4,13 @@ export type SlideSourceHit = {
4
4
  anchor: HTMLElement;
5
5
  };
6
6
 
7
+ export type FindSlideSourceOptions = {
8
+ // Visual editor uses this: skip component-invocation JSX (`<MyComp/>`)
9
+ // since most components don't forward `style`. Comments leave it off
10
+ // so any JSX can be annotated.
11
+ hostOnly?: boolean;
12
+ };
13
+
7
14
  type FiberLike = {
8
15
  return: FiberLike | null;
9
16
  stateNode?: unknown;
@@ -21,17 +28,45 @@ function getSource(fiber: FiberLike) {
21
28
  return fiber._debugSource ?? fiber.memoizedProps?.__source;
22
29
  }
23
30
 
24
- export function findSlideSource(el: HTMLElement, slideId: string): SlideSourceHit | null {
31
+ export function findSlideSource(
32
+ el: HTMLElement,
33
+ slideId: string,
34
+ opts?: FindSlideSourceOptions,
35
+ ): SlideSourceHit | null {
36
+ // Primary path: the `data-slide-loc` attribute injected by the
37
+ // loc-tags Vite plugin. Immune to HMR-stale fiber state.
38
+ const tagged = el.closest<HTMLElement>('[data-slide-loc]');
39
+ if (tagged) {
40
+ const loc = tagged.dataset.slideLoc;
41
+ if (loc) {
42
+ const idx = loc.indexOf(':');
43
+ if (idx > 0) {
44
+ const line = Number(loc.slice(0, idx));
45
+ const column = Number(loc.slice(idx + 1));
46
+ if (Number.isFinite(line) && Number.isFinite(column)) {
47
+ return { line, column, anchor: tagged };
48
+ }
49
+ }
50
+ }
51
+ }
52
+
53
+ // Fallback for JSX rendered from imported component files (which the
54
+ // loc-tags plugin doesn't transform).
25
55
  const needle = `/slides/${slideId}/index.tsx`;
26
56
  let fiber = getFiber(el);
27
57
  let anchor: HTMLElement = el;
28
58
  while (fiber) {
29
59
  const src = getSource(fiber);
30
- if (src?.fileName?.endsWith(needle) && src.lineNumber) {
31
- return { line: src.lineNumber, column: src.columnNumber ?? 0, anchor };
60
+ const isHost = fiber.stateNode instanceof HTMLElement;
61
+ if (src?.fileName?.endsWith(needle) && src.lineNumber && (!opts?.hostOnly || isHost)) {
62
+ return {
63
+ line: src.lineNumber,
64
+ column: src.columnNumber ?? 0,
65
+ anchor: isHost ? (fiber.stateNode as HTMLElement) : anchor,
66
+ };
32
67
  }
33
- if (fiber.stateNode instanceof HTMLElement) {
34
- anchor = fiber.stateNode;
68
+ if (isHost) {
69
+ anchor = fiber.stateNode as HTMLElement;
35
70
  }
36
71
  fiber = fiber.return;
37
72
  }
@@ -0,0 +1,61 @@
1
+ import { useCallback } from 'react';
2
+
3
+ export type EditOp =
4
+ | { kind: 'set-style'; key: string; value: string | null }
5
+ | { kind: 'set-text'; value: string };
6
+
7
+ export type Edit = { line: number; column: number; ops: EditOp[] };
8
+
9
+ export class NoOpEditError extends Error {
10
+ constructor() {
11
+ super(
12
+ 'Edit completed but the source file did not change — the target JSX may already match, or the target element may not be directly editable here.',
13
+ );
14
+ this.name = 'NoOpEditError';
15
+ }
16
+ }
17
+
18
+ export function useEditor(slideId: string) {
19
+ const applyEdit = useCallback(
20
+ async (line: number, column: number, ops: EditOp[]) => {
21
+ const res = await fetch('/__edit', {
22
+ method: 'POST',
23
+ headers: { 'content-type': 'application/json' },
24
+ body: JSON.stringify({ slideId, line, column, ops }),
25
+ });
26
+ const body = (await res.json().catch(() => ({}))) as { error?: string; changed?: boolean };
27
+ if (!res.ok) {
28
+ throw new Error(body.error ?? `POST /__edit → ${res.status}`);
29
+ }
30
+ if (body.changed === false) {
31
+ throw new NoOpEditError();
32
+ }
33
+ },
34
+ [slideId],
35
+ );
36
+
37
+ // Batch many element edits into one file write and one HMR tick.
38
+ const applyEdits = useCallback(
39
+ async (edits: Edit[]) => {
40
+ if (edits.length === 0) return;
41
+ const res = await fetch('/__edit/batch', {
42
+ method: 'POST',
43
+ headers: { 'content-type': 'application/json' },
44
+ body: JSON.stringify({ slideId, edits }),
45
+ });
46
+ const body = (await res.json().catch(() => ({}))) as {
47
+ error?: string;
48
+ changed?: boolean;
49
+ results?: Array<{ ok: boolean; error?: string }>;
50
+ };
51
+ if (!res.ok) {
52
+ throw new Error(body.error ?? `POST /__edit/batch → ${res.status}`);
53
+ }
54
+ const failed = body.results?.find((r) => !r.ok);
55
+ if (failed?.error) throw new Error(failed.error);
56
+ },
57
+ [slideId],
58
+ );
59
+
60
+ return { applyEdit, applyEdits };
61
+ }
@@ -0,0 +1,58 @@
1
+ // Helpers used by the PDF export flow to wait for the page to settle before
2
+ // invoking window.print(). Browser-only — no Node / headless dependency.
3
+
4
+ const DEFAULT_WAITFOR_TIMEOUT_MS = 10_000;
5
+
6
+ export async function waitForFonts(): Promise<void> {
7
+ if (!('fonts' in document)) return;
8
+ await document.fonts.ready;
9
+ const pending: Promise<unknown>[] = [];
10
+ for (const face of document.fonts) {
11
+ if (face.status !== 'loaded') pending.push(face.load());
12
+ }
13
+ if (pending.length) {
14
+ await Promise.all(pending.map((p) => p.catch(() => undefined)));
15
+ }
16
+ }
17
+
18
+ export async function waitForDataWaitfor(
19
+ root: HTMLElement,
20
+ timeoutMs = DEFAULT_WAITFOR_TIMEOUT_MS,
21
+ ): Promise<void> {
22
+ const targets = Array.from(root.querySelectorAll<HTMLElement>('[data-waitfor]'));
23
+ if (targets.length === 0) return;
24
+ const deadline = performance.now() + timeoutMs;
25
+ await Promise.all(
26
+ targets.map(async (el) => {
27
+ const selector = el.getAttribute('data-waitfor');
28
+ if (!selector) return;
29
+ while (performance.now() < deadline) {
30
+ try {
31
+ if (el.querySelector(selector)) return;
32
+ } catch {
33
+ return; // invalid selector — skip rather than hang
34
+ }
35
+ await nextFrame();
36
+ }
37
+ }),
38
+ );
39
+ }
40
+
41
+ /** Returns true if `frame` has no running finite-iteration animations. */
42
+ export function isFrameAnimationSettled(frame: Element): boolean {
43
+ if (typeof document.getAnimations !== 'function') return true;
44
+ for (const anim of document.getAnimations()) {
45
+ const effect = anim.effect as KeyframeEffect | null;
46
+ if (!effect) continue;
47
+ const target = effect.target;
48
+ if (!target || !frame.contains(target)) continue;
49
+ const timing = effect.getComputedTiming();
50
+ if (timing.iterations === Infinity) continue;
51
+ if (anim.playState !== 'finished') return false;
52
+ }
53
+ return true;
54
+ }
55
+
56
+ function nextFrame(): Promise<void> {
57
+ return new Promise((resolve) => requestAnimationFrame(() => resolve()));
58
+ }
@@ -1,14 +1,17 @@
1
1
  import config from 'virtual:open-slide/config';
2
- import { ChevronLeft, Download, FileCode2, Loader2, Pencil, Play } from 'lucide-react';
2
+ import { ChevronLeft, Download, FileCode2, FileText, Loader2, Pencil, Play } from 'lucide-react';
3
3
  import { type RefObject, useCallback, useEffect, useMemo, useRef, useState } from 'react';
4
4
  import { Link, useParams, useSearchParams } from 'react-router-dom';
5
+ import { toast } from 'sonner';
5
6
  import { CommentWidget } from '@/components/inspector/CommentWidget';
6
7
  import { InspectOverlay } from '@/components/inspector/InspectOverlay';
8
+ import { InspectorPanel } from '@/components/inspector/InspectorPanel';
7
9
  import {
8
10
  InspectorProvider,
9
11
  InspectToggleButton,
10
12
  useInspector,
11
13
  } from '@/components/inspector/InspectorProvider';
14
+ import { SaveBar } from '@/components/inspector/SaveBar';
12
15
  import { Button, buttonVariants } from '@/components/ui/button';
13
16
  import {
14
17
  DropdownMenu,
@@ -21,10 +24,12 @@ import { useFolders } from '@/lib/folders';
21
24
  import { useWheelPageNavigation } from '@/lib/useWheelPageNavigation';
22
25
  import { cn } from '@/lib/utils';
23
26
  import { ClickNavZones } from '../components/ClickNavZones';
27
+ import { PdfProgressToast } from '../components/PdfProgressToast';
24
28
  import { Player } from '../components/Player';
25
29
  import { SlideCanvas } from '../components/SlideCanvas';
26
30
  import { ThumbnailRail } from '../components/ThumbnailRail';
27
31
  import { exportSlideAsHtml } from '../lib/export-html';
32
+ import { exportSlideAsPdf } from '../lib/export-pdf';
28
33
  import type { SlideModule } from '../lib/sdk';
29
34
  import { loadSlide } from '../lib/slides';
30
35
 
@@ -218,6 +223,44 @@ export function Slide() {
218
223
  <FileCode2 />
219
224
  Download HTML
220
225
  </DropdownMenuItem>
226
+ <DropdownMenuItem
227
+ disabled={exporting}
228
+ onSelect={async () => {
229
+ if (!slide || exporting) return;
230
+ setExporting(true);
231
+ const toastId = `pdf-export-${slideId}`;
232
+ toast.custom(
233
+ () => (
234
+ <PdfProgressToast
235
+ progress={{
236
+ phase: 'processing',
237
+ current: 0,
238
+ total: pages.length,
239
+ percent: 0,
240
+ }}
241
+ />
242
+ ),
243
+ { id: toastId, duration: Infinity },
244
+ );
245
+ try {
246
+ await exportSlideAsPdf(slide, slideId, (p) => {
247
+ toast.custom(() => <PdfProgressToast progress={p} />, {
248
+ id: toastId,
249
+ duration: Infinity,
250
+ });
251
+ });
252
+ } catch (err) {
253
+ console.error('[open-slide] pdf export failed', err);
254
+ toast.error('PDF export failed', { id: toastId, duration: 4000 });
255
+ } finally {
256
+ setExporting(false);
257
+ toast.dismiss(toastId);
258
+ }
259
+ }}
260
+ >
261
+ <FileText />
262
+ Download PDF
263
+ </DropdownMenuItem>
221
264
  </DropdownMenuContent>
222
265
  </DropdownMenu>
223
266
  )}
@@ -258,13 +301,14 @@ export function Slide() {
258
301
  canNext={index < pageCount - 1}
259
302
  />
260
303
  <InspectOverlay />
304
+ <SaveBar />
305
+ <CommentWidget />
261
306
  <div className="pointer-events-none absolute bottom-3 left-1/2 z-10 -translate-x-1/2 rounded-full bg-black/50 px-2.5 py-0.5 text-[11px] font-medium tabular-nums text-white backdrop-blur md:hidden">
262
307
  {index + 1} / {pageCount}
263
308
  </div>
264
309
  </main>
310
+ <InspectorPanel />
265
311
  </div>
266
-
267
- <CommentWidget />
268
312
  </div>
269
313
  </InspectorProvider>
270
314
  );