@sincpro/web-composer 1.8.0 → 1.9.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
@@ -146,8 +146,9 @@ breadcrumb behind, no peek, the panels stay), and `useSection(workspace, entries
146
146
  entry of that menu the person is under, to mark it — still the same entry a record and its lines
147
147
  deeper. The menu itself is the app's: its groups, its icons, who may see what.
148
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
150
- composer's own dialog; `useWorkspace({ confirmDiscard })` replaces it.
149
+ a reload keeps the breadcrumb and the names views gave — drawn on a server too, add
150
+ `serverRendered: true` ([Server rendering](#server-rendering)). Unsaved changes are asked with
151
+ the composer's own dialog; `useWorkspace({ confirmDiscard })` replaces it.
151
152
 
152
153
  ## Where each behaviour lives
153
154
 
@@ -308,6 +309,42 @@ expect(t.callsTo("open")[0].args).toEqual([paymentRef("F-1"), { to: "modal" }]);
308
309
  t.respond(true); // answers the last chooser it opened, as its view would
309
310
  ```
310
311
 
312
+ ### Server rendering
313
+
314
+ It works in a server-rendered app — Next.js (App Router or Pages Router), any SSR —, and nothing
315
+ changes for a single-page app.
316
+
317
+ - **Server Components** may import from `@sincpro/web-composer`. Every module that needs the
318
+ browser (hooks, context, events) starts with `"use client"`, and a test keeps it so; the model
319
+ (`@sincpro/web-composer/domain`), `createWorkspaceStore`, the copy and `platformKeys` stay
320
+ callable from a server. The workspace itself lives in the browser: hold it in a client
321
+ component of your own, and draw `<Composer>` there.
322
+ - **The workspace in the URL.** The browser never sends the hash to the server.
323
+ `useWorkspace({ hash: true })` reads it as the store is created — a single-page app shows the
324
+ link's place on its first frame —, so hydrating, the browser would draw a place the server did
325
+ not: a hydration error. A server-rendered app asks for
326
+
327
+ ```tsx
328
+ "use client";
329
+ const workspace = useWorkspace({ hash: true, serverRendered: true });
330
+ ```
331
+
332
+ It starts at `initial`, what the server drew, and takes the URL's place once mounted, with its
333
+ breadcrumb on a reload — before the effects of the component that holds it, so
334
+ `if (workspace.get().page === null) workspace.start(home)` in an effect still sees the link.
335
+ `createWorkspaceStore({ hash: true, serverRendered: true })` does the same on its first
336
+ listener or its first change, whichever comes first.
337
+
338
+ - **Drag and drop** is loaded by the browser when the workspace mounts, never on import: a
339
+ server — plain Node included — imports and draws the composer without touching
340
+ `@atlaskit/pragmatic-drag-and-drop`. The browser's bundle still gets it, as any dependency.
341
+ - **The words.** `installComposerCopy` sets the one global there is, and a server renders every
342
+ request in one process: install it in a module every page loads (the root layout's client
343
+ providers), never in one page.
344
+
345
+ The story «16 · Dibujado en el servidor» draws the workspace with `renderToString`, opens a link
346
+ and hydrates it in Chrome: no difference with the server, then the link's record.
347
+
311
348
  ## Your design over it
312
349
 
313
350
  ### Colors
@@ -1,3 +1,4 @@
1
+ "use client";
1
2
  import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
2
3
  import { Destination, destinationOnPhone, focusedRef, modalOver, PEEK, PHONE_WIDTH, Surface, Zone, } from "../domain/index.js";
3
4
  import { composerCopy } from "./copy.js";
@@ -1,3 +1,4 @@
1
+ "use client";
1
2
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
3
  import { modalId, Surface, } from "../domain/index.js";
3
4
  import { composerCopy } from "./copy.js";
@@ -1,3 +1,4 @@
1
+ "use client";
1
2
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
3
  import { Destination, localEntries, matches, MIN_QUERY, PaletteSection, searchEntries, } from "../domain/index.js";
3
4
  import { composerCopy } from "./copy.js";
@@ -1,3 +1,4 @@
1
+ "use client";
1
2
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
3
  import { Zone } from "../domain/index.js";
3
4
  import { composerCopy } from "./copy.js";
