Set up comprehensive frontend testing infrastructure

- Install Jest for unit testing with React Testing Library
- Install Playwright for end-to-end testing
- Configure Jest with proper TypeScript support and module mapping
- Create test setup files and utilities for both unit and e2e tests

Components:
* Jest configuration with coverage thresholds
* Playwright configuration with browser automation
* Unit tests for LoginForm, AuthContext, and useSocketIO hook
* E2E tests for authentication, dashboard, and agents workflows
* GitHub Actions workflow for automated testing
* Mock data and API utilities for consistent testing
* Test documentation with best practices

Testing features:
- Unit tests with 70% coverage threshold
- E2E tests with API mocking and user journey testing
- CI/CD integration for automated test runs
- Cross-browser testing support with Playwright
- Authentication system testing end-to-end

🚀 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
anthonyrawlins
2025-07-11 14:06:34 +10:00
parent c6d69695a8
commit aacb45156b
6109 changed files with 777927 additions and 1 deletions

View File

@@ -0,0 +1,20 @@
import { writeDataTransferToClipboard } from '../utils/dataTransfer/Clipboard.js';
import { copySelection } from '../document/copySelection.js';
async function copy() {
const doc = this.config.document;
var _doc_activeElement;
const target = (_doc_activeElement = doc.activeElement) !== null && _doc_activeElement !== undefined ? _doc_activeElement : /* istanbul ignore next */ doc.body;
const clipboardData = copySelection(target);
if (clipboardData.items.length === 0) {
return;
}
if (this.dispatchUIEvent(target, 'copy', {
clipboardData
}) && this.config.writeToClipboard) {
await writeDataTransferToClipboard(doc, clipboardData);
}
return clipboardData;
}
export { copy };

View File

@@ -0,0 +1,20 @@
import { writeDataTransferToClipboard } from '../utils/dataTransfer/Clipboard.js';
import { copySelection } from '../document/copySelection.js';
async function cut() {
const doc = this.config.document;
var _doc_activeElement;
const target = (_doc_activeElement = doc.activeElement) !== null && _doc_activeElement !== undefined ? _doc_activeElement : /* istanbul ignore next */ doc.body;
const clipboardData = copySelection(target);
if (clipboardData.items.length === 0) {
return;
}
if (this.dispatchUIEvent(target, 'cut', {
clipboardData
}) && this.config.writeToClipboard) {
await writeDataTransferToClipboard(target.ownerDocument, clipboardData);
}
return clipboardData;
}
export { cut };

View File

@@ -0,0 +1,3 @@
export { copy } from './copy.js';
export { cut } from './cut.js';
export { paste } from './paste.js';

View File

@@ -0,0 +1,23 @@
import { createDataTransfer } from '../utils/dataTransfer/DataTransfer.js';
import { readDataTransferFromClipboard } from '../utils/dataTransfer/Clipboard.js';
import { getWindow } from '../utils/misc/getWindow.js';
async function paste(clipboardData) {
const doc = this.config.document;
var _doc_activeElement;
const target = (_doc_activeElement = doc.activeElement) !== null && _doc_activeElement !== undefined ? _doc_activeElement : /* istanbul ignore next */ doc.body;
var _ref;
const dataTransfer = (_ref = typeof clipboardData === 'string' ? getClipboardDataFromString(doc, clipboardData) : clipboardData) !== null && _ref !== undefined ? _ref : await readDataTransferFromClipboard(doc).catch(()=>{
throw new Error('`userEvent.paste()` without `clipboardData` requires the `ClipboardAPI` to be available.');
});
this.dispatchUIEvent(target, 'paste', {
clipboardData: dataTransfer
});
}
function getClipboardDataFromString(doc, text) {
const dt = createDataTransfer(getWindow(doc));
dt.setData('text', text);
return dt;
}
export { paste };

View File

@@ -0,0 +1,31 @@
async function click(element) {
const pointerIn = [];
if (!this.config.skipHover) {
pointerIn.push({
target: element
});
}
pointerIn.push({
keys: '[MouseLeft]',
target: element
});
return this.pointer(pointerIn);
}
async function dblClick(element) {
return this.pointer([
{
target: element
},
'[MouseLeft][MouseLeft]'
]);
}
async function tripleClick(element) {
return this.pointer([
{
target: element
},
'[MouseLeft][MouseLeft][MouseLeft]'
]);
}
export { click, dblClick, tripleClick };

View File

@@ -0,0 +1,16 @@
import '../utils/dataTransfer/Clipboard.js';
import { assertPointerEvents } from '../utils/pointer/cssPointerEvents.js';
async function hover(element) {
return this.pointer({
target: element
});
}
async function unhover(element) {
assertPointerEvents(this, this.system.pointer.getMouseTarget(this));
return this.pointer({
target: element.ownerDocument.body
});
}
export { hover, unhover };

View File

@@ -0,0 +1,3 @@
export { click, dblClick, tripleClick } from './click.js';
export { hover, unhover } from './hover.js';
export { tab } from './tab.js';

View File

@@ -0,0 +1,5 @@
async function tab({ shift } = {}) {
return this.keyboard(shift === true ? '{Shift>}{Tab}{/Shift}' : shift === false ? '[/ShiftLeft][/ShiftRight]{Tab}' : '{Tab}');
}
export { tab };

View File

@@ -0,0 +1,79 @@
const UIValue = Symbol('Displayed value in UI');
const UISelection = Symbol('Displayed selection in UI');
const InitialValue = Symbol('Initial value to compare on blur');
function isUIValue(value) {
return typeof value === 'object' && UIValue in value;
}
function isUISelectionStart(start) {
return !!start && typeof start === 'object' && UISelection in start;
}
function setUIValue(element, value) {
if (element[InitialValue] === undefined) {
element[InitialValue] = element.value;
}
element[UIValue] = value;
// eslint-disable-next-line no-new-wrappers
element.value = Object.assign(new String(value), {
[UIValue]: true
});
}
function getUIValue(element) {
return element[UIValue] === undefined ? element.value : String(element[UIValue]);
}
/** Flag the IDL value as clean. This does not change the value.*/ function setUIValueClean(element) {
element[UIValue] = undefined;
}
function clearInitialValue(element) {
element[InitialValue] = undefined;
}
function getInitialValue(element) {
return element[InitialValue];
}
function setUISelectionRaw(element, selection) {
element[UISelection] = selection;
}
function setUISelection(element, { focusOffset: focusOffsetParam, anchorOffset: anchorOffsetParam = focusOffsetParam }, mode = 'replace') {
const valueLength = getUIValue(element).length;
const sanitizeOffset = (o)=>Math.max(0, Math.min(valueLength, o));
const anchorOffset = mode === 'replace' || element[UISelection] === undefined ? sanitizeOffset(anchorOffsetParam) : element[UISelection].anchorOffset;
const focusOffset = sanitizeOffset(focusOffsetParam);
const startOffset = Math.min(anchorOffset, focusOffset);
const endOffset = Math.max(anchorOffset, focusOffset);
element[UISelection] = {
anchorOffset,
focusOffset
};
if (element.selectionStart === startOffset && element.selectionEnd === endOffset) {
return;
}
// eslint-disable-next-line no-new-wrappers
const startObj = Object.assign(new Number(startOffset), {
[UISelection]: true
});
try {
element.setSelectionRange(startObj, endOffset);
} catch {
// DOMException for invalid state is expected when calling this
// on an element without support for setSelectionRange
}
}
function getUISelection(element) {
var _element_selectionStart, _element_selectionEnd, _element_UISelection;
const sel = (_element_UISelection = element[UISelection]) !== null && _element_UISelection !== undefined ? _element_UISelection : {
anchorOffset: (_element_selectionStart = element.selectionStart) !== null && _element_selectionStart !== undefined ? _element_selectionStart : 0,
focusOffset: (_element_selectionEnd = element.selectionEnd) !== null && _element_selectionEnd !== undefined ? _element_selectionEnd : 0
};
return {
...sel,
startOffset: Math.min(sel.anchorOffset, sel.focusOffset),
endOffset: Math.max(sel.anchorOffset, sel.focusOffset)
};
}
function hasUISelection(element) {
return !!element[UISelection];
}
/** Flag the IDL selection as clean. This does not change the selection. */ function setUISelectionClean(element) {
element[UISelection] = undefined;
}
export { clearInitialValue, getInitialValue, getUISelection, getUIValue, hasUISelection, isUISelectionStart, isUIValue, setUISelection, setUISelectionClean, setUISelectionRaw, setUIValue, setUIValueClean };

View File

@@ -0,0 +1,27 @@
import { createDataTransfer } from '../utils/dataTransfer/DataTransfer.js';
import '../utils/dataTransfer/Clipboard.js';
import { getWindow } from '../utils/misc/getWindow.js';
import { hasOwnSelection } from '../utils/focus/selection.js';
import { getUISelection, getUIValue } from './UI.js';
function copySelection(target) {
const data = hasOwnSelection(target) ? {
'text/plain': readSelectedValueFromInput(target)
} : {
'text/plain': String(target.ownerDocument.getSelection())
};
const dt = createDataTransfer(getWindow(target));
for(const type in data){
if (data[type]) {
dt.setData(type, data[type]);
}
}
return dt;
}
function readSelectedValueFromInput(target) {
const sel = getUISelection(target);
const val = getUIValue(target);
return val.substring(sel.startOffset, sel.endOffset);
}
export { copySelection };

View File

@@ -0,0 +1,16 @@
import '../utils/dataTransfer/Clipboard.js';
import { isContentEditable } from '../utils/edit/isContentEditable.js';
import { getUIValue } from './UI.js';
function getValueOrTextContent(element) {
// istanbul ignore if
if (!element) {
return null;
}
if (isContentEditable(element)) {
return element.textContent;
}
return getUIValue(element);
}
export { getValueOrTextContent };

View File

@@ -0,0 +1,4 @@
export { clearInitialValue, getUISelection, getUIValue, setUISelection, setUIValue } from './UI.js';
export { getValueOrTextContent } from './getValueOrTextContent.js';
export { copySelection } from './copySelection.js';
export { commitValueAfterInput } from './trackValue.js';

View File

@@ -0,0 +1,99 @@
import { isElementType } from '../utils/misc/isElementType.js';
import '../utils/dataTransfer/Clipboard.js';
import { startTrackValue, trackOrSetValue } from './trackValue.js';
import { setUISelectionClean, setUISelectionRaw, getUIValue, setUIValueClean, isUIValue, isUISelectionStart } from './UI.js';
const Interceptor = Symbol('Interceptor for programmatical calls');
function prepareInterceptor(element, propName, interceptorImpl) {
const prototypeDescriptor = Object.getOwnPropertyDescriptor(element.constructor.prototype, propName);
const objectDescriptor = Object.getOwnPropertyDescriptor(element, propName);
const target = (prototypeDescriptor === null || prototypeDescriptor === undefined ? undefined : prototypeDescriptor.set) ? 'set' : 'value';
/* istanbul ignore if */ if (typeof (prototypeDescriptor === null || prototypeDescriptor === undefined ? undefined : prototypeDescriptor[target]) !== 'function' || prototypeDescriptor[target][Interceptor]) {
throw new Error(`Element ${element.tagName} does not implement "${String(propName)}".`);
}
function intercept(...args) {
const { applyNative = false, realArgs, then } = interceptorImpl.call(this, ...args);
const realFunc = (!applyNative && objectDescriptor || prototypeDescriptor)[target];
if (target === 'set') {
realFunc.call(this, realArgs);
} else {
realFunc.call(this, ...realArgs);
}
then === null || then === undefined ? undefined : then();
}
intercept[Interceptor] = Interceptor;
Object.defineProperty(element, propName, {
...objectDescriptor !== null && objectDescriptor !== undefined ? objectDescriptor : prototypeDescriptor,
[target]: intercept
});
}
function prepareValueInterceptor(element) {
prepareInterceptor(element, 'value', function interceptorImpl(v) {
const isUI = isUIValue(v);
if (isUI) {
startTrackValue(this);
}
return {
applyNative: !!isUI,
realArgs: sanitizeValue(this, v),
then: isUI ? undefined : ()=>trackOrSetValue(this, String(v))
};
});
}
function sanitizeValue(element, v) {
// Workaround for JSDOM
if (isElementType(element, 'input', {
type: 'number'
}) && String(v) !== '' && !Number.isNaN(Number(v))) {
// Setting value to "1." results in `null` in JSDOM
return String(Number(v));
}
return String(v);
}
function prepareSelectionInterceptor(element) {
prepareInterceptor(element, 'setSelectionRange', function interceptorImpl(start, ...others) {
const isUI = isUISelectionStart(start);
return {
applyNative: !!isUI,
realArgs: [
Number(start),
...others
],
then: ()=>isUI ? undefined : setUISelectionClean(element)
};
});
prepareInterceptor(element, 'selectionStart', function interceptorImpl(v) {
return {
realArgs: v,
then: ()=>setUISelectionClean(element)
};
});
prepareInterceptor(element, 'selectionEnd', function interceptorImpl(v) {
return {
realArgs: v,
then: ()=>setUISelectionClean(element)
};
});
prepareInterceptor(element, 'select', function interceptorImpl() {
return {
realArgs: [],
then: ()=>setUISelectionRaw(element, {
anchorOffset: 0,
focusOffset: getUIValue(element).length
})
};
});
}
function prepareRangeTextInterceptor(element) {
prepareInterceptor(element, 'setRangeText', function interceptorImpl(...realArgs) {
return {
realArgs,
then: ()=>{
setUIValueClean(element);
setUISelectionClean(element);
}
};
});
}
export { prepareInterceptor, prepareRangeTextInterceptor, prepareSelectionInterceptor, prepareValueInterceptor };

View File

@@ -0,0 +1,101 @@
import { dispatchDOMEvent } from '../event/dispatchEvent.js';
import '../utils/dataTransfer/Clipboard.js';
import { getActiveElement } from '../utils/focus/getActiveElement.js';
import '@testing-library/dom';
const patched = Symbol('patched focus/blur methods');
function patchFocus(HTMLElement) {
if (HTMLElement.prototype[patched]) {
return;
}
// eslint-disable-next-line @typescript-eslint/unbound-method
const { focus, blur } = HTMLElement.prototype;
Object.defineProperties(HTMLElement.prototype, {
focus: {
configurable: true,
get: ()=>patchedFocus
},
blur: {
configurable: true,
get: ()=>patchedBlur
},
[patched]: {
configurable: true,
get: ()=>({
focus,
blur
})
}
});
let activeCall;
function patchedFocus(options) {
if (this.ownerDocument.visibilityState !== 'hidden') {
return focus.call(this, options);
}
const blurred = getActiveTarget(this.ownerDocument);
if (blurred === this) {
return;
}
const thisCall = Symbol('focus call');
activeCall = thisCall;
if (blurred) {
blur.call(blurred);
dispatchDOMEvent(blurred, 'blur', {
relatedTarget: this
});
dispatchDOMEvent(blurred, 'focusout', {
relatedTarget: activeCall === thisCall ? this : null
});
}
if (activeCall === thisCall) {
focus.call(this, options);
dispatchDOMEvent(this, 'focus', {
relatedTarget: blurred
});
}
if (activeCall === thisCall) {
dispatchDOMEvent(this, 'focusin', {
relatedTarget: blurred
});
}
}
function patchedBlur() {
if (this.ownerDocument.visibilityState !== 'hidden') {
return blur.call(this);
}
const blurred = getActiveTarget(this.ownerDocument);
if (blurred !== this) {
return;
}
const thisCall = Symbol('blur call');
activeCall = thisCall;
blur.call(this);
dispatchDOMEvent(blurred, 'blur', {
relatedTarget: null
});
dispatchDOMEvent(blurred, 'focusout', {
relatedTarget: null
});
}
}
function getActiveTarget(document) {
const active = getActiveElement(document);
return (active === null || active === undefined ? undefined : active.tagName) === 'BODY' ? null : active;
}
function restoreFocus(HTMLElement) {
if (HTMLElement.prototype[patched]) {
const { focus, blur } = HTMLElement.prototype[patched];
Object.defineProperties(HTMLElement.prototype, {
focus: {
configurable: true,
get: ()=>focus
},
blur: {
configurable: true,
get: ()=>blur
}
});
}
}
export { patchFocus, restoreFocus };

View File

@@ -0,0 +1,56 @@
import { dispatchDOMEvent } from '../event/dispatchEvent.js';
import { isElementType } from '../utils/misc/isElementType.js';
import '../utils/dataTransfer/Clipboard.js';
import { getInitialValue, clearInitialValue } from './UI.js';
import '@testing-library/dom';
import { prepareValueInterceptor, prepareSelectionInterceptor, prepareRangeTextInterceptor } from './interceptor.js';
const isPrepared = Symbol('Node prepared with document state workarounds');
function prepareDocument(document) {
if (document[isPrepared]) {
return;
}
document.addEventListener('focus', (e)=>{
const el = e.target;
prepareElement(el);
}, {
capture: true,
passive: true
});
// Our test environment defaults to `document.body` as `activeElement`.
// In other environments this might be `null` when preparing.
// istanbul ignore else
if (document.activeElement) {
prepareElement(document.activeElement);
}
document.addEventListener('blur', (e)=>{
const el = e.target;
const initialValue = getInitialValue(el);
if (initialValue !== undefined) {
if (el.value !== initialValue) {
dispatchDOMEvent(el, 'change');
}
clearInitialValue(el);
}
}, {
capture: true,
passive: true
});
document[isPrepared] = isPrepared;
}
function prepareElement(el) {
if (el[isPrepared]) {
return;
}
if (isElementType(el, [
'input',
'textarea'
])) {
prepareValueInterceptor(el);
prepareSelectionInterceptor(el);
prepareRangeTextInterceptor(el);
}
el[isPrepared] = isPrepared;
}
export { prepareDocument };

View File

@@ -0,0 +1,53 @@
import '../utils/dataTransfer/Clipboard.js';
import { getWindow } from '../utils/misc/getWindow.js';
import { setUIValueClean, setUISelection, hasUISelection } from './UI.js';
const TrackChanges = Symbol('Track programmatic changes for React workaround');
// When the input event happens in the browser, React executes all event handlers
// and if they change state of a controlled value, nothing happens.
// But when we trigger the event handlers in test environment with React@17,
// the changes are rolled back before the state update is applied.
// This results in a reset cursor.
// There might be a better way to work around if we figure out
// why the batched update is executed differently in our test environment.
function isReact17Element(element) {
return Object.getOwnPropertyNames(element).some((k)=>k.startsWith('__react')) && getWindow(element).REACT_VERSION === 17;
}
function startTrackValue(element) {
if (!isReact17Element(element)) {
return;
}
element[TrackChanges] = {
previousValue: String(element.value),
tracked: []
};
}
function trackOrSetValue(element, v) {
var _element_TrackChanges_tracked, _element_TrackChanges;
(_element_TrackChanges = element[TrackChanges]) === null || _element_TrackChanges === undefined ? undefined : (_element_TrackChanges_tracked = _element_TrackChanges.tracked) === null || _element_TrackChanges_tracked === undefined ? undefined : _element_TrackChanges_tracked.push(v);
if (!element[TrackChanges]) {
setUIValueClean(element);
setUISelection(element, {
focusOffset: v.length
});
}
}
function commitValueAfterInput(element, cursorOffset) {
var _changes_tracked;
const changes = element[TrackChanges];
element[TrackChanges] = undefined;
if (!(changes === null || changes === undefined ? undefined : (_changes_tracked = changes.tracked) === null || _changes_tracked === undefined ? undefined : _changes_tracked.length)) {
return;
}
const isJustReactStateUpdate = changes.tracked.length === 2 && changes.tracked[0] === changes.previousValue && changes.tracked[1] === element.value;
if (!isJustReactStateUpdate) {
setUIValueClean(element);
}
if (hasUISelection(element)) {
setUISelection(element, {
focusOffset: isJustReactStateUpdate ? cursorOffset : element.value.length
});
}
}
export { commitValueAfterInput, startTrackValue, trackOrSetValue };

View File

