forked from swiftlang/swift-docc-render
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPager.vue
392 lines (360 loc) · 10.7 KB
/
Pager.vue
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
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
<!--
This source file is part of the Swift.org open source project
Copyright (c) 2024 Apple Inc. and the Swift project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See https://swift.org/LICENSE.txt for license information
See https://swift.org/CONTRIBUTORS.txt for Swift project authors
-->
<template>
<div
:class="['pager', { 'with-compact-controls': shouldUseCompactControls }]"
role="region"
:aria-roledescription="$t('pager.roledescription')"
>
<template v-if="pages.length === 1">
<slot name="page" :page="pages[0]" />
</template>
<template v-else>
<div class="container">
<Gutter class="left">
<ControlPrevious
:disabled="!hasPreviousPage"
@click.native="previous"
/>
</Gutter>
<div class="viewport" ref="viewport" role="group">
<div
v-for="({ page, key }, n) in keyedPages"
ref="pages"
:aria-label="$t('pager.page.label', { index: n + 1, count: keyedPages.length })"
:class="['page', pageStates(n)]"
:id="key"
:key="key"
>
<slot name="page" :page="page" />
</div>
</div>
<Gutter class="right">
<ControlNext
:disabled="!hasNextPage"
@click.native="next"
/>
</Gutter>
</div>
<div class="compact-controls" role="group" aria-label="Controls">
<ControlPrevious
:disabled="!hasPreviousPage"
@click.native="previous"
/>
<ControlNext
:disabled="!hasNextPage"
@click.native="next"
/>
</div>
<div class="indicators">
<a
v-for="({ key }, n) in keyedPages"
:aria-current="isActivePage(n)"
:href="`#${key}`"
:key="key"
:class="['indicator', pageStates(n)]"
@click="setActivePage($event, n)"
/>
</div>
</template>
<slot />
</div>
</template>
<script>
import PagerControl from 'docc-render/components/PagerControl.vue';
import { BreakpointAttributes } from 'docc-render/utils/breakpoints';
import DocumentationTopicStore from 'docc-render/stores/DocumentationTopicStore';
const GUTTERS_WIDTH = 174;
function waitForScrollIntoView(element) {
// call `scrollIntoView` to start asynchronously scrollling the off-screen
// page element into the viewport area (would be sync if the behavior is
// instant, but there is an async animation for "smooth" behavior)
element.scrollIntoView({
behavior: 'auto',
block: 'nearest',
inline: 'start',
});
// until the "scrollend" event is more widely supported, we need to manually
// poll every animation frame to manually check if the element is still being
// scrolled or not
return new Promise((resolve) => {
// scroll animation shouldn't realistically take longer than this, so this
// will be used as a timeout to exit early and avoid looping forever if
// something goes wrong down below
const maxFramesToWait = 60;
// shouldn't realistically go quicker than a couple frames either
const minFramesToWait = 2;
// since the scroll animation is not necessarily immediate, we'll utilize
// `requestAnimationFrame` to poll every frame and check if the element
// has finished scrolling and wait to finish the promise until it has
// finished (or we reach a timeout expressed as a maximum number of frames
// to wait for)
let prevLeftPosition = null;
let numFramesWaited = 0;
function waitForScrollEnd() {
const currentLeftPosition = element.getBoundingClientRect().left;
// stop waiting and resolve the promise if the timeout is reached or the
// scroll has finished as calculated from the element position
if ((numFramesWaited > minFramesToWait)
&& ((currentLeftPosition === prevLeftPosition)
|| (numFramesWaited >= maxFramesToWait))) {
resolve(); // done waiting
} else {
// otherwise, advance to the next frame to check again by recursively
// calling this function
prevLeftPosition = currentLeftPosition;
numFramesWaited += 1;
requestAnimationFrame(waitForScrollEnd); // continue waiting
}
}
requestAnimationFrame(waitForScrollEnd); // start waiting
});
}
/**
* Provides a way of viewing one of many pages of content at a time.
*
* This component is similar to what is sometimes referred to as a "carousel"
* of content. Users of this component specify an array of "pages" and can
* specify how individual pages are presented through slots.
*
* ### Example
*
* As an example, this is how you could present a pager, which pages between
* a few different paragraphs. Only one will be shown at a time, and there
* will be controls to select which paragraph is currently showing.
*
* ```html
* <Pager :pages="['a', 'b', 'c']">
* <template #page="{ page }">
* <p>{{ page }}</p>
* </template>
* </Pager>
* ```
*
* - Parameter pages: `Array` (**required**) - An non-empty array of any kind of
* content—each individual item will be provided as a prop to `page` slots.
*/
export default {
name: 'Pager',
components: {
ControlNext: {
render(createElement) {
return createElement(PagerControl, {
props: { action: PagerControl.Action.next },
});
},
},
ControlPrevious: {
render(createElement) {
return createElement(PagerControl, {
props: { action: PagerControl.Action.previous },
});
},
},
Gutter: {
render(createElement) {
return createElement('div', { class: 'gutter' }, (
this.$slots.default
));
},
},
},
props: {
pages: {
type: Array,
required: true,
validator: value => value.length > 0,
},
},
data: () => ({
activePageIndex: 0,
appState: DocumentationTopicStore.state,
}),
computed: {
indices: ({ keyedPages }) => keyedPages.reduce((obj, item, i) => ({
...obj,
[item.key]: i,
}), {}),
keyedPages: ({ _uid, pages }) => pages.map((page, i) => ({
key: `pager-${_uid}-page-${i}`,
page,
})),
hasNextPage: ({ activePageIndex, pages }) => activePageIndex < (pages.length - 1),
hasPreviousPage: ({ activePageIndex }) => activePageIndex > 0,
contentWidth: ({ appState }) => (appState.contentWidth),
shouldUseCompactControls: ({ contentWidth }) => {
if (window.innerWidth > BreakpointAttributes.default.large.minWidth) {
return contentWidth < BreakpointAttributes.default.large.contentWidth + GUTTERS_WIDTH;
}
return contentWidth < BreakpointAttributes.default.medium.contentWidth + GUTTERS_WIDTH;
},
},
methods: {
isActivePage(index) {
return index === this.activePageIndex;
},
pageStates(index) {
return { active: this.isActivePage(index) };
},
async setActivePage(event, index) {
event.preventDefault();
if ((index === this.activePageIndex)
|| (index < 0)
|| (index >= this.$refs.pages.length)) {
return;
}
const ref = this.$refs.pages[index];
// stop observing page elements visibility while scrolling to the active
// one so that the indicators for pages in between the previous and
// currently active one don't activate
this.pauseObservingPages();
await waitForScrollIntoView(ref);
this.startObservingPages();
this.activePageIndex = index;
},
next(event) {
this.setActivePage(event, this.activePageIndex + 1);
},
previous(event) {
this.setActivePage(event, this.activePageIndex - 1);
},
observePages(entries) {
// observe page visibility so that we can activate the indicator for the
// right one as the user scrolls through the viewport
const visibleKey = entries.find(entry => entry.isIntersecting)?.target?.id;
if (visibleKey) {
this.activePageIndex = this.indices[visibleKey];
}
},
setupObserver() {
this.observer = new IntersectionObserver(this.observePages, {
root: this.$refs.viewport,
threshold: 0.5,
});
this.startObservingPages();
},
startObservingPages() {
this.$refs.pages.forEach((page) => {
this.observer?.observe(page);
});
},
pauseObservingPages() {
this.$refs.pages.forEach((page) => {
this.observer?.unobserve(page);
});
},
},
mounted() {
if (this.pages.length > 1) {
this.setupObserver();
}
},
beforeDestroy() {
this.observer?.disconnect();
},
};
</script>
<style scoped lang="scss">
@import 'docc-render/styles/_core.scss';
.pager {
--control-size: 3em;
--control-color-fill: var(--color-fill-tertiary);
--control-color-figure: currentColor;
--indicator-size: 0.65em;
--indicator-color-fill-active: currentColor;
--indicator-color-fill-inactive: var(--color-fill-tertiary);
--color-svg-icon: currentColor;
--gutter-width: #{$large-viewport-dynamic-content-padding};
}
.viewport {
display: flex;
overflow-x: auto;
scroll-behavior: smooth;
scroll-snap-type: x mandatory;
scrollbar-width: none;
-webkit-overflow-scrolling: touch;
&::-webkit-scrollbar {
height: 0;
width: 0;
}
}
.container {
position: relative;
}
.gutter {
align-items: center;
display: flex;
justify-content: center;
position: absolute;
height: 100%;
top: 0;
width: var(--gutter-width);
z-index: 42;
.with-compact-controls & {
display: none;
}
&.left {
left: calc(var(--gutter-width) * -1);
}
&.right {
right: calc(var(--gutter-width) * -1);
}
}
.page {
flex-shrink: 0;
margin-right: var(--gutter-width);
position: relative;
scroll-snap-align: start;
transform: scale(1);
transform-origin: center center;
transition: transform 0.5s ease-in-out;
user-select: none;
width: 100%;
@media (prefers-reduced-motion) {
transition: none;
}
&.active {
user-select: auto;
}
}
.gutter .pager-control {
margin-top: calc(-1 * var(--control-size));
}
.indicators {
display: flex;
flex-wrap: wrap;
gap: 1em;
justify-content: center;
margin-top: 1rem;
.with-compact-controls & {
display: none;
}
}
.indicator {
background: var(--indicator-color-fill-inactive);
border: 1px solid var(--indicator-color-fill-inactive);
border-radius: 50%;
color: currentColor;
display: block;
flex: 0 0 auto;
height: var(--indicator-size);
width: var(--indicator-size);
&.active {
background: var(--indicator-color-fill-active);
border-color: var(--indicator-color-fill-active);
}
}
.compact-controls {
display: none;
gap: 1em;
justify-content: flex-end;
.with-compact-controls & {
display: flex;
}
}
</style>