summaryrefslogtreecommitdiff
path: root/src/slides.js
blob: f61d1fa8347b0c781e1c9a89958586f83b5cebd2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
const Flickity = require("flickity")
import "flickity/dist/flickity.min.css"

export default function initSlides() {
	/* Flickity function for scrolling to ensure next and prev pics are always
	 * visible and to transition between states */
	function scroll(progress) {
		const normalizedProgress = progress / (1 / (flkty.cells.length-1))
		const liveSelectedIndex = Math.round(normalizedProgress)
		const localizedProgress = normalizedProgress - liveSelectedIndex

		const prevSelectedCell = flkty.cells.at(liveSelectedIndex-1).element
		const liveSelectedCell = flkty.cells.at(liveSelectedIndex     % flkty.cells.length).element
		const nextSelectedCell = flkty.cells.at((liveSelectedIndex+1) % flkty.cells.length).element

		const prevSelectedImage = prevSelectedCell.firstElementChild
		const liveSelectedImage = liveSelectedCell.firstElementChild
		const nextSelectedImage = nextSelectedCell.firstElementChild

		const prevMargin = prevSelectedCell.clientWidth - prevSelectedImage.clientWidth
		const liveMargin = liveSelectedCell.clientWidth - liveSelectedImage.clientWidth
		const nextMargin = nextSelectedCell.clientWidth - nextSelectedImage.clientWidth

		liveSelectedImage.style.marginLeft = liveMargin / 2 + "px"
		nextSelectedImage.style.marginLeft = Math.max(0, Math.min(nextMargin, nextMargin * (localizedProgress))) + "px"
		prevSelectedImage.style.marginLeft = prevMargin - Math.max(0, Math.min(prevMargin, prevMargin * localizedProgress * -1)) + "px" // TODO clean this
	}

	/* jump to clicked on slide */
	function staticClick(e, pointer, cellElement, cellIndex) {
		flkty.select(cellIndex)
	}

	/* make sure images have correct margin when loaded since scroll function
	 * depends on them being loaded */
	function positionImageStatic(img) {
		const i = parseInt(img.dataset.index)
		if (i == flkty.selectedIndex)
			img.style.marginLeft = (img.parentElement.clientWidth - img.clientWidth) / 2 + "px"
		else if ((i + 1) % flkty.cells.length == flkty.selectedIndex)
			img.style.marginLeft = img.parentElement.clientWidth - img.clientWidth + "px"
	}

	function imageLoaded(e) { positionImageStatic(e.target) }
	function initImages() {
		const imgs = document.querySelectorAll("#slideshow-carousel img")
		for (let i = 0; i < imgs.length; i++) {
			const img = imgs[i]
			img.dataset.index = i
			img.addEventListener("load", imageLoaded)
			if (img.complete)
				positionImageStatic(img)
		}
	}

	/* initialize slides */
	const flkty = new Flickity('#slideshow-carousel', {
		wrapAround: true,
		prevNextButtons: false,
		pageDots: false,
		resize: true,
		setGallerySize: false,
	})

	flkty.on("scroll", scroll)
	flkty.on("staticClick", staticClick)
	initImages()
}