components
All repositories: gitoria
89.7 KB
// md-editor.hl — THE MARKDOWN WYSIWYG EDITOR, all Hybriel (port of worldapi-components/md-editor.js): headings look like// headings, **bold** is bold, lists are lists — while you type; the value stays plain Markdown. `MdEditor { name = "note" value = "**hi**" }`.// The formatted surface is a contenteditable element whose children are built in the browser (createElement / text nodes, never// innerHTML of user text) — the framework never re-renders it: nothing bound to it changes after the first render. Hybriel has no// mount event, so a 1 ms CSS animation on the surface fires `animationiteration` in the very frame after the page is claimed, and that// hands the editor its first content (the mount hook turns the animation off again). The first editor to hear it draws every editor of// the page (`mountAll`), so a reader never sees the empty surface the server sent. The value is written to the hidden field// `<input name>` (posts in a form) and announced with a bubbling DOM `input` event on it (`e.target.value` = the Markdown).// Subset (what the tickets' markdown.hl renders): headings 1-6, paragraphs (single line breaks kept), - / 1. lists (one level),// fenced code blocks, `code`, links (http(s), mailto, /path, #anchor), *em*, **strong**, GitHub pipe tables (mission 004: header,// `| --- | :-: | --: |` alignment, `\|`, inline Markdown in cells, outer pipes optional).import Icon from '../icons/icons.hl'String name = 'markdown'String value = ''String placeholder = 'Write…'// rows = the height of the editing surface in text lines (min-height rows x 1.5em; the source view the same in its own font)Number rows = 6// readonly = "true": the Markdown shown formatted and nothing else — no toolbar, no source switch, not editable, no field frame// (mission 006: the comments block shows every comment with the editor's own renderer, so typed and shown look the same)String readonly = 'false'// files = "off" (mission 009, tickets#27): no File button, and files dropped on or pasted into the editor are NOT taken here — they go// on to the page, so a FilesUpload in pick mode around the editor collects them as attachments (the comments block's form does that)String files = 'on'String editable = readonly == 'true' ? 'false' : 'true'// readonly: NO inline min-height — an inline style beats the stylesheet's `article { min-height: 0 }` of the readonly look, which made every// shown comment as tall as a 6-row editor (K1). The surface of a readonly editor hugs its text.String surfaceStyle = readonly == 'true' ? '' : 'min-height:' + (rows * 1.5) + 'em'String sourceStyle = 'min-height:' + (rows * 1.35 + 1.2) + 'rem'String surfaceTab = readonly == 'true' ? '-1' : '0'String surfaceRole = readonly == 'true' ? 'document' : 'textbox'Hybrid linkOk = ['http://', 'https://', 'mailto:', '/', '#']static NL = ""static BS = 'x\y'.slice(1, 2)// a REAL carriage return (Windows line ends, a textarea's post). Hybriel strings have no escapes ('\r' is two characters, #17) and// `String.fromCharCode` does not parse here, so the JSON escape is decodedstatic CR = JSON.parse('"' + BS + 'r"')static ZW = ""static NB = " "// ---- small text helpers ---------------------------------------------------------------------------------------------isDigit(c) { k = c.charCodeAt(0) return k >= 48 && k <= 57 }isAlnum(c) { k = c.charCodeAt(0) return (k >= 48 && k <= 57) || (k >= 65 && k <= 90) || (k >= 97 && k <= 122) || k > 127 }isSpace(c) { return c == ' ' || c == NB || c == NL || c == ZW }repeat(c, n) { let s = '' let i = 0 while (i < n) { s = s + c i = i + 1 } return s }// trim spaces (also the non-breaking space the browser types) and the zero-width spaceclean(s) { return s.replaceAll(NB, ' ').replaceAll(ZW, '') }trimSp(s) {let a = 0let b = s.lengthwhile (a < b && (s.slice(a, a + 1) == ' ' || s.slice(a, a + 1) == NB || s.slice(a, a + 1) == ZW)) { a = a + 1 }while (b > a && (s.slice(b - 1, b) == ' ' || s.slice(b - 1, b) == NB || s.slice(b - 1, b) == ZW)) { b = b - 1 }return s.slice(a, b)}safeHref(u) {t = trimSp(u)if (t == '' ) { return '' }for (p of linkOk) { if (t.startsWith(p)) { return t } }return ''}// an image address: http(s) or a path on this site; nothing else (no data:, no javascript:)safeSrc(u) {t = trimSp(u)if (t.startsWith('https://') || t.startsWith('http://') || (t.startsWith('/') && !t.startsWith('//'))) { return t }return ''}// the end of a bare URL that starts at i: up to a space, minus trailing punctuationurlEnd(s, i) {let j = iwhile (j < s.length && !isSpace(s.slice(j, j + 1)) && s.slice(j, j + 1) != '<') { j = j + 1 }while (j > i && ('.,;:!?)]}' + "'" + '"').indexOf(s.slice(j - 1, j)) >= 0) { j = j - 1 }return j}// ---- Markdown → DOM ---------------------------------------------------------------------------------------------------el(tag, text) {e = document.createElement(tag)if (text != null) { e.textContent = text }return e}// the closing run of c (n times) after position i, whose content is not empty and does not end in a space; -1 when nonecloser(s, i, c, n) {mark = repeat(c, n)let j = s.indexOf(mark, i)while (j >= 0) {let after = s.slice(j + n, j + n + 1)let before = s.slice(j - 1, j)let ok = j > i && !isSpace(before) && before != BS && (after != c)if (ok && c == '_' && after != '' && isAlnum(after)) { ok = false }if (ok) { return j }j = s.indexOf(mark, j + 1)}return -1}// appends the inline Markdown `s` to `host`inline(host, s) {let buf = ''let i = 0n = s.lengthwhile (i < n) {let c = s.slice(i, i + 1)let done = falseif (c == BS && i + 1 < n && '\*_`[]<>#-.!()+~|'.indexOf(s.slice(i + 1, i + 2)) >= 0) {buf = buf + s.slice(i + 1, i + 2)i = i + 2done = true}if (!done && c == '`') {let run = 1while (s.slice(i + run, i + run + 1) == '`') { run = run + 1 }let mark = repeat('`', run)let j = s.indexOf(mark, i + run)if (j > i + run) {if (buf != '') { host.appendChild(document.createTextNode(buf)) buf = '' }let inner = s.slice(i + run, j)if (inner.length > 2 && inner.startsWith(' ') && inner.endsWith(' ')) { inner = inner.slice(1, inner.length - 1) }host.appendChild(el('code', inner))i = j + rundone = true}}if (!done && c == '!' && s.slice(i + 1, i + 2) == '[') {let j = s.indexOf('](', i + 2)let k = j >= 0 ? s.indexOf(')', j + 2) : -1if (j > i + 1 && k > j + 2) {let src = safeSrc(s.slice(j + 2, k))if (src != '') {if (buf != '') { host.appendChild(document.createTextNode(buf)) buf = '' }let img = el('img', null)img.setAttribute('src', src)img.setAttribute('alt', s.slice(i + 2, j))host.appendChild(img)i = k + 1done = true}}}if (!done && c == '[') {let j = s.indexOf('](', i + 1)let k = j >= 0 ? s.indexOf(')', j + 2) : -1if (j > i + 1 && k > j + 2) {let href = safeHref(s.slice(j + 2, k))if (href != '') {if (buf != '') { host.appendChild(document.createTextNode(buf)) buf = '' }let a = el('a', null)a.setAttribute('href', href)inline(a, s.slice(i + 1, j))host.appendChild(a)i = k + 1done = true}}}if (!done && c == '<' && (s.slice(i + 1, i + 8) == 'http://' || s.slice(i + 1, i + 9) == 'https://')) {let j = s.indexOf('>', i)if (j > 0 && s.slice(i, j).indexOf(' ') < 0) {if (buf != '') { host.appendChild(document.createTextNode(buf)) buf = '' }let a = el('a', s.slice(i + 1, j))a.setAttribute('href', s.slice(i + 1, j))host.appendChild(a)i = j + 1done = true}}if (!done && c == 'h' && (s.slice(i, i + 7) == 'http://' || s.slice(i, i + 8) == 'https://') && (i == 0 || !isAlnum(s.slice(i - 1, i)))) {let j = urlEnd(s, i)if (j > i + 8) {if (buf != '') { host.appendChild(document.createTextNode(buf)) buf = '' }let a = el('a', s.slice(i, j))a.setAttribute('href', s.slice(i, j))host.appendChild(a)i = jdone = true}}if (!done && (c == '*' || c == '_') && !(c == '_' && i > 0 && isAlnum(s.slice(i - 1, i)))) {let run = 1while (run < 3 && s.slice(i + run, i + run + 1) == c) { run = run + 1 }let first = s.slice(i + run, i + run + 1)if (first != '' && !isSpace(first) && first != c) {let j = closer(s, i + run, c, run)if (j > 0) {if (buf != '') { host.appendChild(document.createTextNode(buf)) buf = '' }let node = nulllet innerNode = nullif (run == 1) { node = el('em', null) innerNode = node }if (run == 2) { node = el('strong', null) innerNode = node }if (run == 3) { node = el('strong', null) innerNode = el('em', null) node.appendChild(innerNode) }inline(innerNode, s.slice(i + run, j))host.appendChild(node)i = j + rundone = true}}}if (!done) { buf = buf + c i = i + 1 }}if (buf != '') { host.appendChild(document.createTextNode(buf)) }}// a line like `## title`: its level (0 = not a heading)headingLevel(line) {let k = 0while (k < line.length && k < 7 && line.slice(k, k + 1) == '#') { k = k + 1 }if (k >= 1 && k <= 6 && (line.length == k || line.slice(k, k + 1) == ' ')) { return k }return 0}// a list line: 0 = none, 1 = bullet, 2 = numbered; the item text is cut off by itemTextlistKind(line) {t = line.trim()if ((t.startsWith('- ') || t.startsWith('* ') || t.startsWith('+ '))) { return 1 }let k = 0while (k < t.length && isDigit(t.slice(k, k + 1))) { k = k + 1 }if (k > 0 && k < 10 && (t.slice(k, k + 2) == '. ' || t.slice(k, k + 2) == ') ')) { return 2 }return 0}itemText(line) {t = line.trim()let k = 0while (k < t.length && isDigit(t.slice(k, k + 1))) { k = k + 1 }return t.slice(k + 2).trim()}fenceOf(line) {t = line.trim()if (t.startsWith('```')) { return '`' }if (t.startsWith('~~~')) { return '~' }return ''}startsBlock(line) { return headingLevel(line) > 0 || listKind(line) > 0 || fenceOf(line) != '' }// ---- GitHub pipe tables (mission 004, the behaviour of notes' md-editor.js 9acc27f) ----------------------------------------// A table is a header row, a delimiter row (`| --- | :-: | --: |`, the colons set the alignment) with the same number of cells,// then body trs up to a blank line or another block; outer pipes are optional, `\|` is a pipe inside a cell (also in code).// how many backslashes stand right before position k (down to `start`): odd = the character at k is escapedescapedAt(s, k, start) {let n = 0while (k - 1 - n >= start && s.slice(k - 1 - n, k - n) == BS) { n = n + 1 }return n % 2 == 1}// a row's cells (trimmed Markdown, still with `\|`): split at every pipe that is not escapedrowCells(s) {let a = 0let b = s.lengthwhile (a < b && isSpace(s.slice(a, a + 1))) { a = a + 1 }while (b > a && isSpace(s.slice(b - 1, b))) { b = b - 1 }if (a < b && s.slice(a, a + 1) == '|') { a = a + 1 }if (b > a && s.slice(b - 1, b) == '|' && !escapedAt(s, b - 1, a)) { b = b - 1 }cells = []let start = alet k = awhile (k < b) {let c = s.slice(k, k + 1)if (c == BS && k + 1 < b) { k = k + 2 }else {if (c == '|') { cells.push(trimSp(s.slice(start, k))) start = k + 1 }k = k + 1}}cells.push(trimSp(s.slice(start, b)))return cells}// a cell's Markdown: `\|` is a pipe, every other escape stays for inline()unpipe(t) {let out = ''let k = 0while (k < t.length) {if (t.slice(k, k + 1) == BS && k + 1 < t.length) {out = out + (t.slice(k + 1, k + 2) == '|' ? '|' : t.slice(k, k + 2))k = k + 2} else { out = out + t.slice(k, k + 1) k = k + 1 }}return out}// the delimiter row (it must hold a pipe): the alignments ('' left center right), or nullalignsOf(line) {if (line.indexOf('|') < 0) { return null }out = []for (c of rowCells(line)) {let core = clet left = core.startsWith(':')if (left) { core = core.slice(1) }let right = core.endsWith(':')if (right) { core = core.slice(0, core.length - 1) }if (core == '' || core.replaceAll('-', '') != '') { return null }out.push(left && right ? 'center' : (right ? 'right' : (left ? 'left' : '')))}return out}// a pipe row: a line that starts with `|` (whether it ends with one does not matter)isPipeRow(line) { return line.trim().startsWith('|') }// a table starting at line i: [alignments, header cells, bare], or null. With a delimiter row: bare = false. WITHOUT one (notes#5: pipe rows// as the creator writes them): two or more pipe rows in a row, the first is the header, bare = true, every column left aligned.tableAt(lines, i) {if (i + 1 >= lines.length || lines[i].trim() == '') { return null }aligns = alignsOf(lines[i + 1])if (aligns == null) {if (isPipeRow(lines[i]) && isPipeRow(lines[i + 1])) {let bareCells = rowCells(lines[i])let bareAligns = []for (c of bareCells) { bareAligns.push('') }return [bareAligns, bareCells, true]}return null}cells = rowCells(lines[i])if (cells.length != aligns.length) { return null }return [aligns, cells, false]}// a cell (th / td) with its alignment and its inline Markdown; an empty cell holds a <br> (a place for the caret)cellEl(tag, align, md) {cell = el(tag, null)if (align != '') { cell.setAttribute('data-align', align) }if (md == '') { cell.appendChild(el('br', null)) } else { inline(cell, md) }return cell}// the table of Markdown lines: lines[0] the header, lines[1] the delimiter, the rest body trs (missing cells padded, extra dropped).// It keeps its source (`mdSrc`) and its canonical form (`mdCanon`): written back byte for byte while it stays the same.tableOf(src, aligns, bare) {t = el('table', null)head = el('thead', null)body = el('tbody', null)let r = 0while (r < src.length) {if (bare || r != 1) {let cells = rowCells(src[r])let tr = el('tr', null)let k = 0while (k < aligns.length) {tr.appendChild(cellEl(r == 0 ? 'th' : 'td', aligns[k], k < cells.length ? unpipe(cells[k]) : ''))k = k + 1}if (r == 0) { head.appendChild(tr) } else { body.appendChild(tr) }}r = r + 1}t.appendChild(head)if (body.childNodes.length > 0) { t.appendChild(body) }t.mdBare = baret.mdSrc = src.join(NL)t.mdCanon = tableMd(t)return t}// Markdown → the block elements in a containerparseInto(box, md) {let lines = md.replaceAll(CR, '').split(NL)let i = 0while (i < lines.length) {let line = lines[i]let fence = fenceOf(line)if (fence != '') {let run = 0let t = line.trim()while (t.slice(run, run + 1) == fence) { run = run + 1 }let body = []i = i + 1while (i < lines.length && !(lines[i].trim().startsWith(repeat(fence, run)) && lines[i].trim().replaceAll(fence, '') == '')) { body.push(lines[i]) i = i + 1 }i = i + 1box.appendChild(el('pre', body.join(NL)))} else if (line.trim() == '') {i = i + 1} else if (headingLevel(line) > 0) {let lv = headingLevel(line)let text = line.trim().slice(lv).trim()while (text.endsWith('#') && text.length > 0) { text = text.slice(0, text.length - 1) }let h = el('h' + lv, null)inline(h, text.trim())box.appendChild(h)i = i + 1} else if (listKind(line) > 0) {let kind = listKind(line)let list = el(kind == 1 ? 'ul' : 'ol', null)let last = nullwhile (i < lines.length && lines[i].trim() != '' && (listKind(lines[i]) == kind || (listKind(lines[i]) == 0 && !startsBlock(lines[i]) && last != null))) {if (listKind(lines[i]) == kind) {last = el('li', null)inline(last, itemText(lines[i]))list.appendChild(last)} else {last.appendChild(el('br', null))inline(last, lines[i].trim())}i = i + 1}box.appendChild(list)} else if (tableAt(lines, i) != null) {let tb = tableAt(lines, i)let j = tb[2] ? i + 1 : i + 2while (j < lines.length && lines[j].trim() != '' && !startsBlock(lines[j]) && (!tb[2] || isPipeRow(lines[j]))) { j = j + 1 }box.appendChild(tableOf(lines.slice(i, j), tb[0], tb[2]))i = j} else {let p = el('p', null)let first = truewhile (i < lines.length && lines[i].trim() != '' && (first || (!startsBlock(lines[i]) && tableAt(lines, i) == null))) {if (!first) { p.appendChild(el('br', null)) }inline(p, lines[i].trim())first = falsei = i + 1}box.appendChild(p)}}if (box.childNodes.length == 0) { let p = el('p', null) p.appendChild(el('br', null)) box.appendChild(p) }// a table at the end gets an empty paragraph after it: a place for the caret (an empty paragraph is never written)if (box.lastChild.nodeName == 'TABLE') { let p = el('p', null) p.appendChild(el('br', null)) box.appendChild(p) }}// ---- DOM → Markdown ---------------------------------------------------------------------------------------------------// a text node's characters, with the ones Markdown would read as formatting written as an escapeescapeText(s, first) {let out = ''let i = 0while (i < s.length) {let c = s.slice(i, i + 1)let prev = i > 0 ? s.slice(i - 1, i) : ' 'let next = i + 1 < s.length ? s.slice(i + 1, i + 2) : ' 'if (c == BS || c == '*' || c == '`' || c == '[' || c == ']' || c == '<') { out = out + BS + c }else if (c == '_' && (!isAlnum(prev) || !isAlnum(next))) { out = out + BS + c }else { out = out + c }i = i + 1}return out}// the inline Markdown of an element's childreninlineMd(node) {let out = ''kids = node.childNodeslet i = 0while (i < kids.length) {let k = kids[i]if (k.nodeType == 3) {out = out + escapeText(clean(k.data), false)} else if (k.nodeType == 1) {let tag = k.nodeName.toLowerCase()if (tag == 'br') { out = out + NL }else if (tag == 'code') {let t = clean(k.textContent)if (t != '') {let run = 1while (t.indexOf(repeat('`', run)) >= 0) { run = run + 1 }let pad = t.startsWith('`') || t.endsWith('`') ? ' ' : ''out = out + repeat('`', run) + pad + t + pad + repeat('`', run)}}else if (tag == 'strong' || tag == 'b' || tag == 'em' || tag == 'i') {let mark = (tag == 'strong' || tag == 'b') ? '**' : '*'let t = inlineMd(k)let core = trimSp(t)if (core != '') {let lead = t.slice(0, t.indexOf(core))let tail = t.slice(t.indexOf(core) + core.length)out = out + lead + mark + core + mark + tail} else { out = out + t }}else if (tag == 'img') {let src = safeSrc(k.getAttribute('src') != null ? k.getAttribute('src') : '')if (src != '') { out = out + '![' + (k.getAttribute('alt') != null ? k.getAttribute('alt') : '').replaceAll('[', '').replaceAll(']', '') + '](' + src.replaceAll(')', '%29').replaceAll(' ', '%20') + ')' }}else if (tag == 'a') {let t = inlineMd(k)let href = safeHref(k.getAttribute('href') != null ? k.getAttribute('href') : '')if (href == '' || trimSp(t) == '') { out = out + t }else if (trimSp(k.textContent) == href && (href.startsWith('http://') || href.startsWith('https://'))) { out = out + href }else { out = out + '[' + t + '](' + href.replaceAll(')', '%29').replaceAll(' ', '%20') + ')' }}else if (tag == 'div' || tag == 'p') { out = out + inlineMd(k) }else { out = out + inlineMd(k) }}i = i + 1}return out}// the text of a paragraph's or item's lines: trailing / leading breaks dropped, each line trimmedlines(md) {parts = md.split(NL)out = []for (p of parts) { out.push(trimSp(p)) }while (out.length > 0 && out[out.length - 1] == '') { out.pop() }while (out.length > 0 && out[0] == '') { out.shift() }return out}// same for a line starting with digits + "." (the backslash goes before the dot)guardNumber(line) {let k = 0while (k < line.length && isDigit(line.slice(k, k + 1))) { k = k + 1 }if (k > 0 && (line.slice(k, k + 2) == '. ' || line.slice(k, k + 2) == ') ')) { return line.slice(0, k) + BS + line.slice(k) }return line}paragraphMd(node) {ls = lines(inlineMd(node))if (ls.length == 0) { return '' }out = []for (l of ls) {if (headingLevel(l) > 0 || fenceOf(l) != '' || l.startsWith('>') || listKind(l) == 1) { out.push(BS + l) }// a line that would read as a table's delimiter row under the line before: its first pipe escapedelse if (out.length > 0 && alignsOf(l) != null) { out.push(l.slice(0, l.indexOf('|')) + BS + l.slice(l.indexOf('|'))) }else { out.push(guardNumber(l)) }}return out.join(NL)}// the Markdown blocks of a container's childrenblocksMd(box) {out = []kids = box.childNodeslet i = 0while (i < kids.length) {let k = kids[i]if (k.nodeType == 3) {let t = paragraphMd(k.parentNode == box ? wrapText(k) : k)if (t != '') { out.push(t) }} else if (k.nodeType == 1) {let tag = k.nodeName.toLowerCase()if (tag.length == 2 && tag.startsWith('h') && isDigit(tag.slice(1, 2)) && tag != 'hr') {let t = lines(inlineMd(k)).join(' ')if (t != '') { out.push(repeat('#', toNumber(tag.slice(1, 2))) + ' ' + t) }} else if (tag == 'ul' || tag == 'ol') {let items = []let n = 1let li = k.childNodeslet j = 0while (j < li.length) {if (li[j].nodeType == 1) {let ls = lines(inlineMd(li[j]))if (ls.length > 0) {items.push((tag == 'ul' ? '- ' : n + '. ') + ls.join(NL + ' '))n = n + 1}}j = j + 1}if (items.length > 0) { out.push(items.join(NL)) }} else if (tag == 'pre') {let body = preText(k)let run = 3while (body.indexOf(repeat('`', run)) >= 0) { run = run + 1 }if (body != '') { out.push(repeat('`', run) + NL + body + NL + repeat('`', run)) }} else if (tag == 'table') {// an unchanged table is written back byte for byte (its source), a changed one in the canonical formlet t = tableMd(k)if (t != '' && t == k.mdCanon) { t = k.mdSrc }if (t != '') { out.push(t) }} else if ((tag == 'div' || tag == 'p') && hasBlockChild(k)) {for (x of blocksMd(k)) { out.push(x) }} else if (tag == 'br') {} else {let t = paragraphMd(k)if (t != '') { out.push(t) }}}i = i + 1}return out}wrapText(t) { p = el('p', null) p.appendChild(document.createTextNode(t.data)) return p }hasBlockChild(node) {kids = node.childNodeslet i = 0while (i < kids.length) {if (kids[i].nodeType == 1 && 'p,div,ul,ol,pre,h1,h2,h3,h4,h5,h6,table'.split(',').indexOf(kids[i].nodeName.toLowerCase()) >= 0) { return true }i = i + 1}return false}// the text of a code block (a <br> is a line break)preText(node) {let out = ''kids = node.childNodeslet i = 0while (i < kids.length) {let k = kids[i]if (k.nodeType == 3) { out = out + k.data.replaceAll(ZW, '').replaceAll(NB, ' ') }else if (k.nodeName.toLowerCase() == 'br') { out = out + NL }else { out = out + preText(k) }i = i + 1}// a trailing line feed is the browser's, not the writer'swhile (out.endsWith(NL)) { out = out.slice(0, out.length - 1) }return out}toMarkdown(box) {return blocksMd(box).join(NL + NL)}// ---- a table → Markdown: one line per row, padded to the column widths (`| a | b |`), `|` in a cell written `\|`cellMd(cell) { return lines(inlineMd(cell)).join(' ').replaceAll('|', BS + '|') }// the cells of a row (th / td only)cellsOf(tr) {out = []kids = tr.childNodeslet i = 0while (i < kids.length) {if (kids[i].nodeName == 'TH' || kids[i].nodeName == 'TD') { out.push(kids[i]) }i = i + 1}return out}dashes(align, n) {if (align == 'center') { return ':' + repeat('-', n - 2) + ':' }if (align == 'left') { return ':' + repeat('-', n - 1) }if (align == 'right') { return repeat('-', n - 1) + ':' }return repeat('-', n)}tableMd(t) {trs = t.querySelectorAll('tr')if (trs.length == 0) { return '' }head = cellsOf(trs[0])cols = head.lengthif (cols == 0) { return '' }// every cell's Markdown, row by row (trs padded / cut to the header's width)md = []aligns = []for (h of head) { aligns.push(h.getAttribute('data-align') != null ? h.getAttribute('data-align') : '') }let r = 0while (r < trs.length) {let cs = cellsOf(trs[r])let k = 0while (k < cols) {let m = k < cs.length ? cellMd(cs[k]) : ''md.push(m)k = k + 1}r = r + 1}w = []let col = 0while (col < cols) {let n = 3let i = colwhile (i < md.length) { if (md[i].length > n) { n = md[i].length } i = i + cols }w.push(n)col = col + 1}out = []r = 0while (r < trs.length) {let line = '|'let c = 0while (c < cols) { line = line + ' ' + md[r * cols + c] + repeat(' ', w[c] - md[r * cols + c].length) + ' |' c = c + 1 }out.push(line)if (r == 0 && !(t.mdBare && trs.length > 1)) {let d = '|'let c2 = 0while (c2 < cols) { d = d + ' ' + dashes(aligns[c2], w[c2]) + ' |' c2 = c2 + 1 }out.push(d)}r = r + 1}return out.join(NL)}// ---- the editor ---------------------------------------------------------------------------------------------------------rootOf(node) { return node.closest('md-editor') }surfaceOf(root) { return root.querySelector('article') }fieldOf(root) { return root.querySelector('input.value') }sourceOf(root) { return root.querySelector('textarea') }// the block (a direct child of the surface) that holds a nodeblockOf(root, node) {s = surfaceOf(root)let n = nodewhile (n != null && n.parentNode != s) { n = n.parentNode }return n}inSurface(root) {sel = document.getSelection()return sel.rangeCount > 0 && sel.anchorNode != null && surfaceOf(root).contains(sel.anchorNode)}inTag(root, tags) {sel = document.getSelection()let n = sel.anchorNodes = surfaceOf(root)while (n != null && n != s) {if (n.nodeType == 1 && tags.indexOf(n.nodeName.toLowerCase()) >= 0) { return true }n = n.parentNode}return false}// Chrome's list / block commands put a <ul>, <pre> or a new <p> INSIDE the <p> the caret was in (`<p><ul>…</ul><p>…</p></p>`, mission 011): the// outer <p> then reads as one block with the list in it, and a table typed after a list stayed paragraphs. Every top-level <p> that holds a block// is unwrapped (its children move up, the caret stays where it was).hasBlock(p) {for (c of p.childNodes) { if (c.nodeType == 1 && ['UL', 'OL', 'PRE', 'TABLE', 'P', 'DIV', 'H1', 'H2', 'H3', 'H4', 'H5', 'H6'].indexOf(c.nodeName) >= 0) { return true } }return false}flatten(root) {s = surfaceOf(root)// the DOM calls below are awaited, so two syncs (input + keyup) interleave: only one flatten runs at a time (a second one racing it removed the same <p> twice: NotFoundError)if (s.mdFlat == true) { return null }s.mdFlat = truesel = document.getSelection()an = sel.anchorNodeao = sel.anchorOffsetfn = sel.focusNodefo = sel.focusOffsetlet changed = falselet i = 0while (i < s.childNodes.length) {k = s.childNodes[i]if (k.nodeType == 1 && k.nodeName == 'P' && hasBlock(k)) {while (k.firstChild != null) { s.insertBefore(k.firstChild, k) }s.removeChild(k)changed = true} else { i = i + 1 }}// text / <br> directly in the surface (Ctrl+A, Backspace over a lone link leaves a bare <br>) gets its paragraph: every rule looks for a blocklet wrap = nulllet j = 0while (j < s.childNodes.length) {k = s.childNodes[j]if (!isBlockEl(k)) {wrap = el('p', null)s.insertBefore(wrap, k)while (wrap.nextSibling != null && !isBlockEl(wrap.nextSibling)) { wrap.appendChild(wrap.nextSibling) }changed = true}j = j + 1}if (changed && an != null && fn != null && s.contains(an) && s.contains(fn)) {if (an == s && wrap != null) { sel.collapse(wrap, 0) } else { sel.setBaseAndExtent(an, ao, fn, fo) }}s.mdFlat = false}isBlockEl(k) { return k.nodeType == 1 && ['UL', 'OL', 'PRE', 'TABLE', 'P', 'DIV', 'H1', 'H2', 'H3', 'H4', 'H5', 'H6'].indexOf(k.nodeName) >= 0 }// the Markdown of the surface is the value: written to the field and announced when it changed. `orig` keeps an untouched value byte for byte.sync(root) {s = surfaceOf(root)f = fieldOf(root)flatten(root)let md = toMarkdown(s)if (root.mdOrig != null && md == root.mdCanon) { md = root.mdOrig }root.classList.toggle('md-empty', md == '' && s.querySelector('pre') == null && s.querySelector('table') == null)if (md != f.value) {f.value = mdroot.mdLast = mdown(root, md)f.dispatchEvent(new Event('input', { bubbles = true }))}}// THE VALUES THIS EDITOR HAS HELD since the last outside change (`mdSeen`: what it loaded and every value it wrote into the field itself).// The framework hands the member back through the `data-value` attribute — and the host may hand back an OLDER text of this very editor// (a note being saved answers with the version the server has, while the user has typed on; the row of a new note first shows its empty text).// Such a value is not news: the surface is kept and its text is written back (sync). A value this editor never held came from outside// (hl:web's rehydrate of kept state, a push from another device, the page setting it) and is shown by followValue.// The first entry (the loaded value) is never dropped; the rest is cut when the list holds more than 300000 characters.own(root, md) {if (root.mdSeen == null) { root.mdSeen = [md] root.mdSeenSize = md.length return null }if (root.mdSeen.indexOf(md) >= 0) { return null }root.mdSeen.push(md)root.mdSeenSize = root.mdSeenSize + md.lengthwhile (root.mdSeen.length > 2 && root.mdSeenSize > 300000) {root.mdSeenSize = root.mdSeenSize - root.mdSeen[1].lengthroot.mdSeen.splice(1, 1)}}// THE SURFACE MUST NEVER STAY EMPTY under a non-empty value. hl:web builds a composed child anew when the value bound into it changes: it may// put a NEW article (and field) under the same <md-editor> element, which mounted already (`mdMounted`). That surface is empty and no// mount would draw it (mdMount returns early), while the observer's load() had gone into the OLD article (F5, hybriel#211: a comment// whose text vanished after a push, about 1 gate run in 3). `mdSurface` is the article this root drew into: a different one gets the// field's value drawn at once (from the data-value observer, the child-list observer, or its own mount event). True when it redrew.rebuilt(root) {let s = surfaceOf(root)if (s == null || root.mdSurface == s) { return false }root.mdSurface = ss.style.animationName = 'none'let v = fieldOf(root).valueroot.mdSeen = nullload(root, v)sourceOf(root).value = vreturn true}// the member `value` moved: an outside value is loaded into the surface (and the source view); one this editor held before is left alonefollowValue(root) {rebuilt(root)let v = root.getAttribute('data-value')if (v == null) { v = '' }if (root.mdSeen != null && root.mdSeen.indexOf(v) >= 0) {if (v != root.mdLast && root.getAttribute('data-readonly') != 'true') { sync(root) }return null}root.mdSeen = nullload(root, v)sourceOf(root).value = vfieldOf(root).value = vs = surfaceOf(root)// a caret in the surface goes to the end of the new text (the old position means nothing in it)if (s.contains(document.activeElement) || document.activeElement == s) {last = s.lastChildif (last != null) { document.getSelection().collapse(last, last.textContent == '' ? 0 : last.childNodes.length) }}updateBar(root)}// a new value (from outside, the source view or a paste-all): shown formattedload(root, md) {s = surfaceOf(root)s.textContent = ''parseInto(s, md)root.mdOrig = mdroot.mdLast = mdown(root, md)root.mdCanon = toMarkdown(s)root.classList.toggle('md-empty', root.mdCanon == '')}// the toolbar shows what the caret is inupdateBar(root) {if (!root.isConnected || !inSurface(root)) { return null }mark = (tool, active) => { b = root.querySelector('button.' + tool) if (b != null) { b.classList.toggle('on', active) } }mark('bold', document.queryCommandState('bold'))mark('italic', document.queryCommandState('italic'))mark('code', inTag(root, ['code']))mark('ul', inTag(root, ['ul']))mark('ol', inTag(root, ['ol']))mark('pre', inTag(root, ['pre']))mark('table', inTag(root, ['table']))mark('link', inTag(root, ['a']))h = root.querySelector('button.heading')let level = ''tags = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6']for (t of tags) { if (inTag(root, [t])) { level = t.toUpperCase() } }if (h != null) { h.setAttribute('data-level', level.slice(1)) h.classList.toggle('on', level != '') }}// bold / italic / heading / lists / code block: the browser's own editing commands, so undo workscodeToggle(root) {sel = document.getSelection()r = sel.getRangeAt(0)let n = sel.anchorNodelet inCode = nullwhile (n != null && n != surfaceOf(root)) { if (n.nodeType == 1 && n.nodeName.toLowerCase() == 'code') { inCode = n } n = n.parentNode }if (inCode != null && r.collapsed) {// the caret in code and no selection: leave the code (the next typed text is plain), like Ctrl+B / Ctrl+I end bold / italiclet nx = inCode.nextSiblingif (nx == null || nx.nodeType != 3) {nx = document.createTextNode(ZW)inCode.parentNode.insertBefore(nx, inCode.nextSibling)} else if (!nx.data.startsWith(ZW)) { nx.insertData(0, ZW) }sel.collapse(nx, 1)return null}if (inCode != null) {let rr = document.createRange()rr.selectNode(inCode)sel.removeAllRanges()sel.addRange(rr)document.execCommand('insertHTML', false, escHtml(clean(inCode.textContent), ''))return null}// no selection (mission 011): an empty code span the caret sits in, like Ctrl+B / Ctrl+I leave the next typed text bold / italicif (r.collapsed) {document.execCommand('insertHTML', false, '<code>' + ZW + '</code>' + ZW)t = document.getSelection().anchorNodeif (t != null && t.previousSibling != null && t.previousSibling.nodeName == 'CODE') { document.getSelection().collapse(t.previousSibling.firstChild, 1) }return null}document.execCommand('insertHTML', false, escHtml(r.toString(), 'code') + ZW)}// text as escaped html (built by the browser from a text node), optionally inside a tagescHtml(text, tag) {box = document.createElement('div')e = tag != '' ? el(tag, text) : document.createTextNode(text)box.appendChild(e)return box.innerHTML}headingCycle(root) {let cur = 0tags = ['h1', 'h2', 'h3']let i = 0while (i < 3) { if (inTag(root, [tags[i]])) { cur = i + 1 } i = i + 1 }document.execCommand('formatBlock', false, cur == 3 ? 'p' : tags[cur])}blockToggle(root, tag, cmd) {if (inTag(root, [tag])) {if (tag == 'pre') { document.execCommand('formatBlock', false, 'p') } else { document.execCommand(cmd) }} else if (tag == 'pre') { document.execCommand('formatBlock', false, 'pre') } else { document.execCommand(cmd) }}linkOpen(root) {sel = document.getSelection()if (!inSurface(root)) { surfaceOf(root).focus() }root.mdRange = sel.rangeCount > 0 ? sel.getRangeAt(0).cloneRange() : nullf = root.querySelector('link-form input')let n = sel.anchorNodelet href = ''while (n != null && n != surfaceOf(root)) { if (n.nodeType == 1 && n.nodeName.toLowerCase() == 'a') { href = n.getAttribute('href') } n = n.parentNode }f.value = hrefroot.classList.add('linking')f.focus()}linkClose(root) {root.classList.remove('linking')surfaceOf(root).focus()sel = document.getSelection()if (root.mdRange != null) { sel.removeAllRanges() sel.addRange(root.mdRange) }}linkApply(root, remove) {f = root.querySelector('link-form input')href = remove ? '' : safeHref(f.value)linkClose(root)if (remove || f.value.trim() == '') { document.execCommand('unlink') }else if (href != '') {sel = document.getSelection()// the caret inside a link and no selection: the address of THAT link changes (mission 011; before, a second link was inserted into it)let an = sel.anchorNodelet inA = nullwhile (an != null && an != surfaceOf(root)) { if (an.nodeType == 1 && an.nodeName.toLowerCase() == 'a') { inA = an } an = an.parentNode }if (sel.isCollapsed && inA != null) { sel.selectAllChildren(inA) }if (sel.isCollapsed) { document.execCommand('insertHTML', false, escLink(href)) } else { document.execCommand('createLink', false, href) }}sync(root)}escLink(href) {box = document.createElement('div')a = el('a', href)a.setAttribute('href', href)box.appendChild(a)return box.innerHTML}// the parsed Markdown as html the browser can insert (built from elements, so every text is escaped)mdHtml(md) {box = document.createElement('div')parseInto(box, md)// a single paragraph is inserted inline: no extra blockif (box.childNodes.length == 1 && box.firstChild.nodeName.toLowerCase() == 'p') { return box.firstChild.innerHTML }return box.innerHTML}// typing rules at the caret: "# " "- " "1. " make a block; the typed marker is consumed (only the formatting stays). They work in a// paragraph, in a heading (an emptied heading keeps its level) and in a list item (a marker of the other list kind switches the list)blockRule(root, e) {sel = document.getSelection()if (!sel.isCollapsed || !inSurface(root)) { return false }let b = blockOf(root, sel.anchorNode)if (b == null) { return false }let tag = b.nodeName.toLowerCase()let inner = sel.anchorNodewhile (inner != null && inner != surfaceOf(root) && !(inner.nodeType == 1 && ['p', 'div', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'li'].indexOf(inner.nodeName.toLowerCase()) >= 0)) { inner = inner.parentNode }if (inner != null && inner != surfaceOf(root) && inner.nodeName.toLowerCase() != 'li') { b = inner tag = inner.nodeName.toLowerCase() }let item = sel.anchorNodewhile (item != null && item != surfaceOf(root) && item.nodeName.toLowerCase() != 'li') { item = item.parentNode }if (item == surfaceOf(root)) { item = null }let box = bif (item != null) {box = itemtag = item.parentNode.nodeName.toLowerCase()} else if (tag != 'p' && tag != 'div' && !(tag.length == 2 && tag.startsWith('h'))) { return false }r = sel.getRangeAt(0)pre = document.createRange()pre.selectNodeContents(box)pre.setEnd(r.endContainer, r.endOffset)before = clean(pre.toString())if (before != clean(box.textContent)) { return false }let cmd = ''let arg = ''if (item == null && before.length >= 1 && before.length <= 6 && before.replaceAll('#', '') == '') { cmd = 'formatBlock' arg = 'h' + before.length }if (before == '-' || before == '*' || before == '+') { cmd = 'insertUnorderedList' }if (before.length >= 2 && before.endsWith('.') && before.slice(0, before.length - 1).length < 9) {let digits = truelet k = 0while (k < before.length - 1) { if (!isDigit(before.slice(k, k + 1))) { digits = false } k = k + 1 }if (digits) { cmd = 'insertOrderedList' }}if (cmd == '') { return false }e.preventDefault()sel.selectAllChildren(box)document.execCommand('delete')// a list marker typed in a list of that kind is only consumedif (item != null && ((cmd == 'insertUnorderedList' && tag == 'ul') || (cmd == 'insertOrderedList' && tag == 'ol'))) { return true }if (item == null && tag != 'p' && tag != 'div' && cmd != 'formatBlock') { document.execCommand('formatBlock', false, 'p') }if (arg != '') { document.execCommand(cmd, false, arg) } else { document.execCommand(cmd) }return true}// a closing * _ ` typed: find the opener before the caret in the same text nodeinlineRule(root, e) {sel = document.getSelection()node = sel.anchorNodeif (!sel.isCollapsed || node == null || node.nodeType != 3 || !surfaceOf(root).contains(node)) { return null }if (inTag(root, ['code', 'pre'])) { return null }off = sel.anchorOffsett = node.data.slice(0, off)c = e.datalet tag = ''let start = -1let ends = ''if (c == '`') {let j = t.slice(0, off - 1).lastIndexOf('`')if (j >= 0 && off - 1 - j - 1 >= 1) { start = j tag = 'code' ends = t.slice(j + 1, off - 1) }}if (c == '*' && t.length >= 5 && t.endsWith('**')) {let j = t.slice(0, off - 2).lastIndexOf('**')let inner = j >= 0 ? t.slice(j + 2, off - 2) : ''if (j >= 0 && inner != '' && !isSpace(inner.slice(0, 1)) && !isSpace(inner.slice(inner.length - 1))) { start = j tag = 'strong' ends = inner }}if ((c == '*' || c == '_') && tag == '' && t.length >= 3 && !t.endsWith(c + c)) {let j = t.slice(0, off - 1).lastIndexOf(c)let inner = j >= 0 ? t.slice(j + 1, off - 1) : ''okStart = j >= 0 && (j == 0 || !isAlnum(t.slice(j - 1, j)) || c == '*') && t.slice(j - 1, j) != c && t.slice(j + 1, j + 2) != cif (okStart && inner != '' && !isSpace(inner.slice(0, 1)) && !isSpace(inner.slice(inner.length - 1))) { start = j tag = 'em' ends = inner }}if (tag == '') { return null }r = document.createRange()r.setStart(node, start)r.setEnd(node, off)sel.removeAllRanges()sel.addRange(r)document.execCommand('insertHTML', false, escHtml(ends, tag) + ZW)// Chrome pins the colour on the new element (`<strong style="color: …">`) when it equals the text around it (the black/white base// look, #15); the surface never carries styles of its ownfor (k of surfaceOf(root).querySelectorAll('[style]')) { k.removeAttribute('style') }}// ---- tables in the editor: typing one, moving between cells, trs; a table never merges with the text around it ----------cellOf(root, node) {s = surfaceOf(root)let n = nodewhile (n != null && n != s) {if (n.nodeName == 'TD' || n.nodeName == 'TH') { return n }n = n.parentNode}return null}inCell(root) {sel = document.getSelection()return sel.rangeCount > 0 && sel.anchorNode != null && cellOf(root, sel.anchorNode) != null}isBlank(node) { return clean(node.textContent).trim() == '' && (node.nodeType != 1 || node.querySelector('img') == null) }// the caret at the end of a cell (an empty cell: at its start, before its <br>)caretIn(cell, atEnd) {sel = document.getSelection()r = document.createRange()r.selectNodeContents(cell)r.collapse(!atEnd || isBlank(cell))sel.removeAllRanges()sel.addRange(r)}// a new empty row (the header's alignments) after `tr`; a header row gets its body firstnewRow(table, tr) {row = el('tr', null)for (h of cellsOf(table.querySelector('tr'))) { row.appendChild(cellEl('td', h.getAttribute('data-align') != null ? h.getAttribute('data-align') : '', '')) }let body = table.querySelector('tbody')if (body == null) { body = el('tbody', null) table.appendChild(body) }if (tr.parentNode.nodeName == 'THEAD') { body.insertBefore(row, body.firstChild) } else { body.insertBefore(row, tr.nextSibling) }return row}// an empty paragraph after a block (the one already there when it is empty), for the caretparaAfter(root, b) {n = b.nextSiblingif (n != null && n.nodeName == 'P' && isBlank(n)) { return n }p = el('p', null)p.appendChild(el('br', null))surfaceOf(root).insertBefore(p, n)return p}// the Table button: an empty table (a header row of two cells and one body row of two) after the block the caret is in (in an empty// paragraph: in its place), the caret in its first header cell. An empty table is written as a real pipe table with empty cells (header row, delimiter row, body row), so it survives the source switch, a save and a reload.tableInsert(root) {s = surfaceOf(root)sel = document.getSelection()b = sel.rangeCount > 0 && sel.anchorNode != null && inSurface(root) ? blockOf(root, sel.anchorNode) : nulltable = el('table', null)head = el('thead', null)tr = el('tr', null)tr.appendChild(cellEl('th', '', ''))tr.appendChild(cellEl('th', '', ''))head.appendChild(tr)table.appendChild(head)newRow(table, tr)if (b != null && b.parentNode == s && b.nodeName == 'P' && isBlank(b)) { s.replaceChild(table, b) }else if (b != null && b.parentNode == s) { s.insertBefore(table, b.nextSibling) }else { s.appendChild(table) }if (table.nextSibling == null) { paraAfter(root, table) }caretIn(tr.firstChild, false)sync(root)}// a row typed with its pipes into a cell (`| a | b |`, the way the Markdown is written): its cells go into this cell and the ones after// it (more than the row has: dropped); answer: the last cell filled, or the cell itself when the text is no pipe rowsplitRow(root, cell) {let txt = trimSp(cell.textContent)if (!txt.startsWith('|')) { return cell }let cs = rowCells(txt)let closed = txt.length > 1 && txt.endsWith('|') && !escapedAt(txt, txt.length - 1, 0)if (!closed && cs.length < 2) { return cell }let all = cellsOf(cell.parentNode)let at = 0while (at < all.length && all[at] != cell) { at = at + 1 }let k = 0let last = cellwhile (k < cs.length && at + k < all.length) {let c = all[at + k]while (c.firstChild != null) { c.removeChild(c.firstChild) }if (cs[k] == '') { c.appendChild(el('br', null)) } else { inline(c, unpipe(cs[k])) }last = ck = k + 1}return last}// Enter in a cell: a new empty row below; in an empty last row (not the header): the row goes, the caret leaves the tablerowEnter(root, typed) {cell = splitRow(root, typed)tr = cell.parentNodetable = tr.closest('table')trs = table.querySelectorAll('tr')empty = isBlank(tr)if (tr.parentNode.nodeName == 'TBODY' && trs[trs.length - 1] == tr && empty) {body = tr.parentNodebody.removeChild(tr)if (body.childNodes.length == 0) { table.removeChild(body) }p = paraAfter(root, table)document.getSelection().collapse(p, 0)} else { caretIn(newRow(table, tr).firstChild, false) }sync(root)}// Tab / Shift+Tab: the next / previous cell (the caret at its end); Tab in the last cell adds a rowcellTab(root, typed, back) {cell = back ? typed : splitRow(root, typed)table = cell.closest('table')cells = table.querySelectorAll('th, td')let i = 0while (i < cells.length && cells[i] != cell) { i = i + 1 }if (back) { if (i > 0) { caretIn(cells[i - 1], true) } return null }if (i + 1 < cells.length) { caretIn(cells[i + 1], true) return null }caretIn(newRow(table, cell.parentNode).firstChild, false)sync(root)}// the lines of a paragraph are its children between <br>s: [from, to) child indexes of its last line and the one before// (a trailing <br> the browser keeps at the end is not a line). Answer: [lastFrom, lastTo, prevFrom] (prevFrom -1 = no line before).lastLines(p) {kids = p.childNodeslet end = kids.lengthwhile (end > 0 && kids[end - 1].nodeName == 'BR') { end = end - 1 }let br = end - 1while (br >= 0 && kids[br].nodeName != 'BR') { br = br - 1 }let prev = -1if (br >= 0) {prev = br - 1while (prev >= 0 && kids[prev].nodeName != 'BR') { prev = prev - 1 }prev = prev + 1}return [br + 1, end, prev]}lineText(p, start, to) {let t = ''let i = startwhile (i < to) { t = t + p.childNodes[i].textContent i = i + 1 }return clean(t)}linePlain(p, start, to) {let i = startwhile (i < to) { if (p.childNodes[i].nodeType != 3) { return false } i = i + 1 }return true}// the header cells of a typed line: its nodes split at every `|` in the text (`\|` typed is a pipe in the cell); formatted parts// (bold, code, a link) go into their cell whole; outer pipes are optionalheadCells(p, start, to, aligns) {text = trimSp(lineText(p, start, to))cells = [el('th', null)]let i = startwhile (i < to) {let n = p.childNodes[i]if (n.nodeType == 3) {let s = clean(n.data)let buf = ''let k = 0while (k < s.length) {let c = s.slice(k, k + 1)if (c == BS && s.slice(k + 1, k + 2) == '|') { buf = buf + '|' k = k + 2 }else if (c == '|') {if (buf != '') { cells[cells.length - 1].appendChild(document.createTextNode(buf)) }buf = ''let th = el('th', null)cells.push(th)k = k + 1} else { buf = buf + c k = k + 1 }}if (buf != '') { cells[cells.length - 1].appendChild(document.createTextNode(buf)) }} else { cells[cells.length - 1].appendChild(n.cloneNode(true)) }i = i + 1}if (text.startsWith('|')) { cells.shift() }if (text.endsWith('|') && !escapedAt(text, text.length - 1, 0) && cells.length > 0) { cells.pop() }if (cells.length != aligns.length) { return null }let k2 = 0while (k2 < cells.length) {let cell = cells[k2]trimCell(cell)if (aligns[k2] != '') { cell.setAttribute('data-align', aligns[k2]) }k2 = k2 + 1}return cells}// leading / trailing spaces of a cell's first / last text go; an empty cell gets its <br>trimCell(cell) {while (cell.firstChild != null && cell.firstChild.nodeType == 3 && trimSp(cell.firstChild.data) == '') { cell.removeChild(cell.firstChild) }while (cell.lastChild != null && cell.lastChild.nodeType == 3 && trimSp(cell.lastChild.data) == '') { cell.removeChild(cell.lastChild) }if (cell.firstChild != null && cell.firstChild.nodeType == 3) {let d = cell.firstChild.datawhile (d.length > 0 && isSpace(d.slice(0, 1))) { d = d.slice(1) }cell.firstChild.data = d}if (cell.lastChild != null && cell.lastChild.nodeType == 3) {let d2 = cell.lastChild.datawhile (d2.length > 0 && isSpace(d2.slice(d2.length - 1))) { d2 = d2.slice(0, d2.length - 1) }cell.lastChild.data = d2}if (cell.childNodes.length == 0) { cell.appendChild(el('br', null)) }}// the children [start, end of the paragraph) go (the line before them loses its <br> too)cutLines(p, start) {let at = startif (at > 0 && p.childNodes[at - 1].nodeName == 'BR') { at = at - 1 }while (p.childNodes.length > at) { p.removeChild(p.lastChild) }}// Enter at the end of a typed delimiter row (`|---|:-:|`) under a header row (the line before, in this paragraph or the paragraph// before): the two lines become a table with an empty body row, the caret in its first celltableByEnter(root, b) {sel = document.getSelection()r = sel.getRangeAt(0)rest = document.createRange()rest.selectNodeContents(b)rest.setStart(r.endContainer, r.endOffset)if (clean(rest.toString()).trim() != '') { return false }ll = lastLines(b)if (!linePlain(b, ll[0], ll[1])) { return false }aligns = alignsOf(lineText(b, ll[0], ll[1]))if (aligns == null) { return false }let hp = blet hFrom = ll[2]let hTo = ll[0] - 1if (hFrom < 0) {hp = b.previousSiblingif (hp == null || hp.nodeName != 'P') { return false }hl = lastLines(hp)hFrom = hl[0]hTo = hl[1]}if (hTo <= hFrom || trimSp(lineText(hp, hFrom, hTo)) == '') { return false }cells = headCells(hp, hFrom, hTo, aligns)if (cells == null) { return false }table = el('table', null)head = el('thead', null)tr = el('tr', null)for (c of cells) { tr.appendChild(c) }head.appendChild(tr)table.appendChild(head)// the lines go: the delimiter (and, in the same paragraph, the header); an emptied paragraph goes toocutLines(b, hp == b ? hFrom : ll[0])if (hp != b) { b.parentNode.removeChild(b) cutLines(hp, hFrom) }if (isBlank(hp)) { hp.parentNode.replaceChild(table, hp) } else { hp.parentNode.insertBefore(table, hp.nextSibling) }row = newRow(table, tr)if (table.nextSibling == null) { paraAfter(root, table) }caretIn(row.firstChild, false)sync(root)return true}// a selection that reaches into or over a table: what is selected in a table is emptied (its cells stay), a table selected as a// whole goes; the text before and after it is cut on its own (it never joins the table). false = no table in the selection.cutAcross(root) {sel = document.getSelection()if (sel.rangeCount == 0 || sel.isCollapsed) { return false }r = sel.getRangeAt(0)c1 = cellOf(root, r.startContainer)c2 = cellOf(root, r.endContainer)if (c1 != null && c1 == c2) { return false }tables = []for (tq of surfaceOf(root).querySelectorAll('table')) { if (r.intersectsNode(tq)) { tables.push(tq) } }if (tables.length == 0) { return false }// the boundaries of the text outside the tables, taken before anything changescuts = []first = tables[0]last = tables[tables.length - 1]if (cellOf(root, r.startContainer) == null) { a = document.createRange() a.setStart(r.startContainer, r.startOffset) a.setEndBefore(first) cuts.push(a) }let i = 0while (i + 1 < tables.length) { let m = document.createRange() m.setStartAfter(tables[i]) m.setEndBefore(tables[i + 1]) cuts.push(m) i = i + 1 }if (cellOf(root, r.endContainer) == null) { z = document.createRange() z.setStartAfter(last) z.setEnd(r.endContainer, r.endOffset) cuts.push(z) }gone = []for (tb of tables) {let cells = tb.querySelectorAll('th, td')let head = document.createRange()head.setStart(cells[0], 0)let tail = document.createRange()tail.selectNodeContents(cells[cells.length - 1])tail.collapse(false)// compareBoundaryPoints: 0 = START_TO_START, 2 = END_TO_ENDif (r.compareBoundaryPoints(0, head) <= 0 && r.compareBoundaryPoints(2, tail) >= 0) { gone.push(tb) }else {for (c of cells) {if (r.intersectsNode(c)) {let part = document.createRange()part.selectNodeContents(c)if (c.contains(r.startContainer)) { part.setStart(r.startContainer, r.startOffset) }if (c.contains(r.endContainer)) { part.setEnd(r.endContainer, r.endOffset) }part.deleteContents()if (c.childNodes.length == 0 || isBlank(c)) { c.textContent = '' c.appendChild(el('br', null)) }}}}}for (cut of cuts) { cut.deleteContents() }// the caret: where the selection began (in a removed table: the block that takes its place)let at = nullfor (tg of gone) {if (tg.contains(r.startContainer)) { at = paraAfter(root, tg) }tg.parentNode.removeChild(tg)}s = surfaceOf(root)if (s.childNodes.length == 0) { np = el('p', null) np.appendChild(el('br', null)) s.appendChild(np) at = np }if (at != null) { sel.collapse(at, 0) } else { sel.collapse(r.startContainer, r.startOffset) }return true}// Backspace at the start of a cell: to the end of the cell before; Delete at the end of a cell: nothing; at the start of the block// after a table / the end of the block before one: never merged (an empty paragraph goes)tableDelete(root, back) {sel = document.getSelection()if (!sel.isCollapsed || !inSurface(root)) { return false }r = sel.getRangeAt(0)cell = cellOf(root, sel.anchorNode)let box = cellif (box == null) { box = blockOf(root, sel.anchorNode) }if (box == null) { return false }edge = document.createRange()edge.selectNodeContents(box)if (back) { edge.setEnd(r.startContainer, r.startOffset) } else { edge.setStart(r.endContainer, r.endOffset) }if (clean(edge.toString()) != '' || edge.cloneContents().querySelector('img') != null) { return false }if (cell != null) {if (back) {all = cell.closest('table').querySelectorAll('th, td')let i = 0while (i < all.length && all[i] != cell) { i = i + 1 }if (i > 0) { caretIn(all[i - 1], true) }}return true}next = back ? box.previousSibling : box.nextSiblingif (next == null || next.nodeName != 'TABLE') { return false }if (isBlank(box)) { box.parentNode.removeChild(box) sync(root) }if (back) { tail = next.querySelectorAll('th, td') caretIn(tail[tail.length - 1], true) }else if (box.parentNode == null) { caretIn(next.querySelector('th, td'), false) }return true}// the editing rules of tables, before the browser edits: true = handled (the browser's edit is cancelled)tableBefore(root, e) {t = e.inputTypeif (t.startsWith('delete') || t.startsWith('insert')) {if (cutAcross(root)) {if (t == 'insertText' && e.data != null) { document.execCommand('insertText', false, e.data) }sync(root)return true}}sel = document.getSelection()if (sel.rangeCount == 0 || sel.anchorNode == null || !inSurface(root)) { return false }cell = cellOf(root, sel.anchorNode)if (t == 'insertParagraph') {if (cell != null) { rowEnter(root, cell) return true }b = blockOf(root, sel.anchorNode)if (b != null && b.nodeName == 'P' && sel.isCollapsed) { return tableByEnter(root, b) }return false}// a cell is one lineif (t == 'insertLineBreak' && cell != null) { return true }if (t.startsWith('delete') && (t.endsWith('Backward') || t.endsWith('Forward'))) { return tableDelete(root, t.endsWith('Backward')) }return false}// ---- pasting: Markdown text (a table in it becomes a table), an HTML table (its cells' text), anything into a cell on one line// the inline html of one line of Markdown (null when it is not a plain paragraph)inlineHtml(md) {box = document.createElement('div')parseInto(box, md)if (box.childNodes.length == 1 && box.firstChild.nodeName == 'P') { return box.firstChild.innerHTML }return null}// blocks with a table in them are put in as elements at the caret (an editing command would pour a table into the paragraph): the// block the caret is in is split there, the new blocks go between its halves (after a list, a code block or a table)insertBlocks(root, box) {s = surfaceOf(root)sel = document.getSelection()if (!inSurface(root)) { s.focus() sel.selectAllChildren(s) sel.collapseToEnd() }if (!sel.isCollapsed) { document.execCommand('delete') }r = sel.getRangeAt(0)b = blockOf(root, sel.anchorNode)let ref = nullif (b == null) { ref = s.childNodes.item(sel.anchorOffset) }else if (['P', 'DIV', 'H1', 'H2', 'H3', 'H4', 'H5', 'H6'].indexOf(b.nodeName) >= 0) {tail = document.createRange()tail.selectNodeContents(b)tail.setStart(r.startContainer, r.startOffset)after = b.cloneNode(false)after.appendChild(tail.extractContents())ref = b.nextSiblingif (!isBlank(after)) { s.insertBefore(after, ref) ref = after }if (isBlank(b)) { s.removeChild(b) }} else { ref = b.nextSibling }let last = nullwhile (box.firstChild != null) { last = box.firstChild s.insertBefore(last, ref) }if (last == null) { return null }if (last.nodeName == 'TABLE') {if (last.nextSibling == null) { paraAfter(root, last) }cells = last.querySelectorAll('th, td')caretIn(cells[cells.length - 1], true)} else { sel.selectAllChildren(last) sel.collapseToEnd() }}// the alignment a pasted cell asks for (data-align, align or text-align)htmlAlign(c) {let v = c.getAttribute('data-align')if (v == null) { v = c.getAttribute('align') }if (v == null) { v = c.style.textAlign }v = v == null ? '' : v.toLowerCase()return v == 'left' || v == 'center' || v == 'right' ? v : ''}// a pasted HTML table as an editor table: every row (thead / tbody / tfoot) with its cells' text, the first row the header,// as many columns as the widest rowhtmlTable(t) {trs = t.rowslet cols = 0for (row of trs) { if (row.cells.length > cols) { cols = row.cells.length } }if (cols == 0) { return null }out = el('table', null)head = el('thead', null)body = el('tbody', null)let r = 0while (r < trs.length) {let tr = el('tr', null)let k = 0while (k < cols) {let src = k < trs[r].cells.length ? trs[r].cells[k] : nulllet first = k < trs[0].cells.length ? trs[0].cells[k] : nulllet cell = el(r == 0 ? 'th' : 'td', null)let al = first != null ? htmlAlign(first) : ''if (al != '') { cell.setAttribute('data-align', al) }let text = src != null ? trimSp(src.textContent.split(NL).join(' ')) : ''if (text == '') { cell.appendChild(el('br', null)) } else { cell.appendChild(document.createTextNode(text)) }tr.appendChild(cell)k = k + 1}if (r == 0) { head.appendChild(tr) } else { body.appendChild(tr) }r = r + 1}out.appendChild(head)if (body.childNodes.length > 0) { out.appendChild(body) }return out}// pasted HTML that holds a table: its tables as tables, every other text as plain text paragraphs (no other element is taken)htmlBlocks(node, box) {kids = node.childNodeslet i = 0while (i < kids.length) {let k = kids[i]if (k.nodeType == 3) {let p = box.lastChildif (p == null || p.nodeName != 'P') { p = el('p', null) box.appendChild(p) }p.appendChild(document.createTextNode(k.data.split(NL).join(' ')))} else if (k.nodeType == 1 && k.nodeName == 'TABLE') {let t = htmlTable(k)if (t != null) { box.appendChild(t) }} else if (k.nodeType == 1 && 'SCRIPT,STYLE,TEMPLATE,HEAD,TITLE,META,LINK,svg'.split(',').indexOf(k.nodeName) < 0) {let block = 'P,DIV,H1,H2,H3,H4,H5,H6,LI,UL,OL,PRE,BLOCKQUOTE,BR,TR,SECTION,ARTICLE,HEADER,FOOTER,DL,DT,DD'.split(',').indexOf(k.nodeName) >= 0if (block) { box.appendChild(el('p', null)) }htmlBlocks(k, box)if (block) { box.appendChild(el('p', null)) }}i = i + 1}}// ---- look: the component's own Style; the base look is black, white and the greys #555 #999 #ddd #f2f2f2 (shared/base.hl names them; README "Look"); every colour is a semantic token with its base value as fallback, `var(--color-…, #000)`, so an app that declares the tokens (layouts.worldapi.org's theme) restyles it. No frames: a border only where it means something (focus ring, drop zone)Style {'@keyframes md-editor-mount' = {'from' = { opacity = '.999' }to = { opacity = '1' }}mdEditor {position = 'relative'display = 'block'border = '0'borderRadius = '.5rem'background = 'var(--color-background-sunken, #f2f2f2)'color = 'var(--color-text, #000)'focusWithin {outline = '2px solid var(--color-accent, #555)'outlineOffset = '-1px'}nav {display = 'flex'flexWrap = 'wrap'gap = '.25rem'padding = '.35rem'borderBottom = '0'background = 'var(--color-surface, #ddd)'borderRadius = '.5rem .5rem 0 0'// a phone (E2): the toolbar is a grid of TWO EVEN ROWS (6 + 5 buttons; with `files = "off"` 5 + 5)@media {maxWidth = '40rem'display = 'grid'gridTemplateColumns = 'repeat(6, minmax(0, 1fr))'gap = '.25rem'}button {display = 'inline-flex'alignItems = 'center'justifyContent = 'center'font = 'inherit'fontSize = '.9rem'fontWeight = '600'minWidth = '2rem'minHeight = '2rem'padding = '.25rem .5rem'color = 'var(--color-text, #000)'background = 'transparent'border = '1px solid transparent'borderRadius = '.35rem'cursor = 'pointer'hover { background = 'var(--color-background, #fff)' }svg { display = 'block' }disabled {opacity = '.4'cursor = 'default'}}// the editor's code sets these classes (on, heading): no form for button.on / button.heading'button.on' {color = 'var(--color-accent-text, #fff)'background = 'var(--color-accent, #000)'}'button.heading' {display = 'inline-flex'alignItems = 'center'justifyContent = 'center'}'input.pick' { display = 'none' }}linkForm {display = 'none'gap = '.35rem'padding = '.35rem'borderBottom = '0'background = 'var(--color-surface, #ddd)'input {flex = '1'minWidth = '0'font = 'inherit'padding = '.3rem .5rem'color = 'var(--color-text, #000)'background = 'var(--color-background, #fff)'border = '0'borderRadius = '.35rem'}button {font = 'inherit'padding = '.3rem .7rem'color = 'var(--color-text, #000)'background = 'transparent'border = '0'borderRadius = '.35rem'cursor = 'pointer'}}article {display = 'block'minHeight = '1.5em'padding = '.6rem .8rem'outline = 'none'overflowWrap = 'anywhere'animation = 'md-editor-mount 1ms infinite'// THE FOCUS RING IS THE EDITOR'S ONLY: the surface and the source view never draw their own (a theme's :focus-visible would add a second rectangle)focus { outline = 'none' }focusVisible { outline = 'none' }}'.placeholder' {display = 'none'position = 'absolute'left = '.8rem'marginTop = '.6rem'pointerEvents = 'none'color = 'var(--color-text-muted, #555)'}footer {display = 'flex'justifyContent = 'flex-end'padding = '.3rem .5rem'borderTop = '0'button {font = 'inherit'fontSize = '.85rem'padding = '.2rem .6rem'color = 'var(--color-text-muted, #555)'background = 'transparent'border = '0'borderRadius = '.35rem'cursor = 'pointer'hover { color = 'var(--color-text, #000)' }}}textarea {display = 'none'boxSizing = 'border-box'width = '100%'minHeight = '2em'padding = '.6rem .8rem'font = '.9rem/1.5 ui-monospace, monospace'color = 'var(--color-text, #000)'background = 'transparent'border = '0'outline = 'none'resize = 'vertical'focus { outline = 'none' }focusVisible { outline = 'none' }}}// a phone: 44 px targets for the toolbar and the footer button. minWidth/minHeight are declarations here, but inside a rule a bare @media reads them as conditions, so the query stands beside the rules@media {maxWidth = '40rem'mdEditor {nav {button {minWidth = '0'minHeight = '2.75rem'padding = '.25rem 0'}}footer {button {fontSize = '.9375rem'minHeight = '2.75rem'padding = '.2rem .8rem'}}}}// NO FORM IN THE LANGUAGE for the rules below: a state class or data attribute on the editor's own element, a class on a button, :not, ::after, the child combinator, and every element the editor builds at run time (the rows of ul.files, the content of article) that its View does not hold'md-editor nav button.heading[data-level]:not([data-level=""])::after' {content = 'attr(data-level)'marginLeft = '.1rem'fontSize = '.7rem'lineHeight = '1'}'md-editor[data-files="off"] nav button.file' { display = 'none' }'md-editor.source nav button' {opacity = '.4'pointerEvents = 'none'}'md-editor ul.files' {display = 'none'margin = '0'padding = '.35rem .8rem'listStyle = 'none'borderBottom = '0'fontSize = '.85rem'}'md-editor ul.files:not(:empty)' { display = 'block' }'md-editor ul.files li' {display = 'flex'alignItems = 'center'gap = '.6rem'}'md-editor ul.files li span' {flex = '0 1 12rem'overflow = 'hidden'textOverflow = 'ellipsis'whiteSpace = 'nowrap'}'md-editor ul.files progress' {flex = '1'accentColor = 'var(--color-accent, #000)'}'md-editor ul.files li.error' { color = 'var(--color-danger, #000)' }'md-editor.linking link-form' { display = 'flex' }'md-editor.source article' { display = 'none' }'md-editor.md-empty:not(.source) .placeholder' { display = 'block' }'md-editor article > :first-child' { marginTop = '0' }'md-editor article > :last-child' { marginBottom = '0' }'md-editor article h1, md-editor article h2, md-editor article h3, md-editor article h4, md-editor article h5, md-editor article h6' {margin = '1rem 0 .5rem'lineHeight = '1.25'color = 'var(--color-text-strong, #000)'}'md-editor article h1' { fontSize = '1.6rem' }'md-editor article h2' { fontSize = '1.35rem' }'md-editor article h3' { fontSize = '1.15rem' }'md-editor article h4, md-editor article h5, md-editor article h6' { fontSize = '1rem' }'md-editor article p' { margin = '0 0 .7rem' }'md-editor article ul, md-editor article ol' {margin = '0 0 .7rem'paddingLeft = '1.5rem'}'md-editor article img' {display = 'block'maxWidth = '100%'height = 'auto'margin = '.3rem 0'borderRadius = '.3rem'}'md-editor article strong' { color = 'var(--color-text-strong, #000)' }'md-editor article a' {color = 'var(--color-accent, #000)'textDecoration = 'underline'}'md-editor article code' {padding = '0 .25rem'fontFamily = 'ui-monospace, monospace'fontSize = '.9em'background = 'var(--color-surface, #ddd)'borderRadius = '.25rem'}// tables take the look of the page's theme; the editor only makes them scroll sideways and keeps a word whole'md-editor article table' {display = 'block'maxWidth = '100%'overflowX = 'auto'}'md-editor article th, md-editor article td' {textAlign = 'start'verticalAlign = 'top'minWidth = '2.5rem'overflowWrap = 'normal'wordBreak = 'normal'}// the :where() rules are the plain fallback where no theme styles tables':where(md-editor article table)' {margin = '0 0 .7rem'borderCollapse = 'collapse'}':where(md-editor article th, md-editor article td)' { padding = '.3rem .6rem' }':where(md-editor article th)' { fontWeight = '700' }'md-editor article [data-align="left"]' { textAlign = 'left' }'md-editor article [data-align="center"]' { textAlign = 'center' }'md-editor article [data-align="right"]' { textAlign = 'right' }'md-editor article pre' {margin = '0 0 .7rem'padding = '.5rem .7rem'fontFamily = 'ui-monospace, monospace'fontSize = '.9rem'whiteSpace = 'pre-wrap'background = 'var(--color-surface, #ddd)'border = '0'borderRadius = '.4rem'}'md-editor.source textarea' { display = 'block' }// readonly: the formatted text alone, on the page's own background'md-editor[data-readonly="true"]' {background = 'transparent'borderRadius = '0'}'md-editor[data-readonly="true"]:focus-within' { outline = 'none' }'md-editor[data-readonly="true"] nav, md-editor[data-readonly="true"] link-form, md-editor[data-readonly="true"] ul.files, md-editor[data-readonly="true"] .placeholder, md-editor[data-readonly="true"] textarea, md-editor[data-readonly="true"] footer' { display = 'none' }'md-editor[data-readonly="true"] article' {minHeight = '0'padding = '0'}'md-editor article th' {@media {maxWidth = '40rem'fontSize = '1rem'}}}// The hidden input `name` carries the value in a form; the article is the surface; the textarea is the source view (a value shown// only while it is on). The rendered parts never change after the first render, so the framework leaves the hand-built content alone.View {mdEditor { 'data-readonly' = readonly 'data-files' = files 'data-value' = valuenav {button { type = "button" class = "bold" title = "Bold (Ctrl+B)" 'aria-label' = "Bold (Ctrl+B)" Icon { name = "bold" } on mousedown(e) { e.preventDefault() } on click(e) { emit mdTool(e, 'bold') } }button { type = "button" class = "italic" title = "Italic (Ctrl+I)" 'aria-label' = "Italic (Ctrl+I)" Icon { name = "italic" } on mousedown(e) { e.preventDefault() } on click(e) { emit mdTool(e, 'italic') } }button { type = "button" class = "code" title = "Code (Ctrl+E)" 'aria-label' = "Code (Ctrl+E)" Icon { name = "code" } on mousedown(e) { e.preventDefault() } on click(e) { emit mdTool(e, 'code') } }button { type = "button" class = "link" title = "Link (Ctrl+K)" 'aria-label' = "Link (Ctrl+K)" Icon { name = "link" } on mousedown(e) { e.preventDefault() } on click(e) { emit mdTool(e, 'link') } }button { type = "button" class = "heading" title = "Heading: paragraph, H1, H2, H3" 'aria-label' = "Heading: paragraph, H1, H2, H3" Icon { name = "heading" } on mousedown(e) { e.preventDefault() } on click(e) { emit mdTool(e, 'heading') } }button { type = "button" class = "ul" title = "Bulleted list" 'aria-label' = "Bulleted list" Icon { name = "ul" } on mousedown(e) { e.preventDefault() } on click(e) { emit mdTool(e, 'ul') } }button { type = "button" class = "ol" title = "Numbered list" 'aria-label' = "Numbered list" Icon { name = "ol" } on mousedown(e) { e.preventDefault() } on click(e) { emit mdTool(e, 'ol') } }button { type = "button" class = "pre" title = "Code block" 'aria-label' = "Code block" Icon { name = "block" } on mousedown(e) { e.preventDefault() } on click(e) { emit mdTool(e, 'pre') } }button { type = "button" class = "table" title = "Table" 'aria-label' = "Table" Icon { name = "table" } on mousedown(e) { e.preventDefault() } on click(e) { emit mdTool(e, 'table') } }button { type = "button" class = "file" title = "Add files or images (or drop / paste them)" 'aria-label' = "Add files or images (or drop / paste them)" Icon { name = "file" } on mousedown(e) { e.preventDefault() } on click(e) { emit mdPick(e) } }input { type = "file" class = "pick" multiple = "multiple" on change(e) { emit mdPicked(e) } }button { type = "button" class = "undo" title = "Undo" 'aria-label' = "Undo" Icon { name = "undo" } on mousedown(e) { e.preventDefault() } on click(e) { emit mdTool(e, 'undo') } }button { type = "button" class = "redo" title = "Redo" 'aria-label' = "Redo" Icon { name = "redo" } on mousedown(e) { e.preventDefault() } on click(e) { emit mdTool(e, 'redo') } }}linkForm {input { type = "text" placeholder = "https://…" autocomplete = "off" on keydown(e) { emit mdLinkKey(e) } }button { type = "button" "Apply" on click(e) { emit mdLinkSubmit(e) } }button { type = "button" title = "Remove the link" "Remove" on click(e) { emit mdLinkRemove(e) } }}ul { class = "files" 'aria-live' = "polite" }span { class = "placeholder" placeholder }article { style = surfaceStyle contenteditable = editable role = surfaceRole tabindex = surfaceTab on animationiteration(e) { emit mdMount(e) } on focus(e) { emit mdMount(e) } on pointerdown(e) { emit mdMount(e) } on input(e) { emit mdInput(e) } on beforeinput(e) { emit mdBefore(e) } on keydown(e) { emit mdKey(e) } on paste(e) { emit mdPaste(e) } on copy(e) { emit mdCopy(e) } on cut(e) { emit mdCut(e) } on drop(e) { emit mdDrop(e) } on click(e) { emit mdClick(e) } on blur(e) { emit mdBlur(e) } }textarea { style = sourceStyle rows = rows spellcheck = "false" on input(e) { emit mdSourceInput(e) } }input { class = "value" type = "hidden" name = name value = value }footer { button { type = "button" class = "source-switch" on click(e) { emit mdSource(e) } "Markdown source" } }}}// Built once: by the 100 ms animation, or — in a tab opened in the background, where Chrome runs no animations until it is shown — by the// first focus / pointer-down / key, whichever comes first (mission 011 (c): keys typed at once after showing the tab landed in an unbuilt surface).// An editor the framework puts into the page LATER (a comment row built anew after a push) is built at once (microtasks), before the// browser paints: waiting 100 ms for the animation showed an EMPTY text for that long, longer under load (F5, hybriel#211: the gate caught// the empty surface of the new row). The first mounted editor starts one observer for the page (`watchPage`) that mounts every added one.on mdMount(e) {let root = rootOf(e.target)mountRoot(root)mountAll(document.body)watchPage()}watchPage() {if (window.mdWatching == true) { return null }window.mdWatching = truenew MutationObserver((recs) => {for (r of recs) {for (n of r.addedNodes) { if (n.nodeType == 1 && n.closest('md-editor article') == null) { mountAll(n) } }}}).observe(document.body, { childList = true, subtree = true })}mountAll(n) {if (n.matches('md-editor')) { mountRoot(n) }for (m of n.querySelectorAll('md-editor')) { mountRoot(m) }}mountRoot(root) {let s = surfaceOf(root)if (s == null) { return null }if (root.mdMounted == true) { rebuilt(root) return null }root.mdMounted = trueroot.mdSurface = ss.style.animationName = 'none'// a value that changes from outside after this build is loaded again; a surface the framework put in anew is drawn at oncenew MutationObserver((recs) => { followValue(root) }).observe(root, { attributes = true, attributeFilter = ['data-value'] })new MutationObserver((recs) => { rebuilt(root) }).observe(root, { childList = true })if (root.getAttribute('data-readonly') == 'true') { load(root, fieldOf(root).value) return null }document.execCommand('defaultParagraphSeparator', false, 'p')document.execCommand('styleWithCSS', false, false)// TEXT TYPED BEFORE THE BUILD: the server sends the surface already editable, and the page's scripts need a moment to start, so keys// pressed in that moment land in the bare surface (no handler saw them, the field does not hold them) and the build below would// empty it. The surface has no content of its own before this build, so anything in it was typed: it is kept, after the start value.let typed = ''if (s.textContent.trim() != '') { typed = clean(s.innerText).trim() }let start = fieldOf(root).valueif (typed != '') { start = start == '' ? typed : start + NL + NL + typed }load(root, start)sourceOf(root).value = startif (typed != '') { sync(root) }document.addEventListener('selectionchange', () => { updateBar(root) })// focus came before the build (it emptied the surface): the caret goes to the end of the textif (s.contains(document.activeElement) || document.activeElement == s) {last = s.lastChildif (last != null) { document.getSelection().collapse(last, last.textContent == '' ? 0 : last.childNodes.length) }}}on mdInput(e) {e.stopPropagation()root = rootOf(e.target)// text typed before the editor was built is taken in by the build (it keeps all of it); writing it to the field here as well would double itif (root.mdMounted != true) { mountRoot(root) return null }s = surfaceOf(root)// an emptied surface gets its paragraph backif (s.childNodes.length == 0) {np = document.createElement('p')np.appendChild(document.createElement('br'))s.appendChild(np)document.getSelection().collapse(np, 0)}if (e.inputType == 'insertText' && (e.data == '*' || e.data == '_' || e.data == '`')) { inlineRule(root, e) }sync(root)updateBar(root)}on mdBefore(e) {root = rootOf(e.target)if (tableBefore(root, e)) { e.preventDefault() updateBar(root) return null }if (e.inputType == 'insertText' && e.data == ' ') { blockRule(root, e) }}on mdKey(e) {root = rootOf(e.target)if (root.mdMounted != true) { mountRoot(root) }mod = e.ctrlKey || e.metaKey// in a table: Tab / Shift+Tab move between the cells; a cell takes no block (heading, list, code block)if (inCell(root)) {if (e.key == 'Tab' && !mod && !e.altKey) { e.preventDefault() cellTab(root, cellOf(root, document.getSelection().anchorNode), e.shiftKey) updateBar(root) return null }if ((mod && e.altKey && (e.code == 'KeyC' || e.code.startsWith('Digit'))) || (mod && e.shiftKey && (e.key == '8' || e.key == '*' || e.key == '7' || e.key == '&'))) { e.preventDefault() return null }}if (mod && !e.shiftKey && !e.altKey && (e.key == 'k' || e.key == 'K')) { e.preventDefault() linkOpen(root) return null }if (mod && !e.shiftKey && !e.altKey && (e.key == 'e' || e.key == 'E')) { e.preventDefault() codeToggle(root) sync(root) return null }if (mod && e.shiftKey && (e.key == '8' || e.key == '*')) { e.preventDefault() blockToggle(root, 'ul', 'insertUnorderedList') sync(root) return null }if (mod && e.shiftKey && (e.key == '7' || e.key == '&')) { e.preventDefault() blockToggle(root, 'ol', 'insertOrderedList') sync(root) return null }if (mod && e.altKey && e.code == 'KeyC') { e.preventDefault() blockToggle(root, 'pre', '') sync(root) return null }if (mod && e.altKey && e.code == 'Digit0') { e.preventDefault() document.execCommand('formatBlock', false, 'p') sync(root) return null }if (mod && e.altKey && (e.code == 'Digit1' || e.code == 'Digit2' || e.code == 'Digit3')) { e.preventDefault() document.execCommand('formatBlock', false, 'h' + e.code.slice(5, 6)) sync(root) return null }// Ctrl+Enter sends the form the editor sits inif (mod && e.key == 'Enter') {e.preventDefault()form = root.closest('form')if (form != null) { form.requestSubmit() }return null}// Backspace at the very start of a heading / list item / code block turns it into a paragraphif (e.key == 'Backspace' && document.getSelection().isCollapsed && inSurface(root)) {let sel = document.getSelection()let b = blockOf(root, sel.anchorNode)if (b != null && 'h1,h2,h3,h4,h5,h6,ul,ol,pre'.split(',').indexOf(b.nodeName.toLowerCase()) >= 0) {r = sel.getRangeAt(0)pre = document.createRange()pre.selectNodeContents(b)pre.setEnd(r.endContainer, r.endOffset)if (pre.toString() == '') {e.preventDefault()tag = b.nodeName.toLowerCase()if (tag == 'ul') { document.execCommand('insertUnorderedList') }else if (tag == 'ol') { document.execCommand('insertOrderedList') }else { document.execCommand('formatBlock', false, 'p') }sync(root)return null}}}// Enter on an empty last line of a code block (Enter twice at its end) leaves the block: a paragraph follows (mission 011; before there was no key out of a last code block)if (e.key == 'Enter' && !mod && !e.shiftKey && inTag(root, ['pre']) && document.getSelection().isCollapsed) {let xsel = document.getSelection()let xb = blockOf(root, xsel.anchorNode)if (xb != null && xb.nodeName == 'PRE') {let xr = xsel.getRangeAt(0)let xrest = document.createRange()xrest.setStart(xr.endContainer, xr.endOffset)xrest.setEnd(xb, xb.childNodes.length)let xkids = xb.childNodesif (xrest.toString() == '' && xkids.length >= 2 && xkids[xkids.length - 1].nodeName == 'BR' && xkids[xkids.length - 2].nodeName == 'BR') {e.preventDefault()xb.removeChild(xkids[xkids.length - 1])let xnp = el('p', null)xnp.appendChild(el('br', null))xb.parentNode.insertBefore(xnp, xb.nextSibling)if (clean(xb.textContent) == '') { xb.parentNode.removeChild(xb) }xsel.collapse(xnp, 0)sync(root)updateBar(root)return null}}}// ``` at the start of a line + Enter opens a code blockif (e.key == 'Enter' && !mod && !e.shiftKey && !inTag(root, ['pre'])) {let sel = document.getSelection()let b = sel.anchorNode != null ? blockOf(root, sel.anchorNode) : nullif (b != null && b.nodeName.toLowerCase() == 'p' && sel.isCollapsed && (clean(b.textContent).startsWith('```') || clean(b.textContent).startsWith('~~~')) && clean(b.textContent).replaceAll('`', '').replaceAll('~', '') == '') {e.preventDefault()sel.selectAllChildren(b)document.execCommand('delete')document.execCommand('formatBlock', false, 'pre')sync(root)}}}on mdTool(e, tool) {root = rootOf(e.target)s = surfaceOf(root)if (!inSurface(root)) { s.focus() }// a cell takes no blockif (inCell(root) && (tool == 'heading' || tool == 'ul' || tool == 'ol' || tool == 'pre')) { return null }if (tool == 'table') { if (!inCell(root)) { tableInsert(root) } updateBar(root) return null }if (tool == 'bold') { document.execCommand('bold') }if (tool == 'italic') { document.execCommand('italic') }if (tool == 'code') { codeToggle(root) }if (tool == 'link') { linkOpen(root) return null }if (tool == 'heading') { headingCycle(root) }if (tool == 'ul') { blockToggle(root, 'ul', 'insertUnorderedList') }if (tool == 'ol') { blockToggle(root, 'ol', 'insertOrderedList') }if (tool == 'pre') { blockToggle(root, 'pre', '') }if (tool == 'undo') { document.execCommand('undo') }if (tool == 'redo') { document.execCommand('redo') }sync(root)updateBar(root)}on mdLinkSubmit(e) { linkApply(rootOf(e.target), false) }on mdLinkRemove(e) { linkApply(rootOf(e.target), true) }on mdLinkKey(e) {if (e.key == 'Escape') { e.preventDefault() linkClose(rootOf(e.target)) }if (e.key == 'Enter') { e.preventDefault() linkApply(rootOf(e.target), false) }}// pasted / dropped text is read as Markdown (rich HTML is not taken: only its plain text — except a table, see mdPaste); a table in it// is put in as elements; into a cell everything goes on one lineinsertMarkdown(root, text) {if (inTag(root, ['pre'])) { document.execCommand('insertText', false, text) return null }cutAcross(root)if (inCell(root)) {
Only the first lines are shown.
Branches
Latest commits
- 519b56e9styles.hl: Style in the language's form (nested like the View, one declaration per line, bare @media)mre
- 29f63d01md-editor: Style in the language's form (nested like the View, one declaration per line, bare @media)mre
- 869f49c7files-upload: Style in the language's form (nested like the View, one declaration per line, bare @media)mre
- f60dab20month-view: Style in the language's form (nested like the View, one declaration per line, bare @media)mre
- 5b3c349aRe-vendor to Hybriel set day35 (cb9e480d): plugins core and web sources, README vendoring notemre
- 3449b117components: a startup error prints its message before exit 1 (hybriel#247)mre
- 59704ce1Merge branch 'n5b-pipes'mre
- 23b9164aMdEditor: a clipboard whose text is only the names or file:// paths of its files (a file manager copy) is about the files, as before; any other text wins (tickets#49); gate casesmre
- b0f1ec28MdEditor: a clipboard with text always pastes the text, also when a picture is on it too (a spreadsheet or office app), files on or off; a picture alone still goes to the files; real Ctrl+V gate tests/md-paste-files.mjs (tickets#49)mre
- ad4e929bMdEditor: pipe rows without a delimiter row are a table (first row = header, short rows padded, written back without an invented | --- | line) (notes#5)mre
- 4bd11128MdEditor: the Table button's empty table is written as a real pipe table (empty cells), so it survives the source switch, a save and a reload (notes#7)mre
- 7437e32bMdEditor draws its surface at once when claimed from server HTML: 1 ms mount animation, the first editor mounts all editors of the pagemre
- 5de0264cRe-vendor onto Hybriel master acaceaf3 (set-day27b): binary, lib and plugins; exit 1 on a startup fault; .gitignore binmre
- 79c77e7dMerge sb3-standby: components deploys through its standbymre
- c5442043components: no jobs switch needed in the standbymre
- 8d2fb24ccomponents: a standby container (port 45016, profile standby); deploy hands over through standby-swap.sh without a gapmre
- c2834dd3Merge mr-fixes: media player state after a queue pick, Range handling, cover-less audio, accessibility labelsmre
- 354fe3c6Media player: audio without a cover starts and shows its time (the mount tick sits on the seek bar, which every item has); the speed button names the current speed, the seek slider says its time in words; a gate page for the first render on cover-less audio and a fourth demo queue item without a covermre
- ee4aee1eMedia player: a new queue item shows its own speed, mute, play state and time and starts when asked, also for two videos in a row; the media route reads suffix ranges and ignores range lists and garbage instead of answering 500; stronger gate checks (the 10 percent drag, the played bar, the queue tap)mre
- 9a4f9b31Merge mp-player: media served from the committed filesmre