@sincpro/web-composer 1.5.0 → 1.7.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
@@ -98,6 +98,7 @@ api.over; // in a modal: the record it was opened over — its context (null els
98
98
  api.replace(ref); // show it HERE without a step back: the record a form just created
99
99
  api.setParams({ tenant }); // a filter that lives in the reference: survives reload and links
100
100
  useCrumbs(api); // the breadcrumb, ready for List.Crumbs / Record.Crumbs — follows setTitle
101
+ usePhone(api); // one screen right now: what a view OFFERS — no «open beside» on a phone
101
102
  api.back(); // one step back: the page's breadcrumb, or the peek's own trail
102
103
  api.close(); // leave: closes the panel, the peek or the modal; on the page, goes back
103
104
  api.expand(); // a window, a side panel or the peek grows into the page
@@ -135,9 +136,17 @@ so the form that asked stays to receive the answer; the peek is the screen's wid
135
136
  were already open wait in «Also open», mounted, and one tap brings each to the page. Widen it and
136
137
  the desk is back as it was.
137
138
 
139
+ A view that wants to know — to offer nothing that opens beside — asks `usePhone(api)`. How it is
140
+ **drawn** at a width is its CSS: every view sits in a container named `sc-view` (the page, a panel,
141
+ the peek, a modal), so `@container sc-view (width < 640px)` answers a narrow side panel on a
142
+ desktop too, which a phone check would not.
143
+
138
144
  From the app, around the workspace: `workspace.start(ref)` starts over from a menu (no
139
- breadcrumb behind, no peek, the panels stay), and `useWorkspace({ hash: true })` puts the
140
- workspace in the URL with the browser's Back working. Unsaved changes are asked with the
145
+ breadcrumb behind, no peek, the panels stay), and `useSection(workspace, entries)` says which
146
+ entry of that menu the person is under, to mark it — still the same entry a record and its lines
147
+ deeper. The menu itself is the app's: its groups, its icons, who may see what.
148
+ `useWorkspace({ hash: true })` puts the workspace in the URL with the browser's Back working, and
149
+ a reload keeps the breadcrumb and the names views gave. Unsaved changes are asked with the
141
150
  composer's own dialog; `useWorkspace({ confirmDiscard })` replaces it.
142
151
 
143
152
  ## Where each behaviour lives
