@perkyzz/emvb 0.8.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 +2 -2
- package/package.json +4 -4
- package/src/admin/editor/Editor.tsx +38 -1
- package/src/admin/editor/FieldPreview.tsx +164 -0
- package/src/admin/editor/TopBar.tsx +32 -1
- package/src/admin/editor/editor-css.ts +3 -0
- package/src/admin/editor/host.ts +6 -0
- package/src/admin/editor/panels/ElementPanel.tsx +4 -1
- package/src/admin/editor/panels/settings/BackgroundControls.tsx +4 -5
- package/src/admin/editor/panels/settings/MediaPicker.tsx +5 -5
- package/src/admin/editor/panels/settings/length-units.ts +2 -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/setup/host-collections.ts +100 -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/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/canvas-collections.ts +20 -0
- package/src/core/elements/dynamic-elements.ts +16 -1
- package/src/core/index.ts +2 -0
- package/src/core/portable-text.ts +127 -0
- package/src/core/render/pagination.ts +20 -1
- package/src/core/schema/layout.ts +5 -0
- package/src/core/theme/pagination.ts +9 -0
- package/src/index.ts +11 -1
- package/src/server/agent-settings.ts +16 -1
- package/src/server/hooks.ts +81 -0
- package/src/server/plugin.ts +20 -5
|
@@ -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
|
+
}
|
|
@@ -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
|
}
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import { sanitizeMediaUrl, type Layout } from "../core/index.ts";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* The part of Astro's `getImage` (astro:assets) this uses. The host passes its own, so EmVB stays
|
|
5
|
+
* free of the virtual module and the host's image service (sharp, Cloudflare Images) does the work.
|
|
6
|
+
*/
|
|
7
|
+
export type ResponsiveGetImage = (options: {
|
|
8
|
+
src: string;
|
|
9
|
+
width: number;
|
|
10
|
+
height: number;
|
|
11
|
+
widths: number[];
|
|
12
|
+
}) => Promise<{
|
|
13
|
+
src: string;
|
|
14
|
+
srcSet?: { values?: { url: string; descriptor?: string }[]; attribute?: string };
|
|
15
|
+
}>;
|
|
16
|
+
|
|
17
|
+
/** EmDash's library file path; only these pictures are the site's own to resize. */
|
|
18
|
+
const LIBRARY_PATH = "/_emdash/api/media/file/";
|
|
19
|
+
/** The layout allows six extra sizes per Image (W-344). */
|
|
20
|
+
const MAX_SOURCES = 6;
|
|
21
|
+
const BREAKPOINTS = [640, 960, 1280, 1600, 1920, 2560];
|
|
22
|
+
|
|
23
|
+
type Source = { src: string; width: number };
|
|
24
|
+
type Node = { type: string; props: Record<string, unknown>; children?: Node[] };
|
|
25
|
+
|
|
26
|
+
/** Widths up to 2x the shown width (for high-density screens), at most six. */
|
|
27
|
+
export function sourceWidths(width: number): number[] {
|
|
28
|
+
const cap = Math.min(width * 2, 8000);
|
|
29
|
+
const widths = BREAKPOINTS.filter((w) => w < cap && w !== width).slice(0, MAX_SOURCES - 1);
|
|
30
|
+
return [...widths, cap];
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function candidates(result: Awaited<ReturnType<ResponsiveGetImage>>): Source[] {
|
|
34
|
+
const values =
|
|
35
|
+
result.srcSet?.values ??
|
|
36
|
+
(result.srcSet?.attribute ?? "").split(", ").map((part) => {
|
|
37
|
+
const [url = "", descriptor] = part.trim().split(/\s+/);
|
|
38
|
+
return { url, descriptor };
|
|
39
|
+
});
|
|
40
|
+
const sources: Source[] = [];
|
|
41
|
+
for (const { url, descriptor } of values) {
|
|
42
|
+
const width = Number(/^(\d+)w$/.exec(descriptor ?? "")?.[1]);
|
|
43
|
+
const safe = sanitizeMediaUrl(url);
|
|
44
|
+
// A space or comma would split into another srcset candidate (W-428).
|
|
45
|
+
if (!safe || safe.length > 2000 || /[\s,]/.test(safe)) continue;
|
|
46
|
+
if (!Number.isInteger(width) || width < 1 || width > 8000) continue;
|
|
47
|
+
if (sources.some((s) => s.width === width)) continue;
|
|
48
|
+
sources.push({ src: safe, width });
|
|
49
|
+
}
|
|
50
|
+
return sources.slice(0, MAX_SOURCES);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
async function fill(node: Node, getImage: ResponsiveGetImage, origin: string): Promise<void> {
|
|
54
|
+
if (node.type === "image") {
|
|
55
|
+
const { src, width, height, sources } = node.props;
|
|
56
|
+
const own = Array.isArray(sources) && sources.length > 0;
|
|
57
|
+
if (
|
|
58
|
+
!own &&
|
|
59
|
+
typeof src === "string" &&
|
|
60
|
+
src.startsWith(LIBRARY_PATH) &&
|
|
61
|
+
typeof width === "number" &&
|
|
62
|
+
typeof height === "number"
|
|
63
|
+
) {
|
|
64
|
+
try {
|
|
65
|
+
// Astro's services only resize absolute URLs; the host authorises its origin.
|
|
66
|
+
const absolute = new URL(src, origin).href;
|
|
67
|
+
const result = await getImage({
|
|
68
|
+
src: absolute,
|
|
69
|
+
width,
|
|
70
|
+
height,
|
|
71
|
+
widths: sourceWidths(width),
|
|
72
|
+
});
|
|
73
|
+
// Passed through unchanged: the origin isn't authorised, so a srcset would be a no-op.
|
|
74
|
+
if (result.src && result.src !== absolute) {
|
|
75
|
+
const found = candidates(result);
|
|
76
|
+
if (found.length > 0) node.props = { ...node.props, sources: found };
|
|
77
|
+
}
|
|
78
|
+
} catch {
|
|
79
|
+
// No image service, or it refused this file: the plain <img> stays.
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
await Promise.all((node.children ?? []).map((child) => fill(child, getImage, origin)));
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* W-915: a copy of the layout whose library Images (with a size and no sizes of their own) get
|
|
88
|
+
* `sources` from the host's image service, so the public <img> has a srcset. Opt-in: only when
|
|
89
|
+
* the host passes `getImage`.
|
|
90
|
+
*/
|
|
91
|
+
export async function withResponsiveSources(
|
|
92
|
+
layout: Layout,
|
|
93
|
+
getImage: ResponsiveGetImage,
|
|
94
|
+
origin: string,
|
|
95
|
+
): Promise<Layout> {
|
|
96
|
+
const copy = structuredClone(layout);
|
|
97
|
+
await fill(copy.root as unknown as Node, getImage, origin);
|
|
98
|
+
return copy;
|
|
99
|
+
}
|
package/src/constants.ts
CHANGED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* W-897 (W-P02): host collections whose entries carry an `emvb:canvas` field. Only EmDash-style
|
|
3
|
+
* slugs are kept; EmVB's own collections are left out because their hooks already cover them.
|
|
4
|
+
*/
|
|
5
|
+
export const MAX_CANVAS_COLLECTIONS = 20;
|
|
6
|
+
const OWN = new Set(["emvb_pages", "emvb_theme_parts"]);
|
|
7
|
+
const SLUG = /^[a-z][a-z0-9_]{0,62}$/;
|
|
8
|
+
|
|
9
|
+
export function canvasCollectionSlugs(input: unknown): string[] {
|
|
10
|
+
if (!Array.isArray(input)) return [];
|
|
11
|
+
const out: string[] = [];
|
|
12
|
+
for (const item of input) {
|
|
13
|
+
if (typeof item !== "string") continue;
|
|
14
|
+
const slug = item.trim();
|
|
15
|
+
if (!SLUG.test(slug) || OWN.has(slug) || out.includes(slug)) continue;
|
|
16
|
+
out.push(slug);
|
|
17
|
+
if (out.length === MAX_CANVAS_COLLECTIONS) break;
|
|
18
|
+
}
|
|
19
|
+
return out;
|
|
20
|
+
}
|
|
@@ -309,8 +309,16 @@ export const pagination: ElementDefinition<PaginationNode> = {
|
|
|
309
309
|
label: "Count text",
|
|
310
310
|
optional: true,
|
|
311
311
|
message:
|
|
312
|
-
'{page} and {total} are filled in. EmDash
|
|
312
|
+
'{page} and {total} are filled in. EmDash doesn\'t report a total, so the count shows "Page N" unless the site turns on page counting.',
|
|
313
313
|
},
|
|
314
|
+
{
|
|
315
|
+
key: "showLast",
|
|
316
|
+
kind: "boolean",
|
|
317
|
+
label: "Show Last link",
|
|
318
|
+
optional: true,
|
|
319
|
+
message: "Links to the last page when the site counts pages; otherwise it's left out.",
|
|
320
|
+
},
|
|
321
|
+
{ key: "lastText", kind: "text", label: "Last text", optional: true },
|
|
314
322
|
{
|
|
315
323
|
key: "titleText",
|
|
316
324
|
kind: "text",
|
|
@@ -357,6 +365,13 @@ export const pagination: ElementDefinition<PaginationNode> = {
|
|
|
357
365
|
optional: true,
|
|
358
366
|
message: 'Read out when Next text is only an arrow. Unset is "Next page".',
|
|
359
367
|
},
|
|
368
|
+
{
|
|
369
|
+
key: "lastLabel",
|
|
370
|
+
kind: "text",
|
|
371
|
+
label: "Last name",
|
|
372
|
+
optional: true,
|
|
373
|
+
message: 'Read out when Last text is only an arrow. Unset is "Last page".',
|
|
374
|
+
},
|
|
360
375
|
],
|
|
361
376
|
},
|
|
362
377
|
// Rendered by core/render/pagination.ts from the archive's page data (W-222).
|
package/src/core/index.ts
CHANGED
|
@@ -518,6 +518,7 @@ export {
|
|
|
518
518
|
type ShareRead,
|
|
519
519
|
} from "./share/link.ts";
|
|
520
520
|
export { canvasStyleUrls, MAX_CANVAS_STYLES } from "./canvas-styles.ts";
|
|
521
|
+
export { canvasCollectionSlugs, MAX_CANVAS_COLLECTIONS } from "./canvas-collections.ts";
|
|
521
522
|
export {
|
|
522
523
|
IMAGE_EDIT_CURVE_POINTS_MAX,
|
|
523
524
|
IMAGE_EDIT_FORMATS,
|
|
@@ -547,3 +548,4 @@ export {
|
|
|
547
548
|
type SavedSectionSummary,
|
|
548
549
|
syncedPartLayout,
|
|
549
550
|
} from "./saved-sections.ts";
|
|
551
|
+
export { portableTextToLayout } from "./portable-text.ts";
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
import { MAX_NODES, MAX_TEXT_LENGTH } from "./limits.ts";
|
|
2
|
+
import { LAYOUT_SCHEMA_VERSION, type Layout, type LayoutNode } from "./schema/layout.ts";
|
|
3
|
+
import { sanitizeUrl } from "./sanitize/url.ts";
|
|
4
|
+
import { newNodeId } from "./tree-ops.ts";
|
|
5
|
+
import { validateLayout } from "./validate.ts";
|
|
6
|
+
|
|
7
|
+
const IMAGE_SCHEMES: ReadonlySet<string> = new Set(["https:", "http:"]);
|
|
8
|
+
const LIST_ITEMS_MAX = 200;
|
|
9
|
+
const MEDIA_ID = /^[A-Za-z0-9_-]{1,128}$/;
|
|
10
|
+
|
|
11
|
+
type Record_ = Record<string, unknown>;
|
|
12
|
+
const isRecord = (value: unknown): value is Record_ =>
|
|
13
|
+
typeof value === "object" && value !== null && !Array.isArray(value);
|
|
14
|
+
|
|
15
|
+
/** A block's plain text: its spans' text joined. Marks and links are dropped (starter layout). */
|
|
16
|
+
function blockText(block: Record_): string {
|
|
17
|
+
const children = Array.isArray(block["children"]) ? block["children"] : [];
|
|
18
|
+
let text = "";
|
|
19
|
+
for (const child of children) {
|
|
20
|
+
if (isRecord(child) && typeof child["text"] === "string") text += child["text"];
|
|
21
|
+
}
|
|
22
|
+
return text.trim().slice(0, MAX_TEXT_LENGTH);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function imageNode(block: Record_, id: string): LayoutNode | null {
|
|
26
|
+
const asset = isRecord(block["asset"]) ? block["asset"] : {};
|
|
27
|
+
const raw = typeof asset["url"] === "string" ? asset["url"] : block["url"];
|
|
28
|
+
const src = typeof raw === "string" ? sanitizeUrl(raw, IMAGE_SCHEMES) : undefined;
|
|
29
|
+
if (!src) return null;
|
|
30
|
+
const alt = typeof block["alt"] === "string" ? block["alt"].trim().slice(0, 500) : "";
|
|
31
|
+
const ref = asset["_ref"] ?? asset["id"];
|
|
32
|
+
const props: Record_ = { src, alt, ...(alt ? {} : { decorative: true }) };
|
|
33
|
+
if (typeof ref === "string" && MEDIA_ID.test(ref)) props["mediaId"] = ref;
|
|
34
|
+
for (const key of ["width", "height"] as const) {
|
|
35
|
+
const value = block[key];
|
|
36
|
+
if (typeof value === "number" && Number.isInteger(value) && value > 0 && value <= 10000)
|
|
37
|
+
props[key] = value;
|
|
38
|
+
}
|
|
39
|
+
return { id, type: "image", props } as LayoutNode;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* W-912: a starter EmVB layout from an entry's Portable Text body. Headings, paragraphs, quotes,
|
|
44
|
+
* bullet/numbered lists and images with a safe URL come across as plain elements; everything else
|
|
45
|
+
* (custom blocks, marks, embeds) is left out and counted. The body is untrusted: only strings are
|
|
46
|
+
* copied, URLs go through the shared URL check, and the result is validated like any saved layout.
|
|
47
|
+
*/
|
|
48
|
+
export function portableTextToLayout(
|
|
49
|
+
body: unknown,
|
|
50
|
+
title = "",
|
|
51
|
+
random?: () => number,
|
|
52
|
+
): { layout: Layout; converted: number; skipped: number } | null {
|
|
53
|
+
if (!Array.isArray(body)) return null;
|
|
54
|
+
const used = new Set<string>();
|
|
55
|
+
const id = () => {
|
|
56
|
+
let next = newNodeId(random);
|
|
57
|
+
while (used.has(next)) next = newNodeId(random);
|
|
58
|
+
used.add(next);
|
|
59
|
+
return next;
|
|
60
|
+
};
|
|
61
|
+
const children: LayoutNode[] = [];
|
|
62
|
+
let skipped = 0;
|
|
63
|
+
let list: { ordered: boolean; items: string[] } | null = null;
|
|
64
|
+
const flush = () => {
|
|
65
|
+
if (list && list.items.length > 0)
|
|
66
|
+
children.push({ id: id(), type: "list", props: { ...list } } as LayoutNode);
|
|
67
|
+
list = null;
|
|
68
|
+
};
|
|
69
|
+
const heading = title.trim().slice(0, MAX_TEXT_LENGTH);
|
|
70
|
+
if (heading) children.push({ id: id(), type: "heading", props: { text: heading, level: 1 } });
|
|
71
|
+
for (const block of body) {
|
|
72
|
+
if (children.length >= MAX_NODES - 2) {
|
|
73
|
+
skipped++;
|
|
74
|
+
continue;
|
|
75
|
+
}
|
|
76
|
+
if (!isRecord(block)) {
|
|
77
|
+
skipped++;
|
|
78
|
+
continue;
|
|
79
|
+
}
|
|
80
|
+
if (block["_type"] === "image") {
|
|
81
|
+
flush();
|
|
82
|
+
const node = imageNode(block, id());
|
|
83
|
+
if (node) children.push(node);
|
|
84
|
+
else skipped++;
|
|
85
|
+
continue;
|
|
86
|
+
}
|
|
87
|
+
if (block["_type"] !== "block") {
|
|
88
|
+
flush();
|
|
89
|
+
skipped++;
|
|
90
|
+
continue;
|
|
91
|
+
}
|
|
92
|
+
const text = blockText(block);
|
|
93
|
+
const listItem = block["listItem"];
|
|
94
|
+
if (listItem === "bullet" || listItem === "number") {
|
|
95
|
+
const ordered = listItem === "number";
|
|
96
|
+
if (list && list.ordered !== ordered) flush();
|
|
97
|
+
list ??= { ordered, items: [] };
|
|
98
|
+
if (text && list.items.length < LIST_ITEMS_MAX) list.items.push(text);
|
|
99
|
+
else if (text) skipped++;
|
|
100
|
+
continue;
|
|
101
|
+
}
|
|
102
|
+
flush();
|
|
103
|
+
if (!text) continue;
|
|
104
|
+
const style = typeof block["style"] === "string" ? block["style"] : "normal";
|
|
105
|
+
const level = /^h([1-6])$/.exec(style);
|
|
106
|
+
children.push(
|
|
107
|
+
level
|
|
108
|
+
? { id: id(), type: "heading", props: { text, level: Number(level[1]) } }
|
|
109
|
+
: { id: id(), type: "text", props: { text } },
|
|
110
|
+
);
|
|
111
|
+
}
|
|
112
|
+
flush();
|
|
113
|
+
const candidate = {
|
|
114
|
+
schemaVersion: LAYOUT_SCHEMA_VERSION,
|
|
115
|
+
root: {
|
|
116
|
+
id: id(),
|
|
117
|
+
type: "container",
|
|
118
|
+
props: {},
|
|
119
|
+
style: { flexDirection: "column", gap: { value: 16, unit: "px" } },
|
|
120
|
+
children,
|
|
121
|
+
},
|
|
122
|
+
};
|
|
123
|
+
const checked = validateLayout(candidate);
|
|
124
|
+
if (!checked.ok) return null;
|
|
125
|
+
const converted = children.length - (heading ? 1 : 0);
|
|
126
|
+
return { layout: checked.layout, converted, skipped };
|
|
127
|
+
}
|
|
@@ -1,6 +1,11 @@
|
|
|
1
1
|
import type { PaginationNode } from "../schema/layout.ts";
|
|
2
2
|
import type { ThemeDynamicData } from "../theme/dynamic.ts";
|
|
3
|
-
import {
|
|
3
|
+
import {
|
|
4
|
+
lastPagePath,
|
|
5
|
+
pageCountText,
|
|
6
|
+
paginationItems,
|
|
7
|
+
type ArchivePagination,
|
|
8
|
+
} from "../theme/pagination.ts";
|
|
4
9
|
import type { VNode } from "./vnode.ts";
|
|
5
10
|
|
|
6
11
|
/** What the editor canvas shows: page 2 of several, links going nowhere (W-222). */
|
|
@@ -101,6 +106,20 @@ export function renderPagination(
|
|
|
101
106
|
};
|
|
102
107
|
}
|
|
103
108
|
});
|
|
109
|
+
// W-916: the editor sample has no total, so its Last link goes nowhere like the others.
|
|
110
|
+
const last = editor ? "#" : lastPagePath(data);
|
|
111
|
+
if (node.props.showLast && last) {
|
|
112
|
+
const text = label(node.props.lastText, "Last");
|
|
113
|
+
children.push({
|
|
114
|
+
tag: "a",
|
|
115
|
+
attrs: {
|
|
116
|
+
class: "emvb-pagination-last",
|
|
117
|
+
href: last,
|
|
118
|
+
...nameIfSymbols(text, label(node.props.lastLabel, "Last page")),
|
|
119
|
+
},
|
|
120
|
+
children: [text],
|
|
121
|
+
});
|
|
122
|
+
}
|
|
104
123
|
if (node.props.showCount) {
|
|
105
124
|
// W-309: "Page N of M", or "Page N" while the host has no total.
|
|
106
125
|
children.unshift({
|
|
@@ -645,6 +645,11 @@ export const PaginationNode = leafNode(
|
|
|
645
645
|
showCount: z.boolean().optional(),
|
|
646
646
|
/** The count's text; `{page}` and `{total}` are filled in. Unset = "Page {page} of {total}". */
|
|
647
647
|
countText: z.string().max(60).optional(),
|
|
648
|
+
/** W-916: a link to the last page, shown when the host knows the total. */
|
|
649
|
+
showLast: z.boolean().optional(),
|
|
650
|
+
lastText: z.string().max(40).optional(),
|
|
651
|
+
/** The Last link's name when its text is only an arrow. Unset = "Last page". */
|
|
652
|
+
lastLabel: z.string().max(60).optional(),
|
|
648
653
|
/**
|
|
649
654
|
* The page title of archive page 2 onward (W-529); `{title}` and `{page}` are filled in.
|
|
650
655
|
* Unset = "{title} – page {page}". Hosts read it with `archivePageTitle`.
|
|
@@ -178,6 +178,15 @@ function totalItems(p: ArchivePagination, total: number): PaginationItem[] {
|
|
|
178
178
|
return items;
|
|
179
179
|
}
|
|
180
180
|
|
|
181
|
+
/**
|
|
182
|
+
* W-916: the last page's path when the total is known and this isn't it. Without a total there
|
|
183
|
+
* is no Last link: a guessed one could point past the end.
|
|
184
|
+
*/
|
|
185
|
+
export function lastPagePath(p: ArchivePagination): string | undefined {
|
|
186
|
+
const total = knownTotal(p);
|
|
187
|
+
return total !== undefined && p.page < total ? archivePagePath(p.basePath, total) : undefined;
|
|
188
|
+
}
|
|
189
|
+
|
|
181
190
|
/** A text prop of the first Pagination element in an archive layout, if set (W-529, W-532). */
|
|
182
191
|
function paginationText(layout: Layout, key: "titleText" | "archiveTitle"): string | undefined {
|
|
183
192
|
let found: string | undefined;
|