@@ -0,0 +1,30 @@
import { isElementType } from '../../utils/misc/isElementType.js';
import '../../utils/dataTransfer/Clipboard.js';
import { getWindow } from '../../utils/misc/getWindow.js';
import { isFocusable } from '../../utils/focus/isFocusable.js';
import { cloneEvent } from '../../utils/misc/cloneEvent.js';
import { focusElement, blurElement } from '../focus.js';
import { behavior } from './registry.js';
behavior.click = (event, target, instance)=>{
const context = target.closest('button,input,label,select,textarea');
const control = context && isElementType(context, 'label') && context.control;
if (control && control !== target) {
return ()=>{
if (isFocusable(control)) {
focusElement(control);
instance.dispatchEvent(control, cloneEvent(event));
}
};
} else if (isElementType(target, 'input', {
type: 'file'
})) {
return ()=>{
// blur fires when the file selector pops up
blurElement(target);
target.dispatchEvent(new (getWindow(target)).Event('fileDialog'));
// focus fires after the file selector has been closed
focusElement(target);
};
}
};

View File

@@ -0,0 +1,12 @@
import '../../utils/dataTransfer/Clipboard.js';
import { isEditable } from '../../utils/edit/isEditable.js';
import { input } from '../input.js';
import { behavior } from './registry.js';
behavior.cut = (event, target, instance)=>{
return ()=>{
if (isEditable(target)) {
input(instance, target, '', 'deleteByCut');
}
};
};

View File

@@ -0,0 +1,7 @@
import './click.js';
import './cut.js';
import './keydown.js';
import './keypress.js';
import './keyup.js';
import './paste.js';
export { behavior } from './registry.js';

View File

@@ -0,0 +1,126 @@
import { getUIValue, setUISelection } from '../../document/UI.js';
import { getValueOrTextContent } from '../../document/getValueOrTextContent.js';
import { isElementType } from '../../utils/misc/isElementType.js';
import '../../utils/dataTransfer/Clipboard.js';
import { isContentEditable } from '../../utils/edit/isContentEditable.js';
import { isEditable } from '../../utils/edit/isEditable.js';
import { getTabDestination } from '../../utils/focus/getTabDestination.js';
import { hasOwnSelection } from '../../utils/focus/selection.js';
import { focusElement } from '../focus.js';
import { input } from '../input.js';
import { moveSelection } from '../selection/moveSelection.js';
import { selectAll } from '../selection/selectAll.js';
import { setSelectionRange } from '../selection/setSelectionRange.js';
import { walkRadio } from '../radio.js';
import { behavior } from './registry.js';
behavior.keydown = (event, target, instance)=>{
var _keydownBehavior_event_key;
var _keydownBehavior_event_key1;
return (_keydownBehavior_event_key1 = (_keydownBehavior_event_key = keydownBehavior[event.key]) === null || _keydownBehavior_event_key === undefined ? undefined : _keydownBehavior_event_key.call(keydownBehavior, event, target, instance)) !== null && _keydownBehavior_event_key1 !== undefined ? _keydownBehavior_event_key1 : combinationBehavior(event, target, instance);
};
const keydownBehavior = {
ArrowDown: (event, target, instance)=>{
/* istanbul ignore else */ if (isElementType(target, 'input', {
type: 'radio'
})) {
return ()=>walkRadio(instance, target, 1);
}
},
ArrowLeft: (event, target, instance)=>{
if (isElementType(target, 'input', {
type: 'radio'
})) {
return ()=>walkRadio(instance, target, -1);
}
return ()=>moveSelection(target, -1);
},
ArrowRight: (event, target, instance)=>{
if (isElementType(target, 'input', {
type: 'radio'
})) {
return ()=>walkRadio(instance, target, 1);
}
return ()=>moveSelection(target, 1);
},
ArrowUp: (event, target, instance)=>{
/* istanbul ignore else */ if (isElementType(target, 'input', {
type: 'radio'
})) {
return ()=>walkRadio(instance, target, -1);
}
},
Backspace: (event, target, instance)=>{
if (isEditable(target)) {
return ()=>{
input(instance, target, '', 'deleteContentBackward');
};
}
},
Delete: (event, target, instance)=>{
if (isEditable(target)) {
return ()=>{
input(instance, target, '', 'deleteContentForward');
};
}
},
End: (event, target)=>{
if (isElementType(target, [
'input',
'textarea'
]) || isContentEditable(target)) {
return ()=>{
var _getValueOrTextContent;
var _getValueOrTextContent_length;
const newPos = (_getValueOrTextContent_length = (_getValueOrTextContent = getValueOrTextContent(target)) === null || _getValueOrTextContent === undefined ? undefined : _getValueOrTextContent.length) !== null && _getValueOrTextContent_length !== undefined ? _getValueOrTextContent_length : /* istanbul ignore next */ 0;
setSelectionRange(target, newPos, newPos);
};
}
},
Home: (event, target)=>{
if (isElementType(target, [
'input',
'textarea'
]) || isContentEditable(target)) {
return ()=>{
setSelectionRange(target, 0, 0);
};
}
},
PageDown: (event, target)=>{
if (isElementType(target, [
'input'
])) {
return ()=>{
const newPos = getUIValue(target).length;
setSelectionRange(target, newPos, newPos);
};
}
},
PageUp: (event, target)=>{
if (isElementType(target, [
'input'
])) {
return ()=>{
setSelectionRange(target, 0, 0);
};
}
},
Tab: (event, target, instance)=>{
return ()=>{
const dest = getTabDestination(target, instance.system.keyboard.modifiers.Shift);
focusElement(dest);
if (hasOwnSelection(dest)) {
setUISelection(dest, {
anchorOffset: 0,
focusOffset: dest.value.length
});
}
};
}
};
const combinationBehavior = (event, target, instance)=>{
if (event.code === 'KeyA' && instance.system.keyboard.modifiers.Control) {
return ()=>selectAll(target);
}
};

View File

@@ -0,0 +1,49 @@
import { isElementType } from '../../utils/misc/isElementType.js';
import '../../utils/dataTransfer/Clipboard.js';
import { isContentEditable } from '../../utils/edit/isContentEditable.js';
import { isEditable } from '../../utils/edit/isEditable.js';
import { input } from '../input.js';
import { behavior } from './registry.js';
behavior.keypress = (event, target, instance)=>{
if (event.key === 'Enter') {
if (isElementType(target, 'button') || isElementType(target, 'input') && ClickInputOnEnter.includes(target.type) || isElementType(target, 'a') && Boolean(target.href)) {
return ()=>{
instance.dispatchUIEvent(target, 'click');
};
} else if (isElementType(target, 'input')) {
const form = target.form;
const submit = form === null || form === undefined ? undefined : form.querySelector('input[type="submit"], button:not([type]), button[type="submit"]');
if (submit) {
return ()=>instance.dispatchUIEvent(submit, 'click');
} else if (form && SubmitSingleInputOnEnter.includes(target.type) && form.querySelectorAll('input').length === 1) {
return ()=>instance.dispatchUIEvent(form, 'submit');
} else {
return;
}
}
}
if (isEditable(target)) {
const inputType = event.key === 'Enter' ? isContentEditable(target) && !instance.system.keyboard.modifiers.Shift ? 'insertParagraph' : 'insertLineBreak' : 'insertText';
const inputData = event.key === 'Enter' ? '\n' : event.key;
return ()=>input(instance, target, inputData, inputType);
}
};
const ClickInputOnEnter = [
'button',
'color',
'file',
'image',
'reset',
'submit'
];
const SubmitSingleInputOnEnter = [
'email',
'month',
'password',
'search',
'tel',
'text',
'url',
'week'
];

View File

@@ -0,0 +1,15 @@
import { isClickableInput } from '../../utils/click/isClickableInput.js';
import '../../utils/dataTransfer/Clipboard.js';
import { behavior } from './registry.js';
behavior.keyup = (event, target, instance)=>{
var _keyupBehavior_event_key;
return (_keyupBehavior_event_key = keyupBehavior[event.key]) === null || _keyupBehavior_event_key === undefined ? undefined : _keyupBehavior_event_key.call(keyupBehavior, event, target, instance);
};
const keyupBehavior = {
' ': (event, target, instance)=>{
if (isClickableInput(target)) {
return ()=>instance.dispatchUIEvent(target, 'click');
}
}
};

View File

@@ -0,0 +1,16 @@
import '../../utils/dataTransfer/Clipboard.js';
import { isEditable } from '../../utils/edit/isEditable.js';
import { input } from '../input.js';
import { behavior } from './registry.js';
behavior.paste = (event, target, instance)=>{
if (isEditable(target)) {
return ()=>{
var _event_clipboardData;
const insertData = (_event_clipboardData = event.clipboardData) === null || _event_clipboardData === undefined ? undefined : _event_clipboardData.getData('text');
if (insertData) {
input(instance, target, insertData, 'insertFromPaste');
}
};
}
};

View File

@@ -0,0 +1,3 @@
const behavior = {};
export { behavior };

View File

@@ -0,0 +1,205 @@
import '../utils/dataTransfer/Clipboard.js';
import { getWindow } from '../utils/misc/getWindow.js';
import { eventMap } from './eventMap.js';
const eventInitializer = {
ClipboardEvent: [
initClipboardEvent
],
Event: [],
FocusEvent: [
initUIEvent,
initFocusEvent
],
InputEvent: [
initUIEvent,
initInputEvent
],
MouseEvent: [
initUIEvent,
initUIEventModifiers,
initMouseEvent
],
PointerEvent: [
initUIEvent,
initUIEventModifiers,
initMouseEvent,
initPointerEvent
],
KeyboardEvent: [
initUIEvent,
initUIEventModifiers,
initKeyboardEvent
]
};
function createEvent(type, target, init) {
const window = getWindow(target);
const { EventType, defaultInit } = eventMap[type];
const event = new (getEventConstructors(window))[EventType](type, defaultInit);
eventInitializer[EventType].forEach((f)=>f(event, init !== null && init !== undefined ? init : {}));
return event;
}
/* istanbul ignore next */ function getEventConstructors(window) {
var _window_Event;
/* eslint-disable @typescript-eslint/no-unnecessary-condition, @typescript-eslint/no-extraneous-class */ const Event = (_window_Event = window.Event) !== null && _window_Event !== undefined ? _window_Event : class Event {
};
var _window_AnimationEvent;
const AnimationEvent = (_window_AnimationEvent = window.AnimationEvent) !== null && _window_AnimationEvent !== undefined ? _window_AnimationEvent : class AnimationEvent extends Event {
};
var _window_ClipboardEvent;
const ClipboardEvent = (_window_ClipboardEvent = window.ClipboardEvent) !== null && _window_ClipboardEvent !== undefined ? _window_ClipboardEvent : class ClipboardEvent extends Event {
};
var _window_PopStateEvent;
const PopStateEvent = (_window_PopStateEvent = window.PopStateEvent) !== null && _window_PopStateEvent !== undefined ? _window_PopStateEvent : class PopStateEvent extends Event {
};
var _window_ProgressEvent;
const ProgressEvent = (_window_ProgressEvent = window.ProgressEvent) !== null && _window_ProgressEvent !== undefined ? _window_ProgressEvent : class ProgressEvent extends Event {
};
var _window_TransitionEvent;
const TransitionEvent = (_window_TransitionEvent = window.TransitionEvent) !== null && _window_TransitionEvent !== undefined ? _window_TransitionEvent : class TransitionEvent extends Event {
};
var _window_UIEvent;
const UIEvent = (_window_UIEvent = window.UIEvent) !== null && _window_UIEvent !== undefined ? _window_UIEvent : class UIEvent extends Event {
};
var _window_CompositionEvent;
const CompositionEvent = (_window_CompositionEvent = window.CompositionEvent) !== null && _window_CompositionEvent !== undefined ? _window_CompositionEvent : class CompositionEvent extends UIEvent {
};
var _window_FocusEvent;
const FocusEvent = (_window_FocusEvent = window.FocusEvent) !== null && _window_FocusEvent !== undefined ? _window_FocusEvent : class FocusEvent extends UIEvent {
};
var _window_InputEvent;
const InputEvent = (_window_InputEvent = window.InputEvent) !== null && _window_InputEvent !== undefined ? _window_InputEvent : class InputEvent extends UIEvent {
};
var _window_KeyboardEvent;
const KeyboardEvent = (_window_KeyboardEvent = window.KeyboardEvent) !== null && _window_KeyboardEvent !== undefined ? _window_KeyboardEvent : class KeyboardEvent extends UIEvent {
};
var _window_MouseEvent;
const MouseEvent = (_window_MouseEvent = window.MouseEvent) !== null && _window_MouseEvent !== undefined ? _window_MouseEvent : class MouseEvent extends UIEvent {
};
var _window_DragEvent;
const DragEvent = (_window_DragEvent = window.DragEvent) !== null && _window_DragEvent !== undefined ? _window_DragEvent : class DragEvent extends MouseEvent {
};
var _window_PointerEvent;
const PointerEvent = (_window_PointerEvent = window.PointerEvent) !== null && _window_PointerEvent !== undefined ? _window_PointerEvent : class PointerEvent extends MouseEvent {
};
var _window_TouchEvent;
const TouchEvent = (_window_TouchEvent = window.TouchEvent) !== null && _window_TouchEvent !== undefined ? _window_TouchEvent : class TouchEvent extends UIEvent {
};
/* eslint-enable @typescript-eslint/no-unnecessary-condition, @typescript-eslint/no-extraneous-class */ return {
Event,
AnimationEvent,
ClipboardEvent,
PopStateEvent,
ProgressEvent,
TransitionEvent,
UIEvent,
CompositionEvent,
FocusEvent,
InputEvent,
KeyboardEvent,
MouseEvent,
DragEvent,
PointerEvent,
TouchEvent
};
}
function assignProps(obj, props) {
for (const [key, value] of Object.entries(props)){
Object.defineProperty(obj, key, {
get: ()=>value !== null && value !== undefined ? value : null
});
}
}
function sanitizeNumber(n) {
return Number(n !== null && n !== undefined ? n : 0);
}
function initClipboardEvent(event, { clipboardData }) {
assignProps(event, {
clipboardData
});
}
function initFocusEvent(event, { relatedTarget }) {
assignProps(event, {
relatedTarget
});
}
function initInputEvent(event, { data, inputType, isComposing }) {
assignProps(event, {
data,
isComposing: Boolean(isComposing),
inputType: String(inputType)
});
}
function initUIEvent(event, { view, detail }) {
assignProps(event, {
view,
detail: sanitizeNumber(detail !== null && detail !== undefined ? detail : 0)
});
}
function initUIEventModifiers(event, { altKey, ctrlKey, metaKey, shiftKey, modifierAltGraph, modifierCapsLock, modifierFn, modifierFnLock, modifierNumLock, modifierScrollLock, modifierSymbol, modifierSymbolLock }) {
assignProps(event, {
altKey: Boolean(altKey),
ctrlKey: Boolean(ctrlKey),
metaKey: Boolean(metaKey),
shiftKey: Boolean(shiftKey),
getModifierState (k) {
return Boolean({
Alt: altKey,
AltGraph: modifierAltGraph,
CapsLock: modifierCapsLock,
Control: ctrlKey,
Fn: modifierFn,
FnLock: modifierFnLock,
Meta: metaKey,
NumLock: modifierNumLock,
ScrollLock: modifierScrollLock,
Shift: shiftKey,
Symbol: modifierSymbol,
SymbolLock: modifierSymbolLock
}[k]);
}
});
}
function initKeyboardEvent(event, { key, code, location, repeat, isComposing, charCode }) {
assignProps(event, {
key: String(key),
code: String(code),
location: sanitizeNumber(location),
repeat: Boolean(repeat),
isComposing: Boolean(isComposing),
charCode
});
}
function initMouseEvent(event, { x, y, screenX, screenY, clientX = x, clientY = y, button, buttons, relatedTarget, offsetX, offsetY, pageX, pageY }) {
assignProps(event, {
screenX: sanitizeNumber(screenX),
screenY: sanitizeNumber(screenY),
clientX: sanitizeNumber(clientX),
x: sanitizeNumber(clientX),
clientY: sanitizeNumber(clientY),
y: sanitizeNumber(clientY),
button: sanitizeNumber(button),
buttons: sanitizeNumber(buttons),
relatedTarget,
offsetX: sanitizeNumber(offsetX),
offsetY: sanitizeNumber(offsetY),
pageX: sanitizeNumber(pageX),
pageY: sanitizeNumber(pageY)
});
}
function initPointerEvent(event, { pointerId, width, height, pressure, tangentialPressure, tiltX, tiltY, twist, pointerType, isPrimary }) {
assignProps(event, {
pointerId: sanitizeNumber(pointerId),
width: sanitizeNumber(width !== null && width !== undefined ? width : 1),
height: sanitizeNumber(height !== null && height !== undefined ? height : 1),
pressure: sanitizeNumber(pressure),
tangentialPressure: sanitizeNumber(tangentialPressure),
tiltX: sanitizeNumber(tiltX),
tiltY: sanitizeNumber(tiltY),
twist: sanitizeNumber(twist),
pointerType: String(pointerType),
isPrimary: Boolean(isPrimary)
});
}
export { createEvent };

View File

@@ -0,0 +1,50 @@
import './behavior/click.js';
import './behavior/cut.js';
import './behavior/keydown.js';
import './behavior/keypress.js';
import './behavior/keyup.js';
import './behavior/paste.js';
import { behavior } from './behavior/registry.js';
import { wrapEvent } from './wrapEvent.js';
import { isMouseEvent, isKeyboardEvent } from './eventMap.js';
import { createEvent } from './createEvent.js';
function dispatchUIEvent(target, type, init, preventDefault = false) {
if (isMouseEvent(type) || isKeyboardEvent(type)) {
init = {
...init,
...this.system.getUIEventModifiers()
};
}
const event = createEvent(type, target, init);
return dispatchEvent.call(this, target, event, preventDefault);
}
function dispatchEvent(target, event, preventDefault = false) {
var _behavior_type;
const type = event.type;
const behaviorImplementation = preventDefault ? ()=>{} : (_behavior_type = behavior[type]) === null || _behavior_type === undefined ? undefined : _behavior_type.call(behavior, event, target, this);
if (behaviorImplementation) {
event.preventDefault();
let defaultPrevented = false;
Object.defineProperty(event, 'defaultPrevented', {
get: ()=>defaultPrevented
});
Object.defineProperty(event, 'preventDefault', {
value: ()=>{
defaultPrevented = event.cancelable;
}
});
wrapEvent(()=>target.dispatchEvent(event));
if (!defaultPrevented) {
behaviorImplementation();
}
return !defaultPrevented;
}
return wrapEvent(()=>target.dispatchEvent(event));
}
function dispatchDOMEvent(target, type, init) {
const event = createEvent(type, target, init);
wrapEvent(()=>target.dispatchEvent(event));
}
export { dispatchDOMEvent, dispatchEvent, dispatchUIEvent };

View File

