slop-editor 0.2.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (5) hide show
  1. package/README.md +25 -6
  2. package/package.json +1 -1
  3. package/react.mjs +12 -3
  4. package/slop.css +48 -8
  5. package/slop.js +357 -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,19 @@ 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's paragraphs (`p1`, `p2`, …) in one element, say so, and the editor can add and remove paragraphs there:
82
+
83
+ ```html
84
+ <div data-slop-list="intro"> <!-- a copy of the first paragraph for each p<n> in "intro", in order -->
85
+ <h2 data-slop="intro.title"></h2> <!-- the group's other texts and other children stay where they are -->
86
+ <p data-slop="intro.p1"></p>
87
+ <p data-slop="intro.p2"></p>
88
+ </div>
89
+ ```
90
+
91
+ All of the group's paragraphs have to be in that element. A new one goes after the paragraph before it. A page that draws them itself (React and the like) puts `data-slop-list-ref="intro"` on the element around them instead, draws one per paragraph key, in order, and redraws after an edit.
78
92
 
79
93
  **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
94
 
@@ -98,11 +112,14 @@ A group's key (`'intro'`) covers all its texts. While shown, the page's own redr
98
112
  `slop-editor/react` wraps it, with no JSX and no build. slop.js still goes in the page first, as a plain `<script>`.
99
113
 
100
114
  ```jsx
101
- import Slop, { SlopText, SlopMeter, slopAttrs, useSlop } from 'slop-editor/react';
115
+ import Slop, { SlopText, SlopMeter, slopAttrs, slopList, useSlop } from 'slop-editor/react';
102
116
 
103
117
  <SlopMeter path="games.othello" /> // a meter (no path: the page's)
104
- <SlopText path="intro.p1" as="p" /> // a text, redrawn after each edit
118
+ <SlopText path="intro.p1" as="p" /> // a text, redrawn after each edit; as a p, li or dd, one per paragraph
105
119
  <img src="hero.png" {...slopAttrs({ alt: 'hero.photo' })} />
120
+ <div {...slopList('intro')}> // a list: the editor can add and remove texts in it
121
+ {Object.keys(Slop.text.intro).map((k) => <SlopText key={k} path={`intro.${k}`} as="p" />)}
122
+ </div>
106
123
  ```
107
124
 
