web_mobile

This commit is contained in:
2026-11-08 17:32:34 +08:00
parent 28bba64611
commit 974a1fb10b
73 changed files with 5506 additions and 0 deletions

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

View File

@@ -0,0 +1,96 @@
import { user } from "@web/core/user";
import mobile from "@web_mobile/js/services/core";
import { isIosApp } from "@web/core/browser/feature_detection";
import { url } from "@web/core/utils/urls";
const DEFAULT_AVATAR_SIZE = 128;
export const accountMethodsForMobile = {
url,
/**
* Update the user's account details on the mobile app
*
* @returns {Promise}
*/
async updateAccount() {
if (!mobile.methods.updateAccount) {
return;
}
const base64Avatar = await accountMethodsForMobile.fetchAvatar();
return mobile.methods.updateAccount({
avatar: base64Avatar.substring(base64Avatar.indexOf(',') + 1),
name: user.name,
username: user.login,
});
},
/**
* Fetch current user's avatar as PNG image
*
* @returns {Promise} resolved with the dataURL, or rejected if the file is
* empty or if an error occurs.
*/
fetchAvatar() {
const avatarUrl = accountMethodsForMobile.url('/web/image', {
model: 'res.users',
field: 'image_medium',
id: user.userId,
});
return new Promise((resolve, reject) => {
const canvas = document.createElement('canvas');
canvas.width = DEFAULT_AVATAR_SIZE;
canvas.height = DEFAULT_AVATAR_SIZE;
const context = canvas.getContext('2d');
const image = new Image();
image.addEventListener('load', () => {
context.drawImage(image, 0, 0, DEFAULT_AVATAR_SIZE, DEFAULT_AVATAR_SIZE);
resolve(canvas.toDataURL('image/png'));
});
image.addEventListener('error', reject);
image.src = avatarUrl;
});
},
};
/**
* Mixin to hook into the controller record's saving method and
* trigger the update of the user's account details on the mobile app.
*
* @mixin
* @name UpdateDeviceAccountControllerMixin
*
*/
const UpdateDeviceAccountControllerMixin = {
/**
* @override
*/
async save() {
const isSaved = await this._super(...arguments);
if (!isSaved) {
return false;
}
const updated = accountMethodsForMobile.updateAccount();
// Crapy workaround for unupdatable Odoo Mobile App iOS (Thanks Apple :@)
if (!isIosApp()){
await updated;
}
return true;
},
};
export async function updateAccountOnMobileDevice() {
const updated = accountMethodsForMobile.updateAccount();
// Crapy workaround for unupdatable Odoo Mobile App iOS (Thanks Apple :@)
if (!isIosApp()){
await updated;
}
}
/**
* Trigger the update of the user's account details on the mobile app.
*/
accountMethodsForMobile.updateAccount();
export default {
UpdateDeviceAccountControllerMixin,
updateAccountOnMobileDevice,
};

View File

@@ -0,0 +1,49 @@
import { browser } from "@web/core/browser/browser";
import mobile from "@web_mobile/js/services/core";
import { download, downloadFile } from "@web/core/network/download";
function extractPathFromUrl(url) {
const parsedUrl = URL.parse(url);
return parsedUrl ? `${parsedUrl.pathname}${parsedUrl.search}` : url;
}
const _download = download._download;
download._download = async function (options) {
if (mobile.methods.downloadFile) {
if (odoo.csrf_token) {
options.csrf_token = odoo.csrf_token;
}
options.url = extractPathFromUrl(options.url);
mobile.methods.downloadFile(options);
// There is no need to wait downloadFile because we delegate this to
// Download Manager Service where error handling will be handled correclty.
// On our side, we do not want to block the UI and consider the request
// as success.
return Promise.resolve();
} else {
return _download.apply(this, arguments);
}
};
const _downloadFile = downloadFile._download;
downloadFile._download = async function (data, filename, mimetype) {
if (!mobile.methods.downloadFile) {
return _downloadFile.apply(this, arguments);
}
const isUrl = !filename && !mimetype && typeof data === "string";
if (isUrl) {
mobile.methods.downloadFile({
form: { method: "GET" },
url: extractPathFromUrl(data)
});
} else {
browser.console.warn(
"downloadFile: the native saveFile bridge only supports URL downloads; ignoring Blob/string content."
);
}
return Promise.resolve();
};

