slop-editor 0.5.0 → 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
@@ -101,6 +101,8 @@ const Slop = (() => {
101
101
  const reslop = (value) => reattribute(value, 'ok', 'ai');
102
102
  // characters start to end (of the plain text) marked as one author's
103
103
  const assign = (value, start, end, to) => fromChars(plain(value), authorsByChar(value).map((a, i) => (i >= start && i < end ? to : a)));
104
+ // characters from `start` on given these authors, one each (what was pasted keeps who wrote it), the text unchanged
105
+ const overlay = (value, start, authors) => fromChars(plain(value), authorsByChar(value).map((a, i) => authors[i - start] ?? a));
104
106
 
105
107
  const LINK = /\[([^\]]+)\]\(([^)\s]+)\)/y;
106
108
  const VAR = /\{(\w+)\}/y;
@@ -109,64 +111,185 @@ const Slop = (() => {
109
111
  // the text as it reads: runs of one author's words (`by`: the category) with their formatting (b, i, code, key)
110
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,
111
113
  // a command or a file name reads as data
112
- 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) {
113
117
  const text = plain(value);
114
118
  const authors = authorsByChar(value);
115
119
  const out = [];
120
+ const marks = [];
116
121
  const st = { b: false, i: false, code: false, key: false, link: null };
122
+ const opened = {}; // the mark that turned each one on
117
123
  let linkEnd = -1;
118
124
  let linkTail = 0;
119
- const push = (s, by, v) => {
120
- 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 };
121
127
  const last = out[out.length - 1];
122
- if (last && !last.v && !v && same(last, run)) last.text += s;
123
- 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);
124
134
  };
125
135
  for (let i = 0; i < text.length;) {
126
136
  const c = text[i];
127
- if (i === linkEnd) { st.link = null; i += linkTail; linkEnd = -1; continue; }
128
- if (c === '\\' && i + 1 < text.length) { push(text[i + 1], authors[i + 1]); i += 2; continue; }
129
- if (c === '[' && text[i + 1] === '[' && !st.key) { st.key = true; i += 2; continue; }
130
- 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; }
131
141
  if (c === '[' && !st.link) {
132
142
  LINK.lastIndex = i;
133
143
  const m = LINK.exec(text);
134
- 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; }
135
145
  }
136
- if (c === '`') { st.code = !st.code; i++; continue; }
146
+ if (c === '`') { st.code = !st.code; mark('code', i, 1); i++; continue; }
137
147
  if (c === '*' && !st.code) {
138
- 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++; }
139
149
  continue;
140
150
  }
141
151
  if (c === '{') {
142
152
  VAR.lastIndex = i;
143
153
  const m = VAR.exec(text);
144
- 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; }
145
155
  }
146
- push(c, authors[i]);
156
+ push(c, authors[i], i);
147
157
  i++;
148
158
  }
149
- 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];
150
263
  }
151
264
 
152
265
  // a text in paragraphs: split at blank lines, each keeping its authors. Without a blank line it's one paragraph
153
- 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) {
154
269
  const text = plain(value);
155
- const authors = authorsByChar(value);
156
270
  const spans = [];
157
- 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
158
272
  let at = 0;
159
273
  for (let m; (m = gap.exec(text));) { spans.push([at, m.index]); at = m.index + m[0].length; }
160
- if (!spans.length) return [value];
161
274
  spans.push([at, text.length]);
162
- const parts = spans.map(([s, e]) => fromChars(text.slice(s, e), authors.slice(s, e))).filter((p) => plain(p).trim());
163
- 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];
164
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)]);
165
286
 
166
287
  // values the page fills in: {html, data} (data: a fact, shown in the data color; otherwise it takes the color of
167
288
  // whoever wrote the {name}), or a plain string or number (a fact)
168
289
  const vars = {};
169
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 };
170
293
  // where the browser editor keeps this page's copy: its path, or the page's own name for it (Slop.start({key}))
171
294
  const pageKey = () => config.key ?? location.pathname;
