Skip to content
Draft
Show file tree
Hide file tree
Changes from 7 commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
ff12429
feat(vega): theme Vega charts from the charts package
AKnassa Jul 26, 2026
3bbd262
Merge upstream/main into ak-977-vega-charts-theming
AKnassa Aug 7, 2026
b846f95
Merge remote-tracking branch 'origin/main' into review-4411-5pm
cixzhang Aug 28, 2026
bf81326
Merge upstream/main into ak-977-vega-charts-theming
AKnassa Sep 26, 2026
74f380c
fix(vega): keep native Vega views across theme changes
AKnassa Sep 26, 2026
73b4e15
fix(vega): align the core peer with the version charts requires
AKnassa Sep 26, 2026
88c1dcf
fix(vega): catch in-place compileOptions edits on Vega-Lite charts
AKnassa Sep 26, 2026
89b933b
fix(vega): declare charts as a peer so the consumer install resolves
AKnassa Sep 26, 2026
0eead76
Merge main into ak-977-vega-charts-theming; theme from the charts pal…
cixzhang Nov 13, 2026
731ad95
fix(vega): a caller's generic axis key outranks the theme's per-axis …
cixzhang Nov 13, 2026
8410123
fix(vega): a caller's or spec's axis key in any earlier axis block ou…
cixzhang Nov 13, 2026
296afab
fix(vega): an orient block counts only for an orient the chart draws
cixzhang Nov 13, 2026
3f53ef0
fix(vega): a key in one orient block keeps the other orients themed; …
cixzhang Nov 13, 2026
1eee702
fix(vega): a caller's axisX or axisY key keeps every axis of that cha…
cixzhang Nov 13, 2026
9237958
Merge main into ak-977-vega-charts-theming
cixzhang Nov 23, 2026
a1c0214
chore(vega): pin @astryxdesign/core to the workspace version
cixzhang Nov 23, 2026
d09431f
Merge main into ak-977-vega-charts-theming
cixzhang Dec 3, 2026
840c760
Merge main into ak-977-vega-charts-theming
cixzhang Dec 3, 2026
9fecbb4
test(ci): a Charts change now also typechecks vega, which peers on ch…
cixzhang Dec 3, 2026
eeeaab2
fix(vega): count the axes Vega-Lite places itself when moving theme a…
cixzhang Dec 3, 2026
19b5619
fix(vega): the caller's mark and per-mark band padding keys, and inhe…
cixzhang Dec 3, 2026
e3d7c92
docs(VegaChart): record named-style precedence as a known FR1 gap
cixzhang Dec 3, 2026
cdc97a6
fix(vega): a filled point keeps its color under the theme; docs name …
cixzhang Dec 3, 2026
680530d
fix(vega): dots a line, area or trail config or a shape encoding turn…
cixzhang Dec 3, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion packages/charts/src/getChartColors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,12 @@ export type TokenResolver = (name: string) => string;
// Internals
// =============================================================================

