Files
bridget/assets/ts/mobile/gallery.ts
Spedon 0812a5a6b8 feat: loading transition (#277)
* refactor: change hires loader function name

* feat: add loading transition animation and improve performance

* refactor: refactor mutation handling in desktop codebase

- Modify the `initStage` function in `assets/ts/desktop/stage.ts`:
  - Change the `onMutation` callback to accept a single mutation instead of an array of mutations.
  - Update the conditions inside the callback to use `hold` instead of `skip`.
- Modify the `onMutation` function in `assets/ts/desktop/utils.ts`:
  - Change the `callback` parameter to `trigger`.
  - Update the implementation of the function to iterate over each mutation and check if it triggers the `trigger` function. If it does, disconnect the observer and break the loop.

* style: refactor state section and remove unnecessary code

- Remove the declaration of `lastIndex` on line 21
- Add a comment block for the state section
- Add a declaration of `lastIndex` for the state section

* refactor: refactor mobile collection and intersection functions

- Modify the `initCollection` function in `assets/ts/mobile/collection.ts`
- Remove the nested loop in the `initCollection` function
- Modify the `onIntersection` function in `assets/ts/mobile/utils.ts`
- Replace the callback parameter with a trigger parameter in the `onIntersection` function
- Remove the nested loop in the `onIntersection` function

* refactor: refactor Watchable class constructor to include lazy parameter

- Add a second parameter `lazy` in the constructor of the `Watchable` class in `globalUtils.ts`
- Set the default value of `lazy` to `true` in the constructor
- Add a condition to check if `e` is equal to `this.obj` and `this.lazy` is `true` to return in `watch`
- Delete the previous constructor definition in the `Watchable` class in `globalUtils.ts`

* fix: set state's lazy param to false

* refactor: refactor third party lib import
2024-02-06 23:12:44 +08:00

316 lines
7.7 KiB
TypeScript

import { type gsap } from 'gsap'
import { type Swiper } from 'swiper'
import { container, scrollable } from '../container'
import { isAnimating, navigateVector, setIndex, state } from '../globalState'
import { expand, loadGsap, removeDuplicates } from '../globalUtils'
import { type ImageJSON } from '../resources'
import { mounted } from './state'
// eslint-disable-next-line sort-imports
import { capitalizeFirstLetter, loadSwiper, type MobileImage } from './utils'
/**
* variables
*/
let swiperNode: HTMLDivElement
let gallery: HTMLDivElement
let curtain: HTMLDivElement
let indexDispNums: HTMLSpanElement[] = []
let galleryImages: MobileImage[] = []
let collectionImages: MobileImage[] = []
let _gsap: typeof gsap
let _swiper: Swiper
/**
* state
*/
let lastIndex = -1
let libLoaded = false
/**
* main functions
*/
export function slideUp(): void {
if (isAnimating.get() || !libLoaded) return
isAnimating.set(true)
_gsap.to(curtain, {
opacity: 1,
duration: 1
})
_gsap.to(gallery, {
y: 0,
ease: 'power3.inOut',
duration: 1,
delay: 0.4
})
setTimeout(() => {
// cleanup
scrollable.set(false)
isAnimating.set(false)
}, 1400)
}
function slideDown(): void {
if (isAnimating.get()) return
isAnimating.set(true)
scrollToActive()
_gsap.to(gallery, {
y: '100%',
ease: 'power3.inOut',
duration: 1
})
_gsap.to(curtain, {
opacity: 0,
duration: 1.2,
delay: 0.4
})
setTimeout(() => {
// cleanup
scrollable.set(true)
isAnimating.set(false)
lastIndex = -1
}, 1600)
}
/**
* init
*/
export function initGallery(ijs: ImageJSON[]): void {
// create gallery
createGallery(ijs)
// get elements
indexDispNums = Array.from(
document.getElementsByClassName('nav').item(0)?.getElementsByClassName('num') ?? []
) as HTMLSpanElement[]
swiperNode = document.getElementsByClassName('galleryInner').item(0) as HTMLDivElement
gallery = document.getElementsByClassName('gallery').item(0) as HTMLDivElement
curtain = document.getElementsByClassName('curtain').item(0) as HTMLDivElement
galleryImages = Array.from(gallery.getElementsByTagName('img')) as MobileImage[]
collectionImages = Array.from(
document
.getElementsByClassName('collection')
.item(0)
?.getElementsByTagName('img') ?? []
) as MobileImage[]
// state watcher
state.addWatcher((o) => {
if (o.index === lastIndex)
return // change slide only when index is changed
else if (lastIndex === -1)
navigateVector.set('none') // lastIndex before set
else if (o.index < lastIndex)
navigateVector.set('prev') // set navigate vector for galleryLoadImages
else if (o.index > lastIndex)
navigateVector.set('next') // set navigate vector for galleryLoadImages
else navigateVector.set('none') // default
changeSlide(o.index) // change slide to new index
updateIndexText() // update index text
lastIndex = o.index // update last index
})
// mounted watcher
mounted.addWatcher((o) => {
if (!o) return
scrollable.set(true)
})
// dynamic import
window.addEventListener(
'touchstart',
() => {
loadGsap()
.then((g) => {
_gsap = g
})
.catch((e) => {
console.log(e)
})
loadSwiper()
.then((S) => {
_swiper = new S(swiperNode, { spaceBetween: 20 })
_swiper.on('slideChange', ({ realIndex }) => {
setIndex(realIndex)
})
})
.catch((e) => {
console.log(e)
})
libLoaded = true
},
{ once: true, passive: true }
)
// mounted
mounted.set(true)
}
/**
* helper
*/
function changeSlide(slide: number): void {
galleryLoadImages()
_swiper.slideTo(slide, 0)
}
function scrollToActive(): void {
collectionImages[state.get().index].scrollIntoView({
block: 'center',
behavior: 'auto'
})
}
function updateIndexText(): void {
const indexValue: string = expand(state.get().index + 1)
const indexLength: string = expand(state.get().length)
indexDispNums.forEach((e: HTMLSpanElement, i: number) => {
if (i < 4) {
e.innerText = indexValue[i]
} else {
e.innerText = indexLength[i - 4]
}
})
}
function galleryLoadImages(): void {
let activeImagesIndex: number[] = []
const currentIndex = state.get().index
const nextIndex = Math.min(currentIndex + 1, state.get().length - 1)
const prevIndex = Math.max(currentIndex - 1, 0)
switch (navigateVector.get()) {
case 'next':
activeImagesIndex = [nextIndex]
break
case 'prev':
activeImagesIndex = [prevIndex]
break
case 'none':
activeImagesIndex = [currentIndex, nextIndex, prevIndex]
break
}
removeDuplicates(activeImagesIndex).forEach((i) => {
const e = galleryImages[i]
if (e.src === e.dataset.src) return // already loaded
e.src = e.dataset.src
})
}
function createGallery(ijs: ImageJSON[]): void {
/**
* gallery
* |- galleryInner
* |- swiper-wrapper
* |- swiper-slide
* |- img
* |- swiper-slide
* |- img
* |- ...
* |- nav
* |- index
* |- close
*/
// swiper wrapper
const _swiperWrapper = document.createElement('div')
_swiperWrapper.className = 'swiper-wrapper'
// loading text
const loadingText = container.dataset.loading + '...'
for (const ij of ijs) {
// swiper slide
const _swiperSlide = document.createElement('div')
_swiperSlide.className = 'swiper-slide'
// loading indicator
const l = document.createElement('div')
l.className = 'loadingText'
l.innerText = loadingText
// img
const e = document.createElement('img') as MobileImage
e.dataset.src = ij.hiUrl
e.height = ij.hiImgH
e.width = ij.hiImgW
e.alt = ij.alt
e.style.opacity = '0'
// load event
e.addEventListener(
'load',
() => {
if (state.get().index !== ij.index) {
_gsap.set(e, { opacity: 1 })
_gsap.set(l, { opacity: 0 })
} else {
_gsap.to(e, { opacity: 1, delay: 0.5, duration: 0.5, ease: 'power3.out' })
_gsap.to(l, { opacity: 0, duration: 0.5, ease: 'power3.in' })
}
},
{ once: true, passive: true }
)
// parent container
const p = document.createElement('div')
p.className = 'slideContainer'
// append
p.append(e)
p.append(l)
_swiperSlide.append(p)
_swiperWrapper.append(_swiperSlide)
}
// swiper node
const _swiperNode = document.createElement('div')
_swiperNode.className = 'galleryInner'
_swiperNode.append(_swiperWrapper)
// index
const _index = document.createElement('div')
_index.insertAdjacentHTML(
'afterbegin',
`<span class="num"></span><span class="num"></span><span class="num"></span><span class="num"></span>
<span>/</span>
<span class="num"></span><span class="num"></span><span class="num"></span><span class="num"></span>`
)
// close
const _close = document.createElement('div')
_close.innerText = capitalizeFirstLetter(container.dataset.close)
_close.addEventListener(
'click',
() => {
slideDown()
},
{ passive: true }
)
_close.addEventListener(
'keydown',
() => {
slideDown()
},
{ passive: true }
)
// nav
const _navDiv = document.createElement('div')
_navDiv.className = 'nav'
_navDiv.append(_index, _close)
// gallery
const _gallery = document.createElement('div')
_gallery.className = 'gallery'
_gallery.append(_swiperNode)
_gallery.append(_navDiv)
/**
* curtain
*/
const _curtain = document.createElement('div')
_curtain.className = 'curtain'
/**
* container
* |- gallery
* |- curtain
*/
container.append(_gallery, _curtain)
}