@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.
Files changed (47) hide show
  1. package/package.json +2 -2
  2. package/skill/SKILL.md +5 -5
  3. package/skill/recipes/area.html +349 -138
  4. package/skill/recipes/bar.html +349 -138
  5. package/skill/recipes/box-plot.html +349 -138
  6. package/skill/recipes/bubble.html +349 -138
  7. package/skill/recipes/bullet.html +349 -138
  8. package/skill/recipes/candlestick.html +349 -138
  9. package/skill/recipes/column.html +349 -138
  10. package/skill/recipes/dial.html +349 -138
  11. package/skill/recipes/diverging-bars.html +349 -138
  12. package/skill/recipes/donut.html +349 -138
  13. package/skill/recipes/dumbbell.html +349 -138
  14. package/skill/recipes/gantt.html +349 -138
  15. package/skill/recipes/grouped-bars.html +349 -138
  16. package/skill/recipes/heatmap.html +349 -138
  17. package/skill/recipes/histogram.html +349 -138
  18. package/skill/recipes/line.html +349 -138
  19. package/skill/recipes/live.html +349 -138
  20. package/skill/recipes/log-line.html +349 -138
  21. package/skill/recipes/lollipop.html +349 -138
  22. package/skill/recipes/multi-line.html +349 -138
  23. package/skill/recipes/pyramid.html +349 -138
  24. package/skill/recipes/race.html +363 -139
  25. package/skill/recipes/radial-bars.html +349 -138
  26. package/skill/recipes/scatter.html +349 -138
  27. package/skill/recipes/silhouettes.html +349 -138
  28. package/skill/recipes/slope.html +349 -138
  29. package/skill/recipes/sparklines.html +349 -138
  30. package/skill/recipes/stacked-100.html +349 -138
  31. package/skill/recipes/stacked-bars.html +349 -138
  32. package/skill/recipes/strip.html +349 -138
  33. package/skill/recipes/tape.html +415 -165
  34. package/skill/recipes/unit-stack.html +349 -138
  35. package/skill/recipes/violin.html +349 -138
  36. package/skill/recipes/waffle.html +349 -138
  37. package/skill/recipes/waterfall.html +349 -138
  38. package/skill/references/api.md +34 -6
  39. package/skill/references/design.md +18 -2
  40. package/skill/references/download.md +372 -140
  41. package/skill/references/environments.md +1 -1
  42. package/skill/references/interaction.md +2 -0
  43. package/skill/references/pitfalls.md +4 -3
  44. package/src/check/README.md +2 -1
  45. package/src/check/findings.js +2 -0
  46. package/src/check/inpage.js +9 -2
  47. package/src/guard/rhp.js +31 -11
@@ -491,7 +491,7 @@ render(() => html`<${BitcoinDecade} />`, document.getElementById("chart"));
491
491
  </script>
492
492
  <style id="poster-download-styles">
493
493
  .poster-download-tools { display: flex; justify-content: flex-end; align-items: center; margin: 0 auto 12px; max-width: 100%; }
494
- .poster-actions { display: flex; align-items: center; margin-left: auto; }
494
+ .poster-actions { position: relative; display: flex; align-items: center; margin-left: auto; }
495
495
  .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; }
496
496
  .poster-actions svg { display: block; width: 20px; height: 20px; }
497
497
  .poster-actions button:hover { background: color-mix(in srgb, currentColor 8%, transparent); }
@@ -502,7 +502,14 @@ render(() => html`<${BitcoinDecade} />`, document.getElementById("chart"));
502
502
  .poster-fit-frame.is-fitted { display: block; margin: 0 auto; overflow: clip; }
503
503
  .poster-fit-frame.is-fitted > .poster-fit-content { display: block; transform-origin: top left; }
504
504
  .poster-download-error { margin: 8px auto; font: 14px/1.4 system-ui, sans-serif; color: inherit; }
505
- @media print { .poster-download-tools, .poster-actions, .poster-download-error { display: none !important; } }
505
+ .poster-download-progress { font: 600 11px/1 system-ui, sans-serif; font-variant-numeric: tabular-nums; }
506
+ .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); }
507
+ .poster-download-menu[hidden] { display: none; }
508
+ .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; }
509
+ .poster-download-menu button span { font-weight: 400; font-size: 12.5px; opacity: .8; }
510
+ .poster-download-menu button:hover { background: color-mix(in srgb, currentColor 9%, transparent); }
511
+ .poster-download-menu button:focus-visible { outline: 2px solid currentColor; outline-offset: -2px; }
512
+ @media print { .poster-download-tools, .poster-actions, .poster-download-menu, .poster-download-error { display: none !important; } }
506
513
  </style>
