visualci-gallery 0.0.0-stage → 0.2.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/dist/load.js ADDED
@@ -0,0 +1,40 @@
1
+ // Reading the manifest: shared by mount() in the browser and by build-time renderers (the Astro component).
2
+ import { buildModel } from "./model.js";
3
+ /** A signal that aborts after `ms` (AbortSignal.timeout is missing before Safari 16). */
4
+ function timeout(ms) {
5
+ if (typeof AbortSignal.timeout === "function")
6
+ return AbortSignal.timeout(ms);
7
+ const controller = new AbortController();
8
+ setTimeout(() => controller.abort(), ms);
9
+ return controller.signal;
10
+ }
11
+ /** Fetches the manifest and builds its model. Throws, naming the URL, when it can't be read or shows nothing. */
12
+ export async function load(options) {
13
+ const get = options.fetch ?? fetch;
14
+ const attempts = Math.max(1, options.attempts ?? 3);
15
+ let last;
16
+ let manifest;
17
+ for (let attempt = 1; attempt <= attempts; attempt++) {
18
+ try {
19
+ const res = await get(options.manifest, { signal: timeout(options.timeout ?? 20000) });
20
+ if (!res.ok)
21
+ throw new Error(`HTTP ${res.status}`);
22
+ manifest = (await res.json());
23
+ break;
24
+ }
25
+ catch (e) {
26
+ last = e;
27
+ if (attempt < attempts)
28
+ await new Promise((r) => setTimeout(r, attempt * 1000));
29
+ }
30
+ }
31
+ if (manifest === undefined) {
32
+ throw new Error(`The screenshots gallery couldn't read ${options.manifest}: ${last instanceof Error ? last.message : String(last)}`);
33
+ }
34
+ try {
35
+ return buildModel(manifest, options);
36
+ }
37
+ catch (e) {
38
+ throw new Error(`The screenshots gallery can't show ${options.manifest}: ${e instanceof Error ? e.message : String(e)}`);
39
+ }
40
+ }
@@ -0,0 +1,166 @@
1
+ export type Theme = "light" | "dark";
2
+ export type Size = "desktop" | "phone";
3
+ /** VisualCI's public gallery manifest (https://visualci.com/docs/gallery/). */
4
+ export interface Manifest {
5
+ project?: string;
6
+ groups: ManifestGroup[];
7
+ }
8
+ export interface ManifestGroup {
9
+ name: string;
10
+ title?: string | null;
11
+ items: ManifestItem[];
12
+ }
13
+ export interface ManifestItem {
14
+ name: string;
15
+ url: string;
16
+ width: number;
17
+ height: number;
18
+ platform?: string;
19
+ sha256?: string;
20
+ since?: string;
21
+ /** The image's size in bytes, when the server gives it. */
22
+ bytes?: number;
23
+ /** A small copy for the cards (VisualCI serves a 640 px WebP), when the server gives one. */
24
+ thumb?: {
25
+ url: string;
26
+ width: number;
27
+ height: number;
28
+ bytes?: number;
29
+ };
30
+ }
31
+ export interface ScreenOptions {
32
+ title?: string;
33
+ caption?: string;
34
+ }
35
+ export interface GroupOptions {
36
+ title?: string;
37
+ /** The size of a shot whose name gives no width, over the image's shape (`desktop` for a Mac app's windows). */
38
+ size?: Size;
39
+ /** "cover" (default): the image fills its card, cropped at the bottom. "contain": shown whole and centred, for
40
+ * windows. */
41
+ fit?: Fit;
42
+ }
43
+ export type Fit = "cover" | "contain";
44
+ /** What a site can set. Every field is optional and JSON-shaped, so the server renderers take the same options. */
45
+ export interface Options {
46
+ /** The gallery's heading and accessible name. Default "Screenshots"; null keeps the name but shows no heading. */
47
+ title?: string | null;
48
+ /** The level of the gallery's heading (2 by default); groups and cards take the levels below it. */
49
+ headingLevel?: number;
50
+ /** The prefix of every id in the markup, for more than one gallery on a page. Default "vg". */
51
+ id?: string;
52
+ /** Titles and captions by screen key (`ios/usage`, `overview`). */
53
+ screens?: Record<string, ScreenOptions>;
54
+ /** Screen keys in the order they show; the rest follow by key. */
55
+ order?: string[];
56
+ /** By group name: its title (over the manifest's), the size of shots whose names give no width, and how its images
57
+ * fit their cards. */
58
+ groups?: Record<string, GroupOptions>;
59
+ /** Group names in the order they show; the rest follow in the manifest's order. */
60
+ groupOrder?: string[];
61
+ /** The "Screenshots by VisualCI" line. Default true. */
62
+ credit?: boolean;
63
+ /** "grid" (default): tabs per group, a grid of cards. "strip": every screen in one row that scrolls sideways, for
64
+ * a homepage band. */
65
+ layout?: Layout;
66
+ /** Light and Dark buttons. Default true for the grid; the strip never has them. Without them the gallery follows
67
+ * the page: `<html data-theme>`, else the reader's setting. */
68
+ themeSwitch?: boolean;
69
+ /** A link under the gallery, such as the strip's link to the full page. */
70
+ seeAll?: {
71
+ href: string;
72
+ text?: string;
73
+ } | null;
74
+ /** Predictive preloading of the images a reader is likely to look at next. Default true; false turns it off; an
75
+ * object sets its own caps (the rest keep their defaults). */
76
+ preload?: boolean | PreloadCaps;
77
+ }
78
+ /** The preloader's limits: `fold` above-the-fold thumbnails always load; past them at most `count` images and
79
+ * `bytes` bytes; `parallel` requests at once. */
80
+ export interface PreloadCaps {
81
+ fold?: number;
82
+ count?: number;
83
+ bytes?: number;
84
+ parallel?: number;
85
+ }
86
+ export declare const PRELOAD_DEFAULTS: {
87
+ fold: number;
88
+ count: number;
89
+ bytes: number;
90
+ parallel: number;
91
+ };
92
+ export type Layout = "grid" | "strip";
93
+ export interface Variant {
94
+ size: Size;
95
+ theme: Theme;
96
+ url: string;
97
+ url2x: string | null;
98
+ width: number;
99
+ height: number;
100
+ /** Bytes of `url` and `url2x`, when the manifest gives them. */
101
+ bytes: number | null;
102
+ bytes2x: number | null;
103
+ /** The cards' small copy, when the manifest gives one; the full-size view shows `url`. */
104
+ thumb: Thumb | null;
105
+ }
106
+ export interface Thumb {
107
+ url: string;
108
+ width: number;
109
+ height: number;
110
+ bytes: number | null;
111
+ }
112
+ export interface Screen {
113
+ key: string;
114
+ title: string;
115
+ caption: string | null;
116
+ variants: Variant[];
117
+ }
118
+ export interface Group {
119
+ name: string;
120
+ title: string;
121
+ slug: string;
122
+ fit: Fit;
123
+ sizes: Size[];
124
+ screens: Screen[];
125
+ }
126
+ export interface Model {
127
+ layout: Layout;
128
+ themeSwitch: boolean;
129
+ seeAll: {
130
+ href: string;
131
+ text: string;
132
+ } | null;
133
+ title: string | null;
134
+ label: string;
135
+ headingLevel: number;
136
+ id: string;
137
+ credit: boolean;
138
+ /** null: preloading with the defaults. "off": none. Else the caps, every one filled in. */
139
+ preload: null | "off" | Required<PreloadCaps>;
140
+ groups: Group[];
141
+ }
142
+ export declare const DEFAULT_TITLE = "Screenshots";
143
+ export declare const SEE_ALL_TEXT = "See all screenshots";
144
+ export interface Shot {
145
+ /** The screen's key: the name without its theme, width and 2x parts. */
146
+ key: string;
147
+ /** null when the name says nothing: the shot stands for both themes. */
148
+ theme: Theme | null;
149
+ size: Size;
150
+ x2: boolean;
151
+ /** The CSS width the name gives (`-1440`), or null. */
152
+ cssWidth: number | null;
153
+ }
154
+ /** How a manifest name pairs: `<screen>-<theme>[-<width>][-2x]`, or `<screen>/<width>-<theme>[-2x]`. A name in
155
+ * neither shape is a screen of its own, in both themes. Under 768 wide is a phone; with no width, a portrait image
156
+ * is a phone and a landscape one a desktop, unless `size` says. */
157
+ export declare function parseShot(name: string, width: number, height: number, size?: Size): Shot;
158
+ /** `billing/free` → "Billing, free". */
159
+ export declare function humanize(segments: string[]): string;
160
+ /** A group's name as an id: ASCII lower case, runs of anything else as one hyphen. */
161
+ export declare function slugify(name: string): string;
162
+ /** A width or height: a whole number from 1 to MAX_SIZE, so the density maths stays exact in every language. */
163
+ export declare const MAX_SIZE = 1000000;
164
+ /** The manifest as the gallery shows it (contract/SPEC.md). Throws when it or the options are invalid, or nothing in
165
+ * it can be shown. */
166
+ export declare function buildModel(manifest: Manifest, options?: Options): Model;
package/dist/model.js ADDED
@@ -0,0 +1,283 @@
1
+ // The manifest, grouped and paired: the step every renderer shares (contract/SPEC.md, "The model"). Pure: no DOM, no
2
+ // network, so it runs in the browser, at build time and in tests alike.
3
+ export const PRELOAD_DEFAULTS = { fold: 250, count: 500, bytes: 50_000_000, parallel: 4 };
4
+ const PRELOAD_KEYS = ["fold", "count", "bytes", "parallel"];
5
+ /** The largest cap, so every language holds it exactly. */
6
+ const MAX_CAP = 1_000_000_000_000;
7
+ export const DEFAULT_TITLE = "Screenshots";
8
+ const SIZES = ["desktop", "phone"];
9
+ const THEMES = ["light", "dark"];
10
+ // Whole-string matches, ASCII digits only and "any character" including line breaks, so every language's regex
11
+ // engine agrees (contract/SPEC.md, "A shot's name").
12
+ const EXTENSION = /\.(?:[pP][nN][gG]|[jJ][pP][eE]?[gG]|[wW][eE][bB][pP])$/;
13
+ const WIDTH_THEME = /^([0-9]+)-(light|dark)(-2x)?$/;
14
+ const SCREEN_THEME = /^([\s\S]+?)-(light|dark)(?:-([0-9]+))?(-2x)?$/;
15
+ export const SEE_ALL_TEXT = "See all screenshots";
16
+ /** How a manifest name pairs: `<screen>-<theme>[-<width>][-2x]`, or `<screen>/<width>-<theme>[-2x]`. A name in
17
+ * neither shape is a screen of its own, in both themes. Under 768 wide is a phone; with no width, a portrait image
18
+ * is a phone and a landscape one a desktop, unless `size` says. */
19
+ export function parseShot(name, width, height, size) {
20
+ const parts = name.replace(EXTENSION, "").split("/");
21
+ const last = parts.pop();
22
+ const folder = parts.join("/");
23
+ const sized = (w) => w !== undefined ? (Number(w) < 768 ? "phone" : "desktop") : (size ?? (height > width ? "phone" : "desktop"));
24
+ const css = (w) => (w !== undefined ? Number(w) : null);
25
+ let m = WIDTH_THEME.exec(last);
26
+ if (m && folder) {
27
+ return { key: folder, theme: m[2], size: sized(m[1]), x2: !!m[3], cssWidth: css(m[1]) };
28
+ }
29
+ m = SCREEN_THEME.exec(last);
30
+ if (m) {
31
+ const key = folder ? `${folder}/${m[1]}` : m[1];
32
+ return { key, theme: m[2], size: sized(m[3]), x2: !!m[4], cssWidth: css(m[3]) };
33
+ }
34
+ return { key: folder ? `${folder}/${last}` : last, theme: null, size: sized(undefined), x2: false, cssWidth: null };
35
+ }
36
+ /** `billing/free` → "Billing, free". */
37
+ export function humanize(segments) {
38
+ const text = segments.map((s) => s.replace(/[-_]+/g, " ").replace(/^ +| +$/g, "")).join(", ");
39
+ const first = text.codePointAt(0);
40
+ if (first === undefined)
41
+ return text;
42
+ const head = String.fromCodePoint(first);
43
+ return head.toUpperCase() + text.slice(head.length);
44
+ }
45
+ /** A group's name as an id: ASCII lower case, runs of anything else as one hyphen. */
46
+ export function slugify(name) {
47
+ return name.replace(/[A-Z]/g, (c) => c.toLowerCase()).replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "") || "group";
48
+ }
49
+ function commonFolder(keys) {
50
+ const folders = keys.map((k) => k.split("/").slice(0, -1));
51
+ if (folders.length === 0)
52
+ return [];
53
+ let common = folders[0];
54
+ for (const f of folders.slice(1)) {
55
+ let i = 0;
56
+ while (i < common.length && i < f.length && common[i] === f[i])
57
+ i++;
58
+ common = common.slice(0, i);
59
+ }
60
+ return common;
61
+ }
62
+ function rankBy(order) {
63
+ const list = order ?? [];
64
+ return (key) => {
65
+ const i = list.indexOf(key);
66
+ return i === -1 ? list.length : i;
67
+ };
68
+ }
69
+ /** By code point, as Ruby, Python and Rust compare strings (JavaScript's < compares UTF-16 units). */
70
+ function compare(a, b) {
71
+ const x = Array.from(a, (c) => c.codePointAt(0));
72
+ const y = Array.from(b, (c) => c.codePointAt(0));
73
+ for (let i = 0; i < Math.min(x.length, y.length); i++)
74
+ if (x[i] !== y[i])
75
+ return x[i] - y[i];
76
+ return x.length - y.length;
77
+ }
78
+ /** A URL a page may link to or load: http or https, with no spaces or control characters (which browsers strip,
79
+ * so `java\tscript:` would still run). */
80
+ const ABSOLUTE = /^[hH][tT][tT][pP][sS]?:\/\/[^\x00-\x20\x7f]+$/;
81
+ /** A link that's absolute (as above) or relative: no scheme, no spaces or control characters. */
82
+ function safeHref(value) {
83
+ return ABSOLUTE.test(value) || (value !== "" && !/[\x00-\x20\x7f]/.test(value) && !/^[A-Za-z][A-Za-z0-9+.-]*:/.test(value));
84
+ }
85
+ const ID = /^[A-Za-z][A-Za-z0-9_-]*$/;
86
+ function fail(message) {
87
+ throw new Error(message);
88
+ }
89
+ const isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
90
+ /** A width or height: a whole number from 1 to MAX_SIZE, so the density maths stays exact in every language. */
91
+ export const MAX_SIZE = 1_000_000;
92
+ const isSize = (v) => typeof v === "number" && Number.isInteger(v) && v > 0 && v <= MAX_SIZE;
93
+ /** An option's value, with null meaning absent. */
94
+ function opt(value, check, what) {
95
+ if (value === null || value === undefined)
96
+ return undefined;
97
+ if (!check(value))
98
+ fail(`gallery option ${what} is invalid`);
99
+ return value;
100
+ }
101
+ const isString = (v) => typeof v === "string";
102
+ /** A size in bytes: a whole number up to 10^12, exact in every language. */
103
+ const isBytes = (v) => typeof v === "number" && Number.isInteger(v) && v >= 0 && v <= 1_000_000_000_000;
104
+ const isStrings = (v) => Array.isArray(v) && v.every(isString);
105
+ const isTexts = (keys) => (v) => isObject(v) &&
106
+ Object.values(v).every((entry) => isObject(entry) && Object.entries(entry).every(([k, x]) => keys.includes(k) && (x === null || isString(x))));
107
+ /** The manifest's shape (contract/SPEC.md, "Validation"): anything else is refused. */
108
+ function checkManifest(manifest) {
109
+ if (!isObject(manifest) || !Array.isArray(manifest.groups))
110
+ fail("not a gallery manifest: it has no groups");
111
+ manifest.groups.forEach((g, i) => {
112
+ if (!isObject(g) || typeof g.name !== "string" || g.name === "")
113
+ fail(`gallery manifest group ${i} has no name`);
114
+ if (g.title !== undefined && g.title !== null && typeof g.title !== "string")
115
+ fail(`gallery manifest group ${g.name}: its title isn't a string`);
116
+ if (!Array.isArray(g.items))
117
+ fail(`gallery manifest group ${g.name} has no items`);
118
+ g.items.forEach((item, j) => {
119
+ const where = `gallery manifest group ${g.name}, item ${j}`;
120
+ if (!isObject(item) || typeof item.name !== "string" || item.name === "")
121
+ fail(`${where} has no name`);
122
+ if (typeof item.url !== "string" || !ABSOLUTE.test(item.url))
123
+ fail(`${where} (${item.name}): its url isn't an http(s) URL`);
124
+ if (!isSize(item.width) || !isSize(item.height))
125
+ fail(`${where} (${item.name}): its width and height aren't whole numbers from 1 to 1000000`);
126
+ if (item.bytes !== undefined && item.bytes !== null && !isBytes(item.bytes))
127
+ fail(`${where} (${item.name}): its bytes isn't a whole number`);
128
+ const t = item.thumb;
129
+ if (t !== undefined && t !== null) {
130
+ if (!isObject(t) ||
131
+ typeof t.url !== "string" ||
132
+ !ABSOLUTE.test(t.url) ||
133
+ !isSize(t.width) ||
134
+ !isSize(t.height) ||
135
+ (t.bytes !== undefined && t.bytes !== null && !isBytes(t.bytes))) {
136
+ fail(`${where} (${item.name}): its thumb needs an http(s) url, a width and a height`);
137
+ }
138
+ }
139
+ });
140
+ });
141
+ }
142
+ /** The manifest as the gallery shows it (contract/SPEC.md). Throws when it or the options are invalid, or nothing in
143
+ * it can be shown. */
144
+ export function buildModel(manifest, options = {}) {
145
+ checkManifest(manifest);
146
+ if (!isObject(options))
147
+ fail("gallery options must be an object");
148
+ const o = options;
149
+ const level = opt(o.headingLevel, (v) => Number.isInteger(v), "headingLevel") ?? 2;
150
+ const headingLevel = Math.min(Math.max(level, 1), 4);
151
+ const title = o.title === undefined ? DEFAULT_TITLE : opt(o.title, isString, "title") ?? null;
152
+ const id = opt(o.id, (v) => isString(v) && ID.test(v), "id") ?? "vg";
153
+ const screensOpt = opt(o.screens, isTexts(["title", "caption"]), "screens") ?? {};
154
+ const groupsOpt = opt(o.groups, (v) => isObject(v) &&
155
+ Object.values(v).every((entry) => isObject(entry) &&
156
+ Object.entries(entry).every(([k, x]) => (k === "title" && (x === null || isString(x))) ||
157
+ (k === "size" && (x === null || SIZES.includes(x))) ||
158
+ (k === "fit" && (x === null || x === "cover" || x === "contain")))), "groups") ?? {};
159
+ const order = opt(o.order, isStrings, "order");
160
+ const groupOrder = opt(o.groupOrder, isStrings, "groupOrder");
161
+ const credit = opt(o.credit, (v) => typeof v === "boolean", "credit") ?? true;
162
+ const themeSwitchOpt = opt(o.themeSwitch, (v) => typeof v === "boolean", "themeSwitch") ?? true;
163
+ const layout = opt(o.layout, (v) => v === "grid" || v === "strip", "layout") ?? "grid";
164
+ const seeAllOpt = opt(o.seeAll, (v) => isObject(v) && isString(v.href) && safeHref(v.href) && (v.text === undefined || v.text === null || isString(v.text)), "seeAll");
165
+ const preloadOpt = opt(o.preload, (v) => typeof v === "boolean" ||
166
+ (isObject(v) &&
167
+ Object.entries(v).every(([k, x]) => PRELOAD_KEYS.includes(k) &&
168
+ (x === null ||
169
+ (typeof x === "number" && Number.isInteger(x) && x >= (k === "parallel" ? 1 : 0) && x <= (k === "parallel" ? 8 : MAX_CAP))))), "preload");
170
+ const preload = preloadOpt === undefined || preloadOpt === true
171
+ ? null
172
+ : preloadOpt === false
173
+ ? "off"
174
+ : {
175
+ fold: preloadOpt.fold ?? PRELOAD_DEFAULTS.fold,
176
+ count: preloadOpt.count ?? PRELOAD_DEFAULTS.count,
177
+ bytes: preloadOpt.bytes ?? PRELOAD_DEFAULTS.bytes,
178
+ parallel: preloadOpt.parallel ?? PRELOAD_DEFAULTS.parallel,
179
+ };
180
+ const slugs = new Set();
181
+ const groups = [];
182
+ for (const g of manifest.groups) {
183
+ const groupSet = Object.prototype.hasOwnProperty.call(groupsOpt, g.name) ? groupsOpt[g.name] : undefined;
184
+ const screens = new Map();
185
+ for (const item of g.items) {
186
+ const shot = parseShot(item.name, item.width, item.height, groupSet?.size ?? undefined);
187
+ const variants = screens.get(shot.key) ?? new Map();
188
+ screens.set(shot.key, variants);
189
+ for (const theme of shot.theme ? [shot.theme] : THEMES) {
190
+ const vid = `${shot.size}-${theme}`;
191
+ const v = variants.get(vid) ?? {
192
+ size: shot.size,
193
+ theme,
194
+ url: "",
195
+ url2x: null,
196
+ width: 0,
197
+ height: 0,
198
+ bytes: null,
199
+ bytes2x: null,
200
+ thumb: null,
201
+ };
202
+ if (shot.x2) {
203
+ if (v.url2x === null) {
204
+ v.url2x = item.url;
205
+ v.bytes2x = item.bytes ?? null;
206
+ }
207
+ }
208
+ else if (v.url === "") {
209
+ // An image wider than the width its name gives was taken at a higher density: shown at the name's width,
210
+ // its height rounded half up in integers (the same in every language).
211
+ const scaled = shot.cssWidth !== null && item.width > shot.cssWidth;
212
+ const width = scaled ? shot.cssWidth : item.width;
213
+ const height = scaled ? Math.floor((2 * item.height * shot.cssWidth + item.width) / (2 * item.width)) : item.height;
214
+ const t = item.thumb;
215
+ const thumb = t ? { url: t.url, width: t.width, height: t.height, bytes: t.bytes ?? null } : null;
216
+ Object.assign(v, { url: item.url, width, height, bytes: item.bytes ?? null, thumb });
217
+ }
218
+ variants.set(vid, v);
219
+ }
220
+ }
221
+ // The screens that have something to show; titles are made from these keys only.
222
+ const kept = [...screens]
223
+ .map(([key, variants]) => ({
224
+ key,
225
+ variants: [...variants.values()]
226
+ .filter((v) => v.url !== "")
227
+ .sort((a, b) => SIZES.indexOf(a.size) - SIZES.indexOf(b.size) || THEMES.indexOf(a.theme) - THEMES.indexOf(b.theme)),
228
+ }))
229
+ .filter((sc) => sc.variants.length > 0);
230
+ // A screen shows both themes at each of its sizes: one theme's image never stands in for the other's.
231
+ for (const sc of kept) {
232
+ for (const v of sc.variants) {
233
+ if (!sc.variants.some((o) => o.size === v.size && o.theme !== v.theme)) {
234
+ fail(`gallery screen ${sc.key} in group ${g.name} has a ${v.theme} ${v.size} screenshot but no ${v.theme === "light" ? "dark" : "light"} one`);
235
+ }
236
+ }
237
+ }
238
+ if (kept.length === 0)
239
+ continue;
240
+ const prefix = commonFolder(kept.map((sc) => sc.key)).length;
241
+ const rank = rankBy(order);
242
+ const list = kept
243
+ .map(({ key, variants }) => {
244
+ const set = Object.prototype.hasOwnProperty.call(screensOpt, key) ? screensOpt[key] : undefined;
245
+ return {
246
+ key,
247
+ title: set?.title ?? humanize(key.split("/").slice(prefix)),
248
+ caption: set?.caption ?? null,
249
+ variants,
250
+ };
251
+ })
252
+ .sort((a, b) => rank(a.key) - rank(b.key) || compare(a.key, b.key));
253
+ let slug = slugify(g.name);
254
+ for (let n = 2; slugs.has(slug); n++)
255
+ slug = `${slugify(g.name)}-${n}`;
256
+ slugs.add(slug);
257
+ groups.push({
258
+ name: g.name,
259
+ title: groupSet?.title ?? g.title ?? g.name,
260
+ slug,
261
+ fit: groupSet?.fit ?? "cover",
262
+ sizes: SIZES.filter((sz) => list.some((sc) => sc.variants.some((v) => v.size === sz))),
263
+ screens: list,
264
+ });
265
+ }
266
+ if (groups.length === 0)
267
+ fail("the gallery manifest has no screenshots to show");
268
+ // Named groups first; the rest keep the manifest's order (the sort is stable).
269
+ const groupRank = rankBy(groupOrder);
270
+ groups.sort((a, b) => groupRank(a.name) - groupRank(b.name));
271
+ return {
272
+ layout,
273
+ themeSwitch: layout === "grid" && themeSwitchOpt,
274
+ seeAll: seeAllOpt ? { href: seeAllOpt.href, text: seeAllOpt.text ?? SEE_ALL_TEXT } : null,
275
+ title,
276
+ label: title ?? DEFAULT_TITLE,
277
+ headingLevel,
278
+ id,
279
+ credit,
280
+ preload,
281
+ groups,
282
+ };
283
+ }
@@ -0,0 +1,149 @@
1
+ import { type Theme } from "./model.js";
2
+ /** One image of a card at the size its tab shows: the thumbnail's URL and its full-size (2x) copy, if any. */
3
+ export interface PlanImage {
4
+ url: string;
5
+ full: string | null;
6
+ width: number;
7
+ height: number;
8
+ /** Bytes of `url` and of `full`: the manifest's where it gives them, else estimateBytes. */
9
+ bytes: number;
10
+ fullBytes: number;
11
+ }
12
+ export interface PlanCard {
13
+ light: PlanImage;
14
+ dark: PlanImage;
15
+ }
16
+ export interface PlanTab {
17
+ cards: PlanCard[];
18
+ /** How many of its cards are above the fold (measured for the shown tab, estimated for the rest). */
19
+ fold: number;
20
+ }
21
+ export interface Item {
22
+ url: string;
23
+ /** An estimate when the size isn't known: see estimateBytes. */
24
+ bytes: number;
25
+ /** Loads whatever the caps say: above the fold, or something the reader did. */
26
+ always: boolean;
27
+ }
28
+ export interface Caps {
29
+ /** Above-the-fold thumbnails of the shown tab, which always load. */
30
+ fold: number;
31
+ /** Everything else: at most this many images… */
32
+ count: number;
33
+ /** …and this many bytes. */
34
+ bytes: number;
35
+ /** Requests at once. */
36
+ parallel: number;
37
+ }
38
+ export declare const DEFAULT_CAPS: Caps;
39
+ /** What a slow connection allows: the shown tab's thumbnails, two at a time. */
40
+ export declare const SLOW_PARALLEL = 2;
41
+ /** The manifest gives no file sizes. VisualCI's PNG screenshots average about 0.08 bytes a pixel (measured on two
42
+ * real galleries, 0.02 to 0.2); 0.1 errs on the side of preloading less. */
43
+ export declare function estimateBytes(width: number, height: number): number;
44
+ export type Mode = "full" | "light";
45
+ export interface PlanInput {
46
+ tabs: PlanTab[];
47
+ current: number;
48
+ theme: Theme;
49
+ caps: Caps;
50
+ /** "light": the shown tab's thumbnails only (Save-Data, a slow connection). */
51
+ mode: Mode;
52
+ /** Whether the full-size view uses the 2x copies (a high-density screen). */
53
+ hiDpi: boolean;
54
+ /** Already loaded: left out, so they cost nothing against the caps. */
55
+ done?: Set<string>;
56
+ /** Images and bytes the background has already loaded past the fold: the caps hold for the whole page view, not
57
+ * for each plan. */
58
+ spent?: {
59
+ count: number;
60
+ bytes: number;
61
+ };
62
+ }
63
+ /** The background queue: thumbnails in the shown theme, then the other theme, then the full-size images, each in the
64
+ * order above, within the caps. The same image twice (a screen shown the same in both themes) is queued once. */
65
+ export declare function plan(input: PlanInput): Item[];
66
+ /** A tab the reader opened: its fold, then the rest of it, in the shown theme. Uncapped: the reader asked for it. */
67
+ export declare function tabItems(tab: PlanTab, theme: Theme, foldOnly?: boolean): Item[];
68
+ /** In the full-size view at card `i`: the next one, the one after, the previous one, the one before that. */
69
+ export declare function neighbours(cards: PlanCard[], i: number, theme: Theme, hiDpi: boolean): Item[];
70
+ export interface Request {
71
+ /** Resolves when the image has loaded (true) or failed (false). Never rejects. */
72
+ done: Promise<boolean>;
73
+ cancel(): void;
74
+ }
75
+ /** Start and end of a finished request, in milliseconds, and its size in bytes when the browser can say (a
76
+ * cross-origin image without Timing-Allow-Origin can't). */
77
+ export interface Timing {
78
+ start: number;
79
+ end: number;
80
+ bytes: number | null;
81
+ }
82
+ export interface Env {
83
+ load(url: string, high: boolean): Request;
84
+ /** Runs `fn` when the browser is idle. */
85
+ idle(fn: () => void): void;
86
+ /** The finished request's timing, if the browser recorded it. */
87
+ timing(url: string): Timing | null;
88
+ /** Runs `fn` after `ms` milliseconds. */
89
+ later(fn: () => void, ms: number): void;
90
+ }
91
+ /** After a slow verdict with nothing left to load, the preloader tries the full plan again after this long, doubling
92
+ * each time the rate is still slow. */
93
+ export declare const RECHECK_MS = 15000;
94
+ /** Bytes a second below which the connection counts as slow: 125 KB/s, 1 Mbit/s. */
95
+ export declare const SLOW_RATE = 125000;
96
+ /** Finished requests a rate is measured over, the latest ones. */
97
+ export declare const RATE_WINDOW = 6;
98
+ export declare class Preloader {
99
+ private env;
100
+ private caps;
101
+ /** Called when the measured rate crosses SLOW_RATE, so the owner can plan again in the other mode. */
102
+ private onSpeed;
103
+ private queue;
104
+ private front;
105
+ private running;
106
+ private finished;
107
+ private samples;
108
+ private stopped;
109
+ private pumping;
110
+ private recheck;
111
+ private rechecking;
112
+ /** Background images loaded past the fold, against the caps. */
113
+ readonly spent: {
114
+ count: number;
115
+ bytes: number;
116
+ };
117
+ /** Set by a slow measured rate, cleared by a fast one. */
118
+ slow: boolean;
119
+ constructor(env: Env, caps: Caps,
120
+ /** Called when the measured rate crosses SLOW_RATE, so the owner can plan again in the other mode. */
121
+ onSpeed?: (slow: boolean) => void);
122
+ /** Replaces the background queue. Background requests still running that the new plan doesn't want are dropped. */
123
+ setPlan(items: Item[]): void;
124
+ /** Puts what the reader did (or is about to do) ahead of everything, replacing the last jump. To make room, the
125
+ * background requests running are dropped first, then the old jump's. */
126
+ jump(items: Item[], high: boolean): void;
127
+ /** Adds a likely next step (a tab the pointer is over) after the current jump, without dropping anything. */
128
+ hint(items: Item[]): void;
129
+ /** Every URL loaded so far. */
130
+ loaded(): Set<string>;
131
+ has(url: string): boolean;
132
+ /** What's running, for tests. */
133
+ inFlight(): string[];
134
+ stop(): void;
135
+ private parallel;
136
+ private drop;
137
+ /** The background waits for idle time; a jump starts at once. */
138
+ private schedule;
139
+ private next;
140
+ private pump;
141
+ /** The rate over the latest finished requests: their bytes over the time from the first start to the last end, so
142
+ * requests running side by side count once. Cached ones are left out. */
143
+ private measure;
144
+ /** A new verdict starts a new window, so old samples never decide the next one. */
145
+ private flip;
146
+ /** Slow, with nothing left to load: nothing new gets measured, so after a while try the full plan again. If the
147
+ * rate is still slow the next samples say so, and the wait doubles. */
148
+ private maybeRecheck;
149
+ }