Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions packages/react-aria-components/stories/TokenField.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -284,6 +284,23 @@ export const TagField: TokenFieldStory = () => {
);
};

export const ScrollableTagField: TokenFieldStory = TagField.bind({});
ScrollableTagField.decorators = [
Story => (
<div
ref={element => {
if (element) {
element.scrollTop = 450;
}
}}
style={{height: 180, overflow: 'auto', marginTop: 200}}>
<div style={{height: 500}} />
<Story />
<div style={{height: 500}} />
</div>
)
];

export const Search: TokenFieldStory = () => {
let inputRef = useRef(null);
let [value, setValue] = useState(
Expand Down
155 changes: 155 additions & 0 deletions packages/react-aria-components/test/TokenField.scroll.browser.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,155 @@
/*
* Copyright 2026 Adobe. 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 http://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 {describe, expect, it} from 'vitest';
import React from 'react';
import {render} from 'vitest-browser-react';
import {Token, TokenField, TokenInput} from '../src/TokenField';
import {TokenFieldSegment, TokenFieldValue} from 'react-stately/useTokenFieldState';
import {userEvent} from 'vitest/browser';

// The tag-field example converts a trailing delimiter into a token with no text after it.
class TagFieldValue extends TokenFieldValue {
tokenize(text: string): TokenFieldSegment[] {
let parts = text.split(/[, \n]/);
let segments: TokenFieldSegment[] = parts.map((part, index) => {
if (index === parts.length - 1 || part.length === 0) {
return {type: 'text', text: part};
}
return {type: 'token', text: part};
});

if (parts.at(-1)?.length === 0) {
segments.pop();
}
return segments;
}

toString(): string {
return this.segments.map(segment => segment.text).join(', ');
}
}

const describeOrSkip = parseInt(React.version, 10) < 19 ? describe.skip : describe;

describeOrSkip('TokenField scrolling', () => {
it.each([
{dir: 'ltr', delimiter: 'Enter', key: '{Enter}'},
{dir: 'rtl', delimiter: 'Enter', key: '{Enter}'},
{dir: 'ltr', delimiter: 'comma', key: ','},
{dir: 'rtl', delimiter: 'comma', key: ','}
] as const)(
'keeps a visible tag field in place after $delimiter and Backspace ($dir)',
async ({dir, key}) => {
let screen = await render(
<div
data-testid="scroller"
dir={dir}
style={{height: 180, overflow: 'auto', marginTop: 200}}>
<div style={{height: 500}} />
<TokenField aria-label="Tags" allowsNewlines defaultValue={new TagFieldValue([])}>
<TokenInput style={{minHeight: 30}}>
{segment => <Token>{segment.text}</Token>}
</TokenInput>
</TokenField>
<div style={{height: 500}} />
</div>
);
let scroller = screen.getByTestId('scroller').element();
let input = screen.getByRole('textbox', {name: 'Tags'});
scroller.scrollTop = 450;
await userEvent.click(input);
await userEvent.keyboard('Design');
let scrollTop = scroller.scrollTop;
expect(scrollTop).toBeGreaterThan(0);

await userEvent.keyboard(key);
await expect.element(input).toHaveTextContent('Design');
expect(input.element().querySelector('[data-react-aria-token]')).not.toBeNull();
expect(scroller.scrollTop).toBe(scrollTop);

await userEvent.keyboard('x{Backspace}');
await expect.element(input).toHaveTextContent('Design');
expect(scroller.scrollTop).toBe(scrollTop);
await expect.element(input).toHaveFocus();

await userEvent.keyboard('{Backspace}{Backspace}');
expect(input.element().querySelector('[data-react-aria-token]')).toBeNull();
expect(scroller.scrollTop).toBe(scrollTop);
}
);

it.each(['ltr', 'rtl'] as const)(
'keeps a visible field in place when Backspace leaves a trailing token (%s)',
async dir => {
let screen = await render(
<div
data-testid="scroller"
dir={dir}
style={{height: 180, overflow: 'auto', marginTop: 200}}>
<div style={{height: 500}} />
<TokenField
aria-label="Tags"
defaultValue={
new TagFieldValue([
{type: 'token', text: 'Design'},
{type: 'text', text: 'x'}
])
}>
<TokenInput style={{minHeight: 30}}>
{segment => <Token>{segment.text}</Token>}
</TokenInput>
</TokenField>
<div style={{height: 500}} />
</div>
);
let scroller = screen.getByTestId('scroller').element();
let input = screen.getByRole('textbox', {name: 'Tags'});
scroller.scrollTop = 450;
await userEvent.click(input);
await userEvent.keyboard('{End}');
let scrollTop = scroller.scrollTop;
expect(scrollTop).toBeGreaterThan(0);

await userEvent.keyboard('{Backspace}');
await expect.element(input).toHaveTextContent('Design');
expect(input.element().querySelector('[data-react-aria-token]')).not.toBeNull();
expect(scroller.scrollTop).toBe(scrollTop);
await expect.element(input).toHaveFocus();
}
);

it('scrolls newly created tokens into view when they wrap below the viewport', async () => {
let screen = await render(
<div
data-testid="scroller"
style={{height: 60, width: 100, overflow: 'auto', marginTop: 200}}>
<TokenField aria-label="Tags" defaultValue={new TagFieldValue([])}>
<TokenInput style={{minHeight: 20, lineHeight: '20px'}}>
{segment => <Token style={{display: 'inline-block'}}>{segment.text}</Token>}
</TokenInput>
</TokenField>
</div>
);
let scroller = screen.getByTestId('scroller').element();
let input = screen.getByRole('textbox', {name: 'Tags'});
await userEvent.click(input);
await userEvent.keyboard('Design,Engineering,Accessibility,Testing,');

let tokens = input.element().querySelectorAll('[data-react-aria-token]');
expect(tokens).toHaveLength(4);
expect(scroller.scrollTop).toBeGreaterThan(0);
expect(tokens[3].getBoundingClientRect().bottom).toBeLessThanOrEqual(
scroller.getBoundingClientRect().bottom + 1
);
});
});
17 changes: 15 additions & 2 deletions packages/react-aria/src/tokenfield/useTokenField.ts
Original file line number Diff line number Diff line change
Expand Up @@ -751,6 +751,11 @@ function scrollCaretIntoView(root: HTMLElement): void {
}

let range = selection.getRangeAt(0);
if (range.collapsed && range.endContainer === root) {
// Root-level positions around tokens have no rect. Measure the adjacent
// zero width space without moving the actual selection into the token.
range = tokenFieldPositionToDOMRange(root, {index: range.endOffset, offset: 0});
}
let rect = range.getBoundingClientRect();

// A collapsed range doesn't always produce a client rect. This happens for empty lines.
Expand All @@ -766,10 +771,10 @@ function scrollCaretIntoView(root: HTMLElement): void {
rect = root.getBoundingClientRect();
} else {
// Otherwise find the next sibling element (e.g. trailing <br>) and use its rect in this case.
let nextSibling = node.nextSibling;
let nextSibling = node === root ? null : node.nextSibling;
while (node && node !== root && !nextSibling) {
node = node.parentNode as Node | null;
nextSibling = node ? node.nextSibling : null;
nextSibling = node && node !== root ? node.nextSibling : null;
}

if (nextSibling?.nodeType === Node.ELEMENT_NODE) {
Expand Down Expand Up @@ -809,6 +814,14 @@ export function tokenFieldPositionToDOMRange(root: Element, pos: Position): Rang

function getDOMRectPosition(root: Element, pos: Position): [Node, number] {
let child = root.childNodes[pos.index];
if (
pos.index >= root.childNodes.length &&
root.lastChild?.lastChild?.nodeType === Node.TEXT_NODE
) {
// A position after the last token belongs to its trailing zero width space.
let text = root.lastChild.lastChild;
return [text, text.textContent!.length];
}
if (child && child.nodeType === Node.ELEMENT_NODE) {
// Place the position inside the zero width space wrappers around the token.
if (pos.offset > 0) {
Expand Down
Loading