slop-editor 0.4.0 → 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 +22 -2
- package/cli.mjs +170 -12
- package/jsx.mjs +248 -0
- package/markup.mjs +6 -6
- package/package.json +10 -3
- 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';
|
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.0",
|
|
4
4
|
"description": "A slop editor: track who wrote every word on a page (the AI, you, or nobody), then read the slop and make it yours.",
|
|
5
5
|
"homepage": "https://baphaelman.github.io/slop-editor/",
|
|
6
6
|
"repository": {
|
|
@@ -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/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
|
+
}
|