The best way to control Claude Code, Codex and more from any computer or phone

main
ts 120 lines 4.36 KB
Raw
1 import { markdownMathRanges } from "@t3tools/shared/markdownMath";
2 import { createAssistantTextSelector } from "@t3tools/shared/assistantCitations";
3 import {
4 splitCodexArtifactTemplateMarkdown,
5 renderCodexInlineDirectivesAsMarkdown,
6 } from "@t3tools/shared/codexMarkdownDirectives";
7 import { splitMarkdownDetails } from "./markdownDetails";
8 import {
9 markdownReferenceDefinitions,
10 parseMarkdownDocument,
11 withReferenceDefinitions,
12 type MarkdownNode,
13 } from "./markdownDocument";
14
15 function renderedText(node: MarkdownNode, restoreMath: (value: string) => string): string {
16 if (
17 node.type === "definition" ||
18 node.type === "image" ||
19 node.type === "imageReference" ||
20 node.type === "html" ||
21 (node.type === "code" && node.lang === "mermaid")
22 )
23 return "";
24 if ("value" in node) return restoreMath(node.value);
25 if ("children" in node) {
26 const inline =
27 node.type === "paragraph" ||
28 node.type === "heading" ||
29 node.type === "link" ||
30 node.type === "linkReference" ||
31 node.type === "emphasis" ||
32 node.type === "strong" ||
33 node.type === "delete" ||
34 node.type === "tableCell";
35 return node.children
36 .map((child) => renderedText(child, restoreMath))
37 .filter((text) => text.length > 0)
38 .join(inline ? "" : "\n");
39 }
40 return node.type === "break" ? "\n" : "";
41 }
42
43 function citationText(markdown: string): string {
44 const formulas = markdownMathRanges(markdown);
45 let marker = "\ue000t3math";
46 while (markdown.includes(marker)) marker += "_";
47 const tokens = formulas.map((_, index) => `${marker}${index}\ue001`);
48 let cursor = 0;
49 let prose = "";
50 for (const [index, formula] of formulas.entries()) {
51 prose += markdown.slice(cursor, formula.start) + tokens[index];
52 cursor = formula.end;
53 }
54 prose += markdown.slice(cursor);
55 return renderedText(parseMarkdownDocument(prose), (value) =>
56 value.replace(new RegExp(`${marker}(\\d+)\ue001`, "g"), (_, index: string) => {
57 const formula = formulas[Number(index)]!;
58 const tex = formula.tex.trim();
59 return formula.display ? `\\[\n${tex}\n\\]` : `\\(${tex}\\)`;
60 }),
61 );
62 }
63
64 function citationSegments(
65 markdown: string,
66 path = "",
67 definitions = markdownReferenceDefinitions(markdown),
68 ): Array<{ path: string; text: string }> {
69 return splitMarkdownDetails(markdown).flatMap((block, index) => {
70 if (block.kind === "details")
71 return citationSegments(block.body, `${path}${index}/`, definitions);
72 return splitCodexArtifactTemplateMarkdown(block.markdown).flatMap((segment, segmentIndex) =>
73 segment.kind === "markdown"
74 ? [
75 {
76 path: `${path}${index}:${segmentIndex}`,
77 text: citationText(
78 renderCodexInlineDirectivesAsMarkdown(
79 withReferenceDefinitions(segment.markdown, definitions),
80 ),
81 ),
82 },
83 ]
84 : [],
85 );
86 });
87 }
88
89 function occurrences(text: string, quote: string): number[] {
90 const result: number[] = [];
91 for (let index = text.indexOf(quote); index !== -1; index = text.indexOf(quote, index + 1))
92 result.push(index);
93 return result;
94 }
95
96 export function collectMobileAssistantTextSelectors(markdown: string, path: string, text: string) {
97 if (!text.trim()) return [];
98 const normalize = (value: string) => value.replace(/\s+/g, " ");
99 const quote = normalize(text);
100 const segments = citationSegments(markdown).filter((segment) => segment.text.trim().length > 0);
101 const segmentIndex = segments.findIndex((segment) => segment.path === path);
102 const segment = segments[segmentIndex];
103 if (!segment) return [];
104 const fullText = normalize(segments.map((entry) => entry.text).join("\n"));
105 const throughSegment = segments
106 .slice(0, segmentIndex + 1)
107 .map((entry) => entry.text)
108 .join("\n");
109 const offset = normalize(throughSegment).length - normalize(segment.text).length;
110 const matches = occurrences(fullText, quote);
111 const localMatches = occurrences(normalize(segment.text), quote);
112 if (localMatches.length > 20) return [];
113 return localMatches.flatMap((localStart) => {
114 const start = offset + localStart;
115 const index = matches.indexOf(start);
116 if (index === -1) return [];
117 const selector = createAssistantTextSelector(fullText, start, start + quote.length);
118 return selector ? [{ selector: { ...selector, text }, index, count: matches.length }] : [];
119 });
120 }