@perkyzz/emvb 0.4.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 (127) hide show
  1. package/README.md +23 -3
  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 +5 -3
  9. package/src/admin/agents-api.ts +39 -0
  10. package/src/admin/editor/CommandPalette.tsx +43 -2
  11. package/src/admin/editor/Editor.tsx +33 -0
  12. package/src/admin/editor/Timeline.tsx +108 -6
  13. package/src/admin/editor/collection-previews.ts +6 -1
  14. package/src/admin/editor/editor-chrome.tsx +49 -0
  15. package/src/admin/editor/editor-commands.ts +13 -0
  16. package/src/admin/editor/editor-css.ts +7 -0
  17. package/src/admin/editor/feature-css.ts +22 -3
  18. package/src/admin/editor/palette.ts +6 -2
  19. package/src/admin/editor/panels/ColorControl.tsx +24 -12
  20. package/src/admin/editor/panels/ElementPanel.tsx +1 -1
  21. package/src/admin/editor/panels/LayersPanel.tsx +13 -3
  22. package/src/admin/editor/panels/TokenScales.tsx +4 -2
  23. package/src/admin/editor/panels/VariableSection.tsx +5 -3
  24. package/src/admin/editor/panels/color-space.ts +12 -1
  25. package/src/admin/editor/panels/settings/AdvancedFields.tsx +84 -28
  26. package/src/admin/editor/panels/settings/AudienceEditor.tsx +42 -4
  27. package/src/admin/editor/panels/settings/DraftTextField.tsx +38 -9
  28. package/src/admin/editor/panels/settings/FieldControl.tsx +24 -7
  29. package/src/admin/editor/panels/settings/IconPicker.tsx +21 -1
  30. package/src/admin/editor/panels/settings/ImageSourcesField.tsx +111 -0
  31. package/src/admin/editor/panels/settings/MediaPicker.tsx +156 -7
  32. package/src/admin/editor/panels/settings/QueryStyleRows.tsx +178 -0
  33. package/src/admin/editor/panels/settings/RequiredFieldsNotice.tsx +76 -0
  34. package/src/admin/editor/panels/settings/advanced-rules.ts +3 -0
  35. package/src/admin/editor/panels/settings/link-rules.ts +19 -0
  36. package/src/admin/editor/panels/settings/number-input.ts +11 -0
  37. package/src/admin/editor/panels/settings/query-style.ts +65 -0
  38. package/src/admin/editor/panels/variable-values.ts +18 -2
  39. package/src/admin/editor/remote-change.ts +67 -0
  40. package/src/admin/editor/store.ts +7 -3
  41. package/src/admin/image-editor/BlurFocus.tsx +112 -0
  42. package/src/admin/image-editor/Canvas.tsx +261 -0
  43. package/src/admin/image-editor/CropOverlay.tsx +390 -0
  44. package/src/admin/image-editor/CurvesPanel.tsx +394 -0
  45. package/src/admin/image-editor/ExportDialog.tsx +354 -0
  46. package/src/admin/image-editor/ImageEditButton.tsx +83 -0
  47. package/src/admin/image-editor/ImageEditorDialog.tsx +786 -0
  48. package/src/admin/image-editor/MetadataPanel.tsx +183 -0
  49. package/src/admin/image-editor/announce.tsx +65 -0
  50. package/src/admin/image-editor/crop-geometry.ts +161 -0
  51. package/src/admin/image-editor/curve-math.ts +177 -0
  52. package/src/admin/image-editor/data-url-fetch.ts +59 -0
  53. package/src/admin/image-editor/engine.ts +55 -0
  54. package/src/admin/image-editor/exif.ts +82 -0
  55. package/src/admin/image-editor/flatten.ts +54 -0
  56. package/src/admin/image-editor/gpu-fit.ts +81 -0
  57. package/src/admin/image-editor/image-editor-css.ts +398 -0
  58. package/src/admin/image-editor/load.ts +109 -0
  59. package/src/admin/image-editor/panels.tsx +287 -0
  60. package/src/admin/image-editor/parts.tsx +565 -0
  61. package/src/admin/image-editor/save.ts +125 -0
  62. package/src/admin/image-editor/tone-panels.tsx +338 -0
  63. package/src/admin/image-editor/tools.ts +59 -0
  64. package/src/admin/image-editor/worker.ts +111 -0
  65. package/src/admin/index.tsx +3 -1
  66. package/src/admin/media-api.ts +132 -2
  67. package/src/admin/pages/AgentsPage.tsx +274 -0
  68. package/src/admin/ui.ts +33 -0
  69. package/src/astro/EmVBPage.astro +11 -2
  70. package/src/astro/floats/runtime.ts +10 -0
  71. package/src/astro/popups/runtime.ts +15 -0
  72. package/src/astro/render.ts +3 -0
  73. package/src/astro/resolve-theme.ts +15 -4
  74. package/src/astro/tabs/runtime.ts +60 -1
  75. package/src/astro/visitor.ts +4 -3
  76. package/src/constants.ts +1 -1
  77. package/src/core/a11y/audit.ts +202 -26
  78. package/src/core/arrange.ts +13 -3
  79. package/src/core/css/generate.ts +9 -1
  80. package/src/core/data/bindings.ts +12 -6
  81. package/src/core/design/classes.ts +5 -3
  82. package/src/core/design/diff.ts +3 -1
  83. package/src/core/design/merge.ts +3 -1
  84. package/src/core/design/transfer.ts +13 -2
  85. package/src/core/design/variables.ts +2 -1
  86. package/src/core/elements/dynamic-elements.ts +9 -1
  87. package/src/core/elements/form-elements.ts +18 -3
  88. package/src/core/elements/index.ts +39 -11
  89. package/src/core/elements/plain-text.ts +2 -2
  90. package/src/core/forms/binding.ts +148 -1
  91. package/src/core/history/diff.ts +32 -4
  92. package/src/core/image-edit/schema.ts +145 -0
  93. package/src/core/image-edit/summary.ts +58 -0
  94. package/src/core/index.ts +14 -0
  95. package/src/core/limits.ts +10 -0
  96. package/src/core/migrate/index.ts +3 -1
  97. package/src/core/perf/meter.ts +9 -1
  98. package/src/core/render/dynamic-post.ts +23 -6
  99. package/src/core/render/form.ts +36 -11
  100. package/src/core/render/index.ts +75 -15
  101. package/src/core/render/pagination.ts +21 -2
  102. package/src/core/sanitize/embed-url.ts +7 -1
  103. package/src/core/sanitize/href.ts +13 -1
  104. package/src/core/schema/descriptors.ts +4 -1
  105. package/src/core/schema/layout.ts +21 -4
  106. package/src/core/share/link.ts +9 -3
  107. package/src/core/stable-json.ts +15 -0
  108. package/src/core/theme/dynamic.ts +32 -24
  109. package/src/core/theme/pagination.ts +30 -3
  110. package/src/core/theme/popup-rules.ts +10 -5
  111. package/src/mcp/errors.ts +44 -0
  112. package/src/mcp/index.ts +4 -0
  113. package/src/mcp/ports.ts +85 -0
  114. package/src/mcp/prompts.ts +76 -0
  115. package/src/mcp/publish.ts +60 -0
  116. package/src/mcp/queue.ts +19 -0
  117. package/src/mcp/rate-limit.ts +80 -0
  118. package/src/mcp/read.ts +486 -0
  119. package/src/mcp/refs.ts +84 -0
  120. package/src/mcp/settings.ts +18 -0
  121. package/src/mcp/tools.ts +265 -0
  122. package/src/mcp/write.ts +664 -0
  123. package/src/server/agent-settings.ts +159 -0
  124. package/src/server/design-routes.ts +71 -17
  125. package/src/server/icon-routes.ts +13 -6
  126. package/src/server/mcp-routes.ts +323 -0
  127. package/src/server/plugin.ts +32 -2
