@ai-matrx/alchemy 0.8.13 → 0.8.17

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 (88) hide show
  1. package/CHANGELOG.md +32 -1
  2. package/dist/actions.cjs +1 -373
  3. package/dist/actions.cjs.map +1 -1
  4. package/dist/actions.js +1 -350
  5. package/dist/actions.js.map +1 -1
  6. package/dist/checks.cjs +9 -314
  7. package/dist/checks.cjs.map +1 -1
  8. package/dist/checks.js +8 -290
  9. package/dist/checks.js.map +1 -1
  10. package/dist/core.cjs +9 -1728
  11. package/dist/core.cjs.map +1 -1
  12. package/dist/core.d.cts +2 -0
  13. package/dist/core.d.ts +2 -0
  14. package/dist/core.js +9 -1702
  15. package/dist/core.js.map +1 -1
  16. package/dist/declare-host.cjs +1 -18
  17. package/dist/declare-host.cjs.map +1 -1
  18. package/dist/declare.cjs +1 -638
  19. package/dist/declare.cjs.map +1 -1
  20. package/dist/declare.js +1 -615
  21. package/dist/declare.js.map +1 -1
  22. package/dist/index.cjs +9 -1728
  23. package/dist/index.cjs.map +1 -1
  24. package/dist/index.d.cts +2 -0
  25. package/dist/index.d.ts +2 -0
  26. package/dist/index.js +9 -1702
  27. package/dist/index.js.map +1 -1
  28. package/dist/menu.cjs +1 -529
  29. package/dist/menu.cjs.map +1 -1
  30. package/dist/menu.js +1 -506
  31. package/dist/menu.js.map +1 -1
  32. package/dist/operate-document.cjs +4 -162
  33. package/dist/operate-document.cjs.map +1 -1
  34. package/dist/operate-document.js +4 -129
  35. package/dist/operate-document.js.map +1 -1
  36. package/dist/operate-rich-html.cjs +1 -128
  37. package/dist/operate-rich-html.cjs.map +1 -1
  38. package/dist/operate-rich-html.js +1 -95
  39. package/dist/operate-rich-html.js.map +1 -1
  40. package/dist/operate-server.cjs +1 -156
  41. package/dist/operate-server.cjs.map +1 -1
  42. package/dist/operate-server.js +1 -133
  43. package/dist/operate-server.js.map +1 -1
  44. package/dist/operate-xlsx.cjs +143 -34230
  45. package/dist/operate-xlsx.cjs.map +1 -1
  46. package/dist/operate-xlsx.js +143 -34214
  47. package/dist/operate-xlsx.js.map +1 -1
  48. package/dist/operate.cjs +9 -1726
  49. package/dist/operate.cjs.map +1 -1
  50. package/dist/operate.d.cts +2 -0
  51. package/dist/operate.d.ts +2 -0
  52. package/dist/operate.js +9 -1702
  53. package/dist/operate.js.map +1 -1
  54. package/dist/ports.cjs +1 -18
  55. package/dist/ports.cjs.map +1 -1
  56. package/dist/react-bar.cjs +2 -795
  57. package/dist/react-bar.cjs.map +1 -1
  58. package/dist/react-bar.js +2 -774
  59. package/dist/react-bar.js.map +1 -1
  60. package/dist/react-host.cjs +1 -299
  61. package/dist/react-host.cjs.map +1 -1
  62. package/dist/react-host.js +1 -267
  63. package/dist/react-host.js.map +1 -1
  64. package/dist/react-menu.cjs +2 -848
  65. package/dist/react-menu.cjs.map +1 -1
  66. package/dist/react-menu.js +2 -835
  67. package/dist/react-menu.js.map +1 -1
  68. package/dist/react-overflow.cjs +2 -695
  69. package/dist/react-overflow.cjs.map +1 -1
  70. package/dist/react-overflow.js +2 -674
  71. package/dist/react-overflow.js.map +1 -1
  72. package/dist/react-palette.cjs +2 -586
  73. package/dist/react-palette.cjs.map +1 -1
  74. package/dist/react-palette.js +2 -554
  75. package/dist/react-palette.js.map +1 -1
  76. package/dist/react-selection.cjs +2 -726
  77. package/dist/react-selection.cjs.map +1 -1
  78. package/dist/react-selection.js +2 -705
  79. package/dist/react-selection.js.map +1 -1
  80. package/dist/react-sheet.cjs +2 -734
  81. package/dist/react-sheet.cjs.map +1 -1
  82. package/dist/react-sheet.js +2 -713
  83. package/dist/react-sheet.js.map +1 -1
  84. package/dist/react.cjs +1 -29
  85. package/dist/react.cjs.map +1 -1
  86. package/dist/react.js +1 -8
  87. package/dist/react.js.map +1 -1
  88. package/package.json +1 -1
package/dist/react-bar.js CHANGED
@@ -1,776 +1,4 @@
1
1
  "use client";
