Debian Codegraph @

addons/web/static/lib/hoot/mock/navigator.js

raw
1 /** @odoo-module */
2
3 import { isInstanceOf } from "../../hoot-dom/hoot_dom_utils";
4 import {
5 createMock,
6 getSyncValue,
7 HootError,
8 MIME_TYPE,
9 MockEventTarget,
10 setSyncValue,
11 } from "../hoot_utils";
12 import { ensureTest } from "../main_runner";
13
14 /**
15 * @typedef {"android" | "ios" | "linux" | "mac" | "windows"} Platform
16 */
17
18 //-----------------------------------------------------------------------------
19 // Global
20 //-----------------------------------------------------------------------------
21
22 const {
23 Blob,
24 ClipboardItem = class NonSecureClipboardItem {},
25 navigator,
26 Object: { assign: $assign },
27 Set,
28 TypeError,
29 } = globalThis;
30 const { userAgent: $userAgent } = navigator;
31
32 //-----------------------------------------------------------------------------
33 // Internal
34 //-----------------------------------------------------------------------------
35
36 function getBlobValue(value) {
37 return isInstanceOf(value, Blob) ? value.text() : value;
38 }
39
40 /**
41 * Returns the final synchronous value of several item types.
42 *
43 * @param {unknown} value
44 * @param {string} type
45 */
46 function getClipboardValue(value, type) {
47 return getBlobValue(isInstanceOf(value, ClipboardItem) ? value.getType(type) : value);
48 }
49
50 function getMockValues() {
51 return {
52 sendBeacon: throwNotImplemented("sendBeacon"),
53 userAgent: makeUserAgent("linux"),
54 /** @type {Navigator["vibrate"]} */
55 vibrate: throwNotImplemented("vibrate"),
56 };
57 }
58
59 /**
60 * @returns {Record<PermissionName, { name: string; state: PermissionState }>}
61 */
62 function getPermissions() {
63 return {
64 "background-sync": {
65 state: "granted", // should always be granted
66 name: "background_sync",
67 },
68 "local-fonts": {
69 state: "denied",
70 name: "local_fonts",
71 },
72 "payment-handler": {
73 state: "denied",
74 name: "payment_handler",
75 },
76 "persistent-storage": {
77 state: "denied",
78 name: "durable_storage",
79 },
80 "screen-wake-lock": {
81 state: "denied",
82 name: "screen_wake_lock",
83 },
84 "storage-access": {
85 state: "denied",
86 name: "storage-access",
87 },
88 "window-management": {
89 state: "denied",
90 name: "window_placement",
91 },
92 accelerometer: {
93 state: "denied",
94 name: "sensors",
95 },
96 camera: {
97 state: "denied",
98 name: "video_capture",
99 },
100 geolocation: {
101 state: "denied",
102 name: "geolocation",
103 },
104 gyroscope: {
105 state: "denied",
106 name: "sensors",
107 },
108 magnetometer: {
109 state: "denied",
110 name: "sensors",
111 },
112 microphone: {
113 state: "denied",
114 name: "audio_capture",
115 },
116 midi: {
117 state: "denied",
118 name: "midi",
119 },
120 notifications: {
121 state: "denied",
122 name: "notifications",
123 },
124 push: {
125 state: "denied",
126 name: "push",
127 },
128 };
129 }
130
131 function getUserAgentBrowser() {
132 if (/Firefox/i.test($userAgent)) {
133 return "Gecko/20100101 Firefox/1000.0"; // Firefox
134 }
135 if (/Chrome/i.test($userAgent)) {
136 return "AppleWebKit/1000.00 (KHTML, like Gecko) Chrome/1000.00 Safari/1000.00"; // Chrome
137 }
138 if (/Safari/i.test($userAgent)) {
139 return "AppleWebKit/1000.00 (KHTML, like Gecko) Version/1000.00 Safari/1000.00"; // Safari
140 }
141 }
142
143 /**
144 * @param {Platform} platform
145 */
146 function makeUserAgent(platform) {
147 const userAgent = ["Mozilla/5.0"];
148 switch (platform.toLowerCase()) {
149 case "android": {
150 userAgent.push("(Linux; Android 1000)");
151 break;
152 }
153 case "ios": {
154 userAgent.push("(iPhone; CPU iPhone OS 1000_0 like Mac OS X)");
155 break;
156 }
157 case "linux": {
158 userAgent.push("(X11; Linux x86_64)");
159 break;
160 }
161 case "mac":
162 case "macintosh": {
163 userAgent.push("(Macintosh; Intel Mac OS X 10_15_7)");
164 break;
165 }
166 case "win":
167 case "windows": {
168 userAgent.push("(Windows NT 10.0; Win64; x64)");
169 break;
170 }
171 default: {
172 userAgent.push(platform);
173 }
174 }
175 if (userAgentBrowser) {
176 userAgent.push(userAgentBrowser);
177 }
178 return userAgent.join(" ");
179 }
180
181 /**
182 * @param {string} fnName
183 */
184 function throwNotImplemented(fnName) {
185 return function notImplemented() {
186 throw new HootError(`unmocked navigator method: ${fnName}`);
187 };
188 }
189
190 /** @type {Set<MockPermissionStatus>} */
191 const permissionStatuses = new Set();
192 const userAgentBrowser = getUserAgentBrowser();
193 const mockValues = getMockValues();
194
195 //-----------------------------------------------------------------------------
196 // Exports
197 //-----------------------------------------------------------------------------
198
199 export class MockClipboard {
200 /** @type {unknown} */
201 _value = null;
202
203 async read() {
204 return this._value;
205 }
206
207 async readText() {
208 return String(getClipboardValue(this._value, MIME_TYPE.text) ?? "");
209 }
210
211 async write(value) {
212 this._value = value;
213 }
214
215 async writeText(value) {
216 this._value = String(getClipboardValue(value, MIME_TYPE.text) ?? "");
217 }
218 }
219
220 export class MockClipboardItem extends ClipboardItem {
221 constructor(items) {
222 super(items);
223
224 setSyncValue(this, items);
225 }
226
227 // Added synchronous methods to enhance speed in tests
228
229 async getType(type) {
230 return getSyncValue(this, false)[type];
231 }
232 }
233
234 export class MockPermissions {
235 /**
236 * @param {PermissionDescriptor} permissionDesc
237 */
238 async query({ name }) {
239 if (!(name in currentPermissions)) {
240 throw new TypeError(
241 `The provided value '${name}' is not a valid enum value of type PermissionName`
242 );
243 }
244 return new MockPermissionStatus(name);
245 }
246 }
247
248 export class MockPermissionStatus extends MockEventTarget {
249 static publicListeners = ["change"];
250
251 /** @type {typeof currentPermissions[PermissionName]} */
252 _permission;
253
254 /**
255 * @param {PermissionName} name
256 * @param {PermissionState} value
257 */
258 constructor(name) {
259 super(...arguments);
260
261 this._permission = currentPermissions[name];
262 permissionStatuses.add(this);
263 }
264
265 get name() {
266 return this._permission.name;
267 }
268
269 get state() {
270 return this._permission.state;
271 }
272 }
273
274 export const currentPermissions = getPermissions();
275
276 export const mockClipboard = new MockClipboard();
277
278 export const mockPermissions = new MockPermissions();
279
280 export const mockNavigator = createMock(navigator, {
281 clipboard: { value: mockClipboard },
282 maxTouchPoints: { get: () => (globalThis.ontouchstart === undefined ? 0 : 1) },
283 permissions: { value: mockPermissions },
284 sendBeacon: { get: () => mockValues.sendBeacon },
285 serviceWorker: { get: () => undefined },
286 userAgent: { get: () => mockValues.userAgent },
287 vibrate: { get: () => mockValues.vibrate },
288 });
289
290 export function cleanupNavigator() {
291 permissionStatuses.clear();
292 $assign(currentPermissions, getPermissions());
293 $assign(mockValues, getMockValues());
294 }
295
296 /**
297 * @param {PermissionName} name
298 * @param {PermissionState} [value]
299 */
300 export function mockPermission(name, value) {
301 ensureTest("mockPermission");
302 if (!(name in currentPermissions)) {
303 throw new TypeError(
304 `The provided value '${name}' is not a valid enum value of type PermissionName`
305 );
306 }
307
308 currentPermissions[name].state = value;
309
310 for (const permissionStatus of permissionStatuses) {
311 if (permissionStatus.name === name) {
312 permissionStatus.dispatchEvent(new Event("change"));
313 }
314 }
315 }
316
317 /**
318 * @param {Navigator["sendBeacon"]} callback
319 */
320 export function mockSendBeacon(callback) {
321 ensureTest("mockSendBeacon");
322 mockValues.sendBeacon = callback;
323 }
324
325 /**
326 * @param {Platform} platform
327 */
328 export function mockUserAgent(platform = "linux") {
329 ensureTest("mockUserAgent");
330 mockValues.userAgent = makeUserAgent(platform);
331 }
332
333 /**
334 * @param {Navigator["vibrate"]} callback
335 */
336 export function mockVibrate(callback) {
337 ensureTest("mockVibrate");
338 mockValues.vibrate = callback;
339 }