@@ -0,0 +1,277 @@
const eventMap = {
auxclick: {
EventType: 'PointerEvent',
defaultInit: {
bubbles: true,
cancelable: true,
composed: true
}
},
beforeinput: {
EventType: 'InputEvent',
defaultInit: {
bubbles: true,
cancelable: true,
composed: true
}
},
blur: {
EventType: 'FocusEvent',
defaultInit: {
bubbles: false,
cancelable: false,
composed: true
}
},
click: {
EventType: 'PointerEvent',
defaultInit: {
bubbles: true,
cancelable: true,
composed: true
}
},
contextmenu: {
EventType: 'PointerEvent',
defaultInit: {
bubbles: true,
cancelable: true,
composed: true
}
},
copy: {
EventType: 'ClipboardEvent',
defaultInit: {
bubbles: true,
cancelable: true,
composed: true
}
},
change: {
EventType: 'Event',
defaultInit: {
bubbles: true,
cancelable: false
}
},
cut: {
EventType: 'ClipboardEvent',
defaultInit: {
bubbles: true,
cancelable: true,
composed: true
}
},
dblclick: {
EventType: 'MouseEvent',
defaultInit: {
bubbles: true,
cancelable: true,
composed: true
}
},
focus: {
EventType: 'FocusEvent',
defaultInit: {
bubbles: false,
cancelable: false,
composed: true
}
},
focusin: {
EventType: 'FocusEvent',
defaultInit: {
bubbles: true,
cancelable: false,
composed: true
}
},
focusout: {
EventType: 'FocusEvent',
defaultInit: {
bubbles: true,
cancelable: false,
composed: true
}
},
keydown: {
EventType: 'KeyboardEvent',
defaultInit: {
bubbles: true,
cancelable: true,
composed: true
}
},
keypress: {
EventType: 'KeyboardEvent',
defaultInit: {
bubbles: true,
cancelable: true,
composed: true
}
},
keyup: {
EventType: 'KeyboardEvent',
defaultInit: {
bubbles: true,
cancelable: true,
composed: true
}
},
paste: {
EventType: 'ClipboardEvent',
defaultInit: {
bubbles: true,
cancelable: true,
composed: true
}
},
input: {
EventType: 'InputEvent',
defaultInit: {
bubbles: true,
cancelable: false,
composed: true
}
},
mousedown: {
EventType: 'MouseEvent',
defaultInit: {
bubbles: true,
cancelable: true,
composed: true
}
},
mouseenter: {
EventType: 'MouseEvent',
defaultInit: {
bubbles: false,
cancelable: false,
composed: true
}
},
mouseleave: {
EventType: 'MouseEvent',
defaultInit: {
bubbles: false,
cancelable: false,
composed: true
}
},
mousemove: {
EventType: 'MouseEvent',
defaultInit: {
bubbles: true,
cancelable: true,
composed: true
}
},
mouseout: {
EventType: 'MouseEvent',
defaultInit: {
bubbles: true,
cancelable: true,
composed: true
}
},
mouseover: {
EventType: 'MouseEvent',
defaultInit: {
bubbles: true,
cancelable: true,
composed: true
}
},
mouseup: {
EventType: 'MouseEvent',
defaultInit: {
bubbles: true,
cancelable: true,
composed: true
}
},
pointerover: {
EventType: 'PointerEvent',
defaultInit: {
bubbles: true,
cancelable: true,
composed: true
}
},
pointerenter: {
EventType: 'PointerEvent',
defaultInit: {
bubbles: false,
cancelable: false
}
},
pointerdown: {
EventType: 'PointerEvent',
defaultInit: {
bubbles: true,
cancelable: true,
composed: true
}
},
pointermove: {
EventType: 'PointerEvent',
defaultInit: {
bubbles: true,
cancelable: true,
composed: true
}
},
pointerup: {
EventType: 'PointerEvent',
defaultInit: {
bubbles: true,
cancelable: true,
composed: true
}
},
pointercancel: {
EventType: 'PointerEvent',
defaultInit: {
bubbles: true,
cancelable: false,
composed: true
}
},
pointerout: {
EventType: 'PointerEvent',
defaultInit: {
bubbles: true,
cancelable: true,
composed: true
}
},
pointerleave: {
EventType: 'PointerEvent',
defaultInit: {
bubbles: false,
cancelable: false
}
},
submit: {
EventType: 'Event',
defaultInit: {
bubbles: true,
cancelable: true
}
}
};
function getEventClass(type) {
return eventMap[type].EventType;
}
const mouseEvents = [
'MouseEvent',
'PointerEvent'
];
function isMouseEvent(type) {
return mouseEvents.includes(getEventClass(type));
}
function isKeyboardEvent(type) {
return getEventClass(type) === 'KeyboardEvent';
}
export { eventMap, isKeyboardEvent, isMouseEvent };

View File

@@ -0,0 +1,31 @@
import '../utils/dataTransfer/Clipboard.js';
import { getActiveElement } from '../utils/focus/getActiveElement.js';
import { isFocusable } from '../utils/focus/isFocusable.js';
import { findClosest } from '../utils/misc/findClosest.js';
import { updateSelectionOnFocus } from './selection/updateSelectionOnFocus.js';
import { wrapEvent } from './wrapEvent.js';
// Browsers do not dispatch FocusEvent if the document does not have focus.
// TODO: simulate FocusEvent in browsers
/**
* Focus closest focusable element.
*/ function focusElement(element) {
const target = findClosest(element, isFocusable);
const activeElement = getActiveElement(element.ownerDocument);
if ((target !== null && target !== undefined ? target : element.ownerDocument.body) === activeElement) {
return;
} else if (target) {
wrapEvent(()=>target.focus());
} else {
wrapEvent(()=>activeElement === null || activeElement === undefined ? undefined : activeElement.blur());
}
updateSelectionOnFocus(target !== null && target !== undefined ? target : element.ownerDocument.body);
}
function blurElement(element) {
if (!isFocusable(element)) return;
const wasActive = getActiveElement(element.ownerDocument) === element;
if (!wasActive) return;
wrapEvent(()=>element.blur());
}
export { blurElement, focusElement };

View File

@@ -0,0 +1,7 @@
export { dispatchDOMEvent, dispatchEvent, dispatchUIEvent } from './dispatchEvent.js';
export { blurElement, focusElement } from './focus.js';
export { input } from './input.js';
import '../utils/dataTransfer/Clipboard.js';
export { setSelectionPerMouseDown } from './selection/setSelectionPerMouse.js';
export { modifySelectionPerMouseMove } from './selection/modifySelectionPerMouse.js';
export { isAllSelected, selectAll } from './selection/selectAll.js';

View File

@@ -0,0 +1,155 @@
import { setUIValue, clearInitialValue, getUIValue } from '../document/UI.js';
import { isElementType } from '../utils/misc/isElementType.js';
import '../utils/dataTransfer/Clipboard.js';
import { isValidDateOrTimeValue, buildTimeValue } from '../utils/edit/timeValue.js';
import { supportsMaxLength, getMaxLength } from '../utils/edit/maxLength.js';
import { getNextCursorPosition } from '../utils/focus/cursor.js';
import { commitValueAfterInput } from '../document/trackValue.js';
import { getInputRange } from './selection/getInputRange.js';
import { setSelection } from './selection/setSelection.js';
function isDateOrTime(element) {
return isElementType(element, 'input') && [
'date',
'time'
].includes(element.type);
}
function input(instance, element, data, inputType = 'insertText') {
const inputRange = getInputRange(element);
/* istanbul ignore if */ if (!inputRange) {
return;
}
// There is no `beforeinput` event on `date` and `time` input
if (!isDateOrTime(element)) {
const unprevented = instance.dispatchUIEvent(element, 'beforeinput', {
inputType,
data
});
if (!unprevented) {
return;
}
}
if ('startContainer' in inputRange) {
editContenteditable(instance, element, inputRange, data, inputType);
} else {
editInputElement(instance, element, inputRange, data, inputType);
}
}
function editContenteditable(instance, element, inputRange, data, inputType) {
let del = false;
if (!inputRange.collapsed) {
del = true;
inputRange.deleteContents();
} else if ([
'deleteContentBackward',
'deleteContentForward'
].includes(inputType)) {
const nextPosition = getNextCursorPosition(inputRange.startContainer, inputRange.startOffset, inputType === 'deleteContentBackward' ? -1 : 1, inputType);
if (nextPosition) {
del = true;
const delRange = inputRange.cloneRange();
if (delRange.comparePoint(nextPosition.node, nextPosition.offset) < 0) {
delRange.setStart(nextPosition.node, nextPosition.offset);
} else {
delRange.setEnd(nextPosition.node, nextPosition.offset);
}
delRange.deleteContents();
}
}
if (data) {
if (inputRange.endContainer.nodeType === 3) {
const offset = inputRange.endOffset;
inputRange.endContainer.insertData(offset, data);
inputRange.setStart(inputRange.endContainer, offset + data.length);
inputRange.setEnd(inputRange.endContainer, offset + data.length);
} else {
const text = element.ownerDocument.createTextNode(data);
inputRange.insertNode(text);
inputRange.setStart(text, data.length);
inputRange.setEnd(text, data.length);
}
}
if (del || data) {
instance.dispatchUIEvent(element, 'input', {
inputType
});
}
}
function editInputElement(instance, element, inputRange, data, inputType) {
let dataToInsert = data;
if (supportsMaxLength(element)) {
const maxLength = getMaxLength(element);
if (maxLength !== undefined && data.length > 0) {
const spaceUntilMaxLength = maxLength - element.value.length;
if (spaceUntilMaxLength > 0) {
dataToInsert = data.substring(0, spaceUntilMaxLength);
} else {
return;
}
}
}
const { newValue, newOffset, oldValue } = calculateNewValue(dataToInsert, element, inputRange, inputType);
if (newValue === oldValue && newOffset === inputRange.startOffset && newOffset === inputRange.endOffset) {
return;
}
if (isElementType(element, 'input', {
type: 'number'
}) && !isValidNumberInput(newValue)) {
return;
}
setUIValue(element, newValue);
setSelection({
focusNode: element,
anchorOffset: newOffset,
focusOffset: newOffset
});
if (isDateOrTime(element)) {
if (isValidDateOrTimeValue(element, newValue)) {
commitInput(instance, element, newOffset, {});
instance.dispatchUIEvent(element, 'change');
clearInitialValue(element);
}
} else {
commitInput(instance, element, newOffset, {
data,
inputType
});
}
}
function calculateNewValue(inputData, node, { startOffset, endOffset }, inputType) {
const value = getUIValue(node);
const prologEnd = Math.max(0, startOffset === endOffset && inputType === 'deleteContentBackward' ? startOffset - 1 : startOffset);
const prolog = value.substring(0, prologEnd);
const epilogStart = Math.min(value.length, startOffset === endOffset && inputType === 'deleteContentForward' ? startOffset + 1 : endOffset);
const epilog = value.substring(epilogStart, value.length);
let newValue = `${prolog}${inputData}${epilog}`;
let newOffset = prologEnd + inputData.length;
if (isElementType(node, 'input', {
type: 'time'
})) {
const builtValue = buildTimeValue(newValue);
if (builtValue !== '' && isValidDateOrTimeValue(node, builtValue)) {
newValue = builtValue;
newOffset = builtValue.length;
}
}
return {
oldValue: value,
newValue,
newOffset
};
}
function commitInput(instance, element, newOffset, inputInit) {
instance.dispatchUIEvent(element, 'input', inputInit);
commitValueAfterInput(element, newOffset);
}
function isValidNumberInput(value) {
var _value_match, _value_match1;
// the browser allows some invalid input but not others
// it allows up to two '-' at any place before any 'e' or one directly following 'e'
// it allows one '.' at any place before e
const valueParts = value.split('e', 2);
return !(/[^\d.\-e]/.test(value) || Number((_value_match = value.match(/-/g)) === null || _value_match === undefined ? undefined : _value_match.length) > 2 || Number((_value_match1 = value.match(/\./g)) === null || _value_match1 === undefined ? undefined : _value_match1.length) > 1 || valueParts[1] && !/^-?\d*$/.test(valueParts[1]));
}
export { input };

View File

@@ -0,0 +1,25 @@
import '../utils/dataTransfer/Clipboard.js';
import { isDisabled } from '../utils/misc/isDisabled.js';
import { getWindow } from '../utils/misc/getWindow.js';
import { focusElement } from './focus.js';
function walkRadio(instance, el, direction) {
const window = getWindow(el);
const group = Array.from(el.ownerDocument.querySelectorAll(el.name ? `input[type="radio"][name="${window.CSS.escape(el.name)}"]` : `input[type="radio"][name=""], input[type="radio"]:not([name])`));
for(let i = group.findIndex((e)=>e === el) + direction;; i += direction){
if (!group[i]) {
i = direction > 0 ? 0 : group.length - 1;
}
if (group[i] === el) {
return;
}
if (isDisabled(group[i])) {
continue;
}
focusElement(group[i]);
instance.dispatchUIEvent(group[i], 'click');
return;
}
}
export { walkRadio };

View File

@@ -0,0 +1,16 @@
import { getTargetTypeAndSelection } from './getTargetTypeAndSelection.js';
/**
* Get the range that would be overwritten by input.
*/ function getInputRange(focusNode) {
const typeAndSelection = getTargetTypeAndSelection(focusNode);
if (typeAndSelection.type === 'input') {
return typeAndSelection.selection;
} else if (typeAndSelection.type === 'contenteditable') {
var _typeAndSelection_selection;
// Multi-range on contenteditable edits the first selection instead of the last
return (_typeAndSelection_selection = typeAndSelection.selection) === null || _typeAndSelection_selection === undefined ? undefined : _typeAndSelection_selection.getRangeAt(0);
}
}
export { getInputRange };

View File

@@ -0,0 +1,29 @@
import { getUISelection } from '../../document/UI.js';
import '../../utils/dataTransfer/Clipboard.js';
import { getContentEditable } from '../../utils/edit/isContentEditable.js';
import { hasOwnSelection } from '../../utils/focus/selection.js';
/**
* Determine which selection logic and selection ranges to consider.
*/ function getTargetTypeAndSelection(node) {
const element = getElement(node);
if (element && hasOwnSelection(element)) {
return {
type: 'input',
selection: getUISelection(element)
};
}
const selection = element === null || element === undefined ? undefined : element.ownerDocument.getSelection();
// It is possible to extend a single-range selection into a contenteditable.
// This results in the range acting like a range outside of contenteditable.
const isCE = getContentEditable(node) && (selection === null || selection === undefined ? undefined : selection.anchorNode) && getContentEditable(selection.anchorNode);
return {
type: isCE ? 'contenteditable' : 'default',
selection
};
}
function getElement(node) {
return node.nodeType === 1 ? node : node.parentElement;
}
export { getTargetTypeAndSelection };

View File

@@ -0,0 +1,9 @@
export { getInputRange } from './getInputRange.js';
export { modifySelection } from './modifySelection.js';
export { moveSelection } from './moveSelection.js';
export { setSelectionPerMouseDown } from './setSelectionPerMouse.js';
export { modifySelectionPerMouseMove } from './modifySelectionPerMouse.js';
export { isAllSelected, selectAll } from './selectAll.js';
export { setSelectionRange } from './setSelectionRange.js';
export { setSelection } from './setSelection.js';
export { updateSelectionOnFocus } from './updateSelectionOnFocus.js';

View File

@@ -0,0 +1,19 @@
import { setUISelection } from '../../document/UI.js';
import '../../utils/dataTransfer/Clipboard.js';
import { getTargetTypeAndSelection } from './getTargetTypeAndSelection.js';
/**
* Extend/shrink the selection like with Shift+Arrows or Shift+Mouse
*/ function modifySelection({ focusNode, focusOffset }) {
var _focusNode_ownerDocument_getSelection, _focusNode_ownerDocument;
const typeAndSelection = getTargetTypeAndSelection(focusNode);
if (typeAndSelection.type === 'input') {
return setUISelection(focusNode, {
anchorOffset: typeAndSelection.selection.anchorOffset,
focusOffset
}, 'modify');
}
(_focusNode_ownerDocument = focusNode.ownerDocument) === null || _focusNode_ownerDocument === undefined ? undefined : (_focusNode_ownerDocument_getSelection = _focusNode_ownerDocument.getSelection()) === null || _focusNode_ownerDocument_getSelection === undefined ? undefined : _focusNode_ownerDocument_getSelection.extend(focusNode, focusOffset);
}
export { modifySelection };

View File

@@ -0,0 +1,38 @@
import { setUISelection } from '../../document/UI.js';
import '../../utils/dataTransfer/Clipboard.js';
import { resolveCaretPosition } from './resolveCaretPosition.js';
function modifySelectionPerMouseMove(selectionRange, { document, target, node, offset }) {
const selectionFocus = resolveCaretPosition({
target,
node,
offset
});
if ('node' in selectionRange) {
// When the mouse is dragged outside of an input/textarea,
// the selection is extended to the beginning or end of the input
// depending on pointer position.
// TODO: extend selection according to pointer position
/* istanbul ignore else */ if (selectionFocus.node === selectionRange.node) {
const anchorOffset = selectionFocus.offset < selectionRange.start ? selectionRange.end : selectionRange.start;
const focusOffset = selectionFocus.offset > selectionRange.end || selectionFocus.offset < selectionRange.start ? selectionFocus.offset : selectionRange.end;
setUISelection(selectionRange.node, {
anchorOffset,
focusOffset
});
}
} else {
const range = selectionRange.cloneRange();
const cmp = range.comparePoint(selectionFocus.node, selectionFocus.offset);
if (cmp < 0) {
range.setStart(selectionFocus.node, selectionFocus.offset);
} else if (cmp > 0) {
range.setEnd(selectionFocus.node, selectionFocus.offset);
}
const selection = document.getSelection();
selection === null || selection === undefined ? undefined : selection.removeAllRanges();
selection === null || selection === undefined ? undefined : selection.addRange(range.cloneRange());
}
}
export { modifySelectionPerMouseMove };

View File

@@ -0,0 +1,36 @@
import { getUISelection } from '../../document/UI.js';
import '../../utils/dataTransfer/Clipboard.js';
import { getNextCursorPosition } from '../../utils/focus/cursor.js';
import { hasOwnSelection } from '../../utils/focus/selection.js';
import { setSelection } from './setSelection.js';
/**
* Move the selection
*/ function moveSelection(node, direction) {
// TODO: implement shift
if (hasOwnSelection(node)) {
const selection = getUISelection(node);
setSelection({
focusNode: node,
focusOffset: selection.startOffset === selection.endOffset ? selection.focusOffset + direction : direction < 0 ? selection.startOffset : selection.endOffset
});
} else {
const selection = node.ownerDocument.getSelection();
if (!(selection === null || selection === undefined ? undefined : selection.focusNode)) {
return;
}
if (selection.isCollapsed) {
const nextPosition = getNextCursorPosition(selection.focusNode, selection.focusOffset, direction);
if (nextPosition) {
setSelection({
focusNode: nextPosition.node,
focusOffset: nextPosition.offset
});
}
} else {
selection[direction < 0 ? 'collapseToStart' : 'collapseToEnd']();
}
}
}
export { moveSelection };

View File

@@ -0,0 +1,59 @@
import { getUIValue } from '../../document/UI.js';
import '../../utils/dataTransfer/Clipboard.js';
import { hasOwnSelection } from '../../utils/focus/selection.js';
function resolveCaretPosition({ target, node, offset }) {
if (hasOwnSelection(target)) {
return {
node: target,
offset: offset !== null && offset !== undefined ? offset : getUIValue(target).length
};
} else if (node) {
return {
node,
offset: offset !== null && offset !== undefined ? offset : node.nodeType === 3 ? node.nodeValue.length : node.childNodes.length
};
}
return findNodeAtTextOffset(target, offset);
}
function findNodeAtTextOffset(node, offset, isRoot = true) {
// When clicking after the content the browser behavior can be complicated:
// 1. If there is textContent after the last element child,
// the cursor is moved there.
// 2. If there is textContent in the last element child,
// the browser moves the cursor to the last non-empty text node inside this element.
// 3. Otherwise the cursor is moved to the end of the target.
let i = offset === undefined ? node.childNodes.length - 1 : 0;
const step = offset === undefined ? -1 : 1;
while(offset === undefined ? i >= (isRoot ? Math.max(node.childNodes.length - 1, 0) : 0) : i <= node.childNodes.length){
if (offset && i === node.childNodes.length) {
throw new Error('The given offset is out of bounds.');
}
const c = node.childNodes.item(i);
const text = String(c.textContent);
if (text.length) {
if (offset !== undefined && text.length < offset) {
offset -= text.length;
} else if (c.nodeType === 1) {
return findNodeAtTextOffset(c, offset, false);
} else {
// The pre-commit hooks keeps changing this
// See https://github.com/kentcdodds/kcd-scripts/issues/218
/* istanbul ignore else */ // eslint-disable-next-line no-lonely-if
if (c.nodeType === 3) {
return {
node: c,
offset: offset !== null && offset !== undefined ? offset : c.nodeValue.length
};
}
}
}
i += step;
}
return {
node,
offset: node.childNodes.length
};
}
export { resolveCaretPosition };

