@open-artifact/editor-kit 0.0.0-stage → 0.1.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 (82) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +5 -0
  3. package/README.md +128 -2
  4. package/package.json +58 -4
  5. package/src/Announcer.d.ts +2 -0
  6. package/src/Announcer.js +8 -0
  7. package/src/FindBar.d.ts +31 -0
  8. package/src/FindBar.js +34 -0
  9. package/src/agent.d.ts +20 -0
  10. package/src/agent.js +40 -0
  11. package/src/announce.d.ts +18 -0
  12. package/src/announce.js +21 -0
  13. package/src/chrome.d.ts +180 -0
  14. package/src/chrome.js +108 -0
  15. package/src/collab/CommentList.d.ts +23 -0
  16. package/src/collab/CommentList.js +117 -0
  17. package/src/collab/CommentViews.d.ts +116 -0
  18. package/src/collab/CommentViews.js +531 -0
  19. package/src/collab/HistoryViews.d.ts +38 -0
  20. package/src/collab/HistoryViews.js +103 -0
  21. package/src/collab/PresenceViews.d.ts +52 -0
  22. package/src/collab/PresenceViews.js +46 -0
  23. package/src/collab/cds/cds.d.ts +148 -0
  24. package/src/collab/cds/cds.js +230 -0
  25. package/src/collab/cds/comment-card.d.ts +93 -0
  26. package/src/collab/cds/comment-card.js +211 -0
  27. package/src/collab/cds/comment-composer.d.ts +28 -0
  28. package/src/collab/cds/comment-composer.js +101 -0
  29. package/src/collab/cds/comments-css.d.ts +2 -0
  30. package/src/collab/cds/comments-css.js +3 -0
  31. package/src/collab/cds/comments.css +497 -0
  32. package/src/collab/cds/edge-piles.d.ts +69 -0
  33. package/src/collab/cds/edge-piles.js +178 -0
  34. package/src/collab/cds/layer.d.ts +41 -0
  35. package/src/collab/cds/layer.js +143 -0
  36. package/src/collab/cds/markdown.d.ts +17 -0
  37. package/src/collab/cds/markdown.js +507 -0
  38. package/src/collab/cds/shield.d.ts +28 -0
  39. package/src/collab/cds/shield.js +114 -0
  40. package/src/collab/cds/time.d.ts +2 -0
  41. package/src/collab/cds/time.js +41 -0
  42. package/src/collab/collab.d.ts +100 -0
  43. package/src/collab/collab.js +119 -0
  44. package/src/collab/comments.d.ts +147 -0
  45. package/src/collab/comments.js +287 -0
  46. package/src/collab/history-wiring.d.ts +32 -0
  47. package/src/collab/history-wiring.js +53 -0
  48. package/src/collab/history.d.ts +53 -0
  49. package/src/collab/history.js +94 -0
  50. package/src/collab/peer-colors.d.ts +123 -0
  51. package/src/collab/peer-colors.js +273 -0
  52. package/src/collab/pins.d.ts +70 -0
  53. package/src/collab/pins.js +44 -0
  54. package/src/collab/presence.d.ts +92 -0
  55. package/src/collab/presence.js +158 -0
  56. package/src/design-systems.d.ts +46 -0
  57. package/src/design-systems.js +61 -0
  58. package/src/downloads.d.ts +24 -0
  59. package/src/downloads.js +36 -0
  60. package/src/find.d.ts +64 -0
  61. package/src/find.js +147 -0
  62. package/src/index.d.ts +25 -0
  63. package/src/index.js +25 -0
  64. package/src/keys.d.ts +13 -0
  65. package/src/keys.js +20 -0
  66. package/src/merge.d.ts +23 -0
  67. package/src/merge.js +116 -0
  68. package/src/page-link.d.ts +33 -0
  69. package/src/page-link.js +75 -0
  70. package/src/project-sync.d.ts +118 -0
  71. package/src/project-sync.js +174 -0
  72. package/src/react.d.ts +16 -0
  73. package/src/react.js +16 -0
  74. package/src/roles.d.ts +33 -0
  75. package/src/roles.js +26 -0
  76. package/src/session.d.ts +42 -0
  77. package/src/session.js +37 -0
  78. package/src/shell.d.ts +56 -0
  79. package/src/shell.js +96 -0
  80. package/src/stash.d.ts +26 -0
  81. package/src/stash.js +66 -0
  82. package/src/styles.css +17 -0
