@pirateandfox/pagestack 0.1.0-beta.4 → 0.1.0-beta.6
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 +105 -13
- package/bin/invite.mjs +1 -1
- package/index.mjs +34 -5
- package/package.json +9 -4
- package/src/client/collection.ts +37 -0
- package/src/client/editor.ts +769 -182
- package/src/client/form.ts +84 -12
- package/src/client/global.ts +33 -0
- package/src/client/icons.ts +27 -0
- package/src/client/inline.ts +29 -35
- package/src/client/inserter.ts +59 -0
- package/src/client/invite.ts +1 -1
- package/src/client/item.ts +107 -0
- package/src/client/media.ts +81 -0
- package/src/client/pages.ts +89 -0
- package/src/client/picker.ts +24 -10
- package/src/client/preview.css +58 -16
- package/src/client/rich.ts +232 -0
- package/src/client/shell.css +200 -20
- package/src/client/state.ts +3 -1
- package/src/client/tree.ts +32 -9
- package/src/client/ui.ts +122 -0
- package/src/client/upload.ts +25 -0
- package/src/client/users.ts +40 -0
- package/src/core/auth.ts +8 -2
- package/src/core/frontmatter.ts +29 -0
- package/src/core/insert.ts +70 -0
- package/src/core/media.ts +37 -0
- package/src/core/pages.ts +52 -0
- package/src/core/patch.ts +2 -1
- package/src/core/ratelimit.ts +13 -0
- package/src/core/sanitize.ts +268 -0
- package/src/core/schema.ts +10 -1
- package/src/core/storage-github.ts +57 -21
- package/src/core/storage-local.ts +22 -5
- package/src/core/storage.ts +19 -3
- package/src/core/synced.ts +19 -0
- package/src/core/transform.ts +66 -0
- package/src/core/users.ts +34 -2
- package/src/routes/Nav.astro +22 -0
- package/src/routes/api/asset.ts +1 -1
- package/src/routes/api/auth.ts +7 -6
- package/src/routes/api/collection.ts +89 -0
- package/src/routes/api/global.ts +33 -0
- package/src/routes/api/images.ts +32 -16
- package/src/routes/api/page.ts +57 -14
- package/src/routes/api/pages.ts +39 -1
- package/src/routes/api/patterns.ts +68 -0
- package/src/routes/api/users.ts +46 -0
- package/src/routes/edit-collection.astro +47 -0
- package/src/routes/edit-global.astro +39 -0
- package/src/routes/edit-index.astro +40 -24
- package/src/routes/edit-item.astro +57 -0
- package/src/routes/edit-media.astro +30 -0
- package/src/routes/edit-page.astro +29 -19
- package/src/routes/edit-users.astro +43 -0
- package/src/routes/login.astro +2 -3
- package/src/routes/preview.astro +15 -5
- package/src/runtime.ts +70 -1
- package/src/server/context.ts +112 -10
- package/src/server/middleware.ts +79 -21
- package/src/server/webauthn.ts +8 -8
- package/src/virtual.d.ts +1 -1
package/src/client/editor.ts
CHANGED
|
@@ -1,30 +1,50 @@
|
|
|
1
|
-
// The editor controller: wires the preview iframe,
|
|
2
|
-
// history and saving together. Framework-free on purpose (small, no build-time coupling).
|
|
3
|
-
import type {
|
|
4
|
-
import { cloneWithNewIds
|
|
5
|
-
import { getAt, insertNode, isNodePath, moveNode, nodeAt, nodePathOf, removeNode, setAt, splitNodePath
|
|
6
|
-
import {
|
|
1
|
+
// The editor controller: wires the preview iframe, List View, the inserter, the Page/Block sidebar,
|
|
2
|
+
// inline editing, history and saving together. Framework-free on purpose (small, no build-time coupling).
|
|
3
|
+
import type { Field, Node, PageDoc, SchemaRegistry } from '../runtime';
|
|
4
|
+
import { cloneWithNewIds } from '../runtime';
|
|
5
|
+
import { getAt, insertNode, isNodePath, moveNode, nodeAt, nodePathOf, pathOfId, removeNode, replaceNode, setAt, splitNodePath } from '../core/patch';
|
|
6
|
+
import { transformNode, transformTargets } from '../core/transform';
|
|
7
|
+
import { accepts, allowedChildTypes, createNode, nodeLabel } from '../core/schema';
|
|
8
|
+
import type { InsertItem, Pattern, SavedPattern } from '../core/insert';
|
|
9
|
+
import { insertItems } from '../core/insert';
|
|
10
|
+
import { slugProblem } from '../core/pages';
|
|
11
|
+
import type { Revision } from '../core/storage';
|
|
7
12
|
import { EditorState } from './state';
|
|
8
13
|
import { renderForm } from './form';
|
|
9
14
|
import { renderTree } from './tree';
|
|
15
|
+
import { renderInserter } from './inserter';
|
|
10
16
|
import { InlineEditor } from './inline';
|
|
11
17
|
import { pickImage } from './picker';
|
|
18
|
+
import { icons } from './icons';
|
|
19
|
+
import type { MenuItem } from './ui';
|
|
20
|
+
import { confirmDialog, dialog, openMenu, promptDialog, toast } from './ui';
|
|
12
21
|
import previewCss from './preview.css?raw';
|
|
13
22
|
|
|
14
23
|
interface Boot {
|
|
15
24
|
slug: string; page: PageDoc; hash: string; registry: SchemaRegistry;
|
|
16
|
-
presets:
|
|
25
|
+
presets: Pattern[]; patterns: SavedPattern[];
|
|
26
|
+
pageFields: Record<string, Field>;
|
|
17
27
|
pages: { slug: string; title: string; url: string }[];
|
|
18
|
-
|
|
28
|
+
reserved: string[];
|
|
29
|
+
options: { storage: string; auth: string; siteName: string; user: string | null; pullRequest: boolean; viewUrl: string; interactiveSelector: string; redirects: boolean };
|
|
19
30
|
}
|
|
20
31
|
const boot = (window as any).__ASE__ as Boot;
|
|
21
32
|
const { registry } = boot;
|
|
22
33
|
const $ = <T extends HTMLElement = HTMLElement>(sel: string) => document.querySelector<T>(sel)!;
|
|
23
34
|
const iframe = $<HTMLIFrameElement>('#ase-preview');
|
|
24
35
|
const state = new EditorState(boot.slug, boot.page, boot.hash);
|
|
36
|
+
const isHome = boot.slug === 'index';
|
|
25
37
|
let selected: string | null = null;
|
|
26
|
-
let
|
|
38
|
+
let tab: 'page' | 'block' = 'page';
|
|
39
|
+
let renderSeq = 0, renderTimer: ReturnType<typeof setTimeout> | undefined, previewReady = false;
|
|
40
|
+
let renderQueued = false, renderFull = false, leaving = false, saving = false;
|
|
41
|
+
/** Field being edited live; one continuous edit is one undo step. */
|
|
42
|
+
let livePath: string | null = null;
|
|
43
|
+
/** Path to scroll to once the next render lands. */
|
|
44
|
+
let reveal: string | null = null;
|
|
45
|
+
let patterns = boot.patterns;
|
|
27
46
|
const iconsField = Object.values(registry).flatMap((s) => Object.values(s.fields)).find((f) => f.type === 'svg' && f.icons)?.icons ?? [];
|
|
47
|
+
const pageLinks = boot.pages.map((p) => ({ url: p.url, title: p.title.split(/\s[-–|]\s/)[0] }));
|
|
28
48
|
|
|
29
49
|
// ---------- restore a draft ----------
|
|
30
50
|
{
|
|
@@ -35,23 +55,41 @@ const iconsField = Object.values(registry).flatMap((s) => Object.values(s.fields
|
|
|
35
55
|
|
|
36
56
|
// ---------- preview iframe ----------
|
|
37
57
|
const idoc = () => iframe.contentDocument!;
|
|
38
|
-
const
|
|
58
|
+
const iwin = () => iframe.contentWindow!;
|
|
59
|
+
const isTop = (path: string) => /^sections\.\d+$/.test(path);
|
|
60
|
+
const topSections = (doc: Document) => Array.from(doc.querySelectorAll<HTMLElement>('[data-ase-node]')).filter((el) => isTop(el.dataset.aseNode!));
|
|
61
|
+
const nodeEl = (path: string) => idoc().querySelector<HTMLElement>(`[data-ase-node="${path}"]`);
|
|
39
62
|
|
|
40
|
-
|
|
63
|
+
/** Where sections live in the page, remembered so an emptied page can still be filled. */
|
|
64
|
+
let sectionHost: HTMLElement | null = null;
|
|
65
|
+
/** Rendered HTML per section, so an update replaces only what changed and widgets elsewhere keep working. */
|
|
66
|
+
let lastHtml: string[] = [];
|
|
67
|
+
|
|
68
|
+
function onPreviewLoad() {
|
|
41
69
|
const d = idoc();
|
|
42
70
|
const style = d.createElement('style'); style.textContent = previewCss; d.head.append(style);
|
|
43
71
|
d.addEventListener('click', onPreviewClick, true);
|
|
44
72
|
d.addEventListener('submit', (e) => e.preventDefault(), true);
|
|
45
73
|
d.addEventListener('mouseover', onPreviewHover);
|
|
46
|
-
d.addEventListener('
|
|
74
|
+
d.addEventListener('mousemove', onPreviewMove, { passive: true });
|
|
75
|
+
d.addEventListener('mouseleave', () => { hover(null); showPlus(null); });
|
|
47
76
|
d.addEventListener('keydown', onKeydown);
|
|
77
|
+
iwin().addEventListener('scroll', placeOverlays, { passive: true });
|
|
78
|
+
iwin().addEventListener('resize', placeOverlays, { passive: true });
|
|
79
|
+
sectionHost = topSections(d)[0]?.parentElement ?? d.querySelector('main') ?? d.body;
|
|
80
|
+
d.documentElement.style.setProperty('--ase-ui', String(uiScale));
|
|
48
81
|
previewReady = true;
|
|
49
|
-
if (state.dirty) render(); else decorate();
|
|
50
|
-
}
|
|
82
|
+
if (state.dirty) render(); else { decorate(); seedHtml(); }
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
async function seedHtml() {
|
|
86
|
+
const html = await (await fetch(iframe.src)).text().catch(() => '');
|
|
87
|
+
if (html && !lastHtml.length) lastHtml = topSections(new DOMParser().parseFromString(html, 'text/html')).map((e) => e.outerHTML);
|
|
88
|
+
}
|
|
51
89
|
|
|
52
90
|
function onPreviewHover(e: MouseEvent) {
|
|
53
91
|
const t = e.target as HTMLElement;
|
|
54
|
-
if (t.closest('[data-ase-
|
|
92
|
+
if (t.closest('[data-ase-ui]')) return;
|
|
55
93
|
hover(t.closest<HTMLElement>('[data-ase-node]'));
|
|
56
94
|
}
|
|
57
95
|
function hover(el: HTMLElement | null) {
|
|
@@ -60,7 +98,7 @@ function hover(el: HTMLElement | null) {
|
|
|
60
98
|
}
|
|
61
99
|
function onPreviewClick(e: MouseEvent) {
|
|
62
100
|
const t = e.target as HTMLElement;
|
|
63
|
-
if (t.closest('[data-ase-toolbar], .ase-
|
|
101
|
+
if (t.closest('[data-ase-ui], [data-ase-toolbar], .ase-popmenu')) return; // handled by their own listeners
|
|
64
102
|
const field = t.closest<HTMLElement>('[data-ase-field]');
|
|
65
103
|
const node = t.closest<HTMLElement>('[data-ase-node]');
|
|
66
104
|
// Let the page's own interactive bits work (accordion summaries, tab titles…); block navigation.
|
|
@@ -79,301 +117,850 @@ function onPreviewClick(e: MouseEvent) {
|
|
|
79
117
|
}
|
|
80
118
|
|
|
81
119
|
const inline = new InlineEditor({
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
120
|
+
onSlash: (fieldPath) => slash(fieldPath),
|
|
121
|
+
pages: pageLinks,
|
|
122
|
+
onStart: () => { state.snapshot(); idoc().body.setAttribute('data-ase-typing', ''); },
|
|
123
|
+
onInput: (path, value) => { state.apply(setAt(state.doc, path, value), 'inline', false); refreshButtons(); },
|
|
124
|
+
onCommit: (path, value, changed) => {
|
|
125
|
+
idoc().body.removeAttribute('data-ase-typing');
|
|
126
|
+
if (changed) state.apply(setAt(state.doc, path, value), 'inline', false); else state.dropSnapshot();
|
|
127
|
+
refreshChrome();
|
|
128
|
+
if (changed || renderQueued) scheduleRender(0);
|
|
129
|
+
renderQueued = false;
|
|
130
|
+
},
|
|
85
131
|
});
|
|
86
132
|
|
|
87
133
|
async function render() {
|
|
88
134
|
if (!previewReady) return;
|
|
135
|
+
// Never swap the element under someone's cursor: this waits for the inline edit to finish.
|
|
136
|
+
if (inline.isActive) { renderQueued = true; return; }
|
|
89
137
|
const seq = ++renderSeq;
|
|
90
|
-
|
|
138
|
+
setSaveStatus('Rendering…');
|
|
91
139
|
try {
|
|
92
140
|
const res = await fetch(`/edit/preview/${boot.slug}`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ page: state.doc }) });
|
|
93
141
|
if (seq !== renderSeq) return;
|
|
94
142
|
const html = await res.text();
|
|
95
|
-
if (!res.ok) {
|
|
143
|
+
if (!res.ok) { setSaveStatus(''); toast(`Preview failed: ${html.slice(0, 200)}`, 'error'); return; }
|
|
144
|
+
if (inline.isActive) { renderQueued = true; setSaveStatus(''); return; }
|
|
96
145
|
swap(html);
|
|
97
|
-
|
|
146
|
+
setSaveStatus('');
|
|
98
147
|
} catch (e: any) { if (seq === renderSeq) toast(`Preview failed: ${e.message}`, 'error'); }
|
|
99
148
|
}
|
|
100
149
|
function scheduleRender(ms = 150) { clearTimeout(renderTimer); renderTimer = setTimeout(render, ms); }
|
|
101
150
|
|
|
102
|
-
/**
|
|
151
|
+
/** Update the preview from fresh HTML, section by section (or the whole body for page-level changes). */
|
|
103
152
|
function swap(html: string) {
|
|
104
153
|
const fresh = new DOMParser().parseFromString(html, 'text/html');
|
|
105
154
|
const next = topSections(fresh);
|
|
155
|
+
const nextHtml = next.map((e) => e.outerHTML);
|
|
106
156
|
const d = idoc();
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
157
|
+
if (renderFull) {
|
|
158
|
+
renderFull = false;
|
|
159
|
+
d.body.innerHTML = fresh.body.innerHTML;
|
|
160
|
+
d.body.className = fresh.body.className;
|
|
161
|
+
sectionHost = topSections(d)[0]?.parentElement ?? d.querySelector('main') ?? d.body;
|
|
162
|
+
} else {
|
|
163
|
+
const cur = topSections(d);
|
|
164
|
+
for (let i = 0; i < Math.max(cur.length, next.length); i++) {
|
|
165
|
+
const a = cur[i], b = next[i];
|
|
166
|
+
if (a && b) { if (nextHtml[i] !== lastHtml[i]) a.replaceWith(d.importNode(b, true)); }
|
|
167
|
+
else if (b) {
|
|
168
|
+
const last = topSections(d).pop();
|
|
169
|
+
const copy = d.importNode(b, true);
|
|
170
|
+
if (last) last.after(copy); else sectionHost!.append(copy);
|
|
171
|
+
} else a?.remove();
|
|
172
|
+
}
|
|
115
173
|
}
|
|
174
|
+
lastHtml = nextHtml;
|
|
116
175
|
decorate();
|
|
176
|
+
if (reveal) { nodeEl(reveal)?.scrollIntoView({ block: 'center', behavior: 'smooth' }); reveal = null; }
|
|
117
177
|
}
|
|
118
178
|
|
|
119
|
-
/** Re-apply selection highlight +
|
|
179
|
+
/** Re-apply selection highlight + overlays after the DOM changed. */
|
|
120
180
|
function decorate() {
|
|
121
181
|
const d = idoc();
|
|
122
182
|
d.querySelectorAll('[data-ase-selected]').forEach((x) => x.removeAttribute('data-ase-selected'));
|
|
123
|
-
d.
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
183
|
+
d.querySelector('.ase-toolbar')?.remove();
|
|
184
|
+
const el = selected ? nodeEl(selected) : null;
|
|
185
|
+
if (el) { el.setAttribute('data-ase-selected', ''); mountToolbar(el); }
|
|
186
|
+
decorateEmpty();
|
|
187
|
+
placeOverlays();
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/** A page with no blocks yet says what to do next, like a new post in the block editor. */
|
|
191
|
+
function decorateEmpty() {
|
|
192
|
+
const d = idoc();
|
|
193
|
+
const empty = !state.doc.sections.length;
|
|
194
|
+
const box = d.querySelector('.ase-empty');
|
|
195
|
+
if (!empty) { box?.remove(); return; }
|
|
196
|
+
if (box) return;
|
|
197
|
+
const div = d.createElement('div');
|
|
198
|
+
div.className = 'ase-empty'; div.setAttribute('data-ase-ui', '');
|
|
199
|
+
div.innerHTML = `<p class="ase-empty__title">This page is empty</p><p>Add your first block to get started.</p><button type="button">${icons.plus} Add block</button>`;
|
|
200
|
+
div.querySelector('button')!.addEventListener('click', () => openInserter({ listPath: 'sections', index: 0 }));
|
|
201
|
+
sectionHost?.append(div);
|
|
128
202
|
}
|
|
129
203
|
|
|
130
204
|
function mountToolbar(el: HTMLElement) {
|
|
131
205
|
const d = idoc();
|
|
132
206
|
const path = el.dataset.aseNode!;
|
|
133
207
|
const node = nodeAt(state.doc, path)!;
|
|
134
|
-
const
|
|
208
|
+
const canAdd = !!allowedChildTypes(node.type, registry)?.length;
|
|
135
209
|
const tb = d.createElement('div');
|
|
136
|
-
tb.className = 'ase-toolbar'
|
|
137
|
-
tb.
|
|
210
|
+
tb.className = 'ase-toolbar';
|
|
211
|
+
tb.setAttribute('data-ase-ui', '');
|
|
212
|
+
tb.setAttribute('role', 'toolbar');
|
|
213
|
+
tb.setAttribute('aria-label', 'Block tools');
|
|
214
|
+
tb.innerHTML = `${isTop(path) ? '' : `<button type="button" data-act="parent" title="Select parent block" aria-label="Select parent block">${icons.parent}</button>`}<span class="ase-grip" title="Drag to move">${icons.grip}</span><span class="ase-toolbar__label"></span><button type="button" data-act="up" title="Move up" aria-label="Move up">${icons.up}</button><button type="button" data-act="down" title="Move down" aria-label="Move down">${icons.down}</button>${canAdd ? `<button type="button" data-act="add" title="Add a block inside" aria-label="Add a block inside">${icons.plus}</button>` : ''}<button type="button" data-act="more" title="Options" aria-label="Options">${icons.more}</button>`;
|
|
138
215
|
tb.querySelector('.ase-toolbar__label')!.textContent = registry[node.type]?.label ?? node.type;
|
|
139
|
-
tb.addEventListener('click', (e) => {
|
|
216
|
+
tb.addEventListener('click', (e) => {
|
|
217
|
+
const b = (e.target as HTMLElement).closest('button');
|
|
218
|
+
if (!b) return;
|
|
219
|
+
e.preventDefault(); e.stopPropagation();
|
|
220
|
+
if (b.dataset.act === 'more') openMenu(b, blockMenu(path)); else act(b.dataset.act!);
|
|
221
|
+
});
|
|
140
222
|
tb.addEventListener('mousedown', (e) => e.stopPropagation());
|
|
141
|
-
|
|
142
|
-
|
|
223
|
+
d.body.append(tb);
|
|
224
|
+
tb.querySelector('.ase-grip')!.addEventListener('pointerdown', (e) => startDrag(e as PointerEvent, el));
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/** Keep the floating pieces next to what they belong to; the page can scroll under them. */
|
|
228
|
+
function placeOverlays() {
|
|
229
|
+
if (!previewReady) return;
|
|
230
|
+
const d = idoc();
|
|
231
|
+
const tb = d.querySelector<HTMLElement>('.ase-toolbar');
|
|
232
|
+
const el = selected ? nodeEl(selected) : null;
|
|
233
|
+
if (tb && el) {
|
|
234
|
+
const r = el.getBoundingClientRect();
|
|
235
|
+
const vw = iwin().innerWidth;
|
|
236
|
+
const visible = r.bottom > 0 && r.top < iwin().innerHeight;
|
|
237
|
+
tb.style.visibility = visible ? '' : 'hidden';
|
|
238
|
+
const size = tb.getBoundingClientRect(); // measured, because a scaled preview scales this back up
|
|
239
|
+
tb.style.top = `${Math.max(4, r.top - size.height - 6)}px`;
|
|
240
|
+
tb.style.left = `${Math.max(4, Math.min(r.left, vw - size.width - 4))}px`;
|
|
241
|
+
}
|
|
242
|
+
const line = d.querySelector<HTMLElement>('.ase-insertline');
|
|
243
|
+
if (line) {
|
|
244
|
+
const y = target ? insertionY(target) : null;
|
|
245
|
+
line.style.display = y === null ? 'none' : '';
|
|
246
|
+
if (y !== null) line.style.top = `${y}px`;
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
/** Screen position of an insertion point in a vertical list. */
|
|
251
|
+
function insertionY(t: Target): number | null {
|
|
252
|
+
const kids = siblings(t.listPath);
|
|
253
|
+
if (kids.length) {
|
|
254
|
+
const at = kids[t.index];
|
|
255
|
+
return at ? at.getBoundingClientRect().top : kids[kids.length - 1].getBoundingClientRect().bottom;
|
|
256
|
+
}
|
|
257
|
+
return t.listPath === 'sections' ? null : nodeEl(t.listPath.replace(/\.blocks$/, ''))?.getBoundingClientRect().bottom ?? null;
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
function siblings(listPath: string): HTMLElement[] {
|
|
261
|
+
const re = new RegExp(`^${listPath.replace(/\./g, '\\.')}\\.(\\d+)$`);
|
|
262
|
+
return Array.from(idoc().querySelectorAll<HTMLElement>('[data-ase-node]')).filter((e) => re.test(e.dataset.aseNode!)).sort((a, b) => Number(a.dataset.aseNode!.match(re)![1]) - Number(b.dataset.aseNode!.match(re)![1]));
|
|
143
263
|
}
|
|
144
264
|
|
|
145
|
-
/**
|
|
265
|
+
/** Drag a block to reorder it among its siblings, in whichever direction they are laid out. */
|
|
146
266
|
function startDrag(e: PointerEvent, el: HTMLElement) {
|
|
147
267
|
e.preventDefault();
|
|
148
268
|
const d = idoc();
|
|
149
|
-
const
|
|
150
|
-
const from =
|
|
151
|
-
const
|
|
269
|
+
const path = el.dataset.aseNode!;
|
|
270
|
+
const { listPath, index: from } = splitNodePath(path);
|
|
271
|
+
const kids = siblings(listPath);
|
|
272
|
+
if (kids.length < 2) return;
|
|
273
|
+
const [a, b] = [kids[0].getBoundingClientRect(), kids[1].getBoundingClientRect()];
|
|
274
|
+
const horizontal = Math.abs(a.top - b.top) < a.height / 2;
|
|
275
|
+
const line = d.createElement('div'); line.className = `ase-dropline${horizontal ? ' ase-dropline--v' : ''}`; line.setAttribute('data-ase-ui', ''); d.body.append(line);
|
|
152
276
|
el.classList.add('ase-dragging');
|
|
153
277
|
let to = from;
|
|
154
278
|
const move = (ev: PointerEvent) => {
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
}
|
|
162
|
-
const
|
|
163
|
-
|
|
164
|
-
line.style.top = `${(to >= sections.length ? rr.bottom : rr.top) + d.defaultView!.scrollY}px`;
|
|
165
|
-
// auto-scroll near the edges
|
|
166
|
-
const vh = d.defaultView!.innerHeight;
|
|
167
|
-
if (ev.clientY < 60) d.defaultView!.scrollBy(0, -12); else if (ev.clientY > vh - 60) d.defaultView!.scrollBy(0, 12);
|
|
279
|
+
let best = 0, dist = Infinity;
|
|
280
|
+
kids.forEach((k, i) => { const r = k.getBoundingClientRect(); const dd = Math.hypot(ev.clientX - (r.left + r.width / 2), ev.clientY - (r.top + r.height / 2)); if (dd < dist) { dist = dd; best = i; } });
|
|
281
|
+
const r = kids[best].getBoundingClientRect();
|
|
282
|
+
const after = horizontal ? ev.clientX > r.left + r.width / 2 : ev.clientY > r.top + r.height / 2;
|
|
283
|
+
to = best + (after ? 1 : 0);
|
|
284
|
+
if (horizontal) { line.style.left = `${after ? r.right : r.left}px`; line.style.top = `${r.top}px`; line.style.height = `${r.height}px`; }
|
|
285
|
+
else { line.style.top = `${after ? r.bottom : r.top}px`; line.style.left = `${r.left}px`; line.style.width = `${r.width}px`; }
|
|
286
|
+
const vh = iwin().innerHeight; // auto-scroll near the edges
|
|
287
|
+
if (ev.clientY < 60) iwin().scrollBy(0, -12); else if (ev.clientY > vh - 60) iwin().scrollBy(0, 12);
|
|
168
288
|
};
|
|
169
289
|
const up = () => {
|
|
170
290
|
d.removeEventListener('pointermove', move); d.removeEventListener('pointerup', up);
|
|
171
291
|
line.remove(); el.classList.remove('ase-dragging');
|
|
172
292
|
const dest = to > from ? to - 1 : to;
|
|
173
|
-
if (dest !== from) { state.apply(moveNode(state.doc,
|
|
174
|
-
else refreshChrome();
|
|
293
|
+
if (dest !== from) { selected = `${listPath}.${dest}`; state.apply(moveNode(state.doc, path, listPath, dest)); scheduleRender(0); } else refreshChrome();
|
|
175
294
|
};
|
|
176
295
|
d.addEventListener('pointermove', move); d.addEventListener('pointerup', up);
|
|
177
296
|
}
|
|
178
297
|
|
|
298
|
+
// ---------- the + between sections ----------
|
|
299
|
+
let plusRaf = 0;
|
|
300
|
+
function onPreviewMove(e: MouseEvent) {
|
|
301
|
+
if (plusRaf) return;
|
|
302
|
+
const { clientY, target: t } = e;
|
|
303
|
+
plusRaf = requestAnimationFrame(() => {
|
|
304
|
+
plusRaf = 0;
|
|
305
|
+
if (inline.isActive || (t as HTMLElement).closest?.('.ase-toolbar, [data-ase-toolbar]')) { showPlus(null); return; }
|
|
306
|
+
const secs = topSections(idoc());
|
|
307
|
+
let index: number | null = null, y = 0;
|
|
308
|
+
secs.forEach((s, i) => {
|
|
309
|
+
const r = s.getBoundingClientRect();
|
|
310
|
+
if (Math.abs(clientY - r.top) < 18) { index = i; y = r.top; }
|
|
311
|
+
else if (i === secs.length - 1 && Math.abs(clientY - r.bottom) < 18) { index = i + 1; y = r.bottom; }
|
|
312
|
+
});
|
|
313
|
+
showPlus(index === null ? null : { index, y });
|
|
314
|
+
});
|
|
315
|
+
}
|
|
316
|
+
function showPlus(at: { index: number; y: number } | null) {
|
|
317
|
+
if (!previewReady) return;
|
|
318
|
+
const d = idoc();
|
|
319
|
+
let plus = d.querySelector<HTMLElement>('.ase-plus');
|
|
320
|
+
if (!at) { if (plus) plus.hidden = true; return; }
|
|
321
|
+
if (!plus) {
|
|
322
|
+
plus = d.createElement('button');
|
|
323
|
+
plus.type = 'button'; plus.className = 'ase-plus'; plus.setAttribute('data-ase-ui', ''); plus.title = 'Add block'; plus.setAttribute('aria-label', 'Add block'); plus.innerHTML = icons.plus;
|
|
324
|
+
plus.addEventListener('click', (e) => { e.preventDefault(); e.stopPropagation(); openInserter({ listPath: 'sections', index: Number(plus!.dataset.index) }); plus!.hidden = true; });
|
|
325
|
+
d.body.append(plus);
|
|
326
|
+
}
|
|
327
|
+
plus.hidden = false; plus.dataset.index = String(at.index); plus.style.top = `${at.y}px`;
|
|
328
|
+
}
|
|
329
|
+
|
|
179
330
|
// ---------- selection ----------
|
|
180
331
|
function select(path: string | null, opts: { fromPreview?: boolean; scroll?: boolean } = {}) {
|
|
181
332
|
if (path && !isNodePath(path)) path = nodePathOf(path);
|
|
182
333
|
selected = path;
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
if (el && opts.scroll !== false) el.scrollIntoView({ block: 'center', behavior: 'smooth' });
|
|
186
|
-
}
|
|
334
|
+
tab = path ? 'block' : 'page';
|
|
335
|
+
if (path && !opts.fromPreview && previewReady && opts.scroll !== false) nodeEl(path)?.scrollIntoView({ block: 'center', behavior: 'smooth' });
|
|
187
336
|
refreshChrome();
|
|
188
337
|
}
|
|
189
|
-
|
|
338
|
+
|
|
339
|
+
function refreshButtons() {
|
|
340
|
+
const dirty = state.dirty;
|
|
341
|
+
const draft = state.doc.status === 'draft';
|
|
342
|
+
$<HTMLButtonElement>('#ase-undo').disabled = !state.canUndo;
|
|
343
|
+
$<HTMLButtonElement>('#ase-redo').disabled = !state.canRedo;
|
|
344
|
+
const save = $<HTMLButtonElement>('#ase-save');
|
|
345
|
+
save.disabled = !dirty || saving;
|
|
346
|
+
save.textContent = draft ? 'Save draft' : 'Save';
|
|
347
|
+
save.classList.toggle('ase-btn--primary', !draft);
|
|
348
|
+
save.classList.toggle('ase-btn--ghost', draft);
|
|
349
|
+
const publish = $<HTMLButtonElement>('#ase-publish');
|
|
350
|
+
publish.hidden = !draft;
|
|
351
|
+
publish.disabled = saving;
|
|
352
|
+
$('#ase-discard').hidden = !dirty;
|
|
353
|
+
$('#ase-view').hidden = draft || boot.page.status === 'draft';
|
|
354
|
+
$('#ase-draft-pill').hidden = !draft;
|
|
355
|
+
$('#ase-title').textContent = state.doc.title;
|
|
356
|
+
document.title = `${dirty ? '• ' : ''}Edit: ${state.doc.title}`;
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
function refreshChrome(opts: { inspector?: boolean } = {}) {
|
|
190
360
|
if (previewReady) decorate();
|
|
191
361
|
renderTree($('#ase-tree'), state.doc, registry, selected, {
|
|
192
362
|
onSelect: (p) => select(p),
|
|
193
|
-
onMove: (fromPath, toList, toIndex) => {
|
|
363
|
+
onMove: (fromPath, toList, toIndex) => {
|
|
364
|
+
const id = nodeAt(state.doc, fromPath)!.id;
|
|
365
|
+
const next = moveNode(state.doc, fromPath, toList, toIndex);
|
|
366
|
+
selected = pathOfId(next, id) ?? null;
|
|
367
|
+
state.apply(next);
|
|
368
|
+
scheduleRender(0);
|
|
369
|
+
},
|
|
370
|
+
canDrop: (fromPath, toList) => {
|
|
371
|
+
if (toList === fromPath || toList.startsWith(`${fromPath}.`)) return false;
|
|
372
|
+
const type = nodeAt(state.doc, fromPath)!.type;
|
|
373
|
+
return accepts(parentTypeOf(toList), type, registry);
|
|
374
|
+
},
|
|
375
|
+
onMenu: (path, anchor) => { select(path, { scroll: false }); openMenu(anchor, blockMenu(path)); },
|
|
194
376
|
});
|
|
195
|
-
renderInspector();
|
|
196
|
-
|
|
197
|
-
$<HTMLButtonElement>('#ase-redo').disabled = !state.canRedo;
|
|
198
|
-
$<HTMLButtonElement>('#ase-save').disabled = !state.dirty;
|
|
199
|
-
$('#ase-discard').hidden = !state.dirty;
|
|
200
|
-
document.title = `${state.dirty ? '• ' : ''}Edit: ${state.doc.title}`;
|
|
377
|
+
if (opts.inspector !== false) renderInspector();
|
|
378
|
+
refreshButtons();
|
|
201
379
|
}
|
|
202
380
|
|
|
203
|
-
|
|
381
|
+
const parentTypeOf = (listPath: string): string | null => (listPath === 'sections' ? null : nodeAt(state.doc, listPath.replace(/\.blocks$/, ''))?.type ?? null);
|
|
382
|
+
|
|
383
|
+
// ---------- sidebar ----------
|
|
204
384
|
function renderInspector() {
|
|
205
385
|
const root = $('#ase-inspector');
|
|
206
386
|
root.innerHTML = '';
|
|
387
|
+
const tabs = document.createElement('div');
|
|
388
|
+
tabs.className = 'ase-tabs'; tabs.setAttribute('role', 'tablist');
|
|
389
|
+
tabs.innerHTML = `<button type="button" role="tab" data-tab="page" aria-selected="${tab === 'page'}">Page</button><button type="button" role="tab" data-tab="block" aria-selected="${tab === 'block'}">Block</button>`;
|
|
390
|
+
tabs.addEventListener('click', (e) => { const b = (e.target as HTMLElement).closest<HTMLElement>('[data-tab]'); if (b) { tab = b.dataset.tab as typeof tab; renderInspector(); } });
|
|
391
|
+
root.append(tabs);
|
|
207
392
|
const node = selected ? nodeAt(state.doc, selected) : null;
|
|
208
|
-
if (
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
393
|
+
if (tab === 'page') renderPageTab(root);
|
|
394
|
+
else if (node) renderBlockTab(root, node, selected!);
|
|
395
|
+
else root.append(hint('Select a block in the page to see its settings.'));
|
|
396
|
+
const syncedNode = selected ? nodeAt(state.doc, selected) : null;
|
|
397
|
+
if (tab === 'block' && syncedNode?.synced) root.append(hint('This block is a copy of a synced pattern. Edits stay on this page until you choose Update all copies in its ⋮ menu.'));
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
const formCallbacks = {
|
|
401
|
+
pickImage,
|
|
402
|
+
pageUrls: pageLinks,
|
|
403
|
+
icons: Object.fromEntries(iconsField.map((i) => [i, i])),
|
|
404
|
+
};
|
|
405
|
+
|
|
406
|
+
/** One field change: a live change streams, and undo sees the whole edit as one step. */
|
|
407
|
+
function applyField(path: string, value: unknown, live: boolean | undefined, field?: Field) {
|
|
408
|
+
state.apply(setAt(state.doc, path, value), 'field', livePath !== path);
|
|
409
|
+
livePath = live ? path : null;
|
|
410
|
+
scheduleRender(live ? 200 : 0);
|
|
411
|
+
if (field?.type === 'image' && !live) renderInspector();
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
function renderBlockTab(root: HTMLElement, node: Node, path: string) {
|
|
218
415
|
const schema = registry[node.type];
|
|
219
|
-
const top = /^sections\.\d+$/.test(selected);
|
|
220
416
|
const head = document.createElement('div');
|
|
221
|
-
head.className = 'ase-
|
|
222
|
-
|
|
223
|
-
head.
|
|
224
|
-
|
|
417
|
+
head.className = 'ase-blockhead';
|
|
418
|
+
const name = document.createElement('strong'); name.textContent = schema?.label ?? node.type;
|
|
419
|
+
head.append(name);
|
|
420
|
+
if (schema?.description) { const d = document.createElement('p'); d.className = 'ase-muted'; d.textContent = schema.description; head.append(d); }
|
|
421
|
+
root.append(breadcrumbs(path), head);
|
|
225
422
|
const actions = document.createElement('div');
|
|
226
423
|
actions.className = 'ase-actions';
|
|
227
|
-
actions.innerHTML = `${top ? '' : '<button type="button" data-act="parent" class="ase-btn ase-btn--small ase-btn--ghost">↖ Parent</button>'}<button type="button" data-act="up" class="ase-btn ase-btn--small">↑</button><button type="button" data-act="down" class="ase-btn ase-btn--small">↓</button><button type="button" data-act="dup" class="ase-btn ase-btn--small">Duplicate</button><button type="button" data-act="del" class="ase-btn ase-btn--small ase-btn--danger">Delete</button>`;
|
|
228
|
-
actions.addEventListener('click', (e) => { const b = (e.target as HTMLElement).closest('button'); if (b) act(b.dataset.act!); });
|
|
229
|
-
root.append(head, actions);
|
|
230
424
|
const allowed = allowedChildTypes(node.type, registry);
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
const sel = document.createElement('select');
|
|
235
|
-
sel.innerHTML = `<option value="">+ Add block…</option>${allowed.map((t) => `<option value="${t}">${registry[t].label}</option>`).join('')}`;
|
|
236
|
-
sel.addEventListener('change', () => { if (sel.value) { addBlock(selected!, sel.value); sel.value = ''; } });
|
|
237
|
-
add.append(sel);
|
|
238
|
-
root.append(add);
|
|
239
|
-
}
|
|
425
|
+
actions.innerHTML = `${allowed?.length ? `<button type="button" data-act="add" class="ase-btn ase-btn--small">${icons.plus} Add block</button>` : ''}<button type="button" data-act="dup" class="ase-btn ase-btn--small">Duplicate</button><button type="button" data-act="del" class="ase-btn ase-btn--small ase-btn--danger">Delete</button>`;
|
|
426
|
+
actions.addEventListener('click', (e) => { const b = (e.target as HTMLElement).closest('button'); if (b) act(b.dataset.act!); });
|
|
427
|
+
root.append(actions);
|
|
240
428
|
const form = document.createElement('div');
|
|
241
429
|
renderForm(form, schema ?? { label: node.type, fields: {} }, node.settings, {
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
state.apply(setAt(state.doc, path, value), 'edit', !o?.live || !liveStarted);
|
|
245
|
-
liveStarted = !!o?.live;
|
|
246
|
-
scheduleRender(o?.live ? 200 : 0);
|
|
247
|
-
if (!o?.live) { liveStarted = false; }
|
|
248
|
-
},
|
|
249
|
-
pickImage,
|
|
250
|
-
pageUrls: boot.pages,
|
|
251
|
-
icons: Object.fromEntries(iconsField.map((i) => [i, i])),
|
|
430
|
+
...formCallbacks,
|
|
431
|
+
onChange: (name, value, o) => applyField(`${path}.settings.${name}`, value, o?.live, schema?.fields[name]),
|
|
252
432
|
});
|
|
253
433
|
root.append(form);
|
|
254
434
|
}
|
|
255
|
-
|
|
435
|
+
|
|
436
|
+
/** Page › Hero › Button; each step selects that block. */
|
|
437
|
+
function breadcrumbs(path: string): HTMLElement {
|
|
438
|
+
const nav = document.createElement('nav');
|
|
439
|
+
nav.className = 'ase-crumbs'; nav.setAttribute('aria-label', 'Block position');
|
|
440
|
+
const add = (label: string, to: string | null, current = false) => {
|
|
441
|
+
if (nav.childElementCount) nav.append(' › ');
|
|
442
|
+
const b = document.createElement('button');
|
|
443
|
+
b.type = 'button'; b.textContent = label; if (current) b.setAttribute('aria-current', 'true');
|
|
444
|
+
b.addEventListener('click', () => select(to));
|
|
445
|
+
nav.append(b);
|
|
446
|
+
};
|
|
447
|
+
add('Page', null);
|
|
448
|
+
const parts = path.split('.');
|
|
449
|
+
for (let i = 2; i <= parts.length; i += 2) {
|
|
450
|
+
const p = parts.slice(0, i).join('.');
|
|
451
|
+
const n = nodeAt(state.doc, p);
|
|
452
|
+
if (n) add(registry[n.type]?.label ?? n.type, p, p === path);
|
|
453
|
+
}
|
|
454
|
+
return nav;
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
function renderPageTab(root: HTMLElement) {
|
|
458
|
+
const doc = state.doc;
|
|
459
|
+
const draft = doc.status === 'draft';
|
|
460
|
+
const summary = document.createElement('div');
|
|
461
|
+
summary.className = 'ase-summary';
|
|
462
|
+
const row = (label: string, value: string, button?: { text: string; id: string; run: () => void; disabled?: boolean }) => {
|
|
463
|
+
const r = document.createElement('div'); r.className = 'ase-summary__row';
|
|
464
|
+
const l = document.createElement('span'); l.className = 'ase-muted'; l.textContent = label;
|
|
465
|
+
const v = document.createElement('span'); v.textContent = value; v.className = 'ase-ellipsis';
|
|
466
|
+
r.append(l, v);
|
|
467
|
+
if (button) { const b = document.createElement('button'); b.type = 'button'; b.id = button.id; b.className = 'ase-linkbtn'; b.textContent = button.text; b.disabled = !!button.disabled; b.addEventListener('click', button.run); r.append(b); }
|
|
468
|
+
summary.append(r);
|
|
469
|
+
};
|
|
470
|
+
row('Status', draft ? 'Draft' : 'Published', draft ? undefined : { text: 'Switch to draft', id: 'ase-unpublish', run: () => publish(false), disabled: isHome });
|
|
471
|
+
row('URL', boot.options.viewUrl, isHome ? undefined : { text: 'Change', id: 'ase-change-url', run: changeUrl });
|
|
472
|
+
root.append(summary);
|
|
473
|
+
|
|
474
|
+
const form = document.createElement('div');
|
|
475
|
+
const fields: Record<string, Field> = {
|
|
476
|
+
title: { type: 'text', label: 'Title', default: '' },
|
|
477
|
+
description: { type: 'textarea', label: 'Description', default: '', help: 'Shown in search results and link previews.' },
|
|
478
|
+
ogImage: { type: 'image', label: 'Social image', asUrl: true, default: '' },
|
|
479
|
+
};
|
|
480
|
+
renderForm(form, { label: 'Page', fields }, { title: doc.title, description: doc.description ?? '', ogImage: doc.ogImage ?? '' }, {
|
|
481
|
+
...formCallbacks,
|
|
482
|
+
onChange: (name, value, o) => applyField(name, value, o?.live, fields[name]),
|
|
483
|
+
});
|
|
484
|
+
root.append(form);
|
|
485
|
+
|
|
486
|
+
if (Object.keys(boot.pageFields).length) {
|
|
487
|
+
const layout = document.createElement('div');
|
|
488
|
+
renderForm(layout, { label: 'Layout', fields: boot.pageFields }, state.doc.layout ?? {}, {
|
|
489
|
+
...formCallbacks,
|
|
490
|
+
onChange: (name, value, o) => { renderFull = !o?.live; applyField(`layout.${name}`, value, o?.live, boot.pageFields[name]); },
|
|
491
|
+
});
|
|
492
|
+
root.append(layout);
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
const tools = document.createElement('div');
|
|
496
|
+
tools.className = 'ase-actions';
|
|
497
|
+
tools.innerHTML = `<button type="button" id="ase-revisions" class="ase-btn ase-btn--small">Revisions</button>${isHome ? '' : '<button type="button" id="ase-delete-page" class="ase-btn ase-btn--small ase-btn--danger">Delete page</button>'}`;
|
|
498
|
+
tools.querySelector('#ase-revisions')!.addEventListener('click', showRevisions);
|
|
499
|
+
tools.querySelector('#ase-delete-page')?.addEventListener('click', deletePage);
|
|
500
|
+
root.append(tools, hint('Click anything in the page to edit it. Press ? for keyboard shortcuts.'));
|
|
501
|
+
}
|
|
256
502
|
const hint = (text: string) => { const p = document.createElement('p'); p.className = 'ase-muted ase-hint'; p.textContent = text; return p; };
|
|
257
503
|
|
|
258
|
-
// ---------- actions ----------
|
|
504
|
+
// ---------- block actions ----------
|
|
505
|
+
function blockMenu(path: string): MenuItem[] {
|
|
506
|
+
const run = (what: string) => () => { selected = path; act(what); };
|
|
507
|
+
return [
|
|
508
|
+
{ label: 'Duplicate', hint: '⇧⌘D', run: run('dup') },
|
|
509
|
+
{ label: 'Copy', hint: '⌘C', run: run('copy') },
|
|
510
|
+
{ label: 'Cut', hint: '⌘X', run: run('cut') },
|
|
511
|
+
{ label: 'Paste after', hint: '⌘V', run: run('paste'), disabled: !readClipboard() },
|
|
512
|
+
{ label: 'Add before', hint: '⌥⌘T', run: run('before'), separator: true },
|
|
513
|
+
{ label: 'Add after', hint: '⌥⌘Y', run: run('after') },
|
|
514
|
+
...transformItems(path),
|
|
515
|
+
...syncedItems(path),
|
|
516
|
+
{ label: 'Save as pattern…', run: run('pattern'), separator: true },
|
|
517
|
+
{ label: 'Delete', hint: 'Del', run: run('del'), danger: true, separator: true },
|
|
518
|
+
];
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
function transformItems(path: string): MenuItem[] {
|
|
522
|
+
const node = nodeAt(state.doc, path);
|
|
523
|
+
if (!node) return [];
|
|
524
|
+
const parent = parentTypeOf(splitNodePath(path).listPath);
|
|
525
|
+
return transformTargets(node, parent, registry).slice(0, 8).map((t, i) => ({
|
|
526
|
+
label: `Turn into ${t.label}`, separator: i === 0,
|
|
527
|
+
run: () => { selected = path; tab = 'block'; state.apply(replaceNode(state.doc, path, transformNode(nodeAt(state.doc, path)!, t.type, registry))); scheduleRender(0); },
|
|
528
|
+
}));
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
function syncedItems(path: string): MenuItem[] {
|
|
532
|
+
const node = nodeAt(state.doc, path);
|
|
533
|
+
if (!node?.synced || !patterns.some((p) => p.id === node.synced)) return [];
|
|
534
|
+
return [
|
|
535
|
+
{ label: 'Update all copies', separator: true, run: () => updateCopies(path) },
|
|
536
|
+
{ label: 'Detach from pattern', run: () => { const { synced: _, ...plain } = nodeAt(state.doc, path)!; state.apply(replaceNode(state.doc, path, plain)); renderInspector(); } },
|
|
537
|
+
];
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
/** This block becomes the pattern, on every page. The page is saved first, so nothing here is lost. */
|
|
541
|
+
async function updateCopies(path: string) {
|
|
542
|
+
const node = nodeAt(state.doc, path)!;
|
|
543
|
+
const name = patterns.find((p) => p.id === node.synced)?.label ?? 'this pattern';
|
|
544
|
+
if (!await confirmDialog('Update all copies', `Every page using "${name}" gets this version, in one commit. This page is saved first.`, 'Update all copies')) return;
|
|
545
|
+
await save();
|
|
546
|
+
if (state.dirty) return; // the save failed and has said so
|
|
547
|
+
const res = await fetch('/api/editor/patterns', { method: 'PUT', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ id: node.synced, node }) });
|
|
548
|
+
const data = await res.json();
|
|
549
|
+
if (!res.ok) { toast(data.error || 'Could not update the copies.', 'error'); return; }
|
|
550
|
+
location.reload();
|
|
551
|
+
}
|
|
552
|
+
|
|
259
553
|
function act(what: string) {
|
|
260
554
|
if (!selected) return;
|
|
555
|
+
const node = nodeAt(state.doc, selected);
|
|
556
|
+
if (!node) return;
|
|
261
557
|
const { listPath, index } = splitNodePath(selected);
|
|
262
558
|
const list: Node[] = getAt(state.doc, listPath) ?? [];
|
|
263
559
|
switch (what) {
|
|
264
560
|
case 'parent': { const p = listPath.replace(/\.blocks$/, ''); select(isNodePath(p) ? p : null); return; }
|
|
265
|
-
case '
|
|
266
|
-
case '
|
|
267
|
-
case '
|
|
561
|
+
case 'add': openInserter({ listPath: `${selected}.blocks`, index: node.blocks?.length ?? 0 }); return;
|
|
562
|
+
case 'before': openInserter({ listPath, index }); return;
|
|
563
|
+
case 'after': openInserter({ listPath, index: index + 1 }); return;
|
|
564
|
+
case 'copy': writeClipboard(node); toast(`Copied ${labelOf(node)}.`, 'info'); return;
|
|
565
|
+
case 'paste': paste(); return;
|
|
566
|
+
case 'pattern': savePattern(node); return;
|
|
567
|
+
case 'cut': writeClipboard(node); act('del'); return;
|
|
568
|
+
case 'up': case 'down': {
|
|
569
|
+
const to = index + (what === 'up' ? -1 : 1);
|
|
570
|
+
if (to < 0 || to >= list.length) return;
|
|
571
|
+
const next = moveNode(state.doc, selected, listPath, to);
|
|
572
|
+
selected = `${listPath}.${to}`;
|
|
573
|
+
state.apply(next);
|
|
574
|
+
break;
|
|
575
|
+
}
|
|
576
|
+
case 'dup': {
|
|
577
|
+
const next = insertNode(state.doc, listPath, index + 1, cloneWithNewIds(node));
|
|
578
|
+
selected = `${listPath}.${index + 1}`;
|
|
579
|
+
state.apply(next);
|
|
580
|
+
break;
|
|
581
|
+
}
|
|
268
582
|
case 'del': {
|
|
269
|
-
const
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
583
|
+
const next = removeNode(state.doc, selected);
|
|
584
|
+
const parent = listPath.replace(/\.blocks$/, '');
|
|
585
|
+
const remaining: Node[] = getAt(next, listPath) ?? [];
|
|
586
|
+
selected = remaining.length ? `${listPath}.${Math.min(index, remaining.length - 1)}` : (isNodePath(parent) ? parent : null);
|
|
587
|
+
if (!selected) tab = 'page';
|
|
588
|
+
state.apply(next);
|
|
589
|
+
toast(`Deleted ${labelOf(node)}.`, 'info', { action: { label: 'Undo', run: () => state.undo() } });
|
|
274
590
|
break;
|
|
275
591
|
}
|
|
276
592
|
}
|
|
277
|
-
refreshChrome();
|
|
278
593
|
scheduleRender(0);
|
|
279
594
|
}
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
if (type === 'container') node.settings = { ...node.settings, boxed: false };
|
|
283
|
-
const listPath = `${parentPath}.blocks`;
|
|
284
|
-
const len = (getAt(state.doc, listPath) ?? []).length;
|
|
285
|
-
state.apply(insertNode(state.doc, listPath, len, node));
|
|
286
|
-
selected = `${listPath}.${len}`;
|
|
287
|
-
refreshChrome(); scheduleRender(0);
|
|
288
|
-
}
|
|
595
|
+
const labelOf = (n: Node) => registry[n.type]?.label ?? n.type;
|
|
596
|
+
|
|
289
597
|
function setField(fieldPath: string, value: unknown) {
|
|
290
598
|
state.apply(setAt(state.doc, fieldPath, value));
|
|
291
|
-
|
|
292
|
-
}
|
|
293
|
-
|
|
294
|
-
// ----------
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
599
|
+
scheduleRender(0);
|
|
600
|
+
}
|
|
601
|
+
|
|
602
|
+
// ---------- clipboard: works across pages of the site ----------
|
|
603
|
+
const CLIP = 'ase:clipboard';
|
|
604
|
+
function writeClipboard(n: Node) { try { localStorage.setItem(CLIP, JSON.stringify(n)); } catch { /* private mode */ } }
|
|
605
|
+
function readClipboard(): Node | null { try { return JSON.parse(localStorage.getItem(CLIP) ?? 'null'); } catch { return null; } }
|
|
606
|
+
|
|
607
|
+
/** The nearest place a block of `type` can go: inside the selection, after it, or further out. */
|
|
608
|
+
function placeFor(type: string): Target | null {
|
|
609
|
+
if (!selected) return accepts(null, type, registry) ? { listPath: 'sections', index: state.doc.sections.length } : null;
|
|
610
|
+
const node = nodeAt(state.doc, selected)!;
|
|
611
|
+
// A copy of the selected kind of block goes beside it, not inside it.
|
|
612
|
+
if (node.type !== type && accepts(node.type, type, registry)) return { listPath: `${selected}.blocks`, index: node.blocks?.length ?? 0 };
|
|
613
|
+
let path = selected;
|
|
614
|
+
for (;;) {
|
|
615
|
+
const { listPath, index } = splitNodePath(path);
|
|
616
|
+
if (accepts(parentTypeOf(listPath), type, registry)) return { listPath, index: index + 1 };
|
|
617
|
+
if (listPath === 'sections') return null;
|
|
618
|
+
path = listPath.replace(/\.blocks$/, '');
|
|
619
|
+
}
|
|
620
|
+
}
|
|
621
|
+
|
|
622
|
+
function paste() {
|
|
623
|
+
const clip = readClipboard();
|
|
624
|
+
if (!clip) { toast('Nothing copied yet.', 'info'); return; }
|
|
625
|
+
const at = placeFor(clip.type);
|
|
626
|
+
if (!at) { toast(`A ${labelOf(clip)} can't go here.`, 'warn'); return; }
|
|
627
|
+
insertAt(at, cloneWithNewIds(clip));
|
|
628
|
+
}
|
|
629
|
+
|
|
630
|
+
function insertAt(at: Target, node: Node) {
|
|
631
|
+
const next = insertNode(state.doc, at.listPath, at.index, node);
|
|
632
|
+
selected = `${at.listPath}.${at.index}`;
|
|
633
|
+
tab = 'block';
|
|
634
|
+
reveal = selected;
|
|
635
|
+
state.apply(next);
|
|
636
|
+
scheduleRender(0);
|
|
637
|
+
}
|
|
638
|
+
|
|
639
|
+
async function savePattern(node: Node) {
|
|
640
|
+
const toggle = { label: 'Synced: keep every copy linked, so one edit can update them all', on: false };
|
|
641
|
+
const label = await promptDialog({ toggle, title: 'Save as pattern', label: 'Name', value: labelOf(node), submit: 'Save pattern', help: 'Patterns appear in the block inserter on every page. Inserting one makes an independent copy.' });
|
|
642
|
+
if (!label) return;
|
|
643
|
+
const res = await fetch('/api/editor/patterns', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ label, node, synced: toggle.on }) });
|
|
644
|
+
const data = await res.json();
|
|
645
|
+
if (!res.ok) { toast(data.error || 'Could not save the pattern.', 'error'); return; }
|
|
646
|
+
patterns = data.patterns;
|
|
647
|
+
if (toggle.on) { // the block it came from is the first copy
|
|
648
|
+
const path = pathOfId(state.doc, node.id);
|
|
649
|
+
if (path) { state.apply(replaceNode(state.doc, path, { ...nodeAt(state.doc, path)!, synced: patterns[patterns.length - 1].id })); renderInspector(); }
|
|
650
|
+
}
|
|
651
|
+
toast(`Saved pattern "${label}".`, 'ok');
|
|
652
|
+
}
|
|
653
|
+
|
|
654
|
+
// ---------- inserter ----------
|
|
655
|
+
interface Target { listPath: string; index: number }
|
|
656
|
+
let target: Target | null = null;
|
|
657
|
+
let leftView: 'list' | 'add' | 'off' = 'list';
|
|
658
|
+
|
|
659
|
+
function setLeft(view: typeof leftView) {
|
|
660
|
+
leftView = view;
|
|
661
|
+
document.body.dataset.left = view;
|
|
662
|
+
$('#ase-toggle-add').classList.toggle('is-active', view === 'add');
|
|
663
|
+
$('#ase-toggle-list').classList.toggle('is-active', view === 'list');
|
|
664
|
+
if (view !== 'add') { target = null; slashBlock = null; placeOverlays(); idoc()?.querySelector('.ase-insertline')?.remove(); }
|
|
665
|
+
fitPreview();
|
|
666
|
+
}
|
|
667
|
+
|
|
668
|
+
function defaultTarget(): Target {
|
|
669
|
+
if (!selected) return { listPath: 'sections', index: state.doc.sections.length };
|
|
670
|
+
const node = nodeAt(state.doc, selected)!;
|
|
671
|
+
if (allowedChildTypes(node.type, registry)?.length) return { listPath: `${selected}.blocks`, index: node.blocks?.length ?? 0 };
|
|
672
|
+
const { listPath, index } = splitNodePath(selected);
|
|
673
|
+
return { listPath, index: index + 1 };
|
|
674
|
+
}
|
|
675
|
+
|
|
676
|
+
function openInserter(at: Target = defaultTarget()) {
|
|
677
|
+
inline.stop(true);
|
|
678
|
+
target = at;
|
|
679
|
+
setLeft('add');
|
|
680
|
+
renderInserterPanel();
|
|
681
|
+
const d = idoc();
|
|
682
|
+
if (!d.querySelector('.ase-insertline')) { const line = d.createElement('div'); line.className = 'ase-insertline'; line.setAttribute('data-ase-ui', ''); d.body.append(line); }
|
|
683
|
+
placeOverlays();
|
|
684
|
+
}
|
|
685
|
+
|
|
686
|
+
function renderInserterPanel() {
|
|
687
|
+
if (!target) return;
|
|
688
|
+
const parent = parentTypeOf(target.listPath);
|
|
689
|
+
renderInserter($('#ase-inserter'), {
|
|
690
|
+
items: () => insertItems(parent, registry, boot.presets, patterns),
|
|
691
|
+
where: () => (parent ? `Adding to ${registry[parent]?.label ?? parent}` : 'Adding to the page'),
|
|
692
|
+
onPick: (item) => pick(item),
|
|
693
|
+
onDeleteSaved: deleteSaved,
|
|
694
|
+
onClose: () => setLeft('list'),
|
|
310
695
|
});
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
696
|
+
}
|
|
697
|
+
|
|
698
|
+
function pick(item: InsertItem) {
|
|
699
|
+
if (!target) return;
|
|
700
|
+
const node = item.node ? cloneWithNewIds(item.node) : createNode(item.type!, registry);
|
|
701
|
+
if (item.syncedId) node.synced = item.syncedId;
|
|
702
|
+
const at = target;
|
|
703
|
+
const gone = slashBlock;
|
|
704
|
+
setLeft('list');
|
|
705
|
+
insertAt(at, node);
|
|
706
|
+
if (gone) { // the empty block `/` was typed in gives way to what was picked
|
|
707
|
+
const path = pathOfId(state.doc, gone);
|
|
708
|
+
if (path) { state.apply(removeNode(state.doc, path)); selected = at.listPath + '.' + (at.index - 1); reveal = selected; scheduleRender(0); }
|
|
709
|
+
}
|
|
710
|
+
}
|
|
711
|
+
|
|
712
|
+
/** A block `/` was typed in, if it held nothing: the block picked next replaces it. */
|
|
713
|
+
let slashBlock: string | null = null;
|
|
714
|
+
function slash(fieldPath: string) {
|
|
715
|
+
const path = nodePathOf(fieldPath);
|
|
716
|
+
const node = nodeAt(state.doc, path);
|
|
717
|
+
if (!node) return;
|
|
718
|
+
const { listPath, index } = splitNodePath(path);
|
|
719
|
+
const blank = !node.blocks?.length && Object.entries(registry[node.type]?.fields ?? {}).every(([k, f]) => !['text', 'textarea', 'richtext'].includes(f.type) || !String(k === nodeField(fieldPath) ? '' : node.settings[k] ?? '').replace(/<[^>]*>/g, '').trim());
|
|
720
|
+
openInserter({ listPath, index: index + 1 });
|
|
721
|
+
slashBlock = blank ? node.id : null;
|
|
722
|
+
}
|
|
723
|
+
const nodeField = (fieldPath: string) => fieldPath.split('.').pop();
|
|
724
|
+
|
|
725
|
+
async function deleteSaved(item: InsertItem) {
|
|
726
|
+
if (!await confirmDialog('Delete pattern', `Delete "${item.label}"? Pages already using it keep their copy.`, 'Delete', 'danger')) return;
|
|
727
|
+
const res = await fetch(`/api/editor/patterns?id=${encodeURIComponent(item.savedId!)}`, { method: 'DELETE' });
|
|
728
|
+
const data = await res.json();
|
|
729
|
+
if (!res.ok) { toast(data.error || 'Could not delete the pattern.', 'error'); return; }
|
|
730
|
+
patterns = data.patterns;
|
|
731
|
+
renderInserterPanel();
|
|
732
|
+
}
|
|
733
|
+
|
|
734
|
+
// ---------- preview size ----------
|
|
735
|
+
const WIDTHS: Record<string, number> = { desktop: 1280, tablet: 1024, mobile: 390 };
|
|
736
|
+
let uiScale = 1;
|
|
737
|
+
|
|
738
|
+
/** Tools drawn inside the preview scale up by the inverse, so they stay a usable size. */
|
|
739
|
+
function applyUiScale(scale: number) {
|
|
740
|
+
uiScale = 1 / scale;
|
|
741
|
+
idoc()?.documentElement?.style.setProperty('--ase-ui', String(uiScale));
|
|
742
|
+
placeOverlays();
|
|
743
|
+
}
|
|
744
|
+
|
|
745
|
+
/** The site should show its real layout at every width, so a device wider than the stage scales down. */
|
|
746
|
+
function fitPreview() {
|
|
747
|
+
const stage = $('.ase-stage');
|
|
748
|
+
const width = WIDTHS[stage.dataset.device!];
|
|
749
|
+
const room = stage.clientWidth;
|
|
750
|
+
const big = stage.dataset.device === 'desktop' && room >= width;
|
|
751
|
+
const scale = big ? 1 : Math.min(1, room / width);
|
|
752
|
+
iframe.style.width = big ? '100%' : `${width}px`;
|
|
753
|
+
iframe.style.height = scale < 1 ? `${stage.clientHeight / scale}px` : '100%';
|
|
754
|
+
iframe.style.transform = scale < 1 ? `scale(${scale})` : '';
|
|
755
|
+
stage.classList.toggle('is-scaled', scale < 1);
|
|
756
|
+
applyUiScale(scale);
|
|
757
|
+
$('#ase-zoom').textContent = scale < 1 ? `${Math.round(scale * 100)}%` : '';
|
|
758
|
+
}
|
|
759
|
+
new ResizeObserver(fitPreview).observe($('.ase-stage'));
|
|
315
760
|
|
|
316
761
|
// ---------- top bar ----------
|
|
317
762
|
$('#ase-undo').addEventListener('click', () => { inline.stop(true); state.undo(); });
|
|
318
763
|
$('#ase-redo').addEventListener('click', () => { inline.stop(true); state.redo(); });
|
|
764
|
+
$('#ase-toggle-add').addEventListener('click', () => { if (leftView === 'add') setLeft('list'); else openInserter(); });
|
|
765
|
+
$('#ase-toggle-list').addEventListener('click', () => setLeft(leftView === 'list' ? 'off' : 'list'));
|
|
766
|
+
const toggleSettings = () => { const off = document.body.dataset.right !== 'off'; document.body.dataset.right = off ? 'off' : 'on'; $('#ase-toggle-settings').classList.toggle('is-active', !off); fitPreview(); };
|
|
767
|
+
$('#ase-toggle-settings').addEventListener('click', toggleSettings);
|
|
319
768
|
$('#ase-discard').addEventListener('click', async () => {
|
|
320
|
-
if (!
|
|
769
|
+
if (!await confirmDialog('Discard changes', 'Discard all unsaved changes to this page?', 'Discard', 'danger')) return;
|
|
321
770
|
const r = await (await fetch(`/api/editor/page/${boot.slug}`)).json();
|
|
771
|
+
renderFull = true;
|
|
322
772
|
state.reset(r.page, r.hash);
|
|
323
773
|
});
|
|
324
|
-
$('#ase-save').addEventListener('click', save);
|
|
774
|
+
$('#ase-save').addEventListener('click', () => save());
|
|
775
|
+
$('#ase-publish').addEventListener('click', () => publish(true));
|
|
776
|
+
$('#ase-preview-tab').addEventListener('click', previewInTab);
|
|
325
777
|
document.querySelectorAll<HTMLButtonElement>('.ase-top__devices button').forEach((b) => b.addEventListener('click', () => {
|
|
326
778
|
document.querySelectorAll('.ase-top__devices button').forEach((x) => x.classList.remove('is-active'));
|
|
327
779
|
b.classList.add('is-active');
|
|
328
780
|
$('.ase-stage').dataset.device = b.dataset.device;
|
|
781
|
+
fitPreview();
|
|
329
782
|
}));
|
|
783
|
+
$('#ase-more').addEventListener('click', (e) => {
|
|
784
|
+
const items: MenuItem[] = [
|
|
785
|
+
{ label: 'Keyboard shortcuts', hint: '?', run: showShortcuts },
|
|
786
|
+
{ label: 'Revisions', run: showRevisions },
|
|
787
|
+
{ label: 'All pages', run: () => { location.href = '/edit'; }, separator: true },
|
|
788
|
+
];
|
|
789
|
+
if (boot.options.auth === 'passkey' && boot.options.user) items.push({ label: `Sign out ${boot.options.user}`, run: () => { location.href = '/api/editor/auth/logout'; } });
|
|
790
|
+
openMenu(e.currentTarget as HTMLElement, items);
|
|
791
|
+
});
|
|
330
792
|
|
|
331
|
-
|
|
332
|
-
|
|
793
|
+
/** The draft, rendered as visitors would see it, in its own tab. */
|
|
794
|
+
function previewInTab() {
|
|
333
795
|
inline.stop(true);
|
|
334
|
-
const
|
|
335
|
-
|
|
796
|
+
const form = document.createElement('form');
|
|
797
|
+
form.method = 'POST'; form.action = `/edit/preview/${boot.slug}`; form.target = '_blank'; form.hidden = true;
|
|
798
|
+
const input = document.createElement('input'); input.type = 'hidden'; input.name = 'page'; input.value = JSON.stringify(state.doc);
|
|
799
|
+
form.append(input);
|
|
800
|
+
document.body.append(form);
|
|
801
|
+
form.submit();
|
|
802
|
+
form.remove();
|
|
803
|
+
}
|
|
804
|
+
|
|
805
|
+
async function save(opts: { slug?: string } = {}): Promise<{ slug?: string; result?: any } | null> {
|
|
806
|
+
if (!state.dirty && !opts.slug) return null;
|
|
807
|
+
inline.stop(true);
|
|
808
|
+
saving = true; refreshButtons(); setSaveStatus('Saving…');
|
|
336
809
|
try {
|
|
337
|
-
const res = await fetch(`/api/editor/page/${boot.slug}`, { method: 'PUT', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ page: state.doc, base: state.hash }) });
|
|
810
|
+
const res = await fetch(`/api/editor/page/${boot.slug}`, { method: 'PUT', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ page: state.doc, base: state.hash, slug: opts.slug }) });
|
|
338
811
|
const data = await res.json();
|
|
339
|
-
if (!res.ok) { toast(data.error || 'Save failed', 'error');
|
|
812
|
+
if (!res.ok) { toast(data.error || 'Save failed', 'error'); setSaveStatus(''); return null; }
|
|
340
813
|
state.markSaved(data.hash);
|
|
814
|
+
boot.page = state.doc;
|
|
341
815
|
const r = data.result;
|
|
342
|
-
if (r.kind === 'github') toast(r.pullRequest ? `Committed and opened a pull request: ${r.pullRequest}` : `Committed ${String(r.commit).slice(0, 7)} to ${r.branch}. The host will rebuild the site.`, 'ok', r.pullRequest || r.url);
|
|
816
|
+
if (r.kind === 'github') toast(r.pullRequest ? `Committed and opened a pull request: ${r.pullRequest}` : `Committed ${String(r.commit).slice(0, 7)} to ${r.branch}. The host will rebuild the site.`, 'ok', { href: r.pullRequest || r.url });
|
|
343
817
|
else toast(`Saved to the working tree (${r.files.join(', ')}). Commit it with git when you're happy.`, 'ok');
|
|
344
|
-
|
|
345
|
-
|
|
818
|
+
setSaveStatus('Saved');
|
|
819
|
+
return data;
|
|
820
|
+
} catch (e: any) { toast(`Save failed: ${e.message}`, 'error'); setSaveStatus(''); return null; }
|
|
821
|
+
finally { saving = false; refreshChrome(); }
|
|
822
|
+
}
|
|
823
|
+
|
|
824
|
+
/** Publish a draft, or take a published page back to draft. Saves straight away, like WordPress. */
|
|
825
|
+
async function publish(live: boolean) {
|
|
826
|
+
if (!live && !await confirmDialog('Switch to draft', 'This page will be left out of the site the next time it is built.', 'Switch to draft')) return;
|
|
827
|
+
inline.stop(true);
|
|
828
|
+
const next = structuredClone(state.doc);
|
|
829
|
+
if (live) delete next.status; else next.status = 'draft';
|
|
830
|
+
state.apply(next);
|
|
831
|
+
if (await save()) toast(live ? `${next.title} is published.` : `${next.title} is now a draft.`, 'ok'); else state.undo();
|
|
832
|
+
}
|
|
833
|
+
|
|
834
|
+
async function changeUrl() {
|
|
835
|
+
const existing = boot.pages.map((p) => p.slug).filter((s) => s !== boot.slug);
|
|
836
|
+
const slug = await promptDialog({
|
|
837
|
+
title: 'Change URL', label: 'URL', value: boot.slug, submit: 'Change URL',
|
|
838
|
+
help: boot.options.redirects ? 'Old links will keep working: a redirect is added for you. Links inside other pages are not rewritten.' : 'Old links to this page will stop working, and links inside other pages are not rewritten.',
|
|
839
|
+
check: (v) => (v === boot.slug ? null : slugProblem(v, { existing, reserved: boot.reserved })),
|
|
840
|
+
});
|
|
841
|
+
if (!slug || slug === boot.slug) return;
|
|
842
|
+
const data = await save({ slug });
|
|
843
|
+
if (!data) return;
|
|
844
|
+
if (data.result?.pullRequest) return; // the move is in a pull request; this page stays where it is for now
|
|
845
|
+
leaving = true;
|
|
846
|
+
location.replace(`/edit/${data.slug}`);
|
|
847
|
+
}
|
|
848
|
+
|
|
849
|
+
async function deletePage() {
|
|
850
|
+
if (!await confirmDialog('Delete page', `Delete "${state.doc.title}"? It stays in the site's git history, so it can be recovered by a developer.`, 'Delete page', 'danger')) return;
|
|
851
|
+
const res = await fetch(`/api/editor/page/${boot.slug}`, { method: 'DELETE', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ base: state.hash }) });
|
|
852
|
+
const data = await res.json();
|
|
853
|
+
if (!res.ok) { toast(data.error || 'Delete failed', 'error'); return; }
|
|
854
|
+
state.clearDraft();
|
|
855
|
+
leaving = true;
|
|
856
|
+
location.href = '/edit';
|
|
857
|
+
}
|
|
858
|
+
|
|
859
|
+
async function showRevisions() {
|
|
860
|
+
const box = document.createElement('div');
|
|
861
|
+
box.innerHTML = '<p class="ase-muted">Loading…</p>';
|
|
862
|
+
const d = dialog('Revisions', box, [{ label: 'Close' }], { wide: true });
|
|
863
|
+
const data = await (await fetch(`/api/editor/page/${boot.slug}?revisions=1`)).json();
|
|
864
|
+
const revs = (data.revisions ?? []) as Revision[];
|
|
865
|
+
box.innerHTML = '';
|
|
866
|
+
if (!revs.length) { box.innerHTML = '<p class="ase-muted">No revisions yet. Each committed save appears here.</p>'; return; }
|
|
867
|
+
const ul = document.createElement('ul'); ul.className = 'ase-revisions';
|
|
868
|
+
for (const r of revs) {
|
|
869
|
+
const li = document.createElement('li');
|
|
870
|
+
const info = document.createElement('div');
|
|
871
|
+
const when = document.createElement('strong'); when.textContent = new Date(r.date).toLocaleString();
|
|
872
|
+
const what = document.createElement('span'); what.className = 'ase-muted ase-ellipsis'; what.textContent = `${r.author} · ${r.message}`;
|
|
873
|
+
info.append(when, what);
|
|
874
|
+
const b = document.createElement('button'); b.type = 'button'; b.className = 'ase-btn ase-btn--small'; b.textContent = 'Restore';
|
|
875
|
+
b.addEventListener('click', async () => {
|
|
876
|
+
const res = await (await fetch(`/api/editor/page/${boot.slug}?rev=${r.sha}`)).json();
|
|
877
|
+
if (!res.page) { toast('That revision could not be loaded.', 'error'); return; }
|
|
878
|
+
d.close();
|
|
879
|
+
inline.stop(true);
|
|
880
|
+
selected = null; tab = 'page';
|
|
881
|
+
renderFull = true;
|
|
882
|
+
const { status, ...rest } = res.page as PageDoc; // restoring content never publishes or unpublishes
|
|
883
|
+
state.apply({ ...rest, ...(state.doc.status ? { status: state.doc.status } : {}) }, 'restore');
|
|
884
|
+
toast('Revision loaded. Save to keep it.', 'info', { action: { label: 'Undo', run: () => state.undo() } });
|
|
885
|
+
});
|
|
886
|
+
li.append(info, b);
|
|
887
|
+
ul.append(li);
|
|
888
|
+
}
|
|
889
|
+
box.append(ul);
|
|
890
|
+
}
|
|
891
|
+
|
|
892
|
+
function showShortcuts() {
|
|
893
|
+
const groups: [string, [string, string][]][] = [
|
|
894
|
+
['Page', [['⌘S', 'Save'], ['⌘Z', 'Undo'], ['⇧⌘Z', 'Redo'], ['/', 'Add a block'], ['⇧⌘,', 'Show or hide settings'], ['⌃⌥O', 'Show or hide List View'], ['?', 'This list']]],
|
|
895
|
+
['Selected block', [['↑ ↓', 'Select previous / next block'], ['Esc', 'Deselect'], ['⇧⌘D', 'Duplicate'], ['Del', 'Delete'], ['⌘C ⌘X ⌘V', 'Copy, cut, paste'], ['⌥⌘T', 'Add before'], ['⌥⌘Y', 'Add after'], ['⇧⌥⌘T', 'Move up'], ['⇧⌥⌘Y', 'Move down']]],
|
|
896
|
+
['Text', [['⌘B', 'Bold'], ['⌘I', 'Italic'], ['⌘U', 'Underline'], ['⌘K', 'Link'], ['Esc', 'Cancel the edit']]],
|
|
897
|
+
];
|
|
898
|
+
const box = document.createElement('div');
|
|
899
|
+
box.className = 'ase-keys';
|
|
900
|
+
for (const [title, rows] of groups) {
|
|
901
|
+
const h = document.createElement('h3'); h.textContent = title;
|
|
902
|
+
const dl = document.createElement('dl');
|
|
903
|
+
for (const [k, what] of rows) { const dt = document.createElement('dt'); dt.textContent = what; const dd = document.createElement('dd'); dd.innerHTML = k.split(' ').map((x) => `<kbd>${x}</kbd>`).join(' '); dl.append(dt, dd); }
|
|
904
|
+
box.append(h, dl);
|
|
905
|
+
}
|
|
906
|
+
dialog('Keyboard shortcuts', box, [{ label: 'Close' }], { wide: true });
|
|
907
|
+
}
|
|
908
|
+
|
|
909
|
+
/** The block before or after the selected one, in page order. */
|
|
910
|
+
function neighbour(step: 1 | -1): string | null {
|
|
911
|
+
const all = Array.from(idoc().querySelectorAll<HTMLElement>('[data-ase-node]')).map((e) => e.dataset.aseNode!);
|
|
912
|
+
if (!selected) return all[0] ?? null;
|
|
913
|
+
return all[all.indexOf(selected) + step] ?? null;
|
|
346
914
|
}
|
|
347
915
|
|
|
348
916
|
function onKeydown(e: KeyboardEvent) {
|
|
349
917
|
const typing = (e.target as HTMLElement)?.closest?.('input, textarea, select, [contenteditable]');
|
|
350
918
|
const mod = e.metaKey || e.ctrlKey;
|
|
351
|
-
|
|
919
|
+
const key = e.key.toLowerCase();
|
|
920
|
+
const run = (fn: () => void) => { e.preventDefault(); fn(); };
|
|
921
|
+
if (mod && key === 's') return run(() => { save(); });
|
|
922
|
+
if (mod && e.shiftKey && (key === ',' || key === '<')) return run(toggleSettings);
|
|
923
|
+
if (e.ctrlKey && e.altKey && (key === 'o' || e.code === 'KeyO')) return run(() => setLeft(leftView === 'list' ? 'off' : 'list'));
|
|
352
924
|
if (typing) return;
|
|
353
|
-
if (
|
|
354
|
-
if (
|
|
355
|
-
if (
|
|
925
|
+
if (document.querySelector('.ase-modal')) return;
|
|
926
|
+
if (mod && key === 'z') return run(() => (e.shiftKey ? state.redo() : state.undo()));
|
|
927
|
+
if (mod && key === 'c' && selected && !idoc().getSelection()?.toString() && !getSelection()?.toString()) return run(() => act('copy'));
|
|
928
|
+
if (mod && key === 'x' && selected) return run(() => act('cut'));
|
|
929
|
+
if (mod && key === 'v') return run(paste);
|
|
930
|
+
if (mod && e.altKey && e.code === 'KeyT') return run(() => act(e.shiftKey ? 'up' : 'before'));
|
|
931
|
+
if (mod && e.altKey && e.code === 'KeyY') return run(() => act(e.shiftKey ? 'down' : 'after'));
|
|
932
|
+
if (mod && e.shiftKey && key === 'd') return run(() => act('dup'));
|
|
933
|
+
if (mod || e.altKey) return;
|
|
934
|
+
if (e.key === '/') return run(() => openInserter());
|
|
935
|
+
if (e.key === '?') return run(showShortcuts);
|
|
936
|
+
if ((e.key === 'Delete' || e.key === 'Backspace') && selected) return run(() => act('del'));
|
|
937
|
+
if (e.key === 'ArrowDown' || e.key === 'ArrowUp') { const to = neighbour(e.key === 'ArrowDown' ? 1 : -1); if (to) run(() => select(to)); return; }
|
|
938
|
+
if (e.key === 'Escape') { if (leftView === 'add') setLeft('list'); else select(null); }
|
|
356
939
|
}
|
|
357
940
|
document.addEventListener('keydown', onKeydown);
|
|
358
|
-
window.addEventListener('beforeunload', (e) => { if (state.dirty)
|
|
941
|
+
window.addEventListener('beforeunload', (e) => { if (state.dirty && !leaving) e.preventDefault(); });
|
|
359
942
|
|
|
360
943
|
// ---------- state → UI ----------
|
|
361
944
|
state.addEventListener('change', (e) => {
|
|
362
945
|
const source = (e as CustomEvent).detail.source;
|
|
363
946
|
if (source === 'inline') return; // DOM already matches; chrome refreshes on commit
|
|
364
|
-
if (source === '
|
|
947
|
+
if (source === 'field') { refreshChrome({ inspector: false }); return; } // the sidebar is the source: leave the focused input alone
|
|
948
|
+
if (source === 'undo' || source === 'redo' || source === 'restore' || source === 'reset') {
|
|
949
|
+
inline.stop(false);
|
|
950
|
+
if (selected && !nodeAt(state.doc, selected)) { selected = null; tab = 'page'; }
|
|
951
|
+
renderFull = true;
|
|
952
|
+
scheduleRender(0);
|
|
953
|
+
}
|
|
365
954
|
refreshChrome();
|
|
366
955
|
});
|
|
367
956
|
|
|
368
|
-
function
|
|
369
|
-
function toast(text: string, kind: 'ok' | 'info' | 'warn' | 'error', href?: string) {
|
|
370
|
-
const t = document.createElement('div');
|
|
371
|
-
t.className = `ase-toast ase-toast--${kind}`;
|
|
372
|
-
t.textContent = text;
|
|
373
|
-
if (href) { const a = document.createElement('a'); a.href = href; a.target = '_blank'; a.rel = 'noopener'; a.textContent = 'Open ↗'; t.append(' ', a); }
|
|
374
|
-
const x = document.createElement('button'); x.type = 'button'; x.textContent = '×'; x.addEventListener('click', () => t.remove()); t.append(x);
|
|
375
|
-
document.body.append(t);
|
|
376
|
-
setTimeout(() => t.remove(), kind === 'error' ? 15000 : 8000);
|
|
377
|
-
}
|
|
957
|
+
function setSaveStatus(t: string) { $('#ase-status').textContent = t; }
|
|
378
958
|
|
|
959
|
+
// Top-bar buttons get their icons here, so the Astro shell stays plain markup.
|
|
960
|
+
document.querySelectorAll<HTMLElement>('[data-icon]').forEach((el) => { el.insertAdjacentHTML('afterbegin', icons[el.dataset.icon as keyof typeof icons]); });
|
|
961
|
+
document.body.dataset.left = 'list';
|
|
962
|
+
fitPreview();
|
|
379
963
|
refreshChrome();
|
|
964
|
+
// A light page can finish loading before this module runs, and then `load` never fires for us.
|
|
965
|
+
if (idoc()?.readyState === 'complete' && idoc().location.href !== 'about:blank') onPreviewLoad();
|
|
966
|
+
else iframe.addEventListener('load', onPreviewLoad);
|