gitoria

components

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commitc2d0de59c2d0de59MdEditor: show a value that changes from outside (data-value observer), demo button and gatemrec2d0de59/components/md-editor/md-editor.hl

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

Branches

Latest commits

  • c2d0de59MdEditor: show a value that changes from outside (data-value observer), demo button and gatemre
  • c4272fa3re-vendor Hybriel 5406d146 (hl:web batches 9+10: #72 emits while the socket is closed delivered after reconnect, browser boot linear, faster list appends; contains int 6–14 + m406)mre
  • 2e22618etests: cdp-blank/md-bg/md-keys-run Chrome range and base port from env (MDK_CHROME, MDK_PORT), defaults unchangedmre
  • a5d2384bre-vendor Hybriel 6f8a0689 (int 6–11: streaming cursors, #203 index heal + close() fix, fd403 listDir/cursor fds, hl:time browser side, hl:web batches 5+6)mre
  • 52902d23docker-compose: nofile 65536 (Hybriel int 6+ boot opened >1024 files in the tracker)mre
  • 022b943fdeploy: backup copies index files first and *.mpack data last (hot-copy skew, hybriel #203)mre
  • d17f8543mission 012: re-vendor Hybriel master f9614007 (plugins), fixes comments push redraw; gate 480/0mre
  • 5f95de05mission 012: re-vendor Hybriel ce6f2e0a (plugins), report: gate 478/2 on comments push redrawmre
  • 3794c591mission 011: report, LOG, STATUS, md-keys-run widths, cdp-blank helpermre
  • 77a93c16mission 011: gate hook for md-keys (480/0), flatten() runs one at a time (removeChild race), surface also built on first focus / pointer-down (background tab), md-bg test, README keysmre
  • 3c906718mission 011: md-editor key tests (real keys) and fixes: nested p/ul flatten, bare br, link change, Ctrl+E, code block exit (WIP)mre
  • 1442e583mission 010: report, LOG, STATUSmre
  • 6f27ad31md-editor: phone toolbar row contained (inline-size) so it never widens a grid parentmre
  • d702d76dmd-editor look: root class md-empty (a host .empty rule hit it), rows = surface height, one phone toolbar row with 44 px targets; comment form rows 3; gate 360/0mre
  • 15be2ac0comments: attach (FilesUpload pick), onPost(text, files), files per comment; md-editor files=off; README, gate fixmre
  • 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