@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,565 @@
1
+ /**
2
+ * Shared pieces of the image editor (W-483): icon buttons with tooltips, the panel header,
3
+ * centered sliders, the histogram strip and the tool pickers.
4
+ *
5
+ * Layout and behaviour follow photocn's editor components (https://github.com/rbbydotdev/photocn,
6
+ * apps/www/src/registry/image-editor: toolbar.tsx, panel-header.tsx, histogram.tsx, crop-panel.tsx,
7
+ * compact-layout.tsx, icon-skew.tsx), MIT License, Copyright (c) 2026 rbbydotdev. Rebuilt with
8
+ * Kumo components and EmVB tokens instead of shadcn/ui.
9
+ */
10
+ import { Button, Tabs, Tooltip } from "@cloudflare/kumo";
11
+ import {
12
+ ArrowCounterClockwiseIcon,
13
+ ArrowUUpLeftIcon,
14
+ ArrowUUpRightIcon,
15
+ CropIcon,
16
+ DropIcon,
17
+ EyeIcon,
18
+ InfoIcon,
19
+ MagicWandIcon,
20
+ PulseIcon,
21
+ SlidersHorizontalIcon,
22
+ SparkleIcon,
23
+ StackIcon,
24
+ type Icon,
25
+ } from "@phosphor-icons/react";
26
+ import * as React from "react";
27
+ import { useImageEditor } from "./engine.ts";
28
+ import { IMAGE_EDITOR_TOOLS, type ImageEditorToolId } from "./tools.ts";
29
+
30
+ export const TOOL_ICONS: Record<ImageEditorToolId, Icon> = {
31
+ adjust: SlidersHorizontalIcon,
32
+ compose: CropIcon,
33
+ curves: PulseIcon,
34
+ effects: SparkleIcon,
35
+ filters: MagicWandIcon,
36
+ blender: StackIcon,
37
+ blur: DropIcon,
38
+ metadata: InfoIcon,
39
+ };
40
+
41
+ type IconButtonProps = {
42
+ label: string;
43
+ icon: React.ReactNode;
44
+ onClick?: () => void;
45
+ disabled?: boolean;
46
+ /** Show the label next to the icon (photocn's `showLabel`). */
47
+ showLabel?: boolean;
48
+ variant?: "ghost" | "outline";
49
+ className?: string;
50
+ } & Omit<React.ButtonHTMLAttributes<HTMLButtonElement>, "onClick" | "disabled" | "className">;
51
+
52
+ /** A ghost or outline button; icon-only ones get a tooltip below (photocn EditorActionButton). */
53
+ export function IconButton({
54
+ label,
55
+ icon,
56
+ showLabel = false,
57
+ variant = "ghost",
58
+ className,
59
+ ...props
60
+ }: IconButtonProps) {
61
+ const classes = `emvb-ie-btn${showLabel ? "" : " emvb-ie-btn-icon"}${className ? ` ${className}` : ""}`;
62
+ const button = showLabel ? (
63
+ <Button type="button" variant={variant} size="sm" className={classes} icon={icon} {...props}>
64
+ {label}
65
+ </Button>
66
+ ) : (
67
+ <Button
68
+ type="button"
69
+ variant={variant}
70
+ size="sm"
71
+ shape="square"
72
+ aria-label={label}
73
+ className={classes}
74
+ icon={icon}
75
+ {...props}
76
+ />
77
+ );
78
+ if (showLabel || props.disabled) return button;
79
+ return (
80
+ <Tooltip content={label} side="bottom" asChild>
81
+ {button}
82
+ </Tooltip>
83
+ );
84
+ }
85
+
86
+ export function UndoButton(props: { className?: string }) {
87
+ const editor = useImageEditor();
88
+ return (
89
+ <IconButton
90
+ label="Undo"
91
+ icon={<ArrowUUpLeftIcon aria-hidden="true" />}
92
+ disabled={editor.disabled || !editor.history.canUndo}
93
+ onClick={() => editor.history.undo()}
94
+ data-emvb-image-undo=""
95
+ {...props}
96
+ />
97
+ );
98
+ }
99
+
100
+ export function RedoButton(props: { className?: string }) {
101
+ const editor = useImageEditor();
102
+ return (
103
+ <IconButton
104
+ label="Redo"
105
+ icon={<ArrowUUpRightIcon aria-hidden="true" />}
106
+ disabled={editor.disabled || !editor.history.canRedo}
107
+ onClick={() => editor.history.redo()}
108
+ data-emvb-image-redo=""
109
+ {...props}
110
+ />
111
+ );
112
+ }
113
+
114
+ export function ResetAllButton() {
115
+ const editor = useImageEditor();
116
+ return (
117
+ <IconButton
118
+ label="Reset"
119
+ showLabel
120
+ variant="outline"
121
+ icon={<ArrowCounterClockwiseIcon aria-hidden="true" />}
122
+ disabled={editor.disabled || !editor.hasImage || editor.recipes.current === null}
123
+ onClick={() => editor.resetAll()}
124
+ data-emvb-image-reset=""
125
+ />
126
+ );
127
+ }
128
+
129
+ /** Press and hold to see the original (geometry is kept). */
130
+ export function CompareButton({ showLabel = true }: { showLabel?: boolean }) {
131
+ const editor = useImageEditor();
132
+ const release = () => editor.compare.setActive(false);
133
+ return (
134
+ <IconButton
135
+ label="Original"
136
+ showLabel={showLabel}
137
+ variant={showLabel ? "outline" : "ghost"}
138
+ icon={<EyeIcon aria-hidden="true" />}
139
+ aria-pressed={editor.compare.active}
140
+ disabled={editor.disabled || !editor.hasImage}
141
+ data-emvb-image-compare=""
142
+ onBlur={release}
143
+ onKeyDown={(event) => {
144
+ if (event.key === " " || event.key === "Enter") editor.compare.setActive(true);
145
+ }}
146
+ onKeyUp={release}
147
+ onPointerCancel={release}
148
+ onPointerDown={() => editor.compare.setActive(true)}
149
+ onPointerLeave={release}
150
+ onPointerUp={release}
151
+ />
152
+ );
153
+ }
154
+
155
+ /** The sidebar's tool switcher: one icon per tool, the active one filled (photocn ToggleGroup). */
156
+ export function ToolSwitcher() {
157
+ const editor = useImageEditor();
158
+ const disabled = editor.disabled || editor.isLoading;
159
+ const buttons = React.useRef<(HTMLButtonElement | null)[]>([]);
160
+ const index = IMAGE_EDITOR_TOOLS.findIndex((t) => t.id === editor.tool);
161
+ const onKeyDown = (event: React.KeyboardEvent) => {
162
+ const count = IMAGE_EDITOR_TOOLS.length;
163
+ const next =
164
+ event.key === "ArrowRight"
165
+ ? (index + 1) % count
166
+ : event.key === "ArrowLeft"
167
+ ? (index - 1 + count) % count
168
+ : event.key === "Home"
169
+ ? 0
170
+ : event.key === "End"
171
+ ? count - 1
172
+ : -1;
173
+ if (next < 0) return;
174
+ event.preventDefault();
175
+ const target = IMAGE_EDITOR_TOOLS[next];
176
+ if (target) editor.setTool(target.id);
177
+ buttons.current[next]?.focus();
178
+ };
179
+ return (
180
+ <div
181
+ className="emvb-ie-switcher"
182
+ role="toolbar"
183
+ aria-label="Editor tools"
184
+ onKeyDown={onKeyDown}
185
+ data-slot="editor-toolbar"
186
+ >
187
+ {IMAGE_EDITOR_TOOLS.map((tool, i) => {
188
+ const ToolIcon = TOOL_ICONS[tool.id];
189
+ const active = tool.id === editor.tool;
190
+ return (
191
+ <button
192
+ key={tool.id}
193
+ ref={(el) => {
194
+ buttons.current[i] = el;
195
+ }}
196
+ type="button"
197
+ className="emvb-ie-switch"
198
+ aria-label={tool.label}
199
+ aria-pressed={active}
200
+ title={tool.label}
201
+ tabIndex={active || (index < 0 && i === 0) ? 0 : -1}
202
+ disabled={disabled}
203
+ data-emvb-image-tool={tool.id}
204
+ onClick={() => editor.setTool(tool.id)}
205
+ >
206
+ <ToolIcon aria-hidden="true" weight={active ? "bold" : "regular"} />
207
+ </button>
208
+ );
209
+ })}
210
+ </div>
211
+ );
212
+ }
213
+
214
+ /** Phone tool bar: labelled, horizontally scrolling, 44 px targets (photocn CompactToolBar). */
215
+ export function CompactToolBar({
216
+ onSelect,
217
+ disabled,
218
+ className,
219
+ }: {
220
+ onSelect: (tool: ImageEditorToolId) => void;
221
+ disabled?: boolean;
222
+ className?: string;
223
+ }) {
224
+ const editor = useImageEditor();
225
+ return (
226
+ <nav
227
+ className={`emvb-ie-compact-tools${className ? ` ${className}` : ""}`}
228
+ aria-label="Editor tools"
229
+ >
230
+ {IMAGE_EDITOR_TOOLS.map((tool) => {
231
+ const ToolIcon = TOOL_ICONS[tool.id];
232
+ const active = tool.id === editor.tool;
233
+ return (
234
+ <button
235
+ key={tool.id}
236
+ type="button"
237
+ className="emvb-ie-compact-tool"
238
+ aria-pressed={active}
239
+ disabled={disabled}
240
+ data-emvb-image-tool={tool.id}
241
+ onClick={() => onSelect(tool.id)}
242
+ >
243
+ <ToolIcon aria-hidden="true" />
244
+ {tool.label}
245
+ </button>
246
+ );
247
+ })}
248
+ </nav>
249
+ );
250
+ }
251
+
252
+ /** Title and description on the left, Reset on the right, a rule below (photocn PanelResetHeader). */
253
+ export function PanelHeader({
254
+ title,
255
+ description,
256
+ onReset,
257
+ resetDisabled = false,
258
+ }: {
259
+ title: string;
260
+ description?: string;
261
+ onReset?: () => void;
262
+ resetDisabled?: boolean;
263
+ }) {
264
+ return (
265
+ <div className="emvb-ie-panel-head">
266
+ <div className="emvb-ie-panel-titles">
267
+ <h2>{title}</h2>
268
+ {description ? <p>{description}</p> : null}
269
+ </div>
270
+ <IconButton
271
+ label="Reset"
272
+ showLabel
273
+ variant="outline"
274
+ icon={<ArrowCounterClockwiseIcon aria-hidden="true" />}
275
+ disabled={resetDisabled || !onReset}
276
+ onClick={onReset}
277
+ data-emvb-image-panel-reset=""
278
+ />
279
+ </div>
280
+ );
281
+ }
282
+
283
+ /**
284
+ * A slider whose zero is the middle, with its value as a click-to-reset button (photocn
285
+ * CenteredSlider).
286
+ * A native range input styled with EmVB tokens: Kumo has no slider. `onCommit` fires on release.
287
+ */
288
+ export function CenteredSlider({
289
+ label,
290
+ value,
291
+ min,
292
+ max,
293
+ step,
294
+ disabled,
295
+ format,
296
+ onChange,
297
+ onCommit,
298
+ name,
299
+ }: {
300
+ label: string;
301
+ value: number;
302
+ min: number;
303
+ max: number;
304
+ step: number;
305
+ disabled?: boolean;
306
+ format: (value: number) => string;
307
+ onChange: (value: number) => void;
308
+ onCommit?: () => void;
309
+ name: string;
310
+ }) {
311
+ const id = React.useId();
312
+ const fill = ((value - min) / (max - min)) * 100;
313
+ return (
314
+ <div className="emvb-ie-slider" data-disabled={disabled || undefined}>
315
+ <div className="emvb-ie-slider-head">
316
+ <label htmlFor={id}>{label}</label>
317
+ <button
318
+ type="button"
319
+ className="emvb-ie-slider-value"
320
+ disabled={disabled || value === 0}
321
+ title="Reset"
322
+ onClick={() => {
323
+ onChange(0);
324
+ onCommit?.();
325
+ }}
326
+ >
327
+ {format(value)}
328
+ </button>
329
+ </div>
330
+ <input
331
+ id={id}
332
+ type="range"
333
+ min={min}
334
+ max={max}
335
+ step={step}
336
+ value={value}
337
+ disabled={disabled}
338
+ data-emvb-image-slider={name}
339
+ style={
340
+ {
341
+ "--emvb-ie-from": "0%",
342
+ "--emvb-ie-to": `${fill}%`,
343
+ } as React.CSSProperties
344
+ }
345
+ onChange={(event) => onChange(Number(event.currentTarget.value))}
346
+ onPointerUp={() => onCommit?.()}
347
+ onKeyUp={() => onCommit?.()}
348
+ onBlur={() => onCommit?.()}
349
+ />
350
+ </div>
351
+ );
352
+ }
353
+
354
+ const roundTo = (v: number, step: number) => {
355
+ const places = Math.max(0, -Math.floor(Math.log10(step)));
356
+ return Number(v.toFixed(places));
357
+ };
358
+
359
+ /**
360
+ * A labelled slider with a typed value (W-484; photocn's adjustment, blur and filter sliders,
361
+ * whose value is a read-only output). The value field takes a number in the shown unit: Enter or
362
+ * leaving the field applies it, Escape puts the old one back, ↑/↓ step it. Values are in the
363
+ * units shown (−1 to 1, or 0 to 100 for percentages); `onCommit` ends one undo step.
364
+ */
365
+ export function ValueSlider({
366
+ label,
367
+ name,
368
+ value,
369
+ min,
370
+ max,
371
+ step,
372
+ disabled,
373
+ format,
374
+ onChange,
375
+ onCommit,
376
+ }: {
377
+ label: string;
378
+ name: string;
379
+ value: number;
380
+ min: number;
381
+ max: number;
382
+ step: number;
383
+ disabled?: boolean;
384
+ format: (value: number) => string;
385
+ onChange: (value: number) => void;
386
+ onCommit?: () => void;
387
+ }) {
388
+ const id = React.useId();
389
+ const labelId = `${id}-label`;
390
+ const [draft, setDraft] = React.useState<string | null>(null);
391
+ const fill = ((value - min) / (max - min)) * 100;
392
+ const apply = (raw: string) => {
393
+ setDraft(null);
394
+ const parsed = Number.parseFloat(raw.replace(/[^\d.+-]/g, ""));
395
+ if (!Number.isFinite(parsed)) return;
396
+ const next = roundTo(Math.min(max, Math.max(min, parsed)), step);
397
+ if (next !== value) onChange(next);
398
+ onCommit?.();
399
+ };
400
+ return (
401
+ <div className="emvb-ie-slider" data-disabled={disabled || undefined}>
402
+ <div className="emvb-ie-slider-head">
403
+ <label id={labelId} htmlFor={id}>
404
+ {label}
405
+ </label>
406
+ <input
407
+ type="text"
408
+ inputMode="decimal"
409
+ className="emvb-ie-number"
410
+ aria-label={`${label} value`}
411
+ disabled={disabled}
412
+ data-emvb-image-number={name}
413
+ value={draft ?? format(value)}
414
+ onFocus={(event) => event.currentTarget.select()}
415
+ onChange={(event) => setDraft(event.currentTarget.value)}
416
+ onBlur={(event) => {
417
+ if (draft !== null) apply(event.currentTarget.value);
418
+ }}
419
+ onKeyDown={(event) => {
420
+ if (event.key === "Enter") {
421
+ event.preventDefault();
422
+ apply(event.currentTarget.value);
423
+ } else if (event.key === "Escape") {
424
+ // Put the old value back, and keep Esc from closing the editor.
425
+ event.preventDefault();
426
+ event.stopPropagation();
427
+ setDraft(null);
428
+ } else if (event.key === "ArrowUp" || event.key === "ArrowDown") {
429
+ event.preventDefault();
430
+ const delta = (event.key === "ArrowUp" ? 1 : -1) * step * (event.shiftKey ? 10 : 1);
431
+ const next = roundTo(Math.min(max, Math.max(min, value + delta)), step);
432
+ setDraft(null);
433
+ onChange(next);
434
+ onCommit?.();
435
+ }
436
+ }}
437
+ />
438
+ </div>
439
+ <input
440
+ id={id}
441
+ type="range"
442
+ min={min}
443
+ max={max}
444
+ step={step}
445
+ value={value}
446
+ disabled={disabled}
447
+ aria-labelledby={labelId}
448
+ aria-valuetext={format(value)}
449
+ data-emvb-image-slider={name}
450
+ style={{ "--emvb-ie-from": "0%", "--emvb-ie-to": `${fill}%` } as React.CSSProperties}
451
+ onChange={(event) => onChange(Number(event.currentTarget.value))}
452
+ onPointerUp={() => onCommit?.()}
453
+ onKeyUp={() => onCommit?.()}
454
+ onBlur={() => onCommit?.()}
455
+ />
456
+ </div>
457
+ );
458
+ }
459
+
460
+ /** Underlined or segmented section tabs (photocn's TabsList, here Kumo Tabs). */
461
+ export function SectionTabs<T extends string>({
462
+ label,
463
+ value,
464
+ items,
465
+ onChange,
466
+ variant = "underline",
467
+ name,
468
+ }: {
469
+ label: string;
470
+ value: T;
471
+ items: readonly { value: T; label: React.ReactNode }[];
472
+ onChange: (value: T) => void;
473
+ variant?: "underline" | "segmented";
474
+ name: string;
475
+ }) {
476
+ return (
477
+ <div
478
+ className="emvb-ie-tabs"
479
+ data-variant={variant}
480
+ data-emvb-image-tabs={name}
481
+ role="group"
482
+ aria-label={label}
483
+ >
484
+ <Tabs
485
+ variant={variant}
486
+ size="sm"
487
+ value={value}
488
+ tabs={items.map((item) => ({ value: item.value, label: item.label }))}
489
+ onValueChange={(next) => {
490
+ const match = items.find((item) => item.value === next);
491
+ if (match) onChange(match.value);
492
+ }}
493
+ />
494
+ </div>
495
+ );
496
+ }
497
+
498
+ /** Live RGB histogram of the rendered image (photocn ImageEditorHistogram). */
499
+ export function Histogram() {
500
+ const editor = useImageEditor();
501
+ const pixels = editor.histogram.data?.pixels;
502
+ return (
503
+ <div className="emvb-ie-histogram" data-slot="image-editor-histogram">
504
+ <div className="emvb-ie-histogram-head">
505
+ <span>Histogram</span>
506
+ <span className="emvb-ie-mono">{pixels ? pixels.toLocaleString() : "—"}</span>
507
+ </div>
508
+ <canvas aria-hidden="true" height={64} width={256} ref={editor.histogram.canvasRef} />
509
+ </div>
510
+ );
511
+ }
512
+
513
+ /** Perspective "adjust corners" icon (photocn icon-skew.tsx, from xdadda/mini-photo-editor). */
514
+ export function SkewIcon() {
515
+ return (
516
+ <svg
517
+ aria-hidden="true"
518
+ fill="none"
519
+ stroke="currentColor"
520
+ strokeLinecap="round"
521
+ strokeLinejoin="round"
522
+ strokeWidth="2"
523
+ viewBox="0 0 24 24"
524
+ width="1em"
525
+ height="1em"
526
+ >
527
+ <path d="M7 5 L21 8 L17 19 L3 16 Z" />
528
+ <circle cx="7" cy="5" r="0.7" fill="currentColor" />
529
+ <circle cx="21" cy="8" r="0.7" fill="currentColor" />
530
+ <circle cx="17" cy="19" r="0.7" fill="currentColor" />
531
+ <circle cx="3" cy="16" r="0.7" fill="currentColor" />
532
+ </svg>
533
+ );
534
+ }
535
+
536
+ /** Quarter-turn icons, as in photocn's crop panel (Lucide rotate-ccw/cw-square, ISC). */
537
+ export function RotateSquareIcon({ direction }: { direction: "left" | "right" }) {
538
+ return (
539
+ <svg
540
+ aria-hidden="true"
541
+ fill="none"
542
+ stroke="currentColor"
543
+ strokeLinecap="round"
544
+ strokeLinejoin="round"
545
+ strokeWidth="2"
546
+ viewBox="0 0 24 24"
547
+ width="1em"
548
+ height="1em"
549
+ >
550
+ {direction === "left" ? (
551
+ <>
552
+ <path d="M20 9V7a2 2 0 0 0-2-2h-6" />
553
+ <path d="m15 2-3 3 3 3" />
554
+ <path d="M20 13v5a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V7a2 2 0 0 1 2-2h2" />
555
+ </>
556
+ ) : (
557
+ <>
558
+ <path d="M12 5H6a2 2 0 0 0-2 2v3" />
559
+ <path d="m9 8 3-3-3-3" />
560
+ <path d="M4 14v4a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7a2 2 0 0 0-2-2h-2" />
561
+ </>
562
+ )}
563
+ </svg>
564
+ );
565
+ }
@@ -0,0 +1,125 @@
1
+ /**
2
+ * Saving an edited picture (W-485): export settings, the output file and the `edit` record.
3
+ * No photocn import here, so this stays testable without WebGL.
4
+ */
5
+ import { ImageEdit, type ImageEditRecipe } from "../../core/index.ts";
6
+ import type { ImageEditOutput } from "../../core/image-edit/schema.ts";
7
+ import { stripJpegGps } from "./exif.ts";
8
+
9
+ /** photocn version the recipes are written for (checked against package.json in tests). */
10
+ export const PHOTOCN_VERSION = "0.1.2";
11
+
12
+ export type ExportFormat = ImageEditOutput["format"];
13
+
14
+ /** photocn's export formats, WebP first and recommended for the site (W-485 defaults). */
15
+ export const EXPORT_FORMATS = [
16
+ { value: "webp", label: "WebP (recommended)", lossy: true, defaultQuality: 0.85 },
17
+ { value: "jpeg", label: "JPEG", lossy: true, defaultQuality: 0.85 },
18
+ { value: "png", label: "PNG", lossy: false, defaultQuality: 1 },
19
+ ] as const satisfies readonly {
20
+ value: ExportFormat;
21
+ label: string;
22
+ lossy: boolean;
23
+ defaultQuality: number;
24
+ }[];
25
+
26
+ /** The longest side of a saved copy is capped to this by default. */
27
+ export const DEFAULT_MAX_SIDE = 2560;
28
+ const EXT: Record<ExportFormat, string> = { webp: "webp", jpeg: "jpg", png: "png" };
29
+
30
+ export function formatInfo(format: ExportFormat) {
31
+ return EXPORT_FORMATS.find((f) => f.value === format) ?? EXPORT_FORMATS[0];
32
+ }
33
+
34
+ type Size = { width: number; height: number };
35
+
36
+ /** The default output width: full size, or less so the longest side fits `maxSide`. */
37
+ export function cappedWidth(full: Size, maxSide = DEFAULT_MAX_SIDE): number | null {
38
+ const longest = Math.max(full.width, full.height);
39
+ if (longest <= maxSide) return null;
40
+ return Math.max(1, Math.round((full.width * maxSide) / longest));
41
+ }
42
+
43
+ /** Output size for a chosen width (null = full size); the height follows the crop. */
44
+ export function outputSize(full: Size, width: number | null): Size {
45
+ if (!width) return full;
46
+ return { width, height: Math.max(1, Math.round((width * full.height) / full.width)) };
47
+ }
48
+
49
+ /** "garden.jpg" + webp → "garden-edited.webp"; an earlier "-edited" isn't repeated. */
50
+ export function editedFileName(name: string, format: ExportFormat): string {
51
+ const base =
52
+ name
53
+ .replace(/\.[^./]+$/, "")
54
+ .replace(/-edited$/, "")
55
+ .replace(/[^\w.-]+/g, "-")
56
+ .replace(/^-+|-+$/g, "") || "image";
57
+ return `${base}-edited.${EXT[format]}`;
58
+ }
59
+
60
+ /** The file to upload: JPEG location data is removed when asked (photocn copies the EXIF). */
61
+ export async function outputFile(
62
+ blob: Blob,
63
+ name: string,
64
+ format: ExportFormat,
65
+ stripGps: boolean,
66
+ ): Promise<{ file: File; gpsRemoved: boolean }> {
67
+ const type = blob.type || `image/${format}`;
68
+ if (format !== "jpeg" || !stripGps) {
69
+ return { file: new File([blob], name, { type }), gpsRemoved: false };
70
+ }
71
+ const { bytes, removed } = stripJpegGps(await blob.arrayBuffer());
72
+ return { file: new File([bytes], name, { type }), gpsRemoved: removed };
73
+ }
74
+
75
+ /** True when a JPEG source carries GPS location data. */
76
+ export async function hasGps(blob: Blob): Promise<boolean> {
77
+ if (!/jpe?g/i.test(blob.type)) return false;
78
+ return stripJpegGps(await blob.arrayBuffer()).removed;
79
+ }
80
+
81
+ /**
82
+ * The record saved on the element. It always points at the untouched original: an edit of an
83
+ * edit keeps the first original, so re-opening never stacks losses.
84
+ */
85
+ export function buildImageEdit(input: {
86
+ imageProps: Record<string, unknown>;
87
+ recipe: unknown;
88
+ output: ImageEditOutput;
89
+ now?: Date;
90
+ }): { ok: true; edit: ImageEdit } | { ok: false; message: string } {
91
+ const { imageProps, output } = input;
92
+ const prior = ImageEdit.safeParse(imageProps.edit);
93
+ const originalSrc = prior.success
94
+ ? prior.data.originalSrc
95
+ : typeof imageProps.src === "string"
96
+ ? imageProps.src
97
+ : "";
98
+ const priorId = prior.success ? prior.data.originalMediaId : undefined;
99
+ const originalMediaId =
100
+ priorId ?? (typeof imageProps.mediaId === "string" ? imageProps.mediaId : undefined);
101
+ const parsed = ImageEdit.safeParse({
102
+ v: 1,
103
+ engine: "photocn",
104
+ engineVersion: PHOTOCN_VERSION,
105
+ recipe: (input.recipe as ImageEditRecipe | null) ?? { version: 1 },
106
+ ...(originalMediaId ? { originalMediaId } : {}),
107
+ originalSrc,
108
+ output,
109
+ editedAt: (input.now ?? new Date()).toISOString(),
110
+ });
111
+ if (parsed.success) return { ok: true, edit: parsed.data };
112
+ const issue = parsed.error.issues[0];
113
+ return {
114
+ ok: false,
115
+ message: `This edit can't be saved${issue?.message ? `: ${issue.message}` : "."}`,
116
+ };
117
+ }
118
+
119
+ /** The recipe to re-apply when re-opening, or null for none or a damaged record. */
120
+ export function savedRecipe(imageProps: Record<string, unknown>): ImageEditRecipe | null {
121
+ const parsed = ImageEdit.safeParse(imageProps.edit);
122
+ if (!parsed.success) return null;
123
+ const { recipe } = parsed.data;
124
+ return Object.keys(recipe).some((k) => k !== "version" && k !== "name") ? recipe : null;
125
+ }