slop-editor 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md 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>`.
@@ -57,6 +61,8 @@ A **text** is a plain string (AI) or a list mixing strings (AI), `{"me": "..."}`
57
61
 
58
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.
59
63
 
64
+ **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
+
60
66
  In the page:
61
67
 
62
68
  ```html
@@ -65,12 +71,28 @@ In the page:
65
71
  <p data-slop="intro.p1"></p>
66
72
  <script>
67
73
  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
74
+ Slop.onChange(() => relayout()); // after an edit: redo anything built from the text (returns an unsubscribe)
69
75
  Slop.start();
70
76
  </script>
71
77
  ```
72
78
 
73
- Code can render texts itself with `Slop.html('intro.p1')` (HTML) or `Slop.words('intro.p1')` (plain text).
79
+ 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
+
81
+ **Lists.** Where the page shows a group as a list of paragraphs, say so, and the editor can add and remove texts there:
82
+
83
+ ```html
84
+ <div data-slop-list="intro"> <!-- a copy of the first child for each text in "intro", in order -->
85
+ <p data-slop="intro.p1"></p>
86
+ </div>
87
+ ```
88
+
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.
90
+
91
+ **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
+
93
+ `[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.
94
+
95
+ 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
96
 
75
97
  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
98
 
@@ -83,18 +105,37 @@ Slop.reveal('intro.note', () => {
83
105
 
84
106
  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
107
 
108
+ ### In a React app
109
+
110
+ `slop-editor/react` wraps it, with no JSX and no build. slop.js still goes in the page first, as a plain `<script>`.
111
+
112
+ ```jsx
113
+ import Slop, { SlopText, SlopMeter, slopAttrs, slopList, useSlop } from 'slop-editor/react';
114
+
115
+ <SlopMeter path="games.othello" /> // a meter (no path: the page's)
116
+ <SlopText path="intro.p1" as="p" /> // a text, redrawn after each edit; as a p, li or dd, one per paragraph
117
+ <img src="hero.png" {...slopAttrs({ alt: 'hero.photo' })} />
118
+ <div {...slopList('intro')}> // a list: the editor can add and remove texts in it
119
+ {Object.keys(Slop.text.intro).map((k) => <SlopText key={k} path={`intro.${k}`} as="p" />)}
120
+ </div>
121
+ ```
122
+
123
+ `useSlop()` makes any component render again after an edit; `SlopText` already does. Call it in a component that uses `slopAttrs` or `Slop.words`.
124
+
86
125
  ## The editor
87
126
 
88
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).
89
128
 
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.
91
- - 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.
129
+ - **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
+ - Each text box shows its words in their authors' colors, as readers see them with the Slop-o-meter on.
131
+ - 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.
92
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).
93
133
  - 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
+ - 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.
94
135
  - 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.
95
136
  - Drag the header to move the editor anywhere, and drag any edge or corner to resize it. It stays where you leave it; double-click the header to put it back. On a phone it's a sheet along the bottom, and dragging changes its height.
96
- - Nothing is written until you click **Save** (or press ⌘S). The button counts the texts changed since the last save. Each changed text has a **Revert** link that takes its words and authorship back to the last save. Saves are versioned: a tab whose copy of the file is out of date gets an error instead of overwriting newer edits, and leaving with unsaved changes asks first.
97
- - ⌘Z in a text undoes typing and gives the restored words back to whoever wrote them. ⌘Z anywhere else undoes the last switch, mark or revert.
137
+ - Nothing is written until you click **Save** (or press ⌘S). The button counts the texts changed since the last save. Each changed text has a **Revert** link that takes its words and authorship back to the last save. Saves are versioned: a tab whose copy of the file is out of date gets an error instead of overwriting newer edits. Leaving with unsaved changes asks first, and a reload keeps them in that tab, still unsaved, with **Discard** (a page in a frame can't ask).
138
+ - What you type is yours, every letter, even one typed over a selection that starts with the same letter. ⌘Z in a text undoes typing and gives the restored words back to whoever wrote them. ⌘Z anywhere else undoes the last switch, mark, revert, added or removed text.
98
139
 
99
140
  ### Repeated text
100
141
 
@@ -119,6 +160,12 @@ It's the page's choice, made in the editor (**Readers see**) and saved in the bl
119
160
 
120
161
  It shows where the page puts `<div data-slop-meter></div>`. While the editor is open, you see the colors whatever readers get.
121
162
 
163
+ 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.
164
+
165
+ Pointing at a category in a legend dims everyone else's words, in the meter's section or the whole page.
166
+
167
+ 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.
168
+
122
169
  ## Rules for agents
123
170
 
124
171
  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.3.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,56 @@
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, Fragment, 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. As a p, li or dd, each paragraph after a blank line gets one of its own
28
+ export function SlopText({ path, as = 'span', vars, ...props }) {
29
+ useSlop();
30
+ const ref = { 'data-slop-ref': path };
31
+ if (!['p', 'li', 'dd'].includes(as)) return createElement(as, { ...props, ...ref, dangerouslySetInnerHTML: { __html: slop.html(path, vars) } });
32
+ const parts = slop.paragraphs(path, vars);
33
+ if (parts.length === 1) return createElement(as, { ...props, ...ref, dangerouslySetInnerHTML: { __html: parts[0] } });
34
+ const { id, ...rest } = props;
35
+ return createElement(Fragment, null, ...parts.map((h, i) => createElement(as, { ...(i ? rest : props), ...ref, key: i, dangerouslySetInnerHTML: { __html: h } })));
36
+ }
37
+
38
+ // a group the page shows as a list (paragraphs it draws one by one): the editor can add and remove texts in it.
39
+ // <div {...slopList('intro')}>{…a <SlopText as="p"> for each…}</div>
40
+ export const slopList = (path) => ({ 'data-slop-list-ref': path });
41
+
42
+ // attributes from texts, as plain text: <img {...slopAttrs({ alt: 'hero.photo' })} />. The editor lists them under
43
+ // Hidden. Call it from a component that calls useSlop(), so they follow edits
44
+ export function slopAttrs(attrs, vars) {
45
+ const pairs = Object.entries(attrs);
46
+ const out = Object.fromEntries(pairs.map(([name, path]) => [name, slop.words(path, vars)]));
47
+ out['data-slop-attr'] = pairs.map(([name, path]) => `${name}:${path}`).join(' ');
48
+ if (vars) out['data-slop-vars'] = JSON.stringify(vars);
49
+ return out;
50
+ }
51
+
52
+ // a Slop-o-meter: the page's, or with a path, a group's, whose switch colors only its section (the closest
53
+ // [data-slop-section], or its parent). slop.js builds what's inside
54
+ export function SlopMeter({ path, className, ...props }) {
55
+ return createElement('div', { ...props, className: className ? `slop-meter ${className}` : 'slop-meter', 'data-slop-meter': path ?? '' });
56
+ }
package/slop.css CHANGED
@@ -4,7 +4,7 @@
4
4
  <html> when it's dark, and writes the colors into a stylesheet of its own. --slop-font and --slop-mono set the
5
5
  editor's fonts. */
6
6
  html {
7
- --_accent: #6d35d0;
7
+ --_accent: #6d35d0; --_danger: #c8173f;
8
8
  --_font: var(--slop-font, ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif);
9
9
  --_mono: var(--slop-mono, ui-monospace, "SF Mono", Menlo, Consolas, monospace);
10
10
  /* the editor's own surface */
@@ -12,7 +12,7 @@ html {
12
12
  --_shadow: 0 1px 2px rgb(30 20 40 / 0.06), 0 18px 48px rgb(30 20 40 / 0.16);
13
13
  }
14
14
  html.slop-dark {
15
- --_accent: #b892ff;
15
+ --_accent: #b892ff; --_danger: #ff6b8a;
16
16
  --_bg: #1b1920; --_sunk: #131217; --_ink: #f1eef5; --_ink-2: #bdb7c6; --_ink-3: #8a8494; --_rule: #2f2c36;
17
17
  --_shadow: 0 1px 2px rgb(0 0 0 / 0.3), 0 18px 48px rgb(0 0 0 / 0.5);
18
18
  }
@@ -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); }
@@ -143,16 +145,49 @@ html.slop-dark {
143
145
  .sp-body > .sp-field { margin-left: 2px; }
144
146
  .sp-flash { background: color-mix(in srgb, var(--_accent) 14%, transparent); }
145
147
  .sp-flabel { display: flex; align-items: center; gap: 6px; min-height: 24px; }
146
- .sp-flabel label { min-width: 0; margin-right: auto; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: 0.76rem; font-weight: 600; color: var(--_ink-3); }
148
+ .sp-fend { display: flex; align-items: center; gap: 6px; margin-left: auto; }
149
+ .sp-flabel label { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: 0.76rem; font-weight: 600; color: var(--_ink-3); }
150
+ /* the box's own letters are see-through: the words behind it show each author's color */
151
+ .sp-ink { position: relative; }
152
+ .sp-field textarea, .sp-mirror { padding: 7px 9px; font: 0.86rem/1.5 var(--_mono); letter-spacing: normal; white-space: pre-wrap; overflow-wrap: break-word; word-break: normal; tab-size: 4; border: 1px solid transparent; border-radius: 8px; }
153
+ .sp-mirror { position: absolute; inset: 0; margin: 0; overflow: hidden; color: var(--_ink); background: var(--_sunk); pointer-events: none; }
154
+ .sp-ink:focus-within .sp-mirror { background: var(--_bg); }
147
155
  .sp-field textarea {
148
- display: block; width: 100%; margin: 0; padding: 7px 9px; resize: none; overflow: hidden;
149
- font: 0.86rem/1.5 var(--_mono); color: var(--_ink); background: var(--_sunk); border: 1px solid transparent; border-radius: 8px;
156
+ position: relative; display: block; width: 100%; margin: 0; resize: none; overflow: hidden;
157
+ color: transparent; caret-color: var(--_ink); background: transparent;
150
158
  }
159
+ .sp-field textarea::selection { color: transparent; background: color-mix(in srgb, var(--_accent) 28%, transparent); }
151
160
  .sp-field textarea:hover { border-color: var(--_rule); }
152
- .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); }
161
+ .sp-field textarea:focus { outline: none; border-color: var(--_accent); box-shadow: 0 0 0 3px color-mix(in srgb, var(--_accent) 18%, transparent); }
162
+ .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); }
163
+ .sp-kind[hidden] { display: none; }
153
164
  .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
