Debian Codegraph @

addons/web/static/tests/legacy/helpers/utils.js

raw symbols SCIP
1 /** @odoo-module alias=@web/../tests/helpers/utils default=false */
2
3 import { getTemplate } from "@web/core/templates";
4 import { browser } from "@web/core/browser/browser";
5 import { isMacOS } from "@web/core/browser/feature_detection";
6 import { download } from "@web/core/network/download";
7 import { getPopoverForTarget } from "@web/core/popover/popover";
8 import { Deferred } from "@web/core/utils/concurrency";
9 import { patch } from "@web/core/utils/patch";
10 import { isVisible } from "@web/core/utils/ui";
11 import { _t } from "@web/core/l10n/translation";
12 import { registerCleanup } from "./cleanup";
13 import { customDirectives, globalValues } from "@web/env";
14
15 import {
16 App,
17 onError,
18 onMounted,
19 onPatched,
20 onRendered,
21 onWillDestroy,
22 onWillPatch,
23 onWillRender,
24 onWillStart,
25 onWillUnmount,
26 onWillUpdateProps,
27 useComponent,
28 } from "@odoo/owl";
29
30 /**
31 * @typedef {keyof HTMLElementEventMap | keyof WindowEventMap} EventType
32 *
33 * @typedef {Side | `${Side}-${Side}` | { x?: number, y?: number }} Position
34 *
35 * @typedef {"bottom" | "left" | "right" | "top"} Side
36 *
37 * @typedef TriggerEventOptions
38 * @property {boolean} [skipVisibilityCheck=false]
39 * @property {boolean} [sync=false]
40 */
41
42 /**
43 * Patch the native Date object
44 *
45 * Note that it will be automatically unpatched at the end of the test
46 *
47 * @param {number} [year]
48 * @param {number} [month]
49 * @param {number} [day]
50 * @param {number} [hours]
51 * @param {number} [minutes]
52 * @param {number} [seconds]
53 * @param {number} [ms=0]
54 */
55 export function patchDate(year, month, day, hours, minutes, seconds, ms = 0) {
56 var RealDate = window.Date;
57 var actualDate = new RealDate();
58
59 // By default, RealDate uses the browser offset, so we must replace it with the offset fixed in luxon.
60 var fakeDate = new RealDate(year, month, day, hours, minutes, seconds, ms);
61 if (!(luxon.Settings.defaultZone instanceof luxon.FixedOffsetZone)) {
62 throw new Error("luxon.Settings.defaultZone must be a FixedOffsetZone");
63 }
64 const browserOffset = -fakeDate.getTimezoneOffset();
65 const patchedOffset = luxon.Settings.defaultZone.offset();
66 const offsetDiff = patchedOffset - browserOffset;
67 const correctedMinutes = fakeDate.getMinutes() - offsetDiff;
68 fakeDate.setMinutes(correctedMinutes);
69
70 var timeInterval = actualDate.getTime() - fakeDate.getTime();
71
72 // eslint-disable-next-line no-global-assign
73 window.Date = (function (NativeDate) {
74 function Date(Y, M, D, h, m, s, ms) {
75 var length = arguments.length;
76 let date;
77 if (arguments.length > 0) {
78 date =
79 length == 1 && String(Y) === Y // isString(Y)
80 ? // We explicitly pass it through parse:
81 new NativeDate(Date.parse(Y))
82 : // We have to manually make calls depending on argument
83 // length here
84 length >= 7
85 ? new NativeDate(Y, M, D, h, m, s, ms)
86 : length >= 6
87 ? new NativeDate(Y, M, D, h, m, s)
88 : length >= 5
89 ? new NativeDate(Y, M, D, h, m)
90 : length >= 4
91 ? new NativeDate(Y, M, D, h)
92 : length >= 3
93 ? new NativeDate(Y, M, D)
94 : length >= 2
95 ? new NativeDate(Y, M)
96 : length >= 1
97 ? new NativeDate(Y)
98 : new NativeDate();
99 // Prevent mixups with unfixed Date object
100 date.constructor = Date;
101 return date;
102 } else {
103 date = new NativeDate();
104 var time = date.getTime();
105 time -= timeInterval;
106 date.setTime(time);
107 return date;
108 }
109 }
110
111 // Copy any custom methods a 3rd party library may have added
112 for (var key in NativeDate) {
113 Date[key] = NativeDate[key];
114 }
115
116 // Copy "native" methods explicitly; they may be non-enumerable
117 // exception: 'now' uses fake date as reference
118 Date.now = function () {
119 var date = new NativeDate();
120 var time = date.getTime();
121 time -= timeInterval;
122 return time;
123 };
124 Date.UTC = NativeDate.UTC;
125 Date.prototype = NativeDate.prototype;
126 Date.prototype.constructor = Date;
127
128 // Upgrade Date.parse to handle simplified ISO 8601 strings
129 Date.parse = NativeDate.parse;
130 return Date;
131 })(Date);
132
133 registerCleanup(() => {
134 window.Date = RealDate;
135 });
136 }
137
138 /**
139 * Applies a fixed time zone to luxon based on an offset to the UTC time zone.
140 *
141 * @param {number} offset the number of minutes ahead or behind the UTC time zone
142 * +120 => UTC+2
143 * -120 => UTC-2
144 */
145 export function patchTimeZone(offset) {
146 patchWithCleanup(luxon.Settings, { defaultZone: luxon.FixedOffsetZone.instance(offset) });
147 }
148
149 /**
150 *
151 * @param {Object} obj object to patch
152 * @param {Object} patchValue the actual patch description
153 */
154 export function patchWithCleanup(obj, patchValue) {
155 const unpatch = patch(obj, patchValue);
156 registerCleanup(() => {
157 unpatch();
158 });
159 }
160
161 /**
162 * @returns {Element}
163 */
164 export function getFixture() {
165 if (!window.QUnit) {
166 return document;
167 }
168 if (QUnit.config.debug) {
169 return document.body;
170 } else {
171 return document.getElementById("qunit-fixture");
172 }
173 }
174
175 export async function nextTick() {
176 await new Promise((resolve) => window.requestAnimationFrame(resolve));
177 await new Promise((resolve) => setTimeout(resolve));
178 }
179
180 export function makeDeferred() {
181 return new Deferred();
182 }
183
184 export function findElement(el, selector) {
185 let target = el;
186 if (selector) {
187 const els = el.querySelectorAll(selector);
188 if (els.length === 0) {
189 throw new Error(`No element found (selector: ${selector})`);
190 }
191 if (els.length > 1) {
192 throw new Error(`Found ${els.length} elements, instead of 1 (selector: ${selector})`);
193 }
194 target = els[0];
195 }
196 return target;
197 }
198
199 //-----------------------------------------------------------------------------
200 // Event init attributes mappers
201 //-----------------------------------------------------------------------------
202
203 /** @param {EventInit} [args] */
204 const mapBubblingEvent = (args) => ({ ...args, bubbles: true });
205
206 /** @param {EventInit} [args] */
207 const mapNonBubblingEvent = (args) => ({ ...args, bubbles: false });
208
209 /** @param {EventInit} [args={}] */
210 const mapBubblingPointerEvent = (args = {}) => ({
211 clientX: args.pageX,
212 clientY: args.pageY,
213 ...args,
214 bubbles: true,
215 cancelable: true,
216 view: window,
217 });
218
219 /** @param {EventInit} [args] */
220 const mapNonBubblingPointerEvent = (args) => ({
221 ...mapBubblingPointerEvent(args),
222 bubbles: false,
223 cancelable: false,
224 });
225
226 /** @param {EventInit} [args={}] */
227 const mapCancelableTouchEvent = (args = {}) => ({
228 ...args,
229 bubbles: true,
230 cancelable: true,
231 composed: true,
232 rotation: 0.0,
233 touches: args.touches ? [...args.touches.map((e) => new Touch(e))] : undefined,
234 view: window,
235 zoom: 1.0,
236 });
237
238 /** @param {EventInit} [args] */
239 const mapNonCancelableTouchEvent = (args) => ({
240 ...mapCancelableTouchEvent(args),
241 cancelable: false,
242 });
243
244 /** @param {EventInit} [args] */
245 const mapKeyboardEvent = (args) => ({
246 ...args,
247 bubbles: true,
248 cancelable: true,
249 });
250
251 /**
252 * @template {typeof Event} T
253 * @param {EventType} eventType
254 * @returns {[T, (attrs: EventInit) => EventInit]}
255 */
256 const getEventConstructor = (eventType) => {
257 switch (eventType) {
258 // Mouse events
259 case "auxclick":
260 case "click":
261 case "contextmenu":
262 case "dblclick":
263 case "mousedown":
264 case "mouseup":
265 case "mousemove":
266 case "mouseover":
267 case "mouseout": {
268 return [MouseEvent, mapBubblingPointerEvent];
269 }
270 case "mouseenter":
271 case "mouseleave": {
272 return [MouseEvent, mapNonBubblingPointerEvent];
273 }
274 // Pointer events
275 case "pointerdown":
276 case "pointerup":
277 case "pointermove":
278 case "pointerover":
279 case "pointerout": {
280 return [PointerEvent, mapBubblingPointerEvent];
281 }
282 case "pointerenter":
283 case "pointerleave": {
284 return [PointerEvent, mapNonBubblingPointerEvent];
285 }
286 // Focus events
287 case "focusin": {
288 return [FocusEvent, mapBubblingEvent];
289 }
290 case "focus":
291 case "blur": {
292 return [FocusEvent, mapNonBubblingEvent];
293 }
294 // Clipboard events
295 case "cut":
296 case "copy":
297 case "paste": {
298 return [ClipboardEvent, mapBubblingEvent];
299 }
300 // Keyboard events
301 case "keydown":
302 case "keypress":
303 case "keyup": {
304 return [KeyboardEvent, mapKeyboardEvent];
305 }
306 // Drag events
307 case "drag":
308 case "dragend":
309 case "dragenter":
310 case "dragstart":
311 case "dragleave":
312 case "dragover":
313 case "drop": {
314 return [DragEvent, mapBubblingEvent];
315 }
316 // Input events
317 case "input": {
318 return [InputEvent, mapBubblingEvent];
319 }
320 // Composition events
321 case "compositionstart":
322 case "compositionend": {
323 return [CompositionEvent, mapBubblingEvent];
324 }
325 // UI events
326 case "scroll": {
327 return [UIEvent, mapNonBubblingEvent];
328 }
329 // Touch events
330 case "touchstart":
331 case "touchend":
332 case "touchmove": {
333 return [TouchEvent, mapCancelableTouchEvent];
334 }
335 case "touchcancel": {
336 return [TouchEvent, mapNonCancelableTouchEvent];
337 }
338 // Default: base Event constructor
339 default: {
340 return [Event, mapBubblingEvent];
341 }
342 }
343 };
344
345 /**
346 * @template {EventType} T
347 * @param {Element} el
348 * @param {string | null | undefined | false} selector
349 * @param {T} eventType
350 * @param {EventInit} [eventInit]
351 * @param {TriggerEventOptions} [options={}]
352 * @returns {GlobalEventHandlersEventMap[T] | Promise<GlobalEventHandlersEventMap[T]>}
353 */
354 export function triggerEvent(el, selector, eventType, eventInit, options = {}) {
355 const errors = [];
356 const target = findElement(el, selector);
357
358 // Error handling
359 if (typeof eventType !== "string") {
360 errors.push("event type must be a string");
361 }
362 if (!target) {
363 errors.push("cannot find target");
364 } else if (!options.skipVisibilityCheck && !isVisible(target)) {
365 errors.push("target is not visible");
366 }
367 if (errors.length) {
368 throw new Error(
369 `Cannot trigger event${eventType ? ` "${eventType}"` : ""}${
370 selector ? ` (with selector "${selector}")` : ""
371 }: ${errors.join(" and ")}`
372 );
373 }
374
375 // Actual dispatch
376 const [Constructor, processParams] = getEventConstructor(eventType);
377 const event = new Constructor(eventType, processParams(eventInit));
378 target.dispatchEvent(event);
379
380 if (window.QUnit && QUnit.config.debug) {
381 const group = `%c[${event.type.toUpperCase()}]`;
382 console.groupCollapsed(group, "color: #b52c9b");
383 console.log(target, event);
384 console.groupEnd(group, "color: #b52c9b");
385 }
386
387 if (options.sync) {
388 return event;
389 } else {
390 return nextTick().then(() => event);
391 }
392 }
393
394 /**
395 * @param {Element} el
396 * @param {string | null | undefined | false} selector
397 * @param {(EventType | [EventType, EventInit])[]} [eventDefs]
398 * @param {TriggerEventOptions} [options={}]
399 */
400 export function triggerEvents(el, selector, eventDefs, options = {}) {
401 const events = [...eventDefs].map((eventDef) => {
402 const [eventType, eventInit] = Array.isArray(eventDef) ? eventDef : [eventDef, {}];
403 return triggerEvent(el, selector, eventType, eventInit, options);
404 });
405 if (options.sync) {
406 return events;
407 } else {
408 return nextTick().then(() => events);
409 }
410 }
411
412 /**
413 * Triggers a scroll event on the given target
414 *
415 * If the target cannot be scrolled or an axis has reached
416 * the end of the scrollable area, the event can be transmitted
417 * to its nearest parent until it can be triggered
418 *
419 * @param {Element} target target of the scroll event
420 * @param {Object} coordinates
421 * @param {number} coordinates.left coordinates to scroll horizontally
422 * @param {number} coordinates.top coordinates to scroll vertically
423 * @param {boolean} canPropagate states if the scroll can propagate to a scrollable parent
424 */
425 export async function triggerScroll(
426 target,
427 coordinates = { left: null, top: null },
428 canPropagate = true
429 ) {
430 const isScrollable =
431 (target.scrollHeight > target.clientHeight && target.clientHeight > 0) ||
432 (target.scrollWidth > target.clientWidth && target.clientWidth > 0);
433 if (!isScrollable && !canPropagate) {
434 return;
435 }
436 if (isScrollable) {
437 const canScrollFrom = {
438 left:
439 coordinates.left > target.scrollLeft
440 ? target.scrollLeft + target.clientWidth < target.scrollWidth
441 : target.scrollLeft > 0,
442 top:
443 coordinates.top > target.scrollTop
444 ? target.scrollTop + target.clientHeight < target.scrollHeight
445 : target.scrollTop > 0,
446 };
447 const scrollCoordinates = {};
448 Object.entries(coordinates).forEach(([key, value]) => {
449 if (value !== null && canScrollFrom[key]) {
450 scrollCoordinates[key] = value;
451 delete coordinates[key];
452 }
453 });
454 target.scrollTo(scrollCoordinates);
455 await triggerEvent(target, null, "scroll");
456 if (!canPropagate || !Object.entries(coordinates).length) {
457 return;
458 }
459 }
460 target.parentElement
461 ? triggerScroll(target.parentElement, coordinates)
462 : triggerEvent(window, null, "scroll");
463 await nextTick();
464 }
465
466 export function click(
467 el,
468 selector,
469 { mouseEventInit = {}, skipDisabledCheck = false, skipVisibilityCheck = false } = {}
470 ) {
471 if (!skipDisabledCheck && el.disabled) {
472 throw new Error("Can't click on a disabled button");
473 }
474 return triggerEvents(
475 el,
476 selector,
477 [
478 "pointerdown",
479 "mousedown",
480 "focus",
481 "focusin",
482 "pointerup",
483 "mouseup",
484 ["click", mouseEventInit],
485 ],
486 { skipVisibilityCheck }
487 );
488 }
489
490 export function clickCreate(htmlElement) {
491 if (
492 htmlElement.querySelectorAll(
493 ".o_control_panel_main_buttons .o_form_button_create"
494 ).length
495 ) {
496 return click(
497 htmlElement,
498 ".o_control_panel_main_buttons .o_form_button_create"
499 );
500 } else if (
501 htmlElement.querySelectorAll(
502 ".o_control_panel_main_buttons .o_list_button_create"
503 ).length
504 ) {
505 return click(
506 htmlElement,
507 ".o_control_panel_main_buttons .o_list_button_create"
508 );
509 } else {
510 throw new Error("No edit button found to be clicked.");
511 }
512 }
513
514 export function clickEdit(htmlElement) {
515 if (htmlElement.querySelectorAll(".o_list_button_edit").length) {
516 return click(htmlElement, ".o_list_button_edit");
517 } else {
518 throw new Error("No edit button found to be clicked.");
519 }
520 }
521
522 export async function clickSave(htmlElement) {
523 if (htmlElement.querySelectorAll(".o_form_status_indicator").length) {
524 await mouseEnter(htmlElement, ".o_form_status_indicator");
525 }
526 if (htmlElement.querySelectorAll(".o_form_button_save").length) {
527 return click(htmlElement, ".o_form_button_save");
528 }
529 const listSaveButtons = htmlElement.querySelectorAll(".o_list_button_save");
530 if (listSaveButtons.length) {
531 return listSaveButtons.length >= 2 ? click(listSaveButtons[1]) : click(listSaveButtons[0]);
532 } else {
533 throw new Error("No save button found to be clicked.");
534 }
535 }
536
537 export async function clickDiscard(htmlElement) {
538 if (htmlElement.querySelectorAll(".o_form_status_indicator").length) {
539 await mouseEnter(htmlElement, ".o_form_status_indicator");
540 }
541 if (htmlElement.querySelectorAll(".o_form_button_cancel").length) {
542 return click(htmlElement, ".o_form_button_cancel");
543 } else if ($(htmlElement).find(".o_list_button_discard:visible").length) {
544 return click($(htmlElement).find(".o_list_button_discard:visible").get(0));
545 } else {
546 throw new Error("No discard button found to be clicked.");
547 }
548 }
549
550 /**
551 * Trigger pointerenter and mouseenter events on the given target. If no
552 * coordinates are given, the event is located by default
553 * in the middle of the target to simplify the test process
554 *
555 * @param {Element} el
556 * @param {string} selector
557 * @param {Object} coordinates position of the mouseenter event
558 */
559 export async function mouseEnter(el, selector, coordinates) {
560 const target = el.querySelector(selector) || el;
561 const atPos = coordinates || {
562 clientX: target.getBoundingClientRect().left + target.getBoundingClientRect().width / 2,
563 clientY: target.getBoundingClientRect().top + target.getBoundingClientRect().height / 2,
564 };
565 return triggerEvents(target, null, ["pointerenter", "mouseenter"], atPos);
566 }
567
568 /**
569 * Trigger pointerleave and mouseleave events on the given target.
570 *
571 * @param {Element} el
572 * @param {string} selector
573 */
574 export async function mouseLeave(el, selector) {
575 const target = el.querySelector(selector) || el;
576 return triggerEvents(target, null, ["pointerleave", "mouseleave"]);
577 }
578
579 export async function editInput(el, selector, value) {
580 const input = findElement(el, selector);
581 if (!(input instanceof HTMLInputElement || input instanceof HTMLTextAreaElement)) {
582 throw new Error("Only 'input' and 'textarea' elements can be edited with 'editInput'.");
583 }
584 if (
585 !["text", "textarea", "email", "search", "color", "number", "file", "tel"].includes(
586 input.type
587 )
588 ) {
589 throw new Error(`Type "${input.type}" not supported by 'editInput'.`);
590 }
591
592 const eventOpts = {};
593 if (input.type === "file") {
594 const files = Array.isArray(value) ? value : [value];
595 const dataTransfer = new DataTransfer();
596 for (const file of files) {
597 if (!(file instanceof File)) {
598 throw new Error(`File input value should be one or several File objects.`);
599 }
600 dataTransfer.items.add(file);
601 }
602 input.files = dataTransfer.files;
603 eventOpts.skipVisibilityCheck = true;
604 } else {
605 input.value = value;
606 }
607
608 await triggerEvents(input, null, ["input", "change"], eventOpts);
609
610 if (input.type === "file") {
611 // Need to wait for the file to be loaded by the input
612 await nextTick();
613 await nextTick();
614 }
615 }
616
617 export function editSelect(el, selector, value) {
618 const select = findElement(el, selector);
619 if (select.tagName !== "SELECT") {
620 throw new Error("Only select tag can be edited with selectInput.");
621 }
622 select.value = value;
623 return triggerEvent(select, null, "change");
624 }
625
626 export async function editSelectMenu(el, selector, value) {
627 const dropdown = el.querySelector(selector);
628 await click(dropdown.querySelector(".dropdown-toggle"));
629 for (const item of Array.from(el.querySelectorAll(".o_select_menu_menu .dropdown-item"))) {
630 if (item.textContent === value) {
631 return click(item);
632 }
633 }
634 }
635
636 /**
637 * Triggers an hotkey properly disregarding the operating system.
638 *
639 * @param {string} hotkey
640 * @param {boolean} addOverlayModParts
641 * @param {KeyboardEventInit} eventAttrs
642 */
643 export async function triggerHotkey(hotkey, addOverlayModParts = false, eventAttrs = {}) {
644 eventAttrs.key = hotkey.split("+").pop();
645
646 if (/shift/i.test(hotkey)) {
647 eventAttrs.shiftKey = true;
648 }
649
650 if (/control/i.test(hotkey)) {
651 if (isMacOS()) {
652 eventAttrs.metaKey = true;
653 } else {
654 eventAttrs.ctrlKey = true;
655 }
656 }
657
658 if (/alt/i.test(hotkey) || addOverlayModParts) {
659 if (isMacOS()) {
660 eventAttrs.ctrlKey = true;
661 } else {
662 eventAttrs.altKey = true;
663 }
664 }
665
666 if (!("bubbles" in eventAttrs)) {
667 eventAttrs.bubbles = true;
668 }
669
670 const [keydownEvent, keyupEvent] = await triggerEvents(
671 document.activeElement,
672 null,
673 [
674 ["keydown", eventAttrs],
675 ["keyup", eventAttrs],
676 ],
677 { skipVisibilityCheck: true }
678 );
679
680 return { keydownEvent, keyupEvent };
681 }
682
683 export function mockDownload(cb) {
684 patchWithCleanup(download, { _download: cb });
685 }
686
687 export const hushConsole = Object.create(null);
688 for (const propName of Object.keys(window.console)) {
689 hushConsole[propName] = () => {};
690 }
691
692 export function mockSendBeacon(mock) {
693 patchWithCleanup(navigator, {
694 sendBeacon: (url, blob) => {
695 return mock(url, blob) !== false;
696 },
697 });
698 }
699
700 export function mockTimeout() {
701 const timeouts = new Map();
702 let currentTime = 0;
703 let id = 1;
704 patchWithCleanup(browser, {
705 setTimeout(fn, delay = 0) {
706 timeouts.set(id, { fn, scheduledFor: delay + currentTime, id });
707 return id++;
708 },
709 clearTimeout(id) {
710 timeouts.delete(id);
711 },
712 });
713 return {
714 execRegisteredTimeouts() {
715 for (const { fn } of timeouts.values()) {
716 fn();
717 }
718 timeouts.clear();
719 },
720 async advanceTime(duration) {
721 // wait here so all microtasktick scheduled in this frame can be
722 // executed and possibly register their own timeout
723 await nextTick();
724 currentTime += duration;
725 for (const { fn, scheduledFor, id } of timeouts.values()) {
726 if (scheduledFor <= currentTime) {
727 fn();
728 timeouts.delete(id);
729 }
730 }
731 // wait here to make sure owl can update the UI
732 await nextTick();
733 },
734 };
735 }
736
737 export function mockAnimationFrame() {
738 const callbacks = new Map();
739 let currentTime = 0;
740 let id = 1;
741 patchWithCleanup(browser, {
742 requestAnimationFrame(fn) {
743 callbacks.set(id, { fn, scheduledFor: 16 + currentTime, id });
744 return id++;
745 },
746 cancelAnimationFrame(id) {
747 callbacks.delete(id);
748 },
749 performance: { now: () => currentTime },
750 });
751 return {
752 execRegisteredAnimationFrames() {
753 for (const { fn } of callbacks.values()) {
754 fn(currentTime);
755 }
756 callbacks.clear();
757 },
758 async advanceFrame(count = 1) {
759 // wait here so all microtasktick scheduled in this frame can be
760 // executed and possibly register their own timeout
761 await nextTick();
762 currentTime += 16 * count;
763 for (const { fn, scheduledFor, id } of callbacks.values()) {
764 if (scheduledFor <= currentTime) {
765 fn(currentTime);
766 callbacks.delete(id);
767 }
768 }
769 // wait here to make sure owl can update the UI
770 await nextTick();
771 },
772 };
773 }
774
775 export async function mount(Comp, target, config = {}) {
776 let { props, env } = config;
777 env = env || {};
778 const configuration = {
779 env,
780 getTemplate,
781 test: true,
782 props,
783 customDirectives,
784 globalValues,
785 };
786 if (env.services && "localization" in env.services) {
787 configuration.translateFn = _t;
788 }
789 const app = new App(Comp, configuration);
790 registerCleanup(() => app.destroy());
791 return app.mount(target);
792 }
793
794 export function destroy(comp) {
795 comp.__owl__.app.destroy();
796 }
797
798 export function findChildren(comp, predicate = (e) => e) {
799 const queue = [];
800 [].unshift.apply(queue, Object.values(comp.__owl__.children));
801
802 while (queue.length > 0) {
803 const curNode = queue.pop();
804 if (predicate(curNode)) {
805 return curNode;
806 }
807 [].unshift.apply(queue, Object.values(curNode.component.__owl__.children));
808 }
809 }
810
811 // partial replacement of t-ref on component
812 export function useChild() {
813 const node = useComponent().__owl__;
814 const setChild = () => {
815 const componentNode = Object.values(node.children)[0];
816 node.component.child = componentNode.component;
817 };
818 onMounted(setChild);
819 onPatched(setChild);
820 }
821
822 export function useLogLifeCycle(logFn, name = "") {
823 const component = useComponent();
824 let loggedName = `${component.constructor.name}`;
825 if (name) {
826 loggedName = `${component.constructor.name} ${name}`;
827 }
828 onError(() => {
829 logFn(`onError ${loggedName}`);
830 });
831 onMounted(() => {
832 logFn(`onMounted ${loggedName}`);
833 });
834 onPatched(() => {
835 logFn(`onPatched ${loggedName}`);
836 });
837 onRendered(() => {
838 logFn(`onRendered ${loggedName}`);
839 });
840 onWillDestroy(() => {
841 logFn(`onWillDestroy ${loggedName}`);
842 });
843 onWillPatch(() => {
844 logFn(`onWillPatch ${loggedName}`);
845 });
846 onWillRender(() => {
847 logFn(`onWillRender ${loggedName}`);
848 });
849 onWillStart(() => {
850 logFn(`onWillStart ${loggedName}`);
851 });
852 onWillUnmount(() => {
853 logFn(`onWillUnmount ${loggedName}`);
854 });
855 onWillUpdateProps(() => {
856 logFn(`onWillUpdateProps ${loggedName}`);
857 });
858 }
859
860 /**
861 * Returns the list of nodes containing n2 (included) that do not contain n1.
862 *
863 * @param {Node} n1
864 * @param {Node} n2
865 * @returns {Node[]}
866 */
867 function getDifferentParents(n1, n2) {
868 const parents = [n2];
869 while (parents[0].parentNode) {
870 const parent = parents[0].parentNode;
871 if (parent.contains(n1)) {
872 break;
873 }
874 parents.unshift(parent);
875 }
876 return parents;
877 }
878
879 /**
880 * Helper performing a drag and drop sequence.
881 *
882 * - 'from' is used to determine the element on which the drag will start;
883 * - 'target' will determine the element on which the first one will be dropped.
884 *
885 * The first element will be dragged by its center, and will be dropped on the
886 * bottom-right inner pixel of the target element. This behavior covers both
887 * cases of appending the first element to the end of a list (toSelector =
888 * target list) or moving it at the position of another element, effectively
889 * placing the first element before the second (toSelector = other element).
890 *
891 * A position can be given to drop the first element above, below, or on the
892 * side of the second (default is inside, as specified above).
893 *
894 * Note that only the last event is awaited, since all the others are
895 * considered to be synchronous.
896 *
897 * @param {Element | string} from
898 * @param {Element | string} to
899 * @param {Position} [position]
900 */
901 export async function dragAndDrop(from, to, position) {
902 const { drop } = await drag(from);
903 await drop(to, position);
904 }
905
906 /**
907 * Helper performing a drag.
908 *
909 * - the 'from' selector is used to determine the element on which the drag will
910 * start;
911 * - the 'target' selector will determine the element on which the dragged element will be
912 * moved.
913 *
914 * Returns a drop function
915 *
916 * @param {Element | string} from
917 */
918 export async function drag(from, pointerType = "mouse") {
919 const assertIsDragging = (fn, endDrag) => {
920 return {
921 async [fn.name](...args) {
922 if (dragEndReason) {
923 throw new Error(
924 `Cannot execute drag helper '${fn.name}': drag sequence has been ended by '${dragEndReason}'.`
925 );
926 }
927 await fn(...args);
928 if (endDrag) {
929 dragEndReason = fn.name;
930 }
931 },
932 }[fn.name];
933 };
934
935 const cancel = assertIsDragging(async function cancel() {
936 await triggerEvent(window, null, "keydown", { key: "Escape" });
937 }, true);
938
939 /**
940 * @param {Element | string} [to]
941 * @param {Position} [position]
942 */
943 const drop = assertIsDragging(async function drop(to, position) {
944 if (to) {
945 await moveTo(to, position);
946 }
947 await triggerEvent(target || source, null, "pointerup", targetPosition);
948 }, true);
949
950 /**
951 * @param {Element | string} selector
952 */
953 const getEl = (selector) =>
954 selector instanceof Element ? selector : fixture.querySelector(selector);
955
956 /**
957 * @param {Position} [position]
958 */
959 const getTargetPosition = (position) => {
960 const tRect = target.getBoundingClientRect();
961 const tPos = {
962 clientX: Math.floor(tRect.x),
963 clientY: Math.floor(tRect.y),
964 };
965 if (position && typeof position === "object") {
966 // x and y coordinates start from the element's initial coordinates
967 tPos.clientX += position.x || 0;
968 tPos.clientY += position.y || 0;
969 } else {
970 const positions = typeof position === "string" ? position.split("-") : [];
971
972 // X position
973 if (positions.includes("left")) {
974 tPos.clientX -= 1;
975 } else if (positions.includes("right")) {
976 tPos.clientX += Math.ceil(tRect.width) + 1;
977 } else {
978 tPos.clientX += Math.floor(tRect.width / 2);
979 }
980
981 // Y position
982 if (positions.includes("top")) {
983 tPos.clientY -= 1;
984 } else if (positions.includes("bottom")) {
985 tPos.clientY += Math.ceil(tRect.height) + 1;
986 } else {
987 tPos.clientY += Math.floor(tRect.height / 2);
988 }
989 }
990 return tPos;
991 };
992
993 /**
994 * @param {Element | string} [to]
995 * @param {Position} [position]
996 */
997 const moveTo = assertIsDragging(async function moveTo(to, position) {
998 target = getEl(to);
999 if (!target) {
1000 return;
1001 }
1002
1003 // Recompute target position
1004 targetPosition = getTargetPosition(position);
1005
1006 // Move, enter and drop the element on the target
1007 await triggerEvent(source, null, "pointermove", { ...targetPosition, button: -1 });
1008
1009 // "pointerenter" is fired on every parent of `target` that do not contain
1010 // `from` (typically: different parent lists).
1011 for (const parent of getDifferentParents(source, target)) {
1012 triggerEvent(parent, null, "pointerenter", targetPosition);
1013 }
1014 await nextTick();
1015
1016 return dragHelpers;
1017 }, false);
1018
1019 const dragHelpers = { cancel, drop, moveTo };
1020 const fixture = getFixture();
1021
1022 const source = getEl(from instanceof Element ? from : fixture.querySelector(from));
1023 const sourceRect = source.getBoundingClientRect();
1024
1025 let dragEndReason = null;
1026 let target;
1027 let targetPosition;
1028
1029 // Pointer down on main target
1030 await triggerEvent(source, null, "pointerdown", {
1031 pointerType,
1032 clientX: sourceRect.x + sourceRect.width / 2,
1033 clientY: sourceRect.y + sourceRect.height / 2,
1034 });
1035
1036 return dragHelpers;
1037 }
1038
1039 /**
1040 * Returns the dropdown menu for a specific toggler.
1041 *
1042 * @param {HTMLElement} target
1043 * @param {String|HTMLElement} togglerSelector
1044 * @returns {HTMLElement|undefined}
1045 */
1046 export function getDropdownMenu(target, togglerSelector) {
1047 if (!(target instanceof HTMLElement)) {
1048 throw new Error(`getDropdownMenu: target is not an HTMLElement.`);
1049 }
1050 let el =
1051 togglerSelector instanceof HTMLElement
1052 ? togglerSelector
1053 : target.querySelector(togglerSelector);
1054
1055 if (el && !el.classList.contains("o-dropdown")) {
1056 el = el.querySelector(".o-dropdown");
1057 }
1058 if (!el) {
1059 throw new Error(`getDropdownMenu: Could not find element "${togglerSelector}".`);
1060 }
1061 return getPopoverForTarget(el);
1062 }
1063
1064 export async function clickDropdown(target, fieldName) {
1065 const dropdownInput = target.querySelector(`[name='${fieldName}'] .dropdown input`);
1066 dropdownInput.focus();
1067 await nextTick();
1068 await click(dropdownInput);
1069 }
1070
1071 export async function clickOpenedDropdownItem(target, fieldName, itemContent) {
1072 const dropdowns = target.querySelectorAll(`[name='${fieldName}'] .dropdown .dropdown-menu`);
1073 if (dropdowns.length === 0) {
1074 throw new Error(`No dropdown found for field ${fieldName}`);
1075 } else if (dropdowns.length > 1) {
1076 throw new Error(`Found ${dropdowns.length} dropdowns for field ${fieldName}`);
1077 }
1078 const dropdownItems = dropdowns[0].querySelectorAll("li");
1079 const indexToClick = Array.from(dropdownItems)
1080 .map((html) => html.textContent)
1081 .indexOf(itemContent);
1082 if (indexToClick === -1) {
1083 throw new Error(`The element '${itemContent}' does not exist in the dropdown`);
1084 }
1085 await click(dropdownItems[indexToClick]);
1086 }
1087
1088 export async function selectDropdownItem(target, fieldName, itemContent) {
1089 await clickDropdown(target, fieldName);
1090 await clickOpenedDropdownItem(target, fieldName, itemContent);
1091 }
1092
1093 export function getNodesTextContent(nodes) {
1094 return Array.from(nodes).map((n) => n.textContent);
1095 }
1096
1097 /**
1098 * Click to open the dropdown on a many2one
1099 */
1100 export async function clickOpenM2ODropdown(el, fieldName, selector) {
1101 const m2oSelector = `${selector || ""} .o_field_many2one[name=${fieldName}] input`;
1102 const matches = el.querySelectorAll(m2oSelector);
1103 if (matches.length !== 1) {
1104 throw new Error(
1105 `cannot open m2o: selector ${selector} has been found ${matches.length} instead of 1`
1106 );
1107 }
1108
1109 await click(matches[0]);
1110 return matches[0];
1111 }
1112
1113 /**
1114 * Click on the active (highlighted) selection in a m2o dropdown.
1115 */
1116 // TO FIX
1117 export async function clickM2OHighlightedItem(el, fieldName, selector) {
1118 const m2oSelector = `${selector || ""} .o_field_many2one[name=${fieldName}] input`;
1119 // const $dropdown = $(m2oSelector).autocomplete('widget');
1120 const matches = el.querySelectorAll(m2oSelector);
1121 if (matches.length !== 1) {
1122 throw new Error(
1123 `cannot open m2o: selector ${selector} has been found ${matches.length} instead of 1`
1124 );
1125 }
1126 // clicking on an li (no matter which one), will select the focussed one
1127 return click(matches[0].parentElement.querySelector("li"));
1128 }
1129
1130 // X2Many
1131 export async function addRow(target, selector) {
1132 await click(target.querySelector(`${selector ? selector : ""} .o_field_x2many_list_row_add a`));
1133 }
1134
1135 export async function removeRow(target, index) {
1136 await click(target.querySelectorAll(".o_list_record_remove")[index]);
1137 }