slop-editor 0.3.1 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +38 -9
- package/cli.mjs +233 -11
- package/jsx.mjs +248 -0
- package/markup.mjs +6 -6
- package/package.json +10 -3
- package/slop.css +48 -2
- package/slop.js +550 -30
- package/vite.mjs +89 -0
package/slop.js
CHANGED
|
@@ -8,14 +8,15 @@
|
|
|
8
8
|
Top-level keys that start with "_" aren't text: "_categories" holds the page's own categories and colors,
|
|
9
9
|
{"<id>": {"label": "...", "color": "#rrggbb"}}, for built-in ones too, and "_show" what readers see: "nothing" (the
|
|
10
10
|
default), "pie" (a pie of who wrote what, with a legend) or "colors" (the Slop-o-meter switch, which colors the words).
|
|
11
|
-
Inside any text: [label](url) is a link, **bold**, *italic*, `code
|
|
12
|
-
fills in (Slop.vars), and \ makes the next character literal.
|
|
11
|
+
Inside any text: [label](url) is a link, **bold**, *italic*, `code` (a fact, shown as data), [[key]] a key cap,
|
|
12
|
+
{name} a value the page 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
15
|
|
|
16
16
|
Elements with data-slop="group.key" are filled from the block. Code renders the rest with Slop.html(path). An
|
|
17
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).
|
|
18
|
+
add and remove texts there (data-slop-list-ref: the page draws them itself). A group's paragraphs in alike elements
|
|
19
|
+
with one parent are a list without marking (data-slop-list="off" on the parent: not one).
|
|
19
20
|
An element with data-slop-meter becomes the Slop-o-meter switch. Under `slop-editor edit`, the page also gets the
|
|
20
21
|
editor, which saves back into the file; with Slop.start({edit: 'local'}) it gets one that saves in the browser. */
|
|
21
22
|
const Slop = (() => {
|
|
@@ -106,7 +107,8 @@ const Slop = (() => {
|
|
|
106
107
|
const same = (a, b) => a.by === b.by && a.link === b.link && a.b === b.b && a.i === b.i && a.code === b.code && a.key === b.key;
|
|
107
108
|
|
|
108
109
|
// the text as it reads: runs of one author's words (`by`: the category) with their formatting (b, i, code, key)
|
|
109
|
-
// and the link they sit in, if any. A {name} is a run of its own with `v` set
|
|
110
|
+
// and the link they sit in, if any. A {name} is a run of its own with `v` set. Code is a fact: whoever wrote it,
|
|
111
|
+
// a command or a file name reads as data
|
|
110
112
|
function runs(value) {
|
|
111
113
|
const text = plain(value);
|
|
112
114
|
const authors = authorsByChar(value);
|
|
@@ -115,7 +117,7 @@ const Slop = (() => {
|
|
|
115
117
|
let linkEnd = -1;
|
|
116
118
|
let linkTail = 0;
|
|
117
119
|
const push = (s, by, v) => {
|
|
118
|
-
const run = { text: s, by, link: st.link, b: st.b, i: st.i, code: st.code, key: st.key, v };
|
|
120
|
+
const run = { text: s, by: st.code ? 'data' : by, link: st.link, b: st.b, i: st.i, code: st.code, key: st.key, v };
|
|
119
121
|
const last = out[out.length - 1];
|
|
120
122
|
if (last && !last.v && !v && same(last, run)) last.text += s;
|
|
121
123
|
else out.push(run);
|
|
@@ -165,6 +167,8 @@ const Slop = (() => {
|
|
|
165
167
|
// whoever wrote the {name}), or a plain string or number (a fact)
|
|
166
168
|
const vars = {};
|
|
167
169
|
const config = { code: 'code' };
|
|
170
|
+
// where the browser editor keeps this page's copy: its path, or the page's own name for it (Slop.start({key}))
|
|
171
|
+
const pageKey = () => config.key ?? location.pathname;
|
|
168
172
|
const esc = (s) => String(s).replace(/[&<>"]/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"' })[c]);
|
|
169
173
|
const stripTags = (h) => h.replace(/<[^>]*>/g, '').replace(/ /g, ' ').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/&/g, '&');
|
|
170
174
|
// the class a category's words render with
|
|
@@ -262,7 +266,51 @@ const Slop = (() => {
|
|
|
262
266
|
return [...byWords].filter(([, paths]) => paths.length > 1).map(([words, paths]) => ({ words, paths }));
|
|
263
267
|
}
|
|
264
268
|
|
|
265
|
-
|
|
269
|
+
// a copy of the block saved in the browser, carried over to a page the author has changed since: text by text,
|
|
270
|
+
// the copy's value stays where the page's is still the one the copy was based on, and the page's wins where the
|
|
271
|
+
// author changed, added or removed it. Groups (and _categories) merge key by key; what the copy added keeps its
|
|
272
|
+
// place after the key it followed
|
|
273
|
+
function rebase(base, mine, page) {
|
|
274
|
+
const group = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
|
|
275
|
+
if (!group(base) || !group(mine) || !group(page)) return JSON.stringify(page) === JSON.stringify(base) ? mine : page;
|
|
276
|
+
const keys = Object.keys(page);
|
|
277
|
+
Object.keys(mine).forEach((k, i, order) => {
|
|
278
|
+
if (keys.includes(k)) return;
|
|
279
|
+
const after = order.slice(0, i).reverse().find((x) => keys.includes(x));
|
|
280
|
+
keys.splice(after === undefined ? 0 : keys.indexOf(after) + 1, 0, k);
|
|
281
|
+
});
|
|
282
|
+
const out = {};
|
|
283
|
+
keys.forEach((k) => {
|
|
284
|
+
const v = rebase(base[k], mine[k], page[k]);
|
|
285
|
+
if (v !== undefined) out[k] = v;
|
|
286
|
+
});
|
|
287
|
+
return out;
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
// a group's paragraphs (keys p1, p2…) are a list without marking when the page has two or more of them in
|
|
291
|
+
// elements that share one parent and are alike: the same tag and the same other attributes, so steps told apart by
|
|
292
|
+
// an attribute (data-b="0", "1"…) aren't one. [{path, parent, tag, attrs}] → Map group → parent
|
|
293
|
+
const isParagraph = (key) => /^p\d+$/.test(key);
|
|
294
|
+
function listsIn(items) {
|
|
295
|
+
const byGroup = new Map();
|
|
296
|
+
items.forEach((x) => {
|
|
297
|
+
const keys = x.path.split('.');
|
|
298
|
+
if (keys.length < 2 || !isParagraph(keys.at(-1))) return;
|
|
299
|
+
const g = keys.slice(0, -1).join('.');
|
|
300
|
+
if (!byGroup.has(g)) byGroup.set(g, []);
|
|
301
|
+
byGroup.get(g).push(x);
|
|
302
|
+
});
|
|
303
|
+
const look = (x) => `${x.tag}\n${JSON.stringify(Object.entries(x.attrs ?? {}).sort())}`;
|
|
304
|
+
const out = new Map();
|
|
305
|
+
byGroup.forEach((xs, g) => {
|
|
306
|
+
const [a] = xs;
|
|
307
|
+
if (xs.length < 2 || a.parent == null || new Set(xs.map((x) => x.path)).size < xs.length) return;
|
|
308
|
+
if (xs.every((x) => x.parent === a.parent && look(x) === look(a))) out.set(g, a.parent);
|
|
309
|
+
});
|
|
310
|
+
return out;
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
const core = { BUILTIN, plain, applyEdit, reslop, unslop, assign, reattribute, runs, readable, render, makeup, share, percent, repeats, rebase, listsIn, wordsOf, paragraphsOf, vars };
|
|
266
314
|
if (typeof document === 'undefined') return core; // Node (the CLI and the tests) only needs the format
|
|
267
315
|
|
|
268
316
|
/* ---------- the block ---------- */
|
|
@@ -380,10 +428,33 @@ const Slop = (() => {
|
|
|
380
428
|
// a list: an element with data-slop-list="group" shows the group's paragraphs (p1, p2, …), in order, each in a copy
|
|
381
429
|
// of the first. The group's other texts (a title, a caption) and the element's other children stay where they
|
|
382
430
|
// 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
431
|
const templates = new WeakMap(); // list → the element its paragraphs are copies of
|
|
432
|
+
// lists the page didn't mark (listsIn): [data-slop] elements, filled here, not drawn by the page's code. Its
|
|
433
|
+
// paragraphs that aren't on the page yet are drawn after the others, as in a marked list. Once found, a list stays
|
|
434
|
+
// one while its element is on the page. data-slop-list="off" on the parent opts out
|
|
435
|
+
const autos = new Map(); // parent → group
|
|
436
|
+
const marked = (x) => (x.dataset.slopList && x.dataset.slopList !== 'off' ? x.dataset.slopList : '');
|
|
437
|
+
const listOf = (box) => marked(box) || autos.get(box);
|
|
438
|
+
// an element's attributes but data-slop and the classes slop.js adds
|
|
439
|
+
const own = (x) => Object.fromEntries([...x.attributes].filter((a) => a.name !== 'data-slop')
|
|
440
|
+
.map((a) => [a.name, a.name === 'class' ? [...x.classList].filter((c) => !c.startsWith('slop-')).sort().join(' ') : a.value])
|
|
441
|
+
.filter(([name, v]) => name !== 'class' || v));
|
|
442
|
+
function findLists() {
|
|
443
|
+
autos.forEach((g, box) => { if (!box.isConnected) autos.delete(box); });
|
|
444
|
+
const taken = new Set([...document.querySelectorAll('[data-slop-list], [data-slop-list-ref]')].map((x) => marked(x) || x.dataset.slopListRef).filter(Boolean));
|
|
445
|
+
autos.forEach((g) => taken.add(g));
|
|
446
|
+
const els = [...document.querySelectorAll('[data-slop]')].filter((x) => !x.closest('.slop-panel'));
|
|
447
|
+
listsIn(els.map((x) => ({ path: x.dataset.slop, parent: x.parentElement, tag: x.tagName, attrs: own(x) }))).forEach((box, g) => {
|
|
448
|
+
if (taken.has(g) || box.dataset.slopList === 'off' || autos.has(box)) return;
|
|
449
|
+
// the page's code shows one of them some other way: not a list of ours
|
|
450
|
+
const paths = textKeys(nodeAt(text, g)).filter(isParagraph).map((k) => `${g}.${k}`);
|
|
451
|
+
if (paths.some((p) => rendered.has(p) || revealers.has(p) || elementsOf(p).some((x) => !x.dataset.slop && !x.dataset.slopMore))) return;
|
|
452
|
+
autos.set(box, g);
|
|
453
|
+
});
|
|
454
|
+
}
|
|
385
455
|
function fillList(box) {
|
|
386
|
-
const at = box
|
|
456
|
+
const at = listOf(box);
|
|
457
|
+
if (!at) return;
|
|
387
458
|
const ours = (x) => x.dataset.slop?.startsWith(`${at}.`) && isParagraph(x.dataset.slop.slice(at.length + 1));
|
|
388
459
|
if (!templates.has(box)) {
|
|
389
460
|
const first = [...box.children].find(ours);
|
|
@@ -410,7 +481,9 @@ const Slop = (() => {
|
|
|
410
481
|
});
|
|
411
482
|
}
|
|
412
483
|
const fill = (root = document) => {
|
|
484
|
+
if (root === document || root.matches?.('[data-slop]') || root.querySelector?.('[data-slop]')) findLists();
|
|
413
485
|
root.querySelectorAll('[data-slop-list]').forEach(fillList);
|
|
486
|
+
autos.forEach((g, box) => { if (root.contains(box) && !marked(box)) fillList(box); });
|
|
414
487
|
root.querySelectorAll('[data-slop], [data-slop-attr]').forEach(fillOne);
|
|
415
488
|
// paragraphs whose element the page took away, or no longer shows that text in
|
|
416
489
|
root.querySelectorAll('[data-slop-more]').forEach((c) => {
|
|
@@ -429,7 +502,7 @@ const Slop = (() => {
|
|
|
429
502
|
};
|
|
430
503
|
// the [data-slop] elements and meters in what the page added after start (a single-page app draws late)
|
|
431
504
|
function added(n) {
|
|
432
|
-
if (n.nodeType !== 1 || n.closest('.slop-panel')) return;
|
|
505
|
+
if (n.nodeType !== 1 || n.closest('.slop-panel, .slop-sampler')) return;
|
|
433
506
|
seenSoon();
|
|
434
507
|
if (n.matches('[data-slop-list]')) fillList(n);
|
|
435
508
|
if (n.matches('[data-slop], [data-slop-attr]')) fillOne(n);
|
|
@@ -547,7 +620,7 @@ const Slop = (() => {
|
|
|
547
620
|
|
|
548
621
|
const storage = (area) => ({
|
|
549
622
|
get: (k) => { try { return area().getItem(k); } catch { return null; } },
|
|
550
|
-
set: (k, v) => { try { area().setItem(k, v); } catch {
|
|
623
|
+
set: (k, v) => { try { area().setItem(k, v); return true; } catch { return false; } },
|
|
551
624
|
drop: (k) => { try { area().removeItem(k); } catch { /* optional */ } },
|
|
552
625
|
});
|
|
553
626
|
const store = storage(() => localStorage);
|
|
@@ -600,7 +673,7 @@ const Slop = (() => {
|
|
|
600
673
|
pie.title = breakdown(m, cats);
|
|
601
674
|
pie.setAttribute('aria-label', pie.title);
|
|
602
675
|
// each category in its own color, with its share of the text
|
|
603
|
-
legend.innerHTML = cats.filter((c) => m.counts[c.id])
|
|
676
|
+
legend.innerHTML = cats.filter((c) => m.counts[c.id]).sort((a, b) => m.counts[b.id] - m.counts[a.id])
|
|
604
677
|
.map((c) => `<span class="slop-key" tabindex="0" data-id="${esc(c.id)}" style="color:${swatch(c)}"><i style="background:${swatch(c)}"></i>${esc(c.label)}<b class="slop-pct">${percent(m.counts[c.id] / m.letters)}</b></span>`).join('');
|
|
605
678
|
});
|
|
606
679
|
}
|
|
@@ -648,7 +721,8 @@ const Slop = (() => {
|
|
|
648
721
|
return title && title.length <= 32 ? title : human(key);
|
|
649
722
|
};
|
|
650
723
|
// 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
|
|
724
|
+
const listed = () => new Set([...document.querySelectorAll('[data-slop-list], [data-slop-list-ref]')].map((x) => marked(x) || x.dataset.slopListRef).filter(Boolean)
|
|
725
|
+
.concat([...autos].filter(([box]) => box.isConnected).map(([, g]) => g)));
|
|
652
726
|
// keys[i], for people. In a list, a paragraph is named by where it is: "Paragraph 3", even when its key is p7
|
|
653
727
|
function keyName(keys, i) {
|
|
654
728
|
const group = keys.slice(0, i).join('.');
|
|
@@ -672,7 +746,7 @@ const Slop = (() => {
|
|
|
672
746
|
const startTab = () => (repeats(entries()).some((s) => s.paths.some(slopIn)) ? 'repeats' : entries().some(([p]) => slopIn(p)) ? 'slop' : 'all');
|
|
673
747
|
|
|
674
748
|
function editor(mode) {
|
|
675
|
-
const LOCAL = `slop-text:${
|
|
749
|
+
const LOCAL = `slop-text:${pageKey()}`;
|
|
676
750
|
// open: the first section, and any the page adds later (pasted text, say)
|
|
677
751
|
// it opens on Repeats, or on Slop left when nothing is repeated
|
|
678
752
|
const state = { tab: startTab(), open: new Set(groupKeys().slice(0, 1)), known: new Set(groupKeys()), focus: null };
|
|
@@ -791,23 +865,29 @@ const Slop = (() => {
|
|
|
791
865
|
for (let n = 2; id in BUILTIN || text._categories?.[id] || categories().some((c) => c.id === id); n++) id = `${base}-${n}`;
|
|
792
866
|
return id;
|
|
793
867
|
};
|
|
868
|
+
// the categories, the one with most of the page first (as the meters' legends). A category of the page's own
|
|
869
|
+
// can say whose words it means and ask an agent to find them (about, find); what an agent marked waits for
|
|
870
|
+
// Keep or Undo (found.before)
|
|
794
871
|
function renderCats() {
|
|
872
|
+
closePicker();
|
|
795
873
|
const box = $('.sp-cats');
|
|
796
874
|
box.innerHTML = '';
|
|
797
|
-
|
|
798
|
-
|
|
875
|
+
const counts = makeup(entries().map(([, v]) => v)).counts;
|
|
876
|
+
categories().sort((a, b) => (counts[b.id] ?? 0) - (counts[a.id] ?? 0)).forEach((cat) => {
|
|
877
|
+
const row = el('span', 'sp-cat', `<button type="button" class="sp-swatch" title="Click to pick a color for ${esc(cat.label)}, or drag onto the page to take one from it" aria-label="Pick a color for ${esc(cat.label)}"></button>`
|
|
799
878
|
+ `<input class="sp-cat-name" aria-label="Category name" spellcheck="false"><b class="sp-cat-pct"></b>`
|
|
800
879
|
+ (cat.builtin ? '' : `<button type="button" class="sp-cat-x" title="Delete ${esc(cat.label)}: its words become AI-generated">×</button>`));
|
|
801
880
|
row.dataset.id = cat.id;
|
|
802
|
-
const
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
own(cat.id).color = picker.value;
|
|
807
|
-
row.querySelector('.sp-swatch').style.background = picker.value;
|
|
881
|
+
const dot = row.querySelector('.sp-swatch');
|
|
882
|
+
const pick = (color) => {
|
|
883
|
+
setColor(cat.id, color);
|
|
884
|
+
dot.style.background = color;
|
|
808
885
|
applyColors();
|
|
809
886
|
touched();
|
|
810
|
-
}
|
|
887
|
+
};
|
|
888
|
+
dot.style.background = swatch(cat);
|
|
889
|
+
dragColor(dot, pick);
|
|
890
|
+
dot.addEventListener('click', (e) => { if (!e.defaultPrevented) picker(cat.id, dot, pick); });
|
|
811
891
|
const name = row.querySelector('.sp-cat-name');
|
|
812
892
|
name.value = cat.label;
|
|
813
893
|
name.size = Math.max(3, cat.label.length);
|
|
@@ -817,6 +897,9 @@ const Slop = (() => {
|
|
|
817
897
|
touched();
|
|
818
898
|
});
|
|
819
899
|
name.addEventListener('keydown', (e) => { if (e.key === 'Enter') name.blur(); });
|
|
900
|
+
// selecting a category opens whose words it means, under the categories
|
|
901
|
+
name.addEventListener('focus', () => about(cat.id));
|
|
902
|
+
row.addEventListener('click', (e) => { if (!e.target.closest('.sp-swatch, .sp-cat-x, .sp-cat-name')) about(cat.id); });
|
|
820
903
|
row.querySelector('.sp-cat-x')?.addEventListener('click', () => {
|
|
821
904
|
withUndo(`Deleted "${cat.label}"`, () => {
|
|
822
905
|
entries().forEach(([p, v]) => set(p, reattribute(v, cat.id, 'ai')));
|
|
@@ -836,23 +919,446 @@ const Slop = (() => {
|
|
|
836
919
|
add.replaceWith(input);
|
|
837
920
|
input.focus();
|
|
838
921
|
let finished = false;
|
|
922
|
+
let made = null;
|
|
839
923
|
const done = (keep) => {
|
|
840
924
|
if (finished) return;
|
|
841
925
|
finished = true;
|
|
842
926
|
const label = input.value.trim();
|
|
843
927
|
if (keep && label) {
|
|
844
|
-
|
|
928
|
+
made = slug(label);
|
|
845
929
|
const color = PALETTE[categories().filter((c) => !c.builtin).length % PALETTE.length];
|
|
846
|
-
Object.assign(own(
|
|
930
|
+
Object.assign(own(made), { label, color });
|
|
847
931
|
applyColors();
|
|
848
932
|
touched();
|
|
849
933
|
}
|
|
850
934
|
render();
|
|
935
|
+
if (made) about(made, true); // whose words they are, next
|
|
851
936
|
};
|
|
852
937
|
input.addEventListener('keydown', (e) => { if (e.key === 'Enter') done(true); if (e.key === 'Escape') done(false); });
|
|
853
938
|
input.addEventListener('blur', () => done(true), { once: true });
|
|
854
939
|
});
|
|
855
940
|
box.append(add);
|
|
941
|
+
// every picked color back to the default, in one undoable step. Shown while there's one (numbers())
|
|
942
|
+
const back = el('button', 'sp-cat-revert', 'Revert colors');
|
|
943
|
+
back.type = 'button';
|
|
944
|
+
back.title = 'Every category back to its default color';
|
|
945
|
+
back.addEventListener('click', () => {
|
|
946
|
+
withUndo('Colors back to the defaults', () => Object.keys(text._categories).forEach((id) => setColor(id, null)));
|
|
947
|
+
applyColors();
|
|
948
|
+
render();
|
|
949
|
+
});
|
|
950
|
+
box.append(back);
|
|
951
|
+
if (aboutOpen && categories().some((c) => c.id === aboutOpen)) about(aboutOpen);
|
|
952
|
+
// what an agent marked, for the author to keep or undo
|
|
953
|
+
Object.entries(text._categories ?? {}).forEach(([id, c]) => {
|
|
954
|
+
const before = c.found?.before;
|
|
955
|
+
if (!before || !Object.keys(before).length) return;
|
|
956
|
+
const n = Object.keys(before).length;
|
|
957
|
+
const label = categories().find((x) => x.id === id)?.label ?? id;
|
|
958
|
+
const note = el('p', 'sp-found', `${esc(`An agent marked ${count(n, 'text')} as ${label}${c.found.on ? ` on ${day(c.found.on)}` : ''}`)} · `);
|
|
959
|
+
note.dataset.id = id;
|
|
960
|
+
const keep = el('button', 'sp-link', 'Keep');
|
|
961
|
+
keep.type = 'button';
|
|
962
|
+
keep.title = 'Keep what the agent marked';
|
|
963
|
+
keep.addEventListener('click', () => { withUndo(`Kept the agent's marks for ${label}`, () => { delete c.found.before; }); render(); });
|
|
964
|
+
const undoBtn = el('button', 'sp-link', 'Undo');
|
|
965
|
+
undoBtn.type = 'button';
|
|
966
|
+
undoBtn.title = 'Give those texts back to whoever had them before (texts whose words changed since stay as they are)';
|
|
967
|
+
undoBtn.addEventListener('click', () => {
|
|
968
|
+
withUndo(`Undid the agent's marks for ${label}`, () => {
|
|
969
|
+
Object.entries(before).forEach(([p, was]) => {
|
|
970
|
+
const now = valueAt(text, p);
|
|
971
|
+
if (now !== undefined && plain(now) === plain(was)) set(p, was);
|
|
972
|
+
});
|
|
973
|
+
delete c.found;
|
|
974
|
+
});
|
|
975
|
+
render();
|
|
976
|
+
});
|
|
977
|
+
note.append(keep, ' · ', undoBtn);
|
|
978
|
+
box.append(note);
|
|
979
|
+
});
|
|
980
|
+
}
|
|
981
|
+
const day = (iso) => { const d = new Date(`${iso}T12:00:00`); return Number.isNaN(+d) ? iso : d.toLocaleDateString(undefined, { month: 'short', day: 'numeric' }); };
|
|
982
|
+
|
|
983
|
+
/* whose words a category means, and whether an agent should find them: under the categories while open */
|
|
984
|
+
let aboutOpen = null;
|
|
985
|
+
// an agent can find the words of a category of the page's own, or facts and quotes. Only the author can say which
|
|
986
|
+
// words are theirs or approved, and slop is whatever's left
|
|
987
|
+
const findable = (id) => !(id in BUILTIN) || id === 'data';
|
|
988
|
+
// a category's entry, dropped once it says nothing
|
|
989
|
+
function tidy(id) {
|
|
990
|
+
const c = text._categories?.[id];
|
|
991
|
+
if (c && !Object.keys(c).length) delete text._categories[id];
|
|
992
|
+
if (text._categories && !Object.keys(text._categories).length) delete text._categories;
|
|
993
|
+
}
|
|
994
|
+
function about(id, focus) {
|
|
995
|
+
aboutOpen = id;
|
|
996
|
+
const box = $('.sp-cats');
|
|
997
|
+
box.querySelector('.sp-about')?.remove();
|
|
998
|
+
box.querySelectorAll('.sp-cat').forEach((x) => x.classList.toggle('sp-cat-on', x.dataset.id === id));
|
|
999
|
+
const c = () => text._categories?.[id] ?? {};
|
|
1000
|
+
const label = () => categories().find((x) => x.id === id)?.label ?? id;
|
|
1001
|
+
const panel = el('div', 'sp-about', `<label class="sp-about-q" for="sp-about-${esc(id)}"></label>`
|
|
1002
|
+
+ `<textarea id="sp-about-${esc(id)}" rows="2" spellcheck="true" placeholder="Who wrote them, or where they come from"></textarea>`
|
|
1003
|
+
+ '<div class="sp-about-row"><label class="sp-check"><input type="checkbox"> Ask an agent to find them</label><button type="button" class="sp-link sp-about-done">Done</button></div>'
|
|
1004
|
+
+ '<p class="sp-about-note"></p>');
|
|
1005
|
+
panel.dataset.id = id;
|
|
1006
|
+
panel.querySelector('.sp-about-q').textContent = `Whose words are ${label()}?`;
|
|
1007
|
+
const desc = panel.querySelector('textarea');
|
|
1008
|
+
const ask = panel.querySelector('input[type="checkbox"]');
|
|
1009
|
+
const note = panel.querySelector('.sp-about-note');
|
|
1010
|
+
panel.querySelector('.sp-check').hidden = !findable(id);
|
|
1011
|
+
desc.value = c().about ?? '';
|
|
1012
|
+
ask.checked = !!c().find;
|
|
1013
|
+
const paint = () => {
|
|
1014
|
+
note.innerHTML = '';
|
|
1015
|
+
if (c().find) {
|
|
1016
|
+
note.append('Waiting for an agent: it finds them the next time one works on this page, once you save. ');
|
|
1017
|
+
const copy = el('button', 'sp-link', 'Copy a prompt');
|
|
1018
|
+
copy.type = 'button';
|
|
1019
|
+
copy.title = 'To ask an agent now';
|
|
1020
|
+
copy.addEventListener('click', () => {
|
|
1021
|
+
const page = decodeURIComponent(location.pathname.split('/').pop() || '') || 'this page';
|
|
1022
|
+
const prompt = `In ${page}, find the words that belong to the slop-editor category "${label()}"${c().about ? ` (${c().about})` : ''} and mark them, following the slop-editor skill's "Categories to find".`;
|
|
1023
|
+
Promise.resolve(navigator.clipboard?.writeText(prompt)).then(() => status('Prompt copied')).catch(() => status("Couldn't copy the prompt", 'error'));
|
|
1024
|
+
});
|
|
1025
|
+
note.append(copy);
|
|
1026
|
+
} else if (c().found?.on) note.append(`Found by an agent · ${day(c().found.on)}`);
|
|
1027
|
+
note.hidden = !note.childNodes.length;
|
|
1028
|
+
};
|
|
1029
|
+
desc.addEventListener('input', () => {
|
|
1030
|
+
if (desc.value.trim()) own(id).about = desc.value.trim();
|
|
1031
|
+
else { delete text._categories?.[id]?.about; tidy(id); }
|
|
1032
|
+
touched();
|
|
1033
|
+
});
|
|
1034
|
+
ask.addEventListener('change', () => {
|
|
1035
|
+
if (ask.checked) own(id).find = true;
|
|
1036
|
+
else { delete text._categories?.[id]?.find; tidy(id); }
|
|
1037
|
+
paint();
|
|
1038
|
+
touched();
|
|
1039
|
+
});
|
|
1040
|
+
panel.querySelector('.sp-about-done').addEventListener('click', () => {
|
|
1041
|
+
aboutOpen = null;
|
|
1042
|
+
panel.remove();
|
|
1043
|
+
box.querySelectorAll('.sp-cat-on').forEach((x) => x.classList.remove('sp-cat-on'));
|
|
1044
|
+
});
|
|
1045
|
+
paint();
|
|
1046
|
+
box.querySelector('.sp-found') ? box.querySelector('.sp-found').before(panel) : box.append(panel);
|
|
1047
|
+
if (focus) desc.focus();
|
|
1048
|
+
}
|
|
1049
|
+
|
|
1050
|
+
/* the color picker, under a category's dot, laid out like the browser's own: a rectangle of shades, then the
|
|
1051
|
+
eyedropper, the color and a hue bar, then its numbers (RGB, HEX or HSL: the arrows switch). Its eyedropper shows
|
|
1052
|
+
the page magnified beside the pointer, not over it */
|
|
1053
|
+
const rgbOf = (c) => [1, 3, 5].map((i) => parseInt(c.slice(i, i + 2), 16));
|
|
1054
|
+
const hexOf = (rgb) => `#${rgb.map((v) => Math.round(clamp(v, 0, 255)).toString(16).padStart(2, '0')).join('')}`;
|
|
1055
|
+
function toHsv(color) {
|
|
1056
|
+
const [r, g, b] = rgbOf(color).map((v) => v / 255);
|
|
1057
|
+
const max = Math.max(r, g, b);
|
|
1058
|
+
const d = max - Math.min(r, g, b);
|
|
1059
|
+
const h = !d ? 0 : max === r ? ((g - b) / d) % 6 : max === g ? (b - r) / d + 2 : (r - g) / d + 4;
|
|
1060
|
+
return { h: (h * 60 + 360) % 360, s: max ? d / max : 0, v: max };
|
|
1061
|
+
}
|
|
1062
|
+
function fromHsv({ h, s, v }) {
|
|
1063
|
+
const f = (n) => { const k = (n + h / 60) % 6; return v - v * s * Math.max(0, Math.min(k, 4 - k, 1)); };
|
|
1064
|
+
return hexOf([f(5), f(3), f(1)].map((x) => x * 255));
|
|
1065
|
+
}
|
|
1066
|
+
function hslOf(color) {
|
|
1067
|
+
const [r, g, b] = rgbOf(color).map((v) => v / 255);
|
|
1068
|
+
const max = Math.max(r, g, b);
|
|
1069
|
+
const min = Math.min(r, g, b);
|
|
1070
|
+
const l = (max + min) / 2;
|
|
1071
|
+
const d = max - min;
|
|
1072
|
+
const s = !d ? 0 : d / (1 - Math.abs(2 * l - 1));
|
|
1073
|
+
return [Math.round(toHsv(color).h), Math.round(s * 100), Math.round(l * 100)];
|
|
1074
|
+
}
|
|
1075
|
+
function fromHsl([h, s, l]) {
|
|
1076
|
+
const a = (s / 100) * Math.min(l / 100, 1 - l / 100);
|
|
1077
|
+
const f = (n) => { const k = (n + h / 30) % 12; return l / 100 - a * Math.max(-1, Math.min(k - 3, 9 - k, 1)); };
|
|
1078
|
+
return hexOf([f(0), f(8), f(4)].map((x) => x * 255));
|
|
1079
|
+
}
|
|
1080
|
+
const FORMATS = {
|
|
1081
|
+
rgb: { labels: ['R', 'G', 'B'], read: rgbOf, write: hexOf, max: [255, 255, 255] },
|
|
1082
|
+
hex: { labels: ['HEX'], read: (c) => [c], write: ([v]) => (/^#?[0-9a-f]{6}$/i.test(v.trim()) ? `#${v.trim().replace('#', '').toLowerCase()}` : null) },
|
|
1083
|
+
hsl: { labels: ['H', 'S', 'L'], read: hslOf, write: fromHsl, max: [359, 100, 100] },
|
|
1084
|
+
};
|
|
1085
|
+
const DROPPER = '<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M10.4 2.4a1.9 1.9 0 0 1 2.7 2.7l-1.6 1.6.8.8-1.1 1.1-.8-.8-5.2 5.2H3v-2.2l5.2-5.2-.8-.8 1.1-1.1.8.8z" fill="none" stroke="currentColor" stroke-width="1.3" stroke-linejoin="round"/></svg>';
|
|
1086
|
+
let pickEl = null;
|
|
1087
|
+
let pickFormat = 'rgb';
|
|
1088
|
+
let dropping = false;
|
|
1089
|
+
function closePicker() {
|
|
1090
|
+
pickEl?.remove();
|
|
1091
|
+
pickEl = null;
|
|
1092
|
+
}
|
|
1093
|
+
function picker(id, dot, pick) {
|
|
1094
|
+
const again = pickEl?.dataset.id === id;
|
|
1095
|
+
closePicker();
|
|
1096
|
+
if (again) return; // a second click on the dot closes it
|
|
1097
|
+
const cat = () => categories().find((c) => c.id === id);
|
|
1098
|
+
const p = el('div', 'sp-pick', '<div class="sp-pick-sv" tabindex="0" role="slider" aria-label="Shade: right for more color, down for darker"><i></i></div>'
|
|
1099
|
+
+ `<div class="sp-pick-row"><button type="button" class="sp-pick-drop" title="Take a color from the page" aria-label="Take a color from the page">${DROPPER}</button>`
|
|
1100
|
+
+ '<b class="sp-pick-now"></b><input type="range" class="sp-pick-hue" min="0" max="359" step="1" aria-label="Hue"></div>'
|
|
1101
|
+
+ '<div class="sp-pick-nums"></div>');
|
|
1102
|
+
p.dataset.id = id;
|
|
1103
|
+
pickEl = p;
|
|
1104
|
+
const sv = p.querySelector('.sp-pick-sv');
|
|
1105
|
+
const handle = sv.querySelector('i');
|
|
1106
|
+
const hue = p.querySelector('.sp-pick-hue');
|
|
1107
|
+
const now = p.querySelector('.sp-pick-now');
|
|
1108
|
+
const nums = p.querySelector('.sp-pick-nums');
|
|
1109
|
+
let hsv = toHsv(hex(swatch(cat())));
|
|
1110
|
+
function fields() {
|
|
1111
|
+
const f = FORMATS[pickFormat];
|
|
1112
|
+
nums.innerHTML = f.labels.map((l) => `<label class="sp-pick-num"><input spellcheck="false" aria-label="${l}"><span>${l}</span></label>`).join('')
|
|
1113
|
+
+ '<button type="button" class="sp-pick-swap" title="RGB, HEX or HSL" aria-label="Switch between RGB, HEX and HSL"><svg viewBox="0 0 12 16" width="10" height="14" aria-hidden="true"><path d="M2 6l4-4 4 4M2 10l4 4 4-4" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"/></svg></button>';
|
|
1114
|
+
const inputs = [...nums.querySelectorAll('input')];
|
|
1115
|
+
inputs.forEach((input) => input.addEventListener('input', () => {
|
|
1116
|
+
const vals = inputs.map((x) => (f.max ? Number(x.value) : x.value));
|
|
1117
|
+
if (f.max && vals.some((v, i) => !Number.isFinite(v) || v < 0 || v > f.max[i])) return;
|
|
1118
|
+
const c = f.write(vals);
|
|
1119
|
+
if (!c) return;
|
|
1120
|
+
hsv = toHsv(c);
|
|
1121
|
+
apply();
|
|
1122
|
+
}));
|
|
1123
|
+
inputs.forEach((input) => input.addEventListener('blur', paint));
|
|
1124
|
+
nums.querySelector('.sp-pick-swap').addEventListener('click', () => {
|
|
1125
|
+
const order = Object.keys(FORMATS);
|
|
1126
|
+
pickFormat = order[(order.indexOf(pickFormat) + 1) % order.length];
|
|
1127
|
+
fields();
|
|
1128
|
+
paint();
|
|
1129
|
+
});
|
|
1130
|
+
}
|
|
1131
|
+
function paint() {
|
|
1132
|
+
const c = fromHsv(hsv);
|
|
1133
|
+
sv.style.background = `linear-gradient(to top, #000, transparent), linear-gradient(to right, #fff, hsl(${hsv.h} 100% 50%))`;
|
|
1134
|
+
Object.assign(handle.style, { left: `${hsv.s * 100}%`, top: `${(1 - hsv.v) * 100}%`, background: c });
|
|
1135
|
+
hue.value = Math.round(hsv.h);
|
|
1136
|
+
hue.style.setProperty('--hue', `hsl(${hsv.h} 100% 50%)`);
|
|
1137
|
+
now.style.background = c;
|
|
1138
|
+
sv.setAttribute('aria-valuetext', c);
|
|
1139
|
+
const vals = FORMATS[pickFormat].read(c);
|
|
1140
|
+
nums.querySelectorAll('input').forEach((x, i) => { if (document.activeElement !== x) x.value = vals[i]; });
|
|
1141
|
+
}
|
|
1142
|
+
function apply() {
|
|
1143
|
+
pick(fromHsv(hsv));
|
|
1144
|
+
paint();
|
|
1145
|
+
}
|
|
1146
|
+
const at = (e) => {
|
|
1147
|
+
const r = sv.getBoundingClientRect();
|
|
1148
|
+
hsv.s = clamp((e.clientX - r.left) / r.width, 0, 1);
|
|
1149
|
+
hsv.v = 1 - clamp((e.clientY - r.top) / r.height, 0, 1);
|
|
1150
|
+
apply();
|
|
1151
|
+
};
|
|
1152
|
+
sv.addEventListener('pointerdown', (e) => {
|
|
1153
|
+
if (e.button !== 0) return;
|
|
1154
|
+
e.preventDefault();
|
|
1155
|
+
sv.focus();
|
|
1156
|
+
sv.setPointerCapture(e.pointerId);
|
|
1157
|
+
at(e);
|
|
1158
|
+
const move = (ev) => at(ev);
|
|
1159
|
+
const up = () => { sv.removeEventListener('pointermove', move); sv.removeEventListener('pointerup', up); };
|
|
1160
|
+
sv.addEventListener('pointermove', move);
|
|
1161
|
+
sv.addEventListener('pointerup', up);
|
|
1162
|
+
});
|
|
1163
|
+
sv.addEventListener('keydown', (e) => {
|
|
1164
|
+
const step = e.shiftKey ? 0.1 : 0.02;
|
|
1165
|
+
const d = { ArrowLeft: ['s', -step], ArrowRight: ['s', step], ArrowUp: ['v', step], ArrowDown: ['v', -step] }[e.key];
|
|
1166
|
+
if (!d) return;
|
|
1167
|
+
e.preventDefault();
|
|
1168
|
+
hsv[d[0]] = clamp(hsv[d[0]] + d[1], 0, 1);
|
|
1169
|
+
apply();
|
|
1170
|
+
});
|
|
1171
|
+
hue.addEventListener('input', () => { hsv.h = +hue.value; apply(); });
|
|
1172
|
+
p.querySelector('.sp-pick-drop').addEventListener('click', (e) => eyedrop(e, (c) => { hsv = toHsv(c); apply(); }));
|
|
1173
|
+
p.addEventListener('keydown', (e) => { if (e.key === 'Escape' && !dropping) { e.stopPropagation(); closePicker(); dot.focus(); } });
|
|
1174
|
+
aside.append(p);
|
|
1175
|
+
// under the dot, inside the editor
|
|
1176
|
+
const a = aside.getBoundingClientRect();
|
|
1177
|
+
const r = dot.getBoundingClientRect();
|
|
1178
|
+
p.style.top = `${r.bottom - a.top + 8}px`;
|
|
1179
|
+
p.style.left = `${clamp(r.left - a.left - 10, 8, a.width - p.offsetWidth - 8)}px`;
|
|
1180
|
+
fields();
|
|
1181
|
+
paint();
|
|
1182
|
+
}
|
|
1183
|
+
// the eyedropper: the magnifier follows the pointer until a click takes the color under it (Escape: none)
|
|
1184
|
+
function eyedrop(start, done) {
|
|
1185
|
+
dropping = true;
|
|
1186
|
+
const lens = sampler();
|
|
1187
|
+
let color = null;
|
|
1188
|
+
const move = (e) => { color = colorAt(e.clientX, e.clientY); lens.show(e.clientX, e.clientY, color); };
|
|
1189
|
+
move(start);
|
|
1190
|
+
const off = new AbortController();
|
|
1191
|
+
const stop = (e) => { e.preventDefault(); e.stopPropagation(); };
|
|
1192
|
+
const finish = (keep) => {
|
|
1193
|
+
off.abort();
|
|
1194
|
+
lens.remove();
|
|
1195
|
+
dropping = false;
|
|
1196
|
+
if (keep && color) done(color);
|
|
1197
|
+
// the click that took it mustn't reach the page (or the next press clears that)
|
|
1198
|
+
const after = new AbortController();
|
|
1199
|
+
addEventListener('click', (e) => { stop(e); after.abort(); }, { capture: true, signal: after.signal });
|
|
1200
|
+
addEventListener('pointerdown', () => after.abort(), { capture: true, signal: after.signal });
|
|
1201
|
+
};
|
|
1202
|
+
addEventListener('pointermove', move, { capture: true, signal: off.signal });
|
|
1203
|
+
addEventListener('pointerdown', (e) => { stop(e); move(e); finish(true); }, { capture: true, signal: off.signal });
|
|
1204
|
+
addEventListener('keydown', (e) => { if (e.key === 'Escape') { stop(e); finish(false); } }, { capture: true, signal: off.signal });
|
|
1205
|
+
}
|
|
1206
|
+
// a press anywhere but the picker or a dot closes it
|
|
1207
|
+
addEventListener('pointerdown', (e) => {
|
|
1208
|
+
if (pickEl && !dropping && !pickEl.contains(e.target) && !e.target.closest?.('.sp-swatch')) closePicker();
|
|
1209
|
+
}, true);
|
|
1210
|
+
|
|
1211
|
+
/* drag a category's dot onto the page to take a color from it: the point is a ring, and the color shows in a
|
|
1212
|
+
circle beside it, joined by a line, so the pointer never hides it. A click still opens the browser's picker */
|
|
1213
|
+
function dragColor(dot, pick) {
|
|
1214
|
+
let dragged = false; // the click that ends a drag mustn't open the picker
|
|
1215
|
+
dot.addEventListener('click', (e) => { if (dragged) { e.preventDefault(); dragged = false; } });
|
|
1216
|
+
dot.addEventListener('pointerdown', (e) => {
|
|
1217
|
+
if (e.button !== 0) return;
|
|
1218
|
+
dragged = false;
|
|
1219
|
+
const x0 = e.clientX;
|
|
1220
|
+
const y0 = e.clientY;
|
|
1221
|
+
let lens = null;
|
|
1222
|
+
let color = null;
|
|
1223
|
+
const move = (ev) => {
|
|
1224
|
+
if (!lens) {
|
|
1225
|
+
if (Math.hypot(ev.clientX - x0, ev.clientY - y0) < 6) return;
|
|
1226
|
+
lens = sampler();
|
|
1227
|
+
dot.setPointerCapture(ev.pointerId);
|
|
1228
|
+
}
|
|
1229
|
+
color = colorAt(ev.clientX, ev.clientY);
|
|
1230
|
+
lens.show(ev.clientX, ev.clientY, color);
|
|
1231
|
+
};
|
|
1232
|
+
let cancelled = false;
|
|
1233
|
+
const up = (ev) => {
|
|
1234
|
+
removeEventListener('pointermove', move, true);
|
|
1235
|
+
removeEventListener('pointerup', up, true);
|
|
1236
|
+
removeEventListener('keydown', esc, true);
|
|
1237
|
+
if (!lens) return;
|
|
1238
|
+
lens.remove();
|
|
1239
|
+
dragged = true;
|
|
1240
|
+
ev.preventDefault();
|
|
1241
|
+
if (!cancelled && color) pick(color);
|
|
1242
|
+
};
|
|
1243
|
+
// Escape drops it: the color stays as it was
|
|
1244
|
+
const esc = (ev) => {
|
|
1245
|
+
if (ev.key !== 'Escape' || !lens) return;
|
|
1246
|
+
ev.preventDefault();
|
|
1247
|
+
cancelled = true;
|
|
1248
|
+
lens.remove();
|
|
1249
|
+
removeEventListener('pointermove', move, true);
|
|
1250
|
+
};
|
|
1251
|
+
addEventListener('pointermove', move, true);
|
|
1252
|
+
addEventListener('pointerup', up, true);
|
|
1253
|
+
addEventListener('keydown', esc, true);
|
|
1254
|
+
});
|
|
1255
|
+
}
|
|
1256
|
+
// a magnifier beside the point, not over it: a copy of the page, scaled up around the point, in a circle up and to
|
|
1257
|
+
// the right (or wherever there's room), joined to a ring at the point by a line. The circle's rim is the color
|
|
1258
|
+
const LENS = { r: 64, zoom: 3, off: 96 };
|
|
1259
|
+
function sampler() {
|
|
1260
|
+
const lens = el('div', 'slop-sampler', '<svg aria-hidden="true"><line></line></svg><i class="slop-sampler-ring"></i>'
|
|
1261
|
+
+ '<b class="slop-sampler-lens"><span class="slop-sampler-page"></span><i class="slop-sampler-dot"></i></b><span class="slop-sampler-hex"></span>');
|
|
1262
|
+
const [line, ring, big, view, label] = ['line', '.slop-sampler-ring', '.slop-sampler-lens', '.slop-sampler-page', '.slop-sampler-hex'].map((q) => lens.querySelector(q));
|
|
1263
|
+
Object.assign(big.style, { width: `${LENS.r * 2}px`, height: `${LENS.r * 2}px` });
|
|
1264
|
+
const root = getComputedStyle(document.documentElement).backgroundColor;
|
|
1265
|
+
const body = getComputedStyle(document.body).backgroundColor;
|
|
1266
|
+
view.style.background = /rgba\([^)]*,\s*0\)|transparent/.test(body) ? root : body;
|
|
1267
|
+
view.style.width = `${document.documentElement.clientWidth}px`;
|
|
1268
|
+
const copy = document.body.cloneNode(true);
|
|
1269
|
+
view.append(copy);
|
|
1270
|
+
document.body.append(lens);
|
|
1271
|
+
document.documentElement.classList.add('slop-sampling');
|
|
1272
|
+
place(document.body, copy, view);
|
|
1273
|
+
return {
|
|
1274
|
+
show(x, y, color) {
|
|
1275
|
+
const { r, zoom, off } = LENS;
|
|
1276
|
+
const cx = x + (x > innerWidth - off - r - 8 ? -off : off);
|
|
1277
|
+
const cy = y + (y < off + r + 8 ? off : -off);
|
|
1278
|
+
Object.assign(ring.style, { left: `${x}px`, top: `${y}px` });
|
|
1279
|
+
Object.assign(big.style, { left: `${cx}px`, top: `${cy}px`, borderColor: color ?? '#fff' });
|
|
1280
|
+
view.style.transform = `translate(${r - (x + scrollX) * zoom}px, ${r - (y + scrollY) * zoom}px) scale(${zoom})`;
|
|
1281
|
+
Object.assign(label.style, { left: `${cx}px`, top: `${cy + r + 18}px` });
|
|
1282
|
+
label.textContent = color ?? '';
|
|
1283
|
+
// the line runs from the ring to the circle's rim
|
|
1284
|
+
const d = Math.hypot(cx - x, cy - y);
|
|
1285
|
+
const ex = cx - ((cx - x) / d) * (r + 3);
|
|
1286
|
+
const ey = cy - ((cy - y) / d) * (r + 3);
|
|
1287
|
+
[['x1', x], ['y1', y], ['x2', ex], ['y2', ey]].forEach(([k, v]) => line.setAttribute(k, v));
|
|
1288
|
+
},
|
|
1289
|
+
remove() { lens.remove(); document.documentElement.classList.remove('slop-sampling'); },
|
|
1290
|
+
};
|
|
1291
|
+
}
|
|
1292
|
+
// the copy shows the page as it is on screen: what's fixed or sticky where it is now, panels scrolled as they are,
|
|
1293
|
+
// and canvases drawn
|
|
1294
|
+
function place(from, to, view) {
|
|
1295
|
+
const a = document.createTreeWalker(from, NodeFilter.SHOW_ELEMENT);
|
|
1296
|
+
const b = document.createTreeWalker(to, NodeFilter.SHOW_ELEMENT);
|
|
1297
|
+
const pinned = [];
|
|
1298
|
+
const scrolled = [];
|
|
1299
|
+
for (let x = a.currentNode, y = b.currentNode; x && y; x = a.nextNode(), y = b.nextNode()) {
|
|
1300
|
+
if (x.classList?.contains('slop-sampler')) break; // the magnifier itself, if it got copied
|
|
1301
|
+
const pos = getComputedStyle(x).position;
|
|
1302
|
+
if (pos === 'fixed' || pos === 'sticky') pinned.push([x, y]);
|
|
1303
|
+
if (x.scrollTop || x.scrollLeft) scrolled.push([x, y]);
|
|
1304
|
+
if (x instanceof HTMLCanvasElement && y instanceof HTMLCanvasElement) {
|
|
1305
|
+
try { y.getContext('2d').drawImage(x, 0, 0); } catch { /* a canvas it can't read */ }
|
|
1306
|
+
}
|
|
1307
|
+
}
|
|
1308
|
+
const box = view.getBoundingClientRect();
|
|
1309
|
+
pinned.forEach(([x, y]) => {
|
|
1310
|
+
const want = x.getBoundingClientRect();
|
|
1311
|
+
const got = y.getBoundingClientRect();
|
|
1312
|
+
y.style.translate = `${want.left + scrollX - (got.left - box.left)}px ${want.top + scrollY - (got.top - box.top)}px`;
|
|
1313
|
+
});
|
|
1314
|
+
scrolled.forEach(([x, y]) => { y.scrollTop = x.scrollTop; y.scrollLeft = x.scrollLeft; });
|
|
1315
|
+
}
|
|
1316
|
+
// the color on the page at a point: a letter's color over a letter, a shape's fill, an image's pixel (when the
|
|
1317
|
+
// browser lets it be read), or else the first background that isn't see-through
|
|
1318
|
+
function colorAt(x, y) {
|
|
1319
|
+
const els = document.elementsFromPoint(x, y);
|
|
1320
|
+
const top = els[0];
|
|
1321
|
+
if (!top) return null;
|
|
1322
|
+
const seen = (c) => { const m = /rgba?\([^)]*?([\d.]+)\)$/.exec(c); return c && c !== 'transparent' && !(c.startsWith('rgba') && m && +m[1] === 0); };
|
|
1323
|
+
if (top instanceof HTMLImageElement || top instanceof HTMLCanvasElement) {
|
|
1324
|
+
try {
|
|
1325
|
+
const r = top.getBoundingClientRect();
|
|
1326
|
+
const w = top.naturalWidth ?? top.width;
|
|
1327
|
+
const h = top.naturalHeight ?? top.height;
|
|
1328
|
+
const c = Object.assign(document.createElement('canvas'), { width: 1, height: 1 }).getContext('2d');
|
|
1329
|
+
c.drawImage(top, ((x - r.left) / r.width) * w, ((y - r.top) / r.height) * h, 1, 1, 0, 0, 1, 1);
|
|
1330
|
+
const [rr, g, b, a] = c.getImageData(0, 0, 1, 1).data;
|
|
1331
|
+
if (a) return hex(`rgb(${rr}, ${g}, ${b})`);
|
|
1332
|
+
} catch { /* another site's image: its pixels can't be read */ }
|
|
1333
|
+
}
|
|
1334
|
+
const caret = document.caretRangeFromPoint?.(x, y) ?? (() => { const p = document.caretPositionFromPoint?.(x, y); if (!p) return null; const r = document.createRange(); r.setStart(p.offsetNode, p.offset); return r; })();
|
|
1335
|
+
const node = caret?.startContainer;
|
|
1336
|
+
if (node?.nodeType === 3 && top.contains(node)) {
|
|
1337
|
+
for (const i of [caret.startOffset - 1, caret.startOffset]) {
|
|
1338
|
+
if (i < 0 || i >= node.length || !node.data[i].trim()) continue;
|
|
1339
|
+
const r = document.createRange();
|
|
1340
|
+
r.setStart(node, i);
|
|
1341
|
+
r.setEnd(node, i + 1);
|
|
1342
|
+
const b = r.getBoundingClientRect();
|
|
1343
|
+
if (x >= b.left && x <= b.right && y >= b.top && y <= b.bottom) return hex(getComputedStyle(node.parentElement).color);
|
|
1344
|
+
}
|
|
1345
|
+
}
|
|
1346
|
+
if (top instanceof SVGElement && seen(getComputedStyle(top).fill)) return hex(getComputedStyle(top).fill);
|
|
1347
|
+
for (const e of els) {
|
|
1348
|
+
const bg = getComputedStyle(e).backgroundColor;
|
|
1349
|
+
if (seen(bg)) return hex(bg);
|
|
1350
|
+
}
|
|
1351
|
+
return hex(getComputedStyle(document.documentElement).backgroundColor) || '#ffffff';
|
|
1352
|
+
}
|
|
1353
|
+
|
|
1354
|
+
// a category's own color, or (null) its default
|
|
1355
|
+
function setColor(id, color) {
|
|
1356
|
+
if (color) { own(id).color = color; return; }
|
|
1357
|
+
const c = text._categories?.[id];
|
|
1358
|
+
if (!c) return;
|
|
1359
|
+
delete c.color;
|
|
1360
|
+
if (!Object.keys(c).length) delete text._categories[id];
|
|
1361
|
+
if (!Object.keys(text._categories).length) delete text._categories;
|
|
856
1362
|
}
|
|
857
1363
|
|
|
858
1364
|
/* marking text: the focused field gets a row of categories. A selection, or the whole text, becomes theirs */
|
|
@@ -1176,6 +1682,8 @@ const Slop = (() => {
|
|
|
1176
1682
|
$('.sp-big b').textContent = percent(page.letters ? (page.counts.ai ?? 0) / page.letters : 0);
|
|
1177
1683
|
$('.sp-words').textContent = count(page.allWords, 'word');
|
|
1178
1684
|
aside.querySelectorAll('.sp-seg button').forEach((b) => b.setAttribute('aria-checked', String(b.dataset.show === shows())));
|
|
1685
|
+
const revert = $('.sp-cat-revert');
|
|
1686
|
+
if (revert) revert.hidden = !Object.values(text._categories ?? {}).some((c) => c.color);
|
|
1179
1687
|
aside.querySelectorAll('.sp-cat').forEach((row) => {
|
|
1180
1688
|
row.querySelector('.sp-cat-pct').textContent = percent(page.letters ? (page.counts[row.dataset.id] ?? 0) / page.letters : 0);
|
|
1181
1689
|
});
|
|
@@ -1366,7 +1874,9 @@ const Slop = (() => {
|
|
|
1366
1874
|
if (stale) { status('This page is out of date: reload it to save (copy any edits first)', 'error'); return; }
|
|
1367
1875
|
const body = JSON.stringify(text);
|
|
1368
1876
|
if (mode === 'local') {
|
|
1369
|
-
|
|
1877
|
+
// with the page as it was published, so the copy can be carried over to the author's next version
|
|
1878
|
+
const kept = store.set(LOCAL, JSON.stringify({ base: JSON.parse(original).version, baseText: JSON.parse(original), text: JSON.parse(body) }));
|
|
1879
|
+
if (!kept) { status("Couldn't save in this browser", 'error'); return; }
|
|
1370
1880
|
saved = JSON.parse(body);
|
|
1371
1881
|
undo = null;
|
|
1372
1882
|
keepDraft();
|
|
@@ -1414,7 +1924,7 @@ const Slop = (() => {
|
|
|
1414
1924
|
addEventListener('beforeunload', (e) => { if (busy || unsaved()) { e.preventDefault(); e.returnValue = ''; } });
|
|
1415
1925
|
// a reload keeps what isn't saved, in this tab, still unsaved: a page in a frame (or a browser that skips the
|
|
1416
1926
|
// 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:${
|
|
1927
|
+
const DRAFT = `slop-draft:${pageKey()}`;
|
|
1418
1928
|
const keepDraft = () => {
|
|
1419
1929
|
if (unsaved() && !stale) session.set(DRAFT, JSON.stringify({ base: saved.version, text }));
|
|
1420
1930
|
else session.drop(DRAFT);
|
|
@@ -1520,7 +2030,7 @@ const Slop = (() => {
|
|
|
1520
2030
|
document.documentElement.classList.toggle('slop-editing', on);
|
|
1521
2031
|
editing = on;
|
|
1522
2032
|
paintShow();
|
|
1523
|
-
if (!on) { mark(false); unreveal(); return; }
|
|
2033
|
+
if (!on) { mark(false); unreveal(); closePicker(); return; }
|
|
1524
2034
|
place();
|
|
1525
2035
|
render();
|
|
1526
2036
|
};
|
|
@@ -1567,7 +2077,9 @@ const Slop = (() => {
|
|
|
1567
2077
|
}
|
|
1568
2078
|
|
|
1569
2079
|
// set things up once the page has filled in Slop.vars. Options: code (the class `code` renders with),
|
|
1570
|
-
// edit: 'local' (an editor anyone can use, saving in their browser; under `slop-editor edit` it saves into the file)
|
|
2080
|
+
// edit: 'local' (an editor anyone can use, saving in their browser; under `slop-editor edit` it saves into the file),
|
|
2081
|
+
// key (the name the browser editor saves under, for a host that gives each version of the page an address of its
|
|
2082
|
+
// own; the page's path otherwise)
|
|
1571
2083
|
function start(options = {}) {
|
|
1572
2084
|
Object.assign(config, options);
|
|
1573
2085
|
fill();
|
|
@@ -1578,12 +2090,20 @@ const Slop = (() => {
|
|
|
1578
2090
|
[document.documentElement, document.body].forEach((x) => watch.observe(x, { attributes: true, attributeFilter: ['class', 'data-theme', 'style'] }));
|
|
1579
2091
|
matchMedia('(prefers-color-scheme: dark)').addEventListener('change', theme);
|
|
1580
2092
|
setMeter(store.get('slop-o-meter') !== 'off'); // on unless this reader turned it off
|
|
1581
|
-
// the browser editor: what this visitor changed last time
|
|
2093
|
+
// the browser editor: what this visitor changed last time. If the author has published a new version since,
|
|
2094
|
+
// their changes win and the visitor's stay everywhere else (a copy saved before 0.4 has no baseText, so it's dropped)
|
|
1582
2095
|
const local = () => {
|
|
1583
2096
|
if (options.edit !== 'local') return;
|
|
2097
|
+
const key = `slop-text:${pageKey()}`;
|
|
1584
2098
|
try {
|
|
1585
|
-
const saved = JSON.parse(store.get(
|
|
2099
|
+
const saved = JSON.parse(store.get(key));
|
|
1586
2100
|
if (saved?.base === text.version) { text = saved.text; applyColors(); changed(); }
|
|
2101
|
+
else if (saved?.baseText && saved.text) {
|
|
2102
|
+
text = rebase(saved.baseText, saved.text, text);
|
|
2103
|
+
store.set(key, JSON.stringify({ base: text.version, baseText: JSON.parse(original), text }));
|
|
2104
|
+
applyColors();
|
|
2105
|
+
changed();
|
|
2106
|
+
}
|
|
1587
2107
|
} catch { /* nothing saved */ }
|
|
1588
2108
|
ed = editor('local');
|
|
1589
2109
|
};
|