refac: 500px 모드 변환기 분리

This commit is contained in:
2021-12-04 11:42:26 +09:00
parent de854cc02c
commit fbd0561420
3 changed files with 73 additions and 50 deletions
+55
View File
@@ -0,0 +1,55 @@
import { htmlReady } from "./htmlReady";
import { unwrap } from "./unwrap";
export function auto500px(targetHeight = 700): void {
let deviceWidth = -1;
let viewportMeta!: HTMLMetaElement;
function init() {
let _viewPortMeta = document.querySelector<HTMLMetaElement>("meta[name=viewport]");
if (_viewPortMeta) {
viewportMeta = _viewPortMeta;
return;
}
const htmlTag = unwrap(document.querySelector("head"));
_viewPortMeta = document.createElement("meta");
_viewPortMeta.name = 'viewport';
_viewPortMeta.content = 'width=500, initial-scale=1';
htmlTag.appendChild(_viewPortMeta);
viewportMeta = _viewPortMeta;
}
function adjustViewportWidth() {
if (deviceWidth == window.screen.availWidth) {
return;
}
deviceWidth = window.screen.availWidth;
const innerHeight = window.innerHeight;
const selectorHeight = targetHeight;
if (deviceWidth < 500) {
viewportMeta.content = 'width=500, initial-scale=1';
return;
}
if (innerHeight < selectorHeight) {
const maybeNextWidth = deviceWidth / innerHeight * selectorHeight;
if (maybeNextWidth >= 750) {
viewportMeta.content = 'width=1000, initial-scale=1';
}
else {
viewportMeta.content = `height=${Math.ceil(selectorHeight)}, initial-scale=1`;
}
return;
}
}
htmlReady(() => {
init();
adjustViewportWidth();
window.addEventListener('scroll', adjustViewportWidth, true);
window.addEventListener('orientationchange', adjustViewportWidth, true);
});
}
+7
View File
@@ -0,0 +1,7 @@
export function htmlReady(fn: () => unknown): void {
if (document.readyState != 'loading') {
fn();
} else {
document.addEventListener('DOMContentLoaded', fn);
}
}