@open-artifact/editor-kit 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (82) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +5 -0
  3. package/README.md +128 -2
  4. package/package.json +58 -4
  5. package/src/Announcer.d.ts +2 -0
  6. package/src/Announcer.js +8 -0
  7. package/src/FindBar.d.ts +31 -0
  8. package/src/FindBar.js +34 -0
  9. package/src/agent.d.ts +20 -0
  10. package/src/agent.js +40 -0
  11. package/src/announce.d.ts +18 -0
  12. package/src/announce.js +21 -0
  13. package/src/chrome.d.ts +180 -0
  14. package/src/chrome.js +108 -0
  15. package/src/collab/CommentList.d.ts +23 -0
  16. package/src/collab/CommentList.js +117 -0
  17. package/src/collab/CommentViews.d.ts +116 -0
  18. package/src/collab/CommentViews.js +531 -0
  19. package/src/collab/HistoryViews.d.ts +38 -0
  20. package/src/collab/HistoryViews.js +103 -0
  21. package/src/collab/PresenceViews.d.ts +52 -0
  22. package/src/collab/PresenceViews.js +46 -0
  23. package/src/collab/cds/cds.d.ts +148 -0
  24. package/src/collab/cds/cds.js +230 -0
  25. package/src/collab/cds/comment-card.d.ts +93 -0
  26. package/src/collab/cds/comment-card.js +211 -0
  27. package/src/collab/cds/comment-composer.d.ts +28 -0
  28. package/src/collab/cds/comment-composer.js +101 -0
  29. package/src/collab/cds/comments-css.d.ts +2 -0
  30. package/src/collab/cds/comments-css.js +3 -0
  31. package/src/collab/cds/comments.css +497 -0
  32. package/src/collab/cds/edge-piles.d.ts +69 -0
  33. package/src/collab/cds/edge-piles.js +178 -0
  34. package/src/collab/cds/layer.d.ts +41 -0
  35. package/src/collab/cds/layer.js +143 -0
  36. package/src/collab/cds/markdown.d.ts +17 -0
  37. package/src/collab/cds/markdown.js +507 -0
  38. package/src/collab/cds/shield.d.ts +28 -0
  39. package/src/collab/cds/shield.js +114 -0
  40. package/src/collab/cds/time.d.ts +2 -0
  41. package/src/collab/cds/time.js +41 -0
  42. package/src/collab/collab.d.ts +100 -0
  43. package/src/collab/collab.js +119 -0
  44. package/src/collab/comments.d.ts +147 -0
  45. package/src/collab/comments.js +287 -0
  46. package/src/collab/history-wiring.d.ts +32 -0
  47. package/src/collab/history-wiring.js +53 -0
  48. package/src/collab/history.d.ts +53 -0
  49. package/src/collab/history.js +94 -0
  50. package/src/collab/peer-colors.d.ts +123 -0
  51. package/src/collab/peer-colors.js +273 -0
  52. package/src/collab/pins.d.ts +70 -0
  53. package/src/collab/pins.js +44 -0
  54. package/src/collab/presence.d.ts +92 -0
  55. package/src/collab/presence.js +158 -0
  56. package/src/design-systems.d.ts +46 -0
  57. package/src/design-systems.js +61 -0
  58. package/src/downloads.d.ts +24 -0
  59. package/src/downloads.js +36 -0
  60. package/src/find.d.ts +64 -0
  61. package/src/find.js +147 -0
  62. package/src/index.d.ts +25 -0
  63. package/src/index.js +25 -0
  64. package/src/keys.d.ts +13 -0
  65. package/src/keys.js +20 -0
  66. package/src/merge.d.ts +23 -0
  67. package/src/merge.js +116 -0
  68. package/src/page-link.d.ts +33 -0
  69. package/src/page-link.js +75 -0
  70. package/src/project-sync.d.ts +118 -0
  71. package/src/project-sync.js +174 -0
  72. package/src/react.d.ts +16 -0
  73. package/src/react.js +16 -0
  74. package/src/roles.d.ts +33 -0
  75. package/src/roles.js +26 -0
  76. package/src/session.d.ts +42 -0
  77. package/src/session.js +37 -0
  78. package/src/shell.d.ts +56 -0
  79. package/src/shell.js +96 -0
  80. package/src/stash.d.ts +26 -0
  81. package/src/stash.js +66 -0
  82. package/src/styles.css +17 -0
