@perkyzz/emvb 0.5.0 → 0.6.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.
Files changed (86) hide show
  1. package/README.md +4 -0
  2. package/THIRD_PARTY_NOTICES.md +23 -1
  3. package/licenses/exif-js.LICENSE +21 -0
  4. package/licenses/fflate.LICENSE +21 -0
  5. package/licenses/glfx.js.LICENSE +19 -0
  6. package/licenses/mini-photo-editor.LICENSE +21 -0
  7. package/licenses/photocn.LICENSE +21 -0
  8. package/package.json +2 -1
  9. package/src/admin/editor/Editor.tsx +6 -0
  10. package/src/admin/editor/collection-previews.ts +6 -1
  11. package/src/admin/editor/editor-chrome.tsx +49 -0
  12. package/src/admin/editor/editor-commands.ts +13 -0
  13. package/src/admin/editor/editor-css.ts +3 -0
  14. package/src/admin/editor/panels/ColorControl.tsx +5 -4
  15. package/src/admin/editor/panels/LayersPanel.tsx +13 -3
  16. package/src/admin/editor/panels/VariableSection.tsx +5 -3
  17. package/src/admin/editor/panels/settings/FieldControl.tsx +18 -7
  18. package/src/admin/editor/panels/settings/MediaPicker.tsx +154 -4
  19. package/src/admin/editor/panels/settings/RequiredFieldsNotice.tsx +76 -0
  20. package/src/admin/editor/panels/variable-values.ts +14 -0
  21. package/src/admin/editor/store.ts +7 -3
  22. package/src/admin/image-editor/BlurFocus.tsx +112 -0
  23. package/src/admin/image-editor/Canvas.tsx +261 -0
  24. package/src/admin/image-editor/CropOverlay.tsx +390 -0
  25. package/src/admin/image-editor/CurvesPanel.tsx +394 -0
  26. package/src/admin/image-editor/ExportDialog.tsx +354 -0
  27. package/src/admin/image-editor/ImageEditButton.tsx +83 -0
  28. package/src/admin/image-editor/ImageEditorDialog.tsx +786 -0
  29. package/src/admin/image-editor/MetadataPanel.tsx +183 -0
  30. package/src/admin/image-editor/announce.tsx +65 -0
  31. package/src/admin/image-editor/crop-geometry.ts +161 -0
  32. package/src/admin/image-editor/curve-math.ts +177 -0
  33. package/src/admin/image-editor/data-url-fetch.ts +59 -0
  34. package/src/admin/image-editor/engine.ts +55 -0
  35. package/src/admin/image-editor/exif.ts +82 -0
  36. package/src/admin/image-editor/flatten.ts +54 -0
  37. package/src/admin/image-editor/gpu-fit.ts +81 -0
  38. package/src/admin/image-editor/image-editor-css.ts +398 -0
  39. package/src/admin/image-editor/load.ts +109 -0
  40. package/src/admin/image-editor/panels.tsx +287 -0
  41. package/src/admin/image-editor/parts.tsx +565 -0
  42. package/src/admin/image-editor/save.ts +125 -0
  43. package/src/admin/image-editor/tone-panels.tsx +338 -0
  44. package/src/admin/image-editor/tools.ts +59 -0
  45. package/src/admin/image-editor/worker.ts +111 -0
  46. package/src/admin/media-api.ts +113 -3
  47. package/src/admin/ui.ts +5 -0
  48. package/src/astro/EmVBPage.astro +11 -2
  49. package/src/astro/render.ts +3 -0
  50. package/src/astro/resolve-theme.ts +15 -4
  51. package/src/astro/visitor.ts +4 -3
  52. package/src/constants.ts +1 -1
  53. package/src/core/arrange.ts +2 -0
  54. package/src/core/data/bindings.ts +12 -6
  55. package/src/core/design/classes.ts +5 -3
  56. package/src/core/design/diff.ts +3 -1
  57. package/src/core/design/merge.ts +3 -1
  58. package/src/core/design/transfer.ts +13 -2
  59. package/src/core/design/variables.ts +2 -1
  60. package/src/core/elements/dynamic-elements.ts +9 -1
  61. package/src/core/elements/form-elements.ts +16 -17
  62. package/src/core/elements/plain-text.ts +2 -2
  63. package/src/core/forms/binding.ts +148 -1
  64. package/src/core/history/diff.ts +32 -4
  65. package/src/core/image-edit/schema.ts +145 -0
  66. package/src/core/image-edit/summary.ts +58 -0
  67. package/src/core/index.ts +14 -0
  68. package/src/core/limits.ts +10 -0
  69. package/src/core/migrate/index.ts +3 -1
  70. package/src/core/perf/meter.ts +9 -1
  71. package/src/core/render/dynamic-post.ts +2 -1
  72. package/src/core/render/form.ts +24 -6
  73. package/src/core/render/index.ts +26 -5
  74. package/src/core/schema/layout.ts +11 -1
  75. package/src/core/share/link.ts +5 -2
  76. package/src/core/stable-json.ts +15 -0
  77. package/src/core/theme/dynamic.ts +21 -18
  78. package/src/core/theme/pagination.ts +30 -3
  79. package/src/core/theme/popup-rules.ts +10 -5
  80. package/src/mcp/ports.ts +8 -1
  81. package/src/mcp/read.ts +68 -1
  82. package/src/mcp/tools.ts +1 -1
  83. package/src/mcp/write.ts +100 -18
  84. package/src/server/agent-settings.ts +28 -3
  85. package/src/server/icon-routes.ts +8 -5
  86. package/src/server/mcp-routes.ts +68 -10
