@perkyzz/emvb 0.7.0 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -3
- package/THIRD_PARTY_NOTICES.md +1 -1
- package/package.json +7 -7
- package/src/admin/editor/DialogCloseButton.tsx +16 -0
- package/src/admin/editor/Editor.tsx +71 -1
- package/src/admin/editor/FieldPreview.tsx +164 -0
- package/src/admin/editor/PerfMeter.tsx +3 -9
- package/src/admin/editor/SavedSectionDialogs.tsx +169 -0
- package/src/admin/editor/ShareLink.tsx +2 -7
- package/src/admin/editor/ShortcutsDialog.tsx +19 -11
- package/src/admin/editor/Timeline.tsx +2 -7
- package/src/admin/editor/TopBar.tsx +32 -1
- package/src/admin/editor/dialogs.tsx +3 -14
- package/src/admin/editor/editor-chrome.tsx +8 -24
- package/src/admin/editor/editor-commands.ts +15 -1
- package/src/admin/editor/editor-css.ts +6 -2
- package/src/admin/editor/feature-css.ts +11 -1
- package/src/admin/editor/focus-when-lost.ts +23 -0
- package/src/admin/editor/host.ts +6 -0
- package/src/admin/editor/icons/IconLibraryDialog.tsx +2 -7
- package/src/admin/editor/palette-items.ts +17 -0
- package/src/admin/editor/panels/AddPanel.tsx +9 -1
- package/src/admin/editor/panels/ElementPanel.tsx +4 -1
- package/src/admin/editor/panels/LayersPanel.tsx +6 -1
- package/src/admin/editor/panels/LeftPanel.tsx +9 -1
- package/src/admin/editor/panels/SavedSectionsGroup.tsx +246 -0
- package/src/admin/editor/panels/SiteStylesDrawer.tsx +54 -10
- package/src/admin/editor/panels/TokenScales.tsx +16 -16
- package/src/admin/editor/panels/TriggersEditor.tsx +1 -1
- package/src/admin/editor/panels/color-space.ts +14 -26
- package/src/admin/editor/panels/settings/AudienceEditor.tsx +36 -39
- package/src/admin/editor/panels/settings/BackgroundControls.tsx +4 -5
- package/src/admin/editor/panels/settings/IconControls.tsx +21 -5
- package/src/admin/editor/panels/settings/LoopItemBindControl.tsx +1 -1
- package/src/admin/editor/panels/settings/MediaPicker.tsx +5 -5
- package/src/admin/editor/panels/settings/length-units.ts +2 -1
- package/src/admin/editor/shortcuts.ts +14 -0
- package/src/admin/editor/useSavedSections.ts +197 -0
- package/src/admin/image-editor/Canvas.tsx +61 -17
- package/src/admin/image-editor/ImageEditorDialog.tsx +130 -1
- package/src/admin/image-editor/image-editor-css.ts +11 -8
- package/src/admin/image-editor/parts.tsx +18 -17
- package/src/admin/image-editor/save.ts +31 -1
- package/src/admin/index.tsx +5 -1
- package/src/admin/media-api.ts +27 -0
- package/src/admin/pages/AgentsPage.tsx +3 -3
- package/src/admin/pages/CollectionsPage.tsx +215 -0
- package/src/admin/pages/ThemePartList.tsx +32 -4
- package/src/admin/saved-sections-api.ts +51 -0
- package/src/admin/setup/host-collections.ts +100 -0
- package/src/admin/theme-api.ts +3 -2
- package/src/admin/ui.ts +9 -0
- package/src/admin/widgets/CanvasField.tsx +202 -0
- package/src/admin/widgets/convert-body.ts +54 -0
- package/src/admin/widgets/field-fetcher.ts +79 -0
- package/src/astro/index.ts +2 -0
- package/src/astro/page-count.ts +77 -0
- package/src/astro/popups/runtime.ts +8 -6
- package/src/astro/resolve-theme.ts +44 -2
- package/src/astro/resolve.ts +40 -4
- package/src/astro/responsive-images.ts +99 -0
- package/src/constants.ts +1 -1
- package/src/core/a11y/audit.ts +32 -7
- package/src/core/arrange.ts +21 -6
- package/src/core/canvas-collections.ts +20 -0
- package/src/core/css/print.ts +5 -0
- package/src/core/design/classes.ts +23 -9
- package/src/core/design/devices.ts +7 -13
- package/src/core/design/states.ts +7 -13
- package/src/core/elements/dynamic-elements.ts +27 -12
- package/src/core/elements/index.ts +1 -1
- package/src/core/elements/menu.ts +3 -0
- package/src/core/icons/animation-runs.ts +11 -0
- package/src/core/index.ts +22 -0
- package/src/core/migrate/index.ts +3 -0
- package/src/core/portable-text.ts +127 -0
- package/src/core/render/loop.ts +1 -1
- package/src/core/render/pagination.ts +20 -1
- package/src/core/sanitize/css.ts +14 -6
- package/src/core/saved-sections.ts +318 -0
- package/src/core/schema/design.ts +1 -1
- package/src/core/schema/layout.ts +6 -1
- package/src/core/schema/style.ts +4 -2
- package/src/core/theme/float.ts +3 -0
- package/src/core/theme/pagination.ts +34 -24
- package/src/core/theme/part-types.ts +4 -4
- package/src/index.ts +11 -1
- package/src/mcp/ports.ts +22 -1
- package/src/mcp/read.ts +1 -1
- package/src/mcp/sections.ts +183 -0
- package/src/mcp/tools.ts +44 -0
- package/src/mcp/write.ts +4 -4
- package/src/server/agent-settings.ts +16 -1
- package/src/server/hooks.ts +81 -0
- package/src/server/mcp-routes.ts +2 -0
- package/src/server/plugin.ts +34 -5
- package/src/server/saved-sections.ts +163 -0
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
import { Badge, Button, LayerCard, Loader, Text } from "@cloudflare/kumo";
|
|
2
|
+
import { LockSimpleIcon, MagicWandIcon, PencilSimpleIcon } from "@phosphor-icons/react";
|
|
3
|
+
import * as React from "react";
|
|
4
|
+
import { summarizeLayout, type Layout, type LayoutNode } from "../../core/index.ts";
|
|
5
|
+
import { clipText } from "../../core/limits.ts";
|
|
6
|
+
import { canUseEmvb, useRole } from "../access/role.ts";
|
|
7
|
+
import { defaultFetcher, type Fetcher } from "../api.ts";
|
|
8
|
+
import { Editor } from "../editor/Editor.tsx";
|
|
9
|
+
import { ELEMENT_NAMES, elementIcon } from "../editor/element-chrome.ts";
|
|
10
|
+
import { EditorHostContext, type EditorHost } from "../editor/host.ts";
|
|
11
|
+
import { layerPreview } from "../editor/panels/LayersPanel.tsx";
|
|
12
|
+
import { BUTTON, SOLID_PRIMARY } from "../ui.ts";
|
|
13
|
+
import { convertEntryBody, hostEntryFromLocation } from "./convert-body.ts";
|
|
14
|
+
import { createFieldFetcher, FIELD_ENTRY_ID, readFieldLayout } from "./field-fetcher.ts";
|
|
15
|
+
import type { FieldWidgetProps } from "./LayoutField.tsx";
|
|
16
|
+
|
|
17
|
+
function describe(layout: Layout | null): string {
|
|
18
|
+
const summary = summarizeLayout(layout);
|
|
19
|
+
if (!summary || summary.nodes === 0) return "No layout yet";
|
|
20
|
+
return `${summary.nodes} ${summary.nodes === 1 ? "element" : "elements"}`;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
const OUTLINE_ROWS = 5;
|
|
24
|
+
|
|
25
|
+
/** W-904: the page's top-level elements, as the Layers panel names them. Text only. */
|
|
26
|
+
function Outline({ layout }: { layout: Layout }) {
|
|
27
|
+
const children = layout.root.children ?? [];
|
|
28
|
+
if (children.length === 0) return null;
|
|
29
|
+
const more = children.length - OUTLINE_ROWS;
|
|
30
|
+
return (
|
|
31
|
+
<ol className="emvb-canvas-outline" aria-label="Top-level elements">
|
|
32
|
+
{children.slice(0, OUTLINE_ROWS).map((node: LayoutNode) => {
|
|
33
|
+
const Icon = elementIcon(node.type);
|
|
34
|
+
const preview = layerPreview(node);
|
|
35
|
+
return (
|
|
36
|
+
<li key={node.id}>
|
|
37
|
+
<Icon size={14} aria-hidden="true" />
|
|
38
|
+
<span className="emvb-canvas-outline-name">
|
|
39
|
+
{ELEMENT_NAMES[node.type] ?? "Element"}
|
|
40
|
+
</span>
|
|
41
|
+
{preview && <span className="emvb-canvas-outline-text">{clipText(preview, 60)}</span>}
|
|
42
|
+
</li>
|
|
43
|
+
);
|
|
44
|
+
})}
|
|
45
|
+
{more > 0 && <li className="emvb-canvas-outline-more">+{more} more</li>}
|
|
46
|
+
</ol>
|
|
47
|
+
);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
const CARD_CSS = `
|
|
51
|
+
[data-emvb-widget="canvas"] .emvb-canvas-head { display: flex; align-items: center; gap: 8px; justify-content: space-between; }
|
|
52
|
+
[data-emvb-widget="canvas"] .emvb-canvas-body { display: grid; gap: 12px; padding: 12px; }
|
|
53
|
+
.emvb-canvas-outline { margin: 0; padding: 0; list-style: none; display: grid; gap: 4px; font-size: 13px; line-height: 18px; }
|
|
54
|
+
.emvb-canvas-outline > li { display: flex; align-items: center; gap: 8px; min-width: 0; padding: 4px 8px; border-radius: 6px; background: var(--color-kumo-tint); color: var(--text-color-kumo-default); }
|
|
55
|
+
.emvb-canvas-outline > li > svg { flex: none; color: var(--color-kumo-brand); }
|
|
56
|
+
.emvb-canvas-outline-name { flex: none; font-weight: 500; }
|
|
57
|
+
.emvb-canvas-outline-text { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--text-color-kumo-subtle); }
|
|
58
|
+
.emvb-canvas-outline > li.emvb-canvas-outline-more { background: none; color: var(--text-color-kumo-subtle); }
|
|
59
|
+
.emvb-canvas-actions { display: flex; flex-wrap: wrap; gap: 8px; }
|
|
60
|
+
.emvb-canvas-convert-note { margin: 0; font-size: 13px; color: var(--text-color-kumo-subtle); }
|
|
61
|
+
.emvb-canvas-convert-note[data-emvb-convert="error"] { color: var(--text-color-kumo-danger); }
|
|
62
|
+
.emvb-canvas-readonly { display: flex; align-items: center; gap: 6px; margin: 0; font-size: 13px; color: var(--text-color-kumo-subtle); }
|
|
63
|
+
`;
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* `emvb:canvas` (W-900): a JSON field on any collection listed in `canvasCollections`, edited in
|
|
67
|
+
* the full EmVB editor. Apply writes the layout back into the entry form; the entry's own Save
|
|
68
|
+
* stores it, and the server checks it again (W-898). D-061: editors and above only.
|
|
69
|
+
*/
|
|
70
|
+
export function CanvasField({
|
|
71
|
+
value,
|
|
72
|
+
onChange,
|
|
73
|
+
label,
|
|
74
|
+
id,
|
|
75
|
+
fetcher = defaultFetcher,
|
|
76
|
+
}: FieldWidgetProps & { fetcher?: Fetcher }) {
|
|
77
|
+
const role = useRole(fetcher);
|
|
78
|
+
const [session, setSession] = React.useState<ReturnType<typeof createFieldFetcher> | null>(null);
|
|
79
|
+
const layout = readFieldLayout(value);
|
|
80
|
+
const unreadable = layout === null && value !== null && value !== undefined && value !== "";
|
|
81
|
+
const canEdit = role.state === "ready" && canUseEmvb(role.role);
|
|
82
|
+
const close = React.useCallback(() => setSession(null), []);
|
|
83
|
+
// W-912: an empty field can start from the entry's saved rich-text body.
|
|
84
|
+
const entry = React.useMemo(() => hostEntryFromLocation(window.location.pathname), []);
|
|
85
|
+
const [convert, setConvert] = React.useState<
|
|
86
|
+
{ state: "idle" } | { state: "busy" } | { state: "done" | "error"; message: string }
|
|
87
|
+
>({ state: "idle" });
|
|
88
|
+
const startConvert = async () => {
|
|
89
|
+
if (!entry) return;
|
|
90
|
+
setConvert({ state: "busy" });
|
|
91
|
+
try {
|
|
92
|
+
const result = await convertEntryBody(fetcher, entry);
|
|
93
|
+
if (!result.ok) {
|
|
94
|
+
setConvert({ state: "error", message: result.message });
|
|
95
|
+
return;
|
|
96
|
+
}
|
|
97
|
+
const left = result.skipped > 0 ? ` ${result.skipped} left out (not supported).` : "";
|
|
98
|
+
setConvert({
|
|
99
|
+
state: "done",
|
|
100
|
+
message: `Converted ${result.converted} ${result.converted === 1 ? "block" : "blocks"} from the entry's ${result.field} field.${left} Its original content is unchanged. Save the entry to keep the layout.`,
|
|
101
|
+
});
|
|
102
|
+
setSession(createFieldFetcher(fetcher, { title: label, layout: result.layout }));
|
|
103
|
+
} catch {
|
|
104
|
+
setConvert({ state: "error", message: "The entry's content couldn't be read. Try again." });
|
|
105
|
+
}
|
|
106
|
+
};
|
|
107
|
+
const host = React.useMemo<EditorHost | null>(() => {
|
|
108
|
+
if (!session) return null;
|
|
109
|
+
const finish = (next: Layout | null | undefined) => {
|
|
110
|
+
if (next !== undefined) onChange(next);
|
|
111
|
+
setSession(null);
|
|
112
|
+
};
|
|
113
|
+
return {
|
|
114
|
+
// Leave → "Save and leave" staged the layout in the session; keep it, as Apply would.
|
|
115
|
+
exit: () => finish(session.saved()),
|
|
116
|
+
back: { label: "Back to the entry", go: close },
|
|
117
|
+
adminLinks: true,
|
|
118
|
+
field: { apply: (next) => finish(next) },
|
|
119
|
+
};
|
|
120
|
+
}, [session, onChange, close]);
|
|
121
|
+
return (
|
|
122
|
+
<div
|
|
123
|
+
id={id}
|
|
124
|
+
role="group"
|
|
125
|
+
aria-label={label}
|
|
126
|
+
data-emvb-widget="canvas"
|
|
127
|
+
className="flex flex-col gap-2"
|
|
128
|
+
>
|
|
129
|
+
<style>{CARD_CSS}</style>
|
|
130
|
+
<LayerCard>
|
|
131
|
+
<LayerCard.Secondary className="emvb-canvas-head">
|
|
132
|
+
<span>{label}</span>
|
|
133
|
+
<Badge variant={layout && !unreadable ? "blue" : "neutral"}>
|
|
134
|
+
{unreadable ? "Unreadable" : describe(layout)}
|
|
135
|
+
</Badge>
|
|
136
|
+
</LayerCard.Secondary>
|
|
137
|
+
<LayerCard.Primary className="emvb-canvas-body">
|
|
138
|
+
{unreadable ? (
|
|
139
|
+
<Text>This layout can't be read.</Text>
|
|
140
|
+
) : layout && (layout.root.children ?? []).length > 0 ? (
|
|
141
|
+
<Outline layout={layout} />
|
|
142
|
+
) : (
|
|
143
|
+
<Text variant="secondary">
|
|
144
|
+
No layout yet. The entry's own content is shown instead.
|
|
145
|
+
</Text>
|
|
146
|
+
)}
|
|
147
|
+
{role.state === "ready" && !canEdit && (
|
|
148
|
+
<p className="emvb-canvas-readonly">
|
|
149
|
+
<LockSimpleIcon size={14} aria-hidden="true" />
|
|
150
|
+
Only editors and administrators can change this layout.
|
|
151
|
+
</p>
|
|
152
|
+
)}
|
|
153
|
+
{canEdit && (
|
|
154
|
+
<div className="emvb-canvas-actions">
|
|
155
|
+
<Button
|
|
156
|
+
variant="primary"
|
|
157
|
+
className={BUTTON}
|
|
158
|
+
style={SOLID_PRIMARY}
|
|
159
|
+
icon={<PencilSimpleIcon aria-hidden="true" />}
|
|
160
|
+
onClick={() => setSession(createFieldFetcher(fetcher, { title: label, layout }))}
|
|
161
|
+
>
|
|
162
|
+
Edit with EmVB
|
|
163
|
+
</Button>
|
|
164
|
+
{entry && !unreadable && (!layout || (layout.root.children ?? []).length === 0) && (
|
|
165
|
+
<Button
|
|
166
|
+
variant="secondary"
|
|
167
|
+
className={`${BUTTON} emvb-canvas-convert`}
|
|
168
|
+
icon={
|
|
169
|
+
convert.state === "busy" ? (
|
|
170
|
+
<Loader size={14} />
|
|
171
|
+
) : (
|
|
172
|
+
<MagicWandIcon aria-hidden="true" />
|
|
173
|
+
)
|
|
174
|
+
}
|
|
175
|
+
disabled={convert.state === "busy"}
|
|
176
|
+
onClick={() => void startConvert()}
|
|
177
|
+
>
|
|
178
|
+
Convert to EmVB
|
|
179
|
+
</Button>
|
|
180
|
+
)}
|
|
181
|
+
</div>
|
|
182
|
+
)}
|
|
183
|
+
{(convert.state === "done" || convert.state === "error") && (
|
|
184
|
+
<p
|
|
185
|
+
className="emvb-canvas-convert-note"
|
|
186
|
+
role={convert.state === "error" ? "alert" : "status"}
|
|
187
|
+
data-emvb-convert={convert.state}
|
|
188
|
+
>
|
|
189
|
+
{convert.message}
|
|
190
|
+
</p>
|
|
191
|
+
)}
|
|
192
|
+
</LayerCard.Primary>
|
|
193
|
+
</LayerCard>
|
|
194
|
+
{/* The editor portals itself over the whole admin (EditorOverlay). */}
|
|
195
|
+
{session && host && (
|
|
196
|
+
<EditorHostContext.Provider value={host}>
|
|
197
|
+
<Editor fetcher={session.fetcher} entryId={FIELD_ENTRY_ID} />
|
|
198
|
+
</EditorHostContext.Provider>
|
|
199
|
+
)}
|
|
200
|
+
</div>
|
|
201
|
+
);
|
|
202
|
+
}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { portableTextToLayout, type Layout } from "../../core/index.ts";
|
|
2
|
+
import { requestJson, type Fetcher } from "../api.ts";
|
|
3
|
+
import { readCollection } from "../setup/run.ts";
|
|
4
|
+
|
|
5
|
+
const SLUG = /^[a-z][a-z0-9_-]{0,63}$/;
|
|
6
|
+
|
|
7
|
+
/** The host entry the field sits on, from the admin URL `/content/<collection>/<id>`. */
|
|
8
|
+
export function hostEntryFromLocation(
|
|
9
|
+
pathname: string,
|
|
10
|
+
): { collection: string; id: string } | undefined {
|
|
11
|
+
const match = /\/content\/([^/?#]+)\/([^/?#]+)/.exec(pathname);
|
|
12
|
+
if (!match) return undefined;
|
|
13
|
+
const collection = decodeURIComponent(match[1] ?? "");
|
|
14
|
+
const id = decodeURIComponent(match[2] ?? "");
|
|
15
|
+
if (!SLUG.test(collection) || id === "new") return undefined;
|
|
16
|
+
return { collection, id };
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export type ConvertResult =
|
|
20
|
+
| { ok: true; layout: Layout; converted: number; skipped: number; field: string }
|
|
21
|
+
| { ok: false; message: string };
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* W-912: reads the entry's saved rich-text body (the first Portable Text field, `content` first)
|
|
25
|
+
* and builds a starter layout from it, headed by the entry's title. Read-only: the body is never written.
|
|
26
|
+
*/
|
|
27
|
+
export async function convertEntryBody(
|
|
28
|
+
fetcher: Fetcher,
|
|
29
|
+
entry: { collection: string; id: string },
|
|
30
|
+
): Promise<ConvertResult> {
|
|
31
|
+
const schema = await readCollection(fetcher, entry.collection);
|
|
32
|
+
const rich = (schema?.fields ?? []).filter((f) => f.type === "portableText");
|
|
33
|
+
const field = rich.find((f) => f.slug === "content") ?? rich[0];
|
|
34
|
+
if (!field) return { ok: false, message: "This collection has no rich-text field to convert." };
|
|
35
|
+
const data = await requestJson<{ item: { data?: Record<string, unknown> } }>(
|
|
36
|
+
fetcher,
|
|
37
|
+
`/_emdash/api/content/${encodeURIComponent(entry.collection)}/${encodeURIComponent(entry.id)}`,
|
|
38
|
+
);
|
|
39
|
+
let body = data.item.data?.[field.slug];
|
|
40
|
+
if (typeof body === "string") {
|
|
41
|
+
try {
|
|
42
|
+
body = JSON.parse(body) as unknown;
|
|
43
|
+
} catch {
|
|
44
|
+
body = null;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
if (!Array.isArray(body) || body.length === 0)
|
|
48
|
+
return { ok: false, message: `The saved ${field.slug} field is empty.` };
|
|
49
|
+
const title = data.item.data?.["title"];
|
|
50
|
+
const result = portableTextToLayout(body, typeof title === "string" ? title : "");
|
|
51
|
+
if (!result || result.converted === 0)
|
|
52
|
+
return { ok: false, message: "Nothing in the saved body could be converted." };
|
|
53
|
+
return { ok: true, ...result, field: field.slug };
|
|
54
|
+
}
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import { PAGES_COLLECTION } from "../../constants.ts";
|
|
2
|
+
import { validateLayout, type Layout } from "../../core/index.ts";
|
|
3
|
+
import type { Fetcher } from "../api.ts";
|
|
4
|
+
|
|
5
|
+
/** The id the editor loads in field mode; it never exists on the server. */
|
|
6
|
+
export const FIELD_ENTRY_ID = "emvb-field";
|
|
7
|
+
|
|
8
|
+
const ENTRY_PATH = `/_emdash/api/content/${PAGES_COLLECTION}/${FIELD_ENTRY_ID}`;
|
|
9
|
+
|
|
10
|
+
const json = (status: number, body: unknown) =>
|
|
11
|
+
new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
|
|
12
|
+
|
|
13
|
+
/** A stored field value (object or JSON string) as a layout, or null when unreadable. */
|
|
14
|
+
export function readFieldLayout(value: unknown): Layout | null {
|
|
15
|
+
let parsed = value;
|
|
16
|
+
if (typeof value === "string") {
|
|
17
|
+
if (value.trim() === "") return null;
|
|
18
|
+
try {
|
|
19
|
+
parsed = JSON.parse(value) as unknown;
|
|
20
|
+
} catch {
|
|
21
|
+
return null;
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
if (parsed === null || parsed === undefined) return null;
|
|
25
|
+
const result = validateLayout(parsed);
|
|
26
|
+
return result.ok ? result.layout : null;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Field mode (W-900): the editor talks to a virtual draft entry held in memory, so Save draft
|
|
31
|
+
* stages the layout here instead of writing an EmVB page. Design, media and plugin routes go to
|
|
32
|
+
* the real server. `saved()` is the last staged layout, or undefined when nothing was saved.
|
|
33
|
+
*/
|
|
34
|
+
export function createFieldFetcher(
|
|
35
|
+
base: Fetcher,
|
|
36
|
+
initial: { title: string; layout: Layout | null },
|
|
37
|
+
): { fetcher: Fetcher; saved: () => Layout | null | undefined } {
|
|
38
|
+
let layout = initial.layout;
|
|
39
|
+
let staged: Layout | null | undefined;
|
|
40
|
+
let rev = 1;
|
|
41
|
+
const fetcher: Fetcher = async (path, init) => {
|
|
42
|
+
if (path !== ENTRY_PATH && !path.startsWith(`${ENTRY_PATH}/`)) return base(path, init);
|
|
43
|
+
const method = (init?.method ?? "GET").toUpperCase();
|
|
44
|
+
if (path === ENTRY_PATH && method === "GET") {
|
|
45
|
+
return json(200, {
|
|
46
|
+
data: {
|
|
47
|
+
item: {
|
|
48
|
+
id: FIELD_ENTRY_ID,
|
|
49
|
+
slug: "",
|
|
50
|
+
status: "draft",
|
|
51
|
+
draftRevisionId: null,
|
|
52
|
+
data: { title: initial.title, layout, canvas_mode: "site-layout" },
|
|
53
|
+
},
|
|
54
|
+
_rev: String(rev),
|
|
55
|
+
},
|
|
56
|
+
});
|
|
57
|
+
}
|
|
58
|
+
if (path === ENTRY_PATH && method === "PUT") {
|
|
59
|
+
const body = JSON.parse(typeof init?.body === "string" ? init.body : "{}") as {
|
|
60
|
+
data?: { layout?: unknown };
|
|
61
|
+
};
|
|
62
|
+
if (body.data && "layout" in body.data) {
|
|
63
|
+
// Every layout string is untrusted, including the editor's own.
|
|
64
|
+
const result = validateLayout(body.data.layout);
|
|
65
|
+
if (!result.ok) {
|
|
66
|
+
return json(400, { error: { code: "INVALID_LAYOUT", message: "Invalid layout." } });
|
|
67
|
+
}
|
|
68
|
+
layout = result.layout;
|
|
69
|
+
staged = layout;
|
|
70
|
+
}
|
|
71
|
+
rev += 1;
|
|
72
|
+
return json(200, { data: { _rev: String(rev) } });
|
|
73
|
+
}
|
|
74
|
+
return json(400, {
|
|
75
|
+
error: { code: "FIELD_MODE", message: "This isn't available while editing a field." },
|
|
76
|
+
});
|
|
77
|
+
};
|
|
78
|
+
return { fetcher, saved: () => staged };
|
|
79
|
+
}
|
package/src/astro/index.ts
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
export { default as EmVBPage } from "./EmVBPage.astro";
|
|
2
2
|
export { resolveEmVBPage, type ResolvedEmVBPage } from "./resolve.ts";
|
|
3
3
|
export type { HostVisitor } from "./visitor.ts";
|
|
4
|
+
export type { ResponsiveGetImage } from "./responsive-images.ts";
|
|
5
|
+
export type { PostCounter } from "./page-count.ts";
|
|
4
6
|
export {
|
|
5
7
|
resolveThemeParts,
|
|
6
8
|
type RenderedThemePart,
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import { MAX_ARCHIVE_PAGE } from "../core/index.ts";
|
|
2
|
+
import type { ContentPort } from "./content-port.ts";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* W-916: how many published entries an archive has. EmDash 1.4's public query reports only
|
|
6
|
+
* `hasMore`, so EmVB's own counter probes; a host can pass its own (a future EmDash count API).
|
|
7
|
+
* `atLeast` is a count the caller already knows exists. Undefined = unknown, shown as "Page N".
|
|
8
|
+
*/
|
|
9
|
+
export type PostCounter = (query: {
|
|
10
|
+
collection: string;
|
|
11
|
+
where?: Record<string, string>;
|
|
12
|
+
atLeast: number;
|
|
13
|
+
}) => Promise<number | undefined>;
|
|
14
|
+
|
|
15
|
+
/** Loops allow 50 per page, so no archive EmVB pages through holds more. */
|
|
16
|
+
const MAX_ENTRIES = MAX_ARCHIVE_PAGE * 50;
|
|
17
|
+
/** Doubling then halving over 5M entries takes about 46 one-row queries; past that, give up. */
|
|
18
|
+
const MAX_PROBES = 64;
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Counts with one-row queries through the same public collection query the archive uses (same
|
|
22
|
+
* filter, published entries only): doubling past `atLeast` until a row is missing, then
|
|
23
|
+
* halving. Read-only, about 2·log2(n) small queries, only on sites that opt in.
|
|
24
|
+
*/
|
|
25
|
+
export function probeCounter(content: ContentPort): PostCounter {
|
|
26
|
+
return async ({ collection, where, atLeast }) => {
|
|
27
|
+
let probes = 0;
|
|
28
|
+
const exists = async (index: number): Promise<boolean> => {
|
|
29
|
+
probes += 1;
|
|
30
|
+
if (probes > MAX_PROBES) throw new Error("too many probes");
|
|
31
|
+
const result = await content.getCollection(
|
|
32
|
+
collection as never,
|
|
33
|
+
{
|
|
34
|
+
orderBy: { published_at: "desc" },
|
|
35
|
+
limit: 1,
|
|
36
|
+
offset: index,
|
|
37
|
+
...(where ? { where } : {}),
|
|
38
|
+
} as never,
|
|
39
|
+
);
|
|
40
|
+
if (result.error) throw result.error;
|
|
41
|
+
return (result.entries?.length ?? 0) > 0;
|
|
42
|
+
};
|
|
43
|
+
try {
|
|
44
|
+
// `lo` is an index known to exist (or -1); `hi` one known not to.
|
|
45
|
+
let lo = Math.max(0, atLeast) - 1;
|
|
46
|
+
let step = Math.max(1, atLeast);
|
|
47
|
+
let hi = lo + step;
|
|
48
|
+
// oxlint-disable-next-line no-await-in-loop -- each probe depends on the last.
|
|
49
|
+
while (hi < MAX_ENTRIES && (await exists(hi))) {
|
|
50
|
+
lo = hi;
|
|
51
|
+
step *= 2;
|
|
52
|
+
hi = lo + step;
|
|
53
|
+
}
|
|
54
|
+
if (hi >= MAX_ENTRIES) return undefined;
|
|
55
|
+
while (hi - lo > 1) {
|
|
56
|
+
const mid = Math.floor((lo + hi) / 2);
|
|
57
|
+
// oxlint-disable-next-line no-await-in-loop -- binary search.
|
|
58
|
+
if (await exists(mid)) lo = mid;
|
|
59
|
+
else hi = mid;
|
|
60
|
+
}
|
|
61
|
+
return lo + 1;
|
|
62
|
+
} catch {
|
|
63
|
+
return undefined;
|
|
64
|
+
}
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** Pages for `count` entries, or undefined when the count is unknown or below this page. */
|
|
69
|
+
export function totalPagesFor(
|
|
70
|
+
count: number | undefined,
|
|
71
|
+
perPage: number,
|
|
72
|
+
page: number,
|
|
73
|
+
): number | undefined {
|
|
74
|
+
if (count === undefined || !Number.isInteger(count) || count < 0) return undefined;
|
|
75
|
+
const total = Math.min(Math.max(1, Math.ceil(count / perPage)), MAX_ARCHIVE_PAGE);
|
|
76
|
+
return total >= page ? total : undefined;
|
|
77
|
+
}
|
|
@@ -81,10 +81,11 @@ function isValidSelector(selector: string): boolean {
|
|
|
81
81
|
}
|
|
82
82
|
}
|
|
83
83
|
|
|
84
|
-
|
|
84
|
+
/** W-846 (D-055): a click is the visitor asking, so "Show at most" neither stops nor counts it. */
|
|
85
|
+
function canOpen(config: PopupConfig, byClick: boolean): boolean {
|
|
85
86
|
const advanced = config.triggers.advanced;
|
|
86
87
|
if (!matchesPopupDevices(advanced, window.innerWidth)) return false;
|
|
87
|
-
if (!withinShowTimes(advanced, timesShown(config.id))) return false;
|
|
88
|
+
if (!byClick && !withinShowTimes(advanced, timesShown(config.id))) return false;
|
|
88
89
|
return true;
|
|
89
90
|
}
|
|
90
91
|
|
|
@@ -240,10 +241,10 @@ function bindA11y(ctrl: Controller): void {
|
|
|
240
241
|
}
|
|
241
242
|
|
|
242
243
|
/** Opens a closed popup and counts the show; a trigger while it's open does neither (W-092). */
|
|
243
|
-
function openOnce(ctrl: Controller, config: PopupConfig): void {
|
|
244
|
-
if (ctrl.opened || !canOpen(config)) return;
|
|
244
|
+
function openOnce(ctrl: Controller, config: PopupConfig, byClick: boolean): void {
|
|
245
|
+
if (ctrl.opened || !canOpen(config, byClick)) return;
|
|
245
246
|
ctrl.open();
|
|
246
|
-
bumpTimesShown(config.id);
|
|
247
|
+
if (!byClick) bumpTimesShown(config.id);
|
|
247
248
|
}
|
|
248
249
|
|
|
249
250
|
const IDLE_EVENTS = ["mousemove", "mousedown", "keydown", "touchstart", "scroll"] as const;
|
|
@@ -314,7 +315,8 @@ const ARM: { [T in OpenTrigger["type"]]: Arm<T> } = {
|
|
|
314
315
|
|
|
315
316
|
function registerTrigger(ctrl: Controller, config: PopupConfig, trigger: OpenTrigger): void {
|
|
316
317
|
const arm = (ARM as Record<string, Arm<OpenTrigger["type"]> | undefined>)[trigger.type];
|
|
317
|
-
|
|
318
|
+
const byClick = trigger.type === "click";
|
|
319
|
+
arm?.(() => openOnce(ctrl, config, byClick), trigger as never);
|
|
318
320
|
}
|
|
319
321
|
|
|
320
322
|
/**
|
|
@@ -41,6 +41,7 @@ import type { HostVisitor, VisitorAstro } from "./visitor.ts";
|
|
|
41
41
|
import { bindingDataFor } from "./request-data.ts";
|
|
42
42
|
import { decodePathSegment, themeContextFrom } from "./theme-context.ts";
|
|
43
43
|
import { entryTimestamp, themePostFromEntry } from "./theme-posts.ts";
|
|
44
|
+
import { probeCounter, totalPagesFor, type PostCounter } from "./page-count.ts";
|
|
44
45
|
|
|
45
46
|
/** The landmark element for a part's wrapper (W-216); other parts get a plain div. */
|
|
46
47
|
const WRAPPER_TAGS: Partial<Record<string, "header" | "footer">> = {
|
|
@@ -318,6 +319,7 @@ async function loadArchivePosts(
|
|
|
318
319
|
perPage: number,
|
|
319
320
|
content: ContentPort,
|
|
320
321
|
postsTitle = "Posts",
|
|
322
|
+
counter?: PostCounter,
|
|
321
323
|
): Promise<{
|
|
322
324
|
posts: ThemePostFields[];
|
|
323
325
|
archiveTitle?: string;
|
|
@@ -354,7 +356,21 @@ async function loadArchivePosts(
|
|
|
354
356
|
: ctx.collection === "posts"
|
|
355
357
|
? postsTitle
|
|
356
358
|
: undefined;
|
|
357
|
-
|
|
359
|
+
const pagination: ArchivePagination = { page, hasMore, basePath: ctx.path };
|
|
360
|
+
if (counter && (hasMore || result.entries.length > 0)) {
|
|
361
|
+
// W-916: the last page needs no count; later pages are counted past the ones seen.
|
|
362
|
+
const seen = (page - 1) * perPage + result.entries.length;
|
|
363
|
+
const count = hasMore
|
|
364
|
+
? await counter({
|
|
365
|
+
collection: "posts",
|
|
366
|
+
...(filter.where ? { where: filter.where } : {}),
|
|
367
|
+
atLeast: seen + 1,
|
|
368
|
+
})
|
|
369
|
+
: seen;
|
|
370
|
+
const totalPages = totalPagesFor(count, perPage, page);
|
|
371
|
+
if (totalPages !== undefined) pagination.totalPages = totalPages;
|
|
372
|
+
}
|
|
373
|
+
return { posts, archiveTitle, pagination };
|
|
358
374
|
} catch {
|
|
359
375
|
return { posts: [] };
|
|
360
376
|
}
|
|
@@ -367,6 +383,7 @@ async function buildDynamicForContent(
|
|
|
367
383
|
parts: StoredPart[],
|
|
368
384
|
content: ContentPort,
|
|
369
385
|
request?: object,
|
|
386
|
+
counter?: PostCounter,
|
|
370
387
|
): Promise<ThemeDynamicData | undefined> {
|
|
371
388
|
const { sectionTemplates, loopTemplates } = await templatesFrom(layout, parts, request);
|
|
372
389
|
const referenced: ThemeDynamicData = {
|
|
@@ -385,6 +402,7 @@ async function buildDynamicForContent(
|
|
|
385
402
|
content,
|
|
386
403
|
// W-532: the Pagination element's "Posts archive title" words it in the site's language.
|
|
387
404
|
paginationArchiveTitle(layout),
|
|
405
|
+
counter,
|
|
388
406
|
);
|
|
389
407
|
return { ...referenced, posts, archiveTitle, ...(pagination ? { pagination } : {}) };
|
|
390
408
|
}
|
|
@@ -407,6 +425,11 @@ export async function resolveThemeParts(
|
|
|
407
425
|
lang?: string;
|
|
408
426
|
/** Popup and float screen reader names in the site's language (W-690). */
|
|
409
427
|
labels?: ChromeLabels;
|
|
428
|
+
/**
|
|
429
|
+
* W-916: count archive pages for "Page N of M" and the Last link. Off by default; `true`
|
|
430
|
+
* uses EmVB's own one-row probe queries, or pass a counter (e.g. an EmDash count API).
|
|
431
|
+
*/
|
|
432
|
+
pageCount?: boolean | PostCounter;
|
|
410
433
|
} = {},
|
|
411
434
|
): Promise<ResolvedThemeParts> {
|
|
412
435
|
return resolveThemePartsWith(emdashContent, astro, ctx, options);
|
|
@@ -423,8 +446,19 @@ export async function resolveThemePartsWith(
|
|
|
423
446
|
lang?: string;
|
|
424
447
|
/** Popup and float screen reader names in the site's language (W-690). */
|
|
425
448
|
labels?: ChromeLabels;
|
|
449
|
+
/**
|
|
450
|
+
* W-916: count archive pages for "Page N of M" and the Last link. Off by default; `true`
|
|
451
|
+
* uses EmVB's own one-row probe queries, or pass a counter (e.g. an EmDash count API).
|
|
452
|
+
*/
|
|
453
|
+
pageCount?: boolean | PostCounter;
|
|
426
454
|
} = {},
|
|
427
455
|
): Promise<ResolvedThemeParts> {
|
|
456
|
+
const counter =
|
|
457
|
+
typeof options.pageCount === "function"
|
|
458
|
+
? options.pageCount
|
|
459
|
+
: options.pageCount === true
|
|
460
|
+
? probeCounter(port)
|
|
461
|
+
: undefined;
|
|
428
462
|
const context =
|
|
429
463
|
ctx ??
|
|
430
464
|
themeContextFrom(astro.url, {
|
|
@@ -564,7 +598,15 @@ export async function resolveThemePartsWith(
|
|
|
564
598
|
layout && winner === contentWinner
|
|
565
599
|
? {
|
|
566
600
|
...referenced,
|
|
567
|
-
...(await buildDynamicForContent(
|
|
601
|
+
...(await buildDynamicForContent(
|
|
602
|
+
stored.partType,
|
|
603
|
+
context,
|
|
604
|
+
layout,
|
|
605
|
+
parts,
|
|
606
|
+
port,
|
|
607
|
+
astro,
|
|
608
|
+
counter,
|
|
609
|
+
)),
|
|
568
610
|
}
|
|
569
611
|
: referenced;
|
|
570
612
|
// A page past the last one has no posts; the host answers 404 (W-221).
|
package/src/astro/resolve.ts
CHANGED
|
@@ -6,12 +6,15 @@ import { designFor, formsFor } from "./render-session.ts";
|
|
|
6
6
|
import { bindingDataFor } from "./request-data.ts";
|
|
7
7
|
import type { HostVisitor, VisitorAstro } from "./visitor.ts";
|
|
8
8
|
import { referencedTemplatesFor } from "./resolve-theme.ts";
|
|
9
|
+
import { withResponsiveSources, type ResponsiveGetImage } from "./responsive-images.ts";
|
|
9
10
|
|
|
10
11
|
type EmDashEntry = NonNullable<Awaited<ReturnType<ContentPort["getEntry"]>>["entry"]>;
|
|
11
12
|
|
|
12
13
|
export type ResolvedEmVBPage = RenderedPage & {
|
|
13
14
|
/** The EmDash entry, for `getSeoMeta` and the host's layout. */
|
|
14
15
|
entry: EmDashEntry;
|
|
16
|
+
/** The collection the entry came from: `emvb_pages`, or the host collection (W-901). */
|
|
17
|
+
collection: string;
|
|
15
18
|
title: string;
|
|
16
19
|
canvasMode: "site-layout" | "blank";
|
|
17
20
|
/** A valid `_preview` token is serving the draft: don't cache the response. */
|
|
@@ -40,6 +43,18 @@ export async function resolveEmVBPage(
|
|
|
40
43
|
visitor?: HostVisitor;
|
|
41
44
|
/** The page's language, e.g. "fr-CA", for Post Dates; defaults to Astro's locale (W-688). */
|
|
42
45
|
lang?: string;
|
|
46
|
+
/**
|
|
47
|
+
* W-901: a host collection listed in `canvasCollections`, read instead of EmVB's own pages.
|
|
48
|
+
* Its entry is an EmVB page only while `field` (an emvb:canvas field) holds a layout.
|
|
49
|
+
*/
|
|
50
|
+
collection?: string;
|
|
51
|
+
/** The emvb:canvas field of `collection` (default `"canvas"`). */
|
|
52
|
+
field?: string;
|
|
53
|
+
/**
|
|
54
|
+
* W-915: Astro's `getImage` from `astro:assets`. When passed, library Images get a srcset
|
|
55
|
+
* from the host's image service (authorise the site origin in `image.remotePatterns`).
|
|
56
|
+
*/
|
|
57
|
+
getImage?: ResponsiveGetImage;
|
|
43
58
|
} = {},
|
|
44
59
|
): Promise<ResolvedEmVBPage | null> {
|
|
45
60
|
return resolveEmVBPageWith(emdashContent, astro, options);
|
|
@@ -55,13 +70,25 @@ export async function resolveEmVBPageWith(
|
|
|
55
70
|
visitor?: HostVisitor;
|
|
56
71
|
/** The page's language, e.g. "fr-CA", for Post Dates; defaults to Astro's locale (W-688). */
|
|
57
72
|
lang?: string;
|
|
73
|
+
/**
|
|
74
|
+
* W-901: a host collection listed in `canvasCollections`, read instead of EmVB's own pages.
|
|
75
|
+
* Its entry is an EmVB page only while `field` (an emvb:canvas field) holds a layout.
|
|
76
|
+
*/
|
|
77
|
+
collection?: string;
|
|
78
|
+
/** The emvb:canvas field of `collection` (default `"canvas"`). */
|
|
79
|
+
field?: string;
|
|
80
|
+
/**
|
|
81
|
+
* W-915: Astro's `getImage` from `astro:assets`. When passed, library Images get a srcset
|
|
82
|
+
* from the host's image service (authorise the site origin in `image.remotePatterns`).
|
|
83
|
+
*/
|
|
84
|
+
getImage?: ResponsiveGetImage;
|
|
58
85
|
} = {},
|
|
59
86
|
): Promise<ResolvedEmVBPage | null> {
|
|
60
87
|
const slug = options.slug ?? content.decodeSlug(astro.params[options.param ?? "slug"]);
|
|
61
88
|
if (!slug) return null;
|
|
62
89
|
let found: Awaited<ReturnType<ContentPort["getEntry"]>>;
|
|
63
90
|
try {
|
|
64
|
-
found = await content.getEntry(PAGES_COLLECTION, slug);
|
|
91
|
+
found = await content.getEntry(options.collection ?? PAGES_COLLECTION, slug);
|
|
65
92
|
} catch {
|
|
66
93
|
// No emvb_pages collection yet (EmVB not set up): not an EmVB page.
|
|
67
94
|
return null;
|
|
@@ -69,9 +96,13 @@ export async function resolveEmVBPageWith(
|
|
|
69
96
|
const entry = found.entry;
|
|
70
97
|
if (!entry) return null;
|
|
71
98
|
const data = entry.data as Record<string, unknown>;
|
|
99
|
+
const hosted = options.collection !== undefined && options.collection !== PAGES_COLLECTION;
|
|
100
|
+
const stored = hosted ? data[options.field ?? "canvas"] : data["layout"];
|
|
101
|
+
// An empty canvas field leaves the entry to the host's own template.
|
|
102
|
+
if (hosted && (stored === null || stored === undefined || stored === "")) return null;
|
|
72
103
|
const handler = content.pluginHandler(astro.locals as never);
|
|
73
104
|
const design = await designFor(astro, handler, astro.url);
|
|
74
|
-
const layout = readLayout(
|
|
105
|
+
const layout = readLayout(stored);
|
|
75
106
|
const referenced = layout
|
|
76
107
|
? await referencedTemplatesFor(layout, content, astro)
|
|
77
108
|
: { sectionTemplates: {}, loopTemplates: {} };
|
|
@@ -102,9 +133,13 @@ export async function resolveEmVBPageWith(
|
|
|
102
133
|
content,
|
|
103
134
|
)),
|
|
104
135
|
};
|
|
136
|
+
const responsive =
|
|
137
|
+
layout && options.getImage
|
|
138
|
+
? await withResponsiveSources(layout, options.getImage, astro.url.origin)
|
|
139
|
+
: stored;
|
|
105
140
|
return {
|
|
106
141
|
...renderStored(
|
|
107
|
-
|
|
142
|
+
responsive,
|
|
108
143
|
design,
|
|
109
144
|
String(data["id"] ?? slug),
|
|
110
145
|
formDefinitions,
|
|
@@ -113,8 +148,9 @@ export async function resolveEmVBPageWith(
|
|
|
113
148
|
options.lang ?? astro.currentLocale,
|
|
114
149
|
),
|
|
115
150
|
entry,
|
|
151
|
+
collection: hosted ? (options.collection as string) : PAGES_COLLECTION,
|
|
116
152
|
title: typeof data["title"] === "string" ? data["title"] : "",
|
|
117
|
-
canvasMode: data["canvas_mode"] === "blank" ? "blank" : "site-layout",
|
|
153
|
+
canvasMode: !hosted && data["canvas_mode"] === "blank" ? "blank" : "site-layout",
|
|
118
154
|
isPreview: Boolean(found.isPreview),
|
|
119
155
|
};
|
|
120
156
|
}
|