Skip to content
Open
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
1 change: 1 addition & 0 deletions packages/design-toolkit/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -431,6 +431,7 @@
"./hooks/coordinate-field/use-timeout-cleanup": "./dist/hooks/coordinate-field/use-timeout-cleanup.js",
"./hooks/kanban": "./dist/hooks/kanban/index.js",
"./hooks/use-frame-delay": "./dist/hooks/use-frame-delay/index.js",
"./hooks/use-prevent-focus-scroll": "./dist/hooks/use-prevent-focus-scroll/index.js",
"./hooks/use-tree/actions": "./dist/hooks/use-tree/actions/index.js",
"./hooks/use-tree/actions/cache": "./dist/hooks/use-tree/actions/cache.js",
"./hooks/use-tree/state": "./dist/hooks/use-tree/state/index.js",
Expand Down
4 changes: 3 additions & 1 deletion packages/design-toolkit/src/components/checkbox/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import {
composeRenderProps,
useContextProps,
} from 'react-aria-components';
import { usePreventFocusScroll } from '../../hooks/use-prevent-focus-scroll';
import { Icon } from '../icon';
import { CheckboxContext } from './context';
import styles from './styles.module.css';
Expand Down Expand Up @@ -76,13 +77,14 @@ import type { CheckboxProps } from './types';
*/
export function Checkbox({ ref, ...props }: CheckboxProps) {
[props, ref] = useContextProps(props, ref ?? null, CheckboxContext);
const refCallback = usePreventFocusScroll(ref);

const { classNames, children, labelPosition = 'end', ...rest } = props;

return (
<AriaCheckbox
{...rest}
ref={ref}
ref={refCallback}
className={composeRenderProps(classNames?.checkbox, (className) =>
clsx(
'group/checkbox',
Expand Down
4 changes: 3 additions & 1 deletion packages/design-toolkit/src/components/radio/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import {
composeRenderProps,
useContextProps,
} from 'react-aria-components';
import { usePreventFocusScroll } from '../../hooks/use-prevent-focus-scroll';
import { RadioContext } from './context';
import styles from './styles.module.css';
import type { RadioProps } from './types';
Expand All @@ -42,13 +43,14 @@ import type { RadioProps } from './types';
*/
export function Radio({ ref, ...props }: RadioProps) {
[props, ref] = useContextProps(props, ref ?? null, RadioContext);
const refCallback = usePreventFocusScroll(ref);

const { classNames, children, labelPosition = 'end', ...rest } = props;

return (
<AriaRadio
{...rest}
ref={ref}
ref={refCallback}
className={composeRenderProps(classNames?.radio, (className) =>
clsx(
'group/radio',
Expand Down
4 changes: 3 additions & 1 deletion packages/design-toolkit/src/components/switch/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import {
composeRenderProps,
useContextProps,
} from 'react-aria-components';
import { usePreventFocusScroll } from '../../hooks/use-prevent-focus-scroll';
import { SwitchContext } from './context';
import styles from './styles.module.css';
import type { SwitchProps } from './types';
Expand All @@ -43,13 +44,14 @@ import type { SwitchProps } from './types';
*/
export function Switch({ ref, ...props }: SwitchProps) {
[props, ref] = useContextProps(props, ref ?? null, SwitchContext);
const refCallback = usePreventFocusScroll(ref);

const { children, classNames, labelPosition = 'end', ...rest } = props;

return (
<AriaSwitch
{...rest}
ref={ref}
ref={refCallback}
className={composeRenderProps(classNames?.switch, (className) =>
clsx('group/switch', styles.switch, styles[labelPosition], className),
)}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
* governing permissions and limitations under the License.
*/

import { useState } from 'react';
import { Switch } from './';
import type { Meta, StoryObj } from '@storybook/react-vite';

Expand All @@ -34,3 +35,70 @@ type Story = StoryObj<typeof meta>;
export const Default: Story = {
render: Switch,
};

/**
* Regression guard for a scroll-jump bug: toggling a Switch inside a
* scrollable ancestor used to cause the ancestor to scroll to the (1px,
* visually-hidden) a11y input. To verify the fix: scroll the container
* so the switch is roughly centered, then toggle it — the container
* should NOT jump.
*
* Root cause: react-aria's useToggle press handler calls
* inputRef.current.focus() without { preventScroll: true }, so the
* browser's default focus() runs scrollIntoView({ block: 'nearest' }) on
* the hidden 1px input. The fix lives in
* src/hooks/use-prevent-focus-scroll, which patches the hidden input's
* focus method to always pass { preventScroll: true }.
*/
export const ScrollJumpRepro: Story = {
parameters: {
controls: { disable: true },
docs: {
description: {
story:
'Scroll the container so the switch is centered, then toggle it. With the fix applied, the scroll position should hold steady.',
},
},
},
render: () => {
const Filler = ({ count, prefix }: { count: number; prefix: string }) => {
const lines = Array.from(
{ length: count },
(_, i) =>
`${prefix} line ${i + 1} — filler content to make the container scrollable.`,
);
return (
<>
{lines.map((text) => (
<p key={text} style={{ margin: '8px 0' }}>
{text}
</p>
))}
</>
);
};

const ReproContainer = () => {
const [enabled, setEnabled] = useState(false);
return (
<div
style={{
border: '1px solid var(--outline-static, #888)',
height: 320,
overflowY: 'auto',
padding: 16,
width: 480,
}}
>
<Filler count={30} prefix='Above' />
<Switch isSelected={enabled} onChange={setEnabled}>
Toggle me — scroll position should hold
</Switch>
<Filler count={30} prefix='Below' />
</div>
);
};

return <ReproContainer />;
},
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
/*
* Copyright 2026 Hypergiant Galactic Systems Inc. All rights reserved.
* This file is licensed to you under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. You may obtain a copy
* of the License at https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
* OF ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/

import { renderHook } from '@testing-library/react';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { usePreventFocusScroll } from './index';

function createLabelWithInput(): HTMLLabelElement {
const label = document.createElement('label');
const input = document.createElement('input');
input.type = 'checkbox';
label.appendChild(input);
document.body.appendChild(label);
return label;
}

describe('usePreventFocusScroll', () => {
afterEach(() => {
vi.restoreAllMocks();
document.body.innerHTML = '';
});

it('returns a stable callback ref across re-renders', () => {
const { result, rerender } = renderHook(() => usePreventFocusScroll(null));
const first = result.current;

rerender();

expect(result.current).toBe(first);
});

it('forwards the node to an object ref', () => {
const ref: { current: HTMLLabelElement | null } = { current: null };
const { result } = renderHook(() => usePreventFocusScroll(ref));
const node = createLabelWithInput();

result.current(node);

expect(ref.current).toBe(node);
});

it('forwards the node to a function ref', () => {
const fn = vi.fn();
const { result } = renderHook(() =>
usePreventFocusScroll<HTMLLabelElement>(fn),
);
const node = createLabelWithInput();

result.current(node);

expect(fn).toHaveBeenCalledWith(node);
});

it('patches input.focus() to pass preventScroll: true', () => {
const focusSpy = vi.spyOn(HTMLElement.prototype, 'focus');
const node = createLabelWithInput();
const input = node.querySelector('input') as HTMLInputElement;

const { result } = renderHook(() => usePreventFocusScroll(null));
result.current(node);

input.focus();

expect(focusSpy).toHaveBeenCalledWith({ preventScroll: true });
});

it('overrides caller-supplied preventScroll: false to true', () => {
const focusSpy = vi.spyOn(HTMLElement.prototype, 'focus');
const node = createLabelWithInput();
const input = node.querySelector('input') as HTMLInputElement;

const { result } = renderHook(() => usePreventFocusScroll(null));
result.current(node);

input.focus({ preventScroll: false });

expect(focusSpy).toHaveBeenLastCalledWith({ preventScroll: true });
});

it('restores the original focus method when the ref detaches', () => {
const node = createLabelWithInput();
const input = node.querySelector('input') as HTMLInputElement;
const beforePatch = input.focus;

const { result } = renderHook(() => usePreventFocusScroll(null));
result.current(node);
expect(input.focus).not.toBe(beforePatch);

result.current(null);

expect(input.focus).toBe(beforePatch);
});

it('does not throw when the label has no input child', () => {
const label = document.createElement('label');
document.body.appendChild(label);
const { result } = renderHook(() => usePreventFocusScroll(null));

expect(() => result.current(label)).not.toThrow();
});

it('does not throw when given null', () => {
const { result } = renderHook(() => usePreventFocusScroll(null));

expect(() => result.current(null)).not.toThrow();
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
/*
* Copyright 2026 Hypergiant Galactic Systems Inc. All rights reserved.
* This file is licensed to you under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. You may obtain a copy
* of the License at https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
* OF ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/

import { useCallback, useRef } from 'react';
import type { Ref, RefCallback } from 'react';

/**
* Returns a ref callback that forwards to the given external ref AND patches
* the contained `<input>`'s `focus()` method to always pass
* `{ preventScroll: true }`.
*
* Why: react-aria-components renders a visually-hidden a11y `<input>` inside
* Switch / Checkbox / Radio, and on press its `usePress` handler calls
* `inputRef.current.focus()` to forward keyboard focus. The browser's default
* `focus()` runs `scrollIntoView({ block: 'nearest' })`, which causes any
* scrollable ancestor to jump toward the 1×1 hidden input. Passing
* `preventScroll: true` is the standard escape hatch and is what react-aria's
* own `focusWithoutScrolling` utility uses elsewhere — useToggle / useRadio /
* useRadioGroup just don't route through it.
*
* Track upstream: adobe/react-spectrum should change those press handlers to
* use `focusWithoutScrolling`; once that ships, this hook can be removed.
*/
export function usePreventFocusScroll<T extends HTMLElement>(
externalRef?: Ref<T> | null,
): RefCallback<T> {
const externalRefHolder = useRef(externalRef);
externalRefHolder.current = externalRef;

const restoreRef = useRef<(() => void) | null>(null);

return useCallback((node: T | null) => {
restoreRef.current?.();
restoreRef.current = null;

const ext = externalRefHolder.current;
if (typeof ext === 'function') {
ext(node);
} else if (ext && typeof ext === 'object') {
(ext as React.RefObject<T | null>).current = node;
}

if (!node) {
return;
}

const input = node.querySelector('input');
if (!input) {
return;
}

const hadOwnFocus = Object.hasOwn(input, 'focus');
const original = input.focus;

input.focus = function (options?: FocusOptions) {
return original.call(this, { ...options, preventScroll: true });
};

restoreRef.current = () => {
if (hadOwnFocus) {
input.focus = original;
} else {
delete (input as { focus?: typeof original }).focus;
}
};
}, []);
}
1 change: 1 addition & 0 deletions packages/design-toolkit/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -684,6 +684,7 @@ export type {
UseFrameDelayOptions,
UseFrameDelayResult,
} from './hooks/use-frame-delay';
export { usePreventFocusScroll } from './hooks/use-prevent-focus-scroll';
export { useTreeActions } from './hooks/use-tree/actions';
export { useTreeState } from './hooks/use-tree/state';
export type {
Expand Down