slop-editor 0.5.1 → 0.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/slop.js CHANGED
@@ -111,64 +111,185 @@ const Slop = (() => {
111
111
  // the text as it reads: runs of one author's words (`by`: the category) with their formatting (b, i, code, key)
112
112
  // and the link they sit in, if any. A {name} is a run of its own with `v` set. Code is a fact: whoever wrote it,
113
113
  // a command or a file name reads as data
114
- function runs(value) {
114
+ // Each run also has `at`, where each of its characters is in the plain text (a {name}: where it starts, and `len`).
115
+ // `marks` are the markup's characters, [start, length, the mark it pairs with], for editing the words as they read
116
+ function parse(value) {
115
117
  const text = plain(value);
116
118
  const authors = authorsByChar(value);
117
119
  const out = [];
120
+ const marks = [];
118
121
  const st = { b: false, i: false, code: false, key: false, link: null };
122
+ const opened = {}; // the mark that turned each one on
119
123
  let linkEnd = -1;
120
124
  let linkTail = 0;
121
- const push = (s, by, v) => {
122
- const run = { text: s, by: st.code ? 'data' : by, link: st.link, b: st.b, i: st.i, code: st.code, key: st.key, v };
125
+ const push = (s, by, src, v, len) => {
126
+ const run = { text: s, by: st.code ? 'data' : by, link: st.link, b: st.b, i: st.i, code: st.code, key: st.key, v, at: [src], len };
123
127
  const last = out[out.length - 1];
124
- if (last && !last.v && !v && same(last, run)) last.text += s;
125
- else out.push(run);
128
+ if (last && !last.v && !v && same(last, run)) { last.text += s; last.at.push(src); } else out.push(run);
129
+ };
130
+ const mark = (kind, start, length) => {
131
+ const m = [start, length, null];
132
+ if (opened[kind]) { m[2] = opened[kind]; opened[kind][2] = m; opened[kind] = null; } else opened[kind] = m;
133
+ marks.push(m);
126
134
  };
127
135
  for (let i = 0; i < text.length;) {
128
136
  const c = text[i];
129
- if (i === linkEnd) { st.link = null; i += linkTail; linkEnd = -1; continue; }
130
- if (c === '\\' && i + 1 < text.length) { push(text[i + 1], authors[i + 1]); i += 2; continue; }
131
- if (c === '[' && text[i + 1] === '[' && !st.key) { st.key = true; i += 2; continue; }
132
- if (c === ']' && text[i + 1] === ']' && st.key) { st.key = false; i += 2; continue; }
137
+ if (i === linkEnd) { st.link = null; mark('link', i, linkTail); i += linkTail; linkEnd = -1; continue; }
138
+ if (c === '\\' && i + 1 < text.length) { marks.push([i, 1, null]); push(text[i + 1], authors[i + 1], i + 1); i += 2; continue; }
139
+ if (c === '[' && text[i + 1] === '[' && !st.key) { st.key = true; mark('key', i, 2); i += 2; continue; }
140
+ if (c === ']' && text[i + 1] === ']' && st.key) { st.key = false; mark('key', i, 2); i += 2; continue; }
133
141
  if (c === '[' && !st.link) {
134
142
  LINK.lastIndex = i;
135
143
  const m = LINK.exec(text);
136
- if (m) { st.link = { href: m[2] }; linkEnd = i + 1 + m[1].length; linkTail = m[0].length - m[1].length - 1; i++; continue; }
144
+ if (m) { st.link = { href: m[2] }; mark('link', i, 1); linkEnd = i + 1 + m[1].length; linkTail = m[0].length - m[1].length - 1; i++; continue; }
137
145
  }
138
- if (c === '`') { st.code = !st.code; i++; continue; }
146
+ if (c === '`') { st.code = !st.code; mark('code', i, 1); i++; continue; }
139
147
  if (c === '*' && !st.code) {
140
- if (text[i + 1] === '*') { st.b = !st.b; i += 2; } else { st.i = !st.i; i++; }
148
+ if (text[i + 1] === '*') { st.b = !st.b; mark('b', i, 2); i += 2; } else { st.i = !st.i; mark('i', i, 1); i++; }
141
149
  continue;
142
150
  }
143
151
  if (c === '{') {
144
152
  VAR.lastIndex = i;
145
153
  const m = VAR.exec(text);
146
- if (m) { push('', authors[i], m[1]); i += m[0].length; continue; }
154
+ if (m) { push('', authors[i], i, m[1], m[0].length); i += m[0].length; continue; }
147
155
  }
148
- push(c, authors[i]);
156
+ push(c, authors[i], i);
149
157
  i++;
150
158
  }
151
- return out;
159
+ return { runs: out, marks };
160
+ }
161
+ const runs = (value) => parse(value).runs;
162
+
163
+ // the words as they read, one character each, with where each is in the plain text. A {name} reads as one
164
+ // character, OBJ, as the editor shows it: one block that can't be typed into
165
+ const OBJ = '';
166
+ function readOf(value) {
167
+ let words = '';
168
+ const at = [];
169
+ const len = [];
170
+ runs(value).forEach((run) => {
171
+ if (run.v) { words += OBJ; at.push(run.at[0]); len.push(run.len); return; }
172
+ words += run.text;
173
+ run.at.forEach((i) => { at.push(i); len.push(1); });
174
+ });
175
+ return { words, at, len };
176
+ }
177
+ // `value` after the words as they read, from `start` to `end`, were replaced with `typed` (typed by me): letters
178
+ // typed are escaped, the markup around and inside the stretch stays, and markup left with nothing in it goes
179
+ function editRead(value, start, end, typed, by = 'me') {
180
+ const text = plain(value);
181
+ const authors = authorsByChar(value);
182
+ const { at, len } = readOf(value);
183
+ const { marks } = parse(value);
184
+ const gone = new Set();
185
+ for (let k = start; k < end; k++) for (let n = 0; n < len[k]; n++) gone.add(at[k] + n);
186
+ // an escaped letter takes its backslash with it
187
+ marks.forEach(([s, l, pair]) => { if (l === 1 && !pair && text[s] === '\\' && gone.has(s + 1)) gone.add(s); });
188
+ // where the typing goes: after the letter before it, so it takes that letter's bold, link or code
189
+ const to = start > 0 ? at[start - 1] + len[start - 1] : 0;
190
+ const escaped = typed.replace(/[\\*`[\]{]/g, '\\$&');
191
+ // marks whose pair now holds nothing go too
192
+ const markup = new Set(marks.flatMap(([s, l]) => [...Array(l).keys()].map((n) => s + n)));
193
+ const holds = (from, until) => {
194
+ for (let i = from; i < until; i++) if (!gone.has(i) && !markup.has(i)) return true;
195
+ return Boolean(escaped) && to >= from && to <= until;
196
+ };
197
+ marks.forEach(([s, l, pair]) => {
198
+ if (!pair || s > pair[0] || holds(s + l, pair[0])) return;
199
+ for (let n = 0; n < l; n++) gone.add(s + n);
200
+ for (let n = 0; n < pair[1]; n++) gone.add(pair[0] + n);
201
+ });
202
+ let next = '';
203
+ const who = [];
204
+ for (let i = 0; i <= text.length; i++) {
205
+ if (i === to) { next += escaped; who.push(...new Array(escaped.length).fill(by)); }
206
+ if (i < text.length && !gone.has(i)) { next += text[i]; who.push(authors[i]); }
207
+ }
208
+ return fromChars(next, who);
209
+ }
210
+ // `value` with the words as they read, from `start` to `end`, made bold, italic or code (`b`, `i`, `code`: on unless
211
+ // they all are already, then off) or a link (`link`: {href}, or null for none). The text's markup is written again,
212
+ // as few marks as it takes; every letter and {name} keeps its author, and a mark takes the author of the letter
213
+ // after it (the one before, at the end)
214
+ function restyle(value, start, end, how) {
215
+ const text = plain(value);
216
+ const authors = authorsByChar(value);
217
+ const chars = [];
218
+ runs(value).forEach((run) => {
219
+ const style = { b: run.b, i: run.i, code: run.code, key: run.key, link: run.link };
220
+ if (run.v) chars.push({ ...style, v: text.slice(run.at[0], run.at[0] + run.len), by: authors[run.at[0]] });
221
+ else for (let k = 0; k < run.text.length; k++) chars.push({ ...style, c: run.text[k], by: authors[run.at[k]] });
222
+ });
223
+ const [key, to] = Object.entries(how)[0];
224
+ const picked = chars.slice(start, end);
225
+ const on = key === 'link' ? to : !picked.filter((c) => !c.v).every((c) => c[key]);
226
+ picked.forEach((c) => { c[key] = on; });
227
+ let out = '';
228
+ const who = [];
229
+ const put = (str, by) => { out += str; who.push(...new Array(str.length).fill(by)); };
230
+ const now = { b: false, i: false, code: false, key: false, link: null };
231
+ // marks are toggles, so their order only matters for brackets: a [[key]] opens before a [link] in it
232
+ const shift = (want, by) => {
233
+ if (now.link && now.link !== want.link) { put(`](${now.link.href})`, by); now.link = null; }
234
+ if (now.code && !want.code) { put('`', by); now.code = false; }
235
+ if (now.key && !want.key) { put(']]', by); now.key = false; }
236
+ if (!now.code && !want.code) {
237
+ if (now.b !== want.b) { put('**', by); now.b = want.b; }
238
+ if (now.i !== want.i) { put('*', by); now.i = want.i; }
239
+ }
240
+ if (want.key && !now.key) { put('[[', by); now.key = true; }
241
+ if (want.link && !now.link) { put('[', by); now.link = want.link; }
242
+ if (want.code && !now.code) {
243
+ if (now.b !== want.b) { put('**', by); now.b = want.b; }
244
+ if (now.i !== want.i) { put('*', by); now.i = want.i; }
245
+ put('`', by);
246
+ now.code = true;
247
+ }
248
+ };
249
+ chars.forEach((c) => {
250
+ shift(c, c.by);
251
+ if (c.v) put(c.v, c.by);
252
+ else put(/[\\*`[\]{]/.test(c.c) ? `\\${c.c}` : c.c, c.by);
253
+ });
254
+ shift({ b: false, i: false, code: false, key: false, link: null }, chars.at(-1)?.by ?? 'ai');
255
+ return fromChars(out, who);
256
+ }
257
+ // where a stretch of the words as they read is in the plain text: [start, end)
258
+ function readSpan(value, start, end) {
259
+ const { at, len } = readOf(value);
260
+ const text = plain(value);
261
+ if (start >= end) { const i = start > 0 ? at[start - 1] + len[start - 1] : 0; return [i, i]; }
262
+ return [at[start] ?? text.length, end > 0 ? at[end - 1] + len[end - 1] : 0];
152
263
  }
153
264
 
154
265
  // a text in paragraphs: split at blank lines, each keeping its authors. Without a blank line it's one paragraph
155
- function paragraphsOf(value) {
266
+ // where each paragraph is in the plain text: [[start, end)]. Empty ones are left out unless `empty` (an editor
267
+ // where a new paragraph is typed into)
268
+ function paragraphSpans(value, empty) {
156
269
  const text = plain(value);
157
- const authors = authorsByChar(value);
158
270
  const spans = [];
159
- const gap = /\n[ \t]*\n\s*/g;
271
+ const gap = /\n[ \t]*\n(?:[ \t]*\n)*/g; // more blank lines too, but not the spaces a paragraph starts with
160
272
  let at = 0;
161
273
  for (let m; (m = gap.exec(text));) { spans.push([at, m.index]); at = m.index + m[0].length; }
162
- if (!spans.length) return [value];
163
274
  spans.push([at, text.length]);
164
- const parts = spans.map(([s, e]) => fromChars(text.slice(s, e), authors.slice(s, e))).filter((p) => plain(p).trim());
165
- return parts.length ? parts : [value];
275
+ const kept = empty ? spans : spans.filter(([s, e]) => text.slice(s, e).trim());
276
+ return spans.length > 1 && kept.length ? kept : [[0, text.length]];
277
+ }
278
+ const slice = (value, s, e) => fromChars(plain(value).slice(s, e), authorsByChar(value).slice(s, e));
279
+ function paragraphsOf(value) {
280
+ const spans = paragraphSpans(value);
281
+ return spans.length > 1 ? spans.map(([s, e]) => slice(value, s, e)) : [value];
166
282
  }
283
+ // `value` with plain characters start to end replaced by `part` (a value), each keeping its author
284
+ const splice = (value, s, e, part) => fromChars(plain(value).slice(0, s) + plain(part) + plain(value).slice(e),
285
+ [...authorsByChar(value).slice(0, s), ...authorsByChar(part), ...authorsByChar(value).slice(e)]);
167
286
 
168
287
  // values the page fills in: {html, data} (data: a fact, shown in the data color; otherwise it takes the color of
169
288
  // whoever wrote the {name}), or a plain string or number (a fact)
170
289
  const vars = {};
171
290
  const config = { code: 'code' };
291
+ // while the words are edited on the page, a {name} is one block that can't be typed into
292
+ const live = { on: false };
172
293
  // where the browser editor keeps this page's copy: its path, or the page's own name for it (Slop.start({key}))
173
294
  const pageKey = () => config.key ?? location.pathname;
174
295
  const esc = (s) => String(s).replace(/[&<>"]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' })[c]);
@@ -186,6 +307,7 @@ const Slop = (() => {
186
307
 
187
308
  // the text as HTML: each author's words in a span (slop-ai, slop-me, slop-ok, slop-data, …), links open in a new tab
188
309
  function render(value, local) {
310
+ const all = runs(value);
189
311
  const one = (run) => {
190
312
  let h;
191
313
  let by = run.by;
@@ -193,8 +315,18 @@ const Slop = (() => {
193
315
  const v = lookup(run.v, local);
194
316
  h = v.html;
195
317
  if (v.data) by = 'data';
196
- } else h = esc(run.text).replace(/\n/g, '<br>');
197
- h = `<span class="${cls(by)}">${h}</span>`;
318
+ } else h = esc(run.text);
319
+ // spaces at either end of a line, or after another space, would collapse: the browser would drop one when
320
+ // you type next to it, and the caret couldn't go after one just typed. While editing they're drawn so they don't
321
+ if (live.on && !run.v) {
322
+ const i = all.indexOf(run);
323
+ const nb = (m) => '&nbsp;'.repeat(m.length);
324
+ h = h.replace(/ +(?=\n)/g, nb).replace(/(?<=\n) +/g, nb).replace(/ {2,}/g, (m) => `${nb(m.slice(1))} `);
325
+ if (i === all.length - 1 || all[i + 1].text?.startsWith('\n')) h = h.replace(/ +$/, nb);
326
+ if (i === 0 || /[\n ]$/.test(all[i - 1].text ?? '')) h = h.replace(/^ +/, nb);
327
+ }
328
+ if (!run.v) h = h.replace(/\n/g, '<br>');
329
+ h = `<span class="${cls(by)}"${run.v && live.on ? ' contenteditable="false" data-slop-v=""' : ''}>${h}</span>`;
198
330
  if (run.key) h = `<kbd>${h}</kbd>`;
199
331
  if (run.code) h = `<span class="${config.code}">${h}</span>`;
200
332
  if (run.i) h = `<em>${h}</em>`;
@@ -202,7 +334,7 @@ const Slop = (() => {
202
334
  return h;
203
335
  };
204
336
  const parts = [];
205
- runs(value).forEach((run) => {
337
+ all.forEach((run) => {
206
338
  const last = parts[parts.length - 1];
207
339
  if (!run.link) parts.push(run);
208
340
  else if (last?.link === run.link) last.runs.push(run);
@@ -312,7 +444,7 @@ const Slop = (() => {
312
444
  return out;
313
445
  }
314
446
 
315
- const core = { BUILTIN, plain, applyEdit, reslop, unslop, assign, overlay, reattribute, runs, readable, render, makeup, share, percent, repeats, rebase, listsIn, wordsOf, paragraphsOf, vars };
447
+ const core = { BUILTIN, plain, applyEdit, readOf, editRead, readSpan, restyle, paragraphSpans, splice, reslop, unslop, assign, overlay, reattribute, runs, readable, render, makeup, share, percent, repeats, rebase, listsIn, wordsOf, paragraphsOf, vars };
316
448
  if (typeof document === 'undefined') return core; // Node (the CLI and the tests) only needs the format
317
449
 
318
450
  /* ---------- the block ---------- */
@@ -393,13 +525,17 @@ const Slop = (() => {
393
525
  const SPLITS = /^(P|LI|DD)$/;
394
526
  const spills = new WeakMap(); // element → the copies after it
395
527
  const ownerOf = new WeakMap(); // copy → its element
528
+ // what the browser gives back as an element's innerHTML once it's set to h (a " in the words comes back bare, not
529
+ // as &quot;): compared with that, an element that already shows its text isn't written again, and keeps the caret
530
+ let shape = null;
531
+ const asSet = (h) => { shape ??= document.createElement('template'); shape.innerHTML = h; return shape.innerHTML; };
396
532
  function fillOne(el) {
397
533
  const local = el.dataset.slopVars ? JSON.parse(el.dataset.slopVars) : undefined;
398
534
  if (el.dataset.slop) {
399
535
  const value = get(el.dataset.slop);
400
- const parts = SPLITS.test(el.tagName) ? paragraphsOf(value) : [value];
536
+ const parts = !SPLITS.test(el.tagName) ? [value] : live.on ? paragraphSpans(value, true).map(([s, e]) => slice(value, s, e)) : paragraphsOf(value);
401
537
  const h = render(parts[0], local);
402
- if (el.innerHTML !== h) el.innerHTML = h;
538
+ if (el.innerHTML !== asSet(h)) el.innerHTML = h;
403
539
  el.classList.toggle('slop-empty', !plain(value).trim());
404
540
  spill(el, parts.slice(1).map((v) => render(v, local)));
405
541
  }
@@ -415,13 +551,13 @@ const Slop = (() => {
415
551
  let c = copies[i];
416
552
  if (!c) {
417
553
  c = el.cloneNode(false);
418
- ['id', 'data-slop', 'data-slop-attr'].forEach((a) => c.removeAttribute(a));
554
+ ['id', 'data-slop', 'data-slop-attr', 'contenteditable'].forEach((a) => c.removeAttribute(a));
419
555
  c.classList.remove('slop-focus', 'slop-copy', 'slop-empty');
420
556
  ownerOf.set(c, el);
421
557
  copies.push(c);
422
558
  }
423
559
  c.dataset.slopMore = el.dataset.slop;
424
- if (c.innerHTML !== h) c.innerHTML = h;
560
+ if (c.innerHTML !== asSet(h)) c.innerHTML = h;
425
561
  const before = i ? copies[i - 1] : el;
426
562
  if (before.nextElementSibling !== c) before.after(c);
427
563
  });
@@ -462,7 +598,7 @@ const Slop = (() => {
462
598
  const first = [...box.children].find(ours);
463
599
  if (!first) return;
464
600
  const t = first.cloneNode(false);
465
- ['id', 'data-slop'].forEach((a) => t.removeAttribute(a));
601
+ ['id', 'data-slop', 'contenteditable'].forEach((a) => t.removeAttribute(a));
466
602
  templates.set(box, t);
467
603
  }
468
604
  const paths = textKeys(nodeAt(text, at)).filter(isParagraph).map((k) => `${at}.${k}`);
@@ -758,17 +894,14 @@ const Slop = (() => {
758
894
  const state = { tab: startTab(), open: new Set(groupKeys().slice(0, 1)), known: new Set(groupKeys()), focus: null };
759
895
  let sets = repeats(entries());
760
896
  let controls = []; // [{el, paths}] in the current view, repainted by numbers()
761
- let undo = null;
762
897
 
763
- const btn = el('button', 'slop-edit-btn', 'Edit text');
764
- btn.type = 'button';
765
898
  const aside = el('aside', 'slop-panel', `
766
899
  <header class="sp-head" title="Drag to move, or drag an edge to resize. Double-click to put it back">
767
900
  <span class="sp-grip" aria-hidden="true"></span>
768
901
  <div><h2>Edit text</h2><p class="sp-status" role="status" aria-live="polite"></p></div>
902
+ <button type="button" class="sp-mode"></button>
769
903
  <button type="button" class="sp-colors" role="switch" title="Slop-o-meter: color the page's words by who wrote them. Only for you, while you edit"><span class="sp-switch" aria-hidden="true"></span>Colors</button>
770
904
  <button type="button" class="sp-save" title="Save (⌘S)" disabled>Saved</button>
771
- <button type="button" class="sp-close" aria-label="Close the editor">×</button>
772
905
  </header>
773
906
  <div class="sp-cover">
774
907
  <div class="sp-cats"></div>
@@ -788,11 +921,12 @@ const Slop = (() => {
788
921
  ${['n', 's', 'e', 'w', 'ne', 'nw', 'se', 'sw'].map((e) => `<div class="sp-edge" data-edge="${e}" aria-hidden="true"></div>`).join('')}`);
789
922
  aside.hidden = true;
790
923
  aside.setAttribute('aria-label', 'Edit text');
791
- document.body.append(btn, aside);
924
+ document.body.append(aside);
792
925
  const $ = (sel) => aside.querySelector(sel);
793
926
  const body = $('.sp-body');
794
927
  const statusEl = $('.sp-status');
795
928
  aside.classList.add('slop-on'); // the text boxes keep their colors when the page's are off
929
+ const modeBtn = $('.sp-mode');
796
930
  editSwitch = $('.sp-colors');
797
931
  editSwitch.addEventListener('click', () => { editColors = !editColors; paintShow(); });
798
932
 
@@ -809,44 +943,152 @@ const Slop = (() => {
809
943
  ? status('Saved in this browser', '', { label: 'Reset', run: reset })
810
944
  : status(`Saved · version ${text.version}`));
811
945
 
812
- // any change to who wrote what (the slop switch, marking text, deleting a category) can be undone
813
- function withUndo(what, change) {
814
- const before = JSON.stringify(text);
946
+ /* one history for every change to the words or who wrote them: typing (on the page or in a box), a switch, a
947
+ mark, a revert, a category deleted. ⌘Z undoes the last step wherever the focus is, and ⌘⇧Z does it again. A
948
+ step keeps only the top-level keys it changed, before and after, so undoing it leaves the rest as it is now */
949
+ const undos = []; // [{what, at, typing, typed, order: [keys before, after], keys: {key: [JSON before, after]}}]
950
+ const redos = [];
951
+ let noted = false; // the status line names the last step, with its Undo or Redo
952
+ let lastPush = 0;
953
+ const snap = () => Object.fromEntries(Object.keys(text).filter((k) => k !== 'version').map((k) => [k, JSON.stringify(text[k])]));
954
+ // `at`: the text it was made in, to put the focus back ({path, where: 'page' or 'panel', owner, sel}); `typing`:
955
+ // keystrokes of one kind in one text join the step before them; `typed`: only words changed, nothing to redraw
956
+ function track(change, { what = '', at = null, typing = '', typed = false } = {}) {
957
+ const a = snap();
815
958
  change();
816
- if (JSON.stringify(text) === before) return false;
959
+ const b = snap();
960
+ const keys = [...new Set([...Object.keys(a), ...Object.keys(b)])].filter((k) => a[k] !== b[k]);
961
+ if (!keys.length) return false;
962
+ const now = performance.now();
963
+ const top = undos.at(-1);
964
+ if (typing && !redos.length && top?.typing === typing && top.at?.path === at?.path && now - lastPush < 800) {
965
+ keys.forEach((k) => { if (k in top.keys) top.keys[k][1] = b[k]; else top.keys[k] = [a[k], b[k]]; });
966
+ top.order[1] = Object.keys(b);
967
+ } else {
968
+ undos.push({ what, at, typing, typed, order: [Object.keys(a), Object.keys(b)], keys: Object.fromEntries(keys.map((k) => [k, [a[k], b[k]]])) });
969
+ if (undos.length > 300) undos.shift();
970
+ }
971
+ lastPush = now;
972
+ redos.length = 0;
973
+ return true;
974
+ }
975
+ function note(what, undone) {
976
+ noted = true;
977
+ status(undone ? `Undone: ${what}` : what, '', undone ? { label: 'Redo', run: () => step(false) } : { label: 'Undo', run: () => step(true) });
978
+ }
979
+ // a change made with a button (a switch, a mark, a revert, deleting a category), named in the status line
980
+ function withUndo(what, change, at = null) {
981
+ if (!track(change, { what, at })) return false;
817
982
  touched();
818
983
  if (state.tab === 'slop') render(); else numbers();
819
- undo = before;
820
- status(what, '', {
821
- label: 'Undo',
822
- run: () => {
823
- if (!undo) return;
824
- const version = text.version;
825
- text = JSON.parse(undo);
826
- text.version = version;
827
- undo = null;
828
- applyColors();
829
- touched();
830
- render();
831
- },
984
+ // a mark: the page shows it now, not a frame later, and its words stay selected to mark again
985
+ if (at) { fill(); liven(); putBack(at); }
986
+ note(what, false);
987
+ return true;
988
+ }
989
+ // undo (back) or redo the last step, and put the focus back where it was made
990
+ function step(back) {
991
+ const u = (back ? undos : redos).pop();
992
+ if (!u) return false;
993
+ (back ? redos : undos).push(u);
994
+ lastPush = 0;
995
+ const i = back ? 0 : 1;
996
+ const was = u.at ? valueAt(text, u.at.path) : undefined;
997
+ // the focus stays in a text a step made elsewhere passes over
998
+ const a = document.activeElement;
999
+ const kept = liveOf(a) ? { x: a, sel: selIn(a) } : a?.tagName === 'TEXTAREA' && body.contains(a) ? { path: a.closest('.sp-field')?.dataset.path, sel: [a.selectionStart, a.selectionEnd] } : null;
1000
+ const next = { version: text.version };
1001
+ const order = u.order[i];
1002
+ [...order, ...Object.keys(text).filter((k) => !order.includes(k))].forEach((k) => {
1003
+ if (k === 'version') return;
1004
+ const v = k in u.keys ? u.keys[k][i] : JSON.stringify(text[k]);
1005
+ if (v !== undefined) next[k] = JSON.parse(v);
832
1006
  });
1007
+ text = next;
1008
+ noted = false;
1009
+ if ('_categories' in u.keys) applyColors();
1010
+ fill(); // now, so the caret put back below isn't lost to the next frame's fill
1011
+ liven();
1012
+ if (u.typed) body.querySelectorAll('.sp-field').forEach((f) => { if (f.input) { f.input.value = plain(valueAt(text, f.dataset.path) ?? ''); grow(f.input); } });
1013
+ touched();
1014
+ if (!u.typed) render();
1015
+ if (u.at) putBack(u.at, was);
1016
+ else if (kept?.x?.isConnected) {
1017
+ kept.x.focus({ preventScroll: true });
1018
+ const n = domWords(kept.x).length;
1019
+ if (kept.sel) caret(kept.x, Math.min(kept.sel[0], n), Math.min(kept.sel[1], n));
1020
+ } else if (kept?.path) {
1021
+ const box = boxOf(kept.path)?.input;
1022
+ box?.focus({ preventScroll: true });
1023
+ box?.setSelectionRange(...kept.sel);
1024
+ }
1025
+ if (u.what) note(u.what, back);
833
1026
  return true;
834
1027
  }
1028
+ const boxOf = (path) => [...body.querySelectorAll('.sp-field')].find((f) => f.paths().includes(path));
1029
+ // the caret back in the text a step was made in: on the selection it was made on, or after what came back
1030
+ function putBack({ path, where, owner, sel }, was) {
1031
+ const value = valueAt(text, path);
1032
+ if (value === undefined) return;
1033
+ let [s, e] = sel ?? [];
1034
+ if (!sel) {
1035
+ const x = plain(was ?? '');
1036
+ const y = plain(value);
1037
+ let pre = 0;
1038
+ let end = 0;
1039
+ while (pre < x.length && pre < y.length && x[pre] === y[pre]) pre++;
1040
+ while (end < x.length - pre && end < y.length - pre && x[x.length - 1 - end] === y[y.length - 1 - end]) end++;
1041
+ s = e = y.length - end;
1042
+ }
1043
+ const box = !inPlace && boxOf(path)?.input;
1044
+ const x = owner?.isConnected ? owner : elementsOf(path).find((y) => y.dataset.slop && y.isContentEditable);
1045
+ if (box && (where === 'panel' || !x)) {
1046
+ box.focus();
1047
+ box.setSelectionRange(s, e);
1048
+ return;
1049
+ }
1050
+ if (!x) return;
1051
+ // on the page: the paragraph it's in, and how far into its words
1052
+ const spans = SPLITS.test(x.tagName) ? paragraphSpans(value, true) : [[0, plain(value).length]];
1053
+ const j = Math.max(0, spans.findIndex(([, b]) => s <= b));
1054
+ const y = shownAt(x, j) ?? x;
1055
+ const { at } = readOf(value);
1056
+ const k = (n) => at.filter((m) => m >= spans[j][0] && m < Math.min(n, spans[j][1])).length;
1057
+ if (document.activeElement !== y) y.focus();
1058
+ caret(y, k(s), k(e));
1059
+ paintFloat();
1060
+ }
835
1061
 
836
1062
  /* the slop switch, next to a pie of what the texts are made of. A text's or section's row takes the pie out, to
837
- sit by its name, and puts the switch at the end (c.pie, c.toggle) */
838
- function control(paths, what, after) {
1063
+ sit by its name, and puts the switch at the end (c.pie, c.toggle). Switched back on, a switch takes back only
1064
+ what it approved, where the words are still as it left them, so what was approved before stays approved; with
1065
+ none of that left, it makes every approved word slop again. `id` names the switch, `what` (a string or a
1066
+ function) the texts, and `scope` (a function) says in its tooltip what it covers */
1067
+ const approvals = new Map(); // path → {by, was, now}: the last switch that approved it, and the text before and after
1068
+ function control(paths, what, { after, id = what, scope } = {}) {
839
1069
  const c = el('span', 'sp-ctl', '<span class="sp-pie" role="img"></span>'
840
1070
  + '<button type="button" class="sp-toggle" role="switch"><span class="sp-switch" aria-hidden="true"></span>slop</button>');
841
1071
  const toggle = c.querySelector('.sp-toggle');
842
1072
  toggle.addEventListener('click', (e) => {
843
1073
  e.preventDefault(); // in a section's summary, don't open or close it
844
1074
  const on = toggle.getAttribute('aria-checked') === 'true';
845
- const done = withUndo(on ? `Approved ${what}` : `Back to slop: ${what}`, () => paths().forEach((p) => set(p, on ? unslop(get(p)) : reslop(get(p)))));
1075
+ const ps = paths();
1076
+ const name = typeof what === 'function' ? what() : what;
1077
+ const mine = on ? [] : ps.filter((p) => approvals.get(p)?.by === id && approvals.get(p).now === JSON.stringify(get(p)));
1078
+ const done = withUndo(on ? `Approved ${name}` : `Back to slop: ${name}`, () => ps.forEach((p) => {
1079
+ const was = get(p);
1080
+ if (on) {
1081
+ set(p, unslop(was));
1082
+ if (JSON.stringify(get(p)) !== JSON.stringify(was)) approvals.set(p, { by: id, was, now: JSON.stringify(get(p)) });
1083
+ } else if (!mine.length) set(p, reslop(was));
1084
+ else if (mine.includes(p)) set(p, approvals.get(p).was);
1085
+ }));
846
1086
  if (done) after?.(on);
847
1087
  });
848
1088
  c.pie = c.querySelector('.sp-pie');
849
1089
  c.toggle = toggle;
1090
+ c.paths = paths;
1091
+ c.scope = scope;
850
1092
  controls.push({ el: c, paths });
851
1093
  return c;
852
1094
  }
@@ -860,8 +1102,8 @@ const Slop = (() => {
860
1102
  const on = (m.counts.ai ?? 0) > 0;
861
1103
  toggle.setAttribute('aria-checked', String(on));
862
1104
  toggle.disabled = !on && !m.counts.ok;
863
- toggle.title = on ? 'Slop. Switch it off to approve the AI\'s words as they are'
864
- : m.counts.ok ? 'Approved. Switch it on to make it slop again' : 'No AI-generated words here';
1105
+ toggle.title = (c.scope ? `${c.scope()}: ` : '') + (on ? 'Slop. Switch it off to approve the AI\'s words as they are'
1106
+ : m.counts.ok ? 'Approved. Switch it on to make it slop again' : 'No AI-generated words here');
865
1107
  }
866
1108
 
867
1109
  /* categories: a color picker and a name for each, and how much of the page is theirs */
@@ -1377,23 +1619,64 @@ const Slop = (() => {
1377
1619
  b.type = 'button';
1378
1620
  b.addEventListener('pointerdown', (e) => e.preventDefault()); // keep the focus and the selection
1379
1621
  b.addEventListener('click', () => {
1380
- let [s, e] = [input.selectionStart, input.selectionEnd];
1622
+ let [s, e, n] = selOf(input);
1623
+ const at = markedIn(input, paths[0], [s, e]);
1381
1624
  const whole = s === e;
1382
- if (whole) [s, e] = [0, input.value.length];
1383
- withUndo(`Marked ${whole ? 'the text' : 'the selection'} as ${cat.label}`, () => paths.forEach((p) => set(p, assign(get(p), s, e, cat.id))));
1625
+ if (whole) [s, e] = [0, n];
1626
+ withUndo(`Marked ${whole ? 'the text' : 'the selection'} as ${cat.label}`, () => paths.forEach((p) => set(p, assign(get(p), s, e, cat.id))), at);
1384
1627
  });
1385
1628
  assignEl.append(b);
1386
1629
  });
1630
+ assignEl.append(newCategory(wrap, input, paths));
1387
1631
  assignLabel(input);
1388
1632
  if (wrap.insert) wrap.insert.before(assignEl); else wrap.append(assignEl); // the + stays last
1389
1633
  }
1634
+ // a category made where the words are: its name and whose words it means, and the selection marked as it
1635
+ function newCategory(wrap, input, paths) {
1636
+ const plus = el('button', 'sp-as sp-as-new', '+');
1637
+ plus.type = 'button';
1638
+ plus.title = 'A new category: another author or source';
1639
+ plus.setAttribute('aria-label', 'New category');
1640
+ plus.addEventListener('pointerdown', (e) => e.preventDefault()); // keep the selection until it's read
1641
+ plus.addEventListener('click', () => {
1642
+ const [s, e] = selOf(input);
1643
+ const form = el('span', 'sp-newcat', '<input class="sp-newcat-name" placeholder="Name" aria-label="New category\'s name" spellcheck="false">'
1644
+ + '<input class="sp-newcat-about" placeholder="Whose words are they?" aria-label="Whose words the new category means">'
1645
+ + `<button type="button" class="sp-newcat-add">${s < e ? 'Add and mark' : 'Add'}</button><button type="button" class="sp-newcat-x" aria-label="Cancel">×</button>`);
1646
+ const [name, desc] = form.querySelectorAll('input');
1647
+ plus.replaceWith(form);
1648
+ name.focus();
1649
+ const back = () => { showAssign(wrap, input, paths); input.focus(); if (input.setSelectionRange) input.setSelectionRange(s, e); };
1650
+ const add = () => {
1651
+ const label = name.value.trim();
1652
+ if (!label) { name.focus(); return; }
1653
+ const id = slug(label);
1654
+ const color = PALETTE[categories().filter((c) => !c.builtin).length % PALETTE.length];
1655
+ withUndo(s < e ? `Added "${label}" and marked the selection as it` : `Added "${label}"`, () => {
1656
+ Object.assign(own(id), { label, color }, desc.value.trim() ? { about: desc.value.trim() } : {});
1657
+ if (s < e) paths.forEach((p) => set(p, assign(get(p), s, e, id)));
1658
+ }, markedIn(input, paths[0], [s, e]));
1659
+ applyColors();
1660
+ if (!inPlace) renderCats();
1661
+ back();
1662
+ };
1663
+ name.addEventListener('keydown', (ev) => { if (ev.key === 'Enter') { ev.preventDefault(); desc.focus(); } if (ev.key === 'Escape') back(); });
1664
+ desc.addEventListener('keydown', (ev) => { if (ev.key === 'Enter') { ev.preventDefault(); add(); } if (ev.key === 'Escape') back(); });
1665
+ form.querySelector('.sp-newcat-add').addEventListener('click', add);
1666
+ form.querySelector('.sp-newcat-x').addEventListener('click', back);
1667
+ });
1668
+ return plus;
1669
+ }
1670
+ // where a mark was made, so ⌘Z there takes it back and selects the words again
1671
+ const markedIn = (input, path, sel) => (input.tagName === 'TEXTAREA' ? { path, where: 'panel', sel } : { path, where: 'page', owner: spot(input)?.owner, sel });
1390
1672
  const assignLabel = (input) => {
1391
- if (assignEl.firstChild) assignEl.firstChild.textContent = input.selectionStart === input.selectionEnd ? 'Mark all as' : 'Mark selection as';
1673
+ const [s, e] = selOf(input);
1674
+ if (assignEl.firstChild) assignEl.firstChild.textContent = s === e ? 'Mark all as' : 'Mark selection as';
1392
1675
  };
1393
1676
  // while a selection is being dragged out too, so the row doesn't change under the pointer once it's let go
1394
1677
  document.addEventListener('selectionchange', () => {
1395
1678
  const a = document.activeElement;
1396
- if (a?.tagName === 'TEXTAREA' && assignEl.parentNode?.contains(a)) assignLabel(a);
1679
+ if ((a?.tagName === 'TEXTAREA' && assignEl.parentNode?.contains(a)) || (a === liveEl && assignEl.parentNode === float)) assignLabel(a);
1397
1680
  });
1398
1681
 
1399
1682
  /* copying a text's words keeps who wrote them: pasted into a text (here, or in another page's editor), they keep
@@ -1479,7 +1762,7 @@ const Slop = (() => {
1479
1762
  }
1480
1763
  // a copy's switch changes that copy only, and says so. A Repeats card's switch changes every copy.
1481
1764
  // The row reads: name and pie, then at the end anything else, the trash can and the switch
1482
- const ctl = control(paths, all ? count(all.paths.length, 'copy', 'copies') : `"${where(path)}"`, all ? null : (approved) => {
1765
+ const ctl = control(paths, all ? count(all.paths.length, 'copy', 'copies') : `"${where(path)}"`, { id: all ? `copies:${all.paths.join(' ')}` : `text:${path}`, after: all ? null : (approved) => {
1483
1766
  const others = (setOf(path)?.paths ?? []).filter((p) => p !== path);
1484
1767
  if (!others.length) return;
1485
1768
  const how = approved ? unslop : reslop;
@@ -1487,12 +1770,19 @@ const Slop = (() => {
1487
1770
  label: others.length === 1 ? 'Change it too' : 'Change them too',
1488
1771
  run: () => withUndo(`${approved ? 'Approved' : 'Back to slop:'} ${count(others.length + 1, 'copy', 'copies')}`, () => others.forEach((p) => set(p, how(get(p))))),
1489
1772
  });
1490
- });
1773
+ } });
1491
1774
  row.before(ctl.pie);
1492
1775
  if (listItem) row.append(removeButton(path, wrap));
1493
1776
  row.append(ctl);
1494
1777
  // the stretch a keystroke or a paste replaces: the selection, or nothing at the caret
1495
- input.addEventListener('beforeinput', () => { input.at = [input.selectionStart, input.selectionEnd]; });
1778
+ input.addEventListener('beforeinput', (e) => {
1779
+ input.at = [input.selectionStart, input.selectionEnd];
1780
+ if (/^history/.test(e.inputType) && e.cancelable) { e.preventDefault(); step(e.inputType === 'historyUndo'); } // from the Edit menu
1781
+ });
1782
+ // ⌘Z is the editor's: it takes back marks and switches too, and the words come back with their authors
1783
+ input.addEventListener('keydown', (e) => {
1784
+ if ((e.metaKey || e.ctrlKey) && !e.altKey && e.key.toLowerCase() === 'z') { e.preventDefault(); step(!e.shiftKey); }
1785
+ });
1496
1786
  input.addEventListener('input', (e) => {
1497
1787
  const restoring = /^history(Undo|Redo)$/.test(e.inputType);
1498
1788
  const pasted = e.inputType === 'insertFromPaste' ? input.pasted : null;
@@ -1509,7 +1799,7 @@ const Slop = (() => {
1509
1799
  mark(false);
1510
1800
  // after the click that moved the focus lands: removing these first would move what's being clicked
1511
1801
  afterClick(() => {
1512
- if (document.activeElement === input) return;
1802
+ if (document.activeElement === input || assignEl.contains(document.activeElement)) return;
1513
1803
  wrap.querySelector('.sp-hint').hidden = true;
1514
1804
  if (assignEl.parentNode === wrap) assignEl.remove();
1515
1805
  });
@@ -1529,7 +1819,7 @@ const Slop = (() => {
1529
1819
  det.dataset.group = key;
1530
1820
  det.open = state.open.has(key) || state.tab === 'hidden'; // there are few, so all of them show
1531
1821
  const all = () => entries(text[key], [key]).map(([p]) => p);
1532
- const ctl = control(all, `"${groupTitle(key)}"`);
1822
+ const ctl = control(all, `"${groupTitle(key)}"`, { id: `group:${key}` });
1533
1823
  det.querySelector('.sp-gname').after(ctl.pie);
1534
1824
  det.querySelector('summary').append(ctl);
1535
1825
  det.addEventListener('toggle', () => {
@@ -1728,6 +2018,7 @@ const Slop = (() => {
1728
2018
  row.querySelector('.sp-cat-pct').textContent = percent(page.letters ? (page.counts[row.dataset.id] ?? 0) / page.letters : 0);
1729
2019
  });
1730
2020
  controls.forEach((c) => paintControl(c, cats));
2021
+ if (floatCtl && !controls.some((c) => c.el === floatCtl)) paintControl({ el: floatCtl, paths: floatCtl.paths }, cats);
1731
2022
  body.querySelectorAll('.sp-goto').forEach((go) => {
1732
2023
  const m = makeup([get(go.dataset.path)]);
1733
2024
  go.querySelector('.sp-pie').style.background = gradient(m, cats);
@@ -1765,7 +2056,7 @@ const Slop = (() => {
1765
2056
  paintMeters();
1766
2057
  }
1767
2058
  repaint = () => { if (!aside.hidden) render(); };
1768
- reseen = () => { if (!aside.hidden) body.querySelectorAll('.sp-field').forEach(paintSeen); };
2059
+ reseen = () => { if (!aside.hidden) { body.querySelectorAll('.sp-field').forEach(paintSeen); liven(); } };
1769
2060
  // a text the page doesn't show right now is tagged, with a way to show it if the page says how
1770
2061
  function paintSeen(f) {
1771
2062
  const tag = f.querySelector('.sp-unseen');
@@ -1843,10 +2134,25 @@ const Slop = (() => {
1843
2134
  setTimeout(() => f.classList.remove('sp-flash'), 900);
1844
2135
  }
1845
2136
 
2137
+ // the box of a text being typed into on the page, scrolled to in the panel without taking the focus
2138
+ function seek(path) {
2139
+ const find = () => [...body.querySelectorAll('.sp-field')].find((x) => x.paths().includes(path));
2140
+ if (!find() || state.tab === 'hidden') {
2141
+ state.tab = state.tab === 'slop' && hasSlop(path) ? 'slop' : 'all';
2142
+ state.open.add(keysOf(path)[0]);
2143
+ render();
2144
+ }
2145
+ const f = find();
2146
+ if (!f) return;
2147
+ f.scrollIntoView({ block: 'nearest', behavior: 'smooth' });
2148
+ f.classList.add('sp-flash');
2149
+ setTimeout(() => f.classList.remove('sp-flash'), 900);
2150
+ }
1846
2151
  const grow = (x) => { x.style.height = 'auto'; x.style.height = `${x.scrollHeight + 2}px`; };
1847
2152
 
1848
2153
  // typing: what you type is yours, the rest keeps its author
1849
- // ⌘Z in a text: the words come back with whoever wrote them, from each text's recent versions
2154
+ // the browser's own undo, where it can't be stopped (the Edit menu, in some browsers): the words come back with
2155
+ // whoever wrote them, from each text's recent versions
1850
2156
  const past = new Map(); // path → [value, …], oldest first
1851
2157
  function remember(p) {
1852
2158
  const list = past.get(p) ?? [];
@@ -1857,15 +2163,16 @@ const Slop = (() => {
1857
2163
  const recall = (p, words) => past.get(p)?.findLast((v) => plain(v) === words);
1858
2164
  // `pasted`: words copied from a text, with their authors, now at `at`
1859
2165
  function edit(paths, input, restoring, at, pasted) {
1860
- undo = null;
2166
+ noted = false;
1861
2167
  const f = state.focus;
1862
2168
  const keep = pasted && at && input.value.startsWith(pasted.words, at[0]);
1863
- [...paths, ...(f?.linked ?? [])].forEach((p) => {
2169
+ const kind = input.value.length < plain(get(paths[0])).length ? 'delete' : 'type';
2170
+ track(() => [...paths, ...(f?.linked ?? [])].forEach((p) => {
1864
2171
  remember(p);
1865
2172
  const next = applyEdit(get(p), input.value, restoring ? recall(p, input.value) : undefined, at);
1866
2173
  set(p, keep ? overlay(next, at[0], pasted.authors) : next);
1867
2174
  remember(p);
1868
- });
2175
+ }), { at: { path: paths[0], where: 'panel' }, typing: restoring || pasted ? '' : kind, typed: true });
1869
2176
  grow(input);
1870
2177
  if (f?.copies.length && !f.linked) {
1871
2178
  // a copy changed on its own: offer to change the others the same way
@@ -1885,6 +2192,354 @@ const Slop = (() => {
1885
2192
  touched();
1886
2193
  }
1887
2194
 
2195
+ /* editing on the page: while the editor is open, every text on the page can be typed into where it is (the
2196
+ panel can shrink to its header, `inPlace`). The browser changes the words; each change is read back as the words that read differently (`reconcile`),
2197
+ made into the text with editRead (what's typed is mine, the markup stays), and the element drawn again */
2198
+ let inPlace = store.get('slop-editor-place') !== 'panel'; // the bar, unless the panel was open last time
2199
+ let liveEl = null; // the element being typed into
2200
+ let floatCtl = null;
2201
+ const float = el('div', 'slop-float slop-on');
2202
+ float.hidden = true;
2203
+ document.body.append(float);
2204
+ const canLive = (x) => !x.closest('.slop-panel, .slop-float, button, select, label, [data-slop-ref]') && (x.dataset.slop || x.dataset.slopMore);
2205
+ const liveOf = (t) => (!aside.hidden ? t?.closest?.('[contenteditable="true"][data-slop], [contenteditable="true"][data-slop-more]') : null);
2206
+ function liven() {
2207
+ const on = !aside.hidden;
2208
+ document.querySelectorAll('[data-slop], [data-slop-more]').forEach((x) => {
2209
+ if (on && canLive(x)) { if (x.contentEditable !== 'true') { x.contentEditable = 'true'; x.spellcheck = true; } } else if (x.hasAttribute('contenteditable')) x.removeAttribute('contenteditable');
2210
+ });
2211
+ }
2212
+ function setPlace(on) {
2213
+ inPlace = on;
2214
+ store.set('slop-editor-place', on ? 'page' : 'panel');
2215
+ aside.classList.toggle('sp-mini', on);
2216
+ modeBtn.innerHTML = on ? 'Panel' : SHRINK;
2217
+ modeBtn.title = on ? 'Show every text in the panel' : 'Shrink the editor to a bar. You type into the page either way';
2218
+ modeBtn.setAttribute('aria-label', on ? 'Show the panel' : 'Shrink to a bar');
2219
+ place();
2220
+ if (!on && !aside.hidden) render();
2221
+ }
2222
+ const SHRINK = '<svg viewBox="0 0 16 16" width="14" height="14" aria-hidden="true"><rect x="1.5" y="2.5" width="13" height="11" rx="2" fill="none" stroke="currentColor" stroke-width="1.4"/><rect x="3.5" y="9.5" width="9" height="2" rx="1" fill="currentColor"/></svg>';
2223
+ function livePage() {
2224
+ const on = !aside.hidden;
2225
+ document.documentElement.classList.toggle('slop-live', on);
2226
+ if (live.on !== on) { live.on = on; fill(); }
2227
+ liven();
2228
+ }
2229
+ // which text an element shows, and which of its paragraphs: {path, owner (its [data-slop] element), j, s, e, part}
2230
+ function spot(x) {
2231
+ const owner = x.dataset.slop ? x : ownerOf.get(x);
2232
+ if (!owner) return null;
2233
+ const path = owner.dataset.slop;
2234
+ const value = get(path);
2235
+ const spans = SPLITS.test(owner.tagName) ? paragraphSpans(value, true) : [[0, plain(value).length]];
2236
+ const j = x === owner ? 0 : (spills.get(owner) ?? []).indexOf(x) + 1;
2237
+ if (!spans[j]) return null;
2238
+ const [s, e] = spans[j];
2239
+ return { path, owner, j, s, e, value, spans, part: slice(value, s, e) };
2240
+ }
2241
+ const shownAt = (owner, j) => (j ? spills.get(owner)?.[j - 1] : owner);
2242
+
2243
+ // the words an element shows, as readOf has them: a {name} is one character, a <br> a line break
2244
+ function domWords(root) {
2245
+ let out = '';
2246
+ const walk = (n) => {
2247
+ if (n.nodeType === 3) out += n.data.replace(/ /g, ' ');
2248
+ else if (n.nodeType === 1 && n.hasAttribute('data-slop-v')) out += OBJ;
2249
+ else if (n.nodeName === 'BR') out += '\n';
2250
+ else n.childNodes.forEach(walk);
2251
+ };
2252
+ root.childNodes.forEach(walk);
2253
+ return out;
2254
+ }
2255
+ // how far into an element's words a point is
2256
+ function indexAt(root, node, offset) {
2257
+ const r = document.createRange();
2258
+ r.selectNodeContents(root);
2259
+ try { r.setEnd(node, offset); } catch { return 0; }
2260
+ return domWords(r.cloneContents()).length;
2261
+ }
2262
+ const selIn = (root) => {
2263
+ const sel = getSelection();
2264
+ if (!sel.rangeCount || !root.contains(sel.anchorNode)) return null;
2265
+ const r = sel.getRangeAt(0);
2266
+ return [indexAt(root, r.startContainer, r.startOffset), indexAt(root, r.endContainer, r.endOffset)];
2267
+ };
2268
+ // the caret at k of an element's words, or the selection k to k2
2269
+ function caret(root, k, k2 = k) {
2270
+ const r = document.createRange();
2271
+ r.setStart(...pointAt(root, k));
2272
+ r.setEnd(...pointAt(root, Math.max(k, k2)));
2273
+ const sel = getSelection();
2274
+ sel.removeAllRanges();
2275
+ sel.addRange(r);
2276
+ }
2277
+ function pointAt(root, k) {
2278
+ let n = 0;
2279
+ let at = null;
2280
+ const walk = (x) => {
2281
+ if (at) return;
2282
+ if (x.nodeType === 3) {
2283
+ if (k <= n + x.length) { at = [x, k - n]; return; }
2284
+ n += x.length;
2285
+ } else if (x.nodeType === 1 && (x.hasAttribute('data-slop-v') || x.nodeName === 'BR')) {
2286
+ if (k === n) { at = [x.parentNode, [...x.parentNode.childNodes].indexOf(x)]; return; }
2287
+ n++;
2288
+ if (k === n && x.nextSibling?.nodeType !== 3) at = [x.parentNode, [...x.parentNode.childNodes].indexOf(x) + 1];
2289
+ } else x.childNodes.forEach(walk);
2290
+ };
2291
+ root.childNodes.forEach(walk);
2292
+ return at ?? [root, root.childNodes.length];
2293
+ }
2294
+ // the selection in source terms, for "Mark as": [start, end, length] of the whole text's plain text
2295
+ function selOf(x) {
2296
+ if (x.tagName === 'TEXTAREA') return [x.selectionStart, x.selectionEnd, x.value.length];
2297
+ const sp = spot(x);
2298
+ const [a, b] = selIn(x) ?? [0, 0];
2299
+ if (!sp) return [0, 0, 0];
2300
+ const [s, e] = readSpan(sp.part, a, b);
2301
+ return [sp.s + s, sp.s + e, plain(sp.value).length];
2302
+ }
2303
+
2304
+ // the words in an element, after a change: into the text, and the element (and every other showing it) redrawn
2305
+ // `coalesce`: a keystroke, which joins the ones before it in one step of ⌘Z
2306
+ function commit(sp, value, j, at, coalesce, to = at) {
2307
+ const kind = plain(value).length < plain(sp.value).length ? 'delete' : 'type';
2308
+ put(sp.path, value, sp.owner, j, at, to, coalesce ? kind : '');
2309
+ }
2310
+ function put(path, value, owner, j, at, to = at, typing = '') {
2311
+ noted = false;
2312
+ track(() => set(path, value), { at: { path, where: 'page', owner }, typing, typed: true });
2313
+ fill();
2314
+ liven();
2315
+ body.querySelectorAll('.sp-field').forEach((f) => {
2316
+ if (!f.paths().includes(path) || !f.input) return;
2317
+ f.input.value = plain(get(f.dataset.path));
2318
+ grow(f.input);
2319
+ });
2320
+ touched();
2321
+ const x = shownAt(owner, j) ?? shownAt(owner, Math.max(0, (spills.get(owner)?.length ?? 0)));
2322
+ if (!x) return;
2323
+ if (document.activeElement !== x) x.focus({ preventScroll: true });
2324
+ const n = domWords(x).length;
2325
+ caret(x, Math.min(at, n), Math.min(to, n));
2326
+ paintFloat();
2327
+ }
2328
+ let replaced = null; // the selection a change replaces, from beforeinput
2329
+ function reconcile(x) {
2330
+ const sp = spot(x);
2331
+ if (!sp) return;
2332
+ const before = readOf(sp.part).words.replace(/\u00a0/g, ' '); // as domWords reads the page: a non-breaking space in the words stays
2333
+ let now = domWords(x);
2334
+ if (now.endsWith('\n') && !before.endsWith('\n') && x.lastChild?.nodeName === 'BR') now = now.slice(0, -1); // the browser's placeholder
2335
+ if (now === before) return;
2336
+ const at = selIn(x)?.[1] ?? now.length;
2337
+ let a = 0;
2338
+ let b = 0;
2339
+ if (replaced && now.startsWith(before.slice(0, replaced[0])) && now.endsWith(before.slice(replaced[1])) && now.length - (before.length - replaced[1]) >= replaced[0]) {
2340
+ [a, b] = replaced;
2341
+ } else {
2342
+ while (a < before.length && a < now.length && before[a] === now[a]) a++;
2343
+ let end = 0;
2344
+ while (end < before.length - a && end < now.length - a && before[before.length - 1 - end] === now[now.length - 1 - end]) end++;
2345
+ b = before.length - end;
2346
+ }
2347
+ const typed = now.slice(a, now.length - (before.length - b)).replaceAll(OBJ, '');
2348
+ replaced = null;
2349
+ commit(sp, splice(sp.value, sp.s, sp.e, editRead(sp.part, a, b, typed)), sp.j, at, true);
2350
+ }
2351
+ // ⌘B, ⌘I, ⌘E (code) and ⌘K (a link) on the selection: its words stay, written again with the markup
2352
+ function format(x, how) {
2353
+ const sp = spot(x);
2354
+ const [a, b] = selIn(x) ?? [0, 0];
2355
+ if (!sp || a === b) { status('Select some words first'); return; }
2356
+ commit(sp, splice(sp.value, sp.s, sp.e, restyle(sp.part, a, b, how)), sp.j, a, false, b);
2357
+ }
2358
+ function linkAt(x) {
2359
+ const sp = spot(x);
2360
+ const [a, b] = selIn(x) ?? [0, 0];
2361
+ if (!sp || a === b) { status('Select some words first'); return; }
2362
+ // already a link: ⌘K takes it off
2363
+ const { at } = readOf(sp.part);
2364
+ const linked = runs(sp.part).filter((r) => r.link && !r.v).flatMap((r) => r.at);
2365
+ if (at.slice(a, b).every((i) => linked.includes(i))) { format(x, { link: null }); return; }
2366
+ float.querySelector('.sp-linkform')?.remove();
2367
+ const form = el('span', 'sp-newcat sp-linkform', '<input class="sp-newcat-about" placeholder="Link to https://…" aria-label="Link to" spellcheck="false">'
2368
+ + '<button type="button" class="sp-newcat-add">Link</button><button type="button" class="sp-newcat-x" aria-label="Cancel">×</button>');
2369
+ float.append(form);
2370
+ const input = form.querySelector('input');
2371
+ input.focus();
2372
+ const back = () => { form.remove(); x.focus(); caret(x, a, b); };
2373
+ const go = () => {
2374
+ const href = input.value.trim();
2375
+ form.remove();
2376
+ if (!href) { back(); return; }
2377
+ x.focus();
2378
+ caret(x, a, b);
2379
+ format(x, { link: { href: /^[a-z][\w+.-]*:|^[/#?.]/i.test(href) ? href : `https://${href}` } });
2380
+ };
2381
+ input.addEventListener('keydown', (e) => { if (e.key === 'Enter') { e.preventDefault(); go(); } if (e.key === 'Escape') back(); });
2382
+ form.querySelector('.sp-newcat-add').addEventListener('click', go);
2383
+ form.querySelector('.sp-newcat-x').addEventListener('click', back);
2384
+ }
2385
+ // typing that isn't left to the browser: a new paragraph, a line break, joining paragraphs, formatting
2386
+ function typeAt(x, words) {
2387
+ const sp = spot(x);
2388
+ const [a, b] = selIn(x) ?? [0, 0];
2389
+ commit(sp, splice(sp.value, sp.s, sp.e, editRead(sp.part, a, b, words)), sp.j, a + words.length);
2390
+ }
2391
+ document.addEventListener('beforeinput', (e) => {
2392
+ const x = liveOf(e.target);
2393
+ if (!x) return;
2394
+ replaced = selIn(x);
2395
+ const t = e.inputType;
2396
+ const sp = spot(x);
2397
+ if (!sp) { e.preventDefault(); return; }
2398
+ const long = isLong(sp.path, sp.value);
2399
+ if (/^format|^history|FromDrop$/.test(t)) {
2400
+ e.preventDefault();
2401
+ if (t === 'historyUndo') step(true);
2402
+ if (t === 'historyRedo') step(false);
2403
+ if (t === 'formatBold') format(x, { b: true });
2404
+ if (t === 'formatItalic') format(x, { i: true });
2405
+ return;
2406
+ }
2407
+ if (t === 'insertParagraph' || t === 'insertLineBreak') {
2408
+ e.preventDefault();
2409
+ if (t === 'insertParagraph' && SPLITS.test(sp.owner.tagName)) {
2410
+ // a new paragraph: the words after the caret move to the element after this one
2411
+ const [a, b] = replaced ?? [0, 0];
2412
+ const part = editRead(sp.part, a, b, '');
2413
+ const [s] = readSpan(part, a, a);
2414
+ const next = splice(sp.value, sp.s, sp.e, fromChars(`${plain(part).slice(0, s)}\n\n${plain(part).slice(s)}`,
2415
+ [...authorsByChar(part).slice(0, s), 'me', 'me', ...authorsByChar(part).slice(s)]));
2416
+ commit(sp, next, sp.j + 1, 0);
2417
+ } else if (long) typeAt(x, '\n');
2418
+ return;
2419
+ }
2420
+ const [a, b] = replaced ?? [0, 0];
2421
+ // backspace at the start of a paragraph joins it to the one before; delete at its end, to the one after
2422
+ const join = a === b && ((t === 'deleteContentBackward' && a === 0 && sp.j > 0) || (t === 'deleteContentForward' && a === readOf(sp.part).words.length && sp.j < sp.spans.length - 1));
2423
+ if (join) {
2424
+ e.preventDefault();
2425
+ const k = t === 'deleteContentBackward' ? sp.j - 1 : sp.j;
2426
+ const keep = readOf(slice(sp.value, ...sp.spans[k])).words.length;
2427
+ commit(sp, splice(sp.value, sp.spans[k][1], sp.spans[k + 1][0], ''), k, keep);
2428
+ }
2429
+ });
2430
+ document.addEventListener('input', (e) => { const x = liveOf(e.target); if (x && !e.isComposing) reconcile(x); });
2431
+ document.addEventListener('compositionstart', (e) => { const x = liveOf(e.target); if (x) replaced = selIn(x); });
2432
+ document.addEventListener('compositionend', (e) => { const x = liveOf(e.target); if (x) reconcile(x); });
2433
+ document.addEventListener('paste', (e) => {
2434
+ const x = liveOf(e.target);
2435
+ if (!x) return;
2436
+ e.preventDefault();
2437
+ const sp = spot(x);
2438
+ const pasted = pastedIn(e);
2439
+ const words = pasted?.words ?? (e.clipboardData?.getData('text/plain') ?? '').replace(/\r\n?/g, '\n');
2440
+ const [a, b] = selIn(x) ?? [0, 0];
2441
+ let part = editRead(sp.part, a, b, words, pasted ? '\u0000' : 'me');
2442
+ if (pasted) {
2443
+ // copied from a text: each letter keeps its author (and an escape takes its letter's)
2444
+ const who = [];
2445
+ for (let i = 0; i < words.length; i++) { if (/[\\*`[\]{]/.test(words[i])) who.push(pasted.authors[i]); who.push(pasted.authors[i]); }
2446
+ part = overlay(part, authorsByChar(part).indexOf('\u0000'), who);
2447
+ }
2448
+ commit(sp, splice(sp.value, sp.s, sp.e, part), sp.j, a + words.length);
2449
+ }, true);
2450
+ document.addEventListener('drop', (e) => { if (liveOf(e.target)) e.preventDefault(); }, true);
2451
+ document.addEventListener('keydown', (e) => {
2452
+ const x = liveOf(e.target);
2453
+ if (!x) return;
2454
+ if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'z') { e.preventDefault(); e.stopPropagation(); step(!e.shiftKey); return; }
2455
+ const style = { b: 'b', i: 'i', e: 'code' }[e.key.toLowerCase()];
2456
+ if ((e.metaKey || e.ctrlKey) && !e.altKey && style) { e.preventDefault(); format(x, { [style]: true }); return; }
2457
+ if ((e.metaKey || e.ctrlKey) && !e.altKey && e.key.toLowerCase() === 'k') { e.preventDefault(); linkAt(x); return; }
2458
+ if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'u') { e.preventDefault(); return; }
2459
+ if (e.key === 'Escape') x.blur();
2460
+ e.stopPropagation(); // the page's own shortcuts stay out of the typing
2461
+ }, true);
2462
+ // the page's own handlers stay out of a click into a text, and a link in it isn't followed
2463
+ ['pointerdown', 'mousedown', 'pointerup', 'mouseup', 'click', 'dblclick'].forEach((type) => document.addEventListener(type, (e) => {
2464
+ if (!liveOf(e.target)) return;
2465
+ e.stopPropagation();
2466
+ if (type === 'click' && e.target.closest('a')) e.preventDefault();
2467
+ }, true));
2468
+ document.addEventListener('focusin', (e) => {
2469
+ const x = liveOf(e.target);
2470
+ // the caret is in my color, as what's typed will be, not in the color of the words it's in. caret-color's
2471
+ // currentColor would be the words' own, so it's set here: my category's color, or the element's ink
2472
+ if (x) x.style.caretColor = colorOf('me', 0) ?? getComputedStyle(x).color;
2473
+ if (!x || x === liveEl) return;
2474
+ liveEl = x;
2475
+ const sp = spot(x);
2476
+ if (!sp) return;
2477
+ document.querySelectorAll('.slop-focus, .slop-copy').forEach((y) => y.classList.remove('slop-focus', 'slop-copy'));
2478
+ elementsOf(sp.path).forEach((y) => y.classList.add('slop-focus'));
2479
+ float.innerHTML = '';
2480
+ // a heading's switch covers its section
2481
+ const { owner, path } = sp;
2482
+ const paths = () => (rankOf(owner) ? sectionUnder(owner) : [path]);
2483
+ const under = () => paths().length - 1;
2484
+ floatCtl = control(paths, () => `"${where(path)}"${under() ? ` and ${count(under(), 'text')} under it` : ''}`, {
2485
+ id: `${rankOf(owner) ? 'section' : 'text'}:${path}`,
2486
+ scope: rankOf(owner) ? () => `This heading and ${count(under(), 'text')} under it` : null,
2487
+ });
2488
+ floatCtl.prepend(floatCtl.pie);
2489
+ float.append(floatCtl);
2490
+ showAssign(float, x, [sp.path]);
2491
+ float.hidden = false;
2492
+ numbers();
2493
+ paintFloat();
2494
+ });
2495
+ document.addEventListener('focusout', (e) => {
2496
+ if (!liveOf(e.target) && !float.contains(e.target)) return;
2497
+ // focus going to another text, or into the row (its switch, ⌘K's link form): the row stays. Without a click, focusout
2498
+ // comes before the focus lands, so where it's going is relatedTarget
2499
+ const to = e.relatedTarget;
2500
+ if (to && (liveOf(to) || float.contains(to))) return;
2501
+ afterClick(() => {
2502
+ const a = document.activeElement;
2503
+ if (liveOf(a) || float.contains(a)) return;
2504
+ hideFloat();
2505
+ });
2506
+ });
2507
+ // a heading's section on the page: it and every text after it up to the next heading as big or bigger, in the
2508
+ // heading's group of the block (so a page's title isn't the whole page)
2509
+ const rankOf = (x) => { const m = /^H([1-6])$/.exec(x.tagName); return m ? +m[1] : x.getAttribute('role') === 'heading' ? +(x.getAttribute('aria-level') || 2) : 0; };
2510
+ function sectionUnder(owner) {
2511
+ const path = owner.dataset.slop;
2512
+ const top = keysOf(path)[0];
2513
+ const out = [path];
2514
+ const all = [...document.querySelectorAll('[data-slop], [data-slop-attr], h1, h2, h3, h4, h5, h6, [role="heading"]')].filter((x) => !x.closest('.slop-panel, .slop-float, .slop-sampler'));
2515
+ if (!all.includes(owner)) return out;
2516
+ for (const x of all.slice(all.indexOf(owner) + 1)) {
2517
+ const r = rankOf(x);
2518
+ if (r && r <= rankOf(owner)) break;
2519
+ [x.dataset.slop, ...attrsOf(x).map(([, p]) => p)].forEach((p) => { if (p && keysOf(p)[0] === top && !out.includes(p) && valueAt(text, p) !== undefined) out.push(p); });
2520
+ }
2521
+ return out;
2522
+ }
2523
+ function hideFloat() {
2524
+ liveEl = null;
2525
+ floatCtl = null;
2526
+ float.hidden = true;
2527
+ document.querySelectorAll('.slop-focus, .slop-copy').forEach((y) => y.classList.remove('slop-focus', 'slop-copy'));
2528
+ }
2529
+ // above the text, or under it when there's no room
2530
+ function paintFloat() {
2531
+ if (!liveEl || float.hidden) return;
2532
+ const r = liveEl.getBoundingClientRect();
2533
+ const h = float.offsetHeight;
2534
+ const w = float.offsetWidth;
2535
+ const top = r.top - h - 10 > 8 ? r.top - h - 10 : r.bottom + 10;
2536
+ float.style.top = `${Math.round(top)}px`;
2537
+ float.style.left = `${Math.round(Math.min(Math.max(8, r.left), innerWidth - w - 8))}px`;
2538
+ }
2539
+ addEventListener('scroll', paintFloat, { capture: true, passive: true });
2540
+ addEventListener('resize', paintFloat);
2541
+ new ResizeObserver(paintFloat).observe(float); // a row that grows (a new category's form) moves up
2542
+
1888
2543
  // saving: only with the Save button (or ⌘S), one request at a time, each carrying the version it was based on.
1889
2544
  // `saved` is the text as of the last save, for the Save button's count and each text's Revert
1890
2545
  let saved = JSON.parse(JSON.stringify(text));
@@ -1921,7 +2576,6 @@ const Slop = (() => {
1921
2576
  const kept = store.set(LOCAL, JSON.stringify({ base: JSON.parse(original).version, baseText: JSON.parse(original), text: JSON.parse(body) }));
1922
2577
  if (!kept) { status("Couldn't save in this browser", 'error'); return; }
1923
2578
  saved = JSON.parse(body);
1924
- undo = null;
1925
2579
  keepDraft();
1926
2580
  savedStatus();
1927
2581
  numbers();
@@ -1936,7 +2590,6 @@ const Slop = (() => {
1936
2590
  if (!res.ok) throw new Error(out || res.statusText);
1937
2591
  text.version = Number(out);
1938
2592
  saved = { ...JSON.parse(body), version: text.version };
1939
- undo = null;
1940
2593
  keepDraft();
1941
2594
  savedStatus();
1942
2595
  } catch (e) {
@@ -1951,14 +2604,16 @@ const Slop = (() => {
1951
2604
  numbers();
1952
2605
  changed();
1953
2606
  keepDraft();
1954
- if (!stale && !undo) status(unsaved() ? 'Not saved yet' : 'No changes since the last save', unsaved() ? 'dirty' : '');
2607
+ if (!stale && !noted) status(unsaved() ? 'Not saved yet' : 'No changes since the last save', unsaved() ? 'dirty' : '');
1955
2608
  }
1956
2609
  function reset() {
1957
2610
  store.drop(LOCAL);
1958
2611
  session.drop(DRAFT);
1959
2612
  text = JSON.parse(original);
1960
2613
  saved = JSON.parse(original);
1961
- undo = null;
2614
+ undos.length = 0;
2615
+ redos.length = 0;
2616
+ noted = false;
1962
2617
  applyColors();
1963
2618
  changed();
1964
2619
  render();
@@ -1974,10 +2629,10 @@ const Slop = (() => {
1974
2629
  };
1975
2630
  addEventListener('keydown', (e) => {
1976
2631
  if ((e.metaKey || e.ctrlKey) && e.key === 's' && !aside.hidden) { e.preventDefault(); save(); }
1977
- // ⌘Z outside a text undoes the last switch or mark (a text's own ⌘Z undoes its typing)
1978
- if ((e.metaKey || e.ctrlKey) && !e.shiftKey && e.key === 'z' && undo && !aside.hidden && !e.target.closest?.('textarea, input')) {
2632
+ // ⌘Z and ⌘⇧Z outside a text too (a text's are caught there; a name or a link's address keeps its own)
2633
+ if ((e.metaKey || e.ctrlKey) && !e.altKey && e.key.toLowerCase() === 'z' && !aside.hidden && !e.defaultPrevented && !e.target.closest?.('textarea, input, [contenteditable="true"]')) {
1979
2634
  e.preventDefault();
1980
- statusEl.querySelector('.sp-link')?.click();
2635
+ step(!e.shiftKey);
1981
2636
  }
1982
2637
  });
1983
2638
  body.addEventListener('pointerdown', (e) => {
@@ -1988,9 +2643,11 @@ const Slop = (() => {
1988
2643
 
1989
2644
  // while the editor is open, a click on a text opens it in the editor
1990
2645
  document.addEventListener('click', (e) => {
1991
- if (aside.hidden || aside.contains(e.target) || btn.contains(e.target)) return;
2646
+ if (aside.hidden || aside.contains(e.target) || float.contains(e.target)) return;
1992
2647
  const target = e.target.closest('[data-slop], [data-slop-ref], [data-slop-more], [data-slop-attr]');
1993
2648
  if (!target) return;
2649
+ // typed into where it is: the panel only shows its box
2650
+ if (liveOf(e.target)) { if (!inPlace) seek(pathOf(target)); return; }
1994
2651
  e.preventDefault();
1995
2652
  e.stopPropagation();
1996
2653
  const path = pathOf(target);
@@ -2010,6 +2667,7 @@ const Slop = (() => {
2010
2667
  try { rect = JSON.parse(store.get(RECT)) ?? {}; } catch { /* docked */ }
2011
2668
  function place() {
2012
2669
  aside.removeAttribute('style');
2670
+ if (inPlace) return;
2013
2671
  if (narrow()) {
2014
2672
  if (rect.sheet) aside.style.height = `${clamp(rect.sheet, 200, innerHeight - 16)}px`;
2015
2673
  return;
@@ -2057,7 +2715,7 @@ const Slop = (() => {
2057
2715
  target.addEventListener('pointercancel', up);
2058
2716
  }
2059
2717
  const head = $('.sp-head');
2060
- head.addEventListener('pointerdown', (e) => { if (!e.target.closest('button')) drag(e, 'move'); });
2718
+ head.addEventListener('pointerdown', (e) => { if (!e.target.closest('button') && !inPlace) drag(e, 'move'); });
2061
2719
  head.addEventListener('dblclick', (e) => {
2062
2720
  if (e.target.closest('button')) return;
2063
2721
  rect = {};
@@ -2069,16 +2727,15 @@ const Slop = (() => {
2069
2727
 
2070
2728
  const open = (on) => {
2071
2729
  aside.hidden = !on;
2072
- btn.hidden = on;
2073
2730
  document.documentElement.classList.toggle('slop-editing', on);
2074
2731
  editing = on;
2075
2732
  paintShow();
2076
- if (!on) { mark(false); unreveal(); closePicker(); return; }
2733
+ livePage();
2734
+ if (!on) { mark(false); unreveal(); closePicker(); hideFloat(); return; }
2077
2735
  place();
2078
2736
  render();
2079
2737
  };
2080
- btn.addEventListener('click', () => open(true));
2081
- $('.sp-close').addEventListener('click', () => open(false));
2738
+ modeBtn.addEventListener('click', () => setPlace(!inPlace));
2082
2739
  aside.querySelectorAll('.sp-seg button').forEach((b) => b.addEventListener('click', () => {
2083
2740
  if (b.dataset.show === shows()) return;
2084
2741
  withUndo(`Readers see: ${b.textContent.toLowerCase()}`, () => {
@@ -2087,6 +2744,7 @@ const Slop = (() => {
2087
2744
  });
2088
2745
  }));
2089
2746
  aside.querySelectorAll('.sp-tabs button').forEach((b) => b.addEventListener('click', () => { state.tab = b.dataset.tab; render(); }));
2747
+ setPlace(inPlace);
2090
2748
  savedStatus();
2091
2749
  try {
2092
2750
  const draft = JSON.parse(session.get(DRAFT));
@@ -2097,10 +2755,12 @@ const Slop = (() => {
2097
2755
  open(true);
2098
2756
  status('Unsaved changes from before the reload', 'dirty', {
2099
2757
  label: 'Discard',
2100
- run: () => { text = JSON.parse(JSON.stringify(saved)); session.drop(DRAFT); applyColors(); changed(); render(); savedStatus(); },
2758
+ run: () => { text = JSON.parse(JSON.stringify(saved)); undos.length = 0; redos.length = 0; noted = false; session.drop(DRAFT); applyColors(); changed(); render(); savedStatus(); },
2101
2759
  });
2102
2760
  }
2103
2761
  } catch { /* none */ }
2762
+ // the editor is open from the start: the page's words can be typed into, and the bar (or the panel) is there
2763
+ if (aside.hidden) open(true);
2104
2764
  return { render: () => { if (!aside.hidden) render(); }, touched, open };
2105
2765
  }
2106
2766