@@ -1,3 +1,4 @@
1
+ "use client";
1
2
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
3
  import { Axis, HandleKind, handles, KEYBOARD_STEP, layout, MIN_WINDOW, modalOver, PAGE, phoneLayout, sizeAt, stableOrder, Surface, Zone, } from "../domain/index.js";
3
4
  import { composerCopy } from "./copy.js";
@@ -1,3 +1,4 @@
1
+ "use client";
1
2
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
3
  import { composerCopy } from "./copy.js";
3
4
  import { useSkin } from "./skin.js";
@@ -1,3 +1,4 @@
1
+ "use client";
1
2
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
3
  import { Destination, } from "../domain/index.js";
3
4
  import { composerCopy } from "./copy.js";
@@ -1,3 +1,4 @@
1
+ "use client";
1
2
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
3
  import { formatRef, loadView, rootRef, } from "../domain/index.js";
3
4
  import { composerCopy } from "./copy.js";
@@ -1,3 +1,4 @@
1
+ "use client";
1
2
  import { BackIcon, BottomIcon, CloseIcon, ExpandIcon, LeftIcon, MaximizeIcon, MinimizeIcon, MoreIcon, PeekIcon, RestoreIcon, RightIcon, SearchIcon, WindowIcon, } from "./icons.js";
2
3
  import { createContext, useContext } from "react";
3
4
  export const DEFAULT_ICONS = {
@@ -1,3 +1,4 @@
1
+ "use client";
1
2
  import { Destination, focusedRef, formatRef, modalId, PAGE, parseRef, PEEK, refOn, rootRef, sameRef, searchEntries, selectionOf, } from "../domain/index.js";
2
3
  import { useEffect, useLayoutEffect, useRef } from "react";
3
4
  /** The draft moved it from `navigator` to `document`; early builds still have the first. */
@@ -1,6 +1,37 @@
1
- import { draggable, dropTargetForElements, monitorForElements, } from "@atlaskit/pragmatic-drag-and-drop/element/adapter";
1
+ "use client";
2
2
  import { DragKind } from "../domain/index.js";
3
3
  import { useEffect, useState } from "react";
4
+ let adapter = null;
5
+ let loading = null;
6
+ /**
7
+ * Context: the drag-and-drop adapter is loaded the first time a browser registers a drag or a
8
+ * drop, never on import. It resolves only through a bundler (a folder with its own
9
+ * `package.json`, extensionless imports inside): imported statically, a server — plain Node, a
10
+ * framework's server render — could not even import the composer. Effects never run on a
11
+ * server, so a server never asks for it. Once loaded it is kept: every registration after the
12
+ * first is immediate, as it always was.
13
+ *
14
+ * A chunk that fails to load leaves nothing draggable and the workspace working; the next
15
+ * element that mounts asks for it again.
16
+ */
17
+ function withDragAdapter(register) {
18
+ if (adapter !== null)
19
+ return register(adapter);
20
+ let cleanup = null;
21
+ let gone = false;
22
+ loading ??= import("@atlaskit/pragmatic-drag-and-drop/element/adapter").then((loaded) => (adapter = loaded), (error) => {
23
+ loading = null;
24
+ throw error;
25
+ });
26
+ loading.then((loaded) => {
27
+ if (!gone)
28
+ cleanup = register(loaded);
29
+ }, () => undefined);
30
+ return () => {
31
+ gone = true;
32
+ cleanup?.();
33
+ };
34
+ }
4
35
  const isDrag = (v) => v["kind"] === DragKind.Panel || v["kind"] === DragKind.Ref;
5
36
  /** Only a DOCKED panel is dragged to another edge. A window moves with the pointer, and a native
6
37
  * drag on the same header would swallow that gesture — `enabled` keeps the two apart. */
@@ -10,7 +41,7 @@ export function useDraggablePanel(ref, panelId, enabled = true) {
10
41
  const el = ref.current;
11
42
  if (el === null || !enabled)
12
43
  return;
13
- return draggable({
44
+ return withDragAdapter(({ draggable }) => draggable({
14
45
  element: el,
15
46
  getInitialData: () => ({
16
47
  kind: DragKind.Panel,
@@ -18,7 +49,7 @@ export function useDraggablePanel(ref, panelId, enabled = true) {
18
49
  }),
19
50
  onDragStart: () => setDragging(true),
20
51
  onDrop: () => setDragging(false),
21
- });
52
+ }));
22
53
  }, [ref, panelId, enabled]);
23
54
  return dragging;
24
55
  }
