Skip to content

Commit acf1121

Browse files
committed
Add Backspace and Delete editing for text inputs
1 parent 9aa48a9 commit acf1121

5 files changed

Lines changed: 89 additions & 17 deletions

File tree

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

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
---
2+
'@clack/ui': minor
3+
---
4+
5+
Support Backspace and Delete in text inputs, including selection replacement,
6+
grapheme boundaries, and cancelable beforeinput events followed by input events.

‎packages/ui/src/dispatch.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ import {
55
getActiveElement,
66
getFocusOrder,
77
incrementFocus,
8-
insertText,
8+
editText,
99
KeyboardEvent,
1010
nativeKeyCode,
1111
transitionActiveElement,
@@ -42,7 +42,7 @@ export function createNativeDispatch(document: Document): NativeEventDispatch {
4242
transitionActiveElement(document, next);
4343
}
4444
} else if (performDefaultAction && event.type === 'keydown') {
45-
insertText(document, event);
45+
editText(document, event);
4646
}
4747
}
4848
};

‎packages/ui/src/dom.ts‎

Lines changed: 53 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -421,6 +421,14 @@ export class Document extends Node {
421421
return this.#forms;
422422
}
423423

424+
get title(): string {
425+
const title = findElement(
426+
Array.from(this.childNodes),
427+
(element) => element.namespaceURI === HTML_NS && element.localName === 'title',
428+
);
429+
return (title?.textContent ?? '').replace(/[\t\n\f\r ]+/g, ' ').replace(/^ | $/g, '');
430+
}
431+
424432
querySelector(selector: string): Element | null {
425433
return querySelector(Array.from(this.childNodes), selector);
426434
}
@@ -1436,9 +1444,7 @@ export class HTMLInputElement extends mixin(HTMLElement, [Disablable, Focusable]
14361444
this.addEventListener('select', listener);
14371445
}
14381446

