Skip to content

Scott/combo chart fix - #428

Merged
sagrimson merged 6 commits into
datacommonsorg:mainfrom
madebypxlp:scott/combo-chart-fix
Jul 29, 2026
Merged

sagrimson merged 6 commits into
datacommonsorg:mainfrom
madebypxlp:scott/combo-chart-fix

Conversation

@sagrimson

@sagrimson sagrimson commented Jul 24, 2026

Copy link
Copy Markdown
Contributor

Overview

Fixes combo (comparison) chart generation when multiple variables are selected for the same place, adds LLM-driven chart style changes and compare/combine intent detection, and stabilizes the Y-axis width across all chart types.

Previously, selecting cards like "Female Life Expectancy in Japan" and "Male Life Expectancy in Japan" would overwrite each other since they shared the same entity key, resulting in only one series appearing in the combined chart. Additionally, changing chart styles and triggering combine/compare flows relied on fragile client-side regex matching — both are now delegated to the LLM via the query parsing step.

Changes Made

LLM-driven chart style changes

  • chartStyleIntent in query parsing — the LLM can now detect when a user wants to change chart appearance (e.g. "make these horizontal", "switch to a line chart") and returns a chartStyleIntent with a targetStyle value (bar-vertical | bar-horizontal | line). Unsupported chart types (pie, scatter, etc.) produce a follow-up with supported options instead (parse_query.md, parse_query.ts)
  • chartStyleChange stream event — new stream event type lets the server signal a style change; the client applies it to all selected chart shapes and persists it in the store (types.ts, route.ts, query_provider.tsx)
  • Persisted chartStyle on cardsChartStyle type promoted from the local menu component to server/types.ts; stored on CardEntry, the tldraw shape props, and AtlasContent so it survives across export/import and re-renders (types.ts, store.ts, helpers.ts, shapes/card.tsx, chart.tsx, menu_chart_options.tsx)
  • cardSetChartStyle store action — new zustand action to update a card's persisted chart style (store.ts)

LLM-driven combine/compare intent

  • combineIntent in query parsing — the LLM detects compare/combine requests (e.g. "combine these", "compare these charts") when multiple chart cards are selected, replacing the client-side isCombineIntent regex. Returns combineIntent: true in the parsed query (parse_query.md, parse_query.ts)
  • Server-side combine flowroute.ts handles combineIntent as an early exit: runs the comparison step directly with the selected results sent from the client, removing the separate /api/combine endpoint dependency for this path
  • Selection context sent to APIhasChartSelection, chartSelectionCount, and selectedResults are now included in the query request so the LLM and server have full context about what's selected (types.ts, query_provider.tsx, route.ts)

Same-place multi-variable fix

  • Same-place, multi-variable combine logic — when combining cards that share the same entity, merge their variables and timeSeries arrays instead of overwriting. Deduplicates by dcid / variableDcid+entityDcid so repeated entries are skipped (query_provider.tsx)
  • Comparison chart derivationderiveComparisonChartContent detects same-place vs. different-place scenarios: when all results share one entity it overlays every variable as a separate series; otherwise it builds one series per place as before (sync_store.ts)
  • Per-variable chart content — new deriveChartContentForVariable derives chart content targeting a specific variable DCID (and optionally entity DCID), used by deriveContentForCard when a card has variableDcid set (sync_store.ts)
  • Selection deduplicationgetResultsForSelectedCards uses a composite entityDcid::variableDcid key so cards with the same place but different variables produce distinct results; narrows each result to only the targeted variable's timeSeries and variables when card.variableDcid is set (store.ts)

Stable Y-axis width

  • measureAxisWidth utility — new shared utility uses a cached off-screen <canvas> to measure the widest label in pixels; companion numericAxisLabels generates representative formatted tick strings. Applied to bar-vertical, bar-horizontal, and line charts, replacing Recharts' width="auto" with a pre-measured value that prevents layout jitter on resize (measure_axis_width.ts)

Minor

  • Formatting fix in content.tsx

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces a stable Y-axis width calculation for charts by extracting measurement utilities into a shared measure_axis_width.ts file, and updates horizontal/vertical bar and line charts to use it. It also enhances the query provider, store, and comparison chart derivation to correctly support same-place, different-variable comparisons by merging and narrowing results appropriately. The review feedback points out that the helper functions niceNum and numericAxisLabels were duplicated in both data_chart_bar_vertical.tsx and data_chart_line.tsx instead of being imported from the new utility file.