108
125
  `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 +129,15 @@ import Slop, { SlopText, SlopMeter, slopAttrs, useSlop } from 'slop-editor/react
112
129
  `slop-editor edit page.html` serves the page's folder on 127.0.0.1 and opens the page with an **Edit text** button. Published, the page shows no sign of the editor. `Slop.start({edit: 'local'})` gives every visitor an editor that saves in their browser instead (the demo page uses it).
113
130
 
114
131
  - **All** shows every text, grouped by section. **Slop left** shows only the texts that aren't all yours yet; work through it until it's empty. **Repeats** shows the repeated text. **Hidden** (on pages that have some) shows alt text, tooltips and labels.
115
- - Each text, section and the whole page has a pie of what it's made of and a **slop** switch. Off approves the AI's words; on takes that back. Your typed words are never touched. Every switch can be undone from the status line.
132
+ - Each text box shows its words in their authors' colors, as readers see them with the Slop-o-meter on.
133
+ - 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
134
  - 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
135
  - Focus a text and a row of categories appears under it: **Mark all as** (or **Mark selection as**, with words selected) gives the text, or just the selection, to a category.
136
+ - 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
137
  - 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
138
  - Drag the header to move the editor anywhere, and drag any edge or corner to resize it. It stays where you leave it; double-click the header to put it back. On a phone it's a sheet along the bottom, and dragging changes its height.
120
- - Nothing is written until you click **Save** (or press ⌘S). The button counts the texts changed since the last save. Each changed text has a **Revert** link that takes its words and authorship back to the last save. Saves are versioned: a tab whose copy of the file is out of date gets an error instead of overwriting newer edits, and leaving with unsaved changes asks first.
121
- - ⌘Z in a text undoes typing and gives the restored words back to whoever wrote them. ⌘Z anywhere else undoes the last switch, mark or revert.
139
+ - 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).
140
+ - 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
141
 
123
142
  ### Repeated text
124
143
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "slop-editor",
3
- "version": "0.2.0",
3
+ "version": "0.3.1",
4
4
  "description": "A slop editor: track who wrote every word on a page (the AI, you, or nobody), then read the slop and make it yours.",
5
5
  "homepage": "https://baphaelman.github.io/slop-editor/",
6
6
  "repository": {
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
- return createElement(as, { ...props, 'data-slop-ref': path, dangerouslySetInnerHTML: { __html: slop.html(path, vars) } });
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-flabel label { min-width: 0; margin-right: auto; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: 0.76rem; font-weight: 600; color: var(--_ink-3); }
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; padding: 7px 9px; resize: none; overflow: hidden;
151
- font: 0.86rem/1.5 var(--_mono); color: var(--_ink); background: var(--_sunk); border: 1px solid transparent; border-radius: 8px;
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); background: var(--_bg); box-shadow: 0 0 0 3px color-mix(in srgb, var(--_accent) 18%, transparent); }
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
- Elements with data-slop="group.key" are filled from the block. Code renders the rest with Slop.html(path).
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
- function applyEdit(value, next, was) {
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
- if (prev === next) return value;
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
- while (end < prev.length - start && end < next.length - start
68
- && prev[prev.length - 1 - end] === next[next.length - 1 - end]) end++;
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, and [data-slop-attr] ones
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,100 @@ 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 h = render(get(el.dataset.slop), local);
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
- const fill = (root = document) => root.querySelectorAll('[data-slop], [data-slop-attr]').forEach(fillOne);
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 the group's paragraphs (p1, p2, …), in order, each in a copy
381
+ // of the first. The group's other texts (a title, a caption) and the element's other children stay where they
382
+ // are. (With data-slop-list-ref, the page draws them itself.) Either way, the editor can add and remove paragraphs
383
+ const isParagraph = (key) => /^p\d+$/.test(key);
384
+ const templates = new WeakMap(); // list → the element its paragraphs are copies of
385
+ function fillList(box) {
386
+ const at = box.dataset.slopList;
387
+ const ours = (x) => x.dataset.slop?.startsWith(`${at}.`) && isParagraph(x.dataset.slop.slice(at.length + 1));
388
+ if (!templates.has(box)) {
389
+ const first = [...box.children].find(ours);
390
+ if (!first) return;
391
+ const t = first.cloneNode(false);
392
+ ['id', 'data-slop'].forEach((a) => t.removeAttribute(a));
393
+ templates.set(box, t);
394
+ }
395
+ const paths = textKeys(nodeAt(text, at)).filter(isParagraph).map((k) => `${at}.${k}`);
396
+ const have = new Map([...box.children].filter(ours).map((x) => [x.dataset.slop, x]));
397
+ have.forEach((x, p) => { if (!paths.includes(p)) { spill(x, []); x.remove(); } });
398
+ // a new one goes after the paragraph before it (and the paragraphs that one spilled into), or else before the
399
+ // one after it
400
+ const shown = (p) => [...box.children].find((x) => x.dataset.slop === p);
401
+ paths.forEach((p, i) => {
402
+ if (have.has(p)) return;
403
+ const x = templates.get(box).cloneNode(false);
404
+ x.dataset.slop = p;
405
+ const before = paths.slice(0, i).reverse().map(shown).find(Boolean);
406
+ const after = paths.slice(i + 1).map(shown).find(Boolean);
407
+ if (before) (spills.get(before)?.at(-1) ?? before).after(x);
408
+ else if (after) after.before(x);
409
+ else box.append(x);
410
+ });
411
+ }
412
+ const fill = (root = document) => {
413
+ root.querySelectorAll('[data-slop-list]').forEach(fillList);
414
+ root.querySelectorAll('[data-slop], [data-slop-attr]').forEach(fillOne);
415
+ // paragraphs whose element the page took away, or no longer shows that text in
416
+ root.querySelectorAll('[data-slop-more]').forEach((c) => {
417
+ const el = ownerOf.get(c);
418
+ if (!el?.isConnected || el.dataset.slop !== c.dataset.slopMore) c.remove();
419
+ });
420
+ };
421
+ // the editor's "not on the page" tags, checked again once the page has drawn what changed (a text just added or
422
+ // restored has no element until then, and a single-page app draws later still)
423
+ let reseen = () => {};
424
+ let seenPending = false;
425
+ const seenSoon = () => {
426
+ if (seenPending) return;
427
+ seenPending = true;
428
+ requestAnimationFrame(() => { seenPending = false; reseen(); });
429
+ };
313
430
  // the [data-slop] elements and meters in what the page added after start (a single-page app draws late)
314
431
  function added(n) {
315
432
  if (n.nodeType !== 1 || n.closest('.slop-panel')) return;
433
+ seenSoon();
434
+ if (n.matches('[data-slop-list]')) fillList(n);
316
435
  if (n.matches('[data-slop], [data-slop-attr]')) fillOne(n);
317
436
  fill(n);
318
437
  if (n.matches('[data-slop-meter]')) meter(n);
@@ -334,6 +453,7 @@ const Slop = (() => {
334
453
  fill();
335
454
  listeners.forEach((fn) => { try { fn(); } catch (e) { console.error(e); } });
336
455
  paintMeters();
456
+ seenSoon();
337
457
  });
338
458
  }
339
459
 
@@ -425,11 +545,13 @@ const Slop = (() => {
425
545
 
426
546
  /* ---------- Slop-o-meter: a switch, a pie of what the page is made of, and what its colors mean ---------- */
427
547
 
428
- const store = {
429
- get: (k) => { try { return localStorage.getItem(k); } catch { return null; } },
430
- set: (k, v) => { try { localStorage.setItem(k, v); } catch { /* optional */ } },
431
- drop: (k) => { try { localStorage.removeItem(k); } catch { /* optional */ } },
432
- };
548
+ const storage = (area) => ({
549
+ get: (k) => { try { return area().getItem(k); } catch { return null; } },
550
+ set: (k, v) => { try { area().setItem(k, v); } catch { /* optional */ } },
551
+ drop: (k) => { try { area().removeItem(k); } catch { /* optional */ } },
552
+ });
553
+ const store = storage(() => localStorage);
554
+ const session = storage(() => sessionStorage); // this tab only: the unsaved draft
433
555
  // what readers see is the page's choice, "nothing" unless it says otherwise. While the editor is open, its
434
556
  // author sees the colors whatever readers get
435
557
  const SHOW = ['nothing', 'pie', 'colors'];
@@ -525,10 +647,18 @@ const Slop = (() => {
525
647
  const title = node && !isText(node) && isText(node.title) ? readable(node.title) : '';
526
648
  return title && title.length <= 32 ? title : human(key);
527
649
  };
650
+ // the groups the page shows as lists, where the editor can add and remove texts
651
+ const listed = () => new Set([...document.querySelectorAll('[data-slop-list], [data-slop-list-ref]')].map((x) => x.dataset.slopList || x.dataset.slopListRef));
652
+ // keys[i], for people. In a list, a paragraph is named by where it is: "Paragraph 3", even when its key is p7
653
+ function keyName(keys, i) {
654
+ const group = keys.slice(0, i).join('.');
655
+ if (!isParagraph(keys[i]) || !listed().has(group)) return human(keys[i]);
656
+ return `Paragraph ${textKeys(nodeAt(text, group)).filter(isParagraph).indexOf(keys[i]) + 1}`;
657
+ }
528
658
  // where a text is, for people: "Introduction · Paragraph 2"
529
659
  const where = (path) => {
530
- const [g, ...rest] = keysOf(path);
531
- return [groupTitle(g), ...rest.map(human)].join(' · ');
660
+ const keys = keysOf(path);
661
+ return [groupTitle(keys[0]), ...keys.slice(1).map((k, i) => keyName(keys, i + 1))].join(' · ');
532
662
  };
533
663
  const count = (n, one, many = `${one}s`) => `${n.toLocaleString()} ${n === 1 ? one : many}`;
534
664
  const isLong = (path, value) => plain(value).length > 48 || /^p\d+$/.test(keysOf(path).at(-1));
@@ -622,7 +752,8 @@ const Slop = (() => {
622
752
  return true;
623
753
  }
624
754
 
625
- /* the slop switch, next to a pie of what the texts are made of */
755
+ /* 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
756
+ sit by its name, and puts the switch at the end (c.pie, c.toggle) */
626
757
  function control(paths, what, after) {
627
758
  const c = el('span', 'sp-ctl', '<span class="sp-pie" role="img"></span>'
628
759
  + '<button type="button" class="sp-toggle" role="switch"><span class="sp-switch" aria-hidden="true"></span>slop</button>');
@@ -633,16 +764,18 @@ const Slop = (() => {
633
764
  const done = withUndo(on ? `Approved ${what}` : `Back to slop: ${what}`, () => paths().forEach((p) => set(p, on ? unslop(get(p)) : reslop(get(p)))));
634
765
  if (done) after?.(on);
635
766
  });
767
+ c.pie = c.querySelector('.sp-pie');
768
+ c.toggle = toggle;
636
769
  controls.push({ el: c, paths });
637
770
  return c;
638
771
  }
639
772
  function paintControl({ el: c, paths }, cats) {
640
- const m = makeup(paths().map(get));
641
- const pie = c.querySelector('.sp-pie');
773
+ const m = makeup(paths().map((p) => valueAt(text, p) ?? '')); // a text just taken out is painted once more
774
+ const { pie } = c;
642
775
  pie.style.background = gradient(m, cats);
643
776
  pie.title = breakdown(m, cats);
644
777
  pie.setAttribute('aria-label', pie.title);
645
- const toggle = c.querySelector('.sp-toggle');
778
+ const { toggle } = c;
646
779
  const on = (m.counts.ai ?? 0) > 0;
647
780
  toggle.setAttribute('aria-checked', String(on));
648
781
  toggle.disabled = !on && !m.counts.ok;
@@ -739,7 +872,7 @@ const Slop = (() => {
739
872
  assignEl.append(b);
740
873
  });
741
874
  assignLabel(input);
742
- wrap.append(assignEl);
875
+ if (wrap.insert) wrap.insert.before(assignEl); else wrap.append(assignEl); // the + stays last
743
876
  }
744
877
  const assignLabel = (input) => {
745
878
  if (assignEl.firstChild) assignEl.firstChild.textContent = input.selectionStart === input.selectionEnd ? 'Mark all as' : 'Mark selection as';
@@ -773,11 +906,13 @@ const Slop = (() => {
773
906
  const wrap = el('div', 'sp-field');
774
907
  wrap.dataset.path = path;
775
908
  const fid = `sp-${path.replace(/\W/g, '-')}${all ? '-all' : ''}`;
776
- const name = all ? `${all.paths.length} copies` : keysOf(path).slice(1).map(human).join(' · ') || human(path);
909
+ const keys = keysOf(path);
910
+ const name = all ? `${all.paths.length} copies` : keys.slice(1).map((k, i) => keyName(keys, i + 1)).join(' · ') || human(path);
777
911
  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><p class="sp-hint" hidden></p>`;
