gitoria

components

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit3b73ae5b3b73ae5bcomponents #16 (mission 005) 2/4: Pagination tells the host the target page — the host hands onPage (hybriel#87: a function, not emit), called on every click that changes the page (pointer, Enter/Space, script click; Previous/Next/numbers/first/last; not … or the current page) with the target read from the clicked button's data-page before the rebuild; demo shows what the page was told; README Data out; 15 gate checks (14 fail on the old pagination)mre3b73ae5b/components/md-editor/md-editor.hl

69.3 KB

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

Branches

Latest commits

  • 3b73ae5bcomponents #16 (mission 005) 2/4: Pagination tells the host the target page — the host hands onPage (hybriel#87: a function, not emit), called on every click that changes the page (pointer, Enter/Space, script click; Previous/Next/numbers/first/last; not … or the current page) with the target read from the clicked button's data-page before the rebuild; demo shows what the page was told; README Data out; 15 gate checks (14 fail on the old pagination)mre
  • 6b27c0f0components #17 (mission 005) 1/4: md-editor keeps backslash + r — parseInto dropped the two characters '\r' (C:\root -> C:oot) instead of a real carriage return; CR now decoded from JSON (String.fromCharCode does not parse in a member), real CRs also go from pasted plain text; 5 gate checks (3 fail on the old md-editor.hl)mre
  • 1a5dc327mission brief w5mre
  • a567b579components (mission 004) 3/3: docs (README Hybriel a832f73b + tables, STATUS, LOG), report reports/004-md-editor-tables.mdmre
  • 70fe7ab5components (mission 004) 2/3: GitHub pipe tables in the Hybriel MdEditor (creator notes#5; behaviour of notes md-editor.js 9acc27f, no JavaScript) — parse/render (header, :--/:-:/--: alignment, \| in cells and code, inline Markdown in cells, outer pipes optional), padded writer, unchanged table byte for byte, typing | a | b | Enter |---|---| Enter makes a table, Tab/Shift+Tab, Enter new row, Enter in empty last row leaves, Backspace/Delete never merge, selection across a table empties cells, pasted HTML table -> table, thin #999 lines, wide table scrolls in its box; demo third editor 'plan'; gate 252/0 (22 new table checks, 20 fail on the old md-editor.hl)mre
  • f2adb3f3components (mission 004) 1/3: Hybriel master a832f73b (incremental build cache, HL_CACHE_DIR, #151) — bin/hybriel sha256 e1b53f7ce687f5afbe3db34bcda69958f56e730571e4841923c9c8eb3d272db9 built from git archive a832f73b (HL_NO_PLUGINS=1 native/build.sh), the same nine plugins; container: HL_CACHE_DIR=/cache on volume hybriel-cache, /tmp tmpfs; tests wait COMPONENTS_COLD_MS (120 s) for every start; deploy.sh DEPLOY_URL_WAIT 120 s; gate 230/0 coldmre
  • 91bd8a0dmission brief (w4)mre
  • 3bc905c5components #15 (mission 003) 2/2: docs (README Look, STATUS, LOG), reportmre
  • 5a98d77ecomponents #15 (mission 003) 1/2: black/white base look — greys for nuances, no WorldAPI fallbacks, no decorative frames; site + icon black/white; gate 230/0mre
  • 3f93d716components code order (mission 002) 4/4: docs, tests/letcount.py, tests/same-output*, reportmre
  • e747cfa0components code order (mission 002) 3/4: let only where reassigned (257 dropped, 0 never-reassigned left); gate 220/0, layouts gate 73/0, same outputmre
  • 172914a3components code order (mission 002) 2/4: lib/uploads.hl (demo upload storage), thin demo handlers, project.hl map; gate 220/0, same outputmre
  • d29f35b1components code order (mission 002) 1/4: styles.hl -> components/styles.hl; gate 220/0, same outputmre
  • 09945750components: Hybriel master 06617221 (plugin allocators 3a781359 + 413f60e4, http1 773de63e); gate 220/0mre
  • ede4d19acomponents: Hybriel master 190aa11d (fc838894 GC correctness, #126 closure scopes, #127); gate 220/0mre
  • 2bb9a935components: Hybriel master 8efba065 (re-vendor round 069: #126 memory, #48 lambda copy)mre
  • e4f01768antcolony#40: mission references point to the moved missionsmre
  • d32b44e2antcolony#40: history (LOG.md), worker briefs (missions/) and reports moved here from antcolony, numbered per project; old numbers in antcolony docs/mission-map.mdmre
  • 0fb80b57components: Hybriel master ff51cf46 (re-vendor round)mre
  • 57408b6ecomponents#14: installable app (manifest, service worker, offline index), own iconmre