slop-editor 0.1.0 → 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/README.md CHANGED
@@ -4,6 +4,8 @@ It tracks who wrote every word on a page: the AI, you, or nobody (facts and quot
4
4
 
5
5
  Every text starts as AI-generated: slop. What you type becomes yours. Switch a text's **slop** off and the AI's words are approved as they are, in a color of their own. Switch it back on to take that back. The point isn't detection. It's owning what you publish.
6
6
 
7
+ It's honest, not proven. The record is the author's own account, like a byline: nothing can tell AI text someone retyped from words they wrote. What the slop editor makes easy is telling the truth about it, and `slop-editor history` shows the account commit by commit.
8
+
7
9
  It's two files (`slop.js` and `slop.css`), has no dependencies and no build step, and works in any HTML page.
8
10
 
9
11
  **[Try it on the demo page](https://baphaelman.github.io/slop-editor/)**, which is itself tracked by the slop editor.
@@ -17,15 +19,17 @@ It's two files (`slop.js` and `slop.css`), has no dependencies and no build step
17
19
  /plugin install slop-editor@slop-editor
18
20
  ```
19
21
 
20
- The agent moves the page's words into the text block for you. That's the tedious part.
22
+ The agent moves the page's words into the text block for you. That's the tedious part. The CLI does the bulk of it too, with `--auto` below.
21
23
 
22
24
  **Without it**, use the command line (Node 18+):
23
25
 
24
26
  ```sh
25
- npx slop-editor install page.html # inline slop.css and slop.js, add the text block
26
- npx slop-editor edit page.html # open the page with the editor; it saves into the file
27
- npx slop-editor check page.html # how much is yours, repeated text, texts the block lacks
28
- npx slop-editor sync page.html # re-inline the current slop.css and slop.js
27
+ npx slop-editor install page.html # inline slop.css and slop.js, add the text block
28
+ npx slop-editor install --auto page.html # the same, and move the page's paragraphs, headings and list items into the block
29
+ npx slop-editor edit page.html # open the page with the editor; it saves into the file
30
+ npx slop-editor check page.html # how much is yours, repeated text, texts the block lacks
31
+ npx slop-editor history page.html # what each git commit did to who wrote what (a page, or a block kept as .json)
32
+ npx slop-editor sync page.html # re-inline the current slop.css and slop.js
29
33
  ```
30
34
 
31
35
  Or link the files instead of inlining them: `<link rel="stylesheet" href="slop.css">` and `<script src="slop.js"></script>`.
@@ -65,12 +69,18 @@ In the page:
65
69
  <p data-slop="intro.p1"></p>
66
70
  <script>
67
71
  Slop.vars.count = 42; // {count} in a text: a fact, shown as data
68
- Slop.onChange(() => relayout()); // after an edit: redo anything built from the text
72
+ Slop.onChange(() => relayout()); // after an edit: redo anything built from the text (returns an unsubscribe)
69
73
  Slop.start();
70
74
  </script>
71
75
  ```
72
76
 
73
- Code can render texts itself with `Slop.html('intro.p1')` (HTML) or `Slop.words('intro.p1')` (plain text).
77
+ Code can render texts itself with `Slop.html('intro.p1')` (HTML) or `Slop.words('intro.p1')` (plain text). Put `data-slop-ref="intro.p1"` on the element that shows them (a button or link the page builds) and the editor can still find, highlight and scroll to it. Unlike `data-slop`, nothing fills it.
78
+
79
+ **Words the page doesn't show as words** (alt text for an image that doesn't load, a tooltip, a label for screen readers, a placeholder) go in attributes: `<img data-slop-attr="alt:hero.photo">`, or several at once, `data-slop-attr="alt:hero.photo title:hero.tip"`. They're filled as plain text. The editor gives them a tab of their own, **Hidden**, since readers' colors can't show them.
80
+
81
+ `[data-slop]` elements and meters the page adds after `Slop.start()` (a single-page app's) are filled and built as they appear. `Slop.meter(el)` builds a meter by hand.
82
+
83
+ For code that draws its own view of who wrote what: `Slop.entries()` lists every `[path, value]`; `Slop.makeup(values)` counts their letters and words by category (`{counts, letters, words, allWords}`); `Slop.categories()` gives each category's `id`, `label` and `color`, in the order the meter shows them; `Slop.percent(fraction)` rounds a share the way the meter does.
74
84
 
75
85
  A text the page shows only some of the time (after a click, in another tab, once something's been pasted) is tagged **not on the page** in the editor. To let the editor show it while it's being edited, tell it how:
76
86
 
@@ -83,11 +93,25 @@ Slop.reveal('intro.note', () => {
83
93
 
84
94
  A group's key (`'intro'`) covers all its texts. While shown, the page's own redraws must keep it shown (here, `render()` checks `showNote`).
85
95
 
96
+ ### In a React app
97
+
98
+ `slop-editor/react` wraps it, with no JSX and no build. slop.js still goes in the page first, as a plain `<script>`.
99
+
100
+ ```jsx
101
+ import Slop, { SlopText, SlopMeter, slopAttrs, useSlop } from 'slop-editor/react';
102
+
103
+ <SlopMeter path="games.othello" /> // a meter (no path: the page's)
104
+ <SlopText path="intro.p1" as="p" /> // a text, redrawn after each edit
105
+ <img src="hero.png" {...slopAttrs({ alt: 'hero.photo' })} />
106
+ ```
107
+
108
+ `useSlop()` makes any component render again after an edit; `SlopText` already does. Call it in a component that uses `slopAttrs` or `Slop.words`.
109
+
86
110
  ## The editor
87
111
 
88
112
  `slop-editor edit page.html` serves the page's folder on 127.0.0.1 and opens the page with an **Edit text** button. Published, the page shows no sign of the editor. `Slop.start({edit: 'local'})` gives every visitor an editor that saves in their browser instead (the demo page uses it).
89
113
 
90
- - **All** shows every text, grouped by section. **Slop left** shows only the texts that aren't all yours yet; work through it until it's empty. **Repeats** shows the repeated text.
114
+ - **All** shows every text, grouped by section. **Slop left** shows only the texts that aren't all yours yet; work through it until it's empty. **Repeats** shows the repeated text. **Hidden** (on pages that have some) shows alt text, tooltips and labels.
91
115
  - Each text, section and the whole page has a pie of what it's made of and a **slop** switch. Off approves the AI's words; on takes that back. Your typed words are never touched. Every switch can be undone from the status line.
92
116
  - At the top: how much of the page is slop, and every category with its share and a color picker. Rename a category by editing its name. **+ Category** adds one; × deletes it (its words become AI-generated).
93
117
  - Focus a text and a row of categories appears under it: **Mark all as** (or **Mark selection as**, with words selected) gives the text, or just the selection, to a category.
@@ -119,6 +143,12 @@ It's the page's choice, made in the editor (**Readers see**) and saved in the bl
119
143
 
120
144
  It shows where the page puts `<div data-slop-meter></div>`. While the editor is open, you see the colors whatever readers get.
121
145
 
146
+ A meter can cover one part of the page: `<div data-slop-meter="games.othello"></div>` measures only the texts under `games.othello`, and its switch colors only its section, the closest `[data-slop-section]` or else its parent. A section's switch starts the way the page's is and is its own once flipped. Only the page's is remembered.
147
+
148
+ Pointing at a category in a legend dims everyone else's words, in the meter's section or the whole page.
149
+
150
+ The colors apply inside `.slop-on` (on `<html>` while the page's switch is on, or a section switched on) and not inside `.slop-off` (a section switched off). Pointing at a category sets `data-slop-only="<id>"` on the section.
151
+
122
152
  ## Rules for agents
123
153
 
124
154
  The full rules are in [skills/slop-editor/SKILL.md](skills/slop-editor/SKILL.md), which the Claude Code plugin loads. In short:
package/cli.mjs CHANGED
@@ -2,15 +2,18 @@
2
2
  // The slop editor's command line. No dependencies.
3
3
  //
4
4
  // slop-editor install <page.html> add the text block and inline slop.css and slop.js into a page (it stays one file)
5
+ // [--auto] also move the page's static prose (paragraphs, headings, list items) into the block
5
6
  // slop-editor sync <page.html …> re-inline the current slop.css and slop.js into pages that have them
6
7
  // slop-editor edit <page.html> serve the page's folder on localhost with the editor, which saves into the file
7
8
  // [--port 5178] [--no-open]
8
9
  // slop-editor check <page.html> what the text is made of, the repeated text, and texts the page uses but the block lacks
10
+ // slop-editor history <page.html> what each git commit did to who wrote what (a page, or a block kept as .json)
9
11
  import http from 'node:http';
10
12
  import net from 'node:net';
11
13
  import { readFile, writeFile, rename, stat } from 'node:fs/promises';
12
- import { spawn } from 'node:child_process';
14
+ import { spawn, execFile } from 'node:child_process';
13
15
  import path from 'node:path';
16
+ import { markup } from './markup.mjs';
14
17
  import { fileURLToPath } from 'node:url';
15
18
 
16
19
  const here = path.dirname(fileURLToPath(import.meta.url));
@@ -22,6 +25,7 @@ const BLOCK = /(<script type="application\/json" id="slop-text">)([\s\S]*?)(<\/s
22
25
  const Slop = new Function(`${await readFile(path.join(here, 'slop.js'), 'utf8')}\nreturn Slop;`)();
23
26
 
24
27
  function readBlock(html, name) {
28
+ if (name.endsWith('.json')) return JSON.parse(html); // a block kept in a file of its own
25
29
  const m = BLOCK.exec(html);
26
30
  if (!m) throw new Error(`${name} has no <script type="application/json" id="slop-text"> block (run install first)`);
27
31
  return JSON.parse(m[2]);
@@ -61,11 +65,36 @@ function install(html) {
61
65
  return `${out}\n${tag}<script>Slop.start();</script>\n`;
62
66
  }
63
67
 
68
+ // --auto: the page's prose goes into the block as AI text, and Slop.start() runs once the marked elements exist
69
+ function auto(html) {
70
+ const found = markup(html);
71
+ const block = readBlock(html, 'the page');
72
+ const { version, ...have } = block;
73
+ const added = [];
74
+ for (const [group, texts] of Object.entries(found.block)) {
75
+ if (group === 'version') continue;
76
+ for (const [key, value] of Object.entries(texts)) {
77
+ if (have[group]?.[key] !== undefined) continue;
78
+ (have[group] ||= {})[key] = value;
79
+ added.push(`${group}.${key}`);
80
+ }
81
+ }
82
+ let out = found.html.replace(BLOCK, (_, a, __, b) => a + serialize({ version, ...have }) + b);
83
+ if (!/Slop\.start\(/.test(out)) {
84
+ const script = /<script id="slop-js">[\s\S]*?<\/script>/.exec(out);
85
+ const end = script.index + script[0].length;
86
+ const direct = out.lastIndexOf('data-slop="') < script.index; // every marked element is above the script
87
+ const call = direct ? '<script>Slop.start();</script>'
88
+ : '<script>document.readyState === \'loading\' ? document.addEventListener(\'DOMContentLoaded\', () => Slop.start()) : Slop.start();</script>';
89
+ out = out.slice(0, end) + '\n' + call + out.slice(end);
90
+ }
91
+ return { html: out, texts: found.texts.length, skipped: found.skipped };
92
+ }
93
+
64
94
  /* ---------- check ---------- */
65
95
 
66
- async function check(file) {
67
- const html = await readFile(file, 'utf8');
68
- const text = readBlock(html, file);
96
+ // every text in a block: [[path, value]]
97
+ function textsOf(text) {
69
98
  const entries = [];
70
99
  const walk = (node, at) => Object.entries(node).forEach(([k, v]) => {
71
100
  if (!at.length && (k === 'version' || k.startsWith('_'))) return; // not text
@@ -73,9 +102,17 @@ async function check(file) {
73
102
  else if (v && typeof v === 'object') walk(v, [...at, k]);
74
103
  });
75
104
  walk(text, []);
105
+ return entries;
106
+ }
107
+ const labelIn = (text) => (id) => text._categories?.[id]?.label || Slop.BUILTIN[id]?.label || id;
108
+
109
+ async function check(file) {
110
+ const html = await readFile(file, 'utf8');
111
+ const text = readBlock(html, file);
112
+ const entries = textsOf(text);
76
113
  const paths = new Set(entries.map(([p]) => p));
77
114
  const m = Slop.makeup(entries.map(([, v]) => v));
78
- const label = (id) => text._categories?.[id]?.label || Slop.BUILTIN[id]?.label || id;
115
+ const label = labelIn(text);
79
116
  console.log(`${path.relative(process.cwd(), file)} (version ${text.version})`);
80
117
  console.log(` ${m.allWords.toLocaleString()} words in ${entries.length} texts`);
81
118
  console.log(` ${Object.entries(m.counts).sort((a, b) => b[1] - a[1]).map(([id, n]) => `${label(id)} ${Slop.percent(n / m.letters)}`).join(' · ')}`);
@@ -83,10 +120,12 @@ async function check(file) {
83
120
  console.log(` ${left.length} ${left.length === 1 ? 'text has' : 'texts have'} slop left`);
84
121
  const sets = Slop.repeats(entries);
85
122
  if (sets.length) console.log(` repeated text:\n${sets.map((r) => ` "${r.words.slice(0, 60)}${r.words.length > 60 ? '…' : ''}": ${r.paths.join(', ')}`).join('\n')}`);
86
- // texts the page asks for: data-slop="…" in a tag, Slop.html('…') and Slop.words('…') in its code. Only a whole
123
+ // texts the page asks for: data-slop="…" (or data-slop-ref, data-slop-attr) in a tag, Slop.html('…') and Slop.words('…') in its code. Only a whole
87
124
  // string counts: Slop.html('caption' + n) builds its path, so its start isn't a text
88
125
  const page = html.replace(SCRIPT, '').replace(STYLE, '').replace(BLOCK, ''); // the page's own markup and code
89
- const used = new Set([...page.matchAll(/<[a-z][^>]*?\bdata-slop="([^"]+)"/gi), ...page.matchAll(/Slop\.(?:html|words|get)\(\s*(['"`])([\w.-]+)\1\s*[,)]/g)].map((m) => m[2] ?? m[1]));
126
+ const used = new Set([...page.matchAll(/<[a-z][^>]*?\bdata-slop(?:-ref)?="([^"]+)"/gi), ...page.matchAll(/Slop\.(?:html|words|get)\(\s*(['"`])([\w.-]+)\1\s*[,)]/g)].map((m) => m[2] ?? m[1]));
127
+ // and data-slop-attr="alt:hero.photo title:hero.tip"
128
+ [...page.matchAll(/<[a-z][^>]*?\bdata-slop-attr="([^"]+)"/gi)].forEach((m) => m[1].split(/\s+/).forEach((pair) => { const at = pair.slice(pair.indexOf(':') + 1); if (pair.includes(':') && at) used.add(at); }));
90
129
  const missing = [...used].filter((p) => !paths.has(p));
91
130
  if (missing.length) console.log(` missing from the block: ${missing.join(', ')}`);
92
131
  return missing.length ? 1 : 0;
@@ -193,16 +232,59 @@ async function edit(file, { port, fixed, open }) {
193
232
  await next();
194
233
  }
195
234
 
235
+ /* ---------- history ---------- */
236
+
237
+ // what each commit did to who wrote what, from git's copies of the file: letters gained or lost by each category, and
238
+ // the share of slop after it. It's the author's own account, commit by commit, not proof of who wrote what
239
+ async function history(file) {
240
+ const git = (...a) => new Promise((resolve, reject) => execFile('git', a, { cwd: path.dirname(file), maxBuffer: 1 << 28 }, (e, out) => (e ? reject(e) : resolve(out))));
241
+ const name = `./${path.basename(file)}`;
242
+ let log;
243
+ try {
244
+ log = await git('log', '--reverse', '--format=%h%x09%ad%x09%s', '--date=short', '--', name);
245
+ } catch {
246
+ throw new Error(`${file} isn't in a git repository`);
247
+ }
248
+ const versions = log.split('\n').filter(Boolean).map((line) => { const [sha, date, subject] = line.split('\t'); return { sha, date, subject }; });
249
+ versions.push({ sha: null, date: 'now', subject: '(not committed)' });
250
+ console.log(path.relative(process.cwd(), file));
251
+ let before = null;
252
+ let shown = 0;
253
+ for (const v of versions) {
254
+ let text;
255
+ try {
256
+ text = readBlock(v.sha ? await git('show', `${v.sha}:${name}`) : await readFile(file, 'utf8'), file);
257
+ } catch { continue; } // no block in that version yet
258
+ const entries = textsOf(text);
259
+ const key = JSON.stringify(entries);
260
+ if (before?.key === key) continue; // the commit didn't change the text
261
+ const m = Slop.makeup(entries.map(([, val]) => val));
262
+ const label = labelIn(text);
263
+ // in the editor's order: mine, approved, the page's own, data, slop
264
+ const rank = (id) => ({ me: 0, ok: 1, data: 3, ai: 4 })[id] ?? 2;
265
+ const ids = [...new Set([...Object.keys(before?.m.counts ?? {}), ...Object.keys(m.counts)])].sort((a, b) => rank(a) - rank(b));
266
+ const change = ids.map((id) => [id, (m.counts[id] ?? 0) - (before?.m.counts[id] ?? 0)]).filter(([, n]) => n)
267
+ .map(([id, n]) => `${label(id)} ${n > 0 ? '+' : '−'}${Math.abs(n).toLocaleString()}`).join(' · ');
268
+ const slop = Slop.percent(m.letters ? (m.counts.ai ?? 0) / m.letters : 0);
269
+ console.log(` ${v.date.padEnd(10)} ${(v.sha ?? '').padEnd(9)} slop ${slop.padStart(4)} ${change || 'only moved or reworded'} ${v.subject}`);
270
+ before = { key, m };
271
+ shown++;
272
+ }
273
+ if (!shown) console.log(' no versions with a text block');
274
+ else console.log('\nLetters gained or lost by each category, per commit. It\'s what the author recorded, not proof of who wrote what.');
275
+ }
276
+
196
277
  /* ---------- main ---------- */
197
278
 
198
279
  const args = process.argv.slice(2);
199
280
  const flag = (name) => { const i = args.indexOf(name); return i >= 0 ? args.splice(i, 2)[1] : null; };
200
281
  const portFlag = flag('--port') ?? process.env.PORT;
201
282
  const port = Number(portFlag ?? 5178);
283
+ const autoFlag = args.includes('--auto') && args.splice(args.indexOf('--auto'), 1);
202
284
  const noOpen = args.includes('--no-open') && args.splice(args.indexOf('--no-open'), 1);
203
285
  const [cmd, ...rest] = args;
204
286
  const files = rest.map((f) => path.resolve(f));
205
- const usage = 'usage: slop-editor install <page.html> | sync <page.html …> | edit <page.html> [--port N] [--no-open] | check <page.html …>';
287
+ const usage = 'usage: slop-editor install <page.html> [--auto] | sync <page.html …> | edit <page.html> [--port N] [--no-open] | check <page.html …> | history <page.html>';
206
288
 
207
289
  if (cmd !== 'help' && cmd && !files.length) {
208
290
  console.error(usage);
@@ -211,10 +293,21 @@ if (cmd !== 'help' && cmd && !files.length) {
211
293
  try {
212
294
  if (cmd === 'install') {
213
295
  for (const file of files) {
214
- await writeFile(file, install(await readFile(file, 'utf8')));
296
+ let html = install(await readFile(file, 'utf8'));
297
+ if (autoFlag) {
298
+ const done = auto(html);
299
+ html = done.html;
300
+ console.log(`${path.relative(process.cwd(), file)}: moved ${done.texts} texts into the block`
301
+ + (done.skipped ? `; ${done.skipped} more have markup it can't carry (spans, line breaks, icons): do those by hand` : ''));
302
+ }
303
+ await writeFile(file, html);
215
304
  await sync(file);
216
305
  }
217
- console.log('\nNext: mark text elements with data-slop="group.key" and put their words in the slop-text block\n'
306
+ if (autoFlag) {
307
+ console.log('\nStatic prose is done. Still yours to check: text the page\'s code builds (Slop.html / Slop.words), text shown only\n'
308
+ + 'sometimes (Slop.reveal), and anything that reads an element\'s text before Slop.start() or after an edit (Slop.onChange).\n'
309
+ + 'Then: slop-editor check <page.html>, and slop-editor edit <page.html>');
310
+ } else console.log('\nNext: mark text elements with data-slop="group.key" and put their words in the slop-text block\n'
218
311
  + '(as AI text to start). Add <div data-slop-meter></div> at the top (readers see\n'
219
312
  + 'nothing there unless you pick a pie chart or colors in the editor). Call Slop.start() once Slop.vars is\n'
220
313
  + 'set and before anything reads the text. Then: slop-editor edit <page.html>');
@@ -226,6 +319,8 @@ try {
226
319
  let status = 0;
227
320
  for (const file of files) status |= await check(file);
228
321
  process.exitCode = status;
322
+ } else if (cmd === 'history') {
323
+ for (const file of files) await history(file);
229
324
  } else {
230
325
  console.log(usage);
231
326
  }
package/markup.mjs ADDED
@@ -0,0 +1,93 @@
1
+ // `slop-editor install --auto`: move a page's static prose into the slop text block, as AI text.
2
+ // It takes paragraphs, headings, list items, captions and quotes whose content is plain words with links, bold,
3
+ // italic and code, and leaves everything else (labels, buttons, spans, text with other markup, text the code builds)
4
+ // to whoever ported the page. Returns the new html and what it did.
5
+
6
+ const PROSE = 'p|h[1-6]|li|dd|dt|figcaption|blockquote';
7
+ const SKIP = 'script|style|svg|textarea|pre|select|button|template|noscript|head|code|kbd|nav|label|form|iframe|canvas|math';
8
+ const BLOCKS = /<(?:p|ul|ol|li|div|h[1-6]|section|article|aside|table|blockquote|details|figure|dl|dd|dt|header|footer|main|br|img|span|svg|input|button|select|textarea)\b/i;
9
+ // elements that hold other prose: look inside them instead of taking them whole
10
+ const CONTAINERS = /<(?:p|ul|ol|li|div|section|article|aside|table|blockquote|details|figure|dl|dd|dt|header|footer|main|h[1-6])\b/i;
11
+ const ENTITIES = { nbsp: ' ', amp: '&', lt: '<', gt: '>', quot: '"', apos: "'", ndash: '–', mdash: '—', hellip: '…', lsquo: '‘', rsquo: '’', ldquo: '“', rdquo: '”' };
12
+ const MIN_WORDS = 3;
13
+
14
+ const decode = (s) => s.replace(/&(?:#(\d+)|#x([0-9a-f]+)|(\w+));/gi, (all, d, x, n) =>
15
+ d ? String.fromCodePoint(+d) : x ? String.fromCodePoint(parseInt(x, 16)) : (ENTITIES[n] ?? all));
16
+ const escape = (s) => s.replace(/([\\*\[\]{}`])/g, '\\$1');
17
+
18
+ // inner HTML -> the format's inline markup, or null if it holds anything the format can't say
19
+ function convert(inner) {
20
+ if (BLOCKS.test(inner) || /\{\{|\$\{|<%|<\?/.test(inner)) return null;
21
+ let out = '', open = [], last = 0, bad = false;
22
+ const re = /<(\/?)(a|b|strong|i|em|code)\b([^>]*)>|<[^>]*>/gi;
23
+ const text = (s) => { out += escape(decode(s)); };
24
+ for (let m; (m = re.exec(inner)); last = re.lastIndex) {
25
+ text(inner.slice(last, m.index));
26
+ if (!m[2]) { bad = true; break; }
27
+ const tag = m[2].toLowerCase();
28
+ if (m[1]) {
29
+ const top = open.pop();
30
+ if (top?.tag !== tag) { bad = true; break; }
31
+ out += top.close;
32
+ continue;
33
+ }
34
+ if (tag === 'a') {
35
+ const href = /\bhref="([^"]*)"/i.exec(m[3])?.[1];
36
+ if (!href || /[()\s]/.test(href)) { bad = true; break; }
37
+ open.push({ tag, close: `](${decode(href)})` });
38
+ out += '[';
39
+ } else {
40
+ const mark = tag === 'b' || tag === 'strong' ? '**' : tag === 'code' ? '`' : '*';
41
+ open.push({ tag, close: mark });
42
+ out += mark;
43
+ }
44
+ }
45
+ if (bad || open.length) return null;
46
+ text(inner.slice(last));
47
+ return out.replace(/\s+/g, ' ').trim();
48
+ }
49
+
50
+ const words = (s) => s.replace(/\[([^\]]*)\]\([^)]*\)/g, '$1').replace(/[*`\\]/g, '').split(/\s+/).filter((w) => /\w/.test(w)).length;
51
+ const slug = (s) => s.toLowerCase().replace(/<[^>]*>/g, '').replace(/&\w+;/g, ' ').match(/[a-z0-9]+/g)?.slice(0, 2).join('-') || '';
52
+
53
+ export function markup(html) {
54
+ const body = /<body\b[^>]*>/i.exec(html);
55
+ const from = body ? body.index + body[0].length : 0;
56
+ const re = new RegExp(`<(${SKIP})\\b[\\s\\S]*?</\\1\\s*>|<!--[\\s\\S]*?-->|<(${PROSE})\\b([^>]*)>([\\s\\S]*?)</\\2\\s*>`, 'gi');
57
+ const text = {};
58
+ const used = new Set();
59
+ let group = 'intro', n = 0, out = html.slice(0, from), last = from, skipped = 0;
60
+ re.lastIndex = from;
61
+ for (let m; (m = re.exec(html));) {
62
+ const [all, skip, tag, attrs, inner] = m;
63
+ if (skip || !tag) continue;
64
+ const t = tag.toLowerCase();
65
+ const heading = /^h[1-6]$/.test(t);
66
+ if (!heading && CONTAINERS.test(inner)) { re.lastIndex = m.index + all.indexOf('>') + 1; continue; } // a container: look inside it
67
+ if (/\bdata-slop\b/.test(attrs)) continue;
68
+ const converted = convert(inner);
69
+ if (converted === null) { if (decode(inner).replace(/<[^>]*>/g, '').trim()) skipped++; continue; }
70
+ if (!/\w/.test(converted) || (!heading && words(converted) < MIN_WORDS)) continue;
71
+ let key;
72
+ if (heading) {
73
+ let g = slug(inner) || 'text', i = 2;
74
+ while (used.has(g)) g = `${slug(inner) || 'text'}-${i++}`;
75
+ used.add(group = g);
76
+ n = 0;
77
+ key = `${group}.title`;
78
+ } else {
79
+ used.add(group);
80
+ key = `${group}.${t}${++n}`;
81
+ }
82
+ text[key] = converted;
83
+ out += html.slice(last, m.index) + `<${tag}${attrs} data-slop="${key}"></${tag}>`;
84
+ last = m.index + all.length;
85
+ }
86
+ out += html.slice(last);
87
+ const block = { version: 1 };
88
+ for (const [k, v] of Object.entries(text)) {
89
+ const dot = k.indexOf('.');
90
+ (block[k.slice(0, dot)] ||= {})[k.slice(dot + 1)] = v;
91
+ }
92
+ return { html: out, block, texts: Object.keys(text), skipped };
93
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "slop-editor",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "A slop editor: track who wrote every word on a page (the AI, you, or nobody), then read the slop and make it yours.",
5
5
  "homepage": "https://baphaelman.github.io/slop-editor/",
6
6
  "repository": {
@@ -12,8 +12,16 @@
12
12
  "bin": {
13
13
  "slop-editor": "cli.mjs"
14
14
  },
15
+ "exports": {
16
+ "./slop.js": "./slop.js",
17
+ "./slop.css": "./slop.css",
18
+ "./react": "./react.mjs",
19
+ "./package.json": "./package.json"
20
+ },
15
21
  "files": [
16
22
  "cli.mjs",
23
+ "markup.mjs",
24
+ "react.mjs",
17
25
  "slop.js",
18
26
  "slop.css",
19
27
  "README.md",
@@ -35,6 +43,14 @@
35
43
  ],
36
44
  "author": "Raphael Bajet",
37
45
  "license": "MIT",
46
+ "peerDependencies": {
47
+ "react": ">=18"
48
+ },
49
+ "peerDependenciesMeta": {
50
+ "react": {
51
+ "optional": true
52
+ }
53
+ },
38
54
  "devDependencies": {
39
55
  "playwright-core": "^1.65.1"
40
56
  }
package/react.mjs ADDED
@@ -0,0 +1,47 @@
1
+ // The slop editor in a React app: `import { SlopText, SlopMeter, slopAttrs, useSlop } from 'slop-editor/react'`.
2
+ // slop.js has to be in the page first, as a plain <script>: this hands its global Slop to the modules. No JSX and no
3
+ // build, so it works from node_modules as it is. MIT license.
4
+ import { createElement, useSyncExternalStore } from 'react';
5
+
6
+ /* global Slop */
7
+ // slop.js declares Slop with const: a global name, but not a property of window
8
+ const slop = typeof Slop === 'undefined' ? null : Slop;
9
+ if (!slop) throw new Error('slop-editor/react: put slop.js in the page before this module');
10
+ export default slop;
11
+
12
+ // after an edit in the editor, every component that called useSlop() renders again
13
+ let version = 0;
14
+ const subscribers = new Set();
15
+ slop.onChange(() => {
16
+ version++;
17
+ subscribers.forEach((fn) => fn());
18
+ });
19
+ const subscribe = (fn) => {
20
+ subscribers.add(fn);
21
+ return () => subscribers.delete(fn);
22
+ };
23
+ const snapshot = () => version;
24
+ export const useSlop = () => useSyncExternalStore(subscribe, snapshot, snapshot);
25
+
26
+ // a text as HTML, in a span (or `as`). React draws it; data-slop-ref lets the editor find it on the page. `vars` fill
27
+ // in {name}s for this one text
28
+ export function SlopText({ path, as = 'span', vars, ...props }) {
29
+ useSlop();
30
+ return createElement(as, { ...props, 'data-slop-ref': path, dangerouslySetInnerHTML: { __html: slop.html(path, vars) } });
31
+ }
32
+
33
+ // attributes from texts, as plain text: <img {...slopAttrs({ alt: 'hero.photo' })} />. The editor lists them under
34
+ // Hidden. Call it from a component that calls useSlop(), so they follow edits
35
+ export function slopAttrs(attrs, vars) {
36
+ const pairs = Object.entries(attrs);
37
+ const out = Object.fromEntries(pairs.map(([name, path]) => [name, slop.words(path, vars)]));
38
+ out['data-slop-attr'] = pairs.map(([name, path]) => `${name}:${path}`).join(' ');
39
+ if (vars) out['data-slop-vars'] = JSON.stringify(vars);
40
+ return out;
41
+ }
42
+
43
+ // a Slop-o-meter: the page's, or with a path, a group's, whose switch colors only its section (the closest
44
+ // [data-slop-section], or its parent). slop.js builds what's inside
45
+ export function SlopMeter({ path, className, ...props }) {
46
+ return createElement('div', { ...props, className: className ? `slop-meter ${className}` : 'slop-meter', 'data-slop-meter': path ?? '' });
47
+ }
package/slop.css CHANGED
@@ -39,7 +39,8 @@ html.slop-dark {
39
39
  .slop-pct { margin-left: 5px; font-weight: 700; font-variant-numeric: tabular-nums; }
40
40
  .slop-pie { flex: none; width: 18px; height: 18px; border-radius: 50%; background: color-mix(in srgb, currentColor 20%, transparent); box-shadow: inset 0 0 0 1px color-mix(in srgb, currentColor 15%, transparent); }
41
41
  .slop-legend { display: inline-flex; flex-wrap: wrap; gap: 2px 10px; font-weight: 600; }
42
- .slop-key { display: inline-flex; align-items: center; gap: 5px; }
42
+ .slop-key { display: inline-flex; align-items: center; gap: 5px; border-radius: 4px; cursor: default; }
43
+ .slop-key:focus-visible { outline: 2px solid var(--_accent); outline-offset: 2px; }
43
44
  .slop-key i { width: 8px; height: 8px; border-radius: 50%; }
44
45
 
45
46
  /* ---------- the editor ---------- */
@@ -120,6 +121,7 @@ html.slop-dark {
120
121
  /* tabs */
121
122
  .sp-tabs { display: flex; gap: 2px; margin: 0 12px; padding: 3px; border-radius: 10px; background: var(--_sunk); }
122
123
  .sp-tabs button { flex: 1; padding: 6px 8px; border: 0; border-radius: 7px; background: none; color: var(--_ink-2); font-size: 0.82rem; font-weight: 600; cursor: pointer; white-space: nowrap; }
124
+ .sp-tabs button[hidden] { display: none; }
123
125
  .sp-tabs button span { margin-left: 3px; font-weight: 500; color: var(--_ink-3); font-variant-numeric: tabular-nums; }
124
126
  .sp-tabs button[aria-selected="true"] { background: var(--_bg); color: var(--_ink); box-shadow: 0 1px 2px rgb(0 0 0 / 0.12); }
125
127
  .sp-tabs button:hover:not([aria-selected="true"]) { color: var(--_ink); }
@@ -150,6 +152,8 @@ html.slop-dark {
150
152
  }
151
153
  .sp-field textarea:hover { border-color: var(--_rule); }
152
154
  .sp-field textarea:focus { outline: none; border-color: var(--_accent); background: var(--_bg); box-shadow: 0 0 0 3px color-mix(in srgb, var(--_accent) 18%, transparent); }
155
+ .sp-kind { flex: none; padding: 1px 6px; border-radius: 4px; background: color-mix(in srgb, var(--_accent) 12%, transparent); font: 600 0.68rem var(--_font); color: var(--_accent); }
156
+ .sp-kind[hidden] { display: none; }
153
157
  .sp-unseen { flex: none; padding: 1px 6px; border: 0; border-radius: 4px; background: var(--_sunk); font: 600 0.68rem var(--_font); color: var(--_ink-3) !important; cursor: help; }
154
158
  .sp-unseen:not(:disabled) { color: var(--_accent) !important; cursor: pointer; }
155
159
  .sp-unseen:not(:disabled):hover { background: color-mix(in srgb, var(--_accent) 12%, transparent); }
package/slop.js CHANGED
@@ -266,7 +266,25 @@ const Slop = (() => {
266
266
  });
267
267
  }
268
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))}"]`);
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
+ }
270
288
 
271
289
  // texts the page's code has rendered (Slop.html, Slop.words): with the [data-slop] elements, what's on the page
272
290
  const rendered = new Set();
@@ -279,16 +297,34 @@ const Slop = (() => {
279
297
  const reveal = (path, fn) => { revealers.set(dotted(path), fn); };
280
298
  const revealerOf = (path) => revealers.get(dotted(path)) ?? revealers.get(keysOf(path)[0]);
281
299
  // 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;
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) {
285
304
  const h = render(get(el.dataset.slop), local);
286
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);
287
310
  });
288
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
+ }
289
321
 
290
322
  const listeners = [];
291
- const onChange = (fn) => listeners.push(fn);
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
+ };
292
328
  let pending = false;
293
329
  function changed() { // after an edit: refill the page, then let the page redo whatever it built from the text
294
330
  if (pending) return;
@@ -337,14 +373,18 @@ const Slop = (() => {
337
373
  }
338
374
  const swatch = (cat) => cat.color ?? ink();
339
375
 
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
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
342
380
  let sheet = null;
343
381
  function applyColors() {
344
382
  sheet ??= document.head.appendChild(Object.assign(document.createElement('style'), { id: 'slop-colors' }));
345
- const cats = categories().filter((c) => c.color);
383
+ const all = categories();
384
+ const cats = all.filter((c) => c.color);
346
385
  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');
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')}`;
348
388
  }
349
389
 
350
390
  // a pie of what these texts are made of, and the same in words for its tooltip
@@ -395,45 +435,80 @@ const Slop = (() => {
395
435
  const SHOW = ['nothing', 'pie', 'colors'];
396
436
  const shows = () => (SHOW.includes(text._show) ? text._show : 'nothing');
397
437
  const meters = [];
438
+ const built = new WeakMap(); // element → its meter
398
439
  let meterOn = false;
399
440
  let editing = false;
400
441
  function setMeter(on) {
401
442
  meterOn = on;
402
443
  paintShow();
403
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);
404
449
  function paintShow() {
405
450
  const mode = shows();
406
451
  document.documentElement.classList.toggle('slop-on', editing || (mode === 'colors' && meterOn));
407
452
  meters.forEach((m) => {
408
453
  m.el.dataset.show = mode;
409
- m.btn.setAttribute('aria-pressed', String(meterOn));
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));
410
464
  });
411
465
  }
412
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));
413
469
  paintShow();
414
470
  if (!meters.length) return;
415
471
  const cats = categories();
416
- const m = makeup(entries().map(([, v]) => v));
417
- meters.forEach(({ pie, legend }) => {
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);
418
477
  pie.style.background = gradient(m, cats);
419
478
  pie.title = breakdown(m, cats);
420
479
  pie.setAttribute('aria-label', pie.title);
421
- // each category in its own color, with its share of the page's text
480
+ // each category in its own color, with its share of the text
422
481
  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('');
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('');
424
483
  });
425
484
  }
426
485
  function buildMeter(el) {
427
486
  el.classList.add('slop-meter');
428
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>'
429
488
  + '<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') };
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') };
431
490
  m.btn.addEventListener('click', () => {
432
- const on = !meterOn;
491
+ const on = !(m.own ?? meterOn);
492
+ if (m.at) { m.own = on; paintShow(); return; } // only the page-wide choice is remembered
433
493
  setMeter(on);
434
494
  store.set('slop-o-meter', on ? 'on' : 'off');
435
495
  });
436
- meters.push(m);
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();
437
512
  }
438
513
 
439
514
  /* ---------- the editor ---------- */
@@ -459,6 +534,9 @@ const Slop = (() => {
459
534
  const isLong = (path, value) => plain(value).length > 48 || /^p\d+$/.test(keysOf(path).at(-1));
460
535
  const el = (tag, className, html = '') => Object.assign(document.createElement(tag), { className, innerHTML: html });
461
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
+
462
540
  // the editor opens on repeated text that still has slop, or on any text that does, or on everything
463
541
  const slopIn = (path) => (makeup([get(path)]).counts.ai ?? 0) > 0;
464
542
  const startTab = () => (repeats(entries()).some((s) => s.paths.some(slopIn)) ? 'repeats' : entries().some(([p]) => slopIn(p)) ? 'slop' : 'all');
@@ -494,6 +572,7 @@ const Slop = (() => {
494
572
  <button type="button" role="tab" data-tab="repeats">Repeats <span></span></button>
495
573
  <button type="button" role="tab" data-tab="slop">Slop left <span></span></button>
496
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>
497
576
  </div>
498
577
  <div class="sp-body" role="tabpanel"></div>
499
578
  ${['n', 's', 'e', 'w', 'ne', 'nw', 'se', 'sw'].map((e) => `<div class="sp-edge" data-edge="${e}" aria-hidden="true"></div>`).join('')}`);
@@ -696,7 +775,7 @@ const Slop = (() => {
696
775
  const fid = `sp-${path.replace(/\W/g, '-')}${all ? '-all' : ''}`;
697
776
  const name = all ? `${all.paths.length} copies` : keysOf(path).slice(1).map(human).join(' · ') || human(path);
698
777
  wrap.innerHTML = `<div class="sp-flabel"><label for="${fid}">${esc(name)}</label>`
699
- + '<button type="button" class="sp-unseen" hidden></button></div>'
778
+ + '<span class="sp-kind" hidden></span><button type="button" class="sp-unseen" hidden></button></div>'
700
779
  + `<textarea id="${fid}" rows="1" spellcheck="true"></textarea><p class="sp-hint" hidden></p>`;
701
780
  const row = wrap.querySelector('.sp-flabel');
702
781
  const input = wrap.querySelector('textarea');
@@ -743,6 +822,7 @@ const Slop = (() => {
743
822
  wrap.querySelector('.sp-unseen').addEventListener('click', () => input.focus());
744
823
  wrap.input = input;
745
824
  wrap.rep = wrap.querySelector('.sp-rep');
825
+ wrap.kind = wrap.querySelector('.sp-kind');
746
826
  wrap.revert = revert;
747
827
  wrap.paths = paths;
748
828
  return wrap;
@@ -751,7 +831,7 @@ const Slop = (() => {
751
831
  function groupView(key, paths) {
752
832
  const det = el('details', 'sp-group', `<summary><span class="sp-gname">${esc(groupTitle(key))}</span><span class="sp-gnote"></span></summary>`);
753
833
  det.dataset.group = key;
754
- det.open = state.open.has(key);
834
+ det.open = state.open.has(key) || state.tab === 'hidden'; // there are few, so all of them show
755
835
  const all = entries(text[key], [key]).map(([p]) => p);
756
836
  det.querySelector('summary').append(control(() => all, `"${groupTitle(key)}"`));
757
837
  det.addEventListener('toggle', () => {
@@ -791,15 +871,18 @@ const Slop = (() => {
791
871
  body.append(card);
792
872
  });
793
873
  } else {
794
- const only = state.tab === 'slop';
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>');
795
877
  let shown = 0;
796
878
  groupKeys().forEach((key) => {
797
- const paths = (isText(text[key]) ? [key] : entries(text[key], [key]).map(([p]) => p)).filter((p) => !only || hasSlop(p));
879
+ const paths = (isText(text[key]) ? [key] : entries(text[key], [key]).map(([p]) => p)).filter(keep);
798
880
  if (!paths.length) return;
799
881
  shown += paths.length;
800
882
  body.append(isText(text[key]) ? field(key) : groupView(key, paths));
801
883
  });
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>');
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>');
803
886
  }
804
887
  aside.classList.add('sp-still'); // new switches appear as they are, without sliding there
805
888
  numbers();
@@ -826,8 +909,12 @@ const Slop = (() => {
826
909
  go.title = breakdown(m, cats);
827
910
  });
828
911
  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]; });
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
+ });
831
918
  body.querySelectorAll('.sp-field').forEach((f) => {
832
919
  f.revert.hidden = !f.paths().some((p) => differs(p) && savedAt(p) !== undefined);
833
920
  const tag = f.querySelector('.sp-unseen');
@@ -838,6 +925,10 @@ const Slop = (() => {
838
925
  tag.title = shown ? 'The page normally hides this. It\'s shown while you edit it'
839
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'
840
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` : '';
841
932
  });
842
933
  paintSave();
843
934
  body.querySelectorAll('.sp-field:not(.sp-set)').forEach((f) => {
@@ -857,15 +948,32 @@ const Slop = (() => {
857
948
  repaint = () => { if (!aside.hidden) render(); };
858
949
 
859
950
  // the page and the editor point at each other
860
- function mark(on, paths = state.focus?.paths ?? [], scroll = false) {
951
+ function mark(on, paths = state.focus?.paths ?? [], scroll = false, tries = 0) {
861
952
  document.querySelectorAll('.slop-focus, .slop-copy').forEach((x) => x.classList.remove('slop-focus', 'slop-copy'));
862
953
  if (!on) return;
863
954
  paths.forEach((p, i) => elementsOf(p).forEach((x) => x.classList.add(i ? 'slop-copy' : 'slop-focus')));
864
955
  const target = paths.map((p) => elementsOf(p)[0]).find(Boolean);
865
- if (!target || !scroll) return;
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);
866
965
  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' });
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;
869
977
  }
870
978
  function focus(path, all, input, wrap) {
871
979
  const s = all ?? setOf(path);
@@ -1034,11 +1142,12 @@ const Slop = (() => {
1034
1142
  // while the editor is open, a click on a text opens it in the editor
1035
1143
  document.addEventListener('click', (e) => {
1036
1144
  if (aside.hidden || aside.contains(e.target) || btn.contains(e.target)) return;
1037
- const target = e.target.closest('[data-slop]');
1145
+ const target = e.target.closest('[data-slop], [data-slop-ref], [data-slop-attr]');
1038
1146
  if (!target) return;
1039
1147
  e.preventDefault();
1040
1148
  e.stopPropagation();
1041
- const path = target.dataset.slop;
1149
+ const path = target.dataset.slop || target.dataset.slopRef || attrsOf(target)[0]?.[1];
1150
+ if (!path) return;
1042
1151
  const s = setOf(path);
1043
1152
  if (state.tab === 'repeats' && s) show('repeats', s.paths[0]);
1044
1153
  else show(state.tab === 'slop' && hasSlop(path) ? 'slop' : 'all', path);
@@ -1155,7 +1264,8 @@ const Slop = (() => {
1155
1264
  function start(options = {}) {
1156
1265
  Object.assign(config, options);
1157
1266
  fill();
1158
- document.querySelectorAll('[data-slop-meter]').forEach(buildMeter);
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 });
1159
1269
  theme(true);
1160
1270
  const watch = new MutationObserver(theme);
1161
1271
  [document.documentElement, document.body].forEach((x) => watch.observe(x, { attributes: true, attributeFilter: ['class', 'data-theme', 'style'] }));
@@ -1175,5 +1285,5 @@ const Slop = (() => {
1175
1285
  fetch('/__slop').then((res) => (res.ok ? res.text() : '')).then((s) => { if (s === 'slop-editor') ed = editor('file'); else local(); }).catch(local);
1176
1286
  }
1177
1287
 
1178
- return { ...core, get, set, remove, entries, categories, html, words, fill, refresh, onChange, reveal, start, get text() { return text; } };
1288
+ return { ...core, get, set, remove, entries, categories, html, words, fill, refresh, onChange, reveal, meter, start, get text() { return text; } };
1179
1289
  })();