slop-editor 0.3.1 → 0.5.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 +38 -9
- package/cli.mjs +233 -11
- package/jsx.mjs +248 -0
- package/markup.mjs +6 -6
- package/package.json +10 -3
- package/slop.css +48 -2
- package/slop.js +550 -30
- package/vite.mjs +89 -0
package/README.md
CHANGED
|
@@ -6,7 +6,7 @@ Every text starts as AI-generated: slop. What you type becomes yours. Switch a t
|
|
|
6
6
|
|
|
7
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
8
|
|
|
9
|
-
It's two files (`slop.js` and `slop.css`)
|
|
9
|
+
It's two files (`slop.js` and `slop.css`) with no dependencies and no build step in the page, and works in any HTML page.
|
|
10
10
|
|
|
11
11
|
**[Try it on the demo page](https://baphaelman.github.io/slop-editor/)**, which is itself tracked by the slop editor.
|
|
12
12
|
|
|
@@ -26,13 +26,16 @@ 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
|
|
29
|
+
npx slop-editor install --auto --author me page.html # the same, with the moved text marked as yours (the default is the AI's)
|
|
30
|
+
npx slop-editor install --auto src # a React app on Vite: the plugin, Slop.start(), and each component's text (see below)
|
|
31
|
+
npx slop-editor edit page.html # open the page with the editor; it saves into the file (and re-inlines the current code)
|
|
30
32
|
npx slop-editor check page.html # how much is yours, repeated text, texts the block lacks
|
|
31
33
|
npx slop-editor history page.html # what each git commit did to who wrote what (a page, or a block kept as .json)
|
|
32
34
|
npx slop-editor sync page.html # re-inline the current slop.css and slop.js
|
|
35
|
+
npx slop-editor pending # categories you asked an agent to find, in the pages under this folder
|
|
33
36
|
```
|
|
34
37
|
|
|
35
|
-
Or link the files instead of inlining them: `<link rel="stylesheet" href="slop.css">` and `<script src="slop.js"></script>`.
|
|
38
|
+
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
39
|
|
|
37
40
|
## The text block
|
|
38
41
|
|
|
@@ -59,7 +62,15 @@ A **text** is a plain string (AI) or a list mixing strings (AI), `{"me": "..."}`
|
|
|
59
62
|
}
|
|
60
63
|
```
|
|
61
64
|
|
|
62
|
-
Slop is only ever the AI's words. Other categories are other people's.
|
|
65
|
+
Slop is only ever the AI's words. Other categories are other people's.
|
|
66
|
+
|
|
67
|
+
**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.
|
|
68
|
+
|
|
69
|
+
```json
|
|
70
|
+
"bob": { "label": "Bob", "about": "My co-author: the methods section, and quotes from his thesis", "find": true }
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
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
74
|
|
|
64
75
|
**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
76
|
|
|
@@ -78,7 +89,7 @@ In the page:
|
|
|
78
89
|
|
|
79
90
|
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
91
|
|
|
81
|
-
**Lists.** Where the page shows a group's paragraphs (`p1`, `p2`, …) in one element,
|
|
92
|
+
**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
93
|
|
|
83
94
|
```html
|
|
84
95
|
<div data-slop-list="intro"> <!-- a copy of the first paragraph for each p<n> in "intro", in order -->
|
|
@@ -88,7 +99,7 @@ Code can render texts itself with `Slop.html('intro.p1')` (HTML), `Slop.paragrap
|
|
|
88
99
|
</div>
|
|
89
100
|
```
|
|
90
101
|
|
|
91
|
-
All of the group's paragraphs have to be in that element. 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.
|
|
102
|
+
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.
|
|
92
103
|
|
|
93
104
|
**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.
|
|
94
105
|
|
|
@@ -109,7 +120,25 @@ A group's key (`'intro'`) covers all its texts. While shown, the page's own redr
|
|
|
109
120
|
|
|
110
121
|
### In a React app
|
|
111
122
|
|
|
112
|
-
|
|
123
|
+
**On Vite, one command does it** (`npm i slop-editor` first):
|
|
124
|
+
|
|
125
|
+
```sh
|
|
126
|
+
npx slop-editor install --auto src/components/Article.jsx # a file, or a folder of .jsx and .tsx files
|
|
127
|
+
npx slop-editor install --auto --dry-run src # what it would do, without doing it
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
It reads each file with Babel and edits its source in place, so formatting and comments stay. It moves the prose (`p`, `h1`–`h6`, `li`, `dd`, `dt`, `figcaption`, `blockquote` holding plain words, links, bold, italic and code) into `src/slopText.json` (`--text words.json` to put it elsewhere) under the file's name (`ArticleOne.jsx` is `articleOne`), and swaps each text for `<SlopText path="…" />`. A link component (`<ExternalLink href="https://…">`) becomes `[label](url)`, and `alt`, `title`, `placeholder` and `aria-label` become `slopAttrs`, with `useSlop()` added to the component. Imports it leaves unused are dropped. It also adds the `slopEditor()` plugin to `vite.config` and `Slop.start()` to the file `index.html` loads, unless they're there. What it can't carry (words with a `<span>` or `<br>` in them, text built from variables, words in an element that isn't prose) it lists by line, for you or an agent to do by hand. As with a page, the moved text is AI text unless you say `--author me`. Running it again moves nothing twice.
|
|
131
|
+
|
|
132
|
+
The plugin, `slop-editor/vite`, is what runs the editor:
|
|
133
|
+
|
|
134
|
+
```js
|
|
135
|
+
import slopEditor from 'slop-editor/vite';
|
|
136
|
+
export default defineConfig({ plugins: [react(), slopEditor()] }); // slopEditor({ text: 'content/words.json' }) to move the file
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
It puts the words in the page as its text block, with `slop.js` and `slop.css`. Under `vite` the page gets an **Edit text** button, and saves go into the words file, version-checked: the file changes under an open page and the page reloads. A build has no editor. Other build tools aren't set up for you yet: put the block, `slop.js` and `slop.css` in the page yourself.
|
|
140
|
+
|
|
141
|
+
By hand, `slop-editor/react` wraps it, with no JSX and no build. slop.js still goes in the page first, as a plain `<script>`.
|
|
113
142
|
|
|
114
143
|
```jsx
|
|
115
144
|
import Slop, { SlopText, SlopMeter, slopAttrs, slopList, useSlop } from 'slop-editor/react';
|
|
@@ -126,12 +155,12 @@ import Slop, { SlopText, SlopMeter, slopAttrs, slopList, useSlop } from 'slop-ed
|
|
|
126
155
|
|
|
127
156
|
## The editor
|
|
128
157
|
|
|
129
|
-
`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).
|
|
158
|
+
`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'})`.
|
|
130
159
|
|
|
131
160
|
- **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.
|
|
132
161
|
- Each text box shows its words in their authors' colors, as readers see them with the Slop-o-meter on.
|
|
133
162
|
- 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.
|
|
134
|
-
- At the top: how much of the page is slop, and every category with its share
|
|
163
|
+
- 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).
|
|
135
164
|
- 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.
|
|
136
165
|
- 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.
|
|
137
166
|
- 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
|
@@ -3,17 +3,25 @@
|
|
|
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
5
|
// [--auto] also move the page's static prose (paragraphs, headings, list items) into the block
|
|
6
|
+
// [--author ai|me] whose words the moved text is: the AI's (the default) or the user's own
|
|
7
|
+
// slop-editor install <file.jsx | folder> a React app: the Vite plugin and entry, and with --auto the components' prose
|
|
8
|
+
// [--text words.json] where the words go (src/slopText.json), [--dry-run] to see what it would do
|
|
6
9
|
// slop-editor sync <page.html …> re-inline the current slop.css and slop.js into pages that have them
|
|
7
10
|
// slop-editor edit <page.html> serve the page's folder on localhost with the editor, which saves into the file
|
|
11
|
+
// (it re-inlines the current code first, and serves slop.js/slop.css to a page that links them)
|
|
8
12
|
// [--port 5178] [--no-open]
|
|
9
13
|
// slop-editor check <page.html> what the text is made of, the repeated text, and texts the page uses but the block lacks
|
|
10
14
|
// slop-editor history <page.html> what each git commit did to who wrote what (a page, or a block kept as .json)
|
|
15
|
+
// slop-editor pending [dir|page …] categories the user asked an agent to find (all pages under the folder by default)
|
|
16
|
+
// [--hook] as a Claude Code SessionStart hook's context, and nothing when there are none
|
|
11
17
|
import http from 'node:http';
|
|
12
18
|
import net from 'node:net';
|
|
13
|
-
import { readFile, writeFile, rename, stat } from 'node:fs/promises';
|
|
19
|
+
import { readFile, writeFile, rename, stat, readdir, mkdir } from 'node:fs/promises';
|
|
20
|
+
import { existsSync } from 'node:fs';
|
|
14
21
|
import { spawn, execFile } from 'node:child_process';
|
|
15
22
|
import path from 'node:path';
|
|
16
23
|
import { markup } from './markup.mjs';
|
|
24
|
+
import { textFileIn } from './vite.mjs';
|
|
17
25
|
import { fileURLToPath } from 'node:url';
|
|
18
26
|
|
|
19
27
|
const here = path.dirname(fileURLToPath(import.meta.url));
|
|
@@ -65,8 +73,12 @@ function install(html) {
|
|
|
65
73
|
return `${out}\n${tag}<script>Slop.start();</script>\n`;
|
|
66
74
|
}
|
|
67
75
|
|
|
68
|
-
//
|
|
69
|
-
|
|
76
|
+
// whose words moved text is: the AI's (a plain string) or the user's (--author me)
|
|
77
|
+
const asAuthor = (value, author) => (author === 'me' ? [{ me: value }] : value);
|
|
78
|
+
|
|
79
|
+
// --auto: the page's prose goes into the block as AI text (or the author asked for), and Slop.start() runs once the
|
|
80
|
+
// marked elements exist
|
|
81
|
+
function auto(html, author) {
|
|
70
82
|
const found = markup(html);
|
|
71
83
|
const block = readBlock(html, 'the page');
|
|
72
84
|
const { version, ...have } = block;
|
|
@@ -75,7 +87,7 @@ function auto(html) {
|
|
|
75
87
|
if (group === 'version') continue;
|
|
76
88
|
for (const [key, value] of Object.entries(texts)) {
|
|
77
89
|
if (have[group]?.[key] !== undefined) continue;
|
|
78
|
-
(have[group] ||= {})[key] = value;
|
|
90
|
+
(have[group] ||= {})[key] = asAuthor(value, author);
|
|
79
91
|
added.push(`${group}.${key}`);
|
|
80
92
|
}
|
|
81
93
|
}
|
|
@@ -91,6 +103,135 @@ function auto(html) {
|
|
|
91
103
|
return { html: out, texts: found.texts.length, skipped: found.skipped };
|
|
92
104
|
}
|
|
93
105
|
|
|
106
|
+
/* ---------- install in a React app ---------- */
|
|
107
|
+
|
|
108
|
+
// the nearest folder up from a file that has a package.json: the project
|
|
109
|
+
function projectRoot(file) {
|
|
110
|
+
for (let dir = path.dirname(file); ; dir = path.dirname(dir)) {
|
|
111
|
+
if (existsSync(path.join(dir, 'package.json'))) return dir;
|
|
112
|
+
if (dir === path.dirname(dir)) return path.dirname(file);
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
// a file's name as a key: ArticleOne.jsx -> articleOne, single-cycles.jsx -> singleCycles
|
|
116
|
+
const keyOf = (file) => path.basename(file).replace(/\.[^.]+$/, '').replace(/[^a-z0-9]+(.)?/gi, (_, c = '') => c.toUpperCase()).replace(/^./, (c) => c.toLowerCase());
|
|
117
|
+
// the index after the last import, where a new one goes
|
|
118
|
+
function afterImports(src) {
|
|
119
|
+
let end = 0;
|
|
120
|
+
for (const m of src.matchAll(/^import\b[^;]*?\bfrom\s*['"][^'"]+['"];?[ \t]*$/gm)) end = m.index + m[0].length;
|
|
121
|
+
return end;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
// what an app needs to run the editor: the plugin in vite.config, and Slop.start() in the entry. Each is skipped when it's
|
|
125
|
+
// there already. Returns what it did, and what it couldn't, for the user
|
|
126
|
+
async function setupVite(root, { text, dry }) {
|
|
127
|
+
const did = [], todo = [];
|
|
128
|
+
const edit = async (file, change, what) => {
|
|
129
|
+
const src = await readFile(file, 'utf8');
|
|
130
|
+
const next = change(src);
|
|
131
|
+
if (next === null) return false;
|
|
132
|
+
if (next !== src) {
|
|
133
|
+
if (!dry) await writeFile(file, next);
|
|
134
|
+
did.push(`${path.relative(process.cwd(), file)}: ${what}`);
|
|
135
|
+
}
|
|
136
|
+
return true;
|
|
137
|
+
};
|
|
138
|
+
const config = ['vite.config.js', 'vite.config.mjs', 'vite.config.ts', 'vite.config.mts'].map((f) => path.join(root, f)).find(existsSync);
|
|
139
|
+
if (!config) {
|
|
140
|
+
todo.push('No vite.config found, and Vite is the only setup done for you. In another build, put the text block, slop.js and slop.css in the\n page yourself (README, "Install"), and keep the text in a JSON file.');
|
|
141
|
+
return { did, todo };
|
|
142
|
+
}
|
|
143
|
+
const options = text ? `{ text: '${text}' }` : '';
|
|
144
|
+
const plugged = await edit(config, (src) => {
|
|
145
|
+
if (/slop-editor\/vite/.test(src)) return src;
|
|
146
|
+
const open = /\bplugins\s*:\s*\[/.exec(src);
|
|
147
|
+
if (!open) return null;
|
|
148
|
+
const inside = open.index + open[0].length;
|
|
149
|
+
const added = `${src.slice(0, inside)}slopEditor(${options})${/^\s*\]/.test(src.slice(inside)) ? '' : ', '}${src.slice(inside)}`;
|
|
150
|
+
const at = afterImports(added);
|
|
151
|
+
return `${added.slice(0, at)}${at ? '\n' : ''}import slopEditor from 'slop-editor/vite';${at ? '' : '\n'}${added.slice(at)}`;
|
|
152
|
+
}, 'added the slopEditor() plugin');
|
|
153
|
+
if (!plugged) todo.push(`In ${path.basename(config)}: import slopEditor from 'slop-editor/vite', and add slopEditor(${options}) to plugins.`);
|
|
154
|
+
// the entry: the module script index.html loads
|
|
155
|
+
const page = path.join(root, 'index.html');
|
|
156
|
+
const entry = existsSync(page)
|
|
157
|
+
? [...(await readFile(page, 'utf8')).matchAll(/<script\b[^>]*>/gi)].map((m) => m[0]).find((t) => /\btype=["']module["']/.test(t) && /\bsrc=/.test(t))?.match(/\bsrc=["']([^"']+)["']/)?.[1]
|
|
158
|
+
: null;
|
|
159
|
+
const entryFile = entry && path.join(root, entry.replace(/^\//, ''));
|
|
160
|
+
const started = entryFile && existsSync(entryFile) && await edit(entryFile, (src) => {
|
|
161
|
+
if (/\bSlop\.start\(/.test(src)) return src;
|
|
162
|
+
if (/slop-editor\/react/.test(src)) return null; // it imports Slop its own way: leave the call to the user
|
|
163
|
+
const at = afterImports(src);
|
|
164
|
+
return `${src.slice(0, at)}${at ? '\n' : ''}import Slop from 'slop-editor/react';\n\nSlop.start();${at ? '' : '\n'}${src.slice(at)}`;
|
|
165
|
+
}, 'Slop.start()');
|
|
166
|
+
if (!started) todo.push(`In the file your index.html loads${entry ? ` (${entry})` : ''}: import Slop from 'slop-editor/react', and call Slop.start() once, before anything renders.`);
|
|
167
|
+
return { did, todo };
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
async function installReact(files, { auto, author, text, dry }) {
|
|
171
|
+
const cwd = process.cwd();
|
|
172
|
+
const rel = (f) => path.relative(cwd, f) || f;
|
|
173
|
+
const projects = new Map(); // project folder -> its words and the files in it
|
|
174
|
+
for (const file of files) {
|
|
175
|
+
const root = projectRoot(file);
|
|
176
|
+
if (!projects.has(root)) projects.set(root, { files: [] });
|
|
177
|
+
projects.get(root).files.push(file);
|
|
178
|
+
}
|
|
179
|
+
for (const [root, project] of projects) {
|
|
180
|
+
const textRel = text ?? textFileIn(root);
|
|
181
|
+
const textFile = path.resolve(root, textRel);
|
|
182
|
+
const existed = existsSync(textFile);
|
|
183
|
+
const block = existed ? JSON.parse(await readFile(textFile, 'utf8')) : { version: 0 };
|
|
184
|
+
const names = new Set();
|
|
185
|
+
let moved = 0, changed = false;
|
|
186
|
+
const left = [];
|
|
187
|
+
const { did, todo } = await setupVite(root, { text, dry });
|
|
188
|
+
for (const file of project.files) {
|
|
189
|
+
if (!auto) break;
|
|
190
|
+
let name = keyOf(file);
|
|
191
|
+
// two files with one name (a Header in two folders): the second takes its folder's name too
|
|
192
|
+
if (names.has(name)) name = keyOf(path.dirname(file)) + name[0].toUpperCase() + name.slice(1);
|
|
193
|
+
names.add(name);
|
|
194
|
+
const { moveJsx } = await import('./jsx.mjs'); // Babel loads only here
|
|
195
|
+
let done;
|
|
196
|
+
try {
|
|
197
|
+
done = moveJsx(await readFile(file, 'utf8'), { name, ts: /\.tsx?$/i.test(file), have: block[name] });
|
|
198
|
+
} catch (e) {
|
|
199
|
+
console.error(`${rel(file)}: not read (${e.message.split('\n')[0]})`);
|
|
200
|
+
continue;
|
|
201
|
+
}
|
|
202
|
+
const count = done.texts + done.attrs;
|
|
203
|
+
for (const [group, texts] of Object.entries(done.block)) {
|
|
204
|
+
for (const [key, value] of Object.entries(texts)) (((block[name] ||= {})[group] ||= {})[key] = asAuthor(value, author));
|
|
205
|
+
}
|
|
206
|
+
if (count) {
|
|
207
|
+
if (!dry) await writeFile(file, done.code);
|
|
208
|
+
changed = true;
|
|
209
|
+
moved += count;
|
|
210
|
+
}
|
|
211
|
+
const lines = (what, list) => (list.length ? `\n ${what}: line${list.length > 1 ? 's' : ''} ${list.join(', ')}` : '');
|
|
212
|
+
console.log(`${rel(file)}: ${dry ? 'would move' : 'moved'} ${done.texts} ${done.texts === 1 ? 'text' : 'texts'}`
|
|
213
|
+
+ (done.attrs ? ` and ${done.attrs} alt texts, tooltips and the like` : '') + (count ? '' : ' (nothing to move)')
|
|
214
|
+
+ lines('prose with markup it can\'t carry, or words the code builds', done.skipped)
|
|
215
|
+
+ lines('words in elements that aren\'t prose (a span, an i, a div)', done.loose)
|
|
216
|
+
+ lines('an alt text or the like outside a component it could add a hook to', done.attrsLeft));
|
|
217
|
+
}
|
|
218
|
+
if ((changed || !existed) && !dry) {
|
|
219
|
+
block.version = existed ? (block.version ?? 0) + 1 : 1; // an editor that's open fails its next save instead of overwriting
|
|
220
|
+
await mkdir(path.dirname(textFile), { recursive: true });
|
|
221
|
+
await writeFile(textFile, JSON.stringify(block, null, 2) + '\n');
|
|
222
|
+
}
|
|
223
|
+
if (auto) console.log(`${moved ? (dry ? 'Would put' : 'Put') : 'No'} ${moved ? `${moved} texts` : 'texts'} ${moved ? 'in' : 'moved into'} ${rel(textFile)}${moved ? ` as ${author === 'me' ? 'yours (me)' : 'AI text'}` : ''}`);
|
|
224
|
+
for (const line of did) console.log(`${dry ? 'would change ' : ''}${line}`);
|
|
225
|
+
const pkg = await readFile(path.join(root, 'package.json'), 'utf8').then(JSON.parse, () => ({}));
|
|
226
|
+
if (!{ ...pkg.dependencies, ...pkg.devDependencies }['slop-editor']) todo.push('Add the package to the project: npm i slop-editor');
|
|
227
|
+
if (todo.length) console.log(`\nStill to do:\n${todo.map((t) => ` - ${t}`).join('\n')}`);
|
|
228
|
+
}
|
|
229
|
+
console.log('\nNext: run your dev server. The page gets an Edit text button, and saves go into the words file.\n'
|
|
230
|
+
+ 'Readers see nothing until you pick what they see in the editor ("Readers see"); put <SlopMeter /> (from \'slop-editor/react\')\n'
|
|
231
|
+
+ 'where the meter should go. Texts the code builds (a title from a variable, text in a data array) are still yours to move:\n'
|
|
232
|
+
+ 'render them with <SlopText path="…" /> or Slop.words(\'…\'). Adding and removing paragraphs in the editor needs slopList.');
|
|
233
|
+
}
|
|
234
|
+
|
|
94
235
|
/* ---------- check ---------- */
|
|
95
236
|
|
|
96
237
|
// every text in a block: [[path, value]]
|
|
@@ -128,9 +269,51 @@ async function check(file) {
|
|
|
128
269
|
[...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
270
|
const missing = [...used].filter((p) => !paths.has(p));
|
|
130
271
|
if (missing.length) console.log(` missing from the block: ${missing.join(', ')}`);
|
|
272
|
+
const asked = waiting(text);
|
|
273
|
+
if (asked.length) console.log(` waiting for an agent to find: ${asked.map((c) => c.label).join(', ')}`);
|
|
131
274
|
return missing.length ? 1 : 0;
|
|
132
275
|
}
|
|
133
276
|
|
|
277
|
+
/* ---------- categories to find ---------- */
|
|
278
|
+
|
|
279
|
+
// a category of the page's own can ask an agent to find its words: {"about": "whose words they are", "find": true}
|
|
280
|
+
const waiting = (text) => Object.entries(text?._categories ?? {}).filter(([, c]) => c?.find).map(([id, c]) => ({ id, label: c.label || id, about: c.about ?? '' }));
|
|
281
|
+
const SKIP = new Set(['node_modules', 'dist', 'build', 'out', 'coverage', 'vendor']);
|
|
282
|
+
async function pagesIn(dir, found = [], depth = 0, pattern = /\.(html?|json)$/i) {
|
|
283
|
+
if (depth > 8 || found.length > 5000) return found;
|
|
284
|
+
for (const d of await readdir(dir, { withFileTypes: true })) {
|
|
285
|
+
if (d.name.startsWith('.') || SKIP.has(d.name)) continue;
|
|
286
|
+
const p = path.join(dir, d.name);
|
|
287
|
+
if (d.isDirectory()) await pagesIn(p, found, depth + 1, pattern);
|
|
288
|
+
else if (pattern.test(d.name)) found.push(p);
|
|
289
|
+
}
|
|
290
|
+
return found;
|
|
291
|
+
}
|
|
292
|
+
async function pending(targets, hook) {
|
|
293
|
+
const files = [];
|
|
294
|
+
for (const t of targets) files.push(...((await stat(t)).isDirectory() ? await pagesIn(t) : [t]));
|
|
295
|
+
const asked = [];
|
|
296
|
+
for (const file of files) {
|
|
297
|
+
try {
|
|
298
|
+
if ((await stat(file)).size > 5e6) continue;
|
|
299
|
+
const s = await readFile(file, 'utf8');
|
|
300
|
+
if (!s.includes('"find"')) continue;
|
|
301
|
+
const text = readBlock(s, file);
|
|
302
|
+
if (typeof text?.version !== 'number') continue;
|
|
303
|
+
waiting(text).forEach((c) => asked.push({ file: path.relative(process.cwd(), file) || file, ...c }));
|
|
304
|
+
} catch { /* not a page with a block */ }
|
|
305
|
+
}
|
|
306
|
+
const lines = asked.map((c) => `- ${c.file}: "${c.label}" (id \`${c.id}\`)${c.about ? `: ${c.about}` : ''}`);
|
|
307
|
+
if (hook) {
|
|
308
|
+
if (!asked.length) return;
|
|
309
|
+
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`
|
|
310
|
+
+ '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.';
|
|
311
|
+
console.log(JSON.stringify({ hookSpecificOutput: { hookEventName: 'SessionStart', additionalContext: context } }));
|
|
312
|
+
return;
|
|
313
|
+
}
|
|
314
|
+
console.log(asked.length ? `Waiting for an agent to find:\n${lines.join('\n')}` : 'No categories are waiting for an agent.');
|
|
315
|
+
}
|
|
316
|
+
|
|
134
317
|
/* ---------- edit ---------- */
|
|
135
318
|
|
|
136
319
|
const TYPES = {
|
|
@@ -145,7 +328,12 @@ const TYPES = {
|
|
|
145
328
|
async function edit(file, { port, fixed, open }) {
|
|
146
329
|
const root = path.dirname(file);
|
|
147
330
|
const name = path.basename(file);
|
|
148
|
-
|
|
331
|
+
const html = await readFile(file, 'utf8');
|
|
332
|
+
readBlock(html, name); // fail now, not on the first save
|
|
333
|
+
// a page that inlines the code gets this version's, so a page on its own stays current
|
|
334
|
+
if (!name.endsWith('.json') && STYLE.test(html) && SCRIPT.test(html)) await sync(file);
|
|
335
|
+
const asked = waiting(readBlock(html, name));
|
|
336
|
+
if (asked.length) console.log(`Waiting for an agent to find: ${asked.map((c) => c.label).join(', ')}`);
|
|
149
337
|
let queue = Promise.resolve(); // one save at a time
|
|
150
338
|
const save = (body) => {
|
|
151
339
|
const run = queue.then(async () => {
|
|
@@ -172,6 +360,10 @@ async function edit(file, { port, fixed, open }) {
|
|
|
172
360
|
res.end(body);
|
|
173
361
|
};
|
|
174
362
|
if (url.pathname === '/__slop') {
|
|
363
|
+
// only the page being edited: another page in its folder would save its own block into this file
|
|
364
|
+
let from = '/';
|
|
365
|
+
try { from = decodeURIComponent(new URL(req.headers.referer).pathname); } catch { /* no referer: curl, say */ }
|
|
366
|
+
if (from !== '/' && from !== `/${name}`) return req.method === 'POST' ? send(403, `this server edits ${name}`) : send(200, 'another page');
|
|
175
367
|
if (req.method !== 'POST') return send(200, 'slop-editor');
|
|
176
368
|
let body = '';
|
|
177
369
|
req.on('data', (chunk) => { body += chunk; });
|
|
@@ -193,6 +385,9 @@ async function edit(file, { port, fixed, open }) {
|
|
|
193
385
|
if (!(await stat(target)).isFile()) return send(404, 'not found');
|
|
194
386
|
send(200, await readFile(target), TYPES[path.extname(target).toLowerCase()] ?? 'application/octet-stream');
|
|
195
387
|
} catch {
|
|
388
|
+
// a page that links slop.js and slop.css from elsewhere (a site's build serves them) gets this version's
|
|
389
|
+
const own = path.basename(url.pathname);
|
|
390
|
+
if (own === 'slop.js' || own === 'slop.css') return send(200, await readFile(path.join(here, own)), TYPES[path.extname(own)]);
|
|
196
391
|
send(404, 'not found');
|
|
197
392
|
}
|
|
198
393
|
});
|
|
@@ -281,36 +476,57 @@ const flag = (name) => { const i = args.indexOf(name); return i >= 0 ? args.spli
|
|
|
281
476
|
const portFlag = flag('--port') ?? process.env.PORT;
|
|
282
477
|
const port = Number(portFlag ?? 5178);
|
|
283
478
|
const autoFlag = args.includes('--auto') && args.splice(args.indexOf('--auto'), 1);
|
|
479
|
+
const dryRun = args.includes('--dry-run') && args.splice(args.indexOf('--dry-run'), 1);
|
|
480
|
+
const authorFlag = flag('--author');
|
|
481
|
+
const textFlag = flag('--text');
|
|
284
482
|
const noOpen = args.includes('--no-open') && args.splice(args.indexOf('--no-open'), 1);
|
|
483
|
+
const hookFlag = args.includes('--hook') && args.splice(args.indexOf('--hook'), 1);
|
|
285
484
|
const [cmd, ...rest] = args;
|
|
286
485
|
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>';
|
|
486
|
+
const usage = 'usage: slop-editor install <page.html | file.jsx | folder> [--auto] [--author ai|me] [--text words.json] [--dry-run] | sync <page.html …> | edit <page.html> [--port N] [--no-open] | check <page.html …> | history <page.html> | pending [dir|page …] [--hook]';
|
|
288
487
|
|
|
289
|
-
if (cmd !== 'help' && cmd && !files.length) {
|
|
488
|
+
if (cmd !== 'help' && cmd !== 'pending' && cmd && !files.length) {
|
|
290
489
|
console.error(usage);
|
|
291
490
|
process.exit(1);
|
|
292
491
|
}
|
|
293
492
|
try {
|
|
493
|
+
if (['sync', 'edit', 'check', 'history'].includes(cmd)) {
|
|
494
|
+
for (const file of files) {
|
|
495
|
+
if ((await stat(file)).isDirectory()) throw new Error(`${path.relative(process.cwd(), file) || file} is a folder. ${cmd} takes a page: slop-editor ${cmd} <folder>/<page>.html`);
|
|
496
|
+
}
|
|
497
|
+
}
|
|
294
498
|
if (cmd === 'install') {
|
|
499
|
+
const author = authorFlag ?? 'ai';
|
|
500
|
+
if (!['ai', 'me'].includes(author)) throw new Error(`--author takes ai (the default) or me, not ${author}`);
|
|
501
|
+
if (authorFlag && !autoFlag) throw new Error('--author goes with --auto: it says whose words the moved text is');
|
|
502
|
+
const pages = [], sources = [];
|
|
295
503
|
for (const file of files) {
|
|
504
|
+
if ((await stat(file)).isDirectory()) sources.push(...await pagesIn(file, [], 0, /\.(?:jsx|tsx)$/i));
|
|
505
|
+
else if (/\.html?$/i.test(file)) pages.push(file);
|
|
506
|
+
else if (/\.(?:jsx|tsx|js|mjs|ts)$/i.test(file)) sources.push(file);
|
|
507
|
+
else throw new Error(`${path.relative(process.cwd(), file)}: install takes a page (.html), a React file (.jsx, .tsx) or a folder of them. Vue, Svelte and the like aren't read yet`);
|
|
508
|
+
}
|
|
509
|
+
if (!pages.length && !sources.length) throw new Error('no .jsx or .tsx files in there');
|
|
510
|
+
for (const file of pages) {
|
|
296
511
|
let html = install(await readFile(file, 'utf8'));
|
|
297
512
|
if (autoFlag) {
|
|
298
|
-
const done = auto(html);
|
|
513
|
+
const done = auto(html, author);
|
|
299
514
|
html = done.html;
|
|
300
|
-
console.log(`${path.relative(process.cwd(), file)}: moved ${done.texts} texts into the block`
|
|
515
|
+
console.log(`${path.relative(process.cwd(), file)}: moved ${done.texts} texts into the block${author === 'me' ? ' as yours' : ''}`
|
|
301
516
|
+ (done.skipped ? `; ${done.skipped} more have markup it can't carry (spans, line breaks, icons): do those by hand` : ''));
|
|
302
517
|
}
|
|
303
518
|
await writeFile(file, html);
|
|
304
519
|
await sync(file);
|
|
305
520
|
}
|
|
306
|
-
if (autoFlag) {
|
|
521
|
+
if (pages.length && autoFlag) {
|
|
307
522
|
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
523
|
+ 'sometimes (Slop.reveal), and anything that reads an element\'s text before Slop.start() or after an edit (Slop.onChange).\n'
|
|
309
524
|
+ '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'
|
|
525
|
+
} else if (pages.length) console.log('\nNext: mark text elements with data-slop="group.key" and put their words in the slop-text block\n'
|
|
311
526
|
+ '(as AI text to start). Add <div data-slop-meter></div> at the top (readers see\n'
|
|
312
527
|
+ 'nothing there unless you pick a pie chart or colors in the editor). Call Slop.start() once Slop.vars is\n'
|
|
313
528
|
+ 'set and before anything reads the text. Then: slop-editor edit <page.html>');
|
|
529
|
+
if (sources.length) await installReact(sources, { auto: autoFlag, author, text: textFlag, dry: dryRun });
|
|
314
530
|
} else if (cmd === 'sync') {
|
|
315
531
|
for (const file of files) await sync(file);
|
|
316
532
|
} else if (cmd === 'edit') {
|
|
@@ -321,6 +537,12 @@ try {
|
|
|
321
537
|
process.exitCode = status;
|
|
322
538
|
} else if (cmd === 'history') {
|
|
323
539
|
for (const file of files) await history(file);
|
|
540
|
+
} else if (cmd === 'pending') {
|
|
541
|
+
try {
|
|
542
|
+
await pending(files.length ? files : [process.cwd()], hookFlag);
|
|
543
|
+
} catch (e) {
|
|
544
|
+
if (!hookFlag) throw e; // a session's start never fails on this
|
|
545
|
+
}
|
|
324
546
|
} else {
|
|
325
547
|
console.log(usage);
|
|
326
548
|
}
|