// markup.mjs — a port of internal/mapa/markup's blocks.go and spans.go,
// and of the emphasis passes in inline.go. It must give exactly what Go
// gives (spec §6.1, gate L4: parity.test.mjs holds it to Go's golden
// file), so it mirrors Go line for line, and spells out the places where
// JavaScript and Go disagree (spec §6.4, "Parity hazards"):
//
// - Go's RE2 \s is [\t\n\f\r ] and \S its complement; JavaScript's are
// Unicode-wide. Every class here is spelled out in ASCII.
// - strings.TrimSpace trims unicode.IsSpace: U+0085 yes, U+FEFF no.
// String.prototype.trim is the other way round. goTrimSpace is Go's.
// - Start and End are UTF-8 byte offsets, as Go's are.
// - A list item's level counts a tab as four spaces.
// - Emphasis runs over HTML-escaped text, as Go's does.
//
// The regular expressions carry the u flag, so a class matches a code
// point, as RE2 matches a rune.
import { safeURL, linkAddress, MAX_ADDRESS } from './safeurl.mjs'
export { safeURL }
export const Paragraph = 'paragraph'
export const Heading = 'heading'
export const Item = 'item'
export const Code = 'code'
export const Quote = 'quote'
export const Rule = 'rule'
// The column layout's fence kinds (columns and icons spec §1.4), and
// the block grammar's version (D17), markup.Grammar.
export const Columns = 'columns'
export const Column = 'column'
export const ColumnEnd = 'column_end'
export const ColumnsEnd = 'columns_end'
export const Grammar = 2
export const Text = 'text'
export const InCode = 'code'
export const WikiLink = 'wiki'
export const WebLink = 'web'
export const Embed = 'embed'
export const Image = 'image'
// MaxAlt is markup.MaxAlt: the longest alt text, in bytes of UTF-8.
export const MaxAlt = 1000
export const ImagePrefix = '/i/'
const imageID = /^[0-9a-z]{1,13}$/u
// isImageID is markup.IsImageID.
export function isImageID (id) { return imageID.test(id) }
const S = '[^\\t\\n\\f\\r ]' // RE2's \S
const headingLine = new RegExp(`^(#{1,6})[ \\t]+${S}`, 'u')
const itemLine = /^([ \t]*)([-*+]|[0-9]{1,9}[.)])[ \t]+/u
const fenceLine = /^ {0,3}(```|~~~)/u
const ruleLine =
/^ {0,3}(?:(?:-[ \t]*){3,}|(?:\*[ \t]*){3,}|(?:_[ \t]*){3,})$/u
const markerTail = /[ \t]\^([A-Za-z0-9-]{1,40})[ \t]*$/u
const autoLink =
/^https?:\/\/[^\t\n\f\r <>()[\]]+[^\t\n\f\r <>()[\].,;:!?'"]/u
const isoDate = /^[0-9]{4}-[0-9]{2}-[0-9]{2}$/u
const taskBox = /^\[([ xX])\][ \t]+/u
// unicode.IsSpace.
const goSpace =
/[\t\n\v\f\r \u0085\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000]/u
export function goTrimSpace (text) {
let start = 0
let end = text.length
while (start < end && goSpace.test(text[start])) start++
while (end > start && goSpace.test(text[end - 1])) end--
return text.slice(start, end)
}
// trimLeft is strings.TrimLeft with an ASCII cutset.
function trimLeft (text, cutset) {
let start = 0
while (start < text.length && cutset.includes(text[start])) start++
return text.slice(start)
}
// utf8Length is len() of a Go string holding text.
export function utf8Length (text) {
let length = 0
for (const char of text) {
const point = char.codePointAt(0)
length += point < 0x80 ? 1 : point < 0x800 ? 2 : point < 0x10000 ? 3 : 4
}
return length
}
// cleanBody is the one rule for a stored body (internal/mapa/pages.go):
// "\n" line endings, and no trailing spaces, tabs or newlines. A loop,
// not /[ \t\n]+$/: that regex tries every run of spaces to the end, and
// took ten seconds over 80,000 of them (review M6).
export function cleanBody (body) {
const text = normalise(body)
let end = text.length
while (end > 0 && ' \t\n'.includes(text[end - 1])) end--
return text.slice(0, end)
}
export function normalise (body) {
return body.replaceAll('\r\n', '\n').replaceAll('\r', '\n')
}
// parse is markup.Parse: blank lines separate blocks and belong to none.
export function parse (body) {
const lines = normalise(body).split('\n')
const offsets = [0]
const indexes = [0]
for (const line of lines) {
offsets.push(offsets[offsets.length - 1] + utf8Length(line) + 1)
indexes.push(indexes[indexes.length - 1] + line.length + 1)
}
return parseLines(lines, offsets, indexes, 0, lines.length, layouts(lines))
}
// parseLines is markup.parseLines: lines[from:to], every offset the
// body's own; found is the whole column layouts by their opener's line.
function parseLines (lines, offsets, indexes, from, to, found) {
const view = lines.slice(0, to)
const blocks = []
for (let index = from; index < to;) {
if (goTrimSpace(view[index]) === '') {
index++
continue
}
const whole = found?.get(index)
if (whole) {
blocks.push(...parseLayout(lines, offsets, indexes, whole))
index = whole.close + 1
continue
}
const [block, next] = parseBlock(view, index)
block.marker = marker(block)
block.start = offsets[index]
block.end = block.start + utf8Length(block.source)
// from and to are the same offsets in JavaScript's UTF-16 units, into
// the normalised body, for the editor's own slicing (fidelity.mjs).
block.from = indexes[index]
block.to = block.from + block.source.length
block.column = 0
blocks.push(block)
index = next
}
return blocks
}
const layoutOpener = /^(:{4,})[ \t]+columns[ \t]*$/u
const columnOpener = /^(:{3,})[ \t]+column[ \t]*$/u
const fenceLike = /^[ \t]*:::/u
// fenceLike is markup.FenceLike: a line whose text, after any spaces and
// tabs, starts with ":::".
export function isFenceLike (line) { return fenceLike.test(line) }
// isFence is markup.IsFence.
export function isFence (kind) {
return kind === Columns || kind === Column || kind === ColumnEnd ||
kind === ColumnsEnd
}
function closesWith (line, colons) {
const trimmed = line.replace(/[ \t]+$/u, '')
return trimmed.length === colons && /^:+$/u.test(trimmed)
}
const blank = line => goTrimSpace(line) === ''
// layouts is markup.layouts: the scan, exactly (spec §1.1).
function layouts (lines) {
const found = new Map()
let fence = ''
for (let index = 0; index < lines.length; index++) {
const line = lines[index]
if (fence !== '') {
if (closesFence(line, fence)) fence = ''
continue
}
const opened = fenceLine.exec(line)
if (opened) {
fence = opened[1]
continue
}
if (index > 0 && !blank(lines[index - 1])) continue
const whole = readLayout(lines, index)
if (whole) {
found.set(index, whole)
index = whole.close
}
}
return found
}
function readLayout (lines, start) {
const match = layoutOpener.exec(lines[start])
if (!match) return null
const outer = match[1].length
const whole = { open: start, close: 0, columns: [] }
for (let at = skipBlank(lines, start + 1); at < lines.length;) {
const line = lines[at]
if (closesWith(line, outer)) {
const ends = at + 1 === lines.length || blank(lines[at + 1])
const count = whole.columns.length
whole.close = at
return ends && count >= 2 && count <= 4 ? whole : null
}
const inner = columnOpener.exec(line)
if (!inner || inner[1].length >= outer || whole.columns.length === 4) {
return null
}
const end = columnEnd(lines, at + 1, inner[1].length)
if (end < 0) return null
whole.columns.push([at, end])
at = skipBlank(lines, end + 1)
}
return null
}
function columnEnd (lines, start, colons) {
let fence = ''
for (let at = start; at < lines.length; at++) {
const line = lines[at]
if (fence !== '') {
if (closesFence(line, fence)) fence = ''
} else if (fenceLine.test(line)) {
fence = fenceLine.exec(line)[1]
} else if (closesWith(line, colons)) {
return at
} else if (fenceLike.test(line)) {
return -1
}
}
return -1
}
function skipBlank (lines, at) {
while (at < lines.length && blank(lines[at])) at++
return at
}
function fenceBlock (kind, lines, offsets, indexes, line, column) {
const made = block(kind, lines[line], { column })
made.start = offsets[line]
made.end = made.start + utf8Length(made.source)
made.from = indexes[line]
made.to = made.from + made.source.length
return made
}
function parseLayout (lines, offsets, indexes, whole) {
const opener = fenceBlock(Columns, lines, offsets, indexes, whole.open, 0)
opener.level = whole.columns.length
const blocks = [opener]
whole.columns.forEach(([open, close], number) => {
const column = number + 1
blocks.push(fenceBlock(Column, lines, offsets, indexes, open, column))
for (const inside of parseLines(lines, offsets, indexes, open + 1, close, null)) {
inside.column = column
blocks.push(inside)
}
blocks.push(fenceBlock(ColumnEnd, lines, offsets, indexes, close, column))
})
blocks.push(fenceBlock(ColumnsEnd, lines, offsets, indexes, whole.close, 0))
return blocks
}
function block (kind, source, extra = {}) {
return { kind, source, level: 0, ordered: false, marker: '', column: 0, ...extra }
}
function parseBlock (lines, start) {
const line = lines[start]
if (fenceLine.test(line)) return parseFence(lines, start)
const heading = headingLine.exec(line)
if (heading) {
return [block(Heading, line, { level: heading[1].length }), start + 1]
}
if (ruleLine.test(line)) return [block(Rule, line), start + 1]
if (itemLine.test(line)) return parseItem(lines, start)
if (isQuoteLine(line)) return parseRun(lines, start, Quote, isQuoteLine)
return parseRun(lines, start, Paragraph, continuesParagraph)
}
function parseFence (lines, start) {
const fence = fenceLine.exec(lines[start])[1]
let end = start + 1
while (end < lines.length && !trimLeft(lines[end], ' ').startsWith(fence)) {
end++
}
if (end < lines.length) end++ // the closing fence belongs to the block
return [block(Code, lines.slice(start, end).join('\n')), end]
}
function parseItem (lines, start) {
const match = itemLine.exec(lines[start])
const indent = match[1].replaceAll('\t', ' ')
let end = start + 1
while (end < lines.length && continuesParagraph(lines[end])) end++
return [block(Item, lines.slice(start, end).join('\n'), {
level: Math.floor(indent.length / 2),
ordered: !/[-*+]/u.test(match[2])
}), end]
}
function parseRun (lines, start, kind, keeps) {
let end = start + 1
while (end < lines.length && keeps(lines[end])) end++
return [block(kind, lines.slice(start, end).join('\n')), end]
}
function isQuoteLine (line) {
return trimLeft(line, ' ').startsWith('>')
}
function continuesParagraph (line) {
return goTrimSpace(line) !== '' && !startsBlock(line)
}
function startsBlock (line) {
return fenceLine.test(line) || headingLine.test(line) ||
ruleLine.test(line) || itemLine.test(line) || isQuoteLine(line)
}
function marker (block) {
if (block.kind === Code || block.kind === Rule || isFence(block.kind)) return ''
const last = block.source.slice(block.source.lastIndexOf('\n') + 1)
const match = markerTail.exec(last)
return match ? match[1] : ''
}
// plain is markup.Plain (and Strip): a block's words without its syntax.
export function plain (block) {
let text = block.source
if (isFence(block.kind)) return ''
switch (block.kind) {
case Code: return codeText(text)
case Heading: text = trimLeft(text, '# \t'); break
case Item: text = text.replace(itemLine, ''); break
case Quote: text = quoteText(text); break
}
if (block.marker !== '') text = text.replace(markerTail, '')
return text
}
export function codeText (source) {
let lines = source.split('\n')
if (lines.length <= 1) return ''
if (fenceLine.test(lines[lines.length - 1])) lines = lines.slice(0, -1)
return lines.slice(1).join('\n')
}
function quoteText (source) {
return source.split('\n').map(line => {
line = trimLeft(line, ' ')
if (line.startsWith('>')) line = line.slice(1)
return line.startsWith(' ') ? line.slice(1) : line
}).join('\n')
}
// itemSyntax is what a list item keeps for fidelity (spec §6.3): its
// exact indent, its bullet or number and delimiter, and its task box.
export function itemSyntax (block) {
const match = itemLine.exec(block.source)
const syntax = { indent: match[1], bullet: null, number: null, delim: null }
if (block.ordered) {
syntax.number = match[2].slice(0, -1)
syntax.delim = match[2].slice(-1)
} else {
syntax.bullet = match[2]
}
return syntax
}
// task splits a list item's text from its box: [text, null | ' ' | 'x'].
export function task (text) {
const match = taskBox.exec(text)
if (!match) return [text, null]
return [text.slice(match[0].length), match[1]]
}
// spans is markup.Spans: a block's inline text as runs.
export function spans (text) {
const scan = new Scan(text)
const out = []
let run = ''
const flush = () => {
if (run !== '') out.push(span(Text, { text: run, source: run }))
run = ''
}
for (let index = 0; index < text.length;) {
const [found, width] = spanAt(scan, index)
if (width === 0) {
run += text[index]
index++
continue
}
flush()
found.source = text.slice(index, index + width)
out.push(found)
index += width
}
flush()
return out
}
function span (kind, fields) {
return {
kind, text: '', target: '', anchor: '', url: '', source: '', ...fields
}
}
// Scan is one text's tables for the link tests, each built in one pass
// on first use: next(name, at) is the first index at or after at where
// the named test holds, or -1. With them a link test costs the same
// wherever it starts; scanning from each [ for its ] or ]] was quadratic,
// seconds over a line of [a (review M6). They answer exactly what Go's
// scans (spans.go) answer.
class Scan {
constructor (text) {
this.text = text
this.tables = {}
}
next (name, at) {
if (at >= this.text.length) return -1
this.tables[name] ??= nextTable(this.text, stops[name])
return this.tables[name][at]
}
}
const stops = {
// A web link's text ends at the first ] or line end, its address at
// the first ), space or line end: [^\]\n]+ and [^)\t\n\f\r ]+.
label: (text, at) => text[at] === ']' || text[at] === '\n',
address: (text, at) => ')\t\n\f\r '.includes(text[at]),
// A wiki link ends at the first ]], unless a [ or a line end is first.
close: (text, at) => text[at] === ']' && text[at + 1] === ']',
open: (text, at) => text[at] === '[' || text[at] === '\n'
}
function nextTable (text, stop) {
const table = new Int32Array(text.length)
let next = -1
for (let at = text.length - 1; at >= 0; at--) {
if (stop(text, at)) next = at
table[at] = next
}
return table
}
function spanAt (scan, index) {
const text = scan.text
if (text[index] === '`') return codeSpan(text.slice(index))
if (text.startsWith('![[', index)) {
const end = closing(scan, index + 3)
if (end >= 0) return [span(Embed, { text: text.slice(index, index + end + 5) }), end + 5]
} else if (text.startsWith('![', index)) {
return imageSpan(scan, index)
} else if (text.startsWith('[[', index)) {
return wikiSpan(scan, index)
} else if (text[index] === '[') {
const match = webLinkAt(scan, index)
if (match && linkAddress(match.url)) {
return [span(WebLink, { text: match.text, url: match.url }), match.width]
}
} else if (text[index] === 'h' && wordStart(text, index)) {
const match = autoLink.exec(text.slice(index))
if (match) return [span(WebLink, { text: match[0], url: match[0] }), match[0].length]
}
return [null, 0]
}
// webLinkAt is /^\[([^\]\n]+)\]\(([^)\t\n\f\r ]+)\)/ at index: neither
// class holds the character that ends it, so there is one way to match.
function webLinkAt (scan, index) {
const text = scan.text
const label = scan.next('label', index + 1)
if (label <= index + 1 || text[label] !== ']' || text[label + 1] !== '(') return null
const address = scan.next('address', label + 2)
if (address <= label + 2 || text[address] !== ')') return null
// Longer than MAX_ADDRESS in UTF-16 units is longer in UTF-8 bytes
// too: refused before the slice, which would be linear per [.
if (address - (label + 2) > MAX_ADDRESS) return null
return {
text: text.slice(index + 1, label),
url: text.slice(label + 2, address),
width: address + 1 - index
}
}
// imageSpan is markup's imageSpan:  at index, where alt
// holds no [, ] or line break and at most MaxAlt bytes.
function imageSpan (scan, index) {
const text = scan.text
const end = scan.next('label', index + 2)
// More than MaxAlt UTF-16 units is more than MaxAlt bytes: refused
// before the slice, which made "![a" repeated quadratic (Fable round
// 3, L8).
if (end < 0 || text[end] !== ']' || text[end + 1] !== '(' ||
end - (index + 2) > MaxAlt ||
utf8Length(text.slice(index + 2, end)) > MaxAlt) return [null, 0]
const open = scan.next('open', index + 2)
if (open >= 0 && open < end) return [null, 0]
const closer = scan.next('address', end + 2)
if (closer < 0 || text[closer] !== ')') return [null, 0]
const address = text.slice(end + 2, closer)
if (!address.startsWith(ImagePrefix)) return [null, 0]
const id = address.slice(ImagePrefix.length)
if (!isImageID(id)) return [null, 0]
return [span(Image, { text: text.slice(index + 2, end), target: id, url: address }),
closer + 1 - index]
}
function codeSpan (rest) {
const end = rest.slice(1).indexOf('`')
if (end <= 0) return [null, 0]
return [span(InCode, { text: rest.slice(1, end + 1) }), end + 2]
}
function cut (text, separator) {
const at = text.indexOf(separator)
return at < 0 ? [text, ''] : [text.slice(0, at), text.slice(at + 1)]
}
function wikiSpan (scan, index) {
const end = closing(scan, index + 2)
if (end < 0) return [null, 0]
const inner = scan.text.slice(index + 2, index + end + 2)
let [target, shown] = cut(inner, '|')
let anchor
;[target, anchor] = cut(target, '#')
target = goTrimSpace(target)
if (target === '') return [null, 0]
const found = span(WikiLink, { target, text: goTrimSpace(shown) })
if (anchor.startsWith('^')) found.anchor = goTrimSpace(anchor.slice(1))
return [found, end + 4]
}
// closing is how far from at the first ]] is, or -1 when there is none
// or a [ or a line end comes before it.
function closing (scan, at) {
const end = scan.next('close', at)
if (end < 0) return -1
const open = scan.next('open', at)
if (open >= 0 && open < end) return -1
return end - at
}
function wordStart (text, index) {
return index === 0 || ' \t\n('.includes(text[index - 1])
}
export function isDateShaped (text) { return isoDate.test(text) }
// The block tests the serialiser needs, exactly as parse applies them.
export function isFenceLine (line) { return fenceLine.test(line) }
export function isRuleLine (line) { return ruleLine.test(line) }
export function fenceOf (line) { return fenceLine.exec(line)?.[1] ?? null }
// closesFence is parseFence's test for a closing line.
export function closesFence (line, fence) {
return trimLeft(line, ' ').startsWith(fence)
}
// isDate is time.Parse(time.DateOnly): a real day in the Gregorian
// calendar, year 0000 to 9999.
export function isDate (text) {
if (!isDateShaped(text)) return false
const [year, month, day] = text.split('-').map(Number)
if (month < 1 || month > 12 || day < 1) return false
const leap = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0)
const days = [31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
return day <= days[month - 1]
}
// The emphasis passes (inline.go's words), over escaped text.
const tripleStar = new RegExp(`\\*\\*\\*(${S}(?:[^*]*?${S})?)\\*\\*\\*`, 'gu')
const strong = new RegExp(`\\*\\*(${S}(?:[^*]*?${S})?)\\*\\*`, 'gu')
const emphasis = new RegExp(`\\*(${S}(?:[^*]*?${S})?)\\*`, 'gu')
const markTag = /<\/?(?:em|strong)>/gu
const lineBreak = /\n[ \t]*/gu
// escapeHTML is html.EscapeString.
export function escapeHTML (text) {
return text.replace(/[&'<>"]/gu, char => ({
'&': '&', "'": ''', '<': '<', '>': '>', '"': '"'
})[char])
}
export function unescapeHTML (text) {
return text.replace(/&(?:amp|#39|lt|gt|#34);/gu, entity => ({
'&': '&', ''': "'", '<': '<', '>': '>', '"': '"'
})[entity])
}
// words is a text run as the editor holds it: text runs and hard breaks,
// each with em and strong. A break carries the next line's indent, which
// is kept in the source and not shown.
export function words (text) {
let tagged = escapeHTML(text)
tagged = tagged.replace(tripleStar, '$1')
tagged = tagged.replace(strong, '$1')
tagged = tagged.replace(emphasis, '$1')
const runs = []
let ems = 0
let strongs = 0
let cursor = 0
for (const match of tagged.matchAll(markTag)) {
lines(runs, tagged.slice(cursor, match.index), ems > 0, strongs > 0)
const step = match[0][1] === '/' ? -1 : 1
if (match[0].endsWith('em>')) ems += step
else strongs += step
cursor = match.index + match[0].length
}
lines(runs, tagged.slice(cursor), ems > 0, strongs > 0)
return runs
}
function lines (runs, escaped, em, strong) {
let cursor = 0
for (const match of escaped.matchAll(lineBreak)) {
pushText(runs, escaped.slice(cursor, match.index), em, strong)
runs.push({ kind: 'break', indent: match[0].slice(1), em, strong })
cursor = match.index + match[0].length
}
pushText(runs, escaped.slice(cursor), em, strong)
}
function pushText (runs, escaped, em, strong) {
if (escaped !== '') {
runs.push({ kind: 'text', text: unescapeHTML(escaped), em, strong })
}
}