slop-editor 0.3.0 → 0.4.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.
Files changed (5) hide show
  1. package/README.md +19 -8
  2. package/cli.mjs +68 -4
  3. package/package.json +1 -1
  4. package/slop.css +48 -2
  5. package/slop.js +583 -59
package/README.md CHANGED
@@ -26,13 +26,14 @@ The agent moves the page's words into the text block for you. That's the tedious
26
26
  ```sh
27
27
  npx slop-editor install page.html # inline slop.css and slop.js, add the text block
28
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
29
+ npx slop-editor edit page.html # open the page with the editor; it saves into the file (and re-inlines the current code)
30
30
  npx slop-editor check page.html # how much is yours, repeated text, texts the block lacks
31
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
32
  npx slop-editor sync page.html # re-inline the current slop.css and slop.js
33
+ npx slop-editor pending # categories you asked an agent to find, in the pages under this folder
33
34
  ```
34
35
 
35
- Or link the files instead of inlining them: `<link rel="stylesheet" href="slop.css">` and `<script src="slop.js"></script>`.
36
+ Or link the files instead of inlining them: `<link rel="stylesheet" href="slop.css">` and `<script src="slop.js"></script>`. A site that installs `slop-editor` from npm can serve `node_modules/slop-editor/slop.js` and `slop.css` itself, so `npm update slop-editor` updates every page. Under `slop-editor edit`, a page that links a `slop.js` or `slop.css` its folder doesn't have gets the CLI's own.
36
37
 
37
38
  ## The text block
38
39
 
@@ -59,7 +60,15 @@ A **text** is a plain string (AI) or a list mixing strings (AI), `{"me": "..."}`
59
60
  }
60
61
  ```
61
62
 
62
- Slop is only ever the AI's words. Other categories are other people's. Inline markup: `[label](url)`, `**bold**`, `*italic*`, `` `code` ``, `[[key]]` for a key cap, `{name}` for a value the page fills in, and `\` to escape.
63
+ Slop is only ever the AI's words. Other categories are other people's.
64
+
65
+ **Categories an agent finds.** A category can say whose words it means (`"about"`), and ask an agent to find them in the page's existing text (`"find": true`). In the editor, a new category asks **Whose words are …?**, with **Ask an agent to find them**; select any category to edit its description. Built-ins have one too, and an agent can be asked to find facts and quotes (`data`), never your words or what you approved. The next agent that works on the project is told at the start of its session (with the Claude Code plugin; `npx slop-editor pending` lists them too, and **Copy a prompt** hands one to any agent now). It marks the words (never changing them), records what it changed in `"found": {"on": "2026-11-25", "before": {"<path>": <old value>}}`, and removes `"find"`. The editor then shows **An agent marked 12 texts as Bob · Keep · Undo**. An agent never puts a category on its own words: only on words that came from that person or source (a quote, a paste, a dictation), as `about` describes.
66
+
67
+ ```json
68
+ "bob": { "label": "Bob", "about": "My co-author: the methods section, and quotes from his thesis", "find": true }
69
+ ```
70
+
71
+ Inline markup: `[label](url)`, `**bold**`, `*italic*`, `` `code` `` (a fact: shown and counted as data, whoever wrote it), `[[key]]` for a key cap, `{name}` for a value the page fills in, and `\` to escape.
63
72
 
64
73
  **Paragraphs.** A blank line in a text shown in a `<p>`, `<li>` or `<dd>` starts a paragraph of its own: the element shows the first, and a copy of it after it shows each of the others (`data-slop-more` instead of `data-slop`). Markup doesn't carry across a blank line. Anywhere else a line break is a `<br>`. An element whose text is empty is hidden (`.slop-empty`), except while the editor is open.
65
74
 
@@ -78,15 +87,17 @@ In the page:
78
87
 
79
88
  Code can render texts itself with `Slop.html('intro.p1')` (HTML), `Slop.paragraphs('intro.p1')` (HTML, one string per paragraph) 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.
80
89
 
81
- **Lists.** Where the page shows a group as a list of paragraphs, say so, and the editor can add and remove texts there:
90
+ **Lists.** Where the page shows a group's paragraphs (`p1`, `p2`, …) in one element, the editor can add and remove paragraphs there. That's found without marking when two or more of them are `data-slop` elements with the same parent, the same tag and the same other attributes (so `<p data-b="0">`, `<p data-b="1">` scroll steps aren't a list). Put `data-slop-list="off"` on the parent to opt out. Or say so:
82
91
 
83
92
  ```html
84
- <div data-slop-list="intro"> <!-- a copy of the first child for each text in "intro", in order -->
93
+ <div data-slop-list="intro"> <!-- a copy of the first paragraph for each p<n> in "intro", in order -->
94
+ <h2 data-slop="intro.title"></h2> <!-- the group's other texts and other children stay where they are -->
85
95
  <p data-slop="intro.p1"></p>
96
+ <p data-slop="intro.p2"></p>
86
97
  </div>
87
98
  ```
88
99
 
89
- The list's children are its texts and nothing else. A page that draws them itself (React and the like) puts `data-slop-list-ref="intro"` on the element around them instead, draws one per key of the group, in order, and redraws after an edit.
100
+ All of the group's paragraphs have to be in that element; the ones the page has no element for are drawn after the others. A new one goes after the paragraph before it. A page that draws them itself (React and the like) puts `data-slop-list-ref="intro"` on the element around them instead, draws one per paragraph key, in order, and redraws after an edit.
90
101
 
91
102
  **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.
92
103
 
@@ -124,12 +135,12 @@ import Slop, { SlopText, SlopMeter, slopAttrs, slopList, useSlop } from 'slop-ed
124
135
 
125
136
  ## The editor
126
137
 
127
- `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).
138
+ `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). When the page's author publishes a new version, a visitor's saved edits carry over: the author's changes win, text by text, and the visitor's stay everywhere else. They're kept under the page's path; on a host that gives each version an address of its own, name the page instead: `Slop.start({edit: 'local', key: 'my-page'})`.
128
139
 
129
140
  - **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.
130
141
  - Each text box shows its words in their authors' colors, as readers see them with the Slop-o-meter on.
131
142
  - Each text, section and the whole page has a pie of what it's made of, by its name, and a **slop** switch at the right. 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.
132
- - 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).
143
+ - At the top: how much of the page is slop, and every category with its share, the biggest first (as in the meters' legends). Click a category's dot for its color picker, laid out like the browser's (a rectangle of shades; the eyedropper, the color and a hue bar; RGB, HEX or HSL numbers). Its eyedropper, or dragging the dot onto any color on the page, takes a color from the page: the point is a ring, and a magnifier beside it (not over it, so you can see where you are) shows the page around the point three times bigger, rimmed in the color, joined to the ring by a line (Escape drops it). **Revert colors** puts every category back to its default. Rename a category by editing its name. **+ Category** adds one; × deletes it (its words become AI-generated).
133
144
  - 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.
134
145
  - In a list, a **+** under the text you're on adds an empty paragraph after it; pointing at the + draws a line on the page where it would go. The trash can before its slop switch outlines the text on the page in dashed red; a text with words takes a second click (it asks **Remove?**), and stays red until then. A removed text stays in **All** as a row with **Restore** until the next save. New texts get new keys (`p7` between `p2` and `p3` is still called Paragraph 3 in the editor), so a key never moves to other words.
135
146
  - Click any text on the page to jump to it in the editor. Focus a text in the editor to find it on the page.
package/cli.mjs CHANGED
@@ -5,12 +5,15 @@
5
5
  // [--auto] also move the page's static prose (paragraphs, headings, list items) into the block
6
6
  // slop-editor sync <page.html …> re-inline the current slop.css and slop.js into pages that have them
7
7
  // slop-editor edit <page.html> serve the page's folder on localhost with the editor, which saves into the file
8
+ // (it re-inlines the current code first, and serves slop.js/slop.css to a page that links them)
8
9
  // [--port 5178] [--no-open]
9
10
  // slop-editor check <page.html> what the text is made of, the repeated text, and texts the page uses but the block lacks
10
11
  // slop-editor history <page.html> what each git commit did to who wrote what (a page, or a block kept as .json)
12
+ // slop-editor pending [dir|page …] categories the user asked an agent to find (all pages under the folder by default)
13
+ // [--hook] as a Claude Code SessionStart hook's context, and nothing when there are none
11
14
  import http from 'node:http';
12
15
  import net from 'node:net';
13
- import { readFile, writeFile, rename, stat } from 'node:fs/promises';
16
+ import { readFile, writeFile, rename, stat, readdir } from 'node:fs/promises';
14
17
  import { spawn, execFile } from 'node:child_process';
15
18
  import path from 'node:path';
16
19
  import { markup } from './markup.mjs';
@@ -128,9 +131,51 @@ async function check(file) {
128
131
  [...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); }));
129
132
  const missing = [...used].filter((p) => !paths.has(p));
130
133
  if (missing.length) console.log(` missing from the block: ${missing.join(', ')}`);
134
+ const asked = waiting(text);
135
+ if (asked.length) console.log(` waiting for an agent to find: ${asked.map((c) => c.label).join(', ')}`);
131
136
  return missing.length ? 1 : 0;
132
137
  }
133
138
 
139
+ /* ---------- categories to find ---------- */
140
+
141
+ // a category of the page's own can ask an agent to find its words: {"about": "whose words they are", "find": true}
142
+ const waiting = (text) => Object.entries(text?._categories ?? {}).filter(([, c]) => c?.find).map(([id, c]) => ({ id, label: c.label || id, about: c.about ?? '' }));
143
+ const SKIP = new Set(['node_modules', 'dist', 'build', 'out', 'coverage', 'vendor']);
144
+ async function pagesIn(dir, found = [], depth = 0) {
145
+ if (depth > 8 || found.length > 5000) return found;
146
+ for (const d of await readdir(dir, { withFileTypes: true })) {
147
+ if (d.name.startsWith('.') || SKIP.has(d.name)) continue;
148
+ const p = path.join(dir, d.name);
149
+ if (d.isDirectory()) await pagesIn(p, found, depth + 1);
150
+ else if (/\.(html?|json)$/i.test(d.name)) found.push(p);
151
+ }
152
+ return found;
153
+ }
154
+ async function pending(targets, hook) {
155
+ const files = [];
156
+ for (const t of targets) files.push(...((await stat(t)).isDirectory() ? await pagesIn(t) : [t]));
157
+ const asked = [];
158
+ for (const file of files) {
159
+ try {
160
+ if ((await stat(file)).size > 5e6) continue;
161
+ const s = await readFile(file, 'utf8');
162
+ if (!s.includes('"find"')) continue;
163
+ const text = readBlock(s, file);
164
+ if (typeof text?.version !== 'number') continue;
165
+ waiting(text).forEach((c) => asked.push({ file: path.relative(process.cwd(), file) || file, ...c }));
166
+ } catch { /* not a page with a block */ }
167
+ }
168
+ const lines = asked.map((c) => `- ${c.file}: "${c.label}" (id \`${c.id}\`)${c.about ? `: ${c.about}` : ''}`);
169
+ if (hook) {
170
+ if (!asked.length) return;
171
+ const context = `The slop editor: the user asked an agent to find the words of these categories (in each page's slop-text block, under \`_categories\`):\n${lines.join('\n')}\n`
172
+ + 'Do it in this session, before you finish, unless the user says not to. Follow the slop-editor skill ("Categories to find"), and tell the user what you marked.';
173
+ console.log(JSON.stringify({ hookSpecificOutput: { hookEventName: 'SessionStart', additionalContext: context } }));
174
+ return;
175
+ }
176
+ console.log(asked.length ? `Waiting for an agent to find:\n${lines.join('\n')}` : 'No categories are waiting for an agent.');
177
+ }
178
+
134
179
  /* ---------- edit ---------- */
