Skip to content

Commit 32b5a76

Browse files
committed
Add arrow-key caret movement for text inputs
1 parent 453ced5 commit 32b5a76

5 files changed

Lines changed: 82 additions & 4 deletions

File tree

‎.changeset/dom-input-caret.md‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
---
2+
'@clack/ui': minor
3+
---
4+
5+
Move the caret in single-line text inputs with the arrow keys. Left and Right
6+
move across grapheme boundaries or collapse an existing selection; Up and Down
7+
move to the start and end. Readonly inputs remain navigable.

‎packages/ui/src/dispatch.ts‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import {
66
getFocusOrder,
77
incrementFocus,
88
editText,
9+
moveCaret,
910
KeyboardEvent,
1011
nativeKeyCode,
1112
transitionActiveElement,
@@ -42,7 +43,16 @@ export function createNativeDispatch(document: Document): NativeEventDispatch {
4243
transitionActiveElement(document, next);
4344
}
4445
} else if (performDefaultAction && event.type === 'keydown') {
45-
editText(document, event);
46+
switch (event.key) {
47+
case 'ArrowLeft':
48+
case 'ArrowRight':
49+
case 'ArrowUp':
50+
case 'ArrowDown':
51+
moveCaret(document, event);
52+
break;
53+
default:
54+
editText(document, event);
55+
}
4656
}
4757
}
4858
};

‎packages/ui/src/dom.ts‎

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1451,6 +1451,31 @@ export class HTMLInputElement extends mixin(HTMLElement, [Disablable, Focusable]
14511451
this.notify();
14521452
}
14531453

1454+
_moveCaret(key: ArrowKey): void {
1455+
const start = this.selectionStart!;
1456+
const end = this.selectionEnd!;
1457+
let offset: number;
1458+
switch (key) {
1459+
case 'ArrowLeft':
1460+
offset =
1461+
start === end
1462+
? adjacentGraphemeOffset(this.value, { offset: start, direction: -1 })
1463+
: start;
1464+
break;
1465+
case 'ArrowRight':
1466+
offset =
1467+
start === end ? adjacentGraphemeOffset(this.value, { offset: end, direction: 1 }) : end;
1468+
break;
1469+
case 'ArrowUp':
1470+
offset = 0;
1471+
break;
1472+
case 'ArrowDown':
1473+
offset = this.value.length;
1474+
break;
1475+
}
1476+
this.#setSelectionRange(offset, offset, 'none', false);
1477+
}
1478+
14541479
#requireTextSelection(): void {
14551480
if (!textInputTypes.has(this.type)) {
14561481
throw new DOMException(
@@ -1559,6 +1584,28 @@ export function editText(document: Document, event: KeyboardEvent): void {
15591584
dispatchEvent(target, { event: new InputEvent('input', init), isTrusted: true });
15601585
}
15611586

1587+
export function moveCaret(document: Document, event: KeyboardEvent): void {
1588+
if (event.ctrlKey || event.metaKey || event.altKey || event.shiftKey || event.isComposing) {
1589+
return;
1590+
}
1591+
const target = getActiveElement(document);
1592+
if (
1593+
!(target instanceof HTMLInputElement) ||
1594+
!isFocusable(target) ||
1595+
target.selectionStart === null
1596+
) {
1597+
return;
1598+
}
1599+
switch (event.key) {
1600+
case 'ArrowLeft':
1601+
case 'ArrowRight':
1602+
case 'ArrowUp':
1603+
case 'ArrowDown':
1604+
target._moveCaret(event.key);
1605+
break;
1606+
}
1607+
}
1608+
15621609
function adjacentGraphemeOffset(
15631610
value: string,
15641611
{ offset, direction }: { offset: number; direction: 1 | -1 },
@@ -2117,6 +2164,7 @@ const fixedKeyCodes = new Map<string, number>([
21172164

21182165
type SelectionDirection = 'none' | 'forward' | 'backward';
21192166
type SelectionMode = 'select' | 'start' | 'end' | 'preserve';
2167+
type ArrowKey = 'ArrowLeft' | 'ArrowRight' | 'ArrowUp' | 'ArrowDown';
21202168

21212169
const textInputTypes = new Set(['text', 'search', 'tel', 'url', 'password']);
21222170
const graphemes = new Intl.Segmenter(undefined, { granularity: 'grapheme' });

‎packages/ui/wpt.config.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -102,6 +102,11 @@ const config: WPTConfig<Document> = {
102102
'uievents/textInput/delete.html': ['textInput: delete, <input>'],
103103
'uievents/textInput/delete-selection.html': ['textInput: delete selection, <input>'],
104104
'html/semantics/forms/the-input-element/password-delete-space.html': true,
105+
'html/semantics/forms/textfieldselection/selection-readonly-keyboard.tentative.html': [
106+
'Arrow keys modify caret position in readonly input',
107+
'Typing and Backspace do not modify value in readonly input',
108+
// Shift-selection is the next rung; textarea editing remains unsupported.
109+
],
105110
'html/semantics/forms/the-input-element/input-value-dirty-flag.html': [
106111
'Input value/defaultValue dirty value flag semantics',
107112
"Input type defaults to 'text' on the property despite no attribute",

‎packages/web-platform-tests/src/node/testdriver.ts‎

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -51,16 +51,16 @@ export function installTestDriver(
5151
const target = record(element);
5252
const document = record(scope.document);
5353
if (target.ownerDocument !== document || target.nodeType !== 1 || !target.isConnected) {
54-
throw new TestDriverError('testdriver send_keys requires an element in the current document');
54+
throw new TestDriverError('testdriver focus requires an element in the current document');
5555
}
5656
if (!isFocusable) {
57-
throw new TestDriverError('testdriver send_keys requires WPTConfig.isFocusable');
57+
throw new TestDriverError('testdriver focus requires WPTConfig.isFocusable');
5858
}
5959
if (
6060
typeof target.focus !== 'function' ||
6161
(document.body !== element && !isFocusable(element))
6262
) {
63-
throw new TestDriverError('testdriver send_keys target is not keyboard-interactable');
63+
throw new TestDriverError('testdriver focus target is not keyboard-interactable');
6464
}
6565
if (document.activeElement !== element) {
6666
target.focus();
@@ -152,6 +152,14 @@ export function installTestDriver(
152152
});
153153
},
154154
});
155+
// Until mouse input is connected, clicks supply focus for keyboard fixtures.
156+
if (scope.test_driver !== undefined) {
157+
const driver = record(scope.test_driver);
158+
driver.click = (element: unknown): Promise<void> =>
159+
enqueue(async () => {
160+
focusTarget(element);
161+
});
162+
}
155163
if (withoutLayout) {
156164
installNoLayoutSendKeys(scope);
157165
}

0 commit comments

Comments
 (0)