Comment thread dataweaver/apps/web/src/components/elements/card/chart/data_chart_line.tsx Outdated
Comment thread dataweaver/apps/web/src/components/elements/card/chart/data_chart_line.tsx Outdated
@sagrimson
sagrimson force-pushed the scott/combo-chart-fix branch from 7097b97 to aa8960f Compare July 24, 2026 23:47
@sagrimson
sagrimson force-pushed the scott/combo-chart-fix branch from aa8960f to 6b08ae9 Compare July 24, 2026 23:58
@beets

beets commented Jul 27, 2026

Copy link
Copy Markdown
Contributor

Code Review Suggestions

Nice refactoring on this PR! Moving combine/style intents to the LLM query analyzer (parse_query.md), fixing entity state overwriting with composite deduplication keys (${entityDcid}::${card.variableDcid}), and eliminating Y-axis resizing jitter with measureAxisWidth are all really clean improvements.

Will early approve to unblock, but below are a few edge cases and actionable suggestions to consider:


1. ⚠️ Bug / Edge Case: Duplicate Combo Charts for Same-Place Multi-Variable Comparisons

  • The Issue:
    When combining multiple variables for a single place (e.g., "Female Life Expectancy in Japan" and "Male Life Expectancy in Japan"):
    1. comparePlaces returns $N$ items in result.charts (one per variable).
    2. In query_provider.tsx (lines 214–224), a comparison chart card is registered for each entry in result.charts.
    3. In deriveComparisonChartContent (sync_store.ts lines 83–109), the if (isSamePlace) branch overlays all variables into a single combo chart series regardless of which variableDcid was passed in.
    4. Result: If $N$ variables are combined for the same place, Atlas spawns $N$ identical combo charts on the canvas—each showing the exact same multi-variable overlay.
  • Suggested Fix:
    In query_provider.tsx under STREAM_EVENT.comparisonResult, detect when the selected results represent a same-place comparison across multiple variables and only register 1 unified comparison chart card (result.charts.slice(0, 1)):
    const isSamePlaceComparison =
      active.selectedResults.length > 0 &&
      new Set(active.selectedResults.map((r) => r.entities[0]?.dcid)).size === 1;
    
    const chartsToRegister = isSamePlaceComparison
      ? result.charts.slice(0, 1)
      : result.charts;

2. 💡 Suggestion: Small-Range Domain Precision in numericAxisLabels (measure_axis_width.ts)

  • The Issue:
    In niceNum(value), candidates are calculated by rounding up to integer/power-of-ten magnitude:
    const exp = 10 ** Math.floor(Math.log10(abs));
    return Math.sign(value) * Math.ceil(abs / exp) * exp;
    • If min and max are finite but close together (e.g., 99.123 to 99.125), Recharts may render tick labels with decimal places ("99.12", "99.13").
    • Because niceNum(99.125) rounds to 100, measuring "100" (3 characters) could underestimate the width of "99.125" (6 characters).
  • Suggested Improvement:
    When max - min is small relative to max (or has fractional variations), include formatChartValue(max, unit) in the candidates array so that fractional tick labels aren't under-measured.

3. 💡 Suggestion: Synchronizing Chart Style Overrides in sync_store.ts

  • The Issue:
    When STREAM_EVENT.chartStyleChange arrives, query_provider.tsx updates shape.props.chartStyle (triggering tldraw component re-render) and calls cardSetChartStyle(shapeId, event.style) in Zustand. However, sync_store.ts (lines 300–325) only calls handle.update(...) when prevCard.type !== card.type.
  • Suggested Improvement:
    In sync_store.ts, check if prevCard.chartStyle !== card.chartStyle so any non-tldraw handles or external subscribers stay synchronized when a style override occurs.

4. 🧪 Suggestion: Adding Unit Tests for New Core Helpers

  • Consider adding a measure_axis_width.test.ts file to test:
    • numericAxisLabels with positive, negative, zero, and infinite values.
    • measureAxisWidth fallback behavior in JSDOM / server environments.
    • A test case in store.test.ts verifying that selecting multiple cards for the same place with different variables produces distinct results in getResultsForSelectedCards.

@sagrimson
sagrimson merged commit 659dc4a into datacommonsorg:main Jul 29, 2026
8 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants