@bezda/rhp-mcp 0.1.7 → 0.1.9
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/package.json +2 -2
- package/skill/SKILL.md +1 -1
- package/skill/recipes/area.html +349 -138
- package/skill/recipes/bar.html +349 -138
- package/skill/recipes/box-plot.html +349 -138
- package/skill/recipes/bubble.html +349 -138
- package/skill/recipes/bullet.html +349 -138
- package/skill/recipes/candlestick.html +349 -138
- package/skill/recipes/column.html +349 -138
- package/skill/recipes/dial.html +349 -138
- package/skill/recipes/diverging-bars.html +349 -138
- package/skill/recipes/donut.html +349 -138
- package/skill/recipes/dumbbell.html +349 -138
- package/skill/recipes/gantt.html +349 -138
- package/skill/recipes/grouped-bars.html +349 -138
- package/skill/recipes/heatmap.html +349 -138
- package/skill/recipes/histogram.html +349 -138
- package/skill/recipes/line.html +349 -138
- package/skill/recipes/live.html +349 -138
- package/skill/recipes/log-line.html +349 -138
- package/skill/recipes/lollipop.html +349 -138
- package/skill/recipes/multi-line.html +349 -138
- package/skill/recipes/pyramid.html +349 -138
- package/skill/recipes/race.html +363 -139
- package/skill/recipes/radial-bars.html +349 -138
- package/skill/recipes/scatter.html +349 -138
- package/skill/recipes/silhouettes.html +349 -138
- package/skill/recipes/slope.html +349 -138
- package/skill/recipes/sparklines.html +349 -138
- package/skill/recipes/stacked-100.html +349 -138
- package/skill/recipes/stacked-bars.html +349 -138
- package/skill/recipes/strip.html +349 -138
- package/skill/recipes/tape.html +415 -165
- package/skill/recipes/unit-stack.html +349 -138
- package/skill/recipes/violin.html +349 -138
- package/skill/recipes/waffle.html +349 -138
- package/skill/recipes/waterfall.html +349 -138
- package/skill/references/api.md +4 -2
- package/skill/references/design.md +13 -0
- package/skill/references/download.md +372 -140
- package/skill/references/environments.md +1 -1
- package/skill/references/interaction.md +2 -0
- package/skill/references/performance.md +45 -0
- package/skill/references/pitfalls.md +9 -0
- package/src/check/README.md +2 -1
- package/src/check/findings.js +17 -1
- package/src/check/inpage.js +53 -5
- package/src/check/report.js +1 -1
- package/src/check/source.js +2 -1
- package/src/guard/rules.js +2 -2
|
@@ -140,7 +140,7 @@ render(() => html`<${WeekendScreens} />`, document.getElementById("chart"));
|
|
|
140
140
|
</script>
|
|
141
141
|
<style id="poster-download-styles">
|
|
142
142
|
.poster-download-tools { display: flex; justify-content: flex-end; align-items: center; margin: 0 auto 12px; max-width: 100%; }
|
|
143
|
-
.poster-actions { display: flex; align-items: center; margin-left: auto; }
|
|
143
|
+
.poster-actions { position: relative; display: flex; align-items: center; margin-left: auto; }
|
|
144
144
|
.poster-download, .poster-fit-toggle { display: inline-flex; align-items: center; justify-content: center; flex: 0 0 auto; width: 44px; height: 44px; padding: 10px; border: 0; border-radius: 4px; background: transparent; color: inherit; cursor: pointer; }
|
|
145
145
|
.poster-actions svg { display: block; width: 20px; height: 20px; }
|
|
146
146
|
.poster-actions button:hover { background: color-mix(in srgb, currentColor 8%, transparent); }
|
|
@@ -151,7 +151,14 @@ render(() => html`<${WeekendScreens} />`, document.getElementById("chart"));
|
|
|
151
151
|
.poster-fit-frame.is-fitted { display: block; margin: 0 auto; overflow: clip; }
|
|
152
152
|
.poster-fit-frame.is-fitted > .poster-fit-content { display: block; transform-origin: top left; }
|
|
153
153
|
.poster-download-error { margin: 8px auto; font: 14px/1.4 system-ui, sans-serif; color: inherit; }
|
|
154
|
-
|
|
154
|
+
.poster-download-progress { font: 600 11px/1 system-ui, sans-serif; font-variant-numeric: tabular-nums; }
|
|
155
|
+
.poster-download-menu { position: absolute; top: calc(100% + 4px); right: 0; z-index: 20; display: grid; gap: 2px; min-width: 220px; padding: 6px; border: 1px solid color-mix(in srgb, currentColor 24%, transparent); border-radius: 8px; background: var(--poster-tools-ground, Canvas); box-shadow: 0 8px 24px rgb(0 0 0 / .28); }
|
|
156
|
+
.poster-download-menu[hidden] { display: none; }
|
|
157
|
+
.poster-download-menu button { display: grid; gap: 2px; width: 100%; padding: 8px 10px; border: 0; border-radius: 5px; background: none; color: inherit; font: 600 14px/1.3 system-ui, sans-serif; text-align: left; cursor: pointer; }
|
|
158
|
+
.poster-download-menu button span { font-weight: 400; font-size: 12.5px; opacity: .8; }
|
|
159
|
+
.poster-download-menu button:hover { background: color-mix(in srgb, currentColor 9%, transparent); }
|
|
160
|
+
.poster-download-menu button:focus-visible { outline: 2px solid currentColor; outline-offset: -2px; }
|
|
161
|
+
@media print { .poster-download-tools, .poster-actions, .poster-download-menu, .poster-download-error { display: none !important; } }
|
|
155
162
|
</style>
|
|
156
163
|
<script type="module" id="poster-download-script">
|
|
157
164
|
function addPosterFit(poster, button, changed) {
|
|
@@ -229,6 +236,8 @@ function addPosterDownloads() {
|
|
|
229
236
|
tools.style.color = light[0] * .2126 + light[1] * .7152 + light[2] * .0722 < .179 ? '#eef2f5' : '#1d1b17';
|
|
230
237
|
}
|
|
231
238
|
}
|
|
239
|
+
const ground = getComputedStyle(document.body).backgroundColor;
|
|
240
|
+
if (!/^(transparent|rgba\(0, 0, 0, 0\))$/.test(ground)) tools.style.setProperty('--poster-tools-ground', ground);
|
|
232
241
|
const button = document.createElement('button');
|
|
233
242
|
button.type = 'button';
|
|
234
243
|
button.className = 'poster-download';
|
|
@@ -274,154 +283,356 @@ function addPosterDownloads() {
|
|
|
274
283
|
for (const type of ['keydown', 'keyup']) actions.addEventListener(type, event => {
|
|
275
284
|
if (event.key === 'Enter' || event.key === ' ') event.stopPropagation();
|
|
276
285
|
});
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
286
|
+
// A poster that plays through its data gives itself a playback ({ duration, position, seek }): its download then
|
|
287
|
+
// offers the poster as it is now, a PNG, or the whole playback, an animated GIF
|
|
288
|
+
let exporter, encoder, retries = 0, busy = false, making = null, cancelled = false;
|
|
289
|
+
const playable = () => typeof poster.playback?.seek === 'function';
|
|
290
|
+
const icon = button.innerHTML;
|
|
291
|
+
const menu = document.createElement('div');
|
|
292
|
+
menu.className = 'poster-download-menu';
|
|
293
|
+
menu.setAttribute('role', 'menu');
|
|
294
|
+
menu.setAttribute('aria-label', 'Download poster');
|
|
295
|
+
menu.hidden = true;
|
|
296
|
+
menu.innerHTML = '<button type="button" role="menuitem" data-format="png">PNG image<span>The poster as it is now</span></button>'
|
|
297
|
+
+ '<button type="button" role="menuitem" data-format="gif">Animated GIF<span>The whole playback</span></button>';
|
|
298
|
+
const items = [...menu.querySelectorAll('[role="menuitem"]')];
|
|
299
|
+
actions.append(menu);
|
|
300
|
+
const label = text => { button.setAttribute('aria-label', text); button.title = text; };
|
|
301
|
+
const rest = () => {
|
|
302
|
+
label(playable() ? 'Download poster' : 'Download poster as PNG');
|
|
303
|
+
if (playable()) { button.setAttribute('aria-haspopup', 'menu'); button.setAttribute('aria-expanded', String(!menu.hidden)); }
|
|
304
|
+
};
|
|
305
|
+
rest();
|
|
306
|
+
const closeMenu = focus => {
|
|
307
|
+
if (menu.hidden) return;
|
|
308
|
+
menu.hidden = true;
|
|
309
|
+
rest();
|
|
310
|
+
if (focus) button.focus();
|
|
311
|
+
};
|
|
312
|
+
const openMenu = focus => {
|
|
313
|
+
menu.hidden = false;
|
|
314
|
+
rest();
|
|
315
|
+
if (focus) items[0].focus();
|
|
316
|
+
};
|
|
317
|
+
document.addEventListener('pointerdown', event => { if (!actions.contains(event.target)) closeMenu(false); }, true);
|
|
318
|
+
menu.addEventListener('keydown', event => {
|
|
319
|
+
const at = items.indexOf(document.activeElement);
|
|
320
|
+
const to = { ArrowDown: at + 1, ArrowUp: at - 1, Home: 0, End: items.length - 1 }[event.key];
|
|
321
|
+
if (to !== undefined) { event.preventDefault(); items[(to + items.length) % items.length].focus(); }
|
|
322
|
+
else if (event.key === 'Escape') { event.preventDefault(); event.stopPropagation(); closeMenu(true); }
|
|
323
|
+
else if (event.key === 'Tab') closeMenu(false);
|
|
324
|
+
});
|
|
325
|
+
menu.addEventListener('focusout', event => { if (!menu.contains(event.relatedTarget) && event.relatedTarget !== button) closeMenu(false); });
|
|
326
|
+
// The capture options, made once for a download and for every frame of a GIF
|
|
327
|
+
const loadExporter = () => (exporter ||= import('https://cdn.jsdelivr.net/npm/modern-screenshot@4.7.0/+esm' + (retries ? `?retry=${retries}` : '')));
|
|
328
|
+
async function captureOptions() {
|
|
329
|
+
await document.fonts.ready;
|
|
330
|
+
// Preserve author layout rules where computed styles lose the grid's used geometry.
|
|
331
|
+
// Safari misreports percentage insets in subgrids, and grid auto margins resolve to zero.
|
|
332
|
+
const autoMargins = new Set(), positioned = new Set();
|
|
333
|
+
const isMargin = name => name === 'margin' || name.startsWith('margin-');
|
|
334
|
+
const isInset = name => name === 'inset' || name.startsWith('inset-') || ['top', 'right', 'bottom', 'left'].includes(name);
|
|
335
|
+
const layoutRules = rules => [...rules].map(rule => {
|
|
336
|
+
if (rule.selectorText && rule.style) {
|
|
337
|
+
const margins = [...rule.style].filter(isMargin);
|
|
338
|
+
if (margins.some(name => /\bauto\b/.test(rule.style.getPropertyValue(name)))) autoMargins.add(rule.selectorText);
|
|
339
|
+
const insets = [...rule.style].filter(isInset);
|
|
340
|
+
if (insets.length) positioned.add(rule.selectorText);
|
|
341
|
+
const layout = [...margins, ...insets];
|
|
342
|
+
return layout.length ? `${rule.selectorText} { ${layout.map(name => `${name}: ${rule.style.getPropertyValue(name)}${rule.style.getPropertyPriority(name) ? ' !important' : ''};`).join(' ')} }` : '';
|
|
343
|
+
}
|
|
344
|
+
if (!rule.cssRules) return /^@layer\b/.test(rule.cssText) ? rule.cssText : '';
|
|
345
|
+
if (rule instanceof CSSMediaRule) return matchMedia(rule.conditionText).matches ? layoutRules(rule.cssRules) : '';
|
|
346
|
+
if (rule instanceof CSSSupportsRule) return CSS.supports(rule.conditionText) ? layoutRules(rule.cssRules) : '';
|
|
347
|
+
return rule.cssText.slice(0, rule.cssText.indexOf('{') + 1) + layoutRules(rule.cssRules) + '}';
|
|
348
|
+
}).join('\n');
|
|
349
|
+
const sheets = [...document.styleSheets, ...document.adoptedStyleSheets];
|
|
350
|
+
const layout = sheets.map(sheet => {
|
|
351
|
+
try { return layoutRules(sheet.cssRules); } catch (cause) { return ''; }
|
|
352
|
+
}).join('\n');
|
|
353
|
+
// Omit display-none HTML subtrees, such as collapsed chart rows, from the image and its SVG payload.
|
|
354
|
+
const includeNode = node => !(node instanceof HTMLElement) || getComputedStyle(node).display !== 'none';
|
|
355
|
+
const restoreLayout = (source, clone) => {
|
|
356
|
+
if (clone.style && source !== poster) {
|
|
357
|
+
const margins = [...autoMargins].some(selector => source.matches(selector));
|
|
358
|
+
const computed = getComputedStyle(source);
|
|
359
|
+
const insets = computed.position === 'absolute' && [...positioned].some(selector => source.matches(selector));
|
|
360
|
+
const restore = name => (margins && isMargin(name)) || (insets && isInset(name));
|
|
361
|
+
[...clone.style].filter(restore).forEach(name => clone.style.removeProperty(name));
|
|
362
|
+
[...source.style].filter(restore).forEach(name => clone.style.setProperty(name, source.style.getPropertyValue(name), source.style.getPropertyPriority(name)));
|
|
363
|
+
if (insets) {
|
|
364
|
+
// Only the scaled axis needs its percentage rule. Freeze the other axis in pixels:
|
|
365
|
+
// Firefox does not reevaluate container queries reliably inside an SVG foreignObject.
|
|
366
|
+
const axis = source.getAttribute('data-rhp-o');
|
|
367
|
+
const fixed = axis === 'h' ? ['top', 'bottom'] : axis === 'v' ? ['left', 'right'] : ['top', 'right', 'bottom', 'left'];
|
|
368
|
+
fixed.forEach(name => clone.style.setProperty(name, computed.getPropertyValue(name), 'important'));
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
const children = [...source.children].filter(node => !['STYLE', 'SCRIPT'].includes(node.tagName) && includeNode(node));
|
|
372
|
+
[...clone.children].forEach((child, i) => { if (children[i]) restoreLayout(children[i], child); });
|
|
373
|
+
};
|
|
374
|
+
// Cross-origin font stylesheets are readable through fetch, but not through cssRules.
|
|
375
|
+
const fontFiles = new Map();
|
|
376
|
+
const fontRules = await Promise.all(sheets.map(async sheet => {
|
|
377
|
+
let css;
|
|
378
|
+
try { css = [...sheet.cssRules].map(rule => rule.cssText).join('\n'); }
|
|
379
|
+
catch (cause) {
|
|
380
|
+
if (!sheet.href) return '';
|
|
381
|
+
const response = await fetch(sheet.href);
|
|
382
|
+
if (!response.ok) throw new Error('Font stylesheet could not be loaded');
|
|
383
|
+
css = await response.text();
|
|
384
|
+
}
|
|
385
|
+
const rules = css.match(/@font-face\s*\{[^}]*\}/g) || [];
|
|
386
|
+
return (await Promise.all(rules.map(async rule => {
|
|
387
|
+
for (const match of [...rule.matchAll(/url\(["']?([^"')]+)["']?\)/g)]) {
|
|
388
|
+
const source = new URL(match[1], sheet.href || document.baseURI).href;
|
|
389
|
+
if (!fontFiles.has(source)) fontFiles.set(source, (async () => {
|
|
390
|
+
const response = await fetch(source);
|
|
391
|
+
if (!response.ok) throw new Error('Font could not be loaded');
|
|
392
|
+
const blob = await response.blob();
|
|
393
|
+
return new Promise((resolve, reject) => {
|
|
394
|
+
const reader = new FileReader();
|
|
395
|
+
reader.onload = () => resolve(reader.result);
|
|
396
|
+
reader.onerror = reject;
|
|
397
|
+
reader.readAsDataURL(blob);
|
|
398
|
+
});
|
|
399
|
+
})());
|
|
400
|
+
rule = rule.replace(match[1], await fontFiles.get(source));
|
|
401
|
+
}
|
|
402
|
+
return rule;
|
|
403
|
+
}))).join('\n');
|
|
404
|
+
}));
|
|
405
|
+
// Rasterize SVG paper textures before nesting them inside the exporter's SVG.
|
|
406
|
+
// This keeps SVG filter fragment references local to their own image.
|
|
407
|
+
const textures = new Map();
|
|
408
|
+
const embedTexture = async (node) => {
|
|
409
|
+
if (!node.style) return;
|
|
410
|
+
let background = node.style.backgroundImage;
|
|
411
|
+
for (const [, source] of background.matchAll(/url\("(data:image\/svg\+xml[^"]+)"\)/g)) {
|
|
412
|
+
if (!textures.has(source)) textures.set(source, (async () => {
|
|
413
|
+
const image = new Image();
|
|
414
|
+
image.src = source;
|
|
415
|
+
await image.decode();
|
|
416
|
+
const canvas = document.createElement('canvas');
|
|
417
|
+
canvas.width = image.naturalWidth;
|
|
418
|
+
canvas.height = image.naturalHeight;
|
|
419
|
+
canvas.getContext('2d').drawImage(image, 0, 0);
|
|
420
|
+
return canvas.toDataURL();
|
|
421
|
+
})());
|
|
422
|
+
background = background.replace(source, await textures.get(source));
|
|
423
|
+
}
|
|
424
|
+
node.style.backgroundImage = background;
|
|
425
|
+
};
|
|
426
|
+
return {
|
|
427
|
+
...fit.dimensions(), style: { margin: '0' }, filter: includeNode,
|
|
428
|
+
font: { cssText: fontRules.join('\n') }, onCloneEachNode: embedTexture,
|
|
429
|
+
onCloneNode: clone => {
|
|
430
|
+
restoreLayout(poster, clone);
|
|
431
|
+
const style = document.createElement('style');
|
|
432
|
+
style.textContent = layout;
|
|
433
|
+
clone.prepend(style);
|
|
434
|
+
},
|
|
435
|
+
// CSS content's alternative text follows a slash and must not be painted.
|
|
436
|
+
onCreateForeignObjectSvg: svg => svg.querySelectorAll('style').forEach(style => {
|
|
437
|
+
style.textContent = style.textContent.replace(/(content:\s*')([^']*)(')/g, (_, start, text, end) => start + text.split(' / ')[0] + end);
|
|
438
|
+
}),
|
|
439
|
+
};
|
|
440
|
+
}
|
|
441
|
+
let url;
|
|
442
|
+
const save = (blob, extension) => {
|
|
443
|
+
url = URL.createObjectURL(blob);
|
|
444
|
+
const link = document.createElement('a');
|
|
445
|
+
const title = poster.querySelector('.headline')?.textContent || document.title || 'poster';
|
|
446
|
+
link.download = (title.trim().toLowerCase().replace(/[^\p{L}\p{N}]+/gu, '-').replace(/^-|-$/g, '').slice(0, 100) || 'poster') + '.' + extension;
|
|
447
|
+
link.href = url;
|
|
448
|
+
link.addEventListener('click', event => event.stopPropagation(), { once: true });
|
|
449
|
+
document.body.append(link);
|
|
450
|
+
link.click();
|
|
451
|
+
link.remove();
|
|
452
|
+
};
|
|
453
|
+
const begin = kind => {
|
|
281
454
|
busy = true;
|
|
282
|
-
|
|
455
|
+
making = kind;
|
|
283
456
|
button.setAttribute('aria-busy', 'true');
|
|
284
457
|
fitButton.setAttribute('aria-disabled', 'true');
|
|
285
|
-
button
|
|
458
|
+
// A GIF takes a while: the button shows its progress and cancels it
|
|
459
|
+
if (kind === 'gif') label('Cancel the GIF');
|
|
460
|
+
else { button.setAttribute('aria-disabled', 'true'); label('Preparing poster PNG'); }
|
|
286
461
|
error.hidden = true;
|
|
287
|
-
|
|
462
|
+
};
|
|
463
|
+
const end = () => {
|
|
464
|
+
if (url) setTimeout(() => URL.revokeObjectURL(url), 60000);
|
|
465
|
+
url = null;
|
|
466
|
+
busy = false;
|
|
467
|
+
making = null;
|
|
468
|
+
cancelled = false;
|
|
469
|
+
button.innerHTML = icon;
|
|
470
|
+
button.removeAttribute('aria-disabled');
|
|
471
|
+
button.removeAttribute('aria-busy');
|
|
472
|
+
fitButton.removeAttribute('aria-disabled');
|
|
473
|
+
rest();
|
|
474
|
+
};
|
|
475
|
+
const fail = message => {
|
|
476
|
+
exporter = null;
|
|
477
|
+
encoder = null;
|
|
478
|
+
retries++;
|
|
479
|
+
error.textContent = message;
|
|
480
|
+
error.hidden = false;
|
|
481
|
+
};
|
|
482
|
+
async function savePng() {
|
|
483
|
+
begin('png');
|
|
288
484
|
try {
|
|
289
|
-
|
|
290
|
-
const
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
const fixed = axis === 'h' ? ['top', 'bottom'] : axis === 'v' ? ['left', 'right'] : ['top', 'right', 'bottom', 'left'];
|
|
330
|
-
fixed.forEach(name => clone.style.setProperty(name, computed.getPropertyValue(name), 'important'));
|
|
485
|
+
const { domToBlob } = await loadExporter();
|
|
486
|
+
const blob = await domToBlob(poster, { ...(await captureOptions()), scale: 2 });
|
|
487
|
+
if (!blob) throw new Error('No PNG was created');
|
|
488
|
+
save(blob, 'png');
|
|
489
|
+
} catch (cause) {
|
|
490
|
+
fail('The PNG could not be saved. Check your connection and try again.');
|
|
491
|
+
} finally {
|
|
492
|
+
end();
|
|
493
|
+
}
|
|
494
|
+
}
|
|
495
|
+
// The GIF's clock: while it is made, rhp's motion (performance.now and animation frames) and the page's CSS
|
|
496
|
+
// animations run on a time of their own, which only moves on when a frame asks it to, so every frame shows the chart
|
|
497
|
+
// exactly as it is that many milliseconds into playing, its glides and slides included
|
|
498
|
+
const gifClock = () => {
|
|
499
|
+
const raf = window.requestAnimationFrame, caf = window.cancelAnimationFrame;
|
|
500
|
+
const queue = new Map(), started = new Map();
|
|
501
|
+
let time = performance.now(), id = 0, pump = 0;
|
|
502
|
+
const flush = () => {
|
|
503
|
+
const due = [...queue.values()];
|
|
504
|
+
queue.clear();
|
|
505
|
+
due.forEach(callback => { try { callback(time); } catch (cause) { reportError(cause); } });
|
|
506
|
+
};
|
|
507
|
+
// Callbacks still run every real frame, at the clock's time, so whatever waits for a frame is not held up
|
|
508
|
+
const loop = () => { flush(); pump = raf.call(window, loop); };
|
|
509
|
+
window.requestAnimationFrame = callback => { queue.set(++id, callback); return id; };
|
|
510
|
+
window.cancelAnimationFrame = n => queue.delete(n);
|
|
511
|
+
performance.now = () => time;
|
|
512
|
+
pump = raf.call(window, loop);
|
|
513
|
+
return {
|
|
514
|
+
// Two of the browser's frames: callbacks that were already waiting for one (rhp's ticker) come over to the clock
|
|
515
|
+
ready: new Promise(resolve => raf.call(window, () => raf.call(window, resolve))),
|
|
516
|
+
advance(ms, steps = 1) {
|
|
517
|
+
for (let i = 0; i < steps; i++) {
|
|
518
|
+
time += ms / steps;
|
|
519
|
+
// A frame's motion, then the style writes it schedules
|
|
520
|
+
flush(); flush(); flush();
|
|
521
|
+
for (const animation of document.getAnimations()) {
|
|
522
|
+
if (!started.has(animation)) started.set(animation, time - (animation.currentTime ?? 0));
|
|
523
|
+
animation.pause();
|
|
524
|
+
animation.currentTime = time - started.get(animation);
|
|
331
525
|
}
|
|
332
526
|
}
|
|
333
|
-
|
|
334
|
-
|
|
527
|
+
},
|
|
528
|
+
stop() {
|
|
529
|
+
caf.call(window, pump);
|
|
530
|
+
window.requestAnimationFrame = raf;
|
|
531
|
+
window.cancelAnimationFrame = caf;
|
|
532
|
+
delete performance.now;
|
|
533
|
+
for (const callback of queue.values()) raf.call(window, callback);
|
|
534
|
+
started.forEach((_, animation) => animation.play());
|
|
535
|
+
},
|
|
536
|
+
};
|
|
537
|
+
};
|
|
538
|
+
// The GIF: the playback at its own pace, 25 frames a second, at most 1200 pixels wide. One palette from the
|
|
539
|
+
// first and the last frame serves every frame; its last color is never drawn and marks the pixels a frame leaves as
|
|
540
|
+
// the frame before had them, so each frame stores only what changed.
|
|
541
|
+
async function saveGif() {
|
|
542
|
+
const playback = poster.playback;
|
|
543
|
+
const from = playback.position();
|
|
544
|
+
let clock = null;
|
|
545
|
+
begin('gif');
|
|
546
|
+
try {
|
|
547
|
+
encoder ||= import('https://cdn.jsdelivr.net/npm/gifenc@1.0.3/+esm' + (retries ? `?retry=${retries}` : ''));
|
|
548
|
+
const [{ domToCanvas }, { GIFEncoder, quantize, applyPalette }] = await Promise.all([loadExporter(), encoder]);
|
|
549
|
+
const options = await captureOptions();
|
|
550
|
+
const scale = Math.min(1, 1200 / options.width);
|
|
551
|
+
// The GIF plays at the chart's own pace: its playback's duration, in frames 40 ms apart
|
|
552
|
+
const step = 40, count = Math.max(2, Math.round((playback.duration ?? 15000) / step) + 1);
|
|
553
|
+
const capture = async () => {
|
|
554
|
+
const canvas = await domToCanvas(poster, { ...options, scale });
|
|
555
|
+
return canvas.getContext('2d').getImageData(0, 0, canvas.width, canvas.height);
|
|
335
556
|
};
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
if (!textures.has(source)) textures.set(source, (async () => {
|
|
375
|
-
const image = new Image();
|
|
376
|
-
image.src = source;
|
|
377
|
-
await image.decode();
|
|
378
|
-
const canvas = document.createElement('canvas');
|
|
379
|
-
canvas.width = image.naturalWidth;
|
|
380
|
-
canvas.height = image.naturalHeight;
|
|
381
|
-
canvas.getContext('2d').drawImage(image, 0, 0);
|
|
382
|
-
return canvas.toDataURL();
|
|
383
|
-
})());
|
|
384
|
-
background = background.replace(source, await textures.get(source));
|
|
557
|
+
clock = gifClock();
|
|
558
|
+
await clock.ready;
|
|
559
|
+
// The end and the start, each given a second to settle, for the palette; the start is also the first frame
|
|
560
|
+
playback.seek(1);
|
|
561
|
+
clock.advance(1000, 25);
|
|
562
|
+
const last = await capture();
|
|
563
|
+
playback.seek(0);
|
|
564
|
+
clock.advance(1000, 25);
|
|
565
|
+
const first = await capture();
|
|
566
|
+
const both = new Uint8ClampedArray(first.data.length + last.data.length);
|
|
567
|
+
both.set(first.data);
|
|
568
|
+
both.set(last.data, first.data.length);
|
|
569
|
+
const palette = quantize(both, 255), kept = palette.length;
|
|
570
|
+
// A flat color that fills a part of the poster keeps its exact value: it takes the nearest palette entry
|
|
571
|
+
const counts = new Map(), taken = new Set();
|
|
572
|
+
for (let j = 0; j < both.length; j += 4) {
|
|
573
|
+
const color = (both[j] << 16) | (both[j + 1] << 8) | both[j + 2];
|
|
574
|
+
counts.set(color, (counts.get(color) ?? 0) + 1);
|
|
575
|
+
}
|
|
576
|
+
for (const [color] of [...counts].filter(([, n]) => n > both.length / 8000).sort((a, b) => b[1] - a[1])) {
|
|
577
|
+
const rgb = [color >> 16, (color >> 8) & 255, color & 255];
|
|
578
|
+
let nearest = -1, distance = Infinity;
|
|
579
|
+
palette.forEach((entry, k) => {
|
|
580
|
+
const d = (entry[0] - rgb[0]) ** 2 + (entry[1] - rgb[1]) ** 2 + (entry[2] - rgb[2]) ** 2;
|
|
581
|
+
if (!taken.has(k) && d < distance) { nearest = k; distance = d; }
|
|
582
|
+
});
|
|
583
|
+
if (nearest >= 0) { palette[nearest] = rgb; taken.add(nearest); }
|
|
584
|
+
}
|
|
585
|
+
palette.push([255, 0, 255]);
|
|
586
|
+
const gif = GIFEncoder();
|
|
587
|
+
let previous = null;
|
|
588
|
+
for (let i = 0; i < count; i++) {
|
|
589
|
+
if (cancelled) return;
|
|
590
|
+
if (i > 0) {
|
|
591
|
+
playback.seek(i / (count - 1));
|
|
592
|
+
clock.advance(step);
|
|
593
|
+
// The last frame is held: it shows the end settled
|
|
594
|
+
if (i === count - 1) clock.advance(1000, 25);
|
|
385
595
|
}
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
}
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
}),
|
|
401
|
-
});
|
|
402
|
-
if (!blob) throw new Error('No PNG was created');
|
|
403
|
-
url = URL.createObjectURL(blob);
|
|
404
|
-
const link = document.createElement('a');
|
|
405
|
-
const title = poster.querySelector('.headline')?.textContent || document.title || 'poster';
|
|
406
|
-
link.download = (title.trim().toLowerCase().replace(/[^\p{L}\p{N}]+/gu, '-').replace(/^-|-$/g, '').slice(0, 100) || 'poster') + '.png';
|
|
407
|
-
link.href = url;
|
|
408
|
-
link.addEventListener('click', event => event.stopPropagation(), { once: true });
|
|
409
|
-
document.body.append(link);
|
|
410
|
-
link.click();
|
|
411
|
-
link.remove();
|
|
596
|
+
const image = i === 0 ? first : await capture();
|
|
597
|
+
const index = applyPalette(image.data, palette.slice(0, kept));
|
|
598
|
+
const pixels = previous ? index.map((p, j) => (p === previous[j] ? kept : p)) : index;
|
|
599
|
+
gif.writeFrame(pixels, image.width, image.height, {
|
|
600
|
+
palette: i === 0 ? palette : undefined, delay: i === 0 ? 1000 : i === count - 1 ? 3000 : step,
|
|
601
|
+
transparent: i > 0, transparentIndex: kept, dispose: 1,
|
|
602
|
+
});
|
|
603
|
+
previous = index;
|
|
604
|
+
const done = Math.round(((i + 1) / count) * 100);
|
|
605
|
+
button.innerHTML = `<span class="poster-download-progress" aria-hidden="true">${done}%</span>`;
|
|
606
|
+
label(`Cancel the GIF, ${done}% made`);
|
|
607
|
+
}
|
|
608
|
+
gif.finish();
|
|
609
|
+
save(new Blob([gif.bytes()], { type: 'image/gif' }), 'gif');
|
|
412
610
|
} catch (cause) {
|
|
413
|
-
|
|
414
|
-
retries++;
|
|
415
|
-
error.textContent = 'The PNG could not be saved. Check your connection and try again.';
|
|
416
|
-
error.hidden = false;
|
|
611
|
+
fail('The GIF could not be made. Check your connection and try again.');
|
|
417
612
|
} finally {
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
613
|
+
clock?.stop();
|
|
614
|
+
playback.seek(from);
|
|
615
|
+
end();
|
|
616
|
+
}
|
|
617
|
+
}
|
|
618
|
+
button.addEventListener('click', event => {
|
|
619
|
+
event.stopPropagation();
|
|
620
|
+
if (busy) {
|
|
621
|
+
if (making === 'gif') cancelled = true;
|
|
622
|
+
return;
|
|
424
623
|
}
|
|
624
|
+
if (!playable()) return savePng();
|
|
625
|
+
// A key press is a click with no pointer detail: it opens the menu on its first item
|
|
626
|
+
if (menu.hidden) openMenu(event.detail === 0);
|
|
627
|
+
else closeMenu(event.detail === 0);
|
|
628
|
+
});
|
|
629
|
+
menu.addEventListener('click', event => {
|
|
630
|
+
const item = event.target.closest('[data-format]');
|
|
631
|
+
if (!item) return;
|
|
632
|
+
event.stopPropagation();
|
|
633
|
+
closeMenu(event.detail === 0);
|
|
634
|
+
if (item.dataset.format === 'gif') saveGif();
|
|
635
|
+
else savePng();
|
|
425
636
|
});
|
|
426
637
|
tools.append(actions);
|
|
427
638
|
});
|