Settings: fix safe area insets emulation

This commit is contained in:
thislight 2024-11-10 21:23:03 +08:00
parent 7e698ebe4c
commit 34dd95e959
No known key found for this signature in database
GPG key ID: FCFE5192241CCD4E

View file

@ -98,7 +98,14 @@ const safeAreaInsets: Record<string, SafeAreaInsets> = {
let screenOrientationCallback: (() => void) | undefined;
function removeSafeAreaEmulation(root: HTMLElement) {
for (const name of ["top", "right", "bottom", "left"]) {
root.style.removeProperty(`--safe-area-inset-${name}`);
}
}
function applySafeAreaEmulation(root: HTMLElement, insets: Inset) {
removeSafeAreaEmulation(root);
for (const key of Object.keys(insets) as (keyof Inset)[]) {
const value = insets[key];
if (!value || value === 0) continue;
@ -109,19 +116,22 @@ function applySafeAreaEmulation(root: HTMLElement, insets: Inset) {
function setupSafeAreaEmulation(name: string) {
const insets = safeAreaInsets[name];
const root = document.querySelector(":root")! as HTMLElement;
if (!insets) {
if (screenOrientationCallback) {
window.screen.orientation.removeEventListener(
"change",
screenOrientationCallback,
);
screenOrientationCallback = undefined;
}
for (const name of ["top", "right", "bottom", "left"]) {
root.style.removeProperty(`--safe-area-inset-${name}`);
}
} else {
if (screenOrientationCallback) {
window.screen.orientation.removeEventListener(
"change",
screenOrientationCallback,
);
screenOrientationCallback = undefined;
}
removeSafeAreaEmulation(root);
if (insets) {
screenOrientationCallback = () => {
console.debug(
`safe area emulation target: ${window.screen.orientation.type}`,
);
if (window.screen.orientation.type === "portrait-primary") {
console.debug("safe area emulation: protrait");
applySafeAreaEmulation(root, insets.protrait);
@ -138,6 +148,16 @@ function setupSafeAreaEmulation(name: string) {
}
}
if (import.meta.hot) {
import.meta.hot.accept((mod) => {
if (!mod) return;
if (screenOrientationCallback) {
mod["screenOrientationCallback"] = screenOrientationCallback;
setTimeout(screenOrientationCallback, 0);
}
});
}
type Strings = {
["lang.auto"]: Template<{ detected: string }>;
} & Record<string, string | undefined>;