forked from swiftlang/swift-docc-render
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAdjustableSidebarWidth.vue
521 lines (486 loc) · 15.3 KB
/
AdjustableSidebarWidth.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
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
<!--
This source file is part of the Swift.org open source project
Copyright (c) 2022-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="adjustable-sidebar-width"
:class="{
dragging: isDragging,
'sidebar-hidden': !enableNavigator || hiddenOnLarge
}"
>
<div
v-if="enableNavigator"
ref="sidebar"
class="sidebar"
>
<div
:class="asideClasses"
:style="asideStyles"
class="aside"
ref="aside"
:aria-hidden="hiddenOnLarge ? 'true': null"
@transitionstart.self="trackTransitionStart"
@transitionend.self="trackTransitionEnd"
>
<slot
name="aside"
animationClass="aside-animated-child"
:scrollLockID="scrollLockID"
:breakpoint="breakpoint"
/>
</div>
<div
v-if="!fixedWidth"
class="resize-handle"
@mousedown.prevent="startDrag"
@touchstart.prevent="startDrag"
/>
</div>
<div class="content" ref="content">
<slot />
</div>
<BreakpointEmitter
v-if="enableNavigator"
:scope="BreakpointScopes.nav"
@change="breakpoint = $event"
/>
</div>
</template>
<script>
import { storage } from 'docc-render/utils/storage';
import debounce from 'docc-render/utils/debounce';
import BreakpointEmitter from 'docc-render/components/BreakpointEmitter.vue';
import { BreakpointName, BreakpointScopes } from 'docc-render/utils/breakpoints';
import { waitFor, waitFrames } from 'docc-render/utils/loading';
import scrollLock from 'docc-render/utils/scroll-lock';
import FocusTrap from 'docc-render/utils/FocusTrap';
import changeElementVOVisibility from 'docc-render/utils/changeElementVOVisibility';
import throttle from 'docc-render/utils/throttle';
import { baseNavStickyAnchorId } from 'docc-render/constants/nav';
export const STORAGE_KEY = 'sidebar';
// the maximum width, after which the full-width content does not grow
export const MAX_WIDTH = 1521;
export const ULTRA_WIDE_DEFAULT = 543;
export const LARGE_DEFAULT_WIDTH = 400;
export const eventsMap = {
touch: {
move: 'touchmove',
end: 'touchend',
},
mouse: {
move: 'mousemove',
end: 'mouseup',
},
};
const calcWidthPercent = (percent, windowWidth = window.innerWidth) => {
const maxWidth = Math.min(windowWidth, MAX_WIDTH);
return Math.floor(Math.min(maxWidth * (percent / 100), maxWidth));
};
export const minWidthResponsivePercents = {
medium: 30,
large: 30,
};
export const maxWidthResponsivePercents = {
medium: 50,
large: 40,
};
const SCROLL_LOCK_ID = 'sidebar-scroll-lock';
export default {
name: 'AdjustableSidebarWidth',
constants: {
SCROLL_LOCK_ID,
},
components: {
BreakpointEmitter,
},
inject: ['store'],
props: {
shownOnMobile: {
type: Boolean,
default: false,
},
enableNavigator: {
type: Boolean,
default: true,
},
hiddenOnLarge: {
type: Boolean,
default: false,
},
fixedWidth: {
type: Number,
default: null,
},
},
data() {
const windowWidth = window.innerWidth;
const windowHeight = window.innerHeight;
const breakpoint = BreakpointName.large;
// get the min width, in case we dont have a previously saved value
const minWidth = calcWidthPercent(minWidthResponsivePercents[breakpoint]);
// calc the maximum width
const maxWidth = calcWidthPercent(maxWidthResponsivePercents[breakpoint]);
// have a default width for very large screens, or use half of the min and max
const defaultWidth = windowWidth >= MAX_WIDTH
? ULTRA_WIDE_DEFAULT
: LARGE_DEFAULT_WIDTH;
// get the already stored data, fallback to a default one.
const storedWidth = storage.get(STORAGE_KEY, defaultWidth);
return {
isDragging: false,
// limit the width to a range
width: this.fixedWidth || Math.min(Math.max(storedWidth, minWidth), maxWidth),
isTouch: false,
windowWidth,
windowHeight,
breakpoint,
noTransition: false,
isTransitioning: false,
isOpeningOnLarge: false,
focusTrapInstance: null,
mobileTopOffset: 0,
topOffset: 0,
scrollLockContainer: null,
};
},
computed: {
minWidthPercent: ({ breakpoint }) => minWidthResponsivePercents[breakpoint] || 0,
maxWidthPercent: ({ breakpoint }) => maxWidthResponsivePercents[breakpoint] || 100,
maxWidth: ({ maxWidthPercent, windowWidth, fixedWidth }) => (
Math.max(fixedWidth, calcWidthPercent(maxWidthPercent, windowWidth))
),
minWidth: ({ minWidthPercent, windowWidth, fixedWidth }) => (
Math.min(fixedWidth || windowWidth, calcWidthPercent(minWidthPercent, windowWidth))
),
widthInPx: ({ width }) => `${width}px`,
// Point at which, the nav is hidden/shown for large, when dragging.
hiddenOnLargeThreshold: ({ minWidth }) => minWidth / 2,
events: ({ isTouch }) => (isTouch ? eventsMap.touch : eventsMap.mouse),
asideStyles: ({
widthInPx, mobileTopOffset, topOffset, windowHeight,
}) => ({
width: widthInPx,
'--top-offset': topOffset ? `${topOffset}px` : null,
'--top-offset-mobile': `${mobileTopOffset}px`,
'--app-height': `${windowHeight}px`,
}),
asideClasses: ({
isDragging, shownOnMobile, noTransition, isTransitioning,
hiddenOnLarge, mobileTopOffset, isOpeningOnLarge,
}) => ({
dragging: isDragging,
'show-on-mobile': shownOnMobile,
'hide-on-large': hiddenOnLarge,
'is-opening-on-large': isOpeningOnLarge,
'no-transition': noTransition,
'sidebar-transitioning': isTransitioning,
'has-mobile-top-offset': mobileTopOffset,
}),
scrollLockID: () => SCROLL_LOCK_ID,
BreakpointScopes: () => BreakpointScopes,
},
async mounted() {
window.addEventListener('keydown', this.onEscapeKeydown);
window.addEventListener('resize', this.storeWindowSize, { passive: true });
window.addEventListener('orientationchange', this.storeWindowSize, { passive: true });
this.storeTopOffset();
if (!(this.topOffset === 0 && window.scrollY === 0)) {
window.addEventListener('scroll', this.storeTopOffset, { passive: true });
}
this.$once('hook:beforeDestroy', () => {
window.removeEventListener('keydown', this.onEscapeKeydown);
window.removeEventListener('resize', this.storeWindowSize);
window.removeEventListener('orientationchange', this.storeWindowSize);
window.removeEventListener('scroll', this.storeTopOffset);
if (this.shownOnMobile) {
this.toggleScrollLock(false);
}
if (this.focusTrapInstance) this.focusTrapInstance.destroy();
});
await this.$nextTick();
this.focusTrapInstance = new FocusTrap(this.$refs.aside);
},
watch: {
// make sure a route navigation closes the sidebar
$route: 'closeMobileSidebar',
width: {
immediate: true,
handler: throttle(function widthHandler(value) {
this.emitEventChange(value);
}, 150),
},
windowWidth: 'getWidthInCheck',
async breakpoint(value) {
// adjust the width, so it does not go outside of limits
this.getWidthInCheck();
// make sure we close the nav
if (value === BreakpointName.large) {
this.closeMobileSidebar();
}
// make sure we dont apply transitions for a few moments, to prevent flashes
this.noTransition = true;
// await for a few moments
await waitFrames(5);
// re-apply transitions
this.noTransition = false;
},
shownOnMobile: 'handleExternalOpen',
async isTransitioning(value) {
if (!value) {
this.updateContentWidthInStore();
} else {
// transitionEnd is not guaranteed to fire, so we ensure we stop
// transitioning after some time
await waitFor(1000);
this.isTransitioning = false;
}
},
hiddenOnLarge() {
this.isTransitioning = true;
},
},
methods: {
getWidthInCheck: debounce(function getWidthInCheck() {
// make sure sidebar is never wider than the windowWidth
if (this.width > this.maxWidth) {
this.width = this.maxWidth;
} else if (this.width < this.minWidth) {
this.width = this.minWidth;
}
}, 50),
onEscapeKeydown({ key }) {
if (key === 'Escape') this.closeMobileSidebar();
},
storeWindowSize: throttle(async function storeWindowSize() {
await this.$nextTick();
this.windowWidth = window.innerWidth;
this.windowHeight = window.innerHeight;
this.updateContentWidthInStore();
}, 100),
closeMobileSidebar() {
if (!this.shownOnMobile) return;
this.$emit('update:shownOnMobile', false);
},
startDrag({ type }) {
this.isTouch = type === 'touchstart';
if (this.isDragging) return;
this.isDragging = true;
document.addEventListener(this.events.move, this.handleDrag, { passive: this.isTouch });
document.addEventListener(this.events.end, this.stopDrag);
},
/**
* Handle dragging the resize element
* @param {MouseEvent|TouchEvent} e
*/
handleDrag(e) {
if (!this.isTouch) e.preventDefault();
// we don't want to do anything if we aren't resizing.
if (!this.isDragging) return;
const { sidebar } = this.$refs;
const clientX = this.isTouch ? e.touches[0].clientX : e.clientX;
// make sure we add the window horizontal scroll to the touch position, fixes zoomed in iOS
let newWidth = ((clientX + window.scrollX) - sidebar.offsetLeft);
// prevent going outside of the window zone
if (newWidth > this.maxWidth) {
newWidth = this.maxWidth;
}
// if we are going beyond the cutoff point and we are closed, open the navigator
if (this.hiddenOnLarge && newWidth >= this.hiddenOnLargeThreshold) {
this.$emit('update:hiddenOnLarge', false);
this.isOpeningOnLarge = true;
}
// prevent from shrinking too much
this.width = Math.max(newWidth, this.minWidth);
// if the new width is smaller than the cutoff point, force close the nav
if (newWidth <= this.hiddenOnLargeThreshold) {
this.$emit('update:hiddenOnLarge', true);
}
},
/**
* Stop the dragging upon mouse up
* @param {MouseEvent} e
*/
stopDrag(e) {
e.preventDefault();
if (!this.isDragging) return;
this.isDragging = false;
storage.set(STORAGE_KEY, this.width);
document.removeEventListener(this.events.move, this.handleDrag);
document.removeEventListener(this.events.end, this.stopDrag);
// emit the width, in case the debounce muted the last change
this.emitEventChange(this.width);
},
emitEventChange(width) {
this.$emit('width-change', width);
this.updateContentWidthInStore();
},
getTopOffset() {
const stickyNavAnchor = document.getElementById(baseNavStickyAnchorId);
if (!stickyNavAnchor) return 0;
const { y } = stickyNavAnchor.getBoundingClientRect();
return Math.max(y, 0);
},
handleExternalOpen(isOpen) {
if (isOpen) {
this.mobileTopOffset = this.getTopOffset();
}
this.toggleScrollLock(isOpen);
},
async updateContentWidthInStore() {
await this.$nextTick();
this.store.setContentWidth(this.$refs.content.offsetWidth);
},
/**
* Toggles the scroll lock on/off
*/
async toggleScrollLock(lock) {
// if applicable, turn off lock on previous container
if (this.scrollLockContainer) {
scrollLock.unlockScroll(this.scrollLockContainer);
this.focusTrapInstance.stop();
changeElementVOVisibility.show(this.$refs.aside);
this.scrollLockContainer = null;
}
if (lock) {
await this.$nextTick();
this.scrollLockContainer = document.getElementById(this.scrollLockID);
if (this.scrollLockContainer) {
scrollLock.lockScroll(this.scrollLockContainer);
// lock focus
this.focusTrapInstance.start();
// hide sibling elements from VO
changeElementVOVisibility.hide(this.$refs.aside);
}
}
},
storeTopOffset: throttle(function storeTopOffset() {
this.topOffset = this.getTopOffset();
}, 60),
async trackTransitionStart({ propertyName }) {
if (propertyName === 'width' || propertyName === 'transform') {
this.isTransitioning = true;
}
},
trackTransitionEnd({ propertyName }) {
if (propertyName === 'width' || propertyName === 'transform') {
this.isTransitioning = false;
this.isOpeningOnLarge = false;
}
},
},
};
</script>
<style scoped lang='scss'>
@import 'docc-render/styles/_core.scss';
@media print {
.sidebar {
display: none;
}
}
.adjustable-sidebar-width {
display: flex;
@include breakpoint(medium, nav) {
display: block;
position: relative;
}
&.dragging :deep(*) {
cursor: col-resize !important;
}
&.sidebar-hidden.dragging :deep(*) {
cursor: e-resize !important;
}
}
.sidebar {
position: relative;
@include breakpoint(medium, nav) {
position: static;
}
}
.aside {
width: 250px;
position: relative;
height: 100%;
max-width: 100vw;
&.no-transition {
transition: none !important;
}
@include breakpoints-from(large, nav) {
// apply a default transition
transition: width $adjustable-sidebar-hide-transition-duration ease-in,
visibility 0s linear var(--visibility-transition-time, 0s);
// Remove the transition when dragging, except when hidden or exiting hidden state.
// This prevents lagging when dragging, because of the transition delay.
&.dragging:not(.is-opening-on-large):not(.hide-on-large) {
transition: none;
}
&.hide-on-large {
width: 0 !important;
visibility: hidden;
pointer-events: none;
--visibility-transition-time: #{$adjustable-sidebar-hide-transition-duration};
}
}
@include breakpoint(medium, nav) {
width: 100% !important;
overflow: hidden;
min-width: 0;
max-width: 100%;
height: calc(var(--app-height) - var(--top-offset-mobile));
position: fixed;
top: var(--top-offset-mobile);
bottom: 0;
left: 0;
z-index: $nav-z-index + 1;
transform: translateX(-100%);
transition: transform var(--nav-transition-duration) ease-in;
left: 0;
:deep(.aside-animated-child) {
opacity: 0;
}
&.show-on-mobile {
transform: translateX(0);
:deep(.aside-animated-child) {
--index: 0;
opacity: 1;
transition: opacity var(--nav-transition-duration) linear;
transition-delay:
calc(var(--index) * var(--nav-transition-duration) + var(--nav-transition-duration));
}
}
&.has-mobile-top-offset {
border-top: 1px solid var(--color-fill-gray-tertiary);
}
}
}
.content {
display: flex;
flex-flow: column;
min-width: 0;
flex: 1 1 auto;
height: 100%;
}
.resize-handle {
position: absolute;
cursor: col-resize;
top: 0;
bottom: 0;
right: 0;
width: 5px;
height: 100%;
user-select: none;
z-index: 1;
transition: background-color .15s;
transform: translateX(50%);
@include breakpoint(medium, nav) {
display: none;
}
&:hover {
background: var(--color-fill-gray-tertiary);
}
}
</style>