gitoria

notes

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit1a8603d11a8603d1notes mission 011 WIP: deploy.sh gate summary also matches check-theme, browser.mjs logout via the user menumre1a8603d1/components/md-editor/md-editor.hl

71.6 KB

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

Branches

Latest commits

  • 1a8603d1notes mission 011 WIP: deploy.sh gate summary also matches check-theme, browser.mjs logout via the user menumre
  • dae2e508notes mission 011 WIP: theme dbe3de7, shell on AppHeader/MainMenu/UserMenu/Sidebar + ListFirst, styles cut to the app's own, check-theme gate, e2e auditmre
  • fd36da27notes mission 010: the note editor is the Hybriel MdEditor block (components.hybriel 1442e58, verbatim); md-editor.js, its route, script tag and offlineFiles retired; gate 66/0, realdata-offline 12/0, round-trip and Chrome E2E tests; report 010mre
  • efa92170notes tests/identkit.mjs: refuse a taken ident port, cold-wait deadline, emit, identities; mission 009 reportmre
  • f3dec0f1Merge branch 'w7'mre
  • d1cf966dre-vendor hybriel 97bcf128: offlineFiles for the editor script, 44 px taps, 390 px offline checks, mission 008mre
  • 4a610a21paths: projects moved into /media/STORAGE/projects/WorldAPI/mre
  • eeaea980report 007: say which runs included the removed checkmre
  • 8a8ad9banotes mission 007: report, LOG, STATUSmre
  • 2cce9c96code order: plain declarations where never reassigned (letcount 0 never); gate: scan every IndexedDB at log-out, soft mode for old-code runs, drop a check that could not failmre
  • 7f6a4090README: offline in Hybriel (hl:web offline, continuation, known md-editor gap); gate waits report instead of crash; realdata-offline checkmre
  • 632223f2notes#4: delete notes-offline.js and sw.js (hl:web's generated worker and kept state replace them)mre
  • 52a2acadgate: offline checks on hl:web's worker/queue, Chrome offline via CDP (reload offline first), one-offline conflict, log-out forgets the kept copymre
  • e5785b03notes#4: the notes page in Hybriel — hl:web offline = [Notes], queued faces notesPut/notesDrop, push notesChanged, value-form notesPull on a tick; notes-offline.js/sw.js no longer loaded or routedmre
  • 510aff75notes#4: server continues a run of saves of one login (by + since), loser keeps writing into its copy; notesFor listmre
  • 0176c4b5mission brief 007mre
  • 06cfa870notes mission 006: re-vendor hybriel 0f396652 (static), reportmre
  • 6c07bd91mission brief w6mre
  • cf64d3d5notes mission 005: stopped at a Hybriel gap (for list repainted during hl:web boot throws, rowKidless); report, LOG, STATUSmre
  • a43b5d2dmission brief 005mre