Repository navigation
Expand file tree
/
Copy pathSlider.js
More file actions
196 lines (176 loc) · 7.05 KB
/
Copy pathSlider.js
File metadata and controls
196 lines (176 loc) · 7.05 KB
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
import AbstractDomElement from './AbstractDomElement'
import Swiper from 'swiper'
import { A11y, Navigation } from 'swiper/modules'
import { __ } from '@wordpress/i18n'
import noop from '../utils/noop'
/**
* Thin wrapper around Swiper with project defaults (A11y + Navigation).
*
* Default modules are always kept; extra modules in `options.modules` are appended
* without duplicates.
*
* - A11y messages are translated via `@wordpress/i18n`; override per instance via `options.a11y` (`prevSlideMessage`, `nextSlideMessage`, etc.).
* - If slides are `<li>`, `slideRole` is cleared so Swiper does not set `role="group"` and break list semantics for screen readers (overridable via `options.a11y`).
* - When `hideNavigationFromA11y` is true, prev/next are removed from the accessibility tree and `.swiper-notification` is removed (nav announcements are unused).
* - When `hideNavigationFromA11y` is false, `.swiper-notification` is kept so Swiper can announce first/prev/next/last messages on keyboard activation of the nav controls.
* - `wrapperLiveRegion` is left to Swiper’s default (`true`): `aria-live="polite"` without autoplay, `aria-live="off"` with autoplay (overridable via `options.a11y`).
*
* Markup (minimal):
* ```html
* <div class="swiper">
* <div class="swiper-wrapper">
* <div class="swiper-slide">…</div>
* </div>
* <!-- get_template_part('components/parts/common/swiper', 'controls') -->
* </div>
* ```
*
* @example
* import Slider from './classes/Slider'
* import { Pagination } from 'swiper/modules'
*
* Slider.init('.my-slider', {
* hideNavigationFromA11y: true,
* fixLastSlideActiveOnEnd: true,
* onChange() {},
* options: {
* slidesPerView: 'auto',
* modules: [Pagination],
* navigation: {
* prevEl: '.swiper-button-prev',
* nextEl: '.swiper-button-next',
* },
* a11y: {
* // Optional: override translated defaults per slider
* nextSlideMessage: 'Next news item',
* },
* },
* })
*
* const slider = new Slider(el, { … })
* slider.getInstance() // Swiper
*
* @extends AbstractDomElement
*/
export default class Slider extends AbstractDomElement {
/**
* @param {HTMLElement} element - Root `.swiper` element
* @param {SliderOptions} [options]
*/
constructor(element, options) {
const instance = super(element, options)
// avoid double init :
if (!instance.isNewInstance()) {
return instance
}
this.init()
}
init() {
const el = this._element
const { options, onChange, hideNavigationFromA11y, fixLastSlideActiveOnEnd } = this._settings
// Merge default modules with user modules, avoiding duplicates.
// AbstractDomElement.extend() replaces arrays instead of concatenating:
// - If user passes no modules: extend copies defaults → old merge duplicated them
// - If user passes modules: extend replaces defaults → we lose A11y/Navigation
// This merge ensures defaults are always present + user modules added without duplicates.
const defaultModules = Slider.defaults.options.modules
const userModules = options.modules || []
const allModules = [...defaultModules, ...userModules.filter((mod) => !defaultModules.includes(mod))]
// role="group" on <li> breaks list semantics for screen readers.
const slidesAreListItems = el.querySelector('.swiper-slide')?.tagName === 'LI'
// Temesis feedback: hide navigation buttons from accessibility tree
// since slides are already keyboard accessible (e.g. cards with focusable content).
const hideNavigationButtons = (swiper) => {
if (!hideNavigationFromA11y) {
return
}
swiper.navigation.prevEl?.setAttribute('tabindex', '-1')
swiper.navigation.prevEl?.setAttribute('aria-hidden', 'true')
swiper.navigation.nextEl?.setAttribute('tabindex', '-1')
swiper.navigation.nextEl?.setAttribute('aria-hidden', 'true')
}
// Swiper usually sets .swiper-slide-active correctly for integer or half
// slidesPerView (e.g. 2, 2.5). With 'auto' or other fractions (e.g. 2.75),
// the last slide may not get that class when reaching the end.
// Keeping activeIndex in sync also keeps keyboard focus consistent: focusing
// content in the last slide scrolls it fully into view instead of leaving it cropped.
const applyLastSlideActiveFix = (swiper) => {
// When all slides fit, Swiper keeps isBeginning and isEnd true while activeIndex stays 0.
if (!swiper.isEnd || swiper.isBeginning) {
return
}
// Force the index on the last slide
swiper.activeIndex = swiper.slides.length - 1
// Ask Swiper to update the classes (.swiper-slide-active)
swiper.updateSlidesClasses()
}
const mergedOptions = {
...options,
modules: allModules,
a11y: {
...(slidesAreListItems ? { slideRole: '' } : {}),
...options.a11y,
},
on: {
...options.on,
afterInit: function (swiper) {
hideNavigationButtons(swiper)
// Live region announces nav messages on keyboard prev/next; keep it when
// navigation is exposed to AT, remove it when nav is intentionally hidden.
if (hideNavigationFromA11y) {
swiper.el.querySelector('.swiper-notification')?.remove()
}
options.on?.afterInit?.call(this, swiper)
},
// Swiper resets tabindex on slide change, so we need to hide buttons again
transitionEnd: function (swiper) {
hideNavigationButtons(swiper)
options.on?.transitionEnd?.call(this, swiper)
},
progress: function (swiper, progress) {
if (fixLastSlideActiveOnEnd) {
applyLastSlideActiveFix(swiper)
}
options.on?.progress?.call(this, swiper, progress)
},
slideChange: function (swiper) {
if (fixLastSlideActiveOnEnd) {
applyLastSlideActiveFix(swiper)
}
options.on?.slideChange?.call(this, swiper)
},
},
}
this.swiper = new Swiper(el, mergedOptions)
this.swiper.on('slideChange', onChange.bind(this))
}
/**
* @returns {import('swiper').Swiper}
*/
getInstance() {
return this.swiper
}
}
/**
* @typedef {Object} SliderOptions
* @property {Function} [onChange] - Called on slideChange (`this` = Slider instance)
* @property {boolean} [hideNavigationFromA11y=false] - Hide prev/next from AT when slides are already focusable; also removes `.swiper-notification`
* @property {boolean} [fixLastSlideActiveOnEnd=false] - Fix `.swiper-slide-active` at the end with `slidesPerView: 'auto'` or fractional values other than halves (e.g. 2.75)
* @property {import('swiper').SwiperOptions} [options] - Native Swiper options (merged with defaults)
*/
Slider.defaults = {
onChange: noop,
hideNavigationFromA11y: false,
fixLastSlideActiveOnEnd: false,
options: {
modules: [A11y, Navigation],
a11y: {
prevSlideMessage: __('Previous slide', 'beapi-frontend-framework'),
nextSlideMessage: __('Next slide', 'beapi-frontend-framework'),
firstSlideMessage: __('This is the first slide', 'beapi-frontend-framework'),
lastSlideMessage: __('This is the last slide', 'beapi-frontend-framework'),
paginationBulletMessage: __('Go to slide {{index}}', 'beapi-frontend-framework'),
slideLabelMessage: __('{{index}} of {{slidesLength}}', 'beapi-frontend-framework'),
},
},
}