@perkyzz/emvb 0.5.0 → 0.7.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 (212) 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/access/RequireEditor.tsx +7 -7
  10. package/src/admin/access/role.ts +5 -2
  11. package/src/admin/content-api.ts +10 -3
  12. package/src/admin/content-item.ts +1 -1
  13. package/src/admin/editor/A11yCopilot.tsx +104 -56
  14. package/src/admin/editor/CommandPalette.tsx +29 -13
  15. package/src/admin/editor/Editor.tsx +88 -20
  16. package/src/admin/editor/EditorToasts.tsx +26 -0
  17. package/src/admin/editor/PerfMeter.tsx +97 -72
  18. package/src/admin/editor/ShareLink.tsx +107 -72
  19. package/src/admin/editor/ShortcutsDialog.tsx +27 -16
  20. package/src/admin/editor/Timeline.tsx +255 -160
  21. package/src/admin/editor/TopBar.tsx +71 -14
  22. package/src/admin/editor/canvas/CanvasFrame.tsx +10 -1
  23. package/src/admin/editor/canvas/CanvasTextEdit.tsx +8 -2
  24. package/src/admin/editor/canvas/drop-line.ts +11 -3
  25. package/src/admin/editor/canvas/frame-focus-ring.ts +37 -0
  26. package/src/admin/editor/canvas/use-canvas-dnd.ts +32 -3
  27. package/src/admin/editor/canvas/vnode-react.tsx +7 -0
  28. package/src/admin/editor/collection-previews.ts +16 -1
  29. package/src/admin/editor/dialogs.tsx +38 -14
  30. package/src/admin/editor/dnd/drop-target.ts +26 -1
  31. package/src/admin/editor/edited-noun.ts +15 -0
  32. package/src/admin/editor/editor-chrome.tsx +108 -7
  33. package/src/admin/editor/editor-commands.ts +15 -1
  34. package/src/admin/editor/editor-css.ts +75 -22
  35. package/src/admin/editor/element-chrome.ts +21 -11
  36. package/src/admin/editor/feature-css.ts +45 -13
  37. package/src/admin/editor/icons/IconLibraryDialog.tsx +52 -11
  38. package/src/admin/editor/icons/library.ts +1 -1
  39. package/src/admin/editor/icons/use-icon-library.ts +5 -2
  40. package/src/admin/editor/ime.ts +29 -0
  41. package/src/admin/editor/palette-items.ts +10 -3
  42. package/src/admin/editor/panels/AddPanel.tsx +35 -10
  43. package/src/admin/editor/panels/ClassesSection.tsx +18 -7
  44. package/src/admin/editor/panels/ColorControl.tsx +135 -27
  45. package/src/admin/editor/panels/ConditionsEditor.tsx +52 -26
  46. package/src/admin/editor/panels/ElementPanel.tsx +134 -24
  47. package/src/admin/editor/panels/LayersPanel.tsx +68 -22
  48. package/src/admin/editor/panels/PageSettings.tsx +66 -35
  49. package/src/admin/editor/panels/SiteStylesDrawer.tsx +170 -32
  50. package/src/admin/editor/panels/TokenScales.tsx +76 -36
  51. package/src/admin/editor/panels/TriggerSettings.tsx +50 -12
  52. package/src/admin/editor/panels/TriggersEditor.tsx +2 -1
  53. package/src/admin/editor/panels/VariableSection.tsx +53 -21
  54. package/src/admin/editor/panels/color-space.ts +9 -3
  55. package/src/admin/editor/panels/settings/AdvancedFields.tsx +12 -2
  56. package/src/admin/editor/panels/settings/AudienceEditor.tsx +51 -35
  57. package/src/admin/editor/panels/settings/BackgroundControls.tsx +55 -11
  58. package/src/admin/editor/panels/settings/BackgroundFill.tsx +3 -2
  59. package/src/admin/editor/panels/settings/BindingsEditor.tsx +15 -18
  60. package/src/admin/editor/panels/settings/BoxControl.tsx +2 -1
  61. package/src/admin/editor/panels/settings/ClassChip.tsx +21 -9
  62. package/src/admin/editor/panels/settings/ClassChipInput.tsx +24 -16
  63. package/src/admin/editor/panels/settings/DraftTextField.tsx +41 -3
  64. package/src/admin/editor/panels/settings/EffectsControls.tsx +38 -14
  65. package/src/admin/editor/panels/settings/FieldBindControl.tsx +46 -28
  66. package/src/admin/editor/panels/settings/FieldControl.tsx +38 -15
  67. package/src/admin/editor/panels/settings/FormBindControl.tsx +2 -2
  68. package/src/admin/editor/panels/settings/HintedSwitch.tsx +33 -0
  69. package/src/admin/editor/panels/settings/IconControls.tsx +12 -8
  70. package/src/admin/editor/panels/settings/IconPicker.tsx +2 -0
  71. package/src/admin/editor/panels/settings/ImageSourcesField.tsx +3 -1
  72. package/src/admin/editor/panels/settings/ItemList.tsx +15 -2
  73. package/src/admin/editor/panels/settings/LengthRow.tsx +8 -6
  74. package/src/admin/editor/panels/settings/MediaPicker.tsx +274 -20
  75. package/src/admin/editor/panels/settings/MotionControl.tsx +28 -15
  76. package/src/admin/editor/panels/settings/NumberRow.tsx +9 -3
  77. package/src/admin/editor/panels/settings/PanelSelect.tsx +50 -0
  78. package/src/admin/editor/panels/settings/QueryStyleRows.tsx +25 -18
  79. package/src/admin/editor/panels/settings/RequiredFieldsNotice.tsx +141 -0
  80. package/src/admin/editor/panels/settings/StyleRow.tsx +10 -3
  81. package/src/admin/editor/panels/settings/StyleSources.tsx +4 -1
  82. package/src/admin/editor/panels/settings/VariantEditor.tsx +10 -1
  83. package/src/admin/editor/panels/settings/box-link-name.ts +6 -2
  84. package/src/admin/editor/panels/settings/class-suggest.ts +7 -7
  85. package/src/admin/editor/panels/settings/query-style.ts +38 -9
  86. package/src/admin/editor/panels/settings/svg-images.ts +13 -0
  87. package/src/admin/editor/panels/site-list.tsx +20 -6
  88. package/src/admin/editor/panels/variable-values.ts +25 -4
  89. package/src/admin/editor/restore-deleted.ts +21 -2
  90. package/src/admin/editor/section-templates.ts +81 -12
  91. package/src/admin/editor/shortcuts.ts +17 -2
  92. package/src/admin/editor/store.ts +14 -3
  93. package/src/admin/editor/useEditorCommands.ts +61 -15
  94. package/src/admin/editor/useEditorData.ts +4 -2
  95. package/src/admin/editor/useEditorShortcuts.ts +17 -7
  96. package/src/admin/editor/useNodeActions.ts +61 -6
  97. package/src/admin/editor/useSave.ts +22 -7
  98. package/src/admin/forms-api.ts +2 -0
  99. package/src/admin/image-editor/BlurFocus.tsx +112 -0
  100. package/src/admin/image-editor/Canvas.tsx +261 -0
  101. package/src/admin/image-editor/CropOverlay.tsx +390 -0
  102. package/src/admin/image-editor/CurvesPanel.tsx +395 -0
  103. package/src/admin/image-editor/ExportDialog.tsx +384 -0
  104. package/src/admin/image-editor/ImageEditButton.tsx +83 -0
  105. package/src/admin/image-editor/ImageEditorDialog.tsx +828 -0
  106. package/src/admin/image-editor/MetadataPanel.tsx +194 -0
  107. package/src/admin/image-editor/announce.tsx +65 -0
  108. package/src/admin/image-editor/crop-geometry.ts +162 -0
  109. package/src/admin/image-editor/curve-math.ts +177 -0
  110. package/src/admin/image-editor/data-url-fetch.ts +59 -0
  111. package/src/admin/image-editor/engine.ts +55 -0
  112. package/src/admin/image-editor/exif.ts +82 -0
  113. package/src/admin/image-editor/flatten.ts +54 -0
  114. package/src/admin/image-editor/gpu-fit.ts +81 -0
  115. package/src/admin/image-editor/image-editor-css.ts +400 -0
  116. package/src/admin/image-editor/load.ts +116 -0
  117. package/src/admin/image-editor/panels.tsx +287 -0
  118. package/src/admin/image-editor/parts.tsx +614 -0
  119. package/src/admin/image-editor/save.ts +141 -0
  120. package/src/admin/image-editor/tone-panels.tsx +338 -0
  121. package/src/admin/image-editor/tools.ts +59 -0
  122. package/src/admin/image-editor/worker.ts +111 -0
  123. package/src/admin/media-api.ts +114 -3
  124. package/src/admin/pages/AgentsPage.tsx +138 -27
  125. package/src/admin/pages/CreateDialog.tsx +97 -30
  126. package/src/admin/pages/NewPageDialog.tsx +21 -3
  127. package/src/admin/pages/NewThemePartDialog.tsx +11 -3
  128. package/src/admin/pages/PageList.tsx +14 -6
  129. package/src/admin/pages/SetupShell.tsx +28 -12
  130. package/src/admin/pages/ThemePartList.tsx +27 -7
  131. package/src/admin/pages/list-kit.tsx +106 -24
  132. package/src/admin/search.ts +15 -0
  133. package/src/admin/setup/useSetupStatus.ts +1 -1
  134. package/src/admin/theme-api.ts +13 -3
  135. package/src/admin/ui.ts +78 -22
  136. package/src/astro/EmVBPage.astro +11 -2
  137. package/src/astro/floats/runtime.ts +21 -0
  138. package/src/astro/menu/runtime.ts +34 -1
  139. package/src/astro/popups/runtime.ts +33 -3
  140. package/src/astro/render.ts +6 -0
  141. package/src/astro/resolve-theme.ts +67 -14
  142. package/src/astro/resolve.ts +9 -1
  143. package/src/astro/tabs/runtime.ts +12 -0
  144. package/src/astro/theme-posts.ts +2 -2
  145. package/src/astro/visitor.ts +6 -3
  146. package/src/constants.ts +1 -1
  147. package/src/core/a11y/audit.ts +171 -24
  148. package/src/core/arrange.ts +29 -6
  149. package/src/core/audience/rules.ts +5 -1
  150. package/src/core/audience/variants.ts +29 -3
  151. package/src/core/clipboard.ts +7 -0
  152. package/src/core/css/generate.ts +31 -6
  153. package/src/core/data/bindings.ts +19 -6
  154. package/src/core/design/classes.ts +20 -9
  155. package/src/core/design/diff.ts +9 -1
  156. package/src/core/design/merge.ts +93 -3
  157. package/src/core/design/tokens.ts +16 -2
  158. package/src/core/design/transfer.ts +46 -8
  159. package/src/core/design/variables.ts +32 -10
  160. package/src/core/elements/dynamic-elements.ts +53 -6
  161. package/src/core/elements/form-elements.ts +68 -30
  162. package/src/core/elements/index.ts +83 -38
  163. package/src/core/elements/menu.ts +37 -19
  164. package/src/core/elements/plain-text.ts +2 -2
  165. package/src/core/elements/select-prompt.ts +3 -0
  166. package/src/core/elements/svg-ids.ts +39 -0
  167. package/src/core/forms/binding.ts +190 -2
  168. package/src/core/forms/definition.ts +72 -0
  169. package/src/core/history/diff.ts +49 -4
  170. package/src/core/icons/catalog.ts +3 -2
  171. package/src/core/image-edit/schema.ts +155 -0
  172. package/src/core/image-edit/summary.ts +61 -0
  173. package/src/core/index.ts +29 -1
  174. package/src/core/limits.ts +21 -0
  175. package/src/core/migrate/index.ts +3 -1
  176. package/src/core/perf/meter.ts +51 -8
  177. package/src/core/recipes/index.ts +5 -4
  178. package/src/core/render/context.ts +8 -0
  179. package/src/core/render/dynamic-post.ts +71 -13
  180. package/src/core/render/extras.ts +77 -4
  181. package/src/core/render/form.ts +164 -12
  182. package/src/core/render/index.ts +179 -22
  183. package/src/core/render/loop.ts +43 -7
  184. package/src/core/render/pagination.ts +18 -4
  185. package/src/core/render/section.ts +27 -0
  186. package/src/core/render/tabs.ts +12 -3
  187. package/src/core/render/vnode.ts +1 -1
  188. package/src/core/sanitize/css.ts +15 -2
  189. package/src/core/sanitize/embed-url.ts +42 -5
  190. package/src/core/sanitize/url.ts +2 -1
  191. package/src/core/schema/layout.ts +26 -7
  192. package/src/core/share/link.ts +5 -2
  193. package/src/core/stable-json.ts +15 -0
  194. package/src/core/stats.ts +2 -1
  195. package/src/core/theme/conditions.ts +3 -1
  196. package/src/core/theme/dynamic.ts +57 -23
  197. package/src/core/theme/float.ts +9 -2
  198. package/src/core/theme/pagination.ts +57 -10
  199. package/src/core/theme/popup-markup.ts +23 -5
  200. package/src/core/theme/popup-rules.ts +11 -5
  201. package/src/core/theme/triggers.ts +3 -2
  202. package/src/core/tree-ops.ts +27 -0
  203. package/src/mcp/ports.ts +8 -1
  204. package/src/mcp/rate-limit.ts +2 -1
  205. package/src/mcp/read.ts +82 -3
  206. package/src/mcp/refs.ts +18 -0
  207. package/src/mcp/tools.ts +1 -1
  208. package/src/mcp/write.ts +271 -25
  209. package/src/server/agent-settings.ts +29 -4
  210. package/src/server/hooks.ts +5 -3
  211. package/src/server/icon-routes.ts +33 -9
  212. package/src/server/mcp-routes.ts +74 -11
