@bezda/rhp-mcp 0.1.7 → 0.1.9

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