View File

@@ -0,0 +1,35 @@
import { getUIValue, getUISelection } from '../../document/UI.js';
import '../../utils/dataTransfer/Clipboard.js';
import { getContentEditable } from '../../utils/edit/isContentEditable.js';
import { hasOwnSelection } from '../../utils/focus/selection.js';
import { setSelection } from './setSelection.js';
/**
* Expand a selection like the browser does when pressing Ctrl+A.
*/ function selectAll(target) {
if (hasOwnSelection(target)) {
return setSelection({
focusNode: target,
anchorOffset: 0,
focusOffset: getUIValue(target).length
});
}
var _getContentEditable;
const focusNode = (_getContentEditable = getContentEditable(target)) !== null && _getContentEditable !== undefined ? _getContentEditable : target.ownerDocument.body;
setSelection({
focusNode,
anchorOffset: 0,
focusOffset: focusNode.childNodes.length
});
}
function isAllSelected(target) {
if (hasOwnSelection(target)) {
return getUISelection(target).startOffset === 0 && getUISelection(target).endOffset === getUIValue(target).length;
}
var _getContentEditable;
const focusNode = (_getContentEditable = getContentEditable(target)) !== null && _getContentEditable !== undefined ? _getContentEditable : target.ownerDocument.body;
const selection = target.ownerDocument.getSelection();
return (selection === null || selection === undefined ? undefined : selection.anchorNode) === focusNode && selection.focusNode === focusNode && selection.anchorOffset === 0 && selection.focusOffset === focusNode.childNodes.length;
}
export { isAllSelected, selectAll };

View File

@@ -0,0 +1,19 @@
import { setUISelection } from '../../document/UI.js';
import '../../utils/dataTransfer/Clipboard.js';
import { getTargetTypeAndSelection } from './getTargetTypeAndSelection.js';
/**
* Set the selection
*/ function setSelection({ focusNode, focusOffset, anchorNode = focusNode, anchorOffset = focusOffset }) {
var _anchorNode_ownerDocument_getSelection, _anchorNode_ownerDocument;
const typeAndSelection = getTargetTypeAndSelection(focusNode);
if (typeAndSelection.type === 'input') {
return setUISelection(focusNode, {
anchorOffset,
focusOffset
});
}
(_anchorNode_ownerDocument = anchorNode.ownerDocument) === null || _anchorNode_ownerDocument === undefined ? undefined : (_anchorNode_ownerDocument_getSelection = _anchorNode_ownerDocument.getSelection()) === null || _anchorNode_ownerDocument_getSelection === undefined ? undefined : _anchorNode_ownerDocument_getSelection.setBaseAndExtent(anchorNode, anchorOffset, focusNode, focusOffset);
}
export { setSelection };

View File

@@ -0,0 +1,79 @@
import { getUIValue, setUISelection } from '../../document/UI.js';
import '../../utils/dataTransfer/Clipboard.js';
import { hasNoSelection, hasOwnSelection } from '../../utils/focus/selection.js';
import { resolveCaretPosition } from './resolveCaretPosition.js';
function setSelectionPerMouseDown({ document, target, clickCount, node, offset }) {
if (hasNoSelection(target)) {
return;
}
const targetHasOwnSelection = hasOwnSelection(target);
// On non-input elements the text selection per multiple click
// can extend beyond the target boundaries.
// The exact mechanism what is considered in the same line is unclear.
// Looks it might be every inline element.
// TODO: Check what might be considered part of the same line of text.
const text = String(targetHasOwnSelection ? getUIValue(target) : target.textContent);
const [start, end] = node ? // which elements might be considered in the same line of text.
// TODO: support expanding initial range on multiple clicks if node is given
[
offset,
offset
] : getTextRange(text, offset, clickCount);
// TODO: implement modifying selection per shift/ctrl+mouse
if (targetHasOwnSelection) {
setUISelection(target, {
anchorOffset: start !== null && start !== undefined ? start : text.length,
focusOffset: end !== null && end !== undefined ? end : text.length
});
return {
node: target,
start: start !== null && start !== undefined ? start : 0,
end: end !== null && end !== undefined ? end : text.length
};
} else {
const { node: startNode, offset: startOffset } = resolveCaretPosition({
target,
node,
offset: start
});
const { node: endNode, offset: endOffset } = resolveCaretPosition({
target,
node,
offset: end
});
const range = target.ownerDocument.createRange();
try {
range.setStart(startNode, startOffset);
range.setEnd(endNode, endOffset);
} catch (e) {
throw new Error('The given offset is out of bounds.');
}
const selection = document.getSelection();
selection === null || selection === undefined ? undefined : selection.removeAllRanges();
selection === null || selection === undefined ? undefined : selection.addRange(range.cloneRange());
return range;
}
}
function getTextRange(text, pos, clickCount) {
if (clickCount % 3 === 1 || text.length === 0) {
return [
pos,
pos
];
}
const textPos = pos !== null && pos !== undefined ? pos : text.length;
if (clickCount % 3 === 2) {
return [
textPos - text.substr(0, pos).match(/(\w+|\s+|\W)?$/)[0].length,
pos === undefined ? pos : pos + text.substr(pos).match(/^(\w+|\s+|\W)?/)[0].length
];
}
// triple click
return [
textPos - text.substr(0, pos).match(/[^\r\n]*$/)[0].length,
pos === undefined ? pos : pos + text.substr(pos).match(/^[^\r\n]*/)[0].length
];
}
export { setSelectionPerMouseDown };

View File

@@ -0,0 +1,29 @@
import '../../utils/dataTransfer/Clipboard.js';
import { isContentEditable } from '../../utils/edit/isContentEditable.js';
import { hasOwnSelection } from '../../utils/focus/selection.js';
import { setSelection } from './setSelection.js';
/**
* Backward-compatible selection.
*
* Handles input elements and contenteditable if it only contains a single text node.
*/ function setSelectionRange(element, anchorOffset, focusOffset) {
var _element_firstChild;
if (hasOwnSelection(element)) {
return setSelection({
focusNode: element,
anchorOffset,
focusOffset
});
}
/* istanbul ignore else */ if (isContentEditable(element) && ((_element_firstChild = element.firstChild) === null || _element_firstChild === undefined ? undefined : _element_firstChild.nodeType) === 3) {
return setSelection({
focusNode: element.firstChild,
anchorOffset,
focusOffset
});
}
/* istanbul ignore next */ throw new Error('Not implemented. The result of this interaction is unreliable.');
}
export { setSelectionRange };

View File

@@ -0,0 +1,38 @@
import '../../utils/dataTransfer/Clipboard.js';
import { getContentEditable } from '../../utils/edit/isContentEditable.js';
import { hasOwnSelection } from '../../utils/focus/selection.js';
// The browser implementation seems to have changed.
// When focus is inside <input type="text"/>,
// Chrome updates Selection to be collapsed at the position of the input element.
// TODO: update implementation to match that of current browsers
/**
* Reset the Document Selection when moving focus into an element
* with own selection implementation.
*/ function updateSelectionOnFocus(element) {
const selection = element.ownerDocument.getSelection();
/* istanbul ignore if */ if (!(selection === null || selection === undefined ? undefined : selection.focusNode)) {
return;
}
// If the focus moves inside an element with own selection implementation,
// the document selection will be this element.
// But if the focused element is inside a contenteditable,
// 1) a collapsed selection will be retained.
// 2) other selections will be replaced by a cursor
// 2.a) at the start of the first child if it is a text node
// 2.b) at the start of the contenteditable.
if (hasOwnSelection(element)) {
const contenteditable = getContentEditable(selection.focusNode);
if (contenteditable) {
if (!selection.isCollapsed) {
var _contenteditable_firstChild;
const focusNode = ((_contenteditable_firstChild = contenteditable.firstChild) === null || _contenteditable_firstChild === undefined ? undefined : _contenteditable_firstChild.nodeType) === 3 ? contenteditable.firstChild : contenteditable;
selection.setBaseAndExtent(focusNode, 0, focusNode, 0);
}
} else {
selection.setBaseAndExtent(element, 0, element, 0);
}
}
}
export { updateSelectionOnFocus };

View File

@@ -0,0 +1 @@

View File

@@ -0,0 +1,7 @@
import { getConfig } from '@testing-library/dom';
function wrapEvent(cb, _element) {
return getConfig().eventWrapper(cb);
}
export { wrapEvent };

View File

@@ -0,0 +1,2 @@
export { userEvent as default, userEvent } from './setup/index.js';
export { PointerEventsCheckLevel } from './options.js';

View File

@@ -0,0 +1,37 @@
import '../utils/dataTransfer/Clipboard.js';
import { wait } from '../utils/misc/wait.js';
import { parseKeyDef } from './parseKeyDef.js';
async function keyboard(text) {
const actions = parseKeyDef(this.config.keyboardMap, text);
for(let i = 0; i < actions.length; i++){
await wait(this.config);
await keyboardAction(this, actions[i]);
}
}
async function keyboardAction(instance, { keyDef, releasePrevious, releaseSelf, repeat }) {
const { system } = instance;
// Release the key automatically if it was pressed before.
if (system.keyboard.isKeyPressed(keyDef)) {
await system.keyboard.keyup(instance, keyDef);
}
if (!releasePrevious) {
for(let i = 1; i <= repeat; i++){
await system.keyboard.keydown(instance, keyDef);
if (i < repeat) {
await wait(instance.config);
}
}
// Release the key only on the last iteration on `state.repeatKey`.
if (releaseSelf) {
await system.keyboard.keyup(instance, keyDef);
}
}
}
async function releaseAllKeys(instance) {
for (const k of instance.system.keyboard.getPressedKeys()){
await instance.system.keyboard.keyup(instance, k);
}
}
export { keyboard, releaseAllKeys };

View File

@@ -0,0 +1,176 @@
import { DOM_KEY_LOCATION } from '../system/keyboard.js';
/**
* Mapping for a default US-104-QWERTY keyboard
*/ const defaultKeyMap = [
// alphanumeric block - writing system
...'0123456789'.split('').map((c)=>({
code: `Digit${c}`,
key: c
})),
...')!@#$%^&*('.split('').map((c, i)=>({
code: `Digit${i}`,
key: c,
shiftKey: true
})),
...'abcdefghijklmnopqrstuvwxyz'.split('').map((c)=>({
code: `Key${c.toUpperCase()}`,
key: c
})),
...'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('').map((c)=>({
code: `Key${c}`,
key: c,
shiftKey: true
})),
{
code: 'BracketLeft',
key: '['
},
{
code: 'BracketLeft',
key: '{',
shiftKey: true
},
{
code: 'BracketRight',
key: ']'
},
{
code: 'BracketRight',
key: '}',
shiftKey: true
},
// alphanumeric block - functional
{
code: 'Space',
key: ' '
},
{
code: 'AltLeft',
key: 'Alt',
location: DOM_KEY_LOCATION.LEFT
},
{
code: 'AltRight',
key: 'Alt',
location: DOM_KEY_LOCATION.RIGHT
},
{
code: 'ShiftLeft',
key: 'Shift',
location: DOM_KEY_LOCATION.LEFT
},
{
code: 'ShiftRight',
key: 'Shift',
location: DOM_KEY_LOCATION.RIGHT
},
{
code: 'ControlLeft',
key: 'Control',
location: DOM_KEY_LOCATION.LEFT
},
{
code: 'ControlRight',
key: 'Control',
location: DOM_KEY_LOCATION.RIGHT
},
{
code: 'MetaLeft',
key: 'Meta',
location: DOM_KEY_LOCATION.LEFT
},
{
code: 'MetaRight',
key: 'Meta',
location: DOM_KEY_LOCATION.RIGHT
},
{
code: 'OSLeft',
key: 'OS',
location: DOM_KEY_LOCATION.LEFT
},
{
code: 'OSRight',
key: 'OS',
location: DOM_KEY_LOCATION.RIGHT
},
{
code: 'ContextMenu',
key: 'ContextMenu'
},
{
code: 'Tab',
key: 'Tab'
},
{
code: 'CapsLock',
key: 'CapsLock'
},
{
code: 'Backspace',
key: 'Backspace'
},
{
code: 'Enter',
key: 'Enter'
},
// function
{
code: 'Escape',
key: 'Escape'
},
// arrows
{
code: 'ArrowUp',
key: 'ArrowUp'
},
{
code: 'ArrowDown',
key: 'ArrowDown'
},
{
code: 'ArrowLeft',
key: 'ArrowLeft'
},
{
code: 'ArrowRight',
key: 'ArrowRight'
},
// control pad
{
code: 'Home',
key: 'Home'
},
{
code: 'End',
key: 'End'
},
{
code: 'Delete',
key: 'Delete'
},
{
code: 'PageUp',
key: 'PageUp'
},
{
code: 'PageDown',
key: 'PageDown'
},
// Special keys that are not part of a default US-layout but included for specific behavior
{
code: 'Fn',
key: 'Fn'
},
{
code: 'Symbol',
key: 'Symbol'
},
{
code: 'AltRight',
key: 'AltGraph'
}
];
export { defaultKeyMap };

View File

@@ -0,0 +1,43 @@
import '../utils/dataTransfer/Clipboard.js';
import { readNextDescriptor } from '../utils/keyDef/readNextDescriptor.js';
/**
* Parse key definitions per `keyboardMap`
*
* Keys can be referenced by `{key}` or `{special}` as well as physical locations per `[code]`.
* Everything else will be interpreted as a typed character - e.g. `a`.
* Brackets `{` and `[` can be escaped by doubling - e.g. `foo[[bar` translates to `foo[bar`.
* Keeping the key pressed can be written as `{key>}`.
* When keeping the key pressed you can choose how long (how many keydown and keypress) the key is pressed `{key>3}`.
* You can then release the key per `{key>3/}` or keep it pressed and continue with the next key.
*/ function parseKeyDef(keyboardMap, text) {
const defs = [];
do {
const { type, descriptor, consumedLength, releasePrevious, releaseSelf = true, repeat } = readNextDescriptor(text, 'keyboard');
var _keyboardMap_find;
const keyDef = (_keyboardMap_find = keyboardMap.find((def)=>{
if (type === '[') {
var _def_code;
return ((_def_code = def.code) === null || _def_code === undefined ? undefined : _def_code.toLowerCase()) === descriptor.toLowerCase();
} else if (type === '{') {
var _def_key;
return ((_def_key = def.key) === null || _def_key === undefined ? undefined : _def_key.toLowerCase()) === descriptor.toLowerCase();
}
return def.key === descriptor;
})) !== null && _keyboardMap_find !== undefined ? _keyboardMap_find : {
key: 'Unknown',
code: 'Unknown',
[type === '[' ? 'code' : 'key']: descriptor
};
defs.push({
keyDef,
releasePrevious,
releaseSelf,
repeat
});
text = text.slice(consumedLength);
}while (text)
return defs;
}
export { parseKeyDef };

View File

@@ -0,0 +1,12 @@
var PointerEventsCheckLevel = /*#__PURE__*/ function(PointerEventsCheckLevel) {
/**
* Check pointer events on every user interaction that triggers a bunch of events.
* E.g. once for releasing a mouse button even though this triggers `pointerup`, `mouseup`, `click`, etc...
*/ PointerEventsCheckLevel[PointerEventsCheckLevel["EachTrigger"] = 4] = "EachTrigger";
/** Check each target once per call to pointer (related) API */ PointerEventsCheckLevel[PointerEventsCheckLevel["EachApiCall"] = 2] = "EachApiCall";
/** Check each event target once */ PointerEventsCheckLevel[PointerEventsCheckLevel["EachTarget"] = 1] = "EachTarget";
/** No pointer events check */ PointerEventsCheckLevel[PointerEventsCheckLevel["Never"] = 0] = "Never";
return PointerEventsCheckLevel;
}({});
export { PointerEventsCheckLevel };

View File

@@ -0,0 +1,3 @@
{
"type": "module"
}

View File

@@ -0,0 +1,72 @@
import '../utils/dataTransfer/Clipboard.js';
import { setLevelRef, ApiLevel } from '../utils/misc/level.js';
import { wait } from '../utils/misc/wait.js';
import { parseKeyDef } from './parseKeyDef.js';
async function pointer(input) {
const { pointerMap } = this.config;
const actions = [];
(Array.isArray(input) ? input : [
input
]).forEach((actionInput)=>{
if (typeof actionInput === 'string') {
actions.push(...parseKeyDef(pointerMap, actionInput));
} else if ('keys' in actionInput) {
actions.push(...parseKeyDef(pointerMap, actionInput.keys).map((i)=>({
...actionInput,
...i
})));
} else {
actions.push(actionInput);
}
});
for(let i = 0; i < actions.length; i++){
await wait(this.config);
await pointerAction(this, actions[i]);
}
this.system.pointer.resetClickCount();
}
async function pointerAction(instance, action) {
var _previousPosition_caret, _previousPosition_caret1;
const pointerName = 'pointerName' in action && action.pointerName ? action.pointerName : 'keyDef' in action ? instance.system.pointer.getPointerName(action.keyDef) : 'mouse';
const previousPosition = instance.system.pointer.getPreviousPosition(pointerName);
var _action_target, _action_coords, _action_node, _action_offset;
const position = {
target: (_action_target = action.target) !== null && _action_target !== undefined ? _action_target : getPrevTarget(instance, previousPosition),
coords: (_action_coords = action.coords) !== null && _action_coords !== undefined ? _action_coords : previousPosition === null || previousPosition === undefined ? undefined : previousPosition.coords,
caret: {
node: (_action_node = action.node) !== null && _action_node !== undefined ? _action_node : hasCaretPosition(action) ? undefined : previousPosition === null || previousPosition === undefined ? undefined : (_previousPosition_caret = previousPosition.caret) === null || _previousPosition_caret === undefined ? undefined : _previousPosition_caret.node,
offset: (_action_offset = action.offset) !== null && _action_offset !== undefined ? _action_offset : hasCaretPosition(action) ? undefined : previousPosition === null || previousPosition === undefined ? undefined : (_previousPosition_caret1 = previousPosition.caret) === null || _previousPosition_caret1 === undefined ? undefined : _previousPosition_caret1.offset
}
};
if ('keyDef' in action) {
if (instance.system.pointer.isKeyPressed(action.keyDef)) {
setLevelRef(instance, ApiLevel.Trigger);
await instance.system.pointer.release(instance, action.keyDef, position);
}
if (!action.releasePrevious) {
setLevelRef(instance, ApiLevel.Trigger);
await instance.system.pointer.press(instance, action.keyDef, position);
if (action.releaseSelf) {
setLevelRef(instance, ApiLevel.Trigger);
await instance.system.pointer.release(instance, action.keyDef, position);
}
}
} else {
setLevelRef(instance, ApiLevel.Trigger);
await instance.system.pointer.move(instance, pointerName, position);
}
}
function hasCaretPosition(action) {
var _action_target, _ref;
return !!((_ref = (_action_target = action.target) !== null && _action_target !== undefined ? _action_target : action.node) !== null && _ref !== undefined ? _ref : action.offset !== undefined);
}
function getPrevTarget(instance, position) {
if (!position) {
throw new Error('This pointer has no previous position. Provide a target property!');
}
var _position_target;
return (_position_target = position.target) !== null && _position_target !== undefined ? _position_target : instance.config.document.body;
}
export { pointer };

View File

@@ -0,0 +1,31 @@
const defaultKeyMap = [
{
name: 'MouseLeft',
pointerType: 'mouse',
button: 'primary'
},
{
name: 'MouseRight',
pointerType: 'mouse',
button: 'secondary'
},
{
name: 'MouseMiddle',
pointerType: 'mouse',
button: 'auxiliary'
},
{
name: 'TouchA',
pointerType: 'touch'
},
{
name: 'TouchB',
pointerType: 'touch'
},
{
name: 'TouchC',
pointerType: 'touch'
}
];
export { defaultKeyMap };

View File

