@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,59 @@
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 '@openartifactsai/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
+ * Called before a restore and awaited: writes edits still on their way to
27
+ * the files, so they don't land on top of the restored version afterwards.
28
+ * A failure doesn't stop the restore.
29
+ */
30
+ settle?(): Promise<void>;
31
+ }
32
+ /** The history store. */
33
+ export interface HistoryState<P> {
34
+ available: boolean;
35
+ open: boolean;
36
+ /** The version previewed (`null`: the current files). */
37
+ previewing: number | null;
38
+ preview: P | null;
39
+ loading: boolean;
40
+ error: string | null;
41
+ canRestore: boolean;
42
+ setOpen(open: boolean): void;
43
+ }
44
+ /** One editor's history. */
45
+ export interface HistoryController<P> {
46
+ readonly store: UseBoundStore<StoreApi<HistoryState<P>>>;
47
+ start(capability: HistoryCapability | null): void;
48
+ capability(): HistoryCapability | null;
49
+ /** Opens or closes the panel. */
50
+ toggle(open?: boolean): void;
51
+ /** Shows version `n` read-only (`null`: back to the current files). */
52
+ preview(n: number | null): Promise<void>;
53
+ /** Restores the whole of version `n`. */
54
+ restore(n: number): Promise<void>;
55
+ /** Restores some artifact paths of version `n`; resolves to the paths that changed, or `null` when it failed. */
56
+ restorePaths(n: number, paths: string[], what: string): Promise<string[] | null>;
57
+ }
58
+ /** Creates an editor's history. */
59
+ export declare function createHistory<P>(adapter: HistoryAdapter<P>): HistoryController<P>;
@@ -0,0 +1,96 @@
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
+ await adapter.settle?.().catch(() => undefined);
73
+ try {
74
+ const result = await capability.restore(n);
75
+ notify({ title: result.changed.length ? `Restored version ${n}` : `The ${noun} already matches version ${n}` });
76
+ await controller.preview(null);
77
+ }
78
+ catch (error) {
79
+ notify({ title: 'The version could not be restored', description: message(error) });
80
+ }
81
+ },
82
+ async restorePaths(n, paths, what) {
83
+ if (!capability)
84
+ return null;
85
+ await adapter.settle?.().catch(() => undefined);
86
+ try {
87
+ return (await capability.restore(n, paths)).changed;
88
+ }
89
+ catch (error) {
90
+ notify({ title: `${what} could not be restored`, description: message(error) });
91
+ return null;
92
+ }
93
+ },
94
+ };
95
+ return controller;
96
+ }
@@ -0,0 +1,63 @@
1
+ /**
2
+ * The `@` list of a comment box. While the text before the caret is an `@name` being typed, a list of who it can name
3
+ * opens over the `@` (the agent first); arrows move through it, Enter or Tab or a click puts the name in, Escape closes
4
+ * it. Focus stays in the box all along: the list is a listbox the box drives, and a polite status next to the box says
5
+ * which row is highlighted.
6
+ *
7
+ * {@link useMentions} is shared by the composer and the edit box. It also remembers whom each picked `@Name` stands
8
+ * for, so the box can say whom the message names when it is sent.
9
+ */
10
+ import { type KeyboardEvent, type ReactNode, type RefObject } from 'react';
11
+ import { type MentionOption, type MentionPerson, type MentionPick } from '../mentions.js';
12
+ /** Who a box's `@` can name. */
13
+ export interface MentionsSpec {
14
+ agentName: string;
15
+ /** The viewer may send to the agent: it gets a row, and a message that mentions it goes to it. */
16
+ agentListed: boolean;
17
+ /** Everyone else, in the order to list them. */
18
+ people(): readonly MentionPerson[];
19
+ /** The viewer: never listed. */
20
+ self: {
21
+ id?: string;
22
+ name: string;
23
+ };
24
+ /** The first `@` typed in this box (to start fetching who has the artifact). */
25
+ onFirstUse?(): void;
26
+ /** Whom the text already names (a message being edited): their `@Name`s keep naming them. */
27
+ picked?: readonly MentionPick[];
28
+ /** The small picture in front of a row's name. */
29
+ avatar?(option: MentionOption): ReactNode;
30
+ }
31
+ /** What the box shows and does with {@link useMentions}. */
32
+ export interface MentionField {
33
+ /** Call first from the box's keydown: true when the list took the key. */
34
+ onKeyDown(event: KeyboardEvent<HTMLTextAreaElement>): boolean;
35
+ onKeyUp(event: KeyboardEvent<HTMLTextAreaElement>): void;
36
+ /** Click, focus: the caret may have moved. */
37
+ onCaret(): void;
38
+ onBlur(): void;
39
+ /** The text mentions the agent (and the agent may be asked). */
40
+ mentionsAgent: boolean;
41
+ /** Whom `text` names: `agent` first when it mentions the agent, then the picked people still in it. */
42
+ targets(text: string): string[];
43
+ /** The `@names` drawn as mentions in the box and in cards. */
44
+ names: readonly string[];
45
+ /** The list (in the layer's portal) and the status region: render both. */
46
+ parts: ReactNode;
47
+ /** The textarea's `aria-*` while the list is open. */
48
+ aria: {
49
+ 'aria-controls'?: string;
50
+ 'aria-activedescendant'?: string;
51
+ 'aria-autocomplete': 'list';
52
+ 'aria-expanded': boolean;
53
+ };
54
+ }
55
+ /** `@` handling for a comment box (see the module comment). */
56
+ export declare function useMentions(spec: MentionsSpec | undefined, value: string, onChange: (value: string) => void, field: RefObject<HTMLTextAreaElement | null>): MentionField;
57
+ /** The `@names` of a box drawn in the accent colour over its text (the rest of the copy is see-through); its parent is `relative` and as big as the box. */
58
+ export declare function MentionMarks({ value, names, field, className }: {
59
+ value: string;
60
+ names: readonly string[];
61
+ field: RefObject<HTMLTextAreaElement | null>;
62
+ className?: string;
63
+ }): ReactNode;
@@ -0,0 +1,257 @@
1
+ import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
2
+ /**
3
+ * The `@` list of a comment box. While the text before the caret is an `@name` being typed, a list of who it can name
4
+ * opens over the `@` (the agent first); arrows move through it, Enter or Tab or a click puts the name in, Escape closes
5
+ * it. Focus stays in the box all along: the list is a listbox the box drives, and a polite status next to the box says
6
+ * which row is highlighted.
7
+ *
8
+ * {@link useMentions} is shared by the composer and the edit box. It also remembers whom each picked `@Name` stands
9
+ * for, so the box can say whom the message names when it is sent.
10
+ */
11
+ import { useEffect, useId, useLayoutEffect, useRef, useState } from 'react';
12
+ import { createPortal } from 'react-dom';
13
+ import { isComposingKey } from '@openartifactsai/ui';
14
+ import { applyMention, mentionOptions, mentionPieces, mentionsName, mentionTargets, optionPosition, stillClosed, typedMention, } from "../mentions.js";
15
+ /** Class names, skipping the empty ones. */
16
+ const classes = (...names) => names.filter(Boolean).join(' ');
17
+ const LIST_WIDTH = 288;
18
+ const LIST_MAX_HEIGHT = 384;
19
+ const EDGE = 16;
20
+ const OFFSET = 24;
21
+ const LIST = 'pointer-events-auto fixed z-[1] flex flex-col overflow-y-auto overscroll-contain scroll-thin rounded-card bg-surface-3 p-[0.25rem] shadow-panel font-sans text-body font-normal text-primary outline-none';
22
+ const ROW = 'flex min-h-control w-full min-w-0 cursor-default select-none items-center gap-xs rounded px-2 text-body';
23
+ /** `@` handling for a comment box (see the module comment). */
24
+ export function useMentions(spec, value, onChange, field) {
25
+ const listId = useId();
26
+ const [caret, setCaret] = useState(null);
27
+ const [closed, setClosed] = useState(null);
28
+ const [keyRow, setKeyRow] = useState(0);
29
+ const [hoverRow, setHoverRow] = useState(null);
30
+ const [picks, setPicks] = useState(() => [...(spec?.picked ?? [])]);
31
+ const [added, setAdded] = useState('');
32
+ const placeCaret = useRef(null);
33
+ const used = useRef(false);
34
+ const list = useRef(null);
35
+ const scrollToKeyRow = useRef(false);
36
+ const typed = spec && caret !== null ? typedMention(value, caret) : null;
37
+ const options = spec && typed && !stillClosed(closed, typed)
38
+ ? mentionOptions({ query: typed.query, agentName: spec.agentName, agentListed: spec.agentListed, people: spec.people(), self: spec.self })
39
+ : [];
40
+ const open = options.length > 0;
41
+ const shown = Math.min(hoverRow ?? keyRow, options.length - 1);
42
+ const readCaret = () => {
43
+ const el = field.current;
44
+ if (!el || el.ownerDocument.activeElement !== el && el.getRootNode().activeElement !== el)
45
+ return setCaret(null);
46
+ setCaret(el.selectionStart === el.selectionEnd ? el.selectionEnd : null);
47
+ };
48
+ // The text changed (typed, or set from outside): put the caret where a pick left it, then read it again.
49
+ useLayoutEffect(() => {
50
+ const el = field.current;
51
+ if (el && placeCaret.current !== null) {
52
+ el.setSelectionRange(placeCaret.current, placeCaret.current);
53
+ placeCaret.current = null;
54
+ }
55
+ else if (added) {
56
+ setAdded('');
57
+ }
58
+ if (spec)
59
+ readCaret();
60
+ }, [value]);
61
+ // A new query: the first row again.
62
+ useEffect(() => {
63
+ setKeyRow(0);
64
+ setHoverRow(null);
65
+ }, [typed?.start, typed?.query]);
66
+ // Escape (or a pick) keeps the list shut only while the same `@` grows from where it was.
67
+ useEffect(() => {
68
+ if (closed && !stillClosed(closed, typed))
69
+ setClosed(null);
70
+ }, [closed, typed?.start, typed?.query]);
71
+ useEffect(() => {
72
+ if (!typed || used.current)
73
+ return;
74
+ used.current = true;
75
+ spec?.onFirstUse?.();
76
+ }, [typed !== null]);
77
+ useLayoutEffect(() => {
78
+ if (!scrollToKeyRow.current)
79
+ return;
80
+ scrollToKeyRow.current = false;
81
+ list.current?.querySelector(`[data-mention-row="${shown}"]`)?.scrollIntoView({ block: 'nearest' });
82
+ });
83
+ const pick = (option) => {
84
+ if (!typed)
85
+ return;
86
+ const next = applyMention(value, typed, option);
87
+ if (option.kind === 'person')
88
+ setPicks((all) => [...all.filter((p) => p.key !== option.key || p.name !== next.name), { key: option.key, name: next.name }]);
89
+ setClosed({ start: typed.start, query: next.name });
90
+ // The new text is read with its new caret at once (with the old one it would look like a different `@`).
91
+ setCaret(next.caret);
92
+ placeCaret.current = next.caret;
93
+ onChange(next.text);
94
+ setAdded(`${option.label} added`);
95
+ };
96
+ const agentName = spec?.agentName ?? '';
97
+ const agentListed = spec?.agentListed ?? false;
98
+ const mentionsAgent = agentListed && mentionsName(value, agentName);
99
+ const field_ = {
100
+ onKeyDown(event) {
101
+ if (!open || isComposingKey(event.nativeEvent))
102
+ return false;
103
+ const plain = !event.shiftKey && !event.altKey && !event.ctrlKey && !event.metaKey;
104
+ if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
105
+ event.preventDefault();
106
+ const step = event.key === 'ArrowDown' ? 1 : -1;
107
+ setKeyRow((shown + step + options.length) % options.length);
108
+ setHoverRow(null);
109
+ scrollToKeyRow.current = true;
110
+ return true;
111
+ }
112
+ if ((event.key === 'Enter' || event.key === 'Tab') && plain) {
113
+ event.preventDefault();
114
+ event.stopPropagation();
115
+ const option = options[shown];
116
+ if (option)
117
+ pick(option);
118
+ return true;
119
+ }
120
+ if (event.key === 'Escape') {
121
+ event.preventDefault();
122
+ event.stopPropagation();
123
+ if (typed)
124
+ setClosed({ start: typed.start, query: typed.query });
125
+ return true;
126
+ }
127
+ return false;
128
+ },
129
+ onKeyUp(event) {
130
+ if (open && (event.key === 'ArrowDown' || event.key === 'ArrowUp'))
131
+ return;
132
+ if (spec)
133
+ readCaret();
134
+ },
135
+ onCaret() {
136
+ if (spec)
137
+ readCaret();
138
+ },
139
+ onBlur() {
140
+ setCaret(null);
141
+ },
142
+ mentionsAgent,
143
+ targets: (text) => mentionTargets(text, picks, { name: agentName, listed: agentListed }),
144
+ names: [...(agentListed && agentName ? [agentName] : []), ...picks.map((p) => p.name)],
145
+ aria: {
146
+ 'aria-autocomplete': 'list',
147
+ 'aria-expanded': open,
148
+ ...(open ? { 'aria-controls': listId, 'aria-activedescendant': `${listId}-${shown}` } : {}),
149
+ },
150
+ parts: spec ? (_jsxs(_Fragment, { children: [open ? (_jsx(MentionList, { id: listId, listRef: list, field: field, at: typed.start, options: options, highlighted: shown, onHover: setHoverRow, onPick: pick, avatar: spec.avatar })) : null, _jsx("span", { role: "status", "aria-live": "polite", className: "sr-only", "data-mention-status": "", children: open ? optionPosition(options[shown].label, shown, options.length) : added })] })) : null,
151
+ };
152
+ return field_;
153
+ }
154
+ /** Where the `@` at `index` of a textarea is on the screen (a hidden copy of the box measures it). */
155
+ function caretBox(el, index) {
156
+ const doc = el.ownerDocument;
157
+ const style = doc.defaultView.getComputedStyle(el);
158
+ const copy = doc.createElement('div');
159
+ for (const name of [
160
+ 'box-sizing',
161
+ 'width',
162
+ 'padding-top',
163
+ 'padding-right',
164
+ 'padding-bottom',
165
+ 'padding-left',
166
+ 'border-top-width',
167
+ 'border-right-width',
168
+ 'border-bottom-width',
169
+ 'border-left-width',
170
+ 'font-family',
171
+ 'font-size',
172
+ 'font-weight',
173
+ 'font-style',
174
+ 'font-variant',
175
+ 'letter-spacing',
176
+ 'word-spacing',
177
+ 'line-height',
178
+ 'text-indent',
179
+ 'text-transform',
180
+ 'tab-size',
181
+ ]) {
182
+ copy.style.setProperty(name, style.getPropertyValue(name));
183
+ }
184
+ Object.assign(copy.style, { position: 'fixed', visibility: 'hidden', top: '0', left: '0', whiteSpace: 'pre-wrap', overflowWrap: 'break-word', borderStyle: 'solid' });
185
+ copy.textContent = el.value.slice(0, index);
186
+ const mark = doc.createElement('span');
187
+ mark.textContent = '@';
188
+ copy.append(mark);
189
+ doc.body.append(copy);
190
+ const left = mark.offsetLeft;
191
+ const top = mark.offsetTop;
192
+ copy.remove();
193
+ const box = el.getBoundingClientRect();
194
+ return { left: box.left + left - el.scrollLeft, top: box.top + top - el.scrollTop };
195
+ }
196
+ /** The portal of the comments layer `el` is in, if any. */
197
+ function layerPortal(el) {
198
+ const root = el?.getRootNode();
199
+ return root && 'querySelector' in root ? root.querySelector('[data-layer-portal]') : null;
200
+ }
201
+ function MentionList({ id, listRef, field, at, options, highlighted, onHover, onPick, avatar, }) {
202
+ // The list goes in the layer's portal (above the cards and the panel) when the box is in a layer.
203
+ const [portal] = useState(() => layerPortal(field.current));
204
+ const [place, setPlace] = useState(null);
205
+ useLayoutEffect(() => {
206
+ const el = field.current;
207
+ const box = listRef.current;
208
+ if (!el || !box)
209
+ return;
210
+ const view = el.ownerDocument.defaultView;
211
+ const point = caretBox(el, at);
212
+ const height = Math.min(LIST_MAX_HEIGHT, box.scrollHeight);
213
+ const above = point.top - OFFSET - EDGE;
214
+ const below = view.innerHeight - (point.top + OFFSET) - EDGE;
215
+ const left = Math.max(EDGE, Math.min(point.left, view.innerWidth - LIST_WIDTH - EDGE));
216
+ const next = above >= height || above >= below
217
+ ? { left, bottom: view.innerHeight - (point.top - OFFSET), maxHeight: Math.min(LIST_MAX_HEIGHT, Math.max(0, above)) }
218
+ : { left, top: point.top + OFFSET, maxHeight: Math.min(LIST_MAX_HEIGHT, Math.max(0, below)) };
219
+ setPlace((last) => (last && last.left === next.left && last.top === next.top && last.bottom === next.bottom && last.maxHeight === next.maxHeight ? last : next));
220
+ }, [at, options.length]);
221
+ const list = (_jsx("div", { ref: listRef, id: id, role: "listbox", "aria-label": "Mention suggestions", "data-mention-list": "", className: LIST, style: { width: LIST_WIDTH, ...(place ?? { left: 0, top: 0, visibility: 'hidden' }) },
222
+ // A press on the list keeps the focus (and the caret) in the box.
223
+ onMouseDown: (event) => event.preventDefault(), onPointerLeave: () => onHover(null), children: options.map((option, index) => (_jsxs("div", { id: `${id}-${index}`, role: "option", "aria-selected": index === highlighted, "data-mention-row": index, "data-highlighted": index === highlighted || undefined, className: classes(ROW, index === highlighted && 'bg-fill-ghost-hover'),
224
+ // Moves only: a row that slides under a still pointer does not take the highlight.
225
+ onPointerMove: () => {
226
+ if (index !== highlighted)
227
+ onHover(index);
228
+ }, onClick: () => onPick(option), children: [avatar ? (_jsx("span", { "aria-hidden": true, className: "inline-flex shrink-0", children: avatar(option) })) : null, _jsx("span", { className: "min-w-0 flex-1 truncate", onPointerEnter: (event) => {
229
+ const label = event.currentTarget;
230
+ label.title = label.scrollWidth > label.clientWidth ? option.label : '';
231
+ }, children: option.label })] }, `${option.kind}:${option.key}`))) }));
232
+ return portal ? createPortal(list, portal) : list;
233
+ }
234
+ /** The `@names` of a box drawn in the accent colour over its text (the rest of the copy is see-through); its parent is `relative` and as big as the box. */
235
+ export function MentionMarks({ value, names, field, className }) {
236
+ const inner = useRef(null);
237
+ const pieces = mentionPieces(value, names);
238
+ const any = pieces.some((piece) => piece.mention);
239
+ useLayoutEffect(() => {
240
+ const el = field.current;
241
+ if (!el || !any)
242
+ return;
243
+ const follow = () => {
244
+ if (!inner.current)
245
+ return;
246
+ inner.current.style.transform = `translateY(${-el.scrollTop}px)`;
247
+ // The copy starts where the box's text does (after a tag in front of it).
248
+ inner.current.style.textIndent = el.ownerDocument.defaultView.getComputedStyle(el).textIndent;
249
+ };
250
+ follow();
251
+ el.addEventListener('scroll', follow);
252
+ return () => el.removeEventListener('scroll', follow);
253
+ });
254
+ if (!any)
255
+ return null;
256
+ return (_jsx("div", { "aria-hidden": true, "data-mention-marks": "", className: classes('pointer-events-none absolute inset-0 overflow-hidden font-sans text-body', className), children: _jsx("div", { ref: inner, className: "whitespace-pre-wrap break-words text-transparent", children: pieces.map((piece, index) => piece.mention ? (_jsx("span", { className: "text-accent", children: piece.text }, index)) : (piece.text)) }) }));
257
+ }
@@ -0,0 +1,112 @@
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 declare const AGENT_KEY = "agent";
9
+ /** Most rows the list shows, the agent's included. */
10
+ export declare const MENTION_ROWS = 8;
11
+ /** Most different people one comment may name. */
12
+ export declare const MENTION_PEOPLE_LIMIT = 32;
13
+ /** Someone a comment can name. */
14
+ export interface MentionPerson {
15
+ /** What a message's `to` names them by. */
16
+ key: string;
17
+ name: string;
18
+ /** Their id on this host, when it is known (to leave the viewer out). */
19
+ id?: string;
20
+ }
21
+ /** A row of the list. */
22
+ export interface MentionOption {
23
+ kind: 'agent' | 'person';
24
+ key: string;
25
+ label: string;
26
+ }
27
+ /** An `@name` being typed: `start` is its `@`, `end` the caret. */
28
+ export interface TypedMention {
29
+ start: number;
30
+ end: number;
31
+ query: string;
32
+ }
33
+ /** A person picked from the list: the name as it went into the text. */
34
+ export interface MentionPick {
35
+ key: string;
36
+ name: string;
37
+ }
38
+ /** The `@name` typed just before `caret`, or `null` when the text there is not one. */
39
+ export declare function typedMention(text: string, caret: number): TypedMention | null;
40
+ /** How names and queries are compared. */
41
+ export declare const foldName: (text: string) => string;
42
+ /** Whether `name`, or one of its words, starts with `query` (an empty query matches everyone). */
43
+ export declare function nameMatches(name: string, query: string): boolean;
44
+ /** A name as it is written after `@`: no `<`, `>` or `@`; `someone` when nothing is left. */
45
+ export declare function mentionName(name: string): string;
46
+ /** What the list is drawn from. */
47
+ export interface MentionSource {
48
+ /** The query typed after `@`. */
49
+ query: string;
50
+ /** The agent's name. */
51
+ agentName: string;
52
+ /** The viewer may send comments to the agent: it gets a row. */
53
+ agentListed: boolean;
54
+ /** Everyone else, in the order they should be listed. */
55
+ people: readonly MentionPerson[];
56
+ /** The viewer, who is never listed. */
57
+ self: {
58
+ id?: string;
59
+ name: string;
60
+ };
61
+ }
62
+ /** The rows for a query: the agent first when it matches, then the people who match, {@link MENTION_ROWS} at most. */
63
+ export declare function mentionOptions({ query, agentName, agentListed, people, self }: MentionSource): MentionOption[];
64
+ /** The text with `typed` replaced by the option's `@name` and a space, and where the caret goes. */
65
+ export declare function applyMention(text: string, typed: TypedMention, option: MentionOption): {
66
+ text: string;
67
+ caret: number;
68
+ name: string;
69
+ };
70
+ /** Whether `text` has `@name` in it (case ignored). */
71
+ export declare function mentionsName(text: string, name: string): boolean;
72
+ /**
73
+ * Whom a message names: {@link AGENT_KEY} when it mentions the agent (and the agent may be asked), then each picked
74
+ * person whose `@name` is still in the text. A name typed without picking it names no one.
75
+ */
76
+ export declare function mentionTargets(text: string, picks: readonly MentionPick[], agent: {
77
+ name: string;
78
+ listed: boolean;
79
+ }): string[];
80
+ /** How many people a `to` list names (the agent not counted). */
81
+ export declare const peopleNamed: (to: readonly string[]) => number;
82
+ /** What refuses a comment that names more than {@link MENTION_PEOPLE_LIMIT} people. */
83
+ export declare function mentionLimitText(verb: 'post' | 'save'): string;
84
+ /** The names a sent message's mentions are drawn for: the agent's when it went to the agent, and the people it named. */
85
+ export declare function sentMentionNames(to: readonly string[] | undefined, agentName: string): string[];
86
+ /**
87
+ * Whether a message's card leads with an `@agent` tag: a person sent it to the agent (the box ticked, or the agent named
88
+ * in `to`) and its text does not mention the agent itself.
89
+ */
90
+ export declare function leadsWithAgent(message: {
91
+ text: string;
92
+ to?: readonly string[];
93
+ author: {
94
+ kind: string;
95
+ };
96
+ }, agentName: string): boolean;
97
+ /** A run of a message's text: plain, or an `@name` drawn as a mention. */
98
+ export interface MentionPiece {
99
+ text: string;
100
+ mention: boolean;
101
+ }
102
+ /** `text` cut into plain runs and the `@name` runs of `names` (the longest name wins where two start alike). */
103
+ export declare function mentionPieces(text: string, names: readonly string[]): MentionPiece[];
104
+ /** Where Escape (or a pick) closed the list: it stays closed while the same `@` grows from that query. */
105
+ export interface ClosedMention {
106
+ start: number;
107
+ query: string;
108
+ }
109
+ /** Whether the list is still closed for `typed` after it was closed at `closed`. */
110
+ export declare function stillClosed(closed: ClosedMention | null, typed: TypedMention | null): boolean;
111
+ /** What the status region says about the highlighted row. */
112
+ export declare function optionPosition(label: string, index: number, total: number): string;