gitoria

notes

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit3e7e79f53e7e79f5reports/H1-hydrate.mdmre3e7e79f5/components/md-editor/md-editor.hl

76.7 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. f.dispatchEvent(new Event('input', { bubbles = true }))
  714. }
  715. }
  716. // a new value (from outside, the source view or a paste-all): shown formatted
  717. load(root, md) {
  718. s = surfaceOf(root)
  719. s.textContent = ''
  720. parseInto(s, md)
  721. root.mdOrig = md
  722. root.mdCanon = toMarkdown(s)
  723. root.classList.toggle('md-empty', root.mdCanon == '')
  724. }
  725. // the toolbar shows what the caret is in
  726. updateBar(root) {
  727. if (!root.isConnected || !inSurface(root)) { return null }
  728. mark = (tool, active) => { b = root.querySelector('button.' + tool) if (b != null) { b.classList.toggle('on', active) } }
  729. mark('bold', document.queryCommandState('bold'))
  730. mark('italic', document.queryCommandState('italic'))
  731. mark('code', inTag(root, ['code']))
  732. mark('ul', inTag(root, ['ul']))
  733. mark('ol', inTag(root, ['ol']))
  734. mark('pre', inTag(root, ['pre']))
  735. mark('link', inTag(root, ['a']))
  736. h = root.querySelector('button.heading')
  737. let level = ''
  738. tags = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6']
  739. for (t of tags) { if (inTag(root, [t])) { level = t.toUpperCase() } }
  740. if (h != null) { h.textContent = level != '' ? level : 'H' h.classList.toggle('on', level != '') }
  741. }
  742. // bold / italic / heading / lists / code block: the browser's own editing commands, so undo works
  743. codeToggle(root) {
  744. sel = document.getSelection()
  745. r = sel.getRangeAt(0)
  746. let n = sel.anchorNode
  747. let inCode = null
  748. while (n != null && n != surfaceOf(root)) { if (n.nodeType == 1 && n.nodeName.toLowerCase() == 'code') { inCode = n } n = n.parentNode }
  749. if (inCode != null && r.collapsed) {
  750. // the caret in code and no selection: leave the code (the next typed text is plain), like Ctrl+B / Ctrl+I end bold / italic
  751. let nx = inCode.nextSibling
  752. if (nx == null || nx.nodeType != 3) {
  753. nx = document.createTextNode(ZW)
  754. inCode.parentNode.insertBefore(nx, inCode.nextSibling)
  755. } else if (!nx.data.startsWith(ZW)) { nx.insertData(0, ZW) }
  756. sel.collapse(nx, 1)
  757. return null
  758. }
  759. if (inCode != null) {
  760. let rr = document.createRange()
  761. rr.selectNode(inCode)
  762. sel.removeAllRanges()
  763. sel.addRange(rr)
  764. document.execCommand('insertHTML', false, escHtml(clean(inCode.textContent), ''))
  765. return null
  766. }
  767. // no selection (mission 011): an empty code span the caret sits in, like Ctrl+B / Ctrl+I leave the next typed text bold / italic
  768. if (r.collapsed) {
  769. document.execCommand('insertHTML', false, '<code>' + ZW + '</code>' + ZW)
  770. t = document.getSelection().anchorNode
  771. if (t != null && t.previousSibling != null && t.previousSibling.nodeName == 'CODE') { document.getSelection().collapse(t.previousSibling.firstChild, 1) }
  772. return null
  773. }
  774. document.execCommand('insertHTML', false, escHtml(r.toString(), 'code') + ZW)
  775. }
  776. // text as escaped html (built by the browser from a text node), optionally inside a tag
  777. escHtml(text, tag) {
  778. box = document.createElement('div')
  779. e = tag != '' ? el(tag, text) : document.createTextNode(text)
  780. box.appendChild(e)
  781. return box.innerHTML
  782. }
  783. headingCycle(root) {
  784. let cur = 0
  785. tags = ['h1', 'h2', 'h3']
  786. let i = 0
  787. while (i < 3) { if (inTag(root, [tags[i]])) { cur = i + 1 } i = i + 1 }
  788. document.execCommand('formatBlock', false, cur == 3 ? 'p' : tags[cur])
  789. }
  790. blockToggle(root, tag, cmd) {
  791. if (inTag(root, [tag])) {
  792. if (tag == 'pre') { document.execCommand('formatBlock', false, 'p') } else { document.execCommand(cmd) }
  793. } else if (tag == 'pre') { document.execCommand('formatBlock', false, 'pre') } else { document.execCommand(cmd) }
  794. }
  795. linkOpen(root) {
  796. sel = document.getSelection()
  797. if (!inSurface(root)) { surfaceOf(root).focus() }
  798. root.mdRange = sel.rangeCount > 0 ? sel.getRangeAt(0).cloneRange() : null
  799. f = root.querySelector('link-form input')
  800. let n = sel.anchorNode
  801. let href = ''
  802. while (n != null && n != surfaceOf(root)) { if (n.nodeType == 1 && n.nodeName.toLowerCase() == 'a') { href = n.getAttribute('href') } n = n.parentNode }
  803. f.value = href
  804. root.classList.add('linking')
  805. f.focus()
  806. }
  807. linkClose(root) {
  808. root.classList.remove('linking')
  809. surfaceOf(root).focus()
  810. sel = document.getSelection()
  811. if (root.mdRange != null) { sel.removeAllRanges() sel.addRange(root.mdRange) }
  812. }
  813. linkApply(root, remove) {
  814. f = root.querySelector('link-form input')
  815. href = remove ? '' : safeHref(f.value)
  816. linkClose(root)
  817. if (remove || f.value.trim() == '') { document.execCommand('unlink') }
  818. else if (href != '') {
  819. sel = document.getSelection()
  820. // the caret inside a link and no selection: the address of THAT link changes (mission 011; before, a second link was inserted into it)
  821. let an = sel.anchorNode
  822. let inA = null
  823. while (an != null && an != surfaceOf(root)) { if (an.nodeType == 1 && an.nodeName.toLowerCase() == 'a') { inA = an } an = an.parentNode }
  824. if (sel.isCollapsed && inA != null) { sel.selectAllChildren(inA) }
  825. if (sel.isCollapsed) { document.execCommand('insertHTML', false, escLink(href)) } else { document.execCommand('createLink', false, href) }
  826. }
  827. sync(root)
  828. }
  829. escLink(href) {
  830. box = document.createElement('div')
  831. a = el('a', href)
  832. a.setAttribute('href', href)
  833. box.appendChild(a)
  834. return box.innerHTML
  835. }
  836. // the parsed Markdown as html the browser can insert (built from elements, so every text is escaped)
  837. mdHtml(md) {
  838. box = document.createElement('div')
  839. parseInto(box, md)
  840. // a single paragraph is inserted inline: no extra block
  841. if (box.childNodes.length == 1 && box.firstChild.nodeName.toLowerCase() == 'p') { return box.firstChild.innerHTML }
  842. return box.innerHTML
  843. }
  844. // typing rules at the caret: "# " "- " "1. " make a block; the typed marker is consumed (only the formatting stays). They work in a
  845. // 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)
  846. blockRule(root, e) {
  847. sel = document.getSelection()
  848. if (!sel.isCollapsed || !inSurface(root)) { return false }
  849. let b = blockOf(root, sel.anchorNode)
  850. if (b == null) { return false }
  851. let tag = b.nodeName.toLowerCase()
  852. let inner = sel.anchorNode
  853. 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 }
  854. if (inner != null && inner != surfaceOf(root) && inner.nodeName.toLowerCase() != 'li') { b = inner tag = inner.nodeName.toLowerCase() }
  855. let item = sel.anchorNode
  856. while (item != null && item != surfaceOf(root) && item.nodeName.toLowerCase() != 'li') { item = item.parentNode }
  857. if (item == surfaceOf(root)) { item = null }
  858. let box = b
  859. if (item != null) {
  860. box = item
  861. tag = item.parentNode.nodeName.toLowerCase()
  862. } else if (tag != 'p' && tag != 'div' && !(tag.length == 2 && tag.startsWith('h'))) { return false }
  863. r = sel.getRangeAt(0)
  864. pre = document.createRange()
  865. pre.selectNodeContents(box)
  866. pre.setEnd(r.endContainer, r.endOffset)
  867. before = clean(pre.toString())
  868. if (before != clean(box.textContent)) { return false }
  869. let cmd = ''
  870. let arg = ''
  871. if (item == null && before.length >= 1 && before.length <= 6 && before.replaceAll('#', '') == '') { cmd = 'formatBlock' arg = 'h' + before.length }
  872. if (before == '-' || before == '*' || before == '+') { cmd = 'insertUnorderedList' }
  873. if (before.length >= 2 && before.endsWith('.') && before.slice(0, before.length - 1).length < 9) {
  874. let digits = true
  875. let k = 0
  876. while (k < before.length - 1) { if (!isDigit(before.slice(k, k + 1))) { digits = false } k = k + 1 }
  877. if (digits) { cmd = 'insertOrderedList' }
  878. }
  879. if (cmd == '') { return false }
  880. e.preventDefault()
  881. sel.selectAllChildren(box)
  882. document.execCommand('delete')
  883. // a list marker typed in a list of that kind is only consumed
  884. if (item != null && ((cmd == 'insertUnorderedList' && tag == 'ul') || (cmd == 'insertOrderedList' && tag == 'ol'))) { return true }
  885. if (item == null && tag != 'p' && tag != 'div' && cmd != 'formatBlock') { document.execCommand('formatBlock', false, 'p') }
  886. if (arg != '') { document.execCommand(cmd, false, arg) } else { document.execCommand(cmd) }
  887. return true
  888. }
  889. // a closing * _ ` typed: find the opener before the caret in the same text node
  890. inlineRule(root, e) {
  891. sel = document.getSelection()
  892. node = sel.anchorNode
  893. if (!sel.isCollapsed || node == null || node.nodeType != 3 || !surfaceOf(root).contains(node)) { return null }
  894. if (inTag(root, ['code', 'pre'])) { return null }
  895. off = sel.anchorOffset
  896. t = node.data.slice(0, off)
  897. c = e.data
  898. let tag = ''
  899. let start = -1
  900. let ends = ''
  901. if (c == '`') {
  902. let j = t.slice(0, off - 1).lastIndexOf('`')
  903. if (j >= 0 && off - 1 - j - 1 >= 1) { start = j tag = 'code' ends = t.slice(j + 1, off - 1) }
  904. }
  905. if (c == '*' && t.length >= 5 && t.endsWith('**')) {
  906. let j = t.slice(0, off - 2).lastIndexOf('**')
  907. let inner = j >= 0 ? t.slice(j + 2, off - 2) : ''
  908. if (j >= 0 && inner != '' && !isSpace(inner.slice(0, 1)) && !isSpace(inner.slice(inner.length - 1))) { start = j tag = 'strong' ends = inner }
  909. }
  910. if ((c == '*' || c == '_') && tag == '' && t.length >= 3 && !t.endsWith(c + c)) {
  911. let j = t.slice(0, off - 1).lastIndexOf(c)
  912. let inner = j >= 0 ? t.slice(j + 1, off - 1) : ''
  913. 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
  914. if (okStart && inner != '' && !isSpace(inner.slice(0, 1)) && !isSpace(inner.slice(inner.length - 1))) { start = j tag = 'em' ends = inner }
  915. }
  916. if (tag == '') { return null }
  917. r = document.createRange()
  918. r.setStart(node, start)
  919. r.setEnd(node, off)
  920. sel.removeAllRanges()
  921. sel.addRange(r)
  922. document.execCommand('insertHTML', false, escHtml(ends, tag) + ZW)
  923. // Chrome pins the colour on the new element (`<strong style="color: …">`) when it equals the text around it (the black/white base
  924. // look, #15); the surface never carries styles of its own
  925. for (k of surfaceOf(root).querySelectorAll('[style]')) { k.removeAttribute('style') }
  926. }
  927. // ---- tables in the editor: typing one, moving between cells, trs; a table never merges with the text around it ----------
  928. cellOf(root, node) {
  929. s = surfaceOf(root)
  930. let n = node
  931. while (n != null && n != s) {
  932. if (n.nodeName == 'TD' || n.nodeName == 'TH') { return n }
  933. n = n.parentNode
  934. }
  935. return null
  936. }
  937. inCell(root) {
  938. sel = document.getSelection()
  939. return sel.rangeCount > 0 && sel.anchorNode != null && cellOf(root, sel.anchorNode) != null
  940. }
  941. isBlank(node) { return clean(node.textContent).trim() == '' && (node.nodeType != 1 || node.querySelector('img') == null) }
  942. // the caret at the end of a cell (an empty cell: at its start, before its <br>)
  943. caretIn(cell, atEnd) {
  944. sel = document.getSelection()
  945. r = document.createRange()
  946. r.selectNodeContents(cell)
  947. r.collapse(!atEnd || isBlank(cell))
  948. sel.removeAllRanges()
  949. sel.addRange(r)
  950. }
  951. // a new empty row (the header's alignments) after `tr`; a header row gets its body first
  952. newRow(table, tr) {
  953. row = el('tr', null)
  954. for (h of cellsOf(table.querySelector('tr'))) { row.appendChild(cellEl('td', h.getAttribute('data-align') != null ? h.getAttribute('data-align') : '', '')) }
  955. let body = table.querySelector('tbody')
  956. if (body == null) { body = el('tbody', null) table.appendChild(body) }
  957. if (tr.parentNode.nodeName == 'THEAD') { body.insertBefore(row, body.firstChild) } else { body.insertBefore(row, tr.nextSibling) }
  958. return row
  959. }
  960. // an empty paragraph after a block (the one already there when it is empty), for the caret
  961. paraAfter(root, b) {
  962. n = b.nextSibling
  963. if (n != null && n.nodeName == 'P' && isBlank(n)) { return n }
  964. p = el('p', null)
  965. p.appendChild(el('br', null))
  966. surfaceOf(root).insertBefore(p, n)
  967. return p
  968. }
  969. // 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
  970. rowEnter(root, cell) {
  971. tr = cell.parentNode
  972. table = tr.closest('table')
  973. trs = table.querySelectorAll('tr')
  974. empty = isBlank(tr)
  975. if (tr.parentNode.nodeName == 'TBODY' && trs[trs.length - 1] == tr && empty) {
  976. body = tr.parentNode
  977. body.removeChild(tr)
  978. if (body.childNodes.length == 0) { table.removeChild(body) }
  979. p = paraAfter(root, table)
  980. document.getSelection().collapse(p, 0)
  981. } else { caretIn(newRow(table, tr).firstChild, false) }
  982. sync(root)
  983. }
  984. // Tab / Shift+Tab: the next / previous cell (the caret at its end); Tab in the last cell adds a row
  985. cellTab(root, cell, back) {
  986. table = cell.closest('table')
  987. cells = table.querySelectorAll('th, td')
  988. let i = 0
  989. while (i < cells.length && cells[i] != cell) { i = i + 1 }
  990. if (back) { if (i > 0) { caretIn(cells[i - 1], true) } return null }
  991. if (i + 1 < cells.length) { caretIn(cells[i + 1], true) return null }
  992. caretIn(newRow(table, cell.parentNode).firstChild, false)
  993. sync(root)
  994. }
  995. // the lines of a paragraph are its children between <br>s: [from, to) child indexes of its last line and the one before
  996. // (a trailing <br> the browser keeps at the end is not a line). Answer: [lastFrom, lastTo, prevFrom] (prevFrom -1 = no line before).
  997. lastLines(p) {
  998. kids = p.childNodes
  999. let end = kids.length
  1000. while (end > 0 && kids[end - 1].nodeName == 'BR') { end = end - 1 }
  1001. let br = end - 1
  1002. while (br >= 0 && kids[br].nodeName != 'BR') { br = br - 1 }
  1003. let prev = -1
  1004. if (br >= 0) {
  1005. prev = br - 1
  1006. while (prev >= 0 && kids[prev].nodeName != 'BR') { prev = prev - 1 }
  1007. prev = prev + 1
  1008. }
  1009. return [br + 1, end, prev]
  1010. }
  1011. lineText(p, start, to) {
  1012. let t = ''
  1013. let i = start
  1014. while (i < to) { t = t + p.childNodes[i].textContent i = i + 1 }
  1015. return clean(t)
  1016. }
  1017. linePlain(p, start, to) {
  1018. let i = start
  1019. while (i < to) { if (p.childNodes[i].nodeType != 3) { return false } i = i + 1 }
  1020. return true
  1021. }
  1022. // the header cells of a typed line: its nodes split at every `|` in the text (`\|` typed is a pipe in the cell); formatted parts
  1023. // (bold, code, a link) go into their cell whole; outer pipes are optional
  1024. headCells(p, start, to, aligns) {
  1025. text = trimSp(lineText(p, start, to))
  1026. cells = [el('th', null)]
  1027. let i = start
  1028. while (i < to) {
  1029. let n = p.childNodes[i]
  1030. if (n.nodeType == 3) {
  1031. let s = clean(n.data)
  1032. let buf = ''
  1033. let k = 0
  1034. while (k < s.length) {
  1035. let c = s.slice(k, k + 1)
  1036. if (c == BS && s.slice(k + 1, k + 2) == '|') { buf = buf + '|' k = k + 2 }
  1037. else if (c == '|') {
  1038. if (buf != '') { cells[cells.length - 1].appendChild(document.createTextNode(buf)) }
  1039. buf = ''
  1040. let th = el('th', null)
  1041. cells.push(th)
  1042. k = k + 1
  1043. } else { buf = buf + c k = k + 1 }
  1044. }
  1045. if (buf != '') { cells[cells.length - 1].appendChild(document.createTextNode(buf)) }
  1046. } else { cells[cells.length - 1].appendChild(n.cloneNode(true)) }
  1047. i = i + 1
  1048. }
  1049. if (text.startsWith('|')) { cells.shift() }
  1050. if (text.endsWith('|') && !escapedAt(text, text.length - 1, 0) && cells.length > 0) { cells.pop() }
  1051. if (cells.length != aligns.length) { return null }
  1052. let k2 = 0
  1053. while (k2 < cells.length) {
  1054. let cell = cells[k2]
  1055. trimCell(cell)
  1056. if (aligns[k2] != '') { cell.setAttribute('data-align', aligns[k2]) }
  1057. k2 = k2 + 1
  1058. }
  1059. return cells
  1060. }
  1061. // leading / trailing spaces of a cell's first / last text go; an empty cell gets its <br>
  1062. trimCell(cell) {
  1063. while (cell.firstChild != null && cell.firstChild.nodeType == 3 && trimSp(cell.firstChild.data) == '') { cell.removeChild(cell.firstChild) }
  1064. while (cell.lastChild != null && cell.lastChild.nodeType == 3 && trimSp(cell.lastChild.data) == '') { cell.removeChild(cell.lastChild) }
  1065. if (cell.firstChild != null && cell.firstChild.nodeType == 3) {
  1066. let d = cell.firstChild.data
  1067. while (d.length > 0 && isSpace(d.slice(0, 1))) { d = d.slice(1) }
  1068. cell.firstChild.data = d
  1069. }
  1070. if (cell.lastChild != null && cell.lastChild.nodeType == 3) {
  1071. let d2 = cell.lastChild.data
  1072. while (d2.length > 0 && isSpace(d2.slice(d2.length - 1))) { d2 = d2.slice(0, d2.length - 1) }
  1073. cell.lastChild.data = d2
  1074. }
  1075. if (cell.childNodes.length == 0) { cell.appendChild(el('br', null)) }
  1076. }
  1077. // the children [start, end of the paragraph) go (the line before them loses its <br> too)
  1078. cutLines(p, start) {
  1079. let at = start
  1080. if (at > 0 && p.childNodes[at - 1].nodeName == 'BR') { at = at - 1 }
  1081. while (p.childNodes.length > at) { p.removeChild(p.lastChild) }
  1082. }
  1083. // Enter at the end of a typed delimiter row (`|---|:-:|`) under a header row (the line before, in this paragraph or the paragraph
  1084. // before): the two lines become a table with an empty body row, the caret in its first cell
  1085. tableByEnter(root, b) {
  1086. sel = document.getSelection()
  1087. r = sel.getRangeAt(0)
  1088. rest = document.createRange()
  1089. rest.selectNodeContents(b)
  1090. rest.setStart(r.endContainer, r.endOffset)
  1091. if (clean(rest.toString()).trim() != '') { return false }
  1092. ll = lastLines(b)
  1093. if (!linePlain(b, ll[0], ll[1])) { return false }
  1094. aligns = alignsOf(lineText(b, ll[0], ll[1]))
  1095. if (aligns == null) { return false }
  1096. let hp = b
  1097. let hFrom = ll[2]
  1098. let hTo = ll[0] - 1
  1099. if (hFrom < 0) {
  1100. hp = b.previousSibling
  1101. if (hp == null || hp.nodeName != 'P') { return false }
  1102. hl = lastLines(hp)
  1103. hFrom = hl[0]
  1104. hTo = hl[1]
  1105. }
  1106. if (hTo <= hFrom || trimSp(lineText(hp, hFrom, hTo)) == '') { return false }
  1107. cells = headCells(hp, hFrom, hTo, aligns)
  1108. if (cells == null) { return false }
  1109. table = el('table', null)
  1110. head = el('thead', null)
  1111. tr = el('tr', null)
  1112. for (c of cells) { tr.appendChild(c) }
  1113. head.appendChild(tr)
  1114. table.appendChild(head)
  1115. // the lines go: the delimiter (and, in the same paragraph, the header); an emptied paragraph goes too
  1116. cutLines(b, hp == b ? hFrom : ll[0])
  1117. if (hp != b) { b.parentNode.removeChild(b) cutLines(hp, hFrom) }
  1118. if (isBlank(hp)) { hp.parentNode.replaceChild(table, hp) } else { hp.parentNode.insertBefore(table, hp.nextSibling) }
  1119. row = newRow(table, tr)
  1120. if (table.nextSibling == null) { paraAfter(root, table) }
  1121. caretIn(row.firstChild, false)
  1122. sync(root)
  1123. return true
  1124. }
  1125. // 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
  1126. // whole goes; the text before and after it is cut on its own (it never joins the table). false = no table in the selection.
  1127. cutAcross(root) {
  1128. sel = document.getSelection()
  1129. if (sel.rangeCount == 0 || sel.isCollapsed) { return false }
  1130. r = sel.getRangeAt(0)
  1131. c1 = cellOf(root, r.startContainer)
  1132. c2 = cellOf(root, r.endContainer)
  1133. if (c1 != null && c1 == c2) { return false }
  1134. tables = []
  1135. for (tq of surfaceOf(root).querySelectorAll('table')) { if (r.intersectsNode(tq)) { tables.push(tq) } }
  1136. if (tables.length == 0) { return false }
  1137. // the boundaries of the text outside the tables, taken before anything changes
  1138. cuts = []
  1139. first = tables[0]
  1140. last = tables[tables.length - 1]
  1141. if (cellOf(root, r.startContainer) == null) { a = document.createRange() a.setStart(r.startContainer, r.startOffset) a.setEndBefore(first) cuts.push(a) }
  1142. let i = 0
  1143. while (i + 1 < tables.length) { let m = document.createRange() m.setStartAfter(tables[i]) m.setEndBefore(tables[i + 1]) cuts.push(m) i = i + 1 }
  1144. if (cellOf(root, r.endContainer) == null) { z = document.createRange() z.setStartAfter(last) z.setEnd(r.endContainer, r.endOffset) cuts.push(z) }
  1145. gone = []
  1146. for (tb of tables) {
  1147. let cells = tb.querySelectorAll('th, td')
  1148. let head = document.createRange()
  1149. head.setStart(cells[0], 0)
  1150. let tail = document.createRange()
  1151. tail.selectNodeContents(cells[cells.length - 1])
  1152. tail.collapse(false)
  1153. // compareBoundaryPoints: 0 = START_TO_START, 2 = END_TO_END
  1154. if (r.compareBoundaryPoints(0, head) <= 0 && r.compareBoundaryPoints(2, tail) >= 0) { gone.push(tb) }
  1155. else {
  1156. for (c of cells) {
  1157. if (r.intersectsNode(c)) {
  1158. let part = document.createRange()
  1159. part.selectNodeContents(c)
  1160. if (c.contains(r.startContainer)) { part.setStart(r.startContainer, r.startOffset) }
  1161. if (c.contains(r.endContainer)) { part.setEnd(r.endContainer, r.endOffset) }
  1162. part.deleteContents()
  1163. if (c.childNodes.length == 0 || isBlank(c)) { c.textContent = '' c.appendChild(el('br', null)) }
  1164. }
  1165. }
  1166. }
  1167. }
  1168. for (cut of cuts) { cut.deleteContents() }
  1169. // the caret: where the selection began (in a removed table: the block that takes its place)
  1170. let at = null
  1171. for (tg of gone) {
  1172. if (tg.contains(r.startContainer)) { at = paraAfter(root, tg) }
  1173. tg.parentNode.removeChild(tg)
  1174. }
  1175. s = surfaceOf(root)
  1176. if (s.childNodes.length == 0) { np = el('p', null) np.appendChild(el('br', null)) s.appendChild(np) at = np }
  1177. if (at != null) { sel.collapse(at, 0) } else { sel.collapse(r.startContainer, r.startOffset) }
  1178. return true
  1179. }
  1180. // 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
  1181. // after a table / the end of the block before one: never merged (an empty paragraph goes)
  1182. tableDelete(root, back) {
  1183. sel = document.getSelection()
  1184. if (!sel.isCollapsed || !inSurface(root)) { return false }
  1185. r = sel.getRangeAt(0)
  1186. cell = cellOf(root, sel.anchorNode)
  1187. let box = cell
  1188. if (box == null) { box = blockOf(root, sel.anchorNode) }
  1189. if (box == null) { return false }
  1190. edge = document.createRange()
  1191. edge.selectNodeContents(box)
  1192. if (back) { edge.setEnd(r.startContainer, r.startOffset) } else { edge.setStart(r.endContainer, r.endOffset) }
  1193. if (clean(edge.toString()) != '' || edge.cloneContents().querySelector('img') != null) { return false }
  1194. if (cell != null) {
  1195. if (back) {
  1196. all = cell.closest('table').querySelectorAll('th, td')
  1197. let i = 0
  1198. while (i < all.length && all[i] != cell) { i = i + 1 }
  1199. if (i > 0) { caretIn(all[i - 1], true) }
  1200. }
  1201. return true
  1202. }
  1203. next = back ? box.previousSibling : box.nextSibling
  1204. if (next == null || next.nodeName != 'TABLE') { return false }
  1205. if (isBlank(box)) { box.parentNode.removeChild(box) sync(root) }
  1206. if (back) { tail = next.querySelectorAll('th, td') caretIn(tail[tail.length - 1], true) }
  1207. else if (box.parentNode == null) { caretIn(next.querySelector('th, td'), false) }
  1208. return true
  1209. }
  1210. // the editing rules of tables, before the browser edits: true = handled (the browser's edit is cancelled)
  1211. tableBefore(root, e) {
  1212. t = e.inputType
  1213. if (t.startsWith('delete') || t.startsWith('insert')) {
  1214. if (cutAcross(root)) {
  1215. if (t == 'insertText' && e.data != null) { document.execCommand('insertText', false, e.data) }
  1216. sync(root)
  1217. return true
  1218. }
  1219. }
  1220. sel = document.getSelection()
  1221. if (sel.rangeCount == 0 || sel.anchorNode == null || !inSurface(root)) { return false }
  1222. cell = cellOf(root, sel.anchorNode)
  1223. if (t == 'insertParagraph') {
  1224. if (cell != null) { rowEnter(root, cell) return true }
  1225. b = blockOf(root, sel.anchorNode)
  1226. if (b != null && b.nodeName == 'P' && sel.isCollapsed) { return tableByEnter(root, b) }
  1227. return false
  1228. }
  1229. // a cell is one line
  1230. if (t == 'insertLineBreak' && cell != null) { return true }
  1231. if (t.startsWith('delete') && (t.endsWith('Backward') || t.endsWith('Forward'))) { return tableDelete(root, t.endsWith('Backward')) }
  1232. return false
  1233. }
  1234. // ---- pasting: Markdown text (a table in it becomes a table), an HTML table (its cells' text), anything into a cell on one line
  1235. // the inline html of one line of Markdown (null when it is not a plain paragraph)
  1236. inlineHtml(md) {
  1237. box = document.createElement('div')
  1238. parseInto(box, md)
  1239. if (box.childNodes.length == 1 && box.firstChild.nodeName == 'P') { return box.firstChild.innerHTML }
  1240. return null
  1241. }
  1242. // 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
  1243. // block the caret is in is split there, the new blocks go between its halves (after a list, a code block or a table)
  1244. insertBlocks(root, box) {
  1245. s = surfaceOf(root)
  1246. sel = document.getSelection()
  1247. if (!inSurface(root)) { s.focus() sel.selectAllChildren(s) sel.collapseToEnd() }
  1248. if (!sel.isCollapsed) { document.execCommand('delete') }
  1249. r = sel.getRangeAt(0)
  1250. b = blockOf(root, sel.anchorNode)
  1251. let ref = null
  1252. if (b == null) { ref = s.childNodes.item(sel.anchorOffset) }
  1253. else if (['P', 'DIV', 'H1', 'H2', 'H3', 'H4', 'H5', 'H6'].indexOf(b.nodeName) >= 0) {
  1254. tail = document.createRange()
  1255. tail.selectNodeContents(b)
  1256. tail.setStart(r.startContainer, r.startOffset)
  1257. after = b.cloneNode(false)
  1258. after.appendChild(tail.extractContents())
  1259. ref = b.nextSibling
  1260. if (!isBlank(after)) { s.insertBefore(after, ref) ref = after }
  1261. if (isBlank(b)) { s.removeChild(b) }
  1262. } else { ref = b.nextSibling }
  1263. let last = null
  1264. while (box.firstChild != null) { last = box.firstChild s.insertBefore(last, ref) }
  1265. if (last == null) { return null }
  1266. if (last.nodeName == 'TABLE') {
  1267. if (last.nextSibling == null) { paraAfter(root, last) }
  1268. cells = last.querySelectorAll('th, td')
  1269. caretIn(cells[cells.length - 1], true)
  1270. } else { sel.selectAllChildren(last) sel.collapseToEnd() }
  1271. }
  1272. // the alignment a pasted cell asks for (data-align, align or text-align)
  1273. htmlAlign(c) {
  1274. let v = c.getAttribute('data-align')
  1275. if (v == null) { v = c.getAttribute('align') }
  1276. if (v == null) { v = c.style.textAlign }
  1277. v = v == null ? '' : v.toLowerCase()
  1278. return v == 'left' || v == 'center' || v == 'right' ? v : ''
  1279. }
  1280. // a pasted HTML table as an editor table: every row (thead / tbody / tfoot) with its cells' text, the first row the header,
  1281. // as many columns as the widest row
  1282. htmlTable(t) {
  1283. trs = t.rows
  1284. let cols = 0
  1285. for (row of trs) { if (row.cells.length > cols) { cols = row.cells.length } }
  1286. if (cols == 0) { return null }
  1287. out = el('table', null)
  1288. head = el('thead', null)
  1289. body = el('tbody', null)
  1290. let r = 0
  1291. while (r < trs.length) {
  1292. let tr = el('tr', null)
  1293. let k = 0
  1294. while (k < cols) {
  1295. let src = k < trs[r].cells.length ? trs[r].cells[k] : null
  1296. let first = k < trs[0].cells.length ? trs[0].cells[k] : null
  1297. let cell = el(r == 0 ? 'th' : 'td', null)
  1298. let al = first != null ? htmlAlign(first) : ''
  1299. if (al != '') { cell.setAttribute('data-align', al) }
  1300. let text = src != null ? trimSp(src.textContent.split(NL).join(' ')) : ''
  1301. if (text == '') { cell.appendChild(el('br', null)) } else { cell.appendChild(document.createTextNode(text)) }
  1302. tr.appendChild(cell)
  1303. k = k + 1
  1304. }
  1305. if (r == 0) { head.appendChild(tr) } else { body.appendChild(tr) }
  1306. r = r + 1
  1307. }
  1308. out.appendChild(head)
  1309. if (body.childNodes.length > 0) { out.appendChild(body) }
  1310. return out
  1311. }
  1312. // pasted HTML that holds a table: its tables as tables, every other text as plain text paragraphs (no other element is taken)
  1313. htmlBlocks(node, box) {
  1314. kids = node.childNodes
  1315. let i = 0
  1316. while (i < kids.length) {
  1317. let k = kids[i]
  1318. if (k.nodeType == 3) {
  1319. let p = box.lastChild
  1320. if (p == null || p.nodeName != 'P') { p = el('p', null) box.appendChild(p) }
  1321. p.appendChild(document.createTextNode(k.data.split(NL).join(' ')))
  1322. } else if (k.nodeType == 1 && k.nodeName == 'TABLE') {
  1323. let t = htmlTable(k)
  1324. if (t != null) { box.appendChild(t) }
  1325. } else if (k.nodeType == 1 && 'SCRIPT,STYLE,TEMPLATE,HEAD,TITLE,META,LINK,svg'.split(',').indexOf(k.nodeName) < 0) {
  1326. 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
  1327. if (block) { box.appendChild(el('p', null)) }
  1328. htmlBlocks(k, box)
  1329. if (block) { box.appendChild(el('p', null)) }
  1330. }
  1331. i = i + 1
  1332. }
  1333. }
  1334. // ---- 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)
  1335. Style {
  1336. '@keyframes md-editor-mount' { 'from' { opacity = '.999' } to { opacity = '1' } }
  1337. 'md-editor' { position = 'relative' display = 'block' border = '0' borderRadius = '.5rem' background = 'var(--color-background-sunken, #f2f2f2)' color = 'var(--color-text, #000)' }
  1338. 'md-editor:focus-within' { outline = '2px solid var(--color-accent, #555)' outlineOffset = '-1px' }
  1339. 'md-editor nav' { display = 'flex' flexWrap = 'wrap' gap = '.25rem' padding = '.35rem' borderBottom = '0' background = 'var(--color-surface, #ddd)' borderRadius = '.5rem .5rem 0 0' }
  1340. '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' }
  1341. 'md-editor nav button:hover' { background = 'var(--color-background, #fff)' }
  1342. 'md-editor nav button.on' { color = 'var(--color-accent-text, #fff)' background = 'var(--color-accent, #000)' }
  1343. 'md-editor nav button.italic' { fontStyle = 'italic' }
  1344. 'md-editor nav button.code' { fontFamily = 'ui-monospace, monospace' }
  1345. 'md-editor[data-files="off"] nav button.file' { display = 'none' }
  1346. 'md-editor nav button:disabled' { opacity = '.4' cursor = 'default' }
  1347. 'md-editor.source nav button' { opacity = '.4' pointerEvents = 'none' }
  1348. 'md-editor nav input.pick' { display = 'none' }
  1349. // 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
  1350. '@media (max-width: 40rem)' {
  1351. 'md-editor nav' { flexWrap = 'nowrap' overflowX = 'auto' contain = 'inline-size' }
  1352. 'md-editor nav button' { flex = '0 0 auto' minWidth = '2.75rem' minHeight = '2.75rem' }
  1353. }
  1354. 'md-editor ul.files' { display = 'none' margin = '0' padding = '.35rem .8rem' listStyle = 'none' borderBottom = '0' fontSize = '.85rem' }
  1355. 'md-editor ul.files:not(:empty)' { display = 'block' }
  1356. 'md-editor ul.files li' { display = 'flex' alignItems = 'center' gap = '.6rem' }
  1357. 'md-editor ul.files li span' { flex = '0 1 12rem' overflow = 'hidden' textOverflow = 'ellipsis' whiteSpace = 'nowrap' }
  1358. 'md-editor ul.files progress' { flex = '1' accentColor = 'var(--color-accent, #000)' }
  1359. 'md-editor ul.files li.error' { color = 'var(--color-danger, #000)' }
  1360. 'md-editor link-form' { display = 'none' gap = '.35rem' padding = '.35rem' borderBottom = '0' background = 'var(--color-surface, #ddd)' }
  1361. 'md-editor.linking link-form' { display = 'flex' }
  1362. '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' }
  1363. 'md-editor link-form button' { font = 'inherit' padding = '.3rem .7rem' color = 'var(--color-text, #000)' background = 'transparent' border = '0' borderRadius = '.35rem' cursor = 'pointer' }
  1364. 'md-editor article' { display = 'block' minHeight = '1.5em' padding = '.6rem .8rem' outline = 'none' overflowWrap = 'anywhere' animation = 'md-editor-mount 100ms infinite' }
  1365. 'md-editor.source article' { display = 'none' }
  1366. 'md-editor .placeholder' { display = 'none' position = 'absolute' left = '.8rem' marginTop = '.6rem' pointerEvents = 'none' color = 'var(--color-text-muted, #555)' }
  1367. 'md-editor.md-empty:not(.source) .placeholder' { display = 'block' }
  1368. 'md-editor article > :first-child' { marginTop = '0' }
  1369. 'md-editor article > :last-child' { marginBottom = '0' }
  1370. '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)' }
  1371. 'md-editor article h1' { fontSize = '1.6rem' }
  1372. 'md-editor article h2' { fontSize = '1.35rem' }
  1373. 'md-editor article h3' { fontSize = '1.15rem' }
  1374. 'md-editor article h4, md-editor article h5, md-editor article h6' { fontSize = '1rem' }
  1375. 'md-editor article p' { margin = '0 0 .7rem' }
  1376. 'md-editor article ul, md-editor article ol' { margin = '0 0 .7rem' paddingLeft = '1.5rem' }
  1377. 'md-editor article img' { display = 'block' maxWidth = '100%' height = 'auto' margin = '.3rem 0' borderRadius = '.3rem' }
  1378. 'md-editor article strong' { color = 'var(--color-text-strong, #000)' }
  1379. 'md-editor article a' { color = 'var(--color-accent, #000)' textDecoration = 'underline' }
  1380. 'md-editor article code' { padding = '0 .25rem' fontFamily = 'ui-monospace, monospace' fontSize = '.9em' background = 'var(--color-surface, #ddd)' borderRadius = '.25rem' }
  1381. 'md-editor article table' { display = 'block' maxWidth = '100%' overflowX = 'auto' margin = '0 0 .7rem' borderCollapse = 'collapse' }
  1382. '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' }
  1383. 'md-editor article th' { fontWeight = '700' color = 'var(--color-text-strong, #000)' }
  1384. 'md-editor article [data-align="left"]' { textAlign = 'left' }
  1385. 'md-editor article [data-align="center"]' { textAlign = 'center' }
  1386. 'md-editor article [data-align="right"]' { textAlign = 'right' }
  1387. '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' }
  1388. 'md-editor footer' { display = 'flex' justifyContent = 'flex-end' padding = '.3rem .5rem' borderTop = '0' }
  1389. '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' }
  1390. 'md-editor footer button:hover' { color = 'var(--color-text, #000)' }
  1391. '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' }
  1392. 'md-editor.source textarea' { display = 'block' }
  1393. // readonly: the formatted text alone, on the page's own background
  1394. 'md-editor[data-readonly="true"]' { background = 'transparent' borderRadius = '0' }
  1395. 'md-editor[data-readonly="true"]:focus-within' { outline = 'none' }
  1396. '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' }
  1397. 'md-editor[data-readonly="true"] article' { minHeight = '0' padding = '0' }
  1398. }
  1399. // The hidden input `name` carries the value in a form; the article is the surface; the textarea is the source view (a value shown
  1400. // only while it is on). The rendered parts never change after the first render, so the framework leaves the hand-built content alone.
  1401. View {
  1402. mdEditor { 'data-readonly' = readonly 'data-files' = files
  1403. nav {
  1404. button { type = "button" class = "bold" title = "Bold (Ctrl+B)" "B" on mousedown(e) { e.preventDefault() } on click(e) { emit mdTool(e, 'bold') } }
  1405. button { type = "button" class = "italic" title = "Italic (Ctrl+I)" "I" on mousedown(e) { e.preventDefault() } on click(e) { emit mdTool(e, 'italic') } }
  1406. button { type = "button" class = "code" title = "Code (Ctrl+E)" "<>" on mousedown(e) { e.preventDefault() } on click(e) { emit mdTool(e, 'code') } }
  1407. button { type = "button" class = "link" title = "Link (Ctrl+K)" "Link" on mousedown(e) { e.preventDefault() } on click(e) { emit mdTool(e, 'link') } }
  1408. button { type = "button" class = "heading" title = "Heading: paragraph, H1, H2, H3" "H" on mousedown(e) { e.preventDefault() } on click(e) { emit mdTool(e, 'heading') } }
  1409. button { type = "button" class = "ul" title = "Bulleted list" "• List" on mousedown(e) { e.preventDefault() } on click(e) { emit mdTool(e, 'ul') } }
  1410. button { type = "button" class = "ol" title = "Numbered list" "1. List" on mousedown(e) { e.preventDefault() } on click(e) { emit mdTool(e, 'ol') } }
  1411. button { type = "button" class = "pre" title = "Code block" "Block" on mousedown(e) { e.preventDefault() } on click(e) { emit mdTool(e, 'pre') } }
  1412. 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) } }
  1413. input { type = "file" class = "pick" multiple = "multiple" on change(e) { emit mdPicked(e) } }
  1414. button { type = "button" class = "undo" title = "Undo" "↶" on mousedown(e) { e.preventDefault() } on click(e) { emit mdTool(e, 'undo') } }
  1415. button { type = "button" class = "redo" title = "Redo" "↷" on mousedown(e) { e.preventDefault() } on click(e) { emit mdTool(e, 'redo') } }
  1416. }
  1417. linkForm {
  1418. input { type = "text" placeholder = "https://…" autocomplete = "off" on keydown(e) { emit mdLinkKey(e) } }
  1419. button { type = "button" "Apply" on click(e) { emit mdLinkSubmit(e) } }
  1420. button { type = "button" title = "Remove the link" "Remove" on click(e) { emit mdLinkRemove(e) } }
  1421. }
  1422. ul { class = "files" 'aria-live' = "polite" }
  1423. span { class = "placeholder" placeholder }
  1424. 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) } }
  1425. textarea { style = sourceStyle rows = rows spellcheck = "false" on input(e) { emit mdSourceInput(e) } }
  1426. input { class = "value" type = "hidden" name = name value = value }
  1427. footer { button { type = "button" class = "source-switch" on click(e) { emit mdSource(e) } "Markdown source" } }
  1428. }
  1429. }
  1430. // 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
  1431. // first focus / pointer-down / key, whichever comes first (mission 011 (c): keys typed at once after showing the tab landed in an unbuilt surface).
  1432. on mdMount(e) {
  1433. s = e.target
  1434. root = rootOf(s)
  1435. if (root.mdMounted == true) { return null }
  1436. root.mdMounted = true
  1437. s.style.animationName = 'none'
  1438. if (root.getAttribute('data-readonly') == 'true') { load(root, fieldOf(root).value) return null }
  1439. document.execCommand('defaultParagraphSeparator', false, 'p')
  1440. document.execCommand('styleWithCSS', false, false)
  1441. load(root, fieldOf(root).value)
  1442. sourceOf(root).value = fieldOf(root).value
  1443. document.addEventListener('selectionchange', () => { updateBar(root) })
  1444. // focus came before the build (it emptied the surface): the caret goes to the end of the text
  1445. if (s.contains(document.activeElement) || document.activeElement == s) {
  1446. last = s.lastChild
  1447. if (last != null) { document.getSelection().collapse(last, last.textContent == '' ? 0 : last.childNodes.length) }
  1448. }
  1449. }
  1450. on mdInput(e) {
  1451. e.stopPropagation()
  1452. root = rootOf(e.target)
  1453. s = surfaceOf(root)
  1454. // an emptied surface gets its paragraph back
  1455. if (s.childNodes.length == 0) {
  1456. np = document.createElement('p')
  1457. np.appendChild(document.createElement('br'))
  1458. s.appendChild(np)
  1459. document.getSelection().collapse(np, 0)
  1460. }
  1461. if (e.inputType == 'insertText' && (e.data == '*' || e.data == '_' || e.data == '`')) { inlineRule(root, e) }
  1462. sync(root)
  1463. updateBar(root)
  1464. }
  1465. on mdBefore(e) {
  1466. root = rootOf(e.target)
  1467. if (tableBefore(root, e)) { e.preventDefault() updateBar(root) return null }
  1468. if (e.inputType == 'insertText' && e.data == ' ') { blockRule(root, e) }
  1469. }
  1470. on mdKey(e) {
  1471. root = rootOf(e.target)
  1472. mod = e.ctrlKey || e.metaKey
  1473. // in a table: Tab / Shift+Tab move between the cells; a cell takes no block (heading, list, code block)
  1474. if (inCell(root)) {
  1475. if (e.key == 'Tab' && !mod && !e.altKey) { e.preventDefault() cellTab(root, cellOf(root, document.getSelection().anchorNode), e.shiftKey) updateBar(root) return null }
  1476. 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 }
  1477. }
  1478. if (mod && !e.shiftKey && !e.altKey && (e.key == 'k' || e.key == 'K')) { e.preventDefault() linkOpen(root) return null }
  1479. if (mod && !e.shiftKey && !e.altKey && (e.key == 'e' || e.key == 'E')) { e.preventDefault() codeToggle(root) sync(root) return null }
  1480. if (mod && e.shiftKey && (e.key == '8' || e.key == '*')) { e.preventDefault() blockToggle(root, 'ul', 'insertUnorderedList') sync(root) return null }
  1481. if (mod && e.shiftKey && (e.key == '7' || e.key == '&')) { e.preventDefault() blockToggle(root, 'ol', 'insertOrderedList') sync(root) return null }
  1482. if (mod && e.altKey && e.code == 'KeyC') { e.preventDefault() blockToggle(root, 'pre', '') sync(root) return null }
  1483. if (mod && e.altKey && e.code == 'Digit0') { e.preventDefault() document.execCommand('formatBlock', false, 'p') sync(root) return null }
  1484. 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 }
  1485. // Ctrl+Enter sends the form the editor sits in
  1486. if (mod && e.key == 'Enter') {
  1487. e.preventDefault()
  1488. form = root.closest('form')
  1489. if (form != null) { form.requestSubmit() }
  1490. return null
  1491. }
  1492. // Backspace at the very start of a heading / list item / code block turns it into a paragraph
  1493. if (e.key == 'Backspace' && document.getSelection().isCollapsed && inSurface(root)) {
  1494. let sel = document.getSelection()
  1495. let b = blockOf(root, sel.anchorNode)
  1496. if (b != null && 'h1,h2,h3,h4,h5,h6,ul,ol,pre'.split(',').indexOf(b.nodeName.toLowerCase()) >= 0) {
  1497. r = sel.getRangeAt(0)
  1498. pre = document.createRange()
  1499. pre.selectNodeContents(b)
  1500. pre.setEnd(r.endContainer, r.endOffset)
  1501. if (pre.toString() == '') {
  1502. e.preventDefault()
  1503. tag = b.nodeName.toLowerCase()
  1504. if (tag == 'ul') { document.execCommand('insertUnorderedList') }
  1505. else if (tag == 'ol') { document.execCommand('insertOrderedList') }
  1506. else { document.execCommand('formatBlock', false, 'p') }
  1507. sync(root)
  1508. return null
  1509. }
  1510. }
  1511. }
  1512. // 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)
  1513. if (e.key == 'Enter' && !mod && !e.shiftKey && inTag(root, ['pre']) && document.getSelection().isCollapsed) {
  1514. let xsel = document.getSelection()
  1515. let xb = blockOf(root, xsel.anchorNode)
  1516. if (xb != null && xb.nodeName == 'PRE') {
  1517. let xr = xsel.getRangeAt(0)
  1518. let xrest = document.createRange()
  1519. xrest.setStart(xr.endContainer, xr.endOffset)
  1520. xrest.setEnd(xb, xb.childNodes.length)
  1521. let xkids = xb.childNodes
  1522. if (xrest.toString() == '' && xkids.length >= 2 && xkids[xkids.length - 1].nodeName == 'BR' && xkids[xkids.length - 2].nodeName == 'BR') {
  1523. e.preventDefault()
  1524. xb.removeChild(xkids[xkids.length - 1])
  1525. let xnp = el('p', null)
  1526. xnp.appendChild(el('br', null))
  1527. xb.parentNode.insertBefore(xnp, xb.nextSibling)
  1528. if (clean(xb.textContent) == '') { xb.parentNode.removeChild(xb) }
  1529. xsel.collapse(xnp, 0)
  1530. sync(root)
  1531. updateBar(root)
  1532. return null
  1533. }
  1534. }
  1535. }
  1536. // ``` at the start of a line + Enter opens a code block
  1537. if (e.key == 'Enter' && !mod && !e.shiftKey && !inTag(root, ['pre'])) {
  1538. let sel = document.getSelection()
  1539. let b = sel.anchorNode != null ? blockOf(root, sel.anchorNode) : null
  1540. if (b != null && b.nodeName.toLowerCase() == 'p' && sel.isCollapsed && (clean(b.textContent).startsWith('```') || clean(b.textContent).startsWith('~~~')) && clean(b.textContent).replaceAll('`', '').replaceAll('~', '') == '') {
  1541. e.preventDefault()
  1542. sel.selectAllChildren(b)
  1543. document.execCommand('delete')
  1544. document.execCommand('formatBlock', false, 'pre')
  1545. sync(root)
  1546. }
  1547. }
  1548. }
  1549. on mdTool(e, tool) {
  1550. root = rootOf(e.target)
  1551. s = surfaceOf(root)
  1552. if (!inSurface(root)) { s.focus() }
  1553. // a cell takes no block
  1554. if (inCell(root) && (tool == 'heading' || tool == 'ul' || tool == 'ol' || tool == 'pre')) { return null }
  1555. if (tool == 'bold') { document.execCommand('bold') }
  1556. if (tool == 'italic') { document.execCommand('italic') }
  1557. if (tool == 'code') { codeToggle(root) }
  1558. if (tool == 'link') { linkOpen(root) return null }
  1559. if (tool == 'heading') { headingCycle(root) }
  1560. if (tool == 'ul') { blockToggle(root, 'ul', 'insertUnorderedList') }
  1561. if (tool == 'ol') { blockToggle(root, 'ol', 'insertOrderedList') }
  1562. if (tool == 'pre') { blockToggle(root, 'pre', '') }
  1563. if (tool == 'undo') { document.execCommand('undo') }
  1564. if (tool == 'redo') { document.execCommand('redo') }
  1565. sync(root)
  1566. updateBar(root)
  1567. }
  1568. on mdLinkSubmit(e) { linkApply(rootOf(e.target), false) }
  1569. on mdLinkRemove(e) { linkApply(rootOf(e.target), true) }
  1570. on mdLinkKey(e) {
  1571. if (e.key == 'Escape') { e.preventDefault() linkClose(rootOf(e.target)) }
  1572. if (e.key == 'Enter') { e.preventDefault() linkApply(rootOf(e.target), false) }
  1573. }
  1574. // 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
  1575. // is put in as elements; into a cell everything goes on one line
  1576. insertMarkdown(root, text) {
  1577. if (inTag(root, ['pre'])) { document.execCommand('insertText', false, text) return null }
  1578. cutAcross(root)
  1579. if (inCell(root)) {
  1580. one = trimSp(text.split(NL).join(' '))
  1581. if (one == '') { return null }
  1582. html = inlineHtml(one)
  1583. if (html != null) { document.execCommand('insertHTML', false, html) } else { document.execCommand('insertText', false, one) }
  1584. return null
  1585. }
  1586. box = el('div', null)
  1587. parseInto(box, text)
  1588. if (box.querySelector('table') != null) { insertBlocks(root, box) return null }
  1589. document.execCommand('insertHTML', false, mdHtml(text))
  1590. }
  1591. on mdPaste(e) {
  1592. e.preventDefault()
  1593. root = rootOf(e.target)
  1594. // files = "off": pasted files are the page's (they bubble on to a FilesUpload around the editor)
  1595. if (e.clipboardData.files.length > 0) {
  1596. if (root.getAttribute('data-files') != 'off') { attach(root, e.clipboardData.files, null) }
  1597. return null
  1598. }
  1599. // copied HTML with a table in it (a spreadsheet, a web page): its tables become tables (their cells' text), the rest plain text
  1600. html = e.clipboardData.getData('text/html')
  1601. if (!inCell(root) && !inTag(root, ['pre']) && html.toLowerCase().indexOf('<table') >= 0) {
  1602. // an inert document (no browsing context: it runs no script and loads nothing); hl:web compiles no `new DOMParser()` (repro
  1603. // .scratch/w004/gap-domparser/)
  1604. doc = document.implementation.createHTMLDocument('')
  1605. doc.body.innerHTML = html
  1606. box = el('div', null)
  1607. htmlBlocks(doc.body, box)
  1608. if (box.querySelector('table') != null) {
  1609. insertMarkdown(root, toMarkdown(box))
  1610. sync(root)
  1611. return null
  1612. }
  1613. }
  1614. // a Windows clipboard ends its lines with CR LF: the CRs go (in a cell or a code block too)
  1615. insertMarkdown(root, e.clipboardData.getData('text/plain').replaceAll(CR, ''))
  1616. sync(root)
  1617. }
  1618. on mdDrop(e) {
  1619. e.preventDefault()
  1620. root = rootOf(e.target)
  1621. if (e.dataTransfer.files.length > 0) {
  1622. if (root.getAttribute('data-files') == 'off') { return null }
  1623. at = document.caretRangeFromPoint(e.clientX, e.clientY)
  1624. attach(root, e.dataTransfer.files, at)
  1625. return null
  1626. }
  1627. text = e.dataTransfer.getData('text/plain')
  1628. if (text != '') { insertMarkdown(root, text) sync(root) }
  1629. }
  1630. // ---- files and images: dropped, pasted or chosen files go to the app through `emit server mdUpload(files)` (the framework sends them
  1631. // over HTTP with progress); the app stores them and answers the addresses; each lands in the text as ![name](address) (an image) or
  1632. // [name](address). Progress comes back as `uploadProgress` and is shown under the toolbar.
  1633. fileRow(root, p) {
  1634. list = root.querySelector('ul.files')
  1635. let li = list.children[p.index]
  1636. if (li == null) {
  1637. li = document.createElement('li')
  1638. li.appendChild(el('span', p.name))
  1639. li.appendChild(document.createElement('progress'))
  1640. list.appendChild(li)
  1641. }
  1642. bar = li.querySelector('progress')
  1643. bar.max = p.size
  1644. bar.value = p.sent
  1645. }
  1646. on client uploadProgress(p) {
  1647. for (root of document.querySelectorAll('md-editor.uploading')) { fileRow(root, p) }
  1648. }
  1649. attachMd(names, kinds, urls) {
  1650. out = []
  1651. let i = 0
  1652. while (i < urls.length) {
  1653. let label = names[i].replaceAll('[', '').replaceAll(']', '')
  1654. let u = urls[i].replaceAll(')', '%29').replaceAll(' ', '%20')
  1655. if (urls[i] != '') { out.push((kinds[i] ? '!' : '') + '[' + label + '](' + u + ')') }
  1656. i = i + 1
  1657. }
  1658. return out.join(NL + NL)
  1659. }
  1660. attach(root, files, at) {
  1661. s = surfaceOf(root)
  1662. sel = document.getSelection()
  1663. let range = at
  1664. if (range == null && inSurface(root)) { range = sel.getRangeAt(0).cloneRange() }
  1665. list = []
  1666. names = []
  1667. kinds = []
  1668. let k = 0
  1669. while (k < files.length) { list.push(files[k]) names.push(files[k].name) kinds.push(files[k].type.startsWith('image/')) k = k + 1 }
  1670. box = root.querySelector('ul.files')
  1671. box.textContent = ''
  1672. root.classList.add('uploading')
  1673. root.classList.remove('failed')
  1674. urls = emit server mdUpload(list)
  1675. root.classList.remove('uploading')
  1676. if (urls == null || urls.length != list.length) {
  1677. root.classList.add('failed')
  1678. box.textContent = ''
  1679. li = el('li', 'The upload failed.')
  1680. li.className = 'error'
  1681. box.appendChild(li)
  1682. return null
  1683. }
  1684. box.textContent = ''
  1685. s.focus()
  1686. if (range != null && s.contains(range.startContainer)) { sel.removeAllRanges() sel.addRange(range) }
  1687. else { sel.selectAllChildren(s) sel.collapseToEnd() }
  1688. md = attachMd(names, kinds, urls)
  1689. if (md == '') { return null }
  1690. // 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
  1691. // item's text: it is put on its own after the list, as elements (an editing command would join it to the item)
  1692. let top = null
  1693. if (sel.anchorNode == s) { top = s.childNodes[sel.anchorOffset - 1 >= 0 ? sel.anchorOffset - 1 : 0] }
  1694. else if (sel.anchorNode != null && s.contains(sel.anchorNode)) { top = blockOf(root, sel.anchorNode) }
  1695. if (top != null && (top.nodeName == 'UL' || top.nodeName == 'OL')) {
  1696. tmp = document.createElement('div')
  1697. parseInto(tmp, md)
  1698. ref = top.nextSibling
  1699. while (tmp.firstChild != null) { s.insertBefore(tmp.firstChild, ref) }
  1700. sel.selectAllChildren(s)
  1701. sel.collapseToEnd()
  1702. sync(root)
  1703. return null
  1704. }
  1705. insertMarkdown(root, md)
  1706. sync(root)
  1707. }
  1708. on mdPick(e) {
  1709. root = rootOf(e.target)
  1710. root.querySelector('input.pick').click()
  1711. }
  1712. on mdPicked(e) {
  1713. root = rootOf(e.target)
  1714. input = e.target
  1715. if (input.files.length > 0) { attach(root, input.files, null) }
  1716. input.value = ''
  1717. }
  1718. // Ctrl / Cmd + click follows a link
  1719. on mdClick(e) {
  1720. a = e.target.closest('a')
  1721. if ((e.ctrlKey || e.metaKey) && a != null && safeHref(a.getAttribute('href')) != '') { window.open(a.getAttribute('href'), '_blank', 'noopener') }
  1722. }
  1723. on mdBlur(e) { sync(rootOf(e.target)) }
  1724. // the Markdown source view: the whole field as a plain textarea, and back
  1725. on mdSource(e) {
  1726. root = rootOf(e.target)
  1727. ta = sourceOf(root)
  1728. b = root.querySelector('button.source-switch')
  1729. if (root.classList.contains('source')) {
  1730. md = ta.value
  1731. load(root, md)
  1732. root.classList.remove('source')
  1733. b.textContent = 'Markdown source'
  1734. sync(root)
  1735. surfaceOf(root).focus()
  1736. } else {
  1737. sync(root)
  1738. ta.value = fieldOf(root).value
  1739. root.classList.add('source')
  1740. b.textContent = 'Visual editor'
  1741. ta.focus()
  1742. }
  1743. }
  1744. on mdSourceInput(e) {
  1745. root = rootOf(e.target)
  1746. f = fieldOf(root)
  1747. f.value = e.target.value
  1748. f.dispatchEvent(new Event('input', { bubbles = true }))
  1749. }