@@ -0,0 +1,338 @@
1
+ /**
2
+ * The Adjust (and Effects), Filters and Blur panels (W-484).
3
+ *
4
+ * Layout, wording and behaviour follow photocn's `adjustments-panel.tsx`, `filters-panel.tsx` and
5
+ * `blur-panel.tsx` (https://github.com/rbbydotdev/photocn, apps/www/src/registry/image-editor),
6
+ * MIT License, Copyright (c) 2026 rbbydotdev, rebuilt with Kumo components and EmVB tokens. Every
7
+ * slider also takes a typed value.
8
+ */
9
+ import { Button } from "@cloudflare/kumo";
10
+ import {
11
+ ApertureIcon,
12
+ ArrowCounterClockwiseIcon,
13
+ CircleNotchIcon,
14
+ PaletteIcon,
15
+ RecordIcon,
16
+ SparkleIcon,
17
+ SunIcon,
18
+ type Icon,
19
+ } from "@phosphor-icons/react";
20
+ import * as React from "react";
21
+ import { SOLID_PRIMARY } from "../ui.ts";
22
+ import { useImageEditor, type AdjustSection, type AdjustValue, type BlurValue } from "./engine.ts";
23
+ import { IconButton, PanelHeader, SectionTabs, ValueSlider } from "./parts.tsx";
24
+
25
+ type Control = { key: string; label: string };
26
+ type SectionConfig = {
27
+ value: AdjustSection;
28
+ label: string;
29
+ description: string;
30
+ icon: Icon;
31
+ controls: readonly Control[];
32
+ };
33
+
34
+ /** photocn's adjustment sections; every slider runs from −1 to 1 in steps of 0.01. */
35
+ const ADJUST_SECTIONS: readonly SectionConfig[] = [
36
+ {
37
+ value: "lights",
38
+ label: "Light",
39
+ description: "Exposure, contrast, and tonal recovery",
40
+ icon: SunIcon,
41
+ controls: [
42
+ { key: "brightness", label: "Brightness" },
43
+ { key: "exposure", label: "Exposure" },
44
+ { key: "gamma", label: "Gamma" },
45
+ { key: "contrast", label: "Contrast" },
46
+ { key: "shadows", label: "Shadows" },
47
+ { key: "highlights", label: "Highlights" },
48
+ { key: "bloom", label: "Bloom" },
49
+ ],
50
+ },
51
+ {
52
+ value: "colors",
53
+ label: "Color",
54
+ description: "Temperature, tint, and color intensity",
55
+ icon: PaletteIcon,
56
+ controls: [
57
+ { key: "temperature", label: "Temperature" },
58
+ { key: "tint", label: "Tint" },
59
+ { key: "vibrance", label: "Vibrance" },
60
+ { key: "saturation", label: "Saturation" },
61
+ { key: "sepia", label: "Sepia" },
62
+ ],
63
+ },
64
+ {
65
+ value: "effects",
66
+ label: "Effects",
67
+ description: "Texture, grain, and edge falloff",
68
+ icon: SparkleIcon,
69
+ controls: [
70
+ { key: "clarity", label: "Clarity" },
71
+ { key: "noise", label: "Noise" },
72
+ { key: "vignette", label: "Vignette" },
73
+ ],
74
+ },
75
+ ];
76
+
77
+ /** "+0.25", "0.00", "−0.40" as photocn shows them (ASCII minus, so it can be typed back). */
78
+ function formatAdjust(value: number): string {
79
+ const rounded = Math.round(value * 100) / 100;
80
+ return rounded > 0 ? `+${rounded.toFixed(2)}` : rounded.toFixed(2);
81
+ }
82
+
83
+ const tabLabel = (IconC: Icon, text: string) => (
84
+ <span className="emvb-ie-tab-label">
85
+ <IconC aria-hidden="true" />
86
+ {text}
87
+ </span>
88
+ );
89
+
90
+ /** Light, color and effects sliders. The Effects tool opens it on its Effects tab, as photocn does. */
91
+ export function AdjustPanel({ defaultSection = "lights" }: { defaultSection?: AdjustSection }) {
92
+ const editor = useImageEditor();
93
+ const [section, setSection] = React.useState<AdjustSection>(defaultSection);
94
+ React.useEffect(() => setSection(defaultSection), [defaultSection]);
95
+ const disabled = editor.disabled || !editor.hasImage;
96
+ const config = ADJUST_SECTIONS.find((s) => s.value === section) ?? ADJUST_SECTIONS[0];
97
+ if (!config) return null;
98
+ const values = editor.adjust.value[section] as unknown as Record<string, number>;
99
+ const set = (key: string, v: number) => {
100
+ const next = { ...values, [key]: v };
101
+ if (section === "lights") editor.adjust.setLights(next as unknown as AdjustValue["lights"]);
102
+ else if (section === "colors")
103
+ editor.adjust.setColors(next as unknown as AdjustValue["colors"]);
104
+ else editor.adjust.setEffects(next as unknown as AdjustValue["effects"]);
105
+ };
106
+ const sectionDirty = Object.values(values).some((v) => v !== 0);
107
+ return (
108
+ <section aria-label="Adjustments" className="emvb-ie-panel" data-emvb-image-panel={editor.tool}>
109
+ <PanelHeader
110
+ title="Adjustments"
111
+ description="Light, color, and effects"
112
+ onReset={() => editor.adjust.reset()}
113
+ resetDisabled={disabled}
114
+ />
115
+ <div className="emvb-ie-tabs-wrap">
116
+ <SectionTabs
117
+ name="adjust"
118
+ label="Adjustment sections"
119
+ value={section}
120
+ items={ADJUST_SECTIONS.map((s) => ({ value: s.value, label: tabLabel(s.icon, s.label) }))}
121
+ onChange={setSection}
122
+ />
123
+ </div>
124
+ <hr className="emvb-ie-sep" />
125
+ <fieldset className="emvb-ie-group emvb-ie-group-sliders" data-emvb-image-section={section}>
126
+ <legend className="emvb-ie-sr">{config.label}</legend>
127
+ <div className="emvb-ie-row emvb-ie-row-between emvb-ie-section-head">
128
+ <div className="emvb-ie-section-titles">
129
+ <span className="emvb-ie-section-title">{config.label}</span>
130
+ <span className="emvb-ie-section-desc">{config.description}</span>
131
+ </div>
132
+ <IconButton
133
+ label={`Reset ${config.label.toLowerCase()}`}
134
+ icon={<ArrowCounterClockwiseIcon aria-hidden="true" />}
135
+ disabled={disabled || !sectionDirty}
136
+ onClick={() => editor.adjust.resetSection(section)}
137
+ data-emvb-image-section-reset={section}
138
+ />
139
+ </div>
140
+ {config.controls.map((control) => (
141
+ <ValueSlider
142
+ key={`${section}-${control.key}`}
143
+ name={control.key}
144
+ label={control.label}
145
+ min={-1}
146
+ max={1}
147
+ step={0.01}
148
+ value={values[control.key] ?? 0}
149
+ disabled={disabled}
150
+ format={formatAdjust}
151
+ onChange={(v) => set(control.key, v)}
152
+ onCommit={() => editor.commit()}
153
+ />
154
+ ))}
155
+ </fieldset>
156
+ </section>
157
+ );
158
+ }
159
+
160
+ /** photocn names its looks in lower case ("crema"); the button says "Crema". */
161
+ const title = (label: string) => label.charAt(0).toUpperCase() + label.slice(1);
162
+
163
+ const pct = (v: number) => `${Math.round(v)}%`;
164
+ const toPct = (v: number) => Math.round(Math.min(1, Math.max(0, v)) * 100);
165
+
166
+ /** photocn's 13 looks (9 LUTs, 4 colour matrices) and a strength slider once one is chosen. */
167
+ export function FiltersPanel() {
168
+ const editor = useImageEditor();
169
+ const [loading, setLoading] = React.useState<string | null>(null);
170
+ const disabled = editor.disabled || !editor.hasImage;
171
+ const active = editor.filters.value.label;
172
+ const busy = loading !== null;
173
+ const choose = async (preset: (typeof editor.filters.presets)[number]) => {
174
+ if (disabled || busy) return;
175
+ setLoading(preset.label);
176
+ try {
177
+ const opt = await preset.load();
178
+ editor.patch("filters", { opt, mix: 0 });
179
+ } finally {
180
+ setLoading(null);
181
+ }
182
+ };
183
+ const chip = (label: string, selected: boolean, onClick: () => void, isLoading = false) => (
184
+ <Button
185
+ key={label}
186
+ type="button"
187
+ size="sm"
188
+ variant={selected ? "primary" : "outline"}
189
+ className="emvb-ie-btn emvb-ie-chip"
190
+ style={selected ? SOLID_PRIMARY : undefined}
191
+ aria-pressed={selected}
192
+ disabled={disabled || (busy && !isLoading)}
193
+ onClick={onClick}
194
+ data-emvb-image-filter={label}
195
+ >
196
+ {isLoading ? (
197
+ <>
198
+ <CircleNotchIcon aria-hidden="true" className="emvb-ie-spin" />
199
+ <span className="emvb-ie-sr">Loading {title(label)}</span>
200
+ </>
201
+ ) : (
202
+ title(label)
203
+ )}
204
+ </Button>
205
+ );
206
+ return (
207
+ <section aria-label="Filters" className="emvb-ie-panel" data-emvb-image-panel="filters">
208
+ <PanelHeader
209
+ title="Filters"
210
+ description="Film-style looks"
211
+ onReset={() => editor.filters.reset()}
212
+ resetDisabled={disabled}
213
+ />
214
+ <div className="emvb-ie-group emvb-ie-group-sliders">
215
+ <div className="emvb-ie-chips" role="group" aria-label="Looks">
216
+ {chip("None", active === null, () => {
217
+ if (!disabled && !busy) void editor.filters.select(null);
218
+ })}
219
+ {editor.filters.presets.map((preset) =>
220
+ chip(
221
+ preset.label,
222
+ active === preset.label,
223
+ () => void choose(preset),
224
+ loading === preset.label,
225
+ ),
226
+ )}
227
+ </div>
228
+ {active !== null ? (
229
+ <ValueSlider
230
+ name="filter-strength"
231
+ label="Strength"
232
+ min={0}
233
+ max={100}
234
+ step={1}
235
+ value={toPct(editor.filters.value.strength)}
236
+ disabled={disabled}
237
+ format={pct}
238
+ onChange={(v) => editor.filters.setStrength(v / 100)}
239
+ onCommit={() => editor.commit()}
240
+ />
241
+ ) : null}
242
+ </div>
243
+ </section>
244
+ );
245
+ }
246
+
247
+ type BlurKind = "bokeh" | "gaussian";
248
+ const BLUR_KINDS: readonly {
249
+ value: BlurKind;
250
+ label: string;
251
+ icon: Icon;
252
+ strength: "bokehStrength" | "gaussianStrength";
253
+ radius: "bokehLensOut" | "gaussianLensOut";
254
+ }[] = [
255
+ {
256
+ value: "bokeh",
257
+ label: "Bokeh",
258
+ icon: ApertureIcon,
259
+ strength: "bokehStrength",
260
+ radius: "bokehLensOut",
261
+ },
262
+ {
263
+ value: "gaussian",
264
+ label: "Gaussian",
265
+ icon: RecordIcon,
266
+ strength: "gaussianStrength",
267
+ radius: "gaussianLensOut",
268
+ },
269
+ ];
270
+
271
+ const BLUR_DEFAULT: BlurValue = {
272
+ bokehStrength: 0,
273
+ bokehLensOut: 0.5,
274
+ gaussianStrength: 0,
275
+ gaussianLensOut: 0.5,
276
+ centerX: 0.5,
277
+ centerY: 0.5,
278
+ };
279
+
280
+ const isBlurDefault = (v: BlurValue) =>
281
+ (Object.keys(BLUR_DEFAULT) as (keyof BlurValue)[]).every((k) => v[k] === BLUR_DEFAULT[k]);
282
+
283
+ /** Bokeh or Gaussian strength and radius, and the sharp spot (also draggable on the image). */
284
+ export function BlurPanel() {
285
+ const editor = useImageEditor();
286
+ const [kind, setKind] = React.useState<BlurKind>("bokeh");
287
+ const disabled = editor.disabled || !editor.hasImage;
288
+ const value = editor.blur.value;
289
+ const config = BLUR_KINDS.find((k) => k.value === kind) ?? BLUR_KINDS[0];
290
+ if (!config) return null;
291
+ const set = (key: keyof BlurValue, percent: number) =>
292
+ editor.blur.set({ ...value, [key]: percent / 100 });
293
+ const slider = (name: string, label: string, key: keyof BlurValue) => (
294
+ <ValueSlider
295
+ key={name}
296
+ name={name}
297
+ label={label}
298
+ min={0}
299
+ max={100}
300
+ step={1}
301
+ value={toPct(value[key])}
302
+ disabled={disabled}
303
+ format={pct}
304
+ onChange={(v) => set(key, v)}
305
+ onCommit={() => editor.commit()}
306
+ />
307
+ );
308
+ return (
309
+ <section aria-label="Blur" className="emvb-ie-panel" data-emvb-image-panel="blur">
310
+ <PanelHeader
311
+ title="Blur"
312
+ description="Bokeh and gaussian blur"
313
+ onReset={() => editor.blur.reset()}
314
+ resetDisabled={disabled || isBlurDefault(value)}
315
+ />
316
+ <div className="emvb-ie-tabs-wrap">
317
+ <SectionTabs
318
+ name="blur"
319
+ label="Blur kind"
320
+ value={kind}
321
+ items={BLUR_KINDS.map((k) => ({ value: k.value, label: tabLabel(k.icon, k.label) }))}
322
+ onChange={setKind}
323
+ />
324
+ </div>
325
+ <hr className="emvb-ie-sep" />
326
+ <div className="emvb-ie-group emvb-ie-group-sliders" data-emvb-image-section={kind}>
327
+ {slider(`${kind}-strength`, "Strength", config.strength)}
328
+ {slider(`${kind}-radius`, "Radius", config.radius)}
329
+ <hr className="emvb-ie-sep" />
330
+ <fieldset className="emvb-ie-subgroup">
331
+ <legend className="emvb-ie-caps">Center</legend>
332
+ {slider("center-x", "X", "centerX")}
333
+ {slider("center-y", "Y", "centerY")}
334
+ </fieldset>
335
+ </div>
336
+ </section>
337
+ );
338
+ }
@@ -0,0 +1,59 @@
1
+ /**
2
+ * The image editor's tools, in photocn's order (W-483). The ids are photocn's tool ids, so the
3
+ * crop tool is "compose" (its crop view) and the panels can come straight from its hook.
4
+ */
5
+ export const IMAGE_EDITOR_TOOLS = [
6
+ { id: "adjust", label: "Adjust", blurb: "Light, color, and effects" },
7
+ { id: "compose", label: "Crop", blurb: "Drag the frame on the image to crop" },
8
+ { id: "curves", label: "Curves", blurb: "RGB and per-channel tone curves" },
9
+ { id: "effects", label: "Effects", blurb: "Texture, grain, and edge falloff" },
10
+ { id: "filters", label: "Filters", blurb: "Film-style looks" },
11
+ { id: "blender", label: "Blender", blurb: "Blend a second picture into this one" },
12
+ { id: "blur", label: "Blur", blurb: "Bokeh and gaussian blur" },
13
+ { id: "metadata", label: "Metadata", blurb: "File details and camera data" },
14
+ ] as const;
15
+
16
+ export type ImageEditorToolId = (typeof IMAGE_EDITOR_TOOLS)[number]["id"];
17
+
18
+ /** Tools whose panels land in a later work item; they show what's coming. */
19
+ export const COMING_SOON: Record<"blender", readonly string[]> = {
20
+ blender: ["Blend a picture from your media library", "A mix slider"],
21
+ };
22
+
23
+ /** "4032 × 3024 px". */
24
+ export const sizeLabel = (width: number, height: number) => `${width} × ${height} px`;
25
+
26
+ /** Media-library keys look like ULIDs; the alt text says more about the picture than that. */
27
+ const STORAGE_KEY = /^[0-9A-HJKMNP-TV-Z]{26}\.[a-z0-9]+$/i;
28
+
29
+ /** The name shown in the editor: the file name, unless it is a storage key. */
30
+ export function displayName(fileName: string, alt: unknown): string {
31
+ if (!STORAGE_KEY.test(fileName)) return fileName;
32
+ return typeof alt === "string" && alt.trim() ? alt.trim() : "Library picture";
33
+ }
34
+
35
+ /** The widest aspect ratio the edit record accepts (core/image-edit/schema.ts). */
36
+ export const MAX_ASPECT = 100;
37
+
38
+ const gcd = (a: number, b: number): number => (b ? gcd(b, a % b) : a);
39
+
40
+ /**
41
+ * W-483 "Fit this element": a crop preset with the Image element's own width and height, so the
42
+ * saved picture fills it without being cut. Landscape-first like photocn's presets (its portrait
43
+ * toggle turns it); undefined when the element has no usable size or it equals a square.
44
+ */
45
+ export function elementAspectOption(
46
+ width: unknown,
47
+ height: unknown,
48
+ ): { value: string; label: string } | undefined {
49
+ if (typeof width !== "number" || typeof height !== "number") return undefined;
50
+ const w = Math.round(width);
51
+ const h = Math.round(height);
52
+ if (w < 1 || h < 1 || w > 100_000 || h > 100_000) return undefined;
53
+ // W-494: the edit record holds ratios from 1:100 to 100:1; a longer strip couldn't be saved.
54
+ if (Math.max(w, h) / Math.min(w, h) > MAX_ASPECT) return undefined;
55
+ const d = gcd(w, h);
56
+ const [a, b] = w >= h ? [w / d, h / d] : [h / d, w / d];
57
+ // Ratios like 1279:719 read as noise; the label keeps the element size instead.
58
+ return { value: `${a}:${b}`, label: `Fit this element (${w} × ${h})` };
59
+ }
@@ -0,0 +1,111 @@
1
+ /**
2
+ * photocn render-worker strategy for the EmDash admin (D-059).
3
+ *
4
+ * photocn's default worker is a `blob:` URL, which the `/_emdash` CSP blocks
5
+ * (no `worker-src`, so `script-src 'self'` applies). We hand photocn a
6
+ * same-origin module worker that the host's Vite bundles from
7
+ * `photocn/worker/entry`, probe it once, and fall back to main-thread
8
+ * rendering when it can't start. Never a `blob:` worker.
9
+ *
10
+ * Only the lazily imported image editor chunk may import this file.
11
+ */
12
+
13
+ import type { CreatePhotoOptions } from "photocn/photo";
14
+
15
+ export type RenderMode = NonNullable<CreatePhotoOptions["renderMode"]>;
16
+
17
+ export interface RenderPlan {
18
+ renderMode: RenderMode;
19
+ spawnWorker?: CreatePhotoOptions["spawnWorker"];
20
+ /** Why the main thread was chosen, for the status bar. */
21
+ reason?: string;
22
+ }
23
+
24
+ /** A same-origin module worker; Vite emits it as a `/_astro/…` (or dev) asset. */
25
+ function spawnPhotoWorker(): Worker {
26
+ return new Worker(new URL("photocn/worker/entry", import.meta.url), { type: "module" });
27
+ }
28
+
29
+ interface WorkerEnv {
30
+ hasWorker: boolean;
31
+ hasOffscreenCanvas: boolean;
32
+ canTransfer: boolean;
33
+ }
34
+
35
+ function readWorkerEnv(g: typeof globalThis = globalThis): WorkerEnv {
36
+ const canvasProto = (g as { HTMLCanvasElement?: { prototype: object } }).HTMLCanvasElement
37
+ ?.prototype;
38
+ return {
39
+ hasWorker: typeof (g as { Worker?: unknown }).Worker === "function",
40
+ hasOffscreenCanvas: typeof (g as { OffscreenCanvas?: unknown }).OffscreenCanvas === "function",
41
+ canTransfer: !!canvasProto && "transferControlToOffscreen" in canvasProto,
42
+ };
43
+ }
44
+
45
+ /**
46
+ * Start a worker and wait for proof it runs: photocn's worker answers a
47
+ * stateless `dispose` request with `{ type: "ok" }`. A CSP block, a 404 or
48
+ * a syntax error shows up as a throw, an `error` event or a timeout.
49
+ */
50
+ export function probeWorker(spawn: () => Worker, timeoutMs = 4000): Promise<true | string> {
51
+ return new Promise((resolve) => {
52
+ let worker: Worker;
53
+ try {
54
+ worker = spawn();
55
+ } catch (err) {
56
+ resolve(`Worker blocked: ${err instanceof Error ? err.message : String(err)}`);
57
+ return;
58
+ }
59
+ const done = (result: true | string) => {
60
+ clearTimeout(timer);
61
+ worker.terminate();
62
+ resolve(result);
63
+ };
64
+ const timer = setTimeout(() => done("Worker did not start in time"), timeoutMs);
65
+ worker.addEventListener("message", (event: MessageEvent) => {
66
+ const data = event.data as { type?: string; reqId?: number } | null;
67
+ if (data?.reqId === -480 && data.type === "ok") done(true);
68
+ });
69
+ worker.addEventListener("error", (event) => {
70
+ event.preventDefault?.();
71
+ done("Worker failed to load");
72
+ });
73
+ // A Worker's postMessage has no targetOrigin.
74
+ // oxlint-disable-next-line unicorn/require-post-message-target-origin
75
+ worker.postMessage({ type: "dispose", reqId: -480 });
76
+ });
77
+ }
78
+
79
+ /** Decide where photocn renders. Cached per page load. */
80
+ let cached: Promise<RenderPlan> | undefined;
81
+
82
+ export function planRendering(
83
+ options: { force?: RenderMode; spawn?: () => Worker; env?: WorkerEnv } = {},
84
+ ): Promise<RenderPlan> {
85
+ if (options.force === "main") return Promise.resolve({ renderMode: "main", reason: "Forced" });
86
+ if (!options.spawn && !options.env && !options.force && cached) return cached;
87
+ const env = options.env ?? readWorkerEnv();
88
+ const spawn = options.spawn ?? spawnPhotoWorker;
89
+ const plan: Promise<RenderPlan> =
90
+ !env.hasWorker || !env.hasOffscreenCanvas || !env.canTransfer
91
+ ? Promise.resolve({
92
+ renderMode: "main",
93
+ reason: "This browser can't render off the main thread",
94
+ })
95
+ : probeWorker(spawn).then((ok) =>
96
+ ok === true
97
+ ? { renderMode: "worker", spawnWorker: spawn }
98
+ : { renderMode: "main", reason: ok },
99
+ );
100
+ if (!options.spawn && !options.env && !options.force) cached = plan;
101
+ return plan;
102
+ }
103
+
104
+ /** WebGL2 is required either way; without it the editor shows "Can't edit here". */
105
+ export function hasWebGL2(doc: Document = document): boolean {
106
+ try {
107
+ return !!doc.createElement("canvas").getContext("webgl2");
108
+ } catch {
109
+ return false;
110
+ }
111
+ }
@@ -3,15 +3,17 @@ import { installSidebarShim } from "./access/sidebar-shim.ts";
3
3
  import { defaultFetcher } from "./api.ts";
