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