slop-editor 0.4.0 → 0.5.1
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 +28 -7
- package/cli.mjs +170 -12
- package/jsx.mjs +248 -0
- package/markup.mjs +6 -6
- package/package.json +10 -3
- package/slop.css +12 -6
- package/slop.js +58 -15
- 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,6 +26,8 @@ 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 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)
|
|
29
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)
|
|
@@ -118,7 +120,25 @@ A group's key (`'intro'`) covers all its texts. While shown, the page's own redr
|
|
|
118
120
|
|
|
119
121
|
### In a React app
|
|
120
122
|
|
|
121
|
-
|
|
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>`.
|
|
122
142
|
|
|
123
143
|
```jsx
|
|
124
144
|
import Slop, { SlopText, SlopMeter, slopAttrs, slopList, useSlop } from 'slop-editor/react';
|
|
@@ -137,11 +157,12 @@ import Slop, { SlopText, SlopMeter, slopAttrs, slopList, useSlop } from 'slop-ed
|
|
|
137
157
|
|
|
138
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'})`.
|
|
139
159
|
|
|
140
|
-
- **All** shows every text, grouped by section. **Slop left** shows only the texts that aren't all yours yet; work through it until it's empty. **Repeats** shows the repeated text. **Hidden** (on pages that have some) shows alt text, tooltips and labels.
|
|
160
|
+
- **All** shows every text, grouped by section. An open section's name stays at the top while you scroll its texts, so you can close it from anywhere in it. **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.
|
|
141
161
|
- Each text box shows its words in their authors' colors, as readers see them with the Slop-o-meter on.
|
|
142
|
-
- Each text
|
|
143
|
-
- At the top:
|
|
144
|
-
- Focus a text and a row of categories appears under it: **Mark all as** (or **Mark selection as**,
|
|
162
|
+
- Each text and section 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.
|
|
163
|
+
- At the top: every category with its share of the page, 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).
|
|
164
|
+
- Focus a text and a row of categories appears under it: **Mark all as** (or **Mark selection as**, as soon as you start selecting) gives the text, or just the selection, to a category.
|
|
165
|
+
- Words copied (or cut) from a text keep their authors when pasted into a text: AI words stay AI, approved stay approved. Words pasted from anywhere else are yours, as if typed.
|
|
145
166
|
- 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.
|
|
146
167
|
- 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.
|
|
147
168
|
- 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.
|
|
@@ -169,7 +190,7 @@ It's the page's choice, made in the editor (**Readers see**) and saved in the bl
|
|
|
169
190
|
- **Pie chart**: a pie of who wrote what, and a legend: each category in its color, with its share of the page's text.
|
|
170
191
|
- **Colors**: the Slop-o-meter, the pie and legend plus a switch that colors every word by who wrote it.
|
|
171
192
|
|
|
172
|
-
It shows where the page puts `<div data-slop-meter></div>`. While the editor is open, you see the colors whatever readers get.
|
|
193
|
+
It shows where the page puts `<div data-slop-meter></div>`. While the editor is open, you see the colors whatever readers get; its **Colors** switch (or the page's Slop-o-meter) turns them off to compare.
|
|
173
194
|
|
|
174
195
|
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.
|
|
175
196
|
|
package/cli.mjs
CHANGED
|
@@ -3,6 +3,9 @@
|
|
|
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
|
|
8
11
|
// (it re-inlines the current code first, and serves slop.js/slop.css to a page that links them)
|
|
@@ -13,10 +16,12 @@
|
|
|
13
16
|
// [--hook] as a Claude Code SessionStart hook's context, and nothing when there are none
|
|
14
17
|
import http from 'node:http';
|
|
15
18
|
import net from 'node:net';
|
|
16
|
-
import { readFile, writeFile, rename, stat, readdir } from 'node:fs/promises';
|
|
19
|
+
import { readFile, writeFile, rename, stat, readdir, mkdir } from 'node:fs/promises';
|
|
20
|
+
import { existsSync } from 'node:fs';
|
|
17
21
|
import { spawn, execFile } from 'node:child_process';
|
|
18
22
|
import path from 'node:path';
|
|
19
23
|
import { markup } from './markup.mjs';
|
|
24
|
+
import { textFileIn } from './vite.mjs';
|
|
20
25
|
import { fileURLToPath } from 'node:url';
|
|
21
26
|
|
|
22
27
|
const here = path.dirname(fileURLToPath(import.meta.url));
|
|
@@ -68,8 +73,12 @@ function install(html) {
|
|
|
68
73
|
return `${out}\n${tag}<script>Slop.start();</script>\n`;
|
|
69
74
|
}
|
|
70
75
|
|
|
71
|
-
//
|
|
72
|
-
|
|
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) {
|
|
73
82
|
const found = markup(html);
|
|
74
83
|
const block = readBlock(html, 'the page');
|
|
75
84
|
const { version, ...have } = block;
|
|
@@ -78,7 +87,7 @@ function auto(html) {
|
|
|
78
87
|
if (group === 'version') continue;
|
|
79
88
|
for (const [key, value] of Object.entries(texts)) {
|
|
80
89
|
if (have[group]?.[key] !== undefined) continue;
|
|
81
|
-
(have[group] ||= {})[key] = value;
|
|
90
|
+
(have[group] ||= {})[key] = asAuthor(value, author);
|
|
82
91
|
added.push(`${group}.${key}`);
|
|
83
92
|
}
|
|
84
93
|
}
|
|
@@ -94,6 +103,135 @@ function auto(html) {
|
|
|
94
103
|
return { html: out, texts: found.texts.length, skipped: found.skipped };
|
|
95
104
|
}
|
|
96
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
|
+
|
|
97
235
|
/* ---------- check ---------- */
|
|
98
236
|
|
|
99
237
|
// every text in a block: [[path, value]]
|
|
@@ -141,13 +279,13 @@ async function check(file) {
|
|
|
141
279
|
// a category of the page's own can ask an agent to find its words: {"about": "whose words they are", "find": true}
|
|
142
280
|
const waiting = (text) => Object.entries(text?._categories ?? {}).filter(([, c]) => c?.find).map(([id, c]) => ({ id, label: c.label || id, about: c.about ?? '' }));
|
|
143
281
|
const SKIP = new Set(['node_modules', 'dist', 'build', 'out', 'coverage', 'vendor']);
|
|
144
|
-
async function pagesIn(dir, found = [], depth = 0) {
|
|
282
|
+
async function pagesIn(dir, found = [], depth = 0, pattern = /\.(html?|json)$/i) {
|
|
145
283
|
if (depth > 8 || found.length > 5000) return found;
|
|
146
284
|
for (const d of await readdir(dir, { withFileTypes: true })) {
|
|
147
285
|
if (d.name.startsWith('.') || SKIP.has(d.name)) continue;
|
|
148
286
|
const p = path.join(dir, d.name);
|
|
149
|
-
if (d.isDirectory()) await pagesIn(p, found, depth + 1);
|
|
150
|
-
else if (
|
|
287
|
+
if (d.isDirectory()) await pagesIn(p, found, depth + 1, pattern);
|
|
288
|
+
else if (pattern.test(d.name)) found.push(p);
|
|
151
289
|
}
|
|
152
290
|
return found;
|
|
153
291
|
}
|
|
@@ -338,37 +476,57 @@ const flag = (name) => { const i = args.indexOf(name); return i >= 0 ? args.spli
|
|
|
338
476
|
const portFlag = flag('--port') ?? process.env.PORT;
|
|
339
477
|
const port = Number(portFlag ?? 5178);
|
|
340
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');
|
|
341
482
|
const noOpen = args.includes('--no-open') && args.splice(args.indexOf('--no-open'), 1);
|
|
342
483
|
const hookFlag = args.includes('--hook') && args.splice(args.indexOf('--hook'), 1);
|
|
343
484
|
const [cmd, ...rest] = args;
|
|
344
485
|
const files = rest.map((f) => path.resolve(f));
|
|
345
|
-
const usage = 'usage: slop-editor install <page.html> [--auto] | sync <page.html …> | edit <page.html> [--port N] [--no-open] | check <page.html …> | history <page.html> | pending [dir|page …] [--hook]';
|
|
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]';
|
|
346
487
|
|
|
347
488
|
if (cmd !== 'help' && cmd !== 'pending' && cmd && !files.length) {
|
|
348
489
|
console.error(usage);
|
|
349
490
|
process.exit(1);
|
|
350
491
|
}
|
|
351
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
|
+
}
|
|
352
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 = [];
|
|
353
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) {
|
|
354
511
|
let html = install(await readFile(file, 'utf8'));
|
|
355
512
|
if (autoFlag) {
|
|
356
|
-
const done = auto(html);
|
|
513
|
+
const done = auto(html, author);
|
|
357
514
|
html = done.html;
|
|
358
|
-
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' : ''}`
|
|
359
516
|
+ (done.skipped ? `; ${done.skipped} more have markup it can't carry (spans, line breaks, icons): do those by hand` : ''));
|
|
360
517
|
}
|
|
361
518
|
await writeFile(file, html);
|
|
362
519
|
await sync(file);
|
|
363
520
|
}
|
|
364
|
-
if (autoFlag) {
|
|
521
|
+
if (pages.length && autoFlag) {
|
|
365
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'
|
|
366
523
|
+ 'sometimes (Slop.reveal), and anything that reads an element\'s text before Slop.start() or after an edit (Slop.onChange).\n'
|
|
367
524
|
+ 'Then: slop-editor check <page.html>, and slop-editor edit <page.html>');
|
|
368
|
-
} 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'
|
|
369
526
|
+ '(as AI text to start). Add <div data-slop-meter></div> at the top (readers see\n'
|
|
370
527
|
+ 'nothing there unless you pick a pie chart or colors in the editor). Call Slop.start() once Slop.vars is\n'
|
|
371
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 });
|
|
372
530
|
} else if (cmd === 'sync') {
|
|
373
531
|
for (const file of files) await sync(file);
|
|
374
532
|
} else if (cmd === 'edit') {
|
package/jsx.mjs
ADDED
|
@@ -0,0 +1,248 @@
|
|
|
1
|
+
// `slop-editor install --auto Foo.jsx`: markup.mjs for React. It moves a component file's static prose into the text
|
|
2
|
+
// block and swaps each text for <SlopText path="…" />, and alt text and the like for slopAttrs. It reads the file with
|
|
3
|
+
// Babel but changes the source in place, so formatting, comments and everything else stay as they were. The cli loads
|
|
4
|
+
// this file only for a React file, so nothing else pays for the parser.
|
|
5
|
+
import { parse } from '@babel/parser';
|
|
6
|
+
import { PROSE, MIN_WORDS, escape, slug, words } from './markup.mjs';
|
|
7
|
+
|
|
8
|
+
const PROSE_TAG = new RegExp(`^(?:${PROSE})$`);
|
|
9
|
+
// elements that hold other prose: look inside them instead of taking them whole
|
|
10
|
+
const CONTAINER_TAG = /^(?:p|ul|ol|li|div|section|article|aside|table|blockquote|details|figure|dl|dd|dt|header|footer|main|h[1-6])$/;
|
|
11
|
+
const MARKS = { b: '**', strong: '**', i: '*', em: '*', code: '`' };
|
|
12
|
+
// a component that is a link: <ExternalLink href="https://…">words</ExternalLink>
|
|
13
|
+
const LINK_COMPONENT = /(?:Link|Anchor)$/;
|
|
14
|
+
// attributes whose words the editor lists under Hidden, and the group each goes in
|
|
15
|
+
const ATTRS = { alt: 'alt-text', title: 'tooltips', placeholder: 'placeholders', 'aria-label': 'labels' };
|
|
16
|
+
const MARKED = ['data-slop', 'data-slop-ref', 'data-slop-attr'];
|
|
17
|
+
const TAKEN_PROPS = ['as', 'path', 'vars'];
|
|
18
|
+
|
|
19
|
+
// JSX's own rule for the whitespace in a text: lines are trimmed, blank ones dropped, the rest joined with a space
|
|
20
|
+
function jsxText(value) {
|
|
21
|
+
const lines = value.split(/\r\n|\n|\r/);
|
|
22
|
+
let last = 0;
|
|
23
|
+
lines.forEach((l, i) => { if (/[^ \t]/.test(l)) last = i; });
|
|
24
|
+
let out = '';
|
|
25
|
+
lines.forEach((line, i) => {
|
|
26
|
+
let t = line.replace(/\t/g, ' ');
|
|
27
|
+
if (i !== 0) t = t.replace(/^ +/, '');
|
|
28
|
+
if (i !== lines.length - 1) t = t.replace(/ +$/, '');
|
|
29
|
+
if (t) out += i === last ? t : `${t} `;
|
|
30
|
+
});
|
|
31
|
+
return out;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
const tagOf = (el) => (el.openingElement.name.type === 'JSXIdentifier' ? el.openingElement.name.name : null);
|
|
35
|
+
const propOf = (el, name) => el.openingElement.attributes.find((a) => a.type === 'JSXAttribute' && a.name.name === name);
|
|
36
|
+
const stringOf = (attr) => {
|
|
37
|
+
const v = attr?.value;
|
|
38
|
+
if (v?.type === 'StringLiteral') return v.value;
|
|
39
|
+
if (v?.type === 'JSXExpressionContainer') {
|
|
40
|
+
if (v.expression.type === 'StringLiteral') return v.expression.value;
|
|
41
|
+
if (v.expression.type === 'TemplateLiteral' && !v.expression.expressions.length) return v.expression.quasis[0].value.cooked;
|
|
42
|
+
}
|
|
43
|
+
return null;
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
// is there anything in it that reads as words, or that code builds? That's what's worth telling the user about
|
|
47
|
+
const hasWords = (el) => el.children.some((c) => (c.type === 'JSXText' && /\S/.test(c.value))
|
|
48
|
+
|| (c.type === 'JSXExpressionContainer' && c.expression.type !== 'JSXEmptyExpression') || (c.type === 'JSXElement' && hasWords(c)));
|
|
49
|
+
|
|
50
|
+
// JSX children -> the format's inline markup and the plain words, or null if they hold anything it can't say
|
|
51
|
+
function convert(children) {
|
|
52
|
+
let md = '', plain = '';
|
|
53
|
+
for (const c of children) {
|
|
54
|
+
let text = null;
|
|
55
|
+
if (c.type === 'JSXText') text = jsxText(c.value);
|
|
56
|
+
else if (c.type === 'JSXExpressionContainer') {
|
|
57
|
+
if (c.expression.type === 'JSXEmptyExpression') continue; // {/* a comment */}
|
|
58
|
+
if (c.expression.type === 'StringLiteral') text = c.expression.value;
|
|
59
|
+
else if (c.expression.type === 'TemplateLiteral' && !c.expression.expressions.length) text = c.expression.quasis[0].value.cooked;
|
|
60
|
+
else return null;
|
|
61
|
+
} else if (c.type === 'JSXElement') {
|
|
62
|
+
const tag = tagOf(c);
|
|
63
|
+
const attrs = c.openingElement.attributes;
|
|
64
|
+
if (!tag || attrs.some((a) => a.type !== 'JSXAttribute' || typeof a.name.name !== 'string')) return null;
|
|
65
|
+
let href = null, inner = c.children, mark;
|
|
66
|
+
if (tag === 'a') {
|
|
67
|
+
href = stringOf(propOf(c, 'href'));
|
|
68
|
+
// an <a> keeps its href and may say where it opens; any other attribute would be lost
|
|
69
|
+
if (!href || attrs.some((a) => !['href', 'target', 'rel'].includes(a.name.name))) return null;
|
|
70
|
+
} else if (LINK_COMPONENT.test(tag)) {
|
|
71
|
+
href = stringOf(propOf(c, 'href'));
|
|
72
|
+
const kid = propOf(c, 'children');
|
|
73
|
+
if (!/^https?:\/\//.test(href ?? '') || attrs.some((a) => !['href', 'children'].includes(a.name.name))) return null;
|
|
74
|
+
if (kid) {
|
|
75
|
+
const label = stringOf(kid);
|
|
76
|
+
if (label === null || inner.length) return null;
|
|
77
|
+
inner = [{ type: 'JSXText', value: label }];
|
|
78
|
+
}
|
|
79
|
+
} else if (MARKS[tag] && !attrs.length) mark = MARKS[tag];
|
|
80
|
+
else return null;
|
|
81
|
+
if (href && /[()\s]/.test(href)) return null;
|
|
82
|
+
const done = convert(inner);
|
|
83
|
+
if (!done?.md) return null;
|
|
84
|
+
md += href ? `[${done.md}](${href})` : `${mark}${done.md}${mark}`;
|
|
85
|
+
plain += done.plain;
|
|
86
|
+
continue;
|
|
87
|
+
} else return null;
|
|
88
|
+
md += escape(text);
|
|
89
|
+
plain += text;
|
|
90
|
+
}
|
|
91
|
+
return { md: md.replace(/\s+/g, ' ').trim(), plain: plain.replace(/\s+/g, ' ').trim() };
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
// the component a node is in, for a hook: the nearest function named like one, with a block body
|
|
95
|
+
function componentOf(parents) {
|
|
96
|
+
for (let i = parents.length - 1; i >= 0; i--) {
|
|
97
|
+
const p = parents[i];
|
|
98
|
+
if (!/^(?:FunctionDeclaration|FunctionExpression|ArrowFunctionExpression)$/.test(p.type)) continue;
|
|
99
|
+
const name = p.id?.name ?? (parents[i - 1]?.type === 'VariableDeclarator' ? parents[i - 1].id.name : null);
|
|
100
|
+
if (name && /^[A-Z]/.test(name)) return p.body.type === 'BlockStatement' ? p : null;
|
|
101
|
+
}
|
|
102
|
+
return null;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
// source: the file's text. name: what its texts go under in the block (`articleOne`), and have: what's there already, so
|
|
106
|
+
// a second run never reuses a key. Returns the new source, the
|
|
107
|
+
// texts for the block ({group: {key: markup}}), and what it left alone: lines of prose it couldn't carry (`skipped`),
|
|
108
|
+
// of attributes it couldn't reach (`attrsLeft`) and of words in elements that aren't prose (`loose`)
|
|
109
|
+
export function moveJsx(source, { name, ts = false, have = {} }) {
|
|
110
|
+
const ast = parse(source, { sourceType: 'module', plugins: ['jsx', ...(ts ? ['typescript'] : [])] });
|
|
111
|
+
const found = [];
|
|
112
|
+
const walk = (node, parents) => {
|
|
113
|
+
if (node.type === 'JSXElement') found.push({ node, parents: [...parents] });
|
|
114
|
+
parents.push(node);
|
|
115
|
+
for (const key of Object.keys(node)) {
|
|
116
|
+
if (key === 'loc' || key === 'extra') continue;
|
|
117
|
+
const v = node[key];
|
|
118
|
+
for (const c of Array.isArray(v) ? v : [v]) if (c && typeof c.type === 'string') walk(c, parents);
|
|
119
|
+
}
|
|
120
|
+
parents.pop();
|
|
121
|
+
};
|
|
122
|
+
walk(ast.program, []);
|
|
123
|
+
found.sort((a, b) => a.node.start - b.node.start); // reading order, whichever way the tree was walked
|
|
124
|
+
|
|
125
|
+
const edits = [], block = {}, skipped = [], taken = new Set();
|
|
126
|
+
const used = new Set([...Object.values(ATTRS), ...Object.keys(have)]);
|
|
127
|
+
const need = new Set(), hooks = new Map();
|
|
128
|
+
const free = (group, key) => have[group]?.[key] === undefined && block[group]?.[key] === undefined;
|
|
129
|
+
const unique = (group, key) => { let k = key, i = 2; while (!free(group, k)) k = `${key}-${i++}`; return k; };
|
|
130
|
+
let group = 'intro', n = 0;
|
|
131
|
+
|
|
132
|
+
for (const { node, parents } of found) {
|
|
133
|
+
const tag = tagOf(node);
|
|
134
|
+
if (!tag || !PROSE_TAG.test(tag) || parents.some((p) => taken.has(p))) continue;
|
|
135
|
+
const attrs = node.openingElement.attributes;
|
|
136
|
+
if (attrs.some((a) => a.type === 'JSXAttribute' && (MARKED.includes(a.name.name) || TAKEN_PROPS.includes(a.name.name)))) continue;
|
|
137
|
+
const heading = /^h[1-6]$/.test(tag);
|
|
138
|
+
if (!heading && node.children.some((c) => c.type === 'JSXElement' && CONTAINER_TAG.test(tagOf(c) ?? ''))) continue; // a container
|
|
139
|
+
const done = convert(node.children);
|
|
140
|
+
if (!done) { if (hasWords(node)) skipped.push(node.loc.start.line); continue; }
|
|
141
|
+
if (!/\w/.test(done.md) || (!heading && words(done.md) < MIN_WORDS)) continue;
|
|
142
|
+
let key;
|
|
143
|
+
if (heading) {
|
|
144
|
+
let g = slug(done.plain) || 'text', i = 2;
|
|
145
|
+
while (used.has(g)) g = `${slug(done.plain) || 'text'}-${i++}`;
|
|
146
|
+
used.add(group = g);
|
|
147
|
+
n = 0;
|
|
148
|
+
key = 'title';
|
|
149
|
+
} else {
|
|
150
|
+
used.add(group);
|
|
151
|
+
key = `${tag}${++n}`;
|
|
152
|
+
while (!free(group, key)) key = `${tag}${++n}`;
|
|
153
|
+
}
|
|
154
|
+
(block[group] ||= {})[key] = done.md;
|
|
155
|
+
const rest = source.slice(node.openingElement.name.end, node.openingElement.end - (node.openingElement.selfClosing ? 2 : 1)).trim();
|
|
156
|
+
edits.push({ start: node.start, end: node.end, text: `<SlopText path="${name}.${group}.${key}" as="${tag}"${rest ? ` ${rest}` : ''} />` });
|
|
157
|
+
taken.add(node);
|
|
158
|
+
need.add('SlopText');
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
// alt text, tooltips, placeholders and labels: slopAttrs, and useSlop() in the component so they follow edits
|
|
162
|
+
const attrsLeft = [];
|
|
163
|
+
let attrCount = 0;
|
|
164
|
+
for (const { node, parents } of found) {
|
|
165
|
+
const tag = tagOf(node);
|
|
166
|
+
if (!tag || tag !== tag.toLowerCase() || taken.has(node) || parents.some((p) => taken.has(p))) continue;
|
|
167
|
+
const attrs = node.openingElement.attributes;
|
|
168
|
+
if (attrs.some((a) => a.type === 'JSXAttribute' && MARKED.includes(a.name.name))) continue;
|
|
169
|
+
const hits = attrs.filter((a) => a.type === 'JSXAttribute' && ATTRS[a.name.name] && a.value?.type === 'StringLiteral' && /\w/.test(a.value.value));
|
|
170
|
+
if (!hits.length) continue;
|
|
171
|
+
const fn = componentOf(parents);
|
|
172
|
+
if (!fn) { attrsLeft.push(node.loc.start.line); continue; }
|
|
173
|
+
const pairs = hits.map((a) => {
|
|
174
|
+
const g = ATTRS[a.name.name];
|
|
175
|
+
const k = unique(g, slug(a.value.value) || 'text');
|
|
176
|
+
(block[g] ||= {})[k] = a.value.value;
|
|
177
|
+
return `${/^\w+$/.test(a.name.name) ? a.name.name : `'${a.name.name}'`}: '${name}.${g}.${k}'`;
|
|
178
|
+
});
|
|
179
|
+
attrCount += hits.length;
|
|
180
|
+
edits.push({ start: hits[0].start, end: hits[0].end, text: `{...slopAttrs({ ${pairs.join(', ')} })}` });
|
|
181
|
+
for (const a of hits.slice(1)) {
|
|
182
|
+
let start = a.start;
|
|
183
|
+
while (/\s/.test(source[start - 1])) start--;
|
|
184
|
+
edits.push({ start, end: a.end, text: '' });
|
|
185
|
+
}
|
|
186
|
+
need.add('slopAttrs');
|
|
187
|
+
hooks.set(fn, true);
|
|
188
|
+
}
|
|
189
|
+
for (const fn of hooks.keys()) {
|
|
190
|
+
if (/\buseSlop\(/.test(source.slice(fn.body.start, fn.body.end))) continue;
|
|
191
|
+
const first = fn.body.body[0];
|
|
192
|
+
const line = first ? source.slice(source.lastIndexOf('\n', first.start - 1) + 1, first.start) : '';
|
|
193
|
+
edits.push({ start: fn.body.start + 1, end: fn.body.start + 1, text: `\n${/^\s+$/.test(line) ? line : ' '}useSlop();` });
|
|
194
|
+
need.add('useSlop');
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
// words sitting in an element that isn't prose (a span, an i, a div): not moved, but worth a line to the user
|
|
198
|
+
const loose = found.filter(({ node, parents }) => {
|
|
199
|
+
const tag = tagOf(node);
|
|
200
|
+
return tag && tag === tag.toLowerCase() && !PROSE_TAG.test(tag) && !parents.some((p) => taken.has(p))
|
|
201
|
+
&& node.children.some((c) => c.type === 'JSXText' && words(jsxText(c.value)) >= MIN_WORDS);
|
|
202
|
+
}).map(({ node }) => node.loc.start.line);
|
|
203
|
+
|
|
204
|
+
// imports this left unused: a link component that's now a [label](url), say. Only names that were used before
|
|
205
|
+
const imports = ast.program.body.filter((s) => s.type === 'ImportDeclaration');
|
|
206
|
+
const apply = (list) => list.slice().sort((a, b) => b.start - a.start || b.end - a.end).reduce((out, e) => out.slice(0, e.start) + e.text + out.slice(e.end), source);
|
|
207
|
+
const bare = (text) => text.replace(/^import\b[\s\S]*?\bfrom\s*['"][^'"]+['"];?[ \t]*$/gm, '');
|
|
208
|
+
const [was, now] = [bare(source), bare(apply(edits))];
|
|
209
|
+
const uses = (text, name) => text.match(new RegExp(`(?<![\\w$.])${name.replace(/\$/g, '\\$')}(?![\\w$])`, 'g'))?.length ?? 0;
|
|
210
|
+
const dropped = new Set();
|
|
211
|
+
if (edits.length) {
|
|
212
|
+
for (const decl of imports) {
|
|
213
|
+
if (decl.source.value === 'slop-editor/react' || !decl.specifiers.length) continue;
|
|
214
|
+
const gone = decl.specifiers.filter((sp) => uses(was, sp.local.name) && !uses(now, sp.local.name));
|
|
215
|
+
if (gone.length === decl.specifiers.length) {
|
|
216
|
+
const lead = source[decl.start - 1] === '\n' ? 1 : 0;
|
|
217
|
+
edits.push({ start: decl.start - lead, end: decl.end, text: '' });
|
|
218
|
+
dropped.add(decl);
|
|
219
|
+
} else if (gone.length && gone.every((sp) => sp.type === 'ImportSpecifier')) {
|
|
220
|
+
for (const sp of gone) {
|
|
221
|
+
const all = decl.specifiers.filter((x) => x.type === 'ImportSpecifier');
|
|
222
|
+
const i = all.indexOf(sp);
|
|
223
|
+
edits.push(i < all.length - 1 ? { start: sp.start, end: all[i + 1].start, text: '' } : { start: all[i - 1]?.end ?? sp.start, end: sp.end, text: '' });
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
// the import
|
|
230
|
+
const kept = imports.filter((d) => !dropped.has(d));
|
|
231
|
+
const existing = imports.find((s) => s.source.value === 'slop-editor/react' && s.importKind !== 'type');
|
|
232
|
+
const imported = new Set((existing?.specifiers ?? []).filter((s) => s.type === 'ImportSpecifier').map((s) => s.imported.name));
|
|
233
|
+
const missing = [...need].filter((x) => !imported.has(x));
|
|
234
|
+
if (missing.length && edits.length) {
|
|
235
|
+
const named = existing?.specifiers.filter((s) => s.type === 'ImportSpecifier') ?? [];
|
|
236
|
+
const plainDefault = existing?.specifiers.length && !existing.specifiers.some((s) => s.type === 'ImportNamespaceSpecifier');
|
|
237
|
+
if (named.length) edits.push({ start: named.at(-1).end, end: named.at(-1).end, text: `, ${missing.join(', ')}` });
|
|
238
|
+
else if (plainDefault) edits.push({ start: existing.specifiers.at(-1).end, end: existing.specifiers.at(-1).end, text: `, { ${missing.join(', ')} }` });
|
|
239
|
+
else {
|
|
240
|
+
const line = `import { ${missing.join(', ')} } from 'slop-editor/react';`;
|
|
241
|
+
// after the last import, or after 'use client' and the like
|
|
242
|
+
const after = kept.at(-1)?.end ?? ast.program.directives?.at(-1)?.end;
|
|
243
|
+
edits.push(after === undefined ? { start: 0, end: 0, text: `${line}\n` } : { start: after, end: after, text: `\n${line}` });
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
return { code: apply(edits), block, texts: edits.filter((e) => e.text.startsWith('<SlopText')).length, attrs: attrCount, skipped, attrsLeft, loose };
|
|
248
|
+
}
|
package/markup.mjs
CHANGED
|
@@ -1,19 +1,19 @@
|
|
|
1
|
-
// `slop-editor install --auto`: move a page's static prose into the slop text block
|
|
1
|
+
// `slop-editor install --auto`: move a page's static prose into the slop text block (as AI text, or the author asked for).
|
|
2
2
|
// It takes paragraphs, headings, list items, captions and quotes whose content is plain words with links, bold,
|
|
3
3
|
// italic and code, and leaves everything else (labels, buttons, spans, text with other markup, text the code builds)
|
|
4
4
|
// to whoever ported the page. Returns the new html and what it did.
|
|
5
5
|
|
|
6
|
-
const PROSE = 'p|h[1-6]|li|dd|dt|figcaption|blockquote';
|
|
6
|
+
export const PROSE = 'p|h[1-6]|li|dd|dt|figcaption|blockquote';
|
|
7
7
|
const SKIP = 'script|style|svg|textarea|pre|select|button|template|noscript|head|code|kbd|nav|label|form|iframe|canvas|math';
|
|
8
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
9
|
// elements that hold other prose: look inside them instead of taking them whole
|
|
10
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
11
|
const ENTITIES = { nbsp: ' ', amp: '&', lt: '<', gt: '>', quot: '"', apos: "'", ndash: '–', mdash: '—', hellip: '…', lsquo: '‘', rsquo: '’', ldquo: '“', rdquo: '”' };
|
|
12
|
-
const MIN_WORDS = 3;
|
|
12
|
+
export const MIN_WORDS = 3;
|
|
13
13
|
|
|
14
14
|
const decode = (s) => s.replace(/&(?:#(\d+)|#x([0-9a-f]+)|(\w+));/gi, (all, d, x, n) =>
|
|
15
15
|
d ? String.fromCodePoint(+d) : x ? String.fromCodePoint(parseInt(x, 16)) : (ENTITIES[n] ?? all));
|
|
16
|
-
const escape = (s) => s.replace(/([\\*\[\]{}`])/g, '\\$1');
|
|
16
|
+
export const escape = (s) => s.replace(/([\\*\[\]{}`])/g, '\\$1');
|
|
17
17
|
|
|
18
18
|
// inner HTML -> the format's inline markup, or null if it holds anything the format can't say
|
|
19
19
|
function convert(inner) {
|
|
@@ -47,8 +47,8 @@ function convert(inner) {
|
|
|
47
47
|
return out.replace(/\s+/g, ' ').trim();
|
|
48
48
|
}
|
|
49
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('-') || '';
|
|
50
|
+
export const words = (s) => s.replace(/\[([^\]]*)\]\([^)]*\)/g, '$1').replace(/[*`\\]/g, '').split(/\s+/).filter((w) => /\w/.test(w)).length;
|
|
51
|
+
export const slug = (s) => s.toLowerCase().replace(/<[^>]*>/g, '').replace(/&\w+;/g, ' ').match(/[a-z0-9]+/g)?.slice(0, 2).join('-') || '';
|
|
52
52
|
|
|
53
53
|
export function markup(html) {
|
|
54
54
|
const body = /<body\b[^>]*>/i.exec(html);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "slop-editor",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.5.1",
|
|
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": {
|
|
@@ -16,7 +16,8 @@
|
|
|
16
16
|
"./slop.js": "./slop.js",
|
|
17
17
|
"./slop.css": "./slop.css",
|
|
18
18
|
"./react": "./react.mjs",
|
|
19
|
-
"./package.json": "./package.json"
|
|
19
|
+
"./package.json": "./package.json",
|
|
20
|
+
"./vite": "./vite.mjs"
|
|
20
21
|
},
|
|
21
22
|
"files": [
|
|
22
23
|
"cli.mjs",
|
|
@@ -24,12 +25,15 @@
|
|
|
24
25
|
"react.mjs",
|
|
25
26
|
"slop.js",
|
|
26
27
|
"slop.css",
|
|
28
|
+
"jsx.mjs",
|
|
29
|
+
"vite.mjs",
|
|
27
30
|
"README.md",
|
|
28
31
|
"LICENSE"
|
|
29
32
|
],
|
|
30
33
|
"scripts": {
|
|
31
34
|
"test": "node --test test.mjs",
|
|
32
|
-
"test:browser": "node browser-test.mjs"
|
|
35
|
+
"test:browser": "node browser-test.mjs",
|
|
36
|
+
"prepublishOnly": "node -e \"const {version:v}=require('./package.json'),{version:w}=require('./.claude-plugin/plugin.json');if(v!==w){console.error('package.json says '+v+' but .claude-plugin/plugin.json says '+w+': make them match');process.exit(1)}const o=JSON.parse(require('child_process').execFileSync('npm',['view','slop-editor','versions','--json'],{encoding:'utf8'}));if(o.includes(v)){console.error('slop-editor '+v+' is already on npm ('+o.at(-1)+' is the latest): bump the version in package.json and .claude-plugin/plugin.json first');process.exit(1)}\""
|
|
33
37
|
},
|
|
34
38
|
"engines": {
|
|
35
39
|
"node": ">=18"
|
|
@@ -53,5 +57,8 @@
|
|
|
53
57
|
},
|
|
54
58
|
"devDependencies": {
|
|
55
59
|
"playwright-core": "^1.65.1"
|
|
60
|
+
},
|
|
61
|
+
"dependencies": {
|
|
62
|
+
"@babel/parser": "^7.29.15"
|
|
56
63
|
}
|
|
57
64
|
}
|
package/slop.css
CHANGED
|
@@ -74,7 +74,16 @@ html.slop-dark {
|
|
|
74
74
|
.sp-status[data-kind="dirty"] { color: var(--_ink-2); }
|
|
75
75
|
.sp-status[data-kind="error"] { color: #d0453a; }
|
|
76
76
|
.sp-link { padding: 0; border: 0; background: none; color: var(--_accent) !important; font: 600 0.78rem var(--_font); text-decoration: underline; text-underline-offset: 2px; cursor: pointer; }
|
|
77
|
-
.sp-
|
|
77
|
+
.sp-colors {
|
|
78
|
+
flex: none; display: inline-flex; align-items: center; gap: 6px; height: 30px; margin-left: auto; padding: 0 10px 0 7px; border-radius: 8px;
|
|
79
|
+
border: 1px solid var(--_rule); background: none; font: 600 0.78rem var(--_font); color: var(--_ink-3) !important; cursor: pointer;
|
|
80
|
+
}
|
|
81
|
+
.sp-colors:hover { border-color: var(--_ink-3); }
|
|
82
|
+
.sp-colors .sp-switch { background: var(--_rule); }
|
|
83
|
+
.sp-colors[aria-checked="true"] { color: var(--_ink) !important; }
|
|
84
|
+
.sp-colors[aria-checked="true"] .sp-switch { background: var(--slop-c-ai, var(--_accent)); }
|
|
85
|
+
.sp-colors[aria-checked="true"] .sp-switch::after { transform: translateX(10px); }
|
|
86
|
+
.sp-save { flex: none; height: 30px; padding: 0 13px; border-radius: 8px; border: 1px solid var(--_accent); background: var(--_accent); color: var(--_bg) !important; font: 600 0.82rem var(--_font); font-variant-numeric: tabular-nums; cursor: pointer; }
|
|
78
87
|
.sp-save:hover:not(:disabled) { filter: brightness(1.1); }
|
|
79
88
|
.sp-save:disabled { border-color: var(--_rule); background: none; color: var(--_ink-3) !important; cursor: default; }
|
|
80
89
|
.sp-revert { flex: none; padding: 0 2px; border: 0; background: none; font: 600 0.72rem var(--_font); color: var(--_ink-3) !important; text-decoration: underline; text-decoration-color: var(--_rule); text-underline-offset: 2px; cursor: pointer; }
|
|
@@ -93,11 +102,6 @@ html.slop-dark {
|
|
|
93
102
|
|
|
94
103
|
/* the whole page: how much is slop, the page's switch, and the categories */
|
|
95
104
|
.sp-cover { display: grid; gap: 10px; padding: 0 16px 14px; }
|
|
96
|
-
.sp-cover-row { display: flex; align-items: center; gap: 10px; }
|
|
97
|
-
.sp-big { font-size: 0.9rem; color: var(--_ink-2); }
|
|
98
|
-
.sp-big b { font: 700 1.55rem/1 var(--_font); color: var(--slop-c-ai, var(--_accent)); font-variant-numeric: tabular-nums; letter-spacing: -0.01em; }
|
|
99
|
-
.sp-words { margin-right: auto !important; font-size: 0.78rem; color: var(--_ink-3); font-variant-numeric: tabular-nums; }
|
|
100
|
-
.sp-cover-row .sp-pie { width: 22px; height: 22px; }
|
|
101
105
|
.sp-cats { display: flex; flex-wrap: wrap; gap: 6px; }
|
|
102
106
|
.sp-cat { display: inline-flex; align-items: center; gap: 6px; height: 28px; padding: 0 9px 0 4px; border: 1px solid var(--_rule); border-radius: 99px; font-size: 0.78rem; }
|
|
103
107
|
.sp-cat { cursor: pointer; }
|
|
@@ -164,6 +168,8 @@ html.slop-dark {
|
|
|
164
168
|
/* sections */
|
|
165
169
|
.sp-group { border-bottom: 1px solid var(--_rule); }
|
|
166
170
|
.sp-group summary { display: flex; align-items: center; gap: 8px; padding: 10px 4px; cursor: pointer; list-style: none; }
|
|
171
|
+
/* an open section's name stays at the top while its texts scroll, so it can be closed from anywhere in it */
|
|
172
|
+
.sp-group[open] > summary { position: sticky; top: -8px; z-index: 3; margin: 0 -12px; padding: 10px 16px; background: var(--_bg); }
|
|
167
173
|
.sp-group summary::-webkit-details-marker { display: none; }
|
|
168
174
|
.sp-group summary::before { content: ""; flex: none; width: 6px; height: 6px; margin: 0 3px 0 1px; border: solid var(--_ink-3); border-width: 0 1.5px 1.5px 0; transform: rotate(-45deg); transition: transform .15s; }
|
|
169
175
|
.sp-group[open] summary::before { transform: rotate(45deg) translate(-2px, 0); }
|
package/slop.js
CHANGED
|
@@ -101,6 +101,8 @@ const Slop = (() => {
|
|
|
101
101
|
const reslop = (value) => reattribute(value, 'ok', 'ai');
|
|
102
102
|
// characters start to end (of the plain text) marked as one author's
|
|
103
103
|
const assign = (value, start, end, to) => fromChars(plain(value), authorsByChar(value).map((a, i) => (i >= start && i < end ? to : a)));
|
|
104
|
+
// characters from `start` on given these authors, one each (what was pasted keeps who wrote it), the text unchanged
|
|
105
|
+
const overlay = (value, start, authors) => fromChars(plain(value), authorsByChar(value).map((a, i) => authors[i - start] ?? a));
|
|
104
106
|
|
|
105
107
|
const LINK = /\[([^\]]+)\]\(([^)\s]+)\)/y;
|
|
106
108
|
const VAR = /\{(\w+)\}/y;
|
|
@@ -310,7 +312,7 @@ const Slop = (() => {
|
|
|
310
312
|
return out;
|
|
311
313
|
}
|
|
312
314
|
|
|
313
|
-
const core = { BUILTIN, plain, applyEdit, reslop, unslop, assign, reattribute, runs, readable, render, makeup, share, percent, repeats, rebase, listsIn, wordsOf, paragraphsOf, vars };
|
|
315
|
+
const core = { BUILTIN, plain, applyEdit, reslop, unslop, assign, overlay, reattribute, runs, readable, render, makeup, share, percent, repeats, rebase, listsIn, wordsOf, paragraphsOf, vars };
|
|
314
316
|
if (typeof document === 'undefined') return core; // Node (the CLI and the tests) only needs the format
|
|
315
317
|
|
|
316
318
|
/* ---------- the block ---------- */
|
|
@@ -626,13 +628,15 @@ const Slop = (() => {
|
|
|
626
628
|
const store = storage(() => localStorage);
|
|
627
629
|
const session = storage(() => sessionStorage); // this tab only: the unsaved draft
|
|
628
630
|
// what readers see is the page's choice, "nothing" unless it says otherwise. While the editor is open, its
|
|
629
|
-
// author sees the colors whatever readers get
|
|
631
|
+
// author sees the colors whatever readers get, until they switch them off to compare (editColors)
|
|
630
632
|
const SHOW = ['nothing', 'pie', 'colors'];
|
|
631
633
|
const shows = () => (SHOW.includes(text._show) ? text._show : 'nothing');
|
|
632
634
|
const meters = [];
|
|
633
635
|
const built = new WeakMap(); // element → its meter
|
|
634
636
|
let meterOn = false;
|
|
635
637
|
let editing = false;
|
|
638
|
+
let editColors = true;
|
|
639
|
+
let editSwitch = null; // the editor's own Slop-o-meter switch, in its header
|
|
636
640
|
function setMeter(on) {
|
|
637
641
|
meterOn = on;
|
|
638
642
|
paintShow();
|
|
@@ -643,7 +647,8 @@ const Slop = (() => {
|
|
|
643
647
|
const sectionOf = (m) => (m.at && m.el.parentElement ? m.el.closest('[data-slop-section]') ?? m.el.parentElement : document.documentElement);
|
|
644
648
|
function paintShow() {
|
|
645
649
|
const mode = shows();
|
|
646
|
-
document.documentElement.classList.toggle('slop-on', editing
|
|
650
|
+
document.documentElement.classList.toggle('slop-on', editing ? editColors : mode === 'colors' && meterOn);
|
|
651
|
+
editSwitch?.setAttribute('aria-checked', String(editColors));
|
|
647
652
|
meters.forEach((m) => {
|
|
648
653
|
m.el.dataset.show = mode;
|
|
649
654
|
const section = sectionOf(m);
|
|
@@ -655,7 +660,7 @@ const Slop = (() => {
|
|
|
655
660
|
section.classList.toggle('slop-on', own === true);
|
|
656
661
|
section.classList.toggle('slop-off', own === false);
|
|
657
662
|
}
|
|
658
|
-
m.btn.setAttribute('aria-pressed', String(m.own ?? meterOn));
|
|
663
|
+
m.btn.setAttribute('aria-pressed', String(editing ? editColors : m.own ?? meterOn));
|
|
659
664
|
});
|
|
660
665
|
}
|
|
661
666
|
function paintMeters() {
|
|
@@ -683,6 +688,7 @@ const Slop = (() => {
|
|
|
683
688
|
+ '<span class="slop-meter-key"><span class="slop-pie" role="img"></span><span class="slop-legend"></span></span>';
|
|
684
689
|
const m = { el, at: el.dataset.slopMeter || '', own: null, section: null, btn: el.querySelector('button'), pie: el.querySelector('.slop-pie'), legend: el.querySelector('.slop-legend') };
|
|
685
690
|
m.btn.addEventListener('click', () => {
|
|
691
|
+
if (editing) { editColors = !editColors; paintShow(); return; } // the editor's switch, while it's open
|
|
686
692
|
const on = !(m.own ?? meterOn);
|
|
687
693
|
if (m.at) { m.own = on; paintShow(); return; } // only the page-wide choice is remembered
|
|
688
694
|
setMeter(on);
|
|
@@ -760,11 +766,11 @@ const Slop = (() => {
|
|
|
760
766
|
<header class="sp-head" title="Drag to move, or drag an edge to resize. Double-click to put it back">
|
|
761
767
|
<span class="sp-grip" aria-hidden="true"></span>
|
|
762
768
|
<div><h2>Edit text</h2><p class="sp-status" role="status" aria-live="polite"></p></div>
|
|
769
|
+
<button type="button" class="sp-colors" role="switch" title="Slop-o-meter: color the page's words by who wrote them. Only for you, while you edit"><span class="sp-switch" aria-hidden="true"></span>Colors</button>
|
|
763
770
|
<button type="button" class="sp-save" title="Save (⌘S)" disabled>Saved</button>
|
|
764
771
|
<button type="button" class="sp-close" aria-label="Close the editor">×</button>
|
|
765
772
|
</header>
|
|
766
773
|
<div class="sp-cover">
|
|
767
|
-
<div class="sp-cover-row"><p class="sp-big"><b></b> slop</p><p class="sp-words"></p></div>
|
|
768
774
|
<div class="sp-cats"></div>
|
|
769
775
|
<div class="sp-show"><span>Readers see</span><div class="sp-seg" role="radiogroup" aria-label="What readers see">
|
|
770
776
|
<button type="button" role="radio" data-show="nothing" title="No sign of the slop editor on the published page">Nothing</button>
|
|
@@ -786,8 +792,9 @@ const Slop = (() => {
|
|
|
786
792
|
const $ = (sel) => aside.querySelector(sel);
|
|
787
793
|
const body = $('.sp-body');
|
|
788
794
|
const statusEl = $('.sp-status');
|
|
789
|
-
|
|
790
|
-
$('.sp-
|
|
795
|
+
aside.classList.add('slop-on'); // the text boxes keep their colors when the page's are off
|
|
796
|
+
editSwitch = $('.sp-colors');
|
|
797
|
+
editSwitch.addEventListener('click', () => { editColors = !editColors; paintShow(); });
|
|
791
798
|
|
|
792
799
|
function status(msg, kind = '', action) {
|
|
793
800
|
statusEl.textContent = msg;
|
|
@@ -1383,6 +1390,32 @@ const Slop = (() => {
|
|
|
1383
1390
|
const assignLabel = (input) => {
|
|
1384
1391
|
if (assignEl.firstChild) assignEl.firstChild.textContent = input.selectionStart === input.selectionEnd ? 'Mark all as' : 'Mark selection as';
|
|
1385
1392
|
};
|
|
1393
|
+
// while a selection is being dragged out too, so the row doesn't change under the pointer once it's let go
|
|
1394
|
+
document.addEventListener('selectionchange', () => {
|
|
1395
|
+
const a = document.activeElement;
|
|
1396
|
+
if (a?.tagName === 'TEXTAREA' && assignEl.parentNode?.contains(a)) assignLabel(a);
|
|
1397
|
+
});
|
|
1398
|
+
|
|
1399
|
+
/* copying a text's words keeps who wrote them: pasted into a text (here, or in another page's editor), they keep
|
|
1400
|
+
their authors. Words from anywhere else are mine, as typed */
|
|
1401
|
+
const CLIP = 'application/x-slop-editor';
|
|
1402
|
+
let clip = null; // {words, authors}, the last copied here: for a browser that keeps only plain text
|
|
1403
|
+
function copyOut(e, input, path) {
|
|
1404
|
+
const [s, t] = [input.selectionStart, input.selectionEnd];
|
|
1405
|
+
if (s === t || !e.clipboardData) return;
|
|
1406
|
+
clip = { words: input.value.slice(s, t), authors: authorsByChar(get(path)).slice(s, t) };
|
|
1407
|
+
e.preventDefault();
|
|
1408
|
+
e.clipboardData.setData('text/plain', clip.words);
|
|
1409
|
+
e.clipboardData.setData(CLIP, JSON.stringify(clip));
|
|
1410
|
+
if (e.type === 'cut') document.execCommand('delete'); // as an edit, so ⌘Z brings it back
|
|
1411
|
+
}
|
|
1412
|
+
function pastedIn(e) {
|
|
1413
|
+
const words = (e.clipboardData?.getData('text/plain') ?? '').replace(/\r\n?/g, '\n');
|
|
1414
|
+
let c = clip;
|
|
1415
|
+
try { c = JSON.parse(e.clipboardData.getData(CLIP)) ?? clip; } catch { /* plain text only */ }
|
|
1416
|
+
if (!c || c.words !== words || !Array.isArray(c.authors) || c.authors.length !== words.length) return null;
|
|
1417
|
+
return { words, authors: c.authors.map((a) => (typeof a === 'string' && a ? a : 'me')) };
|
|
1418
|
+
}
|
|
1386
1419
|
|
|
1387
1420
|
/* the views */
|
|
1388
1421
|
const setOf = (path) => sets.find((s) => s.paths.includes(path));
|
|
@@ -1462,10 +1495,15 @@ const Slop = (() => {
|
|
|
1462
1495
|
input.addEventListener('beforeinput', () => { input.at = [input.selectionStart, input.selectionEnd]; });
|
|
1463
1496
|
input.addEventListener('input', (e) => {
|
|
1464
1497
|
const restoring = /^history(Undo|Redo)$/.test(e.inputType);
|
|
1465
|
-
|
|
1498
|
+
const pasted = e.inputType === 'insertFromPaste' ? input.pasted : null;
|
|
1499
|
+
edit(paths(), input, restoring, restoring || e.isComposing || /Composition/.test(e.inputType) ? undefined : input.at, pasted);
|
|
1466
1500
|
input.at = undefined;
|
|
1501
|
+
input.pasted = null;
|
|
1467
1502
|
});
|
|
1468
|
-
|
|
1503
|
+
input.addEventListener('copy', (e) => copyOut(e, input, paths()[0]));
|
|
1504
|
+
input.addEventListener('cut', (e) => copyOut(e, input, paths()[0]));
|
|
1505
|
+
input.addEventListener('paste', (e) => { input.pasted = pastedIn(e); });
|
|
1506
|
+
['select', 'selectionchange', 'keyup', 'pointerup'].forEach((t) => input.addEventListener(t, () => assignLabel(input)));
|
|
1469
1507
|
input.addEventListener('focus', () => { focus(path, all, input, wrap); showAssign(wrap, input, paths()); });
|
|
1470
1508
|
input.addEventListener('blur', () => {
|
|
1471
1509
|
mark(false);
|
|
@@ -1495,7 +1533,11 @@ const Slop = (() => {
|
|
|
1495
1533
|
det.querySelector('.sp-gname').after(ctl.pie);
|
|
1496
1534
|
det.querySelector('summary').append(ctl);
|
|
1497
1535
|
det.addEventListener('toggle', () => {
|
|
1498
|
-
if (det.open) { state.open.add(key); det.querySelectorAll('textarea').forEach(grow); }
|
|
1536
|
+
if (det.open) { state.open.add(key); det.querySelectorAll('textarea').forEach(grow); return; }
|
|
1537
|
+
state.open.delete(key);
|
|
1538
|
+
// closed from its name stuck at the top: back to where the section starts
|
|
1539
|
+
const above = det.getBoundingClientRect().top - body.getBoundingClientRect().top;
|
|
1540
|
+
if (above < 0) body.scrollTop += above;
|
|
1499
1541
|
});
|
|
1500
1542
|
paths.forEach((p) => det.append(field(p)));
|
|
1501
1543
|
if (state.tab === 'all') listRows(key, det);
|
|
@@ -1625,7 +1667,7 @@ const Slop = (() => {
|
|
|
1625
1667
|
|
|
1626
1668
|
function render() {
|
|
1627
1669
|
FLAGS.forEach((name) => flag(name)); // the elements pointed at may be gone
|
|
1628
|
-
controls = [
|
|
1670
|
+
controls = [];
|
|
1629
1671
|
sets = repeats(entries());
|
|
1630
1672
|
groupKeys().forEach((k) => { if (!state.known.has(k)) { state.known.add(k); state.open.add(k); } });
|
|
1631
1673
|
renderCats();
|
|
@@ -1679,8 +1721,6 @@ const Slop = (() => {
|
|
|
1679
1721
|
const cats = categories();
|
|
1680
1722
|
const all = entries();
|
|
1681
1723
|
const page = makeup(all.map(([, v]) => v));
|
|
1682
|
-
$('.sp-big b').textContent = percent(page.letters ? (page.counts.ai ?? 0) / page.letters : 0);
|
|
1683
|
-
$('.sp-words').textContent = count(page.allWords, 'word');
|
|
1684
1724
|
aside.querySelectorAll('.sp-seg button').forEach((b) => b.setAttribute('aria-checked', String(b.dataset.show === shows())));
|
|
1685
1725
|
const revert = $('.sp-cat-revert');
|
|
1686
1726
|
if (revert) revert.hidden = !Object.values(text._categories ?? {}).some((c) => c.color);
|
|
@@ -1815,12 +1855,15 @@ const Slop = (() => {
|
|
|
1815
1855
|
past.set(p, list.slice(-200));
|
|
1816
1856
|
}
|
|
1817
1857
|
const recall = (p, words) => past.get(p)?.findLast((v) => plain(v) === words);
|
|
1818
|
-
|
|
1858
|
+
// `pasted`: words copied from a text, with their authors, now at `at`
|
|
1859
|
+
function edit(paths, input, restoring, at, pasted) {
|
|
1819
1860
|
undo = null;
|
|
1820
1861
|
const f = state.focus;
|
|
1862
|
+
const keep = pasted && at && input.value.startsWith(pasted.words, at[0]);
|
|
1821
1863
|
[...paths, ...(f?.linked ?? [])].forEach((p) => {
|
|
1822
1864
|
remember(p);
|
|
1823
|
-
|
|
1865
|
+
const next = applyEdit(get(p), input.value, restoring ? recall(p, input.value) : undefined, at);
|
|
1866
|
+
set(p, keep ? overlay(next, at[0], pasted.authors) : next);
|
|
1824
1867
|
remember(p);
|
|
1825
1868
|
});
|
|
1826
1869
|
grow(input);
|
package/vite.mjs
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
// slop-editor/vite: the slop editor in a Vite app. The words live in one JSON file (src/slopText.json). This puts them in
|
|
2
|
+
// the page as its text block, with slop.js and slop.css, which render them, and under `vite` (not a build) it answers
|
|
3
|
+
// the editor: its Edit text button appears on the page and saves back into the file. A built site has no editor.
|
|
4
|
+
//
|
|
5
|
+
// import slopEditor from 'slop-editor/vite';
|
|
6
|
+
// export default defineConfig({ plugins: [react(), slopEditor()] }); // or slopEditor({ text: 'content/words.json' })
|
|
7
|
+
//
|
|
8
|
+
// The file's `version` goes up with every save, so a page that loaded an older version can't save over what changed
|
|
9
|
+
// since. Edit the file directly (an agent, say) and the open page reloads. MIT license.
|
|
10
|
+
import { readFile, writeFile, rename } from 'node:fs/promises';
|
|
11
|
+
import { existsSync } from 'node:fs';
|
|
12
|
+
import path from 'node:path';
|
|
13
|
+
import { fileURLToPath } from 'node:url';
|
|
14
|
+
|
|
15
|
+
const here = path.dirname(fileURLToPath(import.meta.url));
|
|
16
|
+
|
|
17
|
+
// where a project keeps its words unless it says: the file that's there, else src/slopText.json (or slopText.json in a
|
|
18
|
+
// project with no src). `slop-editor install` makes the same choice
|
|
19
|
+
export const textFileIn = (root) => ['src/slopText.json', 'slopText.json'].find((f) => existsSync(path.join(root, f)))
|
|
20
|
+
?? (existsSync(path.join(root, 'src')) ? 'src/slopText.json' : 'slopText.json');
|
|
21
|
+
|
|
22
|
+
export default function slopEditor({ text } = {}) {
|
|
23
|
+
let file;
|
|
24
|
+
let lastSaved = null; // the version this server wrote last, so its own saves don't reload the page
|
|
25
|
+
const read = async () => {
|
|
26
|
+
try {
|
|
27
|
+
return await readFile(file, 'utf8');
|
|
28
|
+
} catch {
|
|
29
|
+
throw new Error(`slop-editor/vite: ${path.relative(process.cwd(), file)} not found. Run \`npx slop-editor install --auto <a .jsx or .tsx file>\` to make it, or write {"version": 1}`);
|
|
30
|
+
}
|
|
31
|
+
};
|
|
32
|
+
return {
|
|
33
|
+
name: 'slop-editor',
|
|
34
|
+
configResolved(config) {
|
|
35
|
+
file = path.resolve(config.root, text ?? textFileIn(config.root));
|
|
36
|
+
},
|
|
37
|
+
async transformIndexHtml() {
|
|
38
|
+
const [words, js, css] = await Promise.all([read(), readFile(path.join(here, 'slop.js'), 'utf8'), readFile(path.join(here, 'slop.css'), 'utf8')]);
|
|
39
|
+
// compact, and safe inside a script element
|
|
40
|
+
const block = JSON.stringify(JSON.parse(words)).replace(/</g, '\\u003c');
|
|
41
|
+
return [
|
|
42
|
+
{ tag: 'style', children: css, injectTo: 'head' },
|
|
43
|
+
{ tag: 'script', attrs: { type: 'application/json', id: 'slop-text' }, children: block, injectTo: 'body-prepend' },
|
|
44
|
+
{ tag: 'script', children: js.replace(/<\/script/gi, '<\\/script'), injectTo: 'body' },
|
|
45
|
+
];
|
|
46
|
+
},
|
|
47
|
+
configureServer(server) {
|
|
48
|
+
server.watcher.add(file);
|
|
49
|
+
server.watcher.on('change', async (changed) => {
|
|
50
|
+
if (path.resolve(changed) !== file) return;
|
|
51
|
+
try {
|
|
52
|
+
if (JSON.parse(await readFile(file, 'utf8')).version === lastSaved) return;
|
|
53
|
+
} catch {
|
|
54
|
+
return; // halfway through being written
|
|
55
|
+
}
|
|
56
|
+
server.ws.send({ type: 'full-reload' });
|
|
57
|
+
});
|
|
58
|
+
// the editor's handshake: a GET answers "slop-editor", and a POST saves the whole text block
|
|
59
|
+
server.middlewares.use('/__slop', (req, res) => {
|
|
60
|
+
if (req.method !== 'POST') {
|
|
61
|
+
res.end('slop-editor');
|
|
62
|
+
return;
|
|
63
|
+
}
|
|
64
|
+
let body = '';
|
|
65
|
+
req.on('data', (chunk) => { body += chunk; });
|
|
66
|
+
req.on('end', async () => {
|
|
67
|
+
try {
|
|
68
|
+
const sent = JSON.parse(body);
|
|
69
|
+
if (!sent || typeof sent !== 'object' || Array.isArray(sent) || typeof sent.version !== 'number') throw new Error('expected an object with a numeric "version"');
|
|
70
|
+
const current = JSON.parse(await read());
|
|
71
|
+
if (sent.version !== current.version) {
|
|
72
|
+
res.statusCode = 409;
|
|
73
|
+
res.end('the file changed since this page loaded it. Reload the page (copy any unsaved edits first)');
|
|
74
|
+
return;
|
|
75
|
+
}
|
|
76
|
+
const saved = { ...sent, version: current.version + 1 };
|
|
77
|
+
lastSaved = saved.version;
|
|
78
|
+
await writeFile(`${file}.saving`, JSON.stringify(saved, null, 2) + '\n');
|
|
79
|
+
await rename(`${file}.saving`, file);
|
|
80
|
+
res.end(String(saved.version));
|
|
81
|
+
} catch (e) {
|
|
82
|
+
res.statusCode = 400;
|
|
83
|
+
res.end(e.message);
|
|
84
|
+
}
|
|
85
|
+
});
|
|
86
|
+
});
|
|
87
|
+
},
|
|
88
|
+
};
|
|
89
|
+
}
|