507
514
  <script type="module" id="poster-download-script">
508
515
  function addPosterFit(poster, button, changed) {
@@ -580,6 +587,8 @@ function addPosterDownloads() {
580
587
  tools.style.color = light[0] * .2126 + light[1] * .7152 + light[2] * .0722 < .179 ? '#eef2f5' : '#1d1b17';
581
588
  }
582
589
  }
590
+ const ground = getComputedStyle(document.body).backgroundColor;
591
+ if (!/^(transparent|rgba\(0, 0, 0, 0\))$/.test(ground)) tools.style.setProperty('--poster-tools-ground', ground);
583
592
  const button = document.createElement('button');
584
593
  button.type = 'button';
585
594
  button.className = 'poster-download';
@@ -625,154 +634,356 @@ function addPosterDownloads() {
625
634
  for (const type of ['keydown', 'keyup']) actions.addEventListener(type, event => {
626
635
  if (event.key === 'Enter' || event.key === ' ') event.stopPropagation();
627
636
  });
628
- let exporter, retries = 0, busy = false;
629
- button.addEventListener('click', async event => {
630
- event.stopPropagation();
631
- if (busy) return;
637
+ // A poster that plays through its data gives itself a playback ({ duration, position, seek }): its download then
638
+ // offers the poster as it is now, a PNG, or the whole playback, an animated GIF
639
+ let exporter, encoder, retries = 0, busy = false, making = null, cancelled = false;
640
+ const playable = () => typeof poster.playback?.seek === 'function';
641
+ const icon = button.innerHTML;
642
+ const menu = document.createElement('div');
643
+ menu.className = 'poster-download-menu';
644
+ menu.setAttribute('role', 'menu');
645
+ menu.setAttribute('aria-label', 'Download poster');
646
+ menu.hidden = true;
647
+ menu.innerHTML = '<button type="button" role="menuitem" data-format="png">PNG image<span>The poster as it is now</span></button>'
648
+ + '<button type="button" role="menuitem" data-format="gif">Animated GIF<span>The whole playback</span></button>';
649
+ const items = [...menu.querySelectorAll('[role="menuitem"]')];
650
+ actions.append(menu);
651
+ const label = text => { button.setAttribute('aria-label', text); button.title = text; };
652
+ const rest = () => {
653
+ label(playable() ? 'Download poster' : 'Download poster as PNG');
654
+ if (playable()) { button.setAttribute('aria-haspopup', 'menu'); button.setAttribute('aria-expanded', String(!menu.hidden)); }
655
+ };
656
+ rest();
657
+ const closeMenu = focus => {
658
+ if (menu.hidden) return;
659
+ menu.hidden = true;
660
+ rest();
661
+ if (focus) button.focus();
662
+ };
663
+ const openMenu = focus => {
664
+ menu.hidden = false;
665
+ rest();
666
+ if (focus) items[0].focus();
667
+ };
668
+ document.addEventListener('pointerdown', event => { if (!actions.contains(event.target)) closeMenu(false); }, true);
669
+ menu.addEventListener('keydown', event => {
670
+ const at = items.indexOf(document.activeElement);
671
+ const to = { ArrowDown: at + 1, ArrowUp: at - 1, Home: 0, End: items.length - 1 }[event.key];
672
+ if (to !== undefined) { event.preventDefault(); items[(to + items.length) % items.length].focus(); }
673
+ else if (event.key === 'Escape') { event.preventDefault(); event.stopPropagation(); closeMenu(true); }
674
+ else if (event.key === 'Tab') closeMenu(false);
675
+ });
676
+ menu.addEventListener('focusout', event => { if (!menu.contains(event.relatedTarget) && event.relatedTarget !== button) closeMenu(false); });
677
+ // The capture options, made once for a download and for every frame of a GIF
678
+ const loadExporter = () => (exporter ||= import('https://cdn.jsdelivr.net/npm/modern-screenshot@4.7.0/+esm' + (retries ? `?retry=${retries}` : '')));
679
+ async function captureOptions() {
680
+ await document.fonts.ready;
681
+ // Preserve author layout rules where computed styles lose the grid's used geometry.
682
+ // Safari misreports percentage insets in subgrids, and grid auto margins resolve to zero.
683
+ const autoMargins = new Set(), positioned = new Set();
684
+ const isMargin = name => name === 'margin' || name.startsWith('margin-');
685
+ const isInset = name => name === 'inset' || name.startsWith('inset-') || ['top', 'right', 'bottom', 'left'].includes(name);
686
+ const layoutRules = rules => [...rules].map(rule => {
687
+ if (rule.selectorText && rule.style) {
688
+ const margins = [...rule.style].filter(isMargin);
689
+ if (margins.some(name => /\bauto\b/.test(rule.style.getPropertyValue(name)))) autoMargins.add(rule.selectorText);
690
+ const insets = [...rule.style].filter(isInset);
691
+ if (insets.length) positioned.add(rule.selectorText);
692
+ const layout = [...margins, ...insets];
693
+ return layout.length ? `${rule.selectorText} { ${layout.map(name => `${name}: ${rule.style.getPropertyValue(name)}${rule.style.getPropertyPriority(name) ? ' !important' : ''};`).join(' ')} }` : '';
694
+ }
695
+ if (!rule.cssRules) return /^@layer\b/.test(rule.cssText) ? rule.cssText : '';
696
+ if (rule instanceof CSSMediaRule) return matchMedia(rule.conditionText).matches ? layoutRules(rule.cssRules) : '';
697
+ if (rule instanceof CSSSupportsRule) return CSS.supports(rule.conditionText) ? layoutRules(rule.cssRules) : '';
698
+ return rule.cssText.slice(0, rule.cssText.indexOf('{') + 1) + layoutRules(rule.cssRules) + '}';
699
+ }).join('\n');
700
+ const sheets = [...document.styleSheets, ...document.adoptedStyleSheets];
701
+ const layout = sheets.map(sheet => {
702
+ try { return layoutRules(sheet.cssRules); } catch (cause) { return ''; }
703
+ }).join('\n');
704
+ // Omit display-none HTML subtrees, such as collapsed chart rows, from the image and its SVG payload.
705
+ const includeNode = node => !(node instanceof HTMLElement) || getComputedStyle(node).display !== 'none';
706
+ const restoreLayout = (source, clone) => {
707
+ if (clone.style && source !== poster) {
708
+ const margins = [...autoMargins].some(selector => source.matches(selector));
709
+ const computed = getComputedStyle(source);
710
+ const insets = computed.position === 'absolute' && [...positioned].some(selector => source.matches(selector));
711
+ const restore = name => (margins && isMargin(name)) || (insets && isInset(name));
712
+ [...clone.style].filter(restore).forEach(name => clone.style.removeProperty(name));
713
+ [...source.style].filter(restore).forEach(name => clone.style.setProperty(name, source.style.getPropertyValue(name), source.style.getPropertyPriority(name)));
714
+ if (insets) {
715
+ // Only the scaled axis needs its percentage rule. Freeze the other axis in pixels:
716
+ // Firefox does not reevaluate container queries reliably inside an SVG foreignObject.
717
+ const axis = source.getAttribute('data-rhp-o');
718
+ const fixed = axis === 'h' ? ['top', 'bottom'] : axis === 'v' ? ['left', 'right'] : ['top', 'right', 'bottom', 'left'];
719
+ fixed.forEach(name => clone.style.setProperty(name, computed.getPropertyValue(name), 'important'));
720
+ }
721
+ }
722
+ const children = [...source.children].filter(node => !['STYLE', 'SCRIPT'].includes(node.tagName) && includeNode(node));
723
+ [...clone.children].forEach((child, i) => { if (children[i]) restoreLayout(children[i], child); });
724
+ };
725
+ // Cross-origin font stylesheets are readable through fetch, but not through cssRules.
726
+ const fontFiles = new Map();
727
+ const fontRules = await Promise.all(sheets.map(async sheet => {
728
+ let css;
729
+ try { css = [...sheet.cssRules].map(rule => rule.cssText).join('\n'); }
730
+ catch (cause) {
731
+ if (!sheet.href) return '';
732
+ const response = await fetch(sheet.href);
733
+ if (!response.ok) throw new Error('Font stylesheet could not be loaded');
734
+ css = await response.text();
735
+ }
736
+ const rules = css.match(/@font-face\s*\{[^}]*\}/g) || [];
737
+ return (await Promise.all(rules.map(async rule => {
738
+ for (const match of [...rule.matchAll(/url\(["']?([^"')]+)["']?\)/g)]) {
739
+ const source = new URL(match[1], sheet.href || document.baseURI).href;
740
+ if (!fontFiles.has(source)) fontFiles.set(source, (async () => {
741
+ const response = await fetch(source);
742
+ if (!response.ok) throw new Error('Font could not be loaded');
743
+ const blob = await response.blob();
744
+ return new Promise((resolve, reject) => {
745
+ const reader = new FileReader();
746
+ reader.onload = () => resolve(reader.result);
747
+ reader.onerror = reject;
748
+ reader.readAsDataURL(blob);
749
+ });
750
+ })());
751
+ rule = rule.replace(match[1], await fontFiles.get(source));
752
+ }
753
+ return rule;
754
+ }))).join('\n');
755
+ }));
756
+ // Rasterize SVG paper textures before nesting them inside the exporter's SVG.
757
+ // This keeps SVG filter fragment references local to their own image.
758
+ const textures = new Map();
759
+ const embedTexture = async (node) => {
760
+ if (!node.style) return;
761
+ let background = node.style.backgroundImage;
762
+ for (const [, source] of background.matchAll(/url\("(data:image\/svg\+xml[^"]+)"\)/g)) {
763
+ if (!textures.has(source)) textures.set(source, (async () => {
764
+ const image = new Image();
765
+ image.src = source;
766
+ await image.decode();
767
+ const canvas = document.createElement('canvas');
768
+ canvas.width = image.naturalWidth;
769
+ canvas.height = image.naturalHeight;
770
+ canvas.getContext('2d').drawImage(image, 0, 0);
771
+ return canvas.toDataURL();
772
+ })());
773
+ background = background.replace(source, await textures.get(source));
774
+ }
775
+ node.style.backgroundImage = background;
776
+ };
777
+ return {
778
+ ...fit.dimensions(), style: { margin: '0' }, filter: includeNode,
779
+ font: { cssText: fontRules.join('\n') }, onCloneEachNode: embedTexture,
780
+ onCloneNode: clone => {
781
+ restoreLayout(poster, clone);
782
+ const style = document.createElement('style');
783
+ style.textContent = layout;
784
+ clone.prepend(style);
785
+ },
786
+ // CSS content's alternative text follows a slash and must not be painted.
787
+ onCreateForeignObjectSvg: svg => svg.querySelectorAll('style').forEach(style => {
788
+ style.textContent = style.textContent.replace(/(content:\s*')([^']*)(')/g, (_, start, text, end) => start + text.split(' / ')[0] + end);
789
+ }),
790
+ };
791
+ }
792
+ let url;
793
+ const save = (blob, extension) => {
794
+ url = URL.createObjectURL(blob);
795
+ const link = document.createElement('a');
796
+ const title = poster.querySelector('.headline')?.textContent || document.title || 'poster';
797
+ link.download = (title.trim().toLowerCase().replace(/[^\p{L}\p{N}]+/gu, '-').replace(/^-|-$/g, '').slice(0, 100) || 'poster') + '.' + extension;
798
+ link.href = url;
799
+ link.addEventListener('click', event => event.stopPropagation(), { once: true });
800
+ document.body.append(link);
801
+ link.click();
802
+ link.remove();
803
+ };
804
+ const begin = kind => {
632
805
  busy = true;
633
- button.setAttribute('aria-disabled', 'true');
806
+ making = kind;
634
807
  button.setAttribute('aria-busy', 'true');
635
808
  fitButton.setAttribute('aria-disabled', 'true');
636
- button.setAttribute('aria-label', 'Preparing poster PNG');
809
+ // A GIF takes a while: the button shows its progress and cancels it
810
+ if (kind === 'gif') label('Cancel the GIF');
811
+ else { button.setAttribute('aria-disabled', 'true'); label('Preparing poster PNG'); }
637
812
  error.hidden = true;
638
- let url;
813
+ };
814
+ const end = () => {
815
+ if (url) setTimeout(() => URL.revokeObjectURL(url), 60000);
816
+ url = null;
817
+ busy = false;
818
+ making = null;
819
+ cancelled = false;
820
+ button.innerHTML = icon;
821
+ button.removeAttribute('aria-disabled');
822
+ button.removeAttribute('aria-busy');
823
+ fitButton.removeAttribute('aria-disabled');
824
+ rest();
825
+ };
826
+ const fail = message => {
827
+ exporter = null;
828
+ encoder = null;
829
+ retries++;
830
+ error.textContent = message;
831
+ error.hidden = false;
832
+ };
833
+ async function savePng() {
834
+ begin('png');
639
835
  try {
640
- exporter ||= import('https://cdn.jsdelivr.net/npm/modern-screenshot@4.7.0/+esm' + (retries ? `?retry=${retries}` : ''));
641
- const { domToBlob } = await exporter;
642
- await document.fonts.ready;
643
- // Preserve author layout rules where computed styles lose the grid's used geometry.
644
- // Safari misreports percentage insets in subgrids, and grid auto margins resolve to zero.
645
- const autoMargins = new Set(), positioned = new Set();
646
- const isMargin = name => name === 'margin' || name.startsWith('margin-');
647
- const isInset = name => name === 'inset' || name.startsWith('inset-') || ['top', 'right', 'bottom', 'left'].includes(name);
648
- const layoutRules = rules => [...rules].map(rule => {
649
- if (rule.selectorText && rule.style) {
650
- const margins = [...rule.style].filter(isMargin);
651
- if (margins.some(name => /\bauto\b/.test(rule.style.getPropertyValue(name)))) autoMargins.add(rule.selectorText);
652
- const insets = [...rule.style].filter(isInset);
653
- if (insets.length) positioned.add(rule.selectorText);
654
- const layout = [...margins, ...insets];
655
- return layout.length ? `${rule.selectorText} { ${layout.map(name => `${name}: ${rule.style.getPropertyValue(name)}${rule.style.getPropertyPriority(name) ? ' !important' : ''};`).join(' ')} }` : '';
656
- }
657
- if (!rule.cssRules) return /^@layer\b/.test(rule.cssText) ? rule.cssText : '';
658
- if (rule instanceof CSSMediaRule) return matchMedia(rule.conditionText).matches ? layoutRules(rule.cssRules) : '';
659
- if (rule instanceof CSSSupportsRule) return CSS.supports(rule.conditionText) ? layoutRules(rule.cssRules) : '';
660
- return rule.cssText.slice(0, rule.cssText.indexOf('{') + 1) + layoutRules(rule.cssRules) + '}';
661
- }).join('\n');
662
- const sheets = [...document.styleSheets, ...document.adoptedStyleSheets];
663
- const layout = sheets.map(sheet => {
664
- try { return layoutRules(sheet.cssRules); } catch (cause) { return ''; }
665
- }).join('\n');
666
- // Omit display-none HTML subtrees, such as collapsed chart rows, from the image and its SVG payload.
667
- const includeNode = node => !(node instanceof HTMLElement) || getComputedStyle(node).display !== 'none';
668
- const restoreLayout = (source, clone) => {
669
- if (clone.style && source !== poster) {
670
- const margins = [...autoMargins].some(selector => source.matches(selector));
671
- const computed = getComputedStyle(source);
672
- const insets = computed.position === 'absolute' && [...positioned].some(selector => source.matches(selector));
673
- const restore = name => (margins && isMargin(name)) || (insets && isInset(name));
674
- [...clone.style].filter(restore).forEach(name => clone.style.removeProperty(name));
675
- [...source.style].filter(restore).forEach(name => clone.style.setProperty(name, source.style.getPropertyValue(name), source.style.getPropertyPriority(name)));
676
- if (insets) {
677
- // Only the scaled axis needs its percentage rule. Freeze the other axis in pixels:
678
- // Firefox does not reevaluate container queries reliably inside an SVG foreignObject.
679
- const axis = source.getAttribute('data-rhp-o');
680
- const fixed = axis === 'h' ? ['top', 'bottom'] : axis === 'v' ? ['left', 'right'] : ['top', 'right', 'bottom', 'left'];
681
- fixed.forEach(name => clone.style.setProperty(name, computed.getPropertyValue(name), 'important'));
836
+ const { domToBlob } = await loadExporter();
837
+ const blob = await domToBlob(poster, { ...(await captureOptions()), scale: 2 });
838
+ if (!blob) throw new Error('No PNG was created');
839
+ save(blob, 'png');
840
+ } catch (cause) {
841
+ fail('The PNG could not be saved. Check your connection and try again.');
842
+ } finally {
843
+ end();
844
+ }
845
+ }
846
+ // The GIF's clock: while it is made, rhp's motion (performance.now and animation frames) and the page's CSS
847
+ // animations run on a time of their own, which only moves on when a frame asks it to, so every frame shows the chart
848
+ // exactly as it is that many milliseconds into playing, its glides and slides included
849
+ const gifClock = () => {
850
+ const raf = window.requestAnimationFrame, caf = window.cancelAnimationFrame;
851
+ const queue = new Map(), started = new Map();
852
+ let time = performance.now(), id = 0, pump = 0;
853
+ const flush = () => {
854
+ const due = [...queue.values()];
855
+ queue.clear();
856
+ due.forEach(callback => { try { callback(time); } catch (cause) { reportError(cause); } });
857
+ };
858
+ // Callbacks still run every real frame, at the clock's time, so whatever waits for a frame is not held up
859
+ const loop = () => { flush(); pump = raf.call(window, loop); };
860
+ window.requestAnimationFrame = callback => { queue.set(++id, callback); return id; };
861
+ window.cancelAnimationFrame = n => queue.delete(n);
862
+ performance.now = () => time;
863
+ pump = raf.call(window, loop);
864
+ return {
865
+ // Two of the browser's frames: callbacks that were already waiting for one (rhp's ticker) come over to the clock
866
+ ready: new Promise(resolve => raf.call(window, () => raf.call(window, resolve))),
867
+ advance(ms, steps = 1) {
868
+ for (let i = 0; i < steps; i++) {
869
+ time += ms / steps;
870
+ // A frame's motion, then the style writes it schedules
871
+ flush(); flush(); flush();
872
+ for (const animation of document.getAnimations()) {
873
+ if (!started.has(animation)) started.set(animation, time - (animation.currentTime ?? 0));
874
+ animation.pause();
875
+ animation.currentTime = time - started.get(animation);
682
876
  }
683
877
  }
684
- const children = [...source.children].filter(node => !['STYLE', 'SCRIPT'].includes(node.tagName) && includeNode(node));
685
- [...clone.children].forEach((child, i) => { if (children[i]) restoreLayout(children[i], child); });
878
+ },
879
+ stop() {
880
+ caf.call(window, pump);
881
+ window.requestAnimationFrame = raf;
882
+ window.cancelAnimationFrame = caf;
883
+ delete performance.now;
884
+ for (const callback of queue.values()) raf.call(window, callback);
885
+ started.forEach((_, animation) => animation.play());
886
+ },
887
+ };
888
+ };
889
+ // The GIF: the playback at its own pace, 25 frames a second, at most 1200 pixels wide. One palette from the
890
+ // first and the last frame serves every frame; its last color is never drawn and marks the pixels a frame leaves as
891
+ // the frame before had them, so each frame stores only what changed.
892
+ async function saveGif() {
893
+ const playback = poster.playback;
894
+ const from = playback.position();
895
+ let clock = null;
896
+ begin('gif');
897
+ try {
898
+ encoder ||= import('https://cdn.jsdelivr.net/npm/gifenc@1.0.3/+esm' + (retries ? `?retry=${retries}` : ''));
899
+ const [{ domToCanvas }, { GIFEncoder, quantize, applyPalette }] = await Promise.all([loadExporter(), encoder]);
900
+ const options = await captureOptions();
901
+ const scale = Math.min(1, 1200 / options.width);
902
+ // The GIF plays at the chart's own pace: its playback's duration, in frames 40 ms apart
903
+ const step = 40, count = Math.max(2, Math.round((playback.duration ?? 15000) / step) + 1);
904
+ const capture = async () => {
905
+ const canvas = await domToCanvas(poster, { ...options, scale });
906
+ return canvas.getContext('2d').getImageData(0, 0, canvas.width, canvas.height);
686
907
  };
687
- // Cross-origin font stylesheets are readable through fetch, but not through cssRules.
688
- const fontFiles = new Map();
689
- const fontRules = await Promise.all(sheets.map(async sheet => {
690
- let css;
691
- try { css = [...sheet.cssRules].map(rule => rule.cssText).join('\n'); }
692
- catch (cause) {
693
- if (!sheet.href) return '';
694
- const response = await fetch(sheet.href);
695
- if (!response.ok) throw new Error('Font stylesheet could not be loaded');
696
- css = await response.text();
697
- }
698
- const rules = css.match(/@font-face\s*\{[^}]*\}/g) || [];
699
- return (await Promise.all(rules.map(async rule => {
700
- for (const match of [...rule.matchAll(/url\(["']?([^"')]+)["']?\)/g)]) {
701
- const source = new URL(match[1], sheet.href || document.baseURI).href;
702
- if (!fontFiles.has(source)) fontFiles.set(source, (async () => {
703
- const response = await fetch(source);
704
- if (!response.ok) throw new Error('Font could not be loaded');
705
- const blob = await response.blob();
706
- return new Promise((resolve, reject) => {
707
- const reader = new FileReader();
708
- reader.onload = () => resolve(reader.result);
709
- reader.onerror = reject;
710
- reader.readAsDataURL(blob);
711
- });
712
- })());
713
- rule = rule.replace(match[1], await fontFiles.get(source));
714
- }
715
- return rule;
716
- }))).join('\n');
717
- }));
718
- // Rasterize SVG paper textures before nesting them inside the exporter's SVG.
719
- // This keeps SVG filter fragment references local to their own image.
720
- const textures = new Map();
721
- const embedTexture = async (node) => {
722
- if (!node.style) return;
723
- let background = node.style.backgroundImage;
724
- for (const [, source] of background.matchAll(/url\("(data:image\/svg\+xml[^"]+)"\)/g)) {
725
- if (!textures.has(source)) textures.set(source, (async () => {
726
- const image = new Image();
727
- image.src = source;
728
- await image.decode();
729
- const canvas = document.createElement('canvas');
730
- canvas.width = image.naturalWidth;
731
- canvas.height = image.naturalHeight;
732
- canvas.getContext('2d').drawImage(image, 0, 0);
733
- return canvas.toDataURL();
734
- })());
735
- background = background.replace(source, await textures.get(source));
908
+ clock = gifClock();
909
+ await clock.ready;
910
+ // The end and the start, each given a second to settle, for the palette; the start is also the first frame
911
+ playback.seek(1);
912
+ clock.advance(1000, 25);
913
+ const last = await capture();
914
+ playback.seek(0);
915
+ clock.advance(1000, 25);
916
+ const first = await capture();
917
+ const both = new Uint8ClampedArray(first.data.length + last.data.length);
918
+ both.set(first.data);
919
+ both.set(last.data, first.data.length);
920
+ const palette = quantize(both, 255), kept = palette.length;
921
+ // A flat color that fills a part of the poster keeps its exact value: it takes the nearest palette entry
922
+ const counts = new Map(), taken = new Set();
923
+ for (let j = 0; j < both.length; j += 4) {
924
+ const color = (both[j] << 16) | (both[j + 1] << 8) | both[j + 2];
925
+ counts.set(color, (counts.get(color) ?? 0) + 1);
926
+ }
927
+ for (const [color] of [...counts].filter(([, n]) => n > both.length / 8000).sort((a, b) => b[1] - a[1])) {
928
+ const rgb = [color >> 16, (color >> 8) & 255, color & 255];
929
+ let nearest = -1, distance = Infinity;
930
+ palette.forEach((entry, k) => {
931
+ const d = (entry[0] - rgb[0]) ** 2 + (entry[1] - rgb[1]) ** 2 + (entry[2] - rgb[2]) ** 2;
932
+ if (!taken.has(k) && d < distance) { nearest = k; distance = d; }
933
+ });
934
+ if (nearest >= 0) { palette[nearest] = rgb; taken.add(nearest); }
935
+ }
936
+ palette.push([255, 0, 255]);
937
+ const gif = GIFEncoder();
938
+ let previous = null;
939
+ for (let i = 0; i < count; i++) {
940
+ if (cancelled) return;
941
+ if (i > 0) {
942
+ playback.seek(i / (count - 1));
943
+ clock.advance(step);
944
+ // The last frame is held: it shows the end settled
945
+ if (i === count - 1) clock.advance(1000, 25);
736
946
  }
737
- node.style.backgroundImage = background;
738
- };
739
- const blob = await domToBlob(poster, {
740
- ...fit.dimensions(), scale: 2, style: { margin: '0' }, filter: includeNode,
741
- font: { cssText: fontRules.join('\n') }, onCloneEachNode: embedTexture,
742
- onCloneNode: clone => {
743
- restoreLayout(poster, clone);
744
- const style = document.createElement('style');
745
- style.textContent = layout;
746
- clone.prepend(style);
747
- },
748
- // CSS content's alternative text follows a slash and must not be painted.
749
- onCreateForeignObjectSvg: svg => svg.querySelectorAll('style').forEach(style => {
750
- style.textContent = style.textContent.replace(/(content:\s*')([^']*)(')/g, (_, start, text, end) => start + text.split(' / ')[0] + end);
751
- }),
752
- });
753
- if (!blob) throw new Error('No PNG was created');
754
- url = URL.createObjectURL(blob);
755
- const link = document.createElement('a');
756
- const title = poster.querySelector('.headline')?.textContent || document.title || 'poster';
757
- link.download = (title.trim().toLowerCase().replace(/[^\p{L}\p{N}]+/gu, '-').replace(/^-|-$/g, '').slice(0, 100) || 'poster') + '.png';
758
- link.href = url;
759
- link.addEventListener('click', event => event.stopPropagation(), { once: true });
760
- document.body.append(link);
761
- link.click();
762
- link.remove();
947
+ const image = i === 0 ? first : await capture();
948
+ const index = applyPalette(image.data, palette.slice(0, kept));
949
+ const pixels = previous ? index.map((p, j) => (p === previous[j] ? kept : p)) : index;
950
+ gif.writeFrame(pixels, image.width, image.height, {
951
+ palette: i === 0 ? palette : undefined, delay: i === 0 ? 1000 : i === count - 1 ? 3000 : step,
952
+ transparent: i > 0, transparentIndex: kept, dispose: 1,
953
+ });
954
+ previous = index;
955
+ const done = Math.round(((i + 1) / count) * 100);
956
+ button.innerHTML = `<span class="poster-download-progress" aria-hidden="true">${done}%</span>`;
957
+ label(`Cancel the GIF, ${done}% made`);
958
+ }
959
+ gif.finish();
960
+ save(new Blob([gif.bytes()], { type: 'image/gif' }), 'gif');
763
961
  } catch (cause) {
764
- exporter = null;
765
- retries++;
766
- error.textContent = 'The PNG could not be saved. Check your connection and try again.';
767
- error.hidden = false;
962
+ fail('The GIF could not be made. Check your connection and try again.');
768
963
  } finally {
769
- if (url) setTimeout(() => URL.revokeObjectURL(url), 60000);
770
- busy = false;
771
- button.removeAttribute('aria-disabled');
772
- button.removeAttribute('aria-busy');
773
- fitButton.removeAttribute('aria-disabled');
774
- button.setAttribute('aria-label', 'Download poster as PNG');
964
+ clock?.stop();
965
+ playback.seek(from);
966
+ end();
967
+ }
968
+ }
969
+ button.addEventListener('click', event => {
970
+ event.stopPropagation();
971
+ if (busy) {
972
+ if (making === 'gif') cancelled = true;
973
+ return;
775
974
  }
975
+ if (!playable()) return savePng();
976
+ // A key press is a click with no pointer detail: it opens the menu on its first item
977
+ if (menu.hidden) openMenu(event.detail === 0);
978
+ else closeMenu(event.detail === 0);
979
+ });
980
+ menu.addEventListener('click', event => {
981
+ const item = event.target.closest('[data-format]');
982
+ if (!item) return;
983
+ event.stopPropagation();
984
+ closeMenu(event.detail === 0);
985
+ if (item.dataset.format === 'gif') saveGif();
986
+ else savePng();
776
987
  });
777
988
  tools.append(actions);
778
989
  });