notes
All repositories: gitoria
76.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 100 ms CSS animation on the surface fires `animationiteration` once the page is live, and that hands the// editor its first content (the mount hook turns the animation off again). 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).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'String surfaceStyle = '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 table starting at line i: [alignments, header cells], or nulltableAt(lines, i) {if (i + 1 >= lines.length || lines[i].trim() == '') { return null }aligns = alignsOf(lines[i + 1])if (aligns == null) { return null }cells = rowCells(lines[i])if (cells.length != aligns.length) { return null }return [aligns, cells]}// 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) {t = el('table', null)head = el('thead', null)body = el('tbody', null)let r = 0while (r < src.length) {if (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.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 = i + 2while (j < lines.length && lines[j].trim() != '' && !startsBlock(lines[j])) { j = j + 1 }box.appendChild(tableOf(lines.slice(i, j), tb[0]))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 any = falselet r = 0while (r < trs.length) {let cs = cellsOf(trs[r])let k = 0while (k < cols) {let m = k < cs.length ? cellMd(cs[k]) : ''if (m != '') { any = true }md.push(m)k = k + 1}r = r + 1}if (!any) { return '' }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) {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 = mdf.dispatchEvent(new Event('input', { bubbles = true }))}}// 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.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('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.textContent = level != '' ? level : 'H' 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}// 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, cell) {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, cell, back) {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' } }'md-editor' { position = 'relative' display = 'block' border = '0' borderRadius = '.5rem' background = 'var(--color-background-sunken, #f2f2f2)' color = 'var(--color-text, #000)' }'md-editor:focus-within' { outline = '2px solid var(--color-accent, #555)' outlineOffset = '-1px' }'md-editor nav' { display = 'flex' flexWrap = 'wrap' gap = '.25rem' padding = '.35rem' borderBottom = '0' background = 'var(--color-surface, #ddd)' borderRadius = '.5rem .5rem 0 0' }'md-editor nav button' { font = 'inherit' fontSize = '.9rem' fontWeight = '600' minWidth = '2rem' padding = '.25rem .5rem' color = 'var(--color-text, #000)' background = 'transparent' border = '1px solid transparent' borderRadius = '.35rem' cursor = 'pointer' }'md-editor nav button:hover' { background = 'var(--color-background, #fff)' }'md-editor nav button.on' { color = 'var(--color-accent-text, #fff)' background = 'var(--color-accent, #000)' }'md-editor nav button.italic' { fontStyle = 'italic' }'md-editor nav button.code' { fontFamily = 'ui-monospace, monospace' }'md-editor[data-files="off"] nav button.file' { display = 'none' }'md-editor nav button:disabled' { opacity = '.4' cursor = 'default' }'md-editor.source nav button' { opacity = '.4' pointerEvents = 'none' }'md-editor nav input.pick' { display = 'none' }// a phone: ONE toolbar row (it scrolls sideways; contain: inline-size so its long row never widens a grid or flex parent), every button a 44 px target'@media (max-width: 40rem)' {'md-editor nav' { flexWrap = 'nowrap' overflowX = 'auto' contain = 'inline-size' }'md-editor nav button' { flex = '0 0 auto' minWidth = '2.75rem' minHeight = '2.75rem' }}'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 link-form' { display = 'none' gap = '.35rem' padding = '.35rem' borderBottom = '0' background = 'var(--color-surface, #ddd)' }'md-editor.linking link-form' { display = 'flex' }'md-editor link-form input' { flex = '1' minWidth = '0' font = 'inherit' padding = '.3rem .5rem' color = 'var(--color-text, #000)' background = 'var(--color-background, #fff)' border = '0' borderRadius = '.35rem' }'md-editor link-form button' { font = 'inherit' padding = '.3rem .7rem' color = 'var(--color-text, #000)' background = 'transparent' border = '0' borderRadius = '.35rem' cursor = 'pointer' }'md-editor article' { display = 'block' minHeight = '1.5em' padding = '.6rem .8rem' outline = 'none' overflowWrap = 'anywhere' animation = 'md-editor-mount 100ms infinite' }'md-editor.source article' { display = 'none' }'md-editor .placeholder' { display = 'none' position = 'absolute' left = '.8rem' marginTop = '.6rem' pointerEvents = 'none' color = 'var(--color-text-muted, #555)' }'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' }'md-editor article table' { display = 'block' maxWidth = '100%' overflowX = 'auto' margin = '0 0 .7rem' borderCollapse = 'collapse' }'md-editor article th, md-editor article td' { padding = '.3rem .6rem' border = '1px solid var(--color-border, #999)' textAlign = 'start' verticalAlign = 'top' minWidth = '2.5rem' overflowWrap = 'normal' wordBreak = 'normal' }'md-editor article th' { fontWeight = '700' color = 'var(--color-text-strong, #000)' }'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 footer' { display = 'flex' justifyContent = 'flex-end' padding = '.3rem .5rem' borderTop = '0' }'md-editor footer button' { font = 'inherit' fontSize = '.85rem' padding = '.2rem .6rem' color = 'var(--color-text-muted, #555)' background = 'transparent' border = '0' borderRadius = '.35rem' cursor = 'pointer' }'md-editor footer button:hover' { color = 'var(--color-text, #000)' }'md-editor 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' }'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' }}// 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' = filesnav {button { type = "button" class = "bold" title = "Bold (Ctrl+B)" "B" on mousedown(e) { e.preventDefault() } on click(e) { emit mdTool(e, 'bold') } }button { type = "button" class = "italic" title = "Italic (Ctrl+I)" "I" on mousedown(e) { e.preventDefault() } on click(e) { emit mdTool(e, 'italic') } }button { type = "button" class = "code" title = "Code (Ctrl+E)" "<>" on mousedown(e) { e.preventDefault() } on click(e) { emit mdTool(e, 'code') } }button { type = "button" class = "link" title = "Link (Ctrl+K)" "Link" on mousedown(e) { e.preventDefault() } on click(e) { emit mdTool(e, 'link') } }button { type = "button" class = "heading" title = "Heading: paragraph, H1, H2, H3" "H" on mousedown(e) { e.preventDefault() } on click(e) { emit mdTool(e, 'heading') } }button { type = "button" class = "ul" title = "Bulleted list" "• List" on mousedown(e) { e.preventDefault() } on click(e) { emit mdTool(e, 'ul') } }button { type = "button" class = "ol" title = "Numbered list" "1. List" on mousedown(e) { e.preventDefault() } on click(e) { emit mdTool(e, 'ol') } }button { type = "button" class = "pre" title = "Code block" "Block" on mousedown(e) { e.preventDefault() } on click(e) { emit mdTool(e, 'pre') } }button { type = "button" class = "file" title = "Add files or images (or drop / paste them)" "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" "↶" on mousedown(e) { e.preventDefault() } on click(e) { emit mdTool(e, 'undo') } }button { type = "button" class = "redo" title = "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 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).on mdMount(e) {s = e.targetroot = rootOf(s)if (root.mdMounted == true) { return null }root.mdMounted = trues.style.animationName = 'none'if (root.getAttribute('data-readonly') == 'true') { load(root, fieldOf(root).value) return null }document.execCommand('defaultParagraphSeparator', false, 'p')document.execCommand('styleWithCSS', false, false)load(root, fieldOf(root).value)sourceOf(root).value = fieldOf(root).valuedocument.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)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)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 == '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)) {one = trimSp(text.split(NL).join(' '))if (one == '') { return null }html = inlineHtml(one)if (html != null) { document.execCommand('insertHTML', false, html) } else { document.execCommand('insertText', false, one) }return null}box = el('div', null)parseInto(box, text)if (box.querySelector('table') != null) { insertBlocks(root, box) return null }document.execCommand('insertHTML', false, mdHtml(text))}on mdPaste(e) {e.preventDefault()root = rootOf(e.target)// files = "off": pasted files are the page's (they bubble on to a FilesUpload around the editor)if (e.clipboardData.files.length > 0) {if (root.getAttribute('data-files') != 'off') { attach(root, e.clipboardData.files, null) }return null}// copied HTML with a table in it (a spreadsheet, a web page): its tables become tables (their cells' text), the rest plain texthtml = e.clipboardData.getData('text/html')if (!inCell(root) && !inTag(root, ['pre']) && html.toLowerCase().indexOf('<table') >= 0) {// an inert document (no browsing context: it runs no script and loads nothing); hl:web compiles no `new DOMParser()` (repro// .scratch/w004/gap-domparser/)doc = document.implementation.createHTMLDocument('')doc.body.innerHTML = htmlbox = el('div', null)htmlBlocks(doc.body, box)if (box.querySelector('table') != null) {insertMarkdown(root, toMarkdown(box))sync(root)return null}}// a Windows clipboard ends its lines with CR LF: the CRs go (in a cell or a code block too)insertMarkdown(root, e.clipboardData.getData('text/plain').replaceAll(CR, ''))sync(root)}on mdDrop(e) {e.preventDefault()root = rootOf(e.target)if (e.dataTransfer.files.length > 0) {if (root.getAttribute('data-files') == 'off') { return null }at = document.caretRangeFromPoint(e.clientX, e.clientY)attach(root, e.dataTransfer.files, at)return null}text = e.dataTransfer.getData('text/plain')if (text != '') { insertMarkdown(root, text) sync(root) }}// ---- files and images: dropped, pasted or chosen files go to the app through `emit server mdUpload(files)` (the framework sends them// over HTTP with progress); the app stores them and answers the addresses; each lands in the text as  (an image) or// [name](address). Progress comes back as `uploadProgress` and is shown under the toolbar.fileRow(root, p) {list = root.querySelector('ul.files')let li = list.children[p.index]if (li == null) {li = document.createElement('li')li.appendChild(el('span', p.name))li.appendChild(document.createElement('progress'))list.appendChild(li)}bar = li.querySelector('progress')bar.max = p.sizebar.value = p.sent}on client uploadProgress(p) {for (root of document.querySelectorAll('md-editor.uploading')) { fileRow(root, p) }}attachMd(names, kinds, urls) {out = []let i = 0while (i < urls.length) {let label = names[i].replaceAll('[', '').replaceAll(']', '')let u = urls[i].replaceAll(')', '%29').replaceAll(' ', '%20')if (urls[i] != '') { out.push((kinds[i] ? '!' : '') + '[' + label + '](' + u + ')') }i = i + 1}return out.join(NL + NL)}attach(root, files, at) {s = surfaceOf(root)sel = document.getSelection()let range = atif (range == null && inSurface(root)) { range = sel.getRangeAt(0).cloneRange() }list = []names = []kinds = []let k = 0while (k < files.length) { list.push(files[k]) names.push(files[k].name) kinds.push(files[k].type.startsWith('image/')) k = k + 1 }box = root.querySelector('ul.files')box.textContent = ''root.classList.add('uploading')root.classList.remove('failed')urls = emit server mdUpload(list)root.classList.remove('uploading')if (urls == null || urls.length != list.length) {root.classList.add('failed')box.textContent = ''li = el('li', 'The upload failed.')li.className = 'error'box.appendChild(li)return null}box.textContent = ''s.focus()if (range != null && s.contains(range.startContainer)) { sel.removeAllRanges() sel.addRange(range) }else { sel.selectAllChildren(s) sel.collapseToEnd() }md = attachMd(names, kinds, urls)if (md == '') { return null }// inside a list item (or at the end of the surface, where the caret sits in the last item) the block would be glued to the// item's text: it is put on its own after the list, as elements (an editing command would join it to the item)let top = nullif (sel.anchorNode == s) { top = s.childNodes[sel.anchorOffset - 1 >= 0 ? sel.anchorOffset - 1 : 0] }else if (sel.anchorNode != null && s.contains(sel.anchorNode)) { top = blockOf(root, sel.anchorNode) }if (top != null && (top.nodeName == 'UL' || top.nodeName == 'OL')) {tmp = document.createElement('div')parseInto(tmp, md)ref = top.nextSiblingwhile (tmp.firstChild != null) { s.insertBefore(tmp.firstChild, ref) }sel.selectAllChildren(s)sel.collapseToEnd()sync(root)return null}insertMarkdown(root, md)sync(root)}on mdPick(e) {root = rootOf(e.target)root.querySelector('input.pick').click()}on mdPicked(e) {root = rootOf(e.target)input = e.targetif (input.files.length > 0) { attach(root, input.files, null) }input.value = ''}// Ctrl / Cmd + click follows a linkon mdClick(e) {a = e.target.closest('a')if ((e.ctrlKey || e.metaKey) && a != null && safeHref(a.getAttribute('href')) != '') { window.open(a.getAttribute('href'), '_blank', 'noopener') }}on mdBlur(e) { sync(rootOf(e.target)) }// the Markdown source view: the whole field as a plain textarea, and backon mdSource(e) {root = rootOf(e.target)ta = sourceOf(root)b = root.querySelector('button.source-switch')if (root.classList.contains('source')) {md = ta.valueload(root, md)root.classList.remove('source')b.textContent = 'Markdown source'sync(root)surfaceOf(root).focus()} else {sync(root)ta.value = fieldOf(root).valueroot.classList.add('source')b.textContent = 'Visual editor'ta.focus()}}on mdSourceInput(e) {root = rootOf(e.target)f = fieldOf(root)f.value = e.target.valuef.dispatchEvent(new Event('input', { bubbles = true }))}
Branches
Latest commits
- 86ea4a85deploy: backup copies index files first and *.mpack data last (hot-copy skew, hybriel #203)mre
- edeab20fnotes mission 015: mission, report, LOG, STATUSmre
- 542a0383notes mission 015: e2e-chrome E2E_HOST (own cookie jar in the shared Chrome)mre
- 8b30f510notes mission 015: main-menu from layouts 0bcc629, current = true kept (route marks only /), server-HTML marker checksmre
- 84b574c4notes mission 015: re-vendor plugins from hybriel f9614007 (incl. web, #117)mre
- 447da53dnotes mission 014: report — remaining gates and lisbeth E2E proofmre
- fd9f92c3notes mission 014: report (partial), LOG, STATUSmre
- b2501360notes mission 014: open() sets asking=false before flush(0) (hybriel#196)mre
- 9414ce59notes mission 014: merge theme 76f99f6, components 3794c59, strict single-press openAsk (fails on old open())mre
- c08c655anotes 013: theme re-copied from layouts 76f99f6 (menu marks the current page), current = true on the menu item, e2e marker checks, reportmre
- 21c8f65dnotes mission 012: STATUSmre
- 0bbb3dd9notes mission 012: delete section of the browser gate de-flaked (openAsk: calm wait, press again when the question closes by itself); report 012mre
- f431bdf8notes mission 011: notes on the layouts theme (ListFirst shell), styles cut, check-theme gate, E2E extended; reportmre
- 1a8603d1notes mission 011 WIP: deploy.sh gate summary also matches check-theme, browser.mjs logout via the user menumre
- dae2e508notes mission 011 WIP: theme dbe3de7, shell on AppHeader/MainMenu/UserMenu/Sidebar + ListFirst, styles cut to the app's own, check-theme gate, e2e auditmre
- fd36da27notes mission 010: the note editor is the Hybriel MdEditor block (components.hybriel 1442e58, verbatim); md-editor.js, its route, script tag and offlineFiles retired; gate 66/0, realdata-offline 12/0, round-trip and Chrome E2E tests; report 010mre
- efa92170notes tests/identkit.mjs: refuse a taken ident port, cold-wait deadline, emit, identities; mission 009 reportmre
- f3dec0f1Merge branch 'w7'mre
- d1cf966dre-vendor hybriel 97bcf128: offlineFiles for the editor script, 44 px taps, 390 px offline checks, mission 008mre
- 4a610a21paths: projects moved into /media/STORAGE/projects/WorldAPI/mre