1
0
Fork 0

Another (better) way of updating safe area insets

Hopefully this works
This commit is contained in:
Lim Chee Aun 2023-09-09 14:10:52 +08:00
parent 5147efd123
commit 8018d06cdf

View file

@ -1,31 +1,35 @@
import mem from 'mem';
const root = document.documentElement; const root = document.documentElement;
const style = getComputedStyle(root); const style = getComputedStyle(root);
const defaultBoundingBoxPadding = 8; 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 // Get safe area inset variables from root
const safeAreaInsetTop = style.getPropertyValue('--sai-top'); const safeAreaInsetTop = style.getPropertyValue('--sai-top');
const safeAreaInsetRight = style.getPropertyValue('--sai-right'); const safeAreaInsetRight = style.getPropertyValue('--sai-right');
const safeAreaInsetBottom = style.getPropertyValue('--sai-bottom'); const safeAreaInsetBottom = style.getPropertyValue('--sai-bottom');
const safeAreaInsetLeft = style.getPropertyValue('--sai-left'); const safeAreaInsetLeft = style.getPropertyValue('--sai-left');
const str = [ safeAreaInsets = [
safeAreaInsetTop, // top, right, bottom, left (clockwise)
safeAreaInsetRight, Math.max(0, parseInt(safeAreaInsetTop, 10)),
safeAreaInsetBottom, Math.max(0, parseInt(safeAreaInsetRight, 10)),
safeAreaInsetLeft, Math.max(0, parseInt(safeAreaInsetBottom, 10)),
] Math.max(0, parseInt(safeAreaInsetLeft, 10)),
.map( ];
(v, i) => }
(parseInt(v, 10) || defaultBoundingBoxPadding) + (paddings[i] || 0), requestAnimationFrame(getSafeAreaInsets);
)
function safeBoundingBoxPadding(paddings = []) {
const str = safeAreaInsets
.map((v, i) => (v || defaultBoundingBoxPadding) + (paddings[i] || 0))
.join(' '); .join(' ');
// console.log(str); // console.log(str);
return 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; export default safeBoundingBoxPadding;