165
  .sp-unseen:not(:disabled) { color: var(--_accent) !important; cursor: pointer; }
155
166
  .sp-unseen:not(:disabled):hover { background: color-mix(in srgb, var(--_accent) 12%, transparent); }
167
+ /* a list's removed texts, until the next save, and a way to start an emptied one */
168
+ .sp-trash { flex: none; display: inline-flex; align-items: center; gap: 4px; height: 22px; padding: 0 4px; border: 0; border-radius: 5px; background: none; font: 600 0.72rem var(--_font); color: var(--_ink-3) !important; cursor: pointer; }
169
+ .sp-trash:hover { background: var(--_sunk); color: var(--_danger) !important; }
170
+ .sp-trash:focus-visible { outline: 2px solid var(--_accent); outline-offset: 1px; }
171
+ .sp-trash[data-armed] { color: var(--_danger) !important; background: color-mix(in srgb, var(--_danger) 10%, transparent); }
172
+ .sp-removing .sp-mirror { background: color-mix(in srgb, var(--_danger) 9%, var(--_bg)); }
173
+ .sp-removing textarea { border-color: var(--_danger) !important; }
174
+ /* the + under a text in a list, on the text you're on: a hairline with a + in the middle. Pointing at it colors both
175
+ and names it */
176
+ .sp-insert {
177
+ display: flex; align-items: center; gap: 6px; width: 100%; height: 18px; margin: 1px 0 -4px; padding: 0; border: 0; background: none;
178
+ font: 600 0.72rem var(--_font); color: var(--_ink-3) !important; cursor: pointer;
179
+ opacity: 0; transition: opacity .15s; /* only on the text you're on */
180
+ }
181
+ .sp-field:hover .sp-insert, .sp-field:focus-within .sp-insert { opacity: 1; }
182
+ .sp-insert::before, .sp-insert::after { content: ""; flex: 1; height: 1px; background: var(--_rule); transition: background .15s; }
183
+ .sp-plus { display: grid; place-items: center; width: 16px; height: 16px; border: 1px solid var(--_rule); border-radius: 50%; background: var(--_bg); font-size: 0.8rem; line-height: 1; transition: border-color .15s, background .15s, color .15s; }
184
+ .sp-insert-label { max-width: 0; overflow: hidden; white-space: nowrap; opacity: 0; transition: max-width .2s, opacity .2s; }
185
+ .sp-insert:hover, .sp-insert:focus-visible { color: var(--_accent) !important; outline: none; }
186
+ .sp-insert:hover::before, .sp-insert:hover::after, .sp-insert:focus-visible::before, .sp-insert:focus-visible::after { background: var(--_accent); }
187
+ .sp-insert:hover .sp-plus, .sp-insert:focus-visible .sp-plus { border-color: var(--_accent); background: var(--_accent); color: var(--_bg); }
188
+ .sp-insert:hover .sp-insert-label, .sp-insert:focus-visible .sp-insert-label { max-width: 8em; opacity: 1; }
189
+ .sp-gone { margin: 0 2px 12px 18px; padding: 5px 9px; border: 1px dashed var(--_rule); border-radius: 8px; font-size: 0.76rem; color: var(--_ink-3); }
190
+ .sp-start { margin: 0 2px 14px 18px; }
156
191
  .sp-hint { padding: 2px 2px 0; font-size: 0.76rem; color: var(--_ink-2); }
