slop-editor 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +133 -2
- package/cli.mjs +235 -0
- package/package.json +39 -4
- package/slop.css +209 -0
- package/slop.js +1179 -0
package/slop.js
ADDED
|
@@ -0,0 +1,1179 @@
|
|
|
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) => ({ '&': '&', '<': '<', '>': '>', '"': '"' })[c]);
|
|
136
|
+
const stripTags = (h) => h.replace(/<[^>]*>/g, '').replace(/ /g, ' ').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/&/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
|
+
const elementsOf = (path) => document.querySelectorAll(`[data-slop="${CSS.escape(dotted(path))}"]`);
|
|
270
|
+
|
|
271
|
+
// texts the page's code has rendered (Slop.html, Slop.words): with the [data-slop] elements, what's on the page
|
|
272
|
+
const rendered = new Set();
|
|
273
|
+
const html = (path, local) => { rendered.add(dotted(path)); return render(get(path), local); };
|
|
274
|
+
const words = (path, local) => { rendered.add(dotted(path)); return readable(get(path), local); };
|
|
275
|
+
const onPage = (path) => rendered.has(dotted(path)) || elementsOf(path).length > 0;
|
|
276
|
+
// 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
|
+
// that shows it and returns a function that undoes that. A group's key covers all its texts
|
|
278
|
+
const revealers = new Map();
|
|
279
|
+
const reveal = (path, fn) => { revealers.set(dotted(path), fn); };
|
|
280
|
+
const revealerOf = (path) => revealers.get(dotted(path)) ?? revealers.get(keysOf(path)[0]);
|
|
281
|
+
// fill every [data-slop] element (data-slop-vars: a JSON object of extra values)
|
|
282
|
+
function fill(root = document) {
|
|
283
|
+
root.querySelectorAll('[data-slop]').forEach((el) => {
|
|
284
|
+
const local = el.dataset.slopVars ? JSON.parse(el.dataset.slopVars) : undefined;
|
|
285
|
+
const h = render(get(el.dataset.slop), local);
|
|
286
|
+
if (el.innerHTML !== h) el.innerHTML = h;
|
|
287
|
+
});
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
const listeners = [];
|
|
291
|
+
const onChange = (fn) => listeners.push(fn);
|
|
292
|
+
let pending = false;
|
|
293
|
+
function changed() { // after an edit: refill the page, then let the page redo whatever it built from the text
|
|
294
|
+
if (pending) return;
|
|
295
|
+
pending = true;
|
|
296
|
+
requestAnimationFrame(() => {
|
|
297
|
+
pending = false;
|
|
298
|
+
fill();
|
|
299
|
+
listeners.forEach((fn) => { try { fn(); } catch (e) { console.error(e); } });
|
|
300
|
+
paintMeters();
|
|
301
|
+
});
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
/* ---------- categories and their colors ---------- */
|
|
305
|
+
|
|
306
|
+
let dark = false;
|
|
307
|
+
const ink = () => getComputedStyle(document.body).color;
|
|
308
|
+
// any CSS color as #rrggbb, for the color pickers
|
|
309
|
+
const hex = (color) => {
|
|
310
|
+
const x = document.createElement('canvas').getContext('2d');
|
|
311
|
+
x.fillStyle = '#000';
|
|
312
|
+
x.fillStyle = color;
|
|
313
|
+
const m = /rgba?\(([\d.]+)[ ,]+([\d.]+)[ ,]+([\d.]+)/.exec(x.fillStyle);
|
|
314
|
+
return m ? `#${m.slice(1, 4).map((v) => Math.round(+v).toString(16).padStart(2, '0')).join('')}` : x.fillStyle;
|
|
315
|
+
};
|
|
316
|
+
// a category's color: the page's choice (in the block, or --slop-<id> in its CSS), or the default for the theme.
|
|
317
|
+
// null for my words, unless picked: they keep the page's color
|
|
318
|
+
function colorOf(id, n) {
|
|
319
|
+
const own = text._categories?.[id]?.color;
|
|
320
|
+
if (own && CSS.supports('color', own)) return own;
|
|
321
|
+
const css = getComputedStyle(document.documentElement).getPropertyValue(`--slop-${id}`).trim();
|
|
322
|
+
if (css) return css;
|
|
323
|
+
if (BUILTIN[id]) return BUILTIN[id][dark ? 'dark' : 'light'];
|
|
324
|
+
return PALETTE[n % PALETTE.length];
|
|
325
|
+
}
|
|
326
|
+
// every category, in the order they're shown: mine, approved, the page's own, data, slop
|
|
327
|
+
function categories() {
|
|
328
|
+
const own = text._categories ?? {};
|
|
329
|
+
const used = entries().flatMap(([, v]) => (typeof v === 'string' ? [] : v.map(authorOf)));
|
|
330
|
+
const custom = [...new Set([...Object.keys(own), ...used])].filter((id) => !(id in BUILTIN));
|
|
331
|
+
return ['me', 'ok', ...custom, 'data', 'ai'].map((id) => ({
|
|
332
|
+
id,
|
|
333
|
+
label: own[id]?.label || BUILTIN[id]?.label || id,
|
|
334
|
+
color: colorOf(id, custom.indexOf(id)),
|
|
335
|
+
builtin: id in BUILTIN,
|
|
336
|
+
}));
|
|
337
|
+
}
|
|
338
|
+
const swatch = (cat) => cat.color ?? ink();
|
|
339
|
+
|
|
340
|
+
// the colors go in a stylesheet of their own: each category's words while the Slop-o-meter is on, and
|
|
341
|
+
// --slop-c-<id> for anything else that wants them
|
|
342
|
+
let sheet = null;
|
|
343
|
+
function applyColors() {
|
|
344
|
+
sheet ??= document.head.appendChild(Object.assign(document.createElement('style'), { id: 'slop-colors' }));
|
|
345
|
+
const cats = categories().filter((c) => c.color);
|
|
346
|
+
sheet.textContent = `:root{${cats.map((c) => `--${cls(c.id).replace('slop-', 'slop-c-')}:${c.color}`).join(';')}}\n`
|
|
347
|
+
+ cats.map((c) => `html.slop-on .${cls(c.id)}{color:${c.color}}`).join('\n');
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
// a pie of what these texts are made of, and the same in words for its tooltip
|
|
351
|
+
function gradient(m, cats) {
|
|
352
|
+
if (!m.letters) return '';
|
|
353
|
+
let at = 0;
|
|
354
|
+
const stops = cats.filter((c) => m.counts[c.id]).map((c) => {
|
|
355
|
+
const from = at;
|
|
356
|
+
at += (m.counts[c.id] / m.letters) * 100;
|
|
357
|
+
return `${swatch(c)} ${from.toFixed(2)}% ${at.toFixed(2)}%`;
|
|
358
|
+
});
|
|
359
|
+
return `conic-gradient(${stops.join(', ')})`;
|
|
360
|
+
}
|
|
361
|
+
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');
|
|
362
|
+
|
|
363
|
+
/* ---------- colors follow the page: dark or light, whatever the system says ---------- */
|
|
364
|
+
|
|
365
|
+
function background(el) {
|
|
366
|
+
for (; el; el = el.parentElement) {
|
|
367
|
+
const m = /rgba?\(([\d.]+)[ ,]+([\d.]+)[ ,]+([\d.]+)(?:[ ,/]+([\d.]+%?))?/.exec(getComputedStyle(el).backgroundColor);
|
|
368
|
+
if (m && (m[4] === undefined || parseFloat(m[4]) > 0)) return m.slice(1, 4).map(Number);
|
|
369
|
+
}
|
|
370
|
+
return null;
|
|
371
|
+
}
|
|
372
|
+
let repaint = () => {};
|
|
373
|
+
function theme(force) {
|
|
374
|
+
const rgb = background(document.body);
|
|
375
|
+
const lin = (c) => { const s = c / 255; return s <= 0.04045 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4; };
|
|
376
|
+
const now = rgb ? 0.2126 * lin(rgb[0]) + 0.7152 * lin(rgb[1]) + 0.0722 * lin(rgb[2]) < 0.2
|
|
377
|
+
: matchMedia('(prefers-color-scheme: dark)').matches;
|
|
378
|
+
if (now === dark && force !== true) return;
|
|
379
|
+
dark = now;
|
|
380
|
+
document.documentElement.classList.toggle('slop-dark', dark);
|
|
381
|
+
applyColors();
|
|
382
|
+
paintMeters();
|
|
383
|
+
repaint();
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
/* ---------- Slop-o-meter: a switch, a pie of what the page is made of, and what its colors mean ---------- */
|
|
387
|
+
|
|
388
|
+
const store = {
|
|
389
|
+
get: (k) => { try { return localStorage.getItem(k); } catch { return null; } },
|
|
390
|
+
set: (k, v) => { try { localStorage.setItem(k, v); } catch { /* optional */ } },
|
|
391
|
+
drop: (k) => { try { localStorage.removeItem(k); } catch { /* optional */ } },
|
|
392
|
+
};
|
|
393
|
+
// what readers see is the page's choice, "nothing" unless it says otherwise. While the editor is open, its
|
|
394
|
+
// author sees the colors whatever readers get
|
|
395
|
+
const SHOW = ['nothing', 'pie', 'colors'];
|
|
396
|
+
const shows = () => (SHOW.includes(text._show) ? text._show : 'nothing');
|
|
397
|
+
const meters = [];
|
|
398
|
+
let meterOn = false;
|
|
399
|
+
let editing = false;
|
|
400
|
+
function setMeter(on) {
|
|
401
|
+
meterOn = on;
|
|
402
|
+
paintShow();
|
|
403
|
+
}
|
|
404
|
+
function paintShow() {
|
|
405
|
+
const mode = shows();
|
|
406
|
+
document.documentElement.classList.toggle('slop-on', editing || (mode === 'colors' && meterOn));
|
|
407
|
+
meters.forEach((m) => {
|
|
408
|
+
m.el.dataset.show = mode;
|
|
409
|
+
m.btn.setAttribute('aria-pressed', String(meterOn));
|
|
410
|
+
});
|
|
411
|
+
}
|
|
412
|
+
function paintMeters() {
|
|
413
|
+
paintShow();
|
|
414
|
+
if (!meters.length) return;
|
|
415
|
+
const cats = categories();
|
|
416
|
+
const m = makeup(entries().map(([, v]) => v));
|
|
417
|
+
meters.forEach(({ pie, legend }) => {
|
|
418
|
+
pie.style.background = gradient(m, cats);
|
|
419
|
+
pie.title = breakdown(m, cats);
|
|
420
|
+
pie.setAttribute('aria-label', pie.title);
|
|
421
|
+
// each category in its own color, with its share of the page's text
|
|
422
|
+
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('');
|
|
424
|
+
});
|
|
425
|
+
}
|
|
426
|
+
function buildMeter(el) {
|
|
427
|
+
el.classList.add('slop-meter');
|
|
428
|
+
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
|
+
+ '<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') };
|
|
431
|
+
m.btn.addEventListener('click', () => {
|
|
432
|
+
const on = !meterOn;
|
|
433
|
+
setMeter(on);
|
|
434
|
+
store.set('slop-o-meter', on ? 'on' : 'off');
|
|
435
|
+
});
|
|
436
|
+
meters.push(m);
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
/* ---------- the editor ---------- */
|
|
440
|
+
|
|
441
|
+
const human = (key) => {
|
|
442
|
+
const p = /^p(\d+)$/.exec(key);
|
|
443
|
+
if (p) return `Paragraph ${p[1]}`;
|
|
444
|
+
const s = key.replace(/([a-z])([A-Z0-9])/g, '$1 $2').replace(/[_-]/g, ' ').toLowerCase();
|
|
445
|
+
return s.charAt(0).toUpperCase() + s.slice(1);
|
|
446
|
+
};
|
|
447
|
+
// a section is named after its title, if it has a short one, or its key
|
|
448
|
+
const groupTitle = (key) => {
|
|
449
|
+
const node = text[key];
|
|
450
|
+
const title = node && !isText(node) && isText(node.title) ? readable(node.title) : '';
|
|
451
|
+
return title && title.length <= 32 ? title : human(key);
|
|
452
|
+
};
|
|
453
|
+
// where a text is, for people: "Introduction · Paragraph 2"
|
|
454
|
+
const where = (path) => {
|
|
455
|
+
const [g, ...rest] = keysOf(path);
|
|
456
|
+
return [groupTitle(g), ...rest.map(human)].join(' · ');
|
|
457
|
+
};
|
|
458
|
+
const count = (n, one, many = `${one}s`) => `${n.toLocaleString()} ${n === 1 ? one : many}`;
|
|
459
|
+
const isLong = (path, value) => plain(value).length > 48 || /^p\d+$/.test(keysOf(path).at(-1));
|
|
460
|
+
const el = (tag, className, html = '') => Object.assign(document.createElement(tag), { className, innerHTML: html });
|
|
461
|
+
|
|
462
|
+
// the editor opens on repeated text that still has slop, or on any text that does, or on everything
|
|
463
|
+
const slopIn = (path) => (makeup([get(path)]).counts.ai ?? 0) > 0;
|
|
464
|
+
const startTab = () => (repeats(entries()).some((s) => s.paths.some(slopIn)) ? 'repeats' : entries().some(([p]) => slopIn(p)) ? 'slop' : 'all');
|
|
465
|
+
|
|
466
|
+
function editor(mode) {
|
|
467
|
+
const LOCAL = `slop-text:${location.pathname}`;
|
|
468
|
+
// open: the first section, and any the page adds later (pasted text, say)
|
|
469
|
+
// it opens on Repeats, or on Slop left when nothing is repeated
|
|
470
|
+
const state = { tab: startTab(), open: new Set(groupKeys().slice(0, 1)), known: new Set(groupKeys()), focus: null };
|
|
471
|
+
let sets = repeats(entries());
|
|
472
|
+
let controls = []; // [{el, paths}] in the current view, repainted by numbers()
|
|
473
|
+
let undo = null;
|
|
474
|
+
|
|
475
|
+
const btn = el('button', 'slop-edit-btn', 'Edit text');
|
|
476
|
+
btn.type = 'button';
|
|
477
|
+
const aside = el('aside', 'slop-panel', `
|
|
478
|
+
<header class="sp-head" title="Drag to move, or drag an edge to resize. Double-click to put it back">
|
|
479
|
+
<span class="sp-grip" aria-hidden="true"></span>
|
|
480
|
+
<div><h2>Edit text</h2><p class="sp-status" role="status" aria-live="polite"></p></div>
|
|
481
|
+
<button type="button" class="sp-save" title="Save (⌘S)" disabled>Saved</button>
|
|
482
|
+
<button type="button" class="sp-close" aria-label="Close the editor">×</button>
|
|
483
|
+
</header>
|
|
484
|
+
<div class="sp-cover">
|
|
485
|
+
<div class="sp-cover-row"><p class="sp-big"><b></b> slop</p><p class="sp-words"></p></div>
|
|
486
|
+
<div class="sp-cats"></div>
|
|
487
|
+
<div class="sp-show"><span>Readers see</span><div class="sp-seg" role="radiogroup" aria-label="What readers see">
|
|
488
|
+
<button type="button" role="radio" data-show="nothing" title="No sign of the slop editor on the published page">Nothing</button>
|
|
489
|
+
<button type="button" role="radio" data-show="pie" title="A pie of who wrote what, with a legend">Pie chart</button>
|
|
490
|
+
<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>
|
|
491
|
+
</div></div>
|
|
492
|
+
</div>
|
|
493
|
+
<div class="sp-tabs" role="tablist">
|
|
494
|
+
<button type="button" role="tab" data-tab="repeats">Repeats <span></span></button>
|
|
495
|
+
<button type="button" role="tab" data-tab="slop">Slop left <span></span></button>
|
|
496
|
+
<button type="button" role="tab" data-tab="all">All <span></span></button>
|
|
497
|
+
</div>
|
|
498
|
+
<div class="sp-body" role="tabpanel"></div>
|
|
499
|
+
${['n', 's', 'e', 'w', 'ne', 'nw', 'se', 'sw'].map((e) => `<div class="sp-edge" data-edge="${e}" aria-hidden="true"></div>`).join('')}`);
|
|
500
|
+
aside.hidden = true;
|
|
501
|
+
aside.setAttribute('aria-label', 'Edit text');
|
|
502
|
+
document.body.append(btn, aside);
|
|
503
|
+
const $ = (sel) => aside.querySelector(sel);
|
|
504
|
+
const body = $('.sp-body');
|
|
505
|
+
const statusEl = $('.sp-status');
|
|
506
|
+
const pageControl = control(() => entries().map(([p]) => p), 'the whole page');
|
|
507
|
+
$('.sp-cover-row').append(pageControl);
|
|
508
|
+
|
|
509
|
+
function status(msg, kind = '', action) {
|
|
510
|
+
statusEl.textContent = msg;
|
|
511
|
+
statusEl.dataset.kind = kind;
|
|
512
|
+
if (!action) return;
|
|
513
|
+
const b = el('button', 'sp-link', esc(action.label));
|
|
514
|
+
b.type = 'button';
|
|
515
|
+
b.addEventListener('click', action.run);
|
|
516
|
+
statusEl.append(' · ', b);
|
|
517
|
+
}
|
|
518
|
+
const savedStatus = () => (mode === 'local'
|
|
519
|
+
? status('Saved in this browser', '', { label: 'Reset', run: reset })
|
|
520
|
+
: status(`Saved · version ${text.version}`));
|
|
521
|
+
|
|
522
|
+
// any change to who wrote what (the slop switch, marking text, deleting a category) can be undone
|
|
523
|
+
function withUndo(what, change) {
|
|
524
|
+
const before = JSON.stringify(text);
|
|
525
|
+
change();
|
|
526
|
+
if (JSON.stringify(text) === before) return false;
|
|
527
|
+
touched();
|
|
528
|
+
if (state.tab === 'slop') render(); else numbers();
|
|
529
|
+
undo = before;
|
|
530
|
+
status(what, '', {
|
|
531
|
+
label: 'Undo',
|
|
532
|
+
run: () => {
|
|
533
|
+
if (!undo) return;
|
|
534
|
+
const version = text.version;
|
|
535
|
+
text = JSON.parse(undo);
|
|
536
|
+
text.version = version;
|
|
537
|
+
undo = null;
|
|
538
|
+
applyColors();
|
|
539
|
+
touched();
|
|
540
|
+
render();
|
|
541
|
+
},
|
|
542
|
+
});
|
|
543
|
+
return true;
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
/* the slop switch, next to a pie of what the texts are made of */
|
|
547
|
+
function control(paths, what, after) {
|
|
548
|
+
const c = el('span', 'sp-ctl', '<span class="sp-pie" role="img"></span>'
|
|
549
|
+
+ '<button type="button" class="sp-toggle" role="switch"><span class="sp-switch" aria-hidden="true"></span>slop</button>');
|
|
550
|
+
const toggle = c.querySelector('.sp-toggle');
|
|
551
|
+
toggle.addEventListener('click', (e) => {
|
|
552
|
+
e.preventDefault(); // in a section's summary, don't open or close it
|
|
553
|
+
const on = toggle.getAttribute('aria-checked') === 'true';
|
|
554
|
+
const done = withUndo(on ? `Approved ${what}` : `Back to slop: ${what}`, () => paths().forEach((p) => set(p, on ? unslop(get(p)) : reslop(get(p)))));
|
|
555
|
+
if (done) after?.(on);
|
|
556
|
+
});
|
|
557
|
+
controls.push({ el: c, paths });
|
|
558
|
+
return c;
|
|
559
|
+
}
|
|
560
|
+
function paintControl({ el: c, paths }, cats) {
|
|
561
|
+
const m = makeup(paths().map(get));
|
|
562
|
+
const pie = c.querySelector('.sp-pie');
|
|
563
|
+
pie.style.background = gradient(m, cats);
|
|
564
|
+
pie.title = breakdown(m, cats);
|
|
565
|
+
pie.setAttribute('aria-label', pie.title);
|
|
566
|
+
const toggle = c.querySelector('.sp-toggle');
|
|
567
|
+
const on = (m.counts.ai ?? 0) > 0;
|
|
568
|
+
toggle.setAttribute('aria-checked', String(on));
|
|
569
|
+
toggle.disabled = !on && !m.counts.ok;
|
|
570
|
+
toggle.title = on ? 'Slop. Switch it off to approve the AI\'s words as they are'
|
|
571
|
+
: m.counts.ok ? 'Approved. Switch it on to make it slop again' : 'No AI-generated words here';
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
/* categories: a color picker and a name for each, and how much of the page is theirs */
|
|
575
|
+
const own = (id) => { text._categories ??= {}; return (text._categories[id] ??= {}); };
|
|
576
|
+
const slug = (label) => {
|
|
577
|
+
const base = label.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '') || 'category';
|
|
578
|
+
let id = base;
|
|
579
|
+
for (let n = 2; id in BUILTIN || text._categories?.[id] || categories().some((c) => c.id === id); n++) id = `${base}-${n}`;
|
|
580
|
+
return id;
|
|
581
|
+
};
|
|
582
|
+
function renderCats() {
|
|
583
|
+
const box = $('.sp-cats');
|
|
584
|
+
box.innerHTML = '';
|
|
585
|
+
categories().forEach((cat) => {
|
|
586
|
+
const row = el('span', 'sp-cat', `<label class="sp-swatch" title="Pick a color for ${esc(cat.label)}"><input type="color"></label>`
|
|
587
|
+
+ `<input class="sp-cat-name" aria-label="Category name" spellcheck="false"><b class="sp-cat-pct"></b>`
|
|
588
|
+
+ (cat.builtin ? '' : `<button type="button" class="sp-cat-x" title="Delete ${esc(cat.label)}: its words become AI-generated">×</button>`));
|
|
589
|
+
row.dataset.id = cat.id;
|
|
590
|
+
const picker = row.querySelector('input[type="color"]');
|
|
591
|
+
picker.value = hex(swatch(cat));
|
|
592
|
+
row.querySelector('.sp-swatch').style.background = swatch(cat);
|
|
593
|
+
picker.addEventListener('input', () => {
|
|
594
|
+
own(cat.id).color = picker.value;
|
|
595
|
+
row.querySelector('.sp-swatch').style.background = picker.value;
|
|
596
|
+
applyColors();
|
|
597
|
+
touched();
|
|
598
|
+
});
|
|
599
|
+
const name = row.querySelector('.sp-cat-name');
|
|
600
|
+
name.value = cat.label;
|
|
601
|
+
name.size = Math.max(3, cat.label.length);
|
|
602
|
+
name.addEventListener('input', () => {
|
|
603
|
+
name.size = Math.max(3, name.value.length);
|
|
604
|
+
own(cat.id).label = name.value.trim();
|
|
605
|
+
touched();
|
|
606
|
+
});
|
|
607
|
+
name.addEventListener('keydown', (e) => { if (e.key === 'Enter') name.blur(); });
|
|
608
|
+
row.querySelector('.sp-cat-x')?.addEventListener('click', () => {
|
|
609
|
+
withUndo(`Deleted "${cat.label}"`, () => {
|
|
610
|
+
entries().forEach(([p, v]) => set(p, reattribute(v, cat.id, 'ai')));
|
|
611
|
+
delete text._categories?.[cat.id];
|
|
612
|
+
});
|
|
613
|
+
applyColors();
|
|
614
|
+
render();
|
|
615
|
+
});
|
|
616
|
+
box.append(row);
|
|
617
|
+
});
|
|
618
|
+
const add = el('button', 'sp-cat-add', '+ Category');
|
|
619
|
+
add.type = 'button';
|
|
620
|
+
add.title = 'Another author or source: a co-author, an editor, a paper you quote';
|
|
621
|
+
add.addEventListener('click', () => {
|
|
622
|
+
const input = el('input', 'sp-cat-new');
|
|
623
|
+
input.placeholder = 'Name, then Enter';
|
|
624
|
+
add.replaceWith(input);
|
|
625
|
+
input.focus();
|
|
626
|
+
let finished = false;
|
|
627
|
+
const done = (keep) => {
|
|
628
|
+
if (finished) return;
|
|
629
|
+
finished = true;
|
|
630
|
+
const label = input.value.trim();
|
|
631
|
+
if (keep && label) {
|
|
632
|
+
const id = slug(label);
|
|
633
|
+
const color = PALETTE[categories().filter((c) => !c.builtin).length % PALETTE.length];
|
|
634
|
+
Object.assign(own(id), { label, color });
|
|
635
|
+
applyColors();
|
|
636
|
+
touched();
|
|
637
|
+
}
|
|
638
|
+
render();
|
|
639
|
+
};
|
|
640
|
+
input.addEventListener('keydown', (e) => { if (e.key === 'Enter') done(true); if (e.key === 'Escape') done(false); });
|
|
641
|
+
input.addEventListener('blur', () => done(true), { once: true });
|
|
642
|
+
});
|
|
643
|
+
box.append(add);
|
|
644
|
+
}
|
|
645
|
+
|
|
646
|
+
/* marking text: the focused field gets a row of categories. A selection, or the whole text, becomes theirs */
|
|
647
|
+
const assignEl = el('div', 'sp-assign');
|
|
648
|
+
function showAssign(wrap, input, paths) {
|
|
649
|
+
assignEl.innerHTML = '<span class="sp-assign-label"></span>';
|
|
650
|
+
categories().forEach((cat) => {
|
|
651
|
+
const b = el('button', 'sp-as', `<i style="background:${swatch(cat)}"></i>${esc(cat.label)}`);
|
|
652
|
+
b.type = 'button';
|
|
653
|
+
b.addEventListener('pointerdown', (e) => e.preventDefault()); // keep the focus and the selection
|
|
654
|
+
b.addEventListener('click', () => {
|
|
655
|
+
let [s, e] = [input.selectionStart, input.selectionEnd];
|
|
656
|
+
const whole = s === e;
|
|
657
|
+
if (whole) [s, e] = [0, input.value.length];
|
|
658
|
+
withUndo(`Marked ${whole ? 'the text' : 'the selection'} as ${cat.label}`, () => paths.forEach((p) => set(p, assign(get(p), s, e, cat.id))));
|
|
659
|
+
});
|
|
660
|
+
assignEl.append(b);
|
|
661
|
+
});
|
|
662
|
+
assignLabel(input);
|
|
663
|
+
wrap.append(assignEl);
|
|
664
|
+
}
|
|
665
|
+
const assignLabel = (input) => {
|
|
666
|
+
if (assignEl.firstChild) assignEl.firstChild.textContent = input.selectionStart === input.selectionEnd ? 'Mark all as' : 'Mark selection as';
|
|
667
|
+
};
|
|
668
|
+
|
|
669
|
+
/* the views */
|
|
670
|
+
const setOf = (path) => sets.find((s) => s.paths.includes(path));
|
|
671
|
+
const hasSlop = (path) => (makeup([get(path)]).counts.ai ?? 0) > 0;
|
|
672
|
+
const hint = (wrap, message, action) => {
|
|
673
|
+
const h = wrap.querySelector('.sp-hint');
|
|
674
|
+
h.innerHTML = esc(message);
|
|
675
|
+
h.hidden = false;
|
|
676
|
+
h.dataset.at = performance.now();
|
|
677
|
+
if (!action) return;
|
|
678
|
+
const b = el('button', 'sp-link', esc(action.label));
|
|
679
|
+
b.type = 'button';
|
|
680
|
+
b.addEventListener('pointerdown', (e) => e.preventDefault()); // keep the focus in the field
|
|
681
|
+
b.addEventListener('click', () => { h.hidden = true; action.run(); });
|
|
682
|
+
h.append(' ', b);
|
|
683
|
+
};
|
|
684
|
+
let pressed = false;
|
|
685
|
+
addEventListener('pointerdown', () => { pressed = true; }, true);
|
|
686
|
+
addEventListener('pointerup', () => { setTimeout(() => { pressed = false; }); }, true);
|
|
687
|
+
const afterClick = (fn) => {
|
|
688
|
+
if (!pressed) { fn(); return; }
|
|
689
|
+
addEventListener('pointerup', () => setTimeout(fn), { once: true, capture: true });
|
|
690
|
+
};
|
|
691
|
+
|
|
692
|
+
function field(path, { all } = {}) {
|
|
693
|
+
const value = get(path);
|
|
694
|
+
const wrap = el('div', 'sp-field');
|
|
695
|
+
wrap.dataset.path = path;
|
|
696
|
+
const fid = `sp-${path.replace(/\W/g, '-')}${all ? '-all' : ''}`;
|
|
697
|
+
const name = all ? `${all.paths.length} copies` : keysOf(path).slice(1).map(human).join(' · ') || human(path);
|
|
698
|
+
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><p class="sp-hint" hidden></p>`;
|
|
701
|
+
const row = wrap.querySelector('.sp-flabel');
|
|
702
|
+
const input = wrap.querySelector('textarea');
|
|
703
|
+
input.value = plain(value);
|
|
704
|
+
if (!isLong(path, value)) input.addEventListener('keydown', (e) => { if (e.key === 'Enter') e.preventDefault(); });
|
|
705
|
+
const paths = () => (all ? all.paths : [path]);
|
|
706
|
+
// back to how it was at the last save, words and authorship
|
|
707
|
+
const revert = el('button', 'sp-revert', 'Revert');
|
|
708
|
+
revert.type = 'button';
|
|
709
|
+
revert.title = 'Back to how this was at the last save';
|
|
710
|
+
revert.addEventListener('click', () => {
|
|
711
|
+
withUndo(`Reverted "${all ? all.words : where(path)}"`, () => paths().forEach((p) => { if (savedAt(p) !== undefined) set(p, savedAt(p)); }));
|
|
712
|
+
render();
|
|
713
|
+
});
|
|
714
|
+
row.append(revert);
|
|
715
|
+
if (!all) {
|
|
716
|
+
const rep = el('button', 'sp-rep');
|
|
717
|
+
rep.type = 'button';
|
|
718
|
+
rep.addEventListener('click', () => { const s = setOf(path); if (s) show('repeats', s.paths[0]); });
|
|
719
|
+
row.append(rep);
|
|
720
|
+
}
|
|
721
|
+
// a copy's switch changes that copy only, and says so. A Repeats card's switch changes every copy
|
|
722
|
+
row.append(control(paths, all ? count(all.paths.length, 'copy', 'copies') : `"${where(path)}"`, all ? null : (approved) => {
|
|
723
|
+
const others = (setOf(path)?.paths ?? []).filter((p) => p !== path);
|
|
724
|
+
if (!others.length) return;
|
|
725
|
+
const how = approved ? unslop : reslop;
|
|
726
|
+
hint(wrap, `Only this copy changed. ${count(others.length, 'other copy', 'other copies')} didn't.`, {
|
|
727
|
+
label: others.length === 1 ? 'Change it too' : 'Change them too',
|
|
728
|
+
run: () => withUndo(`${approved ? 'Approved' : 'Back to slop:'} ${count(others.length + 1, 'copy', 'copies')}`, () => others.forEach((p) => set(p, how(get(p))))),
|
|
729
|
+
});
|
|
730
|
+
}));
|
|
731
|
+
input.addEventListener('input', (e) => edit(paths(), input, /^history(Undo|Redo)$/.test(e.inputType)));
|
|
732
|
+
['select', 'keyup', 'pointerup'].forEach((t) => input.addEventListener(t, () => assignLabel(input)));
|
|
733
|
+
input.addEventListener('focus', () => { focus(path, all, input, wrap); showAssign(wrap, input, paths()); });
|
|
734
|
+
input.addEventListener('blur', () => {
|
|
735
|
+
mark(false);
|
|
736
|
+
// after the click that moved the focus lands: removing these first would move what's being clicked
|
|
737
|
+
afterClick(() => {
|
|
738
|
+
if (document.activeElement === input) return;
|
|
739
|
+
wrap.querySelector('.sp-hint').hidden = true;
|
|
740
|
+
if (assignEl.parentNode === wrap) assignEl.remove();
|
|
741
|
+
});
|
|
742
|
+
});
|
|
743
|
+
wrap.querySelector('.sp-unseen').addEventListener('click', () => input.focus());
|
|
744
|
+
wrap.input = input;
|
|
745
|
+
wrap.rep = wrap.querySelector('.sp-rep');
|
|
746
|
+
wrap.revert = revert;
|
|
747
|
+
wrap.paths = paths;
|
|
748
|
+
return wrap;
|
|
749
|
+
}
|
|
750
|
+
|
|
751
|
+
function groupView(key, paths) {
|
|
752
|
+
const det = el('details', 'sp-group', `<summary><span class="sp-gname">${esc(groupTitle(key))}</span><span class="sp-gnote"></span></summary>`);
|
|
753
|
+
det.dataset.group = key;
|
|
754
|
+
det.open = state.open.has(key);
|
|
755
|
+
const all = entries(text[key], [key]).map(([p]) => p);
|
|
756
|
+
det.querySelector('summary').append(control(() => all, `"${groupTitle(key)}"`));
|
|
757
|
+
det.addEventListener('toggle', () => {
|
|
758
|
+
if (det.open) { state.open.add(key); det.querySelectorAll('textarea').forEach(grow); } else state.open.delete(key);
|
|
759
|
+
});
|
|
760
|
+
paths.forEach((p) => det.append(field(p)));
|
|
761
|
+
return det;
|
|
762
|
+
}
|
|
763
|
+
|
|
764
|
+
function render() {
|
|
765
|
+
controls = [controls.find((c) => c.el === pageControl)];
|
|
766
|
+
sets = repeats(entries());
|
|
767
|
+
groupKeys().forEach((k) => { if (!state.known.has(k)) { state.known.add(k); state.open.add(k); } });
|
|
768
|
+
renderCats();
|
|
769
|
+
const top = body.scrollTop;
|
|
770
|
+
body.innerHTML = '';
|
|
771
|
+
aside.querySelectorAll('.sp-tabs button').forEach((b) => b.setAttribute('aria-selected', String(b.dataset.tab === state.tab)));
|
|
772
|
+
if (state.tab === 'repeats') {
|
|
773
|
+
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>');
|
|
774
|
+
if (!sets.length) body.insertAdjacentHTML('beforeend', '<p class="sp-empty">No repeated text on this page.</p>');
|
|
775
|
+
sets.forEach((s) => {
|
|
776
|
+
const card = field(s.paths[0], { all: s });
|
|
777
|
+
card.classList.add('sp-set');
|
|
778
|
+
const list = el('ul', 'sp-where');
|
|
779
|
+
s.paths.forEach((p) => {
|
|
780
|
+
const li = document.createElement('li');
|
|
781
|
+
const go = el('button', 'sp-goto', `<span class="sp-pie sp-mini"></span>${esc(where(p))}`);
|
|
782
|
+
go.type = 'button';
|
|
783
|
+
go.dataset.path = p;
|
|
784
|
+
go.addEventListener('click', () => show('all', p));
|
|
785
|
+
go.addEventListener('pointerenter', () => mark(true, [p]));
|
|
786
|
+
go.addEventListener('pointerleave', () => mark(false));
|
|
787
|
+
li.append(go);
|
|
788
|
+
list.append(li);
|
|
789
|
+
});
|
|
790
|
+
card.append(list);
|
|
791
|
+
body.append(card);
|
|
792
|
+
});
|
|
793
|
+
} else {
|
|
794
|
+
const only = state.tab === 'slop';
|
|
795
|
+
let shown = 0;
|
|
796
|
+
groupKeys().forEach((key) => {
|
|
797
|
+
const paths = (isText(text[key]) ? [key] : entries(text[key], [key]).map(([p]) => p)).filter((p) => !only || hasSlop(p));
|
|
798
|
+
if (!paths.length) return;
|
|
799
|
+
shown += paths.length;
|
|
800
|
+
body.append(isText(text[key]) ? field(key) : groupView(key, paths));
|
|
801
|
+
});
|
|
802
|
+
if (only && !shown) body.insertAdjacentHTML('beforeend', '<p class="sp-empty">No slop left. Every word here is yours, approved, or someone else\'s.</p>');
|
|
803
|
+
}
|
|
804
|
+
aside.classList.add('sp-still'); // new switches appear as they are, without sliding there
|
|
805
|
+
numbers();
|
|
806
|
+
body.querySelectorAll('textarea').forEach(grow);
|
|
807
|
+
body.scrollTop = top;
|
|
808
|
+
requestAnimationFrame(() => requestAnimationFrame(() => aside.classList.remove('sp-still')));
|
|
809
|
+
}
|
|
810
|
+
|
|
811
|
+
// every number, pie and switch in the editor, after any change
|
|
812
|
+
function numbers() {
|
|
813
|
+
const cats = categories();
|
|
814
|
+
const all = entries();
|
|
815
|
+
const page = makeup(all.map(([, v]) => v));
|
|
816
|
+
$('.sp-big b').textContent = percent(page.letters ? (page.counts.ai ?? 0) / page.letters : 0);
|
|
817
|
+
$('.sp-words').textContent = count(page.allWords, 'word');
|
|
818
|
+
aside.querySelectorAll('.sp-seg button').forEach((b) => b.setAttribute('aria-checked', String(b.dataset.show === shows())));
|
|
819
|
+
aside.querySelectorAll('.sp-cat').forEach((row) => {
|
|
820
|
+
row.querySelector('.sp-cat-pct').textContent = percent(page.letters ? (page.counts[row.dataset.id] ?? 0) / page.letters : 0);
|
|
821
|
+
});
|
|
822
|
+
controls.forEach((c) => paintControl(c, cats));
|
|
823
|
+
body.querySelectorAll('.sp-goto').forEach((go) => {
|
|
824
|
+
const m = makeup([get(go.dataset.path)]);
|
|
825
|
+
go.querySelector('.sp-pie').style.background = gradient(m, cats);
|
|
826
|
+
go.title = breakdown(m, cats);
|
|
827
|
+
});
|
|
828
|
+
const live = repeats(all);
|
|
829
|
+
const tabs = { all: all.length, slop: all.filter(([p]) => hasSlop(p)).length, repeats: live.length };
|
|
830
|
+
aside.querySelectorAll('.sp-tabs button').forEach((b) => { b.querySelector('span').textContent = tabs[b.dataset.tab]; });
|
|
831
|
+
body.querySelectorAll('.sp-field').forEach((f) => {
|
|
832
|
+
f.revert.hidden = !f.paths().some((p) => differs(p) && savedAt(p) !== undefined);
|
|
833
|
+
const tag = f.querySelector('.sp-unseen');
|
|
834
|
+
const shown = revealed && f.paths().includes(revealed.path);
|
|
835
|
+
tag.hidden = !shown && f.paths().some(onPage);
|
|
836
|
+
tag.disabled = shown || !revealerOf(f.paths()[0]);
|
|
837
|
+
tag.textContent = shown ? 'shown while editing' : tag.disabled ? 'not on the page' : 'not on the page · show it';
|
|
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';
|
|
841
|
+
});
|
|
842
|
+
paintSave();
|
|
843
|
+
body.querySelectorAll('.sp-field:not(.sp-set)').forEach((f) => {
|
|
844
|
+
const s = live.find((r) => r.paths.includes(f.dataset.path));
|
|
845
|
+
f.rep.hidden = !s;
|
|
846
|
+
if (!s) return;
|
|
847
|
+
f.rep.textContent = `${s.paths.length}×`;
|
|
848
|
+
f.rep.title = `Same words in ${count(s.paths.length - 1, 'other place')}: ${s.paths.filter((p) => p !== f.dataset.path).map(where).join(', ')}`;
|
|
849
|
+
});
|
|
850
|
+
body.querySelectorAll('.sp-group').forEach((det) => {
|
|
851
|
+
const paths = entries(text[det.dataset.group], [det.dataset.group]);
|
|
852
|
+
const left = paths.filter(([p]) => hasSlop(p)).length;
|
|
853
|
+
det.querySelector('.sp-gnote').textContent = left ? `${left} of ${paths.length} with slop` : 'no slop';
|
|
854
|
+
});
|
|
855
|
+
paintMeters();
|
|
856
|
+
}
|
|
857
|
+
repaint = () => { if (!aside.hidden) render(); };
|
|
858
|
+
|
|
859
|
+
// the page and the editor point at each other
|
|
860
|
+
function mark(on, paths = state.focus?.paths ?? [], scroll = false) {
|
|
861
|
+
document.querySelectorAll('.slop-focus, .slop-copy').forEach((x) => x.classList.remove('slop-focus', 'slop-copy'));
|
|
862
|
+
if (!on) return;
|
|
863
|
+
paths.forEach((p, i) => elementsOf(p).forEach((x) => x.classList.add(i ? 'slop-copy' : 'slop-focus')));
|
|
864
|
+
const target = paths.map((p) => elementsOf(p)[0]).find(Boolean);
|
|
865
|
+
if (!target || !scroll) return;
|
|
866
|
+
const r = target.getBoundingClientRect();
|
|
867
|
+
const bottom = innerWidth <= 900 ? aside.getBoundingClientRect().top : innerHeight;
|
|
868
|
+
if (r.top < 8 || r.bottom > bottom - 8) scrollBy({ top: r.top - (bottom - r.height) / 2, behavior: 'smooth' });
|
|
869
|
+
}
|
|
870
|
+
function focus(path, all, input, wrap) {
|
|
871
|
+
const s = all ?? setOf(path);
|
|
872
|
+
const paths = all ? all.paths : [path, ...(s ? s.paths.filter((p) => p !== path) : [])];
|
|
873
|
+
state.focus = { path, paths, copies: all || !s ? [] : s.paths.filter((p) => p !== path), was: wordsOf(get(path)), wrap, linked: null };
|
|
874
|
+
if (revealed && !paths.includes(revealed.path)) unreveal();
|
|
875
|
+
if (!paths.some(onPage)) showHidden(paths[0]);
|
|
876
|
+
mark(true, paths, true);
|
|
877
|
+
}
|
|
878
|
+
// a text the page hides: shown while it's being edited, if the page says how
|
|
879
|
+
let revealed = null; // {path, undo}
|
|
880
|
+
function showHidden(path) {
|
|
881
|
+
const fn = revealerOf(path);
|
|
882
|
+
if (!fn || revealed?.path === path) return;
|
|
883
|
+
try { revealed = { path, undo: fn() }; } catch (e) { console.error(e); return; }
|
|
884
|
+
fill();
|
|
885
|
+
numbers();
|
|
886
|
+
}
|
|
887
|
+
function unreveal() {
|
|
888
|
+
if (!revealed) return;
|
|
889
|
+
const { undo: hide } = revealed;
|
|
890
|
+
revealed = null;
|
|
891
|
+
try { hide?.(); } catch (e) { console.error(e); }
|
|
892
|
+
numbers();
|
|
893
|
+
}
|
|
894
|
+
// show one text: in this tab if it's there, otherwise in All
|
|
895
|
+
function show(tab, path) {
|
|
896
|
+
state.tab = tab;
|
|
897
|
+
if (tab !== 'repeats') state.open.add(keysOf(path)[0]);
|
|
898
|
+
render();
|
|
899
|
+
const f = [...body.querySelectorAll('.sp-field')].find((x) => x.dataset.path === path);
|
|
900
|
+
if (!f) return;
|
|
901
|
+
f.scrollIntoView({ block: 'center', behavior: 'smooth' });
|
|
902
|
+
f.input.focus({ preventScroll: true });
|
|
903
|
+
f.classList.add('sp-flash');
|
|
904
|
+
setTimeout(() => f.classList.remove('sp-flash'), 900);
|
|
905
|
+
}
|
|
906
|
+
|
|
907
|
+
const grow = (x) => { x.style.height = 'auto'; x.style.height = `${x.scrollHeight + 2}px`; };
|
|
908
|
+
|
|
909
|
+
// typing: what you type is yours, the rest keeps its author
|
|
910
|
+
// ⌘Z in a text: the words come back with whoever wrote them, from each text's recent versions
|
|
911
|
+
const past = new Map(); // path → [value, …], oldest first
|
|
912
|
+
function remember(p) {
|
|
913
|
+
const list = past.get(p) ?? [];
|
|
914
|
+
const v = get(p);
|
|
915
|
+
if (JSON.stringify(list.at(-1)) !== JSON.stringify(v)) list.push(v);
|
|
916
|
+
past.set(p, list.slice(-200));
|
|
917
|
+
}
|
|
918
|
+
const recall = (p, words) => past.get(p)?.findLast((v) => plain(v) === words);
|
|
919
|
+
function edit(paths, input, restoring) {
|
|
920
|
+
undo = null;
|
|
921
|
+
const f = state.focus;
|
|
922
|
+
[...paths, ...(f?.linked ?? [])].forEach((p) => {
|
|
923
|
+
remember(p);
|
|
924
|
+
set(p, applyEdit(get(p), input.value, restoring ? recall(p, input.value) : undefined));
|
|
925
|
+
remember(p);
|
|
926
|
+
});
|
|
927
|
+
grow(input);
|
|
928
|
+
if (f?.copies.length && !f.linked) {
|
|
929
|
+
// a copy changed on its own: offer to change the others the same way
|
|
930
|
+
const stale = f.copies.filter((p) => wordsOf(get(p)) === f.was);
|
|
931
|
+
if (!stale.length || wordsOf(input.value) === f.was) f.wrap.querySelector('.sp-hint').hidden = true;
|
|
932
|
+
else {
|
|
933
|
+
hint(f.wrap, `Changed here only. ${count(stale.length, 'other copy', 'other copies')} still ${stale.length === 1 ? 'says' : 'say'} the old words.`, {
|
|
934
|
+
label: stale.length === 1 ? 'Change it too' : 'Change them too',
|
|
935
|
+
run: () => { // and keep them in step while this field has the focus
|
|
936
|
+
stale.forEach((p) => set(p, applyEdit(get(p), input.value)));
|
|
937
|
+
f.linked = stale;
|
|
938
|
+
touched();
|
|
939
|
+
},
|
|
940
|
+
});
|
|
941
|
+
}
|
|
942
|
+
}
|
|
943
|
+
touched();
|
|
944
|
+
}
|
|
945
|
+
|
|
946
|
+
// saving: only with the Save button (or ⌘S), one request at a time, each carrying the version it was based on.
|
|
947
|
+
// `saved` is the text as of the last save, for the Save button's count and each text's Revert
|
|
948
|
+
let saved = JSON.parse(JSON.stringify(text));
|
|
949
|
+
let busy = false;
|
|
950
|
+
let stale = false;
|
|
951
|
+
function valueAt(root, p) {
|
|
952
|
+
let node = root;
|
|
953
|
+
for (const key of keysOf(p)) node = node?.[key];
|
|
954
|
+
return isText(node) ? node : undefined;
|
|
955
|
+
}
|
|
956
|
+
const savedAt = (p) => valueAt(saved, p);
|
|
957
|
+
const differs = (p) => JSON.stringify(valueAt(text, p)) !== JSON.stringify(savedAt(p));
|
|
958
|
+
// how many texts changed since the last save (and the categories, as one)
|
|
959
|
+
function unsaved() {
|
|
960
|
+
const paths = new Set([...entries(), ...entries(saved)].map(([p]) => p));
|
|
961
|
+
let n = [...paths].filter(differs).length;
|
|
962
|
+
const metaKeys = new Set([...Object.keys(text), ...Object.keys(saved)].filter((k) => k.startsWith('_')));
|
|
963
|
+
n += [...metaKeys].filter((k) => JSON.stringify(text[k] ?? null) !== JSON.stringify(saved[k] ?? null)).length;
|
|
964
|
+
return n;
|
|
965
|
+
}
|
|
966
|
+
const saveBtn = $('.sp-save');
|
|
967
|
+
function paintSave() {
|
|
968
|
+
const n = unsaved();
|
|
969
|
+
saveBtn.disabled = !n || busy;
|
|
970
|
+
saveBtn.textContent = busy ? 'Saving…' : n ? `Save ${n}` : 'Saved';
|
|
971
|
+
saveBtn.title = n ? `Save ${count(n, 'change')} (⌘S)` : 'Everything is saved';
|
|
972
|
+
}
|
|
973
|
+
async function save() {
|
|
974
|
+
if (busy || !unsaved()) return;
|
|
975
|
+
if (stale) { status('This page is out of date: reload it to save (copy any edits first)', 'error'); return; }
|
|
976
|
+
const body = JSON.stringify(text);
|
|
977
|
+
if (mode === 'local') {
|
|
978
|
+
store.set(LOCAL, JSON.stringify({ base: JSON.parse(original).version, text: JSON.parse(body) }));
|
|
979
|
+
saved = JSON.parse(body);
|
|
980
|
+
undo = null;
|
|
981
|
+
savedStatus();
|
|
982
|
+
numbers();
|
|
983
|
+
return;
|
|
984
|
+
}
|
|
985
|
+
busy = true;
|
|
986
|
+
paintSave();
|
|
987
|
+
try {
|
|
988
|
+
const res = await fetch('/__slop', { method: 'POST', headers: { 'content-type': 'application/json' }, body });
|
|
989
|
+
const out = await res.text();
|
|
990
|
+
if (res.status === 409) { stale = true; throw new Error(out); }
|
|
991
|
+
if (!res.ok) throw new Error(out || res.statusText);
|
|
992
|
+
text.version = Number(out);
|
|
993
|
+
saved = { ...JSON.parse(body), version: text.version };
|
|
994
|
+
undo = null;
|
|
995
|
+
savedStatus();
|
|
996
|
+
} catch (e) {
|
|
997
|
+
status(`Couldn't save: ${e.message}`, 'error');
|
|
998
|
+
} finally {
|
|
999
|
+
busy = false;
|
|
1000
|
+
numbers();
|
|
1001
|
+
}
|
|
1002
|
+
}
|
|
1003
|
+
saveBtn.addEventListener('click', save);
|
|
1004
|
+
function touched() {
|
|
1005
|
+
numbers();
|
|
1006
|
+
changed();
|
|
1007
|
+
if (!stale && !undo) status(unsaved() ? 'Not saved yet' : 'No changes since the last save', unsaved() ? 'dirty' : '');
|
|
1008
|
+
}
|
|
1009
|
+
function reset() {
|
|
1010
|
+
store.drop(LOCAL);
|
|
1011
|
+
text = JSON.parse(original);
|
|
1012
|
+
saved = JSON.parse(original);
|
|
1013
|
+
undo = null;
|
|
1014
|
+
applyColors();
|
|
1015
|
+
changed();
|
|
1016
|
+
render();
|
|
1017
|
+
savedStatus();
|
|
1018
|
+
}
|
|
1019
|
+
addEventListener('beforeunload', (e) => { if (busy || unsaved()) e.preventDefault(); });
|
|
1020
|
+
addEventListener('keydown', (e) => {
|
|
1021
|
+
if ((e.metaKey || e.ctrlKey) && e.key === 's' && !aside.hidden) { e.preventDefault(); save(); }
|
|
1022
|
+
// ⌘Z outside a text undoes the last switch or mark (a text's own ⌘Z undoes its typing)
|
|
1023
|
+
if ((e.metaKey || e.ctrlKey) && !e.shiftKey && e.key === 'z' && undo && !aside.hidden && !e.target.closest?.('textarea, input')) {
|
|
1024
|
+
e.preventDefault();
|
|
1025
|
+
statusEl.querySelector('.sp-link')?.click();
|
|
1026
|
+
}
|
|
1027
|
+
});
|
|
1028
|
+
body.addEventListener('pointerdown', (e) => {
|
|
1029
|
+
if (e.target.closest('.sp-hint')) return;
|
|
1030
|
+
const at = performance.now(); // a hint this click makes stays
|
|
1031
|
+
afterClick(() => body.querySelectorAll('.sp-hint').forEach((h) => { if (!(h.dataset.at > at)) h.hidden = true; }));
|
|
1032
|
+
});
|
|
1033
|
+
|
|
1034
|
+
// while the editor is open, a click on a text opens it in the editor
|
|
1035
|
+
document.addEventListener('click', (e) => {
|
|
1036
|
+
if (aside.hidden || aside.contains(e.target) || btn.contains(e.target)) return;
|
|
1037
|
+
const target = e.target.closest('[data-slop]');
|
|
1038
|
+
if (!target) return;
|
|
1039
|
+
e.preventDefault();
|
|
1040
|
+
e.stopPropagation();
|
|
1041
|
+
const path = target.dataset.slop;
|
|
1042
|
+
const s = setOf(path);
|
|
1043
|
+
if (state.tab === 'repeats' && s) show('repeats', s.paths[0]);
|
|
1044
|
+
else show(state.tab === 'slop' && hasSlop(path) ? 'slop' : 'all', path);
|
|
1045
|
+
}, true);
|
|
1046
|
+
|
|
1047
|
+
/* moving and resizing: drag the header to move the editor, or an edge to resize it. On a narrow screen it's a
|
|
1048
|
+
sheet along the bottom, and dragging changes its height. Double-click the header to put it back */
|
|
1049
|
+
const RECT = 'slop-editor-rect';
|
|
1050
|
+
const MIN = { w: 300, h: 240 };
|
|
1051
|
+
const narrow = () => innerWidth <= 900;
|
|
1052
|
+
const clamp = (v, lo, hi) => Math.min(Math.max(v, lo), Math.max(lo, hi));
|
|
1053
|
+
let rect = {};
|
|
1054
|
+
try { rect = JSON.parse(store.get(RECT)) ?? {}; } catch { /* docked */ }
|
|
1055
|
+
function place() {
|
|
1056
|
+
aside.removeAttribute('style');
|
|
1057
|
+
if (narrow()) {
|
|
1058
|
+
if (rect.sheet) aside.style.height = `${clamp(rect.sheet, 200, innerHeight - 16)}px`;
|
|
1059
|
+
return;
|
|
1060
|
+
}
|
|
1061
|
+
if (!rect.box) return;
|
|
1062
|
+
const w = clamp(rect.box.w, MIN.w, innerWidth - 16);
|
|
1063
|
+
const h = clamp(rect.box.h, MIN.h, innerHeight - 16);
|
|
1064
|
+
Object.assign(aside.style, {
|
|
1065
|
+
left: `${clamp(rect.box.l, 8, innerWidth - w - 8)}px`, top: `${clamp(rect.box.t, 8, innerHeight - h - 8)}px`,
|
|
1066
|
+
width: `${w}px`, height: `${h}px`, right: 'auto', bottom: 'auto',
|
|
1067
|
+
});
|
|
1068
|
+
}
|
|
1069
|
+
function drag(e, edge) {
|
|
1070
|
+
if (e.button !== 0) return;
|
|
1071
|
+
e.preventDefault();
|
|
1072
|
+
const start = aside.getBoundingClientRect();
|
|
1073
|
+
const x0 = e.clientX;
|
|
1074
|
+
const y0 = e.clientY;
|
|
1075
|
+
const target = e.currentTarget;
|
|
1076
|
+
target.setPointerCapture(e.pointerId);
|
|
1077
|
+
document.documentElement.classList.add('slop-dragging');
|
|
1078
|
+
const move = (ev) => {
|
|
1079
|
+
const dx = ev.clientX - x0;
|
|
1080
|
+
const dy = ev.clientY - y0;
|
|
1081
|
+
if (narrow()) { rect.sheet = Math.max(200, start.height - dy); place(); return; }
|
|
1082
|
+
let { left: l, top: t, width: w, height: h } = start;
|
|
1083
|
+
const sides = edge === 'move' ? '' : edge;
|
|
1084
|
+
if (edge === 'move') { l += dx; t += dy; }
|
|
1085
|
+
if (sides.includes('e')) w = Math.max(MIN.w, start.width + dx);
|
|
1086
|
+
if (sides.includes('s')) h = Math.max(MIN.h, start.height + dy);
|
|
1087
|
+
if (sides.includes('w')) { w = Math.max(MIN.w, start.width - dx); l = start.right - w; }
|
|
1088
|
+
if (sides.includes('n')) { h = Math.max(MIN.h, start.height - dy); t = start.bottom - h; }
|
|
1089
|
+
rect.box = { l, t, w, h };
|
|
1090
|
+
place();
|
|
1091
|
+
};
|
|
1092
|
+
const up = () => {
|
|
1093
|
+
target.removeEventListener('pointermove', move);
|
|
1094
|
+
target.removeEventListener('pointerup', up);
|
|
1095
|
+
target.removeEventListener('pointercancel', up);
|
|
1096
|
+
document.documentElement.classList.remove('slop-dragging');
|
|
1097
|
+
store.set(RECT, JSON.stringify(rect));
|
|
1098
|
+
};
|
|
1099
|
+
target.addEventListener('pointermove', move);
|
|
1100
|
+
target.addEventListener('pointerup', up);
|
|
1101
|
+
target.addEventListener('pointercancel', up);
|
|
1102
|
+
}
|
|
1103
|
+
const head = $('.sp-head');
|
|
1104
|
+
head.addEventListener('pointerdown', (e) => { if (!e.target.closest('button')) drag(e, 'move'); });
|
|
1105
|
+
head.addEventListener('dblclick', (e) => {
|
|
1106
|
+
if (e.target.closest('button')) return;
|
|
1107
|
+
rect = {};
|
|
1108
|
+
store.drop(RECT);
|
|
1109
|
+
place();
|
|
1110
|
+
});
|
|
1111
|
+
aside.querySelectorAll('.sp-edge').forEach((x) => x.addEventListener('pointerdown', (e) => drag(e, x.dataset.edge)));
|
|
1112
|
+
addEventListener('resize', () => { if (!aside.hidden) place(); });
|
|
1113
|
+
|
|
1114
|
+
const open = (on) => {
|
|
1115
|
+
aside.hidden = !on;
|
|
1116
|
+
btn.hidden = on;
|
|
1117
|
+
document.documentElement.classList.toggle('slop-editing', on);
|
|
1118
|
+
editing = on;
|
|
1119
|
+
paintShow();
|
|
1120
|
+
if (!on) { mark(false); unreveal(); return; }
|
|
1121
|
+
place();
|
|
1122
|
+
render();
|
|
1123
|
+
};
|
|
1124
|
+
btn.addEventListener('click', () => open(true));
|
|
1125
|
+
$('.sp-close').addEventListener('click', () => open(false));
|
|
1126
|
+
aside.querySelectorAll('.sp-seg button').forEach((b) => b.addEventListener('click', () => {
|
|
1127
|
+
if (b.dataset.show === shows()) return;
|
|
1128
|
+
withUndo(`Readers see: ${b.textContent.toLowerCase()}`, () => {
|
|
1129
|
+
if (b.dataset.show === 'nothing') delete text._show; // the default, so the block needn't say it
|
|
1130
|
+
else text._show = b.dataset.show;
|
|
1131
|
+
});
|
|
1132
|
+
}));
|
|
1133
|
+
aside.querySelectorAll('.sp-tabs button').forEach((b) => b.addEventListener('click', () => { state.tab = b.dataset.tab; render(); }));
|
|
1134
|
+
savedStatus();
|
|
1135
|
+
return { render: () => { if (!aside.hidden) render(); }, touched, open };
|
|
1136
|
+
}
|
|
1137
|
+
|
|
1138
|
+
// after the page changes the text itself (Slop.set, Slop.remove): refill the page, rebuild the editor and save
|
|
1139
|
+
let ed = null;
|
|
1140
|
+
function refresh() {
|
|
1141
|
+
fill();
|
|
1142
|
+
paintMeters();
|
|
1143
|
+
ed?.render();
|
|
1144
|
+
ed?.touched();
|
|
1145
|
+
}
|
|
1146
|
+
function remove(path) {
|
|
1147
|
+
const keys = keysOf(path);
|
|
1148
|
+
let node = text;
|
|
1149
|
+
keys.slice(0, -1).forEach((key) => { node = node?.[key]; });
|
|
1150
|
+
if (node) delete node[keys[keys.length - 1]];
|
|
1151
|
+
}
|
|
1152
|
+
|
|
1153
|
+
// set things up once the page has filled in Slop.vars. Options: code (the class `code` renders with),
|
|
1154
|
+
// edit: 'local' (an editor anyone can use, saving in their browser; under `slop-editor edit` it saves into the file)
|
|
1155
|
+
function start(options = {}) {
|
|
1156
|
+
Object.assign(config, options);
|
|
1157
|
+
fill();
|
|
1158
|
+
document.querySelectorAll('[data-slop-meter]').forEach(buildMeter);
|
|
1159
|
+
theme(true);
|
|
1160
|
+
const watch = new MutationObserver(theme);
|
|
1161
|
+
[document.documentElement, document.body].forEach((x) => watch.observe(x, { attributes: true, attributeFilter: ['class', 'data-theme', 'style'] }));
|
|
1162
|
+
matchMedia('(prefers-color-scheme: dark)').addEventListener('change', theme);
|
|
1163
|
+
setMeter(store.get('slop-o-meter') !== 'off'); // on unless this reader turned it off
|
|
1164
|
+
// the browser editor: what this visitor changed last time, if the page hasn't changed since
|
|
1165
|
+
const local = () => {
|
|
1166
|
+
if (options.edit !== 'local') return;
|
|
1167
|
+
try {
|
|
1168
|
+
const saved = JSON.parse(store.get(`slop-text:${location.pathname}`));
|
|
1169
|
+
if (saved?.base === text.version) { text = saved.text; applyColors(); changed(); }
|
|
1170
|
+
} catch { /* nothing saved */ }
|
|
1171
|
+
ed = editor('local');
|
|
1172
|
+
};
|
|
1173
|
+
// the file editor only on this machine, under `slop-editor edit` (a GET there answers "slop-editor")
|
|
1174
|
+
if (!/^(localhost|127\.0\.0\.1|\[::1\])$/.test(location.hostname)) return local();
|
|
1175
|
+
fetch('/__slop').then((res) => (res.ok ? res.text() : '')).then((s) => { if (s === 'slop-editor') ed = editor('file'); else local(); }).catch(local);
|
|
1176
|
+
}
|
|
1177
|
+
|
|
1178
|
+
return { ...core, get, set, remove, entries, categories, html, words, fill, refresh, onChange, reveal, start, get text() { return text; } };
|
|
1179
|
+
})();
|