visualci-gallery 0.1.0 → 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.
@@ -0,0 +1,319 @@
1
+ // Predictive preloading (contract/SPEC.md, "Preloading"): once the page has loaded, the gallery fetches the images a
2
+ // reader is likely to look at next, in idle time, a few at a time, so a tab or the full-size view shows at once.
3
+ //
4
+ // The order and the limits are pure logic (plan, tabItems, neighbours), and so is the queue (Preloader), which takes
5
+ // its loader, idle callback and timing source from outside, so tests drive every case without a browser.
6
+ import { PRELOAD_DEFAULTS } from "./model.js";
7
+ export const DEFAULT_CAPS = { ...PRELOAD_DEFAULTS };
8
+ /** What a slow connection allows: the shown tab's thumbnails, two at a time. */
9
+ export const SLOW_PARALLEL = 2;
10
+ /** The manifest gives no file sizes. VisualCI's PNG screenshots average about 0.08 bytes a pixel (measured on two
11
+ * real galleries, 0.02 to 0.2); 0.1 errs on the side of preloading less. */
12
+ export function estimateBytes(width, height) {
13
+ return Math.round(width * height * 0.1);
14
+ }
15
+ const other = (t) => (t === "light" ? "dark" : "light");
16
+ function thumb(img, always) {
17
+ return { url: img.url, bytes: img.bytes, always };
18
+ }
19
+ /** The full-size view's image for a card (`full`: the original behind a thumbnail, or the 2x copy on a high-density
20
+ * screen), else the card's own image, already loaded, so it costs nothing. hiDpi is decided when `full` is chosen. */
21
+ function fullOf(img, _hiDpi) {
22
+ return img.full ? { url: img.full, bytes: img.fullBytes, always: false } : thumb(img, false);
23
+ }
24
+ /** The other tabs, from the one after the shown tab, left to right, wrapping round. */
25
+ function othersFrom(tabs, current) {
26
+ const out = [];
27
+ for (let i = 1; i < tabs.length; i++)
28
+ out.push((current + i) % tabs.length);
29
+ return out;
30
+ }
31
+ /** The cards in preloading order for one theme: the shown tab's fold, its rest, the fold of every other tab, then the
32
+ * rest of each other tab. Each entry says whether it's the shown tab's fold. */
33
+ function order(tabs, current) {
34
+ const shown = tabs[current];
35
+ if (!shown)
36
+ return [];
37
+ const rest = othersFrom(tabs, current);
38
+ const out = [];
39
+ shown.cards.forEach((card, i) => {
40
+ if (i < shown.fold)
41
+ out.push({ card, fold: true });
42
+ });
43
+ shown.cards.forEach((card, i) => {
44
+ if (i >= shown.fold)
45
+ out.push({ card, fold: false });
46
+ });
47
+ for (const t of rest)
48
+ tabs[t].cards.slice(0, tabs[t].fold).forEach((card) => out.push({ card, fold: false }));
49
+ for (const t of rest)
50
+ tabs[t].cards.slice(tabs[t].fold).forEach((card) => out.push({ card, fold: false }));
51
+ return out;
52
+ }
53
+ /** The background queue: thumbnails in the shown theme, then the other theme, then the full-size images, each in the
54
+ * order above, within the caps. The same image twice (a screen shown the same in both themes) is queued once. */
55
+ export function plan(input) {
56
+ const { tabs, current, theme, caps, mode, hiDpi } = input;
57
+ const seq = order(tabs, current);
58
+ const candidates = [];
59
+ if (mode === "light") {
60
+ const shown = tabs[current];
61
+ if (shown)
62
+ for (const card of shown.cards)
63
+ candidates.push(thumb(card[theme], false));
64
+ shown?.cards.slice(0, shown.fold).forEach((_, i) => (candidates[i].always = true));
65
+ }
66
+ else {
67
+ for (const s of seq)
68
+ candidates.push(thumb(s.card[theme], s.fold));
69
+ for (const s of seq)
70
+ candidates.push(thumb(s.card[other(theme)], false));
71
+ for (const t of [theme, other(theme)])
72
+ for (const s of seq)
73
+ candidates.push(fullOf(s.card[t], hiDpi));
74
+ }
75
+ const spent = input.spent ?? { count: 0, bytes: 0 };
76
+ const left = { ...caps, count: caps.count - spent.count, bytes: caps.bytes - spent.bytes };
77
+ const done = input.done;
78
+ return capped(done ? candidates.filter((c) => !done.has(c.url)) : candidates, left);
79
+ }
80
+ /** Drops repeats, keeps up to caps.fold of the always items and stops at the first other item past the count or
81
+ * bytes cap, so what loads is a prefix of the order. */
82
+ function capped(items, caps) {
83
+ const seen = new Set();
84
+ const out = [];
85
+ let always = 0;
86
+ let count = 0;
87
+ let bytes = 0;
88
+ for (const item of items) {
89
+ if (seen.has(item.url))
90
+ continue;
91
+ seen.add(item.url);
92
+ if (item.always && always < caps.fold) {
93
+ always++;
94
+ out.push(item);
95
+ continue;
96
+ }
97
+ const it = { ...item, always: false };
98
+ if (count + 1 > caps.count || bytes + it.bytes > caps.bytes)
99
+ break;
100
+ count++;
101
+ bytes += it.bytes;
102
+ out.push(it);
103
+ }
104
+ return out;
105
+ }
106
+ /** A tab the reader opened: its fold, then the rest of it, in the shown theme. Uncapped: the reader asked for it. */
107
+ export function tabItems(tab, theme, foldOnly = false) {
108
+ const cards = foldOnly ? tab.cards.slice(0, tab.fold) : tab.cards;
109
+ return cards.map((c) => thumb(c[theme], true));
110
+ }
111
+ /** In the full-size view at card `i`: the next one, the one after, the previous one, the one before that. */
112
+ export function neighbours(cards, i, theme, hiDpi) {
113
+ const n = cards.length;
114
+ if (n < 2)
115
+ return [];
116
+ const seen = new Set([i]);
117
+ const out = [];
118
+ for (const by of [1, 2, -1, -2]) {
119
+ const j = (((i + by) % n) + n) % n;
120
+ if (seen.has(j))
121
+ continue;
122
+ seen.add(j);
123
+ out.push({ ...fullOf(cards[j][theme], hiDpi), always: true });
124
+ }
125
+ return out;
126
+ }
127
+ /** After a slow verdict with nothing left to load, the preloader tries the full plan again after this long, doubling
128
+ * each time the rate is still slow. */
129
+ export const RECHECK_MS = 15_000;
130
+ /** Bytes a second below which the connection counts as slow: 125 KB/s, 1 Mbit/s. */
131
+ export const SLOW_RATE = 125_000;
132
+ /** Finished requests a rate is measured over, the latest ones. */
133
+ export const RATE_WINDOW = 6;
134
+ /** Requests shorter than this came from the cache and say nothing about the connection. */
135
+ const CACHED_MS = 8;
136
+ export class Preloader {
137
+ env;
138
+ caps;
139
+ onSpeed;
140
+ queue = [];
141
+ front = [];
142
+ running = new Map();
143
+ finished = new Set();
144
+ samples = [];
145
+ stopped = false;
146
+ pumping = false;
147
+ recheck = RECHECK_MS;
148
+ rechecking = false;
149
+ /** Background images loaded past the fold, against the caps. */
150
+ spent = { count: 0, bytes: 0 };
151
+ /** Set by a slow measured rate, cleared by a fast one. */
152
+ slow = false;
153
+ constructor(env, caps,
154
+ /** Called when the measured rate crosses SLOW_RATE, so the owner can plan again in the other mode. */
155
+ onSpeed = () => { }) {
156
+ this.env = env;
157
+ this.caps = caps;
158
+ this.onSpeed = onSpeed;
159
+ }
160
+ /** Replaces the background queue. Background requests still running that the new plan doesn't want are dropped. */
161
+ setPlan(items) {
162
+ this.queue = items.slice();
163
+ const wanted = new Set(items.map((i) => i.url));
164
+ for (const r of this.running.values())
165
+ if (!r.front && !wanted.has(r.item.url))
166
+ this.drop(r);
167
+ this.schedule();
168
+ this.maybeRecheck();
169
+ }
170
+ /** Puts what the reader did (or is about to do) ahead of everything, replacing the last jump. To make room, the
171
+ * background requests running are dropped first, then the old jump's. */
172
+ jump(items, high) {
173
+ this.front = items.filter((i) => !this.finished.has(i.url)).map((item) => ({ item, high }));
174
+ const wanted = new Set(this.front.map((f) => f.item.url));
175
+ const waiting = this.front.filter((f) => !this.running.has(f.item.url)).length;
176
+ let free = this.parallel() - this.running.size;
177
+ const victims = [...this.running.values()]
178
+ .filter((r) => !wanted.has(r.item.url))
179
+ .sort((a, b) => Number(a.front) - Number(b.front));
180
+ const back = [];
181
+ for (const r of victims) {
182
+ if (free >= waiting)
183
+ break;
184
+ this.drop(r);
185
+ // Dropped only to make room: a background image goes back to the head of the queue, in its order.
186
+ if (!r.front)
187
+ back.push(r.item);
188
+ free++;
189
+ }
190
+ this.queue.unshift(...back);
191
+ this.pump();
192
+ }
193
+ /** Adds a likely next step (a tab the pointer is over) after the current jump, without dropping anything. */
194
+ hint(items) {
195
+ const queued = new Set(this.front.map((f) => f.item.url));
196
+ for (const item of items) {
197
+ if (!this.finished.has(item.url) && !queued.has(item.url))
198
+ this.front.push({ item, high: false });
199
+ }
200
+ this.pump();
201
+ }
202
+ /** Every URL loaded so far. */
203
+ loaded() {
204
+ return new Set(this.finished);
205
+ }
206
+ has(url) {
207
+ return this.finished.has(url);
208
+ }
209
+ /** What's running, for tests. */
210
+ inFlight() {
211
+ return [...this.running.keys()];
212
+ }
213
+ stop() {
214
+ this.stopped = true;
215
+ for (const r of this.running.values())
216
+ r.req.cancel();
217
+ this.running.clear();
218
+ this.queue = [];
219
+ this.front = [];
220
+ }
221
+ parallel() {
222
+ return this.slow ? Math.min(SLOW_PARALLEL, this.caps.parallel) : this.caps.parallel;
223
+ }
224
+ drop(r) {
225
+ r.req.cancel();
226
+ this.running.delete(r.item.url);
227
+ }
228
+ /** The background waits for idle time; a jump starts at once. */
229
+ schedule() {
230
+ if (this.pumping || this.stopped)
231
+ return;
232
+ this.pumping = true;
233
+ this.env.idle(() => {
234
+ this.pumping = false;
235
+ this.pump();
236
+ });
237
+ }
238
+ next() {
239
+ while (this.front.length) {
240
+ const f = this.front.shift();
241
+ if (!this.finished.has(f.item.url) && !this.running.has(f.item.url))
242
+ return { ...f, front: true };
243
+ }
244
+ while (this.queue.length) {
245
+ const item = this.queue.shift();
246
+ if (!this.finished.has(item.url) && !this.running.has(item.url))
247
+ return { item, high: false, front: false };
248
+ }
249
+ return null;
250
+ }
251
+ pump() {
252
+ while (!this.stopped && this.running.size < this.parallel()) {
253
+ const n = this.next();
254
+ if (!n)
255
+ return;
256
+ const req = this.env.load(n.item.url, n.high);
257
+ const r = { item: n.item, high: n.high, front: n.front, req };
258
+ this.running.set(n.item.url, r);
259
+ req.done.then((ok) => {
260
+ if (this.running.get(n.item.url) !== r)
261
+ return; // dropped
262
+ this.running.delete(n.item.url);
263
+ this.finished.add(n.item.url);
264
+ if (!n.front && !n.item.always) {
265
+ this.spent.count++;
266
+ this.spent.bytes += n.item.bytes;
267
+ }
268
+ if (ok)
269
+ this.measure(n.item);
270
+ if (this.front.length)
271
+ this.pump();
272
+ else
273
+ this.schedule();
274
+ this.maybeRecheck();
275
+ });
276
+ }
277
+ }
278
+ /** The rate over the latest finished requests: their bytes over the time from the first start to the last end, so
279
+ * requests running side by side count once. Cached ones are left out. */
280
+ measure(item) {
281
+ const t = this.env.timing(item.url);
282
+ if (!t || t.end - t.start < CACHED_MS)
283
+ return;
284
+ this.samples.push({ start: t.start, end: t.end, bytes: t.bytes ?? item.bytes });
285
+ if (this.samples.length > RATE_WINDOW)
286
+ this.samples.shift();
287
+ if (this.samples.length < Math.min(3, RATE_WINDOW))
288
+ return;
289
+ const start = Math.min(...this.samples.map((s) => s.start));
290
+ const end = Math.max(...this.samples.map((s) => s.end));
291
+ const bytes = this.samples.reduce((sum, s) => sum + s.bytes, 0);
292
+ const slow = bytes / ((end - start) / 1000) < SLOW_RATE;
293
+ if (slow !== this.slow)
294
+ this.flip(slow);
295
+ else if (!slow)
296
+ this.recheck = RECHECK_MS;
297
+ }
298
+ /** A new verdict starts a new window, so old samples never decide the next one. */
299
+ flip(slow) {
300
+ this.slow = slow;
301
+ this.samples = [];
302
+ this.onSpeed(slow);
303
+ }
304
+ /** Slow, with nothing left to load: nothing new gets measured, so after a while try the full plan again. If the
305
+ * rate is still slow the next samples say so, and the wait doubles. */
306
+ maybeRecheck() {
307
+ if (!this.slow || this.rechecking || this.stopped || this.running.size || this.front.length || this.queue.length)
308
+ return;
309
+ this.rechecking = true;
310
+ const wait = this.recheck;
311
+ this.recheck *= 2;
312
+ this.env.later(() => {
313
+ this.rechecking = false;
314
+ if (this.stopped || !this.slow)
315
+ return;
316
+ this.flip(false);
317
+ }, wait);
318
+ }
319
+ }
package/dist/render.js CHANGED
@@ -21,11 +21,21 @@ function sizeSwitch(sizes, extra = "") {
21
21
  sizes.map((s) => `<button type="button" data-vg-set-size="${s}" aria-pressed="false">${SIZE_LABEL[s]}</button>`).join("") +
22
22
  "</div>");
