@adroit-app/chat-ui 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,103 @@
1
+ import embedStyles from "@arto-app/markdown/bundles/embed.css?inline";
2
+ import { addCopyButtons } from "@arto-app/markdown/code-copy";
3
+ import { renderHtmlEmbeds } from "@arto-app/markdown/html-embed-renderer";
4
+ import { provideHljs, provideHtml2Canvas, provideKatex, provideMermaid, } from "@arto-app/markdown/libraries";
5
+ import { renderMath } from "@arto-app/markdown/math-renderer";
6
+ import { renderDiagrams } from "@arto-app/markdown/mermaid-renderer";
7
+ import { applyPictureTheme } from "@arto-app/markdown/picture-theme";
8
+ import { highlightCodeBlocks } from "@arto-app/markdown/syntax-highlighter";
9
+ import * as wasm from "@arto-app/markdown/wasm";
10
+ import wasmData from "@arto-app/markdown/wasm/arto_markdown_wasm_bg.wasm?url&inline";
11
+ import hljsAll from "@arto-app/markdown/bundles/page-hljs-all.iife.js?url";
12
+ import hljsCommon from "@arto-app/markdown/bundles/page-hljs-common.iife.js?url";
13
+ import math from "@arto-app/markdown/bundles/page-math.iife.js?url";
14
+ import mermaid from "@arto-app/markdown/bundles/page-mermaid.iife.js?url";
15
+ import { renderMarkdown } from "./render.js";
16
+ let ready = false;
17
+ /**
18
+ * The renderer, started from the WebAssembly the bundle carries, so it runs
19
+ * where nothing can be fetched: a page opened from disk, or a webview.
20
+ */
21
+ function arto() {
22
+ if (!ready) {
23
+ const base64 = wasmData.slice(wasmData.indexOf(",") + 1);
24
+ const bytes = Uint8Array.from(atob(base64), (c) => c.charCodeAt(0));
25
+ wasm.initSync({ module: bytes });
26
+ ready = true;
27
+ }
28
+ return wasm;
29
+ }
30
+ export function render(markdown, policy, host) {
31
+ const rendered = renderMarkdown(arto(), markdown, policy, host);
32
+ // A diagram is drawn by whichever Chat loaded the library first; one whose
33
+ // policy leaves diagrams out keeps the fence as code.
34
+ return policy.mermaid
35
+ ? rendered
36
+ : { ...rendered, html: rendered.html.replaceAll("preprocessed-mermaid", "mermaid-source") };
37
+ }
38
+ let sheet = null;
39
+ /** Arto's stylesheet, one sheet for every Chat on the page. */
40
+ export function markdownSheet() {
41
+ if (!sheet) {
42
+ sheet = new CSSStyleSheet();
43
+ sheet.replaceSync(embedStyles);
44
+ }
45
+ return sheet;
46
+ }
47
+ const BUNDLES = {
48
+ mermaid,
49
+ math,
50
+ "hljs-all": hljsAll,
51
+ "hljs-common": hljsCommon,
52
+ };
53
+ const loading = new Map();
54
+ /** Loads the bundle of `library`, which hands what it carries to the renderers. */
55
+ function load(library) {
56
+ let known = loading.get(library);
57
+ if (!known) {
58
+ // The bundles find the renderers through the global the page runtime publishes.
59
+ window.ArtoRenderer ??= { provideMermaid, provideKatex, provideHtml2Canvas, provideHljs };
60
+ known = new Promise((resolve, reject) => {
61
+ // A classic script, as the bundles are written to be: imported as a
62
+ // module, a bundler may wrap what they do on load in code nothing runs.
63
+ const script = document.createElement("script");
64
+ script.src = BUNDLES[library];
65
+ script.onload = () => resolve();
66
+ script.onerror = () => reject(new Error(`could not load ${library}`));
67
+ document.head.append(script);
68
+ });
69
+ loading.set(library, known);
70
+ }
71
+ return known;
72
+ }
73
+ /**
74
+ * Draws what the rendered HTML in `viewer` leaves to script — code colours,
75
+ * diagrams, formulas, embeds and copy buttons — once the libraries the
76
+ * policy allows have loaded.
77
+ */
78
+ /** The latest draw of each viewer, by count. */
79
+ const drawing = new WeakMap();
80
+ export async function draw(viewer, libraries, theme, highlight) {
81
+ viewer.setAttribute("data-theme", theme);
82
+ applyPictureTheme(viewer, theme);
83
+ if (!highlight) {
84
+ for (const code of viewer.querySelectorAll("pre code")) {
85
+ code.dataset.highlighted = "yes";
86
+ }
87
+ }
88
+ const turn = (drawing.get(viewer) ?? 0) + 1;
89
+ drawing.set(viewer, turn);
90
+ // A library that does not load leaves its blocks as written; the rest is still drawn.
91
+ await Promise.allSettled(libraries.map(load));
92
+ // Only the latest draw goes on: an earlier one, waiting on fewer libraries,
93
+ // would give a diagram its copy button first, and a block holding an icon
94
+ // counts as drawn.
95
+ if (!viewer.isConnected || drawing.get(viewer) !== turn)
96
+ return;
97
+ renderMath(viewer);
98
+ highlightCodeBlocks(viewer);
99
+ void renderDiagrams(viewer);
100
+ renderHtmlEmbeds(viewer, () => theme);
101
+ // Last, as arto-markdown does: a diagram counts a block holding an icon as drawn already.
102
+ addCopyButtons(viewer);
103
+ }
@@ -0,0 +1,22 @@
1
+ export interface StandaloneOptions {
2
+ /** A custom property's value where the SVG was drawn; empty when it has none. */
3
+ resolve(name: string): string;
4
+ /** The size it was drawn at, in CSS pixels. */
5
+ width: number;
6
+ height: number;
7
+ /** What to lay it on, as CSS: drawn on the page, it showed the page's background. */
8
+ background?: string;
9
+ }
10
+ /**
11
+ * `markup`, an SVG drawn on the page, as an image of its own: its CSS
12
+ * variables replaced by their values, its size fixed, and its namespace named.
13
+ * An image is a document apart, where the page's stylesheet does not reach.
14
+ */
15
+ export declare function standaloneSvg(markup: string, options: StandaloneOptions): string;
16
+ /** Base64 of `text`'s UTF-8 bytes, as an image's `data` is carried. */
17
+ export declare function base64Utf8(text: string): string;
18
+ /** `svg`, drawn on the page, as the image `open-image` carries: SVG of its own, in the colours it shows. */
19
+ export declare function svgElementImage(svg: SVGSVGElement): {
20
+ data: string;
21
+ mimeType: "image/svg+xml";
22
+ };
@@ -0,0 +1,57 @@
1
+ const SVG_NS = "http://www.w3.org/2000/svg";
2
+ /** `var(--name)` or `var(--name, fallback)`, the fallback holding no `var()` of its own. */
3
+ const VARIABLE = /var\(\s*(--[\w-]+)\s*(?:,\s*([^()]*))?\)/g;
4
+ /**
5
+ * `markup`, an SVG drawn on the page, as an image of its own: its CSS
6
+ * variables replaced by their values, its size fixed, and its namespace named.
7
+ * An image is a document apart, where the page's stylesheet does not reach.
8
+ */
9
+ export function standaloneSvg(markup, options) {
10
+ const resolved = (text) => resolveVariables(text, options.resolve);
11
+ const body = resolved(markup);
12
+ return body.replace(/^<svg\b([^>]*)>/, (_, attributes) => {
13
+ let rest = attributes.replace(/\s(?:width|height)\s*=\s*(?:"[^"]*"|'[^']*')/g, "");
14
+ if (options.background) {
15
+ const background = `background:${resolved(options.background)}`;
16
+ rest = /\sstyle\s*=\s*"/.test(rest)
17
+ ? rest.replace(/\sstyle\s*=\s*"/, (m) => `${m}${background};`)
18
+ : `${rest} style="${background}"`;
19
+ }
20
+ const xmlns = /\sxmlns\s*=/.test(rest) ? "" : ` xmlns="${SVG_NS}"`;
21
+ const size = ` width="${Math.ceil(options.width)}" height="${Math.ceil(options.height)}"`;
22
+ return `<svg${xmlns}${size}${rest}>`;
23
+ });
24
+ }
25
+ function resolveVariables(text, resolve) {
26
+ // A fallback may itself be a variable: resolve the innermost first.
27
+ let out = text;
28
+ for (let previous = ""; previous !== out;) {
29
+ previous = out;
30
+ out = out.replace(VARIABLE, (_, name, fallback) => {
31
+ const value = resolve(name).trim();
32
+ return value || (fallback ?? "").trim();
33
+ });
34
+ }
35
+ return out;
36
+ }
37
+ /** Base64 of `text`'s UTF-8 bytes, as an image's `data` is carried. */
38
+ export function base64Utf8(text) {
39
+ const bytes = new TextEncoder().encode(text);
40
+ let binary = "";
41
+ for (let i = 0; i < bytes.length; i += 0x8000) {
42
+ binary += String.fromCharCode(...bytes.subarray(i, i + 0x8000));
43
+ }
44
+ return btoa(binary);
45
+ }
46
+ /** `svg`, drawn on the page, as the image `open-image` carries: SVG of its own, in the colours it shows. */
47
+ export function svgElementImage(svg) {
48
+ const style = getComputedStyle(svg);
49
+ const { width, height } = svg.getBoundingClientRect();
50
+ const markup = standaloneSvg(new XMLSerializer().serializeToString(svg), {
51
+ resolve: (name) => style.getPropertyValue(name),
52
+ width,
53
+ height,
54
+ background: "var(--pele-bg)",
55
+ });
56
+ return { data: base64Utf8(markup), mimeType: "image/svg+xml" };
57
+ }
@@ -0,0 +1,71 @@
1
+ import type { Files, Library, RenderOptions, RenderResult } from "@arto-app/markdown/wasm";
2
+ /**
3
+ * How Markdown an agent wrote is rendered. Every choice that would let it
4
+ * restyle the Chat, run script or reach the network defaults to the safe one.
5
+ */
6
+ export interface MarkdownPolicy {
7
+ /** Raw HTML in the Markdown: shown as written, filtered of what restyles or scripts, or drawn. */
8
+ rawHtml: "escape" | "filter" | "allow";
9
+ /** Images from another host: left out (their alt text stays), or loaded. */
10
+ remoteImages: "block" | "load";
11
+ /** Images on the host's disk: left out, served by the host at a URL, or inlined as data. */
12
+ localImages: "block" | "defer" | "inline";
13
+ /** Colours in code blocks: none, the common languages, or every language highlight.js has. */
14
+ highlight: "off" | "common" | "all";
15
+ /** `$…$` read as formulas. Off by default: agents write `$` for shells. */
16
+ math: boolean;
17
+ /** Mermaid fences drawn as diagrams. */
18
+ mermaid: boolean;
19
+ /** `svg` fences drawn as images of their markup, never put in the page as markup. */
20
+ svg: boolean;
21
+ /** `html-embed` fences drawn as figures in a sandboxed frame. */
22
+ htmlEmbed: boolean;
23
+ }
24
+ export declare const SAFE_MARKDOWN: Readonly<MarkdownPolicy>;
25
+ /** What only the host can give the renderer: where relative paths start, and its files. */
26
+ export interface MarkdownHost {
27
+ /** The file relative links and images resolve against, as if the Markdown were in it. */
28
+ basePath: string;
29
+ /** The files local images are read from; without them, no local file exists. */
30
+ files?: Files | null;
31
+ /** Where the host serves the local images a `defer` policy leaves to it. */
32
+ deferredImageBaseUrl?: string | null;
33
+ }
34
+ /** The two entry points of arto-markdown's WebAssembly build the Chat uses. */
35
+ export interface ArtoRenderer {
36
+ render(markdown: string, basePath: string, options?: RenderOptions | null, files?: Files | null): RenderResult;
37
+ renderDetached(markdown: string, basePath: string, options?: RenderOptions | null, files?: Files | null): RenderResult;
38
+ }
39
+ export interface Rendered {
40
+ html: string;
41
+ /** The frontend bundles the HTML needs under the policy, in the order to load them. */
42
+ libraries: Library[];
43
+ }
44
+ /** The arto-markdown call `policy` makes: which entry point, its options and the files it sees. */
45
+ export declare function callFor(policy: MarkdownPolicy, host: MarkdownHost): {
46
+ detached: boolean;
47
+ options: RenderOptions;
48
+ files: Files | null;
49
+ };
50
+ /** `markdown` rendered under `policy`. */
51
+ export declare function renderMarkdown(arto: ArtoRenderer, markdown: string, policy: MarkdownPolicy, host: MarkdownHost): Rendered;
52
+ /** Why an image is left out: the policy blocks local images, or web images. */
53
+ export type LeftOut = "local" | "remote";
54
+ /** The file a local image asked for at `src` under `base` is; null for any other image. */
55
+ export declare function servedPath(src: string, base: string | null | undefined): string | null;
56
+ /** The bundles `needed` that `policy` lets load. */
57
+ export declare function librariesFor(needed: readonly Library[], policy: MarkdownPolicy): Library[];
58
+ /**
59
+ * `html` with each image `leftOut` gives a reason for drawn as its alt text,
60
+ * saying why and what would show it. A relative source would be fetched from
61
+ * wherever the Chat is served.
62
+ */
63
+ export declare function withoutImages(html: string, leftOut: (src: string) => LeftOut | null): string;
64
+ /** `text` as a fenced code block of `language`, whatever backticks it holds. */
65
+ export declare function fenced(language: string, text: string): string;
66
+ /**
67
+ * `html` with each `svg` code block that holds SVG drawn as an image of it,
68
+ * the code kept beside it to switch to. The markup reaches the page only
69
+ * inside the image's data URL, where nothing in it runs or restyles the Chat.
70
+ */
71
+ export declare function withSvgImages(html: string): string;
@@ -0,0 +1,183 @@
1
+ import { base64Utf8 } from "./picture.js";
2
+ export const SAFE_MARKDOWN = Object.freeze({
3
+ rawHtml: "escape",
4
+ remoteImages: "block",
5
+ localImages: "block",
6
+ highlight: "common",
7
+ math: false,
8
+ mermaid: true,
9
+ svg: true,
10
+ htmlEmbed: false,
11
+ });
12
+ /** The arto-markdown call `policy` makes: which entry point, its options and the files it sees. */
13
+ export function callFor(policy, host) {
14
+ const deferred = policy.localImages === "defer" && host.deferredImageBaseUrl ? host.deferredImageBaseUrl : null;
15
+ const files = policy.localImages === "block" ? null : (host.files ?? (deferred ? EVERY_FILE : null));
16
+ return {
17
+ detached: policy.remoteImages === "block",
18
+ options: {
19
+ rawHtml: policy.rawHtml,
20
+ math: policy.math,
21
+ htmlEmbed: policy.htmlEmbed,
22
+ ...(deferred ? { deferredImageBaseUrl: deferred } : {}),
23
+ },
24
+ files,
25
+ };
26
+ }
27
+ /** `markdown` rendered under `policy`. */
28
+ export function renderMarkdown(arto, markdown, policy, host) {
29
+ const call = callFor(policy, host);
30
+ const base = call.options.deferredImageBaseUrl;
31
+ const run = (fn) => {
32
+ const result = fn(markdown, host.basePath, call.options, call.files);
33
+ const served = new Map(result.images.map((image) => [image.id, image.path]));
34
+ return { ...result, html: base ? servedByPath(result.html, base, served) : result.html };
35
+ };
36
+ const result = call.detached
37
+ ? webImagesNamed(run(arto.renderDetached), run(arto.render))
38
+ : run(arto.render);
39
+ const html = result.html;
40
+ const leftOut = (src) => {
41
+ if (src.startsWith("data:") || (base && src.startsWith(`${base}/`)))
42
+ return null;
43
+ if (/^https?:\/\//i.test(src))
44
+ return policy.remoteImages === "load" ? null : "remote";
45
+ return "local";
46
+ };
47
+ return {
48
+ html: withoutImages(policy.svg ? withSvgImages(html) : html, leftOut),
49
+ libraries: librariesFor(result.libraries, policy),
50
+ };
51
+ }
52
+ /**
53
+ * The detached rendering, or the loaded one when it differs only in the web
54
+ * images the detached one dropped to their alt text, so that each can say
55
+ * why it is left out. Neither is fetched: the loaded one is a string here,
56
+ * and every web image in it is drawn as its alt text before it reaches the
57
+ * page. Anything else that differs keeps the detached rendering.
58
+ */
59
+ function webImagesNamed(detached, loaded) {
60
+ // Only the loaded rendering marks where each block came from.
61
+ const html = loaded.html.replace(/ data-source-range="[^"]*"/g, "");
62
+ const asAlt = html.replace(/<img\b(?:[^>"']|"[^"]*"|'[^']*')*>/gi, (tag) => /^https?:\/\//i.test(attribute(tag, "src") ?? "") ? (attribute(tag, "alt") ?? "") : tag);
63
+ return asAlt === detached.html ? { ...loaded, html } : detached;
64
+ }
65
+ /**
66
+ * Files as a host that serves them sees them: every path names one. Whether
67
+ * it exists is the host's to answer when the image is asked for.
68
+ */
69
+ const EVERY_FILE = { stat: (path) => ({ path, len: 1 }), read: () => null };
70
+ const LEFT_OUT = {
71
+ local: "Local images are not shown: allow local images in the Markdown settings to show it",
72
+ remote: "Web images are not loaded, as loading one tells its server you read it: allow web images in the Markdown settings to load it",
73
+ };
74
+ /**
75
+ * `html` with each image arto deferred, written as `base/<id>` and an
76
+ * extension, asked for at `base/<its absolute path>` instead, so a host
77
+ * serves it from the path without keeping each rendering's ids.
78
+ */
79
+ /** A path as arto lists it, still escaped as the Markdown's URL was, as the file system spells it. */
80
+ function fromUrl(path) {
81
+ try {
82
+ return decodeURIComponent(path);
83
+ }
84
+ catch {
85
+ return path;
86
+ }
87
+ }
88
+ /** The file a local image asked for at `src` under `base` is; null for any other image. */
89
+ export function servedPath(src, base) {
90
+ if (!base || !src.startsWith(`${base}/`))
91
+ return null;
92
+ const encoded = src.slice(base.length + 1);
93
+ return encoded ? fromUrl(encoded) : null;
94
+ }
95
+ /** An absolute `path` with its `.` and `..` segments resolved, as the file system reads it. */
96
+ function withoutDots(path) {
97
+ const out = [];
98
+ for (const segment of path.split("/")) {
99
+ if (segment === "..") {
100
+ if (out.length > 1)
101
+ out.pop();
102
+ }
103
+ else if (segment !== ".") {
104
+ out.push(segment);
105
+ }
106
+ }
107
+ return out.join("/");
108
+ }
109
+ function servedByPath(html, base, served) {
110
+ const prefix = `${base}/`;
111
+ return html.replace(/(<img\b[^>]*?\ssrc=")([^"]*)"/gi, (whole, head, src) => {
112
+ if (!src.startsWith(prefix))
113
+ return whole;
114
+ const path = served.get(src.slice(prefix.length).replace(/\.[^./]*$/, ""));
115
+ return path === undefined
116
+ ? whole
117
+ : `${head}${prefix}${encodeURIComponent(withoutDots(fromUrl(path)))}"`;
118
+ });
119
+ }
120
+ /** The bundles `needed` that `policy` lets load. */
121
+ export function librariesFor(needed, policy) {
122
+ const out = [];
123
+ for (const library of needed) {
124
+ if (library === "mermaid" && policy.mermaid)
125
+ out.push(library);
126
+ if (library === "math" && policy.math)
127
+ out.push(library);
128
+ }
129
+ if (policy.highlight !== "off")
130
+ out.push(policy.highlight === "all" ? "hljs-all" : "hljs-common");
131
+ return out;
132
+ }
133
+ /**
134
+ * `html` with each image `leftOut` gives a reason for drawn as its alt text,
135
+ * saying why and what would show it. A relative source would be fetched from
136
+ * wherever the Chat is served.
137
+ */
138
+ export function withoutImages(html, leftOut) {
139
+ return html.replace(/<img\b(?:[^>"']|"[^"]*"|'[^']*')*>/gi, (tag) => {
140
+ const why = leftOut(attribute(tag, "src") ?? "");
141
+ if (why === null)
142
+ return tag;
143
+ const alt = (attribute(tag, "alt") ?? "").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
144
+ const reason = LEFT_OUT[why];
145
+ return `<span class="image-left-out ${why}" title="${reason}"><span class="alt">${alt || "image"}</span><span class="why">${reason}</span></span>`;
146
+ });
147
+ }
148
+ function attribute(tag, name) {
149
+ const match = new RegExp(`\\s${name}\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s>]+))`, "i").exec(tag);
150
+ if (!match)
151
+ return null;
152
+ return match[1] ?? match[2] ?? match[3] ?? null;
153
+ }
154
+ /** `text` as a fenced code block of `language`, whatever backticks it holds. */
155
+ export function fenced(language, text) {
156
+ const longest = Math.max(0, ...(text.match(/`+/g) ?? []).map((run) => run.length));
157
+ const fence = "`".repeat(Math.max(3, longest + 1));
158
+ const body = text.endsWith("\n") ? text.slice(0, -1) : text;
159
+ return `${fence}${language}\n${body}\n${fence}\n`;
160
+ }
161
+ /**
162
+ * `html` with each `svg` code block that holds SVG drawn as an image of it,
163
+ * the code kept beside it to switch to. The markup reaches the page only
164
+ * inside the image's data URL, where nothing in it runs or restyles the Chat.
165
+ */
166
+ export function withSvgImages(html) {
167
+ return html.replace(/<pre><code class="language-svg">([^<]*)<\/code><\/pre>/g, (block, escaped) => {
168
+ const markup = unescapeHtml(escaped).replace(/\n$/, "");
169
+ if (!/^\s*(?:<\?xml[^>]*\?>\s*)?(?:<!--[\s\S]*?-->\s*)*<svg[\s>]/i.test(markup))
170
+ return block;
171
+ const src = `data:image/svg+xml;base64,${base64Utf8(markup)}`;
172
+ return `<div class="svg-block" data-svg-view="image"><button type="button" class="svg-toggle" data-svg-toggle><span class="to-code">Code</span><span class="to-image">Image</span></button><img class="svg-image" src="${src}" alt="SVG image">${block}</div>`;
173
+ });
174
+ }
175
+ function unescapeHtml(text) {
176
+ return text
177
+ .replaceAll("&lt;", "<")
178
+ .replaceAll("&gt;", ">")
179
+ .replaceAll("&quot;", '"')
180
+ .replaceAll("&#39;", "'")
181
+ .replaceAll("&#x27;", "'")
182
+ .replaceAll("&amp;", "&");
183
+ }
@@ -0,0 +1,28 @@
1
+ import { LitElement } from "lit";
2
+ import type { MarkdownHost, MarkdownPolicy } from "./render.ts";
3
+ /**
4
+ * Markdown rendered by arto-markdown, drawn into the Chat's own shadow root
5
+ * so the Chat's stylesheets reach it.
6
+ */
7
+ export declare class MarkdownView extends LitElement {
8
+ #private;
9
+ static properties: {
10
+ source: {
11
+ attribute: boolean;
12
+ };
13
+ policy: {
14
+ attribute: boolean;
15
+ };
16
+ host: {
17
+ attribute: boolean;
18
+ };
19
+ theme: {};
20
+ };
21
+ source: string;
22
+ policy: MarkdownPolicy;
23
+ host: MarkdownHost;
24
+ theme: "light" | "dark";
25
+ protected createRenderRoot(): HTMLElement;
26
+ protected render(): unknown;
27
+ protected updated(): void;
28
+ }
@@ -0,0 +1,39 @@
1
+ import { LitElement } from "lit";
2
+ import { draw, render } from "./frontend.js";
3
+ /**
4
+ * Markdown rendered by arto-markdown, drawn into the Chat's own shadow root
5
+ * so the Chat's stylesheets reach it.
6
+ */
7
+ export class MarkdownView extends LitElement {
8
+ static properties = {
9
+ source: { attribute: false },
10
+ policy: { attribute: false },
11
+ host: { attribute: false },
12
+ theme: {},
13
+ };
14
+ #viewer = null;
15
+ #html = "";
16
+ #libraries = [];
17
+ createRenderRoot() {
18
+ return this;
19
+ }
20
+ render() {
21
+ return null;
22
+ }
23
+ updated() {
24
+ if (!this.#viewer) {
25
+ this.#viewer = document.createElement("div");
26
+ this.#viewer.className = "markdown-viewer";
27
+ this.append(this.#viewer);
28
+ }
29
+ const rendered = render(this.source ?? "", this.policy, this.host);
30
+ if (rendered.html !== this.#html) {
31
+ this.#html = rendered.html;
32
+ this.#libraries = rendered.libraries;
33
+ this.#viewer.innerHTML = `<article class="markdown-body">${rendered.html}</article>`;
34
+ }
35
+ void draw(this.#viewer, this.#libraries, this.theme ?? "dark", this.policy.highlight !== "off");
36
+ }
37
+ }
38
+ if (!customElements.get("adroit-markdown"))
39
+ customElements.define("adroit-markdown", MarkdownView);
package/dist/read.d.ts ADDED
@@ -0,0 +1,32 @@
1
+ /** The file name at the end of `path`. */
2
+ export declare function fileName(path: string): string;
3
+ /** The language highlight.js highlights the file at `path` as; null for a type it does not know. */
4
+ export declare function languageOfPath(path: string): string | null;
5
+ /**
6
+ * A file's text as a read tool gave it, `cat -n` style, without the number
7
+ * before each line: the number its first line has, and the text. The
8
+ * numbers must run on from line to line, so text that only looks numbered
9
+ * is left alone; reminders the tool adds after the file are not the file.
10
+ * Null when the text is not numbered so.
11
+ */
12
+ export declare function numberedLines(text: string): {
13
+ first: number;
14
+ text: string;
15
+ } | null;
16
+ /** The code of `text` when it is one fenced code block and nothing else; null otherwise. */
17
+ export declare function unfenced(text: string): string | null;
18
+ /** A block of a read's raw output the Chat draws. */
19
+ export type ReadBlock = {
20
+ type: "text";
21
+ text: string;
22
+ } | {
23
+ type: "image";
24
+ data: string;
25
+ mimeType: string;
26
+ };
27
+ /**
28
+ * A read's raw output as blocks, in order: its text, and its images as ACP's
29
+ * image content or an image block as the Anthropic API spells it, which
30
+ * Claude Code's Read returns and acp-adapter passes on as the raw output.
31
+ */
32
+ export declare function readBlocks(raw: unknown): ReadBlock[];