@@ -252,6 +261,26 @@ useViewTool(api, {
252
261
  The agent is one more person at the desk: it opens through the same `open`, a phone still turns
253
262
  a window into the page, and throwing away what was typed still asks first.
254
263
 
264
+ ### When a view breaks
265
+
266
+ Each view draws inside its own boundary: a view that throws while drawing shows a notice in its
267
+ panel and the rest of the workspace goes on. `onViewError` tells the application, once per
268
+ failure, with the reference the view was opened with — hand it to the error reporter the use
269
+ cases report to:
270
+
271
+ ```tsx
272
+ <Composer
273
+ workspace={workspace}
274
+ registry={registry}
275
+ // @sincpro/client-framework's reportError, or the application's own reporter
276
+ onViewError={(error, { resource }) => reportError(error, `view ${formatRef(resource)}`)}
277
+ />
278
+ ```
279
+
280
+ A host drawn outside `Composer` (`PanelHost`, `ViewHost`) reads the same handler from
281
+ `ViewErrorProvider`. A handler that throws is ignored: telling about a failure never becomes a
282
+ second one.
283
+
255
284
  ### Testing a view
256
285
 
257
286
  A view talks to the workspace only through its `api`, so a test checks what it ASKED for — no
@@ -260,7 +289,7 @@ store, no shell, no browser:
260
289
  ```ts
261
290
  import { createTestApi } from "@sincpro/web-composer";
262
291
 
263
- const t = createTestApi(invoiceRef("F-1")); // { surface, over, crumbs, selection, choosing } optional
292
+ const t = createTestApi(invoiceRef("F-1")); // { surface, over, crumbs, selection, choosing, phone } optional
264
293
  render(<Invoice resource={t.api.self} api={t.api} />);
265
294
  // … click «Register payment»
266
295
  expect(t.callsTo("open")[0].args).toEqual([paymentRef("F-1"), { to: "modal" }]);
@@ -1,10 +1,10 @@
1
1
  /** The model: no React, no CSS. Tested in Node; survives any change of skin. */
2
2
  export type { Dock } from "./enums.js";
3
3
  export { Axis, Destination, DOCKS, DragKind, HandleKind, Surface, Zone, } from "./enums.js";
4
- export { type Box, type Handle, handles, KEYBOARD_STEP, layout, type Length, phoneLayout, resolve, sizeAt, type Slot, stableOrder, STRIP, ZONE_LIMITS, } from "./layout.js";
4
+ export { type Box, type Handle, handles, KEYBOARD_STEP, layout, type Length, phoneLayout, resolve, sizeAt, type Slot, stableOrder, STRIP, } from "./layout.js";
5
5
  export { localEntries, matches, MIN_QUERY, type PaletteEntry, PaletteSection, searchEntries, } from "./palette.js";
6
6
  export { chooserOnPhone, destinationOnPhone, PHONE_WIDTH, } from "./phone.js";
7
7
  export { type Action, type Choosing, createRegistry, type Crumb, loadView, type OpenOptions, type PickOptions, type Registry, type SearchHit, type ViewProps, type ViewSpec, type WorkspaceApi, } from "./registry.js";
8
- export { formatRef, isRef, parseRef, type ResourceRef, rootRef, sameRef, withParams, } from "./resource.js";
8
+ export { formatRef, parseRef, type ResourceRef, rootRef, sameRef, withParams, } from "./resource.js";
9
9
  export { fromHash, restore, type SessionMemory, toHash, } from "./url.js";
10
- export { back, closeModal, closePanel, closePeek, collapsePanel, cycleFocus, DEFAULT_ZONES, drillPeek, EMPTY, expandPanel, findPanel, floatPanel, focusedRef, focusPanel, goTo, hostOf, MAX_ZONE, maximize, MIN_SHARE, MIN_WINDOW, MIN_ZONE, MODAL, type Modal, modalId, modalOver, movePanel, nameOf, nameRef, navigatePanel, openModal, type OpenModalOptions, openPanel, type OpenPanelOptions, PAGE, type Panel, panelsIn, PEEK, peek, peekBack, peekGoTo, peekToPage, peekToSide, type Placement, push, raisePanel, refOn, replace, replacePeek, resizePanel, resizeZone, select, type Selected, selectionOf, settleModals, type Size, start, type WindowBox, type Workspace, type Zones, } from "./workspace.js";
10
+ export { back, closeModal, closePanel, closePeek, collapsePanel, cycleFocus, DEFAULT_ZONES, drillPeek, EMPTY, expandPanel, findPanel, floatPanel, focusedRef, focusPanel, goTo, hostOf, MAX_ZONE, maximize, MIN_SHARE, MIN_WINDOW, MIN_ZONE, MODAL, type Modal, modalId, modalOver, movePanel, nameOf, nameRef, navigatePanel, openModal, type OpenModalOptions, openPanel, type OpenPanelOptions, PAGE, type Panel, panelsIn, PEEK, peek, peekBack, peekGoTo, peekToPage, peekToSide, type Placement, push, raisePanel, refOn, replace, replacePeek, resizePanel, resizeZone, sectionOf, select, type Selected, selectionOf, settleModals, type Size, start, type WindowBox, type Workspace, type Zones, } from "./workspace.js";
@@ -1,9 +1,9 @@
1
1
  /** The model: no React, no CSS. Tested in Node; survives any change of skin. */
2
2
  export { Axis, Destination, DOCKS, DragKind, HandleKind, Surface, Zone, } from "./enums.js";
3
- export { handles, KEYBOARD_STEP, layout, phoneLayout, resolve, sizeAt, stableOrder, STRIP, ZONE_LIMITS, } from "./layout.js";
3
+ export { handles, KEYBOARD_STEP, layout, phoneLayout, resolve, sizeAt, stableOrder, STRIP, } from "./layout.js";
4
4
  export { localEntries, matches, MIN_QUERY, PaletteSection, searchEntries, } from "./palette.js";
5
5
  export { chooserOnPhone, destinationOnPhone, PHONE_WIDTH, } from "./phone.js";
6
6
  export { createRegistry, loadView, } from "./registry.js";
7
- export { formatRef, isRef, parseRef, rootRef, sameRef, withParams, } from "./resource.js";
7
+ export { formatRef, parseRef, rootRef, sameRef, withParams, } from "./resource.js";
8
8
  export { fromHash, restore, toHash, } from "./url.js";
9
- export { back, closeModal, closePanel, closePeek, collapsePanel, cycleFocus, DEFAULT_ZONES, drillPeek, EMPTY, expandPanel, findPanel, floatPanel, focusedRef, focusPanel, goTo, hostOf, MAX_ZONE, maximize, MIN_SHARE, MIN_WINDOW, MIN_ZONE, MODAL, modalId, modalOver, movePanel, nameOf, nameRef, navigatePanel, openModal, openPanel, PAGE, panelsIn, PEEK, peek, peekBack, peekGoTo, peekToPage, peekToSide, push, raisePanel, refOn, replace, replacePeek, resizePanel, resizeZone, select, selectionOf, settleModals, start, } from "./workspace.js";
9
+ export { back, closeModal, closePanel, closePeek, collapsePanel, cycleFocus, DEFAULT_ZONES, drillPeek, EMPTY, expandPanel, findPanel, floatPanel, focusedRef, focusPanel, goTo, hostOf, MAX_ZONE, maximize, MIN_SHARE, MIN_WINDOW, MIN_ZONE, MODAL, modalId, modalOver, movePanel, nameOf, nameRef, navigatePanel, openModal, openPanel, PAGE, panelsIn, PEEK, peek, peekBack, peekGoTo, peekToPage, peekToSide, push, raisePanel, refOn, replace, replacePeek, resizePanel, resizeZone, sectionOf, select, selectionOf, settleModals, start, } from "./workspace.js";
@@ -88,8 +88,4 @@ export declare function handles(w: Workspace): readonly Handle[];
88
88
  /** How far an arrow key moves a handle. A mouse-only handle leaves the workspace
89
89
  * half-assembled for anyone who does not use a pointer. */
90
90
  export declare const KEYBOARD_STEP = 0.02;
91
- export declare const ZONE_LIMITS: {
92
- min: number;
93
- max: number;
94
- };
95
91
  export {};
@@ -1,5 +1,5 @@
1
1
  import { Axis, HandleKind, Zone } from "./enums.js";
2
- import { MAX_ZONE, MIN_ZONE, PAGE, panelsIn, } from "./workspace.js";
2
+ import { PAGE, panelsIn, } from "./workspace.js";
3
3
  const len = (fr, px = 0) => ({ fr, px });
4
4
  const plus = (a, b) => len(a.fr + b.fr, a.px + b.px);
5
5
  const times = (a, k) => len(a.fr * k, a.px * k);
@@ -220,4 +220,3 @@ export function handles(w) {
220
220
  /** How far an arrow key moves a handle. A mouse-only handle leaves the workspace
221
221
  * half-assembled for anyone who does not use a pointer. */
222
222
  export const KEYBOARD_STEP = 0.02;
223
- export const ZONE_LIMITS = { min: MIN_ZONE, max: MAX_ZONE };
@@ -107,6 +107,17 @@ export type WorkspaceApi = {
107
107
  selection: () => readonly ResourceRef[];
108
108
  subscribe: (listener: () => void) => () => void;
109
109
  };
110
+ /**
111
+ * How the workspace is laid out now, read at call time — a view follows it with
112
+ * `usePhone(api)`. It decides what a view OFFERS: on a phone a window or a side panel opens as
113
+ * the page, so «open beside» is not worth a button. How a view is DRAWN at a width is the CSS's
114
+ * (`@container sc-view (width < 640px)`): a side panel is narrow on a desktop too.
115
+ */
116
+ layout: {
117
+ /** One screen: the workspace is narrower than `<Composer phoneBelow>`. */
118
+ phone: () => boolean;
119
+ subscribe: (listener: () => void) => () => void;
120
+ };
110
121
  /**
111
122
  * Open `ref` as a chooser: when its view calls `answer`, `onPick` receives the value and the
112
123
  * chooser closes. The value is a reference by default — a many2one — but it can be anything
@@ -10,7 +10,6 @@ export type ResourceRef = {
10
10
  id?: string;
11
11
  params?: Readonly<Record<string, string>>;
12
12
  };
13
- export declare function isRef(value: unknown): value is ResourceRef;
14
13
  /** Params are sorted so that two equivalent refs produce the same text and `sameRef` works. */
15
14
  export declare function formatRef(ref: ResourceRef): string;
16
15
  export declare function parseRef(text: string): ResourceRef | null;
@@ -9,15 +9,6 @@ function parseParams(query) {
9
9
  }
10
10
  return params;
11
11
  }
12
- export function isRef(value) {
13
- if (typeof value !== "object" || value === null)
14
- return false;
15
- const ref = value;
16
- return (typeof ref.domain === "string" &&
17
- SEGMENT.test(ref.domain) &&
18
- typeof ref.kind === "string" &&
19
- SEGMENT.test(ref.kind));
20
- }
21
12
  /** Params are sorted so that two equivalent refs produce the same text and `sameRef` works. */
22
13
  export function formatRef(ref) {
23
14
  const id = ref.id ? `/${encodeURIComponent(ref.id)}` : "";
@@ -2,15 +2,18 @@ import { type ResourceRef } from "./resource.js";
2
2
  import { type Workspace } from "./workspace.js";
3
3
  export declare function toHash(w: Workspace): string;
4
4
  export declare function fromHash(hash: string): Workspace;
5
- /** What the URL does not carry, written into each browser history entry. */
5
+ /** What the URL does not carry, written into each browser history entry — which a reload keeps. */
6
6
  export type SessionMemory = {
7
7
  trail: readonly ResourceRef[];
8
8
  peekTrail: readonly ResourceRef[];
9
+ /** The names views gave. Optional: an entry written before they rode along has none. */
10
+ titles?: Readonly<Record<string, string>>;
9
11
  };
10
12
  /**
11
13
  * The browser moved through its history: the URL says WHERE, the session says how I got there.
12
14
  * With the entry's own memory the trails are exact; without it they are reconciled. The
13
- * selection survives only while its surface still shows the same resource, and the names views
14
- * gave stay. So does a modal, while what it covers is still there.
15
+ * selection survives only while its surface still shows the same resource. The names views gave
16
+ * stay, and the entry's own fill in the ones forgotten since: a crumb whose view is not mounted
17
+ * reads its name, not its id. A modal stays while what it covers is still there.
15
18
  */
16
19
  export declare function restore(now: Workspace, url: Workspace, memory: SessionMemory | null): Workspace;
@@ -125,8 +125,9 @@ function trailTo(now, page) {
125
125
  /**
126
126
  * The browser moved through its history: the URL says WHERE, the session says how I got there.
127
127
  * With the entry's own memory the trails are exact; without it they are reconciled. The
128
- * selection survives only while its surface still shows the same resource, and the names views
129
- * gave stay. So does a modal, while what it covers is still there.
128
+ * selection survives only while its surface still shows the same resource. The names views gave
129
+ * stay, and the entry's own fill in the ones forgotten since: a crumb whose view is not mounted
130
+ * reads its name, not its id. A modal stays while what it covers is still there.
130
131
  */
131
132
  export function restore(now, url, memory) {
132
133
  const peekTrail = url.peek === null
@@ -142,7 +143,7 @@ export function restore(now, url, memory) {
142
143
  trail: url.page === null ? [] : (memory?.trail ?? trailTo(now, url.page)),
143
144
  peekTrail,
144
145
  selected: keeps ? now.selected : null,
145
- titles: now.titles,
146
+ titles: { ...memory?.titles, ...now.titles },
146
147
  modals: now.modals,
147
148
  });
148
149
  }
@@ -221,6 +221,14 @@ export declare function settleModals(w: Workspace): Workspace;
221
221
  export declare function select(w: Workspace, by: string, refs: readonly ResourceRef[]): Workspace;
222
222
  /** What the user is working on: the page, the peek or the panel that has the focus. */
223
223
  export declare function focusedRef(w: Workspace): ResourceRef | null;
224
+ /**
225
+ * Which of `sections` — the entries of the app's menu — the person is under: the first step of
226
+ * the way to the page that one of them names. A menu `start`s its entry, so the entry stays
227
+ * marked while the person goes deeper — a record, its lines, another record. The same entry with
228
+ * other `params` is still it (a filter changed); when several share it, the first in order wins.
229
+ * `null` when no step is one of them: a link straight to a record.
230
+ */
231
+ export declare function sectionOf<T extends ResourceRef>(w: Workspace, sections: readonly T[]): T | null;
224
232
  /**
225
233
  * The name a view gives its resource once it has loaded it — «Acme S.R.L.» instead of
226
234
  * `acme`. `null` gives the `ViewSpec` title back. Names of what is no longer reachable are
@@ -440,6 +440,25 @@ export function select(w, by, refs) {
440
440
  export function focusedRef(w) {
441
441
  return refOn(w, w.focus) ?? w.page;
442
442
  }
443
+ /**
444
+ * Which of `sections` — the entries of the app's menu — the person is under: the first step of
445
+ * the way to the page that one of them names. A menu `start`s its entry, so the entry stays
446
+ * marked while the person goes deeper — a record, its lines, another record. The same entry with
447
+ * other `params` is still it (a filter changed); when several share it, the first in order wins.
448
+ * `null` when no step is one of them: a link straight to a record.
449
+ */
450
+ export function sectionOf(w, sections) {
451
+ if (w.page === null)
452
+ return null;
453
+ for (const step of [...w.trail, w.page]) {
454
+ const root = rootRef(step);
455
+ const named = sections.find((s) => sameRef(s, step)) ??
456
+ sections.find((s) => sameRef(rootRef(s), root));
457
+ if (named !== undefined)
458
+ return named;
459
+ }
460
+ return null;
461
+ }
443
462
  /** Every resource the workspace shows or can go back to. */
444
463
  const reachable = (w) => [
445
464
  ...w.trail,
package/dist/index.d.ts CHANGED
@@ -7,7 +7,7 @@
7
7
  * does not force a two-place import.
8
8
  */
9
9
  export type { Action, Choosing, Crumb, OpenOptions, PaletteEntry, PickOptions, Registry, ResourceRef, SearchHit, ViewProps, ViewSpec, Workspace, WorkspaceApi, } from "./domain/index.js";
10
- export { Destination, focusedRef, PAGE, PaletteSection, PEEK, selectionOf, Surface, Zone, } from "./domain/index.js";
10
+ export { Destination, focusedRef, PAGE, PaletteSection, PEEK, sectionOf, selectionOf, Surface, Zone, } from "./domain/index.js";
11
11
  export { Composer, type ComposerProps } from "./shell/Composer.js";
12
12
  export { type ComposerCopy, composerCopy, ENGLISH_COMPOSER_COPY, installComposerCopy, SPANISH_COMPOSER_COPY, } from "./shell/copy.js";
13
13
  export { type IconProps } from "./shell/icons.js";
@@ -18,10 +18,10 @@ export { PanelHost, type PanelHostProps } from "./shell/PanelHost.js";
18
18
  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
- 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";
21
+ export { type OnViewError, type ViewErrorAbout, ViewErrorProvider, ViewHost, type ViewHostProps, } from "./shell/ViewHost.js";
22
+ export { type AgentTool, type AgentToolAnnotations, registerAgentTool, registerAgentTools, toolName, useViewTool, workspaceTools, type WorkspaceToolsOptions, } from "./state/agent.js";
23
23
  export { type ApiFactory, createApiFactory, type Target, targetOf, } from "./state/api.js";
24
24
  export { type ConfirmDiscard, createWorkspaceStore, type StoreOptions, type WorkspaceStore, } from "./state/store.js";
25
25
  export { type ApiCall, createTestApi, type TestApi, type TestApiOptions, } from "./state/testing.js";
26
26
  export { useKeyboard, type UseKeyboardOptions, } from "./state/useKeyboard.js";
27
- export { useCrumbs, useWorkspace, useWorkspaceContext, useWorkspaceSlice, useWorkspaceState, } from "./state/useWorkspace.js";
27
+ export { useCrumbs, usePhone, useSection, useWorkspace, useWorkspaceContext, useWorkspaceState, } from "./state/useWorkspace.js";
package/dist/index.js CHANGED
@@ -6,7 +6,7 @@
6
6
  * Only the model TYPES that appear in these signatures are re-exported, so declaring a domain
7
7
  * does not force a two-place import.
8
8
  */
9
- export { Destination, focusedRef, PAGE, PaletteSection, PEEK, selectionOf, Surface, Zone, } from "./domain/index.js";
9
+ export { Destination, focusedRef, PAGE, PaletteSection, PEEK, sectionOf, selectionOf, Surface, Zone, } from "./domain/index.js";
10
10
  export { Composer } from "./shell/Composer.js";
11
11
  export { composerCopy, ENGLISH_COMPOSER_COPY, installComposerCopy, SPANISH_COMPOSER_COPY, } from "./shell/copy.js";
12
12
  export {} from "./shell/icons.js";
@@ -17,10 +17,10 @@ export { PanelHost } from "./shell/PanelHost.js";
17
17
  export { RecordLink } from "./shell/RecordLink.js";
18
18
  export { DEFAULT_ICONS, } from "./shell/skin.js";
19
19
  export { ComposerStyles } from "./shell/styles.js";
20
- export { ViewHost } from "./shell/ViewHost.js";
21
- export { agentAvailable, registerAgentTool, registerAgentTools, toolName, useViewTool, workspaceTools, } from "./state/agent.js";
20
+ export { ViewErrorProvider, ViewHost, } from "./shell/ViewHost.js";
21
+ export { registerAgentTool, registerAgentTools, toolName, useViewTool, workspaceTools, } from "./state/agent.js";
22
22
  export { createApiFactory, targetOf, } from "./state/api.js";
23
23
  export { createWorkspaceStore, } from "./state/store.js";
24
24
  export { createTestApi, } from "./state/testing.js";
25
25
  export { useKeyboard, } from "./state/useKeyboard.js";
26
- export { useCrumbs, useWorkspace, useWorkspaceContext, useWorkspaceSlice, useWorkspaceState, } from "./state/useWorkspace.js";
26
+ export { useCrumbs, usePhone, useSection, useWorkspace, useWorkspaceContext, useWorkspaceState, } from "./state/useWorkspace.js";
@@ -1,5 +1,6 @@
1
1
  import { Destination, type Registry } from "../domain/index.js";
2
2
  import { type ComposerSkin } from "./skin.js";
3
+ import { type OnViewError } from "./ViewHost.js";
3
4
  import type { WorkspaceStore } from "../state/store.js";
4
5
  import { type ReactNode } from "react";
5
6
  export type ComposerProps = {
@@ -25,5 +26,8 @@ export type ComposerProps = {
25
26
  /** Offer the workspace to the browser's agent (WebMCP): where am I, open, search, act. Off by
26
27
  * default; without WebMCP in the browser it does nothing. One workspace per page should. */
27
28
  agentTools?: boolean;
29
+ /** Told when a view breaks while drawing — hand it to the app's error reporter. Its panel
30
+ * shows a notice and the rest of the workspace goes on either way. */
31
+ onViewError?: OnViewError;
28
32
  };
29
- export declare function Composer({ workspace, registry, empty, keyboard, defaultOpen, palette: paletteProp, onPaletteChange, skin: skinProp, phoneBelow, agentTools, }: ComposerProps): import("react").JSX.Element;
33
+ export declare function Composer({ workspace, registry, empty, keyboard, defaultOpen, palette: paletteProp, onPaletteChange, skin: skinProp, phoneBelow, agentTools, onViewError, }: ComposerProps): import("react").JSX.Element;
@@ -7,7 +7,7 @@ import { PanelHost } from "./PanelHost.js";
7
7
  import { ChromeButton, ConfirmDialog, PeekDrawer } from "./Peek.js";
8
8
  import { resolveSkin, SkinProvider, } from "./skin.js";
9
9
  import { ComposerStyles } from "./styles.js";
10
- import { ViewHost } from "./ViewHost.js";
10
+ import { ViewErrorProvider, ViewHost, } from "./ViewHost.js";
11
11
  import { registerAgentTools, workspaceTools } from "../state/agent.js";
12
12
  import { createApiFactory, targetOf } from "../state/api.js";
13
13
  import { useDropMonitor } from "../state/drag.js";
@@ -37,7 +37,7 @@ function useDiscardDialog(workspace, titleOf) {
37
37
  * frame and swapped it, and a click in that frame landed on a panel that was going away. A
38
38
  * workspace with no width yet (hidden, or not laid out) is not a phone.
39
39
  */
40
- function usePhone(root, below) {
40
+ function useMeasuredPhone(root, below) {
41
41
  const [phone, setPhone] = useState(false);
42
42
  useLayoutEffect(() => {
43
43
  const el = root.current;
@@ -61,7 +61,7 @@ function PhoneDock({ panels, titleOf, onBring, }) {
61
61
  const copy = composerCopy().phone;
62
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)))] }));
63
63
  }
64
- export function Composer({ workspace, registry, empty, keyboard = true, defaultOpen = Destination.Page, palette: paletteProp, onPaletteChange, skin: skinProp, phoneBelow = PHONE_WIDTH, agentTools = false, }) {
64
+ export function Composer({ workspace, registry, empty, keyboard = true, defaultOpen = Destination.Page, palette: paletteProp, onPaletteChange, skin: skinProp, phoneBelow = PHONE_WIDTH, agentTools = false, onViewError, }) {
65
65
  const skin = useMemo(() => resolveSkin(skinProp), [skinProp]);
66
66
  const Drawer = skin.Peek ?? PeekDrawer;
67
67
  const Confirm = skin.Confirm ?? ConfirmDialog;
@@ -74,18 +74,12 @@ export function Composer({ workspace, registry, empty, keyboard = true, defaultO
74
74
  onPaletteChange?.(open);
75
75
  }, [onPaletteChange]);
76
76
  const root = useRef(null);
77
- const phone = usePhone(root, phoneBelow);
78
- /* The API reads it at call time: a view's API is not rebuilt when the window is resized. */
79
- const phoneNow = useRef(phone);
80
- useLayoutEffect(() => {
81
- phoneNow.current = phone;
82
- }, [phone]);
83
- const api = useMemo(() => createApiFactory(workspace, {
84
- registry,
85
- defaultOpen,
86
- isPhone: () => phoneNow.current,
87
- }), [workspace, registry, defaultOpen]);
77
+ const phone = useMeasuredPhone(root, phoneBelow);
78
+ const api = useMemo(() => createApiFactory(workspace, { registry, defaultOpen }), [workspace, registry, defaultOpen]);
88
79
  useEffect(() => api.dispose, [api]);
80
+ /* Before paint, like the measure: a view's API is not rebuilt when the window is resized —
81
+ `api.layout` follows it, and so does what `open` does. */
82
+ useLayoutEffect(() => api.setPhone(phone), [api, phone]);
89
83
  useKeyboard({
90
84
  workspace,
91
85
  enabled: keyboard,
@@ -140,5 +134,6 @@ export function Composer({ workspace, registry, empty, keyboard = true, defaultO
140
134
  const peekModal = modalOver(state, PEEK);
141
135
  const peekSpec = peeked === null ? null : registry.resolve(peeked);
142
136
  const cameFrom = state.peekTrail.at(-1);
143
- return (_jsx(SkinProvider, { value: skin, children: _jsxs("div", { ref: root, className: "sc-root", ...(phone ? { "data-phone": "" } : {}), children: [skin.styles ? _jsx(ComposerStyles, {}) : null, state.page === null ? (_jsx("div", { className: "sc-empty", children: empty })) : (_jsx(PanelHost, { workspace: state, registry: registry, store: workspace, api: api, phone: phone, overlay: peeked === null ? null : (_jsxs(_Fragment, { children: [_jsx("div", { style: { display: "contents" }, inert: peekModal !== null, onPointerDownCapture: () => workspace.focusPanel(PEEK), children: _jsx(Drawer, { title: api.titleOf(peeked), onClose: workspace.closePeek, actions: _jsxs(_Fragment, { children: [phone ? null : (_jsx(ChromeButton, { onClick: () => workspace.peekToSide(peekSpec?.preferredZone ?? Zone.Right), children: copy.peek.openAsPanel })), cameFrom === undefined ? null : (_jsx(ChromeButton, { role: "ghost", icon: skin.icons.back, onClick: workspace.peekBack, children: copy.peek.back(api.titleOf(cameFrom)) })), _jsx(ChromeButton, { role: "ghost", onClick: workspace.peekToPage, children: copy.peek.openAsPage })] }), children: _jsx(ViewHost, { resource: peeked, registry: registry, api: api.for(peeked, { surface: Surface.Peek }) }) }) }), peekModal === null ? null : (_jsx(ModalLayer, { modal: peekModal, registry: registry, store: workspace, api: api, phone: phone }))] })) })), phone && state.page !== null && state.panels.length > 0 ? (_jsx(PhoneDock, { panels: state.panels, titleOf: api.titleOf, onBring: workspace.expandPanel })) : null, _jsx(Confirm, { open: asking !== null, title: copy.discard.title, detail: asking === null ? "" : copy.discard.detail(asking.names), keep: copy.discard.keep, discard: copy.discard.discard, onAnswer: (ok) => asking?.answer(ok) }), palette ? (_jsx(WorkspacePalette, { registry: registry, focused: focusedRef(state), onOpen: open, onAction: run, onClose: () => setPalette(false) })) : null] }) }));
137
+ const desk = (_jsxs("div", { ref: root, className: "sc-root", ...(phone ? { "data-phone": "" } : {}), children: [skin.styles ? _jsx(ComposerStyles, {}) : null, state.page === null ? (_jsx("div", { className: "sc-empty", children: empty })) : (_jsx(PanelHost, { workspace: state, registry: registry, store: workspace, api: api, phone: phone, overlay: peeked === null ? null : (_jsxs(_Fragment, { children: [_jsx("div", { style: { display: "contents" }, inert: peekModal !== null, onPointerDownCapture: () => workspace.focusPanel(PEEK), children: _jsx(Drawer, { title: api.titleOf(peeked), onClose: workspace.closePeek, actions: _jsxs(_Fragment, { children: [phone ? null : (_jsx(ChromeButton, { onClick: () => workspace.peekToSide(peekSpec?.preferredZone ?? Zone.Right), children: copy.peek.openAsPanel })), cameFrom === undefined ? null : (_jsx(ChromeButton, { role: "ghost", icon: skin.icons.back, onClick: workspace.peekBack, children: copy.peek.back(api.titleOf(cameFrom)) })), _jsx(ChromeButton, { role: "ghost", onClick: workspace.peekToPage, children: copy.peek.openAsPage })] }), children: _jsx(ViewHost, { resource: peeked, registry: registry, api: api.for(peeked, { surface: Surface.Peek }) }) }) }), peekModal === null ? null : (_jsx(ModalLayer, { modal: peekModal, registry: registry, store: workspace, api: api, phone: phone }))] })) })), phone && state.page !== null && state.panels.length > 0 ? (_jsx(PhoneDock, { panels: state.panels, titleOf: api.titleOf, onBring: workspace.expandPanel })) : null, _jsx(Confirm, { open: asking !== null, title: copy.discard.title, detail: asking === null ? "" : copy.discard.detail(asking.names), keep: copy.discard.keep, discard: copy.discard.discard, onAnswer: (ok) => asking?.answer(ok) }), palette ? (_jsx(WorkspacePalette, { registry: registry, focused: focusedRef(state), onOpen: open, onAction: run, onClose: () => setPalette(false) })) : null] }));
138
+ return (_jsx(SkinProvider, { value: skin, children: onViewError === undefined ? (desk) : (_jsx(ViewErrorProvider, { value: onViewError, children: desk })) }));
144
139
  }
@@ -1,5 +1,21 @@
1
1
  import { type Registry, type ResourceRef, type WorkspaceApi } from "../domain/index.js";
2
2
  import { type ReactNode } from "react";
3
+ /** Where a view failed: the reference it was opened with, and React's stack of components. */
4
+ export type ViewErrorAbout = {
5
+ resource: ResourceRef;
6
+ componentStack: string | undefined;
7
+ };
8
+ /**
9
+ * Told when a view breaks while drawing — once per failure, after the panel shows its notice.
10
+ *
11
+ * Context: the boundary keeps the rest of the workspace alive, but a console line is nobody's
12
+ * report: the application hands this to its error reporter (GlitchTip, Sentry), the same place
13
+ * its use cases report to. Whatever it does, it never breaks the workspace — a handler that
14
+ * throws is ignored.
15
+ */
16
+ export type OnViewError = (error: Error, about: ViewErrorAbout) => void;
17
+ /** `Composer onViewError` sets it for every view it hosts; a host of its own sets it here. */
18
+ export declare const ViewErrorProvider: import("react").Provider<OnViewError | undefined>;
3
19
  export type ViewHostProps = {
4
20
  resource: ResourceRef;
5
21
  registry: Registry;
@@ -2,7 +2,7 @@ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
2
  import { formatRef, loadView, rootRef, } from "../domain/index.js";
3
3
  import { composerCopy } from "./copy.js";
4
4
  import { useSkin } from "./skin.js";
5
- import { Component, lazy, memo, Suspense, useMemo, } from "react";
5
+ import { Component, createContext, lazy, memo, Suspense, useContext, useMemo, } from "react";
6
6
  /**
7
7
  * The only thing that turns a reference into pixels. Resolves against the
8
8
  * registry, isolates failure, and lends the navigation API — the view never
@@ -20,6 +20,9 @@ import { Component, lazy, memo, Suspense, useMemo, } from "react";
20
20
  function DefaultNotice({ heading, detail, bad = false }) {
21
21
  return (_jsxs("div", { role: "status", className: "sc-notice", ...(bad ? { "data-tone": "bad" } : {}), children: [_jsx("strong", { children: heading }), _jsx("code", { children: detail })] }));
22
22
  }
23
+ const ViewErrorContext = createContext(undefined);
24
+ /** `Composer onViewError` sets it for every view it hosts; a host of its own sets it here. */
25
+ export const ViewErrorProvider = ViewErrorContext.Provider;
23
26
  class ErrorBoundary extends Component {
24
27
  state = { error: null };
25
28
  static getDerivedStateFromError(error) {
@@ -27,6 +30,15 @@ class ErrorBoundary extends Component {
27
30
  }
28
31
  componentDidCatch(error, info) {
29
32
  console.error(`[view ${this.props.name}] failed to render`, error, info.componentStack);
33
+ try {
34
+ this.props.onError?.(error, {
35
+ resource: this.props.resource,
36
+ componentStack: info.componentStack ?? undefined,
37
+ });
38
+ }
39
+ catch {
40
+ // Telling someone about a failure never becomes a second one.
41
+ }
30
42
  }
31
43
  componentDidUpdate(prev) {
32
44
  if (prev.name !== this.props.name && this.state.error !== null) {
@@ -44,10 +56,11 @@ function Host({ resource, registry, api, fallback }) {
44
56
  const key = formatRef(resource);
45
57
  const spec = registry.resolve(resource);
46
58
  const Notice = useSkin().Notice ?? DefaultNotice;
59
+ const onError = useContext(ViewErrorContext);
47
60
  const View = useMemo(() => (spec === null ? null : lazy(async () => ({ default: await loadView(spec) }))), [spec]);
48
61
  if (spec === null || View === null) {
49
62
  return (_jsx(Notice, { heading: composerCopy().view.unresolved, detail: `${key} — is the «${resource.domain}» domain missing from the registry?` }));
50
63
  }
51
- return (_jsx(ErrorBoundary, { name: key, Notice: Notice, children: _jsx(Suspense, { fallback: fallback ?? _jsx("p", { className: "sc-loading", children: composerCopy().view.loading(spec.domain) }), children: _jsx(View, { resource: resource, api: api }, formatRef(rootRef(resource))) }) }));
64
+ return (_jsx(ErrorBoundary, { name: key, resource: resource, Notice: Notice, onError: onError, children: _jsx(Suspense, { fallback: fallback ?? _jsx("p", { className: "sc-loading", children: composerCopy().view.loading(spec.domain) }), children: _jsx(View, { resource: resource, api: api }, formatRef(rootRef(resource))) }) }));
52
65
  }
53
66
  export const ViewHost = memo(Host);
@@ -62,7 +62,9 @@ const CSS = `
62
62
  .sc-empty { display: flex; flex: 1; min-height: 0; align-items: center; justify-content: center; padding: 32px; }
63
63
  .sc-host { position: relative; flex: 1; min-height: 0; overflow: hidden; }
64
64
  .sc-slot { position: absolute; isolation: isolate; min-height: 0; }
65
- .sc-slot[data-page] { overflow: auto; }
65
+ /* Every view sits in a container named sc-view — the page, a panel, the peek, a modal — so it is
66
+ drawn for ITS width: @container sc-view (width < 640px). A side panel is narrow on a desktop. */
67
+ .sc-slot[data-page] { overflow: auto; container: sc-view / inline-size; }
66
68
  .sc-slot[data-pad="all"] { padding: 4px; }
67
69
  .sc-slot[data-pad="x"] { padding: 0 4px; }
68
70
  .sc-slot[data-pad="y"] { padding: 4px 0; }
@@ -91,7 +93,7 @@ const CSS = `
91
93
  }
92
94
  .sc-header[data-rail] .sc-title { min-height: 0; padding: 4px 0; writing-mode: vertical-rl; }
93
95
  .sc-body-wrap { position: relative; display: flex; flex: 1; flex-direction: column; min-height: 0; }
94
- .sc-body { flex: 1; min-height: 0; overflow: auto; container-type: inline-size; }
96
+ .sc-body { flex: 1; min-height: 0; overflow: auto; container: sc-view / inline-size; }
95
97
 
96
98
  .sc-control {
97
99
  display: inline-flex; flex-shrink: 0; align-items: center; justify-content: center;
@@ -153,7 +155,7 @@ const CSS = `
153
155
  font-size: var(--_text); font-weight: 600;
154
156
  }
155
157
  .sc-peek-actions { display: flex; flex-shrink: 0; flex-wrap: wrap; gap: 6px; padding: 6px 12px; border-bottom: 1px solid var(--_line); }
156
- .sc-peek-body { flex: 1; min-height: 0; overflow: auto; padding: 12px; container-type: inline-size; }
158
+ .sc-peek-body { flex: 1; min-height: 0; overflow: auto; padding: 12px; container: sc-view / inline-size; }
157
159
 
158
160
  .sc-modal-layer { position: absolute; inset: 0; z-index: 1; }
159
161
  .sc-overlay > .sc-modal-layer { z-index: 31; }
@@ -176,7 +178,7 @@ const CSS = `
176
178
  flex: 1; min-width: 0; margin: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
177
179
  font-size: var(--_text-small); font-weight: 600;
178
180
  }
179
- .sc-modal-body { flex: 1; min-height: 0; overflow: auto; container-type: inline-size; }
181
+ .sc-modal-body { flex: 1; min-height: 0; overflow: auto; container: sc-view / inline-size; }
180
182
 
181
183
  /* A phone: one screen. The drawer is the screen's width, the modal a sheet from the bottom. */
182
184
  .sc-root[data-phone] .sc-peek { width: 100%; border-left: 0; border-radius: 0; }
@@ -34,8 +34,6 @@ export type AgentTool = {
34
34
  execute: (input: Record<string, unknown>) => unknown;
35
35
  annotations?: AgentToolAnnotations;
36
36
  };
37
- /** Whether this browser offers tools to an agent at all. */
38
- export declare const agentAvailable: () => boolean;
39
37
  /** A valid tool name from anything: what is not allowed becomes `_`, and it is cut at 128. */
40
38
  export declare const toolName: (text: string) => string;
41
39
  /** Offers `tool` until the returned function is called. Without WebMCP, or refused (a name
@@ -5,8 +5,6 @@ function modelContext() {
5
5
  const g = globalThis;
6
6
  return g.document?.modelContext ?? g.navigator?.modelContext ?? null;
7
7
  }
8
- /** Whether this browser offers tools to an agent at all. */
9
- export const agentAvailable = () => modelContext() !== null;
10
8
  /** A valid tool name from anything: what is not allowed becomes `_`, and it is cut at 128. */
11
9
  export const toolName = (text) => text.replace(/[^A-Za-z0-9_.-]/g, "_").slice(0, 128) || "tool";
12
10
  const NO_INPUT = { type: "object", properties: {} };
@@ -29,6 +29,9 @@ export type ApiFactory = {
29
29
  zoneFor: (spec: ViewSpec | null) => Zone;
30
30
  /** The name the shell draws for `ref`: the one its view gave, else its `ViewSpec` title. */
31
31
  titleOf: (ref: ResourceRef) => string;
32
+ /** Whether the workspace is a phone now — the shell measures it. Every view's `api.layout`
33
+ * follows it without its API being rebuilt. */
34
+ setPhone: (phone: boolean) => void;
32
35
  /** Stops listening to the store. Call it when the workspace goes away. */
33
36
  dispose: () => void;
34
37
  };
@@ -37,8 +40,8 @@ export type ApiFactoryOptions = {
37
40
  registry?: Registry;
38
41
  /** Where `open(ref)` goes without a `to`. The page: what people expect of a click. */
39
42
  defaultOpen?: Destination;
40
- /** Whether the workspace is a phone right now — read at call time. On a phone a window or a
43
+ /** Whether the workspace starts as a phone; `setPhone` changes it. On a phone a window or a
41
44
  * side panel opens as the page, and a chooser as a modal (`domain/phone.ts`). */
42
- isPhone?: () => boolean;
45
+ phone?: boolean;
43
46
  };
44
- export declare function createApiFactory(store: WorkspaceStore, { registry, defaultOpen, isPhone }?: ApiFactoryOptions): ApiFactory;
47
+ export declare function createApiFactory(store: WorkspaceStore, { registry, defaultOpen, phone }?: ApiFactoryOptions): ApiFactory;
package/dist/state/api.js CHANGED
@@ -21,9 +21,21 @@ 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, isPhone = () => false } = {}) {
24
+ export function createApiFactory(store, { registry, defaultOpen = Destination.Page, phone = false } = {}) {
25
25
  const cache = new Map();
26
26
  const choosers = new Map();
27
+ /* Not in the store: it is the shell's size, not a place — no URL, no history entry. */
28
+ let isPhone = phone;
29
+ const phoneListeners = new Set();
30
+ const layout = {
31
+ phone: () => isPhone,
32
+ subscribe: (listener) => {
33
+ phoneListeners.add(listener);
34
+ return () => {
35
+ phoneListeners.delete(listener);
36
+ };
37
+ },
38
+ };
27
39
  const zoneFor = (spec) => spec?.preferredZone ?? Zone.Right;
28
40
  const titleOf = (ref) => model.nameOf(store.get(), ref) ?? registry?.resolve(ref)?.title(ref) ?? formatRef(ref);
29
41
  /* A chooser whose surface is gone is forgotten, and so is a cached API of a surface that no
@@ -69,7 +81,7 @@ export function createApiFactory(store, { registry, defaultOpen = Destination.Pa
69
81
  /** A fresh modal or peek opened from OUTSIDE it is not the chooser that was there: whoever
70
82
  * waited for that one is not waiting for this. From inside, it is the chooser drilling. */
71
83
  function open(ref, asked, { blur, size } = {}) {
72
- const to = isPhone() ? model.destinationOnPhone(asked) : asked;
84
+ const to = isPhone ? model.destinationOnPhone(asked) : asked;
73
85
  if (to === Destination.Modal && !inModal)
74
86
  forget(model.modalId(model.hostOf(me)));
75
87
  if (to === Destination.Peek && !inPeek)
@@ -145,6 +157,7 @@ export function createApiFactory(store, { registry, defaultOpen = Destination.Pa
145
157
  surface: target.surface,
146
158
  over: inModal ? (model.modalOver(store.get(), target.host)?.over ?? null) : null,
147
159
  context,
160
+ layout,
148
161
  choosing: (() => {
149
162
  const pending = choosers.get(me);
150
163
  return pending === undefined ? null : { question: pending.question };
@@ -204,7 +217,7 @@ export function createApiFactory(store, { registry, defaultOpen = Destination.Pa
204
217
  question: options?.question,
205
218
  };
206
219
  const asked = options?.to ?? Destination.Window;
207
- const to = isPhone() ? model.chooserOnPhone(asked) : asked;
220
+ const to = isPhone ? model.chooserOnPhone(asked) : asked;
208
221
  if (to === Destination.Modal) {
209
222
  open(ref, to, options);
210
223
  ask(model.modalId(model.hostOf(me)), pending);
@@ -248,6 +261,13 @@ export function createApiFactory(store, { registry, defaultOpen = Destination.Pa
248
261
  },
249
262
  zoneFor,
250
263
  titleOf,
264
+ setPhone: (next) => {
265
+ if (next === isPhone)
266
+ return;
267
+ isPhone = next;
268
+ for (const listener of phoneListeners)
269
+ listener();
270
+ },
251
271
  dispose: stop,
252
272
  };
253
273
  }
@@ -7,6 +7,7 @@ const placeOf = (w) => `${w.page === null ? "" : model.formatRef(w.page)} ${w.pe
7
7
  const memoryOf = (w) => ({
8
8
  trail: w.trail,
9
9
  peekTrail: w.peekTrail,
10
+ titles: w.titles,
10
11
  });
11
12
  function isMemory(value) {
12
13
  const m = value;
@@ -17,12 +18,22 @@ function readHash(fallback) {
17
18
  return fallback;
18
19
  return model.fromHash(window.location.hash);
19
20
  }
21
+ /** Where a fresh store starts: the hash, with the memory of its history entry. A reload keeps
22
+ * that entry, so the breadcrumb and the names come back with the page; a link has none, and its
23
+ * page opens alone. */
24
+ function readPlace(fallback) {
25
+ const url = readHash(fallback);
26
+ if (url === fallback)
27
+ return fallback;
28
+ const memory = window.history.state;
29
+ return isMemory(memory) ? model.restore(url, url, memory) : url;
30
+ }
20
31
  const onBeforeUnload = (e) => {
21
32
  e.preventDefault();
22
33
  e.returnValue = "";
23
34
  };
24
35
  export function createWorkspaceStore({ initial = model.EMPTY, hash = false, onChange, confirmDiscard, } = {}) {
25
- let state = hash ? readHash(initial) : initial;
36
+ let state = hash ? readPlace(initial) : initial;
26
37
  const listeners = new Set();
27
38
  /** Surface → the resource it has unsaved changes for. */
28
39
  const dirty = new Map();
@@ -29,6 +29,8 @@ export type TestApiOptions = {
29
29
  selection?: readonly ResourceRef[];
30
30
  /** Opened by `pick` with this question (`api.choosing`). `null` without it: opened to look. */
31
31
  choosing?: Choosing | null;
32
+ /** What `usePhone(api)` / `api.layout.phone()` give. */
33
+ phone?: boolean;
32
34
  };
33
35
  export type TestApi = {
34
36
  api: WorkspaceApi;
@@ -6,6 +6,7 @@ export function createTestApi(self, options = {}) {
6
6
  const pending = [];
7
7
  const crumbs = options.crumbs ?? NO_CRUMBS;
8
8
  const selection = options.selection ?? NO_REFS;
9
+ const phone = options.phone ?? false;
9
10
  const record = (method) => (...args) => {
10
11
  calls.push({ method, args });
11
12
  };
@@ -19,6 +20,10 @@ export function createTestApi(self, options = {}) {
19
20
  selection: () => selection,
20
21
  subscribe: () => () => undefined,
21
22
  },
23
+ layout: {
24
+ phone: () => phone,
25
+ subscribe: () => () => undefined,
26
+ },
22
27
  open: record("open"),
23
28
  navigate: record("navigate"),
24
29
  replace: record("replace"),
@@ -1,4 +1,4 @@
1
- import type { Crumb, Workspace, WorkspaceApi } from "../domain/index.js";
1
+ import { type Crumb, type ResourceRef, type Workspace, type WorkspaceApi } from "../domain/index.js";
2
2
  import { type StoreOptions, type WorkspaceStore } from "./store.js";
3
3
  /**
4
4
  * `useSyncExternalStore` is React, not a state library. What it adds over
@@ -6,22 +6,23 @@ import { type StoreOptions, type WorkspaceStore } from "./store.js";
6
6
  * panel does not redraw the other five.
7
7
  */
8
8
  export declare function useWorkspace(options?: StoreOptions): WorkspaceStore;
9
- /**
10
- * Watch a slice of the workspace and redraw only when THAT slice changes.
11
- * The selector must return something comparable by identity. Reducers are
12
- * pure and leave untouched data alone, so `tab.panels` stays the same array
13
- * until someone moves a panel.
14
- */
15
- export declare function useWorkspaceSlice<T>(store: WorkspaceStore, select: (state: Workspace) => T): T;
16
9
  export declare function useWorkspaceState(store: WorkspaceStore): Workspace;
17
10
  /** For a global panel — the chat, the assistant — that follows what the user
18
11
  * is working on. Redraws only when the focused resource or its selection change. */
19
12
  export declare function useWorkspaceContext(api: WorkspaceApi): {
20
- focused: import("../domain/index.js").ResourceRef | null;
21
- selection: readonly import("../domain/index.js").ResourceRef[];
13
+ focused: ResourceRef | null;
14
+ selection: readonly ResourceRef[];
22
15
  };
23
16
  /** The breadcrumb that FOLLOWS the workspace: a name a view gives later (`setTitle`) redraws
24
17
  * it. `api.crumbs()` read during render is what it was then — nothing redraws a view when a
25
18
  * title changes, and the API it holds stays the same object on purpose. */
26
19
  export declare function useCrumbs(api: WorkspaceApi): readonly Crumb[];
20
+ /** Whether the workspace is a phone right now, redrawn when it changes (`api.layout`): for what
21
+ * a view offers, not for how it is drawn — that is `@container sc-view`, which a narrow side
22
+ * panel on a desktop answers too. */
23
+ export declare function usePhone(api: WorkspaceApi): boolean;
24
+ /** The entry of the app's menu the person is under (`sectionOf`), for a bar or a sidebar to
25
+ * mark. One of `sections` itself, so it redraws when the entry changes, not on every move of a
26
+ * panel. */
27
+ export declare function useSection<T extends ResourceRef>(store: WorkspaceStore, sections: readonly T[]): T | null;
27
28
  export type { StoreOptions as UseWorkspaceOptions, WorkspaceStore };
@@ -1,5 +1,6 @@
1
+ import { sectionOf, } from "../domain/index.js";
1
2
  import { createWorkspaceStore, } from "./store.js";
2
- import { useMemo, useRef, useSyncExternalStore } from "react";
3
+ import { useRef, useSyncExternalStore } from "react";
3
4
  /**
4
5
  * `useSyncExternalStore` is React, not a state library. What it adds over
5
6
  * `useState` is the one thing we needed: subscribe to a slice, so moving one
@@ -10,16 +11,6 @@ export function useWorkspace(options = {}) {
10
11
  saved.current ??= createWorkspaceStore(options);
11
12
  return saved.current;
12
13
  }
13
- /**
14
- * Watch a slice of the workspace and redraw only when THAT slice changes.
15
- * The selector must return something comparable by identity. Reducers are
16
- * pure and leave untouched data alone, so `tab.panels` stays the same array
17
- * until someone moves a panel.
18
- */
19
- export function useWorkspaceSlice(store, select) {
20
- const read = useMemo(() => () => select(store.get()), [store, select]);
21
- return useSyncExternalStore(store.subscribe, read, read);
22
- }
23
14
  export function useWorkspaceState(store) {
24
15
  return useSyncExternalStore(store.subscribe, store.get, store.get);
25
16
  }
@@ -38,3 +29,16 @@ export function useWorkspaceContext(api) {
38
29
  export function useCrumbs(api) {
39
30
  return useSyncExternalStore(api.context.subscribe, api.crumbs, api.crumbs);
40
31
  }
32
+ /** Whether the workspace is a phone right now, redrawn when it changes (`api.layout`): for what
33
+ * a view offers, not for how it is drawn — that is `@container sc-view`, which a narrow side
34
+ * panel on a desktop answers too. */
35
+ export function usePhone(api) {
36
+ return useSyncExternalStore(api.layout.subscribe, api.layout.phone, api.layout.phone);
37
+ }
38
+ /** The entry of the app's menu the person is under (`sectionOf`), for a bar or a sidebar to
39
+ * mark. One of `sections` itself, so it redraws when the entry changes, not on every move of a
40
+ * panel. */
41
+ export function useSection(store, sections) {
42
+ const read = () => sectionOf(store.get(), sections);
43
+ return useSyncExternalStore(store.subscribe, read, read);
44
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sincpro/web-composer",
3
- "version": "1.5.0",
3
+ "version": "1.7.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",