-
Notifications
You must be signed in to change notification settings - Fork 23.5k
/
tour_utils.js
698 lines (661 loc) · 23.3 KB
/
tour_utils.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
/** @odoo-module **/
import { markup } from "@odoo/owl";
import { _t } from "@web/core/l10n/translation";
import { utils } from "@web/core/ui/ui_service";
import { _legacyIsVisible } from "@web/core/utils/ui";
/**
* @typedef {string | (actions: RunningTourActionHelper) => void | Promise<void>} RunCommand
*/
export class TourError extends Error {
constructor(message, ...args) {
super(message, ...args);
this.message = `(TourError) ${message}`;
}
}
/**
* Calls the given `func` then returns/resolves to `true`
* if it will result to unloading of the page.
* @param {(...args: any[]) => void} func
* @param {any[]} args
* @returns {boolean | Promise<boolean>}
*/
export function callWithUnloadCheck(func, ...args) {
let willUnload = false;
const beforeunload = () => (willUnload = true);
window.addEventListener("beforeunload", beforeunload);
const result = func(...args);
if (result instanceof Promise) {
return result.then(() => {
window.removeEventListener("beforeunload", beforeunload);
return willUnload;
});
} else {
window.removeEventListener("beforeunload", beforeunload);
return willUnload;
}
}
export function getFirstVisibleElement($elements) {
for (var i = 0; i < $elements.length; i++) {
var $i = $elements.eq(i);
if (_legacyIsVisible($i[0])) {
return $i;
}
}
return $();
}
/**
* @param {JQuery|undefined} target
*/
export function getJQueryElementFromSelector(selector, $target) {
$target = $target || $(document);
const iframeSplit = typeof selector === "string" && selector.match(/(.*\biframe[^ ]*)(.*)/);
if (iframeSplit && iframeSplit[2]) {
var $iframe = $target.find(`${iframeSplit[1]}:not(.o_ignore_in_tour)`);
if ($iframe.is('[is-ready="false"]')) {
return $();
}
var $el = $iframe.contents().find(iframeSplit[2]);
$el.iframeContainer = $iframe[0];
return $el;
} else if (typeof selector === "string") {
return $target.find(selector);
} else {
return $(selector);
}
}
/**
* @param {HTMLElement} [element]
* @param {RunCommand} [runCommand]
* @returns {string}
*/
export function getConsumeEventType(element, runCommand) {
if (!element) {
return "click";
}
const { classList, tagName, type } = element;
const tag = tagName.toLowerCase();
// Many2one
if (classList.contains("o_field_many2one") || classList.contains("o_field_many2manytags")) {
return "autocompleteselect";
}
// Inputs and textareas
if (
tag === "textarea" ||
(tag === "input" &&
(!type ||
["email", "number", "password", "search", "tel", "text", "url"].includes(type)))
) {
// FieldDateRange triggers a special event when using the widget
if (classList.contains("o_field_date_range")) {
return "apply.daterangepicker input";
}
if (
utils.isSmall() &&
element.closest(".o_field_widget")?.matches(".o_field_many2one, .o_field_many2many")
) {
return "click";
}
return "input";
}
// jQuery draggable
if (classList.contains("ui-draggable-handle")) {
return "mousedown";
}
// Drag & drop run command
if (typeof runCommand === "string" && /^drag_and_drop/.test(runCommand)) {
// this is a heuristic: the element has to be dragged and dropped but it
// doesn't have class 'ui-draggable-handle', so we check if it has an
// ui-sortable parent, and if so, we conclude that its event type is 'sort'
if (element.closest(".ui-sortable")) {
return "sort";
}
if (
(/^drag_and_drop_native/.test(runCommand) && classList.contains("o_draggable")) ||
element.closest(".o_draggable")
) {
return "pointerdown";
}
}
// Default: click
return "click";
}
/**
* ! This function is a copy-paste of its namesake in web/static/tests/helpers/utils.js
* TODO: Unify utils for tests and tours since they're doing the exact same thing
* @param {Node} n1
* @param {Node} n2
* @returns {Node[]}
*/
function getDifferentParents(n1, n2) {
const parents = [n2];
while (parents[0].parentNode) {
const parent = parents[0].parentNode;
if (parent.contains(n1)) {
break;
}
parents.unshift(parent);
}
return parents;
}
/**
* @param {HTMLElement} element
* @returns {HTMLElement | null}
*/
export function getScrollParent(element) {
if (!element) {
return null;
}
if (element.scrollHeight > element.clientHeight) {
return element;
} else {
return getScrollParent(element.parentNode);
}
}
/**
* @param {HTMLElement} el
* @param {string} type
* @param {boolean} canBubbleAndBeCanceled
* @param {PointerEventInit} [additionalParams]
*/
const triggerPointerEvent = (el, type, canBubbleAndBeCanceled, additionalParams) => {
const eventInit = {
bubbles: canBubbleAndBeCanceled,
cancelable: canBubbleAndBeCanceled,
view: window,
...additionalParams,
};
el.dispatchEvent(new PointerEvent(type, eventInit));
if (type.startsWith("pointer")) {
el.dispatchEvent(new MouseEvent(type.replace("pointer", "mouse"), eventInit));
}
};
export class RunningTourActionHelper {
constructor(tip_widget) {
this.tip_widget = tip_widget;
}
click(element) {
this._click(this._get_action_values(element));
}
dblclick(element) {
this._click(this._get_action_values(element), 2);
}
tripleclick(element) {
this._click(this._get_action_values(element), 3);
}
clicknoleave(element) {
this._click(this._get_action_values(element), 1, false);
}
text(text, element) {
this._text(this._get_action_values(element), text);
}
remove_text(text, element) {
this._text(this._get_action_values(element), "\n");
}
text_blur(text, element) {
this._text_blur(this._get_action_values(element), text);
}
range(text, element) {
this._range(this._get_action_values(element), text);
}
drag_and_drop(to, element) {
this._drag_and_drop_jquery(this._get_action_values(element), to);
}
drag_and_drop_native(toSel, element) {
const to = getJQueryElementFromSelector(toSel)[0];
this._drag_and_drop(this._get_action_values(element).$element[0], to);
}
drag_move_and_drop(to, element) {
this._drag_move_and_drop(this._get_action_values(element), to);
}
keydown(keyCodes, element) {
this._keydown(this._get_action_values(element), keyCodes.split(/[,\s]+/));
}
auto(element) {
var values = this._get_action_values(element);
if (values.consume_event === "input") {
this._text(values);
} else {
this._click(values);
}
}
_get_action_values(element) {
var $e = getJQueryElementFromSelector(element);
var $element = element ? getFirstVisibleElement($e) : this.tip_widget.$anchor;
if ($element.length === 0) {
$element = $e.first();
}
var consume_event = element
? getConsumeEventType($element[0])
: this.tip_widget.consume_event;
return {
$element: $element,
consume_event: consume_event,
};
}
_click(values, nb, leave) {
const target = values.$element[0];
triggerPointerEvent(target, "pointerover", true);
triggerPointerEvent(target, "pointerenter", false);
triggerPointerEvent(target, "pointermove", true);
for (let i = 1; i <= (nb || 1); i++) {
triggerPointerEvent(target, "pointerdown", true);
triggerPointerEvent(target, "pointerup", true);
triggerPointerEvent(target, "click", true, { detail: i });
if (i % 2 === 0) {
triggerPointerEvent(target, "dblclick", true);
}
}
if (leave !== false) {
triggerPointerEvent(target, "pointerout", true);
triggerPointerEvent(target, "pointerleave", false);
}
}
_text(values, text) {
this._click(values);
text = text || "Test";
if (values.consume_event === "input") {
values.$element
.trigger({ type: "keydown", key: text[text.length - 1] })
.val(text)
.trigger({ type: "keyup", key: text[text.length - 1] });
values.$element[0].dispatchEvent(
new InputEvent("input", {
bubbles: true,
})
);
} else if (values.$element.is("select")) {
var $options = values.$element.find("option");
$options.prop("selected", false).removeProp("selected");
var $selectedOption = $options.filter(function () {
return $(this).val() === text;
});
if ($selectedOption.length === 0) {
$selectedOption = $options.filter(function () {
return $(this).text().trim() === text;
});
}
const regex = /option\s+([0-9]+)/;
if ($selectedOption.length === 0 && regex.test(text)) {
// Extract position as 1-based, as the nth selectors.
const position = parseInt(regex.exec(text)[1]);
$selectedOption = $options.eq(position - 1); // eq is 0-based.
}
$selectedOption.prop("selected", true);
this._click(values);
// For situations where an `oninput` is defined.
values.$element.trigger("input");
} else {
values.$element.focusIn();
values.$element.trigger($.Event("keydown", { key: "_", keyCode: 95 }));
values.$element.text(text).trigger("input");
values.$element.focusInEnd();
values.$element.trigger($.Event("keyup", { key: "_", keyCode: 95 }));
}
values.$element[0].dispatchEvent(new Event("change", { bubbles: true, cancelable: false }));
}
_text_blur(values, text) {
this._text(values, text);
values.$element.trigger("focusout");
values.$element.trigger("blur");
}
_range(values, text) {
values.$element[0].value = text;
values.$element[0].dispatchEvent(new Event('change', { bubbles: true, cancelable: false }));
}
_calculateCenter($el, selector) {
const center = $el.offset();
if (selector && selector.indexOf("iframe") !== -1) {
const iFrameOffset = $("iframe").offset();
center.left += iFrameOffset.left;
center.top += iFrameOffset.top;
}
center.left += $el.outerWidth() / 2;
center.top += $el.outerHeight() / 2;
return center;
}
_drag_and_drop_jquery(values, to) {
var $to;
const elementCenter = this._calculateCenter(values.$element);
if (to) {
$to = getJQueryElementFromSelector(to);
} else {
$to = $(document.body);
}
values.$element.trigger($.Event("mouseenter"));
// Make the web_studio tour test happy. My guess is that 50%+ of the length of the dragged element
// must be situated to the right of the $to element.
values.$element.trigger(
$.Event("mousedown", {
which: 1,
pageX: elementCenter.left + 1,
pageY: elementCenter.top,
})
);
// Some tests depends on elements present only when the element to drag
// start to move while some other tests break while moving.
if (!$to.length) {
values.$element.trigger(
$.Event("mousemove", {
which: 1,
pageX: elementCenter.left + 1,
pageY: elementCenter.top,
})
);
$to = getJQueryElementFromSelector(to);
}
let toCenter = this._calculateCenter($to, to);
values.$element.trigger(
$.Event("mousemove", { which: 1, pageX: toCenter.left, pageY: toCenter.top })
);
// Recalculate the center as the mousemove might have made the element bigger.
toCenter = this._calculateCenter($to, to);
values.$element.trigger(
$.Event("mouseup", { which: 1, pageX: toCenter.left, pageY: toCenter.top })
);
}
/**
* ! This function is a reduced version of "drag" in web/static/tests/helpers/utils.js
* TODO: Unify utils for tests and tours since they're doing the exact same thing
* @param {HTMLElement} source
* @param {HTMLElement} target
*/
_drag_and_drop(source, target) {
const sourceRect = source.getBoundingClientRect();
const sourcePosition = {
clientX: sourceRect.x + sourceRect.width / 2,
clientY: sourceRect.y + sourceRect.height / 2,
};
const targetRect = target.getBoundingClientRect();
const targetPosition = {
clientX: targetRect.x + targetRect.width / 2,
clientY: targetRect.y + targetRect.height / 2,
};
triggerPointerEvent(source, "pointerdown", true, sourcePosition);
triggerPointerEvent(source, "pointermove", true, targetPosition);
for (const parent of getDifferentParents(source, target)) {
triggerPointerEvent(parent, "pointerenter", false, targetPosition);
}
triggerPointerEvent(target, "pointerup", true, targetPosition);
}
_drag_move_and_drop(values, params) {
// Extract parameters from string: '[deltaX,deltaY]@from => actualTo'.
const parts = /^\[(.+),(.+)\]@(.+) => (.+)/.exec(params);
const initialMoveOffset = [parseInt(parts[1]), parseInt(parts[2])];
const fromSelector = parts[3];
const toSelector = parts[4];
// Click on element.
values.$element.trigger($.Event("mouseenter"));
const elementCenter = this._calculateCenter(values.$element);
values.$element.trigger(
$.Event("mousedown", { which: 1, pageX: elementCenter.left, pageY: elementCenter.top })
);
// Drag through "from".
const fromCenter = this._calculateCenter(
getJQueryElementFromSelector(fromSelector),
fromSelector
);
values.$element.trigger(
$.Event("mousemove", {
which: 1,
pageX: fromCenter.left + initialMoveOffset[0],
pageY: fromCenter.top + initialMoveOffset[1],
})
);
// Drop into "to".
const toCenter = this._calculateCenter(
getJQueryElementFromSelector(toSelector),
toSelector
);
values.$element.trigger(
$.Event("mouseup", { which: 1, pageX: toCenter.left, pageY: toCenter.top })
);
}
_keydown(values, keyCodes) {
while (keyCodes.length) {
const eventOptions = {};
const keyCode = keyCodes.shift();
let insertedText = null;
if (isNaN(keyCode)) {
eventOptions.key = keyCode;
} else {
const code = parseInt(keyCode, 10);
eventOptions.keyCode = code;
eventOptions.which = code;
if (
code === 32 || // spacebar
(code > 47 && code < 58) || // number keys
(code > 64 && code < 91) || // letter keys
(code > 95 && code < 112) || // numpad keys
(code > 185 && code < 193) || // ;=,-./` (in order)
(code > 218 && code < 223) // [\]' (in order))
) {
insertedText = String.fromCharCode(code);
}
}
values.$element.trigger(Object.assign({ type: "keydown" }, eventOptions));
if (insertedText) {
values.$element[0].ownerDocument.execCommand("insertText", 0, insertedText);
}
values.$element.trigger(Object.assign({ type: "keyup" }, eventOptions));
}
}
}
export const stepUtils = {
_getHelpMessage(functionName, ...args) {
return `Generated by function tour utils ${functionName}(${args.join(", ")})`;
},
addDebugHelp(helpMessage, step) {
if (typeof step.debugHelp === "string") {
step.debugHelp = step.debugHelp + "\n" + helpMessage;
} else {
step.debugHelp = helpMessage;
}
return step;
},
editionEnterpriseModifier(step) {
step.edition = "enterprise";
return step;
},
mobileModifier(step) {
step.mobile = true;
return step;
},
showAppsMenuItem() {
return {
edition: "community",
trigger: ".o_navbar_apps_menu button",
auto: true,
position: "bottom",
};
},
toggleHomeMenu() {
return {
edition: "enterprise",
trigger: ".o_main_navbar .o_menu_toggle",
content: markup(_t("Click on the <i>Home icon</i> to navigate across apps.")),
position: "bottom",
};
},
autoExpandMoreButtons(extra_trigger) {
return {
trigger: ".o-form-buttonbox",
extra_trigger: extra_trigger,
auto: true,
run: (actions) => {
const $more = $(".o-form-buttonbox .o_button_more");
if ($more.length) {
actions.click($more);
}
},
};
},
goBackBreadcrumbsMobile(description, ...extraTrigger) {
return extraTrigger.map((element) => ({
mobile: true,
trigger: ".o_back_button",
extra_trigger: element,
content: description,
position: "bottom",
debugHelp: this._getHelpMessage(
"goBackBreadcrumbsMobile",
description,
...extraTrigger
),
}));
},
goToAppSteps(dataMenuXmlid, description) {
return [
this.showAppsMenuItem(),
{
trigger: `.o_app[data-menu-xmlid="${dataMenuXmlid}"]`,
content: description,
position: "right",
edition: "community",
},
{
trigger: `.o_app[data-menu-xmlid="${dataMenuXmlid}"]`,
content: description,
position: "bottom",
edition: "enterprise",
},
].map((step) =>
this.addDebugHelp(this._getHelpMessage("goToApp", dataMenuXmlid, description), step)
);
},
openBurgerMenu(extraTrigger) {
return {
mobile: true,
trigger: ".o_mobile_menu_toggle",
extra_trigger: extraTrigger,
content: _t("Open bugger menu."),
position: "bottom",
debugHelp: this._getHelpMessage("openBurgerMenu", extraTrigger),
};
},
statusbarButtonsSteps(innerTextButton, description, extraTrigger) {
return [
{
mobile: true,
auto: true,
trigger: ".o_statusbar_buttons",
extra_trigger: extraTrigger,
run: (actions) => {
const $action = $(".o_statusbar_buttons .btn.dropdown-toggle:contains(Action)");
if ($action.length) {
actions.click($action);
}
},
},
{
trigger: `.o_statusbar_buttons button:enabled:contains('${innerTextButton}')`,
content: description,
position: "bottom",
},
].map((step) =>
this.addDebugHelp(
this._getHelpMessage(
"statusbarButtonsSteps",
innerTextButton,
description,
extraTrigger
),
step
)
);
},
simulateEnterKeyboardInSearchModal() {
return {
mobile: true,
trigger: ".o_searchview_input",
extra_trigger: ".modal:not(.o_inactive_modal) .dropdown-menu.o_searchview_autocomplete",
position: "bottom",
run: (action) => {
const keyEventEnter = new KeyboardEvent("keydown", {
bubbles: true,
cancelable: true,
key: "Enter",
code: "Enter",
which: 13,
keyCode: 13,
});
action.tip_widget.$anchor[0].dispatchEvent(keyEventEnter);
},
debugHelp: this._getHelpMessage("simulateEnterKeyboardInSearchModal"),
};
},
mobileKanbanSearchMany2X(modalTitle, valueSearched) {
return [
{
mobile: true,
trigger: `.o_control_panel_navigation .btn .fa-search`,
position: "bottom",
},
{
mobile: true,
trigger: ".o_searchview_input",
extra_trigger: `.modal:not(.o_inactive_modal) .modal-title:contains('${modalTitle}')`,
position: "bottom",
run: `text ${valueSearched}`,
},
this.simulateEnterKeyboardInSearchModal(),
{
mobile: true,
trigger: `.o_kanban_record .o_kanban_record_title :contains('${valueSearched}')`,
position: "bottom",
},
].map((step) =>
this.addDebugHelp(
this._getHelpMessage("mobileKanbanSearchMany2X", modalTitle, valueSearched),
step
)
);
},
/**
* Utility steps to save a form and wait for the save to complete
*
* @param {object} [options]
* @param {string} [options.content]
* @param {string} [options.extra_trigger] additional save-condition selector
*/
saveForm(options = {}) {
return [
{
content: options.content || "save form",
trigger: ".o_form_button_save",
extra_trigger: options.extra_trigger,
run: "click",
auto: true,
},
{
content: "wait for save completion",
trigger: ".o_form_readonly, .o_form_saved",
run() {},
auto: true,
},
];
},
/**
* Utility steps to cancel a form creation or edition.
*
* Supports creation/edition from either a form or a list view (so checks
* for both states).
*/
discardForm(options = {}) {
return [
{
content: options.content || "exit the form",
trigger: ".o_form_button_cancel",
extra_trigger: options.extra_trigger,
run: "click",
auto: true,
},
{
content: "wait for cancellation to complete",
trigger:
".o_view_controller.o_list_view, .o_form_view > div > div > .o_form_readonly, .o_form_view > div > div > .o_form_saved",
run() {},
auto: true,
},
];
},
};