vizmatic 0.1.13 → 0.1.15

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/PROMPT.md +28 -8
  2. package/README.md +14 -2
  3. package/dist/cli.js +222 -63
  4. package/dist/index.cjs +85 -27
  5. package/dist/index.d.cts +10 -6
  6. package/dist/index.d.ts +10 -6
  7. package/dist/index.js +85 -27
  8. package/docs/PROMPT.md +28 -8
  9. package/docs/assets/examples/agent-pipeline_dark.png +0 -0
  10. package/docs/assets/examples/agent-pipeline_light.png +0 -0
  11. package/docs/assets/examples/animated-pipeline_dark.png +0 -0
  12. package/docs/assets/examples/animated-pipeline_light.png +0 -0
  13. package/docs/assets/examples/attention-head_dark.png +0 -0
  14. package/docs/assets/examples/attention-head_light.png +0 -0
  15. package/docs/assets/examples/embedding-map_dark.png +0 -0
  16. package/docs/assets/examples/embedding-map_light.png +0 -0
  17. package/docs/assets/examples/eval-dashboard_dark.png +0 -0
  18. package/docs/assets/examples/eval-dashboard_light.png +0 -0
  19. package/docs/assets/examples/manifest.json +16 -0
  20. package/docs/assets/examples/model-router_dark.png +0 -0
  21. package/docs/assets/examples/model-router_light.png +0 -0
  22. package/docs/assets/examples/presentation-frame_dark.png +0 -0
  23. package/docs/assets/examples/presentation-frame_light.png +0 -0
  24. package/docs/assets/examples/rag-graph_dark.png +0 -0
  25. package/docs/assets/examples/rag-graph_light.png +0 -0
  26. package/docs/assets/examples/release-card_dark.png +0 -0
  27. package/docs/assets/examples/release-card_light.png +0 -0
  28. package/docs/assets/examples/research-landscape_dark.png +0 -0
  29. package/docs/assets/examples/research-landscape_light.png +0 -0
  30. package/docs/assets/examples/sources.json +26 -6
  31. package/docs/assets/examples/spec-anatomy_dark.png +0 -0
  32. package/docs/assets/examples/spec-anatomy_light.png +0 -0
  33. package/docs/assets/examples/theme-background_dark.png +0 -0
  34. package/docs/assets/examples/theme-background_light.png +0 -0
  35. package/docs/assets/examples/theme-system_dark.png +0 -0
  36. package/docs/assets/examples/theme-system_light.png +0 -0
  37. package/docs/assets/examples/token-matrix_dark.png +0 -0
  38. package/docs/assets/examples/token-matrix_light.png +0 -0
  39. package/docs/assets/examples/transparent-badge_dark.png +0 -0
  40. package/docs/assets/examples/transparent-badge_light.png +0 -0
  41. package/examples/README.md +2 -0
  42. package/examples/model-router.tsx +1 -1
  43. package/examples/research-landscape.tsx +1 -1
  44. package/examples/theme-background.tsx +15 -0
  45. package/examples/transparent-badge.tsx +15 -0
  46. package/examples/vizmatic-bare.d.ts +1 -0
  47. package/package.json +2 -1