1439-
_insertText(text: string): void {
1440-
const start = this.selectionStart!;
1441-
const end = this.selectionEnd!;
1447+
_replaceText(text: string, { start, end }: { start: number; end: number }): void {
14421448
const value = this.value;
14431449
this.#value = this.#sanitizeValue(value.slice(0, start) + text + value.slice(end));
14441450
this.#setSelectionRange(start + text.length, start + text.length, 'none', false);
@@ -1495,14 +1501,19 @@ export class HTMLInputElement extends mixin(HTMLElement, [Disablable, Focusable]
14951501
}
14961502
}
14971503

1498-
export function insertText(document: Document, event: KeyboardEvent): void {
1504+
export function editText(document: Document, event: KeyboardEvent): void {
1505+
if (event.ctrlKey || event.metaKey || event.altKey || event.isComposing) {
1506+
return;
1507+
}
1508+
const inputType =
1509+
event.key === 'Backspace'
1510+
? 'deleteContentBackward'
1511+
: event.key === 'Delete'
1512+
? 'deleteContentForward'
1513+
: 'insertText';
14991514
if (
1500-
event.ctrlKey ||
1501-
event.metaKey ||
1502-
event.altKey ||
1503-
event.isComposing ||
1504-
[...event.key].length !== 1 ||
1505-
/[\p{Cc}\p{Cs}]/u.test(event.key)
1515+
inputType === 'insertText' &&
1516+
([...event.key].length !== 1 || /[\p{Cc}\p{Cs}]/u.test(event.key))
15061517
) {
15071518
return;
15081519
}
@@ -1515,7 +1526,12 @@ export function insertText(document: Document, event: KeyboardEvent): void {
15151526
) {
15161527
return;
15171528
}
1518-
const init = { data: event.key, inputType: 'insertText', bubbles: true, composed: true };
1529+
const init = {
1530+
data: inputType === 'insertText' ? event.key : null,
1531+
inputType,
1532+
bubbles: true,
1533+
composed: true,
1534+
};
15191535
if (
15201536
!dispatchEvent(target, {
15211537
event: new InputEvent('beforeinput', { ...init, cancelable: true }),
@@ -1527,10 +1543,34 @@ export function insertText(document: Document, event: KeyboardEvent): void {
15271543
if (!isFocusable(target) || target.readOnly || target.selectionStart === null) {
15281544
return;
15291545
}
1530-
target._insertText(event.key);
1546+
let start = target.selectionStart;
1547+
let end = target.selectionEnd!;
1548+
if (inputType !== 'insertText' && start === end) {
1549+
if (inputType === 'deleteContentBackward') {
1550+
start = adjacentGraphemeOffset(target.value, { offset: start, direction: -1 });
1551+
} else {
1552+
end = adjacentGraphemeOffset(target.value, { offset: end, direction: 1 });
1553+
}
1554+
if (start === end) {
1555+
return;
1556+
}
1557+
}
1558+
target._replaceText(init.data ?? '', { start, end });
15311559
dispatchEvent(target, { event: new InputEvent('input', init), isTrusted: true });
15321560
}
15331561

1562+
function adjacentGraphemeOffset(
1563+
value: string,
1564+
{ offset, direction }: { offset: number; direction: 1 | -1 },
1565+
): number {
1566+
const segments = graphemes.segment(value);
1567+
if (direction < 0) {
1568+
return segments.containing(offset - 1)?.index ?? 0;
1569+
}
1570+
const segment = segments.containing(offset);
1571+
return segment ? segment.index + segment.segment.length : value.length;
1572+
}
1573+
15341574
export class HTMLSelectElement extends mixin(HTMLElement, [Disablable, Focusable]) {}
15351575

15361576
export class HTMLTextAreaElement extends mixin(HTMLElement, [Disablable, Focusable]) {}
@@ -2079,6 +2119,7 @@ type SelectionDirection = 'none' | 'forward' | 'backward';
20792119
type SelectionMode = 'select' | 'start' | 'end' | 'preserve';
20802120

20812121
const textInputTypes = new Set(['text', 'search', 'tel', 'url', 'password']);
2122+
const graphemes = new Intl.Segmenter(undefined, { granularity: 'grapheme' });
20822123
const inputTypes = new Set([
20832124
...textInputTypes,
20842125
'hidden',

‎packages/ui/wpt.config.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,10 @@ const config: WPTConfig<Document> = {
3939
createNativeDispatch,
4040
isFocusable: (element) => element instanceof HTMLElement && isFocusable(element),
4141
sendKeysWithoutLayout: [
42+
'uievents/textInput/backspace.html',
43+
'uievents/textInput/delete.html',
44+
'uievents/textInput/delete-selection.html',
45+
'html/semantics/forms/the-input-element/password-delete-space.html',
4246
'html/semantics/forms/the-select-element/select-tab-navigation.tentative.html',
4347
'html/semantics/forms/the-select-element/customizable-select/select-tabindex-order.html',
4448
'html/interaction/focus/sequential-focus-navigation-and-the-tabindex-attribute/focus-tabindex-negative.html',
@@ -94,6 +98,10 @@ const config: WPTConfig<Document> = {
9498
'html/syntax/serializing-html-fragments/serializing.html': true,
9599
'uievents/constructors/inputevent-constructor.html': true,
96100
'uievents/keyboard/keydown-input-events.html': true,
101+
'uievents/textInput/backspace.html': ['textInput: backspace, <input>'],
102+
'uievents/textInput/delete.html': ['textInput: delete, <input>'],
103+
'uievents/textInput/delete-selection.html': ['textInput: delete selection, <input>'],
104+
'html/semantics/forms/the-input-element/password-delete-space.html': true,
97105
'html/semantics/forms/the-input-element/input-value-dirty-flag.html': [
98106
'Input value/defaultValue dirty value flag semantics',
99107
"Input type defaults to 'text' on the property despite no attribute",

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

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -169,9 +169,15 @@ async function loadHelper(
169169
): Promise<SourceScript | null> {
170170
const url = new URL(src, `${origin}/${path}`);
171171
const helper = decodeURIComponent(url.pathname).slice(1);
172-
if (url.origin !== origin || url.search || /\.(?:sub\.js|py)$/.test(helper)) {
172+
const substituted = helper.endsWith('.sub.js');
173+
if (
174+
url.origin !== origin ||
175+
(url.search && !substituted) ||
176+
helper.endsWith('.py') ||
177+
url.searchParams.has('pipe')
178+
) {
173179
throw new UnsupportedSourceError(
174-
`Only static helpers from the WPT checkout are supported: ${src}`,
180+
`Only static helpers and GET-substituted scripts from the WPT checkout are supported: ${src}`,
175181
);
176182
}
177183
if (helper === harnessPath || helper === reporterPath) {
@@ -181,7 +187,18 @@ async function loadHelper(
181187
fileURLToPath(new URL(url.pathname.slice(1), checkoutURL(root))),
182188
root,
183189
);
184-
return { file, code: await readFile(file, 'utf8') };
190+
let code = await readFile(file, 'utf8');
191+
if (substituted) {
192+
// WPT serves .sub.js with sub(none): query values are inserted without escaping.
193+
code = code.replace(/{{([^}]*)}}/g, (_, expression: string) => {
194+
const match = /^GET\[([^\]]*)\]$/.exec(expression);
195+
if (!match) {
196+
throw new UnsupportedSourceError(`Unsupported WPT substitution: {{${expression}}}`);
197+
}
198+
return url.searchParams.get(match[1]!) ?? '';
199+
});
200+
}
201+
return { file, code };
185202
}
186203

187204
async function checkedPath(file: string, root: string): Promise<string> {

0 commit comments

Comments
 (0)