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