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