Visualize Your Ideas With Code
refactor: timeline context
aarthificial7ceb97066688
diff --git a/src/components/timeline/Label.tsx b/src/components/timeline/Label.tsxindex fd5cdc42..7baa4ce7 100644--- a/src/components/timeline/Label.tsx+++ b/src/components/timeline/Label.tsx@@ -2,16 +2,16 @@ import styles from './Timeline.module.scss';import type {Scene, TimeEvent} from '@motion-canvas/core/Scene';import {useDrag, usePlayer} from '../../hooks';-import {useCallback, useEffect, useState} from 'preact/hooks';+import {useCallback, useContext, useEffect, useState} from 'preact/hooks';+import {TimelineContext} from './TimelineContext';interface LabelProps {event: TimeEvent;scene: Scene;- fullLength: number;- duration: number;}-export function Label({event, scene, duration, fullLength}: LabelProps) {+export function Label({event, scene}: LabelProps) {+ const {fullLength, duration} = useContext(TimelineContext);const player = usePlayer();const [frame, setFrame] = useState(event.offset);const [handleDrag, isDragging] = useDrag(diff --git a/src/components/timeline/LabelGroup.tsx b/src/components/timeline/LabelGroup.tsxindex e565b2a3..e9ad1994 100644--- a/src/components/timeline/LabelGroup.tsx+++ b/src/components/timeline/LabelGroup.tsx@@ -1,15 +1,12 @@import type {Scene} from '@motion-canvas/core/Scene';-import {usePlayerState} from '../../hooks';import {useEffect, useState} from 'preact/hooks';import {Label} from './Label';interface LabelGroupProps {scene: Scene;- fullLength: number;}-export function LabelGroup({scene, fullLength}: LabelGroupProps) {- const state = usePlayerState();+export function LabelGroup({scene}: LabelGroupProps) {const [events, setEvents] = useState(scene.timeEvents);useEffect(() => {@@ -21,13 +18,7 @@ export function LabelGroup({scene, fullLength}: LabelGroupProps) {return (<>{events.map(event => (- <Label- key={event.name}- event={event}- scene={scene}- fullLength={fullLength}- duration={state.duration}- />+ <Label key={event.name} event={event} scene={scene} />))}</>);diff --git a/src/components/timeline/LabelTrack.tsx b/src/components/timeline/LabelTrack.tsxindex 007e1ad0..a3659169 100644--- a/src/components/timeline/LabelTrack.tsx+++ b/src/components/timeline/LabelTrack.tsx@@ -1,38 +1,13 @@import styles from './Timeline.module.scss';-import {usePlayerState, useScenes} from '../../hooks';-import {useMemo} from 'preact/hooks';+import {useScenes} from '../../hooks';+import {useContext, useMemo} from 'preact/hooks';import {LabelGroup} from './LabelGroup';+import {TimelineContext} from './TimelineContext';-interface LabelTrackProps {- fullLength: number;- viewLength: number;- offset: number;- scale: number;-}--export function LabelTrack({- fullLength,- viewLength,- offset,- scale,-}: LabelTrackProps) {+export function LabelTrack() {+ const {startFrame, endFrame} = useContext(TimelineContext);const scenes = useScenes();- const state = usePlayerState();-- // FIXME Use Context- const power = Math.pow(- 2,- Math.round(Math.log2(state.duration / scale / viewLength)),- );- const density = Math.max(1, Math.floor(128 * power));- const startFrame =- Math.floor(((offset / fullLength) * state.duration) / density) * density;- const endFrame =- Math.ceil(- (((offset + viewLength) / fullLength) * state.duration) / density,- ) * density;-const filtered = useMemo(() =>scenes.filter(@@ -44,7 +19,7 @@ export function LabelTrack({return (<div className={styles.labelTrack}>{filtered.map(scene => (- <LabelGroup key={scene.name()} scene={scene} fullLength={fullLength} />+ <LabelGroup key={scene.name()} scene={scene} />))}</div>);diff --git a/src/components/timeline/Playhead.tsx b/src/components/timeline/Playhead.tsxindex 7c7bfab9..83ab99b3 100644--- a/src/components/timeline/Playhead.tsx+++ b/src/components/timeline/Playhead.tsx@@ -1,18 +1,17 @@import styles from './Timeline.module.scss';import {usePlayerTime} from '../../hooks';+import {useContext} from 'preact/hooks';+import {TimelineContext} from './TimelineContext';-interface PlayheadProps {- trackSize: number;-}--export function Playhead({trackSize}: PlayheadProps) {+export function Playhead() {+ const {fullLength} = useContext(TimelineContext);const time = usePlayerTime();return (<divclassName={styles.playhead}style={{- left: `${trackSize * time.completion}px`,+ left: `${fullLength * time.completion}px`,}}/>);diff --git a/src/components/timeline/RangeTrack.tsx b/src/components/timeline/RangeTrack.tsxindex 4f35694b..d7a91e10 100644--- a/src/components/timeline/RangeTrack.tsx+++ b/src/components/timeline/RangeTrack.tsx@@ -1,17 +1,13 @@import styles from './Timeline.module.scss';import {useDrag, usePlayer, usePlayerState} from '../../hooks';-import {useCallback, useEffect, useState} from 'preact/hooks';+import {useCallback, useContext, useEffect, useState} from 'preact/hooks';import {Icon, IconType} from '../controls';+import {TimelineContext} from './TimelineContext';-interface RangeTrackProps {- fullLength: number;- viewLength: number;- offset: number;- scale: number;-}+export function RangeTrack() {+ const {fullLength} = useContext(TimelineContext);-export function RangeTrack({fullLength}: RangeTrackProps) {const player = usePlayer();const state = usePlayerState();const [start, setStart] = useState(state.startFrame);@@ -29,7 +25,9 @@ export function RangeTrack({fullLength}: RangeTrackProps) {const [handleDragEnd, isDraggingEnd] = useDrag(useCallback(dx => {- setEnd(Math.min(state.duration, end) + (dx / fullLength) * state.duration);+ setEnd(+ Math.min(state.duration, end) + (dx / fullLength) * state.duration,+ );},[end, setEnd, fullLength, state.duration],),@@ -39,7 +37,9 @@ export function RangeTrack({fullLength}: RangeTrackProps) {useCallback(dx => {setStart(start + (dx / fullLength) * state.duration);- setEnd(Math.min(state.duration, end) + (dx / fullLength) * state.duration);+ setEnd(+ Math.min(state.duration, end) + (dx / fullLength) * state.duration,+ );},[start, end, fullLength, state.duration, setStart, setEnd],),diff --git a/src/components/timeline/Timeline.tsx b/src/components/timeline/Timeline.tsxindex c83bbbc5..102e57d6 100644--- a/src/components/timeline/Timeline.tsx+++ b/src/components/timeline/Timeline.tsx@@ -3,6 +3,7 @@ import styles from './Timeline.module.scss';import {useCallback,useLayoutEffect,+ useMemo,useRef,useState,} from 'preact/hooks';@@ -17,6 +18,8 @@ import {TimestampTrack} from './TimestampTrack';import {LabelTrack} from './LabelTrack';import {SceneTrack} from './SceneTrack';import {RangeTrack} from './RangeTrack';+import {TimelineContext, TimelineState} from './TimelineContext';+import {clamp} from '@motion-canvas/core/tweening';const ZOOM_SPEED = 0.1;@@ -32,17 +35,40 @@ function useStateChange<T>(state: T, onChange: (prev: T, next: T) => any) {export function Timeline() {const player = usePlayer();- const state = usePlayerState();const containerRef = useRef<HTMLDivElement>();const playheadRef = useRef<HTMLDivElement>();+ const {duration} = usePlayerState();const rect = useSize(containerRef);- const [scroll, setScroll] = useState(0);+ const [offset, setOffset] = useState(0);const [scale, setScale] = useState(1);- const trackSize = rect.width * scale;+ const state = useMemo<TimelineState>(() => {+ const fullLength = rect.width * scale;+ const power = Math.pow(+ 2,+ Math.round(Math.log2(duration / scale / rect.width)),+ );+ const density = Math.max(1, Math.floor(128 * power));+ const startFrame =+ Math.floor(((offset / fullLength) * duration) / density) * density;+ const endFrame =+ Math.ceil((((offset + rect.width) / fullLength) * duration) / density) *+ density;++ return {+ scale,+ offset,+ fullLength,+ viewLength: rect.width,+ startFrame,+ endFrame,+ density,+ duration,+ };+ }, [rect.width, scale, duration, offset]);useStateChange(- state.duration,+ duration,useCallback((prev, next) => setScale(Math.max(1, (scale / prev) * next)),[scale],@@ -67,78 +93,62 @@ export function Timeline() {event => {if (event.key !== 'f') return;const time = player.getTime();- const maxOffset = trackSize - rect.width;- const playhead = trackSize * time.completion;- const newScroll = playhead - rect.width / 2;- setScroll(- newScroll < 0 ? 0 : newScroll > maxOffset ? maxOffset : newScroll,- );- setScale(scale * 0.99);+ const maxOffset = state.fullLength - rect.width;+ const playheadPosition = state.fullLength * time.completion;+ const scrollLeft = playheadPosition - rect.width / 2;+ const newOffset = clamp(0, maxOffset, scrollLeft);+ containerRef.current.scrollLeft = newOffset;+ setOffset(newOffset);},- [trackSize, rect, scale],+ [state.fullLength, rect, scale],),);useLayoutEffect(() => {- containerRef.current.scrollLeft = scroll;+ containerRef.current.scrollLeft = offset;}, [scale]);return (- <div- className={styles.root}- ref={containerRef}- onScroll={event => setScroll((event.target as HTMLElement).scrollLeft)}- onWheel={event => {- const ratio = 1 - Math.sign(event.deltaY) * ZOOM_SPEED;- const newScale = scale * ratio < 1 ? 1 : scale * ratio;+ <TimelineContext.Provider value={state}>+ <div+ className={styles.root}+ ref={containerRef}+ onScroll={event => setOffset((event.target as HTMLElement).scrollLeft)}+ onWheel={event => {+ const ratio = 1 - Math.sign(event.deltaY) * ZOOM_SPEED;+ const newScale = scale * ratio < 1 ? 1 : scale * ratio;- const pointer = scroll + event.x - rect.x;- const newScroll = scroll - pointer + pointer * ratio;- const newTrackSize = rect.width * newScale;- const maxOffset = newTrackSize - rect.width;+ const pointer = offset + event.x - rect.x;+ const newOffset = offset - pointer + pointer * ratio;+ const newTrackSize = rect.width * newScale;+ const maxOffset = newTrackSize - rect.width;- containerRef.current.scrollLeft = newScroll;- setScale(newScale);- setScroll(- newScroll < 0 ? 0 : newScroll > maxOffset ? maxOffset : newScroll,- );- }}- onMouseUp={event => {- if (event.button === 0) {- player.requestSeek(- Math.floor(- ((scroll + event.x - rect.x) / trackSize) * state.duration,- ),- );- }- }}- onMouseMove={event => {- playheadRef.current.style.left = `${event.x - rect.x + scroll}px`;- }}- >- <div className={styles.track} style={{width: `${trackSize}px`}}>- <RangeTrack- fullLength={trackSize}- viewLength={rect.width}- offset={scroll}- scale={scale}- />- <TimestampTrack- fullLength={trackSize}- viewLength={rect.width}- offset={scroll}- scale={scale}- />- <SceneTrack />- <LabelTrack- fullLength={trackSize}- viewLength={rect.width}- offset={scroll}- scale={scale}- />+ containerRef.current.scrollLeft = newOffset;+ setScale(newScale);+ setOffset(clamp(0, maxOffset, newOffset));+ }}+ onMouseUp={event => {+ if (event.button === 0) {+ player.requestSeek(+ Math.floor(+ ((offset + event.x - rect.x) / state.fullLength) * duration,+ ),+ );+ }+ }}+ onMouseMove={event => {+ playheadRef.current.style.left = `${event.x - rect.x + offset}px`;+ }}+ >+ <div className={styles.track} style={{width: `${state.fullLength}px`}}>+ <RangeTrack />+ <TimestampTrack />+ <SceneTrack />+ <LabelTrack />+ </div>+ <div ref={playheadRef} className={styles.playheadPreview} />+ <Playhead /></div>- <div ref={playheadRef} className={styles.playheadPreview} />- <Playhead trackSize={trackSize} />- </div>+ </TimelineContext.Provider>);}diff --git a/src/components/timeline/TimelineContext.ts b/src/components/timeline/TimelineContext.tsnew file mode 100644index 00000000..9ba05ca4--- /dev/null+++ b/src/components/timeline/TimelineContext.ts@@ -0,0 +1,25 @@+import {createContext} from 'preact';++export interface TimelineState {+ fullLength: number;+ viewLength: number;+ offset: number;+ scale: number;+ startFrame: number;+ endFrame: number;+ density: number;+ duration: number;+}++const TimelineContext = createContext<TimelineState>({+ fullLength: 0,+ viewLength: 0,+ offset: 0,+ scale: 1,+ density: 1,+ duration: 0,+ endFrame: 0,+ startFrame: 0,+});++export {TimelineContext};diff --git a/src/components/timeline/TimestampTrack.tsx b/src/components/timeline/TimestampTrack.tsxindex 08e0483e..51e83e0b 100644--- a/src/components/timeline/TimestampTrack.tsx+++ b/src/components/timeline/TimestampTrack.tsx@@ -1,45 +1,22 @@import styles from './Timeline.module.scss';-import {usePlayerState} from '../../hooks';-import {useMemo} from 'preact/hooks';+import {useContext, useMemo} from 'preact/hooks';+import {TimelineContext} from './TimelineContext';-interface TimestampTrackProps {- fullLength: number;- viewLength: number;- offset: number;- scale: number;-}--export function TimestampTrack({- fullLength,- viewLength,- offset,- scale,-}: TimestampTrackProps) {- const state = usePlayerState();- const power = Math.pow(- 2,- Math.round(Math.log2(state.duration / scale / viewLength)),- );-- const density = Math.max(1, Math.floor(128 * power));- const startFrame = Math.floor(- ((offset / fullLength) * state.duration) / density,- );- const endFrame = Math.ceil(- (((offset + viewLength) / fullLength) * state.duration) / density,- );+export function TimestampTrack() {+ const {fullLength, startFrame, endFrame, density, duration} =+ useContext(TimelineContext);const timestamps = useMemo(() => {const timestamps = [];- for (let i = startFrame; i < endFrame; i++) {+ for (let i = startFrame; i < endFrame; i += density) {timestamps.push({- time: i * density,- style: {left: `${((i * density) / state.duration) * fullLength}px`},+ time: i,+ style: {left: `${(i / duration) * fullLength}px`},});}return timestamps;- }, [startFrame, endFrame, state.duration, fullLength, density]);+ }, [startFrame, endFrame, duration, fullLength, density]);return (<div className={styles.timestampTrack}>diff --git a/src/hooks/useStorage.ts b/src/hooks/useStorage.tsindex bcdba4f9..2b513c24 100644--- a/src/hooks/useStorage.ts+++ b/src/hooks/useStorage.ts@@ -2,13 +2,13 @@ import {useCallback, useMemo, useState} from 'preact/hooks';export function useStorage<T>(id: string,- initialState?: T,+ initialState: T = null,): [T, (newState: T) => void] {const savedState = useMemo(() => {const savedState = localStorage.getItem(id);- return savedState ? JSON.parse(savedState) : null;+ return savedState ? JSON.parse(savedState) : initialState;}, [id]);- const [state, setState] = useState<T>(savedState ?? initialState ?? null);+ const [state, setState] = useState<T>(savedState);const updateState = useCallback((newState: T) => {