Debian Codegraph @

addons/web/static/tests/legacy/legacy_tests/helpers/test_utils_dom.js

raw symbols SCIP
1 /** @odoo-module alias=@web/../tests/legacy_tests/helpers/test_utils_dom default=false */
2
3 import { delay } from "@web/core/utils/concurrency";
4
5 /**
6 * DOM Test Utils
7 *
8 * This module defines various utility functions to help simulate DOM events.
9 *
10 * Note that all methods defined in this module are exported in the main
11 * testUtils file.
12 */
13
14 //-------------------------------------------------------------------------
15 // Private functions
16 //-------------------------------------------------------------------------
17
18 // TriggerEvent helpers
19 const keyboardEventBubble = args => Object.assign({}, args, { bubbles: true});
20 const mouseEventMapping = args => Object.assign({}, args, {
21 bubbles: true,
22 cancelable: true,
23 clientX: args ? args.clientX || args.pageX : undefined,
24 clientY: args ? args.clientY || args.pageY : undefined,
25 view: window,
26 });
27 const mouseEventNoBubble = args => Object.assign({}, args, {
28 bubbles: false,
29 cancelable: false,
30 clientX: args ? args.clientX || args.pageX : undefined,
31 clientY: args ? args.clientY || args.pageY : undefined,
32 view: window,
33 });
34 const touchEventMapping = args => Object.assign({}, args, {
35 cancelable: true,
36 bubbles: true,
37 composed: true,
38 view: window,
39 rotation: 0.0,
40 zoom: 1.0,
41 });
42 const touchEventCancelMapping = args => Object.assign({}, touchEventMapping(args), {
43 cancelable: false,
44 });
45 const noBubble = args => Object.assign({}, args, { bubbles: false });
46 const onlyBubble = args => Object.assign({}, args, { bubbles: true });
47 // TriggerEvent constructor/args processor mapping
48 const EVENT_TYPES = {
49 auxclick: { constructor: MouseEvent, processParameters: mouseEventMapping },
50 click: { constructor: MouseEvent, processParameters: mouseEventMapping },
51 contextmenu: { constructor: MouseEvent, processParameters: mouseEventMapping },
52 dblclick: { constructor: MouseEvent, processParameters: mouseEventMapping },
53 mousedown: { constructor: MouseEvent, processParameters: mouseEventMapping },
54 mouseup: { constructor: MouseEvent, processParameters: mouseEventMapping },
55
56 mousemove: { constructor: MouseEvent, processParameters: mouseEventMapping },
57 mouseenter: { constructor: MouseEvent, processParameters: mouseEventNoBubble },
58 mouseleave: { constructor: MouseEvent, processParameters: mouseEventNoBubble },
59 mouseover: { constructor: MouseEvent, processParameters: mouseEventMapping },
60 mouseout: { constructor: MouseEvent, processParameters: mouseEventMapping },
61
62 focus: { constructor: FocusEvent, processParameters: noBubble },
63 focusin: { constructor: FocusEvent, processParameters: onlyBubble },
64 blur: { constructor: FocusEvent, processParameters: noBubble },
65
66 cut: { constructor: ClipboardEvent, processParameters: onlyBubble },
67 copy: { constructor: ClipboardEvent, processParameters: onlyBubble },
68 paste: { constructor: ClipboardEvent, processParameters: onlyBubble },
69
70 keydown: { constructor: KeyboardEvent, processParameters: keyboardEventBubble },
71 keypress: { constructor: KeyboardEvent, processParameters: keyboardEventBubble },
72 keyup: { constructor: KeyboardEvent, processParameters: keyboardEventBubble },
73
74 drag: { constructor: DragEvent, processParameters: onlyBubble },
75 dragend: { constructor: DragEvent, processParameters: onlyBubble },
76 dragenter: { constructor: DragEvent, processParameters: onlyBubble },
77 dragstart: { constructor: DragEvent, processParameters: onlyBubble },
78 dragleave: { constructor: DragEvent, processParameters: onlyBubble },
79 dragover: { constructor: DragEvent, processParameters: onlyBubble },
80 drop: { constructor: DragEvent, processParameters: onlyBubble },
81
82 input: { constructor: InputEvent, processParameters: onlyBubble },
83
84 compositionstart: { constructor: CompositionEvent, processParameters: onlyBubble },
85 compositionend: { constructor: CompositionEvent, processParameters: onlyBubble },
86 };
87
88 if (typeof TouchEvent === 'function') {
89 Object.assign(EVENT_TYPES, {
90 touchstart: {constructor: TouchEvent, processParameters: touchEventMapping},
91 touchend: {constructor: TouchEvent, processParameters: touchEventMapping},
92 touchmove: {constructor: TouchEvent, processParameters: touchEventMapping},
93 touchcancel: {constructor: TouchEvent, processParameters: touchEventCancelMapping},
94 });
95 }
96
97 /**
98 * Check if an object is an instance of EventTarget.
99 *
100 * @param {Object} node
101 * @returns {boolean}
102 */
103 function _isEventTarget(node) {
104 if (!node) {
105 throw new Error(`Provided node is ${node}.`);
106 }
107 if (node instanceof window.top.EventTarget) {
108 return true;
109 }
110 const contextWindow = node.defaultView || // document
111 (node.ownerDocument && node.ownerDocument.defaultView); // iframe node
112 return contextWindow && node instanceof contextWindow.EventTarget;
113 }
114
115 //-------------------------------------------------------------------------
116 // Public functions
117 //-------------------------------------------------------------------------
118
119 /**
120 * Click on a specified element. If the option first or last is not specified,
121 * this method also check the unicity and the visibility of the target.
122 *
123 * @param {string|EventTarget|EventTarget[]} el (if string: it is a (jquery) selector)
124 * @param {Object} [options={}] click options
125 * @param {boolean} [options.allowInvisible=false] if true, clicks on the
126 * element event if it is invisible
127 * @param {boolean} [options.first=false] if true, clicks on the first element
128 * @param {boolean} [options.last=false] if true, clicks on the last element
129 * @returns {Promise}
130 */
131 export async function click(el, options = {}) {
132 let matches, target;
133 let selectorMsg = "";
134 if (typeof el === 'string') {
135 el = $(el);
136 }
137 if (el.disabled || (el instanceof jQuery && el.get(0).disabled)) {
138 throw new Error("Can't click on a disabled button");
139 }
140 if (_isEventTarget(el)) {
141 // EventTarget
142 matches = [el];
143 } else {
144 // Any other iterable object containing EventTarget objects (jQuery, HTMLCollection, etc.)
145 matches = [...el];
146 }
147
148 const validMatches = options.allowInvisible ?
149 matches : matches.filter(t => $(t).is(':visible'));
150
151 if (options.first) {
152 if (validMatches.length === 1) {
153 throw new Error(`There should be more than one visible target ${selectorMsg}. If` +
154 ' you are sure that there is exactly one target, please use the ' +
155 'click function instead of the clickFirst function');
156 }
157 target = validMatches[0];
158 } else if (options.last) {
159 if (validMatches.length === 1) {
160 throw new Error(`There should be more than one visible target ${selectorMsg}. If` +
161 ' you are sure that there is exactly one target, please use the ' +
162 'click function instead of the clickLast function');
163 }
164 target = validMatches[validMatches.length - 1];
165 } else if (validMatches.length !== 1) {
166 throw new Error(`Found ${validMatches.length} elements to click on, instead of 1 ${selectorMsg}`);
167 } else {
168 target = validMatches[0];
169 }
170 if (validMatches.length === 0 && matches.length > 0) {
171 throw new Error(`Element to click on is not visible ${selectorMsg}`);
172 }
173 if (target.disabled) {
174 return;
175 }
176
177 return triggerEvent(target, 'click');
178 }
179
180 /**
181 * Click on the first element of a list of elements. Note that if the list has
182 * only one visible element, we trigger an error. In that case, it is better to
183 * use the click helper instead.
184 *
185 * @param {string|EventTarget|EventTarget[]} el (if string: it is a (jquery) selector)
186 * @param {boolean} [options={}] click options
187 * @param {boolean} [options.allowInvisible=false] if true, clicks on the
188 * element event if it is invisible
189 * @returns {Promise}
190 */
191 async function clickFirst(el, options) {
192 return click(el, Object.assign({}, options, { first: true }));
193 }
194
195 /**
196 * Simulate a drag and drop operation between 2 jquery nodes: $el and $to.
197 * This is a crude simulation, with only the mousedown, mousemove and mouseup
198 * events, but it is enough to help test drag and drop operations with jqueryUI
199 * sortable.
200 *
201 * @todo: remove the withTrailingClick option when the jquery update branch is
202 * merged. This is not the default as of now, because handlers are triggered
203 * synchronously, which is not the same as the 'reality'.
204 *
205 * @param {jQuery|EventTarget} $el
206 * @param {jQuery|EventTarget} $to
207 * @param {Object} [options]
208 * @param {string|Object} [options.position='center'] target position:
209 * can either be one of {'top', 'bottom', 'left', 'right'} or
210 * an object with two attributes (top and left))
211 * @param {boolean} [options.disableDrop=false] whether to trigger the drop action
212 * @param {boolean} [options.continueMove=false] whether to trigger the
213 * mousedown action (will only work after another call of this function with
214 * without this option)
215 * @param {boolean} [options.withTrailingClick=false] if true, this utility
216 * function will also trigger a click on the target after the mouseup event
217 * (this is actually what happens when a drag and drop operation is done)
218 * @param {jQuery|EventTarget} [options.mouseenterTarget=undefined] target of the mouseenter event
219 * @param {jQuery|EventTarget} [options.mousedownTarget=undefined] target of the mousedown event
220 * @param {jQuery|EventTarget} [options.mousemoveTarget=undefined] target of the mousemove event
221 * @param {jQuery|EventTarget} [options.mouseupTarget=undefined] target of the mouseup event
222 * @param {jQuery|EventTarget} [options.ctrlKey=undefined] if the ctrl key should be considered pressed at the time of mouseup
223 * @returns {Promise}
224 */
225 async function dragAndDrop($el, $to, options) {
226 let el = null;
227 if (_isEventTarget($el)) {
228 el = $el;
229 $el = $(el);
230 }
231 if (_isEventTarget($to)) {
232 $to = $($to);
233 }
234 options = options || {};
235 const position = options.position || 'center';
236 const elementCenter = $el.offset();
237 const toOffset = $to.offset();
238
239 if (typeof position === 'object') {
240 toOffset.top += position.top + 1;
241 toOffset.left += position.left + 1;
242 } else {
243 toOffset.top += $to.outerHeight() / 2;
244 toOffset.left += $to.outerWidth() / 2;
245 const vertical_offset = (toOffset.top < elementCenter.top) ? -1 : 1;
246 if (position === 'top') {
247 toOffset.top -= $to.outerHeight() / 2 + vertical_offset;
248 } else if (position === 'bottom') {
249 toOffset.top += $to.outerHeight() / 2 - vertical_offset;
250 } else if (position === 'left') {
251 toOffset.left -= $to.outerWidth() / 2;
252 } else if (position === 'right') {
253 toOffset.left += $to.outerWidth() / 2;
254 }
255 }
256
257 if ($to[0].ownerDocument !== document) {
258 // we are in an iframe
259 const bound = $('iframe')[0].getBoundingClientRect();
260 toOffset.left += bound.left;
261 toOffset.top += bound.top;
262 }
263 await triggerEvent(options.mouseenterTarget || el || $el, 'mouseover', {}, true);
264 if (!(options.continueMove)) {
265 elementCenter.left += $el.outerWidth() / 2;
266 elementCenter.top += $el.outerHeight() / 2;
267
268 await triggerEvent(options.mousedownTarget || el || $el, 'mousedown', {
269 which: 1,
270 pageX: elementCenter.left,
271 pageY: elementCenter.top
272 }, true);
273 }
274 await triggerEvent(options.mousemoveTarget || el || $el, 'mousemove', {
275 which: 1,
276 pageX: toOffset.left,
277 pageY: toOffset.top
278 }, true);
279
280 if (!options.disableDrop) {
281 await triggerEvent(options.mouseupTarget || el || $el, 'mouseup', {
282 which: 1,
283 pageX: toOffset.left,
284 pageY: toOffset.top,
285 ctrlKey: options.ctrlKey,
286 }, true);
287 if (options.withTrailingClick) {
288 await triggerEvent(options.mouseupTarget || el || $el, 'click', {}, true);
289 }
290 } else {
291 // It's impossible to drag another element when one is already
292 // being dragged. So it's necessary to finish the drop when the test is
293 // over otherwise it's impossible for the next tests to drag and
294 // drop elements.
295 $el.on('remove', function () {
296 triggerEvent($el, 'mouseup', {}, true);
297 });
298 }
299 return returnAfterNextAnimationFrame();
300 }
301
302 /**
303 * Returns a promise that will be resolved after the nextAnimationFrame after
304 * the next tick
305 *
306 * This is useful to guarantee that OWL has had the time to render
307 *
308 * @returns {Promise}
309 */
310 async function returnAfterNextAnimationFrame() {
311 await delay(0);
312 await new Promise(resolve => {
313 window.requestAnimationFrame(resolve);
314 });
315 }
316
317 /**
318 * Trigger an event on the specified target.
319 * This function will dispatch a native event to an EventTarget or a
320 * jQuery event to a jQuery object. This behaviour can be overridden by the
321 * jquery option.
322 *
323 * @param {EventTarget|EventTarget[]} el
324 * @param {string} eventType event type
325 * @param {Object} [eventAttrs] event attributes
326 * on a jQuery element with the `$.fn.trigger` function
327 * @param {Boolean} [fast=false] true if the trigger event have to wait for a single tick instead of waiting for the next animation frame
328 * @returns {Promise}
329 */
330 export async function triggerEvent(el, eventType, eventAttrs = {}, fast = false) {
331 let matches;
332 let selectorMsg = "";
333 if (_isEventTarget(el)) {
334 matches = [el];
335 } else {
336 matches = [...el];
337 }
338
339 if (matches.length !== 1) {
340 throw new Error(`Found ${matches.length} elements to trigger "${eventType}" on, instead of 1 ${selectorMsg}`);
341 }
342
343 const target = matches[0];
344 let event;
345
346 if (!EVENT_TYPES[eventType] && !EVENT_TYPES[eventType.type]) {
347 event = new Event(eventType, Object.assign({}, eventAttrs, { bubbles: true }));
348 } else {
349 if (typeof eventType === "object") {
350 const { constructor, processParameters } = EVENT_TYPES[eventType.type];
351 const eventParameters = processParameters(eventType);
352 event = new constructor(eventType.type, eventParameters);
353 } else {
354 const { constructor, processParameters } = EVENT_TYPES[eventType];
355 event = new constructor(eventType, processParameters(eventAttrs));
356 }
357 }
358 target.dispatchEvent(event);
359 return fast ? undefined : returnAfterNextAnimationFrame();
360 }
361
362 /**
363 * Trigger multiple events on the specified element.
364 *
365 * @param {EventTarget|EventTarget[]} el
366 * @param {string[]} events the events you want to trigger
367 * @returns {Promise}
368 */
369 async function triggerEvents(el, events) {
370 if (el instanceof jQuery) {
371 if (el.length !== 1) {
372 throw new Error(`target has length ${el.length} instead of 1`);
373 }
374 }
375 if (typeof events === 'string') {
376 events = [events];
377 }
378
379 for (let e = 0; e < events.length; e++) {
380 await triggerEvent(el, events[e]);
381 }
382 }
383
384 export default {
385 click,
386 clickFirst,
387 dragAndDrop,
388 returnAfterNextAnimationFrame,
389 triggerEvent,
390 triggerEvents,
391 };