From 8b30b8813744afc757055db625a0a0a78f24b239 Mon Sep 17 00:00:00 2001 From: alex Date: Mon, 28 Oct 2024 16:54:36 +0100 Subject: [PATCH 1/8] Create selectors --- packages/x-charts/package.json | 5 +- .../src/context/InteractionProvider.tsx | 127 +----------------- .../src/context/InteractionSelectors.ts | 46 +++++++ .../src/internals/plugins/models/index.ts | 39 ++++++ .../internals/plugins/utils/ChartsStore.ts | 35 +++++ .../src/internals/plugins/utils/selectors.ts | 50 +++++++ packages/x-charts/src/internals/useCharts.ts | 25 ++++ .../x-charts/src/internals/useSelector.ts | 23 ++++ packages/x-charts/src/internals/useStore.ts | 25 ++++ pnpm-lock.yaml | 23 ++++ 10 files changed, 277 insertions(+), 121 deletions(-) create mode 100644 packages/x-charts/src/context/InteractionSelectors.ts create mode 100644 packages/x-charts/src/internals/plugins/models/index.ts create mode 100644 packages/x-charts/src/internals/plugins/utils/ChartsStore.ts create mode 100644 packages/x-charts/src/internals/plugins/utils/selectors.ts create mode 100644 packages/x-charts/src/internals/useCharts.ts create mode 100644 packages/x-charts/src/internals/useSelector.ts create mode 100644 packages/x-charts/src/internals/useStore.ts diff --git a/packages/x-charts/package.json b/packages/x-charts/package.json index f61fbfa05f64..dcc6517b8fb9 100644 --- a/packages/x-charts/package.json +++ b/packages/x-charts/package.json @@ -46,7 +46,9 @@ "@react-spring/rafz": "^9.7.5", "@react-spring/web": "^9.7.5", "clsx": "^2.1.1", - "prop-types": "^15.8.1" + "prop-types": "^15.8.1", + "reselect": "^5.1.1", + "use-sync-external-store": "^1.0.0" }, "peerDependencies": { "@emotion/react": "^11.9.0", @@ -71,6 +73,7 @@ "@react-spring/core": "^9.7.5", "@react-spring/shared": "^9.7.5", "@types/prop-types": "^15.7.13", + "@types/use-sync-external-store": "^0.0.6", "csstype": "^3.1.3", "rimraf": "^6.0.1" }, diff --git a/packages/x-charts/src/context/InteractionProvider.tsx b/packages/x-charts/src/context/InteractionProvider.tsx index 80c4658bfc1f..eeccf65f402b 100644 --- a/packages/x-charts/src/context/InteractionProvider.tsx +++ b/packages/x-charts/src/context/InteractionProvider.tsx @@ -1,132 +1,19 @@ 'use client'; import * as React from 'react'; -import { ChartItemIdentifier, ChartSeriesType } from '../models/seriesType/config'; +import { useCharts } from '../internals/useCharts'; +import { ChartsStore } from '../internals/plugins/utils/ChartsStore'; -export interface InteractionProviderProps { - children: React.ReactNode; -} - -export type ItemInteractionData = ChartItemIdentifier; - -export type AxisInteractionData = { - x: null | { - value: number | Date | string; - // Set to -1 if no index. - index: number; - }; - y: null | { - value: number | Date | string; - // Set to -1 if no index. - index: number; - }; -}; - -type InteractionActions = - | { - type: 'enterItem'; - data: ItemInteractionData; - } - | { - type: 'leaveItem'; - data: Partial>; - } - | { - type: 'exitChart'; - } - | { - type: 'updateVoronoiUsage'; - useVoronoiInteraction: boolean; - } - | { - type: 'updateAxis'; - data: AxisInteractionData; - }; - -type InteractionState = { - /** - * The item currently interacting. - */ - item: null | ItemInteractionData; - /** - * The x- and y-axes currently interacting. - */ - axis: AxisInteractionData; - /** - * Set to `true` when `VoronoiHandler` is active. - * Used to prevent collision with mouseEnter events. - */ - useVoronoiInteraction: boolean; - dispatch: React.Dispatch; -}; - -export const InteractionContext = React.createContext({ - item: null, - axis: { x: null, y: null }, - useVoronoiInteraction: false, - dispatch: () => null, -}); +export const ChartsContext = React.createContext<{ store: ChartsStore } | null>(null); if (process.env.NODE_ENV !== 'production') { - InteractionContext.displayName = 'InteractionContext'; + ChartsContext.displayName = 'ChartsContext'; } -const dataReducer: React.Reducer, InteractionActions> = ( - prevState, - action, -) => { - switch (action.type) { - case 'enterItem': - return { ...prevState, item: action.data }; - - case 'exitChart': - if (prevState.item === null && prevState.axis.x === null && prevState.axis.y === null) { - return prevState; - } - return { ...prevState, axis: { x: null, y: null }, item: null }; - - case 'updateVoronoiUsage': - return { ...prevState, useVoronoiInteraction: action.useVoronoiInteraction }; - - case 'leaveItem': - if ( - prevState.item === null || - (Object.keys(action.data) as (keyof ItemInteractionData)[]).some( - (key) => action.data[key] !== prevState.item![key], - ) - ) { - // The item is already something else - return prevState; - } - return { ...prevState, item: null }; - - case 'updateAxis': - if (action.data.x === prevState.axis.x && action.data.y === prevState.axis.y) { - return prevState; - } - return { ...prevState, axis: action.data }; - - default: - return prevState; - } -}; - -function InteractionProvider(props: InteractionProviderProps) { +function InteractionProvider(props: React.PropsWithChildren) { const { children } = props; - const [data, dispatch] = React.useReducer(dataReducer, { - item: null, - axis: { x: null, y: null }, - useVoronoiInteraction: false, - }); - - const value = React.useMemo( - () => ({ - ...data, - dispatch, - }), - [data], - ); - return {children}; + const { contextValue } = useCharts(); + return {children}; } export { InteractionProvider }; diff --git a/packages/x-charts/src/context/InteractionSelectors.ts b/packages/x-charts/src/context/InteractionSelectors.ts new file mode 100644 index 000000000000..4613b01b649a --- /dev/null +++ b/packages/x-charts/src/context/InteractionSelectors.ts @@ -0,0 +1,46 @@ +import { ChartsState } from '../internals/plugins/models'; +import { createSelector } from '../internals/plugins/utils/selectors'; + +function selectInteraction(state: ChartsState) { + return state.interaction; +} + +export const selectorChartsInteractionItem = createSelector( + selectInteraction, + (interaction) => interaction.item, +); + +export const selectorChartsInteractionAxis = createSelector( + selectInteraction, + (interaction) => interaction.axis, +); + +export const selectorChartsInteractionXAxis = createSelector( + selectInteraction, + (interaction) => interaction.axis.x, +); + +export const selectorChartsInteractionYAxis = createSelector( + selectInteraction, + (interaction) => interaction.axis.y, +); + +export const selectorChartsInteractionItemIsDefined = createSelector( + selectorChartsInteractionItem, + (item) => item !== null, +); + +export const selectorChartsInteractionXAxisIsDefined = createSelector( + selectorChartsInteractionXAxis, + (x) => x !== null, +); + +export const selectorChartsInteractionYAxisIsDefined = createSelector( + selectorChartsInteractionYAxis, + (y) => y !== null, +); + +export const selectorChartsInteractionUseVoronoid = createSelector( + selectInteraction, + (interaction) => interaction.useVoronoiInteraction, +); diff --git a/packages/x-charts/src/internals/plugins/models/index.ts b/packages/x-charts/src/internals/plugins/models/index.ts new file mode 100644 index 000000000000..c81b1036a7ea --- /dev/null +++ b/packages/x-charts/src/internals/plugins/models/index.ts @@ -0,0 +1,39 @@ +import { ChartItemIdentifier, ChartSeriesType } from '../../../models/seriesType/config'; + +export type ItemInteractionData = ChartItemIdentifier; + +export type AxisInteractionData = { + x: null | { + value: number | Date | string; + // Set to -1 if no index. + index: number; + }; + y: null | { + value: number | Date | string; + // Set to -1 if no index. + index: number; + }; +}; + +type InteractionState = { + /** + * The item currently interacting. + */ + item: null | ItemInteractionData; + /** + * The x- and y-axes currently interacting. + */ + axis: AxisInteractionData; + /** + * Set to `true` when `VoronoiHandler` is active. + * Used to prevent collision with mouseEnter events. + */ + useVoronoiInteraction?: boolean; +}; + +export type ChartsStateCacheKey = { id: number }; + +export type ChartsState = { + interaction: InteractionState; + cacheKey: ChartsStateCacheKey; +}; diff --git a/packages/x-charts/src/internals/plugins/utils/ChartsStore.ts b/packages/x-charts/src/internals/plugins/utils/ChartsStore.ts new file mode 100644 index 000000000000..8a09576097a7 --- /dev/null +++ b/packages/x-charts/src/internals/plugins/utils/ChartsStore.ts @@ -0,0 +1,35 @@ +import type { ChartsState } from '../models'; // For now this is fixed. Will need to support generic if we add plugins + +type Listener = (value: T) => void; + +export type StoreUpdater = (prevState: ChartsState) => ChartsState; + +export class ChartsStore { + public value: ChartsState; + + private listeners: Set>; + + constructor(value: ChartsState) { + this.value = value; + this.listeners = new Set(); + } + + public subscribe = (fn: Listener) => { + this.listeners.add(fn); + return () => { + this.listeners.delete(fn); + }; + }; + + public getSnapshot = () => { + return this.value; + }; + + public update = (updater: StoreUpdater) => { + const newState = updater(this.value); + if (newState !== this.value) { + this.value = newState; + this.listeners.forEach((l) => l(newState)); + } + }; +} diff --git a/packages/x-charts/src/internals/plugins/utils/selectors.ts b/packages/x-charts/src/internals/plugins/utils/selectors.ts new file mode 100644 index 000000000000..bc75b498e576 --- /dev/null +++ b/packages/x-charts/src/internals/plugins/utils/selectors.ts @@ -0,0 +1,50 @@ +import { lruMemoize, createSelectorCreator, CreateSelectorFunction } from 'reselect'; +import { ChartsState, ChartsStateCacheKey } from '../models'; + +const reselectCreateSelector = createSelectorCreator({ + memoize: lruMemoize, + memoizeOptions: { + maxSize: 1, + equalityCheck: Object.is, + }, +}); + +const cache = new WeakMap< + ChartsStateCacheKey, + Map, any> +>(); + +export type ChartsRootSelector = (state: ChartsState) => ChartsState[keyof ChartsState]; + +export type ChartsSelector = (state: TState, args: TArgs) => TResult; + +/** + * Method wrapping reselect's createSelector to provide caching for tree view instances. + * + */ +export const createSelector = ((...createSelectorArgs: any) => { + const selector: ChartsSelector = (state, selectorArgs) => { + const cacheKey = state.cacheKey; + + // If there is no cache for the current chart instance, create one. + let cacheForCurrentChartInstance = cache.get(cacheKey); + if (!cacheForCurrentChartInstance) { + cacheForCurrentChartInstance = new Map(); + cache.set(cacheKey, cacheForCurrentChartInstance); + } + + // If there is a cached selector, execute it. + const cachedSelector = cacheForCurrentChartInstance.get(createSelectorArgs); + if (cachedSelector) { + return cachedSelector(state, selectorArgs); + } + + // Otherwise, create a new selector and cache it and execute it. + const fn = reselectCreateSelector(...createSelectorArgs); + cacheForCurrentChartInstance.set(createSelectorArgs, fn); + + return fn(state, selectorArgs); + }; + + return selector; +}) as unknown as CreateSelectorFunction; diff --git a/packages/x-charts/src/internals/useCharts.ts b/packages/x-charts/src/internals/useCharts.ts new file mode 100644 index 000000000000..89a2d9e77532 --- /dev/null +++ b/packages/x-charts/src/internals/useCharts.ts @@ -0,0 +1,25 @@ +import * as React from 'react'; +import { ChartsStore } from './plugins/utils/ChartsStore'; +import { ChartsState } from './plugins/models'; + +let globalId = 0; + +export function useCharts() { + const storeRef = React.useRef(null); + if (storeRef.current == null) { + // eslint-disable-next-line react-compiler/react-compiler + globalId += 1; + const initialState: ChartsState = { + interaction: { + item: null, + axis: { x: null, y: null }, + }, + cacheKey: { id: globalId }, + }; + storeRef.current = new ChartsStore(initialState); + } + + const contextValue = React.useMemo(() => ({ store: storeRef.current as ChartsStore }), []); + + return { contextValue }; +} diff --git a/packages/x-charts/src/internals/useSelector.ts b/packages/x-charts/src/internals/useSelector.ts new file mode 100644 index 000000000000..41f93351c078 --- /dev/null +++ b/packages/x-charts/src/internals/useSelector.ts @@ -0,0 +1,23 @@ +import { useSyncExternalStoreWithSelector } from 'use-sync-external-store/with-selector'; +import { ChartsState } from './plugins/models'; +import { ChartsSelector } from './plugins/utils/selectors'; +import { ChartsStore } from './plugins/utils/ChartsStore'; + +const defaultCompare = Object.is; + +export const useSelector = ( + store: ChartsStore, + selector: ChartsSelector, + args: TArgs = undefined as TArgs, + equals: (a: TValue, b: TValue) => boolean = defaultCompare, +): TValue => { + const selectorWithArgs = (state: ChartsState) => selector(state, args); + + return useSyncExternalStoreWithSelector( + store.subscribe, + store.getSnapshot, + store.getSnapshot, + selectorWithArgs, + equals, + ); +}; diff --git a/packages/x-charts/src/internals/useStore.ts b/packages/x-charts/src/internals/useStore.ts new file mode 100644 index 000000000000..f218a6226951 --- /dev/null +++ b/packages/x-charts/src/internals/useStore.ts @@ -0,0 +1,25 @@ +import * as React from 'react'; +import { ChartsContext } from '../context/InteractionProvider'; +import { ChartsStore } from './plugins/utils/ChartsStore'; + +export function useStore(skipError?: boolean): ChartsStore { + const charts = React.useContext(ChartsContext); + + if (skipError) { + // This line is only for `useAxisEvents` which is in the surface of the Gauge. + // But the Gauge don't have store yet because it does not need the interaction provider. + // Will be fixed when every thing move to the store since every component will have access to it. + // @ts-ignore + return charts?.store; + } + if (!charts) { + throw new Error( + [ + 'MUI X: Could not find the charts context.', + 'It looks like you rendered your component outside of a ChartsContainer parent component.', + ].join('\n'), + ); + } + + return charts.store; +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 63cac7483cb2..97b041009a32 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -769,6 +769,12 @@ importers: react-dom: specifier: ^17.0.0 || ^18.0.0 version: 18.3.1(react@18.3.1) + reselect: + specifier: ^5.1.1 + version: 5.1.1 + use-sync-external-store: + specifier: ^1.0.0 + version: 1.2.2(react@18.3.1) devDependencies: '@mui/internal-test-utils': specifier: ^1.0.20 @@ -788,6 +794,9 @@ importers: '@types/prop-types': specifier: ^15.7.13 version: 15.7.13 + '@types/use-sync-external-store': + specifier: ^0.0.6 + version: 0.0.6 csstype: specifier: ^3.1.3 version: 3.1.3 @@ -4268,6 +4277,9 @@ packages: '@types/unist@3.0.3': resolution: {integrity: sha512-ko/gIFJRv177XgZsZcBwnqJN5x/Gien8qNOn0D5bQU/zAzVf9Zt3BlcUiLqhV9y4ARk0GbT3tnUiPNgnTXzc/Q==} + '@types/use-sync-external-store@0.0.6': + resolution: {integrity: sha512-zFDAD+tlpf2r4asuHEj0XH6pY6i0g5NeAHPn+15wk3BV6JA69eERFXC1gyGThDkVa1zCyKr5jox1+2LbV/AMLg==} + '@types/webpack-bundle-analyzer@4.7.0': resolution: {integrity: sha512-c5i2ThslSNSG8W891BRvOd/RoCjI2zwph8maD22b1adtSns20j+0azDDMCK06DiVrzTgnwiDl5Ntmu1YRJw8Sg==} @@ -9922,6 +9934,11 @@ packages: urlpattern-polyfill@8.0.2: resolution: {integrity: sha512-Qp95D4TPJl1kC9SKigDcqgyM2VDVO4RiJc2d4qe5GrYm+zbIQCWWKAFaJNQ4BhdFeDGwBmAxqJBwWSJDb9T3BQ==} + use-sync-external-store@1.2.2: + resolution: {integrity: sha512-PElTlVMwpblvbNqQ82d2n6RjStvdSoNe9FG28kNfz3WiXilJm4DdNkEzRhCZuIDwY8U08WVihhGR5iRqAwfDiw==} + peerDependencies: + react: ^16.8.0 || ^17.0.0 || ^18.0.0 + util-deprecate@1.0.2: resolution: {integrity: sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==} @@ -13344,6 +13361,8 @@ snapshots: '@types/unist@3.0.3': {} + '@types/use-sync-external-store@0.0.6': {} + '@types/webpack-bundle-analyzer@4.7.0(@swc/core@1.7.35(@swc/helpers@0.5.5))(webpack-cli@5.1.4(webpack-bundle-analyzer@4.10.2)(webpack@5.96.1))': dependencies: '@types/node': 20.17.6 @@ -20064,6 +20083,10 @@ snapshots: urlpattern-polyfill@8.0.2: {} + use-sync-external-store@1.2.2(react@18.3.1): + dependencies: + react: 18.3.1 + util-deprecate@1.0.2: {} util.inherits@1.0.3: {} From e8b61c5510e5a526c558ed1c4cd136808a5af5d3 Mon Sep 17 00:00:00 2001 From: alex Date: Thu, 14 Nov 2024 20:14:53 +0100 Subject: [PATCH 2/8] Update Axis Highlight --- .../ChartsAxisHighlight.tsx | 150 +----------------- .../ChartsAxisHighlight.types.ts | 6 + .../ChartsAxisHighlightPath.ts | 37 +++++ .../ChartsXAxisHighlight.tsx | 69 ++++++++ .../ChartsYAxisHighlight.tsx | 71 +++++++++ .../chartsAxisHighlightClasses.ts | 18 +++ .../x-charts/src/ChartsAxisHighlight/index.ts | 3 + scripts/x-charts-pro.exports.json | 1 + scripts/x-charts.exports.json | 1 + 9 files changed, 213 insertions(+), 143 deletions(-) create mode 100644 packages/x-charts/src/ChartsAxisHighlight/ChartsAxisHighlight.types.ts create mode 100644 packages/x-charts/src/ChartsAxisHighlight/ChartsAxisHighlightPath.ts create mode 100644 packages/x-charts/src/ChartsAxisHighlight/ChartsXAxisHighlight.tsx create mode 100644 packages/x-charts/src/ChartsAxisHighlight/ChartsYAxisHighlight.tsx create mode 100644 packages/x-charts/src/ChartsAxisHighlight/chartsAxisHighlightClasses.ts diff --git a/packages/x-charts/src/ChartsAxisHighlight/ChartsAxisHighlight.tsx b/packages/x-charts/src/ChartsAxisHighlight/ChartsAxisHighlight.tsx index 5712979e916c..a53bfafff95f 100644 --- a/packages/x-charts/src/ChartsAxisHighlight/ChartsAxisHighlight.tsx +++ b/packages/x-charts/src/ChartsAxisHighlight/ChartsAxisHighlight.tsx @@ -2,29 +2,10 @@ import * as React from 'react'; import PropTypes from 'prop-types'; import composeClasses from '@mui/utils/composeClasses'; -import generateUtilityClass from '@mui/utils/generateUtilityClass'; -import generateUtilityClasses from '@mui/utils/generateUtilityClasses'; -import { styled } from '@mui/material/styles'; -import { InteractionContext } from '../context/InteractionProvider'; -import { useCartesianContext } from '../context/CartesianProvider'; -import { getValueToPositionMapper } from '../hooks/useScale'; -import { isBandScale } from '../internals/isBandScale'; - -export interface ChartsAxisHighlightClasses { - /** Styles applied to the root element. */ - root: string; -} - -export type ChartsAxisHighlightClassKey = keyof ChartsAxisHighlightClasses; - -export function getAxisHighlightUtilityClass(slot: string) { - return generateUtilityClass('MuiChartsAxisHighlight', slot); -} - -export const chartsAxisHighlightClasses: ChartsAxisHighlightClasses = generateUtilityClasses( - 'MuiChartsAxisHighlight', - ['root'], -); +import { getAxisHighlightUtilityClass } from './chartsAxisHighlightClasses'; +import ChartsYHighlight from './ChartsYAxisHighlight'; +import ChartsXHighlight from './ChartsXAxisHighlight'; +import { ChartsAxisHighlightProps } from './ChartsAxisHighlight.types'; const useUtilityClasses = () => { const slots = { @@ -34,47 +15,6 @@ const useUtilityClasses = () => { return composeClasses(slots, getAxisHighlightUtilityClass); }; -export const ChartsAxisHighlightPath = styled('path', { - name: 'MuiChartsAxisHighlight', - slot: 'Root', - overridesResolver: (_, styles) => styles.root, -})<{ ownerState: { axisHighlight: AxisHighlight } }>(({ theme }) => ({ - pointerEvents: 'none', - variants: [ - { - props: { - axisHighlight: 'band', - }, - style: { - fill: 'white', - fillOpacity: 0.1, - ...theme.applyStyles('light', { - fill: 'gray', - }), - }, - }, - { - props: { - axisHighlight: 'line', - }, - style: { - strokeDasharray: '5 2', - stroke: '#ffffff', - ...theme.applyStyles('light', { - stroke: '#000000', - }), - }, - }, - ], -})); - -type AxisHighlight = 'none' | 'line' | 'band'; - -export type ChartsAxisHighlightProps = { - x?: AxisHighlight; - y?: AxisHighlight; -}; - /** * Demos: * @@ -86,88 +26,12 @@ export type ChartsAxisHighlightProps = { */ function ChartsAxisHighlight(props: ChartsAxisHighlightProps) { const { x: xAxisHighlight, y: yAxisHighlight } = props; - const { xAxisIds, xAxis, yAxisIds, yAxis } = useCartesianContext(); - const classes = useUtilityClasses(); - - const USED_X_AXIS_ID = xAxisIds[0]; - const USED_Y_AXIS_ID = yAxisIds[0]; - - const xScale = xAxis[USED_X_AXIS_ID].scale; - const yScale = yAxis[USED_Y_AXIS_ID].scale; - - const { axis } = React.useContext(InteractionContext); - - const getXPosition = getValueToPositionMapper(xScale); - const getYPosition = getValueToPositionMapper(yScale); - - const axisX = axis.x; - const axisY = axis.y; - - const isBandScaleX = xAxisHighlight === 'band' && axisX !== null && isBandScale(xScale); - const isBandScaleY = yAxisHighlight === 'band' && axisY !== null && isBandScale(yScale); - - if (process.env.NODE_ENV !== 'production') { - const isXError = isBandScaleX && xScale(axisX.value) === undefined; - const isYError = isBandScaleY && yScale(axisY.value) === undefined; - - if (isXError || isYError) { - console.error( - [ - `MUI X: The position value provided for the axis is not valid for the current scale.`, - `This probably means something is wrong with the data passed to the chart.`, - `The ChartsAxisHighlight component will not be displayed.`, - ].join('\n'), - ); - } - } + const classes = useUtilityClasses(); return ( - {isBandScaleX && xScale(axisX.value) !== undefined && ( - - )} - - {isBandScaleY && yScale(axisY.value) !== undefined && ( - - )} - - {xAxisHighlight === 'line' && axis.x !== null && ( - - )} - - {yAxisHighlight === 'line' && axis.y !== null && ( - - )} + {xAxisHighlight && } + {yAxisHighlight && } ); } diff --git a/packages/x-charts/src/ChartsAxisHighlight/ChartsAxisHighlight.types.ts b/packages/x-charts/src/ChartsAxisHighlight/ChartsAxisHighlight.types.ts new file mode 100644 index 000000000000..de1b75d43438 --- /dev/null +++ b/packages/x-charts/src/ChartsAxisHighlight/ChartsAxisHighlight.types.ts @@ -0,0 +1,6 @@ +export type ChartsAxisHighlightType = 'none' | 'line' | 'band'; + +export type ChartsAxisHighlightProps = { + x?: ChartsAxisHighlightType; + y?: ChartsAxisHighlightType; +}; diff --git a/packages/x-charts/src/ChartsAxisHighlight/ChartsAxisHighlightPath.ts b/packages/x-charts/src/ChartsAxisHighlight/ChartsAxisHighlightPath.ts new file mode 100644 index 000000000000..d015d2b5d15c --- /dev/null +++ b/packages/x-charts/src/ChartsAxisHighlight/ChartsAxisHighlightPath.ts @@ -0,0 +1,37 @@ +'use client'; +import { styled } from '@mui/material/styles'; +import { ChartsAxisHighlightType } from './ChartsAxisHighlight.types'; + +export const ChartsAxisHighlightPath = styled('path', { + name: 'MuiChartsAxisHighlight', + slot: 'Root', + overridesResolver: (_, styles) => styles.root, +})<{ ownerState: { axisHighlight: ChartsAxisHighlightType } }>(({ theme }) => ({ + pointerEvents: 'none', + variants: [ + { + props: { + axisHighlight: 'band', + }, + style: { + fill: 'white', + fillOpacity: 0.1, + ...theme.applyStyles('light', { + fill: 'gray', + }), + }, + }, + { + props: { + axisHighlight: 'line', + }, + style: { + strokeDasharray: '5 2', + stroke: '#ffffff', + ...theme.applyStyles('light', { + stroke: '#000000', + }), + }, + }, + ], +})); diff --git a/packages/x-charts/src/ChartsAxisHighlight/ChartsXAxisHighlight.tsx b/packages/x-charts/src/ChartsAxisHighlight/ChartsXAxisHighlight.tsx new file mode 100644 index 000000000000..d828547af94e --- /dev/null +++ b/packages/x-charts/src/ChartsAxisHighlight/ChartsXAxisHighlight.tsx @@ -0,0 +1,69 @@ +'use client'; +import * as React from 'react'; +import { getValueToPositionMapper, useXScale } from '../hooks/useScale'; +import { isBandScale } from '../internals/isBandScale'; +import { useSelector } from '../internals/useSelector'; +import { useStore } from '../internals/useStore'; +import { selectorChartsInteractionXAxis } from '../context/InteractionSelectors'; +import { useDrawingArea } from '../hooks'; +import { ChartsAxisHighlightType } from './ChartsAxisHighlight.types'; +import { ChartsAxisHighlightClasses } from './chartsAxisHighlightClasses'; +import { ChartsAxisHighlightPath } from './ChartsAxisHighlightPath'; + +/** + * @ignore - internal component. + */ +export default function ChartsXHighlight(props: { + type: ChartsAxisHighlightType; + classes: ChartsAxisHighlightClasses; +}) { + const { type, classes } = props; + + const { top, height } = useDrawingArea(); + + const xScale = useXScale(); + + const store = useStore(); + const axisX = useSelector(store, selectorChartsInteractionXAxis); + + const getXPosition = getValueToPositionMapper(xScale); + + const isBandScaleX = type === 'band' && axisX !== null && isBandScale(xScale); + + if (process.env.NODE_ENV !== 'production') { + const isError = isBandScaleX && xScale(axisX.value) === undefined; + + if (isError) { + console.error( + [ + `MUI X: The position value provided for the axis is not valid for the current scale.`, + `This probably means something is wrong with the data passed to the chart.`, + `The ChartsAxisHighlight component will not be displayed.`, + ].join('\n'), + ); + } + } + + return ( + + {isBandScaleX && xScale(axisX.value) !== undefined && ( + + )} + + {type === 'line' && axisX !== null && ( + + )} + + ); +} diff --git a/packages/x-charts/src/ChartsAxisHighlight/ChartsYAxisHighlight.tsx b/packages/x-charts/src/ChartsAxisHighlight/ChartsYAxisHighlight.tsx new file mode 100644 index 000000000000..ce996fb544df --- /dev/null +++ b/packages/x-charts/src/ChartsAxisHighlight/ChartsYAxisHighlight.tsx @@ -0,0 +1,71 @@ +'use client'; +import * as React from 'react'; +import { getValueToPositionMapper, useYScale } from '../hooks/useScale'; +import { isBandScale } from '../internals/isBandScale'; +import { useSelector } from '../internals/useSelector'; +import { useStore } from '../internals/useStore'; +import { selectorChartsInteractionYAxis } from '../context/InteractionSelectors'; +import { useDrawingArea } from '../hooks'; +import { ChartsAxisHighlightType } from './ChartsAxisHighlight.types'; +import { ChartsAxisHighlightClasses } from './chartsAxisHighlightClasses'; +import { ChartsAxisHighlightPath } from './ChartsAxisHighlightPath'; + +/** + * @ignore - internal component. + */ +export default function ChartsYHighlight(props: { + type: ChartsAxisHighlightType; + classes: ChartsAxisHighlightClasses; +}) { + const { type, classes } = props; + + const { left, width } = useDrawingArea(); + + const yScale = useYScale(); + + const store = useStore(); + const axisY = useSelector(store, selectorChartsInteractionYAxis); + + const getYPosition = getValueToPositionMapper(yScale); + + const isBandScaleY = type === 'band' && axisY !== null && isBandScale(yScale); + + if (process.env.NODE_ENV !== 'production') { + const isError = isBandScaleY && yScale(axisY.value) === undefined; + + if (isError) { + console.error( + [ + `MUI X: The position value provided for the axis is not valid for the current scale.`, + `This probably means something is wrong with the data passed to the chart.`, + `The ChartsAxisHighlight component will not be displayed.`, + ].join('\n'), + ); + } + } + + return ( + + {isBandScaleY && yScale(axisY.value) !== undefined && ( + + )} + + {type === 'line' && axisY !== null && ( + + )} + + ); +} diff --git a/packages/x-charts/src/ChartsAxisHighlight/chartsAxisHighlightClasses.ts b/packages/x-charts/src/ChartsAxisHighlight/chartsAxisHighlightClasses.ts new file mode 100644 index 000000000000..7d62c32d82fa --- /dev/null +++ b/packages/x-charts/src/ChartsAxisHighlight/chartsAxisHighlightClasses.ts @@ -0,0 +1,18 @@ +import generateUtilityClass from '@mui/utils/generateUtilityClass'; +import generateUtilityClasses from '@mui/utils/generateUtilityClasses'; + +export interface ChartsAxisHighlightClasses { + /** Styles applied to the root element. */ + root: string; +} + +export type ChartsAxisHighlightClassKey = keyof ChartsAxisHighlightClasses; + +export function getAxisHighlightUtilityClass(slot: string) { + return generateUtilityClass('MuiChartsAxisHighlight', slot); +} + +export const chartsAxisHighlightClasses: ChartsAxisHighlightClasses = generateUtilityClasses( + 'MuiChartsAxisHighlight', + ['root'], +); diff --git a/packages/x-charts/src/ChartsAxisHighlight/index.ts b/packages/x-charts/src/ChartsAxisHighlight/index.ts index 14c071e360be..653afd1cfd87 100644 --- a/packages/x-charts/src/ChartsAxisHighlight/index.ts +++ b/packages/x-charts/src/ChartsAxisHighlight/index.ts @@ -1 +1,4 @@ export * from './ChartsAxisHighlight'; +export * from './chartsAxisHighlightClasses'; +export * from './ChartsAxisHighlight.types'; +export * from './ChartsAxisHighlightPath'; diff --git a/scripts/x-charts-pro.exports.json b/scripts/x-charts-pro.exports.json index 1d29c9cafbc0..7f47fc004ea4 100644 --- a/scripts/x-charts-pro.exports.json +++ b/scripts/x-charts-pro.exports.json @@ -68,6 +68,7 @@ { "name": "ChartsAxisHighlightClassKey", "kind": "TypeAlias" }, { "name": "ChartsAxisHighlightPath", "kind": "Variable" }, { "name": "ChartsAxisHighlightProps", "kind": "TypeAlias" }, + { "name": "ChartsAxisHighlightType", "kind": "TypeAlias" }, { "name": "ChartsAxisProps", "kind": "Interface" }, { "name": "ChartsAxisTooltipContent", "kind": "Function" }, { "name": "ChartsClipPath", "kind": "Function" }, diff --git a/scripts/x-charts.exports.json b/scripts/x-charts.exports.json index 7a4b49ed6348..585b75fa9cd8 100644 --- a/scripts/x-charts.exports.json +++ b/scripts/x-charts.exports.json @@ -66,6 +66,7 @@ { "name": "ChartsAxisHighlightClassKey", "kind": "TypeAlias" }, { "name": "ChartsAxisHighlightPath", "kind": "Variable" }, { "name": "ChartsAxisHighlightProps", "kind": "TypeAlias" }, + { "name": "ChartsAxisHighlightType", "kind": "TypeAlias" }, { "name": "ChartsAxisProps", "kind": "Interface" }, { "name": "ChartsAxisTooltipContent", "kind": "Function" }, { "name": "ChartsClipPath", "kind": "Function" }, From 8fa30ce610aa87a1c34eb32d04e3857e10389780 Mon Sep 17 00:00:00 2001 From: alex Date: Thu, 14 Nov 2024 20:17:05 +0100 Subject: [PATCH 3/8] replace dispatch by store updates --- .../ChartsVoronoiHandler.tsx | 40 ++++++++++++++----- packages/x-charts/src/hooks/useAxisEvents.ts | 39 ++++++++++++++---- .../src/hooks/useInteractionItemProps.ts | 36 +++++++++++++---- 3 files changed, 91 insertions(+), 24 deletions(-) diff --git a/packages/x-charts/src/ChartsVoronoiHandler/ChartsVoronoiHandler.tsx b/packages/x-charts/src/ChartsVoronoiHandler/ChartsVoronoiHandler.tsx index ad1dea102fc6..f0169fb95025 100644 --- a/packages/x-charts/src/ChartsVoronoiHandler/ChartsVoronoiHandler.tsx +++ b/packages/x-charts/src/ChartsVoronoiHandler/ChartsVoronoiHandler.tsx @@ -3,9 +3,9 @@ import * as React from 'react'; import PropTypes from 'prop-types'; import { Delaunay } from '@mui/x-charts-vendor/d3-delaunay'; import useEnhancedEffect from '@mui/utils/useEnhancedEffect'; -import { InteractionContext } from '../context/InteractionProvider'; import { useCartesianContext } from '../context/CartesianProvider'; import { getValueToPositionMapper } from '../hooks/useScale'; +import { useStore } from '../internals/useStore'; import { getSVGPoint } from '../internals/getSVGPoint'; import { ScatterItemIdentifier } from '../models'; import { SeriesId } from '../models/seriesType/common'; @@ -34,7 +34,7 @@ function ChartsVoronoiHandler(props: ChartsVoronoiHandlerProps) { const svgRef = useSvgRef(); const drawingArea = useDrawingArea(); const { xAxis, yAxis, xAxisIds, yAxisIds } = useCartesianContext(); - const { dispatch } = React.useContext(InteractionContext); + const store = useStore(); const { series, seriesOrder } = useScatterSeries() ?? {}; const voronoiRef = React.useRef>({}); @@ -47,11 +47,18 @@ function ChartsVoronoiHandler(props: ChartsVoronoiHandlerProps) { const defaultYAxisId = yAxisIds[0]; useEnhancedEffect(() => { - dispatch({ type: 'updateVoronoiUsage', useVoronoiInteraction: true }); + store.update((prev) => ({ + ...prev, + interaction: { ...prev.interaction, useVoronoiInteraction: true }, + })); + return () => { - dispatch({ type: 'updateVoronoiUsage', useVoronoiInteraction: false }); + store.update((prev) => ({ + ...prev, + interaction: { ...prev.interaction, useVoronoiInteraction: false }, + })); }; - }, [dispatch]); + }, [store]); useEnhancedEffect(() => { // This effect generate and store the Delaunay object that's used to map coordinate to closest point. @@ -153,7 +160,10 @@ function ChartsVoronoiHandler(props: ChartsVoronoiHandlerProps) { } const handleMouseLeave = () => { - dispatch({ type: 'exitChart' }); + store.update((prev) => ({ + ...prev, + interaction: { ...prev.interaction, axis: { x: null, y: null }, item: null }, + })); clearHighlighted(); }; @@ -161,19 +171,29 @@ function ChartsVoronoiHandler(props: ChartsVoronoiHandlerProps) { const closestPoint = getClosestPoint(event); if (closestPoint === 'outside-chart') { - dispatch({ type: 'exitChart' }); + store.update((prev) => ({ + ...prev, + interaction: { ...prev.interaction, axis: { x: null, y: null }, item: null }, + })); clearHighlighted(); return; } if (closestPoint === 'outside-voronoi-max-radius' || closestPoint === 'no-point-found') { - dispatch({ type: 'leaveItem', data: { type: 'scatter' } }); + store.update((prev) => ({ + ...prev, + interaction: { ...prev.interaction, item: null }, + })); clearHighlighted(); return; } const { seriesId, dataIndex } = closestPoint; - dispatch({ type: 'enterItem', data: { type: 'scatter', seriesId, dataIndex } }); + store.update((prev) => ({ + ...prev, + interaction: { ...prev.interaction, item: { type: 'scatter', seriesId, dataIndex } }, + })); + setHighlighted({ seriesId, dataIndex, @@ -205,7 +225,6 @@ function ChartsVoronoiHandler(props: ChartsVoronoiHandlerProps) { }; }, [ svgRef, - dispatch, yAxis, xAxis, voronoiMaxRadius, @@ -213,6 +232,7 @@ function ChartsVoronoiHandler(props: ChartsVoronoiHandlerProps) { setHighlighted, clearHighlighted, drawingArea, + store, ]); // eslint-disable-next-line react/jsx-no-useless-fragment diff --git a/packages/x-charts/src/hooks/useAxisEvents.ts b/packages/x-charts/src/hooks/useAxisEvents.ts index f3973f3fb393..2860ba00e32e 100644 --- a/packages/x-charts/src/hooks/useAxisEvents.ts +++ b/packages/x-charts/src/hooks/useAxisEvents.ts @@ -1,12 +1,12 @@ 'use client'; import * as React from 'react'; -import { InteractionContext } from '../context/InteractionProvider'; import { useCartesianContext } from '../context/CartesianProvider'; import { isBandScale } from '../internals/isBandScale'; import { AxisDefaultized } from '../models/axis'; import { getSVGPoint } from '../internals/getSVGPoint'; import { useSvgRef } from './useSvgRef'; import { useDrawingArea } from './useDrawingArea'; +import { useStore } from '../internals/useStore'; function getAsANumber(value: number | Date) { return value instanceof Date ? value.getTime() : value; @@ -15,7 +15,8 @@ export const useAxisEvents = (disableAxisListener: boolean) => { const svgRef = useSvgRef(); const drawingArea = useDrawingArea(); const { xAxis, yAxis, xAxisIds, yAxisIds } = useCartesianContext(); - const { dispatch } = React.useContext(InteractionContext); + + const store = useStore(disableAxisListener); const usedXAxis = xAxisIds[0]; const usedYAxis = yAxisIds[0]; @@ -29,7 +30,7 @@ export const useAxisEvents = (disableAxisListener: boolean) => { React.useEffect(() => { const element = svgRef.current; - if (element === null || disableAxisListener) { + if (element === null || disableAxisListener || !store) { return () => {}; } @@ -100,7 +101,11 @@ export const useAxisEvents = (disableAxisListener: boolean) => { x: -1, y: -1, }; - dispatch({ type: 'exitChart' }); + + store.update((prev) => ({ + ...prev, + interaction: { item: null, axis: { x: null, y: null } }, + })); }; const handleMove = (event: MouseEvent | TouchEvent) => { @@ -112,7 +117,10 @@ export const useAxisEvents = (disableAxisListener: boolean) => { if (!drawingArea.isPointInside(svgPoint, { targetElement: event.target as SVGElement })) { if (mousePosition.current.isInChart) { - dispatch({ type: 'exitChart' }); + store.update((prev) => ({ + ...prev, + interaction: { item: null, axis: { x: null, y: null } }, + })); mousePosition.current.isInChart = false; } return; @@ -121,7 +129,24 @@ export const useAxisEvents = (disableAxisListener: boolean) => { const newStateX = getNewAxisState(xAxis[usedXAxis], svgPoint.x); const newStateY = getNewAxisState(yAxis[usedYAxis], svgPoint.y); - dispatch({ type: 'updateAxis', data: { x: newStateX, y: newStateY } }); + store.update((prev) => ({ + ...prev, + interaction: { + ...prev.interaction, + axis: { + // A bit verbose, but prevent losing the x value if only y got modified. + ...prev.interaction.axis, + ...(prev.interaction.axis.x?.index !== newStateX?.index || + prev.interaction.axis.x?.value !== newStateX?.value + ? { x: newStateX } + : {}), + ...(prev.interaction.axis.y?.index !== newStateY?.index || + prev.interaction.axis.y?.value !== newStateY?.value + ? { y: newStateY } + : {}), + }, + }, + })); }; const handleDown = (event: PointerEvent) => { @@ -147,5 +172,5 @@ export const useAxisEvents = (disableAxisListener: boolean) => { element.removeEventListener('pointercancel', handleOut); element.removeEventListener('pointerleave', handleOut); }; - }, [svgRef, dispatch, usedYAxis, yAxis, usedXAxis, xAxis, disableAxisListener, drawingArea]); + }, [svgRef, store, usedYAxis, yAxis, usedXAxis, xAxis, disableAxisListener, drawingArea]); }; diff --git a/packages/x-charts/src/hooks/useInteractionItemProps.ts b/packages/x-charts/src/hooks/useInteractionItemProps.ts index 49a6e5e70c90..7474425fe650 100644 --- a/packages/x-charts/src/hooks/useInteractionItemProps.ts +++ b/packages/x-charts/src/hooks/useInteractionItemProps.ts @@ -1,11 +1,11 @@ 'use client'; import * as React from 'react'; -import { InteractionContext } from '../context/InteractionProvider'; import { SeriesItemIdentifier } from '../models'; import { useHighlighted } from '../context'; +import { useStore } from '../internals/useStore'; export const useInteractionItemProps = (skip?: boolean) => { - const { dispatch: dispatchInteraction } = React.useContext(InteractionContext); + const store = useStore(); const { setHighlighted, clearHighlighted } = useHighlighted(); if (skip) { @@ -18,10 +18,13 @@ export const useInteractionItemProps = (skip?: boolean) => { } }; const onPointerEnter = () => { - dispatchInteraction({ - type: 'enterItem', - data, - }); + store.update((prev) => ({ + ...prev, + interaction: { + ...prev.interaction, + item: data, + }, + })); setHighlighted({ seriesId: data.seriesId, dataIndex: data.dataIndex, @@ -29,7 +32,26 @@ export const useInteractionItemProps = (skip?: boolean) => { }; const onPointerLeave = (event: React.PointerEvent) => { event.currentTarget.releasePointerCapture(event.pointerId); - dispatchInteraction({ type: 'leaveItem', data }); + + store.update((prev) => { + const prevItem = prev.interaction.item; + if ( + prevItem === null || + Object.keys(data).some( + (key) => data[key as keyof typeof data] !== prevItem[key as keyof typeof prevItem], + ) + ) { + // The item is already something else, no need to clean it. + return prev; + } + return { + ...prev, + interaction: { + ...prev.interaction, + item: null, + }, + }; + }); clearHighlighted(); }; return { From e2c9cd25fb3ca3454667f71de59bac4d1e8c29a1 Mon Sep 17 00:00:00 2001 From: alex Date: Thu, 14 Nov 2024 20:17:34 +0100 Subject: [PATCH 4/8] update tooltip --- .../ChartsAxisTooltipContent.tsx | 2 +- .../ChartsItemTooltipContent.tsx | 2 +- .../src/ChartsTooltip/ChartsTooltip.tsx | 16 +++--- .../src/ChartsTooltip/useAxisTooltip.tsx | 49 +++++++++++++------ .../src/ChartsTooltip/useItemTooltip.tsx | 8 ++- packages/x-charts/src/ChartsTooltip/utils.tsx | 2 +- 6 files changed, 52 insertions(+), 27 deletions(-) diff --git a/packages/x-charts/src/ChartsTooltip/ChartsAxisTooltipContent.tsx b/packages/x-charts/src/ChartsTooltip/ChartsAxisTooltipContent.tsx index 28b6f6f833e0..ed4f1a6608b4 100644 --- a/packages/x-charts/src/ChartsTooltip/ChartsAxisTooltipContent.tsx +++ b/packages/x-charts/src/ChartsTooltip/ChartsAxisTooltipContent.tsx @@ -1,7 +1,7 @@ import * as React from 'react'; import { SxProps, Theme } from '@mui/material/styles'; import useSlotProps from '@mui/utils/useSlotProps'; -import { AxisInteractionData } from '../context/InteractionProvider'; +import { AxisInteractionData } from '../internals/plugins/models'; import { useCartesianContext } from '../context/CartesianProvider'; import { ChartSeriesDefaultized, ChartSeriesType } from '../models/seriesType/config'; import { AxisDefaultized } from '../models/axis'; diff --git a/packages/x-charts/src/ChartsTooltip/ChartsItemTooltipContent.tsx b/packages/x-charts/src/ChartsTooltip/ChartsItemTooltipContent.tsx index 30140400a948..8d374db974f7 100644 --- a/packages/x-charts/src/ChartsTooltip/ChartsItemTooltipContent.tsx +++ b/packages/x-charts/src/ChartsTooltip/ChartsItemTooltipContent.tsx @@ -1,7 +1,7 @@ import * as React from 'react'; import { SxProps, Theme } from '@mui/material/styles'; import useSlotProps from '@mui/utils/useSlotProps'; -import { ItemInteractionData } from '../context/InteractionProvider'; +import { ItemInteractionData } from '../internals/plugins/models'; import { ChartSeriesDefaultized, ChartSeriesType } from '../models/seriesType/config'; import { ChartsTooltipClasses } from './chartsTooltipClasses'; import { DefaultChartsItemTooltipContent } from './DefaultChartsItemTooltipContent'; diff --git a/packages/x-charts/src/ChartsTooltip/ChartsTooltip.tsx b/packages/x-charts/src/ChartsTooltip/ChartsTooltip.tsx index 560a83ccc9a4..544dac733866 100644 --- a/packages/x-charts/src/ChartsTooltip/ChartsTooltip.tsx +++ b/packages/x-charts/src/ChartsTooltip/ChartsTooltip.tsx @@ -7,17 +7,19 @@ import { styled, useThemeProps, SxProps, Theme } from '@mui/material/styles'; import Popper, { PopperProps as BasePopperProps } from '@mui/material/Popper'; import NoSsr from '@mui/material/NoSsr'; import useSlotProps from '@mui/utils/useSlotProps'; -import { - AxisInteractionData, - InteractionContext, - ItemInteractionData, -} from '../context/InteractionProvider'; import { useSvgRef } from '../hooks/useSvgRef'; import { getTooltipHasData, TriggerOptions, usePointerType } from './utils'; import { ChartSeriesType } from '../models/seriesType/config'; import { ChartsItemContentProps, ChartsItemTooltipContent } from './ChartsItemTooltipContent'; import { ChartsAxisContentProps, ChartsAxisTooltipContent } from './ChartsAxisTooltipContent'; import { ChartsTooltipClasses, getChartsTooltipUtilityClass } from './chartsTooltipClasses'; +import { + selectorChartsInteractionItem, + selectorChartsInteractionAxis, +} from '../context/InteractionSelectors'; +import { ItemInteractionData, AxisInteractionData } from '../internals/plugins/models'; +import { useSelector } from '../internals/useSelector'; +import { useStore } from '../internals/useStore'; export type PopperProps = BasePopperProps & { /** @@ -137,7 +139,9 @@ function ChartsTooltip(inProps: ChartsTooltipProps const positionRef = useLazyRef(() => ({ x: 0, y: 0 })); - const { item, axis } = React.useContext(InteractionContext); + const store = useStore(); + const item = useSelector(store, selectorChartsInteractionItem); + const axis = useSelector(store, selectorChartsInteractionAxis); const displayedData = trigger === 'item' ? item : axis; diff --git a/packages/x-charts/src/ChartsTooltip/useAxisTooltip.tsx b/packages/x-charts/src/ChartsTooltip/useAxisTooltip.tsx index 109665b90e5d..aff76dca6187 100644 --- a/packages/x-charts/src/ChartsTooltip/useAxisTooltip.tsx +++ b/packages/x-charts/src/ChartsTooltip/useAxisTooltip.tsx @@ -1,6 +1,5 @@ 'use client'; import * as React from 'react'; -import { AxisInteractionData, InteractionContext } from '../context/InteractionProvider'; import { useSeries } from '../hooks/useSeries'; import { useCartesianContext } from '../context/CartesianProvider'; import { ZAxisContext } from '../context/ZAxisContextProvider'; @@ -10,6 +9,15 @@ import { CartesianChartSeriesType, ChartsSeriesConfig } from '../models/seriesTy import { getLabel } from '../internals/getLabel'; import { isCartesianSeriesType } from '../internals/isCartesian'; import { utcFormatter } from './utils'; +import { + selectorChartsInteractionAxis, + selectorChartsInteractionXAxis, + selectorChartsInteractionYAxis, +} from '../context/InteractionSelectors'; +import { useXAxis, useYAxis } from '../hooks'; +import { useSelector } from '../internals/useSelector'; +import { useStore } from '../internals/useStore'; +import { AxisInteractionData } from '../internals/plugins/models'; export interface UseAxisTooltipReturnValue< SeriesT extends CartesianChartSeriesType = CartesianChartSeriesType, @@ -30,26 +38,35 @@ interface SeriesItem { } export function useAxisTooltip(): null | UseAxisTooltipReturnValue { - const { axis } = React.useContext(InteractionContext); + const defaultXAxis = useXAxis(); + const defaultYAxis = useYAxis(); + + const xAxisHasData = defaultXAxis.data !== undefined && defaultXAxis.data.length !== 0; + + const store = useStore(); + + // This line will be removed in v8 because it degrade perfs for no reason except avoiding breaking change. + const axis = useSelector(store, selectorChartsInteractionAxis); + const axisData = useSelector( + store, + xAxisHasData ? selectorChartsInteractionXAxis : selectorChartsInteractionYAxis, + ); + const series = useSeries(); - const { xAxis, yAxis, xAxisIds, yAxisIds } = useCartesianContext(); + const { xAxis, yAxis } = useCartesianContext(); + const { zAxis, zAxisIds } = React.useContext(ZAxisContext); const colorProcessors = useColorProcessor(); - // By default use the x-axis - const isXaxis = axis.x !== null && axis.x.index !== -1; - - const axisData = isXaxis ? axis.x && axis.x : axis.y && axis.y; - if (axisData === null) { return null; } const { index: dataIndex, value: axisValue } = axisData; - const USED_AXIS_ID = isXaxis ? xAxisIds[0] : yAxisIds[0]; - const usedAxis = isXaxis ? xAxis[USED_AXIS_ID] : yAxis[USED_AXIS_ID]; + const USED_AXIS_ID = xAxisHasData ? defaultXAxis.id : defaultYAxis.id; + const usedAxis = xAxisHasData ? defaultXAxis : defaultYAxis; const relevantSeries = Object.keys(series) .filter(isCartesianSeriesType) @@ -64,20 +81,20 @@ export function useAxisTooltip(): null | UseAxisTooltipReturnValue { const providedXAxisId = seriesToAdd.xAxisId; const providedYAxisId = seriesToAdd.yAxisId; - const axisKey = isXaxis ? providedXAxisId : providedYAxisId; + const axisKey = xAxisHasData ? providedXAxisId : providedYAxisId; // Test if the series uses the default axis if (axisKey === undefined || axisKey === USED_AXIS_ID) { - const xAxisId = providedXAxisId ?? xAxisIds[0]; - const yAxisId = providedYAxisId ?? yAxisIds[0]; - const zAxisId = (seriesToAdd as any).zAxisId ?? zAxisIds[0]; + const xAxisId = providedXAxisId ?? defaultXAxis.id; + const yAxisId = providedYAxisId ?? defaultYAxis.id; + const zAxisId = 'zAxisId' in seriesToAdd ? seriesToAdd.zAxisId : zAxisIds[0]; const color = colorProcessors[seriesType]?.( seriesToAdd, xAxis[xAxisId], yAxis[yAxisId], - zAxisId && zAxis[zAxisId], + zAxisId ? zAxis[zAxisId] : undefined, )(dataIndex) ?? ''; const value = seriesToAdd.data[dataIndex] ?? null; @@ -107,7 +124,7 @@ export function useAxisTooltip(): null | UseAxisTooltipReturnValue { const axisFormattedValue = axisFormatter(axisValue, { location: 'tooltip' }); return { - identifier: axis as AxisInteractionData, + identifier: axis, seriesItems: relevantSeries, axisValue, axisFormattedValue, diff --git a/packages/x-charts/src/ChartsTooltip/useItemTooltip.tsx b/packages/x-charts/src/ChartsTooltip/useItemTooltip.tsx index a3ab97c287b1..96023ae1b272 100644 --- a/packages/x-charts/src/ChartsTooltip/useItemTooltip.tsx +++ b/packages/x-charts/src/ChartsTooltip/useItemTooltip.tsx @@ -1,6 +1,5 @@ 'use client'; import * as React from 'react'; -import { InteractionContext, ItemInteractionData } from '../context/InteractionProvider'; import { useSeries } from '../hooks/useSeries'; import { useCartesianContext } from '../context/CartesianProvider'; import { ZAxisContext } from '../context/ZAxisContextProvider'; @@ -12,6 +11,10 @@ import { } from '../models/seriesType/config'; import { getLabel } from '../internals/getLabel'; import { CommonSeriesType } from '../models/seriesType/common'; +import { selectorChartsInteractionItem } from '../context/InteractionSelectors'; +import { useSelector } from '../internals/useSelector'; +import { useStore } from '../internals/useStore'; +import { ItemInteractionData } from '../internals/plugins/models'; export interface UseItemTooltipReturnValue { identifier: ItemInteractionData; @@ -22,7 +25,8 @@ export interface UseItemTooltipReturnValue { } export function useItemTooltip(): null | UseItemTooltipReturnValue { - const { item } = React.useContext(InteractionContext); + const stroe = useStore(); + const item = useSelector(stroe, selectorChartsInteractionItem); const series = useSeries(); const { xAxis, yAxis, xAxisIds, yAxisIds } = useCartesianContext(); diff --git a/packages/x-charts/src/ChartsTooltip/utils.tsx b/packages/x-charts/src/ChartsTooltip/utils.tsx index 227c7f58e24e..6964b5ef3e45 100644 --- a/packages/x-charts/src/ChartsTooltip/utils.tsx +++ b/packages/x-charts/src/ChartsTooltip/utils.tsx @@ -1,5 +1,5 @@ import * as React from 'react'; -import { AxisInteractionData, ItemInteractionData } from '../context/InteractionProvider'; +import { AxisInteractionData, ItemInteractionData } from '../internals/plugins/models'; import { ChartSeriesType } from '../models/seriesType/config'; import { useSvgRef } from '../hooks'; From 6935f6ae18741e8aaba056a5085109657cbf59e2 Mon Sep 17 00:00:00 2001 From: alex Date: Thu, 14 Nov 2024 20:17:49 +0100 Subject: [PATCH 5/8] use selectors --- .../ChartsOnAxisClickHandler.tsx | 12 +++++++----- .../x-charts/src/LineChart/CircleMarkElement.tsx | 9 ++++++--- .../x-charts/src/LineChart/LineHighlightPlot.tsx | 10 +++++++--- packages/x-charts/src/LineChart/MarkElement.tsx | 10 +++++++--- packages/x-charts/src/ScatterChart/Scatter.tsx | 9 ++++++--- 5 files changed, 33 insertions(+), 17 deletions(-) diff --git a/packages/x-charts/src/ChartsOnAxisClickHandler/ChartsOnAxisClickHandler.tsx b/packages/x-charts/src/ChartsOnAxisClickHandler/ChartsOnAxisClickHandler.tsx index 8c26ff5650e6..a5a7d65b0ab7 100644 --- a/packages/x-charts/src/ChartsOnAxisClickHandler/ChartsOnAxisClickHandler.tsx +++ b/packages/x-charts/src/ChartsOnAxisClickHandler/ChartsOnAxisClickHandler.tsx @@ -1,7 +1,7 @@ 'use client'; import * as React from 'react'; import PropTypes from 'prop-types'; -import { InteractionContext } from '../context/InteractionProvider'; +import { useStore } from '../internals/useStore'; import { useSeries } from '../hooks/useSeries'; import { useSvgRef } from '../hooks'; import { useCartesianContext } from '../context/CartesianProvider'; @@ -27,7 +27,8 @@ function ChartsOnAxisClickHandler(props: ChartsOnAxisClickHandlerProps) { const svgRef = useSvgRef(); const series = useSeries(); - const { axis } = React.useContext(InteractionContext); + const store = useStore(); + const { xAxisIds, xAxis, yAxisIds, yAxis } = useCartesianContext(); React.useEffect(() => { @@ -39,9 +40,10 @@ function ChartsOnAxisClickHandler(props: ChartsOnAxisClickHandlerProps) { const handleMouseClick = (event: MouseEvent) => { event.preventDefault(); - const isXaxis = axis.x && axis.x.index !== -1; + const { x: axisX, y: axisY } = store.value.interaction.axis; + const isXaxis = axisX && axisX.index !== -1; const USED_AXIS_ID = isXaxis ? xAxisIds[0] : yAxisIds[0]; - const dataIndex = isXaxis ? axis.x && axis.x.index : axis.y && axis.y.index; + const dataIndex = isXaxis ? axisX && axisX.index : axisY && axisY.index; if (dataIndex == null) { return; @@ -72,7 +74,7 @@ function ChartsOnAxisClickHandler(props: ChartsOnAxisClickHandlerProps) { return () => { element.removeEventListener('click', handleMouseClick); }; - }, [axis.x, axis.y, onAxisClick, series, svgRef, xAxis, xAxisIds, yAxis, yAxisIds]); + }, [onAxisClick, series, store, svgRef, xAxis, xAxisIds, yAxis, yAxisIds]); // eslint-disable-next-line react/jsx-no-useless-fragment return ; diff --git a/packages/x-charts/src/LineChart/CircleMarkElement.tsx b/packages/x-charts/src/LineChart/CircleMarkElement.tsx index 584c15bab4d8..ddc1608cc44c 100644 --- a/packages/x-charts/src/LineChart/CircleMarkElement.tsx +++ b/packages/x-charts/src/LineChart/CircleMarkElement.tsx @@ -4,10 +4,12 @@ import PropTypes from 'prop-types'; import { useTheme } from '@mui/material/styles'; import { warnOnce } from '@mui/x-internals/warning'; import { animated, useSpring } from '@react-spring/web'; -import { InteractionContext } from '../context/InteractionProvider'; import { useInteractionItemProps } from '../hooks/useInteractionItemProps'; import { useItemHighlighted } from '../context'; import { MarkElementOwnerState, useUtilityClasses } from './markElementClasses'; +import { useSelector } from '../internals/useSelector'; +import { selectorChartsInteractionXAxis } from '../context/InteractionSelectors'; +import { useStore } from '../internals/useStore'; export type CircleMarkElementProps = Omit & Omit, 'ref' | 'id'> & { @@ -66,13 +68,14 @@ function CircleMarkElement(props: CircleMarkElementProps) { const { isFaded, isHighlighted } = useItemHighlighted({ seriesId: id, }); - const { axis } = React.useContext(InteractionContext); + const store = useStore(); + const xAxisIdentifier = useSelector(store, selectorChartsInteractionXAxis); const position = useSpring({ to: { x, y }, immediate: skipAnimation }); const ownerState = { id, classes: innerClasses, - isHighlighted: axis.x?.index === dataIndex || isHighlighted, + isHighlighted: xAxisIdentifier?.index === dataIndex || isHighlighted, isFaded, color, }; diff --git a/packages/x-charts/src/LineChart/LineHighlightPlot.tsx b/packages/x-charts/src/LineChart/LineHighlightPlot.tsx index a5911052eb10..7c6e30437bd0 100644 --- a/packages/x-charts/src/LineChart/LineHighlightPlot.tsx +++ b/packages/x-charts/src/LineChart/LineHighlightPlot.tsx @@ -5,11 +5,13 @@ import { SlotComponentPropsFromProps } from '@mui/x-internals/types'; import { useCartesianContext } from '../context/CartesianProvider'; import { LineHighlightElement, LineHighlightElementProps } from './LineHighlightElement'; import { getValueToPositionMapper } from '../hooks/useScale'; -import { InteractionContext } from '../context/InteractionProvider'; import { DEFAULT_X_AXIS_KEY } from '../constants'; import getColor from './getColor'; import { useLineSeries } from '../hooks/useSeries'; import { useDrawingArea } from '../hooks/useDrawingArea'; +import { selectorChartsInteractionXAxis } from '../context/InteractionSelectors'; +import { useSelector } from '../internals/useSelector'; +import { useStore } from '../internals/useStore'; export interface LineHighlightPlotSlots { lineHighlight?: React.JSXElementConstructor; @@ -48,9 +50,11 @@ function LineHighlightPlot(props: LineHighlightPlotProps) { const seriesData = useLineSeries(); const axisData = useCartesianContext(); const drawingArea = useDrawingArea(); - const { axis } = React.useContext(InteractionContext); + const store = useStore(); + const xAxisIdentifier = useSelector(store, selectorChartsInteractionXAxis); + + const highlightedIndex = xAxisIdentifier?.index; - const highlightedIndex = axis.x?.index; if (highlightedIndex === undefined) { return null; } diff --git a/packages/x-charts/src/LineChart/MarkElement.tsx b/packages/x-charts/src/LineChart/MarkElement.tsx index 93a77ca25e25..a3d9d6f93857 100644 --- a/packages/x-charts/src/LineChart/MarkElement.tsx +++ b/packages/x-charts/src/LineChart/MarkElement.tsx @@ -5,10 +5,12 @@ import { styled } from '@mui/material/styles'; import { symbol as d3Symbol, symbolsFill as d3SymbolsFill } from '@mui/x-charts-vendor/d3-shape'; import { animated, to, useSpring } from '@react-spring/web'; import { getSymbol } from '../internals/getSymbol'; -import { InteractionContext } from '../context/InteractionProvider'; import { useInteractionItemProps } from '../hooks/useInteractionItemProps'; import { useItemHighlighted } from '../context'; import { MarkElementOwnerState, useUtilityClasses } from './markElementClasses'; +import { selectorChartsInteractionXAxis } from '../context/InteractionSelectors'; +import { useSelector } from '../internals/useSelector'; +import { useStore } from '../internals/useStore'; const MarkElementPath = styled(animated.path, { name: 'MuiMarkElement', @@ -65,13 +67,15 @@ function MarkElement(props: MarkElementProps) { const { isFaded, isHighlighted } = useItemHighlighted({ seriesId: id, }); - const { axis } = React.useContext(InteractionContext); + + const store = useStore(); + const xAxisIdentifier = useSelector(store, selectorChartsInteractionXAxis); const position = useSpring({ to: { x, y }, immediate: skipAnimation }); const ownerState = { id, classes: innerClasses, - isHighlighted: axis.x?.index === dataIndex || isHighlighted, + isHighlighted: xAxisIdentifier?.index === dataIndex || isHighlighted, isFaded, color, }; diff --git a/packages/x-charts/src/ScatterChart/Scatter.tsx b/packages/x-charts/src/ScatterChart/Scatter.tsx index 74aea129dc00..bb842977a98b 100644 --- a/packages/x-charts/src/ScatterChart/Scatter.tsx +++ b/packages/x-charts/src/ScatterChart/Scatter.tsx @@ -8,10 +8,12 @@ import { } from '../models/seriesType/scatter'; import { getValueToPositionMapper } from '../hooks/useScale'; import { useInteractionItemProps } from '../hooks/useInteractionItemProps'; -import { InteractionContext } from '../context/InteractionProvider'; import { D3Scale } from '../models/axis'; import { useHighlighted } from '../context'; import { useDrawingArea } from '../hooks/useDrawingArea'; +import { selectorChartsInteractionUseVoronoid } from '../context/InteractionSelectors'; +import { useSelector } from '../internals/useSelector'; +import { useStore } from '../internals/useStore'; export interface ScatterProps { series: DefaultizedScatterSeriesType; @@ -46,9 +48,10 @@ function Scatter(props: ScatterProps) { const drawingArea = useDrawingArea(); - const { useVoronoiInteraction } = React.useContext(InteractionContext); + const store = useStore(); + const usesVoronoiInteraction = useSelector(store, selectorChartsInteractionUseVoronoid); - const skipInteractionHandlers = useVoronoiInteraction || series.disableHover; + const skipInteractionHandlers = usesVoronoiInteraction || series.disableHover; const getInteractionItemProps = useInteractionItemProps(skipInteractionHandlers); const { isFaded, isHighlighted } = useHighlighted(); From 430537e1495994a9960b9da0aeed84549bd6f77f Mon Sep 17 00:00:00 2001 From: alex Date: Fri, 15 Nov 2024 15:49:02 +0100 Subject: [PATCH 6/8] Reanming suggestions --- packages/x-charts/src/ScatterChart/Scatter.tsx | 6 +++--- .../x-charts/src/context/InteractionProvider.tsx | 4 ++-- .../x-charts/src/context/InteractionSelectors.ts | 8 ++++---- .../x-charts/src/internals/plugins/models/index.ts | 8 ++++---- .../utils/{ChartsStore.ts => ChartStore.ts} | 14 +++++++------- .../src/internals/plugins/utils/selectors.ts | 10 +++++----- packages/x-charts/src/internals/useCharts.ts | 12 ++++++------ packages/x-charts/src/internals/useSelector.ts | 10 +++++----- packages/x-charts/src/internals/useStore.ts | 5 +++-- 9 files changed, 39 insertions(+), 38 deletions(-) rename packages/x-charts/src/internals/plugins/utils/{ChartsStore.ts => ChartStore.ts} (55%) diff --git a/packages/x-charts/src/ScatterChart/Scatter.tsx b/packages/x-charts/src/ScatterChart/Scatter.tsx index bb842977a98b..b6a95e703587 100644 --- a/packages/x-charts/src/ScatterChart/Scatter.tsx +++ b/packages/x-charts/src/ScatterChart/Scatter.tsx @@ -11,7 +11,7 @@ import { useInteractionItemProps } from '../hooks/useInteractionItemProps'; import { D3Scale } from '../models/axis'; import { useHighlighted } from '../context'; import { useDrawingArea } from '../hooks/useDrawingArea'; -import { selectorChartsInteractionUseVoronoid } from '../context/InteractionSelectors'; +import { selectorChartsInteractionIsVoronoiEnabled } from '../context/InteractionSelectors'; import { useSelector } from '../internals/useSelector'; import { useStore } from '../internals/useStore'; @@ -49,9 +49,9 @@ function Scatter(props: ScatterProps) { const drawingArea = useDrawingArea(); const store = useStore(); - const usesVoronoiInteraction = useSelector(store, selectorChartsInteractionUseVoronoid); + const isVoronoiEnabled = useSelector(store, selectorChartsInteractionIsVoronoiEnabled); - const skipInteractionHandlers = usesVoronoiInteraction || series.disableHover; + const skipInteractionHandlers = isVoronoiEnabled || series.disableHover; const getInteractionItemProps = useInteractionItemProps(skipInteractionHandlers); const { isFaded, isHighlighted } = useHighlighted(); diff --git a/packages/x-charts/src/context/InteractionProvider.tsx b/packages/x-charts/src/context/InteractionProvider.tsx index eeccf65f402b..f31eac1c155d 100644 --- a/packages/x-charts/src/context/InteractionProvider.tsx +++ b/packages/x-charts/src/context/InteractionProvider.tsx @@ -1,9 +1,9 @@ 'use client'; import * as React from 'react'; import { useCharts } from '../internals/useCharts'; -import { ChartsStore } from '../internals/plugins/utils/ChartsStore'; +import { ChartStore } from '../internals/plugins/utils/ChartStore'; -export const ChartsContext = React.createContext<{ store: ChartsStore } | null>(null); +export const ChartsContext = React.createContext<{ store: ChartStore } | null>(null); if (process.env.NODE_ENV !== 'production') { ChartsContext.displayName = 'ChartsContext'; diff --git a/packages/x-charts/src/context/InteractionSelectors.ts b/packages/x-charts/src/context/InteractionSelectors.ts index 4613b01b649a..c911baeae216 100644 --- a/packages/x-charts/src/context/InteractionSelectors.ts +++ b/packages/x-charts/src/context/InteractionSelectors.ts @@ -1,7 +1,7 @@ -import { ChartsState } from '../internals/plugins/models'; +import { ChartState } from '../internals/plugins/models'; import { createSelector } from '../internals/plugins/utils/selectors'; -function selectInteraction(state: ChartsState) { +function selectInteraction(state: ChartState) { return state.interaction; } @@ -40,7 +40,7 @@ export const selectorChartsInteractionYAxisIsDefined = createSelector( (y) => y !== null, ); -export const selectorChartsInteractionUseVoronoid = createSelector( +export const selectorChartsInteractionIsVoronoiEnabled = createSelector( selectInteraction, - (interaction) => interaction.useVoronoiInteraction, + (interaction) => interaction.isVoronoiEnabled, ); diff --git a/packages/x-charts/src/internals/plugins/models/index.ts b/packages/x-charts/src/internals/plugins/models/index.ts index c81b1036a7ea..ba5ae5bd5f5f 100644 --- a/packages/x-charts/src/internals/plugins/models/index.ts +++ b/packages/x-charts/src/internals/plugins/models/index.ts @@ -28,12 +28,12 @@ type InteractionState = { * Set to `true` when `VoronoiHandler` is active. * Used to prevent collision with mouseEnter events. */ - useVoronoiInteraction?: boolean; + isVoronoiEnabled?: boolean; }; -export type ChartsStateCacheKey = { id: number }; +export type ChartStateCacheKey = { id: number }; -export type ChartsState = { +export type ChartState = { interaction: InteractionState; - cacheKey: ChartsStateCacheKey; + cacheKey: ChartStateCacheKey; }; diff --git a/packages/x-charts/src/internals/plugins/utils/ChartsStore.ts b/packages/x-charts/src/internals/plugins/utils/ChartStore.ts similarity index 55% rename from packages/x-charts/src/internals/plugins/utils/ChartsStore.ts rename to packages/x-charts/src/internals/plugins/utils/ChartStore.ts index 8a09576097a7..f4cdbc2324d9 100644 --- a/packages/x-charts/src/internals/plugins/utils/ChartsStore.ts +++ b/packages/x-charts/src/internals/plugins/utils/ChartStore.ts @@ -1,20 +1,20 @@ -import type { ChartsState } from '../models'; // For now this is fixed. Will need to support generic if we add plugins +import type { ChartState } from '../models'; // For now this is fixed. Will need to support generic if we add plugins type Listener = (value: T) => void; -export type StoreUpdater = (prevState: ChartsState) => ChartsState; +export type StoreUpdater = (prevState: ChartState) => ChartState; -export class ChartsStore { - public value: ChartsState; +export class ChartStore { + public value: ChartState; - private listeners: Set>; + private listeners: Set>; - constructor(value: ChartsState) { + constructor(value: ChartState) { this.value = value; this.listeners = new Set(); } - public subscribe = (fn: Listener) => { + public subscribe = (fn: Listener) => { this.listeners.add(fn); return () => { this.listeners.delete(fn); diff --git a/packages/x-charts/src/internals/plugins/utils/selectors.ts b/packages/x-charts/src/internals/plugins/utils/selectors.ts index bc75b498e576..a91ac4a1a0fa 100644 --- a/packages/x-charts/src/internals/plugins/utils/selectors.ts +++ b/packages/x-charts/src/internals/plugins/utils/selectors.ts @@ -1,5 +1,5 @@ import { lruMemoize, createSelectorCreator, CreateSelectorFunction } from 'reselect'; -import { ChartsState, ChartsStateCacheKey } from '../models'; +import { ChartState, ChartStateCacheKey } from '../models'; const reselectCreateSelector = createSelectorCreator({ memoize: lruMemoize, @@ -10,20 +10,20 @@ const reselectCreateSelector = createSelectorCreator({ }); const cache = new WeakMap< - ChartsStateCacheKey, + ChartStateCacheKey, Map, any> >(); -export type ChartsRootSelector = (state: ChartsState) => ChartsState[keyof ChartsState]; +export type ChartsRootSelector = (state: ChartState) => ChartState[keyof ChartState]; export type ChartsSelector = (state: TState, args: TArgs) => TResult; /** - * Method wrapping reselect's createSelector to provide caching for tree view instances. + * Method wrapping reselect's createSelector to provide caching for chart instances. * */ export const createSelector = ((...createSelectorArgs: any) => { - const selector: ChartsSelector = (state, selectorArgs) => { + const selector: ChartsSelector = (state, selectorArgs) => { const cacheKey = state.cacheKey; // If there is no cache for the current chart instance, create one. diff --git a/packages/x-charts/src/internals/useCharts.ts b/packages/x-charts/src/internals/useCharts.ts index 89a2d9e77532..dddafa853ba8 100644 --- a/packages/x-charts/src/internals/useCharts.ts +++ b/packages/x-charts/src/internals/useCharts.ts @@ -1,25 +1,25 @@ import * as React from 'react'; -import { ChartsStore } from './plugins/utils/ChartsStore'; -import { ChartsState } from './plugins/models'; +import { ChartStore } from './plugins/utils/ChartStore'; +import { ChartState } from './plugins/models'; let globalId = 0; export function useCharts() { - const storeRef = React.useRef(null); + const storeRef = React.useRef(null); if (storeRef.current == null) { // eslint-disable-next-line react-compiler/react-compiler globalId += 1; - const initialState: ChartsState = { + const initialState: ChartState = { interaction: { item: null, axis: { x: null, y: null }, }, cacheKey: { id: globalId }, }; - storeRef.current = new ChartsStore(initialState); + storeRef.current = new ChartStore(initialState); } - const contextValue = React.useMemo(() => ({ store: storeRef.current as ChartsStore }), []); + const contextValue = React.useMemo(() => ({ store: storeRef.current as ChartStore }), []); return { contextValue }; } diff --git a/packages/x-charts/src/internals/useSelector.ts b/packages/x-charts/src/internals/useSelector.ts index 41f93351c078..b4940ae5c8d3 100644 --- a/packages/x-charts/src/internals/useSelector.ts +++ b/packages/x-charts/src/internals/useSelector.ts @@ -1,17 +1,17 @@ import { useSyncExternalStoreWithSelector } from 'use-sync-external-store/with-selector'; -import { ChartsState } from './plugins/models'; +import { ChartState } from './plugins/models'; import { ChartsSelector } from './plugins/utils/selectors'; -import { ChartsStore } from './plugins/utils/ChartsStore'; +import { ChartStore } from './plugins/utils/ChartStore'; const defaultCompare = Object.is; export const useSelector = ( - store: ChartsStore, - selector: ChartsSelector, + store: ChartStore, + selector: ChartsSelector, args: TArgs = undefined as TArgs, equals: (a: TValue, b: TValue) => boolean = defaultCompare, ): TValue => { - const selectorWithArgs = (state: ChartsState) => selector(state, args); + const selectorWithArgs = (state: ChartState) => selector(state, args); return useSyncExternalStoreWithSelector( store.subscribe, diff --git a/packages/x-charts/src/internals/useStore.ts b/packages/x-charts/src/internals/useStore.ts index f218a6226951..f906789004aa 100644 --- a/packages/x-charts/src/internals/useStore.ts +++ b/packages/x-charts/src/internals/useStore.ts @@ -1,11 +1,12 @@ import * as React from 'react'; import { ChartsContext } from '../context/InteractionProvider'; -import { ChartsStore } from './plugins/utils/ChartsStore'; +import { ChartStore } from './plugins/utils/ChartStore'; -export function useStore(skipError?: boolean): ChartsStore { +export function useStore(skipError?: boolean): ChartStore { const charts = React.useContext(ChartsContext); if (skipError) { + // TODO: Remove once store is used by all charts. // This line is only for `useAxisEvents` which is in the surface of the Gauge. // But the Gauge don't have store yet because it does not need the interaction provider. // Will be fixed when every thing move to the store since every component will have access to it. From f7ce914510967eae13416d02be4bce6cb6d9aef9 Mon Sep 17 00:00:00 2001 From: Alexandre Fauquette <45398769+alexfauquette@users.noreply.github.com> Date: Mon, 18 Nov 2024 12:11:52 +0100 Subject: [PATCH 7/8] Update packages/x-charts/src/internals/useStore.ts Co-authored-by: Jose C Quintas Jr Signed-off-by: Alexandre Fauquette <45398769+alexfauquette@users.noreply.github.com> --- packages/x-charts/src/internals/useStore.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/packages/x-charts/src/internals/useStore.ts b/packages/x-charts/src/internals/useStore.ts index f906789004aa..17e6d3b6316f 100644 --- a/packages/x-charts/src/internals/useStore.ts +++ b/packages/x-charts/src/internals/useStore.ts @@ -6,6 +6,7 @@ export function useStore(skipError?: boolean): ChartStore { const charts = React.useContext(ChartsContext); if (skipError) { + // TODO: Remove once store is used by all charts. // TODO: Remove once store is used by all charts. // This line is only for `useAxisEvents` which is in the surface of the Gauge. // But the Gauge don't have store yet because it does not need the interaction provider. From e04c1eaabf3c6640e52aca871ea03a1658ec2a91 Mon Sep 17 00:00:00 2001 From: alex Date: Mon, 18 Nov 2024 15:12:43 +0100 Subject: [PATCH 8/8] fix --- packages/x-charts/src/ChartsSurface/ChartsSurface.test.tsx | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/packages/x-charts/src/ChartsSurface/ChartsSurface.test.tsx b/packages/x-charts/src/ChartsSurface/ChartsSurface.test.tsx index d052d17b1367..03292560de8d 100644 --- a/packages/x-charts/src/ChartsSurface/ChartsSurface.test.tsx +++ b/packages/x-charts/src/ChartsSurface/ChartsSurface.test.tsx @@ -17,7 +17,12 @@ describe('', () => { render( - + ,