UNPKG

@tanstack/charts

Version:

A chart grammar for TypeScript and JavaScript. Marks consume your data directly, channels describe visual encodings, and the engine compiles them into a renderer-neutral keyed scene. TanStack's compact scales cover common numeric and categorical mappings.

38 lines (37 loc) 1.76 kB
import { number, escapeAttribute } from "./markup-internal.js"; import { renderChartSvgWithHooks, renderSvgClip } from "./svg-renderer.js"; function renderChartSvg(scene, options) { const gradientIds = new Set(scene.gradients.map((gradient) => gradient.id)); return renderChartSvgWithHooks(scene, options, { renderDefinitions: (currentScene, idPrefix) => renderGradients(currentScene, sanitizeId(idPrefix)), renderGroup: renderSvgClip, resolvePaint: gradientIds.size ? (value, idPrefix) => { const match = /^url\(#([^)]+)\)$/.exec(value); const id = match?.[1]; return id && gradientIds.has(id) ? `url(#${scopedId(sanitizeId(idPrefix), id)})` : value; } : void 0 }); } function renderGradients(scene, idPrefix) { if (!scene.gradients.length) return ""; return `<defs data-ts-key="gradients">${scene.gradients.map( (gradient) => `<linearGradient data-ts-key="gradient:${escapeAttribute(gradient.id)}" id="${escapeAttribute(scopedId(idPrefix, gradient.id))}" x1="${percent(gradient.x1 ?? 0)}" y1="${percent(gradient.y1 ?? 1)}" x2="${percent(gradient.x2 ?? 0)}" y2="${percent(gradient.y2 ?? 0)}">${gradient.stops.map( (stop, index) => `<stop data-ts-key="gradient:${escapeAttribute(gradient.id)}:stop:${index}" offset="${percent(stop.offset)}" stop-color="${escapeAttribute(stop.color)}"${stop.opacity === void 0 ? "" : ` stop-opacity="${number(stop.opacity)}"`}/>` ).join("")}</linearGradient>` ).join("")}</defs>`; } function scopedId(prefix, id) { return prefix ? `${prefix}-${id}` : id; } function sanitizeId(value) { return value.replaceAll(/[^a-zA-Z0-9_-]/g, ""); } function percent(value) { return `${number(Math.max(0, Math.min(1, value)) * 100)}%`; } export { renderChartSvg };