diff --git a/CHANGELOG.md b/CHANGELOG.md index e2d1525f6..878121ea8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -21,6 +21,10 @@ You can also check the to main content" link - The metadata panel is an accessible "Details" dialog that works with the keyboard + - Interactive filters open and select by keyboard, keep focus while the chart + reloads, and announce search results + - Editor filters, legend filters and drag handles keep focus, and filter + switches and drag handles have specific names ## 6.5.7 - 2026-11-10 diff --git a/app/charts/shared/chart-data-filters/filter.tsx b/app/charts/shared/chart-data-filters/filter.tsx index c8a5d92a6..08555d8c1 100644 --- a/app/charts/shared/chart-data-filters/filter.tsx +++ b/app/charts/shared/chart-data-filters/filter.tsx @@ -36,14 +36,14 @@ export const ChartDataFilter = ({ chartConfig, dataFilters, filters, - disabled, + loading, }: { dimensionId: string; dataSource: DataSource; chartConfig: ChartConfig; dataFilters: DataFilters; filters: GroupedPreparedFilterEntry[]; - disabled: boolean; + loading: boolean; }) => { const locale = useLocale(); const chartLoadingState = useLoadingState(); @@ -246,7 +246,7 @@ export const ChartDataFilter = ({ value={value as string} dimension={dimension} onChange={setDataFilter} - disabled={disabled} + readOnly={loading} /> ) : hierarchy ? ( ) : ( )} diff --git a/app/charts/shared/chart-data-filters/filters-list.tsx b/app/charts/shared/chart-data-filters/filters-list.tsx index b77f845f9..ffd23042b 100644 --- a/app/charts/shared/chart-data-filters/filters-list.tsx +++ b/app/charts/shared/chart-data-filters/filters-list.tsx @@ -6,6 +6,7 @@ import { useChartInteractiveFilters } from "@/stores/interactive-filters"; export const ChartDataFiltersList = ({ open, + listId, dataSource, chartConfig, loading, @@ -16,6 +17,7 @@ export const ChartDataFiltersList = ({ return componentIds && componentIds.length > 0 ? ( ))} diff --git a/app/charts/shared/chart-data-filters/index.tsx b/app/charts/shared/chart-data-filters/index.tsx index 770ee3e6e..d81979551 100644 --- a/app/charts/shared/chart-data-filters/index.tsx +++ b/app/charts/shared/chart-data-filters/index.tsx @@ -180,6 +180,7 @@ export const useChartDataFiltersState = ({ return { open, setOpen, + listId: `chart-data-filters-${chartConfig.key}`, defaultOpen, dataSource, chartConfig, @@ -194,6 +195,7 @@ export const useChartDataFiltersState = ({ export const ChartDataFiltersToggle = ({ open, setOpen, + listId, defaultOpen, loading, error, @@ -239,6 +241,8 @@ export const ChartDataFiltersToggle = ({ px: 2, py: 1, }} + aria-expanded={open} + aria-controls={listId} onClick={() => setOpen((prev) => !prev)} > {loading && ( @@ -297,7 +301,8 @@ export type DataFilterGenericDimensionProps = { onChange: (e: SelectChangeEvent) => void; onMultiChange?: (values: string[]) => void; options?: Array<{ label: string; value: string }>; - disabled: boolean; + disabled?: boolean; + readOnly?: boolean; }; export const DataFilterGenericDimension = ({ @@ -310,6 +315,7 @@ export const DataFilterGenericDimension = ({ onMultiChange, options: _options, disabled, + readOnly, }: DataFilterGenericDimensionProps) => { const id = `data-filter-${useId()}`; const { label, isKeyDimension } = dimension; @@ -380,6 +386,7 @@ export const DataFilterGenericDimension = ({ onChange={onMultiChange} size="sm" disabled={disabled} + readOnly={readOnly} placeholder={noneLabel} /> ); @@ -394,6 +401,7 @@ export const DataFilterGenericDimension = ({ value={value} onChange={onChange} disabled={disabled} + readOnly={readOnly} /> ); }; @@ -408,6 +416,7 @@ export const DataFilterHierarchyDimension = ({ onMultiChange, hierarchy, disabled, + readOnly, }: { configFilter?: Filters[string]; dimension: Dimension; @@ -417,7 +426,8 @@ export const DataFilterHierarchyDimension = ({ onChange: (e: { target: { value: string } }) => void; onMultiChange?: (values: string[]) => void; hierarchy?: HierarchyValue[]; - disabled: boolean; + disabled?: boolean; + readOnly?: boolean; }) => { const { label, isKeyDimension, values: dimensionValues } = dimension; const noneLabel = t({ @@ -483,6 +493,7 @@ export const DataFilterHierarchyDimension = ({ options={options} onChange={handleChange} isMulti={isMulti} + readOnly={readOnly} label={ | ChangeEvent ) => void; - disabled: boolean; + disabled?: boolean; + readOnly?: boolean; }) => { const { label, timeUnit, timeFormat } = dimension; const formatLocale = useTimeFormatLocale(); @@ -544,6 +557,7 @@ export const DataFilterTemporalDimension = ({ minDate={minDate} maxDate={maxDate} disabled={disabled} + readOnly={readOnly} parseDate={parseDate} showClearButton={configFilter?.type !== "single"} /> @@ -555,6 +569,7 @@ export const DataFilterTemporalDimension = ({ value={value} onChange={onChange} disabled={disabled} + readOnly={readOnly} /> ); }; diff --git a/app/charts/shared/legend-color-content.spec.tsx b/app/charts/shared/legend-color-content.spec.tsx new file mode 100644 index 000000000..8e9aaf726 --- /dev/null +++ b/app/charts/shared/legend-color-content.spec.tsx @@ -0,0 +1,54 @@ +import { ThemeProvider } from "@mui/material"; +import { cleanup, render, screen } from "@testing-library/react"; +import { ReactNode } from "react"; +import { afterEach, describe, expect, it, vi } from "vitest"; + +import { LegendColorContent } from "@/charts/shared/legend-color"; +import { theme } from "@/themes/theme"; + +vi.mock("@lingui/macro", () => ({ + Trans: ({ children }: { children: ReactNode }) => children, + t: ({ message }: { message: string }) => message, + defineMessage: ({ message }: { message: string }) => message, +})); + +vi.mock("@/stores/interactive-filters", () => ({ + useChartInteractiveFilters: ( + selector: (state: Record) => unknown + ) => + selector({ categories: {}, addCategory: vi.fn(), removeCategory: vi.fn() }), +})); + +vi.mock("@/formatters", () => ({ + useFormatNumber: () => (value: number) => `${value}`, +})); + +describe("LegendColorContent", () => { + afterEach(cleanup); + + it("keeps the focused filter checkbox when the values are reordered", () => { + const { rerender } = render(); + const checkbox = screen.getByRole("checkbox", { name: "b" }); + checkbox.focus(); + + rerender(); + + expect(screen.getByRole("checkbox", { name: "b" })).toBe(checkbox); + expect(document.activeElement).toBe(checkbox); + }); +}); + +const Legend = ({ values }: { values: string[] }) => { + return ( + + "#000000"} + getLabel={(value) => value} + symbol="square" + interactive + numberOfOptions={values.length} + /> + + ); +}; diff --git a/app/charts/shared/legend-color.tsx b/app/charts/shared/legend-color.tsx index e581276d0..4707ea4d3 100644 --- a/app/charts/shared/legend-color.tsx +++ b/app/charts/shared/legend-color.tsx @@ -275,7 +275,7 @@ export const MapLegendColor = memo(function LegendColor({ ); }); -const LegendColorContent = ({ +export const LegendColorContent = ({ groups, limits, getColor, @@ -357,14 +357,13 @@ const LegendColorContent = ({ )} ) : null} - {colorValues.map((value, i) => { - const key = `${value}-${i}`; + {colorValues.map((value) => { const label = getLabel(value); const active = !activeInteractiveFilters.has(label); return ( ["size"]; label: ComponentProps["label"]; + "aria-label"?: string; disabled?: boolean; } & FieldProps) => { const genId = `switch-${useId(id)}`; @@ -892,6 +897,7 @@ export const Switch = ({ checked={checked} disabled={disabled} onChange={onChange} + inputProps={ariaLabel ? { "aria-label": ariaLabel } : undefined} /> } /> diff --git a/app/components/move-drag-button.tsx b/app/components/move-drag-button.tsx index d618e42ef..7c879d0d5 100644 --- a/app/components/move-drag-button.tsx +++ b/app/components/move-drag-button.tsx @@ -1,12 +1,30 @@ import { t } from "@lingui/macro"; +import { DraggableProvidedDragHandleProps } from "react-beautiful-dnd"; import { Icon } from "@/icons"; -export const MoveDragButton = () => { +export const MoveDragButton = ({ + label, + dragHandleProps, +}: { + label: string; + dragHandleProps?: DraggableProvidedDragHandleProps | null; +}) => { + const name = t({ + id: "controls.drag-handle.reorder", + message: `Reorder: ${label}`, + }); + return ( diff --git a/app/components/multi-select/index.tsx b/app/components/multi-select/index.tsx index 43b4afb7c..45d7d3341 100644 --- a/app/components/multi-select/index.tsx +++ b/app/components/multi-select/index.tsx @@ -1,3 +1,4 @@ +import { t } from "@lingui/macro"; import { Autocomplete, Box, @@ -33,6 +34,7 @@ export const MultiSelect = ({ value, onChange, disabled, + readOnly, loading, hint, placeholder, @@ -49,6 +51,7 @@ export const MultiSelect = ({ onChange: (values: string[]) => void; label?: ReactNode; disabled?: boolean; + readOnly?: boolean; loading?: boolean; hint?: string; placeholder?: string; @@ -76,6 +79,14 @@ export const MultiSelect = ({ setAnchorX(rect.left + rect.width / 2); setAnchorY(rect.bottom); }); + const handleOpen = useEvent(() => { + if (readOnly) { + return; + } + + setDimensions(); + setOpen(true); + }); const normalizedOptions = useMemo(() => { if (optionGroups && optionGroups.length > 0) { @@ -131,7 +142,8 @@ export const MultiSelect = ({ setOpen(false)} options={normalizedOptions} value={valueOptions} onChange={(_, newValue) => { @@ -142,6 +154,17 @@ export const MultiSelect = ({ } }} disabled={disabled} + readOnly={readOnly} + openText={t({ id: "controls.select.open", message: "Open" })} + closeText={t({ id: "controls.select.close", message: "Close" })} + noOptionsText={t({ + id: "controls.select.no-options", + message: "No options", + })} + loadingText={t({ + id: "controls.select.loading", + message: "Loading…", + })} multiple disableCloseOnSelect disableClearable @@ -182,7 +205,19 @@ export const MultiSelect = ({ placeholder={placeholder} variant={variant} size={size} - onClick={() => setOpen(!open)} + readOnly={readOnly} + onClick={(e) => { + // Autocomplete already toggles on mousedown in the input. + if (e.target instanceof HTMLInputElement) { + return; + } + + if (open) { + setOpen(false); + } else { + handleOpen(); + } + }} /> ); }} diff --git a/app/components/multi-select/input.tsx b/app/components/multi-select/input.tsx index 18f0eea36..327675b33 100644 --- a/app/components/multi-select/input.tsx +++ b/app/components/multi-select/input.tsx @@ -1,6 +1,6 @@ import { t } from "@lingui/macro"; import { AutocompleteRenderInputParams, TextField } from "@mui/material"; -import { ComponentProps } from "react"; +import { ComponentProps, MouseEvent } from "react"; import { MultiSelect } from "@/components/multi-select"; @@ -10,6 +10,7 @@ export const MultiSelectInput = ({ placeholder, variant, size, + readOnly, onClick, }: { params: AutocompleteRenderInputParams; @@ -17,7 +18,8 @@ export const MultiSelectInput = ({ placeholder?: string; variant: ComponentProps["variant"]; size: ComponentProps["size"]; - onClick: () => void; + readOnly?: boolean; + onClick: (e: MouseEvent) => void; }) => { const noneLabel = t({ id: "controls.none", message: "None" }); @@ -31,6 +33,7 @@ export const MultiSelectInput = ({ ...params.inputProps, onClick: undefined, readOnly: true, + "aria-disabled": readOnly || undefined, size, sx: { width: 0, diff --git a/app/components/select-tree.spec.tsx b/app/components/select-tree.spec.tsx new file mode 100644 index 000000000..cfcefe352 --- /dev/null +++ b/app/components/select-tree.spec.tsx @@ -0,0 +1,231 @@ +import { ThemeProvider } from "@mui/material"; +import { + act, + cleanup, + fireEvent, + render, + screen, + within, +} from "@testing-library/react"; +import { ReactNode } from "react"; +import { afterEach, describe, expect, it, vi } from "vitest"; + +import { SelectTree, Tree } from "@/components/select-tree"; +import { FIELD_VALUE_NONE } from "@/configurator/constants"; +import { expectNoAxeViolations } from "@/test/axe"; +import { theme } from "@/themes/theme"; + +vi.mock("@lingui/macro", () => ({ + Trans: ({ children }: { children: ReactNode }) => children, + t: ({ message }: { message: string }) => message, + defineMessage: ({ message }: { message: string }) => message, + plural: (count: number, forms: Record) => + (count === 0 ? forms[0] : count === 1 ? forms.one : forms.other).replace( + "#", + `${count}` + ), +})); + +const OPTIONS: Tree = [ + { + value: "switzerland", + label: "Switzerland", + hasValue: false, + selectable: false, + children: [ + { value: "bern", label: "Bern", hasValue: true }, + { value: "zurich", label: "Zurich", hasValue: true }, + ], + }, +]; + +const OPTIONS_WITH_NONE: Tree = [ + { value: FIELD_VALUE_NONE, label: "Select filter", hasValue: true }, + ...OPTIONS, +]; + +describe("SelectTree", () => { + afterEach(cleanup); + + it("is a labelled button that opens a labelled dialog", async () => { + const { baseElement } = renderSelectTree({ value: "bern" }); + const trigger = screen.getByRole("button", { name: "Canton Bern" }); + + expect(trigger.getAttribute("aria-haspopup")).toBe("dialog"); + expect(trigger.getAttribute("aria-expanded")).toBe("false"); + + openWithKeyboard(trigger); + + expect(trigger.getAttribute("aria-expanded")).toBe("true"); + const dialog = screen.getByRole("dialog", { name: "Canton" }); + expect(within(dialog).getByRole("textbox", { name: "Search" })).toBe( + document.activeElement + ); + expect( + within(dialog).getByRole("button", { name: "Clear search field" }) + ).toBeTruthy(); + expect(within(dialog).getByRole("tree", { name: "Canton" })).toBeTruthy(); + await expectNoAxeViolations(baseElement); + }); + + it("does not open while read only", () => { + renderSelectTree({ value: "bern", readOnly: true }); + const trigger = screen.getByRole("button", { name: "Canton Bern" }); + + expect(trigger.getAttribute("aria-disabled")).toBe("true"); + openWithKeyboard(trigger); + + expect(screen.queryByRole("dialog")).toBeNull(); + }); + + it("searches with special characters and announces the result count", () => { + vi.useFakeTimers(); + renderSelectTree({ value: "bern" }); + openWithKeyboard(screen.getByRole("button", { name: "Canton Bern" })); + const search = screen.getByRole("textbox", { name: "Search" }); + + fireEvent.change(search, { target: { value: "(" } }); + act(() => { + vi.advanceTimersByTime(600); + }); + expect(screen.getByRole("status").textContent).toBe("No results"); + + fireEvent.change(search, { target: { value: "zur" } }); + act(() => { + vi.advanceTimersByTime(600); + }); + expect(screen.getByRole("status").textContent).toBe("1 result"); + vi.useRealTimers(); + }); + + it("selects by keyboard but ignores non-selectable nodes", () => { + const onChange = vi.fn(); + renderSelectTree({ value: "", onChange }); + openWithKeyboard(screen.getByRole("button", { name: /Canton/ })); + const tree = screen.getByRole("tree"); + + fireEvent.focus(tree); + fireEvent.keyDown(tree, { key: " " }); + expect(onChange).not.toHaveBeenCalled(); + + fireEvent.keyDown(tree, { key: "ArrowDown" }); + fireEvent.keyDown(tree, { key: "ArrowDown" }); + fireEvent.keyDown(tree, { key: " " }); + expect(onChange).toHaveBeenCalledWith({ target: { value: "zurich" } }); + }); + + it("adds a value by keyboard in multi mode and stays open", () => { + const onChange = vi.fn(); + renderSelectTree({ value: [], onChange, isMulti: true }); + openWithKeyboard(screen.getByRole("button", { name: /Canton/ })); + const tree = screen.getByRole("tree"); + + fireEvent.focus(tree); + fireEvent.keyDown(tree, { key: " " }); + expect(onChange).not.toHaveBeenCalled(); + + fireEvent.keyDown(tree, { key: "ArrowDown" }); + fireEvent.keyDown(tree, { key: " " }); + + expect(onChange).toHaveBeenCalledWith({ target: { value: ["bern"] } }); + expect(screen.getByRole("dialog")).toBeTruthy(); + }); + + it("removes a value by keyboard in multi mode", () => { + const onChange = vi.fn(); + renderSelectTree({ value: ["zurich"], onChange, isMulti: true }); + openWithKeyboard(screen.getByRole("button", { name: /Canton/ })); + const tree = screen.getByRole("tree"); + + fireEvent.focus(tree); + fireEvent.keyDown(tree, { key: " " }); + + expect(onChange).toHaveBeenCalledWith({ target: { value: [] } }); + }); + + it("keeps the selection when a range selection includes the none option", () => { + const onChange = vi.fn(); + renderSelectTree({ + value: ["zurich"], + onChange, + isMulti: true, + options: OPTIONS_WITH_NONE, + }); + openWithKeyboard(screen.getByRole("button", { name: /Canton/ })); + const tree = screen.getByRole("tree"); + + fireEvent.focus(tree); + fireEvent.keyDown(tree, { key: "a", ctrlKey: true }); + expect(onChange).not.toHaveBeenCalledWith({ target: { value: [] } }); + + fireEvent.keyDown(tree, { key: "Home" }); + fireEvent.keyDown(tree, { key: " " }); + expect(onChange).toHaveBeenLastCalledWith({ target: { value: [] } }); + }); + + it("closes on Escape and returns focus to the trigger", () => { + renderSelectTree({ value: "bern" }); + const trigger = screen.getByRole("button", { name: "Canton Bern" }); + openWithKeyboard(trigger); + + fireEvent.keyDown(screen.getByRole("dialog"), { key: "Escape" }); + + expect(trigger.getAttribute("aria-expanded")).toBe("false"); + expect(document.activeElement).toBe(trigger); + }); + + it("gives each instance its own ids", () => { + render( + + + + + ); + + const canton = screen.getByRole("button", { name: "Canton Bern" }); + const region = screen.getByRole("button", { name: "Region Zurich" }); + expect(canton.id).not.toBe(region.id); + }); +}); + +const renderSelectTree = ({ + value, + onChange = vi.fn(), + isMulti, + readOnly, + options = OPTIONS, +}: { + options?: Tree; + value: string | string[]; + onChange?: (e: { target: { value: string | string[] } }) => void; + isMulti?: boolean; + readOnly?: boolean; +}) => { + return render( + + + + ); +}; + +const openWithKeyboard = (trigger: HTMLElement) => { + trigger.focus(); + fireEvent.keyDown(trigger, { key: "Enter" }); +}; diff --git a/app/components/select-tree.tsx b/app/components/select-tree.tsx index e06cc82ca..0ca8df5b9 100644 --- a/app/components/select-tree.tsx +++ b/app/components/select-tree.tsx @@ -1,4 +1,4 @@ -import { Trans } from "@lingui/macro"; +import { plural, t, Trans } from "@lingui/macro"; import MUITreeItem, { TreeItemContentClassKey, TreeItemProps, @@ -22,11 +22,13 @@ import { useEventCallback, } from "@mui/material"; import { makeStyles } from "@mui/styles"; +import { useId } from "@reach/auto-id"; import clsx from "clsx"; +import isEqual from "lodash/isEqual"; import { ForwardedRef, forwardRef, - HTMLAttributes, + type KeyboardEvent, type MouseEvent, MouseEventHandler, ReactNode, @@ -39,6 +41,7 @@ import { import { Flex } from "@/components/flex"; import { Label, selectSizeToTypography } from "@/components/form"; +import { LiveRegion } from "@/components/live-region"; import { FIELD_VALUE_NONE } from "@/configurator/constants"; import { HierarchyValue } from "@/domain/data"; import { Icon } from "@/icons"; @@ -84,14 +87,12 @@ const useCustomTreeItemStyles = makeStyles( (theme) => ({ action: { marginLeft: theme.spacing(2), - color: theme.palette.text.primary, + color: theme.palette.text.secondary, lineHeight: 0, transform: "translateX(0)", - opacity: 0.5, - transition: "transform 0.3s ease, opacity 0.3s ease", + transition: "transform 0.3s ease, color 0.3s ease", "&:hover": { - opacity: 1, color: theme.palette.primary.main, }, }, @@ -229,7 +230,7 @@ const TreeItemContent = forwardRef< {label} {selectable && hasChildren ? ( -
+
Select @@ -278,14 +279,23 @@ export type SelectTreeProps = { onChange: (e: { target: { value: NodeId | NodeId[] } }) => void; sideControls?: ReactNode; disabled?: boolean; + readOnly?: boolean; // Controlled input value inputValue?: string; onChangeInputValue?: (value: string) => void; }; +const OPEN_KEYS = ["Enter", " ", "ArrowDown", "ArrowUp"]; + +const getSearchRegExp = (value: string) => { + const escapedValue = value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + + return new RegExp(`^${escapedValue}|\\s${escapedValue}`, "i"); +}; + const getFilteredOptions = (options: Tree, value: string) => { - const rx = new RegExp(`^${value}|\\s${value}`, "i"); + const rx = getSearchRegExp(value); return value === "" ? options @@ -411,6 +421,7 @@ export const SelectTree = ({ value, onChange, disabled, + readOnly, sideControls, onOpen, onClose, @@ -418,7 +429,12 @@ export const SelectTree = ({ id, isMulti = false, }: SelectTreeProps) => { + const generatedId = useId(); + const triggerId = id ?? `select-tree-${generatedId}`; + const labelId = label ? `${triggerId}-label` : undefined; + const dialogId = `${triggerId}-dialog`; const [openState, setOpenState] = useState(false); + const isOpen = open ?? openState; const [minMenuWidth, setMinMenuWidth] = useState(); const { @@ -458,7 +474,30 @@ export const SelectTree = ({ return res; }, [options, parentsRef]); + const nonSelectableValues = useMemo(() => { + return new Set( + flattenTree(options as HierarchyValue[]) + .filter((node) => (node as TreeHierarchyValue).selectable === false) + .map((node) => node.value) + ); + }, [options]); + + const resultsCount = useMemo(() => { + const rx = getSearchRegExp(inputValue); + + return flattenTree(filteredOptions as HierarchyValue[]).filter( + (node) => node.value !== FIELD_VALUE_NONE && rx.test(node.label) + ).length; + }, [filteredOptions, inputValue]); + const handleOpen = useEventCallback(() => { + if (disabled || readOnly) { + return; + } + + inputRef.current + ?.querySelector(`[aria-haspopup="dialog"]`) + ?.focus(); setOpenState(true); setMinMenuWidth(inputRef.current?.clientLeft); onOpen?.(); @@ -472,11 +511,32 @@ export const SelectTree = ({ onClose?.(); }); - const handleNodeSelect = useEventCallback((_, v: NodeId | NodeId[]) => { + const handleNodeSelect = useEventCallback((_, v: NodeId) => { + if (nonSelectableValues.has(v)) { + return; + } + onChange({ target: { value: v } }); + handleClose(); + }); - if (!isMulti) { - handleClose(); + const handleMultiNodeSelect = useEventCallback((_, ids: NodeId[]) => { + const currentValues = value as NodeId[]; + const addedIds = ids.filter((id) => !currentValues.includes(id)); + + if (addedIds.length === 1 && addedIds[0] === FIELD_VALUE_NONE) { + onChange({ target: { value: [] } }); + return; + } + + const nextValues = ids.filter( + (id) => + id !== FIELD_VALUE_NONE && + (currentValues.includes(id) || !nonSelectableValues.has(id)) + ); + + if (!isEqual(nextValues, currentValues)) { + onChange({ target: { value: nextValues } }); } }); @@ -564,12 +624,16 @@ export const SelectTree = ({ const paperProps = useMemo( () => ({ + id: dialogId, + role: "dialog", + "aria-modal": true, + "aria-labelledby": labelId, sx: { minWidth: minMenuWidth ?? 0, boxShadow: 3, }, }), - [minMenuWidth] + [minMenuWidth, dialogId, labelId] ); const menuTransitionProps = useMemo( @@ -589,14 +653,12 @@ export const SelectTree = ({ ); const treeRef = useRef(); - const handleKeyDown: HTMLAttributes["onKeyDown"] = useEvent( - (e) => { - if (e.key === "Enter" || e.key == " ") { - handleOpen(); - e.preventDefault(); - } + const handleKeyDown = useEvent((e: KeyboardEvent) => { + if (OPEN_KEYS.includes(e.key)) { + e.preventDefault(); + handleOpen(); } - ); + }); useEffect(() => { const inputNode = inputRef.current; @@ -609,7 +671,7 @@ export const SelectTree = ({
{label && (
+ ))} + + + + ); +}; diff --git a/app/configurator/components/use-focus-filter.ts b/app/configurator/components/use-focus-filter.ts new file mode 100644 index 000000000..2c7412937 --- /dev/null +++ b/app/configurator/components/use-focus-filter.ts @@ -0,0 +1,30 @@ +import { useEffect, useState } from "react"; + +import { useEvent } from "@/utils/use-event"; + +const FILTER_CONTROL_SELECTOR = + '[role="combobox"], [aria-haspopup="dialog"], input:not([type="checkbox"]):not([aria-hidden="true"])'; + +/** Moves focus to the control of a filter card once it has rendered, e.g. after adding it. */ +export const useFocusFilter = () => { + const [pendingId, setPendingId] = useState(); + + useEffect(() => { + if (!pendingId) { + return; + } + + const element = Array.from( + document.querySelectorAll("[data-rbd-draggable-id]") + ) + .find((card) => card.getAttribute("data-rbd-draggable-id") === pendingId) + ?.querySelector(FILTER_CONTROL_SELECTOR); + + element?.focus(); + setPendingId(undefined); + }, [pendingId]); + + return useEvent((id: string) => { + setPendingId(id); + }); +}; diff --git a/app/locales/de/messages.po b/app/locales/de/messages.po index d0e8274c2..4b1ba6d2a 100644 --- a/app/locales/de/messages.po +++ b/app/locales/de/messages.po @@ -19,10 +19,6 @@ msgstr "" msgid "metadata.link.created.with" msgstr "Erstellt mit" -#: app/components/move-drag-button.tsx -msgid "Drag filters to reorganize" -msgstr "Ziehen Sie die Filter per Drag & Drop, um sie neu zu organisieren" - #: app/configurator/components/add-dataset-drawer/add-dataset-drawer.tsx msgid "dataset.search.search-options.no-options-selected" msgstr "Keine Optionen ausgewählt" @@ -105,6 +101,10 @@ msgstr "{0} von {1}" msgid "wmts.search-results" msgstr "{resultsCount, plural, =0 {Keine Ergebnisse} one {# Ergebnis} other {# Ergebnisse}}" +#: app/components/select-tree.tsx +msgid "controls.select-tree.results" +msgstr "{resultsCount, plural, =0 {Keine Ergebnisse} one {# Ergebnis} other {# Ergebnisse}}" + #: app/configurator/components/field-i18n.ts msgid "controls.sorting.byMeasure.ascending" msgstr "1 → 9" @@ -497,12 +497,14 @@ msgstr "Wählen Sie kontrastierende Farben für Start- und Endpunkt. Diese Farbe #: app/charts/map/wms-wmts-selector.tsx #: app/components/form.tsx +#: app/components/select-tree.tsx #: app/configurator/components/add-dataset-drawer/add-dataset-drawer.tsx msgid "controls.search.clear" msgstr "Suche zurücksetzen" #: app/charts/shared/chart-data-filters/index.tsx #: app/components/multi-select/option.tsx +#: app/configurator/components/field-date-picker.tsx msgid "controls.clear-selection" msgstr "Auswahl löschen" @@ -524,6 +526,10 @@ msgstr "Schliessen" msgid "controls.metadata-panel.close" msgstr "Schliessen" +#: app/components/multi-select/index.tsx +msgid "controls.select.close" +msgstr "Schliessen" + #: app/configurator/components/chart-options-selector/color-component-field.tsx #: app/configurator/components/chart-options-selector/conversion-units-field.tsx #: app/configurator/components/field-i18n.ts @@ -1096,6 +1102,26 @@ msgstr "Entwürfe einschliessen" msgid "controls.filters.interactive.toggle" msgstr "Interaktiv" +#: app/configurator/components/chart-options-selector/calculation-field.tsx +msgid "controls.filters.interactive.toggle-calculation" +msgstr "Interaktiver Diagrammmodus" + +#: app/configurator/components/filters.tsx +msgid "controls.filters.interactive.toggle-filter" +msgstr "Interaktiver Filter" + +#: app/configurator/components/filters.tsx +msgid "controls.filters.interactive.toggle-legend" +msgstr "Interaktiver Legendenfilter" + +#: app/configurator/components/filters.tsx +msgid "controls.filters.interactive.toggle-time-range" +msgstr "Interaktiver Zeitbereich" + +#: app/configurator/components/chart-configurator.tsx +msgid "controls.filters.interactive.toggle-for" +msgstr "Interaktiv: {filterLabel}" + #: app/configurator/components/chart-options-selector/color-component-field.tsx msgid "controls.color.scale.interpolation" msgstr "Interpolation" @@ -1244,6 +1270,10 @@ msgstr "Links" msgid "hint.loading.data" msgstr "Lade Daten …" +#: app/components/multi-select/index.tsx +msgid "controls.select.loading" +msgstr "Lade Daten …" + #: app/configurator/components/chart-options-selector/base-layer-field.tsx msgid "chart.map.layers.base.view.locked" msgstr "Gesperrte Ansicht" @@ -1421,6 +1451,10 @@ msgstr "Keine importierte Karten" msgid "chart-selection-tabs.no-label" msgstr "Kein Tab-Titel" +#: app/components/multi-select/index.tsx +msgid "controls.select.no-options" +msgstr "Keine Optionen" + #: app/browse/ui/dataset-results.tsx #: app/components/select-tree.tsx msgid "No results" @@ -1486,6 +1520,10 @@ msgstr "Ein" msgid "controls.color.opacity" msgstr "Transparenz" +#: app/components/multi-select/index.tsx +msgid "controls.select.open" +msgstr "Öffnen" + #: app/configurator/components/chart-controls/color-picker.tsx msgid "controls.colorpicker.open-for" msgstr "Farbauswahl öffnen: {label}" @@ -1653,6 +1691,10 @@ msgstr "Umbenennen" msgid "profile.chart.rename-dialog.title" msgstr "Benennen Sie die Visualisierung um" +#: app/components/move-drag-button.tsx +msgid "controls.drag-handle.reorder" +msgstr "Neu anordnen: {label}" + #: app/configurator/table/table-chart-sorting-options.tsx msgid "controls.table.sorting.reorder" msgstr "Neu anordnen: {label}" @@ -1741,6 +1783,10 @@ msgstr "Scatterplot" msgid "dataset.search.label" msgstr "Suchen" +#: app/components/select-tree.tsx +msgid "controls.select-tree.search" +msgstr "Suchen" + #: app/charts/map/wms-wmts-selector.tsx msgid "wmts.search-label" msgstr "In importierten Karten suchen" @@ -1901,6 +1947,10 @@ msgstr "Teilen via Twitter" msgid "publication.share.linktitle.mail" msgstr "Versenden via E-Mail" +#: app/configurator/components/layout-configurator.tsx +msgid "controls.layout.shared-filter.toggle" +msgstr "Geteilter Filter: {label}" + #: app/configurator/components/layout-configurator.tsx msgid "controls.section.shared-filters" msgstr "Geteilte Filter" diff --git a/app/locales/en/messages.po b/app/locales/en/messages.po index 150de9e05..c258c0833 100644 --- a/app/locales/en/messages.po +++ b/app/locales/en/messages.po @@ -19,10 +19,6 @@ msgstr "" msgid "metadata.link.created.with" msgstr "Created with" -#: app/components/move-drag-button.tsx -msgid "Drag filters to reorganize" -msgstr "Drag filters to reorganize" - #: app/configurator/components/add-dataset-drawer/add-dataset-drawer.tsx msgid "dataset.search.search-options.no-options-selected" msgstr "dataset.search.search-options.no-options-selected" @@ -105,6 +101,10 @@ msgstr "{0} of {1}" msgid "wmts.search-results" msgstr "{resultsCount, plural, =0 {No results} one {# result} other {# results}}" +#: app/components/select-tree.tsx +msgid "controls.select-tree.results" +msgstr "{resultsCount, plural, =0 {No results} one {# result} other {# results}}" + #: app/configurator/components/field-i18n.ts msgid "controls.sorting.byMeasure.ascending" msgstr "1 → 9" @@ -497,12 +497,14 @@ msgstr "Choose contrasting colors for the start and end points. These colors wil #: app/charts/map/wms-wmts-selector.tsx #: app/components/form.tsx +#: app/components/select-tree.tsx #: app/configurator/components/add-dataset-drawer/add-dataset-drawer.tsx msgid "controls.search.clear" msgstr "Clear search field" #: app/charts/shared/chart-data-filters/index.tsx #: app/components/multi-select/option.tsx +#: app/configurator/components/field-date-picker.tsx msgid "controls.clear-selection" msgstr "Clear selection" @@ -524,6 +526,10 @@ msgstr "Close" msgid "controls.metadata-panel.close" msgstr "Close" +#: app/components/multi-select/index.tsx +msgid "controls.select.close" +msgstr "Close" + #: app/configurator/components/chart-options-selector/color-component-field.tsx #: app/configurator/components/chart-options-selector/conversion-units-field.tsx #: app/configurator/components/field-i18n.ts @@ -1096,6 +1102,26 @@ msgstr "Include draft datasets" msgid "controls.filters.interactive.toggle" msgstr "Interactive" +#: app/configurator/components/chart-options-selector/calculation-field.tsx +msgid "controls.filters.interactive.toggle-calculation" +msgstr "Interactive chart mode" + +#: app/configurator/components/filters.tsx +msgid "controls.filters.interactive.toggle-filter" +msgstr "Interactive filter" + +#: app/configurator/components/filters.tsx +msgid "controls.filters.interactive.toggle-legend" +msgstr "Interactive legend filter" + +#: app/configurator/components/filters.tsx +msgid "controls.filters.interactive.toggle-time-range" +msgstr "Interactive time range" + +#: app/configurator/components/chart-configurator.tsx +msgid "controls.filters.interactive.toggle-for" +msgstr "Interactive: {filterLabel}" + #: app/configurator/components/chart-options-selector/color-component-field.tsx msgid "controls.color.scale.interpolation" msgstr "Interpolation" @@ -1244,6 +1270,10 @@ msgstr "Links" msgid "hint.loading.data" msgstr "Loading data..." +#: app/components/multi-select/index.tsx +msgid "controls.select.loading" +msgstr "Loading…" + #: app/configurator/components/chart-options-selector/base-layer-field.tsx msgid "chart.map.layers.base.view.locked" msgstr "Locked view" @@ -1421,6 +1451,10 @@ msgstr "No imported maps" msgid "chart-selection-tabs.no-label" msgstr "No label" +#: app/components/multi-select/index.tsx +msgid "controls.select.no-options" +msgstr "No options" + #: app/browse/ui/dataset-results.tsx #: app/components/select-tree.tsx msgid "No results" @@ -1486,6 +1520,10 @@ msgstr "On" msgid "controls.color.opacity" msgstr "Opacity" +#: app/components/multi-select/index.tsx +msgid "controls.select.open" +msgstr "Open" + #: app/configurator/components/chart-controls/color-picker.tsx msgid "controls.colorpicker.open-for" msgstr "Open color picker: {label}" @@ -1653,6 +1691,10 @@ msgstr "Rename" msgid "profile.chart.rename-dialog.title" msgstr "Rename the visualization" +#: app/components/move-drag-button.tsx +msgid "controls.drag-handle.reorder" +msgstr "Reorder: {label}" + #: app/configurator/table/table-chart-sorting-options.tsx msgid "controls.table.sorting.reorder" msgstr "Reorder: {label}" @@ -1741,6 +1783,10 @@ msgstr "Scatterplot" msgid "dataset.search.label" msgstr "Search" +#: app/components/select-tree.tsx +msgid "controls.select-tree.search" +msgstr "Search" + #: app/charts/map/wms-wmts-selector.tsx msgid "wmts.search-label" msgstr "Search in imported maps" @@ -1901,6 +1947,10 @@ msgstr "Share on Twitter" msgid "publication.share.linktitle.mail" msgstr "Share via Email" +#: app/configurator/components/layout-configurator.tsx +msgid "controls.layout.shared-filter.toggle" +msgstr "Shared filter: {label}" + #: app/configurator/components/layout-configurator.tsx msgid "controls.section.shared-filters" msgstr "Shared filters" diff --git a/app/locales/fr/messages.po b/app/locales/fr/messages.po index a58cf8b4b..3541961f9 100644 --- a/app/locales/fr/messages.po +++ b/app/locales/fr/messages.po @@ -19,10 +19,6 @@ msgstr "" msgid "metadata.link.created.with" msgstr "Créé avec" -#: app/components/move-drag-button.tsx -msgid "Drag filters to reorganize" -msgstr "Faites glisser les filtres pour les réorganiser" - #: app/configurator/components/add-dataset-drawer/add-dataset-drawer.tsx msgid "dataset.search.search-options.no-options-selected" msgstr "Aucune option sélectionnée" @@ -105,6 +101,10 @@ msgstr "{0} sur {1}" msgid "wmts.search-results" msgstr "{resultsCount, plural, =0 {Aucun résultat} one {# résultat} other {# résultats}}" +#: app/components/select-tree.tsx +msgid "controls.select-tree.results" +msgstr "{resultsCount, plural, =0 {Aucun résultat} one {# résultat} other {# résultats}}" + #: app/configurator/components/field-i18n.ts msgid "controls.sorting.byMeasure.ascending" msgstr "1 → 9" @@ -497,14 +497,16 @@ msgstr "Choisissez des couleurs contrastées pour les points de départ et d'arr #: app/charts/map/wms-wmts-selector.tsx #: app/components/form.tsx +#: app/components/select-tree.tsx #: app/configurator/components/add-dataset-drawer/add-dataset-drawer.tsx msgid "controls.search.clear" msgstr "Effacer la recherche" #: app/charts/shared/chart-data-filters/index.tsx #: app/components/multi-select/option.tsx +#: app/configurator/components/field-date-picker.tsx msgid "controls.clear-selection" -msgstr "Sélection claire" +msgstr "Effacer la sélection" #: app/configurator/components/chart-annotations/chart-annotations-selector.tsx msgid "controls.annotations.annotation.clear-text" @@ -524,6 +526,10 @@ msgstr "Fermer" msgid "controls.metadata-panel.close" msgstr "Fermer" +#: app/components/multi-select/index.tsx +msgid "controls.select.close" +msgstr "Fermer" + #: app/configurator/components/chart-options-selector/color-component-field.tsx #: app/configurator/components/chart-options-selector/conversion-units-field.tsx #: app/configurator/components/field-i18n.ts @@ -1096,6 +1102,26 @@ msgstr "Inclure les brouillons" msgid "controls.filters.interactive.toggle" msgstr "Interactif" +#: app/configurator/components/chart-options-selector/calculation-field.tsx +msgid "controls.filters.interactive.toggle-calculation" +msgstr "Interactif : mode de graphique" + +#: app/configurator/components/filters.tsx +msgid "controls.filters.interactive.toggle-filter" +msgstr "Interactif : filtre" + +#: app/configurator/components/filters.tsx +msgid "controls.filters.interactive.toggle-legend" +msgstr "Interactif : filtre de légende" + +#: app/configurator/components/filters.tsx +msgid "controls.filters.interactive.toggle-time-range" +msgstr "Interactif : période" + +#: app/configurator/components/chart-configurator.tsx +msgid "controls.filters.interactive.toggle-for" +msgstr "Interactif : {filterLabel}" + #: app/configurator/components/chart-options-selector/color-component-field.tsx msgid "controls.color.scale.interpolation" msgstr "Interpolation" @@ -1244,6 +1270,10 @@ msgstr "Links" msgid "hint.loading.data" msgstr "Chargement des données..." +#: app/components/multi-select/index.tsx +msgid "controls.select.loading" +msgstr "Chargement…" + #: app/configurator/components/chart-options-selector/base-layer-field.tsx msgid "chart.map.layers.base.view.locked" msgstr "Carte verrouillée" @@ -1421,6 +1451,10 @@ msgstr "Aucune carte importée" msgid "chart-selection-tabs.no-label" msgstr "Pas de Titre" +#: app/components/multi-select/index.tsx +msgid "controls.select.no-options" +msgstr "Aucune option" + #: app/browse/ui/dataset-results.tsx #: app/components/select-tree.tsx msgid "No results" @@ -1486,6 +1520,10 @@ msgstr "Actif" msgid "controls.color.opacity" msgstr "Transparence" +#: app/components/multi-select/index.tsx +msgid "controls.select.open" +msgstr "Ouvrir" + #: app/configurator/components/chart-controls/color-picker.tsx msgid "controls.colorpicker.open-for" msgstr "Ouvrir le sélecteur de couleur : {label}" @@ -1653,6 +1691,10 @@ msgstr "Renommer" msgid "profile.chart.rename-dialog.title" msgstr "Renommer la visualisation" +#: app/components/move-drag-button.tsx +msgid "controls.drag-handle.reorder" +msgstr "Réorganiser : {label}" + #: app/configurator/table/table-chart-sorting-options.tsx msgid "controls.table.sorting.reorder" msgstr "Réorganiser : {label}" @@ -1741,6 +1783,10 @@ msgstr "Nuage de points" msgid "dataset.search.label" msgstr "Chercher" +#: app/components/select-tree.tsx +msgid "controls.select-tree.search" +msgstr "Rechercher" + #: app/charts/map/wms-wmts-selector.tsx msgid "wmts.search-label" msgstr "Rechercher dans les cartes importées" @@ -1901,6 +1947,10 @@ msgstr "Partager sur Twitter" msgid "publication.share.linktitle.mail" msgstr "Partager par courriel" +#: app/configurator/components/layout-configurator.tsx +msgid "controls.layout.shared-filter.toggle" +msgstr "Filtre partagé : {label}" + #: app/configurator/components/layout-configurator.tsx msgid "controls.section.shared-filters" msgstr "Filtres partagés" diff --git a/app/locales/it/messages.po b/app/locales/it/messages.po index d90bf501e..a974172fe 100644 --- a/app/locales/it/messages.po +++ b/app/locales/it/messages.po @@ -19,10 +19,6 @@ msgstr "" msgid "metadata.link.created.with" msgstr "Creato con" -#: app/components/move-drag-button.tsx -msgid "Drag filters to reorganize" -msgstr "Trascina i filtri per riorganizzarli" - #: app/configurator/components/add-dataset-drawer/add-dataset-drawer.tsx msgid "dataset.search.search-options.no-options-selected" msgstr "Nessuna opzione selezionata" @@ -105,6 +101,10 @@ msgstr "{0} di {1}" msgid "wmts.search-results" msgstr "{resultsCount, plural, =0 {Nessun risultato} one {# risultato} other {# risultati}}" +#: app/components/select-tree.tsx +msgid "controls.select-tree.results" +msgstr "{resultsCount, plural, =0 {Nessun risultato} one {# risultato} other {# risultati}}" + #: app/configurator/components/field-i18n.ts msgid "controls.sorting.byMeasure.ascending" msgstr "1 → 9" @@ -497,14 +497,16 @@ msgstr "Scegli colori contrastanti per i punti iniziali e finali: questo aiuter #: app/charts/map/wms-wmts-selector.tsx #: app/components/form.tsx +#: app/components/select-tree.tsx #: app/configurator/components/add-dataset-drawer/add-dataset-drawer.tsx msgid "controls.search.clear" msgstr "Cancella la ricerca" #: app/charts/shared/chart-data-filters/index.tsx #: app/components/multi-select/option.tsx +#: app/configurator/components/field-date-picker.tsx msgid "controls.clear-selection" -msgstr "Selezione chiara" +msgstr "Cancella selezione" #: app/configurator/components/chart-annotations/chart-annotations-selector.tsx msgid "controls.annotations.annotation.clear-text" @@ -524,6 +526,10 @@ msgstr "Chiudi" msgid "controls.metadata-panel.close" msgstr "Chiudi" +#: app/components/multi-select/index.tsx +msgid "controls.select.close" +msgstr "Chiudi" + #: app/configurator/components/chart-options-selector/color-component-field.tsx #: app/configurator/components/chart-options-selector/conversion-units-field.tsx #: app/configurator/components/field-i18n.ts @@ -1096,6 +1102,26 @@ msgstr "Includere le bozze" msgid "controls.filters.interactive.toggle" msgstr "Interattivo" +#: app/configurator/components/chart-options-selector/calculation-field.tsx +msgid "controls.filters.interactive.toggle-calculation" +msgstr "Interattivo: modalità grafico" + +#: app/configurator/components/filters.tsx +msgid "controls.filters.interactive.toggle-filter" +msgstr "Interattivo: filtro" + +#: app/configurator/components/filters.tsx +msgid "controls.filters.interactive.toggle-legend" +msgstr "Interattivo: filtro della legenda" + +#: app/configurator/components/filters.tsx +msgid "controls.filters.interactive.toggle-time-range" +msgstr "Interattivo: intervallo di tempo" + +#: app/configurator/components/chart-configurator.tsx +msgid "controls.filters.interactive.toggle-for" +msgstr "Interattivo: {filterLabel}" + #: app/configurator/components/chart-options-selector/color-component-field.tsx msgid "controls.color.scale.interpolation" msgstr "Interpolazione" @@ -1244,6 +1270,10 @@ msgstr "Collegamenti" msgid "hint.loading.data" msgstr "Caricamento dei dati..." +#: app/components/multi-select/index.tsx +msgid "controls.select.loading" +msgstr "Caricamento…" + #: app/configurator/components/chart-options-selector/base-layer-field.tsx msgid "chart.map.layers.base.view.locked" msgstr "Vista bloccata" @@ -1421,6 +1451,10 @@ msgstr "Nessuna mappa importata" msgid "chart-selection-tabs.no-label" msgstr "Senza etichetta" +#: app/components/multi-select/index.tsx +msgid "controls.select.no-options" +msgstr "Nessuna opzione" + #: app/browse/ui/dataset-results.tsx #: app/components/select-tree.tsx msgid "No results" @@ -1486,6 +1520,10 @@ msgstr "Attivo" msgid "controls.color.opacity" msgstr "Trasparenza" +#: app/components/multi-select/index.tsx +msgid "controls.select.open" +msgstr "Apri" + #: app/configurator/components/chart-controls/color-picker.tsx msgid "controls.colorpicker.open-for" msgstr "Apri il selettore di colore: {label}" @@ -1653,6 +1691,10 @@ msgstr "Rinominare" msgid "profile.chart.rename-dialog.title" msgstr "Rinomina la visualizzazione" +#: app/components/move-drag-button.tsx +msgid "controls.drag-handle.reorder" +msgstr "Riordina: {label}" + #: app/configurator/table/table-chart-sorting-options.tsx msgid "controls.table.sorting.reorder" msgstr "Riordina: {label}" @@ -1741,6 +1783,10 @@ msgstr "Scatterplot" msgid "dataset.search.label" msgstr "Cerca" +#: app/components/select-tree.tsx +msgid "controls.select-tree.search" +msgstr "Cerca" + #: app/charts/map/wms-wmts-selector.tsx msgid "wmts.search-label" msgstr "Cerca nelle mappe importate" @@ -1901,6 +1947,10 @@ msgstr "Condividi su Twitter" msgid "publication.share.linktitle.mail" msgstr "Condividi via Email" +#: app/configurator/components/layout-configurator.tsx +msgid "controls.layout.shared-filter.toggle" +msgstr "Filtro condiviso: {label}" + #: app/configurator/components/layout-configurator.tsx msgid "controls.section.shared-filters" msgstr "Filtri condivisi" diff --git a/e2e/data-filters-keyboard.spec.ts b/e2e/data-filters-keyboard.spec.ts new file mode 100644 index 000000000..0b5ea76e5 --- /dev/null +++ b/e2e/data-filters-keyboard.spec.ts @@ -0,0 +1,154 @@ +import { Locator, Page } from "@playwright/test"; + +import { expectNoAxeViolations } from "./a11y"; +import { setup } from "./common"; +import columnTwoCharts from "./fixtures/column-two-charts-chart-config.json"; +import mapNfi from "./fixtures/map-nfi-chart-config.json"; + +const { expect, test } = setup(); + +test.describe("Interactive data filters by keyboard", () => { + test("a select keeps focus while the chart reloads", async ({ page }) => { + await openWithDataFilters({ + page, + config: columnTwoCharts, + mode: "single", + }); + const select = filters(page).getByRole("combobox"); + await waitUntilEnabled(select); + + await select.focus(); + await page.keyboard.press("ArrowDown"); + await page.keyboard.press("ArrowDown"); + await page.keyboard.press("Enter"); + + await expect(select).not.toHaveText("Zurich"); + await expect(select).toBeFocused(); + await waitUntilEnabled(select); + await expect(select).toBeFocused(); + }); + + test("a multi select opens with the arrow keys and closes with Escape", async ({ + page, + }) => { + await openWithDataFilters({ page, config: columnTwoCharts, mode: "multi" }); + const input = filters(page).getByRole("combobox"); + await waitUntilEnabled(input); + + await input.focus(); + await page.keyboard.press("ArrowDown"); + await expect(input).toHaveAttribute("aria-expanded", "true"); + await expect(page.getByRole("listbox")).toBeVisible(); + + await page.keyboard.press("Escape"); + await expect(input).toHaveAttribute("aria-expanded", "false"); + await expect(input).toBeFocused(); + }); + + test("a multi select still opens and closes on click", async ({ page }) => { + await openWithDataFilters({ + page, + config: columnTwoCharts, + mode: "multi", + }); + const input = filters(page).getByRole("combobox"); + await waitUntilEnabled(input); + + await input.click(); + await expect(page.getByRole("listbox")).toBeVisible(); + + await input.click(); + await expect(page.getByRole("listbox")).toBeHidden(); + }); + + test("a hierarchical filter is a button that opens a searchable tree dialog", async ({ + page, + }) => { + await openWithDataFilters({ page, config: mapNfi, mode: "single" }); + const trigger = filters(page).locator('[aria-haspopup="dialog"]'); + await waitUntilEnabled(trigger); + + await expectNoAxeViolations({ + page, + include: '[data-testid="published-chart-interactive-filters"]', + }); + + await trigger.focus(); + await page.keyboard.press("Enter"); + const dialog = page.getByRole("dialog", { name: "tree condition" }); + await expect(dialog).toHaveCSS("opacity", "1"); + await expectNoAxeViolations({ page, include: '[role="dialog"]' }); + await expect(dialog.getByRole("textbox", { name: "Search" })).toBeFocused(); + + await page.keyboard.type("("); + await expect(page.getByRole("status").last()).toHaveText("No results"); + + await page.keyboard.press("Backspace"); + await page.keyboard.press("Tab"); + await page.keyboard.press("Tab"); + await expect(dialog.getByRole("tree")).toBeFocused(); + + await page.keyboard.press("Home"); + await page.keyboard.press("ArrowDown"); + await page.keyboard.press(" "); + await expect(dialog).toBeHidden(); + await expect(trigger).toBeFocused(); + await expect(trigger).toHaveText("Standing dead"); + }); +}); + +const filters = (page: Page) => + page.getByTestId("published-chart-interactive-filters"); + +const waitUntilEnabled = async (locator: Locator) => { + await expect(locator).not.toHaveAttribute("aria-disabled", "true", { + timeout: 60_000, + }); +}; + +const openWithDataFilters = async ({ + page, + config, + mode, +}: { + page: Page; + config: object; + mode: "single" | "multi"; +}) => { + const key = `data-filters-keyboard-${mode}-${Math.random().toString(36).slice(2)}`; + const storageKey = `vizualize-configurator-state:${key}`; + await page.goto("/en"); + await page.evaluate( + ([k, v]) => localStorage.setItem(k, v), + [storageKey, JSON.stringify(config)] + ); + await page.goto(`/en/create/${key}`); + await page.waitForSelector('[data-chart-loaded="true"]', { + timeout: 60_000, + }); + await page.evaluate( + ([k, filterType]) => { + const state = JSON.parse(localStorage.getItem(k)!); + const chartConfig = state.chartConfigs[0]; + const cubeFilters = chartConfig.cubes[0].filters; + const ids = Object.keys(cubeFilters).filter( + (id) => cubeFilters[id].type !== "range" + ); + delete chartConfig.activeField; + chartConfig.interactiveFiltersConfig.dataFilters = { + ...chartConfig.interactiveFiltersConfig.dataFilters, + active: true, + componentIds: ids, + filterTypes: Object.fromEntries(ids.map((id) => [id, filterType])), + defaultOpen: true, + }; + localStorage.setItem(k, JSON.stringify(state)); + }, + [storageKey, mode] + ); + await page.reload(); + await page.waitForSelector('[data-chart-loaded="true"]', { + timeout: 60_000, + }); + await filters(page).waitFor(); +}; diff --git a/e2e/editor-filters-keyboard.spec.ts b/e2e/editor-filters-keyboard.spec.ts new file mode 100644 index 000000000..3eba90498 --- /dev/null +++ b/e2e/editor-filters-keyboard.spec.ts @@ -0,0 +1,135 @@ +import { Page } from "@playwright/test"; + +import { loadChartInLocalStorage } from "./charts-utils"; +import { setup } from "./common"; +import columnTwoCharts from "./fixtures/column-two-charts-chart-config.json"; +import mapNfi from "./fixtures/map-nfi-chart-config.json"; + +const { expect, test } = setup(); + +test.describe("Editor filters by keyboard", () => { + test("a filter card has a named drag handle and named switch", async ({ + page, + }) => { + await openEditor({ page, key: "editor-filters-names" }); + const filters = filtersSection(page); + + await expect( + filters.getByRole("button", { name: "Reorder: 1. Kanton" }) + ).toBeVisible(); + await expect( + filters.getByRole("checkbox", { name: "Interactive: 1. Kanton" }) + ).toBeVisible(); + await expect( + filters.locator('[data-rbd-draggable-id][tabindex="0"]') + ).toHaveCount(0); + }); + + test("a filter select keeps focus after choosing a value", async ({ + page, + }) => { + await openEditor({ page, key: "editor-filters-focus" }); + const selectId = await filtersSection(page) + .getByRole("combobox") + .first() + .getAttribute("id"); + // The open menu hides the page from the accessibility tree, so use the id. + const select = page.locator(`[id="${selectId}"]`); + await expect(select).not.toHaveAttribute("aria-disabled", "true", { + timeout: 30_000, + }); + + const before = (await select.textContent()) ?? ""; + await select.focus(); + // The editor can refetch right after loading, which makes the select read only for a moment. + await expect(async () => { + if ((await select.getAttribute("aria-expanded")) !== "true") { + await page.keyboard.press("ArrowDown"); + } + + await expect(select).toHaveAttribute("aria-expanded", "true", { + timeout: 1_000, + }); + }).toPass({ timeout: 30_000 }); + await page.keyboard.press("ArrowDown"); + await page.keyboard.press("Enter"); + + await expect(select).not.toHaveText(before); + await expect(select).toBeFocused(); + await expect(select).not.toHaveAttribute("aria-disabled", "true", { + timeout: 30_000, + }); + await expect(select).toBeFocused(); + }); + + test("a filter keeps focus on its drag handle after moving it", async ({ + page, + }) => { + await openEditor({ + page, + key: "editor-filters-reorder", + config: { + ...mapNfi, + activeField: undefined, + chartConfig: { ...mapNfi.chartConfig, activeField: undefined }, + }, + }); + const handle = filtersSection(page).getByRole("button", { + name: /^Reorder: 1\. /, + }); + const name = (await handle.getAttribute("aria-label")) ?? ""; + + await handle.focus(); + await page.keyboard.press(" "); + await page.keyboard.press("ArrowDown"); + await page.keyboard.press(" "); + + const moved = name.replace("Reorder: 1. ", "Reorder: 2. "); + const movedHandle = page.getByRole("button", { name: moved }); + await expect(movedHandle).toBeFocused(); + await expect(movedHandle).not.toHaveAttribute("aria-disabled", "true", { + timeout: 30_000, + }); + await expect(movedHandle).toBeFocused(); + }); + + test("Show Filters reports its state and the list it controls", async ({ + page, + }) => { + const config = structuredClone(columnTwoCharts); + config.chartConfigs[0].interactiveFiltersConfig.dataFilters.defaultOpen = + false; + await openEditor({ page, key: "editor-filters-toggle", config }); + const toggle = page.getByRole("button", { name: "Show Filters" }); + + await expect(toggle).toHaveAttribute("aria-expanded", "false"); + const listId = await toggle.getAttribute("aria-controls"); + await toggle.click(); + + await expect( + page.getByRole("button", { name: "Hide Filters" }) + ).toHaveAttribute("aria-expanded", "true"); + await expect(page.locator(`#${listId}`)).toBeVisible(); + }); +}); + +const filtersSection = (page: Page) => + page.locator('[data-testid="controlSection"]', { + has: page.locator('h6:text-is("Filters")'), + }); + +const openEditor = async ({ + page, + key, + config = columnTwoCharts, +}: { + page: Page; + key: string; + config?: object; +}) => { + await loadChartInLocalStorage(page, key, config); + await page.goto(`/en/create/${key}`); + await page.waitForSelector('[data-chart-loaded="true"]', { + timeout: 60_000, + }); +}; diff --git a/e2e/keyboard-widgets.spec.ts b/e2e/keyboard-widgets.spec.ts index dac81ac02..a79193a21 100644 --- a/e2e/keyboard-widgets.spec.ts +++ b/e2e/keyboard-widgets.spec.ts @@ -267,10 +267,13 @@ test.describe("Keyboard operability", () => { await page.goto(`/en/create/${key}`); await page.getByRole("tab", { name: "Sorting" }).click({ timeout: 30_000 }); - await expect(page.locator('[aria-label^="Reorder: "]')).toHaveAttribute( - "aria-label", - "Reorder: Warning region" - ); + await expect( + page + .locator('[data-testid="controlSection"]', { + has: page.locator('h6:text-is("Table Sorting")'), + }) + .locator('[aria-label^="Reorder: "]') + ).toHaveAttribute("aria-label", "Reorder: Warning region"); }); test("skip link moves focus to the main content", async ({ page }) => { diff --git a/e2e/tooltip.spec.ts b/e2e/tooltip.spec.ts index aa7d6a99f..f8e72bac7 100644 --- a/e2e/tooltip.spec.ts +++ b/e2e/tooltip.spec.ts @@ -22,7 +22,7 @@ test("should have correct tooltip content", async ({ const filterLocator = selectors.edition.controlSectionByTitle("Filters"); await filterLocator - .getByRole("combobox", { name: "All greenhouse gas" }) + .getByRole("button", { name: /All greenhouse gas/ }) .click(); await selectors.mui