oficina / mapa Public

Clone
git clone https://amadan.net/oficina/mapa

Plain git — no account needed to clone.

Download

Download this file

1// fromMarkdown.mjs — a ProseMirror document from Mapa Markdown, built from
2// markup.mjs's blocks and spans (spec §6.3). Each Mapa block becomes one
3// textblock (or a rule); list items nest exactly as render.go's
4// renderList nests them; and the document always ends in a paragraph,
5// the place the editor keeps to type in (§6.2).
6//
7// Origins and the side table (§6.4) are fidelity.mjs's: options.origin
8// gives the origin for the block at an index of blocks, and it is set on
9// that block's textblock (or rule) as it is made. options.trailing false
10// leaves off the trailing paragraph, for a pasted slice.
11
12import { Mark } from 'prosemirror-model'
13import {
14 parse, plain, spans, words, task, itemSyntax, isDate, isFenceLine,
15 fenceOf, closesFence,
16 Paragraph, Heading, Item, Code, Quote, Rule, Columns, Column, ColumnEnd,
17 InCode, WikiLink, WebLink, Embed, Image
18} from './markup.mjs'
19
20export function fromMarkdown (schema, body, options) {
21 return fromBlocks(schema, parse(body), options)
22}
23
24export function fromBlocks (schema, blocks, options = {}) {
25 const origin = options.origin ?? (() => null)
26 const content = contentFrom(schema, blocks, 0, blocks.length, origin)
27 const last = content[content.length - 1]
28 if (options.trailing !== false &&
29 (!last || last.type !== schema.nodes.paragraph)) {
30 content.push(schema.nodes.paragraph.create())
31 }
32 return schema.nodes.doc.create(null, content)
33}
34
35// contentFrom is the nodes for blocks[from:to]: lists nested as
36// renderList nests them, and a column layout as its columns (columns
37// and icons spec §1.7).
38function contentFrom (schema, blocks, from, to, origin) {
39 const content = []
40 for (let index = from; index < to;) {
41 if (blocks[index].kind === Item) {
42 const [lists, next] = listsFrom(schema, blocks, index, origin, to)
43 content.push(...lists)
44 index = next
45 continue
46 }
47 if (blocks[index].kind === Columns) {
48 const [layout, next] = layoutFrom(schema, blocks, index, origin)
49 content.push(layout)
50 index = next
51 continue
52 }
53 content.push(blockNode(schema, blocks[index], origin(index)))
54 index++
55 }
56 return content
57}
58
59const colons = source => /^[ \t]*(:+)/u.exec(source)[1].length
60
61// layoutFrom is the layout opening at start, and the index after it.
62// An empty column holds the editor's empty paragraph, as Go draws it.
63function layoutFrom (schema, blocks, start, origin) {
64 const columns = []
65 let index = start + 1
66 while (index < blocks.length && blocks[index].kind === Column) {
67 let end = index + 1
68 while (end < blocks.length && blocks[end].kind !== ColumnEnd) end++
69 const inside = contentFrom(schema, blocks, index + 1, end, origin)
70 columns.push(schema.nodes.column.create({
71 fence: colons(blocks[index].source),
72 openOrigin: origin(index),
73 closeOrigin: origin(end)
74 }, inside.length ? inside : [schema.nodes.paragraph.create()]))
75 index = end + 1
76 }
77 const layout = schema.nodes.columns.create({
78 fence: colons(blocks[start].source),
79 openOrigin: origin(start),
80 closeOrigin: origin(index)
81 }, columns)
82 return [layout, index + 1]
83}
84
85function blockNode (schema, block, origin) {
86 const marker = block.marker || null
87 const text = plain(block)
88 switch (block.kind) {
89 case Heading:
90 return schema.nodes.heading.create(
91 { origin, marker, level: block.level, source: block.source },
92 inlineNodes(schema, text))
93 case Code:
94 return codeNode(schema, block, text, origin)
95 case Rule:
96 return schema.nodes.horizontal_rule.create({ origin, source: block.source })
97 case Quote:
98 return schema.nodes.blockquote.create(
99 { marker, prefix: quotePrefixes(block.source) },
100 schema.nodes.paragraph.create({ origin }, inlineNodes(schema, text)))
101 }
102 return schema.nodes.paragraph.create({ origin, marker },
103 inlineNodes(schema, text))
104}
105
106// codeNode keeps every byte of a fence that the text does not: the
107// opening line (fence and info) and, when markup.codeText left it out,
108// the last line (close).
109function codeNode (schema, block, text, origin) {
110 const lines = block.source.split('\n')
111 // dotAll: the info string may hold U+2028 or U+2029, which Go reads as
112 // text and . alone would not match (review M5).
113 const fence = /^( {0,3}(?:`{3,}|~{3,}))(.*)$/su.exec(lines[0])
114 const last = lines[lines.length - 1]
115 return schema.nodes.code_block.create({
116 origin,
117 fence: fence[1],
118 info: fence[2],
119 closed: lines.length > 1 && closesFence(last, fenceOf(lines[0])),
120 close: lines.length > 1 && isFenceLine(last) ? last : null
121 }, text === '' ? null : schema.text(text))
122}
123
124function quotePrefixes (source) {
125 return source.split('\n').map(line => /^ *> ?/u.exec(line)?.[0] ?? '')
126}
127
128// listsFrom is renderList's nesting: depth is min(level, lists open), a
129// level skip nests one deep, and an item of the other kind starts a new
130// list at its depth.
131function listsFrom (schema, blocks, start, origin, to = blocks.length) {
132 const top = []
133 const open = []
134 let index = start
135 for (; index < to && blocks[index].kind === Item; index++) {
136 const block = blocks[index]
137 const depth = Math.min(block.level, open.length)
138 open.length = Math.min(open.length, depth + 1)
139 const kind = block.ordered ? 'ordered_list' : 'bullet_list'
140 if (open.length === depth + 1 && open[depth].kind !== kind) {
141 open.length = depth
142 }
143 if (open.length !== depth + 1) {
144 const list = { kind, items: [] }
145 if (depth === 0) top.push(list)
146 else open[depth - 1].items.at(-1).lists.push(list)
147 open.push(list)
148 }
149 open[depth].items.push({ block, lists: [], origin: origin(index) })
150 }
151 return [top.map(list => listNode(schema, list)), index]
152}
153
154function listNode (schema, list) {
155 return schema.nodes[list.kind].create(null,
156 list.items.map(item => itemNode(schema, item)))
157}
158
159function itemNode (schema, { block, lists, origin }) {
160 const [text, box] = task(plain(block))
161 const attrs = {
162 marker: block.marker || null,
163 ...itemSyntax(block),
164 task: box !== null,
165 checked: box
166 }
167 const paragraph = schema.nodes.paragraph.create({ origin },
168 inlineNodes(schema, text))
169 return schema.nodes.list_item.create(attrs,
170 [paragraph, ...lists.map(list => listNode(schema, list))])
171}
172
173// inlineNodes is a block's inline text as nodes: text with marks, hard
174// breaks, and atoms.
175export function inlineNodes (schema, text) {
176 const out = []
177 for (const span of spans(text)) {
178 switch (span.kind) {
179 case InCode:
180 out.push(schema.text(span.text, [schema.marks.code.create()]))
181 break
182 case WebLink:
183 out.push(schema.text(span.text, [schema.marks.link.create({
184 href: span.url, bare: !span.source.startsWith('[')
185 })]))
186 break
187 case WikiLink:
188 out.push(linkNode(schema, span))
189 break
190 case Embed:
191 out.push(schema.nodes.embed.create({
192 ref: span.text.slice(3, -2), source: span.source
193 }))
194 break
195 case Image:
196 out.push(schema.nodes.image.create({
197 id: span.target, alt: span.text, source: span.source
198 }))
199 break
200 default:
201 out.push(...wordNodes(schema, span.text))
202 }
203 }
204 return out
205}
206
207function linkNode (schema, span) {
208 const attrs = { anchor: span.anchor, shown: span.text, source: span.source }
209 if (isDate(span.target)) {
210 return schema.nodes.datelink.create({ ...attrs, date: span.target })
211 }
212 return schema.nodes.wikilink.create({ ...attrs, target: span.target })
213}
214
215function wordNodes (schema, text) {
216 return words(text).map(run => {
217 const marks = Mark.setFrom([
218 ...(run.em ? [schema.marks.em.create()] : []),
219 ...(run.strong ? [schema.marks.strong.create()] : [])
220 ])
221 if (run.kind === 'break') {
222 return schema.nodes.hard_break.create({ indent: run.indent }, null,
223 marks)
224 }
225 return schema.text(run.text, marks)
226 })
227}
228