780
- const row = wrap.querySelector('.sp-flabel');
912
+ + '<span class="sp-fend"><span class="sp-kind" hidden></span><button type="button" class="sp-unseen" hidden></button></span></div>'
913
+ + `<div class="sp-ink"><div class="sp-mirror" aria-hidden="true"></div><textarea id="${fid}" rows="1" spellcheck="true"></textarea></div>`
914
+ + '<p class="sp-hint" hidden></p>';
915
+ const row = wrap.querySelector('.sp-fend'); // the meter sits by the name; the rest at the end of the row
781
916
  const input = wrap.querySelector('textarea');
782
917
  input.value = plain(value);
783
918
  if (!isLong(path, value)) input.addEventListener('keydown', (e) => { if (e.key === 'Enter') e.preventDefault(); });
@@ -790,6 +925,12 @@ const Slop = (() => {
790
925
  withUndo(`Reverted "${all ? all.words : where(path)}"`, () => paths().forEach((p) => { if (savedAt(p) !== undefined) set(p, savedAt(p)); }));
791
926
  render();
792
927
  });
928
+ const group = keys.slice(0, -1).join('.');
929
+ const listItem = !all && group && listed().has(group) && isParagraph(keys.at(-1));
930
+ if (listItem) {
931
+ wrap.insert = plusRow(path, group);
932
+ wrap.append(wrap.insert);
933
+ }
793
934
  row.append(revert);
