okami.mom/strata

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

Niko1221Merge f-027-web: the served web chat page for 0.2.75d9f47922

main
8.6 KiB142 linesraw
1// serve/web/math.js - chat math that never changes the source. Engine-independent: a renderer (math-adapter.js) is plugged in.
2// Ported from PR #2972 by CC-David-CC. The text of a message stays as the model wrote it (history, copying, the Markdown
3// export and the requests all use it); math is only drawn over a placeholder in the page, and a formula that cannot be drawn
4// stays as its source text.
5"use strict";
6(function (root) {
7  const escape = (s) => String(s).replace(/[&<>"']/g, (c) => ({"&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;"}[c]));
8  const escaped = (s, i) => { let n = 0; while (i > 0 && s[--i] === "\\") n++; return n % 2 === 1; };
9
10  // split(text) -> [{raw}, {source, display, raw}, {raw, incomplete: true}, ...]
11  // \( \) and $x$ are inline, \[ \] and $$ $$ are display. Code (fences, `spans`), Markdown link targets and prices ($5 and
12  // $10) are not math. A formula that is still being written (no closing delimiter yet) stays plain text.
13  function split(text) {
14    const parts = []; let start = 0, i = 0;
15    const push = (end, math) => { if (start < i) parts.push({raw: text.slice(start, i)}); parts.push(math); start = i = end; };
16    while (i < text.length) {
17      // Code takes precedence, including incomplete fences while streaming.
18      const fence = (i === 0 || text[i - 1] === "\n") && text.slice(i).match(/^ {0,3}(`{3,}|~{3,})[^\n]*\n/);
19      if (fence) {
20        const marker = fence[1][0], count = fence[1].length;
21        const end = new RegExp("^ {0,3}" + marker + "{" + count + ",}[ \\t]*(?:\\n|$)", "m").exec(text.slice(i + fence[0].length));
22        i = end ? i + fence[0].length + end.index + end[0].length : text.length; continue;
23      }
24      if (text[i] === "`" && !escaped(text, i)) {
25        const ticks = text.slice(i).match(/^`+/)[0]; let end = text.indexOf(ticks, i + ticks.length);
26        while (end >= 0 && (text[end - 1] === "`" || text[end + ticks.length] === "`")) end = text.indexOf(ticks, end + ticks.length);
27        i = end < 0 ? text.length : end + ticks.length; continue;
28      }
29      if (escaped(text, i)) { i++; continue; }
30      // Never inject a math element into a Markdown link's href attribute.
31      if (text.startsWith("](http", i)) {
32        const end = text.indexOf(")", i + 2);
33        i = end < 0 ? text.length : end + 1; continue;
34      }
35      let open, close, display;
36      if (text.startsWith("\\(", i)) { open = "\\("; close = "\\)"; display = false; }
37      else if (text.startsWith("\\[", i)) { open = "\\["; close = "\\]"; display = true; }
38      else if (text.startsWith("$$", i)) { open = close = "$$"; display = true; }
39      else if (text[i] === "$" && !/\s/.test(text[i + 1] || " ") && text[i - 1] !== "$") { open = close = "$"; display = false; }
40      if (!open) { i++; continue; }
41      let end = text.indexOf(close, i + open.length);
42      while (end >= 0 && (escaped(text, end) || (close === "$" && (/\s/.test(text[end - 1]) || /[\d$]/.test(text[end + 1] || ""))))) end = text.indexOf(close, end + close.length);
43      const source = end >= 0 ? text.slice(i + open.length, end) : text.slice(i + open.length);
44      // Numeric prices are text, even when separated by a second dollar amount.
45      if (open === "$" && (/\n/.test(source) || /\$/.test(source) ||
46          /^\d[\d,.]*(?:\s*[A-Za-z]|\s*$)/.test(source))) { i++; continue; }
47      if (end < 0) { push(text.length, {raw: text.slice(i), incomplete: true}); break; }
48      push(end + close.length, {source, display, raw: text.slice(i, end + close.length)});
49    }
50    if (start < text.length) parts.push({raw: text.slice(start)});
51    return parts;
52  }
53
54  // markdown(text, format): format() is the page's Markdown, run on the text with every formula swapped for a placeholder
55  // word, then each word becomes <span class="chat-math" data-math="..."> holding the escaped source until it is drawn.
56  function markdown(text, format) {
57    let prefix = "STRATAMATHPLACEHOLDER"; while (text.includes(prefix)) prefix += "X";
58    const slots = [];
59    const protectedText = split(text).map((p) => {
60      if (p.source === undefined && !p.incomplete) return p.raw;
61      const key = prefix + slots.length + "END";
62      slots.push(p); return key;
63    }).join("");
64    let html = format(protectedText);
65    slots.forEach((p, i) => {
66      const body = p.incomplete ? escape(p.raw) : `<span class="chat-math${p.display ? " chat-math--display" : ""}" data-math="${escape(encodeURIComponent(p.source))}" data-display="${p.display ? "1" : "0"}">${escape(p.raw)}</span>`;
67      html = html.replaceAll(prefix + i + "END", () => body);
68    });
69    return html;
70  }
71
72  // drawing: one formula at a time (an engine may keep state between formulas), 256 results cached, a 10 s deadline for the
73  // engine to start and 15 s for one formula. A formula over 16 KiB is not drawn. The adapter returns an element that is not
74  // in the page; the core clones it into the placeholder if that is still on the screen.
75  const cache = new Map(), done = new Map();
76  let initialization = null, queue = Promise.resolve(), epoch = 0;
77  function reset() { cache.clear(); done.clear(); initialization = null; epoch++; }
78  const keyOf = (source, display) => JSON.stringify([source, display]);
79  async function result(source, display) {
80    if (new TextEncoder().encode(source).length > 16384) return {ok: false, reason: "limit"};
81    const key = keyOf(source, display);
82    if (cache.has(key)) { const hit = cache.get(key); cache.delete(key); cache.set(key, hit); return hit; }
83    if (cache.size >= 256) { const old = cache.keys().next().value; cache.delete(old); done.delete(old); }
84    const current = epoch; let work;
85    const task = queue.then(async () => {
86      if (epoch !== current || cache.get(key) !== task) return {ok: false, reason: "unavailable"};
87      try {
88        const adapter = root.StrataMathAdapter;
89        if (!adapter) return {ok: false, reason: "unavailable"};
90        initialization ||= Promise.race([adapter.initialize(), new Promise((_, reject) =>
91          setTimeout(() => reject(new Error("Math initialization timed out")), 10000))]);
92        await initialization;
93        const signal = AbortSignal.timeout(15000);
94        let onAbort;
95        const deadline = new Promise((resolve) => {
96          onAbort = () => resolve({ok: false, reason: "limit"});
97          signal.addEventListener("abort", onAbort, {once: true});
98        });
99        work = Promise.resolve(adapter.render(source, {display, signal}));
100        try { return await Promise.race([work, deadline]); }
101        finally { signal.removeEventListener("abort", onAbort); }
102      } catch (_) { return {ok: false, reason: "unavailable"}; }
103    });
104    // A browser engine may ignore cancellation. Return source at the deadline,
105    // but do not overlap conversions that mutate the engine's macro state.
106    queue = task.then(() => work, () => work).then(() => undefined, () => undefined);
107    cache.set(key, task);
108    task.then((r) => { if (cache.get(key) === task) done.set(key, r); });
109    return task;
110  }
111
112  function place(slot, r, tr) {
113    if (r.ok) slot.replaceChildren(r.element.cloneNode(true));
114    else { slot.dataset.mathError = r.reason; slot.title = tr ? tr("math.source", "Math source ({reason})", {reason: r.reason}) : "Math source (" + r.reason + ")"; }
115  }
116  // hydrate(container): draw the placeholders in a container. A formula drawn before is placed at once, so a streaming
117  // answer that is rebuilt on every frame does not flicker back to source text.
118  function hydrate(container) {
119    const generation = container._mathGeneration = (container._mathGeneration || 0) + 1;
120    for (const slot of container.querySelectorAll("[data-math]")) {
121      const source = decodeURIComponent(slot.dataset.math), display = slot.dataset.display === "1";
122      const known = done.get(keyOf(source, display));
123      if (known && known.ok) { place(slot, known, root.tr); continue; }
124      result(source, display).then((r) => {
125        if (generation !== container._mathGeneration || !container.contains(slot)) return;
126        place(slot, r, root.tr);
127      });
128    }
129  }
130  function script(url) {
131    return new Promise((resolve, reject) => {
132      const s = document.createElement("script"); s.src = url;
133      const timer = setTimeout(() => { s.remove(); reject(new Error("Math script timed out")); }, 10000);
134      s.onload = () => { clearTimeout(timer); resolve(); };
135      s.onerror = () => { clearTimeout(timer); s.remove(); reject(new Error("Math script unavailable")); };
136      document.head.append(s);
137    });
138  }
139  const api = {split, markdown, hydrate, reset, script, result};
140  root.StrataMath = api;
141  if (typeof module !== "undefined" && module.exports) module.exports = api;
142})(typeof globalThis !== "undefined" ? globalThis : this);