2
-
3
- // src/react/bar.tsx
4
- import * as React4 from "react";
5
- import { DropdownMenu, DropdownMenuContent, DropdownMenuTrigger, TooltipProvider } from "@ai-matrx/design-system";
6
-
7
- // src/menu/layouts.ts
8
- var INLINE_SECTION_MAX = 3;
9
- function sectionLabel(section) {
10
- return section.label ?? null;
11
- }
12
- function fold(section) {
13
- return {
14
- kind: "submenu",
15
- id: `${section.id}:fold`,
16
- label: section.label,
17
- ...section.icon !== void 0 ? { icon: section.icon } : {},
18
- children: section.nodes
19
- };
20
- }
21
- function rowCount(nodes) {
22
- return nodes.filter((n) => n.kind !== "separator" && n.kind !== "label").length;
23
- }
24
- function placementOf(node) {
25
- return "placement" in node && node.placement ? node.placement : "overflow";
26
- }
27
- function foldNamed(sections) {
28
- return sections.map(
29
- (s) => s.label && !s.primary && rowCount(s.nodes) > INLINE_SECTION_MAX ? { id: s.id, group: s.group, nodes: [fold({ ...s, label: s.label })] } : s
30
- );
31
- }
32
- function bar(model, _options = {}) {
33
- const primary = [];
34
- const overflowSections = [];
35
- for (const s of model.sections) {
36
- const rest = [];
37
- for (const n of s.nodes) {
38
- if (n.kind === "separator" || n.kind === "label") {
39
- rest.push(n);
40
- continue;
41
- }
42
- const p = placementOf(n);
43
- if (p === "primary" || p === "both") primary.push(n);
44
- if (p === "overflow" || p === "both") rest.push(n);
45
- }
46
- if (rowCount(rest) > 0) overflowSections.push({ ...s, nodes: rest });
47
- }
48
- return { primary, overflow: foldNamed(overflowSections) };
49
- }
50
-
51
- // src/react/engine.tsx
52
- import * as React2 from "react";
53
-
54
- // src/declare/sensitivity.ts
55
- var DEFAULT_SENSITIVITY = Object.freeze({
56
- exportable: true,
57
- classification: "ordinary",
58
- includedByDefault: true
59
- });
60
- function resolveSensitivity(value) {
61
- return {
62
- exportable: value.sensitivity?.exportable ?? DEFAULT_SENSITIVITY.exportable,
63
- classification: value.sensitivity?.classification ?? DEFAULT_SENSITIVITY.classification,
64
- includedByDefault: value.sensitivity?.includedByDefault ?? DEFAULT_SENSITIVITY.includedByDefault
65
- };
66
- }
67
-
68
- // src/actions/projection.ts
69
- function toJson(value) {
70
- if (value === void 0 || typeof value === "function" || typeof value === "symbol") return void 0;
71
- if (value === null || typeof value === "string" || typeof value === "boolean") return value;
72
- if (typeof value === "number") return Number.isFinite(value) ? value : null;
73
- if (typeof value === "bigint") return value.toString();
74
- if (value instanceof Date) return value.toISOString();
75
- if (Array.isArray(value)) return value.map((v) => toJson(v) ?? null);
76
- if (typeof value === "object") {
77
- const out = {};
78
- for (const [k, v] of Object.entries(value)) {
79
- const j = toJson(v);
80
- if (j !== void 0) out[k] = j;
81
- }
82
- return out;
83
- }
84
- return void 0;
85
- }
86
- function projectValues(raw, declared, pathPrefix = "") {
87
- const byName = new Map(declared.map((d) => [d.name, d]));
88
- const values = {};
89
- const omissions = [];
90
- for (const [name, value] of Object.entries(raw)) {
91
- const path = pathPrefix ? `${pathPrefix}.${name}` : name;
92
- const decl = byName.get(name);
93
- if (!decl) {
94
- omissions.push({ path, reason: "filtered" });
95
- continue;
96
- }
97
- const sensitivity = resolveSensitivity(decl);
98
- if (sensitivity.classification !== "ordinary") {
99
- omissions.push({ path, reason: "excluded", classification: sensitivity.classification });
100
- continue;
101
- }
102
- if (!sensitivity.exportable) {
103
- omissions.push({ path, reason: "excluded" });
104
- continue;
105
- }
106
- const json = toJson(value);
107
- if (json === void 0) continue;
108
- values[name] = json;
109
- }
110
- return { values, omissions };
111
- }
112
- function createProjectedReads(source) {
113
- return {
114
- async values(signal) {
115
- if (!source.surface || !source.declaration) return { values: {}, omissions: [] };
116
- const raw = await source.surface.readValues(signal);
117
- const screenValues = source.declaration.values;
118
- return projectValues(raw, screenValues);
119
- },
120
- async item(signal) {
121
- const item = source.item;
122
- if (!item || !source.declaration) return null;
123
- const type = source.declaration.itemTypes?.find((t) => t.name === item.itemType);
124
- if (!type) return { values: {}, omissions: [{ path: item.itemType, reason: "filtered" }] };
125
- const raw = await item.readValues(signal);
126
- return projectValues(raw, type.values, item.itemType);
127
- },
128
- async live(signal) {
129
- if (!source.surface?.readLive) return {};
130
- return source.surface.readLive(signal);
131
- }
132
- };
133
- }
134
-
135
- // src/actions/run.ts
136
- async function runAction(action, target, options) {
137
- const { ports } = options;
138
- if (action.requiresAuth && !target.auth.authenticated) {
139
- if (!ports.auth) {
140
- ports.diagnostics.capture(new Error(`requiresAuth action "${action.id}" ran signed out with no auth port`), {
141
- area: "actions",
142
- detail: { actionId: action.id }
143
- });
144
- return { status: "failed", error: new Error("sign-in unavailable") };
145
- }
146
- ports.auth.signInThenResume({ actionId: action.id, contentFingerprint: options.contentFingerprint ?? action.id });
147
- return { status: "auth-pending" };
148
- }
149
- const reads = createProjectedReads(options.source ?? { surface: null, declaration: target.declaration, item: null });
150
- const signal = options.signal ?? new AbortController().signal;
151
- try {
152
- const outcome = await action.run(target, { reads, ports, signal });
153
- return { status: "ran", outcome };
154
- } catch (error) {
155
- ports.diagnostics.capture(error, { area: "actions", detail: { actionId: action.id, stage: "run" } });
156
- const label = typeof action.label === "string" ? action.label : action.id;
157
- ports.notify?.error(`${label} did not finish.`, "Try again; if it keeps failing, report it from the feedback button.");
158
- return { status: "failed", error };
159
- }
160
- }
161
-
162
- // src/menu/headings.ts
163
- var APPROVED_HEADINGS = /* @__PURE__ */ new Set([
164
- "Save",
165
- // rich-document menuStructure, e5b8d01229 (2026-05-19)
166
- "Copy as",
167
- // rich-document menuStructure, e5b8d01229 (2026-05-19)
168
- "Export",
169
- // rich-document menuStructure, e5b8d01229 (2026-05-19)
170
- "Edit",
171
- // rich-document menuStructure, e5b8d01229 (2026-05-19)
172
- "Creator tools",
173
- // rich-document menuStructure, e5b8d01229 (2026-05-19)
174
- "Admin",
175
- // rich-document menuStructure, e5b8d01229 (2026-05-19)
176
- "App",
177
- // rich-document menuStructure, e5b8d01229 (2026-05-19)
178
- "Compare",
179
- // rich-document menuStructure, 2e3a8a9fdf (2026-06-11)
180
- "History"
181
- // context-menu-v3 tiered layout — the one grouping Arman approved, 2026-08-22
182
- ]);
183
- var CONTAINER_WORD = /^(more|more…|more\.\.\.|other|others|misc|miscellaneous|additional|extra|extras|actions|options|advanced|stuff|everything else)$/i;
184
- var TARGET_SHAPE = /^(Cell|Row|Column|Table|Range|Selection|Record) · .+$/;
185
- function isContainerWord(label) {
186
- return CONTAINER_WORD.test(label.trim());
187
- }
188
- function isApprovedHeading(label, kind = "group", approved = APPROVED_HEADINGS) {
189
- const l = label.trim();
190
- if (!l || isContainerWord(l)) return false;
191
- if (approved.has(l)) return true;
192
- return kind === "target" || TARGET_SHAPE.test(l);
193
- }
194
- function defaultHeadingPolicy() {
195
- const env = globalThis.process?.env?.NODE_ENV;
196
- return env === "production" ? "inline" : "throw";
197
- }
198
- var UnapprovedHeadingError = class extends Error {
199
- heading;
200
- constructor(heading, where) {
201
- super(
202
- `Menu heading "${heading}" (${where}) is not an approved heading. Remedy: show these rows inline \u2014 declare no section (or kind "target" for the clicked thing's own label) \u2014 or ask Arman to add the name to APPROVED_HEADINGS in @ai-matrx/alchemy/menu. A generic container word ("More\u2026", "Other") is never approved.`
203
- );
204
- this.name = "UnapprovedHeadingError";
205
- this.heading = heading;
206
- }
207
- };
208
-
209
- // src/menu/model.ts
210
- var CATEGORY_GROUP = {
211
- clipboard: "clipboard",
212
- copy: "transfer",
213
- export: "transfer",
214
- save: "document",
215
- share: "document",
216
- edit: "editable",
217
- history: "history",
218
- ai: "ai",
219
- ask: "ai",
220
- listen: "tools",
221
- study: "tools",
222
- app: "tools",
223
- feedback: "quick",
224
- creator: "admin",
225
- admin: "admin",
226
- "surface-info": "surface-info"
227
- };
228
- var GROUP_ORDER = [
229
- "clipboard",
230
- "editable",
231
- "transfer",
232
- "document",
233
- "history",
234
- "ai",
235
- "tools",
236
- "quick",
237
- "surface",
238
- "admin",
239
- "surface-info"
240
- ];
241
- var CATEGORY_ORDER = [
242
- "clipboard",
243
- "edit",
244
- "copy",
245
- "export",
246
- "save",
247
- "share",
248
- "history",
249
- "ask",
250
- "ai",
251
- "listen",
252
- "study",
253
- "app",
254
- "feedback",
255
- "creator",
256
- "admin",
257
- "surface-info"
258
- ];
259
- function translate(i18n, key, fallback) {
260
- if (!i18n) return fallback;
261
- try {
262
- return i18n.t(key, fallback);
263
- } catch {
264
- return fallback;
265
- }
266
- }
267
- function actionToNode(resolved, target, options = {}) {
268
- const { action, eligibility } = resolved;
269
- const rawLabel = typeof action.label === "function" ? action.label(target) : action.label;
270
- const label = translate(options.i18n, action.labelKey ?? action.id, rawLabel);
271
- const base = {
272
- id: action.id,
273
- actionId: action.id,
274
- ...action.icon !== void 0 ? { icon: action.icon } : {},
275
- ...action.placement !== void 0 ? { placement: action.placement } : {}
276
- };
277
- if (action.expand) {
278
- const node = {
279
- ...base,
280
- kind: "submenu",
281
- label,
282
- lazy: true,
283
- loading: false,
284
- ...action.pending?.(target) ? { pending: true } : {},
285
- children: [],
286
- ...action.emptyLabel !== void 0 ? { emptyLabel: action.emptyLabel } : {}
287
- };
288
- return node;
289
- }
290
- if (action.href !== void 0) {
291
- const href = typeof action.href === "function" ? action.href(target) : action.href;
292
- return { ...base, kind: "link", label, href };
293
- }
294
- if (action.toggle) {
295
- return {
296
- ...base,
297
- kind: "checkbox",
298
- label,
299
- checked: action.pressed?.(target) ?? false,
300
- ...action.description !== void 0 ? { description: action.description } : {}
301
- };
302
- }
303
- const state = action.stateIcon?.(target) ?? null;
304
- const pressed = action.pressed?.(target);
305
- const hint = action.hint !== void 0 ? translate(options.i18n, action.hintKey ?? `${action.id}.hint`, action.hint) : void 0;
306
- return {
307
- ...base,
308
- kind: "item",
309
- label,
310
- ...action.iconTone !== void 0 ? { iconTone: action.iconTone } : {},
311
- ...state ? { stateIcon: state } : {},
312
- ...action.description !== void 0 ? { description: action.description } : {},
313
- ...hint !== void 0 ? { hint } : {},
314
- ...pressed !== void 0 ? { pressed } : {},
315
- ...action.destructive ? { destructive: true } : {},
316
- ...action.preserveSelection ? { preserveSelection: true } : {},
317
- ...eligibility.status === "unavailable-verb" ? { unavailable: { sentence: eligibility.sentence } } : {}
318
- };
319
- }
320
- function buildMenuModel(target, resolved, options = {}) {
321
- const policy = options.headingPolicy ?? defaultHeadingPolicy();
322
- resolved = resolved.map((r) => {
323
- const sec = r.action.section;
324
- if (r.action.expand && isContainerWord(typeof r.action.label === "string" ? r.action.label : "") && policy === "throw") {
325
- throw new UnapprovedHeadingError(r.action.label, `submenu of ${r.action.id}`);
326
- }
327
- if (!sec) return r;
328
- const kind = sec.kind ?? (sec.primary ? "target" : "group");
329
- if (isApprovedHeading(sec.label, kind)) return r;
330
- if (policy === "throw") throw new UnapprovedHeadingError(sec.label, `section of ${r.action.id}`);
331
- const { section: _dropped, ...rest } = r.action;
332
- return { ...r, action: rest };
333
- });
334
- const ordered = resolved.map((r, index) => ({ r, index })).sort((a, b) => {
335
- const ca = CATEGORY_ORDER.indexOf(a.r.action.category);
336
- const cb = CATEGORY_ORDER.indexOf(b.r.action.category);
337
- if (ca !== cb) return ca - cb;
338
- const oa = a.r.action.order ?? 0;
339
- const ob = b.r.action.order ?? 0;
340
- if (oa !== ob) return oa - ob;
341
- return a.index - b.index;
342
- }).map((x) => x.r);
343
- const sections = /* @__PURE__ */ new Map();
344
- const roles = {};
345
- const explicit = /* @__PURE__ */ new Map();
346
- resolved.forEach((r, index) => {
347
- const sec = r.action.section;
348
- if (!sec) return;
349
- const entry = explicit.get(sec.id) ?? { group: CATEGORY_GROUP[r.action.category], rows: [] };
350
- entry.rows.push({ r, index });
351
- explicit.set(sec.id, entry);
352
- });
353
- const placed = /* @__PURE__ */ new Set();
354
- for (const r of ordered) {
355
- const sec = r.action.section;
356
- if (sec && placed.has(sec.id)) continue;
357
- const group = sec ? explicit.get(sec.id)?.group ?? CATEGORY_GROUP[r.action.category] : CATEGORY_GROUP[r.action.category];
358
- const sectionId = sec ? `section:${sec.id}` : group;
359
- let section = sections.get(sectionId);
360
- if (!section) {
361
- section = {
362
- id: sectionId,
363
- group,
364
- nodes: [],
365
- ...sec ? { label: translate(options.i18n, sec.labelKey ?? `section.${sec.id}`, sec.label) } : {},
366
- ...sec?.icon !== void 0 ? { icon: sec.icon } : {},
367
- ...sec?.primary ? { primary: true } : {},
368
- ...sec && (sec.kind ?? (sec.primary ? "target" : "group")) === "target" ? { target: true } : {}
369
- };
370
- sections.set(sectionId, section);
371
- }
372
- const rows = sec ? (explicit.get(sec.id)?.rows ?? []).sort((x, y) => (x.r.action.order ?? 0) - (y.r.action.order ?? 0) || x.index - y.index).map((x) => x.r) : [r];
373
- if (sec) placed.add(sec.id);
374
- for (const row of rows) {
375
- section.nodes.push(actionToNode(row, target, options));
376
- if (row.action.verb) roles[row.action.verb] = row.action.id;
377
- }
378
- }
379
- const list = [...sections.values()].sort((a, b) => {
380
- if (Boolean(a.primary) !== Boolean(b.primary)) return a.primary ? -1 : 1;
381
- return GROUP_ORDER.indexOf(a.group) - GROUP_ORDER.indexOf(b.group);
382
- });
383
- const selected = target.selection?.text?.trim();
384
- const content = options.content?.trim();
385
- const header = selected ? { label: "Selected", text: target.selection?.text ?? "" } : content ? { label: "Content", text: options.content ?? "" } : null;
386
- return { header, sections: list, roles };
387
- }
388
- function withExpandedChildren(model, nodeId, children) {
389
- const visit = (nodes) => nodes.map((n) => {
390
- if (n.kind !== "submenu") return n;
391
- if (n.id === nodeId) {
392
- return children === "loading" ? { ...n, loading: true } : { ...n, lazy: false, loading: false, pending: false, children };
393
- }
394
- return { ...n, children: visit(n.children) };
395
- });
396
- return { ...model, sections: model.sections.map((s) => ({ ...s, nodes: visit(s.nodes) })) };
397
- }
398
- function findNode(nodes, id) {
399
- for (const n of nodes) {
400
- if (n.id === id) return n;
401
- if (n.kind === "submenu") {
402
- const hit = findNode(n.children, id);
403
- if (hit) return hit;
404
- }
405
- }
406
- return null;
407
- }
408
-
409
- // src/react/context.ts
410
- import * as React from "react";
411
- var KEY = /* @__PURE__ */ Symbol.for("ai-matrx.alchemy.actions-context");
412
- var AlchemyActionsContext = globalThis[KEY] ??= React.createContext(null);
413
- function useAlchemyActions() {
414
- const value = React.useContext(AlchemyActionsContext);
415
- if (!value) throw new Error("Alchemy actions: render inside <AlchemyActionsProvider> (@ai-matrx/alchemy/react/host).");
416
- return value;
417
- }
418
-
419
- // src/react/engine.tsx
420
- import { jsx } from "react/jsx-runtime";
421
- function useMenuEngine(target, options = {}) {
422
- const { registry, ports } = useAlchemyActions();
423
- const [resolved, setResolved] = React2.useState([]);
424
- const [model, setModel] = React2.useState(null);
425
- const [tick, setTick] = React2.useState(0);
426
- const expanded = React2.useRef(/* @__PURE__ */ new Map());
427
- const opened = React2.useRef(/* @__PURE__ */ new Set());
428
- const expandSeq = React2.useRef(/* @__PURE__ */ new Map());
429
- const active = options.active ?? true;
430
- const optionsRef = React2.useRef(options);
431
- optionsRef.current = options;
432
- React2.useEffect(() => registry.subscribe(() => setTick((t) => t + 1)), [registry]);
433
- const expandAction = React2.useCallback(
434
- async (action, nodeId) => {
435
- if (!target || !action.expand) return;
436
- const seq = (expandSeq.current.get(nodeId) ?? 0) + 1;
437
- expandSeq.current.set(nodeId, seq);
438
- const latest = () => expandSeq.current.get(nodeId) === seq;
439
- setModel((m) => m ? withExpandedChildren(m, nodeId, "loading") : m);
440
- try {
441
- const children = await action.expand(target, new AbortController().signal);
442
- if (!latest()) return;
443
- const nodes = children.map((child) => {
444
- expanded.current.set(child.id, child);
445
- return actionToNode({ action: child, eligibility: { status: "available" } }, target, ports.i18n ? { i18n: ports.i18n } : {});
446
- });
447
- setModel((m) => m ? withExpandedChildren(m, nodeId, nodes) : m);
448
- } catch (error) {
449
- if (!latest()) return;
450
- ports.diagnostics.capture(error, { area: "menu", detail: { nodeId, stage: "expand" } });
451
- setModel((m) => m ? withExpandedChildren(m, nodeId, []) : m);
452
- }
453
- },
454
- [target, ports]
455
- );
456
- React2.useEffect(() => {
457
- opened.current.clear();
458
- }, [target]);
459
- React2.useEffect(() => {
460
- if (!target || !active) return;
461
- let live = true;
462
- void registry.resolve(target, optionsRef.current.restrict).then((list) => {
463
- if (!live) return;
464
- expanded.current.clear();
465
- setResolved(list);
466
- setModel(buildMenuModel(target, list, { ...ports.i18n ? { i18n: ports.i18n } : {}, content: optionsRef.current.content ?? null }));
467
- for (const id of opened.current) {
468
- const action = list.find((r) => r.action.id === id)?.action;
469
- if (action?.expand) void expandAction(action, id);
470
- }
471
- });
472
- return () => {
473
- live = false;
474
- };
475
- }, [registry, ports, target, active, tick, options.revision, expandAction]);
476
- const resolvedRef = React2.useRef(resolved);
477
- resolvedRef.current = resolved;
478
- const subscribedIds = resolved.map((r) => r.action.id).join("\n");
479
- React2.useEffect(() => {
480
- if (!target) return;
481
- let subscribing = true;
482
- const onChange = () => {
483
- if (!subscribing) setTick((t) => t + 1);
484
- };
485
- const offs = resolvedRef.current.map((r) => r.action.subscribe?.(onChange, target)).filter((off) => typeof off === "function");
486
- subscribing = false;
487
- return () => offs.forEach((off) => off());
488
- }, [subscribedIds, target]);
489
- const findAction = React2.useCallback(
490
- (id) => resolved.find((r) => r.action.id === id)?.action ?? expanded.current.get(id),
491
- [resolved]
492
- );
493
- const run = React2.useCallback(
494
- async (nodeId) => {
495
- if (!target || !model) return null;
496
- const node = model.sections.map((s) => findNode(s.nodes, nodeId)).find(Boolean) ?? null;
497
- const action = findAction(node && "actionId" in node && node.actionId ? node.actionId : nodeId);
498
- if (!action) return null;
499
- const o = optionsRef.current;
500
- const result = await runAction(action, target, {
501
- ports,
502
- ...o.source ? { source: o.source } : {},
503
- ...o.contentFingerprint ? { contentFingerprint: o.contentFingerprint } : {}
504
- });
505
- o.onRan?.(nodeId, result);
506
- return result;
507
- },
508
- [target, model, findAction, ports]
509
- );
510
- const expand = React2.useCallback(
511
- async (nodeId) => {
512
- const action = findAction(nodeId);
513
- if (!target || !action?.expand) return;
514
- opened.current.add(nodeId);
515
- await expandAction(action, nodeId);
516
- },
517
- [findAction, target, expandAction]
518
- );
519
- const icon = React2.useCallback(
520
- (key, tone) => {
521
- if (!key || !ports.icons) return null;
522
- const Resolved = ports.icons.resolve(key);
523
- return Resolved ? /* @__PURE__ */ jsx(Resolved, { className: `h-4 w-4 shrink-0 ${tone ?? ""}`, "aria-hidden": true }) : null;
524
- },
525
- [ports.icons]
526
- );
527
- const explain = React2.useCallback(
528
- (sentence) => {
529
- if (ports.notify) ports.notify.info(sentence);
530
- else ports.diagnostics.capture(new Error(`No notify port to explain: ${sentence}`), { area: "menu", detail: { sentence } });
531
- },
532
- [ports]
533
- );
534
- return { model, resolved, run, expand, icon, explain };
535
- }
536
-
537
- // src/react/dropdown-nodes.tsx
538
- import * as React3 from "react";
539
- import {
540
- DropdownMenuCheckboxItem,
541
- DropdownMenuItem,
542
- DropdownMenuLabel,
543
- DropdownMenuSeparator,
544
- DropdownMenuSub,
545
- DropdownMenuSubContent,
546
- DropdownMenuSubTrigger,
547
- Tooltip,
548
- TooltipContent,
549
- TooltipTrigger
550
- } from "@ai-matrx/design-system";
551
- import { Fragment as Fragment2, jsx as jsx2, jsxs } from "react/jsx-runtime";
552
- function NodeList({ nodes, engine }) {
553
- return /* @__PURE__ */ jsx2(Fragment2, { children: nodes.map((node) => /* @__PURE__ */ jsx2(MenuNodeView, { node, engine }, node.id)) });
554
- }
555
- function SectionList({
556
- sections,
557
- engine
558
- }) {
559
- return /* @__PURE__ */ jsx2(Fragment2, { children: sections.map((section, index) => /* @__PURE__ */ jsxs(React3.Fragment, { children: [
560
- index > 0 ? /* @__PURE__ */ jsx2(DropdownMenuSeparator, {}) : null,
561
- sectionLabel(section) ? /* @__PURE__ */ jsx2(DropdownMenuLabel, { className: "text-xs font-medium text-muted-foreground", children: sectionLabel(section) }) : null,
562
- /* @__PURE__ */ jsx2(NodeList, { nodes: section.nodes, engine })
563
- ] }, section.id)) });
564
- }
565
- function iconOf(node, engine) {
566
- if (node.kind !== "item") {
567
- if (!("icon" in node)) return null;
568
- return engine.icon(node.icon);
569
- }
570
- if (node.stateIcon) {
571
- const glyph = engine.icon(node.stateIcon.icon);
572
- return node.stateIcon.spin ? /* @__PURE__ */ jsx2("span", { className: "inline-flex animate-spin", children: glyph }) : glyph;
573
- }
574
- if (!("icon" in node)) return null;
575
- const tone = node.pressed === false ? void 0 : node.iconTone;
576
- return engine.icon(node.icon, tone);
577
- }
578
- function MenuNodeView({ node, engine }) {
579
- switch (node.kind) {
580
- case "separator":
581
- return /* @__PURE__ */ jsx2(DropdownMenuSeparator, {});
582
- case "label":
583
- return /* @__PURE__ */ jsx2(DropdownMenuLabel, { className: "text-xs font-medium text-muted-foreground", children: node.label });
584
- case "submenu":
585
- return /* @__PURE__ */ jsxs(
586
- DropdownMenuSub,
587
- {
588
- onOpenChange: (open) => {
589
- if (open && node.lazy && !node.loading) void engine.expand(node.id);
590
- },
591
- children: [
592
- /* @__PURE__ */ jsxs(DropdownMenuSubTrigger, { "data-alchemy-node": node.id, className: "gap-2", "aria-busy": node.pending ? true : void 0, children: [
593
- iconOf(node, engine),
594
- /* @__PURE__ */ jsx2("span", { className: "truncate", children: node.label }),
595
- node.pending ? /* @__PURE__ */ jsx2("span", { className: "ml-auto text-xs text-muted-foreground", children: "Loading\u2026" }) : null
596
- ] }),
597
- /* @__PURE__ */ jsx2(DropdownMenuSubContent, { className: "max-h-[var(--radix-dropdown-menu-content-available-height)] overflow-y-auto", children: node.loading ? /* @__PURE__ */ jsx2(DropdownMenuLabel, { className: "text-xs text-muted-foreground", children: "Loading\u2026" }) : node.children.length === 0 && !node.lazy ? /* @__PURE__ */ jsx2(DropdownMenuLabel, { className: "text-xs text-muted-foreground", children: node.emptyLabel ?? "Nothing here yet" }) : /* @__PURE__ */ jsx2(NodeList, { nodes: node.children, engine }) })
598
- ]
599
- }
600
- );
601
- case "checkbox":
602
- return /* @__PURE__ */ jsxs(
603
- DropdownMenuCheckboxItem,
604
- {
605
- "data-alchemy-node": node.id,
606
- checked: node.checked,
607
- onSelect: () => void engine.run(node.id),
608
- className: "gap-2",
609
- children: [
610
- iconOf(node, engine),
611
- /* @__PURE__ */ jsx2("span", { className: "truncate", children: node.label })
612
- ]
613
- }
614
- );
615
- case "link":
616
- return /* @__PURE__ */ jsx2(DropdownMenuItem, { asChild: true, "data-alchemy-node": node.id, children: /* @__PURE__ */ jsxs("a", { href: node.href, target: node.target, className: "gap-2", children: [
617
- iconOf(node, engine),
618
- /* @__PURE__ */ jsx2("span", { className: "truncate", children: node.label })
619
- ] }) });
620
- case "item":
621
- return /* @__PURE__ */ jsx2(LeafItem, { node, engine });
622
- }
623
- }
624
- function LeafItem({ node, engine }) {
625
- const row = /* @__PURE__ */ jsxs(
626
- DropdownMenuItem,
627
- {
628
- "data-alchemy-node": node.id,
629
- "aria-disabled": node.unavailable ? true : void 0,
630
- "aria-pressed": node.pressed,
631
- onSelect: (event) => {
632
- if (node.unavailable) {
633
- event.preventDefault();
634
- return;
635
- }
636
- void engine.run(node.id);
637
- },
638
- className: `gap-2 ${node.unavailable ? "opacity-50" : ""} ${node.destructive ? "text-destructive" : ""}`,
639
- children: [
640
- iconOf(node, engine),
641
- /* @__PURE__ */ jsxs("span", { className: "flex min-w-0 flex-1 flex-col", children: [
642
- /* @__PURE__ */ jsx2("span", { className: "truncate", children: node.label }),
643
- node.description ? /* @__PURE__ */ jsx2("span", { className: "truncate text-xs text-muted-foreground", children: node.description }) : null
644
- ] }),
645
- node.hint ? /* @__PURE__ */ jsx2("span", { className: "ml-auto text-xs text-muted-foreground", children: node.hint }) : null
646
- ]
647
- }
648
- );
649
- if (!node.unavailable) return row;
650
- return /* @__PURE__ */ jsxs(Tooltip, { children: [
651
- /* @__PURE__ */ jsx2(TooltipTrigger, { asChild: true, children: row }),
652
- /* @__PURE__ */ jsx2(TooltipContent, { children: node.unavailable.sentence })
653
- ] });
654
- }
655
- function LeafButton({
656
- node,
657
- engine,
658
- showLabel
659
- }) {
660
- if (node.kind !== "item" && node.kind !== "checkbox" && node.kind !== "link") return null;
661
- const unavailable = node.kind === "item" ? node.unavailable : void 0;
662
- const pressed = node.kind === "item" ? node.pressed : node.kind === "checkbox" ? node.checked : void 0;
663
- const glyph = iconOf(node, engine);
664
- const button = /* @__PURE__ */ jsxs(
665
- "button",
666
- {
667
- type: "button",
668
- "data-alchemy-node": node.id,
669
- "data-matrx-button": "",
670
- "data-tap-floor": "",
671
- "data-tap-floor-square": "",
672
- "aria-label": node.label,
673
- "aria-disabled": unavailable ? true : void 0,
674
- "aria-pressed": pressed,
675
- onMouseDown: (e) => {
676
- if (node.kind === "item" && node.preserveSelection) e.preventDefault();
677
- },
678
- onClick: () => {
679
- if (unavailable) {
680
- engine.explain(unavailable.sentence);
681
- return;
682
- }
683
- if (node.kind === "link") {
684
- window.location.assign(node.href);
685
- return;
686
- }
687
- void engine.run(node.id);
688
- },
689
- className: `inline-flex h-7 min-w-7 shrink-0 items-center justify-center gap-1.5 rounded-md px-1.5 text-sm text-muted-foreground hover:bg-accent hover:text-foreground ${unavailable ? "cursor-default opacity-50 hover:bg-transparent" : ""} ${pressed ? "text-foreground" : ""}`,
690
- children: [
691
- glyph,
692
- showLabel || !glyph ? /* @__PURE__ */ jsx2("span", { className: "whitespace-nowrap", children: node.label }) : null
693
- ]
694
- }
695
- );
696
- return /* @__PURE__ */ jsxs(Tooltip, { children: [
697
- /* @__PURE__ */ jsx2(TooltipTrigger, { asChild: true, children: button }),
698
- /* @__PURE__ */ jsx2(TooltipContent, { children: unavailable ? unavailable.sentence : node.label })
699
- ] });
700
- }
701
-
702
- // src/react/bar.tsx
703
- import { Fragment as Fragment3, jsx as jsx3, jsxs as jsxs2 } from "react/jsx-runtime";
704
- function isNarrow(width) {
705
- if (typeof window === "undefined") return false;
706
- return window.matchMedia?.(`(max-width: ${width - 1}px)`).matches ?? false;
707
- }
708
- var TRIGGER_CLASS = "inline-flex h-7 min-w-7 items-center justify-center gap-1 rounded-md px-1.5 text-muted-foreground hover:bg-accent hover:text-foreground";
709
- function PrimarySubmenu({ node, engine }) {
710
- return /* @__PURE__ */ jsxs2(
711
- DropdownMenu,
712
- {
713
- onOpenChange: (open) => {
714
- if (open && node.lazy && !node.loading) void engine.expand(node.id);
715
- },
716
- children: [
717
- /* @__PURE__ */ jsx3(DropdownMenuTrigger, { asChild: true, children: /* @__PURE__ */ jsx3("button", { type: "button", "aria-label": node.label, "data-alchemy-node": node.id, className: TRIGGER_CLASS, children: engine.icon(node.icon) ?? /* @__PURE__ */ jsx3("span", { className: "text-sm", children: node.label }) }) }),
718
- /* @__PURE__ */ jsx3(DropdownMenuContent, { align: "start", className: "w-64 max-h-[var(--radix-dropdown-menu-content-available-height)] overflow-y-auto", children: node.loading ? /* @__PURE__ */ jsx3("div", { className: "px-2 py-1.5 text-xs text-muted-foreground", children: "Loading\u2026" }) : /* @__PURE__ */ jsx3(NodeList, { nodes: node.children, engine }) })
719
- ]
720
- }
721
- );
722
- }
723
- function ActionBar({
724
- target,
725
- mini = false,
726
- className,
727
- hideOverflow = false,
728
- sheetBelow = 768,
729
- loadSheet = () => import("@ai-matrx/alchemy/react/sheet"),
730
- ...options
731
- }) {
732
- const engine = useMenuEngine(target, options);
733
- const [sheetOpen, setSheetOpen] = React4.useState(false);
734
- const [Sheet, setSheet] = React4.useState(null);
735
- if (!engine.model) return null;
736
- const arranged = bar(engine.model, { mini });
737
- if (arranged.primary.length === 0 && arranged.overflow.length === 0) return null;
738
- return /* @__PURE__ */ jsx3(TooltipProvider, { children: /* @__PURE__ */ jsxs2(
739
- "div",
740
- {
741
- role: "toolbar",
742
- "aria-label": "Actions",
743
- "data-alchemy-layout": "bar",
744
- className: `flex items-center ${mini ? "gap-0" : "gap-0.5"} ${className ?? ""}`,
745
- children: [
746
- arranged.primary.map(
747
- (node) => node.kind === "submenu" ? /* @__PURE__ */ jsx3(PrimarySubmenu, { node, engine }, node.id) : /* @__PURE__ */ jsx3(LeafButton, { node, engine, showLabel: false }, node.id)
748
- ),
749
- hideOverflow || arranged.overflow.length === 0 ? null : isNarrow(sheetBelow) ? /* @__PURE__ */ jsxs2(Fragment3, { children: [
750
- /* @__PURE__ */ jsx3(
751
- "button",
752
- {
753
- type: "button",
754
- "aria-label": "More actions",
755
- "data-alchemy-trigger": "overflow",
756
- className: TRIGGER_CLASS,
757
- onClick: () => {
758
- setSheetOpen(true);
759
- if (!Sheet) void loadSheet().then((m) => setSheet(() => m.ActionSheet));
760
- },
761
- children: /* @__PURE__ */ jsx3("span", { "aria-hidden": true, className: "text-base leading-none", children: "\u22EF" })
762
- }
763
- ),
764
- Sheet ? /* @__PURE__ */ jsx3(Sheet, { ...options, target, open: sheetOpen, onOpenChange: setSheetOpen }) : null
765
- ] }) : /* @__PURE__ */ jsxs2(DropdownMenu, { children: [
766
- /* @__PURE__ */ jsx3(DropdownMenuTrigger, { asChild: true, children: /* @__PURE__ */ jsx3("button", { type: "button", "aria-label": "More actions", "data-alchemy-trigger": "overflow", className: TRIGGER_CLASS, children: /* @__PURE__ */ jsx3("span", { "aria-hidden": true, className: "text-base leading-none", children: "\u22EF" }) }) }),
767
- /* @__PURE__ */ jsx3(DropdownMenuContent, { align: "end", className: "w-64 max-h-[var(--radix-dropdown-menu-content-available-height)] overflow-y-auto", children: /* @__PURE__ */ jsx3(SectionList, { sections: arranged.overflow, engine }) })
768
- ] })
769
- ]
770
- }
771
- ) });
772
- }
773
- export {
774
- ActionBar
775
- };
2
+ import*as React4 from"react";import{DropdownMenu,DropdownMenuContent,DropdownMenuTrigger,TooltipProvider}from"@ai-matrx/design-system";function sectionLabel(section){return section.label??null}function fold(section){return{kind:"submenu",id:`${section.id}:fold`,label:section.label,...section.icon!==void 0?{icon:section.icon}:{},children:section.nodes}}function rowCount(nodes){return nodes.filter(n=>n.kind!=="separator"&&n.kind!=="label").length}function placementOf(node){return"placement"in node&&node.placement?node.placement:"overflow"}function foldNamed(sections){return sections.map(s=>s.label&&!s.primary&&rowCount(s.nodes)>3?{id:s.id,group:s.group,nodes:[fold({...s,label:s.label})]}:s)}function bar(model,_options={}){let primary=[],overflowSections=[];for(let s of model.sections){let rest=[];for(let n of s.nodes){if(n.kind==="separator"||n.kind==="label"){rest.push(n);continue}let p=placementOf(n);(p==="primary"||p==="both")&&primary.push(n),(p==="overflow"||p==="both")&&rest.push(n)}rowCount(rest)>0&&overflowSections.push({...s,nodes:rest})}return{primary,overflow:foldNamed(overflowSections)}}import*as React2 from"react";var DEFAULT_SENSITIVITY=Object.freeze({exportable:!0,classification:"ordinary",includedByDefault:!0});function resolveSensitivity(value){return{exportable:value.sensitivity?.exportable??DEFAULT_SENSITIVITY.exportable,classification:value.sensitivity?.classification??DEFAULT_SENSITIVITY.classification,includedByDefault:value.sensitivity?.includedByDefault??DEFAULT_SENSITIVITY.includedByDefault}}function toJson(value){if(!(value===void 0||typeof value=="function"||typeof value=="symbol")){if(value===null||typeof value=="string"||typeof value=="boolean")return value;if(typeof value=="number")return Number.isFinite(value)?value:null;if(typeof value=="bigint")return value.toString();if(value instanceof Date)return value.toISOString();if(Array.isArray(value))return value.map(v=>toJson(v)??null);if(typeof value=="object"){let out={};for(let[k,v]of Object.entries(value)){let j=toJson(v);j!==void 0&&(out[k]=j)}return out}}}function projectValues(raw,declared,pathPrefix=""){let byName=new Map(declared.map(d=>[d.name,d])),values={},omissions=[];for(let[name,value]of Object.entries(raw)){let path=pathPrefix?`${pathPrefix}.${name}`:name,decl=byName.get(name);if(!decl){omissions.push({path,reason:"filtered"});continue}let sensitivity=resolveSensitivity(decl);if(sensitivity.classification!=="ordinary"){omissions.push({path,reason:"excluded",classification:sensitivity.classification});continue}if(!sensitivity.exportable){omissions.push({path,reason:"excluded"});continue}let json=toJson(value);json!==void 0&&(values[name]=json)}return{values,omissions}}function createProjectedReads(source){return{async values(signal){if(!source.surface||!source.declaration)return{values:{},omissions:[]};let raw=await source.surface.readValues(signal),screenValues=source.declaration.values;return projectValues(raw,screenValues)},async item(signal){let item=source.item;if(!item||!source.declaration)return null;let type=source.declaration.itemTypes?.find(t=>t.name===item.itemType);if(!type)return{values:{},omissions:[{path:item.itemType,reason:"filtered"}]};let raw=await item.readValues(signal);return projectValues(raw,type.values,item.itemType)},async live(signal){return source.surface?.readLive?source.surface.readLive(signal):{}}}}async function runAction(action,target,options){let{ports}=options;if(action.requiresAuth&&!target.auth.authenticated)return ports.auth?(ports.auth.signInThenResume({actionId:action.id,contentFingerprint:options.contentFingerprint??action.id}),{status:"auth-pending"}):(ports.diagnostics.capture(new Error(`requiresAuth action "${action.id}" ran signed out with no auth port`),{area:"actions",detail:{actionId:action.id}}),{status:"failed",error:new Error("sign-in unavailable")});let reads=createProjectedReads(options.source??{surface:null,declaration:target.declaration,item:null}),signal=options.signal??new AbortController().signal;try{return{status:"ran",outcome:await action.run(target,{reads,ports,signal})}}catch(error){ports.diagnostics.capture(error,{area:"actions",detail:{actionId:action.id,stage:"run"}});let label=typeof action.label=="string"?action.label:action.id;return ports.notify?.error(`${label} did not finish.`,"Try again; if it keeps failing, report it from the feedback button."),{status:"failed",error}}}var APPROVED_HEADINGS=new Set(["Save","Copy as","Export","Edit","Creator tools","Admin","App","Compare","History"]),CONTAINER_WORD=/^(more|more…|more\.\.\.|other|others|misc|miscellaneous|additional|extra|extras|actions|options|advanced|stuff|everything else)$/i,TARGET_SHAPE=/^(Cell|Row|Column|Table|Range|Selection|Record) · .+$/;function isContainerWord(label){return CONTAINER_WORD.test(label.trim())}function isApprovedHeading(label,kind="group",approved=APPROVED_HEADINGS){let l=label.trim();return!l||isContainerWord(l)?!1:approved.has(l)?!0:kind==="target"||TARGET_SHAPE.test(l)}function defaultHeadingPolicy(){return globalThis.process?.env?.NODE_ENV==="production"?"inline":"throw"}var UnapprovedHeadingError=class extends Error{heading;constructor(heading,where){super(`Menu heading "${heading}" (${where}) is not an approved heading. Remedy: show these rows inline \u2014 declare no section (or kind "target" for the clicked thing's own label) \u2014 or ask Arman to add the name to APPROVED_HEADINGS in @ai-matrx/alchemy/menu. A generic container word ("More\u2026", "Other") is never approved.`),this.name="UnapprovedHeadingError",this.heading=heading}};var CATEGORY_GROUP={clipboard:"clipboard",copy:"transfer",export:"transfer",save:"document",share:"document",edit:"editable",history:"history",ai:"ai",ask:"ai",listen:"tools",study:"tools",app:"tools",feedback:"quick",creator:"admin",admin:"admin","surface-info":"surface-info"},GROUP_ORDER=["clipboard","editable","transfer","document","history","ai","tools","quick","surface","admin","surface-info"],CATEGORY_ORDER=["clipboard","edit","copy","export","save","share","history","ask","ai","listen","study","app","feedback","creator","admin","surface-info"];function translate(i18n,key,fallback){if(!i18n)return fallback;try{return i18n.t(key,fallback)}catch{return fallback}}function actionToNode(resolved,target,options={}){let{action,eligibility}=resolved,rawLabel=typeof action.label=="function"?action.label(target):action.label,label=translate(options.i18n,action.labelKey??action.id,rawLabel),base={id:action.id,actionId:action.id,...action.icon!==void 0?{icon:action.icon}:{},...action.placement!==void 0?{placement:action.placement}:{}};if(action.expand)return{...base,kind:"submenu",label,lazy:!0,loading:!1,...action.pending?.(target)?{pending:!0}:{},children:[],...action.emptyLabel!==void 0?{emptyLabel:action.emptyLabel}:{}};if(action.href!==void 0){let href=typeof action.href=="function"?action.href(target):action.href;return{...base,kind:"link",label,href}}if(action.toggle)return{...base,kind:"checkbox",label,checked:action.pressed?.(target)??!1,...action.description!==void 0?{description:action.description}:{}};let state=action.stateIcon?.(target)??null,pressed=action.pressed?.(target),hint=action.hint!==void 0?translate(options.i18n,action.hintKey??`${action.id}.hint`,action.hint):void 0;return{...base,kind:"item",label,...action.iconTone!==void 0?{iconTone:action.iconTone}:{},...state?{stateIcon:state}:{},...action.description!==void 0?{description:action.description}:{},...hint!==void 0?{hint}:{},...pressed!==void 0?{pressed}:{},...action.destructive?{destructive:!0}:{},...action.preserveSelection?{preserveSelection:!0}:{},...eligibility.status==="unavailable-verb"?{unavailable:{sentence:eligibility.sentence}}:{}}}function buildMenuModel(target,resolved,options={}){let policy=options.headingPolicy??defaultHeadingPolicy();resolved=resolved.map(r=>{let sec=r.action.section;if(r.action.expand&&isContainerWord(typeof r.action.label=="string"?r.action.label:"")&&policy==="throw")throw new UnapprovedHeadingError(r.action.label,`submenu of ${r.action.id}`);if(!sec)return r;let kind=sec.kind??(sec.primary?"target":"group");if(isApprovedHeading(sec.label,kind))return r;if(policy==="throw")throw new UnapprovedHeadingError(sec.label,`section of ${r.action.id}`);let{section:_dropped,...rest}=r.action;return{...r,action:rest}});let ordered=resolved.map((r,index)=>({r,index})).sort((a,b)=>{let ca=CATEGORY_ORDER.indexOf(a.r.action.category),cb=CATEGORY_ORDER.indexOf(b.r.action.category);if(ca!==cb)return ca-cb;let oa=a.r.action.order??0,ob=b.r.action.order??0;return oa!==ob?oa-ob:a.index-b.index}).map(x=>x.r),sections=new Map,roles={},explicit=new Map;resolved.forEach((r,index)=>{let sec=r.action.section;if(!sec)return;let entry=explicit.get(sec.id)??{group:CATEGORY_GROUP[r.action.category],rows:[]};entry.rows.push({r,index}),explicit.set(sec.id,entry)});let placed=new Set;for(let r of ordered){let sec=r.action.section;if(sec&&placed.has(sec.id))continue;let group=sec?explicit.get(sec.id)?.group??CATEGORY_GROUP[r.action.category]:CATEGORY_GROUP[r.action.category],sectionId=sec?`section:${sec.id}`:group,section=sections.get(sectionId);section||(section={id:sectionId,group,nodes:[],...sec?{label:translate(options.i18n,sec.labelKey??`section.${sec.id}`,sec.label)}:{},...sec?.icon!==void 0?{icon:sec.icon}:{},...sec?.primary?{primary:!0}:{},...sec&&(sec.kind??(sec.primary?"target":"group"))==="target"?{target:!0}:{}},sections.set(sectionId,section));let rows=sec?(explicit.get(sec.id)?.rows??[]).sort((x,y)=>(x.r.action.order??0)-(y.r.action.order??0)||x.index-y.index).map(x=>x.r):[r];sec&&placed.add(sec.id);for(let row of rows)section.nodes.push(actionToNode(row,target,options)),row.action.verb&&(roles[row.action.verb]=row.action.id)}let list=[...sections.values()].sort((a,b)=>!!a.primary!=!!b.primary?a.primary?-1:1:GROUP_ORDER.indexOf(a.group)-GROUP_ORDER.indexOf(b.group)),selected=target.selection?.text?.trim(),content=options.content?.trim();return{header:selected?{label:"Selected",text:target.selection?.text??""}:content?{label:"Content",text:options.content??""}:null,sections:list,roles}}function withExpandedChildren(model,nodeId,children){let visit=nodes=>nodes.map(n=>n.kind!=="submenu"?n:n.id===nodeId?children==="loading"?{...n,loading:!0}:{...n,lazy:!1,loading:!1,pending:!1,children}:{...n,children:visit(n.children)});return{...model,sections:model.sections.map(s=>({...s,nodes:visit(s.nodes)}))}}function findNode(nodes,id){for(let n of nodes){if(n.id===id)return n;if(n.kind==="submenu"){let hit=findNode(n.children,id);if(hit)return hit}}return null}import*as React from"react";var KEY=Symbol.for("ai-matrx.alchemy.actions-context"),AlchemyActionsContext=globalThis[KEY]??=React.createContext(null);function useAlchemyActions(){let value=React.useContext(AlchemyActionsContext);if(!value)throw new Error("Alchemy actions: render inside <AlchemyActionsProvider> (@ai-matrx/alchemy/react/host).");return value}function isLatestExpansion(capturedTargetEpoch,currentTargetEpoch,capturedNodeSequence,currentNodeSequence){return capturedTargetEpoch===currentTargetEpoch&&capturedNodeSequence===currentNodeSequence}import{jsx}from"react/jsx-runtime";function useMenuEngine(target,options={}){let{registry,ports}=useAlchemyActions(),[resolved,setResolved]=React2.useState([]),[model,setModel]=React2.useState(null),[tick,setTick]=React2.useState(0),expanded=React2.useRef(new Map),expandSeq=React2.useRef(new Map),targetEpoch=React2.useRef(0),currentTarget=React2.useRef(target);currentTarget.current!==target&&(currentTarget.current=target,targetEpoch.current+=1);let active=options.active??!0,optionsRef=React2.useRef(options);optionsRef.current=options,React2.useEffect(()=>registry.subscribe(()=>setTick(t=>t+1)),[registry]);let expandAction=React2.useCallback(async(action,nodeId)=>{if(!target||!action.expand)return;let epoch=targetEpoch.current,seq=(expandSeq.current.get(nodeId)??0)+1;expandSeq.current.set(nodeId,seq);let latest=()=>isLatestExpansion(epoch,targetEpoch.current,seq,expandSeq.current.get(nodeId));setModel(m=>m&&withExpandedChildren(m,nodeId,"loading"));try{let children=await action.expand(target,new AbortController().signal);if(!latest())return;let nodes=children.map(child=>(expanded.current.set(child.id,child),actionToNode({action:child,eligibility:{status:"available"}},target,ports.i18n?{i18n:ports.i18n}:{})));setModel(m=>m&&withExpandedChildren(m,nodeId,nodes))}catch(error){if(!latest())return;ports.diagnostics.capture(error,{area:"menu",detail:{nodeId,stage:"expand"}}),setModel(m=>m&&withExpandedChildren(m,nodeId,[]))}},[target,ports]);React2.useEffect(()=>{expanded.current.clear()},[target]),React2.useEffect(()=>{if(!target||!active)return;let live=!0;return registry.resolve(target,optionsRef.current.restrict).then(list=>{if(live){setResolved(list),setModel(buildMenuModel(target,list,{...ports.i18n?{i18n:ports.i18n}:{},content:optionsRef.current.content??null}));for(let{action}of list)expanded.current.get(action.id)===null&&action.expand&&expandAction(action,action.id)}}),()=>{live=!1}},[registry,ports,target,active,tick,options.revision,expandAction]);let resolvedRef=React2.useRef(resolved);resolvedRef.current=resolved;let subscribedIds=resolved.map(r=>r.action.id).join(`
3
+ `);React2.useEffect(()=>{if(!target)return;let subscribing=!0,onChange=()=>{subscribing||setTick(t=>t+1)},offs=resolvedRef.current.map(r=>r.action.subscribe?.(onChange,target)).filter(off=>typeof off=="function");return subscribing=!1,()=>offs.forEach(off=>off())},[subscribedIds,target]);let findAction=React2.useCallback(id=>resolved.find(r=>r.action.id===id)?.action??expanded.current.get(id)??void 0,[resolved]),run=React2.useCallback(async nodeId=>{if(!target||!model)return null;let node=model.sections.map(s=>findNode(s.nodes,nodeId)).find(Boolean)??null,action=findAction(node&&"actionId"in node&&node.actionId?node.actionId:nodeId);if(!action)return null;let o=optionsRef.current,result=await runAction(action,target,{ports,...o.source?{source:o.source}:{},...o.contentFingerprint?{contentFingerprint:o.contentFingerprint}:{}});return o.onRan?.(nodeId,result),result},[target,model,findAction,ports]),expand=React2.useCallback(async nodeId=>{let action=findAction(nodeId);!target||!action?.expand||(expanded.current.set(nodeId,null),await expandAction(action,nodeId))},[findAction,target,expandAction]),icon=React2.useCallback((key,tone)=>{if(!key||!ports.icons)return null;let Resolved=ports.icons.resolve(key);return Resolved?jsx(Resolved,{className:`h-4 w-4 shrink-0 ${tone??""}`,"aria-hidden":!0}):null},[ports.icons]),explain=React2.useCallback(sentence=>{ports.notify?ports.notify.info(sentence):ports.diagnostics.capture(new Error(`No notify port to explain: ${sentence}`),{area:"menu",detail:{sentence}})},[ports]);return{model,resolved,run,expand,icon,explain}}import*as React3 from"react";import{DropdownMenuCheckboxItem,DropdownMenuItem,DropdownMenuLabel,DropdownMenuSeparator,DropdownMenuSub,DropdownMenuSubContent,DropdownMenuSubTrigger,Tooltip,TooltipContent,TooltipTrigger}from"@ai-matrx/design-system";import{Fragment as Fragment2,jsx as jsx2,jsxs}from"react/jsx-runtime";function NodeList({nodes,engine}){return jsx2(Fragment2,{children:nodes.map(node=>jsx2(MenuNodeView,{node,engine},node.id))})}function SectionList({sections,engine}){return jsx2(Fragment2,{children:sections.map((section,index)=>jsxs(React3.Fragment,{children:[index>0?jsx2(DropdownMenuSeparator,{}):null,sectionLabel(section)?jsx2(DropdownMenuLabel,{className:"text-xs font-medium text-muted-foreground",children:sectionLabel(section)}):null,jsx2(NodeList,{nodes:section.nodes,engine})]},section.id))})}function iconOf(node,engine){if(node.kind!=="item")return"icon"in node?engine.icon(node.icon):null;if(node.stateIcon){let glyph=engine.icon(node.stateIcon.icon);return node.stateIcon.spin?jsx2("span",{className:"inline-flex animate-spin",children:glyph}):glyph}if(!("icon"in node))return null;let tone=node.pressed===!1?void 0:node.iconTone;return engine.icon(node.icon,tone)}function MenuNodeView({node,engine}){switch(node.kind){case"separator":return jsx2(DropdownMenuSeparator,{});case"label":return jsx2(DropdownMenuLabel,{className:"text-xs font-medium text-muted-foreground",children:node.label});case"submenu":return jsxs(DropdownMenuSub,{onOpenChange:open=>{open&&node.lazy&&!node.loading&&engine.expand(node.id)},children:[jsxs(DropdownMenuSubTrigger,{"data-alchemy-node":node.id,className:"gap-2","aria-busy":node.pending?!0:void 0,children:[iconOf(node,engine),jsx2("span",{className:"truncate",children:node.label}),node.pending?jsx2("span",{className:"ml-auto text-xs text-muted-foreground",children:"Loading\u2026"}):null]}),jsx2(DropdownMenuSubContent,{className:"max-h-[var(--radix-dropdown-menu-content-available-height)] overflow-y-auto",children:node.loading?jsx2(DropdownMenuLabel,{className:"text-xs text-muted-foreground",children:"Loading\u2026"}):node.children.length===0&&!node.lazy?jsx2(DropdownMenuLabel,{className:"text-xs text-muted-foreground",children:node.emptyLabel??"Nothing here yet"}):jsx2(NodeList,{nodes:node.children,engine})})]});case"checkbox":return jsxs(DropdownMenuCheckboxItem,{"data-alchemy-node":node.id,checked:node.checked,onSelect:()=>{engine.run(node.id)},className:"gap-2",children:[iconOf(node,engine),jsx2("span",{className:"truncate",children:node.label})]});case"link":return jsx2(DropdownMenuItem,{asChild:!0,"data-alchemy-node":node.id,children:jsxs("a",{href:node.href,target:node.target,className:"gap-2",children:[iconOf(node,engine),jsx2("span",{className:"truncate",children:node.label})]})});case"item":return jsx2(LeafItem,{node,engine})}}function LeafItem({node,engine}){let row=jsxs(DropdownMenuItem,{"data-alchemy-node":node.id,"aria-disabled":node.unavailable?!0:void 0,"aria-pressed":node.pressed,onSelect:event=>{if(node.unavailable){event.preventDefault();return}engine.run(node.id)},className:`gap-2 ${node.unavailable?"opacity-50":""} ${node.destructive?"text-destructive":""}`,children:[iconOf(node,engine),jsxs("span",{className:"flex min-w-0 flex-1 flex-col",children:[jsx2("span",{className:"truncate",children:node.label}),node.description?jsx2("span",{className:"truncate text-xs text-muted-foreground",children:node.description}):null]}),node.hint?jsx2("span",{className:"ml-auto text-xs text-muted-foreground",children:node.hint}):null]});return node.unavailable?jsxs(Tooltip,{children:[jsx2(TooltipTrigger,{asChild:!0,children:row}),jsx2(TooltipContent,{children:node.unavailable.sentence})]}):row}function LeafButton({node,engine,showLabel}){if(node.kind!=="item"&&node.kind!=="checkbox"&&node.kind!=="link")return null;let unavailable=node.kind==="item"?node.unavailable:void 0,pressed=node.kind==="item"?node.pressed:node.kind==="checkbox"?node.checked:void 0,glyph=iconOf(node,engine),button=jsxs("button",{type:"button","data-alchemy-node":node.id,"data-matrx-button":"","data-tap-floor":"","data-tap-floor-square":"","aria-label":node.label,"aria-disabled":unavailable?!0:void 0,"aria-pressed":pressed,onMouseDown:e=>{node.kind==="item"&&node.preserveSelection&&e.preventDefault()},onClick:()=>{if(unavailable){engine.explain(unavailable.sentence);return}if(node.kind==="link"){window.location.assign(node.href);return}engine.run(node.id)},className:`inline-flex h-7 min-w-7 shrink-0 items-center justify-center gap-1.5 rounded-md px-1.5 text-sm text-muted-foreground hover:bg-accent hover:text-foreground ${unavailable?"cursor-default opacity-50 hover:bg-transparent":""} ${pressed?"text-foreground":""}`,children:[glyph,showLabel||!glyph?jsx2("span",{className:"whitespace-nowrap",children:node.label}):null]});return jsxs(Tooltip,{children:[jsx2(TooltipTrigger,{asChild:!0,children:button}),jsx2(TooltipContent,{children:unavailable?unavailable.sentence:node.label})]})}import{Fragment as Fragment3,jsx as jsx3,jsxs as jsxs2}from"react/jsx-runtime";function isNarrow(width){return typeof window>"u"?!1:window.matchMedia?.(`(max-width: ${width-1}px)`).matches??!1}var TRIGGER_CLASS="inline-flex h-7 min-w-7 items-center justify-center gap-1 rounded-md px-1.5 text-muted-foreground hover:bg-accent hover:text-foreground";function PrimarySubmenu({node,engine}){return jsxs2(DropdownMenu,{onOpenChange:open=>{open&&node.lazy&&!node.loading&&engine.expand(node.id)},children:[jsx3(DropdownMenuTrigger,{asChild:!0,children:jsx3("button",{type:"button","aria-label":node.label,"data-alchemy-node":node.id,className:TRIGGER_CLASS,children:engine.icon(node.icon)??jsx3("span",{className:"text-sm",children:node.label})})}),jsx3(DropdownMenuContent,{align:"start",className:"w-64 max-h-[var(--radix-dropdown-menu-content-available-height)] overflow-y-auto",children:node.loading?jsx3("div",{className:"px-2 py-1.5 text-xs text-muted-foreground",children:"Loading\u2026"}):jsx3(NodeList,{nodes:node.children,engine})})]})}function ActionBar({target,mini=!1,className,hideOverflow=!1,sheetBelow=768,loadSheet=()=>import("@ai-matrx/alchemy/react/sheet"),...options}){let engine=useMenuEngine(target,options),[sheetOpen,setSheetOpen]=React4.useState(!1),[Sheet,setSheet]=React4.useState(null);if(!engine.model)return null;let arranged=bar(engine.model,{mini});return arranged.primary.length===0&&arranged.overflow.length===0?null:jsx3(TooltipProvider,{children:jsxs2("div",{role:"toolbar","aria-label":"Actions","data-alchemy-layout":"bar",className:`flex items-center ${mini?"gap-0":"gap-0.5"} ${className??""}`,children:[arranged.primary.map(node=>node.kind==="submenu"?jsx3(PrimarySubmenu,{node,engine},node.id):jsx3(LeafButton,{node,engine,showLabel:!1},node.id)),hideOverflow||arranged.overflow.length===0?null:isNarrow(sheetBelow)?jsxs2(Fragment3,{children:[jsx3("button",{type:"button","aria-label":"More actions","data-alchemy-trigger":"overflow",className:TRIGGER_CLASS,onClick:()=>{setSheetOpen(!0),Sheet||loadSheet().then(m=>setSheet(()=>m.ActionSheet))},children:jsx3("span",{"aria-hidden":!0,className:"text-base leading-none",children:"\u22EF"})}),Sheet?jsx3(Sheet,{...options,target,open:sheetOpen,onOpenChange:setSheetOpen}):null]}):jsxs2(DropdownMenu,{children:[jsx3(DropdownMenuTrigger,{asChild:!0,children:jsx3("button",{type:"button","aria-label":"More actions","data-alchemy-trigger":"overflow",className:TRIGGER_CLASS,children:jsx3("span",{"aria-hidden":!0,className:"text-base leading-none",children:"\u22EF"})})}),jsx3(DropdownMenuContent,{align:"end",className:"w-64 max-h-[var(--radix-dropdown-menu-content-available-height)] overflow-y-auto",children:jsx3(SectionList,{sections:arranged.overflow,engine})})]})]})})}export{ActionBar};
776
4
  //# sourceMappingURL=react-bar.js.map