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