172
295
  const esc = (s) => String(s).replace(/[&<>"]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' })[c]);
@@ -184,6 +307,7 @@ const Slop = (() => {
184
307
 
185
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
186
309
  function render(value, local) {
310
+ const all = runs(value);
187
311
  const one = (run) => {
188
312
  let h;
189
313
  let by = run.by;
@@ -191,8 +315,18 @@ const Slop = (() => {
191
315
  const v = lookup(run.v, local);
192
316
  h = v.html;
193
317
  if (v.data) by = 'data';
194
- } else h = esc(run.text).replace(/\n/g, '<br>');
195
- 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>`;
196
330
  if (run.key) h = `<kbd>${h}</kbd>`;
197
331
  if (run.code) h = `<span class="${config.code}">${h}</span>`;
198
332
  if (run.i) h = `<em>${h}</em>`;
@@ -200,7 +334,7 @@ const Slop = (() => {
200
334
  return h;
201
335
  };
202
336
  const parts = [];
203
- runs(value).forEach((run) => {
337
+ all.forEach((run) => {
204
338
  const last = parts[parts.length - 1];
205
339
  if (!run.link) parts.push(run);
206
340
  else if (last?.link === run.link) last.runs.push(run);
@@ -310,7 +444,7 @@ const Slop = (() => {
310
444
  return out;
311
445
  }
312
446
 
313
- const core = { BUILTIN, plain, applyEdit, reslop, unslop, assign, 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 };
314
448
  if (typeof document === 'undefined') return core; // Node (the CLI and the tests) only needs the format
315
449
 
316
450
  /* ---------- the block ---------- */
@@ -391,13 +525,17 @@ const Slop = (() => {
391
525
  const SPLITS = /^(P|LI|DD)$/;
392
526
  const spills = new WeakMap(); // element → the copies after it
393
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; };
394
532
  function fillOne(el) {
395
533
  const local = el.dataset.slopVars ? JSON.parse(el.dataset.slopVars) : undefined;
396
534
  if (el.dataset.slop) {
397
535
  const value = get(el.dataset.slop);
398
- 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);
399
537
  const h = render(parts[0], local);
400
- if (el.innerHTML !== h) el.innerHTML = h;
538
+ if (el.innerHTML !== asSet(h)) el.innerHTML = h;
401
539
  el.classList.toggle('slop-empty', !plain(value).trim());
402
540
  spill(el, parts.slice(1).map((v) => render(v, local)));
403
541
  }
@@ -413,13 +551,13 @@ const Slop = (() => {
413
551
  let c = copies[i];
414
552
  if (!c) {
415
553
  c = el.cloneNode(false);
416
- ['id', 'data-slop', 'data-slop-attr'].forEach((a) => c.removeAttribute(a));
554
+ ['id', 'data-slop', 'data-slop-attr', 'contenteditable'].forEach((a) => c.removeAttribute(a));
417
555
  c.classList.remove('slop-focus', 'slop-copy', 'slop-empty');
418
556
  ownerOf.set(c, el);
419
557
  copies.push(c);
420
558
  }
421
559
  c.dataset.slopMore = el.dataset.slop;
422
- if (c.innerHTML !== h) c.innerHTML = h;
560
+ if (c.innerHTML !== asSet(h)) c.innerHTML = h;
423
561
  const before = i ? copies[i - 1] : el;
424
562
  if (before.nextElementSibling !== c) before.after(c);
425
563
  });
@@ -460,7 +598,7 @@ const Slop = (() => {
460
598
  const first = [...box.children].find(ours);
461
599
  if (!first) return;
462
600
  const t = first.cloneNode(false);
463
- ['id', 'data-slop'].forEach((a) => t.removeAttribute(a));
601
+ ['id', 'data-slop', 'contenteditable'].forEach((a) => t.removeAttribute(a));
464
602
  templates.set(box, t);
465
603
  }
466
604
  const paths = textKeys(nodeAt(text, at)).filter(isParagraph).map((k) => `${at}.${k}`);
@@ -626,13 +764,15 @@ const Slop = (() => {
626
764
  const store = storage(() => localStorage);
627
765
  const session = storage(() => sessionStorage); // this tab only: the unsaved draft
628
766
  // what readers see is the page's choice, "nothing" unless it says otherwise. While the editor is open, its
629
- // author sees the colors whatever readers get
767
+ // author sees the colors whatever readers get, until they switch them off to compare (editColors)
630
768
  const SHOW = ['nothing', 'pie', 'colors'];
631
769
  const shows = () => (SHOW.includes(text._show) ? text._show : 'nothing');
632
770
  const meters = [];
633
771
  const built = new WeakMap(); // element → its meter
634
772
  let meterOn = false;
635
773
  let editing = false;
774
+ let editColors = true;
775
+ let editSwitch = null; // the editor's own Slop-o-meter switch, in its header
636
776
  function setMeter(on) {
637
777
  meterOn = on;
638
778
  paintShow();
@@ -643,7 +783,8 @@ const Slop = (() => {
643
783
  const sectionOf = (m) => (m.at && m.el.parentElement ? m.el.closest('[data-slop-section]') ?? m.el.parentElement : document.documentElement);
644
784
  function paintShow() {
645
785
  const mode = shows();
646
- document.documentElement.classList.toggle('slop-on', editing || (mode === 'colors' && meterOn));
786
+ document.documentElement.classList.toggle('slop-on', editing ? editColors : mode === 'colors' && meterOn);
787
+ editSwitch?.setAttribute('aria-checked', String(editColors));
647
788
  meters.forEach((m) => {
648
789
  m.el.dataset.show = mode;
649
790
  const section = sectionOf(m);
@@ -655,7 +796,7 @@ const Slop = (() => {
655
796
  section.classList.toggle('slop-on', own === true);
656
797
  section.classList.toggle('slop-off', own === false);
657
798
  }
658
- m.btn.setAttribute('aria-pressed', String(m.own ?? meterOn));
799
+ m.btn.setAttribute('aria-pressed', String(editing ? editColors : m.own ?? meterOn));
659
800
  });
660
801
  }
661
802
  function paintMeters() {
@@ -683,6 +824,7 @@ const Slop = (() => {
683
824
  + '<span class="slop-meter-key"><span class="slop-pie" role="img"></span><span class="slop-legend"></span></span>';
684
825
  const m = { el, at: el.dataset.slopMeter || '', own: null, section: null, btn: el.querySelector('button'), pie: el.querySelector('.slop-pie'), legend: el.querySelector('.slop-legend') };
685
826
  m.btn.addEventListener('click', () => {
827
+ if (editing) { editColors = !editColors; paintShow(); return; } // the editor's switch, while it's open
686
828
  const on = !(m.own ?? meterOn);
687
829
  if (m.at) { m.own = on; paintShow(); return; } // only the page-wide choice is remembered
688
830
  setMeter(on);
@@ -752,19 +894,16 @@ const Slop = (() => {
752
894
  const state = { tab: startTab(), open: new Set(groupKeys().slice(0, 1)), known: new Set(groupKeys()), focus: null };
753
895
  let sets = repeats(entries());
754
896
  let controls = []; // [{el, paths}] in the current view, repainted by numbers()
755
- let undo = null;
756
897
 
757
- const btn = el('button', 'slop-edit-btn', 'Edit text');
758
- btn.type = 'button';
759
898
  const aside = el('aside', 'slop-panel', `
760
899
  <header class="sp-head" title="Drag to move, or drag an edge to resize. Double-click to put it back">
761
900
  <span class="sp-grip" aria-hidden="true"></span>
762
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>
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>
763
904
  <button type="button" class="sp-save" title="Save (⌘S)" disabled>Saved</button>
764
- <button type="button" class="sp-close" aria-label="Close the editor">×</button>
765
905
  </header>
766
906
  <div class="sp-cover">
767
- <div class="sp-cover-row"><p class="sp-big"><b></b> slop</p><p class="sp-words"></p></div>
768
907
  <div class="sp-cats"></div>
769
908
  <div class="sp-show"><span>Readers see</span><div class="sp-seg" role="radiogroup" aria-label="What readers see">
770
909
  <button type="button" role="radio" data-show="nothing" title="No sign of the slop editor on the published page">Nothing</button>
@@ -782,12 +921,14 @@ const Slop = (() => {
782
921
  ${['n', 's', 'e', 'w', 'ne', 'nw', 'se', 'sw'].map((e) => `<div class="sp-edge" data-edge="${e}" aria-hidden="true"></div>`).join('')}`);
783
922
  aside.hidden = true;
784
923
  aside.setAttribute('aria-label', 'Edit text');
785
- document.body.append(btn, aside);
924
+ document.body.append(aside);
786
925
  const $ = (sel) => aside.querySelector(sel);
787
926
  const body = $('.sp-body');
788
927
  const statusEl = $('.sp-status');
789
- const pageControl = control(() => entries().map(([p]) => p), 'the whole page');
790
- $('.sp-cover-row').append(pageControl);
928
+ aside.classList.add('slop-on'); // the text boxes keep their colors when the page's are off
929
+ const modeBtn = $('.sp-mode');
930
+ editSwitch = $('.sp-colors');
931
+ editSwitch.addEventListener('click', () => { editColors = !editColors; paintShow(); });
791
932
 
792
933
  function status(msg, kind = '', action) {
793
934
  statusEl.textContent = msg;
@@ -802,44 +943,152 @@ const Slop = (() => {
802
943
  ? status('Saved in this browser', '', { label: 'Reset', run: reset })
803
944
  : status(`Saved · version ${text.version}`));
804
945
 
805
- // any change to who wrote what (the slop switch, marking text, deleting a category) can be undone
806
- function withUndo(what, change) {
807
- 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();
808
958
  change();
809
- 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;
810
982
  touched();
811
983
  if (state.tab === 'slop') render(); else numbers();
812
- undo = before;
813
- status(what, '', {
814
- label: 'Undo',
815
- run: () => {
816
- if (!undo) return;
817
- const version = text.version;
818
- text = JSON.parse(undo);
819
- text.version = version;
820
- undo = null;
821
- applyColors();
822
- touched();
823
- render();
824
- },
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);
825
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);
826
1026
  return true;
827
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
+ }
828
1061
 
829
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
830
- sit by its name, and puts the switch at the end (c.pie, c.toggle) */
831
- 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 } = {}) {
832
1069
  const c = el('span', 'sp-ctl', '<span class="sp-pie" role="img"></span>'
833
1070
  + '<button type="button" class="sp-toggle" role="switch"><span class="sp-switch" aria-hidden="true"></span>slop</button>');
834
1071
  const toggle = c.querySelector('.sp-toggle');
835
1072
  toggle.addEventListener('click', (e) => {
836
1073
  e.preventDefault(); // in a section's summary, don't open or close it
837
1074
  const on = toggle.getAttribute('aria-checked') === 'true';
838
- 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
+ }));
839
1086
  if (done) after?.(on);
840
1087
  });
841
1088
  c.pie = c.querySelector('.sp-pie');
842
1089
  c.toggle = toggle;
1090
+ c.paths = paths;
1091
+ c.scope = scope;
843
1092
  controls.push({ el: c, paths });
844
1093
  return c;
845
1094
  }
@@ -853,8 +1102,8 @@ const Slop = (() => {
853
1102
  const on = (m.counts.ai ?? 0) > 0;
854
1103
  toggle.setAttribute('aria-checked', String(on));
855
1104
  toggle.disabled = !on && !m.counts.ok;
856
- toggle.title = on ? 'Slop. Switch it off to approve the AI\'s words as they are'
857
- : 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');
858
1107
  }
859
1108
 
860
1109
  /* categories: a color picker and a name for each, and how much of the page is theirs */
@@ -1370,19 +1619,86 @@ const Slop = (() => {
1370
1619
  b.type = 'button';
1371
1620
  b.addEventListener('pointerdown', (e) => e.preventDefault()); // keep the focus and the selection
1372
1621
  b.addEventListener('click', () => {
1373
- let [s, e] = [input.selectionStart, input.selectionEnd];
1622
+ let [s, e, n] = selOf(input);
1623
+ const at = markedIn(input, paths[0], [s, e]);
1374
1624
  const whole = s === e;
1375
- if (whole) [s, e] = [0, input.value.length];
1376
- 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);
1377
1627
  });
1378
1628
  assignEl.append(b);
1379
1629
  });
1630
+ assignEl.append(newCategory(wrap, input, paths));
1380
1631
  assignLabel(input);
1381
1632
  if (wrap.insert) wrap.insert.before(assignEl); else wrap.append(assignEl); // the + stays last
1382
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 });
1383
1672
  const assignLabel = (input) => {
1384
- 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';
1385
1675
  };
1676
+ // while a selection is being dragged out too, so the row doesn't change under the pointer once it's let go
1677
+ document.addEventListener('selectionchange', () => {
1678
+ const a = document.activeElement;
1679
+ if ((a?.tagName === 'TEXTAREA' && assignEl.parentNode?.contains(a)) || (a === liveEl && assignEl.parentNode === float)) assignLabel(a);
1680
+ });
1681
+
1682
+ /* copying a text's words keeps who wrote them: pasted into a text (here, or in another page's editor), they keep
1683
+ their authors. Words from anywhere else are mine, as typed */
1684
+ const CLIP = 'application/x-slop-editor';
1685
+ let clip = null; // {words, authors}, the last copied here: for a browser that keeps only plain text
1686
+ function copyOut(e, input, path) {
1687
+ const [s, t] = [input.selectionStart, input.selectionEnd];
1688
+ if (s === t || !e.clipboardData) return;
1689
+ clip = { words: input.value.slice(s, t), authors: authorsByChar(get(path)).slice(s, t) };
1690
+ e.preventDefault();
1691
+ e.clipboardData.setData('text/plain', clip.words);
1692
+ e.clipboardData.setData(CLIP, JSON.stringify(clip));
1693
+ if (e.type === 'cut') document.execCommand('delete'); // as an edit, so ⌘Z brings it back
1694
+ }
1695
+ function pastedIn(e) {
1696
+ const words = (e.clipboardData?.getData('text/plain') ?? '').replace(/\r\n?/g, '\n');
1697
+ let c = clip;
1698
+ try { c = JSON.parse(e.clipboardData.getData(CLIP)) ?? clip; } catch { /* plain text only */ }
1699
+ if (!c || c.words !== words || !Array.isArray(c.authors) || c.authors.length !== words.length) return null;
1700
+ return { words, authors: c.authors.map((a) => (typeof a === 'string' && a ? a : 'me')) };
1701
+ }
1386
1702
 
1387
1703
  /* the views */
1388
1704
  const setOf = (path) => sets.find((s) => s.paths.includes(path));
@@ -1446,7 +1762,7 @@ const Slop = (() => {
1446
1762
  }
1447
1763
  // a copy's switch changes that copy only, and says so. A Repeats card's switch changes every copy.
1448
1764
  // The row reads: name and pie, then at the end anything else, the trash can and the switch
1449
- 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) => {
1450
1766
  const others = (setOf(path)?.paths ?? []).filter((p) => p !== path);
1451
1767
  if (!others.length) return;
1452
1768
  const how = approved ? unslop : reslop;
@@ -1454,24 +1770,36 @@ const Slop = (() => {
1454
1770
  label: others.length === 1 ? 'Change it too' : 'Change them too',
1455
1771
  run: () => withUndo(`${approved ? 'Approved' : 'Back to slop:'} ${count(others.length + 1, 'copy', 'copies')}`, () => others.forEach((p) => set(p, how(get(p))))),
1456
1772
  });
1457
- });
1773
+ } });
1458
1774
  row.before(ctl.pie);
1459
1775
  if (listItem) row.append(removeButton(path, wrap));
1460
1776
  row.append(ctl);
1461
1777
  // the stretch a keystroke or a paste replaces: the selection, or nothing at the caret
1462
- 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
+ });
1463
1786
  input.addEventListener('input', (e) => {
1464
1787
  const restoring = /^history(Undo|Redo)$/.test(e.inputType);
1465
- edit(paths(), input, restoring, restoring || e.isComposing || /Composition/.test(e.inputType) ? undefined : input.at);
1788
+ const pasted = e.inputType === 'insertFromPaste' ? input.pasted : null;
1789
+ edit(paths(), input, restoring, restoring || e.isComposing || /Composition/.test(e.inputType) ? undefined : input.at, pasted);
1466
1790
  input.at = undefined;
1791
+ input.pasted = null;
1467
1792
  });
1468
- ['select', 'keyup', 'pointerup'].forEach((t) => input.addEventListener(t, () => assignLabel(input)));
1793
+ input.addEventListener('copy', (e) => copyOut(e, input, paths()[0]));
1794
+ input.addEventListener('cut', (e) => copyOut(e, input, paths()[0]));
1795
+ input.addEventListener('paste', (e) => { input.pasted = pastedIn(e); });
1796
+ ['select', 'selectionchange', 'keyup', 'pointerup'].forEach((t) => input.addEventListener(t, () => assignLabel(input)));
1469
1797
  input.addEventListener('focus', () => { focus(path, all, input, wrap); showAssign(wrap, input, paths()); });
1470
1798
  input.addEventListener('blur', () => {
1471
1799
  mark(false);
1472
1800
  // after the click that moved the focus lands: removing these first would move what's being clicked
1473
1801
  afterClick(() => {
1474
- if (document.activeElement === input) return;
1802
+ if (document.activeElement === input || assignEl.contains(document.activeElement)) return;
1475
1803
  wrap.querySelector('.sp-hint').hidden = true;
1476
1804
  if (assignEl.parentNode === wrap) assignEl.remove();
1477
1805
  });
@@ -1491,11 +1819,15 @@ const Slop = (() => {
1491
1819
  det.dataset.group = key;
1492
1820
  det.open = state.open.has(key) || state.tab === 'hidden'; // there are few, so all of them show
1493
1821
  const all = () => entries(text[key], [key]).map(([p]) => p);
1494
- const ctl = control(all, `"${groupTitle(key)}"`);
1822
+ const ctl = control(all, `"${groupTitle(key)}"`, { id: `group:${key}` });
1495
1823
  det.querySelector('.sp-gname').after(ctl.pie);
1496
1824
  det.querySelector('summary').append(ctl);
1497
1825
  det.addEventListener('toggle', () => {
1498
- if (det.open) { state.open.add(key); det.querySelectorAll('textarea').forEach(grow); } else state.open.delete(key);
1826
+ if (det.open) { state.open.add(key); det.querySelectorAll('textarea').forEach(grow); return; }
1827
+ state.open.delete(key);
1828
+ // closed from its name stuck at the top: back to where the section starts
1829
+ const above = det.getBoundingClientRect().top - body.getBoundingClientRect().top;
1830
+ if (above < 0) body.scrollTop += above;
1499
1831
  });
1500
1832
  paths.forEach((p) => det.append(field(p)));
1501
1833
  if (state.tab === 'all') listRows(key, det);
@@ -1625,7 +1957,7 @@ const Slop = (() => {
1625
1957
 
1626
1958
  function render() {
1627
1959
  FLAGS.forEach((name) => flag(name)); // the elements pointed at may be gone
1628
- controls = [controls.find((c) => c.el === pageControl)];
1960
+ controls = [];
1629
1961
  sets = repeats(entries());
1630
1962
  groupKeys().forEach((k) => { if (!state.known.has(k)) { state.known.add(k); state.open.add(k); } });
1631
1963
  renderCats();
@@ -1679,8 +2011,6 @@ const Slop = (() => {
1679
2011
  const cats = categories();
1680
2012
  const all = entries();
1681
2013
  const page = makeup(all.map(([, v]) => v));
1682
- $('.sp-big b').textContent = percent(page.letters ? (page.counts.ai ?? 0) / page.letters : 0);
1683
- $('.sp-words').textContent = count(page.allWords, 'word');
1684
2014
  aside.querySelectorAll('.sp-seg button').forEach((b) => b.setAttribute('aria-checked', String(b.dataset.show === shows())));
1685
2015
  const revert = $('.sp-cat-revert');
1686
2016
  if (revert) revert.hidden = !Object.values(text._categories ?? {}).some((c) => c.color);
@@ -1688,6 +2018,7 @@ const Slop = (() => {
1688
2018
  row.querySelector('.sp-cat-pct').textContent = percent(page.letters ? (page.counts[row.dataset.id] ?? 0) / page.letters : 0);
1689
2019
  });
1690
2020
  controls.forEach((c) => paintControl(c, cats));
2021
+ if (floatCtl && !controls.some((c) => c.el === floatCtl)) paintControl({ el: floatCtl, paths: floatCtl.paths }, cats);
1691
2022
  body.querySelectorAll('.sp-goto').forEach((go) => {
1692
2023
  const m = makeup([get(go.dataset.path)]);
1693
2024
  go.querySelector('.sp-pie').style.background = gradient(m, cats);
@@ -1725,7 +2056,7 @@ const Slop = (() => {
1725
2056
  paintMeters();
1726
2057
  }
1727
2058
  repaint = () => { if (!aside.hidden) render(); };
1728
- reseen = () => { if (!aside.hidden) body.querySelectorAll('.sp-field').forEach(paintSeen); };
2059
+ reseen = () => { if (!aside.hidden) { body.querySelectorAll('.sp-field').forEach(paintSeen); liven(); } };
1729
2060
  // a text the page doesn't show right now is tagged, with a way to show it if the page says how
1730
2061
  function paintSeen(f) {
1731
2062
  const tag = f.querySelector('.sp-unseen');
@@ -1803,10 +2134,25 @@ const Slop = (() => {
1803
2134
  setTimeout(() => f.classList.remove('sp-flash'), 900);
1804
2135
  }
1805
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
+ }
1806
2151
  const grow = (x) => { x.style.height = 'auto'; x.style.height = `${x.scrollHeight + 2}px`; };
1807
2152
 
1808
2153
  // typing: what you type is yours, the rest keeps its author
1809
- // ⌘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
1810
2156
  const past = new Map(); // path → [value, …], oldest first
1811
2157
  function remember(p) {
1812
2158
  const list = past.get(p) ?? [];
@@ -1815,14 +2161,18 @@ const Slop = (() => {
1815
2161
  past.set(p, list.slice(-200));
1816
2162
  }
1817
2163
  const recall = (p, words) => past.get(p)?.findLast((v) => plain(v) === words);
1818
- function edit(paths, input, restoring, at) {
1819
- undo = null;
2164
+ // `pasted`: words copied from a text, with their authors, now at `at`
2165
+ function edit(paths, input, restoring, at, pasted) {
2166
+ noted = false;
1820
2167
  const f = state.focus;
1821
- [...paths, ...(f?.linked ?? [])].forEach((p) => {
2168
+ const keep = pasted && at && input.value.startsWith(pasted.words, at[0]);
2169
+ const kind = input.value.length < plain(get(paths[0])).length ? 'delete' : 'type';
2170
+ track(() => [...paths, ...(f?.linked ?? [])].forEach((p) => {
1822
2171
  remember(p);
1823
- set(p, applyEdit(get(p), input.value, restoring ? recall(p, input.value) : undefined, at));
2172
+ const next = applyEdit(get(p), input.value, restoring ? recall(p, input.value) : undefined, at);
2173
+ set(p, keep ? overlay(next, at[0], pasted.authors) : next);
1824
2174
  remember(p);
1825
- });
2175
+ }), { at: { path: paths[0], where: 'panel' }, typing: restoring || pasted ? '' : kind, typed: true });
1826
2176
  grow(input);
1827
2177
  if (f?.copies.length && !f.linked) {
1828
2178
  // a copy changed on its own: offer to change the others the same way
@@ -1842,6 +2192,354 @@ const Slop = (() => {
1842
2192
  touched();
1843
2193
  }
1844
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
+
1845
2543
  // saving: only with the Save button (or ⌘S), one request at a time, each carrying the version it was based on.
1846
2544
  // `saved` is the text as of the last save, for the Save button's count and each text's Revert
1847
2545
  let saved = JSON.parse(JSON.stringify(text));
@@ -1878,7 +2576,6 @@ const Slop = (() => {
1878
2576
  const kept = store.set(LOCAL, JSON.stringify({ base: JSON.parse(original).version, baseText: JSON.parse(original), text: JSON.parse(body) }));
1879
2577
  if (!kept) { status("Couldn't save in this browser", 'error'); return; }
1880
2578
  saved = JSON.parse(body);
1881
- undo = null;
1882
2579
  keepDraft();
1883
2580
  savedStatus();
1884
2581
  numbers();
@@ -1893,7 +2590,6 @@ const Slop = (() => {
1893
2590
  if (!res.ok) throw new Error(out || res.statusText);
1894
2591
  text.version = Number(out);
1895
2592
  saved = { ...JSON.parse(body), version: text.version };
1896
- undo = null;
1897
2593
  keepDraft();
1898
2594
  savedStatus();
1899
2595
  } catch (e) {
@@ -1908,14 +2604,16 @@ const Slop = (() => {
1908
2604
  numbers();
1909
2605
  changed();
1910
2606
  keepDraft();
1911
- 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' : '');
1912
2608
  }
1913
2609
  function reset() {
1914
2610
  store.drop(LOCAL);
1915
2611
  session.drop(DRAFT);
1916
2612
  text = JSON.parse(original);
1917
2613
  saved = JSON.parse(original);
1918
- undo = null;
2614
+ undos.length = 0;
2615
+ redos.length = 0;
2616
+ noted = false;
1919
2617
  applyColors();
1920
2618
  changed();
1921
2619
  render();
@@ -1931,10 +2629,10 @@ const Slop = (() => {
1931
2629
  };
1932
2630
  addEventListener('keydown', (e) => {
1933
2631
  if ((e.metaKey || e.ctrlKey) && e.key === 's' && !aside.hidden) { e.preventDefault(); save(); }
1934
- // ⌘Z outside a text undoes the last switch or mark (a text's own ⌘Z undoes its typing)
1935
- 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"]')) {
1936
2634
  e.preventDefault();
1937
- statusEl.querySelector('.sp-link')?.click();
2635
+ step(!e.shiftKey);
1938
2636
  }
1939
2637
  });
1940
2638
  body.addEventListener('pointerdown', (e) => {
@@ -1945,9 +2643,11 @@ const Slop = (() => {
1945
2643
 
1946
2644
  // while the editor is open, a click on a text opens it in the editor
1947
2645
  document.addEventListener('click', (e) => {
1948
- 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;
1949
2647
  const target = e.target.closest('[data-slop], [data-slop-ref], [data-slop-more], [data-slop-attr]');
1950
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; }
1951
2651
  e.preventDefault();
1952
2652
  e.stopPropagation();
1953
2653
  const path = pathOf(target);
@@ -1967,6 +2667,7 @@ const Slop = (() => {
1967
2667
  try { rect = JSON.parse(store.get(RECT)) ?? {}; } catch { /* docked */ }
1968
2668
  function place() {
1969
2669
  aside.removeAttribute('style');
2670
+ if (inPlace) return;
1970
2671
  if (narrow()) {
1971
2672
  if (rect.sheet) aside.style.height = `${clamp(rect.sheet, 200, innerHeight - 16)}px`;
1972
2673
  return;
@@ -2014,7 +2715,7 @@ const Slop = (() => {
2014
2715
  target.addEventListener('pointercancel', up);
2015
2716
  }
2016
2717
  const head = $('.sp-head');
2017
- 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'); });
2018
2719
  head.addEventListener('dblclick', (e) => {
2019
2720
  if (e.target.closest('button')) return;
2020
2721
  rect = {};
@@ -2026,16 +2727,15 @@ const Slop = (() => {
2026
2727
 
2027
2728
  const open = (on) => {
2028
2729
  aside.hidden = !on;
2029
- btn.hidden = on;
2030
2730
  document.documentElement.classList.toggle('slop-editing', on);
2031
2731
  editing = on;
2032
2732
  paintShow();
2033
- if (!on) { mark(false); unreveal(); closePicker(); return; }
2733
+ livePage();
2734
+ if (!on) { mark(false); unreveal(); closePicker(); hideFloat(); return; }
2034
2735
  place();
2035
2736
  render();
2036
2737
  };
2037
- btn.addEventListener('click', () => open(true));
2038
- $('.sp-close').addEventListener('click', () => open(false));
2738
+ modeBtn.addEventListener('click', () => setPlace(!inPlace));
2039
2739
  aside.querySelectorAll('.sp-seg button').forEach((b) => b.addEventListener('click', () => {
2040
2740
  if (b.dataset.show === shows()) return;
2041
2741
  withUndo(`Readers see: ${b.textContent.toLowerCase()}`, () => {
@@ -2044,6 +2744,7 @@ const Slop = (() => {
2044
2744
  });
2045
2745
  }));
2046
2746
  aside.querySelectorAll('.sp-tabs button').forEach((b) => b.addEventListener('click', () => { state.tab = b.dataset.tab; render(); }));
2747
+ setPlace(inPlace);
2047
2748
  savedStatus();
2048
2749
  try {
2049
2750
  const draft = JSON.parse(session.get(DRAFT));
@@ -2054,10 +2755,12 @@ const Slop = (() => {
2054
2755
  open(true);
2055
2756
  status('Unsaved changes from before the reload', 'dirty', {
2056
2757
  label: 'Discard',
2057
- 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(); },
2058
2759
  });
2059
2760
  }
2060
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);
2061
2764
  return { render: () => { if (!aside.hidden) render(); }, touched, open };
2062
2765
  }
2063
2766