@lightblues/jig 0.0.11 → 0.1.1
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.
- package/README.md +3 -1
- package/dist/canvas/bridge.d.ts +110 -0
- package/dist/canvas/bridge.js +255 -0
- package/dist/canvas/build.d.ts +25 -0
- package/dist/canvas/build.js +54 -0
- package/dist/canvas/compile.d.ts +29 -0
- package/dist/canvas/compile.js +218 -0
- package/dist/canvas/context.d.ts +43 -0
- package/dist/canvas/context.js +79 -0
- package/dist/canvas/document.d.ts +50 -0
- package/dist/canvas/document.js +128 -0
- package/dist/canvas/frame.d.ts +65 -0
- package/dist/canvas/frame.js +197 -0
- package/dist/canvas/names.d.ts +1 -0
- package/dist/canvas/names.js +6 -0
- package/dist/canvas/protocol.d.ts +93 -0
- package/dist/canvas/protocol.js +152 -0
- package/dist/canvas/runtime.d.ts +25 -0
- package/dist/canvas/runtime.js +110 -0
- package/dist/canvas/server.d.ts +5 -0
- package/dist/canvas/server.js +8 -0
- package/dist/canvas/state.d.ts +31 -0
- package/dist/canvas/state.js +72 -0
- package/dist/canvas/store.d.ts +39 -0
- package/dist/canvas/store.js +82 -0
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/markdown/blocks.d.ts +123 -0
- package/dist/markdown/blocks.js +166 -0
- package/dist/markdown/index.d.ts +24 -0
- package/dist/markdown/index.js +182 -1
- package/dist/markdown/mermaid.d.ts +34 -0
- package/dist/markdown/mermaid.js +84 -0
- package/dist/markdown/react.d.ts +30 -0
- package/dist/markdown/react.js +57 -0
- package/package.json +55 -3
package/dist/markdown/index.js
CHANGED
|
@@ -3,7 +3,10 @@
|
|
|
3
3
|
// so a host that does not use one does not install it, and no bundler has to resolve a missing optional peer.
|
|
4
4
|
import MarkdownIt from 'markdown-it';
|
|
5
5
|
import { closeOpenMarkdown } from "./close.js";
|
|
6
|
+
import { BLOCK_LIMITS, BLOCK_NAME, checkShape, mapPath, parseBody, validate, } from "./blocks.js";
|
|
6
7
|
export { closeOpenMarkdown };
|
|
8
|
+
export { BLOCK_LIMITS, BLOCK_NAME, YAML_MAX_ALIASES, cardToBlock, fromBlock, toBlock, } from "./blocks.js";
|
|
9
|
+
export { drawMermaid, MERMAID_CONFIG } from "./mermaid.js";
|
|
7
10
|
/** Longest inline `$…$` read as math. texmath's own rule has no bound, so a long line of `$a ` is quadratic. */
|
|
8
11
|
export const MAX_INLINE_MATH = 1000;
|
|
9
12
|
export const DEFAULT_REL = 'noopener noreferrer nofollow';
|
|
@@ -84,11 +87,189 @@ export function createMarkdown(opts = {}) {
|
|
|
84
87
|
else
|
|
85
88
|
md.use(p);
|
|
86
89
|
}
|
|
90
|
+
const blocks = useBlocks(md, opts);
|
|
87
91
|
const strip = opts.streamingStrip;
|
|
92
|
+
const doc = (text, r, out) => {
|
|
93
|
+
if (!r.streaming)
|
|
94
|
+
return md.render(text, blocks ? { [ENV]: out } : {});
|
|
95
|
+
if (!blocks)
|
|
96
|
+
return md.render(closeOpenMarkdown(text, strip ? { strip } : {}));
|
|
97
|
+
// Which fence, if any, the closer added: that block is still being written.
|
|
98
|
+
const s = strip ? stripTail(text, strip) : text;
|
|
99
|
+
const closed = closeOpenMarkdown(s);
|
|
100
|
+
const tail = closed.slice(s.length);
|
|
101
|
+
const open = closed.startsWith(s) && /^\n?(`{3,}|~{3,})$/.test(tail);
|
|
102
|
+
return md.render(closed, { [ENV]: out, [OPEN]: open });
|
|
103
|
+
};
|
|
88
104
|
return {
|
|
89
105
|
md,
|
|
90
|
-
render: (text, r = {}) =>
|
|
106
|
+
render: (text, r = {}) => doc(text, r, undefined),
|
|
107
|
+
renderDocument: (text, r = {}) => {
|
|
108
|
+
const out = { blocks: [], pending: [], errors: [] };
|
|
109
|
+
const html = doc(text, r, out);
|
|
110
|
+
return { html, ...out };
|
|
111
|
+
},
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
function stripTail(text, strip) {
|
|
115
|
+
const m = new RegExp(`(?:${strip.source})$`, strip.flags.replace(/[gym]/g, '')).exec(text);
|
|
116
|
+
return m ? text.slice(0, m.index) : text;
|
|
117
|
+
}
|
|
118
|
+
const ENV = Symbol('jig.blocks');
|
|
119
|
+
const OPEN = Symbol('jig.open');
|
|
120
|
+
const NONE = Symbol('jig.noBlocks');
|
|
121
|
+
const MERMAID = { format: 'text', parse: (s) => ({ ok: true, value: { source: String(s) } }) };
|
|
122
|
+
/**
|
|
123
|
+
* Did markdown-it find the fence's closing line? Its range is the opener, the content lines, and the closer if any;
|
|
124
|
+
* closed content ends with a newline (or is empty), so it holds exactly one newline per line between the fences.
|
|
125
|
+
*/
|
|
126
|
+
const closedFence = (t) => (t.content === '' || t.content.endsWith('\n')) && (t.content.match(/\n/g)?.length ?? 0) === t.map[1] - t.map[0] - 2;
|
|
127
|
+
/**
|
|
128
|
+
* The block layer: a core rule after block parsing turns each registered fence token into a `jig_block` token
|
|
129
|
+
* (slot, pending slot, hidden, or error), and a render rule writes it. Params never enter the HTML.
|
|
130
|
+
*/
|
|
131
|
+
function useBlocks(md, opts) {
|
|
132
|
+
const specs = new Map(Object.entries(opts.blocks ?? {}));
|
|
133
|
+
for (const name of specs.keys())
|
|
134
|
+
if (!BLOCK_NAME.test(name))
|
|
135
|
+
throw new Error(`block name must match ${BLOCK_NAME}: ${JSON.stringify(name)}`);
|
|
136
|
+
if (opts.mermaid) {
|
|
137
|
+
if (specs.has('mermaid'))
|
|
138
|
+
throw new Error('blocks: "mermaid" is registered twice (blocks and the mermaid option)');
|
|
139
|
+
specs.set('mermaid', MERMAID);
|
|
140
|
+
}
|
|
141
|
+
if (!specs.size)
|
|
142
|
+
return false;
|
|
143
|
+
for (const [name, spec] of specs) {
|
|
144
|
+
if ((spec.format ?? (opts.yaml ? 'yaml' : 'json')) === 'yaml' && !opts.yaml)
|
|
145
|
+
throw new Error(`block "${name}": format yaml needs the yaml option`);
|
|
146
|
+
}
|
|
147
|
+
const limits = { ...BLOCK_LIMITS, ...opts.blockLimits };
|
|
148
|
+
const allow = opts.links?.allow;
|
|
149
|
+
const names = [...specs.keys()];
|
|
150
|
+
// Markdown inside params goes through a safe instance: this one, or (with trustedHtml) the same options without it.
|
|
151
|
+
let safe = null;
|
|
152
|
+
const safeMd = () => (safe ??= opts.trustedHtml ? createMarkdown({ ...opts, trustedHtml: false, blocks: undefined, mermaid: false }).md : md);
|
|
153
|
+
const noBlocks = { [NONE]: true };
|
|
154
|
+
const settle = (spec, body) => {
|
|
155
|
+
if (body.length > limits.maxBody)
|
|
156
|
+
return [`body longer than ${limits.maxBody} characters`];
|
|
157
|
+
const format = spec.format ?? (opts.yaml ? 'yaml' : 'json');
|
|
158
|
+
const raw = parseBody(body, format, opts.yaml);
|
|
159
|
+
if (!raw.ok)
|
|
160
|
+
return raw.errors;
|
|
161
|
+
const shape = format === 'text' ? null : checkShape(raw.value, limits);
|
|
162
|
+
if (shape)
|
|
163
|
+
return [shape];
|
|
164
|
+
const r = validate(spec.parse, raw.value);
|
|
165
|
+
if (!r.ok)
|
|
166
|
+
return r.errors;
|
|
167
|
+
let value = r.value;
|
|
168
|
+
for (const [path, kind] of Object.entries(spec.urls ?? {})) {
|
|
169
|
+
const m = mapPath(value, path, (v, at) => {
|
|
170
|
+
if (v === undefined || v === null)
|
|
171
|
+
return { value: v };
|
|
172
|
+
if (typeof v !== 'string')
|
|
173
|
+
return `${at}: expected a URL`;
|
|
174
|
+
return urlAllowed(v, kind, allow) ? { value: v } : `${at}: URL not allowed`;
|
|
175
|
+
});
|
|
176
|
+
if (typeof m === 'string')
|
|
177
|
+
return [m];
|
|
178
|
+
value = m.value;
|
|
179
|
+
}
|
|
180
|
+
for (const [paths, inline] of [[spec.md, false], [spec.mdInline, true]]) {
|
|
181
|
+
for (const path of paths ?? []) {
|
|
182
|
+
const m = mapPath(value, path, (v, at) => {
|
|
183
|
+
if (v === undefined || v === null)
|
|
184
|
+
return { value: v };
|
|
185
|
+
if (typeof v !== 'string')
|
|
186
|
+
return `${at}: expected Markdown text`;
|
|
187
|
+
return { value: inline ? safeMd().renderInline(v, { ...noBlocks }) : safeMd().render(v, { ...noBlocks }) };
|
|
188
|
+
});
|
|
189
|
+
if (typeof m === 'string')
|
|
190
|
+
return [m];
|
|
191
|
+
value = m.value;
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
return { value };
|
|
195
|
+
};
|
|
196
|
+
md.core.ruler.after('block', 'jig_blocks', (state) => {
|
|
197
|
+
const env = (state.env ?? {});
|
|
198
|
+
if (env[NONE])
|
|
199
|
+
return;
|
|
200
|
+
const out = env[ENV];
|
|
201
|
+
const open = env[OPEN] === true;
|
|
202
|
+
const streaming = OPEN in env;
|
|
203
|
+
let lines = null;
|
|
204
|
+
let last = -1;
|
|
205
|
+
const counts = new Map();
|
|
206
|
+
let total = 0;
|
|
207
|
+
for (const t of state.tokens) {
|
|
208
|
+
if (t.type !== 'fence' || !t.map)
|
|
209
|
+
continue;
|
|
210
|
+
const name = t.info.trim().split(/\s+/)[0] ?? '';
|
|
211
|
+
const spec = specs.get(name);
|
|
212
|
+
if (!lines) {
|
|
213
|
+
lines = state.src.split('\n');
|
|
214
|
+
last = lines.length - 1;
|
|
215
|
+
while (last > 0 && !lines[last].trim())
|
|
216
|
+
last--;
|
|
217
|
+
}
|
|
218
|
+
const closed = closedFence(t);
|
|
219
|
+
// Streaming: a fence the closer just closed (it ends the text), or one it could not see (inside a quote), is open.
|
|
220
|
+
const pending = streaming && (!closed || (open && t.map[1] - 1 === last));
|
|
221
|
+
if (!spec) {
|
|
222
|
+
// A fence being opened whose name is still being typed (```fig of ```figure): nothing yet, not a code flash.
|
|
223
|
+
if (pending && !t.content && names.some((n) => n.startsWith(name))) {
|
|
224
|
+
t.type = 'jig_block';
|
|
225
|
+
t.meta = { kind: 'hidden' };
|
|
226
|
+
}
|
|
227
|
+
continue;
|
|
228
|
+
}
|
|
229
|
+
const n = counts.get(name) ?? 0;
|
|
230
|
+
counts.set(name, n + 1);
|
|
231
|
+
const key = `${name}-${n}`;
|
|
232
|
+
const line = t.map[0] + 1;
|
|
233
|
+
t.type = 'jig_block';
|
|
234
|
+
if (pending) {
|
|
235
|
+
t.meta = { kind: 'pending', name, key };
|
|
236
|
+
out?.pending.push({ key, name, line });
|
|
237
|
+
continue;
|
|
238
|
+
}
|
|
239
|
+
const body = t.content;
|
|
240
|
+
let r;
|
|
241
|
+
if (!closed)
|
|
242
|
+
r = ['block not closed'];
|
|
243
|
+
else if (++total > limits.maxBlocks)
|
|
244
|
+
r = [`more than ${limits.maxBlocks} blocks`];
|
|
245
|
+
else
|
|
246
|
+
r = settle(spec, body);
|
|
247
|
+
if (Array.isArray(r)) {
|
|
248
|
+
t.meta = { kind: 'error', name, key, source: body, errors: r };
|
|
249
|
+
out?.errors.push({ key, name, line, errors: r });
|
|
250
|
+
}
|
|
251
|
+
else {
|
|
252
|
+
t.meta = { kind: 'slot', name, key, source: spec === MERMAID ? body : undefined };
|
|
253
|
+
out?.blocks.push({ key, name, value: r.value, source: body, line });
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
});
|
|
257
|
+
const esc = md.utils.escapeHtml;
|
|
258
|
+
md.renderer.rules.jig_block = (tokens, idx) => {
|
|
259
|
+
const m = tokens[idx].meta;
|
|
260
|
+
if (m.kind === 'hidden')
|
|
261
|
+
return '';
|
|
262
|
+
const attrs = `data-jig-block="${esc(m.name)}" data-jig-key="${esc(m.key)}"`;
|
|
263
|
+
if (m.kind === 'pending')
|
|
264
|
+
return `<div ${attrs} data-jig-pending></div>\n`;
|
|
265
|
+
if (m.kind === 'error') {
|
|
266
|
+
return `<div class="jig-block-invalid" ${attrs}><pre><code class="language-${esc(m.name)}">${esc(m.source)}</code></pre>`
|
|
267
|
+
+ `<div class="jig-block-errors">${m.errors.map((e) => `<p>${esc(e)}</p>`).join('')}</div></div>\n`;
|
|
268
|
+
}
|
|
269
|
+
const inner = m.source === undefined ? '' : `<pre><code class="language-${esc(m.name)}">${esc(m.source)}</code></pre>`;
|
|
270
|
+
return `<div ${attrs}>${inner}</div>\n`;
|
|
91
271
|
};
|
|
272
|
+
return true;
|
|
92
273
|
}
|
|
93
274
|
/** Formulas kept per instance. While streaming, every frame re-renders the same formulas; KaTeX is ~80% of the cost. */
|
|
94
275
|
export const MATH_CACHE_SIZE = 500;
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/** The part of the `mermaid` module used. */
|
|
2
|
+
export type MermaidLike = {
|
|
3
|
+
initialize(config: Record<string, unknown>): void;
|
|
4
|
+
render(id: string, text: string): Promise<{
|
|
5
|
+
svg: string;
|
|
6
|
+
}>;
|
|
7
|
+
};
|
|
8
|
+
type MermaidModule = MermaidLike | {
|
|
9
|
+
default: MermaidLike;
|
|
10
|
+
};
|
|
11
|
+
export type MermaidSource = MermaidModule | (() => Promise<MermaidModule>);
|
|
12
|
+
export type DrawMermaidOptions = {
|
|
13
|
+
/** The host's mermaid config (theme, layout, fontFamily…). The keys of `MERMAID_CONFIG` are always jig's. */
|
|
14
|
+
config?: Record<string, unknown>;
|
|
15
|
+
};
|
|
16
|
+
/**
|
|
17
|
+
* Always applied over the host's config. `securityLevel: "strict"`: labels sanitised (DOMPurify), click handlers off.
|
|
18
|
+
* `secure` lists the keys a diagram's own `%%{init: …}%%` directive cannot set.
|
|
19
|
+
*/
|
|
20
|
+
export declare const MERMAID_CONFIG: {
|
|
21
|
+
readonly startOnLoad: false;
|
|
22
|
+
readonly securityLevel: "strict";
|
|
23
|
+
readonly suppressErrorRendering: true;
|
|
24
|
+
readonly maxTextSize: 50000;
|
|
25
|
+
readonly maxEdges: 500;
|
|
26
|
+
readonly secure: readonly ["secure", "securityLevel", "startOnLoad", "maxTextSize", "suppressErrorRendering", "maxEdges", "dompurifyConfig", "themeCSS", "htmlLabels"];
|
|
27
|
+
};
|
|
28
|
+
/**
|
|
29
|
+
* Draws `source` into `el` (its children replaced by `<div class="jig-mermaid">svg</div>`), or, if mermaid fails,
|
|
30
|
+
* shows the source as escaped code with class `jig-mermaid-error`. Resolves to whether it drew. `mermaid` is the module,
|
|
31
|
+
* or a loader (`() => import('mermaid')`) called on first use.
|
|
32
|
+
*/
|
|
33
|
+
export declare function drawMermaid(el: Element, source: string, mermaid: MermaidSource, o?: DrawMermaidOptions): Promise<boolean>;
|
|
34
|
+
export {};
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
// drawMermaid: a `mermaid` block's slot drawn with the host's mermaid module, locked down. Browser only (DOM globals),
|
|
2
|
+
// no imports: mermaid (~159 KB gzipped plus chunks) is the host's, passed in or loaded lazily.
|
|
3
|
+
/**
|
|
4
|
+
* Always applied over the host's config. `securityLevel: "strict"`: labels sanitised (DOMPurify), click handlers off.
|
|
5
|
+
* `secure` lists the keys a diagram's own `%%{init: …}%%` directive cannot set.
|
|
6
|
+
*/
|
|
7
|
+
export const MERMAID_CONFIG = {
|
|
8
|
+
startOnLoad: false,
|
|
9
|
+
securityLevel: 'strict',
|
|
10
|
+
suppressErrorRendering: true,
|
|
11
|
+
maxTextSize: 50_000,
|
|
12
|
+
maxEdges: 500,
|
|
13
|
+
secure: ['secure', 'securityLevel', 'startOnLoad', 'maxTextSize', 'suppressErrorRendering', 'maxEdges', 'dompurifyConfig', 'themeCSS', 'htmlLabels'],
|
|
14
|
+
};
|
|
15
|
+
const DROP = new Set(['script', 'iframe', 'object', 'embed', 'link', 'meta', 'base', 'form', 'input', 'textarea', 'button', 'select', 'frame', 'frameset', 'audio', 'video', 'img', 'image', 'animate', 'set', 'animatemotion', 'animatetransform', 'handler', 'listener', 'feimage']);
|
|
16
|
+
const URL_ATTRS = /^(href|xlink:href|src|srcset|action|formaction|data|poster|background|ping)$/i;
|
|
17
|
+
const FRAGMENT = /^\s*#[\w.:-]*$/;
|
|
18
|
+
/** CSS that loads or runs: `@import` statements, non-fragment `url()`, `expression()`, `javascript:`. */
|
|
19
|
+
function cleanCss(css) {
|
|
20
|
+
return css.replace(/@import[^;]*;?/gi, '').replace(/url\(\s*(?!['"]?#)[^)]*\)/gi, 'url(#)').replace(/expression\s*\(/gi, '(').replace(/javascript:/gi, '');
|
|
21
|
+
}
|
|
22
|
+
let seq = 0;
|
|
23
|
+
/**
|
|
24
|
+
* Strips what strict mode should already have: dangerous elements and handlers, URLs that are not fragment references
|
|
25
|
+
* (except `image`, dropped), CSS that loads. `foreignObject` (mermaid's HTML labels) stays: its content is an inert,
|
|
26
|
+
* scrubbed HTML subtree.
|
|
27
|
+
*/
|
|
28
|
+
function scrub(root) {
|
|
29
|
+
for (const el of [...root.querySelectorAll('*')]) {
|
|
30
|
+
const name = el.localName.toLowerCase();
|
|
31
|
+
if (DROP.has(name) || (name === 'use' && !FRAGMENT.test(el.getAttribute('href') ?? el.getAttribute('xlink:href') ?? ''))) {
|
|
32
|
+
el.remove();
|
|
33
|
+
continue;
|
|
34
|
+
}
|
|
35
|
+
for (const a of [...el.attributes]) {
|
|
36
|
+
const n = a.name.toLowerCase();
|
|
37
|
+
if (n.startsWith('on'))
|
|
38
|
+
el.removeAttribute(a.name);
|
|
39
|
+
else if (URL_ATTRS.test(n) && !FRAGMENT.test(a.value))
|
|
40
|
+
el.removeAttribute(a.name);
|
|
41
|
+
else if (n === 'style')
|
|
42
|
+
el.setAttribute(a.name, cleanCss(a.value));
|
|
43
|
+
}
|
|
44
|
+
if (name === 'style' && el.textContent)
|
|
45
|
+
el.textContent = cleanCss(el.textContent);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Draws `source` into `el` (its children replaced by `<div class="jig-mermaid">svg</div>`), or, if mermaid fails,
|
|
50
|
+
* shows the source as escaped code with class `jig-mermaid-error`. Resolves to whether it drew. `mermaid` is the module,
|
|
51
|
+
* or a loader (`() => import('mermaid')`) called on first use.
|
|
52
|
+
*/
|
|
53
|
+
export async function drawMermaid(el, source, mermaid, o = {}) {
|
|
54
|
+
const id = `jig-mmd-${++seq}`;
|
|
55
|
+
const doc = el.ownerDocument;
|
|
56
|
+
try {
|
|
57
|
+
const mod = typeof mermaid === 'function' ? await mermaid() : mermaid;
|
|
58
|
+
const m = 'default' in mod && mod.default ? mod.default : mod;
|
|
59
|
+
m.initialize({ ...o.config, ...MERMAID_CONFIG, secure: [...MERMAID_CONFIG.secure] });
|
|
60
|
+
const { svg } = await m.render(id, source);
|
|
61
|
+
const tpl = doc.createElement('template');
|
|
62
|
+
tpl.innerHTML = svg; // inert: nothing in a template loads or runs
|
|
63
|
+
scrub(tpl.content);
|
|
64
|
+
const view = doc.createElement('div');
|
|
65
|
+
view.className = 'jig-mermaid';
|
|
66
|
+
view.append(tpl.content);
|
|
67
|
+
el.replaceChildren(view);
|
|
68
|
+
return true;
|
|
69
|
+
}
|
|
70
|
+
catch {
|
|
71
|
+
const pre = doc.createElement('pre');
|
|
72
|
+
pre.className = 'jig-mermaid-error';
|
|
73
|
+
const code = doc.createElement('code');
|
|
74
|
+
code.className = 'language-mermaid';
|
|
75
|
+
code.textContent = source;
|
|
76
|
+
pre.append(code);
|
|
77
|
+
el.replaceChildren(pre);
|
|
78
|
+
return false;
|
|
79
|
+
}
|
|
80
|
+
finally {
|
|
81
|
+
doc.getElementById(id)?.remove();
|
|
82
|
+
doc.getElementById(`d${id}`)?.remove();
|
|
83
|
+
}
|
|
84
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@lightblues/jig/markdown/react`: `FillSlots` puts host components into the slots of a `renderDocument` result.
|
|
3
|
+
* The HTML is set as is (once per string); each block's component is portalled into a holder element that moves into
|
|
4
|
+
* the current slot after each commit, so a component stays mounted (state, effects, a drawn chart) while the text
|
|
5
|
+
* streams and the HTML around it is replaced. React DOM only.
|
|
6
|
+
*/
|
|
7
|
+
import { type ReactNode } from 'react';
|
|
8
|
+
import type { Block, PendingBlock } from './blocks.ts';
|
|
9
|
+
/** Draws one block: framework-escaped (React text), never HTML from a param except the `md` fields jig rendered. */
|
|
10
|
+
export type BlockRenderer = (value: any, ctx: {
|
|
11
|
+
key: string;
|
|
12
|
+
name: string;
|
|
13
|
+
}) => ReactNode;
|
|
14
|
+
export type FillSlotsProps = {
|
|
15
|
+
/** `renderDocument`'s result (or the server's, sent as JSON). */
|
|
16
|
+
doc: {
|
|
17
|
+
html: string;
|
|
18
|
+
blocks: Block[];
|
|
19
|
+
pending?: PendingBlock[];
|
|
20
|
+
};
|
|
21
|
+
/** Components by block name. A slot whose name has none keeps its own HTML (mermaid: its source). */
|
|
22
|
+
registry: Record<string, BlockRenderer | undefined>;
|
|
23
|
+
/** What a still-open block shows while streaming (default: nothing). */
|
|
24
|
+
pending?: (ctx: {
|
|
25
|
+
key: string;
|
|
26
|
+
name: string;
|
|
27
|
+
}) => ReactNode;
|
|
28
|
+
className?: string;
|
|
29
|
+
};
|
|
30
|
+
export declare function FillSlots({ doc, registry, pending, className }: FillSlotsProps): import("react").FunctionComponentElement<import("react").FragmentProps>;
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@lightblues/jig/markdown/react`: `FillSlots` puts host components into the slots of a `renderDocument` result.
|
|
3
|
+
* The HTML is set as is (once per string); each block's component is portalled into a holder element that moves into
|
|
4
|
+
* the current slot after each commit, so a component stays mounted (state, effects, a drawn chart) while the text
|
|
5
|
+
* streams and the HTML around it is replaced. React DOM only.
|
|
6
|
+
*/
|
|
7
|
+
import { createElement, Fragment, memo, useLayoutEffect, useRef } from 'react';
|
|
8
|
+
import { createPortal } from 'react-dom';
|
|
9
|
+
/** The HTML, set by React only when the string changes. */
|
|
10
|
+
const Html = memo(function Html({ html, className, root }) {
|
|
11
|
+
return createElement('div', { ref: root, className, dangerouslySetInnerHTML: { __html: html } });
|
|
12
|
+
});
|
|
13
|
+
/** Re-renders only when the block's source (so its value), its renderer or its state (pending → done) changes. */
|
|
14
|
+
const Fill = memo(function Fill({ render, value, source, name, k }) {
|
|
15
|
+
return createElement(Fragment, null, source === null ? render({ key: k, name }) : render(value, { key: k, name }));
|
|
16
|
+
}, (a, b) => a.render === b.render && a.source === b.source && a.name === b.name && a.k === b.k);
|
|
17
|
+
export function FillSlots({ doc, registry, pending, className }) {
|
|
18
|
+
const root = useRef(null);
|
|
19
|
+
const holders = useRef(new Map());
|
|
20
|
+
const dom = typeof document !== 'undefined';
|
|
21
|
+
const items = [];
|
|
22
|
+
for (const b of doc.blocks) {
|
|
23
|
+
const r = registry[b.name];
|
|
24
|
+
if (r)
|
|
25
|
+
items.push({ key: b.key, name: b.name, value: b.value, source: b.source, render: r });
|
|
26
|
+
}
|
|
27
|
+
if (pending)
|
|
28
|
+
for (const p of doc.pending ?? [])
|
|
29
|
+
if (registry[p.name])
|
|
30
|
+
items.push({ key: p.key, name: p.name, value: undefined, source: null, render: pending });
|
|
31
|
+
const live = new Set(items.map((i) => i.key));
|
|
32
|
+
const holder = (key) => {
|
|
33
|
+
let h = holders.current.get(key);
|
|
34
|
+
if (!h) {
|
|
35
|
+
h = document.createElement('div');
|
|
36
|
+
h.className = 'jig-slot';
|
|
37
|
+
holders.current.set(key, h);
|
|
38
|
+
}
|
|
39
|
+
return h;
|
|
40
|
+
};
|
|
41
|
+
useLayoutEffect(() => {
|
|
42
|
+
const el = root.current;
|
|
43
|
+
if (!el)
|
|
44
|
+
return;
|
|
45
|
+
for (const slot of el.querySelectorAll('[data-jig-key]')) {
|
|
46
|
+
const h = holders.current.get(slot.dataset.jigKey ?? '');
|
|
47
|
+
if (h && live.has(slot.dataset.jigKey) && (h.parentNode !== slot || slot.childNodes.length !== 1))
|
|
48
|
+
slot.replaceChildren(h);
|
|
49
|
+
}
|
|
50
|
+
for (const k of [...holders.current.keys()])
|
|
51
|
+
if (!live.has(k)) {
|
|
52
|
+
holders.current.get(k).remove();
|
|
53
|
+
holders.current.delete(k);
|
|
54
|
+
}
|
|
55
|
+
});
|
|
56
|
+
return createElement(Fragment, null, createElement(Html, { html: doc.html, className, root }), dom ? items.map((i) => createPortal(createElement(Fill, { render: i.render, value: i.value, source: i.source, name: i.name, k: i.key }), holder(i.key), i.key)) : null);
|
|
57
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lightblues/jig",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.1.1",
|
|
4
4
|
"description": "Reusable parts for my apps: agent runtimes (Paseo, pi) that speak AG-UI, a thin thread-following client, one markdown renderer, and more as they prove reusable.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -44,6 +44,30 @@
|
|
|
44
44
|
"types": "./dist/markdown/index.d.ts",
|
|
45
45
|
"default": "./dist/markdown/index.js"
|
|
46
46
|
},
|
|
47
|
+
"./markdown/react": {
|
|
48
|
+
"types": "./dist/markdown/react.d.ts",
|
|
49
|
+
"default": "./dist/markdown/react.js"
|
|
50
|
+
},
|
|
51
|
+
"./canvas/server": {
|
|
52
|
+
"types": "./dist/canvas/server.d.ts",
|
|
53
|
+
"default": "./dist/canvas/server.js"
|
|
54
|
+
},
|
|
55
|
+
"./canvas/state": {
|
|
56
|
+
"types": "./dist/canvas/state.d.ts",
|
|
57
|
+
"default": "./dist/canvas/state.js"
|
|
58
|
+
},
|
|
59
|
+
"./canvas/frame": {
|
|
60
|
+
"types": "./dist/canvas/frame.d.ts",
|
|
61
|
+
"default": "./dist/canvas/frame.js"
|
|
62
|
+
},
|
|
63
|
+
"./canvas/runtime": {
|
|
64
|
+
"types": "./dist/canvas/runtime.d.ts",
|
|
65
|
+
"default": "./dist/canvas/runtime.js"
|
|
66
|
+
},
|
|
67
|
+
"./canvas/build": {
|
|
68
|
+
"types": "./dist/canvas/build.d.ts",
|
|
69
|
+
"default": "./dist/canvas/build.js"
|
|
70
|
+
},
|
|
47
71
|
"./package.json": "./package.json"
|
|
48
72
|
},
|
|
49
73
|
"scripts": {
|
|
@@ -62,18 +86,26 @@
|
|
|
62
86
|
"@types/node": "^24.0.0",
|
|
63
87
|
"@types/pg": "8.23.1",
|
|
64
88
|
"@types/react": "19.3.0",
|
|
89
|
+
"@types/react-dom": "19.3.0",
|
|
65
90
|
"@types/react-test-renderer": "19.3.1",
|
|
66
91
|
"esbuild": "0.28.2",
|
|
92
|
+
"happy-dom": "21.0.4",
|
|
67
93
|
"highlight.js": "11.12.0",
|
|
68
94
|
"katex": "0.19.1",
|
|
69
95
|
"markdown-it": "15.0.3",
|
|
70
96
|
"markdown-it-cjk-friendly": "3.0.0",
|
|
71
97
|
"markdown-it-texmath": "1.0.0",
|
|
98
|
+
"mermaid": "12.3.0",
|
|
72
99
|
"pg": "8.23.1",
|
|
100
|
+
"playwright-core": "1.64.1",
|
|
73
101
|
"postgres": "3.4.9",
|
|
74
102
|
"react": "19.3.1",
|
|
103
|
+
"react-dom": "19.3.1",
|
|
75
104
|
"react-test-renderer": "19.3.1",
|
|
76
|
-
"
|
|
105
|
+
"sucrase": "3.35.1",
|
|
106
|
+
"typescript": "^5.9.0",
|
|
107
|
+
"yaml": "2.9.0",
|
|
108
|
+
"zod": "4.6.7"
|
|
77
109
|
},
|
|
78
110
|
"peerDependencies": {
|
|
79
111
|
"@ag-ui/core": "^1.0.5",
|
|
@@ -81,12 +113,17 @@
|
|
|
81
113
|
"@earendil-works/pi-ai": "~1.4.0",
|
|
82
114
|
"@earendil-works/pi-coding-agent": "~1.4.0",
|
|
83
115
|
"@getpaseo/client": "0.16.1 || 0.17.4",
|
|
116
|
+
"esbuild": ">=0.25",
|
|
84
117
|
"highlight.js": "^11.0.0",
|
|
85
118
|
"katex": ">=0.16.21",
|
|
86
119
|
"markdown-it": "^15.0.0",
|
|
87
120
|
"markdown-it-cjk-friendly": "^3.0.0",
|
|
88
121
|
"markdown-it-texmath": "~1.0.0",
|
|
89
|
-
"
|
|
122
|
+
"mermaid": "^12.0.0",
|
|
123
|
+
"react": ">=18",
|
|
124
|
+
"react-dom": ">=18",
|
|
125
|
+
"sucrase": "~3.35.0",
|
|
126
|
+
"yaml": "^2.0.0"
|
|
90
127
|
},
|
|
91
128
|
"peerDependenciesMeta": {
|
|
92
129
|
"@ag-ui/core": {
|
|
@@ -104,6 +141,9 @@
|
|
|
104
141
|
"@getpaseo/client": {
|
|
105
142
|
"optional": true
|
|
106
143
|
},
|
|
144
|
+
"esbuild": {
|
|
145
|
+
"optional": true
|
|
146
|
+
},
|
|
107
147
|
"highlight.js": {
|
|
108
148
|
"optional": true
|
|
109
149
|
},
|
|
@@ -119,8 +159,20 @@
|
|
|
119
159
|
"markdown-it-texmath": {
|
|
120
160
|
"optional": true
|
|
121
161
|
},
|
|
162
|
+
"mermaid": {
|
|
163
|
+
"optional": true
|
|
164
|
+
},
|
|
122
165
|
"react": {
|
|
123
166
|
"optional": true
|
|
167
|
+
},
|
|
168
|
+
"react-dom": {
|
|
169
|
+
"optional": true
|
|
170
|
+
},
|
|
171
|
+
"sucrase": {
|
|
172
|
+
"optional": true
|
|
173
|
+
},
|
|
174
|
+
"yaml": {
|
|
175
|
+
"optional": true
|
|
124
176
|
}
|
|
125
177
|
}
|
|
126
178
|
}
|