slop-editor 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +163 -2
- package/cli.mjs +330 -0
- package/markup.mjs +93 -0
- package/package.json +55 -4
- package/react.mjs +47 -0
- package/slop.css +213 -0
- package/slop.js +1289 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Raphael Bajet
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,164 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Slop editor
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
It tracks who wrote every word on a page: the AI, you, or nobody (facts and quotes). Readers get a **Slop-o-meter** switch that colors the words by author. You get an editor where you read what your agent wrote, fix it, and sign off on what you agree with.
|
|
4
|
+
|
|
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
|
+
|
|
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
|
+
|
|
9
|
+
It's two files (`slop.js` and `slop.css`), has no dependencies and no build step, and works in any HTML page.
|
|
10
|
+
|
|
11
|
+
**[Try it on the demo page](https://baphaelman.github.io/slop-editor/)**, which is itself tracked by the slop editor.
|
|
12
|
+
|
|
13
|
+
## Install
|
|
14
|
+
|
|
15
|
+
**With Claude Code**, add the plugin, then ask for the slop editor on a page:
|
|
16
|
+
|
|
17
|
+
```
|
|
18
|
+
/plugin marketplace add baphaelman/slop-editor
|
|
19
|
+
/plugin install slop-editor@slop-editor
|
|
20
|
+
```
|
|
21
|
+
|
|
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.
|
|
23
|
+
|
|
24
|
+
**Without it**, use the command line (Node 18+):
|
|
25
|
+
|
|
26
|
+
```sh
|
|
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
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
Or link the files instead of inlining them: `<link rel="stylesheet" href="slop.css">` and `<script src="slop.js"></script>`.
|
|
36
|
+
|
|
37
|
+
## The text block
|
|
38
|
+
|
|
39
|
+
The words live in the page, in `<script type="application/json" id="slop-text">`:
|
|
40
|
+
|
|
41
|
+
```json
|
|
42
|
+
{
|
|
43
|
+
"version": 3,
|
|
44
|
+
"intro": {
|
|
45
|
+
"title": "How it works",
|
|
46
|
+
"p1": ["The agent wrote this. ", { "me": "I wrote this. " }, "Then ", { "data": "\"a quote\"" }, "."]
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
A **text** is a plain string (AI) or a list mixing strings (AI), `{"me": "..."}` (yours), `{"ok": "..."}` (the AI's, approved), `{"data": "..."}` (facts, or other people's words) and `{"<category>": "..."}` for a category of the page's own. Groups are objects, in reading order. Top-level keys starting with `_` aren't text.
|
|
52
|
+
|
|
53
|
+
**Categories.** Co-authors, editors and sources can have categories of their own, with a label and a color, in `_categories`. The same object holds colors picked for the built-in ones:
|
|
54
|
+
|
|
55
|
+
```json
|
|
56
|
+
"_categories": {
|
|
57
|
+
"bob": { "label": "Bob", "color": "#2b9fc0" },
|
|
58
|
+
"ai": { "color": "#d01f4a" }
|
|
59
|
+
}
|
|
60
|
+
```
|
|
61
|
+
|
|
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
|
+
|
|
64
|
+
In the page:
|
|
65
|
+
|
|
66
|
+
```html
|
|
67
|
+
<div data-slop-meter></div> <!-- what readers see, if anything -->
|
|
68
|
+
<h2 data-slop="intro.title"></h2> <!-- filled from the block -->
|
|
69
|
+
<p data-slop="intro.p1"></p>
|
|
70
|
+
<script>
|
|
71
|
+
Slop.vars.count = 42; // {count} in a text: a fact, shown as data
|
|
72
|
+
Slop.onChange(() => relayout()); // after an edit: redo anything built from the text (returns an unsubscribe)
|
|
73
|
+
Slop.start();
|
|
74
|
+
</script>
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
Code can render texts itself with `Slop.html('intro.p1')` (HTML) or `Slop.words('intro.p1')` (plain text). Put `data-slop-ref="intro.p1"` on the element that shows them (a button or link the page builds) and the editor can still find, highlight and scroll to it. Unlike `data-slop`, nothing fills it.
|
|
78
|
+
|
|
79
|
+
**Words the page doesn't show as words** (alt text for an image that doesn't load, a tooltip, a label for screen readers, a placeholder) go in attributes: `<img data-slop-attr="alt:hero.photo">`, or several at once, `data-slop-attr="alt:hero.photo title:hero.tip"`. They're filled as plain text. The editor gives them a tab of their own, **Hidden**, since readers' colors can't show them.
|
|
80
|
+
|
|
81
|
+
`[data-slop]` elements and meters the page adds after `Slop.start()` (a single-page app's) are filled and built as they appear. `Slop.meter(el)` builds a meter by hand.
|
|
82
|
+
|
|
83
|
+
For code that draws its own view of who wrote what: `Slop.entries()` lists every `[path, value]`; `Slop.makeup(values)` counts their letters and words by category (`{counts, letters, words, allWords}`); `Slop.categories()` gives each category's `id`, `label` and `color`, in the order the meter shows them; `Slop.percent(fraction)` rounds a share the way the meter does.
|
|
84
|
+
|
|
85
|
+
A text the page shows only some of the time (after a click, in another tab, once something's been pasted) is tagged **not on the page** in the editor. To let the editor show it while it's being edited, tell it how:
|
|
86
|
+
|
|
87
|
+
```js
|
|
88
|
+
Slop.reveal('intro.note', () => {
|
|
89
|
+
showNote = true; render(); // put the page in a state that shows it
|
|
90
|
+
return () => { showNote = false; render(); }; // and undo that afterwards
|
|
91
|
+
});
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
A group's key (`'intro'`) covers all its texts. While shown, the page's own redraws must keep it shown (here, `render()` checks `showNote`).
|
|
95
|
+
|
|
96
|
+
### In a React app
|
|
97
|
+
|
|
98
|
+
`slop-editor/react` wraps it, with no JSX and no build. slop.js still goes in the page first, as a plain `<script>`.
|
|
99
|
+
|
|
100
|
+
```jsx
|
|
101
|
+
import Slop, { SlopText, SlopMeter, slopAttrs, useSlop } from 'slop-editor/react';
|
|
102
|
+
|
|
103
|
+
<SlopMeter path="games.othello" /> // a meter (no path: the page's)
|
|
104
|
+
<SlopText path="intro.p1" as="p" /> // a text, redrawn after each edit
|
|
105
|
+
<img src="hero.png" {...slopAttrs({ alt: 'hero.photo' })} />
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
`useSlop()` makes any component render again after an edit; `SlopText` already does. Call it in a component that uses `slopAttrs` or `Slop.words`.
|
|
109
|
+
|
|
110
|
+
## The editor
|
|
111
|
+
|
|
112
|
+
`slop-editor edit page.html` serves the page's folder on 127.0.0.1 and opens the page with an **Edit text** button. Published, the page shows no sign of the editor. `Slop.start({edit: 'local'})` gives every visitor an editor that saves in their browser instead (the demo page uses it).
|
|
113
|
+
|
|
114
|
+
- **All** shows every text, grouped by section. **Slop left** shows only the texts that aren't all yours yet; work through it until it's empty. **Repeats** shows the repeated text. **Hidden** (on pages that have some) shows alt text, tooltips and labels.
|
|
115
|
+
- Each text, section and the whole page has a pie of what it's made of and a **slop** switch. Off approves the AI's words; on takes that back. Your typed words are never touched. Every switch can be undone from the status line.
|
|
116
|
+
- At the top: how much of the page is slop, and every category with its share and a color picker. Rename a category by editing its name. **+ Category** adds one; × deletes it (its words become AI-generated).
|
|
117
|
+
- Focus a text and a row of categories appears under it: **Mark all as** (or **Mark selection as**, with words selected) gives the text, or just the selection, to a category.
|
|
118
|
+
- 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.
|
|
119
|
+
- 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.
|
|
120
|
+
- 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.
|
|
121
|
+
- ⌘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.
|
|
122
|
+
|
|
123
|
+
### Repeated text
|
|
124
|
+
|
|
125
|
+
Agents repeat things: a heading that's also in the nav, a tagline in the hero and the footer. When several texts have the same words, the editor treats them as copies of one text:
|
|
126
|
+
|
|
127
|
+
- Each copy keeps its own authorship. A copy is slop until it's approved, even if it repeats your words.
|
|
128
|
+
- Each copy has a **2×** badge. In **All**, a copy's switch changes that copy only, and says so: "Only this copy changed. 1 other copy didn't. Change it too".
|
|
129
|
+
- The **Repeats** tab has one card per repeated text. Its switch and its text change every copy, and it lists where each copy is.
|
|
130
|
+
- Edit one copy on its own and the editor offers to change the others too.
|
|
131
|
+
|
|
132
|
+
## Colors
|
|
133
|
+
|
|
134
|
+
Slop is purple, approved AI text is green, data is amber, and your words keep the page's own color, until you pick others in the editor (they're saved in `_categories`). The defaults follow the page's background (light or dark). A page can also set them in CSS with `--slop-ai`, `--slop-ok`, `--slop-data` and `--slop-me`, and the editor's fonts with `--slop-font` and `--slop-mono`.
|
|
135
|
+
|
|
136
|
+
## What readers see
|
|
137
|
+
|
|
138
|
+
It's the page's choice, made in the editor (**Readers see**) and saved in the block as `"_show"`:
|
|
139
|
+
|
|
140
|
+
- **Nothing** (the default): no sign of the slop editor. The safe choice for a page or project you don't know.
|
|
141
|
+
- **Pie chart**: a pie of who wrote what, and a legend: each category in its color, with its share of the page's text.
|
|
142
|
+
- **Colors**: the Slop-o-meter, the pie and legend plus a switch that colors every word by who wrote it.
|
|
143
|
+
|
|
144
|
+
It shows where the page puts `<div data-slop-meter></div>`. While the editor is open, you see the colors whatever readers get.
|
|
145
|
+
|
|
146
|
+
A meter can cover one part of the page: `<div data-slop-meter="games.othello"></div>` measures only the texts under `games.othello`, and its switch colors only its section, the closest `[data-slop-section]` or else its parent. A section's switch starts the way the page's is and is its own once flipped. Only the page's is remembered.
|
|
147
|
+
|
|
148
|
+
Pointing at a category in a legend dims everyone else's words, in the meter's section or the whole page.
|
|
149
|
+
|
|
150
|
+
The colors apply inside `.slop-on` (on `<html>` while the page's switch is on, or a section switched on) and not inside `.slop-off` (a section switched off). Pointing at a category sets `data-slop-only="<id>"` on the section.
|
|
151
|
+
|
|
152
|
+
## Rules for agents
|
|
153
|
+
|
|
154
|
+
The full rules are in [skills/slop-editor/SKILL.md](skills/slop-editor/SKILL.md), which the Claude Code plugin loads. In short:
|
|
155
|
+
|
|
156
|
+
- Write everything as AI text to start. Only what the user dictates word for word goes in as `{"me": ...}`.
|
|
157
|
+
- Other people's words go in their category (`{"data": ...}` for quotes, or one of the page's own).
|
|
158
|
+
- Never reword the user's words without asking.
|
|
159
|
+
- Don't approve anything (`ok`) or take approval back unless asked.
|
|
160
|
+
- When editing the block by hand while the editor is open: read the file first, bump `version`, and keep every `"me"` and `"ok"` piece word for word.
|
|
161
|
+
|
|
162
|
+
## License
|
|
163
|
+
|
|
164
|
+
MIT
|
package/cli.mjs
ADDED
|
@@ -0,0 +1,330 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// The slop editor's command line. No dependencies.
|
|
3
|
+
//
|
|
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
|
|
6
|
+
// slop-editor sync <page.html …> re-inline the current slop.css and slop.js into pages that have them
|
|
7
|
+
// slop-editor edit <page.html> serve the page's folder on localhost with the editor, which saves into the file
|
|
8
|
+
// [--port 5178] [--no-open]
|
|
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)
|
|
11
|
+
import http from 'node:http';
|
|
12
|
+
import net from 'node:net';
|
|
13
|
+
import { readFile, writeFile, rename, stat } from 'node:fs/promises';
|
|
14
|
+
import { spawn, execFile } from 'node:child_process';
|
|
15
|
+
import path from 'node:path';
|
|
16
|
+
import { markup } from './markup.mjs';
|
|
17
|
+
import { fileURLToPath } from 'node:url';
|
|
18
|
+
|
|
19
|
+
const here = path.dirname(fileURLToPath(import.meta.url));
|
|
20
|
+
const STYLE = /(<style id="slop-css">)[\s\S]*?(<\/style>)/;
|
|
21
|
+
const SCRIPT = /(<script id="slop-js">)[\s\S]*?(<\/script>)/;
|
|
22
|
+
const BLOCK = /(<script type="application\/json" id="slop-text">)([\s\S]*?)(<\/script>)/;
|
|
23
|
+
|
|
24
|
+
// the format's functions, from slop.js itself (it returns only those outside a browser)
|
|
25
|
+
const Slop = new Function(`${await readFile(path.join(here, 'slop.js'), 'utf8')}\nreturn Slop;`)();
|
|
26
|
+
|
|
27
|
+
function readBlock(html, name) {
|
|
28
|
+
if (name.endsWith('.json')) return JSON.parse(html); // a block kept in a file of its own
|
|
29
|
+
const m = BLOCK.exec(html);
|
|
30
|
+
if (!m) throw new Error(`${name} has no <script type="application/json" id="slop-text"> block (run install first)`);
|
|
31
|
+
return JSON.parse(m[2]);
|
|
32
|
+
}
|
|
33
|
+
// JSON inside a <script>: "</" would end the element early
|
|
34
|
+
const serialize = (text) => '\n' + JSON.stringify(text, null, 2).replace(/<\//g, '<\\/') + '\n';
|
|
35
|
+
const inline = (s) => s.trimEnd().replace(/<\/(script|style)/gi, '<\\/$1');
|
|
36
|
+
|
|
37
|
+
/* ---------- install and sync ---------- */
|
|
38
|
+
|
|
39
|
+
async function sync(file) {
|
|
40
|
+
const css = inline(await readFile(path.join(here, 'slop.css'), 'utf8'));
|
|
41
|
+
const js = inline(await readFile(path.join(here, 'slop.js'), 'utf8'));
|
|
42
|
+
const html = await readFile(file, 'utf8');
|
|
43
|
+
if (!STYLE.test(html) || !SCRIPT.test(html)) throw new Error(`${file}: no slop-css or slop-js markers (run install first)`);
|
|
44
|
+
const next = html.replace(STYLE, (_, a, b) => `${a}\n${css}\n${b}`).replace(SCRIPT, (_, a, b) => `${a}\n${js}\n${b}`);
|
|
45
|
+
if (next !== html) await writeFile(file, next);
|
|
46
|
+
console.log(`${next === html ? 'up to date' : 'synced'}: ${path.relative(process.cwd(), file)}`);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// the styles go at the end of <head>; the block and the code just before the page's first inline script (so that
|
|
50
|
+
// script can use Slop), or at the end of <body> with a Slop.start() of their own
|
|
51
|
+
function install(html) {
|
|
52
|
+
let out = html;
|
|
53
|
+
if (!STYLE.test(out)) {
|
|
54
|
+
const tag = '<style id="slop-css"></style>\n';
|
|
55
|
+
out = /<\/head>/i.test(out) ? out.replace(/<\/head>/i, `${tag}</head>`) : tag + out;
|
|
56
|
+
}
|
|
57
|
+
if (BLOCK.test(out) && SCRIPT.test(out)) return out;
|
|
58
|
+
const parts = [];
|
|
59
|
+
if (!BLOCK.test(out)) parts.push('<script type="application/json" id="slop-text">\n{\n "version": 1\n}\n</script>');
|
|
60
|
+
if (!SCRIPT.test(out)) parts.push('<script id="slop-js"></script>');
|
|
61
|
+
const tag = parts.join('\n') + '\n';
|
|
62
|
+
const first = /<script(?![^>]*\bsrc=)(?![^>]*\bid="slop-)(?![^>]*type="application\/(?:ld\+)?json")[^>]*>/i.exec(out);
|
|
63
|
+
if (first) return out.slice(0, first.index) + tag + out.slice(first.index);
|
|
64
|
+
if (/<\/body>/i.test(out)) return out.replace(/<\/body>/i, `${tag}<script>Slop.start();</script>\n</body>`);
|
|
65
|
+
return `${out}\n${tag}<script>Slop.start();</script>\n`;
|
|
66
|
+
}
|
|
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
|
+
|
|
94
|
+
/* ---------- check ---------- */
|
|
95
|
+
|
|
96
|
+
// every text in a block: [[path, value]]
|
|
97
|
+
function textsOf(text) {
|
|
98
|
+
const entries = [];
|
|
99
|
+
const walk = (node, at) => Object.entries(node).forEach(([k, v]) => {
|
|
100
|
+
if (!at.length && (k === 'version' || k.startsWith('_'))) return; // not text
|
|
101
|
+
if (typeof v === 'string' || Array.isArray(v)) entries.push([[...at, k].join('.'), v]);
|
|
102
|
+
else if (v && typeof v === 'object') walk(v, [...at, k]);
|
|
103
|
+
});
|
|
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);
|
|
113
|
+
const paths = new Set(entries.map(([p]) => p));
|
|
114
|
+
const m = Slop.makeup(entries.map(([, v]) => v));
|
|
115
|
+
const label = labelIn(text);
|
|
116
|
+
console.log(`${path.relative(process.cwd(), file)} (version ${text.version})`);
|
|
117
|
+
console.log(` ${m.allWords.toLocaleString()} words in ${entries.length} texts`);
|
|
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(' · ')}`);
|
|
119
|
+
const left = entries.filter(([, v]) => Slop.makeup([v]).counts.ai);
|
|
120
|
+
console.log(` ${left.length} ${left.length === 1 ? 'text has' : 'texts have'} slop left`);
|
|
121
|
+
const sets = Slop.repeats(entries);
|
|
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')}`);
|
|
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
|
|
124
|
+
// string counts: Slop.html('caption' + n) builds its path, so its start isn't a text
|
|
125
|
+
const page = html.replace(SCRIPT, '').replace(STYLE, '').replace(BLOCK, ''); // the page's own markup and code
|
|
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); }));
|
|
129
|
+
const missing = [...used].filter((p) => !paths.has(p));
|
|
130
|
+
if (missing.length) console.log(` missing from the block: ${missing.join(', ')}`);
|
|
131
|
+
return missing.length ? 1 : 0;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/* ---------- edit ---------- */
|
|
135
|
+
|
|
136
|
+
const TYPES = {
|
|
137
|
+
'.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.mjs': 'text/javascript; charset=utf-8',
|
|
138
|
+
'.css': 'text/css; charset=utf-8', '.json': 'application/json', '.svg': 'image/svg+xml', '.png': 'image/png',
|
|
139
|
+
'.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.gif': 'image/gif', '.webp': 'image/webp', '.ico': 'image/x-icon',
|
|
140
|
+
'.woff2': 'font/woff2', '.mp3': 'audio/mpeg', '.wav': 'audio/wav', '.mp4': 'video/mp4', '.txt': 'text/plain; charset=utf-8',
|
|
141
|
+
};
|
|
142
|
+
|
|
143
|
+
// POST /__slop takes the whole text block. Its `version` must be the file's current one (otherwise 409: the file
|
|
144
|
+
// changed since the page loaded it), and every save bumps it. A GET answers "slop-editor": that's how the page knows
|
|
145
|
+
async function edit(file, { port, fixed, open }) {
|
|
146
|
+
const root = path.dirname(file);
|
|
147
|
+
const name = path.basename(file);
|
|
148
|
+
readBlock(await readFile(file, 'utf8'), name); // fail now, not on the first save
|
|
149
|
+
let queue = Promise.resolve(); // one save at a time
|
|
150
|
+
const save = (body) => {
|
|
151
|
+
const run = queue.then(async () => {
|
|
152
|
+
const text = JSON.parse(body);
|
|
153
|
+
if (!text || typeof text !== 'object' || Array.isArray(text) || typeof text.version !== 'number') {
|
|
154
|
+
return [400, 'expected an object with a numeric "version"'];
|
|
155
|
+
}
|
|
156
|
+
const html = await readFile(file, 'utf8');
|
|
157
|
+
const current = readBlock(html, name);
|
|
158
|
+
if (text.version !== current.version) return [409, 'the file changed since this page loaded it. Reload the page (copy any unsaved edits first)'];
|
|
159
|
+
const saved = { ...text, version: current.version + 1 };
|
|
160
|
+
const tmp = `${file}.saving`;
|
|
161
|
+
await writeFile(tmp, html.replace(BLOCK, (_, a, __, b) => a + serialize(saved) + b));
|
|
162
|
+
await rename(tmp, file);
|
|
163
|
+
return [200, String(saved.version)];
|
|
164
|
+
});
|
|
165
|
+
queue = run.catch(() => {});
|
|
166
|
+
return run;
|
|
167
|
+
};
|
|
168
|
+
const server = http.createServer(async (req, res) => {
|
|
169
|
+
const url = new URL(req.url, 'http://localhost');
|
|
170
|
+
const send = (status, body, type = 'text/plain; charset=utf-8') => {
|
|
171
|
+
res.writeHead(status, { 'content-type': type, 'cache-control': 'no-store' });
|
|
172
|
+
res.end(body);
|
|
173
|
+
};
|
|
174
|
+
if (url.pathname === '/__slop') {
|
|
175
|
+
if (req.method !== 'POST') return send(200, 'slop-editor');
|
|
176
|
+
let body = '';
|
|
177
|
+
req.on('data', (chunk) => { body += chunk; });
|
|
178
|
+
req.on('end', async () => {
|
|
179
|
+
try {
|
|
180
|
+
const [status, out] = await save(body);
|
|
181
|
+
if (status === 200) console.log(`saved version ${out}`);
|
|
182
|
+
send(status, out);
|
|
183
|
+
} catch (e) {
|
|
184
|
+
send(400, e.message);
|
|
185
|
+
}
|
|
186
|
+
});
|
|
187
|
+
return;
|
|
188
|
+
}
|
|
189
|
+
if (req.method !== 'GET' && req.method !== 'HEAD') return send(405, '');
|
|
190
|
+
const target = path.resolve(root, '.' + decodeURIComponent(url.pathname === '/' ? `/${name}` : url.pathname));
|
|
191
|
+
if (!target.startsWith(root + path.sep)) return send(403, 'outside the page\'s folder');
|
|
192
|
+
try {
|
|
193
|
+
if (!(await stat(target)).isFile()) return send(404, 'not found');
|
|
194
|
+
send(200, await readFile(target), TYPES[path.extname(target).toLowerCase()] ?? 'application/octet-stream');
|
|
195
|
+
} catch {
|
|
196
|
+
send(404, 'not found');
|
|
197
|
+
}
|
|
198
|
+
});
|
|
199
|
+
// a port that's taken: the next one, unless the port was asked for. Taken means anything answers there, on
|
|
200
|
+
// 127.0.0.1 or ::1: `localhost` can be either, and another dev server (Vite, say) may listen on ::1 only, where
|
|
201
|
+
// binding 127.0.0.1 wouldn't notice it
|
|
202
|
+
const answers = (host) => new Promise((resolve) => {
|
|
203
|
+
const socket = net.connect({ port, host });
|
|
204
|
+
const done = (yes) => { socket.destroy(); resolve(yes); };
|
|
205
|
+
socket.once('connect', () => done(true)).once('error', () => done(false)).setTimeout(500, () => done(false));
|
|
206
|
+
});
|
|
207
|
+
const first = port;
|
|
208
|
+
const taken = async () => (await answers('127.0.0.1')) || (await answers('::1'));
|
|
209
|
+
const next = async () => {
|
|
210
|
+
while (await taken()) {
|
|
211
|
+
if (fixed || port >= first + 20) {
|
|
212
|
+
console.error(`port ${port} is taken: try --port ${port + 1}`);
|
|
213
|
+
process.exit(1);
|
|
214
|
+
}
|
|
215
|
+
port++;
|
|
216
|
+
}
|
|
217
|
+
server.listen(port, '127.0.0.1');
|
|
218
|
+
};
|
|
219
|
+
server.on('error', (e) => {
|
|
220
|
+
if (e.code === 'EADDRINUSE' && !fixed && port < first + 20) { port++; next(); return; }
|
|
221
|
+
console.error(e.code === 'EADDRINUSE' ? `port ${port} is taken: try --port ${port + 1}` : e.message);
|
|
222
|
+
process.exit(1);
|
|
223
|
+
});
|
|
224
|
+
server.on('listening', () => {
|
|
225
|
+
if (port !== first) console.log(`(port ${first} is taken)`);
|
|
226
|
+
const link = `http://127.0.0.1:${port}/${encodeURIComponent(name)}`;
|
|
227
|
+
console.log(`Editing ${name}: ${link}\nThe editor saves into the file. Ctrl+C to stop.`);
|
|
228
|
+
if (!open) return;
|
|
229
|
+
const [cmd, ...rest] = process.platform === 'darwin' ? ['open'] : process.platform === 'win32' ? ['cmd', '/c', 'start', ''] : ['xdg-open'];
|
|
230
|
+
spawn(cmd, [...rest, link], { stdio: 'ignore', detached: true }).on('error', () => {}).unref();
|
|
231
|
+
});
|
|
232
|
+
await next();
|
|
233
|
+
}
|
|
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
|
+
|
|
277
|
+
/* ---------- main ---------- */
|
|
278
|
+
|
|
279
|
+
const args = process.argv.slice(2);
|
|
280
|
+
const flag = (name) => { const i = args.indexOf(name); return i >= 0 ? args.splice(i, 2)[1] : null; };
|
|
281
|
+
const portFlag = flag('--port') ?? process.env.PORT;
|
|
282
|
+
const port = Number(portFlag ?? 5178);
|
|
283
|
+
const autoFlag = args.includes('--auto') && args.splice(args.indexOf('--auto'), 1);
|
|
284
|
+
const noOpen = args.includes('--no-open') && args.splice(args.indexOf('--no-open'), 1);
|
|
285
|
+
const [cmd, ...rest] = args;
|
|
286
|
+
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>';
|
|
288
|
+
|
|
289
|
+
if (cmd !== 'help' && cmd && !files.length) {
|
|
290
|
+
console.error(usage);
|
|
291
|
+
process.exit(1);
|
|
292
|
+
}
|
|
293
|
+
try {
|
|
294
|
+
if (cmd === 'install') {
|
|
295
|
+
for (const file of files) {
|
|
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);
|
|
304
|
+
await sync(file);
|
|
305
|
+
}
|
|
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'
|
|
311
|
+
+ '(as AI text to start). Add <div data-slop-meter></div> at the top (readers see\n'
|
|
312
|
+
+ 'nothing there unless you pick a pie chart or colors in the editor). Call Slop.start() once Slop.vars is\n'
|
|
313
|
+
+ 'set and before anything reads the text. Then: slop-editor edit <page.html>');
|
|
314
|
+
} else if (cmd === 'sync') {
|
|
315
|
+
for (const file of files) await sync(file);
|
|
316
|
+
} else if (cmd === 'edit') {
|
|
317
|
+
await edit(files[0], { port, fixed: portFlag != null, open: !noOpen });
|
|
318
|
+
} else if (cmd === 'check') {
|
|
319
|
+
let status = 0;
|
|
320
|
+
for (const file of files) status |= await check(file);
|
|
321
|
+
process.exitCode = status;
|
|
322
|
+
} else if (cmd === 'history') {
|
|
323
|
+
for (const file of files) await history(file);
|
|
324
|
+
} else {
|
|
325
|
+
console.log(usage);
|
|
326
|
+
}
|
|
327
|
+
} catch (e) {
|
|
328
|
+
console.error(e.message);
|
|
329
|
+
process.exit(1);
|
|
330
|
+
}
|
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
|
+
}
|