Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: DashboardTimeRangeSlider #1725

Merged
merged 4 commits into from
Sep 6, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@ You can also check the
- Renaming of charts through user profile now works correctly
- Manually entering dates in date pickers works correctly again
- Improved scrolling behavior in the chart tabs
- Shared time range filter now correctly positions the marks in the time
slider
- Style
- Aligned editor and layouting page layouts
- Removed dimension selection from modal when merging cubes
Expand Down
88 changes: 88 additions & 0 deletions app/charts/shared/use-combined-temporal-dimension.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
import { t } from "@lingui/macro";
import { ascending, descending } from "d3-array";
import uniqBy from "lodash/uniqBy";
import { useMemo } from "react";

import {
hasChartConfigs,
useConfiguratorState,
} from "@/configurator/configurator-state";
import {
isTemporalDimensionWithTimeUnit,
TemporalDimension,
TemporalEntityDimension,
} from "@/domain/data";
import { useTimeFormatLocale } from "@/formatters";
import { useConfigsCubeComponents } from "@/graphql/hooks";
import { TimeUnit } from "@/graphql/query-hooks";
import { useLocale } from "@/locales/use-locale";
import { timeUnitFormats, timeUnitOrder } from "@/rdf/mappings";
import { useDashboardInteractiveFilters } from "@/stores/interactive-filters";