135
180
 
136
181
  const TYPES = {
@@ -145,7 +190,12 @@ const TYPES = {
145
190
  async function edit(file, { port, fixed, open }) {
146
191
  const root = path.dirname(file);
147
192
  const name = path.basename(file);
148
- readBlock(await readFile(file, 'utf8'), name); // fail now, not on the first save
193
+ const html = await readFile(file, 'utf8');
194
+ readBlock(html, name); // fail now, not on the first save
195
+ // a page that inlines the code gets this version's, so a page on its own stays current
196
+ if (!name.endsWith('.json') && STYLE.test(html) && SCRIPT.test(html)) await sync(file);
197
+ const asked = waiting(readBlock(html, name));
198
+ if (asked.length) console.log(`Waiting for an agent to find: ${asked.map((c) => c.label).join(', ')}`);
149
199
  let queue = Promise.resolve(); // one save at a time
150
200
  const save = (body) => {
151
201
  const run = queue.then(async () => {
@@ -172,6 +222,10 @@ async function edit(file, { port, fixed, open }) {
172
222
  res.end(body);
173
223
  };
174
224
  if (url.pathname === '/__slop') {
225
+ // only the page being edited: another page in its folder would save its own block into this file
226
+ let from = '/';
227
+ try { from = decodeURIComponent(new URL(req.headers.referer).pathname); } catch { /* no referer: curl, say */ }
228
+ if (from !== '/' && from !== `/${name}`) return req.method === 'POST' ? send(403, `this server edits ${name}`) : send(200, 'another page');
175
229
  if (req.method !== 'POST') return send(200, 'slop-editor');
176
230
  let body = '';
177
231
  req.on('data', (chunk) => { body += chunk; });
@@ -193,6 +247,9 @@ async function edit(file, { port, fixed, open }) {
193
247
  if (!(await stat(target)).isFile()) return send(404, 'not found');
194
248
  send(200, await readFile(target), TYPES[path.extname(target).toLowerCase()] ?? 'application/octet-stream');
195
249
  } catch {
250
+ // a page that links slop.js and slop.css from elsewhere (a site's build serves them) gets this version's
251
+ const own = path.basename(url.pathname);
252
+ if (own === 'slop.js' || own === 'slop.css') return send(200, await readFile(path.join(here, own)), TYPES[path.extname(own)]);
196
253
  send(404, 'not found');
197
254
  }
198
255
  });
@@ -282,11 +339,12 @@ const portFlag = flag('--port') ?? process.env.PORT;
282
339
  const port = Number(portFlag ?? 5178);
283
340
  const autoFlag = args.includes('--auto') && args.splice(args.indexOf('--auto'), 1);
284
341
  const noOpen = args.includes('--no-open') && args.splice(args.indexOf('--no-open'), 1);
342
+ const hookFlag = args.includes('--hook') && args.splice(args.indexOf('--hook'), 1);
285
343
  const [cmd, ...rest] = args;
286
344
  const files = rest.map((f) => path.resolve(f));
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>';
345
+ 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> | pending [dir|page …] [--hook]';
288
346
 
289
- if (cmd !== 'help' && cmd && !files.length) {
347
+ if (cmd !== 'help' && cmd !== 'pending' && cmd && !files.length) {
290
348
  console.error(usage);
291
349
  process.exit(1);
292
350
  }
@@ -321,6 +379,12 @@ try {
321
379
  process.exitCode = status;
322
380
  } else if (cmd === 'history') {
323
381
  for (const file of files) await history(file);
382
+ } else if (cmd === 'pending') {
383
+ try {
384
+ await pending(files.length ? files : [process.cwd()], hookFlag);
385
+ } catch (e) {
386
+ if (!hookFlag) throw e; // a session's start never fails on this
387
+ }
324
388
  } else {
325
389
  console.log(usage);
326
390
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "slop-editor",
3
- "version": "0.3.0",
3
+ "version": "0.4.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": {
package/slop.css CHANGED
@@ -100,9 +100,28 @@ html.slop-dark {
100
100
  .sp-cover-row .sp-pie { width: 22px; height: 22px; }
101
101
  .sp-cats { display: flex; flex-wrap: wrap; gap: 6px; }
102
102
  .sp-cat { display: inline-flex; align-items: center; gap: 6px; height: 28px; padding: 0 9px 0 4px; border: 1px solid var(--_rule); border-radius: 99px; font-size: 0.78rem; }
103
- .sp-swatch { position: relative; flex: none; width: 18px; height: 18px; border-radius: 50%; overflow: hidden; cursor: pointer; box-shadow: inset 0 0 0 1px color-mix(in srgb, var(--_ink) 18%, transparent); }
103
+ .sp-cat { cursor: pointer; }
104
+ .sp-cat-on { border-color: var(--_accent); box-shadow: 0 0 0 1px var(--_accent); }
105
+ .sp-swatch { flex: none; width: 18px; height: 18px; padding: 0; border: 0; border-radius: 50%; cursor: pointer; touch-action: none; box-shadow: inset 0 0 0 1px color-mix(in srgb, var(--_ink) 18%, transparent); }
104
106
  .sp-swatch:hover { box-shadow: 0 0 0 2px var(--_rule), inset 0 0 0 1px color-mix(in srgb, var(--_ink) 18%, transparent); }
105
- .sp-swatch input { position: absolute; inset: -4px; width: calc(100% + 8px); height: calc(100% + 8px); padding: 0; border: 0; opacity: 0; cursor: pointer; }
107
+ /* the color picker, under a category's dot, laid out like the browser's own */
108
+ .sp-pick { position: absolute; z-index: 3; width: 240px; display: grid; gap: 12px; padding: 0 0 12px; overflow: hidden; border: 1px solid var(--_rule); border-radius: 10px; background: var(--_bg); box-shadow: var(--_shadow); }
109
+ .sp-pick-sv { position: relative; height: 150px; touch-action: none; }
110
+ .sp-pick-sv:focus-visible { outline: 2px solid var(--_accent); outline-offset: -2px; }
111
+ .sp-pick-sv i { position: absolute; width: 12px; height: 12px; margin: -6px 0 0 -6px; border: 2px solid #fff; border-radius: 50%; box-shadow: 0 0 0 1px rgb(0 0 0 / 0.35); pointer-events: none; }
112
+ .sp-pick-row { display: flex; align-items: center; gap: 10px; padding: 0 12px; }
113
+ .sp-pick-drop { flex: none; display: grid; place-items: center; width: 26px; height: 26px; padding: 0; border: 0; border-radius: 6px; background: none; color: var(--_ink-2) !important; cursor: pointer; }
114
+ .sp-pick-drop:hover { background: var(--_sunk); color: var(--_ink) !important; }
115
+ .sp-pick-now { flex: none; width: 24px; height: 24px; border-radius: 50%; box-shadow: inset 0 0 0 1px color-mix(in srgb, var(--_ink) 18%, transparent); }
116
+ .sp-pick-hue { flex: 1; min-width: 0; -webkit-appearance: none; appearance: none; height: 10px; margin: 0; border-radius: 99px; background: linear-gradient(to right, #f00, #ff0, #0f0, #0ff, #00f, #f0f, #f00); cursor: pointer; }
117
+ .sp-pick-hue::-webkit-slider-thumb { -webkit-appearance: none; width: 16px; height: 16px; border: 2px solid #fff; border-radius: 50%; background: var(--hue, #f00); box-shadow: 0 0 0 1px rgb(0 0 0 / 0.35); }
118
+ .sp-pick-hue::-moz-range-thumb { width: 12px; height: 12px; border: 2px solid #fff; border-radius: 50%; background: var(--hue, #f00); box-shadow: 0 0 0 1px rgb(0 0 0 / 0.35); }
119
+ .sp-pick-nums { display: flex; align-items: flex-start; gap: 6px; padding: 0 12px; }
120
+ .sp-pick-num { flex: 1; min-width: 0; display: grid; gap: 4px; text-align: center; font-size: 0.68rem; color: var(--_ink-3); }
121
+ .sp-pick-num input { width: 100%; height: 26px; padding: 0 4px; border: 1px solid var(--_rule); border-radius: 5px; background: var(--_bg); text-align: center; font: 0.8rem var(--_font); color: var(--_ink); font-variant-numeric: tabular-nums; }
122
+ .sp-pick-num input:focus { outline: none; border-color: var(--_accent); }
123
+ .sp-pick-swap { flex: none; display: grid; place-items: center; width: 22px; height: 26px; padding: 0; border: 0; border-radius: 5px; background: none; color: var(--_ink-3) !important; cursor: pointer; }
124
+ .sp-pick-swap:hover { background: var(--_sunk); color: var(--_ink) !important; }
106
125
  .sp-cat-name { min-width: 3ch; padding: 0; border: 0; border-radius: 4px; background: none; font: 600 0.78rem var(--_font); color: var(--_ink); }
107
126
  .sp-cat-name:hover { background: var(--_sunk); }
108
127
  .sp-cat-name:focus { outline: none; background: var(--_sunk); }
@@ -116,6 +135,18 @@ html.slop-dark {
116
135
  .sp-seg button:hover:not([aria-checked="true"]) { color: var(--_ink); }
117
136
  .sp-cat-add, .sp-cat-new { height: 28px; padding: 0 11px; border: 1px dashed var(--_rule); border-radius: 99px; background: none; font: 600 0.78rem var(--_font); color: var(--_ink-2); cursor: pointer; }
118
137
  .sp-cat-add:hover { border-color: var(--_ink-3); color: var(--_ink); }
138
+ .sp-cat-revert { height: 28px; padding: 0 4px; border: 0; background: none; font: 600 0.78rem var(--_font); color: var(--_ink-3) !important; cursor: pointer; }
139
+ .sp-cat-revert:hover { color: var(--_ink) !important; }
140
+ /* whose words a category means, and asking an agent to find them */
141
+ .sp-about { flex: 1 1 100%; display: grid; gap: 6px; padding: 10px; border: 1px solid var(--_rule); border-radius: 10px; }
142
+ .sp-about-q { font-size: 0.76rem; font-weight: 600; color: var(--_ink-2); }
143
+ .sp-about textarea { width: 100%; resize: vertical; padding: 6px 8px; border: 1px solid var(--_rule); border-radius: 8px; background: var(--_sunk); font: 0.82rem/1.4 var(--_font); color: var(--_ink); }
144
+ .sp-about textarea:focus { outline: none; border-color: var(--_accent); background: var(--_bg); }
145
+ .sp-about-row { display: flex; align-items: center; justify-content: space-between; gap: 8px; }
146
+ .sp-check { display: inline-flex; align-items: center; gap: 6px; font-size: 0.78rem; color: var(--_ink-2); cursor: pointer; }
147
+ .sp-check input { margin: 0; accent-color: var(--_accent); }
148
+ .sp-about-note, .sp-found { font-size: 0.76rem; color: var(--_ink-3); }
149
+ .sp-found { flex: 1 1 100%; padding: 6px 9px; border-radius: 8px; background: color-mix(in srgb, var(--_accent) 8%, transparent); color: var(--_ink-2); }
119
150
  .sp-cat-new { width: 150px; border-style: solid; border-color: var(--_accent); color: var(--_ink); cursor: text; outline: none; }
120
151
 
121
152
  /* tabs */
@@ -231,6 +262,21 @@ html.slop-dark {
231
262
  .sp-goto:hover { border-color: var(--_ink-3); color: var(--_ink) !important; }
232
263
  .sp-pie.sp-mini { width: 10px; height: 10px; }
233
264
 
265
+ /* taking a color from the page: a ring at the point, and a magnifier beside it (a copy of the page, scaled up around
266
+ the point) joined to it by a line, with the color as its rim */
267
+ .slop-sampling, .slop-sampling * { cursor: crosshair !important; }
268
+ .slop-sampler, .slop-sampler * { pointer-events: none !important; }
269
+ .slop-sampler { position: fixed; inset: 0; z-index: 2147483647; font: 600 11px/1 var(--_mono); }
270
+ .slop-sampler svg { position: absolute; inset: 0; width: 100%; height: 100%; overflow: visible; }
271
+ .slop-sampler line { stroke: #fff; stroke-width: 3; filter: drop-shadow(0 0 1px rgb(0 0 0 / 0.6)); }
272
+ .slop-sampler-ring, .slop-sampler-lens, .slop-sampler-hex { position: absolute; transform: translate(-50%, -50%); }
273
+ .slop-sampler-ring { width: 12px; height: 12px; border: 2px solid #fff; border-radius: 50%; box-shadow: 0 0 0 1px rgb(0 0 0 / 0.5); }
274
+ .slop-sampler-lens { box-sizing: content-box; overflow: hidden; border: 6px solid #fff; border-radius: 50%; box-shadow: 0 0 0 1px rgb(0 0 0 / 0.3), 0 6px 18px rgb(0 0 0 / 0.35); }
275
+ .slop-sampler-page { position: absolute; left: 0; top: 0; transform-origin: 0 0; transform: scale(1); }
276
+ .slop-sampler-dot { position: absolute; left: 50%; top: 50%; width: 6px; height: 6px; margin: -3px 0 0 -3px; outline: 1px solid #fff; box-shadow: 0 0 0 2px rgb(0 0 0 / 0.6); }
277
+ .slop-sampler-hex { padding: 3px 5px; border-radius: 4px; background: #1e1b24; color: #fff; white-space: nowrap; }
278
+ .slop-sampler-hex:empty { display: none; }
279
+
234
280
  /* a text with no words isn't on the page, except while the editor is open */
235
281
  html:not(.slop-editing) .slop-empty { display: none !important; }
236
282
  .slop-editing .slop-empty { min-height: 1em; min-height: 1lh; outline: 1px dashed color-mix(in srgb, var(--_accent) 40%, transparent); outline-offset: 3px; }
package/slop.js CHANGED
@@ -8,14 +8,15 @@
8
8
  Top-level keys that start with "_" aren't text: "_categories" holds the page's own categories and colors,
9
9
  {"<id>": {"label": "...", "color": "#rrggbb"}}, for built-in ones too, and "_show" what readers see: "nothing" (the
10
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.
11
+ Inside any text: [label](url) is a link, **bold**, *italic*, `code` (a fact, shown as data), [[key]] a key cap,
12
+ {name} a value the page fills in (Slop.vars), and \ makes the next character literal.
13
13
 
14
14
  A blank line starts a new paragraph in a <p>, <li> or <dd>.
15
15
 
16
16
  Elements with data-slop="group.key" are filled from the block. Code renders the rest with Slop.html(path). An
17
17
  element with data-slop-list="group" shows each text in that group in a copy of its first child, and the editor can
18
- add and remove texts there (data-slop-list-ref: the page draws them itself).
18
+ add and remove texts there (data-slop-list-ref: the page draws them itself). A group's paragraphs in alike elements
19
+ with one parent are a list without marking (data-slop-list="off" on the parent: not one).
19
20
  An element with data-slop-meter becomes the Slop-o-meter switch. Under `slop-editor edit`, the page also gets the
20
21
  editor, which saves back into the file; with Slop.start({edit: 'local'}) it gets one that saves in the browser. */
21
22
  const Slop = (() => {
@@ -106,7 +107,8 @@ const Slop = (() => {
106
107
  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;
107
108
 
108
109
  // the text as it reads: runs of one author's words (`by`: the category) with their formatting (b, i, code, key)
109
- // and the link they sit in, if any. A {name} is a run of its own with `v` set
110
+ // and the link they sit in, if any. A {name} is a run of its own with `v` set. Code is a fact: whoever wrote it,
111
+ // a command or a file name reads as data
110
112
  function runs(value) {
111
113
  const text = plain(value);
112
114
  const authors = authorsByChar(value);
@@ -115,7 +117,7 @@ const Slop = (() => {
115
117
  let linkEnd = -1;
116
118
  let linkTail = 0;
117
119
  const push = (s, by, v) => {
118
- const run = { text: s, by, link: st.link, b: st.b, i: st.i, code: st.code, key: st.key, v };
120
+ const run = { text: s, by: st.code ? 'data' : by, link: st.link, b: st.b, i: st.i, code: st.code, key: st.key, v };
119
121
  const last = out[out.length - 1];
120
122
  if (last && !last.v && !v && same(last, run)) last.text += s;
121
123
  else out.push(run);
@@ -165,6 +167,8 @@ const Slop = (() => {
165
167
  // whoever wrote the {name}), or a plain string or number (a fact)
166
168
  const vars = {};
167
169
  const config = { code: 'code' };
170
+ // where the browser editor keeps this page's copy: its path, or the page's own name for it (Slop.start({key}))
171
+ const pageKey = () => config.key ?? location.pathname;
168
172
  const esc = (s) => String(s).replace(/[&<>"]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' })[c]);
169
173
  const stripTags = (h) => h.replace(/<[^>]*>/g, '').replace(/&nbsp;/g, ' ').replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&quot;/g, '"').replace(/&amp;/g, '&');
170
174
  // the class a category's words render with
@@ -262,7 +266,51 @@ const Slop = (() => {
262
266
  return [...byWords].filter(([, paths]) => paths.length > 1).map(([words, paths]) => ({ words, paths }));
263
267
  }
264
268
 
265
- const core = { BUILTIN, plain, applyEdit, reslop, unslop, assign, reattribute, runs, readable, render, makeup, share, percent, repeats, wordsOf, paragraphsOf, vars };
269
+ // a copy of the block saved in the browser, carried over to a page the author has changed since: text by text,
270
+ // the copy's value stays where the page's is still the one the copy was based on, and the page's wins where the
271
+ // author changed, added or removed it. Groups (and _categories) merge key by key; what the copy added keeps its
272
+ // place after the key it followed
273
+ function rebase(base, mine, page) {
274
+ const group = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
275
+ if (!group(base) || !group(mine) || !group(page)) return JSON.stringify(page) === JSON.stringify(base) ? mine : page;
276
+ const keys = Object.keys(page);
277
+ Object.keys(mine).forEach((k, i, order) => {
278
+ if (keys.includes(k)) return;
279
+ const after = order.slice(0, i).reverse().find((x) => keys.includes(x));
280
+ keys.splice(after === undefined ? 0 : keys.indexOf(after) + 1, 0, k);
281
+ });
282
+ const out = {};
283
+ keys.forEach((k) => {
284
+ const v = rebase(base[k], mine[k], page[k]);
285
+ if (v !== undefined) out[k] = v;
286
+ });
287
+ return out;
288
+ }
289
+
290
+ // a group's paragraphs (keys p1, p2…) are a list without marking when the page has two or more of them in
291
+ // elements that share one parent and are alike: the same tag and the same other attributes, so steps told apart by
292
+ // an attribute (data-b="0", "1"…) aren't one. [{path, parent, tag, attrs}] → Map group → parent
293
+ const isParagraph = (key) => /^p\d+$/.test(key);
294
+ function listsIn(items) {
295
+ const byGroup = new Map();
296
+ items.forEach((x) => {
297
+ const keys = x.path.split('.');
298
+ if (keys.length < 2 || !isParagraph(keys.at(-1))) return;
299
+ const g = keys.slice(0, -1).join('.');
300
+ if (!byGroup.has(g)) byGroup.set(g, []);
301
+ byGroup.get(g).push(x);
302
+ });
303
+ const look = (x) => `${x.tag}\n${JSON.stringify(Object.entries(x.attrs ?? {}).sort())}`;
304
+ const out = new Map();
305
+ byGroup.forEach((xs, g) => {
306
+ const [a] = xs;
307
+ if (xs.length < 2 || a.parent == null || new Set(xs.map((x) => x.path)).size < xs.length) return;
308
+ if (xs.every((x) => x.parent === a.parent && look(x) === look(a))) out.set(g, a.parent);
309
+ });
310
+ return out;
311
+ }
312
+
313
+ const core = { BUILTIN, plain, applyEdit, reslop, unslop, assign, reattribute, runs, readable, render, makeup, share, percent, repeats, rebase, listsIn, wordsOf, paragraphsOf, vars };
266
314
  if (typeof document === 'undefined') return core; // Node (the CLI and the tests) only needs the format
267
315
 
268
316
  /* ---------- the block ---------- */
@@ -377,33 +425,65 @@ const Slop = (() => {
377
425
  });
378
426
  if (copies.length) spills.set(el, copies); else spills.delete(el);
379
427
  }
380
- // a list: an element with data-slop-list="group" shows each text in that group, in order, in a copy of its first
381
- // child. (With data-slop-list-ref, the page draws them itself.) Either way, the editor can add and remove texts there
382
- const templates = new WeakMap(); // list → the element its texts are copies of
428
+ // a list: an element with data-slop-list="group" shows the group's paragraphs (p1, p2, …), in order, each in a copy
429
+ // of the first. The group's other texts (a title, a caption) and the element's other children stay where they
430
+ // are. (With data-slop-list-ref, the page draws them itself.) Either way, the editor can add and remove paragraphs
431
+ const templates = new WeakMap(); // list → the element its paragraphs are copies of
432
+ // lists the page didn't mark (listsIn): [data-slop] elements, filled here, not drawn by the page's code. Its
433
+ // paragraphs that aren't on the page yet are drawn after the others, as in a marked list. Once found, a list stays
434
+ // one while its element is on the page. data-slop-list="off" on the parent opts out
435
+ const autos = new Map(); // parent → group
436
+ const marked = (x) => (x.dataset.slopList && x.dataset.slopList !== 'off' ? x.dataset.slopList : '');
437
+ const listOf = (box) => marked(box) || autos.get(box);
438
+ // an element's attributes but data-slop and the classes slop.js adds
439
+ const own = (x) => Object.fromEntries([...x.attributes].filter((a) => a.name !== 'data-slop')
440
+ .map((a) => [a.name, a.name === 'class' ? [...x.classList].filter((c) => !c.startsWith('slop-')).sort().join(' ') : a.value])
441
+ .filter(([name, v]) => name !== 'class' || v));
442
+ function findLists() {
443
+ autos.forEach((g, box) => { if (!box.isConnected) autos.delete(box); });
444
+ const taken = new Set([...document.querySelectorAll('[data-slop-list], [data-slop-list-ref]')].map((x) => marked(x) || x.dataset.slopListRef).filter(Boolean));
445
+ autos.forEach((g) => taken.add(g));
446
+ const els = [...document.querySelectorAll('[data-slop]')].filter((x) => !x.closest('.slop-panel'));
447
+ listsIn(els.map((x) => ({ path: x.dataset.slop, parent: x.parentElement, tag: x.tagName, attrs: own(x) }))).forEach((box, g) => {
448
+ if (taken.has(g) || box.dataset.slopList === 'off' || autos.has(box)) return;
449
+ // the page's code shows one of them some other way: not a list of ours
450
+ const paths = textKeys(nodeAt(text, g)).filter(isParagraph).map((k) => `${g}.${k}`);
451
+ if (paths.some((p) => rendered.has(p) || revealers.has(p) || elementsOf(p).some((x) => !x.dataset.slop && !x.dataset.slopMore))) return;
452
+ autos.set(box, g);
453
+ });
454
+ }
383
455
  function fillList(box) {
384
- const at = box.dataset.slopList;
456
+ const at = listOf(box);
457
+ if (!at) return;
458
+ const ours = (x) => x.dataset.slop?.startsWith(`${at}.`) && isParagraph(x.dataset.slop.slice(at.length + 1));
385
459
  if (!templates.has(box)) {
386
- if (!box.firstElementChild) return;
387
- const t = box.firstElementChild.cloneNode(false);
460
+ const first = [...box.children].find(ours);
461
+ if (!first) return;
462
+ const t = first.cloneNode(false);
388
463
  ['id', 'data-slop'].forEach((a) => t.removeAttribute(a));
389
464
  templates.set(box, t);
390
465
  }
391
- const paths = textKeys(nodeAt(text, at)).map((k) => `${at}.${k}`);
392
- const have = new Map([...box.children].filter((x) => x.dataset.slop).map((x) => [x.dataset.slop, x]));
466
+ const paths = textKeys(nodeAt(text, at)).filter(isParagraph).map((k) => `${at}.${k}`);
467
+ const have = new Map([...box.children].filter(ours).map((x) => [x.dataset.slop, x]));
393
468
  have.forEach((x, p) => { if (!paths.includes(p)) { spill(x, []); x.remove(); } });
394
- let last = null;
395
- paths.forEach((p) => {
396
- let x = have.get(p);
397
- if (!x) {
398
- x = templates.get(box).cloneNode(false);
399
- x.dataset.slop = p;
400
- }
401
- if (last ? last.nextElementSibling !== x : box.firstElementChild !== x) (last ? last.after(x) : box.prepend(x));
402
- last = spills.get(x)?.at(-1) ?? x;
469
+ // a new one goes after the paragraph before it (and the paragraphs that one spilled into), or else before the
470
+ // one after it
471
+ const shown = (p) => [...box.children].find((x) => x.dataset.slop === p);
472
+ paths.forEach((p, i) => {
473
+ if (have.has(p)) return;
474
+ const x = templates.get(box).cloneNode(false);
475
+ x.dataset.slop = p;
476
+ const before = paths.slice(0, i).reverse().map(shown).find(Boolean);
477
+ const after = paths.slice(i + 1).map(shown).find(Boolean);
478
+ if (before) (spills.get(before)?.at(-1) ?? before).after(x);
479
+ else if (after) after.before(x);
480
+ else box.append(x);
403
481
  });
404
482
  }
405
483
  const fill = (root = document) => {
484
+ if (root === document || root.matches?.('[data-slop]') || root.querySelector?.('[data-slop]')) findLists();
406
485
  root.querySelectorAll('[data-slop-list]').forEach(fillList);
486
+ autos.forEach((g, box) => { if (root.contains(box) && !marked(box)) fillList(box); });
407
487
  root.querySelectorAll('[data-slop], [data-slop-attr]').forEach(fillOne);
408
488
  // paragraphs whose element the page took away, or no longer shows that text in
409
489
  root.querySelectorAll('[data-slop-more]').forEach((c) => {
@@ -422,7 +502,7 @@ const Slop = (() => {
422
502
  };
423
503
  // the [data-slop] elements and meters in what the page added after start (a single-page app draws late)
424
504
  function added(n) {
425
- if (n.nodeType !== 1 || n.closest('.slop-panel')) return;
505
+ if (n.nodeType !== 1 || n.closest('.slop-panel, .slop-sampler')) return;
426
506
  seenSoon();
427
507
  if (n.matches('[data-slop-list]')) fillList(n);
428
508
  if (n.matches('[data-slop], [data-slop-attr]')) fillOne(n);
@@ -540,7 +620,7 @@ const Slop = (() => {
540
620
 
541
621
  const storage = (area) => ({
542
622
  get: (k) => { try { return area().getItem(k); } catch { return null; } },
543
- set: (k, v) => { try { area().setItem(k, v); } catch { /* optional */ } },
623
+ set: (k, v) => { try { area().setItem(k, v); return true; } catch { return false; } },
544
624
  drop: (k) => { try { area().removeItem(k); } catch { /* optional */ } },
545
625
  });
546
626
  const store = storage(() => localStorage);
@@ -593,7 +673,7 @@ const Slop = (() => {
593
673
  pie.title = breakdown(m, cats);
594
674
  pie.setAttribute('aria-label', pie.title);
595
675
  // each category in its own color, with its share of the text
596
- legend.innerHTML = cats.filter((c) => m.counts[c.id])
676
+ legend.innerHTML = cats.filter((c) => m.counts[c.id]).sort((a, b) => m.counts[b.id] - m.counts[a.id])
597
677
  .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('');
598
678
  });
599
679
  }
@@ -641,12 +721,13 @@ const Slop = (() => {
641
721
  return title && title.length <= 32 ? title : human(key);
642
722
  };
643
723
  // the groups the page shows as lists, where the editor can add and remove texts
644
- const listed = () => new Set([...document.querySelectorAll('[data-slop-list], [data-slop-list-ref]')].map((x) => x.dataset.slopList || x.dataset.slopListRef));
724
+ const listed = () => new Set([...document.querySelectorAll('[data-slop-list], [data-slop-list-ref]')].map((x) => marked(x) || x.dataset.slopListRef).filter(Boolean)
725
+ .concat([...autos].filter(([box]) => box.isConnected).map(([, g]) => g)));
645
726
  // keys[i], for people. In a list, a paragraph is named by where it is: "Paragraph 3", even when its key is p7
646
727
  function keyName(keys, i) {
647
728
  const group = keys.slice(0, i).join('.');
648
- if (!/^p\d+$/.test(keys[i]) || !listed().has(group)) return human(keys[i]);
649
- return `Paragraph ${textKeys(nodeAt(text, group)).indexOf(keys[i]) + 1}`;
729
+ if (!isParagraph(keys[i]) || !listed().has(group)) return human(keys[i]);
730
+ return `Paragraph ${textKeys(nodeAt(text, group)).filter(isParagraph).indexOf(keys[i]) + 1}`;
650
731
  }
651
732
  // where a text is, for people: "Introduction · Paragraph 2"
652
733
  const where = (path) => {
@@ -665,7 +746,7 @@ const Slop = (() => {
665
746
  const startTab = () => (repeats(entries()).some((s) => s.paths.some(slopIn)) ? 'repeats' : entries().some(([p]) => slopIn(p)) ? 'slop' : 'all');
666
747
 
667
748
  function editor(mode) {
668
- const LOCAL = `slop-text:${location.pathname}`;
749
+ const LOCAL = `slop-text:${pageKey()}`;
669
750
  // open: the first section, and any the page adds later (pasted text, say)
670
751
  // it opens on Repeats, or on Slop left when nothing is repeated
671
752
  const state = { tab: startTab(), open: new Set(groupKeys().slice(0, 1)), known: new Set(groupKeys()), focus: null };
@@ -784,23 +865,29 @@ const Slop = (() => {
784
865
  for (let n = 2; id in BUILTIN || text._categories?.[id] || categories().some((c) => c.id === id); n++) id = `${base}-${n}`;
785
866
  return id;
786
867
  };
868
+ // the categories, the one with most of the page first (as the meters' legends). A category of the page's own
869
+ // can say whose words it means and ask an agent to find them (about, find); what an agent marked waits for
870
+ // Keep or Undo (found.before)
787
871
  function renderCats() {
872
+ closePicker();
788
873
  const box = $('.sp-cats');
789
874
  box.innerHTML = '';
790
- categories().forEach((cat) => {
791
- const row = el('span', 'sp-cat', `<label class="sp-swatch" title="Pick a color for ${esc(cat.label)}"><input type="color"></label>`
875
+ const counts = makeup(entries().map(([, v]) => v)).counts;
876
+ categories().sort((a, b) => (counts[b.id] ?? 0) - (counts[a.id] ?? 0)).forEach((cat) => {
877
+ const row = el('span', 'sp-cat', `<button type="button" class="sp-swatch" title="Click to pick a color for ${esc(cat.label)}, or drag onto the page to take one from it" aria-label="Pick a color for ${esc(cat.label)}"></button>`
792
878
  + `<input class="sp-cat-name" aria-label="Category name" spellcheck="false"><b class="sp-cat-pct"></b>`
793
879
  + (cat.builtin ? '' : `<button type="button" class="sp-cat-x" title="Delete ${esc(cat.label)}: its words become AI-generated">×</button>`));
794
880
  row.dataset.id = cat.id;
795
- const picker = row.querySelector('input[type="color"]');
796
- picker.value = hex(swatch(cat));
797
- row.querySelector('.sp-swatch').style.background = swatch(cat);
798
- picker.addEventListener('input', () => {
799
- own(cat.id).color = picker.value;
800
- row.querySelector('.sp-swatch').style.background = picker.value;
881
+ const dot = row.querySelector('.sp-swatch');
882
+ const pick = (color) => {
883
+ setColor(cat.id, color);
884
+ dot.style.background = color;
801
885
  applyColors();
802
886
  touched();
803
- });
887
+ };
888
+ dot.style.background = swatch(cat);
889
+ dragColor(dot, pick);
890
+ dot.addEventListener('click', (e) => { if (!e.defaultPrevented) picker(cat.id, dot, pick); });
804
891
  const name = row.querySelector('.sp-cat-name');
805
892
  name.value = cat.label;
806
893
  name.size = Math.max(3, cat.label.length);
@@ -810,6 +897,9 @@ const Slop = (() => {
810
897
  touched();
811
898
  });
812
899
  name.addEventListener('keydown', (e) => { if (e.key === 'Enter') name.blur(); });
900
+ // selecting a category opens whose words it means, under the categories
901
+ name.addEventListener('focus', () => about(cat.id));
902
+ row.addEventListener('click', (e) => { if (!e.target.closest('.sp-swatch, .sp-cat-x, .sp-cat-name')) about(cat.id); });
813
903
  row.querySelector('.sp-cat-x')?.addEventListener('click', () => {
814
904
  withUndo(`Deleted "${cat.label}"`, () => {
815
905
  entries().forEach(([p, v]) => set(p, reattribute(v, cat.id, 'ai')));
@@ -829,23 +919,446 @@ const Slop = (() => {
829
919
  add.replaceWith(input);
830
920
  input.focus();
831
921
  let finished = false;
922
+ let made = null;
832
923
  const done = (keep) => {
833
924
  if (finished) return;
834
925
  finished = true;
835
926
  const label = input.value.trim();
836
927
  if (keep && label) {
837
- const id = slug(label);
928
+ made = slug(label);
838
929
  const color = PALETTE[categories().filter((c) => !c.builtin).length % PALETTE.length];
839
- Object.assign(own(id), { label, color });
930
+ Object.assign(own(made), { label, color });
840
931
  applyColors();
841
932
  touched();
842
933
  }
843
934
  render();
935
+ if (made) about(made, true); // whose words they are, next
844
936
  };
845
937
  input.addEventListener('keydown', (e) => { if (e.key === 'Enter') done(true); if (e.key === 'Escape') done(false); });
846
938
  input.addEventListener('blur', () => done(true), { once: true });
847
939
  });
848
940
  box.append(add);
941
+ // every picked color back to the default, in one undoable step. Shown while there's one (numbers())
942
+ const back = el('button', 'sp-cat-revert', 'Revert colors');
943
+ back.type = 'button';
944
+ back.title = 'Every category back to its default color';
945
+ back.addEventListener('click', () => {
946
+ withUndo('Colors back to the defaults', () => Object.keys(text._categories).forEach((id) => setColor(id, null)));
947
+ applyColors();
948
+ render();
949
+ });
950
+ box.append(back);
951
+ if (aboutOpen && categories().some((c) => c.id === aboutOpen)) about(aboutOpen);
952
+ // what an agent marked, for the author to keep or undo
953
+ Object.entries(text._categories ?? {}).forEach(([id, c]) => {
954
+ const before = c.found?.before;
955
+ if (!before || !Object.keys(before).length) return;
956
+ const n = Object.keys(before).length;
957
+ const label = categories().find((x) => x.id === id)?.label ?? id;
958
+ const note = el('p', 'sp-found', `${esc(`An agent marked ${count(n, 'text')} as ${label}${c.found.on ? ` on ${day(c.found.on)}` : ''}`)} · `);
959
+ note.dataset.id = id;
960
+ const keep = el('button', 'sp-link', 'Keep');
961
+ keep.type = 'button';
962
+ keep.title = 'Keep what the agent marked';
963
+ keep.addEventListener('click', () => { withUndo(`Kept the agent's marks for ${label}`, () => { delete c.found.before; }); render(); });
964
+ const undoBtn = el('button', 'sp-link', 'Undo');
965
+ undoBtn.type = 'button';
966
+ undoBtn.title = 'Give those texts back to whoever had them before (texts whose words changed since stay as they are)';
967
+ undoBtn.addEventListener('click', () => {
968
+ withUndo(`Undid the agent's marks for ${label}`, () => {
969
+ Object.entries(before).forEach(([p, was]) => {
970
+ const now = valueAt(text, p);
971
+ if (now !== undefined && plain(now) === plain(was)) set(p, was);
972
+ });
973
+ delete c.found;
974
+ });
975
+ render();
976
+ });
977
+ note.append(keep, ' · ', undoBtn);
978
+ box.append(note);
979
+ });
980
+ }
981
+ const day = (iso) => { const d = new Date(`${iso}T12:00:00`); return Number.isNaN(+d) ? iso : d.toLocaleDateString(undefined, { month: 'short', day: 'numeric' }); };
982
+
983
+ /* whose words a category means, and whether an agent should find them: under the categories while open */
984
+ let aboutOpen = null;
985
+ // an agent can find the words of a category of the page's own, or facts and quotes. Only the author can say which
986
+ // words are theirs or approved, and slop is whatever's left
987
+ const findable = (id) => !(id in BUILTIN) || id === 'data';
988
+ // a category's entry, dropped once it says nothing
989
+ function tidy(id) {
990
+ const c = text._categories?.[id];
991
+ if (c && !Object.keys(c).length) delete text._categories[id];
992
+ if (text._categories && !Object.keys(text._categories).length) delete text._categories;
993
+ }
994
+ function about(id, focus) {
995
+ aboutOpen = id;
996
+ const box = $('.sp-cats');
997
+ box.querySelector('.sp-about')?.remove();
998
+ box.querySelectorAll('.sp-cat').forEach((x) => x.classList.toggle('sp-cat-on', x.dataset.id === id));
999
+ const c = () => text._categories?.[id] ?? {};
1000
+ const label = () => categories().find((x) => x.id === id)?.label ?? id;
1001
+ const panel = el('div', 'sp-about', `<label class="sp-about-q" for="sp-about-${esc(id)}"></label>`
1002
+ + `<textarea id="sp-about-${esc(id)}" rows="2" spellcheck="true" placeholder="Who wrote them, or where they come from"></textarea>`
1003
+ + '<div class="sp-about-row"><label class="sp-check"><input type="checkbox"> Ask an agent to find them</label><button type="button" class="sp-link sp-about-done">Done</button></div>'
1004
+ + '<p class="sp-about-note"></p>');
1005
+ panel.dataset.id = id;
1006
+ panel.querySelector('.sp-about-q').textContent = `Whose words are ${label()}?`;
1007
+ const desc = panel.querySelector('textarea');
1008
+ const ask = panel.querySelector('input[type="checkbox"]');
1009
+ const note = panel.querySelector('.sp-about-note');
1010
+ panel.querySelector('.sp-check').hidden = !findable(id);
1011
+ desc.value = c().about ?? '';
1012
+ ask.checked = !!c().find;
1013
+ const paint = () => {
1014
+ note.innerHTML = '';
1015
+ if (c().find) {
1016
+ note.append('Waiting for an agent: it finds them the next time one works on this page, once you save. ');
1017
+ const copy = el('button', 'sp-link', 'Copy a prompt');
1018
+ copy.type = 'button';
1019
+ copy.title = 'To ask an agent now';
1020
+ copy.addEventListener('click', () => {
1021
+ const page = decodeURIComponent(location.pathname.split('/').pop() || '') || 'this page';
1022
+ const prompt = `In ${page}, find the words that belong to the slop-editor category "${label()}"${c().about ? ` (${c().about})` : ''} and mark them, following the slop-editor skill's "Categories to find".`;
1023
+ Promise.resolve(navigator.clipboard?.writeText(prompt)).then(() => status('Prompt copied')).catch(() => status("Couldn't copy the prompt", 'error'));
1024
+ });
1025
+ note.append(copy);
1026
+ } else if (c().found?.on) note.append(`Found by an agent · ${day(c().found.on)}`);
1027
+ note.hidden = !note.childNodes.length;
1028
+ };
1029
+ desc.addEventListener('input', () => {
1030
+ if (desc.value.trim()) own(id).about = desc.value.trim();
1031
+ else { delete text._categories?.[id]?.about; tidy(id); }
1032
+ touched();
1033
+ });
1034
+ ask.addEventListener('change', () => {
1035
+ if (ask.checked) own(id).find = true;
1036
+ else { delete text._categories?.[id]?.find; tidy(id); }
1037
+ paint();
1038
+ touched();
1039
+ });
1040
+ panel.querySelector('.sp-about-done').addEventListener('click', () => {
1041
+ aboutOpen = null;
1042
+ panel.remove();
1043
+ box.querySelectorAll('.sp-cat-on').forEach((x) => x.classList.remove('sp-cat-on'));
1044
+ });
1045
+ paint();
1046
+ box.querySelector('.sp-found') ? box.querySelector('.sp-found').before(panel) : box.append(panel);
1047
+ if (focus) desc.focus();
1048
+ }
1049
+
1050
+ /* the color picker, under a category's dot, laid out like the browser's own: a rectangle of shades, then the
1051
+ eyedropper, the color and a hue bar, then its numbers (RGB, HEX or HSL: the arrows switch). Its eyedropper shows
1052
+ the page magnified beside the pointer, not over it */
1053
+ const rgbOf = (c) => [1, 3, 5].map((i) => parseInt(c.slice(i, i + 2), 16));
1054
+ const hexOf = (rgb) => `#${rgb.map((v) => Math.round(clamp(v, 0, 255)).toString(16).padStart(2, '0')).join('')}`;
1055
+ function toHsv(color) {
1056
+ const [r, g, b] = rgbOf(color).map((v) => v / 255);
1057
+ const max = Math.max(r, g, b);
1058
+ const d = max - Math.min(r, g, b);
1059
+ const h = !d ? 0 : max === r ? ((g - b) / d) % 6 : max === g ? (b - r) / d + 2 : (r - g) / d + 4;
1060
+ return { h: (h * 60 + 360) % 360, s: max ? d / max : 0, v: max };
1061
+ }
1062
+ function fromHsv({ h, s, v }) {
1063
+ const f = (n) => { const k = (n + h / 60) % 6; return v - v * s * Math.max(0, Math.min(k, 4 - k, 1)); };
1064
+ return hexOf([f(5), f(3), f(1)].map((x) => x * 255));
1065
+ }
1066
+ function hslOf(color) {
1067
+ const [r, g, b] = rgbOf(color).map((v) => v / 255);
1068
+ const max = Math.max(r, g, b);
1069
+ const min = Math.min(r, g, b);
1070
+ const l = (max + min) / 2;
1071
+ const d = max - min;
1072
+ const s = !d ? 0 : d / (1 - Math.abs(2 * l - 1));
1073
+ return [Math.round(toHsv(color).h), Math.round(s * 100), Math.round(l * 100)];
1074
+ }
1075
+ function fromHsl([h, s, l]) {
1076
+ const a = (s / 100) * Math.min(l / 100, 1 - l / 100);
1077
+ const f = (n) => { const k = (n + h / 30) % 12; return l / 100 - a * Math.max(-1, Math.min(k - 3, 9 - k, 1)); };
1078
+ return hexOf([f(0), f(8), f(4)].map((x) => x * 255));
1079
+ }
1080
+ const FORMATS = {
1081
+ rgb: { labels: ['R', 'G', 'B'], read: rgbOf, write: hexOf, max: [255, 255, 255] },
1082
+ hex: { labels: ['HEX'], read: (c) => [c], write: ([v]) => (/^#?[0-9a-f]{6}$/i.test(v.trim()) ? `#${v.trim().replace('#', '').toLowerCase()}` : null) },
1083
+ hsl: { labels: ['H', 'S', 'L'], read: hslOf, write: fromHsl, max: [359, 100, 100] },
1084
+ };
1085
+ const DROPPER = '<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M10.4 2.4a1.9 1.9 0 0 1 2.7 2.7l-1.6 1.6.8.8-1.1 1.1-.8-.8-5.2 5.2H3v-2.2l5.2-5.2-.8-.8 1.1-1.1.8.8z" fill="none" stroke="currentColor" stroke-width="1.3" stroke-linejoin="round"/></svg>';
1086
+ let pickEl = null;
1087
+ let pickFormat = 'rgb';
1088
+ let dropping = false;
1089
+ function closePicker() {
1090
+ pickEl?.remove();
1091
+ pickEl = null;
1092
+ }
1093
+ function picker(id, dot, pick) {
1094
+ const again = pickEl?.dataset.id === id;
1095
+ closePicker();
1096
+ if (again) return; // a second click on the dot closes it
1097
+ const cat = () => categories().find((c) => c.id === id);
1098
+ const p = el('div', 'sp-pick', '<div class="sp-pick-sv" tabindex="0" role="slider" aria-label="Shade: right for more color, down for darker"><i></i></div>'
1099
+ + `<div class="sp-pick-row"><button type="button" class="sp-pick-drop" title="Take a color from the page" aria-label="Take a color from the page">${DROPPER}</button>`
1100
+ + '<b class="sp-pick-now"></b><input type="range" class="sp-pick-hue" min="0" max="359" step="1" aria-label="Hue"></div>'
1101
+ + '<div class="sp-pick-nums"></div>');
1102
+ p.dataset.id = id;
1103
+ pickEl = p;
1104
+ const sv = p.querySelector('.sp-pick-sv');
1105
+ const handle = sv.querySelector('i');
1106
+ const hue = p.querySelector('.sp-pick-hue');
1107
+ const now = p.querySelector('.sp-pick-now');
1108
+ const nums = p.querySelector('.sp-pick-nums');
1109
+ let hsv = toHsv(hex(swatch(cat())));
1110
+ function fields() {
1111
+ const f = FORMATS[pickFormat];
1112
+ nums.innerHTML = f.labels.map((l) => `<label class="sp-pick-num"><input spellcheck="false" aria-label="${l}"><span>${l}</span></label>`).join('')
1113
+ + '<button type="button" class="sp-pick-swap" title="RGB, HEX or HSL" aria-label="Switch between RGB, HEX and HSL"><svg viewBox="0 0 12 16" width="10" height="14" aria-hidden="true"><path d="M2 6l4-4 4 4M2 10l4 4 4-4" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"/></svg></button>';
1114
+ const inputs = [...nums.querySelectorAll('input')];
1115
+ inputs.forEach((input) => input.addEventListener('input', () => {
1116
+ const vals = inputs.map((x) => (f.max ? Number(x.value) : x.value));
1117
+ if (f.max && vals.some((v, i) => !Number.isFinite(v) || v < 0 || v > f.max[i])) return;
1118
+ const c = f.write(vals);
1119
+ if (!c) return;
1120
+ hsv = toHsv(c);
1121
+ apply();
1122
+ }));
1123
+ inputs.forEach((input) => input.addEventListener('blur', paint));
1124
+ nums.querySelector('.sp-pick-swap').addEventListener('click', () => {
1125
+ const order = Object.keys(FORMATS);
1126
+ pickFormat = order[(order.indexOf(pickFormat) + 1) % order.length];
1127
+ fields();
1128
+ paint();
1129
+ });
1130
+ }
1131
+ function paint() {
1132
+ const c = fromHsv(hsv);
1133
+ sv.style.background = `linear-gradient(to top, #000, transparent), linear-gradient(to right, #fff, hsl(${hsv.h} 100% 50%))`;
1134
+ Object.assign(handle.style, { left: `${hsv.s * 100}%`, top: `${(1 - hsv.v) * 100}%`, background: c });
1135
+ hue.value = Math.round(hsv.h);
1136
+ hue.style.setProperty('--hue', `hsl(${hsv.h} 100% 50%)`);
1137
+ now.style.background = c;
1138
+ sv.setAttribute('aria-valuetext', c);
1139
+ const vals = FORMATS[pickFormat].read(c);
1140
+ nums.querySelectorAll('input').forEach((x, i) => { if (document.activeElement !== x) x.value = vals[i]; });
1141
+ }
1142
+ function apply() {
1143
+ pick(fromHsv(hsv));
1144
+ paint();
1145
+ }
1146
+ const at = (e) => {
1147
+ const r = sv.getBoundingClientRect();
1148
+ hsv.s = clamp((e.clientX - r.left) / r.width, 0, 1);
1149
+ hsv.v = 1 - clamp((e.clientY - r.top) / r.height, 0, 1);
1150
+ apply();
1151
+ };
1152
+ sv.addEventListener('pointerdown', (e) => {
1153
+ if (e.button !== 0) return;
1154
+ e.preventDefault();
1155
+ sv.focus();
1156
+ sv.setPointerCapture(e.pointerId);
1157
+ at(e);
1158
+ const move = (ev) => at(ev);
1159
+ const up = () => { sv.removeEventListener('pointermove', move); sv.removeEventListener('pointerup', up); };
1160
+ sv.addEventListener('pointermove', move);
1161
+ sv.addEventListener('pointerup', up);
1162
+ });
1163
+ sv.addEventListener('keydown', (e) => {
1164
+ const step = e.shiftKey ? 0.1 : 0.02;
1165
+ const d = { ArrowLeft: ['s', -step], ArrowRight: ['s', step], ArrowUp: ['v', step], ArrowDown: ['v', -step] }[e.key];
1166
+ if (!d) return;
1167
+ e.preventDefault();
1168
+ hsv[d[0]] = clamp(hsv[d[0]] + d[1], 0, 1);
1169
+ apply();
1170
+ });
1171
+ hue.addEventListener('input', () => { hsv.h = +hue.value; apply(); });
1172
+ p.querySelector('.sp-pick-drop').addEventListener('click', (e) => eyedrop(e, (c) => { hsv = toHsv(c); apply(); }));
1173
+ p.addEventListener('keydown', (e) => { if (e.key === 'Escape' && !dropping) { e.stopPropagation(); closePicker(); dot.focus(); } });
1174
+ aside.append(p);
1175
+ // under the dot, inside the editor
1176
+ const a = aside.getBoundingClientRect();
1177
+ const r = dot.getBoundingClientRect();
1178
+ p.style.top = `${r.bottom - a.top + 8}px`;
1179
+ p.style.left = `${clamp(r.left - a.left - 10, 8, a.width - p.offsetWidth - 8)}px`;
1180
+ fields();
1181
+ paint();
1182
+ }
1183
+ // the eyedropper: the magnifier follows the pointer until a click takes the color under it (Escape: none)
1184
+ function eyedrop(start, done) {
1185
+ dropping = true;
1186
+ const lens = sampler();
1187
+ let color = null;
1188
+ const move = (e) => { color = colorAt(e.clientX, e.clientY); lens.show(e.clientX, e.clientY, color); };
1189
+ move(start);
1190
+ const off = new AbortController();
1191
+ const stop = (e) => { e.preventDefault(); e.stopPropagation(); };
1192
+ const finish = (keep) => {
1193
+ off.abort();
1194
+ lens.remove();
1195
+ dropping = false;
1196
+ if (keep && color) done(color);
1197
+ // the click that took it mustn't reach the page (or the next press clears that)
1198
+ const after = new AbortController();
1199
+ addEventListener('click', (e) => { stop(e); after.abort(); }, { capture: true, signal: after.signal });
1200
+ addEventListener('pointerdown', () => after.abort(), { capture: true, signal: after.signal });
1201
+ };
1202
+ addEventListener('pointermove', move, { capture: true, signal: off.signal });
1203
+ addEventListener('pointerdown', (e) => { stop(e); move(e); finish(true); }, { capture: true, signal: off.signal });
1204
+ addEventListener('keydown', (e) => { if (e.key === 'Escape') { stop(e); finish(false); } }, { capture: true, signal: off.signal });
1205
+ }
1206
+ // a press anywhere but the picker or a dot closes it
1207
+ addEventListener('pointerdown', (e) => {
1208
+ if (pickEl && !dropping && !pickEl.contains(e.target) && !e.target.closest?.('.sp-swatch')) closePicker();
1209
+ }, true);
1210
+
1211
+ /* drag a category's dot onto the page to take a color from it: the point is a ring, and the color shows in a
1212
+ circle beside it, joined by a line, so the pointer never hides it. A click still opens the browser's picker */
1213
+ function dragColor(dot, pick) {
1214
+ let dragged = false; // the click that ends a drag mustn't open the picker
1215
+ dot.addEventListener('click', (e) => { if (dragged) { e.preventDefault(); dragged = false; } });
1216
+ dot.addEventListener('pointerdown', (e) => {
1217
+ if (e.button !== 0) return;
1218
+ dragged = false;
1219
+ const x0 = e.clientX;
1220
+ const y0 = e.clientY;
1221
+ let lens = null;
1222
+ let color = null;
1223
+ const move = (ev) => {
1224
+ if (!lens) {
1225
+ if (Math.hypot(ev.clientX - x0, ev.clientY - y0) < 6) return;
1226
+ lens = sampler();
1227
+ dot.setPointerCapture(ev.pointerId);
1228
+ }
1229
+ color = colorAt(ev.clientX, ev.clientY);
1230
+ lens.show(ev.clientX, ev.clientY, color);
1231
+ };
1232
+ let cancelled = false;
1233
+ const up = (ev) => {
1234
+ removeEventListener('pointermove', move, true);
1235
+ removeEventListener('pointerup', up, true);
1236
+ removeEventListener('keydown', esc, true);
1237
+ if (!lens) return;
1238
+ lens.remove();
1239
+ dragged = true;
1240
+ ev.preventDefault();
1241
+ if (!cancelled && color) pick(color);
1242
+ };
1243
+ // Escape drops it: the color stays as it was
1244
+ const esc = (ev) => {
1245
+ if (ev.key !== 'Escape' || !lens) return;
1246
+ ev.preventDefault();
1247
+ cancelled = true;
1248
+ lens.remove();
1249
+ removeEventListener('pointermove', move, true);
1250
+ };
1251
+ addEventListener('pointermove', move, true);
1252
+ addEventListener('pointerup', up, true);
1253
+ addEventListener('keydown', esc, true);
1254
+ });
1255
+ }
1256
+ // a magnifier beside the point, not over it: a copy of the page, scaled up around the point, in a circle up and to
1257
+ // the right (or wherever there's room), joined to a ring at the point by a line. The circle's rim is the color
1258
+ const LENS = { r: 64, zoom: 3, off: 96 };
1259
+ function sampler() {
1260
+ const lens = el('div', 'slop-sampler', '<svg aria-hidden="true"><line></line></svg><i class="slop-sampler-ring"></i>'
1261
+ + '<b class="slop-sampler-lens"><span class="slop-sampler-page"></span><i class="slop-sampler-dot"></i></b><span class="slop-sampler-hex"></span>');
1262
+ const [line, ring, big, view, label] = ['line', '.slop-sampler-ring', '.slop-sampler-lens', '.slop-sampler-page', '.slop-sampler-hex'].map((q) => lens.querySelector(q));
1263
+ Object.assign(big.style, { width: `${LENS.r * 2}px`, height: `${LENS.r * 2}px` });
1264
+ const root = getComputedStyle(document.documentElement).backgroundColor;
1265
+ const body = getComputedStyle(document.body).backgroundColor;
1266
+ view.style.background = /rgba\([^)]*,\s*0\)|transparent/.test(body) ? root : body;
1267
+ view.style.width = `${document.documentElement.clientWidth}px`;
1268
+ const copy = document.body.cloneNode(true);
1269
+ view.append(copy);
1270
+ document.body.append(lens);
1271
+ document.documentElement.classList.add('slop-sampling');
1272
+ place(document.body, copy, view);
1273
+ return {
1274
+ show(x, y, color) {
1275
+ const { r, zoom, off } = LENS;
1276
+ const cx = x + (x > innerWidth - off - r - 8 ? -off : off);
1277
+ const cy = y + (y < off + r + 8 ? off : -off);
1278
+ Object.assign(ring.style, { left: `${x}px`, top: `${y}px` });
1279
+ Object.assign(big.style, { left: `${cx}px`, top: `${cy}px`, borderColor: color ?? '#fff' });
1280
+ view.style.transform = `translate(${r - (x + scrollX) * zoom}px, ${r - (y + scrollY) * zoom}px) scale(${zoom})`;
1281
+ Object.assign(label.style, { left: `${cx}px`, top: `${cy + r + 18}px` });
1282
+ label.textContent = color ?? '';
1283
+ // the line runs from the ring to the circle's rim
1284
+ const d = Math.hypot(cx - x, cy - y);
1285
+ const ex = cx - ((cx - x) / d) * (r + 3);
1286
+ const ey = cy - ((cy - y) / d) * (r + 3);
1287
+ [['x1', x], ['y1', y], ['x2', ex], ['y2', ey]].forEach(([k, v]) => line.setAttribute(k, v));
1288
+ },
1289
+ remove() { lens.remove(); document.documentElement.classList.remove('slop-sampling'); },
1290
+ };
1291
+ }
1292
+ // the copy shows the page as it is on screen: what's fixed or sticky where it is now, panels scrolled as they are,
1293
+ // and canvases drawn
1294
+ function place(from, to, view) {
1295
+ const a = document.createTreeWalker(from, NodeFilter.SHOW_ELEMENT);
1296
+ const b = document.createTreeWalker(to, NodeFilter.SHOW_ELEMENT);
1297
+ const pinned = [];
1298
+ const scrolled = [];
1299
+ for (let x = a.currentNode, y = b.currentNode; x && y; x = a.nextNode(), y = b.nextNode()) {
1300
+ if (x.classList?.contains('slop-sampler')) break; // the magnifier itself, if it got copied
1301
+ const pos = getComputedStyle(x).position;
1302
+ if (pos === 'fixed' || pos === 'sticky') pinned.push([x, y]);
1303
+ if (x.scrollTop || x.scrollLeft) scrolled.push([x, y]);
1304
+ if (x instanceof HTMLCanvasElement && y instanceof HTMLCanvasElement) {
1305
+ try { y.getContext('2d').drawImage(x, 0, 0); } catch { /* a canvas it can't read */ }
1306
+ }
1307
+ }
1308
+ const box = view.getBoundingClientRect();
1309
+ pinned.forEach(([x, y]) => {
1310
+ const want = x.getBoundingClientRect();
1311
+ const got = y.getBoundingClientRect();
1312
+ y.style.translate = `${want.left + scrollX - (got.left - box.left)}px ${want.top + scrollY - (got.top - box.top)}px`;
1313
+ });
1314
+ scrolled.forEach(([x, y]) => { y.scrollTop = x.scrollTop; y.scrollLeft = x.scrollLeft; });
1315
+ }
1316
+ // the color on the page at a point: a letter's color over a letter, a shape's fill, an image's pixel (when the
1317
+ // browser lets it be read), or else the first background that isn't see-through
1318
+ function colorAt(x, y) {
1319
+ const els = document.elementsFromPoint(x, y);
1320
+ const top = els[0];
1321
+ if (!top) return null;
1322
+ const seen = (c) => { const m = /rgba?\([^)]*?([\d.]+)\)$/.exec(c); return c && c !== 'transparent' && !(c.startsWith('rgba') && m && +m[1] === 0); };
1323
+ if (top instanceof HTMLImageElement || top instanceof HTMLCanvasElement) {
1324
+ try {
1325
+ const r = top.getBoundingClientRect();
1326
+ const w = top.naturalWidth ?? top.width;
1327
+ const h = top.naturalHeight ?? top.height;
1328
+ const c = Object.assign(document.createElement('canvas'), { width: 1, height: 1 }).getContext('2d');
1329
+ c.drawImage(top, ((x - r.left) / r.width) * w, ((y - r.top) / r.height) * h, 1, 1, 0, 0, 1, 1);
1330
+ const [rr, g, b, a] = c.getImageData(0, 0, 1, 1).data;
1331
+ if (a) return hex(`rgb(${rr}, ${g}, ${b})`);
1332
+ } catch { /* another site's image: its pixels can't be read */ }
1333
+ }
1334
+ const caret = document.caretRangeFromPoint?.(x, y) ?? (() => { const p = document.caretPositionFromPoint?.(x, y); if (!p) return null; const r = document.createRange(); r.setStart(p.offsetNode, p.offset); return r; })();
1335
+ const node = caret?.startContainer;
1336
+ if (node?.nodeType === 3 && top.contains(node)) {
1337
+ for (const i of [caret.startOffset - 1, caret.startOffset]) {
1338
+ if (i < 0 || i >= node.length || !node.data[i].trim()) continue;
1339
+ const r = document.createRange();
1340
+ r.setStart(node, i);
1341
+ r.setEnd(node, i + 1);
1342
+ const b = r.getBoundingClientRect();
1343
+ if (x >= b.left && x <= b.right && y >= b.top && y <= b.bottom) return hex(getComputedStyle(node.parentElement).color);
1344
+ }
1345
+ }
1346
+ if (top instanceof SVGElement && seen(getComputedStyle(top).fill)) return hex(getComputedStyle(top).fill);
1347
+ for (const e of els) {
1348
+ const bg = getComputedStyle(e).backgroundColor;
1349
+ if (seen(bg)) return hex(bg);
1350
+ }
1351
+ return hex(getComputedStyle(document.documentElement).backgroundColor) || '#ffffff';
1352
+ }
1353
+
1354
+ // a category's own color, or (null) its default
1355
+ function setColor(id, color) {
1356
+ if (color) { own(id).color = color; return; }
1357
+ const c = text._categories?.[id];
1358
+ if (!c) return;
1359
+ delete c.color;
1360
+ if (!Object.keys(c).length) delete text._categories[id];
1361
+ if (!Object.keys(text._categories).length) delete text._categories;
849
1362
  }
850
1363
 
851
1364
  /* marking text: the focused field gets a row of categories. A selection, or the whole text, becomes theirs */
@@ -919,7 +1432,7 @@ const Slop = (() => {
919
1432
  render();
920
1433
  });
921
1434
  const group = keys.slice(0, -1).join('.');
922
- const listItem = !all && group && listed().has(group);
1435
+ const listItem = !all && group && listed().has(group) && isParagraph(keys.at(-1));
923
1436
  if (listItem) {
924
1437
  wrap.insert = plusRow(path, group);
925
1438
  wrap.append(wrap.insert);
@@ -1009,13 +1522,10 @@ const Slop = (() => {
1009
1522
 
1010
1523
  /* lists: where the page shows a group as a list, texts can be added and taken out */
1011
1524
  const inList = (key) => [...listed()].some((g) => g === key || g.startsWith(`${key}.`));
1012
- // a key for a new text in a group, like `like` (p3 → p<next>), and never one the group had since it was opened
1013
- function freshKey(group, like) {
1014
- const prefix = /^(.*?)\d+$/.exec(like)?.[1] || 'p';
1015
- const taken = new Set([text, saved, JSON.parse(original)].flatMap((root) => Object.keys(nodeAt(root, group) ?? {})));
1016
- let n = 1 + Math.max(0, ...[...taken].map((k) => (k.startsWith(prefix) && /^\d+$/.test(k.slice(prefix.length)) ? +k.slice(prefix.length) : 0)));
1017
- while (taken.has(`${prefix}${n}`)) n++;
1018
- return `${prefix}${n}`;
1525
+ // a key for a new paragraph in a group: the p<n> after any the group had in the file, at the last save or now
1526
+ function freshKey(group) {
1527
+ const taken = [text, saved, JSON.parse(original)].flatMap((root) => Object.keys(nodeAt(root, group) ?? {})).filter(isParagraph);
1528
+ return `p${1 + Math.max(0, ...taken.map((k) => +k.slice(1)))}`;
1019
1529
  }
1020
1530
  // a text put in a group after the key `after` (or first), the rest in the order they were
1021
1531
  function insert(group, after, key, value) {
@@ -1026,7 +1536,7 @@ const Slop = (() => {
1026
1536
  set(group, next);
1027
1537
  }
1028
1538
  function addText(group, after) {
1029
- const key = freshKey(group, after ?? textKeys(nodeAt(saved, group))[0] ?? '');
1539
+ const key = freshKey(group);
1030
1540
  withUndo('Added a paragraph', () => insert(group, after, key, ''));
1031
1541
  show('all', `${group}.${key}`);
1032
1542
  }
@@ -1084,8 +1594,8 @@ const Slop = (() => {
1084
1594
  // in the All tab, each list's removed texts until the next save, each with Restore, and a way to start an empty one
1085
1595
  function listRows(key, box) {
1086
1596
  [...listed()].filter((g) => g === key || g.startsWith(`${key}.`)).forEach((group) => {
1087
- const now = textKeys(nodeAt(text, group));
1088
- const was = textKeys(nodeAt(saved, group));
1597
+ const now = textKeys(nodeAt(text, group)).filter(isParagraph);
1598
+ const was = textKeys(nodeAt(saved, group)).filter(isParagraph);
1089
1599
  const fieldOf = (k) => [...box.querySelectorAll(':scope > .sp-field')].find((f) => f.dataset.path === `${group}.${k}`);
1090
1600
  was.forEach((k, i) => {
1091
1601
  if (now.includes(k)) return;
@@ -1108,7 +1618,7 @@ const Slop = (() => {
1108
1618
  const start = el('button', 'sp-cat-add sp-start', '+ Paragraph');
1109
1619
  start.type = 'button';
1110
1620
  start.title = `Start "${where(group)}" again`;
1111
- start.addEventListener('click', () => addText(group, null));
1621
+ start.addEventListener('click', () => addText(group, Object.keys(nodeAt(text, group) ?? {}).at(-1) ?? null)); // at the group's end
1112
1622
  box.append(start);
1113
1623
  });
1114
1624
  }
@@ -1172,6 +1682,8 @@ const Slop = (() => {
1172
1682
  $('.sp-big b').textContent = percent(page.letters ? (page.counts.ai ?? 0) / page.letters : 0);
1173
1683
  $('.sp-words').textContent = count(page.allWords, 'word');
1174
1684
  aside.querySelectorAll('.sp-seg button').forEach((b) => b.setAttribute('aria-checked', String(b.dataset.show === shows())));
1685
+ const revert = $('.sp-cat-revert');
1686
+ if (revert) revert.hidden = !Object.values(text._categories ?? {}).some((c) => c.color);
1175
1687
  aside.querySelectorAll('.sp-cat').forEach((row) => {
1176
1688
  row.querySelector('.sp-cat-pct').textContent = percent(page.letters ? (page.counts[row.dataset.id] ?? 0) / page.letters : 0);
1177
1689
  });
@@ -1362,7 +1874,9 @@ const Slop = (() => {
1362
1874
  if (stale) { status('This page is out of date: reload it to save (copy any edits first)', 'error'); return; }
1363
1875
  const body = JSON.stringify(text);
1364
1876
  if (mode === 'local') {
1365
- store.set(LOCAL, JSON.stringify({ base: JSON.parse(original).version, text: JSON.parse(body) }));
1877
+ // with the page as it was published, so the copy can be carried over to the author's next version
1878
+ const kept = store.set(LOCAL, JSON.stringify({ base: JSON.parse(original).version, baseText: JSON.parse(original), text: JSON.parse(body) }));
1879
+ if (!kept) { status("Couldn't save in this browser", 'error'); return; }
1366
1880
  saved = JSON.parse(body);
1367
1881
  undo = null;
1368
1882
  keepDraft();
@@ -1410,7 +1924,7 @@ const Slop = (() => {
1410
1924
  addEventListener('beforeunload', (e) => { if (busy || unsaved()) { e.preventDefault(); e.returnValue = ''; } });
1411
1925
  // a reload keeps what isn't saved, in this tab, still unsaved: a page in a frame (or a browser that skips the
1412
1926
  // prompt) can't ask before it goes. Kept only while the page's version is the one it was based on
1413
- const DRAFT = `slop-draft:${location.pathname}`;
1927
+ const DRAFT = `slop-draft:${pageKey()}`;
1414
1928
  const keepDraft = () => {
1415
1929
  if (unsaved() && !stale) session.set(DRAFT, JSON.stringify({ base: saved.version, text }));
1416
1930
  else session.drop(DRAFT);
@@ -1516,7 +2030,7 @@ const Slop = (() => {
1516
2030
  document.documentElement.classList.toggle('slop-editing', on);
1517
2031
  editing = on;
1518
2032
  paintShow();
1519
- if (!on) { mark(false); unreveal(); return; }
2033
+ if (!on) { mark(false); unreveal(); closePicker(); return; }
1520
2034
  place();
1521
2035
  render();
1522
2036
  };
@@ -1563,7 +2077,9 @@ const Slop = (() => {
1563
2077
  }
1564
2078
 
1565
2079
  // set things up once the page has filled in Slop.vars. Options: code (the class `code` renders with),
1566
- // edit: 'local' (an editor anyone can use, saving in their browser; under `slop-editor edit` it saves into the file)
2080
+ // edit: 'local' (an editor anyone can use, saving in their browser; under `slop-editor edit` it saves into the file),
2081
+ // key (the name the browser editor saves under, for a host that gives each version of the page an address of its
2082
+ // own; the page's path otherwise)
1567
2083
  function start(options = {}) {
1568
2084
  Object.assign(config, options);
1569
2085
  fill();
@@ -1574,12 +2090,20 @@ const Slop = (() => {
1574
2090
  [document.documentElement, document.body].forEach((x) => watch.observe(x, { attributes: true, attributeFilter: ['class', 'data-theme', 'style'] }));
1575
2091
  matchMedia('(prefers-color-scheme: dark)').addEventListener('change', theme);
1576
2092
  setMeter(store.get('slop-o-meter') !== 'off'); // on unless this reader turned it off
1577
- // the browser editor: what this visitor changed last time, if the page hasn't changed since
2093
+ // the browser editor: what this visitor changed last time. If the author has published a new version since,
2094
+ // their changes win and the visitor's stay everywhere else (a copy saved before 0.4 has no baseText, so it's dropped)
1578
2095
  const local = () => {
1579
2096
  if (options.edit !== 'local') return;
2097
+ const key = `slop-text:${pageKey()}`;
1580
2098
  try {
1581
- const saved = JSON.parse(store.get(`slop-text:${location.pathname}`));
2099
+ const saved = JSON.parse(store.get(key));
1582
2100
  if (saved?.base === text.version) { text = saved.text; applyColors(); changed(); }
2101
+ else if (saved?.baseText && saved.text) {
2102
+ text = rebase(saved.baseText, saved.text, text);
2103
+ store.set(key, JSON.stringify({ base: text.version, baseText: JSON.parse(original), text }));
2104
+ applyColors();
2105
+ changed();
2106
+ }
1583
2107
  } catch { /* nothing saved */ }
1584
2108
  ed = editor('local');
1585
2109
  };