@bezda/rhp-mcp 0.1.8 → 0.1.10
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 +5 -5
- 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 +34 -6
- package/skill/references/design.md +18 -2
- package/skill/references/download.md +372 -140
- package/skill/references/environments.md +1 -1
- package/skill/references/interaction.md +2 -0
- package/skill/references/pitfalls.md +4 -3
- package/src/check/README.md +2 -1
- package/src/check/findings.js +2 -0
- package/src/check/inpage.js +9 -2
- package/src/guard/rhp.js +31 -11
package/skill/recipes/race.html
CHANGED
|
@@ -45,7 +45,8 @@
|
|
|
45
45
|
.scrub:focus-visible { outline: 2px solid #1d5b44; outline-offset: 4px; border-radius: 2px; }
|
|
46
46
|
.year { flex: none; min-width: 2.4em; text-align: right; font: italic 500 92px/.8 "Bodoni Moda", Didot, "Bodoni 72", Georgia, serif; font-variant-numeric: lining-nums tabular-nums; color: #1d5b44; }
|
|
47
47
|
/* One line that reads out the country in focus; its height is fixed, so nothing below it moves */
|
|
48
|
-
|
|
48
|
+
/* Its numbers change on every frame of the race: Jost's equal-width digits keep the words after them still */
|
|
49
|
+
.readout { height: 24px; margin: 18px 0 12px; font-size: 16px; line-height: 24px; white-space: nowrap; color: #434b46; font-variant-numeric: tabular-nums; }
|
|
49
50
|
.readout b { font-weight: 600; color: #17201b; }
|
|
50
51
|
.unit { display: block; margin-top: 4px; font-size: 12px; text-align: right; color: #5b645e; }
|
|
51
52
|
.poster .note { display: block; margin-top: 22px; padding-top: 12px; border-top: 1px solid #c3cac3; font-size: 12px; line-height: 1.5; color: #5b645e; }
|
|
@@ -213,6 +214,18 @@ function GdpRace() {
|
|
|
213
214
|
seen.observe(stage);
|
|
214
215
|
onCleanup(() => seen.disconnect());
|
|
215
216
|
});
|
|
217
|
+
// The poster's playback: its download offers the race as an animated GIF as well as the PNG (download.md)
|
|
218
|
+
onMount(() => {
|
|
219
|
+
stage.closest(".poster").playback = {
|
|
220
|
+
duration: (LAST - FIRST) * YEAR_MS,
|
|
221
|
+
position: () => (t() - FIRST) / (LAST - FIRST),
|
|
222
|
+
seek: (at) => {
|
|
223
|
+
auto = false;
|
|
224
|
+
pause();
|
|
225
|
+
setT(FIRST + at * (LAST - FIRST));
|
|
226
|
+
},
|
|
227
|
+
};
|
|
228
|
+
});
|
|
216
229
|
|
|
217
230
|
// JS version: while playing, the values change on every frame, so rhp moves each one on its own clock instead of
|
|
218
231
|
// restarting a CSS transition each frame. Its default 150 ms keeps the bars a few pixels behind the playhead, rounds
|
|
@@ -276,7 +289,7 @@ render(() => html`<${GdpRace} />`, document.getElementById("chart"));
|
|
|
276
289
|
</script>
|
|
277
290
|
<style id="poster-download-styles">
|
|
278
291
|
.poster-download-tools { display: flex; justify-content: flex-end; align-items: center; margin: 0 auto 12px; max-width: 100%; }
|
|
279
|
-
.poster-actions { display: flex; align-items: center; margin-left: auto; }
|
|
292
|
+
.poster-actions { position: relative; display: flex; align-items: center; margin-left: auto; }
|
|
280
293
|
.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; }
|
|
281
294
|
.poster-actions svg { display: block; width: 20px; height: 20px; }
|
|
282
295
|
.poster-actions button:hover { background: color-mix(in srgb, currentColor 8%, transparent); }
|
|
@@ -287,7 +300,14 @@ render(() => html`<${GdpRace} />`, document.getElementById("chart"));
|
|
|
287
300
|
.poster-fit-frame.is-fitted { display: block; margin: 0 auto; overflow: clip; }
|
|
288
301
|
.poster-fit-frame.is-fitted > .poster-fit-content { display: block; transform-origin: top left; }
|
|
289
302
|
.poster-download-error { margin: 8px auto; font: 14px/1.4 system-ui, sans-serif; color: inherit; }
|
|
290
|
-
|
|
303
|
+
.poster-download-progress { font: 600 11px/1 system-ui, sans-serif; font-variant-numeric: tabular-nums; }
|
|
304
|
+
.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); }
|
|
305
|
+
.poster-download-menu[hidden] { display: none; }
|
|
306
|
+
.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; }
|
|
307
|
+
.poster-download-menu button span { font-weight: 400; font-size: 12.5px; opacity: .8; }
|
|
308
|
+
.poster-download-menu button:hover { background: color-mix(in srgb, currentColor 9%, transparent); }
|
|
309
|
+
.poster-download-menu button:focus-visible { outline: 2px solid currentColor; outline-offset: -2px; }
|
|
310
|
+
@media print { .poster-download-tools, .poster-actions, .poster-download-menu, .poster-download-error { display: none !important; } }
|
|
291
311
|
</style>
|
|
292
312
|
<script type="module" id="poster-download-script">
|
|
293
313
|
function addPosterFit(poster, button, changed) {
|
|
@@ -365,6 +385,8 @@ function addPosterDownloads() {
|
|
|
365
385
|
tools.style.color = light[0] * .2126 + light[1] * .7152 + light[2] * .0722 < .179 ? '#eef2f5' : '#1d1b17';
|
|
366
386
|
}
|
|
367
387
|
}
|
|
388
|
+
const ground = getComputedStyle(document.body).backgroundColor;
|
|
389
|
+
if (!/^(transparent|rgba\(0, 0, 0, 0\))$/.test(ground)) tools.style.setProperty('--poster-tools-ground', ground);
|
|
368
390
|
const button = document.createElement('button');
|
|
369
391
|
button.type = 'button';
|
|
370
392
|
button.className = 'poster-download';
|
|
@@ -410,154 +432,356 @@ function addPosterDownloads() {
|
|
|
410
432
|
for (const type of ['keydown', 'keyup']) actions.addEventListener(type, event => {
|
|
411
433
|
if (event.key === 'Enter' || event.key === ' ') event.stopPropagation();
|
|
412
434
|
});
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
435
|
+
// A poster that plays through its data gives itself a playback ({ duration, position, seek }): its download then
|
|
436
|
+
// offers the poster as it is now, a PNG, or the whole playback, an animated GIF
|
|
437
|
+
let exporter, encoder, retries = 0, busy = false, making = null, cancelled = false;
|
|
438
|
+
const playable = () => typeof poster.playback?.seek === 'function';
|
|
439
|
+
const icon = button.innerHTML;
|
|
440
|
+
const menu = document.createElement('div');
|
|
441
|
+
menu.className = 'poster-download-menu';
|
|
442
|
+
menu.setAttribute('role', 'menu');
|
|
443
|
+
menu.setAttribute('aria-label', 'Download poster');
|
|
444
|
+
menu.hidden = true;
|
|
445
|
+
menu.innerHTML = '<button type="button" role="menuitem" data-format="png">PNG image<span>The poster as it is now</span></button>'
|
|
446
|
+
+ '<button type="button" role="menuitem" data-format="gif">Animated GIF<span>The whole playback</span></button>';
|
|
447
|
+
const items = [...menu.querySelectorAll('[role="menuitem"]')];
|
|
448
|
+
actions.append(menu);
|
|
449
|
+
const label = text => { button.setAttribute('aria-label', text); button.title = text; };
|
|
450
|
+
const rest = () => {
|
|
451
|
+
label(playable() ? 'Download poster' : 'Download poster as PNG');
|
|
452
|
+
if (playable()) { button.setAttribute('aria-haspopup', 'menu'); button.setAttribute('aria-expanded', String(!menu.hidden)); }
|
|
453
|
+
};
|
|
454
|
+
rest();
|
|
455
|
+
const closeMenu = focus => {
|
|
456
|
+
if (menu.hidden) return;
|
|
457
|
+
menu.hidden = true;
|
|
458
|
+
rest();
|
|
459
|
+
if (focus) button.focus();
|
|
460
|
+
};
|
|
461
|
+
const openMenu = focus => {
|
|
462
|
+
menu.hidden = false;
|
|
463
|
+
rest();
|
|
464
|
+
if (focus) items[0].focus();
|
|
465
|
+
};
|
|
466
|
+
document.addEventListener('pointerdown', event => { if (!actions.contains(event.target)) closeMenu(false); }, true);
|
|
467
|
+
menu.addEventListener('keydown', event => {
|
|
468
|
+
const at = items.indexOf(document.activeElement);
|
|
469
|
+
const to = { ArrowDown: at + 1, ArrowUp: at - 1, Home: 0, End: items.length - 1 }[event.key];
|
|
470
|
+
if (to !== undefined) { event.preventDefault(); items[(to + items.length) % items.length].focus(); }
|
|
471
|
+
else if (event.key === 'Escape') { event.preventDefault(); event.stopPropagation(); closeMenu(true); }
|
|
472
|
+
else if (event.key === 'Tab') closeMenu(false);
|
|
473
|
+
});
|
|
474
|
+
menu.addEventListener('focusout', event => { if (!menu.contains(event.relatedTarget) && event.relatedTarget !== button) closeMenu(false); });
|
|
475
|
+
// The capture options, made once for a download and for every frame of a GIF
|
|
476
|
+
const loadExporter = () => (exporter ||= import('https://cdn.jsdelivr.net/npm/modern-screenshot@4.7.0/+esm' + (retries ? `?retry=${retries}` : '')));
|
|
477
|
+
async function captureOptions() {
|
|
478
|
+
await document.fonts.ready;
|
|
479
|
+
// Preserve author layout rules where computed styles lose the grid's used geometry.
|
|
480
|
+
// Safari misreports percentage insets in subgrids, and grid auto margins resolve to zero.
|
|
481
|
+
const autoMargins = new Set(), positioned = new Set();
|
|
482
|
+
const isMargin = name => name === 'margin' || name.startsWith('margin-');
|
|
483
|
+
const isInset = name => name === 'inset' || name.startsWith('inset-') || ['top', 'right', 'bottom', 'left'].includes(name);
|
|
484
|
+
const layoutRules = rules => [...rules].map(rule => {
|
|
485
|
+
if (rule.selectorText && rule.style) {
|
|
486
|
+
const margins = [...rule.style].filter(isMargin);
|
|
487
|
+
if (margins.some(name => /\bauto\b/.test(rule.style.getPropertyValue(name)))) autoMargins.add(rule.selectorText);
|
|
488
|
+
const insets = [...rule.style].filter(isInset);
|
|
489
|
+
if (insets.length) positioned.add(rule.selectorText);
|
|
490
|
+
const layout = [...margins, ...insets];
|
|
491
|
+
return layout.length ? `${rule.selectorText} { ${layout.map(name => `${name}: ${rule.style.getPropertyValue(name)}${rule.style.getPropertyPriority(name) ? ' !important' : ''};`).join(' ')} }` : '';
|
|
492
|
+
}
|
|
493
|
+
if (!rule.cssRules) return /^@layer\b/.test(rule.cssText) ? rule.cssText : '';
|
|
494
|
+
if (rule instanceof CSSMediaRule) return matchMedia(rule.conditionText).matches ? layoutRules(rule.cssRules) : '';
|
|
495
|
+
if (rule instanceof CSSSupportsRule) return CSS.supports(rule.conditionText) ? layoutRules(rule.cssRules) : '';
|
|
496
|
+
return rule.cssText.slice(0, rule.cssText.indexOf('{') + 1) + layoutRules(rule.cssRules) + '}';
|
|
497
|
+
}).join('\n');
|
|
498
|
+
const sheets = [...document.styleSheets, ...document.adoptedStyleSheets];
|
|
499
|
+
const layout = sheets.map(sheet => {
|
|
500
|
+
try { return layoutRules(sheet.cssRules); } catch (cause) { return ''; }
|
|
501
|
+
}).join('\n');
|
|
502
|
+
// Omit display-none HTML subtrees, such as collapsed chart rows, from the image and its SVG payload.
|
|
503
|
+
const includeNode = node => !(node instanceof HTMLElement) || getComputedStyle(node).display !== 'none';
|
|
504
|
+
const restoreLayout = (source, clone) => {
|
|
505
|
+
if (clone.style && source !== poster) {
|
|
506
|
+
const margins = [...autoMargins].some(selector => source.matches(selector));
|
|
507
|
+
const computed = getComputedStyle(source);
|
|
508
|
+
const insets = computed.position === 'absolute' && [...positioned].some(selector => source.matches(selector));
|
|
509
|
+
const restore = name => (margins && isMargin(name)) || (insets && isInset(name));
|
|
510
|
+
[...clone.style].filter(restore).forEach(name => clone.style.removeProperty(name));
|
|
511
|
+
[...source.style].filter(restore).forEach(name => clone.style.setProperty(name, source.style.getPropertyValue(name), source.style.getPropertyPriority(name)));
|
|
512
|
+
if (insets) {
|
|
513
|
+
// Only the scaled axis needs its percentage rule. Freeze the other axis in pixels:
|
|
514
|
+
// Firefox does not reevaluate container queries reliably inside an SVG foreignObject.
|
|
515
|
+
const axis = source.getAttribute('data-rhp-o');
|
|
516
|
+
const fixed = axis === 'h' ? ['top', 'bottom'] : axis === 'v' ? ['left', 'right'] : ['top', 'right', 'bottom', 'left'];
|
|
517
|
+
fixed.forEach(name => clone.style.setProperty(name, computed.getPropertyValue(name), 'important'));
|
|
518
|
+
}
|
|
519
|
+
}
|
|
520
|
+
const children = [...source.children].filter(node => !['STYLE', 'SCRIPT'].includes(node.tagName) && includeNode(node));
|
|
521
|
+
[...clone.children].forEach((child, i) => { if (children[i]) restoreLayout(children[i], child); });
|
|
522
|
+
};
|
|
523
|
+
// Cross-origin font stylesheets are readable through fetch, but not through cssRules.
|
|
524
|
+
const fontFiles = new Map();
|
|
525
|
+
const fontRules = await Promise.all(sheets.map(async sheet => {
|
|
526
|
+
let css;
|
|
527
|
+
try { css = [...sheet.cssRules].map(rule => rule.cssText).join('\n'); }
|
|
528
|
+
catch (cause) {
|
|
529
|
+
if (!sheet.href) return '';
|
|
530
|
+
const response = await fetch(sheet.href);
|
|
531
|
+
if (!response.ok) throw new Error('Font stylesheet could not be loaded');
|
|
532
|
+
css = await response.text();
|
|
533
|
+
}
|
|
534
|
+
const rules = css.match(/@font-face\s*\{[^}]*\}/g) || [];
|
|
535
|
+
return (await Promise.all(rules.map(async rule => {
|
|
536
|
+
for (const match of [...rule.matchAll(/url\(["']?([^"')]+)["']?\)/g)]) {
|
|
537
|
+
const source = new URL(match[1], sheet.href || document.baseURI).href;
|
|
538
|
+
if (!fontFiles.has(source)) fontFiles.set(source, (async () => {
|
|
539
|
+
const response = await fetch(source);
|
|
540
|
+
if (!response.ok) throw new Error('Font could not be loaded');
|
|
541
|
+
const blob = await response.blob();
|
|
542
|
+
return new Promise((resolve, reject) => {
|
|
543
|
+
const reader = new FileReader();
|
|
544
|
+
reader.onload = () => resolve(reader.result);
|
|
545
|
+
reader.onerror = reject;
|
|
546
|
+
reader.readAsDataURL(blob);
|
|
547
|
+
});
|
|
548
|
+
})());
|
|
549
|
+
rule = rule.replace(match[1], await fontFiles.get(source));
|
|
550
|
+
}
|
|
551
|
+
return rule;
|
|
552
|
+
}))).join('\n');
|
|
553
|
+
}));
|
|
554
|
+
// Rasterize SVG paper textures before nesting them inside the exporter's SVG.
|
|
555
|
+
// This keeps SVG filter fragment references local to their own image.
|
|
556
|
+
const textures = new Map();
|
|
557
|
+
const embedTexture = async (node) => {
|
|
558
|
+
if (!node.style) return;
|
|
559
|
+
let background = node.style.backgroundImage;
|
|
560
|
+
for (const [, source] of background.matchAll(/url\("(data:image\/svg\+xml[^"]+)"\)/g)) {
|
|
561
|
+
if (!textures.has(source)) textures.set(source, (async () => {
|
|
562
|
+
const image = new Image();
|
|
563
|
+
image.src = source;
|
|
564
|
+
await image.decode();
|
|
565
|
+
const canvas = document.createElement('canvas');
|
|
566
|
+
canvas.width = image.naturalWidth;
|
|
567
|
+
canvas.height = image.naturalHeight;
|
|
568
|
+
canvas.getContext('2d').drawImage(image, 0, 0);
|
|
569
|
+
return canvas.toDataURL();
|
|
570
|
+
})());
|
|
571
|
+
background = background.replace(source, await textures.get(source));
|
|
572
|
+
}
|
|
573
|
+
node.style.backgroundImage = background;
|
|
574
|
+
};
|
|
575
|
+
return {
|
|
576
|
+
...fit.dimensions(), style: { margin: '0' }, filter: includeNode,
|
|
577
|
+
font: { cssText: fontRules.join('\n') }, onCloneEachNode: embedTexture,
|
|
578
|
+
onCloneNode: clone => {
|
|
579
|
+
restoreLayout(poster, clone);
|
|
580
|
+
const style = document.createElement('style');
|
|
581
|
+
style.textContent = layout;
|
|
582
|
+
clone.prepend(style);
|
|
583
|
+
},
|
|
584
|
+
// CSS content's alternative text follows a slash and must not be painted.
|
|
585
|
+
onCreateForeignObjectSvg: svg => svg.querySelectorAll('style').forEach(style => {
|
|
586
|
+
style.textContent = style.textContent.replace(/(content:\s*')([^']*)(')/g, (_, start, text, end) => start + text.split(' / ')[0] + end);
|
|
587
|
+
}),
|
|
588
|
+
};
|
|
589
|
+
}
|
|
590
|
+
let url;
|
|
591
|
+
const save = (blob, extension) => {
|
|
592
|
+
url = URL.createObjectURL(blob);
|
|
593
|
+
const link = document.createElement('a');
|
|
594
|
+
const title = poster.querySelector('.headline')?.textContent || document.title || 'poster';
|
|
595
|
+
link.download = (title.trim().toLowerCase().replace(/[^\p{L}\p{N}]+/gu, '-').replace(/^-|-$/g, '').slice(0, 100) || 'poster') + '.' + extension;
|
|
596
|
+
link.href = url;
|
|
597
|
+
link.addEventListener('click', event => event.stopPropagation(), { once: true });
|
|
598
|
+
document.body.append(link);
|
|
599
|
+
link.click();
|
|
600
|
+
link.remove();
|
|
601
|
+
};
|
|
602
|
+
const begin = kind => {
|
|
417
603
|
busy = true;
|
|
418
|
-
|
|
604
|
+
making = kind;
|
|
419
605
|
button.setAttribute('aria-busy', 'true');
|
|
420
606
|
fitButton.setAttribute('aria-disabled', 'true');
|
|
421
|
-
button
|
|
607
|
+
// A GIF takes a while: the button shows its progress and cancels it
|
|
608
|
+
if (kind === 'gif') label('Cancel the GIF');
|
|
609
|
+
else { button.setAttribute('aria-disabled', 'true'); label('Preparing poster PNG'); }
|
|
422
610
|
error.hidden = true;
|
|
423
|
-
|
|
611
|
+
};
|
|
612
|
+
const end = () => {
|
|
613
|
+
if (url) setTimeout(() => URL.revokeObjectURL(url), 60000);
|
|
614
|
+
url = null;
|
|
615
|
+
busy = false;
|
|
616
|
+
making = null;
|
|
617
|
+
cancelled = false;
|
|
618
|
+
button.innerHTML = icon;
|
|
619
|
+
button.removeAttribute('aria-disabled');
|
|
620
|
+
button.removeAttribute('aria-busy');
|
|
621
|
+
fitButton.removeAttribute('aria-disabled');
|
|
622
|
+
rest();
|
|
623
|
+
};
|
|
624
|
+
const fail = message => {
|
|
625
|
+
exporter = null;
|
|
626
|
+
encoder = null;
|
|
627
|
+
retries++;
|
|
628
|
+
error.textContent = message;
|
|
629
|
+
error.hidden = false;
|
|
630
|
+
};
|
|
631
|
+
async function savePng() {
|
|
632
|
+
begin('png');
|
|
424
633
|
try {
|
|
425
|
-
|
|
426
|
-
const
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
const fixed = axis === 'h' ? ['top', 'bottom'] : axis === 'v' ? ['left', 'right'] : ['top', 'right', 'bottom', 'left'];
|
|
466
|
-
fixed.forEach(name => clone.style.setProperty(name, computed.getPropertyValue(name), 'important'));
|
|
634
|
+
const { domToBlob } = await loadExporter();
|
|
635
|
+
const blob = await domToBlob(poster, { ...(await captureOptions()), scale: 2 });
|
|
636
|
+
if (!blob) throw new Error('No PNG was created');
|
|
637
|
+
save(blob, 'png');
|
|
638
|
+
} catch (cause) {
|
|
639
|
+
fail('The PNG could not be saved. Check your connection and try again.');
|
|
640
|
+
} finally {
|
|
641
|
+
end();
|
|
642
|
+
}
|
|
643
|
+
}
|
|
644
|
+
// The GIF's clock: while it is made, rhp's motion (performance.now and animation frames) and the page's CSS
|
|
645
|
+
// animations run on a time of their own, which only moves on when a frame asks it to, so every frame shows the chart
|
|
646
|
+
// exactly as it is that many milliseconds into playing, its glides and slides included
|
|
647
|
+
const gifClock = () => {
|
|
648
|
+
const raf = window.requestAnimationFrame, caf = window.cancelAnimationFrame;
|
|
649
|
+
const queue = new Map(), started = new Map();
|
|
650
|
+
let time = performance.now(), id = 0, pump = 0;
|
|
651
|
+
const flush = () => {
|
|
652
|
+
const due = [...queue.values()];
|
|
653
|
+
queue.clear();
|
|
654
|
+
due.forEach(callback => { try { callback(time); } catch (cause) { reportError(cause); } });
|
|
655
|
+
};
|
|
656
|
+
// Callbacks still run every real frame, at the clock's time, so whatever waits for a frame is not held up
|
|
657
|
+
const loop = () => { flush(); pump = raf.call(window, loop); };
|
|
658
|
+
window.requestAnimationFrame = callback => { queue.set(++id, callback); return id; };
|
|
659
|
+
window.cancelAnimationFrame = n => queue.delete(n);
|
|
660
|
+
performance.now = () => time;
|
|
661
|
+
pump = raf.call(window, loop);
|
|
662
|
+
return {
|
|
663
|
+
// Two of the browser's frames: callbacks that were already waiting for one (rhp's ticker) come over to the clock
|
|
664
|
+
ready: new Promise(resolve => raf.call(window, () => raf.call(window, resolve))),
|
|
665
|
+
advance(ms, steps = 1) {
|
|
666
|
+
for (let i = 0; i < steps; i++) {
|
|
667
|
+
time += ms / steps;
|
|
668
|
+
// A frame's motion, then the style writes it schedules
|
|
669
|
+
flush(); flush(); flush();
|
|
670
|
+
for (const animation of document.getAnimations()) {
|
|
671
|
+
if (!started.has(animation)) started.set(animation, time - (animation.currentTime ?? 0));
|
|
672
|
+
animation.pause();
|
|
673
|
+
animation.currentTime = time - started.get(animation);
|
|
467
674
|
}
|
|
468
675
|
}
|
|
469
|
-
|
|
470
|
-
|
|
676
|
+
},
|
|
677
|
+
stop() {
|
|
678
|
+
caf.call(window, pump);
|
|
679
|
+
window.requestAnimationFrame = raf;
|
|
680
|
+
window.cancelAnimationFrame = caf;
|
|
681
|
+
delete performance.now;
|
|
682
|
+
for (const callback of queue.values()) raf.call(window, callback);
|
|
683
|
+
started.forEach((_, animation) => animation.play());
|
|
684
|
+
},
|
|
685
|
+
};
|
|
686
|
+
};
|
|
687
|
+
// The GIF: the playback at its own pace, 25 frames a second, at most 1200 pixels wide. One palette from the
|
|
688
|
+
// first and the last frame serves every frame; its last color is never drawn and marks the pixels a frame leaves as
|
|
689
|
+
// the frame before had them, so each frame stores only what changed.
|
|
690
|
+
async function saveGif() {
|
|
691
|
+
const playback = poster.playback;
|
|
692
|
+
const from = playback.position();
|
|
693
|
+
let clock = null;
|
|
694
|
+
begin('gif');
|
|
695
|
+
try {
|
|
696
|
+
encoder ||= import('https://cdn.jsdelivr.net/npm/gifenc@1.0.3/+esm' + (retries ? `?retry=${retries}` : ''));
|
|
697
|
+
const [{ domToCanvas }, { GIFEncoder, quantize, applyPalette }] = await Promise.all([loadExporter(), encoder]);
|
|
698
|
+
const options = await captureOptions();
|
|
699
|
+
const scale = Math.min(1, 1200 / options.width);
|
|
700
|
+
// The GIF plays at the chart's own pace: its playback's duration, in frames 40 ms apart
|
|
701
|
+
const step = 40, count = Math.max(2, Math.round((playback.duration ?? 15000) / step) + 1);
|
|
702
|
+
const capture = async () => {
|
|
703
|
+
const canvas = await domToCanvas(poster, { ...options, scale });
|
|
704
|
+
return canvas.getContext('2d').getImageData(0, 0, canvas.width, canvas.height);
|
|
471
705
|
};
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
if (!textures.has(source)) textures.set(source, (async () => {
|
|
511
|
-
const image = new Image();
|
|
512
|
-
image.src = source;
|
|
513
|
-
await image.decode();
|
|
514
|
-
const canvas = document.createElement('canvas');
|
|
515
|
-
canvas.width = image.naturalWidth;
|
|
516
|
-
canvas.height = image.naturalHeight;
|
|
517
|
-
canvas.getContext('2d').drawImage(image, 0, 0);
|
|
518
|
-
return canvas.toDataURL();
|
|
519
|
-
})());
|
|
520
|
-
background = background.replace(source, await textures.get(source));
|
|
706
|
+
clock = gifClock();
|
|
707
|
+
await clock.ready;
|
|
708
|
+
// The end and the start, each given a second to settle, for the palette; the start is also the first frame
|
|
709
|
+
playback.seek(1);
|
|
710
|
+
clock.advance(1000, 25);
|
|
711
|
+
const last = await capture();
|
|
712
|
+
playback.seek(0);
|
|
713
|
+
clock.advance(1000, 25);
|
|
714
|
+
const first = await capture();
|
|
715
|
+
const both = new Uint8ClampedArray(first.data.length + last.data.length);
|
|
716
|
+
both.set(first.data);
|
|
717
|
+
both.set(last.data, first.data.length);
|
|
718
|
+
const palette = quantize(both, 255), kept = palette.length;
|
|
719
|
+
// A flat color that fills a part of the poster keeps its exact value: it takes the nearest palette entry
|
|
720
|
+
const counts = new Map(), taken = new Set();
|
|
721
|
+
for (let j = 0; j < both.length; j += 4) {
|
|
722
|
+
const color = (both[j] << 16) | (both[j + 1] << 8) | both[j + 2];
|
|
723
|
+
counts.set(color, (counts.get(color) ?? 0) + 1);
|
|
724
|
+
}
|
|
725
|
+
for (const [color] of [...counts].filter(([, n]) => n > both.length / 8000).sort((a, b) => b[1] - a[1])) {
|
|
726
|
+
const rgb = [color >> 16, (color >> 8) & 255, color & 255];
|
|
727
|
+
let nearest = -1, distance = Infinity;
|
|
728
|
+
palette.forEach((entry, k) => {
|
|
729
|
+
const d = (entry[0] - rgb[0]) ** 2 + (entry[1] - rgb[1]) ** 2 + (entry[2] - rgb[2]) ** 2;
|
|
730
|
+
if (!taken.has(k) && d < distance) { nearest = k; distance = d; }
|
|
731
|
+
});
|
|
732
|
+
if (nearest >= 0) { palette[nearest] = rgb; taken.add(nearest); }
|
|
733
|
+
}
|
|
734
|
+
palette.push([255, 0, 255]);
|
|
735
|
+
const gif = GIFEncoder();
|
|
736
|
+
let previous = null;
|
|
737
|
+
for (let i = 0; i < count; i++) {
|
|
738
|
+
if (cancelled) return;
|
|
739
|
+
if (i > 0) {
|
|
740
|
+
playback.seek(i / (count - 1));
|
|
741
|
+
clock.advance(step);
|
|
742
|
+
// The last frame is held: it shows the end settled
|
|
743
|
+
if (i === count - 1) clock.advance(1000, 25);
|
|
521
744
|
}
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
}
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
}),
|
|
537
|
-
});
|
|
538
|
-
if (!blob) throw new Error('No PNG was created');
|
|
539
|
-
url = URL.createObjectURL(blob);
|
|
540
|
-
const link = document.createElement('a');
|
|
541
|
-
const title = poster.querySelector('.headline')?.textContent || document.title || 'poster';
|
|
542
|
-
link.download = (title.trim().toLowerCase().replace(/[^\p{L}\p{N}]+/gu, '-').replace(/^-|-$/g, '').slice(0, 100) || 'poster') + '.png';
|
|
543
|
-
link.href = url;
|
|
544
|
-
link.addEventListener('click', event => event.stopPropagation(), { once: true });
|
|
545
|
-
document.body.append(link);
|
|
546
|
-
link.click();
|
|
547
|
-
link.remove();
|
|
745
|
+
const image = i === 0 ? first : await capture();
|
|
746
|
+
const index = applyPalette(image.data, palette.slice(0, kept));
|
|
747
|
+
const pixels = previous ? index.map((p, j) => (p === previous[j] ? kept : p)) : index;
|
|
748
|
+
gif.writeFrame(pixels, image.width, image.height, {
|
|
749
|
+
palette: i === 0 ? palette : undefined, delay: i === 0 ? 1000 : i === count - 1 ? 3000 : step,
|
|
750
|
+
transparent: i > 0, transparentIndex: kept, dispose: 1,
|
|
751
|
+
});
|
|
752
|
+
previous = index;
|
|
753
|
+
const done = Math.round(((i + 1) / count) * 100);
|
|
754
|
+
button.innerHTML = `<span class="poster-download-progress" aria-hidden="true">${done}%</span>`;
|
|
755
|
+
label(`Cancel the GIF, ${done}% made`);
|
|
756
|
+
}
|
|
757
|
+
gif.finish();
|
|
758
|
+
save(new Blob([gif.bytes()], { type: 'image/gif' }), 'gif');
|
|
548
759
|
} catch (cause) {
|
|
549
|
-
|
|
550
|
-
retries++;
|
|
551
|
-
error.textContent = 'The PNG could not be saved. Check your connection and try again.';
|
|
552
|
-
error.hidden = false;
|
|
760
|
+
fail('The GIF could not be made. Check your connection and try again.');
|
|
553
761
|
} finally {
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
762
|
+
clock?.stop();
|
|
763
|
+
playback.seek(from);
|
|
764
|
+
end();
|
|
765
|
+
}
|
|
766
|
+
}
|
|
767
|
+
button.addEventListener('click', event => {
|
|
768
|
+
event.stopPropagation();
|
|
769
|
+
if (busy) {
|
|
770
|
+
if (making === 'gif') cancelled = true;
|
|
771
|
+
return;
|
|
560
772
|
}
|
|
773
|
+
if (!playable()) return savePng();
|
|
774
|
+
// A key press is a click with no pointer detail: it opens the menu on its first item
|
|
775
|
+
if (menu.hidden) openMenu(event.detail === 0);
|
|
776
|
+
else closeMenu(event.detail === 0);
|
|
777
|
+
});
|
|
778
|
+
menu.addEventListener('click', event => {
|
|
779
|
+
const item = event.target.closest('[data-format]');
|
|
780
|
+
if (!item) return;
|
|
781
|
+
event.stopPropagation();
|
|
782
|
+
closeMenu(event.detail === 0);
|
|
783
|
+
if (item.dataset.format === 'gif') saveGif();
|
|
784
|
+
else savePng();
|
|
561
785
|
});
|
|
562
786
|
tools.append(actions);
|
|
563
787
|
});
|