Branches

Latest commits

  • 3e7e79f5reports/H1-hydrate.mdmre
  • d98775e8tests/browser.mjs: wait for hydration before the clicks after a goto('/') (tables new note, phone sidebar)mre
  • 1f3198b6tests/cdp.mjs: HL_CPU_THROTTLE=<rate> optional CPU throttling for gate runsmre
  • 39cf9fdfre-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
  • db07aa84tests: short-id-switch ports from env (NOTES_SWITCH_IDENT_PORT/_PORT), defaults unchangedmre
  • ef9f9feere-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
  • 5485467cdocker-compose: nofile 65536 (Hybriel int 6+ boot opened >1024 files in the tracker)mre
  • 86ea4a85deploy: backup copies index files first and *.mpack data last (hot-copy skew, hybriel #203)mre
  • edeab20fnotes mission 015: mission, report, LOG, STATUSmre
  • 542a0383notes mission 015: e2e-chrome E2E_HOST (own cookie jar in the shared Chrome)mre
  • 8b30f510notes mission 015: main-menu from layouts 0bcc629, current = true kept (route marks only /), server-HTML marker checksmre
  • 84b574c4notes mission 015: re-vendor plugins from hybriel f9614007 (incl. web, #117)mre
  • 447da53dnotes mission 014: report — remaining gates and lisbeth E2E proofmre
  • fd9f92c3notes mission 014: report (partial), LOG, STATUSmre
  • b2501360notes mission 014: open() sets asking=false before flush(0) (hybriel#196)mre
  • 9414ce59notes mission 014: merge theme 76f99f6, components 3794c59, strict single-press openAsk (fails on old open())mre
  • c08c655anotes 013: theme re-copied from layouts 76f99f6 (menu marks the current page), current = true on the menu item, e2e marker checks, reportmre
  • 21c8f65dnotes mission 012: STATUSmre
  • 0bbb3dd9notes mission 012: delete section of the browser gate de-flaked (openAsk: calm wait, press again when the question closes by itself); report 012mre
  • f431bdf8notes mission 011: notes on the layouts theme (ListFirst shell), styles cut, check-theme gate, E2E extended; reportmre