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