slop-editor 0.1.0 → 0.3.0
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/README.md +58 -11
- package/cli.mjs +105 -10
- package/markup.mjs +93 -0
- package/package.json +17 -1
- package/react.mjs +56 -0
- package/slop.css +53 -9
- package/slop.js +487 -74
package/slop.js
CHANGED
|
@@ -11,7 +11,11 @@
|
|
|
11
11
|
Inside any text: [label](url) is a link, **bold**, *italic*, `code`, [[key]] a key cap, {name} a value the page
|
|
12
12
|
fills in (Slop.vars), and \ makes the next character literal.
|
|
13
13
|
|
|
14
|
-
|
|
14
|
+
A blank line starts a new paragraph in a <p>, <li> or <dd>.
|
|
15
|
+
|
|
16
|
+
Elements with data-slop="group.key" are filled from the block. Code renders the rest with Slop.html(path). An
|
|
17
|
+
element with data-slop-list="group" shows each text in that group in a copy of its first child, and the editor can
|
|
18
|
+
add and remove texts there (data-slop-list-ref: the page draws them itself).
|
|
15
19
|
An element with data-slop-meter becomes the Slop-o-meter switch. Under `slop-editor edit`, the page also gets the
|
|
16
20
|
editor, which saves back into the file; with Slop.start({edit: 'local'}) it gets one that saves in the browser. */
|
|
17
21
|
const Slop = (() => {
|
|
@@ -57,16 +61,31 @@ const Slop = (() => {
|
|
|
57
61
|
|
|
58
62
|
// `value` after its plain text became `next` in the editor. An edit is one stretch replaced (typing, deleting,
|
|
59
63
|
// pasting): what both versions share at the start and the end keeps its author, and the new middle is mine.
|
|
60
|
-
// Unless it's an undo or a redo: then `was`, an earlier version whose plain text is `next`, says who wrote it
|
|
61
|
-
|
|
64
|
+
// Unless it's an undo or a redo: then `was`, an earlier version whose plain text is `next`, says who wrote it.
|
|
65
|
+
// `at`, the [start, end) of `value` the edit replaced (the selection typed over), when the editor knows it: typing
|
|
66
|
+
// "c" over a selected "cat" makes that "c" mine, though it matches the letter that was there
|
|
67
|
+
function applyEdit(value, next, was, at) {
|
|
62
68
|
const prev = plain(value);
|
|
63
|
-
|
|
69
|
+
const typedOver = at && at[1] > at[0];
|
|
70
|
+
if (prev === next && !typedOver) return value;
|
|
64
71
|
let start = 0;
|
|
65
|
-
while (start < prev.length && start < next.length && prev[start] === next[start]) start++;
|
|
66
72
|
let end = 0;
|
|
67
|
-
|
|
68
|
-
|
|
73
|
+
if (at && next.startsWith(prev.slice(0, at[0])) && next.endsWith(prev.slice(at[1])) && next.length - (prev.length - at[1]) >= at[0]) {
|
|
74
|
+
start = at[0];
|
|
75
|
+
end = prev.length - at[1];
|
|
76
|
+
} else {
|
|
77
|
+
while (start < prev.length && start < next.length && prev[start] === next[start]) start++;
|
|
78
|
+
while (end < prev.length - start && end < next.length - start
|
|
79
|
+
&& prev[prev.length - 1 - end] === next[next.length - 1 - end]) end++;
|
|
80
|
+
}
|
|
69
81
|
const authors = authorsByChar(value);
|
|
82
|
+
if (was != null && plain(was) === next) {
|
|
83
|
+
// an undo takes back what was typed: my letters at the edges of the stretch that the earlier version doesn't
|
|
84
|
+
// have as mine (an "a" typed over "agent" matches the "a" there, so it looks shared) go back with it
|
|
85
|
+
const old = authorsByChar(was);
|
|
86
|
+
while (start > 0 && authors[start - 1] === 'me' && old[start - 1] !== 'me') start--;
|
|
87
|
+
while (end > 0 && authors[prev.length - end] === 'me' && old[next.length - end] !== 'me') end--;
|
|
88
|
+
}
|
|
70
89
|
const middle = was != null && plain(was) === next
|
|
71
90
|
? authorsByChar(was).slice(start, next.length - end)
|
|
72
91
|
: new Array(next.length - start - end).fill('me');
|
|
@@ -128,6 +147,20 @@ const Slop = (() => {
|
|
|
128
147
|
return out;
|
|
129
148
|
}
|
|
130
149
|
|
|
150
|
+
// a text in paragraphs: split at blank lines, each keeping its authors. Without a blank line it's one paragraph
|
|
151
|
+
function paragraphsOf(value) {
|
|
152
|
+
const text = plain(value);
|
|
153
|
+
const authors = authorsByChar(value);
|
|
154
|
+
const spans = [];
|
|
155
|
+
const gap = /\n[ \t]*\n\s*/g;
|
|
156
|
+
let at = 0;
|
|
157
|
+
for (let m; (m = gap.exec(text));) { spans.push([at, m.index]); at = m.index + m[0].length; }
|
|
158
|
+
if (!spans.length) return [value];
|
|
159
|
+
spans.push([at, text.length]);
|
|
160
|
+
const parts = spans.map(([s, e]) => fromChars(text.slice(s, e), authors.slice(s, e))).filter((p) => plain(p).trim());
|
|
161
|
+
return parts.length ? parts : [value];
|
|
162
|
+
}
|
|
163
|
+
|
|
131
164
|
// values the page fills in: {html, data} (data: a fact, shown in the data color; otherwise it takes the color of
|
|
132
165
|
// whoever wrote the {name}), or a plain string or number (a fact)
|
|
133
166
|
const vars = {};
|
|
@@ -229,7 +262,7 @@ const Slop = (() => {
|
|
|
229
262
|
return [...byWords].filter(([, paths]) => paths.length > 1).map(([words, paths]) => ({ words, paths }));
|
|
230
263
|
}
|
|
231
264
|
|
|
232
|
-
const core = { BUILTIN, plain, applyEdit, reslop, unslop, assign, reattribute, runs, readable, render, makeup, share, percent, repeats, wordsOf, vars };
|
|
265
|
+
const core = { BUILTIN, plain, applyEdit, reslop, unslop, assign, reattribute, runs, readable, render, makeup, share, percent, repeats, wordsOf, paragraphsOf, vars };
|
|
233
266
|
if (typeof document === 'undefined') return core; // Node (the CLI and the tests) only needs the format
|
|
234
267
|
|
|
235
268
|
/* ---------- the block ---------- */
|
|
@@ -251,6 +284,9 @@ const Slop = (() => {
|
|
|
251
284
|
if (!isText(node)) { console.warn(`slop: no text at ${dotted(path)}`); return ''; }
|
|
252
285
|
return node;
|
|
253
286
|
}
|
|
287
|
+
const nodeAt = (root, path) => keysOf(path).reduce((node, key) => node?.[key], root);
|
|
288
|
+
// the keys of a group's texts, in order
|
|
289
|
+
const textKeys = (node) => (node && typeof node === 'object' && !isText(node) ? Object.keys(node).filter((k) => isText(node[k])) : []);
|
|
254
290
|
function set(path, value) {
|
|
255
291
|
const keys = keysOf(path);
|
|
256
292
|
let node = text;
|
|
@@ -266,12 +302,34 @@ const Slop = (() => {
|
|
|
266
302
|
});
|
|
267
303
|
}
|
|
268
304
|
const groupKeys = () => Object.keys(text).filter((k) => !isMeta(k) && text[k] && (isText(text[k]) || typeof text[k] === 'object'));
|
|
269
|
-
|
|
305
|
+
// the texts an element holds in its attributes, from data-slop-attr="alt:hero.photo title:hero.tip": [[name, path]]
|
|
306
|
+
const attrsOf = (x) => (x.dataset.slopAttr ?? '').split(/\s+/).map((s) => [s.slice(0, s.indexOf(':')), s.slice(s.indexOf(':') + 1)]).filter(([n, p]) => n && p);
|
|
307
|
+
// the elements that show a text: [data-slop] ones, which fill() writes, [data-slop-ref] ones, which the page writes
|
|
308
|
+
// itself (words inside a button or a link it builds) but the editor can still find, [data-slop-more] ones (the
|
|
309
|
+
// paragraphs after a blank line) and [data-slop-attr] ones
|
|
310
|
+
const elementsOf = (path) => {
|
|
311
|
+
const at = dotted(path);
|
|
312
|
+
const q = CSS.escape(at);
|
|
313
|
+
return [...document.querySelectorAll(`[data-slop="${q}"], [data-slop-ref="${q}"], [data-slop-more="${q}"], [data-slop-attr*=":${q}"]`)]
|
|
314
|
+
.filter((x) => x.dataset.slop === at || x.dataset.slopRef === at || x.dataset.slopMore === at || attrsOf(x).some(([, p]) => p === at));
|
|
315
|
+
};
|
|
316
|
+
const pathOf = (x) => x.dataset.slop || x.dataset.slopRef || x.dataset.slopMore || attrsOf(x)[0]?.[1];
|
|
317
|
+
// a text the page has but doesn't show as words (alt text, a tooltip, a label): the attribute it's in, or ''
|
|
318
|
+
function attrOf(path) {
|
|
319
|
+
const at = dotted(path);
|
|
320
|
+
for (const x of document.querySelectorAll('[data-slop-attr]')) {
|
|
321
|
+
const hit = attrsOf(x).find(([, p]) => p === at);
|
|
322
|
+
if (hit) return hit[0];
|
|
323
|
+
}
|
|
324
|
+
return '';
|
|
325
|
+
}
|
|
270
326
|
|
|
271
327
|
// texts the page's code has rendered (Slop.html, Slop.words): with the [data-slop] elements, what's on the page
|
|
272
328
|
const rendered = new Set();
|
|
273
329
|
const html = (path, local) => { rendered.add(dotted(path)); return render(get(path), local); };
|
|
274
330
|
const words = (path, local) => { rendered.add(dotted(path)); return readable(get(path), local); };
|
|
331
|
+
// the text as HTML, one string per paragraph, for code that draws a <p> for each
|
|
332
|
+
const paragraphs = (path, local) => { rendered.add(dotted(path)); return paragraphsOf(get(path)).map((v) => render(v, local)); };
|
|
275
333
|
const onPage = (path) => rendered.has(dotted(path)) || elementsOf(path).length > 0;
|
|
276
334
|
// how to show a text the page shows only some of the time: Slop.reveal(path, fn), where fn puts the page in a state
|
|
277
335
|
// that shows it and returns a function that undoes that. A group's key covers all its texts
|
|
@@ -279,16 +337,106 @@ const Slop = (() => {
|
|
|
279
337
|
const reveal = (path, fn) => { revealers.set(dotted(path), fn); };
|
|
280
338
|
const revealerOf = (path) => revealers.get(dotted(path)) ?? revealers.get(keysOf(path)[0]);
|
|
281
339
|
// fill every [data-slop] element (data-slop-vars: a JSON object of extra values)
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
340
|
+
// fill an element: its words from data-slop, its attributes from data-slop-attr (as plain text)
|
|
341
|
+
// a <p>, <li> or <dd> shows a text's first paragraph, and a copy of it after it shows each of the others. An
|
|
342
|
+
// element whose text is empty gets .slop-empty, which hides it
|
|
343
|
+
const SPLITS = /^(P|LI|DD)$/;
|
|
344
|
+
const spills = new WeakMap(); // element → the copies after it
|
|
345
|
+
const ownerOf = new WeakMap(); // copy → its element
|
|
346
|
+
function fillOne(el) {
|
|
347
|
+
const local = el.dataset.slopVars ? JSON.parse(el.dataset.slopVars) : undefined;
|
|
348
|
+
if (el.dataset.slop) {
|
|
349
|
+
const value = get(el.dataset.slop);
|
|
350
|
+
const parts = SPLITS.test(el.tagName) ? paragraphsOf(value) : [value];
|
|
351
|
+
const h = render(parts[0], local);
|
|
286
352
|
if (el.innerHTML !== h) el.innerHTML = h;
|
|
353
|
+
el.classList.toggle('slop-empty', !plain(value).trim());
|
|
354
|
+
spill(el, parts.slice(1).map((v) => render(v, local)));
|
|
355
|
+
}
|
|
356
|
+
attrsOf(el).forEach(([name, path]) => {
|
|
357
|
+
const v = readable(get(path), local);
|
|
358
|
+
if (el.getAttribute(name) !== v) el.setAttribute(name, v);
|
|
359
|
+
});
|
|
360
|
+
}
|
|
361
|
+
function spill(el, htmls) {
|
|
362
|
+
const copies = spills.get(el) ?? [];
|
|
363
|
+
while (copies.length > htmls.length) copies.pop().remove();
|
|
364
|
+
htmls.forEach((h, i) => {
|
|
365
|
+
let c = copies[i];
|
|
366
|
+
if (!c) {
|
|
367
|
+
c = el.cloneNode(false);
|
|
368
|
+
['id', 'data-slop', 'data-slop-attr'].forEach((a) => c.removeAttribute(a));
|
|
369
|
+
c.classList.remove('slop-focus', 'slop-copy', 'slop-empty');
|
|
370
|
+
ownerOf.set(c, el);
|
|
371
|
+
copies.push(c);
|
|
372
|
+
}
|
|
373
|
+
c.dataset.slopMore = el.dataset.slop;
|
|
374
|
+
if (c.innerHTML !== h) c.innerHTML = h;
|
|
375
|
+
const before = i ? copies[i - 1] : el;
|
|
376
|
+
if (before.nextElementSibling !== c) before.after(c);
|
|
377
|
+
});
|
|
378
|
+
if (copies.length) spills.set(el, copies); else spills.delete(el);
|
|
379
|
+
}
|
|
380
|
+
// a list: an element with data-slop-list="group" shows each text in that group, in order, in a copy of its first
|
|
381
|
+
// child. (With data-slop-list-ref, the page draws them itself.) Either way, the editor can add and remove texts there
|
|
382
|
+
const templates = new WeakMap(); // list → the element its texts are copies of
|
|
383
|
+
function fillList(box) {
|
|
384
|
+
const at = box.dataset.slopList;
|
|
385
|
+
if (!templates.has(box)) {
|
|
386
|
+
if (!box.firstElementChild) return;
|
|
387
|
+
const t = box.firstElementChild.cloneNode(false);
|
|
388
|
+
['id', 'data-slop'].forEach((a) => t.removeAttribute(a));
|
|
389
|
+
templates.set(box, t);
|
|
390
|
+
}
|
|
391
|
+
const paths = textKeys(nodeAt(text, at)).map((k) => `${at}.${k}`);
|
|
392
|
+
const have = new Map([...box.children].filter((x) => x.dataset.slop).map((x) => [x.dataset.slop, x]));
|
|
393
|
+
have.forEach((x, p) => { if (!paths.includes(p)) { spill(x, []); x.remove(); } });
|
|
394
|
+
let last = null;
|
|
395
|
+
paths.forEach((p) => {
|
|
396
|
+
let x = have.get(p);
|
|
397
|
+
if (!x) {
|
|
398
|
+
x = templates.get(box).cloneNode(false);
|
|
399
|
+
x.dataset.slop = p;
|
|
400
|
+
}
|
|
401
|
+
if (last ? last.nextElementSibling !== x : box.firstElementChild !== x) (last ? last.after(x) : box.prepend(x));
|
|
402
|
+
last = spills.get(x)?.at(-1) ?? x;
|
|
403
|
+
});
|
|
404
|
+
}
|
|
405
|
+
const fill = (root = document) => {
|
|
406
|
+
root.querySelectorAll('[data-slop-list]').forEach(fillList);
|
|
407
|
+
root.querySelectorAll('[data-slop], [data-slop-attr]').forEach(fillOne);
|
|
408
|
+
// paragraphs whose element the page took away, or no longer shows that text in
|
|
409
|
+
root.querySelectorAll('[data-slop-more]').forEach((c) => {
|
|
410
|
+
const el = ownerOf.get(c);
|
|
411
|
+
if (!el?.isConnected || el.dataset.slop !== c.dataset.slopMore) c.remove();
|
|
287
412
|
});
|
|
413
|
+
};
|
|
414
|
+
// the editor's "not on the page" tags, checked again once the page has drawn what changed (a text just added or
|
|
415
|
+
// restored has no element until then, and a single-page app draws later still)
|
|
416
|
+
let reseen = () => {};
|
|
417
|
+
let seenPending = false;
|
|
418
|
+
const seenSoon = () => {
|
|
419
|
+
if (seenPending) return;
|
|
420
|
+
seenPending = true;
|
|
421
|
+
requestAnimationFrame(() => { seenPending = false; reseen(); });
|
|
422
|
+
};
|
|
423
|
+
// the [data-slop] elements and meters in what the page added after start (a single-page app draws late)
|
|
424
|
+
function added(n) {
|
|
425
|
+
if (n.nodeType !== 1 || n.closest('.slop-panel')) return;
|
|
426
|
+
seenSoon();
|
|
427
|
+
if (n.matches('[data-slop-list]')) fillList(n);
|
|
428
|
+
if (n.matches('[data-slop], [data-slop-attr]')) fillOne(n);
|
|
429
|
+
fill(n);
|
|
430
|
+
if (n.matches('[data-slop-meter]')) meter(n);
|
|
431
|
+
n.querySelectorAll('[data-slop-meter]').forEach(meter);
|
|
288
432
|
}
|
|
289
433
|
|
|
290
434
|
const listeners = [];
|
|
291
|
-
|
|
435
|
+
// returns a function that stops calling fn
|
|
436
|
+
const onChange = (fn) => {
|
|
437
|
+
listeners.push(fn);
|
|
438
|
+
return () => { const i = listeners.indexOf(fn); if (i >= 0) listeners.splice(i, 1); };
|
|
439
|
+
};
|
|
292
440
|
let pending = false;
|
|
293
441
|
function changed() { // after an edit: refill the page, then let the page redo whatever it built from the text
|
|
294
442
|
if (pending) return;
|
|
@@ -298,6 +446,7 @@ const Slop = (() => {
|
|
|
298
446
|
fill();
|
|
299
447
|
listeners.forEach((fn) => { try { fn(); } catch (e) { console.error(e); } });
|
|
300
448
|
paintMeters();
|
|
449
|
+
seenSoon();
|
|
301
450
|
});
|
|
302
451
|
}
|
|
303
452
|
|
|
@@ -337,14 +486,18 @@ const Slop = (() => {
|
|
|
337
486
|
}
|
|
338
487
|
const swatch = (cat) => cat.color ?? ink();
|
|
339
488
|
|
|
340
|
-
// the colors go in a stylesheet of their own: each category's words
|
|
341
|
-
//
|
|
489
|
+
// the colors go in a stylesheet of their own: each category's words inside a .slop-on (the page, while the
|
|
490
|
+
// Slop-o-meter is on, or a section whose own switch is) but not inside a .slop-off (a section switched off), and
|
|
491
|
+
// --slop-c-<id> for anything else that wants them. Inside a [data-slop-only="<id>"] (a meter's tag is pointed at),
|
|
492
|
+
// everyone else's words are dimmed. :where keeps these as easy to override as html.slop-on .slop-<id> was
|
|
342
493
|
let sheet = null;
|
|
343
494
|
function applyColors() {
|
|
344
495
|
sheet ??= document.head.appendChild(Object.assign(document.createElement('style'), { id: 'slop-colors' }));
|
|
345
|
-
const
|
|
496
|
+
const all = categories();
|
|
497
|
+
const cats = all.filter((c) => c.color);
|
|
346
498
|
sheet.textContent = `:root{${cats.map((c) => `--${cls(c.id).replace('slop-', 'slop-c-')}:${c.color}`).join(';')}}\n`
|
|
347
|
-
+ cats.map((c) =>
|
|
499
|
+
+ cats.map((c) => `:where(.slop-on) .${cls(c.id)}:not(:where(.slop-off) .${cls(c.id)}){color:${c.color}}`).join('\n')
|
|
500
|
+
+ `\n${all.map((c) => `[data-slop-only]:not([data-slop-only="${CSS.escape(c.id)}"]) .${cls(c.id)}{opacity:.3}`).join('\n')}`;
|
|
348
501
|
}
|
|
349
502
|
|
|
350
503
|
// a pie of what these texts are made of, and the same in words for its tooltip
|
|
@@ -385,55 +538,92 @@ const Slop = (() => {
|
|
|
385
538
|
|
|
386
539
|
/* ---------- Slop-o-meter: a switch, a pie of what the page is made of, and what its colors mean ---------- */
|
|
387
540
|
|
|
388
|
-
const
|
|
389
|
-
get: (k) => { try { return
|
|
390
|
-
set: (k, v) => { try {
|
|
391
|
-
drop: (k) => { try {
|
|
392
|
-
};
|
|
541
|
+
const storage = (area) => ({
|
|
542
|
+
get: (k) => { try { return area().getItem(k); } catch { return null; } },
|
|
543
|
+
set: (k, v) => { try { area().setItem(k, v); } catch { /* optional */ } },
|
|
544
|
+
drop: (k) => { try { area().removeItem(k); } catch { /* optional */ } },
|
|
545
|
+
});
|
|
546
|
+
const store = storage(() => localStorage);
|
|
547
|
+
const session = storage(() => sessionStorage); // this tab only: the unsaved draft
|
|
393
548
|
// what readers see is the page's choice, "nothing" unless it says otherwise. While the editor is open, its
|
|
394
549
|
// author sees the colors whatever readers get
|
|
395
550
|
const SHOW = ['nothing', 'pie', 'colors'];
|
|
396
551
|
const shows = () => (SHOW.includes(text._show) ? text._show : 'nothing');
|
|
397
552
|
const meters = [];
|
|
553
|
+
const built = new WeakMap(); // element → its meter
|
|
398
554
|
let meterOn = false;
|
|
399
555
|
let editing = false;
|
|
400
556
|
function setMeter(on) {
|
|
401
557
|
meterOn = on;
|
|
402
558
|
paintShow();
|
|
403
559
|
}
|
|
560
|
+
// a meter with a path (data-slop-meter="games.othello") measures the texts under it, and its switch colors only
|
|
561
|
+
// its section: the closest [data-slop-section], or its parent. A bare one measures the page and switches it
|
|
562
|
+
const inScope = (at) => ([path]) => !at || path === at || path.startsWith(`${at}.`);
|
|
563
|
+
const sectionOf = (m) => (m.at && m.el.parentElement ? m.el.closest('[data-slop-section]') ?? m.el.parentElement : document.documentElement);
|
|
404
564
|
function paintShow() {
|
|
405
565
|
const mode = shows();
|
|
406
566
|
document.documentElement.classList.toggle('slop-on', editing || (mode === 'colors' && meterOn));
|
|
407
567
|
meters.forEach((m) => {
|
|
408
568
|
m.el.dataset.show = mode;
|
|
409
|
-
|
|
569
|
+
const section = sectionOf(m);
|
|
570
|
+
if (m.section && m.section !== section) m.section.classList.remove('slop-on', 'slop-off');
|
|
571
|
+
m.section = section;
|
|
572
|
+
// a section's switch follows the page's until it's flipped. The editor shows the author every color
|
|
573
|
+
if (m.at) {
|
|
574
|
+
const own = mode === 'colors' && !editing ? m.own : null;
|
|
575
|
+
section.classList.toggle('slop-on', own === true);
|
|
576
|
+
section.classList.toggle('slop-off', own === false);
|
|
577
|
+
}
|
|
578
|
+
m.btn.setAttribute('aria-pressed', String(m.own ?? meterOn));
|
|
410
579
|
});
|
|
411
580
|
}
|
|
412
581
|
function paintMeters() {
|
|
582
|
+
// a meter the page took out of the document is dropped; it comes back if the page puts it back
|
|
583
|
+
meters.splice(0, meters.length, ...meters.filter((m) => m.el.isConnected));
|
|
413
584
|
paintShow();
|
|
414
585
|
if (!meters.length) return;
|
|
415
586
|
const cats = categories();
|
|
416
|
-
const
|
|
417
|
-
|
|
587
|
+
const all = entries();
|
|
588
|
+
const byScope = new Map();
|
|
589
|
+
meters.forEach(({ at, pie, legend }) => {
|
|
590
|
+
if (!byScope.has(at)) byScope.set(at, makeup(all.filter(inScope(at)).map(([, v]) => v)));
|
|
591
|
+
const m = byScope.get(at);
|
|
418
592
|
pie.style.background = gradient(m, cats);
|
|
419
593
|
pie.title = breakdown(m, cats);
|
|
420
594
|
pie.setAttribute('aria-label', pie.title);
|
|
421
|
-
// each category in its own color, with its share of the
|
|
595
|
+
// each category in its own color, with its share of the text
|
|
422
596
|
legend.innerHTML = cats.filter((c) => m.counts[c.id])
|
|
423
|
-
.map((c) => `<span class="slop-key" style="color:${swatch(c)}"><i style="background:${swatch(c)}"></i>${esc(c.label)}<b class="slop-pct">${percent(m.counts[c.id] / m.letters)}</b></span>`).join('');
|
|
597
|
+
.map((c) => `<span class="slop-key" tabindex="0" data-id="${esc(c.id)}" style="color:${swatch(c)}"><i style="background:${swatch(c)}"></i>${esc(c.label)}<b class="slop-pct">${percent(m.counts[c.id] / m.letters)}</b></span>`).join('');
|
|
424
598
|
});
|
|
425
599
|
}
|
|
426
600
|
function buildMeter(el) {
|
|
427
601
|
el.classList.add('slop-meter');
|
|
428
602
|
el.innerHTML = '<button type="button" class="slop-meter-btn" aria-pressed="false"><span class="slop-switch" aria-hidden="true"></span>Slop-o-meter</button>'
|
|
429
603
|
+ '<span class="slop-meter-key"><span class="slop-pie" role="img"></span><span class="slop-legend"></span></span>';
|
|
430
|
-
const m = { el, btn: el.querySelector('button'), pie: el.querySelector('.slop-pie'), legend: el.querySelector('.slop-legend') };
|
|
604
|
+
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') };
|
|
431
605
|
m.btn.addEventListener('click', () => {
|
|
432
|
-
const on = !meterOn;
|
|
606
|
+
const on = !(m.own ?? meterOn);
|
|
607
|
+
if (m.at) { m.own = on; paintShow(); return; } // only the page-wide choice is remembered
|
|
433
608
|
setMeter(on);
|
|
434
609
|
store.set('slop-o-meter', on ? 'on' : 'off');
|
|
435
610
|
});
|
|
436
|
-
|
|
611
|
+
// pointing at a tag dims everyone else's words, in the meter's section
|
|
612
|
+
const only = (e) => {
|
|
613
|
+
const key = e.type === 'mouseover' || e.type === 'focusin' ? e.target.closest('.slop-key') : null;
|
|
614
|
+
const section = m.section ?? sectionOf(m);
|
|
615
|
+
if (key) section.dataset.slopOnly = key.dataset.id;
|
|
616
|
+
else delete section.dataset.slopOnly;
|
|
617
|
+
};
|
|
618
|
+
['mouseover', 'mouseout', 'focusin', 'focusout'].forEach((type) => m.legend.addEventListener(type, only));
|
|
619
|
+
built.set(el, m);
|
|
620
|
+
return m;
|
|
621
|
+
}
|
|
622
|
+
// build a meter (or take back one the page moved), and paint it
|
|
623
|
+
function meter(el) {
|
|
624
|
+
const m = built.get(el) ?? buildMeter(el);
|
|
625
|
+
if (!meters.includes(m)) meters.push(m);
|
|
626
|
+
paintMeters();
|
|
437
627
|
}
|
|
438
628
|
|
|
439
629
|
/* ---------- the editor ---------- */
|
|
@@ -450,15 +640,26 @@ const Slop = (() => {
|
|
|
450
640
|
const title = node && !isText(node) && isText(node.title) ? readable(node.title) : '';
|
|
451
641
|
return title && title.length <= 32 ? title : human(key);
|
|
452
642
|
};
|
|
643
|
+
// the groups the page shows as lists, where the editor can add and remove texts
|
|
644
|
+
const listed = () => new Set([...document.querySelectorAll('[data-slop-list], [data-slop-list-ref]')].map((x) => x.dataset.slopList || x.dataset.slopListRef));
|
|
645
|
+
// keys[i], for people. In a list, a paragraph is named by where it is: "Paragraph 3", even when its key is p7
|
|
646
|
+
function keyName(keys, i) {
|
|
647
|
+
const group = keys.slice(0, i).join('.');
|
|
648
|
+
if (!/^p\d+$/.test(keys[i]) || !listed().has(group)) return human(keys[i]);
|
|
649
|
+
return `Paragraph ${textKeys(nodeAt(text, group)).indexOf(keys[i]) + 1}`;
|
|
650
|
+
}
|
|
453
651
|
// where a text is, for people: "Introduction · Paragraph 2"
|
|
454
652
|
const where = (path) => {
|
|
455
|
-
const
|
|
456
|
-
return [groupTitle(
|
|
653
|
+
const keys = keysOf(path);
|
|
654
|
+
return [groupTitle(keys[0]), ...keys.slice(1).map((k, i) => keyName(keys, i + 1))].join(' · ');
|
|
457
655
|
};
|
|
458
656
|
const count = (n, one, many = `${one}s`) => `${n.toLocaleString()} ${n === 1 ? one : many}`;
|
|
459
657
|
const isLong = (path, value) => plain(value).length > 48 || /^p\d+$/.test(keysOf(path).at(-1));
|
|
460
658
|
const el = (tag, className, html = '') => Object.assign(document.createElement(tag), { className, innerHTML: html });
|
|
461
659
|
|
|
660
|
+
// what a hidden text is, by the attribute it's in
|
|
661
|
+
const KINDS = { alt: 'alt text', title: 'tooltip', 'aria-label': 'label', 'aria-description': 'description', placeholder: 'placeholder' };
|
|
662
|
+
|
|
462
663
|
// the editor opens on repeated text that still has slop, or on any text that does, or on everything
|
|
463
664
|
const slopIn = (path) => (makeup([get(path)]).counts.ai ?? 0) > 0;
|
|
464
665
|
const startTab = () => (repeats(entries()).some((s) => s.paths.some(slopIn)) ? 'repeats' : entries().some(([p]) => slopIn(p)) ? 'slop' : 'all');
|
|
@@ -494,6 +695,7 @@ const Slop = (() => {
|
|
|
494
695
|
<button type="button" role="tab" data-tab="repeats">Repeats <span></span></button>
|
|
495
696
|
<button type="button" role="tab" data-tab="slop">Slop left <span></span></button>
|
|
496
697
|
<button type="button" role="tab" data-tab="all">All <span></span></button>
|
|
698
|
+
<button type="button" role="tab" data-tab="hidden" title="Words the page has but doesn't show: alt text, tooltips, labels">Hidden <span></span></button>
|
|
497
699
|
</div>
|
|
498
700
|
<div class="sp-body" role="tabpanel"></div>
|
|
499
701
|
${['n', 's', 'e', 'w', 'ne', 'nw', 'se', 'sw'].map((e) => `<div class="sp-edge" data-edge="${e}" aria-hidden="true"></div>`).join('')}`);
|
|
@@ -543,7 +745,8 @@ const Slop = (() => {
|
|
|
543
745
|
return true;
|
|
544
746
|
}
|
|
545
747
|
|
|
546
|
-
/* the slop switch, next to a pie of what the texts are made of
|
|
748
|
+
/* 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
|
|
749
|
+
sit by its name, and puts the switch at the end (c.pie, c.toggle) */
|
|
547
750
|
function control(paths, what, after) {
|
|
548
751
|
const c = el('span', 'sp-ctl', '<span class="sp-pie" role="img"></span>'
|
|
549
752
|
+ '<button type="button" class="sp-toggle" role="switch"><span class="sp-switch" aria-hidden="true"></span>slop</button>');
|
|
@@ -554,16 +757,18 @@ const Slop = (() => {
|
|
|
554
757
|
const done = withUndo(on ? `Approved ${what}` : `Back to slop: ${what}`, () => paths().forEach((p) => set(p, on ? unslop(get(p)) : reslop(get(p)))));
|
|
555
758
|
if (done) after?.(on);
|
|
556
759
|
});
|
|
760
|
+
c.pie = c.querySelector('.sp-pie');
|
|
761
|
+
c.toggle = toggle;
|
|
557
762
|
controls.push({ el: c, paths });
|
|
558
763
|
return c;
|
|
559
764
|
}
|
|
560
765
|
function paintControl({ el: c, paths }, cats) {
|
|
561
|
-
const m = makeup(paths().map(
|
|
562
|
-
const pie = c
|
|
766
|
+
const m = makeup(paths().map((p) => valueAt(text, p) ?? '')); // a text just taken out is painted once more
|
|
767
|
+
const { pie } = c;
|
|
563
768
|
pie.style.background = gradient(m, cats);
|
|
564
769
|
pie.title = breakdown(m, cats);
|
|
565
770
|
pie.setAttribute('aria-label', pie.title);
|
|
566
|
-
const toggle = c
|
|
771
|
+
const { toggle } = c;
|
|
567
772
|
const on = (m.counts.ai ?? 0) > 0;
|
|
568
773
|
toggle.setAttribute('aria-checked', String(on));
|
|
569
774
|
toggle.disabled = !on && !m.counts.ok;
|
|
@@ -660,7 +865,7 @@ const Slop = (() => {
|
|
|
660
865
|
assignEl.append(b);
|
|
661
866
|
});
|
|
662
867
|
assignLabel(input);
|
|
663
|
-
wrap.append(assignEl);
|
|
868
|
+
if (wrap.insert) wrap.insert.before(assignEl); else wrap.append(assignEl); // the + stays last
|
|
664
869
|
}
|
|
665
870
|
const assignLabel = (input) => {
|
|
666
871
|
if (assignEl.firstChild) assignEl.firstChild.textContent = input.selectionStart === input.selectionEnd ? 'Mark all as' : 'Mark selection as';
|
|
@@ -694,11 +899,13 @@ const Slop = (() => {
|
|
|
694
899
|
const wrap = el('div', 'sp-field');
|
|
695
900
|
wrap.dataset.path = path;
|
|
696
901
|
const fid = `sp-${path.replace(/\W/g, '-')}${all ? '-all' : ''}`;
|
|
697
|
-
const
|
|
902
|
+
const keys = keysOf(path);
|
|
903
|
+
const name = all ? `${all.paths.length} copies` : keys.slice(1).map((k, i) => keyName(keys, i + 1)).join(' · ') || human(path);
|
|
698
904
|
wrap.innerHTML = `<div class="sp-flabel"><label for="${fid}">${esc(name)}</label>`
|
|
699
|
-
+ '<button type="button" class="sp-unseen" hidden></button></div>'
|
|
700
|
-
+ `<textarea id="${fid}" rows="1" spellcheck="true"></textarea
|
|
701
|
-
|
|
905
|
+
+ '<span class="sp-fend"><span class="sp-kind" hidden></span><button type="button" class="sp-unseen" hidden></button></span></div>'
|
|
906
|
+
+ `<div class="sp-ink"><div class="sp-mirror" aria-hidden="true"></div><textarea id="${fid}" rows="1" spellcheck="true"></textarea></div>`
|
|
907
|
+
+ '<p class="sp-hint" hidden></p>';
|
|
908
|
+
const row = wrap.querySelector('.sp-fend'); // the meter sits by the name; the rest at the end of the row
|
|
702
909
|
const input = wrap.querySelector('textarea');
|
|
703
910
|
input.value = plain(value);
|
|
704
911
|
if (!isLong(path, value)) input.addEventListener('keydown', (e) => { if (e.key === 'Enter') e.preventDefault(); });
|
|
@@ -711,6 +918,12 @@ const Slop = (() => {
|
|
|
711
918
|
withUndo(`Reverted "${all ? all.words : where(path)}"`, () => paths().forEach((p) => { if (savedAt(p) !== undefined) set(p, savedAt(p)); }));
|
|
712
919
|
render();
|
|
713
920
|
});
|
|
921
|
+
const group = keys.slice(0, -1).join('.');
|
|
922
|
+
const listItem = !all && group && listed().has(group);
|
|
923
|
+
if (listItem) {
|
|
924
|
+
wrap.insert = plusRow(path, group);
|
|
925
|
+
wrap.append(wrap.insert);
|
|
926
|
+
}
|
|
714
927
|
row.append(revert);
|
|
715
928
|
if (!all) {
|
|
716
929
|
const rep = el('button', 'sp-rep');
|
|
@@ -718,8 +931,9 @@ const Slop = (() => {
|
|
|
718
931
|
rep.addEventListener('click', () => { const s = setOf(path); if (s) show('repeats', s.paths[0]); });
|
|
719
932
|
row.append(rep);
|
|
720
933
|
}
|
|
721
|
-
// a copy's switch changes that copy only, and says so. A Repeats card's switch changes every copy
|
|
722
|
-
row
|
|
934
|
+
// a copy's switch changes that copy only, and says so. A Repeats card's switch changes every copy.
|
|
935
|
+
// The row reads: name and pie, then at the end anything else, the trash can and the switch
|
|
936
|
+
const ctl = control(paths, all ? count(all.paths.length, 'copy', 'copies') : `"${where(path)}"`, all ? null : (approved) => {
|
|
723
937
|
const others = (setOf(path)?.paths ?? []).filter((p) => p !== path);
|
|
724
938
|
if (!others.length) return;
|
|
725
939
|
const how = approved ? unslop : reslop;
|
|
@@ -727,8 +941,17 @@ const Slop = (() => {
|
|
|
727
941
|
label: others.length === 1 ? 'Change it too' : 'Change them too',
|
|
728
942
|
run: () => withUndo(`${approved ? 'Approved' : 'Back to slop:'} ${count(others.length + 1, 'copy', 'copies')}`, () => others.forEach((p) => set(p, how(get(p))))),
|
|
729
943
|
});
|
|
730
|
-
})
|
|
731
|
-
|
|
944
|
+
});
|
|
945
|
+
row.before(ctl.pie);
|
|
946
|
+
if (listItem) row.append(removeButton(path, wrap));
|
|
947
|
+
row.append(ctl);
|
|
948
|
+
// the stretch a keystroke or a paste replaces: the selection, or nothing at the caret
|
|
949
|
+
input.addEventListener('beforeinput', () => { input.at = [input.selectionStart, input.selectionEnd]; });
|
|
950
|
+
input.addEventListener('input', (e) => {
|
|
951
|
+
const restoring = /^history(Undo|Redo)$/.test(e.inputType);
|
|
952
|
+
edit(paths(), input, restoring, restoring || e.isComposing || /Composition/.test(e.inputType) ? undefined : input.at);
|
|
953
|
+
input.at = undefined;
|
|
954
|
+
});
|
|
732
955
|
['select', 'keyup', 'pointerup'].forEach((t) => input.addEventListener(t, () => assignLabel(input)));
|
|
733
956
|
input.addEventListener('focus', () => { focus(path, all, input, wrap); showAssign(wrap, input, paths()); });
|
|
734
957
|
input.addEventListener('blur', () => {
|
|
@@ -742,7 +965,9 @@ const Slop = (() => {
|
|
|
742
965
|
});
|
|
743
966
|
wrap.querySelector('.sp-unseen').addEventListener('click', () => input.focus());
|
|
744
967
|
wrap.input = input;
|
|
968
|
+
wrap.mirror = wrap.querySelector('.sp-mirror');
|
|
745
969
|
wrap.rep = wrap.querySelector('.sp-rep');
|
|
970
|
+
wrap.kind = wrap.querySelector('.sp-kind');
|
|
746
971
|
wrap.revert = revert;
|
|
747
972
|
wrap.paths = paths;
|
|
748
973
|
return wrap;
|
|
@@ -751,17 +976,145 @@ const Slop = (() => {
|
|
|
751
976
|
function groupView(key, paths) {
|
|
752
977
|
const det = el('details', 'sp-group', `<summary><span class="sp-gname">${esc(groupTitle(key))}</span><span class="sp-gnote"></span></summary>`);
|
|
753
978
|
det.dataset.group = key;
|
|
754
|
-
det.open = state.open.has(key);
|
|
755
|
-
const all = entries(text[key], [key]).map(([p]) => p);
|
|
756
|
-
|
|
979
|
+
det.open = state.open.has(key) || state.tab === 'hidden'; // there are few, so all of them show
|
|
980
|
+
const all = () => entries(text[key], [key]).map(([p]) => p);
|
|
981
|
+
const ctl = control(all, `"${groupTitle(key)}"`);
|
|
982
|
+
det.querySelector('.sp-gname').after(ctl.pie);
|
|
983
|
+
det.querySelector('summary').append(ctl);
|
|
757
984
|
det.addEventListener('toggle', () => {
|
|
758
985
|
if (det.open) { state.open.add(key); det.querySelectorAll('textarea').forEach(grow); } else state.open.delete(key);
|
|
759
986
|
});
|
|
760
987
|
paths.forEach((p) => det.append(field(p)));
|
|
988
|
+
if (state.tab === 'all') listRows(key, det);
|
|
761
989
|
return det;
|
|
762
990
|
}
|
|
763
991
|
|
|
992
|
+
// the words behind a text box, each in its author's color. The box's own letters are see-through
|
|
993
|
+
function paintInk(wrap) {
|
|
994
|
+
const value = valueAt(text, wrap.paths()[0]) ?? ''; // a text just taken out is drawn once more
|
|
995
|
+
const key = JSON.stringify(value);
|
|
996
|
+
if (wrap.inked === key) return;
|
|
997
|
+
wrap.inked = key;
|
|
998
|
+
const s = plain(value);
|
|
999
|
+
const authors = authorsByChar(value);
|
|
1000
|
+
let h = '';
|
|
1001
|
+
for (let i = 0; i < s.length;) {
|
|
1002
|
+
let j = i;
|
|
1003
|
+
while (j < s.length && authors[j] === authors[i]) j++;
|
|
1004
|
+
h += `<span class="${cls(authors[i])}">${esc(s.slice(i, j))}</span>`;
|
|
1005
|
+
i = j;
|
|
1006
|
+
}
|
|
1007
|
+
wrap.mirror.innerHTML = `${h} `; // the space holds a last empty line open, as the box does
|
|
1008
|
+
}
|
|
1009
|
+
|
|
1010
|
+
/* lists: where the page shows a group as a list, texts can be added and taken out */
|
|
1011
|
+
const inList = (key) => [...listed()].some((g) => g === key || g.startsWith(`${key}.`));
|
|
1012
|
+
// a key for a new text in a group, like `like` (p3 → p<next>), and never one the group had since it was opened
|
|
1013
|
+
function freshKey(group, like) {
|
|
1014
|
+
const prefix = /^(.*?)\d+$/.exec(like)?.[1] || 'p';
|
|
1015
|
+
const taken = new Set([text, saved, JSON.parse(original)].flatMap((root) => Object.keys(nodeAt(root, group) ?? {})));
|
|
1016
|
+
let n = 1 + Math.max(0, ...[...taken].map((k) => (k.startsWith(prefix) && /^\d+$/.test(k.slice(prefix.length)) ? +k.slice(prefix.length) : 0)));
|
|
1017
|
+
while (taken.has(`${prefix}${n}`)) n++;
|
|
1018
|
+
return `${prefix}${n}`;
|
|
1019
|
+
}
|
|
1020
|
+
// a text put in a group after the key `after` (or first), the rest in the order they were
|
|
1021
|
+
function insert(group, after, key, value) {
|
|
1022
|
+
const node = nodeAt(text, group) ?? {};
|
|
1023
|
+
const next = after == null ? { [key]: value } : {};
|
|
1024
|
+
Object.entries(node).forEach(([k, v]) => { next[k] = v; if (k === after) next[key] = value; });
|
|
1025
|
+
if (!(key in next)) next[key] = value;
|
|
1026
|
+
set(group, next);
|
|
1027
|
+
}
|
|
1028
|
+
function addText(group, after) {
|
|
1029
|
+
const key = freshKey(group, after ?? textKeys(nodeAt(saved, group))[0] ?? '');
|
|
1030
|
+
withUndo('Added a paragraph', () => insert(group, after, key, ''));
|
|
1031
|
+
show('all', `${group}.${key}`);
|
|
1032
|
+
}
|
|
1033
|
+
const TRASH = '<svg viewBox="0 0 16 16" width="14" height="14" aria-hidden="true"><path d="M2.5 4.5h11M6.2 4.5V2.8h3.6v1.7M4 4.5l.7 8.7h6.6l.7-8.7M6.7 7v4M9.3 7v4" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"/></svg>';
|
|
1034
|
+
// a class on the page's elements for a text (`last`: only the last of them), off everything else
|
|
1035
|
+
const FLAGS = ['slop-insert-after', 'slop-remove-hint', 'slop-removing'];
|
|
1036
|
+
function flag(name, path, last) {
|
|
1037
|
+
document.querySelectorAll(`.${name}`).forEach((x) => x.classList.remove(name));
|
|
1038
|
+
if (!path) return;
|
|
1039
|
+
const els = elementsOf(path);
|
|
1040
|
+
(last ? els.slice(-1) : els).forEach((x) => x.classList.add(name));
|
|
1041
|
+
}
|
|
1042
|
+
// the + under a text in a list: pointing at it shows on the page where the new paragraph would go
|
|
1043
|
+
function plusRow(path, group) {
|
|
1044
|
+
const b = el('button', 'sp-insert', '<span class="sp-plus" aria-hidden="true">+</span><span class="sp-insert-label" aria-hidden="true">Add paragraph</span>');
|
|
1045
|
+
b.type = 'button';
|
|
1046
|
+
b.title = 'Add a paragraph below this one';
|
|
1047
|
+
b.setAttribute('aria-label', 'Add a paragraph below this one');
|
|
1048
|
+
const show = (on) => flag('slop-insert-after', on && path, true);
|
|
1049
|
+
['pointerenter', 'focus'].forEach((t) => b.addEventListener(t, () => show(true)));
|
|
1050
|
+
['pointerleave', 'blur'].forEach((t) => b.addEventListener(t, () => show(false)));
|
|
1051
|
+
b.addEventListener('click', () => { show(false); addText(group, keysOf(path).at(-1)); });
|
|
1052
|
+
return b;
|
|
1053
|
+
}
|
|
1054
|
+
// Remove: pointing at it outlines the text on the page in red. One with words takes a second click, and stays
|
|
1055
|
+
// red, here and on the page, until then
|
|
1056
|
+
function removeButton(path, wrap) {
|
|
1057
|
+
const drop = el('button', 'sp-trash', TRASH);
|
|
1058
|
+
drop.type = 'button';
|
|
1059
|
+
drop.title = 'Remove this paragraph';
|
|
1060
|
+
drop.setAttribute('aria-label', 'Remove this paragraph');
|
|
1061
|
+
const armed = () => 'armed' in drop.dataset;
|
|
1062
|
+
const hint = (on) => flag('slop-remove-hint', on && path);
|
|
1063
|
+
const arm = (on) => {
|
|
1064
|
+
if (on) drop.dataset.armed = ''; else delete drop.dataset.armed;
|
|
1065
|
+
drop.innerHTML = on ? `${TRASH}Remove?` : TRASH;
|
|
1066
|
+
wrap.classList.toggle('sp-removing', on);
|
|
1067
|
+
flag('slop-removing', on && path);
|
|
1068
|
+
};
|
|
1069
|
+
['pointerenter', 'focus'].forEach((t) => drop.addEventListener(t, () => hint(true)));
|
|
1070
|
+
['pointerleave', 'blur'].forEach((t) => drop.addEventListener(t, () => hint(false)));
|
|
1071
|
+
drop.addEventListener('click', () => {
|
|
1072
|
+
if (plain(get(path)).trim() && !armed()) {
|
|
1073
|
+
arm(true);
|
|
1074
|
+
setTimeout(() => { if (drop.isConnected && armed()) arm(false); }, 3000);
|
|
1075
|
+
return;
|
|
1076
|
+
}
|
|
1077
|
+
hint(false);
|
|
1078
|
+
arm(false);
|
|
1079
|
+
withUndo(`Removed "${where(path)}"`, () => remove(path));
|
|
1080
|
+
render();
|
|
1081
|
+
});
|
|
1082
|
+
return drop;
|
|
1083
|
+
}
|
|
1084
|
+
// in the All tab, each list's removed texts until the next save, each with Restore, and a way to start an empty one
|
|
1085
|
+
function listRows(key, box) {
|
|
1086
|
+
[...listed()].filter((g) => g === key || g.startsWith(`${key}.`)).forEach((group) => {
|
|
1087
|
+
const now = textKeys(nodeAt(text, group));
|
|
1088
|
+
const was = textKeys(nodeAt(saved, group));
|
|
1089
|
+
const fieldOf = (k) => [...box.querySelectorAll(':scope > .sp-field')].find((f) => f.dataset.path === `${group}.${k}`);
|
|
1090
|
+
was.forEach((k, i) => {
|
|
1091
|
+
if (now.includes(k)) return;
|
|
1092
|
+
const before = was.slice(0, i).reverse().find((x) => now.includes(x)); // the nearest earlier one that's still there
|
|
1093
|
+
const name = /^p\d+$/.test(k) ? `Paragraph ${i + 1}` : human(k);
|
|
1094
|
+
const row = el('p', 'sp-gone', `${esc(name)} removed · `);
|
|
1095
|
+
const b = el('button', 'sp-link', 'Restore');
|
|
1096
|
+
b.type = 'button';
|
|
1097
|
+
b.addEventListener('click', () => {
|
|
1098
|
+
withUndo(`Restored "${name}"`, () => insert(group, before ?? null, k, JSON.parse(JSON.stringify(nodeAt(saved, `${group}.${k}`)))));
|
|
1099
|
+
render();
|
|
1100
|
+
});
|
|
1101
|
+
row.append(b);
|
|
1102
|
+
let at = before ? fieldOf(before) : null;
|
|
1103
|
+
while (at?.nextElementSibling?.classList.contains('sp-gone')) at = at.nextElementSibling;
|
|
1104
|
+
const first = now.length ? fieldOf(now[0]) : null;
|
|
1105
|
+
if (at) at.after(row); else if (first) first.before(row); else box.append(row);
|
|
1106
|
+
});
|
|
1107
|
+
if (now.length) return;
|
|
1108
|
+
const start = el('button', 'sp-cat-add sp-start', '+ Paragraph');
|
|
1109
|
+
start.type = 'button';
|
|
1110
|
+
start.title = `Start "${where(group)}" again`;
|
|
1111
|
+
start.addEventListener('click', () => addText(group, null));
|
|
1112
|
+
box.append(start);
|
|
1113
|
+
});
|
|
1114
|
+
}
|
|
1115
|
+
|
|
764
1116
|
function render() {
|
|
1117
|
+
FLAGS.forEach((name) => flag(name)); // the elements pointed at may be gone
|
|
765
1118
|
controls = [controls.find((c) => c.el === pageControl)];
|
|
766
1119
|
sets = repeats(entries());
|
|
767
1120
|
groupKeys().forEach((k) => { if (!state.known.has(k)) { state.known.add(k); state.open.add(k); } });
|
|
@@ -791,15 +1144,18 @@ const Slop = (() => {
|
|
|
791
1144
|
body.append(card);
|
|
792
1145
|
});
|
|
793
1146
|
} else {
|
|
794
|
-
const
|
|
1147
|
+
const tab = state.tab;
|
|
1148
|
+
const keep = tab === 'slop' ? hasSlop : tab === 'hidden' ? attrOf : () => true;
|
|
1149
|
+
if (tab === 'hidden') body.insertAdjacentHTML('beforeend', '<p class="sp-intro">Words the page has but doesn\'t show: alt text for when an image doesn\'t load, tooltips, labels for screen readers. Readers\' colors can\'t show them, so read them here.</p>');
|
|
795
1150
|
let shown = 0;
|
|
796
1151
|
groupKeys().forEach((key) => {
|
|
797
|
-
const paths = (isText(text[key]) ? [key] : entries(text[key], [key]).map(([p]) => p)).filter(
|
|
798
|
-
if (!paths.length) return;
|
|
1152
|
+
const paths = (isText(text[key]) ? [key] : entries(text[key], [key]).map(([p]) => p)).filter(keep);
|
|
1153
|
+
if (!paths.length && !(tab === 'all' && inList(key))) return; // an emptied list stays, to start again
|
|
799
1154
|
shown += paths.length;
|
|
800
1155
|
body.append(isText(text[key]) ? field(key) : groupView(key, paths));
|
|
801
1156
|
});
|
|
802
|
-
if (
|
|
1157
|
+
if (tab === 'slop' && !shown) body.insertAdjacentHTML('beforeend', '<p class="sp-empty">No slop left. Every word here is yours, approved, or someone else\'s.</p>');
|
|
1158
|
+
if (tab === 'hidden' && !shown) body.insertAdjacentHTML('beforeend', '<p class="sp-empty">No hidden text on this page. Mark an element\'s with <code>data-slop-attr="alt:group.key"</code>.</p>');
|
|
803
1159
|
}
|
|
804
1160
|
aside.classList.add('sp-still'); // new switches appear as they are, without sliding there
|
|
805
1161
|
numbers();
|
|
@@ -826,18 +1182,20 @@ const Slop = (() => {
|
|
|
826
1182
|
go.title = breakdown(m, cats);
|
|
827
1183
|
});
|
|
828
1184
|
const live = repeats(all);
|
|
829
|
-
const
|
|
830
|
-
|
|
1185
|
+
const hidden = new Map(all.map(([p]) => [p, attrOf(p)]).filter(([, a]) => a));
|
|
1186
|
+
const tabs = { all: all.length, slop: all.filter(([p]) => hasSlop(p)).length, repeats: live.length, hidden: hidden.size };
|
|
1187
|
+
aside.querySelectorAll('.sp-tabs button').forEach((b) => {
|
|
1188
|
+
b.querySelector('span').textContent = tabs[b.dataset.tab];
|
|
1189
|
+
if (b.dataset.tab === 'hidden') b.hidden = !hidden.size && state.tab !== 'hidden'; // only on pages that have some
|
|
1190
|
+
});
|
|
831
1191
|
body.querySelectorAll('.sp-field').forEach((f) => {
|
|
1192
|
+
paintInk(f);
|
|
832
1193
|
f.revert.hidden = !f.paths().some((p) => differs(p) && savedAt(p) !== undefined);
|
|
833
|
-
|
|
834
|
-
const
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
tag.title = shown ? 'The page normally hides this. It\'s shown while you edit it'
|
|
839
|
-
: tag.disabled ? 'Not on the page right now: the page shows it only some of the time, or not at all. A page can say how to show it with Slop.reveal'
|
|
840
|
-
: 'Show the page the way it looks with this text';
|
|
1194
|
+
paintSeen(f);
|
|
1195
|
+
const kind = f.paths().map((p) => hidden.get(p)).find(Boolean);
|
|
1196
|
+
f.kind.hidden = !kind;
|
|
1197
|
+
f.kind.textContent = KINDS[kind] ?? kind ?? '';
|
|
1198
|
+
f.kind.title = kind ? `Not shown as words: the page's ${kind} attribute` : '';
|
|
841
1199
|
});
|
|
842
1200
|
paintSave();
|
|
843
1201
|
body.querySelectorAll('.sp-field:not(.sp-set)').forEach((f) => {
|
|
@@ -855,17 +1213,46 @@ const Slop = (() => {
|
|
|
855
1213
|
paintMeters();
|
|
856
1214
|
}
|
|
857
1215
|
repaint = () => { if (!aside.hidden) render(); };
|
|
1216
|
+
reseen = () => { if (!aside.hidden) body.querySelectorAll('.sp-field').forEach(paintSeen); };
|
|
1217
|
+
// a text the page doesn't show right now is tagged, with a way to show it if the page says how
|
|
1218
|
+
function paintSeen(f) {
|
|
1219
|
+
const tag = f.querySelector('.sp-unseen');
|
|
1220
|
+
const shown = revealed && f.paths().includes(revealed.path);
|
|
1221
|
+
tag.hidden = !shown && f.paths().some(onPage);
|
|
1222
|
+
tag.disabled = shown || !revealerOf(f.paths()[0]);
|
|
1223
|
+
tag.textContent = shown ? 'shown while editing' : tag.disabled ? 'not on the page' : 'not on the page · show it';
|
|
1224
|
+
tag.title = shown ? 'The page normally hides this. It\'s shown while you edit it'
|
|
1225
|
+
: tag.disabled ? 'Not on the page right now: the page shows it only some of the time, or not at all. A page can say how to show it with Slop.reveal'
|
|
1226
|
+
: 'Show the page the way it looks with this text';
|
|
1227
|
+
}
|
|
858
1228
|
|
|
859
1229
|
// the page and the editor point at each other
|
|
860
|
-
function mark(on, paths = state.focus?.paths ?? [], scroll = false) {
|
|
1230
|
+
function mark(on, paths = state.focus?.paths ?? [], scroll = false, tries = 0) {
|
|
861
1231
|
document.querySelectorAll('.slop-focus, .slop-copy').forEach((x) => x.classList.remove('slop-focus', 'slop-copy'));
|
|
862
1232
|
if (!on) return;
|
|
863
1233
|
paths.forEach((p, i) => elementsOf(p).forEach((x) => x.classList.add(i ? 'slop-copy' : 'slop-focus')));
|
|
864
1234
|
const target = paths.map((p) => elementsOf(p)[0]).find(Boolean);
|
|
865
|
-
if (!
|
|
1235
|
+
if (!scroll) return;
|
|
1236
|
+
// a text the page only just revealed may not be drawn yet (React and the like draw on the next frame)
|
|
1237
|
+
if (!target) {
|
|
1238
|
+
if (tries < 10) requestAnimationFrame(() => { if (state.focus?.paths === paths) mark(true, paths, true, tries + 1); });
|
|
1239
|
+
return;
|
|
1240
|
+
}
|
|
1241
|
+
// scroll whatever holds it (the window, or a panel of the page's that scrolls on its own) to bring it to
|
|
1242
|
+
// the middle of what's visible, unless it's already well in view
|
|
1243
|
+
const box = scroller(target);
|
|
866
1244
|
const r = target.getBoundingClientRect();
|
|
867
|
-
const
|
|
868
|
-
|
|
1245
|
+
const top = box ? Math.max(box.getBoundingClientRect().top, 0) : 0;
|
|
1246
|
+
const bottom = Math.min(box ? box.getBoundingClientRect().bottom : innerHeight, innerWidth <= 900 ? aside.getBoundingClientRect().top : innerHeight);
|
|
1247
|
+
const pad = Math.min(120, (bottom - top) / 5); // room for a header that stays put
|
|
1248
|
+
if (r.top < top + pad || r.bottom > bottom - 8) (box ?? window).scrollBy({ top: r.top - (top + bottom - r.height) / 2, behavior: 'smooth' });
|
|
1249
|
+
}
|
|
1250
|
+
// the nearest element around `el` that scrolls, or null for the window
|
|
1251
|
+
function scroller(el) {
|
|
1252
|
+
for (let p = el.parentElement; p && p !== document.body && p !== document.documentElement; p = p.parentElement) {
|
|
1253
|
+
if (/(auto|scroll|overlay)/.test(getComputedStyle(p).overflowY) && p.scrollHeight > p.clientHeight) return p;
|
|
1254
|
+
}
|
|
1255
|
+
return null;
|
|
869
1256
|
}
|
|
870
1257
|
function focus(path, all, input, wrap) {
|
|
871
1258
|
const s = all ?? setOf(path);
|
|
@@ -916,12 +1303,12 @@ const Slop = (() => {
|
|
|
916
1303
|
past.set(p, list.slice(-200));
|
|
917
1304
|
}
|
|
918
1305
|
const recall = (p, words) => past.get(p)?.findLast((v) => plain(v) === words);
|
|
919
|
-
function edit(paths, input, restoring) {
|
|
1306
|
+
function edit(paths, input, restoring, at) {
|
|
920
1307
|
undo = null;
|
|
921
1308
|
const f = state.focus;
|
|
922
1309
|
[...paths, ...(f?.linked ?? [])].forEach((p) => {
|
|
923
1310
|
remember(p);
|
|
924
|
-
set(p, applyEdit(get(p), input.value, restoring ? recall(p, input.value) : undefined));
|
|
1311
|
+
set(p, applyEdit(get(p), input.value, restoring ? recall(p, input.value) : undefined, at));
|
|
925
1312
|
remember(p);
|
|
926
1313
|
});
|
|
927
1314
|
grow(input);
|
|
@@ -978,6 +1365,7 @@ const Slop = (() => {
|
|
|
978
1365
|
store.set(LOCAL, JSON.stringify({ base: JSON.parse(original).version, text: JSON.parse(body) }));
|
|
979
1366
|
saved = JSON.parse(body);
|
|
980
1367
|
undo = null;
|
|
1368
|
+
keepDraft();
|
|
981
1369
|
savedStatus();
|
|
982
1370
|
numbers();
|
|
983
1371
|
return;
|
|
@@ -992,6 +1380,7 @@ const Slop = (() => {
|
|
|
992
1380
|
text.version = Number(out);
|
|
993
1381
|
saved = { ...JSON.parse(body), version: text.version };
|
|
994
1382
|
undo = null;
|
|
1383
|
+
keepDraft();
|
|
995
1384
|
savedStatus();
|
|
996
1385
|
} catch (e) {
|
|
997
1386
|
status(`Couldn't save: ${e.message}`, 'error');
|
|
@@ -1004,10 +1393,12 @@ const Slop = (() => {
|
|
|
1004
1393
|
function touched() {
|
|
1005
1394
|
numbers();
|
|
1006
1395
|
changed();
|
|
1396
|
+
keepDraft();
|
|
1007
1397
|
if (!stale && !undo) status(unsaved() ? 'Not saved yet' : 'No changes since the last save', unsaved() ? 'dirty' : '');
|
|
1008
1398
|
}
|
|
1009
1399
|
function reset() {
|
|
1010
1400
|
store.drop(LOCAL);
|
|
1401
|
+
session.drop(DRAFT);
|
|
1011
1402
|
text = JSON.parse(original);
|
|
1012
1403
|
saved = JSON.parse(original);
|
|
1013
1404
|
undo = null;
|
|
@@ -1016,7 +1407,14 @@ const Slop = (() => {
|
|
|
1016
1407
|
render();
|
|
1017
1408
|
savedStatus();
|
|
1018
1409
|
}
|
|
1019
|
-
addEventListener('beforeunload', (e) => { if (busy || unsaved()) e.preventDefault(); });
|
|
1410
|
+
addEventListener('beforeunload', (e) => { if (busy || unsaved()) { e.preventDefault(); e.returnValue = ''; } });
|
|
1411
|
+
// a reload keeps what isn't saved, in this tab, still unsaved: a page in a frame (or a browser that skips the
|
|
1412
|
+
// prompt) can't ask before it goes. Kept only while the page's version is the one it was based on
|
|
1413
|
+
const DRAFT = `slop-draft:${location.pathname}`;
|
|
1414
|
+
const keepDraft = () => {
|
|
1415
|
+
if (unsaved() && !stale) session.set(DRAFT, JSON.stringify({ base: saved.version, text }));
|
|
1416
|
+
else session.drop(DRAFT);
|
|
1417
|
+
};
|
|
1020
1418
|
addEventListener('keydown', (e) => {
|
|
1021
1419
|
if ((e.metaKey || e.ctrlKey) && e.key === 's' && !aside.hidden) { e.preventDefault(); save(); }
|
|
1022
1420
|
// ⌘Z outside a text undoes the last switch or mark (a text's own ⌘Z undoes its typing)
|
|
@@ -1034,11 +1432,12 @@ const Slop = (() => {
|
|
|
1034
1432
|
// while the editor is open, a click on a text opens it in the editor
|
|
1035
1433
|
document.addEventListener('click', (e) => {
|
|
1036
1434
|
if (aside.hidden || aside.contains(e.target) || btn.contains(e.target)) return;
|
|
1037
|
-
const target = e.target.closest('[data-slop]');
|
|
1435
|
+
const target = e.target.closest('[data-slop], [data-slop-ref], [data-slop-more], [data-slop-attr]');
|
|
1038
1436
|
if (!target) return;
|
|
1039
1437
|
e.preventDefault();
|
|
1040
1438
|
e.stopPropagation();
|
|
1041
|
-
const path = target
|
|
1439
|
+
const path = pathOf(target);
|
|
1440
|
+
if (!path) return;
|
|
1042
1441
|
const s = setOf(path);
|
|
1043
1442
|
if (state.tab === 'repeats' && s) show('repeats', s.paths[0]);
|
|
1044
1443
|
else show(state.tab === 'slop' && hasSlop(path) ? 'slop' : 'all', path);
|
|
@@ -1132,6 +1531,19 @@ const Slop = (() => {
|
|
|
1132
1531
|
}));
|
|
1133
1532
|
aside.querySelectorAll('.sp-tabs button').forEach((b) => b.addEventListener('click', () => { state.tab = b.dataset.tab; render(); }));
|
|
1134
1533
|
savedStatus();
|
|
1534
|
+
try {
|
|
1535
|
+
const draft = JSON.parse(session.get(DRAFT));
|
|
1536
|
+
if (draft?.base === saved.version && JSON.stringify(draft.text) !== JSON.stringify(text)) {
|
|
1537
|
+
text = draft.text;
|
|
1538
|
+
applyColors();
|
|
1539
|
+
changed();
|
|
1540
|
+
open(true);
|
|
1541
|
+
status('Unsaved changes from before the reload', 'dirty', {
|
|
1542
|
+
label: 'Discard',
|
|
1543
|
+
run: () => { text = JSON.parse(JSON.stringify(saved)); session.drop(DRAFT); applyColors(); changed(); render(); savedStatus(); },
|
|
1544
|
+
});
|
|
1545
|
+
}
|
|
1546
|
+
} catch { /* none */ }
|
|
1135
1547
|
return { render: () => { if (!aside.hidden) render(); }, touched, open };
|
|
1136
1548
|
}
|
|
1137
1549
|
|
|
@@ -1155,7 +1567,8 @@ const Slop = (() => {
|
|
|
1155
1567
|
function start(options = {}) {
|
|
1156
1568
|
Object.assign(config, options);
|
|
1157
1569
|
fill();
|
|
1158
|
-
document.querySelectorAll('[data-slop-meter]').forEach(buildMeter);
|
|
1570
|
+
document.querySelectorAll('[data-slop-meter]').forEach((x) => { meters.push(buildMeter(x)); });
|
|
1571
|
+
new MutationObserver((changes) => changes.forEach((c) => c.addedNodes.forEach(added))).observe(document.body, { childList: true, subtree: true });
|
|
1159
1572
|
theme(true);
|
|
1160
1573
|
const watch = new MutationObserver(theme);
|
|
1161
1574
|
[document.documentElement, document.body].forEach((x) => watch.observe(x, { attributes: true, attributeFilter: ['class', 'data-theme', 'style'] }));
|
|
@@ -1175,5 +1588,5 @@ const Slop = (() => {
|
|
|
1175
1588
|
fetch('/__slop').then((res) => (res.ok ? res.text() : '')).then((s) => { if (s === 'slop-editor') ed = editor('file'); else local(); }).catch(local);
|
|
1176
1589
|
}
|
|
1177
1590
|
|
|
1178
|
-
return { ...core, get, set, remove, entries, categories, html, words, fill, refresh, onChange, reveal, start, get text() { return text; } };
|
|
1591
|
+
return { ...core, get, set, remove, entries, categories, html, words, paragraphs, fill, refresh, onChange, reveal, meter, start, get text() { return text; } };
|
|
1179
1592
|
})();
|