4
4
  import { EditorPage } from "./pages/EditorPage.tsx";
5
5
  import { PagesPage } from "./pages/PagesPage.tsx";
6
+ import { AgentsPage } from "./pages/AgentsPage.tsx";
6
7
  import { ThemeBuilderPage } from "./pages/ThemeBuilderPage.tsx";
7
8
  import { LayoutField } from "./widgets/LayoutField.tsx";
8
9
 
9
10
  if (typeof document !== "undefined") void installSidebarShim(document, defaultFetcher);
10
11
 
11
- /** `/pages` and `/theme` are declared; `/editor` renders by URL (D-024). */
12
+ /** `/pages`, `/theme` and `/agents` are declared; `/editor` renders by URL (D-024). */
12
13
  export const pages: PluginAdminExports["pages"] = {
13
14
  "/pages": PagesPage,
14
15
  "/theme": ThemeBuilderPage,
16
+ "/agents": AgentsPage,
15
17
  "/editor": EditorPage,
16
18
  };
17
19
 
@@ -53,16 +53,146 @@ export async function uploadImage(
53
53
  return payload.data.item;
54
54
  }
55
55
 
56
+ /** Applies a pasted URL onto an image node's props; the URL is already sanitized. */
57
+ export function propsFromUrl(
58
+ current: Record<string, unknown>,
59
+ src: string,
60
+ ): Record<string, unknown> {
61
+ const next: Record<string, unknown> = { ...current, src };
62
+ delete next.mediaId;
63
+ if (current.src === src) return next;
64
+ // W-422: a different picture drops the old one's extra sizes.
65
+ delete next.sources;
66
+ // W-482: an image-editor record describes the old picture; kept, re-opening would edit it.
67
+ delete next.edit;
68
+ // W-425: a library image's width and height describe that file, not the pasted one.
69
+ if (current.mediaId) {
70
+ delete next.width;
71
+ delete next.height;
72
+ }
73
+ return next;
74
+ }
75
+
76
+ /** The layout's Image width and height top out at 10000 (core/schema/layout.ts). */
77
+ const MAX_IMAGE_SIDE = 10_000;
78
+
79
+ /**
80
+ * W-496: a library picture over 10000 px on a side would be written as-is and the whole draft
81
+ * refused. Its size only sets the aspect ratio, so it is scaled down to fit, keeping the ratio.
82
+ */
83
+ function fitImageSize(
84
+ next: Record<string, unknown>,
85
+ width: number | undefined | null,
86
+ height: number | undefined | null,
87
+ ): void {
88
+ if (!width || !height) {
89
+ if (width) next.width = Math.min(Math.round(width), MAX_IMAGE_SIDE);
90
+ if (height) next.height = Math.min(Math.round(height), MAX_IMAGE_SIDE);
91
+ return;
92
+ }
93
+ const scale = Math.min(1, MAX_IMAGE_SIDE / Math.max(width, height));
94
+ next.width = Math.max(1, Math.round(width * scale));
95
+ next.height = Math.max(1, Math.round(height * scale));
96
+ }
97
+
56
98
  /** Applies a library item onto an image node's props (id, URL, alt, dimensions). */
