@bezda/rhp-mcp 0.1.8 → 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 +1 -1
- 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/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/pitfalls.md +1 -0
package/skill/recipes/dial.html
CHANGED
|
@@ -347,7 +347,7 @@ render(() => html`<${DayDial} />`, document.getElementById("chart"));
|
|
|
347
347
|
</script>
|
|
348
348
|
<style id="poster-download-styles">
|
|
349
349
|
.poster-download-tools { display: flex; justify-content: flex-end; align-items: center; margin: 0 auto 12px; max-width: 100%; }
|
|
350
|
-
.poster-actions { display: flex; align-items: center; margin-left: auto; }
|
|
350
|
+
.poster-actions { position: relative; display: flex; align-items: center; margin-left: auto; }
|
|
351
351
|
.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; }
|
|
352
352
|
.poster-actions svg { display: block; width: 20px; height: 20px; }
|
|
353
353
|
.poster-actions button:hover { background: color-mix(in srgb, currentColor 8%, transparent); }
|
|
@@ -358,7 +358,14 @@ render(() => html`<${DayDial} />`, document.getElementById("chart"));
|
|
|
358
358
|
.poster-fit-frame.is-fitted { display: block; margin: 0 auto; overflow: clip; }
|
|
359
359
|
.poster-fit-frame.is-fitted > .poster-fit-content { display: block; transform-origin: top left; }
|
|
360
360
|
.poster-download-error { margin: 8px auto; font: 14px/1.4 system-ui, sans-serif; color: inherit; }
|
|
361
|
-
|
|
361
|
+
.poster-download-progress { font: 600 11px/1 system-ui, sans-serif; font-variant-numeric: tabular-nums; }
|
|
362
|
+
.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); }
|
|
363
|
+
.poster-download-menu[hidden] { display: none; }
|
|
364
|
+
.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; }
|
|
365
|
+
.poster-download-menu button span { font-weight: 400; font-size: 12.5px; opacity: .8; }
|
|
366
|
+
.poster-download-menu button:hover { background: color-mix(in srgb, currentColor 9%, transparent); }
|
|
367
|
+
.poster-download-menu button:focus-visible { outline: 2px solid currentColor; outline-offset: -2px; }
|
|
368
|
+
@media print { .poster-download-tools, .poster-actions, .poster-download-menu, .poster-download-error { display: none !important; } }
|
|
362
369
|
</style>
|
|
363
370
|
<script type="module" id="poster-download-script">
|
|
364
371
|
function addPosterFit(poster, button, changed) {
|
|
@@ -436,6 +443,8 @@ function addPosterDownloads() {
|
|
|
436
443
|
tools.style.color = light[0] * .2126 + light[1] * .7152 + light[2] * .0722 < .179 ? '#eef2f5' : '#1d1b17';
|
|
437
444
|
}
|
|
438
445
|
}
|
|
446
|
+
const ground = getComputedStyle(document.body).backgroundColor;
|
|
447
|
+
if (!/^(transparent|rgba\(0, 0, 0, 0\))$/.test(ground)) tools.style.setProperty('--poster-tools-ground', ground);
|
|
439
448
|
const button = document.createElement('button');
|
|
440
449
|
button.type = 'button';
|
|
441
450
|
button.className = 'poster-download';
|
|
@@ -481,154 +490,356 @@ function addPosterDownloads() {
|
|
|
481
490
|
for (const type of ['keydown', 'keyup']) actions.addEventListener(type, event => {
|
|
482
491
|
if (event.key === 'Enter' || event.key === ' ') event.stopPropagation();
|
|
483
492
|
});
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
493
|
+
// A poster that plays through its data gives itself a playback ({ duration, position, seek }): its download then
|
|
494
|
+
// offers the poster as it is now, a PNG, or the whole playback, an animated GIF
|
|
495
|
+
let exporter, encoder, retries = 0, busy = false, making = null, cancelled = false;
|
|
496
|
+
const playable = () => typeof poster.playback?.seek === 'function';
|
|
497
|
+
const icon = button.innerHTML;
|
|
498
|
+
const menu = document.createElement('div');
|
|
499
|
+
menu.className = 'poster-download-menu';
|
|
500
|
+
menu.setAttribute('role', 'menu');
|
|
501
|
+
menu.setAttribute('aria-label', 'Download poster');
|
|
502
|
+
menu.hidden = true;
|
|
503
|
+
menu.innerHTML = '<button type="button" role="menuitem" data-format="png">PNG image<span>The poster as it is now</span></button>'
|
|
504
|
+
+ '<button type="button" role="menuitem" data-format="gif">Animated GIF<span>The whole playback</span></button>';
|
|
505
|
+
const items = [...menu.querySelectorAll('[role="menuitem"]')];
|
|
506
|
+
actions.append(menu);
|
|
507
|
+
const label = text => { button.setAttribute('aria-label', text); button.title = text; };
|
|
508
|
+
const rest = () => {
|
|
509
|
+
label(playable() ? 'Download poster' : 'Download poster as PNG');
|
|
510
|
+
if (playable()) { button.setAttribute('aria-haspopup', 'menu'); button.setAttribute('aria-expanded', String(!menu.hidden)); }
|
|
511
|
+
};
|
|
512
|
+
rest();
|
|
513
|
+
const closeMenu = focus => {
|
|
514
|
+
if (menu.hidden) return;
|
|
515
|
+
menu.hidden = true;
|
|
516
|
+
rest();
|
|
517
|
+
if (focus) button.focus();
|
|
518
|
+
};
|
|
519
|
+
const openMenu = focus => {
|
|
520
|
+
menu.hidden = false;
|
|
521
|
+
rest();
|
|
522
|
+
if (focus) items[0].focus();
|
|
523
|
+
};
|
|
524
|
+
document.addEventListener('pointerdown', event => { if (!actions.contains(event.target)) closeMenu(false); }, true);
|
|
525
|
+
menu.addEventListener('keydown', event => {
|
|
526
|
+
const at = items.indexOf(document.activeElement);
|
|
527
|
+
const to = { ArrowDown: at + 1, ArrowUp: at - 1, Home: 0, End: items.length - 1 }[event.key];
|
|
528
|
+
if (to !== undefined) { event.preventDefault(); items[(to + items.length) % items.length].focus(); }
|
|
529
|
+
else if (event.key === 'Escape') { event.preventDefault(); event.stopPropagation(); closeMenu(true); }
|
|
530
|
+
else if (event.key === 'Tab') closeMenu(false);
|
|
531
|
+
});
|
|
532
|
+
menu.addEventListener('focusout', event => { if (!menu.contains(event.relatedTarget) && event.relatedTarget !== button) closeMenu(false); });
|
|
533
|
+
// The capture options, made once for a download and for every frame of a GIF
|
|
534
|
+
const loadExporter = () => (exporter ||= import('https://cdn.jsdelivr.net/npm/modern-screenshot@4.7.0/+esm' + (retries ? `?retry=${retries}` : '')));
|
|
535
|
+
async function captureOptions() {
|
|
536
|
+
await document.fonts.ready;
|
|
537
|
+
// Preserve author layout rules where computed styles lose the grid's used geometry.
|
|
538
|
+
// Safari misreports percentage insets in subgrids, and grid auto margins resolve to zero.
|
|
539
|
+
const autoMargins = new Set(), positioned = new Set();
|
|
540
|
+
const isMargin = name => name === 'margin' || name.startsWith('margin-');
|
|
541
|
+
const isInset = name => name === 'inset' || name.startsWith('inset-') || ['top', 'right', 'bottom', 'left'].includes(name);
|
|
542
|
+
const layoutRules = rules => [...rules].map(rule => {
|
|
543
|
+
if (rule.selectorText && rule.style) {
|
|
544
|
+
const margins = [...rule.style].filter(isMargin);
|
|
545
|
+
if (margins.some(name => /\bauto\b/.test(rule.style.getPropertyValue(name)))) autoMargins.add(rule.selectorText);
|
|
546
|
+
const insets = [...rule.style].filter(isInset);
|
|
547
|
+
if (insets.length) positioned.add(rule.selectorText);
|
|
548
|
+
const layout = [...margins, ...insets];
|
|
549
|
+
return layout.length ? `${rule.selectorText} { ${layout.map(name => `${name}: ${rule.style.getPropertyValue(name)}${rule.style.getPropertyPriority(name) ? ' !important' : ''};`).join(' ')} }` : '';
|
|
550
|
+
}
|
|
551
|
+
if (!rule.cssRules) return /^@layer\b/.test(rule.cssText) ? rule.cssText : '';
|
|
552
|
+
if (rule instanceof CSSMediaRule) return matchMedia(rule.conditionText).matches ? layoutRules(rule.cssRules) : '';
|
|
553
|
+
if (rule instanceof CSSSupportsRule) return CSS.supports(rule.conditionText) ? layoutRules(rule.cssRules) : '';
|
|
554
|
+
return rule.cssText.slice(0, rule.cssText.indexOf('{') + 1) + layoutRules(rule.cssRules) + '}';
|
|
555
|
+
}).join('\n');
|
|
556
|
+
const sheets = [...document.styleSheets, ...document.adoptedStyleSheets];
|
|
557
|
+
const layout = sheets.map(sheet => {
|
|
558
|
+
try { return layoutRules(sheet.cssRules); } catch (cause) { return ''; }
|
|
559
|
+
}).join('\n');
|
|
560
|
+
// Omit display-none HTML subtrees, such as collapsed chart rows, from the image and its SVG payload.
|
|
561
|
+
const includeNode = node => !(node instanceof HTMLElement) || getComputedStyle(node).display !== 'none';
|
|
562
|
+
const restoreLayout = (source, clone) => {
|
|
563
|
+
if (clone.style && source !== poster) {
|
|
564
|
+
const margins = [...autoMargins].some(selector => source.matches(selector));
|
|
565
|
+
const computed = getComputedStyle(source);
|
|
566
|
+
const insets = computed.position === 'absolute' && [...positioned].some(selector => source.matches(selector));
|
|
567
|
+
const restore = name => (margins && isMargin(name)) || (insets && isInset(name));
|
|
568
|
+
[...clone.style].filter(restore).forEach(name => clone.style.removeProperty(name));
|
|
569
|
+
[...source.style].filter(restore).forEach(name => clone.style.setProperty(name, source.style.getPropertyValue(name), source.style.getPropertyPriority(name)));
|
|
570
|
+
if (insets) {
|
|
571
|
+
// Only the scaled axis needs its percentage rule. Freeze the other axis in pixels:
|
|
572
|
+
// Firefox does not reevaluate container queries reliably inside an SVG foreignObject.
|
|
573
|
+
const axis = source.getAttribute('data-rhp-o');
|
|
574
|
+
const fixed = axis === 'h' ? ['top', 'bottom'] : axis === 'v' ? ['left', 'right'] : ['top', 'right', 'bottom', 'left'];
|
|
575
|
+
fixed.forEach(name => clone.style.setProperty(name, computed.getPropertyValue(name), 'important'));
|
|
576
|
+
}
|
|
577
|
+
}
|
|
578
|
+
const children = [...source.children].filter(node => !['STYLE', 'SCRIPT'].includes(node.tagName) && includeNode(node));
|
|
579
|
+
[...clone.children].forEach((child, i) => { if (children[i]) restoreLayout(children[i], child); });
|
|
580
|
+
};
|
|
581
|
+
// Cross-origin font stylesheets are readable through fetch, but not through cssRules.
|
|
582
|
+
const fontFiles = new Map();
|
|
583
|
+
const fontRules = await Promise.all(sheets.map(async sheet => {
|
|
584
|
+
let css;
|
|
585
|
+
try { css = [...sheet.cssRules].map(rule => rule.cssText).join('\n'); }
|
|
586
|
+
catch (cause) {
|
|
587
|
+
if (!sheet.href) return '';
|
|
588
|
+
const response = await fetch(sheet.href);
|
|
589
|
+
if (!response.ok) throw new Error('Font stylesheet could not be loaded');
|
|
590
|
+
css = await response.text();
|
|
591
|
+
}
|
|
592
|
+
const rules = css.match(/@font-face\s*\{[^}]*\}/g) || [];
|
|
593
|
+
return (await Promise.all(rules.map(async rule => {
|
|
594
|
+
for (const match of [...rule.matchAll(/url\(["']?([^"')]+)["']?\)/g)]) {
|
|
595
|
+
const source = new URL(match[1], sheet.href || document.baseURI).href;
|
|
596
|
+
if (!fontFiles.has(source)) fontFiles.set(source, (async () => {
|
|
597
|
+
const response = await fetch(source);
|
|
598
|
+
if (!response.ok) throw new Error('Font could not be loaded');
|
|
599
|
+
const blob = await response.blob();
|
|
600
|
+
return new Promise((resolve, reject) => {
|
|
601
|
+
const reader = new FileReader();
|
|
602
|
+
reader.onload = () => resolve(reader.result);
|
|
603
|
+
reader.onerror = reject;
|
|
604
|
+
reader.readAsDataURL(blob);
|
|
605
|
+
});
|
|
606
|
+
})());
|
|
607
|
+
rule = rule.replace(match[1], await fontFiles.get(source));
|
|
608
|
+
}
|
|
609
|
+
return rule;
|
|
610
|
+
}))).join('\n');
|
|
611
|
+
}));
|
|
612
|
+
// Rasterize SVG paper textures before nesting them inside the exporter's SVG.
|
|
613
|
+
// This keeps SVG filter fragment references local to their own image.
|
|
614
|
+
const textures = new Map();
|
|
615
|
+
const embedTexture = async (node) => {
|
|
616
|
+
if (!node.style) return;
|
|
617
|
+
let background = node.style.backgroundImage;
|
|
618
|
+
for (const [, source] of background.matchAll(/url\("(data:image\/svg\+xml[^"]+)"\)/g)) {
|
|
619
|
+
if (!textures.has(source)) textures.set(source, (async () => {
|
|
620
|
+
const image = new Image();
|
|
621
|
+
image.src = source;
|
|
622
|
+
await image.decode();
|
|
623
|
+
const canvas = document.createElement('canvas');
|
|
624
|
+
canvas.width = image.naturalWidth;
|
|
625
|
+
canvas.height = image.naturalHeight;
|
|
626
|
+
canvas.getContext('2d').drawImage(image, 0, 0);
|
|
627
|
+
return canvas.toDataURL();
|
|
628
|
+
})());
|
|
629
|
+
background = background.replace(source, await textures.get(source));
|
|
630
|
+
}
|
|
631
|
+
node.style.backgroundImage = background;
|
|
632
|
+
};
|
|
633
|
+
return {
|
|
634
|
+
...fit.dimensions(), style: { margin: '0' }, filter: includeNode,
|
|
635
|
+
font: { cssText: fontRules.join('\n') }, onCloneEachNode: embedTexture,
|
|
636
|
+
onCloneNode: clone => {
|
|
637
|
+
restoreLayout(poster, clone);
|
|
638
|
+
const style = document.createElement('style');
|
|
639
|
+
style.textContent = layout;
|
|
640
|
+
clone.prepend(style);
|
|
641
|
+
},
|
|
642
|
+
// CSS content's alternative text follows a slash and must not be painted.
|
|
643
|
+
onCreateForeignObjectSvg: svg => svg.querySelectorAll('style').forEach(style => {
|
|
644
|
+
style.textContent = style.textContent.replace(/(content:\s*')([^']*)(')/g, (_, start, text, end) => start + text.split(' / ')[0] + end);
|
|
645
|
+
}),
|
|
646
|
+
};
|
|
647
|
+
}
|
|
648
|
+
let url;
|
|
649
|
+
const save = (blob, extension) => {
|
|
650
|
+
url = URL.createObjectURL(blob);
|
|
651
|
+
const link = document.createElement('a');
|
|
652
|
+
const title = poster.querySelector('.headline')?.textContent || document.title || 'poster';
|
|
653
|
+
link.download = (title.trim().toLowerCase().replace(/[^\p{L}\p{N}]+/gu, '-').replace(/^-|-$/g, '').slice(0, 100) || 'poster') + '.' + extension;
|
|
654
|
+
link.href = url;
|
|
655
|
+
link.addEventListener('click', event => event.stopPropagation(), { once: true });
|
|
656
|
+
document.body.append(link);
|
|
657
|
+
link.click();
|
|
658
|
+
link.remove();
|
|
659
|
+
};
|
|
660
|
+
const begin = kind => {
|
|
488
661
|
busy = true;
|
|
489
|
-
|
|
662
|
+
making = kind;
|
|
490
663
|
button.setAttribute('aria-busy', 'true');
|
|
491
664
|
fitButton.setAttribute('aria-disabled', 'true');
|
|
492
|
-
button
|
|
665
|
+
// A GIF takes a while: the button shows its progress and cancels it
|
|
666
|
+
if (kind === 'gif') label('Cancel the GIF');
|
|
667
|
+
else { button.setAttribute('aria-disabled', 'true'); label('Preparing poster PNG'); }
|
|
493
668
|
error.hidden = true;
|
|
494
|
-
|
|
669
|
+
};
|
|
670
|
+
const end = () => {
|
|
671
|
+
if (url) setTimeout(() => URL.revokeObjectURL(url), 60000);
|
|
672
|
+
url = null;
|
|
673
|
+
busy = false;
|
|
674
|
+
making = null;
|
|
675
|
+
cancelled = false;
|
|
676
|
+
button.innerHTML = icon;
|
|
677
|
+
button.removeAttribute('aria-disabled');
|
|
678
|
+
button.removeAttribute('aria-busy');
|
|
679
|
+
fitButton.removeAttribute('aria-disabled');
|
|
680
|
+
rest();
|
|
681
|
+
};
|
|
682
|
+
const fail = message => {
|
|
683
|
+
exporter = null;
|
|
684
|
+
encoder = null;
|
|
685
|
+
retries++;
|
|
686
|
+
error.textContent = message;
|
|
687
|
+
error.hidden = false;
|
|
688
|
+
};
|
|
689
|
+
async function savePng() {
|
|
690
|
+
begin('png');
|
|
495
691
|
try {
|
|
496
|
-
|
|
497
|
-
const
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
const fixed = axis === 'h' ? ['top', 'bottom'] : axis === 'v' ? ['left', 'right'] : ['top', 'right', 'bottom', 'left'];
|
|
537
|
-
fixed.forEach(name => clone.style.setProperty(name, computed.getPropertyValue(name), 'important'));
|
|
692
|
+
const { domToBlob } = await loadExporter();
|
|
693
|
+
const blob = await domToBlob(poster, { ...(await captureOptions()), scale: 2 });
|
|
694
|
+
if (!blob) throw new Error('No PNG was created');
|
|
695
|
+
save(blob, 'png');
|
|
696
|
+
} catch (cause) {
|
|
697
|
+
fail('The PNG could not be saved. Check your connection and try again.');
|
|
698
|
+
} finally {
|
|
699
|
+
end();
|
|
700
|
+
}
|
|
701
|
+
}
|
|
702
|
+
// The GIF's clock: while it is made, rhp's motion (performance.now and animation frames) and the page's CSS
|
|
703
|
+
// animations run on a time of their own, which only moves on when a frame asks it to, so every frame shows the chart
|
|
704
|
+
// exactly as it is that many milliseconds into playing, its glides and slides included
|
|
705
|
+
const gifClock = () => {
|
|
706
|
+
const raf = window.requestAnimationFrame, caf = window.cancelAnimationFrame;
|
|
707
|
+
const queue = new Map(), started = new Map();
|
|
708
|
+
let time = performance.now(), id = 0, pump = 0;
|
|
709
|
+
const flush = () => {
|
|
710
|
+
const due = [...queue.values()];
|
|
711
|
+
queue.clear();
|
|
712
|
+
due.forEach(callback => { try { callback(time); } catch (cause) { reportError(cause); } });
|
|
713
|
+
};
|
|
714
|
+
// Callbacks still run every real frame, at the clock's time, so whatever waits for a frame is not held up
|
|
715
|
+
const loop = () => { flush(); pump = raf.call(window, loop); };
|
|
716
|
+
window.requestAnimationFrame = callback => { queue.set(++id, callback); return id; };
|
|
717
|
+
window.cancelAnimationFrame = n => queue.delete(n);
|
|
718
|
+
performance.now = () => time;
|
|
719
|
+
pump = raf.call(window, loop);
|
|
720
|
+
return {
|
|
721
|
+
// Two of the browser's frames: callbacks that were already waiting for one (rhp's ticker) come over to the clock
|
|
722
|
+
ready: new Promise(resolve => raf.call(window, () => raf.call(window, resolve))),
|
|
723
|
+
advance(ms, steps = 1) {
|
|
724
|
+
for (let i = 0; i < steps; i++) {
|
|
725
|
+
time += ms / steps;
|
|
726
|
+
// A frame's motion, then the style writes it schedules
|
|
727
|
+
flush(); flush(); flush();
|
|
728
|
+
for (const animation of document.getAnimations()) {
|
|
729
|
+
if (!started.has(animation)) started.set(animation, time - (animation.currentTime ?? 0));
|
|
730
|
+
animation.pause();
|
|
731
|
+
animation.currentTime = time - started.get(animation);
|
|
538
732
|
}
|
|
539
733
|
}
|
|
540
|
-
|
|
541
|
-
|
|
734
|
+
},
|
|
735
|
+
stop() {
|
|
736
|
+
caf.call(window, pump);
|
|
737
|
+
window.requestAnimationFrame = raf;
|
|
738
|
+
window.cancelAnimationFrame = caf;
|
|
739
|
+
delete performance.now;
|
|
740
|
+
for (const callback of queue.values()) raf.call(window, callback);
|
|
741
|
+
started.forEach((_, animation) => animation.play());
|
|
742
|
+
},
|
|
743
|
+
};
|
|
744
|
+
};
|
|
745
|
+
// The GIF: the playback at its own pace, 25 frames a second, at most 1200 pixels wide. One palette from the
|
|
746
|
+
// first and the last frame serves every frame; its last color is never drawn and marks the pixels a frame leaves as
|
|
747
|
+
// the frame before had them, so each frame stores only what changed.
|
|
748
|
+
async function saveGif() {
|
|
749
|
+
const playback = poster.playback;
|
|
750
|
+
const from = playback.position();
|
|
751
|
+
let clock = null;
|
|
752
|
+
begin('gif');
|
|
753
|
+
try {
|
|
754
|
+
encoder ||= import('https://cdn.jsdelivr.net/npm/gifenc@1.0.3/+esm' + (retries ? `?retry=${retries}` : ''));
|
|
755
|
+
const [{ domToCanvas }, { GIFEncoder, quantize, applyPalette }] = await Promise.all([loadExporter(), encoder]);
|
|
756
|
+
const options = await captureOptions();
|
|
757
|
+
const scale = Math.min(1, 1200 / options.width);
|
|
758
|
+
// The GIF plays at the chart's own pace: its playback's duration, in frames 40 ms apart
|
|
759
|
+
const step = 40, count = Math.max(2, Math.round((playback.duration ?? 15000) / step) + 1);
|
|
760
|
+
const capture = async () => {
|
|
761
|
+
const canvas = await domToCanvas(poster, { ...options, scale });
|
|
762
|
+
return canvas.getContext('2d').getImageData(0, 0, canvas.width, canvas.height);
|
|
542
763
|
};
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
if (!textures.has(source)) textures.set(source, (async () => {
|
|
582
|
-
const image = new Image();
|
|
583
|
-
image.src = source;
|
|
584
|
-
await image.decode();
|
|
585
|
-
const canvas = document.createElement('canvas');
|
|
586
|
-
canvas.width = image.naturalWidth;
|
|
587
|
-
canvas.height = image.naturalHeight;
|
|
588
|
-
canvas.getContext('2d').drawImage(image, 0, 0);
|
|
589
|
-
return canvas.toDataURL();
|
|
590
|
-
})());
|
|
591
|
-
background = background.replace(source, await textures.get(source));
|
|
764
|
+
clock = gifClock();
|
|
765
|
+
await clock.ready;
|
|
766
|
+
// The end and the start, each given a second to settle, for the palette; the start is also the first frame
|
|
767
|
+
playback.seek(1);
|
|
768
|
+
clock.advance(1000, 25);
|
|
769
|
+
const last = await capture();
|
|
770
|
+
playback.seek(0);
|
|
771
|
+
clock.advance(1000, 25);
|
|
772
|
+
const first = await capture();
|
|
773
|
+
const both = new Uint8ClampedArray(first.data.length + last.data.length);
|
|
774
|
+
both.set(first.data);
|
|
775
|
+
both.set(last.data, first.data.length);
|
|
776
|
+
const palette = quantize(both, 255), kept = palette.length;
|
|
777
|
+
// A flat color that fills a part of the poster keeps its exact value: it takes the nearest palette entry
|
|
778
|
+
const counts = new Map(), taken = new Set();
|
|
779
|
+
for (let j = 0; j < both.length; j += 4) {
|
|
780
|
+
const color = (both[j] << 16) | (both[j + 1] << 8) | both[j + 2];
|
|
781
|
+
counts.set(color, (counts.get(color) ?? 0) + 1);
|
|
782
|
+
}
|
|
783
|
+
for (const [color] of [...counts].filter(([, n]) => n > both.length / 8000).sort((a, b) => b[1] - a[1])) {
|
|
784
|
+
const rgb = [color >> 16, (color >> 8) & 255, color & 255];
|
|
785
|
+
let nearest = -1, distance = Infinity;
|
|
786
|
+
palette.forEach((entry, k) => {
|
|
787
|
+
const d = (entry[0] - rgb[0]) ** 2 + (entry[1] - rgb[1]) ** 2 + (entry[2] - rgb[2]) ** 2;
|
|
788
|
+
if (!taken.has(k) && d < distance) { nearest = k; distance = d; }
|
|
789
|
+
});
|
|
790
|
+
if (nearest >= 0) { palette[nearest] = rgb; taken.add(nearest); }
|
|
791
|
+
}
|
|
792
|
+
palette.push([255, 0, 255]);
|
|
793
|
+
const gif = GIFEncoder();
|
|
794
|
+
let previous = null;
|
|
795
|
+
for (let i = 0; i < count; i++) {
|
|
796
|
+
if (cancelled) return;
|
|
797
|
+
if (i > 0) {
|
|
798
|
+
playback.seek(i / (count - 1));
|
|
799
|
+
clock.advance(step);
|
|
800
|
+
// The last frame is held: it shows the end settled
|
|
801
|
+
if (i === count - 1) clock.advance(1000, 25);
|
|
592
802
|
}
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
}
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
}),
|
|
608
|
-
});
|
|
609
|
-
if (!blob) throw new Error('No PNG was created');
|
|
610
|
-
url = URL.createObjectURL(blob);
|
|
611
|
-
const link = document.createElement('a');
|
|
612
|
-
const title = poster.querySelector('.headline')?.textContent || document.title || 'poster';
|
|
613
|
-
link.download = (title.trim().toLowerCase().replace(/[^\p{L}\p{N}]+/gu, '-').replace(/^-|-$/g, '').slice(0, 100) || 'poster') + '.png';
|
|
614
|
-
link.href = url;
|
|
615
|
-
link.addEventListener('click', event => event.stopPropagation(), { once: true });
|
|
616
|
-
document.body.append(link);
|
|
617
|
-
link.click();
|
|
618
|
-
link.remove();
|
|
803
|
+
const image = i === 0 ? first : await capture();
|
|
804
|
+
const index = applyPalette(image.data, palette.slice(0, kept));
|
|
805
|
+
const pixels = previous ? index.map((p, j) => (p === previous[j] ? kept : p)) : index;
|
|
806
|
+
gif.writeFrame(pixels, image.width, image.height, {
|
|
807
|
+
palette: i === 0 ? palette : undefined, delay: i === 0 ? 1000 : i === count - 1 ? 3000 : step,
|
|
808
|
+
transparent: i > 0, transparentIndex: kept, dispose: 1,
|
|
809
|
+
});
|
|
810
|
+
previous = index;
|
|
811
|
+
const done = Math.round(((i + 1) / count) * 100);
|
|
812
|
+
button.innerHTML = `<span class="poster-download-progress" aria-hidden="true">${done}%</span>`;
|
|
813
|
+
label(`Cancel the GIF, ${done}% made`);
|
|
814
|
+
}
|
|
815
|
+
gif.finish();
|
|
816
|
+
save(new Blob([gif.bytes()], { type: 'image/gif' }), 'gif');
|
|
619
817
|
} catch (cause) {
|
|
620
|
-
|
|
621
|
-
retries++;
|
|
622
|
-
error.textContent = 'The PNG could not be saved. Check your connection and try again.';
|
|
623
|
-
error.hidden = false;
|
|
818
|
+
fail('The GIF could not be made. Check your connection and try again.');
|
|
624
819
|
} finally {
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
820
|
+
clock?.stop();
|
|
821
|
+
playback.seek(from);
|
|
822
|
+
end();
|
|
823
|
+
}
|
|
824
|
+
}
|
|
825
|
+
button.addEventListener('click', event => {
|
|
826
|
+
event.stopPropagation();
|
|
827
|
+
if (busy) {
|
|
828
|
+
if (making === 'gif') cancelled = true;
|
|
829
|
+
return;
|
|
631
830
|
}
|
|
831
|
+
if (!playable()) return savePng();
|
|
832
|
+
// A key press is a click with no pointer detail: it opens the menu on its first item
|
|
833
|
+
if (menu.hidden) openMenu(event.detail === 0);
|
|
834
|
+
else closeMenu(event.detail === 0);
|
|
835
|
+
});
|
|
836
|
+
menu.addEventListener('click', event => {
|
|
837
|
+
const item = event.target.closest('[data-format]');
|
|
838
|
+
if (!item) return;
|
|
839
|
+
event.stopPropagation();
|
|
840
|
+
closeMenu(event.detail === 0);
|
|
841
|
+
if (item.dataset.format === 'gif') saveGif();
|
|
842
|
+
else savePng();
|
|
632
843
|
});
|
|
633
844
|
tools.append(actions);
|
|
634
845
|
});
|