native-fn
Version:
111 lines (107 loc) • 3.43 kB
JavaScript
;
var ENTRIES = [];
var FALLBACK_DIMENSION = {
innerWidth: -1,
innerHeight: -1,
outerWidth: -1,
outerHeight: -1,
scale: 1,
};
var currentDimension = null;
var Dimension = {
get value() {
return getDimension();
},
onchange: onchange,
Constants: {},
Errors: {},
};
function getDimensionFromWindow() {
if (typeof globalThis.innerWidth !== 'undefined') {
return {
innerWidth: globalThis.innerWidth,
innerHeight: globalThis.innerHeight,
outerWidth: globalThis.outerWidth,
outerHeight: globalThis.outerHeight,
scale: globalThis.devicePixelRatio || 1
};
}
return FALLBACK_DIMENSION;
}
function getDimension() {
return getDimensionFromWindow();
}
function addListener(capture) {
currentDimension = getDimension();
if (typeof globalThis.addEventListener === 'function')
globalThis.addEventListener('resize', onResize, capture);
}
function removeListener(capture) {
currentDimension = null;
if (typeof globalThis.removeEventListener === 'function')
globalThis.removeEventListener('resize', onResize, capture);
}
function onResize() {
var dimension = getDimension();
if (currentDimension === null || dimension.innerWidth !== currentDimension.innerWidth || dimension.innerHeight !== currentDimension.innerHeight || dimension.outerWidth !== currentDimension.outerWidth || dimension.outerHeight !== currentDimension.outerHeight || dimension.scale !== currentDimension.scale) {
currentDimension = dimension;
notify(dimension);
}
}
function notify(dimension) {
for (var i = 0; i < ENTRIES.length; i++) {
var entry = ENTRIES[i];
entry.fn(dimension);
if (entry.once)
removeEntry(entry);
}
}
function removeEntry(entry) {
var index = indexOfEntry(entry);
if (index !== -1)
ENTRIES.splice(index, 1);
if (ENTRIES.length === 0)
removeListener(entry.capture);
}
function indexOfEntry(entry) {
for (var i = 0; i < ENTRIES.length; i++)
if (ENTRIES[i].fn === entry.fn && ENTRIES[i].capture === entry.capture)
return i;
return -1;
}
function onchange(listener, options) {
if (options === void 0) { options = false; }
var entry = { fn: listener, capture: false, once: false };
if (typeof options === 'boolean')
options = { capture: options };
if (typeof options.capture !== 'undefined')
entry.capture = options.capture;
if (typeof options.once !== 'undefined')
entry.once = options.once;
if (typeof options.signal !== 'undefined')
entry.signal = options.signal;
var index = indexOfEntry(entry);
if (index === -1) {
ENTRIES.push(entry);
if (ENTRIES.length === 1)
addListener(entry.capture);
}
else if (ENTRIES[index].once && !entry.once) {
ENTRIES[index].once = false;
}
var cleanup = function () {
if (typeof entry.signal !== 'undefined')
entry.signal.removeEventListener('abort', cleanup);
removeEntry(entry);
};
if (typeof entry.signal !== 'undefined') {
if (entry.signal.aborted)
removeEntry(entry);
else
entry.signal.addEventListener('abort', cleanup);
}
return function () {
removeEntry(entry);
};
}
module.exports = Dimension;