gitoria

components

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commitf60dab20f60dab20month-view: Style in the language's form (nested like the View, one declaration per line, bare @media)mref60dab20/components/md-editor/md-editor.hl

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

Only the first lines are shown.

Branches

Latest commits

  • f60dab20month-view: Style in the language's form (nested like the View, one declaration per line, bare @media)mre
  • 5b3c349aRe-vendor to Hybriel set day35 (cb9e480d): plugins core and web sources, README vendoring notemre
  • 3449b117components: a startup error prints its message before exit 1 (hybriel#247)mre
  • 59704ce1Merge branch 'n5b-pipes'mre
  • 23b9164aMdEditor: a clipboard whose text is only the names or file:// paths of its files (a file manager copy) is about the files, as before; any other text wins (tickets#49); gate casesmre
  • b0f1ec28MdEditor: a clipboard with text always pastes the text, also when a picture is on it too (a spreadsheet or office app), files on or off; a picture alone still goes to the files; real Ctrl+V gate tests/md-paste-files.mjs (tickets#49)mre
  • ad4e929bMdEditor: pipe rows without a delimiter row are a table (first row = header, short rows padded, written back without an invented | --- | line) (notes#5)mre
  • 4bd11128MdEditor: the Table button's empty table is written as a real pipe table (empty cells), so it survives the source switch, a save and a reload (notes#7)mre
  • 7437e32bMdEditor draws its surface at once when claimed from server HTML: 1 ms mount animation, the first editor mounts all editors of the pagemre
  • 5de0264cRe-vendor onto Hybriel master acaceaf3 (set-day27b): binary, lib and plugins; exit 1 on a startup fault; .gitignore binmre
  • 79c77e7dMerge sb3-standby: components deploys through its standbymre
  • c5442043components: no jobs switch needed in the standbymre
  • 8d2fb24ccomponents: a standby container (port 45016, profile standby); deploy hands over through standby-swap.sh without a gapmre
  • c2834dd3Merge mr-fixes: media player state after a queue pick, Range handling, cover-less audio, accessibility labelsmre
  • 354fe3c6Media player: audio without a cover starts and shows its time (the mount tick sits on the seek bar, which every item has); the speed button names the current speed, the seek slider says its time in words; a gate page for the first render on cover-less audio and a fourth demo queue item without a covermre
  • ee4aee1eMedia player: a new queue item shows its own speed, mute, play state and time and starts when asked, also for two videos in a row; the media route reads suffix ranges and ignores range lists and garbage instead of answering 500; stronger gate checks (the 10 percent drag, the played bar, the queue tap)mre
  • 9a4f9b31Merge mp-player: media served from the committed filesmre
  • ab96e686Media route: serve the demo's media from the committed files in components/media-player (storage/ is not in git, the deploy gate found no files)mre
  • b2980734Merge mp-player: the media player (components/media-player), its demo and the media iconsmre
  • 1c41293eMediaPlayer: back / forward 10 s as replay / forward 10 icons (circular arrow with a 10), the play button keeps its surface background on audio and video, the media route's range end is a letmre