const CATEGORICAL_TOKENS = [
/**
* The categorical palette, in slot order. Exported so integration packages
* (e.g. `@astryxdesign/vega`) build their own scale ranges from the same list
* instead of keeping a parallel copy that can drift.
*/
export const CATEGORICAL_TOKENS = [
'--color-data-categorical-blue',
'--color-data-categorical-orange',
'--color-data-categorical-purple',
Expand Down
1 change: 1 addition & 0 deletions packages/charts/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@ export {useChartColors} from './useChartColors';
export {
getChartColors,
getChartColorsFromResolver,
CATEGORICAL_TOKENS,
type ChartColorsAPI,
type SequentialHue,
type TokenResolver,
Expand Down
79 changes: 63 additions & 16 deletions packages/vega/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,25 +10,32 @@ Renders [Vega](https://vega.github.io/vega/) and [Vega-Lite](https://vega.github

## File Manifest

| File | Role | Purpose |
| ------------------- | --------- | ------------------------------------------------------------ |
| `package.json` | Config | Package metadata, deps, build scripts |
| `tsconfig.json` | Config | TypeScript compiler config (extends root) |
| `tsup.config.ts` | Config | Build config: CJS + ESM + `.d.ts` outputs |
| `src/index.ts` | Barrel | Public API surface |
| `src/VegaChart.tsx` | Component | Inspects `$schema`, compiles or renders, owns View lifecycle |
| `src/viewInputs.ts` | Utility | Detects value changes in the props that own the View |
| `src/schema.ts` | Utility | Parses and validates Vega/Vega-Lite `$schema` URLs |
| `src/types.ts` | Types | Shared TypeScript types for this package |
| File | Role | Purpose |
| ----------------------- | --------- | ------------------------------------------------------------ |
| `package.json` | Config | Package metadata, deps, build scripts |
| `tsconfig.json` | Config | TypeScript compiler config (extends root) |
| `tsconfig.build.json` | Config | Declaration-emit config; excludes tests from `dist` |
| `tsup.config.ts` | Config | Build config: CJS + ESM + `.d.ts` outputs |
| `src/index.ts` | Barrel | Public API surface |
| `src/VegaChart.tsx` | Component | Inspects `$schema`, compiles or renders, owns View lifecycle |
| `src/viewInputs.ts` | Utility | Detects value changes in the props that own the View |
| `src/schema.ts` | Utility | Parses and validates Vega/Vega-Lite `$schema` URLs |
| `src/vegaLiteConfig.ts` | Utility | Astryx-themed Vega-Lite config + compile-option merge |
| `src/types.ts` | Types | Shared TypeScript types for this package |

## Installation

Vega is published **only** under the `@canary` dist-tag, so you must request that tag explicitly. There is no `latest` version to install yet.

```bash
npm install @astryxdesign/vega@canary vega vega-lite
npm install @astryxdesign/vega@canary @astryxdesign/core vega vega-lite
```

`@astryxdesign/charts` comes along as a direct dependency — it owns the shared
data-visualization palette that keeps Vega charts and the compositional charts
looking identical. `@astryxdesign/core` is a peer dependency: the wrapper reads
the active `<Theme>` from it to resolve tokens to concrete values.

> Canary builds track the latest commit on `main` (`0.x.y-canary.<sha>`). They can break between any two versions — pin an exact version if you need stability.

## Usage
Expand Down Expand Up @@ -122,11 +129,11 @@ import {VegaChart} from '@astryxdesign/vega';

`compileOptions` fields (Vega-Lite specs only, ignored otherwise):

| `compileOptions` field | Type | Description |
| ---------------------- | ------------------------------ | --------------------------------------------------- |
| `config` | `VegaLiteConfig` | Vega-Lite config merged on top of the spec's config |
| `logger` | `LoggerInterface` | Custom logger used during compilation |
| `fieldTitle` | `(fieldDef, config) => string` | Custom field title formatter |
| `compileOptions` field | Type | Description |
| ---------------------- | ------------------------------ | --------------------------------------------------------- |
| `config` | `VegaLiteConfig` | Vega-Lite config merged on top of the Astryx theme config |
| `logger` | `LoggerInterface` | Custom logger used during compilation |
| `fieldTitle` | `(fieldDef, config) => string` | Custom field title formatter |

`parseOptions` fields:

Expand Down Expand Up @@ -173,6 +180,11 @@ What that costs differs between the two:
Everything the copy did reach is compared by value either way, so a mutation
elsewhere in the spec is picked up even when part of it is opaque.

A theme or color-mode change rebuilds a **Vega-Lite** View, dropping its zoom,
hover, and signal state, because the [theme config](#theming) is compiled into
the spec. It never rebuilds a **native Vega** View, which does not use that
config.

Everything else is inert to the lifecycle: `data`, `className`, `style`,
`onReady`, and `onError` never rebuild the View.

Expand All @@ -199,6 +211,41 @@ To update data dynamically after render, use `onReady` to get the live View and
/>
```

### Theming

Vega-Lite specs are themed out of the box. `VegaChart` reads the active
`<Theme>` and compiles the spec with the Astryx config from
`buildVegaLiteConfig` as its base — axis, legend, line/point, title and view
chrome, plus the scale ranges. The categorical range comes straight from
`CATEGORICAL_TOKENS` in `@astryxdesign/charts`, so a series colored blue in a
`<Chart>` is the same blue here.

Precedence, weakest first:

1. The derived Astryx theme config
2. `compileOptions.config` you pass to `<VegaChart>`
3. The spec's own inline `config`
Comment thread
astracat-bot[bot] marked this conversation as resolved.
Resolved

Merging is recursive, so a partial override like
`compileOptions={{config: {axis: {grid: true}}}}` replaces only `axis.grid` and
leaves the rest of the themed `axis` block intact.
Comment thread
astracat-bot[bot] marked this conversation as resolved.
Resolved

Native Vega specs are **not** themed — they bypass Vega-Lite compilation
entirely. Pass `parseConfig` for those.

To build the config yourself (custom compile pipeline, SSR, a `vega-embed`
host):

```tsx
import {useTheme} from '@astryxdesign/core/theme';
import {buildVegaLiteConfig, withAstryxConfig} from '@astryxdesign/vega';

const {token} = useTheme();

buildVegaLiteConfig(token); // the themed VegaLiteConfig
withAstryxConfig(token, compileOptions); // …folded into compile options
```

### Untrusted specs

A Vega/Vega-Lite spec is a program, not just data: Vega evaluates the
Expand Down
6 changes: 5 additions & 1 deletion packages/vega/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -43,14 +43,18 @@
"README.md"
],
"scripts": {
"build": "tsup && tsc --project tsconfig.json --emitDeclarationOnly --declaration --noEmit false --outDir dist",
"build": "tsup && tsc --project tsconfig.build.json --emitDeclarationOnly --declaration --noEmit false --outDir dist",
"dev": "tsup --watch",
"test": "vitest run --root ../..",
"test:watch": "vitest --root ../..",
"typecheck:docs": "tsc --project tsconfig.docs.json",
"typecheck": "tsc --noEmit"
},
"dependencies": {
"@astryxdesign/charts": "0.1.9"
},
"peerDependencies": {
"@astryxdesign/core": "0.6.3",
"react": ">=19.2.0",
"react-dom": ">=19.2.0",
"vega": ">=6.0.0",
Expand Down
2 changes: 1 addition & 1 deletion packages/vega/src/VegaChart.doc.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ export const docs = {
name: 'compileOptions',
type: 'CompileOptions',
description:
'Options passed to Vega-Lite compilation. Ignored for native Vega specs.',
'Options passed to Vega-Lite compilation. Its config is merged over the Astryx theme config applied by default. Ignored for native Vega specs.',
},
{
name: 'parseConfig',
Expand Down
107 changes: 103 additions & 4 deletions packages/vega/src/VegaChart.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,18 @@

/**
* @file VegaChart.test.tsx
* @input Uses vitest, @testing-library/react, VegaChart, mocked vega + vega-lite
* @input Uses vitest, @testing-library/react, VegaChart, core's Theme, mocked vega + vega-lite
* @output Functional tests for the VegaChart View lifecycle and error contract
* @position Colocated test for VegaChart.tsx (issue #4295 vega coverage)
*/

import {describe, it, expect, vi, beforeEach} from 'vitest';
import {render, act} from '@testing-library/react';
import React from 'react';
import type * as Vega from 'vega';
import {defineTheme, resolveThemeTokens, Theme} from '@astryxdesign/core/theme';
import {VegaChart} from './VegaChart';
import {buildVegaLiteConfig} from './vegaLiteConfig';
import type {AnySpec} from './types';

const {parseMock, compileMock, views, FakeView} = vi.hoisted(() => {
Expand Down Expand Up @@ -46,7 +49,13 @@ const {parseMock, compileMock, views, FakeView} = vi.hoisted(() => {
return {parseMock, compileMock, views, FakeView};
});

vi.mock('vega', () => ({parse: parseMock, View: FakeView}));
// Only the runtime entry points are faked: the theme config is folded into
// compileOptions with vega's real mergeConfig.
vi.mock('vega', async importOriginal => ({
...(await importOriginal<typeof Vega>()),
parse: parseMock,
View: FakeView,
}));
vi.mock('vega-lite', () => ({compile: compileMock}));

const VEGA_LITE_SPEC = {
Expand All @@ -59,21 +68,31 @@ const VEGA_SPEC = {
marks: [],
} as unknown as AnySpec;

/** The Astryx config a Vega-Lite spec compiles under outside any <Theme>. */
const defaultTokens = resolveThemeTokens(null, {mode: 'light'});
const DEFAULT_THEME_CONFIG = buildVegaLiteConfig(
name => defaultTokens[name] ?? '',
);

beforeEach(() => {
vi.clearAllMocks();
views.length = 0;
});

describe('VegaChart', () => {
describe('spec handling', () => {
it('compiles vega-lite specs with compileOptions and parses the compiled output', () => {
it('compiles vega-lite specs with compileOptions over the Astryx theme and parses the compiled output', () => {
const compileOptions = {config: {background: 'red'}};
render(
<VegaChart spec={VEGA_LITE_SPEC} compileOptions={compileOptions} />,
);

expect(compileMock).toHaveBeenCalledTimes(1);
expect(compileMock).toHaveBeenCalledWith(VEGA_LITE_SPEC, compileOptions);
// The caller's config wins over the theme it is merged onto; theme keys
// it does not set are kept.
expect(compileMock).toHaveBeenCalledWith(VEGA_LITE_SPEC, {
config: {...DEFAULT_THEME_CONFIG, background: 'red'},
});
const compiled = compileMock.mock.results[0].value.spec;
expect(parseMock).toHaveBeenCalledTimes(1);
expect(parseMock.mock.calls[0][0]).toBe(compiled);
Expand Down Expand Up @@ -260,12 +279,92 @@ describe('VegaChart', () => {
expect(views).toHaveLength(2);
});

// Vega-Lite compiles a fresh merge of the theme and the caller's options,
// not the caller's object itself: an equal merge must keep the View, and
// an edit to the caller's object has to reach the comparison through it.
it('keeps a Vega-Lite View when a re-render passes equal inline compileOptions', () => {
const {rerender} = render(
<VegaChart
spec={VEGA_LITE_SPEC}
compileOptions={{config: {background: 'red'}}}
/>,
);

rerender(
<VegaChart
spec={VEGA_LITE_SPEC}
compileOptions={{config: {background: 'red'}}}
/>,
);

expect(views).toHaveLength(1);
expect(compileMock).toHaveBeenCalledTimes(1);
});

it('rebuilds a Vega-Lite View when compileOptions.config is mutated in place', () => {
const compileOptions = {config: {background: 'red'}};
const {rerender} = render(
<VegaChart spec={VEGA_LITE_SPEC} compileOptions={compileOptions} />,
);

compileOptions.config.background = 'blue';
rerender(
<VegaChart spec={VEGA_LITE_SPEC} compileOptions={compileOptions} />,
);

expect(views).toHaveLength(2);
expect(compileMock).toHaveBeenLastCalledWith(VEGA_LITE_SPEC, {
config: {...DEFAULT_THEME_CONFIG, background: 'blue'},
});
});

it('hands Vega the caller’s own spec object, not a copy', () => {
render(<VegaChart spec={VEGA_SPEC} />);

expect(parseMock.mock.calls[0][0]).toBe(VEGA_SPEC);
});

// A theme or color-mode switch changes the Astryx config a Vega-Lite spec
// is compiled with, so that View is rebuilt. A native Vega spec never
// reads that config, so its View -- and its live state -- is kept.
describe('theme changes', () => {
Comment thread
astracat-bot[bot] marked this conversation as resolved.
Resolved
const theme = defineTheme({name: 'vega-theme-change'});

function renderInLightMode(spec: AnySpec) {
const ui = (mode: 'light' | 'dark') => (
<Theme theme={theme} mode={mode}>
<VegaChart spec={spec} />
</Theme>
);
const {rerender} = render(ui('light'));
return {switchToDark: () => rerender(ui('dark'))};
}

it('keeps a native Vega View when the color mode changes', () => {
const {switchToDark} = renderInLightMode(VEGA_SPEC);
expect(views).toHaveLength(1);

switchToDark();

expect(views).toHaveLength(1);
expect(views[0].finalize).not.toHaveBeenCalled();
});

it('rebuilds a Vega-Lite View with the new mode’s theme config', () => {
const {switchToDark} = renderInLightMode(VEGA_LITE_SPEC);
expect(views).toHaveLength(1);

switchToDark();

expect(views).toHaveLength(2);
expect(views[0].finalize).toHaveBeenCalledTimes(1);
const dark = resolveThemeTokens(theme, {mode: 'dark'});
expect(compileMock).toHaveBeenLastCalledWith(VEGA_LITE_SPEC, {
config: buildVegaLiteConfig(name => dark[name] ?? ''),
});
});
});

// A spec the comparison cannot copy — a reference cycle, or nesting past
// its depth bound — is compared by reference instead. That verdict runs
// during render, so an "always changed" answer would re-render forever
Expand Down
28 changes: 27 additions & 1 deletion packages/vega/src/VegaChart.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,9 @@
import React, {useEffect, useEffectEvent, useRef, useState} from 'react';
import {parse, View} from 'vega';
import {compile} from 'vega-lite';
import {useTheme} from '@astryxdesign/core/theme';
import {parseSchema} from './schema';
import {withAstryxConfig} from './vegaLiteConfig';
import {latchViewInputs, latchIsCurrent} from './viewInputs';
import type {ViewInputs} from './viewInputs';
import type {VegaChartProps, VegaSpec, VegaLiteSpec} from './types';
Expand All @@ -33,6 +35,14 @@ import type {VegaChartProps, VegaSpec, VegaLiteSpec} from './types';
* vega.parse(spec, parseConfig, parseOptions)
* new vega.View(runtime, { ...viewOptions, container })
*
* Vega-Lite specs are themed out of the box: the Astryx config from
* `buildVegaLiteConfig` (axis/legend/mark/title chrome plus the shared
* `@astryxdesign/charts` categorical palette) is compiled in as the base
* config, resolved from the active `<Theme>`. Anything passed in
* `compileOptions.config` is merged on top and wins, and a spec's own inline
* `config` wins over both. Native Vega specs are not themed — they bypass
* compilation; use `parseConfig` for those.
*
* Initial dataset values can be provided via `data`. They are loaded once
* during View initialization, before the first render, and are not reactive:
* a change to `data` alone never rebuilds the View, and is not applied to the
Expand All @@ -49,6 +59,9 @@ import type {VegaChartProps, VegaSpec, VegaLiteSpec} from './types';
* (and its zoom, hover, and signal state), while a spec mutated in place is
* still picked up. Nothing needs to be memoized for either to hold.
*
* A theme or color-mode change re-creates a Vega-Lite View, because the theme
* config is compiled into the spec. It never re-creates a native Vega View.
*
* Callbacks (`onReady`, `onError`) are non-reactive Effect Events -- they
* always see the latest props and never re-run the View lifecycle, so you
* don't need to memoize them.
Expand Down Expand Up @@ -98,6 +111,19 @@ export function VegaChart({
}: VegaChartProps) {
const containerRef = useRef<HTMLDivElement>(null);

// Vega-Lite specs are compiled with the Astryx theme underneath the caller's
// own compile options, so a chart is themed out of the box. Native specs
// never compile, so they get the caller's options untouched: otherwise a
// theme or mode switch would change their inputs and rebuild the View for
// nothing. The merge is redone every render, not memoized on the caller's
// object, so an in-place edit to `compileOptions` still reaches the latch.
Comment thread
astracat-bot[bot] marked this conversation as resolved.
Resolved
const {token} = useTheme();
const schema = parseSchema(spec.$schema);
Comment thread
astracat-bot[bot] marked this conversation as resolved.
Resolved
const isVegaLite = schema.ok && schema.library === 'vega-lite';
const effectiveCompileOptions = isVegaLite
? withAstryxConfig(token, compileOptions)
: compileOptions;

// Rebuild only when a value the runtime is built from actually differs.
// The latch holds both the props the live View was built from and a copy of
// their values, so a spec mutated in place is caught too -- comparing
Expand All @@ -107,7 +133,7 @@ export function VegaChart({
// settles in one extra pass.
const inputs: ViewInputs = {
spec,
compileOptions,
compileOptions: effectiveCompileOptions,
parseConfig,
parseOptions,
viewOptions,
Expand Down
1 change: 1 addition & 0 deletions packages/vega/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ export {VegaChart} from './VegaChart';
export {parseSchema} from './schema';
export {
buildVegaLiteConfig,
withAstryxConfig,
DEFAULT_STROKE_WIDTH,
DEFAULT_POINT_SIZE,
DEFAULT_LEGEND_ORIENT,
Expand Down
Loading
Loading