@open-artifact/ui 0.0.0-stage → 0.2.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 (48) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +5 -0
  3. package/README.md +5 -2
  4. package/package.json +48 -4
  5. package/src/button.d.ts +30 -0
  6. package/src/button.js +28 -0
  7. package/src/cn.d.ts +3 -0
  8. package/src/cn.js +5 -0
  9. package/src/color-picker.d.ts +98 -0
  10. package/src/color-picker.js +370 -0
  11. package/src/color.d.ts +144 -0
  12. package/src/color.js +528 -0
  13. package/src/data/google-fonts.json +1775 -0
  14. package/src/effect-editors.d.ts +48 -0
  15. package/src/effect-editors.js +230 -0
  16. package/src/effects.d.ts +118 -0
  17. package/src/effects.js +425 -0
  18. package/src/fields.d.ts +105 -0
  19. package/src/fields.js +77 -0
  20. package/src/focusables.d.ts +26 -0
  21. package/src/focusables.js +42 -0
  22. package/src/font-picker.d.ts +62 -0
  23. package/src/font-picker.js +238 -0
  24. package/src/fonts.d.ts +121 -0
  25. package/src/fonts.js +273 -0
  26. package/src/history-diff.d.ts +64 -0
  27. package/src/history-diff.js +151 -0
  28. package/src/history.d.ts +95 -0
  29. package/src/history.js +160 -0
  30. package/src/index.d.ts +25 -0
  31. package/src/index.js +25 -0
  32. package/src/keys.d.ts +60 -0
  33. package/src/keys.js +78 -0
  34. package/src/layout.d.ts +55 -0
  35. package/src/layout.js +64 -0
  36. package/src/menu.d.ts +50 -0
  37. package/src/menu.js +36 -0
  38. package/src/numbers.d.ts +24 -0
  39. package/src/numbers.js +114 -0
  40. package/src/overlays.d.ts +38 -0
  41. package/src/overlays.js +26 -0
  42. package/src/scroll.d.ts +24 -0
  43. package/src/scroll.js +111 -0
  44. package/src/scrub-number-field.d.ts +56 -0
  45. package/src/scrub-number-field.js +190 -0
  46. package/src/styles.css +122 -0
  47. package/src/tooltip.d.ts +18 -0
  48. package/src/tooltip.js +10 -0
