@cosmicdrift/kumiko-renderer-web 0.193.0 → 0.194.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 (46) hide show
  1. package/package.json +4 -4
  2. package/src/__tests__/create-app.test.tsx +1 -1
  3. package/src/__tests__/entity-edit-redirect.test.tsx +111 -0
  4. package/src/__tests__/field-hide-label.test.tsx +166 -1
  5. package/src/__tests__/kumiko-screen.test.tsx +59 -0
  6. package/src/__tests__/nav-tree.test.tsx +43 -11
  7. package/src/__tests__/primitives.test.tsx +33 -2
  8. package/src/__tests__/render-edit.test.tsx +344 -9
  9. package/src/__tests__/test-utils.tsx +20 -0
  10. package/src/__tests__/wizard-form-validation.test.tsx +129 -1
  11. package/src/app/__tests__/merge-content-editors.test.ts +2 -2
  12. package/src/app/__tests__/plain-content-editor.test.tsx +4 -0
  13. package/src/app/__tests__/rich-content-editor.test.tsx +5 -2
  14. package/src/app/__tests__/tiptap-editor.test.tsx +50 -0
  15. package/src/app/client-plugin.tsx +3 -3
  16. package/src/app/create-app.tsx +40 -49
  17. package/src/app/tiptap-editor.tsx +10 -0
  18. package/src/layout/__tests__/workspace-switcher.test.tsx +40 -0
  19. package/src/layout/sidebar-panel.tsx +1 -4
  20. package/src/layout/workspace-switcher.tsx +20 -13
  21. package/src/lib/__tests__/resize-image.test.ts +152 -0
  22. package/src/lib/clamp.ts +3 -0
  23. package/src/lib/resize-image.ts +61 -0
  24. package/src/primitives/__tests__/data-table-logic.test.ts +15 -3
  25. package/src/primitives/__tests__/date-field.test.tsx +37 -0
  26. package/src/primitives/__tests__/date-parse.test.ts +14 -2
  27. package/src/primitives/__tests__/embedded-list-input.test.tsx +36 -2
  28. package/src/primitives/__tests__/file-upload.test.tsx +24 -0
  29. package/src/primitives/date-field.tsx +8 -0
  30. package/src/primitives/date-parse.ts +6 -1
  31. package/src/primitives/dropdown-menu.tsx +23 -0
  32. package/src/primitives/embedded-list-input.tsx +14 -5
  33. package/src/primitives/file-upload.tsx +6 -1
  34. package/src/primitives/index.tsx +114 -120
  35. package/src/primitives/money-input.tsx +4 -7
  36. package/src/ui/sheet.tsx +3 -1
  37. package/src/widgets/__tests__/drawer.test.tsx +293 -0
  38. package/src/widgets/__tests__/infinity-list.test.tsx +38 -0
  39. package/src/widgets/__tests__/upload-zone.test.tsx +125 -1
  40. package/src/widgets/__tests__/widgets.test.tsx +25 -0
  41. package/src/widgets/ai-text-field.tsx +3 -1
  42. package/src/widgets/drawer.tsx +54 -29
  43. package/src/widgets/infinity-list.tsx +18 -5
  44. package/src/widgets/progress-bar.tsx +3 -1
  45. package/src/widgets/step-bar.tsx +1 -1
  46. package/src/widgets/upload-zone.tsx +42 -3
@@ -9,6 +9,18 @@ function Controlled({ initial }: { readonly initial: string }): ReactNode {
9
9
  return <TiptapEditor value={value} onChange={setValue} variables={["name"]} readOnly={false} />;
10
10
  }
11
11
 
12
+ function ReadOnlyToggle({ initial }: { readonly initial: string }): ReactNode {
13
+ const [readOnly, setReadOnly] = useState(false);
14
+ return (
15
+ <div>
16
+ <button type="button" onClick={() => setReadOnly((r) => !r)}>
17
+ toggle readOnly
18
+ </button>
19
+ <TiptapEditor value={initial} onChange={() => {}} variables={[]} readOnly={readOnly} />
20
+ </div>
21
+ );
22
+ }
23
+
12
24
  // Mirrors the real caller: TextBlockEditor mounts with value="" and only
13
25
  // gets the loaded content after its by-slug query resolves — value arrives
14
26
  // as a prop update, not at mount. A test that renders the final HTML
@@ -91,4 +103,42 @@ describe("TiptapEditor — jsdom smoke", () => {
91
103
  fireEvent.click(screen.getByText("{{name}}"));
92
104
  expect(await screen.findByText("{{name}}", { selector: "p" })).toBeTruthy();
93
105
  });
