gitoria

notes

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit3a8bc0d23a8bc0d2N5: empty Table-button table is written as a real pipe table (MdEditor 4bd1112, plain copy); gate tests/table-button.mjs; reportmre3a8bc0d2/components/md-editor/md-editor.hl

88.2 KB

  1. // md-editor.hl — THE MARKDOWN WYSIWYG EDITOR, all Hybriel (port of worldapi-components/md-editor.js): headings look like
  2. // headings, **bold** is bold, lists are lists — while you type; the value stays plain Markdown. `MdEditor { name = "note" value = "**hi**" }`.
  3. // The formatted surface is a contenteditable element whose children are built in the browser (createElement / text nodes, never
  4. // innerHTML of user text) — the framework never re-renders it: nothing bound to it changes after the first render. Hybriel has no
  5. // mount event, so a 1 ms CSS animation on the surface fires `animationiteration` in the very frame after the page is claimed, and that
  6. // hands the editor its first content (the mount hook turns the animation off again). The first editor to hear it draws every editor of
  7. // the page (`mountAll`), so a reader never sees the empty surface the server sent. The value is written to the hidden field
  8. // `<input name>` (posts in a form) and announced with a bubbling DOM `input` event on it (`e.target.value` = the Markdown).
  9. // Subset (what the tickets' markdown.hl renders): headings 1-6, paragraphs (single line breaks kept), - / 1. lists (one level),
  10. // fenced code blocks, `code`, links (http(s), mailto, /path, #anchor), *em*, **strong**, GitHub pipe tables (mission 004: header,
  11. // `| --- | :-: | --: |` alignment, `\|`, inline Markdown in cells, outer pipes optional).
  12. import Icon from '../icons/icons.hl'
  13. String name = 'markdown'
  14. String value = ''
  15. String placeholder = 'Write…'
  16. // 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)
  17. Number rows = 6
  18. // readonly = "true": the Markdown shown formatted and nothing else — no toolbar, no source switch, not editable, no field frame
  19. // (mission 006: the comments block shows every comment with the editor's own renderer, so typed and shown look the same)
  20. String readonly = 'false'
  21. // files = "off" (mission 009, tickets#27): no File button, and files dropped on or pasted into the editor are NOT taken here — they go
  22. // on to the page, so a FilesUpload in pick mode around the editor collects them as attachments (the comments block's form does that)
  23. String files = 'on'
  24. String editable = readonly == 'true' ? 'false' : 'true'
  25. // readonly: NO inline min-height — an inline style beats the stylesheet's `article { min-height: 0 }` of the readonly look, which made every
  26. // shown comment as tall as a 6-row editor (K1). The surface of a readonly editor hugs its text.
  27. String surfaceStyle = readonly == 'true' ? '' : 'min-height:' + (rows * 1.5) + 'em'
  28. String sourceStyle = 'min-height:' + (rows * 1.35 + 1.2) + 'rem'
  29. String surfaceTab = readonly == 'true' ? '-1' : '0'
  30. String surfaceRole = readonly == 'true' ? 'document' : 'textbox'
  31. Hybrid linkOk = ['http://', 'https://', 'mailto:', '/', '#']
  32. static NL = "
  33. "
  34. static BS = 'x\y'.slice(1, 2)
  35. // a REAL carriage return (Windows line ends, a textarea's post). Hybriel strings have no escapes ('\r' is two characters, #17) and
  36. // `String.fromCharCode` does not parse here, so the JSON escape is decoded
  37. static CR = JSON.parse('"' + BS + 'r"')
  38. static ZW = "​"
  39. static NB = " "
  40. // ---- small text helpers ---------------------------------------------------------------------------------------------
  41. isDigit(c) { k = c.charCodeAt(0) return k >= 48 && k <= 57 }
  42. isAlnum(c) { k = c.charCodeAt(0) return (k >= 48 && k <= 57) || (k >= 65 && k <= 90) || (k >= 97 && k <= 122) || k > 127 }
  43. isSpace(c) { return c == ' ' || c == NB || c == NL || c == ZW }
  44. repeat(c, n) { let s = '' let i = 0 while (i < n) { s = s + c i = i + 1 } return s }
  45. // trim spaces (also the non-breaking space the browser types) and the zero-width space
  46. clean(s) { return s.replaceAll(NB, ' ').replaceAll(ZW, '') }
  47. trimSp(s) {
  48. let a = 0
  49. let b = s.length
  50. while (a < b && (s.slice(a, a + 1) == ' ' || s.slice(a, a + 1) == NB || s.slice(a, a + 1) == ZW)) { a = a + 1 }
  51. while (b > a && (s.slice(b - 1, b) == ' ' || s.slice(b - 1, b) == NB || s.slice(b - 1, b) == ZW)) { b = b - 1 }
  52. return s.slice(a, b)
  53. }
  54. safeHref(u) {
  55. t = trimSp(u)
  56. if (t == '' ) { return '' }
  57. for (p of linkOk) { if (t.startsWith(p)) { return t } }
  58. return ''
  59. }
  60. // an image address: http(s) or a path on this site; nothing else (no data:, no javascript:)
  61. safeSrc(u) {
  62. t = trimSp(u)
  63. if (t.startsWith('https://') || t.startsWith('http://') || (t.startsWith('/') && !t.startsWith('//'))) { return t }
  64. return ''
  65. }
  66. // the end of a bare URL that starts at i: up to a space, minus trailing punctuation
  67. urlEnd(s, i) {
  68. let j = i
  69. while (j < s.length && !isSpace(s.slice(j, j + 1)) && s.slice(j, j + 1) != '<') { j = j + 1 }
  70. while (j > i && ('.,;:!?)]}' + "'" + '"').indexOf(s.slice(j - 1, j)) >= 0) { j = j - 1 }
  71. return j
  72. }
  73. // ---- Markdown → DOM ---------------------------------------------------------------------------------------------------
  74. el(tag, text) {
  75. e = document.createElement(tag)
  76. if (text != null) { e.textContent = text }
  77. return e
  78. }
  79. // the closing run of c (n times) after position i, whose content is not empty and does not end in a space; -1 when none
  80. closer(s, i, c, n) {
  81. mark = repeat(c, n)
  82. let j = s.indexOf(mark, i)
  83. while (j >= 0) {
  84. let after = s.slice(j + n, j + n + 1)
  85. let before = s.slice(j - 1, j)
  86. let ok = j > i && !isSpace(before) && before != BS && (after != c)
  87. if (ok && c == '_' && after != '' && isAlnum(after)) { ok = false }
  88. if (ok) { return j }
  89. j = s.indexOf(mark, j + 1)
  90. }
  91. return -1
  92. }
  93. // appends the inline Markdown `s` to `host`
  94. inline(host, s) {
  95. let buf = ''
  96. let i = 0
  97. n = s.length
  98. while (i < n) {
  99. let c = s.slice(i, i + 1)
  100. let done = false
  101. if (c == BS && i + 1 < n && '\*_`[]<>#-.!()+~|'.indexOf(s.slice(i + 1, i + 2)) >= 0) {
  102. buf = buf + s.slice(i + 1, i + 2)
  103. i = i + 2
  104. done = true
  105. }
  106. if (!done && c == '`') {
  107. let run = 1
  108. while (s.slice(i + run, i + run + 1) == '`') { run = run + 1 }
  109. let mark = repeat('`', run)
  110. let j = s.indexOf(mark, i + run)
  111. if (j > i + run) {
  112. if (buf != '') { host.appendChild(document.createTextNode(buf)) buf = '' }
  113. let inner = s.slice(i + run, j)
  114. if (inner.length > 2 && inner.startsWith(' ') && inner.endsWith(' ')) { inner = inner.slice(1, inner.length - 1) }
  115. host.appendChild(el('code', inner))
  116. i = j + run
  117. done = true
  118. }
  119. }
  120. if (!done && c == '!' && s.slice(i + 1, i + 2) == '[') {
  121. let j = s.indexOf('](', i + 2)
  122. let k = j >= 0 ? s.indexOf(')', j + 2) : -1
  123. if (j > i + 1 && k > j + 2) {
  124. let src = safeSrc(s.slice(j + 2, k))
  125. if (src != '') {
  126. if (buf != '') { host.appendChild(document.createTextNode(buf)) buf = '' }
  127. let img = el('img', null)
  128. img.setAttribute('src', src)
  129. img.setAttribute('alt', s.slice(i + 2, j))
  130. host.appendChild(img)
  131. i = k + 1
  132. done = true
  133. }
  134. }
  135. }
  136. if (!done && c == '[') {
  137. let j = s.indexOf('](', i + 1)
  138. let k = j >= 0 ? s.indexOf(')', j + 2) : -1
  139. if (j > i + 1 && k > j + 2) {
  140. let href = safeHref(s.slice(j + 2, k))
  141. if (href != '') {
  142. if (buf != '') { host.appendChild(document.createTextNode(buf)) buf = '' }
  143. let a = el('a', null)
  144. a.setAttribute('href', href)
  145. inline(a, s.slice(i + 1, j))
  146. host.appendChild(a)
  147. i = k + 1
  148. done = true
  149. }
  150. }
  151. }
  152. if (!done && c == '<' && (s.slice(i + 1, i + 8) == 'http://' || s.slice(i + 1, i + 9) == 'https://')) {
  153. let j = s.indexOf('>', i)
  154. if (j > 0 && s.slice(i, j).indexOf(' ') < 0) {
  155. if (buf != '') { host.appendChild(document.createTextNode(buf)) buf = '' }
  156. let a = el('a', s.slice(i + 1, j))
  157. a.setAttribute('href', s.slice(i + 1, j))
  158. host.appendChild(a)
  159. i = j + 1
  160. done = true
  161. }
  162. }
  163. if (!done && c == 'h' && (s.slice(i, i + 7) == 'http://' || s.slice(i, i + 8) == 'https://') && (i == 0 || !isAlnum(s.slice(i - 1, i)))) {
  164. let j = urlEnd(s, i)
  165. if (j > i + 8) {
  166. if (buf != '') { host.appendChild(document.createTextNode(buf)) buf = '' }
  167. let a = el('a', s.slice(i, j))
  168. a.setAttribute('href', s.slice(i, j))
  169. host.appendChild(a)
  170. i = j
  171. done = true
  172. }
  173. }
  174. if (!done && (c == '*' || c == '_') && !(c == '_' && i > 0 && isAlnum(s.slice(i - 1, i)))) {
  175. let run = 1
  176. while (run < 3 && s.slice(i + run, i + run + 1) == c) { run = run + 1 }
  177. let first = s.slice(i + run, i + run + 1)
  178. if (first != '' && !isSpace(first) && first != c) {
  179. let j = closer(s, i + run, c, run)
  180. if (j > 0) {
  181. if (buf != '') { host.appendChild(document.createTextNode(buf)) buf = '' }
  182. let node = null
  183. let innerNode = null
  184. if (run == 1) { node = el('em', null) innerNode = node }
  185. if (run == 2) { node = el('strong', null) innerNode = node }
  186. if (run == 3) { node = el('strong', null) innerNode = el('em', null) node.appendChild(innerNode) }
  187. inline(innerNode, s.slice(i + run, j))
  188. host.appendChild(node)
  189. i = j + run
  190. done = true
  191. }
  192. }
  193. }
  194. if (!done) { buf = buf + c i = i + 1 }
  195. }
  196. if (buf != '') { host.appendChild(document.createTextNode(buf)) }
  197. }
  198. // a line like `## title`: its level (0 = not a heading)
  199. headingLevel(line) {
  200. let k = 0
  201. while (k < line.length && k < 7 && line.slice(k, k + 1) == '#') { k = k + 1 }
  202. if (k >= 1 && k <= 6 && (line.length == k || line.slice(k, k + 1) == ' ')) { return k }
  203. return 0
  204. }
  205. // a list line: 0 = none, 1 = bullet, 2 = numbered; the item text is cut off by itemText
  206. listKind(line) {
  207. t = line.trim()
  208. if ((t.startsWith('- ') || t.startsWith('* ') || t.startsWith('+ '))) { return 1 }
  209. let k = 0
  210. while (k < t.length && isDigit(t.slice(k, k + 1))) { k = k + 1 }
  211. if (k > 0 && k < 10 && (t.slice(k, k + 2) == '. ' || t.slice(k, k + 2) == ') ')) { return 2 }
  212. return 0
  213. }
  214. itemText(line) {
  215. t = line.trim()
  216. let k = 0
  217. while (k < t.length && isDigit(t.slice(k, k + 1))) { k = k + 1 }
  218. return t.slice(k + 2).trim()
  219. }
  220. fenceOf(line) {
  221. t = line.trim()
  222. if (t.startsWith('```')) { return '`' }
  223. if (t.startsWith('~~~')) { return '~' }
  224. return ''
  225. }
  226. startsBlock(line) { return headingLevel(line) > 0 || listKind(line) > 0 || fenceOf(line) != '' }
  227. // ---- GitHub pipe tables (mission 004, the behaviour of notes' md-editor.js 9acc27f) ----------------------------------------
  228. // A table is a header row, a delimiter row (`| --- | :-: | --: |`, the colons set the alignment) with the same number of cells,
  229. // then body trs up to a blank line or another block; outer pipes are optional, `\|` is a pipe inside a cell (also in code).
  230. // how many backslashes stand right before position k (down to `start`): odd = the character at k is escaped
  231. escapedAt(s, k, start) {
  232. let n = 0
  233. while (k - 1 - n >= start && s.slice(k - 1 - n, k - n) == BS) { n = n + 1 }
  234. return n % 2 == 1
  235. }
  236. // a row's cells (trimmed Markdown, still with `\|`): split at every pipe that is not escaped
  237. rowCells(s) {
  238. let a = 0
  239. let b = s.length
  240. while (a < b && isSpace(s.slice(a, a + 1))) { a = a + 1 }
  241. while (b > a && isSpace(s.slice(b - 1, b))) { b = b - 1 }
  242. if (a < b && s.slice(a, a + 1) == '|') { a = a + 1 }
  243. if (b > a && s.slice(b - 1, b) == '|' && !escapedAt(s, b - 1, a)) { b = b - 1 }
  244. cells = []
  245. let start = a
  246. let k = a
  247. while (k < b) {
  248. let c = s.slice(k, k + 1)
  249. if (c == BS && k + 1 < b) { k = k + 2 }
  250. else {
  251. if (c == '|') { cells.push(trimSp(s.slice(start, k))) start = k + 1 }
  252. k = k + 1
  253. }
  254. }
  255. cells.push(trimSp(s.slice(start, b)))
  256. return cells
  257. }
  258. // a cell's Markdown: `\|` is a pipe, every other escape stays for inline()
  259. unpipe(t) {
  260. let out = ''
  261. let k = 0
  262. while (k < t.length) {
  263. if (t.slice(k, k + 1) == BS && k + 1 < t.length) {
  264. out = out + (t.slice(k + 1, k + 2) == '|' ? '|' : t.slice(k, k + 2))
  265. k = k + 2
  266. } else { out = out + t.slice(k, k + 1) k = k + 1 }
  267. }
  268. return out
  269. }
  270. // the delimiter row (it must hold a pipe): the alignments ('' left center right), or null
  271. alignsOf(line) {
  272. if (line.indexOf('|') < 0) { return null }
  273. out = []
  274. for (c of rowCells(line)) {
  275. let core = c
  276. let left = core.startsWith(':')
  277. if (left) { core = core.slice(1) }
  278. let right = core.endsWith(':')
  279. if (right) { core = core.slice(0, core.length - 1) }
  280. if (core == '' || core.replaceAll('-', '') != '') { return null }
  281. out.push(left && right ? 'center' : (right ? 'right' : (left ? 'left' : '')))
  282. }
  283. return out
  284. }
  285. // a table starting at line i: [alignments, header cells], or null
  286. tableAt(lines, i) {
  287. if (i + 1 >= lines.length || lines[i].trim() == '') { return null }
  288. aligns = alignsOf(lines[i + 1])
  289. if (aligns == null) { return null }
  290. cells = rowCells(lines[i])
  291. if (cells.length != aligns.length) { return null }
  292. return [aligns, cells]
  293. }
  294. // a cell (th / td) with its alignment and its inline Markdown; an empty cell holds a <br> (a place for the caret)
  295. cellEl(tag, align, md) {
  296. cell = el(tag, null)
  297. if (align != '') { cell.setAttribute('data-align', align) }
  298. if (md == '') { cell.appendChild(el('br', null)) } else { inline(cell, md) }
  299. return cell
  300. }
  301. // the table of Markdown lines: lines[0] the header, lines[1] the delimiter, the rest body trs (missing cells padded, extra dropped).
  302. // It keeps its source (`mdSrc`) and its canonical form (`mdCanon`): written back byte for byte while it stays the same.
  303. tableOf(src, aligns) {
  304. t = el('table', null)
  305. head = el('thead', null)
  306. body = el('tbody', null)
  307. let r = 0
  308. while (r < src.length) {
  309. if (r != 1) {
  310. let cells = rowCells(src[r])
  311. let tr = el('tr', null)
  312. let k = 0
  313. while (k < aligns.length) {
  314. tr.appendChild(cellEl(r == 0 ? 'th' : 'td', aligns[k], k < cells.length ? unpipe(cells[k]) : ''))
  315. k = k + 1
  316. }
  317. if (r == 0) { head.appendChild(tr) } else { body.appendChild(tr) }
  318. }
  319. r = r + 1
  320. }
  321. t.appendChild(head)
  322. if (body.childNodes.length > 0) { t.appendChild(body) }
  323. t.mdSrc = src.join(NL)
  324. t.mdCanon = tableMd(t)
  325. return t
  326. }
  327. // Markdown → the block elements in a container
  328. parseInto(box, md) {
  329. let lines = md.replaceAll(CR, '').split(NL)
  330. let i = 0
  331. while (i < lines.length) {
  332. let line = lines[i]
  333. let fence = fenceOf(line)
  334. if (fence != '') {
  335. let run = 0
  336. let t = line.trim()
  337. while (t.slice(run, run + 1) == fence) { run = run + 1 }
  338. let body = []
  339. i = i + 1
  340. while (i < lines.length && !(lines[i].trim().startsWith(repeat(fence, run)) && lines[i].trim().replaceAll(fence, '') == '')) { body.push(lines[i]) i = i + 1 }
  341. i = i + 1
  342. box.appendChild(el('pre', body.join(NL)))
  343. } else if (line.trim() == '') {
  344. i = i + 1
  345. } else if (headingLevel(line) > 0) {
  346. let lv = headingLevel(line)
  347. let text = line.trim().slice(lv).trim()
  348. while (text.endsWith('#') && text.length > 0) { text = text.slice(0, text.length - 1) }
  349. let h = el('h' + lv, null)
  350. inline(h, text.trim())
  351. box.appendChild(h)
  352. i = i + 1
  353. } else if (listKind(line) > 0) {
  354. let kind = listKind(line)
  355. let list = el(kind == 1 ? 'ul' : 'ol', null)
  356. let last = null
  357. while (i < lines.length && lines[i].trim() != '' && (listKind(lines[i]) == kind || (listKind(lines[i]) == 0 && !startsBlock(lines[i]) && last != null))) {
  358. if (listKind(lines[i]) == kind) {
  359. last = el('li', null)
  360. inline(last, itemText(lines[i]))
  361. list.appendChild(last)
  362. } else {
  363. last.appendChild(el('br', null))
  364. inline(last, lines[i].trim())
  365. }
  366. i = i + 1
  367. }
  368. box.appendChild(list)
  369. } else if (tableAt(lines, i) != null) {
  370. let tb = tableAt(lines, i)
  371. let j = i + 2
  372. while (j < lines.length && lines[j].trim() != '' && !startsBlock(lines[j])) { j = j + 1 }
  373. box.appendChild(tableOf(lines.slice(i, j), tb[0]))
  374. i = j
  375. } else {
  376. let p = el('p', null)
  377. let first = true
  378. while (i < lines.length && lines[i].trim() != '' && (first || (!startsBlock(lines[i]) && tableAt(lines, i) == null))) {
  379. if (!first) { p.appendChild(el('br', null)) }
  380. inline(p, lines[i].trim())
  381. first = false
  382. i = i + 1
  383. }
  384. box.appendChild(p)
  385. }
  386. }
  387. if (box.childNodes.length == 0) { let p = el('p', null) p.appendChild(el('br', null)) box.appendChild(p) }
  388. // a table at the end gets an empty paragraph after it: a place for the caret (an empty paragraph is never written)
  389. if (box.lastChild.nodeName == 'TABLE') { let p = el('p', null) p.appendChild(el('br', null)) box.appendChild(p) }
  390. }
  391. // ---- DOM → Markdown ---------------------------------------------------------------------------------------------------
  392. // a text node's characters, with the ones Markdown would read as formatting written as an escape
  393. escapeText(s, first) {
  394. let out = ''
  395. let i = 0
  396. while (i < s.length) {
  397. let c = s.slice(i, i + 1)
  398. let prev = i > 0 ? s.slice(i - 1, i) : ' '
  399. let next = i + 1 < s.length ? s.slice(i + 1, i + 2) : ' '
  400. if (c == BS || c == '*' || c == '`' || c == '[' || c == ']' || c == '<') { out = out + BS + c }
  401. else if (c == '_' && (!isAlnum(prev) || !isAlnum(next))) { out = out + BS + c }
  402. else { out = out + c }
  403. i = i + 1
  404. }
  405. return out
  406. }
  407. // the inline Markdown of an element's children
  408. inlineMd(node) {
  409. let out = ''
  410. kids = node.childNodes
  411. let i = 0
  412. while (i < kids.length) {
  413. let k = kids[i]
  414. if (k.nodeType == 3) {
  415. out = out + escapeText(clean(k.data), false)
  416. } else if (k.nodeType == 1) {
  417. let tag = k.nodeName.toLowerCase()
  418. if (tag == 'br') { out = out + NL }
  419. else if (tag == 'code') {
  420. let t = clean(k.textContent)
  421. if (t != '') {
  422. let run = 1
  423. while (t.indexOf(repeat('`', run)) >= 0) { run = run + 1 }
  424. let pad = t.startsWith('`') || t.endsWith('`') ? ' ' : ''
  425. out = out + repeat('`', run) + pad + t + pad + repeat('`', run)
  426. }
  427. }
  428. else if (tag == 'strong' || tag == 'b' || tag == 'em' || tag == 'i') {
  429. let mark = (tag == 'strong' || tag == 'b') ? '**' : '*'
  430. let t = inlineMd(k)
  431. let core = trimSp(t)
  432. if (core != '') {
  433. let lead = t.slice(0, t.indexOf(core))
  434. let tail = t.slice(t.indexOf(core) + core.length)
  435. out = out + lead + mark + core + mark + tail
  436. } else { out = out + t }
  437. }
  438. else if (tag == 'img') {
  439. let src = safeSrc(k.getAttribute('src') != null ? k.getAttribute('src') : '')
  440. if (src != '') { out = out + '![' + (k.getAttribute('alt') != null ? k.getAttribute('alt') : '').replaceAll('[', '').replaceAll(']', '') + '](' + src.replaceAll(')', '%29').replaceAll(' ', '%20') + ')' }
  441. }
  442. else if (tag == 'a') {
  443. let t = inlineMd(k)
  444. let href = safeHref(k.getAttribute('href') != null ? k.getAttribute('href') : '')
  445. if (href == '' || trimSp(t) == '') { out = out + t }
  446. else if (trimSp(k.textContent) == href && (href.startsWith('http://') || href.startsWith('https://'))) { out = out + href }
  447. else { out = out + '[' + t + '](' + href.replaceAll(')', '%29').replaceAll(' ', '%20') + ')' }
  448. }
  449. else if (tag == 'div' || tag == 'p') { out = out + inlineMd(k) }
  450. else { out = out + inlineMd(k) }
  451. }
  452. i = i + 1
  453. }
  454. return out
  455. }
  456. // the text of a paragraph's or item's lines: trailing / leading breaks dropped, each line trimmed
  457. lines(md) {
  458. parts = md.split(NL)
  459. out = []
  460. for (p of parts) { out.push(trimSp(p)) }
  461. while (out.length > 0 && out[out.length - 1] == '') { out.pop() }
  462. while (out.length > 0 && out[0] == '') { out.shift() }
  463. return out
  464. }
  465. // same for a line starting with digits + "." (the backslash goes before the dot)
  466. guardNumber(line) {
  467. let k = 0
  468. while (k < line.length && isDigit(line.slice(k, k + 1))) { k = k + 1 }
  469. if (k > 0 && (line.slice(k, k + 2) == '. ' || line.slice(k, k + 2) == ') ')) { return line.slice(0, k) + BS + line.slice(k) }
  470. return line
  471. }
  472. paragraphMd(node) {
  473. ls = lines(inlineMd(node))
  474. if (ls.length == 0) { return '' }
  475. out = []
  476. for (l of ls) {
  477. if (headingLevel(l) > 0 || fenceOf(l) != '' || l.startsWith('>') || listKind(l) == 1) { out.push(BS + l) }
  478. // a line that would read as a table's delimiter row under the line before: its first pipe escaped
  479. else if (out.length > 0 && alignsOf(l) != null) { out.push(l.slice(0, l.indexOf('|')) + BS + l.slice(l.indexOf('|'))) }
  480. else { out.push(guardNumber(l)) }
  481. }
  482. return out.join(NL)
  483. }
  484. // the Markdown blocks of a container's children
  485. blocksMd(box) {
  486. out = []
  487. kids = box.childNodes
  488. let i = 0
  489. while (i < kids.length) {
  490. let k = kids[i]
  491. if (k.nodeType == 3) {
  492. let t = paragraphMd(k.parentNode == box ? wrapText(k) : k)
  493. if (t != '') { out.push(t) }
  494. } else if (k.nodeType == 1) {
  495. let tag = k.nodeName.toLowerCase()
  496. if (tag.length == 2 && tag.startsWith('h') && isDigit(tag.slice(1, 2)) && tag != 'hr') {
  497. let t = lines(inlineMd(k)).join(' ')
  498. if (t != '') { out.push(repeat('#', toNumber(tag.slice(1, 2))) + ' ' + t) }
  499. } else if (tag == 'ul' || tag == 'ol') {
  500. let items = []
  501. let n = 1
  502. let li = k.childNodes
  503. let j = 0
  504. while (j < li.length) {
  505. if (li[j].nodeType == 1) {
  506. let ls = lines(inlineMd(li[j]))
  507. if (ls.length > 0) {
  508. items.push((tag == 'ul' ? '- ' : n + '. ') + ls.join(NL + ' '))
  509. n = n + 1
  510. }
  511. }
  512. j = j + 1
  513. }
  514. if (items.length > 0) { out.push(items.join(NL)) }
  515. } else if (tag == 'pre') {
  516. let body = preText(k)
  517. let run = 3
  518. while (body.indexOf(repeat('`', run)) >= 0) { run = run + 1 }
  519. if (body != '') { out.push(repeat('`', run) + NL + body + NL + repeat('`', run)) }
  520. } else if (tag == 'table') {
  521. // an unchanged table is written back byte for byte (its source), a changed one in the canonical form
  522. let t = tableMd(k)
  523. if (t != '' && t == k.mdCanon) { t = k.mdSrc }
  524. if (t != '') { out.push(t) }
  525. } else if ((tag == 'div' || tag == 'p') && hasBlockChild(k)) {
  526. for (x of blocksMd(k)) { out.push(x) }
  527. } else if (tag == 'br') {
  528. } else {
  529. let t = paragraphMd(k)
  530. if (t != '') { out.push(t) }
  531. }
  532. }
  533. i = i + 1
  534. }
  535. return out
  536. }
  537. wrapText(t) { p = el('p', null) p.appendChild(document.createTextNode(t.data)) return p }
  538. hasBlockChild(node) {
  539. kids = node.childNodes
  540. let i = 0
  541. while (i < kids.length) {
  542. 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 }
  543. i = i + 1
  544. }
  545. return false
  546. }
  547. // the text of a code block (a <br> is a line break)
  548. preText(node) {
  549. let out = ''
  550. kids = node.childNodes
  551. let i = 0
  552. while (i < kids.length) {
  553. let k = kids[i]
  554. if (k.nodeType == 3) { out = out + k.data.replaceAll(ZW, '').replaceAll(NB, ' ') }
  555. else if (k.nodeName.toLowerCase() == 'br') { out = out + NL }
  556. else { out = out + preText(k) }
  557. i = i + 1
  558. }
  559. // a trailing line feed is the browser's, not the writer's
  560. while (out.endsWith(NL)) { out = out.slice(0, out.length - 1) }
  561. return out
  562. }
  563. toMarkdown(box) {
  564. return blocksMd(box).join(NL + NL)
  565. }
  566. // ---- a table → Markdown: one line per row, padded to the column widths (`| a | b |`), `|` in a cell written `\|`
  567. cellMd(cell) { return lines(inlineMd(cell)).join(' ').replaceAll('|', BS + '|') }
  568. // the cells of a row (th / td only)
  569. cellsOf(tr) {
  570. out = []
  571. kids = tr.childNodes
  572. let i = 0
  573. while (i < kids.length) {
  574. if (kids[i].nodeName == 'TH' || kids[i].nodeName == 'TD') { out.push(kids[i]) }
  575. i = i + 1
  576. }
  577. return out
  578. }
  579. dashes(align, n) {
  580. if (align == 'center') { return ':' + repeat('-', n - 2) + ':' }
  581. if (align == 'left') { return ':' + repeat('-', n - 1) }
  582. if (align == 'right') { return repeat('-', n - 1) + ':' }
  583. return repeat('-', n)
  584. }
  585. tableMd(t) {
  586. trs = t.querySelectorAll('tr')
  587. if (trs.length == 0) { return '' }
  588. head = cellsOf(trs[0])
  589. cols = head.length
  590. if (cols == 0) { return '' }
  591. // every cell's Markdown, row by row (trs padded / cut to the header's width)
  592. md = []
  593. aligns = []
  594. for (h of head) { aligns.push(h.getAttribute('data-align') != null ? h.getAttribute('data-align') : '') }
  595. let r = 0
  596. while (r < trs.length) {
  597. let cs = cellsOf(trs[r])
  598. let k = 0
  599. while (k < cols) {
  600. let m = k < cs.length ? cellMd(cs[k]) : ''
  601. md.push(m)
  602. k = k + 1
  603. }
  604. r = r + 1
  605. }
  606. w = []
  607. let col = 0
  608. while (col < cols) {
  609. let n = 3
  610. let i = col
  611. while (i < md.length) { if (md[i].length > n) { n = md[i].length } i = i + cols }
  612. w.push(n)
  613. col = col + 1
  614. }
  615. out = []
  616. r = 0
  617. while (r < trs.length) {
  618. let line = '|'
  619. let c = 0
  620. while (c < cols) { line = line + ' ' + md[r * cols + c] + repeat(' ', w[c] - md[r * cols + c].length) + ' |' c = c + 1 }
  621. out.push(line)
  622. if (r == 0) {
  623. let d = '|'
  624. let c2 = 0
  625. while (c2 < cols) { d = d + ' ' + dashes(aligns[c2], w[c2]) + ' |' c2 = c2 + 1 }
  626. out.push(d)
  627. }
  628. r = r + 1
  629. }
  630. return out.join(NL)
  631. }
  632. // ---- the editor ---------------------------------------------------------------------------------------------------------
  633. rootOf(node) { return node.closest('md-editor') }
  634. surfaceOf(root) { return root.querySelector('article') }
  635. fieldOf(root) { return root.querySelector('input.value') }
  636. sourceOf(root) { return root.querySelector('textarea') }
  637. // the block (a direct child of the surface) that holds a node
  638. blockOf(root, node) {
  639. s = surfaceOf(root)
  640. let n = node
  641. while (n != null && n.parentNode != s) { n = n.parentNode }
  642. return n
  643. }
  644. inSurface(root) {
  645. sel = document.getSelection()
  646. return sel.rangeCount > 0 && sel.anchorNode != null && surfaceOf(root).contains(sel.anchorNode)
  647. }
  648. inTag(root, tags) {
  649. sel = document.getSelection()
  650. let n = sel.anchorNode
  651. s = surfaceOf(root)
  652. while (n != null && n != s) {
  653. if (n.nodeType == 1 && tags.indexOf(n.nodeName.toLowerCase()) >= 0) { return true }
  654. n = n.parentNode
  655. }
  656. return false
  657. }
  658. // 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
  659. // 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
  660. // is unwrapped (its children move up, the caret stays where it was).
  661. hasBlock(p) {
  662. 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 } }
  663. return false
  664. }
  665. flatten(root) {
  666. s = surfaceOf(root)
  667. // 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)
  668. if (s.mdFlat == true) { return null }
  669. s.mdFlat = true
  670. sel = document.getSelection()
  671. an = sel.anchorNode
  672. ao = sel.anchorOffset
  673. fn = sel.focusNode
  674. fo = sel.focusOffset
  675. let changed = false
  676. let i = 0
  677. while (i < s.childNodes.length) {
  678. k = s.childNodes[i]
  679. if (k.nodeType == 1 && k.nodeName == 'P' && hasBlock(k)) {
  680. while (k.firstChild != null) { s.insertBefore(k.firstChild, k) }
  681. s.removeChild(k)
  682. changed = true
  683. } else { i = i + 1 }
  684. }
  685. // 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 block
  686. let wrap = null
  687. let j = 0
  688. while (j < s.childNodes.length) {
  689. k = s.childNodes[j]
  690. if (!isBlockEl(k)) {
  691. wrap = el('p', null)
  692. s.insertBefore(wrap, k)
  693. while (wrap.nextSibling != null && !isBlockEl(wrap.nextSibling)) { wrap.appendChild(wrap.nextSibling) }
  694. changed = true
  695. }
  696. j = j + 1
  697. }
  698. if (changed && an != null && fn != null && s.contains(an) && s.contains(fn)) {
  699. if (an == s && wrap != null) { sel.collapse(wrap, 0) } else { sel.setBaseAndExtent(an, ao, fn, fo) }
  700. }
  701. s.mdFlat = false
  702. }
  703. isBlockEl(k) { return k.nodeType == 1 && ['UL', 'OL', 'PRE', 'TABLE', 'P', 'DIV', 'H1', 'H2', 'H3', 'H4', 'H5', 'H6'].indexOf(k.nodeName) >= 0 }
  704. // 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.
  705. sync(root) {
  706. s = surfaceOf(root)
  707. f = fieldOf(root)
  708. flatten(root)
  709. let md = toMarkdown(s)
  710. if (root.mdOrig != null && md == root.mdCanon) { md = root.mdOrig }
  711. root.classList.toggle('md-empty', md == '' && s.querySelector('pre') == null && s.querySelector('table') == null)
  712. if (md != f.value) {
  713. f.value = md
  714. root.mdLast = md
  715. own(root, md)
  716. f.dispatchEvent(new Event('input', { bubbles = true }))
  717. }
  718. }
  719. // THE VALUES THIS EDITOR HAS HELD since the last outside change (`mdSeen`: what it loaded and every value it wrote into the field itself).
  720. // The framework hands the member back through the `data-value` attribute — and the host may hand back an OLDER text of this very editor
  721. // (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).
  722. // 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
  723. // (hl:web's rehydrate of kept state, a push from another device, the page setting it) and is shown by followValue.
  724. // The first entry (the loaded value) is never dropped; the rest is cut when the list holds more than 300000 characters.
  725. own(root, md) {
  726. if (root.mdSeen == null) { root.mdSeen = [md] root.mdSeenSize = md.length return null }
  727. if (root.mdSeen.indexOf(md) >= 0) { return null }
  728. root.mdSeen.push(md)
  729. root.mdSeenSize = root.mdSeenSize + md.length
  730. while (root.mdSeen.length > 2 && root.mdSeenSize > 300000) {
  731. root.mdSeenSize = root.mdSeenSize - root.mdSeen[1].length
  732. root.mdSeen.splice(1, 1)
  733. }
  734. }
  735. // 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
  736. // put a NEW article (and field) under the same <md-editor> element, which mounted already (`mdMounted`). That surface is empty and no
  737. // mount would draw it (mdMount returns early), while the observer's load() had gone into the OLD article (F5, hybriel#211: a comment
  738. // 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
  739. // field's value drawn at once (from the data-value observer, the child-list observer, or its own mount event). True when it redrew.
  740. rebuilt(root) {
  741. let s = surfaceOf(root)
  742. if (s == null || root.mdSurface == s) { return false }
  743. root.mdSurface = s
  744. s.style.animationName = 'none'
  745. let v = fieldOf(root).value
  746. root.mdSeen = null
  747. load(root, v)
  748. sourceOf(root).value = v
  749. return true
  750. }
  751. // the member `value` moved: an outside value is loaded into the surface (and the source view); one this editor held before is left alone
  752. followValue(root) {
  753. rebuilt(root)
  754. let v = root.getAttribute('data-value')
  755. if (v == null) { v = '' }
  756. if (root.mdSeen != null && root.mdSeen.indexOf(v) >= 0) {
  757. if (v != root.mdLast && root.getAttribute('data-readonly') != 'true') { sync(root) }
  758. return null
  759. }
  760. root.mdSeen = null
  761. load(root, v)
  762. sourceOf(root).value = v
  763. fieldOf(root).value = v
  764. s = surfaceOf(root)
  765. // a caret in the surface goes to the end of the new text (the old position means nothing in it)
  766. if (s.contains(document.activeElement) || document.activeElement == s) {
  767. last = s.lastChild
  768. if (last != null) { document.getSelection().collapse(last, last.textContent == '' ? 0 : last.childNodes.length) }
  769. }
  770. updateBar(root)
  771. }
  772. // a new value (from outside, the source view or a paste-all): shown formatted
  773. load(root, md) {
  774. s = surfaceOf(root)
  775. s.textContent = ''
  776. parseInto(s, md)
  777. root.mdOrig = md
  778. root.mdLast = md
  779. own(root, md)
  780. root.mdCanon = toMarkdown(s)
  781. root.classList.toggle('md-empty', root.mdCanon == '')
  782. }
  783. // the toolbar shows what the caret is in
  784. updateBar(root) {
  785. if (!root.isConnected || !inSurface(root)) { return null }
  786. mark = (tool, active) => { b = root.querySelector('button.' + tool) if (b != null) { b.classList.toggle('on', active) } }
  787. mark('bold', document.queryCommandState('bold'))
  788. mark('italic', document.queryCommandState('italic'))
  789. mark('code', inTag(root, ['code']))
  790. mark('ul', inTag(root, ['ul']))
  791. mark('ol', inTag(root, ['ol']))
  792. mark('pre', inTag(root, ['pre']))
  793. mark('table', inTag(root, ['table']))
  794. mark('link', inTag(root, ['a']))
  795. h = root.querySelector('button.heading')
  796. let level = ''
  797. tags = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6']
  798. for (t of tags) { if (inTag(root, [t])) { level = t.toUpperCase() } }
  799. if (h != null) { h.setAttribute('data-level', level.slice(1)) h.classList.toggle('on', level != '') }
  800. }
  801. // bold / italic / heading / lists / code block: the browser's own editing commands, so undo works
  802. codeToggle(root) {
  803. sel = document.getSelection()
  804. r = sel.getRangeAt(0)
  805. let n = sel.anchorNode
  806. let inCode = null
  807. while (n != null && n != surfaceOf(root)) { if (n.nodeType == 1 && n.nodeName.toLowerCase() == 'code') { inCode = n } n = n.parentNode }
  808. if (inCode != null && r.collapsed) {
  809. // the caret in code and no selection: leave the code (the next typed text is plain), like Ctrl+B / Ctrl+I end bold / italic
  810. let nx = inCode.nextSibling
  811. if (nx == null || nx.nodeType != 3) {
  812. nx = document.createTextNode(ZW)
  813. inCode.parentNode.insertBefore(nx, inCode.nextSibling)
  814. } else if (!nx.data.startsWith(ZW)) { nx.insertData(0, ZW) }
  815. sel.collapse(nx, 1)
  816. return null
  817. }
  818. if (inCode != null) {
  819. let rr = document.createRange()
  820. rr.selectNode(inCode)
  821. sel.removeAllRanges()
  822. sel.addRange(rr)
  823. document.execCommand('insertHTML', false, escHtml(clean(inCode.textContent), ''))
  824. return null
  825. }
  826. // no selection (mission 011): an empty code span the caret sits in, like Ctrl+B / Ctrl+I leave the next typed text bold / italic
  827. if (r.collapsed) {
  828. document.execCommand('insertHTML', false, '<code>' + ZW + '</code>' + ZW)
  829. t = document.getSelection().anchorNode
  830. if (t != null && t.previousSibling != null && t.previousSibling.nodeName == 'CODE') { document.getSelection().collapse(t.previousSibling.firstChild, 1) }
  831. return null
  832. }
  833. document.execCommand('insertHTML', false, escHtml(r.toString(), 'code') + ZW)
  834. }
  835. // text as escaped html (built by the browser from a text node), optionally inside a tag
  836. escHtml(text, tag) {
  837. box = document.createElement('div')
  838. e = tag != '' ? el(tag, text) : document.createTextNode(text)
  839. box.appendChild(e)
  840. return box.innerHTML
  841. }
  842. headingCycle(root) {
  843. let cur = 0
  844. tags = ['h1', 'h2', 'h3']
  845. let i = 0
  846. while (i < 3) { if (inTag(root, [tags[i]])) { cur = i + 1 } i = i + 1 }
  847. document.execCommand('formatBlock', false, cur == 3 ? 'p' : tags[cur])
  848. }
  849. blockToggle(root, tag, cmd) {
  850. if (inTag(root, [tag])) {
  851. if (tag == 'pre') { document.execCommand('formatBlock', false, 'p') } else { document.execCommand(cmd) }
  852. } else if (tag == 'pre') { document.execCommand('formatBlock', false, 'pre') } else { document.execCommand(cmd) }
  853. }
  854. linkOpen(root) {
  855. sel = document.getSelection()
  856. if (!inSurface(root)) { surfaceOf(root).focus() }
  857. root.mdRange = sel.rangeCount > 0 ? sel.getRangeAt(0).cloneRange() : null
  858. f = root.querySelector('link-form input')
  859. let n = sel.anchorNode
  860. let href = ''
  861. while (n != null && n != surfaceOf(root)) { if (n.nodeType == 1 && n.nodeName.toLowerCase() == 'a') { href = n.getAttribute('href') } n = n.parentNode }
  862. f.value = href
  863. root.classList.add('linking')
  864. f.focus()
  865. }
  866. linkClose(root) {
  867. root.classList.remove('linking')
  868. surfaceOf(root).focus()
  869. sel = document.getSelection()
  870. if (root.mdRange != null) { sel.removeAllRanges() sel.addRange(root.mdRange) }
  871. }
  872. linkApply(root, remove) {
  873. f = root.querySelector('link-form input')
  874. href = remove ? '' : safeHref(f.value)
  875. linkClose(root)
  876. if (remove || f.value.trim() == '') { document.execCommand('unlink') }
  877. else if (href != '') {
  878. sel = document.getSelection()
  879. // the caret inside a link and no selection: the address of THAT link changes (mission 011; before, a second link was inserted into it)
  880. let an = sel.anchorNode
  881. let inA = null
  882. while (an != null && an != surfaceOf(root)) { if (an.nodeType == 1 && an.nodeName.toLowerCase() == 'a') { inA = an } an = an.parentNode }
  883. if (sel.isCollapsed && inA != null) { sel.selectAllChildren(inA) }
  884. if (sel.isCollapsed) { document.execCommand('insertHTML', false, escLink(href)) } else { document.execCommand('createLink', false, href) }
  885. }
  886. sync(root)
  887. }
  888. escLink(href) {
  889. box = document.createElement('div')
  890. a = el('a', href)
  891. a.setAttribute('href', href)
  892. box.appendChild(a)
  893. return box.innerHTML
  894. }
  895. // the parsed Markdown as html the browser can insert (built from elements, so every text is escaped)
  896. mdHtml(md) {
  897. box = document.createElement('div')
  898. parseInto(box, md)
  899. // a single paragraph is inserted inline: no extra block
  900. if (box.childNodes.length == 1 && box.firstChild.nodeName.toLowerCase() == 'p') { return box.firstChild.innerHTML }
  901. return box.innerHTML
  902. }
  903. // typing rules at the caret: "# " "- " "1. " make a block; the typed marker is consumed (only the formatting stays). They work in a
  904. // 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)
  905. blockRule(root, e) {
  906. sel = document.getSelection()
  907. if (!sel.isCollapsed || !inSurface(root)) { return false }
  908. let b = blockOf(root, sel.anchorNode)
  909. if (b == null) { return false }
  910. let tag = b.nodeName.toLowerCase()
  911. let inner = sel.anchorNode
  912. while (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 }
  913. if (inner != null && inner != surfaceOf(root) && inner.nodeName.toLowerCase() != 'li') { b = inner tag = inner.nodeName.toLowerCase() }
  914. let item = sel.anchorNode
  915. while (item != null && item != surfaceOf(root) && item.nodeName.toLowerCase() != 'li') { item = item.parentNode }
  916. if (item == surfaceOf(root)) { item = null }
  917. let box = b
  918. if (item != null) {
  919. box = item
  920. tag = item.parentNode.nodeName.toLowerCase()
  921. } else if (tag != 'p' && tag != 'div' && !(tag.length == 2 && tag.startsWith('h'))) { return false }
  922. r = sel.getRangeAt(0)
  923. pre = document.createRange()
  924. pre.selectNodeContents(box)
  925. pre.setEnd(r.endContainer, r.endOffset)
  926. before = clean(pre.toString())
  927. if (before != clean(box.textContent)) { return false }
  928. let cmd = ''
  929. let arg = ''
  930. if (item == null && before.length >= 1 && before.length <= 6 && before.replaceAll('#', '') == '') { cmd = 'formatBlock' arg = 'h' + before.length }
  931. if (before == '-' || before == '*' || before == '+') { cmd = 'insertUnorderedList' }
  932. if (before.length >= 2 && before.endsWith('.') && before.slice(0, before.length - 1).length < 9) {
  933. let digits = true
  934. let k = 0
  935. while (k < before.length - 1) { if (!isDigit(before.slice(k, k + 1))) { digits = false } k = k + 1 }
  936. if (digits) { cmd = 'insertOrderedList' }
  937. }
  938. if (cmd == '') { return false }
  939. e.preventDefault()
  940. sel.selectAllChildren(box)
  941. document.execCommand('delete')
  942. // a list marker typed in a list of that kind is only consumed
  943. if (item != null && ((cmd == 'insertUnorderedList' && tag == 'ul') || (cmd == 'insertOrderedList' && tag == 'ol'))) { return true }
  944. if (item == null && tag != 'p' && tag != 'div' && cmd != 'formatBlock') { document.execCommand('formatBlock', false, 'p') }
  945. if (arg != '') { document.execCommand(cmd, false, arg) } else { document.execCommand(cmd) }
  946. return true
  947. }
  948. // a closing * _ ` typed: find the opener before the caret in the same text node
  949. inlineRule(root, e) {
  950. sel = document.getSelection()
  951. node = sel.anchorNode
  952. if (!sel.isCollapsed || node == null || node.nodeType != 3 || !surfaceOf(root).contains(node)) { return null }
  953. if (inTag(root, ['code', 'pre'])) { return null }
  954. off = sel.anchorOffset
  955. t = node.data.slice(0, off)
  956. c = e.data
  957. let tag = ''
  958. let start = -1
  959. let ends = ''
  960. if (c == '`') {
  961. let j = t.slice(0, off - 1).lastIndexOf('`')
  962. if (j >= 0 && off - 1 - j - 1 >= 1) { start = j tag = 'code' ends = t.slice(j + 1, off - 1) }
  963. }
  964. if (c == '*' && t.length >= 5 && t.endsWith('**')) {
  965. let j = t.slice(0, off - 2).lastIndexOf('**')
  966. let inner = j >= 0 ? t.slice(j + 2, off - 2) : ''
  967. if (j >= 0 && inner != '' && !isSpace(inner.slice(0, 1)) && !isSpace(inner.slice(inner.length - 1))) { start = j tag = 'strong' ends = inner }
  968. }
  969. if ((c == '*' || c == '_') && tag == '' && t.length >= 3 && !t.endsWith(c + c)) {
  970. let j = t.slice(0, off - 1).lastIndexOf(c)
  971. let inner = j >= 0 ? t.slice(j + 1, off - 1) : ''
  972. okStart = j >= 0 && (j == 0 || !isAlnum(t.slice(j - 1, j)) || c == '*') && t.slice(j - 1, j) != c && t.slice(j + 1, j + 2) != c
  973. if (okStart && inner != '' && !isSpace(inner.slice(0, 1)) && !isSpace(inner.slice(inner.length - 1))) { start = j tag = 'em' ends = inner }
  974. }
  975. if (tag == '') { return null }
  976. r = document.createRange()
  977. r.setStart(node, start)
  978. r.setEnd(node, off)
  979. sel.removeAllRanges()
  980. sel.addRange(r)
  981. document.execCommand('insertHTML', false, escHtml(ends, tag) + ZW)
  982. // Chrome pins the colour on the new element (`<strong style="color: …">`) when it equals the text around it (the black/white base
  983. // look, #15); the surface never carries styles of its own
  984. for (k of surfaceOf(root).querySelectorAll('[style]')) { k.removeAttribute('style') }
  985. }
  986. // ---- tables in the editor: typing one, moving between cells, trs; a table never merges with the text around it ----------
  987. cellOf(root, node) {
  988. s = surfaceOf(root)
  989. let n = node
  990. while (n != null && n != s) {
  991. if (n.nodeName == 'TD' || n.nodeName == 'TH') { return n }
  992. n = n.parentNode
  993. }
  994. return null
  995. }
  996. inCell(root) {
  997. sel = document.getSelection()
  998. return sel.rangeCount > 0 && sel.anchorNode != null && cellOf(root, sel.anchorNode) != null
  999. }
  1000. isBlank(node) { return clean(node.textContent).trim() == '' && (node.nodeType != 1 || node.querySelector('img') == null) }
  1001. // the caret at the end of a cell (an empty cell: at its start, before its <br>)
  1002. caretIn(cell, atEnd) {
  1003. sel = document.getSelection()
  1004. r = document.createRange()
  1005. r.selectNodeContents(cell)
  1006. r.collapse(!atEnd || isBlank(cell))
  1007. sel.removeAllRanges()
  1008. sel.addRange(r)
  1009. }
  1010. // a new empty row (the header's alignments) after `tr`; a header row gets its body first
  1011. newRow(table, tr) {
  1012. row = el('tr', null)
  1013. for (h of cellsOf(table.querySelector('tr'))) { row.appendChild(cellEl('td', h.getAttribute('data-align') != null ? h.getAttribute('data-align') : '', '')) }
  1014. let body = table.querySelector('tbody')
  1015. if (body == null) { body = el('tbody', null) table.appendChild(body) }
  1016. if (tr.parentNode.nodeName == 'THEAD') { body.insertBefore(row, body.firstChild) } else { body.insertBefore(row, tr.nextSibling) }
  1017. return row
  1018. }
  1019. // an empty paragraph after a block (the one already there when it is empty), for the caret
  1020. paraAfter(root, b) {
  1021. n = b.nextSibling
  1022. if (n != null && n.nodeName == 'P' && isBlank(n)) { return n }
  1023. p = el('p', null)
  1024. p.appendChild(el('br', null))
  1025. surfaceOf(root).insertBefore(p, n)
  1026. return p
  1027. }
  1028. // 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
  1029. // 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.
  1030. tableInsert(root) {
  1031. s = surfaceOf(root)
  1032. sel = document.getSelection()
  1033. b = sel.rangeCount > 0 && sel.anchorNode != null && inSurface(root) ? blockOf(root, sel.anchorNode) : null
  1034. table = el('table', null)
  1035. head = el('thead', null)
  1036. tr = el('tr', null)
  1037. tr.appendChild(cellEl('th', '', ''))
  1038. tr.appendChild(cellEl('th', '', ''))
  1039. head.appendChild(tr)
  1040. table.appendChild(head)
  1041. newRow(table, tr)
  1042. if (b != null && b.parentNode == s && b.nodeName == 'P' && isBlank(b)) { s.replaceChild(table, b) }
  1043. else if (b != null && b.parentNode == s) { s.insertBefore(table, b.nextSibling) }
  1044. else { s.appendChild(table) }
  1045. if (table.nextSibling == null) { paraAfter(root, table) }
  1046. caretIn(tr.firstChild, false)
  1047. sync(root)
  1048. }
  1049. // 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
  1050. // it (more than the row has: dropped); answer: the last cell filled, or the cell itself when the text is no pipe row
  1051. splitRow(root, cell) {
  1052. let txt = trimSp(cell.textContent)
  1053. if (!txt.startsWith('|')) { return cell }
  1054. let cs = rowCells(txt)
  1055. let closed = txt.length > 1 && txt.endsWith('|') && !escapedAt(txt, txt.length - 1, 0)
  1056. if (!closed && cs.length < 2) { return cell }
  1057. let all = cellsOf(cell.parentNode)
  1058. let at = 0
  1059. while (at < all.length && all[at] != cell) { at = at + 1 }
  1060. let k = 0
  1061. let last = cell
  1062. while (k < cs.length && at + k < all.length) {
  1063. let c = all[at + k]
  1064. while (c.firstChild != null) { c.removeChild(c.firstChild) }
  1065. if (cs[k] == '') { c.appendChild(el('br', null)) } else { inline(c, unpipe(cs[k])) }
  1066. last = c
  1067. k = k + 1
  1068. }
  1069. return last
  1070. }
  1071. // Enter in a cell: a new empty row below; in an empty last row (not the header): the row goes, the caret leaves the table
  1072. rowEnter(root, typed) {
  1073. cell = splitRow(root, typed)
  1074. tr = cell.parentNode
  1075. table = tr.closest('table')
  1076. trs = table.querySelectorAll('tr')
  1077. empty = isBlank(tr)
  1078. if (tr.parentNode.nodeName == 'TBODY' && trs[trs.length - 1] == tr && empty) {
  1079. body = tr.parentNode
  1080. body.removeChild(tr)
  1081. if (body.childNodes.length == 0) { table.removeChild(body) }
  1082. p = paraAfter(root, table)
  1083. document.getSelection().collapse(p, 0)
  1084. } else { caretIn(newRow(table, tr).firstChild, false) }
  1085. sync(root)
  1086. }
  1087. // Tab / Shift+Tab: the next / previous cell (the caret at its end); Tab in the last cell adds a row
  1088. cellTab(root, typed, back) {
  1089. cell = back ? typed : splitRow(root, typed)
  1090. table = cell.closest('table')
  1091. cells = table.querySelectorAll('th, td')
  1092. let i = 0
  1093. while (i < cells.length && cells[i] != cell) { i = i + 1 }
  1094. if (back) { if (i > 0) { caretIn(cells[i - 1], true) } return null }
  1095. if (i + 1 < cells.length) { caretIn(cells[i + 1], true) return null }
  1096. caretIn(newRow(table, cell.parentNode).firstChild, false)
  1097. sync(root)
  1098. }
  1099. // the lines of a paragraph are its children between <br>s: [from, to) child indexes of its last line and the one before
  1100. // (a trailing <br> the browser keeps at the end is not a line). Answer: [lastFrom, lastTo, prevFrom] (prevFrom -1 = no line before).
  1101. lastLines(p) {
  1102. kids = p.childNodes
  1103. let end = kids.length
  1104. while (end > 0 && kids[end - 1].nodeName == 'BR') { end = end - 1 }
  1105. let br = end - 1
  1106. while (br >= 0 && kids[br].nodeName != 'BR') { br = br - 1 }
  1107. let prev = -1
  1108. if (br >= 0) {
  1109. prev = br - 1
  1110. while (prev >= 0 && kids[prev].nodeName != 'BR') { prev = prev - 1 }
  1111. prev = prev + 1
  1112. }
  1113. return [br + 1, end, prev]
  1114. }
  1115. lineText(p, start, to) {
  1116. let t = ''
  1117. let i = start
  1118. while (i < to) { t = t + p.childNodes[i].textContent i = i + 1 }
  1119. return clean(t)
  1120. }
  1121. linePlain(p, start, to) {
  1122. let i = start
  1123. while (i < to) { if (p.childNodes[i].nodeType != 3) { return false } i = i + 1 }
  1124. return true
  1125. }
  1126. // the header cells of a typed line: its nodes split at every `|` in the text (`\|` typed is a pipe in the cell); formatted parts
  1127. // (bold, code, a link) go into their cell whole; outer pipes are optional
  1128. headCells(p, start, to, aligns) {
  1129. text = trimSp(lineText(p, start, to))
  1130. cells = [el('th', null)]
  1131. let i = start
  1132. while (i < to) {
  1133. let n = p.childNodes[i]
  1134. if (n.nodeType == 3) {
  1135. let s = clean(n.data)
  1136. let buf = ''
  1137. let k = 0
  1138. while (k < s.length) {
  1139. let c = s.slice(k, k + 1)
  1140. if (c == BS && s.slice(k + 1, k + 2) == '|') { buf = buf + '|' k = k + 2 }
  1141. else if (c == '|') {
  1142. if (buf != '') { cells[cells.length - 1].appendChild(document.createTextNode(buf)) }
  1143. buf = ''
  1144. let th = el('th', null)
  1145. cells.push(th)
  1146. k = k + 1
  1147. } else { buf = buf + c k = k + 1 }
  1148. }
  1149. if (buf != '') { cells[cells.length - 1].appendChild(document.createTextNode(buf)) }
  1150. } else { cells[cells.length - 1].appendChild(n.cloneNode(true)) }
  1151. i = i + 1
  1152. }
  1153. if (text.startsWith('|')) { cells.shift() }
  1154. if (text.endsWith('|') && !escapedAt(text, text.length - 1, 0) && cells.length > 0) { cells.pop() }
  1155. if (cells.length != aligns.length) { return null }
  1156. let k2 = 0
  1157. while (k2 < cells.length) {
  1158. let cell = cells[k2]
  1159. trimCell(cell)
  1160. if (aligns[k2] != '') { cell.setAttribute('data-align', aligns[k2]) }
  1161. k2 = k2 + 1
  1162. }
  1163. return cells
  1164. }
  1165. // leading / trailing spaces of a cell's first / last text go; an empty cell gets its <br>
  1166. trimCell(cell) {
  1167. while (cell.firstChild != null && cell.firstChild.nodeType == 3 && trimSp(cell.firstChild.data) == '') { cell.removeChild(cell.firstChild) }
  1168. while (cell.lastChild != null && cell.lastChild.nodeType == 3 && trimSp(cell.lastChild.data) == '') { cell.removeChild(cell.lastChild) }
  1169. if (cell.firstChild != null && cell.firstChild.nodeType == 3) {
  1170. let d = cell.firstChild.data
  1171. while (d.length > 0 && isSpace(d.slice(0, 1))) { d = d.slice(1) }
  1172. cell.firstChild.data = d
  1173. }
  1174. if (cell.lastChild != null && cell.lastChild.nodeType == 3) {
  1175. let d2 = cell.lastChild.data
  1176. while (d2.length > 0 && isSpace(d2.slice(d2.length - 1))) { d2 = d2.slice(0, d2.length - 1) }
  1177. cell.lastChild.data = d2
  1178. }
  1179. if (cell.childNodes.length == 0) { cell.appendChild(el('br', null)) }
  1180. }
  1181. // the children [start, end of the paragraph) go (the line before them loses its <br> too)
  1182. cutLines(p, start) {
  1183. let at = start
  1184. if (at > 0 && p.childNodes[at - 1].nodeName == 'BR') { at = at - 1 }
  1185. while (p.childNodes.length > at) { p.removeChild(p.lastChild) }
  1186. }
  1187. // Enter at the end of a typed delimiter row (`|---|:-:|`) under a header row (the line before, in this paragraph or the paragraph
  1188. // before): the two lines become a table with an empty body row, the caret in its first cell
  1189. tableByEnter(root, b) {
  1190. sel = document.getSelection()
  1191. r = sel.getRangeAt(0)
  1192. rest = document.createRange()
  1193. rest.selectNodeContents(b)
  1194. rest.setStart(r.endContainer, r.endOffset)
  1195. if (clean(rest.toString()).trim() != '') { return false }
  1196. ll = lastLines(b)
  1197. if (!linePlain(b, ll[0], ll[1])) { return false }
  1198. aligns = alignsOf(lineText(b, ll[0], ll[1]))
  1199. if (aligns == null) { return false }
  1200. let hp = b
  1201. let hFrom = ll[2]
  1202. let hTo = ll[0] - 1
  1203. if (hFrom < 0) {
  1204. hp = b.previousSibling
  1205. if (hp == null || hp.nodeName != 'P') { return false }
  1206. hl = lastLines(hp)
  1207. hFrom = hl[0]
  1208. hTo = hl[1]
  1209. }
  1210. if (hTo <= hFrom || trimSp(lineText(hp, hFrom, hTo)) == '') { return false }
  1211. cells = headCells(hp, hFrom, hTo, aligns)
  1212. if (cells == null) { return false }
  1213. table = el('table', null)
  1214. head = el('thead', null)
  1215. tr = el('tr', null)
  1216. for (c of cells) { tr.appendChild(c) }
  1217. head.appendChild(tr)
  1218. table.appendChild(head)
  1219. // the lines go: the delimiter (and, in the same paragraph, the header); an emptied paragraph goes too
  1220. cutLines(b, hp == b ? hFrom : ll[0])
  1221. if (hp != b) { b.parentNode.removeChild(b) cutLines(hp, hFrom) }
  1222. if (isBlank(hp)) { hp.parentNode.replaceChild(table, hp) } else { hp.parentNode.insertBefore(table, hp.nextSibling) }
  1223. row = newRow(table, tr)
  1224. if (table.nextSibling == null) { paraAfter(root, table) }
  1225. caretIn(row.firstChild, false)
  1226. sync(root)
  1227. return true
  1228. }
  1229. // 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
  1230. // whole goes; the text before and after it is cut on its own (it never joins the table). false = no table in the selection.
  1231. cutAcross(root) {
  1232. sel = document.getSelection()
  1233. if (sel.rangeCount == 0 || sel.isCollapsed) { return false }
  1234. r = sel.getRangeAt(0)
  1235. c1 = cellOf(root, r.startContainer)
  1236. c2 = cellOf(root, r.endContainer)
  1237. if (c1 != null && c1 == c2) { return false }
  1238. tables = []
  1239. for (tq of surfaceOf(root).querySelectorAll('table')) { if (r.intersectsNode(tq)) { tables.push(tq) } }
  1240. if (tables.length == 0) { return false }
  1241. // the boundaries of the text outside the tables, taken before anything changes
  1242. cuts = []
  1243. first = tables[0]
  1244. last = tables[tables.length - 1]
  1245. if (cellOf(root, r.startContainer) == null) { a = document.createRange() a.setStart(r.startContainer, r.startOffset) a.setEndBefore(first) cuts.push(a) }
  1246. let i = 0
  1247. while (i + 1 < tables.length) { let m = document.createRange() m.setStartAfter(tables[i]) m.setEndBefore(tables[i + 1]) cuts.push(m) i = i + 1 }
  1248. if (cellOf(root, r.endContainer) == null) { z = document.createRange() z.setStartAfter(last) z.setEnd(r.endContainer, r.endOffset) cuts.push(z) }
  1249. gone = []
  1250. for (tb of tables) {
  1251. let cells = tb.querySelectorAll('th, td')
  1252. let head = document.createRange()
  1253. head.setStart(cells[0], 0)
  1254. let tail = document.createRange()
  1255. tail.selectNodeContents(cells[cells.length - 1])
  1256. tail.collapse(false)
  1257. // compareBoundaryPoints: 0 = START_TO_START, 2 = END_TO_END
  1258. if (r.compareBoundaryPoints(0, head) <= 0 && r.compareBoundaryPoints(2, tail) >= 0) { gone.push(tb) }
  1259. else {
  1260. for (c of cells) {
  1261. if (r.intersectsNode(c)) {
  1262. let part = document.createRange()
  1263. part.selectNodeContents(c)
  1264. if (c.contains(r.startContainer)) { part.setStart(r.startContainer, r.startOffset) }
  1265. if (c.contains(r.endContainer)) { part.setEnd(r.endContainer, r.endOffset) }
  1266. part.deleteContents()
  1267. if (c.childNodes.length == 0 || isBlank(c)) { c.textContent = '' c.appendChild(el('br', null)) }
  1268. }
  1269. }
  1270. }
  1271. }
  1272. for (cut of cuts) { cut.deleteContents() }
  1273. // the caret: where the selection began (in a removed table: the block that takes its place)
  1274. let at = null
  1275. for (tg of gone) {
  1276. if (tg.contains(r.startContainer)) { at = paraAfter(root, tg) }
  1277. tg.parentNode.removeChild(tg)
  1278. }
  1279. s = surfaceOf(root)
  1280. if (s.childNodes.length == 0) { np = el('p', null) np.appendChild(el('br', null)) s.appendChild(np) at = np }
  1281. if (at != null) { sel.collapse(at, 0) } else { sel.collapse(r.startContainer, r.startOffset) }
  1282. return true
  1283. }
  1284. // 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
  1285. // after a table / the end of the block before one: never merged (an empty paragraph goes)
  1286. tableDelete(root, back) {
  1287. sel = document.getSelection()
  1288. if (!sel.isCollapsed || !inSurface(root)) { return false }
  1289. r = sel.getRangeAt(0)
  1290. cell = cellOf(root, sel.anchorNode)
  1291. let box = cell
  1292. if (box == null) { box = blockOf(root, sel.anchorNode) }
  1293. if (box == null) { return false }
  1294. edge = document.createRange()
  1295. edge.selectNodeContents(box)
  1296. if (back) { edge.setEnd(r.startContainer, r.startOffset) } else { edge.setStart(r.endContainer, r.endOffset) }
  1297. if (clean(edge.toString()) != '' || edge.cloneContents().querySelector('img') != null) { return false }
  1298. if (cell != null) {
  1299. if (back) {
  1300. all = cell.closest('table').querySelectorAll('th, td')
  1301. let i = 0
  1302. while (i < all.length && all[i] != cell) { i = i + 1 }
  1303. if (i > 0) { caretIn(all[i - 1], true) }
  1304. }
  1305. return true
  1306. }
  1307. next = back ? box.previousSibling : box.nextSibling
  1308. if (next == null || next.nodeName != 'TABLE') { return false }
  1309. if (isBlank(box)) { box.parentNode.removeChild(box) sync(root) }
  1310. if (back) { tail = next.querySelectorAll('th, td') caretIn(tail[tail.length - 1], true) }
  1311. else if (box.parentNode == null) { caretIn(next.querySelector('th, td'), false) }
  1312. return true
  1313. }
  1314. // the editing rules of tables, before the browser edits: true = handled (the browser's edit is cancelled)
  1315. tableBefore(root, e) {
  1316. t = e.inputType
  1317. if (t.startsWith('delete') || t.startsWith('insert')) {
  1318. if (cutAcross(root)) {
  1319. if (t == 'insertText' && e.data != null) { document.execCommand('insertText', false, e.data) }
  1320. sync(root)
  1321. return true
  1322. }
  1323. }
  1324. sel = document.getSelection()
  1325. if (sel.rangeCount == 0 || sel.anchorNode == null || !inSurface(root)) { return false }
  1326. cell = cellOf(root, sel.anchorNode)
  1327. if (t == 'insertParagraph') {
  1328. if (cell != null) { rowEnter(root, cell) return true }
  1329. b = blockOf(root, sel.anchorNode)
  1330. if (b != null && b.nodeName == 'P' && sel.isCollapsed) { return tableByEnter(root, b) }
  1331. return false
  1332. }
  1333. // a cell is one line
  1334. if (t == 'insertLineBreak' && cell != null) { return true }
  1335. if (t.startsWith('delete') && (t.endsWith('Backward') || t.endsWith('Forward'))) { return tableDelete(root, t.endsWith('Backward')) }
  1336. return false
  1337. }
  1338. // ---- pasting: Markdown text (a table in it becomes a table), an HTML table (its cells' text), anything into a cell on one line
  1339. // the inline html of one line of Markdown (null when it is not a plain paragraph)
  1340. inlineHtml(md) {
  1341. box = document.createElement('div')
  1342. parseInto(box, md)
  1343. if (box.childNodes.length == 1 && box.firstChild.nodeName == 'P') { return box.firstChild.innerHTML }
  1344. return null
  1345. }
  1346. // 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
  1347. // block the caret is in is split there, the new blocks go between its halves (after a list, a code block or a table)
  1348. insertBlocks(root, box) {
  1349. s = surfaceOf(root)
  1350. sel = document.getSelection()
  1351. if (!inSurface(root)) { s.focus() sel.selectAllChildren(s) sel.collapseToEnd() }
  1352. if (!sel.isCollapsed) { document.execCommand('delete') }
  1353. r = sel.getRangeAt(0)
  1354. b = blockOf(root, sel.anchorNode)
  1355. let ref = null
  1356. if (b == null) { ref = s.childNodes.item(sel.anchorOffset) }
  1357. else if (['P', 'DIV', 'H1', 'H2', 'H3', 'H4', 'H5', 'H6'].indexOf(b.nodeName) >= 0) {
  1358. tail = document.createRange()
  1359. tail.selectNodeContents(b)
  1360. tail.setStart(r.startContainer, r.startOffset)
  1361. after = b.cloneNode(false)
  1362. after.appendChild(tail.extractContents())
  1363. ref = b.nextSibling
  1364. if (!isBlank(after)) { s.insertBefore(after, ref) ref = after }
  1365. if (isBlank(b)) { s.removeChild(b) }
  1366. } else { ref = b.nextSibling }
  1367. let last = null
  1368. while (box.firstChild != null) { last = box.firstChild s.insertBefore(last, ref) }
  1369. if (last == null) { return null }
  1370. if (last.nodeName == 'TABLE') {
  1371. if (last.nextSibling == null) { paraAfter(root, last) }
  1372. cells = last.querySelectorAll('th, td')
  1373. caretIn(cells[cells.length - 1], true)
  1374. } else { sel.selectAllChildren(last) sel.collapseToEnd() }
  1375. }
  1376. // the alignment a pasted cell asks for (data-align, align or text-align)
  1377. htmlAlign(c) {
  1378. let v = c.getAttribute('data-align')
  1379. if (v == null) { v = c.getAttribute('align') }
  1380. if (v == null) { v = c.style.textAlign }
  1381. v = v == null ? '' : v.toLowerCase()
  1382. return v == 'left' || v == 'center' || v == 'right' ? v : ''
  1383. }
  1384. // a pasted HTML table as an editor table: every row (thead / tbody / tfoot) with its cells' text, the first row the header,
  1385. // as many columns as the widest row
  1386. htmlTable(t) {
  1387. trs = t.rows
  1388. let cols = 0
  1389. for (row of trs) { if (row.cells.length > cols) { cols = row.cells.length } }
  1390. if (cols == 0) { return null }
  1391. out = el('table', null)
  1392. head = el('thead', null)
  1393. body = el('tbody', null)
  1394. let r = 0
  1395. while (r < trs.length) {
  1396. let tr = el('tr', null)
  1397. let k = 0
  1398. while (k < cols) {
  1399. let src = k < trs[r].cells.length ? trs[r].cells[k] : null
  1400. let first = k < trs[0].cells.length ? trs[0].cells[k] : null
  1401. let cell = el(r == 0 ? 'th' : 'td', null)
  1402. let al = first != null ? htmlAlign(first) : ''
  1403. if (al != '') { cell.setAttribute('data-align', al) }
  1404. let text = src != null ? trimSp(src.textContent.split(NL).join(' ')) : ''
  1405. if (text == '') { cell.appendChild(el('br', null)) } else { cell.appendChild(document.createTextNode(text)) }
  1406. tr.appendChild(cell)
  1407. k = k + 1
  1408. }
  1409. if (r == 0) { head.appendChild(tr) } else { body.appendChild(tr) }
  1410. r = r + 1
  1411. }
  1412. out.appendChild(head)
  1413. if (body.childNodes.length > 0) { out.appendChild(body) }
  1414. return out
  1415. }
  1416. // pasted HTML that holds a table: its tables as tables, every other text as plain text paragraphs (no other element is taken)
  1417. htmlBlocks(node, box) {
  1418. kids = node.childNodes
  1419. let i = 0
  1420. while (i < kids.length) {
  1421. let k = kids[i]
  1422. if (k.nodeType == 3) {
  1423. let p = box.lastChild
  1424. if (p == null || p.nodeName != 'P') { p = el('p', null) box.appendChild(p) }
  1425. p.appendChild(document.createTextNode(k.data.split(NL).join(' ')))
  1426. } else if (k.nodeType == 1 && k.nodeName == 'TABLE') {
  1427. let t = htmlTable(k)
  1428. if (t != null) { box.appendChild(t) }
  1429. } else if (k.nodeType == 1 && 'SCRIPT,STYLE,TEMPLATE,HEAD,TITLE,META,LINK,svg'.split(',').indexOf(k.nodeName) < 0) {
  1430. 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) >= 0
  1431. if (block) { box.appendChild(el('p', null)) }
  1432. htmlBlocks(k, box)
  1433. if (block) { box.appendChild(el('p', null)) }
  1434. }
  1435. i = i + 1
  1436. }
  1437. }
  1438. // ---- 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)
  1439. Style {
  1440. '@keyframes md-editor-mount' { 'from' { opacity = '.999' } to { opacity = '1' } }
  1441. 'md-editor' { position = 'relative' display = 'block' border = '0' borderRadius = '.5rem' background = 'var(--color-background-sunken, #f2f2f2)' color = 'var(--color-text, #000)' }
  1442. 'md-editor:focus-within' { outline = '2px solid var(--color-accent, #555)' outlineOffset = '-1px' }
  1443. 'md-editor nav' { display = 'flex' flexWrap = 'wrap' gap = '.25rem' padding = '.35rem' borderBottom = '0' background = 'var(--color-surface, #ddd)' borderRadius = '.5rem .5rem 0 0' }
  1444. 'md-editor nav 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' }
  1445. 'md-editor nav button:hover' { background = 'var(--color-background, #fff)' }
  1446. 'md-editor nav button.on' { color = 'var(--color-accent-text, #fff)' background = 'var(--color-accent, #000)' }
  1447. // the toolbar buttons hold an Icon (components/icons): an SVG in the text colour; the heading button adds the level the caret is in (data-level) as a small number
  1448. 'md-editor nav button svg' { display = 'block' }
  1449. 'md-editor nav button.heading[data-level]:not([data-level=""])::after' { content = 'attr(data-level)' marginLeft = '.1rem' fontSize = '.7rem' lineHeight = '1' }
  1450. 'md-editor nav button.heading' { display = 'inline-flex' alignItems = 'center' justifyContent = 'center' }
  1451. 'md-editor[data-files="off"] nav button.file' { display = 'none' }
  1452. 'md-editor nav button:disabled' { opacity = '.4' cursor = 'default' }
  1453. 'md-editor.source nav button' { opacity = '.4' pointerEvents = 'none' }
  1454. 'md-editor nav input.pick' { display = 'none' }
  1455. // a phone (E2): the toolbar is a grid of TWO EVEN ROWS (6 + 5 buttons; with `files = "off"` 5 + 5), every button a 44 px target on a
  1456. // share of the width, so no icon is clipped at the edge and nothing hides behind a sideways swipe; `min-width: 0` lets the grid shrink
  1457. // to a narrow parent. The footer's "Markdown source" label is 15 px (the quiet muted colour stays) and a 44 px target; the table head
  1458. // text takes the body size (an app theme's smaller `th` size made the head smaller than the cells).
  1459. '@media (max-width: 40rem)' {
  1460. 'md-editor nav' { display = 'grid' gridTemplateColumns = 'repeat(6, minmax(0, 1fr))' gap = '.25rem' }
  1461. 'md-editor nav button' { minWidth = '0' minHeight = '2.75rem' padding = '.25rem 0' }
  1462. 'md-editor article th' { fontSize = '1rem' }
  1463. 'md-editor footer button' { fontSize = '.9375rem' minHeight = '2.75rem' padding = '.2rem .8rem' }
  1464. }
  1465. 'md-editor ul.files' { display = 'none' margin = '0' padding = '.35rem .8rem' listStyle = 'none' borderBottom = '0' fontSize = '.85rem' }
  1466. 'md-editor ul.files:not(:empty)' { display = 'block' }
  1467. 'md-editor ul.files li' { display = 'flex' alignItems = 'center' gap = '.6rem' }
  1468. 'md-editor ul.files li span' { flex = '0 1 12rem' overflow = 'hidden' textOverflow = 'ellipsis' whiteSpace = 'nowrap' }
  1469. 'md-editor ul.files progress' { flex = '1' accentColor = 'var(--color-accent, #000)' }
  1470. 'md-editor ul.files li.error' { color = 'var(--color-danger, #000)' }
  1471. 'md-editor link-form' { display = 'none' gap = '.35rem' padding = '.35rem' borderBottom = '0' background = 'var(--color-surface, #ddd)' }
  1472. 'md-editor.linking link-form' { display = 'flex' }
  1473. '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' }
  1474. 'md-editor link-form button' { font = 'inherit' padding = '.3rem .7rem' color = 'var(--color-text, #000)' background = 'transparent' border = '0' borderRadius = '.35rem' cursor = 'pointer' }
  1475. 'md-editor article' { display = 'block' minHeight = '1.5em' padding = '.6rem .8rem' outline = 'none' overflowWrap = 'anywhere' animation = 'md-editor-mount 1ms infinite' }
  1476. // THE FOCUS RING IS THE EDITOR'S ONLY: the surface and the source view never draw their own (an app theme's `:focus-visible` / `textarea:focus` would add a second rectangle inside the first); these selectors out-weigh the theme's without !important
  1477. 'md-editor article:focus, md-editor article:focus-visible, md-editor textarea:focus, md-editor textarea:focus-visible' { outline = 'none' }
  1478. 'md-editor.source article' { display = 'none' }
  1479. 'md-editor .placeholder' { display = 'none' position = 'absolute' left = '.8rem' marginTop = '.6rem' pointerEvents = 'none' color = 'var(--color-text-muted, #555)' }
  1480. 'md-editor.md-empty:not(.source) .placeholder' { display = 'block' }
  1481. 'md-editor article > :first-child' { marginTop = '0' }
  1482. 'md-editor article > :last-child' { marginBottom = '0' }
  1483. '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)' }
  1484. 'md-editor article h1' { fontSize = '1.6rem' }
  1485. 'md-editor article h2' { fontSize = '1.35rem' }
  1486. 'md-editor article h3' { fontSize = '1.15rem' }
  1487. 'md-editor article h4, md-editor article h5, md-editor article h6' { fontSize = '1rem' }
  1488. 'md-editor article p' { margin = '0 0 .7rem' }
  1489. 'md-editor article ul, md-editor article ol' { margin = '0 0 .7rem' paddingLeft = '1.5rem' }
  1490. 'md-editor article img' { display = 'block' maxWidth = '100%' height = 'auto' margin = '.3rem 0' borderRadius = '.3rem' }
  1491. 'md-editor article strong' { color = 'var(--color-text-strong, #000)' }
  1492. 'md-editor article a' { color = 'var(--color-accent, #000)' textDecoration = 'underline' }
  1493. 'md-editor article code' { padding = '0 .25rem' fontFamily = 'ui-monospace, monospace' fontSize = '.9em' background = 'var(--color-surface, #ddd)' borderRadius = '.25rem' }
  1494. // tables take the look of the page's theme (its `table`, `th`, `td` rules: muted head, no grid, striped rows); the editor only makes them
  1495. // scroll sideways inside their own box and keeps a word whole. The :where() rules are the plain fallback where no theme styles tables.
  1496. 'md-editor article table' { display = 'block' maxWidth = '100%' overflowX = 'auto' }
  1497. 'md-editor article th, md-editor article td' { textAlign = 'start' verticalAlign = 'top' minWidth = '2.5rem' overflowWrap = 'normal' wordBreak = 'normal' }
  1498. ':where(md-editor article table)' { margin = '0 0 .7rem' borderCollapse = 'collapse' }
  1499. ':where(md-editor article th, md-editor article td)' { padding = '.3rem .6rem' }
  1500. ':where(md-editor article th)' { fontWeight = '700' }
  1501. 'md-editor article [data-align="left"]' { textAlign = 'left' }
  1502. 'md-editor article [data-align="center"]' { textAlign = 'center' }
  1503. 'md-editor article [data-align="right"]' { textAlign = 'right' }
  1504. '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' }
  1505. 'md-editor footer' { display = 'flex' justifyContent = 'flex-end' padding = '.3rem .5rem' borderTop = '0' }
  1506. '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' }
  1507. 'md-editor footer button:hover' { color = 'var(--color-text, #000)' }
  1508. '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' }
  1509. 'md-editor.source textarea' { display = 'block' }
  1510. // readonly: the formatted text alone, on the page's own background
  1511. 'md-editor[data-readonly="true"]' { background = 'transparent' borderRadius = '0' }
  1512. 'md-editor[data-readonly="true"]:focus-within' { outline = 'none' }
  1513. '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' }
  1514. 'md-editor[data-readonly="true"] article' { minHeight = '0' padding = '0' }
  1515. }
  1516. // The hidden input `name` carries the value in a form; the article is the surface; the textarea is the source view (a value shown
  1517. // only while it is on). The rendered parts never change after the first render, so the framework leaves the hand-built content alone.
  1518. View {
  1519. mdEditor { 'data-readonly' = readonly 'data-files' = files 'data-value' = value
  1520. nav {
  1521. 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') } }
  1522. 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') } }
  1523. 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') } }
  1524. 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') } }
  1525. 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') } }
  1526. 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') } }
  1527. 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') } }
  1528. 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') } }
  1529. 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') } }
  1530. 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) } }
  1531. input { type = "file" class = "pick" multiple = "multiple" on change(e) { emit mdPicked(e) } }
  1532. 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') } }
  1533. 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') } }
  1534. }
  1535. linkForm {
  1536. input { type = "text" placeholder = "https://…" autocomplete = "off" on keydown(e) { emit mdLinkKey(e) } }
  1537. button { type = "button" "Apply" on click(e) { emit mdLinkSubmit(e) } }
  1538. button { type = "button" title = "Remove the link" "Remove" on click(e) { emit mdLinkRemove(e) } }
  1539. }
  1540. ul { class = "files" 'aria-live' = "polite" }
  1541. span { class = "placeholder" placeholder }
  1542. 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) } }
  1543. textarea { style = sourceStyle rows = rows spellcheck = "false" on input(e) { emit mdSourceInput(e) } }
  1544. input { class = "value" type = "hidden" name = name value = value }
  1545. footer { button { type = "button" class = "source-switch" on click(e) { emit mdSource(e) } "Markdown source" } }
  1546. }
  1547. }
  1548. // 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
  1549. // first focus / pointer-down / key, whichever comes first (mission 011 (c): keys typed at once after showing the tab landed in an unbuilt surface).
  1550. // An editor the framework puts into the page LATER (a comment row built anew after a push) is built at once (microtasks), before the
  1551. // browser paints: waiting 100 ms for the animation showed an EMPTY text for that long, longer under load (F5, hybriel#211: the gate caught
  1552. // the empty surface of the new row). The first mounted editor starts one observer for the page (`watchPage`) that mounts every added one.
  1553. on mdMount(e) {
  1554. let root = rootOf(e.target)
  1555. mountRoot(root)
  1556. mountAll(document.body)
  1557. watchPage()
  1558. }
  1559. watchPage() {
  1560. if (window.mdWatching == true) { return null }
  1561. window.mdWatching = true
  1562. new MutationObserver((recs) => {
  1563. for (r of recs) {
  1564. for (n of r.addedNodes) { if (n.nodeType == 1 && n.closest('md-editor article') == null) { mountAll(n) } }
  1565. }
  1566. }).observe(document.body, { childList = true, subtree = true })
  1567. }
  1568. mountAll(n) {
  1569. if (n.matches('md-editor')) { mountRoot(n) }
  1570. for (m of n.querySelectorAll('md-editor')) { mountRoot(m) }
  1571. }
  1572. mountRoot(root) {
  1573. let s = surfaceOf(root)
  1574. if (s == null) { return null }
  1575. if (root.mdMounted == true) { rebuilt(root) return null }
  1576. root.mdMounted = true
  1577. root.mdSurface = s
  1578. s.style.animationName = 'none'
  1579. // a value that changes from outside after this build is loaded again; a surface the framework put in anew is drawn at once
  1580. new MutationObserver((recs) => { followValue(root) }).observe(root, { attributes = true, attributeFilter = ['data-value'] })
  1581. new MutationObserver((recs) => { rebuilt(root) }).observe(root, { childList = true })
  1582. if (root.getAttribute('data-readonly') == 'true') { load(root, fieldOf(root).value) return null }
  1583. document.execCommand('defaultParagraphSeparator', false, 'p')
  1584. document.execCommand('styleWithCSS', false, false)
  1585. // TEXT TYPED BEFORE THE BUILD: the server sends the surface already editable, and the page's scripts need a moment to start, so keys
  1586. // pressed in that moment land in the bare surface (no handler saw them, the field does not hold them) and the build below would
  1587. // 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.
  1588. let typed = ''
  1589. if (s.textContent.trim() != '') { typed = clean(s.innerText).trim() }
  1590. let start = fieldOf(root).value
  1591. if (typed != '') { start = start == '' ? typed : start + NL + NL + typed }
  1592. load(root, start)
  1593. sourceOf(root).value = start
  1594. if (typed != '') { sync(root) }
  1595. document.addEventListener('selectionchange', () => { updateBar(root) })
  1596. // focus came before the build (it emptied the surface): the caret goes to the end of the text
  1597. if (s.contains(document.activeElement) || document.activeElement == s) {
  1598. last = s.lastChild
  1599. if (last != null) { document.getSelection().collapse(last, last.textContent == '' ? 0 : last.childNodes.length) }
  1600. }
  1601. }
  1602. on mdInput(e) {
  1603. e.stopPropagation()
  1604. root = rootOf(e.target)
  1605. // 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 it
  1606. if (root.mdMounted != true) { mountRoot(root) return null }
  1607. s = surfaceOf(root)
  1608. // an emptied surface gets its paragraph back
  1609. if (s.childNodes.length == 0) {
  1610. np = document.createElement('p')
  1611. np.appendChild(document.createElement('br'))
  1612. s.appendChild(np)
  1613. document.getSelection().collapse(np, 0)
  1614. }
  1615. if (e.inputType == 'insertText' && (e.data == '*' || e.data == '_' || e.data == '`')) { inlineRule(root, e) }
  1616. sync(root)
  1617. updateBar(root)
  1618. }
  1619. on mdBefore(e) {
  1620. root = rootOf(e.target)
  1621. if (tableBefore(root, e)) { e.preventDefault() updateBar(root) return null }
  1622. if (e.inputType == 'insertText' && e.data == ' ') { blockRule(root, e) }
  1623. }
  1624. on mdKey(e) {
  1625. root = rootOf(e.target)
  1626. if (root.mdMounted != true) { mountRoot(root) }
  1627. mod = e.ctrlKey || e.metaKey
  1628. // in a table: Tab / Shift+Tab move between the cells; a cell takes no block (heading, list, code block)
  1629. if (inCell(root)) {
  1630. if (e.key == 'Tab' && !mod && !e.altKey) { e.preventDefault() cellTab(root, cellOf(root, document.getSelection().anchorNode), e.shiftKey) updateBar(root) return null }
  1631. 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 }
  1632. }
  1633. if (mod && !e.shiftKey && !e.altKey && (e.key == 'k' || e.key == 'K')) { e.preventDefault() linkOpen(root) return null }
  1634. if (mod && !e.shiftKey && !e.altKey && (e.key == 'e' || e.key == 'E')) { e.preventDefault() codeToggle(root) sync(root) return null }
  1635. if (mod && e.shiftKey && (e.key == '8' || e.key == '*')) { e.preventDefault() blockToggle(root, 'ul', 'insertUnorderedList') sync(root) return null }
  1636. if (mod && e.shiftKey && (e.key == '7' || e.key == '&')) { e.preventDefault() blockToggle(root, 'ol', 'insertOrderedList') sync(root) return null }
  1637. if (mod && e.altKey && e.code == 'KeyC') { e.preventDefault() blockToggle(root, 'pre', '') sync(root) return null }
  1638. if (mod && e.altKey && e.code == 'Digit0') { e.preventDefault() document.execCommand('formatBlock', false, 'p') sync(root) return null }
  1639. 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 }
  1640. // Ctrl+Enter sends the form the editor sits in
  1641. if (mod && e.key == 'Enter') {
  1642. e.preventDefault()
  1643. form = root.closest('form')
  1644. if (form != null) { form.requestSubmit() }
  1645. return null
  1646. }
  1647. // Backspace at the very start of a heading / list item / code block turns it into a paragraph
  1648. if (e.key == 'Backspace' && document.getSelection().isCollapsed && inSurface(root)) {
  1649. let sel = document.getSelection()
  1650. let b = blockOf(root, sel.anchorNode)
  1651. if (b != null && 'h1,h2,h3,h4,h5,h6,ul,ol,pre'.split(',').indexOf(b.nodeName.toLowerCase()) >= 0) {
  1652. r = sel.getRangeAt(0)
  1653. pre = document.createRange()
  1654. pre.selectNodeContents(b)
  1655. pre.setEnd(r.endContainer, r.endOffset)
  1656. if (pre.toString() == '') {
  1657. e.preventDefault()
  1658. tag = b.nodeName.toLowerCase()
  1659. if (tag == 'ul') { document.execCommand('insertUnorderedList') }
  1660. else if (tag == 'ol') { document.execCommand('insertOrderedList') }
  1661. else { document.execCommand('formatBlock', false, 'p') }
  1662. sync(root)
  1663. return null
  1664. }
  1665. }
  1666. }
  1667. // 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)
  1668. if (e.key == 'Enter' && !mod && !e.shiftKey && inTag(root, ['pre']) && document.getSelection().isCollapsed) {
  1669. let xsel = document.getSelection()
  1670. let xb = blockOf(root, xsel.anchorNode)
  1671. if (xb != null && xb.nodeName == 'PRE') {
  1672. let xr = xsel.getRangeAt(0)
  1673. let xrest = document.createRange()
  1674. xrest.setStart(xr.endContainer, xr.endOffset)
  1675. xrest.setEnd(xb, xb.childNodes.length)
  1676. let xkids = xb.childNodes
  1677. if (xrest.toString() == '' && xkids.length >= 2 && xkids[xkids.length - 1].nodeName == 'BR' && xkids[xkids.length - 2].nodeName == 'BR') {
  1678. e.preventDefault()
  1679. xb.removeChild(xkids[xkids.length - 1])
  1680. let xnp = el('p', null)
  1681. xnp.appendChild(el('br', null))
  1682. xb.parentNode.insertBefore(xnp, xb.nextSibling)
  1683. if (clean(xb.textContent) == '') { xb.parentNode.removeChild(xb) }
  1684. xsel.collapse(xnp, 0)
  1685. sync(root)
  1686. updateBar(root)
  1687. return null
  1688. }
  1689. }
  1690. }
  1691. // ``` at the start of a line + Enter opens a code block
  1692. if (e.key == 'Enter' && !mod && !e.shiftKey && !inTag(root, ['pre'])) {
  1693. let sel = document.getSelection()
  1694. let b = sel.anchorNode != null ? blockOf(root, sel.anchorNode) : null
  1695. if (b != null && b.nodeName.toLowerCase() == 'p' && sel.isCollapsed && (clean(b.textContent).startsWith('```') || clean(b.textContent).startsWith('~~~')) && clean(b.textContent).replaceAll('`', '').replaceAll('~', '') == '') {
  1696. e.preventDefault()
  1697. sel.selectAllChildren(b)
  1698. document.execCommand('delete')
  1699. document.execCommand('formatBlock', false, 'pre')
  1700. sync(root)
  1701. }
  1702. }
  1703. }
  1704. on mdTool(e, tool) {
  1705. root = rootOf(e.target)
  1706. s = surfaceOf(root)
  1707. if (!inSurface(root)) { s.focus() }
  1708. // a cell takes no block
  1709. if (inCell(root) && (tool == 'heading' || tool == 'ul' || tool == 'ol' || tool == 'pre')) { return null }
  1710. if (tool == 'table') { if (!inCell(root)) { tableInsert(root) } updateBar(root) return null }
  1711. if (tool == 'bold') { document.execCommand('bold') }
  1712. if (tool == 'italic') { document.execCommand('italic') }
  1713. if (tool == 'code') { codeToggle(root) }
  1714. if (tool == 'link') { linkOpen(root) return null }
  1715. if (tool == 'heading') { headingCycle(root) }
  1716. if (tool == 'ul') { blockToggle(root, 'ul', 'insertUnorderedList') }
  1717. if (tool == 'ol') { blockToggle(root, 'ol', 'insertOrderedList') }
  1718. if (tool == 'pre') { blockToggle(root, 'pre', '') }
  1719. if (tool == 'undo') { document.execCommand('undo') }
  1720. if (tool == 'redo') { document.execCommand('redo') }
  1721. sync(root)
  1722. updateBar(root)
  1723. }
  1724. on mdLinkSubmit(e) { linkApply(rootOf(e.target), false) }
  1725. on mdLinkRemove(e) { linkApply(rootOf(e.target), true) }
  1726. on mdLinkKey(e) {
  1727. if (e.key == 'Escape') { e.preventDefault() linkClose(rootOf(e.target)) }
  1728. if (e.key == 'Enter') { e.preventDefault() linkApply(rootOf(e.target), false) }
  1729. }
  1730. // 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
  1731. // is put in as elements; into a cell everything goes on one line
  1732. insertMarkdown(root, text) {
  1733. if (inTag(root, ['pre'])) { document.execCommand('insertText', false, text) return null }
  1734. cutAcross(root)
  1735. if (inCell(root)) {
  1736. one = trimSp(text.split(NL).join(' '))
  1737. if (one == '') { return null }
  1738. html = inlineHtml(one)
  1739. if (html != null) { document.execCommand('insertHTML', false, html) } else { document.execCommand('insertText', false, one) }
  1740. return null
  1741. }
  1742. box = el('div', null)
  1743. parseInto(box, text)
  1744. if (box.querySelector('table') != null) { insertBlocks(root, box) return null }
  1745. document.execCommand('insertHTML', false, mdHtml(text))
  1746. }
  1747. // copy and cut (components#20): the clipboard gets the selection's Markdown as its plain text (and its HTML), so that pasting it back
  1748. // into an editor gives the same headings, lists, links and breaks. The browser's own plain text of a selection has the marks stripped
  1749. // and the blocks run together. A selection inside a code block or a table cell is left to the browser (its text is already the text).
  1750. clipSelection(e, cutting) {
  1751. root = rootOf(e.target)
  1752. sel = window.getSelection()
  1753. if (sel.rangeCount == 0 || sel.isCollapsed) { return null }
  1754. if (inTag(root, ['pre']) || inCell(root)) { return null }
  1755. box = el('div', null)
  1756. box.appendChild(sel.getRangeAt(0).cloneContents())
  1757. md = toMarkdown(box)
  1758. if (md == '') { return null }
  1759. e.preventDefault()
  1760. e.clipboardData.setData('text/plain', md)
  1761. e.clipboardData.setData('text/html', box.innerHTML)
  1762. if (cutting) {
  1763. if (!cutAcross(root)) { document.execCommand('delete') }
  1764. sync(root)
  1765. }
  1766. }
  1767. on mdCopy(e) { clipSelection(e, false) }
  1768. on mdCut(e) { clipSelection(e, true) }
  1769. on mdPaste(e) {
  1770. e.preventDefault()
  1771. root = rootOf(e.target)
  1772. // files = "off": pasted files are the page's (they bubble on to a FilesUpload around the editor)
  1773. if (e.clipboardData.files.length > 0) {
  1774. if (root.getAttribute('data-files') != 'off') { attach(root, e.clipboardData.files, null) }
  1775. return null
  1776. }
  1777. // copied HTML with a table in it (a spreadsheet, a web page): its tables become tables (their cells' text), the rest plain text
  1778. html = e.clipboardData.getData('text/html')
  1779. if (!inCell(root) && !inTag(root, ['pre']) && html.toLowerCase().indexOf('<table') >= 0) {
  1780. // an inert document (no browsing context: it runs no script and loads nothing); hl:web compiles no `new DOMParser()` (repro
  1781. // .scratch/w004/gap-domparser/)
  1782. doc = document.implementation.createHTMLDocument('')
  1783. doc.body.innerHTML = html
  1784. box = el('div', null)
  1785. htmlBlocks(doc.body, box)
  1786. if (box.querySelector('table') != null) {
  1787. insertMarkdown(root, toMarkdown(box))
  1788. sync(root)
  1789. return null
  1790. }
  1791. }
  1792. // a Windows clipboard ends its lines with CR LF: the CRs go (in a cell or a code block too)
  1793. let text = e.clipboardData.getData('text/plain').replaceAll(CR, '')
  1794. // a clipboard with HTML but no plain text (some apps and pages copy that way): the text of its blocks, as Markdown
  1795. if (trimSp(text) == '' && html != '') {
  1796. let hdoc = document.implementation.createHTMLDocument('')
  1797. hdoc.body.innerHTML = html
  1798. let hbox = el('div', null)
  1799. htmlBlocks(hdoc.body, hbox)
  1800. text = toMarkdown(hbox)
  1801. }
  1802. if (trimSp(text) == '') { return null }
  1803. insertMarkdown(root, text)
  1804. sync(root)
  1805. }
  1806. on mdDrop(e) {
  1807. e.preventDefault()
  1808. root = rootOf(e.target)
  1809. if (e.dataTransfer.files.length > 0) {
  1810. if (root.getAttribute('data-files') == 'off') { return null }
  1811. at = document.caretRangeFromPoint(e.clientX, e.clientY)
  1812. attach(root, e.dataTransfer.files, at)
  1813. return null
  1814. }
  1815. text = e.dataTransfer.getData('text/plain')
  1816. if (text != '') { insertMarkdown(root, text) sync(root) }
  1817. }
  1818. // ---- files and images: dropped, pasted or chosen files go to the app through `emit server mdUpload(files)` (the framework sends them
  1819. // over HTTP with progress); the app stores them and answers the addresses; each lands in the text as ![name](address) (an image) or
  1820. // [name](address). Progress comes back as `uploadProgress` and is shown under the toolbar.
  1821. fileRow(root, p) {
  1822. list = root.querySelector('ul.files')
  1823. let li = list.children[p.index]
  1824. if (li == null) {
  1825. li = document.createElement('li')
  1826. li.appendChild(el('span', p.name))
  1827. li.appendChild(document.createElement('progress'))
  1828. list.appendChild(li)
  1829. }
  1830. bar = li.querySelector('progress')
  1831. bar.max = p.size
  1832. bar.value = p.sent
  1833. }
  1834. on client uploadProgress(p) {
  1835. for (root of document.querySelectorAll('md-editor.uploading')) { fileRow(root, p) }
  1836. }
  1837. attachMd(names, kinds, urls) {
  1838. out = []
  1839. let i = 0
  1840. while (i < urls.length) {
  1841. let label = names[i].replaceAll('[', '').replaceAll(']', '')
  1842. let u = urls[i].replaceAll(')', '%29').replaceAll(' ', '%20')
  1843. if (urls[i] != '') { out.push((kinds[i] ? '!' : '') + '[' + label + '](' + u + ')') }
  1844. i = i + 1
  1845. }
  1846. return out.join(NL + NL)
  1847. }
  1848. attach(root, files, at) {
  1849. s = surfaceOf(root)
  1850. sel = document.getSelection()
  1851. let range = at
  1852. if (range == null && inSurface(root)) { range = sel.getRangeAt(0).cloneRange() }
  1853. list = []
  1854. names = []
  1855. kinds = []
  1856. let k = 0
  1857. while (k < files.length) { list.push(files[k]) names.push(files[k].name) kinds.push(files[k].type.startsWith('image/')) k = k + 1 }
  1858. box = root.querySelector('ul.files')
  1859. box.textContent = ''
  1860. root.classList.add('uploading')
  1861. root.classList.remove('failed')
  1862. urls = emit server mdUpload(list)
  1863. root.classList.remove('uploading')
  1864. if (urls == null || urls.length != list.length) {
  1865. root.classList.add('failed')
  1866. box.textContent = ''
  1867. li = el('li', 'The upload failed.')
  1868. li.className = 'error'
  1869. box.appendChild(li)
  1870. return null
  1871. }
  1872. box.textContent = ''
  1873. s.focus()
  1874. if (range != null && s.contains(range.startContainer)) { sel.removeAllRanges() sel.addRange(range) }
  1875. else { sel.selectAllChildren(s) sel.collapseToEnd() }
  1876. md = attachMd(names, kinds, urls)
  1877. if (md == '') { return null }
  1878. // 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
  1879. // item's text: it is put on its own after the list, as elements (an editing command would join it to the item)
  1880. let top = null
  1881. if (sel.anchorNode == s) { top = s.childNodes[sel.anchorOffset - 1 >= 0 ? sel.anchorOffset - 1 : 0] }
  1882. else if (sel.anchorNode != null && s.contains(sel.anchorNode)) { top = blockOf(root, sel.anchorNode) }
  1883. if (top != null && (top.nodeName == 'UL' || top.nodeName == 'OL')) {
  1884. tmp = document.createElement('div')
  1885. parseInto(tmp, md)
  1886. ref = top.nextSibling
  1887. while (tmp.firstChild != null) { s.insertBefore(tmp.firstChild, ref) }
  1888. sel.selectAllChildren(s)
  1889. sel.collapseToEnd()
  1890. sync(root)
  1891. return null
  1892. }
  1893. insertMarkdown(root, md)
  1894. sync(root)
  1895. }
  1896. on mdPick(e) {
  1897. root = rootOf(e.target)
  1898. root.querySelector('input.pick').click()
  1899. }
  1900. on mdPicked(e) {
  1901. root = rootOf(e.target)
  1902. input = e.target
  1903. if (input.files.length > 0) { attach(root, input.files, null) }
  1904. input.value = ''
  1905. }
  1906. // Ctrl / Cmd + click follows a link
  1907. on mdClick(e) {
  1908. a = e.target.closest('a')
  1909. if ((e.ctrlKey || e.metaKey) && a != null && safeHref(a.getAttribute('href')) != '') { window.open(a.getAttribute('href'), '_blank', 'noopener') }
  1910. }
  1911. on mdBlur(e) { sync(rootOf(e.target)) }
  1912. // the Markdown source view: the whole field as a plain textarea, and back
  1913. on mdSource(e) {
  1914. root = rootOf(e.target)
  1915. ta = sourceOf(root)
  1916. b = root.querySelector('button.source-switch')
  1917. if (root.classList.contains('source')) {
  1918. md = ta.value
  1919. load(root, md)
  1920. root.classList.remove('source')
  1921. b.textContent = 'Markdown source'
  1922. sync(root)
  1923. surfaceOf(root).focus()
  1924. } else {
  1925. sync(root)
  1926. ta.value = fieldOf(root).value
  1927. root.classList.add('source')
  1928. b.textContent = 'Visual editor'
  1929. ta.focus()
  1930. }
  1931. }
  1932. on mdSourceInput(e) {
  1933. root = rootOf(e.target)
  1934. f = fieldOf(root)
  1935. f.value = e.target.value
  1936. root.mdLast = f.value
  1937. own(root, f.value)
  1938. f.dispatchEvent(new Event('input', { bubbles = true }))
  1939. }

