/**
* LoadingScreen - Manual loading overlay for Three.js examples
* Options:
* - blockInput: boolean (default: true) - Blocks click/keyboard events during loading
* - silent: boolean (default: false) - Tracks loading without rendering the overlay
* - onComplete: function - Called once when all loading work is complete
*
* Usage:
* const loader = new LoadingScreen();
* loader.setItems(['HDR Environment', 'Model', 'Textures']); // Register items upfront
* loader.init(container);
*
* // Load assets
* const hdr = await loader.load('HDR Environment', async (onProgress) => {
* return new Promise((resolve, reject) => {
* hdrLoader.load(url, resolve, onProgress, reject);
* });
* });
*
* loader.complete();
*/
export class LoadingScreen {
constructor( options = {} ) {
this.container = null;
this.overlay = null;
this.silent = options.silent ?? false;
this.onComplete = options.onComplete ?? ( () => {} );
// Track loading state
this.items = new Map();
this.totalWeight = 0;
this.isComplete = false;
// Input blocking
this.blockInput = options.blockInput ?? true;
this.blockedEvents = [ 'click', 'mousedown', 'mouseup', 'keydown', 'keyup', 'keypress', 'touchstart', 'touchend' ];
this.blockHandler = this.blockHandler.bind( this );
}
/**
* Register items to load upfront with optional weights
* This ensures progress goes smoothly from 0-100
*
* @param {Array<string|{name: string, weight: number}>} items
*/
setItems( items ) {
this.items.clear();
this.totalWeight = 0;
items.forEach( item => {
if ( typeof item === 'string' ) {
this.items.set( item, { progress: 0, weight: 1, loaded: false } );
this.totalWeight += 1;
} else {
const weight = item.weight ?? 1;
this.items.set( item.name, { progress: 0, weight, loaded: false } );
this.totalWeight += weight;
}
} );
}
/**
* Block input events during loading
*/
blockHandler( event ) {
event.preventDefault();
event.stopPropagation();
}
/**
* Enable input blocking
*/
enableInputBlocking() {
if ( ! this.blockInput ) return;
this.blockedEvents.forEach( eventType => {
document.addEventListener( eventType, this.blockHandler, { capture: true, passive: false } );
} );
}
/**
* Disable input blocking
*/
disableInputBlocking() {
this.blockedEvents.forEach( eventType => {
document.removeEventListener( eventType, this.blockHandler, { capture: true } );
} );
}
/**
* Initialize and attach to container
*/
init( container ) {
this.container = container;
if ( this.items.size === 0 ) return;
this.container.dataset.exampleLoading = 'pending';
if ( this.silent ) return;
this.createUI();
this.enableInputBlocking();
}
/**
* Create the minimal loading indicator
*/
createUI() {
const overlay = document.createElement( 'div' );
overlay.id = 'loading-screen';
overlay.setAttribute( 'role', 'status' );
overlay.setAttribute( 'aria-label', 'Loading assets' );
overlay.style.cssText = `
position: fixed;
inset: 0;
display: flex;
justify-content: center;
align-items: center;
z-index: 10000;
`;
const spinner = document.createElement( 'div' );
spinner.style.cssText = `
width: 28px;
height: 28px;
border: 2px solid rgba(255, 255, 255, 0.2);
border-top-color: #6b8afd;
border-radius: 50%;
filter: drop-shadow(0 0 8px rgba(107, 138, 253, 0.28));
`;
if ( ! window.matchMedia( '(prefers-reduced-motion: reduce)' ).matches ) {
spinner.animate(
[ { transform: 'rotate(0deg)' }, { transform: 'rotate(360deg)' } ],
{ duration: 800, iterations: Infinity }
);
}
overlay.appendChild( spinner );
this.container.appendChild( overlay );
this.overlay = overlay;
}
/**
* Update progress for a specific item (0-1)
*/
updateItem( name, progress ) {
if ( this.items.has( name ) ) {
const item = this.items.get( name );
item.progress = Math.min( 1, Math.max( 0, progress ) );
}
}
/**
* Mark an item as fully loaded
*/
itemLoaded( name ) {
if ( this.items.has( name ) ) {
const item = this.items.get( name );
item.progress = 1;
item.loaded = true;
}
}
/**
* Update status text
*/
updateStatus( text ) {
if ( this.overlay ) this.overlay.setAttribute( 'aria-label', `Loading ${text}` );
}
/**
* Create a progress callback for THREE loaders
*/
createProgressCallback( itemName ) {
return ( event ) => {
if ( event.lengthComputable ) {
const progress = event.loaded / event.total;
this.updateItem( itemName, progress );
}
};
}
/**
* Wrap a loader promise with progress tracking
*/
async load( itemName, loadFunction ) {
// Add item if not already registered
if ( ! this.items.has( itemName ) ) {
this.items.set( itemName, { progress: 0, weight: 1, loaded: false } );
this.totalWeight += 1;
}
this.updateStatus( itemName );
try {
const result = await loadFunction( this.createProgressCallback( itemName ) );
this.itemLoaded( itemName );
return result;
} catch ( error ) {
console.error( `LoadingScreen: Failed to load ${itemName}:`, error );
this.itemLoaded( itemName ); // Mark as "loaded" to not block progress
throw error;
}
}
/**
* Mark loading as complete and hide the overlay
*/
complete() {
if ( this.isComplete ) return;
this.isComplete = true;
this.disableInputBlocking();
if ( this.container ) this.container.dataset.exampleLoading = 'complete';
this.onComplete();
this.container?.dispatchEvent( new CustomEvent( 'example-loading-complete', {
bubbles: true,
} ) );
if ( ! this.overlay ) return;
this.overlay.remove();
this.overlay = null;
}
}