Debian Codegraph @

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

raw
1 /** @odoo-module */
2
3 import { getTimeOffset, isTimeFrozen, resetTimeOffset } from "@web/../lib/hoot-dom/helpers/time";
4 import { createMock, HootError, isNil } from "../hoot_utils";
5 import { ensureTest } from "../main_runner";
6
7 /**
8 * @typedef DateSpecs
9 * @property {number} [year]
10 * @property {number} [month] // 1-12
11 * @property {number} [day] // 1-31
12 * @property {number} [hour] // 0-23
13 * @property {number} [minute] // 0-59
14 * @property {number} [second] // 0-59
15 * @property {number} [millisecond] // 0-999
16 */
17
18 //-----------------------------------------------------------------------------
19 // Global
20 //-----------------------------------------------------------------------------
21
22 const { Date, Intl } = globalThis;
23 const { now: $now, UTC: $UTC } = Date;
24 const { DateTimeFormat, Locale } = Intl;
25
26 //-----------------------------------------------------------------------------
27 // Internal
28 //-----------------------------------------------------------------------------
29
30 /**
31 * @param {Date} baseDate
32 */
33 function computeTimeZoneOffset(baseDate) {
34 const utcDate = new Date(baseDate.toLocaleString(DEFAULT_LOCALE, { timeZone: "UTC" }));
35 const tzDate = new Date(baseDate.toLocaleString(DEFAULT_LOCALE, { timeZone: timeZoneName }));
36 return (utcDate - tzDate) / 60000; // in minutes
37 }
38
39 /**
40 * @param {number} id
41 */
42 function getDateParams() {
43 return [...dateParams.slice(0, -1), dateParams.at(-1) + getTimeStampDiff() + getTimeOffset()];
44 }
45
46 function getTimeStampDiff() {
47 return isTimeFrozen() ? 0 : $now() - dateTimeStamp;
48 }
49
50 /**
51 * @param {string | DateSpecs} dateSpecs
52 */
53 function parseDateParams(dateSpecs) {
54 /** @type {DateSpecs} */
55 const specs =
56 (typeof dateSpecs === "string" ? dateSpecs.match(DATE_REGEX)?.groups : dateSpecs) || {};
57 return [
58 specs.year ?? DEFAULT_DATE[0],
59 (specs.month ?? DEFAULT_DATE[1]) - 1,
60 specs.day ?? DEFAULT_DATE[2],
61 specs.hour ?? DEFAULT_DATE[3],
62 specs.minute ?? DEFAULT_DATE[4],
63 specs.second ?? DEFAULT_DATE[5],
64 specs.millisecond ?? DEFAULT_DATE[6],
65 ].map(Number);
66 }
67
68 /**
69 * @param {typeof dateParams} newDateParams
70 */
71 function setDateParams(newDateParams) {
72 dateParams = newDateParams;
73 dateTimeStamp = $now();
74
75 resetTimeOffset();
76 }
77
78 /**
79 * @param {string | number | null | undefined} tz
80 */
81 function setTimeZone(tz) {
82 if (typeof tz === "string") {
83 if (!tz.includes("/")) {
84 throw new HootError(`invalid time zone: must be in the format <Country/...Location>`);
85 }
86
87 // Set TZ name
88 timeZoneName = tz;
89 // Set TZ offset based on name (must be computed for each date)
90 timeZoneOffset = computeTimeZoneOffset;
91 } else if (typeof tz === "number") {
92 // Only set TZ offset
93 timeZoneOffset = tz * -60;
94 } else {
95 // Reset both TZ name & offset
96 timeZoneName = null;
97 timeZoneOffset = null;
98 }
99
100 for (const callback of timeZoneChangeCallbacks) {
101 callback(tz ?? DEFAULT_TIMEZONE_NAME);
102 }
103 }
104
105 class MockDateTimeFormat extends DateTimeFormat {
106 constructor(locales, options) {
107 super(locales, {
108 ...options,
109 timeZone: options?.timeZone ?? timeZoneName ?? DEFAULT_TIMEZONE_NAME,
110 });
111 }
112
113 /** @type {Intl.DateTimeFormat["format"]} */
114 format(date) {
115 return super.format(date || new MockDate());
116 }
117
118 resolvedOptions() {
119 return {
120 ...super.resolvedOptions(),
121 timeZone: timeZoneName ?? DEFAULT_TIMEZONE_NAME,
122 locale: locale ?? DEFAULT_LOCALE,
123 };
124 }
125 }
126
127 const DATE_REGEX =
128 /(?<year>\d{4})[/-](?<month>\d{2})[/-](?<day>\d{2})([\sT]+(?<hour>\d{2}):(?<minute>\d{2}):(?<second>\d{2})(\.(?<millisecond>\d{3}))?)?/;
129 const DEFAULT_DATE = [2019, 2, 11, 9, 30, 0, 0];
130 const DEFAULT_LOCALE = "en-US";
131 const DEFAULT_TIMEZONE_NAME = "Europe/Brussels";
132 const DEFAULT_TIMEZONE_OFFSET = -60;
133
134 /** @type {((tz: string | number) => any)[]} */
135 const timeZoneChangeCallbacks = [];
136
137 let dateParams = DEFAULT_DATE;
138 let dateTimeStamp = $now();
139 /** @type {string | null} */
140 let locale = null;
141 /** @type {string | null} */
142 let timeZoneName = null;
143 /** @type {number | ((date: Date) => number) | null} */
144 let timeZoneOffset = null;
145
146 //-----------------------------------------------------------------------------
147 // Exports
148 //-----------------------------------------------------------------------------
149
150 export function cleanupDate() {
151 setDateParams(DEFAULT_DATE);
152 locale = null;
153 timeZoneName = null;
154 timeZoneOffset = null;
155 }
156
157 /**
158 * Mocks the current date and time, and also the time zone if any.
159 *
160 * Date can either be an object describing the date and time to mock, or a
161 * string in SQL or ISO format (time and millisecond values can be omitted).
162 * @see {@link mockTimeZone} for the time zone params.
163 *
164 * @param {string | DateSpecs} [date]
165 * @param {string | number | null} [tz]
166 * @example
167 * mockDate("2023-12-25T20:45:00"); // 2023-12-25 20:45:00 UTC
168 * @example
169 * mockDate({ year: 2023, month: 12, day: 25, hour: 20, minute: 45 }); // same as above
170 * @example
171 * mockDate("2019-02-11 09:30:00.001", +2);
172 */
173 export function mockDate(date, tz) {
174 ensureTest("mockDate");
175 setDateParams(date ? parseDateParams(date) : DEFAULT_DATE);
176 if (!isNil(tz)) {
177 setTimeZone(tz);
178 }
179 }
180
181 /**
182 * Mocks the current locale.
183 *
184 * If the time zone hasn't been mocked already, it will be assigned to the first
185 * time zone available in the given locale (if any).
186 *
187 * @param {string} newLocale
188 * @example
189 * mockTimeZone("ja-JP"); // UTC + 9
190 */
191 export function mockLocale(newLocale) {
192 ensureTest("mockLocale");
193 locale = newLocale;
194
195 if (!isNil(locale) && isNil(timeZoneName)) {
196 // Set TZ from locale (if not mocked already)
197 const firstAvailableTZ = new Locale(locale).timeZones?.[0];
198 if (!isNil(firstAvailableTZ)) {
199 setTimeZone(firstAvailableTZ);
200 }
201 }
202 }
203
204 /**
205 * Mocks the current time zone.
206 *
207 * Time zone can either be a time zone or an offset. Number offsets are expressed
208 * in hours.
209 *
210 * @param {string | number | null} [tz]
211 * @example
212 * mockTimeZone(+10); // UTC + 10
213 * @example
214 * mockTimeZone("Europe/Brussels"); // UTC + 1 (or UTC + 2 in summer)
215 * @example
216 * mockTimeZone(null) // Resets to test default (+1)
217 */
218 export function mockTimeZone(tz) {
219 ensureTest("mockTimeZone");
220 setTimeZone(tz);
221 }
222
223 /**
224 * Subscribe to changes made on the time zone (mocked) value.
225 *
226 * @param {(tz: string | number) => any} callback
227 */
228 export function onTimeZoneChange(callback) {
229 timeZoneChangeCallbacks.push(callback);
230 }
231
232 export class MockDate extends Date {
233 constructor(...args) {
234 if (args.length === 1) {
235 super(args[0]);
236 } else {
237 const params = getDateParams();
238 for (let i = 0; i < params.length; i++) {
239 args[i] ??= params[i];
240 }
241 super($UTC(...args));
242 }
243 }
244
245 getTimezoneOffset() {
246 const offset = timeZoneOffset ?? DEFAULT_TIMEZONE_OFFSET;
247 return typeof offset === "function" ? offset(this) : offset;
248 }
249
250 static now() {
251 return new MockDate().getTime();
252 }
253 }
254
255 export const MockIntl = createMock(Intl, {
256 DateTimeFormat: { value: MockDateTimeFormat },
257 });