slop-editor 0.0.0-stage → 0.2.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/slop.js ADDED
@@ -0,0 +1,1289 @@
1
+ /* Slop editor: who wrote every word on a page. MIT license.
2
+
3
+ The words live in the page's text block, a JSON script element with the id "slop-text": an object with a
4
+ top-level "version" and groups (objects) of texts in reading order. A text is a plain string (the AI's words) or a
5
+ list of pieces: a string (the AI's), {"me": "..."} (mine: typed in the editor, or dictated word for word),
6
+ {"ok": "..."} (the AI's words, approved as they are), {"data": "..."} (a fact, or someone else's words quoted), or
7
+ {"<category>": "..."} for a category the page defines. A list is always one text.
8
+ Top-level keys that start with "_" aren't text: "_categories" holds the page's own categories and colors,
9
+ {"<id>": {"label": "...", "color": "#rrggbb"}}, for built-in ones too, and "_show" what readers see: "nothing" (the
10
+ default), "pie" (a pie of who wrote what, with a legend) or "colors" (the Slop-o-meter switch, which colors the words).
11
+ Inside any text: [label](url) is a link, **bold**, *italic*, `code`, [[key]] a key cap, {name} a value the page
12
+ fills in (Slop.vars), and \ makes the next character literal.
13
+
14
+ Elements with data-slop="group.key" are filled from the block. Code renders the rest with Slop.html(path).
15
+ An element with data-slop-meter becomes the Slop-o-meter switch. Under `slop-editor edit`, the page also gets the
16
+ editor, which saves back into the file; with Slop.start({edit: 'local'}) it gets one that saves in the browser. */
17
+ const Slop = (() => {
18
+ 'use strict';
19
+
20
+ /* ---------- the format ---------- */
21
+
22
+ // the built-in categories. Slop is the AI's words; the slop switch approves them (ok) or takes that back.
23
+ // `me` has no color of its own: my words keep the page's
24
+ const BUILTIN = {
25
+ me: { label: 'My words', light: null, dark: null },
26
+ ok: { label: 'AI, approved', light: '#17805a', dark: '#5ccf9c' },
27
+ data: { label: 'Data & quotes', light: '#8a5600', dark: '#e6b45c' },
28
+ ai: { label: 'AI-generated', light: '#6d35d0', dark: '#b892ff' },
29
+ };
30
+ // colors for the page's own categories, in the order they're made
31
+ const PALETTE = ['#e0662b', '#2b9fc0', '#d4469a', '#3b7be0', '#b8860b', '#8b5cf6'];
32
+
33
+ const authorOf = (piece) => (typeof piece === 'string' ? 'ai' : Object.keys(piece)[0] ?? 'ai');
34
+ const textOf = (piece) => (typeof piece === 'string' ? piece : String(Object.values(piece)[0] ?? ''));
35
+ const pieceOf = (author, s) => (author === 'ai' ? s : { [author]: s });
36
+
37
+ // the text with its markup, as the editor shows it
38
+ const plain = (value) => (typeof value === 'string' ? value : value.map(textOf).join(''));
39
+
40
+ // who wrote each character
41
+ function authorsByChar(value) {
42
+ if (typeof value === 'string') return new Array(value.length).fill('ai');
43
+ return value.flatMap((piece) => new Array(textOf(piece).length).fill(authorOf(piece)));
44
+ }
45
+
46
+ function fromChars(text, authors) {
47
+ if (authors.every((author) => author === 'ai')) return text;
48
+ const pieces = [];
49
+ for (let i = 0; i < text.length;) {
50
+ let j = i;
51
+ while (j < text.length && authors[j] === authors[i]) j++;
52
+ pieces.push(pieceOf(authors[i], text.slice(i, j)));
53
+ i = j;
54
+ }
55
+ return pieces;
56
+ }
57
+
58
+ // `value` after its plain text became `next` in the editor. An edit is one stretch replaced (typing, deleting,
59
+ // 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
+ function applyEdit(value, next, was) {
62
+ const prev = plain(value);
63
+ if (prev === next) return value;
64
+ let start = 0;
65
+ while (start < prev.length && start < next.length && prev[start] === next[start]) start++;
66
+ let end = 0;
67
+ while (end < prev.length - start && end < next.length - start
68
+ && prev[prev.length - 1 - end] === next[next.length - 1 - end]) end++;
69
+ const authors = authorsByChar(value);
70
+ const middle = was != null && plain(was) === next
71
+ ? authorsByChar(was).slice(start, next.length - end)
72
+ : new Array(next.length - start - end).fill('me');
73
+ return fromChars(next, [...authors.slice(0, start), ...middle, ...authors.slice(prev.length - end)]);
74
+ }
75
+
76
+ // `value` with one author's words handed to another, the text unchanged
77
+ const reattribute = (value, from, to) => fromChars(plain(value), authorsByChar(value).map((a) => (a === from ? to : a)));
78
+ // unslopify (the slop switch, off): the AI's words, approved as they are
79
+ const unslop = (value) => reattribute(value, 'ai', 'ok');
80
+ // re-slopify (the slop switch, on): approved words go back to being slop. What I typed stays mine
81
+ const reslop = (value) => reattribute(value, 'ok', 'ai');
82
+ // characters start to end (of the plain text) marked as one author's
83
+ const assign = (value, start, end, to) => fromChars(plain(value), authorsByChar(value).map((a, i) => (i >= start && i < end ? to : a)));
84
+
85
+ const LINK = /\[([^\]]+)\]\(([^)\s]+)\)/y;
86
+ const VAR = /\{(\w+)\}/y;
87
+ const same = (a, b) => a.by === b.by && a.link === b.link && a.b === b.b && a.i === b.i && a.code === b.code && a.key === b.key;
88
+
89
+ // the text as it reads: runs of one author's words (`by`: the category) with their formatting (b, i, code, key)
90
+ // and the link they sit in, if any. A {name} is a run of its own with `v` set
91
+ function runs(value) {
92
+ const text = plain(value);
93
+ const authors = authorsByChar(value);
94
+ const out = [];
95
+ const st = { b: false, i: false, code: false, key: false, link: null };
96
+ let linkEnd = -1;
97
+ let linkTail = 0;
98
+ const push = (s, by, v) => {
99
+ const run = { text: s, by, link: st.link, b: st.b, i: st.i, code: st.code, key: st.key, v };
100
+ const last = out[out.length - 1];
101
+ if (last && !last.v && !v && same(last, run)) last.text += s;
102
+ else out.push(run);
103
+ };
104
+ for (let i = 0; i < text.length;) {
105
+ const c = text[i];
106
+ if (i === linkEnd) { st.link = null; i += linkTail; linkEnd = -1; continue; }
107
+ if (c === '\\' && i + 1 < text.length) { push(text[i + 1], authors[i + 1]); i += 2; continue; }
108
+ if (c === '[' && text[i + 1] === '[' && !st.key) { st.key = true; i += 2; continue; }
109
+ if (c === ']' && text[i + 1] === ']' && st.key) { st.key = false; i += 2; continue; }
110
+ if (c === '[' && !st.link) {
111
+ LINK.lastIndex = i;
112
+ const m = LINK.exec(text);
113
+ if (m) { st.link = { href: m[2] }; linkEnd = i + 1 + m[1].length; linkTail = m[0].length - m[1].length - 1; i++; continue; }
114
+ }
115
+ if (c === '`') { st.code = !st.code; i++; continue; }
116
+ if (c === '*' && !st.code) {
117
+ if (text[i + 1] === '*') { st.b = !st.b; i += 2; } else { st.i = !st.i; i++; }
118
+ continue;
119
+ }
120
+ if (c === '{') {
121
+ VAR.lastIndex = i;
122
+ const m = VAR.exec(text);
123
+ if (m) { push('', authors[i], m[1]); i += m[0].length; continue; }
124
+ }
125
+ push(c, authors[i]);
126
+ i++;
127
+ }
128
+ return out;
129
+ }
130
+
131
+ // values the page fills in: {html, data} (data: a fact, shown in the data color; otherwise it takes the color of
132
+ // whoever wrote the {name}), or a plain string or number (a fact)
133
+ const vars = {};
134
+ const config = { code: 'code' };
135
+ const esc = (s) => String(s).replace(/[&<>"]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' })[c]);
136
+ const stripTags = (h) => h.replace(/<[^>]*>/g, '').replace(/&nbsp;/g, ' ').replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&quot;/g, '"').replace(/&amp;/g, '&');
137
+ // the class a category's words render with
138
+ const cls = (id) => `slop-${String(id).replace(/[^\w-]/g, '_')}`;
139
+ function lookup(name, local) {
140
+ const v = local?.[name] ?? vars[name];
141
+ if (v == null) { console.warn(`slop: no value for {${name}}`); return { html: esc(`{${name}}`), data: false }; }
142
+ return typeof v === 'object' ? v : { html: esc(v), data: true };
143
+ }
144
+
145
+ // the text as it reads, in one string (for labels, titles and alt text)
146
+ const readable = (value, local) => runs(value).map((run) => (run.v ? stripTags(lookup(run.v, local).html) : run.text)).join('');
147
+
148
+ // 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
149
+ function render(value, local) {
150
+ const one = (run) => {
151
+ let h;
152
+ let by = run.by;
153
+ if (run.v) {
154
+ const v = lookup(run.v, local);
155
+ h = v.html;
156
+ if (v.data) by = 'data';
157
+ } else h = esc(run.text).replace(/\n/g, '<br>');
158
+ h = `<span class="${cls(by)}">${h}</span>`;
159
+ if (run.key) h = `<kbd>${h}</kbd>`;
160
+ if (run.code) h = `<span class="${config.code}">${h}</span>`;
161
+ if (run.i) h = `<em>${h}</em>`;
162
+ if (run.b) h = `<strong>${h}</strong>`;
163
+ return h;
164
+ };
165
+ const parts = [];
166
+ runs(value).forEach((run) => {
167
+ const last = parts[parts.length - 1];
168
+ if (!run.link) parts.push(run);
169
+ else if (last?.link === run.link) last.runs.push(run);
170
+ else parts.push({ link: run.link, runs: [run] });
171
+ });
172
+ return parts.map((part) => (part.runs
173
+ ? `<a href="${esc(part.link.href)}" target="_blank" rel="noopener">${part.runs.map(one).join('')}</a>`
174
+ : one(part))).join('');
175
+ }
176
+
177
+ // what these texts are made of, as they read: written letters (spaces and filled-in values aside) and words, by
178
+ // category. {counts: {ai: 120, me: 30, …}, letters, words: {…}, allWords}
179
+ function makeup(values) {
180
+ const counts = {};
181
+ const words = {};
182
+ let letters = 0;
183
+ let allWords = 0;
184
+ values.forEach((value) => {
185
+ runs(value).forEach((run) => {
186
+ if (run.v) return;
187
+ const n = run.text.replace(/\s/g, '').length;
188
+ const w = run.text.split(/\s+/).filter(Boolean).length;
189
+ counts[run.by] = (counts[run.by] ?? 0) + n;
190
+ words[run.by] = (words[run.by] ?? 0) + w;
191
+ letters += n;
192
+ allWords += w;
193
+ });
194
+ });
195
+ return { counts, letters, words, allWords };
196
+ }
197
+
198
+ // how much of these texts is mine (typed or approved), facts and quotes aside
199
+ function share(values) {
200
+ const m = makeup(values);
201
+ const letters = m.letters - (m.counts.data ?? 0);
202
+ const mine = (m.counts.me ?? 0) + (m.counts.ok ?? 0);
203
+ return {
204
+ fraction: letters ? mine / letters : 0,
205
+ letters,
206
+ words: (m.words.me ?? 0) + (m.words.ok ?? 0),
207
+ allWords: m.allWords - (m.words.data ?? 0),
208
+ };
209
+ }
210
+
211
+ function percent(fraction) {
212
+ if (fraction > 0 && fraction < 0.01) return '<1%';
213
+ if (fraction < 1 && fraction > 0.99) return '>99%';
214
+ return `${Math.round(fraction * 100)}%`;
215
+ }
216
+
217
+ // repeated text: the same words in more than one place (a header that's also in the nav, a tagline in the hero
218
+ // and the footer). Each copy keeps its own authorship, so a copy is slop until it's approved, like any text.
219
+ // [[path, value]] → [{words, paths}], in reading order. Data-only and very short texts don't count
220
+ const wordsOf = (value) => plain(value).replace(/\s+/g, ' ').trim();
221
+ function repeats(list) {
222
+ const byWords = new Map();
223
+ list.forEach(([path, value]) => {
224
+ const w = wordsOf(value);
225
+ if (w.replace(/\W/g, '').length < 3 || !share([value]).letters) return;
226
+ if (!byWords.has(w)) byWords.set(w, []);
227
+ byWords.get(w).push(path);
228
+ });
229
+ return [...byWords].filter(([, paths]) => paths.length > 1).map(([words, paths]) => ({ words, paths }));
230
+ }
231
+
232
+ const core = { BUILTIN, plain, applyEdit, reslop, unslop, assign, reattribute, runs, readable, render, makeup, share, percent, repeats, wordsOf, vars };
233
+ if (typeof document === 'undefined') return core; // Node (the CLI and the tests) only needs the format
234
+
235
+ /* ---------- the block ---------- */
236
+
237
+ let text = { version: 0 };
238
+ try {
239
+ text = JSON.parse(document.getElementById('slop-text').textContent);
240
+ } catch (e) {
241
+ console.error('slop: the slop-text block is missing or not valid JSON', e);
242
+ }
243
+ const original = JSON.stringify(text);
244
+ const isText = (v) => typeof v === 'string' || Array.isArray(v);
245
+ const isMeta = (key) => key === 'version' || key.startsWith('_');
246
+ const keysOf = (path) => (Array.isArray(path) ? path : path.split('.'));
247
+ const dotted = (path) => keysOf(path).join('.');
248
+ function get(path) {
249
+ let node = text;
250
+ for (const key of keysOf(path)) node = node?.[key];
251
+ if (!isText(node)) { console.warn(`slop: no text at ${dotted(path)}`); return ''; }
252
+ return node;
253
+ }
254
+ function set(path, value) {
255
+ const keys = keysOf(path);
256
+ let node = text;
257
+ keys.slice(0, -1).forEach((key) => { node[key] ??= {}; node = node[key]; });
258
+ node[keys[keys.length - 1]] = value;
259
+ }
260
+ // every text in a group (or the whole block), in reading order: [[path, value]] with dotted paths
261
+ function entries(node = text, at = []) {
262
+ return Object.entries(node).flatMap(([key, v]) => {
263
+ if (!at.length && isMeta(key)) return [];
264
+ if (isText(v)) return [[[...at, key].join('.'), v]];
265
+ return v && typeof v === 'object' ? entries(v, [...at, key]) : [];
266
+ });
267
+ }
268
+ const groupKeys = () => Object.keys(text).filter((k) => !isMeta(k) && text[k] && (isText(text[k]) || typeof text[k] === 'object'));
269
+ // the texts an element holds in its attributes, from data-slop-attr="alt:hero.photo title:hero.tip": [[name, path]]
270
+ 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);
271
+ // the elements that show a text: [data-slop] ones, which fill() writes, [data-slop-ref] ones, which the page writes
272
+ // itself (words inside a button or a link it builds) but the editor can still find, and [data-slop-attr] ones
273
+ const elementsOf = (path) => {
274
+ const at = dotted(path);
275
+ const q = CSS.escape(at);
276
+ return [...document.querySelectorAll(`[data-slop="${q}"], [data-slop-ref="${q}"], [data-slop-attr*=":${q}"]`)]
277
+ .filter((x) => x.dataset.slop === at || x.dataset.slopRef === at || attrsOf(x).some(([, p]) => p === at));
278
+ };
279
+ // a text the page has but doesn't show as words (alt text, a tooltip, a label): the attribute it's in, or ''
280
+ function attrOf(path) {
281
+ const at = dotted(path);
282
+ for (const x of document.querySelectorAll('[data-slop-attr]')) {
283
+ const hit = attrsOf(x).find(([, p]) => p === at);
284
+ if (hit) return hit[0];
285
+ }
286
+ return '';
287
+ }
288
+
289
+ // texts the page's code has rendered (Slop.html, Slop.words): with the [data-slop] elements, what's on the page
290
+ const rendered = new Set();
291
+ const html = (path, local) => { rendered.add(dotted(path)); return render(get(path), local); };
292
+ const words = (path, local) => { rendered.add(dotted(path)); return readable(get(path), local); };
293
+ const onPage = (path) => rendered.has(dotted(path)) || elementsOf(path).length > 0;
294
+ // 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
295
+ // that shows it and returns a function that undoes that. A group's key covers all its texts
296
+ const revealers = new Map();
297
+ const reveal = (path, fn) => { revealers.set(dotted(path), fn); };
298
+ const revealerOf = (path) => revealers.get(dotted(path)) ?? revealers.get(keysOf(path)[0]);
299
+ // fill every [data-slop] element (data-slop-vars: a JSON object of extra values)
300
+ // fill an element: its words from data-slop, its attributes from data-slop-attr (as plain text)
301
+ function fillOne(el) {
302
+ const local = el.dataset.slopVars ? JSON.parse(el.dataset.slopVars) : undefined;
303
+ if (el.dataset.slop) {
304
+ const h = render(get(el.dataset.slop), local);
305
+ if (el.innerHTML !== h) el.innerHTML = h;
306
+ }
307
+ attrsOf(el).forEach(([name, path]) => {
308
+ const v = readable(get(path), local);
309
+ if (el.getAttribute(name) !== v) el.setAttribute(name, v);
310
+ });
311
+ }
312
+ const fill = (root = document) => root.querySelectorAll('[data-slop], [data-slop-attr]').forEach(fillOne);
313
+ // the [data-slop] elements and meters in what the page added after start (a single-page app draws late)
314
+ function added(n) {
315
+ if (n.nodeType !== 1 || n.closest('.slop-panel')) return;
316
+ if (n.matches('[data-slop], [data-slop-attr]')) fillOne(n);
317
+ fill(n);
318
+ if (n.matches('[data-slop-meter]')) meter(n);
319
+ n.querySelectorAll('[data-slop-meter]').forEach(meter);
320
+ }
321
+
322
+ const listeners = [];
323
+ // returns a function that stops calling fn
324
+ const onChange = (fn) => {
325
+ listeners.push(fn);
326
+ return () => { const i = listeners.indexOf(fn); if (i >= 0) listeners.splice(i, 1); };
327
+ };
328
+ let pending = false;
329
+ function changed() { // after an edit: refill the page, then let the page redo whatever it built from the text
330
+ if (pending) return;
331
+ pending = true;
332
+ requestAnimationFrame(() => {
333
+ pending = false;
334
+ fill();
335
+ listeners.forEach((fn) => { try { fn(); } catch (e) { console.error(e); } });
336
+ paintMeters();
337
+ });
338
+ }
339
+
340
+ /* ---------- categories and their colors ---------- */
341
+
342
+ let dark = false;
343
+ const ink = () => getComputedStyle(document.body).color;
344
+ // any CSS color as #rrggbb, for the color pickers
345
+ const hex = (color) => {
346
+ const x = document.createElement('canvas').getContext('2d');
347
+ x.fillStyle = '#000';
348
+ x.fillStyle = color;
349
+ const m = /rgba?\(([\d.]+)[ ,]+([\d.]+)[ ,]+([\d.]+)/.exec(x.fillStyle);
350
+ return m ? `#${m.slice(1, 4).map((v) => Math.round(+v).toString(16).padStart(2, '0')).join('')}` : x.fillStyle;
351
+ };
352
+ // a category's color: the page's choice (in the block, or --slop-<id> in its CSS), or the default for the theme.
353
+ // null for my words, unless picked: they keep the page's color
354
+ function colorOf(id, n) {
355
+ const own = text._categories?.[id]?.color;
356
+ if (own && CSS.supports('color', own)) return own;
357
+ const css = getComputedStyle(document.documentElement).getPropertyValue(`--slop-${id}`).trim();
358
+ if (css) return css;
359
+ if (BUILTIN[id]) return BUILTIN[id][dark ? 'dark' : 'light'];
360
+ return PALETTE[n % PALETTE.length];
361
+ }
362
+ // every category, in the order they're shown: mine, approved, the page's own, data, slop
363
+ function categories() {
364
+ const own = text._categories ?? {};
365
+ const used = entries().flatMap(([, v]) => (typeof v === 'string' ? [] : v.map(authorOf)));
366
+ const custom = [...new Set([...Object.keys(own), ...used])].filter((id) => !(id in BUILTIN));
367
+ return ['me', 'ok', ...custom, 'data', 'ai'].map((id) => ({
368
+ id,
369
+ label: own[id]?.label || BUILTIN[id]?.label || id,
370
+ color: colorOf(id, custom.indexOf(id)),
371
+ builtin: id in BUILTIN,
372
+ }));
373
+ }
374
+ const swatch = (cat) => cat.color ?? ink();
375
+
376
+ // the colors go in a stylesheet of their own: each category's words inside a .slop-on (the page, while the
377
+ // Slop-o-meter is on, or a section whose own switch is) but not inside a .slop-off (a section switched off), and
378
+ // --slop-c-<id> for anything else that wants them. Inside a [data-slop-only="<id>"] (a meter's tag is pointed at),
379
+ // everyone else's words are dimmed. :where keeps these as easy to override as html.slop-on .slop-<id> was
380
+ let sheet = null;
381
+ function applyColors() {
382
+ sheet ??= document.head.appendChild(Object.assign(document.createElement('style'), { id: 'slop-colors' }));
383
+ const all = categories();
384
+ const cats = all.filter((c) => c.color);
385
+ sheet.textContent = `:root{${cats.map((c) => `--${cls(c.id).replace('slop-', 'slop-c-')}:${c.color}`).join(';')}}\n`
386
+ + cats.map((c) => `:where(.slop-on) .${cls(c.id)}:not(:where(.slop-off) .${cls(c.id)}){color:${c.color}}`).join('\n')
387
+ + `\n${all.map((c) => `[data-slop-only]:not([data-slop-only="${CSS.escape(c.id)}"]) .${cls(c.id)}{opacity:.3}`).join('\n')}`;
388
+ }
389
+
390
+ // a pie of what these texts are made of, and the same in words for its tooltip
391
+ function gradient(m, cats) {
392
+ if (!m.letters) return '';
393
+ let at = 0;
394
+ const stops = cats.filter((c) => m.counts[c.id]).map((c) => {
395
+ const from = at;
396
+ at += (m.counts[c.id] / m.letters) * 100;
397
+ return `${swatch(c)} ${from.toFixed(2)}% ${at.toFixed(2)}%`;
398
+ });
399
+ return `conic-gradient(${stops.join(', ')})`;
400
+ }
401
+ const breakdown = (m, cats) => (m.letters ? cats.filter((c) => m.counts[c.id]).map((c) => `${c.label} ${percent(m.counts[c.id] / m.letters)}`).join(' · ') : 'No text');
402
+
403
+ /* ---------- colors follow the page: dark or light, whatever the system says ---------- */
404
+
405
+ function background(el) {
406
+ for (; el; el = el.parentElement) {
407
+ const m = /rgba?\(([\d.]+)[ ,]+([\d.]+)[ ,]+([\d.]+)(?:[ ,/]+([\d.]+%?))?/.exec(getComputedStyle(el).backgroundColor);
408
+ if (m && (m[4] === undefined || parseFloat(m[4]) > 0)) return m.slice(1, 4).map(Number);
409
+ }
410
+ return null;
411
+ }
412
+ let repaint = () => {};
413
+ function theme(force) {
414
+ const rgb = background(document.body);
415
+ const lin = (c) => { const s = c / 255; return s <= 0.04045 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4; };
416
+ const now = rgb ? 0.2126 * lin(rgb[0]) + 0.7152 * lin(rgb[1]) + 0.0722 * lin(rgb[2]) < 0.2
417
+ : matchMedia('(prefers-color-scheme: dark)').matches;
418
+ if (now === dark && force !== true) return;
419
+ dark = now;
420
+ document.documentElement.classList.toggle('slop-dark', dark);
421
+ applyColors();
422
+ paintMeters();
423
+ repaint();
424
+ }
425
+
426
+ /* ---------- Slop-o-meter: a switch, a pie of what the page is made of, and what its colors mean ---------- */
427
+
428
+ const store = {
429
+ get: (k) => { try { return localStorage.getItem(k); } catch { return null; } },
430
+ set: (k, v) => { try { localStorage.setItem(k, v); } catch { /* optional */ } },
431
+ drop: (k) => { try { localStorage.removeItem(k); } catch { /* optional */ } },
432
+ };
433
+ // what readers see is the page's choice, "nothing" unless it says otherwise. While the editor is open, its
434
+ // author sees the colors whatever readers get
435
+ const SHOW = ['nothing', 'pie', 'colors'];
436
+ const shows = () => (SHOW.includes(text._show) ? text._show : 'nothing');
437
+ const meters = [];
438
+ const built = new WeakMap(); // element → its meter
439
+ let meterOn = false;
440
+ let editing = false;
441
+ function setMeter(on) {
442
+ meterOn = on;
443
+ paintShow();
444
+ }
445
+ // a meter with a path (data-slop-meter="games.othello") measures the texts under it, and its switch colors only
446
+ // its section: the closest [data-slop-section], or its parent. A bare one measures the page and switches it
447
+ const inScope = (at) => ([path]) => !at || path === at || path.startsWith(`${at}.`);
448
+ const sectionOf = (m) => (m.at && m.el.parentElement ? m.el.closest('[data-slop-section]') ?? m.el.parentElement : document.documentElement);
449
+ function paintShow() {
450
+ const mode = shows();
451
+ document.documentElement.classList.toggle('slop-on', editing || (mode === 'colors' && meterOn));
452
+ meters.forEach((m) => {
453
+ m.el.dataset.show = mode;
454
+ const section = sectionOf(m);
455
+ if (m.section && m.section !== section) m.section.classList.remove('slop-on', 'slop-off');
456
+ m.section = section;
457
+ // a section's switch follows the page's until it's flipped. The editor shows the author every color
458
+ if (m.at) {
459
+ const own = mode === 'colors' && !editing ? m.own : null;
460
+ section.classList.toggle('slop-on', own === true);
461
+ section.classList.toggle('slop-off', own === false);
462
+ }
463
+ m.btn.setAttribute('aria-pressed', String(m.own ?? meterOn));
464
+ });
465
+ }
466
+ function paintMeters() {
467
+ // a meter the page took out of the document is dropped; it comes back if the page puts it back
468
+ meters.splice(0, meters.length, ...meters.filter((m) => m.el.isConnected));
469
+ paintShow();
470
+ if (!meters.length) return;
471
+ const cats = categories();
472
+ const all = entries();
473
+ const byScope = new Map();
474
+ meters.forEach(({ at, pie, legend }) => {
475
+ if (!byScope.has(at)) byScope.set(at, makeup(all.filter(inScope(at)).map(([, v]) => v)));
476
+ const m = byScope.get(at);
477
+ pie.style.background = gradient(m, cats);
478
+ pie.title = breakdown(m, cats);
479
+ pie.setAttribute('aria-label', pie.title);
480
+ // each category in its own color, with its share of the text
481
+ legend.innerHTML = cats.filter((c) => m.counts[c.id])
482
+ .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('');
483
+ });
484
+ }
485
+ function buildMeter(el) {
486
+ el.classList.add('slop-meter');
487
+ el.innerHTML = '<button type="button" class="slop-meter-btn" aria-pressed="false"><span class="slop-switch" aria-hidden="true"></span>Slop-o-meter</button>'
488
+ + '<span class="slop-meter-key"><span class="slop-pie" role="img"></span><span class="slop-legend"></span></span>';
489
+ 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') };
490
+ m.btn.addEventListener('click', () => {
491
+ const on = !(m.own ?? meterOn);
492
+ if (m.at) { m.own = on; paintShow(); return; } // only the page-wide choice is remembered
493
+ setMeter(on);
494
+ store.set('slop-o-meter', on ? 'on' : 'off');
495
+ });
496
+ // pointing at a tag dims everyone else's words, in the meter's section
497
+ const only = (e) => {
498
+ const key = e.type === 'mouseover' || e.type === 'focusin' ? e.target.closest('.slop-key') : null;
499
+ const section = m.section ?? sectionOf(m);
500
+ if (key) section.dataset.slopOnly = key.dataset.id;
501
+ else delete section.dataset.slopOnly;
502
+ };
503
+ ['mouseover', 'mouseout', 'focusin', 'focusout'].forEach((type) => m.legend.addEventListener(type, only));
504
+ built.set(el, m);
505
+ return m;
506
+ }
507
+ // build a meter (or take back one the page moved), and paint it
508
+ function meter(el) {
509
+ const m = built.get(el) ?? buildMeter(el);
510
+ if (!meters.includes(m)) meters.push(m);
511
+ paintMeters();
512
+ }
513
+
514
+ /* ---------- the editor ---------- */
515
+
516
+ const human = (key) => {
517
+ const p = /^p(\d+)$/.exec(key);
518
+ if (p) return `Paragraph ${p[1]}`;
519
+ const s = key.replace(/([a-z])([A-Z0-9])/g, '$1 $2').replace(/[_-]/g, ' ').toLowerCase();
520
+ return s.charAt(0).toUpperCase() + s.slice(1);
521
+ };
522
+ // a section is named after its title, if it has a short one, or its key
523
+ const groupTitle = (key) => {
524
+ const node = text[key];
525
+ const title = node && !isText(node) && isText(node.title) ? readable(node.title) : '';
526
+ return title && title.length <= 32 ? title : human(key);
527
+ };
528
+ // where a text is, for people: "Introduction · Paragraph 2"
529
+ const where = (path) => {
530
+ const [g, ...rest] = keysOf(path);
531
+ return [groupTitle(g), ...rest.map(human)].join(' · ');
532
+ };
533
+ const count = (n, one, many = `${one}s`) => `${n.toLocaleString()} ${n === 1 ? one : many}`;
534
+ const isLong = (path, value) => plain(value).length > 48 || /^p\d+$/.test(keysOf(path).at(-1));
535
+ const el = (tag, className, html = '') => Object.assign(document.createElement(tag), { className, innerHTML: html });
536
+
537
+ // what a hidden text is, by the attribute it's in
538
+ const KINDS = { alt: 'alt text', title: 'tooltip', 'aria-label': 'label', 'aria-description': 'description', placeholder: 'placeholder' };
539
+
540
+ // the editor opens on repeated text that still has slop, or on any text that does, or on everything
541
+ const slopIn = (path) => (makeup([get(path)]).counts.ai ?? 0) > 0;
542
+ const startTab = () => (repeats(entries()).some((s) => s.paths.some(slopIn)) ? 'repeats' : entries().some(([p]) => slopIn(p)) ? 'slop' : 'all');
543
+
544
+ function editor(mode) {
545
+ const LOCAL = `slop-text:${location.pathname}`;
546
+ // open: the first section, and any the page adds later (pasted text, say)
547
+ // it opens on Repeats, or on Slop left when nothing is repeated
548
+ const state = { tab: startTab(), open: new Set(groupKeys().slice(0, 1)), known: new Set(groupKeys()), focus: null };
549
+ let sets = repeats(entries());
550
+ let controls = []; // [{el, paths}] in the current view, repainted by numbers()
551
+ let undo = null;
552
+
553
+ const btn = el('button', 'slop-edit-btn', 'Edit text');
554
+ btn.type = 'button';
555
+ const aside = el('aside', 'slop-panel', `
556
+ <header class="sp-head" title="Drag to move, or drag an edge to resize. Double-click to put it back">
557
+ <span class="sp-grip" aria-hidden="true"></span>
558
+ <div><h2>Edit text</h2><p class="sp-status" role="status" aria-live="polite"></p></div>
559
+ <button type="button" class="sp-save" title="Save (⌘S)" disabled>Saved</button>
560
+ <button type="button" class="sp-close" aria-label="Close the editor">×</button>
561
+ </header>
562
+ <div class="sp-cover">
563
+ <div class="sp-cover-row"><p class="sp-big"><b></b> slop</p><p class="sp-words"></p></div>
564
+ <div class="sp-cats"></div>
565
+ <div class="sp-show"><span>Readers see</span><div class="sp-seg" role="radiogroup" aria-label="What readers see">
566
+ <button type="button" role="radio" data-show="nothing" title="No sign of the slop editor on the published page">Nothing</button>
567
+ <button type="button" role="radio" data-show="pie" title="A pie of who wrote what, with a legend">Pie chart</button>
568
+ <button type="button" role="radio" data-show="colors" title="The Slop-o-meter: a switch that colors every word by who wrote it, and the pie">Colors</button>
569
+ </div></div>
570
+ </div>
571
+ <div class="sp-tabs" role="tablist">
572
+ <button type="button" role="tab" data-tab="repeats">Repeats <span></span></button>
573
+ <button type="button" role="tab" data-tab="slop">Slop left <span></span></button>
574
+ <button type="button" role="tab" data-tab="all">All <span></span></button>
575
+ <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>
576
+ </div>
577
+ <div class="sp-body" role="tabpanel"></div>
578
+ ${['n', 's', 'e', 'w', 'ne', 'nw', 'se', 'sw'].map((e) => `<div class="sp-edge" data-edge="${e}" aria-hidden="true"></div>`).join('')}`);
579
+ aside.hidden = true;
580
+ aside.setAttribute('aria-label', 'Edit text');
581
+ document.body.append(btn, aside);
582
+ const $ = (sel) => aside.querySelector(sel);
583
+ const body = $('.sp-body');
584
+ const statusEl = $('.sp-status');
585
+ const pageControl = control(() => entries().map(([p]) => p), 'the whole page');
586
+ $('.sp-cover-row').append(pageControl);
587
+
588
+ function status(msg, kind = '', action) {
589
+ statusEl.textContent = msg;
590
+ statusEl.dataset.kind = kind;
591
+ if (!action) return;
592
+ const b = el('button', 'sp-link', esc(action.label));
593
+ b.type = 'button';
594
+ b.addEventListener('click', action.run);
595
+ statusEl.append(' · ', b);
596
+ }
597
+ const savedStatus = () => (mode === 'local'
598
+ ? status('Saved in this browser', '', { label: 'Reset', run: reset })
599
+ : status(`Saved · version ${text.version}`));
600
+
601
+ // any change to who wrote what (the slop switch, marking text, deleting a category) can be undone
602
+ function withUndo(what, change) {
603
+ const before = JSON.stringify(text);
604
+ change();
605
+ if (JSON.stringify(text) === before) return false;
606
+ touched();
607
+ if (state.tab === 'slop') render(); else numbers();
608
+ undo = before;
609
+ status(what, '', {
610
+ label: 'Undo',
611
+ run: () => {
612
+ if (!undo) return;
613
+ const version = text.version;
614
+ text = JSON.parse(undo);
615
+ text.version = version;
616
+ undo = null;
617
+ applyColors();
618
+ touched();
619
+ render();
620
+ },
621
+ });
622
+ return true;
623
+ }
624
+
625
+ /* the slop switch, next to a pie of what the texts are made of */
626
+ function control(paths, what, after) {
627
+ const c = el('span', 'sp-ctl', '<span class="sp-pie" role="img"></span>'
628
+ + '<button type="button" class="sp-toggle" role="switch"><span class="sp-switch" aria-hidden="true"></span>slop</button>');
629
+ const toggle = c.querySelector('.sp-toggle');
630
+ toggle.addEventListener('click', (e) => {
631
+ e.preventDefault(); // in a section's summary, don't open or close it
632
+ const on = toggle.getAttribute('aria-checked') === 'true';
633
+ const done = withUndo(on ? `Approved ${what}` : `Back to slop: ${what}`, () => paths().forEach((p) => set(p, on ? unslop(get(p)) : reslop(get(p)))));
634
+ if (done) after?.(on);
635
+ });
636
+ controls.push({ el: c, paths });
637
+ return c;
638
+ }
639
+ function paintControl({ el: c, paths }, cats) {
640
+ const m = makeup(paths().map(get));
641
+ const pie = c.querySelector('.sp-pie');
642
+ pie.style.background = gradient(m, cats);
643
+ pie.title = breakdown(m, cats);
644
+ pie.setAttribute('aria-label', pie.title);
645
+ const toggle = c.querySelector('.sp-toggle');
646
+ const on = (m.counts.ai ?? 0) > 0;
647
+ toggle.setAttribute('aria-checked', String(on));
648
+ toggle.disabled = !on && !m.counts.ok;
649
+ toggle.title = on ? 'Slop. Switch it off to approve the AI\'s words as they are'
650
+ : m.counts.ok ? 'Approved. Switch it on to make it slop again' : 'No AI-generated words here';
651
+ }
652
+
653
+ /* categories: a color picker and a name for each, and how much of the page is theirs */
654
+ const own = (id) => { text._categories ??= {}; return (text._categories[id] ??= {}); };
655
+ const slug = (label) => {
656
+ const base = label.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '') || 'category';
657
+ let id = base;
658
+ for (let n = 2; id in BUILTIN || text._categories?.[id] || categories().some((c) => c.id === id); n++) id = `${base}-${n}`;
659
+ return id;
660
+ };
661
+ function renderCats() {
662
+ const box = $('.sp-cats');
663
+ box.innerHTML = '';
664
+ categories().forEach((cat) => {
665
+ const row = el('span', 'sp-cat', `<label class="sp-swatch" title="Pick a color for ${esc(cat.label)}"><input type="color"></label>`
666
+ + `<input class="sp-cat-name" aria-label="Category name" spellcheck="false"><b class="sp-cat-pct"></b>`
667
+ + (cat.builtin ? '' : `<button type="button" class="sp-cat-x" title="Delete ${esc(cat.label)}: its words become AI-generated">×</button>`));
668
+ row.dataset.id = cat.id;
669
+ const picker = row.querySelector('input[type="color"]');
670
+ picker.value = hex(swatch(cat));
671
+ row.querySelector('.sp-swatch').style.background = swatch(cat);
672
+ picker.addEventListener('input', () => {
673
+ own(cat.id).color = picker.value;
674
+ row.querySelector('.sp-swatch').style.background = picker.value;
675
+ applyColors();
676
+ touched();
677
+ });
678
+ const name = row.querySelector('.sp-cat-name');
679
+ name.value = cat.label;
680
+ name.size = Math.max(3, cat.label.length);
681
+ name.addEventListener('input', () => {
682
+ name.size = Math.max(3, name.value.length);
683
+ own(cat.id).label = name.value.trim();
684
+ touched();
685
+ });
686
+ name.addEventListener('keydown', (e) => { if (e.key === 'Enter') name.blur(); });
687
+ row.querySelector('.sp-cat-x')?.addEventListener('click', () => {
688
+ withUndo(`Deleted "${cat.label}"`, () => {
689
+ entries().forEach(([p, v]) => set(p, reattribute(v, cat.id, 'ai')));
690
+ delete text._categories?.[cat.id];
691
+ });
692
+ applyColors();
693
+ render();
694
+ });
695
+ box.append(row);
696
+ });
697
+ const add = el('button', 'sp-cat-add', '+ Category');
698
+ add.type = 'button';
699
+ add.title = 'Another author or source: a co-author, an editor, a paper you quote';
700
+ add.addEventListener('click', () => {
701
+ const input = el('input', 'sp-cat-new');
702
+ input.placeholder = 'Name, then Enter';
703
+ add.replaceWith(input);
704
+ input.focus();
705
+ let finished = false;
706
+ const done = (keep) => {
707
+ if (finished) return;
708
+ finished = true;
709
+ const label = input.value.trim();
710
+ if (keep && label) {
711
+ const id = slug(label);
712
+ const color = PALETTE[categories().filter((c) => !c.builtin).length % PALETTE.length];
713
+ Object.assign(own(id), { label, color });
714
+ applyColors();
715
+ touched();
716
+ }
717
+ render();
718
+ };
719
+ input.addEventListener('keydown', (e) => { if (e.key === 'Enter') done(true); if (e.key === 'Escape') done(false); });
720
+ input.addEventListener('blur', () => done(true), { once: true });
721
+ });
722
+ box.append(add);
723
+ }
724
+
725
+ /* marking text: the focused field gets a row of categories. A selection, or the whole text, becomes theirs */
726
+ const assignEl = el('div', 'sp-assign');
727
+ function showAssign(wrap, input, paths) {
728
+ assignEl.innerHTML = '<span class="sp-assign-label"></span>';
729
+ categories().forEach((cat) => {
730
+ const b = el('button', 'sp-as', `<i style="background:${swatch(cat)}"></i>${esc(cat.label)}`);
731
+ b.type = 'button';
732
+ b.addEventListener('pointerdown', (e) => e.preventDefault()); // keep the focus and the selection
733
+ b.addEventListener('click', () => {
734
+ let [s, e] = [input.selectionStart, input.selectionEnd];
735
+ const whole = s === e;
736
+ if (whole) [s, e] = [0, input.value.length];
737
+ withUndo(`Marked ${whole ? 'the text' : 'the selection'} as ${cat.label}`, () => paths.forEach((p) => set(p, assign(get(p), s, e, cat.id))));
738
+ });
739
+ assignEl.append(b);
740
+ });
741
+ assignLabel(input);
742
+ wrap.append(assignEl);
743
+ }
744
+ const assignLabel = (input) => {
745
+ if (assignEl.firstChild) assignEl.firstChild.textContent = input.selectionStart === input.selectionEnd ? 'Mark all as' : 'Mark selection as';
746
+ };
747
+
748
+ /* the views */
749
+ const setOf = (path) => sets.find((s) => s.paths.includes(path));
750
+ const hasSlop = (path) => (makeup([get(path)]).counts.ai ?? 0) > 0;
751
+ const hint = (wrap, message, action) => {
752
+ const h = wrap.querySelector('.sp-hint');
753
+ h.innerHTML = esc(message);
754
+ h.hidden = false;
755
+ h.dataset.at = performance.now();
756
+ if (!action) return;
757
+ const b = el('button', 'sp-link', esc(action.label));
758
+ b.type = 'button';
759
+ b.addEventListener('pointerdown', (e) => e.preventDefault()); // keep the focus in the field
760
+ b.addEventListener('click', () => { h.hidden = true; action.run(); });
761
+ h.append(' ', b);
762
+ };
763
+ let pressed = false;
764
+ addEventListener('pointerdown', () => { pressed = true; }, true);
765
+ addEventListener('pointerup', () => { setTimeout(() => { pressed = false; }); }, true);
766
+ const afterClick = (fn) => {
767
+ if (!pressed) { fn(); return; }
768
+ addEventListener('pointerup', () => setTimeout(fn), { once: true, capture: true });
769
+ };
770
+
771
+ function field(path, { all } = {}) {
772
+ const value = get(path);
773
+ const wrap = el('div', 'sp-field');
774
+ wrap.dataset.path = path;
775
+ const fid = `sp-${path.replace(/\W/g, '-')}${all ? '-all' : ''}`;
776
+ const name = all ? `${all.paths.length} copies` : keysOf(path).slice(1).map(human).join(' · ') || human(path);
777
+ wrap.innerHTML = `<div class="sp-flabel"><label for="${fid}">${esc(name)}</label>`
778
+ + '<span class="sp-kind" hidden></span><button type="button" class="sp-unseen" hidden></button></div>'
779
+ + `<textarea id="${fid}" rows="1" spellcheck="true"></textarea><p class="sp-hint" hidden></p>`;
780
+ const row = wrap.querySelector('.sp-flabel');
781
+ const input = wrap.querySelector('textarea');
782
+ input.value = plain(value);
783
+ if (!isLong(path, value)) input.addEventListener('keydown', (e) => { if (e.key === 'Enter') e.preventDefault(); });
784
+ const paths = () => (all ? all.paths : [path]);
785
+ // back to how it was at the last save, words and authorship
786
+ const revert = el('button', 'sp-revert', 'Revert');
787
+ revert.type = 'button';
788
+ revert.title = 'Back to how this was at the last save';
789
+ revert.addEventListener('click', () => {
790
+ withUndo(`Reverted "${all ? all.words : where(path)}"`, () => paths().forEach((p) => { if (savedAt(p) !== undefined) set(p, savedAt(p)); }));
791
+ render();
792
+ });
793
+ row.append(revert);
794
+ if (!all) {
795
+ const rep = el('button', 'sp-rep');
796
+ rep.type = 'button';
797
+ rep.addEventListener('click', () => { const s = setOf(path); if (s) show('repeats', s.paths[0]); });
798
+ row.append(rep);
799
+ }
800
+ // a copy's switch changes that copy only, and says so. A Repeats card's switch changes every copy
801
+ row.append(control(paths, all ? count(all.paths.length, 'copy', 'copies') : `"${where(path)}"`, all ? null : (approved) => {
802
+ const others = (setOf(path)?.paths ?? []).filter((p) => p !== path);
803
+ if (!others.length) return;
804
+ const how = approved ? unslop : reslop;
805
+ hint(wrap, `Only this copy changed. ${count(others.length, 'other copy', 'other copies')} didn't.`, {
806
+ label: others.length === 1 ? 'Change it too' : 'Change them too',
807
+ run: () => withUndo(`${approved ? 'Approved' : 'Back to slop:'} ${count(others.length + 1, 'copy', 'copies')}`, () => others.forEach((p) => set(p, how(get(p))))),
808
+ });
809
+ }));
810
+ input.addEventListener('input', (e) => edit(paths(), input, /^history(Undo|Redo)$/.test(e.inputType)));
811
+ ['select', 'keyup', 'pointerup'].forEach((t) => input.addEventListener(t, () => assignLabel(input)));
812
+ input.addEventListener('focus', () => { focus(path, all, input, wrap); showAssign(wrap, input, paths()); });
813
+ input.addEventListener('blur', () => {
814
+ mark(false);
815
+ // after the click that moved the focus lands: removing these first would move what's being clicked
816
+ afterClick(() => {
817
+ if (document.activeElement === input) return;
818
+ wrap.querySelector('.sp-hint').hidden = true;
819
+ if (assignEl.parentNode === wrap) assignEl.remove();
820
+ });
821
+ });
822
+ wrap.querySelector('.sp-unseen').addEventListener('click', () => input.focus());
823
+ wrap.input = input;
824
+ wrap.rep = wrap.querySelector('.sp-rep');
825
+ wrap.kind = wrap.querySelector('.sp-kind');
826
+ wrap.revert = revert;
827
+ wrap.paths = paths;
828
+ return wrap;
829
+ }
830
+
831
+ function groupView(key, paths) {
832
+ const det = el('details', 'sp-group', `<summary><span class="sp-gname">${esc(groupTitle(key))}</span><span class="sp-gnote"></span></summary>`);
833
+ det.dataset.group = key;
834
+ det.open = state.open.has(key) || state.tab === 'hidden'; // there are few, so all of them show
835
+ const all = entries(text[key], [key]).map(([p]) => p);
836
+ det.querySelector('summary').append(control(() => all, `"${groupTitle(key)}"`));
837
+ det.addEventListener('toggle', () => {
838
+ if (det.open) { state.open.add(key); det.querySelectorAll('textarea').forEach(grow); } else state.open.delete(key);
839
+ });
840
+ paths.forEach((p) => det.append(field(p)));
841
+ return det;
842
+ }
843
+
844
+ function render() {
845
+ controls = [controls.find((c) => c.el === pageControl)];
846
+ sets = repeats(entries());
847
+ groupKeys().forEach((k) => { if (!state.known.has(k)) { state.known.add(k); state.open.add(k); } });
848
+ renderCats();
849
+ const top = body.scrollTop;
850
+ body.innerHTML = '';
851
+ aside.querySelectorAll('.sp-tabs button').forEach((b) => b.setAttribute('aria-selected', String(b.dataset.tab === state.tab)));
852
+ if (state.tab === 'repeats') {
853
+ body.insertAdjacentHTML('beforeend', '<p class="sp-intro">The same words in more than one place. Each copy is slop until it\'s approved. Here, editing or switching a card changes every copy.</p>');
854
+ if (!sets.length) body.insertAdjacentHTML('beforeend', '<p class="sp-empty">No repeated text on this page.</p>');
855
+ sets.forEach((s) => {
856
+ const card = field(s.paths[0], { all: s });
857
+ card.classList.add('sp-set');
858
+ const list = el('ul', 'sp-where');
859
+ s.paths.forEach((p) => {
860
+ const li = document.createElement('li');
861
+ const go = el('button', 'sp-goto', `<span class="sp-pie sp-mini"></span>${esc(where(p))}`);
862
+ go.type = 'button';
863
+ go.dataset.path = p;
864
+ go.addEventListener('click', () => show('all', p));
865
+ go.addEventListener('pointerenter', () => mark(true, [p]));
866
+ go.addEventListener('pointerleave', () => mark(false));
867
+ li.append(go);
868
+ list.append(li);
869
+ });
870
+ card.append(list);
871
+ body.append(card);
872
+ });
873
+ } else {
874
+ const tab = state.tab;
875
+ const keep = tab === 'slop' ? hasSlop : tab === 'hidden' ? attrOf : () => true;
876
+ 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>');
877
+ let shown = 0;
878
+ groupKeys().forEach((key) => {
879
+ const paths = (isText(text[key]) ? [key] : entries(text[key], [key]).map(([p]) => p)).filter(keep);
880
+ if (!paths.length) return;
881
+ shown += paths.length;
882
+ body.append(isText(text[key]) ? field(key) : groupView(key, paths));
883
+ });
884
+ 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>');
885
+ 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>');
886
+ }
887
+ aside.classList.add('sp-still'); // new switches appear as they are, without sliding there
888
+ numbers();
889
+ body.querySelectorAll('textarea').forEach(grow);
890
+ body.scrollTop = top;
891
+ requestAnimationFrame(() => requestAnimationFrame(() => aside.classList.remove('sp-still')));
892
+ }
893
+
894
+ // every number, pie and switch in the editor, after any change
895
+ function numbers() {
896
+ const cats = categories();
897
+ const all = entries();
898
+ const page = makeup(all.map(([, v]) => v));
899
+ $('.sp-big b').textContent = percent(page.letters ? (page.counts.ai ?? 0) / page.letters : 0);
900
+ $('.sp-words').textContent = count(page.allWords, 'word');
901
+ aside.querySelectorAll('.sp-seg button').forEach((b) => b.setAttribute('aria-checked', String(b.dataset.show === shows())));
902
+ aside.querySelectorAll('.sp-cat').forEach((row) => {
903
+ row.querySelector('.sp-cat-pct').textContent = percent(page.letters ? (page.counts[row.dataset.id] ?? 0) / page.letters : 0);
904
+ });
905
+ controls.forEach((c) => paintControl(c, cats));
906
+ body.querySelectorAll('.sp-goto').forEach((go) => {
907
+ const m = makeup([get(go.dataset.path)]);
908
+ go.querySelector('.sp-pie').style.background = gradient(m, cats);
909
+ go.title = breakdown(m, cats);
910
+ });
911
+ const live = repeats(all);
912
+ const hidden = new Map(all.map(([p]) => [p, attrOf(p)]).filter(([, a]) => a));
913
+ const tabs = { all: all.length, slop: all.filter(([p]) => hasSlop(p)).length, repeats: live.length, hidden: hidden.size };
914
+ aside.querySelectorAll('.sp-tabs button').forEach((b) => {
915
+ b.querySelector('span').textContent = tabs[b.dataset.tab];
916
+ if (b.dataset.tab === 'hidden') b.hidden = !hidden.size && state.tab !== 'hidden'; // only on pages that have some
917
+ });
918
+ body.querySelectorAll('.sp-field').forEach((f) => {
919
+ f.revert.hidden = !f.paths().some((p) => differs(p) && savedAt(p) !== undefined);
920
+ const tag = f.querySelector('.sp-unseen');
921
+ const shown = revealed && f.paths().includes(revealed.path);
922
+ tag.hidden = !shown && f.paths().some(onPage);
923
+ tag.disabled = shown || !revealerOf(f.paths()[0]);
924
+ tag.textContent = shown ? 'shown while editing' : tag.disabled ? 'not on the page' : 'not on the page · show it';
925
+ tag.title = shown ? 'The page normally hides this. It\'s shown while you edit it'
926
+ : 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'
927
+ : 'Show the page the way it looks with this text';
928
+ const kind = f.paths().map((p) => hidden.get(p)).find(Boolean);
929
+ f.kind.hidden = !kind;
930
+ f.kind.textContent = KINDS[kind] ?? kind ?? '';
931
+ f.kind.title = kind ? `Not shown as words: the page's ${kind} attribute` : '';
932
+ });
933
+ paintSave();
934
+ body.querySelectorAll('.sp-field:not(.sp-set)').forEach((f) => {
935
+ const s = live.find((r) => r.paths.includes(f.dataset.path));
936
+ f.rep.hidden = !s;
937
+ if (!s) return;
938
+ f.rep.textContent = `${s.paths.length}×`;
939
+ f.rep.title = `Same words in ${count(s.paths.length - 1, 'other place')}: ${s.paths.filter((p) => p !== f.dataset.path).map(where).join(', ')}`;
940
+ });
941
+ body.querySelectorAll('.sp-group').forEach((det) => {
942
+ const paths = entries(text[det.dataset.group], [det.dataset.group]);
943
+ const left = paths.filter(([p]) => hasSlop(p)).length;
944
+ det.querySelector('.sp-gnote').textContent = left ? `${left} of ${paths.length} with slop` : 'no slop';
945
+ });
946
+ paintMeters();
947
+ }
948
+ repaint = () => { if (!aside.hidden) render(); };
949
+
950
+ // the page and the editor point at each other
951
+ function mark(on, paths = state.focus?.paths ?? [], scroll = false, tries = 0) {
952
+ document.querySelectorAll('.slop-focus, .slop-copy').forEach((x) => x.classList.remove('slop-focus', 'slop-copy'));
953
+ if (!on) return;
954
+ paths.forEach((p, i) => elementsOf(p).forEach((x) => x.classList.add(i ? 'slop-copy' : 'slop-focus')));
955
+ const target = paths.map((p) => elementsOf(p)[0]).find(Boolean);
956
+ if (!scroll) return;
957
+ // a text the page only just revealed may not be drawn yet (React and the like draw on the next frame)
958
+ if (!target) {
959
+ if (tries < 10) requestAnimationFrame(() => { if (state.focus?.paths === paths) mark(true, paths, true, tries + 1); });
960
+ return;
961
+ }
962
+ // scroll whatever holds it (the window, or a panel of the page's that scrolls on its own) to bring it to
963
+ // the middle of what's visible, unless it's already well in view
964
+ const box = scroller(target);
965
+ const r = target.getBoundingClientRect();
966
+ const top = box ? Math.max(box.getBoundingClientRect().top, 0) : 0;
967
+ const bottom = Math.min(box ? box.getBoundingClientRect().bottom : innerHeight, innerWidth <= 900 ? aside.getBoundingClientRect().top : innerHeight);
968
+ const pad = Math.min(120, (bottom - top) / 5); // room for a header that stays put
969
+ if (r.top < top + pad || r.bottom > bottom - 8) (box ?? window).scrollBy({ top: r.top - (top + bottom - r.height) / 2, behavior: 'smooth' });
970
+ }
971
+ // the nearest element around `el` that scrolls, or null for the window
972
+ function scroller(el) {
973
+ for (let p = el.parentElement; p && p !== document.body && p !== document.documentElement; p = p.parentElement) {
974
+ if (/(auto|scroll|overlay)/.test(getComputedStyle(p).overflowY) && p.scrollHeight > p.clientHeight) return p;
975
+ }
976
+ return null;
977
+ }
978
+ function focus(path, all, input, wrap) {
979
+ const s = all ?? setOf(path);
980
+ const paths = all ? all.paths : [path, ...(s ? s.paths.filter((p) => p !== path) : [])];
981
+ state.focus = { path, paths, copies: all || !s ? [] : s.paths.filter((p) => p !== path), was: wordsOf(get(path)), wrap, linked: null };
982
+ if (revealed && !paths.includes(revealed.path)) unreveal();
983
+ if (!paths.some(onPage)) showHidden(paths[0]);
984
+ mark(true, paths, true);
985
+ }
986
+ // a text the page hides: shown while it's being edited, if the page says how
987
+ let revealed = null; // {path, undo}
988
+ function showHidden(path) {
989
+ const fn = revealerOf(path);
990
+ if (!fn || revealed?.path === path) return;
991
+ try { revealed = { path, undo: fn() }; } catch (e) { console.error(e); return; }
992
+ fill();
993
+ numbers();
994
+ }
995
+ function unreveal() {
996
+ if (!revealed) return;
997
+ const { undo: hide } = revealed;
998
+ revealed = null;
999
+ try { hide?.(); } catch (e) { console.error(e); }
1000
+ numbers();
1001
+ }
1002
+ // show one text: in this tab if it's there, otherwise in All
1003
+ function show(tab, path) {
1004
+ state.tab = tab;
1005
+ if (tab !== 'repeats') state.open.add(keysOf(path)[0]);
1006
+ render();
1007
+ const f = [...body.querySelectorAll('.sp-field')].find((x) => x.dataset.path === path);
1008
+ if (!f) return;
1009
+ f.scrollIntoView({ block: 'center', behavior: 'smooth' });
1010
+ f.input.focus({ preventScroll: true });
1011
+ f.classList.add('sp-flash');
1012
+ setTimeout(() => f.classList.remove('sp-flash'), 900);
1013
+ }
1014
+
1015
+ const grow = (x) => { x.style.height = 'auto'; x.style.height = `${x.scrollHeight + 2}px`; };
1016
+
1017
+ // typing: what you type is yours, the rest keeps its author
1018
+ // ⌘Z in a text: the words come back with whoever wrote them, from each text's recent versions
1019
+ const past = new Map(); // path → [value, …], oldest first
1020
+ function remember(p) {
1021
+ const list = past.get(p) ?? [];
1022
+ const v = get(p);
1023
+ if (JSON.stringify(list.at(-1)) !== JSON.stringify(v)) list.push(v);
1024
+ past.set(p, list.slice(-200));
1025
+ }
1026
+ const recall = (p, words) => past.get(p)?.findLast((v) => plain(v) === words);
1027
+ function edit(paths, input, restoring) {
1028
+ undo = null;
1029
+ const f = state.focus;
1030
+ [...paths, ...(f?.linked ?? [])].forEach((p) => {
1031
+ remember(p);
1032
+ set(p, applyEdit(get(p), input.value, restoring ? recall(p, input.value) : undefined));
1033
+ remember(p);
1034
+ });
1035
+ grow(input);
1036
+ if (f?.copies.length && !f.linked) {
1037
+ // a copy changed on its own: offer to change the others the same way
1038
+ const stale = f.copies.filter((p) => wordsOf(get(p)) === f.was);
1039
+ if (!stale.length || wordsOf(input.value) === f.was) f.wrap.querySelector('.sp-hint').hidden = true;
1040
+ else {
1041
+ hint(f.wrap, `Changed here only. ${count(stale.length, 'other copy', 'other copies')} still ${stale.length === 1 ? 'says' : 'say'} the old words.`, {
1042
+ label: stale.length === 1 ? 'Change it too' : 'Change them too',
1043
+ run: () => { // and keep them in step while this field has the focus
1044
+ stale.forEach((p) => set(p, applyEdit(get(p), input.value)));
1045
+ f.linked = stale;
1046
+ touched();
1047
+ },
1048
+ });
1049
+ }
1050
+ }
1051
+ touched();
1052
+ }
1053
+
1054
+ // saving: only with the Save button (or ⌘S), one request at a time, each carrying the version it was based on.
1055
+ // `saved` is the text as of the last save, for the Save button's count and each text's Revert
1056
+ let saved = JSON.parse(JSON.stringify(text));
1057
+ let busy = false;
1058
+ let stale = false;
1059
+ function valueAt(root, p) {
1060
+ let node = root;
1061
+ for (const key of keysOf(p)) node = node?.[key];
1062
+ return isText(node) ? node : undefined;
1063
+ }
1064
+ const savedAt = (p) => valueAt(saved, p);
1065
+ const differs = (p) => JSON.stringify(valueAt(text, p)) !== JSON.stringify(savedAt(p));
1066
+ // how many texts changed since the last save (and the categories, as one)
1067
+ function unsaved() {
1068
+ const paths = new Set([...entries(), ...entries(saved)].map(([p]) => p));
1069
+ let n = [...paths].filter(differs).length;
1070
+ const metaKeys = new Set([...Object.keys(text), ...Object.keys(saved)].filter((k) => k.startsWith('_')));
1071
+ n += [...metaKeys].filter((k) => JSON.stringify(text[k] ?? null) !== JSON.stringify(saved[k] ?? null)).length;
1072
+ return n;
1073
+ }
1074
+ const saveBtn = $('.sp-save');
1075
+ function paintSave() {
1076
+ const n = unsaved();
1077
+ saveBtn.disabled = !n || busy;
1078
+ saveBtn.textContent = busy ? 'Saving…' : n ? `Save ${n}` : 'Saved';
1079
+ saveBtn.title = n ? `Save ${count(n, 'change')} (⌘S)` : 'Everything is saved';
1080
+ }
1081
+ async function save() {
1082
+ if (busy || !unsaved()) return;
1083
+ if (stale) { status('This page is out of date: reload it to save (copy any edits first)', 'error'); return; }
1084
+ const body = JSON.stringify(text);
1085
+ if (mode === 'local') {
1086
+ store.set(LOCAL, JSON.stringify({ base: JSON.parse(original).version, text: JSON.parse(body) }));
1087
+ saved = JSON.parse(body);
1088
+ undo = null;
1089
+ savedStatus();
1090
+ numbers();
1091
+ return;
1092
+ }
1093
+ busy = true;
1094
+ paintSave();
1095
+ try {
1096
+ const res = await fetch('/__slop', { method: 'POST', headers: { 'content-type': 'application/json' }, body });
1097
+ const out = await res.text();
1098
+ if (res.status === 409) { stale = true; throw new Error(out); }
1099
+ if (!res.ok) throw new Error(out || res.statusText);
1100
+ text.version = Number(out);
1101
+ saved = { ...JSON.parse(body), version: text.version };
1102
+ undo = null;
1103
+ savedStatus();
1104
+ } catch (e) {
1105
+ status(`Couldn't save: ${e.message}`, 'error');
1106
+ } finally {
1107
+ busy = false;
1108
+ numbers();
1109
+ }
1110
+ }
1111
+ saveBtn.addEventListener('click', save);
1112
+ function touched() {
1113
+ numbers();
1114
+ changed();
1115
+ if (!stale && !undo) status(unsaved() ? 'Not saved yet' : 'No changes since the last save', unsaved() ? 'dirty' : '');
1116
+ }
1117
+ function reset() {
1118
+ store.drop(LOCAL);
1119
+ text = JSON.parse(original);
1120
+ saved = JSON.parse(original);
1121
+ undo = null;
1122
+ applyColors();
1123
+ changed();
1124
+ render();
1125
+ savedStatus();
1126
+ }
1127
+ addEventListener('beforeunload', (e) => { if (busy || unsaved()) e.preventDefault(); });
1128
+ addEventListener('keydown', (e) => {
1129
+ if ((e.metaKey || e.ctrlKey) && e.key === 's' && !aside.hidden) { e.preventDefault(); save(); }
1130
+ // ⌘Z outside a text undoes the last switch or mark (a text's own ⌘Z undoes its typing)
1131
+ if ((e.metaKey || e.ctrlKey) && !e.shiftKey && e.key === 'z' && undo && !aside.hidden && !e.target.closest?.('textarea, input')) {
1132
+ e.preventDefault();
1133
+ statusEl.querySelector('.sp-link')?.click();
1134
+ }
1135
+ });
1136
+ body.addEventListener('pointerdown', (e) => {
1137
+ if (e.target.closest('.sp-hint')) return;
1138
+ const at = performance.now(); // a hint this click makes stays
1139
+ afterClick(() => body.querySelectorAll('.sp-hint').forEach((h) => { if (!(h.dataset.at > at)) h.hidden = true; }));
1140
+ });
1141
+
1142
+ // while the editor is open, a click on a text opens it in the editor
1143
+ document.addEventListener('click', (e) => {
1144
+ if (aside.hidden || aside.contains(e.target) || btn.contains(e.target)) return;
1145
+ const target = e.target.closest('[data-slop], [data-slop-ref], [data-slop-attr]');
1146
+ if (!target) return;
1147
+ e.preventDefault();
1148
+ e.stopPropagation();
1149
+ const path = target.dataset.slop || target.dataset.slopRef || attrsOf(target)[0]?.[1];
1150
+ if (!path) return;
1151
+ const s = setOf(path);
1152
+ if (state.tab === 'repeats' && s) show('repeats', s.paths[0]);
1153
+ else show(state.tab === 'slop' && hasSlop(path) ? 'slop' : 'all', path);
1154
+ }, true);
1155
+
1156
+ /* moving and resizing: drag the header to move the editor, or an edge to resize it. On a narrow screen it's a
1157
+ sheet along the bottom, and dragging changes its height. Double-click the header to put it back */
1158
+ const RECT = 'slop-editor-rect';
1159
+ const MIN = { w: 300, h: 240 };
1160
+ const narrow = () => innerWidth <= 900;
1161
+ const clamp = (v, lo, hi) => Math.min(Math.max(v, lo), Math.max(lo, hi));
1162
+ let rect = {};
1163
+ try { rect = JSON.parse(store.get(RECT)) ?? {}; } catch { /* docked */ }
1164
+ function place() {
1165
+ aside.removeAttribute('style');
1166
+ if (narrow()) {
1167
+ if (rect.sheet) aside.style.height = `${clamp(rect.sheet, 200, innerHeight - 16)}px`;
1168
+ return;
1169
+ }
1170
+ if (!rect.box) return;
1171
+ const w = clamp(rect.box.w, MIN.w, innerWidth - 16);
1172
+ const h = clamp(rect.box.h, MIN.h, innerHeight - 16);
1173
+ Object.assign(aside.style, {
1174
+ left: `${clamp(rect.box.l, 8, innerWidth - w - 8)}px`, top: `${clamp(rect.box.t, 8, innerHeight - h - 8)}px`,
1175
+ width: `${w}px`, height: `${h}px`, right: 'auto', bottom: 'auto',
1176
+ });
1177
+ }
1178
+ function drag(e, edge) {
1179
+ if (e.button !== 0) return;
1180
+ e.preventDefault();
1181
+ const start = aside.getBoundingClientRect();
1182
+ const x0 = e.clientX;
1183
+ const y0 = e.clientY;
1184
+ const target = e.currentTarget;
1185
+ target.setPointerCapture(e.pointerId);
1186
+ document.documentElement.classList.add('slop-dragging');
1187
+ const move = (ev) => {
1188
+ const dx = ev.clientX - x0;
1189
+ const dy = ev.clientY - y0;
1190
+ if (narrow()) { rect.sheet = Math.max(200, start.height - dy); place(); return; }
1191
+ let { left: l, top: t, width: w, height: h } = start;
1192
+ const sides = edge === 'move' ? '' : edge;
1193
+ if (edge === 'move') { l += dx; t += dy; }
1194
+ if (sides.includes('e')) w = Math.max(MIN.w, start.width + dx);
1195
+ if (sides.includes('s')) h = Math.max(MIN.h, start.height + dy);
1196
+ if (sides.includes('w')) { w = Math.max(MIN.w, start.width - dx); l = start.right - w; }
1197
+ if (sides.includes('n')) { h = Math.max(MIN.h, start.height - dy); t = start.bottom - h; }
1198
+ rect.box = { l, t, w, h };
1199
+ place();
1200
+ };
1201
+ const up = () => {
1202
+ target.removeEventListener('pointermove', move);
1203
+ target.removeEventListener('pointerup', up);
1204
+ target.removeEventListener('pointercancel', up);
1205
+ document.documentElement.classList.remove('slop-dragging');
1206
+ store.set(RECT, JSON.stringify(rect));
1207
+ };
1208
+ target.addEventListener('pointermove', move);
1209
+ target.addEventListener('pointerup', up);
1210
+ target.addEventListener('pointercancel', up);
1211
+ }
1212
+ const head = $('.sp-head');
1213
+ head.addEventListener('pointerdown', (e) => { if (!e.target.closest('button')) drag(e, 'move'); });
1214
+ head.addEventListener('dblclick', (e) => {
1215
+ if (e.target.closest('button')) return;
1216
+ rect = {};
1217
+ store.drop(RECT);
1218
+ place();
1219
+ });
1220
+ aside.querySelectorAll('.sp-edge').forEach((x) => x.addEventListener('pointerdown', (e) => drag(e, x.dataset.edge)));
1221
+ addEventListener('resize', () => { if (!aside.hidden) place(); });
1222
+
1223
+ const open = (on) => {
1224
+ aside.hidden = !on;
1225
+ btn.hidden = on;
1226
+ document.documentElement.classList.toggle('slop-editing', on);
1227
+ editing = on;
1228
+ paintShow();
1229
+ if (!on) { mark(false); unreveal(); return; }
1230
+ place();
1231
+ render();
1232
+ };
1233
+ btn.addEventListener('click', () => open(true));
1234
+ $('.sp-close').addEventListener('click', () => open(false));
1235
+ aside.querySelectorAll('.sp-seg button').forEach((b) => b.addEventListener('click', () => {
1236
+ if (b.dataset.show === shows()) return;
1237
+ withUndo(`Readers see: ${b.textContent.toLowerCase()}`, () => {
1238
+ if (b.dataset.show === 'nothing') delete text._show; // the default, so the block needn't say it
1239
+ else text._show = b.dataset.show;
1240
+ });
1241
+ }));
1242
+ aside.querySelectorAll('.sp-tabs button').forEach((b) => b.addEventListener('click', () => { state.tab = b.dataset.tab; render(); }));
1243
+ savedStatus();
1244
+ return { render: () => { if (!aside.hidden) render(); }, touched, open };
1245
+ }
1246
+
1247
+ // after the page changes the text itself (Slop.set, Slop.remove): refill the page, rebuild the editor and save
1248
+ let ed = null;
1249
+ function refresh() {
1250
+ fill();
1251
+ paintMeters();
1252
+ ed?.render();
1253
+ ed?.touched();
1254
+ }
1255
+ function remove(path) {
1256
+ const keys = keysOf(path);
1257
+ let node = text;
1258
+ keys.slice(0, -1).forEach((key) => { node = node?.[key]; });
1259
+ if (node) delete node[keys[keys.length - 1]];
1260
+ }
1261
+
1262
+ // set things up once the page has filled in Slop.vars. Options: code (the class `code` renders with),
1263
+ // edit: 'local' (an editor anyone can use, saving in their browser; under `slop-editor edit` it saves into the file)
1264
+ function start(options = {}) {
1265
+ Object.assign(config, options);
1266
+ fill();
1267
+ document.querySelectorAll('[data-slop-meter]').forEach((x) => { meters.push(buildMeter(x)); });
1268
+ new MutationObserver((changes) => changes.forEach((c) => c.addedNodes.forEach(added))).observe(document.body, { childList: true, subtree: true });
1269
+ theme(true);
1270
+ const watch = new MutationObserver(theme);
1271
+ [document.documentElement, document.body].forEach((x) => watch.observe(x, { attributes: true, attributeFilter: ['class', 'data-theme', 'style'] }));
1272
+ matchMedia('(prefers-color-scheme: dark)').addEventListener('change', theme);
1273
+ setMeter(store.get('slop-o-meter') !== 'off'); // on unless this reader turned it off
1274
+ // the browser editor: what this visitor changed last time, if the page hasn't changed since
1275
+ const local = () => {
1276
+ if (options.edit !== 'local') return;
1277
+ try {
1278
+ const saved = JSON.parse(store.get(`slop-text:${location.pathname}`));
1279
+ if (saved?.base === text.version) { text = saved.text; applyColors(); changed(); }
1280
+ } catch { /* nothing saved */ }
1281
+ ed = editor('local');
1282
+ };
1283
+ // the file editor only on this machine, under `slop-editor edit` (a GET there answers "slop-editor")
1284
+ if (!/^(localhost|127\.0\.0\.1|\[::1\])$/.test(location.hostname)) return local();
1285
+ fetch('/__slop').then((res) => (res.ok ? res.text() : '')).then((s) => { if (s === 'slop-editor') ed = editor('file'); else local(); }).catch(local);
1286
+ }
1287
+
1288
+ return { ...core, get, set, remove, entries, categories, html, words, fill, refresh, onChange, reveal, meter, start, get text() { return text; } };
1289
+ })();