@bezda/rhp-mcp 0.1.8 → 0.1.10

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