57
99
  export function propsFromMedia(
58
100
  current: Record<string, unknown>,
59
101
  item: MediaLibraryItem,
60
102
  ): Record<string, unknown> {
61
103
  const next: Record<string, unknown> = { ...current, src: item.url, mediaId: item.id };
62
- if (item.width) next.width = item.width;
63
- if (item.height) next.height = item.height;
104
+ // W-422: extra sizes belong to the old picture; kept, the browser could still show it.
105
+ if (current.src !== item.url) {
106
+ delete next.sources;
107
+ // W-482: the image-editor record belongs to the old picture.
108
+ delete next.edit;
109
+ }
110
+ fitImageSize(next, item.width, item.height);
64
111
  const alt = current.alt;
65
112
  if ((!alt || alt === "Image") && item.alt) next.alt = item.alt;
66
113
  else if (!alt || alt === "Image") next.alt = item.filename.replace(/\.[^.]+$/, "") || "Image";
67
114
  return next;
68
115
  }
116
+
117
+ /** One library item by id (EmDash GET /_emdash/api/media/:id); null when it is gone. */
118
+ export async function getMedia(fetcher: Fetcher, id: string): Promise<MediaLibraryItem | null> {
119
+ const response = await fetcher(`${MEDIA_API_PATH}/${encodeURIComponent(id)}`);
120
+ if (response.status === 404) return null;
121
+ const payload = await readEnvelope<{ item?: MediaLibraryItem } & Partial<MediaLibraryItem>>(
122
+ response,
123
+ );
124
+ if (!response.ok) throw envelopeError(response, payload);
125
+ const data = payload.data;
126
+ const item = data?.item ?? (data?.id ? (data as MediaLibraryItem) : null);
127
+ if (!item) return null;
128
+ // GET by id has no `url` (only the list adds it); build the same file path.
129
+ return item.url ? item : { ...item, url: `${MEDIA_API_PATH}/file/${item.storageKey}` };
130
+ }
131
+
132
+ /**
133
+ * An edited copy replaces the picture (W-485): the new file's id, URL and size, plus the edit
134
+ * record. Extra sizes belonged to the old file, so they go; alt and the rest stay.
135
+ */
136
+ export function propsFromEdited(
137
+ current: Record<string, unknown>,
138
+ item: Pick<MediaLibraryItem, "id" | "url" | "width" | "height">,
139
+ edit: unknown,
140
+ ): Record<string, unknown> {
141
+ const next: Record<string, unknown> = { ...current, src: item.url, edit };
142
+ next.mediaId = item.id;
143
+ delete next.sources;
144
+ fitImageSize(next, item.width, item.height);
145
+ return next;
146
+ }
147
+
148
+ /**
149
+ * "Reset to original" (W-485): back to the untouched file. The edited copy stays in the library.
150
+ * Without the library item (deleted, or no id) the recorded URL is used and the size is dropped.
151
+ */
152
+ export function propsFromOriginal(
153
+ current: Record<string, unknown>,
154
+ original: Pick<MediaLibraryItem, "id" | "url" | "width" | "height"> | null,
155
+ ): Record<string, unknown> | null {
156
+ const edit = current.edit as { originalSrc?: unknown } | undefined;
157
+ const originalSrc = typeof edit?.originalSrc === "string" ? edit.originalSrc : "";
158
+ if (!original && !originalSrc) return null;
159
+ const next: Record<string, unknown> = { ...current };
160
+ delete next.edit;
161
+ delete next.sources;
162
+ if (original) {
163
+ next.src = original.url || originalSrc;
164
+ next.mediaId = original.id;
165
+ delete next.width;
166
+ delete next.height;
167
+ fitImageSize(next, original.width, original.height);
168
+ } else {
169
+ next.src = originalSrc;
170
+ delete next.mediaId;
171
+ delete next.width;
172
+ delete next.height;
173
+ }
174
+ return next;
175
+ }
176
+
177
+ /**
178
+ * Uploads an edited copy and returns the element's new props (W-485/W-486): shared by Image
179
+ * settings, the media picker's Edit… and the command palette.
180
+ */
181
+ export async function saveEditedCopy(
182
+ fetcher: Fetcher,
183
+ current: Record<string, unknown>,
184
+ file: File,
185
+ copy: { width: number; height: number; edit: unknown },
186
+ ): Promise<Record<string, unknown>> {
187
+ const alt = typeof current.alt === "string" && current.alt !== "Image" ? current.alt : undefined;
188
+ const item = await uploadImage(fetcher, file, {
189
+ width: copy.width,
190
+ height: copy.height,
191
+ ...(alt ? { alt } : {}),
192
+ });
193
+ return propsFromEdited(
194
+ current,
195
+ { ...item, width: item.width ?? copy.width, height: item.height ?? copy.height },
196
+ copy.edit,
197
+ );
198
+ }