@olenbetong/synergi-react 5.7.0 → 5.9.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.
@@ -0,0 +1,365 @@
1
+ import type { AfDataObject, FieldDefinition } from "@olenbetong/appframe-data";
2
+ import { useEffect, useLayoutEffect, useRef } from "react";
3
+
4
+ import { getLocalizedString, localize } from "../i18n.js";
5
+ import { type AssistantTool, withAssistant } from "./assistant.js";
6
+
7
+ /*
8
+ * Generic record tools for the assistant: an app opts a data object in with
9
+ * `useAssistantDataObject`, naming the fields the model may see and those it may change, and the
10
+ * page gets one `read_records` and (when anything is editable) one `update_records`, whatever the
11
+ * number of data objects. The data object's own permissions and field metadata decide the rest.
12
+ */
13
+
14
+ /** One field the assistant may see. */
15
+ export type AssistantField = {
16
+ /** What the user calls the field, in their language; shown in the approval ("Tittel"). */
17
+ label: string;
18
+ /** For the model, when the label alone does not say what the values mean ("1 open, 2 closed"). */
19
+ description?: string;
20
+ /** Whether the assistant may change it (after the user's approval). Default false. */
21
+ editable?: boolean;
22
+ };
23
+
24
+ export type AssistantDataObjectOptions<T extends Record<string, unknown>> = {
25
+ /** The id the model uses for the data object, e.g. "issues". Letters, digits and `_`; unique on the page. */
26
+ name: string;
27
+ /** What the user calls the records, in their language ("Avvik"); shown in the approval. */
28
+ label: string;
29
+ /** For the model: what one record is and what the list holds ("The issues in the list, as filtered"). */
30
+ description: string;
31
+ /**
32
+ * The fields the assistant may see, and of those which it may change. Nothing else is read, so
33
+ * leave out anything the assistant must not see. The unique id field is always included.
34
+ */
35
+ fields: Partial<Record<keyof T & string, AssistantField>>;
36
+ /** The field that names a record in the approval ("Title"); without it the id is shown. */
37
+ titleField?: keyof T & string;
38
+ };
39
+
40
+ type Entry = {
41
+ dataObject: AfDataObject<any>;
42
+ options: () => AssistantDataObjectOptions<any>;
43
+ };
44
+
45
+ const READ_LIMIT = 25;
46
+ const MAX_READ_LIMIT = 100;
47
+ const MAX_CHANGES = 20;
48
+ const NAME = /^[A-Za-z0-9_]{1,64}$/;
49
+
50
+ const entries = new Map<string, Entry>();
51
+ let unregisterTools: (() => void) | null = null;
52
+
53
+ /** Fields that can never be written from the client: computed, identity, joined and the id. */
54
+ function isWritable(dataObject: AfDataObject<any>, field: string) {
55
+ let definition: FieldDefinition | undefined = dataObject.getFields(field);
56
+ if (!definition) return false;
57
+ if (definition.computed || definition.identity || definition.joined) return false;
58
+ return field !== String(dataObject.getUniqueIdField());
59
+ }
60
+
61
+ function editableFields(entry: Entry) {
62
+ let { fields } = entry.options();
63
+ return Object.keys(fields).filter((field) => fields[field]?.editable && isWritable(entry.dataObject, field));
64
+ }
65
+
66
+ function canUpdate(entry: Entry) {
67
+ return entry.dataObject.isUpdateAllowed() && editableFields(entry).length > 0;
68
+ }
69
+
70
+ function describeEntry(name: string, entry: Entry, withEditable: boolean) {
71
+ let options = entry.options();
72
+ let fields = Object.entries(options.fields as Record<string, AssistantField | undefined>)
73
+ .filter(([field]) => entry.dataObject.hasField(field))
74
+ .map(([field, spec]) => {
75
+ let parts = [field];
76
+ if (spec?.description) parts.push(`(${spec.description})`);
77
+ if (withEditable && spec?.editable && isWritable(entry.dataObject, field)) parts.push("[editable]");
78
+ return parts.join(" ");
79
+ });
80
+ return `- ${name}: ${options.description} Fields: ${fields.join(", ")}.`;
81
+ }
82
+
83
+ function recordFor(entry: Entry, index: number) {
84
+ let { dataObject } = entry;
85
+ let options = entry.options();
86
+ let idField = String(dataObject.getUniqueIdField());
87
+ let row = dataObject.getData(index) as Record<string, unknown>;
88
+ let record: Record<string, unknown> = { index, id: row[idField] };
89
+ for (let field of Object.keys(options.fields)) {
90
+ if (dataObject.hasField(field)) record[field] = row[field] ?? null;
91
+ }
92
+ return record;
93
+ }
94
+
95
+ type ReadArgs = { data_object?: string; offset?: number; limit?: number; current_only?: boolean };
96
+ type ChangeArgs = { data_object?: string; changes?: { id?: unknown; fields?: Record<string, unknown> }[] };
97
+
98
+ function entryFor(name: string | undefined): Entry | { error: string } {
99
+ let entry = name ? entries.get(name) : undefined;
100
+ return entry ?? { error: `No data object "${name}". Use one of: ${[...entries.keys()].join(", ")}.` };
101
+ }
102
+
103
+ function readTool(names: string[]): AssistantTool<ReadArgs> {
104
+ return {
105
+ name: "read_records",
106
+ label: getLocalizedString("Read records"),
107
+ description: [
108
+ "Reads the records the page has loaded in one of its data objects, as the user sees them: index, id and the fields listed below. current_only reads only the record the user has open. Long lists come in parts: call again with offset. Data objects:",
109
+ ...names.map((name) => describeEntry(name, entries.get(name)!, false)),
110
+ ].join("\n"),
111
+ parameters: {
112
+ type: "object",
113
+ properties: {
114
+ data_object: { type: "string", enum: names },
115
+ offset: { type: "integer", description: "The first index to read; default 0." },
116
+ limit: {
117
+ type: "integer",
118
+ description: `At most this many records; default ${READ_LIMIT}, at most ${MAX_READ_LIMIT}.`,
119
+ },
120
+ current_only: { type: "boolean", description: "Only the record the user has open." },
121
+ },
122
+ required: ["data_object"],
123
+ },
124
+ handler: (args) => {
125
+ let entry = entryFor(args.data_object);
126
+ if ("error" in entry) return entry;
127
+ let { dataObject } = entry;
128
+ let current = dataObject.getCurrentIndex();
129
+ if (args.current_only) {
130
+ return current >= 0 ? { record: recordFor(entry, current) } : { record: null, note: "No record is open." };
131
+ }
132
+ let total = dataObject.getDataLength();
133
+ let offset = Math.max(0, Math.floor(args.offset ?? 0));
134
+ let limit = Math.min(MAX_READ_LIMIT, Math.max(1, Math.floor(args.limit ?? READ_LIMIT)));
135
+ let records = [];
136
+ for (let index = offset; index < Math.min(total, offset + limit); index++) records.push(recordFor(entry, index));
137
+ return {
138
+ loaded: total,
139
+ current_index: current,
140
+ records,
141
+ ...(offset + limit < total ? { note: `More records: call again with offset ${offset + limit}.` } : {}),
142
+ };
143
+ },
144
+ };
145
+ }
146
+
147
+ type Planned = { index: number; id: unknown; title: string; fields: Record<string, unknown> };
148
+
149
+ /** Checks every change before anything is asked or saved; the first problem refuses them all. */
150
+ function planChanges(entry: Entry, args: ChangeArgs): Planned[] | { error: string } {
151
+ let { dataObject } = entry;
152
+ let options = entry.options();
153
+ let changes = args.changes ?? [];
154
+ if (!Array.isArray(changes) || changes.length === 0) return { error: "Give at least one change." };
155
+ if (changes.length > MAX_CHANGES) return { error: `At most ${MAX_CHANGES} records in one call.` };
156
+ if (!dataObject.isUpdateAllowed()) return { error: "Records cannot be changed here." };
157
+
158
+ let allowed = new Set(editableFields(entry));
159
+ let idField = String(dataObject.getUniqueIdField());
160
+ let rows = dataObject.getData() as Record<string, unknown>[];
161
+ let planned: Planned[] = [];
162
+ for (let change of changes) {
163
+ let index = rows.findIndex((row) => String(row[idField]) === String(change.id));
164
+ if (index < 0) return { error: `No loaded record has id ${String(change.id)}. Read the records first.` };
165
+ let fields = change.fields ?? {};
166
+ if (Object.keys(fields).length === 0) return { error: `No fields to change for id ${String(change.id)}.` };
167
+ for (let [field, value] of Object.entries(fields)) {
168
+ if (!allowed.has(field)) {
169
+ return { error: `${field} cannot be changed. Editable fields: ${[...allowed].join(", ")}.` };
170
+ }
171
+ let problem = valueProblem(dataObject, field, value);
172
+ if (problem) return { error: `${field} on id ${String(change.id)}: ${problem}` };
173
+ }
174
+ let title = options.titleField ? rows[index][options.titleField] : null;
175
+ planned.push({
176
+ index,
177
+ id: rows[index][idField],
178
+ title: title == null ? String(rows[index][idField]) : String(title),
179
+ fields,
180
+ });
181
+ }
182
+ return planned;
183
+ }
184
+
185
+ function valueProblem(dataObject: AfDataObject<any>, field: string, value: unknown): string | null {
186
+ let definition = dataObject.getFields(field);
187
+ if (value === null) return dataObject.isNullable(field) ? null : "it cannot be empty.";
188
+ switch (definition?.type) {
189
+ case "number":
190
+ case "bigint":
191
+ return typeof value === "number" && Number.isFinite(value) ? null : "give a number.";
192
+ case "boolean":
193
+ return typeof value === "boolean" ? null : "give true or false.";
194
+ default:
195
+ if (typeof value !== "string") return "give text.";
196
+ if (definition?.maxLength && definition.maxLength > 0 && value.length > definition.maxLength) {
197
+ return `at most ${definition.maxLength} characters.`;
198
+ }
199
+ return null;
200
+ }
201
+ }
202
+
203
+ function shown(value: unknown) {
204
+ if (value === null || value === undefined || value === "") return "–";
205
+ let text = String(value);
206
+ return text.length > 80 ? `${text.slice(0, 80)}…` : text;
207
+ }
208
+
209
+ function question(entry: Entry, planned: Planned[]) {
210
+ let options = entry.options();
211
+ let lines = planned.map((change) => {
212
+ let row = entry.dataObject.getData(change.index) as Record<string, unknown>;
213
+ let diffs = Object.entries(change.fields).map(
214
+ ([field, value]) => `${options.fields[field]?.label ?? field}: «${shown(row[field])}» → «${shown(value)}»`,
215
+ );
216
+ return `- ${change.title}: ${diffs.join("; ")}`;
217
+ });
218
+ return [localize`Save changes to ${planned.length} records in ${options.label}?`, ...lines].join("\n");
219
+ }
220
+
221
+ function updateTool(names: string[]): AssistantTool<ChangeArgs> {
222
+ return {
223
+ name: "update_records",
224
+ label: getLocalizedString("Change records"),
225
+ description: [
226
+ "Changes fields of loaded records in one of the page's data objects and saves them, after the user approves all the changes at once. Only the fields marked [editable] can be changed; give each record's id from read_records. Put every change into one call. Refused while the user has unsaved changes in the form. Data objects:",
227
+ ...names.map((name) => describeEntry(name, entries.get(name)!, true)),
228
+ ].join("\n"),
229
+ parameters: {
230
+ type: "object",
231
+ properties: {
232
+ data_object: { type: "string", enum: names },
233
+ changes: {
234
+ type: "array",
235
+ items: {
236
+ type: "object",
237
+ properties: {
238
+ id: { type: ["string", "number"], description: "The record's id from read_records." },
239
+ fields: { type: "object", description: "The new values by field name; null empties a field." },
240
+ },
241
+ required: ["id", "fields"],
242
+ },
243
+ },
244
+ },
245
+ required: ["data_object", "changes"],
246
+ },
247
+ confirm: (args) => {
248
+ let entry = entryFor(args.data_object);
249
+ if ("error" in entry) return null;
250
+ let planned = planChanges(entry, args);
251
+ return Array.isArray(planned) ? question(entry, planned) : null;
252
+ },
253
+ handler: async (args) => {
254
+ let entry = entryFor(args.data_object);
255
+ if ("error" in entry) return entry;
256
+ let planned = planChanges(entry, args);
257
+ if (!Array.isArray(planned)) return { saved: [], ...planned };
258
+
259
+ let { dataObject } = entry;
260
+ let idField = String(dataObject.getUniqueIdField());
261
+ let saved: unknown[] = [];
262
+ for (let change of planned) {
263
+ if (dataObject.isDirty()) {
264
+ return {
265
+ saved,
266
+ error:
267
+ "The open record has unsaved changes. Ask the user to save or undo them first; the rest was not changed.",
268
+ };
269
+ }
270
+ let index = (dataObject.getData() as Record<string, unknown>[]).findIndex(
271
+ (row) => String(row[idField]) === String(change.id),
272
+ );
273
+ if (index < 0) return { saved, error: `The record with id ${String(change.id)} is no longer loaded.` };
274
+ try {
275
+ if (dataObject.getCurrentIndex() !== index) await dataObject.setCurrentIndex(index, true);
276
+ let result = await (dataObject.save as (data: Record<string, unknown>) => Promise<unknown>)(change.fields);
277
+ if (result === false) {
278
+ dataObject.cancelEdit();
279
+ return { saved, error: `The record with id ${String(change.id)} was not saved.` };
280
+ }
281
+ saved.push(change.id);
282
+ } catch (error) {
283
+ dataObject.cancelEdit();
284
+ return { saved, error: `Saving id ${String(change.id)} failed: ${(error as Error).message}` };
285
+ }
286
+ }
287
+ return { saved };
288
+ },
289
+ };
290
+ }
291
+
292
+ /** Registers the two shared tools again for the data objects now on the page. */
293
+ function syncTools() {
294
+ unregisterTools?.();
295
+ unregisterTools = null;
296
+ let names = [...entries.keys()].sort();
297
+ if (names.length === 0) return;
298
+ let editable = names.filter((name) => canUpdate(entries.get(name)!));
299
+ unregisterTools = withAssistant((assistant) => {
300
+ let undo = [assistant.registerTool(readTool(names))];
301
+ if (editable.length > 0) undo.push(assistant.registerTool(updateTool(editable)));
302
+ return () => undo.forEach((unregister) => unregister());
303
+ });
304
+ }
305
+
306
+ /**
307
+ * Lets the assistant read a data object's loaded records and, for the fields marked editable,
308
+ * change and save them after the user approves. Only the fields listed are ever read. All data
309
+ * objects on the page share one `read_records` and one `update_records` tool, so opting in more of
310
+ * them adds no tools. Use it for plain records; keep domain actions (close, approve, send) as tools
311
+ * of their own, since they do more than set fields.
312
+ *
313
+ * @example
314
+ * ```tsx
315
+ * useAssistantDataObject(dsIssues, {
316
+ * name: "issues",
317
+ * label: getLocalizedString("Issues"),
318
+ * description: "The issues in the list, as filtered.",
319
+ * titleField: "Title",
320
+ * fields: {
321
+ * Title: { label: getLocalizedString("Title"), editable: true },
322
+ * Status: { label: getLocalizedString("Status"), description: "1 open, 2 closed" },
323
+ * },
324
+ * });
325
+ * ```
326
+ */
327
+ export function useAssistantDataObject<T extends Record<string, unknown>>(
328
+ dataObject: AfDataObject<T> | null | undefined,
329
+ options: AssistantDataObjectOptions<T> | null | false | undefined,
330
+ ) {
331
+ let latest = useRef(options);
332
+ useLayoutEffect(() => {
333
+ latest.current = options;
334
+ });
335
+
336
+ let key = options
337
+ ? JSON.stringify([
338
+ options.name,
339
+ options.description,
340
+ options.titleField ?? null,
341
+ Object.entries(options.fields as Record<string, AssistantField | undefined>).map(([field, spec]) => [
342
+ field,
343
+ spec?.description ?? null,
344
+ Boolean(spec?.editable),
345
+ ]),
346
+ ])
347
+ : null;
348
+
349
+ useEffect(() => {
350
+ let current = latest.current;
351
+ if (!key || !current || !dataObject) return;
352
+ if (!NAME.test(current.name)) {
353
+ throw new Error(`Assistant data object "${current.name}" must be letters, digits and _, at most 64 characters.`);
354
+ }
355
+ let entry: Entry = { dataObject, options: () => latest.current || current };
356
+ let name = current.name;
357
+ entries.set(name, entry);
358
+ syncTools();
359
+ return () => {
360
+ if (entries.get(name) !== entry) return;
361
+ entries.delete(name);
362
+ syncTools();
363
+ };
364
+ }, [key, dataObject]);
365
+ }
@@ -0,0 +1,205 @@
1
+ import clsx from "clsx";
2
+ import * as monaco from "monaco-editor";
3
+ import { forwardRef, useEffect, useImperativeHandle, useRef } from "react";
4
+
5
+ import { useResolvedColorScheme } from "../../colorScheme.js";
6
+ import "./CodeEditor.css";
7
+
8
+ /*
9
+ * Where Monaco comes from is described in CodeEditor.tsx. The diff editor needs nothing more: the
10
+ * platform's `monaco-editor` entry is the full build, and the diff is computed in the editor worker
11
+ * its `MonacoEnvironment` already serves.
12
+ */
13
+
14
+ export type CodeDiffEditorHandle = {
15
+ /** The Monaco diff editor instance, once mounted. */
16
+ editor: monaco.editor.IStandaloneDiffEditor | null;
17
+ /** Focuses the modified (editable) side. */
18
+ focus(): void;
19
+ };
20
+
21
+ export type CodeDiffEditorProps = {
22
+ /** The text compared against (left / removed side). Never editable. */
23
+ original: string;
24
+ /** The current text (right / added side). Controlled: `onChange` reports every edit. */
25
+ value: string;
26
+ onChange?: (value: string) => void;
27
+ /** Monaco language ID for both sides, e.g. `html`, `css`, `json`, `markdown`. */
28
+ language?: string;
29
+ /**
30
+ * Identifies the document. When it changes, both sides get fresh models, so undo history does
31
+ * not leak from one record to the next. Without it, a new `value` is applied as an edit that
32
+ * can be undone.
33
+ */
34
+ docKey?: string;
35
+ /** Makes the modified side read-only. The original side is always read-only. */
36
+ readOnly?: boolean;
37
+ /** One column with changes inline (default), or two columns side by side. */
38
+ inline?: boolean;
39
+ /** Ctrl/Cmd+S inside the modified side. */
40
+ onSave?: () => void;
41
+ /** Extra Monaco options, applied on mount and whenever the object changes. */
42
+ options?: monaco.editor.IDiffEditorOptions;
43
+ className?: string;
44
+ style?: React.CSSProperties;
45
+ "aria-label"?: string;
46
+ };
47
+
48
+ function diffOptions(
49
+ inline: boolean,
50
+ readOnly: boolean,
51
+ options: monaco.editor.IDiffEditorOptions | undefined,
52
+ ): monaco.editor.IDiffEditorOptions {
53
+ return {
54
+ renderSideBySide: !inline,
55
+ // Monaco otherwise drops to the inline view below 900px, which would ignore `inline={false}`.
56
+ useInlineViewWhenSpaceIsLimited: inline ? undefined : false,
57
+ readOnly,
58
+ ...options,
59
+ originalEditable: false,
60
+ };
61
+ }
62
+
63
+ /**
64
+ * Monaco diff editor that follows the site's colour scheme: `original` against an editable
65
+ * `value`. Unchanged regions collapse, so long documents show only what differs. The element fills
66
+ * its parent's size through `className`/`style`; give it a height.
67
+ */
68
+ export const CodeDiffEditor = forwardRef<CodeDiffEditorHandle, CodeDiffEditorProps>(function CodeDiffEditor(
69
+ {
70
+ original,
71
+ value,
72
+ onChange,
73
+ language = "plaintext",
74
+ docKey,
75
+ readOnly = false,
76
+ inline = true,
77
+ onSave,
78
+ options,
79
+ className,
80
+ style,
81
+ "aria-label": ariaLabel,
82
+ },
83
+ ref,
84
+ ) {
85
+ let container = useRef<HTMLDivElement>(null);
86
+ let editor = useRef<monaco.editor.IStandaloneDiffEditor | null>(null);
87
+ // Latest callbacks without re-creating the editor.
88
+ let callbacks = useRef({ onChange, onSave });
89
+ callbacks.current = { onChange, onSave };
90
+ // Set while the editor applies a `value` from props, so that edit is not reported back.
91
+ let applyingValue = useRef(false);
92
+ let shownDoc = useRef<string | undefined>(undefined);
93
+ let colorScheme = useResolvedColorScheme();
94
+
95
+ useEffect(() => {
96
+ if (!container.current) return;
97
+ let instance = monaco.editor.createDiffEditor(container.current, {
98
+ theme: colorScheme === "dark" ? "vs-dark" : "vs",
99
+ automaticLayout: true,
100
+ minimap: { enabled: false },
101
+ scrollBeyondLastLine: false,
102
+ fixedOverflowWidgets: true,
103
+ renderOverviewRuler: true,
104
+ hideUnchangedRegions: { enabled: true },
105
+ modifiedAriaLabel: ariaLabel,
106
+ ...diffOptions(inline, readOnly, options),
107
+ });
108
+ instance.setModel({
109
+ original: monaco.editor.createModel(original, language),
110
+ modified: monaco.editor.createModel(value, language),
111
+ });
112
+ editor.current = instance;
113
+ shownDoc.current = docKey;
114
+
115
+ let modifiedEditor = instance.getModifiedEditor();
116
+ let changeListener = modifiedEditor.onDidChangeModelContent(() => {
117
+ if (!applyingValue.current) {
118
+ callbacks.current.onChange?.(modifiedEditor.getValue());
119
+ }
120
+ });
121
+ modifiedEditor.addCommand(monaco.KeyMod.CtrlCmd | monaco.KeyCode.KeyS, () => callbacks.current.onSave?.());
122
+
123
+ return () => {
124
+ changeListener.dispose();
125
+ // The diff editor does not own its models; dispose them once nothing shows them.
126
+ let models = instance.getModel();
127
+ instance.dispose();
128
+ models?.original.dispose();
129
+ models?.modified.dispose();
130
+ editor.current = null;
131
+ };
132
+ // The editor is created once; every prop is synced by the effects below.
133
+ // oxlint-disable-next-line react-hooks/exhaustive-deps
134
+ }, []);
135
+
136
+ useEffect(() => {
137
+ let instance = editor.current;
138
+ if (!instance) return;
139
+
140
+ applyingValue.current = true;
141
+ try {
142
+ if (shownDoc.current !== docKey) {
143
+ // New document: new models, so undo history stays with the document it belongs to.
144
+ let old = instance.getModel();
145
+ instance.setModel({
146
+ original: monaco.editor.createModel(original, language),
147
+ modified: monaco.editor.createModel(value, language),
148
+ });
149
+ old?.original.dispose();
150
+ old?.modified.dispose();
151
+ shownDoc.current = docKey;
152
+ return;
153
+ }
154
+
155
+ let models = instance.getModel();
156
+ if (!models) return;
157
+ // The original side is never edited, so there is no undo history to keep.
158
+ if (models.original.getValue() !== original) {
159
+ models.original.setValue(original);
160
+ }
161
+ if (models.modified.getValue() !== value) {
162
+ // Same document, changed from outside (cancel, reload): one undoable edit.
163
+ instance
164
+ .getModifiedEditor()
165
+ .executeEdits("external", [{ range: models.modified.getFullModelRange(), text: value }]);
166
+ }
167
+ } finally {
168
+ applyingValue.current = false;
169
+ }
170
+ }, [docKey, original, value, language]);
171
+
172
+ useEffect(() => {
173
+ let models = editor.current?.getModel();
174
+ if (!models) return;
175
+ for (let model of [models.original, models.modified]) {
176
+ if (model.getLanguageId() !== language) {
177
+ monaco.editor.setModelLanguage(model, language);
178
+ }
179
+ }
180
+ }, [language]);
181
+
182
+ useEffect(() => {
183
+ let instance = editor.current;
184
+ if (!instance) return;
185
+ instance.updateOptions(diffOptions(inline, readOnly, options));
186
+ instance.getModifiedEditor().updateOptions({ ariaLabel });
187
+ }, [inline, readOnly, ariaLabel, options]);
188
+
189
+ useEffect(() => {
190
+ // The theme is global to every editor on the page.
191
+ monaco.editor.setTheme(colorScheme === "dark" ? "vs-dark" : "vs");
192
+ }, [colorScheme]);
193
+
194
+ useImperativeHandle(ref, () => ({
195
+ get editor() {
196
+ return editor.current;
197
+ },
198
+ focus() {
199
+ editor.current?.getModifiedEditor().focus();
200
+ },
201
+ }));
202
+
203
+ // `monaco-component`: see CodeEditor - Monaco's context menu needs the theme variables it defines on that class.
204
+ return <div ref={container} className={clsx("ObCodeEditor-root", "monaco-component", className)} style={style} />;
205
+ });
@@ -1 +1,2 @@
1
+ export { CodeDiffEditor, type CodeDiffEditorHandle, type CodeDiffEditorProps } from "./CodeDiffEditor.js";
1
2
  export { CodeEditor, type CodeEditorHandle, type CodeEditorProps } from "./CodeEditor.js";
