EraScrubber.tsx eras.css eras.ts PhoneFrame.tsx phone-frame.css motion.ts spring.ts geometry.ts
copy "use client" ;
import { useCallback , useEffect , useMemo , useRef , useState , type KeyboardEvent } from "react" ;
import { useMediaQuery , useReducedMotion } from "./motion" ;
import { settled , step as stepSpring , type SpringState } from "./spring" ;
import PhoneFrame from "./PhoneFrame" ;
import { dissolve , layout , nearest , sigmaFor , spans , stopT , swell , type Era } from "./eras" ;
import "./eras.css" ;
interface Props {
eras : Era [];
blur ?: number ;
onStep ?: ( index : number ) => void ;
}
const shot = ( era : Era , device : "desktop" | "phone" , scheme : "light" | "dark" ): string => {
const s = era [ device ];
return ( scheme === "dark" && ! era . lightOnly && s . dark ) || s . light ;
};
const PHONE_BELOW = 560 ;
const LABEL_ROOM = 58 ;
const FOLLOW = { stiffness : 900 , damping : 60 };
const SETTLE = { stiffness : 320 , damping : 30 };
const SWEEP_STEP = 420 ;
const LEAN = 0.035 ;
const SHOT_FADE = 300 ;
const INK_LIGHT = [ 23 , 23 , 23 ];
const INK_DARK = [ 245 , 245 , 247 ];
function topColour ( img : HTMLImageElement ): number [] | null {
try {
const canvas = document . createElement ( "canvas" );
canvas . width = 8 ;
canvas . height = 1 ;
const ctx = canvas . getContext ( "2d" , { willReadFrequently : true });
if (! ctx || ! img . naturalWidth ) return null ;
ctx . drawImage ( img , img . naturalWidth * 0.4 , 10 , img . naturalWidth * 0.2 , 2 , 0 , 0 , 8 , 1 );
const d = ctx . getImageData ( 0 , 0 , 8 , 1 ). data ;
const sum = [ 0 , 0 , 0 ];
for ( let i = 0 ; i < d . length ; i += 4 ) {
sum [ 0 ] += d [ i ];
sum [ 1 ] += d [ i + 1 ];
sum [ 2 ] += d [ i + 2 ];
}
return sum . map (( v ) => v / 8 );
} catch {
return null ;
}
}
const mix = ( a : number [], b : number [], t : number ) => a . map (( v , i ) => Math . round ( v + ( b [ i ] - v ) * t ));
const inkFor = ( c : number []) => ( 0.2126 * c [ 0 ] + 0.7152 * c [ 1 ] + 0.0722 * c [ 2 ] > 140 ? INK_LIGHT : INK_DARK );
export default function EraScrubber ({ eras , blur = 10 , onStep }: Props ) {
const marks = useMemo (() => layout ( eras ), [ eras ]);
const runs = useMemo (() => spans ( eras ), [ eras ]);
const end = eras . length - 1 ;
const onStepRef = useRef ( onStep );
onStepRef . current = onStep ;
const reduced = useReducedMotion ();
const dark = useMediaQuery ( "(prefers-color-scheme: dark)" );
const scheme = dark ? "dark" : "light" ;
const [ active , setActive ] = useState ( 0 );
const [ stage , setStage ] = useState ( 0 );
const [ track , setTrack ] = useState ( 0 );
const root = useRef < HTMLDivElement >( null );
const rail = useRef < HTMLDivElement >( null );
const head = useRef < HTMLSpanElement >( null );
const ticks = useRef <( HTMLSpanElement | null )[]>([]);
const imgs = useRef <( HTMLImageElement | null )[]>([]);
const spring = useRef < SpringState >({ x : 0 , v : 0 });
const target = useRef ( 0 );
const config = useRef ( SETTLE );
const frame = useRef ( 0 );
const last = useRef ( 0 );
const dragging = useRef ( false );
const current = useRef ( 0 );
const touched = useRef ( false );
const sweep = useRef ( 0 );
const loaded = useRef ( new Map < string , number >());
const grounds = useRef ( new Map < string , number []>());
const fading = useRef ( 0 );
const device = stage > 0 && stage < PHONE_BELOW ? "phone" : "desktop" ;
const compact = track > 0 && track / end < LABEL_ROOM ;
useEffect (() => {
const el = root . current ;
const r = rail . current ;
if (! el || ! r ) return ;
const observer = new ResizeObserver (() => {
setStage ( el . clientWidth );
setTrack ( r . clientWidth );
});
observer . observe ( el );
observer . observe ( r );
return () => observer . disconnect ();
}, []);
useEffect (() => {
if (! stage ) return ;
for ( const era of eras ) {
const url = shot ( era , device , scheme );
if (! url ) continue ;
const img = new Image ();
img . src = url ;
img . decode (). catch (() => {});
}
}, [ device , scheme , stage ]);
const draw = useCallback (() => {
const width = rail . current ?. clientWidth ?? 0 ;
if (! width ) return ;
const x = spring . current . x * width ;
if ( head . current ) head . current . style . transform = `translateX( ${ x } px)` ;
const sigma = sigmaFor ( width , eras . length );
marks . forEach (( tick , i ) => {
const el = ticks . current [ i ];
if ( el ) el . style . transform = `scaleY( ${ swell ( tick . t * width - x , sigma ). toFixed ( 3 ) } )` ;
});
const pos = spring . current . x * end ;
const blurPx = reduced ? 0 : blur ;
const lean = reduced ? 0 : LEAN ;
const now = performance . now ();
let pending = false ;
eras . forEach (( _ , i ) => {
const el = imgs . current [ i ];
if (! el ) return ;
const look = dissolve ( pos , i , blurPx , lean );
if (! look ) {
el . style . visibility = "hidden" ;
return ;
}
const at = loaded . current . get ( el . src );
const arrived = at === undefined ? 0 : reduced ? 1 : Math . min ( 1 , ( now - at ) / SHOT_FADE );
if ( at !== undefined && arrived < 1 ) pending = true ;
el . style . visibility = "visible" ;
el . style . opacity = ( look . opacity * arrived ). toFixed ( 3 );
el . style . filter = look . blur > 0.05 ? `blur( ${ look . blur . toFixed ( 2 ) } px)` : "none" ;
el . style . transform = look . scale === 1 ? "none" : `scale( ${ look . scale . toFixed ( 4 ) } )` ;
el . style . zIndex = String ( i );
});
const screen = root . current ?. querySelector < HTMLElement >( ".pf-screen" );
if ( screen ) {
const from = Math . min ( end , Math . floor ( pos ));
const to = Math . min ( end , from + 1 );
const a = grounds . current . get ( imgs . current [ from ]?. src ?? "" );
const b = grounds . current . get ( imgs . current [ to ]?. src ?? "" ) ?? a ;
if ( a && b ) {
const g = to === from ? 0 : ( dissolve ( pos , to , 0 , 0 )?. opacity ?? 0 );
screen . style . setProperty ( "--pf-ground" , `rgb( ${ mix ( a , b , g ). join ( " " ) } )` );
screen . style . color = `rgb( ${ mix ( inkFor ( a ), inkFor ( b ), g ). join ( " " ) } )` ;
} else {
screen . style . removeProperty ( "--pf-ground" );
screen . style . removeProperty ( "color" );
}
}
cancelAnimationFrame ( fading . current );
if ( pending ) fading . current = requestAnimationFrame (() => draw ());
const next = nearest ( spring . current . x , eras . length );
if ( next !== current . current ) {
current . current = next ;
setActive ( next );
if ( touched . current ) onStepRef . current ?.( next );
}
}, [ blur , reduced , marks , eras , end ]);
const run = useCallback (() => {
cancelAnimationFrame ( frame . current );
last . current = performance . now ();
const tick = ( now : number ) => {
const dt = now - last . current ;
last . current = now ;
if ( reduced && ! dragging . current ) {
spring . current = { x : target . current , v : 0 };
} else {
spring . current = stepSpring ( spring . current , target . current , dt , config . current );
}
draw ();
const width = rail . current ?. clientWidth || 1 ;
const px = { x : spring . current . x * width , v : spring . current . v * width };
if (! dragging . current && settled ( px , target . current * width )) {
spring . current = { x : target . current , v : 0 };
draw ();
return ;
}
frame . current = requestAnimationFrame ( tick );
};
frame . current = requestAnimationFrame ( tick );
}, [ draw , reduced ]);
const goTo = useCallback (
( index : number ) => {
target . current = stopT ( Math . min ( end , Math . max ( 0 , index )), eras . length );
config . current = SETTLE ;
run ();
},
[ run , eras . length , end ],
);
useEffect (() => {
draw ();
}, [ draw , track , device , scheme ]);
useEffect (
() => () => {
cancelAnimationFrame ( frame . current );
clearInterval ( sweep . current );
cancelAnimationFrame ( fading . current );
},
[],
);
useEffect (() => {
const el = root . current ;
if (! el ) return ;
const observer = new IntersectionObserver (
([ entry ]) => {
if (! entry ?. isIntersecting ) return ;
observer . disconnect ();
if ( touched . current ) return ;
if ( reduced ) {
goTo ( end );
return ;
}
let i = 0 ;
sweep . current = window . setInterval (() => {
i += 1 ;
if ( touched . current || i > end ) {
clearInterval ( sweep . current );
return ;
}
goTo ( i );
}, SWEEP_STEP );
},
{ threshold : 0.6 },
);
observer . observe ( el );
return () => observer . disconnect ();
}, [ goTo , reduced , end ]);
const take = () => {
touched . current = true ;
clearInterval ( sweep . current );
};
const at = ( clientX : number ) => {
const rect = rail . current ?. getBoundingClientRect ();
if (! rect || rect . width <= 0 ) return 0 ;
return Math . min ( 1 , Math . max ( 0 , ( clientX - rect . left ) / rect . width ));
};
const release = () => {
if (! dragging . current ) return ;
dragging . current = false ;
target . current = stopT ( nearest ( target . current , eras . length ), eras . length );
config . current = SETTLE ;
run ();
};
const onKeyDown = ( event : KeyboardEvent ) => {
const from = nearest ( target . current , eras . length );
let to : number | null = null ;
if ( event . key === "ArrowRight" || event . key === "ArrowUp" ) to = from + 1 ;
else if ( event . key === "ArrowLeft" || event . key === "ArrowDown" ) to = from - 1 ;
else if ( event . key === "Home" ) to = 0 ;
else if ( event . key === "End" ) to = end ;
else if ( / ^ [ 1-9 ] $ / . test ( event . key )) to = Number ( event . key ) - 1 ;
if ( to === null ) return ;
event . preventDefault ();
take ();
goTo ( to );
};
const era = eras [ active ]!;
const shots = useMemo (
() =>
eras . map (( e , i ) => (
< img
key ={ ` ${ e . id } - ${ device } - ${ scheme } ` }
ref ={( el ) => {
imgs . current [ i ] = el ;
}}
className = "er-shot"
src ={ shot ( e , device , scheme )}
alt ={ i === active ? `the home page, ${ e . spoken } ` : "" }
draggable ={ false }
decoding = "async"
onLoad ={( event ) => {
const img = event . currentTarget ;
loaded . current . set ( img . src , performance . now ());
if ( device === "phone" && ! grounds . current . has ( img . src )) {
const colour = topColour ( img );
if ( colour ) grounds . current . set ( img . src , colour );
}
draw ();
}}
/>
)),
[ active , device , scheme , draw , eras ],
);
return (
< div
className = "er-lab"
ref ={ root }
data-device ={ device }
data-tone ={ device === "phone" ? ( era . lightOnly ? "light" : scheme ) : undefined }
>
< div className = "er-view" >
{ device === "desktop" ? (
< div className = "er-window" >
< div className = "er-screen" >{ shots }</ div >
</ div >
) : (
< PhoneFrame width ={ 236 }>
< div className = "er-screen" >{ shots }</ div >
</ PhoneFrame >
)}
</ div >
< div
className = "er-axis"
role = "slider"
tabIndex ={ 0 }
aria-label = "site version"
aria-valuemin ={ 1 }
aria-valuemax ={ eras . length }
aria-valuenow ={ active + 1 }
aria-valuetext ={ era . spoken }
onKeyDown ={ onKeyDown }
onPointerDown ={( event ) => {
take ();
dragging . current = true ;
try {
event . currentTarget . setPointerCapture ( event . pointerId );
} catch {}
event . currentTarget . focus ({ focusVisible : false });
target . current = at ( event . clientX );
config . current = FOLLOW ;
run ();
}}
onPointerMove ={( event ) => {
if (! dragging . current ) return ;
target . current = at ( event . clientX );
}}
onPointerUp ={ release }
onPointerCancel ={ release }
onLostPointerCapture ={ release }
>
< div className = "er-rail" ref ={ rail }>
< div className = "er-versions" aria-hidden = "true" >
{ runs . map (({ version , first , last }) => (
< span
key ={ version }
className = "er-version"
data-on ={ era . version === version || undefined }
style ={{ left : ` ${ stopT ( first , eras . length ) * 100 } %` , width : ` ${ (( last - first ) / end ) * 100 } %` }}
>
{ version }
</ span >
))}
</ div >
< div className = "er-ticks" aria-hidden = "true" >
{ marks . map (( tick , i ) => (
< span
key ={ tick . t }
ref ={( el ) => {
ticks . current [ i ] = el ;
}}
className = "er-tick"
data-major ={ tick . stop >= 0 || undefined }
data-on ={ tick . version === era . version || undefined }
style ={{ left : ` ${ tick . t * 100 } %` }}
/>
))}
< span className = "er-head" ref ={ head } />
</ div >
< div className = "er-labels" aria-hidden = "true" data-compact ={ compact || undefined }>
{ eras . map (( e , i ) => (
< span
key ={ e . id }
className = "er-label"
data-on ={ i === active || undefined }
data-edge ={ i === 0 ? "start" : i === end ? "end" : undefined }
style ={{ left : ` ${ stopT ( i , eras . length ) * 100 } %` }}
>
{ e . label }
</ span >
))}
</ div >
</ div >
</ div >
</ div >
);
}
show all 407 lines