@@ -0,0 +1,141 @@
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
+ // W-581: floor, so rounding never pushes the following height past the cap (tall strips).
41
+ return Math.max(1, Math.floor((full.width * maxSide) / longest));
42
+ }
43
+
44
+ /** Output size for a chosen width (null = full size); the height follows the crop. */
45
+ export function outputSize(full: Size, width: number | null): Size {
46
+ if (!width) return full;
47
+ return { width, height: Math.max(1, Math.round((width * full.height) / full.width)) };
48
+ }
49
+
50
+ /** "garden.jpg" + webp → "garden-edited.webp"; an earlier "-edited" isn't repeated. */
51
+ export function editedFileName(name: string, format: ExportFormat): string {
52
+ const base =
53
+ name
54
+ .replace(/\.[^./]+$/, "")
55
+ .replace(/-edited$/, "")
56
+ // W-593: letters and digits in any script are kept (pageSlug does the same, W-591).
57
+ .replace(/[^\p{L}\p{M}\p{N}_.-]+/gu, "-")
58
+ // W-539: no leading dots (a hidden file) and at most 100 characters.
59
+ .replace(/^[-.]+|[-.]+$/g, "")
60
+ .slice(0, 100)
61
+ .replace(/[-.]+$/g, "") || "image";
62
+ return `${base}-edited.${EXT[format]}`;
63
+ }
64
+
65
+ /** The file to upload: JPEG location data is removed when asked (photocn copies the EXIF). */
66
+ export async function outputFile(
67
+ blob: Blob,
68
+ name: string,
69
+ format: ExportFormat,
70
+ stripGps: boolean,
71
+ ): Promise<{ file: File; gpsRemoved: boolean }> {
72
+ const type = blob.type || `image/${format}`;
73
+ if (format !== "jpeg" || !stripGps) {
74
+ return { file: new File([blob], name, { type }), gpsRemoved: false };
75
+ }
76
+ const { bytes, removed } = stripJpegGps(await blob.arrayBuffer());
77
+ return { file: new File([bytes], name, { type }), gpsRemoved: removed };
78
+ }
79
+
80
+ /** True when a JPEG source carries GPS location data. */
81
+ export async function hasGps(blob: Blob): Promise<boolean> {
82
+ if (!/jpe?g/i.test(blob.type)) return false;
83
+ return stripJpegGps(await blob.arrayBuffer()).removed;
84
+ }
85
+
86
+ /**
87
+ * The record saved on the element. It always points at the untouched original: an edit of an
88
+ * edit keeps the first original, so re-opening never stacks losses.
89
+ */
90
+ export function buildImageEdit(input: {
91
+ imageProps: Record<string, unknown>;
92
+ recipe: unknown;
93
+ output: ImageEditOutput;
94
+ now?: Date;
95
+ }): { ok: true; edit: ImageEdit } | { ok: false; message: string } {
96
+ const { imageProps, output } = input;
97
+ const prior = ImageEdit.safeParse(imageProps.edit);
98
+ // W-582: a damaged record (e.g. a newer photocn's recipe key) still names the original the
99
+ // editor opened (load.ts reads edit.originalSrc leniently), so keep pointing there.
100
+ const raw = (imageProps.edit ?? {}) as { originalSrc?: unknown; originalMediaId?: unknown };
101
+ const rawSrc = typeof raw.originalSrc === "string" ? raw.originalSrc.trim() : "";
102
+ const rawId = typeof raw.originalMediaId === "string" ? raw.originalMediaId : "";
103
+ const originalSrc = prior.success
104
+ ? prior.data.originalSrc
105
+ : rawSrc
106
+ ? rawSrc
107
+ : typeof imageProps.src === "string"
108
+ ? imageProps.src
109
+ : "";
110
+ const priorId = prior.success
111
+ ? prior.data.originalMediaId
112
+ : rawSrc && rawId.length >= 1 && rawId.length <= 128
113
+ ? rawId
114
+ : undefined;
115
+ const originalMediaId =
116
+ priorId ?? (typeof imageProps.mediaId === "string" ? imageProps.mediaId : undefined);
117
+ const parsed = ImageEdit.safeParse({
118
+ v: 1,
119
+ engine: "photocn",
120
+ engineVersion: PHOTOCN_VERSION,
121
+ recipe: (input.recipe as ImageEditRecipe | null) ?? { version: 1 },
122
+ ...(originalMediaId ? { originalMediaId } : {}),
123
+ originalSrc,
124
+ output,
125
+ editedAt: (input.now ?? new Date()).toISOString(),
126
+ });
127
+ if (parsed.success) return { ok: true, edit: parsed.data };
128
+ const issue = parsed.error.issues[0];
129
+ return {
130
+ ok: false,
131
+ message: `This edit can't be saved${issue?.message ? `: ${issue.message}` : "."}`,
132
+ };
133
+ }
134
+
135
+ /** The recipe to re-apply when re-opening, or null for none or a damaged record. */
136
+ export function savedRecipe(imageProps: Record<string, unknown>): ImageEditRecipe | null {
137
+ const parsed = ImageEdit.safeParse(imageProps.edit);
138
+ if (!parsed.success) return null;
139
+ const { recipe } = parsed.data;
140
+ return Object.keys(recipe).some((k) => k !== "version" && k !== "name") ? recipe : null;
141
+ }
@@ -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
+ }