106
+
107
+ test("toggling readOnly flips the surface's contenteditable and disables the toolbar", async () => {
108
+ // @tiptap/react re-applies `editable` from options on every options
109
+ // refresh, overriding what `editable: !readOnly` set at creation — so
110
+ // this only stays correct across a readOnly prop change via the
111
+ // `editor.setEditable` effect. A test that only mounts with a fixed
112
+ // readOnly value can't catch that effect being removed.
113
+ render(<ReadOnlyToggle initial="<p>hello</p>" />);
114
+ const editable = await screen.findByText("hello");
115
+ expect(editable.closest('[contenteditable="true"]')).not.toBeNull();
116
+ expect((screen.getByRole("button", { name: "Bold" }) as HTMLButtonElement).disabled).toBe(
117
+ false,
118
+ );
119
+
120
+ fireEvent.click(screen.getByText("toggle readOnly"));
121
+
122
+ expect(editable.closest('[contenteditable="false"]')).not.toBeNull();
123
+ expect((screen.getByRole("button", { name: "Bold" }) as HTMLButtonElement).disabled).toBe(true);
124
+ });
125
+
126
+ // Documents the ponytail-noted ceiling on useEditor: markup StarterKit's
127
+ // schema doesn't model (tables, raw divs/spans, style attrs) is dropped on
128
+ // first parse, invisible until the first onChange fires. Not a bug to fix
129
+ // here — a fixture for whoever hits the ceiling next.
130
+ test("markup outside StarterKit's schema (a <table>) is dropped on the first onChange", async () => {
131
+ const values: string[] = [];
132
+ render(
133
+ <TiptapEditor
134
+ value="<table><tbody><tr><td>cell</td></tr></tbody></table><p>hello</p>"
135
+ onChange={(html) => values.push(html)}
136
+ variables={[]}
137
+ readOnly={false}
138
+ />,
139
+ );
140
+ const editable = (await screen.findByText("hello")).closest('[contenteditable="true"]');
141
+ fireEvent.click(screen.getByRole("button", { name: "Bold" }));
142
+ expect(editable?.innerHTML).not.toContain("<table");
143
+ });
94
144
  });
@@ -90,12 +90,12 @@ export type ClientFeatureDefinition = {
90
90
  collections: readonly QualifiedContentCollection[],
91
91
  ) => CollectionNavProviders;
92
92
 
93
- /** Content-Editor-Components — Map `contentFormat` ("plain" | "rich" | "markdown") →
94
- * React-Component. `r.contentCollection()` declares which format an
93
+ /** Content editor components — map `contentFormat` ("plain" | "rich" | "markdown") →
94
+ * React component. `r.contentCollection()` declares which format an
95
95
  * editor edits; the collection's editor UI (template-resolver's
96
96
  * TextBlockEditor et al.) looks the component up here and falls back to
97
97
  * a plain textarea when no clientFeature registered one for that
98
- * format. Same Last-Wins-Semantik wie columnRenderers. Public component
98
+ * format. Same last-wins semantics as columnRenderers. Public component
99
99
  * contract: `{ value, onChange, variables, readOnly }`. */
100
100
  readonly contentEditors?: Readonly<Record<string, ContentEditorComponent>>;
101
101
 
