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