gitoria

components

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit6b0936a06b0936a0comments: 'edited' foldable also drops the theme's border, margin and radius (display: contents alone left them computed)mre6b0936a0/components/md-editor/md-editor.hl

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

Branches

Latest commits

  • 6b0936a0comments: 'edited' foldable also drops the theme's border, margin and radius (display: contents alone left them computed)mre
  • 8d79ff79comments bubble hugs its content: a readonly md-editor surface gets no inline min-height (it beat the stylesheet's min-height 0); 'edited' is a quiet label beside the time, versions unframed; gate checksmre
  • ef253fecreports/F4-icons.mdmre
  • ba96735ficons: README, md-editor README note, gate checks for the single focus ring and toolbar iconsmre
  • 96c97691icons: shared Icon component; md-editor toolbar and files-upload remove use it; no inner focus ring in md-editormre
  • 0d6863d6reports/F3-mdvalue.mdmre
  • d58ed98bMdEditor: an older text of the editor handed back is not an outside change (kept surface, written back); gate for itmre
  • 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