/** Hook to get combined temporal dimension. Useful for shared dashboard filters. */
export const useCombinedTemporalDimension = () => {
const locale = useLocale();
const formatLocale = useTimeFormatLocale();
const [state] = useConfiguratorState(hasChartConfigs);
const { potentialTimeRangeFilterIris } = useDashboardInteractiveFilters();
const [{ data }] = useConfigsCubeComponents({
variables: {
state,
locale,
},
});
return useMemo(() => {
const timeUnitDimensions = (
data?.dataCubesComponents.dimensions ?? []
).filter(
(dimension) =>
isTemporalDimensionWithTimeUnit(dimension) &&
potentialTimeRangeFilterIris.includes(dimension.iri)
) as (TemporalDimension | TemporalEntityDimension)[];
// We want to use lowest time unit for combined dimension filtering,
// so in case we have year and day, we'd filter both by day
const timeUnit = timeUnitDimensions.sort((a, b) =>
descending(
timeUnitOrder.get(a.timeUnit) ?? 0,
timeUnitOrder.get(b.timeUnit) ?? 0
)
)[0]?.timeUnit as TimeUnit;
const timeFormat = timeUnitFormats.get(timeUnit) as string;
const values = timeUnitDimensions.flatMap((dimension) => {
const formatDate = formatLocale.format(timeFormat);
const parseDate = formatLocale.parse(dimension.timeFormat);
// Standardize values to have same date format
return dimension.values.map((dimensionValue) => {
const date = parseDate(`${dimensionValue.value}`) as Date;
const dateString = formatDate(date);
return {
...dimensionValue,
value: dateString,
label: dateString,
};
});
});
const combinedDimension: TemporalDimension = {
__typename: "TemporalDimension",
cubeIri: "all",
iri: "combined-date-filter",
label: t({
id: "controls.section.shared-filters.date",
message: "Date",
}),
isKeyDimension: true,
isNumerical: false,
values: uniqBy(values, "value").sort((a, b) =>
ascending(a.value, b.value)
),
timeUnit,
timeFormat,
};

return combinedDimension;
}, [
data?.dataCubesComponents.dimensions,
formatLocale,
potentialTimeRangeFilterIris,
]);
};
67 changes: 24 additions & 43 deletions app/components/dashboard-interactive-filters.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import {
DataFilterHierarchyDimension,
DataFilterTemporalDimension,
} from "@/charts/shared/chart-data-filters";
import { useCombinedTemporalDimension } from "@/charts/shared/use-combined-temporal-dimension";
import {
ChartConfig,
DashboardTimeRangeFilter,
Expand All @@ -25,6 +26,7 @@ import {
useConfiguratorState,
} from "@/configurator";
import {
parseDate,
timeUnitToFormatter,
timeUnitToParser,
} from "@/configurator/components/ui-helpers";
Expand Down Expand Up @@ -140,26 +142,11 @@ const DashboardTimeRangeSlider = ({
);

const timeUnit = filter.timeUnit as TimeUnit;

// In Unix timestamp
const [timeRange, setTimeRange] = useState(() =>
// timeUnit can still be an empty string
timeUnit ? presetToTimeRange(presets, timeUnit) : undefined
);

const { min, max } = useMemo(() => {
if (!timeUnit) {
return { min: 0, max: 0 };
}
const parser = timeUnitToParser[timeUnit];
return {
min: toUnixSeconds(parser(presets.from)),
max: toUnixSeconds(parser(presets.to)),
};
}, [timeUnit, presets]);

const step = stepFromTimeUnit(timeUnit);

const valueLabelFormat = useEventCallback((value: number) => {
if (!timeUnit) {
return "";
Expand Down Expand Up @@ -211,8 +198,23 @@ const DashboardTimeRangeSlider = ({
}, [presets.from, presets.to, timeUnit]);

const mountedForSomeTime = useTimeout(500, mounted);
const combinedTemporalDimension = useCombinedTemporalDimension();
const sliderRange = useMemo(() => {
const { values } = combinedTemporalDimension;
const min = values[0]?.value;
const max = values[values.length - 1]?.value;

if (!timeRange || !filter.active) {
if (!min || !max) {
return;
}

return [
toUnixSeconds(parseDate(min as string)),
toUnixSeconds(parseDate(max as string)),
];
}, [combinedTemporalDimension]);

if (!timeRange || !filter.active || !sliderRange) {
return null;
}

Expand All @@ -221,40 +223,19 @@ const DashboardTimeRangeSlider = ({
className={classes.slider}
onChange={(_ev, value) => handleChangeSlider(value)}
onChangeCommitted={() => setEnableTransition(true)}
min={min}
max={max}
valueLabelFormat={valueLabelFormat}
step={step}
step={null}
min={sliderRange[0]}
max={sliderRange[1]}
valueLabelDisplay={mountedForSomeTime ? "on" : "off"}
value={timeRange}
marks={(max - min) / (step ?? 1) < 50}
marks={combinedTemporalDimension.values.map(({ value }) => ({
value: toUnixSeconds(parseDate(value as string)),
}))}
/>
);
};

function stepFromTimeUnit(timeUnit: TimeUnit | undefined) {
if (!timeUnit) {
return 0;
}

switch (timeUnit) {
case "Year":
return 1 * 60 * 60 * 24 * 365;
case "Month":
return 1 * 60 * 60 * 24 * 30;
case "Week":
return 1 * 60 * 60 * 24 * 7;
case "Day":
return 1 * 60 * 60 * 24;
case "Hour":
return 1 * 60 * 60;
case "Minute":
return 1 * 60;
case "Second":
return 1;
}
}

const useDataFilterStyles = makeStyles((theme: Theme) => ({
wrapper: {
display: "grid",
Expand Down
71 changes: 10 additions & 61 deletions app/configurator/components/layout-configurator.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,12 @@ import {
Typography,
useEventCallback,
} from "@mui/material";
import { ascending, descending } from "d3-array";
import capitalize from "lodash/capitalize";
import omit from "lodash/omit";
import uniqBy from "lodash/uniqBy";
import { useCallback, useEffect, useMemo, useRef } from "react";

import { DataFilterGenericDimensionProps } from "@/charts/shared/chart-data-filters";
import { useCombinedTemporalDimension } from "@/charts/shared/use-combined-temporal-dimension";
import { Select } from "@/components/form";
import { generateLayout } from "@/components/react-grid";
import {
Expand Down Expand Up @@ -46,15 +45,12 @@ import {
import {
canDimensionBeTimeFiltered,
Dimension,
isTemporalDimensionWithTimeUnit,
TemporalDimension,
TemporalEntityDimension,
} from "@/domain/data";
import { useFlag } from "@/flags";
import { useTimeFormatLocale, useTimeFormatUnit } from "@/formatters";
import { useConfigsCubeComponents } from "@/graphql/hooks";
import { TimeUnit } from "@/graphql/resolver-types";
import { timeUnitFormats, timeUnitOrder } from "@/rdf/mappings";
import { useLocale } from "@/src";
import { useDashboardInteractiveFilters } from "@/stores/interactive-filters";
import { getTimeFilterOptions } from "@/utils/time-filter-options";
Expand Down Expand Up @@ -122,7 +118,7 @@ const LayoutSharedFiltersConfigurator = () => {
const [{ data, fetching }] = useConfigsCubeComponents({
variables: {
state,
locale: locale,
locale,
},
});
const dimensions = useMemo(
Expand All @@ -133,68 +129,21 @@ const LayoutSharedFiltersConfigurator = () => {
const formatLocale = useTimeFormatLocale();
const timeFormatUnit = useTimeFormatUnit();

const combinedDimension = useMemo(() => {
const timeUnitDimensions = dimensions.filter(
(dimension) =>
isTemporalDimensionWithTimeUnit(dimension) &&
potentialTimeRangeFilterIris.includes(dimension.iri)
) as (TemporalDimension | TemporalEntityDimension)[];
// We want to use lowest time unit for combined dimension filtering,
// so in case we have year and day, we'd filter both by day
const timeUnit = timeUnitDimensions.sort((a, b) =>
descending(
timeUnitOrder.get(a.timeUnit) ?? 0,
timeUnitOrder.get(b.timeUnit) ?? 0
)
)[0]?.timeUnit as TimeUnit;
const timeFormat = timeUnitFormats.get(timeUnit) as string;
const values = timeUnitDimensions.flatMap((dimension) => {
const formatDate = formatLocale.format(timeFormat);
const parseDate = formatLocale.parse(dimension.timeFormat);
// Standardize values to have same date format
return dimension.values.map((dimensionValue) => {
const value = formatDate(
parseDate(dimensionValue.value as string) as Date
);
return {
...dimensionValue,
value,
label: value,
};
});
});
const combinedDimension: TemporalDimension = {
__typename: "TemporalDimension",
cubeIri: "all",
iri: "combined-date-filter",
label: t({
id: "controls.section.shared-filters.date",
message: "Date",
}),
isKeyDimension: true,
isNumerical: false,
values: uniqBy(values, "value").sort((a, b) =>
ascending(a.value, b.value)
),
timeUnit,
timeFormat,
};

return combinedDimension;
}, [dimensions, formatLocale, potentialTimeRangeFilterIris]);
const combinedTemporalDimension = useCombinedTemporalDimension();

const handleTimeRangeFilterToggle: SwitchProps["onChange"] = useEventCallback(
(_, checked) => {
if (checked) {
const options = getTimeFilterOptions({
dimension: combinedDimension,
dimension: combinedTemporalDimension,
formatLocale,
timeFormatUnit,
});

const from = options.sortedOptions[0]?.date;
const to = options.sortedOptions.at(-1)?.date;
const formatDate = timeUnitToFormatter[combinedDimension.timeUnit];
const formatDate =
timeUnitToFormatter[combinedTemporalDimension.timeUnit];

if (!from || !to) {
return;
Expand All @@ -204,7 +153,7 @@ const LayoutSharedFiltersConfigurator = () => {
type: "DASHBOARD_TIME_RANGE_FILTER_UPDATE",
value: {
active: true,
timeUnit: combinedDimension.timeUnit,
timeUnit: combinedTemporalDimension.timeUnit,
presets: {
from: formatDate(from),
to: formatDate(to),
Expand Down Expand Up @@ -295,7 +244,7 @@ const LayoutSharedFiltersConfigurator = () => {
<ControlSectionContent>
<Stack gap="0.5rem">
{/* TODO: allow TemporalOrdinalDimensions to work here */}
{timeRange && combinedDimension.values.length ? (
{timeRange && combinedTemporalDimension.values.length ? (
<>
<Box
sx={{
Expand All @@ -306,7 +255,7 @@ const LayoutSharedFiltersConfigurator = () => {
}}
>
<Typography variant="body2">
{combinedDimension.label}
{combinedTemporalDimension.label}
</Typography>
<Switch
checked={timeRange.active}
Expand All @@ -316,7 +265,7 @@ const LayoutSharedFiltersConfigurator = () => {
{timeRange.active ? (
<DashboardFiltersOptions
timeRangeFilter={timeRange}
timeRangeCombinedDimension={combinedDimension}
timeRangeCombinedDimension={combinedTemporalDimension}
/>
) : null}
</>
Expand Down
Loading