verso-cms 0.0.0-stage → 0.1.3
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/LICENSE +21 -0
- package/README.md +168 -2
- package/bin/verso.js +16 -0
- package/editor/door.js +139 -0
- package/editor/editor.js +1880 -0
- package/editor/elevate.css +2158 -0
- package/editor/ext-attrs.js +87 -0
- package/editor/ext-blocks.js +422 -0
- package/editor/ext-builder.js +819 -0
- package/editor/ext-channels.js +574 -0
- package/editor/ext-components.js +160 -0
- package/editor/ext-history.js +242 -0
- package/editor/ext-palette.js +307 -0
- package/editor/ext-people.js +345 -0
- package/editor/ext-repeaters.js +143 -0
- package/editor/ext-screens.js +94 -0
- package/editor/ext-site-settings.js +318 -0
- package/editor/ext-site-view.js +632 -0
- package/editor/ext-tokens.js +1195 -0
- package/editor/new-page.js +252 -0
- package/editor/rich.js +23 -0
- package/package.json +69 -4
- package/src/blocks.js +269 -0
- package/src/box.js +339 -0
- package/src/build.js +210 -0
- package/src/cli.js +161 -0
- package/src/color.js +137 -0
- package/src/components.js +223 -0
- package/src/elevate.js +74 -0
- package/src/errors.js +46 -0
- package/src/extensions/README.md +70 -0
- package/src/extensions/blocks.js +294 -0
- package/src/extensions/builder.js +734 -0
- package/src/extensions/channels.js +341 -0
- package/src/extensions/components.js +141 -0
- package/src/extensions/history.js +169 -0
- package/src/extensions/palette.js +31 -0
- package/src/extensions/people.js +113 -0
- package/src/extensions/site-settings.js +251 -0
- package/src/extensions/site-view.js +381 -0
- package/src/extensions/tags.js +15 -0
- package/src/extensions/tokens.js +587 -0
- package/src/fonts.js +139 -0
- package/src/git.js +419 -0
- package/src/html-edit.js +942 -0
- package/src/images.js +116 -0
- package/src/people.js +286 -0
- package/src/rich.js +124 -0
- package/src/scaffold.js +185 -0
- package/src/screens.js +65 -0
- package/src/server.js +693 -0
- package/src/site.js +618 -0
- package/src/template.js +915 -0
- package/src/video.js +29 -0
- package/starter/Dockerfile +20 -0
- package/starter/README.md +49 -0
- package/starter/blocks/call-to-action.html +6 -0
- package/starter/blocks/features.html +15 -0
- package/starter/blocks/hero.html +8 -0
- package/starter/blocks/image-and-text.html +8 -0
- package/starter/blocks/latest-posts.html +20 -0
- package/starter/blocks/post-index.html +30 -0
- package/starter/blocks/quote.html +9 -0
- package/starter/blocks/site-footer.html +8 -0
- package/starter/blocks/site-nav.html +8 -0
- package/starter/blocks/tag-list.html +10 -0
- package/starter/blocks/tagged-posts.html +19 -0
- package/starter/blocks/team.html +15 -0
- package/starter/blocks/text.html +4 -0
- package/starter/content/404/page.json +21 -0
- package/starter/content/about/page.json +65 -0
- package/starter/content/journal/designing-for-the-morning-shift/body.html +22 -0
- package/starter/content/journal/designing-for-the-morning-shift/checklist.jpg +0 -0
- package/starter/content/journal/designing-for-the-morning-shift/cover.jpg +0 -0
- package/starter/content/journal/designing-for-the-morning-shift/page.json +17 -0
- package/starter/content/journal/page.json +19 -0
- package/starter/content/journal/the-first-week/body.html +17 -0
- package/starter/content/journal/the-first-week/cover.jpg +0 -0
- package/starter/content/journal/the-first-week/page.json +17 -0
- package/starter/content/journal/the-first-week/wall-of-cards.jpg +0 -0
- package/starter/content/page.json +94 -0
- package/starter/content/site.json +88 -0
- package/starter/content/studio-table.jpg +0 -0
- package/starter/content/topics/page.json +27 -0
- package/starter/dockerignore +5 -0
- package/starter/elevate/config/design.ts +30 -0
- package/starter/elevate/config/elevate.ts +16 -0
- package/starter/elevate/config/syntax.ts +6 -0
- package/starter/elevate/design/site.ts +9 -0
- package/starter/elevate/design/tokens.json +20 -0
- package/starter/elevate/extend/fonts.css +1 -0
- package/starter/gitignore +6 -0
- package/starter/netlify.toml +5 -0
- package/starter/parts/.gitkeep +0 -0
- package/starter/public/favicon.svg +1 -0
- package/starter/templates/page.html +20 -0
- package/starter/templates/page.layout.json +23 -0
- package/starter/templates/post.html +65 -0
- package/starter/verso.defaults.json +33 -0
- package/starter-blank/blocks/site-footer.html +3 -0
- package/starter-blank/blocks/site-nav.html +8 -0
- package/starter-blank/blocks/text.html +4 -0
- package/starter-blank/content/404/page.json +18 -0
- package/starter-blank/content/page.json +18 -0
- package/starter-blank/content/site.json +36 -0
- package/starter-blank/elevate/design/tokens.json +10 -0
- package/starter-blank/templates/page.html +17 -0
- package/starter-blank/verso.defaults.json +26 -0
package/editor/editor.js
ADDED
|
@@ -0,0 +1,1880 @@
|
|
|
1
|
+
// The editing layer. It runs on top of the real page: click a field to edit
|
|
2
|
+
// it, and every change is saved as you go. The interface lives in a shadow
|
|
3
|
+
// root, so the site's styles can't reach it and its styles can't reach the
|
|
4
|
+
// site. Its classes are Elevate classes, compiled into editor/elevate.css.
|
|
5
|
+
|
|
6
|
+
// Marks a class string for Elevate's scanner (see elevate/config/elevate.ts).
|
|
7
|
+
const ui = (classes) => classes;
|
|
8
|
+
|
|
9
|
+
const data = JSON.parse(document.getElementById('verso-data')?.textContent || '{}');
|
|
10
|
+
|
|
11
|
+
// On a served site (verso serve) several people can be editing at once.
|
|
12
|
+
// Each tab gives itself a name, so the server can tell everyone else what
|
|
13
|
+
// this one changed, and a request that finds itself signed out goes back
|
|
14
|
+
// to the sign-in page instead of failing quietly.
|
|
15
|
+
const TAB = Math.random().toString(36).slice(2, 10);
|
|
16
|
+
if (data.box) {
|
|
17
|
+
const plain = window.fetch.bind(window);
|
|
18
|
+
window.fetch = async (input, init = {}) => {
|
|
19
|
+
const to = typeof input === 'string' ? input : input?.url || '';
|
|
20
|
+
if (!String(to).startsWith('/__verso/')) return plain(input, init);
|
|
21
|
+
const headers = new Headers(init.headers || {});
|
|
22
|
+
headers.set('X-Verso-Tab', TAB);
|
|
23
|
+
const res = await plain(input, { ...init, headers });
|
|
24
|
+
if (res.status === 401) location.href = `/edit?to=${encodeURIComponent(location.pathname)}`;
|
|
25
|
+
return res;
|
|
26
|
+
};
|
|
27
|
+
}
|
|
28
|
+
// The platform's shortcut key: ⌘ on a Mac, Ctrl elsewhere.
|
|
29
|
+
let summary = null; // what Publish would do, from the server
|
|
30
|
+
let lastStatus = null;
|
|
31
|
+
const MOD = /Mac|iPhone|iPad/.test(navigator.platform || navigator.userAgent) ? '⌘' : 'Ctrl+';
|
|
32
|
+
const fieldsByName = new Map((data.fields || []).map((f) => [f.name, f]));
|
|
33
|
+
const values = { ...(data.values || {}) };
|
|
34
|
+
|
|
35
|
+
// ════ Shadow root ════
|
|
36
|
+
|
|
37
|
+
const host = document.createElement('verso-ui');
|
|
38
|
+
document.documentElement.appendChild(host);
|
|
39
|
+
const root = host.attachShadow({ mode: 'open' });
|
|
40
|
+
root.innerHTML = `
|
|
41
|
+
<style>:host{all:initial;position:relative;z-index:2147483600}</style>
|
|
42
|
+
<link rel="stylesheet" href="/__verso/elevate.css">
|
|
43
|
+
<div class="${ui("font:ui:small text:ink -verso")}">
|
|
44
|
+
<div id="marks" class="${ui("fixed top:0 left:0 w:full h:full events:none z:1")}"></div>
|
|
45
|
+
|
|
46
|
+
<div id="toolbar" class="${ui("fixed top:0 left:0 row:y-center gap:d0 max-w:toolbar overflow-x:auto pd:d1 bg-color:ink text:paper bd:round-d4 shadow:float z:5 select:none")}" style="display:none" role="toolbar" aria-label="Formatting"></div>
|
|
47
|
+
|
|
48
|
+
<div id="image-pop" class="${ui("fixed top:0 left:0 w:menu col gap:d3 pd:d4 bg-color:paper bd:round-d4 shadow:float bd:width-px:solid:line z:5")}" style="display:none"></div>
|
|
49
|
+
<input id="file-input" type="file" accept="image/jpeg,image/png,image/gif,image/webp,image/avif" style="display:none">
|
|
50
|
+
|
|
51
|
+
<div id="problems" class="${ui("fixed top:d4 right:d4 w:card bg-color:paper bd:round-d4 shadow:float bd:width-px:solid:line z:3")}" style="display:none"></div>
|
|
52
|
+
|
|
53
|
+
<aside id="settings" class="${ui("fixed top:d3 right:d3 bottom:c3 w:sheet col bg-color:paper bd:round-d5 shadow:float bd:width-px:solid:line z:4 overflow-y:auto")}" style="display:none"></aside>
|
|
54
|
+
|
|
55
|
+
<div id="toast" class="${ui("fixed bottom:c2 left:half translate:(-50%_0) z:9")}" style="display:none"></div>
|
|
56
|
+
|
|
57
|
+
<div id="menu" class="${ui("fixed bottom:c2 left:half translate:(-50%_0) w:menu col pd:d2 bg-color:ink bd:round-d5 shadow:float z:5")}" style="display:none"></div>
|
|
58
|
+
|
|
59
|
+
<div id="bar" class="${ui("fixed bottom:d4 left:half translate:(-50%_0) row:y-center gap:d1 pd:d1 bg-color:ink bd:round-pill shadow:float z:5 select:none")}">
|
|
60
|
+
<a href="/" class="${ui("hidden w:d10 h:d10 bd:round-full bg-color:proof text:paper font:bold child:no-shrink /xs/ row:x-center:y-center")}" data-tip="Home" aria-label="Verso: go to the home page">${icon('mark')}</a>
|
|
61
|
+
<button id="page" class="${ui("bg-color:transparent bd:width-0 cursor:pointer row:y-center gap:d1 h:d10 pd-x:d3 bd:round-pill text:paper font:medium @hover:[bg-color:ink-2] @focus-visible:[outline:d0:solid:proof] transition:fast")}" aria-haspopup="menu">
|
|
62
|
+
<span id="page-label" class="${ui("max-w:c3 overflow:hidden text-overflow:ellipsis format:no-wrap /xs/ max-w:c10")}"></span>${icon('chevron')}
|
|
63
|
+
</button>
|
|
64
|
+
<span class="${ui("w:px h:d6 bg-color:ink-3")}"></span>
|
|
65
|
+
<span id="status" class="${ui("row:y-center gap:d2 h:d10 pd-x:d3 text:mist format:no-wrap")}" role="status" aria-live="polite"></span>
|
|
66
|
+
<button id="undo" class="${ui("hidden bg-color:transparent bd:width-0 cursor:default w:d9 h:d10 bd:round-full text:ink-3 transition:fast /xs/ row:x-center:y-center")}" aria-label="Undo" aria-disabled="true">${icon('undo')}</button>
|
|
67
|
+
<button id="redo" class="${ui("hidden bg-color:transparent bd:width-0 cursor:default w:d9 h:d10 bd:round-full text:ink-3 transition:fast /xs/ row:x-center:y-center")}" aria-label="Redo" aria-disabled="true">${icon('redo')}</button>
|
|
68
|
+
<span id="grp-page" class="${ui("row:y-center gap:d0")}" role="group" aria-label="This page">
|
|
69
|
+
<button id="open-settings" data-tip="Page settings" class="${ui("bg-color:transparent bd:width-0 cursor:pointer row:x-center:y-center w:d10 h:d10 bd:round-full text:paper @hover:[bg-color:ink-2] @focus-visible:[outline:d0:solid:proof] transition:fast /2xl/ w:auto pd-x:d3 gap:d2")}" aria-label="Page settings">${icon('sliders')}<span class="${ui("hidden format:no-wrap /2xl/ inline")}" aria-hidden="true">Page</span></button>
|
|
70
|
+
</span>
|
|
71
|
+
<span id="grp-add" class="${ui("hidden row:y-center gap:d0 /md/ row")}" role="group" aria-label="Add"></span>
|
|
72
|
+
<span id="grp-site" class="${ui("hidden row:y-center gap:d0 /md/ row")}" role="group" aria-label="Site"></span>
|
|
73
|
+
<button id="publish" class="${ui("bd:width-0 cursor:pointer row:y-center gap:d2 h:d10 pd-x:d4 bd:round-pill bg-color:proof text:paper font:semibold @hover:[bg-color:proof-2] @focus-visible:[outline:d0:solid:paper] transition:fast format:no-wrap /xs/ pd-x:d5")}">Publish</button>
|
|
74
|
+
</div>
|
|
75
|
+
<div id="publish-tip" class="${ui("fixed bottom:c2 left:half translate:(-50%_0) max-w:tip pd:d3:d4 bg-color:ink text:paper bd:round-d4 shadow:float z:5 events:none")}" style="display:none"></div>
|
|
76
|
+
<div id="bar-tip" class="${ui("fixed top:0 left:0 pd:d1:d2 bg-color:ink text:paper bd:round-d2 font:tiny:medium shadow:float z:6 events:none format:no-wrap")}" style="display:none" role="tooltip"></div>
|
|
77
|
+
<div id="changes" class="${ui("fixed bottom:c2 left:half translate:(-50%_0) w:menu col gap:d2 pd:d4 bg-color:paper text:ink bd:round-d4 shadow:float bd:width-px:solid:line z:5")}" style="display:none" aria-label="Changes waiting to publish"></div>
|
|
78
|
+
<div id="first-run" class="${ui("fixed bottom:c2 left:half translate:(-50%_0) row:y-center gap:d3 w:toast pd:d3:d4 bg-color:proof text:paper bd:round-d4 shadow:float z:4")}" style="display:none" role="note"></div>
|
|
79
|
+
</div>`;
|
|
80
|
+
|
|
81
|
+
const $ = (id) => root.getElementById(id);
|
|
82
|
+
// Inside the screen-size preview (a frame of this same page), editing works
|
|
83
|
+
// as usual; the bar and hints belong to the page outside.
|
|
84
|
+
const FRAMED = window.parent !== window && new URLSearchParams(location.search).has('verso-frame');
|
|
85
|
+
if (FRAMED) ['bar', 'first-run', 'publish-tip'].forEach((id) => { const el = root.getElementById(id); if (el) el.style.setProperty('display', 'none', 'important'); });
|
|
86
|
+
const show = (el, display = '') => { el.style.display = display; };
|
|
87
|
+
const hide = (el) => { el.style.display = 'none'; };
|
|
88
|
+
const isShown = (el) => el.style.display !== 'none';
|
|
89
|
+
const esc = (s) => String(s ?? '').replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
|
|
90
|
+
const humanize = (name) => {
|
|
91
|
+
const words = String(name).replace(/[-_]+/g, ' ').trim().toLowerCase();
|
|
92
|
+
return words.charAt(0).toUpperCase() + words.slice(1);
|
|
93
|
+
};
|
|
94
|
+
|
|
95
|
+
function icon(name) {
|
|
96
|
+
const s = 'fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"';
|
|
97
|
+
const paths = {
|
|
98
|
+
mark: '<path d="M5 6.5 10 17l5-10.5" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round"/>',
|
|
99
|
+
chevron: `<path d="m7 10 5 5 5-5" ${s}/>`,
|
|
100
|
+
sliders: '<path d="M4 7h10M18 7h2M4 17h4M12 17h8" stroke="currentColor" stroke-width="2" stroke-linecap="round"/><circle cx="16" cy="7" r="2" fill="none" stroke="currentColor" stroke-width="2"/><circle cx="10" cy="17" r="2" fill="none" stroke="currentColor" stroke-width="2"/>',
|
|
101
|
+
close: '<path d="m7 7 10 10M17 7 7 17" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>',
|
|
102
|
+
check: '<path d="m5 12.5 4.5 4.5L19 7.5" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round"/>',
|
|
103
|
+
alert: '<path d="M12 8v5M12 16.5v.01" stroke="currentColor" stroke-width="2.4" stroke-linecap="round"/><circle cx="12" cy="12" r="9" fill="none" stroke="currentColor" stroke-width="2"/>',
|
|
104
|
+
bold: `<path d="M7 5h6a3.5 3.5 0 0 1 0 7H7zM7 12h7a3.5 3.5 0 0 1 0 7H7z" ${s} stroke-width="2.4"/>`,
|
|
105
|
+
italic: `<path d="M14 5h-4M14 19h-4M14.5 5l-5 14" ${s}/>`,
|
|
106
|
+
link: `<path d="M10 14a4 4 0 0 0 5.7 0l3-3a4 4 0 0 0-5.7-5.7l-1 1M14 10a4 4 0 0 0-5.7 0l-3 3a4 4 0 0 0 5.7 5.7l1-1" ${s}/>`,
|
|
107
|
+
ul: `<path d="M10 6h10M10 12h10M10 18h10" ${s}/><circle cx="5" cy="6" r="1.3" fill="currentColor"/><circle cx="5" cy="12" r="1.3" fill="currentColor"/><circle cx="5" cy="18" r="1.3" fill="currentColor"/>`,
|
|
108
|
+
ol: `<path d="M10 6h10M10 12h10M10 18h10M4 5l1.5-1v5M3.8 13.2a1.6 1.6 0 1 1 2.6 1.3L4 17h3" ${s} stroke-width="1.7"/>`,
|
|
109
|
+
quote: '<path d="M7 7h4v4c0 3-1.5 5-4 6M14 7h4v4c0 3-1.5 5-4 6" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>',
|
|
110
|
+
callout: `<rect x="4" y="5" width="16" height="14" rx="3" ${s}/><path d="M8 10h8M8 14h5" ${s}/>`,
|
|
111
|
+
image: `<rect x="4" y="5" width="16" height="14" rx="2.5" ${s}/><path d="m5 17 5-5 3.5 3.5L16 13l3 3" ${s}/><circle cx="15.5" cy="9" r="1.4" fill="currentColor"/>`,
|
|
112
|
+
table: `<rect x="4" y="5" width="16" height="14" rx="2" ${s}/><path d="M4 10h16M4 14.5h16M10 5v14" ${s}/>`,
|
|
113
|
+
video: `<rect x="3.5" y="5.5" width="17" height="13" rx="3" ${s}/><path d="M10.5 9.5v5l4.2-2.5z" fill="currentColor"/>`,
|
|
114
|
+
code: `<path d="m9 8-4 4 4 4M15 8l4 4-4 4" ${s}/>`,
|
|
115
|
+
codeBlock: `<rect x="3.5" y="4.5" width="17" height="15" rx="2.5" ${s}/><path d="m9.5 10-2 2 2 2M14.5 10l2 2-2 2" ${s}/>`,
|
|
116
|
+
undo: `<path d="M9 7 5 11l4 4" ${s}/><path d="M5 11h9a5 5 0 0 1 0 10h-2" ${s}/>`,
|
|
117
|
+
redo: `<path d="m15 7 4 4-4 4" ${s}/><path d="M19 11h-9a5 5 0 0 0 0 10h2" ${s}/>`,
|
|
118
|
+
trash: `<path d="M5 7h14M10 7V5h4v2M7 7l1 12h8l1-12" ${s}/>`,
|
|
119
|
+
plus: `<path d="M12 5v14M5 12h14" ${s}/>`,
|
|
120
|
+
upload: `<path d="M12 16V5M7.5 9.5 12 5l4.5 4.5M5 19h14" ${s}/>`,
|
|
121
|
+
};
|
|
122
|
+
return `<svg width="18" height="18" viewBox="0 0 24 24" aria-hidden="true">${paths[name] || ''}</svg>`;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
$('page-label').textContent = data.label || 'Page';
|
|
126
|
+
setStatus('saved', 'Saved');
|
|
127
|
+
|
|
128
|
+
// ════ Saving ════
|
|
129
|
+
// Changes collect for a moment, then go to disk in one request. There is no
|
|
130
|
+
// save button: the status in the bar says when it's done.
|
|
131
|
+
|
|
132
|
+
let pending = null;
|
|
133
|
+
let saveTimer = null;
|
|
134
|
+
let saving = false;
|
|
135
|
+
let failedAt = 0;
|
|
136
|
+
let uploading = 0;
|
|
137
|
+
let reloadAfterSave = false;
|
|
138
|
+
|
|
139
|
+
function setStatus(state, text) {
|
|
140
|
+
const status = $('status');
|
|
141
|
+
if (state === 'saving') status.className = ui("row:y-center gap:d2 h:d10 pd-x:d1 text:mist format:no-wrap /xs/ pd-x:d3");
|
|
142
|
+
else if (state === 'error') status.className = ui("row:y-center gap:d2 h:d10 pd-x:d1 text:proof format:no-wrap /xs/ pd-x:d3");
|
|
143
|
+
else status.className = ui("row:y-center gap:d2 h:d10 pd-x:d1 text:mist format:no-wrap /xs/ pd-x:d3");
|
|
144
|
+
const dot = state === 'saving'
|
|
145
|
+
? `<span class="${ui("w:d2 h:d2 bd:round-full bg-color:mist animation:(verso-pulse_1s_ease-in-out_infinite)")}"></span>`
|
|
146
|
+
: state === 'error'
|
|
147
|
+
? `<span class="${ui("w:d2 h:d2 bd:round-full bg-color:proof")}"></span>`
|
|
148
|
+
: `<span class="${ui("w:d2 h:d2 bd:round-full bg-color:ok")}"></span>`;
|
|
149
|
+
// When the Publish button already says everything is saved or published,
|
|
150
|
+
// the status is just its green dot.
|
|
151
|
+
const quiet = state === 'saved' && summary && !summary.pending;
|
|
152
|
+
// On a phone, "Saved" is the green dot alone so the bar fits; anything
|
|
153
|
+
// else (Saving…, Not saved) is spelled out.
|
|
154
|
+
status.innerHTML = `${dot}<span class="${quiet ? ui("hidden") : state === 'saved' ? ui("hidden /xs/ inline") : ''}">${esc(text)}</span>`;
|
|
155
|
+
lastStatus = [state, text];
|
|
156
|
+
status.setAttribute('aria-label', text);
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
function queue(change) {
|
|
160
|
+
pending = pending || {};
|
|
161
|
+
if (change.fields) pending.fields = { ...(pending.fields || {}), ...change.fields };
|
|
162
|
+
if ('title' in change) pending.title = change.title;
|
|
163
|
+
if ('description' in change) pending.description = change.description;
|
|
164
|
+
if ('date' in change) pending.date = change.date;
|
|
165
|
+
if ('tags' in change) pending.tags = change.tags;
|
|
166
|
+
if ('tagsOf' in change) pending.tagsOf = change.tagsOf;
|
|
167
|
+
if (change.remove) pending.remove = [...(pending.remove || []), ...change.remove];
|
|
168
|
+
setStatus('saving', 'Saving…');
|
|
169
|
+
clearTimeout(saveTimer);
|
|
170
|
+
saveTimer = setTimeout(flush, 450);
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
async function flush({ keepalive = false } = {}) {
|
|
174
|
+
clearTimeout(saveTimer);
|
|
175
|
+
saveTimer = null;
|
|
176
|
+
if (!pending || saving) return;
|
|
177
|
+
const body = { url: data.url, ...pending };
|
|
178
|
+
pending = null;
|
|
179
|
+
saving = true;
|
|
180
|
+
try {
|
|
181
|
+
const res = await fetch('/__verso/save', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body), keepalive });
|
|
182
|
+
const out = await res.json().catch(() => ({}));
|
|
183
|
+
if (!res.ok || !out.ok) {
|
|
184
|
+
if (res.status === 400) {
|
|
185
|
+
// The change was refused, not lost in transit: say why, don't retry.
|
|
186
|
+
setStatus('error', 'Not saved');
|
|
187
|
+
toast(out.message || 'That change couldn\'t be saved.', 'error');
|
|
188
|
+
} else throw new Error(out.message || 'Save failed');
|
|
189
|
+
} else {
|
|
190
|
+
failedAt = 0;
|
|
191
|
+
if (FRAMED) window.parent.postMessage({ verso: 'saved' }, location.origin);
|
|
192
|
+
setStatus(uploading ? 'saving' : 'saved', uploading ? 'Uploading…' : 'Saved');
|
|
193
|
+
refreshStatusSoon();
|
|
194
|
+
}
|
|
195
|
+
} catch {
|
|
196
|
+
// Put the change back and try again shortly.
|
|
197
|
+
pending = { ...body, ...(pending || {}), fields: { ...(body.fields || {}), ...((pending && pending.fields) || {}) } };
|
|
198
|
+
delete pending.url;
|
|
199
|
+
failedAt = failedAt || Date.now();
|
|
200
|
+
setStatus('error', Date.now() - failedAt > 8000 ? 'Can\'t reach Verso' : 'Retrying…');
|
|
201
|
+
saveTimer = setTimeout(flush, 2000);
|
|
202
|
+
} finally {
|
|
203
|
+
saving = false;
|
|
204
|
+
if (pending && !saveTimer) saveTimer = setTimeout(flush, 450);
|
|
205
|
+
if (!pending && reloadAfterSave) {
|
|
206
|
+
reloadAfterSave = false;
|
|
207
|
+
reloadWaiting = true;
|
|
208
|
+
}
|
|
209
|
+
if (reloadWaiting) maybeReload();
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
window.addEventListener('beforeunload', (e) => {
|
|
214
|
+
if (pending) {
|
|
215
|
+
flush({ keepalive: true });
|
|
216
|
+
e.preventDefault();
|
|
217
|
+
}
|
|
218
|
+
});
|
|
219
|
+
|
|
220
|
+
// ════ Uploads ════
|
|
221
|
+
// Images go into the page's own folder. The server checks what the file
|
|
222
|
+
// really is and answers with its file name and size.
|
|
223
|
+
|
|
224
|
+
async function uploadFile(file) {
|
|
225
|
+
uploading += 1;
|
|
226
|
+
setStatus('saving', 'Uploading…');
|
|
227
|
+
try {
|
|
228
|
+
const res = await fetch(`/__verso/upload?url=${encodeURIComponent(data.url)}&name=${encodeURIComponent(file.name || 'image')}`, {
|
|
229
|
+
method: 'POST',
|
|
230
|
+
headers: { 'Content-Type': 'application/octet-stream' },
|
|
231
|
+
body: file,
|
|
232
|
+
});
|
|
233
|
+
const out = await res.json().catch(() => ({}));
|
|
234
|
+
if (!res.ok || !out.ok) {
|
|
235
|
+
toast(out.message || 'That image couldn\'t be uploaded.', 'error');
|
|
236
|
+
return null;
|
|
237
|
+
}
|
|
238
|
+
if (out.file && !(data.images || []).includes(out.file)) (data.images = data.images || []).push(out.file);
|
|
239
|
+
return out;
|
|
240
|
+
} catch {
|
|
241
|
+
toast('Verso isn\'t running, so the image wasn\'t uploaded. Start it again with "npm run dev".', 'error');
|
|
242
|
+
return null;
|
|
243
|
+
} finally {
|
|
244
|
+
uploading -= 1;
|
|
245
|
+
if (!uploading) setStatus(pending ? 'saving' : 'saved', pending ? 'Saving…' : 'Saved');
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
const imageFile = (list) => [...(list || [])].find((f) => /^image\/(jpeg|png|gif|webp|avif)$/.test(f.type));
|
|
250
|
+
const imageUrl = (file) => (file ? `${data.url}${encodeURIComponent(file)}` : '');
|
|
251
|
+
|
|
252
|
+
// Opens the hidden file picker and resolves with the chosen image, or null.
|
|
253
|
+
function pickImage() {
|
|
254
|
+
return new Promise((resolve) => {
|
|
255
|
+
const input = $('file-input');
|
|
256
|
+
input.value = '';
|
|
257
|
+
const done = () => {
|
|
258
|
+
input.removeEventListener('change', done);
|
|
259
|
+
resolve(imageFile(input.files) || null);
|
|
260
|
+
};
|
|
261
|
+
input.addEventListener('change', done);
|
|
262
|
+
input.click();
|
|
263
|
+
});
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
// ════ History: undo and redo across the page ════
|
|
267
|
+
// Each finished change is one step: a text field you leave, a rich text field
|
|
268
|
+
// you leave, an image set or removed, a setting changed. Inside a field, the
|
|
269
|
+
// field's own undo applies.
|
|
270
|
+
|
|
271
|
+
const past = [];
|
|
272
|
+
const future = [];
|
|
273
|
+
const same = (a, b) => JSON.stringify(a ?? null) === JSON.stringify(b ?? null);
|
|
274
|
+
|
|
275
|
+
function record(action) {
|
|
276
|
+
if (same(action.before, action.after)) return;
|
|
277
|
+
past.push(action);
|
|
278
|
+
if (past.length > 200) past.shift();
|
|
279
|
+
future.length = 0;
|
|
280
|
+
updateHistoryButtons();
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
function updateHistoryButtons() {
|
|
284
|
+
const set = (btn, on) => {
|
|
285
|
+
btn.className = on
|
|
286
|
+
? ui("hidden bg-color:transparent bd:width-0 cursor:pointer w:d9 h:d10 bd:round-full text:paper @hover:[bg-color:ink-2] @focus-visible:[outline:d0:solid:proof] transition:fast /xs/ row:x-center:y-center")
|
|
287
|
+
: ui("hidden bg-color:transparent bd:width-0 cursor:default w:d9 h:d10 bd:round-full text:ink-3 transition:fast /xs/ row:x-center:y-center");
|
|
288
|
+
btn.setAttribute('aria-disabled', on ? 'false' : 'true');
|
|
289
|
+
};
|
|
290
|
+
set($('undo'), past.length > 0);
|
|
291
|
+
set($('redo'), future.length > 0);
|
|
292
|
+
const last = past[past.length - 1];
|
|
293
|
+
const next = future[future.length - 1];
|
|
294
|
+
$('undo').dataset.tip = last ? `Undo ${last.label} (${MOD}Z)` : 'Nothing to undo';
|
|
295
|
+
$('redo').dataset.tip = next ? `Redo ${next.label} (${MOD}${MOD === '⌘' ? '⇧Z' : 'Y'})` : 'Nothing to redo';
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
function apply(action, value) {
|
|
299
|
+
const { type, name } = action;
|
|
300
|
+
if (type === 'text') setText(name, value);
|
|
301
|
+
else if (type === 'rich') {
|
|
302
|
+
const entry = richByName(name);
|
|
303
|
+
if (entry) {
|
|
304
|
+
entry.api.setHTML(value || '');
|
|
305
|
+
values[name] = value || '';
|
|
306
|
+
entry.baseline = values[name];
|
|
307
|
+
queue({ fields: { [name]: values[name] } });
|
|
308
|
+
}
|
|
309
|
+
} else if (type === 'image') setImage(name, value, { record: false });
|
|
310
|
+
else if (type === 'setting') {
|
|
311
|
+
data[name] = value;
|
|
312
|
+
queue({ [name]: value });
|
|
313
|
+
if (isShown($('settings'))) openSettings();
|
|
314
|
+
}
|
|
315
|
+
const el = document.querySelector(`[data-verso-field="${CSS.escape(name)}"],[data-verso-rich="${CSS.escape(name)}"],[data-verso-image="${CSS.escape(name)}"]`);
|
|
316
|
+
if (el) {
|
|
317
|
+
const r = el.getBoundingClientRect();
|
|
318
|
+
if (r.bottom < 0 || r.top > innerHeight) el.scrollIntoView({ block: 'center', behavior: 'smooth' });
|
|
319
|
+
flashEl = el;
|
|
320
|
+
setTimeout(() => { if (flashEl === el) { flashEl = null; redraw(); } }, 900);
|
|
321
|
+
}
|
|
322
|
+
redraw();
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
function undoStep() {
|
|
326
|
+
const action = past.pop();
|
|
327
|
+
if (!action) return;
|
|
328
|
+
apply(action, action.before);
|
|
329
|
+
future.push(action);
|
|
330
|
+
updateHistoryButtons();
|
|
331
|
+
setStatusNote(`Undid ${action.label}`);
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
function redoStep() {
|
|
335
|
+
const action = future.pop();
|
|
336
|
+
if (!action) return;
|
|
337
|
+
apply(action, action.after);
|
|
338
|
+
past.push(action);
|
|
339
|
+
updateHistoryButtons();
|
|
340
|
+
setStatusNote(`Redid ${action.label}`);
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
let noteTimer = 0;
|
|
344
|
+
function setStatusNote(text) {
|
|
345
|
+
setStatus('saving', text);
|
|
346
|
+
clearTimeout(noteTimer);
|
|
347
|
+
noteTimer = setTimeout(() => { if (!pending && !saving && !uploading) setStatus('saved', 'Saved'); }, 1400);
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
$('undo').addEventListener('click', undoStep);
|
|
351
|
+
$('redo').addEventListener('click', redoStep);
|
|
352
|
+
updateHistoryButtons();
|
|
353
|
+
|
|
354
|
+
const typingInField = () => {
|
|
355
|
+
if (editEl) return true;
|
|
356
|
+
if (activeRich && activeRich.api.state().focused) return true;
|
|
357
|
+
const a = document.activeElement;
|
|
358
|
+
if (a && (a.tagName === 'INPUT' || a.tagName === 'TEXTAREA' || a.isContentEditable)) return true;
|
|
359
|
+
const s = root.activeElement;
|
|
360
|
+
return !!(s && (s.tagName === 'INPUT' || s.tagName === 'TEXTAREA'));
|
|
361
|
+
};
|
|
362
|
+
|
|
363
|
+
document.addEventListener('keydown', (e) => {
|
|
364
|
+
const mod = e.metaKey || e.ctrlKey;
|
|
365
|
+
if (!mod || typingInField()) return;
|
|
366
|
+
const key = e.key.toLowerCase();
|
|
367
|
+
if (key === 'z' && !e.shiftKey) { e.preventDefault(); undoStep(); }
|
|
368
|
+
else if ((key === 'z' && e.shiftKey) || (key === 'y' && e.ctrlKey)) { e.preventDefault(); redoStep(); }
|
|
369
|
+
}, true);
|
|
370
|
+
|
|
371
|
+
// ════ Text fields ════
|
|
372
|
+
|
|
373
|
+
const fieldEls = () => [...document.querySelectorAll('[data-verso-field]')];
|
|
374
|
+
const anyField = '[data-verso-field],[data-verso-rich],[data-verso-image]';
|
|
375
|
+
const nameOf = (el) => el?.dataset.versoField || el?.dataset.versoRich || el?.dataset.versoImage || '';
|
|
376
|
+
const labelOf = (name) => fieldsByName.get(name)?.label || humanize(name);
|
|
377
|
+
const plaintextOnly = (() => {
|
|
378
|
+
const probe = document.createElement('div');
|
|
379
|
+
try {
|
|
380
|
+
probe.contentEditable = 'plaintext-only';
|
|
381
|
+
return probe.contentEditable === 'plaintext-only';
|
|
382
|
+
} catch {
|
|
383
|
+
return false;
|
|
384
|
+
}
|
|
385
|
+
})();
|
|
386
|
+
|
|
387
|
+
let hoverEl = null;
|
|
388
|
+
let editEl = null;
|
|
389
|
+
let editBaseline = '';
|
|
390
|
+
let flashEl = null;
|
|
391
|
+
|
|
392
|
+
const isEmpty = (el) => el.hasAttribute('data-verso-empty');
|
|
393
|
+
const readText = (el) => el.textContent.replace(/ /g, ' ').replace(/\s*\n\s*/g, ' ');
|
|
394
|
+
|
|
395
|
+
function showPlaceholder(el) {
|
|
396
|
+
el.setAttribute('data-verso-empty', '');
|
|
397
|
+
el.textContent = labelOf(el.dataset.versoField);
|
|
398
|
+
el.style.opacity = '0.4';
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
function clearPlaceholder(el) {
|
|
402
|
+
el.removeAttribute('data-verso-empty');
|
|
403
|
+
el.textContent = '';
|
|
404
|
+
el.style.opacity = '';
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
fieldEls().forEach((el) => {
|
|
408
|
+
if (isEmpty(el)) el.style.opacity = '0.4';
|
|
409
|
+
});
|
|
410
|
+
|
|
411
|
+
// Shows a text value everywhere the field appears on the page, and saves it.
|
|
412
|
+
function setText(name, value, { except = null } = {}) {
|
|
413
|
+
values[name] = value;
|
|
414
|
+
fieldEls().forEach((el) => {
|
|
415
|
+
if (el === except || el.dataset.versoField !== name) return;
|
|
416
|
+
if (String(value).trim()) {
|
|
417
|
+
el.removeAttribute('data-verso-empty');
|
|
418
|
+
el.style.opacity = '';
|
|
419
|
+
el.textContent = value;
|
|
420
|
+
} else showPlaceholder(el);
|
|
421
|
+
});
|
|
422
|
+
root.querySelectorAll(`[data-field="${CSS.escape(name)}"]`).forEach((input) => {
|
|
423
|
+
if (input.value !== value) input.value = value;
|
|
424
|
+
});
|
|
425
|
+
queue({ fields: { [name]: String(value).trim() } });
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
function startEditing(el) {
|
|
429
|
+
if (editEl === el) return;
|
|
430
|
+
if (editEl) stopEditing();
|
|
431
|
+
closeImagePop();
|
|
432
|
+
editEl = el;
|
|
433
|
+
editBaseline = values[el.dataset.versoField] ?? '';
|
|
434
|
+
el.contentEditable = plaintextOnly ? 'plaintext-only' : 'true';
|
|
435
|
+
el.spellcheck = true;
|
|
436
|
+
el.style.outline = 'none';
|
|
437
|
+
el.style.cursor = 'text';
|
|
438
|
+
if (isEmpty(el)) {
|
|
439
|
+
clearPlaceholder(el);
|
|
440
|
+
el.style.minHeight = '1lh';
|
|
441
|
+
el.style.minWidth = '2ch';
|
|
442
|
+
// An empty inline element has no width, so the caret has nowhere to go.
|
|
443
|
+
if (getComputedStyle(el).display === 'inline') el.style.display = 'inline-block';
|
|
444
|
+
// The click that started editing landed on the placeholder, which is gone
|
|
445
|
+
// now, so put the caret inside the field once the click has finished.
|
|
446
|
+
const caretInside = () => {
|
|
447
|
+
if (editEl !== el || el.textContent) return;
|
|
448
|
+
const range = document.createRange();
|
|
449
|
+
range.selectNodeContents(el);
|
|
450
|
+
range.collapse(true);
|
|
451
|
+
const sel = getSelection();
|
|
452
|
+
sel.removeAllRanges();
|
|
453
|
+
sel.addRange(range);
|
|
454
|
+
};
|
|
455
|
+
caretInside();
|
|
456
|
+
setTimeout(caretInside, 0);
|
|
457
|
+
}
|
|
458
|
+
el.focus({ preventScroll: true });
|
|
459
|
+
drawMarks();
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
function stopEditing() {
|
|
463
|
+
const el = editEl;
|
|
464
|
+
if (!el) return;
|
|
465
|
+
editEl = null;
|
|
466
|
+
el.contentEditable = 'false';
|
|
467
|
+
el.removeAttribute('contenteditable');
|
|
468
|
+
el.style.outline = '';
|
|
469
|
+
el.style.cursor = '';
|
|
470
|
+
el.style.minHeight = '';
|
|
471
|
+
el.style.minWidth = '';
|
|
472
|
+
el.style.display = '';
|
|
473
|
+
const value = readText(el).trim();
|
|
474
|
+
if (!value) showPlaceholder(el);
|
|
475
|
+
else if (el.textContent !== value) el.textContent = value;
|
|
476
|
+
const name = el.dataset.versoField;
|
|
477
|
+
record({ type: 'text', name, label: labelOf(name), before: String(editBaseline).trim(), after: value });
|
|
478
|
+
flush();
|
|
479
|
+
drawMarks();
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
document.addEventListener('mouseover', (e) => {
|
|
483
|
+
const el = e.target.closest?.(anyField);
|
|
484
|
+
if (el !== hoverEl) {
|
|
485
|
+
hoverEl = el;
|
|
486
|
+
drawMarks();
|
|
487
|
+
}
|
|
488
|
+
}, true);
|
|
489
|
+
|
|
490
|
+
document.addEventListener('mousedown', (e) => {
|
|
491
|
+
if (e.composedPath().includes(host)) return;
|
|
492
|
+
const el = e.target.closest?.(anyField);
|
|
493
|
+
const plain = e.button === 0 && !(e.metaKey || e.ctrlKey);
|
|
494
|
+
if (el && plain && el.dataset.versoField) {
|
|
495
|
+
// An empty field shows a placeholder; the click shouldn't place the caret
|
|
496
|
+
// in it, since it's about to disappear. startEditing puts the caret inside.
|
|
497
|
+
if (el !== editEl && isEmpty(el)) e.preventDefault();
|
|
498
|
+
if (el !== editEl) startEditing(el);
|
|
499
|
+
return;
|
|
500
|
+
}
|
|
501
|
+
if (editEl) stopEditing();
|
|
502
|
+
if (el && plain && el.dataset.versoImage) {
|
|
503
|
+
e.preventDefault();
|
|
504
|
+
openImagePop(el);
|
|
505
|
+
return;
|
|
506
|
+
}
|
|
507
|
+
if (!el || !el.dataset.versoImage) closeImagePop();
|
|
508
|
+
}, true);
|
|
509
|
+
|
|
510
|
+
// Text inside a link edits; it doesn't navigate. Cmd or Ctrl-click follows it.
|
|
511
|
+
document.addEventListener('click', (e) => {
|
|
512
|
+
if (e.composedPath().includes(host)) return;
|
|
513
|
+
const el = e.target.closest?.(anyField);
|
|
514
|
+
if (el && !(e.metaKey || e.ctrlKey)) e.preventDefault();
|
|
515
|
+
}, true);
|
|
516
|
+
|
|
517
|
+
document.addEventListener('input', (e) => {
|
|
518
|
+
const el = e.target.closest?.('[data-verso-field]');
|
|
519
|
+
if (!el || el !== editEl) return;
|
|
520
|
+
setText(el.dataset.versoField, readText(el), { except: el });
|
|
521
|
+
drawMarks();
|
|
522
|
+
});
|
|
523
|
+
|
|
524
|
+
document.addEventListener('keydown', (e) => {
|
|
525
|
+
if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 's') {
|
|
526
|
+
e.preventDefault();
|
|
527
|
+
flush();
|
|
528
|
+
if (!pending) toast('Everything is saved. Verso saves as you type.', 'ok');
|
|
529
|
+
return;
|
|
530
|
+
}
|
|
531
|
+
if (!editEl || e.target !== editEl) return;
|
|
532
|
+
if (e.key === 'Enter' || e.key === 'Escape') {
|
|
533
|
+
e.preventDefault();
|
|
534
|
+
editEl.blur();
|
|
535
|
+
stopEditing();
|
|
536
|
+
}
|
|
537
|
+
}, true);
|
|
538
|
+
|
|
539
|
+
document.addEventListener('focusout', (e) => {
|
|
540
|
+
if (editEl && e.target === editEl) setTimeout(() => { if (editEl && document.activeElement !== editEl) stopEditing(); }, 0);
|
|
541
|
+
}, true);
|
|
542
|
+
|
|
543
|
+
// Without plaintext-only editing, keep pasted text plain.
|
|
544
|
+
if (!plaintextOnly) {
|
|
545
|
+
document.addEventListener('paste', (e) => {
|
|
546
|
+
if (!editEl || !editEl.contains(e.target)) return;
|
|
547
|
+
e.preventDefault();
|
|
548
|
+
const text = (e.clipboardData?.getData('text/plain') || '').replace(/\s*\n\s*/g, ' ');
|
|
549
|
+
document.execCommand('insertText', false, text);
|
|
550
|
+
}, true);
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
// ════ Rich text fields ════
|
|
554
|
+
// Every rich field is made editable as soon as the page loads, with the
|
|
555
|
+
// site's own classes, so it looks the same while you write.
|
|
556
|
+
|
|
557
|
+
const richEntries = [];
|
|
558
|
+
let activeRich = null;
|
|
559
|
+
const richByName = (name) => richEntries.find((r) => r.name === name);
|
|
560
|
+
const richIsEmpty = (html) => !/<img\b/i.test(html || '') && String(html || '').replace(/<[^>]*>/g, '').replace(/ |\s/g, '') === '';
|
|
561
|
+
|
|
562
|
+
// An empty picture says what goes there, and stays short so it doesn't
|
|
563
|
+
// push the page down.
|
|
564
|
+
function emptyPicture(name) {
|
|
565
|
+
const label = labelOf(name).toLowerCase();
|
|
566
|
+
const what = /picture|image|photo|logo|icon/.test(label) ? label : `${label} picture`;
|
|
567
|
+
const text = `Add a ${what}${fieldsByName.get(name)?.required ? '' : ' (optional)'}`;
|
|
568
|
+
const svg = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1200 360"><rect width="1200" height="360" fill="#E9E6DF"/><g fill="none" stroke="#8A857A" stroke-width="7" stroke-linejoin="round" transform="translate(560 96)"><rect width="80" height="62" rx="8"/><path d="m6 54 22-24 18 18 13-11 20 17"/></g><text x="600" y="232" text-anchor="middle" font-family="ui-sans-serif,system-ui,sans-serif" font-size="34" font-weight="600" fill="#6E695F">${text.replace(/&/g, '&').replace(/</g, '<')}</text></svg>`;
|
|
569
|
+
return `data:image/svg+xml;utf8,${encodeURIComponent(svg)}`;
|
|
570
|
+
}
|
|
571
|
+
document.querySelectorAll('img[data-verso-image][data-verso-empty]').forEach((el) => { el.src = emptyPicture(el.dataset.versoImage); });
|
|
572
|
+
|
|
573
|
+
const richEls = [...document.querySelectorAll('[data-verso-rich]')];
|
|
574
|
+
if (richEls.length) {
|
|
575
|
+
import('/__verso/rich.js')
|
|
576
|
+
.then(({ mountRich }) => richEls.forEach((el) => mountOne(mountRich, el)))
|
|
577
|
+
.catch(() => toast('The rich text editor couldn\'t load. Reload the page to try again.', 'error'));
|
|
578
|
+
}
|
|
579
|
+
|
|
580
|
+
function mountOne(mountRich, el) {
|
|
581
|
+
const name = el.dataset.versoRich;
|
|
582
|
+
const entry = { name, el, api: null, baseline: '' };
|
|
583
|
+
entry.api = mountRich(el, {
|
|
584
|
+
tools: (el.dataset.versoTools || '').split(/\s+/).filter(Boolean),
|
|
585
|
+
classes: data.rich || {},
|
|
586
|
+
base: data.url,
|
|
587
|
+
// The main text of a page invites writing; others show their name.
|
|
588
|
+
label: /^(body|content|text|main|article|post|story)$/i.test(name.split('.').pop()) ? 'Start writing…' : labelOf(name),
|
|
589
|
+
onChange: () => {
|
|
590
|
+
values[name] = entry.api.html();
|
|
591
|
+
queue({ fields: { [name]: values[name] } });
|
|
592
|
+
redraw();
|
|
593
|
+
},
|
|
594
|
+
onState: () => richState(entry),
|
|
595
|
+
onExit: () => entry.api.view.dom.blur(),
|
|
596
|
+
onHint: (message) => toast(message),
|
|
597
|
+
upload: uploadFile,
|
|
598
|
+
});
|
|
599
|
+
entry.tools = (el.dataset.versoTools || '').split(/\s+/).filter(Boolean);
|
|
600
|
+
values[name] = entry.api.html();
|
|
601
|
+
entry.baseline = values[name];
|
|
602
|
+
richEntries.push(entry);
|
|
603
|
+
redraw();
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
const toolbarHasFocus = () => {
|
|
607
|
+
const a = root.activeElement;
|
|
608
|
+
return !!(a && $('toolbar').contains(a));
|
|
609
|
+
};
|
|
610
|
+
|
|
611
|
+
function richState(entry) {
|
|
612
|
+
const st = entry.api.state();
|
|
613
|
+
if (st.focused) {
|
|
614
|
+
if (activeRich !== entry) {
|
|
615
|
+
if (activeRich) leaveRich(activeRich);
|
|
616
|
+
if (editEl) stopEditing();
|
|
617
|
+
closeImagePop();
|
|
618
|
+
activeRich = entry;
|
|
619
|
+
entry.baseline = entry.api.html();
|
|
620
|
+
toolbarMode = 'main';
|
|
621
|
+
}
|
|
622
|
+
renderToolbar();
|
|
623
|
+
} else if (activeRich === entry) {
|
|
624
|
+
// Focus can move into the toolbar's own inputs (link, alt text).
|
|
625
|
+
setTimeout(() => {
|
|
626
|
+
if (activeRich === entry && !entry.api.state().focused && !toolbarHasFocus()) leaveRich(entry);
|
|
627
|
+
}, 0);
|
|
628
|
+
}
|
|
629
|
+
redraw();
|
|
630
|
+
}
|
|
631
|
+
|
|
632
|
+
function leaveRich(entry) {
|
|
633
|
+
entry.api.hold?.(false);
|
|
634
|
+
const html = entry.api.html();
|
|
635
|
+
record({ type: 'rich', name: entry.name, label: labelOf(entry.name), before: entry.baseline, after: html });
|
|
636
|
+
entry.baseline = html;
|
|
637
|
+
if (activeRich === entry) activeRich = null;
|
|
638
|
+
toolbarMode = 'main';
|
|
639
|
+
hide($('toolbar'));
|
|
640
|
+
flush();
|
|
641
|
+
redraw();
|
|
642
|
+
}
|
|
643
|
+
|
|
644
|
+
// ════ Formatting toolbar ════
|
|
645
|
+
|
|
646
|
+
let toolbarMode = 'main'; // 'main' | 'link' | 'embed'
|
|
647
|
+
const BTN = ui("bg-color:transparent bd:width-0 cursor:pointer row:x-center:y-center min-w:d9 h:d9 pd-x:d2 bd:round-d3 text:paper font:small:semibold @hover:[bg-color:ink-2] transition:fast");
|
|
648
|
+
const BTN_ON = ui("bd:width-0 cursor:pointer row:x-center:y-center min-w:d9 h:d9 pd-x:d2 bd:round-d3 bg-color:proof text:paper font:small:semibold transition:fast");
|
|
649
|
+
const SEP = `<span class="${ui("w:px h:d5 mg-x:d1 bg-color:ink-3")}"></span>`;
|
|
650
|
+
const TOOLBAR_INPUT = ui("h:d9 w:c10 pd-x:d3 bd:round-d3 bd:width-0 bg-color:ink-2 text:paper font:small @focus:[outline:none_shadow:proof-focus]");
|
|
651
|
+
|
|
652
|
+
|
|
653
|
+
function renderToolbar() {
|
|
654
|
+
const entry = activeRich;
|
|
655
|
+
const bar = $('toolbar');
|
|
656
|
+
if (!entry) return hide(bar);
|
|
657
|
+
if (toolbarMode !== 'main' || toolbarHasFocus()) {
|
|
658
|
+
positionToolbar();
|
|
659
|
+
return;
|
|
660
|
+
}
|
|
661
|
+
const st = entry.api.state();
|
|
662
|
+
const has = (t) => entry.tools.includes(t);
|
|
663
|
+
const btn = (cmd, label, content, on = false, name = label) => `<button type="button" data-cmd="${cmd}" class="${on ? BTN_ON : BTN} ${ui("child:no-shrink format:no-wrap")}" title="${esc(label)}" aria-label="${esc(name)}" aria-pressed="${on}">${content}</button>`;
|
|
664
|
+
const groups = [];
|
|
665
|
+
// Inside a table, the table's own tools take the room.
|
|
666
|
+
if (has('headings') && !st.inTable) {
|
|
667
|
+
groups.push([
|
|
668
|
+
btn('p', 'Text', 'Text', st.block === 'p'),
|
|
669
|
+
btn('h2', 'Heading (H2)', 'Heading', st.block === 'h2', 'Heading'),
|
|
670
|
+
btn('h3', 'Subheading (H3)', 'Subheading', st.block === 'h3', 'Subheading'),
|
|
671
|
+
btn('h4', 'Small heading (H4)', 'Small heading', st.block === 'h4', 'Small heading'),
|
|
672
|
+
].join(''));
|
|
673
|
+
}
|
|
674
|
+
const inline = [btn('bold', `Bold (${MOD}B)`, icon('bold'), st.bold, 'Bold'), btn('italic', `Italic (${MOD}I)`, icon('italic'), st.italic, 'Italic')];
|
|
675
|
+
if (has('links')) inline.push(btn('link', st.link ? 'Edit link' : 'Link', icon('link'), !!st.link));
|
|
676
|
+
if (has('code')) inline.push(btn('code', `Inline code (${MOD}E)`, icon('code'), st.code, 'Inline code'));
|
|
677
|
+
groups.push(inline.join(''));
|
|
678
|
+
const blocks = [];
|
|
679
|
+
if (has('lists')) blocks.push(btn('ul', 'Bulleted list', icon('ul'), st.block === 'ul'), btn('ol', 'Numbered list', icon('ol'), st.block === 'ol'));
|
|
680
|
+
if (has('quotes')) blocks.push(btn('quote', 'Quote', icon('quote'), st.block === 'quote'));
|
|
681
|
+
if (has('callouts')) blocks.push(btn('callout', 'Callout', icon('callout'), st.block === 'callout'));
|
|
682
|
+
if (has('code')) blocks.push(btn('codeBlock', 'Code block (type ``` then space)', icon('codeBlock'), st.block === 'pre'));
|
|
683
|
+
if (blocks.length && !st.inTable) groups.push(blocks.join(''));
|
|
684
|
+
const inserts = [];
|
|
685
|
+
if (has('images')) inserts.push(btn('image', 'Add an image', icon('image')));
|
|
686
|
+
if (has('tables')) inserts.push(btn('table', 'Add a table', icon('table'), st.inTable));
|
|
687
|
+
if (has('embeds')) inserts.push(btn('embed', 'Embed a YouTube or Vimeo video', icon('video')));
|
|
688
|
+
if (inserts.length && !st.inTable) groups.push(inserts.join(''));
|
|
689
|
+
if (st.inTable) {
|
|
690
|
+
groups.push([
|
|
691
|
+
btn('row', 'Add a row below', 'Add row'),
|
|
692
|
+
btn('column', 'Add a column to the right', 'Add column'),
|
|
693
|
+
btn('deleteRow', 'Remove this row', 'Remove row'),
|
|
694
|
+
btn('deleteColumn', 'Remove this column', 'Remove column'),
|
|
695
|
+
btn('deleteTable', 'Remove the table', icon('trash')),
|
|
696
|
+
].join(''));
|
|
697
|
+
}
|
|
698
|
+
let html = groups.join(SEP);
|
|
699
|
+
if (st.embed) html += `${SEP}${btn('removeImage', 'Remove the video', icon('trash'))}`;
|
|
700
|
+
if (st.image) {
|
|
701
|
+
html += `${SEP}${st.image.alt ? '' : `<span class="${ui("child:no-shrink pd-x:d2 font:tiny:semibold text:proof format:no-wrap")}">No description</span>`}<input id="tb-alt" class="${TOOLBAR_INPUT} ${ui("child:no-shrink")}" placeholder="Description: what the picture shows" value="${esc(st.image.alt)}" aria-label="Description: what the picture shows">${btn('removeImage', 'Remove the picture', icon('trash'))}`;
|
|
702
|
+
}
|
|
703
|
+
bar.innerHTML = html;
|
|
704
|
+
root.getElementById('tb-alt')?.addEventListener('input', (e) => entry.api.alt(e.target.value));
|
|
705
|
+
root.getElementById('tb-alt')?.addEventListener('keydown', (e) => {
|
|
706
|
+
if (e.key === 'Enter' || e.key === 'Escape') { e.preventDefault(); entry.api.focus(); }
|
|
707
|
+
});
|
|
708
|
+
root.getElementById('tb-alt')?.addEventListener('blur', () => setTimeout(() => {
|
|
709
|
+
if (activeRich === entry && !entry.api.state().focused && !toolbarHasFocus()) leaveRich(entry);
|
|
710
|
+
}, 0));
|
|
711
|
+
show(bar, 'flex');
|
|
712
|
+
positionToolbar();
|
|
713
|
+
}
|
|
714
|
+
|
|
715
|
+
function renderLinkMode() {
|
|
716
|
+
const entry = activeRich;
|
|
717
|
+
if (!entry) return;
|
|
718
|
+
toolbarMode = 'link';
|
|
719
|
+
const current = entry.api.state().link || '';
|
|
720
|
+
const bar = $('toolbar');
|
|
721
|
+
// The site's pages, offered as you type (the same list as element links).
|
|
722
|
+
if (!root.getElementById('verso-attr-pages')) {
|
|
723
|
+
const list = document.createElement('datalist');
|
|
724
|
+
list.id = 'verso-attr-pages';
|
|
725
|
+
list.innerHTML = (data.pages || []).map((p) => `<option value="${esc(p.url)}">${esc(p.label || p.url)}</option>`).join('');
|
|
726
|
+
root.appendChild(list);
|
|
727
|
+
}
|
|
728
|
+
bar.innerHTML = `
|
|
729
|
+
<input id="tb-link" list="verso-attr-pages" autocomplete="off" spellcheck="false" class="${TOOLBAR_INPUT} ${ui("child:no-shrink")}" placeholder="A page, like /about/, or https://…" value="${esc(current)}" aria-label="Link address" aria-describedby="tb-link-warn">
|
|
730
|
+
<span id="tb-link-warn" class="${ui("child:no-shrink pd-x:d2 font:tiny:semibold text:proof format:no-wrap")}" role="status"></span>
|
|
731
|
+
<button type="button" data-cmd="apply-link" class="${BTN}">Apply</button>
|
|
732
|
+
${current ? `<button type="button" data-cmd="remove-link" class="${BTN}">Remove</button>` : ''}
|
|
733
|
+
<button type="button" data-cmd="cancel-link" class="${BTN}" aria-label="Cancel">${icon('close')}</button>`;
|
|
734
|
+
show(bar, 'flex');
|
|
735
|
+
positionToolbar();
|
|
736
|
+
entry.api.hold?.(true);
|
|
737
|
+
const input = root.getElementById('tb-link');
|
|
738
|
+
const warn = root.getElementById('tb-link-warn');
|
|
739
|
+
const check = () => { warn.textContent = missingPage(input.value) ? 'No page at this address' : ''; };
|
|
740
|
+
input.addEventListener('input', check);
|
|
741
|
+
check();
|
|
742
|
+
input.focus();
|
|
743
|
+
input.select();
|
|
744
|
+
input.addEventListener('keydown', (e) => {
|
|
745
|
+
if (e.key === 'Enter') { e.preventDefault(); applyLink(input.value); }
|
|
746
|
+
if (e.key === 'Escape') { e.preventDefault(); e.stopPropagation(); closeLinkMode(); }
|
|
747
|
+
});
|
|
748
|
+
input.addEventListener('blur', () => setTimeout(() => {
|
|
749
|
+
if (toolbarMode !== 'main' && !toolbarHasFocus() && activeRich === entry && !entry.api.state().focused) {
|
|
750
|
+
toolbarMode = 'main';
|
|
751
|
+
leaveRich(entry);
|
|
752
|
+
}
|
|
753
|
+
}, 0));
|
|
754
|
+
}
|
|
755
|
+
|
|
756
|
+
// A YouTube or Vimeo link, typed or pasted, becomes a player in the text.
|
|
757
|
+
function renderEmbedMode() {
|
|
758
|
+
const entry = activeRich;
|
|
759
|
+
if (!entry) return;
|
|
760
|
+
toolbarMode = 'embed';
|
|
761
|
+
const bar = $('toolbar');
|
|
762
|
+
bar.innerHTML = `
|
|
763
|
+
<input id="tb-embed" class="${TOOLBAR_INPUT}" placeholder="YouTube or Vimeo link" aria-label="Video link">
|
|
764
|
+
<button type="button" data-cmd="apply-embed" class="${BTN}">Embed</button>
|
|
765
|
+
<button type="button" data-cmd="cancel-embed" class="${BTN}" aria-label="Cancel">${icon('close')}</button>`;
|
|
766
|
+
show(bar, 'flex');
|
|
767
|
+
positionToolbar();
|
|
768
|
+
const input = root.getElementById('tb-embed');
|
|
769
|
+
input.focus();
|
|
770
|
+
input.addEventListener('keydown', (e) => {
|
|
771
|
+
if (e.key === 'Enter') { e.preventDefault(); applyEmbed(input.value); }
|
|
772
|
+
if (e.key === 'Escape') { e.preventDefault(); e.stopPropagation(); closeLinkMode(); }
|
|
773
|
+
});
|
|
774
|
+
input.addEventListener('blur', () => setTimeout(() => {
|
|
775
|
+
if (toolbarMode === 'embed' && !toolbarHasFocus() && activeRich === entry && !entry.api.state().focused) {
|
|
776
|
+
toolbarMode = 'main';
|
|
777
|
+
leaveRich(entry);
|
|
778
|
+
}
|
|
779
|
+
}, 0));
|
|
780
|
+
}
|
|
781
|
+
|
|
782
|
+
function applyEmbed(url) {
|
|
783
|
+
const entry = activeRich;
|
|
784
|
+
if (!entry) return;
|
|
785
|
+
if (!String(url || '').trim()) return closeLinkMode();
|
|
786
|
+
if (!entry.api.embed(url)) {
|
|
787
|
+
toast('Only YouTube and Vimeo links can be embedded.', 'error');
|
|
788
|
+
root.getElementById('tb-embed')?.focus();
|
|
789
|
+
return;
|
|
790
|
+
}
|
|
791
|
+
toolbarMode = 'main';
|
|
792
|
+
renderToolbar();
|
|
793
|
+
}
|
|
794
|
+
|
|
795
|
+
const cleanHref = (href) => {
|
|
796
|
+
const v = String(href || '').trim();
|
|
797
|
+
if (!v) return '';
|
|
798
|
+
if (/^(https?:|mailto:|tel:|\/|#)/i.test(v)) return v;
|
|
799
|
+
if (/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v)) return `mailto:${v}`;
|
|
800
|
+
return `https://${v}`;
|
|
801
|
+
};
|
|
802
|
+
|
|
803
|
+
// An address on this site that no page answers to.
|
|
804
|
+
function missingPage(href) {
|
|
805
|
+
const v = String(href || '').trim();
|
|
806
|
+
if (!v.startsWith('/') || v.startsWith('//')) return false;
|
|
807
|
+
const path = v.split(/[?#]/)[0];
|
|
808
|
+
if (/\.[a-z0-9]{2,5}$/i.test(path) || path.startsWith('/assets/') || path.startsWith('/__verso')) return false;
|
|
809
|
+
const norm = (u) => (u.endsWith('/') ? u : `${u}/`);
|
|
810
|
+
return !(data.pages || []).some((p) => norm(p.url) === norm(path));
|
|
811
|
+
}
|
|
812
|
+
|
|
813
|
+
function applyLink(href) {
|
|
814
|
+
const entry = activeRich;
|
|
815
|
+
entry?.api.hold?.(false);
|
|
816
|
+
toolbarMode = 'main';
|
|
817
|
+
if (entry) entry.api.link(cleanHref(href));
|
|
818
|
+
renderToolbar();
|
|
819
|
+
}
|
|
820
|
+
|
|
821
|
+
function closeLinkMode() {
|
|
822
|
+
activeRich?.api.hold?.(false);
|
|
823
|
+
toolbarMode = 'main';
|
|
824
|
+
activeRich?.api.focus();
|
|
825
|
+
renderToolbar();
|
|
826
|
+
}
|
|
827
|
+
|
|
828
|
+
// Before acting, make sure the editor has read the latest selection from the
|
|
829
|
+
// page; a very fast click can otherwise arrive first.
|
|
830
|
+
const syncSelection = (api) => {
|
|
831
|
+
try { api.view.domObserver.flush(); } catch { /* not needed when already in step */ }
|
|
832
|
+
};
|
|
833
|
+
|
|
834
|
+
async function runCommand(cmd) {
|
|
835
|
+
const entry = activeRich;
|
|
836
|
+
if (!entry) return;
|
|
837
|
+
const api = entry.api;
|
|
838
|
+
if (toolbarMode === 'main') syncSelection(api);
|
|
839
|
+
switch (cmd) {
|
|
840
|
+
case 'p': case 'h2': case 'h3': case 'h4': api.block(cmd); break;
|
|
841
|
+
case 'bold': api.bold(); break;
|
|
842
|
+
case 'code': api.code(); break;
|
|
843
|
+
case 'codeBlock': api.codeBlock(); break;
|
|
844
|
+
case 'italic': api.italic(); break;
|
|
845
|
+
case 'link': renderLinkMode(); return;
|
|
846
|
+
case 'apply-link': applyLink(root.getElementById('tb-link')?.value); return;
|
|
847
|
+
case 'remove-link': applyLink(''); return;
|
|
848
|
+
case 'cancel-link': closeLinkMode(); return;
|
|
849
|
+
case 'embed': renderEmbedMode(); return;
|
|
850
|
+
case 'apply-embed': applyEmbed(root.getElementById('tb-embed')?.value); return;
|
|
851
|
+
case 'cancel-embed': closeLinkMode(); return;
|
|
852
|
+
case 'ul': api.list('ul'); break;
|
|
853
|
+
case 'ol': api.list('ol'); break;
|
|
854
|
+
case 'quote': api.wrap('quote'); break;
|
|
855
|
+
case 'callout': api.wrap('callout'); break;
|
|
856
|
+
case 'image': {
|
|
857
|
+
const file = await pickImage();
|
|
858
|
+
if (file) await api.images([file]);
|
|
859
|
+
api.focus();
|
|
860
|
+
break;
|
|
861
|
+
}
|
|
862
|
+
case 'table': if (!api.state().inTable) api.table(); break;
|
|
863
|
+
case 'row': api.row(); break;
|
|
864
|
+
case 'column': api.column(); break;
|
|
865
|
+
case 'deleteRow': api.deleteRow(); break;
|
|
866
|
+
case 'deleteColumn': api.deleteColumn(); break;
|
|
867
|
+
case 'deleteTable': api.deleteTable(); break;
|
|
868
|
+
case 'removeImage': api.removeImage(); break;
|
|
869
|
+
default: return;
|
|
870
|
+
}
|
|
871
|
+
renderToolbar();
|
|
872
|
+
}
|
|
873
|
+
|
|
874
|
+
// Buttons act on mousedown and never take focus, so the text stays selected.
|
|
875
|
+
$('toolbar').addEventListener('mousedown', (e) => {
|
|
876
|
+
const b = e.target.closest('[data-cmd]');
|
|
877
|
+
if (!b) return;
|
|
878
|
+
e.preventDefault();
|
|
879
|
+
runCommand(b.dataset.cmd);
|
|
880
|
+
});
|
|
881
|
+
$('toolbar').addEventListener('keydown', (e) => {
|
|
882
|
+
const b = e.target.closest?.('[data-cmd]');
|
|
883
|
+
if (b && (e.key === 'Enter' || e.key === ' ')) { e.preventDefault(); runCommand(b.dataset.cmd); }
|
|
884
|
+
});
|
|
885
|
+
|
|
886
|
+
// Just above the field, never off screen; pinned to the top while the
|
|
887
|
+
// field's top is scrolled away.
|
|
888
|
+
function positionToolbar() {
|
|
889
|
+
const bar = $('toolbar');
|
|
890
|
+
if (!activeRich || !isShown(bar)) return;
|
|
891
|
+
const r = activeRich.el.getBoundingClientRect();
|
|
892
|
+
const w = bar.offsetWidth;
|
|
893
|
+
const h = bar.offsetHeight;
|
|
894
|
+
let top = r.top - h - 12;
|
|
895
|
+
if (top < 8) top = 8;
|
|
896
|
+
if (top + h > r.bottom - 8 && r.bottom < h + 24) top = Math.max(8, r.bottom + 8);
|
|
897
|
+
const left = Math.max(8, Math.min(r.left - 4, innerWidth - w - 8));
|
|
898
|
+
bar.style.top = `${Math.round(top)}px`;
|
|
899
|
+
bar.style.left = `${Math.round(left)}px`;
|
|
900
|
+
}
|
|
901
|
+
|
|
902
|
+
// ════ Image fields ════
|
|
903
|
+
|
|
904
|
+
let popEl = null;
|
|
905
|
+
let dragEl = null;
|
|
906
|
+
let altBaseline = null;
|
|
907
|
+
|
|
908
|
+
function setImage(name, value, { record: shouldRecord = true } = {}) {
|
|
909
|
+
const before = values[name] ?? null;
|
|
910
|
+
const next = value && value.file ? { file: value.file, alt: value.alt || '' } : null;
|
|
911
|
+
values[name] = next;
|
|
912
|
+
let needsReload = false;
|
|
913
|
+
document.querySelectorAll(`[data-verso-image="${CSS.escape(name)}"]`).forEach((el) => {
|
|
914
|
+
if (el.tagName === 'IMG') {
|
|
915
|
+
el.src = next ? imageUrl(next.file) : emptyPicture(name);
|
|
916
|
+
el.alt = next ? next.alt : '';
|
|
917
|
+
if (value?.width && value?.height) {
|
|
918
|
+
el.setAttribute('width', value.width);
|
|
919
|
+
el.setAttribute('height', value.height);
|
|
920
|
+
}
|
|
921
|
+
if (next) el.removeAttribute('data-verso-empty');
|
|
922
|
+
else el.setAttribute('data-verso-empty', '');
|
|
923
|
+
} else {
|
|
924
|
+
needsReload = true;
|
|
925
|
+
}
|
|
926
|
+
});
|
|
927
|
+
queue({ fields: { [name]: next } });
|
|
928
|
+
if (shouldRecord) record({ type: 'image', name, label: labelOf(name), before, after: next });
|
|
929
|
+
if (needsReload) {
|
|
930
|
+
reloadAfterSave = true;
|
|
931
|
+
flush();
|
|
932
|
+
}
|
|
933
|
+
if (popEl && popEl.dataset.versoImage === name) renderImagePop();
|
|
934
|
+
if (isShown($('settings')) && fieldsByName.get(name)?.offPage) openSettings();
|
|
935
|
+
redraw();
|
|
936
|
+
}
|
|
937
|
+
|
|
938
|
+
async function chooseImage(name) {
|
|
939
|
+
const file = await pickImage();
|
|
940
|
+
if (!file) return;
|
|
941
|
+
const out = await uploadFile(file);
|
|
942
|
+
if (out?.file) {
|
|
943
|
+
setImage(name, { file: out.file, alt: values[name]?.alt || '', width: out.width, height: out.height });
|
|
944
|
+
askForAlt(name);
|
|
945
|
+
}
|
|
946
|
+
}
|
|
947
|
+
|
|
948
|
+
// A new image without a description: open its popover with the description
|
|
949
|
+
// field ready, so describing it is the obvious next step, not a chore.
|
|
950
|
+
let askingAlt = null;
|
|
951
|
+
function askForAlt(name) {
|
|
952
|
+
if (values[name]?.alt) return;
|
|
953
|
+
const el = popEl?.dataset.versoImage === name ? popEl : document.querySelector(`[data-verso-image="${CSS.escape(name)}"]`);
|
|
954
|
+
if (!el) return;
|
|
955
|
+
askingAlt = name;
|
|
956
|
+
if (popEl !== el) openImagePop(el);
|
|
957
|
+
else renderImagePop();
|
|
958
|
+
setTimeout(() => root.getElementById('pop-alt')?.focus(), 0);
|
|
959
|
+
}
|
|
960
|
+
|
|
961
|
+
function openImagePop(el) {
|
|
962
|
+
popEl = el;
|
|
963
|
+
renderImagePop();
|
|
964
|
+
drawMarks();
|
|
965
|
+
}
|
|
966
|
+
|
|
967
|
+
function closeImagePop() {
|
|
968
|
+
if (!popEl) return;
|
|
969
|
+
askingAlt = null;
|
|
970
|
+
commitAlt();
|
|
971
|
+
popEl = null;
|
|
972
|
+
hide($('image-pop'));
|
|
973
|
+
drawMarks();
|
|
974
|
+
}
|
|
975
|
+
|
|
976
|
+
function commitAlt() {
|
|
977
|
+
if (!popEl || altBaseline === null) return;
|
|
978
|
+
const name = popEl.dataset.versoImage;
|
|
979
|
+
const now = values[name];
|
|
980
|
+
if (now && altBaseline !== null && now.alt !== altBaseline.alt) {
|
|
981
|
+
record({ type: 'image', name, label: `${labelOf(name)} description`, before: altBaseline, after: { ...now } });
|
|
982
|
+
}
|
|
983
|
+
altBaseline = null;
|
|
984
|
+
}
|
|
985
|
+
|
|
986
|
+
function renderImagePop() {
|
|
987
|
+
const pop = $('image-pop');
|
|
988
|
+
if (!popEl) return hide(pop);
|
|
989
|
+
const name = popEl.dataset.versoImage;
|
|
990
|
+
const field = fieldsByName.get(name);
|
|
991
|
+
const value = values[name];
|
|
992
|
+
pop.innerHTML = `
|
|
993
|
+
<div class="${ui("row:y-center:x-between gap:d3")}">
|
|
994
|
+
<span class="${ui("font:small:semibold text:ink")}">${esc(labelOf(name))}${field?.required ? ` <span class="${ui("text:proof-2 font:tiny")}">Required</span>` : ''}</span>
|
|
995
|
+
<button id="pop-close" class="${ui("bg-color:transparent bd:width-0 cursor:pointer row:x-center:y-center w:d8 h:d8 bd:round-full text:ink @hover:[bg-color:paper-2] transition:fast")}" aria-label="Close">${icon('close')}</button>
|
|
996
|
+
</div>
|
|
997
|
+
<button id="pop-choose" class="${ui("bd:width-0 cursor:pointer row:x-center:y-center gap:d2 h:d10 pd-x:d4 bd:round-pill bg-color:ink text:paper font:small:semibold @hover:[bg-color:ink-2] @focus-visible:[outline:d0:solid:proof] transition:fast")}">${icon('upload')}<span>${value?.file ? 'Replace image' : 'Choose an image'}</span></button>
|
|
998
|
+
<p class="${ui("font:tiny text:mist")}">Or drop an image file onto it.</p>
|
|
999
|
+
${value?.file ? `
|
|
1000
|
+
<label class="${ui("col gap:d2")}">
|
|
1001
|
+
<span class="${ui("font:small:medium text:ink")}">Description</span>
|
|
1002
|
+
${askingAlt === name && !value.alt ? `<span class="${ui("font:tiny text:ink-3")}">Describe it in a few words, for people who can't see it and for search engines.</span>` : ''}
|
|
1003
|
+
<input id="pop-alt" class="${ui("w:full h:d10 pd-x:d3 bd:round-d3 bd:width-px:solid:line bg-color:paper font:small text:ink @focus:[bd:proof_shadow:proof-focus_outline:none] transition:fast")}" placeholder="What the image shows" value="${esc(value.alt || '')}">
|
|
1004
|
+
</label>
|
|
1005
|
+
<button id="pop-remove" class="${ui("bg-color:transparent bd:width-0 cursor:pointer row:y-center gap:d2 w:fit-content h:d9 pd-x:d2 bd:round-pill text:proof-2 font:small:medium @hover:[bg-color:proof-soft] transition:fast")}">${icon('trash')}<span>Remove image</span></button>` : ''}`;
|
|
1006
|
+
root.getElementById('pop-close').addEventListener('click', closeImagePop);
|
|
1007
|
+
root.getElementById('pop-choose').addEventListener('click', () => chooseImage(name));
|
|
1008
|
+
const alt = root.getElementById('pop-alt');
|
|
1009
|
+
if (alt) {
|
|
1010
|
+
alt.addEventListener('focus', () => { altBaseline = values[name] ? { ...values[name] } : null; });
|
|
1011
|
+
alt.addEventListener('input', () => {
|
|
1012
|
+
if (!values[name]) return;
|
|
1013
|
+
values[name] = { ...values[name], alt: alt.value };
|
|
1014
|
+
document.querySelectorAll(`img[data-verso-image="${CSS.escape(name)}"]`).forEach((img) => { img.alt = alt.value; });
|
|
1015
|
+
queue({ fields: { [name]: values[name] } });
|
|
1016
|
+
});
|
|
1017
|
+
alt.addEventListener('blur', commitAlt);
|
|
1018
|
+
alt.addEventListener('keydown', (e) => { if (e.key === 'Enter') { e.preventDefault(); alt.blur(); } });
|
|
1019
|
+
}
|
|
1020
|
+
root.getElementById('pop-remove')?.addEventListener('click', () => setImage(name, null));
|
|
1021
|
+
show(pop, 'flex');
|
|
1022
|
+
positionImagePop();
|
|
1023
|
+
}
|
|
1024
|
+
|
|
1025
|
+
function positionImagePop() {
|
|
1026
|
+
const pop = $('image-pop');
|
|
1027
|
+
if (!popEl || !isShown(pop)) return;
|
|
1028
|
+
const r = popEl.getBoundingClientRect();
|
|
1029
|
+
const w = pop.offsetWidth;
|
|
1030
|
+
const h = pop.offsetHeight;
|
|
1031
|
+
let left = r.right + 12;
|
|
1032
|
+
let top = r.top;
|
|
1033
|
+
if (left + w > innerWidth - 8) {
|
|
1034
|
+
left = Math.max(8, Math.min(r.left, innerWidth - w - 8));
|
|
1035
|
+
top = r.bottom + 12;
|
|
1036
|
+
if (top + h > innerHeight - 80) top = Math.max(8, r.top - h - 12);
|
|
1037
|
+
}
|
|
1038
|
+
top = Math.max(8, Math.min(top, innerHeight - h - 80));
|
|
1039
|
+
pop.style.left = `${Math.round(left)}px`;
|
|
1040
|
+
pop.style.top = `${Math.round(top)}px`;
|
|
1041
|
+
}
|
|
1042
|
+
|
|
1043
|
+
// Dragging image files: onto an image field to set it, into rich text to add
|
|
1044
|
+
// it there. Anywhere else, the browser would open the file, so stop it.
|
|
1045
|
+
const hasFiles = (e) => [...(e.dataTransfer?.types || [])].includes('Files');
|
|
1046
|
+
document.addEventListener('dragover', (e) => {
|
|
1047
|
+
if (!hasFiles(e)) return;
|
|
1048
|
+
const el = e.target.closest?.('[data-verso-image]');
|
|
1049
|
+
if (el) {
|
|
1050
|
+
e.preventDefault();
|
|
1051
|
+
e.dataTransfer.dropEffect = 'copy';
|
|
1052
|
+
} else if (!e.target.closest?.('[data-verso-rich]')) {
|
|
1053
|
+
e.preventDefault();
|
|
1054
|
+
e.dataTransfer.dropEffect = 'none';
|
|
1055
|
+
}
|
|
1056
|
+
if (el !== dragEl) {
|
|
1057
|
+
dragEl = el;
|
|
1058
|
+
drawMarks();
|
|
1059
|
+
}
|
|
1060
|
+
}, true);
|
|
1061
|
+
document.addEventListener('dragleave', (e) => {
|
|
1062
|
+
if (dragEl && !dragEl.contains(e.relatedTarget)) {
|
|
1063
|
+
dragEl = null;
|
|
1064
|
+
drawMarks();
|
|
1065
|
+
}
|
|
1066
|
+
}, true);
|
|
1067
|
+
document.addEventListener('drop', async (e) => {
|
|
1068
|
+
if (!hasFiles(e)) return;
|
|
1069
|
+
const el = e.target.closest?.('[data-verso-image]');
|
|
1070
|
+
dragEl = null;
|
|
1071
|
+
drawMarks();
|
|
1072
|
+
if (e.target.closest?.('[data-verso-rich]')) return; // the rich editor handles it
|
|
1073
|
+
e.preventDefault();
|
|
1074
|
+
if (!el) {
|
|
1075
|
+
toast('Drop images onto an image, or into a text area that allows images.', 'error');
|
|
1076
|
+
return;
|
|
1077
|
+
}
|
|
1078
|
+
const file = imageFile(e.dataTransfer.files);
|
|
1079
|
+
if (!file) {
|
|
1080
|
+
toast('That file isn\'t an image Verso can use. Use a JPEG, PNG, GIF, WebP or AVIF.', 'error');
|
|
1081
|
+
return;
|
|
1082
|
+
}
|
|
1083
|
+
const name = el.dataset.versoImage;
|
|
1084
|
+
const out = await uploadFile(file);
|
|
1085
|
+
if (out?.file) {
|
|
1086
|
+
setImage(name, { file: out.file, alt: values[name]?.alt || '', width: out.width, height: out.height });
|
|
1087
|
+
askForAlt(name);
|
|
1088
|
+
}
|
|
1089
|
+
}, true);
|
|
1090
|
+
|
|
1091
|
+
// ════ Marks: outlines, labels and required badges ════
|
|
1092
|
+
|
|
1093
|
+
const fieldIsEmpty = (el) => {
|
|
1094
|
+
if (el.dataset.versoRich) return richIsEmpty(values[el.dataset.versoRich] ?? '') && (richByName(el.dataset.versoRich) || isEmpty(el));
|
|
1095
|
+
if (el.dataset.versoImage) return !values[el.dataset.versoImage]?.file;
|
|
1096
|
+
return isEmpty(el);
|
|
1097
|
+
};
|
|
1098
|
+
|
|
1099
|
+
function drawMarks() {
|
|
1100
|
+
const marks = $('marks');
|
|
1101
|
+
const parts = [];
|
|
1102
|
+
const drawn = new Set();
|
|
1103
|
+
const box = (el, strong, { label = true, text = null } = {}) => {
|
|
1104
|
+
if (!el || drawn.has(el)) return;
|
|
1105
|
+
drawn.add(el);
|
|
1106
|
+
const r = el.getBoundingClientRect();
|
|
1107
|
+
if (r.width === 0 && r.height === 0) return;
|
|
1108
|
+
const name = nameOf(el);
|
|
1109
|
+
const field = fieldsByName.get(name);
|
|
1110
|
+
const top = r.top - 4;
|
|
1111
|
+
const labelAbove = top > 28;
|
|
1112
|
+
parts.push(`<div class="${strong ? ui("absolute bd:width-d0:solid:proof bd:round-d1 shadow:proof-ring") : ui("absolute bd:width-px:solid:proof bd:round-d1")}" style="left:${r.left - 4}px;top:${top}px;width:${r.width + 8}px;height:${r.height + 8}px"></div>`);
|
|
1113
|
+
if (label) {
|
|
1114
|
+
parts.push(`<div class="${ui("absolute row:y-center gap:d1 pd:d0:d2 bd:round-d1 bg-color:proof text:paper font:tiny:semibold format:no-wrap")}" style="left:${r.left - 4}px;top:${labelAbove ? top - 22 : top + r.height + 12}px">${esc(text || labelOf(name))}${!text && field?.required ? ', required' : ''}${!text && name?.startsWith('site.') ? ', same on every page' : ''}</div>`);
|
|
1115
|
+
}
|
|
1116
|
+
};
|
|
1117
|
+
if (dragEl) box(dragEl, true, { text: 'Drop to use this image' });
|
|
1118
|
+
if (editEl) box(editEl, true);
|
|
1119
|
+
if (activeRich && activeRich.api.state().focused) box(activeRich.el, true, { label: false });
|
|
1120
|
+
else if (activeRich && toolbarHasFocus()) box(activeRich.el, true, { label: false });
|
|
1121
|
+
if (popEl) box(popEl, true);
|
|
1122
|
+
if (flashEl) box(flashEl, true);
|
|
1123
|
+
if (hoverEl) box(hoverEl, false);
|
|
1124
|
+
// Images without a description get a quiet note, so they're easy to find.
|
|
1125
|
+
document.querySelectorAll('img[data-verso-image]').forEach((el) => {
|
|
1126
|
+
const v = values[el.dataset.versoImage];
|
|
1127
|
+
if (!v?.file || v.alt) return;
|
|
1128
|
+
const r = el.getBoundingClientRect();
|
|
1129
|
+
if (r.width < 60 || r.height < 30 || r.bottom < 0 || r.top > innerHeight) return;
|
|
1130
|
+
parts.push(`<div class="${ui("absolute row:y-center gap:d1 pd:d2:d0 bd:round-pill bg-color:ink text:paper font:tiny:medium format:no-wrap opacity:90")}" style="left:${r.left + 8}px;top:${r.bottom - 30}px">No description</div>`);
|
|
1131
|
+
});
|
|
1132
|
+
// Empty required fields are marked all the time, so nothing is published half-done.
|
|
1133
|
+
document.querySelectorAll(anyField).forEach((el) => {
|
|
1134
|
+
if (drawn.has(el) || !el.hasAttribute('data-verso-required') || !fieldIsEmpty(el)) return;
|
|
1135
|
+
const r = el.getBoundingClientRect();
|
|
1136
|
+
if (r.bottom < 0 || r.top > innerHeight) return;
|
|
1137
|
+
parts.push(`<div class="${ui("absolute bd:width-px:dashed:proof bd:round-d1")}" style="left:${r.left - 4}px;top:${r.top - 4}px;width:${r.width + 8}px;height:${r.height + 8}px"></div>`);
|
|
1138
|
+
parts.push(`<div class="${ui("absolute pd:d0:d2 bd:round-d1 bg-color:proof-soft text:proof-2 font:tiny:semibold format:no-wrap")}" style="left:${r.right - 4}px;top:${r.top - 4}px;transform:translate(-100%,-100%)">Required</div>`);
|
|
1139
|
+
});
|
|
1140
|
+
marks.innerHTML = parts.join('');
|
|
1141
|
+
positionToolbar();
|
|
1142
|
+
positionImagePop();
|
|
1143
|
+
}
|
|
1144
|
+
|
|
1145
|
+
let frame = 0;
|
|
1146
|
+
function redraw() {
|
|
1147
|
+
cancelAnimationFrame(frame);
|
|
1148
|
+
frame = requestAnimationFrame(drawMarks);
|
|
1149
|
+
}
|
|
1150
|
+
addEventListener('scroll', redraw, { passive: true, capture: true });
|
|
1151
|
+
addEventListener('resize', redraw);
|
|
1152
|
+
if (document.fonts) document.fonts.ready.then(redraw);
|
|
1153
|
+
addEventListener('load', redraw);
|
|
1154
|
+
redraw();
|
|
1155
|
+
|
|
1156
|
+
// ════ Toasts ════
|
|
1157
|
+
|
|
1158
|
+
let toastTimer = 0;
|
|
1159
|
+
// toast(message, kind, { label, run }): an optional action, like Undo,
|
|
1160
|
+
// keeps the toast up a little longer.
|
|
1161
|
+
function toast(message, kind = 'ok', action = null) {
|
|
1162
|
+
const el = $('toast');
|
|
1163
|
+
const tone = kind === 'error'
|
|
1164
|
+
? `<span class="${ui("row:x-center:y-center w:d6 h:d6 bd:round-full bg-color:proof text:paper child:no-shrink")}">${icon('alert')}</span>`
|
|
1165
|
+
: `<span class="${ui("row:x-center:y-center w:d6 h:d6 bd:round-full bg-color:ok text:paper child:no-shrink")}">${icon('check')}</span>`;
|
|
1166
|
+
const act = action ? `<button data-toast-action class="${ui("bd:width-0 cursor:pointer child:no-shrink h:d8 pd-x:d4 bd:round-pill bg-color:paper text:ink font:small:semibold @hover:[bg-color:proof-soft] @focus-visible:[outline:d0:solid:proof] transition:fast")}">${esc(action.label)}</button>` : '';
|
|
1167
|
+
el.innerHTML = `<div class="${ui("row:y-start gap:d3 w:toast pd:d3:d4 bg-color:ink text:paper bd:round-d4 shadow:float")}"><span class="${ui("pd-y:d0")}">${tone}</span><p class="${ui("child:grow text:paper:normal format:pre-line")}">${esc(message)}</p>${act}</div>`;
|
|
1168
|
+
if (action) {
|
|
1169
|
+
el.querySelector('[data-toast-action]').addEventListener('click', () => { hide(el); action.run(); });
|
|
1170
|
+
}
|
|
1171
|
+
show(el);
|
|
1172
|
+
clearTimeout(toastTimer);
|
|
1173
|
+
toastTimer = setTimeout(() => hide(el), kind === 'error' ? 9000 : action ? 8000 : 3500);
|
|
1174
|
+
}
|
|
1175
|
+
|
|
1176
|
+
// ════ Page menu ════
|
|
1177
|
+
|
|
1178
|
+
const touch = matchMedia('(hover: none)').matches;
|
|
1179
|
+
// Tools in the page menu. One that also has a bar button shows here only on
|
|
1180
|
+
// a phone, where the bar has no room for it.
|
|
1181
|
+
function menuTools() {
|
|
1182
|
+
const onBar = new Set(verso.menuItems.filter((m) => m.phoneOnly).map((m) => m.label));
|
|
1183
|
+
const seen = new Set();
|
|
1184
|
+
const out = [];
|
|
1185
|
+
verso.menuItems.forEach((m, i) => {
|
|
1186
|
+
if (seen.has(m.label)) return;
|
|
1187
|
+
if (!m.phoneOnly && onBar.has(m.label)) return;
|
|
1188
|
+
seen.add(m.label);
|
|
1189
|
+
out.push({ m, i, phoneOnly: m.phoneOnly || onBar.has(m.label) });
|
|
1190
|
+
});
|
|
1191
|
+
// In the bar's order; anything else after.
|
|
1192
|
+
const rank = (label) => { const at = BAR_ORDER.indexOf(label); return at === -1 ? BAR_ORDER.length : at; };
|
|
1193
|
+
return out.sort((a, b) => rank(a.m.label) - rank(b.m.label));
|
|
1194
|
+
}
|
|
1195
|
+
|
|
1196
|
+
$('page').addEventListener('click', () => {
|
|
1197
|
+
const menu = $('menu');
|
|
1198
|
+
if (isShown(menu)) return hide(menu);
|
|
1199
|
+
hide($('publish-tip'));
|
|
1200
|
+
menu.innerHTML = `${(data.pages || []).map((p) => `
|
|
1201
|
+
<a href="${esc(p.url)}" class="${p.url === data.url ? ui("row:y-center:x-between gap:d3 pd:d3 bd:round-d3 bg-color:ink-2 text:paper") : ui("row:y-center:x-between gap:d3 pd:d3 bd:round-d3 text:paper @hover:[bg-color:ink-2] transition:fast")}">
|
|
1202
|
+
<span class="${ui("col gap:d0 min-w:0")}"><span class="${ui("font:medium overflow:hidden text-overflow:ellipsis format:no-wrap")}">${esc(p.label)}</span><span class="${ui("font:tiny text:mist overflow:hidden text-overflow:ellipsis format:no-wrap")}">${esc(p.url)}</span></span>
|
|
1203
|
+
${p.url === data.url ? `<span class="${ui("text:proof")}">${icon('check')}</span>` : ''}
|
|
1204
|
+
</a>`).join('')}
|
|
1205
|
+
<button id="new-page" class="${ui("bg-color:transparent bd:width-0 cursor:pointer row:y-center gap:d2 pd:d3 bd:round-d3 text:paper font:medium @hover:[bg-color:ink-2] transition:fast")}">${icon('plus')}<span>New page</span></button>
|
|
1206
|
+
<span class="${ui("h:px mg-y:d1 bg-color:ink-3")}"></span>
|
|
1207
|
+
<p class="${ui("pd:d1:d3 font:tiny:semibold text:mist")}">Tools</p>
|
|
1208
|
+
<button data-menu-undo class="${ui("bg-color:transparent bd:width-0 cursor:pointer row:y-center gap:d2 pd:d3 bd:round-d3 text:paper font:medium @hover:[bg-color:ink-2] @disabled:[text:ink-3_cursor:default] transition:fast /xs/ hidden")}" ${past.length ? '' : 'disabled'}>${icon('undo')}<span>Undo</span></button>
|
|
1209
|
+
<button data-menu-redo class="${ui("bg-color:transparent bd:width-0 cursor:pointer row:y-center gap:d2 pd:d3 bd:round-d3 text:paper font:medium @hover:[bg-color:ink-2] @disabled:[text:ink-3_cursor:default] transition:fast /xs/ hidden")}" ${future.length ? '' : 'disabled'}>${icon('redo')}<span>Redo</span></button>
|
|
1210
|
+
${menuTools().map(({ m, i, phoneOnly }) => `<button data-ext-menu="${i}" class="${phoneOnly ? ui("bg-color:transparent bd:width-0 cursor:pointer row:y-center gap:d2 pd:d3 bd:round-d3 text:paper font:medium @hover:[bg-color:ink-2] transition:fast /md/ hidden") : ui("bg-color:transparent bd:width-0 cursor:pointer row:y-center gap:d2 pd:d3 bd:round-d3 text:paper font:medium @hover:[bg-color:ink-2] transition:fast")}">${m.icon || ''}<span class="${ui("child:grow text:left")}">${esc(m.label)}</span>${m.hint && !touch ? `<span class="${ui("font:tiny text:mist")}">${esc(m.hint)}</span>` : ''}</button>`).join('')}`;
|
|
1211
|
+
menu.querySelector('[data-menu-undo]')?.addEventListener('click', () => { hide(menu); undoStep(); });
|
|
1212
|
+
menu.querySelector('[data-menu-redo]')?.addEventListener('click', () => { hide(menu); redoStep(); });
|
|
1213
|
+
menu.querySelectorAll('[data-ext-menu]').forEach((b) => b.addEventListener('click', () => { hide(menu); verso.menuItems[Number(b.dataset.extMenu)].run(); }));
|
|
1214
|
+
root.getElementById('new-page').addEventListener('click', () => {
|
|
1215
|
+
hide(menu);
|
|
1216
|
+
import('/__verso/new-page.js')
|
|
1217
|
+
.then((m) => m.openNewPage({ root, data, ui, toast, icon }))
|
|
1218
|
+
.catch(() => toast('The new page window couldn\'t open. Reload the page and try again.', 'error'));
|
|
1219
|
+
});
|
|
1220
|
+
show(menu, 'flex');
|
|
1221
|
+
});
|
|
1222
|
+
|
|
1223
|
+
document.addEventListener('mousedown', (e) => {
|
|
1224
|
+
if (!e.composedPath().includes(host)) hide($('menu'));
|
|
1225
|
+
});
|
|
1226
|
+
|
|
1227
|
+
async function refreshPages() {
|
|
1228
|
+
try {
|
|
1229
|
+
const out = await (await fetch('/__verso/pages')).json();
|
|
1230
|
+
if (Array.isArray(out.pages)) data.pages = out.pages;
|
|
1231
|
+
} catch {
|
|
1232
|
+
// The menu keeps the list it had.
|
|
1233
|
+
}
|
|
1234
|
+
}
|
|
1235
|
+
|
|
1236
|
+
// ════ Publish ════
|
|
1237
|
+
|
|
1238
|
+
let statusTimer = 0;
|
|
1239
|
+
const refreshStatusSoon = () => {
|
|
1240
|
+
clearTimeout(statusTimer);
|
|
1241
|
+
statusTimer = setTimeout(refreshStatus, 600);
|
|
1242
|
+
};
|
|
1243
|
+
|
|
1244
|
+
async function refreshStatus() {
|
|
1245
|
+
try {
|
|
1246
|
+
summary = await (await fetch('/__verso/status')).json();
|
|
1247
|
+
} catch {
|
|
1248
|
+
return;
|
|
1249
|
+
}
|
|
1250
|
+
const btn = $('publish');
|
|
1251
|
+
const changes = summary.changes || [];
|
|
1252
|
+
const count = changes.length || (summary.pending ? 1 : 0);
|
|
1253
|
+
if (!summary.pending) {
|
|
1254
|
+
// Nothing waiting. Online, that's "Published"; without a place to
|
|
1255
|
+
// publish to, it's only saved here.
|
|
1256
|
+
btn.className = ui("bd:width-0 cursor:pointer row:y-center gap:d2 h:d10 pd-x:d3 bd:round-pill bg-color:ink-2 text:mist font:semibold format:no-wrap @focus-visible:[outline:d0:solid:paper] transition:fast /xs/ pd-x:d5");
|
|
1257
|
+
btn.innerHTML = `${icon('check')}<span>${summary.remote || summary.live ? 'Published' : 'Saved'}</span>${summary.remote || summary.live ? '' : `<span class="${ui("hidden font:tiny:normal text:mist /lg/ inline")}">Not online yet</span>`}`;
|
|
1258
|
+
btn.setAttribute('aria-label', summary.remote || summary.live ? 'Everything is published' : 'Saved on this computer. Not online yet');
|
|
1259
|
+
} else {
|
|
1260
|
+
btn.className = ui("bd:width-0 cursor:pointer row:y-center gap:d2 h:d10 pd-x:d3 bd:round-pill bg-color:proof text:paper font:semibold @hover:[bg-color:proof-2] @focus-visible:[outline:d0:solid:paper] transition:fast format:no-wrap /xs/ pd-x:d5");
|
|
1261
|
+
btn.innerHTML = `<span>Publish</span>${count ? `<span class="${ui("row:x-center:y-center min-w:d5 h:d5 pd-x:d1 bd:round-full bg-color:paper text:proof-2 font:tiny:bold")}" aria-hidden="true">${count}</span>` : ''}`;
|
|
1262
|
+
btn.setAttribute('aria-label', `Publish ${count} change${count === 1 ? '' : 's'}`);
|
|
1263
|
+
}
|
|
1264
|
+
if (lastStatus) setStatus(...lastStatus);
|
|
1265
|
+
// Beside the status: what's waiting, as a button that lists it.
|
|
1266
|
+
let what = root.getElementById('what-changed');
|
|
1267
|
+
if (summary.pending && count) {
|
|
1268
|
+
if (!what) {
|
|
1269
|
+
what = document.createElement('button');
|
|
1270
|
+
what.id = 'what-changed';
|
|
1271
|
+
what.className = ui("hidden bg-color:transparent bd:width-0 cursor:pointer h:d10 pd-x:d2 bd:round-pill text:mist:underline font:small @hover:[text:paper] @focus-visible:[outline:d0:solid:proof] transition:fast format:no-wrap /lg/ inline");
|
|
1272
|
+
what.addEventListener('click', toggleChanges);
|
|
1273
|
+
$('status').after(what);
|
|
1274
|
+
}
|
|
1275
|
+
const pages = changes.filter((c) => c.kind !== 'other').length;
|
|
1276
|
+
what.textContent = pages ? `${pages} page${pages === 1 ? '' : 's'} changed` : `${count} change${count === 1 ? '' : 's'}`;
|
|
1277
|
+
} else if (what) {
|
|
1278
|
+
what.remove();
|
|
1279
|
+
hide($('changes'));
|
|
1280
|
+
}
|
|
1281
|
+
}
|
|
1282
|
+
|
|
1283
|
+
// What Publish will send, page by page.
|
|
1284
|
+
function toggleChanges() {
|
|
1285
|
+
const box = $('changes');
|
|
1286
|
+
if (isShown(box)) return hide(box);
|
|
1287
|
+
hide($('publish-tip'));
|
|
1288
|
+
const changes = summary?.changes || [];
|
|
1289
|
+
const line = (c) => {
|
|
1290
|
+
const what = c.kind === 'added' ? 'New page' : c.kind === 'removed' ? 'Removed' : c.parts.length ? c.parts.join(', ') : 'Changed';
|
|
1291
|
+
return `<li class="${ui("col gap:d0 pd-y:d2 bd-b:width-px:solid:line")}"><span class="${ui("font:small:semibold text:ink")}">${esc(c.label)}</span><span class="${ui("font:small text:ink-3")}">${esc(what.charAt(0).toUpperCase() + what.slice(1))}</span></li>`;
|
|
1292
|
+
};
|
|
1293
|
+
box.innerHTML = `
|
|
1294
|
+
<div class="${ui("row:y-center:x-between gap:d3")}"><h2 class="${ui("font:base:semibold text:ink")}">Waiting to publish</h2>
|
|
1295
|
+
<button data-close class="${ui("bg-color:transparent bd:width-0 cursor:pointer row:x-center:y-center w:d8 h:d8 bd:round-full text:ink-3 @hover:[bg-color:paper-2] transition:fast")}" aria-label="Close">${icon('close')}</button></div>
|
|
1296
|
+
<ul class="${ui("col list-style-type:none")}">${changes.map(line).join('')}</ul>
|
|
1297
|
+
${changes.length ? `
|
|
1298
|
+
<label class="${ui("col gap:d1 pd-t:d2")}">
|
|
1299
|
+
<span class="${ui("font:small:medium text:ink")}">What changed? <span class="${ui("font:normal text:ink-3")}">If you like</span></span>
|
|
1300
|
+
<input id="publish-note" maxlength="200" class="${ui("w:full h:d10 pd-x:d3 bd:round-d3 bd:width-px:solid:line bg-color:paper font:small text:ink @focus:[bd:proof_shadow:proof-focus_outline:none] transition:fast")}" placeholder="${esc(summary?.message || 'A few words for History')}">
|
|
1301
|
+
<span class="${ui("font:tiny text:ink-3")}">History shows this beside the date. Left empty, it says “${esc(summary?.message || 'what changed')}”.</span>
|
|
1302
|
+
</label>
|
|
1303
|
+
<button data-publish-now class="${ui("bd:width-0 cursor:pointer w:fit-content h:d10 pd-x:d5 bd:round-pill bg-color:proof text:paper font:small:semibold @hover:[bg-color:proof-2] @focus-visible:[outline:d0:solid:ink] transition:fast")}">Publish</button>` : ''}
|
|
1304
|
+
${summary?.remote || summary?.live ? '' : `<p class="${ui("font:small text:ink-3")}">Not online yet: this folder isn't connected to a GitHub repository, so Publish saves a restore point here.</p>`}`;
|
|
1305
|
+
box.querySelector('[data-close]').addEventListener('click', () => hide(box));
|
|
1306
|
+
box.querySelector('[data-publish-now]')?.addEventListener('click', () => $('publish').click());
|
|
1307
|
+
box.querySelector('#publish-note')?.addEventListener('keydown', (e) => { if (e.key === 'Enter') { e.preventDefault(); $('publish').click(); } });
|
|
1308
|
+
show(box, 'flex');
|
|
1309
|
+
}
|
|
1310
|
+
|
|
1311
|
+
$('publish').addEventListener('mouseenter', () => {
|
|
1312
|
+
if (!summary || isShown($('menu')) || isShown($('changes'))) return;
|
|
1313
|
+
const tip = $('publish-tip');
|
|
1314
|
+
if (!summary.repo) tip.textContent = 'This folder isn\'t a git repository yet.';
|
|
1315
|
+
else if (!summary.pending && !summary.remote && !summary.live) tip.textContent = 'Saved here. Not online yet: connect this folder to a GitHub repository, and Publish will put it there.';
|
|
1316
|
+
else if (!summary.pending) tip.textContent = 'Everything is published.';
|
|
1317
|
+
else if (summary.message) tip.textContent = summary.message;
|
|
1318
|
+
else tip.textContent = 'Saved restore points are waiting to go online.';
|
|
1319
|
+
show(tip);
|
|
1320
|
+
});
|
|
1321
|
+
$('publish').addEventListener('mouseleave', () => hide($('publish-tip')));
|
|
1322
|
+
|
|
1323
|
+
$('publish').addEventListener('click', async () => {
|
|
1324
|
+
const btn = $('publish');
|
|
1325
|
+
if (btn.dataset.busy) return;
|
|
1326
|
+
hide($('publish-tip'));
|
|
1327
|
+
// The first press shows what's going and asks, if you like, what changed;
|
|
1328
|
+
// the second (or Enter) publishes.
|
|
1329
|
+
if ((summary?.changes || []).length && !isShown($('changes'))) {
|
|
1330
|
+
toggleChanges();
|
|
1331
|
+
root.getElementById('publish-note')?.focus();
|
|
1332
|
+
return;
|
|
1333
|
+
}
|
|
1334
|
+
const note = root.getElementById('publish-note')?.value || '';
|
|
1335
|
+
if (editEl) stopEditing();
|
|
1336
|
+
if (activeRich) leaveRich(activeRich);
|
|
1337
|
+
closeImagePop();
|
|
1338
|
+
await flush();
|
|
1339
|
+
btn.dataset.busy = '1';
|
|
1340
|
+
btn.innerHTML = `<span class="${ui("w:d3 h:d3 bd:round-full bd:width-d0:solid text:ink-3 bd-t:paper animation:(verso-spin_0.8s_linear_infinite)")}"></span><span>Publishing…</span>`;
|
|
1341
|
+
try {
|
|
1342
|
+
const res = await fetch('/__verso/publish', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ note }) });
|
|
1343
|
+
const out = await res.json();
|
|
1344
|
+
if (out.problems?.length) showProblems(out.problems, 'Fix these before publishing');
|
|
1345
|
+
hide($('changes'));
|
|
1346
|
+
if (out.ok && !out.nothing && data.draft) {
|
|
1347
|
+
// Published, but this page stays off the live site until it's live.
|
|
1348
|
+
toast(`${out.local ? 'Saved' : 'Published'}. ${data.label} is a draft, so it's not on the live site.`, 'ok', { label: 'Make live', run: makeLive });
|
|
1349
|
+
} else toast(out.message, out.ok ? 'ok' : 'error');
|
|
1350
|
+
} catch {
|
|
1351
|
+
toast('Verso isn\'t running, so nothing was published. Start it again with "npm run dev".', 'error');
|
|
1352
|
+
} finally {
|
|
1353
|
+
delete btn.dataset.busy;
|
|
1354
|
+
refreshStatus();
|
|
1355
|
+
}
|
|
1356
|
+
});
|
|
1357
|
+
|
|
1358
|
+
refreshStatus();
|
|
1359
|
+
|
|
1360
|
+
// Takes this page out of drafts.
|
|
1361
|
+
async function makeLive() {
|
|
1362
|
+
try {
|
|
1363
|
+
const res = await fetch('/__verso/draft', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ url: data.url, draft: false }) });
|
|
1364
|
+
const out = await res.json();
|
|
1365
|
+
if (!res.ok || out.ok === false) return toast(out.message || 'That page couldn\'t be made live.', 'error');
|
|
1366
|
+
try { sessionStorage.setItem('verso-site-view-toast', JSON.stringify({ message: `${data.label} is live. Publish to put it online.` })); } catch {}
|
|
1367
|
+
location.reload();
|
|
1368
|
+
} catch {
|
|
1369
|
+
toast('Verso isn\'t running, so the page is still a draft.', 'error');
|
|
1370
|
+
}
|
|
1371
|
+
}
|
|
1372
|
+
|
|
1373
|
+
// ════ Bar tooltips ════
|
|
1374
|
+
// Every icon in the bar names itself on hover and focus.
|
|
1375
|
+
{
|
|
1376
|
+
const tip = $('bar-tip');
|
|
1377
|
+
const showTip = (b) => {
|
|
1378
|
+
const label = b.dataset.tip;
|
|
1379
|
+
if (!label) return;
|
|
1380
|
+
tip.textContent = label;
|
|
1381
|
+
show(tip);
|
|
1382
|
+
const r = b.getBoundingClientRect();
|
|
1383
|
+
const w = tip.offsetWidth;
|
|
1384
|
+
tip.style.left = `${Math.max(8, Math.min(innerWidth - w - 8, r.left + r.width / 2 - w / 2))}px`;
|
|
1385
|
+
tip.style.top = `${r.top - tip.offsetHeight - 8}px`;
|
|
1386
|
+
};
|
|
1387
|
+
$('bar').addEventListener('mouseover', (e) => { const b = e.target.closest?.('[data-tip]'); if (b) showTip(b); });
|
|
1388
|
+
$('bar').addEventListener('mouseout', (e) => { if (e.target.closest?.('[data-tip]')) hide(tip); });
|
|
1389
|
+
$('bar').addEventListener('focusin', (e) => { const b = e.target.closest?.('[data-tip]'); if (b) showTip(b); });
|
|
1390
|
+
$('bar').addEventListener('focusout', () => hide(tip));
|
|
1391
|
+
}
|
|
1392
|
+
|
|
1393
|
+
// ════ First run ════
|
|
1394
|
+
// Once, on a site's first visit: how editing works, in one line.
|
|
1395
|
+
{
|
|
1396
|
+
let seen = true;
|
|
1397
|
+
try { seen = localStorage.getItem('verso-first-run') === 'done'; } catch {}
|
|
1398
|
+
if (!seen && !FRAMED) {
|
|
1399
|
+
const box = $('first-run');
|
|
1400
|
+
box.innerHTML = `<p class="${ui("child:grow font:small:medium text:paper:normal")}">Click any words or picture to change them. Press Publish when you're done.</p>
|
|
1401
|
+
<button class="${ui("bd:width-0 cursor:pointer child:no-shrink h:d8 pd-x:d4 bd:round-pill bg-color:paper text:ink font:small:semibold @hover:[bg-color:proof-soft] @focus-visible:[outline:d0:solid:ink] transition:fast")}">Got it</button>`;
|
|
1402
|
+
const done = () => { hide(box); try { localStorage.setItem('verso-first-run', 'done'); } catch {} };
|
|
1403
|
+
box.querySelector('button').addEventListener('click', done);
|
|
1404
|
+
show(box, 'flex');
|
|
1405
|
+
// Editing something counts as having read it.
|
|
1406
|
+
document.addEventListener('focusin', (e) => { if (e.target.closest?.('[data-verso-field],[data-verso-rich]')) done(); }, { once: true });
|
|
1407
|
+
}
|
|
1408
|
+
}
|
|
1409
|
+
|
|
1410
|
+
// ════ Page settings ════
|
|
1411
|
+
|
|
1412
|
+
// Tags and dates can show on the page itself, so once they're saved the page
|
|
1413
|
+
// is drawn again, with these settings still open where you were.
|
|
1414
|
+
let settingTimer = null;
|
|
1415
|
+
function showSettingOnPage(focusId) {
|
|
1416
|
+
clearTimeout(settingTimer);
|
|
1417
|
+
settingTimer = setTimeout(async () => {
|
|
1418
|
+
const typing = root.getElementById('tag-input')?.value.trim();
|
|
1419
|
+
if (typing || !isShown($('settings'))) return;
|
|
1420
|
+
await flush();
|
|
1421
|
+
try { sessionStorage.setItem('verso-reopen-settings', JSON.stringify({ focus: focusId, scroll: $('settings').scrollTop })); } catch {}
|
|
1422
|
+
maybeReload();
|
|
1423
|
+
}, 900);
|
|
1424
|
+
}
|
|
1425
|
+
|
|
1426
|
+
const INPUT = ui("w:full h:d11 pd-x:d3 bd:round-d3 bd:width-px:solid:line bg-color:paper font:small text:ink @focus:[bd:proof_shadow:proof-focus_outline:none] transition:fast");
|
|
1427
|
+
|
|
1428
|
+
function openSettings() {
|
|
1429
|
+
hide($('menu'));
|
|
1430
|
+
const panel = $('settings');
|
|
1431
|
+
const scroll = panel.scrollTop;
|
|
1432
|
+
const offPage = (data.fields || []).filter((f) => f.offPage && !f.onPage);
|
|
1433
|
+
// Settings fields that also show on the page (a cover picture, say) are
|
|
1434
|
+
// grouped apart from the ones that live only here (a share image).
|
|
1435
|
+
const onThisPage = (f) => !!document.querySelector(`[data-verso-image="${CSS.escape(f.name)}"],[data-verso-field="${CSS.escape(f.name)}"],[data-verso-rich="${CSS.escape(f.name)}"]`);
|
|
1436
|
+
const alsoHere = offPage.filter(onThisPage);
|
|
1437
|
+
const onlyHere = offPage.filter((f) => !onThisPage(f));
|
|
1438
|
+
const titlePlaceholder = data.label ? `${data.label}` : 'Page title';
|
|
1439
|
+
const offPageField = (f) => {
|
|
1440
|
+
const label = `<span class="${ui("font:small:medium text:ink")}">${esc(f.label)}${f.required ? ` <span class="${ui("text:proof-2 font:tiny")}">Required</span>` : ''}</span>`;
|
|
1441
|
+
if (f.type === 'image') {
|
|
1442
|
+
const v = values[f.name];
|
|
1443
|
+
return `
|
|
1444
|
+
<div class="${ui("col gap:d2")}">
|
|
1445
|
+
${label}
|
|
1446
|
+
${v?.file ? `<img src="${esc(imageUrl(v.file))}" alt="" class="${ui("w:full h:c8 fit:cover bd:round-d3 bg-color:paper-2")}">` : ''}
|
|
1447
|
+
<div class="${ui("row:y-center gap:d2")}">
|
|
1448
|
+
<button data-choose="${esc(f.name)}" class="${ui("bd:width-0 cursor:pointer row:y-center gap:d2 h:d9 pd-x:d4 bd:round-pill bg-color:ink text:paper font:small:semibold @hover:[bg-color:ink-2] transition:fast")}">${icon('upload')}<span>${v?.file ? 'Replace' : 'Choose an image'}</span></button>
|
|
1449
|
+
${v?.file ? `<button data-remove="${esc(f.name)}" class="${ui("bg-color:transparent bd:width-0 cursor:pointer row:y-center gap:d1 h:d9 pd-x:d3 bd:round-pill text:proof-2 font:small:medium @hover:[bg-color:proof-soft] transition:fast")}">${icon('trash')}<span>Remove</span></button>` : ''}
|
|
1450
|
+
</div>
|
|
1451
|
+
${v?.file ? `<input data-alt="${esc(f.name)}" class="${INPUT}" placeholder="Description: what the picture shows" aria-label="Description: what the picture shows" value="${esc(v.alt || '')}">` : ''}
|
|
1452
|
+
</div>`;
|
|
1453
|
+
}
|
|
1454
|
+
if (f.type === 'color') {
|
|
1455
|
+
const current = values[f.name]?.color || '';
|
|
1456
|
+
const swatch = ([name, value]) => `
|
|
1457
|
+
<button data-color-field="${esc(f.name)}" data-color="${esc(name)}" title="${esc(name)}" aria-label="${esc(name)}" aria-pressed="${name === current}" class="${name === current ? ui("cursor:pointer w:d8 h:d8 bd:round-full bd:width-d0:solid:ink shadow:proof-ring") : ui("cursor:pointer w:d8 h:d8 bd:round-full bd:width-px:solid:line @hover:[shadow:proof-focus] transition:fast")}" style="background:${esc(value)}"></button>`;
|
|
1458
|
+
// The site's own colours first; Elevate's built-in ones are tucked away
|
|
1459
|
+
// (and opened when one of them is the choice).
|
|
1460
|
+
const own = Object.entries(data.colors || {}).filter(([name]) => (data.ownColors || []).includes(name));
|
|
1461
|
+
const rest = Object.entries(data.colors || {}).filter(([name]) => !(data.ownColors || []).includes(name));
|
|
1462
|
+
const row = (list) => `<div class="${ui("row:wrap gap:d1 pd:d1")}">${list.map(swatch).join('')}</div>`;
|
|
1463
|
+
const swatches = own.length && rest.length
|
|
1464
|
+
? `${row(own)}<details${rest.some(([name]) => name === current) ? ' open' : ''}><summary class="${ui("font:tiny:medium text:ink-3 cursor:pointer")}">More colours</summary>${row(rest)}</details>`
|
|
1465
|
+
: row(own.length ? own : rest);
|
|
1466
|
+
return `
|
|
1467
|
+
<div class="${ui("col gap:d2")}">
|
|
1468
|
+
${label}
|
|
1469
|
+
<p class="${ui("font:tiny text:mist")}">${current ? esc(current) : 'None chosen'}</p>
|
|
1470
|
+
<div class="${ui("col gap:d1 max-h:c12 overflow-y:auto")}">${swatches}</div>
|
|
1471
|
+
</div>`;
|
|
1472
|
+
}
|
|
1473
|
+
return `
|
|
1474
|
+
<label class="${ui("col gap:d2")}">
|
|
1475
|
+
${label}
|
|
1476
|
+
<input data-field="${esc(f.name)}" class="${INPUT}" value="${esc(values[f.name] || '')}">
|
|
1477
|
+
</label>`;
|
|
1478
|
+
};
|
|
1479
|
+
panel.innerHTML = `
|
|
1480
|
+
<header class="${ui("row:y-center:x-between pd:d5:d5:d3 sticky top:0 bg-color:paper z:1")}">
|
|
1481
|
+
<div class="${ui("col gap:d0")}">
|
|
1482
|
+
<h2 class="${ui("font:h6:semibold text:ink")}">Page settings</h2>
|
|
1483
|
+
<p class="${ui("font:tiny text:mist")}">${esc(data.label)}, ${esc(data.url)}</p>
|
|
1484
|
+
</div>
|
|
1485
|
+
<button id="close-settings" class="${ui("bg-color:transparent bd:width-0 cursor:pointer row:x-center:y-center w:d9 h:d9 bd:round-full text:ink @hover:[bg-color:paper-2] @focus-visible:[outline:d0:solid:proof] transition:fast")}" aria-label="Close settings">${icon('close')}</button>
|
|
1486
|
+
</header>
|
|
1487
|
+
<div class="${ui("col gap:d6 pd-x:d5 pd-t:d3 pd-b:d6")}">
|
|
1488
|
+
<section class="${ui("col gap:d4")}">
|
|
1489
|
+
<h3 class="${ui("font:small:medium text:mist")}">Search and sharing</h3>
|
|
1490
|
+
<label class="${ui("col gap:d2")}">
|
|
1491
|
+
<span class="${ui("row:x-between font:small:medium text:ink")}">Title <span id="title-count" class="${ui("font:tiny text:mist")}"></span></span>
|
|
1492
|
+
<input id="set-title" class="${INPUT}" maxlength="300" placeholder="${esc(titlePlaceholder)}">
|
|
1493
|
+
</label>
|
|
1494
|
+
<label class="${ui("col gap:d2")}">
|
|
1495
|
+
<span class="${ui("row:x-between font:small:medium text:ink")}">Description <span id="desc-count" class="${ui("font:tiny text:mist")}"></span></span>
|
|
1496
|
+
<textarea id="set-desc" rows="3" class="${ui("w:full pd:d2:d3 bd:round-d3 bd:width-px:solid:line bg-color:paper font:small:normal text:ink resize:vertical @focus:[bd:proof_shadow:proof-focus_outline:none] transition:fast")}" maxlength="1000" placeholder="One or two sentences for search results and link previews."></textarea>
|
|
1497
|
+
</label>
|
|
1498
|
+
<div class="${ui("col gap:d1 pd:d4 bd:round-d4 bg-color:paper-2")}">
|
|
1499
|
+
<span class="${ui("font:tiny text:ok-2 overflow:hidden text-overflow:ellipsis format:no-wrap")}">${esc(location.host)}${esc(data.url)}</span>
|
|
1500
|
+
<span id="preview-title" class="${ui("font:base:medium text:link:snug")}"></span>
|
|
1501
|
+
<span id="preview-desc" class="${ui("font:small:normal text:ink-3")}"></span>
|
|
1502
|
+
</div>
|
|
1503
|
+
</section>
|
|
1504
|
+
<section class="${ui("col gap:d4")}">
|
|
1505
|
+
<h3 class="${ui("font:small:medium text:mist")}">Date</h3>
|
|
1506
|
+
<label class="${ui("col gap:d2")}">
|
|
1507
|
+
<span class="${ui("font:small:medium text:ink")}">Published on</span>
|
|
1508
|
+
<input id="set-date" type="date" class="${INPUT}">
|
|
1509
|
+
<span class="${ui("font:tiny text:mist")}">Lists of pages are sorted by this date.</span>
|
|
1510
|
+
</label>
|
|
1511
|
+
</section>
|
|
1512
|
+
<section class="${ui("col gap:d3")}">
|
|
1513
|
+
<h3 class="${ui("font:small:medium text:mist")}">Tags</h3>
|
|
1514
|
+
<div id="set-tags" class="${ui("row:wrap:y-center gap:d1 w:full min-h:d11 pd:d1 bd:round-d3 bd:width-px:solid:line bg-color:paper cursor:text transition:fast")}">
|
|
1515
|
+
${(data.tags || []).map((t, i) => `<span class="${ui("row:y-center gap:d0 h:d8 pd-l:d3 pd-r:d1 bd:round-pill bg-color:paper-2 text:ink font:small:medium format:no-wrap")}">${esc(t)}<button data-untag="${i}" class="${ui("bg-color:transparent bd:width-0 cursor:pointer row:x-center:y-center w:d6 h:d6 bd:round-full text:mist @hover:[bg-color:line_text:ink] @focus-visible:[outline:d0:solid:proof] transition:fast")}" aria-label="Remove the tag ${esc(t)}">${icon('close')}</button></span>`).join('')}
|
|
1516
|
+
<input id="tag-input" list="tag-suggestions" class="${ui("w:c10 h:d8 pd-x:d2 bd:width-0 bg-color:transparent font:small text:ink @focus:[outline:none]")}" placeholder="${(data.tags || []).length ? 'Add another' : 'Add a tag'}" aria-label="Add a tag">
|
|
1517
|
+
<datalist id="tag-suggestions">${(data.siteTags || []).filter((t) => !(data.tags || []).some((x) => x.toLowerCase() === t.toLowerCase())).map((t) => `<option value="${esc(t)}"></option>`).join('')}</datalist>
|
|
1518
|
+
</div>
|
|
1519
|
+
<span class="${ui("font:tiny text:mist")}">Press Enter or a comma after each tag. Pages with the same tag can be listed together.</span>
|
|
1520
|
+
</section>
|
|
1521
|
+
${(data.folders || []).length ? `
|
|
1522
|
+
<details class="${ui("col gap:d3")}" ${data.tagsOf ? 'open' : ''}>
|
|
1523
|
+
<summary class="${ui("font:small:medium text:mist cursor:pointer @hover:[text:ink]")}">Advanced</summary>
|
|
1524
|
+
<label class="${ui("col gap:d2 pd-t:d3")}">
|
|
1525
|
+
<span class="${ui("font:small:medium text:ink")}">Make this a tag page, listing the tags of</span>
|
|
1526
|
+
<select id="set-tags-of" class="${ui("w:full h:d11 pd-x:d3 bd:round-d3 bd:width-px:solid:line bg-color:paper font:small text:ink cursor:pointer @focus:[bd:proof_shadow:proof-focus_outline:none] transition:fast")}">
|
|
1527
|
+
<option value="">Nothing</option>
|
|
1528
|
+
${data.folders.filter((f) => f.url !== data.url && (f.pages > 0 || f.key === data.tagsOf)).map((f) => `<option value="${esc(f.key)}" ${f.key === data.tagsOf ? 'selected' : ''}>${esc(f.label)} (${esc(f.url)})</option>`).join('')}
|
|
1529
|
+
</select>
|
|
1530
|
+
<span id="tags-of-help" class="${ui("font:tiny text:mist")}"></span>
|
|
1531
|
+
</label>
|
|
1532
|
+
</details>` : ''}
|
|
1533
|
+
${data.url !== '/' && !data.tag ? `
|
|
1534
|
+
<details class="${ui("col gap:d3")}">
|
|
1535
|
+
<summary class="${ui("font:small:medium text:mist cursor:pointer @hover:[text:ink]")}">Address, and deleting this page</summary>
|
|
1536
|
+
<div class="${ui("col gap:d2 pd-t:d3")}">
|
|
1537
|
+
<label for="set-address" class="${ui("font:small:medium text:ink")}">Address</label>
|
|
1538
|
+
<div class="${ui("row:y-center gap:d2")}">
|
|
1539
|
+
<span class="${ui("font:small text:mist format:no-wrap")}">${esc(data.url.replace(/[^/]+\/$/, ''))}</span>
|
|
1540
|
+
<input id="set-address" class="${INPUT}" value="${esc(data.url.split('/').filter(Boolean).pop() || '')}" spellcheck="false" autocapitalize="off">
|
|
1541
|
+
<button id="do-address" class="${ui("bd:width-px:solid:line cursor:pointer child:no-shrink h:d11 pd-x:d4 bd:round-pill bg-color:paper text:ink font:small:semibold @hover:[bg-color:paper-2] @focus-visible:[outline:d0:solid:proof] transition:fast")}">Change</button>
|
|
1542
|
+
</div>
|
|
1543
|
+
<span class="${ui("font:tiny text:mist")}">Links to this page from the rest of the site follow it. Bookmarks and links on other sites will stop working.</span>
|
|
1544
|
+
</div>
|
|
1545
|
+
<div id="delete-box" class="${ui("col gap:d2 pd-t:d4")}">
|
|
1546
|
+
<button id="do-delete" class="${ui("bg-color:transparent bd:width-px:solid:line cursor:pointer w:fit-content h:d10 pd-x:d4 bd:round-pill text:proof-2 font:small:semibold @hover:[bg-color:proof-soft_bd:proof] @focus-visible:[outline:d0:solid:proof] transition:fast")}">Delete this page…</button>
|
|
1547
|
+
</div>
|
|
1548
|
+
</details>` : ''}
|
|
1549
|
+
${alsoHere.length ? `
|
|
1550
|
+
<section class="${ui("col gap:d4")}">
|
|
1551
|
+
<h3 class="${ui("font:small:medium text:mist")}">Also on this page</h3>
|
|
1552
|
+
${alsoHere.map(offPageField).join('')}
|
|
1553
|
+
</section>` : ''}
|
|
1554
|
+
${onlyHere.length ? `
|
|
1555
|
+
<section class="${ui("col gap:d4")}">
|
|
1556
|
+
<h3 class="${ui("font:small:medium text:mist")}">Only here</h3>
|
|
1557
|
+
<p class="${ui("font:tiny text:mist")}">These don't show on the page itself. They're used for search results and link previews, or by the page type.</p>
|
|
1558
|
+
${onlyHere.map(offPageField).join('')}
|
|
1559
|
+
</section>` : ''}
|
|
1560
|
+
${data.unused?.length ? `
|
|
1561
|
+
<section id="unused" class="${ui("col gap:d3 pd:d4 bd:round-d4 bg-color:proof-soft")}">
|
|
1562
|
+
<p class="${ui("font:small:normal text:ink")}">This page still has content for ${data.unused.map((n) => `<strong>${esc(n)}</strong>`).join(', ')}, which its page type no longer uses. It isn't shown anywhere, so it's safe to remove.</p>
|
|
1563
|
+
<button id="remove-unused" class="${ui("bd:width-0 cursor:pointer w:fit-content h:d9 pd-x:d4 bd:round-pill bg-color:ink text:paper font:small:semibold @hover:[bg-color:ink-2] transition:fast")}">Remove it</button>
|
|
1564
|
+
</section>` : ''}
|
|
1565
|
+
${verso.settingsSections.length ? verso.settingsSections.map((sec) => sec.html()).join('') : `
|
|
1566
|
+
<section class="${ui("col gap:d2")}">
|
|
1567
|
+
<h3 class="${ui("font:small:medium text:mist")}">Page type</h3>
|
|
1568
|
+
<p class="${ui("font:small text:ink")}">${esc(data.template || '—')} <span class="${ui("text:mist")}">(${esc(data.templateFile || '')})</span></p>
|
|
1569
|
+
</section>`}
|
|
1570
|
+
</div>`;
|
|
1571
|
+
verso.settingsSections.forEach((sec) => sec.bind?.(panel));
|
|
1572
|
+
const title = root.getElementById('set-title');
|
|
1573
|
+
const desc = root.getElementById('set-desc');
|
|
1574
|
+
const date = root.getElementById('set-date');
|
|
1575
|
+
title.value = data.title || '';
|
|
1576
|
+
desc.value = data.description || '';
|
|
1577
|
+
date.value = data.date || '';
|
|
1578
|
+
const preview = () => {
|
|
1579
|
+
root.getElementById('preview-title').textContent = title.value.trim() || titlePlaceholder;
|
|
1580
|
+
root.getElementById('preview-desc').textContent = desc.value.trim() || 'No description yet. Search engines will pick some text from the page.';
|
|
1581
|
+
root.getElementById('title-count').textContent = `${title.value.length}/60`;
|
|
1582
|
+
root.getElementById('desc-count').textContent = `${desc.value.length}/160`;
|
|
1583
|
+
};
|
|
1584
|
+
preview();
|
|
1585
|
+
// Settings: each input you leave is one step in the history.
|
|
1586
|
+
const setting = (input, key, label) => {
|
|
1587
|
+
let before = data[key] || '';
|
|
1588
|
+
input.addEventListener('focus', () => { before = data[key] || ''; });
|
|
1589
|
+
input.addEventListener('input', () => { data[key] = input.value; preview(); queue({ [key]: input.value }); });
|
|
1590
|
+
input.addEventListener('blur', () => record({ type: 'setting', name: key, label, before, after: data[key] || '' }));
|
|
1591
|
+
};
|
|
1592
|
+
setting(title, 'title', 'title');
|
|
1593
|
+
setting(desc, 'description', 'description');
|
|
1594
|
+
date.addEventListener('change', () => {
|
|
1595
|
+
if (date.value && !/^\d{4}-\d{2}-\d{2}$/.test(date.value)) return;
|
|
1596
|
+
const before = data.date || '';
|
|
1597
|
+
data.date = date.value;
|
|
1598
|
+
queue({ date: date.value });
|
|
1599
|
+
showSettingOnPage('set-date');
|
|
1600
|
+
record({ type: 'setting', name: 'date', label: 'date', before, after: date.value });
|
|
1601
|
+
});
|
|
1602
|
+
// Tag pages: this page lists every tag in a folder, with a page for each.
|
|
1603
|
+
// Changing the address, and deleting the page.
|
|
1604
|
+
const later = (message) => { try { sessionStorage.setItem('verso-site-view-toast', JSON.stringify({ message })); } catch {} };
|
|
1605
|
+
const ask = async (url, body) => {
|
|
1606
|
+
try {
|
|
1607
|
+
await flush();
|
|
1608
|
+
const res = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) });
|
|
1609
|
+
const out = await res.json();
|
|
1610
|
+
if (!res.ok || out.ok === false) { toast(out.message || 'That didn\'t work.', 'error'); return null; }
|
|
1611
|
+
return out;
|
|
1612
|
+
} catch {
|
|
1613
|
+
toast('Verso isn\'t running, so nothing changed.', 'error');
|
|
1614
|
+
return null;
|
|
1615
|
+
}
|
|
1616
|
+
};
|
|
1617
|
+
const changeAddress = async () => {
|
|
1618
|
+
const out = await ask('/__verso/page/address', { url: data.url, name: root.getElementById('set-address').value });
|
|
1619
|
+
if (!out || out.to === out.from) return;
|
|
1620
|
+
const links = out.links ? ` ${out.links} link${out.links === 1 ? '' : 's'} on the site followed it.` : '';
|
|
1621
|
+
const code = out.templates?.length ? ` ${out.templates.join(', ')} still link${out.templates.length === 1 ? 's' : ''} to the old address.` : '';
|
|
1622
|
+
later(`This page is now at ${out.to}.${links}${code}`);
|
|
1623
|
+
location.href = out.to;
|
|
1624
|
+
};
|
|
1625
|
+
root.getElementById('do-address')?.addEventListener('click', changeAddress);
|
|
1626
|
+
root.getElementById('set-address')?.addEventListener('keydown', (e) => { if (e.key === 'Enter') { e.preventDefault(); changeAddress(); } });
|
|
1627
|
+
root.getElementById('do-delete')?.addEventListener('click', () => {
|
|
1628
|
+
const inside = (data.pages || []).filter((pg) => pg.url !== data.url && pg.url.startsWith(data.url)).length;
|
|
1629
|
+
const box = root.getElementById('delete-box');
|
|
1630
|
+
box.className = ui("col gap:d3 mg-t:d4 pd:d4 bd:round-d4 bg-color:proof-soft");
|
|
1631
|
+
box.innerHTML = `
|
|
1632
|
+
<p class="${ui("font:small:normal text:ink")}">Delete <strong>${esc(data.label)}</strong>${inside ? ` and the ${inside} page${inside === 1 ? '' : 's'} inside it` : ''}? ${inside ? 'Their' : 'Its'} words and pictures go too. What's been published can be brought back from History.</p>
|
|
1633
|
+
<div class="${ui("row:wrap gap:d2")}">
|
|
1634
|
+
<button id="yes-delete" class="${ui("bd:width-0 cursor:pointer h:d10 pd-x:d4 bd:round-pill bg-color:proof text:paper font:small:semibold @hover:[bg-color:proof-2] @focus-visible:[outline:d0:solid:ink] transition:fast")}">${inside ? `Delete all ${inside + 1} pages` : 'Delete it'}</button>
|
|
1635
|
+
<button id="no-delete" class="${ui("bd:width-px:solid:line cursor:pointer h:d10 pd-x:d4 bd:round-pill bg-color:paper text:ink font:small:semibold @hover:[bg-color:paper-2] @focus-visible:[outline:d0:solid:proof] transition:fast")}">Keep it</button>
|
|
1636
|
+
</div>`;
|
|
1637
|
+
root.getElementById('no-delete').addEventListener('click', () => openSettings());
|
|
1638
|
+
root.getElementById('yes-delete').addEventListener('click', async () => {
|
|
1639
|
+
const out = await ask('/__verso/page/delete', { url: data.url, inside: true });
|
|
1640
|
+
if (!out) return;
|
|
1641
|
+
const linked = out.linked?.length ? ` ${out.linked.slice(0, 3).join(', ')}${out.linked.length > 3 ? ` and ${out.linked.length - 3} more` : ''} still link${out.linked.length === 1 ? 's' : ''} to it.` : '';
|
|
1642
|
+
const lists = out.lists?.length ? ` ${out.lists.join(', ')} listed its pages, and needs changing.` : '';
|
|
1643
|
+
later(`Deleted ${out.label}.${linked}${lists}`);
|
|
1644
|
+
location.href = out.parent || '/';
|
|
1645
|
+
});
|
|
1646
|
+
root.getElementById('no-delete').focus();
|
|
1647
|
+
});
|
|
1648
|
+
|
|
1649
|
+
const tagsOf = root.getElementById('set-tags-of');
|
|
1650
|
+
if (tagsOf) {
|
|
1651
|
+
const help = () => {
|
|
1652
|
+
const f = (data.folders || []).find((x) => x.key === tagsOf.value);
|
|
1653
|
+
root.getElementById('tags-of-help').textContent = f
|
|
1654
|
+
? `This page becomes the list of every tag in ${f.label}, with a page for each tag under it, like ${data.url}design/.`
|
|
1655
|
+
: 'Choose a folder to make this page the list of its tags.';
|
|
1656
|
+
};
|
|
1657
|
+
help();
|
|
1658
|
+
tagsOf.addEventListener('change', () => {
|
|
1659
|
+
const before = data.tagsOf || '';
|
|
1660
|
+
data.tagsOf = tagsOf.value;
|
|
1661
|
+
help();
|
|
1662
|
+
queue({ tagsOf: tagsOf.value });
|
|
1663
|
+
record({ type: 'setting', name: 'tagsOf', label: 'tag pages', before, after: tagsOf.value });
|
|
1664
|
+
flush().then(async () => {
|
|
1665
|
+
if (!tagsOf.value) return;
|
|
1666
|
+
// Offer the blocks that list tags, and warn when this page is inside
|
|
1667
|
+
// the folder it lists.
|
|
1668
|
+
const ask = (add) => fetch('/__verso/tags-page', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ url: data.url, folder: tagsOf.value, add }) }).then((r) => r.json()).catch(() => null);
|
|
1669
|
+
const out = await ask(false);
|
|
1670
|
+
if (out?.warning) toast(out.warning, 'error');
|
|
1671
|
+
else if (out?.canAdd?.length) {
|
|
1672
|
+
toast(`This page lists the tags now. Add the ${out.canAdd.join(' and ')} blocks to show them?`, 'ok', { label: 'Add them', run: async () => { await ask(true); location.reload(); } });
|
|
1673
|
+
} else toast('This page lists the tags now. Reload to see them.', 'ok', { label: 'Reload', run: () => location.reload() });
|
|
1674
|
+
});
|
|
1675
|
+
});
|
|
1676
|
+
}
|
|
1677
|
+
// Tags: chips, added with Enter or a comma, each change one step in the history.
|
|
1678
|
+
const tagInput = root.getElementById('tag-input');
|
|
1679
|
+
const setTags = (next) => {
|
|
1680
|
+
const before = [...(data.tags || [])];
|
|
1681
|
+
const seen = new Set();
|
|
1682
|
+
data.tags = next.map((t) => t.trim()).filter((t) => t && !seen.has(t.toLowerCase()) && seen.add(t.toLowerCase()));
|
|
1683
|
+
queue({ tags: data.tags });
|
|
1684
|
+
record({ type: 'setting', name: 'tags', label: 'tags', before, after: [...data.tags] });
|
|
1685
|
+
openSettings();
|
|
1686
|
+
root.getElementById('tag-input')?.focus();
|
|
1687
|
+
showSettingOnPage('tag-input');
|
|
1688
|
+
};
|
|
1689
|
+
const addTyped = () => {
|
|
1690
|
+
const typed = tagInput.value.split(',').map((t) => t.trim()).filter(Boolean);
|
|
1691
|
+
if (typed.length) setTags([...(data.tags || []), ...typed]);
|
|
1692
|
+
};
|
|
1693
|
+
tagInput.addEventListener('keydown', (e) => {
|
|
1694
|
+
if (e.key === 'Enter' || e.key === ',') { e.preventDefault(); addTyped(); }
|
|
1695
|
+
else if (e.key === 'Backspace' && !tagInput.value && (data.tags || []).length) { e.preventDefault(); setTags(data.tags.slice(0, -1)); }
|
|
1696
|
+
});
|
|
1697
|
+
tagInput.addEventListener('blur', () => { if (tagInput.value.trim()) addTyped(); });
|
|
1698
|
+
root.getElementById('set-tags').addEventListener('click', (e) => { if (e.target.id === 'set-tags') tagInput.focus(); });
|
|
1699
|
+
panel.querySelectorAll('[data-untag]').forEach((b) => b.addEventListener('click', () => setTags(data.tags.filter((_, i) => i !== Number(b.dataset.untag)))));
|
|
1700
|
+
panel.querySelectorAll('[data-color-field]').forEach((b) => b.addEventListener('click', () => {
|
|
1701
|
+
const name = b.dataset.colorField;
|
|
1702
|
+
values[name] = { color: b.dataset.color };
|
|
1703
|
+
queue({ fields: { [name]: { color: b.dataset.color } } });
|
|
1704
|
+
flush().then(() => maybeReload());
|
|
1705
|
+
}));
|
|
1706
|
+
panel.querySelectorAll('[data-field]').forEach((input) => {
|
|
1707
|
+
const name = input.dataset.field;
|
|
1708
|
+
let before = values[name] || '';
|
|
1709
|
+
input.addEventListener('focus', () => { before = values[name] || ''; });
|
|
1710
|
+
input.addEventListener('input', () => setText(name, input.value));
|
|
1711
|
+
input.addEventListener('blur', () => record({ type: 'text', name, label: labelOf(name), before, after: input.value.trim() }));
|
|
1712
|
+
});
|
|
1713
|
+
panel.querySelectorAll('[data-choose]').forEach((b) => b.addEventListener('click', () => chooseImage(b.dataset.choose)));
|
|
1714
|
+
panel.querySelectorAll('[data-remove]').forEach((b) => b.addEventListener('click', () => setImage(b.dataset.remove, null)));
|
|
1715
|
+
panel.querySelectorAll('[data-alt]').forEach((input) => {
|
|
1716
|
+
const name = input.dataset.alt;
|
|
1717
|
+
let before = null;
|
|
1718
|
+
input.addEventListener('focus', () => { before = values[name] ? { ...values[name] } : null; });
|
|
1719
|
+
input.addEventListener('input', () => {
|
|
1720
|
+
if (!values[name]) return;
|
|
1721
|
+
values[name] = { ...values[name], alt: input.value };
|
|
1722
|
+
queue({ fields: { [name]: values[name] } });
|
|
1723
|
+
});
|
|
1724
|
+
input.addEventListener('blur', () => record({ type: 'image', name, label: `${labelOf(name)} description`, before, after: values[name] ? { ...values[name] } : null }));
|
|
1725
|
+
});
|
|
1726
|
+
root.getElementById('close-settings').addEventListener('click', closeSettings);
|
|
1727
|
+
root.getElementById('remove-unused')?.addEventListener('click', () => {
|
|
1728
|
+
queue({ remove: data.unused });
|
|
1729
|
+
data.unused = [];
|
|
1730
|
+
root.getElementById('unused').remove();
|
|
1731
|
+
flush();
|
|
1732
|
+
});
|
|
1733
|
+
const wasOpen = isShown(panel);
|
|
1734
|
+
show(panel, 'flex');
|
|
1735
|
+
panel.scrollTop = scroll;
|
|
1736
|
+
if (!wasOpen) title.focus();
|
|
1737
|
+
}
|
|
1738
|
+
function closeSettings() { hide($('settings')); }
|
|
1739
|
+
$('open-settings').addEventListener('click', () => (isShown($('settings')) ? closeSettings() : openSettings()));
|
|
1740
|
+
document.addEventListener('keydown', (e) => {
|
|
1741
|
+
if (e.key === 'Escape' && !editEl && !activeRich) { closeSettings(); hide($('menu')); closeImagePop(); }
|
|
1742
|
+
});
|
|
1743
|
+
root.addEventListener('keydown', (e) => {
|
|
1744
|
+
if (e.key === 'Escape' && toolbarMode === 'main') { closeSettings(); hide($('menu')); closeImagePop(); }
|
|
1745
|
+
});
|
|
1746
|
+
|
|
1747
|
+
// ════ Problems ════
|
|
1748
|
+
|
|
1749
|
+
function showProblems(problems, heading) {
|
|
1750
|
+
const panel = $('problems');
|
|
1751
|
+
if (!problems?.length) return hide(panel);
|
|
1752
|
+
const items = problems.map((p) => `
|
|
1753
|
+
<li class="${ui("col gap:d1 pd:d4 bd-t:width-px:solid:line")}">
|
|
1754
|
+
<p class="${ui("font:small:normal text:ink")}">${esc(p.message)}</p>
|
|
1755
|
+
${p.where ? `<p class="${ui("font:mono:tiny text:mist")}">${esc(p.where)}</p>` : ''}
|
|
1756
|
+
${p.hint ? `<p class="${ui("font:tiny:normal text:ink-3")}">${esc(p.hint)}</p>` : ''}
|
|
1757
|
+
</li>`).join('');
|
|
1758
|
+
panel.innerHTML = `
|
|
1759
|
+
<div class="${ui("row:y-center:x-between pd:d3:d4")}">
|
|
1760
|
+
<span class="${ui("row:y-center gap:d2 font:small:semibold text:proof-2")}">${icon('alert')}${esc(heading || (problems.every((p) => p.warning) ? 'Worth a look. Nothing here stops Publish' : problems.length === 1 ? 'One thing needs fixing' : `${problems.length} things need fixing`))}</span>
|
|
1761
|
+
<button id="close-problems" class="${ui("bg-color:transparent bd:width-0 cursor:pointer row:x-center:y-center w:d8 h:d8 bd:round-full text:ink @hover:[bg-color:paper-2] transition:fast")}" aria-label="Hide">${icon('close')}</button>
|
|
1762
|
+
</div>
|
|
1763
|
+
<ul class="${ui("col max-h:half-screen overflow-y:auto")}">${items}</ul>`;
|
|
1764
|
+
root.getElementById('close-problems').addEventListener('click', () => hide(panel));
|
|
1765
|
+
show(panel);
|
|
1766
|
+
}
|
|
1767
|
+
showProblems(data.problems);
|
|
1768
|
+
|
|
1769
|
+
// ════ Live updates ════
|
|
1770
|
+
// A template, token or content change made outside the editor reloads the
|
|
1771
|
+
// page, but never while you're typing or a save is on its way.
|
|
1772
|
+
|
|
1773
|
+
let reloadWaiting = false;
|
|
1774
|
+
// A full-screen view (the site view) can hold reloads while it's open, so a
|
|
1775
|
+
// move doesn't throw it away; the page catches up once when it closes.
|
|
1776
|
+
let reloadHeld = false;
|
|
1777
|
+
function holdReload(on) {
|
|
1778
|
+
reloadHeld = on;
|
|
1779
|
+
if (!on && reloadWaiting) setTimeout(maybeReload, 50);
|
|
1780
|
+
}
|
|
1781
|
+
function maybeReload() {
|
|
1782
|
+
if (reloadHeld || editEl || pending || saving || uploading || (activeRich && activeRich.api.state().focused) || toolbarHasFocus()) {
|
|
1783
|
+
reloadWaiting = true;
|
|
1784
|
+
return;
|
|
1785
|
+
}
|
|
1786
|
+
try { sessionStorage.setItem(`verso-scroll:${location.pathname}`, String(scrollY)); } catch {}
|
|
1787
|
+
location.reload();
|
|
1788
|
+
}
|
|
1789
|
+
document.addEventListener('focusout', () => { if (reloadWaiting) setTimeout(maybeReload, 50); }, true);
|
|
1790
|
+
|
|
1791
|
+
try {
|
|
1792
|
+
const y = sessionStorage.getItem(`verso-scroll:${location.pathname}`);
|
|
1793
|
+
if (y) {
|
|
1794
|
+
sessionStorage.removeItem(`verso-scroll:${location.pathname}`);
|
|
1795
|
+
scrollTo(0, Number(y));
|
|
1796
|
+
}
|
|
1797
|
+
} catch {}
|
|
1798
|
+
|
|
1799
|
+
const events = new EventSource('/__verso/events');
|
|
1800
|
+
events.onmessage = (e) => {
|
|
1801
|
+
const event = JSON.parse(e.data);
|
|
1802
|
+
if (event.type === 'reload') maybeReload();
|
|
1803
|
+
if (event.type === 'status') refreshStatus();
|
|
1804
|
+
if (event.type === 'pages') refreshPages();
|
|
1805
|
+
// Someone else on a served site changed something, or published.
|
|
1806
|
+
if (event.type === 'changed' && event.tab !== TAB && !/^(people\/|publish$)/.test(event.what || '')) {
|
|
1807
|
+
refreshStatus();
|
|
1808
|
+
// Words, pictures and blocks belong to one page; anything else (the
|
|
1809
|
+
// design, a block's layout, the site's pages) can show on every page.
|
|
1810
|
+
const onePage = /^(save|upload|blocks\/|draft)/.test(event.what || '');
|
|
1811
|
+
if (!onePage || event.page === location.pathname) {
|
|
1812
|
+
const typing = editEl || pending || saving || uploading || (activeRich && activeRich.api.state().focused);
|
|
1813
|
+
if (typing && event.by !== data.me?.id) toast(`${event.name} changed this page. It'll update when you stop typing.`, 'ok');
|
|
1814
|
+
maybeReload();
|
|
1815
|
+
}
|
|
1816
|
+
}
|
|
1817
|
+
if (event.type === 'published' && event.tab !== TAB && event.by !== data.me?.id) toast(`${event.name} published. It's live now.`, 'ok');
|
|
1818
|
+
};
|
|
1819
|
+
|
|
1820
|
+
// ════ Extensions ════
|
|
1821
|
+
// Features in their own files (editor/ext-*.js) get this object. Each
|
|
1822
|
+
// exports init(verso). Add a page-menu item with verso.menuItems.push({
|
|
1823
|
+
// label, icon, run }), or a bar button with verso.addBarButton().
|
|
1824
|
+
const BAR_GROUPS = { 'Screen sizes': 'page', History: 'page', Blocks: 'add', 'Build a block': 'add', 'Site view': 'site', 'Site settings': 'site', Design: 'site', Channels: 'site' };
|
|
1825
|
+
const BAR_LABELS = { 'Build a block': 'Build', 'Screen sizes': 'Screens' };
|
|
1826
|
+
const BAR_ORDER = ['Page settings', 'Screen sizes', 'History', 'Blocks', 'Build a block', 'Site view', 'Channels', 'Design', 'Site settings'];
|
|
1827
|
+
var verso = {
|
|
1828
|
+
root, data, ui, toast, icon, esc, show, hide, queue, flush, values, tab: TAB,
|
|
1829
|
+
refreshStatus: () => refreshStatus(),
|
|
1830
|
+
reload: () => maybeReload(),
|
|
1831
|
+
holdReload: (on) => holdReload(on),
|
|
1832
|
+
// Outline a field for a moment, to show where something landed.
|
|
1833
|
+
flash: (el) => { flashEl = el; redraw(); setTimeout(() => { if (flashEl === el) { flashEl = null; redraw(); } }, 1200); },
|
|
1834
|
+
menuItems: [],
|
|
1835
|
+
// Sections an extension adds to Page settings: { html() → string, bind(panel) }.
|
|
1836
|
+
settingsSections: [],
|
|
1837
|
+
openSettings: () => openSettings(),
|
|
1838
|
+
addBarButton({ id, title, svg, onClick }) {
|
|
1839
|
+
const b = document.createElement('button');
|
|
1840
|
+
b.id = id;
|
|
1841
|
+
b.dataset.tip = title;
|
|
1842
|
+
b.setAttribute('aria-label', title);
|
|
1843
|
+
// Below md these live in the page menu only, so the bar fits on a phone.
|
|
1844
|
+
b.className = ui("hidden bg-color:transparent bd:width-0 cursor:pointer w:d10 h:d10 bd:round-full text:paper @hover:[bg-color:ink-2] @focus-visible:[outline:d0:solid:proof] transition:fast /md/ row:x-center:y-center /2xl/ w:auto pd-x:d3 gap:d2");
|
|
1845
|
+
// On wide screens each button also says what it opens.
|
|
1846
|
+
b.innerHTML = `${svg}<span class="${ui("hidden format:no-wrap /2xl/ inline")}" aria-hidden="true">${esc(BAR_LABELS[title] || title)}</span>`;
|
|
1847
|
+
b.addEventListener('click', onClick);
|
|
1848
|
+
// Grouped: this page (settings, history), adding (blocks, building),
|
|
1849
|
+
// and the whole site (site view, settings, design, channels).
|
|
1850
|
+
const group = BAR_GROUPS[title] || 'site';
|
|
1851
|
+
const box = $(`grp-${group}`);
|
|
1852
|
+
const order = BAR_ORDER.indexOf(title);
|
|
1853
|
+
const after = [...box.children].find((c) => BAR_ORDER.indexOf(c.dataset.tip) > order && order !== -1);
|
|
1854
|
+
if (after) after.before(b); else box.append(b);
|
|
1855
|
+
if (group !== 'page') box.className = ui("hidden row:y-center gap:d0 pd-l:d1 bd-l:width-px:solid:ink-3 mg-l:d1 /md/ row");
|
|
1856
|
+
// On phones the bar has no room, so the page menu offers it instead.
|
|
1857
|
+
verso.menuItems.push({ label: title, icon: svg, run: onClick, phoneOnly: true });
|
|
1858
|
+
return b;
|
|
1859
|
+
},
|
|
1860
|
+
};
|
|
1861
|
+
// Extensions load together but start in a fixed order, so their bar buttons
|
|
1862
|
+
// keep the same places from one visit to the next.
|
|
1863
|
+
(async () => {
|
|
1864
|
+
const files = data.extensions || [];
|
|
1865
|
+
const loaded = await Promise.allSettled(files.map((file) => import(`/__verso/${file}`)));
|
|
1866
|
+
loaded.forEach((r, i) => {
|
|
1867
|
+
if (r.status === 'rejected') return console.error(`Verso couldn't load ${files[i]}:`, r.reason);
|
|
1868
|
+
try { r.value.init?.(verso); } catch (err) { console.error(`Verso couldn't start ${files[i]}:`, err); }
|
|
1869
|
+
});
|
|
1870
|
+
// Settings that were open before the page was drawn again.
|
|
1871
|
+
try {
|
|
1872
|
+
const again = JSON.parse(sessionStorage.getItem('verso-reopen-settings') || 'null');
|
|
1873
|
+
if (again) {
|
|
1874
|
+
sessionStorage.removeItem('verso-reopen-settings');
|
|
1875
|
+
openSettings();
|
|
1876
|
+
$('settings').scrollTop = again.scroll || 0;
|
|
1877
|
+
if (again.focus) root.getElementById(again.focus)?.focus();
|
|
1878
|
+
}
|
|
1879
|
+
} catch {}
|
|
1880
|
+
})();
|