SPB Git

Repository Public

inline.tsx 7.2 KB 149 lines tsx

1import type { ReactNode } from "react";2import type { Source } from "@/schema";3import { MathView } from "./math";4import { Mark, SIGN_RE, signMark } from "./marks";5import { latexToUnicode, prettyMath } from "./mathtext";67/**8 * Inline Markdown subset → React nodes. Documented subset only:9 *   **bold**  *italic*  `code`  $inline LaTeX$  [label](https://… | mailto:…)  [^source-id]10 *   also accepted for formulas: \(inline\), $$display$$ and \[display\]11 * In plain text, ASCII maths (x_t, A^h) gets real sub- and superscripts and typed signs (✓ ✗ ⚠) are drawn as marks.12 * Everything else — raw HTML included — is plain text, escaped by React. No HTML string is ever built here.13 */14export type InlineNode =15  | { kind: "text"; text: string }16  | { kind: "bold" | "italic"; children: InlineNode[] }17  | { kind: "code"; text: string }18  | { kind: "math"; latex: string; display?: boolean }19  | { kind: "link"; href: string; children: InlineNode[] }20  | { kind: "cite"; id: string };2122/** https and mailto only; anything else (javascript:, data:, http:, relative) is refused. */23export function safeHref(raw: string): string | null {24  const s = raw.trim();25  if (!/^(https:\/\/|mailto:)/i.test(s) || /[\s<>"'`\\]/.test(s) || /[\u0000-\u001f\u007f]/.test(s)) return null;26  try { const u = new URL(s); return u.protocol === "https:" || u.protocol === "mailto:" ? u.href : null; } catch { return null; }27}2829const MAX_DEPTH = 4;3031export function parseInline(text: string, depth = 0, inLink = false): InlineNode[] {32  const out: InlineNode[] = [];33  let buf = "";34  const flush = () => { if (buf) { out.push({ kind: "text", text: buf }); buf = ""; } };35  let i = 0;36  while (i < text.length) {37    const c = text[i];38    if (c === "\\" && (text[i + 1] === "(" || text[i + 1] === "[")) {39      // \(…\) and \[…\]: LaTeX's own delimiters. "\[" alone stays an escaped bracket.40      const display = text[i + 1] === "[";41      const end = text.indexOf(display ? "\\]" : "\\)", i + 2);42      const body = end > 0 ? text.slice(i + 2, end) : "";43      if (body.trim() && (!display || /[\\=^_]/.test(body))) { flush(); out.push({ kind: "math", latex: body.trim(), display }); i = end + 2; continue; }44    }45    if (c === "\\" && i + 1 < text.length && "*`$[]\\".includes(text[i + 1])) { buf += text[i + 1]; i += 2; continue; }46    if (c === "`") {47      const end = text.indexOf("`", i + 1);48      if (end > i + 1) { flush(); out.push({ kind: "code", text: text.slice(i + 1, end) }); i = end + 1; continue; }49    } else if (c === "$" && text[i + 1] === "$") {50      const end = text.indexOf("$$", i + 2);51      if (end > i + 2 && text.slice(i + 2, end).trim()) { flush(); out.push({ kind: "math", latex: text.slice(i + 2, end).trim(), display: true }); i = end + 2; continue; }52      buf += "$$"; i += 2; continue;53    } else if (c === "$") {54      // Opening $ is followed by a non-space, closing $ is preceded by a non-space ("5 $ and 10 $" stays text).55      let end = -1;56      if (i + 1 < text.length && !/\s/.test(text[i + 1])) {57        for (let j = i + 1; j < text.length; j++) {58          if (text[j] === "\\") { j++; continue; }59          if (text[j] === "$") { if (j > i + 1 && !/\s/.test(text[j - 1])) end = j; break; }60        }61      }62      if (end > 0) { flush(); out.push({ kind: "math", latex: text.slice(i + 1, end) }); i = end + 1; continue; }63    } else if (c === "*" && depth < MAX_DEPTH) {64      const strong = text.startsWith("**", i);65      const mark = strong ? "**" : "*";66      const start = i + mark.length;67      let end = -1;68      if (start < text.length && !/\s/.test(text[start])) {69        // Look at whole runs of stars: ** closes on the last two of a run, * on the last one of an odd run.70        let j = start;71        while ((j = text.indexOf("*", j)) !== -1) {72          let run = 1;73          while (text[j + run] === "*") run++;74          const close = j + run - mark.length;75          if ((strong ? run >= 2 : run % 2 === 1) && close > start && !/\s/.test(text[j - 1])) { end = close; break; }76          j += run;77        }78      }79      if (end > 0) { flush(); out.push({ kind: strong ? "bold" : "italic", children: parseInline(text.slice(start, end), depth + 1, inLink) }); i = end + mark.length; continue; }80      if (strong) { buf += "**"; i += 2; continue; }81    } else if (c === "[") {82      const cite = /^\[\^([a-z0-9][a-z0-9-]{0,47})\]/.exec(text.slice(i, i + 52));83      if (cite) { flush(); out.push({ kind: "cite", id: cite[1] }); i += cite[0].length; continue; }84      if (!inLink && depth < MAX_DEPTH) {85        const link = /^\[([^\[\]\n]{1,300})\]\(([^()\s]{1,2000})\)/.exec(text.slice(i, i + 2310));86        const href = link ? safeHref(link[2]) : null;87        if (link && href) { flush(); out.push({ kind: "link", href, children: parseInline(link[1], depth + 1, true) }); i += link[0].length; continue; }88      }89    }90    buf += c; i++;91  }92  flush();93  return out;94}9596/** Typed signs (✓ ✗ ⚠ ★) become marks; the rest of the text is returned as it is. */97function signs(text: string, key: string): ReactNode {98  if (!SIGN_RE.test(text)) return text;99  SIGN_RE.lastIndex = 0;100  const out: ReactNode[] = [];101  let last = 0, m: RegExpExecArray | null;102  while ((m = SIGN_RE.exec(text))) {103    if (m.index > last) out.push(text.slice(last, m.index));104    const s = signMark(m[1]);105    out.push(<Mark key={`${key}s${m.index}`} name={s.name} label={s.label} size="1.05em" className="sh-sign" />);106    last = m.index + m[0].length;107  }108  if (last < text.length) out.push(text.slice(last));109  return out;110}111112function renderNodes(nodes: InlineNode[], sources: Source[] | undefined, keyPrefix: string): ReactNode[] {113  return nodes.map((n, i) => {114    const key = `${keyPrefix}${i}`;115    switch (n.kind) {116      case "text": return signs(prettyMath(n.text), key);117      case "bold": return <strong key={key}>{renderNodes(n.children, sources, key + "-")}</strong>;118      case "italic": return <em key={key}>{renderNodes(n.children, sources, key + "-")}</em>;119      case "code": return <code key={key} className="sh-icode">{n.text}</code>;120      case "math": return <MathView key={key} latex={n.latex} display={n.display} />;121      case "link": return <a key={key} className="sh-link" href={n.href} target="_blank" rel="noopener noreferrer">{renderNodes(n.children, sources, key + "-")}</a>;122      case "cite": {123        const index = sources ? sources.findIndex((s) => s.id === n.id) : -1;124        if (index < 0) return null;125        return <sup key={key} className="sh-cite"><a href={`#src-${n.id}`} aria-label={`Source ${index + 1}`}>{index + 1}</a></sup>;126      }127    }128  });129}130131/** Inline Markdown subset → React nodes (bold, italic, code, $math$, https links, [^source-id] citations). Never HTML. */132export function Inline({ text, sources }: { text: string; sources?: Source[] }) {133  return <>{renderNodes(parseInline(text), sources, "i")}</>;134}135136/** Plain text of an inline string (labels inside SVG, where Markdown cannot be drawn). */137export function inlineToPlain(text: string): string {138  const walk = (nodes: InlineNode[]): string => nodes.map((n) => {139    switch (n.kind) {140      case "text": return prettyMath(n.text);141      case "code": return n.text;142      case "math": return latexToUnicode(n.latex);143      case "cite": return "";144      default: return walk(n.children);145    }146  }).join("");147  return walk(parseInline(text));148}149
Files main
Menu

Theme