mirror of
https://github.com/netbymatt/ws4kp.git
synced 2026-11-28 18:28:04 -08:00
320 lines
13 KiB
JavaScript
320 lines
13 KiB
JavaScript
import settings from '../settings.mjs';
|
|
import { debugFlag } from './debug.mjs';
|
|
import applyScanlineScaling from './scanlines.mjs';
|
|
|
|
document.addEventListener('DOMContentLoaded', () => init());
|
|
|
|
// Define property groups for different scaling modes
|
|
const SCALING_PROPERTIES = {
|
|
wrapper: ['width', 'height', 'transform', 'transform-origin'],
|
|
positioning: ['transform', 'transform-origin', 'width', 'height', 'position', 'left', 'top', 'margin-left', 'margin-top'],
|
|
};
|
|
|
|
// Track the last applied scale to avoid redundant operations
|
|
let lastAppliedScale = null;
|
|
let lastAppliedKioskMode = null;
|
|
// the scale actually applied to the display, used by the scan lines and reported in the headend
|
|
let appliedScale = 1;
|
|
|
|
// Helper function to detect iOS (using technique from nosleep.js)
|
|
const isIOS = () => {
|
|
const { userAgent } = navigator;
|
|
const iOSRegex = /CPU.*OS ([0-9_]{1,})[0-9_]{0,}|(CPU like).*AppleWebKit.*Mobile/i;
|
|
return iOSRegex.test(userAgent) && !window.MSStream;
|
|
};
|
|
|
|
// Helper function to clear CSS properties from elements
|
|
const clearElementStyles = (element, properties) => {
|
|
properties.forEach((prop) => element.style.removeProperty(prop));
|
|
};
|
|
|
|
// set up spacing and scales
|
|
const scaling = () => {
|
|
// available space
|
|
const BASE_SIZE = {
|
|
width: 640,
|
|
height: 480,
|
|
};
|
|
|
|
if (settings.wide?.value) {
|
|
BASE_SIZE.width = 640 + 107 + 107;
|
|
}
|
|
|
|
if (settings.portrait?.value) {
|
|
BASE_SIZE.height = 1137;
|
|
}
|
|
return {
|
|
BASE_SIZE,
|
|
};
|
|
};
|
|
|
|
const init = () => {
|
|
// set up the resize handler with debounce logic to prevent rapid-fire calls
|
|
let resizeTimeout;
|
|
|
|
// fired by settings.mjs when scan lines are switched on or their style changes
|
|
window.addEventListener('scanlines-change', () => applyScanlineScaling(appliedScale));
|
|
|
|
// Handle fullscreen change events and trigger an immediate resize calculation
|
|
const fullscreenEvents = ['fullscreenchange', 'webkitfullscreenchange', 'mozfullscreenchange', 'MSFullscreenChange'];
|
|
fullscreenEvents.forEach((eventName) => {
|
|
document.addEventListener(eventName, () => {
|
|
if (debugFlag('fullscreen')) {
|
|
console.log(`🖥️ ${eventName} event fired. fullscreenElement=${!!document.fullscreenElement}`);
|
|
}
|
|
resize(true);
|
|
});
|
|
});
|
|
|
|
// De-bounced resize handler to prevent rapid-fire resize calls
|
|
window.addEventListener('resize', () => {
|
|
clearTimeout(resizeTimeout);
|
|
resizeTimeout = setTimeout(() => resize(), 100);
|
|
});
|
|
|
|
// Handle orientation changes (Mobile Safari doesn't always fire resize events on orientation change)
|
|
window.addEventListener('orientationchange', () => {
|
|
if (debugFlag('resize')) {
|
|
console.log('📱 Orientation change detected, forcing resize after short delay');
|
|
}
|
|
clearTimeout(resizeTimeout);
|
|
// Use a slightly longer delay for orientation changes to allow the browser to settle
|
|
resizeTimeout = setTimeout(() => resize(true), 200);
|
|
});
|
|
|
|
resize();
|
|
};
|
|
|
|
// resize the container on a page resize
|
|
const resize = (force = false) => {
|
|
// Ignore resize events caused by pinch-to-zoom on mobile
|
|
if (window.visualViewport && Math.abs(window.visualViewport.scale - 1) > 0.01) {
|
|
return;
|
|
}
|
|
|
|
// get the base size
|
|
const { BASE_SIZE } = scaling();
|
|
|
|
const isFullscreen = !!document.fullscreenElement;
|
|
const isKioskMode = settings.kiosk?.value || false;
|
|
const isMobileSafariKiosk = isIOS() && isKioskMode; // Detect Mobile Safari in kiosk mode (regardless of standalone status)
|
|
const targetWidth = BASE_SIZE.width;
|
|
|
|
// Use centering behavior for fullscreen, kiosk mode, or Mobile Safari kiosk mode
|
|
const isKioskLike = isFullscreen || isKioskMode || isMobileSafariKiosk;
|
|
|
|
// Use the page's visible area instead of the bottom container width to avoid zero-dimension issues
|
|
// clientWidth/clientHeight leave out the page scrollbars, which innerWidth/innerHeight include
|
|
// on the normal page the body's width also leaves out the gutter kept by scrollbar-gutter: stable,
|
|
// which the root's clientWidth still counts while no scrollbar is showing (kiosk and fullscreen have no gutter)
|
|
const viewWidth = isKioskLike ? document.documentElement.clientWidth : document.body.clientWidth;
|
|
const widthZoomPercent = viewWidth / targetWidth;
|
|
const heightZoomPercent = document.documentElement.clientHeight / BASE_SIZE.height;
|
|
|
|
// Standard scaling: fit within both dimensions
|
|
const scale = Math.min(widthZoomPercent, heightZoomPercent);
|
|
|
|
if (debugFlag('resize') || debugFlag('fullscreen')) {
|
|
console.log(`🖥️ Resize: force=${force} isKioskLike=${isKioskLike} window=${window.innerWidth}x${window.innerHeight} targetWidth=${targetWidth} widthZoom=${widthZoomPercent.toFixed(3)} heightZoom=${heightZoomPercent.toFixed(3)} finalScale=${scale.toFixed(3)} fullscreenElement=${!!document.fullscreenElement} isIOS=${isIOS()} standalone=${window.navigator.standalone} isMobileSafariKiosk=${isMobileSafariKiosk} kioskMode=${settings.kiosk?.value} wideMode=${settings.wide.value}`);
|
|
}
|
|
|
|
// Prevent zero or negative scale values
|
|
if (scale <= 0) {
|
|
console.warn('Invalid scale calculated, skipping resize');
|
|
return;
|
|
}
|
|
|
|
// Skip redundant resize operations if scale and mode haven't changed (unless forced)
|
|
const scaleChanged = Math.abs((lastAppliedScale || 0) - scale) > 0.001;
|
|
const modeChanged = lastAppliedKioskMode !== isKioskLike;
|
|
|
|
if (!force && !scaleChanged && !modeChanged) {
|
|
return; // No meaningful change, skip resize operation
|
|
}
|
|
|
|
// Update tracking variables
|
|
lastAppliedScale = scale;
|
|
lastAppliedKioskMode = isKioskLike;
|
|
// the scale actually applied to the display, for the scan lines and the headend (the branch below that doesn't scale sets 1)
|
|
appliedScale = scale;
|
|
|
|
const wrapper = document.querySelector('#divTwc');
|
|
const mainContainer = document.querySelector('#divTwcMain');
|
|
|
|
// BASELINE: content fits naturally, no scaling needed
|
|
if (!isKioskLike && scale >= 1.0 && !isKioskMode) {
|
|
if (debugFlag('fullscreen')) {
|
|
console.log('🖥️ Resetting fullscreen/kiosk styles to normal');
|
|
}
|
|
|
|
// Reset all scaling-related styles
|
|
const container = document.querySelector('#container');
|
|
clearElementStyles(wrapper, SCALING_PROPERTIES.wrapper);
|
|
clearElementStyles(container, SCALING_PROPERTIES.positioning);
|
|
clearElementStyles(mainContainer, SCALING_PROPERTIES.positioning);
|
|
|
|
// no scaling is applied here, so the scan lines and the headend use 1x
|
|
appliedScale = 1.0;
|
|
applyScanlineScaling(1.0);
|
|
return;
|
|
}
|
|
|
|
// MOBILE SCALING: Use wrapper scaling for mobile devices (but not when in fullscreen/kiosk mode)
|
|
if ((scale < 1.0 || (isKioskMode && !isKioskLike)) && !isMobileSafariKiosk && !isKioskLike) {
|
|
/*
|
|
* MOBILE SCALING (Wrapper Scaling)
|
|
*
|
|
* This path is used for regular mobile browsing (NOT fullscreen/kiosk modes).
|
|
* Why scale the wrapper instead of mainContainer?
|
|
* - For mobile devices where content is larger than viewport, we need to scale the entire layout
|
|
* - The wrapper (#divTwc) contains both the main content AND the bottom navigation bar
|
|
* - Scaling the wrapper ensures both elements are scaled together as a unit
|
|
* - Content aligns to top-left for typical mobile web browsing behavior (no centering)
|
|
* - Uses explicit dimensions to prevent layout issues and eliminate gaps after scaling
|
|
*/
|
|
|
|
// Reset any container/mainContainer styles that might have been set during fullscreen/kiosk mode
|
|
const container = document.querySelector('#container');
|
|
clearElementStyles(container, SCALING_PROPERTIES.positioning);
|
|
clearElementStyles(mainContainer, SCALING_PROPERTIES.positioning);
|
|
|
|
wrapper.style.setProperty('transform', `scale(${scale})`);
|
|
wrapper.style.setProperty('transform-origin', 'top left'); // Scale from top-left corner
|
|
|
|
// Set explicit dimensions to prevent layout issues on mobile
|
|
const wrapperWidth = BASE_SIZE.width;
|
|
// Calculate total height: main content (480px) + bottom navigation bar
|
|
const bottomBar = document.querySelector('#divTwcBottom');
|
|
const bottomBarHeight = bottomBar ? bottomBar.offsetHeight : 40; // fallback to ~40px
|
|
const totalHeight = BASE_SIZE.height + bottomBarHeight;
|
|
const scaledHeight = totalHeight * scale; // Height after scaling
|
|
|
|
wrapper.style.setProperty('width', `${wrapperWidth}px`);
|
|
wrapper.style.setProperty('height', `${scaledHeight}px`); // Use scaled height to eliminate gap under #divTwc on index page
|
|
applyScanlineScaling(scale);
|
|
return;
|
|
}
|
|
|
|
// KIOSK/FULLSCREEN SCALING: Two different positioning approaches for different platforms
|
|
const wrapperWidth = BASE_SIZE.width;
|
|
const wrapperHeight = BASE_SIZE.height;
|
|
|
|
// Reset wrapper styles to avoid double scaling (wrapper remains unstyled)
|
|
clearElementStyles(wrapper, SCALING_PROPERTIES.wrapper);
|
|
|
|
// Platform-specific positioning logic
|
|
let transformOrigin;
|
|
let leftPosition;
|
|
let topPosition;
|
|
let marginLeft;
|
|
let marginTop;
|
|
|
|
if (isMobileSafariKiosk) {
|
|
/*
|
|
* MOBILE SAFARI KIOSK MODE (Manual offset calculation)
|
|
*
|
|
* Why this approach?
|
|
* - Mobile Safari in kiosk mode has unique viewport behaviors that don't work well with standard CSS centering
|
|
* - We want orientation-specific centering: vertical in portrait, horizontal in landscape
|
|
* - The standard CSS centering method can cause layout issues in Mobile Safari's constrained environment
|
|
*/
|
|
const scaledWidth = wrapperWidth * scale;
|
|
const scaledHeight = wrapperHeight * scale;
|
|
|
|
// Determine if we're in portrait or landscape
|
|
const isPortrait = window.innerHeight > window.innerWidth;
|
|
|
|
let offsetX = 0;
|
|
let offsetY = 0;
|
|
|
|
if (isPortrait) {
|
|
offsetY = (window.innerHeight - scaledHeight) / 2; // center vertically, align to left edge
|
|
} else {
|
|
offsetX = (window.innerWidth - scaledWidth) / 2; // center horizontally, align to top edge
|
|
}
|
|
|
|
if (debugFlag('fullscreen')) {
|
|
console.log(`📱 Mobile Safari kiosk centering: ${isPortrait ? 'portrait' : 'landscape'} wrapper=${wrapperWidth}x${wrapperHeight} scale=${scale.toFixed(3)} offset=${offsetX.toFixed(1)},${offsetY.toFixed(1)}`);
|
|
}
|
|
|
|
// Set positioning values for manual offset calculation
|
|
transformOrigin = 'top left'; // Scale from top-left corner
|
|
leftPosition = `${offsetX}px`; // Exact pixel positioning
|
|
topPosition = `${offsetY}px`; // Exact pixel positioning
|
|
marginLeft = null; // Clear any previous centering margins
|
|
marginTop = null; // Clear any previous centering margins
|
|
} else {
|
|
/*
|
|
* STANDARD FULLSCREEN/KIOSK MODE (CSS-based Centering)
|
|
*
|
|
* Why this approach?
|
|
* - Should work reliably across all other browsers and scenarios (desktop, non-Safari mobile, etc.)
|
|
* - Uses standard CSS centering techniques that browsers handle efficiently
|
|
* - Always centers both horizontally and vertically
|
|
*/
|
|
const scaledWidth = wrapperWidth * scale;
|
|
const scaledHeight = wrapperHeight * scale;
|
|
const offsetX = (document.documentElement.clientWidth - scaledWidth) / 2;
|
|
const offsetY = (document.documentElement.clientHeight - scaledHeight) / 2;
|
|
|
|
if (debugFlag('fullscreen')) {
|
|
console.log(`🖥️ Applying fullscreen/kiosk scaling: wrapper=${wrapperWidth}x${wrapperHeight} scale=${scale.toFixed(3)} offset=${offsetX.toFixed(1)},${offsetY.toFixed(1)} target=${isFullscreen ? '#container' : '#divTwcMain'}`);
|
|
}
|
|
|
|
// Set positioning values for CSS-based centering
|
|
transformOrigin = 'center center'; // Scale from center point
|
|
leftPosition = '50%'; // Position at 50% from left
|
|
topPosition = '50%'; // Position at 50% from top
|
|
marginLeft = `-${wrapperWidth / 2}px`; // Pull back by half width
|
|
marginTop = `-${wrapperHeight / 2}px`; // Pull back by half height
|
|
}
|
|
|
|
// Chrome fullscreen compatibility: apply transform to #container instead of #divTwcMain
|
|
// This works around Chrome's restriction on styling fullscreen elements directly
|
|
const container = document.querySelector('#container');
|
|
const targetElement = isFullscreen ? container : mainContainer;
|
|
|
|
// Reset the other element's styles to avoid conflicts
|
|
if (isFullscreen) {
|
|
// Reset mainContainer styles when using container for fullscreen
|
|
clearElementStyles(mainContainer, SCALING_PROPERTIES.positioning);
|
|
} else {
|
|
// Reset container styles when using mainContainer for kiosk mode
|
|
clearElementStyles(container, SCALING_PROPERTIES.positioning);
|
|
}
|
|
|
|
// Apply shared properties to the target element
|
|
targetElement.style.setProperty('transform', `scale(${scale})`, 'important');
|
|
targetElement.style.setProperty('transform-origin', transformOrigin, 'important');
|
|
// the width of the target element does not change it is the fixed width of the 4:3 display which is then scaled
|
|
// the wrapper adds margins and padding to achieve widescreen
|
|
// targetElement.style.setProperty('width', `${wrapperWidth}px`, 'important');
|
|
targetElement.style.setProperty('height', `${wrapperHeight}px`, 'important');
|
|
targetElement.style.setProperty('position', 'absolute', 'important');
|
|
targetElement.style.setProperty('left', leftPosition, 'important');
|
|
targetElement.style.setProperty('top', topPosition, 'important');
|
|
|
|
// Apply or clear margin properties based on positioning method
|
|
if (marginLeft !== null) {
|
|
targetElement.style.setProperty('margin-left', marginLeft, 'important');
|
|
} else {
|
|
targetElement.style.removeProperty('margin-left');
|
|
}
|
|
if (marginTop !== null) {
|
|
targetElement.style.setProperty('margin-top', marginTop, 'important');
|
|
} else {
|
|
targetElement.style.removeProperty('margin-top');
|
|
}
|
|
|
|
applyScanlineScaling(scale);
|
|
};
|
|
|
|
const displayScale = () => appliedScale;
|
|
|
|
export {
|
|
scaling,
|
|
resize,
|
|
isIOS,
|
|
displayScale,
|
|
};
|