View File

@@ -0,0 +1,12 @@
import { registry } from "@web/core/registry";
import mobile from "@web_mobile/js/services/core";
function mobileErrorHandler(env, error, originalError) {
if (mobile.methods.crashManager) {
error.originalError = originalError;
mobile.methods.crashManager(error);
}
}
registry
.category("error_handlers")
.add("web_mobile.errorHandler", mobileErrorHandler, { sequence: 3 });

View File

@@ -0,0 +1,23 @@
import { EventBus } from "@odoo/owl";
export class HookEventBus extends EventBus {
/**
@param {{}} hooks
@param {Function} [hooks.onAddListener]
@param {Function} [hooks.onRemoveListener]
*/
constructor(hooks = {}) {
super();
this.hooks = hooks;
}
addEventListener(eventName, listener) {
super.addEventListener(eventName, listener);
this.hooks.onAddListener?.(eventName, listener);
}
removeEventListener(eventName, listener) {
super.removeEventListener(eventName, listener);
this.hooks.onRemoveListener?.(eventName, listener);
}
}

View File

@@ -0,0 +1,89 @@
import { HookEventBus } from "@web_mobile/js/hook_event_bus";
import { Plugin, usePlugin } from "@odoo/owl";
import { services } from "@web/core/services";
import { registry } from "@web/core/registry";
import { session } from "@web/session";
import mobile from "@web_mobile/js/services/core";
import { shortcutItem, switchAccountItem } from "./user_menu_items";
const userMenuRegistry = registry.category("user_menuitems");
export class MobilePlugin extends Plugin {
/** @private */
timeBetweenReadsInMs = session.time_between_reads_in_ms || 100;
/** @private */
idInterval = null;
setup() {
let listenerCount = 0;
this.bus = new HookEventBus({
onAddListener: (eventName, listener) => {
listenerCount++;
if (listenerCount === 1) {
this.enableReader();
}
},
onRemoveListener: (eventName, listener) => {
listenerCount--;
if (listenerCount === 0) {
this.stopReader();
}
},
});
if (mobile.methods.addHomeShortcut) {
userMenuRegistry.add("web_mobile.shortcut", shortcutItem);
}
if (mobile.methods.switchAccount) {
// remove "Log Out" and "My Odoo.com Account"
userMenuRegistry.remove("log_out");
userMenuRegistry.remove("odoo_account");
userMenuRegistry.add("web_mobile.switch", switchAccountItem);
}
}
enableReader() {
if (mobile.methods.enableReader && mobile.methods.getReaderData) {
mobile.methods.enableReader().catch((e) => console.error(e));
if (!this.idInterval) {
this.idInterval = setInterval(async () => {
try {
const value = await mobile.methods.getReaderData();
if (value.success) {
const data = value.data;
if (data.length > 0) {
this.bus.trigger("mobile_reader_scanned", { data });
}
}
} catch (e) {
console.error(e);
}
}, this.timeBetweenReadsInMs);
}
}
}
stopReader() {
if (this.idInterval) {
clearInterval(this.idInterval);
this.idInterval = null;
}
}
}
services.add(MobilePlugin);
/**
* -----------------------------------------------------------------------------
* @todo owl3 migration
* temporary - to remove when all use of the mobile service are removed
* -----------------------------------------------------------------------------
*/
registry.category("services").add("mobile", {
start() {
return usePlugin(MobilePlugin);
},
});

View File

