slop-editor 0.2.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +23 -6
- package/package.json +1 -1
- package/react.mjs +12 -3
- package/slop.css +48 -8
- package/slop.js +353 -50
package/README.md
CHANGED
|
@@ -61,6 +61,8 @@ A **text** is a plain string (AI) or a list mixing strings (AI), `{"me": "..."}`
|
|
|
61
61
|
|
|
62
62
|
Slop is only ever the AI's words. Other categories are other people's. Inline markup: `[label](url)`, `**bold**`, `*italic*`, `` `code` ``, `[[key]]` for a key cap, `{name}` for a value the page fills in, and `\` to escape.
|
|
63
63
|
|
|
64
|
+
**Paragraphs.** A blank line in a text shown in a `<p>`, `<li>` or `<dd>` starts a paragraph of its own: the element shows the first, and a copy of it after it shows each of the others (`data-slop-more` instead of `data-slop`). Markup doesn't carry across a blank line. Anywhere else a line break is a `<br>`. An element whose text is empty is hidden (`.slop-empty`), except while the editor is open.
|
|
65
|
+
|
|
64
66
|
In the page:
|
|
65
67
|
|
|
66
68
|
```html
|
|
@@ -74,7 +76,17 @@ In the page:
|
|
|
74
76
|
</script>
|
|
75
77
|
```
|
|
76
78
|
|
|
77
|
-
Code can render texts itself with `Slop.html('intro.p1')` (HTML) or `Slop.words('intro.p1')` (plain text). Put `data-slop-ref="intro.p1"` on the element that shows them (a button or link the page builds) and the editor can still find, highlight and scroll to it. Unlike `data-slop`, nothing fills it.
|
|
79
|
+
Code can render texts itself with `Slop.html('intro.p1')` (HTML), `Slop.paragraphs('intro.p1')` (HTML, one string per paragraph) or `Slop.words('intro.p1')` (plain text). Put `data-slop-ref="intro.p1"` on the element that shows them (a button or link the page builds) and the editor can still find, highlight and scroll to it. Unlike `data-slop`, nothing fills it.
|
|
80
|
+
|
|
81
|
+
**Lists.** Where the page shows a group as a list of paragraphs, say so, and the editor can add and remove texts there:
|
|
82
|
+
|
|
83
|
+
```html
|
|
84
|
+
<div data-slop-list="intro"> <!-- a copy of the first child for each text in "intro", in order -->
|
|
85
|
+
<p data-slop="intro.p1"></p>
|
|
86
|
+
</div>
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
The list's children are its texts and nothing else. A page that draws them itself (React and the like) puts `data-slop-list-ref="intro"` on the element around them instead, draws one per key of the group, in order, and redraws after an edit.
|
|
78
90
|
|
|
79
91
|
**Words the page doesn't show as words** (alt text for an image that doesn't load, a tooltip, a label for screen readers, a placeholder) go in attributes: `<img data-slop-attr="alt:hero.photo">`, or several at once, `data-slop-attr="alt:hero.photo title:hero.tip"`. They're filled as plain text. The editor gives them a tab of their own, **Hidden**, since readers' colors can't show them.
|
|
80
92
|
|
|
@@ -98,11 +110,14 @@ A group's key (`'intro'`) covers all its texts. While shown, the page's own redr
|
|
|
98
110
|
`slop-editor/react` wraps it, with no JSX and no build. slop.js still goes in the page first, as a plain `<script>`.
|
|
99
111
|
|
|
100
112
|
```jsx
|
|
101
|
-
import Slop, { SlopText, SlopMeter, slopAttrs, useSlop } from 'slop-editor/react';
|
|
113
|
+
import Slop, { SlopText, SlopMeter, slopAttrs, slopList, useSlop } from 'slop-editor/react';
|
|
102
114
|
|
|
103
115
|
<SlopMeter path="games.othello" /> // a meter (no path: the page's)
|
|
104
|
-
<SlopText path="intro.p1" as="p" /> // a text, redrawn after each edit
|
|
116
|
+
<SlopText path="intro.p1" as="p" /> // a text, redrawn after each edit; as a p, li or dd, one per paragraph
|
|
105
117
|
<img src="hero.png" {...slopAttrs({ alt: 'hero.photo' })} />
|
|
118
|
+
<div {...slopList('intro')}> // a list: the editor can add and remove texts in it
|
|
119
|
+
{Object.keys(Slop.text.intro).map((k) => <SlopText key={k} path={`intro.${k}`} as="p" />)}
|
|
120
|
+
</div>
|
|
106
121
|
```
|
|
107
122
|
|
|
108
123
|
`useSlop()` makes any component render again after an edit; `SlopText` already does. Call it in a component that uses `slopAttrs` or `Slop.words`.
|
|
@@ -112,13 +127,15 @@ import Slop, { SlopText, SlopMeter, slopAttrs, useSlop } from 'slop-editor/react
|
|
|
112
127
|
`slop-editor edit page.html` serves the page's folder on 127.0.0.1 and opens the page with an **Edit text** button. Published, the page shows no sign of the editor. `Slop.start({edit: 'local'})` gives every visitor an editor that saves in their browser instead (the demo page uses it).
|
|
113
128
|
|
|
114
129
|
- **All** shows every text, grouped by section. **Slop left** shows only the texts that aren't all yours yet; work through it until it's empty. **Repeats** shows the repeated text. **Hidden** (on pages that have some) shows alt text, tooltips and labels.
|
|
115
|
-
- Each text
|
|
130
|
+
- Each text box shows its words in their authors' colors, as readers see them with the Slop-o-meter on.
|
|
131
|
+
- Each text, section and the whole page has a pie of what it's made of, by its name, and a **slop** switch at the right. Off approves the AI's words; on takes that back. Your typed words are never touched. Every switch can be undone from the status line.
|
|
116
132
|
- At the top: how much of the page is slop, and every category with its share and a color picker. Rename a category by editing its name. **+ Category** adds one; × deletes it (its words become AI-generated).
|
|
117
133
|
- Focus a text and a row of categories appears under it: **Mark all as** (or **Mark selection as**, with words selected) gives the text, or just the selection, to a category.
|
|
134
|
+
- In a list, a **+** under the text you're on adds an empty paragraph after it; pointing at the + draws a line on the page where it would go. The trash can before its slop switch outlines the text on the page in dashed red; a text with words takes a second click (it asks **Remove?**), and stays red until then. A removed text stays in **All** as a row with **Restore** until the next save. New texts get new keys (`p7` between `p2` and `p3` is still called Paragraph 3 in the editor), so a key never moves to other words.
|
|
118
135
|
- Click any text on the page to jump to it in the editor. Focus a text in the editor to find it on the page.
|
|
119
136
|
- Drag the header to move the editor anywhere, and drag any edge or corner to resize it. It stays where you leave it; double-click the header to put it back. On a phone it's a sheet along the bottom, and dragging changes its height.
|
|
120
|
-
- Nothing is written until you click **Save** (or press ⌘S). The button counts the texts changed since the last save. Each changed text has a **Revert** link that takes its words and authorship back to the last save. Saves are versioned: a tab whose copy of the file is out of date gets an error instead of overwriting newer edits
|
|
121
|
-
- ⌘Z in a text undoes typing and gives the restored words back to whoever wrote them. ⌘Z anywhere else undoes the last switch, mark or
|
|
137
|
+
- Nothing is written until you click **Save** (or press ⌘S). The button counts the texts changed since the last save. Each changed text has a **Revert** link that takes its words and authorship back to the last save. Saves are versioned: a tab whose copy of the file is out of date gets an error instead of overwriting newer edits. Leaving with unsaved changes asks first, and a reload keeps them in that tab, still unsaved, with **Discard** (a page in a frame can't ask).
|
|
138
|
+
- What you type is yours, every letter, even one typed over a selection that starts with the same letter. ⌘Z in a text undoes typing and gives the restored words back to whoever wrote them. ⌘Z anywhere else undoes the last switch, mark, revert, added or removed text.
|
|
122
139
|
|
|
123
140
|
### Repeated text
|
|
124
141
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "slop-editor",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0",
|
|
4
4
|
"description": "A slop editor: track who wrote every word on a page (the AI, you, or nobody), then read the slop and make it yours.",
|
|
5
5
|
"homepage": "https://baphaelman.github.io/slop-editor/",
|
|
6
6
|
"repository": {
|
package/react.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// The slop editor in a React app: `import { SlopText, SlopMeter, slopAttrs, useSlop } from 'slop-editor/react'`.
|
|
2
2
|
// slop.js has to be in the page first, as a plain <script>: this hands its global Slop to the modules. No JSX and no
|
|
3
3
|
// build, so it works from node_modules as it is. MIT license.
|
|
4
|
-
import { createElement, useSyncExternalStore } from 'react';
|
|
4
|
+
import { createElement, Fragment, useSyncExternalStore } from 'react';
|
|
5
5
|
|
|
6
6
|
/* global Slop */
|
|
7
7
|
// slop.js declares Slop with const: a global name, but not a property of window
|
|
@@ -24,12 +24,21 @@ const snapshot = () => version;
|
|
|
24
24
|
export const useSlop = () => useSyncExternalStore(subscribe, snapshot, snapshot);
|
|
25
25
|
|
|
26
26
|
// a text as HTML, in a span (or `as`). React draws it; data-slop-ref lets the editor find it on the page. `vars` fill
|
|
27
|
-
// in {name}s for this one text
|
|
27
|
+
// in {name}s for this one text. As a p, li or dd, each paragraph after a blank line gets one of its own
|
|
28
28
|
export function SlopText({ path, as = 'span', vars, ...props }) {
|
|
29
29
|
useSlop();
|
|
30
|
-
|
|
30
|
+
const ref = { 'data-slop-ref': path };
|
|
31
|
+
if (!['p', 'li', 'dd'].includes(as)) return createElement(as, { ...props, ...ref, dangerouslySetInnerHTML: { __html: slop.html(path, vars) } });
|
|
32
|
+
const parts = slop.paragraphs(path, vars);
|
|
33
|
+
if (parts.length === 1) return createElement(as, { ...props, ...ref, dangerouslySetInnerHTML: { __html: parts[0] } });
|
|
34
|
+
const { id, ...rest } = props;
|
|
35
|
+
return createElement(Fragment, null, ...parts.map((h, i) => createElement(as, { ...(i ? rest : props), ...ref, key: i, dangerouslySetInnerHTML: { __html: h } })));
|
|
31
36
|
}
|
|
32
37
|
|
|
38
|
+
// a group the page shows as a list (paragraphs it draws one by one): the editor can add and remove texts in it.
|
|
39
|
+
// <div {...slopList('intro')}>{…a <SlopText as="p"> for each…}</div>
|
|
40
|
+
export const slopList = (path) => ({ 'data-slop-list-ref': path });
|
|
41
|
+
|
|
33
42
|
// attributes from texts, as plain text: <img {...slopAttrs({ alt: 'hero.photo' })} />. The editor lists them under
|
|
34
43
|
// Hidden. Call it from a component that calls useSlop(), so they follow edits
|
|
35
44
|
export function slopAttrs(attrs, vars) {
|
package/slop.css
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
<html> when it's dark, and writes the colors into a stylesheet of its own. --slop-font and --slop-mono set the
|
|
5
5
|
editor's fonts. */
|
|
6
6
|
html {
|
|
7
|
-
--_accent: #6d35d0;
|
|
7
|
+
--_accent: #6d35d0; --_danger: #c8173f;
|
|
8
8
|
--_font: var(--slop-font, ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif);
|
|
9
9
|
--_mono: var(--slop-mono, ui-monospace, "SF Mono", Menlo, Consolas, monospace);
|
|
10
10
|
/* the editor's own surface */
|
|
@@ -12,7 +12,7 @@ html {
|
|
|
12
12
|
--_shadow: 0 1px 2px rgb(30 20 40 / 0.06), 0 18px 48px rgb(30 20 40 / 0.16);
|
|
13
13
|
}
|
|
14
14
|
html.slop-dark {
|
|
15
|
-
--_accent: #b892ff;
|
|
15
|
+
--_accent: #b892ff; --_danger: #ff6b8a;
|
|
16
16
|
--_bg: #1b1920; --_sunk: #131217; --_ink: #f1eef5; --_ink-2: #bdb7c6; --_ink-3: #8a8494; --_rule: #2f2c36;
|
|
17
17
|
--_shadow: 0 1px 2px rgb(0 0 0 / 0.3), 0 18px 48px rgb(0 0 0 / 0.5);
|
|
18
18
|
}
|
|
@@ -145,18 +145,49 @@ html.slop-dark {
|
|
|
145
145
|
.sp-body > .sp-field { margin-left: 2px; }
|
|
146
146
|
.sp-flash { background: color-mix(in srgb, var(--_accent) 14%, transparent); }
|
|
147
147
|
.sp-flabel { display: flex; align-items: center; gap: 6px; min-height: 24px; }
|
|
148
|
-
.sp-
|
|
148
|
+
.sp-fend { display: flex; align-items: center; gap: 6px; margin-left: auto; }
|
|
149
|
+
.sp-flabel label { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: 0.76rem; font-weight: 600; color: var(--_ink-3); }
|
|
150
|
+
/* the box's own letters are see-through: the words behind it show each author's color */
|
|
151
|
+
.sp-ink { position: relative; }
|
|
152
|
+
.sp-field textarea, .sp-mirror { padding: 7px 9px; font: 0.86rem/1.5 var(--_mono); letter-spacing: normal; white-space: pre-wrap; overflow-wrap: break-word; word-break: normal; tab-size: 4; border: 1px solid transparent; border-radius: 8px; }
|
|
153
|
+
.sp-mirror { position: absolute; inset: 0; margin: 0; overflow: hidden; color: var(--_ink); background: var(--_sunk); pointer-events: none; }
|
|
154
|
+
.sp-ink:focus-within .sp-mirror { background: var(--_bg); }
|
|
149
155
|
.sp-field textarea {
|
|
150
|
-
display: block; width: 100%; margin: 0;
|
|
151
|
-
|
|
156
|
+
position: relative; display: block; width: 100%; margin: 0; resize: none; overflow: hidden;
|
|
157
|
+
color: transparent; caret-color: var(--_ink); background: transparent;
|
|
152
158
|
}
|
|
159
|
+
.sp-field textarea::selection { color: transparent; background: color-mix(in srgb, var(--_accent) 28%, transparent); }
|
|
153
160
|
.sp-field textarea:hover { border-color: var(--_rule); }
|
|
154
|
-
.sp-field textarea:focus { outline: none; border-color: var(--_accent);
|
|
161
|
+
.sp-field textarea:focus { outline: none; border-color: var(--_accent); box-shadow: 0 0 0 3px color-mix(in srgb, var(--_accent) 18%, transparent); }
|
|
155
162
|
.sp-kind { flex: none; padding: 1px 6px; border-radius: 4px; background: color-mix(in srgb, var(--_accent) 12%, transparent); font: 600 0.68rem var(--_font); color: var(--_accent); }
|
|
156
163
|
.sp-kind[hidden] { display: none; }
|
|
157
164
|
.sp-unseen { flex: none; padding: 1px 6px; border: 0; border-radius: 4px; background: var(--_sunk); font: 600 0.68rem var(--_font); color: var(--_ink-3) !important; cursor: help; }
|
|
158
165
|
.sp-unseen:not(:disabled) { color: var(--_accent) !important; cursor: pointer; }
|
|
159
166
|
.sp-unseen:not(:disabled):hover { background: color-mix(in srgb, var(--_accent) 12%, transparent); }
|
|
167
|
+
/* a list's removed texts, until the next save, and a way to start an emptied one */
|
|
168
|
+
.sp-trash { flex: none; display: inline-flex; align-items: center; gap: 4px; height: 22px; padding: 0 4px; border: 0; border-radius: 5px; background: none; font: 600 0.72rem var(--_font); color: var(--_ink-3) !important; cursor: pointer; }
|
|
169
|
+
.sp-trash:hover { background: var(--_sunk); color: var(--_danger) !important; }
|
|
170
|
+
.sp-trash:focus-visible { outline: 2px solid var(--_accent); outline-offset: 1px; }
|
|
171
|
+
.sp-trash[data-armed] { color: var(--_danger) !important; background: color-mix(in srgb, var(--_danger) 10%, transparent); }
|
|
172
|
+
.sp-removing .sp-mirror { background: color-mix(in srgb, var(--_danger) 9%, var(--_bg)); }
|
|
173
|
+
.sp-removing textarea { border-color: var(--_danger) !important; }
|
|
174
|
+
/* the + under a text in a list, on the text you're on: a hairline with a + in the middle. Pointing at it colors both
|
|
175
|
+
and names it */
|
|
176
|
+
.sp-insert {
|
|
177
|
+
display: flex; align-items: center; gap: 6px; width: 100%; height: 18px; margin: 1px 0 -4px; padding: 0; border: 0; background: none;
|
|
178
|
+
font: 600 0.72rem var(--_font); color: var(--_ink-3) !important; cursor: pointer;
|
|
179
|
+
opacity: 0; transition: opacity .15s; /* only on the text you're on */
|
|
180
|
+
}
|
|
181
|
+
.sp-field:hover .sp-insert, .sp-field:focus-within .sp-insert { opacity: 1; }
|
|
182
|
+
.sp-insert::before, .sp-insert::after { content: ""; flex: 1; height: 1px; background: var(--_rule); transition: background .15s; }
|
|
183
|
+
.sp-plus { display: grid; place-items: center; width: 16px; height: 16px; border: 1px solid var(--_rule); border-radius: 50%; background: var(--_bg); font-size: 0.8rem; line-height: 1; transition: border-color .15s, background .15s, color .15s; }
|
|
184
|
+
.sp-insert-label { max-width: 0; overflow: hidden; white-space: nowrap; opacity: 0; transition: max-width .2s, opacity .2s; }
|
|
185
|
+
.sp-insert:hover, .sp-insert:focus-visible { color: var(--_accent) !important; outline: none; }
|
|
186
|
+
.sp-insert:hover::before, .sp-insert:hover::after, .sp-insert:focus-visible::before, .sp-insert:focus-visible::after { background: var(--_accent); }
|
|
187
|
+
.sp-insert:hover .sp-plus, .sp-insert:focus-visible .sp-plus { border-color: var(--_accent); background: var(--_accent); color: var(--_bg); }
|
|
188
|
+
.sp-insert:hover .sp-insert-label, .sp-insert:focus-visible .sp-insert-label { max-width: 8em; opacity: 1; }
|
|
189
|
+
.sp-gone { margin: 0 2px 12px 18px; padding: 5px 9px; border: 1px dashed var(--_rule); border-radius: 8px; font-size: 0.76rem; color: var(--_ink-3); }
|
|
190
|
+
.sp-start { margin: 0 2px 14px 18px; }
|
|
160
191
|
.sp-hint { padding: 2px 2px 0; font-size: 0.76rem; color: var(--_ink-2); }
|
|
161
192
|
|
|
162
193
|
/* a pie of what the text is made of, and its slop switch */
|
|
@@ -200,11 +231,20 @@ html.slop-dark {
|
|
|
200
231
|
.sp-goto:hover { border-color: var(--_ink-3); color: var(--_ink) !important; }
|
|
201
232
|
.sp-pie.sp-mini { width: 10px; height: 10px; }
|
|
202
233
|
|
|
234
|
+
/* a text with no words isn't on the page, except while the editor is open */
|
|
235
|
+
html:not(.slop-editing) .slop-empty { display: none !important; }
|
|
236
|
+
.slop-editing .slop-empty { min-height: 1em; min-height: 1lh; outline: 1px dashed color-mix(in srgb, var(--_accent) 40%, transparent); outline-offset: 3px; }
|
|
237
|
+
|
|
203
238
|
/* on the page, while the editor is open */
|
|
204
|
-
.slop-editing [data-slop] { cursor: text; }
|
|
205
|
-
.slop-editing [data-slop]:hover { outline: 1px dashed color-mix(in srgb, var(--_accent) 60%, transparent); outline-offset: 3px; border-radius: 2px; }
|
|
239
|
+
.slop-editing [data-slop], .slop-editing [data-slop-more] { cursor: text; }
|
|
240
|
+
.slop-editing [data-slop]:hover, .slop-editing [data-slop-more]:hover { outline: 1px dashed color-mix(in srgb, var(--_accent) 60%, transparent); outline-offset: 3px; border-radius: 2px; }
|
|
206
241
|
.slop-focus { outline: 2px solid var(--_accent) !important; outline-offset: 3px; border-radius: 2px; }
|
|
207
242
|
.slop-copy { outline: 2px dashed var(--_accent) !important; outline-offset: 3px; border-radius: 2px; }
|
|
243
|
+
/* where a new paragraph would go, and what Remove would take */
|
|
244
|
+
.slop-insert-after { position: relative; }
|
|
245
|
+
.slop-insert-after::after { content: ""; position: absolute; left: 0; right: 0; top: calc(100% + 0.5em - 1px); border-top: 2px solid var(--_accent); pointer-events: none; }
|
|
246
|
+
.slop-remove-hint { outline: 2px dashed var(--_danger) !important; outline-offset: 3px; border-radius: 2px; }
|
|
247
|
+
.slop-removing { outline: 2px dashed var(--_danger) !important; outline-offset: 3px; border-radius: 2px; background: color-mix(in srgb, var(--_danger) 12%, transparent); }
|
|
208
248
|
|
|
209
249
|
@media (max-width: 900px) {
|
|
210
250
|
.slop-panel { top: auto; left: 8px; right: 8px; bottom: 8px; width: auto; height: 60svh; }
|
package/slop.js
CHANGED
|
@@ -11,7 +11,11 @@
|
|
|
11
11
|
Inside any text: [label](url) is a link, **bold**, *italic*, `code`, [[key]] a key cap, {name} a value the page
|
|
12
12
|
fills in (Slop.vars), and \ makes the next character literal.
|
|
13
13
|
|
|
14
|
-
|
|
14
|
+
A blank line starts a new paragraph in a <p>, <li> or <dd>.
|
|
15
|
+
|
|
16
|
+
Elements with data-slop="group.key" are filled from the block. Code renders the rest with Slop.html(path). An
|
|
17
|
+
element with data-slop-list="group" shows each text in that group in a copy of its first child, and the editor can
|
|
18
|
+
add and remove texts there (data-slop-list-ref: the page draws them itself).
|
|
15
19
|
An element with data-slop-meter becomes the Slop-o-meter switch. Under `slop-editor edit`, the page also gets the
|
|
16
20
|
editor, which saves back into the file; with Slop.start({edit: 'local'}) it gets one that saves in the browser. */
|
|
17
21
|
const Slop = (() => {
|
|
@@ -57,16 +61,31 @@ const Slop = (() => {
|
|
|
57
61
|
|
|
58
62
|
// `value` after its plain text became `next` in the editor. An edit is one stretch replaced (typing, deleting,
|
|
59
63
|
// pasting): what both versions share at the start and the end keeps its author, and the new middle is mine.
|
|
60
|
-
// Unless it's an undo or a redo: then `was`, an earlier version whose plain text is `next`, says who wrote it
|
|
61
|
-
|
|
64
|
+
// Unless it's an undo or a redo: then `was`, an earlier version whose plain text is `next`, says who wrote it.
|
|
65
|
+
// `at`, the [start, end) of `value` the edit replaced (the selection typed over), when the editor knows it: typing
|
|
66
|
+
// "c" over a selected "cat" makes that "c" mine, though it matches the letter that was there
|
|
67
|
+
function applyEdit(value, next, was, at) {
|
|
62
68
|
const prev = plain(value);
|
|
63
|
-
|
|
69
|
+
const typedOver = at && at[1] > at[0];
|
|
70
|
+
if (prev === next && !typedOver) return value;
|
|
64
71
|
let start = 0;
|
|
65
|
-
while (start < prev.length && start < next.length && prev[start] === next[start]) start++;
|
|
66
72
|
let end = 0;
|
|
67
|
-
|
|
68
|
-
|
|
73
|
+
if (at && next.startsWith(prev.slice(0, at[0])) && next.endsWith(prev.slice(at[1])) && next.length - (prev.length - at[1]) >= at[0]) {
|
|
74
|
+
start = at[0];
|
|
75
|
+
end = prev.length - at[1];
|
|
76
|
+
} else {
|
|
77
|
+
while (start < prev.length && start < next.length && prev[start] === next[start]) start++;
|
|
78
|
+
while (end < prev.length - start && end < next.length - start
|
|
79
|
+
&& prev[prev.length - 1 - end] === next[next.length - 1 - end]) end++;
|
|
80
|
+
}
|
|
69
81
|
const authors = authorsByChar(value);
|
|
82
|
+
if (was != null && plain(was) === next) {
|
|
83
|
+
// an undo takes back what was typed: my letters at the edges of the stretch that the earlier version doesn't
|
|
84
|
+
// have as mine (an "a" typed over "agent" matches the "a" there, so it looks shared) go back with it
|
|
85
|
+
const old = authorsByChar(was);
|
|
86
|
+
while (start > 0 && authors[start - 1] === 'me' && old[start - 1] !== 'me') start--;
|
|
87
|
+
while (end > 0 && authors[prev.length - end] === 'me' && old[next.length - end] !== 'me') end--;
|
|
88
|
+
}
|
|
70
89
|
const middle = was != null && plain(was) === next
|
|
71
90
|
? authorsByChar(was).slice(start, next.length - end)
|
|
72
91
|
: new Array(next.length - start - end).fill('me');
|
|
@@ -128,6 +147,20 @@ const Slop = (() => {
|
|
|
128
147
|
return out;
|
|
129
148
|
}
|
|
130
149
|
|
|
150
|
+
// a text in paragraphs: split at blank lines, each keeping its authors. Without a blank line it's one paragraph
|
|
151
|
+
function paragraphsOf(value) {
|
|
152
|
+
const text = plain(value);
|
|
153
|
+
const authors = authorsByChar(value);
|
|
154
|
+
const spans = [];
|
|
155
|
+
const gap = /\n[ \t]*\n\s*/g;
|
|
156
|
+
let at = 0;
|
|
157
|
+
for (let m; (m = gap.exec(text));) { spans.push([at, m.index]); at = m.index + m[0].length; }
|
|
158
|
+
if (!spans.length) return [value];
|
|
159
|
+
spans.push([at, text.length]);
|
|
160
|
+
const parts = spans.map(([s, e]) => fromChars(text.slice(s, e), authors.slice(s, e))).filter((p) => plain(p).trim());
|
|
161
|
+
return parts.length ? parts : [value];
|
|
162
|
+
}
|
|
163
|
+
|
|
131
164
|
// values the page fills in: {html, data} (data: a fact, shown in the data color; otherwise it takes the color of
|
|
132
165
|
// whoever wrote the {name}), or a plain string or number (a fact)
|
|
133
166
|
const vars = {};
|
|
@@ -229,7 +262,7 @@ const Slop = (() => {
|
|
|
229
262
|
return [...byWords].filter(([, paths]) => paths.length > 1).map(([words, paths]) => ({ words, paths }));
|
|
230
263
|
}
|
|
231
264
|
|
|
232
|
-
const core = { BUILTIN, plain, applyEdit, reslop, unslop, assign, reattribute, runs, readable, render, makeup, share, percent, repeats, wordsOf, vars };
|
|
265
|
+
const core = { BUILTIN, plain, applyEdit, reslop, unslop, assign, reattribute, runs, readable, render, makeup, share, percent, repeats, wordsOf, paragraphsOf, vars };
|
|
233
266
|
if (typeof document === 'undefined') return core; // Node (the CLI and the tests) only needs the format
|
|
234
267
|
|
|
235
268
|
/* ---------- the block ---------- */
|
|
@@ -251,6 +284,9 @@ const Slop = (() => {
|
|
|
251
284
|
if (!isText(node)) { console.warn(`slop: no text at ${dotted(path)}`); return ''; }
|
|
252
285
|
return node;
|
|
253
286
|
}
|
|
287
|
+
const nodeAt = (root, path) => keysOf(path).reduce((node, key) => node?.[key], root);
|
|
288
|
+
// the keys of a group's texts, in order
|
|
289
|
+
const textKeys = (node) => (node && typeof node === 'object' && !isText(node) ? Object.keys(node).filter((k) => isText(node[k])) : []);
|
|
254
290
|
function set(path, value) {
|
|
255
291
|
const keys = keysOf(path);
|
|
256
292
|
let node = text;
|
|
@@ -269,13 +305,15 @@ const Slop = (() => {
|
|
|
269
305
|
// the texts an element holds in its attributes, from data-slop-attr="alt:hero.photo title:hero.tip": [[name, path]]
|
|
270
306
|
const attrsOf = (x) => (x.dataset.slopAttr ?? '').split(/\s+/).map((s) => [s.slice(0, s.indexOf(':')), s.slice(s.indexOf(':') + 1)]).filter(([n, p]) => n && p);
|
|
271
307
|
// the elements that show a text: [data-slop] ones, which fill() writes, [data-slop-ref] ones, which the page writes
|
|
272
|
-
// itself (words inside a button or a link it builds) but the editor can still find,
|
|
308
|
+
// itself (words inside a button or a link it builds) but the editor can still find, [data-slop-more] ones (the
|
|
309
|
+
// paragraphs after a blank line) and [data-slop-attr] ones
|
|
273
310
|
const elementsOf = (path) => {
|
|
274
311
|
const at = dotted(path);
|
|
275
312
|
const q = CSS.escape(at);
|
|
276
|
-
return [...document.querySelectorAll(`[data-slop="${q}"], [data-slop-ref="${q}"], [data-slop-attr*=":${q}"]`)]
|
|
277
|
-
.filter((x) => x.dataset.slop === at || x.dataset.slopRef === at || attrsOf(x).some(([, p]) => p === at));
|
|
313
|
+
return [...document.querySelectorAll(`[data-slop="${q}"], [data-slop-ref="${q}"], [data-slop-more="${q}"], [data-slop-attr*=":${q}"]`)]
|
|
314
|
+
.filter((x) => x.dataset.slop === at || x.dataset.slopRef === at || x.dataset.slopMore === at || attrsOf(x).some(([, p]) => p === at));
|
|
278
315
|
};
|
|
316
|
+
const pathOf = (x) => x.dataset.slop || x.dataset.slopRef || x.dataset.slopMore || attrsOf(x)[0]?.[1];
|
|
279
317
|
// a text the page has but doesn't show as words (alt text, a tooltip, a label): the attribute it's in, or ''
|
|
280
318
|
function attrOf(path) {
|
|
281
319
|
const at = dotted(path);
|
|
@@ -290,6 +328,8 @@ const Slop = (() => {
|
|
|
290
328
|
const rendered = new Set();
|
|
291
329
|
const html = (path, local) => { rendered.add(dotted(path)); return render(get(path), local); };
|
|
292
330
|
const words = (path, local) => { rendered.add(dotted(path)); return readable(get(path), local); };
|
|
331
|
+
// the text as HTML, one string per paragraph, for code that draws a <p> for each
|
|
332
|
+
const paragraphs = (path, local) => { rendered.add(dotted(path)); return paragraphsOf(get(path)).map((v) => render(v, local)); };
|
|
293
333
|
const onPage = (path) => rendered.has(dotted(path)) || elementsOf(path).length > 0;
|
|
294
334
|
// how to show a text the page shows only some of the time: Slop.reveal(path, fn), where fn puts the page in a state
|
|
295
335
|
// that shows it and returns a function that undoes that. A group's key covers all its texts
|
|
@@ -298,21 +338,93 @@ const Slop = (() => {
|
|
|
298
338
|
const revealerOf = (path) => revealers.get(dotted(path)) ?? revealers.get(keysOf(path)[0]);
|
|
299
339
|
// fill every [data-slop] element (data-slop-vars: a JSON object of extra values)
|
|
300
340
|
// fill an element: its words from data-slop, its attributes from data-slop-attr (as plain text)
|
|
341
|
+
// a <p>, <li> or <dd> shows a text's first paragraph, and a copy of it after it shows each of the others. An
|
|
342
|
+
// element whose text is empty gets .slop-empty, which hides it
|
|
343
|
+
const SPLITS = /^(P|LI|DD)$/;
|
|
344
|
+
const spills = new WeakMap(); // element → the copies after it
|
|
345
|
+
const ownerOf = new WeakMap(); // copy → its element
|
|
301
346
|
function fillOne(el) {
|
|
302
347
|
const local = el.dataset.slopVars ? JSON.parse(el.dataset.slopVars) : undefined;
|
|
303
348
|
if (el.dataset.slop) {
|
|
304
|
-
const
|
|
349
|
+
const value = get(el.dataset.slop);
|
|
350
|
+
const parts = SPLITS.test(el.tagName) ? paragraphsOf(value) : [value];
|
|
351
|
+
const h = render(parts[0], local);
|
|
305
352
|
if (el.innerHTML !== h) el.innerHTML = h;
|
|
353
|
+
el.classList.toggle('slop-empty', !plain(value).trim());
|
|
354
|
+
spill(el, parts.slice(1).map((v) => render(v, local)));
|
|
306
355
|
}
|
|
307
356
|
attrsOf(el).forEach(([name, path]) => {
|
|
308
357
|
const v = readable(get(path), local);
|
|
309
358
|
if (el.getAttribute(name) !== v) el.setAttribute(name, v);
|
|
310
359
|
});
|
|
311
360
|
}
|
|
312
|
-
|
|
361
|
+
function spill(el, htmls) {
|
|
362
|
+
const copies = spills.get(el) ?? [];
|
|
363
|
+
while (copies.length > htmls.length) copies.pop().remove();
|
|
364
|
+
htmls.forEach((h, i) => {
|
|
365
|
+
let c = copies[i];
|
|
366
|
+
if (!c) {
|
|
367
|
+
c = el.cloneNode(false);
|
|
368
|
+
['id', 'data-slop', 'data-slop-attr'].forEach((a) => c.removeAttribute(a));
|
|
369
|
+
c.classList.remove('slop-focus', 'slop-copy', 'slop-empty');
|
|
370
|
+
ownerOf.set(c, el);
|
|
371
|
+
copies.push(c);
|
|
372
|
+
}
|
|
373
|
+
c.dataset.slopMore = el.dataset.slop;
|
|
374
|
+
if (c.innerHTML !== h) c.innerHTML = h;
|
|
375
|
+
const before = i ? copies[i - 1] : el;
|
|
376
|
+
if (before.nextElementSibling !== c) before.after(c);
|
|
377
|
+
});
|
|
378
|
+
if (copies.length) spills.set(el, copies); else spills.delete(el);
|
|
379
|
+
}
|
|
380
|
+
// a list: an element with data-slop-list="group" shows each text in that group, in order, in a copy of its first
|
|
381
|
+
// child. (With data-slop-list-ref, the page draws them itself.) Either way, the editor can add and remove texts there
|
|
382
|
+
const templates = new WeakMap(); // list → the element its texts are copies of
|
|
383
|
+
function fillList(box) {
|
|
384
|
+
const at = box.dataset.slopList;
|
|
385
|
+
if (!templates.has(box)) {
|
|
386
|
+
if (!box.firstElementChild) return;
|
|
387
|
+
const t = box.firstElementChild.cloneNode(false);
|
|
388
|
+
['id', 'data-slop'].forEach((a) => t.removeAttribute(a));
|
|
389
|
+
templates.set(box, t);
|
|
390
|
+
}
|
|
391
|
+
const paths = textKeys(nodeAt(text, at)).map((k) => `${at}.${k}`);
|
|
392
|
+
const have = new Map([...box.children].filter((x) => x.dataset.slop).map((x) => [x.dataset.slop, x]));
|
|
393
|
+
have.forEach((x, p) => { if (!paths.includes(p)) { spill(x, []); x.remove(); } });
|
|
394
|
+
let last = null;
|
|
395
|
+
paths.forEach((p) => {
|
|
396
|
+
let x = have.get(p);
|
|
397
|
+
if (!x) {
|
|
398
|
+
x = templates.get(box).cloneNode(false);
|
|
399
|
+
x.dataset.slop = p;
|
|
400
|
+
}
|
|
401
|
+
if (last ? last.nextElementSibling !== x : box.firstElementChild !== x) (last ? last.after(x) : box.prepend(x));
|
|
402
|
+
last = spills.get(x)?.at(-1) ?? x;
|
|
403
|
+
});
|
|
404
|
+
}
|
|
405
|
+
const fill = (root = document) => {
|
|
406
|
+
root.querySelectorAll('[data-slop-list]').forEach(fillList);
|
|
407
|
+
root.querySelectorAll('[data-slop], [data-slop-attr]').forEach(fillOne);
|
|
408
|
+
// paragraphs whose element the page took away, or no longer shows that text in
|
|
409
|
+
root.querySelectorAll('[data-slop-more]').forEach((c) => {
|
|
410
|
+
const el = ownerOf.get(c);
|
|
411
|
+
if (!el?.isConnected || el.dataset.slop !== c.dataset.slopMore) c.remove();
|
|
412
|
+
});
|
|
413
|
+
};
|
|
414
|
+
// the editor's "not on the page" tags, checked again once the page has drawn what changed (a text just added or
|
|
415
|
+
// restored has no element until then, and a single-page app draws later still)
|
|
416
|
+
let reseen = () => {};
|
|
417
|
+
let seenPending = false;
|
|
418
|
+
const seenSoon = () => {
|
|
419
|
+
if (seenPending) return;
|
|
420
|
+
seenPending = true;
|
|
421
|
+
requestAnimationFrame(() => { seenPending = false; reseen(); });
|
|
422
|
+
};
|
|
313
423
|
// the [data-slop] elements and meters in what the page added after start (a single-page app draws late)
|
|
314
424
|
function added(n) {
|
|
315
425
|
if (n.nodeType !== 1 || n.closest('.slop-panel')) return;
|
|
426
|
+
seenSoon();
|
|
427
|
+
if (n.matches('[data-slop-list]')) fillList(n);
|
|
316
428
|
if (n.matches('[data-slop], [data-slop-attr]')) fillOne(n);
|
|
317
429
|
fill(n);
|
|
318
430
|
if (n.matches('[data-slop-meter]')) meter(n);
|
|
@@ -334,6 +446,7 @@ const Slop = (() => {
|
|
|
334
446
|
fill();
|
|
335
447
|
listeners.forEach((fn) => { try { fn(); } catch (e) { console.error(e); } });
|
|
336
448
|
paintMeters();
|
|
449
|
+
seenSoon();
|
|
337
450
|
});
|
|
338
451
|
}
|
|
339
452
|
|
|
@@ -425,11 +538,13 @@ const Slop = (() => {
|
|
|
425
538
|
|
|
426
539
|
/* ---------- Slop-o-meter: a switch, a pie of what the page is made of, and what its colors mean ---------- */
|
|
427
540
|
|
|
428
|
-
const
|
|
429
|
-
get: (k) => { try { return
|
|
430
|
-
set: (k, v) => { try {
|
|
431
|
-
drop: (k) => { try {
|
|
432
|
-
};
|
|
541
|
+
const storage = (area) => ({
|
|
542
|
+
get: (k) => { try { return area().getItem(k); } catch { return null; } },
|
|
543
|
+
set: (k, v) => { try { area().setItem(k, v); } catch { /* optional */ } },
|
|
544
|
+
drop: (k) => { try { area().removeItem(k); } catch { /* optional */ } },
|
|
545
|
+
});
|
|
546
|
+
const store = storage(() => localStorage);
|
|
547
|
+
const session = storage(() => sessionStorage); // this tab only: the unsaved draft
|
|
433
548
|
// what readers see is the page's choice, "nothing" unless it says otherwise. While the editor is open, its
|
|
434
549
|
// author sees the colors whatever readers get
|
|
435
550
|
const SHOW = ['nothing', 'pie', 'colors'];
|
|
@@ -525,10 +640,18 @@ const Slop = (() => {
|
|
|
525
640
|
const title = node && !isText(node) && isText(node.title) ? readable(node.title) : '';
|
|
526
641
|
return title && title.length <= 32 ? title : human(key);
|
|
527
642
|
};
|
|
643
|
+
// the groups the page shows as lists, where the editor can add and remove texts
|
|
644
|
+
const listed = () => new Set([...document.querySelectorAll('[data-slop-list], [data-slop-list-ref]')].map((x) => x.dataset.slopList || x.dataset.slopListRef));
|
|
645
|
+
// keys[i], for people. In a list, a paragraph is named by where it is: "Paragraph 3", even when its key is p7
|
|
646
|
+
function keyName(keys, i) {
|
|
647
|
+
const group = keys.slice(0, i).join('.');
|
|
648
|
+
if (!/^p\d+$/.test(keys[i]) || !listed().has(group)) return human(keys[i]);
|
|
649
|
+
return `Paragraph ${textKeys(nodeAt(text, group)).indexOf(keys[i]) + 1}`;
|
|
650
|
+
}
|
|
528
651
|
// where a text is, for people: "Introduction · Paragraph 2"
|
|
529
652
|
const where = (path) => {
|
|
530
|
-
const
|
|
531
|
-
return [groupTitle(
|
|
653
|
+
const keys = keysOf(path);
|
|
654
|
+
return [groupTitle(keys[0]), ...keys.slice(1).map((k, i) => keyName(keys, i + 1))].join(' · ');
|
|
532
655
|
};
|
|
533
656
|
const count = (n, one, many = `${one}s`) => `${n.toLocaleString()} ${n === 1 ? one : many}`;
|
|
534
657
|
const isLong = (path, value) => plain(value).length > 48 || /^p\d+$/.test(keysOf(path).at(-1));
|
|
@@ -622,7 +745,8 @@ const Slop = (() => {
|
|
|
622
745
|
return true;
|
|
623
746
|
}
|
|
624
747
|
|
|
625
|
-
/* the slop switch, next to a pie of what the texts are made of
|
|
748
|
+
/* the slop switch, next to a pie of what the texts are made of. A text's or section's row takes the pie out, to
|
|
749
|
+
sit by its name, and puts the switch at the end (c.pie, c.toggle) */
|
|
626
750
|
function control(paths, what, after) {
|
|
627
751
|
const c = el('span', 'sp-ctl', '<span class="sp-pie" role="img"></span>'
|
|
628
752
|
+ '<button type="button" class="sp-toggle" role="switch"><span class="sp-switch" aria-hidden="true"></span>slop</button>');
|
|
@@ -633,16 +757,18 @@ const Slop = (() => {
|
|
|
633
757
|
const done = withUndo(on ? `Approved ${what}` : `Back to slop: ${what}`, () => paths().forEach((p) => set(p, on ? unslop(get(p)) : reslop(get(p)))));
|
|
634
758
|
if (done) after?.(on);
|
|
635
759
|
});
|
|
760
|
+
c.pie = c.querySelector('.sp-pie');
|
|
761
|
+
c.toggle = toggle;
|
|
636
762
|
controls.push({ el: c, paths });
|
|
637
763
|
return c;
|
|
638
764
|
}
|
|
639
765
|
function paintControl({ el: c, paths }, cats) {
|
|
640
|
-
const m = makeup(paths().map(
|
|
641
|
-
const pie = c
|
|
766
|
+
const m = makeup(paths().map((p) => valueAt(text, p) ?? '')); // a text just taken out is painted once more
|
|
767
|
+
const { pie } = c;
|
|
642
768
|
pie.style.background = gradient(m, cats);
|
|
643
769
|
pie.title = breakdown(m, cats);
|
|
644
770
|
pie.setAttribute('aria-label', pie.title);
|
|
645
|
-
const toggle = c
|
|
771
|
+
const { toggle } = c;
|
|
646
772
|
const on = (m.counts.ai ?? 0) > 0;
|
|
647
773
|
toggle.setAttribute('aria-checked', String(on));
|
|
648
774
|
toggle.disabled = !on && !m.counts.ok;
|
|
@@ -739,7 +865,7 @@ const Slop = (() => {
|
|
|
739
865
|
assignEl.append(b);
|
|
740
866
|
});
|
|
741
867
|
assignLabel(input);
|
|
742
|
-
wrap.append(assignEl);
|
|
868
|
+
if (wrap.insert) wrap.insert.before(assignEl); else wrap.append(assignEl); // the + stays last
|
|
743
869
|
}
|
|
744
870
|
const assignLabel = (input) => {
|
|
745
871
|
if (assignEl.firstChild) assignEl.firstChild.textContent = input.selectionStart === input.selectionEnd ? 'Mark all as' : 'Mark selection as';
|
|
@@ -773,11 +899,13 @@ const Slop = (() => {
|
|
|
773
899
|
const wrap = el('div', 'sp-field');
|
|
774
900
|
wrap.dataset.path = path;
|
|
775
901
|
const fid = `sp-${path.replace(/\W/g, '-')}${all ? '-all' : ''}`;
|
|
776
|
-
const
|
|
902
|
+
const keys = keysOf(path);
|
|
903
|
+
const name = all ? `${all.paths.length} copies` : keys.slice(1).map((k, i) => keyName(keys, i + 1)).join(' · ') || human(path);
|
|
777
904
|
wrap.innerHTML = `<div class="sp-flabel"><label for="${fid}">${esc(name)}</label>`
|
|
778
|
-
+ '<span class="sp-kind" hidden></span><button type="button" class="sp-unseen" hidden></button></div>'
|
|
779
|
-
+ `<textarea id="${fid}" rows="1" spellcheck="true"></textarea
|
|
780
|
-
|
|
905
|
+
+ '<span class="sp-fend"><span class="sp-kind" hidden></span><button type="button" class="sp-unseen" hidden></button></span></div>'
|
|
906
|
+
+ `<div class="sp-ink"><div class="sp-mirror" aria-hidden="true"></div><textarea id="${fid}" rows="1" spellcheck="true"></textarea></div>`
|
|
907
|
+
+ '<p class="sp-hint" hidden></p>';
|
|
908
|
+
const row = wrap.querySelector('.sp-fend'); // the meter sits by the name; the rest at the end of the row
|
|
781
909
|
const input = wrap.querySelector('textarea');
|
|
782
910
|
input.value = plain(value);
|
|
783
911
|
if (!isLong(path, value)) input.addEventListener('keydown', (e) => { if (e.key === 'Enter') e.preventDefault(); });
|
|
@@ -790,6 +918,12 @@ const Slop = (() => {
|
|
|
790
918
|
withUndo(`Reverted "${all ? all.words : where(path)}"`, () => paths().forEach((p) => { if (savedAt(p) !== undefined) set(p, savedAt(p)); }));
|
|
791
919
|
render();
|
|
792
920
|
});
|
|
921
|
+
const group = keys.slice(0, -1).join('.');
|
|
922
|
+
const listItem = !all && group && listed().has(group);
|
|
923
|
+
if (listItem) {
|
|
924
|
+
wrap.insert = plusRow(path, group);
|
|
925
|
+
wrap.append(wrap.insert);
|
|
926
|
+
}
|
|
793
927
|
row.append(revert);
|
|
794
928
|
if (!all) {
|
|
795
929
|
const rep = el('button', 'sp-rep');
|
|
@@ -797,8 +931,9 @@ const Slop = (() => {
|
|
|
797
931
|
rep.addEventListener('click', () => { const s = setOf(path); if (s) show('repeats', s.paths[0]); });
|
|
798
932
|
row.append(rep);
|
|
799
933
|
}
|
|
800
|
-
// a copy's switch changes that copy only, and says so. A Repeats card's switch changes every copy
|
|
801
|
-
row
|
|
934
|
+
// a copy's switch changes that copy only, and says so. A Repeats card's switch changes every copy.
|
|
935
|
+
// The row reads: name and pie, then at the end anything else, the trash can and the switch
|
|
936
|
+
const ctl = control(paths, all ? count(all.paths.length, 'copy', 'copies') : `"${where(path)}"`, all ? null : (approved) => {
|
|
802
937
|
const others = (setOf(path)?.paths ?? []).filter((p) => p !== path);
|
|
803
938
|
if (!others.length) return;
|
|
804
939
|
const how = approved ? unslop : reslop;
|
|
@@ -806,8 +941,17 @@ const Slop = (() => {
|
|
|
806
941
|
label: others.length === 1 ? 'Change it too' : 'Change them too',
|
|
807
942
|
run: () => withUndo(`${approved ? 'Approved' : 'Back to slop:'} ${count(others.length + 1, 'copy', 'copies')}`, () => others.forEach((p) => set(p, how(get(p))))),
|
|
808
943
|
});
|
|
809
|
-
})
|
|
810
|
-
|
|
944
|
+
});
|
|
945
|
+
row.before(ctl.pie);
|
|
946
|
+
if (listItem) row.append(removeButton(path, wrap));
|
|
947
|
+
row.append(ctl);
|
|
948
|
+
// the stretch a keystroke or a paste replaces: the selection, or nothing at the caret
|
|
949
|
+
input.addEventListener('beforeinput', () => { input.at = [input.selectionStart, input.selectionEnd]; });
|
|
950
|
+
input.addEventListener('input', (e) => {
|
|
951
|
+
const restoring = /^history(Undo|Redo)$/.test(e.inputType);
|
|
952
|
+
edit(paths(), input, restoring, restoring || e.isComposing || /Composition/.test(e.inputType) ? undefined : input.at);
|
|
953
|
+
input.at = undefined;
|
|
954
|
+
});
|
|
811
955
|
['select', 'keyup', 'pointerup'].forEach((t) => input.addEventListener(t, () => assignLabel(input)));
|
|
812
956
|
input.addEventListener('focus', () => { focus(path, all, input, wrap); showAssign(wrap, input, paths()); });
|
|
813
957
|
input.addEventListener('blur', () => {
|
|
@@ -821,6 +965,7 @@ const Slop = (() => {
|
|
|
821
965
|
});
|
|
822
966
|
wrap.querySelector('.sp-unseen').addEventListener('click', () => input.focus());
|
|
823
967
|
wrap.input = input;
|
|
968
|
+
wrap.mirror = wrap.querySelector('.sp-mirror');
|
|
824
969
|
wrap.rep = wrap.querySelector('.sp-rep');
|
|
825
970
|
wrap.kind = wrap.querySelector('.sp-kind');
|
|
826
971
|
wrap.revert = revert;
|
|
@@ -832,16 +977,144 @@ const Slop = (() => {
|
|
|
832
977
|
const det = el('details', 'sp-group', `<summary><span class="sp-gname">${esc(groupTitle(key))}</span><span class="sp-gnote"></span></summary>`);
|
|
833
978
|
det.dataset.group = key;
|
|
834
979
|
det.open = state.open.has(key) || state.tab === 'hidden'; // there are few, so all of them show
|
|
835
|
-
const all = entries(text[key], [key]).map(([p]) => p);
|
|
836
|
-
|
|
980
|
+
const all = () => entries(text[key], [key]).map(([p]) => p);
|
|
981
|
+
const ctl = control(all, `"${groupTitle(key)}"`);
|
|
982
|
+
det.querySelector('.sp-gname').after(ctl.pie);
|
|
983
|
+
det.querySelector('summary').append(ctl);
|
|
837
984
|
det.addEventListener('toggle', () => {
|
|
838
985
|
if (det.open) { state.open.add(key); det.querySelectorAll('textarea').forEach(grow); } else state.open.delete(key);
|
|
839
986
|
});
|
|
840
987
|
paths.forEach((p) => det.append(field(p)));
|
|
988
|
+
if (state.tab === 'all') listRows(key, det);
|
|
841
989
|
return det;
|
|
842
990
|
}
|
|
843
991
|
|
|
992
|
+
// the words behind a text box, each in its author's color. The box's own letters are see-through
|
|
993
|
+
function paintInk(wrap) {
|
|
994
|
+
const value = valueAt(text, wrap.paths()[0]) ?? ''; // a text just taken out is drawn once more
|
|
995
|
+
const key = JSON.stringify(value);
|
|
996
|
+
if (wrap.inked === key) return;
|
|
997
|
+
wrap.inked = key;
|
|
998
|
+
const s = plain(value);
|
|
999
|
+
const authors = authorsByChar(value);
|
|
1000
|
+
let h = '';
|
|
1001
|
+
for (let i = 0; i < s.length;) {
|
|
1002
|
+
let j = i;
|
|
1003
|
+
while (j < s.length && authors[j] === authors[i]) j++;
|
|
1004
|
+
h += `<span class="${cls(authors[i])}">${esc(s.slice(i, j))}</span>`;
|
|
1005
|
+
i = j;
|
|
1006
|
+
}
|
|
1007
|
+
wrap.mirror.innerHTML = `${h} `; // the space holds a last empty line open, as the box does
|
|
1008
|
+
}
|
|
1009
|
+
|
|
1010
|
+
/* lists: where the page shows a group as a list, texts can be added and taken out */
|
|
1011
|
+
const inList = (key) => [...listed()].some((g) => g === key || g.startsWith(`${key}.`));
|
|
1012
|
+
// a key for a new text in a group, like `like` (p3 → p<next>), and never one the group had since it was opened
|
|
1013
|
+
function freshKey(group, like) {
|
|
1014
|
+
const prefix = /^(.*?)\d+$/.exec(like)?.[1] || 'p';
|
|
1015
|
+
const taken = new Set([text, saved, JSON.parse(original)].flatMap((root) => Object.keys(nodeAt(root, group) ?? {})));
|
|
1016
|
+
let n = 1 + Math.max(0, ...[...taken].map((k) => (k.startsWith(prefix) && /^\d+$/.test(k.slice(prefix.length)) ? +k.slice(prefix.length) : 0)));
|
|
1017
|
+
while (taken.has(`${prefix}${n}`)) n++;
|
|
1018
|
+
return `${prefix}${n}`;
|
|
1019
|
+
}
|
|
1020
|
+
// a text put in a group after the key `after` (or first), the rest in the order they were
|
|
1021
|
+
function insert(group, after, key, value) {
|
|
1022
|
+
const node = nodeAt(text, group) ?? {};
|
|
1023
|
+
const next = after == null ? { [key]: value } : {};
|
|
1024
|
+
Object.entries(node).forEach(([k, v]) => { next[k] = v; if (k === after) next[key] = value; });
|
|
1025
|
+
if (!(key in next)) next[key] = value;
|
|
1026
|
+
set(group, next);
|
|
1027
|
+
}
|
|
1028
|
+
function addText(group, after) {
|
|
1029
|
+
const key = freshKey(group, after ?? textKeys(nodeAt(saved, group))[0] ?? '');
|
|
1030
|
+
withUndo('Added a paragraph', () => insert(group, after, key, ''));
|
|
1031
|
+
show('all', `${group}.${key}`);
|
|
1032
|
+
}
|
|
1033
|
+
const TRASH = '<svg viewBox="0 0 16 16" width="14" height="14" aria-hidden="true"><path d="M2.5 4.5h11M6.2 4.5V2.8h3.6v1.7M4 4.5l.7 8.7h6.6l.7-8.7M6.7 7v4M9.3 7v4" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"/></svg>';
|
|
1034
|
+
// a class on the page's elements for a text (`last`: only the last of them), off everything else
|
|
1035
|
+
const FLAGS = ['slop-insert-after', 'slop-remove-hint', 'slop-removing'];
|
|
1036
|
+
function flag(name, path, last) {
|
|
1037
|
+
document.querySelectorAll(`.${name}`).forEach((x) => x.classList.remove(name));
|
|
1038
|
+
if (!path) return;
|
|
1039
|
+
const els = elementsOf(path);
|
|
1040
|
+
(last ? els.slice(-1) : els).forEach((x) => x.classList.add(name));
|
|
1041
|
+
}
|
|
1042
|
+
// the + under a text in a list: pointing at it shows on the page where the new paragraph would go
|
|
1043
|
+
function plusRow(path, group) {
|
|
1044
|
+
const b = el('button', 'sp-insert', '<span class="sp-plus" aria-hidden="true">+</span><span class="sp-insert-label" aria-hidden="true">Add paragraph</span>');
|
|
1045
|
+
b.type = 'button';
|
|
1046
|
+
b.title = 'Add a paragraph below this one';
|
|
1047
|
+
b.setAttribute('aria-label', 'Add a paragraph below this one');
|
|
1048
|
+
const show = (on) => flag('slop-insert-after', on && path, true);
|
|
1049
|
+
['pointerenter', 'focus'].forEach((t) => b.addEventListener(t, () => show(true)));
|
|
1050
|
+
['pointerleave', 'blur'].forEach((t) => b.addEventListener(t, () => show(false)));
|
|
1051
|
+
b.addEventListener('click', () => { show(false); addText(group, keysOf(path).at(-1)); });
|
|
1052
|
+
return b;
|
|
1053
|
+
}
|
|
1054
|
+
// Remove: pointing at it outlines the text on the page in red. One with words takes a second click, and stays
|
|
1055
|
+
// red, here and on the page, until then
|
|
1056
|
+
function removeButton(path, wrap) {
|
|
1057
|
+
const drop = el('button', 'sp-trash', TRASH);
|
|
1058
|
+
drop.type = 'button';
|
|
1059
|
+
drop.title = 'Remove this paragraph';
|
|
1060
|
+
drop.setAttribute('aria-label', 'Remove this paragraph');
|
|
1061
|
+
const armed = () => 'armed' in drop.dataset;
|
|
1062
|
+
const hint = (on) => flag('slop-remove-hint', on && path);
|
|
1063
|
+
const arm = (on) => {
|
|
1064
|
+
if (on) drop.dataset.armed = ''; else delete drop.dataset.armed;
|
|
1065
|
+
drop.innerHTML = on ? `${TRASH}Remove?` : TRASH;
|
|
1066
|
+
wrap.classList.toggle('sp-removing', on);
|
|
1067
|
+
flag('slop-removing', on && path);
|
|
1068
|
+
};
|
|
1069
|
+
['pointerenter', 'focus'].forEach((t) => drop.addEventListener(t, () => hint(true)));
|
|
1070
|
+
['pointerleave', 'blur'].forEach((t) => drop.addEventListener(t, () => hint(false)));
|
|
1071
|
+
drop.addEventListener('click', () => {
|
|
1072
|
+
if (plain(get(path)).trim() && !armed()) {
|
|
1073
|
+
arm(true);
|
|
1074
|
+
setTimeout(() => { if (drop.isConnected && armed()) arm(false); }, 3000);
|
|
1075
|
+
return;
|
|
1076
|
+
}
|
|
1077
|
+
hint(false);
|
|
1078
|
+
arm(false);
|
|
1079
|
+
withUndo(`Removed "${where(path)}"`, () => remove(path));
|
|
1080
|
+
render();
|
|
1081
|
+
});
|
|
1082
|
+
return drop;
|
|
1083
|
+
}
|
|
1084
|
+
// in the All tab, each list's removed texts until the next save, each with Restore, and a way to start an empty one
|
|
1085
|
+
function listRows(key, box) {
|
|
1086
|
+
[...listed()].filter((g) => g === key || g.startsWith(`${key}.`)).forEach((group) => {
|
|
1087
|
+
const now = textKeys(nodeAt(text, group));
|
|
1088
|
+
const was = textKeys(nodeAt(saved, group));
|
|
1089
|
+
const fieldOf = (k) => [...box.querySelectorAll(':scope > .sp-field')].find((f) => f.dataset.path === `${group}.${k}`);
|
|
1090
|
+
was.forEach((k, i) => {
|
|
1091
|
+
if (now.includes(k)) return;
|
|
1092
|
+
const before = was.slice(0, i).reverse().find((x) => now.includes(x)); // the nearest earlier one that's still there
|
|
1093
|
+
const name = /^p\d+$/.test(k) ? `Paragraph ${i + 1}` : human(k);
|
|
1094
|
+
const row = el('p', 'sp-gone', `${esc(name)} removed · `);
|
|
1095
|
+
const b = el('button', 'sp-link', 'Restore');
|
|
1096
|
+
b.type = 'button';
|
|
1097
|
+
b.addEventListener('click', () => {
|
|
1098
|
+
withUndo(`Restored "${name}"`, () => insert(group, before ?? null, k, JSON.parse(JSON.stringify(nodeAt(saved, `${group}.${k}`)))));
|
|
1099
|
+
render();
|
|
1100
|
+
});
|
|
1101
|
+
row.append(b);
|
|
1102
|
+
let at = before ? fieldOf(before) : null;
|
|
1103
|
+
while (at?.nextElementSibling?.classList.contains('sp-gone')) at = at.nextElementSibling;
|
|
1104
|
+
const first = now.length ? fieldOf(now[0]) : null;
|
|
1105
|
+
if (at) at.after(row); else if (first) first.before(row); else box.append(row);
|
|
1106
|
+
});
|
|
1107
|
+
if (now.length) return;
|
|
1108
|
+
const start = el('button', 'sp-cat-add sp-start', '+ Paragraph');
|
|
1109
|
+
start.type = 'button';
|
|
1110
|
+
start.title = `Start "${where(group)}" again`;
|
|
1111
|
+
start.addEventListener('click', () => addText(group, null));
|
|
1112
|
+
box.append(start);
|
|
1113
|
+
});
|
|
1114
|
+
}
|
|
1115
|
+
|
|
844
1116
|
function render() {
|
|
1117
|
+
FLAGS.forEach((name) => flag(name)); // the elements pointed at may be gone
|
|
845
1118
|
controls = [controls.find((c) => c.el === pageControl)];
|
|
846
1119
|
sets = repeats(entries());
|
|
847
1120
|
groupKeys().forEach((k) => { if (!state.known.has(k)) { state.known.add(k); state.open.add(k); } });
|
|
@@ -877,7 +1150,7 @@ const Slop = (() => {
|
|
|
877
1150
|
let shown = 0;
|
|
878
1151
|
groupKeys().forEach((key) => {
|
|
879
1152
|
const paths = (isText(text[key]) ? [key] : entries(text[key], [key]).map(([p]) => p)).filter(keep);
|
|
880
|
-
if (!paths.length) return;
|
|
1153
|
+
if (!paths.length && !(tab === 'all' && inList(key))) return; // an emptied list stays, to start again
|
|
881
1154
|
shown += paths.length;
|
|
882
1155
|
body.append(isText(text[key]) ? field(key) : groupView(key, paths));
|
|
883
1156
|
});
|
|
@@ -916,15 +1189,9 @@ const Slop = (() => {
|
|
|
916
1189
|
if (b.dataset.tab === 'hidden') b.hidden = !hidden.size && state.tab !== 'hidden'; // only on pages that have some
|
|
917
1190
|
});
|
|
918
1191
|
body.querySelectorAll('.sp-field').forEach((f) => {
|
|
1192
|
+
paintInk(f);
|
|
919
1193
|
f.revert.hidden = !f.paths().some((p) => differs(p) && savedAt(p) !== undefined);
|
|
920
|
-
|
|
921
|
-
const shown = revealed && f.paths().includes(revealed.path);
|
|
922
|
-
tag.hidden = !shown && f.paths().some(onPage);
|
|
923
|
-
tag.disabled = shown || !revealerOf(f.paths()[0]);
|
|
924
|
-
tag.textContent = shown ? 'shown while editing' : tag.disabled ? 'not on the page' : 'not on the page · show it';
|
|
925
|
-
tag.title = shown ? 'The page normally hides this. It\'s shown while you edit it'
|
|
926
|
-
: tag.disabled ? 'Not on the page right now: the page shows it only some of the time, or not at all. A page can say how to show it with Slop.reveal'
|
|
927
|
-
: 'Show the page the way it looks with this text';
|
|
1194
|
+
paintSeen(f);
|
|
928
1195
|
const kind = f.paths().map((p) => hidden.get(p)).find(Boolean);
|
|
929
1196
|
f.kind.hidden = !kind;
|
|
930
1197
|
f.kind.textContent = KINDS[kind] ?? kind ?? '';
|
|
@@ -946,6 +1213,18 @@ const Slop = (() => {
|
|
|
946
1213
|
paintMeters();
|
|
947
1214
|
}
|
|
948
1215
|
repaint = () => { if (!aside.hidden) render(); };
|
|
1216
|
+
reseen = () => { if (!aside.hidden) body.querySelectorAll('.sp-field').forEach(paintSeen); };
|
|
1217
|
+
// a text the page doesn't show right now is tagged, with a way to show it if the page says how
|
|
1218
|
+
function paintSeen(f) {
|
|
1219
|
+
const tag = f.querySelector('.sp-unseen');
|
|
1220
|
+
const shown = revealed && f.paths().includes(revealed.path);
|
|
1221
|
+
tag.hidden = !shown && f.paths().some(onPage);
|
|
1222
|
+
tag.disabled = shown || !revealerOf(f.paths()[0]);
|
|
1223
|
+
tag.textContent = shown ? 'shown while editing' : tag.disabled ? 'not on the page' : 'not on the page · show it';
|
|
1224
|
+
tag.title = shown ? 'The page normally hides this. It\'s shown while you edit it'
|
|
1225
|
+
: tag.disabled ? 'Not on the page right now: the page shows it only some of the time, or not at all. A page can say how to show it with Slop.reveal'
|
|
1226
|
+
: 'Show the page the way it looks with this text';
|
|
1227
|
+
}
|
|
949
1228
|
|
|
950
1229
|
// the page and the editor point at each other
|
|
951
1230
|
function mark(on, paths = state.focus?.paths ?? [], scroll = false, tries = 0) {
|
|
@@ -1024,12 +1303,12 @@ const Slop = (() => {
|
|
|
1024
1303
|
past.set(p, list.slice(-200));
|
|
1025
1304
|
}
|
|
1026
1305
|
const recall = (p, words) => past.get(p)?.findLast((v) => plain(v) === words);
|
|
1027
|
-
function edit(paths, input, restoring) {
|
|
1306
|
+
function edit(paths, input, restoring, at) {
|
|
1028
1307
|
undo = null;
|
|
1029
1308
|
const f = state.focus;
|
|
1030
1309
|
[...paths, ...(f?.linked ?? [])].forEach((p) => {
|
|
1031
1310
|
remember(p);
|
|
1032
|
-
set(p, applyEdit(get(p), input.value, restoring ? recall(p, input.value) : undefined));
|
|
1311
|
+
set(p, applyEdit(get(p), input.value, restoring ? recall(p, input.value) : undefined, at));
|
|
1033
1312
|
remember(p);
|
|
1034
1313
|
});
|
|
1035
1314
|
grow(input);
|
|
@@ -1086,6 +1365,7 @@ const Slop = (() => {
|
|
|
1086
1365
|
store.set(LOCAL, JSON.stringify({ base: JSON.parse(original).version, text: JSON.parse(body) }));
|
|
1087
1366
|
saved = JSON.parse(body);
|
|
1088
1367
|
undo = null;
|
|
1368
|
+
keepDraft();
|
|
1089
1369
|
savedStatus();
|
|
1090
1370
|
numbers();
|
|
1091
1371
|
return;
|
|
@@ -1100,6 +1380,7 @@ const Slop = (() => {
|
|
|
1100
1380
|
text.version = Number(out);
|
|
1101
1381
|
saved = { ...JSON.parse(body), version: text.version };
|
|
1102
1382
|
undo = null;
|
|
1383
|
+
keepDraft();
|
|
1103
1384
|
savedStatus();
|
|
1104
1385
|
} catch (e) {
|
|
1105
1386
|
status(`Couldn't save: ${e.message}`, 'error');
|
|
@@ -1112,10 +1393,12 @@ const Slop = (() => {
|
|
|
1112
1393
|
function touched() {
|
|
1113
1394
|
numbers();
|
|
1114
1395
|
changed();
|
|
1396
|
+
keepDraft();
|
|
1115
1397
|
if (!stale && !undo) status(unsaved() ? 'Not saved yet' : 'No changes since the last save', unsaved() ? 'dirty' : '');
|
|
1116
1398
|
}
|
|
1117
1399
|
function reset() {
|
|
1118
1400
|
store.drop(LOCAL);
|
|
1401
|
+
session.drop(DRAFT);
|
|
1119
1402
|
text = JSON.parse(original);
|
|
1120
1403
|
saved = JSON.parse(original);
|
|
1121
1404
|
undo = null;
|
|
@@ -1124,7 +1407,14 @@ const Slop = (() => {
|
|
|
1124
1407
|
render();
|
|
1125
1408
|
savedStatus();
|
|
1126
1409
|
}
|
|
1127
|
-
addEventListener('beforeunload', (e) => { if (busy || unsaved()) e.preventDefault(); });
|
|
1410
|
+
addEventListener('beforeunload', (e) => { if (busy || unsaved()) { e.preventDefault(); e.returnValue = ''; } });
|
|
1411
|
+
// a reload keeps what isn't saved, in this tab, still unsaved: a page in a frame (or a browser that skips the
|
|
1412
|
+
// prompt) can't ask before it goes. Kept only while the page's version is the one it was based on
|
|
1413
|
+
const DRAFT = `slop-draft:${location.pathname}`;
|
|
1414
|
+
const keepDraft = () => {
|
|
1415
|
+
if (unsaved() && !stale) session.set(DRAFT, JSON.stringify({ base: saved.version, text }));
|
|
1416
|
+
else session.drop(DRAFT);
|
|
1417
|
+
};
|
|
1128
1418
|
addEventListener('keydown', (e) => {
|
|
1129
1419
|
if ((e.metaKey || e.ctrlKey) && e.key === 's' && !aside.hidden) { e.preventDefault(); save(); }
|
|
1130
1420
|
// ⌘Z outside a text undoes the last switch or mark (a text's own ⌘Z undoes its typing)
|
|
@@ -1142,11 +1432,11 @@ const Slop = (() => {
|
|
|
1142
1432
|
// while the editor is open, a click on a text opens it in the editor
|
|
1143
1433
|
document.addEventListener('click', (e) => {
|
|
1144
1434
|
if (aside.hidden || aside.contains(e.target) || btn.contains(e.target)) return;
|
|
1145
|
-
const target = e.target.closest('[data-slop], [data-slop-ref], [data-slop-attr]');
|
|
1435
|
+
const target = e.target.closest('[data-slop], [data-slop-ref], [data-slop-more], [data-slop-attr]');
|
|
1146
1436
|
if (!target) return;
|
|
1147
1437
|
e.preventDefault();
|
|
1148
1438
|
e.stopPropagation();
|
|
1149
|
-
const path =
|
|
1439
|
+
const path = pathOf(target);
|
|
1150
1440
|
if (!path) return;
|
|
1151
1441
|
const s = setOf(path);
|
|
1152
1442
|
if (state.tab === 'repeats' && s) show('repeats', s.paths[0]);
|
|
@@ -1241,6 +1531,19 @@ const Slop = (() => {
|
|
|
1241
1531
|
}));
|
|
1242
1532
|
aside.querySelectorAll('.sp-tabs button').forEach((b) => b.addEventListener('click', () => { state.tab = b.dataset.tab; render(); }));
|
|
1243
1533
|
savedStatus();
|
|
1534
|
+
try {
|
|
1535
|
+
const draft = JSON.parse(session.get(DRAFT));
|
|
1536
|
+
if (draft?.base === saved.version && JSON.stringify(draft.text) !== JSON.stringify(text)) {
|
|
1537
|
+
text = draft.text;
|
|
1538
|
+
applyColors();
|
|
1539
|
+
changed();
|
|
1540
|
+
open(true);
|
|
1541
|
+
status('Unsaved changes from before the reload', 'dirty', {
|
|
1542
|
+
label: 'Discard',
|
|
1543
|
+
run: () => { text = JSON.parse(JSON.stringify(saved)); session.drop(DRAFT); applyColors(); changed(); render(); savedStatus(); },
|
|
1544
|
+
});
|
|
1545
|
+
}
|
|
1546
|
+
} catch { /* none */ }
|
|
1244
1547
|
return { render: () => { if (!aside.hidden) render(); }, touched, open };
|
|
1245
1548
|
}
|
|
1246
1549
|
|
|
@@ -1285,5 +1588,5 @@ const Slop = (() => {
|
|
|
1285
1588
|
fetch('/__slop').then((res) => (res.ok ? res.text() : '')).then((s) => { if (s === 'slop-editor') ed = editor('file'); else local(); }).catch(local);
|
|
1286
1589
|
}
|
|
1287
1590
|
|
|
1288
|
-
return { ...core, get, set, remove, entries, categories, html, words, fill, refresh, onChange, reveal, meter, start, get text() { return text; } };
|
|
1591
|
+
return { ...core, get, set, remove, entries, categories, html, words, paragraphs, fill, refresh, onChange, reveal, meter, start, get text() { return text; } };
|
|
1289
1592
|
})();
|