@@ -28,7 +59,7 @@ export function useDropZone(ref, zone) {
28
59
  const el = ref.current;
29
60
  if (el === null)
30
61
  return;
31
- return dropTargetForElements({
62
+ return withDragAdapter(({ dropTargetForElements }) => dropTargetForElements({
32
63
  element: el,
33
64
  getData: () => ({ kind: DragKind.Zone, zone }),
34
65
  canDrop: ({ source }) => isDrag(source.data) &&
@@ -36,7 +67,7 @@ export function useDropZone(ref, zone) {
36
67
  onDragEnter: () => setOver(true),
37
68
  onDragLeave: () => setOver(false),
38
69
  onDrop: () => setOver(false),
39
- });
70
+ }));
40
71
  }, [ref, zone]);
41
72
  return over;
42
73
  }
@@ -47,7 +78,7 @@ export function useDraggableRef(ref, resource, enabled = true) {
47
78
  const el = ref.current;
48
79
  if (el === null || !enabled)
49
80
  return;
50
- return draggable({
81
+ return withDragAdapter(({ draggable }) => draggable({
51
82
  element: el,
52
83
  getInitialData: () => ({
53
84
  kind: DragKind.Ref,
@@ -55,7 +86,7 @@ export function useDraggableRef(ref, resource, enabled = true) {
55
86
  }),
56
87
  onDragStart: () => setDragging(true),
57
88
  onDrop: () => setDragging(false),
58
- });
89
+ }));
59
90
  }, [ref, resource, enabled]);
60
91
  return dragging;
61
92
  }
