Skip to content

Commit cf0e056

Browse files
committed
Add text input state and native character editing
1 parent 3fe9ed8 commit cf0e056

4 files changed

Lines changed: 364 additions & 12 deletions

File tree

‎.changeset/dom-input-editing.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+
Add value and selection handling for text inputs, including setSelectionRange()
6+
and setRangeText(). Native character insertion dispatches cancelable beforeinput
7+
events followed by input events.

‎packages/ui/src/dispatch.ts‎

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import {
55
getActiveElement,
66
getFocusOrder,
77
incrementFocus,
8+
insertText,
89
KeyboardEvent,
910
nativeKeyCode,
1011
transitionActiveElement,
@@ -17,16 +18,17 @@ export interface NativeEventDispatch {
1718
}
1819

1920
export function createNativeDispatch(document: Document): NativeEventDispatch {
20-
return (event: NativeEvent): void => {
21+
return (nativeEvent: NativeEvent): void => {
2122
if (document.activeElement) {
23+
const event = new KeyboardEvent(nativeEvent.type, {
24+
...nativeEvent,
25+
keyCode: nativeKeyCode(nativeEvent),
26+
bubbles: true,
27+
cancelable: true,
28+
composed: true,
29+
});
2230
const performDefaultAction = dispatchEvent(document.activeElement, {
23-
event: new KeyboardEvent(event.type, {
24-
...event,
25-
keyCode: nativeKeyCode(event),
26-
bubbles: true,
27-
cancelable: true,
28-
composed: true,
29-
}),
31+
event,
3032
isTrusted: true,
3133
});
3234

@@ -39,6 +41,8 @@ export function createNativeDispatch(document: Document): NativeEventDispatch {
3941
if (next) {
4042
transitionActiveElement(document, next);
4143
}
44+
} else if (performDefaultAction && event.type === 'keydown') {
45+
insertText(document, event);
4246
}
4347
}
4448
};

‎packages/ui/src/dom.ts‎

Lines changed: 306 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1011,6 +1011,25 @@ export class KeyboardEvent extends Event {
10111011
}
10121012
}
10131013

1014+
export interface InputEventInit extends EventOptions {
1015+
data?: string | null;
1016+
inputType?: string;
1017+
isComposing?: boolean;
1018+
}
1019+
1020+
export class InputEvent extends Event {
1021+
readonly data: string | null;
1022+
readonly inputType: string;
1023+
readonly isComposing: boolean;
1024+
1025+
constructor(type: string, options: InputEventInit = {}) {
1026+
super(type, options);
1027+
this.data = options.data == null ? null : `${options.data}`;
1028+
this.inputType = options.inputType === undefined ? '' : `${options.inputType}`;
1029+
this.isComposing = Boolean(options.isComposing);
1030+
}
1031+
}
1032+
10141033
export function nativeKeyCode(event: { key: string; code?: string }): number {
10151034
if (/^[a-z]$/i.test(event.key)) {
10161035
return event.key.toUpperCase().charCodeAt(0);
@@ -1023,6 +1042,7 @@ export function nativeKeyCode(event: { key: string; code?: string }): number {
10231042
}
10241043
return fixedKeyCodes.get(event.key) ?? 0;
10251044
}
1045+
10261046
/* HTML */
10271047

10281048
export function createHTMLDocument(notify: Node['notify'], title?: string): HTMLDocument {
@@ -1234,7 +1254,266 @@ export class HTMLAnchorElement extends mixin(HTMLElement, [Focusable]) {}
12341254
export class HTMLButtonElement extends mixin(HTMLElement, [Disablable, Focusable]) {}
12351255

12361256
export class HTMLInputElement extends mixin(HTMLElement, [Disablable, Focusable]) {
1237-
value = '';
1257+
#value: string | null = null;
1258+
#selectionStart = 0;
1259+
#selectionEnd = 0;
1260+
#selectionDirection: SelectionDirection = 'none';
1261+
#selectionChangeQueued = false;
1262+
#onselect: EventListener | null = null;
1263+
1264+
get type(): string {
1265+
const type = asciiLowercase(this.getAttributeNS(null, 'type') ?? 'text');
1266+
return inputTypes.has(type) ? type : 'text';
1267+
}
1268+
1269+
set type(value: string) {
1270+
this.setAttributeNS(null, 'type', value);
1271+
}
1272+
1273+
get defaultValue(): string {
1274+
return this.getAttributeNS(null, 'value') ?? '';
1275+
}
1276+
1277+
set defaultValue(value: string) {
1278+
this.setAttributeNS(null, 'value', value);
1279+
}
1280+
1281+
get value(): string {
1282+
return this.#value ?? this.#sanitizeValue(this.defaultValue);
1283+
}
1284+
1285+
set value(value: string) {
1286+
const previous = this.value;
1287+
this.#value = this.#sanitizeValue(value === null ? '' : `${value}`);
1288+
if (this.#value !== previous) {
1289+
this.#setSelectionRange(this.#value.length, this.#value.length, 'none', false);
1290+
this.notify();
1291+
}
1292+
}
1293+
1294+
get readOnly(): boolean {
1295+
return this.hasAttributeNS(null, 'readonly');
1296+
}
1297+
1298+
set readOnly(value: boolean) {
1299+
this.toggleAttribute('readonly', Boolean(value));
1300+
}
1301+
1302+
get selectionStart(): number | null {
1303+
return textInputTypes.has(this.type) ? Math.min(this.#selectionStart, this.value.length) : null;
1304+
}
1305+
1306+
set selectionStart(value: number | null) {
1307+
const start = (value ?? 0) >>> 0;
1308+
this.setSelectionRange(
1309+
start,
1310+
Math.max(start, this.selectionEnd ?? 0),
1311+
this.#selectionDirection,
1312+
);
1313+
}
1314+
1315+
get selectionEnd(): number | null {
1316+
return textInputTypes.has(this.type) ? Math.min(this.#selectionEnd, this.value.length) : null;
1317+
}
1318+
1319+
set selectionEnd(value: number | null) {
1320+
this.setSelectionRange(this.selectionStart ?? 0, (value ?? 0) >>> 0, this.#selectionDirection);
1321+
}
1322+
1323+
get selectionDirection(): SelectionDirection | null {
1324+
return textInputTypes.has(this.type) ? this.#selectionDirection : null;
1325+
}
1326+
1327+
set selectionDirection(value: string | null) {
1328+
this.setSelectionRange(this.selectionStart ?? 0, this.selectionEnd ?? 0, `${value}`);
1329+
}
1330+
1331+
setSelectionRange(start: number, end: number, direction = 'none'): void {
1332+
if (arguments.length < 2) {
1333+
throw new TypeError('setSelectionRange requires a start and end');
1334+
}
1335+
start = start >>> 0;
1336+
end = end >>> 0;
1337+
direction = `${direction}`;
1338+
this.#requireTextSelection();
1339+
this.#setSelectionRange(start, end, direction);
1340+
}
1341+
1342+
select(): void {
1343+
if (textInputTypes.has(this.type)) {
1344+
this.#setSelectionRange(0, this.value.length);
1345+
}
1346+
}
1347+
1348+
setRangeText(replacement: string): void;
1349+
setRangeText(replacement: string, start: number, end: number, mode?: SelectionMode): void;
1350+
setRangeText(
1351+
replacement: string,
1352+
start?: number,
1353+
end?: number,
1354+
mode: SelectionMode = 'preserve',
1355+
): void {
1356+
if (arguments.length === 0 || arguments.length === 2) {
1357+
throw new TypeError(
1358+
'setRangeText requires replacement text and either both endpoints or neither',
1359+
);
1360+
}
1361+
replacement = `${replacement}`;
1362+
start = arguments.length === 1 ? (this.selectionStart ?? 0) : start! >>> 0;
1363+
end = arguments.length === 1 ? (this.selectionEnd ?? 0) : end! >>> 0;
1364+
mode = `${mode}` as SelectionMode;
1365+
if (!['select', 'start', 'end', 'preserve'].includes(mode)) {
1366+
throw new TypeError('Invalid selection mode');
1367+
}
1368+
this.#requireTextSelection();
1369+
const value = this.value;
1370+
this.#value = value;
1371+
if (start > end) {
1372+
throw new DOMException('The start must not be greater than the end', 'IndexSizeError');
1373+
}
1374+
start = Math.min(start, value.length);
1375+
end = Math.min(end, value.length);
1376+
let selectionStart = this.selectionStart!;
1377+
let selectionEnd = this.selectionEnd!;
1378+
this.#value = this.#sanitizeValue(value.slice(0, start) + replacement + value.slice(end));
1379+
const newEnd = start + replacement.length;
1380+
switch (mode) {
1381+
case 'select':
1382+
selectionStart = start;
1383+
selectionEnd = newEnd;
1384+
break;
1385+
case 'start':
1386+
selectionStart = selectionEnd = start;
1387+
break;
1388+
case 'end':
1389+
selectionStart = selectionEnd = newEnd;
1390+
break;
1391+
case 'preserve': {
1392+
const delta = replacement.length - (end - start);
1393+
if (selectionStart > end) {
1394+
selectionStart += delta;
1395+
} else if (selectionStart > start) {
1396+
selectionStart = start;
1397+
}
1398+
if (selectionEnd > end) {
1399+
selectionEnd += delta;
1400+
} else if (selectionEnd > start) {
1401+
selectionEnd = newEnd;
1402+
}
1403+
break;
1404+
}
1405+
}
1406+
this.#setSelectionRange(selectionStart, selectionEnd);
1407+
if (this.#value !== value) {
1408+
this.notify();
1409+
}
1410+
}
1411+
1412+
get onselect(): EventListener | null {
1413+
return this.#onselect;
1414+
}
1415+
1416+
set onselect(listener: EventListener | null) {
1417+
if (this.#onselect) {
1418+
this.removeEventListener('select', this.#onselect);
1419+
}
1420+
this.#onselect = listener;
1421+
this.addEventListener('select', listener);
1422+
}
1423+
1424+
_insertText(text: string): void {
1425+
const start = this.selectionStart!;
1426+
const end = this.selectionEnd!;
1427+
const value = this.value;
1428+
this.#value = this.#sanitizeValue(value.slice(0, start) + text + value.slice(end));
1429+
this.#setSelectionRange(start + text.length, start + text.length, 'none', false);
1430+
this.notify();
1431+
}
1432+
1433+
#requireTextSelection(): void {
1434+
if (!textInputTypes.has(this.type)) {
1435+
throw new DOMException(
1436+
'This input type does not support text selection',
1437+
'InvalidStateError',
1438+
);
1439+
}
1440+
}
1441+
1442+
#sanitizeValue(value: string): string {
1443+
if (textInputTypes.has(this.type)) {
1444+
value = value.replace(/[\r\n]/g, '');
1445+
}
1446+
return this.type === 'url' ? value.replace(/^[\t\n\f\r ]+|[\t\n\f\r ]+$/g, '') : value;
1447+
}
1448+
1449+
#setSelectionRange(start: number, end: number, direction = 'none', fireSelect = true): void {
1450+
end = Math.min(end, this.value.length);
1451+
start = Math.min(start, end);
1452+
const normalizedDirection =
1453+
direction === 'forward' || direction === 'backward' ? direction : 'none';
1454+
if (
1455+
start === this.#selectionStart &&
1456+
end === this.#selectionEnd &&
1457+
normalizedDirection === this.#selectionDirection
1458+
) {
1459+
return;
1460+
}
1461+
this.#selectionStart = start;
1462+
this.#selectionEnd = end;
1463+
this.#selectionDirection = normalizedDirection;
1464+
this.notify();
1465+
if (fireSelect) {
1466+
setTimeout(() => {
1467+
dispatchEvent(this, { event: new Event('select', { bubbles: true }), isTrusted: true });
1468+
}, 0);
1469+
}
1470+
if (!this.#selectionChangeQueued) {
1471+
this.#selectionChangeQueued = true;
1472+
setTimeout(() => {
1473+
this.#selectionChangeQueued = false;
1474+
dispatchEvent(this, {
1475+
event: new Event('selectionchange', { bubbles: true }),
1476+
isTrusted: true,
1477+
});
1478+
}, 0);
1479+
}
1480+
}
1481+
}
1482+
1483+
export function insertText(document: Document, event: KeyboardEvent): void {
1484+
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)
1491+
) {
1492+
return;
1493+
}
1494+
const target = getActiveElement(document);
1495+
if (
1496+
!(target instanceof HTMLInputElement) ||
1497+
!isFocusable(target) ||
1498+
target.readOnly ||
1499+
target.selectionStart === null
1500+
) {
1501+
return;
1502+
}
1503+
const init = { data: event.key, inputType: 'insertText', bubbles: true, composed: true };
1504+
if (
1505+
!dispatchEvent(target, {
1506+
event: new InputEvent('beforeinput', { ...init, cancelable: true }),
1507+
isTrusted: true,
1508+
})
1509+
) {
1510+
return;
1511+
}
1512+
if (!isFocusable(target) || target.readOnly || target.selectionStart === null) {
1513+
return;
1514+
}
1515+
target._insertText(event.key);
1516+
dispatchEvent(target, { event: new InputEvent('input', init), isTrusted: true });
12381517
}
12391518

12401519
export class HTMLSelectElement extends mixin(HTMLElement, [Disablable, Focusable]) {}
@@ -1351,6 +1630,7 @@ export function getFocusOrder(document: Document): HTMLElement[] {
13511630
})
13521631
.map(({ element }) => element);
13531632
}
1633+
13541634
export function transitionActiveElement(document: Document, to: Element | null): void {
13551635
const current = getActiveElement(document);
13561636
if (to === current) {
@@ -1779,3 +2059,28 @@ const fixedKeyCodes = new Map<string, number>([
17792059
['ArrowDown', 40],
17802060
['Delete', 46],
17812061
]);
2062+
2063+
type SelectionDirection = 'none' | 'forward' | 'backward';
2064+
type SelectionMode = 'select' | 'start' | 'end' | 'preserve';
2065+
2066+
const textInputTypes = new Set(['text', 'search', 'tel', 'url', 'password']);
2067+
const inputTypes = new Set([
2068+
...textInputTypes,
2069+
'hidden',
2070+
'email',
2071+
'date',
2072+
'month',
2073+
'week',
2074+
'time',
2075+
'datetime-local',
2076+
'number',
2077+
'range',
2078+
'color',
2079+
'checkbox',
2080+
'radio',
2081+
'file',
2082+
'submit',
2083+
'image',
2084+
'reset',
2085+
'button',
2086+
]);

0 commit comments

Comments
 (0)