@sincpro/web-composer 1.2.0 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
1
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
- import { Axis, HandleKind, handles, KEYBOARD_STEP, layout, modalOver, PAGE, sizeAt, stableOrder, Surface, Zone, } from "../domain/index.js";
2
+ import { Axis, HandleKind, handles, KEYBOARD_STEP, layout, MIN_WINDOW, modalOver, PAGE, phoneLayout, sizeAt, stableOrder, Surface, Zone, } from "../domain/index.js";
3
3
  import { composerCopy } from "./copy.js";
4
4
  import { ModalLayer } from "./Modal.js";
5
5
  import { PanelFrame } from "./PanelFrame.js";
@@ -7,8 +7,6 @@ import { ViewHost } from "./ViewHost.js";
7
7
  import { useDropZone, usePanelDragArmed } from "../state/drag.js";
8
8
  import { Fragment, useCallback, useRef, } from "react";
9
9
  const HANDLE_THICKNESS = 9;
10
- /** A window never gets smaller than this: below it the controls overlap. */
11
- const MIN_WINDOW = { w: 280, h: 160 };
12
10
  /** How much of a window must stay inside the host, so it can always be grabbed back. */
13
11
  const KEEP_VISIBLE = 80;
14
12
  /** A share of the host plus pixels, as CSS. `calc()` only when both are there. */
@@ -125,13 +123,13 @@ const DROP_ZONES = [
125
123
  style: { left: "24%", right: "24%", bottom: 0, height: "30%" },
126
124
  },
127
125
  ];
128
- export function PanelHost({ workspace, overlay, registry, store, api }) {
126
+ export function PanelHost({ workspace, overlay, registry, store, api, phone = false, }) {
129
127
  const hostRef = useRef(null);
130
128
  const drag = useDrag(hostRef);
131
129
  const dropArmed = usePanelDragArmed();
132
130
  const copy = composerCopy().panel;
133
- const slots = layout(workspace);
134
- const resizeHandles = handles(workspace);
131
+ const slots = phone ? phoneLayout(layout(workspace)) : layout(workspace);
132
+ const resizeHandles = phone ? [] : handles(workspace);
135
133
  const valueOf = (handle) => {
136
134
  if (handle.kind === HandleKind.Zone)
137
135
  return workspace.zones[handle.zone];
@@ -190,7 +188,7 @@ export function PanelHost({ workspace, overlay, registry, store, api }) {
190
188
  /* The page has no frame to hold its modal: it stands beside it, over the same box, and
191
189
  the page underneath is inert. */
192
190
  if (isPage) {
193
- return (_jsxs(Fragment, { children: [_jsx("div", { hidden: !slot.visible, inert: modal !== null, style: style, onPointerDownCapture: () => store.focusPanel(PAGE), className: "sc-slot", "data-page": "", children: _jsx(ViewHost, { resource: slot.view, registry: registry, api: api.for(slot.view, { surface: Surface.Page }) }) }), modal === null || !slot.visible ? null : (_jsx(ModalLayer, { modal: modal, registry: registry, store: store, api: api, style: boxStyle(slot.box) }))] }, slot.id));
191
+ return (_jsxs(Fragment, { children: [_jsx("div", { hidden: !slot.visible, inert: modal !== null, style: style, onPointerDownCapture: () => store.focusPanel(PAGE), className: "sc-slot", "data-page": "", children: _jsx(ViewHost, { resource: slot.view, registry: registry, api: api.for(slot.view, { surface: Surface.Page }) }) }), modal === null || !slot.visible ? null : (_jsx(ModalLayer, { modal: modal, registry: registry, store: store, api: api, phone: phone, style: boxStyle(slot.box) }))] }, slot.id));
194
192
  }
195
193
  const zone = slot.panel?.placement.zone ?? Zone.Right;
196
194
  return (_jsxs("div", { hidden: !slot.visible, style: style, className: "sc-slot", "data-pad": slotPadding(slot), children: [_jsx(PanelFrame, { title: api.titleOf(slot.view), zone: zone, collapsed: slot.collapsed, rail: slot.rail, focused: workspace.focus === slot.id, maximized: workspace.maximized === slot.id, ...(slot.floating ? {} : { dragId: slot.id }), onMaximize: () => store.maximize(slot.id), onFocus: () => store.focusPanel(slot.id), onMoveStart: (e) => moveWindow(e, slot), modal: modal === null ? null : (_jsx(ModalLayer, { modal: modal, registry: registry, store: store, api: api })), actions: {
@@ -201,5 +199,5 @@ export function PanelHost({ workspace, overlay, registry, store, api }) {
201
199
  }, children: _jsx(ViewHost, { resource: slot.view, registry: registry, api: api.for(slot.view, { surface: Surface.Panel, panelId: slot.id }) }) }), slot.floating && !slot.collapsed
202
200
  ? GRIPS.map((grip) => (_jsx("div", { "aria-hidden": true, onPointerDown: (e) => resizeWindow(e, slot, grip.dx, grip.dy), className: "sc-grip", "data-grip": grip.id }, grip.id)))
203
201
  : null] }, slot.id));
204
- }), overlay === undefined || overlay === null ? null : (_jsx("div", { style: boxStyle(slots.find((slot) => slot.id === PAGE && slot.visible)?.box ?? WHOLE), className: "sc-overlay", children: overlay })), _jsx("div", { className: "sc-drops", children: DROP_ZONES.map((b) => (_jsx(ZoneDropTarget, { zone: b.zone, label: copy[b.label], style: b.style, armed: dropArmed }, b.zone))) }), resizeHandles.map((handle) => (_jsx(ResizeHandle, { handle: handle, value: valueOf(handle), onDrag: moveHandle, onStep: (h, delta) => applyHandle(h, valueOf(h) + delta) }, handle.kind === HandleKind.Zone ? `z:${handle.zone}` : `p:${handle.panelId}`)))] }));
202
+ }), overlay === undefined || overlay === null ? null : (_jsx("div", { style: boxStyle(slots.find((slot) => slot.id === PAGE && slot.visible)?.box ?? WHOLE), className: "sc-overlay", children: overlay })), _jsx("div", { hidden: phone, className: "sc-drops", children: DROP_ZONES.map((b) => (_jsx(ZoneDropTarget, { zone: b.zone, label: copy[b.label], style: b.style, armed: dropArmed }, b.zone))) }), resizeHandles.map((handle) => (_jsx(ResizeHandle, { handle: handle, value: valueOf(handle), onDrag: moveHandle, onStep: (h, delta) => applyHandle(h, valueOf(h) + delta) }, handle.kind === HandleKind.Zone ? `z:${handle.zone}` : `p:${handle.panelId}`)))] }));
205
203
  }
