gitoria

components

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commitdd003e5ddd003e5dMediaPlayer: audio and video in one phone-first player (components/media-player), its demo /media-player with a queue, the media icons in components/icons, the demo's media files served with ranges (lib/media.hl), 35 gate checksmredd003e5d/components/md-editor/md-editor.hl

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

Branches

Latest commits

  • dd003e5dMediaPlayer: audio and video in one phone-first player (components/media-player), its demo /media-player with a queue, the media icons in components/icons, the demo's media files served with ranges (lib/media.hl), 35 gate checksmre
  • e54f83adMdEditor: text typed before the editor is built is kept (the build takes it in once, the input handler no longer writes it to the field first), tickets#35mre
  • 8c920932gate: the 11 old drop-zone checks now test the one-box pick mode (drop anywhere in the box, Choose files button inside it, no drop zone)mre
  • 626de199MdEditor: copy and cut put the selection's Markdown on the clipboard, a clipboard with HTML only pastes its text, gate checks for copy, cut and paste (components#20)mre
  • 5228126dUX: components synced from the tickets/layouts UX mission (comments: State select in the footer and button words; files-upload: one-box pick mode; modal: footer rule for its own footer). WIP: the gate's #18 pick-mode checks still expect the old drop zone (11 fail), see the UX2 reportmre
  • 0a9216fbMdEditor: a Table button in the toolbar, a typed pipe row fills the cells, tables take the page theme's look; gate checks updated for 12 toolbar buttonsmre
  • f9d405c8comments: reactions row half as far from its comment (creator 2026-10-24: 'half this distance please'); the 44 px tap targets staymre
  • 4922f9cfsessions last 99 years (creator 2026-10-23: logins never expire; only sign out ends them)mre
  • 0355975areports/MC-mobile.md, LOG, STATUS (MC)mre
  • 3f0a7229Month view, date picker, range picker: names follow the page language (English by default, not the browser's), weekday/month names formatted in UTC (a UTC+12 zone showed Tue first), 44 px day cells and buttons, Send row air; gate checks at 390 px for every page, popup and dialog (MC)mre
  • 29eb07eaPhone: 44 px targets on the site (brand, home links, buttons), comments, modal and pagination; the header is the brand alone on a phone; comments demo: labelled 'You are' group with the chosen user pressed (MC)mre
  • d1cc83e2reports/E2-toolbar.mdmre
  • 214c3183MdEditor on a phone: toolbar as two even rows of 44 px targets (no clipped icon, no swipe), 'Markdown source' label 15 px, table head 16 px; gate checks (E2)mre
  • 9215bbaareports/F5-empty.mdmre
  • 134b4e3eMdEditor: an editor the framework puts into the page is built at once (page observer), a surface put in anew under a built editor is redrawn; gates for both (hybriel#211)mre
  • 0dce2899reports/K1-bubble.mdmre
  • 6b0936a0comments: 'edited' foldable also drops the theme's border, margin and radius (display: contents alone left them computed)mre
  • 8d79ff79comments bubble hugs its content: a readonly md-editor surface gets no inline min-height (it beat the stylesheet's min-height 0); 'edited' is a quiet label beside the time, versions unframed; gate checksmre
  • ef253fecreports/F4-icons.mdmre
  • ba96735ficons: README, md-editor README note, gate checks for the single focus ring and toolbar iconsmre