Branches

Latest commits

  • 3a8bc0d2N5: empty Table-button table is written as a real pipe table (MdEditor 4bd1112, plain copy); gate tests/table-button.mjs; reportmre
  • c16bd443N5: step 1 report (tables pass locally; his DASHBOARD note has no delimiter row)mre
  • 6091320anotes: MdEditor 7437e32 (surface drawn at once when the page is claimed); gate measures claim-to-text on 5 note loads at 1280 and 390mre
  • 0aa9277enotes: move each component's styles into its own Style block (shell and header selector in main.hl, list, editor frame and delete question in notes.hl); styles.hl keeps the theme inherit, the accent and the message colour; .gitignore ignores a bin symlink too; tests/shots.mjs for the pixel comparemre
  • 9ba01de3notes: write the standby service out in full so the boot gate can read the main servicemre
  • 98cab40anotes: standby service on its port plus 10 and a deploy that hands over through it without a gapmre
  • 1fadb473notes gate: the editor table now has 1 px cell lines from the notes thememre
  • 8762115cnotes: take the components e54f83a (paste as Markdown, text typed before the editor is built is kept, Table button); table lines come from the notes thememre
  • ac23e194ident#31: the selector's sign-in returns to the page the user started on (return attribute = the login callback with next), gate checkmre
  • 2804f0d3Merge branch 'iw-ident-widget'mre
  • 52d8d242notes: e2e script checks Log out and the selector in the header instead of the user menumre
  • e5abf7b7notes header: the selector alone top right plus Log out as before the theme missions; the user icon is gonemre
  • a2e343aeident selector back in the header (creator 2026-10-24): selector top right signed in and out on phone and desktop, no second Log in button, new gate checks (WIP: gates not re-run after the last edits)mre
  • 7a889b82notes: MdEditor with the Table button, typed pipe rows and the theme's table look (components mt-tables); a table note is named by its header words; gate checks that fail on mainmre
  • b96c7f70theme: sync from layouts 4994037 (list rows stack, td word-keep, heading code, edited tap target)mre
  • 6140e6a0sessions last 99 years (creator 2026-10-23: logins never expire; only sign out ends them)mre
  • cb7e6469deploy: security gate (tests/security.mjs)mre
  • 774bf34bnotes security: CSRF guard on /api/notes, new session at login, Secure cookie, uploadMax 0, login rate limit, nosniff, face payload check; tests/security.mjs; SN reportmre
  • ef18a68fsync components.hybriel 214c318: MdEditor on a phone, two even toolbar rows of 44 px targets, label 15 px, table head 16 px (E2)mre
  • c37488b1MN report: alignment updatemre