Created
June 19, 2024 15:18
-
-
Save tak-dcxi/1c47a004ac6a498dfd8fd0e601af958f to your computer and use it in GitHub Desktop.
initializeViewTransitions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// View Transitions API は TypeScript の型定義に含まれていないため自身で定義する | |
declare global { | |
interface ViewTransition { | |
finished: Promise<void> | |
ready: Promise<void> | |
updateCallbackDone: Promise<void> | |
} | |
interface Document { | |
startViewTransition(updateCallback: () => Promise<void> | void): ViewTransition | |
} | |
interface CSSStyleDeclaration { | |
viewTransitionName?: string | |
} | |
} | |
const handleIntersection = (viewTransitionName: string) => (entries: IntersectionObserverEntry[]) => { | |
entries.forEach((entry) => { | |
const target = entry.target as HTMLElement | |
const transitionName = entry.isIntersecting ? viewTransitionName : 'none' | |
target.style.setProperty('view-transition-name', transitionName) | |
}) | |
} | |
const observeElement = (element: HTMLElement): void => { | |
const { viewTransitionName } = getComputedStyle(element) | |
if (!viewTransitionName || viewTransitionName === 'none') return | |
const observer = new IntersectionObserver(handleIntersection(viewTransitionName)) | |
observer.observe(element) | |
} | |
const initializeViewTransitions = (): void => { | |
if (!document.startViewTransition) return | |
const transitionElements = document.querySelectorAll<HTMLElement>('[data-view-transition-element]') | |
if (transitionElements.length === 0) return | |
transitionElements.forEach(observeElement) | |
} | |
export default initializeViewTransitions |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment