okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221merge f-split-ui5 e9a2ca44a (round-7 UI, time-skip fixes, mode switch mid-goal, /plan, queued messages, uninstaller icon; includes agent6 eecb29593) into f-split-int743a6b3c6

main
6.8 KiB138 linesraw
1/**
2 * The pure parts of the Time-skip A versus B view: what kind of file it is (the view adapts to it), which words changed, which lines
3 * changed, and how an HTML page is made safe to show. The same window serves every kind, so none of this decides a size.
4 */
5export type FileKind = 'markdown' | 'text' | 'html' | 'image' | 'code' | 'other';
6
7const IMAGE = /\.(png|jpe?g|gif|webp|svg|bmp)$/i;
8const MARKDOWN = /\.(md|markdown|mdx)$/i;
9const TEXT = /\.(txt|text|log|rst|csv|tsv)$/i;
10const HTML = /\.(html?|xhtml)$/i;
11
12export function fileKind(path: string, file?: { image?: boolean; unreadable?: boolean }): FileKind {
13  if (file?.image || IMAGE.test(path)) return 'image';
14  if (file?.unreadable) return 'other';
15  if (MARKDOWN.test(path)) return 'markdown';
16  if (HTML.test(path)) return 'html';
17  if (TEXT.test(path)) return 'text';
18  return 'code';
19}
20
21export interface Segment { text: string; changed: boolean }
22
23/** Cap on the work a diff may do (a product of the two lengths); past it the whole text counts as changed rather than freezing the page. */
24const WORK_LIMIT = 6_000_000;
25
26function lcsPairs(a: string[], b: string[]): [number, number][] | null {
27  if (a.length * b.length > WORK_LIMIT) return null;
28  const w = b.length + 1;
29  const table = new Uint32Array((a.length + 1) * w);
30  for (let i = a.length - 1; i >= 0; i--) for (let j = b.length - 1; j >= 0; j--) {
31    table[i * w + j] = a[i] === b[j] ? table[(i + 1) * w + j + 1] + 1 : Math.max(table[(i + 1) * w + j], table[i * w + j + 1]);
32  }
33  const pairs: [number, number][] = [];
34  let i = 0, j = 0;
35  while (i < a.length && j < b.length) {
36    if (a[i] === b[j]) { pairs.push([i, j]); i++; j++; }
37    else if (table[(i + 1) * w + j] >= table[i * w + j + 1]) i++;
38    else j++;
39  }
40  return pairs;
41}
42
43const tokens = (text: string) => text.split(/(\s+)/).filter(t => t !== '');
44
45function joinSegments(parts: string[], keep: Set<number>): Segment[] {
46  const flags = parts.map((text, i) => /\S/.test(text) && !keep.has(i));
47  // Whitespace between two changed words belongs to the mark, so a changed phrase reads as one.
48  parts.forEach((text, i) => { if (!/\S/.test(text) && i > 0 && i < parts.length - 1 && flags[i - 1] && flags[i + 1]) flags[i] = true; });
49  const out: Segment[] = [];
50  parts.forEach((text, i) => {
51    const last = out.at(-1);
52    if (last && last.changed === flags[i]) last.text += text; else out.push({ text, changed: flags[i] });
53  });
54  return out;
55}
56
57/** The words of both versions with the changed ones marked. Unchanged text is identical on both sides. */
58export function wordDiff(original: string, updated: string): { original: Segment[]; updated: Segment[] } {
59  const a = tokens(original), b = tokens(updated);
60  const pairs = lcsPairs(a, b);
61  if (!pairs) return { original: [{ text: original, changed: original !== updated }], updated: [{ text: updated, changed: original !== updated }] };
62  const keepA = new Set(pairs.map(p => p[0])), keepB = new Set(pairs.map(p => p[1]));
63  return { original: joinSegments(a, keepA), updated: joinSegments(b, keepB) };
64}
65
66/** Split marked segments into lines, so a page can lay out headings, lists and paragraphs and still mark words inside them. */
67export function segmentLines(segments: Segment[]): Segment[][] {
68  const lines: Segment[][] = [[]];
69  for (const seg of segments) {
70    const parts = seg.text.split(/\r?\n/);
71    parts.forEach((part, i) => {
72      if (i > 0) lines.push([]);
73      if (part) lines[lines.length - 1].push({ text: part, changed: seg.changed });
74    });
75  }
76  return lines;
77}
78
79export type DiffRow =
80  | { t: 'same' | 'add' | 'del'; text: string; a?: number; b?: number }
81  | { t: 'gap'; n: number };
82
83/** A line diff for code and other text, with unchanged stretches folded to one "n unchanged lines" row so it stays short. */
84export function lineDiff(original: string, updated: string, context = 2): DiffRow[] {
85  const a = original === '' ? [] : original.split(/\r?\n/), b = updated === '' ? [] : updated.split(/\r?\n/);
86  const pairs = lcsPairs(a, b);
87  const rows: DiffRow[] = [];
88  if (!pairs) {
89    a.forEach((text, i) => rows.push({ t: 'del', text, a: i + 1 }));
90    b.forEach((text, j) => rows.push({ t: 'add', text, b: j + 1 }));
91    return rows;
92  }
93  let i = 0, j = 0;
94  const flush = (ei: number, ej: number) => {
95    while (i < ei) { rows.push({ t: 'del', text: a[i], a: i + 1 }); i++; }
96    while (j < ej) { rows.push({ t: 'add', text: b[j], b: j + 1 }); j++; }
97  };
98  for (const [pi, pj] of pairs) { flush(pi, pj); rows.push({ t: 'same', text: a[pi], a: pi + 1, b: pj + 1 }); i = pi + 1; j = pj + 1; }
99  flush(a.length, b.length);
100  // fold unchanged stretches longer than twice the context
101  const out: DiffRow[] = [];
102  let k = 0;
103  while (k < rows.length) {
104    if (rows[k].t !== 'same') { out.push(rows[k]); k++; continue; }
105    let end = k;
106    while (end < rows.length && rows[end].t === 'same') end++;
107    const run = rows.slice(k, end);
108    const head = k === 0 ? 0 : context, tail = end === rows.length ? 0 : context;
109    if (run.length > head + tail + 1) {
110      out.push(...run.slice(0, head), { t: 'gap', n: run.length - head - tail }, ...run.slice(run.length - tail));
111    } else out.push(...run);
112    k = end;
113  }
114  return out;
115}
116
117export const diffStats = (rows: DiffRow[]) => ({ added: rows.filter(r => r.t === 'add').length, removed: rows.filter(r => r.t === 'del').length });
118
119/**
120 * A page for the preview frame. The frame is sandboxed without a same-origin right, forms, navigation or pop-ups; it may run the page's own
121 * scripts, because most pages people ask for (a 3D scene, a game, a chart) draw themselves with a script and would show as an empty dark
122 * page without one. The content policy still blocks every request to the internet: only what was written is shown.
123 */
124export const HTML_PREVIEW_SANDBOX = 'allow-scripts';
125export function htmlPreviewDocument(html: string): string {
126  const policy = '<meta http-equiv="Content-Security-Policy" content="default-src \'none\'; script-src \'unsafe-inline\' \'unsafe-eval\'; img-src data: blob:; style-src \'unsafe-inline\'; font-src data:; media-src data: blob:">';
127  const base = '<base target="_blank">';
128  const head = /<head[^>]*>/i.exec(html);
129  if (head) return html.slice(0, head.index + head[0].length) + policy + base + html.slice(head.index + head[0].length);
130  return `<!doctype html><html><head><meta charset="utf-8">${policy}${base}</head><body>${html}</body></html>`;
131}
132
133/** True when the page asks for something from the internet (a script, style or picture by web address): the preview cannot load it. */
134export const needsOutsideFiles = (html: string) => /<(?:script|link|img|iframe|source)\b[^>]*(?:src|href)\s*=\s*["']?(?:https?:)?\/\//i.test(html);
135
136/** The address of one side of a changed picture on the host. */
137export const timeSkipImageUrl = (jobId: string, path: string, version: 'original' | 'updated') =>
138  `/api/timeskip/file?id=${encodeURIComponent(jobId)}&path=${encodeURIComponent(path)}&version=${version}`;