@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,92 @@
1
+ /**
2
+ * Live presence for any editor, over the `room` capability: who else has
3
+ * the artifact open, where their pointer is and what the editor says they
4
+ * are doing (selection, page, editing); and the agent, shown for a few
5
+ * seconds after it writes.
6
+ *
7
+ * Editor-agnostic: the editor's
8
+ * {@link PresenceAdapter} says what it publishes under its key and reads
9
+ * peers' values back. Peers' values were written by their browsers: the
10
+ * adapter's `parse` must check and clip them.
11
+ */
12
+ import type { ArtifactCapability, Peer, RoomCapability } from '@openartifactsai/runtime';
13
+ import { type StoreApi, type UseBoundStore } from 'zustand';
14
+ import type { Point } from './pins.js';
15
+ /** Peer colors (cursor, outline, avatar). */
16
+ export declare const PEER_COLORS: string[];
17
+ /** The agent's color. */
18
+ export declare const AGENT_COLOR = "#6e56cf";
19
+ /** How long the agent shows after it wrote (ms). */
20
+ export declare const AGENT_SHOWN_MS = 8000;
21
+ /** Most entries kept of any list read from a peer. */
22
+ export declare const PRESENCE_LIST_MAX = 50;
23
+ /** A stable color for a peer id. */
24
+ export declare function peerColor(id: string): string;
25
+ /** Checked readers for peers' values. */
26
+ export declare const peerValue: {
27
+ str: (value: unknown, max?: number) => string | null;
28
+ num: (value: unknown) => number | null;
29
+ strList: (value: unknown, max?: number) => string[];
30
+ point: (value: unknown) => Point | null;
31
+ };
32
+ /** A peer as an editor draws it. */
33
+ export interface PeerView<S> {
34
+ id: string;
35
+ name: string;
36
+ kind: 'person' | 'agent';
37
+ color: string;
38
+ /** Pointer on the surface (world px), `null` when it is elsewhere. */
39
+ cursor: Point | null;
40
+ /** The editor's own state of this peer, `null` when it published none (or it was malformed). */
41
+ state: S | null;
42
+ }
43
+ /**
44
+ * What an editor tells presence. `S` is what it publishes besides the pointer.
45
+ * The pointer goes out as `cursor` beside `S` (only when the editor gives
46
+ * {@link PresenceAdapter.pointer}).
47
+ */
48
+ export interface PresenceAdapter<S extends object> {
49
+ /** The presence key (one per editor type, e.g. `design`, `slides`). */
50
+ key: string;
51
+ /** This page's state now. */
52
+ snapshot(): S;
53
+ /** Reads a peer's value of {@link key} (already an object); `null` when unusable. */
54
+ parse(value: Record<string, unknown>): S | null;
55
+ /** Calls `changed` whenever {@link snapshot} may have changed; returns an unsubscribe. */
56
+ watch(changed: () => void): () => void;
57
+ /**
58
+ * The world point of a pointer event over the editor's surface; `null` when
59
+ * it is elsewhere. Omitted: the editor shares no pointer, nothing listens
60
+ * for one and the value goes out as {@link snapshot} alone (no `cursor`).
61
+ */
62
+ pointer?(event: PointerEvent): Point | null;
63
+ /** Least time between two sends of this page's value, ms (default 80). */
64
+ sendMs?: number;
65
+ /** Hears the room's peers (raw, this page included) after the store took them; `self` is this page's peer id. */
66
+ onPeers?(peers: readonly Peer[], self: string | null): void;
67
+ /** Maps a changed artifact path to what the editor tracks (a project path), or `null` to ignore it. */
68
+ wrotePath?(path: string): string | null;
69
+ }
70
+ /** The presence store. */
71
+ export interface PresenceState<S> {
72
+ available: boolean;
73
+ peers: PeerView<S>[];
74
+ /** The agent wrote these paths recently (as `wrotePath` mapped them); `null` when it has not. */
75
+ agentWrote: {
76
+ at: number;
77
+ paths: string[];
78
+ } | null;
79
+ }
80
+ /** Peers other than this page, as drawn (people first, then agents). */
81
+ export declare function peerViews<S>(peers: readonly Peer[], self: string | null, key: string, parse: (value: Record<string, unknown>) => S | null): PeerView<S>[];
82
+ /** One editor's presence. */
83
+ export interface PresenceController<S> {
84
+ readonly store: UseBoundStore<StoreApi<PresenceState<S>>>;
85
+ /** Starts publishing and listening; returns a function that stops it. */
86
+ start(input: {
87
+ room: RoomCapability | null;
88
+ artifact?: Pick<ArtifactCapability, 'onChange'> | null;
89
+ }): Promise<() => void>;
90
+ }
91
+ /** Creates an editor's presence. */
92
+ export declare function createPresence<S extends object>(adapter: PresenceAdapter<S>): PresenceController<S>;
@@ -0,0 +1,158 @@
1
+ /**
2
+ * Live presence for any editor, over the `room` capability: who else has
3
+ * the artifact open, where their pointer is and what the editor says they
4
+ * are doing (selection, page, editing); and the agent, shown for a few
5
+ * seconds after it writes.
6
+ *
7
+ * Editor-agnostic: the editor's
8
+ * {@link PresenceAdapter} says what it publishes under its key and reads
9
+ * peers' values back. Peers' values were written by their browsers: the
10
+ * adapter's `parse` must check and clip them.
11
+ */
12
+ import { create } from 'zustand';
13
+ /** Peer colors (cursor, outline, avatar). */
14
+ export const PEER_COLORS = ['#e5484d', '#0091ff', '#30a46c', '#f76b15', '#8e4ec6', '#d6409f', '#12a594', '#ad7f58'];
15
+ /** The agent's color. */
16
+ export const AGENT_COLOR = '#6e56cf';
17
+ /** How long the agent shows after it wrote (ms). */
18
+ export const AGENT_SHOWN_MS = 8000;
19
+ /** Pointer updates go out at most this often (ms). */
20
+ const SEND_MS = 80;
21
+ /** Most entries kept of any list read from a peer. */
22
+ export const PRESENCE_LIST_MAX = 50;
23
+ /** A stable color for a peer id. */
24
+ export function peerColor(id) {
25
+ let hash = 0;
26
+ for (let i = 0; i < id.length; i++)
27
+ hash = (hash * 31 + id.charCodeAt(i)) | 0;
28
+ return PEER_COLORS[Math.abs(hash) % PEER_COLORS.length];
29
+ }
30
+ /** Checked readers for peers' values. */
31
+ export const peerValue = {
32
+ str: (value, max = 512) => (typeof value === 'string' && value.length <= max ? value : null),
33
+ num: (value) => (typeof value === 'number' && Number.isFinite(value) ? value : null),
34
+ strList: (value, max = PRESENCE_LIST_MAX) => Array.isArray(value) ? value.map((v) => peerValue.str(v)).filter((v) => v !== null).slice(0, max) : [],
35
+ point: (value) => {
36
+ if (!value || typeof value !== 'object')
37
+ return null;
38
+ const v = value;
39
+ const x = peerValue.num(v.x);
40
+ const y = peerValue.num(v.y);
41
+ return x !== null && y !== null ? { x, y } : null;
42
+ },
43
+ };
44
+ /** Peers other than this page, as drawn (people first, then agents). */
45
+ export function peerViews(peers, self, key, parse) {
46
+ return peers
47
+ .filter((p) => p.id !== self)
48
+ .map((p) => {
49
+ const raw = p.state?.[key];
50
+ const value = raw && typeof raw === 'object' && !Array.isArray(raw) ? raw : null;
51
+ return {
52
+ id: p.id,
53
+ name: (p.name || (p.kind === 'agent' ? 'Agent' : 'Guest')).slice(0, 60),
54
+ kind: p.kind,
55
+ color: p.kind === 'agent' ? AGENT_COLOR : peerColor(p.id),
56
+ cursor: value ? peerValue.point(value.cursor) : null,
57
+ state: value ? parse(value) : null,
58
+ };
59
+ })
60
+ .sort((a, b) => (a.kind === b.kind ? a.name.localeCompare(b.name) : a.kind === 'person' ? -1 : 1));
61
+ }
62
+ /** Creates an editor's presence. */
63
+ export function createPresence(adapter) {
64
+ const store = create()(() => ({ available: false, peers: [], agentWrote: null }));
65
+ async function start({ room, artifact }) {
66
+ const stops = [];
67
+ // The agent's writes, whether or not there is a room.
68
+ let agentTimer = null;
69
+ if (artifact) {
70
+ stops.push(artifact.onChange((event) => {
71
+ if (event.author !== 'agent')
72
+ return;
73
+ const paths = Object.keys(event.changes)
74
+ .map((path) => (adapter.wrotePath ? adapter.wrotePath(path) : path))
75
+ .filter((p) => p !== null);
76
+ const previous = store.getState().agentWrote;
77
+ const recent = previous && Date.now() - previous.at < AGENT_SHOWN_MS ? previous.paths : [];
78
+ store.setState({ agentWrote: { at: Date.now(), paths: [...new Set([...recent, ...paths])].slice(0, PRESENCE_LIST_MAX) } });
79
+ if (agentTimer)
80
+ clearTimeout(agentTimer);
81
+ agentTimer = setTimeout(() => store.setState({ agentWrote: null }), AGENT_SHOWN_MS);
82
+ }));
83
+ stops.push(() => {
84
+ if (agentTimer)
85
+ clearTimeout(agentTimer);
86
+ });
87
+ }
88
+ if (!room)
89
+ return () => stops.forEach((stop) => stop());
90
+ store.setState({ available: true });
91
+ const self = await room.self().catch(() => null);
92
+ // This page's key: its state at once, then throttled (the pointer too).
93
+ const pointer = adapter.pointer?.bind(adapter);
94
+ const sendMs = adapter.sendMs ?? SEND_MS;
95
+ let cursor = null;
96
+ let last = '';
97
+ let timer = null;
98
+ const send = () => {
99
+ timer = null;
100
+ const value = pointer ? { ...adapter.snapshot(), cursor } : adapter.snapshot();
101
+ const text = JSON.stringify(value);
102
+ if (text === last)
103
+ return;
104
+ last = text;
105
+ room.presence({ [adapter.key]: value }).catch(() => undefined);
106
+ };
107
+ const schedule = () => {
108
+ if (!timer)
109
+ timer = setTimeout(send, sendMs);
110
+ };
111
+ send();
112
+ stops.push(adapter.watch(schedule));
113
+ const onMove = (event) => {
114
+ const world = pointer?.(event) ?? null;
115
+ if (!world) {
116
+ if (cursor) {
117
+ cursor = null;
118
+ schedule();
119
+ }
120
+ return;
121
+ }
122
+ cursor = { x: Math.round(world.x), y: Math.round(world.y) };
123
+ schedule();
124
+ };
125
+ const onLeave = () => {
126
+ cursor = null;
127
+ schedule();
128
+ };
129
+ const onVisibility = () => {
130
+ if (document.visibilityState === 'hidden')
131
+ onLeave();
132
+ };
133
+ if (pointer) {
134
+ window.addEventListener('pointermove', onMove, { passive: true });
135
+ document.addEventListener('pointerleave', onLeave);
136
+ document.addEventListener('visibilitychange', onVisibility);
137
+ }
138
+ stops.push(() => {
139
+ if (pointer) {
140
+ window.removeEventListener('pointermove', onMove);
141
+ document.removeEventListener('pointerleave', onLeave);
142
+ document.removeEventListener('visibilitychange', onVisibility);
143
+ }
144
+ if (timer)
145
+ clearTimeout(timer);
146
+ room.presence({ [adapter.key]: null }).catch(() => undefined);
147
+ });
148
+ // The peer list.
149
+ const heard = (peers) => {
150
+ store.setState({ peers: peerViews(peers, self, adapter.key, adapter.parse) });
151
+ adapter.onPeers?.(peers, self);
152
+ };
153
+ room.peers().then(heard, () => undefined);
154
+ stops.push(room.onPeers(heard));
155
+ return () => stops.forEach((stop) => stop());
156
+ }
157
+ return { store, start };
158
+ }
@@ -0,0 +1,46 @@
1
+ /**
2
+ * Loading the design systems an artifact installed (Design, Slides): each
3
+ * copy lives under `project/ds/<folder>/`; its `tokens.json` is read,
4
+ * normalized and handed to the editor, which turns it into what its menus
5
+ * offer. The copies are read again when the installed list changes or a
6
+ * `tokens.json` under `project/ds/` changes; an older read that finishes
7
+ * late is dropped. Pure (no DOM).
8
+ */
9
+ import { type NormalizedTokens } from '@openartifactsai/design-system-core';
10
+ import type { ArtifactCapability } from '@openartifactsai/runtime';
11
+ /** Where installed systems live, as an artifact path. */
12
+ export declare const DS_DIR = "project/ds/";
13
+ /** An installed copy as an artifact's index records it. */
14
+ export interface InstalledRecord {
15
+ namespace: string;
16
+ version?: string | null;
17
+ copiedAt: string;
18
+ }
19
+ /** What one read of every copy found. */
20
+ export interface SystemsRead<S> {
21
+ systems: S[];
22
+ /** Namespaces whose copy could not be read (no tokens.json, or not JSON). */
23
+ missing: string[];
24
+ }
25
+ /** What an editor supplies to {@link createSystemsLoader}. */
26
+ export interface SystemsLoaderAdapter<R extends InstalledRecord, S> {
27
+ /** The artifact to read from (`null`: not connected yet, nothing is read). */
28
+ artifact(): ArtifactCapability | null;
29
+ /** The installed records now. */
30
+ records(): readonly R[];
31
+ /** Calls `listener` whenever the editor's document changes (the loader checks whether the records did). */
32
+ subscribe(listener: () => void): unknown;
33
+ /** Reads a copy's normalized tokens into what the editor offers. */
34
+ read(record: R, tokens: NormalizedTokens): S;
35
+ /** Stores a finished read. */
36
+ loaded(result: SystemsRead<S>): void;
37
+ }
38
+ /** A loader made by {@link createSystemsLoader}. */
39
+ export interface SystemsLoader {
40
+ /** Re-reads every copy now. */
41
+ reload(): Promise<void>;
42
+ /** Reads the copies and keeps them current. Later calls do nothing. */
43
+ start(): void;
44
+ }
45
+ /** The loader of an editor's installed design systems. */
46
+ export declare function createSystemsLoader<R extends InstalledRecord, S>(adapter: SystemsLoaderAdapter<R, S>): SystemsLoader;
@@ -0,0 +1,61 @@
1
+ /**
2
+ * Loading the design systems an artifact installed (Design, Slides): each
3
+ * copy lives under `project/ds/<folder>/`; its `tokens.json` is read,
4
+ * normalized and handed to the editor, which turns it into what its menus
5
+ * offer. The copies are read again when the installed list changes or a
6
+ * `tokens.json` under `project/ds/` changes; an older read that finishes
7
+ * late is dropped. Pure (no DOM).
8
+ */
9
+ import { installedKey, normalizeTokens } from '@openartifactsai/design-system-core';
10
+ /** Where installed systems live, as an artifact path. */
11
+ export const DS_DIR = 'project/ds/';
12
+ /** The loader of an editor's installed design systems. */
13
+ export function createSystemsLoader(adapter) {
14
+ let generation = 0;
15
+ let started = false;
16
+ async function reload() {
17
+ const artifact = adapter.artifact();
18
+ if (!artifact)
19
+ return;
20
+ const run = ++generation;
21
+ const records = adapter.records();
22
+ const results = await Promise.all(records.map(async (record) => {
23
+ const text = await artifact.readText(`${DS_DIR}${record.namespace}/tokens.json`).catch(() => null);
24
+ if (text === null)
25
+ return { record, system: null };
26
+ try {
27
+ return { record, system: adapter.read(record, normalizeTokens(JSON.parse(text)).tokens) };
28
+ }
29
+ catch {
30
+ // Not JSON: the system offers nothing until it is fixed.
31
+ return { record, system: null };
32
+ }
33
+ }));
34
+ if (run !== generation)
35
+ return;
36
+ adapter.loaded({
37
+ systems: results.flatMap((r) => (r.system === null ? [] : [r.system])),
38
+ missing: results.flatMap((r) => (r.system === null ? [r.record.namespace] : [])),
39
+ });
40
+ }
41
+ function start() {
42
+ const artifact = adapter.artifact();
43
+ if (started || !artifact)
44
+ return;
45
+ started = true;
46
+ void reload();
47
+ let key = installedKey(adapter.records());
48
+ adapter.subscribe(() => {
49
+ const next = installedKey(adapter.records());
50
+ if (next === key)
51
+ return;
52
+ key = next;
53
+ void reload();
54
+ });
55
+ artifact.onChange((event) => {
56
+ if (Object.keys(event.changes).some((path) => path.startsWith(DS_DIR) && path.endsWith('/tokens.json')))
57
+ void reload();
58
+ });
59
+ }
60
+ return { reload, start };
61
+ }
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Saving files: through the host's `downloads` capability (it saves on the
3
+ * sharing computer and says where), else as a browser download. Every
4
+ * editor's exports and file downloads end here. No DOM until called.
5
+ */
6
+ import type { DownloadsCapability } from '@openartifactsai/runtime';
7
+ /** How long a browser download's object URL stays valid by default: time for the browser to start reading it. */
8
+ export declare const OBJECT_URL_KEEP_MS = 60000;
9
+ /** Clicks a hidden download link for `url`. */
10
+ export declare function browserDownloadUrl(url: string, name: string): void;
11
+ /** Starts a browser download of `data`; its object URL is revoked after `keepMs`. */
12
+ export declare function browserDownload(name: string, data: Blob, keepMs?: number): void;
13
+ /**
14
+ * Resolves when the person may export here now, else rejects with the host's refusal (`not_writer` and its words): an
15
+ * export that is not a file (a print) asks this first, so it follows the same switch as the downloads. Always
16
+ * resolves on a host that keeps no such switch (this computer). A consistency rule for the product's own buttons, not
17
+ * a security boundary: a viewer can always use the browser's own print or take a screenshot.
18
+ */
19
+ export declare function assertMayExport(downloads: DownloadsCapability | null | undefined): Promise<void>;
20
+ /** Where {@link saveFile} put a file. */
21
+ export type SavedFile = {
22
+ to: 'host';
23
+ savedTo?: string;
24
+ } | {
25
+ to: 'browser';
26
+ };
27
+ /**
28
+ * Saves `data` through `downloads` when the host grants it, else as a
29
+ * browser download. Rejects when the host refuses the file.
30
+ */
31
+ export declare function saveFile(downloads: DownloadsCapability | null | undefined, name: string, data: Blob, keepMs?: number): Promise<SavedFile>;
@@ -0,0 +1,46 @@
1
+ /**
2
+ * Saving files: through the host's `downloads` capability (it saves on the
3
+ * sharing computer and says where), else as a browser download. Every
4
+ * editor's exports and file downloads end here. No DOM until called.
5
+ */
6
+ /** How long a browser download's object URL stays valid by default: time for the browser to start reading it. */
7
+ export const OBJECT_URL_KEEP_MS = 60_000;
8
+ /** Clicks a hidden download link for `url`. */
9
+ export function browserDownloadUrl(url, name) {
10
+ const link = document.createElement('a');
11
+ link.href = url;
12
+ link.download = name;
13
+ link.rel = 'noopener';
14
+ link.style.display = 'none';
15
+ document.body.append(link);
16
+ link.click();
17
+ link.remove();
18
+ }
19
+ /** Starts a browser download of `data`; its object URL is revoked after `keepMs`. */
20
+ export function browserDownload(name, data, keepMs = OBJECT_URL_KEEP_MS) {
21
+ const url = URL.createObjectURL(data);
22
+ browserDownloadUrl(url, name);
23
+ setTimeout(() => URL.revokeObjectURL(url), keepMs);
24
+ }
25
+ /**
26
+ * Resolves when the person may export here now, else rejects with the host's refusal (`not_writer` and its words): an
27
+ * export that is not a file (a print) asks this first, so it follows the same switch as the downloads. Always
28
+ * resolves on a host that keeps no such switch (this computer). A consistency rule for the product's own buttons, not
29
+ * a security boundary: a viewer can always use the browser's own print or take a screenshot.
30
+ */
31
+ export async function assertMayExport(downloads) {
32
+ if (downloads?.browser === true && downloads.check)
33
+ await downloads.check();
34
+ }
35
+ /**
36
+ * Saves `data` through `downloads` when the host grants it, else as a
37
+ * browser download. Rejects when the host refuses the file.
38
+ */
39
+ export async function saveFile(downloads, name, data, keepMs) {
40
+ if (downloads) {
41
+ const { savedTo } = await downloads.save({ name, data });
42
+ return savedTo === undefined ? { to: 'host' } : { to: 'host', savedTo };
43
+ }
44
+ browserDownload(name, data, keepMs);
45
+ return { to: 'browser' };
46
+ }
@@ -0,0 +1,33 @@
1
+ /**
2
+ * A file dropped where nothing takes it (a read-only canvas, panels, toolbars)
3
+ * would make the browser open the file in place of the editor. This guard
4
+ * swallows such drops; a handler that takes the drop has already prevented its
5
+ * default, and an enabled file input keeps its own drop.
6
+ */
7
+ /** Minimal shape of a drag event target, so the guard runs without a DOM. */
8
+ export interface FileDropTarget {
9
+ readonly tagName?: string;
10
+ readonly type?: string;
11
+ readonly disabled?: boolean;
12
+ }
13
+ /** The parts of a drag event the guard reads. */
14
+ export interface FileDragEvent {
15
+ readonly type: string;
16
+ readonly defaultPrevented: boolean;
17
+ readonly target?: EventTarget | FileDropTarget | null;
18
+ readonly dataTransfer: {
19
+ types: ArrayLike<string> | Iterable<string>;
20
+ dropEffect: string;
21
+ } | null;
22
+ composedPath?(): readonly unknown[];
23
+ preventDefault(): void;
24
+ }
25
+ /** The parts of a window the guard listens on. */
26
+ export interface FileDropWindow {
27
+ addEventListener(type: 'dragover' | 'drop', listener: (event: FileDragEvent) => void): void;
28
+ removeEventListener(type: 'dragover' | 'drop', listener: (event: FileDragEvent) => void): void;
29
+ }
30
+ /** True when the drag carries files from outside the page. */
31
+ export declare function carriesFiles(event: FileDragEvent): boolean;
32
+ /** Installs the guard; returns a function that removes it. */
33
+ export declare function guardFileDrops(win: FileDropWindow): () => void;
@@ -0,0 +1,36 @@
1
+ /**
2
+ * A file dropped where nothing takes it (a read-only canvas, panels, toolbars)
3
+ * would make the browser open the file in place of the editor. This guard
4
+ * swallows such drops; a handler that takes the drop has already prevented its
5
+ * default, and an enabled file input keeps its own drop.
6
+ */
7
+ /** True when the drag carries files from outside the page. */
8
+ export function carriesFiles(event) {
9
+ return Array.from(event.dataTransfer?.types ?? []).includes('Files');
10
+ }
11
+ function isEnabledFileInput(node) {
12
+ if (typeof node !== 'object' || node === null)
13
+ return false;
14
+ const target = node;
15
+ return typeof target.tagName === 'string' && target.tagName.toLowerCase() === 'input' && target.type === 'file' && target.disabled !== true;
16
+ }
17
+ function landsOnFileInput(event) {
18
+ const first = event.composedPath?.()[0] ?? event.target ?? null;
19
+ return isEnabledFileInput(first);
20
+ }
21
+ /** Installs the guard; returns a function that removes it. */
22
+ export function guardFileDrops(win) {
23
+ const guard = (event) => {
24
+ if (event.defaultPrevented || !carriesFiles(event) || landsOnFileInput(event))
25
+ return;
26
+ event.preventDefault();
27
+ if (event.type === 'dragover' && event.dataTransfer)
28
+ event.dataTransfer.dropEffect = 'none';
29
+ };
30
+ win.addEventListener('dragover', guard);
31
+ win.addEventListener('drop', guard);
32
+ return () => {
33
+ win.removeEventListener('dragover', guard);
34
+ win.removeEventListener('drop', guard);
35
+ };
36
+ }
package/src/find.d.ts ADDED
@@ -0,0 +1,64 @@
1
+ /**
2
+ * Find (⌘F) as every editor has it: a query, the matches in reading order,
3
+ * the one shown, Enter / ⇧Enter to step (wrapping), Escape to close, and
4
+ * the matched words highlighted with the CSS Custom Highlight API where the
5
+ * browser has it. There is no replace.
6
+ *
7
+ * The editor supplies what differs: how it searches its document, where it
8
+ * starts, how it shows a match, and which element owns a run of rendered
9
+ * text. Pure (no DOM until a highlight is drawn).
10
+ */
11
+ import { type StoreApi, type UseBoundStore } from 'zustand';
12
+ /** Start offsets of each case-insensitive occurrence of `needle` in `text` (no overlaps). */
13
+ export declare function occurrences(text: string, needle: string): number[];
14
+ /** A short excerpt around an occurrence, for the find bar and screen readers. */
15
+ export declare function excerpt(text: string, at: number, length: number, radius?: number): string;
16
+ /** Steps through `count` matches from `index`, wrapping around; -1 when there are none. */
17
+ export declare function stepIndex(index: number, count: number, delta: 1 | -1): number;
18
+ /** The find bar's state. */
19
+ export interface FindState<M> {
20
+ query: string;
21
+ matches: M[];
22
+ /** The match shown, or -1. */
23
+ index: number;
24
+ setQuery(query: string): void;
25
+ step(delta: 1 | -1): void;
26
+ close(): void;
27
+ }
28
+ /** What an editor supplies to {@link createFind}. */
29
+ export interface FindAdapter<M> {
30
+ /** Every match of `query` in the document as it is now (none for a blank query). */
31
+ search(query: string): M[];
32
+ /** The match a new search starts at (default: the first). */
33
+ start?(matches: readonly M[]): number;
34
+ /** Shows a match: its page or slide, its element selected and in view. */
35
+ reveal(match: M, index: number, count: number): void;
36
+ /** A non-blank query found nothing. */
37
+ noResults?(): void;
38
+ /** After the state was reset on close: hide the bar, remove highlights. */
39
+ onClose(): void;
40
+ }
41
+ /**
42
+ * The find bar's store. Stepping searches again first: the document may
43
+ * have changed since the search.
44
+ */
45
+ export declare function createFind<M>(adapter: FindAdapter<M>): UseBoundStore<StoreApi<FindState<M>>>;
46
+ /** Highlight names: every match, and the one shown. */
47
+ export declare const FIND_HIGHLIGHT = "open-artifacts-find";
48
+ export declare const FIND_HIGHLIGHT_CURRENT = "open-artifacts-find-current";
49
+ /** Removes the find highlights of a document. */
50
+ export declare function clearFindHighlights(doc: Document): void;
51
+ /** The element a run of text belongs to, as matches count occurrences. */
52
+ export interface TextOwner {
53
+ /** Occurrences are counted per key, in document order. */
54
+ key: string;
55
+ /** The shown match is in this element. */
56
+ current: boolean;
57
+ }
58
+ /**
59
+ * Highlights `query` in the text under `root` (replacing the document's
60
+ * find highlights). `ownerOf` names the element each text node counts
61
+ * under (`null`: skip the text); the occurrence `currentOccurrence` of the
62
+ * current owner gets the stronger color.
63
+ */
64
+ export declare function highlightText(doc: Document, root: Node | null, query: string, ownerOf: (parent: Element) => TextOwner | null, currentOccurrence?: number): void;