gitoria

components

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit1f8d79d61f8d79d6comments (mission 009 WIP, tickets#27): attachments — attach="true" puts the form in FilesUpload pick mode, onPost(text, files), files per comment (thumbnails open full size, file rows, no url = no link); MdEditor files="off"; demo with attachments; gate m009 checks (WIP: 356/1)mre1f8d79d6/components/md-editor/md-editor.hl

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

Branches

Latest commits

  • 1f8d79d6comments (mission 009 WIP, tickets#27): attachments — attach="true" puts the form in FilesUpload pick mode, onPost(text, files), files per comment (thumbnails open full size, file rows, no url = no link); MdEditor files="off"; demo with attachments; gate m009 checks (WIP: 356/1)mre
  • 13389d67mission 008: report, LOG, STATUSmre
  • ab47e4a2files-upload (mission 008, #18 for hycon#46): pick-first-send-later mode — host-owned list (files + onChange), slot for the host's input area, Ctrl+V paste (both modes), thumbnails, name+size rows, ✕ remove, maxSize per file, Camera on touch screens, 44 px targets; demo /files-upload/pick; gate 343/0 (19 new, 18 fail on the old code)mre
  • 172e66bemission brief 008mre
  • 9db927dfpaths: projects moved into /media/STORAGE/projects/WorldAPI/mre
  • 00a95329components (mission 007): re-vendor Hybriel to the shared static build 0f396652 (plugins; bin/ git-ignored), gate 324/0 old and new, real-data copy unchanged, report 007, same-output.mjs ports overridablemre
  • fe50766bmission brief 007mre
  • 2dce51b8components (mission 006) 4/4: docs (README comments + gate 324, STATUS, LOG), report reports/006-comments.mdmre
  • 9ec7273ecomponents layouts#2 (mission 006) 3/4: comments — each text is MdEditor readonly directly in its row (hl:web builds a composed child anew when a bound value changes, so the keyed one-row list was not needed); demo 'bob edits his comment elsewhere (a push)' + gate check that a text the host changes from outside is drawn anew; theme radii (var(--radius-small/large) with 5px/10px fallbacks: layouts' check-theme 0 problems with comments.hl copied in); README 'How it is built'; gate 324/0 (34 comments checks)mre
  • fd57c18bcomponents layouts#2 (mission 006) 2/3: comments block (components/comments, demo /comments) — pure Hybriel: '1 comment' / 'n comments', avatar initial, bubble with name, time, 'edited' (<details> with the earlier versions), the text drawn by MdEditor readonly (one-row list keyed by id + text, so an edit redraws), like ♥ n (aria-pressed), Edit / Delete (asks first) only where author == user, the form below in MdEditor (Comment button or Ctrl+Enter; a fresh editor after a post). Host passes comments + user and hands onPost / onEdit / onDelete / onLike (hybriel#87); demo keeps a mock thread from lib/comments.hl in the page, switches alice / bob / nobody. Home entry, routes, map line, README; base-look gate covers comments; 33 gate checks with real clicks / keysmre
  • 850a376bcomponents (mission 006) 1/3: MdEditor readonly = "true" — the Markdown shown formatted and nothing else (no toolbar, link form, file rows, placeholder, source view or switch; article contenteditable false, tabindex -1, role document; no field background or focus ring); the mount only loads the value. For the comments block, which draws every comment with the editor's own renderermre
  • ee9f1b57mission brief w6mre
  • fe691586components (mission 005) 4/4: docs (README components + gate 290, STATUS, LOG), report reports/005-fixes-16-17-5.mdmre
  • f1ebab53components #5 (mission 005) 3/4: file upload for several files (components/files-upload, demo /files-upload) — pure Hybriel, each file through emit server uploadFile (hybriel#94), drop or choose many, a row per file with live progress, one after the other in order, a drop during an upload waits, a file over uploadMax fails in its row and the next goes, 'n of m uploaded'; home entry, routes, map line, README; pagination keyboard focus ring #555 (Chrome painted its own orange one); docker-compose init: true (hybriel#156); gate 290/0 (17 #5 checks with real file drops, 1 #16 focus check)mre
  • 3b73ae5bcomponents #16 (mission 005) 2/4: Pagination tells the host the target page — the host hands onPage (hybriel#87: a function, not emit), called on every click that changes the page (pointer, Enter/Space, script click; Previous/Next/numbers/first/last; not … or the current page) with the target read from the clicked button's data-page before the rebuild; demo shows what the page was told; README Data out; 15 gate checks (14 fail on the old pagination)mre
  • 6b27c0f0components #17 (mission 005) 1/4: md-editor keeps backslash + r — parseInto dropped the two characters '\r' (C:\root -> C:oot) instead of a real carriage return; CR now decoded from JSON (String.fromCharCode does not parse in a member), real CRs also go from pasted plain text; 5 gate checks (3 fail on the old md-editor.hl)mre
  • 1a5dc327mission brief w5mre
  • a567b579components (mission 004) 3/3: docs (README Hybriel a832f73b + tables, STATUS, LOG), report reports/004-md-editor-tables.mdmre
  • 70fe7ab5components (mission 004) 2/3: GitHub pipe tables in the Hybriel MdEditor (creator notes#5; behaviour of notes md-editor.js 9acc27f, no JavaScript) — parse/render (header, :--/:-:/--: alignment, \| in cells and code, inline Markdown in cells, outer pipes optional), padded writer, unchanged table byte for byte, typing | a | b | Enter |---|---| Enter makes a table, Tab/Shift+Tab, Enter new row, Enter in empty last row leaves, Backspace/Delete never merge, selection across a table empties cells, pasted HTML table -> table, thin #999 lines, wide table scrolls in its box; demo third editor 'plan'; gate 252/0 (22 new table checks, 20 fail on the old md-editor.hl)mre
  • f2adb3f3components (mission 004) 1/3: Hybriel master a832f73b (incremental build cache, HL_CACHE_DIR, #151) — bin/hybriel sha256 e1b53f7ce687f5afbe3db34bcda69958f56e730571e4841923c9c8eb3d272db9 built from git archive a832f73b (HL_NO_PLUGINS=1 native/build.sh), the same nine plugins; container: HL_CACHE_DIR=/cache on volume hybriel-cache, /tmp tmpfs; tests wait COMPONENTS_COLD_MS (120 s) for every start; deploy.sh DEPLOY_URL_WAIT 120 s; gate 230/0 coldmre