@@ -16,11 +16,10 @@
16
16
  overflow: hidden;
17
17
  display: flex;
18
18
  font-size: var(--ds-font-size-3, 1rem);
19
- outline: none;
20
19
  /* Set here rather than on :root so it follows the nearest data-size. */
21
20
  --ob-datenavigator-height: var(--ds-size-12, 3rem);
22
21
 
23
- &:focus-visible {
22
+ &:focus {
24
23
  outline: 2px solid var(--brand-dark, #336699);
25
24
  outline-offset: 2px;
26
25
  }
@@ -45,6 +44,12 @@
45
44
  cursor: not-allowed;
46
45
  color: var(--ds-color-neutral-border-default, rgba(0 0 0 / 0.2));
47
46
  }
47
+
48
+ /* Inside the edge: the root clips its children to its rounded corners. */
49
+ &:focus {
50
+ outline: 2px solid var(--brand-dark, #336699);
51
+ outline-offset: -2px;
52
+ }
48
53
  }
49
54
 
50
55
  .ObDateNavigator-arrowLeft {
@@ -89,7 +94,7 @@
89
94
  background-color: var(--ds-color-neutral-surface-hover, var(--block-header-button-hover, #e3e3e3));
90
95
  }
91
96
 
92
- &:focus-visible {
97
+ &:focus {
93
98
  outline: 2px solid var(--brand-dark, #336699);
94
99
  outline-offset: 2px;
95
100
  }
@@ -3,28 +3,43 @@ import { Document, Page, pdfjs } from "react-pdf";
3
3
  import "./PdfViewer.css";
4
4
 
5
5
  /*
6
- * pdf.js parses in a Web Worker that must be loaded from a URL on the page's origin. On the
7
- * 2026 templates pdfjs-dist comes from the platform bundle through the import map, and the
8
- * platform serves the worker next to it - so resolve the specifier the way the browser does
9
- * and step up one level. This makes the viewer platform-only: off the platform (a legacy
10
- * template bundling this package) the specifier does not resolve, pdf.js logs a warning and
11
- * parses on the main thread. A `new URL(..., import.meta.url)` fallback would make Vite emit
12
- * the 1.2 MB worker into every consumer's build output without anything ever serving it.
6
+ * pdf.js needs files served from the page's own origin: the Web Worker it parses in, WebAssembly
7
+ * decoders for JBIG2 and JPEG 2000 images (common in scanned documents) and ICC colour profiles, and
8
+ * stand-ins for the standard fonts of a PDF that does not embed them. On the 2026 templates
9
+ * pdfjs-dist comes from the platform bundle through the import map, and the platform serves the
10
+ * worker (`pdf.worker.min.js`) and the folders `wasm/`, `standard_fonts/` and `iccs/` next to it -
11
+ * so resolve the specifier the way the browser does and step up one level. This always gives the
12
+ * files of the pdf.js that is on the page.
13
+ *
14
+ * This makes the viewer platform-only: off the platform (a legacy template bundling this package)
15
+ * the specifier does not resolve, pdf.js logs a warning and parses on the main thread, images in
16
+ * those formats are left out and missing fonts are replaced by the browser's. A
17
+ * `new URL(..., import.meta.url)` fallback would make Vite emit the 1.2 MB worker into every
18
+ * consumer's build output without anything ever serving it.
13
19
  */
14
- function platformWorkerUrl(): string | undefined {
20
+ function platformUrl(relative: string): string | undefined {
15
21
  try {
16
- return new URL("../pdf.worker.min.js", import.meta.resolve("pdfjs-dist")).toString();
22
+ return new URL(relative, import.meta.resolve("pdfjs-dist")).toString();
17
23
  } catch {
18
- console.warn("PdfViewer: pdfjs-dist is not on the page's import map; pdf.js will parse on the main thread.");
19
24
  return undefined;
20
25
  }
21
26
  }
22
27
 
23
- let workerUrl = platformWorkerUrl();
28
+ let workerUrl = platformUrl("../pdf.worker.min.js");
24
29
  if (workerUrl) {
25
30
  pdfjs.GlobalWorkerOptions.workerSrc = workerUrl;
31
+ } else {
32
+ console.warn("PdfViewer: pdfjs-dist is not on the page's import map; pdf.js will parse on the main thread.");
26
33
  }
27
34
 
35
+ // Module level: react-pdf reloads the document whenever `options` is a new object.
36
+ const platformOptions = {
37
+ wasmUrl: platformUrl("../wasm/"),
38
+ standardFontDataUrl: platformUrl("../standard_fonts/"),
39
+ iccUrl: platformUrl("../iccs/"),
40
+ };
41
+ const documentOptions = workerUrl ? platformOptions : undefined;
42
+
28
43
  type PdfViewerProps = { url?: string; file?: string | Blob | ArrayBuffer };
29
44
 
30
45
  export function PdfViewer({ url, file }: PdfViewerProps) {
@@ -99,11 +114,15 @@ export function PdfViewer({ url, file }: PdfViewerProps) {
99
114
  };
100
115
  }, []);
101
116
 
102
- // When source changes, reset auto-fit baseline
103
- useEffect(() => {
117
+ // When the source changes, reset the auto-fit baseline and forget the last error (adjusted
118
+ // during render rather than in an effect, to avoid a cascading render)
119
+ let [prevSource, setPrevSource] = useState({ url, file });
120
+ if (prevSource.url !== url || prevSource.file !== file) {
121
+ setPrevSource({ url, file });
104
122
  setNaturalPageSize(null);
105
123
  setScale(1);
106
- }, [url, file]);
124
+ setError(null);
125
+ }
107
126
 
108
127
  // Compute base width to fit full page into container, then apply zoom scale.
109
128
  // If we don't yet know page's natural size, default to fit-to-width.
@@ -124,6 +143,7 @@ export function PdfViewer({ url, file }: PdfViewerProps) {
124
143
  <div className="pdfViewerContent">
125
144
  <Document
126
145
  file={file ?? url}
146
+ options={documentOptions}
127
147
  onLoadSuccess={({ numPages }) => setNumPages(numPages)}
128
148
  onLoadError={(e) => setError((e as Error)?.message ?? "Failed to load PDF")}
129
149
  >