gitoria

layouts

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit2dbe0df52dbe0df5Re-vendor Hybriel to the shared static build 0f396652 (plugins; bin/ is git-ignored), compose cache volume + tmpfs /tmp, gate wait 120 s, report 004mre2dbe0df5/components/md-editor/md-editor.hl

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

Branches

Latest commits

  • 2dbe0df5Re-vendor Hybriel to the shared static build 0f396652 (plugins; bin/ is git-ignored), compose cache volume + tmpfs /tmp, gate wait 120 s, report 004mre
  • 0adc551emission brief 004mre
  • 1376e905deploy.sh: wait up to DEPLOY_URL_WAIT (120 s) for 200 after the restart, as the other apps (cold compile, hybriel#148)mre
  • c0fdbf6cdocker-compose: init: true (hybriel#156, PID 1 ignored SIGTERM, every restart waited 10 s)mre
  • ecf70665usage: layouts on components a567b57mre
  • 315731efcomponents re-synced to components.hybriel a567b57 (md-editor tables)mre
  • b59e2ee9docs/usage.md + tools/usage.sh: which app carries which component/theme/tokens copy, and whether it matches the sourcemre
  • 0222f67ctheme: two corner radii only (radiusSmall 5px, radiusLarge 10px); check-theme flags any other radius; gate 76/0mre
  • 877b63acdesign rules: two radii only (5px small, 10px large)mre
  • 635234dfcomponents re-synced to components.hybriel 5a98d77 (#15 black/white base look); gate 73/0, check-theme 0, screenshots unchangedmre
  • 876b2064docs: workaround note for hybriel#130 (slot marker mid-line)mre
  • 85b56541layouts mission 002 3/3: same-output tests, letcount, shots ports, docs, reportmre
  • 0f325d3blayouts mission 002 2/3: code rules — styles.hl -> components/styles.hl, the one never-reassigned let dropped; gate 73/0, same outputmre
  • a3e74c8alayouts mission 002 1/3: components re-copied byte-verbatim from components.hybriel 3f93d71 by tools/sync-components.sh (+ --check, components/SOURCE); gate 73/0, check-theme 0mre
  • 80ce6ba9report 001 (mission 075)mre
  • 5c6e338flayouts.worldapi.org in Hybriel: WorldAPI theme (tokens, borderless elements, themed components.hybriel components), shells (header, main/user menu, sidebar overlay, content-first, list-first, three-pane), showcase, check-theme helper; gate 73/0 (mission 075)mre