@xharness/satori-element 0.0.0-stage → 4.0.1-alpha.2

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,397 @@
1
+ /**
2
+ * `normalize()`: the structural contract adapters rely on.
3
+ *
4
+ * - the root is one `<message>`;
5
+ * - flow containers (`message`, `li`, `td`, `th`, `blockquote`, `details`) contain blocks: bare inline runs are
6
+ * wrapped into `<p>`, whitespace-only runs between blocks are dropped;
7
+ * - envelope elements (`quote`, `title`) only appear as direct root children, at most one each, hoisted to the
8
+ * front in the order `quote`, `title`; `summary` is hoisted to the front of its `details`;
9
+ * - `<markdown>` stays one element with its source in `content` (text children are joined into it); the IM render
10
+ * engine expands it, so the source is never parsed here;
11
+ * - a `<fallback>` may stand wherever its candidates may: each candidate becomes one `<case>` normalized as content
12
+ * of the element the `<fallback>` stands in (a fallback of phrasing content joins the surrounding inline run);
13
+ * - T3 (reserved), alias and unknown tags are rejected, as are blocks inside phrasing content and children of
14
+ * elements that take none;
15
+ * - adjacent text is merged, empty text dropped. The input is never mutated; the result is idempotent.
16
+ */
17
+
18
+ import { elementInfo, isReservedTag, isTag, tagAliases } from './elements.ts'
19
+ import { make, toChildren } from './factory.ts'
20
+ import type { Child, Element, Tag } from './vocabulary.ts'
21
+
22
+ /** Thrown for content that violates the v4 structure. `path` locates the offending node (`message/ul[2]/li[0]`). */
23
+ export class NormalizeError extends Error {
24
+ override name = 'NormalizeError'
25
+ constructor(message: string, readonly path: string) {
26
+ super(`${message} (at ${path})`)
27
+ }
28
+ }
29
+
30
+ type Node = Element & { attrs: Record<string, unknown> }
31
+
32
+ /** Normalize any content into one `<message>` root. */
33
+ export function normalize(content: Child): Element<'message'> {
34
+ const nodes = toChildren(content) as Node[]
35
+ if (nodes.length === 1 && nodes[0]!.type === 'message') {
36
+ const [root] = nodes as [Node]
37
+ return make('message', root.attrs, normalizeChildren(root.children, 'message'), root.key) as Element<'message'>
38
+ }
39
+ return make('message', {}, normalizeChildren(nodes, 'message'), undefined) as Element<'message'>
40
+ }
41
+
42
+ /**
43
+ * Normalize content as the children of an element of tag `parent` (used for fallback output and partial trees).
44
+ * `path` is only used in error messages.
45
+ */
46
+ export function normalizeChildren(content: Child, parent: Tag, path: string = parent): Element[] {
47
+ const nodes = toChildren(content) as Node[]
48
+ const model = elementInfo[parent].content
49
+ switch (model) {
50
+ case 'empty': {
51
+ const extra = nodes.find(node => !isEmptyText(node))
52
+ if (extra) throw new NormalizeError(`<${parent}> takes no children, got <${extra.type}>`, path)
53
+ return []
54
+ }
55
+ case 'text': return normalizeText(nodes, parent, path)
56
+ case 'phrasing': return normalizePhrasing(nodes, parent, path)
57
+ case 'flow':
58
+ case 'details': return normalizeFlow(nodes, parent, path)
59
+ case 'list': return normalizeList(nodes, parent, path)
60
+ case 'table': return normalizeOnly(nodes, parent, path, ['tr'])
61
+ case 'row': return normalizeOnly(nodes, parent, path, ['th', 'td'])
62
+ case 'buttons': return normalizeOnly(nodes, parent, path, ['button'])
63
+ case 'options': return normalizeOnly(nodes, parent, path, ['option'])
64
+ case 'cases':
65
+ // A `<fallback>`'s candidates are normalized as content of *its* parent, which this function cannot see.
66
+ if (!nodes.length) return []
67
+ throw new NormalizeError(`the candidates of <${parent}> are normalized as content of its parent`, path)
68
+ }
69
+ }
70
+
71
+ /** Candidates of a `<fallback>`: its `<case>` children, or each other child as a candidate of its own. */
72
+ function candidatesOf(node: Node): Node[][] {
73
+ return (node.children as Node[]).map(child => child.type === 'case' ? toChildren(child.children) as Node[] : [child])
74
+ }
75
+
76
+ /** Whether a `<fallback>` holds only phrasing content, so it joins an inline run instead of standing as a block. */
77
+ function isInlineFallback(node: Node): boolean {
78
+ return candidatesOf(node).every(candidate => candidate.every(child => child.type === 'fallback'
79
+ ? isInlineFallback(child)
80
+ : isTag(child.type) && elementInfo[child.type].position === 'inline'))
81
+ }
82
+
83
+ /** Normalize every candidate of a `<fallback>` as content of `parent`, the element the `<fallback>` stands in. */
84
+ function normalizeFallback(node: Node, parent: Tag, path: string): Node {
85
+ const candidates = candidatesOf(node)
86
+ if (!candidates.length) throw new NormalizeError('<fallback> needs at least one candidate', path)
87
+ const cases = candidates.map((candidate, index) =>
88
+ make('case', {}, normalizeChildren(candidate, parent, `${path}/case[${index}]`)))
89
+ return make('fallback', {}, cases, node.key) as Node
90
+ }
91
+
92
+ function isEmptyText(node: Node) {
93
+ return node.type === 'text' && !node.attrs.content
94
+ }
95
+
96
+ function isBlankText(node: Node) {
97
+ return node.type === 'text' && typeof node.attrs.content === 'string' && !node.attrs.content.trim()
98
+ }
99
+
100
+ function childPath(path: string, node: Node, index: number) {
101
+ return `${path}/${node.type || 'fragment'}[${index}]`
102
+ }
103
+
104
+ function checkTag(node: Node, path: string): Tag {
105
+ const type = node.type as string
106
+ if (isTag(type)) return type
107
+ if (isReservedTag(type)) throw new NormalizeError(`<${type}> is reserved (T3) and not supported in v1`, path)
108
+ const alias = tagAliases[type]
109
+ if (alias) throw new NormalizeError(`unknown element <${type}>; use <${alias}>`, path)
110
+ if (type === 'component') throw new NormalizeError('function components must be called while building the tree', path)
111
+ throw new NormalizeError(`unknown element <${type}>`, path)
112
+ }
113
+
114
+ function nonEmptyString(value: unknown) {
115
+ return typeof value === 'string' && value.length > 0
116
+ }
117
+
118
+ function checkAttrs(tag: Tag, attrs: Record<string, unknown>, path: string) {
119
+ for (const name of elementInfo[tag].required ?? []) {
120
+ if (!nonEmptyString(attrs[name])) throw new NormalizeError(`<${tag}> requires a non-empty "${name}"`, path)
121
+ }
122
+ if (tag === 'text' && typeof attrs.content !== 'string') {
123
+ throw new NormalizeError('<text> requires a string "content"', path)
124
+ }
125
+ if (tag === 'at') {
126
+ if (!['user', 'all', 'here', 'role'].includes(attrs.type as string)) {
127
+ throw new NormalizeError(`<at> type must be user | all | here | role, got ${String(attrs.type)}`, path)
128
+ }
129
+ if ((attrs.type === 'user' || attrs.type === 'role') && !nonEmptyString(attrs.id)) {
130
+ throw new NormalizeError(`<at type="${attrs.type}"> requires an "id"`, path)
131
+ }
132
+ }
133
+ if (tag === 'button') {
134
+ const field = ({ action: 'id', link: 'href', input: 'text', submit: 'id' } as Record<string, string>)[attrs.type as string]
135
+ if (!field) throw new NormalizeError(`<button> type must be action | link | input | submit, got ${String(attrs.type)}`, path)
136
+ if (!nonEmptyString(attrs[field])) throw new NormalizeError(`<button type="${attrs.type}"> requires "${field}"`, path)
137
+ checkButtonStyle(attrs, path)
138
+ }
139
+ if (tag === 'button-group') {
140
+ checkOneOf('button-group', 'width', attrs.width, ['auto', 'fill'], path)
141
+ checkOneOf('button-group', 'align', attrs.align, ['left', 'center', 'right'], path)
142
+ }
143
+ if (tag === 'input') checkInput(attrs, path)
144
+ if (tag === 'select') checkSelect(attrs, path)
145
+ if (tag === 'option' && attrs.selected !== undefined && typeof attrs.selected !== 'boolean') {
146
+ throw new NormalizeError('<option> selected must be a boolean', path)
147
+ }
148
+ }
149
+
150
+ /** A `<select>`: it names a channel (`id` or `name`), and its initial value matches the arity `multiple` asks for. */
151
+ function checkSelect(attrs: Record<string, unknown>, path: string) {
152
+ for (const name of ['placeholder', 'data', 'name']) {
153
+ if (attrs[name] !== undefined && !nonEmptyString(attrs[name])) {
154
+ throw new NormalizeError(`<select> ${name} must be a non-empty string`, path)
155
+ }
156
+ }
157
+ if (attrs.id !== undefined && !nonEmptyString(attrs.id)) {
158
+ throw new NormalizeError('<select> id must be a non-empty string', path)
159
+ }
160
+ if (!nonEmptyString(attrs.id) && !nonEmptyString(attrs.name)) {
161
+ throw new NormalizeError('<select> requires an "id" (reports its pick) or a "name" (feeds its form)', path)
162
+ }
163
+ const value = attrs.value
164
+ if (value === undefined) return
165
+ const ok = attrs.multiple
166
+ ? Array.isArray(value) && value.every(item => typeof item === 'string')
167
+ : typeof value === 'string'
168
+ if (!ok) {
169
+ throw new NormalizeError(`<select${attrs.multiple ? ' multiple' : ''}> value must be ${attrs.multiple ? 'string[]' : 'a string'}`, path)
170
+ }
171
+ }
172
+
173
+ /** A control's channel, its input mode, its bounds and the value type each mode takes. */
174
+ function checkInput(attrs: Record<string, unknown>, path: string) {
175
+ checkOneOf('input', 'type', attrs.type, ['text', 'multiline', 'password', 'checkbox'], path)
176
+ for (const name of ['label', 'placeholder', 'name', 'id']) {
177
+ if (attrs[name] !== undefined && !nonEmptyString(attrs[name])) {
178
+ throw new NormalizeError(`<input> ${name} must be a non-empty string`, path)
179
+ }
180
+ }
181
+ if (!nonEmptyString(attrs.name) && !nonEmptyString(attrs.id)) {
182
+ throw new NormalizeError('<input> requires a "name" (feeds its form) or an "id" (reports its toggle)', path)
183
+ }
184
+ const checkbox = attrs.type === 'checkbox'
185
+ if (attrs.onChange !== undefined) {
186
+ if (!checkbox) throw new NormalizeError('<input> onChange needs type="checkbox"', path)
187
+ if (!nonEmptyString(attrs.id)) throw new NormalizeError('<input type="checkbox" onChange> requires an "id"', path)
188
+ }
189
+ if (attrs.maxLength !== undefined) {
190
+ const max = attrs.maxLength
191
+ if (typeof max !== 'number' || !Number.isInteger(max) || max <= 0) {
192
+ throw new NormalizeError(`<input> maxLength must be a positive integer, got ${String(max)}`, path)
193
+ }
194
+ }
195
+ if (attrs.value !== undefined && typeof attrs.value !== (checkbox ? 'boolean' : 'string')) {
196
+ throw new NormalizeError(`<input${checkbox ? ' type="checkbox"' : ''}> value must be a ${checkbox ? 'boolean' : 'string'}`, path)
197
+ }
198
+ }
199
+
200
+ /** Reject a present attribute outside its allowed values. */
201
+ function checkOneOf(tag: Tag, name: string, value: unknown, allowed: readonly string[], path: string) {
202
+ if (value !== undefined && !allowed.includes(value as string)) {
203
+ throw new NormalizeError(`<${tag}> ${name} must be ${allowed.join(' | ')}, got ${String(value)}`, path)
204
+ }
205
+ }
206
+
207
+ /** The optional `ButtonStyle` attributes: closed values, a positive pixel width and a complete confirmation. */
208
+ function checkButtonStyle(attrs: Record<string, unknown>, path: string) {
209
+ checkOneOf('button', 'size', attrs.size, ['tiny', 'small', 'medium', 'large'], path)
210
+ checkOneOf('button', 'variant', attrs.variant, [
211
+ 'default', 'primary', 'danger', 'text', 'primary_text', 'danger_text', 'primary_filled', 'danger_filled', 'laser',
212
+ ], path)
213
+ const width = attrs.width
214
+ if (width !== undefined && width !== 'default' && width !== 'fill'
215
+ && !(typeof width === 'number' && Number.isFinite(width) && width > 0)) {
216
+ throw new NormalizeError(`<button> width must be default | fill | a positive number of pixels, got ${String(width)}`, path)
217
+ }
218
+ for (const name of ['icon', 'tip', 'disabledTip']) {
219
+ if (attrs[name] !== undefined && !nonEmptyString(attrs[name])) {
220
+ throw new NormalizeError(`<button> ${name} must be a non-empty string`, path)
221
+ }
222
+ }
223
+ const confirm = attrs.confirm as { title?: unknown; text?: unknown } | undefined
224
+ if (confirm !== undefined && (typeof confirm !== 'object' || confirm === null
225
+ || !nonEmptyString(confirm.title) || !nonEmptyString(confirm.text))) {
226
+ throw new NormalizeError('<button> confirm requires a non-empty "title" and "text"', path)
227
+ }
228
+ }
229
+
230
+ /** Normalize one element (its own tag, attributes and children); the caller checked its position. */
231
+ function normalizeElement(node: Node, tag: Tag, path: string): Node {
232
+ checkAttrs(tag, node.attrs, path)
233
+ if (tag === 'text') return make('text', node.attrs, [], node.key) as Node
234
+ return make(tag, node.attrs, normalizeChildren(node.children, tag, path), node.key) as Node
235
+ }
236
+
237
+ function markdownSource(node: Node, path: string): string {
238
+ if (typeof node.attrs.content === 'string') return node.attrs.content
239
+ const children = toChildren(node.children) as Node[]
240
+ if (children.every(child => child.type === 'text')) return children.map(child => child.attrs.content).join('')
241
+ throw new NormalizeError('<markdown> requires a "content" string (or text children)', path)
242
+ }
243
+
244
+ /** `<markdown>` with its source in `content`; the render engine expands it (the source is never parsed here). */
245
+ function normalizeMarkdown(node: Node, path: string): Node {
246
+ return make('markdown', { content: markdownSource(node, path) }, [], node.key) as Node
247
+ }
248
+
249
+ function normalizeText(nodes: Node[], parent: Tag, path: string): Element[] {
250
+ let content = ''
251
+ nodes.forEach((node, index) => {
252
+ if (node.type === 'text' && typeof node.attrs.content === 'string') content += node.attrs.content
253
+ else if (node.type === 'br') content += '\n'
254
+ else throw new NormalizeError(`<${parent}> only contains text, got <${node.type}>`, childPath(path, node, index))
255
+ })
256
+ return content ? [make('text', { content }, [])] : []
257
+ }
258
+
259
+ function pushText(out: Node[], node: Node) {
260
+ const content = node.attrs.content as string
261
+ if (!content) return
262
+ const last = out[out.length - 1]
263
+ if (last?.type === 'text' && last.key === undefined && node.key === undefined) {
264
+ out[out.length - 1] = make('text', { ...last.attrs, content: (last.attrs.content as string) + content }, []) as Node
265
+ } else {
266
+ out.push(node)
267
+ }
268
+ }
269
+
270
+ interface Item { node: Node; path: string }
271
+
272
+ function items(nodes: Node[], path: string): Item[] {
273
+ return nodes.map((node, index) => ({ node, path: childPath(path, node, index) }))
274
+ }
275
+
276
+ function normalizePhrasing(nodes: Node[], parent: Tag, path: string): Element[] {
277
+ return phrasing(items(nodes, path), parent)
278
+ }
279
+
280
+ function phrasing(list: Item[], parent: Tag): Element[] {
281
+ const out: Node[] = []
282
+ list.forEach(({ node, path: p }) => {
283
+ if (node.type === 'markdown') {
284
+ out.push(normalizeMarkdown(node, p))
285
+ return
286
+ }
287
+ if (node.type === 'fallback') {
288
+ out.push(normalizeFallback(node, parent, p))
289
+ return
290
+ }
291
+ const tag = checkTag(node, p)
292
+ const info = elementInfo[tag]
293
+ if (info.parents && !info.parents.includes(parent)) {
294
+ throw new NormalizeError(`<${tag}> is only allowed directly inside ${info.parents.map(t => `<${t}>`).join(' or ')}`, p)
295
+ }
296
+ if (info.position === 'block') {
297
+ throw new NormalizeError(`block <${tag}> inside inline content of <${parent}>`, p)
298
+ }
299
+ const el = normalizeElement(node, tag, p)
300
+ if (tag === 'text') pushText(out, el)
301
+ else out.push(el)
302
+ })
303
+ return out
304
+ }
305
+
306
+ function normalizeFlow(nodes: Node[], parent: Tag, path: string): Element[] {
307
+ const out: Node[] = []
308
+ const envelope: Partial<Record<'quote' | 'title' | 'summary', Node>> = {}
309
+ let run: Item[] = []
310
+ const flush = () => {
311
+ if (run.length && !run.every(({ node }) => isBlankText(node) || isEmptyText(node))) {
312
+ const children = phrasing(run, 'p')
313
+ if (children.length) out.push(make('p', {}, children) as Node)
314
+ }
315
+ run = []
316
+ }
317
+ for (const { node, path: p } of items(nodes, path)) {
318
+ if (node.type === 'markdown') {
319
+ flush()
320
+ out.push(normalizeMarkdown(node, p))
321
+ continue
322
+ }
323
+ if (node.type === 'fallback') {
324
+ if (isInlineFallback(node)) {
325
+ run.push({ node, path: p })
326
+ } else {
327
+ flush()
328
+ out.push(normalizeFallback(node, parent, p))
329
+ }
330
+ continue
331
+ }
332
+ const tag = checkTag(node, p)
333
+ const info = elementInfo[tag]
334
+ if (info.parents && !info.parents.includes(parent)) {
335
+ throw new NormalizeError(`<${tag}> is only allowed directly inside ${info.parents.map(t => `<${t}>`).join(' or ')}`, p)
336
+ }
337
+ if (info.position === 'inline') {
338
+ run.push({ node, path: p })
339
+ continue
340
+ }
341
+ flush()
342
+ if (tag === 'quote' || tag === 'title' || tag === 'summary') {
343
+ if (envelope[tag]) throw new NormalizeError(`at most one <${tag}> per <${parent}>`, p)
344
+ envelope[tag] = normalizeElement(node, tag, p)
345
+ continue
346
+ }
347
+ if (tag === 'message') throw new NormalizeError('<message> is only allowed as the root', p)
348
+ out.push(normalizeElement(node, tag, p))
349
+ }
350
+ flush()
351
+ const head = [envelope.quote, envelope.title, envelope.summary].filter((x): x is Node => !!x)
352
+ return [...head, ...out]
353
+ }
354
+
355
+ function normalizeList(nodes: Node[], parent: Tag, path: string): Element[] {
356
+ const out: Element[] = []
357
+ let run: Node[] = []
358
+ let runPath = path
359
+ const flush = () => {
360
+ if (run.length && !run.every(node => isBlankText(node) || isEmptyText(node))) {
361
+ out.push(make('li', {}, normalizeChildren(run, 'li', `${runPath}<li>`)))
362
+ }
363
+ run = []
364
+ }
365
+ for (const { node, path: p } of items(nodes, path)) {
366
+ if (node.type === 'li') {
367
+ flush()
368
+ out.push(normalizeElement(node, 'li', p))
369
+ } else if (node.type === 'fallback') {
370
+ flush()
371
+ out.push(normalizeFallback(node, parent, p))
372
+ } else {
373
+ if (!run.length) runPath = p
374
+ run.push(node)
375
+ }
376
+ }
377
+ flush()
378
+ return out
379
+ }
380
+
381
+ function normalizeOnly(nodes: Node[], parent: Tag, path: string, allowed: Tag[]): Element[] {
382
+ const out: Element[] = []
383
+ nodes.forEach((node, index) => {
384
+ const p = childPath(path, node, index)
385
+ if (isBlankText(node) || isEmptyText(node)) return
386
+ if (node.type === 'fallback') {
387
+ out.push(normalizeFallback(node, parent, p))
388
+ return
389
+ }
390
+ const tag = checkTag(node, p)
391
+ if (!allowed.includes(tag)) {
392
+ throw new NormalizeError(`<${parent}> only contains ${allowed.map(t => `<${t}>`).join(' or ')}, got <${tag}>`, p)
393
+ }
394
+ out.push(normalizeElement(node, tag, p))
395
+ })
396
+ return out
397
+ }
package/src/text.ts ADDED
@@ -0,0 +1,161 @@
1
+ /**
2
+ * `toText()`: the plain-text projection of content (fallbacks, tests, history, agent-facing inbound text).
3
+ *
4
+ * Total: works on unnormalized trees and never throws for unknown tags (their children are projected).
5
+ * Blocks are separated by one newline; envelope `quote` is omitted, `title` is the first line; a `<fallback>` projects
6
+ * its last candidate; `<markdown>` projects its source as it is (the converter lives with the IM render engine).
7
+ */
8
+
9
+ import { elementInfo, isTag } from './elements.ts'
10
+ import { Fragment, toChildren } from './factory.ts'
11
+ import type { Child, Element } from './vocabulary.ts'
12
+
13
+ type Node = Element & { attrs: Record<string, any> }
14
+
15
+ export function toText(content: Child): string {
16
+ return flow(toChildren(content) as Node[])
17
+ }
18
+
19
+ function isBlockNode(node: Node): boolean {
20
+ const type = node.type as string
21
+ if (type === Fragment || !isTag(type)) return false
22
+ return elementInfo[type].position !== 'inline'
23
+ }
24
+
25
+ /** Children in flow position: consecutive inline nodes form one line group, blocks stand alone. */
26
+ function flow(nodes: Node[]): string {
27
+ const chunks: string[] = []
28
+ let run: Node[] = []
29
+ const flush = () => {
30
+ if (run.length) {
31
+ const text = inline(run)
32
+ if (text.trim()) chunks.push(text)
33
+ }
34
+ run = []
35
+ }
36
+ for (const node of nodes) {
37
+ if (isBlockNode(node)) {
38
+ flush()
39
+ const text = blockText(node)
40
+ if (text !== undefined) chunks.push(text)
41
+ } else {
42
+ run.push(node)
43
+ }
44
+ }
45
+ flush()
46
+ return chunks.join('\n')
47
+ }
48
+
49
+ function inline(nodes: Node[]): string {
50
+ return nodes.map(inlineText).join('')
51
+ }
52
+
53
+ function children(node: Node): string {
54
+ return inline(node.children as Node[])
55
+ }
56
+
57
+ function prefixLines(text: string, first: string, rest: string = ' '.repeat(first.length)) {
58
+ return text.split('\n').map((line, index) => (index ? rest : first) + line).join('\n')
59
+ }
60
+
61
+ function label(kind: string, name: unknown) {
62
+ return name ? `[${kind}: ${name}]` : `[${kind}]`
63
+ }
64
+
65
+ function buttonText(node: Node) {
66
+ const text = children(node) || node.attrs.text || node.attrs.href || node.attrs.id || 'button'
67
+ return `[${text}]`
68
+ }
69
+
70
+ /** A control's text: a checkbox keeps its box and label, every other mode names what would be entered. */
71
+ function inputText(node: Node) {
72
+ const { label, name, type, placeholder, value } = node.attrs
73
+ if (type === 'checkbox') return `${value ? '☑' : '☐'} ${label ?? name ?? ''}`.trimEnd()
74
+ return `[${label ?? placeholder ?? name ?? ''}]`
75
+ }
76
+
77
+ /** A select lists what could have been chosen, so the reader sees the options a click would have offered. */
78
+ function selectText(node: Node) {
79
+ const head = node.attrs.placeholder ?? '选择'
80
+ const labels = (node.children as Node[])
81
+ .filter(child => child.type === 'option')
82
+ .map(option => children(option) || String(option.attrs.value ?? ''))
83
+ return labels.length ? `[${head}: ${labels.join(' / ')}]` : `[${head}]`
84
+ }
85
+
86
+ /** The last candidate of a `<fallback>`: the plainest alternative, which a text projection stands for. */
87
+ function lastCandidate(node: Node): Node[] {
88
+ const last = (node.children as Node[]).at(-1)
89
+ if (!last) return []
90
+ return last.type === 'case' ? last.children as Node[] : [last]
91
+ }
92
+
93
+ /** Text of a block element; `undefined` = renders nothing (envelope quote). */
94
+ function blockText(node: Node): string | undefined {
95
+ const { attrs } = node
96
+ const kids = node.children as Node[]
97
+ switch (node.type) {
98
+ case 'quote': return undefined
99
+ case 'message': return flow(kids)
100
+ case 'fallback': return flow(lastCandidate(node))
101
+ case 'title': return attrs.subtitle ? `${children(node)}\n${attrs.subtitle}` : children(node)
102
+ case 'pre': return inline(kids).replace(/\n$/, '')
103
+ case 'hr': return '---'
104
+ case 'blockquote': return prefixLines(flow(kids), '> ', '> ')
105
+ case 'ul':
106
+ case 'ol': {
107
+ let index = node.type === 'ol' && typeof attrs.start === 'number' ? attrs.start : 1
108
+ return kids.map((item) => {
109
+ const marker = node.type === 'ol' ? `${index++}. ` : '• '
110
+ const body = item.type === 'li' ? flow(item.children as Node[]) : flow([item])
111
+ const check = item.type === 'li' && typeof item.attrs.checked === 'boolean' ? (item.attrs.checked ? '☑ ' : '☐ ') : ''
112
+ return prefixLines(check + body, marker)
113
+ }).join('\n')
114
+ }
115
+ case 'li': return prefixLines(flow(kids), '• ')
116
+ case 'table': return kids.map(row => blockText(row) ?? '').join('\n')
117
+ case 'tr': return kids.map(cell => flow(cell.children as Node[]).replace(/\n/g, ' ')).join(' | ')
118
+ case 'th':
119
+ case 'td': return flow(kids)
120
+ case 'details': return flow(kids)
121
+ case 'button-group': return kids.map(child => child.type === 'button' ? buttonText(child) : inlineText(child)).join(' ')
122
+ case 'input': return inputText(node)
123
+ case 'select': return selectText(node)
124
+ case 'option': return children(node) || String(attrs.value ?? '')
125
+ case 'markdown': return String(attrs.content ?? children(node))
126
+ default: {
127
+ if (!isTag(node.type)) return children(node)
128
+ const info = elementInfo[node.type]
129
+ if (info.content === 'flow' || info.content === 'details') return flow(kids)
130
+ return info.position === 'block' ? children(node) : inlineText(node)
131
+ }
132
+ }
133
+ }
134
+
135
+ function inlineText(node: Node): string {
136
+ const { attrs } = node
137
+ switch (node.type) {
138
+ case 'text': return String(attrs.content ?? '')
139
+ case 'br': return '\n'
140
+ case 'at':
141
+ if (attrs.type === 'all') return '@all'
142
+ if (attrs.type === 'here') return '@here'
143
+ return `@${attrs.name ?? attrs.id ?? ''}`
144
+ case 'channel': return `#${attrs.name ?? attrs.id ?? ''}`
145
+ case 'emoji': return `:${attrs.name ?? attrs.id ?? ''}:`
146
+ case 'a': {
147
+ const text = children(node)
148
+ return !text || text === attrs.href ? String(attrs.href ?? '') : attrs.href ? `${text} (${attrs.href})` : text
149
+ }
150
+ case 'img': return label('image', attrs.alt)
151
+ case 'audio': return label('audio', attrs.name)
152
+ case 'video': return label('video', attrs.name)
153
+ case 'file': return label('file', attrs.name)
154
+ case 'button': return buttonText(node)
155
+ case 'forward': return children(node) || '[forward]'
156
+ case 'quote': return ''
157
+ case 'fallback': return inline(lastCandidate(node))
158
+ case 'markdown': return String(attrs.content ?? children(node))
159
+ default: return isTag(node.type) && elementInfo[node.type].position === 'block' ? blockText(node) ?? '' : children(node)
160
+ }
161
+ }
@@ -0,0 +1,83 @@
1
+ /**
2
+ * Variant detection: which `element.<tag>.<variant>` keys an element instance needs.
3
+ */
4
+
5
+ import { isPhrasingContainer } from './elements.ts'
6
+ import type { Element, ElementKey, Tag, VariantMap, VariantOf } from './vocabulary.ts'
7
+
8
+ /** Declared variants per tag, in `VariantMap` order. */
9
+ export const variantTable: { readonly [K in keyof VariantMap]: readonly VariantMap[K][] } = {
10
+ at: ['user', 'all', 'here', 'role'],
11
+ li: ['checked', 'nested'],
12
+ pre: ['lang'],
13
+ span: ['color'],
14
+ table: ['align'],
15
+ td: ['block'],
16
+ img: ['inline'],
17
+ button: ['action', 'link', 'input', 'submit', 'theme', 'inline'],
18
+ input: ['checkbox'],
19
+ select: ['multiple'],
20
+ }
21
+
22
+ /** Capability key of a tag or one of its variants: `variantKey('at', 'all')` → `'element.at.all'`. */
23
+ export function variantKey<K extends Tag>(tag: K, variant?: VariantOf<K>): ElementKey {
24
+ return (variant ? `element.${tag}.${variant}` : `element.${tag}`) as ElementKey
25
+ }
26
+
27
+ function isInlinePosition(ancestors: readonly Element[] | undefined) {
28
+ const parent = ancestors?.[ancestors.length - 1]
29
+ return !!parent && isPhrasingContainer(parent.type)
30
+ }
31
+
32
+ function hasAlign(table: Element): boolean {
33
+ return table.children.some(row => row.type === 'tr' && row.children.some(cell =>
34
+ (cell.type === 'td' || cell.type === 'th') && cell.attrs.align !== undefined && cell.attrs.align !== 'left'))
35
+ }
36
+
37
+ /**
38
+ * The variant keys an element instance needs, e.g. `<at type="all">` → `['all']`, `<pre lang>` → `['lang']`.
39
+ *
40
+ * Every variant depends only on the element itself, except the position variants `img.inline` and
41
+ * `button.inline`, which need `ancestors` (outermost first, parent last — `RenderContext.ancestors`): they are
42
+ * reported when the parent holds phrasing content (`p`, headings, `b`, `a` …). Without `ancestors` an element is
43
+ * taken to stand in flow position.
44
+ *
45
+ * Rules: `li.checked` = `checked` is a boolean (task item); `li.nested` = the item contains a `ul`/`ol`;
46
+ * `pre.lang` = non-empty `lang`; `span.color` = a `color` other than `default`; `table.align` = some cell has an
47
+ * `align` other than `left` (left is every platform's default, so dropping it is lossless); `td.block` = the cell
48
+ * holds more than one block or anything but a `<p>`; `button.theme` = a `theme` other than `default`;
49
+ * `input.checkbox` = `type="checkbox"` (a separate platform component where one exists); `select.multiple` = the
50
+ * `multiple` flag (a multi-value picker where one exists). `button` variants start with its `type`, so
51
+ * `type="submit"` asks for `element.button.submit`.
52
+ */
53
+ export function variantsOf<K extends Tag>(el: Element<K>, ancestors?: readonly Element[]): readonly VariantOf<K>[]
54
+ export function variantsOf(el: Element, ancestors?: readonly Element[]): readonly string[] {
55
+ switch (el.type) {
56
+ case 'at': return [el.attrs.type]
57
+ case 'li': {
58
+ const out: string[] = []
59
+ if (typeof el.attrs.checked === 'boolean') out.push('checked')
60
+ if (el.children.some(child => child.type === 'ul' || child.type === 'ol')) out.push('nested')
61
+ return out
62
+ }
63
+ case 'pre': return el.attrs.lang ? ['lang'] : []
64
+ case 'span': return el.attrs.color && el.attrs.color !== 'default' ? ['color'] : []
65
+ case 'table': return hasAlign(el) ? ['align'] : []
66
+ case 'td': return el.children.length > 1 || el.children.some(child => child.type !== 'p') ? ['block'] : []
67
+ case 'img': return isInlinePosition(ancestors) ? ['inline'] : []
68
+ case 'input': return el.attrs.type === 'checkbox' ? ['checkbox'] : []
69
+ case 'select': return el.attrs.multiple ? ['multiple'] : []
70
+ case 'button': {
71
+ const out: string[] = [el.attrs.type]
72
+ if (el.attrs.theme && el.attrs.theme !== 'default') out.push('theme')
73
+ if (isInlinePosition(ancestors)) out.push('inline')
74
+ return out
75
+ }
76
+ default: return []
77
+ }
78
+ }
79
+
80
+ /** Capability keys an element instance needs: its tag key followed by its variant keys. */
81
+ export function keysOf(el: Element, ancestors?: readonly Element[]): ElementKey[] {
82
+ return [variantKey(el.type), ...variantsOf(el, ancestors).map(v => variantKey(el.type, v as never))]
83
+ }