From 1036238583829b2ff95e1a79cc9936f9bbb9fcea Mon Sep 17 00:00:00 2001 From: Bartosz Prusinowski Date: Thu, 12 Nov 2026 18:26:25 +0100 Subject: [PATCH 01/11] fix: Keyboard access to menus, confirmation dialogs and the add chart popover --- app/components/action-menu.spec.tsx | 118 +++++++++++++ app/components/action-menu.tsx | 60 +++++++ app/components/arrow-menu.tsx | 18 +- app/components/chart-selection-tabs.tsx | 42 +++-- app/components/chart-shared.spec.tsx | 1 + app/components/chart-shared.tsx | 3 + app/components/confirmation-dialog.tsx | 21 ++- app/components/dashboard-shared.tsx | 72 ++++---- app/components/menu-action-item.tsx | 216 +++++++++++++----------- app/components/rename-dialog.tsx | 2 +- app/components/row-actions.tsx | 20 ++- app/login/components/login-menu.tsx | 11 +- app/login/components/profile-tables.tsx | 2 +- app/utils/focus-first.ts | 3 + 14 files changed, 421 insertions(+), 168 deletions(-) create mode 100644 app/components/action-menu.spec.tsx create mode 100644 app/components/action-menu.tsx create mode 100644 app/utils/focus-first.ts diff --git a/app/components/action-menu.spec.tsx b/app/components/action-menu.spec.tsx new file mode 100644 index 0000000000..5add9d088f --- /dev/null +++ b/app/components/action-menu.spec.tsx @@ -0,0 +1,118 @@ +import { + cleanup, + fireEvent, + render, + screen, + waitFor, +} from "@testing-library/react"; +import { ReactNode, useState } from "react"; +import { afterEach, describe, expect, it, vi } from "vitest"; + +import { ActionMenu } from "@/components/action-menu"; +import { MenuActionItem } from "@/components/menu-action-item"; + +vi.mock("@lingui/macro", () => ({ + Trans: ({ children }: { children: ReactNode }) => children, + t: ({ message }: { message: string }) => message, +})); + +afterEach(cleanup); + +const WrappedItem = ({ label }: { label: string }) => { + return ( + {}} + /> + ); +}; + +const TestMenu = ({ + onDelete, + onParentClick, +}: { + onDelete: () => void; + onParentClick: () => void; +}) => { + const [anchor, setAnchor] = useState(null); + + return ( +
+ + setAnchor(null)} + transitionDuration={0} + > + + + + +
+ ); +}; + +const renderMenu = () => { + const onDelete = vi.fn(); + const onParentClick = vi.fn(); + render(); + fireEvent.click(screen.getByRole("button", { name: "Open" })); + onParentClick.mockClear(); + + return { onDelete, onParentClick }; +}; + +describe("ActionMenu", () => { + it("focuses the first item even when items are wrapped in components", () => { + renderMenu(); + + expect(document.activeElement).toBe( + screen.getByRole("menuitem", { name: "Duplicate" }) + ); + }); + + it("moves focus between items with the arrow keys", () => { + renderMenu(); + fireEvent.keyDown(document.activeElement!, { key: "ArrowDown" }); + + expect(document.activeElement).toBe( + screen.getByRole("menuitem", { name: "Export" }) + ); + }); + + it("renders the confirmation outside the closed menu", async () => { + const { onDelete, onParentClick } = renderMenu(); + fireEvent.click(screen.getByRole("menuitem", { name: "Delete" })); + + expect(screen.getByRole("dialog", { name: "Delete chart?" })).toBeTruthy(); + expect(onParentClick).not.toHaveBeenCalled(); + await waitFor(() => { + expect(screen.queryByRole("menu", { hidden: true })).toBeNull(); + }); + + fireEvent.click(screen.getByRole("button", { name: "Yes" })); + + expect(onDelete).toHaveBeenCalledTimes(1); + }); + + it("keeps the menu closed when the confirmation is cancelled", async () => { + const { onDelete } = renderMenu(); + fireEvent.click(screen.getByRole("menuitem", { name: "Delete" })); + fireEvent.click(screen.getByRole("button", { name: "No" })); + + expect(onDelete).not.toHaveBeenCalled(); + await waitFor(() => { + expect(screen.queryByRole("menu", { hidden: true })).toBeNull(); + }); + }); +}); diff --git a/app/components/action-menu.tsx b/app/components/action-menu.tsx new file mode 100644 index 0000000000..134221a92f --- /dev/null +++ b/app/components/action-menu.tsx @@ -0,0 +1,60 @@ +import { Menu, MenuProps } from "@mui/material"; +import { createContext, MouseEvent, useContext, useState } from "react"; + +import { + ConfirmationDialog, + ConfirmationRequest, +} from "@/components/confirmation-dialog"; +import { focusFirst } from "@/utils/focus-first"; + +const MENU_ITEM_SELECTOR = '[role^="menuitem"]:not([aria-disabled="true"])'; + +const RequestConfirmationContext = createContext< + ((request: ConfirmationRequest) => void) | undefined +>(undefined); + +export const useRequestConfirmation = () => { + return useContext(RequestConfirmationContext); +}; + +export const ActionMenu = ({ + open, + onClose, + TransitionProps, + ...props +}: MenuProps) => { + const [request, setRequest] = useState(); + + return ( + + { + focusFirst(node, MENU_ITEM_SELECTOR); + TransitionProps?.onEntering?.(node, isAppearing); + }, + }} + {...props} + /> + {request ? ( + { + setRequest(undefined); + onClose?.(event, reason); + }} + /> + ) : null} + + ); +}; + +const stopPropagation = (e: MouseEvent) => { + e.stopPropagation(); +}; diff --git a/app/components/arrow-menu.tsx b/app/components/arrow-menu.tsx index da2151d4f6..594a741997 100644 --- a/app/components/arrow-menu.tsx +++ b/app/components/arrow-menu.tsx @@ -1,4 +1,6 @@ -import { Menu, paperClasses, styled } from "@mui/material"; +import { paperClasses, Popover, styled } from "@mui/material"; + +import { ActionMenu } from "@/components/action-menu"; const commonBeforeStyles: Partial = { content: '" "', @@ -11,7 +13,7 @@ const commonBeforeStyles: Partial = { transform: "rotate(45deg)", }; -export const ArrowMenuTopCenter = styled(Menu)({ +const topCenterStyles = { [`& .${paperClasses.root}`]: { overflow: "visible", "&:before": { @@ -21,9 +23,13 @@ export const ArrowMenuTopCenter = styled(Menu)({ right: 0, }, }, -}); +}; + +export const ArrowMenuTopCenter = styled(ActionMenu)(topCenterStyles); + +export const ArrowPopoverTopCenter = styled(Popover)(topCenterStyles); -export const ArrowMenuBottomCenter = styled(Menu)({ +export const ArrowMenuBottomCenter = styled(ActionMenu)({ [`& .${paperClasses.root}`]: { overflow: "visible", "&:before": { @@ -35,7 +41,7 @@ export const ArrowMenuBottomCenter = styled(Menu)({ }, }); -export const ArrowMenuTopBottom = styled(Menu)({ +export const ArrowMenuTopBottom = styled(ActionMenu)({ [`& .${paperClasses.root}`]: { overflow: "visible", "&:before": { @@ -47,7 +53,7 @@ export const ArrowMenuTopBottom = styled(Menu)({ }, }); -export const ArrowMenuBottomTop = styled(Menu)({ +export const ArrowMenuBottomTop = styled(ActionMenu)({ [`& .${paperClasses.root}`]: { overflow: "visible", "&:before": { diff --git a/app/components/chart-selection-tabs.tsx b/app/components/chart-selection-tabs.tsx index 6a95931446..f205a05d2b 100644 --- a/app/components/chart-selection-tabs.tsx +++ b/app/components/chart-selection-tabs.tsx @@ -23,7 +23,10 @@ import { import { DragDropContext, Draggable, Droppable } from "react-beautiful-dnd"; import { AddButton } from "@/components/add-button"; -import { ArrowMenuTopCenter } from "@/components/arrow-menu"; +import { + ArrowMenuTopCenter, + ArrowPopoverTopCenter, +} from "@/components/arrow-menu"; import { DuplicateChartMenuActionItem } from "@/components/chart-shared"; import { DragHandle } from "@/components/drag-handle"; import { Flex } from "@/components/flex"; @@ -44,9 +47,11 @@ import { } from "@/configurator"; import { useSearchDatasetPanelStore } from "@/configurator/components/add-new-dataset-panel"; import { ChartTypeSelector } from "@/configurator/components/chart-type-selector"; +import { getFieldLabel } from "@/configurator/components/field-i18n"; import { getIconName } from "@/configurator/components/ui-helpers"; -import { Icon, IconName } from "@/icons"; +import { Icon } from "@/icons"; import { useLocale } from "@/locales"; +import { focusFirst } from "@/utils/focus-first"; import { useEvent } from "@/utils/use-event"; type TabsState = { @@ -186,7 +191,7 @@ const TabsEditable = (props: TabsEditableProps) => { /> {tabsState.popoverType === "add" ? ( - { vertical: "top", }} onClose={handleClose} + TransitionProps={{ + onEntering: (node) => focusFirst(node, "button:not(:disabled)"), + }} PaperProps={{ + role: "dialog", + "aria-label": t({ + id: "chart-selection-tabs.add-chart", + message: "Add chart", + }), sx: { width: "calc(320px + 2rem)", mt: 3, py: "1rem", - "& > .MuiList-root": { - py: 0, - }, + boxShadow: 4, }, }} > @@ -250,7 +261,7 @@ const TabsEditable = (props: TabsEditableProps) => { - + ) : null} {tabsState.popoverType === "edit" ? ( @@ -496,7 +507,7 @@ const TabsInner = ({ }} label={ void; }) => { const { - iconName, + chartType, chartKey, editable, draggable, @@ -639,6 +650,9 @@ const TabContent = (props: { - ); - } + ) : ( + + )} + {confirmation && !requestConfirmation ? ( + + ) : null} + + ); +}; - return ( - <> +const ActionMenuItem = ({ + label, + leadingIconName, + trailingIconName, + color, + disabled, + linkProps, + onClick, +}: Pick< + MenuActionProps, + "label" | "leadingIconName" | "trailingIconName" | "color" | "disabled" +> & { + linkProps?: { href: string; target?: string; rel?: string }; + onClick: (e: MouseEvent) => void; +}) => { + const content = ( + <> + {leadingIconName && } + {label} + {trailingIconName && ( + + )} + + ); + + return ( + <> + {linkProps ? ( - {leadingIcon && } - {label} - {trailingIcon && ( - - )} + {content} + + ) : ( + + {content} - - - ); - }; - - return ( - <> - {props.type === "link" ? ( - - - - ) : props.type === "button" ? ( - - ) : null} - {props.type === "button" && props.requireConfirmation && ( - )} + ); }; + +const MenuItemLink = forwardRef>( + (props, ref) => +); diff --git a/app/components/rename-dialog.tsx b/app/components/rename-dialog.tsx index c73389b1d8..caf7036ba1 100644 --- a/app/components/rename-dialog.tsx +++ b/app/components/rename-dialog.tsx @@ -87,7 +87,7 @@ export const RenameDialog = ({ : config.data.layout.meta; return ( - +
diff --git a/app/components/row-actions.tsx b/app/components/row-actions.tsx index 0b997dbd50..490d1ab628 100644 --- a/app/components/row-actions.tsx +++ b/app/components/row-actions.tsx @@ -1,3 +1,4 @@ +import { t } from "@lingui/macro"; import { IconButton } from "@mui/material"; import { Flex } from "@/components/flex"; @@ -5,7 +6,13 @@ import { MenuActionItem, MenuActionProps } from "@/components/menu-action-item"; import { useFlipMenu } from "@/components/use-flip-menu"; import { Icon } from "@/icons"; -export const RowActions = ({ actions }: { actions: MenuActionProps[] }) => { +export const RowActions = ({ + actions, + label, +}: { + actions: MenuActionProps[]; + label: string; +}) => { const [primaryAction, ...otherActions] = actions; const { buttonRef, @@ -22,7 +29,16 @@ export const RowActions = ({ actions }: { actions: MenuActionProps[] }) => { return ( - + { {user.name} - { await signOut({ callbackUrl: "/api/auth/signout" }) } /> - + -
+ ); }; diff --git a/app/login/components/profile-tables.tsx b/app/login/components/profile-tables.tsx index adb900953f..95c6093469 100644 --- a/app/login/components/profile-tables.tsx +++ b/app/login/components/profile-tables.tsx @@ -433,7 +433,7 @@ const ProfileVisualizationsRow = ({ })} - + { + node.querySelector(selector)?.focus(); +}; From ec239c3d7433e19a40e3cd08824841cb2c5cd157 Mon Sep 17 00:00:00 2001 From: Bartosz Prusinowski Date: Thu, 12 Nov 2026 18:26:25 +0100 Subject: [PATCH 02/11] fix: Keyboard operable time sliders and time range brush --- app/charts/shared/brush/index.tsx | 177 +++++++++++------- .../dashboard-interactive-filters.tsx | 62 +++--- .../interactive-filters/editor-brush.tsx | 2 +- .../interactive-filters/time-slider.tsx | 36 ++-- app/utils/observables.spec.ts | 16 ++ app/utils/observables.ts | 25 +++ e2e/time-slider.spec.ts | 24 +++ 7 files changed, 237 insertions(+), 105 deletions(-) diff --git a/app/charts/shared/brush/index.tsx b/app/charts/shared/brush/index.tsx index a55b5a5199..e193237500 100644 --- a/app/charts/shared/brush/index.tsx +++ b/app/charts/shared/brush/index.tsx @@ -1,5 +1,5 @@ +import { t } from "@lingui/macro"; import { useEventCallback } from "@mui/material"; -import { bisector } from "d3-array"; import { BrushSelection, brushX } from "d3-brush"; import { pointer, pointers, select, Selection } from "d3-selection"; import { Transition } from "d3-transition"; @@ -17,11 +17,7 @@ import type { import { useChartState } from "@/charts/shared/chart-state"; import { useChartTheme } from "@/charts/shared/use-chart-theme"; import { DashboardTimeRangeFilter } from "@/configurator"; -import { - Observation, - TemporalDimension, - TemporalEntityDimension, -} from "@/domain/data"; +import { TemporalDimension, TemporalEntityDimension } from "@/domain/data"; import { useTimeFormatUnit } from "@/formatters"; import { useChartInteractiveFilters, @@ -35,6 +31,17 @@ const HANDLE_HEIGHT = 12; const BRUSH_HEIGHT = 4; const HEIGHT = HANDLE_HEIGHT + BRUSH_HEIGHT; +const BRUSH_KEYS = [ + "ArrowLeft", + "ArrowDown", + "ArrowRight", + "ArrowUp", + "Home", + "End", +] as const; + +type BrushKey = (typeof BRUSH_KEYS)[number]; + export const shouldShowBrush = ( interactiveFiltersConfig: { timeRange: { active: boolean } }, dashboardTimeRange: DashboardTimeRangeFilter | undefined @@ -221,67 +228,36 @@ export const BrushTime = ({ yOffset }: { yOffset?: number }) => { } }); - /** Keyboard support */ - const moveBrushOnKeyPress = useCallback( - (event: $FixMe, handleDirection: "w" | "e") => { - if (from && to) { - updateBrushEndedStatus(false); + const dates = useMemo(() => { + return Array.from(new Set(fullData.map((d) => getDate(d).getTime()))) + .sort((a, b) => a - b) + .map((d) => new Date(d)); + }, [fullData, getDate]); - const bisectDateLeft = bisector( - (ds: Observation, date: Date) => - getDate(ds).getTime() - date.getTime() - ).left; - const bisectDateRight = bisector( - (ds: Observation, date: Date) => - getDate(ds).getTime() - date.getTime() - ).right; - - if (event.keyCode === 37 && handleDirection === "w") { - // west handle, moving left - const index = bisectDateLeft(fullData, from, 1); - const indexLeft = fullData[index - 1]; - - if (getDate(indexLeft).getTime() < to.getTime()) { - // new lower than "to" - setTimeRange(getDate(indexLeft), to); - } else { - // new too high, don't do anything - setTimeRange(from, to); - } - } else if (event.keyCode === 39 && handleDirection === "w") { - // west handle, moving right - const index = bisectDateRight(fullData, from, 1); - const indexRight = fullData[index]; - if (getDate(indexRight).getTime() < to.getTime()) { - setTimeRange(getDate(indexRight), to); - } else { - setTimeRange(from, to); - } - } else if (event.keyCode === 37 && handleDirection === "e") { - // east handle, moving left - const index = bisectDateLeft(fullData, to, 1); - const indexLeft = fullData[index - 1]; - - if (getDate(indexLeft).getTime() > from.getTime()) { - setTimeRange(from, getDate(indexLeft)); - } else { - setTimeRange(from, to); - } - } else if (event.keyCode === 39 && handleDirection === "e") { - // east handle, moving right - const index = bisectDateRight(fullData, to, 1); - const indexLeft = fullData[index]; - - if (indexLeft && getDate(indexLeft).getTime() > from.getTime()) { - setTimeRange(from, getDate(indexLeft)); - } else { - setTimeRange(from, to); - } - } - updateBrushEndedStatus(true); + const moveBrushOnKeyDown = useEventCallback( + (event: KeyboardEvent, handle: "w" | "e") => { + if (!isBrushKey(event.key) || !ref.current) { + return; } - }, - [fullData, setTimeRange, from, getDate, to] + + const fromIndex = getDateIndex(dates, closestFrom); + const toIndex = getDateIndex(dates, closestTo); + const [min, max, index] = + handle === "w" + ? [0, toIndex - 1, fromIndex] + : [fromIndex + 1, dates.length - 1, toIndex]; + const newIndex = getKeyboardIndex({ key: event.key, index, min, max }); + + event.preventDefault(); + const [newFrom, newTo] = + handle === "w" + ? [dates[newIndex], closestTo] + : [closestFrom, dates[newIndex]]; + select(ref.current).call(brush.move, [ + brushWidthScale(newFrom), + brushWidthScale(newTo), + ]); + } ); useEffect(() => { @@ -329,10 +305,12 @@ export const BrushTime = ({ yOffset }: { yOffset?: number }) => { g.select(".handle--w") .attr("tabindex", 0) - .on("keydown", (e: $FixMe) => moveBrushOnKeyPress(e, "w")); + .attr("role", "slider") + .on("keydown", (e: KeyboardEvent) => moveBrushOnKeyDown(e, "w")); g.select(".handle--e") .attr("tabindex", 0) - .on("keydown", (e: $FixMe) => moveBrushOnKeyPress(e, "e")); + .attr("role", "slider") + .on("keydown", (e: KeyboardEvent) => moveBrushOnKeyDown(e, "e")); }; g.call(mkBrush); @@ -344,10 +322,38 @@ export const BrushTime = ({ yOffset }: { yOffset?: number }) => { brushHandleStrokeColor, brushOverlayColor, brushSelectionColor, - moveBrushOnKeyPress, + moveBrushOnKeyDown, selectionExtent, ]); + useEffect(() => { + if (!ref.current || !closestFrom || !closestTo) { + return; + } + + const g = select(ref.current); + const handles = [ + { + selector: ".handle--w", + label: t({ id: "controls.filters.select.from", message: "From" }), + date: closestFrom, + }, + { + selector: ".handle--e", + label: t({ id: "controls.filters.select.to", message: "To" }), + date: closestTo, + }, + ]; + handles.forEach(({ selector, label, date }) => { + g.select(selector) + .attr("aria-label", label) + .attr("aria-valuemin", 0) + .attr("aria-valuemax", dates.length - 1) + .attr("aria-valuenow", getDateIndex(dates, date)) + .attr("aria-valuetext", formatDate(date)); + }); + }); + // This effect allows "snapping" to actual data points // after brush is ended and interactive-filters state is updated const closestFromStr = closestFrom?.toString(); // Local variables to prevent eslint-plugin-react-hooks bug @@ -433,6 +439,41 @@ export const BrushTime = ({ yOffset }: { yOffset?: number }) => { ) : null; }; +const getDateIndex = (dates: Date[], date: Date) => { + return dates.findIndex((d) => d.getTime() === date.getTime()); +}; + +const isBrushKey = (key: string): key is BrushKey => + BRUSH_KEYS.some((brushKey) => brushKey === key); + +const getKeyboardIndex = ({ + key, + index, + min, + max, +}: { + key: BrushKey; + index: number; + min: number; + max: number; +}) => { + switch (key) { + case "ArrowLeft": + case "ArrowDown": + return Math.max(min, index - 1); + case "ArrowRight": + case "ArrowUp": + return Math.min(max, index + 1); + case "Home": + return min; + case "End": + return max; + default: + const _exhaustiveCheck: never = key; + return _exhaustiveCheck; + } +}; + // Unused BrushOrdinal // export const BrushOrdinal = ({ debug = false }: { debug?: boolean }) => { diff --git a/app/components/dashboard-interactive-filters.tsx b/app/components/dashboard-interactive-filters.tsx index 30b1141e6d..e5a8ff7abf 100644 --- a/app/components/dashboard-interactive-filters.tsx +++ b/app/components/dashboard-interactive-filters.tsx @@ -1,3 +1,4 @@ +import { t } from "@lingui/macro"; import { Box, BoxProps, @@ -8,6 +9,7 @@ import { } from "@mui/material"; import { Theme } from "@mui/material/styles"; import { makeStyles } from "@mui/styles"; +import { bisectLeft } from "d3-array"; import uniq from "lodash/uniq"; import { ChangeEvent, useEffect, useMemo, useRef, useState } from "react"; @@ -213,43 +215,57 @@ const DashboardTimeRangeSlider = ({ 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 (!min || !max) { - return; - } - - return [ - toUnixSeconds(parseDate(min as string)), - toUnixSeconds(parseDate(max as string)), - ]; + const markValues = useMemo(() => { + return combinedTemporalDimension.values.map(({ value }) => + toUnixSeconds(parseDate(value as string)) + ); }, [combinedTemporalDimension]); + const formatIndex = (index: number) => valueLabelFormat(markValues[index]); - if (!timeRange || !filter.active || !sliderRange) { + if (!timeRange || !filter.active || markValues.length === 0) { return null; } return ( handleChangeSlider(value)} + onChange={(_ev, value) => { + handleChangeSlider( + (Array.isArray(value) ? value : [value]).map((i) => markValues[i]) + ); + }} onChangeCommitted={() => setEnableTransition(true)} - valueLabelFormat={valueLabelFormat} - step={null} - min={sliderRange[0]} - max={sliderRange[1]} + getAriaLabel={(index) => + index === 0 + ? t({ id: "controls.filters.select.from", message: "From" }) + : t({ id: "controls.filters.select.to", message: "To" }) + } + getAriaValueText={formatIndex} + valueLabelFormat={formatIndex} + step={1} + min={0} + max={markValues.length - 1} valueLabelDisplay={mountedForSomeTime ? "on" : "off"} - value={timeRange} - marks={combinedTemporalDimension.values.map(({ value }) => ({ - value: toUnixSeconds(parseDate(value as string)), - }))} + value={timeRange.map((value) => getClosestIndex(markValues, value))} + marks={markValues.map((_, i) => ({ value: i }))} /> ); }; +const getClosestIndex = (values: number[], value: number) => { + const i = bisectLeft(values, value); + + if (i === 0) { + return 0; + } + + if (i === values.length) { + return values.length - 1; + } + + return value - values[i - 1] < values[i] - value ? i - 1 : i; +}; + const useDataFilterStyles = makeStyles((theme: Theme) => ({ wrapper: { display: "grid", diff --git a/app/configurator/interactive-filters/editor-brush.tsx b/app/configurator/interactive-filters/editor-brush.tsx index c6f888baff..a8975b6110 100644 --- a/app/configurator/interactive-filters/editor-brush.tsx +++ b/app/configurator/interactive-filters/editor-brush.tsx @@ -116,7 +116,7 @@ export const EditorBrush = ({
{width > 0 && ( - + { return ( - + ); }; -const Root = ({ showPlayButton }: { showPlayButton: boolean }) => { +const Root = ({ + showPlayButton, + label, +}: { + showPlayButton: boolean; + label: string; +}) => { const timeline = useTimeline(); const [min, max] = timeline.formattedExtent; @@ -171,7 +178,7 @@ const Root = ({ showPlayButton }: { showPlayButton: boolean }) => { > {showPlayButton && }
- + { return (
@@ -495,6 +512,13 @@ const LinkDialog = () => { className={classes.popper} open={state.type !== "inactive"} anchorEl={editorRootElementRef?.current} + role="dialog" + aria-label={ + maybeDelayedState.type === "edit" + ? t({ id: "mdx-editor.link-dialog.edit", message: "Edit link" }) + : t({ id: "mdx-editor.link-dialog.preview", message: "Link" }) + } + disablePortal transition sx={{ top: `${(rectangle?.top ?? 0) + (rectangle?.height ?? 0) + 4}px !important`, @@ -505,12 +529,16 @@ const LinkDialog = () => { {maybeDelayedState.type === "edit" && ( - + +
+ +
+
)} {maybeDelayedState.type === "preview" && ( <> @@ -529,6 +557,10 @@ const LinkDialog = () => { ) : null} { switchFromPreviewToLinkEdit(); }} diff --git a/app/components/mdx-editor/list-toggles.tsx b/app/components/mdx-editor/list-toggles.tsx index b324395b5a..2ca4fccaea 100644 --- a/app/components/mdx-editor/list-toggles.tsx +++ b/app/components/mdx-editor/list-toggles.tsx @@ -1,3 +1,4 @@ +import { t } from "@lingui/macro"; import { applyListType$, currentListType$ } from "@mdxeditor/editor"; import { useCellValues, usePublisher } from "@mdxeditor/gurx"; @@ -7,9 +8,11 @@ import { Icon, IconName } from "@/icons"; const ListTypeButton = ({ listType, iconName, + label, }: { listType: "bullet" | "number"; iconName: IconName; + label: string; }) => { const [currentListType] = useCellValues(currentListType$); const applyListType = usePublisher(applyListType$); @@ -17,15 +20,11 @@ const ListTypeButton = ({ return ( { applyListType(active ? "" : listType); }} - sx={{ - backgroundColor: active ? "grey.300" : "transparent", - "&:hover": { - backgroundColor: active ? "grey.300" : "grey.200", - }, - }} > @@ -35,8 +34,22 @@ const ListTypeButton = ({ export const ListToggles = () => { return ( <> - - + + ); }; diff --git a/app/components/mdx-editor/tab-navigation-plugin.tsx b/app/components/mdx-editor/tab-navigation-plugin.tsx new file mode 100644 index 0000000000..77d1c2e66b --- /dev/null +++ b/app/components/mdx-editor/tab-navigation-plugin.tsx @@ -0,0 +1,14 @@ +import { createRootEditorSubscription$, realmPlugin } from "@mdxeditor/editor"; +import { COMMAND_PRIORITY_CRITICAL, KEY_TAB_COMMAND } from "lexical"; + +export const tabNavigationPlugin = realmPlugin({ + init: (realm) => { + realm.pub(createRootEditorSubscription$, (editor) => { + return editor.registerCommand( + KEY_TAB_COMMAND, + () => true, + COMMAND_PRIORITY_CRITICAL + ); + }); + }, +}); diff --git a/app/components/mdx-editor/toolbar-buttons.spec.tsx b/app/components/mdx-editor/toolbar-buttons.spec.tsx new file mode 100644 index 0000000000..c9b522fd43 --- /dev/null +++ b/app/components/mdx-editor/toolbar-buttons.spec.tsx @@ -0,0 +1,50 @@ +import { cleanup, fireEvent, render, screen } from "@testing-library/react"; +import { afterEach, describe, expect, it } from "vitest"; + +import { ToolbarButtons } from "@/components/mdx-editor/toolbar-buttons"; + +afterEach(cleanup); + +const renderToolbar = () => { + render( + + + + + + ); + + return ["Bold", "Italic", "Underline"].map((name) => + screen.getByRole("button", { name }) + ); +}; + +describe("ToolbarButtons", () => { + it("keeps a single tab stop", () => { + const buttons = renderToolbar(); + + expect(buttons.map((b) => b.tabIndex)).toEqual([0, -1, -1]); + }); + + it("moves focus with arrow keys, Home and End", () => { + const [bold, italic, underline] = renderToolbar(); + bold.focus(); + + fireEvent.keyDown(bold, { key: "ArrowRight" }); + expect(document.activeElement).toBe(italic); + expect(italic.tabIndex).toBe(0); + expect(bold.tabIndex).toBe(-1); + + fireEvent.keyDown(italic, { key: "End" }); + expect(document.activeElement).toBe(underline); + + fireEvent.keyDown(underline, { key: "ArrowRight" }); + expect(document.activeElement).toBe(bold); + + fireEvent.keyDown(bold, { key: "ArrowLeft" }); + expect(document.activeElement).toBe(underline); + + fireEvent.keyDown(underline, { key: "Home" }); + expect(document.activeElement).toBe(bold); + }); +}); diff --git a/app/components/mdx-editor/toolbar-buttons.tsx b/app/components/mdx-editor/toolbar-buttons.tsx new file mode 100644 index 0000000000..6abeee2382 --- /dev/null +++ b/app/components/mdx-editor/toolbar-buttons.tsx @@ -0,0 +1,73 @@ +import { FocusEvent, KeyboardEvent, ReactNode, useEffect, useRef } from "react"; + +import { Flex } from "@/components/flex"; + +const KEY_TO_INDEX: Record< + string, + ((index: number, count: number) => number) | undefined +> = { + ArrowRight: (index, count) => (index + 1) % count, + ArrowLeft: (index, count) => (index - 1 + count) % count, + Home: () => 0, + End: (_, count) => count - 1, +}; + +export const ToolbarButtons = ({ children }: { children: ReactNode }) => { + const ref = useRef(null); + const activeIndexRef = useRef(0); + + useEffect(() => { + if (ref.current) { + setRovingTabIndex(getButtons(ref.current), activeIndexRef.current); + } + }); + + const handleFocus = (e: FocusEvent) => { + const buttons = getButtons(e.currentTarget); + const index = buttons.findIndex( + (button) => button === document.activeElement + ); + + if (index !== -1) { + activeIndexRef.current = index; + setRovingTabIndex(buttons, index); + } + }; + + const handleKeyDown = (e: KeyboardEvent) => { + const buttons = getButtons(e.currentTarget); + const index = buttons.findIndex( + (button) => button === document.activeElement + ); + const getNextIndex = KEY_TO_INDEX[e.key]; + + if (index === -1 || !getNextIndex) { + return; + } + + e.preventDefault(); + buttons[getNextIndex(index, buttons.length)].focus(); + }; + + return ( + + {children} + + ); +}; + +const getButtons = (container: HTMLElement) => { + return Array.from( + container.querySelectorAll("button:not(:disabled)") + ); +}; + +const setRovingTabIndex = ( + buttons: HTMLButtonElement[], + activeIndex: number +) => { + const index = Math.min(activeIndex, buttons.length - 1); + buttons.forEach((button, i) => { + button.tabIndex = i === index ? 0 : -1; + }); +}; diff --git a/app/configurator/components/chart-annotations/chart-annotations-selector.tsx b/app/configurator/components/chart-annotations/chart-annotations-selector.tsx index 73a20a48c4..802e0042a9 100644 --- a/app/configurator/components/chart-annotations/chart-annotations-selector.tsx +++ b/app/configurator/components/chart-annotations/chart-annotations-selector.tsx @@ -196,12 +196,18 @@ export const ChartAnnotationsSelector = () => { - + { id: "controls.fill-and-text", message: "Fill and text box", })} + name={`annotation-${annotation.key}-style`} value="filled" checked={annotation.highlightType === "filled"} disabled={!hasTargets} @@ -344,7 +351,7 @@ const AnnotationDrawer = ({ } return ( - +
(); const handleOpenCreateColorPalette: MouseEventHandler = useEvent( (e) => { @@ -224,10 +226,11 @@ export const ColorPalette = ({ }} >
-