Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

markdownText.ts

68 lines2.7 KB

1import { decodeHTMLStrict } from "entities";
2import {
3 codexArtifactTemplatePresentationLabel,
4 resolveCodexArtifactTemplate,
5} from "@t3tools/shared/codexArtifactTemplates";
6import {
7 codexFileCitationMarkdown,
8 resolveCodexFileCitationLink,
9} from "@t3tools/shared/codexFileCitations";
10import { isWindowsAbsolutePath } from "@t3tools/shared/path";
11​
12import { codexDirectiveSources, type CodexDirectiveSource } from "./wordsHast";
13​
14const CODEX_DIRECTIVE = /:codex-file-citation|:codex-followup|::artifact-template/;
15​
16/** Replaces each directive with what `replacement` returns for it; undefined keeps it. */
17function replaceDirectives(
18 markdown: string,
19 replacement: (directive: CodexDirectiveSource) => string | undefined,
20): string {
21 if (!CODEX_DIRECTIVE.test(markdown)) return markdown;
22 let rendered = markdown;
23 const directives = codexDirectiveSources(markdown).sort(
24 (left, right) => right.start - left.start,
25 );
26 for (const directive of directives) {
27 const value = replacement(directive);
28 if (value !== undefined) {
29 rendered = rendered.slice(0, directive.start) + value + rendered.slice(directive.end);
30 }
31 }
32 return rendered;
34​
35/** A file citation as the Markdown link it shows as, and a follow-up as its label. */
36function inlineDirectiveMarkdown(directive: CodexDirectiveSource): string | undefined {
37 if (directive.name === "codex-file-citation") {
38 const citation = directive.inLink ? null : resolveCodexFileCitationLink(directive.attributes);
39 return citation ? codexFileCitationMarkdown(citation) : undefined;
40 }
41 if (directive.name === "codex-followup") {
42 return directive.attributes.prompt?.trim() && directive.label.trim()
43 ? directive.label
44 : undefined;
45 }
46 return undefined;
48​
49export function renderCodexInlineDirectivesAsMarkdown(markdown: string): string {
50 return replaceDirectives(markdown, inlineDirectiveMarkdown);
52​
53/** What copying a message writes: inline directives as Markdown, a template as its name. */
54export function renderCodexDirectivesForCopy(markdown: string): string {
55 return replaceDirectives(markdown, (directive) => {
56 if (directive.name !== "artifact-template") return inlineDirectiveMarkdown(directive);
57 const template = resolveCodexArtifactTemplate(directive.attributes);
58 return template
59 ? `${template.displayName} (${codexArtifactTemplatePresentationLabel(template.artifactKind)})`
60 : undefined;
61 });
63​
64/** A link destination as written, with its character references and escapes resolved. */
65export function decodeMarkdownLinkEscapes(href: string): string {
66 const decoded = href.includes("&") ? decodeHTMLStrict(href) : href;
67 return isWindowsAbsolutePath(decoded) ? decoded : decoded.replace(/\\([!-/:-@[-`{-~])/g, "$1");