@@ -0,0 +1,108 @@
/* global OdooDeviceUtility */
/* global OdooDevicePolyfill */
import { uniqueId } from "@web/core/utils/functions";
import { location, browser } from "@web/core/browser/browser";
import { parseSearchQuery } from "@web/core/browser/router";
import { patch } from "@web/core/utils/patch";
import { BackButtonManager } from "@web/core/utils/hooks";
const available = typeof OdooDeviceUtility !== "undefined";
let DeviceUtility;
const deferreds = {};
export const methods = {};
if (available) {
DeviceUtility = OdooDeviceUtility;
delete window.OdooDeviceUtility;
}
/**
* Responsible for invoking native methods which called from JavaScript
*
* @param {String} name name of action want to perform in mobile
* @param {Object} args extra arguments for mobile
*
* @returns Promise Object
*/
function native_invoke(name, args) {
if (args === undefined) {
args = {};
}
const id = uniqueId();
args = JSON.stringify(args);
DeviceUtility.execute(name, args, id);
return new Promise(function (resolve, reject) {
deferreds[id] = {
successCallback: resolve,
errorCallback: reject,
};
});
}
/**
* Manages deferred callback from initiate from native mobile
*
* @param {String} id callback id
* @param {Object} result
*/
window.odoo.native_notify = function (id, result) {
if (Object.prototype.hasOwnProperty.call(deferreds, id)) {
if (result.success) {
deferreds[id].successCallback(result);
} else {
deferreds[id].errorCallback(result);
}
}
};
const plugins = available ? JSON.parse(DeviceUtility.list_plugins()) : [];
plugins.forEach((plugin) => {
methods[plugin.name] = function (args) {
return native_invoke(plugin.action, args);
};
});
let polyfills = {};
if (window.OdooDevicePolyfill) {
polyfills = OdooDevicePolyfill;
}
/**
* Use to notify an uri hash change on native devices (ios / android)
*/
if (methods.hashChange) {
let currentSearch;
browser.addEventListener("popstate", function () {
const search = parseSearchQuery(location.search);
if (JSON.stringify(currentSearch) !== JSON.stringify(search)) {
methods.hashChange(search);
}
currentSearch = search;
});
}
patch(BackButtonManager.prototype, {
_activate() {
if (methods.overrideBackButton) {
document.addEventListener("backbutton", this._boundPerformLatestBackAction);
methods.overrideBackButton({ enabled: true });
} else {
super._activate();
}
},
_deactivate() {
if (methods.overrideBackButton) {
document.removeEventListener("backbutton", this._boundPerformLatestBackAction);
methods.overrideBackButton({ enabled: false });
} else {
super._deactivate();
}
},
});
export default {
methods,
polyfills,
};

View File

@@ -0,0 +1,40 @@
import { _t } from "@web/core/l10n/translation";
import { useService } from "@web/core/utils/hooks";
import mobile from "@web_mobile/js/services/core";
export function shortcutItem() {
const menu = useService("menu");
const notification = useService("notification");
return {
type: "item",
id: "web_mobile.shortcut",
description: _t("Add to Home Screen"),
callback: () => {
const currentAppMenu = menu.getCurrentApp();
if (currentAppMenu) {
const base64Icon = currentAppMenu.webIconData;
mobile.methods.addHomeShortcut({
title: document.title,
shortcut_url: document.URL,
web_icon: base64Icon.substring(base64Icon.indexOf(",") + 1),
});
} else {
notification.add(_t("No shortcut for Home Menu"));
}
},
sequence: 100,
};
}
export function switchAccountItem() {
return {
type: "item",
id: "web_mobile.switch",
description: _t("Switch/Add Account"),
callback: () => {
mobile.methods.switchAccount();
},
sequence: 100,
};
}

View File

@@ -0,0 +1,14 @@
import { registry } from "@web/core/registry";
import { formView } from "@web/views/form/form_view";
import { updateAccountOnMobileDevice } from "@web_mobile/js/core/mixins";
class ResUsersPreferenceController extends formView.Controller {
onRecordSaved(record) {
return updateAccountOnMobileDevice();
}
}
registry.category("views").add("res_users_preferences_form", {
...formView,
Controller: ResUsersPreferenceController,
});

View File

@@ -0,0 +1,41 @@
import { patch } from "@web/core/utils/patch";
import { shareTargetService } from "@web/webclient/share_target/share_target_service";
import mobile from "@web_mobile/js/services/core";
patch(shareTargetService, {
async _getShareTargetFiles() {
if (!mobile.methods.getShareTargetFiles) {
return super._getShareTargetFiles();
}
/**
* {
* "success" : true,
* "data" : [
* {
* uri: "content://com.google.android.apps.nbu.files.provider/2/1000006851"
* name: "name.jpg"
* type: "image/jpeg",
* },
* ...]
*/
const response = await mobile.methods.getShareTargetFiles();
if (response.success) {
const files = [];
for (let i = 0; i < response.data.length; i++) {
const { name, uri, type } = response.data[i];
// this is a fake rpc call to mobile apps.
// The app will stream the file content to avoid the risk of some Out of Memory
const fakeRpc = await fetch(
`/share_target.localhost/?uri=${encodeURIComponent(uri)}`
);
if (!fakeRpc.ok) {
throw new Error(`Unable to share file: ${name}`);
}
const blob = await fakeRpc.blob();
files.push(new File([blob], name, { type }));
}
return files;
}
return [];
},
});