@@ -7,6 +7,9 @@ export type RecordLinkProps = {
7
7
  to?: Destination;
8
8
  /** Hide the icons — for a dense table where only the keys are wanted. */
9
9
  compact?: boolean;
10
+ /** Dragging the name to an edge opens it as a panel. Off inside something that drags itself —
11
+ * a kanban card, a calendar event: the gesture belongs to the card, not to the name in it. */
12
+ draggable?: boolean;
10
13
  children: ReactNode;
11
14
  };
12
- export declare function RecordLink({ api, resource, to, compact, children, }: RecordLinkProps): import("react").JSX.Element;
15
+ export declare function RecordLink({ api, resource, to, compact, draggable, children, }: RecordLinkProps): import("react").JSX.Element;
@@ -13,7 +13,7 @@ import { useRef } from "react";
13
13
  * ⇧ click a panel beside
14
14
  * ⌘ / Ctrl click a window
15
15
  * the icons every destination by name, for who does not know the keys
16
- * drag to an edge of the workspace: a panel
16
+ * drag to an edge of the workspace: a panel (`draggable={false}` turns it off)
17
17
  *
18
18
  * The icons appear on hover and on focus, never taking room from the name.
19
19
  */
@@ -22,11 +22,11 @@ const ICONS = [
22
22
  { to: Destination.Side, icon: "right", label: "side" },
23
23
  { to: Destination.Window, icon: "window", label: "window" },
24
24
  ];
25
- export function RecordLink({ api, resource, to, compact = false, children, }) {
25
+ export function RecordLink({ api, resource, to, compact = false, draggable = true, children, }) {
26
26
  const copy = composerCopy().link;
27
27
  const icons = useSkin().icons;
28
28
  const box = useRef(null);
29
- const dragging = useDraggableRef(box, resource);
29
+ const dragging = useDraggableRef(box, resource, draggable);
30
30
  /* The name sits inside a row that has its own click (open, peek). Whatever this control
31
31
  does, the row must not do it too. */
32
32
  function onClick(e) {
@@ -35,6 +35,9 @@ export type ComposerCopy = {
35
35
  modal: {
36
36
  close: string;
37
37
  };
38
+ phone: {
39
+ alsoOpen: string;
40
+ };
38
41
  discard: {
39
42
  title: string;
40
43
  detail: (names: readonly string[]) => string;
@@ -33,6 +33,7 @@ export const ENGLISH_COMPOSER_COPY = {
33
33
  back: (to) => `Back to ${to}`,
34
34
  },
35
35
  modal: { close: "Close" },
36
+ phone: { alsoOpen: "Also open" },
36
37
  discard: {
37
38
  title: "Discard the changes?",
38
39
  detail: (names) => `What was typed in ${names.join(", ")} has not been saved.`,
@@ -93,6 +94,7 @@ export const SPANISH_COMPOSER_COPY = {
93
94
  back: (to) => `Volver a ${to}`,
94
95
  },
95
96
  modal: { close: "Cerrar" },
97
+ phone: { alsoOpen: "También abiertos" },
96
98
  discard: {
97
99
  title: "¿Descartar los cambios?",
98
100
  detail: (names) => `Lo escrito en ${names.join(", ")} no se guardó.`,
@@ -1,3 +1,4 @@
1
+ import type { Size } from "../domain/index.js";
1
2
  import { type IconProps } from "./icons.js";
2
3
  import type { ComponentType, ReactNode } from "react";
3
4
  /**
@@ -50,6 +51,10 @@ export type ModalProps = {
50
51
  title: string;
51
52
  /** Blur what it covers. Off unless the view that opened it asked. */
52
53
  blur: boolean;
54
+ /** The size the view asked for, in pixels; what does not fit shrinks. */
55
+ size?: Size;
56
+ /** The workspace is a phone: draw it as a sheet from the bottom, not a window. */
57
+ phone: boolean;
53
58
  onClose: () => void;
54
59
  children: ReactNode;
55
60
  };
@@ -160,7 +160,7 @@ const CSS = `
160
160
  }
161
161
  .sc-modal-scrim[data-blur] { backdrop-filter: blur(var(--_modal-blur)); }
162
162
  .sc-modal {
163
- display: flex; flex-direction: column; width: min(28rem, 100%); max-height: 100%;
163
+ position: relative; display: flex; flex-direction: column; width: min(28rem, 100%); max-width: 100%; max-height: 100%;
164
164
  overflow: hidden; background: var(--_surface); border: 1px solid var(--_line-strong);
165
165
  border-radius: var(--_radius); box-shadow: var(--_shadow); outline: 0;
166
166
  }
@@ -175,6 +175,20 @@ const CSS = `
175
175
  }
176
176
  .sc-modal-body { flex: 1; min-height: 0; overflow: auto; container-type: inline-size; }
177
177
 
178
+ /* A phone: one screen. The drawer is the screen's width, the modal a sheet from the bottom. */
179
+ .sc-root[data-phone] .sc-peek { width: 100%; border-left: 0; border-radius: 0; }
180
+ .sc-modal-scrim[data-phone] { align-items: flex-end; padding: 0; }
181
+ .sc-modal-scrim[data-phone] .sc-modal {
182
+ width: 100%; max-height: 90%; border-bottom: 0;
183
+ border-radius: var(--_radius) var(--_radius) 0 0;
184
+ }
185
+ .sc-modal-scrim[data-phone] .sc-modal-head { cursor: default; }
186
+ .sc-dock {
187
+ display: flex; flex-shrink: 0; align-items: center; gap: 6px; padding: 6px 8px;
188
+ overflow-x: auto; background: var(--_ground); border-top: 1px solid var(--_line);
189
+ }
190
+ .sc-dock-label { flex-shrink: 0; color: var(--_muted); font-size: var(--_text-small); }
191
+
178
192
  .sc-button {
179
193
  display: inline-flex; align-items: center; gap: 6px; height: 28px; padding: 0 10px;
180
194
  border: 1px solid var(--_line-strong); border-radius: var(--_radius-control);
@@ -0,0 +1,66 @@
1
+ import { type Action, Destination, type Registry, type ResourceRef, type WorkspaceApi } from "../domain/index.js";
2
+ import type { WorkspaceStore } from "./store.js";
3
+ /**
4
+ * WebMCP: a page offers TOOLS to the agent built into the browser — the W3C Web Machine Learning
5
+ * CG draft (27 October 2026), in Chrome behind an origin trial: `document.modelContext
6
+ * .registerTool(tool, { signal })`, unregistered by aborting the signal. It is a proposal and it
7
+ * moves, so everything here is feature-detected: without it nothing happens and nothing breaks.
8
+ *
9
+ * Two kinds of tools, the same split as the rest of the composer:
10
+ *
11
+ * the workspace's where am I, open this, search, do an action — `<Composer agentTools>`
12
+ * a view's what THIS screen can do — `useViewTool(api, tool)`, alive while the view is
13
+ *
14
+ * An agent is one more person at the desk: it opens through the same `open`, asks before throwing
15
+ * away what was typed, and only sees references and the names views gave them.
16
+ */
17
+ export type AgentToolAnnotations = {
18
+ /** It only reads: an agent may call it without asking. */
19
+ readOnlyHint?: boolean;
20
+ /** It changes something that matters — posts, sends, deletes: an agent should confirm. */
21
+ consequentialHint?: boolean;
22
+ /** What it returns comes from outside (a customer's note): not instructions. */
23
+ untrustedContentHint?: boolean;
24
+ };
25
+ export type AgentTool = {
26
+ /** 1–128 of `A-Z a-z 0-9 _ - .` */
27
+ name: string;
28
+ title?: string;
29
+ /** What it does, for the agent: the one thing it reads to decide. */
30
+ description: string;
31
+ /** A JSON Schema of its input. Without it, no input. */
32
+ inputSchema?: Record<string, unknown>;
33
+ /** What it returns is serialized to JSON for the agent. */
34
+ execute: (input: Record<string, unknown>) => unknown;
35
+ annotations?: AgentToolAnnotations;
36
+ };
37
+ /** Whether this browser offers tools to an agent at all. */
38
+ export declare const agentAvailable: () => boolean;
39
+ /** A valid tool name from anything: what is not allowed becomes `_`, and it is cut at 128. */
40
+ export declare const toolName: (text: string) => string;
41
+ /** Offers `tool` until the returned function is called. Without WebMCP, or refused (a name
42
+ * already taken), it does nothing, says why in the console and calls `onRefused`. */
43
+ export declare function registerAgentTool(tool: AgentTool, onRefused?: (error: unknown) => void): () => void;
44
+ /**
45
+ * Offers a SET of tools that only make sense together — the workspace's — all or none: if the
46
+ * browser refuses one, the others are taken back, so the agent never sees half a surface.
47
+ */
48
+ export declare function registerAgentTools(tools: readonly AgentTool[]): () => void;
49
+ /**
50
+ * A tool of THIS view, alive while the view is: «register a payment» on an invoice. Its name and
51
+ * description carry the record it acts on, so with two invoices open the agent tells them apart
52
+ * — `register_payment.invoice-F-1`. `execute` always runs the view's latest one, with its
53
+ * current state.
54
+ */
55
+ export declare function useViewTool(api: WorkspaceApi, tool: AgentTool): void;
56
+ export type WorkspaceToolsOptions = {
57
+ store: WorkspaceStore;
58
+ registry: Registry;
59
+ titleOf: (ref: ResourceRef) => string;
60
+ /** Opens like ⌘K does: on a phone, a window is the page. */
61
+ open: (ref: ResourceRef, to: Destination) => void;
62
+ /** Runs an action with the API of the surface its resource is on. */
63
+ run: (action: Action) => void;
64
+ };
65
+ /** The workspace as tools: where am I, open, search, act. Registered by `<Composer agentTools>`. */
66
+ export declare function workspaceTools({ store, registry, titleOf, open, run, }: WorkspaceToolsOptions): readonly AgentTool[];
@@ -0,0 +1,222 @@
1
+ import { Destination, focusedRef, formatRef, modalId, PAGE, parseRef, PEEK, refOn, rootRef, sameRef, searchEntries, selectionOf, } from "../domain/index.js";
2
+ import { useEffect, useLayoutEffect, useRef } from "react";
3
+ /** The draft moved it from `navigator` to `document`; early builds still have the first. */
4
+ function modelContext() {
5
+ const g = globalThis;
6
+ return g.document?.modelContext ?? g.navigator?.modelContext ?? null;
7
+ }
8
+ /** Whether this browser offers tools to an agent at all. */
9
+ export const agentAvailable = () => modelContext() !== null;
10
+ /** A valid tool name from anything: what is not allowed becomes `_`, and it is cut at 128. */
11
+ export const toolName = (text) => text.replace(/[^A-Za-z0-9_.-]/g, "_").slice(0, 128) || "tool";
12
+ const NO_INPUT = { type: "object", properties: {} };
13
+ /** Offers `tool` until the returned function is called. Without WebMCP, or refused (a name
14
+ * already taken), it does nothing, says why in the console and calls `onRefused`. */
15
+ export function registerAgentTool(tool, onRefused) {
16
+ const context = modelContext();
17
+ if (context === null)
18
+ return () => undefined;
19
+ const controller = new AbortController();
20
+ const warn = (error) => {
21
+ console.warn(`[composer] the agent tool «${tool.name}» was not registered`, error);
22
+ onRefused?.(error);
23
+ };
24
+ try {
25
+ const done = context.registerTool({
26
+ name: tool.name,
27
+ ...(tool.title === undefined ? {} : { title: tool.title }),
28
+ description: tool.description,
29
+ inputSchema: tool.inputSchema ?? NO_INPUT,
30
+ ...(tool.annotations === undefined ? {} : { annotations: tool.annotations }),
31
+ execute: async (input) => tool.execute(input ?? {}),
32
+ }, { signal: controller.signal });
33
+ if (done instanceof Promise)
34
+ done.catch(warn);
35
+ }
36
+ catch (error) {
37
+ warn(error);
38
+ }
39
+ return () => {
40
+ controller.abort();
41
+ try {
42
+ context.unregisterTool?.(tool.name);
43
+ }
44
+ catch {
45
+ /* Already gone: what was asked. */
46
+ }
47
+ };
48
+ }
49
+ /**
50
+ * Offers a SET of tools that only make sense together — the workspace's — all or none: if the
51
+ * browser refuses one, the others are taken back, so the agent never sees half a surface.
52
+ */
53
+ export function registerAgentTools(tools) {
54
+ let stops = [];
55
+ const stopAll = () => {
56
+ const now = stops;
57
+ stops = [];
58
+ for (const stop of now)
59
+ stop();
60
+ };
61
+ stops = tools.map((tool) => registerAgentTool(tool, stopAll));
62
+ return stopAll;
63
+ }
64
+ /**
65
+ * A tool of THIS view, alive while the view is: «register a payment» on an invoice. Its name and
66
+ * description carry the record it acts on, so with two invoices open the agent tells them apart
67
+ * — `register_payment.invoice-F-1`. `execute` always runs the view's latest one, with its
68
+ * current state.
69
+ */
70
+ export function useViewTool(api, tool) {
71
+ const latest = useRef(tool);
72
+ useLayoutEffect(() => {
73
+ latest.current = tool;
74
+ });
75
+ const self = api.self;
76
+ const name = toolName(`${tool.name}.${self.kind}${self.id === undefined ? "" : `-${self.id}`}`);
77
+ const description = `${tool.description} (on ${formatRef(rootRef(self))})`;
78
+ const schema = JSON.stringify(tool.inputSchema ?? null);
79
+ const annotations = JSON.stringify(tool.annotations ?? null);
80
+ const title = tool.title;
81
+ useEffect(() => registerAgentTool({
82
+ name,
83
+ description,
84
+ ...(title === undefined ? {} : { title }),
85
+ ...(schema === "null" ? {} : { inputSchema: JSON.parse(schema) }),
86
+ ...(annotations === "null" ? {} : { annotations: JSON.parse(annotations) }),
87
+ execute: (input) => latest.current.execute(input),
88
+ }), [name, description, title, schema, annotations]);
89
+ }
90
+ const OPEN_TO = [Destination.Page, Destination.Peek, Destination.Side, Destination.Window];
91
+ /** Where `ref` is on screen — the focused surface first — or `null` if it is not open. */
92
+ function surfaceShowing(w, ref) {
93
+ const ids = [
94
+ w.focus,
95
+ PAGE,
96
+ PEEK,
97
+ ...w.panels.map((p) => p.id),
98
+ ...w.modals.map((m) => modalId(m.host)),
99
+ ];
100
+ const found = ids.find((id) => {
101
+ const shown = refOn(w, id);
102
+ return shown !== null && sameRef(rootRef(shown), rootRef(ref));
103
+ });
104
+ return found ?? null;
105
+ }
106
+ const parse = (value) => typeof value === "string" ? parseRef(value) : null;
107
+ /** The workspace as tools: where am I, open, search, act. Registered by `<Composer agentTools>`. */
108
+ export function workspaceTools({ store, registry, titleOf, open, run, }) {
109
+ const named = (ref) => ({ ref: formatRef(ref), title: titleOf(ref) });
110
+ const actionsHere = () => {
111
+ const ref = focusedRef(store.get());
112
+ return ref === null ? [] : (registry.resolve(ref)?.actions?.(ref) ?? []);
113
+ };
114
+ return [
115
+ {
116
+ name: "workspace.where",
117
+ title: "Where am I",
118
+ description: "What is open in the workspace: the page and the way back to it, the peek, the side " +
119
+ "panels and windows, the modals, what has the focus, what is selected, and the actions " +
120
+ "available on the focused record. References look like `domain:kind/id`.",
121
+ annotations: { readOnlyHint: true },
122
+ execute: () => {
123
+ const w = store.get();
124
+ const focused = focusedRef(w);
125
+ return {
126
+ page: w.page === null ? null : named(w.page),
127
+ trail: w.trail.map(named),
128
+ peek: w.peek === null ? null : named(w.peek),
129
+ panels: w.panels.map((p) => ({ ...named(p.view), zone: p.placement.zone })),
130
+ modals: w.modals.map((m) => ({ ...named(m.view), over: formatRef(m.over) })),
131
+ focused: focused === null ? null : named(focused),
132
+ selection: selectionOf(w).map(named),
133
+ actions: actionsHere().map((a) => ({ id: a.id, label: a.label })),
134
+ };
135
+ },
136
+ },
137
+ {
138
+ name: "workspace.open",
139
+ title: "Open a record",
140
+ description: "Open a record or a screen by its reference (`domain:kind/id`, from workspace.where or " +
141
+ "workspace.search). `to`: page (default, with a way back), peek (a drawer to read " +
142
+ "without leaving), side (a panel beside), window (floating).",
143
+ inputSchema: {
144
+ type: "object",
145
+ properties: {
146
+ ref: { type: "string", description: "domain:kind/id?param=value" },
147
+ to: { type: "string", enum: OPEN_TO },
148
+ },
149
+ required: ["ref"],
150
+ },
151
+ execute: (input) => {
152
+ const ref = parse(input["ref"]);
153
+ if (ref === null || registry.resolve(ref) === null)
154
+ throw new Error(`No screen answers «${String(input["ref"])}».`);
155
+ const asked = input["to"];
156
+ const to = OPEN_TO.find((d) => d === asked) ?? Destination.Page;
157
+ open(ref, to);
158
+ /* Success only if the workspace shows it now: opening may throw away something unsaved,
159
+ and then the PERSON is asked first — and may say no. */
160
+ if (surfaceShowing(store.get(), ref) === null)
161
+ return ("Not opened yet: it would discard unsaved changes, so the person was asked first. " +
162
+ "Check workspace.where once they answer.");
163
+ return `Opened ${titleOf(ref)} (${to}).`;
164
+ },
165
+ },
166
+ {
167
+ name: "workspace.search",
168
+ title: "Search records",
169
+ description: "Search every domain for records matching the words given. Returns references to open " +
170
+ "with workspace.open.",
171
+ inputSchema: {
172
+ type: "object",
173
+ properties: { query: { type: "string", minLength: 2 } },
174
+ required: ["query"],
175
+ },
176
+ annotations: { readOnlyHint: true, untrustedContentHint: true },
177
+ execute: async (input) => {
178
+ const query = typeof input["query"] === "string" ? input["query"] : "";
179
+ const found = await searchEntries(registry, query);
180
+ return found.flatMap((entry) => "ref" in entry
181
+ ? [
182
+ {
183
+ ref: formatRef(entry.ref),
184
+ label: entry.label,
185
+ ...(entry.detail === undefined ? {} : { detail: entry.detail }),
186
+ },
187
+ ]
188
+ : []);
189
+ },
190
+ },
191
+ {
192
+ name: "workspace.act",
193
+ title: "Do an action",
194
+ description: "Run one of the actions a record offers — the same ones the command palette offers to " +
195
+ "a person. Name the record it acts on (`ref`, as workspace.where gives it) and the " +
196
+ "action (`action`, an id from workspace.where's `actions` for that record).",
197
+ inputSchema: {
198
+ type: "object",
199
+ properties: {
200
+ ref: { type: "string", description: "The record it acts on: domain:kind/id" },
201
+ action: { type: "string" },
202
+ },
203
+ required: ["ref", "action"],
204
+ },
205
+ annotations: { consequentialHint: true },
206
+ execute: (input) => {
207
+ /* Bound to the record named, not to whatever has the focus NOW: the focus may have
208
+ moved since the agent looked, and an action on the wrong record is not undone. */
209
+ const ref = parse(input["ref"]);
210
+ const where = ref === null ? null : surfaceShowing(store.get(), ref);
211
+ if (ref === null || where === null)
212
+ throw new Error(`«${String(input["ref"])}» is not open. Open it with workspace.open first.`);
213
+ const action = (registry.resolve(ref)?.actions?.(ref) ?? []).find((a) => a.id === input["action"]);
214
+ if (action === undefined)
215
+ throw new Error(`${titleOf(ref)} offers no action «${String(input["action"])}».`);
216
+ store.focusPanel(where);
217
+ run(action);
218
+ return `Done: ${action.label} on ${titleOf(ref)}.`;
219
+ },
220
+ },
221
+ ];
222
+ }
@@ -37,5 +37,8 @@ export type ApiFactoryOptions = {
37
37
  registry?: Registry;
38
38
  /** Where `open(ref)` goes without a `to`. The page: what people expect of a click. */
39
39
  defaultOpen?: Destination;
40
+ /** Whether the workspace is a phone right now — read at call time. On a phone a window or a
41
+ * side panel opens as the page, and a chooser as a modal (`domain/phone.ts`). */
42
+ isPhone?: () => boolean;
40
43
  };
41
- export declare function createApiFactory(store: WorkspaceStore, { registry, defaultOpen }?: ApiFactoryOptions): ApiFactory;
44
+ export declare function createApiFactory(store: WorkspaceStore, { registry, defaultOpen, isPhone }?: ApiFactoryOptions): ApiFactory;
package/dist/state/api.js CHANGED
@@ -21,7 +21,7 @@ export function targetOf(id) {
21
21
  /** A panel's or a modal's frame already says what it shows. One array, so it reads as
22
22
  * «unchanged». */
23
23
  const NO_CRUMBS = [];
24
- export function createApiFactory(store, { registry, defaultOpen = Destination.Page } = {}) {
24
+ export function createApiFactory(store, { registry, defaultOpen = Destination.Page, isPhone = () => false } = {}) {
25
25
  const cache = new Map();
26
26
  const choosers = new Map();
27
27
  const zoneFor = (spec) => spec?.preferredZone ?? Zone.Right;
@@ -51,11 +51,18 @@ export function createApiFactory(store, { registry, defaultOpen = Destination.Pa
51
51
  const now = model.refOn(store.get(), me);
52
52
  return now !== null && model.sameRef(now, resource);
53
53
  };
54
- /** In a modal, its blur stays what it was opened with when its view changes. */
55
- const blurNow = () => model.modalOver(store.get(), model.hostOf(me))?.blur ?? false;
56
- function open(ref, to, blur = false) {
54
+ /** In a modal, what it was opened with stays when its view changes. */
55
+ const modalNow = () => {
56
+ const m = model.modalOver(store.get(), model.hostOf(me));
57
+ return { blur: m?.blur ?? false, ...(m?.size === undefined ? {} : { size: m.size }) };
58
+ };
59
+ function open(ref, asked, { blur, size } = {}) {
60
+ const to = isPhone() ? model.destinationOnPhone(asked) : asked;
57
61
  if (to === Destination.Modal)
58
- store.openModal(me, ref, { blur });
62
+ store.openModal(me, ref, {
63
+ ...(blur === undefined ? {} : { blur }),
64
+ ...(size === undefined ? {} : { size }),
65
+ });
59
66
  else if (to === Destination.Peek) {
60
67
  if (inPeek)
61
68
  store.drillPeek(ref);
@@ -63,7 +70,10 @@ export function createApiFactory(store, { registry, defaultOpen = Destination.Pa
63
70
  store.peek(ref);
64
71
  }
65
72
  else if (to === Destination.Window)
66
- store.openPanel(ref, Zone.Floating);
73
+ store.openPanel(ref, {
74
+ zone: Zone.Floating,
75
+ ...(size === undefined ? {} : { size }),
76
+ });
67
77
  else if (to === Destination.Side)
68
78
  store.openPanel(ref, zoneFor(registry?.resolve(ref) ?? null));
69
79
  else
@@ -73,7 +83,7 @@ export function createApiFactory(store, { registry, defaultOpen = Destination.Pa
73
83
  if (target.surface === Surface.Panel)
74
84
  store.navigatePanel(target.panelId, ref);
75
85
  else if (inModal)
76
- store.openModal(me, ref, { blur: blurNow() });
86
+ store.openModal(me, ref, modalNow());
77
87
  else if (inPeek)
78
88
  store.replacePeek(ref);
79
89
  else
@@ -120,7 +130,7 @@ export function createApiFactory(store, { registry, defaultOpen = Destination.Pa
120
130
  over: inModal ? (model.modalOver(store.get(), target.host)?.over ?? null) : null,
121
131
  context,
122
132
  open: (ref, options) => open(ref, options?.to ??
123
- (inPeek && defaultOpen === Destination.Page ? Destination.Peek : defaultOpen), options?.blur),
133
+ (inPeek && defaultOpen === Destination.Page ? Destination.Peek : defaultOpen), options),
124
134
  navigate: (to) => {
125
135
  if (target.surface === Surface.Panel)
126
136
  store.navigatePanel(target.panelId, to);
@@ -169,9 +179,10 @@ export function createApiFactory(store, { registry, defaultOpen = Destination.Pa
169
179
  setDirty: (dirty) => store.setDirty(me, resource, dirty),
170
180
  select: (refs) => store.apply((w) => model.select(w, me, refs)),
171
181
  pick: (ref, onPick, options) => {
172
- const to = options?.to ?? Destination.Window;
182
+ const asked = options?.to ?? Destination.Window;
183
+ const to = isPhone() ? model.chooserOnPhone(asked) : asked;
173
184
  if (to === Destination.Modal) {
174
- open(ref, to, options?.blur);
185
+ open(ref, to, options);
175
186
  choosers.set(model.modalId(model.hostOf(me)), onPick);
176
187
  return;
177
188
  }
@@ -180,7 +191,7 @@ export function createApiFactory(store, { registry, defaultOpen = Destination.Pa
180
191
  choosers.set(PEEK, onPick);
181
192
  return;
182
193
  }
183
- open(ref, to);
194
+ open(ref, to, options);
184
195
  const id = store.get().focus;
185
196
  if (id !== PAGE && id !== PEEK)
186
197
  choosers.set(id, onPick);
@@ -17,7 +17,7 @@ export type DropData = {
17
17
  export declare function useDraggablePanel(ref: RefObject<HTMLElement | null>, panelId: string, enabled?: boolean): boolean;
18
18
  export declare function useDropZone(ref: RefObject<HTMLElement | null>, zone: Dock): boolean;
19
19
  /** Makes an element drag a REFERENCE — a row, a chip — that a zone turns into a panel. */
20
- export declare function useDraggableRef(ref: RefObject<HTMLElement | null>, resource: ResourceRef): boolean;
20
+ export declare function useDraggableRef(ref: RefObject<HTMLElement | null>, resource: ResourceRef, enabled?: boolean): boolean;
21
21
  /** True while a panel or a reference is being dragged. Drop targets must only steal
22
22
  * pointer events then — otherwise they sit on top of “beside” / “floating”
23
23
  * and the buttons never fire. */
@@ -41,11 +41,11 @@ export function useDropZone(ref, zone) {
41
41
  return over;
42
42
  }
43
43
  /** Makes an element drag a REFERENCE — a row, a chip — that a zone turns into a panel. */
44
- export function useDraggableRef(ref, resource) {
44
+ export function useDraggableRef(ref, resource, enabled = true) {
45
45
  const [dragging, setDragging] = useState(false);
46
46
  useEffect(() => {
47
47
  const el = ref.current;
48
- if (el === null)
48
+ if (el === null || !enabled)
49
49
  return;
50
50
  return draggable({
51
51
  element: el,
@@ -56,7 +56,7 @@ export function useDraggableRef(ref, resource) {
56
56
  onDragStart: () => setDragging(true),
57
57
  onDrop: () => setDragging(false),
58
58
  });
59
- }, [ref, resource]);
59
+ }, [ref, resource, enabled]);
60
60
  return dragging;
61
61
  }
62
62
  /** True while a panel or a reference is being dragged. Drop targets must only steal
@@ -0,0 +1,41 @@
1
+ import { type Crumb, type ResourceRef, Surface, type WorkspaceApi } from "../domain/index.js";
2
+ /**
3
+ * An `api` for testing a view WITHOUT a workspace: it does nothing, and remembers every call. A
4
+ * view only talks to the workspace through its `api`, so what it asked for is what a test checks —
5
+ * «opened the payment as a modal», «named itself Acme» — with no store, no shell and no browser.
6
+ *
7
+ * const t = createTestApi(invoiceRef("F-1"));
8
+ * render(<Invoice resource={t.api.self} api={t.api} />);
9
+ * // … click «Register payment»
10
+ * expect(t.calls).toContainEqual({ method: "open", args: [paymentRef("F-1"), { to: "modal" }] });
11
+ *
12
+ * A chooser it was asked to open answers with `respond(value)`, the way its view would.
13
+ */
14
+ /** One call the view made: the method and its arguments, as given. */
15
+ export type ApiCall = {
16
+ [K in keyof WorkspaceApi]: WorkspaceApi[K] extends (...args: infer A) => unknown ? {
17
+ method: K;
18
+ args: A;
19
+ } : never;
20
+ }[keyof WorkspaceApi];
21
+ export type TestApiOptions = {
22
+ surface?: Surface;
23
+ /** What a modal was opened over (`api.over`). */
24
+ over?: ResourceRef | null;
25
+ /** What `useCrumbs(api)` / `api.crumbs()` give. */
26
+ crumbs?: readonly Crumb[];
27
+ /** What `api.context.selection()` gives. */
28
+ selection?: readonly ResourceRef[];
29
+ };
30
+ export type TestApi = {
31
+ api: WorkspaceApi;
32
+ /** Every call, in order. */
33
+ calls: ApiCall[];
34
+ /** The calls to one method, typed: `t.callsTo("open")[0]`. */
35
+ callsTo: <K extends ApiCall["method"]>(method: K) => Extract<ApiCall, {
36
+ method: K;
37
+ }>[];
38
+ /** Answers the last chooser opened with `pick`, as its view would. */
39
+ respond: (value: unknown) => void;
40
+ };
41
+ export declare function createTestApi(self: ResourceRef, options?: TestApiOptions): TestApi;