1/** 2 * Copyright 2017 Google Inc. All rights reserved. 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16import { CDPSession } from './Connection.js'; 17import { Viewport } from './PuppeteerViewport.js'; 18import { Protocol } from 'devtools-protocol'; 19 20export class EmulationManager { 21 _client: CDPSession; 22 _emulatingMobile = false; 23 _hasTouch = false; 24 25 constructor(client: CDPSession) { 26 this._client = client; 27 } 28 29 async emulateViewport(viewport: Viewport): Promise<boolean> { 30 const mobile = viewport.isMobile || false; 31 const width = viewport.width; 32 const height = viewport.height; 33 const deviceScaleFactor = viewport.deviceScaleFactor || 1; 34 const screenOrientation: Protocol.Emulation.ScreenOrientation = 35 viewport.isLandscape 36 ? { angle: 90, type: 'landscapePrimary' } 37 : { angle: 0, type: 'portraitPrimary' }; 38 const hasTouch = viewport.hasTouch || false; 39 40 await Promise.all([ 41 this._client.send('Emulation.setDeviceMetricsOverride', { 42 mobile, 43 width, 44 height, 45 deviceScaleFactor, 46 screenOrientation, 47 }), 48 this._client.send('Emulation.setTouchEmulationEnabled', { 49 enabled: hasTouch, 50 }), 51 ]); 52 53 const reloadNeeded = 54 this._emulatingMobile !== mobile || this._hasTouch !== hasTouch; 55 this._emulatingMobile = mobile; 56 this._hasTouch = hasTouch; 57 return reloadNeeded; 58 } 59} 60