-
Notifications
You must be signed in to change notification settings - Fork 23.1k
/
action_service.js
1466 lines (1381 loc) · 55.1 KB
/
action_service.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
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/** @odoo-module **/
import { _t } from "@web/core/l10n/translation";
import { browser } from "@web/core/browser/browser";
import { makeContext } from "@web/core/context";
import { useDebugCategory } from "@web/core/debug/debug_context";
import { evaluateExpr } from "@web/core/py_js/py";
import { registry } from "@web/core/registry";
import { Deferred, KeepLast } from "@web/core/utils/concurrency";
import { useBus, useService } from "@web/core/utils/hooks";
import { View, ViewNotFoundError } from "@web/views/view";
import { ActionDialog } from "./action_dialog";
import { CallbackRecorder } from "./action_hook";
import { ReportAction } from "./reports/report_action";
import { UPDATE_METHODS } from "@web/core/orm_service";
import { ControlPanel } from "@web/search/control_panel/control_panel";
import {
Component,
markup,
onMounted,
onWillUnmount,
onError,
useChildSubEnv,
xml,
reactive,
} from "@odoo/owl";
import { downloadReport, getReportUrl } from "./reports/utils";
class BlankComponent extends Component {
static props = ["onMounted", "withControlPanel", "*"];
static template = xml`
<ControlPanel display="{disableDropdown: true}" t-if="props.withControlPanel and !env.isSmall">
<t t-set-slot="layout-buttons">
<button class="btn btn-primary invisible"> empty </button>
</t>
</ControlPanel>`;
static components = { ControlPanel };
setup() {
useChildSubEnv({ config: { breadcrumbs: [], noBreadcrumbs: true } });
onMounted(() => this.props.onMounted());
}
}
const actionHandlersRegistry = registry.category("action_handlers");
const actionRegistry = registry.category("actions");
const viewRegistry = registry.category("views");
/** @typedef {number|false} ActionId */
/** @typedef {Object} ActionDescription */
/** @typedef {"current" | "fullscreen" | "new" | "main" | "self" | "inline"} ActionMode */
/** @typedef {string} ActionTag */
/** @typedef {string} ActionXMLId */
/** @typedef {Object} Context */
/** @typedef {Function} CallableFunction */
/** @typedef {string} ViewType */
/** @typedef {ActionId|ActionXMLId|ActionTag|ActionDescription} ActionRequest */
/**
* @typedef {Object} ActionOptions
* @property {Context} [additionalContext]
* @property {boolean} [clearBreadcrumbs]
* @property {CallableFunction} [onClose]
* @property {Object} [props]
* @property {ViewType} [viewType]
*/
export async function clearUncommittedChanges(env) {
const callbacks = [];
env.bus.trigger("CLEAR-UNCOMMITTED-CHANGES", callbacks);
const res = await Promise.all(callbacks.map((fn) => fn()));
return !res.includes(false);
}
export const standardActionServiceProps = {
action: Object, // prop added by _getActionInfo
actionId: { type: Number, optional: true }, // prop added by _getActionInfo
className: String, // prop added by the ActionContainer
globalState: { type: Object, optional: true }, // prop added by _updateUI
state: { type: Object, optional: true }, // prop added by _updateUI
};
function parseActiveIds(ids) {
const activeIds = [];
if (typeof ids === "string") {
activeIds.push(...ids.split(",").map(Number));
} else if (typeof ids === "number") {
activeIds.push(ids);
}
return activeIds;
}
const DIALOG_SIZES = {
"extra-large": "xl",
large: "lg",
medium: "md",
small: "sm",
};
// -----------------------------------------------------------------------------
// Errors
// -----------------------------------------------------------------------------
export class ControllerNotFoundError extends Error {}
export class InvalidButtonParamsError extends Error {}
// -----------------------------------------------------------------------------
// ActionManager (Service)
// -----------------------------------------------------------------------------
// regex that matches context keys not to forward from an action to another
const CTX_KEY_REGEX =
/^(?:(?:default_|search_default_|show_).+|.+_view_ref|group_by|group_by_no_leaf|active_id|active_ids|orderedBy)$/;
// only register this template once for all dynamic classes ControllerComponent
const ControllerComponentTemplate = xml`<t t-component="Component" t-props="componentProps"/>`;
function makeActionManager(env) {
const keepLast = new KeepLast();
let id = 0;
let controllerStack = [];
let dialogCloseProm;
let actionCache = {};
let dialog = null;
let nextDialog = null;
// The state action (or default user action if none) is loaded as soon as possible
// so that the next "doAction" will have its action ready when needed.
const actionParams = _getActionParams();
if (actionParams && typeof actionParams.actionRequest === "number") {
const { actionRequest, options } = actionParams;
_loadAction(actionRequest, options.additionalContext);
}
env.bus.addEventListener("CLEAR-CACHES", () => {
actionCache = {};
});
env.bus.addEventListener("RPC:RESPONSE", (ev) => {
const { model, method } = ev.detail.data.params;
if (model === "ir.actions.act_window" && UPDATE_METHODS.includes(method)) {
actionCache = {};
}
});
// ---------------------------------------------------------------------------
// misc
// ---------------------------------------------------------------------------
/**
* Removes the current dialog from the action service's state.
* It returns the dialog's onClose callback to be able to propagate it to the next dialog.
*
* @return {Function|undefined} When there was a dialog, returns its onClose callback for propagation to next dialog.
*/
function _removeDialog() {
if (dialog) {
const { onClose, remove } = dialog;
dialog = null;
// Remove the dialog from the dialog_service.
// The code is well enough designed to avoid falling in a function call loop.
remove();
return onClose;
}
}
/**
* Returns the last controller of the current controller stack.
*
* @returns {Controller|null}
*/
function _getCurrentController() {
const stack = controllerStack;
return stack.length ? stack[stack.length - 1] : null;
}
/**
* Given an id, xmlid, tag (key of the client action registry) or directly an
* object describing an action.
*
* @private
* @param {ActionRequest} actionRequest
* @param {Context} [context={}]
* @returns {Promise<Action>}
*/
async function _loadAction(actionRequest, context = {}) {
if (typeof actionRequest === "string" && actionRegistry.contains(actionRequest)) {
// actionRequest is a key in the actionRegistry
return {
target: "current",
tag: actionRequest,
type: "ir.actions.client",
};
}
if (typeof actionRequest === "string" || typeof actionRequest === "number") {
// actionRequest is an id or an xmlid
const additional_context = {
active_id: context.active_id,
active_ids: context.active_ids,
active_model: context.active_model,
};
const key = `${JSON.stringify(actionRequest)},${JSON.stringify(additional_context)}`;
let action;
if (!actionCache[key]) {
actionCache[key] = env.services.rpc("/web/action/load", {
action_id: actionRequest,
additional_context,
});
action = await actionCache[key];
if (action.help) {
action.help = markup(action.help);
}
} else {
action = await actionCache[key];
}
if (!action) {
return {
type: "ir.actions.client",
tag: "invalid_action",
id: actionRequest,
};
}
return Object.assign({}, action);
}
// actionRequest is an object describing the action
return actionRequest;
}
/**
* this function returns an action description
* with a unique jsId.
*/
function _preprocessAction(action, context = {}) {
try {
action._originalAction = JSON.stringify(action);
} catch {
// do nothing, the action might simply not be serializable
}
action.context = makeContext([context, action.context], env.services.user.context);
const domain = action.domain || [];
action.domain =
typeof domain === "string"
? evaluateExpr(domain, Object.assign({}, env.services.user.context, action.context))
: domain;
if (action.help) {
const htmlHelp = document.createElement("div");
htmlHelp.innerHTML = action.help;
if (!htmlHelp.innerText.trim()) {
delete action.help;
}
}
action = { ...action }; // manipulate a copy to keep cached action unmodified
action.jsId = `action_${++id}`;
if (action.type === "ir.actions.act_window" || action.type === "ir.actions.client") {
action.target = action.target || "current";
}
if (action.type === "ir.actions.act_window") {
action.views = [...action.views.map((v) => [v[0], v[1] === "tree" ? "list" : v[1]])]; // manipulate a copy to keep cached action unmodified
action.controllers = {};
const target = action.target;
if (target !== "inline" && !(target === "new" && action.views[0][1] === "form")) {
// FIXME: search view arch is already sent with load_action, so either remove it
// from there or load all fieldviews alongside the action for the sake of consistency
const searchViewId = action.search_view_id ? action.search_view_id[0] : false;
action.views.push([searchViewId, "search"]);
}
}
return action;
}
/**
* @private
* @param {string} viewType
* @throws {Error} if the current controller is not a view
* @returns {View | null}
*/
function _getView(viewType) {
const currentController = controllerStack[controllerStack.length - 1];
if (currentController.action.type !== "ir.actions.act_window") {
throw new Error(`switchView called but the current controller isn't a view`);
}
const view = currentController.views.find((view) => view.type === viewType);
return view || null;
}
/**
* Given a controller stack, returns the list of breadcrumb items.
*
* @private
* @param {ControllerStack} stack
* @returns {Breadcrumbs}
*/
function _getBreadcrumbs(stack) {
return stack
.filter((controller) => controller.action.tag !== "menu")
.map((controller) => {
return {
jsId: controller.jsId,
get name() {
return controller.displayName;
},
};
});
}
/**
* @private
* @returns {ActionParams | null}
*/
function _getActionParams() {
const state = env.services.router.current.hash;
const options = { clearBreadcrumbs: true };
let actionRequest = null;
if (state.action) {
const context = {};
if (state.active_id) {
context.active_id = state.active_id;
}
if (state.active_ids) {
context.active_ids = parseActiveIds(state.active_ids);
} else if (state.active_id) {
context.active_ids = [state.active_id];
}
// ClientAction
if (actionRegistry.contains(state.action)) {
actionRequest = {
context,
params: state,
tag: state.action,
type: "ir.actions.client",
};
} else {
// The action to load isn't the current one => executes it
actionRequest = state.action;
context.params = state;
Object.assign(options, {
additionalContext: context,
viewType: state.view_type,
});
if (state.id) {
options.props = { resId: state.id };
}
}
} else if (state.model) {
if (state.id) {
actionRequest = {
res_model: state.model,
res_id: state.id,
type: "ir.actions.act_window",
views: [[state.view_id ? state.view_id : false, "form"]],
};
} else if (state.view_type) {
// This is a window action on a multi-record view => restores it from
// the session storage
const storedAction = browser.sessionStorage.getItem("current_action");
const lastAction = JSON.parse(storedAction || "{}");
if (lastAction.help) {
lastAction.help = markup(lastAction.help);
}
if (lastAction.res_model === state.model) {
if (lastAction.context) {
// If this method is called because of a company switch, the
// stored allowed_company_ids is incorrect.
delete lastAction.context.allowed_company_ids;
}
actionRequest = lastAction;
options.viewType = state.view_type;
}
}
}
// If no action => falls back on the user default action (if any).
if (!actionRequest && env.services.user.home_action_id) {
actionRequest = env.services.user.home_action_id;
}
return actionRequest ? { actionRequest, options } : null;
}
/**
* @param {ClientAction} action
* @param {Object} props
* @returns {{ props: ActionProps, config: Config }}
*/
function _getActionInfo(action, props) {
return {
props: Object.assign({}, props, { action, actionId: action.id }),
config: {
actionId: action.id,
actionType: "ir.actions.client",
actionFlags: action.flags,
},
displayName: action.display_name || action.name || "",
};
}
/**
* @param {Action} action
* @returns {ActionMode}
*/
function _getActionMode(action) {
if (action.target === "new") {
// No possible override for target="new"
return "new";
}
if (action.type === "ir.actions.client") {
const clientAction = actionRegistry.get(action.tag);
if (clientAction.target) {
// Target is forced by the definition of the client action
return clientAction.target;
}
}
if (controllerStack.some((c) => c.action.target === "fullscreen")) {
// Force fullscreen when one of the controllers is set to fullscreen
return "fullscreen";
}
// Default: current
return "current";
}
/**
* @private
* @returns {SwitchViewParams | null}
*/
function _getSwitchViewParams() {
const state = env.services.router.current.hash;
if (state.action && !actionRegistry.contains(state.action)) {
const currentController = controllerStack[controllerStack.length - 1];
const currentActionId =
currentController && currentController.action && currentController.action.id;
// Window Action: determines model, viewType etc....
if (
currentController &&
currentController.action.type === "ir.actions.act_window" &&
currentActionId === state.action
) {
const props = {
resId: state.id || false,
};
const viewType = state.view_type || currentController.view.type;
return { viewType, props };
}
}
return null;
}
/**
* @param {BaseView} view
* @param {ActWindowAction} action
* @param {BaseView[]} views
* @param {Object} props
* @returns {{ props: ViewProps, config: Config }}
*/
function _getViewInfo(view, action, views, props = {}) {
const target = action.target;
const viewSwitcherEntries = views
.filter((v) => v.multiRecord === view.multiRecord)
.map((v) => {
const viewSwitcherEntry = {
icon: v.icon,
name: v.display_name.toString(),
type: v.type,
multiRecord: v.multiRecord,
};
if (view.type === v.type) {
viewSwitcherEntry.active = true;
}
return viewSwitcherEntry;
});
const context = action.context || {};
let groupBy = context.group_by || [];
if (typeof groupBy === "string") {
groupBy = [groupBy];
}
const viewProps = Object.assign({}, props, {
context,
display: { mode: target === "new" ? "inDialog" : target },
domain: action.domain || [],
groupBy,
loadActionMenus: target !== "new" && target !== "inline",
loadIrFilters: action.views.some((v) => v[1] === "search"),
resModel: action.res_model,
type: view.type,
selectRecord: async (resId, { activeIds, mode }) => {
if (target !== "new" && _getView("form")) {
await switchView("form", { mode, resId, resIds: activeIds });
}
},
createRecord: async () => {
if (target !== "new" && _getView("form")) {
await switchView("form", { resId: false });
}
},
});
if (view.type === "form") {
if (action.target === "new") {
viewProps.mode = "edit";
if (!viewProps.onSave) {
viewProps.onSave = (record, params) => {
if (params && params.closable) {
doAction({ type: "ir.actions.act_window_close" });
}
};
}
}
if (action.flags && "mode" in action.flags) {
viewProps.mode = action.flags.mode;
}
}
if (target === "inline") {
viewProps.searchMenuTypes = [];
}
const specialKeys = ["help", "useSampleModel", "limit", "count"];
for (const key of specialKeys) {
if (key in action) {
if (key === "help") {
viewProps.noContentHelp = action.help;
} else {
viewProps[key] = action[key];
}
}
}
if (context.search_disable_custom_filters) {
viewProps.activateFavorite = false;
}
// view specific
if (action.res_id && !viewProps.resId) {
viewProps.resId = action.res_id;
}
viewProps.noBreadcrumbs =
"no_breadcrumbs" in action.context ? action.context.no_breadcrumbs : target === "new";
delete action.context.no_breadcrumbs;
return {
props: viewProps,
config: {
actionId: action.id,
actionType: "ir.actions.act_window",
actionFlags: action.flags,
views: action.views,
viewSwitcherEntries,
},
displayName: action.display_name || action.name || "",
};
}
/**
* Computes the position of the controller in the nextStack according to options
* @param {Object} options
* @param {boolean} [options.clearBreadcrumbs=false]
* @param {'replaceLast' | 'replaceLastAction'} [options.stackPosition]
* @param {number} [options.index]
*/
function _computeStackIndex(options) {
let index = null;
if (options.clearBreadcrumbs) {
index = 0;
} else if (options.stackPosition === "replaceCurrentAction") {
const currentController = controllerStack[controllerStack.length - 1];
if (currentController) {
index = controllerStack.findIndex(
(ct) => ct.action.jsId === currentController.action.jsId
);
}
} else if (options.stackPosition === "replacePreviousAction") {
let last;
for (let i = controllerStack.length - 1; i >= 0; i--) {
const action = controllerStack[i].action.jsId;
if (!last) {
last = action;
}
if (action !== last) {
last = action;
break;
}
}
if (last) {
index = controllerStack.findIndex((ct) => ct.action.jsId === last);
}
// TODO: throw if there is no previous action?
} else if ("index" in options) {
index = options.index;
} else {
index = controllerStack.length;
}
return index;
}
/**
* Triggers a re-rendering with respect to the given controller.
*
* @private
* @param {Controller} controller
* @param {UpdateStackOptions} options
* @param {boolean} [options.clearBreadcrumbs=false]
* @param {number} [options.index]
* @returns {Promise<Number>}
*/
async function _updateUI(controller, options = {}) {
let resolve;
let reject;
let dialogCloseResolve;
let removeDialogFn;
const currentActionProm = new Promise((_res, _rej) => {
resolve = _res;
reject = _rej;
});
const action = controller.action;
const index = _computeStackIndex(options);
const controllerArray = [controller];
if (options.lazyController) {
controllerArray.unshift(options.lazyController);
}
const nextStack = controllerStack.slice(0, index).concat(controllerArray);
// Compute breadcrumbs
controller.config.breadcrumbs = reactive(
action.target === "new" ? [] : _getBreadcrumbs(nextStack)
);
controller.config.getDisplayName = () => controller.displayName;
controller.config.setDisplayName = (displayName) => {
controller.displayName = displayName;
if (controller === _getCurrentController()) {
// if not mounted yet, will be done in "mounted"
env.services.title.setParts({ action: controller.displayName });
}
if (action.target !== "new") {
// This is a hack to force the reactivity when a new displayName is set
controller.config.breadcrumbs.push(undefined);
controller.config.breadcrumbs.pop();
}
};
controller.config.historyBack = () => {
const previousController = controllerStack[controllerStack.length - 2];
if (previousController && !dialog) {
restore(previousController.jsId);
} else {
_executeCloseAction();
}
};
class ControllerComponent extends Component {
setup() {
this.Component = controller.Component;
this.titleService = useService("title");
useDebugCategory("action", { action });
useChildSubEnv({
config: controller.config,
});
if (action.target !== "new") {
this.__beforeLeave__ = new CallbackRecorder();
this.__getGlobalState__ = new CallbackRecorder();
this.__getLocalState__ = new CallbackRecorder();
useBus(env.bus, "CLEAR-UNCOMMITTED-CHANGES", (ev) => {
const callbacks = ev.detail;
const beforeLeaveFns = this.__beforeLeave__.callbacks;
callbacks.push(...beforeLeaveFns);
});
if (this.constructor.Component !== View) {
useChildSubEnv({
__beforeLeave__: this.__beforeLeave__,
__getGlobalState__: this.__getGlobalState__,
__getLocalState__: this.__getLocalState__,
});
}
}
this.isMounted = false;
onMounted(this.onMounted);
onWillUnmount(this.onWillUnmount);
onError(this.onError);
}
onError(error) {
if (this.isMounted) {
// the error occurred on the controller which is
// already in the DOM, so simply show the error
Promise.resolve().then(() => {
throw error;
});
} else {
reject(error);
if (action.target === "new") {
removeDialogFn?.();
} else {
const lastCt = controllerStack[controllerStack.length - 1];
if (lastCt) {
if (lastCt.jsId !== controller.jsId) {
// the error occurred while rendering a new controller,
// so go back to the last non faulty controller
// (the error will be shown anyway as the promise
// has been rejected)
restore(lastCt.jsId);
}
} else {
env.bus.trigger("ACTION_MANAGER:UPDATE", {});
}
}
}
}
onMounted() {
if (action.target === "new") {
dialogCloseProm = new Promise((_r) => {
dialogCloseResolve = _r;
}).then(() => {
dialogCloseProm = undefined;
});
dialog = nextDialog;
} else {
controller.getGlobalState = () => {
const exportFns = this.__getGlobalState__.callbacks;
if (exportFns.length) {
return Object.assign({}, ...exportFns.map((fn) => fn()));
}
};
controller.getLocalState = () => {
const exportFns = this.__getLocalState__.callbacks;
if (exportFns.length) {
return Object.assign({}, ...exportFns.map((fn) => fn()));
}
};
// LEGACY CODE COMPATIBILITY: remove when controllers will be written in owl
// we determine here which actions no longer occur in the nextStack,
// and we manually destroy all their controller's widgets
const nextStackActionIds = nextStack.map((c) => c.action.jsId);
const toDestroy = new Set();
for (const c of controllerStack) {
if (!nextStackActionIds.includes(c.action.jsId)) {
toDestroy.add(c);
}
}
for (const c of toDestroy) {
if (c.exportedState && c.exportedState.__legacy_widget__) {
c.exportedState.__legacy_widget__.destroy();
}
}
// END LEGACY CODE COMPATIBILITY
controllerStack = nextStack; // the controller is mounted, commit the new stack
pushState(controller);
this.titleService.setParts({ action: controller.displayName });
browser.sessionStorage.setItem(
"current_action",
action._originalAction || "{}"
);
}
resolve();
env.bus.trigger("ACTION_MANAGER:UI-UPDATED", _getActionMode(action));
this.isMounted = true;
}
onWillUnmount() {
if (action.target === "new" && dialogCloseResolve) {
dialogCloseResolve();
}
}
get componentProps() {
const componentProps = { ...this.props };
if (this.constructor.Component === View) {
componentProps.__beforeLeave__ = this.__beforeLeave__;
componentProps.__getGlobalState__ = this.__getGlobalState__;
componentProps.__getLocalState__ = this.__getLocalState__;
}
return componentProps;
}
}
ControllerComponent.template = ControllerComponentTemplate;
ControllerComponent.Component = controller.Component;
ControllerComponent.props = {
"*": true,
};
if (action.target === "new") {
const actionDialogProps = {
ActionComponent: ControllerComponent,
actionProps: controller.props,
actionType: action.type,
};
if (action.name) {
actionDialogProps.title = action.name;
}
const size = DIALOG_SIZES[action.context.dialog_size];
if (size) {
actionDialogProps.size = size;
}
const onClose = _removeDialog();
removeDialogFn = env.services.dialog.add(ActionDialog, actionDialogProps, {
onClose: () => {
const onClose = _removeDialog();
if (onClose) {
onClose();
}
},
});
if (nextDialog) {
nextDialog.remove();
}
nextDialog = {
remove: removeDialogFn,
onClose: onClose || options.onClose,
};
return currentActionProm;
}
const currentController = _getCurrentController();
if (currentController && currentController.getLocalState) {
currentController.exportedState = currentController.getLocalState();
}
if (controller.exportedState) {
controller.props.state = controller.exportedState;
}
// TODO DAM Remarks:
// this thing seems useless for client actions.
// restore and switchView (at least) use this --> cannot be done in switchView only
// if prop globalState has been passed in doAction, since the action is new the prop won't be overridden in l655.
// if globalState is not useful for client actions --> maybe use that thing in useSetupView instead of useSetupAction?
// a good thing: the Object.assign seems to reflect the use of "externalState" in legacy Model class --> things should be fine.
if (currentController && currentController.getGlobalState) {
currentController.action.globalState = Object.assign(
{},
currentController.action.globalState,
currentController.getGlobalState() // what if this = {}?
);
}
if (controller.action.globalState) {
controller.props.globalState = controller.action.globalState;
}
const closingProm = _executeCloseAction();
if (options.clearBreadcrumbs && !options.noEmptyTransition) {
const def = new Deferred();
env.bus.trigger("ACTION_MANAGER:UPDATE", {
id: ++id,
Component: BlankComponent,
componentProps: {
onMounted: () => def.resolve(),
withControlPanel: action.type === "ir.actions.act_window",
},
});
await def;
}
if (options.onActionReady) {
options.onActionReady(action);
}
controller.__info__ = {
id: ++id,
Component: ControllerComponent,
componentProps: controller.props,
};
env.services.dialog.closeAll();
env.bus.trigger("ACTION_MANAGER:UPDATE", controller.__info__);
return Promise.all([currentActionProm, closingProm]).then((r) => r[0]);
}
// ---------------------------------------------------------------------------
// ir.actions.act_url
// ---------------------------------------------------------------------------
/**
* Executes actions of type 'ir.actions.act_url', i.e. redirects to the
* given url.
*
* @private
* @param {ActURLAction} action
* @param {ActionOptions} options
*/
function _executeActURLAction(action, options) {
let url = action.url;
if (url && !(url.startsWith("http") || url.startsWith("/"))) {
url = "/" + url;
}
if (action.target === "download" || action.target === "self") {
browser.location.assign(url);
} else {
const w = browser.open(url, "_blank");
if (!w || w.closed || typeof w.closed === "undefined") {
const msg = _t(
"A popup window has been blocked. You may need to change your " +
"browser settings to allow popup windows for this page."
);
env.services.notification.add(msg, {
sticky: true,
type: "warning",
});
}
if (action.close) {
return doAction(
{ type: "ir.actions.act_window_close" },
{ onClose: options.onClose }
);
} else if (options.onClose) {
options.onClose();
}
}
}
// ---------------------------------------------------------------------------
// ir.actions.act_window
// ---------------------------------------------------------------------------
/**
* Executes an action of type 'ir.actions.act_window'.
*
* @private
* @param {ActWindowAction} action
* @param {ActionOptions} options
*/
async function _executeActWindowAction(action, options) {
const views = [];
for (const [, type] of action.views) {
if (type !== "search" && viewRegistry.contains(type)) {
views.push(viewRegistry.get(type));
}
}
if (!views.length) {
throw new Error(`No view found for act_window action ${action.id}`);
}
let view = options.viewType && views.find((v) => v.type === options.viewType);
let lazyView;
if (view && !view.multiRecord) {
lazyView = views[0].multiRecord ? views[0] : undefined;
} else if (!view) {
view = views[0];
}
if (env.isSmall) {
view = _findView(views, view.multiRecord, action.mobile_view_mode) || view;
if (lazyView) {
lazyView =
_findView(views, lazyView.multiRecord, action.mobile_view_mode) || lazyView;
}
}
const controller = {
jsId: `controller_${++id}`,
Component: View,
action,
view,
views,
..._getViewInfo(view, action, views, options.props),
};
action.controllers[view.type] = controller;
const updateUIOptions = {
clearBreadcrumbs: options.clearBreadcrumbs,
onClose: options.onClose,
stackPosition: options.stackPosition,
onActionReady: options.onActionReady,
noEmptyTransition: options.noEmptyTransition,
};
if (lazyView) {
updateUIOptions.lazyController = {
jsId: `controller_${++id}`,
Component: View,
action,
view: lazyView,
views,
..._getViewInfo(lazyView, action, views),
};
}
return _updateUI(controller, updateUIOptions);
}
/**
* @private
* @param {Array} views an array of views
* @param {boolean} multiRecord true if we search for a multiRecord view
* @param {string} viewType type of the view to search
* @returns {Object|undefined} the requested view if it could be found
*/
function _findView(views, multiRecord, viewType) {
return views.find((v) => v.type === viewType && v.multiRecord == multiRecord);
}
// ---------------------------------------------------------------------------
// ir.actions.client
// ---------------------------------------------------------------------------
/**
* Executes an action of type 'ir.actions.client'.
*
* @private
* @param {ClientAction} action
* @param {ActionOptions} options
*/
async function _executeClientAction(action, options) {
const clientAction = actionRegistry.get(action.tag);
if (clientAction.prototype instanceof Component) {
if (action.target !== "new") {
const canProceed = await clearUncommittedChanges(env);