@synap-core/react 1.0.0 → 1.2.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.
Files changed (45) hide show
  1. package/README.md +144 -31
  2. package/api/editor.d.ts +178 -0
  3. package/api/whiteboard.d.ts +104 -0
  4. package/dist/editor.cjs +38733 -0
  5. package/dist/editor.css +9953 -0
  6. package/dist/editor.d.cts +178 -0
  7. package/dist/editor.d.ts +178 -0
  8. package/dist/editor.js +38974 -0
  9. package/dist/index.cjs.map +1 -1
  10. package/dist/index.d.cts +26 -4
  11. package/dist/index.d.ts +26 -4
  12. package/dist/index.js.map +1 -1
  13. package/dist/whiteboard.cjs +4540 -0
  14. package/dist/whiteboard.css +7913 -0
  15. package/dist/whiteboard.d.cts +104 -0
  16. package/dist/whiteboard.d.ts +104 -0
  17. package/dist/whiteboard.js +4568 -0
  18. package/package.json +198 -14
  19. package/src/SynapProvider.tsx +1 -1
  20. package/src/editor/SynapEditor.tsx +288 -0
  21. package/src/editor/SynapMarkdown.tsx +11 -0
  22. package/src/editor/adapter-source.ts +97 -0
  23. package/src/editor/api.ts +30 -0
  24. package/src/editor/copy.ts +18 -0
  25. package/src/editor/drag.ts +14 -0
  26. package/src/editor/editor-base.css +28 -0
  27. package/src/editor/http-adapter.ts +87 -0
  28. package/src/editor/index.ts +22 -0
  29. package/src/editor/no-default-source.ts +7 -0
  30. package/src/editor/provider.tsx +79 -0
  31. package/src/editor/types.ts +162 -0
  32. package/src/index.ts +3 -3
  33. package/src/shared/read-cache.ts +76 -0
  34. package/src/trpc.ts +3 -2
  35. package/src/whiteboard/SynapBoard.tsx +139 -0
  36. package/src/whiteboard/adapter-source.ts +138 -0
  37. package/src/whiteboard/api.ts +22 -0
  38. package/src/whiteboard/copy.ts +24 -0
  39. package/src/whiteboard/http-adapter.ts +57 -0
  40. package/src/whiteboard/index.ts +17 -0
  41. package/src/whiteboard/no-default-source.ts +7 -0
  42. package/src/whiteboard/provider.tsx +14 -0
  43. package/src/whiteboard/shapes.tsx +157 -0
  44. package/src/whiteboard/types.ts +99 -0
  45. package/src/whiteboard/whiteboard-base.css +87 -0