package/src/fonts.js ADDED
@@ -0,0 +1,273 @@
1
+ /**
2
+ * Fonts for the font picker: the Google Fonts catalog (loaded on demand from
3
+ * `data/google-fonts.json`), search, stylesheet URLs, and which families
4
+ * render on this computer.
5
+ *
6
+ * Everything here except {@link isFontAvailable}, {@link detectInstalledFonts}
7
+ * and {@link ensureFontPreview} runs without a DOM.
8
+ */
9
+ /** Categories in the order the picker groups them. */
10
+ export const FONT_CATEGORIES = [
11
+ { value: 'sans-serif', label: 'Sans serif' },
12
+ { value: 'serif', label: 'Serif' },
13
+ { value: 'display', label: 'Display' },
14
+ { value: 'handwriting', label: 'Handwriting' },
15
+ { value: 'monospace', label: 'Monospace' },
16
+ ];
17
+ /** Digit-string weights ("3457", "a" for 1000) to numbers. */
18
+ function weightsOf(digits) {
19
+ return [...digits].map((d) => (d === 'a' ? 1000 : Number(d) * 100));
20
+ }
21
+ /** Expands the stored catalog into {@link GoogleFont} records, in popularity order. */
22
+ export function decodeFontCatalog(file) {
23
+ return file.families.map((row, rank) => {
24
+ const [family, category, weights, italics, axes] = row;
25
+ return {
26
+ family,
27
+ category: (file.categories[category] ?? 'sans-serif'),
28
+ weights: weightsOf(weights),
29
+ italics: weightsOf(italics),
30
+ axes: axes
31
+ ? axes.split(',').map((axis) => {
32
+ const [tag, min, max] = axis.split(':');
33
+ return { tag: tag, min: Number(min), max: Number(max) };
34
+ })
35
+ : [],
36
+ rank,
37
+ };
38
+ });
39
+ }
40
+ let catalogPromise = null;
41
+ /**
42
+ * The Google Fonts catalog, loaded once on first use (the JSON is a separate
43
+ * chunk, about 64 KB, 15 KB gzipped).
44
+ */
45
+ export function loadGoogleFontCatalog() {
46
+ // Bundlers (Vite) serve JSON as a JS module and the browser then rejects
47
+ // a `type: 'json'` attribute; Node needs it. Try the plain import first.
48
+ catalogPromise ??= import('./data/google-fonts.json')
49
+ .catch(() => import('./data/google-fonts.json', { with: { type: 'json' } }))
50
+ .then((module) => decodeFontCatalog(module.default))
51
+ .catch((error) => {
52
+ catalogPromise = null;
53
+ throw error;
54
+ });
55
+ return catalogPromise;
56
+ }
57
+ /* --------------------------------- search --------------------------------- */
58
+ /** Lowercase, accents and punctuation dropped, spaces collapsed. */
59
+ export function normalizeFontName(name) {
60
+ return name
61
+ .normalize('NFKD')
62
+ .replace(/[̀-ͯ]/g, '')
63
+ .toLowerCase()
64
+ .replace(/[^a-z0-9]+/g, ' ')
65
+ .trim();
66
+ }
67
+ /**
68
+ * How well `family` matches `query` (already normalized); higher is better,
69
+ * 0 for no match. Exact > prefix > word prefix > substring > initials
70
+ * ("ibm" for "IBM Plex Sans", "pf" for "Playfair").
71
+ */
72
+ export function fontMatchScore(family, query) {
73
+ if (!query)
74
+ return 1;
75
+ const name = normalizeFontName(family);
76
+ if (name === query)
77
+ return 100;
78
+ const compact = name.replace(/ /g, '');
79
+ const q = query.replace(/ /g, '');
80
+ if (name.startsWith(query) || compact.startsWith(q))
81
+ return 80;
82
+ const words = name.split(' ');
83
+ if (words.some((word) => word.startsWith(query)))
84
+ return 60;
85
+ if (query.includes(' ')) {
86
+ // Every query word starts some word of the name, in order.
87
+ const parts = query.split(' ');
88
+ let at = 0;
89
+ if (parts.every((part) => {
90
+ while (at < words.length && !words[at].startsWith(part))
91
+ at++;
92
+ return at++ < words.length;
93
+ }))
94
+ return 50;
95
+ }
96
+ if (compact.includes(q))
97
+ return 40;
98
+ const initials = words.map((word) => word[0]).join('');
99
+ if (q.length >= 2 && initials.startsWith(q))
100
+ return 30;
101
+ return 0;
102
+ }
103
+ /**
104
+ * Catalog families matching `query`, best match first, ties by popularity.
105
+ * An empty query lists the catalog in popularity order.
106
+ */
107
+ export function searchFonts(catalog, query, options = {}) {
108
+ const q = normalizeFontName(query);
109
+ const pool = options.category ? catalog.filter((font) => font.category === options.category) : catalog;
110
+ const scored = [];
111
+ for (const font of pool) {
112
+ const score = fontMatchScore(font.family, q);
113
+ if (score > 0)
114
+ scored.push({ font, score });
115
+ }
116
+ scored.sort((a, b) => b.score - a.score || a.font.rank - b.font.rank);
117
+ const out = scored.map((entry) => entry.font);
118
+ return options.limit === undefined ? out : out.slice(0, options.limit);
119
+ }
120
+ /** The catalog entry for `family` (case and spacing ignored). */
121
+ export function findGoogleFont(catalog, family) {
122
+ const key = normalizeFontName(family);
123
+ return catalog.find((font) => normalizeFontName(font.family) === key);
124
+ }
125
+ /** The catalog entry of `family`, loading the catalog if needed. */
126
+ export async function lookupGoogleFont(family) {
127
+ return findGoogleFont(await loadGoogleFontCatalog(), family);
128
+ }
129
+ /* ------------------------------- stylesheets ------------------------------ */
130
+ const CSS2 = 'https://fonts.googleapis.com/css2';
131
+ /** Family name as the css2 API writes it. */
132
+ const familyParam = (family) => encodeURIComponent(family.trim()).replace(/%20/g, '+');
133
+ /**
134
+ * The Google Fonts CSS URL for `family`. With the catalog entry, the
135
+ * request names only weights and italics the family has (the API rejects
136
+ * others); without one it asks for the weights given (default 400).
137
+ */
138
+ export function googleFontStylesheetUrl(family, options = {}, font) {
139
+ const display = `display=${options.display ?? 'swap'}`;
140
+ const text = options.text ? `&text=${encodeURIComponent(options.text)}` : '';
141
+ const head = `${CSS2}?family=${familyParam(family)}`;
142
+ const wght = font?.axes.find((axis) => axis.tag === 'wght');
143
+ const italic = Boolean(options.italic) && (!font || font.italics.length > 0);
144
+ if (options.variable && wght) {
145
+ const range = `${wght.min}..${wght.max}`;
146
+ const spec = italic ? `:ital,wght@0,${range};1,${range}` : `:wght@${range}`;
147
+ return `${head}${spec}&${display}${text}`;
148
+ }
149
+ const available = font ? font.weights : null;
150
+ const wanted = options.weights?.length ? [...options.weights] : available ? [400, 700] : [400];
151
+ let upright = available ? wanted.filter((w) => available.includes(w)) : wanted;
152
+ if (!upright.length && available)
153
+ upright = [available.includes(400) ? 400 : available[0]];
154
+ upright = [...new Set(upright)].sort((a, b) => a - b);
155
+ if (!italic) {
156
+ // A family with only 400 needs no axis spec.
157
+ if (upright.length === 1 && upright[0] === 400)
158
+ return `${head}&${display}${text}`;
159
+ return `${head}:wght@${upright.join(';')}&${display}${text}`;
160
+ }
161
+ const slanted = font ? upright.filter((w) => font.italics.includes(w)) : upright;
162
+ const tuples = [...upright.map((w) => `0,${w}`), ...slanted.map((w) => `1,${w}`)];
163
+ return `${head}:ital,wght@${tuples.join(';')}&${display}${text}`;
164
+ }
165
+ /** The CSS `font-family` value for a family with a generic fallback. */
166
+ export function fontFamilyCss(family, category) {
167
+ const generic = category === 'serif' ? 'serif' : category === 'monospace' ? 'monospace' : category === 'handwriting' ? 'cursive' : 'sans-serif';
168
+ if (GENERIC_FAMILIES.has(family.toLowerCase()))
169
+ return family;
170
+ const quoted = /^[a-z][a-z0-9-]*$/i.test(family) ? family : `"${family.replace(/"/g, '\\"')}"`;
171
+ return `${quoted}, ${generic}`;
172
+ }
173
+ /* ------------------------------ availability ------------------------------ */
174
+ /** CSS generic families and keywords, which always render. */
175
+ export const GENERIC_FAMILIES = new Set([
176
+ 'serif', 'sans-serif', 'monospace', 'cursive', 'fantasy', 'system-ui', 'ui-serif', 'ui-sans-serif', 'ui-monospace', 'ui-rounded', 'math', 'emoji', 'fangsong',
177
+ ]);
178
+ /**
179
+ * Families commonly installed on macOS, Windows, Linux, iOS and Android.
180
+ * {@link detectInstalledFonts} checks which of them render here.
181
+ */
182
+ export const COMMON_SYSTEM_FONTS = [
183
+ 'American Typewriter', 'Andale Mono', 'Arial', 'Arial Black', 'Arial Narrow', 'Arial Rounded MT Bold', 'Avenir', 'Avenir Next',
184
+ 'Avenir Next Condensed', 'Baskerville', 'Big Caslon', 'Bodoni 72', 'Bradley Hand', 'Calibri', 'Cambria', 'Candara', 'Chalkboard',
185
+ 'Chalkduster', 'Charter', 'Cochin', 'Comic Sans MS', 'Consolas', 'Constantia', 'Copperplate', 'Corbel', 'Courier', 'Courier New',
186
+ 'DejaVu Sans', 'DejaVu Sans Mono', 'DejaVu Serif', 'Didot', 'Franklin Gothic Medium', 'Futura', 'Garamond', 'Geneva', 'Georgia',
187
+ 'Gill Sans', 'Helvetica', 'Helvetica Neue', 'Hoefler Text', 'Impact', 'Iowan Old Style', 'Liberation Mono', 'Liberation Sans',
188
+ 'Liberation Serif', 'Lucida Console', 'Lucida Grande', 'Marker Felt', 'Menlo', 'Monaco', 'New York', 'Noteworthy', 'Optima',
189
+ 'Palatino', 'Palatino Linotype', 'Papyrus', 'Rockwell', 'Segoe Print', 'Segoe Script', 'Segoe UI', 'SF Mono', 'SF Pro', 'SF Pro Display',
190
+ 'SF Pro Text', 'Skia', 'Snell Roundhand', 'Tahoma', 'Times', 'Times New Roman', 'Trebuchet MS', 'Ubuntu', 'Ubuntu Mono', 'Verdana', 'Zapfino',
191
+ ];
192
+ /** Family names worth measuring: letters, digits, spaces, dashes. */
193
+ const MEASURABLE = /^[A-Za-z0-9][A-Za-z0-9 _.-]*$/;
194
+ /** Text whose width differs between most faces. */
195
+ const SAMPLE = 'mmmmmmmmmmlli';
196
+ /**
197
+ * True when `family` measures differently from both the monospace and the
198
+ * serif fallback (a missing family falls back to them and measures the
199
+ * same). `measure(font)` returns the width of a sample in a CSS `font`
200
+ * shorthand.
201
+ */
202
+ export function fontRenders(family, measure) {
203
+ const name = family.trim();
204
+ if (GENERIC_FAMILIES.has(name.toLowerCase()))
205
+ return true;
206
+ if (!MEASURABLE.test(name))
207
+ return false;
208
+ return ['monospace', 'serif'].some((fallback) => measure(`100px "${name}", ${fallback}`) !== measure(`100px ${fallback}`));
209
+ }
210
+ const availability = new Map();
211
+ let measureContext;
212
+ /** {@link fontRenders} measured on a canvas, cached per family. False outside a browser. */
213
+ export function isFontAvailable(family) {
214
+ const key = family.trim().toLowerCase();
215
+ const hit = availability.get(key);
216
+ if (hit !== undefined)
217
+ return hit;
218
+ if (measureContext === undefined)
219
+ measureContext = typeof document === 'undefined' ? null : document.createElement('canvas').getContext('2d');
220
+ const ctx = measureContext;
221
+ if (!ctx)
222
+ return GENERIC_FAMILIES.has(key);
223
+ const available = fontRenders(family, (font) => {
224
+ ctx.font = font;
225
+ return ctx.measureText(SAMPLE).width;
226
+ });
227
+ availability.set(key, available);
228
+ return available;
229
+ }
230
+ /**
231
+ * Families that render here: those of `candidates` (default
232
+ * {@link COMMON_SYSTEM_FONTS}) that are installed, plus every family the
233
+ * page has loaded with `@font-face` (preview faces excluded). Sorted by name.
234
+ */
235
+ export function detectInstalledFonts(candidates = COMMON_SYSTEM_FONTS) {
236
+ const found = new Map();
237
+ for (const family of candidates)
238
+ if (isFontAvailable(family))
239
+ found.set(family.toLowerCase(), family);
240
+ if (typeof document !== 'undefined' && document.fonts) {
241
+ document.fonts.forEach((face) => {
242
+ if (face.status !== 'loaded')
243
+ return;
244
+ const family = face.family.replace(/^["']|["']$/g, '');
245
+ if (previewFamilies.has(family.toLowerCase()))
246
+ return;
247
+ if (!found.has(family.toLowerCase()))
248
+ found.set(family.toLowerCase(), family);
249
+ });
250
+ }
251
+ return [...found.values()].sort((a, b) => a.localeCompare(b));
252
+ }
253
+ /* -------------------------------- previews -------------------------------- */
254
+ const previewFamilies = new Set();
255
+ const previewLinks = new Set();
256
+ /**
257
+ * Loads just the glyphs of `family`'s own name (a few KB) so a picker row
258
+ * can show the name in its face. Adds one `<link>` per family, once.
259
+ */
260
+ export function ensureFontPreview(family, font) {
261
+ if (typeof document === 'undefined')
262
+ return;
263
+ const href = googleFontStylesheetUrl(family, { weights: font?.weights.includes(400) ? [400] : font ? [font.weights[0]] : [400], text: family, display: 'block' }, font);
264
+ if (previewLinks.has(href))
265
+ return;
266
+ previewLinks.add(href);
267
+ previewFamilies.add(family.toLowerCase());
268
+ const link = document.createElement('link');
269
+ link.rel = 'stylesheet';
270
+ link.href = href;
271
+ link.dataset.fontPreview = family;
272
+ document.head.appendChild(link);
273
+ }
@@ -0,0 +1,64 @@
1
+ /**
2
+ * The pure parts of {@link HistoryPanel}: a line diff with context hunks,
3
+ * and grouping versions by day and author. Kept free of React so tests can
4
+ * run them directly.
5
+ */
6
+ /** One line of a diff: kept (`' '`), removed (`'-'`) or added (`'+'`), with its line numbers. */
7
+ export interface DiffLine {
8
+ op: ' ' | '-' | '+';
9
+ text: string;
10
+ /** 1-based line number before (kept, removed) and after (kept, added). */
11
+ before?: number;
12
+ after?: number;
13
+ }
14
+ /** A run of changed lines with some kept lines around it. */
15
+ export interface DiffHunk {
16
+ lines: DiffLine[];
17
+ /** Kept lines left out before this hunk (0 for the first one when it starts at the top). */
18
+ skippedBefore: number;
19
+ }
20
+ /** Above this many cells (lines before × lines after, after trimming the common ends) the middle is shown as removed then added. */
21
+ export declare const DIFF_MAX_CELLS = 4000000;
22
+ /**
23
+ * The line diff of `before` → `after` (`null`: the file did not exist):
24
+ * every line in order, kept, removed or added. Common leading and trailing
25
+ * lines are matched first, the middle by longest common subsequence.
26
+ */
27
+ export declare function diffLines(before: string | null, after: string | null): DiffLine[];
28
+ /** How many lines `diffLines` removed and added. */
29
+ export declare function diffStats(lines: readonly DiffLine[]): {
30
+ removed: number;
31
+ added: number;
32
+ };
33
+ /** The changed parts of a diff, each with up to `context` kept lines around it. */
34
+ export declare function diffHunks(lines: readonly DiffLine[], context?: number): DiffHunk[];
35
+ /** The fields of a version that grouping reads (structurally the runtime's `HistoryVersion`). */
36
+ export interface GroupableVersion {
37
+ at: string;
38
+ author: {
39
+ kind: string;
40
+ id: string;
41
+ };
42
+ restoredFrom?: number;
43
+ }
44
+ /** Versions of one day, as runs of one author each. */
45
+ export interface VersionDay<V> {
46
+ /** Local `YYYY-MM-DD`. */
47
+ key: string;
48
+ /** Noon of that day, for formatting. */
49
+ date: Date;
50
+ runs: {
51
+ author: V extends {
52
+ author: infer A;
53
+ } ? A : never;
54
+ versions: V[];
55
+ }[];
56
+ }
57
+ /** Local `YYYY-MM-DD` of a time. */
58
+ export declare function dayKey(date: Date): string;
59
+ /**
60
+ * Groups versions (newest first, as listed) by local day, and within a day
61
+ * into runs of consecutive versions by one author. A restore starts a run
62
+ * of its own, so it stands out.
63
+ */
64
+ export declare function groupVersions<V extends GroupableVersion>(versions: readonly V[]): VersionDay<V>[];
@@ -0,0 +1,151 @@
1
+ /**
2
+ * The pure parts of {@link HistoryPanel}: a line diff with context hunks,
3
+ * and grouping versions by day and author. Kept free of React so tests can
4
+ * run them directly.
5
+ */
6
+ /** Above this many cells (lines before × lines after, after trimming the common ends) the middle is shown as removed then added. */
7
+ export const DIFF_MAX_CELLS = 4_000_000;
8
+ function splitLines(text) {
9
+ if (text === null || text === '')
10
+ return [];
11
+ const lines = text.split('\n');
12
+ // A trailing newline ends the last line; it does not start another.
13
+ if (lines[lines.length - 1] === '')
14
+ lines.pop();
15
+ return lines;
16
+ }
17
+ /**
18
+ * The line diff of `before` → `after` (`null`: the file did not exist):
19
+ * every line in order, kept, removed or added. Common leading and trailing
20
+ * lines are matched first, the middle by longest common subsequence.
21
+ */
22
+ export function diffLines(before, after) {
23
+ const a = splitLines(before);
24
+ const b = splitLines(after);
25
+ let start = 0;
26
+ while (start < a.length && start < b.length && a[start] === b[start])
27
+ start++;
28
+ let endA = a.length;
29
+ let endB = b.length;
30
+ while (endA > start && endB > start && a[endA - 1] === b[endB - 1]) {
31
+ endA--;
32
+ endB--;
33
+ }
34
+ const out = [];
35
+ let i = 0;
36
+ let j = 0;
37
+ const keep = () => void out.push({ op: ' ', text: a[i], before: ++i, after: ++j });
38
+ const remove = () => void out.push({ op: '-', text: a[i], before: ++i });
39
+ const add = () => void out.push({ op: '+', text: b[j], after: ++j });
40
+ while (i < start)
41
+ keep();
42
+ const n = endA - start;
43
+ const m = endB - start;
44
+ if (n * m > DIFF_MAX_CELLS) {
45
+ while (i < endA)
46
+ remove();
47
+ while (j < endB)
48
+ add();
49
+ }
50
+ else if (n && m) {
51
+ // lcs[x][y]: the longest common subsequence of a[start+x..endA) and b[start+y..endB).
52
+ const width = m + 1;
53
+ const lcs = new Uint32Array((n + 1) * width);
54
+ for (let x = n - 1; x >= 0; x--) {
55
+ for (let y = m - 1; y >= 0; y--) {
56
+ lcs[x * width + y] =
57
+ a[start + x] === b[start + y] ? lcs[(x + 1) * width + y + 1] + 1 : Math.max(lcs[(x + 1) * width + y], lcs[x * width + y + 1]);
58
+ }
59
+ }
60
+ while (i < endA && j < endB) {
61
+ const x = i - start;
62
+ const y = j - start;
63
+ if (a[i] === b[j])
64
+ keep();
65
+ else if (lcs[(x + 1) * width + y] >= lcs[x * width + y + 1])
66
+ remove();
67
+ else
68
+ add();
69
+ }
70
+ while (i < endA)
71
+ remove();
72
+ while (j < endB)
73
+ add();
74
+ }
75
+ else {
76
+ while (i < endA)
77
+ remove();
78
+ while (j < endB)
79
+ add();
80
+ }
81
+ while (i < a.length)
82
+ keep();
83
+ return out;
84
+ }
85
+ /** How many lines `diffLines` removed and added. */
86
+ export function diffStats(lines) {
87
+ let removed = 0;
88
+ let added = 0;
89
+ for (const line of lines) {
90
+ if (line.op === '-')
91
+ removed++;
92
+ else if (line.op === '+')
93
+ added++;
94
+ }
95
+ return { removed, added };
96
+ }
97
+ /** The changed parts of a diff, each with up to `context` kept lines around it. */
98
+ export function diffHunks(lines, context = 3) {
99
+ const changed = lines.flatMap((line, index) => (line.op === ' ' ? [] : [index]));
100
+ const hunks = [];
101
+ let shownTo = 0;
102
+ let k = 0;
103
+ while (k < changed.length) {
104
+ const from = Math.max(changed[k] - context, shownTo);
105
+ let to = changed[k] + 1;
106
+ // Join changes whose context would touch.
107
+ while (k + 1 < changed.length && changed[k + 1] - to <= context * 2)
108
+ to = changed[++k] + 1;
109
+ k++;
110
+ const end = Math.min(to + context, lines.length);
111
+ hunks.push({ lines: lines.slice(from, end), skippedBefore: from - shownTo });
112
+ shownTo = end;
113
+ }
114
+ return hunks;
115
+ }
116
+ /** Local `YYYY-MM-DD` of a time. */
117
+ export function dayKey(date) {
118
+ const pad = (n) => String(n).padStart(2, '0');
119
+ return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;
120
+ }
121
+ /**
122
+ * Groups versions (newest first, as listed) by local day, and within a day
123
+ * into runs of consecutive versions by one author. A restore starts a run
124
+ * of its own, so it stands out.
125
+ */
126
+ export function groupVersions(versions) {
127
+ const days = [];
128
+ for (const version of versions) {
129
+ const at = new Date(version.at);
130
+ const key = dayKey(at);
131
+ let day = days[days.length - 1];
132
+ if (!day || day.key !== key) {
133
+ day = { key, date: new Date(at.getFullYear(), at.getMonth(), at.getDate(), 12), runs: [] };
134
+ days.push(day);
135
+ }
136
+ const run = day.runs[day.runs.length - 1];
137
+ const last = run?.versions[run.versions.length - 1];
138
+ if (run &&
139
+ last &&
140
+ last.restoredFrom === undefined &&
141
+ version.restoredFrom === undefined &&
142
+ run.author.kind === version.author.kind &&
143
+ run.author.id === version.author.id) {
144
+ run.versions.push(version);
145
+ }
146
+ else {
147
+ day.runs.push({ author: version.author, versions: [version] });
148
+ }
149
+ }
150
+ return days;
151
+ }
@@ -0,0 +1,95 @@
1
+ export * from './history-diff.ts';
2
+ /** Who made a version (the runtime's `HistoryAuthor`). */
3
+ export interface HistoryPanelAuthor {
4
+ kind: 'person' | 'agent' | 'system';
5
+ id: string;
6
+ name: string;
7
+ }
8
+ /** One version (the runtime's `HistoryVersion`). */
9
+ export interface HistoryPanelVersion {
10
+ n: number;
11
+ first: string;
12
+ at: string;
13
+ author: HistoryPanelAuthor;
14
+ files: {
15
+ path: string;
16
+ op: 'added' | 'edited' | 'deleted';
17
+ }[];
18
+ restoredFrom?: number;
19
+ current?: true;
20
+ overwrote?: {
21
+ path: string;
22
+ n: number;
23
+ author: HistoryPanelAuthor;
24
+ }[];
25
+ }
26
+ /** A lost-change notice (the runtime's `HistoryNotice`). */
27
+ export interface HistoryPanelNotice {
28
+ id: string;
29
+ at: string;
30
+ path: string;
31
+ n: number;
32
+ author: HistoryPanelAuthor;
33
+ lost: {
34
+ n: number;
35
+ author: HistoryPanelAuthor;
36
+ deleted?: true;
37
+ };
38
+ }
39
+ /** One path before and after a version (the runtime's `HistoryFileDiff`). */
40
+ export interface HistoryPanelDiff {
41
+ path: string;
42
+ n: number;
43
+ op: 'added' | 'edited' | 'deleted';
44
+ before: string | null;
45
+ after: string | null;
46
+ binary?: true;
47
+ tooLarge?: true;
48
+ }
49
+ /** What the panel calls: the runtime's `HistoryCapability` fits. */
50
+ export interface HistoryPanelSource {
51
+ list(): Promise<{
52
+ versions: HistoryPanelVersion[];
53
+ notices: HistoryPanelNotice[];
54
+ canRestore: boolean;
55
+ }>;
56
+ diff(n: number, path: string): Promise<HistoryPanelDiff>;
57
+ restore(n: number, paths?: string[]): Promise<{
58
+ version: number | null;
59
+ changed: string[];
60
+ }>;
61
+ dismissNotice(id: string): Promise<void>;
62
+ onChange(listener: (event: {
63
+ n: number | null;
64
+ }) => void): () => void;
65
+ }
66
+ /** Props of {@link HistoryPanel}. */
67
+ export interface HistoryPanelProps {
68
+ history: HistoryPanelSource;
69
+ /** The viewer's id: their versions read "You". */
70
+ viewerId?: string;
71
+ /**
72
+ * Show the artifact as version `n` left it (`null`: back to the current
73
+ * files). Without it there is no Preview button. The page renders the
74
+ * preview itself, e.g. from `history.files(n)` and `history.read(n, path)`.
75
+ */
76
+ onPreview?: (n: number | null) => void;
77
+ /** The version being previewed, highlighted in the list. */
78
+ previewing?: number | null;
79
+ /** After a restore wrote something. */
80
+ onRestored?: (result: {
81
+ version: number | null;
82
+ changed: string[];
83
+ }, from: number) => void;
84
+ /** Shows a close button. */
85
+ onClose?: () => void;
86
+ /** How a path reads (default: without `project/` or `db/`). */
87
+ formatPath?: (path: string) => string;
88
+ className?: string;
89
+ }
90
+ /** A file's line diff, changed parts with three lines of context. */
91
+ export declare function HistoryDiffView({ diff }: {
92
+ diff: HistoryPanelDiff;
93
+ }): import("react/jsx-runtime").JSX.Element;
94
+ /** The version history of the open artifact. */
95
+ export declare function HistoryPanel({ history, viewerId, onPreview, previewing, onRestored, onClose, formatPath, className }: HistoryPanelProps): import("react/jsx-runtime").JSX.Element;