vizmatic 0.1.18 → 0.1.20

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.
package/dist/cli.js CHANGED
@@ -102,6 +102,7 @@ __export(index_exports, {
102
102
  renderAnimatedGif: () => renderAnimatedGif,
103
103
  renderToBuffer: () => renderToBuffer,
104
104
  renderToPng: () => renderToPng,
105
+ renderToPngWithOutput: () => renderToPngWithOutput,
105
106
  renderToSvg: () => renderToSvg,
106
107
  styles: () => styles,
107
108
  toneGradients: () => toneGradients,
@@ -633,6 +634,7 @@ function Panel({
633
634
  width: "100%",
634
635
  display: "flex",
635
636
  flexDirection: "column",
637
+ gap,
636
638
  ...bodyStyle
637
639
  }
638
640
  }, children),
@@ -4048,16 +4050,16 @@ function BarChart({
4048
4050
  yAxisLabel,
4049
4051
  footer
4050
4052
  }) {
4051
- const margin = { top: 18, right: 18, bottom: 40, left: yAxisLabel ? 52 : 38 };
4053
+ const margin = { top: 18, right: 38, bottom: 40, left: yAxisLabel ? 52 : 38 };
4052
4054
  const plot = createPlotArea(width, height, margin);
4053
4055
  const domain = chartDomain(data.map((item) => item.value), min, max);
4054
4056
  const ticks = chartTicks(domain.min, domain.max, 4);
4055
- const barGap = Math.max(8, plot.innerWidth / Math.max(data.length, 1) * 0.18);
4056
- const barWidth = Math.max(12, (plot.innerWidth - barGap * (data.length - 1)) / Math.max(data.length, 1));
4057
+ const barSlot = plot.innerWidth / Math.max(data.length, 1);
4058
+ const barWidth = Math.max(8, Math.min(76, barSlot * 0.72));
4057
4059
  const zeroY = yInPlot(0, domain, plot);
4058
4060
  const baselineY = clamp(zeroY, plot.y, plot.bottom);
4059
4061
  const barGeometries = data.map((item, index) => {
4060
- const x = plot.x + index * (barWidth + barGap);
4062
+ const x = plot.x + index * barSlot + (barSlot - barWidth) / 2;
4061
4063
  const valueY = yInPlot(item.value, domain, plot);
4062
4064
  const y = Math.min(valueY, baselineY);
4063
4065
  const barHeight = Math.max(4, Math.abs(baselineY - valueY));
@@ -4151,10 +4153,13 @@ function LineChart({
4151
4153
  const allValues = series.flatMap((item) => item.points);
4152
4154
  const domain = chartDomain(allValues, min, max);
4153
4155
  const maxPoints = Math.max(...series.map((item) => item.points.length), 1);
4154
- const xStep = maxPoints <= 1 ? plot.innerWidth : plot.innerWidth / (maxPoints - 1);
4156
+ const xInset = maxPoints <= 1 ? 0 : Math.min(26, Math.max(14, plot.innerWidth * 0.06));
4157
+ const xStart = maxPoints <= 1 ? plot.x + plot.innerWidth / 2 : plot.x + xInset;
4158
+ const xSpan = maxPoints <= 1 ? 0 : Math.max(1, plot.innerWidth - xInset * 2);
4159
+ const xStep = maxPoints <= 1 ? 0 : xSpan / (maxPoints - 1);
4155
4160
  const ticks = chartTicks(domain.min, domain.max, 4);
4156
4161
  const pointFor = (value, index) => {
4157
- const x = plot.x + index * xStep;
4162
+ const x = xStart + index * xStep;
4158
4163
  const y = yInPlot(value, domain, plot);
4159
4164
  return { x, y };
4160
4165
  };
@@ -4197,7 +4202,12 @@ function LineChart({
4197
4202
  if (item.points.length === 0) return [];
4198
4203
  const color = chartColor(item.color, c, seriesIndex);
4199
4204
  const linePath = pathFor(item.points);
4200
- const areaPath = item.area && item.points.length > 1 ? `${linePath} L ${plot.x + (item.points.length - 1) * xStep} ${plot.bottom} L ${plot.x} ${plot.bottom} Z` : "";
4205
+ let areaPath = "";
4206
+ if (item.area && item.points.length > 1) {
4207
+ const firstPoint = pointFor(item.points[0], 0);
4208
+ const lastPoint = pointFor(item.points[item.points.length - 1], item.points.length - 1);
4209
+ areaPath = `${linePath} L ${lastPoint.x} ${plot.bottom} L ${firstPoint.x} ${plot.bottom} Z`;
4210
+ }
4201
4211
  const elements = [];
4202
4212
  if (areaPath) {
4203
4213
  elements.push(React.createElement("path", { key: `${item.name}-area`, d: areaPath, fill: color, opacity: 0.12 }));
@@ -4238,10 +4248,9 @@ function LineChart({
4238
4248
  fontWeight: 700,
4239
4249
  transform: "translate(-50%, -50%) rotate(-90deg)"
4240
4250
  }),
4241
- ...(labels ?? []).map((label, index, allLabels) => {
4242
- const x = plot.x + index * xStep;
4243
- const align = index === 0 ? "left" : index === allLabels.length - 1 ? "right" : "center";
4244
- return chartLabel(`line-x-${label}`, label, x, height - 14, c, { align, width: 72 });
4251
+ ...(labels ?? []).map((label, index) => {
4252
+ const x = xStart + index * xStep;
4253
+ return chartLabel(`line-x-${label}`, label, x, height - 14, c, { width: 72 });
4245
4254
  })
4246
4255
  )
4247
4256
  });
@@ -5172,10 +5181,35 @@ function sanitizeSvg(svg) {
5172
5181
  }
5173
5182
  var AUTOCROP_PADDING = 24;
5174
5183
  var CROP_THRESHOLD_PERCENT = 10;
5184
+ function replaceSvgAttribute(attrs, name, value) {
5185
+ const pattern = new RegExp(`\\s${name}="[^"]*"`);
5186
+ if (pattern.test(attrs)) return attrs.replace(pattern, ` ${name}="${value}"`);
5187
+ return `${attrs} ${name}="${value}"`;
5188
+ }
5189
+ function cropSvgViewport(svg, region) {
5190
+ const x = Math.max(0, Math.floor(region.x));
5191
+ const y = Math.max(0, Math.floor(region.y));
5192
+ const width = Math.max(1, Math.ceil(region.width));
5193
+ const height = Math.max(1, Math.ceil(region.height));
5194
+ return svg.replace(/^<svg\b([^>]*)>/, (_match, attrs) => {
5195
+ let nextAttrs = attrs;
5196
+ nextAttrs = replaceSvgAttribute(nextAttrs, "width", String(width));
5197
+ nextAttrs = replaceSvgAttribute(nextAttrs, "height", String(height));
5198
+ nextAttrs = replaceSvgAttribute(nextAttrs, "viewBox", `${x} ${y} ${width} ${height}`);
5199
+ return `<svg${nextAttrs}>`;
5200
+ });
5201
+ }
5202
+ function cropSavesEnough(source, target) {
5203
+ if (source <= 0 || target >= source) return false;
5204
+ return (source - target) / source * 100 >= CROP_THRESHOLD_PERCENT;
5205
+ }
5175
5206
  function resolveWatermark(options) {
5176
5207
  return options.watermark ?? options.brand;
5177
5208
  }
5178
5209
  async function renderToPng(element, options, createFn, theme) {
5210
+ await renderToPngWithOutput(element, options, createFn, theme);
5211
+ }
5212
+ async function renderToPngWithOutput(element, options, createFn, theme) {
5179
5213
  return withRenderContext(
5180
5214
  { background: options.background ?? "transparent" },
5181
5215
  () => renderToPngInContext(element, options, createFn, theme)
@@ -5216,7 +5250,7 @@ async function renderToPngInContext(element, options, createFn, theme) {
5216
5250
  `Canvas overflow detected (${options.width}\xD7${options.height}): ${overflow.message}`
5217
5251
  );
5218
5252
  }
5219
- const finalWidth = options.width;
5253
+ let finalWidth = options.width;
5220
5254
  let finalHeight = options.height;
5221
5255
  let finalElement = element;
5222
5256
  const heightSaved = options.height - bounds.height;
@@ -5259,6 +5293,26 @@ async function renderToPngInContext(element, options, createFn, theme) {
5259
5293
  finalSvg = await renderFinalSvg(finalElement, finalWidth, finalHeight);
5260
5294
  }
5261
5295
  }
5296
+ if (options.crop !== false) {
5297
+ const viewportCheck = new Resvg(finalSvg, {
5298
+ fitTo: { mode: "width", value: finalWidth },
5299
+ background: "rgba(0, 0, 0, 0)"
5300
+ }).render();
5301
+ const viewportPixels = new Uint8Array(viewportCheck.pixels.buffer);
5302
+ const viewportBg = detectBackgroundColor(viewportPixels);
5303
+ const viewportBounds = detectContentBounds(
5304
+ viewportPixels,
5305
+ finalWidth,
5306
+ viewportCheck.height,
5307
+ viewportBg,
5308
+ AUTOCROP_PADDING
5309
+ );
5310
+ if (cropSavesEnough(finalWidth, viewportBounds.width) || cropSavesEnough(viewportCheck.height, viewportBounds.height)) {
5311
+ finalSvg = cropSvgViewport(finalSvg, viewportBounds);
5312
+ finalWidth = viewportBounds.width;
5313
+ finalHeight = viewportBounds.height;
5314
+ }
5315
+ }
5262
5316
  const resvg = new Resvg(finalSvg, {
5263
5317
  fitTo: {
5264
5318
  mode: "width",
@@ -5270,6 +5324,7 @@ async function renderToPngInContext(element, options, createFn, theme) {
5270
5324
  const pngBuffer = pngData.asPng();
5271
5325
  await mkdir(dirname(options.outputPath), { recursive: true });
5272
5326
  await writeFile(options.outputPath, pngBuffer);
5327
+ return { width: finalWidth, height: finalHeight };
5273
5328
  }
5274
5329
  async function renderToBuffer(element, width, height, options = {}) {
5275
5330
  return withRenderContext(
@@ -5976,12 +6031,12 @@ async function renderFrameToPng(mod, theme, options) {
5976
6031
  let height = options.height;
5977
6032
  for (let attempt = 0; attempt < AUTO_SIZE_ATTEMPTS; attempt += 1) {
5978
6033
  try {
5979
- await renderToPng(frameElement(mod, theme), {
6034
+ const output = await renderToPngWithOutput(frameElement(mod, theme), {
5980
6035
  ...options,
5981
6036
  width,
5982
6037
  height
5983
6038
  }, mod.create, theme);
5984
- return { width, height };
6039
+ return { width, height, outputWidth: output.width, outputHeight: output.height };
5985
6040
  } catch (error) {
5986
6041
  const edges = overflowEdges(error);
5987
6042
  const next = edges ? nextAutoSize(width, height, mod.autoSize, edges) : void 0;
@@ -5990,7 +6045,7 @@ async function renderFrameToPng(mod, theme, options) {
5990
6045
  height = next.height;
5991
6046
  }
5992
6047
  }
5993
- return { width, height };
6048
+ return { width, height, outputWidth: width, outputHeight: height };
5994
6049
  }
5995
6050
  async function renderCommand(argv) {
5996
6051
  const args = parseRenderArgs(argv);
@@ -6007,6 +6062,8 @@ async function renderCommand(argv) {
6007
6062
  const moduleWatermark = await resolveWatermarkAssets(mod.watermark ?? mod.brand);
6008
6063
  let renderWidth = mod.width;
6009
6064
  let renderHeight = mod.height;
6065
+ let outputWidth = renderWidth;
6066
+ let outputHeight = renderHeight;
6010
6067
  for (const theme of args.themes) {
6011
6068
  const outputName = `${name}_${theme}.png`;
6012
6069
  const outputPath = join2(args.outDir, outputName);
@@ -6021,6 +6078,8 @@ async function renderCommand(argv) {
6021
6078
  });
6022
6079
  renderWidth = rendered.width;
6023
6080
  renderHeight = rendered.height;
6081
+ outputWidth = rendered.outputWidth;
6082
+ outputHeight = rendered.outputHeight;
6024
6083
  outputs.push(outputName);
6025
6084
  console.log(`rendered ${relative(process.cwd(), outputPath)}`);
6026
6085
  }
@@ -6029,6 +6088,8 @@ async function renderCommand(argv) {
6029
6088
  source: relative(process.cwd(), file),
6030
6089
  width: renderWidth,
6031
6090
  height: renderHeight,
6091
+ outputWidth,
6092
+ outputHeight,
6032
6093
  outputs
6033
6094
  });
6034
6095
  }
package/dist/index.cjs CHANGED
@@ -115,6 +115,7 @@ __export(index_exports, {
115
115
  renderAnimatedGif: () => renderAnimatedGif,
116
116
  renderToBuffer: () => renderToBuffer,
117
117
  renderToPng: () => renderToPng,
118
+ renderToPngWithOutput: () => renderToPngWithOutput,
118
119
  renderToSvg: () => renderToSvg,
119
120
  styles: () => styles,
120
121
  toneGradients: () => toneGradients,
@@ -647,6 +648,7 @@ function Panel({
647
648
  width: "100%",
648
649
  display: "flex",
649
650
  flexDirection: "column",
651
+ gap,
650
652
  ...bodyStyle
651
653
  }
652
654
  }, children),
@@ -4062,16 +4064,16 @@ function BarChart({
4062
4064
  yAxisLabel,
4063
4065
  footer
4064
4066
  }) {
4065
- const margin = { top: 18, right: 18, bottom: 40, left: yAxisLabel ? 52 : 38 };
4067
+ const margin = { top: 18, right: 38, bottom: 40, left: yAxisLabel ? 52 : 38 };
4066
4068
  const plot = createPlotArea(width, height, margin);
4067
4069
  const domain = chartDomain(data.map((item) => item.value), min, max);
4068
4070
  const ticks = chartTicks(domain.min, domain.max, 4);
4069
- const barGap = Math.max(8, plot.innerWidth / Math.max(data.length, 1) * 0.18);
4070
- const barWidth = Math.max(12, (plot.innerWidth - barGap * (data.length - 1)) / Math.max(data.length, 1));
4071
+ const barSlot = plot.innerWidth / Math.max(data.length, 1);
4072
+ const barWidth = Math.max(8, Math.min(76, barSlot * 0.72));
4071
4073
  const zeroY = yInPlot(0, domain, plot);
4072
4074
  const baselineY = clamp(zeroY, plot.y, plot.bottom);
4073
4075
  const barGeometries = data.map((item, index) => {
4074
- const x = plot.x + index * (barWidth + barGap);
4076
+ const x = plot.x + index * barSlot + (barSlot - barWidth) / 2;
4075
4077
  const valueY = yInPlot(item.value, domain, plot);
4076
4078
  const y = Math.min(valueY, baselineY);
4077
4079
  const barHeight = Math.max(4, Math.abs(baselineY - valueY));
@@ -4165,10 +4167,13 @@ function LineChart({
4165
4167
  const allValues = series.flatMap((item) => item.points);
4166
4168
  const domain = chartDomain(allValues, min, max);
4167
4169
  const maxPoints = Math.max(...series.map((item) => item.points.length), 1);
4168
- const xStep = maxPoints <= 1 ? plot.innerWidth : plot.innerWidth / (maxPoints - 1);
4170
+ const xInset = maxPoints <= 1 ? 0 : Math.min(26, Math.max(14, plot.innerWidth * 0.06));
4171
+ const xStart = maxPoints <= 1 ? plot.x + plot.innerWidth / 2 : plot.x + xInset;
4172
+ const xSpan = maxPoints <= 1 ? 0 : Math.max(1, plot.innerWidth - xInset * 2);
4173
+ const xStep = maxPoints <= 1 ? 0 : xSpan / (maxPoints - 1);
4169
4174
  const ticks = chartTicks(domain.min, domain.max, 4);
4170
4175
  const pointFor = (value, index) => {
4171
- const x = plot.x + index * xStep;
4176
+ const x = xStart + index * xStep;
4172
4177
  const y = yInPlot(value, domain, plot);
4173
4178
  return { x, y };
4174
4179
  };
@@ -4211,7 +4216,12 @@ function LineChart({
4211
4216
  if (item.points.length === 0) return [];
4212
4217
  const color = chartColor(item.color, c, seriesIndex);
4213
4218
  const linePath = pathFor(item.points);
4214
- const areaPath = item.area && item.points.length > 1 ? `${linePath} L ${plot.x + (item.points.length - 1) * xStep} ${plot.bottom} L ${plot.x} ${plot.bottom} Z` : "";
4219
+ let areaPath = "";
4220
+ if (item.area && item.points.length > 1) {
4221
+ const firstPoint = pointFor(item.points[0], 0);
4222
+ const lastPoint = pointFor(item.points[item.points.length - 1], item.points.length - 1);
4223
+ areaPath = `${linePath} L ${lastPoint.x} ${plot.bottom} L ${firstPoint.x} ${plot.bottom} Z`;
4224
+ }
4215
4225
  const elements = [];
4216
4226
  if (areaPath) {
4217
4227
  elements.push(import_react.default.createElement("path", { key: `${item.name}-area`, d: areaPath, fill: color, opacity: 0.12 }));
@@ -4252,10 +4262,9 @@ function LineChart({
4252
4262
  fontWeight: 700,
4253
4263
  transform: "translate(-50%, -50%) rotate(-90deg)"
4254
4264
  }),
4255
- ...(labels ?? []).map((label, index, allLabels) => {
4256
- const x = plot.x + index * xStep;
4257
- const align = index === 0 ? "left" : index === allLabels.length - 1 ? "right" : "center";
4258
- return chartLabel(`line-x-${label}`, label, x, height - 14, c, { align, width: 72 });
4265
+ ...(labels ?? []).map((label, index) => {
4266
+ const x = xStart + index * xStep;
4267
+ return chartLabel(`line-x-${label}`, label, x, height - 14, c, { width: 72 });
4259
4268
  })
4260
4269
  )
4261
4270
  });
@@ -5187,10 +5196,35 @@ function sanitizeSvg(svg) {
5187
5196
  }
5188
5197
  var AUTOCROP_PADDING = 24;
5189
5198
  var CROP_THRESHOLD_PERCENT = 10;
5199
+ function replaceSvgAttribute(attrs, name, value) {
5200
+ const pattern = new RegExp(`\\s${name}="[^"]*"`);
5201
+ if (pattern.test(attrs)) return attrs.replace(pattern, ` ${name}="${value}"`);
5202
+ return `${attrs} ${name}="${value}"`;
5203
+ }
5204
+ function cropSvgViewport(svg, region) {
5205
+ const x = Math.max(0, Math.floor(region.x));
5206
+ const y = Math.max(0, Math.floor(region.y));
5207
+ const width = Math.max(1, Math.ceil(region.width));
5208
+ const height = Math.max(1, Math.ceil(region.height));
5209
+ return svg.replace(/^<svg\b([^>]*)>/, (_match, attrs) => {
5210
+ let nextAttrs = attrs;
5211
+ nextAttrs = replaceSvgAttribute(nextAttrs, "width", String(width));
5212
+ nextAttrs = replaceSvgAttribute(nextAttrs, "height", String(height));
5213
+ nextAttrs = replaceSvgAttribute(nextAttrs, "viewBox", `${x} ${y} ${width} ${height}`);
5214
+ return `<svg${nextAttrs}>`;
5215
+ });
5216
+ }
5217
+ function cropSavesEnough(source, target) {
5218
+ if (source <= 0 || target >= source) return false;
5219
+ return (source - target) / source * 100 >= CROP_THRESHOLD_PERCENT;
5220
+ }
5190
5221
  function resolveWatermark(options) {
5191
5222
  return options.watermark ?? options.brand;
5192
5223
  }
5193
5224
  async function renderToPng(element, options, createFn, theme) {
5225
+ await renderToPngWithOutput(element, options, createFn, theme);
5226
+ }
5227
+ async function renderToPngWithOutput(element, options, createFn, theme) {
5194
5228
  return withRenderContext(
5195
5229
  { background: options.background ?? "transparent" },
5196
5230
  () => renderToPngInContext(element, options, createFn, theme)
@@ -5231,7 +5265,7 @@ async function renderToPngInContext(element, options, createFn, theme) {
5231
5265
  `Canvas overflow detected (${options.width}\xD7${options.height}): ${overflow.message}`
5232
5266
  );
5233
5267
  }
5234
- const finalWidth = options.width;
5268
+ let finalWidth = options.width;
5235
5269
  let finalHeight = options.height;
5236
5270
  let finalElement = element;
5237
5271
  const heightSaved = options.height - bounds.height;
@@ -5274,6 +5308,26 @@ async function renderToPngInContext(element, options, createFn, theme) {
5274
5308
  finalSvg = await renderFinalSvg(finalElement, finalWidth, finalHeight);
5275
5309
  }
5276
5310
  }
5311
+ if (options.crop !== false) {
5312
+ const viewportCheck = new import_resvg_js.Resvg(finalSvg, {
5313
+ fitTo: { mode: "width", value: finalWidth },
5314
+ background: "rgba(0, 0, 0, 0)"
5315
+ }).render();
5316
+ const viewportPixels = new Uint8Array(viewportCheck.pixels.buffer);
5317
+ const viewportBg = detectBackgroundColor(viewportPixels);
5318
+ const viewportBounds = detectContentBounds(
5319
+ viewportPixels,
5320
+ finalWidth,
5321
+ viewportCheck.height,
5322
+ viewportBg,
5323
+ AUTOCROP_PADDING
5324
+ );
5325
+ if (cropSavesEnough(finalWidth, viewportBounds.width) || cropSavesEnough(viewportCheck.height, viewportBounds.height)) {
5326
+ finalSvg = cropSvgViewport(finalSvg, viewportBounds);
5327
+ finalWidth = viewportBounds.width;
5328
+ finalHeight = viewportBounds.height;
5329
+ }
5330
+ }
5277
5331
  const resvg = new import_resvg_js.Resvg(finalSvg, {
5278
5332
  fitTo: {
5279
5333
  mode: "width",
@@ -5285,6 +5339,7 @@ async function renderToPngInContext(element, options, createFn, theme) {
5285
5339
  const pngBuffer = pngData.asPng();
5286
5340
  await (0, import_promises.mkdir)((0, import_path.dirname)(options.outputPath), { recursive: true });
5287
5341
  await (0, import_promises.writeFile)(options.outputPath, pngBuffer);
5342
+ return { width: finalWidth, height: finalHeight };
5288
5343
  }
5289
5344
  async function renderToBuffer(element, width, height, options = {}) {
5290
5345
  return withRenderContext(
@@ -5577,6 +5632,7 @@ async function renderAnimatedGif(scenes, options) {
5577
5632
  renderAnimatedGif,
5578
5633
  renderToBuffer,
5579
5634
  renderToPng,
5635
+ renderToPngWithOutput,
5580
5636
  renderToSvg,
5581
5637
  styles,
5582
5638
  toneGradients,
package/dist/index.d.cts CHANGED
@@ -1314,6 +1314,12 @@ interface RenderOptions {
1314
1314
  /** Root background for Vizmatic primitives. Defaults to alpha-transparent PNG/SVG output. */
1315
1315
  background?: RenderBackground;
1316
1316
  }
1317
+ interface RenderOutput {
1318
+ /** Final logical output width before scale is applied. */
1319
+ width: number;
1320
+ /** Final logical output height before scale is applied. */
1321
+ height: number;
1322
+ }
1317
1323
  /**
1318
1324
  * Render a JSX element to a PNG file, with auto-crop and optional watermark.
1319
1325
  *
@@ -1330,6 +1336,7 @@ interface RenderOptions {
1330
1336
  * @param theme - Theme mode for re-rendering (if createFn provided)
1331
1337
  */
1332
1338
  declare function renderToPng(element: ReactNode, options: RenderOptions, createFn?: (theme: 'dark' | 'light') => ReactNode, theme?: 'dark' | 'light'): Promise<void>;
1339
+ declare function renderToPngWithOutput(element: ReactNode, options: RenderOptions, createFn?: (theme: 'dark' | 'light') => ReactNode, theme?: 'dark' | 'light'): Promise<RenderOutput>;
1333
1340
  /**
1334
1341
  * Render a JSX element to a PNG buffer (useful for testing).
1335
1342
  */
@@ -1439,4 +1446,4 @@ interface OverflowResult {
1439
1446
  */
1440
1447
  declare function detectOverflow(pixels: Uint8Array, width: number, height: number, bgColor: string, edgeTolerance?: number, minDensity?: number, alphaThreshold?: number): OverflowResult;
1441
1448
 
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 };
1449
+ 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, type RenderOutput, 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, renderToPngWithOutput, renderToSvg, styles, toneGradients, typography, wrapWithBrand, wrapWithWatermark };
package/dist/index.d.ts CHANGED
@@ -1314,6 +1314,12 @@ interface RenderOptions {
1314
1314
  /** Root background for Vizmatic primitives. Defaults to alpha-transparent PNG/SVG output. */
1315
1315
  background?: RenderBackground;
1316
1316
  }
1317
+ interface RenderOutput {
1318
+ /** Final logical output width before scale is applied. */
1319
+ width: number;
1320
+ /** Final logical output height before scale is applied. */
1321
+ height: number;
1322
+ }
1317
1323
  /**
1318
1324
  * Render a JSX element to a PNG file, with auto-crop and optional watermark.
1319
1325
  *
@@ -1330,6 +1336,7 @@ interface RenderOptions {
1330
1336
  * @param theme - Theme mode for re-rendering (if createFn provided)
1331
1337
  */
1332
1338
  declare function renderToPng(element: ReactNode, options: RenderOptions, createFn?: (theme: 'dark' | 'light') => ReactNode, theme?: 'dark' | 'light'): Promise<void>;
1339
+ declare function renderToPngWithOutput(element: ReactNode, options: RenderOptions, createFn?: (theme: 'dark' | 'light') => ReactNode, theme?: 'dark' | 'light'): Promise<RenderOutput>;
1333
1340
  /**
1334
1341
  * Render a JSX element to a PNG buffer (useful for testing).
1335
1342
  */
@@ -1439,4 +1446,4 @@ interface OverflowResult {
1439
1446
  */
1440
1447
  declare function detectOverflow(pixels: Uint8Array, width: number, height: number, bgColor: string, edgeTolerance?: number, minDensity?: number, alphaThreshold?: number): OverflowResult;
1441
1448
 
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 };
1449
+ 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, type RenderOutput, 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, renderToPngWithOutput, renderToSvg, styles, toneGradients, typography, wrapWithBrand, wrapWithWatermark };
package/dist/index.js CHANGED
@@ -521,6 +521,7 @@ function Panel({
521
521
  width: "100%",
522
522
  display: "flex",
523
523
  flexDirection: "column",
524
+ gap,
524
525
  ...bodyStyle
525
526
  }
526
527
  }, children),
@@ -3936,16 +3937,16 @@ function BarChart({
3936
3937
  yAxisLabel,
3937
3938
  footer
3938
3939
  }) {
3939
- const margin = { top: 18, right: 18, bottom: 40, left: yAxisLabel ? 52 : 38 };
3940
+ const margin = { top: 18, right: 38, bottom: 40, left: yAxisLabel ? 52 : 38 };
3940
3941
  const plot = createPlotArea(width, height, margin);
3941
3942
  const domain = chartDomain(data.map((item) => item.value), min, max);
3942
3943
  const ticks = chartTicks(domain.min, domain.max, 4);
3943
- const barGap = Math.max(8, plot.innerWidth / Math.max(data.length, 1) * 0.18);
3944
- const barWidth = Math.max(12, (plot.innerWidth - barGap * (data.length - 1)) / Math.max(data.length, 1));
3944
+ const barSlot = plot.innerWidth / Math.max(data.length, 1);
3945
+ const barWidth = Math.max(8, Math.min(76, barSlot * 0.72));
3945
3946
  const zeroY = yInPlot(0, domain, plot);
3946
3947
  const baselineY = clamp(zeroY, plot.y, plot.bottom);
3947
3948
  const barGeometries = data.map((item, index) => {
3948
- const x = plot.x + index * (barWidth + barGap);
3949
+ const x = plot.x + index * barSlot + (barSlot - barWidth) / 2;
3949
3950
  const valueY = yInPlot(item.value, domain, plot);
3950
3951
  const y = Math.min(valueY, baselineY);
3951
3952
  const barHeight = Math.max(4, Math.abs(baselineY - valueY));
@@ -4039,10 +4040,13 @@ function LineChart({
4039
4040
  const allValues = series.flatMap((item) => item.points);
4040
4041
  const domain = chartDomain(allValues, min, max);
4041
4042
  const maxPoints = Math.max(...series.map((item) => item.points.length), 1);
4042
- const xStep = maxPoints <= 1 ? plot.innerWidth : plot.innerWidth / (maxPoints - 1);
4043
+ const xInset = maxPoints <= 1 ? 0 : Math.min(26, Math.max(14, plot.innerWidth * 0.06));
4044
+ const xStart = maxPoints <= 1 ? plot.x + plot.innerWidth / 2 : plot.x + xInset;
4045
+ const xSpan = maxPoints <= 1 ? 0 : Math.max(1, plot.innerWidth - xInset * 2);
4046
+ const xStep = maxPoints <= 1 ? 0 : xSpan / (maxPoints - 1);
4043
4047
  const ticks = chartTicks(domain.min, domain.max, 4);
4044
4048
  const pointFor = (value, index) => {
4045
- const x = plot.x + index * xStep;
4049
+ const x = xStart + index * xStep;
4046
4050
  const y = yInPlot(value, domain, plot);
4047
4051
  return { x, y };
4048
4052
  };
@@ -4085,7 +4089,12 @@ function LineChart({
4085
4089
  if (item.points.length === 0) return [];
4086
4090
  const color = chartColor(item.color, c, seriesIndex);
4087
4091
  const linePath = pathFor(item.points);
4088
- const areaPath = item.area && item.points.length > 1 ? `${linePath} L ${plot.x + (item.points.length - 1) * xStep} ${plot.bottom} L ${plot.x} ${plot.bottom} Z` : "";
4092
+ let areaPath = "";
4093
+ if (item.area && item.points.length > 1) {
4094
+ const firstPoint = pointFor(item.points[0], 0);
4095
+ const lastPoint = pointFor(item.points[item.points.length - 1], item.points.length - 1);
4096
+ areaPath = `${linePath} L ${lastPoint.x} ${plot.bottom} L ${firstPoint.x} ${plot.bottom} Z`;
4097
+ }
4089
4098
  const elements = [];
4090
4099
  if (areaPath) {
4091
4100
  elements.push(React.createElement("path", { key: `${item.name}-area`, d: areaPath, fill: color, opacity: 0.12 }));
@@ -4126,10 +4135,9 @@ function LineChart({
4126
4135
  fontWeight: 700,
4127
4136
  transform: "translate(-50%, -50%) rotate(-90deg)"
4128
4137
  }),
4129
- ...(labels ?? []).map((label, index, allLabels) => {
4130
- const x = plot.x + index * xStep;
4131
- const align = index === 0 ? "left" : index === allLabels.length - 1 ? "right" : "center";
4132
- return chartLabel(`line-x-${label}`, label, x, height - 14, c, { align, width: 72 });
4138
+ ...(labels ?? []).map((label, index) => {
4139
+ const x = xStart + index * xStep;
4140
+ return chartLabel(`line-x-${label}`, label, x, height - 14, c, { width: 72 });
4133
4141
  })
4134
4142
  )
4135
4143
  });
@@ -5060,10 +5068,35 @@ function sanitizeSvg(svg) {
5060
5068
  }
5061
5069
  var AUTOCROP_PADDING = 24;
5062
5070
  var CROP_THRESHOLD_PERCENT = 10;
5071
+ function replaceSvgAttribute(attrs, name, value) {
5072
+ const pattern = new RegExp(`\\s${name}="[^"]*"`);
5073
+ if (pattern.test(attrs)) return attrs.replace(pattern, ` ${name}="${value}"`);
5074
+ return `${attrs} ${name}="${value}"`;
5075
+ }
5076
+ function cropSvgViewport(svg, region) {
5077
+ const x = Math.max(0, Math.floor(region.x));
5078
+ const y = Math.max(0, Math.floor(region.y));
5079
+ const width = Math.max(1, Math.ceil(region.width));
5080
+ const height = Math.max(1, Math.ceil(region.height));
5081
+ return svg.replace(/^<svg\b([^>]*)>/, (_match, attrs) => {
5082
+ let nextAttrs = attrs;
5083
+ nextAttrs = replaceSvgAttribute(nextAttrs, "width", String(width));
5084
+ nextAttrs = replaceSvgAttribute(nextAttrs, "height", String(height));
5085
+ nextAttrs = replaceSvgAttribute(nextAttrs, "viewBox", `${x} ${y} ${width} ${height}`);
5086
+ return `<svg${nextAttrs}>`;
5087
+ });
5088
+ }
5089
+ function cropSavesEnough(source, target) {
5090
+ if (source <= 0 || target >= source) return false;
5091
+ return (source - target) / source * 100 >= CROP_THRESHOLD_PERCENT;
5092
+ }
5063
5093
  function resolveWatermark(options) {
5064
5094
  return options.watermark ?? options.brand;
5065
5095
  }
5066
5096
  async function renderToPng(element, options, createFn, theme) {
5097
+ await renderToPngWithOutput(element, options, createFn, theme);
5098
+ }
5099
+ async function renderToPngWithOutput(element, options, createFn, theme) {
5067
5100
  return withRenderContext(
5068
5101
  { background: options.background ?? "transparent" },
5069
5102
  () => renderToPngInContext(element, options, createFn, theme)
@@ -5104,7 +5137,7 @@ async function renderToPngInContext(element, options, createFn, theme) {
5104
5137
  `Canvas overflow detected (${options.width}\xD7${options.height}): ${overflow.message}`
5105
5138
  );
5106
5139
  }
5107
- const finalWidth = options.width;
5140
+ let finalWidth = options.width;
5108
5141
  let finalHeight = options.height;
5109
5142
  let finalElement = element;
5110
5143
  const heightSaved = options.height - bounds.height;
@@ -5147,6 +5180,26 @@ async function renderToPngInContext(element, options, createFn, theme) {
5147
5180
  finalSvg = await renderFinalSvg(finalElement, finalWidth, finalHeight);
5148
5181
  }
5149
5182
  }
5183
+ if (options.crop !== false) {
5184
+ const viewportCheck = new Resvg(finalSvg, {
5185
+ fitTo: { mode: "width", value: finalWidth },
5186
+ background: "rgba(0, 0, 0, 0)"
5187
+ }).render();
5188
+ const viewportPixels = new Uint8Array(viewportCheck.pixels.buffer);
5189
+ const viewportBg = detectBackgroundColor(viewportPixels);
5190
+ const viewportBounds = detectContentBounds(
5191
+ viewportPixels,
5192
+ finalWidth,
5193
+ viewportCheck.height,
5194
+ viewportBg,
5195
+ AUTOCROP_PADDING
5196
+ );
5197
+ if (cropSavesEnough(finalWidth, viewportBounds.width) || cropSavesEnough(viewportCheck.height, viewportBounds.height)) {
5198
+ finalSvg = cropSvgViewport(finalSvg, viewportBounds);
5199
+ finalWidth = viewportBounds.width;
5200
+ finalHeight = viewportBounds.height;
5201
+ }
5202
+ }
5150
5203
  const resvg = new Resvg(finalSvg, {
5151
5204
  fitTo: {
5152
5205
  mode: "width",
@@ -5158,6 +5211,7 @@ async function renderToPngInContext(element, options, createFn, theme) {
5158
5211
  const pngBuffer = pngData.asPng();
5159
5212
  await mkdir(dirname(options.outputPath), { recursive: true });
5160
5213
  await writeFile(options.outputPath, pngBuffer);
5214
+ return { width: finalWidth, height: finalHeight };
5161
5215
  }
5162
5216
  async function renderToBuffer(element, width, height, options = {}) {
5163
5217
  return withRenderContext(
@@ -5449,6 +5503,7 @@ export {
5449
5503
  renderAnimatedGif,
5450
5504
  renderToBuffer,
5451
5505
  renderToPng,
5506
+ renderToPngWithOutput,
5452
5507
  renderToSvg,
5453
5508
  styles,
5454
5509
  toneGradients,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "vizmatic",
3
- "version": "0.1.18",
3
+ "version": "0.1.20",
4
4
  "description": "Theme-aware visual primitives and render pipeline for AI-generated diagrams, figures, and presentation frames.",
5
5
  "type": "module",
6
6
  "license": "MIT",