@testing-library/user-event 14.0.0-alpha.3 → 14.0.0-alpha.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/dist/click.d.ts +1 -0
  2. package/dist/click.js +17 -0
  3. package/dist/document/index.d.ts +3 -3
  4. package/dist/document/index.js +8 -10
  5. package/dist/document/interceptor.d.ts +11 -1
  6. package/dist/document/interceptor.js +7 -4
  7. package/dist/document/selection.d.ts +17 -8
  8. package/dist/document/selection.js +51 -28
  9. package/dist/document/value.d.ts +5 -1
  10. package/dist/document/value.js +27 -6
  11. package/dist/keyboard/keyMap.js +4 -0
  12. package/dist/keyboard/keyboardImplementation.js +3 -1
  13. package/dist/keyboard/plugins/arrow.js +7 -12
  14. package/dist/keyboard/plugins/character.js +23 -42
  15. package/dist/keyboard/plugins/control.js +4 -12
  16. package/dist/keyboard/plugins/functional.js +23 -11
  17. package/dist/paste.js +8 -15
  18. package/dist/pointer/pointerMove.js +28 -17
  19. package/dist/pointer/pointerPress.js +6 -4
  20. package/dist/pointer/resolveSelectionTarget.js +7 -6
  21. package/dist/setup.d.ts +5 -2
  22. package/dist/setup.js +4 -7
  23. package/dist/tab.d.ts +1 -2
  24. package/dist/tab.js +3 -132
  25. package/dist/utils/edit/calculateNewValue.d.ts +14 -5
  26. package/dist/utils/edit/calculateNewValue.js +23 -21
  27. package/dist/utils/edit/fireInputEvent.d.ts +5 -2
  28. package/dist/utils/edit/fireInputEvent.js +35 -25
  29. package/dist/utils/edit/isContentEditable.d.ts +4 -0
  30. package/dist/utils/edit/isContentEditable.js +14 -0
  31. package/dist/utils/edit/isEditable.d.ts +1 -0
  32. package/dist/utils/edit/prepareInput.d.ts +4 -0
  33. package/dist/utils/edit/prepareInput.js +60 -0
  34. package/dist/utils/focus/focus.js +3 -0
  35. package/dist/utils/focus/getTabDestination.d.ts +1 -0
  36. package/dist/utils/focus/getTabDestination.js +71 -0
  37. package/dist/utils/focus/selection.d.ts +42 -0
  38. package/dist/utils/focus/selection.js +190 -0
  39. package/dist/utils/index.d.ts +3 -3
  40. package/dist/utils/index.js +30 -30
  41. package/package.json +1 -1
  42. package/dist/document/applyNative.d.ts +0 -8
  43. package/dist/document/applyNative.js +0 -28
  44. package/dist/utils/edit/cursorPosition.d.ts +0 -2
  45. package/dist/utils/edit/cursorPosition.js +0 -35
  46. package/dist/utils/edit/selectionRange.d.ts +0 -5
  47. package/dist/utils/edit/selectionRange.js +0 -64
  48. package/dist/utils/misc/isDocument.d.ts +0 -1
  49. package/dist/utils/misc/isDocument.js +0 -10
