|
| 1 | +// import { fastArrayCompare } from '@mui/x-internals/fastArrayCompare'; |
| 2 | +import { warnOnce } from '@mui/x-internals/warning'; |
| 3 | +import { ChartSeriesDefaultized, ChartsSeriesConfig } from '../models/seriesType/config'; |
| 4 | +import { SeriesId } from '../models/seriesType/common'; |
| 5 | +import { createSelector } from './plugins/utils/selectors'; |
| 6 | +import { selectorChartSeriesProcessed } from './plugins/corePlugins/useChartSeries/useChartSeries.selectors'; |
| 7 | +import { useStore } from './store/useStore'; |
| 8 | +import { useSelector } from './store/useSelector'; |
| 9 | + |
| 10 | +export function createSeriesSelectorsOfType<T extends keyof ChartsSeriesConfig>(seriesType: T) { |
| 11 | + const selectorSeriesWithIds = createSelector( |
| 12 | + [selectorChartSeriesProcessed], |
| 13 | + (processedSeries, ids?: SeriesId | SeriesId[]) => { |
| 14 | + if (!ids || (Array.isArray(ids) && ids.length === 0)) { |
| 15 | + return ( |
| 16 | + processedSeries[seriesType]?.seriesOrder?.map( |
| 17 | + (seriesId) => processedSeries[seriesType]?.series[seriesId], |
| 18 | + ) ?? [] |
| 19 | + ); |
| 20 | + } |
| 21 | + |
| 22 | + if (!Array.isArray(ids)) { |
| 23 | + return processedSeries[seriesType]?.series?.[ids]; |
| 24 | + } |
| 25 | + |
| 26 | + const result: ChartSeriesDefaultized<T>[] = []; |
| 27 | + const failedIds: SeriesId[] = []; |
| 28 | + for (const id of ids) { |
| 29 | + const series = processedSeries[seriesType]?.series?.[id]; |
| 30 | + if (series) { |
| 31 | + result.push(series); |
| 32 | + } else { |
| 33 | + failedIds.push(id); |
| 34 | + } |
| 35 | + } |
| 36 | + if (process.env.NODE_ENV !== 'production' && failedIds.length > 0) { |
| 37 | + const formattedIds = failedIds.map((v) => JSON.stringify(v)).join(', '); |
| 38 | + const fnName = `use${seriesType.charAt(0).toUpperCase()}${seriesType.slice(1)}Series`; |
| 39 | + warnOnce([ |
| 40 | + `MUI X Charts: The following ids provided to "${fnName}" could not be found: ${formattedIds}.`, |
| 41 | + `Make sure that they exist and their series are using the "${seriesType}" series type.`, |
| 42 | + ]); |
| 43 | + } |
| 44 | + return result; |
| 45 | + }, |
| 46 | + ); |
| 47 | + |
| 48 | + return (ids?: SeriesId | SeriesId[]) => { |
| 49 | + const store = useStore(); |
| 50 | + |
| 51 | + return useSelector( |
| 52 | + store, |
| 53 | + selectorSeriesWithIds, |
| 54 | + ids, |
| 55 | + // fastArrayCompare |
| 56 | + ); |
| 57 | + }; |
| 58 | +} |
| 59 | + |
| 60 | +export function createAllSeriesSelectorOfType<T extends keyof ChartsSeriesConfig>(seriesType: T) { |
| 61 | + const selectorSeries = createSelector( |
| 62 | + [selectorChartSeriesProcessed], |
| 63 | + (processedSeries) => processedSeries[seriesType], |
| 64 | + ); |
| 65 | + |
| 66 | + return () => { |
| 67 | + const store = useStore(); |
| 68 | + |
| 69 | + return useSelector(store, selectorSeries); |
| 70 | + }; |
| 71 | +} |
0 commit comments