@olenbetong/synergi-react 5.8.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.
- package/dist/styles/styles.css +1 -1
- package/dist/styles/styles.css.map +1 -1
- package/es/chrome/assistant.d.ts +52 -2
- package/es/chrome/assistant.js +87 -21
- package/es/chrome/assistantDataObjects.d.ts +47 -0
- package/es/chrome/assistantDataObjects.js +318 -0
- package/es/components/DateNavigator/index.css +8 -3
- package/es/components/PdfViewer/PdfViewer.js +34 -15
- package/es/components/Toolbar/Toolbar.css +3 -3
- package/es/components/ValueToggleGroup/index.css +1 -1
- package/es/index.css +1 -1
- package/es/index.d.ts +2 -1
- package/es/index.js +2 -1
- package/package.json +2 -2
- package/src/chrome/assistant.test.tsx +55 -1
- package/src/chrome/assistant.ts +126 -24
- package/src/chrome/assistantDataObjects.test.tsx +162 -0
- package/src/chrome/assistantDataObjects.ts +365 -0
- package/src/components/DateNavigator/index.css +8 -3
- package/src/components/PdfViewer/PdfViewer.tsx +34 -14
- package/src/components/Toolbar/Toolbar.css +3 -3
- package/src/components/Toolbar/ToolbarBreadcrumbs.browser.test.tsx +3 -2
- package/src/components/Toolbar/index.tsx +2 -1
- package/src/components/ValueToggleGroup/index.css +1 -1
- package/src/index.ts +7 -0
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
import { render } from "@testing-library/react";
|
|
2
|
+
import { afterEach, describe, expect, it, vi } from "vitest";
|
|
3
|
+
|
|
4
|
+
vi.mock("@olenbetong/appframe-core", () => ({
|
|
5
|
+
createLocalizer: () => ({
|
|
6
|
+
getLocalizedString: (value: string) => value,
|
|
7
|
+
localize: (strings: TemplateStringsArray, ...values: unknown[]) =>
|
|
8
|
+
strings.reduce((text, part, index) => text + part + (index < values.length ? String(values[index]) : ""), ""),
|
|
9
|
+
}),
|
|
10
|
+
}));
|
|
11
|
+
|
|
12
|
+
import { useAssistantDataObject } from "./assistantDataObjects";
|
|
13
|
+
|
|
14
|
+
let globals = globalThis as { ob?: unknown };
|
|
15
|
+
|
|
16
|
+
type Row = { PrimKey: string; Title: string; Status: number; Secret: string; Computed: string };
|
|
17
|
+
|
|
18
|
+
const FIELDS = [
|
|
19
|
+
{ name: "PrimKey", type: "uniqueidentifier" },
|
|
20
|
+
{ name: "Title", type: "string", maxLength: 10 },
|
|
21
|
+
{ name: "Status", type: "number" },
|
|
22
|
+
{ name: "Secret", type: "string" },
|
|
23
|
+
{ name: "Computed", type: "string", computed: true },
|
|
24
|
+
];
|
|
25
|
+
|
|
26
|
+
function fakeDataObject(rows: Row[], { updatable = true } = {}) {
|
|
27
|
+
let data = rows.map((row) => ({ ...row }));
|
|
28
|
+
let current = 0;
|
|
29
|
+
let dirty = false;
|
|
30
|
+
return {
|
|
31
|
+
data,
|
|
32
|
+
getData: (index?: number) => (index === undefined ? data : data[index]),
|
|
33
|
+
getDataLength: () => data.length,
|
|
34
|
+
getCurrentIndex: () => current,
|
|
35
|
+
setCurrentIndex: vi.fn(async (index: number) => {
|
|
36
|
+
current = index;
|
|
37
|
+
return true;
|
|
38
|
+
}),
|
|
39
|
+
getUniqueIdField: () => "PrimKey",
|
|
40
|
+
getFields: (name: string) => FIELDS.find((field) => field.name === name),
|
|
41
|
+
hasField: (name: string) => FIELDS.some((field) => field.name === name),
|
|
42
|
+
isNullable: () => false,
|
|
43
|
+
isUpdateAllowed: () => updatable,
|
|
44
|
+
isDirty: () => dirty,
|
|
45
|
+
setDirty: (value: boolean) => {
|
|
46
|
+
dirty = value;
|
|
47
|
+
},
|
|
48
|
+
save: vi.fn(async (fields: Partial<Row>) => {
|
|
49
|
+
Object.assign(data[current], fields);
|
|
50
|
+
return data[current];
|
|
51
|
+
}),
|
|
52
|
+
cancelEdit: vi.fn(),
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function fakeAssistant() {
|
|
57
|
+
let tools = new Map<string, any>();
|
|
58
|
+
return {
|
|
59
|
+
enabled: true,
|
|
60
|
+
tools,
|
|
61
|
+
registerTool: vi.fn((tool: any) => {
|
|
62
|
+
tools.set(tool.name, tool);
|
|
63
|
+
return () => {
|
|
64
|
+
if (tools.get(tool.name) === tool) tools.delete(tool.name);
|
|
65
|
+
};
|
|
66
|
+
}),
|
|
67
|
+
setContext: vi.fn(),
|
|
68
|
+
open: vi.fn(),
|
|
69
|
+
close: vi.fn(),
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function Issues({ dataObject }: { dataObject: any }) {
|
|
74
|
+
useAssistantDataObject<Row>(dataObject, {
|
|
75
|
+
name: "issues",
|
|
76
|
+
label: "Avvik",
|
|
77
|
+
description: "The issues in the list.",
|
|
78
|
+
titleField: "Title",
|
|
79
|
+
fields: {
|
|
80
|
+
Title: { label: "Tittel", editable: true },
|
|
81
|
+
Status: { label: "Status", description: "1 open, 2 closed" },
|
|
82
|
+
Computed: { label: "Beregnet", editable: true },
|
|
83
|
+
},
|
|
84
|
+
});
|
|
85
|
+
return null;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
afterEach(() => {
|
|
89
|
+
delete globals.ob;
|
|
90
|
+
});
|
|
91
|
+
|
|
92
|
+
describe("useAssistantDataObject", () => {
|
|
93
|
+
it("reads only the listed fields and the id", async () => {
|
|
94
|
+
let assistant = fakeAssistant();
|
|
95
|
+
globals.ob = { chrome: { assistant } };
|
|
96
|
+
let dataObject = fakeDataObject([{ PrimKey: "a", Title: "Lekk", Status: 1, Secret: "x", Computed: "c" }]);
|
|
97
|
+
let view = render(<Issues dataObject={dataObject} />);
|
|
98
|
+
|
|
99
|
+
let read = assistant.tools.get("read_records");
|
|
100
|
+
expect(read.description).toContain("Status (1 open, 2 closed)");
|
|
101
|
+
let result = await read.handler({ data_object: "issues" });
|
|
102
|
+
expect(result.records).toEqual([{ index: 0, id: "a", Title: "Lekk", Status: 1, Computed: "c" }]);
|
|
103
|
+
|
|
104
|
+
view.unmount();
|
|
105
|
+
expect(assistant.tools.size).toBe(0);
|
|
106
|
+
});
|
|
107
|
+
|
|
108
|
+
it("changes only editable, writable fields, asking with labels and the old and new values", async () => {
|
|
109
|
+
let assistant = fakeAssistant();
|
|
110
|
+
globals.ob = { chrome: { assistant } };
|
|
111
|
+
let dataObject = fakeDataObject([
|
|
112
|
+
{ PrimKey: "a", Title: "Lekk", Status: 1, Secret: "x", Computed: "c" },
|
|
113
|
+
{ PrimKey: "b", Title: "Brudd", Status: 1, Secret: "y", Computed: "c" },
|
|
114
|
+
]);
|
|
115
|
+
let view = render(<Issues dataObject={dataObject} />);
|
|
116
|
+
let update = assistant.tools.get("update_records");
|
|
117
|
+
expect(update.description).toContain("Title [editable]");
|
|
118
|
+
expect(update.description).not.toContain("Computed [editable]");
|
|
119
|
+
|
|
120
|
+
let args = { data_object: "issues", changes: [{ id: "b", fields: { Title: "Sprekk" } }] };
|
|
121
|
+
expect(update.confirm(args)).toBe("Save changes to 1 records in Avvik?\n- Brudd: Tittel: «Brudd» → «Sprekk»");
|
|
122
|
+
expect(await update.handler(args)).toEqual({ saved: ["b"] });
|
|
123
|
+
expect(dataObject.data[1].Title).toBe("Sprekk");
|
|
124
|
+
|
|
125
|
+
for (let fields of [{ Status: 2 }, { Computed: "z" }, { Secret: "z" }, { Title: "far too long text" }]) {
|
|
126
|
+
let refused = { data_object: "issues", changes: [{ id: "a", fields }] };
|
|
127
|
+
expect(update.confirm(refused)).toBeNull();
|
|
128
|
+
expect((await update.handler(refused)).error).toBeTruthy();
|
|
129
|
+
}
|
|
130
|
+
expect(dataObject.save).toHaveBeenCalledTimes(1);
|
|
131
|
+
view.unmount();
|
|
132
|
+
});
|
|
133
|
+
|
|
134
|
+
it("refuses while the open record has unsaved changes", async () => {
|
|
135
|
+
let assistant = fakeAssistant();
|
|
136
|
+
globals.ob = { chrome: { assistant } };
|
|
137
|
+
let dataObject = fakeDataObject([{ PrimKey: "a", Title: "Lekk", Status: 1, Secret: "x", Computed: "c" }]);
|
|
138
|
+
dataObject.setDirty(true);
|
|
139
|
+
let view = render(<Issues dataObject={dataObject} />);
|
|
140
|
+
let result = await assistant.tools
|
|
141
|
+
.get("update_records")
|
|
142
|
+
.handler({ data_object: "issues", changes: [{ id: "a", fields: { Title: "Ny" } }] });
|
|
143
|
+
expect(result.error).toContain("unsaved changes");
|
|
144
|
+
expect(dataObject.save).not.toHaveBeenCalled();
|
|
145
|
+
view.unmount();
|
|
146
|
+
});
|
|
147
|
+
|
|
148
|
+
it("offers no update tool when the data object cannot be updated", () => {
|
|
149
|
+
let assistant = fakeAssistant();
|
|
150
|
+
globals.ob = { chrome: { assistant } };
|
|
151
|
+
let view = render(
|
|
152
|
+
<Issues
|
|
153
|
+
dataObject={fakeDataObject([{ PrimKey: "a", Title: "", Status: 1, Secret: "", Computed: "" }], {
|
|
154
|
+
updatable: false,
|
|
155
|
+
})}
|
|
156
|
+
/>,
|
|
157
|
+
);
|
|
158
|
+
expect(assistant.tools.has("read_records")).toBe(true);
|
|
159
|
+
expect(assistant.tools.has("update_records")).toBe(false);
|
|
160
|
+
view.unmount();
|
|
161
|
+
});
|
|
162
|
+
});
|
|
@@ -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
|
+
}
|
|
@@ -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
|
|
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
|
|
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
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
10
|
-
*
|
|
11
|
-
*
|
|
12
|
-
* the
|
|
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
|
|
20
|
+
function platformUrl(relative: string): string | undefined {
|
|
15
21
|
try {
|
|
16
|
-
return new URL(
|
|
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 =
|
|
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
|
-
|
|
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
|
-
|
|
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
|
>
|
|
@@ -34,7 +34,7 @@
|
|
|
34
34
|
color: var(--ds-link-default-hovered, var(--ds-text, currentColor));
|
|
35
35
|
}
|
|
36
36
|
|
|
37
|
-
&:focus
|
|
37
|
+
&:focus {
|
|
38
38
|
outline: 2px solid var(--ds-border-focused, currentColor);
|
|
39
39
|
outline-offset: 2px;
|
|
40
40
|
border-radius: var(--ds-border-radius-100, 2px);
|
|
@@ -71,7 +71,7 @@
|
|
|
71
71
|
color: var(--ds-text, currentColor);
|
|
72
72
|
}
|
|
73
73
|
|
|
74
|
-
&:focus
|
|
74
|
+
&:focus {
|
|
75
75
|
outline: 2px solid var(--ds-border-focused, currentColor);
|
|
76
76
|
outline-offset: 2px;
|
|
77
77
|
}
|
|
@@ -122,7 +122,7 @@
|
|
|
122
122
|
background: var(--ds-color-neutral-surface-hover, rgb(0 0 0 / 6%));
|
|
123
123
|
}
|
|
124
124
|
|
|
125
|
-
a:focus
|
|
125
|
+
a:focus {
|
|
126
126
|
outline: 2px solid var(--ds-color-focus-outer, currentColor);
|
|
127
127
|
outline-offset: -2px;
|
|
128
128
|
}
|
|
@@ -86,8 +86,9 @@ describe("ToolbarBreadcrumbs in a real toolbar", () => {
|
|
|
86
86
|
let hidden = within(menu)
|
|
87
87
|
.getAllByRole("listitem")
|
|
88
88
|
.map((item) => item.textContent);
|
|
89
|
-
|
|
90
|
-
expect(hidden
|
|
89
|
+
// Nearest first, like a browser's back menu: the menu reads upwards from the visible trail.
|
|
90
|
+
expect([...hidden.toReversed(), ...visibleLabels()]).toEqual(longTrail.map((item) => item.label));
|
|
91
|
+
expect(hidden.at(-1)).toBe("Synergi");
|
|
91
92
|
|
|
92
93
|
// The menu sits under the button, inside the screen.
|
|
93
94
|
let menuBox = menu.getBoundingClientRect();
|