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
7 changes: 7 additions & 0 deletions .changeset/dom-input-caret.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
'@clack/ui': minor
---

Move the caret in single-line text inputs with the arrow keys. Left and Right
move across grapheme boundaries or collapse an existing selection; Up and Down
move to the start and end. Readonly inputs remain navigable.
12 changes: 11 additions & 1 deletion packages/ui/src/dispatch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
getFocusOrder,
incrementFocus,
editText,
moveCaret,
KeyboardEvent,
nativeKeyCode,
transitionActiveElement,
Expand Down Expand Up @@ -42,7 +43,16 @@ export function createNativeDispatch(document: Document): NativeEventDispatch {
transitionActiveElement(document, next);
}
} else if (performDefaultAction && event.type === 'keydown') {
editText(document, event);
switch (event.key) {
case 'ArrowLeft':
case 'ArrowRight':
case 'ArrowUp':
case 'ArrowDown':
moveCaret(document, event);
break;
default:
editText(document, event);
}
}
}
};
Expand Down
48 changes: 48 additions & 0 deletions packages/ui/src/dom.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1451,6 +1451,31 @@ export class HTMLInputElement extends mixin(HTMLElement, [Disablable, Focusable]
this.notify();
}

_moveCaret(key: ArrowKey): void {
const start = this.selectionStart!;
const end = this.selectionEnd!;
let offset: number;
switch (key) {
case 'ArrowLeft':
offset =
start === end
? adjacentGraphemeOffset(this.value, { offset: start, direction: -1 })
: start;
break;
case 'ArrowRight':
offset =
start === end ? adjacentGraphemeOffset(this.value, { offset: end, direction: 1 }) : end;
break;
case 'ArrowUp':
offset = 0;
break;
case 'ArrowDown':
offset = this.value.length;
break;
}
this.#setSelectionRange(offset, offset, 'none', false);
}

#requireTextSelection(): void {
if (!textInputTypes.has(this.type)) {
throw new DOMException(
Expand Down Expand Up @@ -1559,6 +1584,28 @@ export function editText(document: Document, event: KeyboardEvent): void {
dispatchEvent(target, { event: new InputEvent('input', init), isTrusted: true });
}

export function moveCaret(document: Document, event: KeyboardEvent): void {
if (event.ctrlKey || event.metaKey || event.altKey || event.shiftKey || event.isComposing) {
return;
}
const target = getActiveElement(document);
if (
!(target instanceof HTMLInputElement) ||
!isFocusable(target) ||
target.selectionStart === null
) {
return;
}
switch (event.key) {
case 'ArrowLeft':
case 'ArrowRight':
case 'ArrowUp':
case 'ArrowDown':
target._moveCaret(event.key);
break;
}
}

function adjacentGraphemeOffset(
value: string,
{ offset, direction }: { offset: number; direction: 1 | -1 },
Expand Down Expand Up @@ -2117,6 +2164,7 @@ const fixedKeyCodes = new Map<string, number>([

type SelectionDirection = 'none' | 'forward' | 'backward';
type SelectionMode = 'select' | 'start' | 'end' | 'preserve';
type ArrowKey = 'ArrowLeft' | 'ArrowRight' | 'ArrowUp' | 'ArrowDown';

const textInputTypes = new Set(['text', 'search', 'tel', 'url', 'password']);
const graphemes = new Intl.Segmenter(undefined, { granularity: 'grapheme' });
Expand Down
5 changes: 5 additions & 0 deletions packages/ui/wpt.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,11 @@ const config: WPTConfig<Document> = {
'uievents/textInput/delete.html': ['textInput: delete, <input>'],
'uievents/textInput/delete-selection.html': ['textInput: delete selection, <input>'],
'html/semantics/forms/the-input-element/password-delete-space.html': true,
'html/semantics/forms/textfieldselection/selection-readonly-keyboard.tentative.html': [
'Arrow keys modify caret position in readonly input',
'Typing and Backspace do not modify value in readonly input',
// Shift-selection is the next rung; textarea editing remains unsupported.
],
'html/semantics/forms/the-input-element/input-value-dirty-flag.html': [
'Input value/defaultValue dirty value flag semantics',
"Input type defaults to 'text' on the property despite no attribute",
Expand Down
14 changes: 11 additions & 3 deletions packages/web-platform-tests/src/node/testdriver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,16 +51,16 @@ export function installTestDriver(
const target = record(element);
const document = record(scope.document);
if (target.ownerDocument !== document || target.nodeType !== 1 || !target.isConnected) {
throw new TestDriverError('testdriver send_keys requires an element in the current document');
throw new TestDriverError('testdriver focus requires an element in the current document');
}
if (!isFocusable) {
throw new TestDriverError('testdriver send_keys requires WPTConfig.isFocusable');
throw new TestDriverError('testdriver focus requires WPTConfig.isFocusable');
}
if (
typeof target.focus !== 'function' ||
(document.body !== element && !isFocusable(element))
) {
throw new TestDriverError('testdriver send_keys target is not keyboard-interactable');
throw new TestDriverError('testdriver focus target is not keyboard-interactable');
}
if (document.activeElement !== element) {
target.focus();
Expand Down Expand Up @@ -152,6 +152,14 @@ export function installTestDriver(
});
},
});
// Until mouse input is connected, clicks supply focus for keyboard fixtures.
if (scope.test_driver !== undefined) {
const driver = record(scope.test_driver);
driver.click = (element: unknown): Promise<void> =>
enqueue(async () => {
focusTarget(element);
});
}
if (withoutLayout) {
installNoLayoutSendKeys(scope);
}
Expand Down
Loading