Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 | 57x 57x 57x 2910x 2910x 906x 2910x 2910x 2910x 2910x 1812x 1812x 2910x 907x 2910x 2910x 2910x 906x 906x 906x 4530x 4530x 1023x 906x 906x 906x 1812x 1812x 906x 2910x 1812x 905x 2910x 906x 2910x 2910x 1812x 2910x 578x 2910x 603x 19x 19x 19x 2910x 411x 2910x 8472x 348x 8124x 1339x 1339x 1120x 219x 219x 219x 219x 6785x 2910x 8472x 8472x 8472x 2910x 147x 147x 147x 147x 3x 144x 5x 3x 141x 141x 12x 129x 141x 2910x 40x 40x 2x 38x 40x 2910x 69x 69x 12x 57x 69x 2910x 38x 2910x 118x 2910x 33x 2x 31x 31x 2910x 1068x 1068x 2910x 1562x 1562x 2910x 911x 2910x 2839x 2910x | import {
createContext,
useCallback,
useMemo,
useState,
useEffect,
useLayoutEffect,
useRef,
} from 'react';
// Side-effect import: emits the `--a8c-charts-*` catalog, scoped to the `a8c-charts-scope` class applied to this component's wrapper below. Every chart either sits under a `GlobalChartsProvider` or auto-mounts its own, so importing it here guarantees the catalog always reaches the bundle.
//
// This must be a direct import of the stylesheet, not through a re-export barrel: a barrel `.ts` file doesn't match this package's `sideEffects` glob (only `*.css`/`*.scss` do), so tsdown/Rolldown treats an unused barrel import as side-effect-free and drops it — taking the nested stylesheet import with it. The file also can't be named `*.module.scss`: it declares zero CSS-module class names (only a `:where()`-wrapped selector), and `@tsdown/css` marks a `.module.*` file's generated JS proxy `moduleSideEffects: false` (tree-shakeable unless a class name is read); a plain stylesheet gets `moduleSideEffects: "no-treeshake"` instead, so it always ships. `tools/assert-charts-scope-emitted.ts` fails `pnpm run build` if this regresses — a passing test suite alone does not catch a dropped stylesheet.
import '../../styles/chart-scope.scss';
import { CHART_SCOPE_CLASS } from '../../styles/chart-scope-class';
import {
createCssVariableResolver,
getItemShapeStyles,
getSeriesBarStyles,
getSeriesLineStyles,
isValidHexColor,
mergeThemes,
resolveCssVariable,
normalizeColorToHex,
} from '../../utils';
import { sanitizeFormatting } from '../../utils/date-formatting';
// Imported from the module rather than the `chart-scope` barrel: the barrel also pulls `use-standalone-scope-class`, which imports `GlobalChartsContext` back from this file. That cycle resolves today only because the binding is read lazily inside the hook body.
import { ChartScopeContext } from '../chart-scope/chart-scope-context';
import {
BACKGROUND_FALLBACK,
CATALOG_POINTERS,
LABEL_FALLBACK,
LABEL_INVERSE_FALLBACK,
} from './private/catalog-pointers';
import { createPaletteGenerator } from './private/palette-generator';
import { resolveOpaqueHex } from './private/resolve-opaque-hex';
import { SERIES_PALETTE_POINTERS, SERIES_SLOT_1_FALLBACK } from './private/series-palette';
import { defaultTheme } from './themes';
import type { GlobalChartsContextValue, ChartRegistration } from './types';
import type { ChartTheme, CompleteChartTheme } from '../../types';
import type { FC, ReactNode } from 'react';
interface ColorCache {
colors: string[];
background: string;
labelColors: string[];
colorAt: ( index: number ) => string;
}
const PLACEHOLDER_LABEL_COLORS = [ LABEL_FALLBACK, LABEL_INVERSE_FALLBACK ];
export const GlobalChartsContext = createContext< GlobalChartsContextValue | null >( null );
export interface GlobalChartsProviderProps {
children: ReactNode;
theme?: Partial< ChartTheme >;
/**
* BCP-47 language tag every date label is rendered in, e.g. `de-DE`.
* Defaults to the viewer's browser locale.
*/
locale?: string;
/**
* IANA time zone every date label is dated in, e.g. `Asia/Tokyo`.
* Defaults to the viewer's browser time zone.
*/
timeZone?: string;
}
export const GlobalChartsProvider: FC< GlobalChartsProviderProps > = ( {
children,
theme,
locale,
timeZone,
} ) => {
const [ charts, setCharts ] = useState< Map< string, ChartRegistration > >( () => new Map() );
// Track hidden series per chart: chartId -> Set<seriesLabel>
const [ hiddenSeries, setHiddenSeries ] = useState< Map< string, Set< string > > >(
() => new Map()
);
// Which charts have had their defaults seeded. Kept apart from `hiddenSeries`
// because that map drops a chart's entry once its hidden set empties, so an
// absent entry cannot tell "never seeded" from "the reader revealed the lot".
const seededCharts = useRef< Set< string > >( new Set() );
// Ref to the wrapper element for resolving scoped CSS variables
const wrapperRef = useRef< HTMLDivElement >( null );
const [ scopeNode, setScopeNode ] = useState< HTMLElement | null >( null );
const setWrapperNode = useCallback( ( node: HTMLDivElement | null ) => {
wrapperRef.current = node;
setScopeNode( node );
}, [] );
const providerTheme: CompleteChartTheme = useMemo(
() => ( theme ? mergeThemes( defaultTheme, theme ) : defaultTheme ),
[ theme ]
);
// Cache expensive color computations that only change when theme colors change
// Using useState + useLayoutEffect instead of useMemo to ensure CSS variables
// in <style> tags are applied to the DOM before we try to resolve them
// Seeded with what slot 1 resolves to where no DOM answers, so a one-series first render
// never builds the candidate grid and SSR matches the unthemed client palette.
const [ colorCache, setColorCache ] = useState< ColorCache >( () => ( {
colors: [],
background: BACKGROUND_FALLBACK,
labelColors: PLACEHOLDER_LABEL_COLORS,
colorAt: createPaletteGenerator(
[ SERIES_SLOT_1_FALLBACK ],
BACKGROUND_FALLBACK,
PLACEHOLDER_LABEL_COLORS
),
} ) );
// Track if the color palette has been resolved from the DOM
// Useful for animations that should only run after the color palette is resolved
const [ isColorPaletteResolved, setIsColorPaletteResolved ] = useState( false );
// A layout effect rather than a memo: the catalog reaches the wrapper as a stylesheet, which
// must be applied before `getComputedStyle` can answer. Mount only — the slots are a fixed
// manifest and `wrapperRef` is stable for the provider's life.
useLayoutEffect( () => {
setIsColorPaletteResolved( false );
const resolvedColors: string[] = [];
for ( const color of SERIES_PALETTE_POINTERS ) {
const normalizedColor = normalizeColorToHex( color, wrapperRef.current, resolveCssVariable );
// An unset palette slot returns its own `var()` unchanged, so this is also what
// compacts the palette: a slot the consumer never set drops out here.
if ( isValidHexColor( normalizedColor ) ) {
resolvedColors.push( normalizedColor );
}
}
const resolveAtWrapper = createCssVariableResolver( wrapperRef.current );
const backgroundHex =
resolveOpaqueHex( CATALOG_POINTERS.background, resolveAtWrapper ) ?? BACKGROUND_FALLBACK;
// The two roles pie labels choose between on a fill; one left see-through is never painted there.
const labelColors = [ CATALOG_POINTERS.label, CATALOG_POINTERS.labelInverse ]
.map( pointer => resolveOpaqueHex( pointer, resolveAtWrapper ) )
.filter( ( hex ): hex is string => hex !== null );
setColorCache( {
colors: resolvedColors,
background: backgroundHex,
labelColors,
colorAt: createPaletteGenerator( resolvedColors, backgroundHex, labelColors ),
} );
}, [] );
useEffect( () => {
if ( colorCache.colors.length > 0 ) {
setIsColorPaletteResolved( true );
}
}, [ colorCache ] );
const [ groupToColorMap, setGroupToColorMap ] = useState< Map< string, string > >(
() => new Map()
);
// Keyed on the resolved colors, background and labels, not the cache object, so a consumer passing an
// inline `theme` cannot reset the map on every render.
const paletteKey = `${ colorCache.colors.join( ',' ) }|${ colorCache.background }|${ colorCache.labelColors.join( ',' ) }`;
useEffect( () => {
// Create a completely new Map instance to trigger dependencies, e.g. useChartLegendItems
setGroupToColorMap( new Map() );
}, [ paletteKey ] );
const registerChart = useCallback( ( id: string, data: ChartRegistration ) => {
setCharts( prev => new Map( prev ).set( id, data ) );
}, [] );
const unregisterChart = useCallback( ( id: string ) => {
setCharts( prev => {
const newMap = new Map( prev );
newMap.delete( id );
return newMap;
} );
}, [] );
const getChartData = useCallback(
( id: string ) => {
return charts.get( id );
},
[ charts ]
);
const resolveColor = useCallback(
( {
group,
index,
overrideColor,
}: {
group?: string;
index: number;
overrideColor?: string;
} ): string => {
// Highest precedence: eg. explicit series stroke or chart color prop
if ( overrideColor ) {
return normalizeColorToHex( overrideColor, wrapperRef.current, resolveCssVariable );
}
// If group provided, maintain a stable assignment
if ( group ) {
const existing = groupToColorMap.get( group );
if ( existing ) {
return existing;
}
// Use map size as index to assign colors sequentially (0, 1, 2...)
// ensuring each new group gets the next available palette color
const assignedCount = groupToColorMap.size;
const color = colorCache.colorAt( assignedCount );
groupToColorMap.set( group, color );
return color;
}
return colorCache.colorAt( index );
},
[ colorCache, groupToColorMap ]
);
const getElementStyles = useCallback< GlobalChartsContextValue[ 'getElementStyles' ] >(
( { data, index, overrideColor, legendShape } ) => {
const isSeriesData = data && typeof data === 'object' && 'data' in data;
// DataPointPercentage has a numeric 'value' directly, unlike SeriesData which has 'data' array
const isPointPercentageData =
data &&
typeof data === 'object' &&
'value' in data &&
typeof data.value === 'number' &&
! ( 'data' in data );
return {
color: resolveColor( {
group: data?.group,
index,
overrideColor:
overrideColor ||
( isSeriesData && data?.options?.stroke ) ||
( isPointPercentageData && data?.color ),
} ),
lineStyles: isSeriesData ? getSeriesLineStyles( data, index, providerTheme ) : {},
barStyles: isSeriesData ? getSeriesBarStyles( data, index, providerTheme ) : {},
glyph: providerTheme.glyphs?.[ index ],
shapeStyles: isSeriesData
? getItemShapeStyles( data, index, providerTheme, legendShape )
: {},
};
},
[ providerTheme, resolveColor ]
);
// Keep hidden-series updates and no-op detection consistent across setters.
const updateHiddenSeries = useCallback(
( chartId: string, update: ( current: Set< string > ) => Set< string > ) => {
setHiddenSeries( prev => {
const current = prev.get( chartId );
const next = update( new Set( current ?? [] ) );
if ( ! current && next.size === 0 ) {
return prev;
}
// Preserve identity for no-op updates.
if (
current &&
current.size === next.size &&
[ ...next ].every( label => current.has( label ) )
) {
return prev;
}
const newMap = new Map( prev );
if ( next.size === 0 ) {
newMap.delete( chartId );
} else {
newMap.set( chartId, next );
}
return newMap;
} );
},
[]
);
const toggleSeriesVisibility = useCallback(
( chartId: string, seriesLabel: string ) => {
updateHiddenSeries( chartId, current => {
if ( current.has( seriesLabel ) ) {
current.delete( seriesLabel );
} else {
current.add( seriesLabel );
}
return current;
} );
},
[ updateHiddenSeries ]
);
const setSeriesVisibility = useCallback(
( chartId: string, seriesLabel: string, visible: boolean ) => {
updateHiddenSeries( chartId, current => {
if ( visible ) {
current.delete( seriesLabel );
} else {
current.add( seriesLabel );
}
return current;
} );
},
[ updateHiddenSeries ]
);
const setChartHiddenSeries = useCallback(
( chartId: string, seriesLabels: readonly string[] ) => {
updateHiddenSeries( chartId, () => new Set( seriesLabels ) );
},
[ updateHiddenSeries ]
);
const hasSeededChart = useCallback(
( chartId: string ) => seededCharts.current.has( chartId ),
[]
);
const seedChartHiddenSeries = useCallback(
( chartId: string, seriesLabels: readonly string[] ) => {
if ( seededCharts.current.has( chartId ) ) {
return;
}
seededCharts.current.add( chartId );
setChartHiddenSeries( chartId, seriesLabels );
},
[ setChartHiddenSeries ]
);
const isSeriesVisible = useCallback(
( chartId: string, seriesLabel: string ) => {
const chartHidden = hiddenSeries.get( chartId );
return ! chartHidden || ! chartHidden.has( seriesLabel );
},
[ hiddenSeries ]
);
const getHiddenSeries = useCallback(
( chartId: string ): Set< string > => {
const set = hiddenSeries.get( chartId );
return set ? new Set( set ) : new Set< string >();
},
[ hiddenSeries ]
);
// Held as one object so a chart's formatting memos key on a single stable reference.
const formatting = useMemo(
() => sanitizeFormatting( { locale, timeZone } ),
[ locale, timeZone ]
);
const value: GlobalChartsContextValue = useMemo(
() => ( {
charts,
registerChart,
unregisterChart,
getChartData,
theme: providerTheme,
formatting,
getElementStyles,
backgroundColor: colorCache.background,
toggleSeriesVisibility,
setSeriesVisibility,
setChartHiddenSeries,
seedChartHiddenSeries,
hasSeededChart,
isSeriesVisible,
getHiddenSeries,
isColorPaletteResolved,
} ),
[
charts,
registerChart,
unregisterChart,
getChartData,
providerTheme,
formatting,
getElementStyles,
colorCache.background,
toggleSeriesVisibility,
setSeriesVisibility,
setChartHiddenSeries,
seedChartHiddenSeries,
hasSeededChart,
isSeriesVisible,
getHiddenSeries,
isColorPaletteResolved,
]
);
return (
<GlobalChartsContext.Provider value={ value }>
<div
ref={ setWrapperNode }
className={ CHART_SCOPE_CLASS }
data-testid="charts-scope"
style={ { display: 'contents' } }
>
<ChartScopeContext.Provider value={ scopeNode }>{ children }</ChartScopeContext.Provider>
</div>
</GlobalChartsContext.Provider>
);
};
|