package/dist/paste.js CHANGED
@@ -17,6 +17,8 @@ function paste(element, text, init, {
17
17
  initialSelectionStart,
18
18
  initialSelectionEnd
19
19
  } = {}) {
20
+ var _prepareInput;
21
+
20
22
  // TODO: implement for contenteditable
21
23
  if (!isSupportedElement(element)) {
22
24
  throw new TypeError(`The given ${element.tagName} element is currently unsupported.
@@ -47,21 +49,12 @@ function paste(element, text, init, {
47
49
  }
48
50
 
49
51
  text = text.substr(0, (0, _utils.getSpaceUntilMaxLength)(element));
50
- const {
51
- newValue,
52
- newSelectionStart
53
- } = (0, _utils.calculateNewValue)(text, element);
52
+ const inputRange = (0, _utils.getInputRange)(element);
53
+ /* istanbul ignore if */
54
54
 
55
- _dom.fireEvent.input(element, {
56
- inputType: 'insertFromPaste',
57
- target: {
58
- value: newValue
59
- }
60
- });
55
+ if (!inputRange) {
56
+ return;
57
+ }
61
58
 
62
- (0, _utils.setSelectionRange)(element, // TODO: investigate why the selection caused by invalid parameters was expected
63
- {
64
- newSelectionStart,
65
- selectionEnd: newSelectionStart
66
- }, {});
59
+ (_prepareInput = (0, _utils.prepareInput)(text, element, 'insertFromPaste')) == null ? void 0 : _prepareInput.commit();
67
60
  }
@@ -58,31 +58,42 @@ async function pointerMove({
58
58
  fireMove(target, coords);
59
59
 
60
60
  if (selectionRange) {
61
+ // TODO: support extending range (shift)
61
62
  const selectionFocus = (0, _resolveSelectionTarget.resolveSelectionTarget)({
62
63
  target,
63
64
  node,
64
65
  offset
65
66
  });
66
67
 
67
- if ('node' in selectionRange && selectionFocus.node === selectionRange.node) {
68
- (0, _document.setUISelection)(selectionRange.node, Math.min(selectionRange.start, selectionFocus.offset), Math.max(selectionRange.end, selectionFocus.offset));
69
- } else
70
- /* istanbul ignore else */
71
- if ('setEnd' in selectionRange) {
72
- const range = selectionRange.cloneRange();
73
- const cmp = selectionRange.comparePoint(selectionFocus.node, selectionFocus.offset);
74
-
75
- if (cmp < 0) {
76
- range.setStart(selectionFocus.node, selectionFocus.offset);
77
- } else if (cmp > 0) {
78
- range.setEnd(selectionFocus.node, selectionFocus.offset);
79
- } // TODO: support multiple ranges
68
+ if ('node' in selectionRange) {
69
+ // When the mouse is dragged outside of an input/textarea,
70
+ // the selection is extended to the beginning or end of the input
71
+ // depending on pointer position.
72
+ // TODO: extend selection according to pointer position
80
73
 
81
-
82
- const selection = target.ownerDocument.getSelection();
83
- selection.removeAllRanges();
84
- selection.addRange(range.cloneRange());
74
+ /* istanbul ignore else */
75
+ if (selectionFocus.node === selectionRange.node) {
76
+ const anchorOffset = selectionFocus.offset < selectionRange.start ? selectionRange.end : selectionRange.start;
77
+ const focusOffset = selectionFocus.offset > selectionRange.end || selectionFocus.offset < selectionRange.start ? selectionFocus.offset : selectionRange.end;
78
+ (0, _document.setUISelection)(selectionRange.node, {
79
+ anchorOffset,
80
+ focusOffset
81
+ });
85
82
  }
83
+ } else {
84
+ const range = selectionRange.cloneRange();
85
+ const cmp = range.comparePoint(selectionFocus.node, selectionFocus.offset);
86
+
87
+ if (cmp < 0) {
88
+ range.setStart(selectionFocus.node, selectionFocus.offset);
89
+ } else if (cmp > 0) {
90
+ range.setEnd(selectionFocus.node, selectionFocus.offset);
91
+ }
92
+
93
+ const selection = target.ownerDocument.getSelection();
94
+ selection.removeAllRanges();
95
+ selection.addRange(range.cloneRange());
96
+ }
86
97
  }
87
98
 
88
99
  function fireMove(eventTarget, eventCoords) {
@@ -274,10 +274,13 @@ function mousedownDefaultBehavior({
274
274
  const [start, end] = node ? // As offset is describing a DOMOffset it is non-trivial to determine
275
275
  // which elements might be considered in the same line of text.
276
276
  // TODO: support expanding initial range on multiple clicks if node is given
277
- [offset, offset] : getTextRange(text, offset, clickCount);
277
+ [offset, offset] : getTextRange(text, offset, clickCount); // TODO: implement modifying selection per shift/ctrl+mouse
278
278
 
279
279
  if (hasValue) {
280
- (0, _document.setUISelection)(target, start != null ? start : text.length, end != null ? end : text.length);
280
+ (0, _document.setUISelection)(target, {
281
+ anchorOffset: start != null ? start : text.length,
282
+ focusOffset: end != null ? end : text.length
283
+ });
281
284
  position.selectionRange = {
282
285
  node: target,
283
286
  start: start != null ? start : 0,
@@ -303,8 +306,7 @@ function mousedownDefaultBehavior({
303
306
  const range = new Range();
304
307
  range.setStart(startNode, startOffset);
305
308
  range.setEnd(endNode, endOffset);
306
- position.selectionRange = range; // TODO: support multiple ranges
307
-
309
+ position.selectionRange = range;
308
310
  const selection = target.ownerDocument.getSelection();
309
311
  selection.removeAllRanges();
310
312
  selection.addRange(range.cloneRange());
@@ -15,13 +15,9 @@ function resolveSelectionTarget({
15
15
  offset
16
16
  }) {
17
17
  if ((0, _utils.isElementType)(target, ['input', 'textarea'])) {
18
- var _getUIValue;
19
-
20
18
  return {
21
19
  node: target,
22
- offset: offset != null ? offset : ((_getUIValue = (0, _document.getUIValue)(target)) != null ? _getUIValue :
23
- /* istanbul ignore next */
24
- '').length
20
+ offset: offset != null ? offset : (0, _document.getUIValue)(target).length
25
21
  };
26
22
  } else if (node) {
27
23
  return {
@@ -52,8 +48,12 @@ function findNodeAtTextOffset(node, offset, isRoot = true) {
52
48
  offset -= text.length;
53
49
  } else if (c.nodeType === 1) {
54
50
  return findNodeAtTextOffset(c, offset, false);
55
- } else
51
+ } else {
52
+ // The pre-commit hooks keeps changing this
53
+ // See https://github.com/kentcdodds/kcd-scripts/issues/218
54
+
56
55
  /* istanbul ignore else */
56
+ // eslint-disable-next-line no-lonely-if
57
57
  if (c.nodeType === 3) {
58
58
  var _offset;
59
59
 
@@ -62,6 +62,7 @@ function findNodeAtTextOffset(node, offset, isRoot = true) {
62
62
  offset: (_offset = offset) != null ? _offset : c.nodeValue.length
63
63
  };
64
64
  }
65
+ }
65
66
  }
66
67
 
67
68
  i += step;
package/dist/setup.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { clear } from './clear';
2
- import { click, clickOptions, dblClick } from './click';
2
+ import { click, clickOptions, dblClick, tripleClick } from './click';
3
3
  import { hover, unhover } from './hover';
4
4
  import { keyboard, keyboardOptions } from './keyboard';
5
5
  import type { keyboardState } from './keyboard/types';
@@ -22,6 +22,7 @@ export declare const userEventApis: {
22
22
  pointer: typeof pointer;
23
23
  selectOptions: typeof selectOptions;
24
24
  tab: typeof tab;
25
+ tripleClick: typeof tripleClick;
25
26
  type: typeof type;
26
27
  unhover: typeof unhover;
27
28
  upload: typeof upload;
@@ -54,6 +55,7 @@ export declare function setup(options?: SetupOptions): {
54
55
  pointer: typeof pointer;
55
56
  selectOptions: typeof selectOptions;
56
57
  tab: typeof tab;
58
+ tripleClick: typeof tripleClick;
57
59
  type: typeof type;
58
60
  unhover: typeof unhover;
59
61
  upload: typeof upload;
@@ -72,12 +74,13 @@ export declare function setup(options?: SetupOptions): {
72
74
  pointer: typeof pointer;
73
75
  selectOptions: typeof selectOptions;
74
76
  tab: typeof tab;
77
+ tripleClick: typeof tripleClick;
75
78
  type: typeof type;
76
79
  unhover: typeof unhover;
77
80
  upload: typeof upload;
78
81
  } & any;
79
82
  };
80
- declare function _setup({ applyAccept, autoModify, delay, document, focusTrap, keyboardMap, pointerMap, skipAutoClose, skipClick, skipHover, skipPointerEventsCheck, }: SetupOptions, { keyboardState, pointerState, }: {
83
+ declare function _setup({ applyAccept, autoModify, delay, document, keyboardMap, pointerMap, skipAutoClose, skipClick, skipHover, skipPointerEventsCheck, }: SetupOptions, { keyboardState, pointerState, }: {
81
84
  keyboardState: keyboardState;
82
85
  pointerState: pointerState;
83
86
  }): UserEventApis & {
package/dist/setup.js CHANGED
@@ -39,6 +39,7 @@ const userEventApis = {
39
39
  pointer: _pointer.pointer,
40
40
  selectOptions: _selectOptions.selectOptions,
41
41
  tab: _tab.tab,
42
+ tripleClick: _click.tripleClick,
42
43
  type: _type.type,
43
44
  unhover: _hover.unhover,
44
45
  upload: _upload.upload
@@ -64,7 +65,6 @@ function _setup({
64
65
  autoModify,
65
66
  delay = 0,
66
67
  document,
67
- focusTrap,
68
68
  keyboardMap,
69
69
  pointerMap,
70
70
  skipAutoClose,
@@ -91,9 +91,6 @@ function _setup({
91
91
  const clickDefaults = {
92
92
  skipHover
93
93
  };
94
- const tabDefaults = {
95
- focusTrap
96
- };
97
94
  const typeDefaults = {
98
95
  delay,
99
96
  skipAutoClose,
@@ -177,11 +174,11 @@ function _setup({
177
174
  });
178
175
  },
179
176
  tab: (...args) => {
180
- args[0] = { ...tabDefaults,
181
- ...args[0]
182
- };
183
177
  return _tab.tab.call(userEvent, ...args);
184
178
  },
179
+ tripleClick: (...args) => {
180
+ return _click.tripleClick.call(userEvent, ...args);
181
+ },
185
182
  // type needs typecasting because of the overloading
186
183
  type: (...args) => {
187
184
  args[2] = { ...typeDefaults,
package/dist/tab.d.ts CHANGED
@@ -1,6 +1,5 @@
1
1
  import type { UserEvent } from './setup';
2
2
  export interface tabOptions {
3
3
  shift?: boolean;
4
- focusTrap?: Document | Element;
5
4
  }
6
- export declare function tab(this: UserEvent, { shift, focusTrap }?: tabOptions): void;
5
+ export declare function tab(this: UserEvent, { shift }?: tabOptions): void;
package/dist/tab.js CHANGED
@@ -5,137 +5,8 @@ Object.defineProperty(exports, "__esModule", {
5
5
  });
6
6
  exports.tab = tab;
7
7
 
8
- var _dom = require("@testing-library/dom");
9
-
10
- var _utils = require("./utils");
11
-
12
- function getNextElement(currentIndex, shift, elements, focusTrap) {
13
- if ((0, _utils.isDocument)(focusTrap) && (currentIndex === 0 && shift || currentIndex === elements.length - 1 && !shift)) {
14
- return focusTrap.body;
15
- }
16
-
17
- const nextIndex = shift ? currentIndex - 1 : currentIndex + 1;
18
- const defaultIndex = shift ? elements.length - 1 : 0;
19
- return elements[nextIndex] || elements[defaultIndex];
20
- }
21
-
22
8
  function tab({
23
- shift = false,
24
- focusTrap
9
+ shift
25
10
  } = {}) {
26
- var _focusTrap$ownerDocum, _focusTrap;
27
-
28
- const doc = (_focusTrap$ownerDocum = (_focusTrap = focusTrap) == null ? void 0 : _focusTrap.ownerDocument) != null ? _focusTrap$ownerDocum : document;
29
- const previousElement = (0, _utils.getActiveElement)(doc);
30
-
31
- if (!focusTrap) {
32
- focusTrap = doc;
33
- }
34
-
35
- const focusableElements = focusTrap.querySelectorAll(_utils.FOCUSABLE_SELECTOR);
36
- const enabledElements = Array.from(focusableElements).filter(el => el === previousElement || el.getAttribute('tabindex') !== '-1' && !(0, _utils.isDisabled)(el) && // Hidden elements are not tabable
37
- (0, _utils.isVisible)(el));
38
- if (enabledElements.length === 0) return;
39
- const orderedElements = enabledElements.map((el, idx) => ({
40
- el,
41
- idx
42
- })).sort((a, b) => {
43
- // tabindex has no effect if the active element has tabindex="-1"
44
- if (previousElement && previousElement.getAttribute('tabindex') === '-1') {
45
- return a.idx - b.idx;
46
- }
47
-
48
- const tabIndexA = Number(a.el.getAttribute('tabindex'));
49
- const tabIndexB = Number(b.el.getAttribute('tabindex'));
50
- const diff = tabIndexA - tabIndexB;
51
- return diff === 0 ? a.idx - b.idx : diff;
52
- }).map(({
53
- el
54
- }) => el); // TODO: verify/remove type casts
55
-
56
- const checkedRadio = {};
57
- let prunedElements = [];
58
- orderedElements.forEach(currentElement => {
59
- // For radio groups keep only the active radio
60
- // If there is no active radio, keep only the checked radio
61
- // If there is no checked radio, treat like everything else
62
- const el = currentElement;
63
-
64
- if (el.type === 'radio' && el.name) {
65
- // If the active element is part of the group, add only that
66
- const prev = previousElement;
67
-
68
- if (prev && prev.type === el.type && prev.name === el.name) {
69
- if (el === prev) {
70
- prunedElements.push(el);
71
- }
72
-
73
- return;
74
- } // If we stumble upon a checked radio, remove the others
75
-
76
-
77
- if (el.checked) {
78
- prunedElements = prunedElements.filter(e => e.type !== el.type || e.name !== el.name);
79
- prunedElements.push(el);
80
- checkedRadio[el.name] = el;
81
- return;
82
- } // If we already found the checked one, skip
83
-
84
-
85
- if (typeof checkedRadio[el.name] !== 'undefined') {
86
- return;
87
- }
88
- }
89
-
90
- prunedElements.push(el);
91
- });
92
- const index = prunedElements.findIndex(el => el === previousElement);
93
- const nextElement = getNextElement(index, shift, prunedElements, focusTrap);
94
- const shiftKeyInit = {
95
- key: 'Shift',
96
- keyCode: 16,
97
- shiftKey: true
98
- };
99
- const tabKeyInit = {
100
- key: 'Tab',
101
- keyCode: 9,
102
- shiftKey: shift
103
- };
104
- let continueToTab = true; // not sure how to make it so there's no previous element...
105
- // istanbul ignore else
106
-
107
- if (previousElement) {
108
- // preventDefault on the shift key makes no difference
109
- if (shift) _dom.fireEvent.keyDown(previousElement, { ...shiftKeyInit
110
- });
111
- continueToTab = _dom.fireEvent.keyDown(previousElement, { ...tabKeyInit
112
- });
113
- }
114
-
115
- const keyUpTarget = !continueToTab && previousElement ? previousElement : nextElement;
116
-
117
- if (continueToTab) {
118
- if (nextElement === doc.body) {
119
- /* istanbul ignore else */
120
- if (previousElement) {
121
- (0, _utils.blur)(previousElement);
122
- }
123
- } else {
124
- (0, _utils.focus)(nextElement);
125
- }
126
- }
127
-
128
- _dom.fireEvent.keyUp(keyUpTarget, { ...tabKeyInit
129
- });
130
-
131
- if (shift) {
132
- _dom.fireEvent.keyUp(keyUpTarget, { ...shiftKeyInit,
133
- shiftKey: false
134
- });
135
- }
136
- }
137
- /*
138
- eslint
139
- complexity: "off",
140
- max-statements: "off",
141
- */
11
+ this.keyboard(shift === true ? '{Shift>}{Tab}{/Shift}' : shift === false ? '[/ShiftLeft][/ShiftRight]{Tab}' : '{Tab}');
12
+ }
@@ -1,7 +1,16 @@
1
- export declare function calculateNewValue(newEntry: string, element: HTMLElement, value?: string, selectionRange?: {
2
- selectionStart: number | null;
3
- selectionEnd: number | null;
4
- }, deleteContent?: 'backward' | 'forward'): {
1
+ import { EditableInputType } from './isEditable';
2
+ /**
3
+ * Calculate a new text value.
4
+ */
5
+ export declare function calculateNewValue(inputData: string, node: (HTMLInputElement & {
6
+ type: EditableInputType;
7
+ }) | HTMLTextAreaElement | (Node & {
8
+ nodeType: 3;
9
+ }) | Text, { startOffset, endOffset, }: {
10
+ startOffset: number;
11
+ endOffset: number;
12
+ }, inputType?: string): {
13
+ oldValue: string;
5
14
  newValue: string;
6
- newSelectionStart: number;
15
+ newOffset: number;
7
16
  };
@@ -5,44 +5,46 @@ Object.defineProperty(exports, "__esModule", {
5
5
  });
6
6
  exports.calculateNewValue = calculateNewValue;
7
7
 
8
- var _selectionRange = require("./selectionRange");
9
-
10
- var _getValue2 = require("./getValue");
8
+ var _document = require("../../document");
11
9
 
12
10
  var _isValidDateValue = require("./isValidDateValue");
13
11
 
14
12
  var _isValidInputTimeValue = require("./isValidInputTimeValue");
15
13
 
16
- function calculateNewValue(newEntry, element, value = (() => {
17
- var _getValue;
18
-
19
- return (_getValue = (0, _getValue2.getValue)(element)) != null ? _getValue :
20
- /* istanbul ignore next */
21
- '';
22
- })(), selectionRange = (0, _selectionRange.getSelectionRange)(element), deleteContent) {
23
- const selectionStart = selectionRange.selectionStart === null ? value.length : selectionRange.selectionStart;
24
- const selectionEnd = selectionRange.selectionEnd === null ? value.length : selectionRange.selectionEnd;
25
- const prologEnd = Math.max(0, selectionStart === selectionEnd && deleteContent === 'backward' ? selectionStart - 1 : selectionStart);
14
+ /**
15
+ * Calculate a new text value.
16
+ */
17
+ // This implementation does not properly calculate a new DOM state.
18
+ // It only handles text values and neither cares for DOM offsets nor accounts for non-character elements.
19
+ // It can be used for text nodes and elements supporting value property.
20
+ // TODO: The implementation of `deleteContent` is brittle and should be replaced.
21
+ function calculateNewValue(inputData, node, {
22
+ startOffset,
23
+ endOffset
24
+ }, inputType) {
25
+ const value = node.nodeType === 3 ? String(node.nodeValue) : (0, _document.getUIValue)(node);
26
+ const prologEnd = Math.max(0, startOffset === endOffset && inputType === 'deleteContentBackward' ? startOffset - 1 : startOffset);
26
27
  const prolog = value.substring(0, prologEnd);
27
- const epilogStart = Math.min(value.length, selectionStart === selectionEnd && deleteContent === 'forward' ? selectionEnd + 1 : selectionEnd);
28
+ const epilogStart = Math.min(value.length, startOffset === endOffset && inputType === 'deleteContentForward' ? startOffset + 1 : endOffset);
28
29
  const epilog = value.substring(epilogStart, value.length);
29
- let newValue = `${prolog}${newEntry}${epilog}`;
30
- const newSelectionStart = prologEnd + newEntry.length;
30
+ let newValue = `${prolog}${inputData}${epilog}`;
31
+ const newOffset = prologEnd + inputData.length;
31
32
 
32
- if (element.type === 'date' && !(0, _isValidDateValue.isValidDateValue)(element, newValue)) {
33
+ if (node.type === 'date' && !(0, _isValidDateValue.isValidDateValue)(node, newValue)) {
33
34
  newValue = value;
34
35
  }
35
36
 
36
- if (element.type === 'time' && !(0, _isValidInputTimeValue.isValidInputTimeValue)(element, newValue)) {
37
- if ((0, _isValidInputTimeValue.isValidInputTimeValue)(element, newEntry)) {
38
- newValue = newEntry;
37
+ if (node.type === 'time' && !(0, _isValidInputTimeValue.isValidInputTimeValue)(node, newValue)) {
38
+ if ((0, _isValidInputTimeValue.isValidInputTimeValue)(node, inputData)) {
39
+ newValue = inputData;
39
40
  } else {
40
41
  newValue = value;
41
42
  }
42
43
  }
43
44
 
44
45
  return {
46
+ oldValue: value,
45
47
  newValue,
46
- newSelectionStart
48
+ newOffset
47
49
  };
48
50
  }
@@ -1,7 +1,10 @@
1
1
  import { fireEvent } from '@testing-library/dom';
2
- export declare function fireInputEvent(element: HTMLElement, { newValue, newSelectionStart, eventOverrides, }: {
2
+ export declare function fireInputEvent(element: HTMLElement, { newValue, newSelection, eventOverrides, }: {
3
3
  newValue: string;
4
- newSelectionStart: number;
4
+ newSelection: {
5
+ node: Node;
6
+ offset: number;
7
+ };
5
8
  eventOverrides: Partial<Parameters<typeof fireEvent>[1]> & {
6
9
  [k: string]: unknown;
7
10
  };
@@ -7,49 +7,59 @@ exports.fireInputEvent = fireInputEvent;
7
7
 
8
8
  var _dom = require("@testing-library/dom");
9
9
 
10
- var _isElementType = require("../misc/isElementType");
11
-
12
10
  var _document = require("../../document");
13
11
 
14
- var _isContentEditable = require("./isContentEditable");
12
+ var _isElementType = require("../misc/isElementType");
15
13
 
16
- var _selectionRange = require("./selectionRange");
14
+ var _selection = require("../focus/selection");
17
15
 
18
16
  function fireInputEvent(element, {
19
17
  newValue,
20
- newSelectionStart,
18
+ newSelection,
21
19
  eventOverrides
22
20
  }) {
23
- // apply the changes before firing the input event, so that input handlers can access the altered dom and selection
24
- if ((0, _isContentEditable.isContentEditable)(element)) {
25
- (0, _document.applyNative)(element, 'textContent', newValue);
26
- } else
21
+ const oldValue = element.value; // apply the changes before firing the input event, so that input handlers can access the altered dom and selection
22
+
23
+ if ((0, _isElementType.isElementType)(element, ['input', 'textarea'])) {
24
+ (0, _document.setUIValue)(element, newValue);
25
+ } else {
26
+ // The pre-commit hooks keeps changing this
27
+ // See https://github.com/kentcdodds/kcd-scripts/issues/218
28
+
27
29
  /* istanbul ignore else */
28
- if ((0, _isElementType.isElementType)(element, ['input', 'textarea'])) {
29
- (0, _document.setUIValue)(element, newValue);
30
+ // eslint-disable-next-line no-lonely-if
31
+ if (newSelection.node.nodeType === 3) {
32
+ newSelection.node.textContent = newValue;
30
33
  } else {
31
34
  // TODO: properly type guard
32
35
  throw new Error('Invalid Element');
33
36
  }
37
+ }
34
38
 
35
- setSelectionRangeAfterInput(element, newSelectionStart);
39
+ (0, _selection.setSelection)({
40
+ focusNode: newSelection.node,
41
+ anchorOffset: newSelection.offset,
42
+ focusOffset: newSelection.offset
43
+ }); // When the input event happens in the browser, React executes all event handlers
44
+ // and if they change state of a controlled value, nothing happens.
45
+ // But when we trigger the event handlers in test environment,
46
+ // the changes are rolled back by React before the state update is applied.
47
+ // Then the updated state is applied which results in a resetted cursor.
48
+ // There is probably a better way to work around if we figure out
49
+ // why the batched update is executed differently in our test environment.
50
+
51
+ (0, _document.startTrackValue)(element);
36
52
 
37
53
  _dom.fireEvent.input(element, { ...eventOverrides
38
54
  });
39
55
 
40
- setSelectionRangeAfterInputHandler(element, newSelectionStart);
41
- }
42
-
43
- function setSelectionRangeAfterInput(element, newSelectionStart) {
44
- (0, _selectionRange.setSelectionRange)(element, newSelectionStart, newSelectionStart);
45
- }
56
+ const tracked = (0, _document.endTrackValue)(element);
46
57
 
47
- function setSelectionRangeAfterInputHandler(element, newSelectionStart) {
48
- // On controlled inputs the selection changes without a call to
49
- // either the `value` setter or the `setSelectionRange` method.
50
- // So if our tracked position for UI still exists and derives from a valid selectionStart,
51
- // the cursor was moved due to an input being controlled.
52
- if ((0, _isElementType.isElementType)(element, ['input', 'textarea']) && typeof element.selectionStart === 'number' && element.selectionStart !== newSelectionStart && (0, _document.hasUISelection)(element)) {
53
- (0, _selectionRange.setSelectionRange)(element, newSelectionStart, newSelectionStart);
58
+ if ((tracked == null ? void 0 : tracked.length) === 2 && tracked[0] === oldValue && tracked[1] === newValue) {
59
+ (0, _selection.setSelection)({
60
+ focusNode: newSelection.node,
61
+ anchorOffset: newSelection.offset,
62
+ focusOffset: newSelection.offset
63
+ });
54
64
  }
55
65
  }
@@ -1,3 +1,7 @@
1
1
  export declare function isContentEditable(element: Element): element is HTMLElement & {
2
2
  contenteditable: 'true';
3
3
  };
4
+ /**
5
+ * If a node is a contenteditable or inside one, return that element.
6
+ */
7
+ export declare function getContentEditable(node: Node): Element | null;
@@ -3,9 +3,23 @@
3
3
  Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
+ exports.getContentEditable = getContentEditable;
6
7
  exports.isContentEditable = isContentEditable;
7
8
 
8
9
  //jsdom is not supporting isContentEditable
9
10
  function isContentEditable(element) {
10
11
  return element.hasAttribute('contenteditable') && (element.getAttribute('contenteditable') == 'true' || element.getAttribute('contenteditable') == '');
12
+ }
13
+ /**
14
+ * If a node is a contenteditable or inside one, return that element.
15
+ */
16
+
17
+
18
+ function getContentEditable(node) {
19
+ const element = getElement(node);
20
+ return element && (element.closest('[contenteditable=""]') || element.closest('[contenteditable="true"]'));
21
+ }
22
+
23
+ function getElement(node) {
24
+ return node.nodeType === 1 ? node : node.parentElement;
11
25
  }
@@ -17,6 +17,7 @@ export declare enum editableInputTypes {
17
17
  'url' = "url",
18
18
  'week' = "week"
19
19
  }
20
+ export declare type EditableInputType = keyof typeof editableInputTypes;
20
21
  export declare function isEditableInput(element: Element): element is HTMLInputElement & {
21
22
  readOnly: false;
22
23
  type: editableInputTypes;
@@ -0,0 +1,4 @@
1
+ export declare function prepareInput(data: string, element: Element, inputType?: string): {
2
+ newValue: string;
3
+ commit: () => void;
4
+ } | undefined;