gitoria

components

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commitab47e4a2ab47e4a2files-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)mreab47e4a2/components/md-editor/md-editor.hl

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

Branches

Latest commits

  • 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
  • 91bd8a0dmission brief (w4)mre
  • 3bc905c5components #15 (mission 003) 2/2: docs (README Look, STATUS, LOG), reportmre