@@ -0,0 +1,21 @@
import '../utils/dataTransfer/Clipboard.js';
import { readNextDescriptor } from '../utils/keyDef/readNextDescriptor.js';
function parseKeyDef(pointerMap, keys) {
const defs = [];
do {
const { descriptor, consumedLength, releasePrevious, releaseSelf = true } = readNextDescriptor(keys, 'pointer');
const keyDef = pointerMap.find((p)=>p.name === descriptor);
if (keyDef) {
defs.push({
keyDef,
releasePrevious,
releaseSelf
});
}
keys = keys.slice(consumedLength);
}while (keys)
return defs;
}
export { parseKeyDef };

View File

@@ -0,0 +1,33 @@
import { click, dblClick, tripleClick } from '../convenience/click.js';
import { hover, unhover } from '../convenience/hover.js';
import { tab } from '../convenience/tab.js';
import { keyboard } from '../keyboard/index.js';
import { copy } from '../clipboard/copy.js';
import { cut } from '../clipboard/cut.js';
import { paste } from '../clipboard/paste.js';
import { pointer } from '../pointer/index.js';
import { clear } from '../utility/clear.js';
import { deselectOptions, selectOptions } from '../utility/selectOptions.js';
import { type } from '../utility/type.js';
import { upload } from '../utility/upload.js';
const userEventApi = {
click,
dblClick,
tripleClick,
hover,
unhover,
tab,
keyboard,
copy,
cut,
paste,
pointer,
clear,
deselectOptions,
selectOptions,
type,
upload
};
export { userEventApi };

View File

@@ -0,0 +1,58 @@
import { setupDirect } from './setup.js';
function clear(element) {
return setupDirect().api.clear(element);
}
function click(element, options = {}) {
return setupDirect(options, element).api.click(element);
}
function copy(options = {}) {
return setupDirect(options).api.copy();
}
function cut(options = {}) {
return setupDirect(options).api.cut();
}
function dblClick(element, options = {}) {
return setupDirect(options).api.dblClick(element);
}
function deselectOptions(select, values, options = {}) {
return setupDirect(options).api.deselectOptions(select, values);
}
function hover(element, options = {}) {
return setupDirect(options).api.hover(element);
}
async function keyboard(text, options = {}) {
const { api, system } = setupDirect(options);
return api.keyboard(text).then(()=>system);
}
async function pointer(input, options = {}) {
const { api, system } = setupDirect(options);
return api.pointer(input).then(()=>system);
}
function paste(clipboardData, options) {
return setupDirect(options).api.paste(clipboardData);
}
function selectOptions(select, values, options = {}) {
return setupDirect(options).api.selectOptions(select, values);
}
function tripleClick(element, options = {}) {
return setupDirect(options).api.tripleClick(element);
}
function type(element, text, options = {}) {
return setupDirect(options, element).api.type(element, text, options);
}
function unhover(element, options = {}) {
const { api, system } = setupDirect(options);
system.pointer.setMousePosition({
target: element
});
return api.unhover(element);
}
function upload(element, fileOrFiles, options = {}) {
return setupDirect(options).api.upload(element, fileOrFiles);
}
function tab(options = {}) {
return setupDirect().api.tab(options);
}
export { clear, click, copy, cut, dblClick, deselectOptions, hover, keyboard, paste, pointer, selectOptions, tab, tripleClick, type, unhover, upload };

View File

@@ -0,0 +1,9 @@
import { setupMain } from './setup.js';
import * as directApi from './directApi.js';
const userEvent = {
...directApi,
setup: setupMain
};
export { userEvent };

View File

@@ -0,0 +1,119 @@
import { patchFocus } from '../document/patchFocus.js';
import { prepareDocument } from '../document/prepareDocument.js';
import { dispatchEvent, dispatchUIEvent } from '../event/dispatchEvent.js';
import { attachClipboardStubToView } from '../utils/dataTransfer/Clipboard.js';
import { getWindow } from '../utils/misc/getWindow.js';
import { getDocumentFromNode } from '../utils/misc/getDocumentFromNode.js';
import { setLevelRef, ApiLevel } from '../utils/misc/level.js';
import { wait } from '../utils/misc/wait.js';
import { PointerEventsCheckLevel } from '../options.js';
import '@testing-library/dom';
import { defaultKeyMap } from '../keyboard/keyMap.js';
import { defaultKeyMap as defaultKeyMap$1 } from '../pointer/keyMap.js';
import { System } from '../system/index.js';
import { userEventApi } from './api.js';
import { wrapAsync } from './wrapAsync.js';
/**
* Default options applied when API is called per `userEvent.anyApi()`
*/ const defaultOptionsDirect = {
applyAccept: true,
autoModify: true,
delay: 0,
document: globalThis.document,
keyboardMap: defaultKeyMap,
pointerMap: defaultKeyMap$1,
pointerEventsCheck: PointerEventsCheckLevel.EachApiCall,
skipAutoClose: false,
skipClick: false,
skipHover: false,
writeToClipboard: false,
advanceTimers: ()=>Promise.resolve()
};
/**
* Default options applied when API is called per `userEvent().anyApi()`
*/ const defaultOptionsSetup = {
...defaultOptionsDirect,
writeToClipboard: true
};
function createConfig(options = {}, defaults = defaultOptionsSetup, node) {
const document = getDocument(options, node, defaults);
return {
...defaults,
...options,
document
};
}
/**
* Start a "session" with userEvent.
* All APIs returned by this function share an input device state and a default configuration.
*/ function setupMain(options = {}) {
const config = createConfig(options);
prepareDocument(config.document);
patchFocus(getWindow(config.document).HTMLElement);
var _config_document_defaultView;
const view = (_config_document_defaultView = config.document.defaultView) !== null && _config_document_defaultView !== undefined ? _config_document_defaultView : /* istanbul ignore next */ globalThis.window;
attachClipboardStubToView(view);
return createInstance(config).api;
}
/**
* Setup in direct call per `userEvent.anyApi()`
*/ function setupDirect({ keyboardState, pointerState, ...options } = {}, node) {
const config = createConfig(options, defaultOptionsDirect, node);
prepareDocument(config.document);
patchFocus(getWindow(config.document).HTMLElement);
var _ref;
const system = (_ref = pointerState !== null && pointerState !== undefined ? pointerState : keyboardState) !== null && _ref !== undefined ? _ref : new System();
return {
api: createInstance(config, system).api,
system
};
}
/**
* Create a set of callbacks with different default settings but the same state.
*/ function setupSub(options) {
return createInstance({
...this.config,
...options
}, this.system).api;
}
function wrapAndBindImpl(instance, impl) {
function method(...args) {
setLevelRef(instance, ApiLevel.Call);
return wrapAsync(()=>impl.apply(instance, args).then(async (ret)=>{
await wait(instance.config);
return ret;
}));
}
Object.defineProperty(method, 'name', {
get: ()=>impl.name
});
return method;
}
function createInstance(config, system = new System()) {
const instance = {};
Object.assign(instance, {
config,
dispatchEvent: dispatchEvent.bind(instance),
dispatchUIEvent: dispatchUIEvent.bind(instance),
system,
levelRefs: {},
...userEventApi
});
return {
instance,
api: {
...Object.fromEntries(Object.entries(userEventApi).map(([name, api])=>[
name,
wrapAndBindImpl(instance, api)
])),
setup: setupSub.bind(instance)
}
};
}
function getDocument(options, node, defaults) {
var _options_document, _ref;
return (_ref = (_options_document = options.document) !== null && _options_document !== undefined ? _options_document : node && getDocumentFromNode(node)) !== null && _ref !== undefined ? _ref : defaults.document;
}
export { createConfig, createInstance, setupDirect, setupMain, setupSub };

View File

@@ -0,0 +1,9 @@
import { getConfig } from '@testing-library/dom';
/**
* Wrap an internal Promise
*/ function wrapAsync(implementation) {
return getConfig().asyncWrapper(implementation);
}
export { wrapAsync };

View File

