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