View File

@@ -0,0 +1,42 @@
/** @odoo-module **/
import { beforeEach, expect, test } from "@odoo/hoot";
import { patchWithCleanup } from "@web/../tests/web_test_helpers";
import { browser } from "@web/core/browser/browser";
import mobile from "@web_mobile/js/services/core";
import { downloadFile } from "@web/core/network/download";
beforeEach(() => {
patchWithCleanup(mobile.methods, {
downloadFile: (payload) => expect.step(payload),
});
patchWithCleanup(browser.console, {
warn: (message) => expect.step(message),
});
});
test("downloadFile: the host is removed from an absolute URL before calling mobile.methods.downloadFile", async () => {
await downloadFile("https://www.hoot.test/web/content/123?download=true");
expect.verifySteps([{ form: { method: "GET" }, url: "/web/content/123?download=true" }]);
});
test("downloadFile: a relative URL is forwarded as-is to mobile.methods.downloadFile", async () => {
await downloadFile("/web/content/123?download=true");
expect.verifySteps([{ form: { method: "GET" }, url: "/web/content/123?download=true" }]);
});
test("downloadFile: Blob content is not handled, logs a warning instead", async () => {
const blob = new Blob(["hello world"], { type: "text/plain" });
await downloadFile(blob, "test.txt");
expect.verifySteps([
"downloadFile: the native saveFile bridge only supports URL downloads; ignoring Blob/string content.",
]);
});
test("downloadFile: string content with filename/mimetype is not handled, logs a warning instead", async () => {
await downloadFile('{"foo":"bar"}', "export.json", "application/json");
expect.verifySteps([
"downloadFile: the native saveFile bridge only supports URL downloads; ignoring Blob/string content.",
]);
});

View File

@@ -0,0 +1,53 @@
import { expect, test } from "@odoo/hoot";
import { HookEventBus } from "@web_mobile/js/hook_event_bus";
test("HookEventBus: Test callback", async () => {
const eventBus = new HookEventBus({
onAddListener: () => expect.step("onAddListenerCallback"),
onRemoveListener: () => expect.step("onRemoveListenerCallback"),
});
const eventName = "test_event";
const listener1 = () => expect.step("listener1");
const listener2 = () => expect.step("listener2");
// No callback should be call at the initialization
expect.verifySteps([]);
eventBus.trigger(eventName, {});
// No callback should be call on event
expect.verifySteps([]);
eventBus.addEventListener(eventName, listener1);
// enableReader should be call when a listener is added
expect.verifySteps(["onAddListenerCallback"]);
eventBus.trigger(eventName, {});
// No callback should be call when an event is trigger
expect.verifySteps(["listener1"]);
eventBus.addEventListener(eventName, listener2);
// enableReader should be call when a listener is added
expect.verifySteps(["onAddListenerCallback"]);
eventBus.trigger(eventName, {});
// No callback should be call when an event is trigger
expect.verifySteps(["listener1", "listener2"]);
eventBus.removeEventListener(eventName, listener1);
// stopReader should be call when a listeners is removed
expect.verifySteps(["onRemoveListenerCallback"]);
eventBus.trigger(eventName, {});
// No callback should be call when an event is trigger
expect.verifySteps(["listener2"]);
eventBus.removeEventListener(eventName, listener2);
// stopReader should be call when a listeners is removed
expect.verifySteps(["onRemoveListenerCallback"]);
eventBus.trigger(eventName, {});
// No callback should be call when an event is trigger
expect.verifySteps([]);
});

View File

