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