Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@financial-times/o-viewport

Package Overview
Dependencies
Maintainers
18
Versions
19
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@financial-times/o-viewport - npm Package Compare versions

Comparing version 3.3.3 to 4.0.0-beta.1

src/utils.js

130

browser.js
"use strict";
// let debug;
const utils = require("./dist/utils");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
const throttle = utils.throttle;
const debounce = utils.debounce;
const listeners = {};
const intervals = {
var _utils = _interopRequireDefault(require("./dist/utils"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var throttle = _utils.default.throttle;
var debounce = _utils.default.debounce;
var listeners = {};
var intervals = {
resize: 100,

@@ -15,2 +21,15 @@ orientation: 100,

};
/**
*
* @param {string} eventType - The type of event to throttle for this duration.
* @param {number} interval - The duration to throttle in ms.
* @example
* // throttle for different events at different durations
* setThrottleInterval('scroll', 100)
* setThrottleInterval('resize', 300)
* setThrottleInterval('orientation', 30)
* setThrottleInterval('visibility', 30)
* // throttle all events at 30ms
* setThrottleInterval(30);
*/

@@ -27,3 +46,7 @@ function setThrottleInterval(eventType, interval) {

}
/**
* @access private
*/
function listenToResize() {

@@ -34,6 +57,6 @@ if (listeners.resize) {

const eventType = 'resize';
const handler = debounce(function (ev) {
utils.broadcast('resize', {
viewport: utils.getSize(),
var eventType = 'resize';
var handler = debounce(function (ev) {
_utils.default.broadcast('resize', {
viewport: _utils.default.getSize(),
originalEvent: ev

@@ -48,3 +71,7 @@ });

}
/**
* @access private
*/
function listenToOrientation() {

@@ -55,7 +82,7 @@ if (listeners.orientation) {

const eventType = 'orientationchange';
const handler = debounce(function (ev) {
utils.broadcast('orientation', {
viewport: utils.getSize(),
orientation: utils.getOrientation(),
var eventType = 'orientationchange';
var handler = debounce(function (ev) {
_utils.default.broadcast('orientation', {
viewport: _utils.default.getSize(),
orientation: _utils.default.getOrientation(),
originalEvent: ev

@@ -70,3 +97,7 @@ });

}
/**
* @access private
*/
function listenToVisibility() {

@@ -77,6 +108,6 @@ if (listeners.visibility) {

const eventType = utils.detectVisiblityAPI().eventType;
const handler = debounce(function (ev) {
utils.broadcast('visibility', {
hidden: utils.getVisibility(),
var eventType = 'visibilitychange';
var handler = debounce(function (ev) {
_utils.default.broadcast('visibility', {
hidden: _utils.default.getVisibility(),
originalEvent: ev

@@ -91,3 +122,7 @@ });

}
/**
* @access private
*/
function listenToScroll() {

@@ -98,7 +133,8 @@ if (listeners.scroll) {

const eventType = 'scroll';
const handler = throttle(function (ev) {
const scrollPos = utils.getScrollPosition();
utils.broadcast('scroll', {
viewport: utils.getSize(),
var eventType = 'scroll';
var handler = throttle(function (ev) {
var scrollPos = _utils.default.getScrollPosition();
_utils.default.broadcast('scroll', {
viewport: _utils.default.getSize(),
scrollHeight: scrollPos.height,

@@ -117,3 +153,16 @@ scrollLeft: scrollPos.left,

}
/**
* Start listening for an event(s).
* @param {string} eventType - The event to start listening for. One of `resize`, `scroll`, `orientation`, `visibility` or `all`.
* @example
* // Start listening for all events.
* oViewport.listenTo('all');
*
* // It is now possible to listen for debounce o-viewport events such as `oViewport.orientation`.
* document.body.addEventListener('oViewport.orientation', function(event) {
* console.log(event.type); // oViewport.orientation
* });
*/
function listenTo(eventType) {

@@ -136,3 +185,13 @@ if (eventType === 'resize' || eventType === 'all') {

}
/**
* Stop listening for an event(s).
* @param {string} eventType - The event to stop listening for. One of `resize`, `scroll`, `orientation`, `visibility` or `all`.
* @example
* // Start listening for all events.
* oViewport.listenTo('all');
* // We're done. Stop listening for all events.
* oViewport.stopListeningTo('all');
*/
function stopListeningTo(eventType) {

@@ -147,14 +206,15 @@ if (eventType === 'all') {

module.exports = {
var _default = {
debug: function debug() {
// debug = true;
utils.debug();
_utils.default.debug();
},
listenTo: listenTo,
stopListeningTo: stopListeningTo,
setThrottleInterval: setThrottleInterval,
getOrientation: utils.getOrientation,
getSize: utils.getSize,
getScrollPosition: utils.getScrollPosition,
getVisibility: utils.getVisibility
};
listenTo,
stopListeningTo,
setThrottleInterval,
getOrientation: _utils.default.getOrientation,
getSize: _utils.default.getSize,
getScrollPosition: _utils.default.getScrollPosition,
getVisibility: _utils.default.getVisibility
};
exports.default = _default;
module.exports = exports.default;
"use strict";
/* jshint devel: true */
const oUtils = require("@financial-times/o-utils");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
let _debug;
var Utils = _interopRequireWildcard(require("@financial-times/o-utils"));
function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
var _debug;
/**
*
* @param {string} eventType
* @param {object} data
* @param {EventTarget} target
*/
function broadcast(eventType, data, target) {

@@ -20,35 +35,71 @@ target = target || document.body;

}
/**
* Get the viewport height.
* @param {boolean} ignoreScrollbars [false] - set to true to discount scrollbar height.
* @return {number}
*/
function getHeight(ignoreScrollbars) {
return ignoreScrollbars ? document.documentElement.clientHeight : Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
}
/**
* Get the viewport width.
* @param {boolean} ignoreScrollbars [false] - set to true to discount scrollbar width
* @return {number}
*/
function getWidth(ignoreScrollbars) {
return ignoreScrollbars ? document.documentElement.clientWidth : Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
}
/**
* Viewport size.
* @typedef {Object} Size
* @property {number} height
* @property {number} width
*/
/**
* Get the viewport width and height.
* @param {boolean} ignoreScrollbars [false] - set to true to discount scrollbar width/height.
* @return {Size}
*/
function getSize(ignoreScrollbars) {
return {
height: module.exports.getHeight(ignoreScrollbars),
width: module.exports.getWidth(ignoreScrollbars)
height: getHeight(ignoreScrollbars),
width: getWidth(ignoreScrollbars)
};
}
/**
* Scroll position.
* @typedef {Object} ScrollPosition
* @property {number} height - `document.body.scrollHeight`
* @property {number} width - `document.body.scrollWidth`
* @property {number} left - `window.pageXOffset || window.scrollX`
* @property {number} top - `window.pageYOffset || window.scrollY`
*/
/**
* @return {ScrollPosition}
*/
function getScrollPosition() {
const de = document.documentElement;
const db = document.body; // adapted from https://developer.mozilla.org/en-US/docs/Web/API/Window/scrollY
const isCSS1Compat = (document.compatMode || '') === 'CSS1Compat';
const ieX = isCSS1Compat ? de.scrollLeft : db.scrollLeft;
const ieY = isCSS1Compat ? de.scrollTop : db.scrollTop;
return {
height: db.scrollHeight,
width: db.scrollWidth,
left: window.pageXOffset || window.scrollX || ieX,
top: window.pageYOffset || window.scrollY || ieY
height: document.body.scrollHeight,
width: document.body.scrollWidth,
left: window.pageXOffset || window.scrollX,
top: window.pageYOffset || window.scrollY
};
}
/**
* @return {string} - 'portrait' or 'landscape'
*/
function getOrientation() {
const orientation = window.screen.orientation || window.screen.mozOrientation || window.screen.msOrientation || undefined;
var orientation = window.screen.orientation;

@@ -63,46 +114,26 @@ if (orientation) {

}
/**
* @return {boolean} - true if the viewport is visible
*/
function detectVisiblityAPI() {
let hiddenName;
let eventType;
if (typeof document.hidden !== 'undefined') {
hiddenName = 'hidden';
eventType = 'visibilitychange';
} else if (typeof document.mozHidden !== 'undefined') {
hiddenName = 'mozHidden';
eventType = 'mozvisibilitychange';
} else if (typeof document.msHidden !== 'undefined') {
hiddenName = 'msHidden';
eventType = 'msvisibilitychange';
} else if (typeof document.webkitHidden !== 'undefined') {
hiddenName = 'webkitHidden';
eventType = 'webkitvisibilitychange';
}
return {
hiddenName: hiddenName,
eventType: eventType
};
}
function getVisibility() {
const hiddenName = detectVisiblityAPI().hiddenName;
return document[hiddenName];
return document.hidden;
}
module.exports = {
var _default = {
debug: function debug() {
_debug = true;
},
broadcast: broadcast,
getWidth: getWidth,
getHeight: getHeight,
getSize: getSize,
getScrollPosition: getScrollPosition,
getVisibility: getVisibility,
getOrientation: getOrientation,
detectVisiblityAPI: detectVisiblityAPI,
debounce: oUtils.debounce,
throttle: oUtils.throttle
};
broadcast,
getWidth,
getHeight,
getSize,
getScrollPosition,
getVisibility,
getOrientation,
debounce: Utils.debounce,
throttle: Utils.throttle
};
exports.default = _default;
module.exports = exports.default;

@@ -18,3 +18,4 @@ {

"optional": [
"matchmedia"
"matchmedia",
"screen.orientation"
]

@@ -21,0 +22,0 @@ },

@@ -12,2 +12,4 @@ {

"*.json",
"*.js",
"!main.js",
"scss",

@@ -27,3 +29,3 @@ "!bower.json",

"name": "@financial-times/o-viewport",
"version": "3.3.3",
"version": "4.0.0-beta.1",
"description": "Utility for moderating listeners for browser events on window",

@@ -30,0 +32,0 @@ "dependencies": {

@@ -5,3 +5,3 @@ # o-viewport [![CircleCI](https://circleci.com/gh/Financial-Times/o-viewport.svg?style=svg)](https://circleci.com/gh/Financial-Times/o-viewport) [![MIT licensed](https://img.shields.io/badge/license-MIT-blue.svg)](#licence)

*Note: within the module's API and in the documentation below `orientation` and `visibility` are used instead of `orientationchange` or `visibilitychange`, but the actual browser event listened to is `orientationchange` or `visibilitychange`*
*Note: within the component's API and in the documentation below `orientation` and `visibility` are used instead of `orientationchange` or `visibilitychange`, but the actual browser event listened to is `orientationchange` or `visibilitychange`*

@@ -15,2 +15,19 @@ ## Methods

```js
import oViewport from './../main.js';
// Fire for orientation events.
oViewport.listenTo('orientation');
// Listener for debounced orientation events via o-viewport.
document.body.addEventListener('oViewport.orientation', function(event) {
console.log(event.type); // oViewport.orientation
console.log(event.viewport); // { height, width }
console.log(event.orientation); // 'portrait' or 'landscape'
console.log(event.originalEvent); // the original browser event
});
```
See [events](#events) for more examples.
### `o-viewport#stopListeningTo(eventType)`

@@ -21,8 +38,21 @@ Remove the attached listener from the window for the named event [`resize`, `scroll`, `orientation`, `visibility` or `all`].

```js
// Stop listening to the orientation event.
oViewport.stopListeningTo('orientation');
```
### `o-viewport#getOrientation()`
Provides a reasonably reliable way (more so than `window.orientation`) of obtaining the current orientation of the viewport.
```js
oViewport.getOrientation(); // 'portrait' or 'landscape'
```
### `o-viewport#getVisibility()`
Provides a reasonably reliable way of obtaining the current visibility of the viewport.
```js
oViewport.getVisibility(); // boolean, true if visible
```
### `o-viewport#getSize(ignoreScrollbars)`

@@ -33,2 +63,6 @@ Provides a reliable way of obtaining the current dimensions of the browser window. Returns an object with the properties `width` and `height`.

```js
oViewport.getSize(); // {width: 100, height: 100} without scrollbars
oViewport.getSize(true); // {width: 108, height: 100} including scrollbar width
```

@@ -38,2 +72,6 @@ ### `o-viewport#getScrollPosition()`

```js
oViewport.getScrollPosition(); // {width: 100, height: 100, left: 0, top: 10}
```
### `o-viewport#setThrottleInterval(eventType, interval)` *Product use only*

@@ -56,23 +94,38 @@ Sets the debounce/throttle interval for a given event [`scroll`, `resize` or `orientation`].

## Events
Each of these custom events are fired on `document.body`. For each custom event `event.detail.originalEvent` contains a reference to the original browser event and `event.detail.viewport` the result of `o-viewport#getSize()`. Additional properties in `event.detail` are detailed below:
Each of these custom events are fired on `document.body`. For each custom event `event.detail.originalEvent` contains a reference to the original browser event and `event.detail.viewport` the result of `o-viewport#getSize()`. For example:
```js
import oViewport from './../main.js';
// Fire for all viewport events.
oViewport.listenTo('all');
// Listener for debounced visibility events via o-viewport.
document.body.addEventListener('oViewport.visibility', function(event) {
console.log(event.type); // oViewport.resize
console.log(event.detail.viewport); // { height, width }
console.log(event.detail.hidden); // boolean
});
```
Note `event.detail.hidden` is unique to the `oViewport.visibility` event. Additional unique properties for `o-viewport` events are detailed below.
### `oViewport.resize`
No additional properties
- No additional properties.
### `oViewport.orientation`
orientation: 'portrait' or 'landscape'
- data.orientation: 'portrait' or 'landscape'
### `oViewport.visibility`
hidden: true or false
- data.hidden: true or false
### `oViewport.scroll`
```js
scrollLeft: body.scrollLeft // or documentElement.scrollLeft in < ie10
scrollTop: body.scrollTop // or documentElement.scrollTop in < ie10
scrollHeight: body.scrollHeight
scrollWidth: body.scrollWidth
```
- data.scrollLeft: unitless px value of scroll position
- data.scrollTop: unitless px value of scroll position
- data.scrollHeight: unitless px value of scroll height
- data.scrollWidth: unitless px value of scroll width

@@ -84,2 +137,13 @@ ## Throttling

Use the [setThrottleInterval](#o-viewportsetthrottleintervaleventtype-interval-product-use-only) method to customise throttling.
## Migration
State | Major Version | Last Minor Release | Migration guide |
:---: | :---: | :---: | :---:
✨ active | 4 | N/A | [migrate to v4](MIGRATION.md#migrating-from-v3-to-v4) |
⚠ maintained | 3 | 3.3 | [migrate to v3](MIGRATION.md#migrating-from-v2-to-v3) |
╳ deprecated | 2 | 2.3 | [migrate to v2](MIGRATION.md#migrating-from-v1-to-v2) |
╳ deprecated | 1 | 1.5 | N/A |
----

@@ -86,0 +150,0 @@

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc