@sincpro/web-composer 1.3.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.
package/README.md CHANGED
@@ -108,6 +108,7 @@ api.context; // read what the user is on and what is selected — references onl
108
108
  api.pick(ref, onPick); // open a chooser (a many2one search); its view calls api.answer(ref)
109
109
  api.pick(ref, onPick, { to: "modal" }); // the chooser as a modal over the form
110
110
  api.pick(ref, onPick, { size: { w: 720, h: 520 } }); // a chooser window at that size (480×360 without it)
111
+ api.pick<boolean>(confirmRef, (ok) => ok && post(), { to: "modal" }); // any value, not only a ref
111
112
  ```
112
113
 
113
114
  A **modal** belongs to the surface it covers — the page, a window, a side panel or the peek —
@@ -139,6 +140,7 @@ The same gesture means the same thing on every screen:
139
140
  | A row of a list | click | **page**, with breadcrumb |
140
141
  | A record's name INSIDE the peek | click | a step **in the peek**; ← comes back |
141
142
  | The record's name in a column (`RecordLink`) | hover icons, Space, ⇧, ⌘ | **peek**, **side**, **window** |
143
+ | A record's name inside a card that drags (kanban) | `draggable={false}` | the card drags; the name only clicks |
142
144
  | A many2one field | open · search | **window** · a **modal** that **answers** |
143
145
  | A short task on a record (register a payment) | click | **modal** over that record |
144
146
  | A record's buttons that _lead_ (see its items) | click | **side** |
@@ -220,6 +222,42 @@ entries, journal items, bank reconciliation, a form with relations, an audit whe
220
222
  follows the selection, ⌘K, the keyboard, what happens when something fails, and your own
221
223
  design over the composer.
222
224
 
225
+ ### An agent in the browser (WebMCP)
226
+
227
+ [WebMCP](https://webmachinelearning.github.io/webmcp/) lets a page offer **tools** to the agent
228
+ built into the browser (`document.modelContext.registerTool`; a W3C Community Group draft, in
229
+ Chrome behind an origin trial). Everything is feature-detected: without it nothing happens.
230
+
231
+ ```tsx
232
+ <Composer workspace={workspace} registry={registry} agentTools />;
233
+ // workspace.where · workspace.open · workspace.search · workspace.act (the ⌘K actions)
234
+
235
+ // a view offers what ITS screen can do, alive while the view is:
236
+ useViewTool(api, {
237
+ name: "register_payment", // offered as register_payment.invoice-F-1: the record it acts on
238
+ description: "Open the form to register this invoice's payment",
239
+ execute: () => api.open(paymentRef(invoice.id), { to: "modal" }),
240
+ });
241
+ ```
242
+
243
+ The agent is one more person at the desk: it opens through the same `open`, a phone still turns
244
+ a window into the page, and throwing away what was typed still asks first.
245
+
246
+ ### Testing a view
247
+
248
+ A view talks to the workspace only through its `api`, so a test checks what it ASKED for — no
249
+ store, no shell, no browser:
250
+
251
+ ```ts
252
+ import { createTestApi } from "@sincpro/web-composer";
253
+
254
+ const t = createTestApi(invoiceRef("F-1")); // { surface, over, crumbs, selection } optional
255
+ render(<Invoice resource={t.api.self} api={t.api} />);
256
+ // … click «Register payment»
257
+ expect(t.callsTo("open")[0].args).toEqual([paymentRef("F-1"), { to: "modal" }]);
258
+ t.respond(true); // answers the last chooser it opened, as its view would
259
+ ```
260
+
223
261
  ## Your design over it
224
262
 
225
263
  ### Colors
@@ -97,11 +97,18 @@ export type WorkspaceApi = {
97
97
  selection: () => readonly ResourceRef[];
98
98
  subscribe: (listener: () => void) => () => void;
99
99
  };
100
- /** Open `ref` as a chooser: when its view calls `answer`, `onPick` receives the value and
101
- * the chooser closes. */
102
- pick: (ref: ResourceRef, onPick: (value: ResourceRef) => void, options?: PickOptions) => void;
103
- /** From a chooser: deliver the value to whoever asked, and close this surface. */
104
- answer: (value: ResourceRef) => void;
100
+ /**
101
+ * Open `ref` as a chooser: when its view calls `answer`, `onPick` receives the value and the
102
+ * chooser closes. The value is a reference by default — a many2one — but it can be anything
103
+ * the chooser's view answers: `true` for a confirmation, a date range, an amount. Closed
104
+ * without an answer, `onPick` is never called.
105
+ *
106
+ * api.pick<boolean>(confirmRef, (ok) => ok && post(), { to: Destination.Modal });
107
+ */
108
+ pick: <T = ResourceRef>(ref: ResourceRef, onPick: (value: T) => void, options?: PickOptions) => void;
109
+ /** From a chooser: deliver the value to whoever asked, and close this surface. Nobody asked
110
+ * (it was opened with `open`, not `pick`): nothing happens. */
111
+ answer: (value: unknown) => void;
105
112
  };
106
113
  /** Named `resource` rather than `ref` because `ref` is a reserved React prop. */
107
114
  export type ViewProps = {
package/dist/index.d.ts CHANGED
@@ -19,7 +19,9 @@ export { RecordLink, type RecordLinkProps } from "./shell/RecordLink.js";
19
19
  export { type ComposerSkin, type ConfirmProps, DEFAULT_ICONS, type ModalProps, type NoticeProps, type PeekProps, type SkinIcons, } from "./shell/skin.js";
20
20
  export { ComposerStyles } from "./shell/styles.js";
21
21
  export { ViewHost, type ViewHostProps } from "./shell/ViewHost.js";
22
+ export { agentAvailable, type AgentTool, type AgentToolAnnotations, registerAgentTool, registerAgentTools, toolName, useViewTool, workspaceTools, type WorkspaceToolsOptions, } from "./state/agent.js";
22
23
  export { type ApiFactory, createApiFactory, type Target, targetOf, } from "./state/api.js";
23
24
  export { type ConfirmDiscard, createWorkspaceStore, type StoreOptions, type WorkspaceStore, } from "./state/store.js";
25
+ export { type ApiCall, createTestApi, type TestApi, type TestApiOptions, } from "./state/testing.js";
24
26
  export { useKeyboard, type UseKeyboardOptions, } from "./state/useKeyboard.js";
25
27
  export { useCrumbs, useWorkspace, useWorkspaceContext, useWorkspaceSlice, useWorkspaceState, } from "./state/useWorkspace.js";
package/dist/index.js CHANGED
@@ -18,7 +18,9 @@ export { RecordLink } from "./shell/RecordLink.js";
18
18
  export { DEFAULT_ICONS, } from "./shell/skin.js";
19
19
  export { ComposerStyles } from "./shell/styles.js";
20
20
  export { ViewHost } from "./shell/ViewHost.js";
21
+ export { agentAvailable, registerAgentTool, registerAgentTools, toolName, useViewTool, workspaceTools, } from "./state/agent.js";
21
22
  export { createApiFactory, targetOf, } from "./state/api.js";
22
23
  export { createWorkspaceStore, } from "./state/store.js";
24
+ export { createTestApi, } from "./state/testing.js";
23
25
  export { useKeyboard, } from "./state/useKeyboard.js";
24
26
  export { useCrumbs, useWorkspace, useWorkspaceContext, useWorkspaceSlice, useWorkspaceState, } from "./state/useWorkspace.js";
@@ -22,5 +22,8 @@ export type ComposerProps = {
22
22
  /** Below this width (px) of the WORKSPACE it behaves as a phone: one screen, windows and side
23
23
  * panels open as the page, choosers as a sheet (`domain/phone.ts`). `0` never does. */
24
24
  phoneBelow?: number;
25
+ /** Offer the workspace to the browser's agent (WebMCP): where am I, open, search, act. Off by
26
+ * default; without WebMCP in the browser it does nothing. One workspace per page should. */
27
+ agentTools?: boolean;
25
28
  };
26
- export declare function Composer({ workspace, registry, empty, keyboard, defaultOpen, palette: paletteProp, onPaletteChange, skin: skinProp, phoneBelow, }: ComposerProps): import("react").JSX.Element;
29
+ export declare function Composer({ workspace, registry, empty, keyboard, defaultOpen, palette: paletteProp, onPaletteChange, skin: skinProp, phoneBelow, agentTools, }: ComposerProps): import("react").JSX.Element;
@@ -8,6 +8,7 @@ import { ChromeButton, ConfirmDialog, PeekDrawer } from "./Peek.js";
8
8
  import { resolveSkin, SkinProvider, } from "./skin.js";
9
9
  import { ComposerStyles } from "./styles.js";
10
10
  import { ViewHost } from "./ViewHost.js";
11
+ import { registerAgentTools, workspaceTools } from "../state/agent.js";
11
12
  import { createApiFactory, targetOf } from "../state/api.js";
12
13
  import { useDropMonitor } from "../state/drag.js";
13
14
  import { useKeyboard } from "../state/useKeyboard.js";
@@ -60,7 +61,7 @@ function PhoneDock({ panels, titleOf, onBring, }) {
60
61
  const copy = composerCopy().phone;
61
62
  return (_jsxs("nav", { "aria-label": copy.alsoOpen, className: "sc-dock", children: [_jsx("span", { className: "sc-dock-label", children: copy.alsoOpen }), panels.map((p) => (_jsx(ChromeButton, { onClick: () => onBring(p.id), children: titleOf(p.view) }, p.id)))] }));
62
63
  }
63
- export function Composer({ workspace, registry, empty, keyboard = true, defaultOpen = Destination.Page, palette: paletteProp, onPaletteChange, skin: skinProp, phoneBelow = PHONE_WIDTH, }) {
64
+ export function Composer({ workspace, registry, empty, keyboard = true, defaultOpen = Destination.Page, palette: paletteProp, onPaletteChange, skin: skinProp, phoneBelow = PHONE_WIDTH, agentTools = false, }) {
64
65
  const skin = useMemo(() => resolveSkin(skinProp), [skinProp]);
65
66
  const Drawer = skin.Peek ?? PeekDrawer;
66
67
  const Confirm = skin.Confirm ?? ConfirmDialog;
@@ -119,6 +120,22 @@ export function Composer({ workspace, registry, empty, keyboard = true, defaultO
119
120
  return;
120
121
  action.run(api.for(ref, targetOf(w.focus)));
121
122
  }
123
+ /* The tools call the latest `open` and `run`, which close over the current phone state. */
124
+ const latest = useRef({ open, run });
125
+ useLayoutEffect(() => {
126
+ latest.current = { open, run };
127
+ });
128
+ useEffect(() => {
129
+ if (!agentTools)
130
+ return;
131
+ return registerAgentTools(workspaceTools({
132
+ store: workspace,
133
+ registry,
134
+ titleOf: api.titleOf,
135
+ open: (ref, to) => latest.current.open(ref, to),
136
+ run: (action) => latest.current.run(action),
137
+ }));
138
+ }, [agentTools, workspace, registry, api]);
122
139
  const peeked = state.peek;
123
140
  const peekModal = modalOver(state, PEEK);
124
141
  const peekSpec = peeked === null ? null : registry.resolve(peeked);
@@ -63,7 +63,11 @@ export function ModalWindow({ title, blur, size, phone, onClose, children }) {
63
63
  return (_jsx("div", { className: "sc-modal-scrim", ...(blur ? { "data-blur": "" } : {}), ...(phone ? { "data-phone": "" } : {}), children: _jsxs("section", { ref: box, role: "dialog", tabIndex: -1, "aria-labelledby": titleId, className: "sc-modal", style: phone
64
64
  ? undefined
65
65
  : {
66
- transform: `translate(${offset.x}px, ${offset.y}px)`,
66
+ /* `left`/`top` and not `transform`: a transform makes the modal the box every
67
+ `position: fixed` inside it is placed against — the card a calendar or a kanban
68
+ drags would be drawn off its pointer. */
69
+ left: offset.x,
70
+ top: offset.y,
67
71
  ...(size === undefined ? {} : { width: size.w, height: size.h }),
68
72
  }, onKeyDown: (e) => {
69
73
  if (e.key !== "Escape" || e.defaultPrevented)
@@ -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) {
@@ -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-width: 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
  }
@@ -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
+ }
@@ -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;
@@ -0,0 +1,45 @@
1
+ import { Surface, } from "../domain/index.js";
2
+ const NO_CRUMBS = [];
3
+ const NO_REFS = [];
4
+ export function createTestApi(self, options = {}) {
5
+ const calls = [];
6
+ const pending = [];
7
+ const crumbs = options.crumbs ?? NO_CRUMBS;
8
+ const selection = options.selection ?? NO_REFS;
9
+ const record = (method) => (...args) => {
10
+ calls.push({ method, args });
11
+ };
12
+ const api = {
13
+ self,
14
+ surface: options.surface ?? Surface.Page,
15
+ over: options.over ?? null,
16
+ context: {
17
+ focused: () => self,
18
+ selection: () => selection,
19
+ subscribe: () => () => undefined,
20
+ },
21
+ open: record("open"),
22
+ navigate: record("navigate"),
23
+ replace: record("replace"),
24
+ setParams: record("setParams"),
25
+ back: record("back"),
26
+ expand: record("expand"),
27
+ close: record("close"),
28
+ focus: record("focus"),
29
+ crumbs: () => crumbs,
30
+ setTitle: record("setTitle"),
31
+ setDirty: record("setDirty"),
32
+ select: record("select"),
33
+ pick: (ref, onPick, pickOptions) => {
34
+ calls.push({ method: "pick", args: [ref, onPick, pickOptions] });
35
+ pending.push(onPick);
36
+ },
37
+ answer: record("answer"),
38
+ };
39
+ return {
40
+ api,
41
+ calls,
42
+ callsTo: (method) => calls.filter((c) => c.method === method),
43
+ respond: (value) => pending.pop()?.(value),
44
+ };
45
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sincpro/web-composer",
3
- "version": "1.3.0",
3
+ "version": "1.4.0",
4
4
  "description": "The Sincpro workspace for React: one page with its breadcrumb, a peek, side panels and windows, and ⌘K — all over references, never data.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",