@@ -0,0 +1,287 @@
1
+ /**
2
+ * Comment threads for any editor: the store (threads, comment mode, the
3
+ * open card, the draft, the list), and the thread actions over the
4
+ * `comments` capability.
5
+ *
6
+ * Editor-agnostic: what an anchor is,
7
+ * how it is labelled, where it points the agent and how the editor shows it
8
+ * are the {@link CommentsAdapter}'s. The editor hands the capability to
9
+ * {@link CommentsController.start}.
10
+ */
11
+ import { create } from 'zustand';
12
+ /** Longest message. */
13
+ export const COMMENT_TEXT_MAX = 4000;
14
+ /** Open (unresolved) thread count. */
15
+ export function openCount(threads) {
16
+ return threads.filter((t) => t.status === 'open').length;
17
+ }
18
+ export function openMessageCount(threads) {
19
+ return threads.reduce((sum, t) => (t.status === 'open' ? sum + t.messages.length : sum), 0);
20
+ }
21
+ /** The default note of a card whose anchor moved away. */
22
+ function defaultStateNote(state) {
23
+ if (state === 'detached')
24
+ return 'What this was on is gone; shown on what held it.';
25
+ if (state === 'orphaned')
26
+ return 'What this was on has been deleted.';
27
+ return null;
28
+ }
29
+ /** Creates an editor's comments controller. */
30
+ export function createComments(adapter) {
31
+ const maxThreads = adapter.maxThreads ?? 500;
32
+ const noun = adapter.noun ?? 'document';
33
+ const notify = (message) => adapter.notify?.(message);
34
+ let capability = null;
35
+ let unfollow;
36
+ /** Bumped by {@link CommentsController.stop}: a list arriving after it is dropped. */
37
+ let generation = 0;
38
+ const store = create()((set) => ({
39
+ available: false,
40
+ threads: [],
41
+ on: false,
42
+ listOpen: false,
43
+ active: null,
44
+ draft: null,
45
+ showResolved: false,
46
+ sendNew: false,
47
+ draftText: '',
48
+ replies: {},
49
+ setOn(on) {
50
+ set({ on, draft: null });
51
+ adapter.onModeChange?.(on);
52
+ },
53
+ setListOpen(listOpen) {
54
+ set({ listOpen });
55
+ },
56
+ setActive(active) {
57
+ set({ active, draft: null });
58
+ },
59
+ setDraft(draft) {
60
+ // Dropped: its text and box go too. Moved to another spot: they stay.
61
+ set(draft === null ? { draft, active: null, draftText: '', sendNew: false } : { draft, active: null });
62
+ },
63
+ setShowResolved(showResolved) {
64
+ set({ showResolved });
65
+ },
66
+ setSendNew(sendNew) {
67
+ set({ sendNew });
68
+ },
69
+ setDraftText(draftText) {
70
+ set({ draftText });
71
+ },
72
+ setReply(id, reply) {
73
+ set((state) => ({ replies: { ...state.replies, [id]: reply } }));
74
+ },
75
+ }));
76
+ /** Anchors parsed once per stored string. */
77
+ const parsed = new Map();
78
+ const anchorOf = (thread) => {
79
+ let anchor = parsed.get(thread.anchor);
80
+ if (anchor === undefined) {
81
+ anchor = adapter.parse(thread.anchor);
82
+ if (parsed.size > 2000)
83
+ parsed.clear();
84
+ parsed.set(thread.anchor, anchor);
85
+ }
86
+ return anchor;
87
+ };
88
+ const failed = (error) => {
89
+ notify({ title: 'The comment could not be saved', description: error instanceof Error ? error.message : String(error) });
90
+ };
91
+ const put = (thread) => {
92
+ store.setState((state) => ({ threads: state.threads.map((t) => (t.id === thread.id ? thread : t)) }));
93
+ adapter.heard?.([thread]);
94
+ };
95
+ const checkText = (text) => {
96
+ if (adapter.checkText)
97
+ return adapter.checkText(text);
98
+ return text.trim().slice(0, COMMENT_TEXT_MAX) || undefined;
99
+ };
100
+ const canComment = () => Boolean(capability) && adapter.canComment();
101
+ const canSendToAgent = () => Boolean(capability) && adapter.canSendToAgent();
102
+ const canRemove = () => Boolean(capability) && (adapter.canRemove ? adapter.canRemove() : adapter.canComment());
103
+ const controller = {
104
+ store,
105
+ adapter,
106
+ async start(found, open) {
107
+ if (!found)
108
+ return;
109
+ capability = found;
110
+ const started = generation;
111
+ store.setState({ available: true });
112
+ try {
113
+ const threads = await found.list();
114
+ if (started !== generation)
115
+ return;
116
+ store.setState({ threads });
117
+ adapter.heard?.(threads);
118
+ }
119
+ catch {
120
+ // The list arrives with the first change.
121
+ }
122
+ if (started !== generation)
123
+ return;
124
+ unfollow = found.onChange((threads) => {
125
+ const active = store.getState().active;
126
+ store.setState({ threads, active: active && threads.some((t) => t.id === active) ? active : null });
127
+ adapter.heard?.(threads);
128
+ });
129
+ const thread = open ? store.getState().threads.find((t) => t.id === open) : undefined;
130
+ if (thread)
131
+ controller.reveal(thread);
132
+ },
133
+ stop() {
134
+ generation += 1;
135
+ unfollow?.();
136
+ unfollow = undefined;
137
+ },
138
+ capability: () => capability,
139
+ canComment,
140
+ canSendToAgent,
141
+ canRemove,
142
+ anchorOf,
143
+ labelOf: (anchor) => adapter.label(anchor),
144
+ stateOf: (anchor) => adapter.state?.(anchor) ?? 'ok',
145
+ stateNote: (state) => (adapter.stateNote ? adapter.stateNote(state ?? 'ok') : defaultStateNote(state)),
146
+ async create(anchor, text, options) {
147
+ if (!capability)
148
+ return false;
149
+ const body = checkText(text);
150
+ if (!body)
151
+ return false;
152
+ if (store.getState().threads.length >= maxThreads) {
153
+ notify({ title: `This ${noun} already has ${maxThreads} comments` });
154
+ return false;
155
+ }
156
+ try {
157
+ const detail = adapter.detail?.(anchor);
158
+ const thread = await capability.create({
159
+ anchor: adapter.serialize(anchor),
160
+ label: adapter.label(anchor),
161
+ ...(detail !== undefined ? { detail } : {}),
162
+ location: adapter.location?.(anchor) ?? {},
163
+ text: body,
164
+ });
165
+ store.setState((state) => ({
166
+ threads: state.threads.some((t) => t.id === thread.id) ? state.threads : [...state.threads, thread],
167
+ draft: null,
168
+ draftText: '',
169
+ sendNew: false,
170
+ active: thread.id,
171
+ }));
172
+ adapter.heard?.([thread]);
173
+ if (options?.send && canSendToAgent())
174
+ await controller.sendToAgent(thread.id);
175
+ return true;
176
+ }
177
+ catch (error) {
178
+ failed(error);
179
+ return false;
180
+ }
181
+ },
182
+ async reply(id, text, options) {
183
+ if (!capability)
184
+ return false;
185
+ const body = checkText(text);
186
+ if (!body)
187
+ return false;
188
+ try {
189
+ let thread = await capability.reply(id, body);
190
+ // A reply to a resolved thread reopens it.
191
+ if (thread.status === 'resolved')
192
+ thread = await capability.setResolved(id, false);
193
+ put(thread);
194
+ store.setState((state) => {
195
+ const { [id]: _, ...replies } = state.replies;
196
+ return { replies };
197
+ });
198
+ if (options?.send && canSendToAgent())
199
+ await controller.sendToAgent(id);
200
+ return true;
201
+ }
202
+ catch (error) {
203
+ failed(error);
204
+ return false;
205
+ }
206
+ },
207
+ async resolve(id, resolved) {
208
+ if (!capability)
209
+ return;
210
+ try {
211
+ put(await capability.setResolved(id, resolved));
212
+ const state = store.getState();
213
+ if (resolved && state.active === id && !state.showResolved)
214
+ store.setState({ active: null });
215
+ }
216
+ catch (error) {
217
+ failed(error);
218
+ }
219
+ },
220
+ async remove(id, messageId) {
221
+ if (!capability || (adapter.canRemove && !adapter.canRemove()))
222
+ return;
223
+ try {
224
+ await capability.remove(id, messageId);
225
+ if (!messageId)
226
+ store.setState((state) => ({ threads: state.threads.filter((t) => t.id !== id), active: state.active === id ? null : state.active }));
227
+ }
228
+ catch (error) {
229
+ failed(error);
230
+ }
231
+ },
232
+ async move(id, anchor) {
233
+ if (!capability)
234
+ return;
235
+ try {
236
+ put(await capability.move(id, adapter.serialize(anchor), adapter.location?.(anchor)));
237
+ }
238
+ catch (error) {
239
+ failed(error);
240
+ }
241
+ },
242
+ async sendToAgent(id) {
243
+ if (!capability || !canSendToAgent())
244
+ return false;
245
+ const thread = adapter.sendToAgent ? store.getState().threads.find((t) => t.id === id) : undefined;
246
+ if (adapter.sendToAgent)
247
+ return thread ? adapter.sendToAgent(thread, anchorOf(thread)) : false;
248
+ try {
249
+ put(await capability.sendToAgent(id));
250
+ notify({ title: `Sent to ${adapter.agentName?.() || 'the agent'}` });
251
+ return true;
252
+ }
253
+ catch (error) {
254
+ failed(error);
255
+ return false;
256
+ }
257
+ },
258
+ async sendAllToAgent() {
259
+ const open = store.getState().threads.filter((t) => controller.canSendThread(t));
260
+ for (const thread of open)
261
+ await controller.sendToAgent(thread.id);
262
+ },
263
+ canSendThread(thread) {
264
+ if (thread.status !== 'open')
265
+ return false;
266
+ const last = thread.messages.at(-1);
267
+ if (!last || last.author.kind !== 'person')
268
+ return false;
269
+ // Not sent yet, or the agent answered and a person wrote since.
270
+ return !thread.agent || thread.agent.status === 'replied';
271
+ },
272
+ reveal(thread) {
273
+ adapter.reveal?.(anchorOf(thread));
274
+ store.getState().setActive(thread.id);
275
+ },
276
+ show(thread) {
277
+ const state = store.getState();
278
+ if (!state.on)
279
+ state.setOn(true);
280
+ if (thread.status === 'resolved' && !store.getState().showResolved)
281
+ store.getState().setShowResolved(true);
282
+ controller.reveal(thread);
283
+ },
284
+ viewerName: () => adapter.viewerName?.() || 'You',
285
+ };
286
+ return controller;
287
+ }
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Editor-agnostic version-history plumbing: reporting the history to a
3
+ * Shell, answering its `history` command, following who may restore, and
4
+ * reading a version's files a few at a time.
5
+ *
6
+ * Everything here takes the capability and callbacks as parameters (no
7
+ * editor stores), so any editor can wire its own panel and preview to it.
8
+ */
9
+ import type { ChromeCommand, HistoryCapability } from '@open-artifact/runtime';
10
+ /** What {@link wireVersionHistory} connects. */
11
+ export interface VersionHistoryWiring {
12
+ history: Pick<HistoryCapability, 'list' | 'onChange'>;
13
+ /** The viewer's role may restore (owner or editor); the host's listing has the last word. */
14
+ roleMayRestore: boolean;
15
+ /** Sets part of the Shell report (`{history: true}` on start, `{history: undefined}` on stop). */
16
+ report(part: {
17
+ history?: boolean;
18
+ }): void;
19
+ /** Adds a Shell command handler; returns its remover. */
20
+ onCommand(handler: (command: ChromeCommand) => void): () => void;
21
+ /** Opens or closes the history panel (the Shell's History button). */
22
+ toggle(): void;
23
+ /** Whether this viewer may restore now. */
24
+ setCanRestore(can: boolean): void;
25
+ }
26
+ /** Connects a history capability to a page and its Shell. Returns a stop function. */
27
+ export declare function wireVersionHistory(wiring: VersionHistoryWiring): () => void;
28
+ /**
29
+ * Reads the paths of version `n` that `wanted` keeps, `workers` at a time,
30
+ * as `[path, text]` pairs (unreadable paths are left out).
31
+ */
32
+ export declare function readVersionFiles(history: Pick<HistoryCapability, 'files' | 'read'>, n: number, wanted: (paths: string[]) => string[], workers?: number): Promise<Array<readonly [string, string]>>;
@@ -0,0 +1,53 @@
1
+ /**
2
+ * Editor-agnostic version-history plumbing: reporting the history to a
3
+ * Shell, answering its `history` command, following who may restore, and
4
+ * reading a version's files a few at a time.
5
+ *
6
+ * Everything here takes the capability and callbacks as parameters (no
7
+ * editor stores), so any editor can wire its own panel and preview to it.
8
+ */
9
+ /** Connects a history capability to a page and its Shell. Returns a stop function. */
10
+ export function wireVersionHistory(wiring) {
11
+ let stopped = false;
12
+ wiring.setCanRestore(wiring.roleMayRestore);
13
+ wiring.report({ history: true });
14
+ const refresh = () => {
15
+ wiring.history.list().then((listing) => {
16
+ if (!stopped)
17
+ wiring.setCanRestore(listing.canRestore && wiring.roleMayRestore);
18
+ }, () => undefined);
19
+ };
20
+ refresh();
21
+ const stops = [
22
+ wiring.history.onChange(refresh),
23
+ wiring.onCommand((command) => {
24
+ if (command.cmd === 'history')
25
+ wiring.toggle();
26
+ }),
27
+ ];
28
+ return () => {
29
+ stopped = true;
30
+ for (const stop of stops)
31
+ stop();
32
+ wiring.report({ history: undefined });
33
+ };
34
+ }
35
+ /**
36
+ * Reads the paths of version `n` that `wanted` keeps, `workers` at a time,
37
+ * as `[path, text]` pairs (unreadable paths are left out).
38
+ */
39
+ export async function readVersionFiles(history, n, wanted, workers = 12) {
40
+ const paths = wanted(Object.keys(await history.files(n)));
41
+ const texts = [];
42
+ let next = 0;
43
+ const worker = async () => {
44
+ while (next < paths.length) {
45
+ const path = paths[next++];
46
+ const text = await history.read(n, path).catch(() => null);
47
+ if (text !== null)
48
+ texts.push([path, text]);
49
+ }
50
+ };
51
+ await Promise.all(Array.from({ length: Math.min(workers, paths.length) }, worker));
52
+ return texts;
53
+ }
@@ -0,0 +1,53 @@
1
+ /**
2
+ * Version history for any editor: the `history` capability, the panel's
3
+ * open state, a read-only preview of a past version, and restores (whole,
4
+ * or some files of it).
5
+ *
6
+ * Editor-agnostic: what a preview
7
+ * holds (`P`) and how it is read from a version is the editor's
8
+ * {@link HistoryAdapter}. Restores go through the host, which writes the
9
+ * files the way a page would; the editor's sync merges them in like any
10
+ * other change.
11
+ */
12
+ import type { HistoryCapability } from '@open-artifact/runtime';
13
+ import { type StoreApi, type UseBoundStore } from 'zustand';
14
+ /** What an editor tells history. `P` is its loaded preview of one version. */
15
+ export interface HistoryAdapter<P> {
16
+ /** Shows a short message (a toast); default: nothing. */
17
+ notify?(message: {
18
+ title: string;
19
+ description?: string;
20
+ }): void;
21
+ /** Reads what the editor draws of version `n` (its files through `history.files`/`read`). */
22
+ loadPreview(history: HistoryCapability, n: number): Promise<P>;
23
+ /** What the document is called in messages (default `document`). */
24
+ noun?: string;
25
+ }
26
+ /** The history store. */
27
+ export interface HistoryState<P> {
28
+ available: boolean;
29
+ open: boolean;
30
+ /** The version previewed (`null`: the current files). */
31
+ previewing: number | null;
32
+ preview: P | null;
33
+ loading: boolean;
34
+ error: string | null;
35
+ canRestore: boolean;
36
+ setOpen(open: boolean): void;
37
+ }
38
+ /** One editor's history. */
39
+ export interface HistoryController<P> {
40
+ readonly store: UseBoundStore<StoreApi<HistoryState<P>>>;
41
+ start(capability: HistoryCapability | null): void;
42
+ capability(): HistoryCapability | null;
43
+ /** Opens or closes the panel. */
44
+ toggle(open?: boolean): void;
45
+ /** Shows version `n` read-only (`null`: back to the current files). */
46
+ preview(n: number | null): Promise<void>;
47
+ /** Restores the whole of version `n`. */
48
+ restore(n: number): Promise<void>;
49
+ /** Restores some artifact paths of version `n`; resolves to the paths that changed, or `null` when it failed. */
50
+ restorePaths(n: number, paths: string[], what: string): Promise<string[] | null>;
51
+ }
52
+ /** Creates an editor's history. */
53
+ export declare function createHistory<P>(adapter: HistoryAdapter<P>): HistoryController<P>;
@@ -0,0 +1,94 @@
1
+ /**
2
+ * Version history for any editor: the `history` capability, the panel's
3
+ * open state, a read-only preview of a past version, and restores (whole,
4
+ * or some files of it).
5
+ *
6
+ * Editor-agnostic: what a preview
7
+ * holds (`P`) and how it is read from a version is the editor's
8
+ * {@link HistoryAdapter}. Restores go through the host, which writes the
9
+ * files the way a page would; the editor's sync merges them in like any
10
+ * other change.
11
+ */
12
+ import { create } from 'zustand';
13
+ const message = (error) => (error instanceof Error ? error.message : String(error));
14
+ /** Creates an editor's history. */
15
+ export function createHistory(adapter) {
16
+ const noun = adapter.noun ?? 'document';
17
+ const notify = (message) => adapter.notify?.(message);
18
+ let capability = null;
19
+ let request = 0;
20
+ const store = create()((set) => ({
21
+ available: false,
22
+ open: false,
23
+ previewing: null,
24
+ preview: null,
25
+ loading: false,
26
+ error: null,
27
+ canRestore: false,
28
+ setOpen(open) {
29
+ set(open ? { open } : { open, previewing: null, preview: null, error: null, loading: false });
30
+ },
31
+ }));
32
+ const controller = {
33
+ store,
34
+ start(found) {
35
+ capability = found;
36
+ if (!found)
37
+ return;
38
+ store.setState({ available: true });
39
+ const refresh = () => {
40
+ found.list().then((listing) => store.setState({ canRestore: listing.canRestore }), () => undefined);
41
+ };
42
+ refresh();
43
+ found.onChange(refresh);
44
+ },
45
+ capability: () => capability,
46
+ toggle(open) {
47
+ const state = store.getState();
48
+ if (!state.available)
49
+ return;
50
+ state.setOpen(open ?? !state.open);
51
+ },
52
+ async preview(n) {
53
+ const id = ++request;
54
+ if (n === null || !capability) {
55
+ store.setState({ previewing: null, preview: null, loading: false, error: null });
56
+ return;
57
+ }
58
+ store.setState({ previewing: n, loading: true, error: null });
59
+ try {
60
+ const preview = await adapter.loadPreview(capability, n);
61
+ if (id === request)
62
+ store.setState({ preview, loading: false });
63
+ }
64
+ catch (error) {
65
+ if (id === request)
66
+ store.setState({ loading: false, error: message(error) });
67
+ }
68
+ },
69
+ async restore(n) {
70
+ if (!capability)
71
+ return;
72
+ try {
73
+ const result = await capability.restore(n);
74
+ notify({ title: result.changed.length ? `Restored version ${n}` : `The ${noun} already matches version ${n}` });
75
+ await controller.preview(null);
76
+ }
77
+ catch (error) {
78
+ notify({ title: 'The version could not be restored', description: message(error) });
79
+ }
80
+ },
81
+ async restorePaths(n, paths, what) {
82
+ if (!capability)
83
+ return null;
84
+ try {
85
+ return (await capability.restore(n, paths)).changed;
86
+ }
87
+ catch (error) {
88
+ notify({ title: `${what} could not be restored`, description: message(error) });
89
+ return null;
90
+ }
91
+ },
92
+ };
93
+ return controller;
94
+ }
@@ -0,0 +1,123 @@
1
+ /**
2
+ * People's colors that never clash (cursors, selections, frames, avatars):
3
+ * eight colors, picked so people online at once do not share one. Unlike
4
+ * the plain hash of `peerColor` (`presence.ts`), pages here *claim*
5
+ * their color over presence.
6
+ *
7
+ * Alone, a person wears the color their id hashes to ({@link peerColorFromId}),
8
+ * or the one they wore last time. With others online, each page *claims*
9
+ * its color: it publishes `{c, t}` (the color, and when it settled on it;
10
+ * `t` is `null` while it has not). The earliest claim keeps a color
11
+ * ({@link peerColorClaimPrecedes}); a later page that clashes moves on to
12
+ * the next free color in the palette. Pages of the same person adopt that
13
+ * person's earliest claim, so one person keeps one color across tabs.
14
+ *
15
+ * {@link createPeerColorKeeper} runs this for one page:
16
+ * - it settles {@link PEER_COLOR_SETTLE_MS} after the page shows, on the
17
+ * person's own earlier claim or else the least used free color;
18
+ * - every {@link PEER_COLOR_RECONCILE_MS} (and whenever peers change) it
19
+ * looks again: an earlier clash moves it on (a few times a minute at most);
20
+ * - a page hidden for {@link PEER_COLOR_RELEASE_MS} gives its claim up.
21
+ *
22
+ * One color stays reserved ({@link NEVER_GIVEN_PEER_COLORS}): the one
23
+ * nearest the agent's, so people never look like the agent.
24
+ *
25
+ * Pure (timers and storage are injected): unit-tested. {@link keptPeerColor}
26
+ * and {@link PEER_COLOR_TIMERS} are the browser's storage and timers for it.
27
+ */
28
+ /** The palette. Each reads with {@link inkOnPeerColor} text in light and dark themes. */
29
+ export declare const PEER_COLOR_PALETTE: readonly ["#785ee8", "#dc3c3d", "#019c7f", "#fbb315", "#ce447d", "#10a122", "#257de0", "#d25f25"];
30
+ /** A palette color. */
31
+ export type PeerColor = (typeof PEER_COLOR_PALETTE)[number];
32
+ /** Colors never given to people: the purple nearest the agent's own color. */
33
+ export declare const NEVER_GIVEN_PEER_COLORS: readonly string[];
34
+ /** How long after a page shows it settles its color, ms. */
35
+ export declare const PEER_COLOR_SETTLE_MS = 1500;
36
+ /** How often a page looks at its color again, ms. */
37
+ export declare const PEER_COLOR_RECONCILE_MS = 2000;
38
+ /** How long a hidden page keeps its claim, ms. */
39
+ export declare const PEER_COLOR_RELEASE_MS = 8000;
40
+ /** The palette from `start` on (wrapping), without `exclude`. */
41
+ export declare function rotatePeerColors(start: string, exclude?: readonly string[]): string[];
42
+ /** A palette color, lower-cased; `undefined` for anything else. */
43
+ export declare function normalizePeerColor(color: unknown): PeerColor | undefined;
44
+ /** The color an id hashes to (never a reserved one): what a person wears alone. */
45
+ export declare function peerColorFromId(id: string): string;
46
+ /** The color a peer wears: the one it published, else its id's. */
47
+ export declare function peerColorFor(published: unknown, id: string): string;
48
+ /** Text color on a `#rrggbb` background: near-black where white would read poorly (contrast under 3:1), else white. */
49
+ export declare function inkOnPeerColor(hex: string): '#0b0b0b' | '#ffffff';
50
+ /** `color` when free, else the palette color after it worn by the fewest of `taken`. */
51
+ export declare function leastUsedPeerColor(color: string, taken: readonly string[], neverGiven?: readonly string[]): string;
52
+ /** Another page's color claim. */
53
+ export interface PeerColorClaim {
54
+ /** The person (their user id). */
55
+ key: string;
56
+ /** The page (peer id). */
57
+ peer: string;
58
+ /** The page is this person's (another tab of theirs). */
59
+ own: boolean;
60
+ /** The color claimed. */
61
+ c: string;
62
+ /** When the page settled on it (epoch ms). */
63
+ t: number;
64
+ }
65
+ /** True when claim `a` (by `aKey`) came before claim `b` (by `bKey`): earlier, or as early with the smaller key. */
66
+ export declare function peerColorClaimPrecedes(a: {
67
+ t: number;
68
+ }, aKey: string, b: {
69
+ t: number;
70
+ }, bKey: string): boolean;
71
+ /** Claims, earliest first (see {@link peerColorClaimPrecedes}). */
72
+ export declare function sortPeerColorClaims<T extends {
73
+ t: number;
74
+ key: string;
75
+ }>(claims: readonly T[]): T[];
76
+ /** Colors other people claim (this person's other pages aside). */
77
+ export declare function takenPeerColors(claims: readonly PeerColorClaim[]): string[];
78
+ /** What a page publishes about its color: `t` is `null` while it has not settled. */
79
+ export interface PublishedPeerColor {
80
+ c: string;
81
+ t: number | null;
82
+ }
83
+ /** Options of {@link createPeerColorKeeper}. */
84
+ export interface PeerColorKeeperOptions {
85
+ /** This person's id (it hashes to the first color tried, and breaks ties). */
86
+ id: string;
87
+ /** This page's peer id (breaks ties between this person's pages). */
88
+ peer: string;
89
+ /** Publishes this page's claim. */
90
+ publish(claim: PublishedPeerColor): void;
91
+ /** Other pages' claims (this page left out; agents left out). */
92
+ claims(): readonly PeerColorClaim[];
93
+ /** The color this person settled on last time. */
94
+ kept: {
95
+ read(): string | null;
96
+ write(color: string): void;
97
+ };
98
+ now(): number;
99
+ /** Runs `run` once after `ms`; returns a function that cancels. */
100
+ after(run: () => void, ms: number): () => void;
101
+ /** Runs `run` every `ms`; returns a function that stops. */
102
+ every(run: () => void, ms: number): () => void;
103
+ /** Colors never given (default {@link NEVER_GIVEN_PEER_COLORS}). */
104
+ neverGiven?: readonly string[];
105
+ }
106
+ /** Keeps one page's color. */
107
+ export interface PeerColorKeeper {
108
+ /** The color this page wears now. */
109
+ worn(): string;
110
+ /** Call when other pages' claims changed. */
111
+ heard(): void;
112
+ /** Call when the page shows (and once at start, when it is visible). */
113
+ here(): void;
114
+ /** Call when the page is hidden. */
115
+ away(): void;
116
+ dispose(): void;
117
+ }
118
+ /** Keeps one page's color (see the module comment); `onChange` is told when it changes. */
119
+ export declare function createPeerColorKeeper(options: PeerColorKeeperOptions, onChange?: () => void): PeerColorKeeper;
120
+ /** The color a person settled on last time, kept in local storage under `key` (wrapped: storage may be missing or refuse). */
121
+ export declare function keptPeerColor(key: string): PeerColorKeeperOptions['kept'];
122
+ /** The real clock and timers for {@link createPeerColorKeeper}. */
123
+ export declare const PEER_COLOR_TIMERS: Pick<PeerColorKeeperOptions, 'now' | 'after' | 'every'>;