-
Warehouse:
diff --git a/addons/stock/static/tests/stock_traceability_report_backend_tests.js b/addons/stock/static/tests/stock_traceability_report_backend_tests.js
index 08181d8535c..bdd7fc8375b 100644
--- a/addons/stock/static/tests/stock_traceability_report_backend_tests.js
+++ b/addons/stock/static/tests/stock_traceability_report_backend_tests.js
@@ -7,7 +7,9 @@ odoo.define('stock.stock_traceability_report_backend_tests', function (require)
const testUtils = require('web.test_utils');
const { patch, unpatch } = require('web.utils');
- const { createActionManager, dom: domUtils } = testUtils;
+ const { dom: domUtils } = testUtils;
+ const { legacyExtraNextTick } = require("@web/../tests/helpers/utils");
+ const { createWebClient, doAction } = require('@web/../tests/webclient/helpers');
/**
* Helper function to instantiate a stock report action.
@@ -91,23 +93,8 @@ odoo.define('stock.stock_traceability_report_backend_tests', function (require)
this.__superMounted(...arguments);
},
});
-
- const actionManager = await createActionManager({
- actions: [
- {
- id: 42,
- name: "Stock report",
- tag: 'stock_report_generic',
- type: 'ir.actions.client',
- context: {},
- params: {},
- },
- ],
- archs: {
- 'partner,false,form': '
',
- 'partner,false,search': '
',
- },
- data: {
+ const serverData = {
+ models: {
partner: {
fields: {
display_name: { string: "Displayed name", type: "char" },
@@ -117,23 +104,39 @@ odoo.define('stock.stock_traceability_report_backend_tests', function (require)
],
},
},
+ views: {
+ 'partner,false,form': '
',
+ 'partner,false,search': '
',
+ },
+ actions: {
+ 42: {
+ id: 42,
+ name: "Stock report",
+ tag: 'stock_report_generic',
+ type: 'ir.actions.client',
+ context: {},
+ params: {},
+ },
+ },
+ };
+
+ const webClient = await createWebClient({
+ serverData,
mockRPC: function (route) {
if (route === '/web/dataset/call_kw/stock.traceability.report/get_html') {
return Promise.resolve({
html: '
Go to form view ',
});
}
- return this._super.apply(this, arguments);
- },
- intercepts: {
- do_action: ev => actionManager.doAction(ev.data.action, ev.data.options),
},
});
- await actionManager.doAction(42);
- await domUtils.click(actionManager.$('.o_stock_reports_web_action'));
- await domUtils.click(actionManager.$('.breadcrumb-item:first'));
- actionManager.destroy();
+ await doAction(webClient, 42);
+ await domUtils.click($(webClient.el).find('.o_stock_reports_web_action'));
+ await legacyExtraNextTick();
+ await domUtils.click($(webClient.el).find('.breadcrumb-item:first'));
+ await legacyExtraNextTick();
+ webClient.destroy();
assert.verifySteps([
'mounted 1',
diff --git a/addons/survey/__manifest__.py b/addons/survey/__manifest__.py
index fdc1e41dfc5..81df042a8be 100644
--- a/addons/survey/__manifest__.py
+++ b/addons/survey/__manifest__.py
@@ -58,7 +58,7 @@ sent mails with personal token for the invitation of the survey.
'assets': {
'survey.survey_assets': [
'web/static/lib/Chart/Chart.js',
- 'web/static/src/js/fields/field_utils.js',
+ 'web/static/src/legacy/js/fields/field_utils.js',
'survey/static/src/js/survey_quick_access.js',
'survey/static/src/js/survey_timer.js',
'survey/static/src/js/survey_breadcrumb.js',
diff --git a/addons/web/Gruntfile.js b/addons/web/Gruntfile.js
deleted file mode 100644
index 43b58c3b64b..00000000000
--- a/addons/web/Gruntfile.js
+++ /dev/null
@@ -1,20 +0,0 @@
-module.exports = function(grunt) {
-
- grunt.initConfig({
- jshint: {
- src: ['static/src/**/*.js', 'static/tests/**/*.js'],
- options: {
- sub: true, //[] instead of .
- evil: true, //eval
- laxbreak: true, //unsafe line breaks
- },
- },
- });
-
- grunt.loadNpmTasks('grunt-contrib-jshint');
-
- grunt.registerTask('test', []);
-
- grunt.registerTask('default', ['jshint']);
-
-};
\ No newline at end of file
diff --git a/addons/web/__manifest__.py b/addons/web/__manifest__.py
index 403536416d4..e32539890e0 100644
--- a/addons/web/__manifest__.py
+++ b/addons/web/__manifest__.py
@@ -38,31 +38,29 @@ This module provides the core of the Odoo Web Client.
# > web_editor.assets_wysiwyg = assets needed by components defined in the "web_editor" module.
'web.assets_qweb': [
- 'web/static/src/xml/base.xml',
- 'web/static/src/xml/chart.xml',
- 'web/static/src/xml/fields.xml',
- 'web/static/src/xml/file_upload_progress_bar.xml',
- 'web/static/src/xml/file_upload_progress_card.xml',
- 'web/static/src/xml/kanban.xml',
- 'web/static/src/xml/menu.xml',
- 'web/static/src/xml/notification.xml',
- 'web/static/src/xml/pivot.xml',
- 'web/static/src/xml/rainbow_man.xml',
- 'web/static/src/xml/report.xml',
- 'web/static/src/xml/search_panel.xml',
- 'web/static/src/xml/web_calendar.xml',
- 'web/static/src/xml/graph.xml',
- 'web/static/src/xml/week_days.xml',
+ 'web/static/src/**/*.xml',
+ ('remove', 'web/static/src/legacy/**/*.xml'),
+ 'web/static/src/legacy/xml/base.xml',
+ 'web/static/src/legacy/xml/chart.xml',
+ 'web/static/src/legacy/xml/fields.xml',
+ 'web/static/src/legacy/xml/file_upload_progress_bar.xml',
+ 'web/static/src/legacy/xml/file_upload_progress_card.xml',
+ 'web/static/src/legacy/xml/kanban.xml',
+ 'web/static/src/legacy/xml/pivot.xml',
+ 'web/static/src/legacy/xml/report.xml',
+ 'web/static/src/legacy/xml/search_panel.xml',
+ 'web/static/src/legacy/xml/web_calendar.xml',
+ 'web/static/src/legacy/xml/graph.xml',
+ 'web/static/src/legacy/xml/week_days.xml',
],
'web.assets_common_minimal': [
'web/static/lib/es6-promise/es6-promise-polyfill.js',
- 'web/static/src/js/promise_extension.js',
- 'web/static/src/js/boot.js',
+ 'web/static/src/legacy/js/promise_extension.js',
+ 'web/static/src/boot.js',
],
'web.assets_common': [
('include', 'web._assets_helpers'),
- 'web/static/src/scss/debug_profiling.scss',
'web/static/lib/bootstrap/scss/_variables.scss',
('include', 'web._assets_common_styles'),
@@ -73,8 +71,8 @@ This module provides the core of the Odoo Web Client.
('include', 'web.assets_common'),
# Remove assets_common_minimal
('remove', 'web/static/lib/es6-promise/es6-promise-polyfill.js'),
- ('remove', 'web/static/src/js/promise_extension.js'),
- ('remove', 'web/static/src/js/boot.js'),
+ ('remove', 'web/static/src/legacy/js/promise_extension.js'),
+ ('remove', 'web/static/src/boot.js'),
],
'web.assets_backend': [
('include', 'web._assets_helpers'),
@@ -85,138 +83,110 @@ This module provides the core of the Odoo Web Client.
('include', 'web._assets_bootstrap'),
'base/static/src/css/modules.css',
-
- 'web/static/src/scss/webclient_extra.scss',
- 'web/static/src/scss/webclient_layout.scss',
-
- 'web/static/src/scss/webclient.scss',
- 'web/static/src/scss/domain_selector.scss',
- 'web/static/src/scss/model_field_selector.scss',
- 'web/static/src/scss/progress_bar.scss',
- 'web/static/src/scss/dropdown.scss',
- 'web/static/src/scss/tooltip.scss',
- 'web/static/src/scss/switch_company_menu.scss',
- 'web/static/src/scss/debug_manager.scss',
- 'web/static/src/scss/ace.scss',
- 'web/static/src/scss/control_panel.scss',
- 'web/static/src/scss/fields.scss',
- 'web/static/src/scss/file_upload.scss',
- 'web/static/src/scss/views.scss',
- 'web/static/src/scss/pivot_view.scss',
- 'web/static/src/scss/graph_view.scss',
- 'web/static/src/scss/form_view.scss',
- 'web/static/src/scss/list_view.scss',
- 'web/static/src/scss/kanban_dashboard.scss',
- 'web/static/src/scss/kanban_examples_dialog.scss',
- 'web/static/src/scss/kanban_column_progressbar.scss',
- 'web/static/src/scss/kanban_view.scss',
- 'web/static/src/scss/web_calendar.scss',
- 'web/static/src/scss/search_view.scss',
- 'web/static/src/scss/search_panel.scss',
- 'web/static/src/scss/dropdown_menu.scss',
- 'web/static/src/scss/data_export.scss',
- 'base/static/src/scss/onboarding.scss',
- 'web/static/src/scss/attachment_preview.scss',
- 'web/static/src/scss/notification.scss',
- 'web/static/src/scss/base_document_layout.scss',
- 'web/static/src/scss/special_fields.scss',
- 'web/static/src/scss/ribbon.scss',
- 'web/static/src/scss/base_settings.scss',
- 'web/static/src/scss/report_backend.scss',
- 'web/static/src/scss/dropdown_extra.scss',
- 'web/static/src/scss/fields_extra.scss',
- 'web/static/src/scss/form_view_extra.scss',
- 'web/static/src/scss/list_view_extra.scss',
- 'web/static/src/scss/search_view_extra.scss',
-
'base/static/src/js/res_config_settings.js',
+
+ 'web/static/src/core/utils/transitions.scss',
+ 'web/static/src/core/**/*',
+ 'web/static/src/fields/**/*',
+ 'web/static/src/views/**/*',
+ 'web/static/src/webclient/**/*',
+ ('remove', 'web/static/src/webclient/clickbot/clickbot.js'), # lazy loaded
+ 'web/static/src/env.js',
+
'web/static/lib/jquery.scrollTo/jquery.scrollTo.js',
'web/static/lib/fuzzy-master/fuzzy.js',
+ 'web/static/lib/luxon/luxon.js',
'web/static/lib/py.js/lib/py.js',
'web/static/lib/py.js/lib/py_extras.js',
'web/static/lib/jquery.ba-bbq/jquery.ba-bbq.js',
- 'web/static/src/js/_deprecated/*',
- 'web/static/src/js/chrome/abstract_action.js',
- 'web/static/src/js/chrome/abstract_web_client.js',
- 'web/static/src/js/chrome/action_manager_act_window.js',
- 'web/static/src/js/chrome/action_manager_report.js',
- 'web/static/src/js/chrome/action_manager.js',
- 'web/static/src/js/chrome/action_mixin.js',
- 'web/static/src/js/chrome/apps_menu.js',
- 'web/static/src/js/chrome/loading.js',
- 'web/static/src/js/chrome/menu.js',
- 'web/static/src/js/chrome/root_widget.js',
- 'web/static/src/js/chrome/systray_menu.js',
- 'web/static/src/js/chrome/user_menu.js',
- 'web/static/src/js/chrome/web_client.js',
- 'web/static/src/js/components/*',
- 'web/static/src/js/control_panel/*',
- 'web/static/src/js/core/domain.js',
- 'web/static/src/js/core/mvc.js',
- 'web/static/src/js/core/py_utils.js',
- 'web/static/src/js/core/context.js',
- 'web/static/src/js/core/data_comparison_utils.js',
- 'web/static/src/js/core/math_utils.js',
- 'web/static/src/js/core/misc.js',
- 'web/static/src/js/fields/*',
- 'web/static/src/js/report/utils.js',
- 'web/static/src/js/report/client_action.js',
- 'web/static/src/js/services/crash_manager_service.js',
- 'web/static/src/js/services/data_manager.js',
- 'web/static/src/js/services/report_service.js',
- 'web/static/src/js/services/session.js',
- 'web/static/src/js/tools/test_menus_loader.js',
- 'web/static/src/js/tools/debug_manager_backend.js',
- 'web/static/src/js/tools/tools.js',
- 'web/static/src/js/views/abstract_view.js',
- 'web/static/src/js/views/abstract_renderer.js',
- 'web/static/src/js/views/abstract_renderer_owl.js',
- 'web/static/src/js/views/abstract_model.js',
- 'web/static/src/js/views/abstract_controller.js',
- 'web/static/src/js/views/renderer_wrapper.js',
- 'web/static/src/js/views/search_panel_model_extension.js',
- 'web/static/src/js/views/search_panel.js',
- 'web/static/src/js/views/action_model.js',
- 'web/static/src/js/views/field_manager_mixin.js',
- 'web/static/src/js/views/file_upload_mixin.js',
- 'web/static/src/js/views/file_upload_progress_bar.js',
- 'web/static/src/js/views/file_upload_progress_card.js',
- 'web/static/src/js/views/sample_server.js',
- 'web/static/src/js/views/select_create_controllers_registry.js',
- 'web/static/src/js/views/signature_dialog.js',
- 'web/static/src/js/views/standalone_field_manager_mixin.js',
- 'web/static/src/js/views/view_registry.js',
- 'web/static/src/js/views/view_dialogs.js',
- 'web/static/src/js/views/view_utils.js',
- 'web/static/src/js/views/basic/*',
- 'web/static/src/js/views/calendar/*',
- 'web/static/src/js/views/form/*',
- 'web/static/src/js/views/graph/*',
- 'web/static/src/js/views/kanban/*',
- 'web/static/src/js/views/list/*',
- 'web/static/src/js/views/pivot/*',
- 'web/static/src/js/views/qweb/*',
- 'web/static/src/js/widgets/change_password.js',
- 'web/static/src/js/widgets/data_export.js',
- 'web/static/src/js/widgets/date_picker.js',
- 'web/static/src/js/widgets/domain_selector_dialog.js',
- 'web/static/src/js/widgets/domain_selector.js',
- 'web/static/src/js/widgets/iframe_widget.js',
- 'web/static/src/js/widgets/model_field_selector.js',
- 'web/static/src/js/widgets/switch_company_menu.js',
- 'web/static/src/js/widgets/pie_chart.js',
- 'web/static/src/js/widgets/ribbon.js',
- 'web/static/src/js/widgets/week_days.js',
- 'web/static/src/js/widgets/signature.js',
- 'web/static/src/js/widgets/attach_document.js',
- 'web/static/src/js/apps.js',
- 'web/static/src/js/env.js',
- 'web/static/src/js/model.js',
- 'web/static/src/js/owl_compatibility.js',
+ 'web/static/src/legacy/scss/domain_selector.scss',
+ 'web/static/src/legacy/scss/model_field_selector.scss',
+ 'web/static/src/legacy/scss/progress_bar.scss',
+ 'web/static/src/legacy/scss/dropdown.scss',
+ 'web/static/src/legacy/scss/tooltip.scss',
+ 'web/static/src/legacy/scss/switch_company_menu.scss',
+ 'web/static/src/legacy/scss/ace.scss',
+ 'web/static/src/legacy/scss/control_panel.scss',
+ 'web/static/src/legacy/scss/fields.scss',
+ 'web/static/src/legacy/scss/file_upload.scss',
+ 'web/static/src/legacy/scss/views.scss',
+ 'web/static/src/legacy/scss/pivot_view.scss',
+ 'web/static/src/legacy/scss/graph_view.scss',
+ 'web/static/src/legacy/scss/form_view.scss',
+ 'web/static/src/legacy/scss/list_view.scss',
+ 'web/static/src/legacy/scss/kanban_dashboard.scss',
+ 'web/static/src/legacy/scss/kanban_examples_dialog.scss',
+ 'web/static/src/legacy/scss/kanban_column_progressbar.scss',
+ 'web/static/src/legacy/scss/kanban_view.scss',
+ 'web/static/src/legacy/scss/web_calendar.scss',
+ 'web/static/src/legacy/scss/search_view.scss',
+ 'web/static/src/legacy/scss/search_panel.scss',
+ 'web/static/src/legacy/scss/data_export.scss',
+ 'base/static/src/scss/onboarding.scss',
+ 'web/static/src/legacy/scss/attachment_preview.scss',
+ 'web/static/src/legacy/scss/base_document_layout.scss',
+ 'web/static/src/legacy/scss/special_fields.scss',
+ 'web/static/src/legacy/scss/ribbon.scss',
+ 'web/static/src/legacy/scss/base_settings.scss',
+ 'web/static/src/legacy/scss/report_backend.scss',
+ 'web/static/src/legacy/scss/dropdown_extra.scss',
+ 'web/static/src/legacy/scss/fields_extra.scss',
+ 'web/static/src/legacy/scss/form_view_extra.scss',
+ 'web/static/src/legacy/scss/list_view_extra.scss',
+ 'web/static/src/legacy/scss/search_view_extra.scss',
+
+ 'web/static/src/legacy/action_adapters.js',
+ 'web/static/src/legacy/debug_manager.js',
+ 'web/static/src/legacy/legacy_service_provider.js',
+ 'web/static/src/legacy/legacy_client_actions.js',
+ 'web/static/src/legacy/legacy_dialog.js',
+ 'web/static/src/legacy/legacy_views.js',
+ 'web/static/src/legacy/legacy_promise_error_handler.js',
+ 'web/static/src/legacy/legacy_rpc_error_handler.js',
+ 'web/static/src/legacy/root_widget.js',
+ 'web/static/src/legacy/systray_menu.js',
+ 'web/static/src/legacy/systray_menu_item.js',
+ 'web/static/src/legacy/utils.js',
+ 'web/static/src/legacy/web_client.js',
+ 'web/static/src/legacy/js/_deprecated/*',
+ 'web/static/src/legacy/js/chrome/*',
+ 'web/static/src/legacy/js/components/*',
+ 'web/static/src/legacy/js/control_panel/*',
+ 'web/static/src/legacy/js/core/domain.js',
+ 'web/static/src/legacy/js/core/mvc.js',
+ 'web/static/src/legacy/js/core/py_utils.js',
+ 'web/static/src/legacy/js/core/context.js',
+ 'web/static/src/legacy/js/core/data_comparison_utils.js',
+ 'web/static/src/legacy/js/core/math_utils.js',
+ 'web/static/src/legacy/js/core/misc.js',
+ 'web/static/src/legacy/js/fields/*',
+ 'web/static/src/legacy/js/report/utils.js',
+ 'web/static/src/legacy/js/report/client_action.js',
+ 'web/static/src/legacy/js/services/data_manager.js',
+ 'web/static/src/legacy/js/services/report_service.js',
+ 'web/static/src/legacy/js/services/session.js',
+ 'web/static/src/legacy/js/tools/tools.js',
+ 'web/static/src/legacy/js/views/**/*',
+ 'web/static/src/legacy/js/widgets/change_password.js',
+ 'web/static/src/legacy/js/widgets/data_export.js',
+ 'web/static/src/legacy/js/widgets/date_picker.js',
+ 'web/static/src/legacy/js/widgets/domain_selector_dialog.js',
+ 'web/static/src/legacy/js/widgets/domain_selector.js',
+ 'web/static/src/legacy/js/widgets/iframe_widget.js',
+ 'web/static/src/legacy/js/widgets/model_field_selector.js',
+ 'web/static/src/legacy/js/widgets/pie_chart.js',
+ 'web/static/src/legacy/js/widgets/ribbon.js',
+ 'web/static/src/legacy/js/widgets/week_days.js',
+ 'web/static/src/legacy/js/widgets/signature.js',
+ 'web/static/src/legacy/js/widgets/attach_document.js',
+ 'web/static/src/legacy/js/apps.js',
+ 'web/static/src/legacy/js/env.js',
+ 'web/static/src/legacy/js/model.js',
+ 'web/static/src/legacy/js/owl_compatibility.js',
],
'web.assets_frontend_minimal': [
- 'web/static/src/js/public/lazyloader.js',
+ 'web/static/src/legacy/js/public/lazyloader.js',
],
'web.assets_frontend': [
('include', 'web._assets_helpers'),
@@ -226,28 +196,29 @@ This module provides the core of the Odoo Web Client.
('include', 'web._assets_bootstrap'),
- 'web/static/src/scss/base_frontend.scss',
- 'web/static/src/scss/lazyloader.scss',
- 'web/static/src/scss/navbar_mobile.scss',
- 'web/static/src/scss/notification.scss',
+ 'web/static/src/legacy/scss/base_frontend.scss',
+ 'web/static/src/legacy/scss/lazyloader.scss',
+ 'web/static/src/legacy/scss/navbar_mobile.scss',
('include', 'web.assets_frontend_minimal'),
- 'web/static/src/js/services/session.js',
- 'web/static/src/js/public/public_env.js',
- 'web/static/src/js/public/public_crash_manager.js',
- 'web/static/src/js/public/public_notification.js',
- 'web/static/src/js/public/public_root.js',
- 'web/static/src/js/public/public_root_instance.js',
- 'web/static/src/js/public/public_widget.js',
+ 'web/static/src/legacy/js/services/session.js',
+ 'web/static/src/legacy/js/public/public_env.js',
+ 'web/static/src/legacy/js/public/public_root.js',
+ 'web/static/src/legacy/js/public/public_root_instance.js',
+ 'web/static/src/legacy/js/public/public_widget.js',
+
+ ('include', 'web.frontend_legacy'),
],
'web.assets_frontend_lazy': [
('include', 'web.assets_frontend'),
# Remove assets_frontend_minimal
- ('remove', 'web/static/src/js/public/lazyloader.js')
+ ('remove', 'web/static/src/legacy/js/public/lazyloader.js')
],
'web.assets_backend_prod_only': [
- 'web/static/src/js/main.js',
+ 'web/static/src/main.js',
+ 'web/static/src/start.js',
+ 'web/static/src/legacy/legacy_setup.js',
],
# Optional Bundle for PDFJS lib
# Since PDFJS is quite huge (80000≈ lines), please only load it when it is necessary.
@@ -260,7 +231,7 @@ This module provides the core of the Odoo Web Client.
'web.report_assets_common': [
('include', 'web._assets_helpers'),
- 'web/static/src/scss/bootstrap_overridden_report.scss',
+ 'web/static/src/legacy/scss/bootstrap_overridden_report.scss',
'web/static/lib/bootstrap/scss/_variables.scss',
('include', 'web._assets_bootstrap'),
@@ -268,18 +239,18 @@ This module provides the core of the Odoo Web Client.
'base/static/src/css/description.css',
'web/static/lib/fontawesome/css/font-awesome.css',
'web/static/fonts/fonts.scss',
- 'web/static/src/scss/report.scss',
- 'web/static/src/scss/layout_standard.scss',
- 'web/static/src/scss/layout_background.scss',
- 'web/static/src/scss/layout_boxed.scss',
- 'web/static/src/scss/layout_clean.scss',
- '/web/static/src/scss/asset_styles_company_report.scss',
- 'web/static/src/js/services/session.js',
- 'web/static/src/js/public/public_root.js',
- 'web/static/src/js/public/public_root_instance.js',
- 'web/static/src/js/public/public_widget.js',
- 'web/static/src/js/report/utils.js',
- 'web/static/src/js/report/report.js',
+ 'web/static/src/legacy/scss/report.scss',
+ 'web/static/src/legacy/scss/layout_standard.scss',
+ 'web/static/src/legacy/scss/layout_background.scss',
+ 'web/static/src/legacy/scss/layout_boxed.scss',
+ 'web/static/src/legacy/scss/layout_clean.scss',
+ '/web/static/src/legacy/scss/asset_styles_company_report.scss',
+ 'web/static/src/legacy/js/services/session.js',
+ 'web/static/src/legacy/js/public/public_root.js',
+ 'web/static/src/legacy/js/public/public_root_instance.js',
+ 'web/static/src/legacy/js/public/public_widget.js',
+ 'web/static/src/legacy/js/report/utils.js',
+ 'web/static/src/legacy/js/report/report.js',
],
'web.report_assets_pdf': [
'web/static/src/css/reset.min.css',
@@ -299,62 +270,62 @@ This module provides the core of the Odoo Web Client.
# > web._assets_helpers = define assets needed in most main bundles
'web._assets_primary_variables': [
- 'web/static/src/scss/primary_variables.scss',
+ 'web/static/src/legacy/scss/primary_variables.scss',
],
'web._assets_secondary_variables': [
- 'web/static/src/scss/secondary_variables.scss',
+ 'web/static/src/legacy/scss/secondary_variables.scss',
],
'web._assets_helpers': [
'web/static/lib/bootstrap/scss/_functions.scss',
'web/static/lib/bootstrap/scss/_mixins.scss',
- 'web/static/src/scss/bs_mixins_overrides.scss',
- 'web/static/src/scss/utils.scss',
+ 'web/static/src/legacy/scss/bs_mixins_overrides.scss',
+ 'web/static/src/legacy/scss/utils.scss',
('include', 'web._assets_primary_variables'),
('include', 'web._assets_secondary_variables'),
],
'web._assets_bootstrap': [
- 'web/static/src/scss/import_bootstrap.scss',
- 'web/static/src/scss/bootstrap_review.scss',
+ 'web/static/src/legacy/scss/import_bootstrap.scss',
+ 'web/static/src/legacy/scss/bootstrap_review.scss',
],
'web._assets_backend_helpers': [
- 'web/static/src/scss/bootstrap_overridden.scss',
+ 'web/static/src/legacy/scss/bootstrap_overridden.scss',
+ 'web/static/src/legacy/scss/bs_mixins_overrides_backend.scss',
],
'web._assets_frontend_helpers': [
- 'web/static/src/scss/bootstrap_overridden_frontend.scss',
+ 'web/static/src/legacy/scss/bootstrap_overridden_frontend.scss',
],
'web._assets_common_styles': [
'web/static/lib/jquery.ui/jquery-ui.css',
'web/static/lib/fontawesome/css/font-awesome.css',
'web/static/lib/select2/select2.css',
'web/static/lib/select2-bootstrap-css/select2-bootstrap.css',
- 'web/static/lib/tempusdominus/tempusdominus.scss',
'web/static/fonts/fonts.scss',
- 'web/static/src/scss/ui.scss',
- 'web/static/src/scss/ui_extra.scss',
- 'web/static/src/scss/navbar.scss',
- 'web/static/src/scss/mimetypes.scss',
- 'web/static/src/scss/modal.scss',
- 'web/static/src/scss/animation.scss',
- 'web/static/src/scss/rainbow.scss',
- 'web/static/src/scss/datepicker.scss',
- 'web/static/src/scss/daterangepicker.scss',
- 'web/static/src/scss/banner.scss',
- 'web/static/src/scss/colorpicker.scss',
- 'web/static/src/scss/popover.scss',
- 'web/static/src/scss/translation_dialog.scss',
- 'web/static/src/scss/keyboard.scss',
- 'web/static/src/scss/name_and_signature.scss',
- 'web/static/src/scss/web.zoomodoo.scss',
- 'web/static/src/scss/color_picker.scss',
- 'web/static/src/scss/fontawesome_overridden.scss',
+ 'web/static/src/legacy/scss/ui.scss',
+ 'web/static/src/legacy/scss/ui_extra.scss',
+ 'web/static/src/legacy/scss/navbar.scss',
+ 'web/static/src/legacy/scss/mimetypes.scss',
+ 'web/static/src/legacy/scss/modal.scss',
+ 'web/static/src/legacy/scss/animation.scss',
+ 'web/static/src/legacy/scss/datepicker.scss',
+ 'web/static/src/legacy/scss/daterangepicker.scss',
+ 'web/static/src/legacy/scss/banner.scss',
+ 'web/static/src/legacy/scss/colorpicker.scss',
+ 'web/static/src/legacy/scss/popover.scss',
+ 'web/static/src/legacy/scss/translation_dialog.scss',
+ 'web/static/src/legacy/scss/keyboard.scss',
+ 'web/static/src/legacy/scss/name_and_signature.scss',
+ 'web/static/src/legacy/scss/web.zoomodoo.scss',
+ 'web/static/src/legacy/scss/color_picker.scss',
+ 'web/static/src/legacy/scss/fontawesome_overridden.scss',
+ 'web/static/lib/tempusdominus/tempusdominus.scss',
],
'web._assets_common_scripts': [
'web/static/lib/underscore/underscore.js',
'web/static/lib/underscore.string/lib/underscore.string.js',
'web/static/lib/moment/moment.js',
'web/static/lib/owl/owl.js',
- 'web/static/src/js/component_extension.js',
+ 'web/static/src/legacy/js/component_extension.js',
'web/static/lib/jquery/jquery.js',
'web/static/lib/jquery.ui/jquery-ui.js',
'web/static/lib/jquery/jquery.browser.js',
@@ -383,60 +354,59 @@ This module provides the core of the Odoo Web Client.
'web/static/lib/clipboard/clipboard.js',
'web/static/lib/jSignature/jSignatureCustom.js',
'web/static/lib/qweb/qweb2.js',
- 'web/static/src/js/libs/autocomplete.js',
- 'web/static/src/js/libs/bootstrap.js',
- 'web/static/src/js/libs/content-disposition.js',
- 'web/static/src/js/libs/download.js',
- 'web/static/src/js/libs/fullcalendar.js',
- 'web/static/src/js/libs/jquery.js',
- 'web/static/src/js/libs/underscore.js',
- 'web/static/src/js/libs/pdfjs.js',
- 'web/static/src/js/libs/popper.js',
- 'web/static/src/js/libs/zoomodoo.js',
- 'web/static/src/js/libs/jSignatureCustom.js',
- 'web/static/src/js/chrome/keyboard_navigation_mixin.js',
- 'web/static/src/js/core/abstract_service.js',
- 'web/static/src/js/core/abstract_storage_service.js',
- 'web/static/src/js/core/ajax.js',
- 'web/static/src/js/core/browser_detection.js',
- 'web/static/src/js/core/bus.js',
- 'web/static/src/js/core/custom_hooks.js',
- 'web/static/src/js/core/class.js',
- 'web/static/src/js/core/collections.js',
- 'web/static/src/js/core/concurrency.js',
- 'web/static/src/js/core/dialog.js',
- 'web/static/src/js/core/owl_dialog.js',
- 'web/static/src/js/core/popover.js',
- 'web/static/src/js/core/dom.js',
- 'web/static/src/js/core/local_storage.js',
- 'web/static/src/js/core/mixins.js',
- 'web/static/src/js/core/qweb.js',
- 'web/static/src/js/core/ram_storage.js',
- 'web/static/src/js/core/registry.js',
- 'web/static/src/js/core/rpc.js',
- 'web/static/src/js/core/service_mixins.js',
- 'web/static/src/js/core/session.js',
- 'web/static/src/js/core/session_storage.js',
- 'web/static/src/js/core/time.js',
- 'web/static/src/js/core/translation.js',
- 'web/static/src/js/core/utils.js',
- 'web/static/src/js/core/widget.js',
- 'web/static/src/js/services/ajax_service.js',
- 'web/static/src/js/services/config.js',
- 'web/static/src/js/services/core.js',
- 'web/static/src/js/services/local_storage_service.js',
- 'web/static/src/js/services/notification_service.js',
- 'web/static/src/js/services/crash_manager.js',
- 'web/static/src/js/core/error_utils.js',
- 'web/static/src/js/services/session_storage_service.js',
- 'web/static/src/js/tools/debug_manager.js',
- 'web/static/src/js/common_env.js',
- 'web/static/src/js/widgets/name_and_signature.js',
- 'web/static/src/js/widgets/notification.js',
- 'web/static/src/js/widgets/rainbow_man.js',
- 'web/static/src/js/core/smooth_scroll_on_drag.js',
- 'web/static/src/js/widgets/colorpicker.js',
- 'web/static/src/js/widgets/translation_dialog.js',
+ 'web/static/src/legacy/js/libs/autocomplete.js',
+ 'web/static/src/legacy/js/libs/bootstrap.js',
+ 'web/static/src/legacy/js/libs/content-disposition.js',
+ 'web/static/src/legacy/js/libs/download.js',
+ 'web/static/src/legacy/js/libs/fullcalendar.js',
+ 'web/static/src/legacy/js/libs/jquery.js',
+ 'web/static/src/legacy/js/libs/underscore.js',
+ 'web/static/src/legacy/js/libs/pdfjs.js',
+ 'web/static/src/legacy/js/libs/popper.js',
+ 'web/static/src/legacy/js/libs/zoomodoo.js',
+ 'web/static/src/legacy/js/libs/jSignatureCustom.js',
+ 'web/static/src/legacy/js/core/abstract_service.js',
+ 'web/static/src/legacy/js/core/abstract_storage_service.js',
+ 'web/static/src/legacy/js/core/ajax.js',
+ 'web/static/src/legacy/js/core/browser_detection.js',
+ 'web/static/src/legacy/js/core/bus.js',
+ 'web/static/src/legacy/js/core/custom_hooks.js',
+ 'web/static/src/legacy/js/core/class.js',
+ 'web/static/src/legacy/js/core/collections.js',
+ 'web/static/src/legacy/js/core/concurrency.js',
+ 'web/static/src/legacy/js/core/dialog.js',
+ 'web/static/src/legacy/js/core/owl_dialog.js',
+ 'web/static/src/legacy/js/core/popover.js',
+ 'web/static/src/legacy/js/core/dom.js',
+ 'web/static/src/legacy/js/core/local_storage.js',
+ 'web/static/src/legacy/js/core/mixins.js',
+ 'web/static/src/legacy/js/core/qweb.js',
+ 'web/static/src/legacy/js/core/ram_storage.js',
+ 'web/static/src/legacy/js/core/registry.js',
+ 'web/static/src/legacy/js/core/rpc.js',
+ 'web/static/src/legacy/js/core/service_mixins.js',
+ 'web/static/src/legacy/js/core/session.js',
+ 'web/static/src/legacy/js/core/session_storage.js',
+ 'web/static/src/legacy/js/core/time.js',
+ 'web/static/src/legacy/js/core/translation.js',
+ 'web/static/src/legacy/js/core/utils.js',
+ 'web/static/src/legacy/js/core/widget.js',
+ 'web/static/src/legacy/js/services/ajax_service.js',
+ 'web/static/src/legacy/js/services/config.js',
+ 'web/static/src/legacy/js/services/core.js',
+ 'web/static/src/legacy/js/services/local_storage_service.js',
+ 'web/static/src/legacy/js/core/error_utils.js',
+ 'web/static/src/legacy/js/services/session_storage_service.js',
+ 'web/static/src/legacy/js/common_env.js',
+ 'web/static/src/legacy/js/widgets/name_and_signature.js',
+ 'web/static/src/legacy/js/core/smooth_scroll_on_drag.js',
+ 'web/static/src/legacy/js/widgets/colorpicker.js',
+ 'web/static/src/legacy/js/widgets/translation_dialog.js',
+ ],
+
+ # Used during the transition of the web architecture
+ 'web.frontend_legacy': [
+ 'web/static/src/legacy/frontend/**/*',
],
# ---------------------------------------------------------------------
@@ -446,13 +416,15 @@ This module provides the core of the Odoo Web Client.
'web.assets_tests': [
# No tours are defined in web, but the bundle "assets_tests" is
# first called in web.
- 'web/static/tests/helpers/test_utils_file.js'
+ 'web/static/tests/legacy/helpers/test_utils_file.js'
],
'web.tests_assets': [
'web/static/lib/daterangepicker/daterangepicker.css',
'web/static/lib/qunit/qunit-2.9.1.css',
'web/static/lib/qunit/qunit-2.9.1.js',
- 'web/static/tests/helpers/**/*',
+ 'web/static/tests/legacy/helpers/**/*',
+ ('remove', 'web/static/tests/legacy/helpers/test_utils_tests.js'),
+ 'web/static/tests/legacy/legacy_setup.js',
'web/static/lib/fullcalendar/core/main.css',
'web/static/lib/fullcalendar/daygrid/main.css',
@@ -473,56 +445,50 @@ This module provides the core of the Odoo Web Client.
'web/static/lib/nearest/jquery.nearest.js',
'web/static/lib/daterangepicker/daterangepicker.js',
'web/static/lib/stacktracejs/stacktrace.js',
- 'web/static/tests/main_tests.js',
+
+ # 'web/static/tests/legacy/main_tests.js',
+ 'web/static/tests/helpers/**/*.js',
+ 'web/static/tests/webclient/**/helpers.js',
+ 'web/static/tests/qunit.js',
+ 'web/static/tests/main.js',
+ 'web/static/tests/setup.js',
+
+ # These 2 lines below are taken from web.assets_frontend
+ # They're required for the web.frontend_legacy to work properly
+ # It is expected to add other lines coming from the web.assets_frontend
+ # if we need to add more and more legacy stuff that would require other scss or js.
+ ('include', 'web._assets_helpers'),
+ 'web/static/lib/bootstrap/scss/_variables.scss',
+
+ ('include', 'web.frontend_legacy'),
],
'web.qunit_suite_tests': [
'base/static/tests/base_settings_tests.js',
- 'web/static/tests/chrome/**/*.js',
- 'web/static/tests/components/action_menus_tests.js',
- 'web/static/tests/components/custom_checkbox_tests.js',
- 'web/static/tests/components/custom_file_input_tests.js',
- 'web/static/tests/components/datepicker_tests.js',
- 'web/static/tests/components/dropdown_menu_tests.js',
- 'web/static/tests/components/pager_tests.js',
- 'web/static/tests/control_panel/**/*.js',
+ 'web/static/tests/env_tests.js',
'web/static/tests/core/**/*.js',
- 'web/static/tests/fields/relational_fields/**/*.js',
- 'web/static/tests/fields/basic_fields_tests.js',
- 'web/static/tests/fields/field_utils_tests.js',
- 'web/static/tests/fields/relational_fields_tests.js',
- 'web/static/tests/fields/signature_tests.js',
- 'web/static/tests/fields/special_fields_tests.js',
- 'web/static/tests/fields/upgrade_fields_tests.js',
- 'web/static/tests/services/**/*.js',
- 'web/static/tests/tools/**/*.js',
- 'web/static/tests/views/abstract_controller_tests.js',
- 'web/static/tests/views/abstract_model_tests.js',
- 'web/static/tests/views/abstract_view_banner_tests.js',
- 'web/static/tests/views/abstract_view_tests.js',
- 'web/static/tests/views/basic_model_tests.js',
- 'web/static/tests/views/calendar_tests.js',
- 'web/static/tests/views/form_tests.js',
- 'web/static/tests/views/graph_tests.js',
- 'web/static/tests/views/kanban_model_tests.js',
- 'web/static/tests/views/kanban_tests.js',
- 'web/static/tests/views/list_tests.js',
- 'web/static/tests/views/pivot_tests.js',
- 'web/static/tests/views/qweb_tests.js',
- 'web/static/tests/views/sample_server_tests.js',
- 'web/static/tests/views/search_panel_tests.js',
- 'web/static/tests/views/view_dialogs_tests.js',
- 'web/static/tests/widgets/**/*.js',
- 'web/static/tests/report/**/*.js',
- 'web/static/tests/component_extension_tests.js',
- 'web/static/tests/mockserver_tests.js',
- 'web/static/tests/owl_compatibility_tests.js',
- 'web/static/tests/qweb_tests.js',
+ 'web/static/tests/fields/**/*.js',
+ 'web/static/tests/views/**/*.js',
+ 'web/static/tests/webclient/**/*.js',
+ ('remove', 'web/static/tests/webclient/**/helpers.js'),
+ 'web/static/tests/legacy/**/*.js',
+ ('remove', 'web/static/tests/legacy/**/*_mobile_tests.js'),
+ ('remove', 'web/static/tests/legacy/**/*_benchmarks.js'),
+ ('remove', 'web/static/tests/legacy/helpers/**/*.js'),
+ ('remove', 'web/static/tests/legacy/legacy_setup.js'),
+
+ ('include', 'web.frontend_legacy_tests'),
],
'web.qunit_mobile_suite_tests': [
'web/static/lib/jquery.touchSwipe/jquery.touchSwipe.js',
- 'web/static/tests/fields/basic_fields_mobile_tests.js',
- 'web/static/tests/fields/relational_fields_mobile_tests.js',
- 'web/static/tests/components/dropdown_menu_mobile_tests.js',
+
+ 'web/static/tests/legacy/fields/basic_fields_mobile_tests.js',
+ 'web/static/tests/legacy/fields/relational_fields_mobile_tests.js',
+ 'web/static/tests/legacy/components/dropdown_menu_mobile_tests.js',
+ ],
+
+ # Used during the transition of the web architecture
+ 'web.frontend_legacy_tests': [
+ 'web/static/tests/legacy/frontend/*.js',
],
},
'bootstrap': True, # load translations for login screen
diff --git a/addons/web/bower.json b/addons/web/bower.json
deleted file mode 100644
index cdd0ad6eba7..00000000000
--- a/addons/web/bower.json
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "name": "web",
- "version": "0.0.0",
- "ignore": [
- "**/.*",
- "node_modules",
- "bower_components",
- "test",
- "tests"
- ],
- "dependencies": {
- "jquery": "1.8.3",
- "underscore": "1.3.1",
- "underscore.string": "2.2.1",
- "qweb": "git@github.com:OpenERP/qweb.git#~1.0.0"
- }
-}
diff --git a/addons/web/controllers/main.py b/addons/web/controllers/main.py
index 48cf9640a43..1b8bd54e899 100644
--- a/addons/web/controllers/main.py
+++ b/addons/web/controllers/main.py
@@ -845,7 +845,7 @@ class Home(http.Controller):
:param unique: this parameters is not used, but mandatory: it is used by the HTTP stack to make a unique request
:return: the menus (including the images in Base64)
"""
- menus = request.env["ir.ui.menu"].load_menus(request.session.debug)
+ menus = request.env["ir.ui.menu"].load_web_menus(request.session.debug)
body = json.dumps(menus, default=ustr)
response = request.make_response(body, [
# this method must specify a content-type application/json instead of using the default text/html set because
diff --git a/addons/web/data/report_layout.xml b/addons/web/data/report_layout.xml
index 9200788277d..29140ead90b 100644
--- a/addons/web/data/report_layout.xml
+++ b/addons/web/data/report_layout.xml
@@ -38,7 +38,7 @@
text/scss
res.company.scss
binary
-
/web/static/src/scss/asset_styles_company_report.scss
+
/web/static/src/legacy/scss/asset_styles_company_report.scss
diff --git a/addons/web/models/__init__.py b/addons/web/models/__init__.py
index 79eef9803e3..7c9ec692afc 100644
--- a/addons/web/models/__init__.py
+++ b/addons/web/models/__init__.py
@@ -3,5 +3,6 @@
from . import ir_qweb
from . import ir_http
+from . import ir_ui_menu
from . import models
from . import base_document_layout
diff --git a/addons/web/models/ir_http.py b/addons/web/models/ir_http.py
index 1b4370d0fcd..92577de7d34 100644
--- a/addons/web/models/ir_http.py
+++ b/addons/web/models/ir_http.py
@@ -40,6 +40,7 @@ class Http(models.AbstractModel):
"db": request.session.db,
"server_version": version_info.get('server_version'),
"server_version_info": version_info.get('server_version_info'),
+ "support_url": "https://www.odoo.com/buy",
"name": user.name,
"username": user.login,
"partner_display_name": user.partner_id.display_name,
@@ -51,6 +52,7 @@ class Http(models.AbstractModel):
'profile_collectors': request.session.profile_collectors,
'profile_params': request.session.profile_params,
"max_file_upload_size": max_file_upload_size,
+ "home_action_id": user.action_id.id,
}
if self.env.user.has_group('base.group_user'):
# the following is only useful in the context of a webclient bootstrapping
@@ -63,7 +65,9 @@ class Http(models.AbstractModel):
qweb_checksum = HomeStaticTemplateHelpers.get_qweb_templates_checksum(debug=request.session.debug, bundle="web.assets_qweb")
lang = user_context.get("lang")
translation_hash = request.env['ir.translation'].get_web_translations_hash(mods, lang)
- menu_json_utf8 = json.dumps(request.env['ir.ui.menu'].load_menus(request.session.debug), default=ustr, sort_keys=True).encode()
+ menus = request.env['ir.ui.menu'].load_menus(request.session.debug)
+ ordered_menus = {str(k): v for k, v in menus.items()}
+ menu_json_utf8 = json.dumps(ordered_menus, default=ustr, sort_keys=True).encode()
cache_hashes = {
"load_menus": hashlib.sha512(menu_json_utf8).hexdigest()[:64], # sha512/256
"qweb": qweb_checksum,
diff --git a/addons/web/models/ir_ui_menu.py b/addons/web/models/ir_ui_menu.py
new file mode 100644
index 00000000000..be5ae1e705c
--- /dev/null
+++ b/addons/web/models/ir_ui_menu.py
@@ -0,0 +1,61 @@
+# -*- coding: utf-8 -*-
+# Part of Odoo. See LICENSE file for full copyright and licensing details.
+
+from odoo import models
+
+
+class IrUiMenu(models.Model):
+ _inherit = "ir.ui.menu"
+
+ def load_web_menus(self, debug):
+ """ Loads all menu items (all applications and their sub-menus) and
+ processes them to be used by the webclient. Mainly, it associates with
+ each application (top level menu) the action of its first child menu
+ that is associated with an action (recursively), i.e. with the action
+ to execute when the opening the app.
+
+ :return: the menus (including the images in Base64)
+ """
+ menus = self.load_menus(debug)
+
+ web_menus = {}
+ for menu in menus.values():
+ if not menu['id']:
+ # special root menu case
+ web_menus['root'] = {
+ "id": 'root',
+ "name": menu['name'],
+ "children": menu['children'],
+ "appID": False,
+ "xmlid": "",
+ "actionID": False,
+ "actionModel": False,
+ "webIcon": None,
+ "webIconData": None,
+ }
+ else:
+ action = menu['action']
+
+ if menu['id'] == menu['app_id']:
+ # if it's an app take action of first (sub)child having one defined
+ child = menu
+ while child and not action:
+ action = child['action']
+ child = menus[child['children'][0]] if child['children'] else False
+
+ action_model, action_id = action.split(',') if action else (False, False)
+ action_id = int(action_id) if action_id else False
+
+ web_menus[menu['id']] = {
+ "id": menu['id'],
+ "name": menu['name'],
+ "children": menu['children'],
+ "appID": menu['app_id'],
+ "xmlid": menu['xmlid'],
+ "actionID": action_id,
+ "actionModel": action_model,
+ "webIcon": menu['web_icon'],
+ "webIconData": menu['web_icon_data'],
+ }
+
+ return web_menus
diff --git a/addons/web/package.json b/addons/web/package.json
deleted file mode 100644
index cce1f2ad28f..00000000000
--- a/addons/web/package.json
+++ /dev/null
@@ -1,8 +0,0 @@
-{
- "devDependencies": {
- "grunt": "*",
- "grunt-contrib-jshint": "*",
- "grunt-contrib-sass": "~0.4.1",
- "grunt-contrib-watch": "~0.5.1"
- }
-}
diff --git a/addons/web/static/lib/luxon/luxon.js b/addons/web/static/lib/luxon/luxon.js
new file mode 100644
index 00000000000..e7992a92781
--- /dev/null
+++ b/addons/web/static/lib/luxon/luxon.js
@@ -0,0 +1,8296 @@
+var luxon = (function (exports) {
+ 'use strict';
+
+ function _defineProperties(target, props) {
+ for (var i = 0; i < props.length; i++) {
+ var descriptor = props[i];
+ descriptor.enumerable = descriptor.enumerable || false;
+ descriptor.configurable = true;
+ if ("value" in descriptor) descriptor.writable = true;
+ Object.defineProperty(target, descriptor.key, descriptor);
+ }
+ }
+
+ function _createClass(Constructor, protoProps, staticProps) {
+ if (protoProps) _defineProperties(Constructor.prototype, protoProps);
+ if (staticProps) _defineProperties(Constructor, staticProps);
+ return Constructor;
+ }
+
+ function _inheritsLoose(subClass, superClass) {
+ subClass.prototype = Object.create(superClass.prototype);
+ subClass.prototype.constructor = subClass;
+ subClass.__proto__ = superClass;
+ }
+
+ function _getPrototypeOf(o) {
+ _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
+ return o.__proto__ || Object.getPrototypeOf(o);
+ };
+ return _getPrototypeOf(o);
+ }
+
+ function _setPrototypeOf(o, p) {
+ _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
+ o.__proto__ = p;
+ return o;
+ };
+
+ return _setPrototypeOf(o, p);
+ }
+
+ function _isNativeReflectConstruct() {
+ if (typeof Reflect === "undefined" || !Reflect.construct) return false;
+ if (Reflect.construct.sham) return false;
+ if (typeof Proxy === "function") return true;
+
+ try {
+ Date.prototype.toString.call(Reflect.construct(Date, [], function () {}));
+ return true;
+ } catch (e) {
+ return false;
+ }
+ }
+
+ function _construct(Parent, args, Class) {
+ if (_isNativeReflectConstruct()) {
+ _construct = Reflect.construct;
+ } else {
+ _construct = function _construct(Parent, args, Class) {
+ var a = [null];
+ a.push.apply(a, args);
+ var Constructor = Function.bind.apply(Parent, a);
+ var instance = new Constructor();
+ if (Class) _setPrototypeOf(instance, Class.prototype);
+ return instance;
+ };
+ }
+
+ return _construct.apply(null, arguments);
+ }
+
+ function _isNativeFunction(fn) {
+ return Function.toString.call(fn).indexOf("[native code]") !== -1;
+ }
+
+ function _wrapNativeSuper(Class) {
+ var _cache = typeof Map === "function" ? new Map() : undefined;
+
+ _wrapNativeSuper = function _wrapNativeSuper(Class) {
+ if (Class === null || !_isNativeFunction(Class)) return Class;
+
+ if (typeof Class !== "function") {
+ throw new TypeError("Super expression must either be null or a function");
+ }
+
+ if (typeof _cache !== "undefined") {
+ if (_cache.has(Class)) return _cache.get(Class);
+
+ _cache.set(Class, Wrapper);
+ }
+
+ function Wrapper() {
+ return _construct(Class, arguments, _getPrototypeOf(this).constructor);
+ }
+
+ Wrapper.prototype = Object.create(Class.prototype, {
+ constructor: {
+ value: Wrapper,
+ enumerable: false,
+ writable: true,
+ configurable: true
+ }
+ });
+ return _setPrototypeOf(Wrapper, Class);
+ };
+
+ return _wrapNativeSuper(Class);
+ }
+
+ function _objectWithoutPropertiesLoose(source, excluded) {
+ if (source == null) return {};
+ var target = {};
+ var sourceKeys = Object.keys(source);
+ var key, i;
+
+ for (i = 0; i < sourceKeys.length; i++) {
+ key = sourceKeys[i];
+ if (excluded.indexOf(key) >= 0) continue;
+ target[key] = source[key];
+ }
+
+ return target;
+ }
+
+ function _unsupportedIterableToArray(o, minLen) {
+ if (!o) return;
+ if (typeof o === "string") return _arrayLikeToArray(o, minLen);
+ var n = Object.prototype.toString.call(o).slice(8, -1);
+ if (n === "Object" && o.constructor) n = o.constructor.name;
+ if (n === "Map" || n === "Set") return Array.from(n);
+ if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
+ }
+
+ function _arrayLikeToArray(arr, len) {
+ if (len == null || len > arr.length) len = arr.length;
+
+ for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
+
+ return arr2;
+ }
+
+ function _createForOfIteratorHelperLoose(o) {
+ var i = 0;
+
+ if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) {
+ if (Array.isArray(o) || (o = _unsupportedIterableToArray(o))) return function () {
+ if (i >= o.length) return {
+ done: true
+ };
+ return {
+ done: false,
+ value: o[i++]
+ };
+ };
+ throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
+ }
+
+ i = o[Symbol.iterator]();
+ return i.next.bind(i);
+ }
+
+ // these aren't really private, but nor are they really useful to document
+
+ /**
+ * @private
+ */
+ var LuxonError = /*#__PURE__*/function (_Error) {
+ _inheritsLoose(LuxonError, _Error);
+
+ function LuxonError() {
+ return _Error.apply(this, arguments) || this;
+ }
+
+ return LuxonError;
+ }( /*#__PURE__*/_wrapNativeSuper(Error));
+ /**
+ * @private
+ */
+
+
+ var InvalidDateTimeError = /*#__PURE__*/function (_LuxonError) {
+ _inheritsLoose(InvalidDateTimeError, _LuxonError);
+
+ function InvalidDateTimeError(reason) {
+ return _LuxonError.call(this, "Invalid DateTime: " + reason.toMessage()) || this;
+ }
+
+ return InvalidDateTimeError;
+ }(LuxonError);
+ /**
+ * @private
+ */
+
+ var InvalidIntervalError = /*#__PURE__*/function (_LuxonError2) {
+ _inheritsLoose(InvalidIntervalError, _LuxonError2);
+
+ function InvalidIntervalError(reason) {
+ return _LuxonError2.call(this, "Invalid Interval: " + reason.toMessage()) || this;
+ }
+
+ return InvalidIntervalError;
+ }(LuxonError);
+ /**
+ * @private
+ */
+
+ var InvalidDurationError = /*#__PURE__*/function (_LuxonError3) {
+ _inheritsLoose(InvalidDurationError, _LuxonError3);
+
+ function InvalidDurationError(reason) {
+ return _LuxonError3.call(this, "Invalid Duration: " + reason.toMessage()) || this;
+ }
+
+ return InvalidDurationError;
+ }(LuxonError);
+ /**
+ * @private
+ */
+
+ var ConflictingSpecificationError = /*#__PURE__*/function (_LuxonError4) {
+ _inheritsLoose(ConflictingSpecificationError, _LuxonError4);
+
+ function ConflictingSpecificationError() {
+ return _LuxonError4.apply(this, arguments) || this;
+ }
+
+ return ConflictingSpecificationError;
+ }(LuxonError);
+ /**
+ * @private
+ */
+
+ var InvalidUnitError = /*#__PURE__*/function (_LuxonError5) {
+ _inheritsLoose(InvalidUnitError, _LuxonError5);
+
+ function InvalidUnitError(unit) {
+ return _LuxonError5.call(this, "Invalid unit " + unit) || this;
+ }
+
+ return InvalidUnitError;
+ }(LuxonError);
+ /**
+ * @private
+ */
+
+ var InvalidArgumentError = /*#__PURE__*/function (_LuxonError6) {
+ _inheritsLoose(InvalidArgumentError, _LuxonError6);
+
+ function InvalidArgumentError() {
+ return _LuxonError6.apply(this, arguments) || this;
+ }
+
+ return InvalidArgumentError;
+ }(LuxonError);
+ /**
+ * @private
+ */
+
+ var ZoneIsAbstractError = /*#__PURE__*/function (_LuxonError7) {
+ _inheritsLoose(ZoneIsAbstractError, _LuxonError7);
+
+ function ZoneIsAbstractError() {
+ return _LuxonError7.call(this, "Zone is an abstract class") || this;
+ }
+
+ return ZoneIsAbstractError;
+ }(LuxonError);
+
+ /**
+ * @private
+ */
+ var n = "numeric",
+ s = "short",
+ l = "long";
+ var DATE_SHORT = {
+ year: n,
+ month: n,
+ day: n
+ };
+ var DATE_MED = {
+ year: n,
+ month: s,
+ day: n
+ };
+ var DATE_MED_WITH_WEEKDAY = {
+ year: n,
+ month: s,
+ day: n,
+ weekday: s
+ };
+ var DATE_FULL = {
+ year: n,
+ month: l,
+ day: n
+ };
+ var DATE_HUGE = {
+ year: n,
+ month: l,
+ day: n,
+ weekday: l
+ };
+ var TIME_SIMPLE = {
+ hour: n,
+ minute: n
+ };
+ var TIME_WITH_SECONDS = {
+ hour: n,
+ minute: n,
+ second: n
+ };
+ var TIME_WITH_SHORT_OFFSET = {
+ hour: n,
+ minute: n,
+ second: n,
+ timeZoneName: s
+ };
+ var TIME_WITH_LONG_OFFSET = {
+ hour: n,
+ minute: n,
+ second: n,
+ timeZoneName: l
+ };
+ var TIME_24_SIMPLE = {
+ hour: n,
+ minute: n,
+ hour12: false
+ };
+ /**
+ * {@link toLocaleString}; format like '09:30:23', always 24-hour.
+ */
+
+ var TIME_24_WITH_SECONDS = {
+ hour: n,
+ minute: n,
+ second: n,
+ hour12: false
+ };
+ /**
+ * {@link toLocaleString}; format like '09:30:23 EDT', always 24-hour.
+ */
+
+ var TIME_24_WITH_SHORT_OFFSET = {
+ hour: n,
+ minute: n,
+ second: n,
+ hour12: false,
+ timeZoneName: s
+ };
+ /**
+ * {@link toLocaleString}; format like '09:30:23 Eastern Daylight Time', always 24-hour.
+ */
+
+ var TIME_24_WITH_LONG_OFFSET = {
+ hour: n,
+ minute: n,
+ second: n,
+ hour12: false,
+ timeZoneName: l
+ };
+ /**
+ * {@link toLocaleString}; format like '10/14/1983, 9:30 AM'. Only 12-hour if the locale is.
+ */
+
+ var DATETIME_SHORT = {
+ year: n,
+ month: n,
+ day: n,
+ hour: n,
+ minute: n
+ };
+ /**
+ * {@link toLocaleString}; format like '10/14/1983, 9:30:33 AM'. Only 12-hour if the locale is.
+ */
+
+ var DATETIME_SHORT_WITH_SECONDS = {
+ year: n,
+ month: n,
+ day: n,
+ hour: n,
+ minute: n,
+ second: n
+ };
+ var DATETIME_MED = {
+ year: n,
+ month: s,
+ day: n,
+ hour: n,
+ minute: n
+ };
+ var DATETIME_MED_WITH_SECONDS = {
+ year: n,
+ month: s,
+ day: n,
+ hour: n,
+ minute: n,
+ second: n
+ };
+ var DATETIME_MED_WITH_WEEKDAY = {
+ year: n,
+ month: s,
+ day: n,
+ weekday: s,
+ hour: n,
+ minute: n
+ };
+ var DATETIME_FULL = {
+ year: n,
+ month: l,
+ day: n,
+ hour: n,
+ minute: n,
+ timeZoneName: s
+ };
+ var DATETIME_FULL_WITH_SECONDS = {
+ year: n,
+ month: l,
+ day: n,
+ hour: n,
+ minute: n,
+ second: n,
+ timeZoneName: s
+ };
+ var DATETIME_HUGE = {
+ year: n,
+ month: l,
+ day: n,
+ weekday: l,
+ hour: n,
+ minute: n,
+ timeZoneName: l
+ };
+ var DATETIME_HUGE_WITH_SECONDS = {
+ year: n,
+ month: l,
+ day: n,
+ weekday: l,
+ hour: n,
+ minute: n,
+ second: n,
+ timeZoneName: l
+ };
+
+ /*
+ This is just a junk drawer, containing anything used across multiple classes.
+ Because Luxon is small(ish), this should stay small and we won't worry about splitting
+ it up into, say, parsingUtil.js and basicUtil.js and so on. But they are divided up by feature area.
+ */
+ /**
+ * @private
+ */
+ // TYPES
+
+ function isUndefined(o) {
+ return typeof o === "undefined";
+ }
+ function isNumber(o) {
+ return typeof o === "number";
+ }
+ function isInteger(o) {
+ return typeof o === "number" && o % 1 === 0;
+ }
+ function isString(o) {
+ return typeof o === "string";
+ }
+ function isDate(o) {
+ return Object.prototype.toString.call(o) === "[object Date]";
+ } // CAPABILITIES
+
+ function hasIntl() {
+ try {
+ return typeof Intl !== "undefined" && Intl.DateTimeFormat;
+ } catch (e) {
+ return false;
+ }
+ }
+ function hasFormatToParts() {
+ return !isUndefined(Intl.DateTimeFormat.prototype.formatToParts);
+ }
+ function hasRelative() {
+ try {
+ return typeof Intl !== "undefined" && !!Intl.RelativeTimeFormat;
+ } catch (e) {
+ return false;
+ }
+ } // OBJECTS AND ARRAYS
+
+ function maybeArray(thing) {
+ return Array.isArray(thing) ? thing : [thing];
+ }
+ function bestBy(arr, by, compare) {
+ if (arr.length === 0) {
+ return undefined;
+ }
+
+ return arr.reduce(function (best, next) {
+ var pair = [by(next), next];
+
+ if (!best) {
+ return pair;
+ } else if (compare(best[0], pair[0]) === best[0]) {
+ return best;
+ } else {
+ return pair;
+ }
+ }, null)[1];
+ }
+ function pick(obj, keys) {
+ return keys.reduce(function (a, k) {
+ a[k] = obj[k];
+ return a;
+ }, {});
+ }
+ function hasOwnProperty(obj, prop) {
+ return Object.prototype.hasOwnProperty.call(obj, prop);
+ } // NUMBERS AND STRINGS
+
+ function integerBetween(thing, bottom, top) {
+ return isInteger(thing) && thing >= bottom && thing <= top;
+ } // x % n but takes the sign of n instead of x
+
+ function floorMod(x, n) {
+ return x - n * Math.floor(x / n);
+ }
+ function padStart(input, n) {
+ if (n === void 0) {
+ n = 2;
+ }
+
+ if (input.toString().length < n) {
+ return ("0".repeat(n) + input).slice(-n);
+ } else {
+ return input.toString();
+ }
+ }
+ function parseInteger(string) {
+ if (isUndefined(string) || string === null || string === "") {
+ return undefined;
+ } else {
+ return parseInt(string, 10);
+ }
+ }
+ function parseMillis(fraction) {
+ // Return undefined (instead of 0) in these cases, where fraction is not set
+ if (isUndefined(fraction) || fraction === null || fraction === "") {
+ return undefined;
+ } else {
+ var f = parseFloat("0." + fraction) * 1000;
+ return Math.floor(f);
+ }
+ }
+ function roundTo(number, digits, towardZero) {
+ if (towardZero === void 0) {
+ towardZero = false;
+ }
+
+ var factor = Math.pow(10, digits),
+ rounder = towardZero ? Math.trunc : Math.round;
+ return rounder(number * factor) / factor;
+ } // DATE BASICS
+
+ function isLeapYear(year) {
+ return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
+ }
+ function daysInYear(year) {
+ return isLeapYear(year) ? 366 : 365;
+ }
+ function daysInMonth(year, month) {
+ var modMonth = floorMod(month - 1, 12) + 1,
+ modYear = year + (month - modMonth) / 12;
+
+ if (modMonth === 2) {
+ return isLeapYear(modYear) ? 29 : 28;
+ } else {
+ return [31, null, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][modMonth - 1];
+ }
+ } // covert a calendar object to a local timestamp (epoch, but with the offset baked in)
+
+ function objToLocalTS(obj) {
+ var d = Date.UTC(obj.year, obj.month - 1, obj.day, obj.hour, obj.minute, obj.second, obj.millisecond); // for legacy reasons, years between 0 and 99 are interpreted as 19XX; revert that
+
+ if (obj.year < 100 && obj.year >= 0) {
+ d = new Date(d);
+ d.setUTCFullYear(d.getUTCFullYear() - 1900);
+ }
+
+ return +d;
+ }
+ function weeksInWeekYear(weekYear) {
+ var p1 = (weekYear + Math.floor(weekYear / 4) - Math.floor(weekYear / 100) + Math.floor(weekYear / 400)) % 7,
+ last = weekYear - 1,
+ p2 = (last + Math.floor(last / 4) - Math.floor(last / 100) + Math.floor(last / 400)) % 7;
+ return p1 === 4 || p2 === 3 ? 53 : 52;
+ }
+ function untruncateYear(year) {
+ if (year > 99) {
+ return year;
+ } else return year > 60 ? 1900 + year : 2000 + year;
+ } // PARSING
+
+ function parseZoneInfo(ts, offsetFormat, locale, timeZone) {
+ if (timeZone === void 0) {
+ timeZone = null;
+ }
+
+ var date = new Date(ts),
+ intlOpts = {
+ hour12: false,
+ year: "numeric",
+ month: "2-digit",
+ day: "2-digit",
+ hour: "2-digit",
+ minute: "2-digit"
+ };
+
+ if (timeZone) {
+ intlOpts.timeZone = timeZone;
+ }
+
+ var modified = Object.assign({
+ timeZoneName: offsetFormat
+ }, intlOpts),
+ intl = hasIntl();
+
+ if (intl && hasFormatToParts()) {
+ var parsed = new Intl.DateTimeFormat(locale, modified).formatToParts(date).find(function (m) {
+ return m.type.toLowerCase() === "timezonename";
+ });
+ return parsed ? parsed.value : null;
+ } else if (intl) {
+ // this probably doesn't work for all locales
+ var without = new Intl.DateTimeFormat(locale, intlOpts).format(date),
+ included = new Intl.DateTimeFormat(locale, modified).format(date),
+ diffed = included.substring(without.length),
+ trimmed = diffed.replace(/^[, \u200e]+/, "");
+ return trimmed;
+ } else {
+ return null;
+ }
+ } // signedOffset('-5', '30') -> -330
+
+ function signedOffset(offHourStr, offMinuteStr) {
+ var offHour = parseInt(offHourStr, 10); // don't || this because we want to preserve -0
+
+ if (Number.isNaN(offHour)) {
+ offHour = 0;
+ }
+
+ var offMin = parseInt(offMinuteStr, 10) || 0,
+ offMinSigned = offHour < 0 || Object.is(offHour, -0) ? -offMin : offMin;
+ return offHour * 60 + offMinSigned;
+ } // COERCION
+
+ function asNumber(value) {
+ var numericValue = Number(value);
+ if (typeof value === "boolean" || value === "" || Number.isNaN(numericValue)) throw new InvalidArgumentError("Invalid unit value " + value);
+ return numericValue;
+ }
+ function normalizeObject(obj, normalizer, nonUnitKeys) {
+ var normalized = {};
+
+ for (var u in obj) {
+ if (hasOwnProperty(obj, u)) {
+ if (nonUnitKeys.indexOf(u) >= 0) continue;
+ var v = obj[u];
+ if (v === undefined || v === null) continue;
+ normalized[normalizer(u)] = asNumber(v);
+ }
+ }
+
+ return normalized;
+ }
+ function formatOffset(offset, format) {
+ var hours = Math.trunc(Math.abs(offset / 60)),
+ minutes = Math.trunc(Math.abs(offset % 60)),
+ sign = offset >= 0 ? "+" : "-";
+
+ switch (format) {
+ case "short":
+ return "" + sign + padStart(hours, 2) + ":" + padStart(minutes, 2);
+
+ case "narrow":
+ return "" + sign + hours + (minutes > 0 ? ":" + minutes : "");
+
+ case "techie":
+ return "" + sign + padStart(hours, 2) + padStart(minutes, 2);
+
+ default:
+ throw new RangeError("Value format " + format + " is out of range for property format");
+ }
+ }
+ function timeObject(obj) {
+ return pick(obj, ["hour", "minute", "second", "millisecond"]);
+ }
+ var ianaRegex = /[A-Za-z_+-]{1,256}(:?\/[A-Za-z_+-]{1,256}(\/[A-Za-z_+-]{1,256})?)?/;
+
+ function stringify(obj) {
+ return JSON.stringify(obj, Object.keys(obj).sort());
+ }
+ /**
+ * @private
+ */
+
+
+ var monthsLong = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
+ var monthsShort = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
+ var monthsNarrow = ["J", "F", "M", "A", "M", "J", "J", "A", "S", "O", "N", "D"];
+ function months(length) {
+ switch (length) {
+ case "narrow":
+ return monthsNarrow;
+
+ case "short":
+ return monthsShort;
+
+ case "long":
+ return monthsLong;
+
+ case "numeric":
+ return ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"];
+
+ case "2-digit":
+ return ["01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"];
+
+ default:
+ return null;
+ }
+ }
+ var weekdaysLong = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"];
+ var weekdaysShort = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
+ var weekdaysNarrow = ["M", "T", "W", "T", "F", "S", "S"];
+ function weekdays(length) {
+ switch (length) {
+ case "narrow":
+ return weekdaysNarrow;
+
+ case "short":
+ return weekdaysShort;
+
+ case "long":
+ return weekdaysLong;
+
+ case "numeric":
+ return ["1", "2", "3", "4", "5", "6", "7"];
+
+ default:
+ return null;
+ }
+ }
+ var meridiems = ["AM", "PM"];
+ var erasLong = ["Before Christ", "Anno Domini"];
+ var erasShort = ["BC", "AD"];
+ var erasNarrow = ["B", "A"];
+ function eras(length) {
+ switch (length) {
+ case "narrow":
+ return erasNarrow;
+
+ case "short":
+ return erasShort;
+
+ case "long":
+ return erasLong;
+
+ default:
+ return null;
+ }
+ }
+ function meridiemForDateTime(dt) {
+ return meridiems[dt.hour < 12 ? 0 : 1];
+ }
+ function weekdayForDateTime(dt, length) {
+ return weekdays(length)[dt.weekday - 1];
+ }
+ function monthForDateTime(dt, length) {
+ return months(length)[dt.month - 1];
+ }
+ function eraForDateTime(dt, length) {
+ return eras(length)[dt.year < 0 ? 0 : 1];
+ }
+ function formatRelativeTime(unit, count, numeric, narrow) {
+ if (numeric === void 0) {
+ numeric = "always";
+ }
+
+ if (narrow === void 0) {
+ narrow = false;
+ }
+
+ var units = {
+ years: ["year", "yr."],
+ quarters: ["quarter", "qtr."],
+ months: ["month", "mo."],
+ weeks: ["week", "wk."],
+ days: ["day", "day", "days"],
+ hours: ["hour", "hr."],
+ minutes: ["minute", "min."],
+ seconds: ["second", "sec."]
+ };
+ var lastable = ["hours", "minutes", "seconds"].indexOf(unit) === -1;
+
+ if (numeric === "auto" && lastable) {
+ var isDay = unit === "days";
+
+ switch (count) {
+ case 1:
+ return isDay ? "tomorrow" : "next " + units[unit][0];
+
+ case -1:
+ return isDay ? "yesterday" : "last " + units[unit][0];
+
+ case 0:
+ return isDay ? "today" : "this " + units[unit][0];
+
+ }
+ }
+
+ var isInPast = Object.is(count, -0) || count < 0,
+ fmtValue = Math.abs(count),
+ singular = fmtValue === 1,
+ lilUnits = units[unit],
+ fmtUnit = narrow ? singular ? lilUnits[1] : lilUnits[2] || lilUnits[1] : singular ? units[unit][0] : unit;
+ return isInPast ? fmtValue + " " + fmtUnit + " ago" : "in " + fmtValue + " " + fmtUnit;
+ }
+ function formatString(knownFormat) {
+ // these all have the offsets removed because we don't have access to them
+ // without all the intl stuff this is backfilling
+ var filtered = pick(knownFormat, ["weekday", "era", "year", "month", "day", "hour", "minute", "second", "timeZoneName", "hour12"]),
+ key = stringify(filtered),
+ dateTimeHuge = "EEEE, LLLL d, yyyy, h:mm a";
+
+ switch (key) {
+ case stringify(DATE_SHORT):
+ return "M/d/yyyy";
+
+ case stringify(DATE_MED):
+ return "LLL d, yyyy";
+
+ case stringify(DATE_MED_WITH_WEEKDAY):
+ return "EEE, LLL d, yyyy";
+
+ case stringify(DATE_FULL):
+ return "LLLL d, yyyy";
+
+ case stringify(DATE_HUGE):
+ return "EEEE, LLLL d, yyyy";
+
+ case stringify(TIME_SIMPLE):
+ return "h:mm a";
+
+ case stringify(TIME_WITH_SECONDS):
+ return "h:mm:ss a";
+
+ case stringify(TIME_WITH_SHORT_OFFSET):
+ return "h:mm a";
+
+ case stringify(TIME_WITH_LONG_OFFSET):
+ return "h:mm a";
+
+ case stringify(TIME_24_SIMPLE):
+ return "HH:mm";
+
+ case stringify(TIME_24_WITH_SECONDS):
+ return "HH:mm:ss";
+
+ case stringify(TIME_24_WITH_SHORT_OFFSET):
+ return "HH:mm";
+
+ case stringify(TIME_24_WITH_LONG_OFFSET):
+ return "HH:mm";
+
+ case stringify(DATETIME_SHORT):
+ return "M/d/yyyy, h:mm a";
+
+ case stringify(DATETIME_MED):
+ return "LLL d, yyyy, h:mm a";
+
+ case stringify(DATETIME_FULL):
+ return "LLLL d, yyyy, h:mm a";
+
+ case stringify(DATETIME_HUGE):
+ return dateTimeHuge;
+
+ case stringify(DATETIME_SHORT_WITH_SECONDS):
+ return "M/d/yyyy, h:mm:ss a";
+
+ case stringify(DATETIME_MED_WITH_SECONDS):
+ return "LLL d, yyyy, h:mm:ss a";
+
+ case stringify(DATETIME_MED_WITH_WEEKDAY):
+ return "EEE, d LLL yyyy, h:mm a";
+
+ case stringify(DATETIME_FULL_WITH_SECONDS):
+ return "LLLL d, yyyy, h:mm:ss a";
+
+ case stringify(DATETIME_HUGE_WITH_SECONDS):
+ return "EEEE, LLLL d, yyyy, h:mm:ss a";
+
+ default:
+ return dateTimeHuge;
+ }
+ }
+
+ function stringifyTokens(splits, tokenToString) {
+ var s = "";
+
+ for (var _iterator = _createForOfIteratorHelperLoose(splits), _step; !(_step = _iterator()).done;) {
+ var token = _step.value;
+
+ if (token.literal) {
+ s += token.val;
+ } else {
+ s += tokenToString(token.val);
+ }
+ }
+
+ return s;
+ }
+
+ var _macroTokenToFormatOpts = {
+ D: DATE_SHORT,
+ DD: DATE_MED,
+ DDD: DATE_FULL,
+ DDDD: DATE_HUGE,
+ t: TIME_SIMPLE,
+ tt: TIME_WITH_SECONDS,
+ ttt: TIME_WITH_SHORT_OFFSET,
+ tttt: TIME_WITH_LONG_OFFSET,
+ T: TIME_24_SIMPLE,
+ TT: TIME_24_WITH_SECONDS,
+ TTT: TIME_24_WITH_SHORT_OFFSET,
+ TTTT: TIME_24_WITH_LONG_OFFSET,
+ f: DATETIME_SHORT,
+ ff: DATETIME_MED,
+ fff: DATETIME_FULL,
+ ffff: DATETIME_HUGE,
+ F: DATETIME_SHORT_WITH_SECONDS,
+ FF: DATETIME_MED_WITH_SECONDS,
+ FFF: DATETIME_FULL_WITH_SECONDS,
+ FFFF: DATETIME_HUGE_WITH_SECONDS
+ };
+ /**
+ * @private
+ */
+
+ var Formatter = /*#__PURE__*/function () {
+ Formatter.create = function create(locale, opts) {
+ if (opts === void 0) {
+ opts = {};
+ }
+
+ return new Formatter(locale, opts);
+ };
+
+ Formatter.parseFormat = function parseFormat(fmt) {
+ var current = null,
+ currentFull = "",
+ bracketed = false;
+ var splits = [];
+
+ for (var i = 0; i < fmt.length; i++) {
+ var c = fmt.charAt(i);
+
+ if (c === "'") {
+ if (currentFull.length > 0) {
+ splits.push({
+ literal: bracketed,
+ val: currentFull
+ });
+ }
+
+ current = null;
+ currentFull = "";
+ bracketed = !bracketed;
+ } else if (bracketed) {
+ currentFull += c;
+ } else if (c === current) {
+ currentFull += c;
+ } else {
+ if (currentFull.length > 0) {
+ splits.push({
+ literal: false,
+ val: currentFull
+ });
+ }
+
+ currentFull = c;
+ current = c;
+ }
+ }
+
+ if (currentFull.length > 0) {
+ splits.push({
+ literal: bracketed,
+ val: currentFull
+ });
+ }
+
+ return splits;
+ };
+
+ Formatter.macroTokenToFormatOpts = function macroTokenToFormatOpts(token) {
+ return _macroTokenToFormatOpts[token];
+ };
+
+ function Formatter(locale, formatOpts) {
+ this.opts = formatOpts;
+ this.loc = locale;
+ this.systemLoc = null;
+ }
+
+ var _proto = Formatter.prototype;
+
+ _proto.formatWithSystemDefault = function formatWithSystemDefault(dt, opts) {
+ if (this.systemLoc === null) {
+ this.systemLoc = this.loc.redefaultToSystem();
+ }
+
+ var df = this.systemLoc.dtFormatter(dt, Object.assign({}, this.opts, opts));
+ return df.format();
+ };
+
+ _proto.formatDateTime = function formatDateTime(dt, opts) {
+ if (opts === void 0) {
+ opts = {};
+ }
+
+ var df = this.loc.dtFormatter(dt, Object.assign({}, this.opts, opts));
+ return df.format();
+ };
+
+ _proto.formatDateTimeParts = function formatDateTimeParts(dt, opts) {
+ if (opts === void 0) {
+ opts = {};
+ }
+
+ var df = this.loc.dtFormatter(dt, Object.assign({}, this.opts, opts));
+ return df.formatToParts();
+ };
+
+ _proto.resolvedOptions = function resolvedOptions(dt, opts) {
+ if (opts === void 0) {
+ opts = {};
+ }
+
+ var df = this.loc.dtFormatter(dt, Object.assign({}, this.opts, opts));
+ return df.resolvedOptions();
+ };
+
+ _proto.num = function num(n, p) {
+ if (p === void 0) {
+ p = 0;
+ }
+
+ // we get some perf out of doing this here, annoyingly
+ if (this.opts.forceSimple) {
+ return padStart(n, p);
+ }
+
+ var opts = Object.assign({}, this.opts);
+
+ if (p > 0) {
+ opts.padTo = p;
+ }
+
+ return this.loc.numberFormatter(opts).format(n);
+ };
+
+ _proto.formatDateTimeFromString = function formatDateTimeFromString(dt, fmt) {
+ var _this = this;
+
+ var knownEnglish = this.loc.listingMode() === "en",
+ useDateTimeFormatter = this.loc.outputCalendar && this.loc.outputCalendar !== "gregory" && hasFormatToParts(),
+ string = function string(opts, extract) {
+ return _this.loc.extract(dt, opts, extract);
+ },
+ formatOffset = function formatOffset(opts) {
+ if (dt.isOffsetFixed && dt.offset === 0 && opts.allowZ) {
+ return "Z";
+ }
+
+ return dt.isValid ? dt.zone.formatOffset(dt.ts, opts.format) : "";
+ },
+ meridiem = function meridiem() {
+ return knownEnglish ? meridiemForDateTime(dt) : string({
+ hour: "numeric",
+ hour12: true
+ }, "dayperiod");
+ },
+ month = function month(length, standalone) {
+ return knownEnglish ? monthForDateTime(dt, length) : string(standalone ? {
+ month: length
+ } : {
+ month: length,
+ day: "numeric"
+ }, "month");
+ },
+ weekday = function weekday(length, standalone) {
+ return knownEnglish ? weekdayForDateTime(dt, length) : string(standalone ? {
+ weekday: length
+ } : {
+ weekday: length,
+ month: "long",
+ day: "numeric"
+ }, "weekday");
+ },
+ maybeMacro = function maybeMacro(token) {
+ var formatOpts = Formatter.macroTokenToFormatOpts(token);
+
+ if (formatOpts) {
+ return _this.formatWithSystemDefault(dt, formatOpts);
+ } else {
+ return token;
+ }
+ },
+ era = function era(length) {
+ return knownEnglish ? eraForDateTime(dt, length) : string({
+ era: length
+ }, "era");
+ },
+ tokenToString = function tokenToString(token) {
+ // Where possible: http://cldr.unicode.org/translation/date-time#TOC-Stand-Alone-vs.-Format-Styles
+ switch (token) {
+ // ms
+ case "S":
+ return _this.num(dt.millisecond);
+
+ case "u": // falls through
+
+ case "SSS":
+ return _this.num(dt.millisecond, 3);
+ // seconds
+
+ case "s":
+ return _this.num(dt.second);
+
+ case "ss":
+ return _this.num(dt.second, 2);
+ // minutes
+
+ case "m":
+ return _this.num(dt.minute);
+
+ case "mm":
+ return _this.num(dt.minute, 2);
+ // hours
+
+ case "h":
+ return _this.num(dt.hour % 12 === 0 ? 12 : dt.hour % 12);
+
+ case "hh":
+ return _this.num(dt.hour % 12 === 0 ? 12 : dt.hour % 12, 2);
+
+ case "H":
+ return _this.num(dt.hour);
+
+ case "HH":
+ return _this.num(dt.hour, 2);
+ // offset
+
+ case "Z":
+ // like +6
+ return formatOffset({
+ format: "narrow",
+ allowZ: _this.opts.allowZ
+ });
+
+ case "ZZ":
+ // like +06:00
+ return formatOffset({
+ format: "short",
+ allowZ: _this.opts.allowZ
+ });
+
+ case "ZZZ":
+ // like +0600
+ return formatOffset({
+ format: "techie",
+ allowZ: _this.opts.allowZ
+ });
+
+ case "ZZZZ":
+ // like EST
+ return dt.zone.offsetName(dt.ts, {
+ format: "short",
+ locale: _this.loc.locale
+ });
+
+ case "ZZZZZ":
+ // like Eastern Standard Time
+ return dt.zone.offsetName(dt.ts, {
+ format: "long",
+ locale: _this.loc.locale
+ });
+ // zone
+
+ case "z":
+ // like America/New_York
+ return dt.zoneName;
+ // meridiems
+
+ case "a":
+ return meridiem();
+ // dates
+
+ case "d":
+ return useDateTimeFormatter ? string({
+ day: "numeric"
+ }, "day") : _this.num(dt.day);
+
+ case "dd":
+ return useDateTimeFormatter ? string({
+ day: "2-digit"
+ }, "day") : _this.num(dt.day, 2);
+ // weekdays - standalone
+
+ case "c":
+ // like 1
+ return _this.num(dt.weekday);
+
+ case "ccc":
+ // like 'Tues'
+ return weekday("short", true);
+
+ case "cccc":
+ // like 'Tuesday'
+ return weekday("long", true);
+
+ case "ccccc":
+ // like 'T'
+ return weekday("narrow", true);
+ // weekdays - format
+
+ case "E":
+ // like 1
+ return _this.num(dt.weekday);
+
+ case "EEE":
+ // like 'Tues'
+ return weekday("short", false);
+
+ case "EEEE":
+ // like 'Tuesday'
+ return weekday("long", false);
+
+ case "EEEEE":
+ // like 'T'
+ return weekday("narrow", false);
+ // months - standalone
+
+ case "L":
+ // like 1
+ return useDateTimeFormatter ? string({
+ month: "numeric",
+ day: "numeric"
+ }, "month") : _this.num(dt.month);
+
+ case "LL":
+ // like 01, doesn't seem to work
+ return useDateTimeFormatter ? string({
+ month: "2-digit",
+ day: "numeric"
+ }, "month") : _this.num(dt.month, 2);
+
+ case "LLL":
+ // like Jan
+ return month("short", true);
+
+ case "LLLL":
+ // like January
+ return month("long", true);
+
+ case "LLLLL":
+ // like J
+ return month("narrow", true);
+ // months - format
+
+ case "M":
+ // like 1
+ return useDateTimeFormatter ? string({
+ month: "numeric"
+ }, "month") : _this.num(dt.month);
+
+ case "MM":
+ // like 01
+ return useDateTimeFormatter ? string({
+ month: "2-digit"
+ }, "month") : _this.num(dt.month, 2);
+
+ case "MMM":
+ // like Jan
+ return month("short", false);
+
+ case "MMMM":
+ // like January
+ return month("long", false);
+
+ case "MMMMM":
+ // like J
+ return month("narrow", false);
+ // years
+
+ case "y":
+ // like 2014
+ return useDateTimeFormatter ? string({
+ year: "numeric"
+ }, "year") : _this.num(dt.year);
+
+ case "yy":
+ // like 14
+ return useDateTimeFormatter ? string({
+ year: "2-digit"
+ }, "year") : _this.num(dt.year.toString().slice(-2), 2);
+
+ case "yyyy":
+ // like 0012
+ return useDateTimeFormatter ? string({
+ year: "numeric"
+ }, "year") : _this.num(dt.year, 4);
+
+ case "yyyyyy":
+ // like 000012
+ return useDateTimeFormatter ? string({
+ year: "numeric"
+ }, "year") : _this.num(dt.year, 6);
+ // eras
+
+ case "G":
+ // like AD
+ return era("short");
+
+ case "GG":
+ // like Anno Domini
+ return era("long");
+
+ case "GGGGG":
+ return era("narrow");
+
+ case "kk":
+ return _this.num(dt.weekYear.toString().slice(-2), 2);
+
+ case "kkkk":
+ return _this.num(dt.weekYear, 4);
+
+ case "W":
+ return _this.num(dt.weekNumber);
+
+ case "WW":
+ return _this.num(dt.weekNumber, 2);
+
+ case "o":
+ return _this.num(dt.ordinal);
+
+ case "ooo":
+ return _this.num(dt.ordinal, 3);
+
+ case "q":
+ // like 1
+ return _this.num(dt.quarter);
+
+ case "qq":
+ // like 01
+ return _this.num(dt.quarter, 2);
+
+ case "X":
+ return _this.num(Math.floor(dt.ts / 1000));
+
+ case "x":
+ return _this.num(dt.ts);
+
+ default:
+ return maybeMacro(token);
+ }
+ };
+
+ return stringifyTokens(Formatter.parseFormat(fmt), tokenToString);
+ };
+
+ _proto.formatDurationFromString = function formatDurationFromString(dur, fmt) {
+ var _this2 = this;
+
+ var tokenToField = function tokenToField(token) {
+ switch (token[0]) {
+ case "S":
+ return "millisecond";
+
+ case "s":
+ return "second";
+
+ case "m":
+ return "minute";
+
+ case "h":
+ return "hour";
+
+ case "d":
+ return "day";
+
+ case "M":
+ return "month";
+
+ case "y":
+ return "year";
+
+ default:
+ return null;
+ }
+ },
+ tokenToString = function tokenToString(lildur) {
+ return function (token) {
+ var mapped = tokenToField(token);
+
+ if (mapped) {
+ return _this2.num(lildur.get(mapped), token.length);
+ } else {
+ return token;
+ }
+ };
+ },
+ tokens = Formatter.parseFormat(fmt),
+ realTokens = tokens.reduce(function (found, _ref) {
+ var literal = _ref.literal,
+ val = _ref.val;
+ return literal ? found : found.concat(val);
+ }, []),
+ collapsed = dur.shiftTo.apply(dur, realTokens.map(tokenToField).filter(function (t) {
+ return t;
+ }));
+
+ return stringifyTokens(tokens, tokenToString(collapsed));
+ };
+
+ return Formatter;
+ }();
+
+ var Invalid = /*#__PURE__*/function () {
+ function Invalid(reason, explanation) {
+ this.reason = reason;
+ this.explanation = explanation;
+ }
+
+ var _proto = Invalid.prototype;
+
+ _proto.toMessage = function toMessage() {
+ if (this.explanation) {
+ return this.reason + ": " + this.explanation;
+ } else {
+ return this.reason;
+ }
+ };
+
+ return Invalid;
+ }();
+
+ /**
+ * @interface
+ */
+
+ var Zone = /*#__PURE__*/function () {
+ function Zone() {}
+
+ var _proto = Zone.prototype;
+
+ /**
+ * Returns the offset's common name (such as EST) at the specified timestamp
+ * @abstract
+ * @param {number} ts - Epoch milliseconds for which to get the name
+ * @param {Object} opts - Options to affect the format
+ * @param {string} opts.format - What style of offset to return. Accepts 'long' or 'short'.
+ * @param {string} opts.locale - What locale to return the offset name in.
+ * @return {string}
+ */
+ _proto.offsetName = function offsetName(ts, opts) {
+ throw new ZoneIsAbstractError();
+ }
+ /**
+ * Returns the offset's value as a string
+ * @abstract
+ * @param {number} ts - Epoch milliseconds for which to get the offset
+ * @param {string} format - What style of offset to return.
+ * Accepts 'narrow', 'short', or 'techie'. Returning '+6', '+06:00', or '+0600' respectively
+ * @return {string}
+ */
+ ;
+
+ _proto.formatOffset = function formatOffset(ts, format) {
+ throw new ZoneIsAbstractError();
+ }
+ /**
+ * Return the offset in minutes for this zone at the specified timestamp.
+ * @abstract
+ * @param {number} ts - Epoch milliseconds for which to compute the offset
+ * @return {number}
+ */
+ ;
+
+ _proto.offset = function offset(ts) {
+ throw new ZoneIsAbstractError();
+ }
+ /**
+ * Return whether this Zone is equal to another zone
+ * @abstract
+ * @param {Zone} otherZone - the zone to compare
+ * @return {boolean}
+ */
+ ;
+
+ _proto.equals = function equals(otherZone) {
+ throw new ZoneIsAbstractError();
+ }
+ /**
+ * Return whether this Zone is valid.
+ * @abstract
+ * @type {boolean}
+ */
+ ;
+
+ _createClass(Zone, [{
+ key: "type",
+
+ /**
+ * The type of zone
+ * @abstract
+ * @type {string}
+ */
+ get: function get() {
+ throw new ZoneIsAbstractError();
+ }
+ /**
+ * The name of this zone.
+ * @abstract
+ * @type {string}
+ */
+
+ }, {
+ key: "name",
+ get: function get() {
+ throw new ZoneIsAbstractError();
+ }
+ /**
+ * Returns whether the offset is known to be fixed for the whole year.
+ * @abstract
+ * @type {boolean}
+ */
+
+ }, {
+ key: "universal",
+ get: function get() {
+ throw new ZoneIsAbstractError();
+ }
+ }, {
+ key: "isValid",
+ get: function get() {
+ throw new ZoneIsAbstractError();
+ }
+ }]);
+
+ return Zone;
+ }();
+
+ var singleton = null;
+ /**
+ * Represents the local zone for this Javascript environment.
+ * @implements {Zone}
+ */
+
+ var LocalZone = /*#__PURE__*/function (_Zone) {
+ _inheritsLoose(LocalZone, _Zone);
+
+ function LocalZone() {
+ return _Zone.apply(this, arguments) || this;
+ }
+
+ var _proto = LocalZone.prototype;
+
+ /** @override **/
+ _proto.offsetName = function offsetName(ts, _ref) {
+ var format = _ref.format,
+ locale = _ref.locale;
+ return parseZoneInfo(ts, format, locale);
+ }
+ /** @override **/
+ ;
+
+ _proto.formatOffset = function formatOffset$1(ts, format) {
+ return formatOffset(this.offset(ts), format);
+ }
+ /** @override **/
+ ;
+
+ _proto.offset = function offset(ts) {
+ return -new Date(ts).getTimezoneOffset();
+ }
+ /** @override **/
+ ;
+
+ _proto.equals = function equals(otherZone) {
+ return otherZone.type === "local";
+ }
+ /** @override **/
+ ;
+
+ _createClass(LocalZone, [{
+ key: "type",
+
+ /** @override **/
+ get: function get() {
+ return "local";
+ }
+ /** @override **/
+
+ }, {
+ key: "name",
+ get: function get() {
+ if (hasIntl()) {
+ return new Intl.DateTimeFormat().resolvedOptions().timeZone;
+ } else return "local";
+ }
+ /** @override **/
+
+ }, {
+ key: "universal",
+ get: function get() {
+ return false;
+ }
+ }, {
+ key: "isValid",
+ get: function get() {
+ return true;
+ }
+ }], [{
+ key: "instance",
+
+ /**
+ * Get a singleton instance of the local zone
+ * @return {LocalZone}
+ */
+ get: function get() {
+ if (singleton === null) {
+ singleton = new LocalZone();
+ }
+
+ return singleton;
+ }
+ }]);
+
+ return LocalZone;
+ }(Zone);
+
+ var matchingRegex = RegExp("^" + ianaRegex.source + "$");
+ var dtfCache = {};
+
+ function makeDTF(zone) {
+ if (!dtfCache[zone]) {
+ dtfCache[zone] = new Intl.DateTimeFormat("en-US", {
+ hour12: false,
+ timeZone: zone,
+ year: "numeric",
+ month: "2-digit",
+ day: "2-digit",
+ hour: "2-digit",
+ minute: "2-digit",
+ second: "2-digit"
+ });
+ }
+
+ return dtfCache[zone];
+ }
+
+ var typeToPos = {
+ year: 0,
+ month: 1,
+ day: 2,
+ hour: 3,
+ minute: 4,
+ second: 5
+ };
+
+ function hackyOffset(dtf, date) {
+ var formatted = dtf.format(date).replace(/\u200E/g, ""),
+ parsed = /(\d+)\/(\d+)\/(\d+),? (\d+):(\d+):(\d+)/.exec(formatted),
+ fMonth = parsed[1],
+ fDay = parsed[2],
+ fYear = parsed[3],
+ fHour = parsed[4],
+ fMinute = parsed[5],
+ fSecond = parsed[6];
+ return [fYear, fMonth, fDay, fHour, fMinute, fSecond];
+ }
+
+ function partsOffset(dtf, date) {
+ var formatted = dtf.formatToParts(date),
+ filled = [];
+
+ for (var i = 0; i < formatted.length; i++) {
+ var _formatted$i = formatted[i],
+ type = _formatted$i.type,
+ value = _formatted$i.value,
+ pos = typeToPos[type];
+
+ if (!isUndefined(pos)) {
+ filled[pos] = parseInt(value, 10);
+ }
+ }
+
+ return filled;
+ }
+
+ var ianaZoneCache = {};
+ /**
+ * A zone identified by an IANA identifier, like America/New_York
+ * @implements {Zone}
+ */
+
+ var IANAZone = /*#__PURE__*/function (_Zone) {
+ _inheritsLoose(IANAZone, _Zone);
+
+ /**
+ * @param {string} name - Zone name
+ * @return {IANAZone}
+ */
+ IANAZone.create = function create(name) {
+ if (!ianaZoneCache[name]) {
+ ianaZoneCache[name] = new IANAZone(name);
+ }
+
+ return ianaZoneCache[name];
+ }
+ /**
+ * Reset local caches. Should only be necessary in testing scenarios.
+ * @return {void}
+ */
+ ;
+
+ IANAZone.resetCache = function resetCache() {
+ ianaZoneCache = {};
+ dtfCache = {};
+ }
+ /**
+ * Returns whether the provided string is a valid specifier. This only checks the string's format, not that the specifier identifies a known zone; see isValidZone for that.
+ * @param {string} s - The string to check validity on
+ * @example IANAZone.isValidSpecifier("America/New_York") //=> true
+ * @example IANAZone.isValidSpecifier("Fantasia/Castle") //=> true
+ * @example IANAZone.isValidSpecifier("Sport~~blorp") //=> false
+ * @return {boolean}
+ */
+ ;
+
+ IANAZone.isValidSpecifier = function isValidSpecifier(s) {
+ return !!(s && s.match(matchingRegex));
+ }
+ /**
+ * Returns whether the provided string identifies a real zone
+ * @param {string} zone - The string to check
+ * @example IANAZone.isValidZone("America/New_York") //=> true
+ * @example IANAZone.isValidZone("Fantasia/Castle") //=> false
+ * @example IANAZone.isValidZone("Sport~~blorp") //=> false
+ * @return {boolean}
+ */
+ ;
+
+ IANAZone.isValidZone = function isValidZone(zone) {
+ try {
+ new Intl.DateTimeFormat("en-US", {
+ timeZone: zone
+ }).format();
+ return true;
+ } catch (e) {
+ return false;
+ }
+ } // Etc/GMT+8 -> -480
+
+ /** @ignore */
+ ;
+
+ IANAZone.parseGMTOffset = function parseGMTOffset(specifier) {
+ if (specifier) {
+ var match = specifier.match(/^Etc\/GMT([+-]\d{1,2})$/i);
+
+ if (match) {
+ return -60 * parseInt(match[1]);
+ }
+ }
+
+ return null;
+ };
+
+ function IANAZone(name) {
+ var _this;
+
+ _this = _Zone.call(this) || this;
+ /** @private **/
+
+ _this.zoneName = name;
+ /** @private **/
+
+ _this.valid = IANAZone.isValidZone(name);
+ return _this;
+ }
+ /** @override **/
+
+
+ var _proto = IANAZone.prototype;
+
+ /** @override **/
+ _proto.offsetName = function offsetName(ts, _ref) {
+ var format = _ref.format,
+ locale = _ref.locale;
+ return parseZoneInfo(ts, format, locale, this.name);
+ }
+ /** @override **/
+ ;
+
+ _proto.formatOffset = function formatOffset$1(ts, format) {
+ return formatOffset(this.offset(ts), format);
+ }
+ /** @override **/
+ ;
+
+ _proto.offset = function offset(ts) {
+ var date = new Date(ts),
+ dtf = makeDTF(this.name),
+ _ref2 = dtf.formatToParts ? partsOffset(dtf, date) : hackyOffset(dtf, date),
+ year = _ref2[0],
+ month = _ref2[1],
+ day = _ref2[2],
+ hour = _ref2[3],
+ minute = _ref2[4],
+ second = _ref2[5],
+ adjustedHour = hour === 24 ? 0 : hour;
+
+ var asUTC = objToLocalTS({
+ year: year,
+ month: month,
+ day: day,
+ hour: adjustedHour,
+ minute: minute,
+ second: second,
+ millisecond: 0
+ });
+ var asTS = +date;
+ var over = asTS % 1000;
+ asTS -= over >= 0 ? over : 1000 + over;
+ return (asUTC - asTS) / (60 * 1000);
+ }
+ /** @override **/
+ ;
+
+ _proto.equals = function equals(otherZone) {
+ return otherZone.type === "iana" && otherZone.name === this.name;
+ }
+ /** @override **/
+ ;
+
+ _createClass(IANAZone, [{
+ key: "type",
+ get: function get() {
+ return "iana";
+ }
+ /** @override **/
+
+ }, {
+ key: "name",
+ get: function get() {
+ return this.zoneName;
+ }
+ /** @override **/
+
+ }, {
+ key: "universal",
+ get: function get() {
+ return false;
+ }
+ }, {
+ key: "isValid",
+ get: function get() {
+ return this.valid;
+ }
+ }]);
+
+ return IANAZone;
+ }(Zone);
+
+ var singleton$1 = null;
+ /**
+ * A zone with a fixed offset (meaning no DST)
+ * @implements {Zone}
+ */
+
+ var FixedOffsetZone = /*#__PURE__*/function (_Zone) {
+ _inheritsLoose(FixedOffsetZone, _Zone);
+
+ /**
+ * Get an instance with a specified offset
+ * @param {number} offset - The offset in minutes
+ * @return {FixedOffsetZone}
+ */
+ FixedOffsetZone.instance = function instance(offset) {
+ return offset === 0 ? FixedOffsetZone.utcInstance : new FixedOffsetZone(offset);
+ }
+ /**
+ * Get an instance of FixedOffsetZone from a UTC offset string, like "UTC+6"
+ * @param {string} s - The offset string to parse
+ * @example FixedOffsetZone.parseSpecifier("UTC+6")
+ * @example FixedOffsetZone.parseSpecifier("UTC+06")
+ * @example FixedOffsetZone.parseSpecifier("UTC-6:00")
+ * @return {FixedOffsetZone}
+ */
+ ;
+
+ FixedOffsetZone.parseSpecifier = function parseSpecifier(s) {
+ if (s) {
+ var r = s.match(/^utc(?:([+-]\d{1,2})(?::(\d{2}))?)?$/i);
+
+ if (r) {
+ return new FixedOffsetZone(signedOffset(r[1], r[2]));
+ }
+ }
+
+ return null;
+ };
+
+ _createClass(FixedOffsetZone, null, [{
+ key: "utcInstance",
+
+ /**
+ * Get a singleton instance of UTC
+ * @return {FixedOffsetZone}
+ */
+ get: function get() {
+ if (singleton$1 === null) {
+ singleton$1 = new FixedOffsetZone(0);
+ }
+
+ return singleton$1;
+ }
+ }]);
+
+ function FixedOffsetZone(offset) {
+ var _this;
+
+ _this = _Zone.call(this) || this;
+ /** @private **/
+
+ _this.fixed = offset;
+ return _this;
+ }
+ /** @override **/
+
+
+ var _proto = FixedOffsetZone.prototype;
+
+ /** @override **/
+ _proto.offsetName = function offsetName() {
+ return this.name;
+ }
+ /** @override **/
+ ;
+
+ _proto.formatOffset = function formatOffset$1(ts, format) {
+ return formatOffset(this.fixed, format);
+ }
+ /** @override **/
+ ;
+
+ /** @override **/
+ _proto.offset = function offset() {
+ return this.fixed;
+ }
+ /** @override **/
+ ;
+
+ _proto.equals = function equals(otherZone) {
+ return otherZone.type === "fixed" && otherZone.fixed === this.fixed;
+ }
+ /** @override **/
+ ;
+
+ _createClass(FixedOffsetZone, [{
+ key: "type",
+ get: function get() {
+ return "fixed";
+ }
+ /** @override **/
+
+ }, {
+ key: "name",
+ get: function get() {
+ return this.fixed === 0 ? "UTC" : "UTC" + formatOffset(this.fixed, "narrow");
+ }
+ }, {
+ key: "universal",
+ get: function get() {
+ return true;
+ }
+ }, {
+ key: "isValid",
+ get: function get() {
+ return true;
+ }
+ }]);
+
+ return FixedOffsetZone;
+ }(Zone);
+
+ /**
+ * A zone that failed to parse. You should never need to instantiate this.
+ * @implements {Zone}
+ */
+
+ var InvalidZone = /*#__PURE__*/function (_Zone) {
+ _inheritsLoose(InvalidZone, _Zone);
+
+ function InvalidZone(zoneName) {
+ var _this;
+
+ _this = _Zone.call(this) || this;
+ /** @private */
+
+ _this.zoneName = zoneName;
+ return _this;
+ }
+ /** @override **/
+
+
+ var _proto = InvalidZone.prototype;
+
+ /** @override **/
+ _proto.offsetName = function offsetName() {
+ return null;
+ }
+ /** @override **/
+ ;
+
+ _proto.formatOffset = function formatOffset() {
+ return "";
+ }
+ /** @override **/
+ ;
+
+ _proto.offset = function offset() {
+ return NaN;
+ }
+ /** @override **/
+ ;
+
+ _proto.equals = function equals() {
+ return false;
+ }
+ /** @override **/
+ ;
+
+ _createClass(InvalidZone, [{
+ key: "type",
+ get: function get() {
+ return "invalid";
+ }
+ /** @override **/
+
+ }, {
+ key: "name",
+ get: function get() {
+ return this.zoneName;
+ }
+ /** @override **/
+
+ }, {
+ key: "universal",
+ get: function get() {
+ return false;
+ }
+ }, {
+ key: "isValid",
+ get: function get() {
+ return false;
+ }
+ }]);
+
+ return InvalidZone;
+ }(Zone);
+
+ /**
+ * @private
+ */
+ function normalizeZone(input, defaultZone) {
+ var offset;
+
+ if (isUndefined(input) || input === null) {
+ return defaultZone;
+ } else if (input instanceof Zone) {
+ return input;
+ } else if (isString(input)) {
+ var lowered = input.toLowerCase();
+ if (lowered === "local") return defaultZone;else if (lowered === "utc" || lowered === "gmt") return FixedOffsetZone.utcInstance;else if ((offset = IANAZone.parseGMTOffset(input)) != null) {
+ // handle Etc/GMT-4, which V8 chokes on
+ return FixedOffsetZone.instance(offset);
+ } else if (IANAZone.isValidSpecifier(lowered)) return IANAZone.create(input);else return FixedOffsetZone.parseSpecifier(lowered) || new InvalidZone(input);
+ } else if (isNumber(input)) {
+ return FixedOffsetZone.instance(input);
+ } else if (typeof input === "object" && input.offset && typeof input.offset === "number") {
+ // This is dumb, but the instanceof check above doesn't seem to really work
+ // so we're duck checking it
+ return input;
+ } else {
+ return new InvalidZone(input);
+ }
+ }
+
+ var now = function now() {
+ return Date.now();
+ },
+ defaultZone = null,
+ // not setting this directly to LocalZone.instance bc loading order issues
+ defaultLocale = null,
+ defaultNumberingSystem = null,
+ defaultOutputCalendar = null,
+ throwOnInvalid = false;
+ /**
+ * Settings contains static getters and setters that control Luxon's overall behavior. Luxon is a simple library with few options, but the ones it does have live here.
+ */
+
+
+ var Settings = /*#__PURE__*/function () {
+ function Settings() {}
+
+ /**
+ * Reset Luxon's global caches. Should only be necessary in testing scenarios.
+ * @return {void}
+ */
+ Settings.resetCaches = function resetCaches() {
+ Locale.resetCache();
+ IANAZone.resetCache();
+ };
+
+ _createClass(Settings, null, [{
+ key: "now",
+
+ /**
+ * Get the callback for returning the current timestamp.
+ * @type {function}
+ */
+ get: function get() {
+ return now;
+ }
+ /**
+ * Set the callback for returning the current timestamp.
+ * The function should return a number, which will be interpreted as an Epoch millisecond count
+ * @type {function}
+ * @example Settings.now = () => Date.now() + 3000 // pretend it is 3 seconds in the future
+ * @example Settings.now = () => 0 // always pretend it's Jan 1, 1970 at midnight in UTC time
+ */
+ ,
+ set: function set(n) {
+ now = n;
+ }
+ /**
+ * Get the default time zone to create DateTimes in.
+ * @type {string}
+ */
+
+ }, {
+ key: "defaultZoneName",
+ get: function get() {
+ return Settings.defaultZone.name;
+ }
+ /**
+ * Set the default time zone to create DateTimes in. Does not affect existing instances.
+ * @type {string}
+ */
+ ,
+ set: function set(z) {
+ if (!z) {
+ defaultZone = null;
+ } else {
+ defaultZone = normalizeZone(z);
+ }
+ }
+ /**
+ * Get the default time zone object to create DateTimes in. Does not affect existing instances.
+ * @type {Zone}
+ */
+
+ }, {
+ key: "defaultZone",
+ get: function get() {
+ return defaultZone || LocalZone.instance;
+ }
+ /**
+ * Get the default locale to create DateTimes with. Does not affect existing instances.
+ * @type {string}
+ */
+
+ }, {
+ key: "defaultLocale",
+ get: function get() {
+ return defaultLocale;
+ }
+ /**
+ * Set the default locale to create DateTimes with. Does not affect existing instances.
+ * @type {string}
+ */
+ ,
+ set: function set(locale) {
+ defaultLocale = locale;
+ }
+ /**
+ * Get the default numbering system to create DateTimes with. Does not affect existing instances.
+ * @type {string}
+ */
+
+ }, {
+ key: "defaultNumberingSystem",
+ get: function get() {
+ return defaultNumberingSystem;
+ }
+ /**
+ * Set the default numbering system to create DateTimes with. Does not affect existing instances.
+ * @type {string}
+ */
+ ,
+ set: function set(numberingSystem) {
+ defaultNumberingSystem = numberingSystem;
+ }
+ /**
+ * Get the default output calendar to create DateTimes with. Does not affect existing instances.
+ * @type {string}
+ */
+
+ }, {
+ key: "defaultOutputCalendar",
+ get: function get() {
+ return defaultOutputCalendar;
+ }
+ /**
+ * Set the default output calendar to create DateTimes with. Does not affect existing instances.
+ * @type {string}
+ */
+ ,
+ set: function set(outputCalendar) {
+ defaultOutputCalendar = outputCalendar;
+ }
+ /**
+ * Get whether Luxon will throw when it encounters invalid DateTimes, Durations, or Intervals
+ * @type {boolean}
+ */
+
+ }, {
+ key: "throwOnInvalid",
+ get: function get() {
+ return throwOnInvalid;
+ }
+ /**
+ * Set whether Luxon will throw when it encounters invalid DateTimes, Durations, or Intervals
+ * @type {boolean}
+ */
+ ,
+ set: function set(t) {
+ throwOnInvalid = t;
+ }
+ }]);
+
+ return Settings;
+ }();
+
+ var intlDTCache = {};
+
+ function getCachedDTF(locString, opts) {
+ if (opts === void 0) {
+ opts = {};
+ }
+
+ var key = JSON.stringify([locString, opts]);
+ var dtf = intlDTCache[key];
+
+ if (!dtf) {
+ dtf = new Intl.DateTimeFormat(locString, opts);
+ intlDTCache[key] = dtf;
+ }
+
+ return dtf;
+ }
+
+ var intlNumCache = {};
+
+ function getCachedINF(locString, opts) {
+ if (opts === void 0) {
+ opts = {};
+ }
+
+ var key = JSON.stringify([locString, opts]);
+ var inf = intlNumCache[key];
+
+ if (!inf) {
+ inf = new Intl.NumberFormat(locString, opts);
+ intlNumCache[key] = inf;
+ }
+
+ return inf;
+ }
+
+ var intlRelCache = {};
+
+ function getCachedRTF(locString, opts) {
+ if (opts === void 0) {
+ opts = {};
+ }
+
+ var _opts = opts,
+ base = _opts.base,
+ cacheKeyOpts = _objectWithoutPropertiesLoose(_opts, ["base"]); // exclude `base` from the options
+
+
+ var key = JSON.stringify([locString, cacheKeyOpts]);
+ var inf = intlRelCache[key];
+
+ if (!inf) {
+ inf = new Intl.RelativeTimeFormat(locString, opts);
+ intlRelCache[key] = inf;
+ }
+
+ return inf;
+ }
+
+ var sysLocaleCache = null;
+
+ function systemLocale() {
+ if (sysLocaleCache) {
+ return sysLocaleCache;
+ } else if (hasIntl()) {
+ var computedSys = new Intl.DateTimeFormat().resolvedOptions().locale; // node sometimes defaults to "und". Override that because that is dumb
+
+ sysLocaleCache = !computedSys || computedSys === "und" ? "en-US" : computedSys;
+ return sysLocaleCache;
+ } else {
+ sysLocaleCache = "en-US";
+ return sysLocaleCache;
+ }
+ }
+
+ function parseLocaleString(localeStr) {
+ // I really want to avoid writing a BCP 47 parser
+ // see, e.g. https://github.com/wooorm/bcp-47
+ // Instead, we'll do this:
+ // a) if the string has no -u extensions, just leave it alone
+ // b) if it does, use Intl to resolve everything
+ // c) if Intl fails, try again without the -u
+ var uIndex = localeStr.indexOf("-u-");
+
+ if (uIndex === -1) {
+ return [localeStr];
+ } else {
+ var options;
+ var smaller = localeStr.substring(0, uIndex);
+
+ try {
+ options = getCachedDTF(localeStr).resolvedOptions();
+ } catch (e) {
+ options = getCachedDTF(smaller).resolvedOptions();
+ }
+
+ var _options = options,
+ numberingSystem = _options.numberingSystem,
+ calendar = _options.calendar; // return the smaller one so that we can append the calendar and numbering overrides to it
+
+ return [smaller, numberingSystem, calendar];
+ }
+ }
+
+ function intlConfigString(localeStr, numberingSystem, outputCalendar) {
+ if (hasIntl()) {
+ if (outputCalendar || numberingSystem) {
+ localeStr += "-u";
+
+ if (outputCalendar) {
+ localeStr += "-ca-" + outputCalendar;
+ }
+
+ if (numberingSystem) {
+ localeStr += "-nu-" + numberingSystem;
+ }
+
+ return localeStr;
+ } else {
+ return localeStr;
+ }
+ } else {
+ return [];
+ }
+ }
+
+ function mapMonths(f) {
+ var ms = [];
+
+ for (var i = 1; i <= 12; i++) {
+ var dt = DateTime.utc(2016, i, 1);
+ ms.push(f(dt));
+ }
+
+ return ms;
+ }
+
+ function mapWeekdays(f) {
+ var ms = [];
+
+ for (var i = 1; i <= 7; i++) {
+ var dt = DateTime.utc(2016, 11, 13 + i);
+ ms.push(f(dt));
+ }
+
+ return ms;
+ }
+
+ function listStuff(loc, length, defaultOK, englishFn, intlFn) {
+ var mode = loc.listingMode(defaultOK);
+
+ if (mode === "error") {
+ return null;
+ } else if (mode === "en") {
+ return englishFn(length);
+ } else {
+ return intlFn(length);
+ }
+ }
+
+ function supportsFastNumbers(loc) {
+ if (loc.numberingSystem && loc.numberingSystem !== "latn") {
+ return false;
+ } else {
+ return loc.numberingSystem === "latn" || !loc.locale || loc.locale.startsWith("en") || hasIntl() && new Intl.DateTimeFormat(loc.intl).resolvedOptions().numberingSystem === "latn";
+ }
+ }
+ /**
+ * @private
+ */
+
+
+ var PolyNumberFormatter = /*#__PURE__*/function () {
+ function PolyNumberFormatter(intl, forceSimple, opts) {
+ this.padTo = opts.padTo || 0;
+ this.floor = opts.floor || false;
+
+ if (!forceSimple && hasIntl()) {
+ var intlOpts = {
+ useGrouping: false
+ };
+ if (opts.padTo > 0) intlOpts.minimumIntegerDigits = opts.padTo;
+ this.inf = getCachedINF(intl, intlOpts);
+ }
+ }
+
+ var _proto = PolyNumberFormatter.prototype;
+
+ _proto.format = function format(i) {
+ if (this.inf) {
+ var fixed = this.floor ? Math.floor(i) : i;
+ return this.inf.format(fixed);
+ } else {
+ // to match the browser's numberformatter defaults
+ var _fixed = this.floor ? Math.floor(i) : roundTo(i, 3);
+
+ return padStart(_fixed, this.padTo);
+ }
+ };
+
+ return PolyNumberFormatter;
+ }();
+ /**
+ * @private
+ */
+
+
+ var PolyDateFormatter = /*#__PURE__*/function () {
+ function PolyDateFormatter(dt, intl, opts) {
+ this.opts = opts;
+ this.hasIntl = hasIntl();
+ var z;
+
+ if (dt.zone.universal && this.hasIntl) {
+ // Chromium doesn't support fixed-offset zones like Etc/GMT+8 in its formatter,
+ // See https://bugs.chromium.org/p/chromium/issues/detail?id=364374.
+ // So we have to make do. Two cases:
+ // 1. The format options tell us to show the zone. We can't do that, so the best
+ // we can do is format the date in UTC.
+ // 2. The format options don't tell us to show the zone. Then we can adjust them
+ // the time and tell the formatter to show it to us in UTC, so that the time is right
+ // and the bad zone doesn't show up.
+ // We can clean all this up when Chrome fixes this.
+ z = "UTC";
+
+ if (opts.timeZoneName) {
+ this.dt = dt;
+ } else {
+ this.dt = dt.offset === 0 ? dt : DateTime.fromMillis(dt.ts + dt.offset * 60 * 1000);
+ }
+ } else if (dt.zone.type === "local") {
+ this.dt = dt;
+ } else {
+ this.dt = dt;
+ z = dt.zone.name;
+ }
+
+ if (this.hasIntl) {
+ var intlOpts = Object.assign({}, this.opts);
+
+ if (z) {
+ intlOpts.timeZone = z;
+ }
+
+ this.dtf = getCachedDTF(intl, intlOpts);
+ }
+ }
+
+ var _proto2 = PolyDateFormatter.prototype;
+
+ _proto2.format = function format() {
+ if (this.hasIntl) {
+ return this.dtf.format(this.dt.toJSDate());
+ } else {
+ var tokenFormat = formatString(this.opts),
+ loc = Locale.create("en-US");
+ return Formatter.create(loc).formatDateTimeFromString(this.dt, tokenFormat);
+ }
+ };
+
+ _proto2.formatToParts = function formatToParts() {
+ if (this.hasIntl && hasFormatToParts()) {
+ return this.dtf.formatToParts(this.dt.toJSDate());
+ } else {
+ // This is kind of a cop out. We actually could do this for English. However, we couldn't do it for intl strings
+ // and IMO it's too weird to have an uncanny valley like that
+ return [];
+ }
+ };
+
+ _proto2.resolvedOptions = function resolvedOptions() {
+ if (this.hasIntl) {
+ return this.dtf.resolvedOptions();
+ } else {
+ return {
+ locale: "en-US",
+ numberingSystem: "latn",
+ outputCalendar: "gregory"
+ };
+ }
+ };
+
+ return PolyDateFormatter;
+ }();
+ /**
+ * @private
+ */
+
+
+ var PolyRelFormatter = /*#__PURE__*/function () {
+ function PolyRelFormatter(intl, isEnglish, opts) {
+ this.opts = Object.assign({
+ style: "long"
+ }, opts);
+
+ if (!isEnglish && hasRelative()) {
+ this.rtf = getCachedRTF(intl, opts);
+ }
+ }
+
+ var _proto3 = PolyRelFormatter.prototype;
+
+ _proto3.format = function format(count, unit) {
+ if (this.rtf) {
+ return this.rtf.format(count, unit);
+ } else {
+ return formatRelativeTime(unit, count, this.opts.numeric, this.opts.style !== "long");
+ }
+ };
+
+ _proto3.formatToParts = function formatToParts(count, unit) {
+ if (this.rtf) {
+ return this.rtf.formatToParts(count, unit);
+ } else {
+ return [];
+ }
+ };
+
+ return PolyRelFormatter;
+ }();
+ /**
+ * @private
+ */
+
+
+ var Locale = /*#__PURE__*/function () {
+ Locale.fromOpts = function fromOpts(opts) {
+ return Locale.create(opts.locale, opts.numberingSystem, opts.outputCalendar, opts.defaultToEN);
+ };
+
+ Locale.create = function create(locale, numberingSystem, outputCalendar, defaultToEN) {
+ if (defaultToEN === void 0) {
+ defaultToEN = false;
+ }
+
+ var specifiedLocale = locale || Settings.defaultLocale,
+ // the system locale is useful for human readable strings but annoying for parsing/formatting known formats
+ localeR = specifiedLocale || (defaultToEN ? "en-US" : systemLocale()),
+ numberingSystemR = numberingSystem || Settings.defaultNumberingSystem,
+ outputCalendarR = outputCalendar || Settings.defaultOutputCalendar;
+ return new Locale(localeR, numberingSystemR, outputCalendarR, specifiedLocale);
+ };
+
+ Locale.resetCache = function resetCache() {
+ sysLocaleCache = null;
+ intlDTCache = {};
+ intlNumCache = {};
+ intlRelCache = {};
+ };
+
+ Locale.fromObject = function fromObject(_temp) {
+ var _ref = _temp === void 0 ? {} : _temp,
+ locale = _ref.locale,
+ numberingSystem = _ref.numberingSystem,
+ outputCalendar = _ref.outputCalendar;
+
+ return Locale.create(locale, numberingSystem, outputCalendar);
+ };
+
+ function Locale(locale, numbering, outputCalendar, specifiedLocale) {
+ var _parseLocaleString = parseLocaleString(locale),
+ parsedLocale = _parseLocaleString[0],
+ parsedNumberingSystem = _parseLocaleString[1],
+ parsedOutputCalendar = _parseLocaleString[2];
+
+ this.locale = parsedLocale;
+ this.numberingSystem = numbering || parsedNumberingSystem || null;
+ this.outputCalendar = outputCalendar || parsedOutputCalendar || null;
+ this.intl = intlConfigString(this.locale, this.numberingSystem, this.outputCalendar);
+ this.weekdaysCache = {
+ format: {},
+ standalone: {}
+ };
+ this.monthsCache = {
+ format: {},
+ standalone: {}
+ };
+ this.meridiemCache = null;
+ this.eraCache = {};
+ this.specifiedLocale = specifiedLocale;
+ this.fastNumbersCached = null;
+ }
+
+ var _proto4 = Locale.prototype;
+
+ _proto4.listingMode = function listingMode(defaultOK) {
+ if (defaultOK === void 0) {
+ defaultOK = true;
+ }
+
+ var intl = hasIntl(),
+ hasFTP = intl && hasFormatToParts(),
+ isActuallyEn = this.isEnglish(),
+ hasNoWeirdness = (this.numberingSystem === null || this.numberingSystem === "latn") && (this.outputCalendar === null || this.outputCalendar === "gregory");
+
+ if (!hasFTP && !(isActuallyEn && hasNoWeirdness) && !defaultOK) {
+ return "error";
+ } else if (!hasFTP || isActuallyEn && hasNoWeirdness) {
+ return "en";
+ } else {
+ return "intl";
+ }
+ };
+
+ _proto4.clone = function clone(alts) {
+ if (!alts || Object.getOwnPropertyNames(alts).length === 0) {
+ return this;
+ } else {
+ return Locale.create(alts.locale || this.specifiedLocale, alts.numberingSystem || this.numberingSystem, alts.outputCalendar || this.outputCalendar, alts.defaultToEN || false);
+ }
+ };
+
+ _proto4.redefaultToEN = function redefaultToEN(alts) {
+ if (alts === void 0) {
+ alts = {};
+ }
+
+ return this.clone(Object.assign({}, alts, {
+ defaultToEN: true
+ }));
+ };
+
+ _proto4.redefaultToSystem = function redefaultToSystem(alts) {
+ if (alts === void 0) {
+ alts = {};
+ }
+
+ return this.clone(Object.assign({}, alts, {
+ defaultToEN: false
+ }));
+ };
+
+ _proto4.months = function months$1(length, format, defaultOK) {
+ var _this = this;
+
+ if (format === void 0) {
+ format = false;
+ }
+
+ if (defaultOK === void 0) {
+ defaultOK = true;
+ }
+
+ return listStuff(this, length, defaultOK, months, function () {
+ var intl = format ? {
+ month: length,
+ day: "numeric"
+ } : {
+ month: length
+ },
+ formatStr = format ? "format" : "standalone";
+
+ if (!_this.monthsCache[formatStr][length]) {
+ _this.monthsCache[formatStr][length] = mapMonths(function (dt) {
+ return _this.extract(dt, intl, "month");
+ });
+ }
+
+ return _this.monthsCache[formatStr][length];
+ });
+ };
+
+ _proto4.weekdays = function weekdays$1(length, format, defaultOK) {
+ var _this2 = this;
+
+ if (format === void 0) {
+ format = false;
+ }
+
+ if (defaultOK === void 0) {
+ defaultOK = true;
+ }
+
+ return listStuff(this, length, defaultOK, weekdays, function () {
+ var intl = format ? {
+ weekday: length,
+ year: "numeric",
+ month: "long",
+ day: "numeric"
+ } : {
+ weekday: length
+ },
+ formatStr = format ? "format" : "standalone";
+
+ if (!_this2.weekdaysCache[formatStr][length]) {
+ _this2.weekdaysCache[formatStr][length] = mapWeekdays(function (dt) {
+ return _this2.extract(dt, intl, "weekday");
+ });
+ }
+
+ return _this2.weekdaysCache[formatStr][length];
+ });
+ };
+
+ _proto4.meridiems = function meridiems$1(defaultOK) {
+ var _this3 = this;
+
+ if (defaultOK === void 0) {
+ defaultOK = true;
+ }
+
+ return listStuff(this, undefined, defaultOK, function () {
+ return meridiems;
+ }, function () {
+ // In theory there could be aribitrary day periods. We're gonna assume there are exactly two
+ // for AM and PM. This is probably wrong, but it's makes parsing way easier.
+ if (!_this3.meridiemCache) {
+ var intl = {
+ hour: "numeric",
+ hour12: true
+ };
+ _this3.meridiemCache = [DateTime.utc(2016, 11, 13, 9), DateTime.utc(2016, 11, 13, 19)].map(function (dt) {
+ return _this3.extract(dt, intl, "dayperiod");
+ });
+ }
+
+ return _this3.meridiemCache;
+ });
+ };
+
+ _proto4.eras = function eras$1(length, defaultOK) {
+ var _this4 = this;
+
+ if (defaultOK === void 0) {
+ defaultOK = true;
+ }
+
+ return listStuff(this, length, defaultOK, eras, function () {
+ var intl = {
+ era: length
+ }; // This is utter bullshit. Different calendars are going to define eras totally differently. What I need is the minimum set of dates
+ // to definitely enumerate them.
+
+ if (!_this4.eraCache[length]) {
+ _this4.eraCache[length] = [DateTime.utc(-40, 1, 1), DateTime.utc(2017, 1, 1)].map(function (dt) {
+ return _this4.extract(dt, intl, "era");
+ });
+ }
+
+ return _this4.eraCache[length];
+ });
+ };
+
+ _proto4.extract = function extract(dt, intlOpts, field) {
+ var df = this.dtFormatter(dt, intlOpts),
+ results = df.formatToParts(),
+ matching = results.find(function (m) {
+ return m.type.toLowerCase() === field;
+ });
+ return matching ? matching.value : null;
+ };
+
+ _proto4.numberFormatter = function numberFormatter(opts) {
+ if (opts === void 0) {
+ opts = {};
+ }
+
+ // this forcesimple option is never used (the only caller short-circuits on it, but it seems safer to leave)
+ // (in contrast, the rest of the condition is used heavily)
+ return new PolyNumberFormatter(this.intl, opts.forceSimple || this.fastNumbers, opts);
+ };
+
+ _proto4.dtFormatter = function dtFormatter(dt, intlOpts) {
+ if (intlOpts === void 0) {
+ intlOpts = {};
+ }
+
+ return new PolyDateFormatter(dt, this.intl, intlOpts);
+ };
+
+ _proto4.relFormatter = function relFormatter(opts) {
+ if (opts === void 0) {
+ opts = {};
+ }
+
+ return new PolyRelFormatter(this.intl, this.isEnglish(), opts);
+ };
+
+ _proto4.isEnglish = function isEnglish() {
+ return this.locale === "en" || this.locale.toLowerCase() === "en-us" || hasIntl() && new Intl.DateTimeFormat(this.intl).resolvedOptions().locale.startsWith("en-us");
+ };
+
+ _proto4.equals = function equals(other) {
+ return this.locale === other.locale && this.numberingSystem === other.numberingSystem && this.outputCalendar === other.outputCalendar;
+ };
+
+ _createClass(Locale, [{
+ key: "fastNumbers",
+ get: function get() {
+ if (this.fastNumbersCached == null) {
+ this.fastNumbersCached = supportsFastNumbers(this);
+ }
+
+ return this.fastNumbersCached;
+ }
+ }]);
+
+ return Locale;
+ }();
+
+ /*
+ * This file handles parsing for well-specified formats. Here's how it works:
+ * Two things go into parsing: a regex to match with and an extractor to take apart the groups in the match.
+ * An extractor is just a function that takes a regex match array and returns a { year: ..., month: ... } object
+ * parse() does the work of executing the regex and applying the extractor. It takes multiple regex/extractor pairs to try in sequence.
+ * Extractors can take a "cursor" representing the offset in the match to look at. This makes it easy to combine extractors.
+ * combineExtractors() does the work of combining them, keeping track of the cursor through multiple extractions.
+ * Some extractions are super dumb and simpleParse and fromStrings help DRY them.
+ */
+
+ function combineRegexes() {
+ for (var _len = arguments.length, regexes = new Array(_len), _key = 0; _key < _len; _key++) {
+ regexes[_key] = arguments[_key];
+ }
+
+ var full = regexes.reduce(function (f, r) {
+ return f + r.source;
+ }, "");
+ return RegExp("^" + full + "$");
+ }
+
+ function combineExtractors() {
+ for (var _len2 = arguments.length, extractors = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
+ extractors[_key2] = arguments[_key2];
+ }
+
+ return function (m) {
+ return extractors.reduce(function (_ref, ex) {
+ var mergedVals = _ref[0],
+ mergedZone = _ref[1],
+ cursor = _ref[2];
+
+ var _ex = ex(m, cursor),
+ val = _ex[0],
+ zone = _ex[1],
+ next = _ex[2];
+
+ return [Object.assign(mergedVals, val), mergedZone || zone, next];
+ }, [{}, null, 1]).slice(0, 2);
+ };
+ }
+
+ function parse(s) {
+ if (s == null) {
+ return [null, null];
+ }
+
+ for (var _len3 = arguments.length, patterns = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) {
+ patterns[_key3 - 1] = arguments[_key3];
+ }
+
+ for (var _i = 0, _patterns = patterns; _i < _patterns.length; _i++) {
+ var _patterns$_i = _patterns[_i],
+ regex = _patterns$_i[0],
+ extractor = _patterns$_i[1];
+ var m = regex.exec(s);
+
+ if (m) {
+ return extractor(m);
+ }
+ }
+
+ return [null, null];
+ }
+
+ function simpleParse() {
+ for (var _len4 = arguments.length, keys = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
+ keys[_key4] = arguments[_key4];
+ }
+
+ return function (match, cursor) {
+ var ret = {};
+ var i;
+
+ for (i = 0; i < keys.length; i++) {
+ ret[keys[i]] = parseInteger(match[cursor + i]);
+ }
+
+ return [ret, null, cursor + i];
+ };
+ } // ISO and SQL parsing
+
+
+ var offsetRegex = /(?:(Z)|([+-]\d\d)(?::?(\d\d))?)/,
+ isoTimeBaseRegex = /(\d\d)(?::?(\d\d)(?::?(\d\d)(?:[.,](\d{1,30}))?)?)?/,
+ isoTimeRegex = RegExp("" + isoTimeBaseRegex.source + offsetRegex.source + "?"),
+ isoTimeExtensionRegex = RegExp("(?:T" + isoTimeRegex.source + ")?"),
+ isoYmdRegex = /([+-]\d{6}|\d{4})(?:-?(\d\d)(?:-?(\d\d))?)?/,
+ isoWeekRegex = /(\d{4})-?W(\d\d)(?:-?(\d))?/,
+ isoOrdinalRegex = /(\d{4})-?(\d{3})/,
+ extractISOWeekData = simpleParse("weekYear", "weekNumber", "weekDay"),
+ extractISOOrdinalData = simpleParse("year", "ordinal"),
+ sqlYmdRegex = /(\d{4})-(\d\d)-(\d\d)/,
+ // dumbed-down version of the ISO one
+ sqlTimeRegex = RegExp(isoTimeBaseRegex.source + " ?(?:" + offsetRegex.source + "|(" + ianaRegex.source + "))?"),
+ sqlTimeExtensionRegex = RegExp("(?: " + sqlTimeRegex.source + ")?");
+
+ function int(match, pos, fallback) {
+ var m = match[pos];
+ return isUndefined(m) ? fallback : parseInteger(m);
+ }
+
+ function extractISOYmd(match, cursor) {
+ var item = {
+ year: int(match, cursor),
+ month: int(match, cursor + 1, 1),
+ day: int(match, cursor + 2, 1)
+ };
+ return [item, null, cursor + 3];
+ }
+
+ function extractISOTime(match, cursor) {
+ var item = {
+ hour: int(match, cursor, 0),
+ minute: int(match, cursor + 1, 0),
+ second: int(match, cursor + 2, 0),
+ millisecond: parseMillis(match[cursor + 3])
+ };
+ return [item, null, cursor + 4];
+ }
+
+ function extractISOOffset(match, cursor) {
+ var local = !match[cursor] && !match[cursor + 1],
+ fullOffset = signedOffset(match[cursor + 1], match[cursor + 2]),
+ zone = local ? null : FixedOffsetZone.instance(fullOffset);
+ return [{}, zone, cursor + 3];
+ }
+
+ function extractIANAZone(match, cursor) {
+ var zone = match[cursor] ? IANAZone.create(match[cursor]) : null;
+ return [{}, zone, cursor + 1];
+ } // ISO duration parsing
+
+
+ var isoDuration = /^-?P(?:(?:(-?\d{1,9})Y)?(?:(-?\d{1,9})M)?(?:(-?\d{1,9})W)?(?:(-?\d{1,9})D)?(?:T(?:(-?\d{1,9})H)?(?:(-?\d{1,9})M)?(?:(-?\d{1,20})(?:[.,](-?\d{1,9}))?S)?)?)$/;
+
+ function extractISODuration(match) {
+ var s = match[0],
+ yearStr = match[1],
+ monthStr = match[2],
+ weekStr = match[3],
+ dayStr = match[4],
+ hourStr = match[5],
+ minuteStr = match[6],
+ secondStr = match[7],
+ millisecondsStr = match[8];
+ var hasNegativePrefix = s[0] === "-";
+
+ var maybeNegate = function maybeNegate(num) {
+ return num && hasNegativePrefix ? -num : num;
+ };
+
+ return [{
+ years: maybeNegate(parseInteger(yearStr)),
+ months: maybeNegate(parseInteger(monthStr)),
+ weeks: maybeNegate(parseInteger(weekStr)),
+ days: maybeNegate(parseInteger(dayStr)),
+ hours: maybeNegate(parseInteger(hourStr)),
+ minutes: maybeNegate(parseInteger(minuteStr)),
+ seconds: maybeNegate(parseInteger(secondStr)),
+ milliseconds: maybeNegate(parseMillis(millisecondsStr))
+ }];
+ } // These are a little braindead. EDT *should* tell us that we're in, say, America/New_York
+ // and not just that we're in -240 *right now*. But since I don't think these are used that often
+ // I'm just going to ignore that
+
+
+ var obsOffsets = {
+ GMT: 0,
+ EDT: -4 * 60,
+ EST: -5 * 60,
+ CDT: -5 * 60,
+ CST: -6 * 60,
+ MDT: -6 * 60,
+ MST: -7 * 60,
+ PDT: -7 * 60,
+ PST: -8 * 60
+ };
+
+ function fromStrings(weekdayStr, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr) {
+ var result = {
+ year: yearStr.length === 2 ? untruncateYear(parseInteger(yearStr)) : parseInteger(yearStr),
+ month: monthsShort.indexOf(monthStr) + 1,
+ day: parseInteger(dayStr),
+ hour: parseInteger(hourStr),
+ minute: parseInteger(minuteStr)
+ };
+ if (secondStr) result.second = parseInteger(secondStr);
+
+ if (weekdayStr) {
+ result.weekday = weekdayStr.length > 3 ? weekdaysLong.indexOf(weekdayStr) + 1 : weekdaysShort.indexOf(weekdayStr) + 1;
+ }
+
+ return result;
+ } // RFC 2822/5322
+
+
+ var rfc2822 = /^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|(?:([+-]\d\d)(\d\d)))$/;
+
+ function extractRFC2822(match) {
+ var weekdayStr = match[1],
+ dayStr = match[2],
+ monthStr = match[3],
+ yearStr = match[4],
+ hourStr = match[5],
+ minuteStr = match[6],
+ secondStr = match[7],
+ obsOffset = match[8],
+ milOffset = match[9],
+ offHourStr = match[10],
+ offMinuteStr = match[11],
+ result = fromStrings(weekdayStr, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr);
+ var offset;
+
+ if (obsOffset) {
+ offset = obsOffsets[obsOffset];
+ } else if (milOffset) {
+ offset = 0;
+ } else {
+ offset = signedOffset(offHourStr, offMinuteStr);
+ }
+
+ return [result, new FixedOffsetZone(offset)];
+ }
+
+ function preprocessRFC2822(s) {
+ // Remove comments and folding whitespace and replace multiple-spaces with a single space
+ return s.replace(/\([^)]*\)|[\n\t]/g, " ").replace(/(\s\s+)/g, " ").trim();
+ } // http date
+
+
+ var rfc1123 = /^(Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d\d) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d\d):(\d\d):(\d\d) GMT$/,
+ rfc850 = /^(Monday|Tuesday|Wedsday|Thursday|Friday|Saturday|Sunday), (\d\d)-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d\d) (\d\d):(\d\d):(\d\d) GMT$/,
+ ascii = /^(Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( \d|\d\d) (\d\d):(\d\d):(\d\d) (\d{4})$/;
+
+ function extractRFC1123Or850(match) {
+ var weekdayStr = match[1],
+ dayStr = match[2],
+ monthStr = match[3],
+ yearStr = match[4],
+ hourStr = match[5],
+ minuteStr = match[6],
+ secondStr = match[7],
+ result = fromStrings(weekdayStr, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr);
+ return [result, FixedOffsetZone.utcInstance];
+ }
+
+ function extractASCII(match) {
+ var weekdayStr = match[1],
+ monthStr = match[2],
+ dayStr = match[3],
+ hourStr = match[4],
+ minuteStr = match[5],
+ secondStr = match[6],
+ yearStr = match[7],
+ result = fromStrings(weekdayStr, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr);
+ return [result, FixedOffsetZone.utcInstance];
+ }
+
+ var isoYmdWithTimeExtensionRegex = combineRegexes(isoYmdRegex, isoTimeExtensionRegex);
+ var isoWeekWithTimeExtensionRegex = combineRegexes(isoWeekRegex, isoTimeExtensionRegex);
+ var isoOrdinalWithTimeExtensionRegex = combineRegexes(isoOrdinalRegex, isoTimeExtensionRegex);
+ var isoTimeCombinedRegex = combineRegexes(isoTimeRegex);
+ var extractISOYmdTimeAndOffset = combineExtractors(extractISOYmd, extractISOTime, extractISOOffset);
+ var extractISOWeekTimeAndOffset = combineExtractors(extractISOWeekData, extractISOTime, extractISOOffset);
+ var extractISOOrdinalDataAndTime = combineExtractors(extractISOOrdinalData, extractISOTime);
+ var extractISOTimeAndOffset = combineExtractors(extractISOTime, extractISOOffset);
+ /**
+ * @private
+ */
+
+ function parseISODate(s) {
+ return parse(s, [isoYmdWithTimeExtensionRegex, extractISOYmdTimeAndOffset], [isoWeekWithTimeExtensionRegex, extractISOWeekTimeAndOffset], [isoOrdinalWithTimeExtensionRegex, extractISOOrdinalDataAndTime], [isoTimeCombinedRegex, extractISOTimeAndOffset]);
+ }
+ function parseRFC2822Date(s) {
+ return parse(preprocessRFC2822(s), [rfc2822, extractRFC2822]);
+ }
+ function parseHTTPDate(s) {
+ return parse(s, [rfc1123, extractRFC1123Or850], [rfc850, extractRFC1123Or850], [ascii, extractASCII]);
+ }
+ function parseISODuration(s) {
+ return parse(s, [isoDuration, extractISODuration]);
+ }
+ var sqlYmdWithTimeExtensionRegex = combineRegexes(sqlYmdRegex, sqlTimeExtensionRegex);
+ var sqlTimeCombinedRegex = combineRegexes(sqlTimeRegex);
+ var extractISOYmdTimeOffsetAndIANAZone = combineExtractors(extractISOYmd, extractISOTime, extractISOOffset, extractIANAZone);
+ var extractISOTimeOffsetAndIANAZone = combineExtractors(extractISOTime, extractISOOffset, extractIANAZone);
+ function parseSQL(s) {
+ return parse(s, [sqlYmdWithTimeExtensionRegex, extractISOYmdTimeOffsetAndIANAZone], [sqlTimeCombinedRegex, extractISOTimeOffsetAndIANAZone]);
+ }
+
+ var INVALID = "Invalid Duration"; // unit conversion constants
+
+ var lowOrderMatrix = {
+ weeks: {
+ days: 7,
+ hours: 7 * 24,
+ minutes: 7 * 24 * 60,
+ seconds: 7 * 24 * 60 * 60,
+ milliseconds: 7 * 24 * 60 * 60 * 1000
+ },
+ days: {
+ hours: 24,
+ minutes: 24 * 60,
+ seconds: 24 * 60 * 60,
+ milliseconds: 24 * 60 * 60 * 1000
+ },
+ hours: {
+ minutes: 60,
+ seconds: 60 * 60,
+ milliseconds: 60 * 60 * 1000
+ },
+ minutes: {
+ seconds: 60,
+ milliseconds: 60 * 1000
+ },
+ seconds: {
+ milliseconds: 1000
+ }
+ },
+ casualMatrix = Object.assign({
+ years: {
+ quarters: 4,
+ months: 12,
+ weeks: 52,
+ days: 365,
+ hours: 365 * 24,
+ minutes: 365 * 24 * 60,
+ seconds: 365 * 24 * 60 * 60,
+ milliseconds: 365 * 24 * 60 * 60 * 1000
+ },
+ quarters: {
+ months: 3,
+ weeks: 13,
+ days: 91,
+ hours: 91 * 24,
+ minutes: 91 * 24 * 60,
+ seconds: 91 * 24 * 60 * 60,
+ milliseconds: 91 * 24 * 60 * 60 * 1000
+ },
+ months: {
+ weeks: 4,
+ days: 30,
+ hours: 30 * 24,
+ minutes: 30 * 24 * 60,
+ seconds: 30 * 24 * 60 * 60,
+ milliseconds: 30 * 24 * 60 * 60 * 1000
+ }
+ }, lowOrderMatrix),
+ daysInYearAccurate = 146097.0 / 400,
+ daysInMonthAccurate = 146097.0 / 4800,
+ accurateMatrix = Object.assign({
+ years: {
+ quarters: 4,
+ months: 12,
+ weeks: daysInYearAccurate / 7,
+ days: daysInYearAccurate,
+ hours: daysInYearAccurate * 24,
+ minutes: daysInYearAccurate * 24 * 60,
+ seconds: daysInYearAccurate * 24 * 60 * 60,
+ milliseconds: daysInYearAccurate * 24 * 60 * 60 * 1000
+ },
+ quarters: {
+ months: 3,
+ weeks: daysInYearAccurate / 28,
+ days: daysInYearAccurate / 4,
+ hours: daysInYearAccurate * 24 / 4,
+ minutes: daysInYearAccurate * 24 * 60 / 4,
+ seconds: daysInYearAccurate * 24 * 60 * 60 / 4,
+ milliseconds: daysInYearAccurate * 24 * 60 * 60 * 1000 / 4
+ },
+ months: {
+ weeks: daysInMonthAccurate / 7,
+ days: daysInMonthAccurate,
+ hours: daysInMonthAccurate * 24,
+ minutes: daysInMonthAccurate * 24 * 60,
+ seconds: daysInMonthAccurate * 24 * 60 * 60,
+ milliseconds: daysInMonthAccurate * 24 * 60 * 60 * 1000
+ }
+ }, lowOrderMatrix); // units ordered by size
+
+ var orderedUnits = ["years", "quarters", "months", "weeks", "days", "hours", "minutes", "seconds", "milliseconds"];
+ var reverseUnits = orderedUnits.slice(0).reverse(); // clone really means "create another instance just like this one, but with these changes"
+
+ function clone(dur, alts, clear) {
+ if (clear === void 0) {
+ clear = false;
+ }
+
+ // deep merge for vals
+ var conf = {
+ values: clear ? alts.values : Object.assign({}, dur.values, alts.values || {}),
+ loc: dur.loc.clone(alts.loc),
+ conversionAccuracy: alts.conversionAccuracy || dur.conversionAccuracy
+ };
+ return new Duration(conf);
+ }
+
+ function antiTrunc(n) {
+ return n < 0 ? Math.floor(n) : Math.ceil(n);
+ } // NB: mutates parameters
+
+
+ function convert(matrix, fromMap, fromUnit, toMap, toUnit) {
+ var conv = matrix[toUnit][fromUnit],
+ raw = fromMap[fromUnit] / conv,
+ sameSign = Math.sign(raw) === Math.sign(toMap[toUnit]),
+ // ok, so this is wild, but see the matrix in the tests
+ added = !sameSign && toMap[toUnit] !== 0 && Math.abs(raw) <= 1 ? antiTrunc(raw) : Math.trunc(raw);
+ toMap[toUnit] += added;
+ fromMap[fromUnit] -= added * conv;
+ } // NB: mutates parameters
+
+
+ function normalizeValues(matrix, vals) {
+ reverseUnits.reduce(function (previous, current) {
+ if (!isUndefined(vals[current])) {
+ if (previous) {
+ convert(matrix, vals, previous, vals, current);
+ }
+
+ return current;
+ } else {
+ return previous;
+ }
+ }, null);
+ }
+ /**
+ * A Duration object represents a period of time, like "2 months" or "1 day, 1 hour". Conceptually, it's just a map of units to their quantities, accompanied by some additional configuration and methods for creating, parsing, interrogating, transforming, and formatting them. They can be used on their own or in conjunction with other Luxon types; for example, you can use {@link DateTime.plus} to add a Duration object to a DateTime, producing another DateTime.
+ *
+ * Here is a brief overview of commonly used methods and getters in Duration:
+ *
+ * * **Creation** To create a Duration, use {@link Duration.fromMillis}, {@link Duration.fromObject}, or {@link Duration.fromISO}.
+ * * **Unit values** See the {@link Duration.years}, {@link Duration.months}, {@link Duration.weeks}, {@link Duration.days}, {@link Duration.hours}, {@link Duration.minutes}, {@link Duration.seconds}, {@link Duration.milliseconds} accessors.
+ * * **Configuration** See {@link Duration.locale} and {@link Duration.numberingSystem} accessors.
+ * * **Transformation** To create new Durations out of old ones use {@link Duration.plus}, {@link Duration.minus}, {@link Duration.normalize}, {@link Duration.set}, {@link Duration.reconfigure}, {@link Duration.shiftTo}, and {@link Duration.negate}.
+ * * **Output** To convert the Duration into other representations, see {@link Duration.as}, {@link Duration.toISO}, {@link Duration.toFormat}, and {@link Duration.toJSON}
+ *
+ * There's are more methods documented below. In addition, for more information on subtler topics like internationalization and validity, see the external documentation.
+ */
+
+
+ var Duration = /*#__PURE__*/function () {
+ /**
+ * @private
+ */
+ function Duration(config) {
+ var accurate = config.conversionAccuracy === "longterm" || false;
+ /**
+ * @access private
+ */
+
+ this.values = config.values;
+ /**
+ * @access private
+ */
+
+ this.loc = config.loc || Locale.create();
+ /**
+ * @access private
+ */
+
+ this.conversionAccuracy = accurate ? "longterm" : "casual";
+ /**
+ * @access private
+ */
+
+ this.invalid = config.invalid || null;
+ /**
+ * @access private
+ */
+
+ this.matrix = accurate ? accurateMatrix : casualMatrix;
+ /**
+ * @access private
+ */
+
+ this.isLuxonDuration = true;
+ }
+ /**
+ * Create Duration from a number of milliseconds.
+ * @param {number} count of milliseconds
+ * @param {Object} opts - options for parsing
+ * @param {string} [opts.locale='en-US'] - the locale to use
+ * @param {string} opts.numberingSystem - the numbering system to use
+ * @param {string} [opts.conversionAccuracy='casual'] - the conversion system to use
+ * @return {Duration}
+ */
+
+
+ Duration.fromMillis = function fromMillis(count, opts) {
+ return Duration.fromObject(Object.assign({
+ milliseconds: count
+ }, opts));
+ }
+ /**
+ * Create a Duration from a Javascript object with keys like 'years' and 'hours.
+ * If this object is empty then a zero milliseconds duration is returned.
+ * @param {Object} obj - the object to create the DateTime from
+ * @param {number} obj.years
+ * @param {number} obj.quarters
+ * @param {number} obj.months
+ * @param {number} obj.weeks
+ * @param {number} obj.days
+ * @param {number} obj.hours
+ * @param {number} obj.minutes
+ * @param {number} obj.seconds
+ * @param {number} obj.milliseconds
+ * @param {string} [obj.locale='en-US'] - the locale to use
+ * @param {string} obj.numberingSystem - the numbering system to use
+ * @param {string} [obj.conversionAccuracy='casual'] - the conversion system to use
+ * @return {Duration}
+ */
+ ;
+
+ Duration.fromObject = function fromObject(obj) {
+ if (obj == null || typeof obj !== "object") {
+ throw new InvalidArgumentError("Duration.fromObject: argument expected to be an object, got " + (obj === null ? "null" : typeof obj));
+ }
+
+ return new Duration({
+ values: normalizeObject(obj, Duration.normalizeUnit, ["locale", "numberingSystem", "conversionAccuracy", "zone" // a bit of debt; it's super inconvenient internally not to be able to blindly pass this
+ ]),
+ loc: Locale.fromObject(obj),
+ conversionAccuracy: obj.conversionAccuracy
+ });
+ }
+ /**
+ * Create a Duration from an ISO 8601 duration string.
+ * @param {string} text - text to parse
+ * @param {Object} opts - options for parsing
+ * @param {string} [opts.locale='en-US'] - the locale to use
+ * @param {string} opts.numberingSystem - the numbering system to use
+ * @param {string} [opts.conversionAccuracy='casual'] - the conversion system to use
+ * @see https://en.wikipedia.org/wiki/ISO_8601#Durations
+ * @example Duration.fromISO('P3Y6M1W4DT12H30M5S').toObject() //=> { years: 3, months: 6, weeks: 1, days: 4, hours: 12, minutes: 30, seconds: 5 }
+ * @example Duration.fromISO('PT23H').toObject() //=> { hours: 23 }
+ * @example Duration.fromISO('P5Y3M').toObject() //=> { years: 5, months: 3 }
+ * @return {Duration}
+ */
+ ;
+
+ Duration.fromISO = function fromISO(text, opts) {
+ var _parseISODuration = parseISODuration(text),
+ parsed = _parseISODuration[0];
+
+ if (parsed) {
+ var obj = Object.assign(parsed, opts);
+ return Duration.fromObject(obj);
+ } else {
+ return Duration.invalid("unparsable", "the input \"" + text + "\" can't be parsed as ISO 8601");
+ }
+ }
+ /**
+ * Create an invalid Duration.
+ * @param {string} reason - simple string of why this datetime is invalid. Should not contain parameters or anything else data-dependent
+ * @param {string} [explanation=null] - longer explanation, may include parameters and other useful debugging information
+ * @return {Duration}
+ */
+ ;
+
+ Duration.invalid = function invalid(reason, explanation) {
+ if (explanation === void 0) {
+ explanation = null;
+ }
+
+ if (!reason) {
+ throw new InvalidArgumentError("need to specify a reason the Duration is invalid");
+ }
+
+ var invalid = reason instanceof Invalid ? reason : new Invalid(reason, explanation);
+
+ if (Settings.throwOnInvalid) {
+ throw new InvalidDurationError(invalid);
+ } else {
+ return new Duration({
+ invalid: invalid
+ });
+ }
+ }
+ /**
+ * @private
+ */
+ ;
+
+ Duration.normalizeUnit = function normalizeUnit(unit) {
+ var normalized = {
+ year: "years",
+ years: "years",
+ quarter: "quarters",
+ quarters: "quarters",
+ month: "months",
+ months: "months",
+ week: "weeks",
+ weeks: "weeks",
+ day: "days",
+ days: "days",
+ hour: "hours",
+ hours: "hours",
+ minute: "minutes",
+ minutes: "minutes",
+ second: "seconds",
+ seconds: "seconds",
+ millisecond: "milliseconds",
+ milliseconds: "milliseconds"
+ }[unit ? unit.toLowerCase() : unit];
+ if (!normalized) throw new InvalidUnitError(unit);
+ return normalized;
+ }
+ /**
+ * Check if an object is a Duration. Works across context boundaries
+ * @param {object} o
+ * @return {boolean}
+ */
+ ;
+
+ Duration.isDuration = function isDuration(o) {
+ return o && o.isLuxonDuration || false;
+ }
+ /**
+ * Get the locale of a Duration, such 'en-GB'
+ * @type {string}
+ */
+ ;
+
+ var _proto = Duration.prototype;
+
+ /**
+ * Returns a string representation of this Duration formatted according to the specified format string. You may use these tokens:
+ * * `S` for milliseconds
+ * * `s` for seconds
+ * * `m` for minutes
+ * * `h` for hours
+ * * `d` for days
+ * * `M` for months
+ * * `y` for years
+ * Notes:
+ * * Add padding by repeating the token, e.g. "yy" pads the years to two digits, "hhhh" pads the hours out to four digits
+ * * The duration will be converted to the set of units in the format string using {@link Duration.shiftTo} and the Durations's conversion accuracy setting.
+ * @param {string} fmt - the format string
+ * @param {Object} opts - options
+ * @param {boolean} [opts.floor=true] - floor numerical values
+ * @example Duration.fromObject({ years: 1, days: 6, seconds: 2 }).toFormat("y d s") //=> "1 6 2"
+ * @example Duration.fromObject({ years: 1, days: 6, seconds: 2 }).toFormat("yy dd sss") //=> "01 06 002"
+ * @example Duration.fromObject({ years: 1, days: 6, seconds: 2 }).toFormat("M S") //=> "12 518402000"
+ * @return {string}
+ */
+ _proto.toFormat = function toFormat(fmt, opts) {
+ if (opts === void 0) {
+ opts = {};
+ }
+
+ // reverse-compat since 1.2; we always round down now, never up, and we do it by default
+ var fmtOpts = Object.assign({}, opts, {
+ floor: opts.round !== false && opts.floor !== false
+ });
+ return this.isValid ? Formatter.create(this.loc, fmtOpts).formatDurationFromString(this, fmt) : INVALID;
+ }
+ /**
+ * Returns a Javascript object with this Duration's values.
+ * @param opts - options for generating the object
+ * @param {boolean} [opts.includeConfig=false] - include configuration attributes in the output
+ * @example Duration.fromObject({ years: 1, days: 6, seconds: 2 }).toObject() //=> { years: 1, days: 6, seconds: 2 }
+ * @return {Object}
+ */
+ ;
+
+ _proto.toObject = function toObject(opts) {
+ if (opts === void 0) {
+ opts = {};
+ }
+
+ if (!this.isValid) return {};
+ var base = Object.assign({}, this.values);
+
+ if (opts.includeConfig) {
+ base.conversionAccuracy = this.conversionAccuracy;
+ base.numberingSystem = this.loc.numberingSystem;
+ base.locale = this.loc.locale;
+ }
+
+ return base;
+ }
+ /**
+ * Returns an ISO 8601-compliant string representation of this Duration.
+ * @see https://en.wikipedia.org/wiki/ISO_8601#Durations
+ * @example Duration.fromObject({ years: 3, seconds: 45 }).toISO() //=> 'P3YT45S'
+ * @example Duration.fromObject({ months: 4, seconds: 45 }).toISO() //=> 'P4MT45S'
+ * @example Duration.fromObject({ months: 5 }).toISO() //=> 'P5M'
+ * @example Duration.fromObject({ minutes: 5 }).toISO() //=> 'PT5M'
+ * @example Duration.fromObject({ milliseconds: 6 }).toISO() //=> 'PT0.006S'
+ * @return {string}
+ */
+ ;
+
+ _proto.toISO = function toISO() {
+ // we could use the formatter, but this is an easier way to get the minimum string
+ if (!this.isValid) return null;
+ var s = "P";
+ if (this.years !== 0) s += this.years + "Y";
+ if (this.months !== 0 || this.quarters !== 0) s += this.months + this.quarters * 3 + "M";
+ if (this.weeks !== 0) s += this.weeks + "W";
+ if (this.days !== 0) s += this.days + "D";
+ if (this.hours !== 0 || this.minutes !== 0 || this.seconds !== 0 || this.milliseconds !== 0) s += "T";
+ if (this.hours !== 0) s += this.hours + "H";
+ if (this.minutes !== 0) s += this.minutes + "M";
+ if (this.seconds !== 0 || this.milliseconds !== 0) // this will handle "floating point madness" by removing extra decimal places
+ // https://stackoverflow.com/questions/588004/is-floating-point-math-broken
+ s += roundTo(this.seconds + this.milliseconds / 1000, 3) + "S";
+ if (s === "P") s += "T0S";
+ return s;
+ }
+ /**
+ * Returns an ISO 8601 representation of this Duration appropriate for use in JSON.
+ * @return {string}
+ */
+ ;
+
+ _proto.toJSON = function toJSON() {
+ return this.toISO();
+ }
+ /**
+ * Returns an ISO 8601 representation of this Duration appropriate for use in debugging.
+ * @return {string}
+ */
+ ;
+
+ _proto.toString = function toString() {
+ return this.toISO();
+ }
+ /**
+ * Returns an milliseconds value of this Duration.
+ * @return {number}
+ */
+ ;
+
+ _proto.valueOf = function valueOf() {
+ return this.as("milliseconds");
+ }
+ /**
+ * Make this Duration longer by the specified amount. Return a newly-constructed Duration.
+ * @param {Duration|Object|number} duration - The amount to add. Either a Luxon Duration, a number of milliseconds, the object argument to Duration.fromObject()
+ * @return {Duration}
+ */
+ ;
+
+ _proto.plus = function plus(duration) {
+ if (!this.isValid) return this;
+ var dur = friendlyDuration(duration),
+ result = {};
+
+ for (var _iterator = _createForOfIteratorHelperLoose(orderedUnits), _step; !(_step = _iterator()).done;) {
+ var k = _step.value;
+
+ if (hasOwnProperty(dur.values, k) || hasOwnProperty(this.values, k)) {
+ result[k] = dur.get(k) + this.get(k);
+ }
+ }
+
+ return clone(this, {
+ values: result
+ }, true);
+ }
+ /**
+ * Make this Duration shorter by the specified amount. Return a newly-constructed Duration.
+ * @param {Duration|Object|number} duration - The amount to subtract. Either a Luxon Duration, a number of milliseconds, the object argument to Duration.fromObject()
+ * @return {Duration}
+ */
+ ;
+
+ _proto.minus = function minus(duration) {
+ if (!this.isValid) return this;
+ var dur = friendlyDuration(duration);
+ return this.plus(dur.negate());
+ }
+ /**
+ * Scale this Duration by the specified amount. Return a newly-constructed Duration.
+ * @param {function} fn - The function to apply to each unit. Arity is 1 or 2: the value of the unit and, optionally, the unit name. Must return a number.
+ * @example Duration.fromObject({ hours: 1, minutes: 30 }).mapUnit(x => x * 2) //=> { hours: 2, minutes: 60 }
+ * @example Duration.fromObject({ hours: 1, minutes: 30 }).mapUnit((x, u) => u === "hour" ? x * 2 : x) //=> { hours: 2, minutes: 30 }
+ * @return {Duration}
+ */
+ ;
+
+ _proto.mapUnits = function mapUnits(fn) {
+ if (!this.isValid) return this;
+ var result = {};
+
+ for (var _i = 0, _Object$keys = Object.keys(this.values); _i < _Object$keys.length; _i++) {
+ var k = _Object$keys[_i];
+ result[k] = asNumber(fn(this.values[k], k));
+ }
+
+ return clone(this, {
+ values: result
+ }, true);
+ }
+ /**
+ * Get the value of unit.
+ * @param {string} unit - a unit such as 'minute' or 'day'
+ * @example Duration.fromObject({years: 2, days: 3}).years //=> 2
+ * @example Duration.fromObject({years: 2, days: 3}).months //=> 0
+ * @example Duration.fromObject({years: 2, days: 3}).days //=> 3
+ * @return {number}
+ */
+ ;
+
+ _proto.get = function get(unit) {
+ return this[Duration.normalizeUnit(unit)];
+ }
+ /**
+ * "Set" the values of specified units. Return a newly-constructed Duration.
+ * @param {Object} values - a mapping of units to numbers
+ * @example dur.set({ years: 2017 })
+ * @example dur.set({ hours: 8, minutes: 30 })
+ * @return {Duration}
+ */
+ ;
+
+ _proto.set = function set(values) {
+ if (!this.isValid) return this;
+ var mixed = Object.assign(this.values, normalizeObject(values, Duration.normalizeUnit, []));
+ return clone(this, {
+ values: mixed
+ });
+ }
+ /**
+ * "Set" the locale and/or numberingSystem. Returns a newly-constructed Duration.
+ * @example dur.reconfigure({ locale: 'en-GB' })
+ * @return {Duration}
+ */
+ ;
+
+ _proto.reconfigure = function reconfigure(_temp) {
+ var _ref = _temp === void 0 ? {} : _temp,
+ locale = _ref.locale,
+ numberingSystem = _ref.numberingSystem,
+ conversionAccuracy = _ref.conversionAccuracy;
+
+ var loc = this.loc.clone({
+ locale: locale,
+ numberingSystem: numberingSystem
+ }),
+ opts = {
+ loc: loc
+ };
+
+ if (conversionAccuracy) {
+ opts.conversionAccuracy = conversionAccuracy;
+ }
+
+ return clone(this, opts);
+ }
+ /**
+ * Return the length of the duration in the specified unit.
+ * @param {string} unit - a unit such as 'minutes' or 'days'
+ * @example Duration.fromObject({years: 1}).as('days') //=> 365
+ * @example Duration.fromObject({years: 1}).as('months') //=> 12
+ * @example Duration.fromObject({hours: 60}).as('days') //=> 2.5
+ * @return {number}
+ */
+ ;
+
+ _proto.as = function as(unit) {
+ return this.isValid ? this.shiftTo(unit).get(unit) : NaN;
+ }
+ /**
+ * Reduce this Duration to its canonical representation in its current units.
+ * @example Duration.fromObject({ years: 2, days: 5000 }).normalize().toObject() //=> { years: 15, days: 255 }
+ * @example Duration.fromObject({ hours: 12, minutes: -45 }).normalize().toObject() //=> { hours: 11, minutes: 15 }
+ * @return {Duration}
+ */
+ ;
+
+ _proto.normalize = function normalize() {
+ if (!this.isValid) return this;
+ var vals = this.toObject();
+ normalizeValues(this.matrix, vals);
+ return clone(this, {
+ values: vals
+ }, true);
+ }
+ /**
+ * Convert this Duration into its representation in a different set of units.
+ * @example Duration.fromObject({ hours: 1, seconds: 30 }).shiftTo('minutes', 'milliseconds').toObject() //=> { minutes: 60, milliseconds: 30000 }
+ * @return {Duration}
+ */
+ ;
+
+ _proto.shiftTo = function shiftTo() {
+ for (var _len = arguments.length, units = new Array(_len), _key = 0; _key < _len; _key++) {
+ units[_key] = arguments[_key];
+ }
+
+ if (!this.isValid) return this;
+
+ if (units.length === 0) {
+ return this;
+ }
+
+ units = units.map(function (u) {
+ return Duration.normalizeUnit(u);
+ });
+ var built = {},
+ accumulated = {},
+ vals = this.toObject();
+ var lastUnit;
+
+ for (var _iterator2 = _createForOfIteratorHelperLoose(orderedUnits), _step2; !(_step2 = _iterator2()).done;) {
+ var k = _step2.value;
+
+ if (units.indexOf(k) >= 0) {
+ lastUnit = k;
+ var own = 0; // anything we haven't boiled down yet should get boiled to this unit
+
+ for (var ak in accumulated) {
+ own += this.matrix[ak][k] * accumulated[ak];
+ accumulated[ak] = 0;
+ } // plus anything that's already in this unit
+
+
+ if (isNumber(vals[k])) {
+ own += vals[k];
+ }
+
+ var i = Math.trunc(own);
+ built[k] = i;
+ accumulated[k] = own - i; // we'd like to absorb these fractions in another unit
+ // plus anything further down the chain that should be rolled up in to this
+
+ for (var down in vals) {
+ if (orderedUnits.indexOf(down) > orderedUnits.indexOf(k)) {
+ convert(this.matrix, vals, down, built, k);
+ }
+ } // otherwise, keep it in the wings to boil it later
+
+ } else if (isNumber(vals[k])) {
+ accumulated[k] = vals[k];
+ }
+ } // anything leftover becomes the decimal for the last unit
+ // lastUnit must be defined since units is not empty
+
+
+ for (var key in accumulated) {
+ if (accumulated[key] !== 0) {
+ built[lastUnit] += key === lastUnit ? accumulated[key] : accumulated[key] / this.matrix[lastUnit][key];
+ }
+ }
+
+ return clone(this, {
+ values: built
+ }, true).normalize();
+ }
+ /**
+ * Return the negative of this Duration.
+ * @example Duration.fromObject({ hours: 1, seconds: 30 }).negate().toObject() //=> { hours: -1, seconds: -30 }
+ * @return {Duration}
+ */
+ ;
+
+ _proto.negate = function negate() {
+ if (!this.isValid) return this;
+ var negated = {};
+
+ for (var _i2 = 0, _Object$keys2 = Object.keys(this.values); _i2 < _Object$keys2.length; _i2++) {
+ var k = _Object$keys2[_i2];
+ negated[k] = -this.values[k];
+ }
+
+ return clone(this, {
+ values: negated
+ }, true);
+ }
+ /**
+ * Get the years.
+ * @type {number}
+ */
+ ;
+
+ /**
+ * Equality check
+ * Two Durations are equal iff they have the same units and the same values for each unit.
+ * @param {Duration} other
+ * @return {boolean}
+ */
+ _proto.equals = function equals(other) {
+ if (!this.isValid || !other.isValid) {
+ return false;
+ }
+
+ if (!this.loc.equals(other.loc)) {
+ return false;
+ }
+
+ for (var _iterator3 = _createForOfIteratorHelperLoose(orderedUnits), _step3; !(_step3 = _iterator3()).done;) {
+ var u = _step3.value;
+
+ if (this.values[u] !== other.values[u]) {
+ return false;
+ }
+ }
+
+ return true;
+ };
+
+ _createClass(Duration, [{
+ key: "locale",
+ get: function get() {
+ return this.isValid ? this.loc.locale : null;
+ }
+ /**
+ * Get the numbering system of a Duration, such 'beng'. The numbering system is used when formatting the Duration
+ *
+ * @type {string}
+ */
+
+ }, {
+ key: "numberingSystem",
+ get: function get() {
+ return this.isValid ? this.loc.numberingSystem : null;
+ }
+ }, {
+ key: "years",
+ get: function get() {
+ return this.isValid ? this.values.years || 0 : NaN;
+ }
+ /**
+ * Get the quarters.
+ * @type {number}
+ */
+
+ }, {
+ key: "quarters",
+ get: function get() {
+ return this.isValid ? this.values.quarters || 0 : NaN;
+ }
+ /**
+ * Get the months.
+ * @type {number}
+ */
+
+ }, {
+ key: "months",
+ get: function get() {
+ return this.isValid ? this.values.months || 0 : NaN;
+ }
+ /**
+ * Get the weeks
+ * @type {number}
+ */
+
+ }, {
+ key: "weeks",
+ get: function get() {
+ return this.isValid ? this.values.weeks || 0 : NaN;
+ }
+ /**
+ * Get the days.
+ * @type {number}
+ */
+
+ }, {
+ key: "days",
+ get: function get() {
+ return this.isValid ? this.values.days || 0 : NaN;
+ }
+ /**
+ * Get the hours.
+ * @type {number}
+ */
+
+ }, {
+ key: "hours",
+ get: function get() {
+ return this.isValid ? this.values.hours || 0 : NaN;
+ }
+ /**
+ * Get the minutes.
+ * @type {number}
+ */
+
+ }, {
+ key: "minutes",
+ get: function get() {
+ return this.isValid ? this.values.minutes || 0 : NaN;
+ }
+ /**
+ * Get the seconds.
+ * @return {number}
+ */
+
+ }, {
+ key: "seconds",
+ get: function get() {
+ return this.isValid ? this.values.seconds || 0 : NaN;
+ }
+ /**
+ * Get the milliseconds.
+ * @return {number}
+ */
+
+ }, {
+ key: "milliseconds",
+ get: function get() {
+ return this.isValid ? this.values.milliseconds || 0 : NaN;
+ }
+ /**
+ * Returns whether the Duration is invalid. Invalid durations are returned by diff operations
+ * on invalid DateTimes or Intervals.
+ * @return {boolean}
+ */
+
+ }, {
+ key: "isValid",
+ get: function get() {
+ return this.invalid === null;
+ }
+ /**
+ * Returns an error code if this Duration became invalid, or null if the Duration is valid
+ * @return {string}
+ */
+
+ }, {
+ key: "invalidReason",
+ get: function get() {
+ return this.invalid ? this.invalid.reason : null;
+ }
+ /**
+ * Returns an explanation of why this Duration became invalid, or null if the Duration is valid
+ * @type {string}
+ */
+
+ }, {
+ key: "invalidExplanation",
+ get: function get() {
+ return this.invalid ? this.invalid.explanation : null;
+ }
+ }]);
+
+ return Duration;
+ }();
+ function friendlyDuration(durationish) {
+ if (isNumber(durationish)) {
+ return Duration.fromMillis(durationish);
+ } else if (Duration.isDuration(durationish)) {
+ return durationish;
+ } else if (typeof durationish === "object") {
+ return Duration.fromObject(durationish);
+ } else {
+ throw new InvalidArgumentError("Unknown duration argument " + durationish + " of type " + typeof durationish);
+ }
+ }
+
+ var INVALID$1 = "Invalid Interval"; // checks if the start is equal to or before the end
+
+ function validateStartEnd(start, end) {
+ if (!start || !start.isValid) {
+ return Interval.invalid("missing or invalid start");
+ } else if (!end || !end.isValid) {
+ return Interval.invalid("missing or invalid end");
+ } else if (end < start) {
+ return Interval.invalid("end before start", "The end of an interval must be after its start, but you had start=" + start.toISO() + " and end=" + end.toISO());
+ } else {
+ return null;
+ }
+ }
+ /**
+ * An Interval object represents a half-open interval of time, where each endpoint is a {@link DateTime}. Conceptually, it's a container for those two endpoints, accompanied by methods for creating, parsing, interrogating, comparing, transforming, and formatting them.
+ *
+ * Here is a brief overview of the most commonly used methods and getters in Interval:
+ *
+ * * **Creation** To create an Interval, use {@link fromDateTimes}, {@link after}, {@link before}, or {@link fromISO}.
+ * * **Accessors** Use {@link start} and {@link end} to get the start and end.
+ * * **Interrogation** To analyze the Interval, use {@link count}, {@link length}, {@link hasSame}, {@link contains}, {@link isAfter}, or {@link isBefore}.
+ * * **Transformation** To create other Intervals out of this one, use {@link set}, {@link splitAt}, {@link splitBy}, {@link divideEqually}, {@link merge}, {@link xor}, {@link union}, {@link intersection}, or {@link difference}.
+ * * **Comparison** To compare this Interval to another one, use {@link equals}, {@link overlaps}, {@link abutsStart}, {@link abutsEnd}, {@link engulfs}.
+ * * **Output** To convert the Interval into other representations, see {@link toString}, {@link toISO}, {@link toISODate}, {@link toISOTime}, {@link toFormat}, and {@link toDuration}.
+ */
+
+
+ var Interval = /*#__PURE__*/function () {
+ /**
+ * @private
+ */
+ function Interval(config) {
+ /**
+ * @access private
+ */
+ this.s = config.start;
+ /**
+ * @access private
+ */
+
+ this.e = config.end;
+ /**
+ * @access private
+ */
+
+ this.invalid = config.invalid || null;
+ /**
+ * @access private
+ */
+
+ this.isLuxonInterval = true;
+ }
+ /**
+ * Create an invalid Interval.
+ * @param {string} reason - simple string of why this Interval is invalid. Should not contain parameters or anything else data-dependent
+ * @param {string} [explanation=null] - longer explanation, may include parameters and other useful debugging information
+ * @return {Interval}
+ */
+
+
+ Interval.invalid = function invalid(reason, explanation) {
+ if (explanation === void 0) {
+ explanation = null;
+ }
+
+ if (!reason) {
+ throw new InvalidArgumentError("need to specify a reason the Interval is invalid");
+ }
+
+ var invalid = reason instanceof Invalid ? reason : new Invalid(reason, explanation);
+
+ if (Settings.throwOnInvalid) {
+ throw new InvalidIntervalError(invalid);
+ } else {
+ return new Interval({
+ invalid: invalid
+ });
+ }
+ }
+ /**
+ * Create an Interval from a start DateTime and an end DateTime. Inclusive of the start but not the end.
+ * @param {DateTime|Date|Object} start
+ * @param {DateTime|Date|Object} end
+ * @return {Interval}
+ */
+ ;
+
+ Interval.fromDateTimes = function fromDateTimes(start, end) {
+ var builtStart = friendlyDateTime(start),
+ builtEnd = friendlyDateTime(end);
+ var validateError = validateStartEnd(builtStart, builtEnd);
+
+ if (validateError == null) {
+ return new Interval({
+ start: builtStart,
+ end: builtEnd
+ });
+ } else {
+ return validateError;
+ }
+ }
+ /**
+ * Create an Interval from a start DateTime and a Duration to extend to.
+ * @param {DateTime|Date|Object} start
+ * @param {Duration|Object|number} duration - the length of the Interval.
+ * @return {Interval}
+ */
+ ;
+
+ Interval.after = function after(start, duration) {
+ var dur = friendlyDuration(duration),
+ dt = friendlyDateTime(start);
+ return Interval.fromDateTimes(dt, dt.plus(dur));
+ }
+ /**
+ * Create an Interval from an end DateTime and a Duration to extend backwards to.
+ * @param {DateTime|Date|Object} end
+ * @param {Duration|Object|number} duration - the length of the Interval.
+ * @return {Interval}
+ */
+ ;
+
+ Interval.before = function before(end, duration) {
+ var dur = friendlyDuration(duration),
+ dt = friendlyDateTime(end);
+ return Interval.fromDateTimes(dt.minus(dur), dt);
+ }
+ /**
+ * Create an Interval from an ISO 8601 string.
+ * Accepts `
/`, `/`, and `/` formats.
+ * @param {string} text - the ISO string to parse
+ * @param {Object} [opts] - options to pass {@link DateTime.fromISO} and optionally {@link Duration.fromISO}
+ * @see https://en.wikipedia.org/wiki/ISO_8601#Time_intervals
+ * @return {Interval}
+ */
+ ;
+
+ Interval.fromISO = function fromISO(text, opts) {
+ var _split = (text || "").split("/", 2),
+ s = _split[0],
+ e = _split[1];
+
+ if (s && e) {
+ var start, startIsValid;
+
+ try {
+ start = DateTime.fromISO(s, opts);
+ startIsValid = start.isValid;
+ } catch (e) {
+ startIsValid = false;
+ }
+
+ var end, endIsValid;
+
+ try {
+ end = DateTime.fromISO(e, opts);
+ endIsValid = end.isValid;
+ } catch (e) {
+ endIsValid = false;
+ }
+
+ if (startIsValid && endIsValid) {
+ return Interval.fromDateTimes(start, end);
+ }
+
+ if (startIsValid) {
+ var dur = Duration.fromISO(e, opts);
+
+ if (dur.isValid) {
+ return Interval.after(start, dur);
+ }
+ } else if (endIsValid) {
+ var _dur = Duration.fromISO(s, opts);
+
+ if (_dur.isValid) {
+ return Interval.before(end, _dur);
+ }
+ }
+ }
+
+ return Interval.invalid("unparsable", "the input \"" + text + "\" can't be parsed as ISO 8601");
+ }
+ /**
+ * Check if an object is an Interval. Works across context boundaries
+ * @param {object} o
+ * @return {boolean}
+ */
+ ;
+
+ Interval.isInterval = function isInterval(o) {
+ return o && o.isLuxonInterval || false;
+ }
+ /**
+ * Returns the start of the Interval
+ * @type {DateTime}
+ */
+ ;
+
+ var _proto = Interval.prototype;
+
+ /**
+ * Returns the length of the Interval in the specified unit.
+ * @param {string} unit - the unit (such as 'hours' or 'days') to return the length in.
+ * @return {number}
+ */
+ _proto.length = function length(unit) {
+ if (unit === void 0) {
+ unit = "milliseconds";
+ }
+
+ return this.isValid ? this.toDuration.apply(this, [unit]).get(unit) : NaN;
+ }
+ /**
+ * Returns the count of minutes, hours, days, months, or years included in the Interval, even in part.
+ * Unlike {@link length} this counts sections of the calendar, not periods of time, e.g. specifying 'day'
+ * asks 'what dates are included in this interval?', not 'how many days long is this interval?'
+ * @param {string} [unit='milliseconds'] - the unit of time to count.
+ * @return {number}
+ */
+ ;
+
+ _proto.count = function count(unit) {
+ if (unit === void 0) {
+ unit = "milliseconds";
+ }
+
+ if (!this.isValid) return NaN;
+ var start = this.start.startOf(unit),
+ end = this.end.startOf(unit);
+ return Math.floor(end.diff(start, unit).get(unit)) + 1;
+ }
+ /**
+ * Returns whether this Interval's start and end are both in the same unit of time
+ * @param {string} unit - the unit of time to check sameness on
+ * @return {boolean}
+ */
+ ;
+
+ _proto.hasSame = function hasSame(unit) {
+ return this.isValid ? this.isEmpty() || this.e.minus(1).hasSame(this.s, unit) : false;
+ }
+ /**
+ * Return whether this Interval has the same start and end DateTimes.
+ * @return {boolean}
+ */
+ ;
+
+ _proto.isEmpty = function isEmpty() {
+ return this.s.valueOf() === this.e.valueOf();
+ }
+ /**
+ * Return whether this Interval's start is after the specified DateTime.
+ * @param {DateTime} dateTime
+ * @return {boolean}
+ */
+ ;
+
+ _proto.isAfter = function isAfter(dateTime) {
+ if (!this.isValid) return false;
+ return this.s > dateTime;
+ }
+ /**
+ * Return whether this Interval's end is before the specified DateTime.
+ * @param {DateTime} dateTime
+ * @return {boolean}
+ */
+ ;
+
+ _proto.isBefore = function isBefore(dateTime) {
+ if (!this.isValid) return false;
+ return this.e <= dateTime;
+ }
+ /**
+ * Return whether this Interval contains the specified DateTime.
+ * @param {DateTime} dateTime
+ * @return {boolean}
+ */
+ ;
+
+ _proto.contains = function contains(dateTime) {
+ if (!this.isValid) return false;
+ return this.s <= dateTime && this.e > dateTime;
+ }
+ /**
+ * "Sets" the start and/or end dates. Returns a newly-constructed Interval.
+ * @param {Object} values - the values to set
+ * @param {DateTime} values.start - the starting DateTime
+ * @param {DateTime} values.end - the ending DateTime
+ * @return {Interval}
+ */
+ ;
+
+ _proto.set = function set(_temp) {
+ var _ref = _temp === void 0 ? {} : _temp,
+ start = _ref.start,
+ end = _ref.end;
+
+ if (!this.isValid) return this;
+ return Interval.fromDateTimes(start || this.s, end || this.e);
+ }
+ /**
+ * Split this Interval at each of the specified DateTimes
+ * @param {...[DateTime]} dateTimes - the unit of time to count.
+ * @return {[Interval]}
+ */
+ ;
+
+ _proto.splitAt = function splitAt() {
+ var _this = this;
+
+ if (!this.isValid) return [];
+
+ for (var _len = arguments.length, dateTimes = new Array(_len), _key = 0; _key < _len; _key++) {
+ dateTimes[_key] = arguments[_key];
+ }
+
+ var sorted = dateTimes.map(friendlyDateTime).filter(function (d) {
+ return _this.contains(d);
+ }).sort(),
+ results = [];
+ var s = this.s,
+ i = 0;
+
+ while (s < this.e) {
+ var added = sorted[i] || this.e,
+ next = +added > +this.e ? this.e : added;
+ results.push(Interval.fromDateTimes(s, next));
+ s = next;
+ i += 1;
+ }
+
+ return results;
+ }
+ /**
+ * Split this Interval into smaller Intervals, each of the specified length.
+ * Left over time is grouped into a smaller interval
+ * @param {Duration|Object|number} duration - The length of each resulting interval.
+ * @return {[Interval]}
+ */
+ ;
+
+ _proto.splitBy = function splitBy(duration) {
+ var dur = friendlyDuration(duration);
+
+ if (!this.isValid || !dur.isValid || dur.as("milliseconds") === 0) {
+ return [];
+ }
+
+ var s = this.s,
+ added,
+ next;
+ var results = [];
+
+ while (s < this.e) {
+ added = s.plus(dur);
+ next = +added > +this.e ? this.e : added;
+ results.push(Interval.fromDateTimes(s, next));
+ s = next;
+ }
+
+ return results;
+ }
+ /**
+ * Split this Interval into the specified number of smaller intervals.
+ * @param {number} numberOfParts - The number of Intervals to divide the Interval into.
+ * @return {[Interval]}
+ */
+ ;
+
+ _proto.divideEqually = function divideEqually(numberOfParts) {
+ if (!this.isValid) return [];
+ return this.splitBy(this.length() / numberOfParts).slice(0, numberOfParts);
+ }
+ /**
+ * Return whether this Interval overlaps with the specified Interval
+ * @param {Interval} other
+ * @return {boolean}
+ */
+ ;
+
+ _proto.overlaps = function overlaps(other) {
+ return this.e > other.s && this.s < other.e;
+ }
+ /**
+ * Return whether this Interval's end is adjacent to the specified Interval's start.
+ * @param {Interval} other
+ * @return {boolean}
+ */
+ ;
+
+ _proto.abutsStart = function abutsStart(other) {
+ if (!this.isValid) return false;
+ return +this.e === +other.s;
+ }
+ /**
+ * Return whether this Interval's start is adjacent to the specified Interval's end.
+ * @param {Interval} other
+ * @return {boolean}
+ */
+ ;
+
+ _proto.abutsEnd = function abutsEnd(other) {
+ if (!this.isValid) return false;
+ return +other.e === +this.s;
+ }
+ /**
+ * Return whether this Interval engulfs the start and end of the specified Interval.
+ * @param {Interval} other
+ * @return {boolean}
+ */
+ ;
+
+ _proto.engulfs = function engulfs(other) {
+ if (!this.isValid) return false;
+ return this.s <= other.s && this.e >= other.e;
+ }
+ /**
+ * Return whether this Interval has the same start and end as the specified Interval.
+ * @param {Interval} other
+ * @return {boolean}
+ */
+ ;
+
+ _proto.equals = function equals(other) {
+ if (!this.isValid || !other.isValid) {
+ return false;
+ }
+
+ return this.s.equals(other.s) && this.e.equals(other.e);
+ }
+ /**
+ * Return an Interval representing the intersection of this Interval and the specified Interval.
+ * Specifically, the resulting Interval has the maximum start time and the minimum end time of the two Intervals.
+ * Returns null if the intersection is empty, meaning, the intervals don't intersect.
+ * @param {Interval} other
+ * @return {Interval}
+ */
+ ;
+
+ _proto.intersection = function intersection(other) {
+ if (!this.isValid) return this;
+ var s = this.s > other.s ? this.s : other.s,
+ e = this.e < other.e ? this.e : other.e;
+
+ if (s > e) {
+ return null;
+ } else {
+ return Interval.fromDateTimes(s, e);
+ }
+ }
+ /**
+ * Return an Interval representing the union of this Interval and the specified Interval.
+ * Specifically, the resulting Interval has the minimum start time and the maximum end time of the two Intervals.
+ * @param {Interval} other
+ * @return {Interval}
+ */
+ ;
+
+ _proto.union = function union(other) {
+ if (!this.isValid) return this;
+ var s = this.s < other.s ? this.s : other.s,
+ e = this.e > other.e ? this.e : other.e;
+ return Interval.fromDateTimes(s, e);
+ }
+ /**
+ * Merge an array of Intervals into a equivalent minimal set of Intervals.
+ * Combines overlapping and adjacent Intervals.
+ * @param {[Interval]} intervals
+ * @return {[Interval]}
+ */
+ ;
+
+ Interval.merge = function merge(intervals) {
+ var _intervals$sort$reduc = intervals.sort(function (a, b) {
+ return a.s - b.s;
+ }).reduce(function (_ref2, item) {
+ var sofar = _ref2[0],
+ current = _ref2[1];
+
+ if (!current) {
+ return [sofar, item];
+ } else if (current.overlaps(item) || current.abutsStart(item)) {
+ return [sofar, current.union(item)];
+ } else {
+ return [sofar.concat([current]), item];
+ }
+ }, [[], null]),
+ found = _intervals$sort$reduc[0],
+ final = _intervals$sort$reduc[1];
+
+ if (final) {
+ found.push(final);
+ }
+
+ return found;
+ }
+ /**
+ * Return an array of Intervals representing the spans of time that only appear in one of the specified Intervals.
+ * @param {[Interval]} intervals
+ * @return {[Interval]}
+ */
+ ;
+
+ Interval.xor = function xor(intervals) {
+ var _Array$prototype;
+
+ var start = null,
+ currentCount = 0;
+
+ var results = [],
+ ends = intervals.map(function (i) {
+ return [{
+ time: i.s,
+ type: "s"
+ }, {
+ time: i.e,
+ type: "e"
+ }];
+ }),
+ flattened = (_Array$prototype = Array.prototype).concat.apply(_Array$prototype, ends),
+ arr = flattened.sort(function (a, b) {
+ return a.time - b.time;
+ });
+
+ for (var _iterator = _createForOfIteratorHelperLoose(arr), _step; !(_step = _iterator()).done;) {
+ var i = _step.value;
+ currentCount += i.type === "s" ? 1 : -1;
+
+ if (currentCount === 1) {
+ start = i.time;
+ } else {
+ if (start && +start !== +i.time) {
+ results.push(Interval.fromDateTimes(start, i.time));
+ }
+
+ start = null;
+ }
+ }
+
+ return Interval.merge(results);
+ }
+ /**
+ * Return an Interval representing the span of time in this Interval that doesn't overlap with any of the specified Intervals.
+ * @param {...Interval} intervals
+ * @return {[Interval]}
+ */
+ ;
+
+ _proto.difference = function difference() {
+ var _this2 = this;
+
+ for (var _len2 = arguments.length, intervals = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
+ intervals[_key2] = arguments[_key2];
+ }
+
+ return Interval.xor([this].concat(intervals)).map(function (i) {
+ return _this2.intersection(i);
+ }).filter(function (i) {
+ return i && !i.isEmpty();
+ });
+ }
+ /**
+ * Returns a string representation of this Interval appropriate for debugging.
+ * @return {string}
+ */
+ ;
+
+ _proto.toString = function toString() {
+ if (!this.isValid) return INVALID$1;
+ return "[" + this.s.toISO() + " \u2013 " + this.e.toISO() + ")";
+ }
+ /**
+ * Returns an ISO 8601-compliant string representation of this Interval.
+ * @see https://en.wikipedia.org/wiki/ISO_8601#Time_intervals
+ * @param {Object} opts - The same options as {@link DateTime.toISO}
+ * @return {string}
+ */
+ ;
+
+ _proto.toISO = function toISO(opts) {
+ if (!this.isValid) return INVALID$1;
+ return this.s.toISO(opts) + "/" + this.e.toISO(opts);
+ }
+ /**
+ * Returns an ISO 8601-compliant string representation of date of this Interval.
+ * The time components are ignored.
+ * @see https://en.wikipedia.org/wiki/ISO_8601#Time_intervals
+ * @return {string}
+ */
+ ;
+
+ _proto.toISODate = function toISODate() {
+ if (!this.isValid) return INVALID$1;
+ return this.s.toISODate() + "/" + this.e.toISODate();
+ }
+ /**
+ * Returns an ISO 8601-compliant string representation of time of this Interval.
+ * The date components are ignored.
+ * @see https://en.wikipedia.org/wiki/ISO_8601#Time_intervals
+ * @param {Object} opts - The same options as {@link DateTime.toISO}
+ * @return {string}
+ */
+ ;
+
+ _proto.toISOTime = function toISOTime(opts) {
+ if (!this.isValid) return INVALID$1;
+ return this.s.toISOTime(opts) + "/" + this.e.toISOTime(opts);
+ }
+ /**
+ * Returns a string representation of this Interval formatted according to the specified format string.
+ * @param {string} dateFormat - the format string. This string formats the start and end time. See {@link DateTime.toFormat} for details.
+ * @param {Object} opts - options
+ * @param {string} [opts.separator = ' – '] - a separator to place between the start and end representations
+ * @return {string}
+ */
+ ;
+
+ _proto.toFormat = function toFormat(dateFormat, _temp2) {
+ var _ref3 = _temp2 === void 0 ? {} : _temp2,
+ _ref3$separator = _ref3.separator,
+ separator = _ref3$separator === void 0 ? " – " : _ref3$separator;
+
+ if (!this.isValid) return INVALID$1;
+ return "" + this.s.toFormat(dateFormat) + separator + this.e.toFormat(dateFormat);
+ }
+ /**
+ * Return a Duration representing the time spanned by this interval.
+ * @param {string|string[]} [unit=['milliseconds']] - the unit or units (such as 'hours' or 'days') to include in the duration.
+ * @param {Object} opts - options that affect the creation of the Duration
+ * @param {string} [opts.conversionAccuracy='casual'] - the conversion system to use
+ * @example Interval.fromDateTimes(dt1, dt2).toDuration().toObject() //=> { milliseconds: 88489257 }
+ * @example Interval.fromDateTimes(dt1, dt2).toDuration('days').toObject() //=> { days: 1.0241812152777778 }
+ * @example Interval.fromDateTimes(dt1, dt2).toDuration(['hours', 'minutes']).toObject() //=> { hours: 24, minutes: 34.82095 }
+ * @example Interval.fromDateTimes(dt1, dt2).toDuration(['hours', 'minutes', 'seconds']).toObject() //=> { hours: 24, minutes: 34, seconds: 49.257 }
+ * @example Interval.fromDateTimes(dt1, dt2).toDuration('seconds').toObject() //=> { seconds: 88489.257 }
+ * @return {Duration}
+ */
+ ;
+
+ _proto.toDuration = function toDuration(unit, opts) {
+ if (!this.isValid) {
+ return Duration.invalid(this.invalidReason);
+ }
+
+ return this.e.diff(this.s, unit, opts);
+ }
+ /**
+ * Run mapFn on the interval start and end, returning a new Interval from the resulting DateTimes
+ * @param {function} mapFn
+ * @return {Interval}
+ * @example Interval.fromDateTimes(dt1, dt2).mapEndpoints(endpoint => endpoint.toUTC())
+ * @example Interval.fromDateTimes(dt1, dt2).mapEndpoints(endpoint => endpoint.plus({ hours: 2 }))
+ */
+ ;
+
+ _proto.mapEndpoints = function mapEndpoints(mapFn) {
+ return Interval.fromDateTimes(mapFn(this.s), mapFn(this.e));
+ };
+
+ _createClass(Interval, [{
+ key: "start",
+ get: function get() {
+ return this.isValid ? this.s : null;
+ }
+ /**
+ * Returns the end of the Interval
+ * @type {DateTime}
+ */
+
+ }, {
+ key: "end",
+ get: function get() {
+ return this.isValid ? this.e : null;
+ }
+ /**
+ * Returns whether this Interval's end is at least its start, meaning that the Interval isn't 'backwards'.
+ * @type {boolean}
+ */
+
+ }, {
+ key: "isValid",
+ get: function get() {
+ return this.invalidReason === null;
+ }
+ /**
+ * Returns an error code if this Interval is invalid, or null if the Interval is valid
+ * @type {string}
+ */
+
+ }, {
+ key: "invalidReason",
+ get: function get() {
+ return this.invalid ? this.invalid.reason : null;
+ }
+ /**
+ * Returns an explanation of why this Interval became invalid, or null if the Interval is valid
+ * @type {string}
+ */
+
+ }, {
+ key: "invalidExplanation",
+ get: function get() {
+ return this.invalid ? this.invalid.explanation : null;
+ }
+ }]);
+
+ return Interval;
+ }();
+
+ /**
+ * The Info class contains static methods for retrieving general time and date related data. For example, it has methods for finding out if a time zone has a DST, for listing the months in any supported locale, and for discovering which of Luxon features are available in the current environment.
+ */
+
+ var Info = /*#__PURE__*/function () {
+ function Info() {}
+
+ /**
+ * Return whether the specified zone contains a DST.
+ * @param {string|Zone} [zone='local'] - Zone to check. Defaults to the environment's local zone.
+ * @return {boolean}
+ */
+ Info.hasDST = function hasDST(zone) {
+ if (zone === void 0) {
+ zone = Settings.defaultZone;
+ }
+
+ var proto = DateTime.local().setZone(zone).set({
+ month: 12
+ });
+ return !zone.universal && proto.offset !== proto.set({
+ month: 6
+ }).offset;
+ }
+ /**
+ * Return whether the specified zone is a valid IANA specifier.
+ * @param {string} zone - Zone to check
+ * @return {boolean}
+ */
+ ;
+
+ Info.isValidIANAZone = function isValidIANAZone(zone) {
+ return IANAZone.isValidSpecifier(zone) && IANAZone.isValidZone(zone);
+ }
+ /**
+ * Converts the input into a {@link Zone} instance.
+ *
+ * * If `input` is already a Zone instance, it is returned unchanged.
+ * * If `input` is a string containing a valid time zone name, a Zone instance
+ * with that name is returned.
+ * * If `input` is a string that doesn't refer to a known time zone, a Zone
+ * instance with {@link Zone.isValid} == false is returned.
+ * * If `input is a number, a Zone instance with the specified fixed offset
+ * in minutes is returned.
+ * * If `input` is `null` or `undefined`, the default zone is returned.
+ * @param {string|Zone|number} [input] - the value to be converted
+ * @return {Zone}
+ */
+ ;
+
+ Info.normalizeZone = function normalizeZone$1(input) {
+ return normalizeZone(input, Settings.defaultZone);
+ }
+ /**
+ * Return an array of standalone month names.
+ * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat
+ * @param {string} [length='long'] - the length of the month representation, such as "numeric", "2-digit", "narrow", "short", "long"
+ * @param {Object} opts - options
+ * @param {string} [opts.locale] - the locale code
+ * @param {string} [opts.numberingSystem=null] - the numbering system
+ * @param {string} [opts.outputCalendar='gregory'] - the calendar
+ * @example Info.months()[0] //=> 'January'
+ * @example Info.months('short')[0] //=> 'Jan'
+ * @example Info.months('numeric')[0] //=> '1'
+ * @example Info.months('short', { locale: 'fr-CA' } )[0] //=> 'janv.'
+ * @example Info.months('numeric', { locale: 'ar' })[0] //=> '١'
+ * @example Info.months('long', { outputCalendar: 'islamic' })[0] //=> 'Rabiʻ I'
+ * @return {[string]}
+ */
+ ;
+
+ Info.months = function months(length, _temp) {
+ if (length === void 0) {
+ length = "long";
+ }
+
+ var _ref = _temp === void 0 ? {} : _temp,
+ _ref$locale = _ref.locale,
+ locale = _ref$locale === void 0 ? null : _ref$locale,
+ _ref$numberingSystem = _ref.numberingSystem,
+ numberingSystem = _ref$numberingSystem === void 0 ? null : _ref$numberingSystem,
+ _ref$outputCalendar = _ref.outputCalendar,
+ outputCalendar = _ref$outputCalendar === void 0 ? "gregory" : _ref$outputCalendar;
+
+ return Locale.create(locale, numberingSystem, outputCalendar).months(length);
+ }
+ /**
+ * Return an array of format month names.
+ * Format months differ from standalone months in that they're meant to appear next to the day of the month. In some languages, that
+ * changes the string.
+ * See {@link months}
+ * @param {string} [length='long'] - the length of the month representation, such as "numeric", "2-digit", "narrow", "short", "long"
+ * @param {Object} opts - options
+ * @param {string} [opts.locale] - the locale code
+ * @param {string} [opts.numberingSystem=null] - the numbering system
+ * @param {string} [opts.outputCalendar='gregory'] - the calendar
+ * @return {[string]}
+ */
+ ;
+
+ Info.monthsFormat = function monthsFormat(length, _temp2) {
+ if (length === void 0) {
+ length = "long";
+ }
+
+ var _ref2 = _temp2 === void 0 ? {} : _temp2,
+ _ref2$locale = _ref2.locale,
+ locale = _ref2$locale === void 0 ? null : _ref2$locale,
+ _ref2$numberingSystem = _ref2.numberingSystem,
+ numberingSystem = _ref2$numberingSystem === void 0 ? null : _ref2$numberingSystem,
+ _ref2$outputCalendar = _ref2.outputCalendar,
+ outputCalendar = _ref2$outputCalendar === void 0 ? "gregory" : _ref2$outputCalendar;
+
+ return Locale.create(locale, numberingSystem, outputCalendar).months(length, true);
+ }
+ /**
+ * Return an array of standalone week names.
+ * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat
+ * @param {string} [length='long'] - the length of the weekday representation, such as "narrow", "short", "long".
+ * @param {Object} opts - options
+ * @param {string} [opts.locale] - the locale code
+ * @param {string} [opts.numberingSystem=null] - the numbering system
+ * @example Info.weekdays()[0] //=> 'Monday'
+ * @example Info.weekdays('short')[0] //=> 'Mon'
+ * @example Info.weekdays('short', { locale: 'fr-CA' })[0] //=> 'lun.'
+ * @example Info.weekdays('short', { locale: 'ar' })[0] //=> 'الاثنين'
+ * @return {[string]}
+ */
+ ;
+
+ Info.weekdays = function weekdays(length, _temp3) {
+ if (length === void 0) {
+ length = "long";
+ }
+
+ var _ref3 = _temp3 === void 0 ? {} : _temp3,
+ _ref3$locale = _ref3.locale,
+ locale = _ref3$locale === void 0 ? null : _ref3$locale,
+ _ref3$numberingSystem = _ref3.numberingSystem,
+ numberingSystem = _ref3$numberingSystem === void 0 ? null : _ref3$numberingSystem;
+
+ return Locale.create(locale, numberingSystem, null).weekdays(length);
+ }
+ /**
+ * Return an array of format week names.
+ * Format weekdays differ from standalone weekdays in that they're meant to appear next to more date information. In some languages, that
+ * changes the string.
+ * See {@link weekdays}
+ * @param {string} [length='long'] - the length of the weekday representation, such as "narrow", "short", "long".
+ * @param {Object} opts - options
+ * @param {string} [opts.locale=null] - the locale code
+ * @param {string} [opts.numberingSystem=null] - the numbering system
+ * @return {[string]}
+ */
+ ;
+
+ Info.weekdaysFormat = function weekdaysFormat(length, _temp4) {
+ if (length === void 0) {
+ length = "long";
+ }
+
+ var _ref4 = _temp4 === void 0 ? {} : _temp4,
+ _ref4$locale = _ref4.locale,
+ locale = _ref4$locale === void 0 ? null : _ref4$locale,
+ _ref4$numberingSystem = _ref4.numberingSystem,
+ numberingSystem = _ref4$numberingSystem === void 0 ? null : _ref4$numberingSystem;
+
+ return Locale.create(locale, numberingSystem, null).weekdays(length, true);
+ }
+ /**
+ * Return an array of meridiems.
+ * @param {Object} opts - options
+ * @param {string} [opts.locale] - the locale code
+ * @example Info.meridiems() //=> [ 'AM', 'PM' ]
+ * @example Info.meridiems({ locale: 'my' }) //=> [ 'နံနက်', 'ညနေ' ]
+ * @return {[string]}
+ */
+ ;
+
+ Info.meridiems = function meridiems(_temp5) {
+ var _ref5 = _temp5 === void 0 ? {} : _temp5,
+ _ref5$locale = _ref5.locale,
+ locale = _ref5$locale === void 0 ? null : _ref5$locale;
+
+ return Locale.create(locale).meridiems();
+ }
+ /**
+ * Return an array of eras, such as ['BC', 'AD']. The locale can be specified, but the calendar system is always Gregorian.
+ * @param {string} [length='short'] - the length of the era representation, such as "short" or "long".
+ * @param {Object} opts - options
+ * @param {string} [opts.locale] - the locale code
+ * @example Info.eras() //=> [ 'BC', 'AD' ]
+ * @example Info.eras('long') //=> [ 'Before Christ', 'Anno Domini' ]
+ * @example Info.eras('long', { locale: 'fr' }) //=> [ 'avant Jésus-Christ', 'après Jésus-Christ' ]
+ * @return {[string]}
+ */
+ ;
+
+ Info.eras = function eras(length, _temp6) {
+ if (length === void 0) {
+ length = "short";
+ }
+
+ var _ref6 = _temp6 === void 0 ? {} : _temp6,
+ _ref6$locale = _ref6.locale,
+ locale = _ref6$locale === void 0 ? null : _ref6$locale;
+
+ return Locale.create(locale, null, "gregory").eras(length);
+ }
+ /**
+ * Return the set of available features in this environment.
+ * Some features of Luxon are not available in all environments. For example, on older browsers, timezone support is not available. Use this function to figure out if that's the case.
+ * Keys:
+ * * `zones`: whether this environment supports IANA timezones
+ * * `intlTokens`: whether this environment supports internationalized token-based formatting/parsing
+ * * `intl`: whether this environment supports general internationalization
+ * * `relative`: whether this environment supports relative time formatting
+ * @example Info.features() //=> { intl: true, intlTokens: false, zones: true, relative: false }
+ * @return {Object}
+ */
+ ;
+
+ Info.features = function features() {
+ var intl = false,
+ intlTokens = false,
+ zones = false,
+ relative = false;
+
+ if (hasIntl()) {
+ intl = true;
+ intlTokens = hasFormatToParts();
+ relative = hasRelative();
+
+ try {
+ zones = new Intl.DateTimeFormat("en", {
+ timeZone: "America/New_York"
+ }).resolvedOptions().timeZone === "America/New_York";
+ } catch (e) {
+ zones = false;
+ }
+ }
+
+ return {
+ intl: intl,
+ intlTokens: intlTokens,
+ zones: zones,
+ relative: relative
+ };
+ };
+
+ return Info;
+ }();
+
+ function dayDiff(earlier, later) {
+ var utcDayStart = function utcDayStart(dt) {
+ return dt.toUTC(0, {
+ keepLocalTime: true
+ }).startOf("day").valueOf();
+ },
+ ms = utcDayStart(later) - utcDayStart(earlier);
+
+ return Math.floor(Duration.fromMillis(ms).as("days"));
+ }
+
+ function highOrderDiffs(cursor, later, units) {
+ var differs = [["years", function (a, b) {
+ return b.year - a.year;
+ }], ["months", function (a, b) {
+ return b.month - a.month + (b.year - a.year) * 12;
+ }], ["weeks", function (a, b) {
+ var days = dayDiff(a, b);
+ return (days - days % 7) / 7;
+ }], ["days", dayDiff]];
+ var results = {};
+ var lowestOrder, highWater;
+
+ for (var _i = 0, _differs = differs; _i < _differs.length; _i++) {
+ var _differs$_i = _differs[_i],
+ unit = _differs$_i[0],
+ differ = _differs$_i[1];
+
+ if (units.indexOf(unit) >= 0) {
+ var _cursor$plus;
+
+ lowestOrder = unit;
+ var delta = differ(cursor, later);
+ highWater = cursor.plus((_cursor$plus = {}, _cursor$plus[unit] = delta, _cursor$plus));
+
+ if (highWater > later) {
+ var _cursor$plus2;
+
+ cursor = cursor.plus((_cursor$plus2 = {}, _cursor$plus2[unit] = delta - 1, _cursor$plus2));
+ delta -= 1;
+ } else {
+ cursor = highWater;
+ }
+
+ results[unit] = delta;
+ }
+ }
+
+ return [cursor, results, highWater, lowestOrder];
+ }
+
+ function _diff (earlier, later, units, opts) {
+ var _highOrderDiffs = highOrderDiffs(earlier, later, units),
+ cursor = _highOrderDiffs[0],
+ results = _highOrderDiffs[1],
+ highWater = _highOrderDiffs[2],
+ lowestOrder = _highOrderDiffs[3];
+
+ var remainingMillis = later - cursor;
+ var lowerOrderUnits = units.filter(function (u) {
+ return ["hours", "minutes", "seconds", "milliseconds"].indexOf(u) >= 0;
+ });
+
+ if (lowerOrderUnits.length === 0) {
+ if (highWater < later) {
+ var _cursor$plus3;
+
+ highWater = cursor.plus((_cursor$plus3 = {}, _cursor$plus3[lowestOrder] = 1, _cursor$plus3));
+ }
+
+ if (highWater !== cursor) {
+ results[lowestOrder] = (results[lowestOrder] || 0) + remainingMillis / (highWater - cursor);
+ }
+ }
+
+ var duration = Duration.fromObject(Object.assign(results, opts));
+
+ if (lowerOrderUnits.length > 0) {
+ var _Duration$fromMillis;
+
+ return (_Duration$fromMillis = Duration.fromMillis(remainingMillis, opts)).shiftTo.apply(_Duration$fromMillis, lowerOrderUnits).plus(duration);
+ } else {
+ return duration;
+ }
+ }
+
+ var numberingSystems = {
+ arab: "[\u0660-\u0669]",
+ arabext: "[\u06F0-\u06F9]",
+ bali: "[\u1B50-\u1B59]",
+ beng: "[\u09E6-\u09EF]",
+ deva: "[\u0966-\u096F]",
+ fullwide: "[\uFF10-\uFF19]",
+ gujr: "[\u0AE6-\u0AEF]",
+ hanidec: "[〇|一|二|三|四|五|六|七|八|九]",
+ khmr: "[\u17E0-\u17E9]",
+ knda: "[\u0CE6-\u0CEF]",
+ laoo: "[\u0ED0-\u0ED9]",
+ limb: "[\u1946-\u194F]",
+ mlym: "[\u0D66-\u0D6F]",
+ mong: "[\u1810-\u1819]",
+ mymr: "[\u1040-\u1049]",
+ orya: "[\u0B66-\u0B6F]",
+ tamldec: "[\u0BE6-\u0BEF]",
+ telu: "[\u0C66-\u0C6F]",
+ thai: "[\u0E50-\u0E59]",
+ tibt: "[\u0F20-\u0F29]",
+ latn: "\\d"
+ };
+ var numberingSystemsUTF16 = {
+ arab: [1632, 1641],
+ arabext: [1776, 1785],
+ bali: [6992, 7001],
+ beng: [2534, 2543],
+ deva: [2406, 2415],
+ fullwide: [65296, 65303],
+ gujr: [2790, 2799],
+ khmr: [6112, 6121],
+ knda: [3302, 3311],
+ laoo: [3792, 3801],
+ limb: [6470, 6479],
+ mlym: [3430, 3439],
+ mong: [6160, 6169],
+ mymr: [4160, 4169],
+ orya: [2918, 2927],
+ tamldec: [3046, 3055],
+ telu: [3174, 3183],
+ thai: [3664, 3673],
+ tibt: [3872, 3881]
+ }; // eslint-disable-next-line
+
+ var hanidecChars = numberingSystems.hanidec.replace(/[\[|\]]/g, "").split("");
+ function parseDigits(str) {
+ var value = parseInt(str, 10);
+
+ if (isNaN(value)) {
+ value = "";
+
+ for (var i = 0; i < str.length; i++) {
+ var code = str.charCodeAt(i);
+
+ if (str[i].search(numberingSystems.hanidec) !== -1) {
+ value += hanidecChars.indexOf(str[i]);
+ } else {
+ for (var key in numberingSystemsUTF16) {
+ var _numberingSystemsUTF = numberingSystemsUTF16[key],
+ min = _numberingSystemsUTF[0],
+ max = _numberingSystemsUTF[1];
+
+ if (code >= min && code <= max) {
+ value += code - min;
+ }
+ }
+ }
+ }
+
+ return parseInt(value, 10);
+ } else {
+ return value;
+ }
+ }
+ function digitRegex(_ref, append) {
+ var numberingSystem = _ref.numberingSystem;
+
+ if (append === void 0) {
+ append = "";
+ }
+
+ return new RegExp("" + numberingSystems[numberingSystem || "latn"] + append);
+ }
+
+ var MISSING_FTP = "missing Intl.DateTimeFormat.formatToParts support";
+
+ function intUnit(regex, post) {
+ if (post === void 0) {
+ post = function post(i) {
+ return i;
+ };
+ }
+
+ return {
+ regex: regex,
+ deser: function deser(_ref) {
+ var s = _ref[0];
+ return post(parseDigits(s));
+ }
+ };
+ }
+
+ var NBSP = String.fromCharCode(160);
+ var spaceOrNBSP = "( |" + NBSP + ")";
+ var spaceOrNBSPRegExp = new RegExp(spaceOrNBSP, "g");
+
+ function fixListRegex(s) {
+ // make dots optional and also make them literal
+ // make space and non breakable space characters interchangeable
+ return s.replace(/\./g, "\\.?").replace(spaceOrNBSPRegExp, spaceOrNBSP);
+ }
+
+ function stripInsensitivities(s) {
+ return s.replace(/\./g, "") // ignore dots that were made optional
+ .replace(spaceOrNBSPRegExp, " ") // interchange space and nbsp
+ .toLowerCase();
+ }
+
+ function oneOf(strings, startIndex) {
+ if (strings === null) {
+ return null;
+ } else {
+ return {
+ regex: RegExp(strings.map(fixListRegex).join("|")),
+ deser: function deser(_ref2) {
+ var s = _ref2[0];
+ return strings.findIndex(function (i) {
+ return stripInsensitivities(s) === stripInsensitivities(i);
+ }) + startIndex;
+ }
+ };
+ }
+ }
+
+ function offset(regex, groups) {
+ return {
+ regex: regex,
+ deser: function deser(_ref3) {
+ var h = _ref3[1],
+ m = _ref3[2];
+ return signedOffset(h, m);
+ },
+ groups: groups
+ };
+ }
+
+ function simple(regex) {
+ return {
+ regex: regex,
+ deser: function deser(_ref4) {
+ var s = _ref4[0];
+ return s;
+ }
+ };
+ }
+
+ function escapeToken(value) {
+ // eslint-disable-next-line no-useless-escape
+ return value.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&");
+ }
+
+ function unitForToken(token, loc) {
+ var one = digitRegex(loc),
+ two = digitRegex(loc, "{2}"),
+ three = digitRegex(loc, "{3}"),
+ four = digitRegex(loc, "{4}"),
+ six = digitRegex(loc, "{6}"),
+ oneOrTwo = digitRegex(loc, "{1,2}"),
+ oneToThree = digitRegex(loc, "{1,3}"),
+ oneToSix = digitRegex(loc, "{1,6}"),
+ oneToNine = digitRegex(loc, "{1,9}"),
+ twoToFour = digitRegex(loc, "{2,4}"),
+ fourToSix = digitRegex(loc, "{4,6}"),
+ literal = function literal(t) {
+ return {
+ regex: RegExp(escapeToken(t.val)),
+ deser: function deser(_ref5) {
+ var s = _ref5[0];
+ return s;
+ },
+ literal: true
+ };
+ },
+ unitate = function unitate(t) {
+ if (token.literal) {
+ return literal(t);
+ }
+
+ switch (t.val) {
+ // era
+ case "G":
+ return oneOf(loc.eras("short", false), 0);
+
+ case "GG":
+ return oneOf(loc.eras("long", false), 0);
+ // years
+
+ case "y":
+ return intUnit(oneToSix);
+
+ case "yy":
+ return intUnit(twoToFour, untruncateYear);
+
+ case "yyyy":
+ return intUnit(four);
+
+ case "yyyyy":
+ return intUnit(fourToSix);
+
+ case "yyyyyy":
+ return intUnit(six);
+ // months
+
+ case "M":
+ return intUnit(oneOrTwo);
+
+ case "MM":
+ return intUnit(two);
+
+ case "MMM":
+ return oneOf(loc.months("short", true, false), 1);
+
+ case "MMMM":
+ return oneOf(loc.months("long", true, false), 1);
+
+ case "L":
+ return intUnit(oneOrTwo);
+
+ case "LL":
+ return intUnit(two);
+
+ case "LLL":
+ return oneOf(loc.months("short", false, false), 1);
+
+ case "LLLL":
+ return oneOf(loc.months("long", false, false), 1);
+ // dates
+
+ case "d":
+ return intUnit(oneOrTwo);
+
+ case "dd":
+ return intUnit(two);
+ // ordinals
+
+ case "o":
+ return intUnit(oneToThree);
+
+ case "ooo":
+ return intUnit(three);
+ // time
+
+ case "HH":
+ return intUnit(two);
+
+ case "H":
+ return intUnit(oneOrTwo);
+
+ case "hh":
+ return intUnit(two);
+
+ case "h":
+ return intUnit(oneOrTwo);
+
+ case "mm":
+ return intUnit(two);
+
+ case "m":
+ return intUnit(oneOrTwo);
+
+ case "q":
+ return intUnit(oneOrTwo);
+
+ case "qq":
+ return intUnit(two);
+
+ case "s":
+ return intUnit(oneOrTwo);
+
+ case "ss":
+ return intUnit(two);
+
+ case "S":
+ return intUnit(oneToThree);
+
+ case "SSS":
+ return intUnit(three);
+
+ case "u":
+ return simple(oneToNine);
+ // meridiem
+
+ case "a":
+ return oneOf(loc.meridiems(), 0);
+ // weekYear (k)
+
+ case "kkkk":
+ return intUnit(four);
+
+ case "kk":
+ return intUnit(twoToFour, untruncateYear);
+ // weekNumber (W)
+
+ case "W":
+ return intUnit(oneOrTwo);
+
+ case "WW":
+ return intUnit(two);
+ // weekdays
+
+ case "E":
+ case "c":
+ return intUnit(one);
+
+ case "EEE":
+ return oneOf(loc.weekdays("short", false, false), 1);
+
+ case "EEEE":
+ return oneOf(loc.weekdays("long", false, false), 1);
+
+ case "ccc":
+ return oneOf(loc.weekdays("short", true, false), 1);
+
+ case "cccc":
+ return oneOf(loc.weekdays("long", true, false), 1);
+ // offset/zone
+
+ case "Z":
+ case "ZZ":
+ return offset(new RegExp("([+-]" + oneOrTwo.source + ")(?::(" + two.source + "))?"), 2);
+
+ case "ZZZ":
+ return offset(new RegExp("([+-]" + oneOrTwo.source + ")(" + two.source + ")?"), 2);
+ // we don't support ZZZZ (PST) or ZZZZZ (Pacific Standard Time) in parsing
+ // because we don't have any way to figure out what they are
+
+ case "z":
+ return simple(/[a-z_+-/]{1,256}?/i);
+
+ default:
+ return literal(t);
+ }
+ };
+
+ var unit = unitate(token) || {
+ invalidReason: MISSING_FTP
+ };
+ unit.token = token;
+ return unit;
+ }
+
+ var partTypeStyleToTokenVal = {
+ year: {
+ "2-digit": "yy",
+ numeric: "yyyyy"
+ },
+ month: {
+ numeric: "M",
+ "2-digit": "MM",
+ short: "MMM",
+ long: "MMMM"
+ },
+ day: {
+ numeric: "d",
+ "2-digit": "dd"
+ },
+ weekday: {
+ short: "EEE",
+ long: "EEEE"
+ },
+ dayperiod: "a",
+ dayPeriod: "a",
+ hour: {
+ numeric: "h",
+ "2-digit": "hh"
+ },
+ minute: {
+ numeric: "m",
+ "2-digit": "mm"
+ },
+ second: {
+ numeric: "s",
+ "2-digit": "ss"
+ }
+ };
+
+ function tokenForPart(part, locale, formatOpts) {
+ var type = part.type,
+ value = part.value;
+
+ if (type === "literal") {
+ return {
+ literal: true,
+ val: value
+ };
+ }
+
+ var style = formatOpts[type];
+ var val = partTypeStyleToTokenVal[type];
+
+ if (typeof val === "object") {
+ val = val[style];
+ }
+
+ if (val) {
+ return {
+ literal: false,
+ val: val
+ };
+ }
+
+ return undefined;
+ }
+
+ function buildRegex(units) {
+ var re = units.map(function (u) {
+ return u.regex;
+ }).reduce(function (f, r) {
+ return f + "(" + r.source + ")";
+ }, "");
+ return ["^" + re + "$", units];
+ }
+
+ function match(input, regex, handlers) {
+ var matches = input.match(regex);
+
+ if (matches) {
+ var all = {};
+ var matchIndex = 1;
+
+ for (var i in handlers) {
+ if (hasOwnProperty(handlers, i)) {
+ var h = handlers[i],
+ groups = h.groups ? h.groups + 1 : 1;
+
+ if (!h.literal && h.token) {
+ all[h.token.val[0]] = h.deser(matches.slice(matchIndex, matchIndex + groups));
+ }
+
+ matchIndex += groups;
+ }
+ }
+
+ return [matches, all];
+ } else {
+ return [matches, {}];
+ }
+ }
+
+ function dateTimeFromMatches(matches) {
+ var toField = function toField(token) {
+ switch (token) {
+ case "S":
+ return "millisecond";
+
+ case "s":
+ return "second";
+
+ case "m":
+ return "minute";
+
+ case "h":
+ case "H":
+ return "hour";
+
+ case "d":
+ return "day";
+
+ case "o":
+ return "ordinal";
+
+ case "L":
+ case "M":
+ return "month";
+
+ case "y":
+ return "year";
+
+ case "E":
+ case "c":
+ return "weekday";
+
+ case "W":
+ return "weekNumber";
+
+ case "k":
+ return "weekYear";
+
+ case "q":
+ return "quarter";
+
+ default:
+ return null;
+ }
+ };
+
+ var zone;
+
+ if (!isUndefined(matches.Z)) {
+ zone = new FixedOffsetZone(matches.Z);
+ } else if (!isUndefined(matches.z)) {
+ zone = IANAZone.create(matches.z);
+ } else {
+ zone = null;
+ }
+
+ if (!isUndefined(matches.q)) {
+ matches.M = (matches.q - 1) * 3 + 1;
+ }
+
+ if (!isUndefined(matches.h)) {
+ if (matches.h < 12 && matches.a === 1) {
+ matches.h += 12;
+ } else if (matches.h === 12 && matches.a === 0) {
+ matches.h = 0;
+ }
+ }
+
+ if (matches.G === 0 && matches.y) {
+ matches.y = -matches.y;
+ }
+
+ if (!isUndefined(matches.u)) {
+ matches.S = parseMillis(matches.u);
+ }
+
+ var vals = Object.keys(matches).reduce(function (r, k) {
+ var f = toField(k);
+
+ if (f) {
+ r[f] = matches[k];
+ }
+
+ return r;
+ }, {});
+ return [vals, zone];
+ }
+
+ var dummyDateTimeCache = null;
+
+ function getDummyDateTime() {
+ if (!dummyDateTimeCache) {
+ dummyDateTimeCache = DateTime.fromMillis(1555555555555);
+ }
+
+ return dummyDateTimeCache;
+ }
+
+ function maybeExpandMacroToken(token, locale) {
+ if (token.literal) {
+ return token;
+ }
+
+ var formatOpts = Formatter.macroTokenToFormatOpts(token.val);
+
+ if (!formatOpts) {
+ return token;
+ }
+
+ var formatter = Formatter.create(locale, formatOpts);
+ var parts = formatter.formatDateTimeParts(getDummyDateTime());
+ var tokens = parts.map(function (p) {
+ return tokenForPart(p, locale, formatOpts);
+ });
+
+ if (tokens.includes(undefined)) {
+ return token;
+ }
+
+ return tokens;
+ }
+
+ function expandMacroTokens(tokens, locale) {
+ var _Array$prototype;
+
+ return (_Array$prototype = Array.prototype).concat.apply(_Array$prototype, tokens.map(function (t) {
+ return maybeExpandMacroToken(t, locale);
+ }));
+ }
+ /**
+ * @private
+ */
+
+
+ function explainFromTokens(locale, input, format) {
+ var tokens = expandMacroTokens(Formatter.parseFormat(format), locale),
+ units = tokens.map(function (t) {
+ return unitForToken(t, locale);
+ }),
+ disqualifyingUnit = units.find(function (t) {
+ return t.invalidReason;
+ });
+
+ if (disqualifyingUnit) {
+ return {
+ input: input,
+ tokens: tokens,
+ invalidReason: disqualifyingUnit.invalidReason
+ };
+ } else {
+ var _buildRegex = buildRegex(units),
+ regexString = _buildRegex[0],
+ handlers = _buildRegex[1],
+ regex = RegExp(regexString, "i"),
+ _match = match(input, regex, handlers),
+ rawMatches = _match[0],
+ matches = _match[1],
+ _ref6 = matches ? dateTimeFromMatches(matches) : [null, null],
+ result = _ref6[0],
+ zone = _ref6[1];
+
+ if (hasOwnProperty(matches, "a") && hasOwnProperty(matches, "H")) {
+ throw new ConflictingSpecificationError("Can't include meridiem when specifying 24-hour format");
+ }
+
+ return {
+ input: input,
+ tokens: tokens,
+ regex: regex,
+ rawMatches: rawMatches,
+ matches: matches,
+ result: result,
+ zone: zone
+ };
+ }
+ }
+ function parseFromTokens(locale, input, format) {
+ var _explainFromTokens = explainFromTokens(locale, input, format),
+ result = _explainFromTokens.result,
+ zone = _explainFromTokens.zone,
+ invalidReason = _explainFromTokens.invalidReason;
+
+ return [result, zone, invalidReason];
+ }
+
+ var nonLeapLadder = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334],
+ leapLadder = [0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335];
+
+ function unitOutOfRange(unit, value) {
+ return new Invalid("unit out of range", "you specified " + value + " (of type " + typeof value + ") as a " + unit + ", which is invalid");
+ }
+
+ function dayOfWeek(year, month, day) {
+ var js = new Date(Date.UTC(year, month - 1, day)).getUTCDay();
+ return js === 0 ? 7 : js;
+ }
+
+ function computeOrdinal(year, month, day) {
+ return day + (isLeapYear(year) ? leapLadder : nonLeapLadder)[month - 1];
+ }
+
+ function uncomputeOrdinal(year, ordinal) {
+ var table = isLeapYear(year) ? leapLadder : nonLeapLadder,
+ month0 = table.findIndex(function (i) {
+ return i < ordinal;
+ }),
+ day = ordinal - table[month0];
+ return {
+ month: month0 + 1,
+ day: day
+ };
+ }
+ /**
+ * @private
+ */
+
+
+ function gregorianToWeek(gregObj) {
+ var year = gregObj.year,
+ month = gregObj.month,
+ day = gregObj.day,
+ ordinal = computeOrdinal(year, month, day),
+ weekday = dayOfWeek(year, month, day);
+ var weekNumber = Math.floor((ordinal - weekday + 10) / 7),
+ weekYear;
+
+ if (weekNumber < 1) {
+ weekYear = year - 1;
+ weekNumber = weeksInWeekYear(weekYear);
+ } else if (weekNumber > weeksInWeekYear(year)) {
+ weekYear = year + 1;
+ weekNumber = 1;
+ } else {
+ weekYear = year;
+ }
+
+ return Object.assign({
+ weekYear: weekYear,
+ weekNumber: weekNumber,
+ weekday: weekday
+ }, timeObject(gregObj));
+ }
+ function weekToGregorian(weekData) {
+ var weekYear = weekData.weekYear,
+ weekNumber = weekData.weekNumber,
+ weekday = weekData.weekday,
+ weekdayOfJan4 = dayOfWeek(weekYear, 1, 4),
+ yearInDays = daysInYear(weekYear);
+ var ordinal = weekNumber * 7 + weekday - weekdayOfJan4 - 3,
+ year;
+
+ if (ordinal < 1) {
+ year = weekYear - 1;
+ ordinal += daysInYear(year);
+ } else if (ordinal > yearInDays) {
+ year = weekYear + 1;
+ ordinal -= daysInYear(weekYear);
+ } else {
+ year = weekYear;
+ }
+
+ var _uncomputeOrdinal = uncomputeOrdinal(year, ordinal),
+ month = _uncomputeOrdinal.month,
+ day = _uncomputeOrdinal.day;
+
+ return Object.assign({
+ year: year,
+ month: month,
+ day: day
+ }, timeObject(weekData));
+ }
+ function gregorianToOrdinal(gregData) {
+ var year = gregData.year,
+ month = gregData.month,
+ day = gregData.day,
+ ordinal = computeOrdinal(year, month, day);
+ return Object.assign({
+ year: year,
+ ordinal: ordinal
+ }, timeObject(gregData));
+ }
+ function ordinalToGregorian(ordinalData) {
+ var year = ordinalData.year,
+ ordinal = ordinalData.ordinal,
+ _uncomputeOrdinal2 = uncomputeOrdinal(year, ordinal),
+ month = _uncomputeOrdinal2.month,
+ day = _uncomputeOrdinal2.day;
+
+ return Object.assign({
+ year: year,
+ month: month,
+ day: day
+ }, timeObject(ordinalData));
+ }
+ function hasInvalidWeekData(obj) {
+ var validYear = isInteger(obj.weekYear),
+ validWeek = integerBetween(obj.weekNumber, 1, weeksInWeekYear(obj.weekYear)),
+ validWeekday = integerBetween(obj.weekday, 1, 7);
+
+ if (!validYear) {
+ return unitOutOfRange("weekYear", obj.weekYear);
+ } else if (!validWeek) {
+ return unitOutOfRange("week", obj.week);
+ } else if (!validWeekday) {
+ return unitOutOfRange("weekday", obj.weekday);
+ } else return false;
+ }
+ function hasInvalidOrdinalData(obj) {
+ var validYear = isInteger(obj.year),
+ validOrdinal = integerBetween(obj.ordinal, 1, daysInYear(obj.year));
+
+ if (!validYear) {
+ return unitOutOfRange("year", obj.year);
+ } else if (!validOrdinal) {
+ return unitOutOfRange("ordinal", obj.ordinal);
+ } else return false;
+ }
+ function hasInvalidGregorianData(obj) {
+ var validYear = isInteger(obj.year),
+ validMonth = integerBetween(obj.month, 1, 12),
+ validDay = integerBetween(obj.day, 1, daysInMonth(obj.year, obj.month));
+
+ if (!validYear) {
+ return unitOutOfRange("year", obj.year);
+ } else if (!validMonth) {
+ return unitOutOfRange("month", obj.month);
+ } else if (!validDay) {
+ return unitOutOfRange("day", obj.day);
+ } else return false;
+ }
+ function hasInvalidTimeData(obj) {
+ var hour = obj.hour,
+ minute = obj.minute,
+ second = obj.second,
+ millisecond = obj.millisecond;
+ var validHour = integerBetween(hour, 0, 23) || hour === 24 && minute === 0 && second === 0 && millisecond === 0,
+ validMinute = integerBetween(minute, 0, 59),
+ validSecond = integerBetween(second, 0, 59),
+ validMillisecond = integerBetween(millisecond, 0, 999);
+
+ if (!validHour) {
+ return unitOutOfRange("hour", hour);
+ } else if (!validMinute) {
+ return unitOutOfRange("minute", minute);
+ } else if (!validSecond) {
+ return unitOutOfRange("second", second);
+ } else if (!validMillisecond) {
+ return unitOutOfRange("millisecond", millisecond);
+ } else return false;
+ }
+
+ var INVALID$2 = "Invalid DateTime";
+ var MAX_DATE = 8.64e15;
+
+ function unsupportedZone(zone) {
+ return new Invalid("unsupported zone", "the zone \"" + zone.name + "\" is not supported");
+ } // we cache week data on the DT object and this intermediates the cache
+
+
+ function possiblyCachedWeekData(dt) {
+ if (dt.weekData === null) {
+ dt.weekData = gregorianToWeek(dt.c);
+ }
+
+ return dt.weekData;
+ } // clone really means, "make a new object with these modifications". all "setters" really use this
+ // to create a new object while only changing some of the properties
+
+
+ function clone$1(inst, alts) {
+ var current = {
+ ts: inst.ts,
+ zone: inst.zone,
+ c: inst.c,
+ o: inst.o,
+ loc: inst.loc,
+ invalid: inst.invalid
+ };
+ return new DateTime(Object.assign({}, current, alts, {
+ old: current
+ }));
+ } // find the right offset a given local time. The o input is our guess, which determines which
+ // offset we'll pick in ambiguous cases (e.g. there are two 3 AMs b/c Fallback DST)
+
+
+ function fixOffset(localTS, o, tz) {
+ // Our UTC time is just a guess because our offset is just a guess
+ var utcGuess = localTS - o * 60 * 1000; // Test whether the zone matches the offset for this ts
+
+ var o2 = tz.offset(utcGuess); // If so, offset didn't change and we're done
+
+ if (o === o2) {
+ return [utcGuess, o];
+ } // If not, change the ts by the difference in the offset
+
+
+ utcGuess -= (o2 - o) * 60 * 1000; // If that gives us the local time we want, we're done
+
+ var o3 = tz.offset(utcGuess);
+
+ if (o2 === o3) {
+ return [utcGuess, o2];
+ } // If it's different, we're in a hole time. The offset has changed, but the we don't adjust the time
+
+
+ return [localTS - Math.min(o2, o3) * 60 * 1000, Math.max(o2, o3)];
+ } // convert an epoch timestamp into a calendar object with the given offset
+
+
+ function tsToObj(ts, offset) {
+ ts += offset * 60 * 1000;
+ var d = new Date(ts);
+ return {
+ year: d.getUTCFullYear(),
+ month: d.getUTCMonth() + 1,
+ day: d.getUTCDate(),
+ hour: d.getUTCHours(),
+ minute: d.getUTCMinutes(),
+ second: d.getUTCSeconds(),
+ millisecond: d.getUTCMilliseconds()
+ };
+ } // convert a calendar object to a epoch timestamp
+
+
+ function objToTS(obj, offset, zone) {
+ return fixOffset(objToLocalTS(obj), offset, zone);
+ } // create a new DT instance by adding a duration, adjusting for DSTs
+
+
+ function adjustTime(inst, dur) {
+ var oPre = inst.o,
+ year = inst.c.year + Math.trunc(dur.years),
+ month = inst.c.month + Math.trunc(dur.months) + Math.trunc(dur.quarters) * 3,
+ c = Object.assign({}, inst.c, {
+ year: year,
+ month: month,
+ day: Math.min(inst.c.day, daysInMonth(year, month)) + Math.trunc(dur.days) + Math.trunc(dur.weeks) * 7
+ }),
+ millisToAdd = Duration.fromObject({
+ years: dur.years - Math.trunc(dur.years),
+ quarters: dur.quarters - Math.trunc(dur.quarters),
+ months: dur.months - Math.trunc(dur.months),
+ weeks: dur.weeks - Math.trunc(dur.weeks),
+ days: dur.days - Math.trunc(dur.days),
+ hours: dur.hours,
+ minutes: dur.minutes,
+ seconds: dur.seconds,
+ milliseconds: dur.milliseconds
+ }).as("milliseconds"),
+ localTS = objToLocalTS(c);
+
+ var _fixOffset = fixOffset(localTS, oPre, inst.zone),
+ ts = _fixOffset[0],
+ o = _fixOffset[1];
+
+ if (millisToAdd !== 0) {
+ ts += millisToAdd; // that could have changed the offset by going over a DST, but we want to keep the ts the same
+
+ o = inst.zone.offset(ts);
+ }
+
+ return {
+ ts: ts,
+ o: o
+ };
+ } // helper useful in turning the results of parsing into real dates
+ // by handling the zone options
+
+
+ function parseDataToDateTime(parsed, parsedZone, opts, format, text) {
+ var setZone = opts.setZone,
+ zone = opts.zone;
+
+ if (parsed && Object.keys(parsed).length !== 0) {
+ var interpretationZone = parsedZone || zone,
+ inst = DateTime.fromObject(Object.assign(parsed, opts, {
+ zone: interpretationZone,
+ // setZone is a valid option in the calling methods, but not in fromObject
+ setZone: undefined
+ }));
+ return setZone ? inst : inst.setZone(zone);
+ } else {
+ return DateTime.invalid(new Invalid("unparsable", "the input \"" + text + "\" can't be parsed as " + format));
+ }
+ } // if you want to output a technical format (e.g. RFC 2822), this helper
+ // helps handle the details
+
+
+ function toTechFormat(dt, format, allowZ) {
+ if (allowZ === void 0) {
+ allowZ = true;
+ }
+
+ return dt.isValid ? Formatter.create(Locale.create("en-US"), {
+ allowZ: allowZ,
+ forceSimple: true
+ }).formatDateTimeFromString(dt, format) : null;
+ } // technical time formats (e.g. the time part of ISO 8601), take some options
+ // and this commonizes their handling
+
+
+ function toTechTimeFormat(dt, _ref) {
+ var _ref$suppressSeconds = _ref.suppressSeconds,
+ suppressSeconds = _ref$suppressSeconds === void 0 ? false : _ref$suppressSeconds,
+ _ref$suppressMillisec = _ref.suppressMilliseconds,
+ suppressMilliseconds = _ref$suppressMillisec === void 0 ? false : _ref$suppressMillisec,
+ includeOffset = _ref.includeOffset,
+ _ref$includeZone = _ref.includeZone,
+ includeZone = _ref$includeZone === void 0 ? false : _ref$includeZone,
+ _ref$spaceZone = _ref.spaceZone,
+ spaceZone = _ref$spaceZone === void 0 ? false : _ref$spaceZone,
+ _ref$format = _ref.format,
+ format = _ref$format === void 0 ? "extended" : _ref$format;
+ var fmt = format === "basic" ? "HHmm" : "HH:mm";
+
+ if (!suppressSeconds || dt.second !== 0 || dt.millisecond !== 0) {
+ fmt += format === "basic" ? "ss" : ":ss";
+
+ if (!suppressMilliseconds || dt.millisecond !== 0) {
+ fmt += ".SSS";
+ }
+ }
+
+ if ((includeZone || includeOffset) && spaceZone) {
+ fmt += " ";
+ }
+
+ if (includeZone) {
+ fmt += "z";
+ } else if (includeOffset) {
+ fmt += format === "basic" ? "ZZZ" : "ZZ";
+ }
+
+ return toTechFormat(dt, fmt);
+ } // defaults for unspecified units in the supported calendars
+
+
+ var defaultUnitValues = {
+ month: 1,
+ day: 1,
+ hour: 0,
+ minute: 0,
+ second: 0,
+ millisecond: 0
+ },
+ defaultWeekUnitValues = {
+ weekNumber: 1,
+ weekday: 1,
+ hour: 0,
+ minute: 0,
+ second: 0,
+ millisecond: 0
+ },
+ defaultOrdinalUnitValues = {
+ ordinal: 1,
+ hour: 0,
+ minute: 0,
+ second: 0,
+ millisecond: 0
+ }; // Units in the supported calendars, sorted by bigness
+
+ var orderedUnits$1 = ["year", "month", "day", "hour", "minute", "second", "millisecond"],
+ orderedWeekUnits = ["weekYear", "weekNumber", "weekday", "hour", "minute", "second", "millisecond"],
+ orderedOrdinalUnits = ["year", "ordinal", "hour", "minute", "second", "millisecond"]; // standardize case and plurality in units
+
+ function normalizeUnit(unit) {
+ var normalized = {
+ year: "year",
+ years: "year",
+ month: "month",
+ months: "month",
+ day: "day",
+ days: "day",
+ hour: "hour",
+ hours: "hour",
+ minute: "minute",
+ minutes: "minute",
+ quarter: "quarter",
+ quarters: "quarter",
+ second: "second",
+ seconds: "second",
+ millisecond: "millisecond",
+ milliseconds: "millisecond",
+ weekday: "weekday",
+ weekdays: "weekday",
+ weeknumber: "weekNumber",
+ weeksnumber: "weekNumber",
+ weeknumbers: "weekNumber",
+ weekyear: "weekYear",
+ weekyears: "weekYear",
+ ordinal: "ordinal"
+ }[unit.toLowerCase()];
+ if (!normalized) throw new InvalidUnitError(unit);
+ return normalized;
+ } // this is a dumbed down version of fromObject() that runs about 60% faster
+ // but doesn't do any validation, makes a bunch of assumptions about what units
+ // are present, and so on.
+
+
+ function quickDT(obj, zone) {
+ // assume we have the higher-order units
+ for (var _iterator = _createForOfIteratorHelperLoose(orderedUnits$1), _step; !(_step = _iterator()).done;) {
+ var u = _step.value;
+
+ if (isUndefined(obj[u])) {
+ obj[u] = defaultUnitValues[u];
+ }
+ }
+
+ var invalid = hasInvalidGregorianData(obj) || hasInvalidTimeData(obj);
+
+ if (invalid) {
+ return DateTime.invalid(invalid);
+ }
+
+ var tsNow = Settings.now(),
+ offsetProvis = zone.offset(tsNow),
+ _objToTS = objToTS(obj, offsetProvis, zone),
+ ts = _objToTS[0],
+ o = _objToTS[1];
+
+ return new DateTime({
+ ts: ts,
+ zone: zone,
+ o: o
+ });
+ }
+
+ function diffRelative(start, end, opts) {
+ var round = isUndefined(opts.round) ? true : opts.round,
+ format = function format(c, unit) {
+ c = roundTo(c, round || opts.calendary ? 0 : 2, true);
+ var formatter = end.loc.clone(opts).relFormatter(opts);
+ return formatter.format(c, unit);
+ },
+ differ = function differ(unit) {
+ if (opts.calendary) {
+ if (!end.hasSame(start, unit)) {
+ return end.startOf(unit).diff(start.startOf(unit), unit).get(unit);
+ } else return 0;
+ } else {
+ return end.diff(start, unit).get(unit);
+ }
+ };
+
+ if (opts.unit) {
+ return format(differ(opts.unit), opts.unit);
+ }
+
+ for (var _iterator2 = _createForOfIteratorHelperLoose(opts.units), _step2; !(_step2 = _iterator2()).done;) {
+ var unit = _step2.value;
+ var count = differ(unit);
+
+ if (Math.abs(count) >= 1) {
+ return format(count, unit);
+ }
+ }
+
+ return format(0, opts.units[opts.units.length - 1]);
+ }
+ /**
+ * A DateTime is an immutable data structure representing a specific date and time and accompanying methods. It contains class and instance methods for creating, parsing, interrogating, transforming, and formatting them.
+ *
+ * A DateTime comprises of:
+ * * A timestamp. Each DateTime instance refers to a specific millisecond of the Unix epoch.
+ * * A time zone. Each instance is considered in the context of a specific zone (by default the local system's zone).
+ * * Configuration properties that effect how output strings are formatted, such as `locale`, `numberingSystem`, and `outputCalendar`.
+ *
+ * Here is a brief overview of the most commonly used functionality it provides:
+ *
+ * * **Creation**: To create a DateTime from its components, use one of its factory class methods: {@link local}, {@link utc}, and (most flexibly) {@link fromObject}. To create one from a standard string format, use {@link fromISO}, {@link fromHTTP}, and {@link fromRFC2822}. To create one from a custom string format, use {@link fromFormat}. To create one from a native JS date, use {@link fromJSDate}.
+ * * **Gregorian calendar and time**: To examine the Gregorian properties of a DateTime individually (i.e as opposed to collectively through {@link toObject}), use the {@link year}, {@link month},
+ * {@link day}, {@link hour}, {@link minute}, {@link second}, {@link millisecond} accessors.
+ * * **Week calendar**: For ISO week calendar attributes, see the {@link weekYear}, {@link weekNumber}, and {@link weekday} accessors.
+ * * **Configuration** See the {@link locale} and {@link numberingSystem} accessors.
+ * * **Transformation**: To transform the DateTime into other DateTimes, use {@link set}, {@link reconfigure}, {@link setZone}, {@link setLocale}, {@link plus}, {@link minus}, {@link endOf}, {@link startOf}, {@link toUTC}, and {@link toLocal}.
+ * * **Output**: To convert the DateTime to other representations, use the {@link toRelative}, {@link toRelativeCalendar}, {@link toJSON}, {@link toISO}, {@link toHTTP}, {@link toObject}, {@link toRFC2822}, {@link toString}, {@link toLocaleString}, {@link toFormat}, {@link toMillis} and {@link toJSDate}.
+ *
+ * There's plenty others documented below. In addition, for more information on subtler topics like internationalization, time zones, alternative calendars, validity, and so on, see the external documentation.
+ */
+
+
+ var DateTime = /*#__PURE__*/function () {
+ /**
+ * @access private
+ */
+ function DateTime(config) {
+ var zone = config.zone || Settings.defaultZone;
+ var invalid = config.invalid || (Number.isNaN(config.ts) ? new Invalid("invalid input") : null) || (!zone.isValid ? unsupportedZone(zone) : null);
+ /**
+ * @access private
+ */
+
+ this.ts = isUndefined(config.ts) ? Settings.now() : config.ts;
+ var c = null,
+ o = null;
+
+ if (!invalid) {
+ var unchanged = config.old && config.old.ts === this.ts && config.old.zone.equals(zone);
+
+ if (unchanged) {
+ var _ref2 = [config.old.c, config.old.o];
+ c = _ref2[0];
+ o = _ref2[1];
+ } else {
+ var ot = zone.offset(this.ts);
+ c = tsToObj(this.ts, ot);
+ invalid = Number.isNaN(c.year) ? new Invalid("invalid input") : null;
+ c = invalid ? null : c;
+ o = invalid ? null : ot;
+ }
+ }
+ /**
+ * @access private
+ */
+
+
+ this._zone = zone;
+ /**
+ * @access private
+ */
+
+ this.loc = config.loc || Locale.create();
+ /**
+ * @access private
+ */
+
+ this.invalid = invalid;
+ /**
+ * @access private
+ */
+
+ this.weekData = null;
+ /**
+ * @access private
+ */
+
+ this.c = c;
+ /**
+ * @access private
+ */
+
+ this.o = o;
+ /**
+ * @access private
+ */
+
+ this.isLuxonDateTime = true;
+ } // CONSTRUCT
+
+ /**
+ * Create a local DateTime
+ * @param {number} [year] - The calendar year. If omitted (as in, call `local()` with no arguments), the current time will be used
+ * @param {number} [month=1] - The month, 1-indexed
+ * @param {number} [day=1] - The day of the month
+ * @param {number} [hour=0] - The hour of the day, in 24-hour time
+ * @param {number} [minute=0] - The minute of the hour, meaning a number between 0 and 59
+ * @param {number} [second=0] - The second of the minute, meaning a number between 0 and 59
+ * @param {number} [millisecond=0] - The millisecond of the second, meaning a number between 0 and 999
+ * @example DateTime.local() //~> now
+ * @example DateTime.local(2017) //~> 2017-01-01T00:00:00
+ * @example DateTime.local(2017, 3) //~> 2017-03-01T00:00:00
+ * @example DateTime.local(2017, 3, 12) //~> 2017-03-12T00:00:00
+ * @example DateTime.local(2017, 3, 12, 5) //~> 2017-03-12T05:00:00
+ * @example DateTime.local(2017, 3, 12, 5, 45) //~> 2017-03-12T05:45:00
+ * @example DateTime.local(2017, 3, 12, 5, 45, 10) //~> 2017-03-12T05:45:10
+ * @example DateTime.local(2017, 3, 12, 5, 45, 10, 765) //~> 2017-03-12T05:45:10.765
+ * @return {DateTime}
+ */
+
+
+ DateTime.local = function local(year, month, day, hour, minute, second, millisecond) {
+ if (isUndefined(year)) {
+ return new DateTime({
+ ts: Settings.now()
+ });
+ } else {
+ return quickDT({
+ year: year,
+ month: month,
+ day: day,
+ hour: hour,
+ minute: minute,
+ second: second,
+ millisecond: millisecond
+ }, Settings.defaultZone);
+ }
+ }
+ /**
+ * Create a DateTime in UTC
+ * @param {number} [year] - The calendar year. If omitted (as in, call `utc()` with no arguments), the current time will be used
+ * @param {number} [month=1] - The month, 1-indexed
+ * @param {number} [day=1] - The day of the month
+ * @param {number} [hour=0] - The hour of the day, in 24-hour time
+ * @param {number} [minute=0] - The minute of the hour, meaning a number between 0 and 59
+ * @param {number} [second=0] - The second of the minute, meaning a number between 0 and 59
+ * @param {number} [millisecond=0] - The millisecond of the second, meaning a number between 0 and 999
+ * @example DateTime.utc() //~> now
+ * @example DateTime.utc(2017) //~> 2017-01-01T00:00:00Z
+ * @example DateTime.utc(2017, 3) //~> 2017-03-01T00:00:00Z
+ * @example DateTime.utc(2017, 3, 12) //~> 2017-03-12T00:00:00Z
+ * @example DateTime.utc(2017, 3, 12, 5) //~> 2017-03-12T05:00:00Z
+ * @example DateTime.utc(2017, 3, 12, 5, 45) //~> 2017-03-12T05:45:00Z
+ * @example DateTime.utc(2017, 3, 12, 5, 45, 10) //~> 2017-03-12T05:45:10Z
+ * @example DateTime.utc(2017, 3, 12, 5, 45, 10, 765) //~> 2017-03-12T05:45:10.765Z
+ * @return {DateTime}
+ */
+ ;
+
+ DateTime.utc = function utc(year, month, day, hour, minute, second, millisecond) {
+ if (isUndefined(year)) {
+ return new DateTime({
+ ts: Settings.now(),
+ zone: FixedOffsetZone.utcInstance
+ });
+ } else {
+ return quickDT({
+ year: year,
+ month: month,
+ day: day,
+ hour: hour,
+ minute: minute,
+ second: second,
+ millisecond: millisecond
+ }, FixedOffsetZone.utcInstance);
+ }
+ }
+ /**
+ * Create a DateTime from a Javascript Date object. Uses the default zone.
+ * @param {Date} date - a Javascript Date object
+ * @param {Object} options - configuration options for the DateTime
+ * @param {string|Zone} [options.zone='local'] - the zone to place the DateTime into
+ * @return {DateTime}
+ */
+ ;
+
+ DateTime.fromJSDate = function fromJSDate(date, options) {
+ if (options === void 0) {
+ options = {};
+ }
+
+ var ts = isDate(date) ? date.valueOf() : NaN;
+
+ if (Number.isNaN(ts)) {
+ return DateTime.invalid("invalid input");
+ }
+
+ var zoneToUse = normalizeZone(options.zone, Settings.defaultZone);
+
+ if (!zoneToUse.isValid) {
+ return DateTime.invalid(unsupportedZone(zoneToUse));
+ }
+
+ return new DateTime({
+ ts: ts,
+ zone: zoneToUse,
+ loc: Locale.fromObject(options)
+ });
+ }
+ /**
+ * Create a DateTime from a number of milliseconds since the epoch (meaning since 1 January 1970 00:00:00 UTC). Uses the default zone.
+ * @param {number} milliseconds - a number of milliseconds since 1970 UTC
+ * @param {Object} options - configuration options for the DateTime
+ * @param {string|Zone} [options.zone='local'] - the zone to place the DateTime into
+ * @param {string} [options.locale] - a locale to set on the resulting DateTime instance
+ * @param {string} options.outputCalendar - the output calendar to set on the resulting DateTime instance
+ * @param {string} options.numberingSystem - the numbering system to set on the resulting DateTime instance
+ * @return {DateTime}
+ */
+ ;
+
+ DateTime.fromMillis = function fromMillis(milliseconds, options) {
+ if (options === void 0) {
+ options = {};
+ }
+
+ if (!isNumber(milliseconds)) {
+ throw new InvalidArgumentError("fromMillis requires a numerical input, but received a " + typeof milliseconds + " with value " + milliseconds);
+ } else if (milliseconds < -MAX_DATE || milliseconds > MAX_DATE) {
+ // this isn't perfect because because we can still end up out of range because of additional shifting, but it's a start
+ return DateTime.invalid("Timestamp out of range");
+ } else {
+ return new DateTime({
+ ts: milliseconds,
+ zone: normalizeZone(options.zone, Settings.defaultZone),
+ loc: Locale.fromObject(options)
+ });
+ }
+ }
+ /**
+ * Create a DateTime from a number of seconds since the epoch (meaning since 1 January 1970 00:00:00 UTC). Uses the default zone.
+ * @param {number} seconds - a number of seconds since 1970 UTC
+ * @param {Object} options - configuration options for the DateTime
+ * @param {string|Zone} [options.zone='local'] - the zone to place the DateTime into
+ * @param {string} [options.locale] - a locale to set on the resulting DateTime instance
+ * @param {string} options.outputCalendar - the output calendar to set on the resulting DateTime instance
+ * @param {string} options.numberingSystem - the numbering system to set on the resulting DateTime instance
+ * @return {DateTime}
+ */
+ ;
+
+ DateTime.fromSeconds = function fromSeconds(seconds, options) {
+ if (options === void 0) {
+ options = {};
+ }
+
+ if (!isNumber(seconds)) {
+ throw new InvalidArgumentError("fromSeconds requires a numerical input");
+ } else {
+ return new DateTime({
+ ts: seconds * 1000,
+ zone: normalizeZone(options.zone, Settings.defaultZone),
+ loc: Locale.fromObject(options)
+ });
+ }
+ }
+ /**
+ * Create a DateTime from a Javascript object with keys like 'year' and 'hour' with reasonable defaults.
+ * @param {Object} obj - the object to create the DateTime from
+ * @param {number} obj.year - a year, such as 1987
+ * @param {number} obj.month - a month, 1-12
+ * @param {number} obj.day - a day of the month, 1-31, depending on the month
+ * @param {number} obj.ordinal - day of the year, 1-365 or 366
+ * @param {number} obj.weekYear - an ISO week year
+ * @param {number} obj.weekNumber - an ISO week number, between 1 and 52 or 53, depending on the year
+ * @param {number} obj.weekday - an ISO weekday, 1-7, where 1 is Monday and 7 is Sunday
+ * @param {number} obj.hour - hour of the day, 0-23
+ * @param {number} obj.minute - minute of the hour, 0-59
+ * @param {number} obj.second - second of the minute, 0-59
+ * @param {number} obj.millisecond - millisecond of the second, 0-999
+ * @param {string|Zone} [obj.zone='local'] - interpret the numbers in the context of a particular zone. Can take any value taken as the first argument to setZone()
+ * @param {string} [obj.locale='system's locale'] - a locale to set on the resulting DateTime instance
+ * @param {string} obj.outputCalendar - the output calendar to set on the resulting DateTime instance
+ * @param {string} obj.numberingSystem - the numbering system to set on the resulting DateTime instance
+ * @example DateTime.fromObject({ year: 1982, month: 5, day: 25}).toISODate() //=> '1982-05-25'
+ * @example DateTime.fromObject({ year: 1982 }).toISODate() //=> '1982-01-01'
+ * @example DateTime.fromObject({ hour: 10, minute: 26, second: 6 }) //~> today at 10:26:06
+ * @example DateTime.fromObject({ hour: 10, minute: 26, second: 6, zone: 'utc' }),
+ * @example DateTime.fromObject({ hour: 10, minute: 26, second: 6, zone: 'local' })
+ * @example DateTime.fromObject({ hour: 10, minute: 26, second: 6, zone: 'America/New_York' })
+ * @example DateTime.fromObject({ weekYear: 2016, weekNumber: 2, weekday: 3 }).toISODate() //=> '2016-01-13'
+ * @return {DateTime}
+ */
+ ;
+
+ DateTime.fromObject = function fromObject(obj) {
+ var zoneToUse = normalizeZone(obj.zone, Settings.defaultZone);
+
+ if (!zoneToUse.isValid) {
+ return DateTime.invalid(unsupportedZone(zoneToUse));
+ }
+
+ var tsNow = Settings.now(),
+ offsetProvis = zoneToUse.offset(tsNow),
+ normalized = normalizeObject(obj, normalizeUnit, ["zone", "locale", "outputCalendar", "numberingSystem"]),
+ containsOrdinal = !isUndefined(normalized.ordinal),
+ containsGregorYear = !isUndefined(normalized.year),
+ containsGregorMD = !isUndefined(normalized.month) || !isUndefined(normalized.day),
+ containsGregor = containsGregorYear || containsGregorMD,
+ definiteWeekDef = normalized.weekYear || normalized.weekNumber,
+ loc = Locale.fromObject(obj); // cases:
+ // just a weekday -> this week's instance of that weekday, no worries
+ // (gregorian data or ordinal) + (weekYear or weekNumber) -> error
+ // (gregorian month or day) + ordinal -> error
+ // otherwise just use weeks or ordinals or gregorian, depending on what's specified
+
+ if ((containsGregor || containsOrdinal) && definiteWeekDef) {
+ throw new ConflictingSpecificationError("Can't mix weekYear/weekNumber units with year/month/day or ordinals");
+ }
+
+ if (containsGregorMD && containsOrdinal) {
+ throw new ConflictingSpecificationError("Can't mix ordinal dates with month/day");
+ }
+
+ var useWeekData = definiteWeekDef || normalized.weekday && !containsGregor; // configure ourselves to deal with gregorian dates or week stuff
+
+ var units,
+ defaultValues,
+ objNow = tsToObj(tsNow, offsetProvis);
+
+ if (useWeekData) {
+ units = orderedWeekUnits;
+ defaultValues = defaultWeekUnitValues;
+ objNow = gregorianToWeek(objNow);
+ } else if (containsOrdinal) {
+ units = orderedOrdinalUnits;
+ defaultValues = defaultOrdinalUnitValues;
+ objNow = gregorianToOrdinal(objNow);
+ } else {
+ units = orderedUnits$1;
+ defaultValues = defaultUnitValues;
+ } // set default values for missing stuff
+
+
+ var foundFirst = false;
+
+ for (var _iterator3 = _createForOfIteratorHelperLoose(units), _step3; !(_step3 = _iterator3()).done;) {
+ var u = _step3.value;
+ var v = normalized[u];
+
+ if (!isUndefined(v)) {
+ foundFirst = true;
+ } else if (foundFirst) {
+ normalized[u] = defaultValues[u];
+ } else {
+ normalized[u] = objNow[u];
+ }
+ } // make sure the values we have are in range
+
+
+ var higherOrderInvalid = useWeekData ? hasInvalidWeekData(normalized) : containsOrdinal ? hasInvalidOrdinalData(normalized) : hasInvalidGregorianData(normalized),
+ invalid = higherOrderInvalid || hasInvalidTimeData(normalized);
+
+ if (invalid) {
+ return DateTime.invalid(invalid);
+ } // compute the actual time
+
+
+ var gregorian = useWeekData ? weekToGregorian(normalized) : containsOrdinal ? ordinalToGregorian(normalized) : normalized,
+ _objToTS2 = objToTS(gregorian, offsetProvis, zoneToUse),
+ tsFinal = _objToTS2[0],
+ offsetFinal = _objToTS2[1],
+ inst = new DateTime({
+ ts: tsFinal,
+ zone: zoneToUse,
+ o: offsetFinal,
+ loc: loc
+ }); // gregorian data + weekday serves only to validate
+
+
+ if (normalized.weekday && containsGregor && obj.weekday !== inst.weekday) {
+ return DateTime.invalid("mismatched weekday", "you can't specify both a weekday of " + normalized.weekday + " and a date of " + inst.toISO());
+ }
+
+ return inst;
+ }
+ /**
+ * Create a DateTime from an ISO 8601 string
+ * @param {string} text - the ISO string
+ * @param {Object} opts - options to affect the creation
+ * @param {string|Zone} [opts.zone='local'] - use this zone if no offset is specified in the input string itself. Will also convert the time to this zone
+ * @param {boolean} [opts.setZone=false] - override the zone with a fixed-offset zone specified in the string itself, if it specifies one
+ * @param {string} [opts.locale='system's locale'] - a locale to set on the resulting DateTime instance
+ * @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance
+ * @param {string} opts.numberingSystem - the numbering system to set on the resulting DateTime instance
+ * @example DateTime.fromISO('2016-05-25T09:08:34.123')
+ * @example DateTime.fromISO('2016-05-25T09:08:34.123+06:00')
+ * @example DateTime.fromISO('2016-05-25T09:08:34.123+06:00', {setZone: true})
+ * @example DateTime.fromISO('2016-05-25T09:08:34.123', {zone: 'utc'})
+ * @example DateTime.fromISO('2016-W05-4')
+ * @return {DateTime}
+ */
+ ;
+
+ DateTime.fromISO = function fromISO(text, opts) {
+ if (opts === void 0) {
+ opts = {};
+ }
+
+ var _parseISODate = parseISODate(text),
+ vals = _parseISODate[0],
+ parsedZone = _parseISODate[1];
+
+ return parseDataToDateTime(vals, parsedZone, opts, "ISO 8601", text);
+ }
+ /**
+ * Create a DateTime from an RFC 2822 string
+ * @param {string} text - the RFC 2822 string
+ * @param {Object} opts - options to affect the creation
+ * @param {string|Zone} [opts.zone='local'] - convert the time to this zone. Since the offset is always specified in the string itself, this has no effect on the interpretation of string, merely the zone the resulting DateTime is expressed in.
+ * @param {boolean} [opts.setZone=false] - override the zone with a fixed-offset zone specified in the string itself, if it specifies one
+ * @param {string} [opts.locale='system's locale'] - a locale to set on the resulting DateTime instance
+ * @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance
+ * @param {string} opts.numberingSystem - the numbering system to set on the resulting DateTime instance
+ * @example DateTime.fromRFC2822('25 Nov 2016 13:23:12 GMT')
+ * @example DateTime.fromRFC2822('Fri, 25 Nov 2016 13:23:12 +0600')
+ * @example DateTime.fromRFC2822('25 Nov 2016 13:23 Z')
+ * @return {DateTime}
+ */
+ ;
+
+ DateTime.fromRFC2822 = function fromRFC2822(text, opts) {
+ if (opts === void 0) {
+ opts = {};
+ }
+
+ var _parseRFC2822Date = parseRFC2822Date(text),
+ vals = _parseRFC2822Date[0],
+ parsedZone = _parseRFC2822Date[1];
+
+ return parseDataToDateTime(vals, parsedZone, opts, "RFC 2822", text);
+ }
+ /**
+ * Create a DateTime from an HTTP header date
+ * @see https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3.1
+ * @param {string} text - the HTTP header date
+ * @param {Object} opts - options to affect the creation
+ * @param {string|Zone} [opts.zone='local'] - convert the time to this zone. Since HTTP dates are always in UTC, this has no effect on the interpretation of string, merely the zone the resulting DateTime is expressed in.
+ * @param {boolean} [opts.setZone=false] - override the zone with the fixed-offset zone specified in the string. For HTTP dates, this is always UTC, so this option is equivalent to setting the `zone` option to 'utc', but this option is included for consistency with similar methods.
+ * @param {string} [opts.locale='system's locale'] - a locale to set on the resulting DateTime instance
+ * @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance
+ * @param {string} opts.numberingSystem - the numbering system to set on the resulting DateTime instance
+ * @example DateTime.fromHTTP('Sun, 06 Nov 1994 08:49:37 GMT')
+ * @example DateTime.fromHTTP('Sunday, 06-Nov-94 08:49:37 GMT')
+ * @example DateTime.fromHTTP('Sun Nov 6 08:49:37 1994')
+ * @return {DateTime}
+ */
+ ;
+
+ DateTime.fromHTTP = function fromHTTP(text, opts) {
+ if (opts === void 0) {
+ opts = {};
+ }
+
+ var _parseHTTPDate = parseHTTPDate(text),
+ vals = _parseHTTPDate[0],
+ parsedZone = _parseHTTPDate[1];
+
+ return parseDataToDateTime(vals, parsedZone, opts, "HTTP", opts);
+ }
+ /**
+ * Create a DateTime from an input string and format string.
+ * Defaults to en-US if no locale has been specified, regardless of the system's locale.
+ * @see https://moment.github.io/luxon/docs/manual/parsing.html#table-of-tokens
+ * @param {string} text - the string to parse
+ * @param {string} fmt - the format the string is expected to be in (see the link below for the formats)
+ * @param {Object} opts - options to affect the creation
+ * @param {string|Zone} [opts.zone='local'] - use this zone if no offset is specified in the input string itself. Will also convert the DateTime to this zone
+ * @param {boolean} [opts.setZone=false] - override the zone with a zone specified in the string itself, if it specifies one
+ * @param {string} [opts.locale='en-US'] - a locale string to use when parsing. Will also set the DateTime to this locale
+ * @param {string} opts.numberingSystem - the numbering system to use when parsing. Will also set the resulting DateTime to this numbering system
+ * @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance
+ * @return {DateTime}
+ */
+ ;
+
+ DateTime.fromFormat = function fromFormat(text, fmt, opts) {
+ if (opts === void 0) {
+ opts = {};
+ }
+
+ if (isUndefined(text) || isUndefined(fmt)) {
+ throw new InvalidArgumentError("fromFormat requires an input string and a format");
+ }
+
+ var _opts = opts,
+ _opts$locale = _opts.locale,
+ locale = _opts$locale === void 0 ? null : _opts$locale,
+ _opts$numberingSystem = _opts.numberingSystem,
+ numberingSystem = _opts$numberingSystem === void 0 ? null : _opts$numberingSystem,
+ localeToUse = Locale.fromOpts({
+ locale: locale,
+ numberingSystem: numberingSystem,
+ defaultToEN: true
+ }),
+ _parseFromTokens = parseFromTokens(localeToUse, text, fmt),
+ vals = _parseFromTokens[0],
+ parsedZone = _parseFromTokens[1],
+ invalid = _parseFromTokens[2];
+
+ if (invalid) {
+ return DateTime.invalid(invalid);
+ } else {
+ return parseDataToDateTime(vals, parsedZone, opts, "format " + fmt, text);
+ }
+ }
+ /**
+ * @deprecated use fromFormat instead
+ */
+ ;
+
+ DateTime.fromString = function fromString(text, fmt, opts) {
+ if (opts === void 0) {
+ opts = {};
+ }
+
+ return DateTime.fromFormat(text, fmt, opts);
+ }
+ /**
+ * Create a DateTime from a SQL date, time, or datetime
+ * Defaults to en-US if no locale has been specified, regardless of the system's locale
+ * @param {string} text - the string to parse
+ * @param {Object} opts - options to affect the creation
+ * @param {string|Zone} [opts.zone='local'] - use this zone if no offset is specified in the input string itself. Will also convert the DateTime to this zone
+ * @param {boolean} [opts.setZone=false] - override the zone with a zone specified in the string itself, if it specifies one
+ * @param {string} [opts.locale='en-US'] - a locale string to use when parsing. Will also set the DateTime to this locale
+ * @param {string} opts.numberingSystem - the numbering system to use when parsing. Will also set the resulting DateTime to this numbering system
+ * @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance
+ * @example DateTime.fromSQL('2017-05-15')
+ * @example DateTime.fromSQL('2017-05-15 09:12:34')
+ * @example DateTime.fromSQL('2017-05-15 09:12:34.342')
+ * @example DateTime.fromSQL('2017-05-15 09:12:34.342+06:00')
+ * @example DateTime.fromSQL('2017-05-15 09:12:34.342 America/Los_Angeles')
+ * @example DateTime.fromSQL('2017-05-15 09:12:34.342 America/Los_Angeles', { setZone: true })
+ * @example DateTime.fromSQL('2017-05-15 09:12:34.342', { zone: 'America/Los_Angeles' })
+ * @example DateTime.fromSQL('09:12:34.342')
+ * @return {DateTime}
+ */
+ ;
+
+ DateTime.fromSQL = function fromSQL(text, opts) {
+ if (opts === void 0) {
+ opts = {};
+ }
+
+ var _parseSQL = parseSQL(text),
+ vals = _parseSQL[0],
+ parsedZone = _parseSQL[1];
+
+ return parseDataToDateTime(vals, parsedZone, opts, "SQL", text);
+ }
+ /**
+ * Create an invalid DateTime.
+ * @param {string} reason - simple string of why this DateTime is invalid. Should not contain parameters or anything else data-dependent
+ * @param {string} [explanation=null] - longer explanation, may include parameters and other useful debugging information
+ * @return {DateTime}
+ */
+ ;
+
+ DateTime.invalid = function invalid(reason, explanation) {
+ if (explanation === void 0) {
+ explanation = null;
+ }
+
+ if (!reason) {
+ throw new InvalidArgumentError("need to specify a reason the DateTime is invalid");
+ }
+
+ var invalid = reason instanceof Invalid ? reason : new Invalid(reason, explanation);
+
+ if (Settings.throwOnInvalid) {
+ throw new InvalidDateTimeError(invalid);
+ } else {
+ return new DateTime({
+ invalid: invalid
+ });
+ }
+ }
+ /**
+ * Check if an object is a DateTime. Works across context boundaries
+ * @param {object} o
+ * @return {boolean}
+ */
+ ;
+
+ DateTime.isDateTime = function isDateTime(o) {
+ return o && o.isLuxonDateTime || false;
+ } // INFO
+
+ /**
+ * Get the value of unit.
+ * @param {string} unit - a unit such as 'minute' or 'day'
+ * @example DateTime.local(2017, 7, 4).get('month'); //=> 7
+ * @example DateTime.local(2017, 7, 4).get('day'); //=> 4
+ * @return {number}
+ */
+ ;
+
+ var _proto = DateTime.prototype;
+
+ _proto.get = function get(unit) {
+ return this[unit];
+ }
+ /**
+ * Returns whether the DateTime is valid. Invalid DateTimes occur when:
+ * * The DateTime was created from invalid calendar information, such as the 13th month or February 30
+ * * The DateTime was created by an operation on another invalid date
+ * @type {boolean}
+ */
+ ;
+
+ /**
+ * Returns the resolved Intl options for this DateTime.
+ * This is useful in understanding the behavior of formatting methods
+ * @param {Object} opts - the same options as toLocaleString
+ * @return {Object}
+ */
+ _proto.resolvedLocaleOpts = function resolvedLocaleOpts(opts) {
+ if (opts === void 0) {
+ opts = {};
+ }
+
+ var _Formatter$create$res = Formatter.create(this.loc.clone(opts), opts).resolvedOptions(this),
+ locale = _Formatter$create$res.locale,
+ numberingSystem = _Formatter$create$res.numberingSystem,
+ calendar = _Formatter$create$res.calendar;
+
+ return {
+ locale: locale,
+ numberingSystem: numberingSystem,
+ outputCalendar: calendar
+ };
+ } // TRANSFORM
+
+ /**
+ * "Set" the DateTime's zone to UTC. Returns a newly-constructed DateTime.
+ *
+ * Equivalent to {@link setZone}('utc')
+ * @param {number} [offset=0] - optionally, an offset from UTC in minutes
+ * @param {Object} [opts={}] - options to pass to `setZone()`
+ * @return {DateTime}
+ */
+ ;
+
+ _proto.toUTC = function toUTC(offset, opts) {
+ if (offset === void 0) {
+ offset = 0;
+ }
+
+ if (opts === void 0) {
+ opts = {};
+ }
+
+ return this.setZone(FixedOffsetZone.instance(offset), opts);
+ }
+ /**
+ * "Set" the DateTime's zone to the host's local zone. Returns a newly-constructed DateTime.
+ *
+ * Equivalent to `setZone('local')`
+ * @return {DateTime}
+ */
+ ;
+
+ _proto.toLocal = function toLocal() {
+ return this.setZone(Settings.defaultZone);
+ }
+ /**
+ * "Set" the DateTime's zone to specified zone. Returns a newly-constructed DateTime.
+ *
+ * By default, the setter keeps the underlying time the same (as in, the same timestamp), but the new instance will report different local times and consider DSTs when making computations, as with {@link plus}. You may wish to use {@link toLocal} and {@link toUTC} which provide simple convenience wrappers for commonly used zones.
+ * @param {string|Zone} [zone='local'] - a zone identifier. As a string, that can be any IANA zone supported by the host environment, or a fixed-offset name of the form 'UTC+3', or the strings 'local' or 'utc'. You may also supply an instance of a {@link Zone} class.
+ * @param {Object} opts - options
+ * @param {boolean} [opts.keepLocalTime=false] - If true, adjust the underlying time so that the local time stays the same, but in the target zone. You should rarely need this.
+ * @return {DateTime}
+ */
+ ;
+
+ _proto.setZone = function setZone(zone, _temp) {
+ var _ref3 = _temp === void 0 ? {} : _temp,
+ _ref3$keepLocalTime = _ref3.keepLocalTime,
+ keepLocalTime = _ref3$keepLocalTime === void 0 ? false : _ref3$keepLocalTime,
+ _ref3$keepCalendarTim = _ref3.keepCalendarTime,
+ keepCalendarTime = _ref3$keepCalendarTim === void 0 ? false : _ref3$keepCalendarTim;
+
+ zone = normalizeZone(zone, Settings.defaultZone);
+
+ if (zone.equals(this.zone)) {
+ return this;
+ } else if (!zone.isValid) {
+ return DateTime.invalid(unsupportedZone(zone));
+ } else {
+ var newTS = this.ts;
+
+ if (keepLocalTime || keepCalendarTime) {
+ var offsetGuess = zone.offset(this.ts);
+ var asObj = this.toObject();
+
+ var _objToTS3 = objToTS(asObj, offsetGuess, zone);
+
+ newTS = _objToTS3[0];
+ }
+
+ return clone$1(this, {
+ ts: newTS,
+ zone: zone
+ });
+ }
+ }
+ /**
+ * "Set" the locale, numberingSystem, or outputCalendar. Returns a newly-constructed DateTime.
+ * @param {Object} properties - the properties to set
+ * @example DateTime.local(2017, 5, 25).reconfigure({ locale: 'en-GB' })
+ * @return {DateTime}
+ */
+ ;
+
+ _proto.reconfigure = function reconfigure(_temp2) {
+ var _ref4 = _temp2 === void 0 ? {} : _temp2,
+ locale = _ref4.locale,
+ numberingSystem = _ref4.numberingSystem,
+ outputCalendar = _ref4.outputCalendar;
+
+ var loc = this.loc.clone({
+ locale: locale,
+ numberingSystem: numberingSystem,
+ outputCalendar: outputCalendar
+ });
+ return clone$1(this, {
+ loc: loc
+ });
+ }
+ /**
+ * "Set" the locale. Returns a newly-constructed DateTime.
+ * Just a convenient alias for reconfigure({ locale })
+ * @example DateTime.local(2017, 5, 25).setLocale('en-GB')
+ * @return {DateTime}
+ */
+ ;
+
+ _proto.setLocale = function setLocale(locale) {
+ return this.reconfigure({
+ locale: locale
+ });
+ }
+ /**
+ * "Set" the values of specified units. Returns a newly-constructed DateTime.
+ * You can only set units with this method; for "setting" metadata, see {@link reconfigure} and {@link setZone}.
+ * @param {Object} values - a mapping of units to numbers
+ * @example dt.set({ year: 2017 })
+ * @example dt.set({ hour: 8, minute: 30 })
+ * @example dt.set({ weekday: 5 })
+ * @example dt.set({ year: 2005, ordinal: 234 })
+ * @return {DateTime}
+ */
+ ;
+
+ _proto.set = function set(values) {
+ if (!this.isValid) return this;
+ var normalized = normalizeObject(values, normalizeUnit, []),
+ settingWeekStuff = !isUndefined(normalized.weekYear) || !isUndefined(normalized.weekNumber) || !isUndefined(normalized.weekday);
+ var mixed;
+
+ if (settingWeekStuff) {
+ mixed = weekToGregorian(Object.assign(gregorianToWeek(this.c), normalized));
+ } else if (!isUndefined(normalized.ordinal)) {
+ mixed = ordinalToGregorian(Object.assign(gregorianToOrdinal(this.c), normalized));
+ } else {
+ mixed = Object.assign(this.toObject(), normalized); // if we didn't set the day but we ended up on an overflow date,
+ // use the last day of the right month
+
+ if (isUndefined(normalized.day)) {
+ mixed.day = Math.min(daysInMonth(mixed.year, mixed.month), mixed.day);
+ }
+ }
+
+ var _objToTS4 = objToTS(mixed, this.o, this.zone),
+ ts = _objToTS4[0],
+ o = _objToTS4[1];
+
+ return clone$1(this, {
+ ts: ts,
+ o: o
+ });
+ }
+ /**
+ * Add a period of time to this DateTime and return the resulting DateTime
+ *
+ * Adding hours, minutes, seconds, or milliseconds increases the timestamp by the right number of milliseconds. Adding days, months, or years shifts the calendar, accounting for DSTs and leap years along the way. Thus, `dt.plus({ hours: 24 })` may result in a different time than `dt.plus({ days: 1 })` if there's a DST shift in between.
+ * @param {Duration|Object|number} duration - The amount to add. Either a Luxon Duration, a number of milliseconds, the object argument to Duration.fromObject()
+ * @example DateTime.local().plus(123) //~> in 123 milliseconds
+ * @example DateTime.local().plus({ minutes: 15 }) //~> in 15 minutes
+ * @example DateTime.local().plus({ days: 1 }) //~> this time tomorrow
+ * @example DateTime.local().plus({ days: -1 }) //~> this time yesterday
+ * @example DateTime.local().plus({ hours: 3, minutes: 13 }) //~> in 3 hr, 13 min
+ * @example DateTime.local().plus(Duration.fromObject({ hours: 3, minutes: 13 })) //~> in 3 hr, 13 min
+ * @return {DateTime}
+ */
+ ;
+
+ _proto.plus = function plus(duration) {
+ if (!this.isValid) return this;
+ var dur = friendlyDuration(duration);
+ return clone$1(this, adjustTime(this, dur));
+ }
+ /**
+ * Subtract a period of time to this DateTime and return the resulting DateTime
+ * See {@link plus}
+ * @param {Duration|Object|number} duration - The amount to subtract. Either a Luxon Duration, a number of milliseconds, the object argument to Duration.fromObject()
+ @return {DateTime}
+ */
+ ;
+
+ _proto.minus = function minus(duration) {
+ if (!this.isValid) return this;
+ var dur = friendlyDuration(duration).negate();
+ return clone$1(this, adjustTime(this, dur));
+ }
+ /**
+ * "Set" this DateTime to the beginning of a unit of time.
+ * @param {string} unit - The unit to go to the beginning of. Can be 'year', 'quarter', 'month', 'week', 'day', 'hour', 'minute', 'second', or 'millisecond'.
+ * @example DateTime.local(2014, 3, 3).startOf('month').toISODate(); //=> '2014-03-01'
+ * @example DateTime.local(2014, 3, 3).startOf('year').toISODate(); //=> '2014-01-01'
+ * @example DateTime.local(2014, 3, 3, 5, 30).startOf('day').toISOTime(); //=> '00:00.000-05:00'
+ * @example DateTime.local(2014, 3, 3, 5, 30).startOf('hour').toISOTime(); //=> '05:00:00.000-05:00'
+ * @return {DateTime}
+ */
+ ;
+
+ _proto.startOf = function startOf(unit) {
+ if (!this.isValid) return this;
+ var o = {},
+ normalizedUnit = Duration.normalizeUnit(unit);
+
+ switch (normalizedUnit) {
+ case "years":
+ o.month = 1;
+ // falls through
+
+ case "quarters":
+ case "months":
+ o.day = 1;
+ // falls through
+
+ case "weeks":
+ case "days":
+ o.hour = 0;
+ // falls through
+
+ case "hours":
+ o.minute = 0;
+ // falls through
+
+ case "minutes":
+ o.second = 0;
+ // falls through
+
+ case "seconds":
+ o.millisecond = 0;
+ break;
+ // no default, invalid units throw in normalizeUnit()
+ }
+
+ if (normalizedUnit === "weeks") {
+ o.weekday = 1;
+ }
+
+ if (normalizedUnit === "quarters") {
+ var q = Math.ceil(this.month / 3);
+ o.month = (q - 1) * 3 + 1;
+ }
+
+ return this.set(o);
+ }
+ /**
+ * "Set" this DateTime to the end (meaning the last millisecond) of a unit of time
+ * @param {string} unit - The unit to go to the end of. Can be 'year', 'month', 'day', 'hour', 'minute', 'second', or 'millisecond'.
+ * @example DateTime.local(2014, 3, 3).endOf('month').toISO(); //=> '2014-03-31T23:59:59.999-05:00'
+ * @example DateTime.local(2014, 3, 3).endOf('year').toISO(); //=> '2014-12-31T23:59:59.999-05:00'
+ * @example DateTime.local(2014, 3, 3, 5, 30).endOf('day').toISO(); //=> '2014-03-03T23:59:59.999-05:00'
+ * @example DateTime.local(2014, 3, 3, 5, 30).endOf('hour').toISO(); //=> '2014-03-03T05:59:59.999-05:00'
+ * @return {DateTime}
+ */
+ ;
+
+ _proto.endOf = function endOf(unit) {
+ var _this$plus;
+
+ return this.isValid ? this.plus((_this$plus = {}, _this$plus[unit] = 1, _this$plus)).startOf(unit).minus(1) : this;
+ } // OUTPUT
+
+ /**
+ * Returns a string representation of this DateTime formatted according to the specified format string.
+ * **You may not want this.** See {@link toLocaleString} for a more flexible formatting tool. For a table of tokens and their interpretations, see [here](https://moment.github.io/luxon/docs/manual/formatting.html#table-of-tokens).
+ * Defaults to en-US if no locale has been specified, regardless of the system's locale.
+ * @see https://moment.github.io/luxon/docs/manual/formatting.html#table-of-tokens
+ * @param {string} fmt - the format string
+ * @param {Object} opts - opts to override the configuration options
+ * @example DateTime.local().toFormat('yyyy LLL dd') //=> '2017 Apr 22'
+ * @example DateTime.local().setLocale('fr').toFormat('yyyy LLL dd') //=> '2017 avr. 22'
+ * @example DateTime.local().toFormat('yyyy LLL dd', { locale: "fr" }) //=> '2017 avr. 22'
+ * @example DateTime.local().toFormat("HH 'hours and' mm 'minutes'") //=> '20 hours and 55 minutes'
+ * @return {string}
+ */
+ ;
+
+ _proto.toFormat = function toFormat(fmt, opts) {
+ if (opts === void 0) {
+ opts = {};
+ }
+
+ return this.isValid ? Formatter.create(this.loc.redefaultToEN(opts)).formatDateTimeFromString(this, fmt) : INVALID$2;
+ }
+ /**
+ * Returns a localized string representing this date. Accepts the same options as the Intl.DateTimeFormat constructor and any presets defined by Luxon, such as `DateTime.DATE_FULL` or `DateTime.TIME_SIMPLE`.
+ * The exact behavior of this method is browser-specific, but in general it will return an appropriate representation
+ * of the DateTime in the assigned locale.
+ * Defaults to the system's locale if no locale has been specified
+ * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat
+ * @param opts {Object} - Intl.DateTimeFormat constructor options and configuration options
+ * @example DateTime.local().toLocaleString(); //=> 4/20/2017
+ * @example DateTime.local().setLocale('en-gb').toLocaleString(); //=> '20/04/2017'
+ * @example DateTime.local().toLocaleString({ locale: 'en-gb' }); //=> '20/04/2017'
+ * @example DateTime.local().toLocaleString(DateTime.DATE_FULL); //=> 'April 20, 2017'
+ * @example DateTime.local().toLocaleString(DateTime.TIME_SIMPLE); //=> '11:32 AM'
+ * @example DateTime.local().toLocaleString(DateTime.DATETIME_SHORT); //=> '4/20/2017, 11:32 AM'
+ * @example DateTime.local().toLocaleString({ weekday: 'long', month: 'long', day: '2-digit' }); //=> 'Thursday, April 20'
+ * @example DateTime.local().toLocaleString({ weekday: 'short', month: 'short', day: '2-digit', hour: '2-digit', minute: '2-digit' }); //=> 'Thu, Apr 20, 11:27 AM'
+ * @example DateTime.local().toLocaleString({ hour: '2-digit', minute: '2-digit', hour12: false }); //=> '11:32'
+ * @return {string}
+ */
+ ;
+
+ _proto.toLocaleString = function toLocaleString(opts) {
+ if (opts === void 0) {
+ opts = DATE_SHORT;
+ }
+
+ return this.isValid ? Formatter.create(this.loc.clone(opts), opts).formatDateTime(this) : INVALID$2;
+ }
+ /**
+ * Returns an array of format "parts", meaning individual tokens along with metadata. This is allows callers to post-process individual sections of the formatted output.
+ * Defaults to the system's locale if no locale has been specified
+ * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat/formatToParts
+ * @param opts {Object} - Intl.DateTimeFormat constructor options, same as `toLocaleString`.
+ * @example DateTime.local().toLocaleParts(); //=> [
+ * //=> { type: 'day', value: '25' },
+ * //=> { type: 'literal', value: '/' },
+ * //=> { type: 'month', value: '05' },
+ * //=> { type: 'literal', value: '/' },
+ * //=> { type: 'year', value: '1982' }
+ * //=> ]
+ */
+ ;
+
+ _proto.toLocaleParts = function toLocaleParts(opts) {
+ if (opts === void 0) {
+ opts = {};
+ }
+
+ return this.isValid ? Formatter.create(this.loc.clone(opts), opts).formatDateTimeParts(this) : [];
+ }
+ /**
+ * Returns an ISO 8601-compliant string representation of this DateTime
+ * @param {Object} opts - options
+ * @param {boolean} [opts.suppressMilliseconds=false] - exclude milliseconds from the format if they're 0
+ * @param {boolean} [opts.suppressSeconds=false] - exclude seconds from the format if they're 0
+ * @param {boolean} [opts.includeOffset=true] - include the offset, such as 'Z' or '-04:00'
+ * @param {string} [opts.format='extended'] - choose between the basic and extended format
+ * @example DateTime.utc(1982, 5, 25).toISO() //=> '1982-05-25T00:00:00.000Z'
+ * @example DateTime.local().toISO() //=> '2017-04-22T20:47:05.335-04:00'
+ * @example DateTime.local().toISO({ includeOffset: false }) //=> '2017-04-22T20:47:05.335'
+ * @example DateTime.local().toISO({ format: 'basic' }) //=> '20170422T204705.335-0400'
+ * @return {string}
+ */
+ ;
+
+ _proto.toISO = function toISO(opts) {
+ if (opts === void 0) {
+ opts = {};
+ }
+
+ if (!this.isValid) {
+ return null;
+ }
+
+ return this.toISODate(opts) + "T" + this.toISOTime(opts);
+ }
+ /**
+ * Returns an ISO 8601-compliant string representation of this DateTime's date component
+ * @param {Object} opts - options
+ * @param {string} [opts.format='extended'] - choose between the basic and extended format
+ * @example DateTime.utc(1982, 5, 25).toISODate() //=> '1982-05-25'
+ * @example DateTime.utc(1982, 5, 25).toISODate({ format: 'basic' }) //=> '19820525'
+ * @return {string}
+ */
+ ;
+
+ _proto.toISODate = function toISODate(_temp3) {
+ var _ref5 = _temp3 === void 0 ? {} : _temp3,
+ _ref5$format = _ref5.format,
+ format = _ref5$format === void 0 ? "extended" : _ref5$format;
+
+ var fmt = format === "basic" ? "yyyyMMdd" : "yyyy-MM-dd";
+
+ if (this.year > 9999) {
+ fmt = "+" + fmt;
+ }
+
+ return toTechFormat(this, fmt);
+ }
+ /**
+ * Returns an ISO 8601-compliant string representation of this DateTime's week date
+ * @example DateTime.utc(1982, 5, 25).toISOWeekDate() //=> '1982-W21-2'
+ * @return {string}
+ */
+ ;
+
+ _proto.toISOWeekDate = function toISOWeekDate() {
+ return toTechFormat(this, "kkkk-'W'WW-c");
+ }
+ /**
+ * Returns an ISO 8601-compliant string representation of this DateTime's time component
+ * @param {Object} opts - options
+ * @param {boolean} [opts.suppressMilliseconds=false] - exclude milliseconds from the format if they're 0
+ * @param {boolean} [opts.suppressSeconds=false] - exclude seconds from the format if they're 0
+ * @param {boolean} [opts.includeOffset=true] - include the offset, such as 'Z' or '-04:00'
+ * @param {string} [opts.format='extended'] - choose between the basic and extended format
+ * @example DateTime.utc().set({ hour: 7, minute: 34 }).toISOTime() //=> '07:34:19.361Z'
+ * @example DateTime.utc().set({ hour: 7, minute: 34, seconds: 0, milliseconds: 0 }).toISOTime({ suppressSeconds: true }) //=> '07:34Z'
+ * @example DateTime.utc().set({ hour: 7, minute: 34 }).toISOTime({ format: 'basic' }) //=> '073419.361Z'
+ * @return {string}
+ */
+ ;
+
+ _proto.toISOTime = function toISOTime(_temp4) {
+ var _ref6 = _temp4 === void 0 ? {} : _temp4,
+ _ref6$suppressMillise = _ref6.suppressMilliseconds,
+ suppressMilliseconds = _ref6$suppressMillise === void 0 ? false : _ref6$suppressMillise,
+ _ref6$suppressSeconds = _ref6.suppressSeconds,
+ suppressSeconds = _ref6$suppressSeconds === void 0 ? false : _ref6$suppressSeconds,
+ _ref6$includeOffset = _ref6.includeOffset,
+ includeOffset = _ref6$includeOffset === void 0 ? true : _ref6$includeOffset,
+ _ref6$format = _ref6.format,
+ format = _ref6$format === void 0 ? "extended" : _ref6$format;
+
+ return toTechTimeFormat(this, {
+ suppressSeconds: suppressSeconds,
+ suppressMilliseconds: suppressMilliseconds,
+ includeOffset: includeOffset,
+ format: format
+ });
+ }
+ /**
+ * Returns an RFC 2822-compatible string representation of this DateTime, always in UTC
+ * @example DateTime.utc(2014, 7, 13).toRFC2822() //=> 'Sun, 13 Jul 2014 00:00:00 +0000'
+ * @example DateTime.local(2014, 7, 13).toRFC2822() //=> 'Sun, 13 Jul 2014 00:00:00 -0400'
+ * @return {string}
+ */
+ ;
+
+ _proto.toRFC2822 = function toRFC2822() {
+ return toTechFormat(this, "EEE, dd LLL yyyy HH:mm:ss ZZZ", false);
+ }
+ /**
+ * Returns a string representation of this DateTime appropriate for use in HTTP headers.
+ * Specifically, the string conforms to RFC 1123.
+ * @see https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3.1
+ * @example DateTime.utc(2014, 7, 13).toHTTP() //=> 'Sun, 13 Jul 2014 00:00:00 GMT'
+ * @example DateTime.utc(2014, 7, 13, 19).toHTTP() //=> 'Sun, 13 Jul 2014 19:00:00 GMT'
+ * @return {string}
+ */
+ ;
+
+ _proto.toHTTP = function toHTTP() {
+ return toTechFormat(this.toUTC(), "EEE, dd LLL yyyy HH:mm:ss 'GMT'");
+ }
+ /**
+ * Returns a string representation of this DateTime appropriate for use in SQL Date
+ * @example DateTime.utc(2014, 7, 13).toSQLDate() //=> '2014-07-13'
+ * @return {string}
+ */
+ ;
+
+ _proto.toSQLDate = function toSQLDate() {
+ return toTechFormat(this, "yyyy-MM-dd");
+ }
+ /**
+ * Returns a string representation of this DateTime appropriate for use in SQL Time
+ * @param {Object} opts - options
+ * @param {boolean} [opts.includeZone=false] - include the zone, such as 'America/New_York'. Overrides includeOffset.
+ * @param {boolean} [opts.includeOffset=true] - include the offset, such as 'Z' or '-04:00'
+ * @example DateTime.utc().toSQL() //=> '05:15:16.345'
+ * @example DateTime.local().toSQL() //=> '05:15:16.345 -04:00'
+ * @example DateTime.local().toSQL({ includeOffset: false }) //=> '05:15:16.345'
+ * @example DateTime.local().toSQL({ includeZone: false }) //=> '05:15:16.345 America/New_York'
+ * @return {string}
+ */
+ ;
+
+ _proto.toSQLTime = function toSQLTime(_temp5) {
+ var _ref7 = _temp5 === void 0 ? {} : _temp5,
+ _ref7$includeOffset = _ref7.includeOffset,
+ includeOffset = _ref7$includeOffset === void 0 ? true : _ref7$includeOffset,
+ _ref7$includeZone = _ref7.includeZone,
+ includeZone = _ref7$includeZone === void 0 ? false : _ref7$includeZone;
+
+ return toTechTimeFormat(this, {
+ includeOffset: includeOffset,
+ includeZone: includeZone,
+ spaceZone: true
+ });
+ }
+ /**
+ * Returns a string representation of this DateTime appropriate for use in SQL DateTime
+ * @param {Object} opts - options
+ * @param {boolean} [opts.includeZone=false] - include the zone, such as 'America/New_York'. Overrides includeOffset.
+ * @param {boolean} [opts.includeOffset=true] - include the offset, such as 'Z' or '-04:00'
+ * @example DateTime.utc(2014, 7, 13).toSQL() //=> '2014-07-13 00:00:00.000 Z'
+ * @example DateTime.local(2014, 7, 13).toSQL() //=> '2014-07-13 00:00:00.000 -04:00'
+ * @example DateTime.local(2014, 7, 13).toSQL({ includeOffset: false }) //=> '2014-07-13 00:00:00.000'
+ * @example DateTime.local(2014, 7, 13).toSQL({ includeZone: true }) //=> '2014-07-13 00:00:00.000 America/New_York'
+ * @return {string}
+ */
+ ;
+
+ _proto.toSQL = function toSQL(opts) {
+ if (opts === void 0) {
+ opts = {};
+ }
+
+ if (!this.isValid) {
+ return null;
+ }
+
+ return this.toSQLDate() + " " + this.toSQLTime(opts);
+ }
+ /**
+ * Returns a string representation of this DateTime appropriate for debugging
+ * @return {string}
+ */
+ ;
+
+ _proto.toString = function toString() {
+ return this.isValid ? this.toISO() : INVALID$2;
+ }
+ /**
+ * Returns the epoch milliseconds of this DateTime. Alias of {@link toMillis}
+ * @return {number}
+ */
+ ;
+
+ _proto.valueOf = function valueOf() {
+ return this.toMillis();
+ }
+ /**
+ * Returns the epoch milliseconds of this DateTime.
+ * @return {number}
+ */
+ ;
+
+ _proto.toMillis = function toMillis() {
+ return this.isValid ? this.ts : NaN;
+ }
+ /**
+ * Returns the epoch seconds of this DateTime.
+ * @return {number}
+ */
+ ;
+
+ _proto.toSeconds = function toSeconds() {
+ return this.isValid ? this.ts / 1000 : NaN;
+ }
+ /**
+ * Returns an ISO 8601 representation of this DateTime appropriate for use in JSON.
+ * @return {string}
+ */
+ ;
+
+ _proto.toJSON = function toJSON() {
+ return this.toISO();
+ }
+ /**
+ * Returns a BSON serializable equivalent to this DateTime.
+ * @return {Date}
+ */
+ ;
+
+ _proto.toBSON = function toBSON() {
+ return this.toJSDate();
+ }
+ /**
+ * Returns a Javascript object with this DateTime's year, month, day, and so on.
+ * @param opts - options for generating the object
+ * @param {boolean} [opts.includeConfig=false] - include configuration attributes in the output
+ * @example DateTime.local().toObject() //=> { year: 2017, month: 4, day: 22, hour: 20, minute: 49, second: 42, millisecond: 268 }
+ * @return {Object}
+ */
+ ;
+
+ _proto.toObject = function toObject(opts) {
+ if (opts === void 0) {
+ opts = {};
+ }
+
+ if (!this.isValid) return {};
+ var base = Object.assign({}, this.c);
+
+ if (opts.includeConfig) {
+ base.outputCalendar = this.outputCalendar;
+ base.numberingSystem = this.loc.numberingSystem;
+ base.locale = this.loc.locale;
+ }
+
+ return base;
+ }
+ /**
+ * Returns a Javascript Date equivalent to this DateTime.
+ * @return {Date}
+ */
+ ;
+
+ _proto.toJSDate = function toJSDate() {
+ return new Date(this.isValid ? this.ts : NaN);
+ } // COMPARE
+
+ /**
+ * Return the difference between two DateTimes as a Duration.
+ * @param {DateTime} otherDateTime - the DateTime to compare this one to
+ * @param {string|string[]} [unit=['milliseconds']] - the unit or array of units (such as 'hours' or 'days') to include in the duration.
+ * @param {Object} opts - options that affect the creation of the Duration
+ * @param {string} [opts.conversionAccuracy='casual'] - the conversion system to use
+ * @example
+ * var i1 = DateTime.fromISO('1982-05-25T09:45'),
+ * i2 = DateTime.fromISO('1983-10-14T10:30');
+ * i2.diff(i1).toObject() //=> { milliseconds: 43807500000 }
+ * i2.diff(i1, 'hours').toObject() //=> { hours: 12168.75 }
+ * i2.diff(i1, ['months', 'days']).toObject() //=> { months: 16, days: 19.03125 }
+ * i2.diff(i1, ['months', 'days', 'hours']).toObject() //=> { months: 16, days: 19, hours: 0.75 }
+ * @return {Duration}
+ */
+ ;
+
+ _proto.diff = function diff(otherDateTime, unit, opts) {
+ if (unit === void 0) {
+ unit = "milliseconds";
+ }
+
+ if (opts === void 0) {
+ opts = {};
+ }
+
+ if (!this.isValid || !otherDateTime.isValid) {
+ return Duration.invalid(this.invalid || otherDateTime.invalid, "created by diffing an invalid DateTime");
+ }
+
+ var durOpts = Object.assign({
+ locale: this.locale,
+ numberingSystem: this.numberingSystem
+ }, opts);
+
+ var units = maybeArray(unit).map(Duration.normalizeUnit),
+ otherIsLater = otherDateTime.valueOf() > this.valueOf(),
+ earlier = otherIsLater ? this : otherDateTime,
+ later = otherIsLater ? otherDateTime : this,
+ diffed = _diff(earlier, later, units, durOpts);
+
+ return otherIsLater ? diffed.negate() : diffed;
+ }
+ /**
+ * Return the difference between this DateTime and right now.
+ * See {@link diff}
+ * @param {string|string[]} [unit=['milliseconds']] - the unit or units units (such as 'hours' or 'days') to include in the duration
+ * @param {Object} opts - options that affect the creation of the Duration
+ * @param {string} [opts.conversionAccuracy='casual'] - the conversion system to use
+ * @return {Duration}
+ */
+ ;
+
+ _proto.diffNow = function diffNow(unit, opts) {
+ if (unit === void 0) {
+ unit = "milliseconds";
+ }
+
+ if (opts === void 0) {
+ opts = {};
+ }
+
+ return this.diff(DateTime.local(), unit, opts);
+ }
+ /**
+ * Return an Interval spanning between this DateTime and another DateTime
+ * @param {DateTime} otherDateTime - the other end point of the Interval
+ * @return {Interval}
+ */
+ ;
+
+ _proto.until = function until(otherDateTime) {
+ return this.isValid ? Interval.fromDateTimes(this, otherDateTime) : this;
+ }
+ /**
+ * Return whether this DateTime is in the same unit of time as another DateTime
+ * @param {DateTime} otherDateTime - the other DateTime
+ * @param {string} unit - the unit of time to check sameness on
+ * @example DateTime.local().hasSame(otherDT, 'day'); //~> true if both the same calendar day
+ * @return {boolean}
+ */
+ ;
+
+ _proto.hasSame = function hasSame(otherDateTime, unit) {
+ if (!this.isValid) return false;
+
+ if (unit === "millisecond") {
+ return this.valueOf() === otherDateTime.valueOf();
+ } else {
+ var inputMs = otherDateTime.valueOf();
+ return this.startOf(unit) <= inputMs && inputMs <= this.endOf(unit);
+ }
+ }
+ /**
+ * Equality check
+ * Two DateTimes are equal iff they represent the same millisecond, have the same zone and location, and are both valid.
+ * To compare just the millisecond values, use `+dt1 === +dt2`.
+ * @param {DateTime} other - the other DateTime
+ * @return {boolean}
+ */
+ ;
+
+ _proto.equals = function equals(other) {
+ return this.isValid && other.isValid && this.valueOf() === other.valueOf() && this.zone.equals(other.zone) && this.loc.equals(other.loc);
+ }
+ /**
+ * Returns a string representation of a this time relative to now, such as "in two days". Can only internationalize if your
+ * platform supports Intl.RelativeTimeFormat. Rounds down by default.
+ * @param {Object} options - options that affect the output
+ * @param {DateTime} [options.base=DateTime.local()] - the DateTime to use as the basis to which this time is compared. Defaults to now.
+ * @param {string} [options.style="long"] - the style of units, must be "long", "short", or "narrow"
+ * @param {string} options.unit - use a specific unit; if omitted, the method will pick the unit. Use one of "years", "quarters", "months", "weeks", "days", "hours", "minutes", or "seconds"
+ * @param {boolean} [options.round=true] - whether to round the numbers in the output.
+ * @param {boolean} [options.padding=0] - padding in milliseconds. This allows you to round up the result if it fits inside the threshold. Don't use in combination with {round: false} because the decimal output will include the padding.
+ * @param {string} options.locale - override the locale of this DateTime
+ * @param {string} options.numberingSystem - override the numberingSystem of this DateTime. The Intl system may choose not to honor this
+ * @example DateTime.local().plus({ days: 1 }).toRelative() //=> "in 1 day"
+ * @example DateTime.local().setLocale("es").toRelative({ days: 1 }) //=> "dentro de 1 día"
+ * @example DateTime.local().plus({ days: 1 }).toRelative({ locale: "fr" }) //=> "dans 23 heures"
+ * @example DateTime.local().minus({ days: 2 }).toRelative() //=> "2 days ago"
+ * @example DateTime.local().minus({ days: 2 }).toRelative({ unit: "hours" }) //=> "48 hours ago"
+ * @example DateTime.local().minus({ hours: 36 }).toRelative({ round: false }) //=> "1.5 days ago"
+ */
+ ;
+
+ _proto.toRelative = function toRelative(options) {
+ if (options === void 0) {
+ options = {};
+ }
+
+ if (!this.isValid) return null;
+ var base = options.base || DateTime.fromObject({
+ zone: this.zone
+ }),
+ padding = options.padding ? this < base ? -options.padding : options.padding : 0;
+ return diffRelative(base, this.plus(padding), Object.assign(options, {
+ numeric: "always",
+ units: ["years", "months", "days", "hours", "minutes", "seconds"]
+ }));
+ }
+ /**
+ * Returns a string representation of this date relative to today, such as "yesterday" or "next month".
+ * Only internationalizes on platforms that supports Intl.RelativeTimeFormat.
+ * @param {Object} options - options that affect the output
+ * @param {DateTime} [options.base=DateTime.local()] - the DateTime to use as the basis to which this time is compared. Defaults to now.
+ * @param {string} options.locale - override the locale of this DateTime
+ * @param {string} options.unit - use a specific unit; if omitted, the method will pick the unit. Use one of "years", "quarters", "months", "weeks", or "days"
+ * @param {string} options.numberingSystem - override the numberingSystem of this DateTime. The Intl system may choose not to honor this
+ * @example DateTime.local().plus({ days: 1 }).toRelativeCalendar() //=> "tomorrow"
+ * @example DateTime.local().setLocale("es").plus({ days: 1 }).toRelative() //=> ""mañana"
+ * @example DateTime.local().plus({ days: 1 }).toRelativeCalendar({ locale: "fr" }) //=> "demain"
+ * @example DateTime.local().minus({ days: 2 }).toRelativeCalendar() //=> "2 days ago"
+ */
+ ;
+
+ _proto.toRelativeCalendar = function toRelativeCalendar(options) {
+ if (options === void 0) {
+ options = {};
+ }
+
+ if (!this.isValid) return null;
+ return diffRelative(options.base || DateTime.fromObject({
+ zone: this.zone
+ }), this, Object.assign(options, {
+ numeric: "auto",
+ units: ["years", "months", "days"],
+ calendary: true
+ }));
+ }
+ /**
+ * Return the min of several date times
+ * @param {...DateTime} dateTimes - the DateTimes from which to choose the minimum
+ * @return {DateTime} the min DateTime, or undefined if called with no argument
+ */
+ ;
+
+ DateTime.min = function min() {
+ for (var _len = arguments.length, dateTimes = new Array(_len), _key = 0; _key < _len; _key++) {
+ dateTimes[_key] = arguments[_key];
+ }
+
+ if (!dateTimes.every(DateTime.isDateTime)) {
+ throw new InvalidArgumentError("min requires all arguments be DateTimes");
+ }
+
+ return bestBy(dateTimes, function (i) {
+ return i.valueOf();
+ }, Math.min);
+ }
+ /**
+ * Return the max of several date times
+ * @param {...DateTime} dateTimes - the DateTimes from which to choose the maximum
+ * @return {DateTime} the max DateTime, or undefined if called with no argument
+ */
+ ;
+
+ DateTime.max = function max() {
+ for (var _len2 = arguments.length, dateTimes = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
+ dateTimes[_key2] = arguments[_key2];
+ }
+
+ if (!dateTimes.every(DateTime.isDateTime)) {
+ throw new InvalidArgumentError("max requires all arguments be DateTimes");
+ }
+
+ return bestBy(dateTimes, function (i) {
+ return i.valueOf();
+ }, Math.max);
+ } // MISC
+
+ /**
+ * Explain how a string would be parsed by fromFormat()
+ * @param {string} text - the string to parse
+ * @param {string} fmt - the format the string is expected to be in (see description)
+ * @param {Object} options - options taken by fromFormat()
+ * @return {Object}
+ */
+ ;
+
+ DateTime.fromFormatExplain = function fromFormatExplain(text, fmt, options) {
+ if (options === void 0) {
+ options = {};
+ }
+
+ var _options = options,
+ _options$locale = _options.locale,
+ locale = _options$locale === void 0 ? null : _options$locale,
+ _options$numberingSys = _options.numberingSystem,
+ numberingSystem = _options$numberingSys === void 0 ? null : _options$numberingSys,
+ localeToUse = Locale.fromOpts({
+ locale: locale,
+ numberingSystem: numberingSystem,
+ defaultToEN: true
+ });
+ return explainFromTokens(localeToUse, text, fmt);
+ }
+ /**
+ * @deprecated use fromFormatExplain instead
+ */
+ ;
+
+ DateTime.fromStringExplain = function fromStringExplain(text, fmt, options) {
+ if (options === void 0) {
+ options = {};
+ }
+
+ return DateTime.fromFormatExplain(text, fmt, options);
+ } // FORMAT PRESETS
+
+ /**
+ * {@link toLocaleString} format like 10/14/1983
+ * @type {Object}
+ */
+ ;
+
+ _createClass(DateTime, [{
+ key: "isValid",
+ get: function get() {
+ return this.invalid === null;
+ }
+ /**
+ * Returns an error code if this DateTime is invalid, or null if the DateTime is valid
+ * @type {string}
+ */
+
+ }, {
+ key: "invalidReason",
+ get: function get() {
+ return this.invalid ? this.invalid.reason : null;
+ }
+ /**
+ * Returns an explanation of why this DateTime became invalid, or null if the DateTime is valid
+ * @type {string}
+ */
+
+ }, {
+ key: "invalidExplanation",
+ get: function get() {
+ return this.invalid ? this.invalid.explanation : null;
+ }
+ /**
+ * Get the locale of a DateTime, such 'en-GB'. The locale is used when formatting the DateTime
+ *
+ * @type {string}
+ */
+
+ }, {
+ key: "locale",
+ get: function get() {
+ return this.isValid ? this.loc.locale : null;
+ }
+ /**
+ * Get the numbering system of a DateTime, such 'beng'. The numbering system is used when formatting the DateTime
+ *
+ * @type {string}
+ */
+
+ }, {
+ key: "numberingSystem",
+ get: function get() {
+ return this.isValid ? this.loc.numberingSystem : null;
+ }
+ /**
+ * Get the output calendar of a DateTime, such 'islamic'. The output calendar is used when formatting the DateTime
+ *
+ * @type {string}
+ */
+
+ }, {
+ key: "outputCalendar",
+ get: function get() {
+ return this.isValid ? this.loc.outputCalendar : null;
+ }
+ /**
+ * Get the time zone associated with this DateTime.
+ * @type {Zone}
+ */
+
+ }, {
+ key: "zone",
+ get: function get() {
+ return this._zone;
+ }
+ /**
+ * Get the name of the time zone.
+ * @type {string}
+ */
+
+ }, {
+ key: "zoneName",
+ get: function get() {
+ return this.isValid ? this.zone.name : null;
+ }
+ /**
+ * Get the year
+ * @example DateTime.local(2017, 5, 25).year //=> 2017
+ * @type {number}
+ */
+
+ }, {
+ key: "year",
+ get: function get() {
+ return this.isValid ? this.c.year : NaN;
+ }
+ /**
+ * Get the quarter
+ * @example DateTime.local(2017, 5, 25).quarter //=> 2
+ * @type {number}
+ */
+
+ }, {
+ key: "quarter",
+ get: function get() {
+ return this.isValid ? Math.ceil(this.c.month / 3) : NaN;
+ }
+ /**
+ * Get the month (1-12).
+ * @example DateTime.local(2017, 5, 25).month //=> 5
+ * @type {number}
+ */
+
+ }, {
+ key: "month",
+ get: function get() {
+ return this.isValid ? this.c.month : NaN;
+ }
+ /**
+ * Get the day of the month (1-30ish).
+ * @example DateTime.local(2017, 5, 25).day //=> 25
+ * @type {number}
+ */
+
+ }, {
+ key: "day",
+ get: function get() {
+ return this.isValid ? this.c.day : NaN;
+ }
+ /**
+ * Get the hour of the day (0-23).
+ * @example DateTime.local(2017, 5, 25, 9).hour //=> 9
+ * @type {number}
+ */
+
+ }, {
+ key: "hour",
+ get: function get() {
+ return this.isValid ? this.c.hour : NaN;
+ }
+ /**
+ * Get the minute of the hour (0-59).
+ * @example DateTime.local(2017, 5, 25, 9, 30).minute //=> 30
+ * @type {number}
+ */
+
+ }, {
+ key: "minute",
+ get: function get() {
+ return this.isValid ? this.c.minute : NaN;
+ }
+ /**
+ * Get the second of the minute (0-59).
+ * @example DateTime.local(2017, 5, 25, 9, 30, 52).second //=> 52
+ * @type {number}
+ */
+
+ }, {
+ key: "second",
+ get: function get() {
+ return this.isValid ? this.c.second : NaN;
+ }
+ /**
+ * Get the millisecond of the second (0-999).
+ * @example DateTime.local(2017, 5, 25, 9, 30, 52, 654).millisecond //=> 654
+ * @type {number}
+ */
+
+ }, {
+ key: "millisecond",
+ get: function get() {
+ return this.isValid ? this.c.millisecond : NaN;
+ }
+ /**
+ * Get the week year
+ * @see https://en.wikipedia.org/wiki/ISO_week_date
+ * @example DateTime.local(2014, 11, 31).weekYear //=> 2015
+ * @type {number}
+ */
+
+ }, {
+ key: "weekYear",
+ get: function get() {
+ return this.isValid ? possiblyCachedWeekData(this).weekYear : NaN;
+ }
+ /**
+ * Get the week number of the week year (1-52ish).
+ * @see https://en.wikipedia.org/wiki/ISO_week_date
+ * @example DateTime.local(2017, 5, 25).weekNumber //=> 21
+ * @type {number}
+ */
+
+ }, {
+ key: "weekNumber",
+ get: function get() {
+ return this.isValid ? possiblyCachedWeekData(this).weekNumber : NaN;
+ }
+ /**
+ * Get the day of the week.
+ * 1 is Monday and 7 is Sunday
+ * @see https://en.wikipedia.org/wiki/ISO_week_date
+ * @example DateTime.local(2014, 11, 31).weekday //=> 4
+ * @type {number}
+ */
+
+ }, {
+ key: "weekday",
+ get: function get() {
+ return this.isValid ? possiblyCachedWeekData(this).weekday : NaN;
+ }
+ /**
+ * Get the ordinal (meaning the day of the year)
+ * @example DateTime.local(2017, 5, 25).ordinal //=> 145
+ * @type {number|DateTime}
+ */
+
+ }, {
+ key: "ordinal",
+ get: function get() {
+ return this.isValid ? gregorianToOrdinal(this.c).ordinal : NaN;
+ }
+ /**
+ * Get the human readable short month name, such as 'Oct'.
+ * Defaults to the system's locale if no locale has been specified
+ * @example DateTime.local(2017, 10, 30).monthShort //=> Oct
+ * @type {string}
+ */
+
+ }, {
+ key: "monthShort",
+ get: function get() {
+ return this.isValid ? Info.months("short", {
+ locale: this.locale
+ })[this.month - 1] : null;
+ }
+ /**
+ * Get the human readable long month name, such as 'October'.
+ * Defaults to the system's locale if no locale has been specified
+ * @example DateTime.local(2017, 10, 30).monthLong //=> October
+ * @type {string}
+ */
+
+ }, {
+ key: "monthLong",
+ get: function get() {
+ return this.isValid ? Info.months("long", {
+ locale: this.locale
+ })[this.month - 1] : null;
+ }
+ /**
+ * Get the human readable short weekday, such as 'Mon'.
+ * Defaults to the system's locale if no locale has been specified
+ * @example DateTime.local(2017, 10, 30).weekdayShort //=> Mon
+ * @type {string}
+ */
+
+ }, {
+ key: "weekdayShort",
+ get: function get() {
+ return this.isValid ? Info.weekdays("short", {
+ locale: this.locale
+ })[this.weekday - 1] : null;
+ }
+ /**
+ * Get the human readable long weekday, such as 'Monday'.
+ * Defaults to the system's locale if no locale has been specified
+ * @example DateTime.local(2017, 10, 30).weekdayLong //=> Monday
+ * @type {string}
+ */
+
+ }, {
+ key: "weekdayLong",
+ get: function get() {
+ return this.isValid ? Info.weekdays("long", {
+ locale: this.locale
+ })[this.weekday - 1] : null;
+ }
+ /**
+ * Get the UTC offset of this DateTime in minutes
+ * @example DateTime.local().offset //=> -240
+ * @example DateTime.utc().offset //=> 0
+ * @type {number}
+ */
+
+ }, {
+ key: "offset",
+ get: function get() {
+ return this.isValid ? +this.o : NaN;
+ }
+ /**
+ * Get the short human name for the zone's current offset, for example "EST" or "EDT".
+ * Defaults to the system's locale if no locale has been specified
+ * @type {string}
+ */
+
+ }, {
+ key: "offsetNameShort",
+ get: function get() {
+ if (this.isValid) {
+ return this.zone.offsetName(this.ts, {
+ format: "short",
+ locale: this.locale
+ });
+ } else {
+ return null;
+ }
+ }
+ /**
+ * Get the long human name for the zone's current offset, for example "Eastern Standard Time" or "Eastern Daylight Time".
+ * Defaults to the system's locale if no locale has been specified
+ * @type {string}
+ */
+
+ }, {
+ key: "offsetNameLong",
+ get: function get() {
+ if (this.isValid) {
+ return this.zone.offsetName(this.ts, {
+ format: "long",
+ locale: this.locale
+ });
+ } else {
+ return null;
+ }
+ }
+ /**
+ * Get whether this zone's offset ever changes, as in a DST.
+ * @type {boolean}
+ */
+
+ }, {
+ key: "isOffsetFixed",
+ get: function get() {
+ return this.isValid ? this.zone.universal : null;
+ }
+ /**
+ * Get whether the DateTime is in a DST.
+ * @type {boolean}
+ */
+
+ }, {
+ key: "isInDST",
+ get: function get() {
+ if (this.isOffsetFixed) {
+ return false;
+ } else {
+ return this.offset > this.set({
+ month: 1
+ }).offset || this.offset > this.set({
+ month: 5
+ }).offset;
+ }
+ }
+ /**
+ * Returns true if this DateTime is in a leap year, false otherwise
+ * @example DateTime.local(2016).isInLeapYear //=> true
+ * @example DateTime.local(2013).isInLeapYear //=> false
+ * @type {boolean}
+ */
+
+ }, {
+ key: "isInLeapYear",
+ get: function get() {
+ return isLeapYear(this.year);
+ }
+ /**
+ * Returns the number of days in this DateTime's month
+ * @example DateTime.local(2016, 2).daysInMonth //=> 29
+ * @example DateTime.local(2016, 3).daysInMonth //=> 31
+ * @type {number}
+ */
+
+ }, {
+ key: "daysInMonth",
+ get: function get() {
+ return daysInMonth(this.year, this.month);
+ }
+ /**
+ * Returns the number of days in this DateTime's year
+ * @example DateTime.local(2016).daysInYear //=> 366
+ * @example DateTime.local(2013).daysInYear //=> 365
+ * @type {number}
+ */
+
+ }, {
+ key: "daysInYear",
+ get: function get() {
+ return this.isValid ? daysInYear(this.year) : NaN;
+ }
+ /**
+ * Returns the number of weeks in this DateTime's year
+ * @see https://en.wikipedia.org/wiki/ISO_week_date
+ * @example DateTime.local(2004).weeksInWeekYear //=> 53
+ * @example DateTime.local(2013).weeksInWeekYear //=> 52
+ * @type {number}
+ */
+
+ }, {
+ key: "weeksInWeekYear",
+ get: function get() {
+ return this.isValid ? weeksInWeekYear(this.weekYear) : NaN;
+ }
+ }], [{
+ key: "DATE_SHORT",
+ get: function get() {
+ return DATE_SHORT;
+ }
+ /**
+ * {@link toLocaleString} format like 'Oct 14, 1983'
+ * @type {Object}
+ */
+
+ }, {
+ key: "DATE_MED",
+ get: function get() {
+ return DATE_MED;
+ }
+ /**
+ * {@link toLocaleString} format like 'Fri, Oct 14, 1983'
+ * @type {Object}
+ */
+
+ }, {
+ key: "DATE_MED_WITH_WEEKDAY",
+ get: function get() {
+ return DATE_MED_WITH_WEEKDAY;
+ }
+ /**
+ * {@link toLocaleString} format like 'October 14, 1983'
+ * @type {Object}
+ */
+
+ }, {
+ key: "DATE_FULL",
+ get: function get() {
+ return DATE_FULL;
+ }
+ /**
+ * {@link toLocaleString} format like 'Tuesday, October 14, 1983'
+ * @type {Object}
+ */
+
+ }, {
+ key: "DATE_HUGE",
+ get: function get() {
+ return DATE_HUGE;
+ }
+ /**
+ * {@link toLocaleString} format like '09:30 AM'. Only 12-hour if the locale is.
+ * @type {Object}
+ */
+
+ }, {
+ key: "TIME_SIMPLE",
+ get: function get() {
+ return TIME_SIMPLE;
+ }
+ /**
+ * {@link toLocaleString} format like '09:30:23 AM'. Only 12-hour if the locale is.
+ * @type {Object}
+ */
+
+ }, {
+ key: "TIME_WITH_SECONDS",
+ get: function get() {
+ return TIME_WITH_SECONDS;
+ }
+ /**
+ * {@link toLocaleString} format like '09:30:23 AM EDT'. Only 12-hour if the locale is.
+ * @type {Object}
+ */
+
+ }, {
+ key: "TIME_WITH_SHORT_OFFSET",
+ get: function get() {
+ return TIME_WITH_SHORT_OFFSET;
+ }
+ /**
+ * {@link toLocaleString} format like '09:30:23 AM Eastern Daylight Time'. Only 12-hour if the locale is.
+ * @type {Object}
+ */
+
+ }, {
+ key: "TIME_WITH_LONG_OFFSET",
+ get: function get() {
+ return TIME_WITH_LONG_OFFSET;
+ }
+ /**
+ * {@link toLocaleString} format like '09:30', always 24-hour.
+ * @type {Object}
+ */
+
+ }, {
+ key: "TIME_24_SIMPLE",
+ get: function get() {
+ return TIME_24_SIMPLE;
+ }
+ /**
+ * {@link toLocaleString} format like '09:30:23', always 24-hour.
+ * @type {Object}
+ */
+
+ }, {
+ key: "TIME_24_WITH_SECONDS",
+ get: function get() {
+ return TIME_24_WITH_SECONDS;
+ }
+ /**
+ * {@link toLocaleString} format like '09:30:23 EDT', always 24-hour.
+ * @type {Object}
+ */
+
+ }, {
+ key: "TIME_24_WITH_SHORT_OFFSET",
+ get: function get() {
+ return TIME_24_WITH_SHORT_OFFSET;
+ }
+ /**
+ * {@link toLocaleString} format like '09:30:23 Eastern Daylight Time', always 24-hour.
+ * @type {Object}
+ */
+
+ }, {
+ key: "TIME_24_WITH_LONG_OFFSET",
+ get: function get() {
+ return TIME_24_WITH_LONG_OFFSET;
+ }
+ /**
+ * {@link toLocaleString} format like '10/14/1983, 9:30 AM'. Only 12-hour if the locale is.
+ * @type {Object}
+ */
+
+ }, {
+ key: "DATETIME_SHORT",
+ get: function get() {
+ return DATETIME_SHORT;
+ }
+ /**
+ * {@link toLocaleString} format like '10/14/1983, 9:30:33 AM'. Only 12-hour if the locale is.
+ * @type {Object}
+ */
+
+ }, {
+ key: "DATETIME_SHORT_WITH_SECONDS",
+ get: function get() {
+ return DATETIME_SHORT_WITH_SECONDS;
+ }
+ /**
+ * {@link toLocaleString} format like 'Oct 14, 1983, 9:30 AM'. Only 12-hour if the locale is.
+ * @type {Object}
+ */
+
+ }, {
+ key: "DATETIME_MED",
+ get: function get() {
+ return DATETIME_MED;
+ }
+ /**
+ * {@link toLocaleString} format like 'Oct 14, 1983, 9:30:33 AM'. Only 12-hour if the locale is.
+ * @type {Object}
+ */
+
+ }, {
+ key: "DATETIME_MED_WITH_SECONDS",
+ get: function get() {
+ return DATETIME_MED_WITH_SECONDS;
+ }
+ /**
+ * {@link toLocaleString} format like 'Fri, 14 Oct 1983, 9:30 AM'. Only 12-hour if the locale is.
+ * @type {Object}
+ */
+
+ }, {
+ key: "DATETIME_MED_WITH_WEEKDAY",
+ get: function get() {
+ return DATETIME_MED_WITH_WEEKDAY;
+ }
+ /**
+ * {@link toLocaleString} format like 'October 14, 1983, 9:30 AM EDT'. Only 12-hour if the locale is.
+ * @type {Object}
+ */
+
+ }, {
+ key: "DATETIME_FULL",
+ get: function get() {
+ return DATETIME_FULL;
+ }
+ /**
+ * {@link toLocaleString} format like 'October 14, 1983, 9:30:33 AM EDT'. Only 12-hour if the locale is.
+ * @type {Object}
+ */
+
+ }, {
+ key: "DATETIME_FULL_WITH_SECONDS",
+ get: function get() {
+ return DATETIME_FULL_WITH_SECONDS;
+ }
+ /**
+ * {@link toLocaleString} format like 'Friday, October 14, 1983, 9:30 AM Eastern Daylight Time'. Only 12-hour if the locale is.
+ * @type {Object}
+ */
+
+ }, {
+ key: "DATETIME_HUGE",
+ get: function get() {
+ return DATETIME_HUGE;
+ }
+ /**
+ * {@link toLocaleString} format like 'Friday, October 14, 1983, 9:30:33 AM Eastern Daylight Time'. Only 12-hour if the locale is.
+ * @type {Object}
+ */
+
+ }, {
+ key: "DATETIME_HUGE_WITH_SECONDS",
+ get: function get() {
+ return DATETIME_HUGE_WITH_SECONDS;
+ }
+ }]);
+
+ return DateTime;
+ }();
+ function friendlyDateTime(dateTimeish) {
+ if (DateTime.isDateTime(dateTimeish)) {
+ return dateTimeish;
+ } else if (dateTimeish && dateTimeish.valueOf && isNumber(dateTimeish.valueOf())) {
+ return DateTime.fromJSDate(dateTimeish);
+ } else if (dateTimeish && typeof dateTimeish === "object") {
+ return DateTime.fromObject(dateTimeish);
+ } else {
+ throw new InvalidArgumentError("Unknown datetime argument: " + dateTimeish + ", of type " + typeof dateTimeish);
+ }
+ }
+
+ exports.DateTime = DateTime;
+ exports.Duration = Duration;
+ exports.FixedOffsetZone = FixedOffsetZone;
+ exports.IANAZone = IANAZone;
+ exports.Info = Info;
+ exports.Interval = Interval;
+ exports.InvalidZone = InvalidZone;
+ exports.LocalZone = LocalZone;
+ exports.Settings = Settings;
+ exports.Zone = Zone;
+
+ return exports;
+
+}({}));
+//# sourceMappingURL=luxon.js.map
\ No newline at end of file
diff --git a/addons/web/static/lib/qunit/qunit-2.9.1.js b/addons/web/static/lib/qunit/qunit-2.9.1.js
index ddbdcee3e75..7efc1f1f759 100644
--- a/addons/web/static/lib/qunit/qunit-2.9.1.js
+++ b/addons/web/static/lib/qunit/qunit-2.9.1.js
@@ -14,6 +14,8 @@
global$1 = global$1 && global$1.hasOwnProperty('default') ? global$1['default'] : global$1;
+ const debug = odoo.debug;
+
var window$1 = global$1.window;
var self$1 = global$1.self;
var console = global$1.console;
@@ -5338,7 +5340,7 @@
// Odoo Customisation!!!
// Crappy hack to display traceback with sourcemaps if debug=assets
- if (lastError && QUnit.annotateTraceback && odoo && odoo.debug && odoo.debug.includes("assets")) {
+ if (lastError && QUnit.annotateTraceback && debug && debug.includes("assets")) {
const pre = assertLi.querySelector("pre");
QUnit.annotateTraceback(lastError).then(traceback => {
diff --git a/addons/web/static/src/js/boot.js b/addons/web/static/src/boot.js
similarity index 62%
rename from addons/web/static/src/js/boot.js
rename to addons/web/static/src/boot.js
index 468eb33fbab..d1165935c74 100644
--- a/addons/web/static/src/js/boot.js
+++ b/addons/web/static/src/boot.js
@@ -35,20 +35,21 @@
var services = Object.create({});
- var commentRegExp = /(\/\*([\s\S]*?)\*\/|([^:]|^)\/\/(.*)$)/mg;
+ var commentRegExp = /(\/\*([\s\S]*?)\*\/|([^:]|^)\/\/(.*)$)/gm;
var cjsRequireRegExp = /[^.]\s*require\s*\(\s*["']([^'"\s]+)["']\s*\)/g;
if (!window.odoo) {
window.odoo = {};
}
var odoo = window.odoo;
+ var debug = odoo.debug;
var didLogInfoResolve;
var didLogInfoPromise = new Promise(function (resolve) {
didLogInfoResolve = resolve;
});
- odoo.testing = typeof QUnit === 'object';
+ odoo.testing = typeof QUnit === "object";
odoo.remainingJobs = jobs;
odoo.__DEBUG__ = {
didLogInfo: didLogInfoPromise,
@@ -67,18 +68,23 @@
return deps;
},
getDependents: function (name) {
- return jobDeps.filter(function (dep) {
- return dep.from === name;
- }).map(function (dep) {
- return dep.to;
- });
+ return jobDeps
+ .filter(function (dep) {
+ return dep.from === name;
+ })
+ .map(function (dep) {
+ return dep.to;
+ });
},
getWaitedJobs: function () {
- return jobs.map(function (job) {
- return job.name;
- }).filter(function (item, index, self) { // uniq
- return self.indexOf(item) === index;
- });
+ return jobs
+ .map(function (job) {
+ return job.name;
+ })
+ .filter(function (item, index, self) {
+ // uniq
+ return self.indexOf(item) === index;
+ });
},
getMissingJobs: function () {
var self = this;
@@ -91,13 +97,16 @@
}
});
});
- return missing.filter(function (item, index, self) {
- return self.indexOf(item) === index;
- }).filter(function (item) {
- return waited.indexOf(item) < 0;
- }).filter(function (job) {
- return !job.error;
- });
+ return missing
+ .filter(function (item, index, self) {
+ return self.indexOf(item) === index;
+ })
+ .filter(function (item) {
+ return waited.indexOf(item) < 0;
+ })
+ .filter(function (job) {
+ return !job.error;
+ });
},
getFailedJobs: function () {
return jobs.filter(function (job) {
@@ -109,27 +118,28 @@
};
odoo.define = function () {
var args = Array.prototype.slice.call(arguments);
- var name = typeof args[0] === 'string' ? args.shift() : ('__odoo_job' + (jobUID++));
+ var name = typeof args[0] === "string" ? args.shift() : "__odoo_job" + jobUID++;
var factory = args[args.length - 1];
var deps;
if (args[0] instanceof Array) {
deps = args[0];
} else {
deps = [];
- factory.toString()
- .replace(commentRegExp, '')
+ factory
+ .toString()
+ .replace(commentRegExp, "")
.replace(cjsRequireRegExp, function (match, dep) {
deps.push(dep);
});
}
if (!(deps instanceof Array)) {
- throw new Error('Dependencies should be defined by an array', deps);
+ throw new Error("Dependencies should be defined by an array", deps);
}
- if (typeof factory !== 'function') {
- throw new Error('Factory should be defined by a function', factory);
+ if (typeof factory !== "function") {
+ throw new Error("Factory should be defined by a function", factory);
}
- if (typeof name !== 'string') {
+ if (typeof name !== "string") {
throw new Error("Invalid name definition (should be a string", name);
}
if (name in factories) {
@@ -146,7 +156,7 @@
});
deps.forEach(function (dep) {
- jobDeps.push({from: dep, to: name});
+ jobDeps.push({ from: dep, to: name });
});
this.processJobs(jobs, services);
@@ -154,6 +164,7 @@
odoo.log = function () {
var missing = [];
var failed = [];
+ var cycle = null;
if (jobs.length) {
var debugJobs = {};
@@ -166,7 +177,7 @@
debugJobs[jobs[k].name] = job = {
dependencies: jobs[k].deps,
dependents: odoo.__DEBUG__.getDependents(jobs[k].name),
- name: jobs[k].name
+ name: jobs[k].name,
};
if (jobs[k].error) {
job.error = jobs[k].error;
@@ -207,42 +218,58 @@
var unloaded = Object.keys(debugJobs) // Object.values is not supported
.map(function (key) {
return debugJobs[key];
- }).filter(function (job) {
+ })
+ .filter(function (job) {
return job.missing;
});
- if (odoo.debug || failed.length || unloaded.length) {
- var log = window.console[!failed.length || !unloaded.length ? 'info' : 'error'].bind(window.console);
- log((failed.length ? 'error' : (unloaded.length ? 'warning' : 'info')) + ': Some modules could not be started');
+ if (debug || failed.length || unloaded.length) {
+ var log = window.console[
+ !failed.length || !unloaded.length ? "info" : "error"
+ ].bind(window.console);
+ log(
+ (failed.length ? "error" : unloaded.length ? "warning" : "info") +
+ ": Some modules could not be started"
+ );
if (missing.length) {
- log('Missing dependencies: ', missing);
+ log("Missing dependencies: ", missing);
}
if (failed.length) {
- log('Failed modules: ', failed.map(function (fail) {
- return fail.name;
- }));
+ log(
+ "Failed modules: ",
+ failed.map(function (fail) {
+ return fail.name;
+ })
+ );
}
if (rejected.length) {
- log('Rejected modules: ', rejected);
+ log("Rejected modules: ", rejected);
}
if (rejectedLinked.length) {
- log('Rejected linked modules: ', rejectedLinked);
+ log("Rejected linked modules: ", rejectedLinked);
}
if (unloaded.length) {
- log('Non loaded modules: ', unloaded.map(function (unload) {
- return unload.name;
- }));
+ cycle = findCycle(unloaded);
+ if (cycle) {
+ console.error("Cyclic dependencies: " + cycle);
+ }
+ log(
+ "Non loaded modules: ",
+ unloaded.map(function (unload) {
+ return unload.name;
+ })
+ );
}
- if (odoo.debug && Object.keys(debugJobs).length) {
- log('Debug: ', debugJobs);
+ if (debug && Object.keys(debugJobs).length) {
+ log("Debug: ", debugJobs);
}
}
}
odoo.__DEBUG__.jsModules = {
missing: missing,
- failed: failed.map(function (fail) {
- return fail.name;
- }),
+ failed: failed.map((mod) => mod.name),
+ unloaded: unloaded ? unloaded.map((mod) => mod.name) : [],
+ cycle,
};
didLogInfoResolve();
};
@@ -263,39 +290,47 @@
console.error(`Error while loading ${job.name}: ${e.message}`);
}
if (!job.error) {
- Promise.resolve(jobExec).then(
- function (data) {
+ Promise.resolve(jobExec)
+ .then(function (data) {
services[job.name] = data;
resolve();
odoo.processJobs(jobs, services);
- }).guardedCatch(function (e) {
+ })
+ .guardedCatch(function (e) {
job.rejected = e || true;
jobs.push(job);
resolve();
- }
- );
+ });
+ } else {
+ resolve();
}
});
jobPromises.push(def);
}
function isReady(job) {
- return !job.error && !job.rejected && job.factory.deps.every(function (name) {
- return name in services;
- });
+ return (
+ !job.error &&
+ !job.rejected &&
+ job.factory.deps.every(function (name) {
+ return name in services;
+ })
+ );
}
function makeRequire(job) {
var deps = {};
- Object.keys(services).filter(function (item) {
- return job.deps.indexOf(item) >= 0;
- }).forEach(function (key) {
- deps[key] = services[key];
- });
+ Object.keys(services)
+ .filter(function (item) {
+ return job.deps.indexOf(item) >= 0;
+ })
+ .forEach(function (key) {
+ deps[key] = services[key];
+ });
return function require(name) {
if (!(name in deps)) {
- console.error('Undefined dependency: ', name);
+ console.error("Undefined dependency: ", name);
}
return deps[name];
};
@@ -319,7 +354,7 @@
};
// Automatically log errors detected when loading modules
- window.addEventListener('load', function logWhenLoaded() {
+ window.addEventListener("load", function logWhenLoaded() {
setTimeout(function () {
var len = jobPromises.length;
Promise.all(jobPromises).then(function () {
@@ -329,6 +364,47 @@
logWhenLoaded();
}
});
- }, 9999);
+ }, 5000);
});
+
+ /**
+ * Visit the list of jobs, and return the first found cycle, if any
+ *
+ * @param {any[]} jobs
+ * @returns {null | string} either a string describing a cycle, or null
+ */
+ function findCycle(jobs) {
+ // build dependency graph
+ const dependencyGraph = new Map();
+ for (let job of jobs) {
+ dependencyGraph.set(job.name, job.dependencies);
+ }
+
+ // helpers
+ function visitJobs(jobs, visited = new Set()) {
+ for (let job of jobs) {
+ const result = visitJob(job, visited);
+ if (result) {
+ return result;
+ }
+ }
+ return null;
+ }
+
+ function visitJob(job, visited) {
+ if (visited.has(job)) {
+ const jobs = Array.from(visited).concat([job]);
+ const index = jobs.indexOf(job);
+ return jobs
+ .slice(index)
+ .map((j) => `"${j}"`)
+ .join(" => ");
+ }
+ const deps = dependencyGraph.get(job);
+ return deps ? visitJobs(deps, new Set(visited).add(job)) : null;
+ }
+
+ // visit each root to find cycles
+ return visitJobs(jobs.map((j) => j.name));
+ }
})();
diff --git a/addons/web/static/src/core/assets.js b/addons/web/static/src/core/assets.js
new file mode 100644
index 00000000000..9d3196b9e4c
--- /dev/null
+++ b/addons/web/static/src/core/assets.js
@@ -0,0 +1,252 @@
+/** @odoo-module **/
+
+const { useEnv, onWillStart } = owl.hooks;
+import { memoize } from "./utils/functions";
+import { browser } from "./browser/browser";
+
+class AssetsLoadingError extends Error {}
+
+//------------------------------------------------------------------------------
+// Types
+//------------------------------------------------------------------------------
+
+/**
+ * An object describing a bundle to load
+ * @typedef {Object} Bundle
+ * @property {boolean} [templates] whether to load the qweb templates
+ * @property {boolean} [js] whether to load the js from the bundle. Currently
+ * not implemented.
+ * @property {boolean} [css] whether to load the css from the bundle. Currently
+ * not implemented.
+ */
+
+/**
+ * An object describing a bundle to load. The keys are bundle names.
+ * @typedef {Object} Bundles
+ */
+
+/**
+ * An object describing a loaded bundle
+ * @typedef {Object} LoadedBundle
+ * @property {XMLDocument} templates an XML document containing the owl
+ * templates defined in that bundle
+ */
+
+/**
+ * An object describing a loaded bundle. The keys are bundle names.
+ * @typedef {Object} LoadedBundles
+ */
+
+//------------------------------------------------------------------------------
+// Helpers
+//------------------------------------------------------------------------------
+
+/**
+ * Loads the given url inside a script tag.
+ *
+ * @param {string} url the url of the script
+ * @returns {Promise} resolved when the script has been loaded
+ */
+const loadJS = memoize(function loadJS(url) {
+ if (document.querySelector(`script[src="${url}"]`)) {
+ // Already in the DOM and wasn't loaded through this function
+ // Unfortunately there is no way to check whether a script has loaded
+ // or not (which may not be the case for async/defer scripts)
+ // so we assume it is.
+ return Promise.resolve();
+ }
+ const scriptEl = document.createElement("script");
+ scriptEl.type = "text/javascript";
+ scriptEl.src = url;
+ document.head.appendChild(scriptEl);
+ return new Promise((resolve, reject) => {
+ scriptEl.addEventListener("load", resolve);
+ scriptEl.addEventListener("error", () => {
+ reject(new AssetsLoadingError(`The loading of ${url} failed`));
+ });
+ });
+});
+/**
+ * Loads the given url as a stylesheet.
+ *
+ * @param {string} url the url of the stylesheet
+ * @returns {Promise} resolved when the stylesheet has been loaded
+ */
+const loadCSS = memoize(function loadCSS(url) {
+ if (document.querySelector(`link[href="${url}"]`)) {
+ // Already in the DOM and wasn't loaded through this function
+ // Unfortunately there is no way to check whether a link has loaded
+ // or not (which may not be the case for async/defer stylesheets)
+ // so we assume it is.
+ return Promise.resolve();
+ }
+ const linkEl = document.createElement("link");
+ linkEl.type = "text/css";
+ linkEl.rel = "stylesheet";
+ linkEl.href = url;
+ document.head.appendChild(linkEl);
+ return new Promise(function (resolve, reject) {
+ linkEl.addEventListener("load", resolve);
+ linkEl.addEventListener("error", () => {
+ reject(new AssetsLoadingError(`The loading of ${url} failed`));
+ });
+ });
+});
+/**
+ * Loads the qweb templates from a given bundle name.
+ *
+ * @param {string} name the name of the bundle as declared in the manifest.
+ * @returns {Promise} A Promise of an XML document containing the
+ * owl templates.
+ */
+const loadBundleTemplates = memoize(async function loadBundleTemplates(name) {
+ // TODO: quid of the "unique" in the URL? We can"t have one cache_hash
+ // for each and every bundle I"m guessing.
+ const bundleURL = new URL(`/web/webclient/qweb/${Date.now()}`, window.location.origin);
+ bundleURL.searchParams.set("bundle", name);
+ const templates = await (await browser.fetch(bundleURL.href)).text();
+ return processTemplates(templates);
+});
+
+const bundlesCache = {};
+/**
+ * Loads a bundle.
+ *
+ * @param {string} name the name of the bundle to load
+ * @param {Bundle} options parts of the bundle to load (see Bundle typedef)
+ * @returns {Promise}
+ */
+async function loadBundle(name, options) {
+ const { templates } = options;
+ if (!bundlesCache[name]) {
+ bundlesCache[name] = { name };
+ }
+ if (templates && !bundlesCache[name].templates) {
+ bundlesCache[name].templates = loadBundleTemplates(name);
+ }
+ // TODO: if ("js/css") {...} to support lazy loading js/css from bundles
+
+ // Wait only for the requested keys
+ const entries = await Promise.all(
+ Object.keys(options).map(async (key) => [key, await bundlesCache[name][key]])
+ );
+ return Object.fromEntries(entries);
+}
+
+//------------------------------------------------------------------------------
+// Exports
+//------------------------------------------------------------------------------
+
+/**
+ * Process the qweb templates to obtain only the owl templates. This function
+ * does NOT register the templates into Owl.
+ *
+ * @param {string} templates An xml string describing templates
+ * @returns {XMLDocument} An xml document containing only the owl templates
+ */
+export function processTemplates(templates) {
+ const doc = new DOMParser().parseFromString(templates, "text/xml");
+ // as we currently have two qweb engines (owl and legacy), owl templates are
+ // flagged with attribute `owl="1"`. The following lines removes the "owl"
+ // attribute from the templates, so that it doesn't appear in the DOM. We
+ // also remove the non-owl templates, as those shouldn't be loaded in the
+ // owl environment's QWeb, and will be loaded separately.
+ for (const template of [...doc.querySelector("templates").children]) {
+ if (template.hasAttribute("owl")) {
+ template.removeAttribute("owl");
+ } else {
+ template.remove();
+ }
+ }
+ return doc;
+}
+/**
+ * Renders a public asset template and loads the libraries defined inside of it.
+ * Only loads js and css, template declarations will be ignored. Only loads
+ * scripts and styles that are defined in script src and link href, ignores
+ * inline scripts and styles.
+ *
+ * @deprecated
+ * @param {string} xmlid The xmlid of the template that defines the public asset
+ * @param {ORM} orm An ORM object capable of calling methods on models
+ * @returns {Promise} Resolved when the contents of the asset is loaded
+ */
+export const loadPublicAsset = memoize(async function loadPublicAsset(xmlid, orm) {
+ const xml = await orm.call("ir.ui.view", "render_public_asset", [xmlid]);
+ const doc = new DOMParser().parseFromString(`${xml} `, "text/xml");
+ return loadAssets({
+ cssLibs: [...doc.querySelectorAll("link[href]")].map((node) => node.getAttribute("href")),
+ jsLibs: [...doc.querySelectorAll("script[src]")].map((node) => node.getAttribute("src")),
+ });
+});
+/**
+ * Loads the given assets. Currently, when passing bundles, only the templates
+ * key is supported, as loading a bundle's JS/CSS asynchronously requires some
+ * groundwork.
+ *
+ * @param {Object} assets
+ * @param {Bundles} [assets.bundles] an object describing the bundles to load.
+ * The keys are bundle names, and the values describe whether to load the
+ * templates, js and/or css from that bundle.
+ * @param {string[]} [assets.jsLibs] urls of the javascript libraries to load
+ * @param {string[]} [assets.cssLibs] urls of the css libraries to load
+ * @returns {Promise<{[bundles: LoadedBundle[]]}>} An object describing the loaded
+ * assets. The js and css libs are loaded globally and will be loaded when
+ * this promise is resolved, the owl xml templates will be loaded in the
+ * `templates` key of each LoadedBundle object.
+ */
+export async function loadAssets(assets) {
+ const proms = [];
+ const loadedAssets = {};
+ if ("bundles" in assets) {
+ const bundles = Object.entries(assets.bundles);
+ const bundlesProm = Promise.all(
+ bundles.map(async ([name, options]) => [name, await loadBundle(name, options)])
+ ).then((loadedBundles) => {
+ loadedAssets.bundles = Object.fromEntries(loadedBundles);
+ });
+ proms.push(bundlesProm);
+ }
+ if ("jsLibs" in assets) {
+ proms.push(Promise.all(assets.jsLibs.map(loadJS)));
+ }
+ if ("cssLibs" in assets) {
+ proms.push(Promise.all(assets.cssLibs.map(loadCSS)));
+ }
+ await Promise.all(proms);
+ return loadedAssets;
+}
+/**
+ * Loads the given assets, and adds the loaded owl templates into the current
+ * environment's qweb instance.
+ *
+ * @param {Object} assets
+ * @param {Bundles} [assets.bundles] the bundles to load. See above typedef for
+ * details.
+ * @param {string[]} [assets.jsLibs] urls of the javascript libraries to load
+ * @param {string[]} [assets.cssLibs] urls of the css libraries to load
+ */
+export function useAssets(assets) {
+ const env = useEnv();
+ onWillStart(async () => {
+ const loadedAssets = await loadAssets(assets);
+ // TODO: { js, css } = loadedAssets when we support lazy loading js/css from bundles
+ const { bundles } = loadedAssets;
+ if (bundles) {
+ const templateDocs = Object.values(bundles).map(({ templates }) => templates);
+ // Some templates might already be defined by another bundle, but need
+ // to be included in the current bundle for primary inherits to work.
+ // We don't want to add those again. We also have to add them to qweb
+ // one bundle at a time in case multiple bundles were specified that
+ // include the same template (e.g. for inheritance)
+ for (const xmlDoc of templateDocs) {
+ for (const template of [...xmlDoc.querySelector("templates").children]) {
+ if (template.getAttribute("t-name") in env.qweb.templates) {
+ template.remove();
+ }
+ }
+ env.qweb.addTemplates(xmlDoc);
+ }
+ }
+ });
+}
diff --git a/addons/web/static/src/core/autofocus_hook.js b/addons/web/static/src/core/autofocus_hook.js
new file mode 100644
index 00000000000..c061a1074a7
--- /dev/null
+++ b/addons/web/static/src/core/autofocus_hook.js
@@ -0,0 +1,45 @@
+/** @odoo-module **/
+
+import { useEffect } from "./effect_hook";
+
+const { useComponent } = owl.hooks;
+
+// -----------------------------------------------------------------------------
+// Hook functions
+// -----------------------------------------------------------------------------
+
+/**
+ * Focus a given selector as soon as it appears in the DOM and if it was not
+ * displayed before. If the selected target is an input|textarea, set the selection
+ * at the end.
+ *
+ * @param {Object} [params]
+ * @param {string} [params.selector='autofocus'] default: select the first element
+ * with an `autofocus` attribute.
+ * @returns {Function} function that forces the focus on the next update if visible.
+ */
+export function useAutofocus(params = {}) {
+ const comp = useComponent();
+ // Prevent autofocus in mobile
+ if (comp.env.isSmall) {
+ return () => {};
+ }
+ const selector = params.selector || "[autofocus]";
+ let forceFocusCount = 0;
+ useEffect(
+ function autofocus(target) {
+ if (target) {
+ target.focus();
+ if (["INPUT", "TEXTAREA"].includes(target.tagName)) {
+ const inputEl = target;
+ inputEl.selectionStart = inputEl.selectionEnd = inputEl.value.length;
+ }
+ }
+ },
+ () => [comp.el.querySelector(selector), forceFocusCount]
+ );
+
+ return function focusOnUpdate() {
+ forceFocusCount++; // force the effect to rerun on next patch
+ };
+}
diff --git a/addons/web/static/src/core/browser/browser.js b/addons/web/static/src/core/browser/browser.js
new file mode 100644
index 00000000000..a3aac8df47f
--- /dev/null
+++ b/addons/web/static/src/core/browser/browser.js
@@ -0,0 +1,65 @@
+/** @odoo-module **/
+
+/**
+ * Browser
+ *
+ * This file exports an object containing common browser API. It may not look
+ * incredibly useful, but it is very convenient when one needs to test code using
+ * these methods. With this indirection, it is possible to patch the browser
+ * object for a test.
+ */
+
+let sessionStorage = window.sessionStorage;
+let localStorage = owl.browser.localStorage;
+try {
+ // Safari crashes in Private Browsing
+ localStorage.setItem("__localStorage__", "true");
+ localStorage.removeItem("__localStorage__");
+} catch (e) {
+ localStorage = makeRAMLocalStorage();
+ sessionStorage = makeRAMLocalStorage();
+}
+
+export const browser = Object.assign({}, owl.browser, {
+ addEventListener: window.addEventListener.bind(window),
+ removeEventListener: window.removeEventListener.bind(window),
+ console: window.console,
+ location: window.location,
+ history: window.history,
+ navigator: navigator,
+ open: window.open.bind(window),
+ XMLHttpRequest: window.XMLHttpRequest,
+ localStorage,
+ sessionStorage,
+});
+
+// -----------------------------------------------------------------------------
+// memory localStorage
+// -----------------------------------------------------------------------------
+
+/**
+ * @returns {typeof window["localStorage"]}
+ */
+export function makeRAMLocalStorage() {
+ let store = {};
+ return {
+ setItem(key, value) {
+ store[key] = value;
+ },
+ getItem(key) {
+ return store[key];
+ },
+ clear() {
+ store = {};
+ },
+ removeItem(key) {
+ delete store[key];
+ },
+ get length() {
+ return Object.keys(store).length;
+ },
+ key() {
+ return "";
+ },
+ };
+}
diff --git a/addons/web/static/src/core/browser/cookie_service.js b/addons/web/static/src/core/browser/cookie_service.js
new file mode 100644
index 00000000000..845808e35c4
--- /dev/null
+++ b/addons/web/static/src/core/browser/cookie_service.js
@@ -0,0 +1,59 @@
+/** @odoo-module **/
+
+import { registry } from "../registry";
+
+/**
+ * Service to make use of document.cookie
+ * https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies
+ * As recommended, storage should not be done by the cookie
+ * but with localStorage/sessionStorage
+ */
+
+const COOKIE_TTL = 24 * 60 * 60 * 365;
+
+function parseCookieString(str) {
+ const cookie = {};
+ const parts = str.split("; ");
+ for (let part of parts) {
+ const [key, value] = part.split("=");
+ cookie[key] = value || "";
+ }
+ return cookie;
+}
+
+function cookieToString(key, value, ttl = COOKIE_TTL) {
+ let fullCookie = [];
+ if (value !== undefined) {
+ fullCookie.push(`${key}=${value}`);
+ }
+ fullCookie = fullCookie.concat(["path=/", `max-age=${ttl}`]);
+ return fullCookie.join(";");
+}
+
+function makeCookieService() {
+ function getCurrent() {
+ return parseCookieString(document.cookie);
+ }
+ let cookie = getCurrent();
+ function setCookie(key, value, ttl) {
+ document.cookie = cookieToString(key, value, ttl);
+ cookie = getCurrent();
+ }
+ return {
+ get current() {
+ return cookie;
+ },
+ setCookie,
+ deleteCookie(key) {
+ setCookie(key, "kill", 0);
+ },
+ };
+}
+
+export const cookieService = {
+ start() {
+ return makeCookieService();
+ },
+};
+
+registry.category("services").add("cookie", cookieService);
diff --git a/addons/web/static/src/core/browser/feature_detection.js b/addons/web/static/src/core/browser/feature_detection.js
new file mode 100644
index 00000000000..58dd52b0451
--- /dev/null
+++ b/addons/web/static/src/core/browser/feature_detection.js
@@ -0,0 +1,40 @@
+/** @odoo-module **/
+
+import { browser } from "./browser";
+
+// -----------------------------------------------------------------------------
+// Feature detection
+// -----------------------------------------------------------------------------
+
+/**
+ * true if the browser is based on Chromium (Google Chrome, Opera, Edge)
+ *
+ * @returns {boolean}
+ */
+export function isBrowserChrome() {
+ return browser.navigator.userAgent.includes("Chrome");
+}
+
+export function isMacOS() {
+ return Boolean(browser.navigator.platform.match(/Mac/i));
+}
+
+export function isMobileOS() {
+ return Boolean(
+ browser.navigator.userAgent.match(/Android/i) ||
+ browser.navigator.userAgent.match(/webOS/i) ||
+ browser.navigator.userAgent.match(/iPhone/i) ||
+ browser.navigator.userAgent.match(/iPad/i) ||
+ browser.navigator.userAgent.match(/iPod/i) ||
+ browser.navigator.userAgent.match(/BlackBerry/i) ||
+ browser.navigator.userAgent.match(/Windows Phone/i)
+ );
+}
+
+export function isIosApp() {
+ return navigator.userAgent.match(/OdooMobile \(iOS\)/i);
+}
+
+export function hasTouch() {
+ return "ontouchstart" in window || "onmsgesturechange" in window;
+}
diff --git a/addons/web/static/src/core/browser/router_service.js b/addons/web/static/src/core/browser/router_service.js
new file mode 100644
index 00000000000..9b722e9d839
--- /dev/null
+++ b/addons/web/static/src/core/browser/router_service.js
@@ -0,0 +1,196 @@
+/** @odoo-module **/
+
+import { registry } from "../registry";
+import { shallowEqual } from "../utils/objects";
+import { objectToUrlEncodedString } from "../utils/urls";
+import { browser } from "./browser";
+
+/**
+ * @typedef {{ [key: string]: string }} Query
+ * @typedef {{ [key: string]: any }} Route
+ */
+
+function parseString(str) {
+ const parts = str.split("&");
+ const result = {};
+ for (let part of parts) {
+ const [key, value] = part.split("=");
+ const decoded = decodeURIComponent(value || "");
+ result[key] = !decoded || isNaN(decoded) ? decoded : Number(decoded);
+ }
+ return result;
+}
+
+/**
+ * For each push request (replaceState or pushState), filterout keys that have been locked before
+ * overrides locked keys that are explicitly re-locked or unlocked
+ * registers keys in "hash" in "lockedKeys" according to the "lock" Boolean
+ *
+ * @param {Set} lockedKeys A set containing all keys that were locked
+ * @param {Query} hash An Object representing the pushed url hash
+ * @param {Query} currentHash The current hash compare against
+ * @param {Object} [options={}] Whether to lock all hash keys in "hash" to prevent them from being changed afterwards
+ * @param {Boolean} [options.lock] Whether to lock all hash keys in "hash" to prevent them from being changed afterwards
+ * @return {Query} The resulting "hash" where previous locking has been applied
+ */
+function applyLocking(lockedKeys, hash, currentHash, options = {}) {
+ const newHash = {};
+ for (const key in hash) {
+ if ("lock" in options) {
+ options.lock ? lockedKeys.add(key) : lockedKeys.delete(key);
+ } else if (lockedKeys.has(key)) {
+ // forbid implicit override of key
+ continue;
+ }
+ newHash[key] = hash[key];
+ }
+ for (const key in currentHash) {
+ if (lockedKeys.has(key) && !(key in newHash)) {
+ newHash[key] = currentHash[key];
+ }
+ }
+ return newHash;
+}
+
+function computeNewRoute(hash, replace, currentRoute) {
+ if (!replace) {
+ hash = Object.assign({}, currentRoute.hash, hash);
+ }
+ hash = sanitizeHash(hash);
+ if (!shallowEqual(currentRoute.hash, hash)) {
+ return Object.assign({}, currentRoute, { hash });
+ }
+ return false;
+}
+
+function sanitizeHash(hash) {
+ return Object.fromEntries(Object.entries(hash).filter(([, v]) => v !== undefined));
+}
+
+/**
+ * @param {string} hash
+ * @returns {any}
+ */
+export function parseHash(hash) {
+ return hash && hash !== "#" ? parseString(hash.slice(1)) : {};
+}
+
+/**
+ * @param {string} search
+ * @returns {any}
+ */
+export function parseSearchQuery(search) {
+ return search ? parseString(search.slice(1)) : {};
+}
+
+/**
+ * @param {{ [key: string]: any }} route
+ * @returns
+ */
+export function routeToUrl(route) {
+ const search = objectToUrlEncodedString(route.search);
+ const hash = objectToUrlEncodedString(route.hash);
+ return route.pathname + (search ? "?" + search : "") + (hash ? "#" + hash : "");
+}
+
+async function redirect(env, url, wait = false) {
+ if (wait) {
+ await new Promise((resolve) => {
+ const waitForServer = (delay) => {
+ browser.setTimeout(async () => {
+ env.services
+ .rpc("/web/webclient/version_info", {})
+ .then(resolve)
+ .catch(() => waitForServer(250));
+ }, delay);
+ };
+ waitForServer(1000);
+ });
+ }
+ browser.location.assign(url);
+}
+
+function getRoute() {
+ const { pathname, search, hash } = browser.location;
+ const searchQuery = parseSearchQuery(search);
+ const hashQuery = parseHash(hash);
+ return { pathname, search: searchQuery, hash: hashQuery };
+}
+
+function makeRouter(env) {
+ const bus = env.bus;
+ const lockedKeys = new Set();
+ let current = getRoute();
+ let pushTimeout;
+ browser.addEventListener("hashchange", () => {
+ current = getRoute();
+ bus.trigger("ROUTE_CHANGE");
+ });
+
+ /**
+ * @param {string} mode
+ * @returns {(hash: string, options: any) => any}
+ */
+ function makeDebouncedPush(mode) {
+ let allPushArgs = [];
+ function doPush() {
+ // Aggregates push/replace state arguments
+ const replace = allPushArgs.some(([, options]) => options && options.replace);
+ const newHash = allPushArgs.reduce((finalHash, [hash, options]) => {
+ hash = applyLocking(lockedKeys, hash, current.hash, options);
+ if (finalHash) {
+ hash = applyLocking(lockedKeys, hash, finalHash, options);
+ }
+ return Object.assign(finalHash || {}, hash);
+ }, null);
+ // Calculates new route based on aggregated hash and options
+ const newRoute = computeNewRoute(newHash, replace, current);
+ if (!newRoute) {
+ return;
+ }
+ // If the route changed: pushes or replaces browser state
+ const url = browser.location.origin + routeToUrl(newRoute);
+ if (mode === "push") {
+ browser.history.pushState({}, "", url);
+ } else {
+ browser.history.replaceState({}, "", url);
+ }
+ current = getRoute();
+ }
+ return function pushOrReplaceState(hash, options) {
+ allPushArgs.push([hash, options]);
+ browser.clearTimeout(pushTimeout);
+ pushTimeout = browser.setTimeout(() => {
+ doPush();
+ pushTimeout = null;
+ allPushArgs = [];
+ });
+ };
+ }
+
+ return {
+ get current() {
+ return current;
+ },
+ pushState: makeDebouncedPush("push"),
+ replaceState: makeDebouncedPush("replace"),
+ redirect: (url, wait) => redirect(env, url, wait),
+ cancelPushes: () => browser.clearTimeout(pushTimeout),
+ };
+}
+
+export const routerService = {
+ start(env) {
+ return makeRouter(env);
+ },
+};
+
+export function objectToQuery(obj) {
+ const query = {};
+ Object.entries(obj).forEach(([k, v]) => {
+ query[k] = v ? String(v) : v;
+ });
+ return query;
+}
+
+registry.category("services").add("router", routerService);
diff --git a/addons/web/static/src/core/browser/title_service.js b/addons/web/static/src/core/browser/title_service.js
new file mode 100644
index 00000000000..a3e1201c5aa
--- /dev/null
+++ b/addons/web/static/src/core/browser/title_service.js
@@ -0,0 +1,38 @@
+/** @odoo-module **/
+
+import { registry } from "../registry";
+
+export const titleService = {
+ start() {
+ const titleParts = {};
+
+ function getParts() {
+ return Object.assign({}, titleParts);
+ }
+
+ function setParts(parts) {
+ for (const key in parts) {
+ const val = parts[key];
+ if (!val) {
+ delete titleParts[key];
+ } else {
+ titleParts[key] = val;
+ }
+ }
+ document.title = Object.values(titleParts).join(" - ");
+ }
+
+ return {
+ /**
+ * @returns {string}
+ */
+ get current() {
+ return document.title;
+ },
+ getParts,
+ setParts,
+ };
+ },
+};
+
+registry.category("services").add("title", titleService);
diff --git a/addons/web/static/src/core/bus_hook.js b/addons/web/static/src/core/bus_hook.js
new file mode 100644
index 00000000000..c3f28169a57
--- /dev/null
+++ b/addons/web/static/src/core/bus_hook.js
@@ -0,0 +1,40 @@
+/** @odoo-module **/
+import { useEffect } from "./effect_hook";
+const { useComponent } = owl.hooks;
+
+/**
+ * This file contains various custom hooks.
+ * Their inner working is rather simple:
+ * Each custom hook simply hook itself to any number of owl lifecycle hooks.
+ * You can then use them just like an owl hook in any Component
+ * e.g.:
+ * import { useBus } from "@web/core/bus_hook";
+ * ...
+ * setup() {
+ * ...
+ * useBus(someBus, someEvent, callback)
+ * ...
+ * }
+ */
+
+// -----------------------------------------------------------------------------
+// Hook functions
+// -----------------------------------------------------------------------------
+
+/**
+ * Ensures a bus event listener is attached and cleared the proper way.
+ *
+ * @param {EventBus} bus
+ * @param {string} eventName
+ * @param {Callback} callback
+ */
+export function useBus(bus, eventName, callback) {
+ const component = useComponent();
+ useEffect(
+ () => {
+ bus.on(eventName, component, callback);
+ return () => bus.off(eventName, component);
+ },
+ () => []
+ );
+}
diff --git a/addons/web/static/src/core/checkbox/checkbox.js b/addons/web/static/src/core/checkbox/checkbox.js
new file mode 100644
index 00000000000..87e4a082ca7
--- /dev/null
+++ b/addons/web/static/src/core/checkbox/checkbox.js
@@ -0,0 +1,28 @@
+/** @odoo-module **/
+
+const { Component, QWeb } = owl;
+
+/**
+ * Custom checkbox
+ *
+ *
+ * Change the label text
+ *
+ *
+ * @extends Component
+ */
+
+export class CheckBox extends Component {
+ setup() {
+ this.id = `checkbox-comp-${CheckBox.nextId++}`;
+ }
+}
+
+CheckBox.template = "web.CheckBox";
+CheckBox.nextId = 1;
+
+QWeb.registerComponent("CheckBox", CheckBox);
diff --git a/addons/web/static/src/core/checkbox/checkbox.scss b/addons/web/static/src/core/checkbox/checkbox.scss
new file mode 100644
index 00000000000..49e574a57b8
--- /dev/null
+++ b/addons/web/static/src/core/checkbox/checkbox.scss
@@ -0,0 +1,29 @@
+// = Checkbox
+// ============================================================================
+
+.custom-control.custom-checkbox .custom-control-input {
+ // Force default bts default border color
+ &:not(:checked):not(:indeterminate):not(:disabled) ~ .custom-control-label:before {
+ border-color: $custom-control-indicator-border-color;
+ }
+
+ &:disabled {
+ ~ .custom-control-label {
+ cursor: not-allowed;
+
+ &:before {
+ border-color: $custom-control-indicator-checked-disabled-bg;
+ }
+ }
+
+ &:checked ~ .custom-control-label:after {
+ // Use odoo custom muted icon
+ background-image: $o-custom-checkbox-indicator-icon-checked-disabled;
+ }
+ }
+
+ @media print {
+ -webkit-print-color-adjust: exact !important;
+ color-adjust: exact !important;
+ }
+}
diff --git a/addons/web/static/src/core/checkbox/checkbox.xml b/addons/web/static/src/core/checkbox/checkbox.xml
new file mode 100644
index 00000000000..ba826343c57
--- /dev/null
+++ b/addons/web/static/src/core/checkbox/checkbox.xml
@@ -0,0 +1,19 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/addons/web/static/src/core/confirmation_dialog/confirmation_dialog.js b/addons/web/static/src/core/confirmation_dialog/confirmation_dialog.js
new file mode 100644
index 00000000000..8c61ffe6af7
--- /dev/null
+++ b/addons/web/static/src/core/confirmation_dialog/confirmation_dialog.js
@@ -0,0 +1,57 @@
+/** @odoo-module */
+
+import { Dialog } from "../dialog/dialog";
+import { _lt } from "../l10n/translation";
+
+export class ConfirmationDialog extends Dialog {
+ setup() {
+ super.setup();
+ this.title = this.props.title;
+ }
+ _cancel() {
+ if (this.props.cancel) {
+ this.props.cancel();
+ }
+ this.close();
+ }
+
+ _confirm() {
+ if (this.props.confirm) {
+ this.props.confirm();
+ }
+ this.close();
+ }
+}
+ConfirmationDialog.props = {
+ title: {
+ validate: (m) => {
+ return (
+ typeof m === "string" || (typeof m === "object" && typeof m.toString === "function")
+ );
+ },
+ },
+ body: String,
+ confirm: { type: Function, optional: true },
+ cancel: { type: Function, optional: true },
+ close: Function,
+};
+
+ConfirmationDialog.bodyTemplate = "web.ConfirmationDialogBody";
+ConfirmationDialog.footerTemplate = "web.ConfirmationDialogFooter";
+
+export class AlertDialog extends ConfirmationDialog {
+ setup() {
+ super.setup();
+ if ("contentClass" in this.props) {
+ this.contentClass = this.props.contentClass;
+ }
+ }
+}
+AlertDialog.size = "modal-sm";
+AlertDialog.props = Object.assign(Object.create(ConfirmationDialog.props), {
+ contentClass: { type: String, optional: true },
+});
+
+AlertDialog.defaultProps = {
+ title: _lt("Alert"),
+};
diff --git a/addons/web/static/src/core/confirmation_dialog/confirmation_dialog.xml b/addons/web/static/src/core/confirmation_dialog/confirmation_dialog.xml
new file mode 100644
index 00000000000..45606c1c04a
--- /dev/null
+++ b/addons/web/static/src/core/confirmation_dialog/confirmation_dialog.xml
@@ -0,0 +1,17 @@
+
+
+
+
+
+
+
+
+
+ Ok
+
+
+ Cancel
+
+
+
+
\ No newline at end of file
diff --git a/addons/web/static/src/core/context.js b/addons/web/static/src/core/context.js
new file mode 100644
index 00000000000..79eb31de874
--- /dev/null
+++ b/addons/web/static/src/core/context.js
@@ -0,0 +1,23 @@
+/** @odoo-module **/
+
+import { evaluateExpr } from "./py_js/py";
+
+/**
+ * @typedef {{[key: string]: any}} Context
+ * @typedef {Context | string | undefined} ContextDescription
+ */
+
+/**
+ * Create an evaluated context from an arbitrary list of context representations
+ *
+ * @param {...ContextDescription} contexts
+ * @returns {Context}
+ */
+export function makeContext(...contexts) {
+ let context = {};
+ for (let ctx of contexts) {
+ const subCtx = typeof ctx === "string" ? evaluateExpr(ctx, context) : ctx;
+ Object.assign(context, subCtx);
+ }
+ return context;
+}
diff --git a/addons/web/static/src/core/debug/debug_menu.js b/addons/web/static/src/core/debug/debug_menu.js
new file mode 100644
index 00000000000..e103475e9ed
--- /dev/null
+++ b/addons/web/static/src/core/debug/debug_menu.js
@@ -0,0 +1,92 @@
+/** @odoo-module **/
+
+import { useService } from "../service_hook";
+import { useEffect } from "../effect_hook";
+import { registry } from "../registry";
+
+const debugRegistry = registry.category("debug");
+
+const { Component } = owl;
+let debugElementsId = 1;
+
+export class DebugMenu extends Component {
+ setup() {
+ const globalContext = { env: this.env };
+ this.activeCategories = new Set();
+ this.contexts = new Map([["global", globalContext]]);
+ this.debugService = useService("debug");
+ this.hasAccessRights = false;
+ // Defined as arrow to be passed as prop
+ // @ts-ignore
+ this.beforeOpenDropdown = async () => {
+ if (!this.hasAccessRights) {
+ this.hasAccessRights = true;
+ const accessRights = await this.debugService.getAccessRights();
+ Object.assign(globalContext, { accessRights });
+ }
+ };
+ this.env.bus.on("DEBUG-MANAGER:ADD-CONTEXT", this, (payload) => {
+ const { category, context, inDialog, itemId } = payload;
+ if (this.env.inDialog === inDialog) {
+ this.contexts.set(itemId, context);
+ this.activeCategories.add(category);
+ }
+ });
+ this.env.bus.on("DEBUG-MANAGER:REMOVE-CONTEXT", this, (payload) => {
+ const { category, inDialog, itemId } = payload;
+ if (this.env.inDialog === inDialog) {
+ this.contexts.delete(itemId);
+ this.activeCategories.delete(category);
+ }
+ });
+ }
+
+ getElements() {
+ const factories = [];
+ const context = Object.assign({}, ...this.contexts.values());
+ // If not in dialog => gets root (generic) factories
+ if (!this.env.inDialog) {
+ factories.push(...debugRegistry.getAll());
+ }
+ // Retrieves the active categories factories
+ for (const category of this.activeCategories) {
+ factories.push(...debugRegistry.category(category).getAll());
+ }
+ // Builds, filters and sorts all items
+ return factories
+ .map((factory) => factory(context))
+ .filter(Boolean)
+ .sort((x, y) => {
+ const xSeq = x.sequence ? x.sequence : 1000;
+ const ySeq = y.sequence ? y.sequence : 1000;
+ return xSeq - ySeq;
+ });
+ }
+
+ onDropdownItemSelected(ev) {
+ // items of type "component" don't necessarily have a payload/callback
+ if (ev.detail.payload && ev.detail.payload.callback) {
+ ev.detail.payload.callback();
+ }
+ }
+}
+
+DebugMenu.template = "web.DebugMenu";
+
+export function useDebugMenu(category, context = {}) {
+ const component = Component.current;
+ const env = component.env;
+ const payload = {
+ category,
+ context,
+ inDialog: env.inDialog,
+ itemId: debugElementsId++,
+ };
+ useEffect(
+ () => {
+ env.bus.trigger("DEBUG-MANAGER:ADD-CONTEXT", payload);
+ return () => env.bus.trigger("DEBUG-MANAGER:REMOVE-CONTEXT", payload);
+ },
+ () => []
+ );
+}
diff --git a/addons/web/static/src/core/debug/debug_menu.scss b/addons/web/static/src/core/debug/debug_menu.scss
new file mode 100644
index 00000000000..3eac3a68b7e
--- /dev/null
+++ b/addons/web/static/src/core/debug/debug_menu.scss
@@ -0,0 +1,6 @@
+.o_dialog {
+ .o_debug_manager .o_dropdown_toggler {
+ padding: 0 4px;
+ margin: 2px 10px 2px 0;
+ }
+}
diff --git a/addons/web/static/src/core/debug/debug_menu.xml b/addons/web/static/src/core/debug/debug_menu.xml
new file mode 100644
index 00000000000..3c383283ea3
--- /dev/null
+++ b/addons/web/static/src/core/debug/debug_menu.xml
@@ -0,0 +1,27 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/addons/web/static/src/core/debug/debug_menu_items.js b/addons/web/static/src/core/debug/debug_menu_items.js
new file mode 100644
index 00000000000..b80891ece32
--- /dev/null
+++ b/addons/web/static/src/core/debug/debug_menu_items.js
@@ -0,0 +1,167 @@
+/** @odoo-module **/
+
+import { browser } from "../browser/browser";
+import { routeToUrl } from "../browser/router_service";
+import { registry } from "../registry";
+
+// @legacy
+import dialogs from "web.view_dialogs";
+import { ComponentAdapter } from "web.OwlCompatibility";
+
+// Backend Debug Manager Items
+function runJSTestsItem({ env }) {
+ const runTestsURL = browser.location.origin + "/web/tests?mod=*";
+ return {
+ type: "item",
+ description: env._t("Run JS Tests"),
+ href: runTestsURL,
+ callback: () => {
+ browser.open(runTestsURL);
+ },
+ sequence: 10,
+ };
+}
+
+function runJSTestsMobileItem({ env }) {
+ const runTestsMobileURL = browser.location.origin + "/web/tests/mobile?mod=*";
+ return {
+ type: "item",
+ description: env._t("Run JS Mobile Tests"),
+ href: runTestsMobileURL,
+ callback: () => {
+ browser.open(runTestsMobileURL);
+ },
+ sequence: 20,
+ };
+}
+
+export function openViewItem({ env }) {
+ async function onSelected(records) {
+ const views = await env.services.orm.searchRead(
+ "ir.ui.view",
+ [["id", "=", records[0].id]],
+ ["name", "model", "type"],
+ { limit: 1 }
+ );
+ const view = views[0];
+ view.type = view.type === "tree" ? "list" : view.type; // ignore tree view
+ env.services.action.doAction({
+ type: "ir.actions.act_window",
+ name: view.name,
+ res_model: view.model,
+ views: [[view.id, view.type]],
+ });
+ }
+
+ return {
+ type: "item",
+ description: env._t("Open View"),
+ callback: () => {
+ const adapterParent = new ComponentAdapter(null, { Component: owl.Component });
+ const selectCreateDialog = new dialogs.SelectCreateDialog(adapterParent, {
+ res_model: "ir.ui.view",
+ title: env._t("Select a view"),
+ disable_multiple_selection: true,
+ domain: [
+ ["type", "!=", "qweb"],
+ ["type", "!=", "search"],
+ ],
+ on_selected: onSelected,
+ });
+
+ selectCreateDialog.open();
+ },
+ sequence: 40,
+ };
+}
+
+// Global Debug Manager Items
+function globalSeparator() {
+ return {
+ type: "separator",
+ sequence: 400,
+ };
+}
+
+function activateAssetsDebugging({ env }) {
+ return {
+ type: "item",
+ description: env._t("Activate Assets Debugging"),
+ callback: () => {
+ browser.location.search = "?debug=assets";
+ },
+ sequence: 410,
+ };
+}
+
+function activateTestsAssetsDebugging({ env }) {
+ return {
+ type: "item",
+ description: env._t("Activate Tests Assets Debugging"),
+ callback: () => {
+ browser.location.search = "?debug=assets,tests";
+ },
+ sequence: 420,
+ };
+}
+
+export function regenerateAssets({ env }) {
+ return {
+ type: "item",
+ description: env._t("Regenerate Assets Bundles"),
+ callback: async () => {
+ const domain = [
+ "&",
+ ["res_model", "=", "ir.ui.view"],
+ "|",
+ ["name", "=like", "%.assets_%.css"],
+ ["name", "=like", "%.assets_%.js"],
+ ];
+ const ids = await env.services.orm.search("ir.attachment", domain);
+ await env.services.orm.unlink("ir.attachment", ids);
+ browser.location.reload();
+ },
+ sequence: 430,
+ };
+}
+
+function becomeSuperuser({ env }) {
+ const becomeSuperuserULR = browser.location.origin + "/web/become";
+ return {
+ type: "item",
+ description: env._t("Become Superuser"),
+ hide: !env.services.user.isAdmin,
+ href: becomeSuperuserULR,
+ callback: () => {
+ browser.open(becomeSuperuserULR, "_self");
+ },
+ sequence: 440,
+ };
+}
+
+function leaveDebugMode({ env }) {
+ return {
+ type: "item",
+ description: env._t("Leave the Developer Tools"),
+ callback: () => {
+ const route = env.services.router.current;
+ route.search.debug = "";
+ browser.location.href = browser.location.origin + routeToUrl(route);
+ },
+ sequence: 450,
+ };
+}
+
+registry
+ .category("debug")
+ // Backend
+ .add("runJSTestsItem", runJSTestsItem)
+ .add("runJSTestsMobileItem", runJSTestsMobileItem)
+ .add("openViewItem", openViewItem)
+ // Global
+ .add("globalSeparator", globalSeparator)
+ .add("activateAssetsDebugging", activateAssetsDebugging)
+ .add("regenerateAssets", regenerateAssets)
+ .add("becomeSuperuser", becomeSuperuser)
+ .add("leaveDebugMode", leaveDebugMode)
+ .add("activateTestsAssetsDebugging", activateTestsAssetsDebugging);
diff --git a/addons/web/static/src/core/debug/debug_menu_items.xml b/addons/web/static/src/core/debug/debug_menu_items.xml
new file mode 100644
index 00000000000..058135e2483
--- /dev/null
+++ b/addons/web/static/src/core/debug/debug_menu_items.xml
@@ -0,0 +1,102 @@
+
+
+
+
+ Close
+ Save default
+
+
+
+
+
+
+
+
+
+ ID:
+
+
+
+ XML ID:
+
+
+
+ No Update:
+
+
+
+ (change)
+
+
+
+
+ Creation User:
+
+
+
+ Creation Date:
+
+
+
+ Latest Modification by:
+
+
+
+ Latest Modification Date:
+
+
+
+
+
diff --git a/addons/web/static/src/core/debug/debug_service.js b/addons/web/static/src/core/debug/debug_service.js
new file mode 100644
index 00000000000..a29948abc29
--- /dev/null
+++ b/addons/web/static/src/core/debug/debug_service.js
@@ -0,0 +1,74 @@
+/** @odoo-module **/
+
+import { registry } from "../registry";
+import { DebugMenu } from "./debug_menu";
+
+export function editModelDebug(env, title, model, id) {
+ return env.services.action.doAction({
+ res_model: model,
+ res_id: id,
+ name: title,
+ type: "ir.actions.act_window",
+ views: [[false, "form"]],
+ view_mode: "form",
+ target: "new",
+ flags: { action_buttons: true, headless: true },
+ });
+}
+
+export const debugService = {
+ dependencies: ["orm"],
+ start(env, { orm }) {
+ let accessRightsProm;
+ if (env.debug !== "") {
+ registry.category("systray").add(
+ "web.debug_mode_menu",
+ {
+ Component: DebugMenu,
+ },
+ { sequence: 100 }
+ );
+ }
+
+ return {
+ getAccessRights() {
+ if (!accessRightsProm) {
+ accessRightsProm = new Promise((resolve, reject) => {
+ const accessRights = {
+ canEditView: false,
+ canSeeRecordRules: false,
+ canSeeModelAccess: false,
+ };
+ const canEditView = orm
+ .call("ir.ui.view", "check_access_rights", [], {
+ operation: "write",
+ raise_exception: false,
+ })
+ .then((result) => (accessRights.canEditView = result));
+ const canSeeRecordRules = orm
+ .call("ir.rule", "check_access_rights", [], {
+ operation: "read",
+ raise_exception: false,
+ })
+ .then((result) => (accessRights.canSeeRecordRules = result));
+ const canSeeModelAccess = orm
+ .call("ir.model.access", "check_access_rights", [], {
+ operation: "read",
+ raise_exception: false,
+ })
+ .then((result) => (accessRights.canSeeModelAccess = result));
+ Promise.all([canEditView, canSeeRecordRules, canSeeModelAccess])
+ .then(() => resolve(accessRights))
+ .catch((error) => {
+ accessRightsProm = undefined;
+ reject(error);
+ });
+ });
+ }
+ return accessRightsProm;
+ },
+ };
+ },
+};
+
+registry.category("services").add("debug", debugService);
diff --git a/addons/web/static/src/core/debug/profiling/profiling_item.js b/addons/web/static/src/core/debug/profiling/profiling_item.js
new file mode 100644
index 00000000000..64eb4f890d1
--- /dev/null
+++ b/addons/web/static/src/core/debug/profiling/profiling_item.js
@@ -0,0 +1,24 @@
+/** @odoo-module **/
+
+import { DropdownItem } from "@web/core/dropdown/dropdown_item";
+import { useBus } from "@web/core/bus_hook";
+import { useService } from "@web/core/service_hook";
+
+const { Component } = owl;
+
+export class ProfilingItem extends Component {
+ setup() {
+ this.profiling = useService("profiling");
+ this.actionService = useService("action");
+ useBus(this.props.bus, "UPDATE", this.render);
+ }
+
+ changeParam(param, ev) {
+ this.profiling.setParam(param, ev.target.value);
+ }
+ openProfiles() {
+ this.actionService.doAction("base.action_menu_ir_profile");
+ }
+}
+ProfilingItem.components = { DropdownItem };
+ProfilingItem.template = "web.DebugMenu.ProfilingItem";
diff --git a/addons/web/static/src/core/debug/profiling/profiling_item.scss b/addons/web/static/src/core/debug/profiling/profiling_item.scss
new file mode 100644
index 00000000000..8644c3e1e5e
--- /dev/null
+++ b/addons/web/static/src/core/debug/profiling/profiling_item.scss
@@ -0,0 +1,25 @@
+.o_debug_profiling_item {
+ .o_profiling_switch {
+ padding-top: 3px;
+ padding-bottom: 3px;
+ .custom-switch {
+ display: inline-block;
+ }
+ .custom-control-label {
+ cursor: pointer;
+ }
+ .o_open_profiling {
+ padding-top: 3px;
+ }
+ }
+}
+
+.o_debug_manager .fa-bug {
+ position: relative;
+ .o_recording {
+ position: absolute;
+ bottom: -0.1em;
+ right: -0.4em;
+ font-size: 0.8em;
+ }
+}
diff --git a/addons/web/static/src/core/debug/profiling/profiling_item.xml b/addons/web/static/src/core/debug/profiling/profiling_item.xml
new file mode 100644
index 00000000000..a6e43a0e4b8
--- /dev/null
+++ b/addons/web/static/src/core/debug/profiling/profiling_item.xml
@@ -0,0 +1,44 @@
+
+
+
+
+
+
+
+
+
+ Enable profiling
+
+
+
+
+
+
+
+
+ Record sql
+
+
+
+ Record traces
+
+
+
+
+
+
+
diff --git a/addons/web/static/src/core/debug/profiling/profiling_service.js b/addons/web/static/src/core/debug/profiling/profiling_service.js
new file mode 100644
index 00000000000..0f67e5e92de
--- /dev/null
+++ b/addons/web/static/src/core/debug/profiling/profiling_service.js
@@ -0,0 +1,104 @@
+/** @odoo-module **/
+
+import { registry } from "@web/core/registry";
+import { ProfilingItem } from "./profiling_item";
+
+const { core } = owl;
+
+const profilingService = {
+ dependencies: ["orm"],
+ start(env, { orm }) {
+ const sessionInfo = odoo.session_info;
+ const state = {
+ session: sessionInfo.profile_session || false,
+ collectors: sessionInfo.profile_collectors || ["sql", "traces_async"],
+ params: sessionInfo.profile_params || {},
+ get isEnabled() {
+ return Boolean(state.session);
+ },
+ };
+ const bus = new core.EventBus();
+
+ let recordingIcon = null;
+ function updateDebugIcon() {
+ const debugItem = document.querySelector(".o_main_navbar .o_debug_manager .fa-bug");
+ if (state.isEnabled) {
+ recordingIcon = document.createElement("span");
+ recordingIcon.classList.add("o_recording", "text-danger", "fa", "fa-circle");
+ debugItem.appendChild(recordingIcon);
+ } else if (recordingIcon) {
+ debugItem.removeChild(recordingIcon);
+ recordingIcon = null;
+ }
+ }
+
+ if (env.debug) {
+ env.bus.on("WEB_CLIENT_READY", null, updateDebugIcon);
+ }
+
+ async function setProfiling(params) {
+ const kwargs = Object.assign(
+ {
+ collectors: state.collectors,
+ params: state.params,
+ profile: state.isEnabled,
+ },
+ params
+ );
+ const resp = await orm.call("ir.profile", "set_profiling", [], kwargs);
+ state.session = resp.session;
+ state.collectors = resp.collectors;
+ state.params = resp.params;
+ bus.trigger("UPDATE");
+ updateDebugIcon();
+ }
+
+ function profilingSeparator() {
+ return {
+ type: "separator",
+ sequence: 500,
+ };
+ }
+
+ function profilingItem() {
+ return {
+ type: "component",
+ Component: ProfilingItem,
+ props: { bus },
+ sequence: 510,
+ };
+ }
+
+ registry
+ .category("debug")
+ .add("profilingSeparator", profilingSeparator)
+ .add("profilingItem", profilingItem);
+
+ return {
+ state,
+ async toggleProfiling() {
+ await setProfiling({ profile: !state.isEnabled });
+ },
+ async toggleCollector(collector) {
+ let nextCollectors = state.collectors.slice();
+ const index = nextCollectors.indexOf(collector);
+ if (index >= 0) {
+ nextCollectors.splice(index, 1);
+ } else {
+ nextCollectors.push(collector);
+ }
+ await setProfiling({ collectors: nextCollectors });
+ },
+ async setParam(key, value) {
+ const nextParams = Object.assign({}, state.params);
+ nextParams[key] = value;
+ await setProfiling({ params: nextParams });
+ },
+ isCollectorEnabled(collector) {
+ return state.collectors.includes(collector);
+ },
+ };
+ },
+};
+
+registry.category("services").add("profiling", profilingService);
diff --git a/addons/web/static/src/core/dialog/dialog.js b/addons/web/static/src/core/dialog/dialog.js
new file mode 100644
index 00000000000..0766058f92a
--- /dev/null
+++ b/addons/web/static/src/core/dialog/dialog.js
@@ -0,0 +1,55 @@
+/** @odoo-module **/
+
+import { useHotkey } from "../hotkey_hook";
+import { useService } from "../service_hook";
+import { useActiveElement } from "../ui/ui_service";
+
+const { Component, hooks } = owl;
+const { useRef, useSubEnv } = hooks;
+
+export class Dialog extends Component {
+ setup() {
+ if (this.constructor === Dialog) {
+ throw new Error(
+ "Dialog should not be used by itself. Please use the dialog service with a Dialog subclass."
+ );
+ }
+ this.modalRef = useRef("modal");
+ useActiveElement("modal");
+ useHotkey(
+ "escape",
+ () => {
+ this.close();
+ },
+ { altIsOptional: true }
+ );
+ useSubEnv({ inDialog: true });
+ this.close = this.close.bind(this);
+ this.contentClass = this.constructor.contentClass;
+ this.fullscreen = this.constructor.fullscreen;
+ this.renderFooter = this.constructor.renderFooter;
+ this.renderHeader = this.constructor.renderHeader;
+ this.size = this.constructor.size;
+ this.technical = this.constructor.technical;
+ this.title = this.constructor.title;
+ }
+
+ /**
+ * Send an event signaling that the dialog should be closed.
+ * @private
+ */
+ close() {
+ this.props.close();
+ }
+}
+
+Dialog.template = "web.Dialog";
+Dialog.contentClass = null;
+Dialog.fullscreen = false;
+Dialog.renderFooter = true;
+Dialog.renderHeader = true;
+Dialog.size = "modal-lg";
+Dialog.technical = true;
+Dialog.title = "Odoo";
+Dialog.bodyTemplate = owl.tags.xml`
`;
+Dialog.footerTemplate = "web.DialogFooterDefault";
diff --git a/addons/web/static/src/core/dialog/dialog.scss b/addons/web/static/src/core/dialog/dialog.scss
new file mode 100644
index 00000000000..18782781c07
--- /dev/null
+++ b/addons/web/static/src/core/dialog/dialog.scss
@@ -0,0 +1,52 @@
+.o_dialog {
+ > .modal {
+ display: block;
+ }
+}
+
+.modal.o_technical_modal {
+ .modal-content {
+ border-radius: 0;
+
+ .modal-header .modal-title {
+ word-break: break-word;
+ }
+
+ .modal-footer {
+ flex-wrap: wrap;
+ text-align: left;
+ justify-content: flex-start;
+
+ footer {
+ > :not(:first-child) {
+ margin-left: 0.25rem;
+ }
+ > :not(:last-child) {
+ margin-right: 0.25rem;
+ }
+ button {
+ margin-bottom: 0.5rem;
+ }
+ }
+ }
+ }
+
+ @include media-breakpoint-up(sm) {
+ .modal-dialog .modal-content.o_dialog_error .modal-body {
+ overflow: visible;
+ display: flex;
+ flex-flow: column nowrap;
+
+ > .alert,
+ > button {
+ flex: 0 0 auto;
+ }
+
+ > .o_error_detail {
+ flex: 1 1 auto;
+ min-height: 0;
+ overflow: auto;
+ }
+ }
+ }
+}
diff --git a/addons/web/static/src/core/dialog/dialog.xml b/addons/web/static/src/core/dialog/dialog.xml
new file mode 100644
index 00000000000..61a3ce9fd4c
--- /dev/null
+++ b/addons/web/static/src/core/dialog/dialog.xml
@@ -0,0 +1,36 @@
+
+
+
+
+
+
+
+
+
+ Ok
+
+
+
diff --git a/addons/web/static/src/core/dialog/dialog_container.js b/addons/web/static/src/core/dialog/dialog_container.js
new file mode 100644
index 00000000000..c71610d6bf7
--- /dev/null
+++ b/addons/web/static/src/core/dialog/dialog_container.js
@@ -0,0 +1,38 @@
+/** @odoo-module **/
+
+import { ErrorHandler, NotUpdatable } from "../utils/components";
+
+const { Component, tags } = owl;
+
+export class DialogContainer extends Component {
+ setup() {
+ this.props.bus.on("UPDATE", this, this.render);
+ }
+
+ close(id) {
+ if (this.props.dialogs[id]) {
+ this.props.dialogs[id].props.close();
+ }
+ }
+
+ handleError(error, dialogId) {
+ this.close(dialogId);
+ Promise.resolve().then(() => {
+ throw error;
+ });
+ }
+}
+DialogContainer.components = { ErrorHandler, NotUpdatable };
+DialogContainer.template = tags.xml`
+
+
+
+
+
+
+
+
+
+ `;
diff --git a/addons/web/static/src/core/dialog/dialog_service.js b/addons/web/static/src/core/dialog/dialog_service.js
new file mode 100644
index 00000000000..bb6145f6c10
--- /dev/null
+++ b/addons/web/static/src/core/dialog/dialog_service.js
@@ -0,0 +1,68 @@
+/** @odoo-module **/
+
+import { registry } from "../registry";
+import { Dialog } from "./dialog";
+import { DialogContainer } from "./dialog_container";
+
+const { core } = owl;
+const { EventBus } = core;
+
+/**
+ * @typedef {{
+ * onClose?(): void;
+ * }} DialogServiceInterfaceAddOptions
+ */
+/**
+ * @typedef {{
+ * add(
+ * Component: any,
+ * props: {},
+ * options?: DialogServiceInterfaceAddOptions
+ * ): () => void;
+ * }} DialogServiceInterface
+ */
+
+export const dialogService = {
+ /** @returns {DialogServiceInterface} */
+ start() {
+ const dialogs = {};
+ const bus = new EventBus();
+ let dialogId = 0;
+
+ registry.category("main_components").add("DialogContainer", {
+ Component: DialogContainer,
+ props: { bus, dialogs },
+ });
+
+ function add(dialogClass, props, options = {}) {
+ if (!(dialogClass.prototype instanceof Dialog)) {
+ throw new Error(`${dialogClass.name} must be a subclass of Dialog`);
+ }
+
+ const id = ++dialogId;
+ function close() {
+ if (dialogs[id]) {
+ delete dialogs[id];
+ if (options.onClose) {
+ options.onClose();
+ }
+ bus.trigger("UPDATE");
+ }
+ }
+
+ const dialog = {
+ id,
+ class: dialogClass,
+ props: { ...props, close },
+ };
+ dialogs[id] = dialog;
+ bus.trigger("UPDATE");
+
+ return close;
+ }
+
+ return { add };
+ },
+};
+
+registry.category("services").add("dialog", dialogService);
diff --git a/addons/web/static/src/core/domain.js b/addons/web/static/src/core/domain.js
new file mode 100644
index 00000000000..fa92462d090
--- /dev/null
+++ b/addons/web/static/src/core/domain.js
@@ -0,0 +1,276 @@
+/** @odoo-module **/
+
+import { evaluate, formatAST, parseExpr } from "./py_js/py";
+import { toPyValue } from "./py_js/py_utils";
+
+/**
+ * @typedef {import("./py_js/py_parser").AST} AST
+ * @typedef {[string, string, any]} Condition
+ * @typedef {("&" | "|" | "!" | Condition)[]} DomainListRepr
+ * @typedef {DomainListRepr | string | Domain} DomainRepr
+ */
+
+class InvalidDomainError extends Error {}
+
+/**
+ * Javascript representation of an Odoo domain
+ */
+export class Domain {
+ /**
+ * Combine various domains together with a given operator
+ * @param {DomainRepr[]} domains
+ * @param {"AND" | "OR"} operator
+ * @returns {Domain}
+ */
+ static combine(domains, operator) {
+ if (domains.length === 0) {
+ return new Domain([]);
+ }
+ const domain1 = domains[0] instanceof Domain ? domains[0] : new Domain(domains[0]);
+ if (domains.length === 1) {
+ return domain1;
+ }
+ const domain2 = Domain.combine(domains.slice(1), operator);
+ const result = new Domain([]);
+ const astValues1 = domain1.ast.value;
+ const astValues2 = domain2.ast.value;
+ const op = operator === "AND" ? "&" : "|";
+ const combinedAST = { type: 4 /* List */, value: astValues1.concat(astValues2) };
+ result.ast = normalizeDomainAST(combinedAST, op);
+ return result;
+ }
+
+ /**
+ * Combine various domains together with `AND` operator
+ * @param {DomainRepr} domains
+ * @returns {Domain}
+ */
+ static and(domains) {
+ return Domain.combine(domains, "AND");
+ }
+
+ /**
+ * Combine various domains together with `OR` operator
+ * @param {DomainRepr} domains
+ * @returns {Domain}
+ */
+ static or(domains) {
+ return Domain.combine(domains, "OR");
+ }
+
+ /**
+ * Return the negation of the domain
+ * @returns {Domain}
+ */
+ static not(domain) {
+ const result = new Domain(domain);
+ result.ast.value.unshift({ type: 1, value: "!" });
+ return result;
+ }
+
+ /**
+ * @param {DomainRepr} [descr]
+ */
+ constructor(descr = []) {
+ if (descr instanceof Domain) {
+ /** @type {AST} */
+ return new Domain(descr.toString());
+ } else {
+ const rawAST = typeof descr === "string" ? parseExpr(descr) : toAST(descr);
+ this.ast = normalizeDomainAST(rawAST);
+ }
+ }
+
+ /**
+ * Check if the set of records represented by a domain contains a record
+ *
+ * @param {Object} record
+ * @returns {boolean}
+ */
+ contains(record) {
+ const expr = evaluate(this.ast, record);
+ return matchDomain(record, expr);
+ }
+
+ /**
+ * @returns {string}
+ */
+ toString() {
+ return formatAST(this.ast);
+ }
+
+ /**
+ * @param {Object} context
+ * @returns {DomainListRepr}
+ */
+ toList(context) {
+ return evaluate(this.ast, context);
+ }
+}
+
+const TRUE_LEAF = [1, "=", 1];
+const FALSE_LEAF = [0, "=", 1];
+const TRUE_DOMAIN = new Domain([TRUE_LEAF]);
+const FALSE_DOMAIN = new Domain([FALSE_LEAF]);
+
+Domain.TRUE = TRUE_DOMAIN;
+Domain.FALSE = FALSE_DOMAIN;
+
+// -----------------------------------------------------------------------------
+// Helpers
+// -----------------------------------------------------------------------------
+
+/**
+ * @param {DomainListRepr} domain
+ * @returns {AST}
+ */
+function toAST(domain) {
+ const elems = domain.map((elem) => {
+ switch (elem) {
+ case "!":
+ case "&":
+ case "|":
+ return { type: 1 /* String */, value: elem };
+ default:
+ return {
+ type: 10 /* Tuple */,
+ value: elem.map(toPyValue),
+ };
+ }
+ });
+ return { type: 4 /* List */, value: elems };
+}
+
+/**
+ * Normalizes a domain
+ *
+ * @param {AST} domain
+ * @param {'&' | '|'} [op]
+ * @returns {AST}
+ */
+
+function normalizeDomainAST(domain, op = "&") {
+ if (domain.type !== 4 /* List */) {
+ throw new InvalidDomainError("Invalid domain AST");
+ }
+ if (domain.value.length === 0) {
+ return domain;
+ }
+ let expected = 1;
+ for (let child of domain.value) {
+ if (child.type === 1 /* String */ && (child.value === "&" || child.value === "|")) {
+ expected++;
+ } else if (child.type !== 1 /* String */ || child.value !== "!") {
+ expected--;
+ }
+ }
+ let values = domain.value.slice();
+ while (expected < 0) {
+ expected++;
+ values.unshift({ type: 1 /* String */, value: op });
+ }
+ if (expected > 0) {
+ throw new InvalidDomainError(
+ `invalid domain ${formatAST(domain)} (missing ${expected} segment(s))`
+ );
+ }
+ return { type: 4 /* List */, value: values };
+}
+
+/**
+ * @param {Object} record
+ * @param {Condition | boolean} condition
+ * @returns {boolean}
+ */
+function matchCondition(record, condition) {
+ if (typeof condition === "boolean") {
+ return condition;
+ }
+ const [field, operator, value] = condition;
+ const fieldValue = typeof field === "number" ? field : record[field];
+ switch (operator) {
+ case "=":
+ case "==":
+ return fieldValue === value;
+ case "!=":
+ case "<>":
+ return fieldValue !== value;
+ case "<":
+ return fieldValue < value;
+ case "<=":
+ return fieldValue <= value;
+ case ">":
+ return fieldValue > value;
+ case ">=":
+ return fieldValue >= value;
+ case "in":
+ if (Array.isArray(fieldValue)) {
+ return fieldValue.some((fv) => value.includes(fv));
+ }
+ return value.includes(fieldValue);
+ case "not in":
+ if (Array.isArray(fieldValue)) {
+ return !fieldValue.some((fv) => value.includes(fv));
+ }
+ return !value.includes(fieldValue);
+ case "like":
+ if (fieldValue === false) {
+ return false;
+ }
+ return fieldValue.indexOf(value) >= 0;
+ case "=like":
+ if (fieldValue === false) {
+ return false;
+ }
+ return new RegExp(value.replace(/%/g, ".*")).test(fieldValue);
+ case "ilike":
+ if (fieldValue === false) {
+ return false;
+ }
+ return fieldValue.toLowerCase().indexOf(value.toLowerCase()) >= 0;
+ case "=ilike":
+ if (fieldValue === false) {
+ return false;
+ }
+ return new RegExp(value.replace(/%/g, ".*"), "i").test(fieldValue);
+ }
+ throw new InvalidDomainError("could not match domain");
+}
+
+/**
+ * @param {Object} record
+ * @returns {Object}
+ */
+function makeOperators(record) {
+ const match = matchCondition.bind(null, record);
+ return {
+ "!": (x) => !match(x),
+ "&": (a, b) => match(a) && match(b),
+ "|": (a, b) => match(a) || match(b),
+ };
+}
+
+/**
+ *
+ * @param {Object} record
+ * @param {DomainListRepr} domain
+ * @returns {boolean}
+ */
+function matchDomain(record, domain) {
+ if (domain.length === 0) {
+ return true;
+ }
+ const operators = makeOperators(record);
+ const reversedDomain = Array.from(domain).reverse();
+ const condStack = [];
+ for (const item of reversedDomain) {
+ if (item in operators) {
+ const operator = operators[item];
+ const operands = condStack.splice(-operator.length);
+ condStack.push(operator(...operands));
+ } else {
+ condStack.push(item);
+ }
+ }
+ return matchCondition(record, condStack.pop());
+}
diff --git a/addons/web/static/src/core/dropdown/dropdown.js b/addons/web/static/src/core/dropdown/dropdown.js
new file mode 100644
index 00000000000..f41b3ab42fa
--- /dev/null
+++ b/addons/web/static/src/core/dropdown/dropdown.js
@@ -0,0 +1,324 @@
+/** @odoo-module **/
+
+import { useBus } from "../bus_hook";
+import { useService } from "../service_hook";
+import { useEffect } from "../effect_hook";
+import { scrollTo } from "../utils/scrolling";
+import { ParentClosingMode } from "./dropdown_item";
+
+const { Component, core, hooks, useState, QWeb } = owl;
+const { EventBus } = core;
+const { useExternalListener, onWillStart } = hooks;
+
+/**
+ * @typedef DropdownState
+ * @property {boolean} open
+ * @property {boolean} groupIsOpen
+ */
+
+/**
+ * @typedef DropdownStateChangedPayload
+ * @property {Dropdown} emitter
+ * @property {DropdownState} newState
+ */
+
+/**
+ * @extends Component
+ */
+export class Dropdown extends Component {
+ setup() {
+ this.state = useState({
+ open: this.props.startOpen,
+ groupIsOpen: this.props.startOpen,
+ });
+
+ onWillStart(() => {
+ if ((this.state.open || this.state.groupIsOpen) && this.props.beforeOpen) {
+ return this.props.beforeOpen();
+ }
+ });
+
+ if (!this.props.manualOnly) {
+ // Close on outside click listener
+ useExternalListener(window, "click", this.onWindowClicked);
+ // Listen to all dropdowns state changes
+ useBus(Dropdown.bus, "state-changed", this.onDropdownStateChanged);
+ }
+
+ // Set up UI active element related behavior ---------------------------
+ this.ui = useService("ui");
+ useBus(this.ui.bus, "active-element-changed", (activeElement) => {
+ if (activeElement !== this.myActiveEl && !this.state.open) {
+ // Close when UI active element changes to something different
+ this.close();
+ }
+ });
+ useEffect(
+ () => {
+ Promise.resolve().then(() => {
+ this.myActiveEl = this.ui.activeElement;
+ });
+ },
+ () => []
+ );
+
+ // Set up key navigation -----------------------------------------------
+ this.hotkeyService = useService("hotkey");
+ this.hotkeyRemoves = [];
+
+ const nextActiveIndexFns = {
+ FIRST: () => 0,
+ LAST: (items) => items.length - 1,
+ NEXT: (items, prevActiveIndex) => Math.min(prevActiveIndex + 1, items.length - 1),
+ PREV: (_, prevActiveIndex) => Math.max(0, prevActiveIndex - 1),
+ };
+
+ /** @type {(direction: "FIRST"|"LAST"|"NEXT"|"PREV") => Function} */
+ function activeItemSetter(direction) {
+ return function () {
+ const items = [
+ ...this.el.querySelectorAll(":scope > ul.o_dropdown_menu > .o_dropdown_item"),
+ ];
+ const prevActiveIndex = items.findIndex((item) =>
+ [...item.classList].includes("o_dropdown_active")
+ );
+ const nextActiveIndex = nextActiveIndexFns[direction](items, prevActiveIndex);
+ items.forEach((item) => item.classList.remove("o_dropdown_active"));
+ items[nextActiveIndex].classList.add("o_dropdown_active");
+ scrollTo(items[nextActiveIndex], this.el.querySelector(".o_dropdown_menu"));
+ };
+ }
+
+ const hotkeyCallbacks = {
+ arrowdown: activeItemSetter("NEXT").bind(this),
+ arrowup: activeItemSetter("PREV").bind(this),
+ "shift+arrowdown": activeItemSetter("LAST").bind(this),
+ "shift+arrowup": activeItemSetter("FIRST").bind(this),
+ enter: () => {
+ const activeItem = this.el.querySelector(
+ ":scope > ul.o_dropdown_menu > .o_dropdown_item.o_dropdown_active"
+ );
+ if (activeItem) {
+ activeItem.click();
+ }
+ },
+ escape: this.close.bind(this),
+ };
+
+ /** @this {Dropdown} */
+ function autoSubscribeKeynav() {
+ if (this.state.open) {
+ // Subscribe keynav
+ if (this.hotkeyRemoves.length) {
+ // Keynav already subscribed
+ return;
+ }
+ for (const [hotkey, callback] of Object.entries(hotkeyCallbacks)) {
+ this.hotkeyRemoves.push(
+ this.hotkeyService.add(hotkey, callback, {
+ altIsOptional: true,
+ allowRepeat: true,
+ })
+ );
+ }
+ } else {
+ // Unsubscribe keynav
+ for (const removeHotkey of this.hotkeyRemoves) {
+ removeHotkey();
+ }
+ this.hotkeyRemoves = [];
+ }
+ }
+
+ useEffect(autoSubscribeKeynav.bind(this));
+ }
+
+ // -------------------------------------------------------------------------
+ // Private
+ // -------------------------------------------------------------------------
+
+ /**
+ * Changes the dropdown state and notifies over the Dropdown bus.
+ *
+ * All state changes must trigger on the bus, except when reacting to
+ * another dropdown state change.
+ *
+ * @see onDropdownStateChanged()
+ *
+ * @param {Partial} stateSlice
+ */
+ async changeStateAndNotify(stateSlice) {
+ if ((stateSlice.open || stateSlice.groupIsOpen) && this.props.beforeOpen) {
+ await this.props.beforeOpen();
+ }
+ // Update the state
+ Object.assign(this.state, stateSlice);
+ // Notify over the bus
+ /** @type DropdownStateChangedPayload */
+ const stateChangedPayload = {
+ emitter: this,
+ newState: { ...this.state },
+ };
+ Dropdown.bus.trigger("state-changed", stateChangedPayload);
+ }
+
+ /**
+ * Closes the dropdown.
+ *
+ * @returns {Promise}
+ */
+ close() {
+ return this.changeStateAndNotify({ open: false, groupIsOpen: false });
+ }
+
+ /**
+ * Opens the dropdown.
+ *
+ * @returns {Promise}
+ */
+ open() {
+ return this.changeStateAndNotify({ open: true, groupIsOpen: true });
+ }
+
+ /**
+ * Toggles the dropdown open state.
+ *
+ * @returns {Promise}
+ */
+ toggle() {
+ const toggled = !this.state.open;
+ return this.changeStateAndNotify({ open: toggled, groupIsOpen: toggled });
+ }
+
+ // -------------------------------------------------------------------------
+ // Handlers
+ // -------------------------------------------------------------------------
+
+ /**
+ * Checks if should close on dropdown item selection.
+ *
+ * @param {CustomEvent} ev
+ */
+ onItemSelected(ev) {
+ // Handle parent closing request
+ const { dropdownClosingRequest } = ev.detail;
+ const closeAll = dropdownClosingRequest.mode === ParentClosingMode.AllParents;
+ const closeSelf =
+ dropdownClosingRequest.isFresh &&
+ dropdownClosingRequest.mode === ParentClosingMode.ClosestParent;
+ if (!this.props.manualOnly && (closeAll || closeSelf)) {
+ this.close();
+ }
+ // Mark closing request as started
+ ev.detail.dropdownClosingRequest.isFresh = false;
+ }
+
+ /**
+ * Dropdowns react to each other state changes through this method.
+ *
+ * All state changes must trigger on the bus, except when reacting to
+ * another dropdown state change.
+ *
+ * @see changeStateAndNotify()
+ *
+ * @param {DropdownStateChangedPayload} args
+ */
+ onDropdownStateChanged(args) {
+ if (this.el.contains(args.emitter.el)) {
+ // Do not listen to events emitted by self or children
+ return;
+ }
+
+ // Emitted by direct siblings ?
+ if (args.emitter.el.parentElement === this.el.parentElement) {
+ // Sync the group status
+ this.state.groupIsOpen = args.newState.groupIsOpen;
+
+ // Another dropdown is now open ? Close myself without notifying siblings.
+ if (this.state.open && args.newState.open) {
+ this.state.open = false;
+ }
+ } else {
+ // Another dropdown is now open ? Close myself and notify the world (i.e. siblings).
+ if (this.state.open && args.newState.open) {
+ this.close();
+ }
+ }
+ }
+
+ /**
+ * Toggles the dropdown on its toggler click.
+ */
+ onTogglerClick() {
+ this.toggle();
+ }
+
+ /**
+ * Opens the dropdown the mous enters its toggler.
+ * NB: only if its siblings dropdown group is opened.
+ */
+ onTogglerMouseEnter() {
+ if (this.state.groupIsOpen && !this.state.open) {
+ this.open();
+ }
+ }
+
+ /**
+ * Used to close ourself on outside click.
+ *
+ * @param {MouseEvent} ev
+ */
+ onWindowClicked(ev) {
+ // Return if already closed
+ if (!this.state.open) {
+ return;
+ }
+ // Return if it's a different ui active element
+ if (this.ui.activeElement !== this.myActiveEl) {
+ return;
+ }
+
+ const gotClickedInside = this.el.contains(ev.target);
+ if (!gotClickedInside) {
+ this.close();
+ }
+ }
+}
+Dropdown.bus = new EventBus();
+Dropdown.props = {
+ startOpen: {
+ type: Boolean,
+ optional: true,
+ },
+ manualOnly: {
+ type: Boolean,
+ optional: true,
+ },
+ menuClass: {
+ type: String,
+ optional: true,
+ },
+ beforeOpen: {
+ type: Function,
+ optional: true,
+ },
+ tag: {
+ type: String,
+ optional: true,
+ },
+ togglerClass: {
+ type: String,
+ optional: true,
+ },
+ hotkey: {
+ type: String,
+ optional: true,
+ },
+ title: {
+ type: String,
+ optional: true,
+ },
+};
+Dropdown.template = "web.Dropdown";
+
+QWeb.registerComponent("Dropdown", Dropdown);
diff --git a/addons/web/static/src/core/dropdown/dropdown.scss b/addons/web/static/src/core/dropdown/dropdown.scss
new file mode 100644
index 00000000000..628c846b6b6
--- /dev/null
+++ b/addons/web/static/src/core/dropdown/dropdown.scss
@@ -0,0 +1,129 @@
+// = Default Boostrap Classes customizations
+// ----------------------------------------------------------------------------
+.dropdown-menu {
+ min-width: 100%;
+ max-height: 70vh;
+ overflow: auto;
+ background-clip: border-box;
+ box-shadow: $o-dropdown-box-shadow;
+}
+
+.dropdown-item {
+ &.active {
+ position: relative;
+ @extend .font-weight-bold;
+
+ &:not(.o_dropdown_item_active_noarrow):before {
+ @include o-position-absolute(0);
+ transform: translate(-1.5em, 90%);
+ font: .7em/1em FontAwesome;
+ color: $primary;
+ content: "\f00c";
+ }
+ }
+
+ &.selected { // Legacy
+ @extend .dropdown-item.active;
+ }
+
+}
+
+.dropdown-menu .dropdown-item {
+ // Using tags inside a '.dropdown-item' elements should not be necessary
+ // since the class in usually applied to the tag itself.
+ // The following rules will handle custom layouts needs (eg '.o_user_menu').
+ &:not(.disabled):not(:disabled) a:not(.disabled):not(:disabled) {
+ @include o-hover-text-color($dropdown-link-color, $dropdown-link-hover-color);
+ font-weight: inherit;
+ }
+
+ &.disabled a, &:disabled a {
+ @include o-hover-text-color(
+ $dropdown-link-disabled-color,
+ $dropdown-link-disabled-color);
+ }
+}
+
+.dropdown-header {
+ @extend .font-weight-bold;
+ padding-bottom: .1em;
+
+ &:not(:first-child) {
+ margin-top: .3em;
+ }
+}
+
+.dropdown-divider:first-child {
+ display: none;
+}
+
+.o_rtl {
+ .dropdown-menu {
+ @extend .dropdown-menu-right;
+ }
+}
+
+// = Extend Owl custom classes to visually match Boostrap ones
+// ----------------------------------------------------------------------------
+.o_dropdown {
+ @extend .dropdown;
+
+ &_toggler {
+ @extend .dropdown-toggle;
+ }
+
+ &_menu {
+ @extend .dropdown-menu;
+
+ &.o_dropdown_menu_right {
+ @extend .dropdown-menu-right;
+ }
+ }
+
+ &_item {
+ @extend .dropdown-item;
+
+ // we want the dropdownitem first child to define its own padding
+ // because it can be an
+ padding: 0;
+ > *:first-child {
+ padding: $dropdown-item-padding-y $dropdown-item-padding-x;
+ display: flex;
+ }
+
+ &.o_dropdown_active {
+ @extend .dropdown-item:hover;
+ }
+ }
+
+ &_menu_group {
+ @extend .dropdown-header;
+ }
+}
+
+// = Owl components specific rules
+// -----------------------------------------------------------------------------
+.o_dropdown_item:not(.disabled):not(:disabled) {
+ // Needed 'cause generate html tags that for browsers are
+ // normally not clickable.
+ cursor: pointer;
+}
+
+button.o_dropdown_toggler {
+ > span {
+ min-width: max-content;
+ }
+
+ &%--state-active {
+ outline: none;
+ box-shadow: none !important;
+ }
+
+ &.o_dropdown_active {
+ @extend %--state-active;
+ }
+
+ @include hover-focus-active() {
+ @extend %--state-active;
+ }
+}
diff --git a/addons/web/static/src/core/dropdown/dropdown.xml b/addons/web/static/src/core/dropdown/dropdown.xml
new file mode 100644
index 00000000000..f2b8d4d4fdf
--- /dev/null
+++ b/addons/web/static/src/core/dropdown/dropdown.xml
@@ -0,0 +1,27 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/addons/web/static/src/core/dropdown/dropdown_item.js b/addons/web/static/src/core/dropdown/dropdown_item.js
new file mode 100644
index 00000000000..c51361aec57
--- /dev/null
+++ b/addons/web/static/src/core/dropdown/dropdown_item.js
@@ -0,0 +1,66 @@
+/** @odoo-module **/
+
+const { Component, QWeb } = owl;
+
+/**
+ * @enum {string}
+ */
+export const ParentClosingMode = {
+ None: "none",
+ ClosestParent: "closest",
+ AllParents: "all",
+};
+
+/**
+ * @typedef DropdownItemSelectedEventDetail
+ * @property {*} payload
+ * @property {Object} dropdownClosingRequest
+ * @property {boolean} dropdownClosingRequest.isFresh
+ * @property {ParentClosingMode} dropdownClosingRequest.mode
+ *
+ * @typedef {CustomEvent} DropdownItemSelectedEvent
+ */
+
+/**
+ * @extends Component
+ */
+export class DropdownItem extends Component {
+ /**
+ * Triggers a custom DropdownItemSelectedEvent
+ */
+ onClick() {
+ /** @type DropdownItemSelectedEventDetail */
+ const detail = {
+ payload: this.props.payload,
+ dropdownClosingRequest: {
+ isFresh: true,
+ mode: this.props.parentClosingMode,
+ },
+ };
+ this.trigger("dropdown-item-selected", detail);
+ }
+}
+DropdownItem.template = "web.DropdownItem";
+DropdownItem.props = {
+ payload: {
+ type: Object,
+ optional: true,
+ },
+ parentClosingMode: {
+ type: ParentClosingMode,
+ optional: true,
+ },
+ hotkey: {
+ type: String,
+ optional: true,
+ },
+ title: {
+ type: String,
+ optional: true,
+ },
+};
+DropdownItem.defaultProps = {
+ parentClosingMode: ParentClosingMode.AllParents,
+};
+
+QWeb.registerComponent("DropdownItem", DropdownItem);
diff --git a/addons/web/static/src/core/dropdown/dropdown_item.xml b/addons/web/static/src/core/dropdown/dropdown_item.xml
new file mode 100644
index 00000000000..f1533698cf6
--- /dev/null
+++ b/addons/web/static/src/core/dropdown/dropdown_item.xml
@@ -0,0 +1,15 @@
+
+
+
+
+
+
+
+
+
+
diff --git a/addons/web/static/src/core/effect_hook.js b/addons/web/static/src/core/effect_hook.js
new file mode 100644
index 00000000000..91ae4e8df69
--- /dev/null
+++ b/addons/web/static/src/core/effect_hook.js
@@ -0,0 +1,47 @@
+/** @odoo-module */
+const { onMounted, onWillPatch, onPatched, onWillUnmount } = owl.hooks;
+
+const NO_OP = () => {};
+/**
+ * @callback Effect
+ * @param {...any} dependencies the dependecies computed by computeDependencies
+ * @returns {()=>void)?} a cleanup function that reverses the side
+ * effects of the effect callback.
+ */
+
+/**
+ * This hook will run a callback when a component is mounted and patched, and
+ * will run a cleanup function before patching and before unmounting the
+ * the component.
+ *
+ * @param {Effect} effect the effect to run on component mount and/or patch
+ * @param {()=>any[]} [computeDependencies=()=>[NaN]] a callback to compute
+ * dependencies that will decide if the effect needs to be cleaned up and
+ * run again. If the dependencies did not change, the effect will not run
+ * again. The default value returns an array containing only NaN because
+ * NaN !== NaN, which will cause the effect to rerun on every patch.
+ */
+export function useEffect(effect, computeDependencies = () => [NaN]) {
+ let cleanup, dependencies;
+ onMounted(() => {
+ dependencies = computeDependencies();
+ cleanup = effect(...dependencies) || NO_OP;
+ });
+
+ let shouldReapplyOnPatch = false;
+ onWillPatch(() => {
+ const newDeps = computeDependencies();
+ shouldReapplyOnPatch = newDeps.some((val, i) => val !== dependencies[i]);
+ if (shouldReapplyOnPatch) {
+ cleanup();
+ dependencies = newDeps;
+ }
+ });
+ onPatched(() => {
+ if (shouldReapplyOnPatch) {
+ cleanup = effect(...dependencies) || NO_OP;
+ }
+ });
+
+ onWillUnmount(() => cleanup());
+}
diff --git a/addons/web/static/src/core/errors/error_dialogs.js b/addons/web/static/src/core/errors/error_dialogs.js
new file mode 100644
index 00000000000..84f932f2b9f
--- /dev/null
+++ b/addons/web/static/src/core/errors/error_dialogs.js
@@ -0,0 +1,184 @@
+/** @odoo-module **/
+
+import { browser } from "../browser/browser";
+import { Dialog } from "../dialog/dialog";
+import { _lt } from "../l10n/translation";
+import { registry } from "../registry";
+import { useService } from "../service_hook";
+import { capitalize } from "../utils/strings";
+
+const { hooks } = owl;
+const { useState } = hooks;
+
+const odooExceptionTitleMap = new Map();
+
+odooExceptionTitleMap.set("odoo.exceptions.AccessDenied", _lt("Access Denied"));
+odooExceptionTitleMap.set("odoo.exceptions.AccessError", _lt("Access Error"));
+odooExceptionTitleMap.set("odoo.exceptions.MissingError", _lt("Missing Record"));
+odooExceptionTitleMap.set("odoo.exceptions.UserError", _lt("User Error"));
+odooExceptionTitleMap.set("odoo.exceptions.ValidationError", _lt("Validation Error"));
+
+// -----------------------------------------------------------------------------
+// Generic Error Dialog
+// -----------------------------------------------------------------------------
+export class ErrorDialog extends Dialog {
+ setup() {
+ super.setup();
+ this.state = useState({
+ showTraceback: false,
+ });
+ }
+ onClickClipboard() {
+ browser.navigator.clipboard.writeText(
+ `${this.props.name}\n${this.props.message}\n${this.props.traceback}`
+ );
+ }
+}
+ErrorDialog.contentClass = "o_dialog_error";
+ErrorDialog.bodyTemplate = "web.ErrorDialogBody";
+ErrorDialog.title = _lt("Odoo Error");
+
+// -----------------------------------------------------------------------------
+// Client Error Dialog
+// -----------------------------------------------------------------------------
+export class ClientErrorDialog extends ErrorDialog {}
+ClientErrorDialog.title = _lt("Odoo Client Error");
+
+// -----------------------------------------------------------------------------
+// Server Error Dialog
+// -----------------------------------------------------------------------------
+export class ServerErrorDialog extends ErrorDialog {}
+ServerErrorDialog.title = _lt("Odoo Server Error");
+
+// -----------------------------------------------------------------------------
+// Network Error Dialog
+// -----------------------------------------------------------------------------
+export class NetworkErrorDialog extends ErrorDialog {}
+NetworkErrorDialog.title = _lt("Odoo Network Error");
+
+// -----------------------------------------------------------------------------
+// RPC Error Dialog
+// -----------------------------------------------------------------------------
+export class RPCErrorDialog extends Dialog {
+ setup() {
+ super.setup();
+ this.title = this.env._t("Odoo Error");
+ this.state = useState({
+ showTraceback: false,
+ });
+ this.inferTitle();
+ this.traceback = this.props.traceback;
+ if (this.props.data && this.props.data.debug) {
+ this.traceback = `${this.props.data.debug}`;
+ }
+ }
+ inferTitle() {
+ // If the server provides an exception name that we have in a registry.
+ if (this.props.exceptionName && odooExceptionTitleMap.has(this.props.exceptionName)) {
+ this.title = odooExceptionTitleMap.get(this.props.exceptionName).toString();
+ return;
+ }
+ // Fall back to a name based on the error type.
+ if (!this.props.type) return;
+ switch (this.props.type) {
+ case "server":
+ this.title = this.env._t("Odoo Server Error");
+ break;
+ case "script":
+ this.title = this.env._t("Odoo Client Error");
+ break;
+ case "network":
+ this.title = this.env._t("Odoo Network Error");
+ break;
+ }
+ }
+
+ onClickClipboard() {
+ browser.navigator.clipboard.writeText(
+ `${this.props.name}\n${this.props.message}\n${this.traceback}`
+ );
+ }
+}
+RPCErrorDialog.bodyTemplate = "web.ErrorDialogBody";
+
+// -----------------------------------------------------------------------------
+// Warning Dialog
+// -----------------------------------------------------------------------------
+export class WarningDialog extends Dialog {
+ setup() {
+ super.setup();
+ this.title = this.env._t("Odoo Warning");
+ this.inferTitle();
+ const { data, message } = this.props;
+ if (data && data.arguments && data.arguments.length > 0) {
+ this.message = data.arguments[0];
+ } else {
+ this.message = message;
+ }
+ }
+ inferTitle() {
+ if (this.props.exceptionName && odooExceptionTitleMap.has(this.props.exceptionName)) {
+ this.title = odooExceptionTitleMap.get(this.props.exceptionName).toString();
+ }
+ }
+}
+WarningDialog.bodyTemplate = "web.WarningDialogBody";
+
+// -----------------------------------------------------------------------------
+// Redirect Warning Dialog
+// -----------------------------------------------------------------------------
+export class RedirectWarningDialog extends Dialog {
+ setup() {
+ super.setup();
+ this.actionService = useService("action");
+ const { data, subType } = this.props;
+ const [message, actionId, buttonText, additional_context] = data.arguments;
+ this.title = capitalize(subType) || this.env._t("Odoo Warning");
+ this.message = message;
+ this.actionId = actionId;
+ this.buttonText = buttonText;
+ this.additionalContext = additional_context;
+ }
+ async onClick() {
+ await this.actionService.doAction(this.actionId, {
+ additionalContext: this.additionalContext,
+ });
+ this.close();
+ }
+ onCancel() {
+ this.close();
+ }
+}
+RedirectWarningDialog.bodyTemplate = "web.RedirectWarningDialogBody";
+RedirectWarningDialog.footerTemplate = "web.RedirectWarningDialogFooter";
+
+// -----------------------------------------------------------------------------
+// Error 504 Dialog
+// -----------------------------------------------------------------------------
+export class Error504Dialog extends Dialog {}
+Error504Dialog.bodyTemplate = "web.Error504DialogBody";
+Error504Dialog.title = _lt("Request timeout");
+
+// -----------------------------------------------------------------------------
+// Expired Session Error Dialog
+// -----------------------------------------------------------------------------
+export class SessionExpiredDialog extends Dialog {
+ onClick() {
+ browser.location.reload();
+ }
+}
+SessionExpiredDialog.bodyTemplate = "web.SessionExpiredDialogBody";
+SessionExpiredDialog.footerTemplate = "web.SessionExpiredDialogFooter";
+SessionExpiredDialog.title = _lt("Odoo Session Expired");
+
+registry
+ .category("error_dialogs")
+ .add("odoo.exceptions.AccessDenied", WarningDialog)
+ .add("odoo.exceptions.AccessError", WarningDialog)
+ .add("odoo.exceptions.MissingError", WarningDialog)
+ .add("odoo.exceptions.UserError", WarningDialog)
+ .add("odoo.exceptions.ValidationError", WarningDialog)
+ .add("odoo.exceptions.RedirectWarning", RedirectWarningDialog)
+ .add("odoo.http.SessionExpiredException", SessionExpiredDialog)
+ .add("werkzeug.exceptions.Forbidden", SessionExpiredDialog)
+ .add("504", Error504Dialog);
diff --git a/addons/web/static/src/core/errors/error_dialogs.xml b/addons/web/static/src/core/errors/error_dialogs.xml
new file mode 100644
index 00000000000..0d2c6e6c7b3
--- /dev/null
+++ b/addons/web/static/src/core/errors/error_dialogs.xml
@@ -0,0 +1,63 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Cancel
+
+
+
+
+
+ The operation was interrupted. This usually means that the current operation is taking too much time.
+
+
+
+
+
+
+
+ Your Odoo session expired. The current page is about to be refreshed.
+
+
+
+
+
+ Ok
+
+
+
+
+
+
+ Copy the full error to clipboard
+
+
+
An error occurred
+
Please use the copy button to report the error to your support service.
+
+
+
+ See details
+
+
+
+
+
diff --git a/addons/web/static/src/core/errors/error_handlers.js b/addons/web/static/src/core/errors/error_handlers.js
new file mode 100644
index 00000000000..1de0938a911
--- /dev/null
+++ b/addons/web/static/src/core/errors/error_handlers.js
@@ -0,0 +1,201 @@
+/** @odoo-module **/
+
+import { browser } from "../browser/browser";
+import { ConnectionLostError, RPCError } from "../network/rpc_service";
+import { registry } from "../registry";
+import {
+ ClientErrorDialog,
+ ErrorDialog,
+ NetworkErrorDialog,
+ RPCErrorDialog,
+} from "./error_dialogs";
+import { UncaughtClientError, UncaughtCorsError, UncaughtPromiseError } from "./error_service";
+
+/**
+ * @typedef {import("../../env").OdooEnv} OdooEnv
+ * @typedef {import("./error_service").UncaughtError} UncaughError
+ */
+
+const errorHandlerRegistry = registry.category("error_handlers");
+const errorDialogRegistry = registry.category("error_dialogs");
+
+// -----------------------------------------------------------------------------
+// CORS errors
+// -----------------------------------------------------------------------------
+
+/**
+ * @param {OdooEnv} env
+ * @param {UncaughError} error
+ * @returns {boolean}
+ */
+function corsErrorHandler(env, error) {
+ if (error instanceof UncaughtCorsError) {
+ env.services.dialog.add(NetworkErrorDialog, {
+ traceback: error.traceback,
+ message: error.message,
+ name: error.name,
+ });
+ return true;
+ }
+}
+errorHandlerRegistry.add("corsErrorHandler", corsErrorHandler, { sequence: 95 });
+
+// -----------------------------------------------------------------------------
+// Client errors
+// -----------------------------------------------------------------------------
+
+/**
+ * @param {OdooEnv} env
+ * @param {UncaughError} error
+ * @returns {boolean}
+ */
+function clientErrorHandler(env, error) {
+ if (error instanceof UncaughtClientError) {
+ env.services.dialog.add(ClientErrorDialog, {
+ traceback: error.traceback,
+ message: error.message,
+ name: error.name,
+ });
+ return true;
+ }
+}
+errorHandlerRegistry.add("clientErrorHandler", clientErrorHandler, { sequence: 96 });
+
+// -----------------------------------------------------------------------------
+// RPC errors
+// -----------------------------------------------------------------------------
+
+/**
+ * @param {OdooEnv} env
+ * @param {UncaughError} error
+ * @param {Error} originalError
+ * @returns {boolean}
+ */
+function rpcErrorHandler(env, error, originalError) {
+ if (!(error instanceof UncaughtPromiseError)) {
+ return false;
+ }
+ if (originalError instanceof RPCError) {
+ // When an error comes from the server, it can have an exeption name.
+ // (or any string truly). It is used as key in the error dialog from
+ // server registry to know which dialog component to use.
+ // It's how a backend dev can easily map its error to another component.
+ // Note that for a client side exception, we don't use this registry
+ // as we can directly assign a value to `component`.
+ // error is here a RPCError
+ error.unhandledRejectionEvent.preventDefault();
+ const exceptionName = originalError.exceptionName;
+ let ErrorComponent = null;
+ if (exceptionName && errorDialogRegistry.contains(exceptionName)) {
+ ErrorComponent = errorDialogRegistry.get(exceptionName);
+ }
+
+ env.services.dialog.add(ErrorComponent || RPCErrorDialog, {
+ traceback: error.traceback,
+ message: originalError.message,
+ name: originalError.name,
+ exceptionName: originalError.exceptionName,
+ data: originalError.data,
+ subType: originalError.subType,
+ code: originalError.code,
+ type: originalError.type,
+ });
+ return true;
+ }
+}
+errorHandlerRegistry.add("rpcErrorHandler", rpcErrorHandler, { sequence: 97 });
+
+// -----------------------------------------------------------------------------
+// Lost connection errors
+// -----------------------------------------------------------------------------
+
+let connectionLostNotifRemove = null;
+/**
+ * @param {OdooEnv} env
+ * @param {UncaughError} error
+ * @param {Error} originalError
+ * @returns {boolean}
+ */
+function lostConnectionHandler(env, error, originalError) {
+ if (!(error instanceof UncaughtPromiseError)) {
+ return false;
+ }
+ if (originalError instanceof ConnectionLostError) {
+ if (connectionLostNotifRemove) {
+ // notification already displayed (can occur if there were several
+ // concurrent rpcs when the connection was lost)
+ return true;
+ }
+ connectionLostNotifRemove = env.services.notification.add(
+ env._t("Connection lost. Trying to reconnect..."),
+ { sticky: true }
+ );
+ let delay = 2000;
+ browser.setTimeout(function checkConnection() {
+ env.services
+ .rpc("/web/webclient/version_info", {})
+ .then(function () {
+ if (connectionLostNotifRemove) {
+ connectionLostNotifRemove();
+ connectionLostNotifRemove = null;
+ }
+ env.services.notification.add(
+ env._t("Connection restored. You are back online."),
+ {
+ type: "info",
+ }
+ );
+ })
+ .catch(() => {
+ // exponential backoff, with some jitter
+ delay = delay * 1.5 + 500 * Math.random();
+ browser.setTimeout(checkConnection, delay);
+ });
+ }, delay);
+ return true;
+ }
+}
+errorHandlerRegistry.add("lostConnectionHandler", lostConnectionHandler, { sequence: 98 });
+
+// -----------------------------------------------------------------------------
+// Empty rejection errors
+// -----------------------------------------------------------------------------
+
+/**
+ * @param {OdooEnv} env
+ * @param {UncaughError} error
+ * @returns {boolean}
+ */
+function emptyRejectionErrorHandler(env, error) {
+ if (!(error instanceof UncaughtPromiseError)) {
+ return false;
+ }
+ env.services.dialog.add(ClientErrorDialog, {
+ traceback: error.traceback,
+ message: error.message,
+ name: error.name,
+ });
+ return true;
+}
+errorHandlerRegistry.add("emptyRejectionErrorHandler", emptyRejectionErrorHandler, {
+ sequence: 99,
+});
+
+// -----------------------------------------------------------------------------
+// Default handler
+// -----------------------------------------------------------------------------
+
+/**
+ * @param {OdooEnv} env
+ * @param {UncaughError} error
+ * @returns {boolean}
+ */
+function defaultHandler(env, error) {
+ env.services.dialog.add(ErrorDialog, {
+ traceback: error.traceback,
+ message: error.message,
+ name: error.name,
+ });
+ return true;
+}
+errorHandlerRegistry.add("defaultHandler", defaultHandler, { sequence: 100 });
diff --git a/addons/web/static/src/core/errors/error_service.js b/addons/web/static/src/core/errors/error_service.js
new file mode 100644
index 00000000000..c8725927fac
--- /dev/null
+++ b/addons/web/static/src/core/errors/error_service.js
@@ -0,0 +1,134 @@
+/** @odoo-module **/
+
+import { browser } from "../browser/browser";
+import { _lt } from "../l10n/translation";
+import { registry } from "../registry";
+import { annotateTraceback, formatTraceback, getErrorTechnicalName } from "./error_utils";
+
+/**
+ * Uncaught Errors have 4 properties:
+ * - name: technical name of the error (UncaughtError, ...)
+ * - message: short user visible description of the issue ("Uncaught Cors Error")
+ * - traceback: long description, possibly technical of the issue (such as a traceback)
+ * - originalError: the error that was actually being caught. Note that it is not
+ * necessarily an error (for ex, if some code does throw "boom")
+ */
+export class UncaughtError extends Error {
+ constructor(message) {
+ super(message);
+ this.name = getErrorTechnicalName(this);
+ this.traceback = null;
+ }
+}
+
+export class UncaughtClientError extends UncaughtError {
+ constructor(message = _lt("Uncaught Javascript Error")) {
+ super(message);
+ }
+}
+
+export class UncaughtPromiseError extends UncaughtError {
+ constructor(message = _lt("Uncaught Promise")) {
+ super(message);
+ this.unhandledRejectionEvent = null;
+ }
+}
+
+export class UncaughtCorsError extends UncaughtError {
+ constructor(message = _lt("Uncaught CORS Error")) {
+ super(message);
+ }
+}
+
+/**
+ * @param {UncaughtError} uncaughtError
+ * @param {Error} originalError
+ * @returns {string}
+ */
+function combineErrorNames(uncaughtError, originalError) {
+ const originalErrorName = getErrorTechnicalName(originalError);
+ const uncaughtErrorName = getErrorTechnicalName(uncaughtError);
+ if (originalErrorName === Error.name) {
+ return uncaughtErrorName;
+ } else {
+ return `${uncaughtErrorName} > ${originalErrorName}`;
+ }
+}
+
+/**
+ * @param {import("../../env").OdooEnv} env
+ * @param {UncaughtError} uncaughtError
+ * @param {Error} originalError
+ * @returns {Promise}
+ */
+async function completeUncaughtError(env, uncaughtError, originalError) {
+ uncaughtError.name = combineErrorNames(uncaughtError, originalError);
+ if (env.debug.includes("assets")) {
+ uncaughtError.traceback = await annotateTraceback(originalError);
+ } else {
+ uncaughtError.traceback = formatTraceback(originalError);
+ }
+ if (originalError.message) {
+ uncaughtError.message = `${uncaughtError.message} > ${originalError.message}`;
+ }
+}
+
+export const errorService = {
+ start(env) {
+ const handlers = registry.category("error_handlers").getAll();
+
+ function handleError(error, originalError, retry = true) {
+ const services = env.services;
+ if (!services.dialog || !services.notification || !services.rpc) {
+ // here, the environment is not ready to provide feedback to the user.
+ // We simply wait 1 sec and try again, just in case the application can
+ // recover.
+ if (retry) {
+ browser.setTimeout(() => {
+ handleError(error, originalError, false);
+ }, 1000);
+ }
+ return;
+ }
+ for (let handler of handlers) {
+ if (handler(env, error, originalError)) {
+ break;
+ }
+ }
+ }
+
+ window.addEventListener("error", async (ev) => {
+ const { colno, error: originalError, filename, lineno, message } = ev;
+ let uncaughtError;
+ if (!filename && !lineno && !colno) {
+ uncaughtError = new UncaughtCorsError();
+ uncaughtError.traceback = env._t(
+ `Unknown CORS error\n\n` +
+ `An unknown CORS error occured.\n` +
+ `The error probably originates from a JavaScript file served from a different origin.\n` +
+ `(Opening your browser console might give you a hint on the error.)`
+ );
+ } else {
+ // ignore Chrome video internal error: https://crbug.com/809574
+ if (!originalError && message === "ResizeObserver loop limit exceeded") {
+ return;
+ }
+ uncaughtError = new UncaughtClientError();
+ await completeUncaughtError(env, uncaughtError, originalError);
+ }
+ handleError(uncaughtError, originalError);
+ });
+
+ window.addEventListener("unhandledrejection", async (ev) => {
+ const originalError = ev.reason;
+ const uncaughtError = new UncaughtPromiseError();
+ uncaughtError.unhandledRejectionEvent = ev;
+ if (originalError instanceof Error) {
+ await completeUncaughtError(env, uncaughtError, originalError);
+ }
+ handleError(uncaughtError, originalError);
+ });
+ },
+};
+
+registry.category("services").add("error", errorService, { sequence: 1 });
diff --git a/addons/web/static/src/core/errors/error_utils.js b/addons/web/static/src/core/errors/error_utils.js
new file mode 100644
index 00000000000..e6d3be23f8e
--- /dev/null
+++ b/addons/web/static/src/core/errors/error_utils.js
@@ -0,0 +1,94 @@
+/** @odoo-module **/
+
+import { loadAssets } from "../assets";
+import { isBrowserChrome } from "../browser/feature_detection";
+
+/**
+ * @param {Error} error
+ * @returns {string}
+ */
+export function getErrorTechnicalName(error) {
+ return error.name !== Error.name ? error.name : error.constructor.name;
+}
+
+/**
+ * Format the traceback of an error. Basically, we just add the error message
+ * in the traceback if necessary (Chrome already does it by default, but not
+ * other browser.)
+ *
+ * @param {Error} error
+ * @returns {string}
+ */
+export function formatTraceback(error) {
+ let traceback = error.stack;
+ const errorName = getErrorTechnicalName(error);
+ if (!isBrowserChrome()) {
+ // transforms the stack into a chromium stack
+ // Chromium stack example:
+ // Error: Mock: Can't write value
+ // _onOpenFormView@http://localhost:8069/web/content/425-baf33f1/web.assets.js:1064:30
+ // ...
+ traceback = `${errorName}: ${error.message}\n${error.stack}`.replace(/\n/g, "\n ");
+ } else {
+ // Chromium stack starts with the error's name but the name is "Error" by default
+ // so we replace it to have the error type name
+ traceback = error.stack.replace(/^[^:]*/g, errorName);
+ }
+ return traceback;
+}
+
+/**
+ * Returns an annotated traceback from an error. This is asynchronous because
+ * it needs to fetch the sourcemaps for each script involved in the error,
+ * then compute the correct file/line numbers and add the information to the
+ * correct line.
+ *
+ * @param {Error} error
+ * @returns {Promise}
+ */
+export async function annotateTraceback(error) {
+ const traceback = formatTraceback(error);
+ try {
+ await loadAssets({
+ jsLibs: ["/web/static/lib/stacktracejs/stacktrace.js"],
+ });
+ } catch (e) {
+ return traceback;
+ }
+ // In Firefox, the error stack generated by anonymous code (example: invalid
+ // code in a template) is not compatible with the stacktrace lib. This code
+ // corrects the stack to make it compatible with the lib stacktrace.
+ if (error.stack) {
+ const regex = / line (\d*) > (Function):(\d*)/gm;
+ const subst = `:$1`;
+ error.stack = error.stack.replace(regex, subst);
+ }
+ // eslint-disable-next-line no-undef
+ const frames = await StackTrace.fromError(error);
+ const lines = traceback.split("\n");
+ if (lines[lines.length - 1].trim() === "") {
+ // firefox traceback have an empty line at the end
+ lines.splice(-1);
+ }
+
+ // Chrome stacks contains some lines with (index 0) which apparently
+ // corresponds to some native functions (at least Promise.all). We need to
+ // ignore them because they will not correspond to a stackframe.
+ const skips = lines.filter((l) => l.includes("(index 0")).length;
+ const offset = lines.length - frames.length - skips;
+ let lineIndex = offset;
+ let frameIndex = 0;
+ while (frameIndex < frames.length) {
+ const line = lines[lineIndex];
+ if (line.includes("(index 0)")) {
+ lineIndex++;
+ continue;
+ }
+ const frame = frames[frameIndex];
+ const info = ` (${frame.fileName}:${frame.lineNumber})`;
+ lines[lineIndex] = line + info;
+ lineIndex++;
+ frameIndex++;
+ }
+ return lines.join("\n");
+}
diff --git a/addons/web/static/src/core/file_input/file_input.js b/addons/web/static/src/core/file_input/file_input.js
new file mode 100644
index 00000000000..7b86febcdf4
--- /dev/null
+++ b/addons/web/static/src/core/file_input/file_input.js
@@ -0,0 +1,87 @@
+/** @odoo-module **/
+
+import { useService } from "../service_hook";
+
+const { Component, hooks, QWeb } = owl;
+const { useRef } = hooks;
+
+/**
+ * Custom file input
+ *
+ * Component representing a customized input of type file. It takes a sub-template
+ * in its default t-slot and uses it as the trigger to open the file upload
+ * prompt.
+ * @extends Component
+ *
+ * Props:
+ * @param {string} [props.accepted_file_extensions='*'] Comma-separated
+ * list of authorized file extensions (default to all).
+ * @param {string} [props.action='/web/binary/upload'] Route called when
+ * a file is uploaded in the input.
+ * @param {string} [props.id]
+ * @param {string} [props.model]
+ * @param {string} [props.multi_upload=false] Whether the input should allow
+ * to upload multiple files at once.
+ */
+export class FileInput extends Component {
+ setup() {
+ this.http = useService("http");
+ this.fileInputRef = useRef("file-input");
+ }
+
+ //--------------------------------------------------------------------------
+ // Handlers
+ //--------------------------------------------------------------------------
+
+ /**
+ * Upload an attachment to the given action with the given parameters:
+ * - ufile: list of files contained in the file input
+ * - csrf_token: CSRF token provided by the odoo global object
+ * - model: a specific model which will be given when creating the attachment
+ * - id: the id of the model target instance
+ * @private
+ */
+ async onFileInputChange() {
+ const { action, model, id } = this.props;
+ const params = {
+ csrf_token: odoo.csrf_token,
+ ufile: [...this.fileInputRef.el.files],
+ };
+ if (model) {
+ params.model = model;
+ }
+ if (id) {
+ params.id = id;
+ }
+ const fileData = await this.http.post(action, params, "text");
+ const parsedFileData = JSON.parse(fileData);
+ if (parsedFileData.error) {
+ throw new Error(parsedFileData.error);
+ }
+ this.trigger("uploaded", { files: parsedFileData });
+ }
+
+ /**
+ * Redirect clicks from the trigger element to the input.
+ * @private
+ */
+ onTriggerClicked() {
+ this.fileInputRef.el.click();
+ }
+}
+
+FileInput.defaultProps = {
+ accepted_file_extensions: "*",
+ action: "/web/binary/upload",
+ multi_upload: false,
+};
+FileInput.props = {
+ accepted_file_extensions: { type: String, optional: 1 },
+ action: { type: String, optional: 1 },
+ id: { type: Number, optional: 1 },
+ model: { type: String, optional: 1 },
+ multi_upload: { type: Boolean, optional: 1 },
+};
+FileInput.template = "web.FileInput";
+
+QWeb.registerComponent("FileInput", FileInput);
diff --git a/addons/web/static/src/core/file_input/file_input.xml b/addons/web/static/src/core/file_input/file_input.xml
new file mode 100644
index 00000000000..aec7608927d
--- /dev/null
+++ b/addons/web/static/src/core/file_input/file_input.xml
@@ -0,0 +1,19 @@
+
+
+
+
+
+
+
+ Choose File
+
+
+
+
+
+
+
diff --git a/addons/web/static/src/core/hotkey_hook.js b/addons/web/static/src/core/hotkey_hook.js
new file mode 100644
index 00000000000..f9535dbc9dc
--- /dev/null
+++ b/addons/web/static/src/core/hotkey_hook.js
@@ -0,0 +1,26 @@
+/** @odoo-module */
+
+import { useService } from "./service_hook";
+import { useEffect } from "./effect_hook";
+
+/**
+ * This hook will register/unregister the given registration
+ * when the caller component will mount/unmount.
+ *
+ * @param {string} hotkey
+ * @param {()=>void} callback
+ * @param {Object} options additional options
+ * @param {boolean} [options.altIsOptional=false]
+ * allow registration to perform even without pressing the ALT key
+ * @param {boolean} [options.allowRepeat=false]
+ * allow registration to perform multiple times when hotkey is held down
+ * @param {boolean} [options.global=false]
+ * allow registration to perform no matter the UI active element
+ */
+export function useHotkey(hotkey, callback, options = {}) {
+ const hotkeyService = useService("hotkey");
+ useEffect(
+ () => hotkeyService.add(hotkey, callback, options),
+ () => []
+ );
+}
diff --git a/addons/web/static/src/core/hotkeys/hotkey.scss b/addons/web/static/src/core/hotkeys/hotkey.scss
new file mode 100644
index 00000000000..1c852fdcfed
--- /dev/null
+++ b/addons/web/static/src/core/hotkeys/hotkey.scss
@@ -0,0 +1,12 @@
+.o_web_hotkey_overlay {
+ @include o-position-absolute(0, 0);
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ width: 100%;
+ height: 100%;
+ background-color: rgba(0, 0, 0, 0.6);
+ color: #ffffff;
+ font-size: 1rem;
+ font-family: $font-family-sans-serif;
+}
diff --git a/addons/web/static/src/core/hotkeys/hotkey_service.js b/addons/web/static/src/core/hotkeys/hotkey_service.js
new file mode 100644
index 00000000000..10a6d89ce90
--- /dev/null
+++ b/addons/web/static/src/core/hotkeys/hotkey_service.js
@@ -0,0 +1,330 @@
+/** @odoo-module **/
+
+import { isMacOS } from "../browser/feature_detection";
+import { registry } from "../registry";
+import { browser } from "../browser/browser";
+
+export function getHotkeyToPress(hotkey, altIsOptional = false) {
+ let result = hotkey.split("+");
+ if (isMacOS()) {
+ result = result.map((x) => x.replace("control", "command"));
+ }
+ if (!altIsOptional) {
+ result = isMacOS() ? ["control", ...result] : ["alt", ...result];
+ }
+ return result.join("+");
+}
+
+const ALPHANUM_KEYS = "abcdefghijklmnopqrstuvwxyz0123456789".split("");
+const NAV_KEYS = [
+ "arrowleft",
+ "arrowright",
+ "arrowup",
+ "arrowdown",
+ "pageup",
+ "pagedown",
+ "home",
+ "end",
+ "backspace",
+ "enter",
+ "escape",
+];
+const MODIFIERS = new Set(["control", "shift"]);
+const AUTHORIZED_KEYS = new Set([...ALPHANUM_KEYS, ...NAV_KEYS]);
+
+export const hotkeyService = {
+ dependencies: ["ui"],
+ start(env, { ui }) {
+ const registrations = new Map();
+ let nextToken = 0;
+ let overlaysVisible = false;
+
+ browser.addEventListener("keydown", onKeydown);
+ browser.addEventListener("keyup", removeHotkeyOverlays);
+ browser.addEventListener("blur", removeHotkeyOverlays);
+ browser.addEventListener("click", removeHotkeyOverlays);
+
+ /**
+ * Handler for keydown events.
+ * Verifies if the keyboard event can be dispatched or not.
+ * Rules sequence to forbid dispatching :
+ * - UI is blocked
+ * - the pressed key is not whitelisted
+ *
+ * @param {KeyboardEvent} event
+ */
+ function onKeydown(event) {
+ if (!event.key) {
+ // Chrome may trigger incomplete keydown events under certain circumstances.
+ // E.g. when using browser built-in autocomplete on an input.
+ // See https://stackoverflow.com/questions/59534586/google-chrome-fires-keydown-event-when-form-autocomplete
+ return;
+ }
+
+ const hotkey = getActiveHotkey(event);
+
+ // Do not dispatch if UI is blocked
+ if (ui.isBlocked) {
+ return;
+ }
+
+ // FIXME : this is a temporary hack. It replaces all [accesskey] attrs by [data-hotkey] on all elements.
+ const elementsWithoutDataHotkey = ui.getVisibleElements(
+ "[accesskey]:not([data-hotkey])"
+ );
+ for (const el of elementsWithoutDataHotkey) {
+ el.dataset.hotkey = el.accessKey;
+ el.removeAttribute("accesskey");
+ }
+
+ // Special case: open hotkey overlays
+ if (isMacOS() ? hotkey === "control" : hotkey === "alt") {
+ addHotkeyOverlays();
+ event.preventDefault();
+ return;
+ }
+
+ // Is the pressed key NOT whitelisted ?
+ const singleKey = hotkey.split("+").pop();
+ if (!AUTHORIZED_KEYS.has(singleKey)) {
+ return;
+ }
+
+ // Finally, prepare and dispatch.
+ const infos = {
+ hotkey,
+ _originalEvent: event,
+ };
+ dispatch(infos);
+ removeHotkeyOverlays();
+ }
+
+ /**
+ * Dispatches an hotkey to all matching registrations and
+ * clicks on all elements having a data-hotkey attribute matching the hotkey.
+ *
+ * @param {{
+ * hotkey: string,
+ * _originalEvent: KeyboardEvent
+ * }} infos
+ */
+ function dispatch(infos) {
+ let dispatched = false;
+ const { hotkey, _originalEvent: event } = infos;
+ const isAlted = isMacOS() ? event.ctrlKey : event.altKey;
+ const activeElement = ui.activeElement;
+
+ // Dispatch actual hotkey to all matching registrations
+ for (const [_, reg] of registrations) {
+ if (!reg.global && reg.activeElement !== activeElement) {
+ continue;
+ }
+
+ if (reg.hotkey !== hotkey) {
+ continue;
+ }
+
+ if (!reg.altIsOptional && !isAlted) {
+ continue;
+ }
+
+ if (!reg.allowRepeat && event.repeat) {
+ continue;
+ }
+
+ reg.callback();
+ dispatched = true;
+ }
+
+ if (!event.repeat && isAlted) {
+ // Click on all elements having a data-hotkey attribute matching the actual hotkey.
+ const elems = activeElement.querySelectorAll(`[data-hotkey='${hotkey}' i]`);
+ for (const el of elems) {
+ // AAB: not sure it is enough, we might need to trigger all events that occur when you actually click
+ el.focus();
+ el.click();
+ dispatched = true;
+ }
+ }
+
+ // Prevent default on event if it has been handheld.
+ if (dispatched) {
+ event.preventDefault();
+ }
+ }
+
+ /**
+ * Add the hotkey overlays respecting the ui active element.
+ */
+ function addHotkeyOverlays() {
+ if (overlaysVisible) {
+ return;
+ }
+ for (const el of env.services.ui.getVisibleElements("[data-hotkey]:not(:disabled)")) {
+ const hotkey = el.dataset.hotkey;
+ const overlay = document.createElement("div");
+ overlay.className = "o_web_hotkey_overlay";
+ overlay.appendChild(document.createTextNode(hotkey.toUpperCase()));
+
+ let overlayParent;
+ if (el.tagName.toUpperCase() === "INPUT") {
+ // special case for the search input that has an access key
+ // defined. We cannot set the overlay on the input itself,
+ // only on its parent.
+ overlayParent = el.parentElement;
+ } else {
+ overlayParent = el;
+ }
+
+ if (overlayParent.style.position !== "absolute") {
+ overlayParent.style.position = "relative";
+ }
+ overlayParent.appendChild(overlay);
+ }
+ overlaysVisible = true;
+ }
+
+ /**
+ * Remove all the hotkey overlays.
+ */
+ function removeHotkeyOverlays() {
+ if (!overlaysVisible) {
+ return;
+ }
+ for (const overlay of document.querySelectorAll(".o_web_hotkey_overlay")) {
+ overlay.remove();
+ }
+ overlaysVisible = false;
+ }
+
+ /**
+ * Get the actual hotkey being pressed.
+ *
+ * @param {KeyboardEvent} ev
+ * @returns {string} the active hotkey, in lowercase
+ */
+ function getActiveHotkey(ev) {
+ const hotkey = [];
+
+ // ------- Modifiers -------
+ // Modifiers are pushed in ascending order to the hotkey.
+ if (isMacOS() ? ev.metaKey : ev.ctrlKey) {
+ hotkey.push("control");
+ }
+ if (ev.shiftKey) {
+ hotkey.push("shift");
+ }
+
+ // ------- Key -------
+ let key = ev.key.toLowerCase();
+ // Identify if the user has tapped on the number keys above the text keys.
+ if (ev.code && ev.code.indexOf("Digit") === 0) {
+ key = ev.code.slice(-1);
+ }
+ // Make sure we do not duplicate a modifier key
+ if (!hotkey.includes(key)) {
+ hotkey.push(key);
+ }
+
+ return hotkey.join("+");
+ }
+
+ /**
+ * Registers a new hotkey.
+ *
+ * @param {string} hotkey
+ * @param {()=>void} callback
+ * @param {Object} options additional options
+ * @param {boolean} [options.altIsOptional=false]
+ * allow registration to perform even without pressing the ALT key
+ * @param {boolean} [options.allowRepeat=false]
+ * allow registration to perform multiple times when hotkey is held down
+ * @param {boolean} [options.global=false]
+ * allow registration to perform no matter the UI active element
+ * @returns {number} registration token
+ */
+ function registerHotkey(hotkey, callback, options = {}) {
+ // Validate some informations
+ if (!hotkey || hotkey.length === 0) {
+ throw new Error("You must specify an hotkey when registering a registration.");
+ }
+
+ if (!callback || typeof callback !== "function") {
+ throw new Error(
+ "You must specify a callback function when registering a registration."
+ );
+ }
+
+ /**
+ * An hotkey must comply to these rules:
+ * - all parts are whitelisted
+ * - single key part comes last
+ * - each part is separated by the dash character: "+"
+ */
+ const keys = hotkey
+ .toLowerCase()
+ .split("+")
+ .filter((k) => !MODIFIERS.has(k));
+ if (keys.some((k) => !AUTHORIZED_KEYS.has(k))) {
+ throw new Error(
+ `You are trying to subscribe for an hotkey ('${hotkey}')
+ that contains parts not whitelisted: ${keys.join(", ")}`
+ );
+ } else if (keys.length > 1) {
+ throw new Error(
+ `You are trying to subscribe for an hotkey ('${hotkey}')
+ that contains more than one single key part: ${keys.join("+")}`
+ );
+ }
+
+ // Add registration
+ const token = nextToken++;
+ const registration = {
+ hotkey: hotkey.toLowerCase(),
+ callback,
+ activeElement: null,
+ altIsOptional: options && options.altIsOptional,
+ allowRepeat: options && options.allowRepeat,
+ global: options && options.global,
+ };
+ registrations.set(token, registration);
+
+ // Due to the way elements are mounted in the DOM by Owl (bottom-to-top),
+ // we need to wait the next micro task tick to set the context owner of the registration.
+ Promise.resolve().then(() => {
+ registration.activeElement = ui.activeElement;
+ });
+
+ return token;
+ }
+
+ /**
+ * Unsubscribes the token corresponding registration.
+ *
+ * @param {number} token
+ */
+ function unregisterHotkey(token) {
+ registrations.delete(token);
+ }
+
+ return {
+ /**
+ * @param {string} hotkey
+ * @param {() => void} callback
+ * @param {Object} options
+ * @param {boolean} [options.altIsOptional=false]
+ * @param {boolean} [options.allowRepeat=false]
+ * @param {boolean} [options.global=false]
+ * @returns {() => void}
+ */
+ add(hotkey, callback, options = {}) {
+ const token = registerHotkey(hotkey, callback, options);
+ return () => {
+ unregisterHotkey(token);
+ };
+ },
+ };
+ },
+};
+
+registry.category("services").add("hotkey", hotkeyService);
diff --git a/addons/web/static/src/core/l10n/currency.js b/addons/web/static/src/core/l10n/currency.js
new file mode 100644
index 00000000000..4fc3844493d
--- /dev/null
+++ b/addons/web/static/src/core/l10n/currency.js
@@ -0,0 +1,72 @@
+/** @odoo-module **/
+
+import { formatFloat, humanNumber, parseFloat, InvalidNumberError } from "./numbers";
+
+/**
+ * Formats a value as a currency.
+ *
+ * @param {number|false} value currency value number
+ * @param {string} cid currency id
+ * @param {Object} [options={}] formatting options
+ * @param {boolean} [options.noSymbol] this currency has not a sympbol
+ * @param {boolean} [options.humanReadable] this currency needs to be human readable
+ * @param {[number, number]} [options.digits]
+ * the number of digits that should be used, instead of the default digits precision in the field.
+ * Note: if the currency defines a precision, the currency's one is used.
+ * The first number is always ignored (legacy constraint)
+ * @returns The formatted currency
+ */
+export function formatCurrency(value, cid, options = {}) {
+ if (value === false) {
+ return "";
+ }
+ const currency = odoo.session_info.currencies[cid];
+ const { noSymbol } = options || {};
+ const digits = (currency && currency.digits) || options.digits;
+
+ const formatted = options.humanReadable
+ ? humanNumber(value)
+ : formatFloat(value, { precision: digits && digits[1] });
+ if (!currency || noSymbol) {
+ return formatted;
+ }
+ if (currency.position === "after") {
+ return `${formatted} ${currency.symbol}`;
+ } else {
+ return `${currency.symbol} ${formatted}`;
+ }
+}
+
+/**
+ * Try to extract a monetary value from a string. The localization is considered in the process.
+ * The monetary value can have the formats sym$ float, float$ sym or float
+ * where $ is a non breaking space and sym is a currency symbol.
+ * If a symbol is found it must correspond to the default currency symbol or to the
+ * symbol of the currency whose id is passed in options.
+ *
+ * @param {string} value
+ * @param {Object} [options={}]
+ * @param {number} [options.currencyId]
+ * @returns {number} float
+ */
+export function parseCurrency(value, options = {}) {
+ let values = value.split(" ");
+ if (values.length === 1) {
+ return parseFloat(value);
+ }
+ let currency;
+ if (options.currencyId) {
+ currency = odoo.session_info.currencies[options.currencyId];
+ } else {
+ currency = Object.values(odoo.session_info.currencies)[0];
+ }
+ const symbolIndex = values.findIndex((v) => v === currency.symbol);
+ if (symbolIndex === -1) {
+ throw new InvalidNumberError(`"${value}" is not a correct number`);
+ }
+ values.splice(symbolIndex, 1);
+ if (values.length !== 1) {
+ throw new InvalidNumberError(`"${value}" is not a correct number`);
+ }
+ return parseFloat(values[0]);
+}
diff --git a/addons/web/static/src/core/l10n/dates.js b/addons/web/static/src/core/l10n/dates.js
new file mode 100644
index 00000000000..c7441b673a5
--- /dev/null
+++ b/addons/web/static/src/core/l10n/dates.js
@@ -0,0 +1,284 @@
+/** @odoo-module **/
+
+import { memoize } from "../utils/functions";
+import { sprintf } from "../utils/strings";
+import { localization } from "./localization";
+import { _lt } from "./translation";
+
+const { DateTime } = luxon;
+
+/**
+ * Change the method toJSON to return the formated value to send server side.
+ */
+DateTime.prototype.toJSON = function () {
+ return this.toFormat("yyyy-MM-dd HH:mm:ss");
+};
+
+// -----------------------------------------------------------------------------
+// Helpers
+// -----------------------------------------------------------------------------
+
+const alphaRegex = /[a-zA-Z]/g;
+const nonAlphaRegex = /[^a-zA-Z]/g;
+const nonDigitsRegex = /[^0-9]/g;
+
+const normalizeFormatTable = {
+ // Python strftime to luxon.js conversion table
+ // See odoo/addons/base/views/res_lang_views.xml
+ // for details about supported directives
+ a: "ccc",
+ A: "cccc",
+ b: "MMM",
+ B: "MMMM",
+ d: "dd",
+ H: "HH",
+ I: "hh",
+ j: "o",
+ m: "MM",
+ M: "mm",
+ p: "a",
+ S: "ss",
+ W: "WW",
+ w: "c",
+ y: "yy",
+ Y: "yyyy",
+ c: "ccc MMM d HH:mm:ss yyyy",
+ x: "MM/dd/yy",
+ X: "HH:mm:ss",
+};
+
+const smartDateUnits = {
+ d: "days",
+ m: "months",
+ w: "weeks",
+ y: "years",
+};
+const smartDateRegex = new RegExp(`^([+-])(\\d+)([${Object.keys(smartDateUnits).join("")}]?)$`);
+
+/**
+ * Smart date inputs are shortcuts to write dates quicker.
+ * These shortcuts should respect the format ^[+-]\d+[dmwy]?$
+ *
+ * e.g.
+ * "+1d" or "+1" will return now + 1 day
+ * "-2w" will return now - 2 weeks
+ * "+3m" will return now + 3 months
+ * "-4y" will return now + 4 years
+ *
+ * @param {string} value
+ * @returns {DateTime|false} Luxon datetime object (in the UTC timezone)
+ */
+function parseSmartDateInput(value) {
+ const match = smartDateRegex.exec(value);
+ if (match) {
+ let date = DateTime.utc();
+ const offset = parseInt(match[2], 10);
+ const unit = smartDateUnits[match[3] || "d"];
+ if (match[1] === "+") {
+ date = date.plus({ [unit]: offset });
+ } else {
+ date = date.minus({ [unit]: offset });
+ }
+ return date;
+ }
+ return false;
+}
+
+/**
+ * Enforces some restrictions to a Luxon DateTime object.
+ * Returns it if within those restrictions.
+ * Returns false otherwise.
+ *
+ * @param {DateTime | false} date
+ * @returns {DateTime | false}
+ */
+function constrain(dt) {
+ let valid = dt !== false;
+ valid = valid && dt.isValid;
+ valid = valid && dt.year >= 1000;
+ valid = valid && dt.year < 10000;
+ return valid ? dt : false;
+}
+
+/**
+ * Removes any duplicated alphabetic characters in a given string.
+ * Example: "aa-bb-CCcc-ddD xxxx-Yy-ZZ" -> "a-b-Cc-dD x-Yy-Z"
+ *
+ * @param {string} str
+ * @returns {string}
+ */
+const stripAlphaDupes = memoize(function stripAlphaDupes(str) {
+ return str.replace(alphaRegex, (letter, index, str) => {
+ return letter === str[index - 1] ? "" : letter;
+ });
+});
+
+/**
+ * Convert Python strftime to escaped luxon.js format.
+ *
+ * @param {string} value original format
+ * @returns {string} valid Luxon format
+ */
+export const strftimeToLuxonFormat = memoize(function strftimeToLuxonFormat(value) {
+ const output = [];
+ let inToken = false;
+ for (let index = 0; index < value.length; ++index) {
+ let character = value[index];
+ if (character === "%" && !inToken) {
+ inToken = true;
+ continue;
+ }
+ if (character.match(alphaRegex)) {
+ if (inToken && normalizeFormatTable[character] !== undefined) {
+ character = normalizeFormatTable[character];
+ } else {
+ character = "[" + character + "]"; // moment.js escape
+ }
+ }
+ output.push(character);
+ inToken = false;
+ }
+ return output.join("");
+});
+
+// -----------------------------------------------------------------------------
+// Formatting
+// -----------------------------------------------------------------------------
+
+/**
+ * Format a DateTime object
+ *
+ * @param {DateTime | false} value
+ * @param {Object} options
+ * @param {string} [options.format]
+ * Provided format used to format the input DateTime object.
+ *
+ * Default=the session localization format.
+ *
+ * @param {boolean} [options.timezone]
+ * - True = input will be set in local time before being formatted.
+ * - False = input will be set in UTC time before being formatted.
+ *
+ * Default=false.
+ *
+ * @returns {string}
+ */
+export function formatDateTime(value, options = {}) {
+ if (value === false) {
+ return "";
+ }
+ const format = options.format || localization.dateTimeFormat;
+ const zone = options.timezone ? "local" : "utc";
+ value = value.setZone(zone, { keepLocaltime: options.timezone });
+ return value.toFormat(format);
+}
+
+// -----------------------------------------------------------------------------
+// Parsing
+// -----------------------------------------------------------------------------
+
+/**
+ * Parses a string value to an UTC Luxon DateTime object.
+ *
+ * @param {string} value value to parse.
+ * - Value can take the form of a smart date:
+ * e.g. "+3w" for three weeks from now.
+ * (`options.format` and `options.timezone` are ignored in this case)
+ *
+ * - If value cannot be parsed within the provided format,
+ * ISO8601 and SQL formats are then tried.
+ *
+ * @param {object} options
+ * @param {string} [options.format]
+ * Provided format used to parse the input value.
+ * Default=the session localization format
+ * @returns {DateTime|false} Luxon DateTime object (in the UTC timezone)
+ */
+export function parseDate(value, options = {}) {
+ return parseDateTime(value, { dateOnly: true, format: options.format });
+}
+
+/**
+ * Parses a string value to an UTC Luxon DateTime object.
+ *
+ * @param {string} value value to parse.
+ * - Value can take the form of a smart date:
+ * e.g. "+3w" for three weeks from now.
+ * (`options.format` and `options.timezone` are ignored in this case)
+ *
+ * - If value cannot be parsed within the provided format,
+ * ISO8601 and SQL formats are then tried.
+ *
+ * @param {object} options
+ * @param {boolean} [options.dateOnly]
+ * The output date will represent the start of day (time is truncated).
+ *
+ * Default=false.
+ *
+ * @param {string} [options.format]
+ * Provided format used to parse the input value.
+ *
+ * Default=the session localization format
+ *
+ * @param {boolean} [options.timezone]
+ * - True = input value is considered being in localtime.
+ * - False = input value is considered being in utc time.
+ *
+ * NB: ISO strings containing timezone information
+ * will have priority over this option.
+ *
+ * Default=false.
+ *
+ * @returns {DateTime|false} Luxon DateTime object (in the UTC timezone)
+ */
+export function parseDateTime(value, options = {}) {
+ if (!value) {
+ // BOI: is {DateTime|false} really what we want ?
+ // I think we should return a DateTime.invalid when falsy.
+ return false;
+ }
+
+ const valueDigitsOnly = value.replace(nonDigitsRegex, "");
+ const parseOpts = {
+ setZone: true,
+ zone: options.timezone ? "local" : "utc",
+ };
+
+ let result = constrain(parseSmartDateInput(value));
+
+ if (!result) {
+ const fmt = options.format || localization.dateTimeFormat;
+ const fmtWoZero = stripAlphaDupes(fmt);
+
+ // Luxon is not permissive regarding delimiting characters in the format.
+ // So if the value to parse has less characters than the format, we would
+ // try to parse without the delimiting characters.
+ const woSeps = {
+ val: valueDigitsOnly,
+ fmt: fmt.replace(nonAlphaRegex, "").slice(0, valueDigitsOnly.length),
+ };
+
+ result =
+ constrain(DateTime.fromFormat(value, fmt, parseOpts)) ||
+ constrain(DateTime.fromFormat(value, fmtWoZero, parseOpts)) ||
+ constrain(DateTime.fromFormat(woSeps.val, woSeps.fmt, parseOpts));
+ }
+
+ if (!result) {
+ if (valueDigitsOnly.length > 4) {
+ // Also try some fallback formats, but only if value counts more than
+ // four digit characters as this could get misinterpreted as the time of
+ // the actual date.
+ result =
+ constrain(DateTime.fromISO(value, parseOpts)) || // ISO8601
+ constrain(DateTime.fromSQL(value, parseOpts)); // last try: SQL
+ }
+ }
+
+ if (!result) {
+ throw new Error(sprintf(_lt("'%s' is not a correct date or datetime").toString(), value));
+ }
+
+ result = result.toUTC();
+ return options.dateOnly ? result.startOf("day") : result;
+}
diff --git a/addons/web/static/src/core/l10n/localization.js b/addons/web/static/src/core/l10n/localization.js
new file mode 100644
index 00000000000..0c13a344b58
--- /dev/null
+++ b/addons/web/static/src/core/l10n/localization.js
@@ -0,0 +1,20 @@
+/** @odoo-module **/
+
+/**
+ * @type {any}
+ */
+const notReadyError = new Error(
+ "Localization parameters not ready yet. Maybe add 'localization' to your dependencies?"
+);
+
+export const localization = {
+ dateFormat: notReadyError,
+ dateTimeFormat: notReadyError,
+ timeFormat: notReadyError,
+ decimalPoint: notReadyError,
+ direction: notReadyError,
+ grouping: notReadyError,
+ multiLang: notReadyError,
+ thousandsSep: notReadyError,
+ weekStart: notReadyError,
+};
diff --git a/addons/web/static/src/core/l10n/localization_service.js b/addons/web/static/src/core/l10n/localization_service.js
new file mode 100644
index 00000000000..57193e37ccb
--- /dev/null
+++ b/addons/web/static/src/core/l10n/localization_service.js
@@ -0,0 +1,60 @@
+/** @odoo-module **/
+
+import { browser } from "../browser/browser";
+import { registry } from "../registry";
+import { strftimeToLuxonFormat } from "./dates";
+import { localization } from "./localization";
+import { translatedTerms } from "./translation";
+
+export const localizationService = {
+ dependencies: ["user"],
+ start: async (env, { user }) => {
+ const cacheHashes = odoo.session_info.cache_hashes;
+ const translationsHash = cacheHashes.translations || new Date().getTime().toString();
+ const lang = user.lang || null;
+ let url = `/web/webclient/translations/${translationsHash}`;
+ if (lang) {
+ url += `?lang=${lang}`;
+ }
+
+ const response = await browser.fetch(url);
+ if (!response.ok) {
+ throw new Error("Error while fetching translations");
+ }
+ const { lang_parameters: userLocalization, modules: modules } = await response.json();
+
+ // FIXME We flatten the result of the python route.
+ // Eventually, we want a new python route to return directly the good result.
+ let terms = {};
+ for (const addon of Object.keys(modules)) {
+ for (const message of modules[addon].messages) {
+ terms[message.id] = message.string;
+ }
+ }
+
+ Object.setPrototypeOf(translatedTerms, terms);
+ function _t(str) {
+ return terms[str] || str;
+ }
+ env._t = _t;
+ env.qweb.translateFn = _t;
+ const dateFormat = strftimeToLuxonFormat(userLocalization.date_format);
+ const timeFormat = strftimeToLuxonFormat(userLocalization.time_format);
+ const dateTimeFormat = `${dateFormat} ${timeFormat}`;
+ const grouping = JSON.parse(userLocalization.grouping);
+
+ Object.assign(localization, {
+ dateFormat,
+ timeFormat,
+ dateTimeFormat,
+ decimalPoint: userLocalization.decimal_point,
+ direction: userLocalization.direction,
+ grouping,
+ multiLang: userLocalization.multi_lang,
+ thousandsSep: userLocalization.thousands_sep,
+ weekStart: userLocalization.week_start,
+ });
+ },
+};
+
+registry.category("services").add("localization", localizationService);
diff --git a/addons/web/static/src/core/l10n/numbers.js b/addons/web/static/src/core/l10n/numbers.js
new file mode 100644
index 00000000000..c2f024f8ec8
--- /dev/null
+++ b/addons/web/static/src/core/l10n/numbers.js
@@ -0,0 +1,202 @@
+/** @odoo-module **/
+
+import { escapeRegExp, intersperse } from "../utils/strings";
+import { localization } from "./localization";
+import { _lt } from "./translation";
+
+export class InvalidNumberError extends Error {}
+
+// -----------------------------------------------------------------------------
+// Helpers
+// -----------------------------------------------------------------------------
+
+/**
+ * Inserts "thousands" separators in the provided number.
+ *
+ * @param {number} [num] integer number
+ * @param {string} [thousandsSep=","] the separator to insert
+ * @param {number[]} [grouping=[3,0]]
+ * array of relative offsets at which to insert `thousandsSep`.
+ * See `strings.intersperse` method.
+ * @returns {string}
+ */
+function insertThousandsSep(num, thousandsSep = ",", grouping = [3, 0]) {
+ let numStr = `${num}`;
+ const negative = numStr[0] === "-";
+ numStr = negative ? numStr.slice(1) : numStr;
+ return (negative ? "-" : "") + intersperse(numStr, grouping, thousandsSep);
+}
+
+/**
+ * Parses a string into a number.
+ *
+ * @param {string} value
+ * @param {Object} options - additional options
+ * @param {string|RegExp} [options.thousandsSep] - the thousands separator used in the value
+ * @param {string|RegExp} [options.decimalPoint] - the decimal point used in the value
+ * @returns {number}
+ */
+function parseNumber(value, options = {}) {
+ // a number can have the thousand separator multiple times. ex: 1,000,000.00
+ value = value.replaceAll(options.thousandsSep || ",", "");
+ // a number only have one decimal separator
+ value = value.replace(options.decimalPoint || ".", ".");
+ return Number(value);
+}
+
+// -----------------------------------------------------------------------------
+// Exports
+// -----------------------------------------------------------------------------
+
+/**
+ * Formats a number into a more readable string representing a float.
+ *
+ * @param {number|false} value
+ * @param {Object} options additional options
+ * @param {number} [options.precision=2] number of digits to keep after decimal point
+ * @param {string} [options.decimalPoint="."] decimal separating character
+ * @param {string} [options.thousandsSep=""] thousands separator to insert
+ * @param {number[]} [options.grouping]
+ * array of relative offsets at which to insert `thousandsSep`.
+ * See `numbers.insertThousandsSep` method.
+ * @returns {string}
+ */
+export function formatFloat(value, options = {}) {
+ if (value === false) {
+ return "";
+ }
+ const grouping = options.grouping || localization.grouping;
+ const thousandsSep = options.thousandsSep || localization.thousandsSep;
+ const decimalPoint = options.decimalPoint || localization.decimalPoint;
+ const formatted = value.toFixed(options.precision || 2).split(".");
+ formatted[0] = insertThousandsSep(+formatted[0], thousandsSep, grouping);
+ return formatted.join(decimalPoint);
+}
+
+/**
+ * Try to extract a float from a string. The localization is considered in the process.
+ *
+ * @param {string} value
+ * @returns {number} a float
+ */
+export function parseFloat(value) {
+ let thousandsSepRegex = new RegExp(escapeRegExp(localization.thousandsSep), "g");
+ let decimalPointRegex = new RegExp(escapeRegExp(localization.decimalPoint), "g");
+ const parsed = parseNumber(value, {
+ thousandsSep: thousandsSepRegex,
+ decimalPoint: decimalPointRegex,
+ });
+ if (isNaN(parsed)) {
+ throw new InvalidNumberError(`"${value}" is not a correct number`);
+ }
+ return parsed;
+}
+
+/**
+ * Try to extract a float time from a string. The localization is considered in the process.
+ * The float time can have two formats: float or integer:integer.
+ *
+ * @param {string} value
+ * @returns {number} a float
+ */
+export function parseFloatTime(value) {
+ let sign = 1;
+ if (value[0] === "-") {
+ value = value.slice(1);
+ sign = -1;
+ }
+ const values = value.split(":");
+ if (values.length > 2) {
+ throw new InvalidNumberError(`"${value}" is not a correct number`);
+ }
+ if (values.length === 1) {
+ return sign * parseFloat(value);
+ }
+ const hours = parseInteger(values[0]);
+ const minutes = parseInteger(values[1]);
+ return sign * (hours + minutes / 60);
+}
+
+/**
+ * Try to extract an integer from a string. The localization is considered in the process.
+ *
+ * @param {string} value
+ * @returns {number} an integer
+ */
+export function parseInteger(value) {
+ let thousandsSepRegex = new RegExp(escapeRegExp(localization.thousandsSep), "g");
+ let decimalPointRegex = new RegExp(escapeRegExp(localization.decimalPoint), "g");
+ const parsed = parseNumber(value, {
+ thousandsSep: thousandsSepRegex,
+ decimalPoint: decimalPointRegex,
+ });
+ if (!Number.isInteger(parsed)) {
+ throw new InvalidNumberError(`"${value}" is not a correct number`);
+ }
+ return parsed;
+}
+
+/**
+ * Try to extract a float from a string and unconvert it with a conversion factor of 100.
+ * The localization is considered in the process.
+ * The percentage can have two formats: float or float%.
+ *
+ * @param {string} value
+ * @returns {number} float
+ */
+export function parsePercentage(value) {
+ if (value[value.length - 1] === "%") {
+ value = value.slice(0, value.length - 1);
+ }
+ return parseFloat(value) / 100;
+}
+
+/**
+ * Format a number to a human readable format.
+ * By example, 3000 could become 3k. Or massive number can use the scientific exponential notation.
+ *
+ * @param {number} number to format
+ * @param {Object} [options] Options to format
+ * @param {number} [options.decimals=0] maximum number of decimals to use
+ * @param {number} [options.minDigits=1]
+ * the minimum number of digits to preserve when switching to another
+ * level of thousands (e.g. with a value of '2', 4321 will still be
+ * represented as 4321 otherwise it will be down to one digit (4k))
+ * @returns {string}
+ */
+export function humanNumber(number, options = { decimals: 0, minDigits: 1 }) {
+ number = Math.round(number);
+ const decimals = options.decimals || 0;
+ const minDigits = options.minDigits || 1;
+ const d2 = Math.pow(10, decimals);
+ const numberMagnitude = +number.toExponential().split("e+")[1];
+ // the case numberMagnitude >= 21 corresponds to a number
+ // better expressed in the scientific format.
+ if (numberMagnitude >= 21) {
+ // we do not use number.toExponential(decimals) because we want to
+ // avoid the possible useless O decimals: 1e.+24 preferred to 1.0e+24
+ number = Math.round(number * Math.pow(10, decimals - numberMagnitude)) / d2;
+ return `${number}e+${numberMagnitude}`;
+ }
+ // note: we need to call toString here to make sure we manipulate the resulting
+ // string, not an object with a toString method.
+ const unitSymbols = _lt("kMGTPE").toString();
+ const sign = Math.sign(number);
+ number = Math.abs(number);
+ let symbol = "";
+ for (let i = unitSymbols.length; i > 0; i--) {
+ const s = Math.pow(10, i * 3);
+ if (s <= number / Math.pow(10, minDigits - 1)) {
+ number = Math.round((number * d2) / s) / d2;
+ symbol = unitSymbols[i - 1];
+ break;
+ }
+ }
+ const { decimalPoint, grouping, thousandsSep } = localization;
+ const [integerPart, decimalPart] = String(number).split(".");
+ const int = insertThousandsSep(sign * Number(integerPart), thousandsSep, grouping);
+ if (!decimalPart) {
+ return int + symbol;
+ }
+ return int + decimalPoint + decimalPart + symbol;
+}
diff --git a/addons/web/static/src/core/l10n/translation.js b/addons/web/static/src/core/l10n/translation.js
new file mode 100644
index 00000000000..354e2cf0ea0
--- /dev/null
+++ b/addons/web/static/src/core/l10n/translation.js
@@ -0,0 +1,35 @@
+/** @odoo-module **/
+
+export const translatedTerms = {};
+
+/**
+ * Lazy translation function, only performs the translation when actually
+ * printed (e.g. inserted into a template).
+ * Useful when defining translatable strings in code evaluated before the
+ * translations are loaded, as class attributes or at the top-level of
+ * an Odoo Web module
+ *
+ * @returns {{toString: () => string}}
+ */
+export function _lt(str) {
+ return { toString: () => translatedTerms[str] || str };
+}
+
+/*
+ * Setup jQuery timeago:
+ * Strings in timeago are "composed" with prefixes, words and suffixes. This
+ * makes their detection by our translating system impossible. Use all literal
+ * strings we're using with a translation mark here so the extractor can do its
+ * job.
+ */
+_lt("less than a minute ago");
+_lt("about a minute ago");
+_lt("%d minutes ago");
+_lt("about an hour ago");
+_lt("%d hours ago");
+_lt("a day ago");
+_lt("%d days ago");
+_lt("about a month ago");
+_lt("%d months ago");
+_lt("about a year ago");
+_lt("%d years ago");
diff --git a/addons/web/static/src/core/network/download.js b/addons/web/static/src/core/network/download.js
new file mode 100644
index 00000000000..058ec88ff78
--- /dev/null
+++ b/addons/web/static/src/core/network/download.js
@@ -0,0 +1,525 @@
+/** @odoo-module **/
+
+import { NetworkErrorDialog, ServerErrorDialog } from "../errors/error_dialogs";
+import { _lt } from "../l10n/translation";
+
+// -----------------------------------------------------------------------------
+// Content Disposition Library
+// -----------------------------------------------------------------------------
+
+/*
+(The MIT License)
+Copyright (c) 2014-2017 Douglas Christopher Wilson
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of this software and associated documentation files (the
+'Software'), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, sublicense, and/or sell copies of the Software, and to
+permit persons to whom the Software is furnished to do so, subject to
+the following conditions:
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+/**
+ * Stripped down to only parsing/decoding.
+ * Slightly changed for export and lint compliance
+ */
+
+/**
+ * RegExp to match percent encoding escape.
+ * @private
+ */
+const HEX_ESCAPE_REPLACE_REGEXP = /%([0-9A-Fa-f]{2})/g;
+
+/**
+ * RegExp to match non-latin1 characters.
+ * @private
+ */
+const NON_LATIN1_REGEXP = /[^\x20-\x7e\xa0-\xff]/g;
+
+/**
+ * RegExp to match quoted-pair in RFC 2616
+ *
+ * quoted-pair = "\" CHAR
+ * CHAR =
+ * @private
+ */
+const QESC_REGEXP = /\\([\u0000-\u007f])/g;
+
+/**
+ * RegExp for various RFC 2616 grammar
+ *
+ * parameter = token "=" ( token | quoted-string )
+ * token = 1*
+ * separators = "(" | ")" | "<" | ">" | "@"
+ * | "," | ";" | ":" | "\" | <">
+ * | "/" | "[" | "]" | "?" | "="
+ * | "{" | "}" | SP | HT
+ * quoted-string = ( <"> *(qdtext | quoted-pair ) <"> )
+ * qdtext = >
+ * quoted-pair = "\" CHAR
+ * CHAR =
+ * TEXT =
+ * LWS = [CRLF] 1*( SP | HT )
+ * CRLF = CR LF
+ * CR =
+ * LF =
+ * SP =
+ * HT =
+ * CTL =
+ * OCTET =
+ * @private
+ */
+const PARAM_REGEXP = /;[\x09\x20]*([!#$%&'*+.0-9A-Z^_`a-z|~-]+)[\x09\x20]*=[\x09\x20]*("(?:[\x20!\x23-\x5b\x5d-\x7e\x80-\xff]|\\[\x20-\x7e])*"|[!#$%&'*+.0-9A-Z^_`a-z|~-]+)[\x09\x20]*/g;
+
+/**
+ * RegExp for various RFC 5987 grammar
+ *
+ * ext-value = charset "'" [ language ] "'" value-chars
+ * charset = "UTF-8" / "ISO-8859-1" / mime-charset
+ * mime-charset = 1*mime-charsetc
+ * mime-charsetc = ALPHA / DIGIT
+ * / "!" / "#" / "$" / "%" / "&"
+ * / "+" / "-" / "^" / "_" / "`"
+ * / "{" / "}" / "~"
+ * language = ( 2*3ALPHA [ extlang ] )
+ * / 4ALPHA
+ * / 5*8ALPHA
+ * extlang = *3( "-" 3ALPHA )
+ * value-chars = *( pct-encoded / attr-char )
+ * pct-encoded = "%" HEXDIG HEXDIG
+ * attr-char = ALPHA / DIGIT
+ * / "!" / "#" / "$" / "&" / "+" / "-" / "."
+ * / "^" / "_" / "`" / "|" / "~"
+ * @private
+ */
+const EXT_VALUE_REGEXP = /^([A-Za-z0-9!#$%&+\-^_`{}~]+)'(?:[A-Za-z]{2,3}(?:-[A-Za-z]{3}){0,3}|[A-Za-z]{4,8}|)'((?:%[0-9A-Fa-f]{2}|[A-Za-z0-9!#$&+.^_`|~-])+)$/;
+
+/**
+ * RegExp for various RFC 6266 grammar
+ *
+ * disposition-type = "inline" | "attachment" | disp-ext-type
+ * disp-ext-type = token
+ * disposition-parm = filename-parm | disp-ext-parm
+ * filename-parm = "filename" "=" value
+ * | "filename*" "=" ext-value
+ * disp-ext-parm = token "=" value
+ * | ext-token "=" ext-value
+ * ext-token =
+ * @private
+ */
+const DISPOSITION_TYPE_REGEXP = /^([!#$%&'*+.0-9A-Z^_`a-z|~-]+)[\x09\x20]*(?:$|;)/;
+
+/**
+ * Decode a RFC 6987 field value (gracefully).
+ *
+ * @param {string} str
+ * @return {string}
+ * @private
+ */
+function decodefield(str) {
+ const match = EXT_VALUE_REGEXP.exec(str);
+
+ if (!match) {
+ throw new TypeError("invalid extended field value");
+ }
+
+ const charset = match[1].toLowerCase();
+ const encoded = match[2];
+
+ switch (charset) {
+ case "iso-8859-1":
+ return encoded
+ .replace(HEX_ESCAPE_REPLACE_REGEXP, pdecode)
+ .replace(NON_LATIN1_REGEXP, "?");
+ case "utf-8":
+ return decodeURIComponent(encoded);
+ default:
+ throw new TypeError("unsupported charset in extended field");
+ }
+}
+
+/**
+ * Parse Content-Disposition header string.
+ *
+ * @param {string} string
+ * @return {ContentDisposition}
+ * @public
+ */
+function parse(string) {
+ if (!string || typeof string !== "string") {
+ throw new TypeError("argument string is required");
+ }
+
+ let match = DISPOSITION_TYPE_REGEXP.exec(string);
+
+ if (!match) {
+ throw new TypeError("invalid type format");
+ }
+
+ // normalize type
+ let index = match[0].length;
+ const type = match[1].toLowerCase();
+
+ let key;
+ const names = [];
+ const params = {};
+ let value;
+
+ // calculate index to start at
+ index = PARAM_REGEXP.lastIndex = match[0].substr(-1) === ";" ? index - 1 : index;
+
+ // match parameters
+ while ((match = PARAM_REGEXP.exec(string))) {
+ if (match.index !== index) {
+ throw new TypeError("invalid parameter format");
+ }
+
+ index += match[0].length;
+ key = match[1].toLowerCase();
+ value = match[2];
+
+ if (names.indexOf(key) !== -1) {
+ throw new TypeError("invalid duplicate parameter");
+ }
+
+ names.push(key);
+
+ if (key.indexOf("*") + 1 === key.length) {
+ // decode extended value
+ key = key.slice(0, -1);
+ value = decodefield(value);
+
+ // overwrite existing value
+ params[key] = value;
+ continue;
+ }
+
+ if (typeof params[key] === "string") {
+ continue;
+ }
+
+ if (value[0] === '"') {
+ // remove quotes and escapes
+ value = value.substr(1, value.length - 2).replace(QESC_REGEXP, "$1");
+ }
+
+ params[key] = value;
+ }
+
+ if (index !== -1 && index !== string.length) {
+ throw new TypeError("invalid parameter format");
+ }
+
+ return new ContentDisposition(type, params);
+}
+
+/**
+ * Percent decode a single character.
+ *
+ * @param {string} str
+ * @param {string} hex
+ * @return {string}
+ * @private
+ */
+function pdecode(str, hex) {
+ return String.fromCharCode(parseInt(hex, 16));
+}
+
+/**
+ * Class for parsed Content-Disposition header for v8 optimization
+ *
+ * @public
+ * @param {string} type
+ * @param {object} parameters
+ * @constructor
+ */
+function ContentDisposition(type, parameters) {
+ this.type = type;
+ this.parameters = parameters;
+}
+
+// -----------------------------------------------------------------------------
+// download.js library
+// -----------------------------------------------------------------------------
+
+/*
+MIT License
+Copyright (c) 2016 dandavis
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+ */
+
+/**
+ * download.js v4.2, by dandavis; 2008-2018. [MIT] see http://danml.com/download.html for tests/usage
+ * v1 landed a FF+Chrome compat way of downloading strings to local un-named files, upgraded to use a hidden frame and optional mime
+ * v2 added named files via a[download], msSaveBlob, IE (10+) support, and window.URL support for larger+faster saves than dataURLs
+ * v3 added dataURL and Blob Input, bind-toggle arity, and legacy dataURL fallback was improved with force-download mime and base64 support. 3.1 improved safari handling.
+ * v4 adds AMD/UMD, commonJS, and plain browser support
+ * v4.1 adds url download capability via solo URL argument (same domain/CORS only)
+ * v4.2 adds semantic variable names, long (over 2MB) dataURL support, and hidden by default temp anchors
+ *
+ * Slightly modified for export and lint compliance
+ *
+ * @param {Blob | File | String} data
+ * @param {String} [filename]
+ * @param {String} [mimetype]
+ */
+function _download(data, filename, mimetype) {
+ let self = window, // this script is only for browsers anyway...
+ defaultMime = "application/octet-stream", // this default mime also triggers iframe downloads
+ mimeType = mimetype || defaultMime,
+ payload = data,
+ url = !filename && !mimetype && payload,
+ anchor = document.createElement("a"),
+ toString = function (a) {
+ return String(a);
+ },
+ myBlob = self.Blob || self.MozBlob || self.WebKitBlob || toString,
+ fileName = filename || "download",
+ blob,
+ reader;
+ myBlob = myBlob.call ? myBlob.bind(self) : Blob;
+
+ if (String(this) === "true") {
+ //reverse arguments, allowing download.bind(true, "text/xml", "export.xml") to act as a callback
+ payload = [payload, mimeType];
+ mimeType = payload[0];
+ payload = payload[1];
+ }
+
+ if (url && url.length < 2048) {
+ // if no filename and no mime, assume a url was passed as the only argument
+ fileName = url.split("/").pop().split("?")[0];
+ anchor.href = url; // assign href prop to temp anchor
+ if (anchor.href.indexOf(url) !== -1) {
+ // if the browser determines that it's a potentially valid url path:
+ let ajax = new XMLHttpRequest();
+ ajax.open("GET", url, true);
+ ajax.responseType = "blob";
+ ajax.onload = function (e) {
+ _download(e.target.response, fileName, defaultMime);
+ };
+ setTimeout(() => {
+ ajax.send();
+ }, 0); // allows setting custom ajax headers using the return:
+ return ajax;
+ }
+ }
+
+ //go ahead and download dataURLs right away
+ if (/^data:[\w+\-]+\/[\w+\-]+[,;]/.test(payload)) {
+ if (payload.length > 1024 * 1024 * 1.999 && myBlob !== toString) {
+ payload = dataUrlToBlob(payload);
+ mimeType = payload.type || defaultMime;
+ } else {
+ return navigator.msSaveBlob // IE10 can't do a[download], only Blobs:
+ ? navigator.msSaveBlob(dataUrlToBlob(payload), fileName)
+ : saver(payload); // everyone else can save dataURLs un-processed
+ }
+ }
+
+ blob = payload instanceof myBlob ? payload : new myBlob([payload], { type: mimeType });
+
+ function dataUrlToBlob(strUrl) {
+ let parts = strUrl.split(/[:;,]/),
+ type = parts[1],
+ decoder = parts[2] === "base64" ? atob : decodeURIComponent,
+ binData = decoder(parts.pop()),
+ mx = binData.length,
+ i = 0,
+ uiArr = new Uint8Array(mx);
+
+ for (i; i < mx; ++i) {
+ uiArr[i] = binData.charCodeAt(i);
+ }
+
+ return new myBlob([uiArr], { type });
+ }
+
+ function saver(url, winMode) {
+ if ("download" in anchor) {
+ //html5 A[download]
+ anchor.href = url;
+ anchor.setAttribute("download", fileName);
+ anchor.className = "download-js-link";
+ anchor.innerText = _lt("downloading...");
+ anchor.style.display = "none";
+ document.body.appendChild(anchor);
+ setTimeout(() => {
+ anchor.click();
+ document.body.removeChild(anchor);
+ if (winMode === true) {
+ setTimeout(() => {
+ self.URL.revokeObjectURL(anchor.href);
+ }, 250);
+ }
+ }, 66);
+ return true;
+ }
+
+ // handle non-a[download] safari as best we can:
+ if (/(Version)\/(\d+)\.(\d+)(?:\.(\d+))?.*Safari\//.test(navigator.userAgent)) {
+ url = url.replace(/^data:([\w\/\-+]+)/, defaultMime);
+ if (!window.open(url)) {
+ // popup blocked, offer direct download:
+ if (
+ confirm(
+ "Displaying New Document\n\nUse Save As... to download, then click back to return to this page."
+ )
+ ) {
+ location.href = url;
+ }
+ }
+ return true;
+ }
+
+ //do iframe dataURL download (old ch+FF):
+ let f = document.createElement("iframe");
+ document.body.appendChild(f);
+
+ if (!winMode) {
+ // force a mime that will download:
+ url = `data:${url.replace(/^data:([\w\/\-+]+)/, defaultMime)}`;
+ }
+ f.src = url;
+ setTimeout(() => {
+ document.body.removeChild(f);
+ }, 333);
+ }
+
+ if (navigator.msSaveBlob) {
+ // IE10+ : (has Blob, but not a[download] or URL)
+ return navigator.msSaveBlob(blob, fileName);
+ }
+
+ if (self.URL) {
+ // simple fast and modern way using Blob and URL:
+ saver(self.URL.createObjectURL(blob), true);
+ } else {
+ // handle non-Blob()+non-URL browsers:
+ if (typeof blob === "string" || blob.constructor === toString) {
+ try {
+ return saver(`data:${mimeType};base64,${self.btoa(blob)}`);
+ } catch (y) {
+ return saver(`data:${mimeType},${encodeURIComponent(blob)}`);
+ }
+ }
+
+ // Blob but not URL support:
+ reader = new FileReader();
+ reader.onload = function () {
+ saver(this.result);
+ };
+ reader.readAsDataURL(blob);
+ }
+ return true;
+}
+
+// -----------------------------------------------------------------------------
+// Exported download function
+// -----------------------------------------------------------------------------
+
+/**
+ * Download a file
+ *
+ * Note: the actual implementation is certainly unconventional, but sadly
+ * necessary to be able to test code using the download function
+ *
+ * @param {*} options
+ * @returns {Promise}
+ */
+export function download(options) {
+ return download._download(options);
+}
+
+download._download = (options) => {
+ return new Promise((resolve, reject) => {
+ const xhr = new XMLHttpRequest();
+ let data;
+ if (Object.prototype.hasOwnProperty.call(options, "form")) {
+ xhr.open(options.form.method, options.form.action);
+ data = new FormData(options.form);
+ } else {
+ xhr.open("POST", options.url);
+ data = new FormData();
+ Object.entries(options.data).forEach((entry) => {
+ const [key, value] = entry;
+ data.append(key, value);
+ });
+ }
+ data.append("token", "dummy-because-api-expects-one");
+ if (odoo.csrf_token) {
+ data.append("csrf_token", odoo.csrf_token);
+ }
+ // IE11 wants this after xhr.open or it throws
+ xhr.responseType = "blob";
+ xhr.onload = () => {
+ const mimetype = xhr.response.type;
+ if (xhr.status === 200 && mimetype !== "text/html") {
+ // replace because apparently we send some C-D headers with a trailing ";"
+ const header = (xhr.getResponseHeader("Content-Disposition") || "").replace(
+ /;$/,
+ ""
+ );
+ const filename = header ? parse(header).parameters.filename : null;
+ _download(xhr.response, filename, mimetype);
+ return resolve(filename);
+ } else {
+ const decoder = new FileReader();
+ decoder.onload = () => {
+ const contents = decoder.result;
+ const doc = new DOMParser().parseFromString(contents, "text/html");
+ const nodes =
+ doc.body.children.length === 0 ? doc.body.childNodes : doc.body.children;
+ const error = new Error();
+ error.name = "XHR_SERVER_ERROR";
+ error.Component = ServerErrorDialog;
+ try {
+ // Case of a serialized Odoo Exception: It is Json Parsable
+ const node = nodes[1] || nodes[0];
+ error.message = "Serialized Python Exception";
+ error.traceback = JSON.parse(node.textContent);
+ } catch (e) {
+ // Arbitrary uncaught python side exception
+ error.message = "Arbitrary Uncaught Python Exception";
+ error.traceback = `${xhr.status}
+ ${nodes.length > 0 ? nodes[0].textContent : ""}
+ ${nodes.length > 1 ? nodes[1].textContent : ""}
+ `;
+ }
+ reject(error);
+ };
+ decoder.readAsText(xhr.response);
+ }
+ };
+ xhr.onerror = () => {
+ const error = new Error();
+ error.name = "XHR_NETWORK_ERROR";
+ error.Component = NetworkErrorDialog;
+ reject(error);
+ };
+ xhr.send(data);
+ });
+};
diff --git a/addons/web/static/src/core/network/http_service.js b/addons/web/static/src/core/network/http_service.js
new file mode 100644
index 00000000000..13f25142ebe
--- /dev/null
+++ b/addons/web/static/src/core/network/http_service.js
@@ -0,0 +1,43 @@
+/** @odoo-module **/
+
+import { registry } from "../registry";
+
+function checkResponseStatus(response) {
+ if (response.status === 502) {
+ throw new Error("Failed to fetch");
+ }
+}
+
+export const httpService = {
+ start() {
+ return {
+ async get(route, readMethod = "json") {
+ const response = await fetch(route, { method: "GET" });
+ checkResponseStatus(response);
+ return response[readMethod]();
+ },
+ async post(route, params = {}, readMethod = "json") {
+ const formData = new FormData();
+ for (const key in params) {
+ const value = params[key];
+ if (Array.isArray(value) && value.length) {
+ for (const val of value) {
+ formData.append(key, val);
+ }
+ } else {
+ formData.append(key, value);
+ }
+ }
+ const info = {
+ body: formData,
+ method: "POST",
+ };
+ const response = await fetch(route, info);
+ checkResponseStatus(response);
+ return response[readMethod]();
+ },
+ };
+ },
+};
+
+registry.category("services").add("http", httpService);
diff --git a/addons/web/static/src/core/network/rpc_service.js b/addons/web/static/src/core/network/rpc_service.js
new file mode 100644
index 00000000000..e2261754650
--- /dev/null
+++ b/addons/web/static/src/core/network/rpc_service.js
@@ -0,0 +1,108 @@
+/** @odoo-module **/
+
+import { browser } from "../browser/browser";
+import { registry } from "../registry";
+
+// -----------------------------------------------------------------------------
+// Errors
+// -----------------------------------------------------------------------------
+export class RPCError extends Error {
+ constructor() {
+ super(...arguments);
+ this.name = "RPC_ERROR";
+ this.type = "server";
+ this.code = null;
+ this.data = null;
+ this.exceptionName = null;
+ this.subType = null;
+ }
+}
+
+export class ConnectionLostError extends Error {}
+
+export class ConnectionAbortedError extends Error {}
+
+// -----------------------------------------------------------------------------
+// Main RPC method
+// -----------------------------------------------------------------------------
+export function makeErrorFromResponse(reponse) {
+ // Odoo returns error like this, in a error field instead of properly
+ // using http error codes...
+ const { code, data: errorData, message, type: subType } = reponse;
+ const { context: data_context, name: data_name } = errorData || {};
+ const { exception_class } = data_context || {};
+ const exception_class_name = exception_class || data_name;
+ const error = new RPCError();
+ error.exceptionName = exception_class_name;
+ error.subType = subType;
+ error.data = errorData;
+ error.message = message;
+ error.code = code;
+ return error;
+}
+
+function jsonrpc(env, rpcId, url, params, settings = {}) {
+ const bus = env.bus;
+ const XHR = browser.XMLHttpRequest;
+ const data = {
+ id: rpcId,
+ jsonrpc: "2.0",
+ method: "call",
+ params: params,
+ };
+ const request = new XHR();
+ let rejectFn;
+ const promise = new Promise((resolve, reject) => {
+ rejectFn = reject;
+ if (!settings.silent) {
+ bus.trigger("RPC:REQUEST", data.id);
+ }
+ // handle success
+ request.addEventListener("load", () => {
+ if (request.status === 502) {
+ // If Odoo is behind another server (eg.: nginx)
+ bus.trigger("RPC:RESPONSE", data.id);
+ reject(new ConnectionLostError());
+ return;
+ }
+ const { error: responseError, result: responseResult } = JSON.parse(request.response);
+ bus.trigger("RPC:RESPONSE", data.id);
+ if (!responseError) {
+ return resolve(responseResult);
+ }
+ const error = makeErrorFromResponse(responseError);
+ reject(error);
+ });
+ // handle failure
+ request.addEventListener("error", () => {
+ bus.trigger("RPC:RESPONSE", data.id);
+ reject(new ConnectionLostError());
+ });
+ // configure and send request
+ request.open("POST", url);
+ request.setRequestHeader("Content-Type", "application/json");
+ request.send(JSON.stringify(data));
+ });
+ promise.abort = function () {
+ if (request.abort) {
+ request.abort();
+ }
+ rejectFn(new ConnectionAbortedError());
+ };
+ return promise;
+}
+
+// -----------------------------------------------------------------------------
+// RPC service
+// -----------------------------------------------------------------------------
+export const rpcService = {
+ async: true,
+ start(env) {
+ let rpcId = 0;
+ return function rpc(route, params = {}, settings) {
+ return jsonrpc(env, rpcId++, route, params, settings);
+ };
+ },
+};
+
+registry.category("services").add("rpc", rpcService);
diff --git a/addons/web/static/src/core/notifications/notification.js b/addons/web/static/src/core/notifications/notification.js
new file mode 100644
index 00000000000..64cc6919e7c
--- /dev/null
+++ b/addons/web/static/src/core/notifications/notification.js
@@ -0,0 +1,72 @@
+/** @odoo-module **/
+
+const { Component, hooks } = owl;
+
+export class Notification extends Component {
+ setup() {
+ if (this.props.onClose) {
+ hooks.onWillUnmount(() => this.props.onClose());
+ }
+ }
+
+ shouldUpdate() {
+ return false;
+ }
+
+ get className() {
+ let className;
+ switch (this.props.type) {
+ case "danger":
+ className = "bg-danger";
+ break;
+ case "warning":
+ className = "bg-warning";
+ break;
+ case "success":
+ className = "bg-success";
+ break;
+ case "info":
+ className = "bg-info";
+ break;
+ }
+ return className ? `${className} ${this.props.className}` : this.props.className;
+ }
+}
+
+Notification.template = "web.NotificationWowl";
+Notification.props = {
+ message: {
+ validate: (m) => {
+ return (
+ typeof m === "string" || (typeof m === "object" && typeof m.toString === "function")
+ );
+ },
+ },
+ title: { type: [String, Boolean], optional: true },
+ type: {
+ type: String,
+ optional: true,
+ validate: (t) => ["warning", "danger", "success", "info"].includes(t),
+ },
+ messageIsHtml: { type: Boolean, optional: true },
+ className: { type: String, optional: true },
+ buttons: {
+ type: Array,
+ element: {
+ type: Object,
+ shape: {
+ name: { type: String },
+ icon: { type: String, optional: true },
+ primary: { type: Boolean, optional: true },
+ onClick: Function,
+ },
+ },
+ },
+ onClose: { type: Function, optional: true },
+};
+Notification.defaultProps = {
+ buttons: [],
+ className: "",
+ messageIsHtml: false,
+ type: "warning",
+};
diff --git a/addons/web/static/src/core/notifications/notification.scss b/addons/web/static/src/core/notifications/notification.scss
new file mode 100644
index 00000000000..2a45afcb4a9
--- /dev/null
+++ b/addons/web/static/src/core/notifications/notification.scss
@@ -0,0 +1,48 @@
+$notification-width: 320px;
+$notification-text-color: #212529;
+$notification-title-text-color: #6c757d;
+
+// Colors of the notification are not managed by this file.
+// It is handled by the other classes defining a background. (like danger, warning, etc.)
+// The notification just add overlays.
+
+.o_notification_manager {
+ @include o-position-absolute(3.5rem, 0);
+ position: fixed;
+ z-index: ($zindex-modal + $zindex-popover) / 2;
+ width: $notification-width;
+ margin-right: 0.5rem;
+ max-width: 100%;
+
+ .o_notification {
+ width: 100%;
+ margin-bottom: 0.375rem;
+ overflow: hidden;
+ background-color: rgba(255, 255, 255, 0.7);
+ background-clip: padding-box;
+ border: 1px solid rgba(0, 0, 0, 0.1);
+ box-shadow: 0 0.25rem 0.75rem rgba(0, 0, 0, 0.1);
+ border-radius: 0.25rem;
+
+ .o_notification_body {
+ padding: 0.5rem 0.625rem;
+ background-color: rgba(255, 255, 255, 0.78) !important;
+ color: $notification-text-color;
+
+ .o_notification_close {
+ margin-left: 1rem;
+ }
+ }
+
+ .o_notification_header {
+ display: flex;
+ align-items: center;
+ padding: 0.5rem 1.5rem;
+ color: $notification-title-text-color;
+ background-color: rgba(255, 255, 255, 0.7);
+ border-bottom: 1px solid rgba(0, 0, 0, 0.05);
+ }
+ }
+}
+
+@include owl-fade(0.5s, "o_notification");
diff --git a/addons/web/static/src/core/notifications/notification.xml b/addons/web/static/src/core/notifications/notification.xml
new file mode 100644
index 00000000000..577ab48ad3b
--- /dev/null
+++ b/addons/web/static/src/core/notifications/notification.xml
@@ -0,0 +1,33 @@
+
+
+
+
+
+
+
+
diff --git a/addons/web/static/src/core/notifications/notification_container.js b/addons/web/static/src/core/notifications/notification_container.js
new file mode 100644
index 00000000000..5fbccdfa28e
--- /dev/null
+++ b/addons/web/static/src/core/notifications/notification_container.js
@@ -0,0 +1,25 @@
+/** @odoo-module **/
+
+import { Notification } from "./notification";
+
+const { Component, tags } = owl;
+
+export class NotificationContainer extends Component {
+ setup() {
+ // this works, but then this component cannot be unmounted, then
+ // remounted. would need a destroyed hook different from willunmount
+ this.props.bus.on("UPDATE", this, this.render);
+ }
+}
+
+NotificationContainer.template = tags.xml`
+
+
+
+
+
`;
+NotificationContainer.components = { Notification };
diff --git a/addons/web/static/src/core/notifications/notification_service.js b/addons/web/static/src/core/notifications/notification_service.js
new file mode 100644
index 00000000000..3669eb971f6
--- /dev/null
+++ b/addons/web/static/src/core/notifications/notification_service.js
@@ -0,0 +1,73 @@
+/** @odoo-module **/
+
+import { browser } from "../browser/browser";
+import { registry } from "../registry";
+import { NotificationContainer } from "./notification_container";
+
+const { EventBus } = owl.core;
+
+const AUTOCLOSE_DELAY = 4000;
+
+/**
+ * @typedef {Object} NotificationButton
+ * @property {string} name
+ * @property {string} [icon]
+ * @property {boolean} [primary]
+ * @property {() => void} onClick
+ *
+ * @typedef {Object} NotificationOptions
+ * @property {string} [title]
+ * @property {"warning" | "danger" | "success" | "info"} [type]
+ * @property {boolean} [sticky]
+ * @property {string} [className]
+ * @property {() => void} [onClose]
+ * @property {NotificationButton} [buttons]
+ */
+
+export const notificationService = {
+ start() {
+ let notifId = 0;
+ let notifications = [];
+ const bus = new EventBus();
+
+ registry.category("main_components").add("NotificationContainer", {
+ Component: NotificationContainer,
+ props: { bus, notifications },
+ });
+
+ /**
+ * @param {string} message
+ * @param {NotificationOptions} [options]
+ */
+ function add(message, options = {}) {
+ const id = ++notifId;
+ const props = Object.assign({}, options, { message });
+ const sticky = props.sticky;
+ delete props.sticky;
+ const closeFn = () => close(id);
+ const notification = {
+ id,
+ props,
+ close: closeFn,
+ };
+ notifications.push(notification);
+ bus.trigger("UPDATE");
+ if (!sticky) {
+ browser.setTimeout(closeFn, AUTOCLOSE_DELAY);
+ }
+ return closeFn;
+ }
+
+ function close(id) {
+ const index = notifications.findIndex((n) => n.id === id);
+ if (index > -1) {
+ notifications.splice(index, 1);
+ bus.trigger("UPDATE");
+ }
+ }
+
+ return { add };
+ },
+};
+
+registry.category("services").add("notification", notificationService);
diff --git a/addons/web/static/src/core/orm_service.js b/addons/web/static/src/core/orm_service.js
new file mode 100644
index 00000000000..b765fdc4627
--- /dev/null
+++ b/addons/web/static/src/core/orm_service.js
@@ -0,0 +1,171 @@
+/** @odoo-module **/
+
+import { registry } from "./registry";
+
+/**
+ * This ORM service is the standard way to interact with the ORM in python from
+ * the javascript codebase.
+ */
+
+// -----------------------------------------------------------------------------
+// Helper
+// -----------------------------------------------------------------------------
+function assignOptions(kwargs, options, whileList) {
+ for (let elem of whileList) {
+ if (elem in options) {
+ kwargs[elem] = options[elem];
+ }
+ }
+}
+
+// -----------------------------------------------------------------------------
+// ORM
+// -----------------------------------------------------------------------------
+
+/**
+ * One2many and Many2many fields expect a special command to manipulate the
+ * relation they implement.
+ *
+ * Internally, each command is a 3-elements tuple where the first element is a
+ * mandatory integer that identifies the command, the second element is either
+ * the related record id to apply the command on (commands update, delete,
+ * unlink and link) either 0 (commands create, clear and set), the third
+ * element is either the ``values`` to write on the record (commands create
+ * and update) either the new ``ids`` list of related records (command set),
+ * either 0 (commands delete, unlink, link, and clear).
+ */
+export const Commands = {
+ create(virtualID, values) {
+ delete values.id;
+ return [0, virtualID || false, values];
+ },
+
+ update(id, values) {
+ delete values.id;
+ return [1, id, values];
+ },
+
+ delete(id) {
+ return [2, id, false];
+ },
+
+ forget(id) {
+ return [3, id, false];
+ },
+
+ linkTo(id) {
+ return [4, id, false];
+ },
+
+ deleteAll() {
+ return [5, false, false];
+ },
+
+ replaceWith(ids) {
+ return [6, false, ids];
+ },
+};
+
+class ORM {
+ constructor(rpc, user) {
+ this.rpc = rpc;
+ this.user = user;
+ this._silent = false;
+ }
+
+ get silent() {
+ return Object.assign(Object.create(this), { _silent: true });
+ }
+
+ call(model, method, args = [], kwargs = {}) {
+ let url = `/web/dataset/call_kw/${model}/${method}`;
+ const fullContext = Object.assign({}, this.user.context, kwargs.context || {});
+ const fullKwargs = Object.assign({}, kwargs, { context: fullContext });
+ let params = {
+ model,
+ method,
+ args,
+ kwargs: fullKwargs,
+ };
+ return this.rpc(url, params, { silent: this._silent });
+ }
+
+ create(model, state, ctx) {
+ return this.call(model, "create", [state], { context: ctx });
+ }
+
+ read(model, ids, fields, ctx) {
+ return this.call(model, "read", [ids, fields], { context: ctx });
+ }
+
+ readGroup(model, domain, fields, groupby, options = {}, ctx = {}) {
+ const kwargs = {
+ domain,
+ groupby,
+ fields,
+ context: ctx,
+ };
+ assignOptions(kwargs, options, ["lazy", "offset", "orderby", "limit"]);
+ return this.call(model, "web_read_group", [], kwargs);
+ }
+
+ search(model, domain, options = {}, ctx = {}) {
+ const kwargs = {
+ context: ctx,
+ };
+ assignOptions(kwargs, options, ["offset", "limit", "order"]);
+ return this.call(model, "search", [domain], kwargs);
+ }
+
+ searchRead(model, domain, fields, options = {}, ctx = {}) {
+ const kwargs = { context: ctx, domain, fields };
+ assignOptions(kwargs, options, ["offset", "limit", "order"]);
+ return this.call(model, "search_read", [], kwargs);
+ }
+
+ unlink(model, ids, ctx) {
+ return this.call(model, "unlink", [ids], { context: ctx });
+ }
+
+ webSearchRead(model, domain, fields, options = {}, ctx = {}) {
+ const kwargs = { context: ctx, domain, fields };
+ assignOptions(kwargs, options, ["offset", "limit", "order"]);
+ return this.call(model, "web_search_read", [], kwargs);
+ }
+
+ write(model, ids, data, ctx) {
+ return this.call(model, "write", [ids, data], { context: ctx });
+ }
+}
+
+/**
+ * Note:
+ *
+ * when we will need a way to configure a rpc (for example, to setup a "shadow"
+ * flag, or some way of not displaying errors), we can use the following api:
+ *
+ * this.orm = useService('orm');
+ *
+ * ...
+ *
+ * const result = await this.orm.withOption({shadow: true}).read('res.partner', [id]);
+ */
+export const ormService = {
+ dependencies: ["rpc", "user"],
+ async: [
+ "call",
+ "create",
+ "read",
+ "readGroup",
+ "search",
+ "searchRead",
+ "unlink",
+ "web_search_read",
+ "write",
+ ],
+ start(env, { rpc, user }) {
+ return new ORM(rpc, user);
+ },
+};
+
+registry.category("services").add("orm", ormService);
diff --git a/addons/web/static/src/core/popover/popover.js b/addons/web/static/src/core/popover/popover.js
new file mode 100644
index 00000000000..92b46b1553e
--- /dev/null
+++ b/addons/web/static/src/core/popover/popover.js
@@ -0,0 +1,158 @@
+/** @odoo-module **/
+
+import { debounce, throttle } from "../utils/timing";
+
+const { Component } = owl;
+const { useExternalListener, useRef } = owl.hooks;
+
+export class Popover extends Component {
+ setup() {
+ this.popoverRef = useRef("popover");
+
+ useExternalListener(document, "scroll", throttle(this.compute, 50), { capture: true });
+ useExternalListener(window, "resize", debounce(this.compute, 250));
+ }
+
+ mounted() {
+ this.compute();
+ }
+ patched() {
+ this.compute();
+ }
+
+ //--------------------------------------------------------------------------
+ // Private
+ //--------------------------------------------------------------------------
+
+ /**
+ * Computes the popover according to its props. This method will try to
+ * position the popover as requested (according to the `position` props).
+ * If the requested position does not fit the viewport, other positions will
+ * be tried in a clockwise order starting a the requested position
+ * (e.g. starting from left: top, right, bottom). If no position is found
+ * that fits the viewport, "bottom" is used.
+ *
+ * @private
+ */
+ compute() {
+ const positioningData = this.constructor.computePositioningData(
+ this.popoverRef.el,
+ this.props.target
+ );
+
+ const ORDERED_POSITIONS = ["top", "bottom", "left", "right"];
+ // copy the default ordered position to avoid updating them in place
+ const positionIndex = ORDERED_POSITIONS.indexOf(this.props.position);
+ // check if the requested position fits the viewport; if not,
+ // try all other positions and find one that does
+ const position = ORDERED_POSITIONS.slice(positionIndex)
+ .concat(ORDERED_POSITIONS.slice(0, positionIndex))
+ .map((pos) => positioningData[pos])
+ .find((pos) => {
+ this.popoverRef.el.style.top = `${pos.top}px`;
+ this.popoverRef.el.style.left = `${pos.left}px`;
+ const rect = this.popoverRef.el.getBoundingClientRect();
+ const html = document.documentElement;
+ return (
+ rect.top >= 0 &&
+ rect.left >= 0 &&
+ rect.bottom <= (window.innerHeight || html.clientHeight) &&
+ rect.right <= (window.innerWidth || html.clientWidth)
+ );
+ });
+
+ // remove all existing positioning classes
+ for (const pos of ORDERED_POSITIONS) {
+ this.popoverRef.el.classList.remove(`o_popover_${pos}`);
+ }
+
+ if (position) {
+ // apply the preferred found position that fits the viewport
+ this.popoverRef.el.classList.add(`o_popover_${position.name}`);
+ } else {
+ // use the given `position` props because no position fits
+ this.popoverRef.el.style.top = `${positioningData[this.props.position].top}px`;
+ this.popoverRef.el.style.left = `${positioningData[this.props.position].left}px`;
+ this.popoverRef.el.classList.add(`o_popover_${this.props.position}`);
+ }
+ }
+}
+
+Popover.template = "web.PopoverWowl";
+Popover.defaultProps = {
+ position: "bottom",
+};
+Popover.props = {
+ popoverClass: {
+ optional: true,
+ type: String,
+ },
+ position: {
+ type: String,
+ validate: (p) => ["top", "bottom", "left", "right"].includes(p),
+ },
+ target: HTMLElement,
+};
+
+/**
+ * Compute the expected positioning coordinates for each possible
+ * positioning based on the target and popover sizes.
+ * In particular the popover must not overflow the viewport in any
+ * direction, it should actually stay at `margin` distance from the
+ * border to look good.
+ *
+ * @param {HTMLElement} popoverElement The popover element
+ * @param {HTMLElement} targetElement The target element, to which
+ * the popover will be visually "bound"
+ * @param {number} [margin=16] Minimal accepted margin from the border
+ * of the viewport.
+ * @returns {Object}
+ */
+Popover.computePositioningData = function (popoverElement, targetElement, margin = 16) {
+ // set target position, possible position
+ const boundingRectangle = targetElement.getBoundingClientRect();
+ const targetTop = boundingRectangle.top;
+ const targetLeft = boundingRectangle.left;
+ const targetHeight = targetElement.offsetHeight;
+ const targetWidth = targetElement.offsetWidth;
+ const popoverHeight = popoverElement.offsetHeight;
+ const popoverWidth = popoverElement.offsetWidth;
+ const windowWidth = window.innerWidth || document.documentElement.clientWidth;
+ const windowHeight = window.innerHeight || document.documentElement.clientHeight;
+ const leftOffsetForVertical = Math.max(
+ margin,
+ Math.min(
+ Math.round(targetLeft - (popoverWidth - targetWidth) / 2),
+ windowWidth - popoverWidth - margin
+ )
+ );
+ const topOffsetForHorizontal = Math.max(
+ margin,
+ Math.min(
+ Math.round(targetTop - (popoverHeight - targetHeight) / 2),
+ windowHeight - popoverHeight - margin
+ )
+ );
+ return {
+ top: {
+ name: "top",
+ top: Math.round(targetTop - popoverHeight),
+ left: leftOffsetForVertical,
+ },
+ right: {
+ name: "right",
+ top: topOffsetForHorizontal,
+ left: Math.round(targetLeft + targetWidth),
+ },
+ bottom: {
+ name: "bottom",
+ top: Math.round(targetTop + targetHeight),
+ left: leftOffsetForVertical,
+ },
+ left: {
+ name: "left",
+ top: topOffsetForHorizontal,
+ left: Math.round(targetLeft - popoverWidth),
+ },
+ };
+};
diff --git a/addons/web/static/src/core/popover/popover.scss b/addons/web/static/src/core/popover/popover.scss
new file mode 100644
index 00000000000..7f65b53cd66
--- /dev/null
+++ b/addons/web/static/src/core/popover/popover.scss
@@ -0,0 +1,152 @@
+@keyframes slide-top {
+ 0% {
+ opacity: 0;
+ transform: translateY(-5%);
+ }
+
+ 100% {
+ opacity: 1;
+ transform: translateY(0);
+ }
+}
+
+@keyframes slide-right {
+ 0% {
+ opacity: 0;
+ transform: translateX(5%);
+ }
+
+ 100% {
+ opacity: 1;
+ transform: translateX(0);
+ }
+}
+
+@keyframes slide-bottom {
+ 0% {
+ opacity: 0;
+ transform: translateY(5%);
+ }
+
+ 100% {
+ opacity: 1;
+ transform: translateY(0);
+ }
+}
+
+@keyframes slide-left {
+ 0% {
+ opacity: 0;
+ transform: translateX(-5%);
+ }
+
+ 100% {
+ opacity: 1;
+ transform: translateX(0);
+ }
+}
+
+.o_popover {
+ $border-color: gray("300");
+ $bg-color: gray("200");
+ $arrow-pad: 0px;
+ $arrow-size: 8px;
+ $animation-time: 0.2s;
+ max-width: 100vw;
+
+ position: fixed;
+ top: 0; // will be updated in js
+ left: 0; // but let's set it in the viewport in case of test/debug
+ z-index: 1060;
+ border: 1px solid $border-color;
+ background-color: #fff;
+ box-shadow: 0 1px 4px rgba(0, 0, 0, 0.2);
+
+ &_top {
+ animation: $animation-time slide-top;
+ margin-top: -$arrow-size;
+
+ &::before,
+ &::after {
+ pointer-events: none;
+ content: "";
+ position: absolute;
+ top: 100%;
+ left: 50%;
+ margin-left: -$arrow-size;
+ border: $arrow-size solid transparent;
+ border-top-color: $bg-color;
+ }
+
+ &::before {
+ margin-top: 1px;
+ border-top-color: $border-color;
+ }
+ }
+
+ &_right {
+ animation: $animation-time slide-right;
+ margin-left: $arrow-size;
+
+ &::before,
+ &::after {
+ pointer-events: none;
+ content: "";
+ position: absolute;
+ top: 50%;
+ right: 100%;
+ margin-top: -$arrow-size;
+ border: $arrow-size solid transparent;
+ border-right-color: $bg-color;
+ }
+
+ &::before {
+ margin-right: 1px;
+ border-right-color: $border-color;
+ }
+ }
+
+ &_bottom {
+ animation: $animation-time slide-bottom;
+ margin-top: $arrow-size;
+
+ &::before,
+ &::after {
+ pointer-events: none;
+ content: "";
+ position: absolute;
+ bottom: 100%;
+ left: 50%;
+ margin-left: -$arrow-size;
+ border: $arrow-size solid transparent;
+ border-bottom-color: $bg-color;
+ }
+
+ &::before {
+ margin-bottom: 1px;
+ border-bottom-color: $border-color;
+ }
+ }
+
+ &_left {
+ animation: $animation-time slide-left;
+ margin-left: -$arrow-size;
+
+ &::before,
+ &::after {
+ pointer-events: none;
+ content: "";
+ position: absolute;
+ top: 50%;
+ left: 100%;
+ margin-top: -$arrow-size;
+ border: $arrow-size solid transparent;
+ border-left-color: $bg-color;
+ }
+
+ &::before {
+ margin-left: 1px;
+ border-left-color: $border-color;
+ }
+ }
+}
diff --git a/addons/web/static/src/core/popover/popover.xml b/addons/web/static/src/core/popover/popover.xml
new file mode 100644
index 00000000000..7ec48f8082d
--- /dev/null
+++ b/addons/web/static/src/core/popover/popover.xml
@@ -0,0 +1,14 @@
+
+
+
+
+
+
+
+
+
+
diff --git a/addons/web/static/src/core/popover/popover_container.js b/addons/web/static/src/core/popover/popover_container.js
new file mode 100644
index 00000000000..92a0ae68bc6
--- /dev/null
+++ b/addons/web/static/src/core/popover/popover_container.js
@@ -0,0 +1,79 @@
+/** @odoo-module **/
+
+import { Popover } from "./popover";
+
+const { Component } = owl;
+const { useExternalListener, useState } = owl.hooks;
+const { xml } = owl.tags;
+
+class PopoverController extends Component {
+ setup() {
+ this.state = useState({ displayed: false });
+ this.targetObserver = new MutationObserver(this.onTargetMutate.bind(this));
+
+ useExternalListener(window, "click", this.onClickAway, { capture: true });
+ }
+ mounted() {
+ this.targetObserver.observe(this.target.parentElement, { childList: true });
+ }
+ willUnmount() {
+ this.targetObserver.disconnect();
+ }
+
+ shouldUpdate() {
+ return false;
+ }
+
+ get popoverProps() {
+ return {
+ target: this.target,
+ position: this.props.position,
+ popoverClass: this.props.popoverClass,
+ };
+ }
+ get target() {
+ if (typeof this.props.target === "string") {
+ return document.querySelector(this.props.target);
+ } else {
+ return this.props.target;
+ }
+ }
+ onClickAway(ev) {
+ if (this.target.contains(ev.target) || ev.target.closest(".o_popover")) {
+ return;
+ }
+ if (this.props.closeOnClickAway) {
+ this.props.close();
+ }
+ }
+ onTargetMutate() {
+ const target = this.target;
+ if (!target || !target.parentElement) {
+ this.props.close();
+ }
+ }
+}
+PopoverController.components = { Popover };
+PopoverController.defaultProps = {
+ alwaysDisplayed: false,
+ closeOnClickAway: true,
+};
+PopoverController.template = xml/*xml*/ `
+
+
+
+`;
+
+export class PopoverContainer extends Component {
+ setup() {
+ this.props.bus.on("UPDATE", this, this.render);
+ }
+}
+PopoverContainer.components = { PopoverController };
+PopoverContainer.template = xml`
+
+`;
diff --git a/addons/web/static/src/core/popover/popover_hook.js b/addons/web/static/src/core/popover/popover_hook.js
new file mode 100644
index 00000000000..3349851a114
--- /dev/null
+++ b/addons/web/static/src/core/popover/popover_hook.js
@@ -0,0 +1,46 @@
+/** @odoo-module **/
+
+import { useService } from "../service_hook";
+
+const { onWillUnmount, useComponent } = owl.hooks;
+
+export function usePopover() {
+ const removeFns = new Set();
+ const service = useService("popover");
+ const component = useComponent();
+
+ onWillUnmount(function () {
+ for (const removeFn of removeFns) {
+ removeFn();
+ }
+ removeFns.clear();
+ });
+ return {
+ /**
+ * Signals the manager to add a popover.
+ *
+ * @param {string | HTMLElement} target
+ * @param {any} Component
+ * @param {Object} props
+ * @param {Object} [options]
+ * @param {boolean} [options.closeOnClickAway=true]
+ * @param {() => void} [options.onClose]
+ * @param {string} [options.popoverClass]
+ * @param {string} [options.position]
+ * @returns {() => void}
+ */
+ add(target, Component, props, options = {}) {
+ const newOptions = Object.create(options);
+ newOptions.onClose = function () {
+ removeFns.delete(removeFn);
+ if (options.onClose && component.__owl__.status !== 5 /* DESTROYED */) {
+ options.onClose();
+ }
+ };
+
+ const removeFn = service.add(target, Component, props, newOptions);
+ removeFns.add(removeFn);
+ return removeFn;
+ },
+ };
+}
diff --git a/addons/web/static/src/core/popover/popover_service.js b/addons/web/static/src/core/popover/popover_service.js
new file mode 100644
index 00000000000..e592a111ab1
--- /dev/null
+++ b/addons/web/static/src/core/popover/popover_service.js
@@ -0,0 +1,65 @@
+/** @odoo-module **/
+
+import { registry } from "../registry";
+import { PopoverContainer } from "./popover_container";
+
+const { EventBus } = owl.core;
+
+export const popoverService = {
+ start() {
+ let nextId = 0;
+ const popovers = {};
+ const bus = new EventBus();
+
+ registry
+ .category("main_components")
+ .add("PopoverContainer", { Component: PopoverContainer, props: { bus, popovers } });
+
+ /**
+ * Signals the manager to add a popover.
+ *
+ * @param {string | HTMLElement} target
+ * @param {any} Component
+ * @param {Object} props
+ * @param {Object} [options]
+ * @param {boolean} [options.closeOnClickAway=true]
+ * @param {() => void} [options.onClose]
+ * @param {string} [options.popoverClass]
+ * @param {string} [options.position]
+ * @returns {() => void}
+ */
+ function add(target, Component, props, options = {}) {
+ const id = ++nextId;
+ const closeFn = () => close(id);
+ const popover = {
+ id,
+ target,
+ Component,
+ props,
+ close: closeFn,
+ onClose: options.onClose,
+ position: options.position,
+ popoverClass: options.popoverClass,
+ closeOnClickAway: options.closeOnClickAway,
+ };
+ popovers[id] = popover;
+ bus.trigger("UPDATE");
+ return closeFn;
+ }
+
+ function close(id) {
+ if (id in popovers) {
+ const popover = popovers[id];
+ if (popover.onClose) {
+ popover.onClose();
+ }
+ delete popovers[id];
+ bus.trigger("UPDATE");
+ }
+ }
+
+ return { add };
+ },
+};
+
+registry.category("services").add("popover", popoverService);
diff --git a/addons/web/static/src/core/py_js/py.js b/addons/web/static/src/core/py_js/py.js
new file mode 100644
index 00000000000..322e5287bfa
--- /dev/null
+++ b/addons/web/static/src/core/py_js/py.js
@@ -0,0 +1,38 @@
+/** @odoo-module **/
+
+import { evaluate } from "./py_interpreter";
+import { parse } from "./py_parser";
+import { tokenize } from "./py_tokenizer";
+
+export { evaluate } from "./py_interpreter";
+export { parse } from "./py_parser";
+export { tokenize } from "./py_tokenizer";
+export { formatAST } from "./py_utils";
+
+/**
+ * @typedef { import("./py_tokenizer").Token } Token
+ * @typedef { import("./py_parser").AST } AST
+ */
+
+/**
+ * Parses an expression into a valid AST representation
+
+ * @param {string} expr
+ * @returns { AST }
+ */
+export function parseExpr(expr) {
+ const tokens = tokenize(expr);
+ return parse(tokens);
+}
+
+/**
+ * Evaluates a python expression
+ *
+ * @param {string} expr
+ * @param {Object} context
+ * @returns {any}
+ */
+export function evaluateExpr(expr, context) {
+ const ast = parseExpr(expr);
+ return evaluate(ast, context);
+}
diff --git a/addons/web/static/src/core/py_js/py_builtin.js b/addons/web/static/src/core/py_js/py_builtin.js
new file mode 100644
index 00000000000..760c5f26ff3
--- /dev/null
+++ b/addons/web/static/src/core/py_js/py_builtin.js
@@ -0,0 +1,50 @@
+/** @odoo-module **/
+
+import { PyDate, PyDateTime, PyRelativeDelta, PyTime } from "./py_date";
+
+export const BUILTINS = {
+ /**
+ * @param {any} value
+ * @returns {boolean}
+ */
+ bool(value) {
+ switch (typeof value) {
+ case "number":
+ return value !== 0;
+ case "string":
+ return value !== "";
+ case "boolean":
+ return value;
+ case "object":
+ return value !== null;
+ }
+ return true;
+ },
+
+ time: {
+ strftime(format) {
+ return PyDateTime.now().strftime(format);
+ },
+ },
+
+ context_today() {
+ return PyDate.today();
+ },
+
+ get today() {
+ return PyDate.today().strftime("%Y-%m-%d");
+ },
+
+ get now() {
+ return PyDateTime.now().strftime("%Y-%m-%d %H:%M:%S");
+ },
+
+ datetime: {
+ time: PyTime,
+ timedelta: PyRelativeDelta,
+ datetime: PyDateTime,
+ date: PyDate,
+ },
+
+ relativedelta: PyRelativeDelta,
+};
diff --git a/addons/web/static/src/core/py_js/py_date.js b/addons/web/static/src/core/py_js/py_date.js
new file mode 100644
index 00000000000..40c957aafdc
--- /dev/null
+++ b/addons/web/static/src/core/py_js/py_date.js
@@ -0,0 +1,475 @@
+/** @odoo-module **/
+
+import { parseArgs } from "./py_utils";
+
+// -----------------------------------------------------------------------------
+// Errors
+// -----------------------------------------------------------------------------
+
+export class AssertionError extends Error {}
+export class ValueError extends Error {}
+export class NotSupportedError extends Error {}
+
+// -----------------------------------------------------------------------------
+// helpers
+// -----------------------------------------------------------------------------
+
+function fmt2(n) {
+ return String(n).padStart(2, "0");
+}
+function fmt4(n) {
+ return String(n).padStart(4, "0");
+}
+
+/**
+ * computes (Math.floor(a/b), a%b and passes that to the callback.
+ *
+ * returns the callback's result
+ */
+function divmod(a, b, fn) {
+ let mod = a % b;
+ // in python, sign(a % b) === sign(b). Not in JS. If wrong side, add a
+ // round of b
+ if ((mod > 0 && b < 0) || (mod < 0 && b > 0)) {
+ mod += b;
+ }
+ return fn(Math.floor(a / b), mod);
+}
+
+function assert(bool) {
+ if (!bool) {
+ throw new AssertionError("AssertionError");
+ }
+}
+
+const DAYS_IN_MONTH = [null, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
+const DAYS_BEFORE_MONTH = [null];
+
+for (let dbm = 0, i = 1; i < DAYS_IN_MONTH.length; ++i) {
+ DAYS_BEFORE_MONTH.push(dbm);
+ dbm += DAYS_IN_MONTH[i];
+}
+
+function daysInMonth(year, month) {
+ if (month === 2 && isLeap(year)) {
+ return 29;
+ }
+ return DAYS_IN_MONTH[month];
+}
+
+function isLeap(year) {
+ return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
+}
+
+function daysBeforeYear(year) {
+ const y = year - 1;
+ return y * 365 + Math.floor(y / 4) - Math.floor(y / 100) + Math.floor(y / 400);
+}
+
+function daysBeforeMonth(year, month) {
+ const postLeapFeb = month > 2 && isLeap(year);
+ return DAYS_BEFORE_MONTH[month] + (postLeapFeb ? 1 : 0);
+}
+
+function ymd2ord(year, month, day) {
+ const dim = daysInMonth(year, month);
+ if (!(1 <= day && day <= dim)) {
+ throw new ValueError(`day must be in 1..${dim}`);
+ }
+ return daysBeforeYear(year) + daysBeforeMonth(year, month) + day;
+}
+
+const DI400Y = daysBeforeYear(401);
+const DI100Y = daysBeforeYear(101);
+const DI4Y = daysBeforeYear(5);
+
+function ord2ymd(n) {
+ --n;
+ let n400, n100, n4, n1, n0;
+ divmod(n, DI400Y, function (_n400, n) {
+ n400 = _n400;
+ divmod(n, DI100Y, function (_n100, n) {
+ n100 = _n100;
+ divmod(n, DI4Y, function (_n4, n) {
+ n4 = _n4;
+ divmod(n, 365, function (_n1, n) {
+ n1 = _n1;
+ n0 = n;
+ });
+ });
+ });
+ });
+
+ n = n0;
+ const year = n400 * 400 + 1 + n100 * 100 + n4 * 4 + n1;
+ if (n1 == 4 || n100 == 100) {
+ assert(n0 === 0);
+ return {
+ year: year - 1,
+ month: 12,
+ day: 31,
+ };
+ }
+
+ let leapyear = n1 === 3 && (n4 !== 24 || n100 == 3);
+ assert(leapyear == isLeap(year));
+ let month = (n + 50) >> 5;
+ let preceding = DAYS_BEFORE_MONTH[month] + (month > 2 && leapyear ? 1 : 0);
+ if (preceding > n) {
+ --month;
+ preceding -= DAYS_IN_MONTH[month] + (month === 2 && leapyear ? 1 : 0);
+ }
+ n -= preceding;
+ return {
+ year: year,
+ month: month,
+ day: n + 1,
+ };
+}
+
+/**
+ * Converts the stuff passed in into a valid date, applying overflows as needed
+ */
+function tmxxx(year, month, day, hour, minute, second, microsecond) {
+ hour = hour || 0;
+ minute = minute || 0;
+ second = second || 0;
+ microsecond = microsecond || 0;
+
+ if (microsecond < 0 || microsecond > 999999) {
+ divmod(microsecond, 1000000, function (carry, ms) {
+ microsecond = ms;
+ second += carry;
+ });
+ }
+ if (second < 0 || second > 59) {
+ divmod(second, 60, function (carry, s) {
+ second = s;
+ minute += carry;
+ });
+ }
+ if (minute < 0 || minute > 59) {
+ divmod(minute, 60, function (carry, m) {
+ minute = m;
+ hour += carry;
+ });
+ }
+ if (hour < 0 || hour > 23) {
+ divmod(hour, 24, function (carry, h) {
+ hour = h;
+ day += carry;
+ });
+ }
+ // That was easy. Now it gets muddy: the proper range for day
+ // can't be determined without knowing the correct month and year,
+ // but if day is, e.g., plus or minus a million, the current month
+ // and year values make no sense (and may also be out of bounds
+ // themselves).
+ // Saying 12 months == 1 year should be non-controversial.
+ if (month < 1 || month > 12) {
+ divmod(month - 1, 12, function (carry, m) {
+ month = m + 1;
+ year += carry;
+ });
+ }
+ // Now only day can be out of bounds (year may also be out of bounds
+ // for a datetime object, but we don't care about that here).
+ // If day is out of bounds, what to do is arguable, but at least the
+ // method here is principled and explainable.
+ let dim = daysInMonth(year, month);
+ if (day < 1 || day > dim) {
+ // Move day-1 days from the first of the month. First try to
+ // get off cheap if we're only one day out of range (adjustments
+ // for timezone alone can't be worse than that).
+ if (day === 0) {
+ --month;
+ if (month > 0) {
+ day = daysInMonth(year, month);
+ } else {
+ --year;
+ month = 12;
+ day = 31;
+ }
+ } else if (day == dim + 1) {
+ ++month;
+ day = 1;
+ if (month > 12) {
+ month = 1;
+ ++year;
+ }
+ } else {
+ let r = ord2ymd(ymd2ord(year, month, 1) + (day - 1));
+ year = r.year;
+ month = r.month;
+ day = r.day;
+ }
+ }
+ return {
+ year: year,
+ month: month,
+ day: day,
+ hour: hour,
+ minute: minute,
+ second: second,
+ microsecond: microsecond,
+ };
+}
+
+// -----------------------------------------------------------------------------
+// Date/Time and related classes
+// -----------------------------------------------------------------------------
+
+export class PyDate {
+ /**
+ * @returns {PyDate}
+ */
+ static today() {
+ const now = new Date();
+ const year = now.getUTCFullYear();
+ const month = now.getUTCMonth() + 1;
+ const day = now.getUTCDate();
+ return new PyDate(year, month, day);
+ }
+
+ constructor(year, month, day) {
+ this.year = year;
+ this.month = month; // 1-indexed => 1 = january, 2 = february, ...
+ this.day = day; // 1-indexed => 1 = first day of month, ...
+ }
+
+ /**
+ * @param {...any} args
+ * @returns {PyDate}
+ */
+ static create(...args) {
+ const { year, month, day } = parseArgs(args, ["year", "month", "day"]);
+ return new PyDate(year, month, day);
+ }
+
+ /**
+ * @param {string} format
+ * @returns {string}
+ */
+ strftime(format) {
+ return format.replace(/%([A-Za-z])/g, (m, c) => {
+ switch (c) {
+ case "Y":
+ return fmt4(this.year);
+ case "m":
+ return fmt2(this.month);
+ case "d":
+ return fmt2(this.day);
+ }
+ throw new ValueError(`No known conversion for ${m}`);
+ });
+ }
+}
+
+export class PyDateTime {
+ /**
+ * @returns {PyDateTime}
+ */
+ static now() {
+ const now = new Date();
+ const year = now.getUTCFullYear();
+ const month = now.getUTCMonth() + 1;
+ const day = now.getUTCDate();
+ const hour = now.getUTCHours();
+ const minute = now.getUTCMinutes();
+ const second = now.getUTCSeconds();
+ return new PyDateTime(year, month, day, hour, minute, second, 0);
+ }
+
+ /**
+ * @param {...any} args
+ * @returns {PyDateTime}
+ */
+ static create(...args) {
+ const namedArgs = parseArgs(args, [
+ "year",
+ "month",
+ "day",
+ "hour",
+ "minute",
+ "second",
+ "microsecond",
+ ]);
+ const year = namedArgs.year;
+ const month = namedArgs.month;
+ const day = namedArgs.day;
+ const hour = namedArgs.hour || 0;
+ const minute = namedArgs.minute || 0;
+ const second = namedArgs.second || 0;
+ const ms = namedArgs.micro / 1000 || 0;
+ return new PyDateTime(year, month, day, hour, minute, second, ms);
+ }
+
+ /**
+ * @param {...any} args
+ * @returns {PyDateTime}
+ */
+ static combine(...args) {
+ const { date, time } = parseArgs(args, ["date", "time"]);
+ // not sure. should we go through constructor instead? what about args normalization?
+ return PyDateTime.create(
+ date.year,
+ date.month,
+ date.day,
+ time.hour,
+ time.minute,
+ time.second
+ );
+ }
+
+ constructor(year, month, day, hour, minute, second, millisecond) {
+ this.year = year;
+ this.month = month; // 1-indexed => 1 = january, 2 = february, ...
+ this.day = day; // 1-indexed => 1 = first day of month, ...
+ this.hour = hour;
+ this.minute = minute;
+ this.second = second;
+ this.millisecond = millisecond;
+ }
+
+ /**
+ * @param {string} format
+ * @returns {string}
+ */
+ strftime(format) {
+ return format.replace(/%([A-Za-z])/g, (m, c) => {
+ switch (c) {
+ case "Y":
+ return fmt4(this.year);
+ case "m":
+ return fmt2(this.month);
+ case "d":
+ return fmt2(this.day);
+ case "H":
+ return fmt2(this.hour);
+ case "M":
+ return fmt2(this.minute);
+ case "S":
+ return fmt2(this.second);
+ }
+ throw new ValueError(`No known conversion for ${m}`);
+ });
+ }
+}
+
+export class PyTime extends PyDate {
+ /**
+ * @param {...any} args
+ * @returns {PyTime}
+ */
+ static create(...args) {
+ const namedArgs = parseArgs(args, ["hour", "minute", "second"]);
+ const hour = namedArgs.hour || 0;
+ const minute = namedArgs.minute || 0;
+ const second = namedArgs.second || 0;
+ return new PyTime(hour, minute, second);
+ }
+
+ constructor(hour, minute, second) {
+ const now = new Date();
+ const year = now.getFullYear();
+ const month = now.getUTCMonth();
+ const day = now.getUTCDate();
+ super(year, month, day);
+ this.hour = hour;
+ this.minute = minute;
+ this.second = second;
+ }
+
+ /**
+ * @param {string} format
+ * @returns {string}
+ */
+ strftime(format) {
+ return format.replace(/%([A-Za-z])/g, (m, c) => {
+ switch (c) {
+ case "Y":
+ return fmt4(this.year);
+ case "m":
+ return fmt2(this.month + 1);
+ case "d":
+ return fmt2(this.day);
+ case "H":
+ return fmt2(this.hour);
+ case "M":
+ return fmt2(this.minute);
+ case "S":
+ return fmt2(this.second);
+ }
+ throw new ValueError(`No known conversion for ${m}`);
+ });
+ }
+}
+
+const argsSpec = "year month day hour minute second years months weeks days hours minutes seconds weekday".split(
+ " "
+);
+
+export class PyRelativeDelta {
+ /**
+ * @param {...any} args
+ * @returns {PyRelativeDelta}
+ */
+ static create(...args) {
+ const delta = new PyRelativeDelta();
+ const namedArgs = parseArgs(args, argsSpec);
+ delta.year = (namedArgs.year || 0) + (namedArgs.years || 0);
+ delta.month = (namedArgs.month || 0) + (namedArgs.months || 0);
+ delta.day = (namedArgs.day || 0) + (namedArgs.days || 0);
+ delta.hour = (namedArgs.hour || 0) + (namedArgs.hours || 0);
+ delta.minute = (namedArgs.minute || 0) + (namedArgs.minutes || 0);
+ delta.second = (namedArgs.second || 0) + (namedArgs.seconds || 0);
+ delta.day += 7 * (namedArgs.weeks || 0);
+ if (namedArgs.weekday) {
+ throw new NotSupportedError("weekday is not supported");
+ }
+ return delta;
+ }
+
+ /**
+ * @param {PyDate} date
+ * @param {PyRelativeDelta} delta
+ * @returns {PyDateTime}
+ */
+ static add(date, delta) {
+ const s = tmxxx(
+ date.year,
+ date.month,
+ date.day + delta.day,
+ delta.hour,
+ delta.minute,
+ delta.second
+ );
+ return new PyDateTime(s.year, s.month, s.day, s.hour, s.minute, s.second, 0);
+ }
+
+ /**
+ * @param {PyDate} date
+ * @param {PyRelativeDelta} delta
+ * @returns {PyDateTime}
+ */
+ static substract(date, delta) {
+ const s = tmxxx(
+ date.year,
+ date.month,
+ date.day - delta.day,
+ -delta.hour,
+ -delta.minute,
+ -delta.second
+ );
+ return new PyDateTime(s.year, s.month, s.day, s.hour, s.minute, s.second, 0);
+ }
+
+ constructor() {
+ this.year = 0;
+ this.month = 0;
+ this.day = 0;
+ this.hour = 0;
+ this.minute = 0;
+ this.second = 0;
+ }
+}
diff --git a/addons/web/static/src/core/py_js/py_interpreter.js b/addons/web/static/src/core/py_js/py_interpreter.js
new file mode 100644
index 00000000000..6343310a34a
--- /dev/null
+++ b/addons/web/static/src/core/py_js/py_interpreter.js
@@ -0,0 +1,288 @@
+/** @odoo-module **/
+
+import { BUILTINS } from "./py_builtin";
+import { PyDate, PyDateTime, PyRelativeDelta, PyTime } from "./py_date";
+import { parseArgs, PY_DICT } from "./py_utils";
+
+// -----------------------------------------------------------------------------
+// Types
+// -----------------------------------------------------------------------------
+
+/**
+ * @typedef { import("./py_parser").AST } AST
+ */
+
+export class EvaluationError extends Error {}
+
+// -----------------------------------------------------------------------------
+// Constants and helpers
+// -----------------------------------------------------------------------------
+
+const isTrue = BUILTINS.bool;
+
+/**
+ * @param {AST} ast
+ * @param {Object} context
+ * @returns {any}
+ */
+function applyUnaryOp(ast, context) {
+ const expr = evaluate(ast.right, context);
+ switch (ast.op) {
+ case "-":
+ return -expr;
+ case "+":
+ return expr;
+ case "not":
+ return !isTrue(expr);
+ }
+ throw new EvaluationError(`Unknown unary operator: ${ast.op}`);
+}
+
+/**
+ * We want to maintain this order:
+ * None < number (boolean) < dict < string < list < dict
+ * So, each type is mapped to a number to represent that order
+ *
+ * @param {any} val
+ * @returns {number} index type
+ */
+function pytypeIndex(val) {
+ switch (typeof val) {
+ case "object":
+ // None, List, Object, Dict
+ return val === null ? 1 : Array.isArray(val) ? 5 : 3;
+ case "number":
+ return 2;
+ case "string":
+ return 4;
+ }
+ throw new EvaluationError(`Unknown type: ${typeof val}`);
+}
+
+/**
+ * Compare two values
+ *
+ * @param {any} left
+ * @param {any} right
+ * @returns {boolean}
+ */
+function isLess(left, right) {
+ if (typeof left === "number" && typeof right === "number") {
+ return left < right;
+ }
+ if (typeof left === "boolean") {
+ left = left ? 1 : 0;
+ }
+ if (typeof right === "boolean") {
+ right = right ? 1 : 0;
+ }
+ const leftIndex = pytypeIndex(left);
+ const rightIndex = pytypeIndex(right);
+ if (leftIndex === rightIndex) {
+ return left < right;
+ }
+ return leftIndex < rightIndex;
+}
+
+/**
+ * @param {any} left
+ * @param {any} right
+ * @returns {boolean}
+ */
+function isEqual(left, right) {
+ if (typeof left !== typeof right) {
+ if (typeof left === "boolean" && typeof right === "number") {
+ return right === (left ? 1 : 0);
+ }
+ if (typeof left === "number" && typeof right === "boolean") {
+ return left === (right ? 1 : 0);
+ }
+ return false;
+ }
+ return left === right;
+}
+
+/**
+ * @param {any} left
+ * @param {any} right
+ * @returns {boolean}
+ */
+function isIn(left, right) {
+ if (Array.isArray(right)) {
+ return right.includes(left);
+ }
+ if (typeof right === "string" && typeof left === "string") {
+ return right.includes(left);
+ }
+ return false;
+}
+
+/**
+ * @param {AST} ast
+ * @param {object} context
+ * @returns {any}
+ */
+function applyBinaryOp(ast, context) {
+ const left = evaluate(ast.left, context);
+ const right = evaluate(ast.right, context);
+ switch (ast.op) {
+ case "+": {
+ const isLeftDelta = left instanceof PyRelativeDelta;
+ const isRightDelta = right instanceof PyRelativeDelta;
+ if (isLeftDelta || isRightDelta) {
+ const date = isLeftDelta ? right : left;
+ const delta = isLeftDelta ? left : right;
+ return PyRelativeDelta.add(date, delta);
+ }
+ return left + right;
+ }
+ case "-": {
+ const isRightDelta = right instanceof PyRelativeDelta;
+ if (isRightDelta) {
+ return PyRelativeDelta.substract(left, right);
+ }
+ return left - right;
+ }
+ case "*":
+ return left * right;
+ case "/":
+ return left / right;
+ case "%":
+ return left % right;
+ case "//":
+ return Math.floor(left / right);
+ case "**":
+ return left ** right;
+ case "==":
+ return isEqual(left, right);
+ case "<>":
+ case "!=":
+ return !isEqual(left, right);
+ case "<":
+ return isLess(left, right);
+ case ">":
+ return isLess(right, left);
+ case ">=":
+ return isEqual(left, right) || isLess(right, left);
+ case "<=":
+ return isEqual(left, right) || isLess(left, right);
+ case "in":
+ return isIn(left, right);
+ case "not in":
+ return !isIn(left, right);
+ }
+ throw new EvaluationError(`Unknown binary operator: ${ast.op}`);
+}
+
+const DICT = {
+ get(dict) {
+ return (...args) => {
+ const { key, defValue } = parseArgs(args, ["key", "defValue"]);
+ if (key in dict) {
+ return dict[key];
+ } else if (defValue) {
+ return defValue;
+ }
+ return null;
+ };
+ },
+};
+
+// -----------------------------------------------------------------------------
+// Evaluate function
+// -----------------------------------------------------------------------------
+
+/**
+ * @param {AST} ast
+ * @param {Object} context
+ * @returns {any}
+ */
+export function evaluate(ast, context = {}) {
+ const dicts = new Set();
+
+ /**
+ * @param {AST} ast
+ */
+ function _evaluate(ast) {
+ switch (ast.type) {
+ case 0 /* Number */:
+ case 1 /* String */:
+ return ast.value;
+ case 5 /* Name */:
+ if (ast.value in context) {
+ return context[ast.value];
+ } else if (ast.value in BUILTINS) {
+ return BUILTINS[ast.value];
+ } else {
+ throw new EvaluationError(`Name '${ast.value}' is not defined`);
+ }
+ case 3 /* None */:
+ return null;
+ case 2 /* Boolean */:
+ return ast.value;
+ case 6 /* UnaryOperator */:
+ return applyUnaryOp(ast, context);
+ case 7 /* BinaryOperator */:
+ return applyBinaryOp(ast, context);
+ case 14 /* BooleanOperator */:
+ const left = _evaluate(ast.left);
+ if (ast.op === "and") {
+ return isTrue(left) ? _evaluate(ast.right) : left;
+ } else {
+ return isTrue(left) ? left : _evaluate(ast.right);
+ }
+ case 4 /* List */:
+ case 10 /* Tuple */:
+ return ast.value.map(_evaluate);
+ case 11 /* Dictionary */:
+ const dict = {};
+ for (let key in ast.value) {
+ dict[key] = _evaluate(ast.value[key]);
+ }
+ dicts.add(dict);
+ return dict;
+ case 8 /* FunctionCall */:
+ const fnValue = _evaluate(ast.fn);
+ const args = ast.args.map(_evaluate);
+ const kwargs = {};
+ for (let kwarg in ast.kwargs) {
+ kwargs[kwarg] = _evaluate(ast.kwargs[kwarg]);
+ }
+ if (
+ fnValue === PyDate ||
+ fnValue === PyDateTime ||
+ fnValue === PyTime ||
+ fnValue === PyRelativeDelta
+ ) {
+ return fnValue.create(...args, kwargs);
+ }
+ return fnValue(...args, kwargs);
+ case 12 /* Lookup */: {
+ const dict = _evaluate(ast.target);
+ const key = _evaluate(ast.key);
+ return dict[key];
+ }
+ case 13 /* If */: {
+ if (isTrue(_evaluate(ast.condition))) {
+ return _evaluate(ast.ifTrue);
+ } else {
+ return _evaluate(ast.ifFalse);
+ }
+ }
+ case 15 /* ObjLookup */: {
+ const left = _evaluate(ast.obj);
+ if (dicts.has(left) || Object.isPrototypeOf.call(PY_DICT, left)) {
+ // this is a dictionary => need to apply dict methods
+ return DICT[ast.key](left);
+ }
+ if (left instanceof PyDate || left instanceof PyDateTime) {
+ const result = left[ast.key];
+ return typeof result === "function" ? result.bind(left) : result;
+ }
+ return left[ast.key];
+ }
+ }
+ throw new EvaluationError(`AST of type ${ast.type} cannot be evaluated`);
+ }
+ return _evaluate(ast);
+}
diff --git a/addons/web/static/src/core/py_js/py_parser.js b/addons/web/static/src/core/py_js/py_parser.js
new file mode 100644
index 00000000000..ddaedfbef9f
--- /dev/null
+++ b/addons/web/static/src/core/py_js/py_parser.js
@@ -0,0 +1,368 @@
+/** @odoo-module **/
+
+import { binaryOperators, comparators } from "./py_tokenizer";
+
+// -----------------------------------------------------------------------------
+// Types
+// -----------------------------------------------------------------------------
+
+/**
+ * @typedef { import("./py_tokenizer").Token } Token
+ */
+
+/**
+ * @typedef {{type: 0, value: number}} ASTNumber
+ * @typedef {{type: 1, value: string}} ASTString
+ * @typedef {{type: 2, value: boolean}} ASTBoolean
+ * @typedef {{type: 3}} ASTNone
+ * @typedef {{type: 4, value: AST[]}} ASTList
+ * @typedef {{type: 5, value: string}} ASTName
+ * @typedef {{type: 6, op: string, right: AST}} ASTUnaryOperator
+ * @typedef {{type: 7, op: string, left: AST, right: AST}} ASTBinaryOperator
+ * @typedef {{type: 8, fn: AST, args: AST[], kwargs: {[key: string]: AST}}} ASTFunctionCall
+ * @typedef {{type: 9, name: ASTName, value: AST}} ASTAssignment
+ * @typedef {{type: 10, value: AST[]}} ASTTuple
+ * @typedef {{type: 11, value: { [key: string]: AST}}} ASTDictionary
+ * @typedef {{type: 12, target: AST, key: AST}} ASTLookup
+ * @typedef {{type: 13, condition: AST, ifTrue: AST, ifFalse: AST}} ASTIf
+ * @typedef {{type: 14, op: string, left: AST, right: AST}} ASTBooleanOperator
+ * @typedef {{type: 15, obj: AST, key: string}} ASTObjLookup
+ *
+ * @typedef { ASTNumber | ASTString | ASTBoolean | ASTNone | ASTList | ASTName | ASTUnaryOperator | ASTBinaryOperator | ASTFunctionCall | ASTAssignment | ASTTuple | ASTDictionary |ASTLookup | ASTIf | ASTBooleanOperator | ASTObjLookup} AST
+ */
+
+export class ParserError extends Error {}
+
+// -----------------------------------------------------------------------------
+// Constants and helpers
+// -----------------------------------------------------------------------------
+
+const chainedOperators = new Set(comparators);
+const infixOperators = new Set(binaryOperators.concat(comparators));
+
+/**
+ * Compute the "binding power" of a symbol
+ *
+ * @param {string} symbol
+ * @returns {number}
+ */
+export function bp(symbol) {
+ switch (symbol) {
+ case "=":
+ return 10;
+ case "if":
+ return 20;
+ case "in":
+ case "not in":
+ case "is":
+ case "is not":
+ case "<":
+ case "<=":
+ case ">":
+ case ">=":
+ case "<>":
+ case "==":
+ case "!=":
+ return 60;
+ case "or":
+ return 30;
+ case "and":
+ return 40;
+ case "not":
+ return 50;
+ case "|":
+ return 70;
+ case "^":
+ return 80;
+ case "&":
+ return 90;
+ case "<<":
+ case ">>":
+ return 100;
+ case "+":
+ case "-":
+ return 110;
+ case "*":
+ case "/":
+ case "//":
+ case "%":
+ return 120;
+ case "**":
+ return 140;
+ case ".":
+ case "(":
+ case "[":
+ return 150;
+ }
+ return 0;
+}
+
+/**
+ * Compute binding power of a symbol
+ *
+ * @param {Token} token
+ * @returns {number}
+ */
+function bindingPower(token) {
+ return token.type === 2 /* Symbol */ ? bp(token.value) : 0;
+}
+
+/**
+ * Check if a token is a symbol of a given value
+ *
+ * @param {Token} token
+ * @param {string} value
+ * @returns {boolean}
+ */
+function isSymbol(token, value) {
+ return token.type === 2 /* Symbol */ && token.value === value;
+}
+
+/**
+ * @param {Token} current
+ * @param {Token[]} tokens
+ * @returns {AST}
+ */
+function parsePrefix(current, tokens) {
+ switch (current.type) {
+ case 0 /* Number */:
+ return { type: 0 /* Number */, value: current.value };
+ case 1 /* String */:
+ return { type: 1 /* String */, value: current.value };
+ case 4 /* Constant */:
+ if (current.value === "None") {
+ return { type: 3 /* None */ };
+ } else {
+ return { type: 2 /* Boolean */, value: current.value === "True" };
+ }
+ case 3 /* Name */:
+ return { type: 5 /* Name */, value: current.value };
+ case 2 /* Symbol */:
+ switch (current.value) {
+ case "-":
+ case "+":
+ case "~":
+ return {
+ type: 6 /* UnaryOperator */,
+ op: current.value,
+ right: _parse(tokens, 130),
+ };
+ case "not":
+ return {
+ type: 6 /* UnaryOperator */,
+ op: current.value,
+ right: _parse(tokens, 50),
+ };
+ case "(":
+ const content = [];
+ let isTuple = false;
+ while (tokens[0] && !isSymbol(tokens[0], ")")) {
+ content.push(_parse(tokens, 0));
+ if (tokens[0]) {
+ if (tokens[0] && isSymbol(tokens[0], ",")) {
+ isTuple = true;
+ tokens.shift();
+ } else if (!isSymbol(tokens[0], ")")) {
+ throw new ParserError("parsing error");
+ }
+ } else {
+ throw new ParserError("parsing error");
+ }
+ }
+ if (!tokens[0] || !isSymbol(tokens[0], ")")) {
+ throw new ParserError("parsing error");
+ }
+ tokens.shift();
+ isTuple = isTuple || content.length === 0;
+ return isTuple ? { type: 10 /* Tuple */, value: content } : content[0];
+ case "[":
+ const value = [];
+ while (tokens[0] && !isSymbol(tokens[0], "]")) {
+ value.push(_parse(tokens, 0));
+ if (tokens[0]) {
+ if (isSymbol(tokens[0], ",")) {
+ tokens.shift();
+ } else if (!isSymbol(tokens[0], "]")) {
+ throw new ParserError("parsing error");
+ }
+ }
+ }
+ if (!tokens[0] || !isSymbol(tokens[0], "]")) {
+ throw new ParserError("parsing error");
+ }
+ tokens.shift();
+ return { type: 4 /* List */, value };
+ case "{": {
+ const dict = {};
+ while (tokens[0] && !isSymbol(tokens[0], "}")) {
+ const key = _parse(tokens, 0);
+ if (
+ (key.type !== 1 /* String */ && key.type !== 0) /* Number */ ||
+ !tokens[0] ||
+ !isSymbol(tokens[0], ":")
+ ) {
+ throw new ParserError("parsing error");
+ }
+ tokens.shift();
+ const value = _parse(tokens, 0);
+ dict[key.value] = value;
+ if (isSymbol(tokens[0], ",")) {
+ tokens.shift();
+ }
+ }
+ // remove the } token
+ if (!tokens.shift()) {
+ throw new ParserError("parsing error");
+ }
+ return { type: 11 /* Dictionary */, value: dict };
+ }
+ }
+ }
+ throw new ParserError("Token cannot be parsed");
+}
+
+/**
+ * @param {AST} ast
+ * @param {Token} current
+ * @param {Token[]} tokens
+ * @returns {AST}
+ */
+function parseInfix(left, current, tokens) {
+ switch (current.type) {
+ case 2 /* Symbol */:
+ if (infixOperators.has(current.value)) {
+ let right = _parse(tokens, bindingPower(current));
+ if (current.value === "and" || current.value === "or") {
+ return {
+ type: 14 /* BooleanOperator */,
+ op: current.value,
+ left,
+ right,
+ };
+ } else if (current.value === ".") {
+ if (right.type === 5 /* Name */) {
+ return {
+ type: 15 /* ObjLookup */,
+ obj: left,
+ key: right.value,
+ };
+ } else {
+ throw new ParserError("invalid obj lookup");
+ }
+ }
+ let op = {
+ type: 7 /* BinaryOperator */,
+ op: current.value,
+ left,
+ right,
+ };
+ while (
+ chainedOperators.has(current.value) &&
+ tokens[0] &&
+ tokens[0].type === 2 /* Symbol */ &&
+ chainedOperators.has(tokens[0].value)
+ ) {
+ const nextToken = tokens.shift();
+ op = {
+ type: 14 /* BooleanOperator */,
+ op: "and",
+ left: op,
+ right: {
+ type: 7 /* BinaryOperator */,
+ op: nextToken.value,
+ left: right,
+ right: _parse(tokens, bindingPower(nextToken)),
+ },
+ };
+ right = op.right.right;
+ }
+ return op;
+ }
+ switch (current.value) {
+ case "(":
+ // function call
+ const args = [];
+ const kwargs = {};
+ while (tokens[0] && !isSymbol(tokens[0], ")")) {
+ const arg = _parse(tokens, 0);
+ if (arg.type === 9 /* Assignment */) {
+ kwargs[arg.name.value] = arg.value;
+ } else {
+ args.push(arg);
+ }
+ if (tokens[0] && isSymbol(tokens[0], ",")) {
+ tokens.shift();
+ }
+ }
+ if (!tokens[0] || !isSymbol(tokens[0], ")")) {
+ throw new ParserError("parsing error");
+ }
+ tokens.shift();
+ return { type: 8 /* FunctionCall */, fn: left, args, kwargs };
+ case "=":
+ if (left.type === 5 /* Name */) {
+ return {
+ type: 9 /* Assignment */,
+ name: left,
+ value: _parse(tokens, 10),
+ };
+ }
+ case "[": {
+ // lookup in dictionary
+ const key = _parse(tokens);
+ if (!tokens[0] || !isSymbol(tokens[0], "]")) {
+ throw new ParserError("parsing error");
+ }
+ tokens.shift();
+ return {
+ type: 12 /* Lookup */,
+ target: left,
+ key: key,
+ };
+ }
+ case "if": {
+ const condition = _parse(tokens);
+ if (!tokens[0] || !isSymbol(tokens[0], "else")) {
+ throw new ParserError("parsing error");
+ }
+ tokens.shift();
+ const ifFalse = _parse(tokens);
+ return {
+ type: 13 /* If */,
+ condition,
+ ifTrue: left,
+ ifFalse,
+ };
+ }
+ }
+ }
+ throw new ParserError("Token cannot be parsed");
+}
+
+/**
+ * @param {Token[]} tokens
+ * @param {number} [bp]
+ * @returns {AST}
+ */
+function _parse(tokens, bp = 0) {
+ const token = tokens.shift();
+ let expr = parsePrefix(token, tokens);
+ while (tokens[0] && bindingPower(tokens[0]) > bp) {
+ expr = parseInfix(expr, tokens.shift(), tokens);
+ }
+ return expr;
+}
+
+// -----------------------------------------------------------------------------
+// Parse function
+// -----------------------------------------------------------------------------
+
+/**
+ * Parse a list of tokens
+ *
+ * @param {Token[]} tokens
+ * @returns {AST}
+ */
+export function parse(tokens) {
+ return _parse(tokens, 0);
+}
diff --git a/addons/web/static/src/core/py_js/py_tokenizer.js b/addons/web/static/src/core/py_js/py_tokenizer.js
new file mode 100644
index 00000000000..3ad1f6dfc9d
--- /dev/null
+++ b/addons/web/static/src/core/py_js/py_tokenizer.js
@@ -0,0 +1,314 @@
+/** @odoo-module **/
+
+// -----------------------------------------------------------------------------
+// Types
+// -----------------------------------------------------------------------------
+
+/**
+ * @typedef {{type: 0, value: number}} TokenNumber
+ *
+ * @typedef {{type: 1, value: string}} TokenString
+ *
+ * @typedef {{type: 2, value: string}} TokenSymbol
+ *
+ * @typedef {{type: 3, value: string}} TokenName
+ *
+ * @typedef {{type: 4, value: string}} TokenConstant
+ *
+ * @typedef {TokenNumber | TokenString | TokenSymbol | TokenName | TokenConstant} Token
+ */
+
+export class TokenizerError extends Error {}
+
+// -----------------------------------------------------------------------------
+// Helpers and Constants
+// -----------------------------------------------------------------------------
+
+/**
+ * Directly maps a single escape code to an output character
+ */
+const directMap = {
+ "\\": "\\",
+ '"': '"',
+ "'": "'",
+ a: "\x07",
+ b: "\x08",
+ f: "\x0c",
+ n: "\n",
+ r: "\r",
+ t: "\t",
+ v: "\v",
+};
+
+/**
+ * Implements the decoding of Python string literals (embedded in
+ * JS strings) into actual JS strings. This includes the decoding
+ * of escapes into their corresponding JS
+ * characters/codepoints/whatever.
+ *
+ * The ``unicode`` flags notes whether the literal should be
+ * decoded as a bytestring literal or a unicode literal, which
+ * pretty much only impacts decoding (or not) of unicode escapes
+ * at this point since bytestrings are not technically handled
+ * (everything is decoded to JS "unicode" strings)
+ *
+ * Eventurally, ``str`` could eventually use typed arrays, that'd
+ * be interesting...
+ *
+ * @param {string} str
+ * @param {boolean} unicode
+ * @returns {string}
+ */
+function decodeStringLiteral(str, unicode) {
+ let out = [];
+ let code;
+ for (var i = 0; i < str.length; ++i) {
+ if (str[i] !== "\\") {
+ out.push(str[i]);
+ continue;
+ }
+ var escape = str[i + 1];
+ if (escape in directMap) {
+ out.push(directMap[escape]);
+ ++i;
+ continue;
+ }
+ switch (escape) {
+ // Ignored
+ case "\n":
+ ++i;
+ continue;
+ // Character named name in the Unicode database (Unicode only)
+ case "N":
+ if (!unicode) {
+ break;
+ }
+ throw new TokenizerError("SyntaxError: \\N{} escape not implemented");
+ case "u":
+ if (!unicode) {
+ break;
+ }
+ var uni = str.slice(i + 2, i + 6);
+ if (!/[0-9a-f]{4}/i.test(uni)) {
+ throw new TokenizerError(
+ [
+ "SyntaxError: (unicode error) 'unicodeescape' codec",
+ " can't decode bytes in position ",
+ i,
+ "-",
+ i + 4,
+ ": truncated \\uXXXX escape",
+ ].join("")
+ );
+ }
+ code = parseInt(uni, 16);
+ out.push(String.fromCharCode(code));
+ // escape + 4 hex digits
+ i += 5;
+ continue;
+ case "U":
+ if (!unicode) {
+ break;
+ }
+ // TODO: String.fromCodePoint
+ throw new TokenizerError("SyntaxError: \\U escape not implemented");
+ case "x":
+ // get 2 hex digits
+ var hex = str.slice(i + 2, i + 4);
+ if (!/[0-9a-f]{2}/i.test(hex)) {
+ if (!unicode) {
+ throw new TokenizerError("ValueError: invalid \\x escape");
+ }
+ throw new TokenizerError(
+ [
+ "SyntaxError: (unicode error) 'unicodeescape'",
+ " codec can't decode bytes in position ",
+ i,
+ "-",
+ i + 2,
+ ": truncated \\xXX escape",
+ ].join("")
+ );
+ }
+ code = parseInt(hex, 16);
+ out.push(String.fromCharCode(code));
+ // skip escape + 2 hex digits
+ i += 3;
+ continue;
+ default:
+ // Check if octal
+ if (!/[0-8]/.test(escape)) {
+ break;
+ }
+ var r = /[0-8]{1,3}/g;
+ r.lastIndex = i + 1;
+ var m = r.exec(str);
+ var oct = m[0];
+ code = parseInt(oct, 8);
+ out.push(String.fromCharCode(code));
+ // skip matchlength
+ i += oct.length;
+ continue;
+ }
+ out.push("\\");
+ }
+ return out.join("");
+}
+
+const constants = new Set(["None", "False", "True"]);
+
+export const comparators = [
+ "in",
+ "not",
+ "not in",
+ "is",
+ "is not",
+ "<",
+ "<=",
+ ">",
+ ">=",
+ "<>",
+ "!=",
+ "==",
+];
+
+export const binaryOperators = [
+ "or",
+ "and",
+ "|",
+ "^",
+ "&",
+ "<<",
+ ">>",
+ "+",
+ "-",
+ "*",
+ "/",
+ "//",
+ "%",
+ "~",
+ "**",
+ ".",
+];
+
+export const unaryOperators = ["-"];
+
+const symbols = new Set([
+ ...["(", ")", "[", "]", "{", "}", ":", ","],
+ ...["if", "else", "lambda", "="],
+ ...comparators,
+ ...binaryOperators,
+ ...unaryOperators,
+]);
+
+// Regexps
+function group(...args) {
+ return "(" + args.join("|") + ")";
+}
+
+const Name = "[a-zA-Z_]\\w*";
+const Whitespace = "[ \\f\\t]*";
+const DecNumber = "\\d+(L|l)?";
+const IntNumber = DecNumber;
+const PointFloat = group("\\d+\\.\\d*", "\\.\\d+");
+const FloatNumber = PointFloat;
+const Number = group(FloatNumber, IntNumber);
+const Operator = group("\\*\\*=?", ">>=?", "<<=?", "<>", "!=", "//=?", "[+\\-*/%&|^=<>]=?", "~");
+const Bracket = "[\\[\\]\\(\\)\\{\\}]";
+const Special = "[:;.,`@]";
+const Funny = group(Operator, Bracket, Special);
+const ContStr = group(
+ "([uU])?'([^\n'\\\\]*(?:\\\\.[^\n'\\\\]*)*)'",
+ '([uU])?"([^\n"\\\\]*(?:\\\\.[^\n"\\\\]*)*)"'
+);
+const PseudoToken = Whitespace + group(Number, Funny, ContStr, Name);
+const NumberPattern = new RegExp("^" + Number + "$");
+const StringPattern = new RegExp("^" + ContStr + "$");
+const NamePattern = new RegExp("^" + Name + "$");
+const strip = new RegExp("^" + Whitespace);
+
+// -----------------------------------------------------------------------------
+// Tokenize function
+// -----------------------------------------------------------------------------
+
+/**
+ * Transform a string into a list of tokens
+ *
+ * @param {string} str
+ * @returns {Token[]}
+ */
+export function tokenize(str) {
+ const tokens = [];
+ let max = str.length;
+ let start = 0;
+ let end = 0;
+ // /g flag makes repeated exec() have memory
+ const pseudoprog = new RegExp(PseudoToken, "g");
+ while (pseudoprog.lastIndex < max) {
+ const pseudomatch = pseudoprog.exec(str);
+ if (!pseudomatch) {
+ // if match failed on trailing whitespace, end tokenizing
+ if (/^\s+$/.test(str.slice(end))) {
+ break;
+ }
+ throw new TokenizerError(
+ "Failed to tokenize <<" +
+ str +
+ ">> at index " +
+ (end || 0) +
+ "; parsed so far: " +
+ tokens
+ );
+ }
+ if (pseudomatch.index > end) {
+ if (str.slice(end, pseudomatch.index).trim()) {
+ throw new TokenizerError("Invalid expression");
+ }
+ }
+ start = pseudomatch.index;
+ end = pseudoprog.lastIndex;
+ let token = str.slice(start, end).replace(strip, "");
+ if (NumberPattern.test(token)) {
+ tokens.push({
+ type: 0 /* Number */,
+ value: parseFloat(token),
+ });
+ } else if (StringPattern.test(token)) {
+ var m = StringPattern.exec(token);
+ tokens.push({
+ type: 1 /* String */,
+ value: decodeStringLiteral(m[3] !== undefined ? m[3] : m[5], !!(m[2] || m[4])),
+ });
+ } else if (symbols.has(token)) {
+ // transform 'not in' and 'is not' in a single token
+ if (token === "in" && tokens.length > 0 && tokens[tokens.length - 1].value === "not") {
+ token = "not in";
+ tokens.pop();
+ } else if (
+ token === "not" &&
+ tokens.length > 0 &&
+ tokens[tokens.length - 1].value === "is"
+ ) {
+ token = "is not";
+ tokens.pop();
+ }
+ tokens.push({
+ type: 2 /* Symbol */,
+ value: token,
+ });
+ } else if (constants.has(token)) {
+ tokens.push({
+ type: 4 /* Constant */,
+ value: token,
+ });
+ } else if (NamePattern.test(token)) {
+ tokens.push({
+ type: 3 /* Name */,
+ value: token,
+ });
+ } else {
+ throw new TokenizerError("Invalid expression");
+ }
+ }
+ return tokens;
+}
diff --git a/addons/web/static/src/core/py_js/py_utils.js b/addons/web/static/src/core/py_js/py_utils.js
new file mode 100644
index 00000000000..cbd0ec2d1a0
--- /dev/null
+++ b/addons/web/static/src/core/py_js/py_utils.js
@@ -0,0 +1,137 @@
+/** @odoo-module **/
+
+import { bp } from "./py_parser";
+
+// -----------------------------------------------------------------------------
+// Types
+// -----------------------------------------------------------------------------
+
+/**
+ * @typedef { import("./py_parser").AST } AST
+ */
+
+// -----------------------------------------------------------------------------
+// Utils
+// -----------------------------------------------------------------------------
+
+/**
+ * @param {any[]} args
+ * @param {string[]} spec
+ * @returns {{[name: string]: any}}
+ */
+export function parseArgs(args, spec) {
+ const last = args[args.length - 1];
+ const unnamedArgs = typeof last === "object" ? args.slice(0, -1) : args;
+ const kwargs = typeof last === "object" ? last : {};
+ for (let [index, val] of unnamedArgs.entries()) {
+ kwargs[spec[index]] = val;
+ }
+ return kwargs;
+}
+
+/**
+ * Represent any value as a primitive AST
+ *
+ * @param {any} value
+ * @returns {AST}
+ */
+export function toPyValue(value) {
+ switch (typeof value) {
+ case "string":
+ return { type: 1 /* String */, value };
+ case "number":
+ return { type: 0 /* Number */, value };
+ case "boolean":
+ return { type: 2 /* Boolean */, value };
+ case "object":
+ if (Array.isArray(value)) {
+ return { type: 4 /* List */, value: value.map(toPyValue) };
+ } else if (value === null) {
+ return { type: 3 /* None */ };
+ } else {
+ const content = {};
+ for (let key in value) {
+ content[key] = toPyValue(value[key]);
+ }
+ return { type: 11 /* Dictionary */, value: content };
+ }
+ default:
+ throw new Error("Invalid type");
+ }
+}
+
+/**
+ * @param {AST} ast
+ * @param {number} [lbp] left binding power
+ * @return {string}
+ */
+export function formatAST(ast, lbp = 0) {
+ switch (ast.type) {
+ case 3 /* None */:
+ return "None";
+ case 1 /* String */:
+ return JSON.stringify(ast.value);
+ case 0 /* Number */:
+ return String(ast.value);
+ case 2 /* Boolean */:
+ return ast.value ? "True" : "False";
+ case 4 /* List */:
+ return `[${ast.value.map(formatAST).join(", ")}]`;
+ case 6 /* UnaryOperator */:
+ if (ast.op === "not") {
+ return `not ` + formatAST(ast.right, 50);
+ }
+ return ast.op + formatAST(ast.right, 130);
+ case 7 /* BinaryOperator */: {
+ const abp = bp(ast.op);
+ const str = `${formatAST(ast.left, abp)} ${ast.op} ${formatAST(ast.right, abp)}`;
+ return abp < lbp ? `(${str})` : str;
+ }
+ case 11 /* Dictionary */: {
+ const pairs = [];
+ for (let k in ast.value) {
+ pairs.push(`"${k}": ${formatAST(ast.value[k])}`);
+ }
+ return `{` + pairs.join(", ") + `}`;
+ }
+ case 10 /* Tuple */:
+ return `(${ast.value.map(formatAST).join(", ")})`;
+ case 5 /* Name */:
+ return ast.value;
+ case 12 /* Lookup */: {
+ return `${formatAST(ast.target)}[${formatAST(ast.key)}]`;
+ }
+ case 13 /* If */: {
+ const { ifTrue, condition, ifFalse } = ast;
+ return `${formatAST(ifTrue)} if ${formatAST(condition)} else ${formatAST(ifFalse)}`;
+ }
+ case 14 /* BooleanOperator */: {
+ const abp = bp(ast.op);
+ const str = `${formatAST(ast.left, abp)} ${ast.op} ${formatAST(ast.right, abp)}`;
+ return abp < lbp ? `(${str})` : str;
+ }
+ case 15 /* ObjLookup */:
+ return `${formatAST(ast.obj, 150)}.${ast.key}`;
+ case 8 /* FunctionCall */: {
+ const args = ast.args.map(formatAST);
+ const kwargs = [];
+ for (let kwarg in ast.kwargs) {
+ kwargs.push(`${kwarg} = ${formatAST(ast.kwargs[kwarg])}`);
+ }
+ const argStr = args.concat(kwargs).join(", ");
+ return `${formatAST(ast.fn)}(${argStr})`;
+ }
+ }
+ throw new Error("invalid expression: " + ast);
+}
+
+export const PY_DICT = Object.create(null);
+
+/**
+ * @param {Object} obj
+ * @returns {AST} a python dictionary
+ */
+export function toPyDict(obj) {
+ const result = Object.create(PY_DICT);
+ return Object.assign(result, obj);
+}
diff --git a/addons/web/static/src/core/registry.js b/addons/web/static/src/core/registry.js
new file mode 100644
index 00000000000..5cd3f2a47b4
--- /dev/null
+++ b/addons/web/static/src/core/registry.js
@@ -0,0 +1,144 @@
+/** @odoo-module **/
+
+const { core } = owl;
+const { EventBus } = core;
+
+// -----------------------------------------------------------------------------
+// Errors
+// -----------------------------------------------------------------------------
+export class KeyNotFoundError extends Error {}
+
+export class DuplicatedKeyError extends Error {}
+
+/**
+ * Registry
+ *
+ * The Registry class is basically just a mapping from a string key to an object.
+ * It is really not much more than an object. It is however useful for the
+ * following reasons:
+ *
+ * 1. it let us react and execute code when someone add something to the registry
+ * (for example, the FunctionRegistry subclass this for this purpose)
+ * 2. it throws an error when the get operation fails
+ * 3. it provides a chained API to add items to the registry.
+ */
+export class Registry extends EventBus {
+ constructor() {
+ super();
+ this.content = {};
+ this.subRegistries = {};
+ this.elements = null;
+ this.entries = null;
+
+ this.on("UPDATE", this, () => {
+ this.elements = null;
+ this.entries = null;
+ });
+ }
+
+ /**
+ * Add an entry (key, value) to the registry if key is not already used. If
+ * the parameter force is set to true, an entry with same key (if any) is replaced.
+ *
+ * Note that this also returns the registry, so another add method call can
+ * be chained
+ *
+ * @param {string} key
+ * @param {any} value
+ * @param {{force?: boolean, sequence?: number}} [options]
+ * @returns {Registry}
+ */
+ add(key, value, { force, sequence } = {}) {
+ if (!force && key in this.content) {
+ throw new DuplicatedKeyError(`Cannot add '${key}' in this registry: it already exists`);
+ }
+ let previousSequence;
+ if (force) {
+ const elem = this.content[key];
+ previousSequence = elem && elem[0];
+ }
+ sequence = sequence === undefined ? previousSequence || 50 : sequence;
+ this.content[key] = [sequence, value];
+ const payload = { operation: "add", key, value };
+ this.trigger("UPDATE", payload);
+ return this;
+ }
+
+ /**
+ * Get an item from the registry
+ *
+ * @param {string} key
+ * @returns {any}
+ */
+ get(key, defaultValue) {
+ if (arguments.length < 2 && !(key in this.content)) {
+ throw new KeyNotFoundError(`Cannot find ${key} in this registry!`);
+ }
+ const info = this.content[key];
+ return info ? info[1] : defaultValue;
+ }
+
+ /**
+ * Check the presence of a key in the registry
+ *
+ * @param {string} key
+ * @returns {boolean}
+ */
+ contains(key) {
+ return key in this.content;
+ }
+
+ /**
+ * Get a list of all elements in the registry. Note that it is ordered
+ * according to the sequence numbers.
+ *
+ * @returns {any[]}
+ */
+ getAll() {
+ if (!this.elements) {
+ const content = Object.values(this.content).sort((el1, el2) => el1[0] - el2[0]);
+ this.elements = content.map((elem) => elem[1]);
+ }
+ return this.elements;
+ }
+
+ /**
+ * Return a list of all entries, ordered by sequence numbers.
+ *
+ * @returns {[string, any][]}
+ */
+ getEntries() {
+ if (!this.entries) {
+ const entries = Object.entries(this.content).sort((el1, el2) => el1[1][0] - el2[1][0]);
+ this.entries = entries.map(([str, elem]) => [str, elem[1]]);
+ }
+ return this.entries;
+ }
+
+ /**
+ * Remove an item from the registry
+ *
+ * @param {string} key
+ */
+ remove(key) {
+ const value = this.content[key];
+ delete this.content[key];
+ const payload = { operation: "delete", key, value };
+ this.trigger("UPDATE", payload);
+ }
+
+ /**
+ * Open a sub registry (and create it if necessary)
+ *
+ * @param {string} subcategory
+ * @returns {Registry}
+ */
+ category(subcategory) {
+ if (!(subcategory in this.subRegistries)) {
+ this.subRegistries[subcategory] = new Registry();
+ }
+ return this.subRegistries[subcategory];
+ }
+}
+
+export const registry = new Registry();
diff --git a/addons/web/static/src/core/scroller_service.js b/addons/web/static/src/core/scroller_service.js
new file mode 100644
index 00000000000..aafd57dc6cf
--- /dev/null
+++ b/addons/web/static/src/core/scroller_service.js
@@ -0,0 +1,54 @@
+/** @odoo-module **/
+
+import { browser } from "./browser/browser";
+import { registry } from "./registry";
+import { scrollTo } from "./utils/scrolling";
+
+export const scrollerService = {
+ start() {
+ /**
+ * Listen to click event to allow having links with href towards an anchor.
+ * Since odoo use hashtag to represent the current state of the view, we can't
+ * easily distinguish between a link towards an anchor and a link towards
+ * another view/state. If we want to navigate towards an anchor, we must not
+ * change the hash of the url otherwise we will be redirected to the app switcher
+ * instead To check if we have an anchor, first check if we have an href
+ * attribute starting with #. Try to find a element in the DOM using JQuery
+ * selector. If we have a match, it means that it is probably a link to an
+ * anchor, so we jump to that anchor.
+ *
+ * @param {MouseEvent} ev
+ */
+ browser.addEventListener("click", (ev) => {
+ const link = ev.target.closest("a");
+ if (!link) {
+ return;
+ }
+ const disableAnchor = link.attributes.getNamedItem("disable_anchor");
+ if (disableAnchor && disableAnchor.value === "true") {
+ return;
+ }
+ const href = link.attributes.getNamedItem("href");
+ if (href) {
+ if (href.value[0] === "#") {
+ if (href.value.length === 1) {
+ ev.preventDefault(); // single hash in href are just a way to activate A-tags node
+ return;
+ }
+ let matchingEl = null;
+ try {
+ matchingEl = document.querySelector(`.o_content #${href.value.substr(1)}`);
+ } catch (e) {
+ // Invalid selector: not an anchor anyway
+ }
+ if (matchingEl) {
+ ev.preventDefault();
+ scrollTo(matchingEl);
+ }
+ }
+ }
+ });
+ },
+};
+
+registry.category("services").add("scroller", scrollerService);
diff --git a/addons/web/static/src/core/service_hook.js b/addons/web/static/src/core/service_hook.js
new file mode 100644
index 00000000000..5fd2f4ef321
--- /dev/null
+++ b/addons/web/static/src/core/service_hook.js
@@ -0,0 +1,43 @@
+/** @odoo-module **/
+
+import { SERVICES_METADATA } from "../env";
+
+const { useComponent } = owl.hooks;
+
+/**
+ * Import a service into a component
+ *
+ * @param {string} serviceName
+ * @returns {any}
+ */
+export function useService(serviceName) {
+ const component = useComponent();
+ const { services } = component.env;
+ if (!(serviceName in services)) {
+ throw new Error(`Service ${serviceName} is not available`);
+ }
+ const service = services[serviceName];
+ if (serviceName in SERVICES_METADATA) {
+ if (service instanceof Function) {
+ return protectMethod(component, null, service);
+ } else {
+ const methods = SERVICES_METADATA[serviceName];
+ const result = Object.create(service);
+ for (let method of methods) {
+ result[method] = protectMethod(component, service, service[method]);
+ }
+ return result;
+ }
+ }
+ return service;
+}
+
+function protectMethod(component, caller, fn) {
+ return async (...args) => {
+ if (component.__owl__.status === 5 /* DESTROYED */) {
+ throw new Error("Component is destroyed");
+ }
+ const result = await fn.call(caller, ...args);
+ return component.__owl__.status === 5 ? new Promise(() => {}) : result;
+ };
+}
diff --git a/addons/web/static/src/core/ui/block_ui.js b/addons/web/static/src/core/ui/block_ui.js
new file mode 100644
index 00000000000..85a5806f948
--- /dev/null
+++ b/addons/web/static/src/core/ui/block_ui.js
@@ -0,0 +1,84 @@
+/** @odoo-module **/
+
+import { browser } from "@web/core/browser/browser";
+
+const { Component, tags, useState } = owl;
+
+export class BlockUI extends Component {
+ setup() {
+ this.messagesByDuration = [
+ { time: 20, l1: this.env._t("Loading...") },
+ { time: 40, l1: this.env._t("Still loading...") },
+ {
+ time: 60,
+ l1: this.env._t("Still loading..."),
+ l2: this.env._t("Please be patient."),
+ },
+ {
+ time: 180,
+ l1: this.env._t("Don't leave yet,"),
+ l2: this.env._t("it's still loading..."),
+ },
+ {
+ time: 120,
+ l1: this.env._t("You may not believe it,"),
+ l2: this.env._t("but the application is actually loading..."),
+ },
+ {
+ time: 3180,
+ l1: this.env._t("Take a minute to get a coffee,"),
+ l2: this.env._t("because it's loading..."),
+ },
+ {
+ time: null,
+ l1: this.env._t(
+ "Maybe you should consider reloading the application by pressing F5..."
+ ),
+ },
+ ];
+ this.state = useState({
+ blockUI: false,
+ line1: "",
+ line2: "",
+ });
+
+ this.props.bus.on("BLOCK", this, this.block);
+ this.props.bus.on("UNBLOCK", this, this.unblock);
+ }
+
+ replaceMessage(index) {
+ const message = this.messagesByDuration[index];
+ this.state.line1 = message.l1;
+ this.state.line2 = message.l2 || "";
+ if (message.time !== null) {
+ this.msgTimer = browser.setTimeout(() => {
+ this.replaceMessage(index + 1);
+ }, message.time * 1000);
+ }
+ }
+
+ block() {
+ this.state.blockUI = true;
+ this.replaceMessage(0);
+ }
+
+ unblock() {
+ this.state.blockUI = false;
+ clearTimeout(this.msgTimer);
+ this.state.line1 = "";
+ this.state.line2 = "";
+ }
+}
+
+BlockUI.template = tags.xml`
+
+
+
+
+
+
+
+
+
+
+
`;
diff --git a/addons/web/static/src/core/ui/block_ui.scss b/addons/web/static/src/core/ui/block_ui.scss
new file mode 100644
index 00000000000..c75a769b306
--- /dev/null
+++ b/addons/web/static/src/core/ui/block_ui.scss
@@ -0,0 +1,31 @@
+.o_blockUI {
+ position: absolute;
+ top: 0;
+ left: 0;
+ z-index: 1100;
+
+ cursor: wait;
+ background: #000000;
+ opacity: 0.6;
+ height: 100vh;
+ width: 100vw;
+
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ flex-direction: column;
+
+ .o_spinner {
+ height: 4.2rem;
+ margin-bottom: 1rem;
+
+ img {
+ animation: fa-spin 1s infinite steps(12);
+ }
+ }
+
+ .o_message {
+ color: #ffffff;
+ text-align: center;
+ }
+}
diff --git a/addons/web/static/src/core/ui/ui_service.js b/addons/web/static/src/core/ui/ui_service.js
new file mode 100644
index 00000000000..59d9a1a9e45
--- /dev/null
+++ b/addons/web/static/src/core/ui/ui_service.js
@@ -0,0 +1,143 @@
+/** @odoo-module **/
+
+import { useService } from "@web/core/service_hook";
+import { registry } from "@web/core/registry";
+import { debounce } from "@web/core/utils/timing";
+import { useEffect } from "@web/core/effect_hook";
+import { BlockUI } from "./block_ui";
+
+const { Component, core, hooks } = owl;
+const { EventBus } = core;
+const { useRef } = hooks;
+
+export const SIZES = { XS: 0, VSM: 1, SM: 2, MD: 3, LG: 4, XL: 5, XXL: 6 };
+
+/**
+ * This hook will set the UI active element
+ * when the caller component will mount/unmount.
+ *
+ * The caller component could pass a `t-ref` value of its template
+ * to delegate the UI active element to another element than itself.
+ * In that case, it is mandatory that the referenced element is fixed and
+ * not dynamically attached in/detached from the DOM (e.g. with t-if directive).
+ *
+ * @param {string} refName
+ */
+export function useActiveElement(refName = null) {
+ const uiService = useService("ui");
+ const owner = refName ? useRef(refName) : Component.current;
+ useEffect(
+ () => {
+ uiService.activateElement(owner.el);
+ return () => uiService.deactivateElement(owner.el);
+ },
+ () => []
+ );
+}
+
+export const uiService = {
+ start(env) {
+ let ui = {};
+
+ // block/unblock code
+ const bus = new EventBus();
+ registry.category("main_components").add("BlockUI", { Component: BlockUI, props: { bus } });
+
+ let blockCount = 0;
+ function block() {
+ blockCount++;
+ if (blockCount === 1) {
+ bus.trigger("BLOCK");
+ }
+ }
+ function unblock() {
+ blockCount = Math.max(0, blockCount - 1);
+ if (blockCount === 0) {
+ bus.trigger("UNBLOCK");
+ }
+ }
+
+ Object.assign(ui, {
+ bus,
+ block,
+ unblock,
+ });
+
+ Object.defineProperty(ui, "isBlocked", {
+ get() {
+ return blockCount > 0;
+ },
+ });
+
+ // UI active element code
+ let activeElems = [document];
+
+ function activateElement(el) {
+ activeElems.push(el);
+ bus.trigger("active-element-changed", el);
+ }
+ function deactivateElement(el) {
+ activeElems = activeElems.filter((x) => x !== el);
+ bus.trigger("active-element-changed", ui.activeElement);
+ }
+ function getVisibleElements(selector) {
+ const visibleElements = [];
+ for (const el of ui.activeElement.querySelectorAll(selector)) {
+ const isVisible = el.offsetWidth > 0 && el.offsetHeight > 0;
+ if (isVisible) {
+ visibleElements.push(el);
+ }
+ }
+ return visibleElements;
+ }
+
+ Object.assign(ui, {
+ activateElement,
+ deactivateElement,
+ getVisibleElements,
+ });
+ Object.defineProperty(ui, "activeElement", {
+ get() {
+ return activeElems[activeElems.length - 1];
+ },
+ });
+
+ // window size handling
+ const MEDIAS = [
+ window.matchMedia("(max-width: 474px)"),
+ window.matchMedia("(min-width: 475px) and (max-width: 575px)"),
+ window.matchMedia("(min-width: 576px) and (max-width: 767px)"),
+ window.matchMedia("(min-width: 768px) and (max-width: 991px)"),
+ window.matchMedia("(min-width: 992px) and (max-width: 1199px)"),
+ window.matchMedia("(min-width: 1200px) and (max-width: 1533px)"),
+ window.matchMedia("(min-width: 1534px)"),
+ ];
+ function getSize() {
+ return MEDIAS.findIndex((media) => media.matches);
+ }
+
+ // listen to media query status changes
+ function updateSize() {
+ ui.size = getSize();
+ }
+ MEDIAS.forEach((media) => media.addEventListener("change", debounce(updateSize, 100)));
+
+ Object.assign(ui, {
+ size: getSize(),
+ });
+ Object.defineProperty(ui, "isSmall", {
+ get() {
+ return ui.size <= SIZES.SM;
+ },
+ });
+ Object.defineProperty(env, "isSmall", {
+ get() {
+ return ui.size <= SIZES.SM;
+ },
+ });
+
+ return ui;
+ },
+};
+
+registry.category("services").add("ui", uiService);
diff --git a/addons/web/static/src/core/user_service.js b/addons/web/static/src/core/user_service.js
new file mode 100644
index 00000000000..4a701687646
--- /dev/null
+++ b/addons/web/static/src/core/user_service.js
@@ -0,0 +1,69 @@
+/** @odoo-module **/
+
+import { registry } from "./registry";
+
+export const userService = {
+ dependencies: ["rpc"],
+ async: ["hasGroup"],
+ start(env, { rpc }) {
+ const sessionInfo = odoo.session_info;
+ const groupProms = {};
+
+ const context = {
+ ...sessionInfo.user_context,
+ uid: sessionInfo.uid,
+ };
+ return {
+ get context() {
+ return Object.assign({}, context);
+ },
+ removeFromContext(key) {
+ delete context[key];
+ },
+ updateContext(update) {
+ Object.assign(context, update);
+ },
+ hasGroup(group) {
+ if (!context.uid) {
+ return Promise.resolve(false);
+ }
+ if (!groupProms[group]) {
+ groupProms[group] = rpc("/web/dataset/call_kw/res.users/has_group", {
+ model: "res.users",
+ method: "has_group",
+ args: [group],
+ kwargs: { context },
+ });
+ }
+ return groupProms[group];
+ },
+ name: sessionInfo.name,
+ userName: sessionInfo.username,
+ isAdmin: sessionInfo.is_admin,
+ isSystem: sessionInfo.is_system,
+ partnerId: sessionInfo.partner_id,
+ home_action_id: sessionInfo.home_action_id,
+ showEffect: sessionInfo.show_effect,
+ get userId() {
+ return context.uid;
+ },
+ get lang() {
+ return context.lang;
+ },
+ get tz() {
+ return context.tz;
+ },
+ get db() {
+ const res = {
+ name: sessionInfo.db,
+ };
+ if ("dbuuid" in sessionInfo) {
+ res.uuid = sessionInfo.dbuuid;
+ }
+ return res;
+ },
+ };
+ },
+};
+
+registry.category("services").add("user", userService);
diff --git a/addons/web/static/src/core/utils/arrays.js b/addons/web/static/src/core/utils/arrays.js
new file mode 100644
index 00000000000..79d1d8a9fed
--- /dev/null
+++ b/addons/web/static/src/core/utils/arrays.js
@@ -0,0 +1,94 @@
+/** @odoo-module **/
+
+/**
+ * Helper function returning an extraction handler to use on array elements to
+ * return a certain attribute or mutated form of the element.
+ *
+ * @private
+ * @param {string | function} [criterion]
+ * @returns {(element: any) => any}
+ */
+function _getExtractorFrom(criterion) {
+ if (criterion) {
+ switch (typeof criterion) {
+ case "string":
+ return (element) => element[criterion];
+ case "function":
+ return criterion;
+ default:
+ throw new Error(
+ `Expected criterion of type 'string' or 'function' and got '${typeof criterion}'`
+ );
+ }
+ } else {
+ return (element) => element;
+ }
+}
+
+/**
+ * Returns an object holding different groups defined by a given criterion
+ * or a default one. Each group is a subset of the original given list.
+ * The given criterion can either be:
+ * - a string: a property name on the list elements which value will be the
+ * group name,
+ * - a function: a handler that will return the group name from a given
+ * element.
+ *
+ * @param {any[]} array
+ * @param {string | function} [criterion]
+ * @returns {Object}
+ */
+export function groupBy(array, criterion) {
+ const extract = _getExtractorFrom(criterion);
+ const groups = {};
+ for (const element of array) {
+ const group = String(extract(element));
+ if (!(group in groups)) {
+ groups[group] = [];
+ }
+ groups[group].push(element);
+ }
+ return groups;
+}
+
+/**
+ * Return a shallow copy of a given array sorted by a given criterion or a default one.
+ * The given criterion can either be:
+ * - a string: a property name on the array elements returning the sortable primitive
+ * - a function: a handler that will return the sortable primitive from a given element.
+ * The default order is ascending ('asc'). It can be modified by setting the extra param 'order' to 'desc'.
+ *
+ * @param {any[]} array
+ * @param {string | function} [criterion]
+ * @param {"asc" | "desc"} [order="asc"]
+ * @returns {any[]}
+ */
+export function sortBy(array, criterion, order = "asc") {
+ const extract = _getExtractorFrom(criterion);
+ return array.slice().sort((elA, elB) => {
+ const a = extract(elA);
+ const b = extract(elB);
+ let result;
+ if (isNaN(a) && isNaN(b)) {
+ result = a > b ? 1 : a < b ? -1 : 0;
+ } else {
+ result = a - b;
+ }
+ return order === "asc" ? result : -result;
+ });
+}
+
+/**
+ * Returns an array containing all the elements of arrayA
+ * that are not in arrayB and vice-versa.
+ *
+ * @param {any[]} arrayA
+ * @param {any[]} arrayB
+ * @returns an array containing all the elements of arrayA
+ * that are not in arrayB and vice-versa.
+ */
+export function symmetricalDifference(arrayA, arrayB) {
+ return arrayA
+ .filter((id) => !arrayB.includes(id))
+ .concat(arrayB.filter((id) => !arrayA.includes(id)));
+}
diff --git a/addons/web/static/src/core/utils/components.js b/addons/web/static/src/core/utils/components.js
new file mode 100644
index 00000000000..eedfab693e7
--- /dev/null
+++ b/addons/web/static/src/core/utils/components.js
@@ -0,0 +1,19 @@
+/** @odoo-module **/
+
+const { Component, tags } = owl;
+
+export class NotUpdatable extends Component {
+ shouldUpdate() {
+ return false;
+ }
+}
+NotUpdatable.template = tags.xml` `;
+
+export class ErrorHandler extends Component {
+ catchError(error) {
+ if (this.props.onError) {
+ this.props.onError(error);
+ }
+ }
+}
+ErrorHandler.template = tags.xml` `;
diff --git a/addons/web/static/src/core/utils/concurrency.js b/addons/web/static/src/core/utils/concurrency.js
new file mode 100644
index 00000000000..76e38c3d42e
--- /dev/null
+++ b/addons/web/static/src/core/utils/concurrency.js
@@ -0,0 +1,119 @@
+/** @odoo-module **/
+
+/**
+ * KeepLast is a concurrency primitive that manages a list of tasks, and only
+ * keeps the last task active.
+ */
+export class KeepLast {
+ constructor() {
+ this._id = 0;
+ }
+ /**
+ * Register a new task
+ *
+ * @template T
+ * @param {Promise} promise
+ * @returns {Promise}
+ */
+ add(promise) {
+ this._id++;
+ const currentId = this._id;
+ return new Promise((resolve, reject) => {
+ promise
+ .then((value) => {
+ if (this._id === currentId) {
+ resolve(value);
+ }
+ })
+ .catch((reason) => {
+ // not sure about this part
+ if (this._id === currentId) {
+ reject(reason);
+ }
+ });
+ });
+ }
+}
+
+/**
+ * A (Odoo) mutex is a primitive for serializing computations. This is
+ * useful to avoid a situation where two computations modify some shared
+ * state and cause some corrupted state.
+ *
+ * Imagine that we have a function to fetch some data _load(), which returns
+ * a promise which resolves to something useful. Now, we have some code
+ * looking like this::
+ *
+ * return this._load().then(function (result) {
+ * this.state = result;
+ * });
+ *
+ * If this code is run twice, but the second execution ends before the
+ * first, then the final state will be the result of the first call to
+ * _load. However, if we have a mutex::
+ *
+ * this.mutex = new Mutex();
+ *
+ * and if we wrap the calls to _load in a mutex::
+ *
+ * return this.mutex.exec(function() {
+ * return this._load().then(function (result) {
+ * this.state = result;
+ * });
+ * });
+ *
+ * Then, it is guaranteed that the final state will be the result of the
+ * second execution.
+ *
+ * A Mutex has to be a class, and not a function, because we have to keep
+ * track of some internal state.
+ */
+export class Mutex {
+ constructor() {
+ this._lock = Promise.resolve();
+ this._queueSize = 0;
+ this._unlockedProm = undefined;
+ this._unlock = undefined;
+ }
+ /**
+ * Add a computation to the queue, it will be executed as soon as the
+ * previous computations are completed.
+ *
+ * @param {function} action a function which may return a Promise
+ * @returns {Promise}
+ */
+ async exec(action) {
+ const currentLock = this._lock;
+ let result;
+ this._queueSize++;
+ this._unlockedProm =
+ this._unlockedProm ||
+ new Promise((resolve) => {
+ this._unlock = resolve;
+ });
+ this._lock = new Promise((unlockCurrent) => {
+ currentLock.then(() => {
+ result = action();
+ const always = (returnedResult) => {
+ unlockCurrent();
+ this._queueSize--;
+ if (this._queueSize === 0) {
+ this._unlockedProm = undefined;
+ this._unlock();
+ }
+ return returnedResult;
+ };
+ Promise.resolve(result).then(always).guardedCatch(always);
+ });
+ });
+ await this._lock;
+ return result;
+ }
+ /**
+ * @returns {Promise} resolved as soon as the Mutex is unlocked
+ * (directly if it is currently idle)
+ */
+ getUnlockedDef() {
+ return this._unlockedProm || Promise.resolve();
+ }
+}
diff --git a/addons/web/static/src/core/utils/functions.js b/addons/web/static/src/core/utils/functions.js
new file mode 100644
index 00000000000..5bd038a1b87
--- /dev/null
+++ b/addons/web/static/src/core/utils/functions.js
@@ -0,0 +1,22 @@
+/** @odoo-module **/
+
+/**
+ * Creates a version of the function that's memoized on the value of its first
+ * argument, if any.
+ *
+ * @template T, U
+ * @param {(arg: T) => U} func the function to memoize
+ * @returns {(arg: T) => U} a memoized version of the original function
+ */
+export function memoize(func) {
+ const cache = new Map();
+ const funcName = func.name ? func.name + " (memoized)" : "memoized";
+ return {
+ [funcName](...args) {
+ if (!cache.has(args[0])) {
+ cache.set(args[0], func(...args));
+ }
+ return cache.get(...args);
+ },
+ }[funcName];
+}
diff --git a/addons/web/static/src/core/utils/objects.js b/addons/web/static/src/core/utils/objects.js
new file mode 100644
index 00000000000..7962bdf01e3
--- /dev/null
+++ b/addons/web/static/src/core/utils/objects.js
@@ -0,0 +1,12 @@
+/** @odoo-module **/
+
+/**
+ * Shallow compares two objects.
+ */
+export function shallowEqual(obj1, obj2) {
+ const obj1Keys = Object.keys(obj1);
+ return (
+ obj1Keys.length === Object.keys(obj2).length &&
+ obj1Keys.every((key) => obj1[key] === obj2[key])
+ );
+}
diff --git a/addons/web/static/src/core/utils/patch.js b/addons/web/static/src/core/utils/patch.js
new file mode 100644
index 00000000000..0c4431960c5
--- /dev/null
+++ b/addons/web/static/src/core/utils/patch.js
@@ -0,0 +1,120 @@
+/** @odoo-module **/
+
+const patchMap = new WeakMap();
+
+/**
+ * Patch an object
+ *
+ * If the intent is to patch a class, don't forget to patch the prototype, unless
+ * you want to patch static properties/methods.
+ *
+ * @param {Object} obj Object to patch
+ * @param {string} patchName
+ * @param {Object} patchValue
+ * @param {{pure?: boolean}} [options]
+ */
+export function patch(obj, patchName, patchValue, options = {}) {
+ const pure = Boolean(options.pure);
+ if (!patchMap.has(obj)) {
+ patchMap.set(obj, {
+ original: {},
+ patches: [],
+ });
+ }
+ const objDesc = patchMap.get(obj);
+ if (objDesc.patches.some((p) => p.name === patchName)) {
+ throw new Error(`Class ${obj.name} already has a patch ${patchName}`);
+ }
+ objDesc.patches.push({
+ name: patchName,
+ patch: patchValue,
+ pure,
+ });
+
+ for (const k in patchValue) {
+ let prevDesc = null;
+ let proto = obj;
+ do {
+ prevDesc = Object.getOwnPropertyDescriptor(proto, k);
+ proto = Object.getPrototypeOf(proto);
+ } while (!prevDesc && proto);
+
+ const newDesc = Object.getOwnPropertyDescriptor(patchValue, k);
+ if (!objDesc.original.hasOwnProperty(k)) {
+ objDesc.original[k] = Object.getOwnPropertyDescriptor(obj, k);
+ }
+
+ if (prevDesc) {
+ const patchedFnName = `${k} (patch ${patchName})`;
+
+ if (prevDesc.value && typeof newDesc.value === "function") {
+ makeIntermediateFunction("value", prevDesc, newDesc, patchedFnName);
+ }
+ if (prevDesc.get || prevDesc.set) {
+ // get and set are defined together. If they are both defined
+ // in the previous descriptor but only one in the new descriptor
+ // then the other will be undefined so we need to apply the
+ // previous descriptor in the new one.
+ newDesc.get = newDesc.get || prevDesc.get;
+ newDesc.set = newDesc.set || prevDesc.set;
+ if (prevDesc.get && typeof newDesc.get === "function") {
+ makeIntermediateFunction("get", prevDesc, newDesc, patchedFnName);
+ }
+ if (prevDesc.set && typeof newDesc.set === "function") {
+ makeIntermediateFunction("set", prevDesc, newDesc, patchedFnName);
+ }
+ }
+ }
+
+ Object.defineProperty(obj, k, newDesc);
+ }
+
+ function makeIntermediateFunction(key, prevDesc, newDesc, patchedFnName) {
+ const _superFn = prevDesc[key];
+ const patchFn = newDesc[key];
+ if (pure) {
+ newDesc[key] = patchFn;
+ } else {
+ newDesc[key] = {
+ [patchedFnName](...args) {
+ const prevSuper = this._super;
+ this._super = _superFn.bind(this);
+ const result = patchFn.call(this, ...args);
+ this._super = prevSuper;
+ return result;
+ },
+ }[patchedFnName];
+ }
+ }
+}
+
+/**
+ * We define here an unpatch function. This is mostly useful if we want to
+ * remove a patch. For example, for testing purposes
+ *
+ * @param {Object} obj
+ * @param {string} patchName
+ */
+export function unpatch(obj, patchName) {
+ const objDesc = patchMap.get(obj);
+ if (!objDesc.patches.some((p) => p.name === patchName)) {
+ throw new Error(`Class ${obj.name} does not have any patch ${patchName}`);
+ }
+ patchMap.delete(obj);
+
+ // Restore original methods on the prototype and the class.
+ for (const k in objDesc.original) {
+ if (objDesc.original[k] === undefined) {
+ delete obj[k];
+ } else {
+ Object.defineProperty(obj, k, objDesc.original[k]);
+ }
+ }
+
+ // Re-apply the patches except the one to remove.
+ for (const patchDesc of objDesc.patches) {
+ if (patchDesc.name !== patchName) {
+ patch(obj, patchDesc.name, patchDesc.patch, { pure: patchDesc.pure });
+ }
+ }
+}
diff --git a/addons/web/static/src/core/utils/scrolling.js b/addons/web/static/src/core/utils/scrolling.js
new file mode 100644
index 00000000000..dbe2e18a558
--- /dev/null
+++ b/addons/web/static/src/core/utils/scrolling.js
@@ -0,0 +1,78 @@
+/** @odoo-module */
+
+/**
+ * Ensures that `element` will be visible in its `scrollable`.
+ *
+ * @param {HTMLElement} element
+ * @param {HTMLElement} scrollable
+ */
+export function scrollTo(element, scrollable) {
+ function _getScrollParent(node) {
+ if (node == null) {
+ return null;
+ }
+
+ if (node.scrollHeight > node.clientHeight) {
+ return node;
+ } else {
+ return _getScrollParent(node.parentNode);
+ }
+ }
+ scrollable = scrollable ? scrollable : _getScrollParent(element);
+
+ // Scrollbar is present ?
+ if (scrollable.scrollHeight > scrollable.clientHeight) {
+ const scrollBottom = scrollable.clientHeight + scrollable.scrollTop;
+ const elementBottom = element.offsetTop + element.offsetHeight;
+ if (elementBottom > scrollBottom) {
+ // Scroll down
+ scrollable.scrollTop = elementBottom - scrollable.clientHeight;
+ } else if (element.offsetTop < scrollable.scrollTop) {
+ // Scroll up
+ scrollable.scrollTop = element.offsetTop;
+ }
+ }
+}
+
+/**
+ * Retrieves the current top and left scroll position. By default, the scrolling
+ * area is the '.o_content' main div. In mobile, it is the body.
+ *
+ * @param {Component} an action Component containing an .o_content scrollable
+ * area.
+ */
+export function getScrollPosition(component) {
+ let scrollingEl;
+ if (component.env.isSmall) {
+ scrollingEl = document.body;
+ } else {
+ scrollingEl = component.el.querySelector(".o_action_manager .o_content");
+ }
+ return {
+ left: scrollingEl ? scrollingEl.scrollLeft : 0,
+ top: scrollingEl ? scrollingEl.scrollTop : 0,
+ };
+}
+
+/**
+ * Sets top and left scroll positions to the given values. By default, the
+ * scrolling area is the '.o_content' main div. In mobile, it is the body.
+ *
+ * @param {Component} an action Component containing an .o_content scrollable
+ * area.
+ * @param {Object} offset
+ * @param {number} [offset.left=0]
+ * @param {number} [offset.top=0]
+ */
+export function setScrollPosition(component, offset) {
+ let scrollingEl;
+ if (component.env.isSmall) {
+ scrollingEl = document.body;
+ } else {
+ scrollingEl = component.el.querySelector(".o_action_manager .o_content");
+ }
+ if (scrollingEl) {
+ scrollingEl.scrollLeft = offset.left || 0;
+ scrollingEl.scrollTop = offset.top || 0;
+ }
+}
diff --git a/addons/web/static/src/core/utils/strings.js b/addons/web/static/src/core/utils/strings.js
new file mode 100644
index 00000000000..4a77488bb97
--- /dev/null
+++ b/addons/web/static/src/core/utils/strings.js
@@ -0,0 +1,90 @@
+/** @odoo-module **/
+
+/**
+ * Escapes a string to use as a RegExp.
+ * @url https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#Escaping
+ *
+ * @param {string} str
+ * @returns {string} escaped string to use as a RegExp
+ */
+export function escapeRegExp(str) {
+ return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
+}
+
+/**
+ * Intersperses ``separator`` in ``str`` at the positions indicated by
+ * ``indices``.
+ *
+ * ``indices`` is an array of relative offsets (from the previous insertion
+ * position, starting from the end of the string) at which to insert
+ * ``separator``.
+ *
+ * There are two special values:
+ *
+ * ``-1``
+ * indicates the insertion should end now
+ * ``0``
+ * indicates that the previous section pattern should be repeated (until all
+ * of ``str`` is consumed)
+ *
+ * @param {string} str
+ * @param {number[]} indices
+ * @param {string} separator
+ * @returns {string}
+ */
+export function intersperse(str, indices, separator = "") {
+ separator = separator || "";
+ const result = [];
+ let last = str.length;
+ for (let i = 0; i < indices.length; ++i) {
+ let section = indices[i];
+ if (section === -1 || last <= 0) {
+ // Done with string, or -1 (stops formatting string)
+ break;
+ } else if (section === 0 && i === 0) {
+ // repeats previous section, which there is none => stop
+ break;
+ } else if (section === 0) {
+ // repeat previous section forever
+ //noinspection AssignmentToForLoopParameterJS
+ section = indices[--i];
+ }
+ result.push(str.substring(last - section, last));
+ last -= section;
+ }
+ const s = str.substring(0, last);
+ if (s) {
+ result.push(s);
+ }
+ return result.reverse().join(separator);
+}
+
+/**
+ * Returns a string formatted using given values.
+ * If the value is an object, its keys will replace `%(key)s` expressions.
+ * If the values are a set of strings, they will replace `%s` expressions.
+ * If no value is given, the string will not be formatted.
+ *
+ * @param {string} s
+ * @param {...string} ...values
+ * @returns {string}
+ */
+export function sprintf(s, ...values) {
+ if (values.length === 1 && typeof values[0] === "object") {
+ const valuesDict = values[0];
+ s = s.replace(/\%\(?([^\)]+)\)s/g, (match, value) => valuesDict[value]);
+ } else if (values.length > 0) {
+ s = s.replace(/\%s/g, () => values.shift());
+ }
+ return s;
+}
+
+/**
+ * Capitalizes a string: "abc def" => "Abc def"
+ *
+ * @param {string} s the input string
+ * @returns {string}
+ */
+export function capitalize(s) {
+ return s ? s[0].toUpperCase() + s.slice(1) : "";
+}
diff --git a/addons/web/static/src/core/utils/timing.js b/addons/web/static/src/core/utils/timing.js
new file mode 100644
index 00000000000..83f74c70a39
--- /dev/null
+++ b/addons/web/static/src/core/utils/timing.js
@@ -0,0 +1,61 @@
+/** @odoo-module **/
+
+import { browser } from "../browser/browser";
+
+/**
+ * Returns a function, that, as long as it continues to be invoked, will not
+ * be triggered. The function will be called after it stops being called for
+ * N milliseconds. If `immediate` is passed, trigger the function on the
+ * leading edge, instead of the trailing.
+ *
+ * Inspired by https://davidwalsh.name/javascript-debounce-function
+ * @param {Function} func
+ * @param {number} wait
+ * @param {boolean} [immediate=false]
+ * @returns {Function}
+ */
+export function debounce(func, wait, immediate = false) {
+ let timeout;
+ const funcName = func.name ? func.name + " (debounce)" : "debounce";
+ return {
+ [funcName](...args) {
+ const context = this;
+ function later() {
+ if (!immediate) {
+ func.apply(context, args);
+ }
+ }
+ const callNow = immediate && !timeout;
+ browser.clearTimeout(timeout);
+ timeout = browser.setTimeout(later, wait);
+ if (callNow) {
+ func.apply(context, args);
+ }
+ },
+ }[funcName];
+}
+
+/**
+ * Returns a function, that, as long as it continues to be invoked, will be
+ * triggered every N milliseconds.
+ *
+ * @param {Function} func
+ * @param {number} wait
+ * @returns {Function}
+ */
+export function throttle(func, wait) {
+ let waiting = false;
+ const funcName = func.name ? func.name + " (throttle)" : "throttle";
+ return {
+ [funcName](...args) {
+ const context = this;
+ if (!waiting) {
+ waiting = true;
+ browser.setTimeout(function () {
+ waiting = false;
+ func.call(context, ...args);
+ }, wait);
+ }
+ },
+ }[funcName];
+}
diff --git a/addons/web/static/src/core/utils/transitions.scss b/addons/web/static/src/core/utils/transitions.scss
new file mode 100644
index 00000000000..2ef7a8a451e
--- /dev/null
+++ b/addons/web/static/src/core/utils/transitions.scss
@@ -0,0 +1,24 @@
+/**
+ * This file includes all the t-transition mixins.
+ */
+
+/*
+ Fade in and out with t-transition
+ Usage:
+ scss: @include owl-fade(0.5s, 'o_notification')
+ xml:
+ */
+@mixin owl-fade($time, $name) {
+ .#{$name}_fade-enter-active,
+ .#{$name}_fade-active {
+ transition: all $time;
+ }
+
+ .#{$name}_fade-enter {
+ opacity: 0;
+ }
+
+ .#{$name}_fade-leave-to {
+ opacity: 0;
+ }
+}
diff --git a/addons/web/static/src/core/utils/urls.js b/addons/web/static/src/core/utils/urls.js
new file mode 100644
index 00000000000..fb78bd9ad5c
--- /dev/null
+++ b/addons/web/static/src/core/utils/urls.js
@@ -0,0 +1,56 @@
+/** @odoo-module **/
+
+import { browser } from "../browser/browser";
+
+/**
+ * Trasnforms a key value mapping to a string formatted as url hash, e.g.
+ * {a: "x", b: 2} -> "a=x&b=2"
+ *
+ * @param {Object} obj
+ * @returns {string}
+ */
+export function objectToUrlEncodedString(obj) {
+ return Object.entries(obj)
+ .map(([k, v]) => (v ? `${k}=${encodeURIComponent(v)}` : k))
+ .join("&");
+}
+
+/**
+ * Gets the origin url of the page, or cleans a given one
+ *
+ * @param {string} [origin]: a given origin url
+ * @return {string} a cleaned origin url
+ */
+export function getOrigin(origin) {
+ if (origin) {
+ // remove trailing slashes
+ origin = origin.replace(/\/+$/, "");
+ } else {
+ const { host, protocol } = browser.location;
+ origin = `${protocol}//${host}`;
+ }
+ return origin;
+}
+
+/**
+ * @param {string} route: the relative route, or absolute in the case of cors urls
+ * @param {object} [queryParams]: parameters to be appended as the url's queryString
+ * @param {object} [options]
+ * @param {string} [options.origin]: a precomputed origin
+ */
+export function url(route, queryParams, options = {}) {
+ const origin = getOrigin(options.origin);
+ if (!route) {
+ return origin;
+ }
+
+ let queryString = objectToUrlEncodedString(queryParams || {});
+ queryString = queryString.length > 0 ? `?${queryString}` : queryString;
+
+ // Compare the wanted url against the current origin
+ let prefix = ["http://", "https://", "//"].some(
+ (el) => route.length >= el.length && route.slice(0, el.length) === el
+ );
+ prefix = prefix ? "" : origin;
+ return `${prefix}${route}${queryString}`;
+}
diff --git a/addons/web/static/src/css/reset.min.css b/addons/web/static/src/css/reset.min.css
deleted file mode 100644
index b6163764a5c..00000000000
--- a/addons/web/static/src/css/reset.min.css
+++ /dev/null
@@ -1,103 +0,0 @@
-/*
-
-HTML5 CSS Reset
-Based on Eric Meyer's CSS Reset
-and html5doctor.com HTML5 Reset
-
-Copyright (c) 2011 736 Computing Services Limited
-Released under the MIT license. http://opensource.736cs.com/licenses/mit
-
-*/
-
-html, body, div, span, applet, object, iframe,
-h1, h2, h3, h4, h5, h6, p, blockquote, pre,
-a, abbr, acronym, address, big, cite, code,
-del, dfn, em, font, img, ins, kbd, q, s, samp,
-small, strike, strong, sub, sup, tt, var,
-b, i, center, dl, dt, dd, ol, ul, li,
-fieldset, form, label, legend,
-table, caption, tbody, tfoot, thead, tr, th, td,
-article, aside, audio, canvas, details, figcaption,
-figure, footer, header, hgroup, mark, menu, meter, nav,
-output, progress, section, summary, time, video {
- margin: 0;
- padding: 0;
- border: 0;
- outline: 0;
- font-size: 100%;
- vertical-align: baseline;
- background: transparent;
-}
-
-body {
- line-height: 1;
-}
-
-article, aside, dialog, figure, footer, header,
-hgroup, nav, section, blockquote {
- display: block;
-}
-
-nav ul {
- list-style: none;
-}
-
-ol {
- list-style: decimal;
-}
-
-ul {
- list-style: disc;
- padding-left: 40px;
-}
-
-ul ul {
- list-style: circle;
-}
-
-blockquote:before, blockquote:after,
-q:before, q:after {
- content: '';
- content: none;
-}
-
-ins {
- text-decoration: underline;
-}
-
-del {
- text-decoration: line-through;
-}
-
-mark {
- background: none;
-}
-
-abbr[title], dfn[title] {
- border-bottom:1px dotted #000;
- cursor:help;
-}
-
-/* tables still need 'cellspacing="0"' in the markup */
-table {
- border-collapse: collapse;
- border-spacing: 0;
-}
-
-hr {
- display: block;
- height: 1px;
- border: 0;
- border-top: 1px solid #ccc;
- margin: 1em 0;
- padding: 0;
-}
-
-input[type="submit"], input[type="button"], button {
- padding: 0 !important;
- margin: 0 !important;
-}
-
-input, select, a img {
- vertical-align: middle;
-}
diff --git a/addons/web/static/src/env.js b/addons/web/static/src/env.js
new file mode 100644
index 00000000000..fbc2571537a
--- /dev/null
+++ b/addons/web/static/src/env.js
@@ -0,0 +1,166 @@
+/** @odoo-module **/
+
+import { registry } from "./core/registry";
+
+// -----------------------------------------------------------------------------
+// Types
+// -----------------------------------------------------------------------------
+
+/**
+ * @typedef {Object} OdooEnv
+ * @property {Object} services
+ * @property {owl.core.EventBus} bus
+ * @property {owl.QWeb} qweb
+ * @property {string} debug
+ * @property {(str: string) => string} _t
+ * @property {boolean} [isSmall]
+ */
+
+// -----------------------------------------------------------------------------
+// makeEnv
+// -----------------------------------------------------------------------------
+
+/**
+ * Return a value Odoo Env object
+ *
+ * @returns {OdooEnv}
+ */
+export function makeEnv() {
+ return {
+ qweb: new owl.QWeb(),
+ bus: new owl.core.EventBus(),
+ services: {},
+ debug: odoo.debug,
+ _t: () => {
+ throw new Error("Translations are not ready yet. Maybe use _lt instead?");
+ },
+ get isSmall() {
+ throw new Error("UI service not initialized!");
+ },
+ };
+}
+
+// -----------------------------------------------------------------------------
+// Service Launcher
+// -----------------------------------------------------------------------------
+
+const serviceRegistry = registry.category("services");
+
+export const SERVICES_METADATA = {};
+
+/**
+ * Start all services registered in the service registry, while making sure
+ * each service dependencies are properly fulfilled.
+ *
+ * @param {OdooEnv} env
+ * @returns {Promise}
+ */
+export async function startServices(env) {
+ const toStart = new Set();
+ serviceRegistry.on("UPDATE", null, async (payload) => {
+ // Wait for all synchronous code so that if new services that depend on
+ // one another are added to the registry, they're all present before we
+ // start them regardless of the order they're added to the registry.
+ await Promise.resolve();
+ const { operation, key: name, value: service } = payload;
+ if (operation === "delete") {
+ // We hardly see why it would be usefull to remove a service.
+ // Furthermore we could encounter problems with dependencies.
+ // Keep it simple!
+ return;
+ }
+ if (toStart.size) {
+ const namedService = Object.assign(Object.create(service), { name });
+ toStart.add(namedService);
+ } else {
+ await _startServices(env, toStart);
+ }
+ });
+ // Wait for all synchronous code so that if new services that depend on
+ // one another are added to the registry, they're all present before we
+ // start them regardless of the order they're added to the registry.
+ await Promise.resolve();
+ await _startServices(env, toStart);
+}
+
+async function _startServices(env, toStart) {
+ const services = env.services;
+ for (const [name, service] of serviceRegistry.getEntries()) {
+ if (!(name in services)) {
+ const namedService = Object.assign(Object.create(service), { name });
+ toStart.add(namedService);
+ }
+ }
+
+ // start as many services in parallel as possible
+ async function start() {
+ let service = null;
+ const proms = [];
+ while ((service = findNext())) {
+ let name = service.name;
+ toStart.delete(service);
+ const entries = (service.dependencies || []).map((dep) => [dep, services[dep]]);
+ const dependencies = Object.fromEntries(entries);
+ let value;
+ try {
+ value = service.start(env, dependencies);
+ } catch (e) {
+ value = e;
+ console.error(e);
+ }
+ if ("async" in service) {
+ SERVICES_METADATA[name] = service.async;
+ }
+ if (value instanceof Promise) {
+ proms.push(
+ new Promise(async (resolve) => {
+ value
+ .then((val) => {
+ services[name] = val || null;
+ })
+ .catch((error) => {
+ services[name] = error;
+ console.error(error);
+ })
+ .finally(resolve);
+ })
+ );
+ } else {
+ services[service.name] = value || null;
+ }
+ }
+ await Promise.all(proms);
+ if (proms.length) {
+ return start();
+ }
+ }
+ await start();
+ if (toStart.size) {
+ const names = [...toStart].map((s) => s.name);
+ const missingDeps = new Set();
+ [...toStart].forEach((s) =>
+ s.dependencies.forEach((dep) => {
+ if (!(dep in services) && !names.includes(dep)) {
+ missingDeps.add(dep);
+ }
+ })
+ );
+ const depNames = [...missingDeps].join(", ");
+ throw new Error(
+ `Some services could not be started: ${names}. Missing dependencies: ${depNames}`
+ );
+ }
+
+ function findNext() {
+ for (let s of toStart) {
+ if (s.dependencies) {
+ if (s.dependencies.every((d) => d in services)) {
+ return s;
+ }
+ } else {
+ return s;
+ }
+ }
+ return null;
+ }
+}
diff --git a/addons/web/static/src/fields/format.js b/addons/web/static/src/fields/format.js
new file mode 100644
index 00000000000..b6ffeb00f8b
--- /dev/null
+++ b/addons/web/static/src/fields/format.js
@@ -0,0 +1,32 @@
+/** @odoo-module **/
+
+/**
+ * Returns a string representing an many2one. If the value is false, then we
+ * return an empty string. Note that it accepts two types of input parameters:
+ * an array, in that case we assume that the many2one value is of the form
+ * [id, nameget], and we return the nameget, or it can be an object, and in that
+ * case, we assume that it is a record datapoint from a BasicModel.
+ *
+ * @param {Array|Object|false} value
+ * @param {{escape?: boolean}} [options] additional options
+ * @param {boolean} [options.escape=false] if true, escapes the formatted value
+ * @returns {string}
+ */
+export function formatMany2one(value, options) {
+ if (!value) {
+ value = "";
+ } else if (Array.isArray(value)) {
+ // value is a pair [id, nameget]
+ value = value[1];
+ } else {
+ // value is a datapoint, so we read its display_name field, which
+ // may in turn be a datapoint (if the name field is a many2one)
+ while (value.data) {
+ value = value.data.display_name || "";
+ }
+ }
+ if (options && options.escape) {
+ value = encodeURIComponent(value);
+ }
+ return value;
+}
diff --git a/addons/web/static/src/js/chrome/abstract_web_client.js b/addons/web/static/src/js/chrome/abstract_web_client.js
deleted file mode 100644
index d7f3af00357..00000000000
--- a/addons/web/static/src/js/chrome/abstract_web_client.js
+++ /dev/null
@@ -1,571 +0,0 @@
-odoo.define('web.AbstractWebClient', function (require) {
-"use strict";
-
-/**
- * AbstractWebClient
- *
- * This class defines a simple, basic web client. It is mostly functional.
- * The WebClient is in some way the most important class for the web framework:
- * - this is the class that instantiate everything else,
- * - it is the top of the component tree,
- * - it coordinates many events bubbling up
- */
-
-var ActionManager = require('web.ActionManager');
-var concurrency = require('web.concurrency');
-var core = require('web.core');
-var config = require('web.config');
-var WarningDialog = require('web.CrashManager').WarningDialog;
-var data_manager = require('web.data_manager');
-var dom = require('web.dom');
-var KeyboardNavigationMixin = require('web.KeyboardNavigationMixin');
-var Loading = require('web.Loading');
-var RainbowMan = require('web.RainbowMan');
-var session = require('web.session');
-var utils = require('web.utils');
-var Widget = require('web.Widget');
-
-const env = require('web.env');
-
-var _t = core._t;
-
-var AbstractWebClient = Widget.extend(KeyboardNavigationMixin, {
- dependencies: ['notification'],
- events: _.extend({}, KeyboardNavigationMixin.events),
- custom_events: {
- call_service: '_onCallService',
- clear_uncommitted_changes: function (e) {
- this.clear_uncommitted_changes().then(e.data.callback);
- },
- toggle_fullscreen: function (event) {
- this.toggle_fullscreen(event.data.fullscreen);
- },
- current_action_updated: function (ev) {
- this.current_action_updated(ev.data.action, ev.data.controller);
- },
- // GENERIC SERVICES
- // the next events are dedicated to generic services required by
- // downstream widgets. Mainly side effects, such as rpcs, notifications
- // or cache.
- warning: '_onDisplayWarning',
- load_action: '_onLoadAction',
- load_views: function (event) {
- var params = {
- model: event.data.modelName,
- context: event.data.context,
- views_descr: event.data.views,
- };
- return data_manager
- .load_views(params, event.data.options || {})
- .then(event.data.on_success);
- },
- load_filters: function (event) {
- return data_manager
- .load_filters(event.data)
- .then(event.data.on_success);
- },
- create_filter: '_onCreateFilter',
- delete_filter: '_onDeleteFilter',
- push_state: '_onPushState',
- show_effect: '_onShowEffect',
- // session
- get_session: function (event) {
- if (event.data.callback) {
- event.data.callback(session);
- }
- },
- do_action: function (event) {
- const actionProm = this.do_action(event.data.action, event.data.options || {});
- this.menu_dp.add(actionProm).then(function (result) {
- if (event.data.on_success) {
- event.data.on_success(result);
- }
- }).guardedCatch(function (result) {
- if (event.data.on_fail) {
- event.data.on_fail(result);
- }
- });
- },
- getScrollPosition: '_onGetScrollPosition',
- scrollTo: '_onScrollTo',
- set_title_part: '_onSetTitlePart',
- webclient_started: '_onWebClientStarted',
- },
- init: function (parent) {
- // a flag to determine that odoo is fully loaded
- odoo.isReady = false;
- this.client_options = {};
- this._super(parent);
- KeyboardNavigationMixin.init.call(this);
- this.origin = undefined;
- this._current_state = null;
- this.menu_dp = new concurrency.DropPrevious();
- this.action_mutex = new concurrency.Mutex();
- this.set('title_part', {"zopenerp": "Odoo"});
- this.env = env;
- this.env.bus.on('set_title_part', this, this._onSetTitlePart);
- // Only manage the multi company state if a session exists (in order not to interfere during js tests)
- if (session.uid && Number.isInteger(session.uid) && session.uid > 0) {
- this._manageMultiCompanyState();
- }
- if (session.user_context &&
- session.user_context.allowed_company_ids &&
- session.user_context.allowed_company_ids.length) {
- this.currentCompanyId = session.user_context.allowed_company_ids[0];
- const currentCompany = session.user_companies.allowed_companies[this.currentCompanyId];
- const currentCompanyTimesheetUOMId = currentCompany.timesheet_uom_id || false;
- this.currentCompanyTimesheetUOMFactor = currentCompany.timesheet_uom_factor || 1;
- this.currentCompanyTimesheetUOM = currentCompanyTimesheetUOMId && session.uom_ids[currentCompanyTimesheetUOMId] || false;
- }
- },
- /**
- * @override
- */
- start: function () {
- KeyboardNavigationMixin.start.call(this);
- var self = this;
-
- // we add the o_touch_device css class to allow CSS to target touch
- // devices. This is only for styling purpose, if you need javascript
- // specific behaviour for touch device, just use the config object
- // exported by web.config
- this.$el.toggleClass('o_touch_device', config.device.touch);
- this.on("change:title_part", this, this._title_changed);
- this._title_changed();
-
- // Update favicon
- $("link[type='image/x-icon']").attr('href', '/web/image/res.company/' + String(this.currentCompanyId) + '/favicon/');
-
- return session.is_bound
- .then(function () {
- self.$el.toggleClass('o_rtl', _t.database.parameters.direction === "rtl");
- self.bind_events();
- return Promise.all([
- self.set_action_manager(),
- self.set_loading()
- ]);
- }).then(function () {
- if (session.session_is_valid()) {
- return self.show_application();
- } else {
- // database manager needs the webclient to keep going even
- // though it has no valid session
- return Promise.resolve();
- }
- });
- },
- /**
- * @override
- */
- destroy: function () {
- KeyboardNavigationMixin.destroy.call(this);
- return this._super(...arguments);
- },
- bind_events: function () {
- var self = this;
- $('.oe_systray').show();
- this.$el.on('mouseenter', '.oe_systray > div:not([data-toggle=tooltip])', function () {
- $(this).attr('data-toggle', 'tooltip').tooltip().trigger('mouseenter');
- });
- // TODO: this handler seems useless since 11.0, should be removed
- this.$el.on('click', '.oe_dropdown_toggle', function (ev) {
- ev.preventDefault();
- var $toggle = $(this);
- var doc_width = $(document).width();
- var $menu = $toggle.siblings('.oe_dropdown_menu');
- $menu = $menu.length >= 1 ? $menu : $toggle.find('.oe_dropdown_menu');
- var state = $menu.is('.oe_opened');
- setTimeout(function () {
- // Do not alter propagation
- $toggle.add($menu).toggleClass('oe_opened', !state);
- if (!state) {
- // Move $menu if outside window's edge
- var offset = $menu.offset();
- var menu_width = $menu.width();
- var x = doc_width - offset.left - menu_width - 2;
- if (x < 0) {
- $menu.offset({ left: offset.left + x }).width(menu_width);
- }
- }
- }, 0);
- });
- core.bus.on('click', this, function (ev) {
- $('.tooltip').remove();
- if (!$(ev.target).is('input[type=file]')) {
- $(this.el.getElementsByClassName('oe_dropdown_menu oe_opened')).removeClass('oe_opened');
- $(this.el.getElementsByClassName('oe_dropdown_toggle oe_opened')).removeClass('oe_opened');
- }
- });
- core.bus.on('connection_lost', this, this._onConnectionLost);
- core.bus.on('connection_restored', this, this._onConnectionRestored);
- },
- set_action_manager: function () {
- var self = this;
- this.action_manager = new ActionManager(this, session.user_context);
- this.env.bus.on('do-action', this, payload => {
- this.do_action(payload.action, payload.options || {})
- .then(payload.on_success || (() => {}))
- .guardedCatch(payload.on_fail || (() => {}));
- });
- var fragment = document.createDocumentFragment();
- return this.action_manager.appendTo(fragment).then(function () {
- dom.append(self.$el, fragment, {
- in_DOM: true,
- callbacks: [{widget: self.action_manager}],
- });
- });
- },
- set_loading: function () {
- this.loading = new Loading(this);
- return this.loading.appendTo(this.$el);
- },
- show_application: function () {
- },
- clear_uncommitted_changes: function () {
- return this.action_manager.clearUncommittedChanges();
- },
- destroy_content: function () {
- _.each(_.clone(this.getChildren()), function (el) {
- el.destroy();
- });
- this.$el.children().remove();
- },
- _manageMultiCompanyState: function () {
- let state = $.bbq.getState();
- // If not set on the url, retrieve cids from the local storage
- // or from the default company on the user
- const current_company_id = session.user_companies.current_company;
- if (!state.cids) {
- state.cids = utils.get_cookie('cids') !== null ? utils.get_cookie('cids') : String(current_company_id);
- }
- // If a key appears several times in the hash, it is available in the
- // bbq state as an array containing all occurrences of that key
- const cids = Array.isArray(state.cids) ? state.cids[0] : state.cids;
- let stateCompanyIDS = cids.split(',').map(cid => parseInt(cid, 10));
- const userCompanyIDS = Object.keys(session.user_companies.allowed_companies).map(id => parseInt(id, 10));
- // Check that the user has access to all the companies
- if (!_.isEmpty(_.difference(stateCompanyIDS, userCompanyIDS))) {
- state.cids = String(current_company_id);
- stateCompanyIDS = [current_company_id];
- }
- // Update the user context with this configuration
- session.user_context.allowed_company_ids = stateCompanyIDS;
- $.bbq.pushState(state);
- },
- // --------------------------------------------------------------
- // Window title handling
- // --------------------------------------------------------------
- /**
- * Sets the first part of the title of the window, dedicated to the current action.
- */
- set_title: function (title) {
- this.set_title_part("action", title);
- },
- /**
- * Sets an arbitrary part of the title of the window. Title parts are
- * identified by strings. Each time a title part is changed, all parts
- * are gathered, ordered by alphabetical order and displayed in the title
- * of the window separated by ``-``.
- *
- * @private
- * @param {string} part
- * @param {string} title
- */
- set_title_part: function (part, title) {
- var tmp = _.clone(this.get("title_part"));
- tmp[part] = title;
- this.set("title_part", tmp);
- },
- _title_changed: function () {
- var parts = _.sortBy(_.keys(this.get("title_part")), function (x) { return x; });
- var tmp = "";
- _.each(parts, function (part) {
- var str = this.get("title_part")[part];
- if (str) {
- tmp = tmp ? tmp + " - " + str : str;
- }
- }, this);
- document.title = tmp;
- },
- // --------------------------------------------------------------
- // do_*
- // --------------------------------------------------------------
- /**
- * When do_action is performed on the WebClient, forward it to the main ActionManager
- * This allows to widgets that are not inside the ActionManager to perform do_action
- */
- do_action: function () {
- return this.action_manager.doAction.apply(this.action_manager, arguments);
- },
- do_reload: function () {
- var self = this;
- return session.session_reload().then(function () {
- session.load_modules(true).then(
- self.menu.proxy('do_reload'));
- });
- },
- do_push_state: function (state) {
- if (!state.menu_id && this.menu) { // this.menu doesn't exist in the POS
- state.menu_id = this.menu.getCurrentPrimaryMenu();
- }
- if ('title' in state) {
- this.set_title(state.title);
- delete state.title;
- }
- var url = '#' + $.param(state);
- this._current_state = $.deparam($.param(state), false); // stringify all values
- $.bbq.pushState(url);
- this.trigger('state_pushed', state);
- },
- // --------------------------------------------------------------
- // Connection notifications
- // --------------------------------------------------------------
- /**
- * Handler to be overridden, called each time the UI is updated by the
- * ActionManager.
- *
- * @param {Object} action the action of the currently displayed controller
- * @param {Object} controller the currently displayed controller
- */
- current_action_updated: function (action, controller) {
- },
- //--------------------------------------------------------------
- // Misc.
- //--------------------------------------------------------------
- toggle_fullscreen: function (fullscreen) {
- this.$el.toggleClass('o_fullscreen', fullscreen);
- },
-
- //--------------------------------------------------------------------------
- // Public
- //--------------------------------------------------------------------------
-
- /**
- * Returns the left and top scroll positions of the main scrolling area
- * (i.e. the '.o_content' div in desktop).
- *
- * @returns {Object} with keys left and top
- */
- getScrollPosition: function () {
- var scrollingEl = this.action_manager.el.getElementsByClassName('o_content')[0];
- return {
- left: scrollingEl ? scrollingEl.scrollLeft : 0,
- top: scrollingEl ? scrollingEl.scrollTop : 0,
- };
- },
-
- //--------------------------------------------------------------------------
- // Handlers
- //--------------------------------------------------------------------------
-
- /**
- * Calls the requested service from the env.
- *
- * For the ajax service, the arguments are extended with the target so that
- * it can call back the caller.
- *
- * @private
- * @param {OdooEvent} event
- */
- _onCallService: function (ev) {
- const payload = ev.data;
- let args = payload.args || [];
- if (payload.service === 'ajax' && payload.method === 'rpc') {
- // ajax service uses an extra 'target' argument for rpc
- args = args.concat(ev.target);
- }
- const service = this.env.services[payload.service];
- const result = service[payload.method].apply(service, args);
- payload.callback(result);
- },
- /**
- * Whenever the connection is lost, we need to notify the user.
- *
- * @private
- */
- _onConnectionLost: function () {
- this.connectionNotificationID = this.displayNotification({
- message: _t('Connection lost. Trying to reconnect...'),
- sticky: true
- });
- },
- /**
- * Whenever the connection is restored, we need to notify the user.
- *
- * @private
- */
- _onConnectionRestored: function () {
- if (this.connectionNotificationID) {
- this.call('notification', 'close', this.connectionNotificationID);
- this.displayNotification({
- type: 'info',
- message: _t('Connection restored. You are back online.'),
- sticky: false
- });
- this.connectionNotificationID = false;
- }
- },
- /**
- * @private
- * @param {OdooEvent} e
- * @param {Object} e.data.filter the filter description
- * @param {function} e.data.on_success called when the RPC succeeds with its
- * returned value as argument
- */
- _onCreateFilter: function (e) {
- data_manager
- .create_filter(e.data.filter)
- .then(e.data.on_success);
- },
- /**
- * @private
- * @param {OdooEvent} e
- * @param {Object} e.data.filter the filter description
- * @param {function} e.data.on_success called when the RPC succeeds with its
- * returned value as argument
- */
- _onDeleteFilter: function (e) {
- data_manager
- .delete_filter(e.data.filterId)
- .then(e.data.on_success);
- },
- /**
- * Displays a warning in a dialog or with the notification service
- *
- * @private
- * @param {OdooEvent} e
- * @param {string} e.data.message the warning's message
- * @param {string} e.data.title the warning's title
- * @param {string} [e.data.type] 'dialog' to display in a dialog
- * @param {boolean} [e.data.sticky] whether or not the warning should be
- * sticky (if displayed with the Notification)
- */
- _onDisplayWarning: function (e) {
- var data = e.data;
- if (data.type === 'dialog') {
- new WarningDialog(this, {
- title: data.title,
- }, data).open();
- } else {
- data.type = 'warning';
- this.call('notification', 'notify', data);
- }
- },
- /**
- * Provides to the caller the current scroll position (left and top) of the
- * main scrolling area of the webclient.
- *
- * @private
- * @param {OdooEvent} ev
- * @param {function} ev.data.callback
- */
- _onGetScrollPosition: function (ev) {
- ev.data.callback(this.getScrollPosition());
- },
- /**
- * Loads an action from the database given its ID.
- *
- * @private
- * @param {OdooEvent} event
- * @param {integer} event.data.actionID
- * @param {Object} event.data.context
- * @param {function} event.data.on_success
- */
- _onLoadAction: function (event) {
- data_manager
- .load_action(event.data.actionID, event.data.context)
- .then(event.data.on_success);
- },
- /**
- * @private
- * @param {OdooEvent} e
- */
- _onPushState: function (e) {
- this.do_push_state(_.extend(e.data.state, {'cids': $.bbq.getState().cids}));
- },
- /**
- * Scrolls either to a given offset or to a target element (given a selector).
- * It must be called with: trigger_up('scrollTo', options).
- *
- * @private
- * @param {OdooEvent} ev
- * @param {integer} [ev.data.top] the number of pixels to scroll from top
- * @param {integer} [ev.data.left] the number of pixels to scroll from left
- * @param {string} [ev.data.selector] the selector of the target element to
- * scroll to
- */
- _onScrollTo: function (ev) {
- var scrollingEl = this.action_manager.el.getElementsByClassName('o_content')[0];
- if (!scrollingEl) {
- return;
- }
- var offset = {top: ev.data.top, left: ev.data.left || 0};
- if (ev.data.selector) {
- offset = dom.getPosition(document.querySelector(ev.data.selector));
- // Substract the position of the scrolling element
- offset.top -= dom.getPosition(scrollingEl).top;
- }
-
- scrollingEl.scrollTop = offset.top;
- scrollingEl.scrollLeft = offset.left;
- },
- /**
- * @private
- * @param {Object} payload
- * @param {string} payload.part
- * @param {string} [payload.title]
- */
- _onSetTitlePart: function (payload) {
- var part = payload.part;
- var title = payload.title;
- this.set_title_part(part, title);
- },
- /**
- * Displays a visual effect (for example, a rainbowman0
- *
- * @private
- * @param {OdooEvent} e
- * @param {Object} [e.data] - key-value options to decide rainbowman
- * behavior / appearance
- */
- _onShowEffect: function (e) {
- var data = e.data || {};
- var type = data.type || 'rainbow_man';
- if (type === 'rainbow_man') {
- if (session.show_effect) {
- new RainbowMan(data).appendTo(this.$el);
- } else {
- // For instance keep title blank, as we don't have title in data
- this.call('notification', 'notify', {
- title: "",
- message: data.message,
- sticky: false
- });
- }
- } else {
- throw new Error('Unknown effect type: ' + type);
- }
- },
- /**
- * Reacts to the end of the loading of the WebClient as a whole
- * It allows for signalling to the rest of the ecosystem that the interface is usable
- *
- * @private
- */
- _onWebClientStarted: function() {
- if (!this.isStarted) {
- // Listen to 'scroll' event and propagate it on main bus
- this.action_manager.$el.on('scroll', core.bus.trigger.bind(core.bus, 'scroll'));
- odoo.isReady = true;
- core.bus.trigger('web_client_ready');
- if (session.uid === 1) {
- this.$el.addClass('o_is_superuser');
- }
- this.isStarted = true;
- }
- }
-});
-
-return AbstractWebClient;
-
-});
diff --git a/addons/web/static/src/js/chrome/action_manager.js b/addons/web/static/src/js/chrome/action_manager.js
deleted file mode 100644
index d1cca361b67..00000000000
--- a/addons/web/static/src/js/chrome/action_manager.js
+++ /dev/null
@@ -1,939 +0,0 @@
-odoo.define('web.ActionManager', function (require) {
-"use strict";
-
-/**
- * ActionManager
- *
- * The ActionManager is one of the centrepieces in the WebClient architecture.
- * Its role is to makes sure that Odoo actions are properly started and
- * coordinated.
- */
-
-var AbstractAction = require('web.AbstractAction');
-var concurrency = require('web.concurrency');
-var Context = require('web.Context');
-var core = require('web.core');
-var Dialog = require('web.Dialog');
-var dom = require('web.dom');
-var framework = require('web.framework');
-var pyUtils = require('web.py_utils');
-var Widget = require('web.Widget');
-
-var _t = core._t;
-var ActionManager = Widget.extend({
- className: 'o_action_manager',
- custom_events: {
- breadcrumb_clicked: '_onBreadcrumbClicked',
- history_back: '_onHistoryBack',
- push_state: '_onPushState',
- redirect: '_onRedirect',
- },
-
- /**
- * @override
- * @param {Object} [userContext={}]
- */
- init: function (parent, userContext) {
- this._super.apply(this, arguments);
- this.userContext = userContext || {};
-
- // use a DropPrevious to drop previous actions when multiple actions are
- // run simultaneously
- this.dp = new concurrency.DropPrevious();
-
- // 'actions' is an Object that registers the actions that are currently
- // handled by the ActionManager (either stacked in the current window,
- // or opened in dialogs)
- this.actions = {};
-
- // 'controllers' is an Object that registers the alive controllers
- // linked registered actions, a controller being Object with keys
- // (amongst others) 'jsID' (a local identifier) and 'widget' (the
- // instance of the controller's widget)
- this.controllers = {};
-
- // 'controllerStack' is the stack of ids of the controllers currently
- // displayed in the current window
- this.controllerStack = [];
-
- // 'currentDialogController' is the current controller opened in a
- // dialog (i.e. coming from an action with target='new')
- this.currentDialogController = null;
- },
- /**
- * Called each time the action manager is attached into the DOM.
- */
- on_attach_callback: function () {
- this.isInDOM = true;
- var currentController = this.getCurrentController();
- if (currentController) {
- currentController.widget.on_attach_callback();
- }
- },
- /**
- * Called each time the action manager is detached from the DOM.
- */
- on_detach_callback: function () {
- this.isInDOM = false;
- var currentController = this.getCurrentController();
- if (currentController) {
- currentController.widget.on_detach_callback();
- }
- },
-
- //--------------------------------------------------------------------------
- // Public
- //--------------------------------------------------------------------------
-
- /**
- * This function is called when the current controller is about to be
- * removed from the DOM, because a new one will be pushed, or an old one
- * will be restored. It ensures that the current controller can be left (for
- * instance, that it has no unsaved changes).
- *
- * @returns {Promise} resolved if the current controller can be left,
- * rejected otherwise.
- */
- clearUncommittedChanges: function () {
- var currentController = this.getCurrentController();
- if (currentController) {
- return currentController.widget.canBeRemoved();
- }
- return Promise.resolve();
- },
- /**
- * This is the entry point to execute Odoo actions, given as an ID in
- * database, an xml ID, a client action tag or an action descriptor.
- *
- * @param {number|string|Object} action the action to execute
- * @param {Object} [options]
- * @param {Object} [options.additional_context] additional context to be
- * merged with the action's context.
- * @param {boolean} [options.clear_breadcrumbs=false] set to true to clear
- * the breadcrumbs history list
- * @param {Function} [options.on_close] callback to be executed when the
- * current action is active again (typically, if the new action is
- * executed in target="new", on_close will be executed when the dialog is
- * closed, if the current controller is still active)
- * @param {Function} [options.on_reverse_breadcrumb] callback to be executed
- * whenever an anterior breadcrumb item is clicked on
- * @param {boolean} [options.pushState=true] set to false to prevent the
- * ActionManager from pushing the state when the action is executed (this
- * is useful when we come from a loadState())
- * @param {boolean} [options.replace_last_action=false] set to true to
- * replace last part of the breadcrumbs with the action
- * @return {Promise} resolved with the action when the action is
- * loaded and appended to the DOM ; rejected if the action can't be
- * executed (e.g. if doAction has been called to execute another action
- * before this one was complete).
- */
- doAction: function (action, options) {
- var self = this;
- options = _.defaults({}, options, {
- additional_context: {},
- clear_breadcrumbs: false,
- on_close: function () {},
- on_reverse_breadcrumb: function () {},
- pushState: true,
- replace_last_action: false,
- });
-
- // build or load an action descriptor for the given action
- var def;
- if (_.isString(action) && core.action_registry.contains(action)) {
- // action is a tag of a client action
- action = { type: 'ir.actions.client', tag: action };
- } else if (_.isNumber(action) || _.isString(action)) {
- // action is an id or xml id
- def = this._loadAction(action, {
- active_id: options.additional_context.active_id,
- active_ids: options.additional_context.active_ids,
- active_model: options.additional_context.active_model,
- }).then(function (result) {
- action = result;
- });
- }
-
- return this.dp.add(Promise.resolve(def)).then(function () {
- // action.target 'main' is equivalent to 'current' except that it
- // also clears the breadcrumbs
- options.clear_breadcrumbs = action.target === 'main' ||
- options.clear_breadcrumbs;
-
- self._preprocessAction(action, options);
-
- return self._handleAction(action, options).then(function () {
- // now that the action has been executed, force its 'pushState'
- // flag to 'true', as we don't want to prevent its controller
- // from pushing its state if it changes in the future
- action.pushState = true;
-
- return action;
- });
- }).then(function(action) {
- self.trigger_up('webclient_started');
- return action;
- });
- },
- /**
- * Compatibility with client actions that are still using do_push_state.
- *
- * @todo: convert all of them to trigger_up('push_state') instead.
- * @param {Object} state
- */
- do_push_state: function (state) {
- this.trigger_up('push_state', {state: state});
- },
- /**
- * Returns the action of the last controller in the controllerStack, i.e.
- * the action of the currently displayed controller in the main window (not
- * in a dialog), and null if there is no controller in the stack.
- *
- * @returns {Object|null}
- */
- getCurrentAction: function () {
- var controller = this.getCurrentController();
- return controller ? this.actions[controller.actionID] : null;
- },
- /**
- * Returns the last controller in the controllerStack, i.e. the currently
- * displayed controller in the main window (not in a dialog), and
- * null if there is no controller in the stack.
- *
- * @returns {Object|null}
- */
- getCurrentController: function () {
- var currentControllerID = _.last(this.controllerStack);
- return currentControllerID ? this.controllers[currentControllerID] : null;
- },
- /**
- * Updates the UI according to the given state, for instance, executes a new
- * action, or updates the state of the current action.
- *
- * @param {Object} state
- * @param {integer|string} [state.action] the action to execute (given its
- * id or tag for client actions)
- * @returns {Promise} resolved when the UI has been updated
- */
- loadState: function (state) {
- var action;
- if (!state.action) {
- return Promise.resolve();
- }
- if (_.isString(state.action) && core.action_registry.contains(state.action)) {
- action = {
- params: state,
- tag: state.action,
- type: 'ir.actions.client',
- };
- } else {
- action = state.action;
- }
- return this.doAction(action, {
- clear_breadcrumbs: true,
- pushState: false,
- });
- },
-
- //--------------------------------------------------------------------------
- // Private
- //--------------------------------------------------------------------------
-
- /**
- * Appends the given controller to the DOM and restores its scroll position.
- * Also updates the control panel.
- *
- * @private
- * @param {Object} controller
- */
- _appendController: function (controller) {
- dom.append(this.$el, controller.widget.$el, {
- in_DOM: this.isInDOM,
- callbacks: [{widget: controller.widget}],
- });
-
- if (controller.scrollPosition) {
- this.trigger_up('scrollTo', controller.scrollPosition);
- }
- },
- /**
- * Closes the current dialog, if any. Because we listen to the 'closed'
- * event triggered by the dialog when it is closed, this also destroys the
- * embedded controller and removes the reference to the corresponding action.
- * This also executes the 'on_close' handler in some cases, and may also
- * provide infos for closing this dialog.
- *
- * @private
- * @param {Object} options
- * @param {Object} [options.infos] some infos related to the closing the
- * dialog.
- * @param {boolean} [options.silent=false] if true, the 'on_close' handler
- * won't be called ; this is in general the case when the current dialog
- * is closed because another action is opened, so we don't want the former
- * action to execute its handler as it won't be displayed anyway
- */
- _closeDialog: function (options) {
- if (this.currentDialogController) {
- this.currentDialogController.dialog.destroy(options);
- }
- },
- /**
- * Detaches the current controller from the DOM and stores its scroll
- * position, in case we'd come back to that controller later.
- *
- * @private
- */
- _detachCurrentController: function () {
- var currentController = this.getCurrentController();
- if (currentController) {
- currentController.scrollPosition = this._getScrollPosition();
- dom.detach([{widget: currentController.widget}]);
- }
- },
- /**
- * Executes actions for which a controller has to be appended to the DOM,
- * either in the main content (target="current", by default), or in a dialog
- * (target="new").
- *
- * @private
- * @param {Object} action
- * @param {widget} action.controller a Widget instance to append to the DOM
- * @param {string} [action.target="current"] set to "new" to render the
- * controller in a dialog
- * @param {Object} options @see doAction for details
- * @returns {Promise} resolved when the controller is started and appended
- */
- _executeAction: function (action, options) {
- var self = this;
- this.actions[action.jsID] = action;
-
- if (action.target === 'new') {
- return this._executeActionInDialog(action, options);
- }
-
- var controller = self.controllers[action.controllerID];
- return this.clearUncommittedChanges()
- .then(function () {
- return self.dp.add(self._startController(controller));
- })
- .then(function () {
- if (self.currentDialogController) {
- self._closeDialog({ silent: true });
- }
-
- // store the optional 'on_reverse_breadcrumb' handler
- // AAB: store it on the AbstractAction instance, and call it
- // automatically when the action is restored
- if (options.on_reverse_breadcrumb) {
- var currentAction = self.getCurrentAction();
- if (currentAction) {
- currentAction.on_reverse_breadcrumb = options.on_reverse_breadcrumb;
- }
- }
-
- // update the internal state and the DOM
- self._pushController(controller);
-
- // store the action into the sessionStorage so that it can be
- // fully restored on F5
- self.call('session_storage', 'setItem', 'current_action', action._originalAction);
-
- return action;
- })
- .guardedCatch(function () {
- self._removeAction(action.jsID);
- });
- },
- /**
- * Executes actions with attribute target='new'. Such actions are rendered
- * in a dialog.
- *
- * @private
- * @param {Object} action
- * @param {Object} options @see doAction for details
- * @returns {Promise} resolved when the controller is rendered inside a
- * dialog appended to the DOM
- */
- _executeActionInDialog: function (action, options) {
- var self = this;
- var controller = this.controllers[action.controllerID];
- var widget = controller.widget;
-
- return this._startController(controller).then(function (controller) {
- var prevDialogOnClose;
- if (self.currentDialogController) {
- prevDialogOnClose = self.currentDialogController.onClose;
- self._closeDialog({ silent: true });
- }
-
- controller.onClose = prevDialogOnClose || options.on_close;
- var dialog = new Dialog(self, _.defaults({}, options, {
- buttons: [],
- dialogClass: controller.className,
- title: action.name,
- size: action.context.dialog_size,
- }));
- /**
- * @param {Object} [options={}]
- * @param {Object} [options.infos] if provided and `silent` is
- * unset, the `on_close` handler will pass this information,
- * which gives some context for closing this dialog.
- * @param {boolean} [options.silent=false] if set, do not call the
- * `on_close` handler.
- */
- dialog.on('closed', self, function (options) {
- options = options || {};
- self._removeAction(action.jsID);
- self.currentDialogController = null;
- if (options.silent !== true) {
- controller.onClose(options.infos);
- }
- });
- controller.dialog = dialog;
-
- return dialog.open().opened(function () {
- self.currentDialogController = controller;
- widget.setParent(dialog);
- dom.append(dialog.$el, widget.$el, {
- in_DOM: true,
- callbacks: [{widget: controller.widget}],
- });
- widget.renderButtons(dialog.$footer);
- dialog.rebindButtonBehavior();
-
- return action;
- });
- }).guardedCatch(function () {
- self._removeAction(action.jsID);
- });
- },
- /**
- * Executes actions of type 'ir.actions.client'.
- *
- * @private
- * @param {Object} action the description of the action to execute
- * @param {string} action.tag the key of the action in the action_registry
- * @param {Object} options @see doAction for details
- * @returns {Promise} resolved when the client action has been executed
- */
- _executeClientAction: function (action, options) {
- var self = this;
- var ClientAction = core.action_registry.get(action.tag);
- if (!ClientAction) {
- console.error("Could not find client action " + action.tag, action);
- return Promise.reject();
- }
- if (!(ClientAction.prototype instanceof Widget)) {
- // the client action might be a function, which is executed and
- // whose returned value might be another action to execute
- var next = ClientAction(this, action);
- if (next) {
- return this.doAction(next, options);
- }
- return Promise.resolve();
- }
- if (!(ClientAction.prototype instanceof AbstractAction)) {
- console.warn('The client action ' + action.tag + ' should be an instance of AbstractAction!');
- }
-
- var controllerID = _.uniqueId('controller_');
-
- var index = this._getControllerStackIndex(options);
- options.breadcrumbs = this._getBreadcrumbs(this.controllerStack.slice(0, index));
- options.controllerID = controllerID;
- var widget = new ClientAction(this, action, options);
- var controller = {
- actionID: action.jsID,
- index: index,
- jsID: controllerID,
- title: widget.getTitle(),
- widget: widget,
- };
- this.controllers[controllerID] = controller;
- action.controllerID = controllerID;
- var prom = this._executeAction(action, options);
- prom.then(function () {
- self._pushState(controllerID, {});
- });
- return prom;
- },
- /**
- * Executes actions of type 'ir.actions.act_window_close', i.e. closes the
- * last opened dialog.
- *
- * The action may also specify an effect to display right after the close
- * action (e.g. rainbow man), or provide a reason for the close action.
- * This is useful for decision making for the `on_close` handler.
- *
- * @private
- * @param {Object} action
- * @param {Object} [action.effect] effect to show up, e.g. rainbow man.
- * @param {Object} [action.infos] infos on performing the close action.
- * Useful for providing some context for the `on_close` handler.
- * @returns {Promise} resolved immediately
- */
- _executeCloseAction: function (action, options) {
- var result;
- if (!this.currentDialogController) {
- result = options.on_close(action.infos);
- }
-
- this._closeDialog({ infos: action.infos });
-
- // display some effect (like rainbowman) on appropriate actions
- if (action.effect) {
- this.trigger_up('show_effect', action.effect);
- }
-
- return Promise.resolve(result);
- },
- /**
- * Executes actions of type 'ir.actions.server'.
- *
- * @private
- * @param {Object} action the description of the action to execute
- * @param {integer} action.id the db ID of the action to execute
- * @param {Object} [action.context]
- * @param {Object} options @see doAction for details
- * @returns {Promise} resolved when the action has been executed
- */
- _executeServerAction: function (action, options) {
- var self = this;
- var runDef = this._rpc({
- route: '/web/action/run',
- params: {
- action_id: action.id,
- context: action.context || {},
- },
- });
- return this.dp.add(runDef).then(function (action) {
- action = action || { type: 'ir.actions.act_window_close' };
- return self.doAction(action, options);
- });
- },
- /**
- * Executes actions of type 'ir.actions.act_url', i.e. redirects to the
- * given url.
- *
- * @private
- * @param {Object} action the description of the action to execute
- * @param {string} action.url
- * @param {string} [action.target] set to 'self' to redirect in the current page,
- * redirects to a new page by default
- * @param {Object} options @see doAction for details
- * @returns {Promise} resolved when the redirection is done (immediately
- * when redirecting to a new page)
- */
- _executeURLAction: function (action, options) {
- var url = action.url;
-
- if (action.target === 'self') {
- framework.redirect(url);
- return Promise.resolve();
- } else {
- var w = window.open(url, '_blank');
- if (!w || w.closed || typeof w.closed === 'undefined') {
- var message = _t('A popup window has been blocked. You ' +
- 'may need to change your browser settings to allow ' +
- 'popup windows for this page.');
- this.displayNotification({ message, type: 'danger' });
- }
- }
-
- options.on_close();
-
- return Promise.resolve();
- },
- /**
- * Returns a description of the controllers in the given controller stack.
- * It is used to render the breadcrumbs. It is an array of Objects with keys
- * 'title' (what to display in the breadcrumbs) and 'controllerID' (the ID
- * of the corresponding controller, used to restore it when this part of the
- * breadcrumbs is clicked).
- *
- * @private
- * @param {string[]} controllerStack
- * @returns {Object[]}
- */
- _getBreadcrumbs: function (controllerStack) {
- var self = this;
- return _.map(controllerStack, function (controllerID) {
- return {
- controllerID: controllerID,
- title: self.controllers[controllerID].title,
- };
- });
- },
- /**
- * Returns the index where a controller should be inserted in the controller
- * stack according to the given options. By default, a controller is pushed
- * on the top of the stack.
- *
- * @private
- * @param {options} [options.clear_breadcrumbs=false] if true, insert at
- * index 0 and remove all other controllers
- * @param {options} [options.index=null] if given, that index is returned
- * @param {options} [options.replace_last_action=false] if true, replace the
- * last controller of the stack
- * @returns {integer} index
- */
- _getControllerStackIndex: function (options) {
- var index;
- if ('index' in options) {
- index = options.index;
- } else if (options.clear_breadcrumbs) {
- index = 0;
- } else if (options.replace_last_action) {
- index = this.controllerStack.length - 1;
- } else {
- index = this.controllerStack.length;
- }
- return index;
- },
- /**
- * Returns an object containing information about the given controller, like
- * its title, its action's id, the active_id and active_ids of the action...
- *
- * @private
- * @param {string} controllerID
- * @returns {Object}
- */
- _getControllerState: function (controllerID) {
- var controller = this.controllers[controllerID];
- var action = this.actions[controller.actionID];
- var state = {
- title: controller.widget.getTitle(),
- };
- if (action.id) {
- state.action = action.id;
- } else if (action.type === 'ir.actions.client') {
- state.action = action.tag;
- var params = _.pick(action.params, function (v) {
- return _.isString(v) || _.isNumber(v);
- });
- state = _.extend(params || {}, state);
- }
- if (action.context) {
- var active_id = action.context.active_id;
- if (active_id) {
- state.active_id = active_id;
- }
- var active_ids = action.context.active_ids;
- // we don't push active_ids if it's a single element array containing the active_id
- // to make the url shorter in most cases
- if (active_ids && !(active_ids.length === 1 && active_ids[0] === active_id)) {
- state.active_ids = action.context.active_ids.join(',');
- }
- }
- state = _.extend({}, controller.widget.getState(), state);
- return state;
- },
- /**
- * Returns the current horizontal and vertical scroll positions.
- *
- * @private
- * @returns {Object}
- */
- _getScrollPosition: function () {
- var scrollPosition;
- this.trigger_up('getScrollPosition', {
- callback: function (_scrollPosition) {
- scrollPosition = _scrollPosition;
- }
- });
- return scrollPosition;
- },
- /**
- * Dispatches the given action to the corresponding handler to execute it,
- * according to its type. This function can be overridden to extend the
- * range of supported action types.
- *
- * @private
- * @param {Object} action
- * @param {string} action.type
- * @param {Object} options
- * @returns {Promise} resolved when the action has been executed ; rejected
- * if the type of action isn't supported, or if the action can't be
- * executed
- */
- _handleAction: function (action, options) {
- if (!action.type) {
- console.error("No type for action", action);
- return Promise.reject();
- }
- switch (action.type) {
- case 'ir.actions.act_url':
- return this._executeURLAction(action, options);
- case 'ir.actions.act_window_close':
- return this._executeCloseAction(action, options);
- case 'ir.actions.client':
- return this._executeClientAction(action, options);
- case 'ir.actions.server':
- return this._executeServerAction(action, options);
- default:
- console.error("The ActionManager can't handle actions of type " +
- action.type, action);
- return Promise.reject();
- }
- },
- /**
- * Updates the internal state and the DOM with the given controller as
- * current controller.
- *
- * @private
- * @param {Object} controller
- * @param {string} controller.jsID
- * @param {Widget} controller.widget
- * @param {integer} controller.index the controller is pushed at that
- * position in the controller stack and controllers with an higher index
- * are destroyed
- */
- _pushController: function (controller) {
- var self = this;
-
- // detach the current controller
- this._detachCurrentController();
-
- // push the new controller to the stack at the given position, and
- // destroy controllers with an higher index
- var toDestroy = this.controllerStack.slice(controller.index);
- // reject from the list of controllers to destroy the one that we are
- // currently pushing, or those linked to the same action as the one
- // linked to the controller that we are pushing
- toDestroy = _.reject(toDestroy, function (controllerID) {
- return controllerID === controller.jsID ||
- self.controllers[controllerID].actionID === controller.actionID;
- });
- this._removeControllers(toDestroy);
- this.controllerStack = this.controllerStack.slice(0, controller.index);
- this.controllerStack.push(controller.jsID);
-
- // append the new controller to the DOM
- this._appendController(controller);
-
- // notify the environment of the new action
- this.trigger_up('current_action_updated', {
- action: this.getCurrentAction(),
- controller: controller,
- });
-
- // close all dialogs when the current controller changes
- core.bus.trigger('close_dialogs');
-
- // toggle the fullscreen mode for actions in target='fullscreen'
- this._toggleFullscreen();
- },
- /**
- * Pushes the given state, with additional information about the given
- * controller, like the action's id and the controller's title.
- *
- * @private
- * @param {string} controllerID
- * @param {Object} [state={}]
- */
- _pushState: function (controllerID, state) {
- var controller = this.controllers[controllerID];
- if (controller) {
- var action = this.actions[controller.actionID];
- if (action.target === 'new' || action.pushState === false) {
- // do not push state for actions in target="new" or for actions
- // that have been explicitly marked as not pushable
- return;
- }
- state = _.extend({}, state, this._getControllerState(controller.jsID));
- this.trigger_up('push_state', {state: state});
- }
- },
- /**
- * Loads an action from the database given its ID.
- *
- * @todo: turn this in a service (DataManager)
- * @private
- * @param {integer|string} action's ID or xml ID
- * @param {Object} context
- * @returns {Promise} resolved with the description of the action
- */
- _loadAction: function (actionID, context) {
- var self = this;
- return new Promise(function (resolve, reject) {
- self.trigger_up('load_action', {
- actionID: actionID,
- context: context,
- on_success: resolve,
- });
- });
- },
- /**
- * Preprocesses the action before it is handled by the ActionManager
- * (assigns a JS id, evaluates its context and domains, etc.).
- *
- * @param {Object} action
- * @param {Object} options see @doAction options
- */
- _preprocessAction: function (action, options) {
- // ensure that the context and domain are evaluated
- var context = new Context(this.userContext, options.additional_context, action.context);
- action.context = pyUtils.eval('context', context);
- if (action.domain) {
- action.domain = pyUtils.eval('domain', action.domain, action.context);
- }
-
- action._originalAction = JSON.stringify(action);
-
- action.jsID = _.uniqueId('action_');
- action.pushState = options.pushState;
- },
- /**
- * Unlinks the given action and its controller from the internal structures
- * and destroys its controllers.
- *
- * @private
- * @param {string} actionID the id of the action to remove
- */
- _removeAction: function (actionID) {
- var action = this.actions[actionID];
- var controller = this.controllers[action.controllerID];
- delete this.actions[action.jsID];
- delete this.controllers[action.controllerID];
- controller.widget.destroy();
- },
- /**
- * Removes the given controllers and their corresponding actions.
- *
- * @see _removeAction
- * @private
- * @param {string[]} controllerIDs
- */
- _removeControllers: function (controllerIDs) {
- var self = this;
- var actionsToRemove = _.map(controllerIDs, function (controllerID) {
- return self.controllers[controllerID].actionID;
- });
- _.each(_.uniq(actionsToRemove), this._removeAction.bind(this));
- },
- /**
- * Restores a controller from the controllerStack and destroys all
- * controllers stacked over the given controller (called when coming back
- * using the breadcrumbs).
- *
- * @private
- * @param {string} controllerID
- * @returns {Promise} resolved when the controller has been restored
- */
- _restoreController: function (controllerID) {
- var self = this;
- var controller = this.controllers[controllerID];
- // AAB: AbstractAction should define a proper hook to execute code when
- // it is restored (other than do_show), and it should return a promise
- var action = this.actions[controller.actionID];
- var def;
- if (action.on_reverse_breadcrumb) {
- def = action.on_reverse_breadcrumb();
- }
- return Promise.resolve(def).then(function () {
- return Promise.resolve(controller.widget.do_show()).then(function () {
- var index = _.indexOf(self.controllerStack, controllerID);
- self._pushController(controller, index);
- });
- });
- },
- /**
- * Starts the controller by appending it in a document fragment, so that it
- * is ready when it will be appended to the DOM. This allows to prevent
- * flickering for widgets doing async stuff in willStart() or start().
- *
- * Also updates the control panel on any change of the title on controller's
- * widget.
- *
- * @private
- * @param {Object} controller
- * @returns {Promise} resolved with the controller when it is ready
- */
- _startController: function (controller) {
- var fragment = document.createDocumentFragment();
- return controller.widget.appendTo(fragment).then(function () {
- return controller;
- });
- },
- /**
- * Toggles the fullscreen mode if there is an action in target='fullscreen'
- * in the current stack.
- *
- * @private
- */
- _toggleFullscreen: function () {
- var self = this;
- var fullscreen = _.some(this.controllerStack, function (controllerID) {
- var controller = self.controllers[controllerID];
- return self.actions[controller.actionID].target === 'fullscreen';
- });
- this.trigger_up('toggle_fullscreen', {fullscreen: fullscreen});
- },
-
- //--------------------------------------------------------------------------
- // Handlers
- //--------------------------------------------------------------------------
-
- /**
- * @private
- * @param {OdooEvent} ev
- * @param {string} ev.data.controllerID
- */
- _onBreadcrumbClicked: function (ev) {
- ev.stopPropagation();
- this._restoreController(ev.data.controllerID);
- },
- /**
- * Goes back in the history: if a controller is opened in a dialog, closes
- * the dialog, otherwise, restores the second to last controller from the
- * stack.
- *
- * @private
- */
- _onHistoryBack: function () {
- if (this.currentDialogController) {
- this._closeDialog();
- } else {
- var length = this.controllerStack.length;
- if (length > 1) {
- this._restoreController(this.controllerStack[length - 2]);
- }
- }
- },
- /**
- * Intercepts and triggers a new push_state event, with additional
- * information about the given controller.
- *
- * @private
- * @param {OdooEvent} ev
- * @param {string} ev.controllerID
- * @param {Object} [ev.state={}]
- */
- _onPushState: function (ev) {
- if (ev.target !== this) {
- ev.stopPropagation();
- this._pushState(ev.data.controllerID, ev.data.state);
- }
- },
- /**
- * Intercepts and triggers a redirection on a link.
- *
- * @private
- * @param {OdooEvent} ev
- * @param {integer} ev.data.res_id
- * @param {string} ev.data.res_model
- */
- _onRedirect: function (ev) {
- this.do_action({
- type:'ir.actions.act_window',
- view_mode: 'form',
- res_model: ev.data.res_model,
- views: [[false, 'form']],
- res_id: ev.data.res_id,
- });
- },
-});
-
-return ActionManager;
-
-});
diff --git a/addons/web/static/src/js/chrome/action_manager_act_window.js b/addons/web/static/src/js/chrome/action_manager_act_window.js
deleted file mode 100644
index 507d8a18217..00000000000
--- a/addons/web/static/src/js/chrome/action_manager_act_window.js
+++ /dev/null
@@ -1,736 +0,0 @@
-odoo.define('web.ActWindowActionManager', function (require) {
-"use strict";
-
-/**
- * The purpose of this file is to add the support of Odoo actions of type
- * 'ir.actions.act_window' to the ActionManager.
- */
-
-var ActionManager = require('web.ActionManager');
-var config = require('web.config');
-var Context = require('web.Context');
-var core = require('web.core');
-var pyUtils = require('web.py_utils');
-var view_registry = require('web.view_registry');
-
-ActionManager.include({
- custom_events: _.extend({}, ActionManager.prototype.custom_events, {
- execute_action: '_onExecuteAction',
- switch_view: '_onSwitchView',
- }),
-
- //--------------------------------------------------------------------------
- // Public
- //--------------------------------------------------------------------------
-
- /**
- * Override to handle the case of lazy-loaded controllers, which may be the
- * last controller in the stack, but which should not be considered as
- * current controller as they don't have an alive widget.
- *
- * Note: this function assumes that there can be at most one lazy loaded
- * controller in the stack
- *
- * @override
- */
- getCurrentController: function () {
- var currentController = this._super.apply(this, arguments);
- var action = currentController && this.actions[currentController.actionID];
- if (action && action.type === 'ir.actions.act_window' && !currentController.widget) {
- var lastControllerID = this.controllerStack.pop();
- currentController = this._super.apply(this, arguments);
- this.controllerStack.push(lastControllerID);
- }
- return currentController;
- },
- /**
- * Overrides to handle the case where an 'ir.actions.act_window' has to be
- * loaded.
- *
- * @override
- * @param {Object} state
- * @param {integer|string} [state.action] the ID or xml ID of the action to
- * execute
- * @param {integer} [state.active_id]
- * @param {string} [state.active_ids]
- * @param {integer} [state.id]
- * @param {integer} [state.view_id=false]
- * @param {string} [state.view_type]
- */
- loadState: function (state) {
- var _super = this._super.bind(this);
- var action;
- var options = {
- clear_breadcrumbs: true,
- pushState: false,
- };
- if (state.action) {
- var currentController = this.getCurrentController();
- var currentAction = currentController && this.actions[currentController.actionID];
- if (currentAction && currentAction.id === state.action &&
- currentAction.type === 'ir.actions.act_window') {
- // the action to load is already the current one, so update it
- this._closeDialog(true); // there may be a currently opened dialog, close it
- var viewOptions = {currentId: state.id};
- var viewType = state.view_type || currentController.viewType;
- return this.clearUncommittedChanges().then(() => {
- return this._switchController(currentAction, viewType, viewOptions);
- });
- } else if (!core.action_registry.contains(state.action)) {
- // the action to load isn't the current one, so execute it
- var context = {};
- if (state.active_id) {
- context.active_id = state.active_id;
- }
- if (state.active_ids) {
- // jQuery's BBQ plugin does some parsing on values that are valid integers
- // which means that if there's only one item, it will do parseInt() on it,
- // otherwise it will keep the comma seperated list as string
- context.active_ids = state.active_ids.toString().split(',').map(function (id) {
- return parseInt(id, 10) || id;
- });
- } else if (state.active_id) {
- context.active_ids = [state.active_id];
- }
- context.params = state;
- action = state.action;
- options = _.extend(options, {
- additional_context: context,
- resID: state.id || undefined, // empty string with bbq
- viewType: state.view_type,
- });
- }
- } else if (state.model && state.id) {
- action = {
- res_model: state.model,
- res_id: state.id,
- type: 'ir.actions.act_window',
- views: [[state.view_id || false, 'form']],
- };
- } else if (state.model && state.view_type) {
- // this is a window action on a multi-record view, so restore it
- // from the session storage
- var storedAction = this.call('session_storage', 'getItem', 'current_action');
- var lastAction = JSON.parse(storedAction || '{}');
- if (lastAction.res_model === state.model) {
- action = lastAction;
- options.viewType = state.view_type;
- }
- }
- if (action) {
- return this.doAction(action, options);
- }
- return _super.apply(this, arguments);
- },
-
- //--------------------------------------------------------------------------
- // Private
- //--------------------------------------------------------------------------
-
- /**
- * Instantiates the controller for a given action and view type, and adds it
- * to the list of controllers in the action.
- *
- * @private
- * @param {Object} action
- * @param {AbstractController[]} action.controllers the already created
- * controllers for this action
- * @param {Object[]} action.views the views available for the action, each
- * one containing its fieldsView
- * @param {Object} action.env
- * @param {string} viewType
- * @param {Object} [viewOptions] dict of options passed to the initialization
- * of the controller's widget
- * @param {Object} [options]
- * @param {string} [options.controllerID=false] when the controller has
- * previously been lazy-loaded, we want to keep its jsID when loading it
- * @param {integer} [options.index=0] the controller's index in the stack
- * @param {boolean} [options.lazy=false] set to true to differ the
- * initialization of the controller's widget
- * @returns {Promise} resolved with the created controller
- */
- _createViewController: function (action, viewType, viewOptions, options) {
- var self = this;
- var viewDescr = _.findWhere(action.views, {type: viewType});
- if (!viewDescr) {
- // the requested view type isn't specified in the action (e.g.
- // action with list view only, user clicks on a row in the list, it
- // tries to switch to form view)
- return Promise.reject();
- }
-
- options = options || {};
- var index = options.index || 0;
- var controllerID = options.controllerID || _.uniqueId('controller_');
- var controller = {
- actionID: action.jsID,
- className: 'o_act_window', // used to remove the padding in dialogs
- index: index,
- jsID: controllerID,
- viewType: viewType,
- };
- Object.defineProperty(controller, 'title', {
- get: function () {
- // handle the case where the widget is lazy loaded
- return controller.widget ?
- controller.widget.getTitle() :
- (action.display_name || action.name);
- },
- });
- this.controllers[controllerID] = controller;
-
- if (!options.lazy) {
- // build the view options from different sources
- var flags = action.flags || {};
- viewOptions = _.extend({}, flags, flags[viewType], viewOptions, {
- action: action,
- breadcrumbs: this._getBreadcrumbs(this.controllerStack.slice(0, index)),
- // pass the controllerID to the views as an hook for further
- // communication with trigger_up
- controllerID: controllerID,
- });
- var rejection;
- var view = new viewDescr.Widget(viewDescr.fieldsView, viewOptions);
- var def = new Promise(function (resolve, reject) {
- rejection = reject;
- view.getController(self).then(function (widget) {
- if (def.rejected) {
- // the promise has been rejected meanwhile, meaning that
- // the action has been removed, so simply destroy the widget
- widget.destroy();
- } else {
- controller.widget = widget;
- resolve(controller);
- }
- }).guardedCatch(reject);
- });
- // Need to define an reject property to call it into _destroyWindowAction
- def.reject = rejection;
- def.guardedCatch(function () {
- def.rejected = true;
- delete self.controllers[controllerID];
- });
- action.controllers[viewType] = def;
- } else {
- action.controllers[viewType] = Promise.resolve(controller);
- }
- return action.controllers[viewType];
- },
- /**
- * Destroys the controllers and search view of a given action of type
- * 'ir.actions.act_window'.
- *
- * @private
- * @param {Object} action
- */
- _destroyWindowAction: function (action) {
- var self = this;
- for (var c in action.controllers) {
- var controllerDef = action.controllers[c];
- controllerDef.then(function (controller) {
- delete self.controllers[controller.jsID];
- if (controller.widget) {
- controller.widget.destroy();
- }
- });
- // If controllerDef is not resolved yet, reject it so that the
- // controller will be correctly destroyed as soon as it'll be ready,
- // and its reference will be removed. Lazy-loaded controllers do
- // not have a reject function on their promise
- if (controllerDef.reject) {
- controllerDef.reject();
- }
- }
- },
- /**
- * Executes actions of type 'ir.actions.act_window'.
- *
- * @private
- * @param {Object} action the description of the action to execute
- * @param {Array} action.views list of tuples [viewID, viewType]
- * @param {Object} options @see doAction for details
- * @param {integer} [options.resID] the current res ID
- * @param {string} [options.viewType] the view to open
- * @returns {Promise} resolved when the action is appended to the DOM
- */
- _executeWindowAction: function (action, options) {
- var self = this;
- return this.dp.add(this._loadViews(action)).then(function (fieldsViews) {
- var views = self._generateActionViews(action, fieldsViews);
- action._views = action.views; // save the initial attribute
- action.views = views;
- action.controlPanelFieldsView = fieldsViews.search;
- action.controllers = {};
-
- // select the current view to display, and optionally the main view
- // of the action which will be lazyloaded
- var curView = options.viewType && _.findWhere(views, {type: options.viewType});
- var lazyView;
- if (curView) {
- if (!curView.multiRecord && views[0].multiRecord) {
- lazyView = views[0];
- }
- } else {
- curView = views[0];
- }
-
- // use mobile-friendly view by default in mobile, if possible
- if (config.device.isMobile) {
- if (!curView.isMobileFriendly) {
- curView = self._findMobileView(views, curView.multiRecord) || curView;
- }
- if (lazyView && !lazyView.isMobileFriendly) {
- lazyView = self._findMobileView(views, lazyView.multiRecord) || lazyView;
- }
- }
-
- var lazyViewDef;
- var lazyControllerID;
- if (lazyView) {
- // if the main view is lazy-loaded, its (lazy-loaded) controller is inserted
- // into the controller stack (so that breadcrumbs can be correctly computed),
- // so we force clear_breadcrumbs to false so that it won't be removed when the
- // current controller will be inserted afterwards
- options.clear_breadcrumbs = false;
- // this controller being lazy-loaded, this call is actually sync
- lazyViewDef = self._createViewController(action, lazyView.type, {}, {lazy: true})
- .then(function (lazyLoadedController) {
- lazyControllerID = lazyLoadedController.jsID;
- self.controllerStack.push(lazyLoadedController.jsID);
- });
- }
- return self.dp.add(Promise.resolve(lazyViewDef))
- .then(function () {
- var viewOptions = {
- controllerState: options.controllerState,
- currentId: options.resID,
- };
- var curViewDef = self._createViewController(action, curView.type, viewOptions, {
- index: self._getControllerStackIndex(options),
- });
- return self.dp.add(curViewDef);
- })
- .then(function (controller) {
- action.controllerID = controller.jsID;
- return self._executeAction(action, options);
- })
- .guardedCatch(function () {
- if (lazyControllerID) {
- var index = self.controllerStack.indexOf(lazyControllerID);
- self.controllerStack = self.controllerStack.slice(0, index);
- }
- self._destroyWindowAction(action);
- });
- });
- },
- /**
- * Helper function to find the first mobile-friendly view, if any.
- *
- * @private
- * @param {Array} views an array of views
- * @param {boolean} multiRecord set to true iff we search for a multiRecord
- * view
- * @returns {Object|undefined} a mobile-friendly view of the requested
- * multiRecord type, undefined if there is no such view
- */
- _findMobileView: function (views, multiRecord) {
- return _.findWhere(views, {
- isMobileFriendly: true,
- multiRecord: multiRecord,
- });
- },
- /**
- * Generate the description of the views of a given action. For each view,
- * it generates a dict with information like the fieldsView, the view type,
- * the Widget to use...
- *
- * @private
- * @param {Object} action
- * @param {Object} fieldsViews
- * @returns {Object}
- */
- _generateActionViews: function (action, fieldsViews) {
- var views = [];
- _.each(action.views, function (view) {
- var viewType = view[1];
- var fieldsView = fieldsViews[viewType];
- var parsedXML = new DOMParser().parseFromString(fieldsView.arch, "text/xml");
- var key = parsedXML.documentElement.getAttribute('js_class');
- var View = view_registry.get(key || viewType);
- if (View) {
- views.push({
- accessKey: View.prototype.accessKey || View.prototype.accesskey,
- displayName: View.prototype.display_name,
- fieldsView: fieldsView,
- icon: View.prototype.icon,
- isMobileFriendly: View.prototype.mobile_friendly,
- multiRecord: View.prototype.multi_record,
- type: viewType,
- viewID: view[0],
- Widget: View,
- });
- } else if (config.isDebug('assets')) {
- console.log("View type '" + viewType + "' is not present in the view registry.");
- }
- });
- return views;
- },
- /**
- * Overrides to add specific information for controllers from actions of
- * type 'ir.actions.act_window', like the res_model and the view_type.
- *
- * @override
- * @private
- */
- _getControllerState: function (controllerID) {
- var state = this._super.apply(this, arguments);
- var controller = this.controllers[controllerID];
- var action = this.actions[controller.actionID];
- if (action.type === 'ir.actions.act_window') {
- state.model = action.res_model;
- state.view_type = controller.viewType;
- }
- return state;
- },
- /**
- * Overrides to handle the 'ir.actions.act_window' actions.
- *
- * @override
- * @private
- */
- _handleAction: function (action, options) {
- if (action.type === 'ir.actions.act_window') {
- return this._executeWindowAction(action, options);
- }
- return this._super.apply(this, arguments);
- },
- /**
- * Loads the fields_views and fields for the given action.
- *
- * @private
- * @param {Object} action
- * @returns {Promise}
- */
- _loadViews: function (action) {
- var inDialog = action.target === 'new';
- var inline = action.target === 'inline';
- var options = {
- action_id: action.id,
- toolbar: !inDialog && !inline,
- };
- var views = action.views.slice();
- if (!inline && !(inDialog && action.views[0][1] === 'form')) {
- options.load_filters = true;
- var searchviewID = action.search_view_id && action.search_view_id[0];
- views.push([searchviewID || false, 'search']);
- }
- return this.loadViews(action.res_model, action.context, views, options);
- },
- /**
- * Overrides to handle the case of 'ir.actions.act_window' actions, i.e.
- * destroys all controllers associated to the given action, and its search
- * view.
- *
- * @override
- * @private
- */
- _removeAction: function (actionID) {
- var action = this.actions[actionID];
- if (action.type === 'ir.actions.act_window') {
- delete this.actions[action.jsID];
- this._destroyWindowAction(action);
- } else {
- this._super.apply(this, arguments);
- }
- },
- /**
- * Overrides to handle the case where the controller to restore is from an
- * 'ir.actions.act_window' action. In this case, only the controllers
- * stacked over the one to restore *that are not from the same action* are
- * destroyed.
- * For instance, when going back to the list controller from a form
- * controller of the same action using the breadcrumbs, the form controller
- * isn't destroyed, as it might be reused in the future.
- *
- * @override
- * @private
- */
- _restoreController: function (controllerID) {
- var self = this;
- var controller = this.controllers[controllerID];
- var action = this.actions[controller.actionID];
- if (action.type === 'ir.actions.act_window') {
- return this.clearUncommittedChanges().then(function () {
- // AAB: this will be done directly in AbstractAction's restore
- // function
- var def = Promise.resolve();
- if (action.on_reverse_breadcrumb) {
- def = action.on_reverse_breadcrumb();
- }
- return Promise.resolve(def).then(function () {
- return self._switchController(action, controller.viewType);
- });
- });
- }
- return this._super.apply(this, arguments);
- },
- /**
- * Handles the switch from a controller to another (either inside the same
- * window action, or from a window action to another using the breadcrumbs).
- *
- * @private
- * @param {Object} controller the controller to switch to
- * @param {Object} [viewOptions]
- * @return {Promise} resolved when the new controller is in the DOM
- */
- _switchController: function (action, viewType, viewOptions) {
- var self = this;
- var view = _.findWhere(action.views, {type: viewType});
- if (!view) {
- // can't switch to an unknown view
- return Promise.reject();
- }
-
- var currentController = this.getCurrentController();
- var index;
- if (currentController.actionID !== action.jsID) {
- // the requested controller is from another action, so we went back
- // to a previous action using the breadcrumbs
- var controller = _.findWhere(this.controllers, {
- actionID: action.jsID,
- viewType: viewType,
- });
- index = _.indexOf(this.controllerStack, controller.jsID);
- } else {
- // the requested controller is from the same action as the current
- // one, so we either
- // 1) go one step back from a mono record view to a multi record
- // one using the breadcrumbs
- // 2) or we switched from a view to another using the view
- // switcher
- // 3) or we opened a record from a multi record view
- if (view.multiRecord) {
- // cases 1) and 2) (with multi record views): replace the first
- // controller linked to the same action in the stack
- index = _.findIndex(this.controllerStack, function (controllerID) {
- return self.controllers[controllerID].actionID === action.jsID;
- });
- } else if (!_.findWhere(action.views, {type: currentController.viewType}).multiRecord) {
- // case 2) (with mono record views): replace the last
- // controller by the new one if they are from the same action
- // and if they both are mono record
- index = this.controllerStack.length - 1;
- } else {
- // case 3): insert the controller on the top of the controller
- // stack
- index = this.controllerStack.length;
- }
- }
-
- var newController = function (controllerID) {
- var options = {
- controllerID: controllerID,
- index: index,
- };
- return self
- ._createViewController(action, viewType, viewOptions, options)
- .then(function (controller) {
- return self._startController(controller);
- });
- };
-
- var controllerDef = action.controllers[viewType];
- if (controllerDef) {
- controllerDef = controllerDef.then(function (controller) {
- if (!controller.widget) {
- // lazy loaded -> load it now (with same jsID)
- return newController(controller.jsID);
- } else {
- return Promise.resolve(controller.widget.willRestore()).then(function () {
- viewOptions = _.extend({}, viewOptions, {
- breadcrumbs: self._getBreadcrumbs(self.controllerStack.slice(0, index)),
- shouldUpdateSearchComponents: true,
- });
- return controller.widget.reload(viewOptions).then(function () {
- return controller;
- });
- });
- }
- }, function () {
- // if the controllerDef is rejected, it probably means that the js
- // code or the requests made to the server crashed. In that case,
- // if we reuse the same promise, then the switch to the view is
- // definitely blocked. We want to use a new controller, even though
- // it is very likely that it will recrash again. At least, it will
- // give more feedback to the user, and it could happen that one
- // record crashes, but not another.
- return newController();
- });
- } else {
- controllerDef = newController();
- }
-
- return this.dp.add(controllerDef).then(function (controller) {
- return self._pushController(controller);
- });
- },
-
- //--------------------------------------------------------------------------
- // Handlers
- //--------------------------------------------------------------------------
-
- /**
- * Handler for event 'execute_action', which is typically called when a
- * button is clicked. The button may be of type 'object' (call a given
- * method of a given model) or 'action' (execute a given action).
- * Alternatively, the button may have the attribute 'special', and in this
- * case an 'ir.actions.act_window_close' is executed.
- *
- * @private
- * @param {OdooEvent} ev
- * @param {Object} ev.data.action_data typically, the html attributes of the
- * button extended with additional information like the context
- * @param {Object} [ev.data.action_data.special=false]
- * @param {Object} [ev.data.action_data.type] 'object' or 'action', if set
- * @param {Object} ev.data.env
- * @param {function} [ev.data.on_closed]
- * @param {function} [ev.data.on_fail]
- * @param {function} [ev.data.on_success]
- */
- _onExecuteAction: function (ev) {
- ev.stopPropagation();
- var self = this;
- var actionData = ev.data.action_data;
- var env = ev.data.env;
- var context = new Context(env.context, actionData.context || {});
- var recordID = env.currentID || null; // pyUtils handles null value, not undefined
- var def;
-
- // determine the action to execute according to the actionData
- if (actionData.special) {
- def = Promise.resolve({
- type: 'ir.actions.act_window_close',
- infos: { special: true },
- });
- } else if (actionData.type === 'object') {
- // call a Python Object method, which may return an action to execute
- var args = recordID ? [[recordID]] : [env.resIDs];
- if (actionData.args) {
- try {
- // warning: quotes and double quotes problem due to json and xml clash
- // maybe we should force escaping in xml or do a better parse of the args array
- var additionalArgs = JSON.parse(actionData.args.replace(/'/g, '"'));
- args = args.concat(additionalArgs);
- } catch (e) {
- console.error("Could not JSON.parse arguments", actionData.args);
- }
- }
- def = this._rpc({
- route: '/web/dataset/call_button',
- params: {
- args: args,
- kwargs: {context: context.eval()},
- method: actionData.name,
- model: env.model,
- },
- });
- } else if (actionData.type === 'action') {
- // execute a given action, so load it first
- def = this._loadAction(actionData.name, _.extend(pyUtils.eval('context', context), {
- active_model: env.model,
- active_ids: env.resIDs,
- active_id: recordID,
- }));
- } else {
- def = Promise.reject();
- }
-
- // use the DropPrevious to prevent from executing the handler if another
- // request (doAction, switchView...) has been done meanwhile ; execute
- // the fail handler if the 'call_button' or 'loadAction' failed but not
- // if the request failed due to the DropPrevious,
- def.guardedCatch(ev.data.on_fail);
- this.dp.add(def).then(function (action) {
- // show effect if button have effect attribute
- // rainbowman can be displayed from two places: from attribute on a button or from python
- // code below handles the first case i.e 'effect' attribute on button.
- var effect = false;
- if (actionData.effect) {
- effect = pyUtils.py_eval(actionData.effect);
- }
-
- if (action && action.constructor === Object) {
- // filter out context keys that are specific to the current action, because:
- // - wrong default_* and search_default_* values won't give the expected result
- // - wrong group_by values will fail and forbid rendering of the destination view
- var ctx = new Context(
- _.object(_.reject(_.pairs(env.context), function (pair) {
- return pair[0].match('^(?:(?:default_|search_default_|show_).+|' +
- '.+_view_ref|group_by|group_by_no_leaf|active_id|' +
- 'active_ids|orderedBy)$') !== null;
- }))
- );
- ctx.add(actionData.context || {});
- ctx.add({active_model: env.model});
- if (recordID) {
- ctx.add({
- active_id: recordID,
- active_ids: [recordID],
- });
- }
- ctx.add(action.context || {});
- action.context = ctx;
- // in case an effect is returned from python and there is already an effect
- // attribute on the button, the priority is given to the button attribute
- action.effect = effect || action.effect;
- } else {
- // if action doesn't return anything, but there is an effect
- // attribute on the button, display rainbowman
- action = {
- effect: effect,
- type: 'ir.actions.act_window_close',
- };
- }
- var options = {on_close: ev.data.on_closed};
- if (config.device.isMobile && actionData.mobile) {
- options = Object.assign({}, options, actionData.mobile);
- }
- return self.doAction(action, options).then(ev.data.on_success, ev.data.on_fail);
- });
- },
- /**
- * @private
- * @param {OdooEvent} ev
- * @param {string} ev.data.controllerID the id of the controller that
- * triggered the event
- * @param {string} ev.data.viewType the type of view to switch to
- * @param {integer} [ev.data.res_id] the id of the record to open (for
- * mono-record views)
- * @param {mode} [ev.data.mode] the mode to open, i.e. 'edit' or 'readonly'
- * (only relevant for form views)
- */
- _onSwitchView: function (ev) {
- ev.stopPropagation();
- const viewType = ev.data.view_type;
- const currentController = this.getCurrentController();
- if (currentController.jsID === ev.data.controllerID) {
- // only switch to the requested view if the controller that
- // triggered the request is the current controller
- const action = this.actions[currentController.actionID];
- const currentControllerState = currentController.widget.exportState();
- action.controllerState = _.extend({}, action.controllerState, currentControllerState);
- const options = {
- controllerState: action.controllerState,
- currentId: ev.data.res_id,
- };
- if (ev.data.mode) {
- options.mode = ev.data.mode;
- }
- this.clearUncommittedChanges().then(() => {
- return this._switchController(action, viewType, options);
- });
- }
- },
-});
-
-});
diff --git a/addons/web/static/src/js/chrome/action_manager_report.js b/addons/web/static/src/js/chrome/action_manager_report.js
deleted file mode 100644
index 2515f73ad6e..00000000000
--- a/addons/web/static/src/js/chrome/action_manager_report.js
+++ /dev/null
@@ -1,203 +0,0 @@
-odoo.define('web.ReportActionManager', function (require) {
-"use strict";
-
-/**
- * The purpose of this file is to add the support of Odoo actions of type
- * 'ir.actions.report' to the ActionManager.
- */
-
-var ActionManager = require('web.ActionManager');
-var core = require('web.core');
-var framework = require('web.framework');
-var session = require('web.session');
-
-
-var _t = core._t;
-var _lt = core._lt;
-
-// Messages that might be shown to the user dependening on the state of wkhtmltopdf
-var link = 'wkhtmltopdf.org ';
-var WKHTMLTOPDF_MESSAGES = {
- broken: _lt('Your installation of Wkhtmltopdf seems to be broken. The report will be shown ' +
- 'in html.') + link,
- install: _lt('Unable to find Wkhtmltopdf on this system. The report will be shown in ' +
- 'html.') + link,
- upgrade: _lt('You should upgrade your version of Wkhtmltopdf to at least 0.12.0 in order to ' +
- 'get a correct display of headers and footers as well as support for ' +
- 'table-breaking between pages.') + link,
- workers: _lt('You need to start Odoo with at least two workers to print a pdf version of ' +
- 'the reports.'),
-};
-
-ActionManager.include({
- //--------------------------------------------------------------------------
- // Private
- //--------------------------------------------------------------------------
-
- /**
- * Downloads a PDF report for the given url. It blocks the UI during the
- * report generation and download.
- *
- * @param {string} url
- * @returns {Promise} resolved when the report has been downloaded ;
- * rejected if something went wrong during the report generation
- */
- _downloadReport: function (url) {
- var self = this;
- framework.blockUI();
- return new Promise(function (resolve, reject) {
- var type = 'qweb-' + url.split('/')[2];
- var blocked = !session.get_file({
- url: '/report/download',
- data: {
- data: JSON.stringify([url, type]),
- context: JSON.stringify(session.user_context),
- },
- success: resolve,
- error: (error) => {
- self.call('crash_manager', 'rpc_error', error);
- reject();
- },
- complete: framework.unblockUI,
- });
- if (blocked) {
- // AAB: this check should be done in get_file service directly,
- // should not be the concern of the caller (and that way, get_file
- // could return a promise)
- var message = _t('A popup window with your report was blocked. You ' +
- 'may need to change your browser settings to allow ' +
- 'popup windows for this page.');
- self.displayNotification({ title: _t('Warning'), message, sticky: true, type: 'danger' });
- }
- });
- },
-
- /**
- * Launch download action of the report
- *
- * @private
- * @param {Object} action the description of the action to execute
- * @param {Object} options @see doAction for details
- * @returns {Promise} resolved when the action has been executed
- */
- _triggerDownload: function (action, options, type){
- var self = this;
- var reportUrls = this._makeReportUrls(action);
- return this._downloadReport(reportUrls[type]).then(function () {
- if (action.close_on_report_download) {
- var closeAction = { type: 'ir.actions.act_window_close' };
- return self.doAction(closeAction, _.pick(options, 'on_close'));
- } else {
- return options.on_close();
- }
- });
- },
- /**
- * Executes actions of type 'ir.actions.report'.
- *
- * @private
- * @param {Object} action the description of the action to execute
- * @param {Object} options @see doAction for details
- * @returns {Promise} resolved when the action has been executed
- */
- _executeReportAction: function (action, options) {
- var self = this;
-
- if (action.report_type === 'qweb-html') {
- return this._executeReportClientAction(action, options);
- } else if (action.report_type === 'qweb-pdf') {
- // check the state of wkhtmltopdf before proceeding
- return this.call('report', 'checkWkhtmltopdf').then(function (state) {
- // display a notification according to wkhtmltopdf's state
- if (state in WKHTMLTOPDF_MESSAGES) {
- self.displayNotification({ title: _t('Report'), message: WKHTMLTOPDF_MESSAGES[state], sticky: true });
- }
-
- if (state === 'upgrade' || state === 'ok') {
- // trigger the download of the PDF report
- return self._triggerDownload(action, options, 'pdf');
- } else {
- // open the report in the client action if generating the PDF is not possible
- return self._executeReportClientAction(action, options);
- }
- });
- } else if (action.report_type === 'qweb-text') {
- return self._triggerDownload(action, options, 'text');
- } else {
- console.error("The ActionManager can't handle reports of type " +
- action.report_type, action);
- return Promise.reject();
- }
- },
- /**
- * Executes the report client action, either because the report_type is
- * 'qweb-html', or because the PDF can't be generated by wkhtmltopdf (in
- * the case of 'qweb-pdf' reports).
- *
- * @param {Object} action
- * @param {Object} options
- * @returns {Promise} resolved when the client action has been executed
- */
- _executeReportClientAction: function (action, options) {
- var urls = this._makeReportUrls(action);
- var clientActionOptions = _.extend({}, options, {
- context: action.context,
- data: action.data,
- display_name: action.display_name,
- name: action.name,
- report_file: action.report_file,
- report_name: action.report_name,
- report_url: urls.html,
- });
- return this.doAction('report.client_action', clientActionOptions);
- },
- /**
- * Overrides to handle the 'ir.actions.report' actions.
- *
- * @override
- * @private
- */
- _handleAction: function (action, options) {
- if (action.type === 'ir.actions.report') {
- return this._executeReportAction(action, options);
- }
- return this._super.apply(this, arguments);
- },
- /**
- * Generates an object containing the report's urls (as value) for every
- * qweb-type we support (as key). It's convenient because we may want to use
- * another report's type at some point (for example, when `qweb-pdf` is not
- * available).
- *
- * @param {Object} action
- * @returns {Object}
- */
- _makeReportUrls: function (action) {
- var reportUrls = {
- html: '/report/html/' + action.report_name,
- pdf: '/report/pdf/' + action.report_name,
- text: '/report/text/' + action.report_name,
- };
- // We may have to build a query string with `action.data`. It's the place
- // were report's using a wizard to customize the output traditionally put
- // their options.
- if (_.isUndefined(action.data) || _.isNull(action.data) ||
- (_.isObject(action.data) && _.isEmpty(action.data))) {
- if (action.context.active_ids) {
- var activeIDsPath = '/' + action.context.active_ids.join(',');
- reportUrls = _.mapObject(reportUrls, function (value) {
- return value += activeIDsPath;
- });
- }
- reportUrls.html += '?context=' + encodeURIComponent(JSON.stringify(session.user_context));
- } else {
- var serializedOptionsPath = '?options=' + encodeURIComponent(JSON.stringify(action.data));
- serializedOptionsPath += '&context=' + encodeURIComponent(JSON.stringify(action.context));
- reportUrls = _.mapObject(reportUrls, function (value) {
- return value += serializedOptionsPath;
- });
- }
- return reportUrls;
- },
-});
-});
diff --git a/addons/web/static/src/js/chrome/apps_menu.js b/addons/web/static/src/js/chrome/apps_menu.js
deleted file mode 100644
index b7e057f80fb..00000000000
--- a/addons/web/static/src/js/chrome/apps_menu.js
+++ /dev/null
@@ -1,102 +0,0 @@
-odoo.define('web.AppsMenu', function (require) {
-"use strict";
-
-var Widget = require('web.Widget');
-
-var AppsMenu = Widget.extend({
- template: 'AppsMenu',
- events: {
- 'click .o_app': '_onAppsMenuItemClicked',
- },
- /**
- * @override
- * @param {web.Widget} parent
- * @param {Object} menuData
- * @param {Object[]} menuData.children
- */
- init: function (parent, menuData) {
- this._super.apply(this, arguments);
- this._activeApp = undefined;
- this._apps = _.map(menuData.children, function (appMenuData) {
- return {
- actionID: parseInt(appMenuData.action.split(',')[1]),
- menuID: appMenuData.id,
- name: appMenuData.name,
- xmlID: appMenuData.xmlid,
- };
- });
- },
-
- //--------------------------------------------------------------------------
- // Public
- //--------------------------------------------------------------------------
-
- /**
- * @returns {Object[]}
- */
- getApps: function () {
- return this._apps;
- },
- /**
- * Open the first app in the list of apps. Returns whether one was found.
- *
- * @returns {Boolean}
- */
- openFirstApp: function () {
- if (!this._apps.length) {
- return false;
- }
- var firstApp = this._apps[0];
- this._openApp(firstApp);
- return true;
- },
-
- //--------------------------------------------------------------------------
- // Handlers
- //--------------------------------------------------------------------------
-
- /**
- * @private
- * @param {Object} app
- */
- _openApp: function (app) {
- this._setActiveApp(app);
- this.trigger_up('app_clicked', {
- action_id: app.actionID,
- menu_id: app.menuID,
- });
- },
- /**
- * @private
- * @param {Object} app
- */
- _setActiveApp: function (app) {
- var $oldActiveApp = this.$('.o_app.active');
- $oldActiveApp.removeClass('active');
- var $newActiveApp = this.$('.o_app[data-action-id="' + app.actionID + '"]');
- $newActiveApp.addClass('active');
- },
-
- //--------------------------------------------------------------------------
- // Handlers
- //--------------------------------------------------------------------------
-
- /**
- * Called when clicking on an item in the apps menu.
- *
- * @private
- * @param {MouseEvent} ev
- */
- _onAppsMenuItemClicked: function (ev) {
- var $target = $(ev.currentTarget);
- var actionID = $target.data('action-id');
- var menuID = $target.data('menu-id');
- var app = _.findWhere(this._apps, { actionID: actionID, menuID: menuID });
- this._openApp(app);
- },
-
-});
-
-return AppsMenu;
-
-});
diff --git a/addons/web/static/src/js/chrome/loading.js b/addons/web/static/src/js/chrome/loading.js
deleted file mode 100644
index 9ea48a40c9e..00000000000
--- a/addons/web/static/src/js/chrome/loading.js
+++ /dev/null
@@ -1,80 +0,0 @@
-odoo.define('web.Loading', function (require) {
-"use strict";
-
-/**
- * Loading Indicator
- *
- * When the user performs an action, it is good to give him some feedback that
- * something is currently happening. The purpose of the Loading Indicator is to
- * display a small rectangle on the bottom right of the screen with just the
- * text 'Loading' and the number of currently running rpcs.
- *
- * After a delay of 3s, if a rpc is still not completed, we also block the UI.
- */
-
-var config = require('web.config');
-var core = require('web.core');
-var framework = require('web.framework');
-var Widget = require('web.Widget');
-
-var _t = core._t;
-
-var Loading = Widget.extend({
- template: "Loading",
-
- init: function(parent) {
- this._super(parent);
- this.count = 0;
- this.blocked_ui = false;
- },
- start: function() {
- core.bus.on('rpc_request', this, this.request_call);
- core.bus.on("rpc_response", this, this.response_call);
- core.bus.on("rpc_response_failed", this, this.response_call);
- },
- destroy: function() {
- this.on_rpc_event(-this.count);
- this._super();
- },
- request_call: function() {
- this.on_rpc_event(1);
- },
- response_call: function() {
- this.on_rpc_event(-1);
- },
- on_rpc_event : function(increment) {
- var self = this;
- if (!this.count && increment === 1) {
- // Block UI after 3s
- this.long_running_timer = setTimeout(function () {
- self.blocked_ui = true;
- framework.blockUI();
- }, 3000);
- }
-
- this.count += increment;
- if (this.count > 0) {
- if (config.isDebug()) {
- this.$el.text(_.str.sprintf( _t("Loading (%d)"), this.count));
- } else {
- this.$el.text(_t("Loading"));
- }
- this.$el.show();
- this.getParent().$el.addClass('oe_wait');
- } else {
- this.count = 0;
- clearTimeout(this.long_running_timer);
- // Don't unblock if blocked by somebody else
- if (self.blocked_ui) {
- this.blocked_ui = false;
- framework.unblockUI();
- }
- this.$el.fadeOut();
- this.getParent().$el.removeClass('oe_wait');
- }
- }
-});
-
-return Loading;
-});
-
diff --git a/addons/web/static/src/js/chrome/menu.js b/addons/web/static/src/js/chrome/menu.js
deleted file mode 100644
index 28585aa1df7..00000000000
--- a/addons/web/static/src/js/chrome/menu.js
+++ /dev/null
@@ -1,243 +0,0 @@
-odoo.define('web.Menu', function (require) {
-"use strict";
-
-var AppsMenu = require('web.AppsMenu');
-var config = require('web.config');
-var core = require('web.core');
-var dom = require('web.dom');
-var SystrayMenu = require('web.SystrayMenu');
-var UserMenu = require('web.UserMenu');
-var Widget = require('web.Widget');
-
-UserMenu.prototype.sequence = 0; // force UserMenu to be the right-most item in the systray
-SystrayMenu.Items.push(UserMenu);
-
-var QWeb = core.qweb;
-
-var Menu = Widget.extend({
- template: 'Menu',
- menusTemplate: 'Menu.sections',
- events: {
- 'mouseover .o_menu_sections > li:not(.show)': '_onMouseOverMenu',
- 'click .o_menu_brand': '_onAppNameClicked',
- },
-
- init: function (parent, menu_data) {
- var self = this;
- this._super.apply(this, arguments);
-
- this.$menu_sections = {};
- this.menu_data = menu_data;
-
- // Prepare navbar's menus
- var $menu_sections = $(QWeb.render(this.menusTemplate, {
- menu_data: this.menu_data,
- }));
- $menu_sections.filter('section').each(function () {
- self.$menu_sections[parseInt(this.className, 10)] = $(this).children('li');
- });
-
- // Bus event
- core.bus.on('change_menu_section', this, this.change_menu_section);
- },
- start: function () {
- var self = this;
-
- this.$menu_apps = this.$('.o_menu_apps');
- this.$menu_brand_placeholder = this.$('.o_menu_brand');
- this.$section_placeholder = this.$('.o_menu_sections');
- this._updateMenuBrand();
-
- // Navbar's menus event handlers
- var on_secondary_menu_click = function (ev) {
- ev.preventDefault();
- var menu_id = $(ev.currentTarget).data('menu');
- var action_id = $(ev.currentTarget).data('action-id');
- self._on_secondary_menu_click(menu_id, action_id);
- };
- var menu_ids = _.keys(this.$menu_sections);
- var primary_menu_id, $section;
- for (var i = 0; i < menu_ids.length; i++) {
- primary_menu_id = menu_ids[i];
- $section = this.$menu_sections[primary_menu_id];
- $section.on('click', 'a[data-menu]', self, on_secondary_menu_click.bind(this));
- }
-
- // Apps Menu
- this._appsMenu = new AppsMenu(self, this.menu_data);
- var appsMenuProm = this._appsMenu.appendTo(this.$menu_apps);
-
- // Systray Menu
- this.systray_menu = new SystrayMenu(this);
- var systrayMenuProm = this.systray_menu.attachTo(this.$('.o_menu_systray')).then(function() {
- self.systray_menu.on_attach_callback(); // At this point, we know we are in the DOM
- dom.initAutoMoreMenu(self.$section_placeholder, {
- maxWidth: function () {
- return self.$el.width() - (self.$menu_apps.outerWidth(true) + self.$menu_brand_placeholder.outerWidth(true) + self.systray_menu.$el.outerWidth(true));
- },
- sizeClass: 'SM',
- });
- });
-
-
-
- return Promise.all([this._super.apply(this, arguments), appsMenuProm, systrayMenuProm]);
- },
- change_menu_section: function (primary_menu_id) {
- if (!this.$menu_sections[primary_menu_id]) {
- this._updateMenuBrand();
- return; // unknown menu_id
- }
-
- if (this.current_primary_menu === primary_menu_id) {
- return; // already in that menu
- }
-
- if (this.current_primary_menu) {
- this.$menu_sections[this.current_primary_menu].detach();
- }
-
- // Get back the application name
- for (var i = 0; i < this.menu_data.children.length; i++) {
- if (this.menu_data.children[i].id === primary_menu_id) {
- this._updateMenuBrand(this.menu_data.children[i].name);
- break;
- }
- }
-
- this.$menu_sections[primary_menu_id].appendTo(this.$section_placeholder);
- this.current_primary_menu = primary_menu_id;
-
- core.bus.trigger('resize');
- },
- _trigger_menu_clicked: function (menu_id, action_id) {
- this.trigger_up('menu_clicked', {
- id: menu_id,
- action_id: action_id,
- previous_menu_id: this.current_secondary_menu || this.current_primary_menu,
- });
- },
- /**
- * Updates the name of the app in the menu to the value of brandName.
- * If brandName is falsy, hides the menu and its sections.
- *
- * @private
- * @param {brandName} string
- */
- _updateMenuBrand: function (brandName) {
- if (brandName) {
- this.$menu_brand_placeholder.text(brandName).show();
- this.$section_placeholder.show();
- } else {
- this.$menu_brand_placeholder.hide()
- this.$section_placeholder.hide();
- }
- },
- _on_secondary_menu_click: function (menu_id, action_id) {
- var self = this;
-
- // It is still possible that we don't have an action_id (for example, menu toggler)
- if (action_id) {
- self._trigger_menu_clicked(menu_id, action_id);
- this.current_secondary_menu = menu_id;
- }
- },
- /**
- * Helpers used by web_client in order to restore the state from
- * an url (by restore, read re-synchronize menu and action manager)
- */
- action_id_to_primary_menu_id: function (action_id) {
- var primary_menu_id, found;
- for (var i = 0; i < this.menu_data.children.length && !primary_menu_id; i++) {
- found = this._action_id_in_subtree(this.menu_data.children[i], action_id);
- if (found) {
- primary_menu_id = this.menu_data.children[i].id;
- }
- }
- return primary_menu_id;
- },
- _action_id_in_subtree: function (root, action_id) {
- // action_id can be a string or an integer
- if (root.action && root.action.split(',')[1] === String(action_id)) {
- return true;
- }
- var found;
- for (var i = 0; i < root.children.length && !found; i++) {
- found = this._action_id_in_subtree(root.children[i], action_id);
- }
- return found;
- },
- menu_id_to_action_id: function (menu_id, root) {
- if (!root) {
- root = $.extend(true, {}, this.menu_data);
- }
-
- if (root.id === menu_id) {
- return root.action.split(',')[1] ;
- }
- for (var i = 0; i < root.children.length; i++) {
- var action_id = this.menu_id_to_action_id(menu_id, root.children[i]);
- if (action_id !== undefined) {
- return action_id;
- }
- }
- return undefined;
- },
-
- //--------------------------------------------------------------------------
- // Public
- //--------------------------------------------------------------------------
-
- /**
- * Returns the id of the current primary (first level) menu.
- *
- * @returns {integer}
- */
- getCurrentPrimaryMenu: function () {
- return this.current_primary_menu;
- },
- /**
- * Open the first app, returns whether an application was found.
- *
- * @returns {Boolean}
- */
- openFirstApp: function () {
- return this._appsMenu.openFirstApp();
- },
-
- //--------------------------------------------------------------------------
- // Handlers
- //--------------------------------------------------------------------------
-
- /**
- * When clicking on app name, opens the first action of the app
- *
- * @private
- * @param {MouseEvent} ev
- */
- _onAppNameClicked: function (ev) {
- var actionID = parseInt(this.menu_id_to_action_id(this.current_primary_menu));
- this._trigger_menu_clicked(this.current_primary_menu, actionID);
- },
- /**
- * @private
- * @param {MouseEvent} ev
- */
- _onMouseOverMenu: function (ev) {
- if (config.device.isMobile) {
- return;
- }
- var $target = $(ev.currentTarget);
- var $opened = $target.siblings('.show');
- if ($opened.length) {
- $opened.find('[data-toggle="dropdown"]:first').dropdown('toggle');
- $opened.removeClass('show');
- $target.find('[data-toggle="dropdown"]:first').dropdown('toggle');
- $target.addClass('show');
- }
- },
-});
-
-return Menu;
-
-});
diff --git a/addons/web/static/src/js/chrome/root_widget.js b/addons/web/static/src/js/chrome/root_widget.js
deleted file mode 100644
index 9cf0515b134..00000000000
--- a/addons/web/static/src/js/chrome/root_widget.js
+++ /dev/null
@@ -1,7 +0,0 @@
-odoo.define('root.widget', function (require) {
-"use strict";
-
-var webClient = require('web.web_client');
-
-return webClient;
-});
diff --git a/addons/web/static/src/js/chrome/systray_menu.js b/addons/web/static/src/js/chrome/systray_menu.js
deleted file mode 100644
index 0e25f2566de..00000000000
--- a/addons/web/static/src/js/chrome/systray_menu.js
+++ /dev/null
@@ -1,65 +0,0 @@
-odoo.define('web.SystrayMenu', function (require) {
-"use strict";
-
-var dom = require('web.dom');
-var Widget = require('web.Widget');
-
-/**
- * The SystrayMenu is the class that manage the list of icons in the top right
- * of the menu bar.
- */
-var SystrayMenu = Widget.extend({
- /**
- * This widget renders the systray menu. It creates and renders widgets
- * pushed in instance.web.SystrayItems.
- */
- init: function (parent) {
- this._super(parent);
- this.items = [];
- this.widgets = [];
- },
- /**
- * Instanciate the items and add them into a temporary fragmenet
- * @override
- */
- willStart: function () {
- var self = this;
- var proms = [];
- SystrayMenu.Items = _.sortBy(SystrayMenu.Items, function (item) {
- return !_.isUndefined(item.prototype.sequence) ? item.prototype.sequence : 50;
- });
-
- SystrayMenu.Items.forEach(function (WidgetClass) {
- var cur_systray_item = new WidgetClass(self);
- self.widgets.push(cur_systray_item);
- proms.push(cur_systray_item.appendTo($('')));
- });
-
- return this._super.apply(this, arguments).then(function () {
- return Promise.all(proms);
- });
- },
- on_attach_callback() {
- this.widgets
- .filter(widget => widget.on_attach_callback)
- .forEach(widget => widget.on_attach_callback());
- },
- /**
- * Add the instanciated items, using the object located in this.wisgets
- */
- start: function () {
- var self = this;
- return this._super.apply(this, arguments).then(function () {
- self.widgets.forEach(function (widget) {
- dom.prepend(self.$el, widget.$el);
- });
- });
- },
-});
-
-SystrayMenu.Items = [];
-
-return SystrayMenu;
-
-});
-
diff --git a/addons/web/static/src/js/chrome/user_menu.js b/addons/web/static/src/js/chrome/user_menu.js
deleted file mode 100644
index a3622245c7f..00000000000
--- a/addons/web/static/src/js/chrome/user_menu.js
+++ /dev/null
@@ -1,132 +0,0 @@
-odoo.define('web.UserMenu', function (require) {
-"use strict";
-
-/**
- * This widget is appended by the webclient to the right of the navbar.
- * It displays the avatar and the name of the logged user (and optionally the
- * db name, in debug mode).
- * If clicked, it opens a dropdown allowing the user to perform actions like
- * editing its preferences, accessing the documentation, logging out...
- */
-
-var config = require('web.config');
-var core = require('web.core');
-var framework = require('web.framework');
-var Dialog = require('web.Dialog');
-var Widget = require('web.Widget');
-
-var _t = core._t;
-var QWeb = core.qweb;
-
-var UserMenu = Widget.extend({
- template: 'UserMenu',
-
- /**
- * @override
- * @returns {Promise}
- */
- start: function () {
- var self = this;
- var session = this.getSession();
- this.$el.on('click', '[data-menu]', function (ev) {
- ev.preventDefault();
- var menu = $(this).data('menu');
- self['_onMenu' + menu.charAt(0).toUpperCase() + menu.slice(1)]();
- });
- return this._super.apply(this, arguments).then(function () {
- var $avatar = self.$('.oe_topbar_avatar');
- if (!session.uid) {
- $avatar.attr('src', $avatar.data('default-src'));
- return Promise.resolve();
- }
- var topbar_name = session.name;
- if (config.isDebug()) {
- topbar_name = _.str.sprintf("%s (%s)", topbar_name, session.db);
- }
- self.$('.oe_topbar_name').text(topbar_name);
- var avatar_src = session.url('/web/image', {
- model:'res.users',
- field: 'avatar_128',
- id: session.uid,
- });
- $avatar.attr('src', avatar_src);
- });
- },
-
- //--------------------------------------------------------------------------
- // Handlers
- //--------------------------------------------------------------------------
-
- /**
- * @private
- */
- _onMenuAccount: function () {
- var self = this;
- this.trigger_up('clear_uncommitted_changes', {
- callback: function () {
- self._rpc({route: '/web/session/account'})
- .then(function (url) {
- framework.redirect(url);
- })
- .guardedCatch(function (result, ev){
- ev.preventDefault();
- framework.redirect('https://accounts.odoo.com/account');
- });
- },
- });
- },
- /**
- * @private
- */
- _onMenuDocumentation: function () {
- window.open('https://www.odoo.com/documentation/14.0', '_blank');
- },
- /**
- * @private
- */
- _onMenuLogout: function () {
- this.trigger_up('clear_uncommitted_changes', {
- callback: this.do_action.bind(this, 'logout'),
- });
- },
- /**
- * @private
- */
- _onMenuSettings: function () {
- var self = this;
- var session = this.getSession();
- this.trigger_up('clear_uncommitted_changes', {
- callback: function () {
- self._rpc({
- model: "res.users",
- method: "action_get"
- })
- .then(function (result) {
- result.res_id = session.uid;
- self.do_action(result);
- });
- },
- });
- },
- /**
- * @private
- */
- _onMenuSupport: function () {
- window.open('https://www.odoo.com/buy', '_blank');
- },
- /**
- * @private
- */
- _onMenuShortcuts: function() {
- new Dialog(this, {
- size: 'large',
- dialogClass: 'o_act_window',
- title: _t("Keyboard Shortcuts"),
- $content: $(QWeb.render("UserMenu.shortcuts"))
- }).open();
- },
-});
-
-return UserMenu;
-
-});
diff --git a/addons/web/static/src/js/chrome/web_client.js b/addons/web/static/src/js/chrome/web_client.js
deleted file mode 100644
index 8067d77a857..00000000000
--- a/addons/web/static/src/js/chrome/web_client.js
+++ /dev/null
@@ -1,231 +0,0 @@
-odoo.define('web.WebClient', function (require) {
-"use strict";
-
-var AbstractWebClient = require('web.AbstractWebClient');
-var config = require('web.config');
-var core = require('web.core');
-var data_manager = require('web.data_manager');
-var dom = require('web.dom');
-var Menu = require('web.Menu');
-var session = require('web.session');
-
-return AbstractWebClient.extend({
- custom_events: _.extend({}, AbstractWebClient.prototype.custom_events, {
- app_clicked: 'on_app_clicked',
- menu_clicked: 'on_menu_clicked',
- }),
- start: function () {
- core.bus.on('change_menu_section', this, function (menuID) {
- this.do_push_state(_.extend($.bbq.getState(), {
- menu_id: menuID,
- }));
- });
-
- return this._super.apply(this, arguments);
- },
- bind_events: function () {
- var self = this;
- this._super.apply(this, arguments);
-
- /*
- Small patch to allow having a link with a href towards an anchor. Since odoo use hashtag
- to represent the current state of the view, we can't easily distinguish between a link
- towards an anchor and a link towards anoter view/state. If we want to navigate towards an
- anchor, we must not change the hash of the url otherwise we will be redirected to the app
- switcher instead.
- To check if we have an anchor, first check if we have an href attributes starting with #.
- Try to find a element in the DOM using JQuery selector.
- If we have a match, it means that it is probably a link to an anchor, so we jump to that anchor.
- */
- this.$el.on('click', 'a', function (ev) {
- var disable_anchor = ev.target.attributes.disable_anchor;
- if (disable_anchor && disable_anchor.value === "true") {
- return;
- }
-
- var href = ev.target.attributes.href;
- if (href) {
- if (href.value[0] === '#' && href.value.length > 1) {
- if (self.$("[id='"+href.value.substr(1)+"']").length) {
- ev.preventDefault();
- self.trigger_up('scrollTo', {'selector': href.value});
- }
- }
- }
- });
- },
- load_menus: function () {
- return (odoo.loadMenusPromise || odoo.reloadMenus())
- .then(function (menuData) {
- // Compute action_id if not defined on a top menu item
- for (var i = 0; i < menuData.children.length; i++) {
- var child = menuData.children[i];
- if (child.action === false) {
- while (child.children && child.children.length) {
- child = child.children[0];
- if (child.action) {
- menuData.children[i].action = child.action;
- break;
- }
- }
- }
- }
- odoo.loadMenusPromise = null;
- return menuData;
- });
- },
- async show_application() {
- this.set_title();
-
- await this.menu_dp.add(this.instanciate_menu_widgets());
- $(window).bind('hashchange', this.on_hashchange);
-
- const state = $.bbq.getState(true);
- if (!_.isEqual(_.keys(state), ["cids"])) {
- return this.on_hashchange();
- }
-
- const [data] = await this.menu_dp.add(this._rpc({
- model: 'res.users',
- method: 'read',
- args: [session.uid, ["action_id"]],
- }));
- if (data.action_id) {
- await this.do_action(data.action_id[0]);
- this.menu.change_menu_section(this.menu.action_id_to_primary_menu_id(data.action_id[0]));
- return;
- }
-
- if (!this.menu.openFirstApp()) {
- this.trigger_up('webclient_started');
- }
- },
-
- instanciate_menu_widgets: function () {
- var self = this;
- var proms = [];
- return this.load_menus().then(function (menuData) {
- self.menu_data = menuData;
-
- // Here, we instanciate every menu widgets and we immediately append them into dummy
- // document fragments, so that their `start` method are executed before inserting them
- // into the DOM.
- if (self.menu) {
- self.menu.destroy();
- }
- self.menu = new Menu(self, menuData);
- proms.push(self.menu.prependTo(self.$el));
- return Promise.all(proms);
- });
- },
-
- // --------------------------------------------------------------
- // URL state handling
- // --------------------------------------------------------------
- on_hashchange: async function (event) {
- if (this._ignore_hashchange) {
- this._ignore_hashchange = false;
- return Promise.resolve();
- }
-
- var self = this;
- var stringstate = $.bbq.getState(false);
- if (!_.isEqual(self._current_state, stringstate)) {
- var state = $.bbq.getState(true);
- if (state.action || (state.model && (state.view_type || state.id))) {
- return self.menu_dp.add(self.action_manager.loadState(state, !!self._current_state)).then(function () {
- if (state.menu_id) {
- if (state.menu_id !== self.menu.current_primary_menu) {
- core.bus.trigger('change_menu_section', state.menu_id);
- }
- } else {
- var action = self.action_manager.getCurrentAction();
- if (action) {
- var menu_id = self.menu.action_id_to_primary_menu_id(action.id);
- core.bus.trigger('change_menu_section', menu_id);
- }
- }
- });
- } else if (state.menu_id) {
- var action_id = self.menu.menu_id_to_action_id(state.menu_id);
- return self.menu_dp.add(self.do_action(action_id, {clear_breadcrumbs: true})).then(function () {
- core.bus.trigger('change_menu_section', state.menu_id);
- });
- } else {
- self.menu.openFirstApp();
- }
- }
- self._current_state = stringstate;
- },
-
- // --------------------------------------------------------------
- // Menu handling
- // --------------------------------------------------------------
- on_app_clicked: function (ev) {
- var self = this;
- return this.menu_dp.add(data_manager.load_action(ev.data.action_id))
- .then(function (result) {
- return self.action_mutex.exec(function () {
- var completed = new Promise(function (resolve, reject) {
- var options = _.extend({}, ev.data.options, {
- clear_breadcrumbs: true,
- action_menu_id: ev.data.menu_id,
- });
-
- Promise.resolve(self._openMenu(result, options))
- .then(function() {
- self._on_app_clicked_done(ev)
- .then(resolve)
- .guardedCatch(reject);
- }).guardedCatch(function() {
- resolve();
- });
- setTimeout(function () {
- resolve();
- }, 2000);
- });
- return completed;
- });
- });
- },
- _on_app_clicked_done: function (ev) {
- core.bus.trigger('change_menu_section', ev.data.menu_id);
- return Promise.resolve();
- },
- on_menu_clicked: function (ev) {
- var self = this;
- return this.menu_dp.add(data_manager.load_action(ev.data.action_id))
- .then(function (result) {
- self.$el.removeClass('o_mobile_menu_opened');
-
- return self.action_mutex.exec(function () {
- var completed = new Promise(function (resolve, reject) {
- Promise.resolve(self._openMenu(result, {
- clear_breadcrumbs: true,
- })).then(resolve).guardedCatch(reject);
-
- setTimeout(function () {
- resolve();
- }, 2000);
- });
- return completed;
- });
- }).guardedCatch(function () {
- self.$el.removeClass('o_mobile_menu_opened');
- });
- },
- /**
- * Open the action linked to a menu.
- * This function is mostly used to allow override in other modules.
- *
- * @private
- * @param {Object} action
- * @param {Object} options
- * @returns {Promise}
- */
- _openMenu: function (action, options) {
- return this.do_action(action, options);
- },
-});
-
-});
diff --git a/addons/web/static/src/js/main.js b/addons/web/static/src/js/main.js
deleted file mode 100644
index 465ea0d63d4..00000000000
--- a/addons/web/static/src/js/main.js
+++ /dev/null
@@ -1,29 +0,0 @@
-odoo.define('web.web_client', function (require) {
- "use strict";
-
- const AbstractService = require('web.AbstractService');
- const env = require('web.env');
- const session = require("web.session");
- const WebClient = require('web.WebClient');
-
- // configure the env and set it on Owl Component
- owl.config.mode = env.isDebug() ? "dev" : "prod";
- owl.Component.env = env;
-
- // deploy services in the env
- AbstractService.prototype.deployServices(env);
-
- // add the owl templates to the environment and start the web client
- const webClient = new WebClient();
- async function startWebClient() {
- await session.is_bound;
- env.qweb.addTemplates(session.owlTemplates);
-
- await owl.utils.whenReady();
- webClient.setElement($(document.body));
- webClient.start();
- }
- startWebClient();
-
- return webClient;
-});
diff --git a/addons/web/static/src/js/public/public_crash_manager.js b/addons/web/static/src/js/public/public_crash_manager.js
deleted file mode 100644
index 8eae270f23a..00000000000
--- a/addons/web/static/src/js/public/public_crash_manager.js
+++ /dev/null
@@ -1,31 +0,0 @@
-odoo.define('web.PublicCrashManager', function (require) {
-"use strict";
-
-const core = require('web.core');
-const CrashManager = require('web.CrashManager').CrashManager;
-
-const PublicCrashManager = CrashManager.extend({
-
- //--------------------------------------------------------------------------
- // Private
- //--------------------------------------------------------------------------
-
- /**
- * @override
- */
- _displayWarning(message, title, options) {
- this.displayNotification(Object.assign({}, options, {
- title,
- message,
- sticky: true,
- }));
- },
-});
-
-core.serviceRegistry.add('crash_manager', PublicCrashManager);
-
-return {
- CrashManager: PublicCrashManager,
-};
-
-});
diff --git a/addons/web/static/src/js/public/public_notification.js b/addons/web/static/src/js/public/public_notification.js
deleted file mode 100644
index 260937f072b..00000000000
--- a/addons/web/static/src/js/public/public_notification.js
+++ /dev/null
@@ -1,9 +0,0 @@
-odoo.define('web.public.Notification', function (require) {
-'use strict';
-
-var Notification = require('web.Notification');
-
-Notification.include({
- xmlDependencies: ['/web/static/src/xml/notification.xml'],
-});
-});
diff --git a/addons/web/static/src/js/services/crash_manager.js b/addons/web/static/src/js/services/crash_manager.js
deleted file mode 100644
index eb31131d7dc..00000000000
--- a/addons/web/static/src/js/services/crash_manager.js
+++ /dev/null
@@ -1,421 +0,0 @@
-odoo.define('web.ErrorDialogRegistry', function (require) {
-"use strict";
-
-var Registry = require('web.Registry');
-
-return new Registry();
-});
-
-odoo.define('web.CrashManager', function (require) {
-"use strict";
-
-const AbstractService = require('web.AbstractService');
-var ajax = require('web.ajax');
-const BrowserDetection = require('web.BrowserDetection');
-var core = require('web.core');
-var Dialog = require('web.Dialog');
-var ErrorDialogRegistry = require('web.ErrorDialogRegistry');
-var Widget = require('web.Widget');
-var config = require('web.config');
-var { formatTraceback, annotateTraceback} = require("@web/js/core/error_utils");
-
-var _t = core._t;
-var _lt = core._lt;
-
-// Register this eventlistener before qunit does.
-// Some errors needs to be negated by the crash_manager.
-window.addEventListener('unhandledrejection', ev =>
- core.bus.trigger('crash_manager_unhandledrejection', ev)
-);
-
-let active = true;
-
-/**
- * An extension of Dialog Widget to render the warnings and errors on the website.
- * Extend it with your template of choice like ErrorDialog/WarningDialog
- */
-var CrashManagerDialog = Dialog.extend({
- xmlDependencies: (Dialog.prototype.xmlDependencies || []).concat(
- ['/web/static/src/xml/crash_manager.xml']
- ),
-
- /**
- * @param {Object} error
- * @param {string} error.message the message in Warning/Error Dialog
- * @param {string} error.traceback the traceback in ErrorDialog
- *
- * @constructor
- */
- init: function (parent, options, error) {
- this._super.apply(this, [parent, options]);
- this.error = error;
- this.message = error.message;
- this.traceback = error.traceback;
- core.bus.off('close_dialogs', this);
- },
-
- willStart: async function () {
- await this._super()
- const jsError = this.error.data && this.error.data.jsError;
- if (jsError) {
- if (config.isDebug('assets')) {
- this.traceback = await annotateTraceback(jsError);
- } else {
- this.traceback = formatTraceback(jsError);
- }
- }
- },
-
- start: async function () {
- await this._super();
- const message = this.message;
- const traceback = this.traceback;
-
- if (!traceback) {
- return;
- }
- this.$(".o_error_detail").on("shown.bs.collapse", function (e) {
- e.target.scrollTop = e.target.scrollHeight;
- });
-
- const $clipboardBtn = this.$(".o_clipboard_button");
- $clipboardBtn.tooltip({title: _t("Copied !"), trigger: "manual", placement: "left"});
- this.clipboard = new window.ClipboardJS($clipboardBtn[0], {
- text: function () {
- return (_t("Error") + ":\n" + message + "\n\n" + traceback).trim();
- },
- // Container added because of Bootstrap modal that give the focus to another element.
- // We need to give to correct focus to ClipboardJS (see in ClipboardJS doc)
- // https://github.com/zenorocha/clipboard.js/issues/155
- container: this.el,
- });
- this.clipboard.on("success", function (e) {
- _.defer(function () {
- $clipboardBtn.tooltip("show");
- _.delay(function () {
- $clipboardBtn.tooltip("hide");
- }, 800);
- });
- });
- },
- destroy() {
- if (this.clipboard) {
- this.$(".o_clipboard_button").tooltip('dispose');
- this.clipboard.destroy();
- }
- this._super();
- }
-});
-
-var ErrorDialog = CrashManagerDialog.extend({
- template: 'CrashManager.error',
-});
-
-var WarningDialog = CrashManagerDialog.extend({
- template: 'CrashManager.warning',
-
- /**
- * Sets size to medium by default.
- *
- * @override
- */
- init: function (parent, options, error) {
- this._super(parent, _.extend({
- size: 'medium',
- }, options), error);
- },
-
- //--------------------------------------------------------------------------
- // Public
- //--------------------------------------------------------------------------
-
- /**
- * Focuses the ok button.
- *
- * @override
- */
- open: function () {
- this._super({shouldFocusButtons: true});
- },
-});
-
-var CrashManager = AbstractService.extend({
- init: function () {
- var self = this;
- active = true;
- this.isConnected = true;
- this.odooExceptionTitleMap = {
- 'odoo.addons.base.models.ir_mail_server.MailDeliveryException': _lt("MailDeliveryException"),
- 'odoo.exceptions.AccessDenied': _lt("Access Denied"),
- 'odoo.exceptions.AccessError': _lt("Access Error"),
- 'odoo.exceptions.MissingError': _lt("Missing Record"),
- 'odoo.exceptions.UserError': _lt("User Error"),
- 'odoo.exceptions.ValidationError': _lt("Validation Error"),
- 'odoo.exceptions.Warning': _lt("Warning"),
- };
-
- this._super.apply(this, arguments);
-
- // crash manager integration
- core.bus.on('rpc_error', this, this.rpc_error);
- window.onerror = function (message, file, line, col, error) {
- // Scripts injected in DOM (eg: google API's js files) won't return a clean error on window.onerror.
- // The browser will just give you a 'Script error.' as message and nothing else for security issue.
- // To enable onerror to work properly with CORS file, you should:
- // 1. add crossorigin="anonymous" to your
diff --git a/addons/web_editor/static/lib/odoo-editor/odoo-editor.css b/addons/web_editor/static/lib/odoo-editor/odoo-editor.css
index f281cd7194d..68af3ad36df 100644
--- a/addons/web_editor/static/lib/odoo-editor/odoo-editor.css
+++ b/addons/web_editor/static/lib/odoo-editor/odoo-editor.css
@@ -136,11 +136,11 @@
.oe-toolbar li > a.dropdown-item {
color: white;
}
-.oe-toolbar .dropdown-item:hover, .dropdown-item:focus {
+.oe-toolbar .dropdown-item:hover, .oe-toolbar .dropdown-item:focus {
color: white;
background: #868686;
}
-.oe-toolbar .dropdown-item.active, .dropdown-item:active {
+.oe-toolbar .dropdown-item.active, .oe-toolbar .dropdown-item:active {
color: white;
background: #555555;
}
diff --git a/addons/web_tour/__manifest__.py b/addons/web_tour/__manifest__.py
index 2055418fa67..6ecc5774530 100644
--- a/addons/web_tour/__manifest__.py
+++ b/addons/web_tour/__manifest__.py
@@ -18,7 +18,7 @@ Odoo Web tours.
],
'assets': {
'web.assets_qweb': [
- 'web_tour/static/src/xml/debug_manager.xml',
+ 'web_tour/static/src/debug/tour_dialog_component.xml',
],
'web.assets_common': [
'web_tour/static/src/scss/**/*',
@@ -30,7 +30,9 @@ Odoo Web tours.
'web_tour/static/src/js/tour_utils.js',
],
'web.assets_backend': [
- 'web_tour/static/src/js/debug_manager.js',
+ 'web_tour/static/src/debug/debug_manager.js',
+ 'web_tour/static/src/debug/tour_dialog_component.js',
+ 'web_tour/static/src/services/*.js',
],
'web.assets_frontend': [
'web_tour/static/src/js/public/**/*',
diff --git a/addons/web_tour/static/src/debug/debug_manager.js b/addons/web_tour/static/src/debug/debug_manager.js
new file mode 100644
index 00000000000..892e4b0a819
--- /dev/null
+++ b/addons/web_tour/static/src/debug/debug_manager.js
@@ -0,0 +1,47 @@
+/** @odoo-module **/
+
+import { browser } from "@web/core/browser/browser";
+import { registry } from "@web/core/registry";
+import ToursDialog from "@web_tour/debug/tour_dialog_component";
+import utils from "web_tour.utils";
+
+function disableTours({ env }) {
+ if (!env.services.user.isSystem) {
+ return null;
+ }
+ const activeTours = env.services.tour.getActiveTours();
+ if (activeTours.length === 0) {
+ return null;
+ }
+ return {
+ type: "item",
+ description: env._t("Disable Tours"),
+ callback: async () => {
+ await env.services.orm.call("web_tour.tour", "consume", [activeTours]);
+ for (const tourName of activeTours) {
+ browser.localStorage.removeItem(utils.get_debugging_key(tourName));
+ }
+ browser.location.reload();
+ },
+ sequence: 50,
+ };
+}
+
+function startTour({ env }) {
+ if (!env.services.user.isSystem) {
+ return null;
+ }
+ return {
+ type: "item",
+ description: env._t("Start Tour"),
+ callback: async () => {
+ env.services.dialog.add(ToursDialog);
+ },
+ sequence: 60,
+ };
+}
+
+registry
+ .category("debug")
+ .add("web_tour.startTour", startTour)
+ .add("web_tour.disableTours", disableTours);
diff --git a/addons/web_tour/static/src/debug/tour_dialog_component.js b/addons/web_tour/static/src/debug/tour_dialog_component.js
new file mode 100644
index 00000000000..e57079e00f0
--- /dev/null
+++ b/addons/web_tour/static/src/debug/tour_dialog_component.js
@@ -0,0 +1,41 @@
+/** @odoo-module **/
+
+import { useService } from "@web/core/service_hook";
+import { Dialog } from "@web/core/dialog/dialog";
+import { _lt } from "@web/core/l10n/translation";
+
+export default class ToursDialog extends Dialog {
+ setup() {
+ super.setup();
+ this.tourService = useService("tour");
+ this.onboardingTours = this.tourService.getOnboardingTours();
+ this.testingTours = this.tourService.getTestingTours();
+ }
+
+ //--------------------------------------------------------------------------
+ // Handlers
+ //--------------------------------------------------------------------------
+
+ /**
+ * Resets the given tour to its initial step, in onboarding mode.
+ *
+ * @private
+ * @param {MouseEvent} ev
+ */
+ _onStartTour(ev) {
+ this.tourService.reset(ev.target.dataset.name);
+ this.close();
+ }
+ /**
+ * Starts the given tour in test mode.
+ *
+ * @private
+ * @param {MouseEvent} ev
+ */
+ _onTestTour(ev) {
+ this.tourService.run(ev.target.dataset.name);
+ this.close();
+ }
+}
+ToursDialog.bodyTemplate = "web_tour.ToursDialog";
+ToursDialog.title = _lt("Tours");
diff --git a/addons/web_tour/static/src/xml/debug_manager.xml b/addons/web_tour/static/src/debug/tour_dialog_component.xml
similarity index 55%
rename from addons/web_tour/static/src/xml/debug_manager.xml
rename to addons/web_tour/static/src/debug/tour_dialog_component.xml
index 2585c1f662f..03a3b2d9913 100644
--- a/addons/web_tour/static/src/xml/debug_manager.xml
+++ b/addons/web_tour/static/src/debug/tour_dialog_component.xml
@@ -1,29 +1,20 @@
-
-
-
- Disable Tours
- Start Tour
-
-
-
-
-
+
-
+ Onboarding tours
-
+ Testing tours
-
+
@@ -43,8 +34,22 @@
-
-
+
+
+
+
+
+
diff --git a/addons/web_tour/static/src/js/debug_manager.js b/addons/web_tour/static/src/js/debug_manager.js
deleted file mode 100644
index f7bf46ba0ce..00000000000
--- a/addons/web_tour/static/src/js/debug_manager.js
+++ /dev/null
@@ -1,81 +0,0 @@
-odoo.define('web_tour.DebugManager.Backend', function (require) {
-"use strict";
-
-var core = require("web.core");
-var DebugManager = require('web.DebugManager.Backend');
-var Dialog = require("web.Dialog");
-var local_storage = require('web.local_storage');
-
-var tour = require('web_tour.tour');
-var utils = require('web_tour.utils');
-
-var get_debugging_key = utils.get_debugging_key;
-
-function get_active_tours () {
- return _.difference(_.keys(tour.tours), tour.consumed_tours);
-}
-
-DebugManager.include({
- start: function () {
- this.consume_tours_enabled = get_active_tours().length > 0;
- return this._super.apply(this, arguments);
- },
- consume_tours: function () {
- var active_tours = get_active_tours();
- if (active_tours.length > 0) { // tours might have been consumed meanwhile
- this._rpc({
- model: 'web_tour.tour',
- method: 'consume',
- args: [active_tours],
- })
- .then(function () {
- for (const tourName of active_tours) {
- local_storage.removeItem(get_debugging_key(tourName));
- }
- window.location.reload();
- });
- }
- },
- start_tour: async function () {
- const tours = Object.values(tour.tours).sort((t1, t2) => {
- return (t1.sequence - t2.sequence) || (t1.name < t2.name ? -1 : 1);
- });
- const dialog = new Dialog(this, {
- title: 'Tours',
- $content: core.qweb.render('web_tour.ToursDialog', {
- onboardingTours: tours.filter(t => !t.test),
- testingTours: tours.filter(t => t.test),
- }),
- });
- await dialog.open().opened();
- dialog.$('.o_start_tour').on('click', this._onStartTour.bind(this));
- dialog.$('.o_test_tour').on('click', this._onTestTour.bind(this));
- },
-
- //--------------------------------------------------------------------------
- // Handlers
- //--------------------------------------------------------------------------
-
- /**
- * Resets the given tour to its initial step, in onboarding mode.
- *
- * @private
- * @param {MouseEvent}
- */
- _onStartTour(ev) {
- ev.preventDefault();
- tour.reset($(ev.target).data('name'));
- },
- /**
- * Starts the given tour in test mode.
- *
- * @private
- * @param {MouseEvent}
- */
- _onTestTour(ev) {
- ev.preventDefault();
- tour.run($(ev.target).data('name'));
- },
-});
-
-});
diff --git a/addons/web_tour/static/src/js/tour_manager.js b/addons/web_tour/static/src/js/tour_manager.js
index 97fa343b583..5ccdf631fac 100644
--- a/addons/web_tour/static/src/js/tour_manager.js
+++ b/addons/web_tour/static/src/js/tour_manager.js
@@ -7,7 +7,6 @@ var local_storage = require('web.local_storage');
var mixins = require('web.mixins');
var utils = require('web_tour.utils');
var TourStepUtils = require('web_tour.TourStepUtils');
-var RainbowMan = require('web.RainbowMan');
var RunningTourActionHelper = require('web_tour.RunningTourActionHelper');
var ServicesMixin = require('web.ServicesMixin');
var session = require('web.session');
@@ -433,7 +432,7 @@ return core.Class.extend(mixins.EventDispatcherMixin, ServicesMixin, {
message = _t('
Good job! You went through all steps of this tour.');
}
const fadeout = this.tours[tour_name].fadeout;
- new RainbowMan({message, fadeout}).appendTo(this.$body);
+ core.bus.trigger('show-effect', {type: "rainbowman", message, fadeout});
}
this.tours[tour_name].current_step = 0;
local_storage.removeItem(get_step_key(tour_name));
diff --git a/addons/web_tour/static/src/js/tour_step_utils.js b/addons/web_tour/static/src/js/tour_step_utils.js
index dc69e8968e2..f2b6f3930ec 100644
--- a/addons/web_tour/static/src/js/tour_step_utils.js
+++ b/addons/web_tour/static/src/js/tour_step_utils.js
@@ -29,7 +29,7 @@ return core.Class.extend({
showAppsMenuItem() {
return {
edition: 'community',
- trigger: '.o_menu_apps a',
+ trigger: '.o_navbar_apps_menu button',
auto: true,
position: 'bottom',
};
diff --git a/addons/web_tour/static/src/services/tour_service.js b/addons/web_tour/static/src/services/tour_service.js
new file mode 100644
index 00000000000..9032abdcd64
--- /dev/null
+++ b/addons/web_tour/static/src/services/tour_service.js
@@ -0,0 +1,93 @@
+/** @odoo-module **/
+
+import { registry } from "@web/core/registry";
+import tourManager from "web_tour.tour";
+
+export const tourService = {
+ start() {
+ /**
+ * @private
+ * @returns {Object} All the tours as a map
+ */
+ function _getAllTourMap() {
+ return tourManager.tours;
+ }
+
+ /**
+ * @private
+ * @returns {Object} All the active tours as a map
+ */
+ function _getActiveTourMap() {
+ return Object.fromEntries(
+ Object.entries(_getAllTourMap()).filter(
+ ([key, value]) => !tourManager.consumed_tours.includes(key)
+ )
+ );
+ }
+
+ /**
+ * @private
+ * @returns {Array} Takes an Object (map) of tours and returns all the values
+ */
+ function _fromTourMapToArray(tourMap) {
+ return Object.values(tourMap).sort((t1, t2) => {
+ return t1.sequence - t2.sequence || (t1.name < t2.name ? -1 : 1);
+ });
+ }
+
+ /**
+ * @returns {Array} All the tours
+ */
+ function getAllTours() {
+ return _fromTourMapToArray(_getAllTourMap());
+ }
+
+ /**
+ * @returns {Array} All the active tours
+ */
+ function getActiveTours() {
+ return _fromTourMapToArray(_getActiveTourMap());
+ }
+
+ /**
+ * @returns {Array} The onboarding tours
+ */
+ function getOnboardingTours() {
+ return getAllTours().filter((t) => !t.test);
+ }
+
+ /**
+ * @returns {Array} The testing tours
+ */
+ function getTestingTours() {
+ return getAllTours().filter((t) => t.test);
+ }
+
+ /**
+ * @param {string} tourName
+ * Run a tour
+ */
+ function run(tourName) {
+ return tourManager.run(tourName);
+ }
+
+ /**
+ * @param {string} tourName
+ * Reset a tour
+ */
+ function reset(tourName) {
+ return tourManager.reset(tourName);
+ }
+
+ return {
+ getAllTours,
+ getActiveTours,
+ getOnboardingTours,
+ getTestingTours,
+ run,
+ reset,
+ };
+ },
+};
+
+registry.category("services").add("tour", tourService);
diff --git a/addons/website/__manifest__.py b/addons/website/__manifest__.py
index 3693fb0278c..a709f2ac51c 100644
--- a/addons/website/__manifest__.py
+++ b/addons/website/__manifest__.py
@@ -101,7 +101,7 @@
'uninstall_hook': 'uninstall_hook',
'assets': {
'web.assets_frontend': [
- ('replace', 'web/static/src/js/public/public_root_instance.js', 'website/static/src/js/content/website_root_instance.js'),
+ ('replace', 'web/static/src/legacy/js/public/public_root_instance.js', 'website/static/src/js/content/website_root_instance.js'),
'website/static/src/scss/website.scss',
'website/static/src/scss/website.ui.scss',
'website/static/src/js/set_view_track.js',
@@ -185,7 +185,7 @@
'website.assets_editor': [
('include', 'web._assets_helpers'),
'web/static/lib/bootstrap/scss/_variables.scss',
- 'web/static/src/scss/ace.scss',
+ 'web/static/src/legacy/scss/ace.scss',
'website/static/src/scss/website.editor.ui.scss',
'website/static/src/scss/website.theme_install.scss',
'website/static/src/js/menu/content.js',
@@ -211,7 +211,7 @@
'http://test.external.link/javascript1.js',
'/web/static/lib/jquery.ui/jquery-ui.css',
'http://test.external.link/style1.css',
- '/web/static/src/js/boot.js',
+ '/web/static/src/boot.js',
'http://test.external.link/javascript2.js',
'http://test.external.link/style2.css',
],
diff --git a/addons/website/static/src/scss/website.ui.scss b/addons/website/static/src/scss/website.ui.scss
index 14bf204b634..dbf2aaa671d 100644
--- a/addons/website/static/src/scss/website.ui.scss
+++ b/addons/website/static/src/scss/website.ui.scss
@@ -86,10 +86,17 @@ body.o_connected_user {
text-decoration: none;
}
.dropdown-menu {
+ border-top: 0;
+ margin-top: 0;
+ background-clip: border-box;
font-size: inherit;
border-radius: 0;
color: $dropdown-link-active-color;
}
+ #oe_applications .dropdown-menu {
+ // Compensate #oe_applications's padding
+ margin-left: $dropdown-item-padding-x * -0.5;
+ }
.o_menu_sections {
.o_mobile_preview a {
@@ -99,8 +106,6 @@ body.o_connected_user {
}
.o_menu_systray {
> li > a {
- padding: 0 $grid-gutter-width/2;
-
&.css_edit_dynamic{
padding: 0 $grid-gutter-width/4;
}
diff --git a/addons/website/static/tests/tours/dashboard_tour.js b/addons/website/static/tests/tours/dashboard_tour.js
index de1a5f10473..610adb2e5eb 100644
--- a/addons/website/static/tests/tours/dashboard_tour.js
+++ b/addons/website/static/tests/tours/dashboard_tour.js
@@ -1,22 +1,31 @@
odoo.define("website.tour.backend_dashboard", function (require) {
-"use strict";
+ "use strict";
-var tour = require("web_tour.tour");
+ var tour = require("web_tour.tour");
-tour.register("backend_dashboard", {
- test: true,
- url: "/web",
-}, [tour.stepUtils.showAppsMenuItem(),
+ tour.register(
+ "backend_dashboard",
{
- trigger: 'a[data-menu-xmlid="website.menu_website_configuration"]',
-}, {
- trigger: '.dropdown-toggle[data-menu-xmlid="website.menu_dashboard"]',
-}, {
- trigger: '.dropdown-item[data-menu-xmlid="website.menu_website_google_analytics"]',
-}, {
- // Visits section should always be present even when empty / not hooked to anything
- trigger: 'h2:contains("Visits")',
- content: "Check if dashboard loads",
- run: function () {}
-}]);
+ test: true,
+ url: "/web",
+ },
+ [
+ tour.stepUtils.showAppsMenuItem(),
+ {
+ trigger: '.o_app[data-menu-xmlid="website.menu_website_configuration"]',
+ },
+ {
+ trigger: 'button[data-menu-xmlid="website.menu_dashboard"]',
+ },
+ {
+ trigger: 'li[data-menu-xmlid="website.menu_website_google_analytics"]',
+ },
+ {
+ // Visits section should always be present even when empty / not hooked to anything
+ trigger: 'h2:contains("Visits")',
+ content: "Check if dashboard loads",
+ run: function () {},
+ },
+ ]
+ );
});
diff --git a/addons/website/views/website_navbar_templates.xml b/addons/website/views/website_navbar_templates.xml
index a4fc8dbd64b..7cd2a0eed48 100644
--- a/addons/website/views/website_navbar_templates.xml
+++ b/addons/website/views/website_navbar_templates.xml
@@ -4,7 +4,7 @@
-
+
Unpublished
@@ -34,7 +34,7 @@
-