@@ -0,0 +1,18 @@
1
+ /** The words `<SynapEditor>` writes (chrome; the document itself is content). */
2
+ export const EDITOR_COPY = {
3
+ loading: "Opening the document…",
4
+ loadFailed: "Couldn’t open this document.",
5
+ retry: "Try again",
6
+ saving: "Saving…",
7
+ saved: "Saved",
8
+ proposed: "Waiting for review",
9
+ openReview: "Review",
10
+ saveFailed: "Couldn’t save your changes.",
11
+ conflict: "This document changed elsewhere. Reload theirs, or keep yours over it.",
12
+ reload: "Reload",
13
+ keepMine: "Keep mine",
14
+ linked: "Linked",
15
+ linkProposed: "Link waiting for review",
16
+ linkFailed: "Couldn’t link it.",
17
+ noProvider: "<SynapEditor> needs an <EditorDataProvider adapter={…}> above it.",
18
+ } as const;
@@ -0,0 +1,14 @@
1
+ /**
2
+ * The drag a pod app's object list sets so `<SynapEditor>` takes the drop:
3
+ * `onDragStart={(e) => setSynapObjectDrag(e.dataTransfer, { id, kind, label })}`.
4
+ */
5
+ import { SYNAP_OBJECT_MIME } from "@synap-core/web/markdown-engine/embeddable";
6
+ import type { SynapDraggedObject } from "./types";
7
+
8
+ export { SYNAP_OBJECT_MIME };
9
+
10
+ export function setSynapObjectDrag(dataTransfer: DataTransfer, object: SynapDraggedObject): void {
11
+ dataTransfer.setData(SYNAP_OBJECT_MIME, JSON.stringify({ id: object.id, kind: object.kind, label: object.label }));
12
+ dataTransfer.setData("text/plain", object.label || object.id);
13
+ dataTransfer.effectAllowed = "copyLink";
14
+ }
@@ -0,0 +1,28 @@
1
+ /*
2
+ * @synap-core/react/editor.css: the editor's and reader's styles, bundled into
3
+ * one file with the component CSS they import. The `--synap-*` tokens come
4
+ * first, so a host overrides any of them after this file (`:root { --synap-… }`).
5
+ */
6
+ @import "@synap-core/design-tokens/synap-tokens.css";
7
+ @import "@synap-core/web/spatial-ui/styles.css";
8
+
9
+ .synap-editor__status {
10
+ display: flex;
11
+ flex-wrap: wrap;
12
+ gap: var(--synap-space-150);
13
+ align-items: center;
14
+ margin-block-start: var(--synap-space-100);
15
+ font-family: var(--synap-type-caption-family);
16
+ font-size: var(--synap-type-caption-size);
17
+ font-weight: var(--synap-type-caption-weight);
18
+ line-height: var(--synap-type-caption-leading);
19
+ color: var(--synap-muted);
20
+ }
21
+ .synap-editor__status [data-tone="success"] { color: var(--synap-tone-success-ink); }
22
+ .synap-editor__status [data-tone="warning"] { color: var(--synap-tone-warning-ink); }
23
+ .synap-editor__status [data-tone="danger"] { color: var(--synap-tone-error-ink); }
24
+ .synap-editor--loading,
25
+ .synap-editor--failed {
26
+ padding: var(--synap-space-200);
27
+ color: var(--synap-muted);
28
+ }
@@ -0,0 +1,87 @@
1
+ /**
2
+ * `createHttpEditorAdapter()`: the editor's data calls against the app's own
3
+ * routes (`createEditorHandlers` from `@synap-core/sdk/connect`, mounted at
4
+ * `basePath`). Same-origin, cookies included: the pod token stays on the app's
5
+ * server. Reads throw `EditorReadError`; writes answer what the pod did.
6
+ */
7
+ import {
8
+ EditorReadError,
9
+ type EditorDataAdapter,
10
+ type EditorDocument,
11
+ type EditorEntity,
12
+ type EditorError,
13
+ type EditorView,
14
+ type EditorWriteResult,
15
+ type HttpEditorAdapterOptions,
16
+ type ResolvedRef,
17
+ } from "./types";
18
+
19
+ const UNREACHABLE = (detail: string): EditorError => ({ code: "unreachable", status: null, detail });
20
+
21
+ function errorOf(body: unknown, status: number): EditorError {
22
+ const e = (body as { error?: Partial<EditorError> } | null)?.error;
23
+ return {
24
+ code: typeof e?.code === "string" ? e.code : "server",
25
+ // The route's own `status` wins, null included (nothing answered: the SDK refused).
26
+ status: e && "status" in e ? (typeof e.status === "number" ? e.status : null) : status,
27
+ ...(typeof e?.detail === "string" ? { detail: e.detail } : {}),
28
+ };
29
+ }
30
+
31
+ export function createHttpEditorAdapter(options: HttpEditorAdapterOptions = {}): EditorDataAdapter {
32
+ const base = (options.basePath ?? "/api/synap/editor").replace(/\/+$/, "");
33
+ const doFetch = () => options.fetch ?? fetch;
34
+ const enc = encodeURIComponent;
35
+
36
+ async function call(method: string, path: string, payload?: unknown): Promise<{ status: number; body: unknown }> {
37
+ const res = await doFetch()(`${base}${path}`, {
38
+ method,
39
+ credentials: "same-origin",
40
+ headers: payload === undefined ? { accept: "application/json" } : { accept: "application/json", "content-type": "application/json" },
41
+ ...(payload === undefined ? {} : { body: JSON.stringify(payload) }),
42
+ });
43
+ let body: unknown = null;
44
+ try {
45
+ body = await res.json();
46
+ } catch {
47
+ body = null;
48
+ }
49
+ return { status: res.status, body };
50
+ }
51
+
52
+ async function get<T>(path: string): Promise<T> {
53
+ let answer: { status: number; body: unknown };
54
+ try {
55
+ answer = await call("GET", path);
56
+ } catch (err) {
57
+ throw new EditorReadError(UNREACHABLE(err instanceof Error ? err.message : String(err)));
58
+ }
59
+ const b = answer.body as { ok?: boolean; data?: T } | null;
60
+ if (answer.status !== 200 || b?.ok !== true || b.data === undefined) throw new EditorReadError(errorOf(answer.body, answer.status));
61
+ return b.data;
62
+ }
63
+
64
+ async function write(method: string, path: string, payload: unknown): Promise<EditorWriteResult> {
65
+ let answer: { status: number; body: unknown };
66
+ try {
67
+ answer = await call(method, path, payload);
68
+ } catch (err) {
69
+ return { ok: false, error: UNREACHABLE(err instanceof Error ? err.message : String(err)) };
70
+ }
71
+ const b = answer.body as { ok?: boolean; status?: string; reviewUrl?: unknown } | null;
72
+ if (answer.status === 200 && b?.ok === true) {
73
+ if (b.status === "applied") return { ok: true, status: "applied" };
74
+ if (b.status === "proposed" && typeof b.reviewUrl === "string") return { ok: true, status: "proposed", reviewUrl: b.reviewUrl };
75
+ }
76
+ return { ok: false, error: errorOf(answer.body, answer.status) };
77
+ }
78
+
79
+ return {
80
+ resolveRef: (id) => get<ResolvedRef>(`/resolve/${enc(id)}`),
81
+ listEntities: (workspaceId) => get<EditorEntity[]>(`/entities?workspaceId=${enc(workspaceId)}`),
82
+ listViews: (workspaceId) => get<EditorView[]>(`/views?workspaceId=${enc(workspaceId)}`),
83
+ getDocument: (id) => get<EditorDocument>(`/documents/${enc(id)}`),
84
+ saveDocument: (id, markdown, baseRevision) => write("PATCH", `/documents/${enc(id)}`, { content: markdown, baseRevision }),
85
+ linkObjects: ({ sourceId, targetId, type }) => write("POST", "/relations", { sourceId, targetId, type }),
86
+ };
87
+ }
@@ -0,0 +1,22 @@
1
+ /**
2
+ * `@synap-core/react/editor`: the pod's markdown editor and reader for a pod
3
+ * app, over a data adapter (`EditorDataProvider`). Import the styles once:
4
+ * `import "@synap-core/react/editor.css"`.
5
+ *
6
+ * Every export is typed by `./api` (the published declarations).
7
+ */
8
+ import "./editor-base.css";
9
+ import type * as Api from "./api";
10
+ import { EditorDataProvider as Provider } from "./provider";
11
+ import { SynapEditor as Editor } from "./SynapEditor";
12
+ import { SynapMarkdown as Markdown } from "./SynapMarkdown";
13
+ import { createHttpEditorAdapter as httpAdapter } from "./http-adapter";
14
+ import { SYNAP_OBJECT_MIME as MIME, setSynapObjectDrag as setDrag } from "./drag";
15
+
16
+ export * from "./types";
17
+ export const EditorDataProvider: typeof Api.EditorDataProvider = Provider;
18
+ export const SynapEditor: typeof Api.SynapEditor = Editor;
19
+ export const SynapMarkdown: typeof Api.SynapMarkdown = Markdown;
20
+ export const createHttpEditorAdapter: typeof Api.createHttpEditorAdapter = httpAdapter;
21
+ export const SYNAP_OBJECT_MIME: typeof Api.SYNAP_OBJECT_MIME = MIME;
22
+ export const setSynapObjectDrag: typeof Api.setSynapObjectDrag = setDrag;
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Stands in for `@synap-core/web`'s `markdown-engine/data/default-source` in
3
+ * this package's editor build (tsup.config.ts): a pod app has no default data
4
+ * source, it mounts `<EditorDataProvider>`. Keeping the desktop's out of the
5
+ * graph is what keeps `@synap-core/hooks` and the pod client out of the bundle.
6
+ */
7
+ export const defaultEditorData = (): null => null;
@@ -0,0 +1,79 @@
1
+ /**
2
+ * `<EditorDataProvider adapter>`: the app's data calls, for every Synap editor
3
+ * and reader below it.
4
+ */
5
+ import React, { createContext, useContext, useMemo } from "react";
6
+ import {
7
+ EditorDataContext,
8
+ FALLBACK_EMBEDS,
9
+ type EditorDataSource,
10
+ type EditorEmbedDirective,
11
+ type EmbedSubjectProps,
12
+ } from "@synap-core/web/markdown-engine/embeddable";
13
+ import { adapterSource, createReadCache, type ReadCache } from "./adapter-source";
14
+ import type { EditorDataAdapter, EditorDataProviderProps, SynapEmbed } from "./types";
15
+ import { EDITOR_COPY } from "./copy";
16
+
17
+ interface AppEditorData {
18
+ adapter: EditorDataAdapter;
19
+ cache: ReadCache;
20
+ embeds?: EditorDataSource["embeds"];
21
+ }
22
+
23
+ const AppEditorContext = createContext<AppEditorData | null>(null);
24
+
25
+ /** The provider's adapter and cache; throws when there is none above. */
26
+ export function useAppEditorData(): AppEditorData {
27
+ const value = useContext(AppEditorContext);
28
+ if (!value) throw new Error(EDITOR_COPY.noProvider);
29
+ return value;
30
+ }
31
+
32
+ const DIRECTIVES: EditorEmbedDirective[] = ["synap-cell", "synap-entity", "synap-view"];
33
+
34
+ /** `renderEmbed` as the editor's per-directive subjects; null draws the default fallback. */
35
+ function embedsFrom(renderEmbed: (embed: SynapEmbed) => React.ReactNode): EditorDataSource["embeds"] {
36
+ const out: NonNullable<EditorDataSource["embeds"]> = {};
37
+ for (const directive of DIRECTIVES) {
38
+ out[directive] = function AppEmbed(props: EmbedSubjectProps) {
39
+ const drawn = renderEmbed({ directive, reference: props.reference, props: props.props, fallback: props.fallback });
40
+ if (drawn !== null && drawn !== undefined) return <>{drawn}</>;
41
+ const Fallback = FALLBACK_EMBEDS[directive];
42
+ return <Fallback {...props} />;
43
+ };
44
+ }
45
+ return out;
46
+ }
47
+
48
+ export function EditorDataProvider({ adapter, renderEmbed, children }: EditorDataProviderProps) {
49
+ const cache = useMemo(() => createReadCache(), [adapter]);
50
+ const embeds = useMemo(
51
+ () => (renderEmbed ? embedsFrom(renderEmbed) : undefined),
52
+ [renderEmbed],
53
+ );
54
+ const app = useMemo<AppEditorData>(() => ({ adapter, cache, embeds }), [adapter, cache, embeds]);
55
+ const source = useMemo(() => adapterSource(adapter, cache, { embeds }), [adapter, cache, embeds]);
56
+ return (
57
+ <AppEditorContext.Provider value={app}>
58
+ <EditorDataContext.Provider value={source}>{children}</EditorDataContext.Provider>
59
+ </AppEditorContext.Provider>
60
+ );
61
+ }
62
+
63
+ /** A nested source for one document: its space's views, and drops linked from its subject. */
64
+ export function DocumentDataScope({
65
+ workspaceId,
66
+ onObjectDrop,
67
+ children,
68
+ }: {
69
+ workspaceId: string | null;
70
+ onObjectDrop?: EditorDataSource["onObjectDrop"];
71
+ children: React.ReactNode;
72
+ }) {
73
+ const { adapter, cache, embeds } = useAppEditorData();
74
+ const source = useMemo(
75
+ () => adapterSource(adapter, cache, { workspaceId, onObjectDrop, embeds }),
76
+ [adapter, cache, workspaceId, onObjectDrop, embeds],
77
+ );
78
+ return <EditorDataContext.Provider value={source}>{children}</EditorDataContext.Provider>;
79
+ }
@@ -0,0 +1,162 @@
1
+ /**
2
+ * The public types of `@synap-core/react/editor`. Self-contained on purpose:
3
+ * the published `editor.d.ts` is built from THIS module (tsup `dts.entry`), so
4
+ * a refactor inside the bundled editor cannot change the API an app compiles
5
+ * against without a change here (snapshot: `api/editor.d.ts`).
6
+ */
7
+ import type { ReactNode } from "react";
8
+
9
+ /**
10
+ * What an id names, as the pod's `GET /api/hub/resolve/:id` answers it.
11
+ * `type: "unknown"` = nothing this reader can see has the id (not a failure).
12
+ */
13
+ export interface ResolvedRef {
14
+ type: string;
15
+ displayName?: string | null;
16
+ openable?: boolean | null;
17
+ profileSlug?: string | null;
18
+ }
19
+
20
+ /** An entity row the `@` picker searches. */
21
+ export interface EditorEntity {
22
+ id: string;
23
+ title?: string | null;
24
+ profileSlug?: string;
25
+ }
26
+
27
+ /** A view row the `@` picker and the `/` menu's "Saved views" list. */
28
+ export interface EditorView {
29
+ id: string;
30
+ name?: string;
31
+ type?: string;
32
+ }
33
+
34
+ /** A document as the editor loads it. */
35
+ export interface EditorDocument {
36
+ id: string;
37
+ title: string;
38
+ content: string;
39
+ /** Pass back as `baseRevision` when saving. */
40
+ revision: number;
41
+ workspaceId: string | null;
42
+ }
43
+
44
+ /** Why a call failed. `code` is what to do (`conflict`: reload; `unauthorized`: connect again). */
45
+ export interface EditorError {
46
+ code: string;
47
+ /** The HTTP status, or null when nothing answered. */
48
+ status: number | null;
49
+ /** For logs only, never a headline. */
50
+ detail?: string;
51
+ }
52
+
53
+ /** What the pod did with a write: applied, filed for the person's review, or refused. */
54
+ export type EditorWriteResult =
55
+ | { ok: true; status: "applied" }
56
+ | { ok: true; status: "proposed"; reviewUrl: string }
57
+ | { ok: false; error: EditorError };
58
+
59
+ /** A read that failed: thrown by an adapter's reads, so it is never shown as empty. */
60
+ export class EditorReadError extends Error {
61
+ readonly error: EditorError;
62
+ constructor(error: EditorError) {
63
+ super(`Synap editor read failed: ${error.code}${error.status ? ` (${error.status})` : ""}`);
64
+ this.name = "EditorReadError";
65
+ this.error = error;
66
+ }
67
+ }
68
+
69
+ /**
70
+ * The editor's data calls. Reads throw (`EditorReadError`) on failure; writes
71
+ * answer what the pod did. `createHttpEditorAdapter` implements it against the
72
+ * app's own routes (`createEditorHandlers` in `@synap-core/sdk/connect`); a test
73
+ * or a story can implement it in memory.
74
+ */
75
+ export interface EditorDataAdapter {
76
+ /** What an id names, for a reference chip. */
77
+ resolveRef(id: string): Promise<ResolvedRef>;
78
+ /** The entities of a space, for the `@` picker. */
79
+ listEntities(workspaceId: string): Promise<EditorEntity[]>;
80
+ /** The views of a space, for the `@` picker and the `/` menu. */
81
+ listViews(workspaceId: string): Promise<EditorView[]>;
82
+ getDocument(id: string): Promise<EditorDocument>;
83
+ /** Replace the document's markdown, guarded by `baseRevision`. */
84
+ saveDocument(id: string, markdown: string, baseRevision: number): Promise<EditorWriteResult>;
85
+ /** Write a relation `sourceId --type--> targetId` (a dropped object). */
86
+ linkObjects(input: { sourceId: string; targetId: string; type: string }): Promise<EditorWriteResult>;
87
+ }
88
+
89
+ /** A pod object being dragged onto the editor (`text/x-synap-object`). */
90
+ export interface SynapDraggedObject {
91
+ id: string;
92
+ /** `entity`, `view`, `document`, or a profile slug (`post`, `person`…). */
93
+ kind: string;
94
+ label: string;
95
+ }
96
+
97
+ /** A `:::synap-*` embed, for a host that draws embeds itself (`renderEmbed`). */
98
+ export interface SynapEmbed {
99
+ directive: "synap-cell" | "synap-entity" | "synap-view";
100
+ /** Reference attributes as authored (`id`, `viewId`, `cellKey`, `instanceId`). */
101
+ reference: Record<string, string>;
102
+ props?: Record<string, unknown> | null;
103
+ /** The author's fallback, rendered. */
104
+ fallback?: ReactNode;
105
+ }
106
+
107
+ export interface EditorDataProviderProps {
108
+ adapter: EditorDataAdapter;
109
+ /**
110
+ * Draws a `:::synap-*` embed. Omitted: the author's fallback, or a chip
111
+ * naming the embedded object. Return null to draw the default.
112
+ */
113
+ renderEmbed?: (embed: SynapEmbed) => ReactNode;
114
+ children?: ReactNode;
115
+ }
116
+
117
+ export interface SynapEditorProps {
118
+ documentId: string;
119
+ /**
120
+ * The entity this document belongs to (e.g. the content piece). A dropped
121
+ * object is linked FROM it (`linkObjects`). Omitted: a drop inserts the chip
122
+ * and links nothing.
123
+ */
124
+ subjectId?: string;
125
+ /** The relation a drop writes. Default `"references"`. */
126
+ relationType?: string;
127
+ /** The space the `@` picker searches. Default: the document's own. */
128
+ workspaceId?: string;
129
+ /** Save this long after the last keystroke, in ms. Default 1500. */
130
+ autoSaveMs?: number;
131
+ editable?: boolean;
132
+ /** Opens an object a chip names (`id`, its kind). Omitted: chips are not buttons. */
133
+ onObjectClick?: (id: string, kind: string) => void;
134
+ /**
135
+ * The mounted editor's handle, for edits made from beside it (dictation, a
136
+ * quoted idea); null when it unmounts. Its edits save like typing.
137
+ */
138
+ onReady?: (handle: SynapEditorHandle | null) => void;
139
+ className?: string;
140
+ }
141
+
142
+ /** Edits a host makes from beside `<SynapEditor>`: each is the person's own, saved like typing. */
143
+ export interface SynapEditorHandle {
144
+ /** The document as markdown, as the next save would send it. */
145
+ getMarkdown(): string;
146
+ /** Plain text at the caret (never parsed as markdown). */
147
+ insertText(text: string): void;
148
+ /** Markdown blocks after the last one. */
149
+ appendMarkdown(markdown: string): void;
150
+ }
151
+
152
+ export interface SynapMarkdownProps {
153
+ content: string;
154
+ onObjectClick?: (id: string, kind: string) => void;
155
+ className?: string;
156
+ }
157
+
158
+ export interface HttpEditorAdapterOptions {
159
+ /** Where the app mounted `createEditorHandlers`. Default `/api/synap/editor`. */
160
+ basePath?: string;
161
+ fetch?: typeof fetch;
162
+ }
package/src/index.ts CHANGED
@@ -12,8 +12,8 @@
12
12
  *