@@ -64,18 +95,18 @@ export function useDraggableRef(ref, resource, enabled = true) {
64
95
  * and the buttons never fire. */
65
96
  export function usePanelDragArmed() {
66
97
  const [armed, setArmed] = useState(false);
67
- useEffect(() => monitorForElements({
98
+ useEffect(() => withDragAdapter(({ monitorForElements }) => monitorForElements({
68
99
  canMonitor: ({ source }) => isDrag(source.data) &&
69
100
  (source.data.kind === DragKind.Panel || source.data.kind === DragKind.Ref),
70
101
  onDragStart: () => setArmed(true),
71
102
  onDrop: () => setArmed(false),
72
- }), []);
103
+ })), []);
73
104
  return armed;
74
105
  }
75
106
  /** One monitor for the whole workspace: drop is ONE event with ONE result.
76
107
  * Split across targets, an overlapping zone and tab would both apply. */
77
108
  export function useDropMonitor({ onPanelToZone, onRefToZone }) {
78
- useEffect(() => monitorForElements({
109
+ useEffect(() => withDragAdapter(({ monitorForElements }) => monitorForElements({
79
110
  canMonitor: ({ source }) => isDrag(source.data),
80
111
  onDrop: ({ source, location }) => {
81
112
  const target = location.current.dropTargets[0];
@@ -91,5 +122,5 @@ export function useDropMonitor({ onPanelToZone, onRefToZone }) {
91
122
  return;
92
123
  }
93
124
  },
94
- }), [onPanelToZone, onRefToZone]);
125
+ })), [onPanelToZone, onRefToZone]);
95
126
  }
@@ -74,10 +74,27 @@ export type StoreOptions = {
74
74
  /** Persist the workspace in the URL hash. The browser's Back and «share this link» come
75
75
  * from here. */
76
76
  hash?: boolean;
77
+ /**
78
+ * The page is drawn on the server and hydrated (SSR, React Server Components). With `hash`,
79
+ * the store starts at `initial` — what the server drew: it never sees the hash — and takes the
80
+ * URL's place once in the browser: when `useWorkspace` mounts, when someone first listens
81
+ * (`<Composer>`, `useWorkspaceState`, `useSection`) or before its first change, whichever comes
82
+ * first. Without it `hash` reads the URL at once, which a single-page app wants: the link's
83
+ * place on its first frame. Without `hash` it changes nothing.
84
+ */
85
+ serverRendered?: boolean;
77
86
  /** Called after every change. Hook for telemetry or saving the user's workspace. */
78
87
  onChange?: (state: Workspace) => void;
79
88
  /** Asked before a change throws away a view with unsaved changes. Without it, `<Composer>`
80
89
  * asks with its own dialog; with neither, nothing is asked. */
81
90
  confirmDiscard?: ConfirmDiscard;
82
91
  };
83
- export declare function createWorkspaceStore({ initial, hash, onChange, confirmDiscard, }?: StoreOptions): WorkspaceStore;
92
+ /** What a `serverRendered` store with `hash` keeps for the hooks. */
93
+ export type Hydration = {
94
+ /** What the server drew: hydrating, the browser draws the same. */
95
+ server: () => Workspace;
96
+ /** Takes the URL's place now, if it has not yet. */
97
+ takeUrl: () => void;
98
+ };
99
+ export declare const hydrationOf: (store: WorkspaceStore) => Hydration | null;
100
+ export declare function createWorkspaceStore({ initial, hash, serverRendered, onChange, confirmDiscard, }?: StoreOptions): WorkspaceStore;
@@ -32,8 +32,16 @@ const onBeforeUnload = (e) => {
32
32
  e.preventDefault();
33
33
  e.returnValue = "";
34
34
  };
35
- export function createWorkspaceStore({ initial = model.EMPTY, hash = false, onChange, confirmDiscard, } = {}) {
36
- let state = hash ? readPlace(initial) : initial;
35
+ /**
36
+ * Context: the hooks' business, not the app's — so it is not a member of `WorkspaceStore`, whose
37
+ * shape stays the same for whoever builds one of their own (a fake in a test).
38
+ */
39
+ const hydrations = new WeakMap();
40
+ export const hydrationOf = (store) => hydrations.get(store) ?? null;
41
+ export function createWorkspaceStore({ initial = model.EMPTY, hash = false, serverRendered = false, onChange, confirmDiscard, } = {}) {
42
+ /** The URL's place, not read yet: it waits for the browser (`serverRendered`). */
43
+ let waiting = hash && serverRendered;
44
+ let state = hash && !waiting ? readPlace(initial) : initial;
37
45
  const listeners = new Set();
38
46
  /** Surface → the resource it has unsaved changes for. */
39
47
  const dirty = new Map();
@@ -48,6 +56,18 @@ export function createWorkspaceStore({ initial = model.EMPTY, hash = false, onCh
48
56
  l();
49
57
  onChange?.(state);
50
58
  };
59
+ /** The URL's place, read once in the browser and announced like any change: until now
60
+ * everyone drew `initial`. */
61
+ function takeUrl() {
62
+ if (!waiting || !inBrowser())
63
+ return;
64
+ waiting = false;
65
+ const url = readPlace(initial);
66
+ if (url === state)
67
+ return;
68
+ state = url;
69
+ notify();
70
+ }
51
71
  /** The browser asks before closing the tab only while something is unsaved. */
52
72
  function guardUnload() {
53
73
  const want = dirty.size > 0;
@@ -116,7 +136,10 @@ export function createWorkspaceStore({ initial = model.EMPTY, hash = false, onCh
116
136
  const answer = ask(lost);
117
137
  return answer instanceof Promise ? answer.then(proceed) : proceed(answer);
118
138
  }
139
+ /** A change starts from where the URL says: a store that moved before reading it would write
140
+ * its own place over the link. */
119
141
  function go(change, mode = History.Auto) {
142
+ takeUrl();
120
143
  const result = line === null ? run(change, mode) : line.then(() => run(change, mode));
121
144
  if (!(result instanceof Promise))
122
145
  return;
@@ -153,7 +176,10 @@ export function createWorkspaceStore({ initial = model.EMPTY, hash = false, onCh
153
176
  else
154
177
  settle(answer);
155
178
  }
179
+ /** Hydrating, React listens only after drawing what the server drew: the first listener in
180
+ * the browser is when the URL's place can be taken. */
156
181
  const subscribe = (listener) => {
182
+ takeUrl();
157
183
  listeners.add(listener);
158
184
  if (listeners.size === 1 && hash && inBrowser())
159
185
  window.addEventListener("popstate", onPopState);
@@ -163,7 +189,7 @@ export function createWorkspaceStore({ initial = model.EMPTY, hash = false, onCh
163
189
  window.removeEventListener("popstate", onPopState);
164
190
  };
165
191
  };
166
- return {
192
+ const store = {
167
193
  get: () => state,
168
194
  subscribe,
169
195
  apply: (change) => go(change),
@@ -215,4 +241,7 @@ export function createWorkspaceStore({ initial = model.EMPTY, hash = false, onCh
215
241
  palette = open;
216
242
  },
217
243
  };
244
+ if (waiting)
245
+ hydrations.set(store, { server: () => initial, takeUrl });
246
+ return store;
218
247
  }
@@ -1,3 +1,4 @@
1
+ "use client";
1
2
  import { MODAL, PAGE, PEEK } from "../domain/index.js";
2
3
  import { useEffect } from "react";
3
4
  /** Inside a field only Escape survives. Stealing a key from someone who is typing is worse than
@@ -4,7 +4,14 @@ import { type StoreOptions, type WorkspaceStore } from "./store.js";
4
4
  * `useSyncExternalStore` is React, not a state library. What it adds over
5
5
  * `useState` is the one thing we needed: subscribe to a slice, so moving one
6
6
  * panel does not redraw the other five.
7
+ *
8
+ * Its server snapshot is what the server drew: the store as it is, or — `serverRendered` —
9
+ * `initial`, so a part hydrated late (a Suspense boundary) still matches the server's HTML
10
+ * after the store took the URL's place.
7
11
  */
12
+ /** The workspace an app holds. Server-rendered, `{ hash: true, serverRendered: true }`: the
13
+ * first render is the server's, and the URL's place comes once mounted — before the effects of
14
+ * the component that holds it, which may ask `get()` where it is. */
8
15
  export declare function useWorkspace(options?: StoreOptions): WorkspaceStore;
9
16
  export declare function useWorkspaceState(store: WorkspaceStore): Workspace;
10
17
  /** For a global panel — the chat, the assistant — that follows what the user
@@ -1,18 +1,28 @@
1
+ "use client";
1
2
  import { sectionOf, } from "../domain/index.js";
2
- import { createWorkspaceStore, } from "./store.js";
3
- import { useRef, useSyncExternalStore } from "react";
3
+ import { createWorkspaceStore, hydrationOf, } from "./store.js";
4
+ import { useEffect, useRef, useSyncExternalStore } from "react";
4
5
  /**
5
6
  * `useSyncExternalStore` is React, not a state library. What it adds over
6
7
  * `useState` is the one thing we needed: subscribe to a slice, so moving one
7
8
  * panel does not redraw the other five.
9
+ *
10
+ * Its server snapshot is what the server drew: the store as it is, or — `serverRendered` —
11
+ * `initial`, so a part hydrated late (a Suspense boundary) still matches the server's HTML
12
+ * after the store took the URL's place.
8
13
  */
14
+ /** The workspace an app holds. Server-rendered, `{ hash: true, serverRendered: true }`: the
15
+ * first render is the server's, and the URL's place comes once mounted — before the effects of
16
+ * the component that holds it, which may ask `get()` where it is. */
9
17
  export function useWorkspace(options = {}) {
10
18
  const saved = useRef(null);
11
19
  saved.current ??= createWorkspaceStore(options);
12
- return saved.current;
20
+ const store = saved.current;
21
+ useEffect(() => hydrationOf(store)?.takeUrl(), [store]);
22
+ return store;
13
23
  }
14
24
  export function useWorkspaceState(store) {
15
- return useSyncExternalStore(store.subscribe, store.get, store.get);
25
+ return useSyncExternalStore(store.subscribe, store.get, hydrationOf(store)?.server ?? store.get);
16
26
  }
17
27
  /** For a global panel — the chat, the assistant — that follows what the user
18
28
  * is working on. Redraws only when the focused resource or its selection change. */
@@ -40,5 +50,7 @@ export function usePhone(api) {
40
50
  * panel. */
41
51
  export function useSection(store, sections) {
42
52
  const read = () => sectionOf(store.get(), sections);
43
- return useSyncExternalStore(store.subscribe, read, read);
53
+ const server = hydrationOf(store)?.server;
54
+ const drawn = server === undefined ? read : () => sectionOf(server(), sections);
55
+ return useSyncExternalStore(store.subscribe, read, drawn);
44
56
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sincpro/web-composer",
3
- "version": "1.8.0",
3
+ "version": "1.9.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",