UNPKG

2.75 kBJavaScriptView Raw
1import { getWindow, getDocument } from 'ssr-window';
2import $ from '../../shared/dom.js';
3export default function HashNavigation({
4 swiper,
5 extendParams,
6 emit,
7 on
8}) {
9 let initialized = false;
10 const document = getDocument();
11 const window = getWindow();
12 extendParams({
13 hashNavigation: {
14 enabled: false,
15 replaceState: false,
16 watchState: false
17 }
18 });
19
20 const onHashChange = () => {
21 emit('hashChange');
22 const newHash = document.location.hash.replace('#', '');
23 const activeSlideHash = swiper.slides.eq(swiper.activeIndex).attr('data-hash');
24
25 if (newHash !== activeSlideHash) {
26 const newIndex = swiper.$wrapperEl.children(`.${swiper.params.slideClass}[data-hash="${newHash}"]`).index();
27 if (typeof newIndex === 'undefined') return;
28 swiper.slideTo(newIndex);
29 }
30 };
31
32 const setHash = () => {
33 if (!initialized || !swiper.params.hashNavigation.enabled) return;
34
35 if (swiper.params.hashNavigation.replaceState && window.history && window.history.replaceState) {
36 window.history.replaceState(null, null, `#${swiper.slides.eq(swiper.activeIndex).attr('data-hash')}` || '');
37 emit('hashSet');
38 } else {
39 const slide = swiper.slides.eq(swiper.activeIndex);
40 const hash = slide.attr('data-hash') || slide.attr('data-history');
41 document.location.hash = hash || '';
42 emit('hashSet');
43 }
44 };
45
46 const init = () => {
47 if (!swiper.params.hashNavigation.enabled || swiper.params.history && swiper.params.history.enabled) return;
48 initialized = true;
49 const hash = document.location.hash.replace('#', '');
50
51 if (hash) {
52 const speed = 0;
53
54 for (let i = 0, length = swiper.slides.length; i < length; i += 1) {
55 const slide = swiper.slides.eq(i);
56 const slideHash = slide.attr('data-hash') || slide.attr('data-history');
57
58 if (slideHash === hash && !slide.hasClass(swiper.params.slideDuplicateClass)) {
59 const index = slide.index();
60 swiper.slideTo(index, speed, swiper.params.runCallbacksOnInit, true);
61 }
62 }
63 }
64
65 if (swiper.params.hashNavigation.watchState) {
66 $(window).on('hashchange', onHashChange);
67 }
68 };
69
70 const destroy = () => {
71 if (swiper.params.hashNavigation.watchState) {
72 $(window).off('hashchange', onHashChange);
73 }
74 };
75
76 on('init', () => {
77 if (swiper.params.hashNavigation.enabled) {
78 init();
79 }
80 });
81 on('destroy', () => {
82 if (swiper.params.hashNavigation.enabled) {
83 destroy();
84 }
85 });
86 on('transitionEnd _freeModeNoMomentumRelease', () => {
87 if (initialized) {
88 setHash();
89 }
90 });
91 on('slideChange', () => {
92 if (initialized && swiper.params.cssMode) {
93 setHash();
94 }
95 });
96}
\No newline at end of file