gitoria

notes

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit04a625ed04a625edmission 004: re-vendor hybriel a832f73b (native bin + plugins as tickets), compose HL_CACHE_DIR volume + tmpfs /tmp, deploy URL wait 120 s, tests wait 120 s per start; gate 57/0 old and new; real-data same output. Not deployed.mre04a625ed/shared/md-editor.js

115.1 KB

  1. // md-editor.js — <md-editor>: a Markdown field that is edited VISUALLY (formatted while typing)
  2. // and whose value stays PLAIN MARKDOWN. worldapi-components (ticket tickets.worldapi.org#12,
  3. // concept accepted in #14). Plain JS, no build step, no dependencies, framework independent.
  4. //
  5. // <script src="md-editor.js"></script>
  6. // <md-editor><textarea name="summary" rows="4"></textarea></md-editor> ENHANCES a textarea
  7. // <md-editor name="summary" value="**hi**"></md-editor> or stands alone
  8. //
  9. // ENHANCE MODE (the normal case): the textarea stays in the form and keeps the Markdown — the
  10. // editor writes every change into it (+ an `input` event on it), and follows it when a script
  11. // sets `textarea.value` (a framework clearing the field after a send). Without JS the page shows
  12. // the plain textarea as before. STANDALONE: a form-associated element (`name`, `value`).
  13. //
  14. // THE MARKDOWN SUBSET is exactly the one tickets' renderer understands (tickets.worldapi.org
  15. // markdown.hl — the parser below is a line-by-line port of it): `#`…`######` headings, `-`/`*`/`+`
  16. // and `1.`/`1)` lists (one level), ``` / ~~~ fenced code, paragraphs whose single line breaks are
  17. // kept, `code`, [text](url), <https://…>, bare http(s) URLs, *em* _em_ **strong** __strong__
  18. // ***both***, backslash escapes, GitHub pipe tables (notes#5: header row, `| --- | :-: | --: |`
  19. // delimiter row with alignment, body rows, outer pipes optional, `\|` = a pipe in a cell, inline
  20. // Markdown in cells). Nothing else exists in the editor (no quotes, images, nesting, HTML).
  21. //
  22. // LOSSLESS: a block the user did not change is written back byte for byte (its original source);
  23. // a changed block is written in a canonical form that is VERIFIED against the parser (it must
  24. // parse back to exactly what the editor shows, else a safer escaping/marker variant is taken).
  25. // SAFE: the editor's DOM is built only with createElement/text nodes; hrefs pass safeHref
  26. // (http(s):, mailto:, /path, #anchor); pasted HTML is parsed in an inert document and reduced to
  27. // the subset — no HTML from outside ever reaches the page.
  28. //
  29. // See README.md (attributes, events, keyboard, restyling with --md-* variables and ::part()).
  30. (() => {
  31. 'use strict';
  32. if (typeof window === 'undefined' || !window.customElements || customElements.get('md-editor')) return;
  33. const NL = '\n';
  34. // =============================================================================================
  35. // 1. THE SUBSET — port of tickets.worldapi.org/markdown.hl (keep in step with it)
  36. // =============================================================================================
  37. const isSpaceC = (c) => c === 32 || c === 9 || c === 10 || c === 13;
  38. const isAlnumC = (c) => (c >= 48 && c <= 57) || (c >= 65 && c <= 90) || (c >= 97 && c <= 122) || c > 127;
  39. const isPunctC = (c) => (c >= 33 && c <= 47) || (c >= 58 && c <= 64) || (c >= 91 && c <= 96) || (c >= 123 && c <= 126);
  40. function safeHref(u) {
  41. if (u == null) return null;
  42. const t = String(u).trim();
  43. if (t === '' || t.length > 2000) return null;
  44. for (let i = 0; i < t.length; i++) {
  45. const c = t.charCodeAt(i);
  46. if (c <= 32 || c === 127 || c === 34 || c === 39 || c === 60 || c === 62 || c === 96 || c === 92) return null;
  47. }
  48. const low = t.toLowerCase();
  49. if (low.startsWith('https://') && t.length > 8) return t;
  50. if (low.startsWith('http://') && t.length > 7) return t;
  51. if (low.startsWith('mailto:') && t.length > 7) return t;
  52. if (t.startsWith('/') && !t.startsWith('//')) return t;
  53. if (t.startsWith('#')) return t;
  54. return null;
  55. }
  56. const isUrlStart = (s, i) => {
  57. const low = s.slice(i, i + 8).toLowerCase();
  58. return low.startsWith('https://') || low.startsWith('http://');
  59. };
  60. const isUrlStop = (c) => isSpaceC(c) || c === 60 || c === 62 || c === 34 || c === 96;
  61. function urlEnd(s, i) {
  62. let end = i;
  63. while (end < s.length && !isUrlStop(s.charCodeAt(end))) end++;
  64. let trimming = true;
  65. while (trimming && end > i) {
  66. const c = s.charCodeAt(end - 1);
  67. if (c === 46 || c === 44 || c === 59 || c === 58 || c === 33 || c === 63 || c === 39 || c === 42 || c === 95) {
  68. end--;
  69. } else if (c === 41) {
  70. let opens = 0, closes = 0;
  71. for (let k = i; k < end; k++) {
  72. if (s.charCodeAt(k) === 40) opens++;
  73. if (s.charCodeAt(k) === 41) closes++;
  74. }
  75. if (closes > opens) end--; else trimming = false;
  76. } else {
  77. trimming = false;
  78. }
  79. }
  80. return end;
  81. }
  82. function linkAt(s, i) {
  83. let j = i + 1, found = -1;
  84. while (j < s.length && found < 0) {
  85. const c = s.charCodeAt(j);
  86. if (c === 91) return null;
  87. if (c === 93) found = j;
  88. j++;
  89. }
  90. if (found < 0 || found === i + 1) return null;
  91. if (found + 1 >= s.length || s.charCodeAt(found + 1) !== 40) return null;
  92. const k = s.indexOf(')', found + 2);
  93. if (k < 0) return null;
  94. let target = s.slice(found + 2, k).trim();
  95. const sp = target.indexOf(' ');
  96. if (sp > 0) target = target.slice(0, sp);
  97. return { label: s.slice(i + 1, found), href: safeHref(target), end: k + 1 };
  98. }
  99. const textSpan = (t, strong, em) => ({ text: t, isText: !strong && !em, isStrong: strong && !em, isEm: em && !strong, isStrongEm: strong && em, isCode: false, isLink: false, href: '' });
  100. const codeSpan = (t) => ({ text: t, isText: false, isStrong: false, isEm: false, isStrongEm: false, isCode: true, isLink: false, href: '' });
  101. const linkSpan = (t, h) => ({ text: t, isText: false, isStrong: false, isEm: false, isStrongEm: false, isCode: false, isLink: true, href: h });
  102. function runAt(s, at, c, n, esc) {
  103. let i = at;
  104. while (i < s.length) {
  105. if (esc && s.charCodeAt(i) === 92) {
  106. i += 2;
  107. } else if (s.charCodeAt(i) === c) {
  108. let k = i;
  109. while (k < s.length && s.charCodeAt(k) === c) k++;
  110. if (k - i === n) return i;
  111. i = k;
  112. } else {
  113. i++;
  114. }
  115. }
  116. return -1;
  117. }
  118. function hasCloser(s, at, c, n) {
  119. let i = at;
  120. while (i < s.length) {
  121. const r = runAt(s, i, c, n, true);
  122. if (r < 0) return false;
  123. const prev = r > 0 ? s.charCodeAt(r - 1) : 32;
  124. const next = r + n < s.length ? s.charCodeAt(r + n) : 32;
  125. if (r > at && !isSpaceC(prev) && (c !== 95 || !isAlnumC(next))) return true;
  126. i = r + n;
  127. }
  128. return false;
  129. }
  130. function inlineSpans(src) {
  131. const out = [];
  132. if (src == null || src === '') return out;
  133. const s = String(src);
  134. const n = s.length;
  135. let buf = '', strong = false, em = false, strongC = 0, emC = 0, i = 0;
  136. while (i < n) {
  137. const c = s.charCodeAt(i);
  138. if (c === 92 && i + 1 < n && isPunctC(s.charCodeAt(i + 1))) {
  139. buf += s[i + 1];
  140. i += 2;
  141. } else if (c === 96) {
  142. let k = i;
  143. while (k < n && s.charCodeAt(k) === 96) k++;
  144. const close = runAt(s, k, 96, k - i, false);
  145. if (close < 0) {
  146. buf += s.slice(i, k);
  147. i = k;
  148. } else {
  149. if (buf !== '') out.push(textSpan(buf, strong, em));
  150. buf = '';
  151. let code = s.slice(k, close).split(NL).join(' ');
  152. if (code.length > 2 && code.startsWith(' ') && code.endsWith(' ') && code.trim() !== '') code = code.slice(1, code.length - 1);
  153. out.push(codeSpan(code));
  154. i = close + (k - i);
  155. }
  156. } else if (c === 91) {
  157. const l = linkAt(s, i);
  158. if (l == null) {
  159. buf += '[';
  160. i++;
  161. } else if (l.href == null) {
  162. buf += s.slice(i, l.end);
  163. i = l.end;
  164. } else {
  165. if (buf !== '') out.push(textSpan(buf, strong, em));
  166. buf = '';
  167. out.push(linkSpan(l.label, l.href));
  168. i = l.end;
  169. }
  170. } else if (c === 60 && i + 1 < n && isUrlStart(s, i + 1)) {
  171. const e = s.indexOf('>', i + 1);
  172. const url = e > 0 ? s.slice(i + 1, e) : '';
  173. const h = safeHref(url);
  174. if (e < 0 || h == null) {
  175. buf += '<';
  176. i++;
  177. } else {
  178. if (buf !== '') out.push(textSpan(buf, strong, em));
  179. buf = '';
  180. out.push(linkSpan(url, h));
  181. i = e + 1;
  182. }
  183. } else if ((c === 104 || c === 72) && (i === 0 || !isAlnumC(s.charCodeAt(i - 1))) && isUrlStart(s, i)) {
  184. const e = urlEnd(s, i);
  185. const url = s.slice(i, e);
  186. const h = safeHref(url);
  187. if (h == null) {
  188. buf += s[i];
  189. i++;
  190. } else {
  191. if (buf !== '') out.push(textSpan(buf, strong, em));
  192. buf = '';
  193. out.push(linkSpan(url, h));
  194. i = e;
  195. }
  196. } else if (c === 42 || c === 95) {
  197. let k = i;
  198. while (k < n && s.charCodeAt(k) === c) k++;
  199. const run = k - i;
  200. const prev = i > 0 ? s.charCodeAt(i - 1) : 32;
  201. const next = k < n ? s.charCodeAt(k) : 32;
  202. const wantStrong = run === 2 || run === 3;
  203. const wantEm = run === 1 || run === 3;
  204. const canOpen = !isSpaceC(next) && (c === 42 || !isAlnumC(prev));
  205. const canClose = !isSpaceC(prev) && (c === 42 || !isAlnumC(next));
  206. const closes = canClose && run <= 3 && (!wantStrong || (strong && strongC === c)) && (!wantEm || (em && emC === c));
  207. const opens = !closes && canOpen && run <= 3 && (!wantStrong || !strong) && (!wantEm || !em) && hasCloser(s, k, c, run);
  208. if (closes || opens) {
  209. if (buf !== '') out.push(textSpan(buf, strong, em));
  210. buf = '';
  211. if (wantStrong) { strong = opens; strongC = c; }
  212. if (wantEm) { em = opens; emC = c; }
  213. } else {
  214. buf += s.slice(i, k);
  215. }
  216. i = k;
  217. } else {
  218. buf += s[i];
  219. i++;
  220. }
  221. }
  222. if (buf !== '') out.push(textSpan(buf, strong, em));
  223. return out;
  224. }
  225. const noCr = (line) => (line.length > 0 && line.charCodeAt(line.length - 1) === 13 ? line.slice(0, line.length - 1) : line);
  226. const indentOf = (line) => {
  227. let i = 0;
  228. while (i < line.length && (line.charCodeAt(i) === 32 || line.charCodeAt(i) === 9)) i++;
  229. return i;
  230. };
  231. function headingOf(line) {
  232. if (indentOf(line) > 3) return null;
  233. const t = line.trim();
  234. let k = 0;
  235. while (k < t.length && t.charCodeAt(k) === 35) k++;
  236. if (k === 0 || k > 6) return null;
  237. if (k < t.length && t.charCodeAt(k) !== 32 && t.charCodeAt(k) !== 9) return null;
  238. let body = t.slice(k).trim();
  239. let e = body.length;
  240. while (e > 0 && body.charCodeAt(e - 1) === 35) e--;
  241. if (e === 0) body = '';
  242. else if (e < body.length && (body.charCodeAt(e - 1) === 32 || body.charCodeAt(e - 1) === 9)) body = body.slice(0, e).trim();
  243. return { level: k, text: body };
  244. }
  245. function itemOf(line) {
  246. const t = line.trim();
  247. if (t.length >= 2 && (t.charCodeAt(0) === 45 || t.charCodeAt(0) === 42 || t.charCodeAt(0) === 43) && (t.charCodeAt(1) === 32 || t.charCodeAt(1) === 9)) {
  248. return { ordered: false, start: 1, text: t.slice(2).trim() };
  249. }
  250. if (t.length === 1 && (t === '-' || t === '*' || t === '+')) return { ordered: false, start: 1, text: '' };
  251. let k = 0;
  252. while (k < t.length && k < 9 && t.charCodeAt(k) >= 48 && t.charCodeAt(k) <= 57) k++;
  253. if (k === 0 || k >= t.length) return null;
  254. const d = t.charCodeAt(k);
  255. if (d !== 46 && d !== 41) return null;
  256. if (k + 1 < t.length && t.charCodeAt(k + 1) !== 32 && t.charCodeAt(k + 1) !== 9) return null;
  257. return { ordered: true, start: Number(t.slice(0, k)), text: t.slice(k + 1).trim() };
  258. }
  259. function fenceOf(line) {
  260. if (indentOf(line) > 3) return null;
  261. const t = line.trim();
  262. if (t.length < 3) return null;
  263. const c = t.charCodeAt(0);
  264. if (c !== 96 && c !== 126) return null;
  265. let k = 0;
  266. while (k < t.length && t.charCodeAt(k) === c) k++;
  267. if (k < 3) return null;
  268. if (c === 96 && t.slice(k).includes('`')) return null;
  269. return t.slice(0, k);
  270. }
  271. // ---- GitHub pipe tables (notes#5) ---------------------------------------------------------
  272. // a row's cells as [from, to) ranges of `s` (trimmed): split at every '|' that is not escaped
  273. // (`\|`); a leading and a trailing pipe are optional. `skip(k)` (editor model only) marks
  274. // characters that never split or escape (inside code spans and links).
  275. function rowCells(s, skip) {
  276. const no = (k) => !!(skip && skip(k));
  277. const pipe = (k) => s.charCodeAt(k) === 124 && !no(k);
  278. const escaped = (k, from) => { let n = 0; while (k - 1 - n >= from && s.charCodeAt(k - 1 - n) === 92 && !no(k - 1 - n)) n++; return n % 2 === 1; };
  279. let a = 0, b = s.length;
  280. while (a < b && isSpaceC(s.charCodeAt(a))) a++;
  281. while (b > a && isSpaceC(s.charCodeAt(b - 1))) b--;
  282. if (a < b && pipe(a)) a++;
  283. if (b > a && pipe(b - 1) && !escaped(b - 1, a)) b--;
  284. const cells = [];
  285. let from = a, k = a;
  286. while (k < b) {
  287. if (s.charCodeAt(k) === 92 && !no(k) && k + 1 < b) { k += 2; continue; }
  288. if (pipe(k)) { cells.push([from, k]); from = k + 1; }
  289. k++;
  290. }
  291. cells.push([from, b]);
  292. return cells.map(([f, t]) => {
  293. while (f < t && isSpaceC(s.charCodeAt(f))) f++;
  294. while (t > f && isSpaceC(s.charCodeAt(t - 1))) t--;
  295. return [f, t];
  296. });
  297. }
  298. // a cell's Markdown: `\|` is a pipe (also inside code spans), every other escape stays for inlineSpans
  299. function unpipe(t) {
  300. let out = '', k = 0;
  301. while (k < t.length) {
  302. if (t.charCodeAt(k) === 92 && k + 1 < t.length) { out += t.charCodeAt(k + 1) === 124 ? '|' : t.slice(k, k + 2); k += 2; }
  303. else { out += t[k]; k++; }
  304. }
  305. return out;
  306. }
  307. // the delimiter row (must hold a pipe): the alignments ('' | 'left' | 'center' | 'right'), or null
  308. function alignsOf(line) {
  309. if (indentOf(line) > 3 || !line.includes('|')) return null;
  310. const out = [];
  311. for (const [f, t] of rowCells(line)) {
  312. const c = line.slice(f, t);
  313. if (!/^:?-+:?$/.test(c)) return null;
  314. const l = c.startsWith(':'), r = c.endsWith(':');
  315. out.push(l && r ? 'center' : r ? 'right' : l ? 'left' : '');
  316. }
  317. return out;
  318. }
  319. // a table starting at line i (header row + delimiter row with the same number of cells), or null
  320. function tableAt(lines, i) {
  321. if (i + 1 >= lines.length) return null;
  322. const head = noCr(lines[i]);
  323. if (indentOf(head) > 3 || head.trim() === '') return null;
  324. const aligns = alignsOf(noCr(lines[i + 1]));
  325. if (!aligns) return null;
  326. const cells = rowCells(head);
  327. return cells.length === aligns.length ? { aligns, head, cells } : null;
  328. }
  329. const blockBase = () => ({ isP: false, isH1: false, isH2: false, isH3: false, isUl: false, isOl: false, isCode: false, isTable: false, spans: [], items: [], start: 1, code: '', rows: [], aligns: [], cols: 0 });
  330. // the text → blocks, exactly as markdown.hl markdownBlocks. `ranges` (optional) receives, per
  331. // block, the source lines it came from ({ from, to } line indexes) and the heading level.
  332. function markdownBlocks(text, ranges) {
  333. const out = [];
  334. if (text == null || text === '') return out;
  335. const lines = String(text).split(NL);
  336. const rg = (from, to, level) => { if (ranges) ranges.push({ from, to, level }); };
  337. let para = [], paraFrom = 0;
  338. let inList = false, listOrdered = false, listStart = 1, items = [], listFrom = 0, listTo = 0;
  339. let blankBefore = false;
  340. const flushPara = () => {
  341. if (para.length > 0) {
  342. out.push(Object.assign(blockBase(), { isP: true, spans: inlineSpans(para.join(NL)) }));
  343. rg(paraFrom, paraFrom + para.length, 0);
  344. }
  345. para = [];
  346. };
  347. const flushList = () => {
  348. if (inList) {
  349. out.push(Object.assign(blockBase(), { isUl: !listOrdered, isOl: listOrdered, items: items.map((ls) => ({ spans: inlineSpans(ls.join(NL)) })), start: listStart }));
  350. rg(listFrom, listTo, 0);
  351. }
  352. inList = false;
  353. items = [];
  354. };
  355. let i = 0;
  356. while (i < lines.length) {
  357. const line = noCr(lines[i]);
  358. const fence = fenceOf(line);
  359. const h = fence == null ? headingOf(line) : null;
  360. const it = fence == null && h == null ? itemOf(line) : null;
  361. const tb = fence == null && h == null && it == null ? tableAt(lines, i) : null;
  362. if (fence != null) {
  363. flushPara();
  364. flushList();
  365. const code = [];
  366. let j = i + 1, closed = false;
  367. const fc = fence.charCodeAt(0);
  368. while (j < lines.length && !closed) {
  369. const l = noCr(lines[j]);
  370. const f = fenceOf(l);
  371. if (f != null && f.charCodeAt(0) === fc && f.length >= fence.length && l.trim() === f) closed = true;
  372. else code.push(l);
  373. j++;
  374. }
  375. out.push(Object.assign(blockBase(), { isCode: true, code: code.join(NL) }));
  376. rg(i, j, 0);
  377. i = j;
  378. blankBefore = false;
  379. } else if (line.trim() === '') {
  380. flushPara();
  381. blankBefore = true;
  382. i++;
  383. } else if (h != null) {
  384. flushPara();
  385. flushList();
  386. out.push(Object.assign(blockBase(), { isH1: h.level === 1, isH2: h.level === 2, isH3: h.level >= 3, spans: inlineSpans(h.text) }));
  387. rg(i, i + 1, h.level);
  388. blankBefore = false;
  389. i++;
  390. } else if (tb != null) {
  391. // a table: header, delimiter, then every line up to a blank line or another block
  392. flushPara();
  393. flushList();
  394. const cols = tb.aligns.length;
  395. const cellsOf = (l, rg0) => {
  396. const cs = rg0.map(([f, t]) => inlineSpans(unpipe(l.slice(f, t))));
  397. while (cs.length < cols) cs.push([]);
  398. return cs.slice(0, cols);
  399. };
  400. const rows = [cellsOf(tb.head, tb.cells)];
  401. let j = i + 2;
  402. while (j < lines.length) {
  403. const l = noCr(lines[j]);
  404. if (l.trim() === '' || fenceOf(l) != null || headingOf(l) != null || itemOf(l) != null) break;
  405. rows.push(cellsOf(l, rowCells(l)));
  406. j++;
  407. }
  408. out.push(Object.assign(blockBase(), { isTable: true, rows, aligns: tb.aligns, cols }));
  409. rg(i, j, 0);
  410. i = j;
  411. blankBefore = false;
  412. } else if (it != null) {
  413. flushPara();
  414. if (inList && listOrdered !== it.ordered) flushList();
  415. if (!inList) {
  416. inList = true;
  417. listOrdered = it.ordered;
  418. listStart = it.start;
  419. items = [];
  420. listFrom = i;
  421. }
  422. items.push([it.text]);
  423. listTo = i + 1;
  424. blankBefore = false;
  425. i++;
  426. } else if (inList && (!blankBefore || indentOf(line) >= 2)) {
  427. items[items.length - 1].push(line.trim());
  428. listTo = i + 1;
  429. blankBefore = false;
  430. i++;
  431. } else {
  432. flushList();
  433. if (para.length === 0) paraFrom = i;
  434. para.push(line.trim());
  435. blankBefore = false;
  436. i++;
  437. }
  438. }
  439. flushPara();
  440. flushList();
  441. return out;
  442. }
  443. // =============================================================================================
  444. // 2. THE EDITOR MODEL — blocks of items of segments
  445. // block { t: 'p'|'h'|'ul'|'ol'|'code', level, start, items: [segs], o (index of the original
  446. // block it came from, -1 = new) }; p / h / code have exactly one item.
  447. // seg { x: text, s: strong, e: em, c: code span, h: href | null, a: auto link (a bare URL) }
  448. // =============================================================================================
  449. const seg = (x, s = false, e = false, c = false, h = null, a = false) => ({ x, s, e, c, h, a });
  450. const same = (p, q) => p.s === q.s && p.e === q.e && p.c === q.c && p.h === q.h && p.a === q.a;
  451. function merge(segs) {
  452. const out = [];
  453. for (const g of segs) {
  454. if (!g.x) continue;
  455. const last = out[out.length - 1];
  456. if (last && same(last, g)) last.x += g.x;
  457. else out.push(seg(g.x, !!g.s, !!g.e, !!g.c, g.h || null, !!g.a));
  458. }
  459. return out;
  460. }
  461. function toChars(segs) {
  462. const out = [];
  463. for (const g of segs) for (let i = 0; i < g.x.length; i++) out.push({ x: g.x[i], s: !!g.s, e: !!g.e, c: !!g.c, h: g.h || null, a: !!g.a });
  464. return out;
  465. }
  466. const fromChars = (chars) => merge(chars);
  467. const textOf = (segs) => segs.map((g) => g.x).join('');
  468. const lenOf = (segs) => segs.reduce((n, g) => n + g.x.length, 0);
  469. const isWs = (ch) => ch === ' ' || ch === '\t' || ch === NL || ch === '\r';
  470. const block = (t, items, extra) => Object.assign({ t, level: 1, start: 1, items, o: -1 }, extra || {});
  471. const clone = (doc) => doc.map((b) => Object.assign({}, b, { items: b.items.map((it) => it.map((g) => Object.assign({}, g))) }));
  472. function spansToSegs(spans) {
  473. return merge(spans.map((sp) => {
  474. if (sp.isCode) return seg(sp.text, false, false, true);
  475. if (sp.isLink) return seg(sp.text, false, false, false, sp.href, sp.text === sp.href);
  476. return seg(sp.text, sp.isStrong || sp.isStrongEm, sp.isEm || sp.isStrongEm);
  477. }));
  478. }
  479. function fromParsed(pb, level) {
  480. if (pb.isP) return block('p', [spansToSegs(pb.spans)]);
  481. if (pb.isH1 || pb.isH2 || pb.isH3) return block('h', [spansToSegs(pb.spans)], { level: level || (pb.isH1 ? 1 : pb.isH2 ? 2 : 3) });
  482. if (pb.isUl) return block('ul', pb.items.map((it) => spansToSegs(it.spans)));
  483. if (pb.isOl) return block('ol', pb.items.map((it) => spansToSegs(it.spans)), { start: pb.start });
  484. if (pb.isTable) return block('table', [].concat(...pb.rows.map((r) => r.map(spansToSegs))), { cols: pb.cols, aligns: pb.aligns.slice() });
  485. return block('code', [pb.code ? [seg(pb.code)] : []]);
  486. }
  487. // ---- editor normalisation: what the model may hold at all ---------------------------------
  488. // (code blocks plain, headings one line, code spans / links carry no emphasis and no line
  489. // break, bare URLs are links — as the renderer shows them — and adjacent lists of one kind are
  490. // one list, because Markdown cannot keep them apart)
  491. function autolink(chars) {
  492. // demote auto links that were typed into or touch text (they are re-detected below)
  493. let i = 0;
  494. while (i < chars.length) {
  495. if (chars[i].a && chars[i].h) {
  496. let k = i;
  497. while (k < chars.length && chars[k].a && chars[k].h === chars[i].h) k++;
  498. const text = chars.slice(i, k).map((c) => c.x).join('');
  499. const before = i > 0 ? chars[i - 1] : null;
  500. const after = k < chars.length ? chars[k] : null;
  501. const touches = (c) => c && !c.h && !c.c && !isWs(c.x);
  502. if (text !== chars[i].h || touches(before) || touches(after)) {
  503. for (let j = i; j < k; j++) { chars[j].h = null; chars[j].a = false; }
  504. }
  505. i = k;
  506. } else i++;
  507. }
  508. // detect bare URLs in runs of plain text, the way the renderer does
  509. i = 0;
  510. while (i < chars.length) {
  511. if (chars[i].h || chars[i].c) { i++; continue; }
  512. let k = i;
  513. while (k < chars.length && !chars[k].h && !chars[k].c) k++;
  514. const T = chars.slice(i, k).map((c) => c.x).join('');
  515. let j = 0;
  516. while (j < T.length) {
  517. const c = T.charCodeAt(j);
  518. const prevC = j > 0 ? T.charCodeAt(j - 1) : (i > 0 && !chars[i - 1].h && !chars[i - 1].c ? chars[i - 1].x.charCodeAt(0) : 32);
  519. if ((c === 104 || c === 72) && !isAlnumC(prevC) && isUrlStart(T, j)) {
  520. const e = urlEnd(T, j);
  521. const url = T.slice(j, e);
  522. const h = safeHref(url);
  523. if (h != null) {
  524. for (let m = i + j; m < i + e; m++) Object.assign(chars[m], { h: url, a: true, s: false, e: false, c: false });
  525. j = e;
  526. continue;
  527. }
  528. }
  529. j++;
  530. }
  531. i = k;
  532. }
  533. return chars;
  534. }
  535. function edItem(segs, t) {
  536. let chars = toChars(segs);
  537. if (t === 'code') return chars.length ? [seg(chars.map((c) => c.x).join(''))] : [];
  538. for (const ch of chars) {
  539. if (ch.h) { ch.s = false; ch.e = false; ch.c = false; }
  540. if (ch.c) { ch.s = false; ch.e = false; ch.h = null; ch.a = false; }
  541. if (!ch.h) ch.a = false;
  542. if ((ch.c || ch.h) && (ch.x === NL || ch.x === '\r')) ch.x = ' ';
  543. if ((t === 'h' || t === 'td') && (ch.x === NL || ch.x === '\r')) ch.x = ' ';
  544. }
  545. chars = autolink(chars);
  546. return fromChars(chars);
  547. }
  548. function edDoc(doc) {
  549. const out = [];
  550. for (const b0 of doc) {
  551. const b = Object.assign({}, b0);
  552. if (b.t === 'code') {
  553. b.items = [edItem([seg(b.items.map(textOf).join(NL))], 'code')];
  554. } else if (b.t === 'p' || b.t === 'h') {
  555. b.items = [edItem(b.items.length ? [].concat(...b.items.map((it, k) => (k ? [seg(NL)].concat(it) : it))) : [], b.t)];
  556. } else if (b.t === 'table') {
  557. // a table: cells row by row (the first `cols` = the header), one line each
  558. const cols = Math.max(1, b.cols | 0);
  559. const items = b.items.slice();
  560. while (items.length < cols || items.length % cols) items.push([]);
  561. b.cols = cols;
  562. b.items = items.map((it) => edItem(it, 'td'));
  563. b.aligns = Array.from({ length: cols }, (_, k) => (b.aligns && b.aligns[k]) || '');
  564. } else {
  565. b.items = (b.items.length ? b.items : [[]]).map((it) => edItem(it, b.t));
  566. }
  567. if (b.t === 'h') b.level = Math.min(6, Math.max(1, b.level | 0 || 1));
  568. if (b.t === 'ol') b.start = Number.isFinite(b.start) && b.start >= 0 ? b.start : 1;
  569. const prev = out[out.length - 1];
  570. if (prev && (b.t === 'ul' || b.t === 'ol') && prev.t === b.t) {
  571. prev.items = prev.items.concat(b.items);
  572. prev.o = -1;
  573. continue;
  574. }
  575. out.push(b);
  576. }
  577. // a table at the end gets an empty paragraph after it (a place for the caret; never stored)
  578. if (!out.length || out[out.length - 1].t === 'table') out.push(block('p', [[]]));
  579. return out;
  580. }
  581. // ---- what is stored: empty blocks, empty lines and line-edge spaces cannot be kept ---------
  582. function trimLines(chars, dropEmpty) {
  583. // spaces/tabs at the item's edges and around line breaks go; empty lines go (dropEmpty) or
  584. // split the item (returned as several)
  585. const lines = [[]];
  586. for (const ch of chars) {
  587. if (ch.x === NL) lines.push([]);
  588. else if (ch.x !== '\r') lines[lines.length - 1].push(ch);
  589. }
  590. const trimmed = lines.map((l) => {
  591. let a = 0, b = l.length;
  592. while (a < b && (l[a].x === ' ' || l[a].x === '\t')) a++;
  593. while (b > a && (l[b - 1].x === ' ' || l[b - 1].x === '\t')) b--;
  594. return l.slice(a, b);
  595. });
  596. const groups = [[]];
  597. for (const l of trimmed) {
  598. if (l.length === 0) { if (!dropEmpty && groups[groups.length - 1].length) groups.push([]); continue; }
  599. groups[groups.length - 1].push(l);
  600. }
  601. return groups.filter((g) => g.length).map((g) => {
  602. const out = [];
  603. g.forEach((l, k) => { if (k) out.push({ x: NL, s: false, e: false, c: false, h: null, a: false }); out.push(...l); });
  604. return out;
  605. });
  606. }
  607. function fixLabels(chars) {
  608. for (const ch of chars) if (ch.h) { if (ch.x === '[') ch.x = '('; if (ch.x === ']') ch.x = ')'; }
  609. return chars;
  610. }
  611. function storable(b) {
  612. if (b.t === 'code') {
  613. const text = textOf(b.items[0] || []);
  614. return text === '' ? [] : [block('code', [[seg(text)]])];
  615. }
  616. if (b.t === 'p') return trimLines(fixLabels(toChars(b.items[0] || [])), false).map((cs) => block('p', [fromChars(cs)]));
  617. if (b.t === 'table') {
  618. const cells = b.items.map((it) => { const g = trimLines(fixLabels(toChars(it)), true); return g.length ? fromChars(g[0]) : []; });
  619. return cells.some((c) => lenOf(c) > 0) ? [block('table', cells, { cols: b.cols, aligns: b.aligns.slice() })] : [];
  620. }
  621. if (b.t === 'h') {
  622. const g = trimLines(fixLabels(toChars(b.items[0] || [])), true);
  623. return g.length ? [block('h', [fromChars(g[0])], { level: b.level })] : [];
  624. }
  625. const items = [];
  626. for (const it of b.items) {
  627. const g = trimLines(fixLabels(toChars(it)), true);
  628. if (g.length) items.push(fromChars(g[0]));
  629. }
  630. return items.length ? [block(b.t, items, { start: b.start })] : [];
  631. }
  632. // ---- the semantic key: what the renderer would show (two texts with the same key look the same)
  633. function itemKey(segs) {
  634. const chars = toChars(segs);
  635. for (const ch of chars) if (!ch.c && !ch.h && isWs(ch.x)) { ch.s = false; ch.e = false; }
  636. return merge(chars.map((ch) => Object.assign(ch, { a: false }))).map((g) => [g.x, g.s ? 1 : 0, g.e ? 1 : 0, g.c ? 1 : 0, g.h || '']);
  637. }
  638. function blockKey(b) {
  639. const kind = b.t === 'h' ? 'h' + Math.min(3, b.level) : b.t;
  640. if (b.t === 'code') return JSON.stringify(['code', textOf(b.items[0] || [])]);
  641. if (b.t === 'table') return JSON.stringify(['table', b.cols, b.aligns, b.items.map(itemKey)]);
  642. return JSON.stringify([kind, b.t === 'ol' ? b.start : 0, b.items.map(itemKey)]);
  643. }
  644. const keysOf = (blocks) => blocks.map(blockKey).join(NL);
  645. // the stored form of parsed Markdown (as the editor would hold it), as keys
  646. function parsedKeys(md) {
  647. const ranges = [];
  648. const pbs = markdownBlocks(md, ranges);
  649. const doc = edDoc(pbs.map((pb, k) => fromParsed(pb, ranges[k].level)));
  650. return keysOf([].concat(...doc.map(storable)));
  651. }
  652. // =============================================================================================
  653. // 3. MODEL → MARKDOWN (canonical, verified)
  654. // =============================================================================================
  655. const VARIANTS = [
  656. { em: '*', st: '**', auto: 'bare' }, { em: '*', st: '**', auto: 'angle' },
  657. { em: '_', st: '**', auto: 'bare' }, { em: '_', st: '**', auto: 'angle' },
  658. { em: '*', st: '__', auto: 'angle' }, { em: '_', st: '__', auto: 'angle' },
  659. ];
  660. function codeMd(x) {
  661. let run = 0, longest = 0;
  662. for (const ch of x) { if (ch === '`') { run++; longest = Math.max(longest, run); } else run = 0; }
  663. const fence = '`'.repeat(longest + 1);
  664. const pad = x.startsWith('`') || x.endsWith('`') || (x.startsWith(' ') && x.endsWith(' ') && x.trim() !== '') ? ' ' : '';
  665. return fence + pad + x + pad + fence;
  666. }
  667. // an auto link is written bare where the renderer finds exactly it again (prev not a letter,
  668. // the URL does not run on into what follows), else in <…>
  669. function linkMd(g, v, prev, after) {
  670. if (g.a && g.x === g.h && /^https?:\/\//i.test(g.h)) {
  671. const bare = v.auto === 'bare' && !isAlnumC(prev.charCodeAt(0) || 32) && urlEnd(g.x + after, 0) === g.x.length;
  672. return bare ? g.x : '<' + g.x + '>';
  673. }
  674. return '[' + g.x + '](' + g.h.replace(/\)/g, '%29') + ')';
  675. }
  676. // pieces: strings (fixed) and { ch, risky, esc } (a text character that may need a backslash)
  677. function buildPieces(segs, v, ctx) {
  678. const out = [];
  679. let line = '';
  680. const put = (str) => { out.push(str); const k = str.lastIndexOf(NL); line = k >= 0 ? str.slice(k + 1) : line + str; };
  681. const putCh = (ch) => {
  682. const lead = line.trim() === '';
  683. let risky = false;
  684. if (ch === '|' && ctx === 'td') { put('\\|'); return; }
  685. if ('\\`*_[<|'.includes(ch)) risky = true;
  686. else if (ch === '#') risky = lead || ctx === 'h';
  687. else if ('-+~'.includes(ch)) risky = lead;
  688. else if (ch === '.' || ch === ')') risky = /^\s*\d+$/.test(line);
  689. else if (ch === ':') risky = /https?$/i.test(line);
  690. if (ch === NL) { put(NL); return; }
  691. out.push({ ch, risky, esc: false });
  692. line += ch;
  693. };
  694. let cur = { s: false, e: false }, pend = '';
  695. const markers = (next) => {
  696. let m = '';
  697. if (cur.e && !next.e) m += v.em;
  698. if (cur.s && !next.s) m += v.st;
  699. let o = '';
  700. if (!cur.s && next.s) o += v.st;
  701. if (!cur.e && next.e) o += v.em;
  702. return [m, o];
  703. };
  704. const flushPend = () => { for (const ch of pend) putCh(ch); pend = ''; };
  705. const ms = merge(segs);
  706. ms.forEach((g, k) => {
  707. if (g.h) {
  708. flushPend();
  709. const nx = ms[k + 1];
  710. const after = !nx ? '' : nx.h ? '[' : nx.c ? '`' : (cur.s || cur.e) && !(nx.s === cur.s && nx.e === cur.e) ? '*' : nx.x;
  711. const lk = linkMd(g, v, line.slice(-1), after);
  712. put(ctx === 'td' ? lk.replace(/\|/g, '\\|') : lk);
  713. return;
  714. }
  715. if (g.c) { flushPend(); put(ctx === 'td' ? codeMd(g.x).replace(/\|/g, '\\|') : codeMd(g.x)); return; }
  716. let a = 0, b = g.x.length;
  717. while (a < b && isWs(g.x[a])) a++;
  718. while (b > a && isWs(g.x[b - 1])) b--;
  719. if (a === b) { pend += g.x; return; }
  720. const [close, open] = markers(g);
  721. if (close) put(close);
  722. flushPend();
  723. for (const ch of g.x.slice(0, a)) putCh(ch);
  724. if (open) put(open);
  725. for (const ch of g.x.slice(a, b)) putCh(ch);
  726. pend = g.x.slice(b);
  727. cur = { s: g.s, e: g.e };
  728. });
  729. const [close] = markers({ s: false, e: false });
  730. if (close) put(close);
  731. flushPend();
  732. return out;
  733. }
  734. const piecesStr = (ps) => ps.map((p) => (typeof p === 'string' ? p : p.esc ? '\\' + p.ch : p.ch)).join('');
  735. const wrapCtx = (md, ctx, level) => (ctx === 'h' ? '#'.repeat(level) + ' ' + md : ctx === 'li' ? '- ' + md.split(NL).join(NL + ' ') : ctx === 'td' ? '| ' + md + ' |' + NL + '| --- |' : md);
  736. const inlineCache = new Map();
  737. function inlineMd(segs, ctx, level) {
  738. const ck = ctx + (level || '') + JSON.stringify(segs);
  739. if (inlineCache.has(ck)) return inlineCache.get(ck);
  740. const target = JSON.stringify(itemKey(segs));
  741. const check = (md) => {
  742. const ranges = [];
  743. const bl = markdownBlocks(wrapCtx(md, ctx, level), ranges);
  744. if (bl.length !== 1) return md === '' && segs.length === 0;
  745. const b = edDoc([fromParsed(bl[0], ranges[0].level)])[0];
  746. if (ctx === 'p' && b.t !== 'p') return false;
  747. if (ctx === 'h' && b.t !== 'h') return false;
  748. if (ctx === 'li' && (b.t !== 'ul' || b.items.length !== 1)) return false;
  749. if (ctx === 'td' && (b.t !== 'table' || b.items.length !== 1)) return false;
  750. return JSON.stringify(itemKey(b.items[0])) === target;
  751. };
  752. let result = null;
  753. for (const v of VARIANTS) {
  754. const s = piecesStr(buildPieces(segs, v, ctx));
  755. if (check(s)) { result = s; break; }
  756. }
  757. if (result == null) {
  758. for (const v of VARIANTS) {
  759. const ps = buildPieces(segs, v, ctx);
  760. const risky = ps.filter((p) => typeof p !== 'string' && p.risky);
  761. risky.forEach((p) => { p.esc = true; });
  762. if (!check(piecesStr(ps))) continue;
  763. for (const p of risky) { p.esc = false; if (!check(piecesStr(ps))) p.esc = true; }
  764. result = piecesStr(ps);
  765. break;
  766. }
  767. }
  768. if (result == null) {
  769. // cannot be written exactly (should not happen): the fully escaped first variant
  770. const ps = buildPieces(segs, VARIANTS[0], ctx);
  771. ps.forEach((p) => { if (typeof p !== 'string' && p.risky) p.esc = true; });
  772. result = piecesStr(ps);
  773. }
  774. if (inlineCache.size > 2000) inlineCache.clear();
  775. inlineCache.set(ck, result);
  776. return result;
  777. }
  778. function tableMd(b) {
  779. const cols = b.cols;
  780. const cells = b.items.map((it) => inlineMd(it, 'td'));
  781. const w = [];
  782. for (let k = 0; k < cols; k++) {
  783. w[k] = 3;
  784. for (let i = k; i < cells.length; i += cols) w[k] = Math.max(w[k], cells[i].length);
  785. }
  786. const row = (r) => '| ' + cells.slice(r * cols, r * cols + cols).map((c, k) => c + ' '.repeat(w[k] - c.length)).join(' | ') + ' |';
  787. const dash = (al, n) => (al === 'center' ? ':' + '-'.repeat(n - 2) + ':' : al === 'left' ? ':' + '-'.repeat(n - 1) : al === 'right' ? '-'.repeat(n - 1) + ':' : '-'.repeat(n));
  788. const lines = [row(0), '| ' + b.aligns.map((al, k) => dash(al, w[k])).join(' | ') + ' |'];
  789. for (let r = 1; r < cells.length / cols; r++) lines.push(row(r));
  790. return lines.join(NL);
  791. }
  792. function blockMd(b) {
  793. if (b.t === 'table') return tableMd(b);
  794. if (b.t === 'p') return inlineMd(b.items[0], 'p');
  795. if (b.t === 'h') return '#'.repeat(b.level) + ' ' + inlineMd(b.items[0], 'h', b.level);
  796. if (b.t === 'ul') return b.items.map((it) => '- ' + inlineMd(it, 'li').split(NL).join(NL + ' ')).join(NL);
  797. if (b.t === 'ol') {
  798. return b.items.map((it, k) => {
  799. const mark = String(b.start + k) + '. ';
  800. return mark + inlineMd(it, 'li').split(NL).join(NL + ' '.repeat(mark.length));
  801. }).join(NL);
  802. }
  803. const text = textOf(b.items[0] || []);
  804. let n = 3;
  805. for (const l of text.split(NL)) { const m = /^\s*(`{3,})/.exec(l); if (m && m[1].length >= n) n = m[1].length + 1; }
  806. const fence = '`'.repeat(n);
  807. return fence + NL + text + NL + fence;
  808. }
  809. // the original text, cut into its blocks (sources, the lines between them, their keys)
  810. function prepareOriginal(md) {
  811. const text = md == null ? '' : String(md);
  812. const ranges = [];
  813. const pbs = markdownBlocks(text, ranges);
  814. const lines = text.split(NL);
  815. const doc = pbs.map((pb, k) => Object.assign(fromParsed(pb, ranges[k].level), { o: k }));
  816. const src = ranges.map((r) => lines.slice(r.from, r.to).join(NL));
  817. const keys = doc.map((b) => keysOf([].concat(...edDoc([b]).map(storable))));
  818. const joiners = ranges.map((r, k) => (k === 0 ? '' : NL + lines.slice(ranges[k - 1].to, r.from).map((l) => l + NL).join('')));
  819. const prefix = ranges.length ? lines.slice(0, ranges[0].from).map((l) => l + NL).join('') : '';
  820. const suffix = ranges.length ? lines.slice(ranges[ranges.length - 1].to).map((l) => NL + l).join('') : '';
  821. return { text, doc, src, keys, joiners, prefix, suffix, n: ranges.length };
  822. }
  823. function serialize(doc, orig) {
  824. const parts = [];
  825. const used = new Set();
  826. for (const b of doc) {
  827. const st = storable(b);
  828. const key = keysOf(st);
  829. const from = orig && b.o >= 0 && b.o < orig.n && !used.has(b.o) ? b.o : -1;
  830. if (from >= 0 && orig.keys[from] === key && key !== '') {
  831. used.add(from);
  832. parts.push({ md: orig.src[from], first: from, last: from, key });
  833. continue;
  834. }
  835. if (from >= 0) used.add(from);
  836. // a changed block is written anew, but keeps the blank lines around it
  837. st.forEach((sb, k) => parts.push({ md: blockMd(sb), first: k === 0 ? from : -1, last: k === st.length - 1 ? from : -1, key: blockKey(sb) }));
  838. }
  839. const expected = parts.map((p) => p.key).join(NL);
  840. let out = '';
  841. parts.forEach((p, k) => {
  842. if (k === 0) out += orig && p.first === 0 ? orig.prefix : '';
  843. else out += orig && p.first > 0 && parts[k - 1].last === p.first - 1 ? orig.joiners[p.first] : NL + NL;
  844. out += p.md;
  845. });
  846. if (orig && parts.length && parts[parts.length - 1].last === orig.n - 1 && orig.n > 0) out += orig.suffix;
  847. if (parsedKeys(out) === expected) return out;
  848. // the neighbours changed how a kept block reads: everything canonical
  849. const canon = [].concat(...doc.map(storable)).map(blockMd).join(NL + NL);
  850. return canon;
  851. }
  852. // =============================================================================================
  853. // 4. MODEL OPERATIONS on linear positions (every item counts its length + 1)
  854. // =============================================================================================
  855. function fromLin(doc, n) {
  856. let rest = Math.max(0, n);
  857. for (let b = 0; b < doc.length; b++) {
  858. for (let i = 0; i < doc[b].items.length; i++) {
  859. const L = lenOf(doc[b].items[i]);
  860. if (rest <= L) return { b, i, o: rest };
  861. rest -= L + 1;
  862. }
  863. }
  864. const b = doc.length - 1, i = doc[b].items.length - 1;
  865. return { b, i, o: lenOf(doc[b].items[i]) };
  866. }
  867. function toLin(doc, p) {
  868. let n = 0;
  869. for (let b = 0; b < p.b; b++) for (const it of doc[b].items) n += lenOf(it) + 1;
  870. for (let i = 0; i < p.i; i++) n += lenOf(doc[p.b].items[i]) + 1;
  871. return n + p.o;
  872. }
  873. const docLen = (doc) => toLin(doc, { b: doc.length - 1, i: doc[doc.length - 1].items.length - 1, o: lenOf(doc[doc.length - 1].items[doc[doc.length - 1].items.length - 1]) });
  874. // a table never merges with its neighbours: what is selected in it is emptied (cells stay), a
  875. // table selected as a whole (or between the ends) goes
  876. function cutItem(blk, i, f, t) {
  877. const chars = toChars(blk.items[i]);
  878. blk.items[i] = fromChars(chars.slice(0, f).concat(chars.slice(t == null ? chars.length : t)));
  879. }
  880. function delRange(doc, a, b) {
  881. if (b <= a) return doc;
  882. const p = fromLin(doc, a), q = fromLin(doc, b);
  883. const bp = doc[p.b], bq = doc[q.b];
  884. if (bp.t === 'table' || bq.t === 'table') {
  885. const whole = (blk, from, to) => from.i === 0 && from.o === 0 && to.i === blk.items.length - 1 && to.o === lenOf(blk.items[to.i]);
  886. if (p.b === q.b) {
  887. if (whole(bp, p, q)) { doc.splice(p.b, 1, block('p', [[]])); return doc; }
  888. for (let i = p.i; i <= q.i; i++) cutItem(bp, i, i === p.i ? p.o : 0, i === q.i ? q.o : null);
  889. return doc;
  890. }
  891. // the end block first (indexes before it stay valid)
  892. if (bq.t === 'table') {
  893. for (let i = 0; i <= q.i; i++) cutItem(bq, i, 0, i === q.i ? q.o : null);
  894. } else {
  895. bq.items = bq.items.slice(q.i);
  896. cutItem(bq, 0, 0, q.o);
  897. bq.o = -1;
  898. }
  899. doc.splice(p.b + 1, q.b - p.b - 1);
  900. if (bp.t === 'table') {
  901. for (let i = p.i; i < bp.items.length; i++) cutItem(bp, i, i === p.i ? p.o : 0, null);
  902. } else {
  903. bp.items = bp.items.slice(0, p.i + 1);
  904. cutItem(bp, p.i, p.o, null);
  905. }
  906. return doc;
  907. }
  908. const merged = fromChars(toChars(bp.items[p.i]).slice(0, p.o).concat(toChars(bq.items[q.i]).slice(q.o)));
  909. if (p.b === q.b) {
  910. bp.items.splice(p.i, q.i - p.i + 1, merged);
  911. return doc;
  912. }
  913. const rest = bq.items.slice(q.i + 1);
  914. bp.items = bp.items.slice(0, p.i).concat([merged]);
  915. const repl = rest.length ? [block(bq.t, rest, { level: bq.level, start: bq.start + q.i + 1 })] : [];
  916. doc.splice(p.b + 1, q.b - p.b, ...repl);
  917. return doc;
  918. }
  919. function insChars(doc, a, chars) {
  920. const p = fromLin(doc, a);
  921. const it = toChars(doc[p.b].items[p.i]);
  922. it.splice(p.o, 0, ...chars);
  923. doc[p.b].items[p.i] = fromChars(it);
  924. return a + chars.length;
  925. }
  926. const plainChars = (text, attrs) => Array.from(text).flatMap((u) => u.split('')).map((x) => Object.assign({ x, s: false, e: false, c: false, h: null, a: false }, attrs || {}));
  927. // Enter at the end of a typed delimiter row (`|---|:-:|`) under a header row (the line before,
  928. // in this paragraph or the one before it): the lines become a table with an empty row to type in.
  929. // Cells split at '|' outside code spans / links; `\|` typed in a row is a pipe in the cell.
  930. function linesOf(item) {
  931. const out = [[]];
  932. for (const ch of toChars(item)) { if (ch.x === NL) out.push([]); else out[out.length - 1].push(ch); }
  933. return out;
  934. }
  935. function cellsOfLine(chars) {
  936. const s = chars.map((c) => c.x).join('');
  937. const rich = (k) => !!(chars[k] && (chars[k].c || chars[k].h));
  938. return rowCells(s, rich).map(([f, t]) => {
  939. const out = [];
  940. for (let k = f; k < t; k++) {
  941. if (chars[k].x === '\\' && !rich(k) && k + 1 < t && chars[k + 1].x === '|' && !rich(k + 1)) continue;
  942. out.push(chars[k]);
  943. }
  944. return fromChars(out);
  945. });
  946. }
  947. function tableByEnter(doc, bi) {
  948. const lines = linesOf(doc[bi].items[0]);
  949. const prev = bi > 0 && doc[bi - 1].t === 'p' ? linesOf(doc[bi - 1].items[0]) : null;
  950. const plain = (l) => l.every((c) => !c.c && !c.h);
  951. for (let k = 0; k < lines.length; k++) {
  952. const delim = lines[k];
  953. if (!plain(delim)) continue;
  954. const aligns = alignsOf(delim.map((c) => c.x).join(''));
  955. if (!aligns) continue;
  956. const head = k > 0 ? lines[k - 1] : prev ? prev[prev.length - 1] : null;
  957. if (!head || head.every((c) => isWs(c.x))) continue;
  958. const hc = cellsOfLine(head);
  959. if (hc.length !== aligns.length) continue;
  960. const cols = aligns.length;
  961. const items = hc.slice();
  962. for (const l of lines.slice(k + 1)) {
  963. const rc = cellsOfLine(l).slice(0, cols);
  964. while (rc.length < cols) rc.push([]);
  965. items.push(...rc);
  966. }
  967. for (let c = 0; c < cols; c++) items.push([]);
  968. const join = (ls) => fromChars([].concat(...ls.map((l, n) => (n ? [{ x: NL, s: false, e: false, c: false, h: null, a: false }] : []).concat(l))));
  969. const repl = [];
  970. let from = bi, count = 1;
  971. if (k > 0) { if (k > 1) repl.push(block('p', [join(lines.slice(0, k - 1))])); }
  972. else {
  973. from = bi - 1;
  974. count = 2;
  975. if (prev.length > 1) repl.push(block('p', [join(prev.slice(0, prev.length - 1))]));
  976. }
  977. repl.push(block('table', items, { cols, aligns }));
  978. doc.splice(from, count, ...repl);
  979. const tb = from + repl.length - 1;
  980. return toLin(doc, { b: tb, i: items.length - cols, o: 0 });
  981. }
  982. return null;
  983. }
  984. function opEnter(doc, a) {
  985. const p = fromLin(doc, a);
  986. const blk = doc[p.b];
  987. const chars = toChars(blk.items[p.i]);
  988. if (blk.t === 'table') {
  989. // Enter in a table: a new empty row below; in an empty last row: out of the table
  990. const cols = blk.cols, row = Math.floor(p.i / cols), rows = blk.items.length / cols;
  991. const empty = blk.items.slice(row * cols, row * cols + cols).every((it) => lenOf(it) === 0);
  992. if (row > 0 && row === rows - 1 && empty) {
  993. blk.items.splice(row * cols, cols);
  994. const next = doc[p.b + 1];
  995. if (!(next && next.t === 'p' && lenOf(next.items[0]) === 0)) doc.splice(p.b + 1, 0, block('p', [[]]));
  996. return toLin(doc, { b: p.b + 1, i: 0, o: 0 });
  997. }
  998. blk.items.splice((row + 1) * cols, 0, ...Array.from({ length: cols }, () => []));
  999. return toLin(doc, { b: p.b, i: (row + 1) * cols, o: 0 });
  1000. }
  1001. if (blk.t === 'p' && p.o === chars.length) {
  1002. const t = tableByEnter(doc, p.b);
  1003. if (t != null) return t;
  1004. }
  1005. const head = fromChars(chars.slice(0, p.o)), tail = fromChars(chars.slice(p.o));
  1006. if (blk.t === 'code') {
  1007. const text = chars.map((c) => c.x).join('');
  1008. if (p.o === text.length && text.endsWith(NL)) {
  1009. blk.items[0] = fromChars(chars.slice(0, -1));
  1010. doc.splice(p.b + 1, 0, block('p', [[]]));
  1011. return toLin(doc, { b: p.b + 1, i: 0, o: 0 });
  1012. }
  1013. return insChars(doc, a, plainChars(NL));
  1014. }
  1015. if (blk.t === 'ul' || blk.t === 'ol') {
  1016. if (chars.every((c) => isWs(c.x))) {
  1017. const before = blk.items.slice(0, p.i), after = blk.items.slice(p.i + 1);
  1018. const repl = [];
  1019. if (before.length) repl.push(block(blk.t, before, { start: blk.start, o: blk.o }));
  1020. repl.push(block('p', [[]]));
  1021. if (after.length) repl.push(block(blk.t, after, { start: blk.start + p.i + 1 }));
  1022. doc.splice(p.b, 1, ...repl);
  1023. return toLin(doc, { b: p.b + (before.length ? 1 : 0), i: 0, o: 0 });
  1024. }
  1025. blk.items.splice(p.i, 1, head, tail);
  1026. return toLin(doc, { b: p.b, i: p.i + 1, o: 0 });
  1027. }
  1028. if (blk.t === 'h' && p.o === 0 && chars.length) {
  1029. doc.splice(p.b, 0, block('p', [[]]));
  1030. return toLin(doc, { b: p.b + 1, i: 0, o: 0 });
  1031. }
  1032. blk.items[0] = head;
  1033. doc.splice(p.b + 1, 0, block('p', [tail]));
  1034. return toLin(doc, { b: p.b + 1, i: 0, o: 0 });
  1035. }
  1036. function opBackspaceAtStart(doc, a) {
  1037. const p = fromLin(doc, a);
  1038. const blk = doc[p.b];
  1039. if (blk.t === 'table') return p.i > 0 ? a - 1 : a; // to the end of the cell before
  1040. if (blk.t === 'h' || blk.t === 'code') { blk.t = 'p'; blk.o = -1; return a; }
  1041. if (blk.t === 'ul' || blk.t === 'ol') {
  1042. if (p.i === 0) {
  1043. const rest = blk.items.slice(1);
  1044. const repl = [block('p', [blk.items[0]])];
  1045. if (rest.length) repl.push(block(blk.t, rest, { start: blk.start + 1 }));
  1046. doc.splice(p.b, 1, ...repl);
  1047. return a;
  1048. }
  1049. blk.items.splice(p.i - 1, 2, blk.items[p.i - 1].concat(blk.items[p.i]));
  1050. return a - 1;
  1051. }
  1052. if (p.b === 0) return a;
  1053. const prev = doc[p.b - 1];
  1054. if (prev.t === 'table') {
  1055. // never into a table: an empty paragraph goes, the caret moves to the last cell
  1056. if (lenOf(blk.items[0]) === 0) doc.splice(p.b, 1);
  1057. return a - 1;
  1058. }
  1059. if ((prev.t === 'p' || prev.t === 'h') && lenOf(prev.items[0]) === 0) {
  1060. doc.splice(p.b - 1, 1);
  1061. return a - 1;
  1062. }
  1063. const last = prev.items.length - 1;
  1064. prev.items[last] = prev.items[last].concat(blk.items[0]);
  1065. doc.splice(p.b, 1);
  1066. return a - 1;
  1067. }
  1068. function opDeleteAtEnd(doc, a) {
  1069. const p = fromLin(doc, a);
  1070. const blk = doc[p.b];
  1071. if (blk.t === 'table') return a;
  1072. if ((blk.t === 'ul' || blk.t === 'ol') && p.i < blk.items.length - 1) {
  1073. blk.items.splice(p.i, 2, blk.items[p.i].concat(blk.items[p.i + 1]));
  1074. return a;
  1075. }
  1076. if (p.b >= doc.length - 1) return a;
  1077. if (blk.t === 'p' && lenOf(blk.items[0]) === 0) { doc.splice(p.b, 1); return a; }
  1078. const next = doc[p.b + 1];
  1079. if (next.t === 'table') return a;
  1080. blk.items[p.i] = blk.items[p.i].concat(next.items[0]);
  1081. next.items.shift();
  1082. if (!next.items.length) doc.splice(p.b + 1, 1);
  1083. return a;
  1084. }
  1085. function opBlockType(doc, a, b, type, level) {
  1086. const P = fromLin(doc, a), Q = fromLin(doc, b);
  1087. const blocks = doc.slice(P.b, Q.b + 1);
  1088. if (blocks.some((blk) => blk.t === 'table')) return doc; // a table stays a table
  1089. const is = (blk) => (type === 'h' ? blk.t === 'h' && blk.level === level : blk.t === type);
  1090. const target = blocks.every(is) ? 'p' : type;
  1091. const lines = (it) => {
  1092. const out = [[]];
  1093. for (const ch of toChars(it)) { if (ch.x === NL) out.push([]); else out[out.length - 1].push(ch); }
  1094. return out.map(fromChars);
  1095. };
  1096. let repl = [];
  1097. if (target === 'code') {
  1098. const text = [].concat(...blocks.map((blk) => blk.items)).map(textOf).join(NL);
  1099. repl = [block('code', [text ? [seg(text)] : []])];
  1100. } else if (target === 'ul' || target === 'ol') {
  1101. const items = [];
  1102. for (const blk of blocks) {
  1103. if (blk.t === 'p' || blk.t === 'code') items.push(...lines(blk.items[0]));
  1104. else items.push(...blk.items);
  1105. }
  1106. const first = blocks.find((blk) => blk.t === 'ol');
  1107. repl = [block(target, items, { start: target === 'ol' && first ? first.start : 1 })];
  1108. } else {
  1109. for (const blk of blocks) {
  1110. for (const it of blk.items) repl.push(block(target, [it], { level: level || 1 }));
  1111. }
  1112. }
  1113. doc.splice(P.b, blocks.length, ...repl);
  1114. return doc;
  1115. }
  1116. // every item overlapping [a, b) (code blocks skipped): fn(chars, from, to) edits chars in place
  1117. function eachInRange(doc, a, b, fn) {
  1118. let n = 0;
  1119. for (const blk of doc) {
  1120. for (let i = 0; i < blk.items.length; i++) {
  1121. const L = lenOf(blk.items[i]);
  1122. const from = Math.max(a, n), to = Math.min(b, n + L);
  1123. if (from < to && blk.t !== 'code') {
  1124. const chars = toChars(blk.items[i]);
  1125. fn(chars, from - n, to - n);
  1126. blk.items[i] = fromChars(chars);
  1127. }
  1128. n += L + 1;
  1129. }
  1130. }
  1131. }
  1132. function charsInRange(doc, a, b) {
  1133. const out = [];
  1134. eachInRange(clone(doc), a, b, (chars, f, t) => { out.push(...chars.slice(f, t)); });
  1135. return out;
  1136. }
  1137. function opToggle(doc, a, b, attr) {
  1138. const all = charsInRange(doc, a, b).filter((ch) => !isWs(ch.x) && (attr === 'c' ? !ch.h : !ch.c && !ch.h));
  1139. const on = !(all.length && all.every((ch) => ch[attr]));
  1140. eachInRange(doc, a, b, (chars, f, t) => {
  1141. for (let k = f; k < t; k++) {
  1142. const ch = chars[k];
  1143. if (ch.x === NL) continue;
  1144. if (attr === 'c') {
  1145. if (ch.h) continue;
  1146. ch.c = on;
  1147. if (on) { ch.s = false; ch.e = false; }
  1148. } else if (!ch.c && !ch.h) ch[attr] = on;
  1149. }
  1150. });
  1151. return doc;
  1152. }
  1153. function opLink(doc, a, b, href) {
  1154. eachInRange(doc, a, b, (chars, f, t) => {
  1155. for (let k = f; k < t; k++) {
  1156. const ch = chars[k];
  1157. if (ch.x === NL) continue;
  1158. if (href) Object.assign(ch, { h: href, a: false, s: false, e: false, c: false });
  1159. else Object.assign(ch, { h: null, a: false });
  1160. }
  1161. });
  1162. return doc;
  1163. }
  1164. function linkExtent(doc, a) {
  1165. const p = fromLin(doc, a);
  1166. const chars = toChars(doc[p.b].items[p.i]);
  1167. let k = p.o < chars.length && chars[p.o].h ? p.o : p.o > 0 && chars[p.o - 1].h ? p.o - 1 : -1;
  1168. if (k < 0) return null;
  1169. const h = chars[k].h;
  1170. let f = k, t = k;
  1171. while (f > 0 && chars[f - 1].h === h) f--;
  1172. while (t < chars.length && chars[t].h === h) t++;
  1173. const base = a - p.o;
  1174. return { a: base + f, b: base + t, href: h, auto: chars[k].a };
  1175. }
  1176. // =============================================================================================
  1177. // 5. DOM ⇄ MODEL
  1178. // =============================================================================================
  1179. const BLOCK_TAGS = new Set(['P', 'DIV', 'H1', 'H2', 'H3', 'H4', 'H5', 'H6', 'UL', 'OL', 'LI', 'PRE', 'BLOCKQUOTE', 'SECTION', 'ARTICLE', 'HEADER', 'FOOTER', 'ASIDE', 'NAV', 'MAIN', 'TABLE', 'THEAD', 'TBODY', 'TFOOT', 'TR', 'HR', 'DL', 'DT', 'DD', 'FIGURE', 'FIGCAPTION', 'ADDRESS', 'FORM', 'FIELDSET', 'DETAILS', 'SUMMARY']);
  1180. const SKIP_TAGS = new Set(['SCRIPT', 'STYLE', 'TEMPLATE', 'NOSCRIPT', 'IFRAME', 'OBJECT', 'EMBED', 'SVG', 'MATH', 'CANVAS', 'VIDEO', 'AUDIO', 'HEAD', 'META', 'LINK', 'TITLE', 'BUTTON', 'SELECT', 'INPUT', 'TEXTAREA', 'IMG', 'PICTURE', 'SOURCE']);
  1181. // reads DOM content into items. `opts.html` = foreign HTML (paste): whitespace collapses and
  1182. // styles (font-weight / font-style) count; else it is our own editor DOM. `marks`: DOM points
  1183. // whose model positions are wanted ({ node, off } → .lin).
  1184. function readDom(root, opts) {
  1185. const html = !!(opts && opts.html);
  1186. const marks = (opts && opts.marks) || [];
  1187. const doc = [];
  1188. let lin = 0; // linear position at the start of the open item
  1189. let cur = null; // the open item: { blk, chars, marks: [] }
  1190. let waiting = []; // marks met between items: they belong to the start of the next one
  1191. const open = (blk) => {
  1192. close();
  1193. cur = { blk, chars: [], marks: [] };
  1194. for (const m of waiting) { m.rel = 0; cur.marks.push(m); }
  1195. waiting = [];
  1196. };
  1197. const close = () => {
  1198. if (!cur) return;
  1199. const chars = cur.chars;
  1200. if (!html && chars.length && chars[chars.length - 1].x === NL) chars.pop(); // the caret's filler <br>
  1201. if (html) {
  1202. // collapsed HTML whitespace: none at the item's edges or around line breaks
  1203. const lines = [[]];
  1204. for (const ch of chars) { if (ch.x === NL) lines.push([]); else lines[lines.length - 1].push(ch); }
  1205. const t = lines.map((l) => { let a = 0, b = l.length; while (a < b && l[a].x === ' ') a++; while (b > a && l[b - 1].x === ' ') b--; return l.slice(a, b); });
  1206. chars.length = 0;
  1207. t.forEach((l, k) => { if (k) chars.push({ x: NL, s: false, e: false, c: false, h: null, a: false }); chars.push(...l); });
  1208. }
  1209. for (const m of cur.marks) m.lin = lin + Math.min(m.rel, chars.length);
  1210. const blk = cur.blk;
  1211. if (!blk.pushed) { blk.pushed = true; doc.push(blk); }
  1212. blk.items.push(fromChars(chars));
  1213. lin += chars.length + 1;
  1214. cur = null;
  1215. };
  1216. const ensure = () => { if (!cur) open(block('p', [])); };
  1217. const markAt = (node, off) => {
  1218. for (const m of marks) {
  1219. if (m.node !== node || m.off !== off || m.lin != null) continue;
  1220. m.lin = -2;
  1221. if (cur) { cur.marks.push(m); m.rel = cur.chars.length; } else waiting.push(m);
  1222. }
  1223. };
  1224. const pushText = (s, at) => {
  1225. ensure();
  1226. for (let k = 0; k < s.length; k++) cur.chars.push({ x: s[k], s: !!at.s, e: !!at.e, c: !!at.c, h: at.h || null, a: !!at.a });
  1227. };
  1228. const attrsOf = (el, at) => {
  1229. const t = el.tagName;
  1230. const n = Object.assign({}, at);
  1231. if (t === 'STRONG' || t === 'B') n.s = true;
  1232. if (t === 'EM' || t === 'I' || t === 'CITE' || t === 'DFN' || t === 'VAR') n.e = true;
  1233. if (t === 'CODE' || t === 'KBD' || t === 'SAMP' || t === 'TT') n.c = true;
  1234. if (t === 'A') {
  1235. const h = safeHref(el.getAttribute('href'));
  1236. if (h) { n.h = h; n.a = !html && el.hasAttribute('data-auto'); }
  1237. }
  1238. if (html && el.style) {
  1239. const fw = el.style.fontWeight;
  1240. if (fw === 'bold' || fw === 'bolder' || Number(fw) >= 600) n.s = true;
  1241. if (fw === 'normal' || fw === 'lighter' || (Number(fw) > 0 && Number(fw) < 600)) n.s = false;
  1242. if (el.style.fontStyle === 'italic' || el.style.fontStyle === 'oblique') n.e = true;
  1243. if (el.style.fontStyle === 'normal') n.e = false;
  1244. }
  1245. return n;
  1246. };
  1247. const textOfPre = (el) => {
  1248. let s = '';
  1249. const walk = (n) => {
  1250. for (const c of n.childNodes) {
  1251. if (c.nodeType === 3) s += c.data;
  1252. else if (c.nodeType === 1 && c.tagName === 'BR') s += NL;
  1253. else if (c.nodeType === 1 && !SKIP_TAGS.has(c.tagName)) walk(c);
  1254. }
  1255. };
  1256. walk(el);
  1257. return s;
  1258. };
  1259. const inline = (n, at, pre) => {
  1260. if (n.nodeType === 3) {
  1261. let s = n.data;
  1262. if (html && !pre) s = s.replace(/[\t\n\r\f ]+/g, ' ');
  1263. else s = s.replace(/\r\n?/g, NL);
  1264. if (!html) { for (const m of marks) if (m.node === n && m.lin == null) { ensure(); cur.marks.push(m); m.rel = cur.chars.length + Math.min(m.off, s.length); m.lin = -2; } }
  1265. if (s) pushText(s, at);
  1266. return;
  1267. }
  1268. if (n.nodeType !== 1 || SKIP_TAGS.has(n.tagName)) {
  1269. if (n.nodeType === 1 && n.tagName === 'IMG' && html && n.getAttribute('alt')) pushText(n.getAttribute('alt'), at);
  1270. return;
  1271. }
  1272. if (n.tagName === 'BR') { ensure(); cur.chars.push({ x: NL, s: false, e: false, c: false, h: null, a: false }); return; }
  1273. if (BLOCK_TAGS.has(n.tagName)) { blockEl(n, at); return; }
  1274. if ((n.tagName === 'TD' || n.tagName === 'TH') && cur && cur.chars.length) pushText(' ', {});
  1275. const na = attrsOf(n, at);
  1276. children(n, na, pre);
  1277. };
  1278. const children = (n, at, pre) => {
  1279. const kids = Array.from(n.childNodes);
  1280. kids.forEach((c, k) => { markAt(n, k); inline(c, at, pre); });
  1281. markAt(n, kids.length);
  1282. };
  1283. const listEl = (el, at) => {
  1284. const t = el.tagName === 'OL' ? 'ol' : 'ul';
  1285. const start = t === 'ol' && el.hasAttribute('start') ? Number(el.getAttribute('start')) || 1 : 1;
  1286. const blk = block(t, [], { start });
  1287. if (!html && el.__mdO != null) blk.o = el.__mdO;
  1288. close();
  1289. const kids = Array.from(el.childNodes);
  1290. kids.forEach((c, k) => {
  1291. markAt(el, k);
  1292. if (c.nodeType === 1 && c.tagName === 'LI') {
  1293. open(blk);
  1294. const inner = Array.from(c.childNodes);
  1295. inner.forEach((d, j) => {
  1296. markAt(c, j);
  1297. if (d.nodeType === 1 && (d.tagName === 'UL' || d.tagName === 'OL')) {
  1298. // a nested list: its items become items of this one (one level only)
  1299. for (const li of d.children) { open(blk); children(li, at, false); }
  1300. } else if (d.nodeType === 1 && BLOCK_TAGS.has(d.tagName) && d.tagName !== 'LI') {
  1301. if (cur && cur.chars.length && cur.chars[cur.chars.length - 1].x !== NL) cur.chars.push({ x: NL, s: false, e: false, c: false, h: null, a: false });
  1302. children(d, attrsOf(d, at), false);
  1303. } else inline(d, at, false);
  1304. });
  1305. markAt(c, inner.length);
  1306. close();
  1307. } else if (c.nodeType === 3 && !c.data.trim()) {
  1308. // whitespace between items
  1309. } else {
  1310. open(blk);
  1311. inline(c, at, false);
  1312. close();
  1313. }
  1314. });
  1315. markAt(el, kids.length);
  1316. if (!blk.items.length && !html) { open(blk); close(); }
  1317. close();
  1318. };
  1319. // a table: one item per cell, row by row (the first row = the header); pasted cells are read
  1320. // as their text (blocks inside a cell become one line)
  1321. const alignOf = (c) => {
  1322. const v = String((c.getAttribute && (c.getAttribute('data-align') || c.getAttribute('align'))) || (c.style && c.style.textAlign) || '').toLowerCase();
  1323. return v === 'left' || v === 'center' || v === 'right' ? v : '';
  1324. };
  1325. const isCell = (c) => c.nodeType === 1 && (c.tagName === 'TD' || c.tagName === 'TH');
  1326. const tableEl = (el) => {
  1327. close();
  1328. const trs = [];
  1329. const collect = (n) => { for (const c of n.children) { if (c.tagName === 'TR') trs.push(c); else if (c.tagName === 'THEAD' || c.tagName === 'TBODY' || c.tagName === 'TFOOT') collect(c); } };
  1330. collect(el);
  1331. const counts = trs.map((tr) => Array.from(tr.childNodes).filter(isCell).length);
  1332. const cols = html ? Math.max(0, ...counts) : counts[0] || 0;
  1333. if (!cols) return;
  1334. const first = Array.from(trs[0].childNodes).filter(isCell);
  1335. const blk = block('table', [], { cols, aligns: Array.from({ length: cols }, (_, k) => (first[k] ? alignOf(first[k]) : '')) });
  1336. if (!html && el.__mdO != null) blk.o = el.__mdO;
  1337. const walk = (n) => {
  1338. const kids = Array.from(n.childNodes);
  1339. kids.forEach((c, k) => {
  1340. markAt(n, k);
  1341. if (c.nodeType !== 1) return;
  1342. if (c.tagName === 'THEAD' || c.tagName === 'TBODY' || c.tagName === 'TFOOT') { walk(c); return; }
  1343. if (c.tagName !== 'TR') return;
  1344. let n2 = 0;
  1345. const cells = Array.from(c.childNodes);
  1346. cells.forEach((d, j) => {
  1347. markAt(c, j);
  1348. if (!isCell(d) || n2 >= cols) return;
  1349. open(blk);
  1350. if (html) {
  1351. const parts = readDom(d, { html: true });
  1352. const items = [].concat(...parts.map((b) => b.items)).filter((it) => lenOf(it) > 0);
  1353. items.forEach((it, m) => { if (m) pushText(' ', {}); cur.chars.push(...toChars(it)); });
  1354. } else children(d, {}, false);
  1355. close();
  1356. n2++;
  1357. });
  1358. markAt(c, cells.length);
  1359. while (n2 < cols) { open(blk); close(); n2++; }
  1360. });
  1361. markAt(n, kids.length);
  1362. };
  1363. walk(el);
  1364. close();
  1365. };
  1366. const blockEl = (el, at) => {
  1367. const t = el.tagName;
  1368. if (t === 'HR') { close(); return; }
  1369. if (t === 'TABLE') { tableEl(el); return; }
  1370. if (t === 'UL' || t === 'OL') { listEl(el, at); return; }
  1371. if (t === 'LI') { const fake = { tagName: 'UL', childNodes: [el], hasAttribute: () => false }; listEl(fake, at); return; }
  1372. if (t === 'PRE') {
  1373. const blk = block('code', []);
  1374. if (!html && el.__mdO != null) blk.o = el.__mdO;
  1375. open(blk);
  1376. if (html) pushText(textOfPre(el).replace(/\n$/, ''), {});
  1377. else children(el, {}, true);
  1378. close();
  1379. return;
  1380. }
  1381. if (/^H[1-6]$/.test(t)) {
  1382. const blk = block('h', [], { level: Number(t[1]) });
  1383. if (!html && el.__mdO != null) blk.o = el.__mdO;
  1384. open(blk);
  1385. children(el, html ? attrsOf(el, at) : at, false);
  1386. close();
  1387. return;
  1388. }
  1389. // P / DIV / … : a paragraph, unless it holds blocks itself
  1390. const hasBlocks = Array.from(el.children).some((c) => BLOCK_TAGS.has(c.tagName));
  1391. if (hasBlocks) {
  1392. close();
  1393. const na = html ? attrsOf(el, at) : at;
  1394. const kids = Array.from(el.childNodes);
  1395. kids.forEach((c, k) => {
  1396. markAt(el, k);
  1397. if (c.nodeType === 1 && BLOCK_TAGS.has(c.tagName)) { close(); blockEl(c, na); close(); }
  1398. else inline(c, na, false);
  1399. });
  1400. markAt(el, kids.length);
  1401. close();
  1402. return;
  1403. }
  1404. const blk = block('p', []);
  1405. if (!html && el.__mdO != null) blk.o = el.__mdO;
  1406. open(blk);
  1407. children(el, html ? attrsOf(el, at) : at, false);
  1408. close();
  1409. };
  1410. const kids = Array.from(root.childNodes);
  1411. kids.forEach((c, k) => {
  1412. markAt(root, k);
  1413. if (c.nodeType === 1 && BLOCK_TAGS.has(c.tagName)) { close(); blockEl(c, {}); close(); }
  1414. else if (c.nodeType === 3 && !html && c.data === '') { /* nothing */ }
  1415. else if (c.nodeType === 3 && html && !cur && !c.data.trim()) { /* whitespace between blocks */ }
  1416. else inline(c, {}, false);
  1417. });
  1418. markAt(root, kids.length);
  1419. close();
  1420. for (const m of marks) if (m.lin == null || m.lin < 0) m.lin = lin > 0 ? lin - 1 : 0; // after the last item
  1421. const out = doc.map((b) => { delete b.pushed; return b; });
  1422. return html ? out.filter((b) => b.t === 'code' || b.items.some((it) => lenOf(it) > 0)) : out;
  1423. }
  1424. function renderInline(parent, segs) {
  1425. let text = '';
  1426. for (const g of merge(segs)) {
  1427. let host = parent;
  1428. const wrap = (tag) => { const el = document.createElement(tag); host.appendChild(el); host = el; return el; };
  1429. if (g.h) {
  1430. const a = wrap('a');
  1431. a.setAttribute('href', g.h);
  1432. a.setAttribute('title', g.h);
  1433. if (g.a) a.setAttribute('data-auto', '');
  1434. } else if (g.c) wrap('code');
  1435. else {
  1436. if (g.s) wrap('strong');
  1437. if (g.e) wrap('em');
  1438. }
  1439. const parts = g.x.split(NL);
  1440. parts.forEach((p, k) => {
  1441. if (k) host.appendChild(document.createElement('br'));
  1442. if (p) host.appendChild(document.createTextNode(p));
  1443. });
  1444. text += g.x;
  1445. }
  1446. if (text === '' || text.endsWith(NL)) parent.appendChild(document.createElement('br'));
  1447. }
  1448. function renderTable(b) {
  1449. const table = document.createElement('table');
  1450. let body = null;
  1451. for (let r = 0; r * b.cols < b.items.length; r++) {
  1452. const tr = document.createElement('tr');
  1453. for (let k = 0; k < b.cols; k++) {
  1454. const cell = document.createElement(r === 0 ? 'th' : 'td');
  1455. if (b.aligns[k]) cell.setAttribute('data-align', b.aligns[k]);
  1456. renderInline(cell, b.items[r * b.cols + k] || []);
  1457. tr.appendChild(cell);
  1458. }
  1459. if (r === 0) { const head = document.createElement('thead'); head.appendChild(tr); table.appendChild(head); }
  1460. else { if (!body) { body = document.createElement('tbody'); table.appendChild(body); } body.appendChild(tr); }
  1461. }
  1462. return table;
  1463. }
  1464. function renderDoc(doc) {
  1465. const frag = document.createDocumentFragment();
  1466. for (const b of doc) {
  1467. let el;
  1468. if (b.t === 'p') el = document.createElement('p');
  1469. else if (b.t === 'h') el = document.createElement('h' + Math.min(6, b.level));
  1470. else if (b.t === 'code') el = document.createElement('pre');
  1471. else if (b.t === 'table') el = renderTable(b);
  1472. else el = document.createElement(b.t);
  1473. if (b.t === 'ol' && b.start !== 1) el.setAttribute('start', String(b.start));
  1474. if (b.t === 'ul' || b.t === 'ol') {
  1475. for (const it of b.items) { const li = document.createElement('li'); renderInline(li, it); el.appendChild(li); }
  1476. } else if (b.t !== 'table') renderInline(el, b.items[0] || []);
  1477. el.__mdO = b.o;
  1478. frag.appendChild(el);
  1479. }
  1480. return frag;
  1481. }
  1482. // =============================================================================================
  1483. // 6. THE ELEMENT
  1484. // =============================================================================================
  1485. const ICON = {
  1486. link: '<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M10 14a4 4 0 0 0 5.66 0l3-3a4 4 0 0 0-5.66-5.66l-1 1M14 10a4 4 0 0 0-5.66 0l-3 3a4 4 0 0 0 5.66 5.66l1-1"/></svg>',
  1487. ul: '<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M9 6h11M9 12h11M9 18h11"/><circle cx="4.5" cy="6" r="1.2"/><circle cx="4.5" cy="12" r="1.2"/><circle cx="4.5" cy="18" r="1.2"/></svg>',
  1488. ol: '<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M10 6h10M10 12h10M10 18h10M4 4.5h1.5V9M3.5 9h3M3.5 14.5c.5-.8 2.8-.9 2.8.6 0 1.1-2.8 2.2-2.8 3.4h3"/></svg>',
  1489. code: '<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M8 7l-5 5 5 5M16 7l5 5-5 5"/></svg>',
  1490. block: '<svg viewBox="0 0 24 24" aria-hidden="true"><rect x="3" y="4" width="18" height="16" rx="2"/><path d="M8 10l-2 2 2 2M16 10l2 2-2 2"/></svg>',
  1491. undo: '<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M9 14L4 9l5-5"/><path d="M4 9h10a6 6 0 0 1 0 12h-3"/></svg>',
  1492. redo: '<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M15 14l5-5-5-5"/><path d="M20 9H10a6 6 0 0 0 0 12h3"/></svg>',
  1493. };
  1494. const MAC = /Mac|iPhone|iPad/.test(navigator.platform || navigator.userAgent || '');
  1495. const MOD = MAC ? 'Cmd' : 'Ctrl';
  1496. const TOOLS = [
  1497. { id: 'bold', label: '<b>B</b>', title: `Bold (${MOD}+B)` },
  1498. { id: 'italic', label: '<i>I</i>', title: `Italic (${MOD}+I)` },
  1499. { id: 'code', label: ICON.code, title: `Code (${MOD}+E)` },
  1500. { id: 'link', label: ICON.link, title: `Link (${MOD}+K)` },
  1501. { id: 'heading', label: 'H', title: `Heading: paragraph → H1 → H2 → H3 (${MOD}+Alt+1/2/3, ${MOD}+Alt+0)` },
  1502. { id: 'ul', label: ICON.ul, title: `Bulleted list (${MOD}+Shift+8)` },
  1503. { id: 'ol', label: ICON.ol, title: `Numbered list (${MOD}+Shift+7)` },
  1504. { id: 'codeblock', label: ICON.block, title: `Code block (${MOD}+Alt+C)` },
  1505. { id: 'undo', label: ICON.undo, title: `Undo (${MOD}+Z)` },
  1506. { id: 'redo', label: ICON.redo, title: `Redo (${MOD}+Shift+Z)` },
  1507. ];
  1508. const CSS = `
  1509. :host {
  1510. --_bg: var(--md-background, Field);
  1511. --_text: var(--md-text, FieldText);
  1512. --_strong: var(--md-text-strong, var(--_text));
  1513. --_muted: var(--md-text-muted, GrayText);
  1514. --_border: var(--md-border, GrayText);
  1515. --_accent: var(--md-accent, Highlight);
  1516. --_accent-text: var(--md-accent-text, HighlightText);
  1517. --_link: var(--md-link, var(--_accent));
  1518. --_code-bg: var(--md-code-background, rgba(127, 127, 127, .18));
  1519. --_table-border: var(--md-table-border, rgba(127, 127, 127, .55));
  1520. --_toolbar-bg: var(--md-toolbar-background, transparent);
  1521. --_danger: var(--md-danger, #f44747);
  1522. --_radius: var(--md-radius, .4rem);
  1523. --_mono: var(--md-mono-font, ui-monospace, SFMono-Regular, Menlo, Consolas, monospace);
  1524. display: block;
  1525. position: relative;
  1526. min-width: 0;
  1527. max-width: 100%;
  1528. font: var(--md-font, inherit);
  1529. color: var(--_text);
  1530. text-align: start;
  1531. }
  1532. :host([hidden]) { display: none; }
  1533. * { box-sizing: border-box; }
  1534. .box { display: flex; flex-direction: column; min-width: 0; background: var(--_bg); border: 1px solid var(--_border); border-radius: var(--_radius); }
  1535. :host(:focus-within) .box { outline: 2px solid var(--_accent); outline-offset: 1px; }
  1536. :host([invalid]) .box { border-color: var(--_danger); outline-color: var(--_danger); }
  1537. [part~="toolbar"] { display: flex; flex-wrap: wrap; gap: 1px; padding: 3px; background: var(--_toolbar-bg); border-bottom: 1px solid var(--_border); border-radius: var(--_radius) var(--_radius) 0 0; }
  1538. :host([toolbar="none"]) [part~="toolbar"] { display: none; }
  1539. [part~="toolbar"][hidden] { display: none; }
  1540. [part~="button"] { display: inline-flex; align-items: center; justify-content: center; min-width: 2rem; height: 2.1rem; padding: 0 .3rem; font: 600 .95rem/1 system-ui, sans-serif; color: var(--_text); background: transparent; border: 1px solid transparent; border-radius: calc(var(--_radius) * .8); cursor: pointer; }
  1541. [part~="button"]:hover { border-color: var(--_border); }
  1542. [part~="button"]:focus-visible { outline: 2px solid var(--_accent); outline-offset: -1px; }
  1543. [part~="button"][aria-pressed="true"] { color: var(--_accent-text); background: var(--_accent); }
  1544. [part~="button"]:disabled { opacity: .45; cursor: default; }
  1545. [part~="button"] svg { width: 1.15rem; height: 1.15rem; fill: none; stroke: currentColor; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; }
  1546. [part~="button"] svg circle { fill: currentColor; stroke: none; }
  1547. [part~="editor"] { min-height: var(--md-min-height, 6rem); padding: .5rem .7rem; outline: none; color: var(--_strong); white-space: pre-wrap; overflow-wrap: anywhere; word-break: normal; line-height: 1.5; cursor: text; }
  1548. [part~="editor"][hidden] { display: none; }
  1549. [part~="editor"] > :first-child { margin-top: 0; }
  1550. [part~="editor"] > :last-child { margin-bottom: 0; }
  1551. [part~="editor"] p { margin: 0 0 .5rem; }
  1552. [part~="editor"] h1, [part~="editor"] h2, [part~="editor"] h3, [part~="editor"] h4, [part~="editor"] h5, [part~="editor"] h6 { margin: .6rem 0 .35rem; line-height: 1.3; color: var(--_strong); }
  1553. [part~="editor"] h1 { font-size: var(--md-h1-size, 1.3em); }
  1554. [part~="editor"] h2 { font-size: var(--md-h2-size, 1.15em); }
  1555. [part~="editor"] h3, [part~="editor"] h4, [part~="editor"] h5, [part~="editor"] h6 { font-size: var(--md-h3-size, 1.02em); }
  1556. [part~="editor"] ul, [part~="editor"] ol { margin: 0 0 .5rem; padding-left: 1.4rem; }
  1557. [part~="editor"] ul { list-style-type: disc; }
  1558. [part~="editor"] ol { list-style-type: decimal; }
  1559. [part~="editor"] li + li { margin-top: .15rem; }
  1560. [part~="editor"] code { font: .88em/1.4 var(--_mono); padding: .05em .3em; background: var(--_code-bg); border-radius: .25rem; }
  1561. [part~="editor"] pre { margin: 0 0 .5rem; padding: .5rem .65rem; font: .88em/1.45 var(--_mono); white-space: pre-wrap; background: var(--_code-bg); border-radius: calc(var(--_radius) * .8); }
  1562. [part~="editor"] a { color: var(--_link); text-decoration: underline; text-underline-offset: .15em; }
  1563. [part~="editor"] strong { font-weight: 700; }
  1564. [part~="editor"] table { display: block; max-width: 100%; overflow-x: auto; margin: 0 0 .5rem; border-collapse: collapse; }
  1565. [part~="editor"] th, [part~="editor"] td { padding: .3rem .6rem; border: 1px solid var(--_table-border); text-align: start; vertical-align: top; min-width: 2.5rem; overflow-wrap: normal; word-break: normal; }
  1566. [part~="editor"] th { font-weight: 700; color: var(--_strong); }
  1567. [part~="editor"] [data-align="left"] { text-align: left; }
  1568. [part~="editor"] [data-align="center"] { text-align: center; }
  1569. [part~="editor"] [data-align="right"] { text-align: right; }
  1570. [part~="editor"] { position: relative; }
  1571. [part~="editor"].empty::before { content: attr(data-placeholder); position: absolute; left: .7rem; top: .5rem; right: .7rem; color: var(--_muted); pointer-events: none; }
  1572. [part~="link-form"] { display: flex; flex-wrap: wrap; align-items: center; gap: .35rem; padding: .4rem; border-top: 1px solid var(--_border); }
  1573. [part~="link-form"][hidden] { display: none; }
  1574. [part~="link-form"] input { flex: 1 1 12rem; min-width: 0; font: inherit; padding: .35rem .5rem; color: var(--_strong); background: transparent; border: 1px solid var(--_border); border-radius: calc(var(--_radius) * .8); }
  1575. [part~="link-form"] button { font: 600 .9rem/1 system-ui, sans-serif; padding: .45rem .7rem; color: var(--_text); background: transparent; border: 1px solid var(--_border); border-radius: calc(var(--_radius) * .8); cursor: pointer; }
  1576. [part~="link-form"] button.primary { color: var(--_accent-text); background: var(--_accent); border-color: var(--_accent); }
  1577. .linkmsg { flex-basis: 100%; margin: 0; font-size: .85rem; color: var(--_danger); }
  1578. .linkmsg:empty { display: none; }
  1579. [part~="source"] { display: block; box-sizing: border-box; width: 100%; min-height: var(--md-min-height, 6rem); margin: 0; padding: .5rem .7rem; font: .92em/1.5 var(--_mono); color: var(--_strong); background: transparent; border: 0; outline: none; resize: vertical; }
  1580. [part~="source"][hidden] { display: none; }
  1581. [part~="footer"] { display: flex; justify-content: flex-end; padding: .25rem .4rem; border-top: 1px solid var(--_border); }
  1582. :host([toolbar="none"]) [part~="footer"] { display: none; }
  1583. [part~="footer"] [part~="button"] { min-width: 0; height: auto; padding: .3rem .6rem; font: 600 .8rem/1 system-ui, sans-serif; color: var(--_muted); }
  1584. [part~="footer"] [part~="button"]:hover { color: var(--_text); }
  1585. [part~="footer"] [part~="button"][aria-pressed="true"] { color: var(--_accent-text); background: var(--_accent); }
  1586. .keep { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; opacity: 0; pointer-events: none; }
  1587. `;
  1588. const TEXTAREA_VALUE = Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, 'value');
  1589. const shadowSelectionOk = typeof ShadowRoot !== 'undefined' && 'getSelection' in ShadowRoot.prototype;
  1590. class MdEditor extends HTMLElement {
  1591. static get formAssociated() { return true; }
  1592. static get observedAttributes() { return ['placeholder', 'disabled', 'readonly', 'value', 'label']; }
  1593. constructor() {
  1594. super();
  1595. this._internals = this.attachInternals ? this.attachInternals() : null;
  1596. const root = this.attachShadow({ mode: 'open', delegatesFocus: false });
  1597. const style = document.createElement('style');
  1598. style.textContent = CSS;
  1599. const box = document.createElement('div');
  1600. box.className = 'box';
  1601. box.setAttribute('part', 'box');
  1602. // the toolbar (fixed markup of our own — no user text in it)
  1603. const bar = document.createElement('div');
  1604. bar.setAttribute('part', 'toolbar');
  1605. bar.setAttribute('role', 'toolbar');
  1606. bar.setAttribute('aria-label', 'Formatting');
  1607. this._buttons = {};
  1608. TOOLS.forEach((t, k) => {
  1609. const b = document.createElement('button');
  1610. b.type = 'button';
  1611. b.setAttribute('part', 'button ' + t.id);
  1612. b.dataset.tool = t.id;
  1613. b.title = t.title;
  1614. b.setAttribute('aria-label', t.title);
  1615. b.tabIndex = k === 0 ? 0 : -1;
  1616. if (!['link', 'undo', 'redo'].includes(t.id)) b.setAttribute('aria-pressed', 'false');
  1617. b.innerHTML = t.label;
  1618. bar.appendChild(b);
  1619. this._buttons[t.id] = b;
  1620. });
  1621. const ed = document.createElement('div');
  1622. ed.setAttribute('part', 'editor');
  1623. ed.setAttribute('role', 'textbox');
  1624. ed.setAttribute('aria-multiline', 'true');
  1625. ed.contentEditable = 'true';
  1626. ed.spellcheck = true;
  1627. // the link form
  1628. const lf = document.createElement('form');
  1629. lf.setAttribute('part', 'link-form');
  1630. lf.hidden = true;
  1631. lf.noValidate = true;
  1632. const li = document.createElement('input');
  1633. li.type = 'text';
  1634. li.setAttribute('inputmode', 'url');
  1635. li.autocomplete = 'off';
  1636. li.placeholder = 'https://…';
  1637. li.setAttribute('aria-label', 'Link address');
  1638. const mkBtn = (text, cls, type) => { const b = document.createElement('button'); b.type = type || 'button'; b.textContent = text; if (cls) b.className = cls; return b; };
  1639. const lOk = mkBtn('Apply', 'primary', 'submit');
  1640. const lRemove = mkBtn('Remove link');
  1641. const lCancel = mkBtn('Cancel');
  1642. const lMsg = document.createElement('p');
  1643. lMsg.className = 'linkmsg';
  1644. lMsg.setAttribute('role', 'alert');
  1645. lf.append(li, lOk, lRemove, lCancel, lMsg);
  1646. // the plain-text source view (raw Markdown, for copy/paste and direct editing)
  1647. const src = document.createElement('textarea');
  1648. src.setAttribute('part', 'source');
  1649. src.hidden = true;
  1650. src.spellcheck = false;
  1651. src.setAttribute('aria-label', 'Markdown source');
  1652. const footer = document.createElement('div');
  1653. footer.setAttribute('part', 'footer');
  1654. const srcBtn = document.createElement('button');
  1655. srcBtn.type = 'button';
  1656. srcBtn.setAttribute('part', 'button source-toggle');
  1657. srcBtn.setAttribute('aria-pressed', 'false');
  1658. srcBtn.textContent = 'Markdown source';
  1659. footer.appendChild(srcBtn);
  1660. // the enhanced textarea stays in the form, out of sight (a label click reaches it → the editor)
  1661. const keep = document.createElement('div');
  1662. keep.className = 'keep';
  1663. keep.appendChild(document.createElement('slot'));
  1664. box.append(bar, ed, src, lf, footer);
  1665. root.append(style, box, keep);
  1666. this._ed = ed;
  1667. this._bar = bar;
  1668. this._src = src;
  1669. this._srcBtn = srcBtn;
  1670. this._srcMode = false;
  1671. this._lf = lf; this._li = li; this._lRemove = lRemove; this._lMsg = lMsg;
  1672. this._slot = keep.firstChild;
  1673. this._ta = null;
  1674. this._doc = [block('p', [[]])];
  1675. this._orig = prepareOriginal('');
  1676. this._value = '';
  1677. this._undo = [];
  1678. this._redo = [];
  1679. this._lastSnap = null;
  1680. this._lastTypeAt = 0;
  1681. this._pending = null;
  1682. this._saved = null;
  1683. this._focusValue = null;
  1684. this._composing = false;
  1685. this._loaded = false;
  1686. ed.addEventListener('beforeinput', (e) => this._onBeforeInput(e));
  1687. // the editor's own input events stay inside: the page hears ONE input per change, from the
  1688. // textarea (enhance mode) or from <md-editor> itself, after the value is up to date
  1689. ed.addEventListener('input', (e) => { e.stopPropagation(); if (!e.isComposing && !this._composing) this._sync(e.inputType, e.data); });
  1690. ed.addEventListener('beforeinput', (e) => e.stopPropagation());
  1691. ed.addEventListener('compositionstart', () => { this._composing = true; });
  1692. ed.addEventListener('compositionend', (e) => {
  1693. this._composing = false;
  1694. const d = e.data || '';
  1695. setTimeout(() => this._sync(d ? 'insertText' : 'insertCompositionText', d ? d[d.length - 1] : null), 0);
  1696. });
  1697. ed.addEventListener('keydown', (e) => this._onKey(e));
  1698. ed.addEventListener('paste', (e) => this._onPaste(e));
  1699. ed.addEventListener('copy', (e) => this._onCopy(e, false));
  1700. ed.addEventListener('cut', (e) => this._onCopy(e, true));
  1701. ed.addEventListener('drop', (e) => this._onDrop(e));
  1702. ed.addEventListener('dragstart', (e) => e.preventDefault());
  1703. ed.addEventListener('focus', () => { this._focusValue = this.value; });
  1704. ed.addEventListener('blur', () => {
  1705. if (this._focusValue != null && this._focusValue !== this.value) this._fire('change');
  1706. this._focusValue = null;
  1707. });
  1708. // a click in the text must not reach a surrounding <label> (it would focus the hidden
  1709. // textarea and move the caret); Ctrl/Cmd+click opens a link
  1710. ed.addEventListener('click', (e) => {
  1711. e.preventDefault();
  1712. const a = e.target && e.target.closest && e.target.closest('a');
  1713. if (a && (e.ctrlKey || e.metaKey)) { const h = safeHref(a.getAttribute('href')); if (h) window.open(h, '_blank', 'noopener'); }
  1714. });
  1715. bar.addEventListener('mousedown', (e) => { if (e.target.closest('button')) e.preventDefault(); });
  1716. bar.addEventListener('click', (e) => { const b = e.target.closest('button'); if (b) this._tool(b.dataset.tool); });
  1717. bar.addEventListener('keydown', (e) => this._barKey(e));
  1718. lf.addEventListener('submit', (e) => { e.preventDefault(); this._linkApply(); });
  1719. lRemove.addEventListener('click', () => this._linkApply(true));
  1720. lCancel.addEventListener('click', () => this._linkClose());
  1721. lf.addEventListener('keydown', (e) => { if (e.key === 'Escape') { e.preventDefault(); this._linkClose(); } });
  1722. srcBtn.addEventListener('click', () => this._toggleSource());
  1723. src.addEventListener('input', () => {
  1724. this._value = src.value;
  1725. this._dirty = true;
  1726. this.removeAttribute('invalid');
  1727. this._writeOut(true);
  1728. });
  1729. src.addEventListener('focus', () => { this._focusValue = src.value; });
  1730. src.addEventListener('blur', () => {
  1731. if (this._focusValue != null && this._focusValue !== src.value) this._fire('change');
  1732. this._focusValue = null;
  1733. });
  1734. src.addEventListener('keydown', (e) => {
  1735. const mod = MAC ? e.metaKey : e.ctrlKey;
  1736. if (mod && e.key === 'Enter') {
  1737. e.preventDefault();
  1738. const f = this.form || this.closest('form');
  1739. if (f) { if (f.requestSubmit) f.requestSubmit(); else f.submit(); }
  1740. }
  1741. });
  1742. this._slot.addEventListener('slotchange', () => this._adopt());
  1743. this._onSelChange = () => this._selChanged();
  1744. // <md-editor> is form-associated, so a surrounding <label> activates IT: the label's click
  1745. // arrives on the host itself (not from inside) → the caret goes into the editor
  1746. this.addEventListener('click', (e) => { if (e.composedPath()[0] === this) this.focus(); });
  1747. }
  1748. // ---- lifecycle --------------------------------------------------------------------------
  1749. connectedCallback() {
  1750. document.addEventListener('selectionchange', this._onSelChange);
  1751. this._adopt();
  1752. if (!this._loaded && !this._ta) {
  1753. this._loaded = true;
  1754. this._load(this.getAttribute('value') || '', false);
  1755. }
  1756. this._applyAttrs();
  1757. }
  1758. disconnectedCallback() { document.removeEventListener('selectionchange', this._onSelChange); }
  1759. attributeChangedCallback(name, old, v) {
  1760. if (name === 'value' && !this._ta && this._loaded && old !== v && !this._dirty) this._load(v || '', false);
  1761. this._applyAttrs();
  1762. }
  1763. formResetCallback() {
  1764. if (!this._ta) this._load(this.getAttribute('value') || '', true);
  1765. }
  1766. formDisabledCallback(disabled) { this._formDisabled = disabled; this._applyAttrs(); }
  1767. // the textarea child (enhance mode)
  1768. _adopt() {
  1769. const ta = Array.from(this.children).find((c) => c.tagName === 'TEXTAREA') || null;
  1770. if (ta === this._ta) return;
  1771. this._ta = ta;
  1772. if (!ta) return;
  1773. const self = this;
  1774. if (!ta.__mdEditor) {
  1775. Object.defineProperty(ta, 'value', {
  1776. configurable: true,
  1777. get() { return TEXTAREA_VALUE.get.call(this); },
  1778. set(v) { TEXTAREA_VALUE.set.call(this, v); if (this.__mdEditor && !this.__mdEditor._writing) this.__mdEditor._external(TEXTAREA_VALUE.get.call(this)); },
  1779. });
  1780. ta.addEventListener('invalid', (e) => { e.preventDefault(); const m = ta.__mdEditor; if (m) { m.setAttribute('invalid', ''); m.focus(); } });
  1781. ta.addEventListener('focus', () => { const m = ta.__mdEditor; if (m) m.focus(); });
  1782. // a script that writes the value and announces it with an input event
  1783. ta.addEventListener('input', () => { const m = ta.__mdEditor; if (m && !m._writing && TEXTAREA_VALUE.get.call(ta) !== m._value) m._external(TEXTAREA_VALUE.get.call(ta)); });
  1784. }
  1785. ta.__mdEditor = self;
  1786. ta.tabIndex = -1;
  1787. this._loaded = true;
  1788. this._load(TEXTAREA_VALUE.get.call(ta), false);
  1789. this._applyAttrs();
  1790. }
  1791. _applyAttrs() {
  1792. const ta = this._ta;
  1793. const off = this.hasAttribute('disabled') || this.hasAttribute('readonly') || !!this._formDisabled || (ta && (ta.disabled || ta.readOnly));
  1794. this._ed.contentEditable = off ? 'false' : 'true';
  1795. this._ed.setAttribute('aria-disabled', off ? 'true' : 'false');
  1796. for (const b of Object.values(this._buttons)) b.disabled = !!off;
  1797. this._histButtons();
  1798. const hardOff = this.hasAttribute('disabled') || !!this._formDisabled || (ta && ta.disabled);
  1799. this._srcBtn.disabled = !!hardOff;
  1800. this._src.disabled = !!hardOff;
  1801. this._src.readOnly = !!off;
  1802. const ph = this.getAttribute('placeholder') || (ta && ta.getAttribute('placeholder')) || '';
  1803. this._ed.dataset.placeholder = ph;
  1804. this._src.placeholder = ph;
  1805. let label = this.getAttribute('label') || (ta && ta.getAttribute('aria-label')) || '';
  1806. const labels = (this._internals && this._internals.labels && this._internals.labels.length ? this._internals.labels : ta && ta.labels) || [];
  1807. if (!label && labels[0]) label = Array.from(labels[0].childNodes).filter((n) => n.nodeType === 3).map((n) => n.data).join(' ').trim();
  1808. if (label) this._ed.setAttribute('aria-label', label);
  1809. if (ta && ta.required) this._ed.setAttribute('aria-required', 'true');
  1810. const rows = ta ? Number(ta.getAttribute('rows')) : Number(this.getAttribute('rows'));
  1811. if (rows > 0) { this._ed.style.minHeight = `calc(${rows} * 1.5em + 1rem)`; this._src.style.minHeight = this._ed.style.minHeight; }
  1812. }
  1813. // ---- value ------------------------------------------------------------------------------
  1814. get value() { return this._value; }
  1815. set value(v) { this._load(v == null ? '' : String(v), true); this._writeOut(false); }
  1816. focus(opts) {
  1817. this._ed.focus(opts);
  1818. if (!this._rangeLin()) {
  1819. const s = this._saved;
  1820. const n = docLen(this._doc);
  1821. if (s) this._setSel(Math.min(s.a, n), Math.min(s.b, n)); else this._setSel(n, n);
  1822. }
  1823. }
  1824. get form() { return this._ta ? this._ta.form : this._internals ? this._internals.form : null; }
  1825. get name() { return this._ta ? this._ta.name : this.getAttribute('name'); }
  1826. _load(md, keepUndo) {
  1827. const text = md == null ? '' : String(md);
  1828. if (keepUndo && this._lastSnap) this._pushUndo(this._lastSnap);
  1829. this._orig = prepareOriginal(text);
  1830. this._doc = edDoc(clone(this._orig.doc));
  1831. this._value = text;
  1832. this._dirty = false;
  1833. this._pending = null;
  1834. this._render(true);
  1835. if (this._src) this._src.value = text;
  1836. this._lastSnap = this._snap();
  1837. if (!keepUndo) { this._undo = []; this._redo = []; }
  1838. if (this._internals && !this._ta) this._internals.setFormValue(text);
  1839. }
  1840. _external(v) {
  1841. if (v === this._value) return;
  1842. const focused = this._hasFocus();
  1843. this._load(v, true);
  1844. if (focused) this._setSel(docLen(this._doc), docLen(this._doc));
  1845. }
  1846. _commit() {
  1847. const md = serialize(this._doc, this._orig);
  1848. this._dirty = true;
  1849. if (md === this._value) return;
  1850. this._value = md;
  1851. this.removeAttribute('invalid');
  1852. this._writeOut(true);
  1853. }
  1854. _writeOut(announce) {
  1855. if (this._ta) {
  1856. this._writing = true;
  1857. try { TEXTAREA_VALUE.set.call(this._ta, this._value); } finally { this._writing = false; }
  1858. if (announce) this._ta.dispatchEvent(new Event('input', { bubbles: true }));
  1859. } else {
  1860. if (this._internals) this._internals.setFormValue(this._value);
  1861. if (announce) this._fire('input');
  1862. }
  1863. }
  1864. _fire(type) {
  1865. if (this._ta) this._ta.dispatchEvent(new Event(type, { bubbles: true }));
  1866. else this.dispatchEvent(new Event(type, { bubbles: true }));
  1867. }
  1868. // ---- rendering + selection ----------------------------------------------------------------
  1869. _render(force) {
  1870. const frag = renderDoc(this._doc);
  1871. if (!force) {
  1872. const probe = document.createElement('div');
  1873. probe.appendChild(frag.cloneNode(true));
  1874. if (probe.innerHTML === this._ed.innerHTML) {
  1875. // same markup: only hand the blocks their origin again
  1876. Array.from(this._ed.children).forEach((el, k) => { if (this._doc[k]) el.__mdO = this._doc[k].o; });
  1877. this._placeholder();
  1878. return false;
  1879. }
  1880. }
  1881. this._ed.replaceChildren(frag);
  1882. this._placeholder();
  1883. return true;
  1884. }
  1885. _placeholder() {
  1886. const d = this._doc;
  1887. const empty = d.length === 1 && d[0].t === 'p' && lenOf(d[0].items[0]) === 0;
  1888. this._ed.classList.toggle('empty', empty);
  1889. }
  1890. _selection() {
  1891. if (shadowSelectionOk) return this.shadowRoot.getSelection();
  1892. return document.getSelection();
  1893. }
  1894. _hasFocus() { return this.shadowRoot.activeElement === this._ed; }
  1895. _rawRange() {
  1896. const sel = this._selection();
  1897. if (!sel) return null;
  1898. if (!shadowSelectionOk && sel.getComposedRanges) {
  1899. const rs = sel.getComposedRanges({ shadowRoots: [this.shadowRoot] });
  1900. if (!rs.length) return null;
  1901. return { sc: rs[0].startContainer, so: rs[0].startOffset, ec: rs[0].endContainer, eo: rs[0].endOffset };
  1902. }
  1903. if (!sel.rangeCount) return null;
  1904. const r = sel.getRangeAt(0);
  1905. return { sc: r.startContainer, so: r.startOffset, ec: r.endContainer, eo: r.endOffset };
  1906. }
  1907. // the selection as linear model positions { a, b } (read from the current DOM), or null
  1908. _rangeLin(fromDom) {
  1909. const r = this._rawRange();
  1910. if (!r || !this._ed.contains(r.sc) || !this._ed.contains(r.ec)) return null;
  1911. const m1 = { node: r.sc, off: r.so }, m2 = { node: r.ec, off: r.eo };
  1912. const raw = readDom(this._ed, { marks: [m1, m2] });
  1913. const res = { a: Math.min(m1.lin, m2.lin), b: Math.max(m1.lin, m2.lin), doc: raw };
  1914. return fromDom ? res : { a: res.a, b: res.b };
  1915. }
  1916. _point(lin) {
  1917. const p = fromLin(this._doc, lin);
  1918. const bel = this._ed.children[p.b];
  1919. if (!bel) return [this._ed, this._ed.childNodes.length];
  1920. const iel = (bel.tagName === 'UL' || bel.tagName === 'OL') ? bel.children[p.i] || bel : bel.tagName === 'TABLE' ? bel.querySelectorAll('th, td')[p.i] || bel : bel;
  1921. let o = p.o;
  1922. const walker = document.createTreeWalker(iel, NodeFilter.SHOW_TEXT | NodeFilter.SHOW_ELEMENT);
  1923. let n = walker.nextNode();
  1924. let lastBr = null;
  1925. while (n) {
  1926. if (n.nodeType === 3) {
  1927. if (o <= n.data.length) return [n, o];
  1928. o -= n.data.length;
  1929. } else if (n.tagName === 'BR') {
  1930. if (o === 0) return [n.parentNode, Array.prototype.indexOf.call(n.parentNode.childNodes, n)];
  1931. o -= 1;
  1932. lastBr = n;
  1933. }
  1934. n = walker.nextNode();
  1935. }
  1936. if (lastBr && lastBr === iel.lastChild) return [iel, iel.childNodes.length - 1];
  1937. return [iel, iel.childNodes.length];
  1938. }
  1939. _setSel(a, b) {
  1940. const sel = this._selection() || document.getSelection();
  1941. const [n1, o1] = this._point(a);
  1942. const [n2, o2] = this._point(b == null ? a : b);
  1943. try { sel.setBaseAndExtent(n1, o1, n2, o2); } catch (err) { /* detached */ }
  1944. this._saved = { a, b: b == null ? a : b };
  1945. }
  1946. _snap() {
  1947. const r = this._saved || { a: 0, b: 0 };
  1948. return { doc: clone(this._doc), a: r.a, b: r.b };
  1949. }
  1950. _pushUndo(s) {
  1951. this._undo.push(s);
  1952. if (this._undo.length > 200) this._undo.shift();
  1953. this._redo = [];
  1954. }
  1955. // ---- the one path every change takes -----------------------------------------------------
  1956. _apply(doc, a, b) {
  1957. this._doc = edDoc(doc);
  1958. this._render(true);
  1959. const n = docLen(this._doc);
  1960. a = Math.min(Math.max(0, a), n);
  1961. b = b == null ? a : Math.min(Math.max(0, b), n);

Only the first lines are shown.

Branches

Latest commits

  • 04a625edmission 004: re-vendor hybriel a832f73b (native bin + plugins as tickets), compose HL_CACHE_DIR volume + tmpfs /tmp, deploy URL wait 120 s, tests wait 120 s per start; gate 57/0 old and new; real-data same output. Not deployed.mre
  • aefb9d44mission brief w4mre
  • 202098b3docker-compose: init: true (hybriel#156, PID 1 ignored SIGTERM, every restart waited 10 s)mre
  • 304f6a9dnotes mission 003 (#5): report, STATUS, LOGmre
  • 9acc27f8notes mission 003 (#5): GitHub pipe tables in md-editor (parse, render, type, write) + gate checksmre
  • 2149e902notes mission 002 (4/4): code order — README file map + same-output test, STATUS, LOG, report; tests/letcount.py, tests/realdata-baseline.mjs, tests/realdata-compare.pymre
  • 47db4fc1notes mission 002 (3/4): code order — let only where reassigned (58 dropped; 34 left: 19 reassigned, 15 loop-bound); gates 50/0 + 18/0, live-data run = step 2mre
  • 3f8cb383notes mission 002 (2/4): code order — topics, map, thin wrappers: lib/util.hl, lib/notes(-helpers).hl, lib/users.hl (+userOfLoginCode, tagOf), lib/api(-helpers).hl; project.hl = map; login routes take &req/&sessions (failed-login reason now kept); dead notes#1 functions removed; gates 50/0 + 18/0mre
  • 8cda5412notes mission 002 (1/4): code order — files moved: lib/notes.hl, lib/users.hl, lib/jsoncheck.hl, components/styles.hl (imports only); gates 50/0 + 18/0, live-data run identicalmre
  • 47dad68bnotes: Hybriel master 06617221 (plugin allocators 3a781359 + 413f60e4, mpackdb 2cb7ae5e, http1 773de63e); gates 50/0 + 18/0mre
  • a4a2b2aeantcolony#40: tracker missions moved too — references to them in missions/reports/LOG.md updatedmre
  • 3dea0ef2notes: Hybriel master 190aa11d (fc838894 GC correctness, #126 closure scopes, #127); gate 50/0mre
  • e27c7d71notes: Hybriel master 8efba065 (#126 GC by bytes, #48 lambda params copy; audit: nothing to fix; gate 50/0)mre
  • 124613b6antcolony#40: mission references point to the moved missionsmre
  • 1ca2f34dantcolony#40: history (LOG.md), worker briefs (missions/) and reports moved here from antcolony, numbered per project; old numbers in antcolony docs/mission-map.mdmre
  • 2bebebdanotes: Hybriel master ff51cf46 (re-vendor round)mre
  • 3eff126dnotes#3: installable app (manifest + own icon/favicon; notes' own sw.js kept)mre
  • 9883c540deploy.sh: back up live storage/.sessions/.env before every deploy (newest 5 kept)mre
  • eee693b8deploy.sh: never send .git or .gitignore to Byrodinmre
  • c8904061State of 2026-09-27, before the move to gitoriamre