13
13
  * // 2. Use hooks anywhere inside
14
14
  * function MyComponent() {
15
- * const { entities } = useSynap();
16
- * const { data } = entities.list.useQuery({ limit: 20 });
15
+ * // `useSynap` is the tRPC hook tree itself, not a function to call.
16
+ * const { data } = useSynap.entities.list.useQuery({ limit: 20 });
17
17
  * }
18
18
  * ```
19
19
  */
@@ -21,7 +21,7 @@
21
21
  export { SynapProvider, useSynapContext } from "./SynapProvider";
22
22
  export type { SynapProviderProps } from "./SynapProvider";
23
23
 
24
- // Expose the raw tRPC hooks for advanced use (useSynap().entities.list.useQuery etc.)
24
+ // Expose the raw tRPC hooks for advanced use (useSynap.entities.list.useQuery etc.)
25
25
  export { trpc as useSynap } from "./trpc";
26
26
 
27
27
  // Thin ergonomic data hooks over the SDK + TanStack Query.
@@ -0,0 +1,76 @@
1
+ /**
2
+ * One small read cache per provider (the editor's and the board's): the same
3
+ * key is asked once, a failed read stays failed (with a refetch) and never
4
+ * turns into an empty answer. `useSyncExternalStore` reads it.
5
+ */
6
+ import { useCallback, useSyncExternalStore } from "react";
7
+
8
+ export type Entry = {
9
+ status: "loading" | "ready" | "failed";
10
+ data?: unknown;
11
+ error?: unknown;
12
+ /** Bumped on every change, so `useSyncExternalStore` sees a new snapshot. */
13
+ version: number;
14
+ };
15
+
16
+ export interface ReadCache {
17
+ read(key: string, load: () => Promise<unknown>): Entry;
18
+ refetch(key: string, load: () => Promise<unknown>): void;
19
+ subscribe(listener: () => void): () => void;
20
+ }
21
+
22
+ export function createReadCache(): ReadCache {
23
+ const entries = new Map<string, Entry>();
24
+ const listeners = new Set<() => void>();
25
+ const emit = () => listeners.forEach((l) => l());
26
+
27
+ function start(key: string, load: () => Promise<unknown>, previous?: Entry): Entry {
28
+ const entry: Entry = { status: "loading", data: previous?.data, version: (previous?.version ?? 0) + 1 };
29
+ entries.set(key, entry);
30
+ load().then(
31
+ (data) => {
32
+ if (entries.get(key) !== entry) return;
33
+ entries.set(key, { status: "ready", data, version: entry.version + 1 });
34
+ emit();
35
+ },
36
+ (error: unknown) => {
37
+ if (entries.get(key) !== entry) return;
38
+ entries.set(key, { status: "failed", error, version: entry.version + 1 });
39
+ emit();
40
+ },
41
+ );
42
+ return entry;
43
+ }
44
+
45
+ return {
46
+ read(key, load) {
47
+ return entries.get(key) ?? start(key, load);
48
+ },
49
+ refetch(key, load) {
50
+ start(key, load, entries.get(key));
51
+ emit();
52
+ },
53
+ subscribe(listener) {
54
+ listeners.add(listener);
55
+ return () => listeners.delete(listener);
56
+ },
57
+ };
58
+ }
59
+
60
+ const IDLE: Entry = { status: "ready", data: undefined, version: 0 };
61
+
62
+ /** A cached read; `key: null` = not asked (disabled). */
63
+ export function useRead(cache: ReadCache, key: string | null, load: () => Promise<unknown>) {
64
+ const subscribe = useCallback((l: () => void) => cache.subscribe(l), [cache]);
65
+ // `read` starts the load on first sight; the snapshot is the stored entry
66
+ // object, stable until the cache replaces it.
67
+ const entry = useSyncExternalStore(
68
+ subscribe,
69
+ () => (key === null ? IDLE : cache.read(key, load)),
70
+ () => (key === null ? IDLE : cache.read(key, load)),
71
+ );
72
+ const refetch = useCallback(() => {
73
+ if (key !== null) cache.refetch(key, load);
74
+ }, [cache, key, load]);
75
+ return { entry, refetch };
76
+ }
package/src/trpc.ts CHANGED
@@ -2,8 +2,9 @@ import { createTRPCReact, type CreateTRPCReact } from "@trpc/react-query";
2
2
  import type { AppRouter } from "@synap-core/api-types";
3
3
 
4
4
  /**
5
- * tRPC React hooks — use via `useSynap()` from the provider context.
6
- * Exported for advanced use cases (e.g. calling `trpc.useUtils()`).
5
+ * tRPC React hooks, exported publicly as `useSynap`. Call hooks on the tree
6
+ * directly (`useSynap.entities.list.useQuery(...)`, `useSynap.useUtils()`)
7
+ * inside `<SynapProvider>`. Calling `useSynap()` itself returns undefined.
7
8
  */
8
9
  export const trpc: CreateTRPCReact<AppRouter, unknown> =
9
10
  createTRPCReact<AppRouter>();
@@ -0,0 +1,139 @@
1
+ /**
2
+ * `<SynapBoard documentId>`: the pod's tldraw board on one board document, in a
3
+ * pod app. It joins the board's LIVE room with a room ticket from the app's
4
+ * server (the same room, the same records and the same sync as the desktop,
5
+ * `useWhiteboardCollaboration`), so what one person draws, every person on the
6
+ * board sees, and the realtime server keeps it.
7
+ *
8
+ * Honest states: opening, a room that could not be opened (why, and Try
9
+ * again), a board whose saved content could not be loaded (never an empty
10
+ * board), and read-only when the room takes no writes from this person.
11
+ *
12
+ * v1 draws tldraw's own toolbar and menus; the desktop's toolbar, panels, AI
13
+ * and brand projection stay on the desktop.
14
+ */
15
+ import React, { useEffect, useMemo, useState } from "react";
16
+ import { DefaultColorThemePalette, Tldraw, type Editor, type TLEventInfo } from "@tldraw/tldraw";
17
+ import {
18
+ CollabStatusChip,
19
+ SpatialErrorState,
20
+ SpatialSpinner,
21
+ boardReadOnlyFor,
22
+ installReadonlyToolGuard,
23
+ useWhiteboardCollaboration,
24
+ } from "@synap-core/web/whiteboard/embeddable";
25
+ import { APP_SHAPE_UTILS, cardTarget } from "./shapes";
26
+ import { BOARD_COPY, roomFailedWords } from "./copy";
27
+ import type { BoardUser, SynapBoardProps } from "./types";
28
+
29
+ /** Cursor colours: tldraw's own content palette (a person's colour is content, not chrome). */
30
+ const CURSOR_HUES = ["blue", "green", "yellow", "red", "violet", "light-red", "light-blue", "light-green"] as const;
31
+ const LOCAL_ID_KEY = "synap_collab_id";
32
+
33
+ /** The desktop's anonymous cursor: an id kept on this device, named "You". */
34
+ function anonymousUser(): BoardUser {
35
+ let id: string | null = null;
36
+ try {
37
+ id = localStorage.getItem(LOCAL_ID_KEY);
38
+ if (!id) {
39
+ id = crypto.randomUUID();
40
+ localStorage.setItem(LOCAL_ID_KEY, id);
41
+ }
42
+ } catch {
43
+ // No storage (privacy mode, a server render): a cursor id for this visit.
44
+ id ??= `anon-${Math.random().toString(36).slice(2, 10)}`;
45
+ }
46
+ return { id, name: "You", color: DefaultColorThemePalette.lightMode[CURSOR_HUES[id.charCodeAt(0) % CURSOR_HUES.length]!].solid };
47
+ }
48
+
49
+ export function SynapBoard({ documentId, user, licenseKey, readOnly = false, onObjectClick, className }: SynapBoardProps) {
50
+ const me = useMemo(() => user ?? anonymousUser(), [user?.id, user?.name, user?.color]); // eslint-disable-line react-hooks/exhaustive-deps
51
+ const [editor, setEditor] = useState<Editor | null>(null);
52
+ const room = useWhiteboardCollaboration(documentId, {
53
+ user: me,
54
+ shapeUtils: APP_SHAPE_UTILS,
55
+ enabled: !!documentId,
56
+ });
57
+ const { store, status, readOnly: roomReadOnly, loadFailed, retry, roomFailure } = room;
58
+
59
+ // DLP: read-only until the store is hydrated, and while the room takes no
60
+ // writes from this person (or the host asks for it).
61
+ useEffect(() => {
62
+ if (!editor) return;
63
+ const locked = boardReadOnlyFor({ status, roomReadOnly });
64
+ if (readOnly) editor.updateInstanceState({ isReadonly: true });
65
+ else if (locked !== undefined) editor.updateInstanceState({ isReadonly: locked });
66
+ }, [editor, status, roomReadOnly, readOnly]);
67
+
68
+ useEffect(() => (editor ? installReadonlyToolGuard(editor) : undefined), [editor]);
69
+
70
+ // A double-click on a card opens what it names, in the host.
71
+ useEffect(() => {
72
+ if (!editor || !onObjectClick) return;
73
+ const onEvent = (info: TLEventInfo) => {
74
+ if (info.type !== "click" || info.name !== "double_click" || info.phase !== "up") return;
75
+ if (info.target !== "shape") return;
76
+ const target = cardTarget(info.shape as unknown as { type: string; props: Record<string, unknown> });
77
+ if (target) onObjectClick(target.id, target.kind);
78
+ };
79
+ editor.on("event", onEvent);
80
+ return () => {
81
+ editor.off("event", onEvent);
82
+ };
83
+ }, [editor, onObjectClick]);
84
+
85
+ const rootClass = ["synap-board", className].filter(Boolean).join(" ");
86
+
87
+ if (roomFailure && !store) {
88
+ return (
89
+ <div className={rootClass} data-state="failed">
90
+ <SpatialErrorState fill noun={BOARD_COPY.noun} description={roomFailedWords(roomFailure.code)} retry={retry} />
91
+ </div>
92
+ );
93
+ }
94
+ if (status === "unavailable") {
95
+ return (
96
+ <div className={rootClass} data-state="failed">
97
+ <SpatialErrorState fill noun={BOARD_COPY.noun} description={BOARD_COPY.unavailable} retry={retry} />
98
+ </div>
99
+ );
100
+ }
101
+ if (loadFailed) {
102
+ return (
103
+ <div className={rootClass} data-state="failed">
104
+ <SpatialErrorState fill noun={BOARD_COPY.noun} description={BOARD_COPY.loadFailed} retry={retry} />
105
+ </div>
106
+ );
107
+ }
108
+ if (!store) {
109
+ return (
110
+ <div className={rootClass} data-state="opening">
111
+ <SpatialSpinner size={28} />
112
+ <span className="synap-board__note">{BOARD_COPY.opening}</span>
113
+ </div>
114
+ );
115
+ }
116
+
117
+ const viewOnly = readOnly || roomReadOnly;
118
+ return (
119
+ <div className={rootClass} data-state={viewOnly ? "read-only" : "live"}>
120
+ <Tldraw
121
+ key={documentId}
122
+ store={store}
123
+ shapeUtils={APP_SHAPE_UTILS}
124
+ licenseKey={licenseKey}
125
+ onMount={(mounted: Editor) => {
126
+ setEditor(mounted);
127
+ // DLP: never writable before the store is hydrated (the effect above lifts it).
128
+ if (status !== "ready" && status !== "offline") mounted.updateInstanceState({ isReadonly: true });
129
+ }}
130
+ />
131
+ <CollabStatusChip collabStatus={status} />
132
+ {viewOnly || roomFailure ? (
133
+ <div className="synap-board__banner" role="status">
134
+ {roomFailure ? roomFailedWords(roomFailure.code) : BOARD_COPY.readOnly}
135
+ </div>
136
+ ) : null}
137
+ </div>
138
+ );
139
+ }