oficina / mapa Public

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

Plain git — no account needed to clone.

Download

Download this file

1// markup.mjs — a port of internal/mapa/markup's blocks.go and spans.go,
2// and of the emphasis passes in inline.go. It must give exactly what Go
3// gives (spec §6.1, gate L4: parity.test.mjs holds it to Go's golden
4// file), so it mirrors Go line for line, and spells out the places where
5// JavaScript and Go disagree (spec §6.4, "Parity hazards"):
6//
7// - Go's RE2 \s is [\t\n\f\r ] and \S its complement; JavaScript's are
8// Unicode-wide. Every class here is spelled out in ASCII.
9// - strings.TrimSpace trims unicode.IsSpace: U+0085 yes, U+FEFF no.
10// String.prototype.trim is the other way round. goTrimSpace is Go's.
11// - Start and End are UTF-8 byte offsets, as Go's are.
12// - A list item's level counts a tab as four spaces.
13// - Emphasis runs over HTML-escaped text, as Go's does.
14//
15// The regular expressions carry the u flag, so a class matches a code
16// point, as RE2 matches a rune.
17
18import { safeURL, linkAddress, MAX_ADDRESS } from './safeurl.mjs'
19
20export { safeURL }
21
22export const Paragraph = 'paragraph'
23export const Heading = 'heading'
24export const Item = 'item'
25export const Code = 'code'
26export const Quote = 'quote'
27export const Rule = 'rule'
28
29// The column layout's fence kinds (columns and icons spec §1.4), and
30// the block grammar's version (D17), markup.Grammar.
31export const Columns = 'columns'
32export const Column = 'column'
33export const ColumnEnd = 'column_end'
34export const ColumnsEnd = 'columns_end'
35export const Grammar = 2
36
37export const Text = 'text'
38export const InCode = 'code'
39export const WikiLink = 'wiki'
40export const WebLink = 'web'
41export const Embed = 'embed'
42export const Image = 'image'
43
44// MaxAlt is markup.MaxAlt: the longest alt text, in bytes of UTF-8.
45export const MaxAlt = 1000
46export const ImagePrefix = '/i/'
47const imageID = /^[0-9a-z]{1,13}$/u
48
49// isImageID is markup.IsImageID.
50export function isImageID (id) { return imageID.test(id) }
51
52const S = '[^\\t\\n\\f\\r ]' // RE2's \S
53const headingLine = new RegExp(`^(#{1,6})[ \\t]+${S}`, 'u')
54const itemLine = /^([ \t]*)([-*+]|[0-9]{1,9}[.)])[ \t]+/u
55const fenceLine = /^ {0,3}(```|~~~)/u
56const ruleLine =
57 /^ {0,3}(?:(?:-[ \t]*){3,}|(?:\*[ \t]*){3,}|(?:_[ \t]*){3,})$/u
58const markerTail = /[ \t]\^([A-Za-z0-9-]{1,40})[ \t]*$/u
59const autoLink =
60 /^https?:\/\/[^\t\n\f\r <>()[\]]+[^\t\n\f\r <>()[\].,;:!?'"]/u
61const isoDate = /^[0-9]{4}-[0-9]{2}-[0-9]{2}$/u
62const taskBox = /^\[([ xX])\][ \t]+/u
63
64// unicode.IsSpace.
65const goSpace =
66 /[\t\n\v\f\r \u0085\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000]/u
67
68export function goTrimSpace (text) {
69 let start = 0
70 let end = text.length
71 while (start < end && goSpace.test(text[start])) start++
72 while (end > start && goSpace.test(text[end - 1])) end--
73 return text.slice(start, end)
74}
75
76// trimLeft is strings.TrimLeft with an ASCII cutset.
77function trimLeft (text, cutset) {
78 let start = 0
79 while (start < text.length && cutset.includes(text[start])) start++
80 return text.slice(start)
81}
82
83// utf8Length is len() of a Go string holding text.
84export function utf8Length (text) {
85 let length = 0
86 for (const char of text) {
87 const point = char.codePointAt(0)
88 length += point < 0x80 ? 1 : point < 0x800 ? 2 : point < 0x10000 ? 3 : 4
89 }
90 return length
91}
92
93// cleanBody is the one rule for a stored body (internal/mapa/pages.go):
94// "\n" line endings, and no trailing spaces, tabs or newlines. A loop,
95// not /[ \t\n]+$/: that regex tries every run of spaces to the end, and
96// took ten seconds over 80,000 of them (review M6).
97export function cleanBody (body) {
98 const text = normalise(body)
99 let end = text.length
100 while (end > 0 && ' \t\n'.includes(text[end - 1])) end--
101 return text.slice(0, end)
102}
103
104export function normalise (body) {
105 return body.replaceAll('\r\n', '\n').replaceAll('\r', '\n')
106}
107
108// parse is markup.Parse: blank lines separate blocks and belong to none.
109export function parse (body) {
110 const lines = normalise(body).split('\n')
111 const offsets = [0]
112 const indexes = [0]
113 for (const line of lines) {
114 offsets.push(offsets[offsets.length - 1] + utf8Length(line) + 1)
115 indexes.push(indexes[indexes.length - 1] + line.length + 1)
116 }
117 return parseLines(lines, offsets, indexes, 0, lines.length, layouts(lines))
118}
119
120// parseLines is markup.parseLines: lines[from:to], every offset the
121// body's own; found is the whole column layouts by their opener's line.
122function parseLines (lines, offsets, indexes, from, to, found) {
123 const view = lines.slice(0, to)
124 const blocks = []
125 for (let index = from; index < to;) {
126 if (goTrimSpace(view[index]) === '') {
127 index++
128 continue
129 }
130 const whole = found?.get(index)
131 if (whole) {
132 blocks.push(...parseLayout(lines, offsets, indexes, whole))
133 index = whole.close + 1
134 continue
135 }
136 const [block, next] = parseBlock(view, index)
137 block.marker = marker(block)
138 block.start = offsets[index]
139 block.end = block.start + utf8Length(block.source)
140 // from and to are the same offsets in JavaScript's UTF-16 units, into
141 // the normalised body, for the editor's own slicing (fidelity.mjs).
142 block.from = indexes[index]
143 block.to = block.from + block.source.length
144 block.column = 0
145 blocks.push(block)
146 index = next
147 }
148 return blocks
149}
150
151const layoutOpener = /^(:{4,})[ \t]+columns[ \t]*$/u
152const columnOpener = /^(:{3,})[ \t]+column[ \t]*$/u
153const fenceLike = /^[ \t]*:::/u
154
155// fenceLike is markup.FenceLike: a line whose text, after any spaces and
156// tabs, starts with ":::".
157export function isFenceLike (line) { return fenceLike.test(line) }
158
159// isFence is markup.IsFence.
160export function isFence (kind) {
161 return kind === Columns || kind === Column || kind === ColumnEnd ||
162 kind === ColumnsEnd
163}
164
165function closesWith (line, colons) {
166 const trimmed = line.replace(/[ \t]+$/u, '')
167 return trimmed.length === colons && /^:+$/u.test(trimmed)
168}
169
170const blank = line => goTrimSpace(line) === ''
171
172// layouts is markup.layouts: the scan, exactly (spec §1.1).
173function layouts (lines) {
174 const found = new Map()
175 let fence = ''
176 for (let index = 0; index < lines.length; index++) {
177 const line = lines[index]
178 if (fence !== '') {
179 if (closesFence(line, fence)) fence = ''
180 continue
181 }
182 const opened = fenceLine.exec(line)
183 if (opened) {
184 fence = opened[1]
185 continue
186 }
187 if (index > 0 && !blank(lines[index - 1])) continue
188 const whole = readLayout(lines, index)
189 if (whole) {
190 found.set(index, whole)
191 index = whole.close
192 }
193 }
194 return found
195}
196
197function readLayout (lines, start) {
198 const match = layoutOpener.exec(lines[start])
199 if (!match) return null
200 const outer = match[1].length
201 const whole = { open: start, close: 0, columns: [] }
202 for (let at = skipBlank(lines, start + 1); at < lines.length;) {
203 const line = lines[at]
204 if (closesWith(line, outer)) {
205 const ends = at + 1 === lines.length || blank(lines[at + 1])
206 const count = whole.columns.length
207 whole.close = at
208 return ends && count >= 2 && count <= 4 ? whole : null
209 }
210 const inner = columnOpener.exec(line)
211 if (!inner || inner[1].length >= outer || whole.columns.length === 4) {
212 return null
213 }
214 const end = columnEnd(lines, at + 1, inner[1].length)
215 if (end < 0) return null
216 whole.columns.push([at, end])
217 at = skipBlank(lines, end + 1)
218 }
219 return null
220}
221
222function columnEnd (lines, start, colons) {
223 let fence = ''
224 for (let at = start; at < lines.length; at++) {
225 const line = lines[at]
226 if (fence !== '') {
227 if (closesFence(line, fence)) fence = ''
228 } else if (fenceLine.test(line)) {
229 fence = fenceLine.exec(line)[1]
230 } else if (closesWith(line, colons)) {
231 return at
232 } else if (fenceLike.test(line)) {
233 return -1
234 }
235 }
236 return -1
237}
238
239function skipBlank (lines, at) {
240 while (at < lines.length && blank(lines[at])) at++
241 return at
242}
243
244function fenceBlock (kind, lines, offsets, indexes, line, column) {
245 const made = block(kind, lines[line], { column })
246 made.start = offsets[line]
247 made.end = made.start + utf8Length(made.source)
248 made.from = indexes[line]
249 made.to = made.from + made.source.length
250 return made
251}
252
253function parseLayout (lines, offsets, indexes, whole) {
254 const opener = fenceBlock(Columns, lines, offsets, indexes, whole.open, 0)
255 opener.level = whole.columns.length
256 const blocks = [opener]
257 whole.columns.forEach(([open, close], number) => {
258 const column = number + 1
259 blocks.push(fenceBlock(Column, lines, offsets, indexes, open, column))
260 for (const inside of parseLines(lines, offsets, indexes, open + 1, close, null)) {
261 inside.column = column
262 blocks.push(inside)
263 }
264 blocks.push(fenceBlock(ColumnEnd, lines, offsets, indexes, close, column))
265 })
266 blocks.push(fenceBlock(ColumnsEnd, lines, offsets, indexes, whole.close, 0))
267 return blocks
268}
269
270function block (kind, source, extra = {}) {
271 return { kind, source, level: 0, ordered: false, marker: '', column: 0, ...extra }
272}
273
274function parseBlock (lines, start) {
275 const line = lines[start]
276 if (fenceLine.test(line)) return parseFence(lines, start)
277 const heading = headingLine.exec(line)
278 if (heading) {
279 return [block(Heading, line, { level: heading[1].length }), start + 1]
280 }
281 if (ruleLine.test(line)) return [block(Rule, line), start + 1]
282 if (itemLine.test(line)) return parseItem(lines, start)
283 if (isQuoteLine(line)) return parseRun(lines, start, Quote, isQuoteLine)
284 return parseRun(lines, start, Paragraph, continuesParagraph)
285}
286
287function parseFence (lines, start) {
288 const fence = fenceLine.exec(lines[start])[1]
289 let end = start + 1
290 while (end < lines.length && !trimLeft(lines[end], ' ').startsWith(fence)) {
291 end++
292 }
293 if (end < lines.length) end++ // the closing fence belongs to the block
294 return [block(Code, lines.slice(start, end).join('\n')), end]
295}
296
297function parseItem (lines, start) {
298 const match = itemLine.exec(lines[start])
299 const indent = match[1].replaceAll('\t', ' ')
300 let end = start + 1
301 while (end < lines.length && continuesParagraph(lines[end])) end++
302 return [block(Item, lines.slice(start, end).join('\n'), {
303 level: Math.floor(indent.length / 2),
304 ordered: !/[-*+]/u.test(match[2])
305 }), end]
306}
307
308function parseRun (lines, start, kind, keeps) {
309 let end = start + 1
310 while (end < lines.length && keeps(lines[end])) end++
311 return [block(kind, lines.slice(start, end).join('\n')), end]
312}
313
314function isQuoteLine (line) {
315 return trimLeft(line, ' ').startsWith('>')
316}
317
318function continuesParagraph (line) {
319 return goTrimSpace(line) !== '' && !startsBlock(line)
320}
321
322function startsBlock (line) {
323 return fenceLine.test(line) || headingLine.test(line) ||
324 ruleLine.test(line) || itemLine.test(line) || isQuoteLine(line)
325}
326
327function marker (block) {
328 if (block.kind === Code || block.kind === Rule || isFence(block.kind)) return ''
329 const last = block.source.slice(block.source.lastIndexOf('\n') + 1)
330 const match = markerTail.exec(last)
331 return match ? match[1] : ''
332}
333
334// plain is markup.Plain (and Strip): a block's words without its syntax.
335export function plain (block) {
336 let text = block.source
337 if (isFence(block.kind)) return ''
338 switch (block.kind) {
339 case Code: return codeText(text)
340 case Heading: text = trimLeft(text, '# \t'); break
341 case Item: text = text.replace(itemLine, ''); break
342 case Quote: text = quoteText(text); break
343 }
344 if (block.marker !== '') text = text.replace(markerTail, '')
345 return text
346}
347
348export function codeText (source) {
349 let lines = source.split('\n')
350 if (lines.length <= 1) return ''
351 if (fenceLine.test(lines[lines.length - 1])) lines = lines.slice(0, -1)
352 return lines.slice(1).join('\n')
353}
354
355function quoteText (source) {
356 return source.split('\n').map(line => {
357 line = trimLeft(line, ' ')
358 if (line.startsWith('>')) line = line.slice(1)
359 return line.startsWith(' ') ? line.slice(1) : line
360 }).join('\n')
361}
362
363// itemSyntax is what a list item keeps for fidelity (spec §6.3): its
364// exact indent, its bullet or number and delimiter, and its task box.
365export function itemSyntax (block) {
366 const match = itemLine.exec(block.source)
367 const syntax = { indent: match[1], bullet: null, number: null, delim: null }
368 if (block.ordered) {
369 syntax.number = match[2].slice(0, -1)
370 syntax.delim = match[2].slice(-1)
371 } else {
372 syntax.bullet = match[2]
373 }
374 return syntax
375}
376
377// task splits a list item's text from its box: [text, null | ' ' | 'x'].
378export function task (text) {
379 const match = taskBox.exec(text)
380 if (!match) return [text, null]
381 return [text.slice(match[0].length), match[1]]
382}
383
384// spans is markup.Spans: a block's inline text as runs.
385export function spans (text) {
386 const scan = new Scan(text)
387 const out = []
388 let run = ''
389 const flush = () => {
390 if (run !== '') out.push(span(Text, { text: run, source: run }))
391 run = ''
392 }
393 for (let index = 0; index < text.length;) {
394 const [found, width] = spanAt(scan, index)
395 if (width === 0) {
396 run += text[index]
397 index++
398 continue
399 }
400 flush()
401 found.source = text.slice(index, index + width)
402 out.push(found)
403 index += width
404 }
405 flush()
406 return out
407}
408
409function span (kind, fields) {
410 return {
411 kind, text: '', target: '', anchor: '', url: '', source: '', ...fields
412 }
413}
414
415// Scan is one text's tables for the link tests, each built in one pass
416// on first use: next(name, at) is the first index at or after at where
417// the named test holds, or -1. With them a link test costs the same
418// wherever it starts; scanning from each [ for its ] or ]] was quadratic,
419// seconds over a line of [a (review M6). They answer exactly what Go's
420// scans (spans.go) answer.
421class Scan {
422 constructor (text) {
423 this.text = text
424 this.tables = {}
425 }
426
427 next (name, at) {
428 if (at >= this.text.length) return -1
429 this.tables[name] ??= nextTable(this.text, stops[name])
430 return this.tables[name][at]
431 }
432}
433
434const stops = {
435 // A web link's text ends at the first ] or line end, its address at
436 // the first ), space or line end: [^\]\n]+ and [^)\t\n\f\r ]+.
437 label: (text, at) => text[at] === ']' || text[at] === '\n',
438 address: (text, at) => ')\t\n\f\r '.includes(text[at]),
439 // A wiki link ends at the first ]], unless a [ or a line end is first.
440 close: (text, at) => text[at] === ']' && text[at + 1] === ']',
441 open: (text, at) => text[at] === '[' || text[at] === '\n'
442}
443
444function nextTable (text, stop) {
445 const table = new Int32Array(text.length)
446 let next = -1
447 for (let at = text.length - 1; at >= 0; at--) {
448 if (stop(text, at)) next = at
449 table[at] = next
450 }
451 return table
452}
453
454function spanAt (scan, index) {
455 const text = scan.text
456 if (text[index] === '`') return codeSpan(text.slice(index))
457 if (text.startsWith('![[', index)) {
458 const end = closing(scan, index + 3)
459 if (end >= 0) return [span(Embed, { text: text.slice(index, index + end + 5) }), end + 5]
460 } else if (text.startsWith('![', index)) {
461 return imageSpan(scan, index)
462 } else if (text.startsWith('[[', index)) {
463 return wikiSpan(scan, index)
464 } else if (text[index] === '[') {
465 const match = webLinkAt(scan, index)
466 if (match && linkAddress(match.url)) {
467 return [span(WebLink, { text: match.text, url: match.url }), match.width]
468 }
469 } else if (text[index] === 'h' && wordStart(text, index)) {
470 const match = autoLink.exec(text.slice(index))
471 if (match) return [span(WebLink, { text: match[0], url: match[0] }), match[0].length]
472 }
473 return [null, 0]
474}
475
476// webLinkAt is /^\[([^\]\n]+)\]\(([^)\t\n\f\r ]+)\)/ at index: neither
477// class holds the character that ends it, so there is one way to match.
478function webLinkAt (scan, index) {
479 const text = scan.text
480 const label = scan.next('label', index + 1)
481 if (label <= index + 1 || text[label] !== ']' || text[label + 1] !== '(') return null
482 const address = scan.next('address', label + 2)
483 if (address <= label + 2 || text[address] !== ')') return null
484 // Longer than MAX_ADDRESS in UTF-16 units is longer in UTF-8 bytes
485 // too: refused before the slice, which would be linear per [.
486 if (address - (label + 2) > MAX_ADDRESS) return null
487 return {
488 text: text.slice(index + 1, label),
489 url: text.slice(label + 2, address),
490 width: address + 1 - index
491 }
492}
493
494// imageSpan is markup's imageSpan: ![alt](/i/id) at index, where alt
495// holds no [, ] or line break and at most MaxAlt bytes.
496function imageSpan (scan, index) {
497 const text = scan.text
498 const end = scan.next('label', index + 2)
499 // More than MaxAlt UTF-16 units is more than MaxAlt bytes: refused
500 // before the slice, which made "![a" repeated quadratic (Fable round
501 // 3, L8).
502 if (end < 0 || text[end] !== ']' || text[end + 1] !== '(' ||
503 end - (index + 2) > MaxAlt ||
504 utf8Length(text.slice(index + 2, end)) > MaxAlt) return [null, 0]
505 const open = scan.next('open', index + 2)
506 if (open >= 0 && open < end) return [null, 0]
507 const closer = scan.next('address', end + 2)
508 if (closer < 0 || text[closer] !== ')') return [null, 0]
509 const address = text.slice(end + 2, closer)
510 if (!address.startsWith(ImagePrefix)) return [null, 0]
511 const id = address.slice(ImagePrefix.length)
512 if (!isImageID(id)) return [null, 0]
513 return [span(Image, { text: text.slice(index + 2, end), target: id, url: address }),
514 closer + 1 - index]
515}
516
517function codeSpan (rest) {
518 const end = rest.slice(1).indexOf('`')
519 if (end <= 0) return [null, 0]
520 return [span(InCode, { text: rest.slice(1, end + 1) }), end + 2]
521}
522
523function cut (text, separator) {
524 const at = text.indexOf(separator)
525 return at < 0 ? [text, ''] : [text.slice(0, at), text.slice(at + 1)]
526}
527
528function wikiSpan (scan, index) {
529 const end = closing(scan, index + 2)
530 if (end < 0) return [null, 0]
531 const inner = scan.text.slice(index + 2, index + end + 2)
532 let [target, shown] = cut(inner, '|')
533 let anchor
534 ;[target, anchor] = cut(target, '#')
535 target = goTrimSpace(target)
536 if (target === '') return [null, 0]
537 const found = span(WikiLink, { target, text: goTrimSpace(shown) })
538 if (anchor.startsWith('^')) found.anchor = goTrimSpace(anchor.slice(1))
539 return [found, end + 4]
540}
541
542// closing is how far from at the first ]] is, or -1 when there is none
543// or a [ or a line end comes before it.
544function closing (scan, at) {
545 const end = scan.next('close', at)
546 if (end < 0) return -1
547 const open = scan.next('open', at)
548 if (open >= 0 && open < end) return -1
549 return end - at
550}
551
552function wordStart (text, index) {
553 return index === 0 || ' \t\n('.includes(text[index - 1])
554}
555
556export function isDateShaped (text) { return isoDate.test(text) }
557
558// The block tests the serialiser needs, exactly as parse applies them.
559export function isFenceLine (line) { return fenceLine.test(line) }
560export function isRuleLine (line) { return ruleLine.test(line) }
561export function fenceOf (line) { return fenceLine.exec(line)?.[1] ?? null }
562
563// closesFence is parseFence's test for a closing line.
564export function closesFence (line, fence) {
565 return trimLeft(line, ' ').startsWith(fence)
566}
567
568// isDate is time.Parse(time.DateOnly): a real day in the Gregorian
569// calendar, year 0000 to 9999.
570export function isDate (text) {
571 if (!isDateShaped(text)) return false
572 const [year, month, day] = text.split('-').map(Number)
573 if (month < 1 || month > 12 || day < 1) return false
574 const leap = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0)
575 const days = [31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
576 return day <= days[month - 1]
577}
578
579// The emphasis passes (inline.go's words), over escaped text.
580const tripleStar = new RegExp(`\\*\\*\\*(${S}(?:[^*]*?${S})?)\\*\\*\\*`, 'gu')
581const strong = new RegExp(`\\*\\*(${S}(?:[^*]*?${S})?)\\*\\*`, 'gu')
582const emphasis = new RegExp(`\\*(${S}(?:[^*]*?${S})?)\\*`, 'gu')
583const markTag = /<\/?(?:em|strong)>/gu
584const lineBreak = /\n[ \t]*/gu
585
586// escapeHTML is html.EscapeString.
587export function escapeHTML (text) {
588 return text.replace(/[&'<>"]/gu, char => ({
589 '&': '&amp;', "'": '&#39;', '<': '&lt;', '>': '&gt;', '"': '&#34;'
590 })[char])
591}
592
593export function unescapeHTML (text) {
594 return text.replace(/&(?:amp|#39|lt|gt|#34);/gu, entity => ({
595 '&amp;': '&', '&#39;': "'", '&lt;': '<', '&gt;': '>', '&#34;': '"'
596 })[entity])
597}
598
599// words is a text run as the editor holds it: text runs and hard breaks,
600// each with em and strong. A break carries the next line's indent, which
601// is kept in the source and not shown.
602export function words (text) {
603 let tagged = escapeHTML(text)
604 tagged = tagged.replace(tripleStar, '<em><strong>$1</strong></em>')
605 tagged = tagged.replace(strong, '<strong>$1</strong>')
606 tagged = tagged.replace(emphasis, '<em>$1</em>')
607 const runs = []
608 let ems = 0
609 let strongs = 0
610 let cursor = 0
611 for (const match of tagged.matchAll(markTag)) {
612 lines(runs, tagged.slice(cursor, match.index), ems > 0, strongs > 0)
613 const step = match[0][1] === '/' ? -1 : 1
614 if (match[0].endsWith('em>')) ems += step
615 else strongs += step
616 cursor = match.index + match[0].length
617 }
618 lines(runs, tagged.slice(cursor), ems > 0, strongs > 0)
619 return runs
620}
621
622function lines (runs, escaped, em, strong) {
623 let cursor = 0
624 for (const match of escaped.matchAll(lineBreak)) {
625 pushText(runs, escaped.slice(cursor, match.index), em, strong)
626 runs.push({ kind: 'break', indent: match[0].slice(1), em, strong })
627 cursor = match.index + match[0].length
628 }
629 pushText(runs, escaped.slice(cursor), em, strong)
630}
631
632function pushText (runs, escaped, em, strong) {
633 if (escaped !== '') {
634 runs.push({ kind: 'text', text: unescapeHTML(escaped), em, strong })
635 }
636}
637