@@ -0,0 +1,50 @@
import { expect, test } from "@odoo/hoot";
import { getService, mockService, mountWithCleanup } from "@web/../tests/web_test_helpers";
import { WebClient } from "@web/webclient/webclient";
test("test Reader Loop", async () => {
mockService("mobile", {
enableReader: () => expect.step("enableReader"),
stopReader: () => expect.step("stopReader"),
});
const eventName = "test_event";
const listener1 = () => expect.step("listener1");
const listener2 = () => expect.step("listener2");
await mountWithCleanup(WebClient);
const eventBus = await getService("mobile").bus;
// No callback should be call at the initialization
expect.verifySteps([]);
eventBus.trigger(eventName, {});
// No callback should be call if no listener
expect.verifySteps([]);
eventBus.addEventListener(eventName, listener1);
// enableReader should be call at first listener
expect.verifySteps(["enableReader"]);
eventBus.trigger(eventName, {});
// No callback should be call when an event is trigger
expect.verifySteps(["listener1"]);
eventBus.addEventListener(eventName, listener2);
eventBus.trigger(eventName, {});
// No callback should be call if one listener is already present and another one is added
expect.verifySteps(["listener1", "listener2"]);
eventBus.removeEventListener(eventName, listener1);
eventBus.trigger(eventName, {});
// No callback should be call if there is at least one listener and another one is removed
expect.verifySteps(["listener2"]);
eventBus.removeEventListener(eventName, listener2);
// stopReader should be call if there is no listeners anymore
expect.verifySteps(["stopReader"]);
eventBus.trigger(eventName, {});
// No callback should be call if no listener
expect.verifySteps([]);
});

View File

@@ -0,0 +1,123 @@
import { beforeEach, expect, test } from "@odoo/hoot";
import {
contains,
defineMenus,
getService,
mockService,
mountWithCleanup,
patchWithCleanup,
} from "@web/../tests/web_test_helpers";
import { queryAll } from "@odoo/hoot-dom";
import { animationFrame } from "@odoo/hoot-mock";
import { download } from "@web/core/network/download";
import { methods as mobileNativeMethods } from "@web_mobile/js/services/core";
import { config as transitionConfig } from "@web/core/transition";
import { WebClient } from "@web/webclient/webclient";
beforeEach(async () => patchWithCleanup(transitionConfig, { disabled: true }));
test.tags("mobile");
test("can execute the callback of addHomeShortcut on an App", async () => {
const MY_IMAGE =
"iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==";
patchWithCleanup(mobileNativeMethods, {
addHomeShortcut({ title, shortcut_url, web_icon }) {
expect.step("should call addHomeShortcut");
expect(document.title).toBe(title);
expect(document.URL).toBe(shortcut_url);
expect(web_icon).toBe(MY_IMAGE);
},
});
defineMenus([
{
id: 2,
children: [],
name: "App2",
appID: 2,
actionID: 1003,
xmlid: "menu_2",
webIconData: `data:image/png;base64,${MY_IMAGE}`,
webIcon: false,
},
]);
await mountWithCleanup(WebClient);
getService("menu").setCurrentMenu(2);
await animationFrame();
expect(".o_user_menu").toHaveClass("d-none");
await contains("button.o_mobile_menu_toggle").click();
await contains(".o_user_menu_mobile > *:contains('Add to Home Screen')", {
root: document.body,
}).click();
expect.verifySteps(["should call addHomeShortcut"]);
});
test.tags("mobile");
test("can execute the callback of addHomeShortcut on the HomeMenu", async () => {
patchWithCleanup(mobileNativeMethods, {
addHomeShortcut() {
expect.step("shouldn't call addHomeShortcut");
},
});
mockService("notification", {
add(message) {
expect.step(`notification (${message})`);
},
});
await mountWithCleanup(WebClient);
await contains("button.o_mobile_menu_toggle").click();
await contains(".o_user_menu_mobile > *:contains('Add to Home Screen')", {
root: document.body,
}).click();
expect.verifySteps(["notification (No shortcut for Home Menu)"]);
});
test.tags("mobile");
test("can execute the callback of switchAccount", async () => {
patchWithCleanup(mobileNativeMethods, {
switchAccount() {
expect.step("should call switchAccount");
},
});
await mountWithCleanup(WebClient);
await contains("button.o_mobile_menu_toggle").click();
expect(
queryAll(".o_user_menu_mobile > *:contains('My Odoo.com account')", {
root: document.body,
})
).toHaveCount(0);
expect(
queryAll(".o_user_menu_mobile > *:contains('Log out')", {
root: document.body,
})
).toHaveCount(0);
await contains(".o_user_menu_mobile > *:contains('Switch/Add Account')", {
root: document.body,
}).click();
expect.verifySteps(["should call switchAccount"]);
});
test("remove origin from url before calling downloadFile native method", async () => {
patchWithCleanup(mobileNativeMethods, {
downloadFile(options) {
expect.step(options.url);
},
});
await download({
data: {},
url: "http://localhost:8080/abcd?a=b&c=d#e",
});
await download({
data: {},
url: "https://www.odoo.com/example",
});
await download({
data: {},
url: "/web/content/1?download=true",
});
expect.verifySteps(["/abcd?a=b&c=d", "/example", "/web/content/1?download=true"]);
});

