@estiva-app/protocol 0.6.0 → 0.8.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.
package/src/render.ts ADDED
@@ -0,0 +1,203 @@
1
+ /**
2
+ * One tree, whichever content model the body is in — SPEC §13.5.
3
+ *
4
+ * §13.5 asks for a renderer *"safe by construction"*, and the safety is not in
5
+ * a component: it is in never handing an app a string it has to interpret.
6
+ * What this module produces is a fully resolved tree — marks decided, blocks
7
+ * decided, nothing left to parse and nothing to interpolate — so the app's only
8
+ * remaining job is to create elements and set text. An app that maps this tree
9
+ * cannot accidentally render markup, because there is no markup in it.
10
+ *
11
+ * ## Why a tree rather than a shared component
12
+ *
13
+ * Not because the apps use different frameworks — Ship and Peek are both React
14
+ * and already share `@estiva-app/ui`, so a component was possible. Because
15
+ * **how rich text looks is the consumer's**, which is the same rule RFC 0.4
16
+ * §13.1 states for projections — *the owner defines the projection, the
17
+ * consumer decides how it looks* — and SPEC §10's line about apps sharing the
18
+ * wire and never the interpretation. A shared component would make Ship and
19
+ * Peek look alike by construction, which is not a property anybody asked for.
20
+ *
21
+ * So: one parse, one resolution, two designs.
22
+ *
23
+ * ## The three formats, including the one nobody has written yet
24
+ *
25
+ * `toRenderTree` takes the format from `contentFormatOf` in
26
+ * `@estiva-app/interop` — the tag, never the body (§13.4). `'unknown'` is the
27
+ * interesting one: a format declared after this code was written becomes a
28
+ * single unmarked paragraph of the raw value, which §13.5 says is conformant.
29
+ * Handling it here rather than in each consumer is what stops one app deciding
30
+ * to guess.
31
+ */
32
+ import {
33
+ type BodySegment,
34
+ type InlineMark,
35
+ type InlineTextNode,
36
+ parseBodySegments,
37
+ parseInlineMarks,
38
+ } from './content.js'
39
+ import { type Block, type BlockDocument, parseBlockDocument, inlineTextOf } from './blocks.js'
40
+
41
+ /** A run of text and the marks on it. Nothing here needs escaping; it is text. */
42
+ export interface RenderInline {
43
+ text: string
44
+ marks: InlineMark[]
45
+ }
46
+
47
+ /**
48
+ * A resolved block.
49
+ *
50
+ * **A `\n` inside `inline` text is a line break**, in both content models — it
51
+ * is how a marker-text paragraph carries its lines, and it keeps a consumer
52
+ * from needing two rules. Splitting on it is the consumer's whole obligation.
53
+ */
54
+ export interface RenderBlock {
55
+ type:
56
+ | 'paragraph' | 'heading' | 'bulletList' | 'orderedList' | 'listItem'
57
+ | 'blockquote' | 'codeBlock' | 'table' | 'horizontalRule'
58
+ | 'attachment' | 'widget' | 'unknown'
59
+ /** The block's address, from a block document. Marker text has no addressable
60
+ * sub-unit (§13.1), so it is absent — which is the difference that matters. */
61
+ id?: string
62
+ level?: 1 | 2 | 3
63
+ language?: string
64
+ attrs?: Record<string, unknown>
65
+ /** What the document actually called it, when `type` is `'unknown'`. */
66
+ typeName?: string
67
+ inline?: RenderInline[]
68
+ children?: RenderBlock[]
69
+ }
70
+
71
+ /** The content models a body can be in — `contentFormatOf`'s three values. */
72
+ export type RenderFormat = 'marker' | 'blocks' | 'unknown'
73
+
74
+ const KNOWN: ReadonlySet<string> = new Set([
75
+ 'paragraph', 'heading', 'bulletList', 'orderedList', 'listItem',
76
+ 'blockquote', 'codeBlock', 'table', 'horizontalRule', 'attachment', 'widget',
77
+ ])
78
+
79
+ const marksOf = (span: { bold?: boolean; italic?: boolean; underline?: boolean; code?: boolean }): InlineMark[] => {
80
+ const out: InlineMark[] = []
81
+ if (span.bold) out.push('bold')
82
+ if (span.italic) out.push('italic')
83
+ if (span.underline) out.push('underline')
84
+ if (span.code) out.push('code')
85
+ return out
86
+ }
87
+
88
+ const inlineFromMarkers = (text: string): RenderInline[] =>
89
+ parseInlineMarks(text).map((s) => ({ text: s.text, marks: marksOf(s) }))
90
+
91
+ /** One inline run per line, joined by the `\n` the interface documents. */
92
+ const inlineFromLines = (lines: string[]): RenderInline[] => inlineFromMarkers(lines.join('\n'))
93
+
94
+ function blockFromSegment(seg: BodySegment): RenderBlock {
95
+ switch (seg.type) {
96
+ case 'heading':
97
+ return { type: 'heading', level: seg.level, inline: inlineFromMarkers(seg.text) }
98
+ case 'bullet':
99
+ return {
100
+ type: 'bulletList',
101
+ children: seg.items.map((item) => ({ type: 'listItem' as const, inline: inlineFromMarkers(item) })),
102
+ }
103
+ case 'numbered':
104
+ return {
105
+ type: 'orderedList',
106
+ children: seg.items.map((item) => ({ type: 'listItem' as const, inline: inlineFromMarkers(item) })),
107
+ }
108
+ case 'quote':
109
+ return { type: 'blockquote', inline: inlineFromLines(seg.lines) }
110
+ case 'code':
111
+ // A fence is literal by definition — its content is never mark-parsed.
112
+ return {
113
+ type: 'codeBlock',
114
+ ...(seg.language ? { language: seg.language } : {}),
115
+ inline: [{ text: seg.lines.join('\n'), marks: [] }],
116
+ }
117
+ case 'text':
118
+ return { type: 'paragraph', inline: inlineFromLines(seg.lines) }
119
+ }
120
+ }
121
+
122
+ const isInlineRun = (content: unknown): content is InlineTextNode[] =>
123
+ Array.isArray(content) && content.every((n) => typeof n === 'object' && n !== null && (n as { type?: unknown }).type === 'text')
124
+
125
+ function blockFromDocument(block: Block): RenderBlock {
126
+ const known = KNOWN.has(block.type)
127
+ const out: RenderBlock = {
128
+ type: (known ? block.type : 'unknown') as RenderBlock['type'],
129
+ id: block.id,
130
+ ...(known ? {} : { typeName: block.type }),
131
+ ...(block.attrs ? { attrs: block.attrs } : {}),
132
+ }
133
+ const level = block.attrs?.level
134
+ if (block.type === 'heading' && (level === 1 || level === 2 || level === 3)) out.level = level
135
+ const language = block.attrs?.language
136
+ if (block.type === 'codeBlock' && typeof language === 'string') out.language = language
137
+
138
+ if (Array.isArray(block.content)) {
139
+ if (isInlineRun(block.content)) {
140
+ out.inline = block.content.map((node) => ({
141
+ text: node.text,
142
+ marks: (node.marks ?? []).map((m) => m.type),
143
+ }))
144
+ } else {
145
+ out.children = (block.content as Block[]).map(blockFromDocument)
146
+ }
147
+ }
148
+ /*
149
+ §13.3: a reader MUST render an unknown block's inline text and MUST NOT drop
150
+ it. A later version could nest content in a shape this code cannot walk, so
151
+ the fallback reads the text by shape rather than trusting the walk above to
152
+ have found it.
153
+ */
154
+ if (!known && !out.inline && !out.children) {
155
+ const text = inlineTextOf(block)
156
+ if (text) out.inline = [{ text, marks: [] }]
157
+ }
158
+ return out
159
+ }
160
+
161
+ /**
162
+ * The body, resolved.
163
+ *
164
+ * `format` comes from the event's `content-format` tag — `contentFormatOf` in
165
+ * `@estiva-app/interop`. Do not infer it from `value`: §13.4 forbids it, and a
166
+ * legacy description that happens to begin with `{` is the case that proves
167
+ * why.
168
+ *
169
+ * A body in an unparseable state never throws here. A `'blocks'` value that is
170
+ * not a document degrades to one unmarked paragraph — the same outcome as
171
+ * `'unknown'` — because a reader that throws renders nothing at all, and a
172
+ * description that is present is better shown as its own text than as an empty
173
+ * field.
174
+ */
175
+ export function toRenderTree(value: string, format: RenderFormat): RenderBlock[] {
176
+ if (format === 'unknown') return plainParagraph(value)
177
+ if (format === 'blocks') {
178
+ let doc: BlockDocument
179
+ try {
180
+ doc = parseBlockDocument(value)
181
+ } catch {
182
+ return plainParagraph(value)
183
+ }
184
+ return doc.content.map(blockFromDocument)
185
+ }
186
+ return parseBodySegments(value).map(blockFromSegment)
187
+ }
188
+
189
+ function plainParagraph(value: string): RenderBlock[] {
190
+ return value === '' ? [] : [{ type: 'paragraph', inline: [{ text: value, marks: [] }] }]
191
+ }
192
+
193
+ /** Every character a reader would see, for previews and search. */
194
+ export function renderTreeText(blocks: readonly RenderBlock[]): string {
195
+ return blocks
196
+ .map((b) => {
197
+ const own = (b.inline ?? []).map((i) => i.text).join('')
198
+ const kids = b.children ? renderTreeText(b.children) : ''
199
+ return [own, kids].filter((s) => s !== '').join('\n')
200
+ })
201
+ .filter((s) => s !== '')
202
+ .join('\n')
203
+ }