@@ -9,7 +9,6 @@ import type {
9
9
  import {
10
10
  AppFeaturesProvider,
11
11
  type AppSchema,
12
- type ColumnRendererComponent,
13
12
  ColumnRenderersProvider,
14
13
  type ContentEditorComponent,
15
14
  ContentEditorsProvider,
@@ -18,7 +17,6 @@ import {
18
17
  DispatcherProvider,
19
18
  type DraftStorage,
20
19
  DraftStorageProvider,
21
- type ExtensionSectionComponent,
22
20
  ExtensionSectionsProvider,
23
21
  type FeatureSchema,
24
22
  KumikoScreen,
@@ -99,7 +97,7 @@ export function buildNavProviderMaps(
99
97
  for (const [navId, provider] of Object.entries(f.navProviders ?? {})) {
100
98
  const qn = qualifyNavProviderKey(f.name, navId);
101
99
  if (navProviders.has(qn) && !derivedQns.delete(qn)) {
102
- // biome-ignore lint/suspicious/noConsole: dev-warning für Schema-Konflikte
100
+ // biome-ignore lint/suspicious/noConsole: dev warning for schema conflicts
103
101
  console.warn(
104
102
  `[kumiko] navProvider for "${qn}" defined by multiple clientFeatures — last wins.`,
105
103
  );
@@ -228,26 +226,39 @@ export function firstOpenScreenQn(features: readonly FeatureSchema[]): string |
228
226
  return undefined;
229
227
  }
230
228
 
231
- // Merges the content-editor map — same last-wins semantics as
232
- // columnRenderers. No entry for a contentFormat → useContentEditor falls
233
- // back to the textarea on its own, no warning needed.
234
- export function mergeContentEditors(
229
+ // Last-wins merge for a clientFeature-contributed map (contentEditors,
230
+ // columnRenderers, extensionSectionComponents, ...): later features in
231
+ // `clientFeatures` override earlier ones on key collision, logging once
232
+ // per collision so an accidental override isn't silent.
233
+ function mergeByKey<T>(
235
234
  clientFeatures: readonly ClientFeatureDefinition[],
236
- ): Record<string, ContentEditorComponent> {
237
- const contentEditors: Record<string, ContentEditorComponent> = {};
235
+ pick: (f: ClientFeatureDefinition) => Record<string, T> | undefined,
236
+ label: string,
237
+ ): Record<string, T> {
238
+ const merged: Record<string, T> = {};
238
239
  for (const f of clientFeatures) {
239
- if (f.contentEditors === undefined) continue;
240
- for (const [key, value] of Object.entries(f.contentEditors)) {
241
- if (contentEditors[key] !== undefined) {
242
- // biome-ignore lint/suspicious/noConsole: dev-warning für Schema-Konflikte
240
+ const entries = pick(f);
241
+ if (entries === undefined) continue;
242
+ for (const [key, value] of Object.entries(entries)) {
243
+ if (merged[key] !== undefined) {
244
+ // biome-ignore lint/suspicious/noConsole: dev warning for schema conflicts
243
245
  console.warn(
244
- `[kumiko] contentEditor "${key}" defined by multiple clientFeatures — last definition (from "${f.name}") wins.`,
246
+ `[kumiko] ${label} "${key}" defined by multiple clientFeatures — last definition (from "${f.name}") wins.`,
245
247
  );
246
248
  }
247
- contentEditors[key] = value;
249
+ merged[key] = value;
248
250
  }
249
251
  }
250
- return contentEditors;
252
+ return merged;
253
+ }
254
+
255
+ // Merges the content-editor map — same last-wins semantics as
256
+ // columnRenderers. No entry for a contentFormat → useContentEditor falls
257
+ // back to the textarea on its own, no warning needed.
258
+ export function mergeContentEditors(
259
+ clientFeatures: readonly ClientFeatureDefinition[],
260
+ ): Record<string, ContentEditorComponent> {
261
+ return mergeByKey(clientFeatures, (f) => f.contentEditors, "contentEditor");
251
262
  }
252
263
 
253
264
  export function createKumikoApp(options: CreateKumikoAppOptions = {}): { readonly root: Root } {
@@ -321,39 +332,19 @@ export function createKumikoApp(options: CreateKumikoAppOptions = {}): { readonl
321
332
  for (const f of clientFeatures) {
322
333
  if (f.components !== undefined) Object.assign(customScreens, f.components);
323
334
  }
324
- // Column-Renderer-Map mergen — gleiche Last-Wins-Semantik wie bei
325
- // customScreens. Doppelte Keys über Features sind selten gewollt;
326
- // wir warnen einmalig pro Kollision damit das nicht stillschweigend
327
- // den Renderer einer Library überschreibt.
328
- const columnRenderers: Record<string, ColumnRendererComponent> = {};
329
- for (const f of clientFeatures) {
330
- if (f.columnRenderers === undefined) continue;
331
- for (const [key, value] of Object.entries(f.columnRenderers)) {
332
- if (columnRenderers[key] !== undefined) {
333
- // biome-ignore lint/suspicious/noConsole: dev-warning für Schema-Konflikte
334
- console.warn(
335
- `[kumiko] columnRenderer "${key}" defined by multiple clientFeatures — last definition (from "${f.name}") wins.`,
336
- );
337
- }
338
- columnRenderers[key] = value;
339
- }
340
- }
341
- // Extension-Section-Components — same Last-Wins + Warn-Semantik wie
342
- // columnRenderers. Mountet sich am ExtensionSectionsProvider; RenderEdit
343
- // löst die Component aus dem `__component`-Marker der section.
344
- const extensionSectionComponents: Record<string, ExtensionSectionComponent> = {};
345
- for (const f of clientFeatures) {
346
- if (f.extensionSectionComponents === undefined) continue;
347
- for (const [key, value] of Object.entries(f.extensionSectionComponents)) {
348
- if (extensionSectionComponents[key] !== undefined) {
349
- // biome-ignore lint/suspicious/noConsole: dev-warning für Schema-Konflikte
350
- console.warn(
351
- `[kumiko] extensionSectionComponent "${key}" defined by multiple clientFeatures — last definition (from "${f.name}") wins.`,
352
- );
353
- }
354
- extensionSectionComponents[key] = value;
355
- }
356
- }
335
+ // Column-renderer map, same last-wins semantics as customScreens —
336
+ // duplicate keys across features are rarely intentional, so a
337
+ // collision logs once instead of silently overriding a library's
338
+ // renderer.
339
+ const columnRenderers = mergeByKey(clientFeatures, (f) => f.columnRenderers, "columnRenderer");
340
+ // Extension-section components — same last-wins + warn semantics as
341
+ // columnRenderers. Mounted on ExtensionSectionsProvider; RenderEdit
342
+ // resolves the component from the section's `__component` marker.
343
+ const extensionSectionComponents = mergeByKey(
344
+ clientFeatures,
345
+ (f) => f.extensionSectionComponents,
346
+ "extensionSectionComponent",
347
+ );
357
348
 
358
349
  const contentEditors = mergeContentEditors(clientFeatures);
359
350
 
@@ -68,6 +68,12 @@ export default function TiptapEditor({
68
68
  readOnly,
69
69
  }: ContentEditorProps): ReactNode {
70
70
  const t = useTranslation();
71
+ // ponytail: rich = StarterKit's schema (bold/italic/lists/headings/links).
72
+ // Anything the schema doesn't model — <table>, <div>/<span>, style attrs,
73
+ // <img>, classes — is dropped on first parse (setContent below, and the
74
+ // initial `content: value` here). Upgrade if that ceiling is hit: add the
75
+ // matching tiptap extensions, or a raw-HTML mode for markup StarterKit
76
+ // can't represent.
71
77
  const editor = useEditor({
72
78
  extensions: [StarterKit],
73
79
  content: value,
@@ -79,6 +85,10 @@ export default function TiptapEditor({
79
85
  // Same id the textarea fallback uses — the Field wrapping the editor
80
86
  // (TextBlockEditor) associates its label via this id; the editor
81
87
  // contract has no `id` prop of its own, see content-editors.tsx.
88
+ // ponytail: fixed id, not a prop — two simultaneously mounted rich
89
+ // editors (or a rich + a plain editor on one screen) collide on this
90
+ // DOM id, same ceiling plain-content-editor.tsx documents. Upgrade:
91
+ // thread `id` through ContentEditorProps as an optional override.
82
92
  editorProps: { attributes: { id: CONTENT_EDITOR_ELEMENT_ID } },
83
93
  onUpdate: ({ editor: e }) => onChange(e.getHTML()),
84
94
  });
@@ -55,6 +55,46 @@ describe("WorkspaceSwitcher — Render", () => {
55
55
  expect(screen.getByTestId("workspace-tab-b").getAttribute("aria-checked")).toBe("true");
56
56
  });
57
57
 
58
+ test("entries carry role=menuitemradio (exclusive choice), not menuitemcheckbox", async () => {
59
+ const user = userEvent.setup();
60
+ renderWithSidebar(
61
+ <WorkspaceSwitcher
62
+ workspaces={[ws("a", "Alpha"), ws("b", "Beta")]}
63
+ activeId="a"
64
+ onSelect={() => {}}
65
+ />,
66
+ );
67
+ await user.click(screen.getByTestId("workspace-switcher-trigger"));
68
+ expect(screen.getByTestId("workspace-tab-a").getAttribute("role")).toBe("menuitemradio");
69
+ expect(screen.getByTestId("workspace-tab-b").getAttribute("role")).toBe("menuitemradio");
70
+ });
71
+
72
+ test("trigger has an accessible name beyond the active workspace label", () => {
73
+ renderWithSidebar(
74
+ <WorkspaceSwitcher
75
+ workspaces={[ws("a", "Alpha"), ws("b", "Beta")]}
76
+ activeId="a"
77
+ onSelect={() => {}}
78
+ />,
79
+ );
80
+ expect(
81
+ screen.getByTestId("workspace-switcher-trigger").getAttribute("aria-label"),
82
+ ).toBeTruthy();
83
+ });
84
+
85
+ test("activeId zeigt auf keinen sichtbaren Workspace → Trigger zeigt Fallback-Label statt leerem span (fw#1816)", () => {
86
+ renderWithSidebar(
87
+ <WorkspaceSwitcher
88
+ workspaces={[ws("a", "Alpha"), ws("b", "Beta")]}
89
+ activeId="stale-id-not-in-list"
90
+ onSelect={() => {}}
91
+ testId="sw"
92
+ />,
93
+ );
94
+ expect(screen.getByTestId("sw").textContent).not.toBe("");
95
+ expect(screen.getByText("Select workspace")).toBeTruthy();
96
+ });
97
+
58
98
  test("Click auf einen Eintrag ruft onSelect mit der Workspace-id", async () => {
59
99
  const user = userEvent.setup();
60
100
  const onSelect = mock((_id: string) => {});
@@ -22,6 +22,7 @@ import {
22
22
  useState,
23
23
  } from "react";
24
24
  import { createPortal } from "react-dom";
25
+ import { clamp } from "../lib/clamp";
25
26
  import { cn } from "../lib/cn";
26
27
 
27
28
  type SlotElement = HTMLElement | null;
@@ -57,10 +58,6 @@ const DEFAULT_WIDTH = 340;
57
58
  const DEFAULT_MIN = 260;
58
59
  const DEFAULT_MAX = 640;
59
60
 
60
- function clamp(value: number, min: number, max: number): number {
61
- return Math.min(Math.max(value, min), max);
62
- }
63
-
64
61
  function readStoredWidth(key: string | undefined): number | null {
65
62
  if (key === undefined || typeof window === "undefined") return null;
66
63
  const raw = window.localStorage.getItem(key);
@@ -20,8 +20,9 @@ import { ChevronsUpDown } from "lucide-react";
20
20
  import type { ReactNode } from "react";
21
21
  import {
22
22
  DropdownMenu,
23
- DropdownMenuCheckboxItem,
24
23
  DropdownMenuContent,
24
+ DropdownMenuRadioGroup,
25
+ DropdownMenuRadioItem,
25
26
  DropdownMenuTrigger,
26
27
  } from "../primitives/dropdown-menu";
27
28
  import { SidebarMenu, SidebarMenuButton, SidebarMenuItem } from "../ui/sidebar";
@@ -57,22 +58,28 @@ export function WorkspaceSwitcher({
57
58
  <SidebarMenuItem>
58
59
  <DropdownMenu>
59
60
  <DropdownMenuTrigger asChild>
60
- <SidebarMenuButton data-testid="workspace-switcher-trigger">
61
- <span className="truncate">{active !== undefined ? labelOf(active) : ""}</span>
61
+ <SidebarMenuButton
62
+ data-testid="workspace-switcher-trigger"
63
+ aria-label={t("kumiko.workspace.switch")}
64
+ >
65
+ <span className="truncate">
66
+ {active !== undefined ? labelOf(active) : t("kumiko.workspace.select")}
67
+ </span>
62
68
  <ChevronsUpDown className="ml-auto" />
63
69
  </SidebarMenuButton>
64
70
  </DropdownMenuTrigger>
65
71
  <DropdownMenuContent align="start" className="min-w-[10rem]">
66
- {workspaces.map((ws) => (
67
- <DropdownMenuCheckboxItem
68
- key={ws.definition.id}
69
- checked={ws.definition.id === activeId}
70
- data-testid={`workspace-tab-${ws.definition.id}`}
71
- onSelect={() => onSelect(ws.definition.id)}
72
- >
73
- <span className="truncate">{labelOf(ws)}</span>
74
- </DropdownMenuCheckboxItem>
75
- ))}
72
+ <DropdownMenuRadioGroup value={activeId} onValueChange={onSelect}>
73
+ {workspaces.map((ws) => (
74
+ <DropdownMenuRadioItem
75
+ key={ws.definition.id}
76
+ value={ws.definition.id}
77
+ data-testid={`workspace-tab-${ws.definition.id}`}
78
+ >
79
+ <span className="truncate">{labelOf(ws)}</span>
80
+ </DropdownMenuRadioItem>
81
+ ))}
82
+ </DropdownMenuRadioGroup>
76
83
  </DropdownMenuContent>
77
84
  </DropdownMenu>
78
85
  </SidebarMenuItem>
@@ -0,0 +1,152 @@
1
+ import { describe, expect, mock, test } from "bun:test";
2
+ import { resizeImageBeforeUpload } from "../resize-image";
3
+
4
+ describe("resizeImageBeforeUpload", () => {
5
+ test("lässt Nicht-Bilder unverändert", async () => {
6
+ const file = new File(["hi"], "report.pdf", { type: "application/pdf" });
7
+ const result = await resizeImageBeforeUpload(file);
8
+ expect(result).toBe(file);
9
+ });
10
+
11
+ test("fehlt OffscreenCanvas, bleibt das Bild unverändert", async () => {
12
+ // @ts-expect-error simulate a browser without OffscreenCanvas support
13
+ globalThis.OffscreenCanvas = undefined;
14
+ const file = new File(["hi"], "photo.jpg", { type: "image/jpeg" });
15
+ const result = await resizeImageBeforeUpload(file);
16
+ expect(result).toBe(file);
17
+ });
18
+
19
+ test("lässt SVGs unverändert (Vektor würde beim Re-Encode zerstört)", async () => {
20
+ const file = new File(["<svg/>"], "logo.svg", { type: "image/svg+xml" });
21
+ const result = await resizeImageBeforeUpload(file);
22
+ expect(result).toBe(file);
23
+ });
24
+
25
+ test("lässt GIFs unverändert (Animation würde auf ein Frame kollabieren)", async () => {
26
+ const file = new File(["gif"], "anim.gif", { type: "image/gif" });
27
+ const result = await resizeImageBeforeUpload(file);
28
+ expect(result).toBe(file);
29
+ });
30
+
31
+ test("skaliert auf maxEdge herunter und behält das Seitenverhältnis", async () => {
32
+ const bitmap = { close: mock(() => {}), height: 2000, width: 4000 };
33
+ let capturedWidth = 0;
34
+ let capturedHeight = 0;
35
+ class FakeOffscreenCanvas {
36
+ constructor(w: number, h: number) {
37
+ capturedWidth = w;
38
+ capturedHeight = h;
39
+ }
40
+ getContext() {
41
+ return { drawImage: mock(() => {}) };
42
+ }
43
+ convertToBlob() {
44
+ return Promise.resolve(new Blob(["x"], { type: "image/jpeg" }));
45
+ }
46
+ }
47
+ // @ts-expect-error test stub for a browser-only API missing in jsdom
48
+ globalThis.OffscreenCanvas = FakeOffscreenCanvas;
49
+ globalThis.createImageBitmap = mock(async () => bitmap);
50
+
51
+ try {
52
+ const file = new File(["x"], "photo.jpg", { type: "image/jpeg" });
53
+ const result = await resizeImageBeforeUpload(file, 2560);
54
+ expect(capturedWidth).toBe(2560);
55
+ expect(capturedHeight).toBe(1280);
56
+ expect(result.name).toBe("photo.jpg");
57
+ expect(result.type).toBe("image/jpeg");
58
+ } finally {
59
+ // @ts-expect-error restore missing-API baseline
60
+ globalThis.OffscreenCanvas = undefined;
61
+ // @ts-expect-error restore missing-API baseline
62
+ globalThis.createImageBitmap = undefined;
63
+ }
64
+ });
65
+
66
+ test("konvertiert nicht-erhaltbare Formate zu jpeg und passt die Extension an", async () => {
67
+ class FakeOffscreenCanvas {
68
+ getContext() {
69
+ return { drawImage: mock(() => {}) };
70
+ }
71
+ convertToBlob(opts: { type: string }) {
72
+ return Promise.resolve(new Blob(["x"], { type: opts.type }));
73
+ }
74
+ }
75
+ // @ts-expect-error test stub for a browser-only API missing in jsdom
76
+ globalThis.OffscreenCanvas = FakeOffscreenCanvas;
77
+ globalThis.createImageBitmap = mock(async () => ({
78
+ close: mock(() => {}),
79
+ height: 100,
80
+ width: 100,
81
+ }));
82
+
83
+ try {
84
+ const file = new File(["x"], "photo.heic", { type: "image/heic" });
85
+ const result = await resizeImageBeforeUpload(file);
86
+ expect(result.name).toBe("photo.jpg");
87
+ expect(result.type).toBe("image/jpeg");
88
+ } finally {
89
+ // @ts-expect-error restore missing-API baseline
90
+ globalThis.OffscreenCanvas = undefined;
91
+ // @ts-expect-error restore missing-API baseline
92
+ globalThis.createImageBitmap = undefined;
93
+ }
94
+ });
95
+
96
+ test("benennt nach dem tatsächlich erzeugten Blob-Typ, nicht dem angeforderten", async () => {
97
+ // A browser without webp encoding support silently falls back to png
98
+ // (spec behavior of convertToBlob) — naming must follow the blob, or a
99
+ // ".webp" file ends up holding png bytes with a matching-looking mimeType.
100
+ class FakeOffscreenCanvas {
101
+ getContext() {
102
+ return { drawImage: mock(() => {}) };
103
+ }
104
+ convertToBlob() {
105
+ return Promise.resolve(new Blob(["x"], { type: "image/png" }));
106
+ }
107
+ }
108
+ // @ts-expect-error test stub for a browser-only API missing in jsdom
109
+ globalThis.OffscreenCanvas = FakeOffscreenCanvas;
110
+ globalThis.createImageBitmap = mock(async () => ({
111
+ close: mock(() => {}),
112
+ height: 100,
113
+ width: 100,
114
+ }));
115
+
116
+ try {
117
+ const file = new File(["x"], "photo.webp", { type: "image/webp" });
118
+ const result = await resizeImageBeforeUpload(file);
119
+ expect(result.name).toBe("photo.png");
120
+ expect(result.type).toBe("image/png");
121
+ } finally {
122
+ // @ts-expect-error restore missing-API baseline
123
+ globalThis.OffscreenCanvas = undefined;
124
+ // @ts-expect-error restore missing-API baseline
125
+ globalThis.createImageBitmap = undefined;
126
+ }
127
+ });
128
+
129
+ test("fällt bei Decode-Fehlern auf die Originaldatei zurück", async () => {
130
+ class FakeOffscreenCanvas {
131
+ getContext() {
132
+ return { drawImage: mock(() => {}) };
133
+ }
134
+ }
135
+ // @ts-expect-error test stub for a browser-only API missing in jsdom
136
+ globalThis.OffscreenCanvas = FakeOffscreenCanvas;
137
+ globalThis.createImageBitmap = mock(async () => {
138
+ throw new Error("unsupported format");
139
+ });
140
+
141
+ try {
142
+ const file = new File(["x"], "photo.heic", { type: "image/heic" });
143
+ const result = await resizeImageBeforeUpload(file);
144
+ expect(result).toBe(file);
145
+ } finally {
146
+ // @ts-expect-error restore missing-API baseline
147
+ globalThis.OffscreenCanvas = undefined;
148
+ // @ts-expect-error restore missing-API baseline
149
+ globalThis.createImageBitmap = undefined;
150
+ }
151
+ });
152
+ });
@@ -0,0 +1,3 @@
1
+ export function clamp(value: number, min: number, max: number): number {
2
+ return Math.min(Math.max(value, min), max);
3
+ }
@@ -0,0 +1,61 @@
1
+ const DEFAULT_MAX_EDGE = 2560;
2
+
3
+ // Raster formats a canvas can losslessly re-encode as themselves; anything
4
+ // else (heic, bmp, tiff, ...) falls back to jpeg. svg/gif are excluded
5
+ // upstream (vector/animation would be destroyed by a canvas re-encode).
6
+ const PRESERVED_TYPES = new Set(["image/png", "image/webp"]);
7
+ const OUTPUT_EXTENSIONS: Record<string, string> = {
8
+ "image/jpeg": "jpg",
9
+ "image/png": "png",
10
+ "image/webp": "webp",
11
+ };
12
+
13
+ function pickOutputType(inputType: string): string {
14
+ return PRESERVED_TYPES.has(inputType) ? inputType : "image/jpeg";
15
+ }
16
+
17
+ // The server validates the upload's extension against its mimeType
18
+ // (mime_mismatch), so a re-encode that changes type must rename the file too.
19
+ function withMatchingExtension(fileName: string, outputType: string): string {
20
+ const ext = OUTPUT_EXTENSIONS[outputType] ?? "jpg";
21
+ const dot = fileName.lastIndexOf(".");
22
+ const base = dot > 0 ? fileName.slice(0, dot) : fileName;
23
+ return `${base}.${ext}`;
24
+ }
25
+
26
+ // Downscales images before upload to a reasonable edge length (bandwidth)
27
+ // and drops EXIF/GPS as a side effect (canvas re-encode carries no
28
+ // metadata). Missing OffscreenCanvas/createImageBitmap (older browser), or a
29
+ // decode failure, leaves the file unchanged — no hard error before upload.
30
+ export async function resizeImageBeforeUpload(
31
+ file: File,
32
+ maxEdge = DEFAULT_MAX_EDGE,
33
+ ): Promise<File> {
34
+ if (!file.type.startsWith("image/")) return file;
35
+ if (file.type === "image/svg+xml" || file.type === "image/gif") return file;
36
+ if (typeof OffscreenCanvas === "undefined" || typeof createImageBitmap !== "function") {
37
+ return file;
38
+ }
39
+ try {
40
+ const bitmap = await createImageBitmap(file, { imageOrientation: "from-image" });
41
+ const scale = Math.min(1, maxEdge / Math.max(bitmap.width, bitmap.height));
42
+ const width = Math.round(bitmap.width * scale);
43
+ const height = Math.round(bitmap.height * scale);
44
+ const canvas = new OffscreenCanvas(width, height);
45
+ const ctx = canvas.getContext("2d");
46
+ if (ctx === null) return file;
47
+ ctx.drawImage(bitmap, 0, 0, width, height);
48
+ bitmap.close();
49
+ const blob = await canvas.convertToBlob({ type: pickOutputType(file.type), quality: 0.85 });
50
+ // Name off the blob's actual type, not the requested one — a browser
51
+ // without webp encoding support silently falls back to png, and naming
52
+ // by the request would then store a lie (extension/mimeType both "webp"
53
+ // over png bytes).
54
+ const actualType = blob.type || file.type;
55
+ const fileName =
56
+ actualType === file.type ? file.name : withMatchingExtension(file.name, actualType);
57
+ return new File([blob], fileName, { type: actualType });
58
+ } catch {
59
+ return file;
60
+ }
61
+ }
@@ -183,13 +183,25 @@ describe("defaultCellRender", () => {
183
183
  expect(result).not.toMatch(/[.,]\d\d$/);
184
184
  });
185
185
 
186
- test("money → rehydrated { amount major, amountMinor } uses amountMinor (not major×100 wrong)", () => {
187
- // rehydrateMoney (fw#1830): amount is major units, amountMinor is cents.
188
- // formatMoney expects cents — using amount would show 100× too small.
186
+ test("money → rehydrated { amount major, amountMinor } derives minor units from amount + currencyDecimals", () => {
187
+ // rehydrateMoney (fw#1830): amount is major units, amountMinor is a flat
188
+ // ×100 scale that disagrees with currencyDecimals for non-2-decimal
189
+ // currencies — defaultCellRender ignores amountMinor and derives minor
190
+ // units from `amount` instead (see index.tsx).
189
191
  const result = defaultCellRender({ amount: 119, currency: "EUR", amountMinor: 11900 }, "money");
190
192
  expect(result.replace(/[^0-9]/g, "")).toBe("11900");
191
193
  });
192
194
 
195
+ test("money → zero-decimal currency (JPY) ignores amountMinor's mismatched flat scale", () => {
196
+ const result = defaultCellRender({ amount: 500, currency: "JPY", amountMinor: 50000 }, "money");
197
+ expect(result.replace(/[^0-9]/g, "")).toBe("500");
198
+ });
199
+
200
+ test("money → three-decimal currency (BHD) ignores amountMinor's mismatched flat scale", () => {
201
+ const result = defaultCellRender({ amount: 1.5, currency: "BHD", amountMinor: 150 }, "money");
202
+ expect(result.replace(/[^0-9]/g, "")).toBe("1500");
203
+ });
204
+
193
205
  test("money → unerwarteter Value-Shape fällt auf String zurück", () => {
194
206
  expect(defaultCellRender(45000, "money")).toBe("45000");
195
207
  });
@@ -0,0 +1,37 @@
1
+ // DateField rendering tests — happy-dom + @testing-library/react. Pins
2
+ // that the input's `placeholder` actually comes from `t()` + resolvedLocale
3
+ // (date-parse.test.ts only covers the pure formatDatePlaceholder logic; a
4
+ // wrong/renamed i18n key or a missing LocaleProvider fallback would stay
5
+ // green there).
6
+
7
+ import { describe, expect, test } from "bun:test";
8
+ import {
9
+ createStaticLocaleResolver,
10
+ kumikoDefaultTranslations,
11
+ LocaleProvider,
12
+ } from "@cosmicdrift/kumiko-renderer";
13
+ import { render, screen } from "@testing-library/react";
14
+ import { DateField } from "../date-field";
15
+
16
+ function renderWithLocale(locale: string) {
17
+ return render(
18
+ <LocaleProvider
19
+ resolver={createStaticLocaleResolver({ locale })}
20
+ fallbackBundles={[kumikoDefaultTranslations]}
21
+ >
22
+ <DateField id="date" name="date" value="" onChange={() => {}} locale={locale} />
23
+ </LocaleProvider>,
24
+ );
25
+ }
26
+
27
+ describe("DateField placeholder", () => {
28
+ test("de-DE → placeholder built from t() keys, not a hardcoded pattern", () => {
29
+ renderWithLocale("de-DE");
30
+ expect(screen.getByRole("textbox").getAttribute("placeholder")).toBe("TT.MM.JJJJ");
31
+ });
32
+
33
+ test("en-US → placeholder built from t() keys, not a hardcoded pattern", () => {
34
+ renderWithLocale("en-US");
35
+ expect(screen.getByRole("textbox").getAttribute("placeholder")).toBe("MM/DD/YYYY");
36
+ });
37
+ });