@@ -0,0 +1,42 @@
import { KeyboardHost } from './keyboard.js';
import { PointerHost } from './pointer/index.js';
function _define_property(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
/**
* @internal Do not create/alter this by yourself as this type might be subject to changes.
*/ class System {
getUIEventModifiers() {
return {
altKey: this.keyboard.modifiers.Alt,
ctrlKey: this.keyboard.modifiers.Control,
metaKey: this.keyboard.modifiers.Meta,
shiftKey: this.keyboard.modifiers.Shift,
modifierAltGraph: this.keyboard.modifiers.AltGraph,
modifierCapsLock: this.keyboard.modifiers.CapsLock,
modifierFn: this.keyboard.modifiers.Fn,
modifierFnLock: this.keyboard.modifiers.FnLock,
modifierNumLock: this.keyboard.modifiers.NumLock,
modifierScrollLock: this.keyboard.modifiers.ScrollLock,
modifierSymbol: this.keyboard.modifiers.Symbol,
modifierSymbolLock: this.keyboard.modifiers.SymbolLock
};
}
constructor(){
_define_property(this, "keyboard", new KeyboardHost(this));
_define_property(this, "pointer", new PointerHost(this));
}
}
export { System };

View File

@@ -0,0 +1,166 @@
import '../utils/dataTransfer/Clipboard.js';
import { getActiveElementOrBody } from '../utils/focus/getActiveElement.js';
function _define_property(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
var DOM_KEY_LOCATION = /*#__PURE__*/ function(DOM_KEY_LOCATION) {
DOM_KEY_LOCATION[DOM_KEY_LOCATION["STANDARD"] = 0] = "STANDARD";
DOM_KEY_LOCATION[DOM_KEY_LOCATION["LEFT"] = 1] = "LEFT";
DOM_KEY_LOCATION[DOM_KEY_LOCATION["RIGHT"] = 2] = "RIGHT";
DOM_KEY_LOCATION[DOM_KEY_LOCATION["NUMPAD"] = 3] = "NUMPAD";
return DOM_KEY_LOCATION;
}({});
const modifierKeys = [
'Alt',
'AltGraph',
'Control',
'Fn',
'Meta',
'Shift',
'Symbol'
];
function isModifierKey(key) {
return modifierKeys.includes(key);
}
const modifierLocks = [
'CapsLock',
'FnLock',
'NumLock',
'ScrollLock',
'SymbolLock'
];
function isModifierLock(key) {
return modifierLocks.includes(key);
}
class KeyboardHost {
isKeyPressed(keyDef) {
return this.pressed.has(String(keyDef.code));
}
getPressedKeys() {
return this.pressed.values().map((p)=>p.keyDef);
}
/** Press a key */ async keydown(instance, keyDef) {
const key = String(keyDef.key);
const code = String(keyDef.code);
const target = getActiveElementOrBody(instance.config.document);
this.setKeydownTarget(target);
this.pressed.add(code, keyDef);
if (isModifierKey(key)) {
this.modifiers[key] = true;
}
const unprevented = instance.dispatchUIEvent(target, 'keydown', {
key,
code
});
if (isModifierLock(key) && !this.modifiers[key]) {
this.modifiers[key] = true;
this.modifierLockStart[key] = true;
}
if (unprevented) {
this.pressed.setUnprevented(code);
}
if (unprevented && this.hasKeyPress(key)) {
instance.dispatchUIEvent(getActiveElementOrBody(instance.config.document), 'keypress', {
key,
code,
charCode: keyDef.key === 'Enter' ? 13 : String(keyDef.key).charCodeAt(0)
});
}
}
/** Release a key */ async keyup(instance, keyDef) {
const key = String(keyDef.key);
const code = String(keyDef.code);
const unprevented = this.pressed.isUnprevented(code);
this.pressed.delete(code);
if (isModifierKey(key) && !this.pressed.values().find((p)=>p.keyDef.key === key)) {
this.modifiers[key] = false;
}
instance.dispatchUIEvent(getActiveElementOrBody(instance.config.document), 'keyup', {
key,
code
}, !unprevented);
if (isModifierLock(key) && this.modifiers[key]) {
if (this.modifierLockStart[key]) {
this.modifierLockStart[key] = false;
} else {
this.modifiers[key] = false;
}
}
}
setKeydownTarget(target) {
if (target !== this.lastKeydownTarget) {
this.carryChar = '';
}
this.lastKeydownTarget = target;
}
hasKeyPress(key) {
return (key.length === 1 || key === 'Enter') && !this.modifiers.Control && !this.modifiers.Alt;
}
constructor(system){
_define_property(this, "system", undefined);
_define_property(this, "modifiers", {
Alt: false,
AltGraph: false,
CapsLock: false,
Control: false,
Fn: false,
FnLock: false,
Meta: false,
NumLock: false,
ScrollLock: false,
Shift: false,
Symbol: false,
SymbolLock: false
});
_define_property(this, "pressed", new class {
add(code, keyDef) {
var _this_registry, _code;
var _;
(_ = (_this_registry = this.registry)[_code = code]) !== null && _ !== undefined ? _ : _this_registry[_code] = {
keyDef,
unpreventedDefault: false
};
}
has(code) {
return !!this.registry[code];
}
setUnprevented(code) {
const o = this.registry[code];
if (o) {
o.unpreventedDefault = true;
}
}
isUnprevented(code) {
var _this_registry_code;
return !!((_this_registry_code = this.registry[code]) === null || _this_registry_code === undefined ? undefined : _this_registry_code.unpreventedDefault);
}
delete(code) {
// eslint-disable-next-line @typescript-eslint/no-dynamic-delete
delete this.registry[code];
}
values() {
return Object.values(this.registry);
}
constructor(){
_define_property(this, "registry", {});
}
}());
_define_property(this, "carryChar", '');
_define_property(this, "lastKeydownTarget", undefined);
_define_property(this, "modifierLockStart", {});
this.system = system;
}
}
export { DOM_KEY_LOCATION, KeyboardHost };

View File

@@ -0,0 +1,78 @@
function _define_property(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
class Buttons {
getButtons() {
let v = 0;
for (const button of Object.keys(this.pressed)){
// eslint-disable-next-line no-bitwise
v |= 2 ** Number(button);
}
return v;
}
down(keyDef) {
const button = getMouseButtonId(keyDef.button);
if (button in this.pressed) {
this.pressed[button].push(keyDef);
return undefined;
}
this.pressed[button] = [
keyDef
];
return button;
}
up(keyDef) {
const button = getMouseButtonId(keyDef.button);
if (button in this.pressed) {
this.pressed[button] = this.pressed[button].filter((k)=>k.name !== keyDef.name);
if (this.pressed[button].length === 0) {
// eslint-disable-next-line @typescript-eslint/no-dynamic-delete
delete this.pressed[button];
return button;
}
}
return undefined;
}
constructor(){
_define_property(this, "pressed", {});
}
}
const MouseButton = {
primary: 0,
secondary: 1,
auxiliary: 2,
back: 3,
X1: 3,
forward: 4,
X2: 4
};
function getMouseButtonId(button = 0) {
if (button in MouseButton) {
return MouseButton[button];
}
return Number(button);
}
// On the `MouseEvent.button` property auxiliary and secondary button are flipped compared to `MouseEvent.buttons`.
const MouseButtonFlip = {
1: 2,
2: 1
};
function getMouseEventButton(button) {
button = getMouseButtonId(button);
if (button in MouseButtonFlip) {
return MouseButtonFlip[button];
}
return button;
}
export { Buttons, MouseButton, MouseButtonFlip, getMouseButtonId, getMouseEventButton };

View File

@@ -0,0 +1,32 @@
function _define_property(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
class Device {
get countPressed() {
return this.pressedKeys.size;
}
isPressed(keyDef) {
return this.pressedKeys.has(keyDef.name);
}
addPressed(keyDef) {
return this.pressedKeys.add(keyDef.name);
}
removePressed(keyDef) {
return this.pressedKeys.delete(keyDef.name);
}
constructor(){
_define_property(this, "pressedKeys", new Set());
}
}
export { Device };

View File

@@ -0,0 +1,157 @@
import { Buttons } from './buttons.js';
import { Device } from './device.js';
import { Mouse } from './mouse.js';
import { Pointer } from './pointer.js';
function _define_property(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
class PointerHost {
isKeyPressed(keyDef) {
return this.devices.get(keyDef.pointerType).isPressed(keyDef);
}
async press(instance, keyDef, position) {
this.devices.get(keyDef.pointerType).addPressed(keyDef);
this.buttons.down(keyDef);
const pointerName = this.getPointerName(keyDef);
const pointer = keyDef.pointerType === 'touch' ? this.pointers.new(pointerName, keyDef.pointerType, this.buttons) : this.pointers.get(pointerName);
// TODO: deprecate the following implicit setting of position
pointer.position = position;
if (pointer.pointerType !== 'touch') {
this.mouse.position = position;
}
if (pointer.pointerType === 'touch') {
pointer.init(instance);
}
pointer.down(instance, keyDef.button);
if (pointer.pointerType !== 'touch') {
this.mouse.down(instance, keyDef, pointer.isPrevented);
}
}
async move(instance, pointerName, position) {
const pointer = this.pointers.get(pointerName);
// In (some?) browsers this order of events can be observed.
// This interweaving of events is probably unnecessary.
// While the order of mouse (or pointer) events is defined per spec,
// the order in which they interweave/follow on a user interaction depends on the implementation.
const pointermove = pointer.move(instance, position);
const mousemove = pointer.pointerType === 'touch' ? undefined : this.mouse.move(instance, position, pointer.isPrevented);
pointermove === null || pointermove === undefined ? undefined : pointermove.leave();
mousemove === null || mousemove === undefined ? undefined : mousemove.leave();
pointermove === null || pointermove === undefined ? undefined : pointermove.enter();
mousemove === null || mousemove === undefined ? undefined : mousemove.enter();
pointermove === null || pointermove === undefined ? undefined : pointermove.move();
mousemove === null || mousemove === undefined ? undefined : mousemove.move();
}
async release(instance, keyDef, position) {
const device = this.devices.get(keyDef.pointerType);
device.removePressed(keyDef);
this.buttons.up(keyDef);
const pointer = this.pointers.get(this.getPointerName(keyDef));
const isPrevented = pointer.isPrevented;
// TODO: deprecate the following implicit setting of position
pointer.position = position;
if (pointer.pointerType !== 'touch') {
this.mouse.position = position;
}
if (device.countPressed === 0) {
pointer.up(instance, keyDef.button);
}
if (pointer.pointerType === 'touch') {
pointer.release(instance);
}
if (pointer.pointerType === 'touch' && !pointer.isMultitouch) {
const mousemove = this.mouse.move(instance, position, isPrevented);
mousemove === null || mousemove === undefined ? undefined : mousemove.leave();
mousemove === null || mousemove === undefined ? undefined : mousemove.enter();
mousemove === null || mousemove === undefined ? undefined : mousemove.move();
this.mouse.down(instance, keyDef, isPrevented);
}
if (!pointer.isMultitouch) {
const mousemove = this.mouse.move(instance, position, isPrevented);
mousemove === null || mousemove === undefined ? undefined : mousemove.leave();
mousemove === null || mousemove === undefined ? undefined : mousemove.enter();
mousemove === null || mousemove === undefined ? undefined : mousemove.move();
this.mouse.up(instance, keyDef, isPrevented);
}
}
getPointerName(keyDef) {
return keyDef.pointerType === 'touch' ? keyDef.name : keyDef.pointerType;
}
getPreviousPosition(pointerName) {
return this.pointers.has(pointerName) ? this.pointers.get(pointerName).position : undefined;
}
resetClickCount() {
this.mouse.resetClickCount();
}
getMouseTarget(instance) {
var _this_mouse_position_target;
return (_this_mouse_position_target = this.mouse.position.target) !== null && _this_mouse_position_target !== undefined ? _this_mouse_position_target : instance.config.document.body;
}
setMousePosition(position) {
this.mouse.position = position;
this.pointers.get('mouse').position = position;
}
constructor(system){
_define_property(this, "system", undefined);
_define_property(this, "mouse", undefined);
_define_property(this, "buttons", undefined);
_define_property(this, "devices", new class {
get(k) {
var _this_registry, _k;
var _;
return (_ = (_this_registry = this.registry)[_k = k]) !== null && _ !== undefined ? _ : _this_registry[_k] = new Device();
}
constructor(){
_define_property(this, "registry", {});
}
}());
_define_property(this, "pointers", new class {
new(pointerName, pointerType, buttons) {
const isPrimary = pointerType !== 'touch' || !Object.values(this.registry).some((p)=>p.pointerType === 'touch' && !p.isCancelled);
if (!isPrimary) {
Object.values(this.registry).forEach((p)=>{
if (p.pointerType === pointerType && !p.isCancelled) {
p.isMultitouch = true;
}
});
}
this.registry[pointerName] = new Pointer({
pointerId: this.nextId++,
pointerType,
isPrimary
}, buttons);
return this.registry[pointerName];
}
get(pointerName) {
if (!this.has(pointerName)) {
throw new Error(`Trying to access pointer "${pointerName}" which does not exist.`);
}
return this.registry[pointerName];
}
has(pointerName) {
return pointerName in this.registry;
}
constructor(){
_define_property(this, "registry", {});
_define_property(this, "nextId", 1);
}
}());
this.system = system;
this.buttons = new Buttons();
this.mouse = new Mouse();
this.pointers.new('mouse', 'mouse', this.buttons);
}
}
export { PointerHost };

View File

@@ -0,0 +1,205 @@
import '../../event/behavior/click.js';
import '../../event/behavior/cut.js';
import '../../event/behavior/keydown.js';
import '../../event/behavior/keypress.js';
import '../../event/behavior/keyup.js';
import '../../event/behavior/paste.js';
import '@testing-library/dom';
import '../../utils/dataTransfer/Clipboard.js';
import { isDisabled } from '../../utils/misc/isDisabled.js';
import { getTreeDiff } from '../../utils/misc/getTreeDiff.js';
import { focusElement } from '../../event/focus.js';
import { setSelectionPerMouseDown } from '../../event/selection/setSelectionPerMouse.js';
import { modifySelectionPerMouseMove } from '../../event/selection/modifySelectionPerMouse.js';
import { getMouseEventButton, Buttons } from './buttons.js';
import { isDifferentPointerPosition } from './shared.js';
function _define_property(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
/**
* This object is the single "virtual" mouse that might be controlled by multiple different pointer devices.
*/ class Mouse {
move(instance, position, /** Whether `preventDefault()` has been called on the `pointerdown` event */ isPrevented) {
const prevPosition = this.position;
const prevTarget = this.getTarget(instance);
this.position = position;
if (!isDifferentPointerPosition(prevPosition, position)) {
return;
}
const nextTarget = this.getTarget(instance);
const init = this.getEventInit('mousemove');
const [leave, enter] = getTreeDiff(prevTarget, nextTarget);
return {
leave: ()=>{
if (prevTarget !== nextTarget) {
instance.dispatchUIEvent(prevTarget, 'mouseout', init);
leave.forEach((el)=>instance.dispatchUIEvent(el, 'mouseleave', init));
}
},
enter: ()=>{
if (prevTarget !== nextTarget) {
instance.dispatchUIEvent(nextTarget, 'mouseover', init);
enter.forEach((el)=>instance.dispatchUIEvent(el, 'mouseenter', init));
}
},
move: ()=>{
if (isPrevented) {
return;
}
instance.dispatchUIEvent(nextTarget, 'mousemove', init);
this.modifySelecting(instance);
}
};
}
down(instance, keyDef, /** Whether `preventDefault()` has been called on the `pointerdown` event */ isPrevented) {
const button = this.buttons.down(keyDef);
if (button === undefined) {
return;
}
const target = this.getTarget(instance);
this.buttonDownTarget[button] = target;
const init = this.getEventInit('mousedown', keyDef.button);
const disabled = isDisabled(target);
if (!isPrevented && (disabled || instance.dispatchUIEvent(target, 'mousedown', init))) {
this.startSelecting(instance, init.detail);
focusElement(target);
}
if (!disabled && getMouseEventButton(keyDef.button) === 2) {
instance.dispatchUIEvent(target, 'contextmenu', this.getEventInit('contextmenu', keyDef.button));
}
}
up(instance, keyDef, /** Whether `preventDefault()` has been called on the `pointerdown` event */ isPrevented) {
const button = this.buttons.up(keyDef);
if (button === undefined) {
return;
}
const target = this.getTarget(instance);
if (!isDisabled(target)) {
if (!isPrevented) {
const mouseUpInit = this.getEventInit('mouseup', keyDef.button);
instance.dispatchUIEvent(target, 'mouseup', mouseUpInit);
this.endSelecting();
}
const clickTarget = getTreeDiff(this.buttonDownTarget[button], target)[2][0];
if (clickTarget) {
const init = this.getEventInit('click', keyDef.button);
if (init.detail) {
instance.dispatchUIEvent(clickTarget, init.button === 0 ? 'click' : 'auxclick', init);
if (init.button === 0 && init.detail === 2) {
instance.dispatchUIEvent(clickTarget, 'dblclick', {
...this.getEventInit('dblclick', keyDef.button),
detail: init.detail
});
}
}
}
}
}
resetClickCount() {
this.clickCount.reset();
}
getEventInit(type, button) {
const init = {
...this.position.coords
};
init.button = getMouseEventButton(button);
init.buttons = this.buttons.getButtons();
if (type === 'mousedown') {
init.detail = this.clickCount.getOnDown(init.button);
} else if (type === 'mouseup') {
init.detail = this.clickCount.getOnUp(init.button);
} else if (type === 'click' || type === 'auxclick') {
init.detail = this.clickCount.incOnClick(init.button);
}
return init;
}
getTarget(instance) {
var _this_position_target;
return (_this_position_target = this.position.target) !== null && _this_position_target !== undefined ? _this_position_target : instance.config.document.body;
}
startSelecting(instance, clickCount) {
var _this_position_caret, _this_position_caret1;
// TODO: support extending range (shift)
this.selecting = setSelectionPerMouseDown({
document: instance.config.document,
target: this.getTarget(instance),
node: (_this_position_caret = this.position.caret) === null || _this_position_caret === undefined ? undefined : _this_position_caret.node,
offset: (_this_position_caret1 = this.position.caret) === null || _this_position_caret1 === undefined ? undefined : _this_position_caret1.offset,
clickCount
});
}
modifySelecting(instance) {
var _this_position_caret, _this_position_caret1;
if (!this.selecting) {
return;
}
modifySelectionPerMouseMove(this.selecting, {
document: instance.config.document,
target: this.getTarget(instance),
node: (_this_position_caret = this.position.caret) === null || _this_position_caret === undefined ? undefined : _this_position_caret.node,
offset: (_this_position_caret1 = this.position.caret) === null || _this_position_caret1 === undefined ? undefined : _this_position_caret1.offset
});
}
endSelecting() {
this.selecting = undefined;
}
constructor(){
_define_property(this, "position", {});
_define_property(this, "buttons", new Buttons());
_define_property(this, "selecting", undefined);
_define_property(this, "buttonDownTarget", {});
// According to spec the `detail` on click events should be the number
// of *consecutive* clicks with a specific button.
// On `mousedown` and `mouseup` it should be this number increased by one.
// But the browsers don't implement it this way.
// If another button is pressed,
// in Webkit: the `mouseup` on the previously pressed button has `detail: 0` and no `click`/`auxclick`.
// in Gecko: the `mouseup` and click events have the same detail as the `mousedown`.
// If there is a delay while a button is pressed,
// the `mouseup` and `click` are normal, but a following `mousedown` starts a new click count.
// We'll follow the minimal implementation of Webkit.
_define_property(this, "clickCount", new class {
incOnClick(button) {
const current = this.down[button] === undefined ? undefined : Number(this.down[button]) + 1;
this.count = this.count[button] === undefined ? {} : {
[button]: Number(this.count[button]) + 1
};
return current;
}
getOnDown(button) {
var _this_count_button;
this.down = {
[button]: (_this_count_button = this.count[button]) !== null && _this_count_button !== undefined ? _this_count_button : 0
};
var _this_count_button1;
this.count = {
[button]: (_this_count_button1 = this.count[button]) !== null && _this_count_button1 !== undefined ? _this_count_button1 : 0
};
return Number(this.count[button]) + 1;
}
getOnUp(button) {
return this.down[button] === undefined ? undefined : Number(this.down[button]) + 1;
}
reset() {
this.count = {};
}
constructor(){
_define_property(this, "down", {});
_define_property(this, "count", {});
}
}());
}
}
export { Mouse };

View File

@@ -0,0 +1,129 @@
import '../../utils/dataTransfer/Clipboard.js';
import { getTreeDiff } from '../../utils/misc/getTreeDiff.js';
import { assertPointerEvents, hasPointerEvents } from '../../utils/pointer/cssPointerEvents.js';
import { isDifferentPointerPosition } from './shared.js';
import { getMouseEventButton } from './buttons.js';
function _define_property(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
class Pointer {
init(instance) {
const target = this.getTarget(instance);
const [, enter] = getTreeDiff(null, target);
const init = this.getEventInit();
assertPointerEvents(instance, target);
instance.dispatchUIEvent(target, 'pointerover', init);
enter.forEach((el)=>instance.dispatchUIEvent(el, 'pointerenter', init));
return this;
}
move(instance, position) {
const prevPosition = this.position;
const prevTarget = this.getTarget(instance);
this.position = position;
if (!isDifferentPointerPosition(prevPosition, position)) {
return;
}
const nextTarget = this.getTarget(instance);
const init = this.getEventInit(-1);
const [leave, enter] = getTreeDiff(prevTarget, nextTarget);
return {
leave: ()=>{
if (hasPointerEvents(instance, prevTarget)) {
if (prevTarget !== nextTarget) {
instance.dispatchUIEvent(prevTarget, 'pointerout', init);
leave.forEach((el)=>instance.dispatchUIEvent(el, 'pointerleave', init));
}
}
},
enter: ()=>{
assertPointerEvents(instance, nextTarget);
if (prevTarget !== nextTarget) {
instance.dispatchUIEvent(nextTarget, 'pointerover', init);
enter.forEach((el)=>instance.dispatchUIEvent(el, 'pointerenter', init));
}
},
move: ()=>{
instance.dispatchUIEvent(nextTarget, 'pointermove', init);
}
};
}
down(instance, button = 0) {
if (this.isDown) {
return;
}
const target = this.getTarget(instance);
assertPointerEvents(instance, target);
this.isDown = true;
this.isPrevented = !instance.dispatchUIEvent(target, 'pointerdown', this.getEventInit(button));
}
up(instance, button = 0) {
if (!this.isDown) {
return;
}
const target = this.getTarget(instance);
assertPointerEvents(instance, target);
this.isPrevented = false;
this.isDown = false;
instance.dispatchUIEvent(target, 'pointerup', this.getEventInit(button));
}
release(instance) {
const target = this.getTarget(instance);
const [leave] = getTreeDiff(target, null);
const init = this.getEventInit();
// Currently there is no PointerEventsCheckLevel that would
// make this check not use the *asserted* cached value from `up`.
/* istanbul ignore else */ if (hasPointerEvents(instance, target)) {
instance.dispatchUIEvent(target, 'pointerout', init);
leave.forEach((el)=>instance.dispatchUIEvent(el, 'pointerleave', init));
}
this.isCancelled = true;
}
getTarget(instance) {
var _this_position_target;
return (_this_position_target = this.position.target) !== null && _this_position_target !== undefined ? _this_position_target : instance.config.document.body;
}
getEventInit(/**
* The `button` that caused the event.
*
* This should be `-1` if the event is not caused by a button or touch/pen contact,
* e.g. a moving pointer.
*/ button) {
return {
...this.position.coords,
pointerId: this.pointerId,
pointerType: this.pointerType,
isPrimary: this.isPrimary,
button: getMouseEventButton(button),
buttons: this.buttons.getButtons()
};
}
constructor({ pointerId, pointerType, isPrimary }, buttons){
_define_property(this, "pointerId", undefined);
_define_property(this, "pointerType", undefined);
_define_property(this, "isPrimary", undefined);
_define_property(this, "buttons", undefined);
_define_property(this, "isMultitouch", false);
_define_property(this, "isCancelled", false);
_define_property(this, "isDown", false);
_define_property(this, "isPrevented", false);
_define_property(this, "position", {});
this.pointerId = pointerId;
this.pointerType = pointerType;
this.isPrimary = isPrimary;
this.isMultitouch = !isPrimary;
this.buttons = buttons;
}
}
export { Pointer };

View File

@@ -0,0 +1,6 @@
function isDifferentPointerPosition(positionA, positionB) {
var _positionA_coords, _positionB_coords, _positionA_coords1, _positionB_coords1, _positionA_coords2, _positionB_coords2, _positionA_coords3, _positionB_coords3, _positionA_coords4, _positionB_coords4, _positionA_coords5, _positionB_coords5, _positionA_coords6, _positionB_coords6, _positionA_coords7, _positionB_coords7, _positionA_coords8, _positionB_coords8, _positionA_coords9, _positionB_coords9, _positionA_caret, _positionB_caret, _positionA_caret1, _positionB_caret1;
return positionA.target !== positionB.target || ((_positionA_coords = positionA.coords) === null || _positionA_coords === undefined ? undefined : _positionA_coords.x) !== ((_positionB_coords = positionB.coords) === null || _positionB_coords === undefined ? undefined : _positionB_coords.x) || ((_positionA_coords1 = positionA.coords) === null || _positionA_coords1 === undefined ? undefined : _positionA_coords1.y) !== ((_positionB_coords1 = positionB.coords) === null || _positionB_coords1 === undefined ? undefined : _positionB_coords1.y) || ((_positionA_coords2 = positionA.coords) === null || _positionA_coords2 === undefined ? undefined : _positionA_coords2.clientX) !== ((_positionB_coords2 = positionB.coords) === null || _positionB_coords2 === undefined ? undefined : _positionB_coords2.clientX) || ((_positionA_coords3 = positionA.coords) === null || _positionA_coords3 === undefined ? undefined : _positionA_coords3.clientY) !== ((_positionB_coords3 = positionB.coords) === null || _positionB_coords3 === undefined ? undefined : _positionB_coords3.clientY) || ((_positionA_coords4 = positionA.coords) === null || _positionA_coords4 === undefined ? undefined : _positionA_coords4.offsetX) !== ((_positionB_coords4 = positionB.coords) === null || _positionB_coords4 === undefined ? undefined : _positionB_coords4.offsetX) || ((_positionA_coords5 = positionA.coords) === null || _positionA_coords5 === undefined ? undefined : _positionA_coords5.offsetY) !== ((_positionB_coords5 = positionB.coords) === null || _positionB_coords5 === undefined ? undefined : _positionB_coords5.offsetY) || ((_positionA_coords6 = positionA.coords) === null || _positionA_coords6 === undefined ? undefined : _positionA_coords6.pageX) !== ((_positionB_coords6 = positionB.coords) === null || _positionB_coords6 === undefined ? undefined : _positionB_coords6.pageX) || ((_positionA_coords7 = positionA.coords) === null || _positionA_coords7 === undefined ? undefined : _positionA_coords7.pageY) !== ((_positionB_coords7 = positionB.coords) === null || _positionB_coords7 === undefined ? undefined : _positionB_coords7.pageY) || ((_positionA_coords8 = positionA.coords) === null || _positionA_coords8 === undefined ? undefined : _positionA_coords8.screenX) !== ((_positionB_coords8 = positionB.coords) === null || _positionB_coords8 === undefined ? undefined : _positionB_coords8.screenX) || ((_positionA_coords9 = positionA.coords) === null || _positionA_coords9 === undefined ? undefined : _positionA_coords9.screenY) !== ((_positionB_coords9 = positionB.coords) === null || _positionB_coords9 === undefined ? undefined : _positionB_coords9.screenY) || ((_positionA_caret = positionA.caret) === null || _positionA_caret === undefined ? undefined : _positionA_caret.node) !== ((_positionB_caret = positionB.caret) === null || _positionB_caret === undefined ? undefined : _positionB_caret.node) || ((_positionA_caret1 = positionA.caret) === null || _positionA_caret1 === undefined ? undefined : _positionA_caret1.offset) !== ((_positionB_caret1 = positionB.caret) === null || _positionB_caret1 === undefined ? undefined : _positionB_caret1.offset);
}
export { isDifferentPointerPosition };

View File

@@ -0,0 +1,30 @@
import '../event/behavior/click.js';
import '../event/behavior/cut.js';
import '../event/behavior/keydown.js';
import '../event/behavior/keypress.js';
import '../event/behavior/keyup.js';
import '../event/behavior/paste.js';
import '@testing-library/dom';
import '../utils/dataTransfer/Clipboard.js';
import { isEditable } from '../utils/edit/isEditable.js';
import { isDisabled } from '../utils/misc/isDisabled.js';
import { focusElement } from '../event/focus.js';
import { input } from '../event/input.js';
import { selectAll, isAllSelected } from '../event/selection/selectAll.js';
async function clear(element) {
if (!isEditable(element) || isDisabled(element)) {
throw new Error('clear()` is only supported on editable elements.');
}
focusElement(element);
if (element.ownerDocument.activeElement !== element) {
throw new Error('The element to be cleared could not be focused.');
}
selectAll(element);
if (!isAllSelected(element)) {
throw new Error('The element content to be cleared could not be selected.');
}
input(this, element, '', 'deleteContentBackward');
}
export { clear };

View File

@@ -0,0 +1,4 @@
export { clear } from './clear.js';
export { deselectOptions, selectOptions } from './selectOptions.js';
export { type } from './type.js';
export { upload } from './upload.js';

View File

@@ -0,0 +1,111 @@
import { getConfig } from '@testing-library/dom';
import { isElementType } from '../utils/misc/isElementType.js';
import '../utils/dataTransfer/Clipboard.js';
import { isDisabled } from '../utils/misc/isDisabled.js';
import { wait } from '../utils/misc/wait.js';
import { hasPointerEvents } from '../utils/pointer/cssPointerEvents.js';
import '../event/behavior/click.js';
import '../event/behavior/cut.js';
import '../event/behavior/keydown.js';
import '../event/behavior/keypress.js';
import '../event/behavior/keyup.js';
import '../event/behavior/paste.js';
import { focusElement } from '../event/focus.js';
async function selectOptions(select, values) {
return selectOptionsBase.call(this, true, select, values);
}
async function deselectOptions(select, values) {
return selectOptionsBase.call(this, false, select, values);
}
async function selectOptionsBase(newValue, select, values) {
if (!newValue && !select.multiple) {
throw getConfig().getElementError(`Unable to deselect an option in a non-multiple select. Use selectOptions to change the selection instead.`, select);
}
const valArray = Array.isArray(values) ? values : [
values
];
const allOptions = Array.from(select.querySelectorAll('option, [role="option"]'));
const selectedOptions = valArray.map((val)=>{
if (typeof val !== 'string' && allOptions.includes(val)) {
return val;
} else {
const matchingOption = allOptions.find((o)=>o.value === val || o.innerHTML === val);
if (matchingOption) {
return matchingOption;
} else {
throw getConfig().getElementError(`Value "${String(val)}" not found in options`, select);
}
}
}).filter((option)=>!isDisabled(option));
if (isDisabled(select) || !selectedOptions.length) return;
const selectOption = (option)=>{
option.selected = newValue;
this.dispatchUIEvent(select, 'input', {
bubbles: true,
cancelable: false,
composed: true
});
this.dispatchUIEvent(select, 'change');
};
if (isElementType(select, 'select')) {
if (select.multiple) {
for (const option of selectedOptions){
const withPointerEvents = this.config.pointerEventsCheck === 0 ? true : hasPointerEvents(this, option);
// events fired for multiple select are weird. Can't use hover...
if (withPointerEvents) {
this.dispatchUIEvent(option, 'pointerover');
this.dispatchUIEvent(select, 'pointerenter');
this.dispatchUIEvent(option, 'mouseover');
this.dispatchUIEvent(select, 'mouseenter');
this.dispatchUIEvent(option, 'pointermove');
this.dispatchUIEvent(option, 'mousemove');
this.dispatchUIEvent(option, 'pointerdown');
this.dispatchUIEvent(option, 'mousedown');
}
focusElement(select);
if (withPointerEvents) {
this.dispatchUIEvent(option, 'pointerup');
this.dispatchUIEvent(option, 'mouseup');
}
selectOption(option);
if (withPointerEvents) {
this.dispatchUIEvent(option, 'click');
}
await wait(this.config);
}
} else if (selectedOptions.length === 1) {
const withPointerEvents = this.config.pointerEventsCheck === 0 ? true : hasPointerEvents(this, select);
// the click to open the select options
if (withPointerEvents) {
await this.click(select);
} else {
focusElement(select);
}
selectOption(selectedOptions[0]);
if (withPointerEvents) {
// the browser triggers another click event on the select for the click on the option
// this second click has no 'down' phase
this.dispatchUIEvent(select, 'pointerover');
this.dispatchUIEvent(select, 'pointerenter');
this.dispatchUIEvent(select, 'mouseover');
this.dispatchUIEvent(select, 'mouseenter');
this.dispatchUIEvent(select, 'pointerup');
this.dispatchUIEvent(select, 'mouseup');
this.dispatchUIEvent(select, 'click');
}
await wait(this.config);
} else {
throw getConfig().getElementError(`Cannot select multiple options on a non-multiple select`, select);
}
} else if (select.getAttribute('role') === 'listbox') {
for (const option of selectedOptions){
await this.click(option);
await this.unhover(option);
}
} else {
throw getConfig().getElementError(`Cannot select options on elements that are neither select nor listbox elements`, select);
}
}
export { deselectOptions, selectOptions };

View File

@@ -0,0 +1,21 @@
import { releaseAllKeys } from '../keyboard/index.js';
import '../utils/dataTransfer/Clipboard.js';
import { setSelectionRange } from '../event/selection/setSelectionRange.js';
async function type(element, text, { skipClick = this.config.skipClick, skipAutoClose = this.config.skipAutoClose, initialSelectionStart, initialSelectionEnd } = {}) {
// TODO: properly type guard
// we use this workaround for now to prevent changing behavior
if (element.disabled) return;
if (!skipClick) {
await this.click(element);
}
if (initialSelectionStart !== undefined) {
setSelectionRange(element, initialSelectionStart, initialSelectionEnd !== null && initialSelectionEnd !== undefined ? initialSelectionEnd : initialSelectionStart);
}
await this.keyboard(text);
if (!skipAutoClose) {
await releaseAllKeys(this);
}
}
export { type };

View File

@@ -0,0 +1,60 @@
import { isElementType } from '../utils/misc/isElementType.js';
import { createFileList } from '../utils/dataTransfer/FileList.js';
import '../utils/dataTransfer/Clipboard.js';
import { setFiles } from '../utils/edit/setFiles.js';
import { isDisabled } from '../utils/misc/isDisabled.js';
import { getWindow } from '../utils/misc/getWindow.js';
async function upload(element, fileOrFiles) {
const input = isElementType(element, 'label') ? element.control : element;
if (!input || !isElementType(input, 'input', {
type: 'file'
})) {
throw new TypeError(`The ${input === element ? 'given' : 'associated'} ${input === null || input === undefined ? undefined : input.tagName} element does not accept file uploads`);
}
if (isDisabled(element)) return;
const files = (Array.isArray(fileOrFiles) ? fileOrFiles : [
fileOrFiles
]).filter((file)=>!this.config.applyAccept || isAcceptableFile(file, input.accept)).slice(0, input.multiple ? undefined : 1);
const fileDialog = ()=>{
var _input_files;
// do not fire an input event if the file selection does not change
if (files.length === ((_input_files = input.files) === null || _input_files === undefined ? undefined : _input_files.length) && files.every((f, i)=>{
var _input_files;
return f === ((_input_files = input.files) === null || _input_files === undefined ? undefined : _input_files.item(i));
})) {
return;
}
setFiles(input, createFileList(getWindow(element), files));
this.dispatchUIEvent(input, 'input');
this.dispatchUIEvent(input, 'change');
};
input.addEventListener('fileDialog', fileDialog);
await this.click(element);
input.removeEventListener('fileDialog', fileDialog);
}
// When matching files, browsers ignore case and consider jpeg/jpg interchangeable.
function normalize(nameOrType) {
return nameOrType.toLowerCase().replace(/(\.|\/)jpg\b/g, '$1jpeg');
}
function isAcceptableFile(file, accept) {
if (!accept) {
return true;
}
const wildcards = [
'audio/*',
'image/*',
'video/*'
];
return normalize(accept).trim().split(/\s*,\s*/).some((acceptToken)=>{
// tokens starting with a dot represent a file extension
if (acceptToken.startsWith('.')) {
return normalize(file.name).endsWith(acceptToken);
} else if (wildcards.includes(acceptToken)) {
return normalize(file.type).startsWith(acceptToken.replace('*', ''));
}
return normalize(file.type) === acceptToken;
});
}
export { upload };

View File

@@ -0,0 +1,18 @@
import { isElementType } from '../misc/isElementType.js';
var clickableInputTypes = /*#__PURE__*/ function(clickableInputTypes) {
clickableInputTypes["button"] = "button";
clickableInputTypes["color"] = "color";
clickableInputTypes["file"] = "file";
clickableInputTypes["image"] = "image";
clickableInputTypes["reset"] = "reset";
clickableInputTypes["submit"] = "submit";
clickableInputTypes["checkbox"] = "checkbox";
clickableInputTypes["radio"] = "radio";
return clickableInputTypes;
}(clickableInputTypes || {});
function isClickableInput(element) {
return isElementType(element, 'button') || isElementType(element, 'input') && element.type in clickableInputTypes;
}
export { isClickableInput };

View File

@@ -0,0 +1,14 @@
// jsdom does not implement Blob.text()
function readBlobText(blob, FileReader) {
return new Promise((res, rej)=>{
const fr = new FileReader();
fr.onerror = rej;
fr.onabort = rej;
fr.onload = ()=>{
res(String(fr.result));
};
fr.readAsText(blob);
});
}
export { readBlobText };

View File

@@ -0,0 +1,162 @@
import { getWindow } from '../misc/getWindow.js';
import { readBlobText } from './Blob.js';
import { createDataTransfer, getBlobFromDataTransferItem } from './DataTransfer.js';
// Clipboard is not available in jsdom
function _define_property(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
// MDN lists string|Blob|Promise<Blob|string> as possible types in ClipboardItemData
// lib.dom.d.ts lists only Promise<Blob|string>
// https://developer.mozilla.org/en-US/docs/Web/API/ClipboardItem/ClipboardItem#syntax
function createClipboardItem(window, ...blobs) {
const dataMap = Object.fromEntries(blobs.map((b)=>[
typeof b === 'string' ? 'text/plain' : b.type,
Promise.resolve(b)
]));
// use real ClipboardItem if available
/* istanbul ignore if */ if (typeof window.ClipboardItem !== 'undefined') {
return new window.ClipboardItem(dataMap);
}
return new class ClipboardItem {
get types() {
return Array.from(Object.keys(this.data));
}
async getType(type) {
const value = await this.data[type];
if (!value) {
throw new Error(`${type} is not one of the available MIME types on this item.`);
}
return value instanceof window.Blob ? value : new window.Blob([
value
], {
type
});
}
constructor(d){
_define_property(this, "data", undefined);
this.data = d;
}
}(dataMap);
}
const ClipboardStubControl = Symbol('Manage ClipboardSub');
function createClipboardStub(window, control) {
return Object.assign(new class Clipboard extends window.EventTarget {
async read() {
return Array.from(this.items);
}
async readText() {
let text = '';
for (const item of this.items){
const type = item.types.includes('text/plain') ? 'text/plain' : item.types.find((t)=>t.startsWith('text/'));
if (type) {
text += await item.getType(type).then((b)=>readBlobText(b, window.FileReader));
}
}
return text;
}
async write(data) {
this.items = data;
}
async writeText(text) {
this.items = [
createClipboardItem(window, text)
];
}
constructor(...args){
super(...args), _define_property(this, "items", []);
}
}(), {
[ClipboardStubControl]: control
});
}
function isClipboardStub(clipboard) {
return !!(clipboard === null || clipboard === undefined ? undefined : clipboard[ClipboardStubControl]);
}
function attachClipboardStubToView(window) {
if (isClipboardStub(window.navigator.clipboard)) {
return window.navigator.clipboard[ClipboardStubControl];
}
const realClipboard = Object.getOwnPropertyDescriptor(window.navigator, 'clipboard');
let stub;
const control = {
resetClipboardStub: ()=>{
stub = createClipboardStub(window, control);
},
detachClipboardStub: ()=>{
/* istanbul ignore if */ if (realClipboard) {
Object.defineProperty(window.navigator, 'clipboard', realClipboard);
} else {
Object.defineProperty(window.navigator, 'clipboard', {
value: undefined,
configurable: true
});
}
}
};
stub = createClipboardStub(window, control);
Object.defineProperty(window.navigator, 'clipboard', {
get: ()=>stub,
configurable: true
});
return stub[ClipboardStubControl];
}
function resetClipboardStubOnView(window) {
if (isClipboardStub(window.navigator.clipboard)) {
window.navigator.clipboard[ClipboardStubControl].resetClipboardStub();
}
}
function detachClipboardStubFromView(window) {
if (isClipboardStub(window.navigator.clipboard)) {
window.navigator.clipboard[ClipboardStubControl].detachClipboardStub();
}
}
async function readDataTransferFromClipboard(document) {
const window = document.defaultView;
const clipboard = window === null || window === undefined ? undefined : window.navigator.clipboard;
const items = clipboard && await clipboard.read();
if (!items) {
throw new Error('The Clipboard API is unavailable.');
}
const dt = createDataTransfer(window);
for (const item of items){
for (const type of item.types){
dt.setData(type, await item.getType(type).then((b)=>readBlobText(b, window.FileReader)));
}
}
return dt;
}
async function writeDataTransferToClipboard(document, clipboardData) {
const window = getWindow(document);
const clipboard = window.navigator.clipboard;
const items = [];
for(let i = 0; i < clipboardData.items.length; i++){
const dtItem = clipboardData.items[i];
const blob = await getBlobFromDataTransferItem(window, dtItem);
items.push(createClipboardItem(window, blob));
}
const written = clipboard && await clipboard.write(items).then(()=>true, // Can happen with other implementations that e.g. require permissions
/* istanbul ignore next */ ()=>false);
if (!written) {
throw new Error('The Clipboard API is unavailable.');
}
}
const g = globalThis;
/* istanbul ignore else */ if (typeof g.afterEach === 'function') {
g.afterEach(()=>resetClipboardStubOnView(globalThis.window));
}
/* istanbul ignore else */ if (typeof g.afterAll === 'function') {
g.afterAll(()=>detachClipboardStubFromView(globalThis.window));
}
export { attachClipboardStubToView, createClipboardItem, detachClipboardStubFromView, readDataTransferFromClipboard, resetClipboardStubOnView, writeDataTransferToClipboard };

View File

@@ -0,0 +1,133 @@
import { createFileList } from './FileList.js';
function _define_property(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
// DataTransfer is not implemented in jsdom.
// DataTransfer with FileList is being created by the browser on certain events.
class DataTransferItemStub {
getAsFile() {
return this.file;
}
getAsString(callback) {
if (typeof this.data === 'string') {
callback(this.data);
}
}
/* istanbul ignore next */ webkitGetAsEntry() {
throw new Error('not implemented');
}
constructor(dataOrFile, type){
_define_property(this, "kind", undefined);
_define_property(this, "type", undefined);
_define_property(this, "file", null);
_define_property(this, "data", undefined);
if (typeof dataOrFile === 'string') {
this.kind = 'string';
this.type = String(type);
this.data = dataOrFile;
} else {
this.kind = 'file';
this.type = dataOrFile.type;
this.file = dataOrFile;
}
}
}
class DataTransferItemListStub extends Array {
add(...args) {
const item = new DataTransferItemStub(args[0], args[1]);
this.push(item);
return item;
}
clear() {
this.splice(0, this.length);
}
remove(index) {
this.splice(index, 1);
}
}
function getTypeMatcher(type, exact) {
const [group, sub] = type.split('/');
const isGroup = !sub || sub === '*';
return (item)=>{
return exact ? item.type === (isGroup ? group : type) : isGroup ? item.type.startsWith(`${group}/`) : item.type === group;
};
}
function createDataTransferStub(window) {
return new class DataTransferStub {
getData(format) {
var _this_items_find;
const match = (_this_items_find = this.items.find(getTypeMatcher(format, true))) !== null && _this_items_find !== undefined ? _this_items_find : this.items.find(getTypeMatcher(format, false));
let text = '';
match === null || match === undefined ? undefined : match.getAsString((t)=>{
text = t;
});
return text;
}
setData(format, data) {
const matchIndex = this.items.findIndex(getTypeMatcher(format, true));
const item = new DataTransferItemStub(data, format);
if (matchIndex >= 0) {
this.items.splice(matchIndex, 1, item);
} else {
this.items.push(item);
}
}
clearData(format) {
if (format) {
const matchIndex = this.items.findIndex(getTypeMatcher(format, true));
if (matchIndex >= 0) {
this.items.remove(matchIndex);
}
} else {
this.items.clear();
}
}
get types() {
const t = [];
if (this.files.length) {
t.push('Files');
}
this.items.forEach((i)=>t.push(i.type));
Object.freeze(t);
return t;
}
/* istanbul ignore next */ setDragImage() {}
constructor(){
_define_property(this, "dropEffect", 'none');
_define_property(this, "effectAllowed", 'uninitialized');
_define_property(this, "items", new DataTransferItemListStub());
_define_property(this, "files", createFileList(window, []));
}
}();
}
function createDataTransfer(window, files = []) {
// Use real DataTransfer if available
const dt = typeof window.DataTransfer === 'undefined' ? createDataTransferStub(window) : /* istanbul ignore next */ new window.DataTransfer();
Object.defineProperty(dt, 'files', {
get: ()=>createFileList(window, files)
});
return dt;
}
async function getBlobFromDataTransferItem(window, item) {
if (item.kind === 'file') {
return item.getAsFile();
}
return new window.Blob([
await new Promise((r)=>item.getAsString(r))
], {
type: item.type
});
}
export { createDataTransfer, getBlobFromDataTransferItem };

View File

@@ -0,0 +1,22 @@
// FileList can not be created per constructor.
function createFileList(window, files) {
const list = {
...files,
length: files.length,
item: (index)=>list[index],
[Symbol.iterator]: function* nextFile() {
for(let i = 0; i < list.length; i++){
yield list[i];
}
}
};
list.constructor = window.FileList;
// guard for environments without FileList
/* istanbul ignore else */ if (window.FileList) {
Object.setPrototypeOf(list, window.FileList.prototype);
}
Object.freeze(list);
return list;
}
export { createFileList };

View File

@@ -0,0 +1,15 @@
//jsdom is not supporting isContentEditable
function isContentEditable(element) {
return element.hasAttribute('contenteditable') && (element.getAttribute('contenteditable') == 'true' || element.getAttribute('contenteditable') == '');
}
/**
* If a node is a contenteditable or inside one, return that element.
*/ function getContentEditable(node) {
const element = getElement(node);
return element && (element.closest('[contenteditable=""]') || element.closest('[contenteditable="true"]'));
}
function getElement(node) {
return node.nodeType === 1 ? node : node.parentElement;
}
export { getContentEditable, isContentEditable };

View File

@@ -0,0 +1,26 @@
import { isElementType } from '../misc/isElementType.js';
import { isContentEditable } from './isContentEditable.js';
function isEditable(element) {
return isEditableInputOrTextArea(element) && !element.readOnly || isContentEditable(element);
}
var editableInputTypes = /*#__PURE__*/ function(editableInputTypes) {
editableInputTypes["text"] = "text";
editableInputTypes["date"] = "date";
editableInputTypes["datetime-local"] = "datetime-local";
editableInputTypes["email"] = "email";
editableInputTypes["month"] = "month";
editableInputTypes["number"] = "number";
editableInputTypes["password"] = "password";
editableInputTypes["search"] = "search";
editableInputTypes["tel"] = "tel";
editableInputTypes["time"] = "time";
editableInputTypes["url"] = "url";
editableInputTypes["week"] = "week";
return editableInputTypes;
}(editableInputTypes || {});
function isEditableInputOrTextArea(element) {
return isElementType(element, 'textarea') || isElementType(element, 'input') && element.type in editableInputTypes;
}
export { isEditable, isEditableInputOrTextArea };

View File

@@ -0,0 +1,23 @@
import { isElementType } from '../misc/isElementType.js';
var maxLengthSupportedTypes = /*#__PURE__*/ function(maxLengthSupportedTypes) {
maxLengthSupportedTypes["email"] = "email";
maxLengthSupportedTypes["password"] = "password";
maxLengthSupportedTypes["search"] = "search";
maxLengthSupportedTypes["telephone"] = "telephone";
maxLengthSupportedTypes["text"] = "text";
maxLengthSupportedTypes["url"] = "url";
return maxLengthSupportedTypes;
}(maxLengthSupportedTypes || {});
// can't use .maxLength property because of a jsdom bug:
// https://github.com/jsdom/jsdom/issues/2927
function getMaxLength(element) {
var _element_getAttribute;
const attr = (_element_getAttribute = element.getAttribute('maxlength')) !== null && _element_getAttribute !== undefined ? _element_getAttribute : '';
return /^\d+$/.test(attr) && Number(attr) >= 0 ? Number(attr) : undefined;
}
function supportsMaxLength(element) {
return isElementType(element, 'textarea') || isElementType(element, 'input') && element.type in maxLengthSupportedTypes;
}
export { getMaxLength, supportsMaxLength };

View File

@@ -0,0 +1,57 @@
// It is not possible to create a real FileList programmatically.
// Therefore assigning `files` property with a programmatically created FileList results in an error.
// Just assigning the property (as per fireEvent) breaks the interweaving with the `value` property.
const fakeFiles = Symbol('files and value properties are mocked');
function restoreProperty(obj, prop, descriptor) {
if (descriptor) {
Object.defineProperty(obj, prop, descriptor);
} else {
// eslint-disable-next-line @typescript-eslint/no-dynamic-delete
delete obj[prop];
}
}
function setFiles(el, files) {
var _el_fakeFiles;
(_el_fakeFiles = el[fakeFiles]) === null || _el_fakeFiles === undefined ? undefined : _el_fakeFiles.restore();
const typeDescr = Object.getOwnPropertyDescriptor(el, 'type');
const valueDescr = Object.getOwnPropertyDescriptor(el, 'value');
const filesDescr = Object.getOwnPropertyDescriptor(el, 'files');
function restore() {
restoreProperty(el, 'type', typeDescr);
restoreProperty(el, 'value', valueDescr);
restoreProperty(el, 'files', filesDescr);
}
el[fakeFiles] = {
restore
};
Object.defineProperties(el, {
files: {
configurable: true,
get: ()=>files
},
value: {
configurable: true,
get: ()=>files.length ? `C:\\fakepath\\${files[0].name}` : '',
set (v) {
if (v === '') {
restore();
} else {
var _valueDescr_set;
valueDescr === null || valueDescr === undefined ? undefined : (_valueDescr_set = valueDescr.set) === null || _valueDescr_set === undefined ? undefined : _valueDescr_set.call(el, v);
}
}
},
type: {
configurable: true,
get: ()=>'file',
set (v) {
if (v !== 'file') {
restore();
el.type = v;
}
}
}
});
}
export { setFiles };

View File

@@ -0,0 +1,37 @@
const parseInt = globalThis.parseInt;
function buildTimeValue(value) {
const onlyDigitsValue = value.replace(/\D/g, '');
if (onlyDigitsValue.length < 2) {
return value;
}
const firstDigit = parseInt(onlyDigitsValue[0], 10);
const secondDigit = parseInt(onlyDigitsValue[1], 10);
if (firstDigit >= 3 || firstDigit === 2 && secondDigit >= 4) {
let index;
if (firstDigit >= 3) {
index = 1;
} else {
index = 2;
}
return build(onlyDigitsValue, index);
}
if (value.length === 2) {
return value;
}
return build(onlyDigitsValue, 2);
}
function build(onlyDigitsValue, index) {
const hours = onlyDigitsValue.slice(0, index);
const validHours = Math.min(parseInt(hours, 10), 23);
const minuteCharacters = onlyDigitsValue.slice(index);
const parsedMinutes = parseInt(minuteCharacters, 10);
const validMinutes = Math.min(parsedMinutes, 59);
return `${validHours.toString().padStart(2, '0')}:${validMinutes.toString().padStart(2, '0')}`;
}
function isValidDateOrTimeValue(element, value) {
const clone = element.cloneNode();
clone.value = value;
return clone.value === value;
}
export { buildTimeValue, isValidDateOrTimeValue };

View File

@@ -0,0 +1,124 @@
import { isContentEditable } from '../edit/isContentEditable.js';
import { isElementType } from '../misc/isElementType.js';
function getNextCursorPosition(node, offset, direction, inputType) {
// The behavior at text node zero offset is inconsistent.
// When walking backwards:
// Firefox always moves to zero offset and jumps over last offset.
// Chrome jumps over zero offset per default but over last offset when Shift is pressed.
// The cursor always moves to zero offset if the focus area (contenteditable or body) ends there.
// When walking forward both ignore zero offset.
// When walking over input elements the cursor moves before or after that element.
// When walking over line breaks the cursor moves inside any following text node.
if (isTextNode(node) && offset + direction >= 0 && offset + direction <= node.nodeValue.length) {
return {
node,
offset: offset + direction
};
}
const nextNode = getNextCharacterContentNode(node, offset, direction);
if (nextNode) {
if (isTextNode(nextNode)) {
return {
node: nextNode,
offset: direction > 0 ? Math.min(1, nextNode.nodeValue.length) : Math.max(nextNode.nodeValue.length - 1, 0)
};
} else if (isElementType(nextNode, 'br')) {
const nextPlusOne = getNextCharacterContentNode(nextNode, undefined, direction);
if (!nextPlusOne) {
// The behavior when there is no possible cursor position beyond the line break is inconsistent.
// In Chrome outside of contenteditable moving before a leading line break is possible.
// A leading line break can still be removed per deleteContentBackward.
// A trailing line break on the other hand is not removed by deleteContentForward.
if (direction < 0 && inputType === 'deleteContentBackward') {
return {
node: nextNode.parentNode,
offset: getOffset(nextNode)
};
}
return undefined;
} else if (isTextNode(nextPlusOne)) {
return {
node: nextPlusOne,
offset: direction > 0 ? 0 : nextPlusOne.nodeValue.length
};
} else if (direction < 0 && isElementType(nextPlusOne, 'br')) {
return {
node: nextNode.parentNode,
offset: getOffset(nextNode)
};
} else {
return {
node: nextPlusOne.parentNode,
offset: getOffset(nextPlusOne) + (direction > 0 ? 0 : 1)
};
}
} else {
return {
node: nextNode.parentNode,
offset: getOffset(nextNode) + (direction > 0 ? 1 : 0)
};
}
}
}
function getNextCharacterContentNode(node, offset, direction) {
const nextOffset = Number(offset) + (direction < 0 ? -1 : 0);
if (offset !== undefined && isElement(node) && nextOffset >= 0 && nextOffset < node.children.length) {
node = node.children[nextOffset];
}
return walkNodes(node, direction === 1 ? 'next' : 'previous', isTreatedAsCharacterContent);
}
function isTreatedAsCharacterContent(node) {
if (isTextNode(node)) {
return true;
}
if (isElement(node)) {
if (isElementType(node, [
'input',
'textarea'
])) {
return node.type !== 'hidden';
} else if (isElementType(node, 'br')) {
return true;
}
}
return false;
}
function getOffset(node) {
let i = 0;
while(node.previousSibling){
i++;
node = node.previousSibling;
}
return i;
}
function isElement(node) {
return node.nodeType === 1;
}
function isTextNode(node) {
return node.nodeType === 3;
}
function walkNodes(node, direction, callback) {
for(;;){
var _node_ownerDocument;
const sibling = node[`${direction}Sibling`];
if (sibling) {
node = getDescendant(sibling, direction === 'next' ? 'first' : 'last');
if (callback(node)) {
return node;
}
} else if (node.parentNode && (!isElement(node.parentNode) || !isContentEditable(node.parentNode) && node.parentNode !== ((_node_ownerDocument = node.ownerDocument) === null || _node_ownerDocument === undefined ? undefined : _node_ownerDocument.body))) {
node = node.parentNode;
} else {
break;
}
}
}
function getDescendant(node, direction) {
while(node.hasChildNodes()){
node = node[`${direction}Child`];
}
return node;
}
export { getNextCursorPosition };

View File

@@ -0,0 +1,20 @@
import { isDisabled } from '../misc/isDisabled.js';
function getActiveElement(document) {
const activeElement = document.activeElement;
if (activeElement === null || activeElement === undefined ? undefined : activeElement.shadowRoot) {
return getActiveElement(activeElement.shadowRoot);
} else {
// Browser does not yield disabled elements as document.activeElement - jsdom does
if (isDisabled(activeElement)) {
return document.ownerDocument ? /* istanbul ignore next */ document.ownerDocument.body : document.body;
}
return activeElement;
}
}
function getActiveElementOrBody(document) {
var _getActiveElement;
return (_getActiveElement = getActiveElement(document)) !== null && _getActiveElement !== undefined ? _getActiveElement : /* istanbul ignore next */ document.body;
}
export { getActiveElement, getActiveElementOrBody };

View File

@@ -0,0 +1,78 @@
import { isDisabled } from '../misc/isDisabled.js';
import { isElementType } from '../misc/isElementType.js';
import { isVisible } from '../misc/isVisible.js';
import { FOCUSABLE_SELECTOR } from './selector.js';
function getTabDestination(activeElement, shift) {
const document = activeElement.ownerDocument;
const focusableElements = document.querySelectorAll(FOCUSABLE_SELECTOR);
const enabledElements = Array.from(focusableElements).filter((el)=>el === activeElement || !(Number(el.getAttribute('tabindex')) < 0 || isDisabled(el)));
// tabindex has no effect if the active element has negative tabindex
if (Number(activeElement.getAttribute('tabindex')) >= 0) {
enabledElements.sort((a, b)=>{
const i = Number(a.getAttribute('tabindex'));
const j = Number(b.getAttribute('tabindex'));
if (i === j) {
return 0;
} else if (i === 0) {
return 1;
} else if (j === 0) {
return -1;
}
return i - j;
});
}
const checkedRadio = {};
let prunedElements = [
document.body
];
const activeRadioGroup = isElementType(activeElement, 'input', {
type: 'radio'
}) ? activeElement.name : undefined;
enabledElements.forEach((currentElement)=>{
const el = currentElement;
// For radio groups keep only the active radio
// If there is no active radio, keep only the checked radio
// If there is no checked radio, treat like everything else
if (isElementType(el, 'input', {
type: 'radio'
}) && el.name) {
// If the active element is part of the group, add only that
if (el === activeElement) {
prunedElements.push(el);
return;
} else if (el.name === activeRadioGroup) {
return;
}
// If we stumble upon a checked radio, remove the others
if (el.checked) {
prunedElements = prunedElements.filter((e)=>!isElementType(e, 'input', {
type: 'radio',
name: el.name
}));
prunedElements.push(el);
checkedRadio[el.name] = el;
return;
}
// If we already found the checked one, skip
if (typeof checkedRadio[el.name] !== 'undefined') {
return;
}
}
prunedElements.push(el);
});
for(let index = prunedElements.findIndex((el)=>el === activeElement);;){
index += shift ? -1 : 1;
// loop at overflow
if (index === prunedElements.length) {
index = 0;
} else if (index === -1) {
index = prunedElements.length - 1;
}
if (prunedElements[index] === activeElement || prunedElements[index] === document.body || isVisible(prunedElements[index])) {
return prunedElements[index];
}
}
}
export { getTabDestination };

View File

@@ -0,0 +1,7 @@
import { FOCUSABLE_SELECTOR } from './selector.js';
function isFocusable(element) {
return element.matches(FOCUSABLE_SELECTOR);
}
export { isFocusable };

View File

@@ -0,0 +1,17 @@
import { isClickableInput } from '../click/isClickableInput.js';
import { isEditableInputOrTextArea } from '../edit/isEditable.js';
/**
* Determine if the element has its own selection implementation
* and does not interact with the Document Selection API.
*/ function hasOwnSelection(node) {
return isElement(node) && isEditableInputOrTextArea(node);
}
function hasNoSelection(node) {
return isElement(node) && isClickableInput(node);
}
function isElement(node) {
return node.nodeType === 1;
}
export { hasNoSelection, hasOwnSelection };

View File

@@ -0,0 +1,12 @@
const FOCUSABLE_SELECTOR = [
'input:not([type=hidden]):not([disabled])',
'button:not([disabled])',
'select:not([disabled])',
'textarea:not([disabled])',
'[contenteditable=""]',
'[contenteditable="true"]',
'a[href]',
'[tabindex]:not([disabled])'
].join(', ');
export { FOCUSABLE_SELECTOR };

View File

@@ -0,0 +1,29 @@
export { isClickableInput } from './click/isClickableInput.js';
export { readBlobText } from './dataTransfer/Blob.js';
export { createDataTransfer, getBlobFromDataTransferItem } from './dataTransfer/DataTransfer.js';
export { createFileList } from './dataTransfer/FileList.js';
export { attachClipboardStubToView, createClipboardItem, detachClipboardStubFromView, readDataTransferFromClipboard, resetClipboardStubOnView, writeDataTransferToClipboard } from './dataTransfer/Clipboard.js';
export { buildTimeValue, isValidDateOrTimeValue } from './edit/timeValue.js';
export { getContentEditable, isContentEditable } from './edit/isContentEditable.js';
export { isEditable, isEditableInputOrTextArea } from './edit/isEditable.js';
export { getMaxLength, supportsMaxLength } from './edit/maxLength.js';
export { setFiles } from './edit/setFiles.js';
export { getNextCursorPosition } from './focus/cursor.js';
export { getActiveElement, getActiveElementOrBody } from './focus/getActiveElement.js';
export { getTabDestination } from './focus/getTabDestination.js';
export { isFocusable } from './focus/isFocusable.js';
export { hasNoSelection, hasOwnSelection } from './focus/selection.js';
export { FOCUSABLE_SELECTOR } from './focus/selector.js';
export { readNextDescriptor } from './keyDef/readNextDescriptor.js';
export { cloneEvent } from './misc/cloneEvent.js';
export { findClosest } from './misc/findClosest.js';
export { getDocumentFromNode } from './misc/getDocumentFromNode.js';
export { getTreeDiff } from './misc/getTreeDiff.js';
export { getWindow } from './misc/getWindow.js';
export { isDescendantOrSelf } from './misc/isDescendantOrSelf.js';
export { isElementType } from './misc/isElementType.js';
export { isVisible } from './misc/isVisible.js';
export { isDisabled } from './misc/isDisabled.js';
export { ApiLevel, getLevelRef, setLevelRef } from './misc/level.js';
export { wait } from './misc/wait.js';
export { assertPointerEvents, hasPointerEvents } from './pointer/cssPointerEvents.js';

View File

@@ -0,0 +1,90 @@
var bracketDict = /*#__PURE__*/ function(bracketDict) {
bracketDict["{"] = "}";
bracketDict["["] = "]";
return bracketDict;
}(bracketDict || {});
/**
* Read the next key definition from user input
*
* Describe key per `{descriptor}` or `[descriptor]`.
* Everything else will be interpreted as a single character as descriptor - e.g. `a`.
* Brackets `{` and `[` can be escaped by doubling - e.g. `foo[[bar` translates to `foo[bar`.
* A previously pressed key can be released per `{/descriptor}`.
* Keeping the key pressed can be written as `{descriptor>}`.
* When keeping the key pressed you can choose how long the key is pressed `{descriptor>3}`.
* You can then release the key per `{descriptor>3/}` or keep it pressed and continue with the next key.
*/ function readNextDescriptor(text, context) {
let pos = 0;
const startBracket = text[pos] in bracketDict ? text[pos] : '';
pos += startBracket.length;
const isEscapedChar = new RegExp(`^\\${startBracket}{2}`).test(text);
const type = isEscapedChar ? '' : startBracket;
return {
type,
...type === '' ? readPrintableChar(text, pos, context) : readTag(text, pos, type, context)
};
}
function readPrintableChar(text, pos, context) {
const descriptor = text[pos];
assertDescriptor(descriptor, text, pos, context);
pos += descriptor.length;
return {
consumedLength: pos,
descriptor,
releasePrevious: false,
releaseSelf: true,
repeat: 1
};
}
function readTag(text, pos, startBracket, context) {
var _text_slice_match, _text_slice_match1;
const releasePreviousModifier = text[pos] === '/' ? '/' : '';
pos += releasePreviousModifier.length;
const escapedDescriptor = startBracket === '{' && text[pos] === '\\';
pos += Number(escapedDescriptor);
const descriptor = escapedDescriptor ? text[pos] : (_text_slice_match = text.slice(pos).match(startBracket === '{' ? /^\w+|^[^}>/]/ : /^\w+/)) === null || _text_slice_match === undefined ? undefined : _text_slice_match[0];
assertDescriptor(descriptor, text, pos, context);
pos += descriptor.length;
var _text_slice_match_;
const repeatModifier = (_text_slice_match_ = (_text_slice_match1 = text.slice(pos).match(/^>\d+/)) === null || _text_slice_match1 === undefined ? undefined : _text_slice_match1[0]) !== null && _text_slice_match_ !== undefined ? _text_slice_match_ : '';
pos += repeatModifier.length;
const releaseSelfModifier = text[pos] === '/' || !repeatModifier && text[pos] === '>' ? text[pos] : '';
pos += releaseSelfModifier.length;
const expectedEndBracket = bracketDict[startBracket];
const endBracket = text[pos] === expectedEndBracket ? expectedEndBracket : '';
if (!endBracket) {
throw new Error(getErrorMessage([
!repeatModifier && 'repeat modifier',
!releaseSelfModifier && 'release modifier',
`"${expectedEndBracket}"`
].filter(Boolean).join(' or '), text[pos], text, context));
}
pos += endBracket.length;
return {
consumedLength: pos,
descriptor,
releasePrevious: !!releasePreviousModifier,
repeat: repeatModifier ? Math.max(Number(repeatModifier.substr(1)), 1) : 1,
releaseSelf: hasReleaseSelf(releaseSelfModifier, repeatModifier)
};
}
function assertDescriptor(descriptor, text, pos, context) {
if (!descriptor) {
throw new Error(getErrorMessage('key descriptor', text[pos], text, context));
}
}
function hasReleaseSelf(releaseSelfModifier, repeatModifier) {
if (releaseSelfModifier) {
return releaseSelfModifier === '/';
}
if (repeatModifier) {
return false;
}
}
function getErrorMessage(expected, found, text, context) {
return `Expected ${expected} but found "${found !== null && found !== undefined ? found : ''}" in "${text}"
See ${context === 'pointer' ? `https://testing-library.com/docs/user-event/pointer#pressing-a-button-or-touching-the-screen` : `https://testing-library.com/docs/user-event/keyboard`}
for more information about how userEvent parses your input.`;
}
export { readNextDescriptor };

View File

@@ -0,0 +1,5 @@
function cloneEvent(event) {
return new event.constructor(event.type, event);
}
export { cloneEvent };

View File

@@ -0,0 +1,12 @@
function findClosest(element, callback) {
let el = element;
do {
if (callback(el)) {
return el;
}
el = el.parentElement;
}while (el && el !== element.ownerDocument.body)
return undefined;
}
export { findClosest };

View File

@@ -0,0 +1,8 @@
function getDocumentFromNode(el) {
return isDocument(el) ? el : el.ownerDocument;
}
function isDocument(node) {
return node.nodeType === 9;
}
export { getDocumentFromNode };

View File

@@ -0,0 +1,23 @@
function getTreeDiff(a, b) {
const treeA = [];
for(let el = a; el; el = el.parentElement){
treeA.push(el);
}
const treeB = [];
for(let el = b; el; el = el.parentElement){
treeB.push(el);
}
let i = 0;
for(;; i++){
if (i >= treeA.length || i >= treeB.length || treeA[treeA.length - 1 - i] !== treeB[treeB.length - 1 - i]) {
break;
}
}
return [
treeA.slice(0, treeA.length - i),
treeB.slice(0, treeB.length - i),
treeB.slice(treeB.length - i)
];
}
export { getTreeDiff };

View File

@@ -0,0 +1,17 @@
function getWindow(node) {
var _node_ownerDocument;
if (isDocument(node) && node.defaultView) {
return node.defaultView;
} else if ((_node_ownerDocument = node.ownerDocument) === null || _node_ownerDocument === undefined ? undefined : _node_ownerDocument.defaultView) {
return node.ownerDocument.defaultView;
}
throw new Error(`Could not determine window of node. Node was ${describe(node)}`);
}
function isDocument(node) {
return node.nodeType === 9;
}
function describe(val) {
return typeof val === 'function' ? `function ${val.name}` : val === null ? 'null' : String(val);
}
export { getWindow };

View File

@@ -0,0 +1,12 @@
function isDescendantOrSelf(potentialDescendant, potentialAncestor) {
let el = potentialDescendant;
do {
if (el === potentialAncestor) {
return true;
}
el = el.parentElement;
}while (el)
return false;
}
export { isDescendantOrSelf };

View File

@@ -0,0 +1,31 @@
import { isElementType } from './isElementType.js';
// This should probably just rely on the :disabled pseudo-class, but JSDOM doesn't implement it properly.
function isDisabled(element) {
for(let el = element; el; el = el.parentElement){
if (isElementType(el, [
'button',
'input',
'select',
'textarea',
'optgroup',
'option'
])) {
if (el.hasAttribute('disabled')) {
return true;
}
} else if (isElementType(el, 'fieldset')) {
var _el_querySelector;
if (el.hasAttribute('disabled') && !((_el_querySelector = el.querySelector(':scope > legend')) === null || _el_querySelector === undefined ? undefined : _el_querySelector.contains(element))) {
return true;
}
} else if (el.tagName.includes('-')) {
if (el.constructor.formAssociated && el.hasAttribute('disabled')) {
return true;
}
}
}
return false;
}
export { isDisabled };

View File

@@ -0,0 +1,18 @@
function isElementType(element, tag, props) {
if (element.namespaceURI && element.namespaceURI !== 'http://www.w3.org/1999/xhtml') {
return false;
}
tag = Array.isArray(tag) ? tag : [
tag
];
// tagName is uppercase in HTMLDocument and lowercase in XMLDocument
if (!tag.includes(element.tagName.toLowerCase())) {
return false;
}
if (props) {
return Object.entries(props).every(([k, v])=>element[k] === v);
}
return true;
}
export { isElementType };

View File

@@ -0,0 +1,17 @@
import { getWindow } from './getWindow.js';
function isVisible(element) {
const window = getWindow(element);
for(let el = element; el === null || el === undefined ? undefined : el.ownerDocument; el = el.parentElement){
const { display, visibility } = window.getComputedStyle(el);
if (display === 'none') {
return false;
}
if (visibility === 'hidden') {
return false;
}
}
return true;
}
export { isVisible };

View File

@@ -0,0 +1,13 @@
var ApiLevel = /*#__PURE__*/ function(ApiLevel) {
ApiLevel[ApiLevel["Trigger"] = 2] = "Trigger";
ApiLevel[ApiLevel["Call"] = 1] = "Call";
return ApiLevel;
}({});
function setLevelRef(instance, level) {
instance.levelRefs[level] = {};
}
function getLevelRef(instance, level) {
return instance.levelRefs[level];
}
export { ApiLevel, getLevelRef, setLevelRef };

Some files were not shown because too many files have changed in this diff Show More