containing any provided children.
- *
- * @param {object} module the mock function object exported from a
- * module that defines the component to be mocked
- * @param {?string} mockTagName optional dummy root tag name to return
- * from render method (overrides
- * module.mockTagName if provided)
- * @return {object} the ReactTestUtils object (for chaining)
- */
-
-
- function mockComponent(module, mockTagName) {
- {
- if (!hasWarnedAboutDeprecatedMockComponent) {
- hasWarnedAboutDeprecatedMockComponent = true;
-
- warn('ReactTestUtils.mockComponent() is deprecated. ' + 'Use shallow rendering or jest.mock() instead.\n\n' + 'See https://reactjs.org/link/test-utils-mock-component for more information.');
- }
- }
-
- mockTagName = mockTagName || module.mockTagName || 'div';
- module.prototype.render.mockImplementation(function () {
- return React.createElement(mockTagName, null, this.props.children);
- });
- return this;
- }
-
- function nativeTouchData(x, y) {
- return {
- touches: [{
- pageX: x,
- pageY: y
- }]
- };
- } // Start of inline: the below functions were inlined from
- // EventPropagator.js, as they deviated from ReactDOM's newer
- // implementations.
-
- /**
- * Dispatch the event to the listener.
- * @param {SyntheticEvent} event SyntheticEvent to handle
- * @param {function} listener Application-level callback
- * @param {*} inst Internal component instance
- */
-
-
- function executeDispatch(event, listener, inst) {
- var type = event.type || 'unknown-event';
- event.currentTarget = getNodeFromInstance(inst);
- invokeGuardedCallbackAndCatchFirstError(type, listener, undefined, event);
- event.currentTarget = null;
- }
- /**
- * Standard/simple iteration through an event's collected dispatches.
- */
-
-
- function executeDispatchesInOrder(event) {
- var dispatchListeners = event._dispatchListeners;
- var dispatchInstances = event._dispatchInstances;
-
- if (Array.isArray(dispatchListeners)) {
- for (var i = 0; i < dispatchListeners.length; i++) {
- if (event.isPropagationStopped()) {
- break;
- } // Listeners and Instances are two parallel arrays that are always in sync.
-
-
- executeDispatch(event, dispatchListeners[i], dispatchInstances[i]);
- }
- } else if (dispatchListeners) {
- executeDispatch(event, dispatchListeners, dispatchInstances);
- }
-
- event._dispatchListeners = null;
- event._dispatchInstances = null;
- }
- /**
- * Dispatches an event and releases it back into the pool, unless persistent.
- *
- * @param {?object} event Synthetic event to be dispatched.
- * @private
- */
-
-
- var executeDispatchesAndRelease = function (event) {
- if (event) {
- executeDispatchesInOrder(event);
-
- if (!event.isPersistent()) {
- event.constructor.release(event);
- }
- }
- };
-
- function isInteractive(tag) {
- return tag === 'button' || tag === 'input' || tag === 'select' || tag === 'textarea';
- }
-
- function getParent(inst) {
- do {
- inst = inst.return; // TODO: If this is a HostRoot we might want to bail out.
- // That is depending on if we want nested subtrees (layers) to bubble
- // events to their parent. We could also go through parentNode on the
- // host node but that wouldn't work for React Native and doesn't let us
- // do the portal feature.
- } while (inst && inst.tag !== HostComponent);
-
- if (inst) {
- return inst;
- }
-
- return null;
- }
- /**
- * Simulates the traversal of a two-phase, capture/bubble event dispatch.
- */
-
-
- function traverseTwoPhase(inst, fn, arg) {
- var path = [];
-
- while (inst) {
- path.push(inst);
- inst = getParent(inst);
- }
-
- var i;
-
- for (i = path.length; i-- > 0;) {
- fn(path[i], 'captured', arg);
- }
-
- for (i = 0; i < path.length; i++) {
- fn(path[i], 'bubbled', arg);
- }
- }
-
- function shouldPreventMouseEvent(name, type, props) {
- switch (name) {
- case 'onClick':
- case 'onClickCapture':
- case 'onDoubleClick':
- case 'onDoubleClickCapture':
- case 'onMouseDown':
- case 'onMouseDownCapture':
- case 'onMouseMove':
- case 'onMouseMoveCapture':
- case 'onMouseUp':
- case 'onMouseUpCapture':
- case 'onMouseEnter':
- return !!(props.disabled && isInteractive(type));
-
- default:
- return false;
- }
- }
- /**
- * @param {object} inst The instance, which is the source of events.
- * @param {string} registrationName Name of listener (e.g. `onClick`).
- * @return {?function} The stored callback.
- */
-
-
- function getListener(inst, registrationName) {
- // TODO: shouldPreventMouseEvent is DOM-specific and definitely should not
- // live here; needs to be moved to a better place soon
- var stateNode = inst.stateNode;
-
- if (!stateNode) {
- // Work in progress (ex: onload events in incremental mode).
- return null;
- }
-
- var props = getFiberCurrentPropsFromNode(stateNode);
-
- if (!props) {
- // Work in progress.
- return null;
- }
-
- var listener = props[registrationName];
-
- if (shouldPreventMouseEvent(registrationName, inst.type, props)) {
- return null;
- }
-
- if (!(!listener || typeof listener === 'function')) {
- {
- throw Error( "Expected `" + registrationName + "` listener to be a function, instead got a value of `" + typeof listener + "` type." );
- }
- }
-
- return listener;
- }
-
- function listenerAtPhase(inst, event, propagationPhase) {
- var registrationName = event._reactName;
-
- if (propagationPhase === 'captured') {
- registrationName += 'Capture';
- }
-
- return getListener(inst, registrationName);
- }
-
- function accumulateDispatches(inst, ignoredDirection, event) {
- if (inst && event && event._reactName) {
- var registrationName = event._reactName;
- var listener = getListener(inst, registrationName);
-
- if (listener) {
- if (event._dispatchListeners == null) {
- event._dispatchListeners = [];
- }
-
- if (event._dispatchInstances == null) {
- event._dispatchInstances = [];
- }
-
- event._dispatchListeners.push(listener);
-
- event._dispatchInstances.push(inst);
- }
- }
- }
-
- function accumulateDirectionalDispatches(inst, phase, event) {
- {
- if (!inst) {
- error('Dispatching inst must not be null');
- }
- }
-
- var listener = listenerAtPhase(inst, event, phase);
-
- if (listener) {
- if (event._dispatchListeners == null) {
- event._dispatchListeners = [];
- }
-
- if (event._dispatchInstances == null) {
- event._dispatchInstances = [];
- }
-
- event._dispatchListeners.push(listener);
-
- event._dispatchInstances.push(inst);
- }
- }
-
- function accumulateDirectDispatchesSingle(event) {
- if (event && event._reactName) {
- accumulateDispatches(event._targetInst, null, event);
- }
- }
-
- function accumulateTwoPhaseDispatchesSingle(event) {
- if (event && event._reactName) {
- traverseTwoPhase(event._targetInst, accumulateDirectionalDispatches, event);
- }
- } // End of inline
-
-
- var Simulate = {};
- var directDispatchEventTypes = new Set(['mouseEnter', 'mouseLeave', 'pointerEnter', 'pointerLeave']);
- /**
- * Exports:
- *
- * - `Simulate.click(Element)`
- * - `Simulate.mouseMove(Element)`
- * - `Simulate.change(Element)`
- * - ... (All keys from event plugin `eventTypes` objects)
- */
-
- function makeSimulator(eventType) {
- return function (domNode, eventData) {
- if (!!React.isValidElement(domNode)) {
- {
- throw Error( "TestUtils.Simulate expected a DOM node as the first argument but received a React element. Pass the DOM node you wish to simulate the event on instead. Note that TestUtils.Simulate will not work if you are using shallow rendering." );
- }
- }
-
- if (!!isCompositeComponent(domNode)) {
- {
- throw Error( "TestUtils.Simulate expected a DOM node as the first argument but received a component instance. Pass the DOM node you wish to simulate the event on instead." );
- }
- }
-
- var reactName = 'on' + eventType[0].toUpperCase() + eventType.slice(1);
- var fakeNativeEvent = new Event();
- fakeNativeEvent.target = domNode;
- fakeNativeEvent.type = eventType.toLowerCase();
- var targetInst = getInstanceFromNode(domNode);
- var event = new SyntheticEvent(reactName, fakeNativeEvent.type, targetInst, fakeNativeEvent, domNode); // Since we aren't using pooling, always persist the event. This will make
- // sure it's marked and won't warn when setting additional properties.
-
- event.persist();
-
- _assign(event, eventData);
-
- if (directDispatchEventTypes.has(eventType)) {
- accumulateDirectDispatchesSingle(event);
- } else {
- accumulateTwoPhaseDispatchesSingle(event);
- }
-
- ReactDOM.unstable_batchedUpdates(function () {
- // Normally extractEvent enqueues a state restore, but we'll just always
- // do that since we're by-passing it here.
- enqueueStateRestore(domNode);
- executeDispatchesAndRelease(event);
- rethrowCaughtError();
- });
- restoreStateIfNeeded();
- };
- } // A one-time snapshot with no plans to update. We'll probably want to deprecate Simulate API.
-
-
- var simulatedEventTypes = ['blur', 'cancel', 'click', 'close', 'contextMenu', 'copy', 'cut', 'auxClick', 'doubleClick', 'dragEnd', 'dragStart', 'drop', 'focus', 'input', 'invalid', 'keyDown', 'keyPress', 'keyUp', 'mouseDown', 'mouseUp', 'paste', 'pause', 'play', 'pointerCancel', 'pointerDown', 'pointerUp', 'rateChange', 'reset', 'seeked', 'submit', 'touchCancel', 'touchEnd', 'touchStart', 'volumeChange', 'drag', 'dragEnter', 'dragExit', 'dragLeave', 'dragOver', 'mouseMove', 'mouseOut', 'mouseOver', 'pointerMove', 'pointerOut', 'pointerOver', 'scroll', 'toggle', 'touchMove', 'wheel', 'abort', 'animationEnd', 'animationIteration', 'animationStart', 'canPlay', 'canPlayThrough', 'durationChange', 'emptied', 'encrypted', 'ended', 'error', 'gotPointerCapture', 'load', 'loadedData', 'loadedMetadata', 'loadStart', 'lostPointerCapture', 'playing', 'progress', 'seeking', 'stalled', 'suspend', 'timeUpdate', 'transitionEnd', 'waiting', 'mouseEnter', 'mouseLeave', 'pointerEnter', 'pointerLeave', 'change', 'select', 'beforeInput', 'compositionEnd', 'compositionStart', 'compositionUpdate'];
-
- function buildSimulators() {
- simulatedEventTypes.forEach(function (eventType) {
- Simulate[eventType] = makeSimulator(eventType);
- });
- }
-
- buildSimulators();
-
- exports.Simulate = Simulate;
- exports.act = act;
- exports.findAllInRenderedTree = findAllInRenderedTree;
- exports.findRenderedComponentWithType = findRenderedComponentWithType;
- exports.findRenderedDOMComponentWithClass = findRenderedDOMComponentWithClass;
- exports.findRenderedDOMComponentWithTag = findRenderedDOMComponentWithTag;
- exports.isCompositeComponent = isCompositeComponent;
- exports.isCompositeComponentWithType = isCompositeComponentWithType;
- exports.isDOMComponent = isDOMComponent;
- exports.isDOMComponentElement = isDOMComponentElement;
- exports.isElement = isElement;
- exports.isElementOfType = isElementOfType;
- exports.mockComponent = mockComponent;
- exports.nativeTouchData = nativeTouchData;
- exports.renderIntoDocument = renderIntoDocument;
- exports.scryRenderedComponentsWithType = scryRenderedComponentsWithType;
- exports.scryRenderedDOMComponentsWithClass = scryRenderedDOMComponentsWithClass;
- exports.scryRenderedDOMComponentsWithTag = scryRenderedDOMComponentsWithTag;
- exports.traverseTwoPhase = traverseTwoPhase;
- exports.unstable_concurrentAct = unstable_concurrentAct;
- })();
- }
- });
-
- var testUtils = createCommonjsModule(function (module) {
-
- {
- module.exports = reactDomTestUtils_development;
- }
- });
-
- var reactAct = testUtils.act;
- var actSupported = reactAct !== undefined; // act is supported react-dom@16.8.0
- // so for versions that don't have act from test utils
- // we do this little polyfill. No warnings, but it's
- // better than nothing.
-
- function actPolyfill(cb) {
- m__default['default'].unstable_batchedUpdates(cb);
- m__default['default'].render( /*#__PURE__*/l.createElement("div", null), document.createElement('div'));
- }
-
- var act = reactAct || actPolyfill;
- var youHaveBeenWarned = false;
- var isAsyncActSupported = null;
-
- function asyncAct(cb) {
- if (actSupported === true) {
- if (isAsyncActSupported === null) {
- return new Promise(function (resolve, reject) {
- // patch console.error here
- var originalConsoleError = console.error;
-
- console.error = function error() {
- for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
- args[_key] = arguments[_key];
- }
-
- /* if console.error fired *with that specific message* */
-
- /* istanbul ignore next */
- var firstArgIsString = typeof args[0] === 'string';
-
- if (firstArgIsString && args[0].indexOf('Warning: Do not await the result of calling ReactTestUtils.act') === 0) {
- // v16.8.6
- isAsyncActSupported = false;
- } else if (firstArgIsString && args[0].indexOf('Warning: The callback passed to ReactTestUtils.act(...) function must not return anything') === 0) ; else {
- originalConsoleError.apply(console, args);
- }
- };
-
- var cbReturn, result;
-
- try {
- result = reactAct(function () {
- cbReturn = cb();
- return cbReturn;
- });
- } catch (err) {
- console.error = originalConsoleError;
- reject(err);
- return;
- }
-
- result.then(function () {
- console.error = originalConsoleError; // if it got here, it means async act is supported
-
- isAsyncActSupported = true;
- resolve();
- }, function (err) {
- console.error = originalConsoleError;
- isAsyncActSupported = true;
- reject(err);
- }); // 16.8.6's act().then() doesn't call a resolve handler, so we need to manually flush here, sigh
-
- if (isAsyncActSupported === false) {
- console.error = originalConsoleError;
- /* istanbul ignore next */
-
- if (!youHaveBeenWarned) {
- // if act is supported and async act isn't and they're trying to use async
- // act, then they need to upgrade from 16.8 to 16.9.
- // This is a seamless upgrade, so we'll add a warning
- console.error("It looks like you're using a version of react-dom that supports the \"act\" function, but not an awaitable version of \"act\" which you will need. Please upgrade to at least react-dom@16.9.0 to remove this warning.");
- youHaveBeenWarned = true;
- }
-
- cbReturn.then(function () {
- // a faux-version.
- // todo - copy https://github.com/facebook/react/blob/master/packages/shared/enqueueTask.js
- Promise.resolve().then(function () {
- // use sync act to flush effects
- act(function () {});
- resolve();
- });
- }, reject);
- }
- });
- } else if (isAsyncActSupported === false) {
- // use the polyfill directly
- var _result;
-
- act(function () {
- _result = cb();
- });
- return _result.then(function () {
- return Promise.resolve().then(function () {
- // use sync act to flush effects
- act(function () {});
- });
- });
- } // all good! regular act
-
-
- return act(cb);
- } // use the polyfill
-
-
- var result;
- act(function () {
- result = cb();
- });
- return result.then(function () {
- return Promise.resolve().then(function () {
- // use sync act to flush effects
- act(function () {});
- });
- });
- }
- /* eslint no-console:0 */
-
- // dom-testing-library's version of fireEvent. The reason
- // we make this distinction however is because we have
- // a few extra events that work a bit differently
-
- var fireEvent = function fireEvent() {
- return fireEvent$1.apply(void 0, arguments);
- };
-
- Object.keys(fireEvent$1).forEach(function (key) {
- fireEvent[key] = function () {
- return fireEvent$1[key].apply(fireEvent$1, arguments);
- };
- }); // React event system tracks native mouseOver/mouseOut events for
- // running onMouseEnter/onMouseLeave handlers
- // @link https://github.com/facebook/react/blob/b87aabdfe1b7461e7331abb3601d9e6bb27544bc/packages/react-dom/src/events/EnterLeaveEventPlugin.js#L24-L31
-
- var mouseEnter = fireEvent.mouseEnter;
- var mouseLeave = fireEvent.mouseLeave;
-
- fireEvent.mouseEnter = function () {
- mouseEnter.apply(void 0, arguments);
- return fireEvent.mouseOver.apply(fireEvent, arguments);
- };
-
- fireEvent.mouseLeave = function () {
- mouseLeave.apply(void 0, arguments);
- return fireEvent.mouseOut.apply(fireEvent, arguments);
- };
-
- var pointerEnter = fireEvent.pointerEnter;
- var pointerLeave = fireEvent.pointerLeave;
-
- fireEvent.pointerEnter = function () {
- pointerEnter.apply(void 0, arguments);
- return fireEvent.pointerOver.apply(fireEvent, arguments);
- };
-
- fireEvent.pointerLeave = function () {
- pointerLeave.apply(void 0, arguments);
- return fireEvent.pointerOut.apply(fireEvent, arguments);
- };
-
- var select = fireEvent.select;
-
- fireEvent.select = function (node, init) {
- select(node, init); // React tracks this event only on focused inputs
-
- node.focus(); // React creates this event when one of the following native events happens
- // - contextMenu
- // - mouseUp
- // - dragEnd
- // - keyUp
- // - keyDown
- // so we can use any here
- // @link https://github.com/facebook/react/blob/b87aabdfe1b7461e7331abb3601d9e6bb27544bc/packages/react-dom/src/events/SelectEventPlugin.js#L203-L224
-
- fireEvent.keyUp(node, init);
- }; // React event system tracks native focusout/focusin events for
- // running blur/focus handlers
- // @link https://github.com/facebook/react/pull/19186
-
-
- var blur$1 = fireEvent.blur;
- var focus$1 = fireEvent.focus;
-
- fireEvent.blur = function () {
- fireEvent.focusOut.apply(fireEvent, arguments);
- return blur$1.apply(void 0, arguments);
- };
-
- fireEvent.focus = function () {
- fireEvent.focusIn.apply(fireEvent, arguments);
- return focus$1.apply(void 0, arguments);
- };
-
- configure({
- asyncWrapper: function () {
- var _asyncWrapper = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee2(cb) {
- var result;
- return regenerator.wrap(function _callee2$(_context2) {
- while (1) {
- switch (_context2.prev = _context2.next) {
- case 0:
- _context2.next = 2;
- return asyncAct( /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee() {
- return regenerator.wrap(function _callee$(_context) {
- while (1) {
- switch (_context.prev = _context.next) {
- case 0:
- _context.next = 2;
- return cb();
-
- case 2:
- result = _context.sent;
-
- case 3:
- case "end":
- return _context.stop();
- }
- }
- }, _callee);
- })));
-
- case 2:
- return _context2.abrupt("return", result);
-
- case 3:
- case "end":
- return _context2.stop();
- }
- }
- }, _callee2);
- }));
-
- function asyncWrapper(_x) {
- return _asyncWrapper.apply(this, arguments);
- }
-
- return asyncWrapper;
- }(),
- eventWrapper: function eventWrapper(cb) {
- var result;
- act(function () {
- result = cb();
- });
- return result;
- }
- });
- var mountedContainers = new Set();
-
- function render(ui, _temp) {
- var _ref2 = _temp === void 0 ? {} : _temp,
- container = _ref2.container,
- _ref2$baseElement = _ref2.baseElement,
- baseElement = _ref2$baseElement === void 0 ? container : _ref2$baseElement,
- queries = _ref2.queries,
- _ref2$hydrate = _ref2.hydrate,
- hydrate = _ref2$hydrate === void 0 ? false : _ref2$hydrate,
- WrapperComponent = _ref2.wrapper;
-
- if (!baseElement) {
- // default to document.body instead of documentElement to avoid output of potentially-large
- // head elements (such as JSS style blocks) in debug output
- baseElement = document.body;
- }
-
- if (!container) {
- container = baseElement.appendChild(document.createElement('div'));
- } // we'll add it to the mounted containers regardless of whether it's actually
- // added to document.body so the cleanup method works regardless of whether
- // they're passing us a custom container or not.
-
-
- mountedContainers.add(container);
-
- var wrapUiIfNeeded = function wrapUiIfNeeded(innerElement) {
- return WrapperComponent ? /*#__PURE__*/l.createElement(WrapperComponent, null, innerElement) : innerElement;
- };
-
- act(function () {
- if (hydrate) {
- m__default['default'].hydrate(wrapUiIfNeeded(ui), container);
- } else {
- m__default['default'].render(wrapUiIfNeeded(ui), container);
- }
- });
- return _extends({
- container: container,
- baseElement: baseElement,
- debug: function debug(el, maxLength, options) {
- if (el === void 0) {
- el = baseElement;
- }
-
- return Array.isArray(el) ? // eslint-disable-next-line no-console
- el.forEach(function (e) {
- return console.log(prettyDOM(e, maxLength, options));
- }) : // eslint-disable-next-line no-console,
- console.log(prettyDOM(el, maxLength, options));
- },
- unmount: function unmount() {
- act(function () {
- m__default['default'].unmountComponentAtNode(container);
- });
- },
- rerender: function rerender(rerenderUi) {
- render(wrapUiIfNeeded(rerenderUi), {
- container: container,
- baseElement: baseElement
- }); // Intentionally do not return anything to avoid unnecessarily complicating the API.
- // folks can use all the same utilities we return in the first place that are bound to the container
- },
- asFragment: function asFragment() {
- /* istanbul ignore else (old jsdom limitation) */
- if (typeof document.createRange === 'function') {
- return document.createRange().createContextualFragment(container.innerHTML);
- } else {
- var template = document.createElement('template');
- template.innerHTML = container.innerHTML;
- return template.content;
- }
- }
- }, getQueriesForElement(baseElement, queries));
- }
-
- function cleanup() {
- mountedContainers.forEach(cleanupAtContainer);
- } // maybe one day we'll expose this (perhaps even as a utility returned by render).
- // but let's wait until someone asks for it.
-
-
- function cleanupAtContainer(container) {
- act(function () {
- m__default['default'].unmountComponentAtNode(container);
- });
-
- if (container.parentNode === document.body) {
- document.body.removeChild(container);
- }
-
- mountedContainers.delete(container);
- } // just re-export everything from dom-testing-library
- // thing for people using react-dom@16.8.0. Anyone else doesn't need it and
- // people should just upgrade anyway.
-
- /* eslint func-name-matching:0 */
-
- // or teardown then we'll automatically run cleanup afterEach test
- // this ensures that tests run in isolation from each other
- // if you don't like this then either import the `pure` module
- // or set the RTL_SKIP_AUTO_CLEANUP env variable to 'true'.
-
- {
- // ignore teardown() in code coverage because Jest does not support it
-
- /* istanbul ignore else */
- if (typeof afterEach === 'function') {
- afterEach(function () {
- cleanup();
- });
- } else if (typeof teardown === 'function') {
- // Block is guarded by `typeof` check.
- // eslint does not support `typeof` guards.
- // eslint-disable-next-line no-undef
- teardown(function () {
- cleanup();
- });
- }
- }
-
- // Copyright 2021 Workiva Inc.
-
- var buildTestingLibraryElementError = function buildTestingLibraryElementError(message) {
- var err = new Error(message);
- err.name = 'TestingLibraryElementError';
- return err;
- };
-
- var buildJsGetElementError = function buildJsGetElementError(message, container) {
- var _message$replace;
-
- // With findBy* async queries, there is a race condition during which `originalMessage` will already
- // contain the prettyDOM-printed HTML of the `container`. This causes the prettyDOM-printed HTML to be
- // output twice in the error because of the call to `setEphemeralElementErrorMessage`,
- // which calls `buildCustomTestingLibraryElementJsError`, which assumes that the prettyDOM-printed output
- // is not already there. So we'll do an additional replace here to get rid of the prettyDOM-printed output
- // if found.
- var prettyDOMRegex = /(?<=[\s\S]*)\s*<\w+>[\s\S]+/gm;
- var newMessage = (_message$replace = message === null || message === void 0 ? void 0 : message.replace(prettyDOMRegex, '')) !== null && _message$replace !== void 0 ? _message$replace : '';
- var prettyDomOutput = prettyDOM(container);
- return buildTestingLibraryElementError([newMessage, prettyDomOutput].filter(Boolean).join('\n\n'));
- };
-
- var getMouseEventOptions_2 = getMouseEventOptions;
-
- function isMousePressEvent(event) {
- return event === 'mousedown' || event === 'mouseup' || event === 'click' || event === 'dblclick';
- } // https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/buttons
-
-
- const BUTTONS_NAMES = {
- none: 0,
- primary: 1,
- secondary: 2,
- auxiliary: 4
- }; // https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/button
-
- const BUTTON_NAMES = {
- primary: 0,
- auxiliary: 1,
- secondary: 2
- };
-
- function translateButtonNumber(value, from) {
- var _Object$entries$find;
-
- const [mapIn, mapOut] = from === 'button' ? [BUTTON_NAMES, BUTTONS_NAMES] : [BUTTONS_NAMES, BUTTON_NAMES];
- const name = (_Object$entries$find = Object.entries(mapIn).find(([, i]) => i === value)) == null ? void 0 : _Object$entries$find[0]; // istanbul ignore next
-
- return name && Object.prototype.hasOwnProperty.call(mapOut, name) ? mapOut[name] : 0;
- }
-
- function convertMouseButtons(event, init, property) {
- if (!isMousePressEvent(event)) {
- return 0;
- }
-
- if (typeof init[property] === 'number') {
- return init[property];
- } else if (property === 'button' && typeof init.buttons === 'number') {
- return translateButtonNumber(init.buttons, 'buttons');
- } else if (property === 'buttons' && typeof init.button === 'number') {
- return translateButtonNumber(init.button, 'button');
- }
-
- return property != 'button' && isMousePressEvent(event) ? 1 : 0;
- }
-
- function getMouseEventOptions(event, init, clickCount = 0) {
- var _init;
-
- init = (_init = init) != null ? _init : {};
- return { ...init,
- // https://developer.mozilla.org/en-US/docs/Web/API/UIEvent/detail
- detail: event === 'mousedown' || event === 'mouseup' || event === 'click' ? 1 + clickCount : clickCount,
- buttons: convertMouseButtons(event, init, 'buttons'),
- button: convertMouseButtons(event, init, 'button')
- };
- }
-
- var getMouseEventOptions_1 = /*#__PURE__*/Object.defineProperty({
- getMouseEventOptions: getMouseEventOptions_2
- }, '__esModule', {value: true});
-
- var isElementType_2 = isElementType;
-
- 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;
- }
-
- var isElementType_1 = /*#__PURE__*/Object.defineProperty({
- isElementType: isElementType_2
- }, '__esModule', {value: true});
-
- var isClickableInput_2 = isClickableInput;
-
-
-
- const CLICKABLE_INPUT_TYPES = ['button', 'color', 'file', 'image', 'reset', 'submit', 'checkbox', 'radio'];
-
- function isClickableInput(element) {
- return (0, isElementType_1.isElementType)(element, 'button') || (0, isElementType_1.isElementType)(element, 'input') && CLICKABLE_INPUT_TYPES.includes(element.type);
- }
-
- var isClickableInput_1 = /*#__PURE__*/Object.defineProperty({
- isClickableInput: isClickableInput_2
- }, '__esModule', {value: true});
-
- var buildTimeValue_2 = buildTimeValue;
-
- 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')}`;
- }
-
- var buildTimeValue_1 = /*#__PURE__*/Object.defineProperty({
- buildTimeValue: buildTimeValue_2
- }, '__esModule', {value: true});
-
- var getSelectionRange_1 = getSelectionRange;
- var hasSelectionSupport_1 = hasSelectionSupport;
- var setSelectionRange_1 = setSelectionRange;
-
-
-
- // https://github.com/jsdom/jsdom/blob/c2fb8ff94917a4d45e2398543f5dd2a8fed0bdab/lib/jsdom/living/nodes/HTMLInputElement-impl.js#L45
- var selectionSupportType;
-
- (function (selectionSupportType) {
- selectionSupportType["text"] = "text";
- selectionSupportType["search"] = "search";
- selectionSupportType["url"] = "url";
- selectionSupportType["tel"] = "tel";
- selectionSupportType["password"] = "password";
- })(selectionSupportType || (selectionSupportType = {}));
-
- const InputSelection = Symbol('inputSelection');
-
- function hasSelectionSupport(element) {
- return (0, isElementType_1.isElementType)(element, 'textarea') || (0, isElementType_1.isElementType)(element, 'input') && Boolean(selectionSupportType[element.type]);
- }
-
- function getSelectionRange(element) {
- if (hasSelectionSupport(element)) {
- return {
- selectionStart: element.selectionStart,
- selectionEnd: element.selectionEnd
- };
- }
-
- if ((0, isElementType_1.isElementType)(element, 'input')) {
- var _InputSelection;
-
- return (_InputSelection = element[InputSelection]) != null ? _InputSelection : {
- selectionStart: null,
- selectionEnd: null
- };
- }
-
- const selection = element.ownerDocument.getSelection(); // there should be no editing if the focusNode is outside of element
- // TODO: properly handle selection ranges
-
- if (selection != null && selection.rangeCount && element.contains(selection.focusNode)) {
- const range = selection.getRangeAt(0);
- return {
- selectionStart: range.startOffset,
- selectionEnd: range.endOffset
- };
- } else {
- return {
- selectionStart: null,
- selectionEnd: null
- };
- }
- }
-
- function setSelectionRange(element, newSelectionStart, newSelectionEnd) {
- const {
- selectionStart,
- selectionEnd
- } = getSelectionRange(element);
-
- if (selectionStart === newSelectionStart && selectionEnd === newSelectionEnd) {
- return;
- }
-
- if (hasSelectionSupport(element)) {
- element.setSelectionRange(newSelectionStart, newSelectionEnd);
- }
-
- if ((0, isElementType_1.isElementType)(element, 'input')) {
- element[InputSelection] = {
- selectionStart: newSelectionStart,
- selectionEnd: newSelectionEnd
- };
- } // Moving the selection inside
or