@openartifactsai/editor-kit 0.0.0-stage → 0.23.0-rc.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 (120) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +5 -0
  3. package/README.md +143 -2
  4. package/package.json +67 -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 +37 -0
  9. package/src/FoldToolbar.d.ts +58 -0
  10. package/src/FoldToolbar.js +438 -0
  11. package/src/PanelEdge.d.ts +20 -0
  12. package/src/PanelEdge.js +74 -0
  13. package/src/VideoShrinkNotice.d.ts +10 -0
  14. package/src/VideoShrinkNotice.js +81 -0
  15. package/src/WheelZoomItem.d.ts +12 -0
  16. package/src/WheelZoomItem.js +18 -0
  17. package/src/agent.d.ts +68 -0
  18. package/src/agent.js +113 -0
  19. package/src/announce.d.ts +21 -0
  20. package/src/announce.js +31 -0
  21. package/src/chrome.d.ts +208 -0
  22. package/src/chrome.js +148 -0
  23. package/src/clipboard.d.ts +19 -0
  24. package/src/clipboard.js +48 -0
  25. package/src/collab/CommentList.d.ts +32 -0
  26. package/src/collab/CommentList.js +165 -0
  27. package/src/collab/CommentViews.d.ts +131 -0
  28. package/src/collab/CommentViews.js +619 -0
  29. package/src/collab/HistoryViews.d.ts +38 -0
  30. package/src/collab/HistoryViews.js +103 -0
  31. package/src/collab/PresenceViews.d.ts +53 -0
  32. package/src/collab/PresenceViews.js +48 -0
  33. package/src/collab/cds/cds.d.ts +151 -0
  34. package/src/collab/cds/cds.js +231 -0
  35. package/src/collab/cds/comment-card.d.ts +113 -0
  36. package/src/collab/cds/comment-card.js +230 -0
  37. package/src/collab/cds/comment-composer.d.ts +35 -0
  38. package/src/collab/cds/comment-composer.js +125 -0
  39. package/src/collab/cds/comments-css.d.ts +2 -0
  40. package/src/collab/cds/comments-css.js +3 -0
  41. package/src/collab/cds/comments.css +504 -0
  42. package/src/collab/cds/edge-piles.d.ts +69 -0
  43. package/src/collab/cds/edge-piles.js +178 -0
  44. package/src/collab/cds/layer.d.ts +41 -0
  45. package/src/collab/cds/layer.js +144 -0
  46. package/src/collab/cds/markdown.d.ts +20 -0
  47. package/src/collab/cds/markdown.js +534 -0
  48. package/src/collab/cds/shield.d.ts +28 -0
  49. package/src/collab/cds/shield.js +114 -0
  50. package/src/collab/cds/time.d.ts +2 -0
  51. package/src/collab/cds/time.js +41 -0
  52. package/src/collab/collab.d.ts +102 -0
  53. package/src/collab/collab.js +121 -0
  54. package/src/collab/comments.d.ts +272 -0
  55. package/src/collab/comments.js +596 -0
  56. package/src/collab/history-wiring.d.ts +32 -0
  57. package/src/collab/history-wiring.js +53 -0
  58. package/src/collab/history.d.ts +59 -0
  59. package/src/collab/history.js +96 -0
  60. package/src/collab/mentions/mention-list.d.ts +63 -0
  61. package/src/collab/mentions/mention-list.js +257 -0
  62. package/src/collab/mentions.d.ts +112 -0
  63. package/src/collab/mentions.js +164 -0
  64. package/src/collab/peer-colors.d.ts +123 -0
  65. package/src/collab/peer-colors.js +273 -0
  66. package/src/collab/pins.d.ts +70 -0
  67. package/src/collab/pins.js +44 -0
  68. package/src/collab/presence.d.ts +92 -0
  69. package/src/collab/presence.js +158 -0
  70. package/src/design-systems.d.ts +46 -0
  71. package/src/design-systems.js +61 -0
  72. package/src/downloads.d.ts +31 -0
  73. package/src/downloads.js +46 -0
  74. package/src/file-drop.d.ts +33 -0
  75. package/src/file-drop.js +36 -0
  76. package/src/find.d.ts +64 -0
  77. package/src/find.js +147 -0
  78. package/src/follow.d.ts +141 -0
  79. package/src/follow.js +389 -0
  80. package/src/index.d.ts +32 -0
  81. package/src/index.js +32 -0
  82. package/src/keys.d.ts +18 -0
  83. package/src/keys.js +42 -0
  84. package/src/menu-fit.d.ts +12 -0
  85. package/src/menu-fit.js +9 -0
  86. package/src/merge.d.ts +23 -0
  87. package/src/merge.js +116 -0
  88. package/src/page-link.d.ts +33 -0
  89. package/src/page-link.js +75 -0
  90. package/src/project-sync.d.ts +161 -0
  91. package/src/project-sync.js +319 -0
  92. package/src/react.d.ts +20 -0
  93. package/src/react.js +20 -0
  94. package/src/read-retries.d.ts +55 -0
  95. package/src/read-retries.js +125 -0
  96. package/src/right-drag-pan.d.ts +128 -0
  97. package/src/right-drag-pan.js +253 -0
  98. package/src/roles.d.ts +39 -0
  99. package/src/roles.js +27 -0
  100. package/src/session.d.ts +56 -0
  101. package/src/session.js +57 -0
  102. package/src/shell.d.ts +60 -0
  103. package/src/shell.js +111 -0
  104. package/src/stash.d.ts +26 -0
  105. package/src/stash.js +69 -0
  106. package/src/styles.css +17 -0
  107. package/src/toolbar-fold.d.ts +106 -0
  108. package/src/toolbar-fold.js +130 -0
  109. package/src/video-shrink/index.d.ts +8 -0
  110. package/src/video-shrink/index.js +7 -0
  111. package/src/video-shrink/plan.d.ts +92 -0
  112. package/src/video-shrink/plan.js +133 -0
  113. package/src/video-shrink/protocol.d.ts +29 -0
  114. package/src/video-shrink/protocol.js +2 -0
  115. package/src/video-shrink/queue.d.ts +69 -0
  116. package/src/video-shrink/queue.js +287 -0
  117. package/src/video-shrink/worker.d.ts +8 -0
  118. package/src/video-shrink/worker.js +223 -0
  119. package/src/wheel-zoom.d.ts +14 -0
  120. package/src/wheel-zoom.js +48 -0
