orientation.js (2877B)
1 /* This Source Code Form is subject to the terms of the Mozilla Public 2 * License, v. 2.0. If a copy of the MPL was not distributed with this 3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ 4 5 "use strict"; 6 7 const { 8 PORTRAIT_PRIMARY, 9 LANDSCAPE_PRIMARY, 10 } = require("resource://devtools/client/responsive/constants.js"); 11 12 /** 13 * Helper that gets the screen orientation of the device displayed in the RDM viewport. 14 * This function take in both a device and viewport object and an optional rotated angle. 15 * If a rotated angle is passed, then we calculate what the orientation type of the device 16 * would be in relation to its current orientation. Otherwise, return the current 17 * orientation and angle. 18 * 19 * @param {object} device 20 * The device whose content is displayed in the viewport. Used to determine the 21 * primary orientation. 22 * @param {object} viewport 23 * The viewport displaying device content. Used to determine the current 24 * orientation type of the device while in RDM. 25 * @param {number | null} angleToRotateTo 26 * Optional. The rotated angle specifies the degree to which the device WILL be 27 * turned to. If undefined, then only return the current orientation and angle 28 * of the device. 29 * @return {object} the orientation of the device. 30 */ 31 function getOrientation(device, viewport, angleToRotateTo = null) { 32 const { width: deviceWidth, height: deviceHeight } = device; 33 const { width: viewportWidth, height: viewportHeight } = viewport; 34 35 // Determine the primary orientation of the device screen. 36 const primaryOrientation = 37 deviceHeight >= deviceWidth ? PORTRAIT_PRIMARY : LANDSCAPE_PRIMARY; 38 39 // Determine the current orientation of the device screen. 40 const currentOrientation = 41 viewportHeight >= viewportWidth ? PORTRAIT_PRIMARY : LANDSCAPE_PRIMARY; 42 43 // Calculate the orientation angle of the device. 44 let angle; 45 46 if (typeof angleToRotateTo === "number") { 47 angle = angleToRotateTo; 48 } else if (currentOrientation !== primaryOrientation) { 49 angle = 90; 50 } else { 51 angle = 0; 52 } 53 54 // Calculate the orientation type of the device. 55 let orientationType = currentOrientation; 56 57 // If the viewport orientation is different from the primary orientation and the angle 58 // to rotate to is 0, then we are moving the device orientation back to its primary 59 // orientation. 60 if (currentOrientation !== primaryOrientation && angleToRotateTo === 0) { 61 orientationType = primaryOrientation; 62 } else if (angleToRotateTo === 90 || angleToRotateTo === 270) { 63 if (currentOrientation.includes("portrait")) { 64 orientationType = LANDSCAPE_PRIMARY; 65 } else if (currentOrientation.includes("landscape")) { 66 orientationType = PORTRAIT_PRIMARY; 67 } 68 } 69 70 return { 71 type: orientationType, 72 angle, 73 }; 74 } 75 76 exports.getOrientation = getOrientation;