@bezda/rhp-mcp 0.1.7 → 0.1.9

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