Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add watchResize and watchSlides options #449

Merged
merged 17 commits into from
Apr 4, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
Scaffold resize and slides observers
  • Loading branch information
davidjerleke committed Mar 23, 2023
commit b25a85b03db4a08fe75eae4c220fdb23297a7622
30 changes: 29 additions & 1 deletion packages/embla-carousel-react/src/components/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ function useEmblaCarousel(
plugins: EmblaPluginType[] = [],
): UseEmblaCarouselType {
const optionsHandler = useRef(EmblaCarousel.optionsHandler())
const slideObserver = useRef<MutationObserver>()
const storedOptions = useRef(options)
const storedPlugins = useRef(plugins)
const [embla, setEmbla] = useState<EmblaCarouselType>()
Expand All @@ -38,8 +39,35 @@ function useEmblaCarousel(
storedPlugins.current,
)
setEmbla(newEmbla)
return () => newEmbla.destroy()

// const queue: MutationRecord[][] = []

// const reInitLazy = () => {
// newEmbla.reInit()
// queue.length = 0
// }

// const slideObserverConfig = { childList: true }
// slideObserver.current = new MutationObserver((mutationList) => {
// for (const mutation of mutationList) {
// if (mutation.type === 'childList') {
// if (!queue.length) requestAnimationFrame(reInitLazy)
// queue.push(mutationList)
// }
// }
// })

// slideObserver.current.observe(
// newEmbla.containerNode(),
// slideObserverConfig,
// )

return () => {
// if (slideObserver.current) slideObserver.current.disconnect()
newEmbla.destroy()
}
} else {
// if (slideObserver.current) slideObserver.current.disconnect()
setEmbla(undefined)
}
}, [viewport, setEmbla])
Expand Down
8 changes: 7 additions & 1 deletion packages/embla-carousel/src/components/Engine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { EventStore, EventStoreType } from './EventStore'
import { LimitType } from './Limit'
import { OptionsType } from './Options'
import { PercentOfView, PercentOfViewType } from './PercentOfView'
import { ResizeHandler, ResizeHandlerType } from './ResizeHandler'
import { ScrollBody, ScrollBodyType } from './ScrollBody'
import { ScrollBounds, ScrollBoundsType } from './ScrollBounds'
import { ScrollContain } from './ScrollContain'
Expand All @@ -20,6 +21,7 @@ import { ScrollSnaps } from './ScrollSnaps'
import { ScrollTarget, ScrollTargetType } from './ScrollTarget'
import { ScrollTo, ScrollToType } from './ScrollTo'
import { SlideLooper, SlideLooperType } from './SlideLooper'
import { SlidesHandler, SlidesHandlerType } from './SlidesHandler'
import { SlidesInView, SlidesInViewType } from './SlidesInView'
import { SlideSizes } from './SlideSizes'
import { SlidesToScroll, SlidesToScrollType } from './SlidesToScroll'
Expand Down Expand Up @@ -48,6 +50,8 @@ export type EngineType = {
slidesToScroll: SlidesToScrollType
target: Vector1DType
translate: TranslateType
resizeHandler: ResizeHandlerType
slidesHandler: SlidesHandlerType
scrollTo: ScrollToType
scrollTarget: ScrollTargetType
scrollSnaps: number[]
Expand Down Expand Up @@ -212,6 +216,7 @@ export function Engine(
limit,
location,
options,
resizeHandler: ResizeHandler(container, slides, axis, eventHandler),
scrollBody,
scrollBounds: ScrollBounds(
limit,
Expand Down Expand Up @@ -239,9 +244,10 @@ export function Engine(
location,
slides,
),
slidesToScroll,
slidesHandler: SlidesHandler(container),
slidesInView,
slideIndexes,
slidesToScroll,
target,
translate: Translate(axis, direction, container),
}
Expand Down
3 changes: 2 additions & 1 deletion packages/embla-carousel/src/components/OptionsHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,14 +23,15 @@ export function OptionsHandler(): OptionsHandlerType {
return <TypeA>objectsMergeDeep(optionsA, optionsB || {})
}

// TODO: Move to embla-carousel-reactive-utils
function areEqual<TypeA extends OptionsType, TypeB extends OptionsType>(
optionsA: TypeA,
optionsB: TypeB,
): boolean {
const breakpointsA = JSON.stringify(objectKeys(optionsA.breakpoints || {}))
const breakpointsB = JSON.stringify(objectKeys(optionsB.breakpoints || {}))
if (breakpointsA !== breakpointsB) return false
return objectsAreEqual(optionsA, optionsB)
return objectsAreEqual(optionsA, optionsB) // TODO: Move to embla-carousel-reactive-utils
}

function atMedia<Type extends OptionsType>(options: Type): Type {
Expand Down
17 changes: 1 addition & 16 deletions packages/embla-carousel/src/components/PluginsHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,36 +2,22 @@ import { EmblaCarouselType } from '.'
import { OptionsHandler } from './OptionsHandler'
import { EmblaPluginsType, EmblaPluginType } from './Plugins'

type PluginChangedHandlerType = () => boolean

export type PluginsHandlerType = {
init: (
plugins: EmblaPluginType[],
embla: EmblaCarouselType,
) => EmblaPluginsType
destroy: () => void
haveChanged: PluginChangedHandlerType
}

export function PluginsHandler(): PluginsHandlerType {
const { atMedia, areEqual } = OptionsHandler()
const { atMedia } = OptionsHandler()
let activePlugins: EmblaPluginType[] = []
let pluginsChanged: PluginChangedHandlerType[] = []

function haveChanged(): boolean {
return pluginsChanged.some((hasChanged) => hasChanged())
}

function hasChanged(plugin: EmblaPluginType): PluginChangedHandlerType {
const options = atMedia(plugin.options)
return (): boolean => !areEqual(options, atMedia(plugin.options))
}

function init(
plugins: EmblaPluginType[],
embla: EmblaCarouselType,
): EmblaPluginsType {
pluginsChanged = plugins.map(hasChanged)
activePlugins = plugins.filter((plugin) => atMedia(plugin.options).active)
activePlugins.forEach((plugin) => plugin.init(embla))

Expand All @@ -47,7 +33,6 @@ export function PluginsHandler(): PluginsHandlerType {
const self: PluginsHandlerType = {
init,
destroy,
haveChanged,
}
return self
}
50 changes: 50 additions & 0 deletions packages/embla-carousel/src/components/ResizeHandler.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import { AxisType } from './Axis'
import { EventHandlerType } from './EventHandler'

export type ResizeHandlerType = {
init: <CallbackType extends Function>(cb: CallbackType) => void
destroy: () => void
}

export function ResizeHandler(
container: HTMLElement,
slides: HTMLElement[],
axis: AxisType,
eventHandler: EventHandlerType,
): ResizeHandlerType {
let resizeObserver: ResizeObserver
let containerSize: number
let slideSizes: number[] = []

function readSize(node: Element | HTMLElement): number {
return axis.measureSize(node.getBoundingClientRect())
}

function init<CallbackType extends Function>(cb: CallbackType): void {
containerSize = readSize(container)
slideSizes = slides.map(readSize)

resizeObserver = new ResizeObserver((entries) => {
entries.forEach((entry) => {
const slideSize = slideSizes[slides.indexOf(<HTMLElement>entry.target)]
const lastSize = entry.target === container ? containerSize : slideSize

if (lastSize !== readSize(entry.target)) cb()
eventHandler.emit('resize')
})
})

const observeNodes = [container].concat(slides)
observeNodes.forEach((node) => resizeObserver.observe(node))
}

function destroy(): void {
resizeObserver.disconnect()
}

const self: ResizeHandlerType = {
init,
destroy,
}
return self
}
28 changes: 28 additions & 0 deletions packages/embla-carousel/src/components/SlidesHandler.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
export type SlidesHandlerType = {
init: <CallbackType extends Function>(cb: CallbackType) => void
destroy: () => void
}

export function SlidesHandler(container: HTMLElement): SlidesHandlerType {
let mutationObserver: MutationObserver

function init<CallbackType extends Function>(cb: CallbackType): void {
mutationObserver = new MutationObserver((mutationList) => {
for (const mutation of mutationList) {
if (mutation.type === 'childList') cb()
}
})

mutationObserver.observe(container, { childList: true })
}

function destroy(): void {
mutationObserver.disconnect()
}

const self: SlidesHandlerType = {
init,
destroy,
}
return self
}
50 changes: 32 additions & 18 deletions packages/embla-carousel/src/components/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { defaultOptions, EmblaOptionsType } from './Options'
import { OptionsHandler } from './OptionsHandler'
import { PluginsHandler } from './PluginsHandler'
import { EmblaPluginsType, EmblaPluginType } from './Plugins'
import { isString } from './utils'
import { isString, objectKeys } from './utils'

export type EmblaCarouselType = {
canScrollNext: () => boolean
Expand Down Expand Up @@ -36,7 +36,7 @@ function EmblaCarousel(
userOptions?: EmblaOptionsType,
userPlugins?: EmblaPluginType[],
): EmblaCarouselType {
const resizeHandlers = EventStore()
const mediaHandlers = EventStore()
const optionsHandler = OptionsHandler()
const pluginsHandler = PluginsHandler()
const eventHandler = EventHandler()
Expand All @@ -52,7 +52,7 @@ function EmblaCarousel(
let options = optionsHandler.merge(optionsBase)
let pluginList: EmblaPluginType[] = []
let pluginApis: EmblaPluginsType
let rootSize = 0

let container: HTMLElement
let slides: HTMLElement[]

Expand Down Expand Up @@ -80,16 +80,40 @@ function EmblaCarousel(
options = optionsHandler.atMedia(optionsBase)

storeElements()

engine = Engine(root, container, slides, options, eventHandler)
rootSize = engine.axis.measureSize(root.getBoundingClientRect())

if (!options.active) return deActivate()

engine.translate.to(engine.location)
pluginList = withPlugins || pluginList
pluginApis = pluginsHandler.init(pluginList, self)

// NEW ---------------------->

// move to optionsHandler
const mediaQueryList = pluginList.reduce(
(acc, { options }) => acc.concat(objectKeys(options.breakpoints)),
objectKeys(optionsBase.breakpoints),
)
const uniqueMediaQueryList = mediaQueryList.filter((mediaQuery, index) => {
return mediaQueryList.indexOf(mediaQuery) === index
}) // change to new [...Set(mediaQueryList)]

mediaHandlers.removeAll()
uniqueMediaQueryList.forEach((mediaQuery) => {
mediaHandlers.add(matchMedia(mediaQuery), 'change', () => {
console.log('options changed')
return reActivate()
})
})

engine.slidesHandler.init(reActivate)
engine.resizeHandler.init(reActivate)

// TODO: DRY out engine.axis.measureSize() used in many places

// NEW ----------------------<

if (options.loop) {
if (!engine.slideLooper.canLoop()) {
deActivate()
Expand Down Expand Up @@ -120,28 +144,19 @@ function EmblaCarousel(
engine.eventStore.removeAll()
engine.translate.clear()
engine.slideLooper.clear()
engine.resizeHandler.destroy()
engine.slidesHandler.destroy()
pluginsHandler.destroy()
}

function destroy(): void {
if (destroyed) return
destroyed = true
resizeHandlers.removeAll()
mediaHandlers.removeAll()
deActivate()
eventHandler.emit('destroy')
}

function resize(): void {
const newOptions = optionsHandler.atMedia(optionsBase)
const optionsChanged = !optionsHandler.areEqual(newOptions, options)
const newRootSize = engine.axis.measureSize(root.getBoundingClientRect())
const rootSizeChanged = rootSize !== newRootSize
const pluginsChanged = pluginsHandler.haveChanged()

if (rootSizeChanged || optionsChanged || pluginsChanged) reActivate()
eventHandler.emit('resize')
}

function slidesInView(target?: boolean): number[] {
const location = engine[target ? 'target' : 'location'].get()
const type = options.loop ? 'removeOffset' : 'constrain'
Expand Down Expand Up @@ -244,7 +259,6 @@ function EmblaCarousel(
}

activate(userOptions, userPlugins)
resizeHandlers.add(window, 'resize', resize)
setTimeout(() => eventHandler.emit('init'), 0)
return self
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import React, { useState, useEffect, useCallback } from 'react'
import useEmblaCarousel, { EmblaOptionsType } from 'embla-carousel-react'
import Autoplay from 'embla-carousel-autoplay'
import { DotButton, PrevButton, NextButton } from './Buttons'
import imageByIndex from './imageByIndex'

Expand All @@ -10,7 +11,16 @@ type PropType = {

export const EmblaCarousel: React.FC<PropType> = (props) => {
const { slides, options } = props
const [emblaRef, emblaApi] = useEmblaCarousel(options)
const [emblaRef, emblaApi] = useEmblaCarousel(options, [
// Autoplay({
// delay: 3000,
// breakpoints: {
// '(min-width: 768px)': {
// delay: 6000,
// },
// },
// }),
])
const [prevBtnEnabled, setPrevBtnEnabled] = useState(false)
const [nextBtnEnabled, setNextBtnEnabled] = useState(false)
const [selectedIndex, setSelectedIndex] = useState(0)
Expand All @@ -36,13 +46,19 @@ export const EmblaCarousel: React.FC<PropType> = (props) => {
setNextBtnEnabled(emblaApi.canScrollNext())
}, [emblaApi, setSelectedIndex])

const updateScrollSnaps = useCallback(() => {
if (!emblaApi) return
setScrollSnaps(emblaApi.scrollSnapList())
}, [emblaApi])

useEffect(() => {
if (!emblaApi) return
onSelect()
setScrollSnaps(emblaApi.scrollSnapList())
updateScrollSnaps()
emblaApi.on('select', onSelect)
emblaApi.on('reInit', onSelect)
}, [emblaApi, setScrollSnaps, onSelect])
emblaApi.on('reInit', updateScrollSnaps)
}, [emblaApi, updateScrollSnaps, onSelect])

return (
<>
Expand Down
Loading