@pirateandfox/pagestack 0.1.0-beta.7 → 0.1.0-beta.8
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 +39 -12
- package/index.mjs +18 -6
- package/package.json +1 -1
- package/src/client/auth.ts +5 -5
- package/src/client/collection.ts +6 -6
- package/src/client/editor.ts +105 -105
- package/src/client/form.ts +26 -26
- package/src/client/global.ts +4 -4
- package/src/client/inline.ts +4 -4
- package/src/client/inserter.ts +11 -11
- package/src/client/invite.ts +4 -4
- package/src/client/item.ts +202 -54
- package/src/client/live.ts +92 -0
- package/src/client/media.ts +12 -12
- package/src/client/pages.ts +14 -14
- package/src/client/picker.ts +30 -30
- package/src/client/preview.css +58 -58
- package/src/client/rich.ts +14 -14
- package/src/client/shell.css +281 -272
- package/src/client/state.ts +2 -2
- package/src/client/tomarkdown.ts +4 -2
- package/src/client/tree.ts +11 -11
- package/src/client/ui.ts +13 -13
- package/src/client/users.ts +6 -6
- package/src/core/auth.ts +1 -1
- package/src/core/markdown.ts +54 -5
- package/src/core/pages.ts +6 -2
- package/src/core/storage-github.ts +51 -5
- package/src/core/storage.ts +14 -0
- package/src/routes/Nav.astro +5 -3
- package/src/routes/api/collection.ts +30 -8
- package/src/routes/api/live.ts +27 -0
- package/src/routes/edit-collection.astro +14 -14
- package/src/routes/edit-global.astro +8 -8
- package/src/routes/edit-index.astro +18 -18
- package/src/routes/edit-item.astro +25 -23
- package/src/routes/edit-media.astro +9 -9
- package/src/routes/edit-page.astro +32 -30
- package/src/routes/edit-users.astro +9 -9
- package/src/routes/enroll.astro +6 -6
- package/src/routes/login.astro +6 -6
- package/src/routes/preview-item.astro +1 -1
- package/src/routes/preview.astro +1 -1
- package/src/runtime.ts +3 -3
- package/src/server/context.ts +3 -3
- package/src/server/middleware.ts +19 -4
package/src/client/item.ts
CHANGED
|
@@ -4,22 +4,23 @@ import type { Field } from '../runtime';
|
|
|
4
4
|
import { sanitizeHtml } from '../core/sanitize';
|
|
5
5
|
import { renderForm } from './form';
|
|
6
6
|
import { pickImage } from './picker';
|
|
7
|
-
import { promptDialog, toast } from './ui';
|
|
7
|
+
import { confirmDialog, dialog, openMenu, promptDialog, toast } from './ui';
|
|
8
|
+
import { icons } from './icons';
|
|
8
9
|
import { InlineEditor } from './inline';
|
|
9
|
-
import { blockAt, replaceBlock } from '../core/markdown';
|
|
10
|
+
import { NEW_BLOCKS, blockAt, insertBlock, replaceBlock } from '../core/markdown';
|
|
10
11
|
import { blockToMarkdown } from './tomarkdown';
|
|
11
12
|
import previewCss from './preview.css?raw';
|
|
12
13
|
|
|
13
|
-
interface Boot { id: string; slug: string; singular: string; fields: Record<string, Field>; data: Record<string, any>; body: string; hash: string; viewUrl: string | null; preview: boolean; pages: { title: string; url: string }[] }
|
|
14
|
-
const boot = (window as any).
|
|
14
|
+
interface Boot { id: string; slug: string; singular: string; fields: Record<string, Field>; data: Record<string, any>; body: string; hash: string; viewUrl: string | null; redirects: boolean; preview: boolean; pages: { title: string; url: string }[] }
|
|
15
|
+
const boot = (window as any).__PS_ITEM__ as Boot;
|
|
15
16
|
const $ = <T extends HTMLElement>(id: string) => document.getElementById(id) as T;
|
|
16
|
-
const title = $<HTMLInputElement>('
|
|
17
|
-
const body = $<HTMLTextAreaElement>('
|
|
18
|
-
const preview = $('
|
|
19
|
-
const saveBtn = $<HTMLButtonElement>('
|
|
20
|
-
const publishBtn = $<HTMLButtonElement>('
|
|
21
|
-
const draftBtn = $<HTMLButtonElement>('
|
|
22
|
-
const status = $('
|
|
17
|
+
const title = $<HTMLInputElement>('ps-item-title');
|
|
18
|
+
const body = $<HTMLTextAreaElement>('ps-item-body');
|
|
19
|
+
const preview = $('ps-item-preview');
|
|
20
|
+
const saveBtn = $<HTMLButtonElement>('ps-item-save');
|
|
21
|
+
const publishBtn = $<HTMLButtonElement>('ps-item-publish');
|
|
22
|
+
const draftBtn = $<HTMLButtonElement>('ps-item-draft');
|
|
23
|
+
const status = $('ps-item-status');
|
|
23
24
|
|
|
24
25
|
const data = structuredClone(boot.data);
|
|
25
26
|
const hasDraft = boot.fields.draft?.type === 'boolean';
|
|
@@ -32,7 +33,7 @@ function chrome() {
|
|
|
32
33
|
publishBtn.hidden = !draft;
|
|
33
34
|
draftBtn.hidden = !hasDraft || draft;
|
|
34
35
|
saveBtn.disabled = !dirty;
|
|
35
|
-
const view = document.getElementById('
|
|
36
|
+
const view = document.getElementById('ps-item-view'); if (view) view.hidden = draft;
|
|
36
37
|
status.textContent = dirty ? 'Unsaved changes' : draft ? 'Draft: not on the site yet' : '';
|
|
37
38
|
}
|
|
38
39
|
const touch = () => { dirty = true; chrome(); };
|
|
@@ -73,9 +74,9 @@ const tools: [string, string, () => void][] = [
|
|
|
73
74
|
];
|
|
74
75
|
for (const [label, text, run] of tools) {
|
|
75
76
|
const b = document.createElement('button');
|
|
76
|
-
b.type = 'button'; b.title = label; b.setAttribute('aria-label', label); b.textContent = text; b.className = '
|
|
77
|
+
b.type = 'button'; b.title = label; b.setAttribute('aria-label', label); b.textContent = text; b.className = 'ps-btn ps-btn--small ps-btn--ghost';
|
|
77
78
|
b.addEventListener('click', run);
|
|
78
|
-
$('
|
|
79
|
+
$('ps-mdbar').append(b);
|
|
79
80
|
}
|
|
80
81
|
function changed() { draw(); touch(); schedulePage(); }
|
|
81
82
|
body.addEventListener('input', changed);
|
|
@@ -93,7 +94,7 @@ async function save(): Promise<boolean> {
|
|
|
93
94
|
const d = await res.json();
|
|
94
95
|
if (!res.ok) { toast(d.error || 'Save failed', 'error'); saveBtn.disabled = false; status.textContent = 'Not saved'; return false; }
|
|
95
96
|
hash = d.hash; dirty = false; chrome();
|
|
96
|
-
toast(d.unchanged ? 'No changes to save.' : d.result?.pullRequest ? 'Saved as a pull request.' : d.result?.kind === 'github' ? 'Saved. The site will rebuild.' : 'Saved.', 'ok');
|
|
97
|
+
toast(d.unchanged ? 'No changes to save.' : d.result?.pullRequest ? 'Saved as a pull request.' : d.result?.kind === 'github' ? (document.getElementById('ps-live') ? 'Saved. Use Go live to put it on the site.' : 'Saved. The site will rebuild.') : 'Saved.', 'ok');
|
|
97
98
|
return true;
|
|
98
99
|
}
|
|
99
100
|
saveBtn.addEventListener('click', save);
|
|
@@ -103,27 +104,96 @@ draftBtn.addEventListener('click', () => setDraft(true));
|
|
|
103
104
|
addEventListener('keydown', (e) => { if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 's') { e.preventDefault(); if (dirty) save(); } });
|
|
104
105
|
addEventListener('beforeunload', (e) => { if (dirty) e.preventDefault(); });
|
|
105
106
|
|
|
107
|
+
// ---- URL, revisions, delete ----
|
|
108
|
+
const moreBtn = $<HTMLButtonElement>('ps-item-more');
|
|
109
|
+
moreBtn.innerHTML = icons.more;
|
|
110
|
+
moreBtn.addEventListener('click', () => openMenu(moreBtn, [
|
|
111
|
+
{ label: 'Change URL', run: changeUrl },
|
|
112
|
+
{ label: 'Revisions', run: showRevisions },
|
|
113
|
+
{ label: `Delete ${boot.singular}`, run: deleteItem, danger: true },
|
|
114
|
+
]));
|
|
115
|
+
|
|
116
|
+
async function changeUrl() {
|
|
117
|
+
const next = await promptDialog({
|
|
118
|
+
title: 'Change URL', label: 'URL', value: boot.slug, submit: 'Change URL',
|
|
119
|
+
help: boot.redirects ? 'Old links keep working: a redirect is added for you. Links inside other pages are not rewritten.' : 'Old links to it will stop working, and links inside other pages are not rewritten.',
|
|
120
|
+
check: (v) => (v === boot.slug || /^[a-z0-9][a-z0-9_-]*$/.test(v) ? null : 'Use lowercase letters, numbers and dashes.'),
|
|
121
|
+
});
|
|
122
|
+
if (!next || next === boot.slug) return;
|
|
123
|
+
if (frame && inline.isActive) inline.stop(true);
|
|
124
|
+
const res = await fetch(`/api/editor/collection/${boot.id}/${boot.slug}`, { method: 'PUT', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ data, body: body.value, base: hash, slug: next }) });
|
|
125
|
+
const d = await res.json();
|
|
126
|
+
if (!res.ok) { toast(d.error || 'Could not change the URL.', 'error'); return; }
|
|
127
|
+
if (d.result?.pullRequest) { toast('The move is in a pull request; this stays where it is until that is merged.', 'info', { href: d.result.pullRequest }); return; }
|
|
128
|
+
dirty = false;
|
|
129
|
+
location.replace(`/edit/collection/${boot.id}/${d.slug}`);
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
async function showRevisions() {
|
|
133
|
+
const box = document.createElement('div');
|
|
134
|
+
box.innerHTML = '<p class="ps-muted">Loading…</p>';
|
|
135
|
+
const dlg = dialog('Revisions', box, [{ label: 'Close' }], { wide: true });
|
|
136
|
+
const res = await (await fetch(`/api/editor/collection/${boot.id}/${boot.slug}?revisions=1`)).json();
|
|
137
|
+
const revs = (res.revisions ?? []) as { sha: string; message: string; author: string; date: string }[];
|
|
138
|
+
box.innerHTML = '';
|
|
139
|
+
if (!revs.length) { box.innerHTML = '<p class="ps-muted">No revisions yet. Each committed save appears here.</p>'; return; }
|
|
140
|
+
const ul = document.createElement('ul'); ul.className = 'ps-revisions';
|
|
141
|
+
for (const r of revs) {
|
|
142
|
+
const li = document.createElement('li');
|
|
143
|
+
const info = document.createElement('div');
|
|
144
|
+
const when = document.createElement('strong'); when.textContent = new Date(r.date).toLocaleString();
|
|
145
|
+
const what = document.createElement('span'); what.className = 'ps-muted ps-ellipsis'; what.textContent = `${r.author} · ${r.message}`;
|
|
146
|
+
info.append(when, what);
|
|
147
|
+
const b = document.createElement('button'); b.type = 'button'; b.className = 'ps-btn ps-btn--small'; b.textContent = 'Restore';
|
|
148
|
+
b.addEventListener('click', async () => {
|
|
149
|
+
const old = await (await fetch(`/api/editor/collection/${boot.id}/${boot.slug}?rev=${r.sha}`)).json();
|
|
150
|
+
if (!old?.data) { toast('That revision could not be loaded.', 'error'); return; }
|
|
151
|
+
dlg.close();
|
|
152
|
+
if (frame && inline.isActive) inline.stop(false);
|
|
153
|
+
const draft = data.draft; // restoring content never publishes or unpublishes
|
|
154
|
+
for (const k of Object.keys(data)) delete data[k];
|
|
155
|
+
Object.assign(data, old.data);
|
|
156
|
+
if (hasDraft) data.draft = draft; else delete data.draft;
|
|
157
|
+
title.value = data.title ?? '';
|
|
158
|
+
body.value = old.body ?? '';
|
|
159
|
+
drawForm(); changed(); chrome();
|
|
160
|
+
toast('Revision loaded. Save to keep it.', 'info');
|
|
161
|
+
});
|
|
162
|
+
li.append(info, b); ul.append(li);
|
|
163
|
+
}
|
|
164
|
+
box.append(ul);
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
async function deleteItem() {
|
|
168
|
+
if (!await confirmDialog(`Delete ${boot.singular}`, `Delete "${data.title ?? boot.slug}"? It stays in the site's git history, so it can be recovered by a developer.`, 'Delete', 'danger')) return;
|
|
169
|
+
const res = await fetch(`/api/editor/collection/${boot.id}/${boot.slug}`, { method: 'DELETE' });
|
|
170
|
+
const d = await res.json().catch(() => ({}));
|
|
171
|
+
if (!res.ok) { toast(d.error || 'Delete failed', 'error'); return; }
|
|
172
|
+
dirty = false;
|
|
173
|
+
location.href = `/edit/collection/${boot.id}`;
|
|
174
|
+
}
|
|
175
|
+
|
|
106
176
|
// ---- start ----
|
|
107
177
|
title.value = data.title ?? '';
|
|
108
178
|
title.addEventListener('input', () => { data.title = title.value; touch(); schedulePage(); });
|
|
109
179
|
body.value = boot.body;
|
|
110
180
|
const { title: _, draft: __, ...side } = boot.fields;
|
|
111
|
-
const drawForm = () => renderForm($('
|
|
181
|
+
const drawForm = () => renderForm($('ps-item-form'), { label: boot.singular, fields: side }, data, { pickImage, pageUrls: boot.pages, onChange: (name, value) => { data[name] = value; touch(); schedulePage(); } });
|
|
112
182
|
drawForm();
|
|
113
183
|
draw(); chrome();
|
|
114
184
|
|
|
115
185
|
// ---- page mode: the item on its own layout, edited in place ----
|
|
116
|
-
// The site's `previews` component renders it; body blocks carry data-
|
|
186
|
+
// The site's `previews` component renders it; body blocks carry data-ps-md="<index>", and an
|
|
117
187
|
// edited paragraph or heading is turned back into Markdown and replaces only its own source.
|
|
118
|
-
const frame = document.getElementById('
|
|
119
|
-
const pageBox = document.getElementById('
|
|
188
|
+
const frame = document.getElementById('ps-item-frame') as HTMLIFrameElement | null;
|
|
189
|
+
const pageBox = document.getElementById('ps-item-page');
|
|
120
190
|
const previewUrl = `/edit/preview-item/${boot.id}/${boot.slug}`;
|
|
121
191
|
let mode: 'page' | 'markdown' = 'markdown';
|
|
122
192
|
let frameReady = false;
|
|
123
193
|
let pageTimer: ReturnType<typeof setTimeout> | undefined;
|
|
124
194
|
let pageSeq = 0;
|
|
125
195
|
let pageQueued = false;
|
|
126
|
-
let editingBlock: { el: HTMLElement; index: number; depth?: number } | null = null;
|
|
196
|
+
let editingBlock: { el: HTMLElement; index: number; depth?: number; undo?: { body: string; dirty: boolean } } | null = null;
|
|
127
197
|
const fdoc = () => frame!.contentDocument!;
|
|
128
198
|
|
|
129
199
|
function setMode(m: 'page' | 'markdown') {
|
|
@@ -131,35 +201,50 @@ function setMode(m: 'page' | 'markdown') {
|
|
|
131
201
|
if (inline.isActive) inline.stop(true);
|
|
132
202
|
mode = m;
|
|
133
203
|
pageBox!.hidden = m !== 'page';
|
|
134
|
-
$('
|
|
135
|
-
document.querySelectorAll<HTMLElement>('.
|
|
136
|
-
try { localStorage.setItem('
|
|
204
|
+
$('ps-item-md').hidden = m === 'page';
|
|
205
|
+
document.querySelectorAll<HTMLElement>('.ps-seg__btn').forEach((b) => b.setAttribute('aria-pressed', String(b.dataset.mode === m)));
|
|
206
|
+
try { localStorage.setItem('ps-item-mode', m); } catch { /* private mode */ }
|
|
137
207
|
if (m === 'page') { if (!frame.src) frame.src = previewUrl; else if (frameReady) renderPage(); }
|
|
138
208
|
}
|
|
139
209
|
function schedulePage(ms = 300) { if (frame && mode === 'page') { clearTimeout(pageTimer); pageTimer = setTimeout(renderPage, ms); } }
|
|
140
210
|
|
|
141
|
-
async function renderPage() {
|
|
142
|
-
if (!frameReady) return;
|
|
143
|
-
if (inline.isActive) { pageQueued = true; return; } // never swap the text under the cursor
|
|
211
|
+
async function renderPage(): Promise<boolean> {
|
|
212
|
+
if (!frameReady) return false;
|
|
213
|
+
if (inline.isActive) { pageQueued = true; return false; } // never swap the text under the cursor
|
|
144
214
|
const seq = ++pageSeq;
|
|
145
215
|
const res = await fetch(previewUrl, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ data, body: body.value }) }).catch(() => null);
|
|
146
|
-
if (!res || seq !== pageSeq) return;
|
|
216
|
+
if (!res || seq !== pageSeq) return false;
|
|
147
217
|
const html = await res.text();
|
|
148
|
-
if (!res.ok) { toast(`Preview failed: ${html.slice(0, 160)}`, 'error'); return; }
|
|
149
|
-
if (inline.isActive) { pageQueued = true; return; }
|
|
218
|
+
if (!res.ok) { toast(`Preview failed: ${html.slice(0, 160)}`, 'error'); return false; }
|
|
219
|
+
if (inline.isActive) { pageQueued = true; return false; }
|
|
150
220
|
const fresh = new DOMParser().parseFromString(html, 'text/html');
|
|
151
221
|
const win = frame!.contentWindow!; const y = win.scrollY;
|
|
152
222
|
fdoc().body.innerHTML = fresh.body.innerHTML;
|
|
153
223
|
fdoc().body.className = fresh.body.className;
|
|
154
224
|
win.scrollTo(0, y);
|
|
225
|
+
return true;
|
|
155
226
|
}
|
|
156
227
|
|
|
157
228
|
const inline = new InlineEditor({
|
|
158
229
|
pages: boot.pages,
|
|
159
230
|
onStart: () => {},
|
|
160
231
|
onInput: () => {},
|
|
232
|
+
onSlash: () => {
|
|
233
|
+
// "/" in an emptied block: the new block takes its place. Stop editing first, without saving
|
|
234
|
+
// the emptied text, so the menu taking focus can't commit it.
|
|
235
|
+
const blk = editingBlock; if (!blk) return;
|
|
236
|
+
const undo = blk.undo ?? { body: body.value, dirty };
|
|
237
|
+
editingBlock = null; inline.stop(false);
|
|
238
|
+
const base = removeAt(body.value, blk.index);
|
|
239
|
+
openInserter(blk.el, base, prevIndex(base, blk.index), undo);
|
|
240
|
+
},
|
|
161
241
|
onCommit: (path, value, didChange) => {
|
|
162
242
|
const blk = editingBlock; editingBlock = null;
|
|
243
|
+
if (blk?.undo && !didChange) {
|
|
244
|
+
// A block just added and left as it came: take it out again.
|
|
245
|
+
body.value = blk.undo.body; dirty = blk.undo.dirty; draw(); chrome(); schedulePage(0);
|
|
246
|
+
return;
|
|
247
|
+
}
|
|
163
248
|
if (didChange) {
|
|
164
249
|
if (blk) {
|
|
165
250
|
const md = blockToMarkdown(blk.el, blk.depth);
|
|
@@ -178,13 +263,13 @@ const removeBlock = (md: string, i: number) => { const b = blockAt(md, i); retur
|
|
|
178
263
|
|
|
179
264
|
function onFrameClick(e: MouseEvent) {
|
|
180
265
|
const t = e.target as HTMLElement;
|
|
181
|
-
if (t.closest('.
|
|
266
|
+
if (t.closest('.ps-rt, .ps-link, [data-ps-ui]')) return;
|
|
182
267
|
if (!t.closest('summary')) e.preventDefault(); // links don't navigate while editing
|
|
183
|
-
const field = t.closest<HTMLElement>('[data-
|
|
184
|
-
const blockEl = t.closest<HTMLElement>('[data-
|
|
185
|
-
if (field && !field.dataset.
|
|
186
|
-
const name = field.dataset.
|
|
187
|
-
if (field.dataset.
|
|
268
|
+
const field = t.closest<HTMLElement>('[data-ps-field]');
|
|
269
|
+
const blockEl = t.closest<HTMLElement>('[data-ps-md]');
|
|
270
|
+
if (field && !field.dataset.psField!.startsWith('md:')) {
|
|
271
|
+
const name = field.dataset.psField!;
|
|
272
|
+
if (field.dataset.psFieldType === 'image') {
|
|
188
273
|
const f = boot.fields[name];
|
|
189
274
|
const cur = data[name];
|
|
190
275
|
pickImage(cur ? (typeof cur === 'string' ? { src: cur, alt: f?.altField ? data[f.altField] ?? '' : '' } : cur) : undefined, (img) => {
|
|
@@ -198,49 +283,112 @@ function onFrameClick(e: MouseEvent) {
|
|
|
198
283
|
return;
|
|
199
284
|
}
|
|
200
285
|
if (blockEl) {
|
|
201
|
-
const index = Number(blockEl.dataset.
|
|
202
|
-
const kind = blockEl.dataset.
|
|
203
|
-
if (kind === 'text') {
|
|
204
|
-
if (editingBlock?.el === blockEl) return;
|
|
205
|
-
if (inline.isActive) inline.stop(true);
|
|
206
|
-
const src = blockAt(body.value, index);
|
|
207
|
-
editingBlock = { el: blockEl, index, depth: src?.type === 'heading' ? src.depth : undefined };
|
|
208
|
-
blockEl.dataset.aseField = `md:${index}`; blockEl.dataset.aseFieldType = 'richtext';
|
|
209
|
-
inline.start(blockEl);
|
|
210
|
-
return;
|
|
211
|
-
}
|
|
286
|
+
const index = Number(blockEl.dataset.psMd);
|
|
287
|
+
const kind = blockEl.dataset.psMdKind;
|
|
288
|
+
if (kind === 'text') { if (editingBlock?.el !== blockEl) editBlock(blockEl, index); return; }
|
|
212
289
|
if (inline.isActive) inline.stop(true);
|
|
213
290
|
if (kind === 'image') {
|
|
214
291
|
const m = blockAt(body.value, index)?.raw.match(/!\[([^\]]*)\]\(([^)\s]+)/);
|
|
215
292
|
pickImage(m ? { src: m[2], alt: m[1] } : undefined, (img) => { body.value = replaceBlock(body.value, index, `![${img.alt.replace(/[[\]]/g, '')}](${img.src})`); changed(); });
|
|
216
293
|
return;
|
|
217
294
|
}
|
|
218
|
-
//
|
|
219
|
-
const b = blockAt(body.value, index);
|
|
220
|
-
setMode('markdown');
|
|
221
|
-
if (b) { body.focus(); body.setSelectionRange(b.start, b.start + b.raw.trimEnd().length); }
|
|
295
|
+
markdownAt(index); // tables, code, nested lists: edit their Markdown, with the block selected
|
|
222
296
|
return;
|
|
223
297
|
}
|
|
224
298
|
if (inline.isActive) inline.stop(true);
|
|
225
299
|
}
|
|
226
300
|
|
|
301
|
+
function editBlock(el: HTMLElement, index: number, undo?: { body: string; dirty: boolean }) {
|
|
302
|
+
if (inline.isActive) inline.stop(true);
|
|
303
|
+
const src = blockAt(body.value, index);
|
|
304
|
+
editingBlock = { el, index, depth: src?.type === 'heading' ? src.depth : undefined, undo };
|
|
305
|
+
el.dataset.psField = `md:${index}`; el.dataset.psFieldType = 'richtext';
|
|
306
|
+
inline.start(el);
|
|
307
|
+
if (undo) { // a new block: its sample text is selected, so typing replaces it
|
|
308
|
+
const target = el.querySelector('li, p') ?? el;
|
|
309
|
+
const r = fdoc().createRange(); r.selectNodeContents(target);
|
|
310
|
+
const sel = fdoc().getSelection(); sel?.removeAllRanges(); sel?.addRange(r);
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
function markdownAt(index: number) {
|
|
315
|
+
const b = blockAt(body.value, index);
|
|
316
|
+
setMode('markdown');
|
|
317
|
+
if (b) { body.focus(); body.setSelectionRange(b.start, b.start + b.raw.trimEnd().length); }
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
// ---- adding blocks on the page: a + beside the block under the pointer, or / in an empty one ----
|
|
321
|
+
const ADD: { label: string; hint?: string; key: keyof typeof NEW_BLOCKS | 'image' }[] = [
|
|
322
|
+
{ label: 'Paragraph', key: 'paragraph' }, { label: 'Heading', key: 'heading' }, { label: 'Subheading', key: 'subheading' },
|
|
323
|
+
{ label: 'Bulleted list', key: 'list' }, { label: 'Numbered list', key: 'numbered' }, { label: 'Quote', key: 'quote' },
|
|
324
|
+
{ label: 'Image', key: 'image' }, { label: 'Table', hint: 'in Markdown', key: 'table' },
|
|
325
|
+
];
|
|
326
|
+
let plus: HTMLButtonElement | null = null;
|
|
327
|
+
let plusFor: { el: HTMLElement; index: number } | null = null;
|
|
328
|
+
|
|
329
|
+
function placePlus(e: MouseEvent) {
|
|
330
|
+
if (!plus || inline.isActive) return;
|
|
331
|
+
const t = e.target as HTMLElement;
|
|
332
|
+
if (t === plus) return;
|
|
333
|
+
const blk = t.closest<HTMLElement>('[data-ps-md]');
|
|
334
|
+
if (!blk) return;
|
|
335
|
+
const r = blk.getBoundingClientRect();
|
|
336
|
+
plusFor = { el: blk, index: Number(blk.dataset.psMd) };
|
|
337
|
+
plus.style.top = `${r.bottom}px`;
|
|
338
|
+
plus.style.left = `${Math.max(16, r.left - 18)}px`;
|
|
339
|
+
plus.hidden = false;
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
function openInserter(anchor: HTMLElement, base: string, at: number | null, undo: { body: string; dirty: boolean }) {
|
|
343
|
+
openMenu(anchor, ADD.map((a) => ({ label: a.label, hint: a.hint, run: () => addBlock(a.key, base, at, undo) })));
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
async function addBlock(key: (typeof ADD)[number]['key'], base: string, at: number | null, undo: { body: string; dirty: boolean }) {
|
|
347
|
+
if (inline.isActive) inline.stop(true);
|
|
348
|
+
if (key === 'image') {
|
|
349
|
+
pickImage(undefined, (img) => { body.value = insertBlock(base, at, `![${img.alt.replace(/[[\]]/g, '')}](${img.src})`).md; changed(); });
|
|
350
|
+
return;
|
|
351
|
+
}
|
|
352
|
+
const { md, index } = insertBlock(base, at, NEW_BLOCKS[key]);
|
|
353
|
+
body.value = md; draw(); touch();
|
|
354
|
+
if (key === 'table') { markdownAt(index); return; }
|
|
355
|
+
if (!await renderPage()) return;
|
|
356
|
+
const el = fdoc().querySelector<HTMLElement>(`[data-ps-md="${index}"]`);
|
|
357
|
+
if (!el) return;
|
|
358
|
+
el.scrollIntoView({ block: 'nearest' });
|
|
359
|
+
editBlock(el, index, undo);
|
|
360
|
+
}
|
|
361
|
+
const removeAt = (md: string, i: number) => { const b = blockAt(md, i); return b ? (md.slice(0, b.start) + md.slice(b.end)) : md; };
|
|
362
|
+
/** The block before position `i` once block `i` is gone, as an index into `md`. */
|
|
363
|
+
function prevIndex(md: string, i: number): number | null {
|
|
364
|
+
for (let j = i - 1; j >= 0; j--) { const b = blockAt(md, j); if (b && b.type !== 'space') return j; }
|
|
365
|
+
return null;
|
|
366
|
+
}
|
|
367
|
+
|
|
227
368
|
if (frame) {
|
|
228
369
|
frame.addEventListener('load', () => {
|
|
229
370
|
const d = fdoc();
|
|
230
|
-
const style = d.createElement('style'); style.textContent = previewCss + '[data-
|
|
371
|
+
const style = d.createElement('style'); style.textContent = previewCss + '[data-ps-md]{cursor:text}[data-ps-md]:hover{outline:1px dotted #2563eb;outline-offset:2px}[data-ps-md-kind="block"],[data-ps-md-kind="image"]{cursor:pointer}';
|
|
231
372
|
d.head.append(style);
|
|
232
373
|
d.addEventListener('click', onFrameClick, true);
|
|
233
374
|
d.addEventListener('submit', (e) => e.preventDefault(), true);
|
|
375
|
+
plus = d.createElement('button');
|
|
376
|
+
plus.type = 'button'; plus.className = 'ps-plus'; plus.setAttribute('data-ps-ui', ''); plus.hidden = true;
|
|
377
|
+
plus.title = 'Add a block'; plus.setAttribute('aria-label', 'Add a block'); plus.innerHTML = icons.plus;
|
|
378
|
+
plus.addEventListener('click', (e) => { e.preventDefault(); e.stopPropagation(); if (plusFor) openInserter(plus!, body.value, plusFor.index, { body: body.value, dirty }); });
|
|
379
|
+
d.documentElement.append(plus);
|
|
380
|
+
d.addEventListener('mousemove', placePlus);
|
|
381
|
+
d.defaultView?.addEventListener('scroll', () => { if (plus) plus.hidden = true; });
|
|
234
382
|
d.addEventListener('keydown', (e) => { if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 's') { e.preventDefault(); if (inline.isActive) inline.stop(true); if (dirty) save(); } });
|
|
235
383
|
frameReady = true;
|
|
236
384
|
if (dirty) renderPage();
|
|
237
385
|
});
|
|
238
|
-
document.querySelectorAll<HTMLElement>('.
|
|
386
|
+
document.querySelectorAll<HTMLElement>('.ps-seg__btn').forEach((b) => b.addEventListener('click', () => setMode(b.dataset.mode as 'page' | 'markdown')));
|
|
239
387
|
let saved: string | null = null;
|
|
240
|
-
try { saved = localStorage.getItem('
|
|
388
|
+
try { saved = localStorage.getItem('ps-item-mode'); } catch { /* private mode */ }
|
|
241
389
|
setMode(saved === 'markdown' ? 'markdown' : 'page');
|
|
242
390
|
// A look at the unsaved item as visitors will see it, in its own tab.
|
|
243
|
-
document.getElementById('
|
|
391
|
+
document.getElementById('ps-item-tab')?.addEventListener('click', () => {
|
|
244
392
|
if (inline.isActive) inline.stop(true);
|
|
245
393
|
const form = document.createElement('form');
|
|
246
394
|
form.method = 'POST'; form.action = previewUrl; form.target = '_blank'; form.hidden = true;
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
// The Go live button, in every screen's top bar. Hidden unless the site has a live branch
|
|
2
|
+
// (`github.live`): then saves wait on staging, the button counts them, and one click puts them all
|
|
3
|
+
// on the public site. It refreshes itself after any save, wherever on the screen that happened.
|
|
4
|
+
import { dialog, toast } from './ui';
|
|
5
|
+
|
|
6
|
+
interface Pending { enabled: true; branch: string; live: string; count: number; changes: { sha: string; message: string; author: string; date: string }[]; stagingUrl: string | null }
|
|
7
|
+
|
|
8
|
+
const btn = document.getElementById('ps-live') as HTMLButtonElement | null;
|
|
9
|
+
let state: Pending | null = null;
|
|
10
|
+
|
|
11
|
+
function ago(iso: string): string {
|
|
12
|
+
const s = (Date.now() - Date.parse(iso)) / 1000;
|
|
13
|
+
if (!isFinite(s)) return '';
|
|
14
|
+
if (s < 90) return 'just now';
|
|
15
|
+
if (s < 5400) return `${Math.round(s / 60)} min ago`;
|
|
16
|
+
if (s < 129600) return `${Math.round(s / 3600)} h ago`;
|
|
17
|
+
return new Date(iso).toLocaleDateString();
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function draw() {
|
|
21
|
+
if (!btn || !state) return;
|
|
22
|
+
btn.hidden = false;
|
|
23
|
+
const n = state.count;
|
|
24
|
+
btn.disabled = n === 0;
|
|
25
|
+
btn.textContent = 'Go live';
|
|
26
|
+
if (n) { const b = document.createElement('span'); b.className = 'ps-live__count'; b.textContent = String(n); btn.append(b); }
|
|
27
|
+
btn.title = n ? `${n} saved change${n === 1 ? '' : 's'} not on the live site yet` : 'Everything saved is on the live site';
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
let inflight: Promise<void> | null = null;
|
|
31
|
+
async function refresh() {
|
|
32
|
+
if (inflight) return inflight;
|
|
33
|
+
inflight = (async () => {
|
|
34
|
+
try {
|
|
35
|
+
const r = await fetch('/api/editor/live', { headers: { accept: 'application/json' } });
|
|
36
|
+
const data = await r.json();
|
|
37
|
+
if (data?.enabled) { state = data; draw(); }
|
|
38
|
+
} catch { /* offline or signed out: leave the button as it was */ }
|
|
39
|
+
finally { inflight = null; }
|
|
40
|
+
})();
|
|
41
|
+
return inflight;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
async function goLive() {
|
|
45
|
+
await refresh();
|
|
46
|
+
if (!state?.count) return;
|
|
47
|
+
const body = document.createElement('div');
|
|
48
|
+
const intro = document.createElement('p');
|
|
49
|
+
intro.textContent = `${state.count} saved change${state.count === 1 ? '' : 's'} will go on the public site. It updates a few minutes after you confirm.`;
|
|
50
|
+
const list = document.createElement('ul'); list.className = 'ps-live__list';
|
|
51
|
+
for (const c of state.changes) {
|
|
52
|
+
const li = document.createElement('li');
|
|
53
|
+
const what = document.createElement('span'); what.textContent = c.message;
|
|
54
|
+
const meta = document.createElement('span'); meta.className = 'ps-muted'; meta.textContent = [c.author, ago(c.date)].filter(Boolean).join(' · ');
|
|
55
|
+
li.append(what, meta); list.append(li);
|
|
56
|
+
}
|
|
57
|
+
body.append(intro, list);
|
|
58
|
+
if (state.count > state.changes.length) { const more = document.createElement('p'); more.className = 'ps-muted'; more.textContent = `…and ${state.count - state.changes.length} earlier.`; body.append(more); }
|
|
59
|
+
if (state.stagingUrl) {
|
|
60
|
+
const p = document.createElement('p'); const a = document.createElement('a');
|
|
61
|
+
a.href = state.stagingUrl; a.target = '_blank'; a.rel = 'noopener'; a.textContent = 'See them on the staging site first ↗';
|
|
62
|
+
p.append(a); body.append(p);
|
|
63
|
+
}
|
|
64
|
+
dialog('Go live?', body, [
|
|
65
|
+
{ label: 'Cancel' },
|
|
66
|
+
{
|
|
67
|
+
label: 'Go live', kind: 'primary', run: async () => {
|
|
68
|
+
const r = await fetch('/api/editor/live', { method: 'POST', headers: { accept: 'application/json' } });
|
|
69
|
+
const data = await r.json().catch(() => ({}));
|
|
70
|
+
if (!r.ok) { toast(data.error ?? 'Could not go live.', 'error'); return false; }
|
|
71
|
+
if (data.nothing) toast('Everything saved was already live.', 'info');
|
|
72
|
+
else toast(`Live. ${data.count} change${data.count === 1 ? ' is' : 's are'} on the way to the site; it updates in a few minutes.`, 'ok', { href: data.url });
|
|
73
|
+
await refresh();
|
|
74
|
+
},
|
|
75
|
+
},
|
|
76
|
+
], { wide: true });
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
if (btn) {
|
|
80
|
+
btn.addEventListener('click', goLive);
|
|
81
|
+
// Saves are writes to the editor API from many screens; recount after any that succeeds.
|
|
82
|
+
const original = window.fetch.bind(window);
|
|
83
|
+
window.fetch = async (input, init) => {
|
|
84
|
+
const res = await original(input, init);
|
|
85
|
+
const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url;
|
|
86
|
+
const method = (init?.method ?? (input instanceof Request ? input.method : 'GET')).toUpperCase();
|
|
87
|
+
if (res.ok && method !== 'GET' && /\/api\/editor\/(?!live|auth\/)/.test(url)) setTimeout(refresh, 300);
|
|
88
|
+
return res;
|
|
89
|
+
};
|
|
90
|
+
window.addEventListener('focus', () => { refresh(); });
|
|
91
|
+
refresh();
|
|
92
|
+
}
|
package/src/client/media.ts
CHANGED
|
@@ -3,10 +3,10 @@ import { dialog, toast } from './ui';
|
|
|
3
3
|
import { uploadImage } from './upload';
|
|
4
4
|
|
|
5
5
|
interface Image { src: string; name: string; size?: number }
|
|
6
|
-
const grid = document.getElementById('
|
|
7
|
-
const search = document.getElementById('
|
|
8
|
-
const count = document.getElementById('
|
|
9
|
-
const drop = document.querySelector<HTMLElement>('.
|
|
6
|
+
const grid = document.getElementById('ps-media-grid')!;
|
|
7
|
+
const search = document.getElementById('ps-media-search') as HTMLInputElement;
|
|
8
|
+
const count = document.getElementById('ps-media-count')!;
|
|
9
|
+
const drop = document.querySelector<HTMLElement>('.ps-media__drop')!;
|
|
10
10
|
|
|
11
11
|
const kb = (n?: number) => (n == null ? '' : n > 1048576 ? `${(n / 1048576).toFixed(1)} MB` : `${Math.round(n / 1024)} KB`);
|
|
12
12
|
|
|
@@ -15,14 +15,14 @@ async function load() {
|
|
|
15
15
|
const { images, total } = await res.json() as { images: Image[]; total: number };
|
|
16
16
|
count.textContent = String(total);
|
|
17
17
|
grid.replaceChildren(...images.map(tile));
|
|
18
|
-
if (!images.length) { const p = document.createElement('p'); p.className = '
|
|
18
|
+
if (!images.length) { const p = document.createElement('p'); p.className = 'ps-muted'; p.textContent = search.value ? 'No images match.' : 'No images yet.'; grid.append(p); }
|
|
19
19
|
}
|
|
20
20
|
|
|
21
21
|
function tile(img: Image) {
|
|
22
22
|
const b = document.createElement('button');
|
|
23
|
-
b.type = 'button'; b.className = '
|
|
23
|
+
b.type = 'button'; b.className = 'ps-media__tile'; b.title = img.name; b.setAttribute('role', 'listitem');
|
|
24
24
|
const pic = document.createElement('img'); pic.loading = 'lazy'; pic.alt = ''; pic.src = img.src;
|
|
25
|
-
const name = document.createElement('span'); name.className = '
|
|
25
|
+
const name = document.createElement('span'); name.className = 'ps-ellipsis'; name.textContent = img.name;
|
|
26
26
|
b.append(pic, name);
|
|
27
27
|
b.addEventListener('click', () => details(img));
|
|
28
28
|
return b;
|
|
@@ -38,13 +38,13 @@ async function remove(img: Image, force = false): Promise<boolean> {
|
|
|
38
38
|
}
|
|
39
39
|
|
|
40
40
|
async function details(img: Image) {
|
|
41
|
-
const box = document.createElement('div'); box.className = '
|
|
41
|
+
const box = document.createElement('div'); box.className = 'ps-media__detail';
|
|
42
42
|
const pic = document.createElement('img'); pic.src = img.src; pic.alt = '';
|
|
43
43
|
const info = document.createElement('div');
|
|
44
|
-
const url = Object.assign(document.createElement('input'), { type: 'text', readOnly: true, value: img.src, className: '
|
|
44
|
+
const url = Object.assign(document.createElement('input'), { type: 'text', readOnly: true, value: img.src, className: 'ps-invite__url' });
|
|
45
45
|
url.setAttribute('aria-label', 'Image URL');
|
|
46
|
-
const size = document.createElement('p'); size.className = '
|
|
47
|
-
const usedBox = document.createElement('div'); usedBox.textContent = 'Checking where this is used…'; usedBox.className = '
|
|
46
|
+
const size = document.createElement('p'); size.className = 'ps-muted'; size.textContent = kb(img.size);
|
|
47
|
+
const usedBox = document.createElement('div'); usedBox.textContent = 'Checking where this is used…'; usedBox.className = 'ps-muted';
|
|
48
48
|
info.append(url, size, usedBox); box.append(pic, info);
|
|
49
49
|
const used = fetch(`/api/editor/images?used=${encodeURIComponent(img.src)}`).then((r) => r.json()).then((d) => d.used as { title: string; href: string }[]);
|
|
50
50
|
dialog(img.name, box, [
|
|
@@ -74,7 +74,7 @@ async function upload(files: File[]) {
|
|
|
74
74
|
|
|
75
75
|
let t: ReturnType<typeof setTimeout>;
|
|
76
76
|
search.addEventListener('input', () => { clearTimeout(t); t = setTimeout(load, 200); });
|
|
77
|
-
(document.getElementById('
|
|
77
|
+
(document.getElementById('ps-media-file') as HTMLInputElement).addEventListener('change', (e) => { const i = e.target as HTMLInputElement; upload([...i.files ?? []]); i.value = ''; });
|
|
78
78
|
addEventListener('dragover', (e) => { e.preventDefault(); drop.hidden = false; });
|
|
79
79
|
addEventListener('dragleave', (e) => { if (!e.relatedTarget) drop.hidden = true; });
|
|
80
80
|
addEventListener('drop', (e) => { e.preventDefault(); drop.hidden = true; upload([...e.dataTransfer?.files ?? []].filter((f) => f.type.startsWith('image/'))); });
|
package/src/client/pages.ts
CHANGED
|
@@ -3,7 +3,7 @@ import { publicPath, slugify, slugProblem, uniqueSlug } from '../core/pages';
|
|
|
3
3
|
import { confirmDialog, dialog, toast } from './ui';
|
|
4
4
|
|
|
5
5
|
interface Boot { pages: { slug: string; title: string }[]; reserved: string[]; templates: { id: number; label: string; description?: string }[] }
|
|
6
|
-
const boot = (window as any).
|
|
6
|
+
const boot = (window as any).__PS_PAGES__ as Boot;
|
|
7
7
|
const existing = boot.pages.map((p) => p.slug);
|
|
8
8
|
const titleOnly = (t: string) => t.split(/\s[-–|]\s/)[0];
|
|
9
9
|
|
|
@@ -21,18 +21,18 @@ function opened(data: any) {
|
|
|
21
21
|
function addPage(copyOf?: string) {
|
|
22
22
|
const source = boot.pages.find((p) => p.slug === copyOf);
|
|
23
23
|
const form = document.createElement('div');
|
|
24
|
-
form.className = '
|
|
24
|
+
form.className = 'ps-newpage';
|
|
25
25
|
form.innerHTML = `
|
|
26
|
-
<div class="
|
|
27
|
-
<div class="
|
|
28
|
-
<span class="
|
|
29
|
-
<p class="
|
|
30
|
-
<div class="
|
|
31
|
-
<small class="
|
|
26
|
+
<div class="ps-field"><label>Title <input type="text" name="title" autocomplete="off" /></label></div>
|
|
27
|
+
<div class="ps-field"><label>URL
|
|
28
|
+
<span class="ps-prefixed"><span class="ps-muted">/</span><input type="text" name="slug" autocomplete="off" spellcheck="false" /><span class="ps-muted">/</span></span></label>
|
|
29
|
+
<p class="ps-error" hidden></p></div>
|
|
30
|
+
<div class="ps-field"><label>Start from <select name="from"></select></label></div>
|
|
31
|
+
<small class="ps-muted">New pages start as drafts. Nothing is public until you press Publish.</small>`;
|
|
32
32
|
const title = form.querySelector<HTMLInputElement>('[name=title]')!;
|
|
33
33
|
const slug = form.querySelector<HTMLInputElement>('[name=slug]')!;
|
|
34
34
|
const from = form.querySelector<HTMLSelectElement>('[name=from]')!;
|
|
35
|
-
const error = form.querySelector<HTMLElement>('.
|
|
35
|
+
const error = form.querySelector<HTMLElement>('.ps-error')!;
|
|
36
36
|
const option = (value: string, label: string, parent: HTMLElement = from) => { const o = document.createElement('option'); o.value = value; o.textContent = label; parent.append(o); };
|
|
37
37
|
option('blank', 'Blank page');
|
|
38
38
|
boot.templates.forEach((t) => option(`template:${t.id}`, t.label));
|
|
@@ -73,17 +73,17 @@ async function deletePage(slug: string, row: HTMLElement) {
|
|
|
73
73
|
toast(`Deleted ${titleOnly(page.title)}.`, 'ok');
|
|
74
74
|
}
|
|
75
75
|
|
|
76
|
-
document.getElementById('
|
|
77
|
-
document.getElementById('
|
|
76
|
+
document.getElementById('ps-add-page')!.addEventListener('click', () => addPage());
|
|
77
|
+
document.getElementById('ps-pagelist')!.addEventListener('click', (e) => {
|
|
78
78
|
const b = (e.target as HTMLElement).closest<HTMLElement>('[data-duplicate], [data-delete]');
|
|
79
79
|
if (!b) return;
|
|
80
80
|
if (b.dataset.duplicate) addPage(b.dataset.duplicate);
|
|
81
81
|
else deletePage(b.dataset.delete!, b.closest('li')!);
|
|
82
82
|
});
|
|
83
|
-
const search = document.getElementById('
|
|
83
|
+
const search = document.getElementById('ps-page-search') as HTMLInputElement;
|
|
84
84
|
search.addEventListener('input', () => {
|
|
85
85
|
const q = search.value.trim().toLowerCase();
|
|
86
86
|
let shown = 0;
|
|
87
|
-
document.querySelectorAll<HTMLElement>('#
|
|
88
|
-
document.getElementById('
|
|
87
|
+
document.querySelectorAll<HTMLElement>('#ps-pagelist > li').forEach((li) => { const on = li.dataset.search!.includes(q); li.hidden = !on; if (on) shown++; });
|
|
88
|
+
document.getElementById('ps-no-match')!.hidden = shown > 0;
|
|
89
89
|
});
|