@@ -0,0 +1,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 '@open-artifact/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,24 @@
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 '@open-artifact/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
+ /** Where {@link saveFile} put a file. */
14
+ export type SavedFile = {
15
+ to: 'host';
16
+ savedTo?: string;
17
+ } | {
18
+ to: 'browser';
19
+ };
20
+ /**
21
+ * Saves `data` through `downloads` when the host grants it, else as a
22
+ * browser download. Rejects when the host refuses the file.
23
+ */
24
+ export declare function saveFile(downloads: DownloadsCapability | null | undefined, name: string, data: Blob, keepMs?: number): Promise<SavedFile>;
@@ -0,0 +1,36 @@
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
+ * Saves `data` through `downloads` when the host grants it, else as a
27
+ * browser download. Rejects when the host refuses the file.
28
+ */
29
+ export async function saveFile(downloads, name, data, keepMs) {
30
+ if (downloads) {
31
+ const { savedTo } = await downloads.save({ name, data });
32
+ return savedTo === undefined ? { to: 'host' } : { to: 'host', savedTo };
33
+ }
34
+ browserDownload(name, data, keepMs);
35
+ return { to: 'browser' };
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-artifact-find";
48
+ export declare const FIND_HIGHLIGHT_CURRENT = "open-artifact-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;
package/src/find.js ADDED
@@ -0,0 +1,147 @@
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 { create } from 'zustand';
12
+ /* -------------------------------------------------------------------------- */
13
+ /* Matching */
14
+ /* -------------------------------------------------------------------------- */
15
+ /** Start offsets of each case-insensitive occurrence of `needle` in `text` (no overlaps). */
16
+ export function occurrences(text, needle) {
17
+ const hay = text.toLowerCase();
18
+ const n = needle.toLowerCase();
19
+ if (!n)
20
+ return [];
21
+ const out = [];
22
+ for (let at = hay.indexOf(n); at >= 0; at = hay.indexOf(n, at + n.length))
23
+ out.push(at);
24
+ return out;
25
+ }
26
+ /** A short excerpt around an occurrence, for the find bar and screen readers. */
27
+ export function excerpt(text, at, length, radius = 24) {
28
+ const start = Math.max(0, at - radius);
29
+ const end = Math.min(text.length, at + length + radius);
30
+ return `${start > 0 ? '…' : ''}${text.slice(start, end)}${end < text.length ? '…' : ''}`;
31
+ }
32
+ /** Steps through `count` matches from `index`, wrapping around; -1 when there are none. */
33
+ export function stepIndex(index, count, delta) {
34
+ if (count <= 0)
35
+ return -1;
36
+ if (index < 0)
37
+ return delta > 0 ? 0 : count - 1;
38
+ return (((index + delta) % count) + count) % count;
39
+ }
40
+ /**
41
+ * The find bar's store. Stepping searches again first: the document may
42
+ * have changed since the search.
43
+ */
44
+ export function createFind(adapter) {
45
+ return create()((set, get) => ({
46
+ query: '',
47
+ matches: [],
48
+ index: -1,
49
+ setQuery(query) {
50
+ const matches = adapter.search(query);
51
+ const index = matches.length ? (adapter.start?.(matches) ?? 0) : -1;
52
+ set({ query, matches, index });
53
+ if (!query.trim())
54
+ return;
55
+ if (matches.length)
56
+ adapter.reveal(matches[index], index, matches.length);
57
+ else
58
+ adapter.noResults?.();
59
+ },
60
+ step(delta) {
61
+ const { index, query } = get();
62
+ const fresh = adapter.search(query);
63
+ const next = stepIndex(Math.min(index, fresh.length - 1), fresh.length, delta);
64
+ set({ matches: fresh, index: next });
65
+ if (next >= 0)
66
+ adapter.reveal(fresh[next], next, fresh.length);
67
+ },
68
+ close() {
69
+ set({ query: '', matches: [], index: -1 });
70
+ adapter.onClose();
71
+ },
72
+ }));
73
+ }
74
+ /* -------------------------------------------------------------------------- */
75
+ /* Highlights */
76
+ /* -------------------------------------------------------------------------- */
77
+ /** Highlight names: every match, and the one shown. */
78
+ export const FIND_HIGHLIGHT = 'open-artifact-find';
79
+ export const FIND_HIGHLIGHT_CURRENT = 'open-artifact-find-current';
80
+ /** A window's highlight registry, when the browser has one. */
81
+ function registry(win) {
82
+ const css = win?.CSS;
83
+ const Highlight = win?.Highlight;
84
+ return css?.highlights && Highlight ? { highlights: css.highlights, Highlight } : null;
85
+ }
86
+ /**
87
+ * The highlight colors, injected at runtime: `::highlight()` is newer than
88
+ * the build's CSS minifier, which warns about it in a stylesheet.
89
+ */
90
+ const HIGHLIGHT_CSS = `::highlight(${FIND_HIGHLIGHT}){background-color:rgb(250 204 21 / .45);color:inherit}::highlight(${FIND_HIGHLIGHT_CURRENT}){background-color:rgb(249 115 22 / .75);color:inherit}`;
91
+ function installStyles(doc) {
92
+ if (doc.getElementById('open-artifact-find-styles'))
93
+ return;
94
+ const style = doc.createElement('style');
95
+ style.id = 'open-artifact-find-styles';
96
+ style.textContent = HIGHLIGHT_CSS;
97
+ (doc.head ?? doc.documentElement).appendChild(style);
98
+ }
99
+ /** Removes the find highlights of a document. */
100
+ export function clearFindHighlights(doc) {
101
+ const reg = registry(doc.defaultView);
102
+ reg?.highlights.delete(FIND_HIGHLIGHT);
103
+ reg?.highlights.delete(FIND_HIGHLIGHT_CURRENT);
104
+ }
105
+ /**
106
+ * Highlights `query` in the text under `root` (replacing the document's
107
+ * find highlights). `ownerOf` names the element each text node counts
108
+ * under (`null`: skip the text); the occurrence `currentOccurrence` of the
109
+ * current owner gets the stronger color.
110
+ */
111
+ export function highlightText(doc, root, query, ownerOf, currentOccurrence) {
112
+ const reg = registry(doc.defaultView);
113
+ if (!reg)
114
+ return;
115
+ reg.highlights.delete(FIND_HIGHLIGHT);
116
+ reg.highlights.delete(FIND_HIGHLIGHT_CURRENT);
117
+ const needle = query.trim().toLowerCase();
118
+ if (!root || !needle)
119
+ return;
120
+ installStyles(doc);
121
+ const all = [];
122
+ const strong = [];
123
+ const counts = new Map();
124
+ const walker = doc.createTreeWalker(root, NodeFilter.SHOW_TEXT);
125
+ for (let node = walker.nextNode(); node; node = walker.nextNode()) {
126
+ const parent = node.parentElement;
127
+ const owner = parent ? ownerOf(parent) : null;
128
+ if (!owner)
129
+ continue;
130
+ const text = node.textContent?.toLowerCase() ?? '';
131
+ for (let at = text.indexOf(needle); at >= 0; at = text.indexOf(needle, at + needle.length)) {
132
+ const range = doc.createRange();
133
+ range.setStart(node, at);
134
+ range.setEnd(node, at + needle.length);
135
+ const n = counts.get(owner.key) ?? 0;
136
+ counts.set(owner.key, n + 1);
137
+ if (owner.current && n === currentOccurrence)
138
+ strong.push(range);
139
+ else
140
+ all.push(range);
141
+ }
142
+ }
143
+ if (all.length)
144
+ reg.highlights.set(FIND_HIGHLIGHT, new reg.Highlight(...all));
145
+ if (strong.length)
146
+ reg.highlights.set(FIND_HIGHLIGHT_CURRENT, new reg.Highlight(...strong));
147
+ }
package/src/index.d.ts ADDED
@@ -0,0 +1,25 @@
1
+ /**
2
+ * `@open-artifact/editor-kit`: the logic every artifact editor shares. This
3
+ * entry is pure TypeScript (no JSX), so node's test runner loads it; the
4
+ * React views are in `@open-artifact/editor-kit/react`.
5
+ */
6
+ export * from './collab/comments.ts';
7
+ export * from './collab/history.ts';
8
+ export * from './collab/history-wiring.ts';
9
+ export * from './collab/presence.ts';
10
+ export * from './collab/peer-colors.ts';
11
+ export * from './collab/collab.ts';
12
+ export * from './collab/pins.ts';
13
+ export * from './announce.ts';
14
+ export * from './page-link.ts';
15
+ export * from './stash.ts';
16
+ export * from './merge.ts';
17
+ export * from './project-sync.ts';
18
+ export * from './keys.ts';
19
+ export * from './roles.ts';
20
+ export * from './session.ts';
21
+ export * from './shell.ts';
22
+ export * from './agent.ts';
23
+ export * from './downloads.ts';
24
+ export * from './find.ts';
25
+ export * from './design-systems.ts';
package/src/index.js ADDED
@@ -0,0 +1,25 @@
1
+ /**
2
+ * `@open-artifact/editor-kit`: the logic every artifact editor shares. This
3
+ * entry is pure TypeScript (no JSX), so node's test runner loads it; the
4
+ * React views are in `@open-artifact/editor-kit/react`.
5
+ */
6
+ export * from "./collab/comments.js";
7
+ export * from "./collab/history.js";
8
+ export * from "./collab/history-wiring.js";
9
+ export * from "./collab/presence.js";
10
+ export * from "./collab/peer-colors.js";
11
+ export * from "./collab/collab.js";
12
+ export * from "./collab/pins.js";
13
+ export * from "./announce.js";
14
+ export * from "./page-link.js";
15
+ export * from "./stash.js";
16
+ export * from "./merge.js";
17
+ export * from "./project-sync.js";
18
+ export * from "./keys.js";
19
+ export * from "./roles.js";
20
+ export * from "./session.js";
21
+ export * from "./shell.js";
22
+ export * from "./agent.js";
23
+ export * from "./downloads.js";
24
+ export * from "./find.js";
25
+ export * from "./design-systems.js";
package/src/keys.d.ts ADDED
@@ -0,0 +1,13 @@
1
+ /** Platform key labels and the text-field test every editor's shortcuts use. Pure. */
2
+ /** True on Apple platforms (⌘ instead of Ctrl in labels and shortcuts). */
3
+ export declare function isApplePlatform(): boolean;
4
+ /** The platform's modifier key, as shortcuts are written. */
5
+ export declare const MOD: string;
6
+ /** The platform's option key. */
7
+ export declare const ALT: string;
8
+ /** The platform's shift key. */
9
+ export declare const SHIFT: string;
10
+ /** The platform's modifier label, read now. */
11
+ export declare function modKey(): string;
12
+ /** True when a key or clipboard event goes to a text field (input, textarea, select or editable text). */
13
+ export declare function isTextField(target: EventTarget | null): boolean;
package/src/keys.js ADDED
@@ -0,0 +1,20 @@
1
+ /** Platform key labels and the text-field test every editor's shortcuts use. Pure. */
2
+ /** True on Apple platforms (⌘ instead of Ctrl in labels and shortcuts). */
3
+ export function isApplePlatform() {
4
+ return typeof navigator !== 'undefined' && /Mac|iPhone|iPad|iPod/.test(navigator.platform || navigator.userAgent);
5
+ }
6
+ /** The platform's modifier key, as shortcuts are written. */
7
+ export const MOD = isApplePlatform() ? '⌘' : 'Ctrl+';
8
+ /** The platform's option key. */
9
+ export const ALT = MOD === '⌘' ? '⌥' : 'Alt+';
10
+ /** The platform's shift key. */
11
+ export const SHIFT = MOD === '⌘' ? '⇧' : 'Shift+';
12
+ /** The platform's modifier label, read now. */
13
+ export function modKey() {
14
+ return isApplePlatform() ? '⌘' : 'Ctrl+';
15
+ }
16
+ /** True when a key or clipboard event goes to a text field (input, textarea, select or editable text). */
17
+ export function isTextField(target) {
18
+ const element = target;
19
+ return Boolean(element && (element.isContentEditable || /^(INPUT|TEXTAREA|SELECT)$/.test(element.tagName)));
20
+ }
package/src/merge.d.ts ADDED
@@ -0,0 +1,23 @@
1
+ /**
2
+ * Three-way line merge of a text file both this page and someone else (the
3
+ * agent, another viewer) changed since the page last read it. When the two
4
+ * sides changed different lines of the version both started from, the
5
+ * merge keeps both changes; when they changed the same lines differently
6
+ * (or inserted different lines at the same place) there is no merge and
7
+ * the editor asks the person.
8
+ *
9
+ * Changes to lines right next to each other merge by default; an editor
10
+ * whose files read as one unit (a slide's HTML) passes
11
+ * `{ adjacent: 'conflict' }` to give up on those too. Pure.
12
+ */
13
+ /** How {@link mergeLines} treats changes to neighbouring lines. */
14
+ export interface LineMergeOptions {
15
+ /** `merge` (default): neighbouring changes both apply. `conflict`: they need the person. */
16
+ adjacent?: 'merge' | 'conflict';
17
+ }
18
+ /**
19
+ * Merges `ours` and `theirs`, both edited from `base`, line by line. Returns
20
+ * the merged text, or `null` when both changed the same region differently
21
+ * (or the files are too large to compare).
22
+ */
23
+ export declare function mergeLines(base: string, ours: string, theirs: string, options?: LineMergeOptions): string | null;
package/src/merge.js ADDED
@@ -0,0 +1,116 @@
1
+ /**
2
+ * Three-way line merge of a text file both this page and someone else (the
3
+ * agent, another viewer) changed since the page last read it. When the two
4
+ * sides changed different lines of the version both started from, the
5
+ * merge keeps both changes; when they changed the same lines differently
6
+ * (or inserted different lines at the same place) there is no merge and
7
+ * the editor asks the person.
8
+ *
9
+ * Changes to lines right next to each other merge by default; an editor
10
+ * whose files read as one unit (a slide's HTML) passes
11
+ * `{ adjacent: 'conflict' }` to give up on those too. Pure.
12
+ */
13
+ /** Largest LCS table the merge builds (base lines × other lines); larger files are not merged. */
14
+ const MAX_CELLS = 4_000_000;
15
+ const same = (a, b) => a.length === b.length && a.every((line, i) => line === b[i]);
16
+ /** The changes that turn `a` into `b`; `null` when the files are too large to compare. */
17
+ function hunks(a, b) {
18
+ // Common head and tail first: most edits are small.
19
+ let head = 0;
20
+ while (head < a.length && head < b.length && a[head] === b[head])
21
+ head++;
22
+ let tail = 0;
23
+ while (tail < a.length - head && tail < b.length - head && a[a.length - 1 - tail] === b[b.length - 1 - tail])
24
+ tail++;
25
+ const x = a.slice(head, a.length - tail);
26
+ const y = b.slice(head, b.length - tail);
27
+ if ((x.length + 1) * (y.length + 1) > MAX_CELLS)
28
+ return null;
29
+ const width = y.length + 1;
30
+ const table = new Uint32Array((x.length + 1) * width);
31
+ for (let i = x.length - 1; i >= 0; i--) {
32
+ for (let j = y.length - 1; j >= 0; j--)
33
+ table[i * width + j] = x[i] === y[j] ? table[(i + 1) * width + j + 1] + 1 : Math.max(table[(i + 1) * width + j], table[i * width + j + 1]);
34
+ }
35
+ const out = [];
36
+ let current = null;
37
+ let i = 0;
38
+ let j = 0;
39
+ const flush = () => {
40
+ if (current)
41
+ out.push(current);
42
+ current = null;
43
+ };
44
+ while (i < x.length || j < y.length) {
45
+ if (i < x.length && j < y.length && x[i] === y[j]) {
46
+ flush();
47
+ i++;
48
+ j++;
49
+ }
50
+ else if (j >= y.length || (i < x.length && table[(i + 1) * width + j] >= table[i * width + j + 1])) {
51
+ current ??= { start: head + i, end: head + i, lines: [] };
52
+ current.end = head + i + 1;
53
+ i++;
54
+ }
55
+ else {
56
+ current ??= { start: head + i, end: head + i, lines: [] };
57
+ current.lines.push(y[j]);
58
+ j++;
59
+ }
60
+ }
61
+ flush();
62
+ return out;
63
+ }
64
+ /** True when two changes touch the same base lines (or insert at the same place); with `adjacent`, also when they meet. */
65
+ function clash(a, b, adjacent) {
66
+ if (adjacent)
67
+ return Math.max(a.start, b.start) <= Math.min(a.end, b.end);
68
+ if (a.start === b.start && (a.start === a.end || b.start === b.end))
69
+ return true;
70
+ if (a.start === a.end)
71
+ return b.start < a.start && a.start < b.end;
72
+ if (b.start === b.end)
73
+ return a.start < b.start && b.start < a.end;
74
+ return Math.max(a.start, b.start) < Math.min(a.end, b.end);
75
+ }
76
+ /**
77
+ * Merges `ours` and `theirs`, both edited from `base`, line by line. Returns
78
+ * the merged text, or `null` when both changed the same region differently
79
+ * (or the files are too large to compare).
80
+ */
81
+ export function mergeLines(base, ours, theirs, options = {}) {
82
+ if (ours === theirs)
83
+ return ours;
84
+ if (base === ours)
85
+ return theirs;
86
+ if (base === theirs)
87
+ return ours;
88
+ const adjacent = options.adjacent === 'conflict';
89
+ const lines = base.split('\n');
90
+ const mine = hunks(lines, ours.split('\n'));
91
+ const other = hunks(lines, theirs.split('\n'));
92
+ if (!mine || !other)
93
+ return null;
94
+ const all = [];
95
+ for (const hunk of mine) {
96
+ const twin = other.find((candidate) => clash(hunk, candidate, adjacent));
97
+ if (!twin) {
98
+ all.push(hunk);
99
+ continue;
100
+ }
101
+ // The same change on both sides is no conflict.
102
+ if (twin.start === hunk.start && twin.end === hunk.end && same(twin.lines, hunk.lines))
103
+ continue;
104
+ return null;
105
+ }
106
+ all.push(...other);
107
+ all.sort((a, b) => a.start - b.start || a.end - b.end);
108
+ const out = [];
109
+ let at = 0;
110
+ for (const hunk of all) {
111
+ out.push(...lines.slice(at, hunk.start), ...hunk.lines);
112
+ at = hunk.end;
113
+ }
114
+ out.push(...lines.slice(at));
115
+ return out.join('\n');
116
+ }
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Page addresses: the page shown is kept in the address as `#page=<id>`,
3
+ * so a copied link opens that page and the browser's back and forward step
4
+ * between the pages visited. Other `#` parameters are kept.
5
+ */
6
+ /** The page named by a location hash, or `null`. */
7
+ export declare function pageFromHash(hash: string): string | null;
8
+ /** The hash showing `page` (`null`: none), keeping other parameters. */
9
+ export declare function hashForPage(hash: string, page: string | null): string;
10
+ /**
11
+ * The shareable link to a page: the editor's address without its query
12
+ * (which can carry session parameters), with the page in the hash.
13
+ */
14
+ export declare function pageLink(href: string, page: string | null): string;
15
+ /** What {@link syncPageHistory} needs from an editor: plain callbacks, no store. */
16
+ export interface PageHistoryHost {
17
+ /** The page shown now (`null`: the first / only page). */
18
+ current(): string | null;
19
+ /** Shows a page (from back / forward). */
20
+ show(page: string | null): void;
21
+ /** Whether a page id exists. */
22
+ exists(page: string): boolean;
23
+ /** The page to show when the address names none. */
24
+ fallback(): string | null;
25
+ /** Calls `listener` whenever the page shown changes; returns an unsubscribe. */
26
+ subscribe(listener: (page: string | null) => void): () => void;
27
+ }
28
+ /**
29
+ * Keeps the address bar's `#page=` in step with the page shown: a page
30
+ * switch pushes a history entry, back and forward switch back. Returns a
31
+ * dispose function. Works on `window`'s location and history.
32
+ */
33
+ export declare function syncPageHistory(host: PageHistoryHost): () => void;
@@ -0,0 +1,75 @@
1
+ /**
2
+ * Page addresses: the page shown is kept in the address as `#page=<id>`,
3
+ * so a copied link opens that page and the browser's back and forward step
4
+ * between the pages visited. Other `#` parameters are kept.
5
+ */
6
+ /** The page named by a location hash, or `null`. */
7
+ export function pageFromHash(hash) {
8
+ const params = new URLSearchParams(hash.replace(/^#/, ''));
9
+ const page = params.get('page');
10
+ return page ? page : null;
11
+ }
12
+ /** The hash showing `page` (`null`: none), keeping other parameters. */
13
+ export function hashForPage(hash, page) {
14
+ const params = new URLSearchParams(hash.replace(/^#/, ''));
15
+ if (page)
16
+ params.set('page', page);
17
+ else
18
+ params.delete('page');
19
+ const text = params.toString();
20
+ return text ? `#${text}` : '';
21
+ }
22
+ /**
23
+ * The shareable link to a page: the editor's address without its query
24
+ * (which can carry session parameters), with the page in the hash.
25
+ */
26
+ export function pageLink(href, page) {
27
+ const url = new URL(href);
28
+ return `${url.origin}${url.pathname}${hashForPage(url.hash, page)}`;
29
+ }
30
+ /**
31
+ * Keeps the address bar's `#page=` in step with the page shown: a page
32
+ * switch pushes a history entry, back and forward switch back. Returns a
33
+ * dispose function. Works on `window`'s location and history.
34
+ */
35
+ export function syncPageHistory(host) {
36
+ let applying = false;
37
+ const write = (page, push) => {
38
+ const hash = hashForPage(location.hash, page);
39
+ if (hash === location.hash || (!hash && !location.hash))
40
+ return;
41
+ const url = `${location.pathname}${location.search}${hash}`;
42
+ try {
43
+ if (push)
44
+ history.pushState(history.state, '', url);
45
+ else
46
+ history.replaceState(history.state, '', url);
47
+ }
48
+ catch {
49
+ // Sandboxed frames may refuse history changes.
50
+ }
51
+ };
52
+ write(host.current(), false);
53
+ const unsubscribe = host.subscribe((page) => {
54
+ if (!applying)
55
+ write(page, true);
56
+ });
57
+ const onPop = () => {
58
+ const named = pageFromHash(location.hash);
59
+ const page = named && host.exists(named) ? named : host.fallback();
60
+ if (page === host.current())
61
+ return;
62
+ applying = true;
63
+ try {
64
+ host.show(page);
65
+ }
66
+ finally {
67
+ applying = false;
68
+ }
69
+ };
70
+ window.addEventListener('popstate', onPop);
71
+ return () => {
72
+ unsubscribe();
73
+ window.removeEventListener('popstate', onPop);
74
+ };
75
+ }