Skip to content

Commit b83b083

Browse files
committed
Add Backspace and Delete editing for text inputs
1 parent cf0e056 commit b83b083

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
}
@@ -1421,9 +1429,7 @@ export class HTMLInputElement extends mixin(HTMLElement, [Disablable, Focusable]
14211429
this.addEventListener('select', listener);
14221430
}
14231431

1424-
_insertText(text: string): void {
1425-
const start = this.selectionStart!;
1426-
const end = this.selectionEnd!;
1432+
_replaceText(text: string, { start, end }: { start: number; end: number }): void {
14271433
const value = this.value;
14281434
this.#value = this.#sanitizeValue(value.slice(0, start) + text + value.slice(end));
14291435
this.#setSelectionRange(start + text.length, start + text.length, 'none', false);
@@ -1480,14 +1486,19 @@ export class HTMLInputElement extends mixin(HTMLElement, [Disablable, Focusable]
14801486
}
14811487
}
14821488

1483-
export function insertText(document: Document, event: KeyboardEvent): void {
1489+
export function editText(document: Document, event: KeyboardEvent): void {
1490+
if (event.ctrlKey || event.metaKey || event.altKey || event.isComposing) {
1491+
return;
1492+
}
1493+
const inputType =
1494+
event.key === 'Backspace'
1495+
? 'deleteContentBackward'
1496+
: event.key === 'Delete'
1497+
? 'deleteContentForward'
1498+
: 'insertText';
14841499
if (
1485-
event.ctrlKey ||
1486-
event.metaKey ||
1487-
event.altKey ||
1488-
event.isComposing ||
1489-
[...event.key].length !== 1 ||
1490-
/[\p{Cc}\p{Cs}]/u.test(event.key)
1500+
inputType === 'insertText' &&
1501+
([...event.key].length !== 1 || /[\p{Cc}\p{Cs}]/u.test(event.key))
14911502
) {
14921503
return;
14931504
}
@@ -1500,7 +1511,12 @@ export function insertText(document: Document, event: KeyboardEvent): void {
15001511
) {
15011512
return;
15021513
}
1503-
const init = { data: event.key, inputType: 'insertText', bubbles: true, composed: true };
1514+
const init = {
1515+
data: inputType === 'insertText' ? event.key : null,
1516+
inputType,
1517+
bubbles: true,
1518+
composed: true,
1519+
};
15041520
if (
15051521
!dispatchEvent(target, {
15061522
event: new InputEvent('beforeinput', { ...init, cancelable: true }),
@@ -1512,10 +1528,34 @@ export function insertText(document: Document, event: KeyboardEvent): void {
15121528
if (!isFocusable(target) || target.readOnly || target.selectionStart === null) {
15131529
return;
15141530
}
1515-
target._insertText(event.key);
1531+
let start = target.selectionStart;
1532+
let end = target.selectionEnd!;
1533+
if (inputType !== 'insertText' && start === end) {
1534+
if (inputType === 'deleteContentBackward') {
1535+
start = adjacentGraphemeOffset(target.value, { offset: start, direction: -1 });
1536+
} else {
1537+
end = adjacentGraphemeOffset(target.value, { offset: end, direction: 1 });
1538+
}
1539+
if (start === end) {
1540+
return;
1541+
}
1542+
}
1543+
target._replaceText(init.data ?? '', { start, end });
15161544
dispatchEvent(target, { event: new InputEvent('input', init), isTrusted: true });
15171545
}
15181546

1547+
function adjacentGraphemeOffset(
1548+
value: string,
1549+
{ offset, direction }: { offset: number; direction: 1 | -1 },
1550+
): number {
1551+
const segments = graphemes.segment(value);
1552+
if (direction < 0) {
1553+
return segments.containing(offset - 1)?.index ?? 0;
1554+
}
1555+
const segment = segments.containing(offset);
1556+
return segment ? segment.index + segment.segment.length : value.length;
1557+
}
1558+
15191559
export class HTMLSelectElement extends mixin(HTMLElement, [Disablable, Focusable]) {}
15201560

15211561
export class HTMLTextAreaElement extends mixin(HTMLElement, [Disablable, Focusable]) {}
@@ -2064,6 +2104,7 @@ type SelectionDirection = 'none' | 'forward' | 'backward';
20642104
type SelectionMode = 'select' | 'start' | 'end' | 'preserve';
20652105

20662106
const textInputTypes = new Set(['text', 'search', 'tel', 'url', 'password']);
2107+
const graphemes = new Intl.Segmenter(undefined, { granularity: 'grapheme' });
20672108
const inputTypes = new Set([
20682109
...textInputTypes,
20692110
'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)