refactor: sync timezone state (#10857)

This commit is contained in:
Alex Rudenko 2023-09-07 11:57:19 +02:00 committed by GitHub
parent 7f9c14c745
commit f8c7a46448
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -36,6 +36,11 @@ interface IdleOverridesState {
active: boolean; active: boolean;
} }
interface TimezoneState {
timezoneId?: string;
active: boolean;
}
/** /**
* @internal * @internal
*/ */
@ -49,6 +54,9 @@ export class EmulationManager {
#idleOverridesState: IdleOverridesState = { #idleOverridesState: IdleOverridesState = {
active: false, active: false,
}; };
#timezoneState: TimezoneState = {
active: false,
};
#secondaryClients = new Set<CDPSession>(); #secondaryClients = new Set<CDPSession>();
constructor(client: CDPSession) { constructor(client: CDPSession) {
@ -65,8 +73,11 @@ export class EmulationManager {
client.once(CDPSessionEmittedEvents.Disconnected, () => { client.once(CDPSessionEmittedEvents.Disconnected, () => {
return this.#secondaryClients.delete(client); return this.#secondaryClients.delete(client);
}); });
// We don't await here because we want to register all state changes before
// the target is unpaused.
void this.#syncViewport().catch(debugError); void this.#syncViewport().catch(debugError);
void this.#syncIdleState().catch(debugError); void this.#syncIdleState().catch(debugError);
void this.#syncTimezoneState().catch(debugError);
} }
get javascriptEnabled(): boolean { get javascriptEnabled(): boolean {
@ -170,19 +181,42 @@ export class EmulationManager {
} }
} }
async emulateTimezone(timezoneId?: string): Promise<void> { async #emulateTimezone(
client: CDPSession,
timezoneState: TimezoneState
): Promise<void> {
if (!timezoneState.active) {
return;
}
try { try {
await this.#client.send('Emulation.setTimezoneOverride', { await client.send('Emulation.setTimezoneOverride', {
timezoneId: timezoneId || '', timezoneId: timezoneState.timezoneId || '',
}); });
} catch (error) { } catch (error) {
if (isErrorLike(error) && error.message.includes('Invalid timezone')) { if (isErrorLike(error) && error.message.includes('Invalid timezone')) {
throw new Error(`Invalid timezone ID: ${timezoneId}`); throw new Error(`Invalid timezone ID: ${timezoneState.timezoneId}`);
} }
throw error; throw error;
} }
} }
async #syncTimezoneState() {
await Promise.all([
this.#emulateTimezone(this.#client, this.#timezoneState),
...Array.from(this.#secondaryClients).map(client => {
return this.#emulateTimezone(client, this.#timezoneState);
}),
]);
}
async emulateTimezone(timezoneId?: string): Promise<void> {
this.#timezoneState = {
timezoneId,
active: true,
};
await this.#syncTimezoneState();
}
async emulateVisionDeficiency( async emulateVisionDeficiency(
type?: Protocol.Emulation.SetEmulatedVisionDeficiencyRequest['type'] type?: Protocol.Emulation.SetEmulatedVisionDeficiencyRequest['type']
): Promise<void> { ): Promise<void> {