package/dist/index.cjs CHANGED
@@ -387,6 +387,21 @@ function lerpColor(a, b, t) {
387
387
 
388
388
  // src/primitives.ts
389
389
  var import_react = __toESM(require("react"), 1);
390
+
391
+ // src/renderContext.ts
392
+ var import_async_hooks = require("async_hooks");
393
+ var RENDER_CONTEXT_KEY = /* @__PURE__ */ Symbol.for("vizmatic.renderContext");
394
+ var globalRenderContext = globalThis;
395
+ var renderContext = globalRenderContext[RENDER_CONTEXT_KEY] ??= new import_async_hooks.AsyncLocalStorage();
396
+ function getRenderBackground() {
397
+ return renderContext.getStore()?.background ?? "transparent";
398
+ }
399
+ async function withRenderContext(context, render) {
400
+ const parent = renderContext.getStore();
401
+ return renderContext.run({ ...parent, ...context }, render);
402
+ }
403
+
404
+ // src/primitives.ts
390
405
  function defineIllustration(build, defaultTheme = "dark") {
391
406
  return {
392
407
  create(theme) {
@@ -396,6 +411,8 @@ function defineIllustration(build, defaultTheme = "dark") {
396
411
  };
397
412
  }
398
413
  function Canvas({ children, c, padding = 40, justify = "center", background }) {
414
+ const renderBackground = getRenderBackground();
415
+ const canvasBackground = background ?? (renderBackground === "theme" ? c.bg : renderBackground);
399
416
  return import_react.default.createElement("div", {
400
417
  style: {
401
418
  width: "100%",
@@ -405,7 +422,7 @@ function Canvas({ children, c, padding = 40, justify = "center", background }) {
405
422
  flexDirection: "column",
406
423
  alignItems: "center",
407
424
  justifyContent: justify,
408
- backgroundColor: background ?? c.bg,
425
+ backgroundColor: canvasBackground,
409
426
  fontFamily: "Inter",
410
427
  padding
411
428
  }
@@ -4874,7 +4891,7 @@ function detectBackgroundColor(pixels) {
4874
4891
  const b = pixels[2];
4875
4892
  const a = pixels[3];
4876
4893
  if (a < 10) {
4877
- return "#000000";
4894
+ return "transparent";
4878
4895
  }
4879
4896
  return `#${r.toString(16).padStart(2, "0")}${g.toString(16).padStart(2, "0")}${b.toString(16).padStart(2, "0")}`;
4880
4897
  }
@@ -4886,12 +4903,18 @@ function parseHexColor(hex) {
4886
4903
  parseInt(h.slice(4, 6), 16)
4887
4904
  ];
4888
4905
  }
4889
- function isBackground(r, g, b, a, bgR, bgG, bgB, tolerance = 6) {
4890
- if (a < 10) return true;
4891
- return Math.abs(r - bgR) <= tolerance && Math.abs(g - bgG) <= tolerance && Math.abs(b - bgB) <= tolerance;
4906
+ function createBackgroundMatcher(bgColor, tolerance = 6) {
4907
+ if (bgColor === "transparent") {
4908
+ return (_r, _g, _b, a) => a < 10;
4909
+ }
4910
+ const [bgR, bgG, bgB] = parseHexColor(bgColor);
4911
+ return (r, g, b, a) => {
4912
+ if (a < 10) return true;
4913
+ return Math.abs(r - bgR) <= tolerance && Math.abs(g - bgG) <= tolerance && Math.abs(b - bgB) <= tolerance;
4914
+ };
4892
4915
  }
4893
4916
  function detectContentBounds(pixels, width, height, bgColor, padding = 20) {
4894
- const [bgR, bgG, bgB] = parseHexColor(bgColor);
4917
+ const isBackground = createBackgroundMatcher(bgColor);
4895
4918
  let minX = width;
4896
4919
  let minY = height;
4897
4920
  let maxX = 0;
@@ -4903,7 +4926,7 @@ function detectContentBounds(pixels, width, height, bgColor, padding = 20) {
4903
4926
  const g = pixels[idx + 1];
4904
4927
  const b = pixels[idx + 2];
4905
4928
  const a = pixels[idx + 3];
4906
- if (!isBackground(r, g, b, a, bgR, bgG, bgB)) {
4929
+ if (!isBackground(r, g, b, a)) {
4907
4930
  if (x < minX) minX = x;
4908
4931
  if (x > maxX) maxX = x;
4909
4932
  if (y < minY) minY = y;
@@ -4938,20 +4961,12 @@ function cropPixels(pixels, srcWidth, region) {
4938
4961
  return out;
4939
4962
  }
4940
4963
  function detectOverflow(pixels, width, height, bgColor, edgeTolerance = 3, minDensity = 0.05, alphaThreshold = 128) {
4941
- const [bgR, bgG, bgB] = parseHexColor(bgColor);
4964
+ const isBackground = createBackgroundMatcher(bgColor);
4942
4965
  function isContentPixel(x, y) {
4943
4966
  const idx = (y * width + x) * 4;
4944
4967
  const a = pixels[idx + 3];
4945
4968
  if (a < alphaThreshold) return false;
4946
- return !isBackground(
4947
- pixels[idx],
4948
- pixels[idx + 1],
4949
- pixels[idx + 2],
4950
- a,
4951
- bgR,
4952
- bgG,
4953
- bgB
4954
- );
4969
+ return !isBackground(pixels[idx], pixels[idx + 1], pixels[idx + 2], a);
4955
4970
  }
4956
4971
  function checkEdge(scanFn, length) {
4957
4972
  for (let offset = 0; offset < edgeTolerance; offset++) {
@@ -5176,6 +5191,12 @@ function resolveWatermark(options) {
5176
5191
  return options.watermark ?? options.brand;
5177
5192
  }
5178
5193
  async function renderToPng(element, options, createFn, theme) {
5194
+ return withRenderContext(
5195
+ { background: options.background ?? "transparent" },
5196
+ () => renderToPngInContext(element, options, createFn, theme)
5197
+ );
5198
+ }
5199
+ async function renderToPngInContext(element, options, createFn, theme) {
5179
5200
  const fonts = await getFonts();
5180
5201
  let svg = await satori(element, {
5181
5202
  width: options.width,
@@ -5249,6 +5270,12 @@ async function renderToPng(element, options, createFn, theme) {
5249
5270
  await (0, import_promises.writeFile)(options.outputPath, pngBuffer);
5250
5271
  }
5251
5272
  async function renderToBuffer(element, width, height, options = {}) {
5273
+ return withRenderContext(
5274
+ { background: options.background ?? "transparent" },
5275
+ () => renderToBufferInContext(element, width, height, options)
5276
+ );
5277
+ }
5278
+ async function renderToBufferInContext(element, width, height, options) {
5252
5279
  const fonts = await getFonts();
5253
5280
  const watermark = resolveWatermark(options);
5254
5281
  const outputElement = watermark ? wrapWithWatermark(
@@ -5266,12 +5293,19 @@ async function renderToBuffer(element, width, height, options = {}) {
5266
5293
  });
5267
5294
  svg = sanitizeSvg(svg);
5268
5295
  const resvg = new import_resvg_js.Resvg(svg, {
5269
- fitTo: { mode: "width", value: width * (options.scale ?? 2) }
5296
+ fitTo: { mode: "width", value: width * (options.scale ?? 2) },
5297
+ background: "rgba(0, 0, 0, 0)"
5270
5298
  });
5271
5299
  const pngData = resvg.render();
5272
5300
  return Buffer.from(pngData.asPng());
5273
5301
  }
5274
5302
  async function renderToSvg(element, width, height, options = {}) {
5303
+ return withRenderContext(
5304
+ { background: options.background ?? "transparent" },
5305
+ () => renderToSvgInContext(element, width, height, options)
5306
+ );
5307
+ }
5308
+ async function renderToSvgInContext(element, width, height, options) {
5275
5309
  const fonts = await getFonts();
5276
5310
  const watermark = resolveWatermark(options);
5277
5311
  const outputElement = watermark ? wrapWithWatermark(
@@ -5306,14 +5340,14 @@ function resolveGifenc(api) {
5306
5340
  throw new Error("gifenc exports could not be resolved");
5307
5341
  }
5308
5342
  var { GIFEncoder, applyPalette, quantize } = resolveGifenc(gifenc);
5309
- async function renderToPixels(element, width, height, scale) {
5343
+ async function renderToPixels(element, width, height, scale, background) {
5310
5344
  const fonts = await getFonts();
5311
- const svg = await satori(element, {
5345
+ const svg = await withRenderContext({ background }, () => satori(element, {
5312
5346
  width,
5313
5347
  height,
5314
5348
  fonts,
5315
5349
  loadAdditionalAsset
5316
- });
5350
+ }));
5317
5351
  const resvg = new import_resvg_js2.Resvg(svg, {
5318
5352
  fitTo: { mode: "width", value: width * scale },
5319
5353
  background: "rgba(0, 0, 0, 0)"
@@ -5336,14 +5370,37 @@ function blendPixels(base, overlay, opacity) {
5336
5370
  }
5337
5371
  return result;
5338
5372
  }
5339
- function backgroundPixels(width, height, theme) {
5373
+ function colorForBackground(background, theme) {
5374
+ if (background === "transparent") return { r: 0, g: 0, b: 0, a: 0 };
5375
+ const value = background === "theme" ? getThemeColors(theme).bg : background;
5376
+ const hex = value.match(/^#([0-9a-f]{6})$/i)?.[1];
5377
+ if (hex) {
5378
+ return {
5379
+ r: parseInt(hex.slice(0, 2), 16),
5380
+ g: parseInt(hex.slice(2, 4), 16),
5381
+ b: parseInt(hex.slice(4, 6), 16),
5382
+ a: 255
5383
+ };
5384
+ }
5385
+ const rgb = value.match(/^rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)(?:\s*,\s*([0-9.]+))?\s*\)$/i);
5386
+ if (rgb) {
5387
+ return {
5388
+ r: Number(rgb[1]),
5389
+ g: Number(rgb[2]),
5390
+ b: Number(rgb[3]),
5391
+ a: Math.round(Number(rgb[4] ?? "1") * 255)
5392
+ };
5393
+ }
5394
+ return { r: 0, g: 0, b: 0, a: 0 };
5395
+ }
5396
+ function backgroundPixels(width, height, theme, background) {
5340
5397
  const buffer = new Uint8Array(width * height * 4);
5341
- const color = theme === "light" ? { r: 245, g: 247, b: 250 } : { r: 21, g: 22, b: 32 };
5398
+ const color = colorForBackground(background, theme);
5342
5399
  for (let index = 0; index < buffer.length; index += 4) {
5343
5400
  buffer[index] = color.r;
5344
5401
  buffer[index + 1] = color.g;
5345
5402
  buffer[index + 2] = color.b;
5346
- buffer[index + 3] = 255;
5403
+ buffer[index + 3] = color.a;
5347
5404
  }
5348
5405
  return buffer;
5349
5406
  }
@@ -5371,7 +5428,7 @@ async function scenesToFrames(scenes, options) {
5371
5428
  for (const scene of scenes) {
5372
5429
  const watermark = options.watermark ?? options.brand;
5373
5430
  const element = watermark ? wrapWithWatermark(scene.element, options.width, options.height, options.theme, watermark) : scene.element;
5374
- renderedScenes.push(await renderToPixels(element, options.width, options.height, options.scale));
5431
+ renderedScenes.push(await renderToPixels(element, options.width, options.height, options.scale, options.background));
5375
5432
  }
5376
5433
  const frames = [];
5377
5434
  const scaledWidth = options.width * options.scale;
@@ -5390,7 +5447,7 @@ async function scenesToFrames(scenes, options) {
5390
5447
  const frameDelay = transitionDuration / transitionFrames;
5391
5448
  for (let frameIndex = 0; frameIndex < transitionFrames; frameIndex += 1) {
5392
5449
  const amount = (frameIndex + 1) / transitionFrames;
5393
- const pixels = transition === "fade" ? blendPixels(previous.pixels, current.pixels, amount) : blendPixels(backgroundPixels(scaledWidth, scaledHeight, options.theme), current.pixels, amount);
5450
+ const pixels = transition === "fade" ? blendPixels(previous.pixels, current.pixels, amount) : blendPixels(backgroundPixels(scaledWidth, scaledHeight, options.theme, options.background), current.pixels, amount);
5394
5451
  frames.push({ pixels, delay: frameDelay, width: scaledWidth, height: scaledHeight });
5395
5452
  }
5396
5453
  }
@@ -5408,7 +5465,8 @@ async function renderAnimatedGif(scenes, options) {
5408
5465
  ...options,
5409
5466
  loop: options.loop ?? 0,
5410
5467
  scale: options.scale ?? 1,
5411
- theme: options.theme ?? "dark"
5468
+ theme: options.theme ?? "dark",
5469
+ background: options.background ?? "theme"
5412
5470
  };
5413
5471
  await (0, import_promises2.mkdir)((0, import_path2.dirname)(options.outputPath), { recursive: true });
5414
5472
  const frames = await scenesToFrames(scenes, normalized);
package/dist/index.d.cts CHANGED
@@ -1270,6 +1270,8 @@ declare function Watermark(_props: WatermarkElementProps): null;
1270
1270
  declare function wrapWithWatermark(element: React.ReactNode, width: number, height: number, theme?: 'dark' | 'light', watermark?: WatermarkInput): React.ReactElement;
1271
1271
  declare function wrapWithBrand(element: React.ReactNode, width: number, height: number, theme?: 'dark' | 'light', label?: string): React.ReactElement;
1272
1272
 
1273
+ type RenderBackground = 'transparent' | 'theme' | (string & {});
1274
+
1273
1275
  /**
1274
1276
  * Vizmatic — Core Renderer
1275
1277
  *
@@ -1309,6 +1311,8 @@ interface RenderOptions {
1309
1311
  crop?: boolean;
1310
1312
  /** Retina output scale. */
1311
1313
  scale?: number;
1314
+ /** Root background for Vizmatic primitives. Defaults to alpha-transparent PNG/SVG output. */
1315
+ background?: RenderBackground;
1312
1316
  }
1313
1317
  /**
1314
1318
  * Render a JSX element to a PNG file, with auto-crop and optional watermark.
@@ -1329,11 +1333,11 @@ declare function renderToPng(element: ReactNode, options: RenderOptions, createF
1329
1333
  /**
1330
1334
  * Render a JSX element to a PNG buffer (useful for testing).
1331
1335
  */
1332
- declare function renderToBuffer(element: ReactNode, width: number, height: number, options?: Pick<RenderOptions, 'brand' | 'watermark' | 'scale'>): Promise<Buffer>;
1336
+ declare function renderToBuffer(element: ReactNode, width: number, height: number, options?: Pick<RenderOptions, 'brand' | 'watermark' | 'scale' | 'background'>): Promise<Buffer>;
1333
1337
  /**
1334
1338
  * Render a JSX element to SVG markup without rasterization.
1335
1339
  */
1336
- declare function renderToSvg(element: ReactNode, width: number, height: number, options?: Pick<RenderOptions, 'brand' | 'watermark'>): Promise<string>;
1340
+ declare function renderToSvg(element: ReactNode, width: number, height: number, options?: Pick<RenderOptions, 'brand' | 'watermark' | 'background'>): Promise<string>;
1337
1341
 
1338
1342
  type TransitionType = 'none' | 'fade' | 'appear';
1339
1343
  interface AnimatedScene {
@@ -1352,6 +1356,7 @@ interface AnimationOptions {
1352
1356
  watermark?: WatermarkInput;
1353
1357
  brand?: boolean | string;
1354
1358
  theme?: 'dark' | 'light';
1359
+ background?: RenderBackground;
1355
1360
  }
1356
1361
  declare function renderAnimatedGif(scenes: AnimatedScene[], options: AnimationOptions): Promise<void>;
1357
1362
 
@@ -1377,9 +1382,8 @@ interface CropRegion {
1377
1382
  /**
1378
1383
  * Detect background color from top-left corner pixel.
1379
1384
  *
1380
- * Transparent canvases still rely on alpha-based background detection, so the
1381
- * exact RGB value is only relevant when the illustration paints an opaque root
1382
- * background.
1385
+ * Transparent canvases are tracked separately so opaque black content is not
1386
+ * mistaken for a transparent background.
1383
1387
  */
1384
1388
  declare function detectBackgroundColor(pixels: Uint8Array): string;
1385
1389
  /**
@@ -1435,4 +1439,4 @@ interface OverflowResult {
1435
1439
  */
1436
1440
  declare function detectOverflow(pixels: Uint8Array, width: number, height: number, bgColor: string, edgeTolerance?: number, minDensity?: number, alphaThreshold?: number): OverflowResult;
1437
1441
 
1438
- export { type AnimatedScene, type AnimationOptions, Arrow, ArrowMarkerDef, AxisPlot, type AxisPlotPath, Badge, BadgePill, BarChart, type BarChartDatum, Box, CalloutCard, Canvas, Card, ChartFrame, type ChartLegendItem, type ChartMargins, type ChartValueFormat, CodeBlock, type CodeLineSpec, type ColorName, Column, Comparison, type ComparisonSideSpec, Connector, type CropRegion, DashedLine, DataTable, DetailList, DotPoint, EquationCard, Flow, FlowArrow, type FlowStageSpec, GradientChip, GraphDiagram, type GraphDiagramEdge, type GraphDiagramNode, Grid, Heatmap, type IllustrationBuilder, type IntervalDatum, IntervalPlot, KeyValueList, type KeyValueRow, LayeredNetwork, type LayeredNetworkLayer, Legend, LineChart, type LineChartSeries, MathText, Matrix, MetricCard, MiniBarChart, type MiniBarDatum, type OverflowResult, Panel, Pipeline, type PlotArea, ProgressList, ProgressRow, type ProgressRowSpec, QuadrantChart, type QuadrantRegion, type RenderOptions, Row, ScatterPlot, type ScatterPoint, Scene, Stack, StackedBar, type StackedBarSegment, type StatusKind, StatusList, StatusRow, type StatusRowSpec, StepCard, SvgFrame, SvgMathText, SvgPoint, TextLabel, type ThemeColors, type ThemeMode, Tile, TileGrid, type TileSpec, TiledMatrix, type TiledMatrixRegion, TitleBar, type ToneName, ToneStrip, type TransitionType, ValuePill, VectorArrow, VectorSegment, Watermark, type WatermarkElementProps, type WatermarkImageOptions, type WatermarkInput, type WatermarkOptions, type WatermarkPosition, WindowFrame, canvas, colors, createPlotArea, cropPixels, defineIllustration, detectBackgroundColor, detectContentBounds, detectOverflow, formatMathText, getColor, getFonts, getGradient, getStyles, getThemeColors, getToneColor, getToneGradient, gradients, heatColor, loadAdditionalAsset, normalizeWatermark, renderAnimatedGif, renderToBuffer, renderToPng, renderToSvg, styles, toneGradients, typography, wrapWithBrand, wrapWithWatermark };
1442
+ export { type AnimatedScene, type AnimationOptions, Arrow, ArrowMarkerDef, AxisPlot, type AxisPlotPath, Badge, BadgePill, BarChart, type BarChartDatum, Box, CalloutCard, Canvas, Card, ChartFrame, type ChartLegendItem, type ChartMargins, type ChartValueFormat, CodeBlock, type CodeLineSpec, type ColorName, Column, Comparison, type ComparisonSideSpec, Connector, type CropRegion, DashedLine, DataTable, DetailList, DotPoint, EquationCard, Flow, FlowArrow, type FlowStageSpec, GradientChip, GraphDiagram, type GraphDiagramEdge, type GraphDiagramNode, Grid, Heatmap, type IllustrationBuilder, type IntervalDatum, IntervalPlot, KeyValueList, type KeyValueRow, LayeredNetwork, type LayeredNetworkLayer, Legend, LineChart, type LineChartSeries, MathText, Matrix, MetricCard, MiniBarChart, type MiniBarDatum, type OverflowResult, Panel, Pipeline, type PlotArea, ProgressList, ProgressRow, type ProgressRowSpec, QuadrantChart, type QuadrantRegion, type RenderBackground, type RenderOptions, Row, ScatterPlot, type ScatterPoint, Scene, Stack, StackedBar, type StackedBarSegment, type StatusKind, StatusList, StatusRow, type StatusRowSpec, StepCard, SvgFrame, SvgMathText, SvgPoint, TextLabel, type ThemeColors, type ThemeMode, Tile, TileGrid, type TileSpec, TiledMatrix, type TiledMatrixRegion, TitleBar, type ToneName, ToneStrip, type TransitionType, ValuePill, VectorArrow, VectorSegment, Watermark, type WatermarkElementProps, type WatermarkImageOptions, type WatermarkInput, type WatermarkOptions, type WatermarkPosition, WindowFrame, canvas, colors, createPlotArea, cropPixels, defineIllustration, detectBackgroundColor, detectContentBounds, detectOverflow, formatMathText, getColor, getFonts, getGradient, getStyles, getThemeColors, getToneColor, getToneGradient, gradients, heatColor, loadAdditionalAsset, normalizeWatermark, renderAnimatedGif, renderToBuffer, renderToPng, renderToSvg, styles, toneGradients, typography, wrapWithBrand, wrapWithWatermark };
package/dist/index.d.ts CHANGED
@@ -1270,6 +1270,8 @@ declare function Watermark(_props: WatermarkElementProps): null;
1270
1270
  declare function wrapWithWatermark(element: React.ReactNode, width: number, height: number, theme?: 'dark' | 'light', watermark?: WatermarkInput): React.ReactElement;
1271
1271
  declare function wrapWithBrand(element: React.ReactNode, width: number, height: number, theme?: 'dark' | 'light', label?: string): React.ReactElement;
1272
1272
 
1273
+ type RenderBackground = 'transparent' | 'theme' | (string & {});
1274
+
1273
1275
  /**
1274
1276
  * Vizmatic — Core Renderer
1275
1277
  *
@@ -1309,6 +1311,8 @@ interface RenderOptions {
1309
1311
  crop?: boolean;
1310
1312
  /** Retina output scale. */
1311
1313
  scale?: number;
1314
+ /** Root background for Vizmatic primitives. Defaults to alpha-transparent PNG/SVG output. */
1315
+ background?: RenderBackground;
1312
1316
  }
1313
1317
  /**
1314
1318
  * Render a JSX element to a PNG file, with auto-crop and optional watermark.
@@ -1329,11 +1333,11 @@ declare function renderToPng(element: ReactNode, options: RenderOptions, createF
1329
1333
  /**
1330
1334
  * Render a JSX element to a PNG buffer (useful for testing).
1331
1335
  */
1332
- declare function renderToBuffer(element: ReactNode, width: number, height: number, options?: Pick<RenderOptions, 'brand' | 'watermark' | 'scale'>): Promise<Buffer>;
1336
+ declare function renderToBuffer(element: ReactNode, width: number, height: number, options?: Pick<RenderOptions, 'brand' | 'watermark' | 'scale' | 'background'>): Promise<Buffer>;
1333
1337
  /**
1334
1338
  * Render a JSX element to SVG markup without rasterization.
1335
1339
  */
1336
- declare function renderToSvg(element: ReactNode, width: number, height: number, options?: Pick<RenderOptions, 'brand' | 'watermark'>): Promise<string>;
1340
+ declare function renderToSvg(element: ReactNode, width: number, height: number, options?: Pick<RenderOptions, 'brand' | 'watermark' | 'background'>): Promise<string>;
1337
1341
 
1338
1342
  type TransitionType = 'none' | 'fade' | 'appear';
1339
1343
  interface AnimatedScene {
@@ -1352,6 +1356,7 @@ interface AnimationOptions {
1352
1356
  watermark?: WatermarkInput;
1353
1357
  brand?: boolean | string;
1354
1358
  theme?: 'dark' | 'light';
1359
+ background?: RenderBackground;
1355
1360
  }
1356
1361
  declare function renderAnimatedGif(scenes: AnimatedScene[], options: AnimationOptions): Promise<void>;
1357
1362
 
@@ -1377,9 +1382,8 @@ interface CropRegion {
1377
1382
  /**
1378
1383
  * Detect background color from top-left corner pixel.
1379
1384
  *
1380
- * Transparent canvases still rely on alpha-based background detection, so the
1381
- * exact RGB value is only relevant when the illustration paints an opaque root
1382
- * background.
1385
+ * Transparent canvases are tracked separately so opaque black content is not
1386
+ * mistaken for a transparent background.
1383
1387
  */
1384
1388
  declare function detectBackgroundColor(pixels: Uint8Array): string;
1385
1389
  /**
@@ -1435,4 +1439,4 @@ interface OverflowResult {
1435
1439
  */
1436
1440
  declare function detectOverflow(pixels: Uint8Array, width: number, height: number, bgColor: string, edgeTolerance?: number, minDensity?: number, alphaThreshold?: number): OverflowResult;
1437
1441
 
1438
- export { type AnimatedScene, type AnimationOptions, Arrow, ArrowMarkerDef, AxisPlot, type AxisPlotPath, Badge, BadgePill, BarChart, type BarChartDatum, Box, CalloutCard, Canvas, Card, ChartFrame, type ChartLegendItem, type ChartMargins, type ChartValueFormat, CodeBlock, type CodeLineSpec, type ColorName, Column, Comparison, type ComparisonSideSpec, Connector, type CropRegion, DashedLine, DataTable, DetailList, DotPoint, EquationCard, Flow, FlowArrow, type FlowStageSpec, GradientChip, GraphDiagram, type GraphDiagramEdge, type GraphDiagramNode, Grid, Heatmap, type IllustrationBuilder, type IntervalDatum, IntervalPlot, KeyValueList, type KeyValueRow, LayeredNetwork, type LayeredNetworkLayer, Legend, LineChart, type LineChartSeries, MathText, Matrix, MetricCard, MiniBarChart, type MiniBarDatum, type OverflowResult, Panel, Pipeline, type PlotArea, ProgressList, ProgressRow, type ProgressRowSpec, QuadrantChart, type QuadrantRegion, type RenderOptions, Row, ScatterPlot, type ScatterPoint, Scene, Stack, StackedBar, type StackedBarSegment, type StatusKind, StatusList, StatusRow, type StatusRowSpec, StepCard, SvgFrame, SvgMathText, SvgPoint, TextLabel, type ThemeColors, type ThemeMode, Tile, TileGrid, type TileSpec, TiledMatrix, type TiledMatrixRegion, TitleBar, type ToneName, ToneStrip, type TransitionType, ValuePill, VectorArrow, VectorSegment, Watermark, type WatermarkElementProps, type WatermarkImageOptions, type WatermarkInput, type WatermarkOptions, type WatermarkPosition, WindowFrame, canvas, colors, createPlotArea, cropPixels, defineIllustration, detectBackgroundColor, detectContentBounds, detectOverflow, formatMathText, getColor, getFonts, getGradient, getStyles, getThemeColors, getToneColor, getToneGradient, gradients, heatColor, loadAdditionalAsset, normalizeWatermark, renderAnimatedGif, renderToBuffer, renderToPng, renderToSvg, styles, toneGradients, typography, wrapWithBrand, wrapWithWatermark };
1442
+ export { type AnimatedScene, type AnimationOptions, Arrow, ArrowMarkerDef, AxisPlot, type AxisPlotPath, Badge, BadgePill, BarChart, type BarChartDatum, Box, CalloutCard, Canvas, Card, ChartFrame, type ChartLegendItem, type ChartMargins, type ChartValueFormat, CodeBlock, type CodeLineSpec, type ColorName, Column, Comparison, type ComparisonSideSpec, Connector, type CropRegion, DashedLine, DataTable, DetailList, DotPoint, EquationCard, Flow, FlowArrow, type FlowStageSpec, GradientChip, GraphDiagram, type GraphDiagramEdge, type GraphDiagramNode, Grid, Heatmap, type IllustrationBuilder, type IntervalDatum, IntervalPlot, KeyValueList, type KeyValueRow, LayeredNetwork, type LayeredNetworkLayer, Legend, LineChart, type LineChartSeries, MathText, Matrix, MetricCard, MiniBarChart, type MiniBarDatum, type OverflowResult, Panel, Pipeline, type PlotArea, ProgressList, ProgressRow, type ProgressRowSpec, QuadrantChart, type QuadrantRegion, type RenderBackground, type RenderOptions, Row, ScatterPlot, type ScatterPoint, Scene, Stack, StackedBar, type StackedBarSegment, type StatusKind, StatusList, StatusRow, type StatusRowSpec, StepCard, SvgFrame, SvgMathText, SvgPoint, TextLabel, type ThemeColors, type ThemeMode, Tile, TileGrid, type TileSpec, TiledMatrix, type TiledMatrixRegion, TitleBar, type ToneName, ToneStrip, type TransitionType, ValuePill, VectorArrow, VectorSegment, Watermark, type WatermarkElementProps, type WatermarkImageOptions, type WatermarkInput, type WatermarkOptions, type WatermarkPosition, WindowFrame, canvas, colors, createPlotArea, cropPixels, defineIllustration, detectBackgroundColor, detectContentBounds, detectOverflow, formatMathText, getColor, getFonts, getGradient, getStyles, getThemeColors, getToneColor, getToneGradient, gradients, heatColor, loadAdditionalAsset, normalizeWatermark, renderAnimatedGif, renderToBuffer, renderToPng, renderToSvg, styles, toneGradients, typography, wrapWithBrand, wrapWithWatermark };
package/dist/index.js CHANGED
@@ -261,6 +261,21 @@ function lerpColor(a, b, t) {
261
261
 
262
262
  // src/primitives.ts
263
263
  import React from "react";
264
+
265
+ // src/renderContext.ts
266
+ import { AsyncLocalStorage } from "async_hooks";
267
+ var RENDER_CONTEXT_KEY = /* @__PURE__ */ Symbol.for("vizmatic.renderContext");
268
+ var globalRenderContext = globalThis;
269
+ var renderContext = globalRenderContext[RENDER_CONTEXT_KEY] ??= new AsyncLocalStorage();
270
+ function getRenderBackground() {
271
+ return renderContext.getStore()?.background ?? "transparent";
272
+ }
273
+ async function withRenderContext(context, render) {
274
+ const parent = renderContext.getStore();
275
+ return renderContext.run({ ...parent, ...context }, render);
276
+ }
277
+
278
+ // src/primitives.ts
264
279
  function defineIllustration(build, defaultTheme = "dark") {
265
280
  return {
266
281
  create(theme) {
@@ -270,6 +285,8 @@ function defineIllustration(build, defaultTheme = "dark") {
270
285
  };
271
286
  }
272
287
  function Canvas({ children, c, padding = 40, justify = "center", background }) {
288
+ const renderBackground = getRenderBackground();
289
+ const canvasBackground = background ?? (renderBackground === "theme" ? c.bg : renderBackground);
273
290
  return React.createElement("div", {
274
291
  style: {
275
292
  width: "100%",
@@ -279,7 +296,7 @@ function Canvas({ children, c, padding = 40, justify = "center", background }) {
279
296
  flexDirection: "column",
280
297
  alignItems: "center",
281
298
  justifyContent: justify,
282
- backgroundColor: background ?? c.bg,
299
+ backgroundColor: canvasBackground,
283
300
  fontFamily: "Inter",
284
301
  padding
285
302
  }
@@ -4748,7 +4765,7 @@ function detectBackgroundColor(pixels) {
4748
4765
  const b = pixels[2];
4749
4766
  const a = pixels[3];
4750
4767
  if (a < 10) {
4751
- return "#000000";
4768
+ return "transparent";
4752
4769
  }
4753
4770
  return `#${r.toString(16).padStart(2, "0")}${g.toString(16).padStart(2, "0")}${b.toString(16).padStart(2, "0")}`;
4754
4771
  }
@@ -4760,12 +4777,18 @@ function parseHexColor(hex) {
4760
4777
  parseInt(h.slice(4, 6), 16)
4761
4778
  ];
4762
4779
  }
4763
- function isBackground(r, g, b, a, bgR, bgG, bgB, tolerance = 6) {
4764
- if (a < 10) return true;
4765
- return Math.abs(r - bgR) <= tolerance && Math.abs(g - bgG) <= tolerance && Math.abs(b - bgB) <= tolerance;
4780
+ function createBackgroundMatcher(bgColor, tolerance = 6) {
4781
+ if (bgColor === "transparent") {
4782
+ return (_r, _g, _b, a) => a < 10;
4783
+ }
4784
+ const [bgR, bgG, bgB] = parseHexColor(bgColor);
4785
+ return (r, g, b, a) => {
4786
+ if (a < 10) return true;
4787
+ return Math.abs(r - bgR) <= tolerance && Math.abs(g - bgG) <= tolerance && Math.abs(b - bgB) <= tolerance;
4788
+ };
4766
4789
  }
4767
4790
  function detectContentBounds(pixels, width, height, bgColor, padding = 20) {
4768
- const [bgR, bgG, bgB] = parseHexColor(bgColor);
4791
+ const isBackground = createBackgroundMatcher(bgColor);
4769
4792
  let minX = width;
4770
4793
  let minY = height;
4771
4794
  let maxX = 0;
@@ -4777,7 +4800,7 @@ function detectContentBounds(pixels, width, height, bgColor, padding = 20) {
4777
4800
  const g = pixels[idx + 1];
4778
4801
  const b = pixels[idx + 2];
4779
4802
  const a = pixels[idx + 3];
4780
- if (!isBackground(r, g, b, a, bgR, bgG, bgB)) {
4803
+ if (!isBackground(r, g, b, a)) {
4781
4804
  if (x < minX) minX = x;
4782
4805
  if (x > maxX) maxX = x;
4783
4806
  if (y < minY) minY = y;
@@ -4812,20 +4835,12 @@ function cropPixels(pixels, srcWidth, region) {
4812
4835
  return out;
4813
4836
  }
4814
4837
  function detectOverflow(pixels, width, height, bgColor, edgeTolerance = 3, minDensity = 0.05, alphaThreshold = 128) {
4815
- const [bgR, bgG, bgB] = parseHexColor(bgColor);
4838
+ const isBackground = createBackgroundMatcher(bgColor);
4816
4839
  function isContentPixel(x, y) {
4817
4840
  const idx = (y * width + x) * 4;
4818
4841
  const a = pixels[idx + 3];
4819
4842
  if (a < alphaThreshold) return false;
4820
- return !isBackground(
4821
- pixels[idx],
4822
- pixels[idx + 1],
4823
- pixels[idx + 2],
4824
- a,
4825
- bgR,
4826
- bgG,
4827
- bgB
4828
- );
4843
+ return !isBackground(pixels[idx], pixels[idx + 1], pixels[idx + 2], a);
4829
4844
  }
4830
4845
  function checkEdge(scanFn, length) {
4831
4846
  for (let offset = 0; offset < edgeTolerance; offset++) {
@@ -5049,6 +5064,12 @@ function resolveWatermark(options) {
5049
5064
  return options.watermark ?? options.brand;
5050
5065
  }
5051
5066
  async function renderToPng(element, options, createFn, theme) {
5067
+ return withRenderContext(
5068
+ { background: options.background ?? "transparent" },
5069
+ () => renderToPngInContext(element, options, createFn, theme)
5070
+ );
5071
+ }
5072
+ async function renderToPngInContext(element, options, createFn, theme) {
5052
5073
  const fonts = await getFonts();
5053
5074
  let svg = await satori(element, {
5054
5075
  width: options.width,
@@ -5122,6 +5143,12 @@ async function renderToPng(element, options, createFn, theme) {
5122
5143
  await writeFile(options.outputPath, pngBuffer);
5123
5144
  }
5124
5145
  async function renderToBuffer(element, width, height, options = {}) {
5146
+ return withRenderContext(
5147
+ { background: options.background ?? "transparent" },
5148
+ () => renderToBufferInContext(element, width, height, options)
5149
+ );
5150
+ }
5151
+ async function renderToBufferInContext(element, width, height, options) {
5125
5152
  const fonts = await getFonts();
5126
5153
  const watermark = resolveWatermark(options);
5127
5154
  const outputElement = watermark ? wrapWithWatermark(
@@ -5139,12 +5166,19 @@ async function renderToBuffer(element, width, height, options = {}) {
5139
5166
  });
5140
5167
  svg = sanitizeSvg(svg);
5141
5168
  const resvg = new Resvg(svg, {
5142
- fitTo: { mode: "width", value: width * (options.scale ?? 2) }
5169
+ fitTo: { mode: "width", value: width * (options.scale ?? 2) },
5170
+ background: "rgba(0, 0, 0, 0)"
5143
5171
  });
5144
5172
  const pngData = resvg.render();
5145
5173
  return Buffer.from(pngData.asPng());
5146
5174
  }
5147
5175
  async function renderToSvg(element, width, height, options = {}) {
5176
+ return withRenderContext(
5177
+ { background: options.background ?? "transparent" },
5178
+ () => renderToSvgInContext(element, width, height, options)
5179
+ );
5180
+ }
5181
+ async function renderToSvgInContext(element, width, height, options) {
5148
5182
  const fonts = await getFonts();
5149
5183
  const watermark = resolveWatermark(options);
5150
5184
  const outputElement = watermark ? wrapWithWatermark(
@@ -5179,14 +5213,14 @@ function resolveGifenc(api) {
5179
5213
  throw new Error("gifenc exports could not be resolved");
5180
5214
  }
5181
5215
  var { GIFEncoder, applyPalette, quantize } = resolveGifenc(gifenc);
5182
- async function renderToPixels(element, width, height, scale) {
5216
+ async function renderToPixels(element, width, height, scale, background) {
5183
5217
  const fonts = await getFonts();
5184
- const svg = await satori(element, {
5218
+ const svg = await withRenderContext({ background }, () => satori(element, {
5185
5219
  width,
5186
5220
  height,
5187
5221
  fonts,
5188
5222
  loadAdditionalAsset
5189
- });
5223
+ }));
5190
5224
  const resvg = new Resvg2(svg, {
5191
5225
  fitTo: { mode: "width", value: width * scale },
5192
5226
  background: "rgba(0, 0, 0, 0)"
@@ -5209,14 +5243,37 @@ function blendPixels(base, overlay, opacity) {
5209
5243
  }
5210
5244
  return result;
5211
5245
  }
5212
- function backgroundPixels(width, height, theme) {
5246
+ function colorForBackground(background, theme) {
5247
+ if (background === "transparent") return { r: 0, g: 0, b: 0, a: 0 };
5248
+ const value = background === "theme" ? getThemeColors(theme).bg : background;
5249
+ const hex = value.match(/^#([0-9a-f]{6})$/i)?.[1];
5250
+ if (hex) {
5251
+ return {
5252
+ r: parseInt(hex.slice(0, 2), 16),
5253
+ g: parseInt(hex.slice(2, 4), 16),
5254
+ b: parseInt(hex.slice(4, 6), 16),
5255
+ a: 255
5256
+ };
5257
+ }
5258
+ const rgb = value.match(/^rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)(?:\s*,\s*([0-9.]+))?\s*\)$/i);
5259
+ if (rgb) {
5260
+ return {
5261
+ r: Number(rgb[1]),
5262
+ g: Number(rgb[2]),
5263
+ b: Number(rgb[3]),
5264
+ a: Math.round(Number(rgb[4] ?? "1") * 255)
5265
+ };
5266
+ }
5267
+ return { r: 0, g: 0, b: 0, a: 0 };
5268
+ }
5269
+ function backgroundPixels(width, height, theme, background) {
5213
5270
  const buffer = new Uint8Array(width * height * 4);
5214
- const color = theme === "light" ? { r: 245, g: 247, b: 250 } : { r: 21, g: 22, b: 32 };
5271
+ const color = colorForBackground(background, theme);
5215
5272
  for (let index = 0; index < buffer.length; index += 4) {
5216
5273
  buffer[index] = color.r;
5217
5274
  buffer[index + 1] = color.g;
5218
5275
  buffer[index + 2] = color.b;
5219
- buffer[index + 3] = 255;
5276
+ buffer[index + 3] = color.a;
5220
5277
  }
5221
5278
  return buffer;
5222
5279
  }
@@ -5244,7 +5301,7 @@ async function scenesToFrames(scenes, options) {
5244
5301
  for (const scene of scenes) {
5245
5302
  const watermark = options.watermark ?? options.brand;
5246
5303
  const element = watermark ? wrapWithWatermark(scene.element, options.width, options.height, options.theme, watermark) : scene.element;
5247
- renderedScenes.push(await renderToPixels(element, options.width, options.height, options.scale));
5304
+ renderedScenes.push(await renderToPixels(element, options.width, options.height, options.scale, options.background));
5248
5305
  }
5249
5306
  const frames = [];
5250
5307
  const scaledWidth = options.width * options.scale;
@@ -5263,7 +5320,7 @@ async function scenesToFrames(scenes, options) {
5263
5320
  const frameDelay = transitionDuration / transitionFrames;
5264
5321
  for (let frameIndex = 0; frameIndex < transitionFrames; frameIndex += 1) {
5265
5322
  const amount = (frameIndex + 1) / transitionFrames;
5266
- const pixels = transition === "fade" ? blendPixels(previous.pixels, current.pixels, amount) : blendPixels(backgroundPixels(scaledWidth, scaledHeight, options.theme), current.pixels, amount);
5323
+ const pixels = transition === "fade" ? blendPixels(previous.pixels, current.pixels, amount) : blendPixels(backgroundPixels(scaledWidth, scaledHeight, options.theme, options.background), current.pixels, amount);
5267
5324
  frames.push({ pixels, delay: frameDelay, width: scaledWidth, height: scaledHeight });
5268
5325
  }
5269
5326
  }
@@ -5281,7 +5338,8 @@ async function renderAnimatedGif(scenes, options) {
5281
5338
  ...options,
5282
5339
  loop: options.loop ?? 0,
5283
5340
  scale: options.scale ?? 1,
5284
- theme: options.theme ?? "dark"
5341
+ theme: options.theme ?? "dark",
5342
+ background: options.background ?? "theme"
5285
5343
  };
5286
5344
  await mkdir2(dirname2(options.outputPath), { recursive: true });
5287
5345
  const frames = await scenesToFrames(scenes, normalized);