@@ -0,0 +1,164 @@
1
+ /**
2
+ * `@` in a comment box: the name being typed before the caret, who it can name, what a pick puts in the text, and whom
3
+ * a message names when it is sent. Pure: no DOM.
4
+ *
5
+ * People are named by their display name (a message's `to` holds it); the agent by {@link AGENT_KEY}.
6
+ */
7
+ /** The `to` entry that names the agent. */
8
+ export const AGENT_KEY = 'agent';
9
+ /** Most rows the list shows, the agent's included. */
10
+ export const MENTION_ROWS = 8;
11
+ /** Most different people one comment may name. */
12
+ export const MENTION_PEOPLE_LIMIT = 32;
13
+ const WORD = String.raw `[\p{L}\p{M}\p{N}_.'’-]`;
14
+ /** Before the caret: `@` at the start or after a space or an opening bracket, then up to three words of a name. */
15
+ const TYPING = new RegExp(String.raw `(?:^|[\s([{])@(${WORD}{1,40}(?: ${WORD}{0,40}){0,2})?$`, 'u');
16
+ /** The `@name` typed just before `caret`, or `null` when the text there is not one. */
17
+ export function typedMention(text, caret) {
18
+ const head = text.slice(0, caret);
19
+ const found = TYPING.exec(head);
20
+ if (found === null)
21
+ return null;
22
+ const query = found[1] ?? '';
23
+ return { start: head.length - query.length - 1, end: head.length, query };
24
+ }
25
+ /** How names and queries are compared. */
26
+ export const foldName = (text) => text.trim().toLocaleLowerCase();
27
+ /** Whether `name`, or one of its words, starts with `query` (an empty query matches everyone). */
28
+ export function nameMatches(name, query) {
29
+ const wanted = foldName(query);
30
+ if (wanted === '')
31
+ return true;
32
+ const folded = name.toLocaleLowerCase();
33
+ return folded.startsWith(wanted) || folded.split(/\s+/).some((word) => word.startsWith(wanted));
34
+ }
35
+ /** A name as it is written after `@`: no `<`, `>` or `@`; `someone` when nothing is left. */
36
+ export function mentionName(name) {
37
+ return name.replace(/[<>@]/g, '').trim() || 'someone';
38
+ }
39
+ /** The rows for a query: the agent first when it matches, then the people who match, {@link MENTION_ROWS} at most. */
40
+ export function mentionOptions({ query, agentName, agentListed, people, self }) {
41
+ const rows = [];
42
+ const wanted = foldName(query);
43
+ const agentFolded = foldName(agentName);
44
+ if (agentListed && agentFolded.startsWith(wanted))
45
+ rows.push({ kind: 'agent', key: AGENT_KEY, label: agentName });
46
+ const seen = new Set([AGENT_KEY]);
47
+ const selfName = foldName(self.name);
48
+ for (const person of people) {
49
+ if (rows.length >= MENTION_ROWS)
50
+ break;
51
+ const key = foldName(person.key);
52
+ const name = foldName(person.name);
53
+ if (key === '' || name === '' || seen.has(key))
54
+ continue;
55
+ if ((self.id !== undefined && person.id === self.id) || name === selfName)
56
+ continue;
57
+ // Someone whose name starts with the agent's could pass for it.
58
+ if (agentFolded !== '' && name.startsWith(agentFolded))
59
+ continue;
60
+ if (!nameMatches(person.name, query))
61
+ continue;
62
+ seen.add(key);
63
+ rows.push({ kind: 'person', key: person.key, label: person.name });
64
+ }
65
+ return rows;
66
+ }
67
+ /** The text with `typed` replaced by the option's `@name` and a space, and where the caret goes. */
68
+ export function applyMention(text, typed, option) {
69
+ const name = mentionName(option.label);
70
+ const word = `@${name} `;
71
+ return { text: text.slice(0, typed.start) + word + text.slice(typed.end), caret: typed.start + word.length, name };
72
+ }
73
+ const escapeRegExp = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
74
+ /**
75
+ * `@name` as a whole: after the start, a space or an opening bracket; a name ending in a Latin letter, digit or `_`
76
+ * must end there (`@Bob`, not `@Bobby`), any other may run into what follows (a script written without spaces).
77
+ */
78
+ function namePattern(name, flags) {
79
+ const tail = /[A-Za-z0-9_]$/.test(name) ? '(?![A-Za-z0-9_])' : '';
80
+ return new RegExp(`(?<=^|[\\s([{])@${escapeRegExp(name)}${tail}`, flags);
81
+ }
82
+ /** Whether `text` has `@name` in it (case ignored). */
83
+ export function mentionsName(text, name) {
84
+ return name.trim() !== '' && namePattern(name, 'iu').test(text);
85
+ }
86
+ /**
87
+ * Whom a message names: {@link AGENT_KEY} when it mentions the agent (and the agent may be asked), then each picked
88
+ * person whose `@name` is still in the text. A name typed without picking it names no one.
89
+ */
90
+ export function mentionTargets(text, picks, agent) {
91
+ const keys = [];
92
+ if (agent.listed && mentionsName(text, agent.name))
93
+ keys.push(AGENT_KEY);
94
+ // Longer names first, each blanked out once found: `@Bob Smith` names Bob Smith, not also a Bob picked earlier.
95
+ let rest = text;
96
+ const named = new Set();
97
+ for (const pick of [...picks].sort((a, b) => b.name.length - a.name.length)) {
98
+ if (!mentionsName(rest, pick.name))
99
+ continue;
100
+ named.add(pick);
101
+ rest = rest.replace(namePattern(pick.name, 'giu'), (found) => ' '.repeat(found.length));
102
+ }
103
+ for (const pick of picks) {
104
+ if (keys.includes(pick.key) || !named.has(pick))
105
+ continue;
106
+ keys.push(pick.key);
107
+ }
108
+ return keys;
109
+ }
110
+ /** How many people a `to` list names (the agent not counted). */
111
+ export const peopleNamed = (to) => to.filter((key) => key !== AGENT_KEY).length;
112
+ /** What refuses a comment that names more than {@link MENTION_PEOPLE_LIMIT} people. */
113
+ export function mentionLimitText(verb) {
114
+ return `A comment can mention up to ${MENTION_PEOPLE_LIMIT} people. Remove some mentions to ${verb}.`;
115
+ }
116
+ /** The names a sent message's mentions are drawn for: the agent's when it went to the agent, and the people it named. */
117
+ export function sentMentionNames(to, agentName) {
118
+ const keys = to ?? [];
119
+ return [...(agentName && keys.includes(AGENT_KEY) ? [agentName] : []), ...keys.filter((key) => key !== AGENT_KEY).map(mentionName)];
120
+ }
121
+ /**
122
+ * Whether a message's card leads with an `@agent` tag: a person sent it to the agent (the box ticked, or the agent named
123
+ * in `to`) and its text does not mention the agent itself.
124
+ */
125
+ export function leadsWithAgent(message, agentName) {
126
+ return message.author.kind === 'person' && Boolean(message.to?.includes(AGENT_KEY)) && agentName.trim() !== '' && !mentionsName(message.text, agentName);
127
+ }
128
+ /** `text` cut into plain runs and the `@name` runs of `names` (the longest name wins where two start alike). */
129
+ export function mentionPieces(text, names) {
130
+ const wanted = [...new Set(names.map((name) => name.trim()).filter(Boolean))].sort((a, b) => b.length - a.length);
131
+ if (wanted.length === 0 || !text.includes('@'))
132
+ return text ? [{ text, mention: false }] : [];
133
+ const patterns = wanted.map((name) => namePattern(name, 'giu'));
134
+ const pieces = [];
135
+ let from = 0;
136
+ for (;;) {
137
+ let best = null;
138
+ for (const pattern of patterns) {
139
+ pattern.lastIndex = from;
140
+ const hit = pattern.exec(text);
141
+ if (hit !== null && (best === null || hit.index < best.at))
142
+ best = { at: hit.index, length: hit[0].length };
143
+ }
144
+ if (best === null)
145
+ break;
146
+ if (best.at > from)
147
+ pieces.push({ text: text.slice(from, best.at), mention: false });
148
+ pieces.push({ text: text.slice(best.at, best.at + best.length), mention: true });
149
+ from = best.at + best.length;
150
+ }
151
+ if (from < text.length)
152
+ pieces.push({ text: text.slice(from), mention: false });
153
+ return pieces;
154
+ }
155
+ /** Whether the list is still closed for `typed` after it was closed at `closed`. */
156
+ export function stillClosed(closed, typed) {
157
+ if (closed === null || typed === null || typed.start !== closed.start)
158
+ return false;
159
+ return foldName(typed.query).startsWith(foldName(closed.query));
160
+ }
161
+ /** What the status region says about the highlighted row. */
162
+ export function optionPosition(label, index, total) {
163
+ return `${label}, ${index + 1} of ${total}`;
164
+ }
@@ -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'>;
@@ -0,0 +1,273 @@
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 const PEER_COLOR_PALETTE = ['#785ee8', '#dc3c3d', '#019c7f', '#fbb315', '#ce447d', '#10a122', '#257de0', '#d25f25'];
30
+ /** Colors never given to people: the purple nearest the agent's own color. */
31
+ export const NEVER_GIVEN_PEER_COLORS = ['#785ee8'];
32
+ /** How long after a page shows it settles its color, ms. */
33
+ export const PEER_COLOR_SETTLE_MS = 1500;
34
+ /** How often a page looks at its color again, ms. */
35
+ export const PEER_COLOR_RECONCILE_MS = 2000;
36
+ /** How long a hidden page keeps its claim, ms. */
37
+ export const PEER_COLOR_RELEASE_MS = 8000;
38
+ /** A gap in the reconcile beat this long means the computer slept, ms. */
39
+ const WAKE_GAP_MS = 10_000;
40
+ /** Within this long of waking, a hidden page gives its claim up at once, ms. */
41
+ const WOKE_RECENTLY_MS = 60_000;
42
+ /** Moves on from clashes are counted over this long, ms. */
43
+ const BUMP_WINDOW_MS = 60_000;
44
+ /** The palette from `start` on (wrapping), without `exclude`. */
45
+ export function rotatePeerColors(start, exclude = NEVER_GIVEN_PEER_COLORS) {
46
+ const from = Math.max(0, PEER_COLOR_PALETTE.indexOf(start));
47
+ return PEER_COLOR_PALETTE.map((_, offset) => PEER_COLOR_PALETTE[(from + offset) % PEER_COLOR_PALETTE.length]).filter((color) => !exclude.includes(color));
48
+ }
49
+ /** A palette color, lower-cased; `undefined` for anything else. */
50
+ export function normalizePeerColor(color) {
51
+ const lower = typeof color === 'string' ? color.toLowerCase() : '';
52
+ return PEER_COLOR_PALETTE.includes(lower) ? lower : undefined;
53
+ }
54
+ /** The color an id hashes to (never a reserved one): what a person wears alone. */
55
+ export function peerColorFromId(id) {
56
+ let hash = 0;
57
+ for (let index = 0; index < id.length; index += 1)
58
+ hash = (hash * 31 + id.charCodeAt(index)) >>> 0;
59
+ return rotatePeerColors(PEER_COLOR_PALETTE[hash % PEER_COLOR_PALETTE.length])[0] ?? PEER_COLOR_PALETTE[1];
60
+ }
61
+ /** The color a peer wears: the one it published, else its id's. */
62
+ export function peerColorFor(published, id) {
63
+ return normalizePeerColor(published) ?? peerColorFromId(id);
64
+ }
65
+ /** Text color on a `#rrggbb` background: near-black where white would read poorly (contrast under 3:1), else white. */
66
+ export function inkOnPeerColor(hex) {
67
+ const [red = 0, green = 0, blue = 0] = [1, 3, 5].map((offset) => {
68
+ const channel = parseInt(hex.slice(offset, offset + 2), 16) / 255;
69
+ return channel <= 0.03928 ? channel / 12.92 : ((channel + 0.055) / 1.055) ** 2.4;
70
+ });
71
+ return 1.05 / (0.2126 * red + 0.7152 * green + 0.0722 * blue + 0.05) < 3 ? '#0b0b0b' : '#ffffff';
72
+ }
73
+ /** `color` when free, else the palette color after it worn by the fewest of `taken`. */
74
+ export function leastUsedPeerColor(color, taken, neverGiven = NEVER_GIVEN_PEER_COLORS) {
75
+ if (!neverGiven.includes(color) && !taken.includes(color))
76
+ return color;
77
+ const count = (candidate) => taken.filter((item) => item === candidate).length;
78
+ return rotatePeerColors(color, neverGiven).reduce((best, candidate) => (count(candidate) < count(best) ? candidate : best));
79
+ }
80
+ /** True when claim `a` (by `aKey`) came before claim `b` (by `bKey`): earlier, or as early with the smaller key. */
81
+ export function peerColorClaimPrecedes(a, aKey, b, bKey) {
82
+ return a.t < b.t || (a.t === b.t && aKey < bKey);
83
+ }
84
+ /** Claims, earliest first (see {@link peerColorClaimPrecedes}). */
85
+ export function sortPeerColorClaims(claims) {
86
+ const ordered = [];
87
+ for (const claim of claims) {
88
+ const index = ordered.findIndex((other) => peerColorClaimPrecedes(claim, claim.key, other, other.key));
89
+ ordered.splice(index < 0 ? ordered.length : index, 0, claim);
90
+ }
91
+ return ordered;
92
+ }
93
+ /** Colors other people claim (this person's other pages aside). */
94
+ export function takenPeerColors(claims) {
95
+ return claims.filter((claim) => !claim.own).map((claim) => claim.c);
96
+ }
97
+ /** Keeps one page's color (see the module comment); `onChange` is told when it changes. */
98
+ export function createPeerColorKeeper(options, onChange = () => { }) {
99
+ const { now } = options;
100
+ const neverGiven = options.neverGiven ?? NEVER_GIVEN_PEER_COLORS;
101
+ const keptColor = normalizePeerColor(options.kept.read());
102
+ let worn = leastUsedPeerColor(keptColor !== undefined && !neverGiven.includes(keptColor) ? keptColor : peerColorFromId(options.id), [], neverGiven);
103
+ let wornSince = null;
104
+ let bumps = 0;
105
+ let lastBumpAt = -Infinity;
106
+ let cancelSettle;
107
+ let pendingRelease;
108
+ let lastTick = now();
109
+ let lastWakeAt = -Infinity;
110
+ let lastPublished;
111
+ const tickWoke = () => {
112
+ const at = now();
113
+ const woke = at - lastTick > WAKE_GAP_MS;
114
+ if (woke)
115
+ lastWakeAt = at;
116
+ lastTick = at;
117
+ return woke;
118
+ };
119
+ const wear = (color, since) => {
120
+ const changed = color !== worn;
121
+ [worn, wornSince] = [color, since];
122
+ if (since !== null)
123
+ options.kept.write(worn);
124
+ const published = `${worn} ${String(wornSince)}`;
125
+ if (published !== lastPublished) {
126
+ lastPublished = published;
127
+ options.publish({ c: worn, t: wornSince });
128
+ }
129
+ if (changed)
130
+ onChange();
131
+ };
132
+ const release = () => {
133
+ pendingRelease?.cancel();
134
+ pendingRelease = undefined;
135
+ wear(worn, null);
136
+ };
137
+ /** Usable claims, one per person and kind (their earliest page's). */
138
+ const claimsOf = (all) => {
139
+ const usable = all.filter((claim) => !neverGiven.includes(claim.c));
140
+ return usable.filter((b) => !usable.some((a) => a !== b && a.key === b.key && a.own === b.own && peerColorClaimPrecedes(a, a.peer, b, b.peer)));
141
+ };
142
+ /** Someone else claimed `color` before `claim`. */
143
+ const clashes = (claims, color, claim) => claims.some((other) => !other.own && other.c === color && peerColorClaimPrecedes(other, other.key, claim, options.id));
144
+ /**
145
+ * The color to move to from `color`: every clashing claim, earliest first,
146
+ * takes the next free color, and this page gets what is left.
147
+ */
148
+ const resolveClash = (all, claims, color, claim) => {
149
+ const self = { key: options.id, peer: options.peer, own: true, c: color, t: claim.t };
150
+ const ordered = sortPeerColorClaims([...claims.filter((other) => !other.own), self]);
151
+ const clashing = ordered.filter((a) => a === self || ordered.some((b) => b !== a && b.c === a.c && peerColorClaimPrecedes(b, b.key, a, a.key)));
152
+ const taken = new Set([color, ...takenPeerColors(all)]);
153
+ for (const entry of clashing) {
154
+ const next = rotatePeerColors(entry.c, neverGiven).find((candidate) => !taken.has(candidate));
155
+ if (next === undefined || entry === self)
156
+ return next;
157
+ taken.add(next);
158
+ }
159
+ return undefined;
160
+ };
161
+ const settle = () => {
162
+ cancelSettle = undefined;
163
+ const all = options.claims();
164
+ const claims = claimsOf(all);
165
+ const own = claims.find((claim) => claim.own);
166
+ if (own === undefined)
167
+ wear(leastUsedPeerColor(worn, takenPeerColors(all), neverGiven), now());
168
+ else
169
+ wear((clashes(claims, own.c, own) ? resolveClash(all, claims, own.c, own) : undefined) ?? own.c, own.t);
170
+ };
171
+ const reconcile = () => {
172
+ if (pendingRelease !== undefined)
173
+ return;
174
+ const all = options.claims();
175
+ const claims = claimsOf(all);
176
+ const own = claims.find((claim) => claim.own);
177
+ if (wornSince === null) {
178
+ if (own !== undefined && own.c !== worn)
179
+ wear(own.c, null);
180
+ return;
181
+ }
182
+ const mine = { t: wornSince };
183
+ // This person's earlier page wins (unless its color clashes and can move).
184
+ if (own !== undefined && peerColorClaimPrecedes(own, own.peer, mine, options.peer) && !(clashes(claims, own.c, own) && resolveClash(all, claims, own.c, own) !== undefined)) {
185
+ if (own.c !== worn || own.t !== wornSince)
186
+ wear(own.c, own.t);
187
+ return;
188
+ }
189
+ if (now() - lastBumpAt > BUMP_WINDOW_MS)
190
+ bumps = 0;
191
+ const next = clashes(claims, worn, mine) && bumps < rotatePeerColors(worn, neverGiven).length ? resolveClash(all, claims, worn, mine) : undefined;
192
+ if (next === undefined)
193
+ return;
194
+ [bumps, lastBumpAt] = [bumps + 1, now()];
195
+ wear(next, wornSince);
196
+ };
197
+ const stopTicking = options.every(() => {
198
+ if (tickWoke() && pendingRelease !== undefined)
199
+ release();
200
+ reconcile();
201
+ }, PEER_COLOR_RECONCILE_MS);
202
+ lastPublished = `${worn} null`;
203
+ options.publish({ c: worn, t: null });
204
+ return {
205
+ worn: () => worn,
206
+ heard: reconcile,
207
+ here() {
208
+ const pending = pendingRelease;
209
+ pendingRelease = undefined;
210
+ pending?.cancel();
211
+ const expired = pending !== undefined && now() - pending.at >= PEER_COLOR_RELEASE_MS;
212
+ if (expired)
213
+ wear(worn, null);
214
+ if (pending !== undefined && !expired)
215
+ return reconcile();
216
+ if (cancelSettle !== undefined || wornSince !== null)
217
+ return;
218
+ bumps = 0;
219
+ wear(worn, null);
220
+ cancelSettle = options.after(settle, PEER_COLOR_SETTLE_MS);
221
+ },
222
+ away() {
223
+ cancelSettle?.();
224
+ cancelSettle = undefined;
225
+ if (wornSince === null || pendingRelease !== undefined)
226
+ return;
227
+ tickWoke();
228
+ if (now() - lastWakeAt < WOKE_RECENTLY_MS)
229
+ return wear(worn, null);
230
+ pendingRelease = { at: now(), cancel: options.after(release, PEER_COLOR_RELEASE_MS) };
231
+ },
232
+ dispose() {
233
+ if (pendingRelease !== undefined)
234
+ release();
235
+ cancelSettle?.();
236
+ cancelSettle = undefined;
237
+ stopTicking();
238
+ },
239
+ };
240
+ }
241
+ /** The color a person settled on last time, kept in local storage under `key` (wrapped: storage may be missing or refuse). */
242
+ export function keptPeerColor(key) {
243
+ return {
244
+ read() {
245
+ try {
246
+ return globalThis.localStorage?.getItem(key) ?? null;
247
+ }
248
+ catch {
249
+ return null;
250
+ }
251
+ },
252
+ write(color) {
253
+ try {
254
+ globalThis.localStorage?.setItem(key, color);
255
+ }
256
+ catch {
257
+ // Not kept: the id's color is used next time.
258
+ }
259
+ },
260
+ };
261
+ }
262
+ /** The real clock and timers for {@link createPeerColorKeeper}. */
263
+ export const PEER_COLOR_TIMERS = {
264
+ now: () => Date.now(),
265
+ after(run, ms) {
266
+ const timer = setTimeout(run, ms);
267
+ return () => clearTimeout(timer);
268
+ },
269
+ every(run, ms) {
270
+ const timer = setInterval(run, ms);
271
+ return () => clearInterval(timer);
272
+ },
273
+ };
@@ -0,0 +1,70 @@
1
+ /**
2
+ * Pin geometry shared by every editor's comments. Pure.
3
+ *
4
+ * Editor-agnostic: this folder
5
+ * imports only `@openartifactsai/runtime`, `@openartifactsai/ui`, React, zustand
6
+ * and lucide-react, never an editor's own stores. Where a comment sits is the
7
+ * editor's business; it hands these modules world points and boxes.
8
+ */
9
+ /** A point (world or screen px). */
10
+ export interface Point {
11
+ x: number;
12
+ y: number;
13
+ }
14
+ /** A box (world or screen px). */
15
+ export interface Box {
16
+ x: number;
17
+ y: number;
18
+ w: number;
19
+ h: number;
20
+ /** A dragged area (a highlight draws it dashed, as it was drawn). */
21
+ area?: boolean;
22
+ }
23
+ /** A pan-and-zoom camera: screen = world × zoom + (x, y). */
24
+ export interface Camera {
25
+ x: number;
26
+ y: number;
27
+ zoom: number;
28
+ }
29
+ /**
30
+ * How a stored anchor resolves against the document now:
31
+ *
32
+ * - `ok`: what it names is there.
33
+ * - `moved`: found again at another address (by a fingerprint).
34
+ * - `detached`: the element is gone; the thread falls back to its container.
35
+ * - `orphaned`: the container is gone too (the thread shows in the list only).
36
+ */
37
+ export type AnchorState = 'ok' | 'moved' | 'detached' | 'orphaned';
38
+ /** Where a thread's pin sits, as the editor resolved its anchor. */
39
+ export interface PinPlace {
40
+ world: Point;
41
+ state: AnchorState;
42
+ }
43
+ /** A world point on screen. */
44
+ export declare function toScreenPoint(camera: Camera, world: Point): Point;
45
+ /** A screen point in the world. */
46
+ export declare function toWorldPoint(camera: Camera, screen: Point): Point;
47
+ /** A world box on screen, as CSS `left/top/width/height`. */
48
+ export declare function screenBox(camera: Camera, r: Box): {
49
+ left: number;
50
+ top: number;
51
+ width: number;
52
+ height: number;
53
+ };
54
+ /**
55
+ * Pins that would sit on top of each other are fanned out: a pin within
56
+ * `gap` screen px of an earlier one moves right by `gap` until it is clear.
57
+ * Input order is kept; returns the shifted screen points.
58
+ */
59
+ export declare function spreadPins(points: readonly Point[], gap?: number): Point[];
60
+ /**
61
+ * Where a thread card opens next to its pin: to the right when it fits in
62
+ * the viewport, else to the left; kept inside vertically.
63
+ */
64
+ export declare function cardPosition(pin: Point, viewport: {
65
+ width: number;
66
+ height: number;
67
+ }, card?: {
68
+ w: number;
69
+ h: number;
70
+ }): Point;
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Pin geometry shared by every editor's comments. Pure.
3
+ *
4
+ * Editor-agnostic: this folder
5
+ * imports only `@openartifactsai/runtime`, `@openartifactsai/ui`, React, zustand
6
+ * and lucide-react, never an editor's own stores. Where a comment sits is the
7
+ * editor's business; it hands these modules world points and boxes.
8
+ */
9
+ /** A world point on screen. */
10
+ export function toScreenPoint(camera, world) {
11
+ return { x: world.x * camera.zoom + camera.x, y: world.y * camera.zoom + camera.y };
12
+ }
13
+ /** A screen point in the world. */
14
+ export function toWorldPoint(camera, screen) {
15
+ const zoom = camera.zoom || 1;
16
+ return { x: (screen.x - camera.x) / zoom, y: (screen.y - camera.y) / zoom };
17
+ }
18
+ /** A world box on screen, as CSS `left/top/width/height`. */
19
+ export function screenBox(camera, r) {
20
+ return { left: r.x * camera.zoom + camera.x, top: r.y * camera.zoom + camera.y, width: r.w * camera.zoom, height: r.h * camera.zoom };
21
+ }
22
+ /**
23
+ * Pins that would sit on top of each other are fanned out: a pin within
24
+ * `gap` screen px of an earlier one moves right by `gap` until it is clear.
25
+ * Input order is kept; returns the shifted screen points.
26
+ */
27
+ export function spreadPins(points, gap = 20) {
28
+ const placed = [];
29
+ for (const p of points) {
30
+ let x = p.x;
31
+ for (let tries = 0; tries < 50 && placed.some((q) => Math.abs(q.x - x) < gap && Math.abs(q.y - p.y) < gap); tries++)
32
+ x += gap;
33
+ placed.push({ x, y: p.y });
34
+ }
35
+ return placed;
36
+ }
37
+ /**
38
+ * Where a thread card opens next to its pin: to the right when it fits in
39
+ * the viewport, else to the left; kept inside vertically.
40
+ */
41
+ export function cardPosition(pin, viewport, card = { w: 288, h: 320 }) {
42
+ const right = pin.x + 18 + card.w <= viewport.width - 8;
43
+ return { x: right ? pin.x + 18 : Math.max(8, pin.x - 14 - card.w), y: Math.max(8, Math.min(pin.y - 8, viewport.height - card.h)) };
44
+ }