Another (better) way of updating safe area insets

Hopefully this works
pull/228/head
Lim Chee Aun 2023-09-09 14:10:52 +08:00
rodzic 5147efd123
commit 8018d06cdf
1 zmienionych plików z 21 dodań i 17 usunięć

Wyświetl plik

@ -1,31 +1,35 @@
import mem from 'mem';
const root = document.documentElement;
const style = getComputedStyle(root);
const defaultBoundingBoxPadding = 8;
function _safeBoundingBoxPadding(paddings = []) {
// paddings = [top, right, bottom, left]
let safeAreaInsets = [0, 0, 0, 0];
function getSafeAreaInsets() {
// Get safe area inset variables from root
const safeAreaInsetTop = style.getPropertyValue('--sai-top');
const safeAreaInsetRight = style.getPropertyValue('--sai-right');
const safeAreaInsetBottom = style.getPropertyValue('--sai-bottom');
const safeAreaInsetLeft = style.getPropertyValue('--sai-left');
const str = [
safeAreaInsetTop,
safeAreaInsetRight,
safeAreaInsetBottom,
safeAreaInsetLeft,
]
.map(
(v, i) =>
(parseInt(v, 10) || defaultBoundingBoxPadding) + (paddings[i] || 0),
)
safeAreaInsets = [
// top, right, bottom, left (clockwise)
Math.max(0, parseInt(safeAreaInsetTop, 10)),
Math.max(0, parseInt(safeAreaInsetRight, 10)),
Math.max(0, parseInt(safeAreaInsetBottom, 10)),
Math.max(0, parseInt(safeAreaInsetLeft, 10)),
];
}
requestAnimationFrame(getSafeAreaInsets);
function safeBoundingBoxPadding(paddings = []) {
const str = safeAreaInsets
.map((v, i) => (v || defaultBoundingBoxPadding) + (paddings[i] || 0))
.join(' ');
// console.log(str);
return str;
}
const safeBoundingBoxPadding = mem(_safeBoundingBoxPadding, {
maxAge: 10000, // 10 seconds
});
// Update safe area insets when orientation or resize
if (CSS.supports('top: env(safe-area-inset-top)')) {
window.addEventListener('resize', getSafeAreaInsets, { passive: true });
}
export default safeBoundingBoxPadding;