794
935
  if (!all) {
795
936
  const rep = el('button', 'sp-rep');
@@ -797,8 +938,9 @@ const Slop = (() => {
797
938
  rep.addEventListener('click', () => { const s = setOf(path); if (s) show('repeats', s.paths[0]); });
798
939
  row.append(rep);
799
940
  }
800
- // a copy's switch changes that copy only, and says so. A Repeats card's switch changes every copy
801
- row.append(control(paths, all ? count(all.paths.length, 'copy', 'copies') : `"${where(path)}"`, all ? null : (approved) => {
941
+ // a copy's switch changes that copy only, and says so. A Repeats card's switch changes every copy.
942
+ // The row reads: name and pie, then at the end anything else, the trash can and the switch
943
+ const ctl = control(paths, all ? count(all.paths.length, 'copy', 'copies') : `"${where(path)}"`, all ? null : (approved) => {
802
944
  const others = (setOf(path)?.paths ?? []).filter((p) => p !== path);
803
945
  if (!others.length) return;
804
946
  const how = approved ? unslop : reslop;
@@ -806,8 +948,17 @@ const Slop = (() => {
806
948
  label: others.length === 1 ? 'Change it too' : 'Change them too',
807
949
  run: () => withUndo(`${approved ? 'Approved' : 'Back to slop:'} ${count(others.length + 1, 'copy', 'copies')}`, () => others.forEach((p) => set(p, how(get(p))))),
808
950
  });
809
- }));
810
- input.addEventListener('input', (e) => edit(paths(), input, /^history(Undo|Redo)$/.test(e.inputType)));
951
+ });
952
+ row.before(ctl.pie);
953
+ if (listItem) row.append(removeButton(path, wrap));
954
+ row.append(ctl);
955
+ // the stretch a keystroke or a paste replaces: the selection, or nothing at the caret
956
+ input.addEventListener('beforeinput', () => { input.at = [input.selectionStart, input.selectionEnd]; });
957
+ input.addEventListener('input', (e) => {
958
+ const restoring = /^history(Undo|Redo)$/.test(e.inputType);
959
+ edit(paths(), input, restoring, restoring || e.isComposing || /Composition/.test(e.inputType) ? undefined : input.at);
960
+ input.at = undefined;
961
+ });
811
962
  ['select', 'keyup', 'pointerup'].forEach((t) => input.addEventListener(t, () => assignLabel(input)));
812
963
  input.addEventListener('focus', () => { focus(path, all, input, wrap); showAssign(wrap, input, paths()); });
813
964
  input.addEventListener('blur', () => {
@@ -821,6 +972,7 @@ const Slop = (() => {
821
972
  });
822
973
  wrap.querySelector('.sp-unseen').addEventListener('click', () => input.focus());
823
974
  wrap.input = input;
975
+ wrap.mirror = wrap.querySelector('.sp-mirror');
824
976
  wrap.rep = wrap.querySelector('.sp-rep');
825
977
  wrap.kind = wrap.querySelector('.sp-kind');
826
978
  wrap.revert = revert;
@@ -832,16 +984,141 @@ const Slop = (() => {
832
984
  const det = el('details', 'sp-group', `<summary><span class="sp-gname">${esc(groupTitle(key))}</span><span class="sp-gnote"></span></summary>`);
833
985
  det.dataset.group = key;
834
986
  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
- det.querySelector('summary').append(control(() => all, `"${groupTitle(key)}"`));
987
+ const all = () => entries(text[key], [key]).map(([p]) => p);
988
+ const ctl = control(all, `"${groupTitle(key)}"`);
989
+ det.querySelector('.sp-gname').after(ctl.pie);
990
+ det.querySelector('summary').append(ctl);
837
991
  det.addEventListener('toggle', () => {
838
992
  if (det.open) { state.open.add(key); det.querySelectorAll('textarea').forEach(grow); } else state.open.delete(key);
839
993
  });
840
994
  paths.forEach((p) => det.append(field(p)));
995
+ if (state.tab === 'all') listRows(key, det);
841
996
  return det;
842
997
  }
843
998
 
999
+ // the words behind a text box, each in its author's color. The box's own letters are see-through
1000
+ function paintInk(wrap) {
1001
+ const value = valueAt(text, wrap.paths()[0]) ?? ''; // a text just taken out is drawn once more
1002
+ const key = JSON.stringify(value);
1003
+ if (wrap.inked === key) return;
1004
+ wrap.inked = key;
1005
+ const s = plain(value);
1006
+ const authors = authorsByChar(value);
1007
+ let h = '';
1008
+ for (let i = 0; i < s.length;) {
1009
+ let j = i;
1010
+ while (j < s.length && authors[j] === authors[i]) j++;
1011
+ h += `<span class="${cls(authors[i])}">${esc(s.slice(i, j))}</span>`;
1012
+ i = j;
1013
+ }
1014
+ wrap.mirror.innerHTML = `${h} `; // the space holds a last empty line open, as the box does
1015
+ }
1016
+
1017
+ /* lists: where the page shows a group as a list, texts can be added and taken out */
1018
+ const inList = (key) => [...listed()].some((g) => g === key || g.startsWith(`${key}.`));
1019
+ // a key for a new paragraph in a group: the p<n> after any the group had in the file, at the last save or now
1020
+ function freshKey(group) {
1021
+ const taken = [text, saved, JSON.parse(original)].flatMap((root) => Object.keys(nodeAt(root, group) ?? {})).filter(isParagraph);
1022
+ return `p${1 + Math.max(0, ...taken.map((k) => +k.slice(1)))}`;
1023
+ }
1024
+ // a text put in a group after the key `after` (or first), the rest in the order they were
1025
+ function insert(group, after, key, value) {
1026
+ const node = nodeAt(text, group) ?? {};
1027
+ const next = after == null ? { [key]: value } : {};
1028
+ Object.entries(node).forEach(([k, v]) => { next[k] = v; if (k === after) next[key] = value; });
1029
+ if (!(key in next)) next[key] = value;
1030
+ set(group, next);
1031
+ }
1032
+ function addText(group, after) {
1033
+ const key = freshKey(group);
1034
+ withUndo('Added a paragraph', () => insert(group, after, key, ''));
1035
+ show('all', `${group}.${key}`);
1036
+ }
1037
+ 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>';
1038
+ // a class on the page's elements for a text (`last`: only the last of them), off everything else
1039
+ const FLAGS = ['slop-insert-after', 'slop-remove-hint', 'slop-removing'];
1040
+ function flag(name, path, last) {
1041
+ document.querySelectorAll(`.${name}`).forEach((x) => x.classList.remove(name));
1042
+ if (!path) return;
1043
+ const els = elementsOf(path);
1044
+ (last ? els.slice(-1) : els).forEach((x) => x.classList.add(name));
1045
+ }
1046
+ // the + under a text in a list: pointing at it shows on the page where the new paragraph would go
1047
+ function plusRow(path, group) {
1048
+ 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>');
1049
+ b.type = 'button';
1050
+ b.title = 'Add a paragraph below this one';
1051
+ b.setAttribute('aria-label', 'Add a paragraph below this one');
1052
+ const show = (on) => flag('slop-insert-after', on && path, true);
1053
+ ['pointerenter', 'focus'].forEach((t) => b.addEventListener(t, () => show(true)));
1054
+ ['pointerleave', 'blur'].forEach((t) => b.addEventListener(t, () => show(false)));
1055
+ b.addEventListener('click', () => { show(false); addText(group, keysOf(path).at(-1)); });
1056
+ return b;
1057
+ }
1058
+ // Remove: pointing at it outlines the text on the page in red. One with words takes a second click, and stays
1059
+ // red, here and on the page, until then
1060
+ function removeButton(path, wrap) {
1061
+ const drop = el('button', 'sp-trash', TRASH);
1062
+ drop.type = 'button';
1063
+ drop.title = 'Remove this paragraph';
1064
+ drop.setAttribute('aria-label', 'Remove this paragraph');
1065
+ const armed = () => 'armed' in drop.dataset;
1066
+ const hint = (on) => flag('slop-remove-hint', on && path);
1067
+ const arm = (on) => {
1068
+ if (on) drop.dataset.armed = ''; else delete drop.dataset.armed;
1069
+ drop.innerHTML = on ? `${TRASH}Remove?` : TRASH;
1070
+ wrap.classList.toggle('sp-removing', on);
1071
+ flag('slop-removing', on && path);
1072
+ };
1073
+ ['pointerenter', 'focus'].forEach((t) => drop.addEventListener(t, () => hint(true)));
1074
+ ['pointerleave', 'blur'].forEach((t) => drop.addEventListener(t, () => hint(false)));
1075
+ drop.addEventListener('click', () => {
1076
+ if (plain(get(path)).trim() && !armed()) {
1077
+ arm(true);
1078
+ setTimeout(() => { if (drop.isConnected && armed()) arm(false); }, 3000);
1079
+ return;
1080
+ }
1081
+ hint(false);
1082
+ arm(false);
1083
+ withUndo(`Removed "${where(path)}"`, () => remove(path));
1084
+ render();
1085
+ });
1086
+ return drop;
1087
+ }
1088
+ // in the All tab, each list's removed texts until the next save, each with Restore, and a way to start an empty one
1089
+ function listRows(key, box) {
1090
+ [...listed()].filter((g) => g === key || g.startsWith(`${key}.`)).forEach((group) => {
1091
+ const now = textKeys(nodeAt(text, group)).filter(isParagraph);
1092
+ const was = textKeys(nodeAt(saved, group)).filter(isParagraph);
1093
+ const fieldOf = (k) => [...box.querySelectorAll(':scope > .sp-field')].find((f) => f.dataset.path === `${group}.${k}`);
1094
+ was.forEach((k, i) => {
1095
+ if (now.includes(k)) return;
1096
+ const before = was.slice(0, i).reverse().find((x) => now.includes(x)); // the nearest earlier one that's still there
1097
+ const name = /^p\d+$/.test(k) ? `Paragraph ${i + 1}` : human(k);
1098
+ const row = el('p', 'sp-gone', `${esc(name)} removed · `);
1099
+ const b = el('button', 'sp-link', 'Restore');
1100
+ b.type = 'button';
1101
+ b.addEventListener('click', () => {
1102
+ withUndo(`Restored "${name}"`, () => insert(group, before ?? null, k, JSON.parse(JSON.stringify(nodeAt(saved, `${group}.${k}`)))));
1103
+ render();
1104
+ });
1105
+ row.append(b);
1106
+ let at = before ? fieldOf(before) : null;
1107
+ while (at?.nextElementSibling?.classList.contains('sp-gone')) at = at.nextElementSibling;
1108
+ const first = now.length ? fieldOf(now[0]) : null;
1109
+ if (at) at.after(row); else if (first) first.before(row); else box.append(row);
1110
+ });
1111
+ if (now.length) return;
1112
+ const start = el('button', 'sp-cat-add sp-start', '+ Paragraph');
1113
+ start.type = 'button';
1114
+ start.title = `Start "${where(group)}" again`;
1115
+ start.addEventListener('click', () => addText(group, Object.keys(nodeAt(text, group) ?? {}).at(-1) ?? null)); // at the group's end
1116
+ box.append(start);
1117
+ });
1118
+ }
1119
+
844
1120
  function render() {
1121
+ FLAGS.forEach((name) => flag(name)); // the elements pointed at may be gone
845
1122
  controls = [controls.find((c) => c.el === pageControl)];
846
1123
  sets = repeats(entries());
847
1124
  groupKeys().forEach((k) => { if (!state.known.has(k)) { state.known.add(k); state.open.add(k); } });
@@ -877,7 +1154,7 @@ const Slop = (() => {
877
1154
  let shown = 0;
878
1155
  groupKeys().forEach((key) => {
879
1156
  const paths = (isText(text[key]) ? [key] : entries(text[key], [key]).map(([p]) => p)).filter(keep);
880
- if (!paths.length) return;
1157
+ if (!paths.length && !(tab === 'all' && inList(key))) return; // an emptied list stays, to start again
881
1158
  shown += paths.length;
882
1159
  body.append(isText(text[key]) ? field(key) : groupView(key, paths));
883
1160
  });
@@ -916,15 +1193,9 @@ const Slop = (() => {
916
1193
  if (b.dataset.tab === 'hidden') b.hidden = !hidden.size && state.tab !== 'hidden'; // only on pages that have some
917
1194
  });
918
1195
  body.querySelectorAll('.sp-field').forEach((f) => {
1196
+ paintInk(f);
919
1197
  f.revert.hidden = !f.paths().some((p) => differs(p) && savedAt(p) !== undefined);
920
- const tag = f.querySelector('.sp-unseen');
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';
1198
+ paintSeen(f);
928
1199
  const kind = f.paths().map((p) => hidden.get(p)).find(Boolean);
929
1200
  f.kind.hidden = !kind;
930
1201
  f.kind.textContent = KINDS[kind] ?? kind ?? '';
@@ -946,6 +1217,18 @@ const Slop = (() => {
946
1217
  paintMeters();
947
1218
  }
948
1219
  repaint = () => { if (!aside.hidden) render(); };
1220
+ reseen = () => { if (!aside.hidden) body.querySelectorAll('.sp-field').forEach(paintSeen); };
1221
+ // a text the page doesn't show right now is tagged, with a way to show it if the page says how
1222
+ function paintSeen(f) {
1223
+ const tag = f.querySelector('.sp-unseen');
1224
+ const shown = revealed && f.paths().includes(revealed.path);
1225
+ tag.hidden = !shown && f.paths().some(onPage);
1226
+ tag.disabled = shown || !revealerOf(f.paths()[0]);
1227
+ tag.textContent = shown ? 'shown while editing' : tag.disabled ? 'not on the page' : 'not on the page · show it';
1228
+ tag.title = shown ? 'The page normally hides this. It\'s shown while you edit it'
1229
+ : 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'
1230
+ : 'Show the page the way it looks with this text';
1231
+ }
949
1232
 
950
1233
  // the page and the editor point at each other
951
1234
  function mark(on, paths = state.focus?.paths ?? [], scroll = false, tries = 0) {
@@ -1024,12 +1307,12 @@ const Slop = (() => {
1024
1307
  past.set(p, list.slice(-200));
1025
1308
  }
1026
1309
  const recall = (p, words) => past.get(p)?.findLast((v) => plain(v) === words);
1027
- function edit(paths, input, restoring) {
1310
+ function edit(paths, input, restoring, at) {
1028
1311
  undo = null;
1029
1312
  const f = state.focus;
1030
1313
  [...paths, ...(f?.linked ?? [])].forEach((p) => {
1031
1314
  remember(p);
1032
- set(p, applyEdit(get(p), input.value, restoring ? recall(p, input.value) : undefined));
1315
+ set(p, applyEdit(get(p), input.value, restoring ? recall(p, input.value) : undefined, at));
1033
1316
  remember(p);
1034
1317
  });
1035
1318
  grow(input);
@@ -1086,6 +1369,7 @@ const Slop = (() => {
1086
1369
  store.set(LOCAL, JSON.stringify({ base: JSON.parse(original).version, text: JSON.parse(body) }));
1087
1370
  saved = JSON.parse(body);
1088
1371
  undo = null;
1372
+ keepDraft();
1089
1373
  savedStatus();
1090
1374
  numbers();
1091
1375
  return;
@@ -1100,6 +1384,7 @@ const Slop = (() => {
1100
1384
  text.version = Number(out);
1101
1385
  saved = { ...JSON.parse(body), version: text.version };
1102
1386
  undo = null;
1387
+ keepDraft();
1103
1388
  savedStatus();
1104
1389
  } catch (e) {
1105
1390
  status(`Couldn't save: ${e.message}`, 'error');
@@ -1112,10 +1397,12 @@ const Slop = (() => {
1112
1397
  function touched() {
1113
1398
  numbers();
1114
1399
  changed();
1400
+ keepDraft();
1115
1401
  if (!stale && !undo) status(unsaved() ? 'Not saved yet' : 'No changes since the last save', unsaved() ? 'dirty' : '');
1116
1402
  }
1117
1403
  function reset() {
1118
1404
  store.drop(LOCAL);
1405
+ session.drop(DRAFT);
1119
1406
  text = JSON.parse(original);
1120
1407
  saved = JSON.parse(original);
1121
1408
  undo = null;
@@ -1124,7 +1411,14 @@ const Slop = (() => {
1124
1411
  render();
1125
1412
  savedStatus();
1126
1413
  }
1127
- addEventListener('beforeunload', (e) => { if (busy || unsaved()) e.preventDefault(); });
1414
+ addEventListener('beforeunload', (e) => { if (busy || unsaved()) { e.preventDefault(); e.returnValue = ''; } });
1415
+ // a reload keeps what isn't saved, in this tab, still unsaved: a page in a frame (or a browser that skips the
1416
+ // prompt) can't ask before it goes. Kept only while the page's version is the one it was based on
1417
+ const DRAFT = `slop-draft:${location.pathname}`;
1418
+ const keepDraft = () => {
1419
+ if (unsaved() && !stale) session.set(DRAFT, JSON.stringify({ base: saved.version, text }));
1420
+ else session.drop(DRAFT);
1421
+ };
1128
1422
  addEventListener('keydown', (e) => {
1129
1423
  if ((e.metaKey || e.ctrlKey) && e.key === 's' && !aside.hidden) { e.preventDefault(); save(); }
1130
1424
  // ⌘Z outside a text undoes the last switch or mark (a text's own ⌘Z undoes its typing)
@@ -1142,11 +1436,11 @@ const Slop = (() => {
1142
1436
  // while the editor is open, a click on a text opens it in the editor
1143
1437
  document.addEventListener('click', (e) => {
1144
1438
  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]');
1439
+ const target = e.target.closest('[data-slop], [data-slop-ref], [data-slop-more], [data-slop-attr]');
1146
1440
  if (!target) return;
1147
1441
  e.preventDefault();
1148
1442
  e.stopPropagation();
1149
- const path = target.dataset.slop || target.dataset.slopRef || attrsOf(target)[0]?.[1];
1443
+ const path = pathOf(target);
1150
1444
  if (!path) return;
1151
1445
  const s = setOf(path);
1152
1446
  if (state.tab === 'repeats' && s) show('repeats', s.paths[0]);
@@ -1241,6 +1535,19 @@ const Slop = (() => {
1241
1535
  }));
1242
1536
  aside.querySelectorAll('.sp-tabs button').forEach((b) => b.addEventListener('click', () => { state.tab = b.dataset.tab; render(); }));
1243
1537
  savedStatus();
1538
+ try {
1539
+ const draft = JSON.parse(session.get(DRAFT));
1540
+ if (draft?.base === saved.version && JSON.stringify(draft.text) !== JSON.stringify(text)) {
1541
+ text = draft.text;
1542
+ applyColors();
1543
+ changed();
1544
+ open(true);
1545
+ status('Unsaved changes from before the reload', 'dirty', {
1546
+ label: 'Discard',
1547
+ run: () => { text = JSON.parse(JSON.stringify(saved)); session.drop(DRAFT); applyColors(); changed(); render(); savedStatus(); },
1548
+ });
1549
+ }
1550
+ } catch { /* none */ }
1244
1551
  return { render: () => { if (!aside.hidden) render(); }, touched, open };
1245
1552
  }
1246
1553
 
@@ -1285,5 +1592,5 @@ const Slop = (() => {
1285
1592
  fetch('/__slop').then((res) => (res.ok ? res.text() : '')).then((s) => { if (s === 'slop-editor') ed = editor('file'); else local(); }).catch(local);
1286
1593
  }
1287
1594
 
1288
- return { ...core, get, set, remove, entries, categories, html, words, fill, refresh, onChange, reveal, meter, start, get text() { return text; } };
1595
+ return { ...core, get, set, remove, entries, categories, html, words, paragraphs, fill, refresh, onChange, reveal, meter, start, get text() { return text; } };
1289
1596
  })();