View File

@@ -0,0 +1,291 @@
import {
animationFrame,
expect,
getFixture,
manuallyDispatchProgrammaticEvent,
mockUserAgent,
test,
} from "@odoo/hoot";
import { Component, useProps, signal, types as t, xml } from "@odoo/owl";
import {
clickSave,
contains,
defineModels,
destroyApp,
fields,
models,
mountView,
mountWithCleanup,
patchWithCleanup,
} from "@web/../tests/web_test_helpers";
import { Popover } from "@web/core/popover/popover";
import { user } from "@web/core/user";
import { useBackButton } from "@web/core/utils/hooks";
import { accountMethodsForMobile } from "@web_mobile/js/core/mixins";
import { methods as mobileNativeMethods } from "@web_mobile/js/services/core";
const MY_IMAGE =
"iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==";
const BASE64_SVG_IMAGE =
"PHN2ZyB4bWxucz0naHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmcnIHdpZHRoPScxNzUnIGhlaWdodD0nMTAwJyBmaWxsPScjMDAwJz48cG9seWdvbiBwb2ludHM9JzAsMCAxMDAsMCA1MCw1MCcvPjwvc3ZnPg==";
const BASE64_PNG_HEADER = "iVBORw0KGg";
class Users extends models.Model {
name = fields.Char();
}
defineModels([Users]);
test.tags("mobile");
test("component should receive a backbutton event", async () => {
mockUserAgent("android");
patchWithCleanup(mobileNativeMethods, {
overrideBackButton({ enabled }) {
expect.step(`overrideBackButton: ${enabled}`);
},
});
class DummyComponent extends Component {
static template = xml`<div/>`;
setup() {
useBackButton(this.onBack.bind(this));
}
onBack(ev) {
expect.step(`${ev.type} event`);
}
}
await mountWithCleanup(DummyComponent);
// simulate 'backbutton' event triggered by the app
document.dispatchEvent(new Event("backbutton"));
expect.verifySteps(["overrideBackButton: true", "backbutton event"]);
destroyApp();
expect.verifySteps(["overrideBackButton: false"]);
});
test.tags("mobile");
test("multiple components should receive backbutton events in the right order", async () => {
mockUserAgent("android");
patchWithCleanup(mobileNativeMethods, {
overrideBackButton({ enabled }) {
expect.step(`overrideBackButton: ${enabled}`);
},
});
class DummyComponent extends Component {
static template = xml`<div t-out="this.props.name" />`;
props = useProps({ name: t.string() });
setup() {
useBackButton(this.onBack.bind(this));
}
onBack(ev) {
expect.step(`${this.props.name}: ${ev.type} event`);
dummies().delete(this.props.name);
}
}
class Parent extends Component {
static components = { DummyComponent };
static template = xml`
<t t-foreach="this.dummies()" t-as="name" t-key="name">
<DummyComponent name="name" />
</t>
`;
dummies = dummies;
}
const dummies = signal.Set(new Set());
await mountWithCleanup(Parent);
// Need to be added 1 by 1 because Owl mounts siblings from last to first
dummies().add("dummy1");
await animationFrame();
dummies().add("dummy2");
await animationFrame();
dummies().add("dummy3");
await animationFrame();
// simulate 'backbutton' events triggered by the app
await manuallyDispatchProgrammaticEvent(document, "backbutton");
await animationFrame();
await manuallyDispatchProgrammaticEvent(document, "backbutton");
await animationFrame();
await manuallyDispatchProgrammaticEvent(document, "backbutton");
await animationFrame();
expect.verifySteps([
"overrideBackButton: true",
"dummy3: backbutton event",
"dummy2: backbutton event",
"dummy1: backbutton event",
"overrideBackButton: false",
]);
});
test.tags("mobile");
test("component should receive a backbutton event: custom activation", async () => {
mockUserAgent("android");
patchWithCleanup(mobileNativeMethods, {
overrideBackButton({ enabled }) {
expect.step(`overrideBackButton: ${enabled}`);
},
});
class DummyComponent extends Component {
static template = xml`<button class="dummy" t-out="this.show()" t-on-click="this.toggle" />`;
props = useProps({ show: t.boolean() });
show = signal(this.props.show);
setup() {
useBackButton(this.onBack.bind(this), this.show);
}
onBack(ev) {
expect.step(`${ev.type} event`);
}
toggle() {
this.show.set(!this.show());
}
}
await mountWithCleanup(DummyComponent, { props: { show: false } });
// shouldn't have enabled back button mount
expect.verifySteps([]);
await contains(".dummy").click();
// simulate 'backbutton' event triggered by the app
document.dispatchEvent(new Event("backbutton"));
await contains(".dummy").click();
// should have enabled/disabled the back button override
expect.verifySteps([
"overrideBackButton: true",
"backbutton event",
"overrideBackButton: false",
]);
destroyApp();
// enabled at mount
await mountWithCleanup(DummyComponent, { props: { show: true } });
// shouldn't have enabled back button at mount
expect.verifySteps(["overrideBackButton: true"]);
// simulate 'backbutton' event triggered by the app
document.dispatchEvent(new Event("backbutton"));
destroyApp();
// should have disabled the back-button override during unmount
expect.verifySteps(["backbutton event", "overrideBackButton: false"]);
});
test.tags("mobile");
test("popover is closable with backbutton event", async () => {
mockUserAgent("android");
patchWithCleanup(mobileNativeMethods, {
overrideBackButton({ enabled }) {
expect.step(`overrideBackButton: ${enabled}`);
},
});
class Comp extends Component {
static template = xml`<div id="comp">in popover</div>`;
}
await mountWithCleanup(Popover, {
props: {
target: getFixture(),
position: "bottom",
component: Comp,
close: () => destroyApp(),
},
});
await animationFrame();
expect(".o_popover").toHaveCount(1);
expect(".o_popover #comp").toHaveCount(1);
expect.verifySteps(["overrideBackButton: true"]);
// simulate 'backbutton' event triggered by the app
document.dispatchEvent(new Event("backbutton"));
expect.verifySteps(["overrideBackButton: false"]);
expect(".o_popover").toHaveCount(0);
expect(".o_popover #comp").toHaveCount(0);
});
test("controller should call native updateAccount method with SVG avatar when saving record", async () => {
patchWithCleanup(mobileNativeMethods, {
updateAccount(options) {
const { avatar, name, username } = options;
expect.step("should call updateAccount");
expect(avatar.startsWith(BASE64_PNG_HEADER)).toBe(true, {
message: "should have a PNG base64 encoded avatar",
});
expect(name).toBe("Marc Demo");
expect(username).toBe("demo");
},
});
patchWithCleanup(user, { login: "demo", name: "Marc Demo" });
patchWithCleanup(accountMethodsForMobile, {
url(path) {
if (path === "/web/image") {
return `data:image/svg+xml;base64,${BASE64_SVG_IMAGE}`;
}
return super.url(...arguments);
},
});
await mountView({
type: "form",
resModel: "users",
arch: `
<form js_class="res_users_preferences_form">
<sheet>
<field name="name"/>
</sheet>
</form>`,
});
await clickSave();
expect.verifySteps(["should call updateAccount"]);
});
test("controller should call native updateAccount method when saving record", async () => {
patchWithCleanup(mobileNativeMethods, {
async updateAccount(options) {
const { avatar, name, username } = options;
expect.step("should call updateAccount");
expect(avatar.startsWith(BASE64_PNG_HEADER)).toBe(true, {
message: "should have a PNG base64 encoded avatar",
});
expect(name).toBe("Marc Demo");
expect(username).toBe("demo");
},
});
patchWithCleanup(user, { login: "demo", name: "Marc Demo" });
patchWithCleanup(accountMethodsForMobile, {
url(path) {
if (path === "/web/image") {
return `data:image/png;base64,${MY_IMAGE}`;
}
return super.url(...arguments);
},
});
await mountView({
type: "form",
resModel: "users",
arch: `
<form js_class="res_users_preferences_form">
<sheet>
<field name="name"/>
</sheet>
</form>`,
});
await clickSave();
expect.verifySteps(["should call updateAccount"]);
});