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-editing.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
'@clack/ui': minor
---

Add value and selection handling for text inputs, including setSelectionRange()
and setRangeText(). Native character insertion dispatches cancelable beforeinput
events followed by input events.
20 changes: 12 additions & 8 deletions packages/ui/src/dispatch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
getActiveElement,
getFocusOrder,
incrementFocus,
insertText,
KeyboardEvent,
nativeKeyCode,
transitionActiveElement,
Expand All @@ -17,16 +18,17 @@ export interface NativeEventDispatch {
}

export function createNativeDispatch(document: Document): NativeEventDispatch {
return (event: NativeEvent): void => {
return (nativeEvent: NativeEvent): void => {
if (document.activeElement) {
const event = new KeyboardEvent(nativeEvent.type, {
...nativeEvent,
keyCode: nativeKeyCode(nativeEvent),
bubbles: true,
cancelable: true,
composed: true,
});
const performDefaultAction = dispatchEvent(document.activeElement, {
event: new KeyboardEvent(event.type, {
...event,
keyCode: nativeKeyCode(event),
bubbles: true,
cancelable: true,
composed: true,
}),
event,
isTrusted: true,
});

Expand All @@ -39,6 +41,8 @@ export function createNativeDispatch(document: Document): NativeEventDispatch {
if (next) {
transitionActiveElement(document, next);
}
} else if (performDefaultAction && event.type === 'keydown') {
insertText(document, event);
}
}
};
Expand Down
307 changes: 306 additions & 1 deletion packages/ui/src/dom.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1026,6 +1026,25 @@ export class KeyboardEvent extends Event {
}
}

export interface InputEventInit extends EventOptions {
data?: string | null;
inputType?: string;
isComposing?: boolean;
}

export class InputEvent extends Event {
readonly data: string | null;
readonly inputType: string;
readonly isComposing: boolean;

constructor(type: string, options: InputEventInit = {}) {
super(type, options);
this.data = options.data == null ? null : `${options.data}`;
this.inputType = options.inputType === undefined ? '' : `${options.inputType}`;
this.isComposing = Boolean(options.isComposing);
}
}

export function nativeKeyCode(event: { key: string; code?: string }): number {
if (/^[a-z]$/i.test(event.key)) {
return event.key.toUpperCase().charCodeAt(0);
Expand All @@ -1038,6 +1057,7 @@ export function nativeKeyCode(event: { key: string; code?: string }): number {
}
return fixedKeyCodes.get(event.key) ?? 0;
}

/* HTML */

export function createHTMLDocument(notify: Node['notify'], title?: string): HTMLDocument {
Expand Down Expand Up @@ -1249,7 +1269,266 @@ export class HTMLAnchorElement extends mixin(HTMLElement, [Focusable]) {}
export class HTMLButtonElement extends mixin(HTMLElement, [Disablable, Focusable]) {}

export class HTMLInputElement extends mixin(HTMLElement, [Disablable, Focusable]) {
value = '';
#value: string | null = null;
#selectionStart = 0;
#selectionEnd = 0;
#selectionDirection: SelectionDirection = 'none';
#selectionChangeQueued = false;
#onselect: EventListener | null = null;

get type(): string {
const type = asciiLowercase(this.getAttributeNS(null, 'type') ?? 'text');
return inputTypes.has(type) ? type : 'text';
}

set type(value: string) {
this.setAttributeNS(null, 'type', value);
}

get defaultValue(): string {
return this.getAttributeNS(null, 'value') ?? '';
}

set defaultValue(value: string) {
this.setAttributeNS(null, 'value', value);
}

get value(): string {
return this.#value ?? this.#sanitizeValue(this.defaultValue);
}

set value(value: string) {
const previous = this.value;
this.#value = this.#sanitizeValue(value === null ? '' : `${value}`);
if (this.#value !== previous) {
this.#setSelectionRange(this.#value.length, this.#value.length, 'none', false);
this.notify();
}
}

get readOnly(): boolean {
return this.hasAttributeNS(null, 'readonly');
}

set readOnly(value: boolean) {
this.toggleAttribute('readonly', Boolean(value));
}

get selectionStart(): number | null {
return textInputTypes.has(this.type) ? Math.min(this.#selectionStart, this.value.length) : null;
}

set selectionStart(value: number | null) {
const start = (value ?? 0) >>> 0;
this.setSelectionRange(
start,
Math.max(start, this.selectionEnd ?? 0),
this.#selectionDirection,
);
}

get selectionEnd(): number | null {
return textInputTypes.has(this.type) ? Math.min(this.#selectionEnd, this.value.length) : null;
}

set selectionEnd(value: number | null) {
this.setSelectionRange(this.selectionStart ?? 0, (value ?? 0) >>> 0, this.#selectionDirection);
}

get selectionDirection(): SelectionDirection | null {
return textInputTypes.has(this.type) ? this.#selectionDirection : null;
}

set selectionDirection(value: string | null) {
this.setSelectionRange(this.selectionStart ?? 0, this.selectionEnd ?? 0, `${value}`);
}

setSelectionRange(start: number, end: number, direction = 'none'): void {
if (arguments.length < 2) {
throw new TypeError('setSelectionRange requires a start and end');
}
start = start >>> 0;
end = end >>> 0;
direction = `${direction}`;
this.#requireTextSelection();
this.#setSelectionRange(start, end, direction);
}

select(): void {
if (textInputTypes.has(this.type)) {
this.#setSelectionRange(0, this.value.length);
}
}

setRangeText(replacement: string): void;
setRangeText(replacement: string, start: number, end: number, mode?: SelectionMode): void;
setRangeText(
replacement: string,
start?: number,
end?: number,
mode: SelectionMode = 'preserve',
): void {
if (arguments.length === 0 || arguments.length === 2) {
throw new TypeError(
'setRangeText requires replacement text and either both endpoints or neither',
);
}
replacement = `${replacement}`;
start = arguments.length === 1 ? (this.selectionStart ?? 0) : start! >>> 0;
end = arguments.length === 1 ? (this.selectionEnd ?? 0) : end! >>> 0;
mode = `${mode}` as SelectionMode;
if (!['select', 'start', 'end', 'preserve'].includes(mode)) {
throw new TypeError('Invalid selection mode');
}
this.#requireTextSelection();
const value = this.value;
this.#value = value;
if (start > end) {
throw new DOMException('The start must not be greater than the end', 'IndexSizeError');
}
start = Math.min(start, value.length);
end = Math.min(end, value.length);
let selectionStart = this.selectionStart!;
let selectionEnd = this.selectionEnd!;
this.#value = this.#sanitizeValue(value.slice(0, start) + replacement + value.slice(end));
const newEnd = start + replacement.length;
switch (mode) {
case 'select':
selectionStart = start;
selectionEnd = newEnd;
break;
case 'start':
selectionStart = selectionEnd = start;
break;
case 'end':
selectionStart = selectionEnd = newEnd;
break;
case 'preserve': {
const delta = replacement.length - (end - start);
if (selectionStart > end) {
selectionStart += delta;
} else if (selectionStart > start) {
selectionStart = start;
}
if (selectionEnd > end) {
selectionEnd += delta;
} else if (selectionEnd > start) {
selectionEnd = newEnd;
}
break;
}
}
this.#setSelectionRange(selectionStart, selectionEnd);
if (this.#value !== value) {
this.notify();
}
}

get onselect(): EventListener | null {
return this.#onselect;
}

set onselect(listener: EventListener | null) {
if (this.#onselect) {
this.removeEventListener('select', this.#onselect);
}
this.#onselect = listener;
this.addEventListener('select', listener);
}

_insertText(text: string): void {
const start = this.selectionStart!;
const end = this.selectionEnd!;
const value = this.value;
this.#value = this.#sanitizeValue(value.slice(0, start) + text + value.slice(end));
this.#setSelectionRange(start + text.length, start + text.length, 'none', false);
this.notify();
}

#requireTextSelection(): void {
if (!textInputTypes.has(this.type)) {
throw new DOMException(
'This input type does not support text selection',
'InvalidStateError',
);
}
}

#sanitizeValue(value: string): string {
if (textInputTypes.has(this.type)) {
value = value.replace(/[\r\n]/g, '');
}
return this.type === 'url' ? value.replace(/^[\t\n\f\r ]+|[\t\n\f\r ]+$/g, '') : value;
}

#setSelectionRange(start: number, end: number, direction = 'none', fireSelect = true): void {
end = Math.min(end, this.value.length);
start = Math.min(start, end);
const normalizedDirection =
direction === 'forward' || direction === 'backward' ? direction : 'none';
if (
start === this.#selectionStart &&
end === this.#selectionEnd &&
normalizedDirection === this.#selectionDirection
) {
return;
}
this.#selectionStart = start;
this.#selectionEnd = end;
this.#selectionDirection = normalizedDirection;
this.notify();
if (fireSelect) {
setTimeout(() => {
dispatchEvent(this, { event: new Event('select', { bubbles: true }), isTrusted: true });
}, 0);
}
if (!this.#selectionChangeQueued) {
this.#selectionChangeQueued = true;
setTimeout(() => {
this.#selectionChangeQueued = false;
dispatchEvent(this, {
event: new Event('selectionchange', { bubbles: true }),
isTrusted: true,
});
}, 0);
}
}
}

export function insertText(document: Document, event: KeyboardEvent): void {
if (
event.ctrlKey ||
event.metaKey ||
event.altKey ||
event.isComposing ||
[...event.key].length !== 1 ||
/[\p{Cc}\p{Cs}]/u.test(event.key)
) {
return;
}
const target = getActiveElement(document);
if (
!(target instanceof HTMLInputElement) ||
!isFocusable(target) ||
target.readOnly ||
target.selectionStart === null
) {
return;
}
const init = { data: event.key, inputType: 'insertText', bubbles: true, composed: true };
if (
!dispatchEvent(target, {
event: new InputEvent('beforeinput', { ...init, cancelable: true }),
isTrusted: true,
})
) {
return;
}
if (!isFocusable(target) || target.readOnly || target.selectionStart === null) {
return;
}
target._insertText(event.key);
dispatchEvent(target, { event: new InputEvent('input', init), isTrusted: true });
}

export class HTMLSelectElement extends mixin(HTMLElement, [Disablable, Focusable]) {}
Expand Down Expand Up @@ -1366,6 +1645,7 @@ export function getFocusOrder(document: Document): HTMLElement[] {
})
.map(({ element }) => element);
}

export function transitionActiveElement(document: Document, to: Element | null): void {
const current = getActiveElement(document);
if (to === current) {
Expand Down Expand Up @@ -1794,3 +2074,28 @@ const fixedKeyCodes = new Map<string, number>([
['ArrowDown', 40],
['Delete', 46],
]);

type SelectionDirection = 'none' | 'forward' | 'backward';
type SelectionMode = 'select' | 'start' | 'end' | 'preserve';

const textInputTypes = new Set(['text', 'search', 'tel', 'url', 'password']);
const inputTypes = new Set([
...textInputTypes,
'hidden',
'email',
'date',
'month',
'week',
'time',
'datetime-local',
'number',
'range',
'color',
'checkbox',
'radio',
'file',
'submit',
'image',
'reset',
'button',
]);
Loading
Loading