@@ -0,0 +1,786 @@
1
+ /**
2
+ * The full-screen image editor (W-482, laid out like photocn's editor in W-483). Loaded on demand
3
+ * from the Image settings; photocn and this file never ship in the main editor chunk or on public
4
+ * pages.
5
+ *
6
+ * The desktop layout (toolbar on top, canvas, resizable sidebar with the tool switcher, histogram
7
+ * and panel) and the compact phone layout (photo first, tools at the bottom, controls in a sheet)
8
+ * follow photocn's `image-editor.tsx`, `layout.tsx` and `compact-layout.tsx`
9
+ * (https://github.com/rbbydotdev/photocn, apps/www/src/registry/image-editor), MIT License,
10
+ * Copyright (c) 2026 rbbydotdev. Rebuilt with Kumo components and EmVB tokens.
11
+ */
12
+ import { Badge, Button, Dialog, DropdownMenu, TooltipProvider } from "@cloudflare/kumo";
13
+ import {
14
+ ArrowCounterClockwiseIcon,
15
+ DotsThreeIcon,
16
+ DownloadSimpleIcon,
17
+ WarningCircleIcon,
18
+ XIcon,
19
+ } from "@phosphor-icons/react";
20
+ import * as React from "react";
21
+ import { SOLID_PRIMARY, UI_CSS } from "../ui.ts";
22
+ import { EditorCanvas } from "./Canvas.tsx";
23
+ import {
24
+ aspectRatioOptions,
25
+ errorMessage,
26
+ ImageEditorProvider,
27
+ planEngine,
28
+ useImageEditor,
29
+ useImageEditorState,
30
+ } from "./engine.ts";
31
+ import { IMAGE_EDITOR_CSS } from "./image-editor-css.ts";
32
+ import { Announcer } from "./announce.tsx";
33
+ import { withDataUrlFetch } from "./data-url-fetch.ts";
34
+ import { ExportDialog, type ExportResult, type ExportSettings } from "./ExportDialog.tsx";
35
+ import { fitSourceToGpu } from "./gpu-fit.ts";
36
+ import { loadEditableSource, type LoadedSource } from "./load.ts";
37
+ import { ImageNameContext } from "./MetadataPanel.tsx";
38
+ import { ToolPanel } from "./panels.tsx";
39
+ import {
40
+ CompactToolBar,
41
+ CompareButton,
42
+ Histogram,
43
+ RedoButton,
44
+ ResetAllButton,
45
+ ToolSwitcher,
46
+ UndoButton,
47
+ } from "./parts.tsx";
48
+ import { buildImageEdit, editedFileName, hasGps, outputFile, savedRecipe } from "./save.ts";
49
+ import { displayName, elementAspectOption, sizeLabel, type ImageEditorToolId } from "./tools.ts";
50
+ import type { RenderMode } from "./worker.ts";
51
+ import type { ImageEdit } from "../../core/index.ts";
52
+
53
+ export type ImageEditorDialogProps = {
54
+ open: boolean;
55
+ onOpenChange: (open: boolean) => void;
56
+ /** The Image element's props (`src`, `alt`, `edit`, `width`, `height`…). */
57
+ imageProps: Record<string, unknown>;
58
+ /** Tests and the spike force main-thread rendering. */
59
+ forceRenderMode?: RenderMode;
60
+ onClosed?: () => void;
61
+ /**
62
+ * Saves the edited copy (W-485): upload `file` as a new media item and point the element at
63
+ * it with `edit`. Rejecting keeps the editor open with the error and a Retry. Without it the
64
+ * export step only downloads.
65
+ */
66
+ onSave?: (file: File, copy: SavedCopy) => Promise<void>;
67
+ };
68
+
69
+ export type SavedCopy = {
70
+ width: number;
71
+ height: number;
72
+ /** The validated `ImageEdit` record for `props.edit`. */
73
+ edit: ImageEdit;
74
+ };
75
+
76
+ type SaveApi = { open: () => void; enabled: boolean };
77
+ const SaveContext = React.createContext<SaveApi>({ open: () => undefined, enabled: false });
78
+
79
+ /** Below this editor width the compact (phone) layout is used (photocn COMPACT_WIDTH). */
80
+ export const COMPACT_WIDTH = 640;
81
+
82
+ function withoutEdit(props: Record<string, unknown>): Record<string, unknown> {
83
+ const { edit: _edit, ...rest } = props;
84
+ return rest;
85
+ }
86
+ const SIDEBAR = { default: 338, min: 288, max: 544, canvasMin: 384 };
87
+ /** Sheet heights as a fraction of the editor: peek and expanded (photocn SNAP_POINTS). */
88
+ const SNAP_POINTS = [0.42, 0.9] as const;
89
+
90
+ type Ready = {
91
+ source: Extract<LoadedSource, { ok: true }>;
92
+ renderMode: RenderMode;
93
+ spawnWorker?: () => Worker;
94
+ reason?: string;
95
+ };
96
+ type Phase =
97
+ | { kind: "loading" }
98
+ | { kind: "error"; message: string; retry: boolean }
99
+ | { kind: "ready"; ready: Ready };
100
+
101
+ /** The editor's width, measured before paint (null until then). */
102
+ function useWidth(ref: React.RefObject<HTMLElement | null>) {
103
+ const [width, setWidth] = React.useState<number | null>(null);
104
+ React.useLayoutEffect(() => {
105
+ const element = ref.current;
106
+ if (!element) return;
107
+ setWidth(element.getBoundingClientRect().width || window.innerWidth);
108
+ if (typeof ResizeObserver === "undefined") return;
109
+ const observer = new ResizeObserver(([entry]) => {
110
+ if (entry) setWidth(entry.contentRect.width);
111
+ });
112
+ observer.observe(element);
113
+ return () => observer.disconnect();
114
+ }, [ref]);
115
+ return width;
116
+ }
117
+
118
+ function SaveCopyButton() {
119
+ const save = React.useContext(SaveContext);
120
+ const editor = useImageEditor();
121
+ return (
122
+ <Button
123
+ type="button"
124
+ variant="primary"
125
+ size="sm"
126
+ className="emvb-ie-btn"
127
+ style={SOLID_PRIMARY}
128
+ icon={<DownloadSimpleIcon aria-hidden="true" />}
129
+ disabled={!save.enabled || !editor.isReady || editor.disabled}
130
+ onClick={save.open}
131
+ aria-haspopup="dialog"
132
+ data-emvb-image-save=""
133
+ >
134
+ Save copy
135
+ </Button>
136
+ );
137
+ }
138
+
139
+ function CancelButton({ compact = false }: { compact?: boolean }) {
140
+ return (
141
+ <Dialog.Close
142
+ render={(props) =>
143
+ compact ? (
144
+ <Button
145
+ {...props}
146
+ type="button"
147
+ variant="ghost"
148
+ size="sm"
149
+ shape="square"
150
+ className="emvb-ie-btn emvb-ie-btn-icon emvb-ie-touch"
151
+ aria-label="Close editor"
152
+ icon={<XIcon aria-hidden="true" />}
153
+ data-emvb-image-cancel=""
154
+ />
155
+ ) : (
156
+ <Button
157
+ {...props}
158
+ type="button"
159
+ variant="outline"
160
+ size="sm"
161
+ className="emvb-ie-btn"
162
+ data-emvb-image-cancel=""
163
+ >
164
+ Cancel
165
+ </Button>
166
+ )
167
+ }
168
+ />
169
+ );
170
+ }
171
+
172
+ /** Loading or error (photocn ImageEditorStatusBadge), plus the main-thread fallback note. */
173
+ function StatusBadge({ renderMode, reason }: { renderMode: RenderMode; reason?: string }) {
174
+ const editor = useImageEditor();
175
+ if (editor.status === "error") {
176
+ const message = errorMessage(editor.error);
177
+ return (
178
+ <span className="emvb-ie-badge" title={message}>
179
+ <Badge variant="error">
180
+ <WarningCircleIcon aria-hidden="true" /> {message}
181
+ </Badge>
182
+ </span>
183
+ );
184
+ }
185
+ if (editor.status === "loading" || editor.status === "idle") {
186
+ return (
187
+ <span className="emvb-ie-badge">
188
+ <Badge variant="neutral">Loading</Badge>
189
+ </span>
190
+ );
191
+ }
192
+ if (renderMode !== "main") return null;
193
+ return (
194
+ <span className="emvb-ie-badge" title={reason} data-emvb-image-mode="main">
195
+ <Badge variant="neutral">Standard preview</Badge>
196
+ </span>
197
+ );
198
+ }
199
+
200
+ /** File name and output size, where photocn has its Open button. */
201
+ function FileLabel({ name }: { name: string }) {
202
+ const editor = useImageEditor();
203
+ const size = editor.geometry.outputSize;
204
+ return (
205
+ <span className="emvb-ie-file" data-emvb-image-editor-file="" title={name}>
206
+ <span className="emvb-ie-file-name">{name}</span>
207
+ {size ? (
208
+ <span className="emvb-ie-file-size">{sizeLabel(size.width, size.height)}</span>
209
+ ) : null}
210
+ </span>
211
+ );
212
+ }
213
+
214
+ function DesktopLayout({ ready, name }: { ready: Ready; name: string }) {
215
+ const [sidebar, setSidebar] = React.useState(SIDEBAR.default);
216
+ const workspaceRef = React.useRef<HTMLDivElement>(null);
217
+ const drag = React.useRef<{ id: number; x: number; start: number } | null>(null);
218
+ const clamp = (w: number) => {
219
+ const total = workspaceRef.current?.getBoundingClientRect().width ?? 0;
220
+ const max = total ? Math.min(SIDEBAR.max, total - SIDEBAR.canvasMin) : SIDEBAR.max;
221
+ return Math.round(Math.max(SIDEBAR.min, Math.min(Math.max(SIDEBAR.min, max), w)));
222
+ };
223
+ return (
224
+ <div className="emvb-ie-layout" data-slot="image-editor-layout">
225
+ <div className="emvb-ie-toolbar" data-slot="editor-toolbar">
226
+ <UndoButton />
227
+ <RedoButton />
228
+ <FileLabel name={name} />
229
+ <StatusBadge renderMode={ready.renderMode} reason={ready.reason} />
230
+ {ready.source.reducedFrom ? (
231
+ <span
232
+ className="emvb-ie-badge"
233
+ data-emvb-image-reduced=""
234
+ title={`The original is ${sizeLabel(ready.source.reducedFrom.width, ready.source.reducedFrom.height)}, more than this browser can edit. The copy is saved at the reduced size; the original stays untouched.`}
235
+ >
236
+ <Badge variant="neutral">Reduced to fit</Badge>
237
+ </span>
238
+ ) : null}
239
+ <div className="emvb-ie-toolbar-end">
240
+ <ResetAllButton />
241
+ <CompareButton />
242
+ <CancelButton />
243
+ <SaveCopyButton />
244
+ </div>
245
+ </div>
246
+ <div
247
+ className="emvb-ie-workspace"
248
+ ref={workspaceRef}
249
+ style={{ gridTemplateColumns: `minmax(0, 1fr) 0 ${sidebar}px` }}
250
+ data-slot="editor-workspace"
251
+ >
252
+ <main className="emvb-ie-main" data-slot="editor-canvas">
253
+ <EditorCanvas alt={name} />
254
+ </main>
255
+ <div
256
+ className="emvb-ie-resize"
257
+ role="separator"
258
+ aria-orientation="vertical"
259
+ aria-label="Resize the sidebar"
260
+ aria-valuemin={SIDEBAR.min}
261
+ aria-valuemax={SIDEBAR.max}
262
+ aria-valuenow={sidebar}
263
+ tabIndex={0}
264
+ onKeyDown={(event) => {
265
+ const step = event.shiftKey ? 48 : 16;
266
+ if (event.key === "ArrowLeft") setSidebar((w) => clamp(w + step));
267
+ else if (event.key === "ArrowRight") setSidebar((w) => clamp(w - step));
268
+ else return;
269
+ event.preventDefault();
270
+ }}
271
+ onPointerDown={(event) => {
272
+ event.currentTarget.setPointerCapture?.(event.pointerId);
273
+ drag.current = { id: event.pointerId, x: event.clientX, start: sidebar };
274
+ }}
275
+ onPointerMove={(event) => {
276
+ const d = drag.current;
277
+ if (d?.id === event.pointerId) setSidebar(clamp(d.start - (event.clientX - d.x)));
278
+ }}
279
+ onPointerUp={() => {
280
+ drag.current = null;
281
+ }}
282
+ >
283
+ <span aria-hidden="true" />
284
+ </div>
285
+ <aside className="emvb-ie-sidebar" data-slot="editor-sidebar">
286
+ <div className="emvb-ie-sidebar-tools">
287
+ <ToolSwitcher />
288
+ </div>
289
+ <Histogram />
290
+ <ToolPanel />
291
+ </aside>
292
+ </div>
293
+ </div>
294
+ );
295
+ }
296
+
297
+ /** A non-modal bottom sheet: the photo stays touchable, e.g. to drag the crop frame. */
298
+ function PanelSheet({
299
+ open,
300
+ onOpenChange,
301
+ snap,
302
+ onSnapChange,
303
+ label,
304
+ children,
305
+ }: {
306
+ open: boolean;
307
+ onOpenChange: (open: boolean) => void;
308
+ snap: number;
309
+ onSnapChange: (snap: number) => void;
310
+ label: string;
311
+ children: React.ReactNode;
312
+ }) {
313
+ const drag = React.useRef<{ pointerId: number; startY: number; startSnap: number } | null>(null);
314
+ const [dragSnap, setDragSnap] = React.useState<number | null>(null);
315
+ const height = dragSnap ?? snap;
316
+ const onPointerUp = (event: React.PointerEvent<HTMLDivElement>) => {
317
+ const d = drag.current;
318
+ if (!d || d.pointerId !== event.pointerId) return;
319
+ drag.current = null;
320
+ const released = dragSnap ?? snap;
321
+ setDragSnap(null);
322
+ if (released < SNAP_POINTS[0] * 0.6) {
323
+ onOpenChange(false);
324
+ return;
325
+ }
326
+ onSnapChange(
327
+ SNAP_POINTS.reduce((best, point) =>
328
+ Math.abs(point - released) < Math.abs(best - released) ? point : best,
329
+ ),
330
+ );
331
+ };
332
+ return (
333
+ <section
334
+ aria-hidden={!open}
335
+ aria-label={`${label} controls`}
336
+ className="emvb-ie-sheet"
337
+ data-open={open || undefined}
338
+ data-dragging={dragSnap === null ? undefined : ""}
339
+ data-emvb-image-sheet={open ? "open" : "closed"}
340
+ inert={!open}
341
+ style={{ height: `${height * 100}%` }}
342
+ >
343
+ <div
344
+ aria-label="Resize panel"
345
+ className="emvb-ie-sheet-grip"
346
+ role="separator"
347
+ onPointerCancel={onPointerUp}
348
+ onPointerDown={(event) => {
349
+ event.currentTarget.setPointerCapture?.(event.pointerId);
350
+ drag.current = { pointerId: event.pointerId, startY: event.clientY, startSnap: snap };
351
+ }}
352
+ onPointerMove={(event) => {
353
+ const d = drag.current;
354
+ if (!d || d.pointerId !== event.pointerId) return;
355
+ const container = event.currentTarget.closest(".emvb-ie-compact");
356
+ const containerHeight = container?.clientHeight || window.innerHeight;
357
+ const next = d.startSnap - (event.clientY - d.startY) / containerHeight;
358
+ setDragSnap(Math.min(0.96, Math.max(0.08, next)));
359
+ }}
360
+ onPointerUp={onPointerUp}
361
+ >
362
+ <span />
363
+ </div>
364
+ {children}
365
+ </section>
366
+ );
367
+ }
368
+
369
+ function CompactLayout({ name }: { name: string }) {
370
+ const editor = useImageEditor();
371
+ const rootRef = React.useRef<HTMLDivElement | null>(null);
372
+ const [rootHeight, setRootHeight] = React.useState<number | null>(null);
373
+ React.useLayoutEffect(() => {
374
+ const element = rootRef.current;
375
+ if (!element) return;
376
+ setRootHeight(element.getBoundingClientRect().height);
377
+ if (typeof ResizeObserver === "undefined") return;
378
+ const observer = new ResizeObserver(([entry]) => {
379
+ if (entry) setRootHeight(entry.contentRect.height);
380
+ });
381
+ observer.observe(element);
382
+ return () => observer.disconnect();
383
+ }, []);
384
+ const [panelOpen, setPanelOpen] = React.useState(false);
385
+ const [snap, setSnap] = React.useState<number>(SNAP_POINTS[0]);
386
+ const selectTool = (tool: ImageEditorToolId) => {
387
+ if (tool === editor.tool) {
388
+ setPanelOpen((open) => !open);
389
+ return;
390
+ }
391
+ editor.setTool(tool);
392
+ setPanelOpen(true);
393
+ setSnap(SNAP_POINTS[0]);
394
+ };
395
+ // Keep the photo above the sheet: pad the canvas by the sheet's peek height.
396
+ const inset = panelOpen && rootHeight ? Math.max(0, rootHeight * SNAP_POINTS[0] - 28) : undefined;
397
+ const label =
398
+ editor.tool === "compose" ? "Crop" : editor.tool.charAt(0).toUpperCase() + editor.tool.slice(1);
399
+ return (
400
+ <div className="emvb-ie-compact" ref={rootRef} data-slot="image-editor-compact">
401
+ <header className="emvb-ie-compact-head">
402
+ <UndoButton className="emvb-ie-touch" />
403
+ <RedoButton className="emvb-ie-touch" />
404
+ <div className="emvb-ie-toolbar-end">
405
+ <CompareButton showLabel={false} />
406
+ <SaveCopyButton />
407
+ <DropdownMenu>
408
+ <DropdownMenu.Trigger
409
+ render={
410
+ <Button
411
+ type="button"
412
+ variant="ghost"
413
+ shape="square"
414
+ size="sm"
415
+ aria-label="More"
416
+ className="emvb-ie-btn emvb-ie-btn-icon emvb-ie-touch"
417
+ icon={<DotsThreeIcon aria-hidden="true" weight="bold" />}
418
+ data-emvb-image-more=""
419
+ />
420
+ }
421
+ />
422
+ <DropdownMenu.Content align="end">
423
+ <DropdownMenu.Item
424
+ icon={ArrowCounterClockwiseIcon}
425
+ variant="danger"
426
+ disabled={!editor.hasImage || editor.recipes.current === null}
427
+ onClick={() => editor.resetAll()}
428
+ >
429
+ Reset all edits
430
+ </DropdownMenu.Item>
431
+ </DropdownMenu.Content>
432
+ </DropdownMenu>
433
+ <CancelButton compact />
434
+ </div>
435
+ </header>
436
+ <div className="emvb-ie-compact-canvas" style={{ paddingBottom: inset }}>
437
+ <EditorCanvas alt={name} padding={12} />
438
+ </div>
439
+ <CompactToolBar onSelect={selectTool} disabled={!editor.hasImage || editor.disabled} />
440
+ <PanelSheet
441
+ label={label}
442
+ open={panelOpen}
443
+ onOpenChange={setPanelOpen}
444
+ snap={snap}
445
+ onSnapChange={setSnap}
446
+ >
447
+ <div className="emvb-ie-sheet-tools">
448
+ <CompactToolBar
449
+ className="emvb-ie-compact-tools-inline"
450
+ disabled={editor.disabled}
451
+ onSelect={(tool) => editor.setTool(tool)}
452
+ />
453
+ <Button
454
+ type="button"
455
+ variant="ghost"
456
+ shape="square"
457
+ size="sm"
458
+ aria-label="Close panel"
459
+ className="emvb-ie-btn emvb-ie-btn-icon emvb-ie-touch"
460
+ icon={<XIcon aria-hidden="true" />}
461
+ onClick={() => setPanelOpen(false)}
462
+ />
463
+ </div>
464
+ {/* Focusable so the keyboard can scroll a panel with no controls (Metadata, W-486). */}
465
+ <div className="emvb-ie-sheet-body" tabIndex={0} role="region" aria-label={label}>
466
+ <ToolPanel />
467
+ </div>
468
+ </PanelSheet>
469
+ </div>
470
+ );
471
+ }
472
+
473
+ function EditorView({
474
+ ready,
475
+ imageProps,
476
+ escapeRef,
477
+ onSave,
478
+ onSaved,
479
+ }: {
480
+ ready: Ready;
481
+ imageProps: Record<string, unknown>;
482
+ escapeRef: React.MutableRefObject<(() => void) | null>;
483
+ onSave?: (file: File, copy: SavedCopy) => Promise<void>;
484
+ onSaved: () => void;
485
+ }) {
486
+ const fitValue = elementAspectOption(imageProps.width, imageProps.height);
487
+ const fitKey = fitValue ? `${fitValue.value}|${fitValue.label}` : "";
488
+ // A stable list: a new one each render would look like new options to the hook.
489
+ const options = React.useMemo(
490
+ () => (fitValue ? withElementOption(fitValue) : undefined),
491
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- fitKey stands for fitValue.
492
+ [fitKey],
493
+ );
494
+ const editor = useImageEditorState({
495
+ src: ready.source.blob,
496
+ decodeOptions: { name: ready.source.name, type: ready.source.type },
497
+ renderMode: ready.renderMode,
498
+ ...(ready.spawnWorker ? { spawnWorker: ready.spawnWorker } : {}),
499
+ defaultTool: "adjust",
500
+ ...(options ? { aspectRatioOptions: options } : {}),
501
+ });
502
+ // Esc leaves corner editing before it closes the editor.
503
+ const { editingCorners, setEditingCorners } = editor.geometry;
504
+ escapeRef.current = editingCorners ? () => setEditingCorners(false) : null;
505
+ const mainThread = ready.renderMode === "main";
506
+ // Re-opening an edited picture: the original is loaded, then the saved recipe goes back on.
507
+ const applied = React.useRef(false);
508
+ const { isReady, recipes } = editor;
509
+ React.useEffect(() => {
510
+ if (!isReady || applied.current) return;
511
+ applied.current = true;
512
+ const recipe = ready.source.fromOriginal ? savedRecipe(imageProps) : null;
513
+ if (!recipe) return;
514
+ const task = () => recipes.apply(recipe as Parameters<typeof recipes.apply>[0]);
515
+ void (mainThread ? withDataUrlFetch(task) : task()).catch(() => undefined);
516
+ }, [isReady, recipes, imageProps, ready.source.fromOriginal, mainThread]);
517
+ const [gps, setGps] = React.useState(false);
518
+ React.useEffect(() => {
519
+ let alive = true;
520
+ void hasGps(ready.source.blob).then(
521
+ (found) => alive && setGps(found),
522
+ () => undefined,
523
+ );
524
+ return () => {
525
+ alive = false;
526
+ };
527
+ }, [ready.source.blob]);
528
+ const [exportOpen, setExportOpen] = React.useState(false);
529
+ const save = React.useMemo<SaveApi>(
530
+ () => ({ open: () => setExportOpen(true), enabled: Boolean(onSave) }),
531
+ [onSave],
532
+ );
533
+ const currentRecipe = editor.recipes.current;
534
+ const saveCopy = async (result: ExportResult, settings: ExportSettings) => {
535
+ if (!onSave) return;
536
+ // W-493: with the original gone, the copy becomes the new original of this edit.
537
+ const base = ready.source.originalMissing ? withoutEdit(imageProps) : imageProps;
538
+ const built = buildImageEdit({ imageProps: base, recipe: currentRecipe, output: settings });
539
+ if (!built.ok) throw new Error(built.message);
540
+ const name = editedFileName(ready.source.name, settings.format);
541
+ const { file } = await outputFile(result.blob, name, settings.format, settings.stripGps);
542
+ try {
543
+ await onSave(file, { width: result.width, height: result.height, edit: built.edit });
544
+ } catch (caught) {
545
+ const why = caught instanceof Error && caught.message ? ` ${caught.message}` : "";
546
+ throw new Error(`Couldn't save the copy.${why}`, { cause: caught });
547
+ }
548
+ setExportOpen(false);
549
+ onSaved();
550
+ };
551
+ const width = useWidth(editor.rootRef);
552
+ const compact = width !== null && width < COMPACT_WIDTH;
553
+ const name = displayName(ready.source.name, imageProps.alt);
554
+ return (
555
+ <ImageEditorProvider editor={editor}>
556
+ <SaveContext.Provider value={save}>
557
+ <ImageNameContext.Provider value={name}>
558
+ <div
559
+ className="emvb-ie"
560
+ ref={editor.rootRef}
561
+ data-emvb-dialog="image-editor"
562
+ data-emvb-image-editor={
563
+ editor.status === "error" ? "error" : editor.isReady ? "ready" : "loading"
564
+ }
565
+ data-emvb-render-mode={ready.renderMode}
566
+ data-layout={compact ? "compact" : "desktop"}
567
+ data-emvb-image-tool-active={editor.tool}
568
+ >
569
+ {width === null ? null : compact ? (
570
+ <CompactLayout name={name} />
571
+ ) : (
572
+ <DesktopLayout ready={ready} name={name} />
573
+ )}
574
+ <Announcer />
575
+ </div>
576
+ {exportOpen ? <div className="emvb-ie-scrim" aria-hidden="true" /> : null}
577
+ {onSave ? (
578
+ <ExportDialog
579
+ open={exportOpen}
580
+ onOpenChange={setExportOpen}
581
+ mainThread={mainThread}
582
+ sourceHasGps={gps}
583
+ sourceType={ready.source.blob.type}
584
+ downloadName={editedFileName(ready.source.name, "jpeg")}
585
+ onSave={saveCopy}
586
+ />
587
+ ) : null}
588
+ </ImageNameContext.Provider>
589
+ </SaveContext.Provider>
590
+ </ImageEditorProvider>
591
+ );
592
+ }
593
+
594
+ /** photocn's presets with "Fit this element" after Original (W-483). */
595
+ function withElementOption(fit: { value: string; label: string }) {
596
+ const rest = aspectRatioOptions.filter((o) => o.value !== fit.value);
597
+ const at = rest.findIndex((o) => o.value === "original") + 1;
598
+ return [...rest.slice(0, at), fit, ...rest.slice(at)];
599
+ }
600
+
601
+ /** Before the picture loads, or when it can't: the same frame with a message in the stage. */
602
+ function StateFrame({
603
+ phase,
604
+ onRetry,
605
+ }: {
606
+ phase: Exclude<Phase, { kind: "ready" }>;
607
+ onRetry: () => void;
608
+ }) {
609
+ return (
610
+ <div
611
+ className="emvb-ie"
612
+ data-emvb-dialog="image-editor"
613
+ data-emvb-image-editor={phase.kind}
614
+ data-layout="desktop"
615
+ >
616
+ <div className="emvb-ie-layout">
617
+ <div className="emvb-ie-toolbar">
618
+ <span className="emvb-ie-file">
619
+ <span className="emvb-ie-file-name">
620
+ {phase.kind === "error" ? "Couldn't open the picture" : "Opening the picture…"}
621
+ </span>
622
+ </span>
623
+ <div className="emvb-ie-toolbar-end">
624
+ <CancelButton />
625
+ </div>
626
+ </div>
627
+ <main className="emvb-ie-main emvb-ie-main-solo">
628
+ <div className="emvb-ie-stage emvb-ie-stage-message">
629
+ {phase.kind === "loading" ? (
630
+ <div className="emvb-ie-loading" aria-busy="true">
631
+ <span className="emvb-ie-spinner" aria-hidden="true" />
632
+ <span className="emvb-ie-sr">Opening the picture…</span>
633
+ </div>
634
+ ) : (
635
+ <div className="emvb-ie-error" role="alert" data-emvb-image-error="">
636
+ <span className="emvb-ie-error-icon" aria-hidden="true">
637
+ <WarningCircleIcon weight="duotone" />
638
+ </span>
639
+ <h3>Can't edit this picture</h3>
640
+ <p>{phase.message}</p>
641
+ {phase.retry ? (
642
+ <Button variant="outline" size="sm" className="emvb-ie-btn" onClick={onRetry}>
643
+ Try again
644
+ </Button>
645
+ ) : (
646
+ <Dialog.Close
647
+ render={(props) => (
648
+ <Button {...props} variant="outline" size="sm" className="emvb-ie-btn">
649
+ Back to the page
650
+ </Button>
651
+ )}
652
+ />
653
+ )}
654
+ </div>
655
+ )}
656
+ </div>
657
+ </main>
658
+ </div>
659
+ </div>
660
+ );
661
+ }
662
+
663
+ function Editor({
664
+ imageProps,
665
+ forceRenderMode,
666
+ escapeRef,
667
+ onSave,
668
+ onSaved,
669
+ }: {
670
+ imageProps: Record<string, unknown>;
671
+ forceRenderMode?: RenderMode;
672
+ escapeRef: React.MutableRefObject<(() => void) | null>;
673
+ onSave?: (file: File, copy: SavedCopy) => Promise<void>;
674
+ onSaved: () => void;
675
+ }) {
676
+ const [phase, setPhase] = React.useState<Phase>({ kind: "loading" });
677
+ const [attempt, setAttempt] = React.useState(0);
678
+ React.useEffect(() => {
679
+ let alive = true;
680
+ setPhase({ kind: "loading" });
681
+ void (async () => {
682
+ const source = await loadEditableSource(imageProps, window.location.origin);
683
+ if (!alive) return;
684
+ if (!source.ok) {
685
+ setPhase({ kind: "error", message: source.message, retry: source.reason === "network" });
686
+ return;
687
+ }
688
+ const plan = await planEngine(forceRenderMode ? { force: forceRenderMode } : {});
689
+ if (!alive) return;
690
+ if (!plan.ok) {
691
+ setPhase({ kind: "error", message: plan.message, retry: false });
692
+ return;
693
+ }
694
+ const fitted = await fitSourceToGpu(source).catch(() => null);
695
+ if (!alive) return;
696
+ if (!fitted) {
697
+ setPhase({
698
+ kind: "error",
699
+ retry: false,
700
+ message: "This picture is too large to edit in the browser. Use a smaller copy.",
701
+ });
702
+ return;
703
+ }
704
+ setPhase({
705
+ kind: "ready",
706
+ ready: {
707
+ source: fitted,
708
+ renderMode: plan.renderMode,
709
+ ...(plan.spawnWorker ? { spawnWorker: plan.spawnWorker } : {}),
710
+ ...(plan.reason ? { reason: plan.reason } : {}),
711
+ },
712
+ });
713
+ })().catch((error: unknown) => {
714
+ if (alive) {
715
+ setPhase({
716
+ kind: "error",
717
+ retry: true,
718
+ message: `Couldn't open this picture${error instanceof Error && error.message ? `: ${error.message}` : "."}`,
719
+ });
720
+ }
721
+ });
722
+ return () => {
723
+ alive = false;
724
+ };
725
+ }, [imageProps, forceRenderMode, attempt]);
726
+ if (phase.kind !== "ready") {
727
+ return <StateFrame phase={phase} onRetry={() => setAttempt((n) => n + 1)} />;
728
+ }
729
+ return (
730
+ <EditorView
731
+ key={attempt}
732
+ ready={phase.ready}
733
+ imageProps={imageProps}
734
+ escapeRef={escapeRef}
735
+ onSave={onSave}
736
+ onSaved={onSaved}
737
+ />
738
+ );
739
+ }
740
+
741
+ export default function ImageEditorDialog({
742
+ open,
743
+ onOpenChange,
744
+ imageProps,
745
+ forceRenderMode,
746
+ onClosed,
747
+ onSave,
748
+ }: ImageEditorDialogProps) {
749
+ const escapeRef = React.useRef<(() => void) | null>(null);
750
+ return (
751
+ <Dialog.Root
752
+ open={open}
753
+ onOpenChange={(next, details) => {
754
+ // photocn's Esc leaves the corner handles; it shouldn't also close the editor.
755
+ const leave = escapeRef.current;
756
+ if (!next && leave && details?.reason === "escape-key") {
757
+ leave();
758
+ return;
759
+ }
760
+ onOpenChange(next);
761
+ }}
762
+ onOpenChangeComplete={(next) => {
763
+ if (!next) onClosed?.();
764
+ }}
765
+ >
766
+ <Dialog className="emvb-image-editor-popup" data-emvb-image-editor-popup="">
767
+ <style>{UI_CSS + IMAGE_EDITOR_CSS}</style>
768
+ <Dialog.Title className="emvb-ie-sr">Edit image</Dialog.Title>
769
+ <Dialog.Description className="emvb-ie-sr">
770
+ Crop, rotate and adjust a copy of this picture.
771
+ </Dialog.Description>
772
+ <TooltipProvider>
773
+ {open ? (
774
+ <Editor
775
+ imageProps={imageProps}
776
+ forceRenderMode={forceRenderMode}
777
+ escapeRef={escapeRef}
778
+ onSave={onSave}
779
+ onSaved={() => onOpenChange(false)}
780
+ />
781
+ ) : null}
782
+ </TooltipProvider>
783
+ </Dialog>
784
+ </Dialog.Root>
785
+ );
786
+ }