157
192
 
158
193
  /* a pie of what the text is made of, and its slop switch */
@@ -196,11 +231,20 @@ html.slop-dark {
196
231
  .sp-goto:hover { border-color: var(--_ink-3); color: var(--_ink) !important; }
197
232
  .sp-pie.sp-mini { width: 10px; height: 10px; }
198
233
 
234
+ /* a text with no words isn't on the page, except while the editor is open */
235
+ html:not(.slop-editing) .slop-empty { display: none !important; }
236
+ .slop-editing .slop-empty { min-height: 1em; min-height: 1lh; outline: 1px dashed color-mix(in srgb, var(--_accent) 40%, transparent); outline-offset: 3px; }
237
+
199
238
  /* on the page, while the editor is open */
200
- .slop-editing [data-slop] { cursor: text; }
201
- .slop-editing [data-slop]:hover { outline: 1px dashed color-mix(in srgb, var(--_accent) 60%, transparent); outline-offset: 3px; border-radius: 2px; }
239
+ .slop-editing [data-slop], .slop-editing [data-slop-more] { cursor: text; }
240
+ .slop-editing [data-slop]:hover, .slop-editing [data-slop-more]:hover { outline: 1px dashed color-mix(in srgb, var(--_accent) 60%, transparent); outline-offset: 3px; border-radius: 2px; }
202
241
  .slop-focus { outline: 2px solid var(--_accent) !important; outline-offset: 3px; border-radius: 2px; }
203
242
  .slop-copy { outline: 2px dashed var(--_accent) !important; outline-offset: 3px; border-radius: 2px; }
243
+ /* where a new paragraph would go, and what Remove would take */
244
+ .slop-insert-after { position: relative; }
245
+ .slop-insert-after::after { content: ""; position: absolute; left: 0; right: 0; top: calc(100% + 0.5em - 1px); border-top: 2px solid var(--_accent); pointer-events: none; }
246
+ .slop-remove-hint { outline: 2px dashed var(--_danger) !important; outline-offset: 3px; border-radius: 2px; }
247
+ .slop-removing { outline: 2px dashed var(--_danger) !important; outline-offset: 3px; border-radius: 2px; background: color-mix(in srgb, var(--_danger) 12%, transparent); }
204
248
 
205
249
  @media (max-width: 900px) {
206
250
  .slop-panel { top: auto; left: 8px; right: 8px; bottom: 8px; width: auto; height: 60svh; }