@opendata-ai/openchart-engine 9.0.0 → 9.1.0

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/index.js CHANGED
@@ -1,3 +1,6 @@
1
+ // src/compile.ts
2
+ import { isRaceSpec as isRaceSpec3 } from "@opendata-ai/openchart-core";
3
+
1
4
  // src/compiler/mark-options.ts
2
5
  import { jsonPointer } from "@opendata-ai/openchart-core";
3
6
  var APPLIES_TO = {
@@ -49,6 +52,7 @@ var SHARED_OPTIONS = /* @__PURE__ */ new Set([
49
52
  function collectMarkOptionErrors(input, path = "") {
50
53
  if (!input || typeof input !== "object" || Array.isArray(input)) return [];
51
54
  const spec = input;
55
+ if (spec.type === "race") return [];
52
56
  const errors = [];
53
57
  if (spec.mark && typeof spec.mark === "object" && !Array.isArray(spec.mark)) {
54
58
  const mark = spec.mark;
@@ -573,6 +577,7 @@ function computeBarMarks(spec, scales, _chartArea, _strategy, containerWidth, th
573
577
  const categoryField = yChannel.field;
574
578
  stampBarKeys(marks, categoryField, colorField);
575
579
  applyStackSeams(marks, theme);
580
+ for (const mark of marks) mark.baseline = baseline;
576
581
  return applyMarkDefOverrides(marks, spec, bandwidth);
577
582
  }
578
583
  function stampBarKeys(marks, categoryField, colorField) {
@@ -879,17 +884,17 @@ function computeBarLabels(marks, chartArea, density = "auto", labelFormatter, la
879
884
  valuePart = options.content === "label" ? label : `${label} ${valuePart}`;
880
885
  }
881
886
  const measured = options.measureText?.(valuePart, FONT_SIZE, LABEL_FONT_WEIGHT);
882
- const textWidth = measured?.width ?? estimateTextWidth(valuePart, FONT_SIZE, LABEL_FONT_WEIGHT);
887
+ const textWidth2 = measured?.width ?? estimateTextWidth(valuePart, FONT_SIZE, LABEL_FONT_WEIGHT);
883
888
  const textHeight = Math.max(FONT_SIZE * 1.2, measured?.height ?? 0);
884
889
  const isStacked2 = mark.stackGroup !== void 0;
885
- const isInside = placement === "inside" || placement === "adaptive" && mark.width >= MIN_WIDTH_FOR_INSIDE_LABEL && textWidth <= mark.width - 2 * LABEL_PADDING;
890
+ const isInside = placement === "inside" || placement === "adaptive" && mark.width >= MIN_WIDTH_FOR_INSIDE_LABEL && textWidth2 <= mark.width - 2 * LABEL_PADDING;
886
891
  const isNegative = Number.isFinite(rawNum) ? rawNum < 0 : false;
887
892
  const bgColor = getRepresentativeColor2(mark.fill);
888
893
  let anchorX;
889
894
  let fill;
890
895
  let textAnchor;
891
896
  if (placement === "column") {
892
- anchorX = chartArea.x + chartArea.width + 12 + (options.columnWidth ?? textWidth);
897
+ anchorX = chartArea.x + chartArea.width + 12 + (options.columnWidth ?? textWidth2);
893
898
  fill = labelColor ?? bgColor;
894
899
  textAnchor = "end";
895
900
  } else if (isStacked2 && isInside) {
@@ -919,9 +924,9 @@ function computeBarLabels(marks, chartArea, density = "auto", labelFormatter, la
919
924
  }
920
925
  const centerY = mark.y + mark.height / 2;
921
926
  const anchorY = centerY - textHeight / 2;
922
- const leftEdgeX = textAnchor === "end" ? anchorX - textWidth : textAnchor === "middle" ? anchorX - textWidth / 2 : anchorX;
923
- const adaptiveOutsideFits = placement !== "adaptive" || isInside || leftEdgeX >= chartArea.x && leftEdgeX + textWidth <= chartArea.x + chartArea.width;
924
- const fits = adaptiveOutsideFits && (placement === "inside" ? textWidth <= mark.width - 2 * LABEL_PADDING && textHeight <= mark.height : !(isStacked2 && placement === "adaptive" && textWidth > mark.width - 2 * LABEL_PADDING));
927
+ const leftEdgeX = textAnchor === "end" ? anchorX - textWidth2 : textAnchor === "middle" ? anchorX - textWidth2 / 2 : anchorX;
928
+ const adaptiveOutsideFits = placement !== "adaptive" || isInside || leftEdgeX >= chartArea.x && leftEdgeX + textWidth2 <= chartArea.x + chartArea.width;
929
+ const fits = adaptiveOutsideFits && (placement === "inside" ? textWidth2 <= mark.width - 2 * LABEL_PADDING && textHeight <= mark.height : !(isStacked2 && placement === "adaptive" && textWidth2 > mark.width - 2 * LABEL_PADDING));
925
930
  haloFlags.push(!isInside);
926
931
  displayAnchorX.push(anchorX);
927
932
  fitsInSegment.push(fits);
@@ -929,7 +934,7 @@ function computeBarLabels(marks, chartArea, density = "auto", labelFormatter, la
929
934
  text: valuePart,
930
935
  anchorX: leftEdgeX,
931
936
  anchorY,
932
- width: textWidth,
937
+ width: textWidth2,
933
938
  height: textHeight,
934
939
  priority: "data",
935
940
  style: {
@@ -1552,6 +1557,7 @@ function computeCalendarMarks(spec, scales, chartArea, theme) {
1552
1557
  fill: getSequentialColor(scales, datum.value),
1553
1558
  cornerRadius: cellRadius,
1554
1559
  shapeRendering: "crispEdges",
1560
+ cell: true,
1555
1561
  data: datum.row,
1556
1562
  aria: {
1557
1563
  label: `${dateLabel}, ${colorEnc.field}: ${calendarFmt(datum.value)}`
@@ -1568,6 +1574,7 @@ function computeCalendarMarks(spec, scales, chartArea, theme) {
1568
1574
  fill: theme.colors.annotationFill,
1569
1575
  cornerRadius: cellRadius,
1570
1576
  shapeRendering: "crispEdges",
1577
+ cell: true,
1571
1578
  data: {},
1572
1579
  aria: { decorative: true }
1573
1580
  });
@@ -1692,6 +1699,7 @@ function computeColumnMarks(spec, scales, _chartArea, _strategy, theme, grouping
1692
1699
  const categoryField = xChannel.field;
1693
1700
  stampColumnKeys(marks, categoryField, colorField);
1694
1701
  applyStackSeams2(marks, theme);
1702
+ for (const mark of marks) mark.baseline = baseline;
1695
1703
  return applyMarkDefOverrides2(marks, spec, bandwidth);
1696
1704
  }
1697
1705
  function stampColumnKeys(marks, categoryField, colorField) {
@@ -1966,7 +1974,7 @@ function computeColumnLabels(marks, _chartArea, density = "auto", labelFormatter
1966
1974
  valuePart = options.content === "label" ? label : `${label} ${valuePart}`;
1967
1975
  }
1968
1976
  const measured = options.measureText?.(valuePart, FONT_SIZE, LABEL_FONT_WEIGHT2);
1969
- const textWidth = measured?.width ?? estimateTextWidth2(valuePart, FONT_SIZE, LABEL_FONT_WEIGHT2);
1977
+ const textWidth2 = measured?.width ?? estimateTextWidth2(valuePart, FONT_SIZE, LABEL_FONT_WEIGHT2);
1970
1978
  const textHeight = Math.max(FONT_SIZE * 1.2, measured?.height ?? 0);
1971
1979
  const isStacked2 = mark.stackGroup !== void 0;
1972
1980
  const anchorX = mark.x + mark.width / 2;
@@ -1981,16 +1989,16 @@ function computeColumnLabels(marks, _chartArea, density = "auto", labelFormatter
1981
1989
  fill = labelColor ?? getRepresentativeColor3(mark.fill);
1982
1990
  }
1983
1991
  fitsInSegment.push(
1984
- !(isInside && (textHeight > mark.height - 2 * LABEL_PADDING_Y || placement === "inside" && textWidth > mark.width - 4))
1992
+ !(isInside && (textHeight > mark.height - 2 * LABEL_PADDING_Y || placement === "inside" && textWidth2 > mark.width - 4))
1985
1993
  );
1986
1994
  haloFlags.push(!isInside);
1987
- const horizontalShift = placement === "adaptive" ? 0 : textWidth / 2;
1995
+ const horizontalShift = placement === "adaptive" ? 0 : textWidth2 / 2;
1988
1996
  horizontalShifts.push(horizontalShift);
1989
1997
  candidates.push({
1990
1998
  text: valuePart,
1991
1999
  anchorX: anchorX - horizontalShift,
1992
2000
  anchorY,
1993
- width: textWidth,
2001
+ width: textWidth2,
1994
2002
  height: textHeight,
1995
2003
  priority: "data",
1996
2004
  style: {
@@ -2295,13 +2303,13 @@ function computeDotLabels(marks, _chartArea, density = "auto", labelPrefix, labe
2295
2303
  }
2296
2304
  }
2297
2305
  if (labelPrefix) valuePart = labelPrefix + valuePart;
2298
- const textWidth = estimateTextWidth3(valuePart, LABEL_FONT_SIZE3, LABEL_FONT_WEIGHT3);
2306
+ const textWidth2 = estimateTextWidth3(valuePart, LABEL_FONT_SIZE3, LABEL_FONT_WEIGHT3);
2299
2307
  const textHeight = LABEL_FONT_SIZE3 * 1.2;
2300
2308
  candidates.push({
2301
2309
  text: valuePart,
2302
2310
  anchorX: mark.cx + mark.r + LABEL_OFFSET_X,
2303
2311
  anchorY: mark.cy - textHeight / 2,
2304
- width: textWidth,
2312
+ width: textWidth2,
2305
2313
  height: textHeight,
2306
2314
  priority: "data",
2307
2315
  style: {
@@ -2436,7 +2444,7 @@ var errorbarRenderer = (spec, scales, area3) => computeErrorbarMarks(spec, scale
2436
2444
  import { getRepresentativeColor as getRepresentativeColor8 } from "@opendata-ai/openchart-core";
2437
2445
 
2438
2446
  // src/charts/line/area.ts
2439
- import { getRepresentativeColor as getRepresentativeColor7, isGradientDef as isGradientDef3 } from "@opendata-ai/openchart-core";
2447
+ import { getRepresentativeColor as getRepresentativeColor7, isGradientDef as isGradientDef3, isOpaqueColor } from "@opendata-ai/openchart-core";
2440
2448
  import { area as area2, line as line3 } from "d3-shape";
2441
2449
 
2442
2450
  // src/data/area-stack.ts
@@ -2788,6 +2796,16 @@ var OVERLAP_GRADIENT_STOPS = [
2788
2796
  { offset: 1, opacity: 0 }
2789
2797
  ];
2790
2798
  var STACKED_FILL_OPACITY = 0.92;
2799
+ var MUTED_STACKED_FILL_OPACITY = 0.42;
2800
+ var MUTED_STACKED_SEAM_WIDTH = 1.5;
2801
+ var LIGHT_SEAM_FALLBACK = "#ffffff";
2802
+ var DARK_SEAM_FALLBACK = "#111827";
2803
+ function resolveMutedSeamColor(theme) {
2804
+ if (theme?.colors.background && isOpaqueColor(theme.colors.background)) {
2805
+ return theme.colors.background;
2806
+ }
2807
+ return theme?.isDark ? DARK_SEAM_FALLBACK : LIGHT_SEAM_FALLBACK;
2808
+ }
2791
2809
  function buildGradientFill(colorStr, stops) {
2792
2810
  return {
2793
2811
  gradient: "linear",
@@ -2915,9 +2933,11 @@ function computeStackedArea(spec, scales, chartArea, theme) {
2915
2933
  spec.areaStackCache
2916
2934
  );
2917
2935
  const yScale = scales.y.scale;
2936
+ const highlightSet = spec.highlight && spec.highlight.length > 0 ? new Set(spec.highlight) : null;
2918
2937
  const marks = [];
2919
2938
  for (const layer of stackedData) {
2920
2939
  const seriesKey = layer.key;
2940
+ const isMuted = highlightSet !== null && !highlightSet.has(seriesKey);
2921
2941
  const color = getColor(scales, seriesKey);
2922
2942
  const validPoints = [];
2923
2943
  const segments2 = [[]];
@@ -2963,8 +2983,11 @@ function computeStackedArea(spec, scales, chartArea, theme) {
2963
2983
  fillOpacity = isGradientDef3(markFill) ? 1 : spec.markDef.fillOpacity ?? spec.markDef.opacity ?? 0.7;
2964
2984
  } else {
2965
2985
  fillValue = getRepresentativeColor7(color);
2966
- fillOpacity = spec.markDef.fillOpacity ?? STACKED_FILL_OPACITY;
2986
+ const defaultFillOpacity = isMuted ? MUTED_STACKED_FILL_OPACITY : STACKED_FILL_OPACITY;
2987
+ fillOpacity = spec.markDef.fillOpacity ?? defaultFillOpacity;
2967
2988
  }
2989
+ const stroke = isMuted ? resolveMutedSeamColor(theme) : resolveSeriesStroke(spec, color, theme);
2990
+ const strokeWidth = isMuted ? MUTED_STACKED_SEAM_WIDTH : 1;
2968
2991
  const rawPointKeys = validPoints.map((point) => serializeKeyValue(point.xKey));
2969
2992
  marks.push({
2970
2993
  type: "area",
@@ -2977,8 +3000,8 @@ function computeStackedArea(spec, scales, chartArea, theme) {
2977
3000
  topPath: topPathStr,
2978
3001
  fill: fillValue,
2979
3002
  fillOpacity,
2980
- stroke: resolveSeriesStroke(spec, color, theme),
2981
- strokeWidth: 1,
3003
+ stroke,
3004
+ strokeWidth,
2982
3005
  seriesKey,
2983
3006
  stacked: true,
2984
3007
  stackNormalized: stackProp === "normalize",
@@ -3513,7 +3536,7 @@ function computePieLabels(marks, _chartArea, density = "auto", _textFill = "#333
3513
3536
  const rawValue = Number(rawValueText);
3514
3537
  const valueText = formatValue3 && Number.isFinite(rawValue) ? formatValue3(rawValue) : percentText;
3515
3538
  const labelText = valueText ? `${sliceName} ${valueText}` : sliceName;
3516
- const textWidth = estimateTextWidth4(labelText, LABEL_FONT_SIZE4, LABEL_FONT_WEIGHT4);
3539
+ const textWidth2 = estimateTextWidth4(labelText, LABEL_FONT_SIZE4, LABEL_FONT_WEIGHT4);
3517
3540
  const textHeight = LABEL_FONT_SIZE4 * 1.2;
3518
3541
  const midAngle = (mark.startAngle + mark.endAngle) / 2;
3519
3542
  const labelRadius = mark.outerRadius + LEADER_LINE_OFFSET;
@@ -3522,9 +3545,9 @@ function computePieLabels(marks, _chartArea, density = "auto", _textFill = "#333
3522
3545
  const isRight = Math.sin(midAngle) > 0;
3523
3546
  candidates.push({
3524
3547
  text: labelText,
3525
- anchorX: isRight ? labelX : labelX - textWidth,
3548
+ anchorX: isRight ? labelX : labelX - textWidth2,
3526
3549
  anchorY: labelY - textHeight / 2,
3527
- width: textWidth,
3550
+ width: textWidth2,
3528
3551
  height: textHeight,
3529
3552
  priority: "data",
3530
3553
  // Index into the ORIGINAL marks array, not `targetMarks`. Density
@@ -4230,22 +4253,22 @@ function rangeEndpointText(value, formatter, prefix, content, title, suffix) {
4230
4253
  }
4231
4254
  function buildCandidate(mark, text, horizontal, outerSide, index, fontFamily, measureText) {
4232
4255
  const measured = measureText?.(text, RANGE_LABEL_FONT_SIZE, RANGE_LABEL_FONT_WEIGHT);
4233
- const textWidth = measured?.width ?? estimateTextWidth6(text, RANGE_LABEL_FONT_SIZE, RANGE_LABEL_FONT_WEIGHT);
4256
+ const textWidth2 = measured?.width ?? estimateTextWidth6(text, RANGE_LABEL_FONT_SIZE, RANGE_LABEL_FONT_WEIGHT);
4234
4257
  const textHeight = Math.max(RANGE_LABEL_FONT_SIZE * 1.2, measured?.height ?? 0);
4235
4258
  let anchorX;
4236
4259
  let anchorY;
4237
4260
  if (horizontal) {
4238
- anchorX = outerSide === "min" ? mark.cx - mark.r - RANGE_LABEL_OFFSET - textWidth : mark.cx + mark.r + RANGE_LABEL_OFFSET;
4261
+ anchorX = outerSide === "min" ? mark.cx - mark.r - RANGE_LABEL_OFFSET - textWidth2 : mark.cx + mark.r + RANGE_LABEL_OFFSET;
4239
4262
  anchorY = mark.cy - textHeight / 2;
4240
4263
  } else {
4241
- anchorX = mark.cx - textWidth / 2;
4264
+ anchorX = mark.cx - textWidth2 / 2;
4242
4265
  anchorY = outerSide === "min" ? mark.cy + mark.r + RANGE_LABEL_OFFSET - textHeight / 2 : mark.cy - mark.r - RANGE_LABEL_OFFSET - textHeight / 2;
4243
4266
  }
4244
4267
  return {
4245
4268
  text,
4246
4269
  anchorX,
4247
4270
  anchorY,
4248
- width: textWidth,
4271
+ width: textWidth2,
4249
4272
  height: textHeight,
4250
4273
  priority: "data",
4251
4274
  index,
@@ -4469,6 +4492,7 @@ function computeRectMarks(spec, scales, _chartArea) {
4469
4492
  width: cellWidth,
4470
4493
  height: cellHeight,
4471
4494
  fill,
4495
+ cell: true,
4472
4496
  data: row,
4473
4497
  aria
4474
4498
  });
@@ -4977,6 +5001,7 @@ function computeWaffleMarks(spec, scales, chartArea, _strategy) {
4977
5001
  fill,
4978
5002
  cornerRadius,
4979
5003
  shapeRendering: "crispEdges",
5004
+ cell: true,
4980
5005
  data: row,
4981
5006
  aria: k === 0 ? aria : { ...aria, decorative: true }
4982
5007
  });
@@ -5096,8 +5121,8 @@ function descriptionForRows(encoding, rows, warnings, series) {
5096
5121
  }
5097
5122
  if (value == null) return void 0;
5098
5123
  if (channel.type === "temporal" || value instanceof Date) {
5099
- const format = buildTemporalFormatter(channel.format);
5100
- return format ? format(value) : formatDate2(value);
5124
+ const format2 = buildTemporalFormatter(channel.format);
5125
+ return format2 ? format2(value) : formatDate2(value);
5101
5126
  }
5102
5127
  if (typeof value === "number")
5103
5128
  return resolveFieldFormatter({
@@ -5800,6 +5825,9 @@ function expandLayerSugar(spec, warnings, inheritedData, parentEncoding) {
5800
5825
  const expandedChildren = layer.map((child) => {
5801
5826
  if (!child || typeof child !== "object" || Array.isArray(child)) return child;
5802
5827
  const childObj = child;
5828
+ if (childObj.type === "race") {
5829
+ throw new Error("Race specs cannot be layered. Render the race in its own container.");
5830
+ }
5803
5831
  if (Array.isArray(childObj.layer)) {
5804
5832
  return expandLayerSugar(childObj, warnings, layerData, mergedEncoding);
5805
5833
  }
@@ -5838,6 +5866,7 @@ function expandValueFormatSugar(spec, warnings) {
5838
5866
  }
5839
5867
  function expandSpecSugar(spec, warnings = [], checkMarkOptions = true) {
5840
5868
  if (!spec || typeof spec !== "object" || Array.isArray(spec)) return spec;
5869
+ if (spec.type === "race") return spec;
5841
5870
  const removed = collectRemovedSpecErrors(spec);
5842
5871
  if (removed.length)
5843
5872
  throw new Error(`Invalid spec:
@@ -5874,30 +5903,36 @@ function emitSpecWarnings(warnings, sink = defaultWarnSink) {
5874
5903
  }
5875
5904
 
5876
5905
  // src/compiler/animation.ts
5877
- import { FLUID_SPRING, springDuration } from "@opendata-ai/openchart-core";
5906
+ import {
5907
+ EXIT_CURVE,
5908
+ EXIT_FADE_MS,
5909
+ FLUID_SPRING,
5910
+ springDuration
5911
+ } from "@opendata-ai/openchart-core";
5912
+ import { clampStaggerDelay, MAX_TOTAL_STAGGER_MS } from "@opendata-ai/openchart-core";
5878
5913
  var ENTER_DEFAULTS = {
5879
- duration: 450,
5914
+ duration: 800,
5880
5915
  ease: "smooth",
5881
- staggerDelay: 30,
5882
- staggerOrder: "index"
5916
+ staggerDelay: 80,
5917
+ staggerOrder: "index",
5918
+ trigger: "visible"
5883
5919
  };
5884
5920
  var UPDATE_DEFAULTS = {
5885
- duration: 450,
5921
+ duration: 500,
5886
5922
  ease: "smooth",
5887
5923
  staggerDelay: 0,
5888
5924
  staggerOrder: "index"
5889
5925
  };
5890
5926
  var EXIT_DEFAULTS = {
5891
- duration: 250,
5892
- ease: "smooth",
5927
+ duration: EXIT_FADE_MS,
5928
+ ease: EXIT_CURVE,
5893
5929
  staggerDelay: 0,
5894
5930
  staggerOrder: "index"
5895
5931
  };
5896
5932
  var DEFAULT_ANNOTATION_DELAY = 150;
5897
- var MAX_TOTAL_STAGGER_MS = 300;
5898
5933
  function resolveAnimation(spec) {
5899
- if (spec === void 0 || spec === false) return void 0;
5900
- if (spec === true) {
5934
+ if (spec === false) return void 0;
5935
+ if (spec === void 0 || spec === true) {
5901
5936
  return {
5902
5937
  enter: { ...ENTER_DEFAULTS },
5903
5938
  update: { ...UPDATE_DEFAULTS },
@@ -5911,10 +5946,11 @@ function resolveAnimation(spec) {
5911
5946
  const base = (defaults) => preset === void 0 ? defaults : { ...defaults, duration: spring ? springDuration(spring) : 250, spring, staggerDelay: 0 };
5912
5947
  const enter = resolvePhase(config.enter, base(ENTER_DEFAULTS));
5913
5948
  const update = resolvePhase(config.update, base(UPDATE_DEFAULTS));
5914
- const exit = resolvePhase(
5915
- config.exit,
5916
- preset === void 0 ? EXIT_DEFAULTS : { ...EXIT_DEFAULTS, duration: 160 }
5917
- );
5949
+ const exit = resolvePhase(config.exit, EXIT_DEFAULTS);
5950
+ if (enter) {
5951
+ const authored = config.enter && typeof config.enter === "object" ? config.enter.trigger : void 0;
5952
+ enter.trigger = authored === "mount" ? "mount" : "visible";
5953
+ }
5918
5954
  if (update && config.update && typeof config.update === "object" && !Array.isArray(config.update)) {
5919
5955
  const cap = config.update.maxMarks;
5920
5956
  if (typeof cap === "number" && Number.isFinite(cap) && cap >= 1) {
@@ -5929,10 +5965,6 @@ function resolveAnimation(spec) {
5929
5965
  annotationDelay: config.annotationDelay ?? (preset === void 0 ? DEFAULT_ANNOTATION_DELAY : 0)
5930
5966
  };
5931
5967
  }
5932
- function clampStaggerDelay(delay, elementCount) {
5933
- if (elementCount <= 1) return 0;
5934
- return Math.min(delay, MAX_TOTAL_STAGGER_MS / elementCount);
5935
- }
5936
5968
  function resolvePhase(phase, defaults) {
5937
5969
  if (phase === false) return null;
5938
5970
  if (phase === void 0 || phase === true) {
@@ -5965,12 +5997,13 @@ function resolveStagger(stagger, defaults) {
5965
5997
 
5966
5998
  // src/compiler/normalize.ts
5967
5999
  import {
5968
- inferFieldType as inferFieldType2,
6000
+ inferFieldType as inferFieldType3,
5969
6001
  isBarListSpec,
5970
6002
  isChartSpec,
5971
6003
  isGeoMapSpec,
5972
6004
  isGraphSpec,
5973
6005
  isLayerSpec,
6006
+ isRaceSpec,
5974
6007
  isSankeySpec,
5975
6008
  isTableSpec,
5976
6009
  isTileMapSpec,
@@ -5978,6 +6011,72 @@ import {
5978
6011
  resolveMarkType
5979
6012
  } from "@opendata-ai/openchart-core";
5980
6013
 
6014
+ // src/race/normalize.ts
6015
+ import {
6016
+ inferFieldType as inferFieldType2
6017
+ } from "@opendata-ai/openchart-core";
6018
+ var CHROME_FIELDS = [
6019
+ "eyebrow",
6020
+ "title",
6021
+ "subtitle",
6022
+ "source",
6023
+ "byline",
6024
+ "footer",
6025
+ "brand"
6026
+ ];
6027
+ function normalizeChrome(chrome) {
6028
+ const result = {};
6029
+ for (const field of CHROME_FIELDS) {
6030
+ const value = chrome?.[field];
6031
+ if (value !== void 0) result[field] = typeof value === "string" ? { text: value } : value;
6032
+ }
6033
+ return result;
6034
+ }
6035
+ function normalizeRaceSpec(spec, warnings) {
6036
+ const { encoding, race } = spec;
6037
+ const mark = typeof spec.mark === "string" ? { type: spec.mark } : spec.mark;
6038
+ const timeType = encoding.time.type ?? inferFieldType2(spec.data, encoding.time.field);
6039
+ const autoplay = spec.animation === false ? false : race?.autoplay ?? "visible";
6040
+ const controls = race?.controls ?? true;
6041
+ const period = race?.period;
6042
+ const periodFormat = (period === false ? void 0 : period?.format) ?? encoding.time.format;
6043
+ if (!controls && autoplay !== false) {
6044
+ warnings.push(
6045
+ "Race autoplay is enabled with controls disabled. Set race.controls to true or race.autoplay to false so viewers can pause motion (WCAG 2.2.2)."
6046
+ );
6047
+ }
6048
+ return {
6049
+ ...spec,
6050
+ mark: mark.type === "line" ? { ...mark, window: mark.window ?? "reveal" } : mark.type === "bar" ? { ...mark, cornerRadius: mark.cornerRadius ?? 0 } : {
6051
+ ...mark,
6052
+ columns: mark.columns ?? ["rank", "change", "name", "bar", "value", "share"]
6053
+ },
6054
+ encoding: {
6055
+ ...encoding,
6056
+ time: { ...encoding.time, type: timeType === "nominal" ? "ordinal" : timeType },
6057
+ key: { ...encoding.key, type: encoding.key.type ?? "nominal" },
6058
+ value: { ...encoding.value, type: "quantitative" }
6059
+ },
6060
+ race: {
6061
+ top: race?.top ?? 10,
6062
+ duration: race?.duration,
6063
+ step: race?.step,
6064
+ swap: race?.swap ?? 400,
6065
+ rescale: race?.rescale ?? "frame",
6066
+ gaps: race?.gaps ?? "interpolate",
6067
+ holdEnd: race?.holdEnd ?? 1500,
6068
+ loop: race?.loop ?? false,
6069
+ autoplay,
6070
+ controls,
6071
+ period: period === false ? false : periodFormat === void 0 ? {} : { format: periodFormat },
6072
+ summary: race?.summary ?? false
6073
+ },
6074
+ chrome: normalizeChrome(spec.chrome),
6075
+ theme: spec.theme ?? {},
6076
+ watermark: spec.watermark ?? true
6077
+ };
6078
+ }
6079
+
5981
6080
  // src/tilemap/layout.ts
5982
6081
  var US_STATE_TILES = [
5983
6082
  // Row 0
@@ -6118,7 +6217,7 @@ function normalizeChromeField(value) {
6118
6217
  if (typeof value === "string") return { text: value };
6119
6218
  return value;
6120
6219
  }
6121
- function normalizeChrome(chrome) {
6220
+ function normalizeChrome2(chrome) {
6122
6221
  if (!chrome) return {};
6123
6222
  return {
6124
6223
  eyebrow: normalizeChromeField(chrome.eyebrow),
@@ -6138,13 +6237,13 @@ function inferEncodingTypes(encoding, data, warnings) {
6138
6237
  if ("condition" in spec) continue;
6139
6238
  if (!("field" in spec)) continue;
6140
6239
  if (!spec.type) {
6141
- const inferred = inferFieldType2(data, spec.field);
6240
+ const inferred = inferFieldType3(data, spec.field);
6142
6241
  result[channel] = { ...spec, type: inferred };
6143
6242
  warnings.push(
6144
6243
  `Inferred encoding.${channel}.type as "${inferred}" from data values for field "${spec.field}"`
6145
6244
  );
6146
6245
  } else {
6147
- const actualType = inferFieldType2(data, spec.field);
6246
+ const actualType = inferFieldType3(data, spec.field);
6148
6247
  if (spec.type === "nominal" && actualType === "temporal") {
6149
6248
  warnings.push(`Field "${spec.field}" looks temporal but was declared as nominal`);
6150
6249
  }
@@ -6343,7 +6442,7 @@ function normalizeChartSpec(spec, warnings) {
6343
6442
  markDef,
6344
6443
  data,
6345
6444
  encoding,
6346
- chrome: normalizeChrome(spec.chrome),
6445
+ chrome: normalizeChrome2(spec.chrome),
6347
6446
  chromeLayout: spec.chromeLayout ?? "notes",
6348
6447
  metrics: spec.metrics,
6349
6448
  seriesSearch: normalizeSeriesSearch(spec, encoding, warnings),
@@ -6387,7 +6486,7 @@ function normalizeTableSpec(spec, _warnings) {
6387
6486
  data: spec.data,
6388
6487
  columns: spec.columns,
6389
6488
  rowKey: spec.rowKey,
6390
- chrome: normalizeChrome(spec.chrome),
6489
+ chrome: normalizeChrome2(spec.chrome),
6391
6490
  theme: spec.theme ?? {},
6392
6491
  search: spec.search ?? false,
6393
6492
  pagination: spec.pagination ?? false,
@@ -6413,7 +6512,7 @@ function normalizeSankeySpec(spec, _warnings) {
6413
6512
  linkStyle: spec.linkStyle ?? "gradient",
6414
6513
  nodeLabelAlign: spec.nodeLabelAlign ?? "auto",
6415
6514
  nodeSort: spec.nodeSort,
6416
- chrome: normalizeChrome(spec.chrome),
6515
+ chrome: normalizeChrome2(spec.chrome),
6417
6516
  legend: spec.legend,
6418
6517
  theme: spec.theme ?? {},
6419
6518
  animation: spec.animation,
@@ -6432,6 +6531,12 @@ function normalizeGraphSpec(spec, warnings) {
6432
6531
  warnings.push(`seedNode "${seedNode.id}" does not match any node id; it will be ignored.`);
6433
6532
  seedNode = void 0;
6434
6533
  }
6534
+ const enter = spec.animation && typeof spec.animation === "object" ? spec.animation.enter : void 0;
6535
+ if (enter && typeof enter === "object" && enter.stagger && typeof enter.stagger === "object") {
6536
+ warnings.push(
6537
+ "Graph animation.enter.stagger only takes true or false; the object form is ignored (graphs order their reveal by layout)."
6538
+ );
6539
+ }
6435
6540
  return {
6436
6541
  type: "graph",
6437
6542
  nodes: spec.nodes,
@@ -6440,7 +6545,7 @@ function normalizeGraphSpec(spec, warnings) {
6440
6545
  layout,
6441
6546
  nodeOverrides: spec.nodeOverrides,
6442
6547
  seedNode,
6443
- chrome: normalizeChrome(spec.chrome),
6548
+ chrome: normalizeChrome2(spec.chrome),
6444
6549
  annotations: normalizeAnnotations(spec.annotations, warnings),
6445
6550
  theme: spec.theme ?? {},
6446
6551
  watermark: spec.watermark ?? true,
@@ -6494,7 +6599,7 @@ function normalizeTileMapSpec(spec, warnings) {
6494
6599
  encoding,
6495
6600
  palette: spec.palette ?? "blue",
6496
6601
  colors: spec.colors,
6497
- chrome: normalizeChrome(spec.chrome),
6602
+ chrome: normalizeChrome2(spec.chrome),
6498
6603
  legend: spec.legend,
6499
6604
  theme: spec.theme ?? {},
6500
6605
  watermark: spec.watermark ?? true,
@@ -6522,7 +6627,7 @@ function normalizeGeoMapSpec(spec, _warnings) {
6522
6627
  },
6523
6628
  data: spec.data,
6524
6629
  encoding: spec.encoding,
6525
- chrome: normalizeChrome(spec.chrome),
6630
+ chrome: normalizeChrome2(spec.chrome),
6526
6631
  legend: spec.legend,
6527
6632
  theme: spec.theme ?? {},
6528
6633
  watermark: spec.watermark ?? true,
@@ -6546,10 +6651,10 @@ function normalizeBarListSpec(spec, _warnings) {
6546
6651
  barHeight: spec.barHeight ?? 6,
6547
6652
  cornerRadius: spec.cornerRadius ?? "pill",
6548
6653
  maxItems: spec.maxItems ?? 20,
6549
- chrome: normalizeChrome(spec.chrome),
6654
+ chrome: normalizeChrome2(spec.chrome),
6550
6655
  theme: spec.theme ?? {},
6551
6656
  watermark: spec.watermark ?? true,
6552
- animation: spec.animation ?? true
6657
+ animation: spec.animation
6553
6658
  };
6554
6659
  }
6555
6660
  function normalizeSpec(spec, warnings = []) {
@@ -6563,6 +6668,9 @@ function normalizeSpec(spec, warnings = []) {
6563
6668
  "[openchart] Missing or duplicate annotation IDs use revision-local source indices; provide unique IDs for durable identity."
6564
6669
  );
6565
6670
  }
6671
+ if (isRaceSpec(spec)) {
6672
+ return normalizeRaceSpec(spec, warnings);
6673
+ }
6566
6674
  if (isLayerSpec(spec)) {
6567
6675
  const leaves = flattenLayers(spec);
6568
6676
  if (leaves.length === 0) {
@@ -6592,7 +6700,7 @@ function normalizeSpec(spec, warnings = []) {
6592
6700
  return normalizeBarListSpec(spec, warnings);
6593
6701
  }
6594
6702
  throw new Error(
6595
- `Unknown spec shape. Expected mark (chart), layer, type: 'table', type: 'graph', type: 'sankey', type: 'tilemap', type: 'map', or type: 'barlist'.`
6703
+ `Unknown spec shape. Expected mark (chart), layer, type: 'table', type: 'graph', type: 'sankey', type: 'tilemap', type: 'map', type: 'barlist', or type: 'race'.`
6596
6704
  );
6597
6705
  }
6598
6706
  function flattenLayers(spec, parentData, parentEncoding, parentTransforms, parentWatermark, parentEndpointLabels, parentFigure) {
@@ -6609,6 +6717,9 @@ function flattenLayers(spec, parentData, parentEncoding, parentTransforms, paren
6609
6717
  };
6610
6718
  const leaves = [];
6611
6719
  for (const child of spec.layer) {
6720
+ if (isRaceSpec(child)) {
6721
+ throw new Error("Race specs cannot be layered. Render the race in its own container.");
6722
+ }
6612
6723
  if (isLayerSpec(child)) {
6613
6724
  leaves.push(
6614
6725
  ...flattenLayers(
@@ -6646,7 +6757,7 @@ function flattenLayers(spec, parentData, parentEncoding, parentTransforms, paren
6646
6757
  }
6647
6758
 
6648
6759
  // src/compiler/validate.ts
6649
- import { jsonPointer as jsonPointer13, MARK_TYPES as MARK_TYPES2 } from "@opendata-ai/openchart-core";
6760
+ import { isRaceSpec as isRaceSpec2, jsonPointer as jsonPointer15, MARK_TYPES as MARK_TYPES2 } from "@opendata-ai/openchart-core";
6650
6761
 
6651
6762
  // src/compiler/validation/barlist.ts
6652
6763
  import { jsonPointer as jsonPointer3 } from "@opendata-ai/openchart-core";
@@ -6915,7 +7026,7 @@ function validateBarListSpec(spec, errors) {
6915
7026
 
6916
7027
  // src/compiler/validation/chart.ts
6917
7028
  import {
6918
- inferFieldType as inferFieldType5,
7029
+ inferFieldType as inferFieldType6,
6919
7030
  jsonPointer as jsonPointer5,
6920
7031
  MARK_ENCODING_RULES
6921
7032
  } from "@opendata-ai/openchart-core";
@@ -6946,7 +7057,7 @@ function validateFrame(spec, errors, prefix = "") {
6946
7057
  }
6947
7058
 
6948
7059
  // src/compiler/validation/label-placement.ts
6949
- import { inferFieldType as inferFieldType3 } from "@opendata-ai/openchart-core";
7060
+ import { inferFieldType as inferFieldType4 } from "@opendata-ai/openchart-core";
6950
7061
  function validateLabelPlacement(spec, errors) {
6951
7062
  const mark = typeof spec.mark === "string" ? spec.mark : spec.mark?.type;
6952
7063
  const encoding = spec.encoding ?? {};
@@ -7003,8 +7114,8 @@ function simpleColumnRows(spec) {
7003
7114
  const categoryField = category?.field;
7004
7115
  const valueField = encoding.x?.field;
7005
7116
  if (typeof categoryField !== "string" || typeof valueField !== "string") return false;
7006
- const categoryType = category.type ?? inferFieldType3(rows, categoryField);
7007
- const valueType = encoding.x.type ?? inferFieldType3(rows, valueField);
7117
+ const categoryType = category.type ?? inferFieldType4(rows, categoryField);
7118
+ const valueType = encoding.x.type ?? inferFieldType4(rows, valueField);
7008
7119
  if (!["nominal", "ordinal"].includes(String(categoryType)) || valueType !== "quantitative")
7009
7120
  return false;
7010
7121
  if (encoding.detail?.field || encoding.xOffset || encoding.yOffset || encoding.x2 || encoding.y2 || encoding.x?.stack === "normalize" || encoding.x?.stack === "center")
@@ -7038,7 +7149,7 @@ function validatePreparedLabelPlacement(spec) {
7038
7149
  }
7039
7150
 
7040
7151
  // src/compiler/validation/mark-rules.ts
7041
- import { inferFieldType as inferFieldType4, jsonPointer as jsonPointer4 } from "@opendata-ai/openchart-core";
7152
+ import { inferFieldType as inferFieldType5, jsonPointer as jsonPointer4 } from "@opendata-ai/openchart-core";
7042
7153
  var VALID_RANGE_STYLES = /* @__PURE__ */ new Set(["dumbbell", "arrow", "bar"]);
7043
7154
  function validateRangeSpec(spec, errors) {
7044
7155
  const encoding = spec.encoding;
@@ -7048,8 +7159,8 @@ function validateRangeSpec(spec, errors) {
7048
7159
  if (!x?.field || typeof x.field !== "string" || !y?.field || typeof y.field !== "string") {
7049
7160
  return;
7050
7161
  }
7051
- const xType = x.type ?? inferFieldType4(data, x.field);
7052
- const yType = y.type ?? inferFieldType4(data, y.field);
7162
+ const xType = x.type ?? inferFieldType5(data, x.field);
7163
+ const yType = y.type ?? inferFieldType5(data, y.field);
7053
7164
  const xIsCategory = xType === "nominal" || xType === "ordinal";
7054
7165
  const yIsCategory = yType === "nominal" || yType === "ordinal";
7055
7166
  if (xIsCategory && yIsCategory) {
@@ -7186,7 +7297,7 @@ function validateCalendarSpec(spec, errors) {
7186
7297
  }
7187
7298
  const x = encoding.x;
7188
7299
  if (!x?.field || typeof x.field !== "string") return;
7189
- const xType = x.type ?? inferFieldType4(data, x.field);
7300
+ const xType = x.type ?? inferFieldType5(data, x.field);
7190
7301
  if (xType !== "temporal") {
7191
7302
  if (!x.type) {
7192
7303
  errors.push({
@@ -7286,7 +7397,7 @@ function validateErrorbarSpec(spec, errors) {
7286
7397
  [end, horizontal ? "x2" : "y2"]
7287
7398
  ]) {
7288
7399
  if (typeof channel?.field !== "string") continue;
7289
- const type = channel.type ?? (data.some((row) => row[channel.field] != null) ? inferFieldType4(data, channel.field) : "quantitative");
7400
+ const type = channel.type ?? (data.some((row) => row[channel.field] != null) ? inferFieldType5(data, channel.field) : "quantitative");
7290
7401
  if (type !== "quantitative")
7291
7402
  errors.push({
7292
7403
  message: `Spec error: errorbar encoding.${name} must be quantitative`,
@@ -7296,7 +7407,7 @@ function validateErrorbarSpec(spec, errors) {
7296
7407
  });
7297
7408
  }
7298
7409
  if (typeof category?.field === "string") {
7299
- const type = category.type ?? inferFieldType4(data, category.field);
7410
+ const type = category.type ?? inferFieldType5(data, category.field);
7300
7411
  if (!["nominal", "ordinal", "temporal"].includes(String(type)))
7301
7412
  errors.push({
7302
7413
  message: "Spec error: errorbar requires a nominal, ordinal or temporal category axis",
@@ -7621,7 +7732,7 @@ function validateChartSpec(spec, errors) {
7621
7732
  suggestion: "Provide a series name (string) or an array of series names."
7622
7733
  });
7623
7734
  } else {
7624
- const colorType = colorCh.type ?? (colorCh.field && Array.isArray(spec.data) && spec.data.length > 0 ? inferFieldType5(spec.data, colorCh.field) : void 0);
7735
+ const colorType = colorCh.type ?? (colorCh.field && Array.isArray(spec.data) && spec.data.length > 0 ? inferFieldType6(spec.data, colorCh.field) : void 0);
7625
7736
  if (colorType === "quantitative") {
7626
7737
  errors.push({
7627
7738
  message: "Spec error: encoding.color.highlight is not supported on quantitative color channels",
@@ -7744,7 +7855,7 @@ function validateChartSpec(spec, errors) {
7744
7855
  const data = Array.isArray(spec.data) ? spec.data : [];
7745
7856
  const colorCh = encoding?.color;
7746
7857
  if (colorCh && typeof colorCh === "object" && typeof colorCh.field === "string") {
7747
- const colorType = colorCh.type ?? inferFieldType5(data, colorCh.field);
7858
+ const colorType = colorCh.type ?? inferFieldType6(data, colorCh.field);
7748
7859
  if (colorType !== "quantitative") {
7749
7860
  const distinct = new Set(data.map((row) => row[colorCh.field]));
7750
7861
  if (distinct.size > 1) {
@@ -7786,44 +7897,17 @@ function validateAnimation(spec, errors) {
7786
7897
  for (const phase of ["enter", "update", "exit"]) {
7787
7898
  const value = config[phase];
7788
7899
  if (!value || typeof value !== "object") continue;
7789
- const settings = value;
7790
- if (settings.spring !== void 0) {
7791
- if (settings.duration !== void 0 || settings.ease !== void 0) {
7792
- errors.push({
7793
- code: "INVALID_VALUE",
7794
- suggestion: "Use a named preset or separate valid spring and tween phase settings.",
7795
- path: jsonPointer6("animation", phase),
7796
- message: "A phase cannot combine spring with duration or ease."
7797
- });
7798
- }
7799
- if (!settings.spring || typeof settings.spring !== "object" || Array.isArray(settings.spring)) {
7800
- errors.push({
7801
- code: "INVALID_VALUE",
7802
- suggestion: "Use a named preset or separate valid spring and tween phase settings.",
7803
- path: jsonPointer6("animation", phase, "spring"),
7804
- message: "Spring must be a configuration object."
7805
- });
7806
- } else {
7807
- for (const [key, number] of Object.entries(settings.spring)) {
7808
- const known = ["stiffness", "damping", "mass"].includes(key);
7809
- if (known && number === void 0) continue;
7810
- if (!known || typeof number !== "number" || !Number.isFinite(number) || number <= 0) {
7811
- errors.push({
7812
- code: "INVALID_VALUE",
7813
- suggestion: "Use a named preset or separate valid spring and tween phase settings.",
7814
- path: jsonPointer6("animation", phase, "spring", key),
7815
- message: "Spring parameters must be finite positive stiffness, damping, or mass."
7816
- });
7817
- }
7818
- }
7819
- }
7820
- }
7821
- if (settings.duration !== void 0 && (typeof settings.duration !== "number" || !Number.isFinite(settings.duration) || settings.duration < 0)) {
7900
+ validatePhaseTiming(value, ["animation", phase], errors);
7901
+ }
7902
+ const enter = config.enter;
7903
+ if (enter && typeof enter === "object" && !Array.isArray(enter)) {
7904
+ const trigger = enter.trigger;
7905
+ if (trigger !== void 0 && trigger !== "visible" && trigger !== "mount") {
7822
7906
  errors.push({
7907
+ message: `Spec error: animation.enter.trigger must be 'visible' or 'mount', got ${JSON.stringify(trigger)}`,
7908
+ path: "/animation/enter/trigger",
7823
7909
  code: "INVALID_VALUE",
7824
- suggestion: "Use a named preset or separate valid spring and tween phase settings.",
7825
- path: jsonPointer6("animation", phase, "duration"),
7826
- message: "Animation duration must be finite and nonnegative."
7910
+ suggestion: "Use animation: { enter: { trigger: 'mount' } } to play the entrance at mount, or omit trigger to play it when the chart scrolls into view."
7827
7911
  });
7828
7912
  }
7829
7913
  }
@@ -7840,6 +7924,111 @@ function validateAnimation(spec, errors) {
7840
7924
  });
7841
7925
  }
7842
7926
  }
7927
+ var ANIMATION_EASES = ["smooth", "snappy", "gentle"];
7928
+ var TIMING_SUGGESTION = "Use a named preset or separate valid spring and tween phase settings.";
7929
+ function validatePhaseTiming(settings, path, errors) {
7930
+ if (settings.spring !== void 0) {
7931
+ if (settings.duration !== void 0 || settings.ease !== void 0) {
7932
+ errors.push({
7933
+ code: "INVALID_VALUE",
7934
+ suggestion: TIMING_SUGGESTION,
7935
+ path: jsonPointer6(...path),
7936
+ message: "A phase cannot combine spring with duration or ease."
7937
+ });
7938
+ }
7939
+ if (!settings.spring || typeof settings.spring !== "object" || Array.isArray(settings.spring)) {
7940
+ errors.push({
7941
+ code: "INVALID_VALUE",
7942
+ suggestion: TIMING_SUGGESTION,
7943
+ path: jsonPointer6(...path, "spring"),
7944
+ message: "Spring must be a configuration object."
7945
+ });
7946
+ } else {
7947
+ for (const [key, number] of Object.entries(settings.spring)) {
7948
+ const known = ["stiffness", "damping", "mass"].includes(key);
7949
+ if (known && number === void 0) continue;
7950
+ if (!known || typeof number !== "number" || !Number.isFinite(number) || number <= 0) {
7951
+ errors.push({
7952
+ code: "INVALID_VALUE",
7953
+ suggestion: TIMING_SUGGESTION,
7954
+ path: jsonPointer6(...path, "spring", key),
7955
+ message: "Spring parameters must be finite positive stiffness, damping, or mass."
7956
+ });
7957
+ }
7958
+ }
7959
+ }
7960
+ }
7961
+ validateDuration(settings.duration, path, errors);
7962
+ validateEase(settings.ease, path, errors);
7963
+ }
7964
+ function validateDuration(duration, path, errors) {
7965
+ if (duration !== void 0 && (typeof duration !== "number" || !Number.isFinite(duration) || duration < 0)) {
7966
+ errors.push({
7967
+ code: "INVALID_VALUE",
7968
+ suggestion: TIMING_SUGGESTION,
7969
+ path: jsonPointer6(...path, "duration"),
7970
+ message: "Animation duration must be finite and nonnegative."
7971
+ });
7972
+ }
7973
+ }
7974
+ function validateEase(ease, path, errors) {
7975
+ if (ease !== void 0 && !ANIMATION_EASES.includes(ease)) {
7976
+ errors.push({
7977
+ code: "INVALID_VALUE",
7978
+ suggestion: "Use ease: 'smooth', 'snappy', or 'gentle'.",
7979
+ path: jsonPointer6(...path, "ease"),
7980
+ message: `Animation ease must be 'smooth', 'snappy', or 'gentle', got ${JSON.stringify(ease)}.`
7981
+ });
7982
+ }
7983
+ }
7984
+ function validateGraphAnimation(spec, errors) {
7985
+ const animation = spec.animation;
7986
+ if (animation === void 0 || typeof animation === "boolean") return;
7987
+ if (!animation || typeof animation !== "object" || Array.isArray(animation)) {
7988
+ errors.push({
7989
+ code: "INVALID_VALUE",
7990
+ suggestion: "Use animation: false to turn graph motion off, or an object to configure phases.",
7991
+ path: "/animation",
7992
+ message: "Graph animation must be a boolean or an object."
7993
+ });
7994
+ return;
7995
+ }
7996
+ const config = animation;
7997
+ for (const phase of ["enter", "update", "exit"]) {
7998
+ const value = config[phase];
7999
+ if (!value || typeof value !== "object" || Array.isArray(value)) continue;
8000
+ const settings = value;
8001
+ validatePhaseTiming(settings, ["animation", phase], errors);
8002
+ if (phase !== "enter") continue;
8003
+ const stagger = settings.stagger;
8004
+ if (stagger !== void 0 && typeof stagger !== "boolean" && (!stagger || typeof stagger !== "object" || Array.isArray(stagger))) {
8005
+ errors.push({
8006
+ code: "INVALID_VALUE",
8007
+ suggestion: "graphs order their reveal by layout; use stagger: true or false",
8008
+ path: "/animation/enter/stagger",
8009
+ message: `Graph animation.enter.stagger must be true or false, got ${JSON.stringify(stagger)}.`
8010
+ });
8011
+ }
8012
+ const trigger = settings.trigger;
8013
+ if (trigger !== void 0 && trigger !== "visible" && trigger !== "mount") {
8014
+ errors.push({
8015
+ code: "INVALID_VALUE",
8016
+ suggestion: "Use animation: { enter: { trigger: 'mount' } } to play the reveal at mount, or omit trigger to play it when the graph scrolls into view.",
8017
+ path: "/animation/enter/trigger",
8018
+ message: `Spec error: animation.enter.trigger must be 'visible' or 'mount', got ${JSON.stringify(trigger)}`
8019
+ });
8020
+ }
8021
+ }
8022
+ for (const behavior of ["camera", "hover"]) {
8023
+ const value = config[behavior];
8024
+ if (!value || typeof value !== "object" || Array.isArray(value)) continue;
8025
+ const settings = value;
8026
+ if (!(behavior === "camera" && settings.duration === "auto")) {
8027
+ validateDuration(settings.duration, ["animation", behavior], errors);
8028
+ }
8029
+ validateEase(settings.ease, ["animation", behavior], errors);
8030
+ }
8031
+ }
7843
8032
  function validateFieldMetadata(obj, errors) {
7844
8033
  if (obj.fields === void 0) return;
7845
8034
  const fail2 = (path, message) => errors.push({
@@ -8728,6 +8917,15 @@ function validateLayerSpec(spec, errors, prefix = "") {
8728
8917
  continue;
8729
8918
  }
8730
8919
  const childObj = child;
8920
+ if (childObj.type === "race") {
8921
+ errors.push({
8922
+ code: "INVALID_VALUE",
8923
+ path: `${prefix}${jsonPointer9("layer", i, "type")}`,
8924
+ message: "Race specs cannot be layered.",
8925
+ suggestion: "Render the race in its own container."
8926
+ });
8927
+ continue;
8928
+ }
8731
8929
  const isNestedLayer = "layer" in childObj && Array.isArray(childObj.layer);
8732
8930
  const isChildChart = "mark" in childObj;
8733
8931
  if (!isNestedLayer && !isChildChart) {
@@ -8786,102 +8984,563 @@ function validateLayerSpec(spec, errors, prefix = "") {
8786
8984
  }
8787
8985
  }
8788
8986
 
8789
- // src/compiler/validation/sankey.ts
8987
+ // src/compiler/validation/race.ts
8988
+ import { jsonPointer as jsonPointer11 } from "@opendata-ai/openchart-core";
8989
+
8990
+ // src/compiler/validation/race-options.ts
8790
8991
  import { jsonPointer as jsonPointer10 } from "@opendata-ai/openchart-core";
8791
- function validateSankeySpec(spec, errors) {
8792
- if (!Array.isArray(spec.data)) {
8992
+ var RACE_OPTIONS = [
8993
+ "top",
8994
+ "duration",
8995
+ "step",
8996
+ "swap",
8997
+ "rescale",
8998
+ "gaps",
8999
+ "holdEnd",
9000
+ "loop",
9001
+ "autoplay",
9002
+ "controls",
9003
+ "period",
9004
+ "summary"
9005
+ ];
9006
+ function isRecord(value) {
9007
+ return typeof value === "object" && value !== null && !Array.isArray(value);
9008
+ }
9009
+ function isFiniteNumber(value) {
9010
+ return typeof value === "number" && Number.isFinite(value);
9011
+ }
9012
+ function checkUnknownRaceKeys(race, errors) {
9013
+ for (const option of Object.keys(race)) {
9014
+ if (RACE_OPTIONS.some((known) => known === option)) continue;
9015
+ const hint = didYouMean(option, RACE_OPTIONS);
8793
9016
  errors.push({
8794
- message: 'Spec error: sankey spec requires a "data" array',
8795
- path: "/data",
8796
- code: "INVALID_TYPE",
8797
- suggestion: 'Provide data as an array of objects, e.g. data: [{ source: "A", target: "B", value: 10 }]'
9017
+ code: "INVALID_VALUE",
9018
+ path: jsonPointer10("race", option),
9019
+ message: `Spec error: Unknown race option "${option}"`,
9020
+ suggestion: hint ? `Check the option name and keep its value.${hint}` : `Remove "${option}". Supported race options are ${RACE_OPTIONS.join(", ")}.`
8798
9021
  });
8799
- return;
8800
9022
  }
8801
- if (spec.data.length === 0) {
9023
+ }
9024
+ function checkTiming(race, errors) {
9025
+ if (race.duration !== void 0 && race.step !== void 0) {
8802
9026
  errors.push({
8803
- message: 'Spec error: "data" must be a non-empty array',
8804
- path: "/data",
8805
- code: "EMPTY_DATA",
8806
- suggestion: 'Add at least one data row, e.g. data: [{ source: "A", target: "B", value: 10 }]'
9027
+ code: "INVALID_VALUE",
9028
+ path: "/race",
9029
+ message: "Spec error: race.duration and race.step are mutually exclusive",
9030
+ suggestion: "Keep duration for the whole race or step for each period. Remove the other option."
9031
+ });
9032
+ }
9033
+ const timingErrorStart = errors.length;
9034
+ const timingExamples = { duration: 12e3, step: 700, swap: 0, holdEnd: 0 };
9035
+ for (const [option, example] of Object.entries(timingExamples)) {
9036
+ const value = race[option];
9037
+ if (value === void 0) continue;
9038
+ const allowZero = option === "swap" || option === "holdEnd";
9039
+ if (!isFiniteNumber(value) || value < 0 || value === 0 && !allowZero) {
9040
+ errors.push({
9041
+ code: "INVALID_VALUE",
9042
+ path: jsonPointer10("race", option),
9043
+ message: `Spec error: race.${option} must be a finite number ${allowZero ? "of zero or more" : "greater than zero"}`,
9044
+ suggestion: `Use ${option}: ${example} or omit the option. Times are in milliseconds.`
9045
+ });
9046
+ }
9047
+ }
9048
+ return timingErrorStart;
9049
+ }
9050
+ function checkScale(race, errors, topAt) {
9051
+ const { top, rescale, gaps } = race;
9052
+ if (top !== void 0 && (!isFiniteNumber(top) || !Number.isInteger(top) || top < 1)) {
9053
+ errors.splice(topAt, 0, {
9054
+ code: "INVALID_VALUE",
9055
+ path: "/race/top",
9056
+ message: "Spec error: race.top must be an integer of at least 1",
9057
+ suggestion: "Set race.top to the desired number of visible ranks, e.g. top: 10."
9058
+ });
9059
+ }
9060
+ if (rescale !== void 0 && rescale !== "frame" && rescale !== "fixed" && !(isRecord(rescale) && isFiniteNumber(rescale.min))) {
9061
+ errors.push({
9062
+ code: "INVALID_VALUE",
9063
+ path: "/race/rescale",
9064
+ message: 'Spec error: race.rescale must be "frame", "fixed", or an object with a finite min',
9065
+ suggestion: 'Use "frame" to follow visible values, "fixed" to keep one scale, or { min: 100 } to set a floor on the maximum.'
9066
+ });
9067
+ }
9068
+ if (gaps !== void 0 && gaps !== "interpolate" && gaps !== "hold" && gaps !== "drop") {
9069
+ errors.push({
9070
+ code: "INVALID_VALUE",
9071
+ path: "/race/gaps",
9072
+ message: 'Spec error: race.gaps must be "interpolate", "hold", or "drop"',
9073
+ suggestion: 'Use "interpolate" to fill gaps between observed periods, "hold" to carry the last value, or "drop" to leave values absent.'
9074
+ });
9075
+ }
9076
+ }
9077
+ function checkPeriod(period, errors) {
9078
+ if (period === void 0 || period === false) return;
9079
+ if (!isRecord(period)) {
9080
+ errors.push({
9081
+ code: "INVALID_VALUE",
9082
+ path: "/race/period",
9083
+ message: "Spec error: race.period must be false or an object",
9084
+ suggestion: 'Use period: false to hide the label, period: { format: "%Y" } to format it, or omit period to use the default label.'
8807
9085
  });
8808
9086
  return;
8809
9087
  }
8810
- const firstRow = spec.data[0];
8811
- if (typeof firstRow !== "object" || firstRow === null || Array.isArray(firstRow)) {
9088
+ if (period.format !== void 0 && typeof period.format !== "string") {
9089
+ errors.push({
9090
+ code: "INVALID_VALUE",
9091
+ path: "/race/period/format",
9092
+ message: "Spec error: race.period.format must be a string",
9093
+ suggestion: 'Use a format string such as format: "%Y" for temporal years or omit format.'
9094
+ });
9095
+ }
9096
+ }
9097
+ function validatePlaybackOptions(race, errors) {
9098
+ for (const option of ["loop", "controls"]) {
9099
+ if (race[option] === void 0 || typeof race[option] === "boolean") continue;
9100
+ errors.push({
9101
+ code: "INVALID_VALUE",
9102
+ path: jsonPointer10("race", option),
9103
+ message: `Spec error: race.${option} must be true or false`,
9104
+ suggestion: `Use ${option}: false to disable it or ${option}: true to enable it.`
9105
+ });
9106
+ }
9107
+ const { autoplay, summary, period } = race;
9108
+ if (autoplay !== void 0 && autoplay !== "visible" && typeof autoplay !== "boolean") {
9109
+ errors.push({
9110
+ code: "INVALID_VALUE",
9111
+ path: "/race/autoplay",
9112
+ message: 'Spec error: race.autoplay must be "visible", true, or false',
9113
+ suggestion: 'Use "visible" to start when the chart is in view, true to start immediately, or false to wait for play.'
9114
+ });
9115
+ }
9116
+ if (summary !== void 0 && summary !== "sum" && summary !== false) {
9117
+ errors.push({
9118
+ code: "INVALID_VALUE",
9119
+ path: "/race/summary",
9120
+ message: 'Spec error: race.summary must be "sum" or false',
9121
+ suggestion: 'Use "sum" to show the total for visible items or false to hide the summary.'
9122
+ });
9123
+ }
9124
+ checkPeriod(period, errors);
9125
+ }
9126
+ function validateOptions(race, errors) {
9127
+ if (race === void 0) return;
9128
+ if (!isRecord(race)) {
8812
9129
  errors.push({
8813
- message: 'Spec error: each item in "data" must be a plain object',
8814
- path: "/data/0",
8815
9130
  code: "INVALID_TYPE",
8816
- suggestion: 'Each data item should be an object, e.g. { source: "A", target: "B", value: 10 }'
9131
+ path: "/race",
9132
+ message: "Spec error: race must be an object when provided",
9133
+ suggestion: "Use race: { top: 10 } or omit race to use the defaults."
8817
9134
  });
8818
9135
  return;
8819
9136
  }
8820
- if (!spec.encoding || typeof spec.encoding !== "object") {
9137
+ checkUnknownRaceKeys(race, errors);
9138
+ const timingErrorStart = checkTiming(race, errors);
9139
+ checkScale(race, errors, timingErrorStart);
9140
+ validatePlaybackOptions(race, errors);
9141
+ }
9142
+
9143
+ // src/compiler/validation/race.ts
9144
+ var MARK_OPTIONS = {
9145
+ bar: "cornerRadius",
9146
+ line: "window",
9147
+ table: "columns"
9148
+ };
9149
+ var TABLE_COLUMNS = [
9150
+ "rank",
9151
+ "change",
9152
+ "name",
9153
+ "bar",
9154
+ "value",
9155
+ "share"
9156
+ ];
9157
+ function isRecord2(value) {
9158
+ return typeof value === "object" && value !== null && !Array.isArray(value);
9159
+ }
9160
+ function validateEncodingType(channel, type, errors) {
9161
+ if (type === void 0) return;
9162
+ if (channel === "value" && type !== "quantitative") {
8821
9163
  errors.push({
8822
- message: 'Spec error: sankey spec requires an "encoding" object with source, target, and value channels',
9164
+ code: "ENCODING_MISMATCH",
9165
+ path: "/encoding/value/type",
9166
+ message: `Spec error: encoding.value.type must be "quantitative"${typeof type === "string" ? `, received "${type}"` : ""}`,
9167
+ suggestion: 'Set encoding.value.type to "quantitative" or omit it, and rank a numeric column.'
9168
+ });
9169
+ }
9170
+ if (channel === "time" && type !== "temporal" && type !== "ordinal" && type !== "quantitative") {
9171
+ errors.push({
9172
+ code: "ENCODING_MISMATCH",
9173
+ path: "/encoding/time/type",
9174
+ message: 'Spec error: encoding.time.type must be "temporal", "ordinal", or "quantitative"',
9175
+ suggestion: 'Use "temporal" for dates or years, "ordinal" for ordered categories, or "quantitative" for numbers.'
9176
+ });
9177
+ }
9178
+ }
9179
+ function validateEncoding(encoding, errors) {
9180
+ if (!isRecord2(encoding)) {
9181
+ errors.push({
9182
+ code: encoding === void 0 ? "MISSING_FIELD" : "INVALID_TYPE",
8823
9183
  path: "/encoding",
8824
- code: "MISSING_FIELD",
8825
- suggestion: 'Add an encoding object, e.g. encoding: { source: { field: "source", type: "nominal" }, target: { field: "target", type: "nominal" }, value: { field: "value", type: "quantitative" } }'
9184
+ message: 'Spec error: a race requires an "encoding" object',
9185
+ suggestion: "Add an encoding object with time, key, and value channels that name data fields."
8826
9186
  });
8827
9187
  return;
8828
9188
  }
8829
- const encoding = spec.encoding;
8830
- const dataColumns = new Set(Object.keys(firstRow));
8831
- const columnList = [...dataColumns];
8832
- const availableColumns = columnList.join(", ");
8833
- for (const channel of ["source", "target", "value"]) {
8834
- const ch = encoding[channel];
8835
- if (!ch || typeof ch !== "object") {
8836
- errors.push({
8837
- message: `Spec error: sankey encoding requires "${channel}" channel`,
8838
- path: jsonPointer10("encoding", channel),
8839
- code: "MISSING_FIELD",
8840
- suggestion: `Add encoding.${channel} with a field from your data (${availableColumns}). Example: ${channel}: { field: "${columnList[0] ?? "myField"}", type: "${channel === "value" ? "quantitative" : "nominal"}" }`
8841
- });
8842
- continue;
8843
- }
8844
- if (!ch.field || typeof ch.field !== "string") {
9189
+ for (const [channel, example] of Object.entries({ time: "year", key: "country", value: "gdp" })) {
9190
+ const definition = encoding[channel];
9191
+ if (!isRecord2(definition)) {
8845
9192
  errors.push({
8846
- message: `Spec error: encoding.${channel} must have a "field" string`,
8847
- path: jsonPointer10("encoding", channel, "field"),
8848
- code: "MISSING_FIELD",
8849
- suggestion: `Add a field name from your data columns: ${availableColumns}`
9193
+ code: definition === void 0 ? "MISSING_FIELD" : "INVALID_TYPE",
9194
+ path: jsonPointer11("encoding", channel),
9195
+ message: definition === void 0 ? `Spec error: race encoding requires a "${channel}" channel` : `Spec error: encoding.${channel} must be an object`,
9196
+ suggestion: `Add encoding.${channel} with a field from your data, e.g. { field: "${example}" }.`
8850
9197
  });
8851
9198
  continue;
8852
9199
  }
8853
- if (!dataColumns.has(ch.field)) {
9200
+ const { field, type } = definition;
9201
+ if (typeof field !== "string" || field.trim() === "") {
8854
9202
  errors.push({
8855
- message: `Spec error: encoding.${channel}.field "${ch.field}" does not exist in data. Available columns: ${availableColumns}`,
8856
- path: jsonPointer10("encoding", channel, "field"),
8857
- code: "DATA_FIELD_MISSING",
8858
- suggestion: `Use one of the available data columns: ${availableColumns}.${didYouMean(ch.field, columnList)}`
9203
+ code: field === void 0 ? "MISSING_FIELD" : "INVALID_TYPE",
9204
+ path: jsonPointer11("encoding", channel, "field"),
9205
+ message: `Spec error: encoding.${channel} requires a non-empty "field" string`,
9206
+ suggestion: `Set encoding.${channel}.field to the name of a column in your data, e.g. "${example}".`
8859
9207
  });
8860
9208
  }
9209
+ validateEncodingType(channel, type, errors);
8861
9210
  }
8862
- checkSchemeUnused(
8863
- encoding,
8864
- errors,
8865
- "sankey node colors cycle the theme categorical palette",
8866
- "Remove scale.scheme. To customize sankey colors, set theme.colors.categorical."
8867
- );
8868
- }
8869
-
8870
- // src/compiler/validation/table.ts
8871
- import { jsonPointer as jsonPointer11 } from "@opendata-ai/openchart-core";
8872
- function validateTableSpec(spec, errors) {
8873
- if (!Array.isArray(spec.data)) {
9211
+ for (const channel of ["label", "color"]) {
9212
+ const definition = encoding[channel];
9213
+ if (definition === void 0 || isRecord2(definition)) continue;
8874
9214
  errors.push({
8875
- message: 'Spec error: "data" must be an array',
8876
- path: "/data",
8877
9215
  code: "INVALID_TYPE",
8878
- suggestion: 'Provide data as an array of objects, e.g. data: [{ name: "Alice", age: 30 }]'
9216
+ path: jsonPointer11("encoding", channel),
9217
+ message: `Spec error: encoding.${channel} must be an object`,
9218
+ suggestion: `Use a channel definition or omit encoding.${channel}.`
8879
9219
  });
8880
- return;
8881
9220
  }
8882
- if (spec.data.length === 0) {
9221
+ }
9222
+ function validateEncodingFields(encoding, data, errors) {
9223
+ if (!isRecord2(encoding) || data.length === 0) return;
9224
+ const dataColumns = /* @__PURE__ */ new Set();
9225
+ for (const row of data) {
9226
+ for (const column of Object.keys(row)) dataColumns.add(column);
9227
+ }
9228
+ const columnList = [...dataColumns];
9229
+ const availableColumns = columnList.join(", ");
9230
+ for (const channel of ["time", "key", "value", "label", "color"]) {
9231
+ const definition = encoding[channel];
9232
+ if (!isRecord2(definition)) continue;
9233
+ const { field } = definition;
9234
+ if (typeof field !== "string" || field.trim() === "" || dataColumns.has(field)) continue;
8883
9235
  errors.push({
8884
- message: 'Spec error: "data" must be a non-empty array',
9236
+ message: `Spec error: encoding.${channel}.field "${field}" does not exist in data. Available columns: ${availableColumns}`,
9237
+ path: jsonPointer11("encoding", channel, "field"),
9238
+ code: "DATA_FIELD_MISSING",
9239
+ suggestion: `Use one of the available data columns: ${availableColumns}.${didYouMean(field, columnList)}`
9240
+ });
9241
+ }
9242
+ }
9243
+ function validateTableColumns(columns, errors) {
9244
+ if (columns === void 0 || Array.isArray(columns) && columns.length > 0 && new Set(columns).size === columns.length && [...columns].every((column) => typeof column === "string" && TABLE_COLUMNS.includes(column))) {
9245
+ return;
9246
+ }
9247
+ errors.push({
9248
+ code: "INVALID_VALUE",
9249
+ path: "/mark/columns",
9250
+ message: "Spec error: mark.columns must be a non-empty array of supported table column names. Each column must be unique.",
9251
+ suggestion: 'Choose one or more distinct columns from "rank", "change", "name", "bar", "value", "share" in display order, or omit columns for the defaults.'
9252
+ });
9253
+ }
9254
+ function validateMarkOptions(type, definition, errors) {
9255
+ const { cornerRadius, window, columns } = definition;
9256
+ if (type === "bar" && cornerRadius !== void 0 && (typeof cornerRadius !== "number" || !Number.isFinite(cornerRadius) || cornerRadius < 0)) {
9257
+ errors.push({
9258
+ code: "INVALID_VALUE",
9259
+ path: "/mark/cornerRadius",
9260
+ message: "Spec error: mark.cornerRadius must be a finite, non-negative number of pixels",
9261
+ suggestion: "Use cornerRadius: 4 for rounded corners or omit it for square corners."
9262
+ });
9263
+ }
9264
+ if (type === "line" && window !== void 0 && window !== "reveal" && window !== "all") {
9265
+ errors.push({
9266
+ code: "INVALID_VALUE",
9267
+ path: "/mark/window",
9268
+ message: 'Spec error: mark.window must be "reveal" or "all"',
9269
+ suggestion: 'Use "reveal" to extend the axis to the playhead or "all" to show the full span.'
9270
+ });
9271
+ }
9272
+ if (type === "table") validateTableColumns(columns, errors);
9273
+ }
9274
+ function validateMark(mark, errors) {
9275
+ const definition = isRecord2(mark) ? mark : void 0;
9276
+ const type = definition ? definition.type : mark;
9277
+ if (type !== "bar" && type !== "line" && type !== "table") {
9278
+ errors.push({
9279
+ code: type === void 0 ? "MISSING_FIELD" : typeof type === "string" ? "INVALID_VALUE" : "INVALID_TYPE",
9280
+ path: definition ? "/mark/type" : "/mark",
9281
+ message: typeof type === "string" ? `Spec error: "${type}" is an unsupported race mark. Use "bar", "line", or "table".` : 'Spec error: a race mark must be "bar", "line", or "table"',
9282
+ suggestion: 'Use mark: "bar" for horizontal bars, or set mark.type to "bar", "line", or "table".'
9283
+ });
9284
+ return;
9285
+ }
9286
+ if (!definition) return;
9287
+ const supported = MARK_OPTIONS[type];
9288
+ for (const option of Object.keys(definition)) {
9289
+ if (option === "type" || option === supported) continue;
9290
+ errors.push({
9291
+ code: "INVALID_VALUE",
9292
+ path: jsonPointer11("mark", option),
9293
+ message: `Spec error: unknown option "${option}" on the race "${type}" mark`,
9294
+ suggestion: `Remove "${option}". The "${type}" mark supports "${supported}".${didYouMean(option, [supported])}`
9295
+ });
9296
+ }
9297
+ validateMarkOptions(type, definition, errors);
9298
+ }
9299
+ function validateData(data, errors) {
9300
+ if (!Array.isArray(data)) {
9301
+ errors.push({
9302
+ code: "INVALID_TYPE",
9303
+ path: "/data",
9304
+ message: 'Spec error: a race requires a "data" array',
9305
+ suggestion: "Provide data as an array of rows with one row per key and period."
9306
+ });
9307
+ return false;
9308
+ }
9309
+ let firstInvalidRow = -1;
9310
+ let invalidCount = 0;
9311
+ for (let index = 0; index < data.length; index++) {
9312
+ if (isRecord2(data[index])) continue;
9313
+ if (firstInvalidRow === -1) firstInvalidRow = index;
9314
+ invalidCount++;
9315
+ }
9316
+ if (firstInvalidRow === -1) return true;
9317
+ const invalidRows = invalidCount === 1 ? "is not an object" : "are not objects";
9318
+ const otherRows = invalidCount > 1 ? " and the other non-object rows" : "";
9319
+ errors.push({
9320
+ code: "INVALID_TYPE",
9321
+ path: jsonPointer11("data", firstInvalidRow),
9322
+ message: `Spec error: each race data row must be an object. ${invalidCount} of ${data.length} rows ${invalidRows}.`,
9323
+ suggestion: `Replace or remove row ${firstInvalidRow + 1}${otherRows}. Each row should name the fields used by time, key, and value.`
9324
+ });
9325
+ return false;
9326
+ }
9327
+ function validateRaceSpec(spec, errors) {
9328
+ const { data, encoding } = spec;
9329
+ const validData = validateData(data, errors);
9330
+ validateEncoding(encoding, errors);
9331
+ if (validData) validateEncodingFields(encoding, data, errors);
9332
+ validateMark(spec.mark, errors);
9333
+ validateOptions(spec.race, errors);
9334
+ if (Object.hasOwn(spec, "transform")) {
9335
+ errors.push({
9336
+ code: "INVALID_VALUE",
9337
+ path: "/transform",
9338
+ message: "Race specs don't support transform yet. Aggregate your data to one row per key and period before passing it in.",
9339
+ suggestion: "Remove transform and put the aggregated rows in data."
9340
+ });
9341
+ }
9342
+ }
9343
+
9344
+ // src/compiler/validation/sankey.ts
9345
+ import { jsonPointer as jsonPointer12 } from "@opendata-ai/openchart-core";
9346
+
9347
+ // src/sankey/overrides.ts
9348
+ import { getBreakpoint } from "@opendata-ai/openchart-core";
9349
+ var SANKEY_OVERRIDE_FIELDS = [
9350
+ "chrome",
9351
+ "other",
9352
+ "nodeSort",
9353
+ "nodeLabelAlign",
9354
+ "nodePadding"
9355
+ ];
9356
+ var SANKEY_OVERRIDE_BREAKPOINTS = ["compact", "medium"];
9357
+ var isPlainObject = (value) => !!value && typeof value === "object" && !Array.isArray(value);
9358
+ function applySankeyOverride(spec, width) {
9359
+ if (!isPlainObject(spec.overrides)) return spec;
9360
+ const breakpoint = getBreakpoint(width);
9361
+ if (breakpoint === "full") return spec;
9362
+ const block = spec.overrides[breakpoint];
9363
+ if (!isPlainObject(block)) return spec;
9364
+ const merged = { ...spec };
9365
+ for (const field of SANKEY_OVERRIDE_FIELDS) {
9366
+ if (block[field] === void 0) continue;
9367
+ merged[field] = field === "chrome" && isPlainObject(block.chrome) ? { ...isPlainObject(spec.chrome) ? spec.chrome : {}, ...block.chrome } : block[field];
9368
+ }
9369
+ return merged;
9370
+ }
9371
+
9372
+ // src/compiler/validation/sankey.ts
9373
+ function validateSankeySpec(spec, errors) {
9374
+ if (!Array.isArray(spec.data)) {
9375
+ errors.push({
9376
+ message: 'Spec error: sankey spec requires a "data" array',
9377
+ path: "/data",
9378
+ code: "INVALID_TYPE",
9379
+ suggestion: 'Provide data as an array of objects, e.g. data: [{ source: "A", target: "B", value: 10 }]'
9380
+ });
9381
+ return;
9382
+ }
9383
+ if (spec.data.length === 0) {
9384
+ errors.push({
9385
+ message: 'Spec error: "data" must be a non-empty array',
9386
+ path: "/data",
9387
+ code: "EMPTY_DATA",
9388
+ suggestion: 'Add at least one data row, e.g. data: [{ source: "A", target: "B", value: 10 }]'
9389
+ });
9390
+ return;
9391
+ }
9392
+ const firstRow = spec.data[0];
9393
+ if (typeof firstRow !== "object" || firstRow === null || Array.isArray(firstRow)) {
9394
+ errors.push({
9395
+ message: 'Spec error: each item in "data" must be a plain object',
9396
+ path: "/data/0",
9397
+ code: "INVALID_TYPE",
9398
+ suggestion: 'Each data item should be an object, e.g. { source: "A", target: "B", value: 10 }'
9399
+ });
9400
+ return;
9401
+ }
9402
+ if (!spec.encoding || typeof spec.encoding !== "object") {
9403
+ errors.push({
9404
+ message: 'Spec error: sankey spec requires an "encoding" object with source, target, and value channels',
9405
+ path: "/encoding",
9406
+ code: "MISSING_FIELD",
9407
+ suggestion: 'Add an encoding object, e.g. encoding: { source: { field: "source", type: "nominal" }, target: { field: "target", type: "nominal" }, value: { field: "value", type: "quantitative" } }'
9408
+ });
9409
+ return;
9410
+ }
9411
+ const encoding = spec.encoding;
9412
+ const dataColumns = new Set(Object.keys(firstRow));
9413
+ const columnList = [...dataColumns];
9414
+ const availableColumns = columnList.join(", ");
9415
+ for (const channel of ["source", "target", "value"]) {
9416
+ const ch = encoding[channel];
9417
+ if (!ch || typeof ch !== "object") {
9418
+ errors.push({
9419
+ message: `Spec error: sankey encoding requires "${channel}" channel`,
9420
+ path: jsonPointer12("encoding", channel),
9421
+ code: "MISSING_FIELD",
9422
+ suggestion: `Add encoding.${channel} with a field from your data (${availableColumns}). Example: ${channel}: { field: "${columnList[0] ?? "myField"}", type: "${channel === "value" ? "quantitative" : "nominal"}" }`
9423
+ });
9424
+ continue;
9425
+ }
9426
+ if (!ch.field || typeof ch.field !== "string") {
9427
+ errors.push({
9428
+ message: `Spec error: encoding.${channel} must have a "field" string`,
9429
+ path: jsonPointer12("encoding", channel, "field"),
9430
+ code: "MISSING_FIELD",
9431
+ suggestion: `Add a field name from your data columns: ${availableColumns}`
9432
+ });
9433
+ continue;
9434
+ }
9435
+ if (!dataColumns.has(ch.field)) {
9436
+ errors.push({
9437
+ message: `Spec error: encoding.${channel}.field "${ch.field}" does not exist in data. Available columns: ${availableColumns}`,
9438
+ path: jsonPointer12("encoding", channel, "field"),
9439
+ code: "DATA_FIELD_MISSING",
9440
+ suggestion: `Use one of the available data columns: ${availableColumns}.${didYouMean(ch.field, columnList)}`
9441
+ });
9442
+ }
9443
+ }
9444
+ checkSchemeUnused(
9445
+ encoding,
9446
+ errors,
9447
+ "sankey node colors cycle the theme categorical palette",
9448
+ "Remove scale.scheme. To customize sankey colors, set theme.colors.categorical."
9449
+ );
9450
+ validateSankeyOverrides(spec.overrides, errors);
9451
+ }
9452
+ function validateSankeyOverrides(overrides, errors) {
9453
+ if (overrides === void 0) return;
9454
+ if (!isPlainObject2(overrides)) {
9455
+ errors.push({
9456
+ message: 'Spec error: sankey "overrides" must be an object keyed by breakpoint',
9457
+ path: "/overrides",
9458
+ code: "INVALID_TYPE",
9459
+ suggestion: "Use overrides: { compact: { other: 0.05 } }. Valid breakpoints: compact, medium."
9460
+ });
9461
+ return;
9462
+ }
9463
+ const breakpoints = SANKEY_OVERRIDE_BREAKPOINTS;
9464
+ for (const [breakpoint, block] of Object.entries(overrides)) {
9465
+ if (!breakpoints.includes(breakpoint)) {
9466
+ errors.push({
9467
+ message: `Spec error: sankey overrides has unknown breakpoint "${breakpoint}"`,
9468
+ path: jsonPointer12("overrides", breakpoint),
9469
+ code: "INVALID_VALUE",
9470
+ suggestion: `Valid breakpoints: compact (under 400px), medium (400 to 700px).${didYouMean(breakpoint, [...breakpoints])}`
9471
+ });
9472
+ continue;
9473
+ }
9474
+ if (!isPlainObject2(block)) {
9475
+ errors.push({
9476
+ message: `Spec error: overrides.${breakpoint} must be an object`,
9477
+ path: jsonPointer12("overrides", breakpoint),
9478
+ code: "INVALID_TYPE",
9479
+ suggestion: `Use overrides.${breakpoint}: { other: 0.05 }`
9480
+ });
9481
+ continue;
9482
+ }
9483
+ validateOverrideBlock(breakpoint, block, errors);
9484
+ }
9485
+ }
9486
+ var isPlainObject2 = (value) => !!value && typeof value === "object" && !Array.isArray(value);
9487
+ var LABEL_ALIGNS = ["auto", "left", "right"];
9488
+ var OVERRIDE_FIELD_CHECKS = {
9489
+ chrome: (value) => isPlainObject2(value) ? null : "must be a chrome object",
9490
+ other: (value) => {
9491
+ const threshold = isPlainObject2(value) ? value.threshold : value;
9492
+ if (typeof threshold !== "number" || !(threshold > 0 && threshold < 1)) {
9493
+ return "must be a share between 0 and 1, or { threshold, label }";
9494
+ }
9495
+ if (isPlainObject2(value) && value.label !== void 0 && typeof value.label !== "string") {
9496
+ return "label must be a string";
9497
+ }
9498
+ return null;
9499
+ },
9500
+ nodeSort: (value) => Array.isArray(value) && value.every((id) => typeof id === "string") ? null : "must be an array of node ids",
9501
+ nodeLabelAlign: (value) => typeof value === "string" && LABEL_ALIGNS.includes(value) ? null : 'must be "auto", "left" or "right"',
9502
+ nodePadding: (value) => typeof value === "number" && Number.isFinite(value) && value >= 0 ? null : "must be a number of pixels, 0 or more"
9503
+ };
9504
+ function validateOverrideBlock(breakpoint, block, errors) {
9505
+ const fields = SANKEY_OVERRIDE_FIELDS;
9506
+ for (const [field, value] of Object.entries(block)) {
9507
+ const path = jsonPointer12("overrides", breakpoint, field);
9508
+ if (!fields.includes(field)) {
9509
+ errors.push({
9510
+ message: `Spec error: overrides.${breakpoint} cannot set "${field}"`,
9511
+ path,
9512
+ code: "INVALID_VALUE",
9513
+ suggestion: `A sankey override may set ${fields.join(", ")}.${didYouMean(field, [...fields])}`
9514
+ });
9515
+ continue;
9516
+ }
9517
+ const problem = OVERRIDE_FIELD_CHECKS[field](value);
9518
+ if (problem) {
9519
+ errors.push({
9520
+ message: `Spec error: overrides.${breakpoint}.${field} ${problem}, got ${JSON.stringify(value)}`,
9521
+ path,
9522
+ code: "INVALID_TYPE",
9523
+ suggestion: `Fix overrides.${breakpoint}.${field}, or remove it to keep the top-level value.`
9524
+ });
9525
+ }
9526
+ }
9527
+ }
9528
+
9529
+ // src/compiler/validation/table.ts
9530
+ import { jsonPointer as jsonPointer13 } from "@opendata-ai/openchart-core";
9531
+ function validateTableSpec(spec, errors) {
9532
+ if (!Array.isArray(spec.data)) {
9533
+ errors.push({
9534
+ message: 'Spec error: "data" must be an array',
9535
+ path: "/data",
9536
+ code: "INVALID_TYPE",
9537
+ suggestion: 'Provide data as an array of objects, e.g. data: [{ name: "Alice", age: 30 }]'
9538
+ });
9539
+ return;
9540
+ }
9541
+ if (spec.data.length === 0) {
9542
+ errors.push({
9543
+ message: 'Spec error: "data" must be a non-empty array',
8885
9544
  path: "/data",
8886
9545
  code: "EMPTY_DATA",
8887
9546
  suggestion: "Add at least one data row to the data array"
@@ -8917,7 +9576,7 @@ function validateTableSpec(spec, errors) {
8917
9576
  if (!col || typeof col !== "object") {
8918
9577
  errors.push({
8919
9578
  message: `Spec error: columns[${i}] must be an object`,
8920
- path: jsonPointer11("columns", i),
9579
+ path: jsonPointer13("columns", i),
8921
9580
  code: "INVALID_TYPE",
8922
9581
  suggestion: 'Each column entry should be an object, e.g. { key: "fieldName" }'
8923
9582
  });
@@ -8926,7 +9585,7 @@ function validateTableSpec(spec, errors) {
8926
9585
  if (!col.key || typeof col.key !== "string") {
8927
9586
  errors.push({
8928
9587
  message: `Spec error: columns[${i}] must have a "key" string`,
8929
- path: jsonPointer11("columns", i, "key"),
9588
+ path: jsonPointer13("columns", i, "key"),
8930
9589
  code: "MISSING_FIELD",
8931
9590
  suggestion: `Add a key referencing a data field. Available columns: ${availableColumns}`
8932
9591
  });
@@ -8935,7 +9594,7 @@ function validateTableSpec(spec, errors) {
8935
9594
  if (!dataColumns.has(col.key)) {
8936
9595
  errors.push({
8937
9596
  message: `Spec error: columns[${i}].key "${col.key}" does not exist in data. Available columns: ${availableColumns}`,
8938
- path: jsonPointer11("columns", i, "key"),
9597
+ path: jsonPointer13("columns", i, "key"),
8939
9598
  code: "DATA_FIELD_MISSING",
8940
9599
  suggestion: `Use one of the available data columns: ${availableColumns}.${didYouMean(col.key, columnList)}`
8941
9600
  });
@@ -8946,7 +9605,7 @@ function validateTableSpec(spec, errors) {
8946
9605
  if (visuals.length > 1) {
8947
9606
  errors.push({
8948
9607
  message: `Spec error: columns[${i}] has multiple visual features (${visuals.join(", ")}). Only one is allowed per column.`,
8949
- path: jsonPointer11("columns", i),
9608
+ path: jsonPointer13("columns", i),
8950
9609
  code: "INVALID_VALUE",
8951
9610
  suggestion: `Keep only one visual feature per column. Remove all but one of: ${visuals.join(", ")}`
8952
9611
  });
@@ -8955,7 +9614,7 @@ function validateTableSpec(spec, errors) {
8955
9614
  }
8956
9615
 
8957
9616
  // src/compiler/validation/tilemap.ts
8958
- import { jsonPointer as jsonPointer12 } from "@opendata-ai/openchart-core";
9617
+ import { jsonPointer as jsonPointer14 } from "@opendata-ai/openchart-core";
8959
9618
  function validateTileMapSpec(spec, errors) {
8960
9619
  if (!spec.data || typeof spec.data !== "object") {
8961
9620
  errors.push({
@@ -9013,7 +9672,7 @@ function validateTileMapSpec(spec, errors) {
9013
9672
  if (!ch || typeof ch !== "object") {
9014
9673
  errors.push({
9015
9674
  message: `Spec error: tilemap encoding requires "${channel}" channel`,
9016
- path: jsonPointer12("encoding", channel),
9675
+ path: jsonPointer14("encoding", channel),
9017
9676
  code: "MISSING_FIELD",
9018
9677
  suggestion: `Add encoding.${channel} with a field from your data (${availableColumns}). Example: ${channel}: { field: "${columnList[0] ?? "myField"}", type: "${channel === "value" ? "quantitative" : "nominal"}" }`
9019
9678
  });
@@ -9022,7 +9681,7 @@ function validateTileMapSpec(spec, errors) {
9022
9681
  if (!ch.field || typeof ch.field !== "string") {
9023
9682
  errors.push({
9024
9683
  message: `Spec error: encoding.${channel} must have a "field" string`,
9025
- path: jsonPointer12("encoding", channel, "field"),
9684
+ path: jsonPointer14("encoding", channel, "field"),
9026
9685
  code: "MISSING_FIELD",
9027
9686
  suggestion: `Add a field name from your data columns: ${availableColumns}`
9028
9687
  });
@@ -9031,7 +9690,7 @@ function validateTileMapSpec(spec, errors) {
9031
9690
  if (!dataColumns.has(ch.field)) {
9032
9691
  errors.push({
9033
9692
  message: `Spec error: encoding.${channel}.field "${ch.field}" does not exist in data. Available columns: ${availableColumns}`,
9034
- path: jsonPointer12("encoding", channel, "field"),
9693
+ path: jsonPointer14("encoding", channel, "field"),
9035
9694
  code: "DATA_FIELD_MISSING",
9036
9695
  suggestion: `Use one of the available data columns: ${availableColumns}.${didYouMean(ch.field, columnList)}`
9037
9696
  });
@@ -9068,7 +9727,7 @@ function validateAnnotationLayout(spec, errors, prefix = "") {
9068
9727
  if (typeof value !== "number" || !Number.isFinite(value) || value <= 0)
9069
9728
  errors.push({
9070
9729
  code: "INVALID_VALUE",
9071
- path: `${prefix}${jsonPointer13("annotations", index, field)}`,
9730
+ path: `${prefix}${jsonPointer15("annotations", index, field)}`,
9072
9731
  message: `${field} must be a positive finite number`,
9073
9732
  suggestion: field === "maxWidth" ? "Use null for unlimited width." : "Omit subtitleFontSize to use the default ratio."
9074
9733
  });
@@ -9076,7 +9735,7 @@ function validateAnnotationLayout(spec, errors, prefix = "") {
9076
9735
  if (annotation?.labelPlacement !== void 0 && !["auto", "start", "end", "outside"].includes(annotation.labelPlacement))
9077
9736
  errors.push({
9078
9737
  code: "INVALID_VALUE",
9079
- path: `${prefix}${jsonPointer13("annotations", index, "labelPlacement")}`,
9738
+ path: `${prefix}${jsonPointer15("annotations", index, "labelPlacement")}`,
9080
9739
  message: "Unknown reference label placement",
9081
9740
  suggestion: "Use auto, start, end or outside."
9082
9741
  });
@@ -9084,7 +9743,7 @@ function validateAnnotationLayout(spec, errors, prefix = "") {
9084
9743
  if (bend !== void 0 && (typeof bend !== "number" || !Number.isFinite(bend) || bend < -1 || bend > 1)) {
9085
9744
  errors.push({
9086
9745
  code: "INVALID_VALUE",
9087
- path: `${prefix}${jsonPointer13("annotations", index, "connector", "bend")}`,
9746
+ path: `${prefix}${jsonPointer15("annotations", index, "connector", "bend")}`,
9088
9747
  message: "Connector bend must be a finite number between -1 and 1",
9089
9748
  suggestion: "Omit bend for the automatic curve, or use a number in [-1, 1]."
9090
9749
  });
@@ -9132,7 +9791,7 @@ function validateSpecShape(spec) {
9132
9791
  if (value === void 0) continue;
9133
9792
  if (typeof value !== "string" && (!value || typeof value !== "object" || Array.isArray(value) || typeof value.text !== "string")) {
9134
9793
  errors.push({
9135
- path: jsonPointer13("chrome", key),
9794
+ path: jsonPointer15("chrome", key),
9136
9795
  code: "INVALID_TYPE",
9137
9796
  message: `${key} must be text or an object with a string text property.`,
9138
9797
  suggestion: "Preserve authored styling in the object and provide text as a string."
@@ -9149,9 +9808,10 @@ function validateSpecShape(spec) {
9149
9808
  const isTileMap = obj.type === "tilemap";
9150
9809
  const isMap = obj.type === "map";
9151
9810
  const isBarList = obj.type === "barlist";
9152
- const isLayer = hasLayer && !isTable && !isGraph && !isSankey && !isTileMap && !isMap && !isBarList;
9153
- const isChart = hasMark && !hasLayer && !isTable && !isGraph && !isSankey && !isTileMap && !isMap && !isBarList;
9154
- if (!isChart && !isTable && !isGraph && !isSankey && !isTileMap && !isMap && !isBarList && !isLayer) {
9811
+ const isRace = obj.type === "race";
9812
+ const isLayer = hasLayer && !isTable && !isGraph && !isSankey && !isTileMap && !isMap && !isBarList && !isRace;
9813
+ const isChart = hasMark && !hasLayer && !isTable && !isGraph && !isSankey && !isTileMap && !isMap && !isBarList && !isRace;
9814
+ if (!isChart && !isTable && !isGraph && !isSankey && !isTileMap && !isMap && !isBarList && !isRace && !isLayer) {
9155
9815
  if ("hconcat" in obj || "vconcat" in obj) {
9156
9816
  const key = "hconcat" in obj ? "hconcat" : "vconcat";
9157
9817
  return {
@@ -9159,7 +9819,7 @@ function validateSpecShape(spec) {
9159
9819
  errors: [
9160
9820
  {
9161
9821
  message: `Spec error: "${key}" composition is not supported`,
9162
- path: jsonPointer13(key),
9822
+ path: jsonPointer15(key),
9163
9823
  code: "INVALID_VALUE",
9164
9824
  suggestion: "Render each chart in its own container instead. For small multiples of the same chart, use the facet encoding channel: encoding.facet = { field, type }"
9165
9825
  }
@@ -9185,10 +9845,10 @@ function validateSpecShape(spec) {
9185
9845
  valid: false,
9186
9846
  errors: [
9187
9847
  {
9188
- message: 'Spec error: spec must have a "mark" field for charts, a "layer" array for layered charts, or a "type" field for tables/graphs/sankey/tilemap/map/barlist',
9848
+ message: 'Spec error: spec must have a "mark" field for charts, a "layer" array for layered charts, or a "type" field for tables/graphs/sankey/tilemap/map/barlist/race',
9189
9849
  path: "/mark",
9190
9850
  code: "MISSING_FIELD",
9191
- suggestion: `Add a "mark" field for charts (e.g. mark: "bar"), a "layer" array for layered charts, or a "type" field (type: "table", type: "graph", type: "sankey", type: "tilemap", type: "map", or type: "barlist"). Valid mark types: ${[...MARK_TYPES2].join(", ")}`
9851
+ suggestion: `Add a "mark" field for charts (e.g. mark: "bar"), a "layer" array for layered charts, or a "type" field (type: "table", type: "graph", type: "sankey", type: "tilemap", type: "map", type: "barlist", or type: "race"). Valid mark types: ${[...MARK_TYPES2].join(", ")}`
9192
9852
  }
9193
9853
  ],
9194
9854
  normalized: null
@@ -9232,8 +9892,12 @@ function validateSpecShape(spec) {
9232
9892
  validateGeoMapSpec(obj, errors);
9233
9893
  } else if (isBarList) {
9234
9894
  validateBarListSpec(obj, errors);
9895
+ } else if (isRace) {
9896
+ validateRaceSpec(obj, errors);
9235
9897
  }
9236
- if (!isGraph) {
9898
+ if (isGraph) {
9899
+ validateGraphAnimation(obj, errors);
9900
+ } else {
9237
9901
  validateAnimation(obj, errors);
9238
9902
  }
9239
9903
  if (errors.length > 0) {
@@ -9247,6 +9911,7 @@ function validateSpecShape(spec) {
9247
9911
  }
9248
9912
  function validateSpec(spec) {
9249
9913
  const result = validateSpecShape(spec);
9914
+ if (isRaceSpec2(spec)) return result;
9250
9915
  const errors = collectMarkOptionErrors(spec);
9251
9916
  return errors.length ? { ...result, valid: false, errors: [...result.errors, ...errors], normalized: null } : result;
9252
9917
  }
@@ -9475,6 +10140,7 @@ function compileBarList(spec, options) {
9475
10140
  const subtitleColor = options.darkMode ? "rgba(255,255,255,0.5)" : "rgba(0,0,0,0.45)";
9476
10141
  const valueColor = options.darkMode ? "rgba(255,255,255,0.6)" : "rgba(0,0,0,0.55)";
9477
10142
  const rows = [];
10143
+ const rowKeys = dedupeKeys(validRows.map((row) => serializeKeyValue(row[labelField])));
9478
10144
  for (let i = 0; i < validRows.length; i++) {
9479
10145
  const row = validRows[i];
9480
10146
  const value = Number(row[valueField]);
@@ -9555,6 +10221,7 @@ function compileBarList(spec, options) {
9555
10221
  };
9556
10222
  const rowMark = {
9557
10223
  type: "barlist-row",
10224
+ key: rowKeys[i],
9558
10225
  markType: "bar",
9559
10226
  fullLabel: labelText,
9560
10227
  identity: identityForRows(
@@ -12260,7 +12927,7 @@ function planBarLabels(spec, _theme, options) {
12260
12927
  if (!channel || !("field" in channel)) return empty;
12261
12928
  const field = channel.field;
12262
12929
  const values = spec.data.map((row) => finiteNumber(row[field])).filter((value) => value !== void 0);
12263
- const format = resolveFieldFormatter({
12930
+ const format2 = resolveFieldFormatter({
12264
12931
  surfaceFormat: spec.labels.format,
12265
12932
  channelFormat: "format" in channel ? channel.format : void 0,
12266
12933
  values
@@ -12274,7 +12941,7 @@ function planBarLabels(spec, _theme, options) {
12274
12941
  let positive = false;
12275
12942
  for (const value of values) {
12276
12943
  const number = Number(value);
12277
- const text = `${spec.labels.prefix ?? ""}${format(number)}${spec.labels.suffix ?? ""}`;
12944
+ const text = `${spec.labels.prefix ?? ""}${format2(number)}${spec.labels.suffix ?? ""}`;
12278
12945
  const measured = options.measureText?.(text, fontSize, 600) ?? {
12279
12946
  width: estimateTextWidth9(text, fontSize, 600),
12280
12947
  height: fontSize * 1.2
@@ -12339,7 +13006,7 @@ function emitValueLabelDiagnostic(plan, options) {
12339
13006
  }
12340
13007
 
12341
13008
  // src/compiler/a11y-warnings.ts
12342
- import { contrastRatio, findAccessibleColor, isOpaqueColor } from "@opendata-ai/openchart-core";
13009
+ import { contrastRatio, findAccessibleColor, isOpaqueColor as isOpaqueColor2 } from "@opendata-ai/openchart-core";
12343
13010
 
12344
13011
  // src/legend/suppression.ts
12345
13012
  function legendShownExplicitly(spec) {
@@ -12443,7 +13110,7 @@ var fmt = (ratio) => `${ratio.toFixed(2)}:1`;
12443
13110
  function collectContrastWarnings(scales, markType, theme) {
12444
13111
  const warnings = [];
12445
13112
  const bg = theme.colors.background;
12446
- const bgIsCheckable = isOpaqueColor(bg);
13113
+ const bgIsCheckable = isOpaqueColor2(bg);
12447
13114
  const series = [];
12448
13115
  if (scales.color && scales.color.type === "ordinal") {
12449
13116
  const ordinal = scales.color.scale;
@@ -12496,6 +13163,8 @@ function seriesIdentificationWarnings(spec) {
12496
13163
  const hidden = spec.endpointLabels === false || typeof spec.endpointLabels === "object" && spec.endpointLabels.show === false;
12497
13164
  const field = seriesField(spec);
12498
13165
  if (!hidden || !field) return [];
13166
+ const facetField = spec.encoding.facet?.field ?? spec.encoding.row?.field ?? spec.encoding.column?.field;
13167
+ if (facetField === field) return [];
12499
13168
  return new Set(spec.data.map((row) => row[field])).size > 1 ? [
12500
13169
  "[openchart a11y] Both legend and endpointLabels are disabled on a multi-series chart. Enable either to identify the series."
12501
13170
  ] : [];
@@ -12533,7 +13202,7 @@ function describeRefusal(markType, display, faceted, layered) {
12533
13202
  }
12534
13203
 
12535
13204
  // src/design/diagnostics.ts
12536
- import { computeLabelBounds, contrastRatio as contrastRatio2, isOpaqueColor as isOpaqueColor2 } from "@opendata-ai/openchart-core";
13205
+ import { computeLabelBounds, contrastRatio as contrastRatio2, isOpaqueColor as isOpaqueColor3 } from "@opendata-ai/openchart-core";
12537
13206
 
12538
13207
  // src/charts/range/label-plan.ts
12539
13208
  import { estimateTextWidth as estimateTextWidth10 } from "@opendata-ai/openchart-core";
@@ -12542,7 +13211,7 @@ function rangeLabelReserve(spec, measureText) {
12542
13211
  return 0;
12543
13212
  const start = spec.encoding.x, end = spec.encoding.x2;
12544
13213
  if (!start || !end) return 0;
12545
- const format = resolveFieldFormatter({
13214
+ const format2 = resolveFieldFormatter({
12546
13215
  surfaceFormat: spec.labels.format,
12547
13216
  channelFormat: start.format,
12548
13217
  values: spec.data.flatMap((row) => [row[start.field], row[end.field]])
@@ -12554,7 +13223,7 @@ function rangeLabelReserve(spec, measureText) {
12554
13223
  if (!Number.isFinite(value)) continue;
12555
13224
  const text = rangeEndpointText(
12556
13225
  value,
12557
- format,
13226
+ format2,
12558
13227
  spec.labels.prefix,
12559
13228
  spec.labels.content,
12560
13229
  channel.title ?? channel.field,
@@ -14510,6 +15179,10 @@ var MIN_TICK_COUNT = 2;
14510
15179
  function measureLabel(text, fontSize, fontWeight, measureText) {
14511
15180
  return measureText ? measureText(text, fontSize, fontWeight).width : estimateTextWidth16(text, fontSize, fontWeight);
14512
15181
  }
15182
+ function tickLabelsOverlap(a, b, fontSize) {
15183
+ const gap = fontSize * MIN_TICK_GAP_FACTOR;
15184
+ return a.left < b.right + gap && a.right > b.left - gap;
15185
+ }
14513
15186
  function ticksOverlap(ticks, fontSize, fontWeight, measureText, orientation = "horizontal") {
14514
15187
  if (ticks.length < 2) return false;
14515
15188
  const minGap = fontSize * MIN_TICK_GAP_FACTOR;
@@ -14526,9 +15199,14 @@ function ticksOverlap(ticks, fontSize, fontWeight, measureText, orientation = "h
14526
15199
  for (let i = 0; i < ticks.length - 1; i++) {
14527
15200
  const aWidth = measureLabel(ticks[i].label, fontSize, fontWeight, measureText);
14528
15201
  const bWidth = measureLabel(ticks[i + 1].label, fontSize, fontWeight, measureText);
14529
- const aRight = ticks[i].position + aWidth / 2;
14530
- const bLeft = ticks[i + 1].position - bWidth / 2;
14531
- if (aRight + minGap > bLeft) return true;
15202
+ const a = ticks[i].position;
15203
+ const b = ticks[i + 1].position;
15204
+ if (tickLabelsOverlap(
15205
+ { left: a - aWidth / 2, right: a + aWidth / 2 },
15206
+ { left: b - bWidth / 2, right: b + bWidth / 2 },
15207
+ fontSize
15208
+ ))
15209
+ return true;
14532
15210
  }
14533
15211
  return false;
14534
15212
  }
@@ -15796,7 +16474,7 @@ function diagnoseChart(spec, layout) {
15796
16474
  );
15797
16475
  }
15798
16476
  const background = layout.theme.colors.background;
15799
- if (!isOpaqueColor2(background)) {
16477
+ if (!isOpaqueColor3(background)) {
15800
16478
  emit(
15801
16479
  "contrast.unknown-background",
15802
16480
  "/theme/colors/background",
@@ -16956,7 +17634,7 @@ function noteBandHeight(noteLines, summaryLines, theme) {
16956
17634
  return computeNoteBandHeight(noteLines + summaryLines, theme);
16957
17635
  }
16958
17636
  function measureAuthoredReserves(spec, width, theme, measureText, opts) {
16959
- const noteLines = spec.autoThin ? annotationNoteCapacity(spec.annotations, width, theme, measureText, opts.compactNotes) : 0;
17637
+ const noteLines = spec.autoThin && opts.reserveNotes ? annotationNoteCapacity(spec.annotations, width, theme, measureText, opts.compactNotes) : 0;
16960
17638
  const summaryLines = opts.summaryLines ?? 0;
16961
17639
  const measure = annotationMeasureFn(measureText);
16962
17640
  const referenceAt = (containerWidth) => referenceLabelReserve(spec.annotations, containerWidth, measure, theme.fonts.sizes.small);
@@ -18113,7 +18791,7 @@ function applySparklineLabelDefault(chartSpec) {
18113
18791
  function resolveChartAnimation(rawSpec, bp, chartSpec) {
18114
18792
  let rawAnimationSpec = bp?.animation ?? rawSpec.animation;
18115
18793
  if (rawAnimationSpec === void 0 && chartSpec.display === "sparkline") {
18116
- rawAnimationSpec = false;
18794
+ rawAnimationSpec = true;
18117
18795
  }
18118
18796
  if (chartSpec.display === "sparkline" && rawAnimationSpec !== false && rawAnimationSpec !== void 0) {
18119
18797
  if (rawAnimationSpec === true) {
@@ -18337,11 +19015,13 @@ function isCompactContainer(options) {
18337
19015
  }
18338
19016
  function heightContextResolver(params) {
18339
19017
  const { options, breakpoint, chartSpec, theme, annotationsInline, watermarkAt } = params;
19018
+ const reserveNotes = options.stableNoteBand === true || !outsideBudget(resolveChromeLayout(chartSpec, options), "notes");
18340
19019
  return (height) => {
18341
19020
  const sized = height === options.height ? options : { ...options, height };
18342
19021
  const base = getLayoutStrategy(breakpoint, getHeightClass4(height));
18343
19022
  const reserves = measureAuthoredReserves(chartSpec, sized.width, theme, sized.measureText, {
18344
- compactNotes: isCompactContainer(sized) && chartSpec.compactAnnotationLimit != null
19023
+ compactNotes: isCompactContainer(sized) && chartSpec.compactAnnotationLimit != null,
19024
+ reserveNotes
18345
19025
  });
18346
19026
  return {
18347
19027
  options: sized,
@@ -18358,8 +19038,16 @@ function compileFaceted(chartSpec, renderSpec, facetChannel, facetDirection, the
18358
19038
  const measure = createMeasureFn(initial.options.measureText);
18359
19039
  const panelEncoding = { ...renderSpec.encoding };
18360
19040
  delete panelEncoding.facet;
18361
- const panelSpec = { ...renderSpec, encoding: panelEncoding };
18362
- const panelChartSpec = { ...chartSpec, encoding: panelEncoding };
19041
+ const panelSpec = {
19042
+ ...renderSpec,
19043
+ encoding: panelEncoding,
19044
+ endpointLabels: false
19045
+ };
19046
+ const panelChartSpec = {
19047
+ ...chartSpec,
19048
+ encoding: panelEncoding,
19049
+ endpointLabels: false
19050
+ };
18363
19051
  let figureSpec = renderSpec.labels.placement ? { ...panelSpec, labels: { ...panelSpec.labels, placement: void 0 } } : panelSpec;
18364
19052
  const hasAxisHeader = isYAxisHeader(panelEncoding.y);
18365
19053
  if (hasAxisHeader && figureSpec.encoding.y?.axis) {
@@ -18712,7 +19400,7 @@ function compileFaceted(chartSpec, renderSpec, facetChannel, facetDirection, the
18712
19400
  }
18713
19401
 
18714
19402
  // src/compile/prepare.ts
18715
- import { getBreakpoint, resolveChromeEconomy } from "@opendata-ai/openchart-core";
19403
+ import { getBreakpoint as getBreakpoint2, resolveChromeEconomy } from "@opendata-ai/openchart-core";
18716
19404
 
18717
19405
  // src/transforms/bin.ts
18718
19406
  function computeStep(extent3, maxbins, nice) {
@@ -19457,7 +20145,7 @@ function prepareChartSpec(spec, optionsInput) {
19457
20145
  if (rawTransforms && rawTransforms.length > 0) {
19458
20146
  chartSpec = { ...chartSpec, data: runTransforms(chartSpec.data, rawTransforms) };
19459
20147
  }
19460
- const breakpoint = getBreakpoint(options.width);
20148
+ const breakpoint = getBreakpoint2(options.width);
19461
20149
  const economy = resolveChromeEconomy(options.width, options.height);
19462
20150
  const overrides = rawSpec.overrides;
19463
20151
  const bp = overrides?.[breakpoint];
@@ -21105,7 +21793,7 @@ import {
21105
21793
  computeChrome as computeChrome4,
21106
21794
  estimateTextWidth as estimateTextWidth25,
21107
21795
  formatNumber as formatNumber4,
21108
- getBreakpoint as getBreakpoint2,
21796
+ getBreakpoint as getBreakpoint3,
21109
21797
  HPAD_COMPACT_FRACTION as HPAD_COMPACT_FRACTION3,
21110
21798
  HPAD_COMPACT_MIN as HPAD_COMPACT_MIN3,
21111
21799
  mergeThemeConfig as mergeThemeConfig4,
@@ -21519,14 +22207,14 @@ function formatLocale(locale2) {
21519
22207
  utcFormats.c = newFormat(locale_dateTime, utcFormats);
21520
22208
  function newFormat(specifier, formats2) {
21521
22209
  return function(date) {
21522
- var string = [], i = -1, j = 0, n = specifier.length, c, pad2, format;
22210
+ var string = [], i = -1, j = 0, n = specifier.length, c, pad2, format2;
21523
22211
  if (!(date instanceof Date)) date = /* @__PURE__ */ new Date(+date);
21524
22212
  while (++i < n) {
21525
22213
  if (specifier.charCodeAt(i) === 37) {
21526
22214
  string.push(specifier.slice(j, i));
21527
22215
  if ((pad2 = pads[c = specifier.charAt(++i)]) != null) c = specifier.charAt(++i);
21528
22216
  else pad2 = c === "e" ? " " : "0";
21529
- if (format = formats2[c]) c = format(date, pad2);
22217
+ if (format2 = formats2[c]) c = format2(date, pad2);
21530
22218
  string.push(c);
21531
22219
  j = i + 1;
21532
22220
  }
@@ -23088,7 +23776,7 @@ function textBlock(text, subtitle, width, style, measure) {
23088
23776
  return { lines, width: Math.ceil(measuredWidth), height: Math.ceil(y) };
23089
23777
  }
23090
23778
  function fieldText(channel, rows) {
23091
- const format = channel.type === "quantitative" ? resolveFieldFormatter({
23779
+ const format2 = channel.type === "quantitative" ? resolveFieldFormatter({
23092
23780
  channelFormat: channel.format,
23093
23781
  values: rows.map((row) => row[channel.field])
23094
23782
  }) : void 0;
@@ -23097,7 +23785,7 @@ function fieldText(channel, rows) {
23097
23785
  if (value === null || value === void 0) return void 0;
23098
23786
  if (channel.type === "quantitative") {
23099
23787
  const number = finiteNumber(value);
23100
- return number === void 0 ? void 0 : format(number);
23788
+ return number === void 0 ? void 0 : format2(number);
23101
23789
  }
23102
23790
  if (channel.type === "temporal") {
23103
23791
  const date = value instanceof Date ? value : new Date(value);
@@ -23125,9 +23813,9 @@ function prepareGeoLabels(spec, features, joined, theme, measure, width) {
23125
23813
  ...feature.properties,
23126
23814
  ...joined.get(feature.id)
23127
23815
  }));
23128
- const format = fieldText(spec.encoding.text, contexts);
23816
+ const format2 = fieldText(spec.encoding.text, contexts);
23129
23817
  for (const [index, feature] of features.entries()) {
23130
- const text = format(contexts[index]);
23818
+ const text = format2(contexts[index]);
23131
23819
  if (text === void 0) continue;
23132
23820
  const id = String(feature.id);
23133
23821
  candidates.push({
@@ -23145,9 +23833,9 @@ function prepareGeoLabels(spec, features, joined, theme, measure, width) {
23145
23833
  }
23146
23834
  if (spec.points?.text) {
23147
23835
  const points = spec.points;
23148
- const format = fieldText(points.text, points.data);
23836
+ const format2 = fieldText(points.text, points.data);
23149
23837
  for (const row of points.data) {
23150
- const text = format(row);
23838
+ const text = format2(row);
23151
23839
  if (text === void 0) continue;
23152
23840
  const id = row[points.key.field];
23153
23841
  const priority = points.textPriority ?? points.size;
@@ -23288,23 +23976,23 @@ function compilePreparedGeoLabels(prepared, features, projection, points, area3,
23288
23976
  }
23289
23977
 
23290
23978
  // src/geo/legend-semantics.ts
23291
- function classIntervalText(scale, index, format) {
23979
+ function classIntervalText(scale, index, format2) {
23292
23980
  const lower = index > 0 ? scale.breaks[index - 1] : void 0;
23293
23981
  const upper = scale.breaks[index];
23294
23982
  if (lower === void 0 && upper === void 0) return "All finite values";
23295
- if (lower === void 0) return `Less than ${format(upper)}`;
23296
- if (upper === void 0) return `${format(lower)} or greater`;
23297
- return `${format(lower)} inclusive to ${format(upper)} exclusive`;
23983
+ if (lower === void 0) return `Less than ${format2(upper)}`;
23984
+ if (upper === void 0) return `${format2(lower)} or greater`;
23985
+ return `${format2(lower)} inclusive to ${format2(upper)} exclusive`;
23298
23986
  }
23299
23987
  function mapLegendCaptionCandidate(channel, metadata) {
23300
- const format = channel.format;
23301
- const formatUnit = typeof format === "string" ? format.includes("%") ? "%" : format.includes("$") ? "$" : void 0 : void 0;
23988
+ const format2 = channel.format;
23989
+ const formatUnit = typeof format2 === "string" ? format2.includes("%") ? "%" : format2.includes("$") ? "$" : void 0 : void 0;
23302
23990
  return {
23303
23991
  title: channel.title ?? metadata?.label ?? channel.field,
23304
23992
  unit: metadata?.unit ?? formatUnit
23305
23993
  };
23306
23994
  }
23307
- function mapNeutralClassContext(scale, format, neutralColors) {
23995
+ function mapNeutralClassContext(scale, format2, neutralColors) {
23308
23996
  if (scale.colors.length % 2 !== 1) return void 0;
23309
23997
  const index = Math.floor(scale.colors.length / 2);
23310
23998
  if (scale.binIndex(0) !== index || index === 0 || !neutralColors.some((color) => color.toLowerCase() === scale.colors[index].toLowerCase()))
@@ -23312,7 +24000,7 @@ function mapNeutralClassContext(scale, format, neutralColors) {
23312
24000
  const lower = scale.breaks[index - 1];
23313
24001
  const upper = scale.breaks[index];
23314
24002
  if (!(lower < 0 && upper > 0)) return void 0;
23315
- return { index, label: format(0), caption: `Near zero: ${format(lower)} to <${format(upper)}` };
24003
+ return { index, label: format2(0), caption: `Near zero: ${format2(lower)} to <${format2(upper)}` };
23316
24004
  }
23317
24005
 
23318
24006
  // src/geo/view-geometry.ts
@@ -23640,10 +24328,10 @@ function collectCategories(rows, field, domain) {
23640
24328
  function legendTitleFor(colorEncoding) {
23641
24329
  const base = colorEncoding.title ?? colorEncoding.field;
23642
24330
  if (!base) return void 0;
23643
- const format = colorEncoding.format;
23644
- if (typeof format === "string") {
23645
- if (format.includes("%")) return `${base} (%)`;
23646
- if (format.includes("$")) return `${base} ($)`;
24331
+ const format2 = colorEncoding.format;
24332
+ if (typeof format2 === "string") {
24333
+ if (format2.includes("%")) return `${base} (%)`;
24334
+ if (format2.includes("$")) return `${base} ($)`;
23647
24335
  }
23648
24336
  return base;
23649
24337
  }
@@ -23705,7 +24393,7 @@ function compileGeoMapImpl(spec, options) {
23705
24393
  theme = adaptTheme3(theme);
23706
24394
  }
23707
24395
  const isDarkMode = options.darkMode;
23708
- const padding = getBreakpoint2(options.width) === "compact" ? Math.max(HPAD_COMPACT_MIN3, Math.round(theme.spacing.padding * HPAD_COMPACT_FRACTION3)) : theme.spacing.padding;
24396
+ const padding = getBreakpoint3(options.width) === "compact" ? Math.max(HPAD_COMPACT_MIN3, Math.round(theme.spacing.padding * HPAD_COMPACT_FRACTION3)) : theme.spacing.padding;
23709
24397
  const chrome = computeChrome4(
23710
24398
  mapSpec.chrome,
23711
24399
  theme,
@@ -23924,12 +24612,12 @@ function compileGeoMapImpl(spec, options) {
23924
24612
  const labels2 = {};
23925
24613
  let lines = 1, width = 0;
23926
24614
  if (mapSpec.colorKey?.activeValue && channel) {
23927
- const format = buildD3Formatter2(channel.format) ?? formatNumber4;
24615
+ const format2 = buildD3Formatter2(channel.format) ?? formatNumber4;
23928
24616
  const domain = channel.scale?.domain;
23929
24617
  const clamp2 = channel.scale?.type !== "threshold" && channel.scale?.type !== "quantile" && Array.isArray(domain) && domain.length === 2 && domain.every((value) => typeof value === "number" && Number.isFinite(value)) ? domain : void 0;
23930
24618
  for (const raw of [void 0, ...rows.map((row) => row[channel.field])]) {
23931
24619
  const value = finiteNumber(raw);
23932
- const exact = raw == null || channel.type === "quantitative" && value === void 0 ? "No data" : channel.type === "quantitative" ? format(value) : raw === "" ? "(empty)" : String(raw);
24620
+ const exact = raw == null || channel.type === "quantitative" && value === void 0 ? "No data" : channel.type === "quantitative" ? format2(value) : raw === "" ? "(empty)" : String(raw);
23933
24621
  const outside = value !== void 0 && clamp2 && (value < clamp2[0] || value > clamp2[1]);
23934
24622
  const text = `A: ${exact}${outside ? " \xB7 outside displayed range" : ""}`;
23935
24623
  const plan = measureGeoKeyText(
@@ -24075,16 +24763,16 @@ function compileGeoMapImpl(spec, options) {
24075
24763
  )
24076
24764
  );
24077
24765
  const pointFormatter = buildD3Formatter2(pointColor?.format) ?? formatNumber4;
24078
- const sideRangeLabel = (scale, index, format) => {
24766
+ const sideRangeLabel = (scale, index, format2) => {
24079
24767
  const lo = index ? scale.breaks[index - 1] : void 0;
24080
24768
  const hi = scale.breaks[index];
24081
- return lo === void 0 ? hi === void 0 ? "All finite values" : `< ${format(hi)}` : hi === void 0 ? `\u2265 ${format(lo)}` : `${format(lo)} \u2013 < ${format(hi)}`;
24769
+ return lo === void 0 ? hi === void 0 ? "All finite values" : `< ${format2(hi)}` : hi === void 0 ? `\u2265 ${format2(lo)}` : `${format2(lo)} \u2013 < ${format2(hi)}`;
24082
24770
  };
24083
24771
  const sideRangeRowHeight = Math.max(14, Math.ceil(sideLabelStyle.fontSize * 1.3)) + 6;
24084
- const rangeWidth = (scale, format) => scale ? Math.max(
24772
+ const rangeWidth = (scale, format2) => scale ? Math.max(
24085
24773
  ...scale.colors.map(
24086
24774
  (_, index) => 22 + measureSideText(
24087
- sideRangeLabel(scale, index, format),
24775
+ sideRangeLabel(scale, index, format2),
24088
24776
  sideLabelStyle.fontSize,
24089
24777
  sideLabelStyle.fontWeight
24090
24778
  ).width
@@ -24910,7 +25598,7 @@ function compileGeoMapImpl(spec, options) {
24910
25598
  }
24911
25599
  if (key.type === "continuous") {
24912
25600
  const scale = key === continuousLegend ? classScale : pointClassScale;
24913
- const format = key === continuousLegend ? formatter : pointFormatter;
25601
+ const format2 = key === continuousLegend ? formatter : pointFormatter;
24914
25602
  const headerHeight = key === continuousLegend ? titleHeight : pointTitleHeight;
24915
25603
  key.bounds.width = sideWidth;
24916
25604
  key.rangeEntries = key.bins.map((_, index) => ({
@@ -24940,7 +25628,7 @@ function compileGeoMapImpl(spec, options) {
24940
25628
  for (const entry of key.rangeEntries)
24941
25629
  if (scale)
24942
25630
  key.textRows.push({
24943
- text: sideRangeLabel(scale, entry.index, format),
25631
+ text: sideRangeLabel(scale, entry.index, format2),
24944
25632
  x: entry.bounds.x + 22,
24945
25633
  y: entry.bounds.y + sideLabelStyle.fontSize,
24946
25634
  style: sideLabelStyle,
@@ -25673,11 +26361,13 @@ import {
25673
26361
  } from "@opendata-ai/openchart-core";
25674
26362
 
25675
26363
  // src/graphs/animation.ts
26364
+ import { springDuration as springDuration2 } from "@opendata-ai/openchart-core";
25676
26365
  var ENTER_DEFAULT = {
25677
26366
  duration: 500,
25678
26367
  ease: "smooth",
25679
26368
  stagger: true,
25680
- cameraFit: true
26369
+ cameraFit: true,
26370
+ trigger: "visible"
25681
26371
  };
25682
26372
  var UPDATE_DEFAULT = { duration: 300, ease: "smooth" };
25683
26373
  var EXIT_DEFAULT = { duration: 300, ease: "smooth" };
@@ -25697,8 +26387,8 @@ function resolveGraphAnimation(spec) {
25697
26387
  if (spec === false) return void 0;
25698
26388
  return {
25699
26389
  enter: resolveEnter(spec.enter),
25700
- update: resolveDurationPhase(spec.update, UPDATE_DEFAULT),
25701
- exit: resolveDurationPhase(spec.exit, EXIT_DEFAULT),
26390
+ update: resolvePhase2(spec.update, UPDATE_DEFAULT),
26391
+ exit: resolvePhase2(spec.exit, EXIT_DEFAULT),
25702
26392
  camera: resolveCamera(spec.camera),
25703
26393
  hover: resolveDurationPhase(spec.hover, HOVER_DEFAULT)
25704
26394
  };
@@ -25707,11 +26397,28 @@ function resolveEnter(phase) {
25707
26397
  if (phase === false) return null;
25708
26398
  if (phase === void 0 || phase === true) return { ...ENTER_DEFAULT };
25709
26399
  return {
25710
- duration: phase.duration ?? ENTER_DEFAULT.duration,
25711
- ease: phase.ease ?? ENTER_DEFAULT.ease,
26400
+ ...resolvePhaseConfig(phase, ENTER_DEFAULT),
25712
26401
  stagger: phase.stagger !== false,
25713
- cameraFit: ENTER_DEFAULT.cameraFit
26402
+ cameraFit: ENTER_DEFAULT.cameraFit,
26403
+ trigger: phase.trigger === "mount" ? "mount" : "visible"
26404
+ };
26405
+ }
26406
+ function resolvePhase2(phase, defaults) {
26407
+ if (phase === false) return null;
26408
+ if (phase === void 0 || phase === true)
26409
+ return { duration: defaults.duration, ease: defaults.ease };
26410
+ return resolvePhaseConfig(phase, defaults);
26411
+ }
26412
+ function resolvePhaseConfig(phase, defaults) {
26413
+ const resolved = {
26414
+ duration: phase.duration ?? defaults.duration,
26415
+ ease: phase.ease ?? defaults.ease
25714
26416
  };
26417
+ if (phase.spring) {
26418
+ resolved.spring = { ...phase.spring };
26419
+ resolved.duration = springDuration2(phase.spring);
26420
+ }
26421
+ return resolved;
25715
26422
  }
25716
26423
  function resolveDurationPhase(phase, defaults) {
25717
26424
  if (phase === false) return null;
@@ -26401,10 +27108,145 @@ import {
26401
27108
  buildD3Formatter as buildD3Formatter3,
26402
27109
  computeChrome as computeChrome6,
26403
27110
  defaultNumberFormatter as defaultNumberFormatter10,
26404
- estimateTextWidth as estimateTextWidth26,
27111
+ estimateTextWidth as estimateTextWidth28,
26405
27112
  resolveTheme as resolveTheme6
26406
27113
  } from "@opendata-ai/openchart-core";
26407
27114
 
27115
+ // src/sankey/label-placement.ts
27116
+ import { estimateTextWidth as estimateTextWidth26, wrapText as wrapText6 } from "@opendata-ai/openchart-core";
27117
+ var MIN_OUTSIDE_FLOW_SHARE = 0.5;
27118
+ var LABEL_GAP3 = 6;
27119
+ var LABEL_STACK_GAP = 2;
27120
+ function shouldPlaceLabelsInside(align, plotWidth, gutters) {
27121
+ if (align !== "auto" || plotWidth <= 0) return false;
27122
+ const flowWidth = plotWidth - gutters.left - gutters.right;
27123
+ return flowWidth < plotWidth * MIN_OUTSIDE_FLOW_SHARE;
27124
+ }
27125
+ function columnEdges(nodes) {
27126
+ const edges = /* @__PURE__ */ new Map();
27127
+ for (const node3 of nodes) {
27128
+ const current = edges.get(node3.depth);
27129
+ if (!current) edges.set(node3.depth, { left: node3.x0, right: node3.x1 });
27130
+ else {
27131
+ current.left = Math.min(current.left, node3.x0);
27132
+ current.right = Math.max(current.right, node3.x1);
27133
+ }
27134
+ }
27135
+ return edges;
27136
+ }
27137
+ function textWidth(text, fontWeight, metrics) {
27138
+ return metrics.measureText ? metrics.measureText(text, metrics.fontSize, fontWeight).width : estimateTextWidth26(text, metrics.fontSize, fontWeight);
27139
+ }
27140
+ function longestWordWidth(name, metrics) {
27141
+ let widest = 0;
27142
+ for (const word of name.split(/\s+/)) {
27143
+ widest = Math.max(widest, textWidth(word, metrics.fontWeight, metrics));
27144
+ }
27145
+ return widest;
27146
+ }
27147
+ function boundedLabelWidth(name, columnRoom, frameRoom, metrics) {
27148
+ const room = longestWordWidth(name, metrics) <= columnRoom ? columnRoom : frameRoom;
27149
+ return Math.max(room, 0);
27150
+ }
27151
+ function placeInsideLabels(nodes, frame, metrics) {
27152
+ const maxDepth = nodes.reduce((max4, n) => Math.max(max4, n.depth), 0);
27153
+ const edges = columnEdges(nodes);
27154
+ const placed = /* @__PURE__ */ new Map();
27155
+ for (const node3 of nodes) {
27156
+ placed.set(node3.id, insideLabelFor(node3, maxDepth, edges, frame, metrics));
27157
+ }
27158
+ const spreadWith = (showValue2) => spreadLabelBlocks(
27159
+ nodes.map((node3) => blockOf(node3, placed.get(node3.id), showValue2, metrics)),
27160
+ frame.top,
27161
+ frame.bottom
27162
+ );
27163
+ let spread = spreadWith(true);
27164
+ let showValue = true;
27165
+ if (!spread.fits) {
27166
+ showValue = false;
27167
+ spread = spreadWith(false);
27168
+ }
27169
+ for (const [id, centre] of spread.centres) {
27170
+ const label = placed.get(id);
27171
+ label.y = centre;
27172
+ label.showValue = showValue && label.showValue;
27173
+ }
27174
+ return placed;
27175
+ }
27176
+ function insideLabelFor(node3, maxDepth, edges, frame, metrics) {
27177
+ const centre = (node3.y0 + node3.y1) / 2;
27178
+ const isLast = node3.depth === maxDepth && maxDepth > 0;
27179
+ const showValue = !!node3.value;
27180
+ if (isLast) {
27181
+ const x2 = node3.x0 - LABEL_GAP3;
27182
+ const previous = edges.get(node3.depth - 1);
27183
+ const columnRoom2 = previous ? x2 - (previous.right + LABEL_GAP3) : x2 - frame.left;
27184
+ const maxWidth2 = boundedLabelWidth(node3.name, columnRoom2, x2 - frame.left, metrics);
27185
+ const lines2 = wrapName(node3.name, maxWidth2, metrics);
27186
+ return { x: x2, y: centre, anchor: "end", maxWidth: maxWidth2, lines: lines2, showValue };
27187
+ }
27188
+ const x = node3.x1 + LABEL_GAP3;
27189
+ const next = edges.get(node3.depth + 1);
27190
+ const columnRoom = next ? next.left - LABEL_GAP3 - x : frame.right - x;
27191
+ const maxWidth = boundedLabelWidth(node3.name, columnRoom, frame.right - x, metrics);
27192
+ const lines = wrapName(node3.name, maxWidth, metrics);
27193
+ return { x, y: centre, anchor: "start", maxWidth, lines, showValue };
27194
+ }
27195
+ function wrapName(name, maxWidth, metrics) {
27196
+ return wrapText6(name, metrics.fontSize, metrics.fontWeight, maxWidth, metrics.measureText);
27197
+ }
27198
+ function blockOf(node3, label, showValue, metrics) {
27199
+ const withValue = showValue && !!node3.value;
27200
+ const widths = label.lines.map((line4) => textWidth(line4, metrics.fontWeight, metrics));
27201
+ if (withValue) widths.push(textWidth(node3.value ?? "", metrics.valueFontWeight, metrics));
27202
+ const width = Math.max(0, ...widths);
27203
+ const lineCount = label.lines.length + (withValue ? 1 : 0);
27204
+ return {
27205
+ id: node3.id,
27206
+ centre: label.y,
27207
+ height: lineCount * metrics.lineHeight,
27208
+ left: label.anchor === "start" ? label.x : label.x - width,
27209
+ right: label.anchor === "start" ? label.x + width : label.x
27210
+ };
27211
+ }
27212
+ function shareSpan(a, b) {
27213
+ return a.left < b.right && b.left < a.right;
27214
+ }
27215
+ function spreadLabelBlocks(blocks, top, bottom) {
27216
+ const sorted = [...blocks].sort((a, b) => a.centre - b.centre);
27217
+ const tops = sorted.map((b) => b.centre - b.height / 2);
27218
+ for (let i = 0; i < sorted.length; i++) {
27219
+ let floor = top;
27220
+ for (let j = 0; j < i; j++) {
27221
+ if (shareSpan(sorted[i], sorted[j])) {
27222
+ floor = Math.max(floor, tops[j] + sorted[j].height + LABEL_STACK_GAP);
27223
+ }
27224
+ }
27225
+ tops[i] = Math.max(tops[i], floor);
27226
+ }
27227
+ for (let i = sorted.length - 1; i >= 0; i--) {
27228
+ let ceiling = bottom;
27229
+ for (let j = i + 1; j < sorted.length; j++) {
27230
+ if (shareSpan(sorted[i], sorted[j])) ceiling = Math.min(ceiling, tops[j] - LABEL_STACK_GAP);
27231
+ }
27232
+ tops[i] = Math.min(tops[i], ceiling - sorted[i].height);
27233
+ }
27234
+ const fits = tops.every((t) => t >= top);
27235
+ if (!fits) compressInto(sorted, tops, top, bottom);
27236
+ return { centres: new Map(sorted.map((b, i) => [b.id, tops[i] + b.height / 2])), fits };
27237
+ }
27238
+ function compressInto(sorted, tops, top, bottom) {
27239
+ const first = Math.min(...tops);
27240
+ const lastIndex = tops.indexOf(Math.max(...tops));
27241
+ const span = tops[lastIndex] - first;
27242
+ const room = bottom - sorted[lastIndex].height - top;
27243
+ const scale = span > 0 ? Math.max(room, 0) / span : 0;
27244
+ for (let i = 0; i < tops.length; i++) {
27245
+ const mapped = top + (tops[i] - first) * scale;
27246
+ tops[i] = Math.max(top, Math.min(mapped, bottom - sorted[i].height));
27247
+ }
27248
+ }
27249
+
26408
27250
  // src/sankey/layout.ts
26409
27251
  import { sankey, sankeyCenter, sankeyJustify, sankeyLeft, sankeyRight } from "d3-sankey";
26410
27252
  var ALIGN_MAP = {
@@ -26471,36 +27313,166 @@ function generateLinkPath(link) {
26471
27313
  ].join(" ");
26472
27314
  }
26473
27315
 
26474
- // src/sankey/compile-sankey.ts
26475
- var LABEL_GAP3 = 6;
26476
- var LINK_OPACITY_LIGHT = 0.5;
26477
- var LINK_OPACITY_DARK = 0.6;
26478
- var NODE_CORNER_RADIUS = 2;
27316
+ // src/sankey/node-labels.ts
27317
+ import { estimateTextWidth as estimateTextWidth27, wrapText as wrapText7 } from "@opendata-ai/openchart-core";
27318
+ var LABEL_LINE_HEIGHT = 1.3;
26479
27319
  var VALUE_GAP = 5;
26480
- var MAX_LABEL_GUTTER = 0.35;
26481
- var OTHER_ID_PREFIX = "__oc_other_";
26482
- function pickColor(palette, index) {
26483
- return palette[index % palette.length];
26484
- }
26485
- function buildNodeColorMap(nodes, palette, colorField, data, sourceField, targetField) {
26486
- const colorMap = /* @__PURE__ */ new Map();
26487
- if (colorField) {
26488
- const nodeCategoryMap = /* @__PURE__ */ new Map();
26489
- for (const row of data) {
26490
- const src = String(row[sourceField]);
26491
- const tgt = String(row[targetField]);
26492
- const cat = String(row[colorField]);
26493
- if (!nodeCategoryMap.has(src)) nodeCategoryMap.set(src, cat);
26494
- if (!nodeCategoryMap.has(tgt)) nodeCategoryMap.set(tgt, cat);
26495
- }
26496
- const categoryIndex = /* @__PURE__ */ new Map();
26497
- let nextIdx = 0;
26498
- for (const node3 of nodes) {
26499
- const category = nodeCategoryMap.get(node3.id) ?? node3.id;
26500
- if (!categoryIndex.has(category)) {
26501
- categoryIndex.set(category, nextIdx++);
26502
- }
26503
- colorMap.set(node3.id, pickColor(palette, categoryIndex.get(category)));
27320
+ function labelsLeftForDepth(depth, maxDepth, align) {
27321
+ if (align === "left") return true;
27322
+ if (align === "right") return false;
27323
+ return depth === 0 && maxDepth > 0;
27324
+ }
27325
+ function resolveNodeLabels(nodes, ctx) {
27326
+ const { theme } = ctx;
27327
+ const metrics = {
27328
+ fontSize: theme.fonts.sizes.small,
27329
+ fontWeight: theme.fonts.weights.medium,
27330
+ valueFontWeight: theme.fonts.weights.normal,
27331
+ lineHeight: theme.fonts.sizes.small * LABEL_LINE_HEIGHT,
27332
+ measureText: ctx.measureText
27333
+ };
27334
+ const labelNodes = nodes.map((node3) => ({
27335
+ id: node3.id,
27336
+ depth: node3.depth ?? 0,
27337
+ x0: node3.x0 ?? 0,
27338
+ x1: node3.x1 ?? 0,
27339
+ y0: node3.y0 ?? 0,
27340
+ y1: node3.y1 ?? 0,
27341
+ name: node3.label ?? node3.id,
27342
+ value: ctx.formatValue(node3.value ?? 0)
27343
+ }));
27344
+ const valueStyle = valueStyleFor(theme);
27345
+ const resolved = /* @__PURE__ */ new Map();
27346
+ if (ctx.inside) {
27347
+ const placed = placeInsideLabels(labelNodes, ctx.frame, metrics);
27348
+ for (const node3 of labelNodes) {
27349
+ const spot = placed.get(node3.id);
27350
+ resolved.set(node3.id, {
27351
+ label: insideLabelMark(node3.name, spot, theme),
27352
+ valueLabel: spot.showValue ? { text: node3.value ?? "", style: valueStyle } : void 0
27353
+ });
27354
+ }
27355
+ return resolved;
27356
+ }
27357
+ const maxDepth = labelNodes.reduce((max4, n) => Math.max(max4, n.depth), 0);
27358
+ const nextColumnLeft = new Map(
27359
+ [...columnEdges(labelNodes)].map(([depth, edges]) => [depth - 1, edges.left])
27360
+ );
27361
+ for (const node3 of labelNodes) {
27362
+ const label = outsideLabelMark(node3, maxDepth, ctx);
27363
+ const keepValue = outsideValueFits(node3, label, maxDepth, nextColumnLeft, ctx.align, metrics);
27364
+ resolved.set(node3.id, {
27365
+ label,
27366
+ valueLabel: keepValue ? { text: node3.value ?? "", style: valueStyle } : void 0
27367
+ });
27368
+ }
27369
+ return resolved;
27370
+ }
27371
+ function valueStyleFor(theme) {
27372
+ return {
27373
+ fontFamily: theme.fonts.family,
27374
+ fontSize: theme.fonts.sizes.small,
27375
+ fontWeight: theme.fonts.weights.normal,
27376
+ fill: theme.colors.axis,
27377
+ fontVariant: "tabular-nums",
27378
+ lineHeight: LABEL_LINE_HEIGHT
27379
+ };
27380
+ }
27381
+ function nameStyle(theme, anchor) {
27382
+ return {
27383
+ fontFamily: theme.fonts.family,
27384
+ fontSize: theme.fonts.sizes.small,
27385
+ fontWeight: theme.fonts.weights.medium,
27386
+ fill: theme.colors.text,
27387
+ lineHeight: LABEL_LINE_HEIGHT,
27388
+ textAnchor: anchor,
27389
+ dominantBaseline: "central"
27390
+ };
27391
+ }
27392
+ function insideLabelMark(text, placed, theme) {
27393
+ return {
27394
+ text,
27395
+ lines: placed.lines,
27396
+ x: placed.x,
27397
+ y: placed.y,
27398
+ style: nameStyle(theme, placed.anchor),
27399
+ visible: true,
27400
+ maxWidth: placed.maxWidth,
27401
+ halo: true
27402
+ };
27403
+ }
27404
+ function outsideLabelMark(node3, maxDepth, ctx) {
27405
+ const y = (node3.y0 + node3.y1) / 2;
27406
+ if (labelsLeftForDepth(node3.depth, maxDepth, ctx.align)) {
27407
+ const x2 = node3.x0 - LABEL_GAP3;
27408
+ return {
27409
+ text: node3.name,
27410
+ x: x2,
27411
+ y,
27412
+ style: nameStyle(ctx.theme, "end"),
27413
+ visible: true,
27414
+ maxWidth: Math.max(x2 - ctx.frame.left, 0)
27415
+ };
27416
+ }
27417
+ const x = node3.x1 + LABEL_GAP3;
27418
+ return {
27419
+ text: node3.name,
27420
+ x,
27421
+ y,
27422
+ style: nameStyle(ctx.theme, "start"),
27423
+ visible: true,
27424
+ maxWidth: Math.max(ctx.frame.right - x, 0)
27425
+ };
27426
+ }
27427
+ function outsideValueFits(node3, label, maxDepth, nextColumnLeft, align, metrics) {
27428
+ const width = (text, weight) => metrics.measureText ? metrics.measureText(text, metrics.fontSize, weight).width : estimateTextWidth27(text, metrics.fontSize, weight);
27429
+ const valueWidth = VALUE_GAP + width(node3.value ?? "", metrics.valueFontWeight);
27430
+ const placedLeft = labelsLeftForDepth(node3.depth, maxDepth, align);
27431
+ const nextColumn = nextColumnLeft.get(node3.depth);
27432
+ if (!placedLeft && node3.depth !== maxDepth && nextColumn !== void 0) {
27433
+ const available = nextColumn - LABEL_GAP3 - (node3.x1 + LABEL_GAP3);
27434
+ return width(label.text, metrics.fontWeight) + valueWidth <= available;
27435
+ }
27436
+ if (label.maxWidth === void 0 || label.maxWidth <= 0) return true;
27437
+ const lines = wrapText7(
27438
+ label.text,
27439
+ metrics.fontSize,
27440
+ metrics.fontWeight,
27441
+ label.maxWidth,
27442
+ metrics.measureText
27443
+ );
27444
+ const lastLine = lines[lines.length - 1] ?? "";
27445
+ return width(lastLine, metrics.fontWeight) + valueWidth <= label.maxWidth;
27446
+ }
27447
+
27448
+ // src/sankey/compile-sankey.ts
27449
+ var LINK_OPACITY_LIGHT = 0.5;
27450
+ var LINK_OPACITY_DARK = 0.6;
27451
+ var NODE_CORNER_RADIUS = 2;
27452
+ var MAX_LABEL_GUTTER = 0.35;
27453
+ var OTHER_ID_PREFIX = "__oc_other_";
27454
+ function pickColor(palette, index) {
27455
+ return palette[index % palette.length];
27456
+ }
27457
+ function buildNodeColorMap(nodes, palette, colorField, data, sourceField, targetField) {
27458
+ const colorMap = /* @__PURE__ */ new Map();
27459
+ if (colorField) {
27460
+ const nodeCategoryMap = /* @__PURE__ */ new Map();
27461
+ for (const row of data) {
27462
+ const src = String(row[sourceField]);
27463
+ const tgt = String(row[targetField]);
27464
+ const cat = String(row[colorField]);
27465
+ if (!nodeCategoryMap.has(src)) nodeCategoryMap.set(src, cat);
27466
+ if (!nodeCategoryMap.has(tgt)) nodeCategoryMap.set(tgt, cat);
27467
+ }
27468
+ const categoryIndex = /* @__PURE__ */ new Map();
27469
+ let nextIdx = 0;
27470
+ for (const node3 of nodes) {
27471
+ const category = nodeCategoryMap.get(node3.id) ?? node3.id;
27472
+ if (!categoryIndex.has(category)) {
27473
+ categoryIndex.set(category, nextIdx++);
27474
+ }
27475
+ colorMap.set(node3.id, pickColor(palette, categoryIndex.get(category)));
26504
27476
  }
26505
27477
  } else {
26506
27478
  for (let i = 0; i < nodes.length; i++) {
@@ -26569,59 +27541,12 @@ function rewriteRowsForOther(data, sourceField, targetField, valueField, merged)
26569
27541
  }
26570
27542
  return out;
26571
27543
  }
26572
- function labelsLeftForDepth(depth, maxDepth, nodeLabelAlign) {
26573
- if (nodeLabelAlign === "left") return true;
26574
- if (nodeLabelAlign === "right") return false;
26575
- if (depth === 0 && maxDepth > 0) return true;
26576
- return false;
26577
- }
26578
- function computeNodeLabel(node3, maxDepth, theme, nodeWidth, nodeLabelAlign = "auto", containerWidth, padding) {
26579
- const depth = node3.depth ?? 0;
26580
- const placeLeft = labelsLeftForDepth(depth, maxDepth, nodeLabelAlign);
26581
- const style = {
26582
- fontFamily: theme.fonts.family,
26583
- fontSize: theme.fonts.sizes.small,
26584
- fontWeight: theme.fonts.weights.medium,
26585
- fill: theme.colors.text,
26586
- lineHeight: 1.3
26587
- };
26588
- const x0 = node3.x0 ?? 0;
26589
- const x1 = node3.x1 ?? nodeWidth;
26590
- const y0 = node3.y0 ?? 0;
26591
- const y1 = node3.y1 ?? 0;
26592
- const midY = (y0 + y1) / 2;
26593
- const pad2 = padding ?? 0;
26594
- let maxWidth;
26595
- if (containerWidth !== void 0) {
26596
- if (placeLeft) {
26597
- maxWidth = x0 - LABEL_GAP3 - pad2;
26598
- } else {
26599
- maxWidth = containerWidth - pad2 - (x1 + LABEL_GAP3);
26600
- }
26601
- if (maxWidth !== void 0 && maxWidth < 0) maxWidth = 0;
26602
- }
26603
- if (placeLeft) {
26604
- return {
26605
- text: node3.label ?? node3.id,
26606
- x: x0 - LABEL_GAP3,
26607
- y: midY,
26608
- style: { ...style, textAnchor: "end", dominantBaseline: "central" },
26609
- visible: true,
26610
- maxWidth
26611
- };
26612
- }
26613
- return {
26614
- text: node3.label ?? node3.id,
26615
- x: x1 + LABEL_GAP3,
26616
- y: midY,
26617
- style: { ...style, textAnchor: "start", dominantBaseline: "central" },
26618
- visible: true,
26619
- maxWidth
26620
- };
26621
- }
26622
27544
  function compileSankey(spec, options) {
26623
27545
  const sugarWarnings = [];
26624
- const expandedSpec = spec && typeof spec === "object" && !Array.isArray(spec) ? expandSpecSugar(spec, sugarWarnings) : spec;
27546
+ const expandedSpec = spec && typeof spec === "object" && !Array.isArray(spec) ? expandSpecSugar(
27547
+ applySankeyOverride(spec, options.width),
27548
+ sugarWarnings
27549
+ ) : spec;
26625
27550
  const { spec: normalized, warnings } = compile(expandedSpec);
26626
27551
  emitSpecWarnings([...sugarWarnings, ...warnings], options.onWarn);
26627
27552
  if (!("type" in normalized) || normalized.type !== "sankey") {
@@ -26738,6 +27663,7 @@ function compileSankey(spec, options) {
26738
27663
  const labelFontSize = theme.fonts.sizes.small;
26739
27664
  const labelFontWeight = theme.fonts.weights.medium;
26740
27665
  const valueFontWeight = theme.fonts.weights.normal;
27666
+ const textWidth2 = (text, fontWeight) => options.measureText ? options.measureText(text, labelFontSize, fontWeight).width : estimateTextWidth28(text, labelFontSize, fontWeight);
26741
27667
  const nodeLabelAlign = sankeySpec.nodeLabelAlign ?? "auto";
26742
27668
  let workingData = measuredData;
26743
27669
  const runLayout = (rect) => computeSankeyLayout(
@@ -26781,23 +27707,19 @@ function compileSankey(spec, options) {
26781
27707
  const nodeFmt = resolveNodeValueFormatter(nodes, resolvedValueFormat, flowFmt);
26782
27708
  const labelBlockWidth = (node3) => {
26783
27709
  const name = node3.label ?? node3.id;
26784
- const nameWidth = estimateTextWidth26(name, labelFontSize, labelFontWeight);
26785
- const valueWidth = estimateTextWidth26(
26786
- formatFlowValue(node3.value ?? 0, nodeFmt),
26787
- labelFontSize,
26788
- valueFontWeight
26789
- );
27710
+ const nameWidth = textWidth2(name, labelFontWeight);
27711
+ const valueWidth = textWidth2(formatFlowValue(node3.value ?? 0, nodeFmt), valueFontWeight);
26790
27712
  return nameWidth + VALUE_GAP + valueWidth;
26791
27713
  };
26792
27714
  const measureGutters = (list) => {
26793
- const maxDepth2 = list.reduce((max4, n) => Math.max(max4, n.depth ?? 0), 0);
27715
+ const maxDepth = list.reduce((max4, n) => Math.max(max4, n.depth ?? 0), 0);
26794
27716
  const cap = area3.width * MAX_LABEL_GUTTER;
26795
27717
  let left = 0;
26796
27718
  let right = 0;
26797
27719
  for (const node3 of list) {
26798
27720
  const depth = node3.depth ?? 0;
26799
27721
  const width = labelBlockWidth(node3) + LABEL_GAP3;
26800
- if (labelsLeftForDepth(depth, maxDepth2, nodeLabelAlign)) {
27722
+ if (labelsLeftForDepth(depth, maxDepth, nodeLabelAlign)) {
26801
27723
  const need = width - ((node3.x0 ?? 0) - area3.x);
26802
27724
  if (need > left) left = need;
26803
27725
  } else {
@@ -26811,7 +27733,8 @@ function compileSankey(spec, options) {
26811
27733
  };
26812
27734
  };
26813
27735
  const gutters = measureGutters(nodes);
26814
- if (gutters.left > 0 || gutters.right > 0) {
27736
+ const labelsInside = shouldPlaceLabelsInside(nodeLabelAlign, area3.width, gutters);
27737
+ if (!labelsInside && (gutters.left > 0 || gutters.right > 0)) {
26815
27738
  const left = Math.ceil(gutters.left);
26816
27739
  const right = Math.ceil(gutters.right);
26817
27740
  layoutArea = {
@@ -26834,36 +27757,20 @@ function compileSankey(spec, options) {
26834
27757
  for (const otherId of otherMembers.keys()) {
26835
27758
  nodeColorMap.set(otherId, theme.colors.neutral[300]);
26836
27759
  }
26837
- const maxDepth = nodes.reduce((max4, n) => Math.max(max4, n.depth ?? 0), 0);
26838
- const valueStyle = {
26839
- fontFamily: theme.fonts.family,
26840
- fontSize: theme.fonts.sizes.small,
26841
- fontWeight: theme.fonts.weights.normal,
26842
- fill: theme.colors.axis,
26843
- fontVariant: "tabular-nums",
26844
- lineHeight: 1.3
26845
- };
26846
- const columnX0 = /* @__PURE__ */ new Map();
26847
- for (const node3 of nodes) {
26848
- const d = node3.depth ?? 0;
26849
- const x0 = node3.x0 ?? 0;
26850
- const current = columnX0.get(d);
26851
- if (current === void 0 || x0 < current) columnX0.set(d, x0);
26852
- }
26853
- const valueLabelFor = (node3, depth, text) => {
26854
- const placedLeft = labelsLeftForDepth(depth, maxDepth, nodeLabelAlign);
26855
- if (placedLeft || depth === maxDepth) return { text, style: valueStyle };
26856
- const nextColumn = columnX0.get(depth + 1);
26857
- if (nextColumn === void 0) return { text, style: valueStyle };
26858
- const available = nextColumn - LABEL_GAP3 - ((node3.x1 ?? 0) + LABEL_GAP3);
26859
- const needed = estimateTextWidth26(node3.label ?? node3.id, labelFontSize, labelFontWeight) + VALUE_GAP + estimateTextWidth26(text, labelFontSize, valueFontWeight);
26860
- return needed <= available ? { text, style: valueStyle } : void 0;
26861
- };
27760
+ const nodeLabels = resolveNodeLabels(nodes, {
27761
+ theme,
27762
+ align: nodeLabelAlign,
27763
+ inside: labelsInside,
27764
+ frame: { left: area3.x, right: area3.x + area3.width, top: area3.y, bottom: area3.y + area3.height },
27765
+ measureText: options.measureText,
27766
+ formatValue: (value) => formatFlowValue(value, nodeFmt)
27767
+ });
26862
27768
  const nodeMarks = nodes.map((node3) => {
26863
27769
  const fill = nodeColorMap.get(node3.id) ?? theme.colors.categorical[0];
26864
27770
  const depth = node3.depth ?? 0;
26865
27771
  const merged = otherMembers.get(node3.id);
26866
27772
  const valueText = formatFlowValue(node3.value ?? 0, nodeFmt);
27773
+ const { label, valueLabel } = nodeLabels.get(node3.id);
26867
27774
  return {
26868
27775
  type: "sankeyNode",
26869
27776
  x: node3.x0 ?? 0,
@@ -26875,16 +27782,8 @@ function compileSankey(spec, options) {
26875
27782
  // this the renderer inherits whatever stroke the SVG context carries.
26876
27783
  stroke: "none",
26877
27784
  cornerRadius: NODE_CORNER_RADIUS,
26878
- label: computeNodeLabel(
26879
- node3,
26880
- maxDepth,
26881
- theme,
26882
- sankeySpec.nodeWidth,
26883
- nodeLabelAlign,
26884
- options.width,
26885
- padding
26886
- ),
26887
- valueLabel: valueLabelFor(node3, depth, valueText),
27785
+ label,
27786
+ valueLabel,
26888
27787
  nodeId: node3.id,
26889
27788
  value: node3.value ?? 0,
26890
27789
  depth,
@@ -27114,7 +28013,7 @@ function emptyLayout4(area3, chrome, theme, options, watermark) {
27114
28013
  }
27115
28014
 
27116
28015
  // src/tables/compile-table.ts
27117
- import { computeChrome as computeChrome7, estimateTextWidth as estimateTextWidth27 } from "@opendata-ai/openchart-core";
28016
+ import { computeChrome as computeChrome7, estimateTextWidth as estimateTextWidth29 } from "@opendata-ai/openchart-core";
27118
28017
 
27119
28018
  // src/tables/bar-column.ts
27120
28019
  var NEGATIVE_BAR_COLOR = "#c44e52";
@@ -27587,13 +28486,13 @@ function estimateColumnWidth(col, data, fontSize, paddingX) {
27587
28486
  if (col.image) return (col.image.width ?? 24) + paddingX;
27588
28487
  if (col.flag) return 60;
27589
28488
  const label = col.label ?? col.key;
27590
- const headerWidth = estimateTextWidth27(label, fontSize, 600) + paddingX;
28489
+ const headerWidth = estimateTextWidth29(label, fontSize, 600) + paddingX;
27591
28490
  const sampleSize = Math.min(100, data.length);
27592
28491
  let maxDataWidth = 0;
27593
28492
  for (let i = 0; i < sampleSize; i++) {
27594
28493
  const val = data[i][col.key];
27595
28494
  const text = val == null ? "" : String(val);
27596
- const width = estimateTextWidth27(text, fontSize, 400) + paddingX;
28495
+ const width = estimateTextWidth29(text, fontSize, 400) + paddingX;
27597
28496
  if (width > maxDataWidth) maxDataWidth = width;
27598
28497
  }
27599
28498
  return Math.max(MIN_WIDTH, headerWidth, maxDataWidth);
@@ -27956,8 +28855,8 @@ import {
27956
28855
  adaptTheme as adaptTheme6,
27957
28856
  CATEGORICAL_PALETTE as CATEGORICAL_PALETTE2,
27958
28857
  computeChrome as computeChrome8,
27959
- estimateTextWidth as estimateTextWidth28,
27960
- getBreakpoint as getBreakpoint3,
28858
+ estimateTextWidth as estimateTextWidth30,
28859
+ getBreakpoint as getBreakpoint4,
27961
28860
  HPAD_COMPACT_FRACTION as HPAD_COMPACT_FRACTION4,
27962
28861
  HPAD_COMPACT_MIN as HPAD_COMPACT_MIN4,
27963
28862
  pickLabelColor as pickLabelColor6,
@@ -28019,7 +28918,7 @@ function compileTileMap(spec, options) {
28019
28918
  void 0,
28020
28919
  watermark
28021
28920
  );
28022
- const padding = getBreakpoint3(options.width) === "compact" ? Math.max(HPAD_COMPACT_MIN4, Math.round(theme.spacing.padding * HPAD_COMPACT_FRACTION4)) : theme.spacing.padding;
28921
+ const padding = getBreakpoint4(options.width) === "compact" ? Math.max(HPAD_COMPACT_MIN4, Math.round(theme.spacing.padding * HPAD_COMPACT_FRACTION4)) : theme.spacing.padding;
28023
28922
  const chromeLayout = resolveChromeLayout(
28024
28923
  spec,
28025
28924
  options
@@ -28132,7 +29031,7 @@ function compileQuantitative(tilemapSpec, options, theme, chrome, fullArea, isDa
28132
29031
  });
28133
29032
  const hasEmptyTiles = tiles.some((t) => !t.hasData);
28134
29033
  const noDataLabel = "No data";
28135
- const noDataLabelWidth = estimateTextWidth28(noDataLabel, 11);
29034
+ const noDataLabelWidth = estimateTextWidth30(noDataLabel, 11);
28136
29035
  const noDataBlockWidth2 = hasEmptyTiles ? NO_DATA_BAR_GAP + legendBarHeight + NO_DATA_LABEL_GAP2 + noDataLabelWidth : 0;
28137
29036
  const barWidth = Math.max(0, legendWidth - noDataBlockWidth2);
28138
29037
  const noDataX = legendX + barWidth + NO_DATA_BAR_GAP;
@@ -28192,7 +29091,7 @@ function compileQuantitative(tilemapSpec, options, theme, chrome, fullArea, isDa
28192
29091
  height: contentHeight,
28193
29092
  animation: resolvedAnimation,
28194
29093
  watermark,
28195
- measureText: options.measureText ?? ((text, fontSize) => ({ width: estimateTextWidth28(text, fontSize), height: fontSize }))
29094
+ measureText: options.measureText ?? ((text, fontSize) => ({ width: estimateTextWidth30(text, fontSize), height: fontSize }))
28196
29095
  };
28197
29096
  }
28198
29097
  function compileCategorical(tilemapSpec, options, theme, chrome, fullArea, isDarkMode, watermark, chromeLayout) {
@@ -28336,7 +29235,7 @@ function compileCategorical(tilemapSpec, options, theme, chrome, fullArea, isDar
28336
29235
  height: contentHeight,
28337
29236
  animation: resolvedAnimation,
28338
29237
  watermark,
28339
- measureText: options.measureText ?? ((text, fontSize) => ({ width: estimateTextWidth28(text, fontSize), height: fontSize }))
29238
+ measureText: options.measureText ?? ((text, fontSize) => ({ width: estimateTextWidth30(text, fontSize), height: fontSize }))
28340
29239
  };
28341
29240
  }
28342
29241
  function buildTileMark(opts) {
@@ -28462,7 +29361,7 @@ function countLegendRows(labels, availableWidth, fontSize) {
28462
29361
  let rows = 1;
28463
29362
  let offsetX = 0;
28464
29363
  for (let i = 0; i < labels.length; i++) {
28465
- const labelWidth = estimateTextWidth28(labels[i], fontSize);
29364
+ const labelWidth = estimateTextWidth30(labels[i], fontSize);
28466
29365
  const entryWidth = LEGEND_SWATCH_SIZE + LEGEND_SWATCH_GAP + labelWidth + LEGEND_ENTRY_GAP;
28467
29366
  if (i > 0 && offsetX + entryWidth > availableWidth) {
28468
29367
  rows++;
@@ -28506,12 +29405,2020 @@ function emptyLayout5(chrome, theme, options, watermark) {
28506
29405
  height: options.height,
28507
29406
  watermark,
28508
29407
  animation: void 0,
28509
- measureText: options.measureText ?? ((text, fontSize) => ({ width: estimateTextWidth28(text, fontSize), height: fontSize }))
29408
+ measureText: options.measureText ?? ((text, fontSize) => ({ width: estimateTextWidth30(text, fontSize), height: fontSize }))
29409
+ };
29410
+ }
29411
+
29412
+ // src/race/errors.ts
29413
+ var RaceDataError = class extends Error {
29414
+ constructor(code, message) {
29415
+ super(message);
29416
+ this.code = code;
29417
+ }
29418
+ name = "RaceDataError";
29419
+ };
29420
+
29421
+ // src/race/frame.ts
29422
+ function buildRaceFrame(sample, presentation) {
29423
+ const { t, periodIndex, items, domainMin, domainMax } = sample;
29424
+ const { keys, labels, colors, formatValue: formatValue3, periods, periodLabels, top, summary } = presentation;
29425
+ const frame = {
29426
+ t,
29427
+ period: {
29428
+ index: periodIndex,
29429
+ value: periods[periodIndex].value,
29430
+ label: periodLabels[periodIndex]
29431
+ },
29432
+ items: items.map(({ keyIndex, value, rank, rankPos, opacity, change }) => ({
29433
+ key: keys[keyIndex],
29434
+ label: labels[keyIndex],
29435
+ color: colors[keyIndex],
29436
+ value,
29437
+ valueLabel: formatValue3(value),
29438
+ rank,
29439
+ rankPos,
29440
+ opacity,
29441
+ change
29442
+ })),
29443
+ domain: [domainMin, domainMax]
29444
+ };
29445
+ if (summary) {
29446
+ const value = items.reduce((sum, item) => item.rank < top ? sum + item.value : sum, 0);
29447
+ frame.summary = { value, label: formatValue3(value) };
29448
+ }
29449
+ return frame;
29450
+ }
29451
+
29452
+ // src/race/layout-bar.ts
29453
+ import {
29454
+ DEFAULT_THEME,
29455
+ estimateTextWidth as estimateTextWidth31,
29456
+ truncateToWidth
29457
+ } from "@opendata-ai/openchart-core";
29458
+
29459
+ // src/race/ticks.ts
29460
+ function valueTickLadder(span, multipliers = [1, 5]) {
29461
+ const ladder = [];
29462
+ if (span <= 0 || !Number.isFinite(span)) return ladder;
29463
+ const decade = Math.floor(Math.log10(span));
29464
+ for (let exponent = decade - 2; exponent <= decade + 1; exponent++) {
29465
+ for (const multiplier of multipliers) {
29466
+ const step = Number(`${multiplier}e${exponent}`);
29467
+ if (step === 0 || !Number.isFinite(step)) continue;
29468
+ ladder.push(step);
29469
+ if (step >= span) return ladder;
29470
+ }
29471
+ }
29472
+ return ladder;
29473
+ }
29474
+ function periodTickLadder() {
29475
+ return [1, 5, 10, 50, 100, 500];
29476
+ }
29477
+ function crossfadeTicks(domain, pxPerUnit, ladder, room = 64, fadeFrom = 40) {
29478
+ if (ladder.length === 0) return [];
29479
+ const firstWithRoom = ladder.findIndex((step) => step * pxPerUnit >= room);
29480
+ const active = firstWithRoom === -1 ? ladder.length - 1 : firstWithRoom;
29481
+ const finer = ladder[active - 1];
29482
+ const weight = finer === void 0 ? 0 : Math.max(0, Math.min(1, (finer * pxPerUnit - fadeFrom) / (room - fadeFrom)));
29483
+ const [min4, max4] = domain;
29484
+ const opacities = /* @__PURE__ */ new Map();
29485
+ const addTicks = (step, opacity) => {
29486
+ if (opacity === 0) return;
29487
+ const start = Math.floor(min4 / step);
29488
+ const end = Math.ceil(max4 / step);
29489
+ if (!Number.isSafeInteger(start) || !Number.isSafeInteger(end)) return;
29490
+ const [coefficient, exponent] = step.toExponential().split("e");
29491
+ const [whole, fraction = ""] = coefficient.split(".");
29492
+ const digits = BigInt(whole + fraction);
29493
+ const power = Number(exponent) - fraction.length;
29494
+ for (let index = start; index <= end; index++) {
29495
+ const value = Number(`${BigInt(index) * digits}e${power}`);
29496
+ if (value >= min4 && value <= max4) {
29497
+ opacities.set(value, Math.min(1, (opacities.get(value) ?? 0) + opacity));
29498
+ }
29499
+ }
29500
+ };
29501
+ addTicks(ladder[active], 1 - weight);
29502
+ if (finer !== void 0) addTicks(finer, weight);
29503
+ return [...opacities].filter(([, opacity]) => opacity > 0.01).sort(([a], [b]) => a - b).map(([value, opacity]) => ({ value, opacity }));
29504
+ }
29505
+
29506
+ // src/race/layout-bar.ts
29507
+ var NAME_GAP = 8;
29508
+ var VALUE_GAP2 = 6;
29509
+ var TICK_PADDING = 10;
29510
+ var TICK_LABEL_GAP = 4;
29511
+ var MIN_PLOT_FRACTION = 0.4;
29512
+ function computeBarStatic(input) {
29513
+ const { area: area3, top, maxLabelWidth, maxValueLabelWidth, hasNegatives, showPeriod, showSummary } = input;
29514
+ const areaWidth = Math.max(0, area3.width);
29515
+ const minPlotWidth = areaWidth * MIN_PLOT_FRACTION;
29516
+ const gutterBudget = areaWidth - minPlotWidth;
29517
+ const nameGutter = Math.min(maxLabelWidth + NAME_GAP, gutterBudget);
29518
+ const valueGutter = Math.min(
29519
+ maxValueLabelWidth + VALUE_GAP2,
29520
+ (gutterBudget - nameGutter) / (hasNegatives ? 2 : 1)
29521
+ );
29522
+ const leftGutter = nameGutter + (hasNegatives ? valueGutter : 0);
29523
+ const tickFontSize = input.fontSize.tick;
29524
+ const tickHeight = Math.min(tickFontSize + TICK_PADDING, Math.max(0, area3.height));
29525
+ const plot = {
29526
+ x: area3.x + leftGutter,
29527
+ y: area3.y + tickHeight,
29528
+ width: Math.max(minPlotWidth, areaWidth - leftGutter - valueGutter),
29529
+ height: Math.max(0, area3.height - tickHeight)
29530
+ };
29531
+ const rowHeight = plot.height / top;
29532
+ const right = plot.x + plot.width;
29533
+ const bottom = plot.y + plot.height;
29534
+ let period = null;
29535
+ if (showPeriod) {
29536
+ const fontSize = Math.max(36, Math.min(72, rowHeight * 2.4));
29537
+ const labelWidth = input.measurePeriodWidth?.(fontSize) ?? 0;
29538
+ const budget = plot.width * 0.4;
29539
+ period = {
29540
+ x: right,
29541
+ y: bottom,
29542
+ fontSize: labelWidth > budget ? Math.max(36, fontSize * (budget / labelWidth)) : fontSize
29543
+ };
29544
+ }
29545
+ return {
29546
+ plot,
29547
+ clip: { x: area3.x, y: plot.y, width: areaWidth, height: plot.height },
29548
+ nameX: area3.x + Math.min(maxLabelWidth, nameGutter),
29549
+ rowHeight,
29550
+ barHeight: Math.round(rowHeight * 0.74),
29551
+ cornerRadius: input.cornerRadius,
29552
+ top,
29553
+ axisY: plot.y,
29554
+ tickFontSize,
29555
+ period,
29556
+ summary: showSummary ? { x: right, y: period ? Math.max(plot.y, bottom - period.fontSize - VALUE_GAP2) : bottom } : null
29557
+ };
29558
+ }
29559
+ function barScale(stat, [min4, max4]) {
29560
+ const { x, width } = stat.plot;
29561
+ const span = max4 - min4;
29562
+ const scale = (value) => x + (value - min4) / (span || 1) * width;
29563
+ return { scale, zero: scale(0), pxPerUnit: span > 0 ? width / span : 0 };
29564
+ }
29565
+ var defaultValueText = {
29566
+ fontSize: DEFAULT_THEME.fonts.sizes.body,
29567
+ fontWeight: DEFAULT_THEME.fonts.weights.normal
29568
+ };
29569
+ function truncateRaceLabel(label, budget, fontSize, fontWeight, measureWidth) {
29570
+ const fitted = truncateToWidth(label, budget, fontSize, fontWeight, measureWidth);
29571
+ return fitted === "\u2026" && measureWidth(fitted, fontSize, fontWeight) > budget ? "" : fitted;
29572
+ }
29573
+ function fitBarValue(text, edge, y, negative, clip, { fontSize, fontWeight, measureWidth = estimateTextWidth31 }) {
29574
+ let width = measureWidth(text, fontSize, fontWeight);
29575
+ if (width > clip.width) {
29576
+ text = truncateRaceLabel(text, clip.width, fontSize, fontWeight, measureWidth);
29577
+ width = measureWidth(text, fontSize, fontWeight);
29578
+ }
29579
+ const left = clip.x + (negative ? width : 0);
29580
+ const right = clip.x + clip.width - (negative ? 0 : width);
29581
+ const preferredX = edge + (negative ? -VALUE_GAP2 : VALUE_GAP2);
29582
+ return {
29583
+ x: Math.max(left, Math.min(right, preferredX)),
29584
+ y,
29585
+ text,
29586
+ anchor: negative ? "end" : "start"
29587
+ };
29588
+ }
29589
+ function barTicks(stat, domain, { scale, pxPerUnit }, formatTick, { fontWeight, measureWidth = estimateTextWidth31 }) {
29590
+ const fontSize = stat.tickFontSize;
29591
+ const { x, width } = stat.clip;
29592
+ const ladder = valueTickLadder(domain[1] - domain[0]);
29593
+ const ticks = crossfadeTicks(domain, pxPerUnit, ladder).map((tick) => ({
29594
+ ...tick,
29595
+ position: scale(tick.value),
29596
+ label: ""
29597
+ }));
29598
+ const occupied = [];
29599
+ const byPriority = [...ticks].sort(
29600
+ (a, b) => Number(b.value === 0) - Number(a.value === 0) || b.opacity - a.opacity
29601
+ );
29602
+ for (const tick of byPriority) {
29603
+ const { position } = tick;
29604
+ const budget = 2 * Math.max(0, Math.min(position - x, x + width - position));
29605
+ const label = formatTick(tick.value);
29606
+ if (!label) continue;
29607
+ const labelWidth = measureWidth(label, fontSize, fontWeight);
29608
+ if (labelWidth > budget) continue;
29609
+ const halfWidth = labelWidth / 2;
29610
+ const left = position - halfWidth;
29611
+ const right = position + halfWidth;
29612
+ if (occupied.some(
29613
+ (other) => left < other.right + TICK_LABEL_GAP && right > other.left - TICK_LABEL_GAP
29614
+ )) {
29615
+ continue;
29616
+ }
29617
+ tick.label = label;
29618
+ occupied.push({ left, right });
29619
+ }
29620
+ return ticks;
29621
+ }
29622
+ function barGeometry(stat, frame, formatTick, valueText = defaultValueText) {
29623
+ const { plot, rowHeight, barHeight, clip } = stat;
29624
+ const axis = barScale(stat, frame.domain);
29625
+ const { scale, zero } = axis;
29626
+ const inset = (rowHeight - barHeight) / 2;
29627
+ const right = clip.x + clip.width;
29628
+ const valueLeft = Math.max(clip.x, Math.min(stat.nameX + NAME_GAP, right));
29629
+ const valueClip = { ...clip, x: valueLeft, width: right - valueLeft };
29630
+ return {
29631
+ mark: "bar",
29632
+ rows: frame.items.map((item) => {
29633
+ const x = scale(item.value);
29634
+ const y = plot.y + item.rankPos * rowHeight + inset;
29635
+ const center = y + barHeight / 2;
29636
+ return {
29637
+ key: item.key,
29638
+ color: item.color,
29639
+ opacity: item.opacity,
29640
+ bar: { x: Math.min(zero, x), y, width: Math.abs(x - zero), height: barHeight },
29641
+ name: { x: stat.nameX, y: center, text: item.label },
29642
+ value: fitBarValue(item.valueLabel, x, center, item.value < 0, valueClip, valueText)
29643
+ };
29644
+ }),
29645
+ ticks: barTicks(stat, frame.domain, axis, formatTick, valueText),
29646
+ period: stat.period ? { ...stat.period, text: frame.period.label } : null,
29647
+ summary: stat.summary && frame.summary ? { ...stat.summary, text: frame.summary.label } : null
29648
+ };
29649
+ }
29650
+
29651
+ // src/race/layout-line.ts
29652
+ import {
29653
+ estimateTextWidth as estimateTextWidth32
29654
+ } from "@opendata-ai/openchart-core";
29655
+
29656
+ // src/race/interpolate.ts
29657
+ function lerp(from, to, fraction) {
29658
+ const delta = to - from;
29659
+ return Number.isFinite(delta) ? from + delta * fraction : from * (1 - fraction) + to * fraction;
29660
+ }
29661
+ function interpolateRaceValue(values, periodIndex, fraction, nextPeriodIndex = periodIndex + 1) {
29662
+ const from = values[periodIndex];
29663
+ if (!Number.isFinite(from)) return NaN;
29664
+ if (fraction === 0) return from;
29665
+ const to = values[nextPeriodIndex];
29666
+ return Number.isFinite(to) ? lerp(from, to, fraction) : NaN;
29667
+ }
29668
+
29669
+ // src/race/rank-smoothing.ts
29670
+ function sampleRanks(values, periodCount, samplesPerPeriod, top) {
29671
+ const sampleCount = (periodCount - 1) * samplesPerPeriod + 1;
29672
+ const keyCount = values.length;
29673
+ const ranks = values.map(() => new Float32Array(sampleCount));
29674
+ const sampleValues = new Float64Array(keyCount);
29675
+ const previousRanks = new Uint32Array(keyCount).fill(keyCount);
29676
+ const present = [];
29677
+ const compare = (a, b) => sampleValues[b] - sampleValues[a] || previousRanks[a] - previousRanks[b] || a - b;
29678
+ for (let sample = 0; sample < sampleCount; sample++) {
29679
+ const t = sample / samplesPerPeriod;
29680
+ const period = Math.floor(t);
29681
+ const fraction = t - period;
29682
+ present.length = 0;
29683
+ for (let key = 0; key < keyCount; key++) {
29684
+ const value = interpolateRaceValue(values[key], period, fraction);
29685
+ if (Number.isFinite(value)) {
29686
+ sampleValues[key] = value;
29687
+ present.push(key);
29688
+ } else {
29689
+ ranks[key][sample] = top;
29690
+ }
29691
+ }
29692
+ present.sort(compare);
29693
+ previousRanks.fill(keyCount);
29694
+ for (let rank = 0; rank < present.length; rank++) {
29695
+ const key = present[rank];
29696
+ previousRanks[key] = rank;
29697
+ ranks[key][sample] = Math.min(rank, top);
29698
+ }
29699
+ }
29700
+ return ranks;
29701
+ }
29702
+ function boxPass(values, width) {
29703
+ const prefix = new Float64Array(values.length + 1);
29704
+ for (let index = 0; index < values.length; index++) {
29705
+ prefix[index + 1] = prefix[index] + values[index];
29706
+ }
29707
+ const result = new Float64Array(values.length - width + 1);
29708
+ for (let index = 0; index < result.length; index++) {
29709
+ result[index] = (prefix[index + width] - prefix[index]) / width;
29710
+ }
29711
+ return result;
29712
+ }
29713
+ function smoothRanks(raw, halfWidthSamples) {
29714
+ const { length } = raw;
29715
+ if (halfWidthSamples === 0 || length < 3) return raw.slice();
29716
+ const pad2 = 2 * halfWidthSamples;
29717
+ const values = new Float64Array(length + 2 * pad2);
29718
+ values.fill(raw[0], 0, pad2);
29719
+ values.set(raw, pad2);
29720
+ values.fill(raw[length - 1], pad2 + length);
29721
+ const width = pad2 + 1;
29722
+ const smoothed = new Float32Array(boxPass(boxPass(values, width), width));
29723
+ smoothed[0] = raw[0];
29724
+ smoothed[length - 1] = raw[length - 1];
29725
+ return smoothed;
29726
+ }
29727
+
29728
+ // src/race/timeline.ts
29729
+ var PRESENCE_FADE = 1;
29730
+ var PRESENCE_PIN = 2;
29731
+ var VISIBILITY_EPSILON = 1e-6;
29732
+ function presenceEdges(ranks, absentRank, radius) {
29733
+ if (!ranks.includes(absentRank)) return void 0;
29734
+ const edges = new Uint8Array(ranks.length);
29735
+ for (let start = 0; start < ranks.length; ) {
29736
+ if (ranks[start] === absentRank) {
29737
+ start++;
29738
+ continue;
29739
+ }
29740
+ let end = start + 1;
29741
+ while (end < ranks.length && ranks[end] !== absentRank) end++;
29742
+ if (start > 0) edges.fill(PRESENCE_FADE, start, Math.min(end, start + 2 * radius + 1));
29743
+ if (end < ranks.length) edges.fill(PRESENCE_FADE, Math.max(start, end - 2 * radius - 1), end);
29744
+ if (start > 0) edges.fill(PRESENCE_PIN, start, Math.min(end, start + radius + 1));
29745
+ if (end < ranks.length) edges.fill(PRESENCE_PIN, Math.max(start, end - radius - 1), end);
29746
+ start = end;
29747
+ }
29748
+ return edges;
29749
+ }
29750
+ function clipVisibleRanks(exact, edges, top) {
29751
+ if (edges.every((edge) => edge === void 0)) {
29752
+ return exact.map((ranks) => ranks.map((rank) => Math.min(rank, top)));
29753
+ }
29754
+ const keyCount = exact.length;
29755
+ const sampleCount = exact[0].length;
29756
+ const visible = exact.map(() => new Float32Array(sampleCount));
29757
+ const skippedByRank = new Uint32Array(keyCount);
29758
+ for (let sample = 0; sample < sampleCount; sample++) {
29759
+ skippedByRank.fill(0);
29760
+ for (let key = 0; key < keyCount; key++) {
29761
+ if (edges[key]?.[sample] === PRESENCE_PIN) skippedByRank[exact[key][sample]] = 1;
29762
+ }
29763
+ for (let rank = 1; rank < keyCount; rank++) skippedByRank[rank] += skippedByRank[rank - 1];
29764
+ for (let key = 0; key < keyCount; key++) {
29765
+ const rank = exact[key][sample];
29766
+ visible[key][sample] = rank === keyCount || edges[key]?.[sample] === PRESENCE_PIN ? top : Math.min(rank - skippedByRank[rank], top);
29767
+ }
29768
+ }
29769
+ return visible;
29770
+ }
29771
+ function createRaceTimeline(matrix, options) {
29772
+ const { samplesPerPeriod, swapPeriods, rescale } = options;
29773
+ const periodCount = matrix.periods.length;
29774
+ const lastSample = (periodCount - 1) * samplesPerPeriod;
29775
+ const keyCount = matrix.keys.length;
29776
+ const top = Math.min(options.top, keyCount);
29777
+ const halfWidth = Math.min(lastSample + 1, Math.round(swapPeriods * (samplesPerPeriod / 4)));
29778
+ const exactSamples = sampleRanks(matrix.values, periodCount, samplesPerPeriod, keyCount);
29779
+ const edges = exactSamples.map((ranks) => presenceEdges(ranks, keyCount, 2 * halfWidth));
29780
+ const smoothedSamples = clipVisibleRanks(exactSamples, edges, top).map((ranks, key) => {
29781
+ const smoothed = smoothRanks(ranks, halfWidth);
29782
+ smoothed[0] = Math.min(exactSamples[key][0], top);
29783
+ smoothed[lastSample] = Math.min(exactSamples[key][lastSample], top);
29784
+ return smoothed;
29785
+ });
29786
+ let globalMin = 0;
29787
+ let globalMax = -Infinity;
29788
+ if (rescale === "fixed") {
29789
+ for (const series of matrix.values) {
29790
+ for (const value of series) {
29791
+ if (!Number.isFinite(value)) continue;
29792
+ globalMin = Math.min(globalMin, value);
29793
+ globalMax = Math.max(globalMax, value);
29794
+ }
29795
+ }
29796
+ }
29797
+ function clampTime(t) {
29798
+ return Math.max(0, Math.min(periodCount - 1, t));
29799
+ }
29800
+ function valueAt(keyIndex, t) {
29801
+ t = clampTime(t);
29802
+ const period = Math.floor(t);
29803
+ return interpolateRaceValue(matrix.values[keyIndex], period, t - period);
29804
+ }
29805
+ function periodRank(keyIndex, period) {
29806
+ const rank = exactSamples[keyIndex][period * samplesPerPeriod];
29807
+ return rank < keyCount ? rank : Infinity;
29808
+ }
29809
+ function rankPos(keyIndex, t) {
29810
+ const sample = clampTime(t) * samplesPerPeriod;
29811
+ const ranks = smoothedSamples[keyIndex];
29812
+ const startIndex = Math.floor(sample);
29813
+ const start = ranks[startIndex];
29814
+ const end = ranks[Math.ceil(sample)];
29815
+ return start + (end - start) * (sample - startIndex);
29816
+ }
29817
+ function rankedValues(t) {
29818
+ const period = Math.floor(t);
29819
+ const nearest = Math.round(t * samplesPerPeriod);
29820
+ const present = [];
29821
+ for (let keyIndex = 0; keyIndex < keyCount; keyIndex++) {
29822
+ const value = interpolateRaceValue(matrix.values[keyIndex], period, t - period);
29823
+ if (Number.isFinite(value)) present.push({ keyIndex, value });
29824
+ }
29825
+ return present.sort(
29826
+ (a, b) => b.value - a.value || exactSamples[a.keyIndex][nearest] - exactSamples[b.keyIndex][nearest] || a.keyIndex - b.keyIndex
29827
+ );
29828
+ }
29829
+ return {
29830
+ periodCount,
29831
+ keyCount,
29832
+ top,
29833
+ samplesPerPeriod,
29834
+ valueAt,
29835
+ rankPos,
29836
+ periodRank,
29837
+ rankSamples(keyIndex) {
29838
+ return { exact: exactSamples[keyIndex], smoothed: smoothedSamples[keyIndex] };
29839
+ },
29840
+ ranked(t) {
29841
+ return rankedValues(clampTime(t)).map(({ keyIndex }) => keyIndex);
29842
+ },
29843
+ exactRank(keyIndex, t) {
29844
+ const rank = rankedValues(clampTime(t)).findIndex((item) => item.keyIndex === keyIndex);
29845
+ return rank === -1 ? Infinity : rank;
29846
+ },
29847
+ sample(t) {
29848
+ t = clampTime(t);
29849
+ const periodIndex = Math.floor(t);
29850
+ let domainMin = 0;
29851
+ let domainMax = -Infinity;
29852
+ const items = [];
29853
+ rankedValues(t).forEach(({ keyIndex, value }, rank) => {
29854
+ const position = rankPos(keyIndex, t);
29855
+ if (!(position < top - VISIBILITY_EPSILON)) return;
29856
+ let change = 0;
29857
+ if (periodIndex > 0) {
29858
+ const previous = periodRank(keyIndex, periodIndex - 1);
29859
+ const current = periodRank(keyIndex, periodIndex);
29860
+ if (Number.isFinite(previous) && Number.isFinite(current)) change = previous - current;
29861
+ }
29862
+ const item = {
29863
+ keyIndex,
29864
+ value,
29865
+ rank,
29866
+ rankPos: position,
29867
+ opacity: Math.min(1, top - position),
29868
+ change
29869
+ };
29870
+ items.push(item);
29871
+ domainMin = Math.min(domainMin, value);
29872
+ domainMax = Math.max(domainMax, value);
29873
+ });
29874
+ if (rescale === "fixed") {
29875
+ domainMin = globalMin;
29876
+ domainMax = globalMax;
29877
+ } else if (typeof rescale === "object") {
29878
+ domainMax = Math.max(rescale.min, domainMax);
29879
+ }
29880
+ items.sort((a, b) => a.rankPos - b.rankPos || a.keyIndex - b.keyIndex);
29881
+ return { t, periodIndex, items, domainMin, domainMax: domainMax > 0 ? domainMax : 1 };
29882
+ }
29883
+ };
29884
+ }
29885
+
29886
+ // src/race/line-visibility.ts
29887
+ function lineVisibilityRuns(timeline, key, values) {
29888
+ const { samplesPerPeriod } = timeline;
29889
+ const { smoothed } = timeline.rankSamples(key);
29890
+ const threshold = timeline.top - VISIBILITY_EPSILON;
29891
+ const runs = [];
29892
+ function add(start, end, startRank, endRank) {
29893
+ const peakOpacity = Math.min(1, timeline.top - Math.min(startRank, endRank));
29894
+ const fullRank = timeline.top - 1;
29895
+ let peakTime = end;
29896
+ if (endRank > startRank && endRank > fullRank) {
29897
+ const fraction = Math.max(0, (fullRank - startRank) / (endRank - startRank));
29898
+ peakTime = start + fraction * (end - start);
29899
+ }
29900
+ const previous = runs.at(-1);
29901
+ if (previous && previous.end === start) {
29902
+ previous.end = end;
29903
+ if (peakOpacity >= previous.peakOpacity) {
29904
+ previous.peakOpacity = peakOpacity;
29905
+ previous.peakTime = peakTime;
29906
+ }
29907
+ } else {
29908
+ runs.push({ start, end, peakTime, peakOpacity });
29909
+ }
29910
+ }
29911
+ for (let period = 0; period < values.length; period++) {
29912
+ if (!Number.isFinite(values[period])) continue;
29913
+ const first = period * samplesPerPeriod;
29914
+ let rank = smoothed[first];
29915
+ if (rank < threshold) add(period, period, rank, rank);
29916
+ if (!Number.isFinite(values[period + 1])) continue;
29917
+ for (let sample = 0; sample < samplesPerPeriod; sample++) {
29918
+ const start = period + sample / samplesPerPeriod;
29919
+ const end = period + (sample + 1) / samplesPerPeriod;
29920
+ const nextRank = smoothed[first + sample + 1];
29921
+ if (rank < threshold && nextRank < threshold) {
29922
+ add(start, end, rank, nextRank);
29923
+ } else if (rank < threshold || nextRank < threshold) {
29924
+ const crossing = start + (threshold - rank) / (nextRank - rank) * (end - start);
29925
+ if (rank < threshold) add(start, crossing, rank, threshold);
29926
+ else add(crossing, end, threshold, nextRank);
29927
+ }
29928
+ rank = nextRank;
29929
+ }
29930
+ }
29931
+ return runs;
29932
+ }
29933
+ function departingLineOpacity(run, t) {
29934
+ const expiry = run.end + 1;
29935
+ return t < run.peakTime ? 0 : run.peakOpacity * ((expiry - t) / (expiry - run.peakTime));
29936
+ }
29937
+
29938
+ // src/race/layout-line.ts
29939
+ var LABEL_GAP4 = 14;
29940
+ var LINE_VALUES_MIN_WIDTH = 420;
29941
+ var TICK_GAP = 4;
29942
+ var TICK_PADDING2 = 10;
29943
+ var OVERLAP_OPACITY = 0.15;
29944
+ function roundBound(value) {
29945
+ const step = valueTickLadder(Math.abs(value))[0];
29946
+ if (!step) return value;
29947
+ const rounded = Math.sign(value) * Math.ceil(Math.abs(value) / step) * step;
29948
+ return Number.isFinite(rounded) ? Math.sign(value) * Math.max(Math.abs(value), Math.abs(rounded)) : value;
29949
+ }
29950
+ var computeLineStatic = (model, { area: area3, labels, theme }, mark, measureText) => {
29951
+ const { body, axisTick } = theme.fonts.sizes;
29952
+ const { normal } = theme.fonts.weights;
29953
+ const history = buildHistory(model);
29954
+ let labelWidth = 0;
29955
+ let min4 = 0;
29956
+ let max4 = 0;
29957
+ const lastPeriod = model.timeline.periodCount - 1;
29958
+ for (const entry of history) {
29959
+ labelWidth = Math.max(labelWidth, measureText(labels[entry.key], body, normal).width);
29960
+ const lastRun = entry.runs.at(-1);
29961
+ if (!lastRun) continue;
29962
+ const [low, high] = extentAt(model, entry, Math.min(lastPeriod, lastRun.end + 1));
29963
+ min4 = Math.min(min4, low);
29964
+ max4 = Math.max(max4, high);
29965
+ }
29966
+ const valueProbes = /* @__PURE__ */ new Set([min4, 0, max4, min4 / 2 + max4 / 2]);
29967
+ const tickProbes = /* @__PURE__ */ new Set([roundBound(min4), 0, roundBound(max4)]);
29968
+ for (const bound of [min4, max4]) {
29969
+ for (const step of valueTickLadder(Math.abs(bound))) {
29970
+ const value = Math.sign(bound) * step;
29971
+ if (value < min4 || value > max4) continue;
29972
+ tickProbes.add(value);
29973
+ valueProbes.add(value / 3);
29974
+ }
29975
+ }
29976
+ const maxWidth = (values, size) => Math.max(
29977
+ ...[...values].map((value) => measureText(model.formatValue(value), size, normal).width)
29978
+ );
29979
+ const window = mark.window ?? "reveal";
29980
+ let leftWidth = maxWidth(tickProbes, axisTick) + TICK_GAP;
29981
+ const showValues = area3.width >= LINE_VALUES_MIN_WIDTH;
29982
+ let rightWidth = labelWidth + LABEL_GAP4;
29983
+ if (showValues) {
29984
+ rightWidth += measureText(" ", body, normal).width + maxWidth(valueProbes, body);
29985
+ }
29986
+ if (window === "all") {
29987
+ const [first, ...rest] = model.periodLabels;
29988
+ leftWidth = Math.max(leftWidth, measureText(first, axisTick, normal).width + TICK_GAP / 2);
29989
+ for (const label of rest) {
29990
+ rightWidth = Math.max(rightWidth, measureText(label, axisTick, normal).width + TICK_GAP / 2);
29991
+ }
29992
+ }
29993
+ const gutterBudget = area3.width * (showValues ? 0.5 : 0.56);
29994
+ const leftGutter = Math.min(
29995
+ Math.ceil(leftWidth),
29996
+ gutterBudget - Math.min(rightWidth, gutterBudget / 2)
29997
+ );
29998
+ const labelGutter = Math.min(Math.ceil(rightWidth), gutterBudget - leftGutter);
29999
+ const plot = {
30000
+ x: area3.x + leftGutter,
30001
+ y: area3.y,
30002
+ width: area3.width - leftGutter - labelGutter,
30003
+ height: Math.max(0, area3.height - axisTick - TICK_PADDING2)
30004
+ };
30005
+ return {
30006
+ plot,
30007
+ window,
30008
+ xScale: {
30009
+ domain: [0, lastPeriod],
30010
+ range: [plot.x, plot.x + plot.width]
30011
+ },
30012
+ yAxisX: plot.x,
30013
+ labelGutter,
30014
+ showValues,
30015
+ tickFontSize: axisTick,
30016
+ history
30017
+ };
30018
+ };
30019
+ function buildHistory(model) {
30020
+ const history = [];
30021
+ model.matrix.values.forEach((values, key) => {
30022
+ const runs = lineVisibilityRuns(model.timeline, key, values);
30023
+ if (runs.length === 0) return;
30024
+ let min4 = 0;
30025
+ let max4 = 0;
30026
+ const mins = [];
30027
+ const maxes = [];
30028
+ values.forEach((value, period) => {
30029
+ if (Number.isFinite(value)) {
30030
+ min4 = Math.min(min4, value);
30031
+ max4 = Math.max(max4, value);
30032
+ }
30033
+ mins[period] = min4;
30034
+ maxes[period] = max4;
30035
+ });
30036
+ history.push({ key, runs, mins, maxes });
30037
+ });
30038
+ return history;
30039
+ }
30040
+ function extentAt(model, { key, mins, maxes }, t) {
30041
+ const period = Math.floor(t);
30042
+ const head = interpolateRaceValue(model.matrix.values[key], period, t - period);
30043
+ const value = Number.isFinite(head) ? head : 0;
30044
+ return [Math.min(mins[period], value), Math.max(maxes[period], value)];
30045
+ }
30046
+ function lineText(layout, size) {
30047
+ const weight = layout.theme.fonts.weights.normal;
30048
+ const measure = layout.measureText;
30049
+ const measureWidth = measure ? (text, fontSize, fontWeight) => measure(text, fontSize, fontWeight).width : estimateTextWidth32;
30050
+ return {
30051
+ width: (text) => measureWidth(text, size, weight),
30052
+ fit: (text, budget) => truncateRaceLabel(text, budget, size, weight, measureWidth)
30053
+ };
30054
+ }
30055
+ function periodTicks(layout, playhead, x, xMax) {
30056
+ const { area: area3, periods, static: stat } = layout;
30057
+ const text = lineText(layout, stat.tickFontSize);
30058
+ const occupied = [];
30059
+ const ticks = [];
30060
+ const add = (period, left, right2, required) => {
30061
+ const position = x(period);
30062
+ const centered = stat.window === "reveal";
30063
+ const first = period === 0;
30064
+ const labelX = centered ? position : position + (first ? -TICK_GAP / 2 : TICK_GAP / 2);
30065
+ const budget = centered ? 2 * Math.min(labelX - left, right2 - labelX) : first ? labelX - left : right2 - labelX;
30066
+ const label = required ? text.fit(periods[period], budget) : periods[period];
30067
+ const width2 = text.width(label);
30068
+ const start = labelX - (centered ? width2 / 2 : first ? width2 : 0);
30069
+ const end = start + width2;
30070
+ if (!required && (width2 > budget || occupied.some(
30071
+ (other) => tickLabelsOverlap({ left: start, right: end }, other, stat.tickFontSize)
30072
+ )))
30073
+ return;
30074
+ ticks.push({ value: period, label, opacity: 1, position });
30075
+ if (label) occupied.push({ left: start, right: end });
30076
+ };
30077
+ const right = area3.x + area3.width;
30078
+ const middle = (x(0) + x(playhead)) / 2;
30079
+ const halfGap = stat.tickFontSize / 4;
30080
+ add(0, area3.x, playhead === 0 ? right : middle - halfGap, true);
30081
+ if (playhead !== 0) add(playhead, middle + halfGap, right, true);
30082
+ const { width } = stat.plot;
30083
+ if (width > 0) {
30084
+ let step = 1;
30085
+ for (const candidate of periodTickLadder()) {
30086
+ if (candidate * width / xMax > 40) break;
30087
+ step = candidate;
30088
+ }
30089
+ for (let period = step; period <= xMax; period += step) {
30090
+ if (period !== playhead) add(period, area3.x, right, false);
30091
+ }
30092
+ }
30093
+ return ticks.sort((a, b) => a.value - b.value);
30094
+ }
30095
+ function placeHeadLabels(layout, candidates) {
30096
+ const { plot } = layout.static;
30097
+ const { sizes, weights } = layout.theme.fonts;
30098
+ const fontSize = sizes.body;
30099
+ const measuredHeight = layout.measureText?.("Mg", fontSize, weights.normal).height;
30100
+ const labelHeight = Math.ceil(measuredHeight ?? fontSize * 1.2) + 1;
30101
+ const spacing = Math.max(fontSize + 2, labelHeight);
30102
+ const capacity = plot.height < labelHeight ? 0 : 1 + (plot.height - labelHeight) / spacing;
30103
+ const labels = [];
30104
+ let occupied = 0;
30105
+ for (const label of candidates) {
30106
+ if (occupied + label.opacity <= capacity) {
30107
+ labels.push(label);
30108
+ occupied += label.opacity;
30109
+ } else {
30110
+ label.endLabel.text = "";
30111
+ label.endLabel.value = "";
30112
+ }
30113
+ }
30114
+ labels.sort((a, b) => a.rankPos - b.rankPos);
30115
+ const slots = labels.map((label) => {
30116
+ let slot = 0;
30117
+ let weightedY = 0;
30118
+ let weight = 0;
30119
+ for (const other of labels) {
30120
+ const delta = label.rankPos - other.rankPos;
30121
+ slot += other.opacity * Math.max(0, Math.min(1, 0.5 + 2 * delta));
30122
+ const nearby = other.opacity * Math.max(0, 1 - Math.abs(delta));
30123
+ weightedY += nearby * other.endLabel.y;
30124
+ weight += nearby;
30125
+ }
30126
+ const offset = slot * spacing;
30127
+ return { offset, preferred: weightedY / weight - offset };
30128
+ });
30129
+ const blocks = [];
30130
+ for (const [index, { preferred }] of slots.entries()) {
30131
+ const weight = labels[index].opacity;
30132
+ const block = { start: index, end: index, total: preferred * weight, weight };
30133
+ let previous = blocks.at(-1);
30134
+ while (previous && previous.total / previous.weight > block.total / block.weight) {
30135
+ block.start = previous.start;
30136
+ block.total += previous.total;
30137
+ block.weight += previous.weight;
30138
+ blocks.pop();
30139
+ previous = blocks.at(-1);
30140
+ }
30141
+ blocks.push(block);
30142
+ }
30143
+ const top = plot.y + labelHeight / 2;
30144
+ const bottom = plot.y + plot.height - labelHeight / 2;
30145
+ const minOffset = top - spacing / 2;
30146
+ const maxOffset = bottom - (occupied - 0.5) * spacing;
30147
+ for (const block of blocks) {
30148
+ const base = Math.max(minOffset, Math.min(maxOffset, block.total / block.weight));
30149
+ for (let index = block.start; index <= block.end; index++) {
30150
+ labels[index].endLabel.y = Math.max(top, Math.min(bottom, base + slots[index].offset));
30151
+ }
30152
+ }
30153
+ const painted = labels.filter(({ endLabel }) => endLabel.text || endLabel.value);
30154
+ for (const label of painted) {
30155
+ if (label.opacity <= OVERLAP_OPACITY) continue;
30156
+ let visibility = 1;
30157
+ for (const other of painted) {
30158
+ if (label === other) continue;
30159
+ const clearance = Math.abs(label.endLabel.y - other.endLabel.y);
30160
+ const fit = Math.max(0, Math.min(1, clearance - labelHeight + 1));
30161
+ const priority = Math.max(0, Math.min(1, (label.opacity - other.opacity) * 2));
30162
+ visibility = Math.min(visibility, Math.max(fit, priority));
30163
+ }
30164
+ const opacity = OVERLAP_OPACITY + (label.opacity - OVERLAP_OPACITY) * visibility;
30165
+ if (opacity < label.opacity) label.endLabel.opacity = opacity;
30166
+ }
30167
+ return labelHeight;
30168
+ }
30169
+ function lineValueTicks(domain, height) {
30170
+ const span = domain[1] - domain[0];
30171
+ if (span === 0) return [{ value: 0, opacity: 1, coarse: true }];
30172
+ const target = targetTickCount(height, "full", "y");
30173
+ const ideal = span / target;
30174
+ const ladder = valueTickLadder(span, [1, 2, 5]);
30175
+ const upper = ladder.findIndex((step) => step >= ideal);
30176
+ const pxPerUnit = height / span;
30177
+ const ticksAt = (step) => crossfadeTicks(domain, pxPerUnit, step).map((tick) => ({ ...tick, coarse: true }));
30178
+ if (upper <= 0) return ticksAt(ladder.slice(0, 1));
30179
+ const finer = ladder[upper - 1];
30180
+ const coarser = ladder[upper];
30181
+ const ratio = coarser / finer;
30182
+ if (Math.abs(ratio - Math.round(ratio)) > 1e-6) {
30183
+ return ticksAt([ideal / finer < Math.sqrt(ratio) ? finer : coarser]);
30184
+ }
30185
+ const threshold = height / target * Math.sqrt(finer / coarser);
30186
+ const coarseValues = new Set(ticksAt([coarser]).map(({ value }) => value));
30187
+ return crossfadeTicks(domain, pxPerUnit, [finer, coarser], threshold * 1.1, threshold * 0.9).map(
30188
+ (tick) => ({ ...tick, coarse: coarseValues.has(tick.value) })
30189
+ );
30190
+ }
30191
+ function fitYTickLabels(ticks, labelHeight) {
30192
+ const occupied = [];
30193
+ const byPriority = [...ticks].sort(
30194
+ (a, b) => Number(b.value === 0) - Number(a.value === 0) || Number(b.coarse) - Number(a.coarse) || a.value - b.value
30195
+ );
30196
+ for (const tick of byPriority) {
30197
+ if (!tick.label || tick.opacity <= 0.01) continue;
30198
+ const y = tick.labelPosition ?? tick.position;
30199
+ let clearance = Infinity;
30200
+ for (const position of occupied) clearance = Math.min(clearance, Math.abs(position - y));
30201
+ const opacity = Math.max(0, Math.min(1, (clearance - labelHeight) / 4));
30202
+ if (opacity === 0) tick.label = "";
30203
+ else {
30204
+ tick.labelOpacity = opacity;
30205
+ occupied.push(y);
30206
+ }
30207
+ }
30208
+ }
30209
+ var lineGeometry = (model, layout, frame) => {
30210
+ const { t } = frame;
30211
+ const { plot, xScale, window, tickFontSize, history, showValues } = layout.static;
30212
+ const xMax = window === "all" ? xScale.domain[1] : Math.max(1, t);
30213
+ const x = (period2) => xScale.range[0] + period2 / xMax * plot.width;
30214
+ const period = frame.period.index;
30215
+ const fraction = t - period;
30216
+ const active = new Map(frame.items.map((item) => [item.key, item]));
30217
+ let min4 = 0;
30218
+ let max4 = 0;
30219
+ const visible = [];
30220
+ for (const entry of history) {
30221
+ const { key, runs } = entry;
30222
+ let index = runs.length - 1;
30223
+ while (index >= 0 && runs[index].start > t) index--;
30224
+ const run = runs[index];
30225
+ const item = active.get(model.matrix.keys[key]);
30226
+ if (!run && !item) continue;
30227
+ const lastDraw = item || !run ? t : Math.min(t, run.end + 1);
30228
+ const [low2, high2] = extentAt(model, entry, lastDraw);
30229
+ min4 = Math.min(min4, low2);
30230
+ max4 = Math.max(max4, high2);
30231
+ let opacity = item?.opacity ?? 0;
30232
+ while (index >= 0 && runs[index].end + 1 > t) {
30233
+ opacity = Math.max(opacity, departingLineOpacity(runs[index], t));
30234
+ index--;
30235
+ }
30236
+ if (opacity > 0) {
30237
+ const age = run ? Math.max(0, t - run.end) : 0;
30238
+ visible.push({
30239
+ key,
30240
+ opacity,
30241
+ rankPos: (item?.rankPos ?? model.timeline.rankPos(key, t)) + age,
30242
+ departing: !item || item.rank >= model.timeline.top
30243
+ });
30244
+ }
30245
+ }
30246
+ visible.sort(
30247
+ (a, b) => Number(a.departing) - Number(b.departing) || b.opacity - a.opacity || a.rankPos - b.rankPos
30248
+ );
30249
+ min4 = roundBound(min4);
30250
+ max4 = roundBound(max4);
30251
+ const divisor = Number.isFinite(max4 - min4) ? 1 : 2;
30252
+ const low = min4 / divisor;
30253
+ const high = max4 / divisor;
30254
+ const span = high - low;
30255
+ const y = (value) => plot.y + plot.height * (span === 0 ? 1 : (high - value / divisor) / span);
30256
+ const text = lineText(layout, layout.theme.fonts.sizes.body);
30257
+ const series = [];
30258
+ const labels = [];
30259
+ const anchors = [];
30260
+ for (const { key, opacity, rankPos } of visible) {
30261
+ const values = model.matrix.values[key];
30262
+ const points = Array.from(
30263
+ values.subarray(0, period + 1),
30264
+ (value2, index) => Number.isFinite(value2) ? { x: x(index), y: y(value2) } : null
30265
+ );
30266
+ const head = interpolateRaceValue(values, period, fraction);
30267
+ if (fraction > 0) points.push(Number.isFinite(head) ? { x: x(t), y: y(head) } : null);
30268
+ let last = points.length - 1;
30269
+ while (last >= 0 && points[last] === null) last--;
30270
+ const anchor = points[last];
30271
+ if (!anchor) continue;
30272
+ const labelX = anchor.x + LABEL_GAP4;
30273
+ const budget = layout.area.x + layout.area.width - labelX;
30274
+ const valueText = showValues ? model.formatValue(Number.isFinite(head) ? head : values[last]) : "";
30275
+ const value = text.width(valueText) <= budget ? valueText : "";
30276
+ const name = text.fit(layout.labels[key], budget - (value ? text.width(` ${value}`) : 0));
30277
+ const endLabel = { x: labelX, y: anchor.y, text: name, value };
30278
+ series.push({
30279
+ key: model.matrix.keys[key],
30280
+ color: layout.colors[key],
30281
+ opacity,
30282
+ points,
30283
+ endLabel
30284
+ });
30285
+ labels.push({ endLabel, opacity, rankPos });
30286
+ anchors.push(anchor);
30287
+ }
30288
+ const labelHeight = placeHeadLabels(layout, labels);
30289
+ for (const [index, { endLabel, opacity }] of labels.entries()) {
30290
+ const anchor = anchors[index];
30291
+ const displacement = Math.abs(anchor.y - endLabel.y);
30292
+ const strength = Math.min(1, 2 * displacement / labelHeight - 1);
30293
+ if ((endLabel.text || endLabel.value) && strength > 0) {
30294
+ endLabel.leader = { ...anchor, opacity: strength * (endLabel.opacity ?? opacity) * 0.45 };
30295
+ }
30296
+ }
30297
+ const tickText = lineText(layout, tickFontSize);
30298
+ const showAxes = plot.width > 0 && plot.height > 0;
30299
+ const yTicks = !showAxes ? [] : lineValueTicks([low, high], plot.height).map((tick) => {
30300
+ const value = tick.value * divisor;
30301
+ const position = y(value);
30302
+ const distanceToEdge = Math.max(
30303
+ 0,
30304
+ Math.min(position - plot.y, plot.y + plot.height - position)
30305
+ );
30306
+ const edgeOpacity = value === 0 ? 1 : Math.min(1, distanceToEdge / tickFontSize);
30307
+ return {
30308
+ value,
30309
+ opacity: tick.opacity * edgeOpacity,
30310
+ position,
30311
+ labelPosition: value === 0 ? Math.min(position, plot.y + plot.height - tickFontSize * 0.75) : position,
30312
+ coarse: tick.coarse,
30313
+ label: tickText.fit(
30314
+ model.formatValue(value),
30315
+ layout.static.yAxisX - layout.area.x - TICK_GAP
30316
+ )
30317
+ };
30318
+ });
30319
+ const tickHeight = layout.measureText?.(
30320
+ "Mg",
30321
+ tickFontSize,
30322
+ layout.theme.fonts.weights.normal
30323
+ ).height;
30324
+ fitYTickLabels(yTicks, tickHeight ?? tickFontSize * 1.2);
30325
+ return {
30326
+ mark: "line",
30327
+ series,
30328
+ xTicks: showAxes ? periodTicks(layout, period, x, xMax) : [],
30329
+ yTicks,
30330
+ domain: [min4, max4]
30331
+ };
30332
+ };
30333
+
30334
+ // src/race/layout-table.ts
30335
+ import { format } from "d3-format";
30336
+ var DEFAULT_COLUMNS2 = ["rank", "change", "name", "bar", "value", "share"];
30337
+ var LABELS = {
30338
+ rank: "Rank",
30339
+ change: "Change",
30340
+ name: "Name",
30341
+ bar: "",
30342
+ value: "Value",
30343
+ share: "Share"
30344
+ };
30345
+ var COMPACT_WIDTH4 = 520;
30346
+ var COMPACT_CHANGE = "\u2195";
30347
+ var CHIP_WIDTH_AND_GAP = 14;
30348
+ var EMPTY = "\u2014";
30349
+ var formatShare = format(".1%");
30350
+ var VALUE_WIDTH_SAMPLES = [0.25, 0.5, 0.75, Math.SQRT1_2];
30351
+ function frameShareBase(values, period, fraction) {
30352
+ let total = 0;
30353
+ let magnitude = 0;
30354
+ for (const series of values) {
30355
+ const value = interpolateRaceValue(series, period, fraction);
30356
+ if (!Number.isFinite(value)) continue;
30357
+ if (value < 0) return null;
30358
+ total += value;
30359
+ magnitude = Math.max(magnitude, value);
30360
+ }
30361
+ if (Number.isFinite(total)) return { total, scale: 1 };
30362
+ total = 0;
30363
+ for (const series of values) {
30364
+ const value = interpolateRaceValue(series, period, fraction);
30365
+ if (Number.isFinite(value)) total += value / magnitude;
30366
+ }
30367
+ return { total, scale: magnitude };
30368
+ }
30369
+ function shareText(value, base) {
30370
+ if (!base || base.total === 0) return EMPTY;
30371
+ const share = value / base.scale / base.total;
30372
+ return Number.isFinite(share * 100) ? formatShare(share) : EMPTY;
30373
+ }
30374
+ var modelData = /* @__PURE__ */ new WeakMap();
30375
+ function tableData(model) {
30376
+ const cached = modelData.get(model);
30377
+ if (cached) return cached;
30378
+ const data = {
30379
+ keyIndices: new Map(model.matrix.keys.map((key, index) => [key, index]))
30380
+ };
30381
+ modelData.set(model, data);
30382
+ return data;
30383
+ }
30384
+ function digitPattern(text) {
30385
+ return text.replace(/\d/g, "0");
30386
+ }
30387
+ function collectValueLabels({ matrix, formatValue: formatValue3 }) {
30388
+ const labels = /* @__PURE__ */ new Set([EMPTY]);
30389
+ for (const series of matrix.values) {
30390
+ for (let period = 0; period < series.length; period++) {
30391
+ const value = series[period];
30392
+ if (!Number.isFinite(value)) continue;
30393
+ labels.add(digitPattern(formatValue3(value)));
30394
+ const next = series[period + 1];
30395
+ if (!Number.isFinite(next) || next === value) continue;
30396
+ for (const fraction of VALUE_WIDTH_SAMPLES) {
30397
+ const between = interpolateRaceValue(series, period, fraction);
30398
+ if (Number.isFinite(between)) labels.add(digitPattern(formatValue3(between)));
30399
+ }
30400
+ }
30401
+ }
30402
+ return labels;
30403
+ }
30404
+ function measureColumns(model, { labels, theme }, columns, measureText, headings, cellPadding) {
30405
+ const { body: fontSize } = theme.fonts.sizes;
30406
+ const { normal, semibold } = theme.fonts.weights;
30407
+ const { top } = model.timeline;
30408
+ const measure = (text, weight = normal) => measureText(text, fontSize, weight).width;
30409
+ const digits = Array.from("0123456789", (digit) => ({ digit, width: measure(digit) }));
30410
+ const { digit: widestDigit } = digits.reduce(
30411
+ (widest, digit) => digit.width > widest.width ? digit : widest
30412
+ );
30413
+ const measureNumber = (pattern) => measure(pattern.replace(/0/g, widestDigit)) + 1;
30414
+ const measureNumbers = (patterns) => {
30415
+ let width = 0;
30416
+ for (const pattern of patterns ?? []) width = Math.max(width, measureNumber(pattern));
30417
+ return width;
30418
+ };
30419
+ const data = tableData(model);
30420
+ const valueLabels = columns.includes("value") ? data.valueLabels ??= collectValueLabels(model) : void 0;
30421
+ const emptyWidth = measure(EMPTY);
30422
+ const maxChange = digitPattern(String(Math.max(0, top - 1)));
30423
+ const widths = {
30424
+ rank: Math.max(emptyWidth, measureNumber(digitPattern(String(top)))),
30425
+ change: Math.max(
30426
+ emptyWidth,
30427
+ measure("new"),
30428
+ measureNumber(`\u2191${maxChange}`),
30429
+ measureNumber(`\u2193${maxChange}`)
30430
+ ),
30431
+ name: labels.reduce((width, label) => Math.max(width, measure(label)), 0) + CHIP_WIDTH_AND_GAP,
30432
+ bar: 0,
30433
+ value: measureNumbers(valueLabels),
30434
+ // Gaps can leave a single key with a 100% share between observations.
30435
+ share: Math.max(emptyWidth, measureNumber(digitPattern(formatShare(1))))
28510
30436
  };
30437
+ for (const column of columns) {
30438
+ if (column === "bar") continue;
30439
+ widths[column] = Math.ceil(Math.max(widths[column], measure(headings[column], semibold))) + 2 * cellPadding;
30440
+ }
30441
+ return widths;
30442
+ }
30443
+ function fitColumns(columns, widths, area3) {
30444
+ const fixed = columns.filter((column) => column !== "bar");
30445
+ const fixedWidth = fixed.reduce((sum, column) => sum + widths[column], 0);
30446
+ if (columns.includes("name")) {
30447
+ const nameBudget = Math.max(0, area3.width - (fixedWidth - widths.name));
30448
+ widths.name = columns.includes("bar") ? Math.min(widths.name, nameBudget) : nameBudget;
30449
+ }
30450
+ const fittedWidth = fixed.reduce((sum, column) => sum + widths[column], 0);
30451
+ const shrink = fittedWidth > area3.width ? area3.width / fittedWidth : 1;
30452
+ widths.bar = Math.max(0, area3.width - fittedWidth);
30453
+ let x = area3.x;
30454
+ return columns.map((column) => {
30455
+ const width = widths[column] * shrink;
30456
+ const position = { column, x, width };
30457
+ x += width;
30458
+ return position;
30459
+ });
30460
+ }
30461
+ var computeTableStatic = (model, base, mark, measureText) => {
30462
+ const { area: area3, theme } = base;
30463
+ const fontSize = theme.fonts.sizes.body;
30464
+ const headerHeight = Math.min(area3.height, fontSize + 12);
30465
+ const requested = mark.columns ?? DEFAULT_COLUMNS2;
30466
+ const compact = area3.width < COMPACT_WIDTH4;
30467
+ const columns = requested.filter(
30468
+ (column) => column !== "bar" || !compact || requested.length === 1
30469
+ );
30470
+ const compactChange = compact && columns.includes("name");
30471
+ const labels = { ...LABELS, change: compactChange ? COMPACT_CHANGE : LABELS.change };
30472
+ const bodyHeight = area3.height - headerHeight;
30473
+ const cellPadding = compact ? 1.5 : 5;
30474
+ return {
30475
+ headerHeight,
30476
+ bodyHeight,
30477
+ rowHeight: bodyHeight / model.timeline.top,
30478
+ compactChange,
30479
+ cellPadding,
30480
+ fontSize,
30481
+ labels,
30482
+ columns: fitColumns(
30483
+ columns,
30484
+ measureColumns(model, base, columns, measureText, labels, cellPadding),
30485
+ area3
30486
+ )
30487
+ };
30488
+ };
30489
+ function changeCell(rank, previous, top) {
30490
+ if (rank === previous) return { column: "change", direction: "same", text: "" };
30491
+ if (previous >= top) return { column: "change", direction: "new", text: "new" };
30492
+ if (rank < previous) return { column: "change", direction: "up", text: `\u2191${previous - rank}` };
30493
+ return { column: "change", direction: "down", text: `\u2193${rank - previous}` };
30494
+ }
30495
+ function poolRows(rows, gap, inset, bottom) {
30496
+ const gaps = [0];
30497
+ for (let index = 1; index < rows.length; index++) {
30498
+ const clearance = rows[index].y - rows[index - 1].y;
30499
+ gaps.push(gaps[index - 1] + Math.min(gap, clearance * 1.5));
30500
+ }
30501
+ const blocks = [];
30502
+ for (const [index, row] of rows.entries()) {
30503
+ const block = {
30504
+ start: index,
30505
+ end: index,
30506
+ total: (row.y + inset - gaps[index]) * row.opacity,
30507
+ weight: row.opacity
30508
+ };
30509
+ let previous = blocks.at(-1);
30510
+ while (previous && previous.total / previous.weight > block.total / block.weight) {
30511
+ block.start = previous.start;
30512
+ block.total += previous.total;
30513
+ block.weight += previous.weight;
30514
+ blocks.pop();
30515
+ previous = blocks.at(-1);
30516
+ }
30517
+ blocks.push(block);
30518
+ }
30519
+ const targets = new Array(rows.length);
30520
+ for (const block of blocks) {
30521
+ const base = Math.max(0, Math.min(bottom - (gaps.at(-1) ?? 0), block.total / block.weight));
30522
+ for (let index = block.start; index <= block.end; index++) targets[index] = base + gaps[index];
30523
+ }
30524
+ return targets;
30525
+ }
30526
+ function contentOffsets(rows, { rowHeight, fontSize, bodyHeight }) {
30527
+ const paintHeight = Math.max(0, rowHeight - 1);
30528
+ const textHeight = Math.min(paintHeight, fontSize * 1.2);
30529
+ const inset = (paintHeight - textHeight) / 2;
30530
+ const visible = rows.filter(({ opacity }) => opacity > 0).sort((a, b) => a.y - b.y);
30531
+ const edge = visible.at(-1);
30532
+ const edgeRoom = edge?.atEdge ? Math.max(0, edge.y - (bodyHeight - rowHeight)) * edge.opacity : 0;
30533
+ const progress = rowHeight > 0 ? Math.min(1, edgeRoom / rowHeight) : 0;
30534
+ const bottom = Math.max(0, bodyHeight - textHeight);
30535
+ const gap = Math.min(rowHeight, textHeight + 2, bottom / Math.max(1, visible.length - 1));
30536
+ const targets = poolRows(
30537
+ visible,
30538
+ gap,
30539
+ inset,
30540
+ Math.max(bottom, edge?.atEdge ? edge.y + inset : 0)
30541
+ );
30542
+ const interior = progress > 0 ? poolRows(visible.slice(0, -1), gap, inset, Math.max(0, bottom - edgeRoom)) : targets;
30543
+ for (const [index, row] of visible.entries()) {
30544
+ const top = row.y + inset;
30545
+ const offset = (targets[index] - top) * (1 - progress) + ((interior[index] ?? top) - top) * progress;
30546
+ if (Math.abs(offset) > 1e-3) row.contentOffset = offset;
30547
+ }
30548
+ }
30549
+ var tableGeometry = (model, { static: stat }, frame) => {
30550
+ const { rowHeight, columns } = stat;
30551
+ const { timeline, matrix } = model;
30552
+ const {
30553
+ t,
30554
+ items,
30555
+ period: { index: period },
30556
+ domain: [min4, max4]
30557
+ } = frame;
30558
+ const { top } = timeline;
30559
+ const data = tableData(model);
30560
+ const shareBase = columns.some(({ column }) => column === "share") ? frameShareBase(matrix.values, period, t - period) : null;
30561
+ const magnitude = Math.max(-min4, max4) || 1;
30562
+ const span = max4 / magnitude - min4 / magnitude || 1;
30563
+ const lastSlot = top - 1;
30564
+ let cutoff = items[top]?.rankPos ?? top;
30565
+ for (let index = 1; index < items.length; index++) {
30566
+ const inner = items[index - 1].rankPos;
30567
+ const outer = items[index].rankPos;
30568
+ cutoff = Math.min(cutoff, outer + 2 * Math.max(0, lastSlot - inner));
30569
+ }
30570
+ const visible = items.filter(({ rankPos }) => rankPos < cutoff).sort((a, b) => a.rank - b.rank);
30571
+ const rows = visible.map((item, rank) => {
30572
+ const keyIndex = data.keyIndices.get(item.key);
30573
+ if (keyIndex === void 0) throw new Error(`Unknown race table key: ${item.key}`);
30574
+ const position = item.rankPos;
30575
+ const atEdge = position > lastSlot;
30576
+ const y = position * rowHeight;
30577
+ const previous = period > 0 ? timeline.periodRank(keyIndex, period - 1) : rank;
30578
+ const motion = timeline.rankPos(keyIndex, t + 1e-3) - timeline.rankPos(keyIndex, t - 1e-3);
30579
+ const settled = !atEdge && (t === timeline.periodCount - 1 || Math.abs(motion) < 1e-6 && Math.abs(item.rankPos - rank) < 1e-6);
30580
+ const cells = columns.map(({ column, width }) => {
30581
+ switch (column) {
30582
+ case "rank":
30583
+ return { column, text: String(rank + 1) };
30584
+ case "change":
30585
+ return changeCell(rank, settled ? previous : rank, top);
30586
+ case "name":
30587
+ return { column, text: item.label, color: item.color };
30588
+ case "bar": {
30589
+ const value = item.value / magnitude;
30590
+ const x = (Math.min(0, value) - min4 / magnitude) / span * width;
30591
+ return { column, x, width: Math.abs(value) / span * width, color: item.color };
30592
+ }
30593
+ case "share":
30594
+ return { column, text: shareText(item.value, shareBase) };
30595
+ }
30596
+ return { column, text: item.valueLabel };
30597
+ });
30598
+ return {
30599
+ row: {
30600
+ key: item.key,
30601
+ rank,
30602
+ y,
30603
+ opacity: Math.min(1, cutoff - position),
30604
+ atEdge,
30605
+ contentOffset: 0,
30606
+ cells
30607
+ },
30608
+ movesUp: motion < 0
30609
+ };
30610
+ });
30611
+ rows.sort((a, b) => Number(a.movesUp) - Number(b.movesUp));
30612
+ const ordered = rows.map(({ row }) => row);
30613
+ contentOffsets(ordered, stat);
30614
+ return { mark: "table", rows: ordered };
30615
+ };
30616
+
30617
+ // src/race/marks.ts
30618
+ var RACE_MARKS = {
30619
+ bar: {
30620
+ computeStatic(model, layout, mark, measureText) {
30621
+ const { area: area3, labels, theme } = layout;
30622
+ const { body, axisTick } = theme.fonts.sizes;
30623
+ const { normal } = theme.fonts.weights;
30624
+ const measureWidth = (text) => measureText(text, body, normal).width;
30625
+ let maxLabelWidth = 0;
30626
+ for (const label of labels) {
30627
+ maxLabelWidth = Math.max(maxLabelWidth, measureWidth(label));
30628
+ }
30629
+ let min4 = Infinity;
30630
+ let max4 = -Infinity;
30631
+ for (const series of model.matrix.values) {
30632
+ for (const value of series) {
30633
+ if (!Number.isFinite(value)) continue;
30634
+ min4 = Math.min(min4, value);
30635
+ max4 = Math.max(max4, value);
30636
+ }
30637
+ }
30638
+ return computeBarStatic({
30639
+ area: area3,
30640
+ top: model.timeline.top,
30641
+ maxLabelWidth,
30642
+ maxValueLabelWidth: Math.max(
30643
+ measureWidth(model.formatValue(min4)),
30644
+ measureWidth(model.formatValue(max4)),
30645
+ measureWidth(model.formatValue(min4 / 2 + max4 / 2))
30646
+ ),
30647
+ cornerRadius: mark.cornerRadius ?? 0,
30648
+ fontSize: { name: body, value: body, tick: axisTick },
30649
+ showPeriod: model.spec.race.period !== false,
30650
+ measurePeriodWidth(fontSize) {
30651
+ const labels2 = new Set(model.periodLabels.map((label) => label.replace(/\d/g, "0")));
30652
+ let width = 0;
30653
+ for (const label of labels2)
30654
+ width = Math.max(width, measureText(label, fontSize, 600).width);
30655
+ return width;
30656
+ },
30657
+ showSummary: model.spec.race.summary === "sum",
30658
+ hasNegatives: min4 < 0
30659
+ });
30660
+ },
30661
+ geometry(model, layout, frame) {
30662
+ const { measureText, theme } = layout;
30663
+ return barGeometry(layout.static, frame, model.formatValue, {
30664
+ fontSize: theme.fonts.sizes.body,
30665
+ fontWeight: theme.fonts.weights.normal,
30666
+ measureWidth: measureText && ((text, size, weight) => measureText(text, size, weight).width)
30667
+ });
30668
+ }
30669
+ },
30670
+ line: { computeStatic: computeLineStatic, geometry: lineGeometry },
30671
+ table: { computeStatic: computeTableStatic, geometry: tableGeometry }
30672
+ };
30673
+ function raceMarkEntry(mark) {
30674
+ const entry = RACE_MARKS[mark];
30675
+ if (!Object.hasOwn(RACE_MARKS, mark) || !entry) {
30676
+ throw new Error(
30677
+ `Race mark "${mark}" is not registered. Registered: ${Object.keys(RACE_MARKS).join(", ")}`
30678
+ );
30679
+ }
30680
+ return entry;
30681
+ }
30682
+ function layoutForRaceMark(model, base, mark, measureText) {
30683
+ const entry = raceMarkEntry(mark.type);
30684
+ return { ...base, mark: mark.type, static: entry.computeStatic(model, base, mark, measureText) };
30685
+ }
30686
+
30687
+ // src/race/geometry.ts
30688
+ function frameAt(model, t, colors, labels) {
30689
+ if (!Number.isFinite(t)) throw new RangeError("Race frame time must be finite.");
30690
+ const { matrix, timeline, spec, periodLabels, formatValue: formatValue3 } = model;
30691
+ return buildRaceFrame(timeline.sample(t), {
30692
+ keys: matrix.keys,
30693
+ labels,
30694
+ colors,
30695
+ formatValue: formatValue3,
30696
+ periods: matrix.periods,
30697
+ periodLabels,
30698
+ summary: spec.race.summary === "sum",
30699
+ top: timeline.top
30700
+ });
30701
+ }
30702
+ function raceFrameAt(model, t) {
30703
+ return frameAt(model, t, model.frameColors, model.matrix.labels);
30704
+ }
30705
+ function geometryForMark(model, layout, frame) {
30706
+ return raceMarkEntry(layout.mark).geometry(model, layout, frame);
30707
+ }
30708
+ function raceGeometryAt(model, layout, t) {
30709
+ return geometryForMark(model, layout, frameAt(model, t, layout.colors, layout.labels));
30710
+ }
30711
+
30712
+ // src/race/layout.ts
30713
+ import {
30714
+ adaptTheme as adaptTheme7,
30715
+ computeChrome as computeChrome9,
30716
+ estimateTextWidth as estimateTextWidth33,
30717
+ mergeThemeConfig as mergeThemeConfig8,
30718
+ resolveTheme as resolveTheme9
30719
+ } from "@opendata-ai/openchart-core";
30720
+
30721
+ // src/race/a11y.ts
30722
+ var MAX_PERIOD_ROWS = 60;
30723
+ var metadataByModel = /* @__PURE__ */ new WeakMap();
30724
+ function accessibleLabel(matrix, key) {
30725
+ return matrix.labels[key].trim() || matrix.keys[key].trim() || "Unnamed entry";
30726
+ }
30727
+ function raceA11yLeaders(model, t) {
30728
+ return model.timeline.ranked(t).slice(0, Math.min(model.timeline.top, 3)).map((key) => accessibleLabel(model.matrix, key));
30729
+ }
30730
+ function describeRace(model, first, last) {
30731
+ const { matrix, periodLabels } = model;
30732
+ const startLabel = periodLabels[0];
30733
+ const endLabel = periodLabels[periodLabels.length - 1];
30734
+ const lead = (ranked, period) => ranked.length ? `${accessibleLabel(matrix, ranked[0])} leads in ${period}.` : `No ranked entries in ${period}.`;
30735
+ const sentences = [
30736
+ `${startLabel} to ${endLabel}.`,
30737
+ lead(first, startLabel),
30738
+ lead(last, endLabel)
30739
+ ];
30740
+ const startRanks = new Map(first.map((key, rank) => [key, rank + 1]));
30741
+ let biggestClimb = 0;
30742
+ let climberSentence;
30743
+ last.forEach((key, rank) => {
30744
+ const startRank = startRanks.get(key);
30745
+ const endRank = rank + 1;
30746
+ if (startRank !== void 0 && startRank - endRank > biggestClimb) {
30747
+ biggestClimb = startRank - endRank;
30748
+ climberSentence = `${accessibleLabel(matrix, key)} climbs the most, from rank ${startRank} to rank ${endRank}.`;
30749
+ }
30750
+ });
30751
+ if (climberSentence) sentences.push(climberSentence);
30752
+ return sentences.join(" ");
30753
+ }
30754
+ function buildMetadata(model) {
30755
+ const { matrix, periodLabels, timeline, formatValue: formatValue3, spec } = model;
30756
+ const { hidden, table, description } = spec.a11y ?? {};
30757
+ const { periodCount, top } = timeline;
30758
+ const lastPeriod = periodCount - 1;
30759
+ const rowCount = Math.min(periodCount, MAX_PERIOD_ROWS);
30760
+ const showTable = !hidden && table !== false;
30761
+ const first = timeline.ranked(0);
30762
+ const last = timeline.ranked(lastPeriod);
30763
+ const dataTableFallback = [];
30764
+ if (showTable) {
30765
+ dataTableFallback.push(["Period", ...Array.from({ length: top }, (_, i) => `Rank ${i + 1}`)]);
30766
+ for (let row = 0; row < rowCount; row++) {
30767
+ const period = Math.round(row * lastPeriod / (rowCount - 1));
30768
+ const ranked = period === 0 ? first : period === lastPeriod ? last : timeline.ranked(period);
30769
+ const values = Array.from({ length: top }, (_, rank) => {
30770
+ const key = ranked[rank];
30771
+ return key === void 0 ? "" : `${accessibleLabel(matrix, key)} (${formatValue3(matrix.values[key][period])})`;
30772
+ });
30773
+ dataTableFallback.push([periodLabels[period], ...values]);
30774
+ }
30775
+ }
30776
+ return {
30777
+ altText: description ?? describeRace(model, first, last),
30778
+ dataTableFallback,
30779
+ role: "img",
30780
+ keyboardNavigable: false,
30781
+ ...hidden && { hidden },
30782
+ ...showTable && rowCount < periodCount && { totalRows: periodCount }
30783
+ };
30784
+ }
30785
+ function raceA11y(model) {
30786
+ let metadata = metadataByModel.get(model);
30787
+ if (!metadata) {
30788
+ metadata = buildMetadata(model);
30789
+ metadataByModel.set(model, metadata);
30790
+ }
30791
+ return { ...metadata, dataTableFallback: metadata.dataTableFallback.map((row) => [...row]) };
30792
+ }
30793
+
30794
+ // src/race/colors.ts
30795
+ import { CATEGORICAL_PALETTE as CATEGORICAL_PALETTE3 } from "@opendata-ai/openchart-core";
30796
+ function firstAppearanceOrder(timeline) {
30797
+ const { samplesPerPeriod, keyCount, periodCount, top } = timeline;
30798
+ const periods = Array.from({ length: periodCount }, () => []);
30799
+ for (let key = 0; key < keyCount; key++) {
30800
+ const { exact, smoothed } = timeline.rankSamples(key);
30801
+ for (let period = 0; period < periodCount; period++) {
30802
+ const sample = period * samplesPerPeriod;
30803
+ const rank = smoothed[sample];
30804
+ if (rank < top - VISIBILITY_EPSILON && exact[sample] < keyCount) {
30805
+ periods[period].push({ key, rank });
30806
+ }
30807
+ }
30808
+ }
30809
+ const order = /* @__PURE__ */ new Set();
30810
+ for (const items of periods) {
30811
+ items.sort((a, b) => a.rank - b.rank || a.key - b.key);
30812
+ for (const { key } of items) order.add(key);
30813
+ }
30814
+ for (let key = 0; key < keyCount; key++) order.add(key);
30815
+ return [...order];
30816
+ }
30817
+ function collectConflicts(matrix, timeline) {
30818
+ const { keyCount, samplesPerPeriod, top } = timeline;
30819
+ const stride = samplesPerPeriod % 4 === 0 ? 4 : 1;
30820
+ const scoresPerPeriod = samplesPerPeriod / stride;
30821
+ const count = (timeline.periodCount - 1) * scoresPerPeriod + 1;
30822
+ const frames = Array.from(
30823
+ { length: count },
30824
+ () => []
30825
+ );
30826
+ const minOpacity = 0.1;
30827
+ const threshold = top - minOpacity;
30828
+ const trailWeights = new Float64Array(count);
30829
+ for (let key = 0; key < keyCount; key++) {
30830
+ const { exact, smoothed } = timeline.rankSamples(key);
30831
+ let wasVisible = false;
30832
+ for (let score = 0; score < count; score++) {
30833
+ const sample = score * stride;
30834
+ if (smoothed[sample] >= threshold || exact[sample] === keyCount) continue;
30835
+ frames[score].push({ key, rank: exact[sample], weight: Math.min(1, top - smoothed[sample]) });
30836
+ wasVisible = true;
30837
+ }
30838
+ if (!wasVisible && !smoothed.some((rank) => rank < threshold)) continue;
30839
+ trailWeights.fill(0);
30840
+ let first = count;
30841
+ let last = 0;
30842
+ for (const run of lineVisibilityRuns(timeline, key, matrix.values[key])) {
30843
+ const start = Math.ceil(run.end * scoresPerPeriod);
30844
+ const expiry = Math.min(count, Math.ceil((run.end + 1) * scoresPerPeriod));
30845
+ first = Math.min(first, start);
30846
+ last = Math.max(last, expiry);
30847
+ for (let score = start; score < expiry; score++) {
30848
+ const sample = score * stride;
30849
+ if (smoothed[sample] < threshold && exact[sample] < keyCount) continue;
30850
+ const opacity = departingLineOpacity(run, score / scoresPerPeriod);
30851
+ trailWeights[score] = Math.max(opacity, trailWeights[score]);
30852
+ }
30853
+ }
30854
+ for (let score = first; score < last; score++) {
30855
+ if (trailWeights[score] > minOpacity)
30856
+ frames[score].push({ key, rank: top, weight: trailWeights[score] });
30857
+ }
30858
+ }
30859
+ const comparisons = frames.reduce((sum, frame) => sum + frame.length ** 2, 0);
30860
+ const dense = keyCount <= 1024 && comparisons > keyCount ** 2 ? new Float64Array(keyCount ** 2) : void 0;
30861
+ const sparse = dense ? [] : matrix.keys.map(() => /* @__PURE__ */ new Map());
30862
+ for (const ranked of frames) {
30863
+ for (let index = 0; index < ranked.length; index++) {
30864
+ const a = ranked[index];
30865
+ for (let other = index + 1; other < ranked.length; other++) {
30866
+ const b = ranked[other];
30867
+ const gap = Math.max(1, Math.abs(a.rank - b.rank));
30868
+ const weight = gap === 1 ? 64 : gap === 2 ? 16 : gap === 3 ? 4 : 1;
30869
+ const contribution = weight * Math.min(a.weight, b.weight);
30870
+ if (dense) dense[a.key * keyCount + b.key] += contribution;
30871
+ else sparse[a.key].set(b.key, (sparse[a.key].get(b.key) ?? 0) + contribution);
30872
+ }
30873
+ }
30874
+ }
30875
+ const graph = matrix.keys.map(() => ({ keys: [], weights: [], total: 0 }));
30876
+ function connect(a, b, weight) {
30877
+ graph[a].keys.push(b);
30878
+ graph[a].weights.push(weight);
30879
+ graph[a].total += weight;
30880
+ graph[b].keys.push(a);
30881
+ graph[b].weights.push(weight);
30882
+ graph[b].total += weight;
30883
+ }
30884
+ for (let a = 0; a < keyCount; a++) {
30885
+ if (dense) {
30886
+ for (let b = a + 1; b < keyCount; b++) {
30887
+ const weight = dense[a * keyCount + b];
30888
+ if (weight > 0) connect(a, b, weight);
30889
+ }
30890
+ } else {
30891
+ for (const [b, weight] of sparse[a]) connect(a, b, weight);
30892
+ }
30893
+ }
30894
+ return graph;
30895
+ }
30896
+ function conflictAwareSlots(order, conflicts, paletteSize, slots) {
30897
+ const uses = new Array(paletteSize).fill(0);
30898
+ for (const slot of slots) {
30899
+ if (slot >= 0) uses[slot]++;
30900
+ }
30901
+ function costsFor(key) {
30902
+ const costs = uses.map(() => 0);
30903
+ const { keys, weights } = conflicts[key];
30904
+ for (let index = 0; index < keys.length; index++) {
30905
+ const slot = slots[keys[index]];
30906
+ if (slot >= 0) costs[slot] += weights[index];
30907
+ }
30908
+ return costs;
30909
+ }
30910
+ const priority = [...order].sort((a, b) => conflicts[b].total - conflicts[a].total);
30911
+ for (const key of priority) {
30912
+ const costs = costsFor(key);
30913
+ const slot = costs.reduce(
30914
+ (best, cost, candidate) => cost < costs[best] || cost === costs[best] && uses[candidate] < uses[best] ? candidate : best,
30915
+ 0
30916
+ );
30917
+ slots[key] = slot;
30918
+ uses[slot]++;
30919
+ }
30920
+ let improved = true;
30921
+ while (improved) {
30922
+ improved = false;
30923
+ for (const key of priority) {
30924
+ const current = slots[key];
30925
+ const costs = costsFor(key);
30926
+ const best = costs.reduce(
30927
+ (slot, cost, candidate) => cost < costs[slot] ? candidate : slot,
30928
+ current
30929
+ );
30930
+ if (best !== current) {
30931
+ slots[key] = best;
30932
+ improved = true;
30933
+ }
30934
+ }
30935
+ }
30936
+ }
30937
+ function seedSlots(matrix, categoryField, previous) {
30938
+ const seeds = /* @__PURE__ */ new Map();
30939
+ if (!previous) return seeds;
30940
+ const { encoding } = previous.spec;
30941
+ const color = encoding.color;
30942
+ if (color && "value" in color) return seeds;
30943
+ const previousCategory = color?.field === encoding.key.field ? void 0 : color?.field;
30944
+ if (categoryField !== previousCategory) return seeds;
30945
+ const previousIndices = new Map(previous.matrix.keys.map((key, index) => [key, index]));
30946
+ const matching = matrix.keys.map((key, index) => {
30947
+ const oldIndex = previousIndices.get(key);
30948
+ if (oldIndex === void 0) return -1;
30949
+ if (categoryField && previous.matrix.colorValues[oldIndex] !== matrix.colorValues[index])
30950
+ return -1;
30951
+ return oldIndex;
30952
+ });
30953
+ for (const [size, slots] of previous.colorAssignment.byPaletteSize) {
30954
+ seeds.set(
30955
+ size,
30956
+ matching.map((index) => {
30957
+ const slot = slots[index];
30958
+ return typeof slot === "number" ? slot : -1;
30959
+ })
30960
+ );
30961
+ }
30962
+ return seeds;
30963
+ }
30964
+ function assignRaceColors(matrix, timeline, colorEncoding, keyField, previous) {
30965
+ const byPaletteSize = /* @__PURE__ */ new Map();
30966
+ if (colorEncoding && "value" in colorEncoding) {
30967
+ const slots = matrix.keys.map(() => colorEncoding.value);
30968
+ return { slotsFor: () => slots, byPaletteSize };
30969
+ }
30970
+ const order = firstAppearanceOrder(timeline);
30971
+ const field = colorEncoding?.field;
30972
+ const categoryField = field === keyField ? void 0 : field;
30973
+ const seeds = seedSlots(matrix, categoryField, previous);
30974
+ let conflicts;
30975
+ return {
30976
+ byPaletteSize,
30977
+ slotsFor(size) {
30978
+ const paletteSize = size || CATEGORICAL_PALETTE3.length;
30979
+ const cached = byPaletteSize.get(paletteSize);
30980
+ if (cached) return cached;
30981
+ const slots = seeds.get(paletteSize) ?? matrix.keys.map(() => -1);
30982
+ const unassigned = order.filter((key) => slots[key] < 0);
30983
+ if (categoryField || paletteSize >= slots.length) {
30984
+ const byGroup = /* @__PURE__ */ new Map();
30985
+ const used = /* @__PURE__ */ new Set();
30986
+ const group = (key) => categoryField ? matrix.colorValues[key] : key;
30987
+ for (const key of order) {
30988
+ if (slots[key] < 0) continue;
30989
+ byGroup.set(group(key), slots[key]);
30990
+ used.add(slots[key]);
30991
+ }
30992
+ const uses = new Array(paletteSize).fill(0);
30993
+ for (const slot of used) uses[slot % paletteSize]++;
30994
+ for (const key of unassigned) {
30995
+ const id = group(key);
30996
+ let slot = byGroup.get(id);
30997
+ if (slot === void 0) {
30998
+ const effective = uses.reduce(
30999
+ (best, count, candidate) => count < uses[best] ? candidate : best,
31000
+ 0
31001
+ );
31002
+ slot = effective;
31003
+ while (used.has(slot)) slot += paletteSize;
31004
+ used.add(slot);
31005
+ uses[effective]++;
31006
+ byGroup.set(id, slot);
31007
+ }
31008
+ slots[key] = slot;
31009
+ }
31010
+ } else if (unassigned.length > 0) {
31011
+ conflicts ??= collectConflicts(matrix, timeline);
31012
+ conflictAwareSlots(unassigned, conflicts, paletteSize, slots);
31013
+ }
31014
+ byPaletteSize.set(paletteSize, slots);
31015
+ return slots;
31016
+ }
31017
+ };
31018
+ }
31019
+ function resolveRaceColors(slots, palette) {
31020
+ const colors = palette.length > 0 ? palette : CATEGORICAL_PALETTE3;
31021
+ return slots.map((slot) => typeof slot === "number" ? colors[slot % colors.length] : slot);
31022
+ }
31023
+
31024
+ // src/race/prepare.ts
31025
+ import { resolveTheme as resolveTheme8 } from "@opendata-ai/openchart-core";
31026
+
31027
+ // src/race/matrix.ts
31028
+ var ISO_TIME_WITHOUT_OFFSET = /T\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?$/i;
31029
+ function readPeriod(raw, type) {
31030
+ const value = raw instanceof Date && Number.isFinite(raw.getTime()) ? raw.toISOString() : raw;
31031
+ if (typeof value !== "string" && typeof value !== "number") return void 0;
31032
+ let sortKey = 0;
31033
+ if (type === "temporal") {
31034
+ sortKey = typeof value === "number" ? value : Date.parse(ISO_TIME_WITHOUT_OFFSET.test(value) ? `${value}Z` : value);
31035
+ } else if (type === "quantitative") {
31036
+ sortKey = finiteNumber(value) ?? NaN;
31037
+ }
31038
+ if (Number.isFinite(sortKey)) return { value, sortKey };
31039
+ }
31040
+ function orderPeriods(periods, time) {
31041
+ if (time.type === "ordinal") {
31042
+ if (Array.isArray(time.sort)) {
31043
+ const positions = new Map([...new Set(time.sort)].map((value, index) => [value, index]));
31044
+ const order = (period) => positions.get(String(period.value)) ?? positions.size;
31045
+ periods.sort((a, b) => order(a) - order(b));
31046
+ }
31047
+ periods.forEach((period, index) => {
31048
+ period.sortKey = index;
31049
+ });
31050
+ } else {
31051
+ if (time.type === "temporal" && periods.some(({ value }) => typeof value === "string")) {
31052
+ for (const period of periods) {
31053
+ if (typeof period.value === "number") period.sortKey = Date.UTC(period.value, 0, 1);
31054
+ }
31055
+ }
31056
+ periods.sort((a, b) => a.sortKey - b.sortKey);
31057
+ }
31058
+ }
31059
+ function fillInteriorGaps(values, gaps) {
31060
+ if (gaps === "drop") return;
31061
+ let previous = -1;
31062
+ for (let period = 0; period < values.length; period++) {
31063
+ if (Number.isNaN(values[period])) continue;
31064
+ if (previous >= 0) {
31065
+ for (let gap = previous + 1; gap < period; gap++) {
31066
+ values[gap] = gaps === "hold" ? values[previous] : interpolateRaceValue(
31067
+ values,
31068
+ previous,
31069
+ (gap - previous) / (period - previous),
31070
+ period
31071
+ );
31072
+ }
31073
+ }
31074
+ previous = period;
31075
+ }
31076
+ }
31077
+ function buildRaceMatrix(rows, encoding, gaps, warn) {
31078
+ const { time, key, value, label, color } = encoding;
31079
+ const timeType = time.type ?? "temporal";
31080
+ const periodsByValue = /* @__PURE__ */ new Map();
31081
+ const rowsByKey = /* @__PURE__ */ new Map();
31082
+ let firstCollision;
31083
+ let skippedCount = 0;
31084
+ let invalidPeriodCount = 0;
31085
+ let firstSkipped;
31086
+ let nonFiniteCount = 0;
31087
+ for (const row of rows) {
31088
+ const raw = row[value.field];
31089
+ const number = finiteNumber(raw);
31090
+ if (number === void 0 && raw != null) nonFiniteCount++;
31091
+ const rawPeriod = row[time.field];
31092
+ const rawKey = row[key.field];
31093
+ const parsedPeriod = readPeriod(rawPeriod, timeType);
31094
+ if (!parsedPeriod || rawKey == null) {
31095
+ skippedCount++;
31096
+ if (!parsedPeriod) invalidPeriodCount++;
31097
+ firstSkipped ??= !parsedPeriod ? `'${time.field}' has an invalid ${timeType} period '${String(rawPeriod)}'` : `'${key.field}' has a missing key '${String(rawKey)}'`;
31098
+ continue;
31099
+ }
31100
+ const period = periodsByValue.get(parsedPeriod.value) ?? parsedPeriod;
31101
+ periodsByValue.set(period.value, period);
31102
+ const keyValue = String(rawKey);
31103
+ let keyRows = rowsByKey.get(keyValue);
31104
+ if (!keyRows) {
31105
+ keyRows = /* @__PURE__ */ new Map();
31106
+ rowsByKey.set(keyValue, keyRows);
31107
+ }
31108
+ const entry = keyRows.get(period);
31109
+ if (entry) {
31110
+ entry.count++;
31111
+ firstCollision ??= { key: keyValue, period, entry };
31112
+ } else {
31113
+ keyRows.set(period, { row, value: number ?? NaN, count: 1 });
31114
+ }
31115
+ }
31116
+ if (firstSkipped) {
31117
+ const rowsLabel = skippedCount === 1 ? "row" : "rows";
31118
+ warn(`Skipped ${skippedCount} ${rowsLabel}. In the first skipped row, ${firstSkipped}.`);
31119
+ }
31120
+ if (firstCollision) {
31121
+ const { key: keyValue, period, entry } = firstCollision;
31122
+ throw new RaceDataError(
31123
+ "DUPLICATE_KEY_PERIOD",
31124
+ `${entry.count} rows have ${key.field} = '${keyValue}' and ${time.field} = ${period.value}. Aggregate them first so each key has one value per period.`
31125
+ );
31126
+ }
31127
+ const periods = [...periodsByValue.values()];
31128
+ if (periods.length < 2) {
31129
+ const suggestion = invalidPeriodCount > 0 && invalidPeriodCount === rows.length && timeType !== "ordinal" ? " For category labels, set type: 'ordinal'." : "";
31130
+ throw new RaceDataError(
31131
+ "TOO_FEW_PERIODS",
31132
+ `${rows.length} rows contain ${periods.length} distinct periods in '${time.field}' (type '${timeType}'). Supply at least two periods.${suggestion}`
31133
+ );
31134
+ }
31135
+ orderPeriods(periods, { ...time, type: timeType });
31136
+ const keys = [...rowsByKey.keys()].sort((a, b) => a.localeCompare(b, "en"));
31137
+ const labels = [];
31138
+ const colorValues = [];
31139
+ const colorField = color && "field" in color ? color.field : void 0;
31140
+ let finiteCount = 0;
31141
+ const values = keys.map((keyValue) => {
31142
+ const keyRows = rowsByKey.get(keyValue);
31143
+ const series = new Float64Array(periods.length).fill(NaN);
31144
+ let displayLabel = keyValue;
31145
+ let colorValue = null;
31146
+ periods.forEach((period, index) => {
31147
+ const observation = keyRows?.get(period);
31148
+ if (!observation) return;
31149
+ const { row, value: value2 } = observation;
31150
+ series[index] = value2;
31151
+ if (Number.isFinite(value2)) finiteCount++;
31152
+ const rowLabel = label === void 0 ? void 0 : row[label.field];
31153
+ const rowColor = colorField === void 0 ? void 0 : row[colorField];
31154
+ if (rowLabel != null) displayLabel = String(rowLabel);
31155
+ if (rowColor != null) colorValue = String(rowColor);
31156
+ });
31157
+ fillInteriorGaps(series, gaps);
31158
+ labels.push(displayLabel);
31159
+ colorValues.push(colorValue);
31160
+ return series;
31161
+ });
31162
+ if (nonFiniteCount > 0) {
31163
+ warn(`Dropped ${nonFiniteCount} non-finite values from '${value.field}'.`);
31164
+ }
31165
+ if (keys.length > 500) {
31166
+ warn(
31167
+ `${keys.length} distinct keys in '${key.field}' can slow race rank precomputation. Filter to the keys that can reach the top N, or aggregate the rest into an "Other" key.`
31168
+ );
31169
+ }
31170
+ if (finiteCount === 0) {
31171
+ throw new RaceDataError(
31172
+ "NO_VALUES",
31173
+ `${rows.length} rows contain no finite values in '${value.field}' across ${periods.length} periods. Supply a finite number for at least one key and period.`
31174
+ );
31175
+ }
31176
+ return { periods, keys, labels, colorValues, values };
31177
+ }
31178
+
31179
+ // src/race/period-labels.ts
31180
+ function formatPeriodLabels(periods, time) {
31181
+ if (time.type === "temporal") {
31182
+ const dates = periods.map(({ value, sortKey }) => {
31183
+ const year = typeof value === "number" && Number.isInteger(value) && value >= 1e3 && value <= 9999 && sortKey === value;
31184
+ return { value, year, date: new Date(year ? Date.UTC(value, 0, 1) : sortKey) };
31185
+ });
31186
+ const allFirstOfMonth = dates.every(({ date }) => date.getUTCDate() === 1);
31187
+ const allJanuary = dates.every(({ date }) => date.getUTCMonth() === 0);
31188
+ const format2 = utcFormat(
31189
+ time.format ?? (allFirstOfMonth ? allJanuary ? "%Y" : "%b %Y" : "%b %-d, %Y")
31190
+ );
31191
+ return dates.map(
31192
+ ({ value, year, date }) => year && time.format === void 0 ? String(value) : format2(date)
31193
+ );
31194
+ }
31195
+ if (time.type === "quantitative" && time.format) {
31196
+ const format2 = resolveFieldFormatter({
31197
+ channelFormat: time.format,
31198
+ values: periods.map(({ value }) => value)
31199
+ });
31200
+ return periods.map(({ value }) => format2(Number(value)));
31201
+ }
31202
+ return periods.map(({ value }) => String(value));
31203
+ }
31204
+
31205
+ // src/race/prepare.ts
31206
+ var warningAdapters = /* @__PURE__ */ new WeakMap();
31207
+ function raceSpecWarning(message) {
31208
+ return { code: "RACE_SPEC_WARNING", message };
31209
+ }
31210
+ function createRaceWarn(warnings, onWarn) {
31211
+ let adapter = onWarn && warningAdapters.get(onWarn);
31212
+ if (onWarn && !adapter) {
31213
+ adapter = (message) => onWarn(raceSpecWarning(message));
31214
+ warningAdapters.set(onWarn, adapter);
31215
+ }
31216
+ emitSpecWarnings(warnings, adapter);
31217
+ return (message) => {
31218
+ warnings.push(message);
31219
+ emitSpecWarnings([message], adapter);
31220
+ };
31221
+ }
31222
+ function resolveDurationMs(race, periodCount) {
31223
+ if (race.step === void 0) {
31224
+ return race.duration ?? Math.max(8e3, Math.min(9e4, periodCount * 700));
31225
+ }
31226
+ const durationMs = race.step * (periodCount - 1);
31227
+ if (!Number.isFinite(durationMs)) {
31228
+ throw new RangeError(`race.step is too large for ${periodCount} periods. Use a shorter step.`);
31229
+ }
31230
+ return durationMs;
31231
+ }
31232
+ function authoredWatermark(spec, normalized) {
31233
+ return typeof spec === "object" && spec !== null && "watermark" in spec && spec.watermark !== void 0 ? normalized : void 0;
31234
+ }
31235
+ var preparedInputs = /* @__PURE__ */ new WeakMap();
31236
+ function preparationInputs({ data, encoding, race, labels }) {
31237
+ const { duration, step, swap, top, gaps, rescale, period } = race;
31238
+ const { time, key, value, label, color } = encoding;
31239
+ const colorValue = color && "value" in color ? color.value : void 0;
31240
+ const colorField = color && "field" in color ? color.field : void 0;
31241
+ const options = JSON.stringify([
31242
+ time.field,
31243
+ time.type,
31244
+ time.sort,
31245
+ time.format,
31246
+ key.field,
31247
+ value.field,
31248
+ value.format,
31249
+ label?.field,
31250
+ colorValue,
31251
+ colorField,
31252
+ duration,
31253
+ step,
31254
+ swap,
31255
+ top,
31256
+ gaps,
31257
+ typeof rescale === "object" ? rescale.min : rescale,
31258
+ period === false ? false : period.format,
31259
+ labels?.format
31260
+ ]);
31261
+ const fields = /* @__PURE__ */ new Set([time.field, key.field, value.field]);
31262
+ if (label) fields.add(label.field);
31263
+ if (colorField !== void 0) fields.add(colorField);
31264
+ const columns = [...fields].map(
31265
+ (field) => data.map((row) => {
31266
+ const value2 = row[field];
31267
+ if (value2 instanceof Date) return new Date(value2.getTime());
31268
+ if (typeof value2 === "object" && value2 !== null) return {};
31269
+ return value2;
31270
+ })
31271
+ );
31272
+ return { options, columns, warnings: [] };
31273
+ }
31274
+ function sameInputs(a, b) {
31275
+ return a.options === b.options && a.columns.every(
31276
+ (column, i) => column.length === b.columns[i]?.length && column.every((value, row) => {
31277
+ const previous = b.columns[i][row];
31278
+ return value instanceof Date && previous instanceof Date ? Object.is(value.getTime(), previous.getTime()) : Object.is(value, previous);
31279
+ })
31280
+ );
31281
+ }
31282
+ function prepareRanking({ data, encoding, race, labels }, warn) {
31283
+ const matrix = buildRaceMatrix(data, encoding, race.gaps, warn);
31284
+ const periodCount = matrix.periods.length;
31285
+ const durationMs = resolveDurationMs(race, periodCount);
31286
+ const timeline = createRaceTimeline(matrix, {
31287
+ top: race.top,
31288
+ swapPeriods: race.swap / durationMs * (periodCount - 1),
31289
+ samplesPerPeriod: 24,
31290
+ rescale: race.rescale
31291
+ });
31292
+ if (race.top > timeline.top) {
31293
+ warn(
31294
+ `race.top is ${race.top} but the data has ${timeline.top} distinct keys. Showing at most ${timeline.top}.`
31295
+ );
31296
+ }
31297
+ const periodFormat = race.period === false ? void 0 : race.period.format;
31298
+ const periodLabels = formatPeriodLabels(matrix.periods, {
31299
+ ...encoding.time,
31300
+ format: periodFormat ?? encoding.time.format
31301
+ });
31302
+ function* values() {
31303
+ for (const series of matrix.values) yield* series;
31304
+ }
31305
+ const formatValue3 = resolveFieldFormatter({
31306
+ surfaceFormat: labels?.format,
31307
+ channelFormat: encoding.value.format,
31308
+ values: values()
31309
+ });
31310
+ return { matrix, timeline, periodLabels, formatValue: formatValue3 };
31311
+ }
31312
+ function prepareRace(spec, options) {
31313
+ const { spec: normalized, warnings } = compile(spec);
31314
+ if (!("type" in normalized) || normalized.type !== "race") {
31315
+ throw new Error(
31316
+ 'prepareRace received a non-race spec. Set type to "race" or use the matching compiler.'
31317
+ );
31318
+ }
31319
+ const warn = createRaceWarn(warnings, options.onWarn);
31320
+ const { encoding, race } = normalized;
31321
+ const inputs = preparationInputs(normalized);
31322
+ const { previousModel } = options;
31323
+ const previousInputs = previousModel && preparedInputs.get(previousModel);
31324
+ const reusable = previousInputs && sameInputs(inputs, previousInputs) ? previousModel : void 0;
31325
+ const { matrix, timeline, periodLabels, formatValue: formatValue3 } = reusable ?? prepareRanking(normalized, (message) => {
31326
+ inputs.warnings.push(message);
31327
+ warn(message);
31328
+ });
31329
+ if (reusable && previousInputs) {
31330
+ inputs.warnings = previousInputs.warnings;
31331
+ for (const message of inputs.warnings) warn(message);
31332
+ }
31333
+ const palette = resolveTheme8(normalized.theme).colors.categorical;
31334
+ const colorAssignment = reusable?.colorAssignment ?? assignRaceColors(matrix, timeline, encoding.color, encoding.key.field, previousModel);
31335
+ const frameColors = resolveRaceColors(colorAssignment.slotsFor(palette.length), palette);
31336
+ const model = {
31337
+ spec: normalized,
31338
+ specWatermark: authoredWatermark(spec, normalized.watermark),
31339
+ matrix,
31340
+ timeline,
31341
+ colorAssignment,
31342
+ frameColors,
31343
+ periodLabels,
31344
+ formatValue: formatValue3,
31345
+ playback: {
31346
+ durationMs: resolveDurationMs(race, timeline.periodCount),
31347
+ holdEndMs: race.holdEnd,
31348
+ loop: race.loop,
31349
+ autoplay: race.autoplay,
31350
+ controls: race.controls
31351
+ },
31352
+ warnings
31353
+ };
31354
+ preparedInputs.set(model, inputs);
31355
+ return model;
31356
+ }
31357
+
31358
+ // src/race/layout.ts
31359
+ function raceLayoutBase(model, options, measureText) {
31360
+ const { width, height } = options;
31361
+ const { spec } = model;
31362
+ const watermark = model.specWatermark ?? options.watermark ?? true;
31363
+ const lightTheme = resolveTheme9(mergeThemeConfig8(spec.theme, options.theme));
31364
+ const theme = options.darkMode ? adaptTheme7(lightTheme) : lightTheme;
31365
+ const chrome = computeChrome9(
31366
+ spec.chrome,
31367
+ theme,
31368
+ width,
31369
+ options.measureText,
31370
+ "full",
31371
+ void 0,
31372
+ watermark
31373
+ );
31374
+ const { padding } = theme.spacing;
31375
+ const bottomPadding = model.playback.controls ? Math.max(8, padding) : padding;
31376
+ const area3 = {
31377
+ x: padding,
31378
+ y: padding + chrome.topHeight,
31379
+ width: Math.max(0, width - 2 * padding),
31380
+ height: Math.max(0, height - padding - bottomPadding - chrome.topHeight - chrome.bottomHeight)
31381
+ };
31382
+ const { body } = theme.fonts.sizes;
31383
+ const { normal } = theme.fonts.weights;
31384
+ const labelBudget = area3.width * 0.4;
31385
+ const measureWidth = (text, size, weight) => measureText(text, size, weight).width;
31386
+ const labels = model.matrix.labels.map(
31387
+ (label) => truncateRaceLabel(label, labelBudget, body, normal, measureWidth)
31388
+ );
31389
+ return {
31390
+ width,
31391
+ height,
31392
+ chrome,
31393
+ theme,
31394
+ a11y: raceA11y(model),
31395
+ watermark,
31396
+ periods: [...model.periodLabels],
31397
+ colors: resolveRaceColors(
31398
+ model.colorAssignment.slotsFor(theme.colors.categorical.length),
31399
+ theme.colors.categorical
31400
+ ),
31401
+ labels,
31402
+ measureText: options.measureText,
31403
+ playback: { ...model.playback },
31404
+ warnings: model.warnings.map(raceSpecWarning),
31405
+ area: area3
31406
+ };
31407
+ }
31408
+ function layoutRace(model, options) {
31409
+ const measureText = options.measureText ?? ((text, fontSize, fontWeight) => ({
31410
+ width: estimateTextWidth33(text, fontSize, fontWeight),
31411
+ height: fontSize
31412
+ }));
31413
+ const base = raceLayoutBase(model, options, measureText);
31414
+ return layoutForRaceMark(model, base, options.mark ?? model.spec.mark, measureText);
28511
31415
  }
28512
31416
 
28513
31417
  // src/compile.ts
28514
31418
  function compileChart(spec, optionsInput) {
31419
+ if (isRaceSpec3(spec)) {
31420
+ throw new Error("compileChart received a race spec. Use prepareRace and layoutRace instead.");
31421
+ }
28515
31422
  assertMarkOptions(spec);
28516
31423
  return compileChartInternal(spec, optionsInput);
28517
31424
  }
@@ -29142,17 +32049,17 @@ function buildGeoReaderIndex(spec, layout) {
29142
32049
  const reported = /* @__PURE__ */ new Set();
29143
32050
  const formatter = (kind, channel) => {
29144
32051
  const key = `${kind}:${channel.field}:${channel.format ?? ""}`;
29145
- let format = formatters.get(key);
29146
- if (!format) {
29147
- format = resolveFieldFormatter({
32052
+ let format2 = formatters.get(key);
32053
+ if (!format2) {
32054
+ format2 = resolveFieldFormatter({
29148
32055
  channelFormat: channel.format,
29149
32056
  values: (kind === "feature" ? spec.data : spec.points?.data ?? []).map(
29150
32057
  (row) => row[channel.field]
29151
32058
  )
29152
32059
  });
29153
- formatters.set(key, format);
32060
+ formatters.set(key, format2);
29154
32061
  }
29155
- return format;
32062
+ return format2;
29156
32063
  };
29157
32064
  const validId = (value) => typeof value === "string" && value.trim() !== "" || typeof value === "number" && Number.isFinite(value);
29158
32065
  const featureCounts = /* @__PURE__ */ new Map();
@@ -29244,10 +32151,10 @@ function buildGeoReaderIndex(spec, layout) {
29244
32151
  (field) => {
29245
32152
  const raw = datum?.[field.field];
29246
32153
  const numeric = finiteNumber(raw);
29247
- const format = field.format ? buildD3Formatter5(field.format) : void 0;
32154
+ const format2 = field.format ? buildD3Formatter5(field.format) : void 0;
29248
32155
  return {
29249
32156
  label: field.title ?? spec.fields?.[field.field]?.label ?? field.field,
29250
- value: raw == null ? "No data" : field.type === "quantitative" ? numeric === void 0 ? "No data" : format ? format(numeric) : String(numeric) : String(raw)
32157
+ value: raw == null ? "No data" : field.type === "quantitative" ? numeric === void 0 ? "No data" : format2 ? format2(numeric) : String(numeric) : String(raw)
29251
32158
  };
29252
32159
  }
29253
32160
  );
@@ -29351,7 +32258,7 @@ import {
29351
32258
  CATEGORICAL_PALETTE_DARK,
29352
32259
  encodePointerToken as encodePointerToken3,
29353
32260
  legacyEditorial,
29354
- resolveTheme as resolveTheme8
32261
+ resolveTheme as resolveTheme10
29355
32262
  } from "@opendata-ai/openchart-core";
29356
32263
  var V8_CATEGORICAL = ["#06b6d4", "#e29e47", "#4170cb", "#b2417f", "#3ca368", "#a584dc"];
29357
32264
  var V8_CATEGORICAL_FILL = ["#51bccc", "#dda96b", "#587fc8", "#bf6291", "#62ab7d", "#ae96da"];
@@ -29573,7 +32480,7 @@ function migrateSpecV8(input, options = {}) {
29573
32480
  for (const [key, value] of Object.entries(legacyEditorial.fonts.sizes)) {
29574
32481
  if (newSizes[key] === void 0) newSizes[key] = value;
29575
32482
  }
29576
- const legacyDark = resolveTheme8(oldTheme).isDark;
32483
+ const legacyDark = resolveTheme10(oldTheme).isDark;
29577
32484
  const legacySurface = legacyDark ? "#0a0a0a" : "#ffffff";
29578
32485
  const newChrome = { ...chromeDefaults };
29579
32486
  for (const key of ["byline", "source", "footer"]) {
@@ -29628,7 +32535,7 @@ function migrateSpecV8(input, options = {}) {
29628
32535
  rewrite(
29629
32536
  "theme",
29630
32537
  materialized,
29631
- "Preserve v8 palettes, typography and scaffolding ink without overriding authored chrome sizes. Shared measured attribution replaces the fixed brand reserve; footer wrapping, default watermark size and resulting automatic geometry have no legacy opt-out." + (current.type === "map" ? " Updated static map captions, neutral-class context geometry and occupied size-key placement have no legacy opt-out; their layout cannot be preserved." : "") + (hasCorrectedValueLabels(current) && resolveTheme8(oldTheme).fonts.family !== "system-ui, -apple-system, sans-serif" ? " Corrected value labels now follow the resolved theme font; their former system-font mismatch cannot be preserved independently." : "")
32538
+ "Preserve v8 palettes, typography and scaffolding ink without overriding authored chrome sizes. Shared measured attribution replaces the fixed brand reserve; footer wrapping, default watermark size and resulting automatic geometry have no legacy opt-out." + (current.type === "map" ? " Updated static map captions, neutral-class context geometry and occupied size-key placement have no legacy opt-out; their layout cannot be preserved." : "") + (hasCorrectedValueLabels(current) && resolveTheme10(oldTheme).fonts.family !== "system-ui, -apple-system, sans-serif" ? " Corrected value labels now follow the resolved theme font; their former system-font mismatch cannot be preserved independently." : "")
29632
32539
  );
29633
32540
  }
29634
32541
  }
@@ -29732,6 +32639,8 @@ export {
29732
32639
  ENTER_DEFAULTS,
29733
32640
  EXIT_DEFAULTS,
29734
32641
  MAX_3D_NODES,
32642
+ MAX_TOTAL_STAGGER_MS,
32643
+ RaceDataError,
29735
32644
  UPDATE_DEFAULTS,
29736
32645
  applySpecPatch,
29737
32646
  automaticControlPoint,
@@ -29767,6 +32676,7 @@ export {
29767
32676
  interpolateAnnotationGeometry,
29768
32677
  inverseLabelPlacement,
29769
32678
  isConditionalValueDef,
32679
+ layoutRace,
29770
32680
  legendGap,
29771
32681
  linkedEntityKeys,
29772
32682
  migrateSpecV8,
@@ -29774,10 +32684,15 @@ export {
29774
32684
  normalizeSpec,
29775
32685
  observationKey,
29776
32686
  parseAnnotationSpans,
32687
+ prepareRace,
29777
32688
  previewAnnotationMove,
29778
32689
  previewConnectorBend,
29779
32690
  previewConnectorOffset,
29780
32691
  queryGeoReaderRecords,
32692
+ raceA11y,
32693
+ raceA11yLeaders,
32694
+ raceFrameAt,
32695
+ raceGeometryAt,
29781
32696
  readerDomainValue,
29782
32697
  readerSliceByKey,
29783
32698
  recommendCompositions,