23
23
  }
24
+ /** The sizes the preloader caps by, where the manifest gives them: of the card's image (`src`), of the full-size one
25
+ * when the card shows a thumbnail, and of the 2x copy. */
26
+ function bytesAttrs(v) {
27
+ const shown = v.thumb ? v.thumb.bytes : v.bytes;
28
+ return ((shown !== null ? ` data-vg-bytes="${shown}"` : "") +
29
+ (v.thumb && v.bytes !== null ? ` data-vg-full-bytes="${v.bytes}"` : "") +
30
+ (v.url2x && v.bytes2x !== null ? ` data-vg-2x-bytes="${v.bytes2x}"` : ""));
31
+ }
24
32
  /** An image, shown for `themes`, which its alt text names. */
25
33
  function image(title, v, themes) {
26
34
  const alt = `${title}, ${SIZE_LABEL[v.size].toLowerCase()}, ${themes.join(" and ")}`;
27
- return (`<img class="vg-img" data-vg-size="${v.size}" data-vg-theme="${themes.join(" ")}" src="${escapeHtml(v.url)}"` +
35
+ return (`<img class="vg-img" data-vg-size="${v.size}" data-vg-theme="${themes.join(" ")}" src="${escapeHtml(v.thumb ? v.thumb.url : v.url)}"` +
36
+ (v.thumb ? ` data-src-full="${escapeHtml(v.url)}"` : "") +
28
37
  (v.url2x ? ` data-src-2x="${escapeHtml(v.url2x)}"` : "") +
38
+ bytesAttrs(v) +
29
39
  ` width="${v.width}" height="${v.height}" alt="${escapeHtml(alt)}" loading="lazy" decoding="async">`);
30
40
  }
31
41
  /** One card: a link to its first image (which hydrate() turns into the full-size view), every variant at the given
@@ -41,7 +51,7 @@ function card(sc, sizes, heading, caption, fit) {
41
51
  shown.push(size);
42
52
  first ??= at[0];
43
53
  // Every size has both themes (the model refuses a screen without); the same image for both is shown once.
44
- if (at[0].url === at[1].url && at[0].url2x === at[1].url2x) {
54
+ if (at[0].url === at[1].url && at[0].url2x === at[1].url2x && at[0].thumb?.url === at[1].thumb?.url) {
45
55
  imgs.push(image(sc.title, at[0], ["light", "dark"]));
46
56
  }
47
57
  else
@@ -58,6 +68,14 @@ function card(sc, sizes, heading, caption, fit) {
58
68
  (caption && sc.caption !== null ? `<p class="vg-caption">${escapeHtml(sc.caption)}</p>` : "") +
59
69
  "</li>");
60
70
  }
71
+ /** Preloading with the defaults needs no attribute; off, or with caps of the site's own, says so. */
72
+ function preloadAttr(p) {
73
+ if (p === null)
74
+ return "";
75
+ if (p === "off")
76
+ return ' data-vg-preload="off"';
77
+ return ` data-vg-preload="fold=${p.fold} count=${p.count} bytes=${p.bytes} parallel=${p.parallel}"`;
78
+ }
61
79
  /** The gallery's markup: one line per block, no indentation, "\n" after each line. */
62
80
  export function render(model) {
63
81
  const id = escapeHtml(model.id);
@@ -68,6 +86,7 @@ export function render(model) {
68
86
  const size = model.layout === "strip" ? stripSize(model) : model.groups[0].sizes[0];
69
87
  out.push(`<section class="vg" data-vg data-vg-layout="${model.layout}" aria-label="${escapeHtml(model.label)}" data-vg-size="${size}"` +
70
88
  (model.themeSwitch ? "" : ' data-vg-theme-source="page"') +
89
+ preloadAttr(model.preload) +
71
90
  ">");
72
91
  if (model.title !== null)
73
92
  out.push(`<${h(0)} class="vg-title">${escapeHtml(model.title)}</${h(0)}>`);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "visualci-gallery",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "A screenshots page from VisualCI's public gallery: render it into an empty element, or hydrate markup a server rendered.",
5
5
  "license": "Apache-2.0",
6
6
  "homepage": "https://visualci.com/docs/gallery/",