-
Notifications
You must be signed in to change notification settings - Fork 493
/
Copy pathCustomScrollbar.ts
547 lines (481 loc) · 18.5 KB
/
CustomScrollbar.ts
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
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
/**
* CustomScrollbar.ts
*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT license.
*
* Custom scrollbar implementation for web.
*/
import * as React from 'react';
import assert from '../common/assert';
import Timers from '../common/utils/Timers';
const UNIT = 'px';
const SCROLLER_MIN_SIZE = 15;
const SCROLLER_NEGATIVE_MARGIN = 30;
const NEUTRAL_OVERRIDE_CLASS = 'neutraloverride';
interface ScrollbarInfo {
size?: number;
scrollSize?: number;
scroll2Slider?: number;
slider2Scroll?: number;
sliderSize?: number;
dragOffset?: number;
rail?: HTMLElement;
slider?: HTMLElement;
}
export interface ScrollbarOptions {
horizontal?: boolean;
vertical?: boolean;
hiddenScrollbar?: boolean;
}
let _nativeSrollBarWidth = -1;
let _isStyleSheetInstalled = false;
const _customScrollbarCss = `
.rxCustomScroll .scrollViewport > * {
box-sizing: border-box;
display: block;
}
.rxCustomScroll .rail {
position: absolute;
border-radius: 4px;
opacity: 0;
background-color: transparent;
transition-delay: 0, 0;
transition-duration: .2s, .2s;
transition-property: background-color, opacity;
transition-timing-function: linear, linear;
display: none;
box-sizing: border-box;
}
.rxCustomScroll .rail:hover {
background-color: #EEE;
border-color: #EEE;
opacity: .9;
border-radius: 6px;
}
.rxCustomScroll .rail:hover .slider {
border-radius: 6px;
}
.rxCustomScroll .rail .slider {
position: absolute;
border-radius: 4px;
background: #555;
box-sizing: border-box;
border: 1px solid #555;
}
.rxCustomScroll:not(.neutraloverride) > .scrollViewportV > * {
margin-right: em(-17px) !important;
}
.rxCustomScroll .railV {
top: 0;
bottom: 0;
right: 3px;
width: 8px;
}
.rxCustomScroll .railV .slider {
top: 10px;
width: 8px;
min-height: 15px;
}
.rxCustomScroll .railV.railBoth {
bottom: 15px;
}
.rxCustomScroll .railH {
left: 0;
right: 0;
bottom: 3px;
height: 8px;
}
.rxCustomScroll .railH .slider {
left: 10px;
top: -1px;
height: 8px;
min-width: 15px;
}
.rxCustomScroll .railH.railBoth {
right: 15px;
}
.rxCustomScroll.active .rail {
display: block;
}
.rxCustomScroll:hover .rail {
opacity: .6;
}
.rxCustomScroll:hover .rail .slider {
background: #AAA;
border-color: #AAA;
}
.rxCustomScroll.rxCustomScrollH {
width: auto;
}
.rxCustomScroll.rxCustomScrollV {
width: 100%;
}
.rxCustomScroll.scrolling .rail {
background-color: #EEE;
border-color: #EEE;
opacity: .9;
border-radius: 6px;
}
.rxCustomScroll.scrolling .rail .slider {
border-radius: 6px;
background: #AAA;
border-color: #AAA;
}
.rxCustomScroll.scrolling .scrollViewport > * {
pointer-events: none !important;
}
.rxCustomScroll.scrolling .railV {
width: 12px;
}
.rxCustomScroll.scrolling .railV .slider {
width: 12px;
}
.rxCustomScroll.scrolling .railH {
height: 12px;
}
.rxCustomScroll.scrolling .railH .slider {
height: 12px;
}
.rxCustomScroll .railV:hover {
width: 12px;
}
.rxCustomScroll .railV:hover .slider {
width: 12px;
}
.rxCustomScroll .railH:hover {
height: 12px;
}
.rxCustomScroll .railH:hover .slider {
height: 12px;
}
`;
export class Scrollbar {
private _container: HTMLElement;
private _verticalBar: ScrollbarInfo = {};
private _horizontalBar: ScrollbarInfo = {};
// Viewport will always be initialized before it's used
private _viewport!: HTMLElement;
private _dragging = false;
private _dragIsVertical = false;
private _scrollingVisible = false;
private _hasHorizontal = false;
private _hasVertical = true;
private _hasHiddenScrollbar = false;
private _stopDragCallback = this._stopDrag.bind(this);
private _startDragVCallback = this._startDrag.bind(this, true);
private _startDragHCallback = this._startDrag.bind(this, false);
private _handleDragCallback = this._handleDrag.bind(this);
private _handleWheelCallback = this._handleWheel.bind(this);
private _handleMouseDownCallback = this._handleMouseDown.bind(this);
private _updateCallback = this.update.bind(this);
private _asyncInitTimer: number | undefined;
static getNativeScrollbarWidth(): number {
// Have we cached the value alread?
if (_nativeSrollBarWidth >= 0) {
return _nativeSrollBarWidth;
}
const inner = document.createElement('p');
inner.style.width = '100%';
inner.style.height = '100%';
const outer = document.createElement('div');
outer.style.position = 'absolute';
outer.style.top = '0';
outer.style.left = '0';
outer.style.visibility = 'hidden';
outer.style.width = '100px';
outer.style.height = '100px';
outer.style.overflow = 'hidden';
outer.appendChild(inner);
document.body.appendChild(outer);
const w1 = inner.offsetWidth;
outer.style.overflow = 'scroll';
let w2 = inner.offsetWidth;
if (w1 === w2) {
w2 = outer.clientWidth;
}
document.body.removeChild(outer);
_nativeSrollBarWidth = w1 - w2;
return _nativeSrollBarWidth;
}
private static _installStyleSheet(): void {
// Have we installed the style sheet already?
if (_isStyleSheetInstalled) {
return;
}
// We set the CSS style sheet here to avoid the need
// for users of this class to carry along another CSS
// file.
const head = document.head || document.getElementsByTagName('head')[0];
const style = document.createElement('style') as any;
style.type = 'text/css';
if (style.styleSheet) {
style.styleSheet.cssText = _customScrollbarCss;
} else {
style.appendChild(document.createTextNode(_customScrollbarCss));
}
head.appendChild(style);
_isStyleSheetInstalled = true;
}
constructor(container: HTMLElement) {
assert(container, 'Container must not be null');
this._container = container;
}
private _tryLtrOverride(): void {
const rtlbox = document.createElement('div');
rtlbox.style.cssText = 'position: absolute; overflow-y: scroll; width: 30px; visibility: hidden;';
rtlbox.innerHTML = '<div class="probe"></div>';
this._container.appendChild(rtlbox);
const probe = rtlbox.querySelector('.probe')!;
const rtlboxRect = rtlbox.getBoundingClientRect();
const probeRect = probe.getBoundingClientRect();
const isLeftBound = rtlboxRect.left === probeRect.left;
const isRightBound = rtlboxRect.right === probeRect.right;
const isNeutral = isLeftBound && isRightBound;
this._container.classList.remove(NEUTRAL_OVERRIDE_CLASS);
if (isNeutral) {
this._container.classList.add(NEUTRAL_OVERRIDE_CLASS);
}
rtlbox.innerHTML = '';
this._container.removeChild(rtlbox);
}
private _prevent(e: React.SyntheticEvent<any>): void {
e.preventDefault();
}
private _updateSliders(): void {
if (this._hasHorizontal) {
// Read from DOM before we write back
const newSliderWidth = this._horizontalBar.sliderSize + UNIT;
const newSliderLeft = this._viewport.scrollLeft * this._horizontalBar.scroll2Slider! + UNIT;
this._horizontalBar.slider!.style.width = newSliderWidth;
this._horizontalBar.slider!.style.left = newSliderLeft;
}
if (this._hasVertical) {
// Read from DOM before we write back
const newSliderHeight = this._verticalBar.sliderSize + UNIT;
const newSliderTop = this._viewport.scrollTop * this._verticalBar.scroll2Slider! + UNIT;
this._verticalBar.slider!.style.height = newSliderHeight;
this._verticalBar.slider!.style.top = newSliderTop;
}
}
private _handleDrag(e: React.MouseEvent<any>): void {
if (this._dragIsVertical) {
this._viewport.scrollTop = (e.pageY - this._verticalBar.dragOffset!) * this._verticalBar.slider2Scroll!;
} else {
this._viewport.scrollLeft = (e.pageX - this._horizontalBar.dragOffset!) * this._horizontalBar.slider2Scroll!;
}
}
private _startDrag(dragIsVertical: boolean, e: React.MouseEvent<any>): void {
if (!this._dragging) {
window.addEventListener('mouseup', this._stopDragCallback);
window.addEventListener('mousemove', this._handleDragCallback);
this._container.classList.add('scrolling');
if (this._hasHorizontal) {
this._horizontalBar.dragOffset = e.pageX - this._horizontalBar.slider!.offsetLeft;
}
if (this._hasVertical) {
this._verticalBar.dragOffset = e.pageY - this._verticalBar.slider!.offsetTop;
}
this._dragging = true;
this._dragIsVertical = dragIsVertical;
}
this._prevent(e);
}
private _stopDrag(): void {
this._container.classList.remove('scrolling');
window.removeEventListener('mouseup', this._stopDragCallback);
window.removeEventListener('mousemove', this._handleDragCallback);
this._dragging = false;
}
private _handleWheel(e: React.WheelEvent<any>): void {
// Always prefer the vertical axis if present. User can override with the control key.
if (this._hasVertical) {
this._viewport.scrollTop = this._normalizeDelta(e) + this._viewport.scrollTop;
} else if (this._hasHorizontal) {
this._viewport.scrollLeft = this._normalizeDelta(e) + this._viewport.scrollLeft;
}
}
private _handleMouseDown(e: React.MouseEvent<HTMLElement>): void {
const target = e.currentTarget;
if (this._dragging || !target) {
this._prevent(e);
return;
}
if (this._hasVertical) {
const eventOffsetY = e.pageY - target.getBoundingClientRect().top;
const halfHeight = this._verticalBar.slider!.offsetHeight / 2;
const offsetY = (eventOffsetY - this._verticalBar.slider!.offsetTop - halfHeight) * this._verticalBar.slider2Scroll!;
this._viewport.scrollTop = offsetY + this._viewport.scrollTop;
}
if (this._hasHorizontal) {
const eventOffsetX = e.pageX - target.getBoundingClientRect().left;
const halfWidth = this._horizontalBar.slider!.offsetWidth / 2;
const offsetX = (eventOffsetX - this._horizontalBar.slider!.offsetLeft - halfWidth) * this._horizontalBar.slider2Scroll!;
this._viewport.scrollLeft = offsetX + this._viewport.scrollLeft;
}
}
private _normalizeDelta(e: React.WheelEvent<any>): number {
if (e.deltaY) {
return e.deltaY > 0 ? 100 : -100;
}
const originalEvent = (e as any).originalEvent;
if (originalEvent && originalEvent.wheelDelta) {
return originalEvent.wheelDelta;
}
return 0;
}
private _addListeners(): void {
if (this._hasVertical) {
this._verticalBar.slider!.addEventListener('mousedown', this._startDragVCallback);
this._verticalBar.rail!.addEventListener('wheel', this._handleWheelCallback, { passive: true });
this._verticalBar.rail!.addEventListener('mousedown', this._handleMouseDownCallback);
}
if (this._hasHorizontal) {
this._horizontalBar.slider!.addEventListener('mousedown', this._startDragHCallback);
this._horizontalBar.rail!.addEventListener('wheel', this._handleWheelCallback, { passive: true });
this._horizontalBar.rail!.addEventListener('mousedown', this._handleMouseDownCallback);
}
}
private _removeListeners(): void {
if (this._hasVertical) {
this._verticalBar.slider!.removeEventListener('mousedown', this._startDragVCallback);
this._verticalBar.rail!.removeEventListener('wheel', this._handleWheelCallback);
this._verticalBar.rail!.removeEventListener('mousedown', this._handleMouseDownCallback);
}
if (this._hasHorizontal) {
this._horizontalBar.slider!.removeEventListener('mousedown', this._startDragHCallback);
this._horizontalBar.rail!.removeEventListener('wheel', this._handleWheelCallback);
this._horizontalBar.rail!.removeEventListener('mousedown', this._handleMouseDownCallback);
}
}
private _createDivWithClass(className: string): HTMLElement {
const div = document.createElement('div');
div.setAttribute('role', 'none');
div.className = className;
return div;
}
private _addScrollBar(scrollbarInfo: ScrollbarInfo, railClass: string, hasBoth: boolean): void {
const slider = this._createDivWithClass('slider');
scrollbarInfo.rail = this._createDivWithClass('rail ' + railClass + (hasBoth ? ' railBoth' : ''));
scrollbarInfo.slider = slider;
scrollbarInfo.rail.appendChild(slider);
this._container.appendChild(scrollbarInfo.rail);
}
private _addScrollbars(): void {
const containerClass = this._hasVertical ? 'rxCustomScrollV' : 'rxCustomScrollH';
if (this._hasVertical) {
this._addScrollBar(this._verticalBar, 'railV', this._hasHorizontal);
}
if (this._hasHorizontal) {
this._addScrollBar(this._horizontalBar, 'railH', this._hasVertical);
}
this._container.classList.add(containerClass);
this._container.classList.add('rxCustomScroll');
this._viewport = this._container.querySelector('.scrollViewport') as HTMLElement;
}
private _removeScrollbars(): void {
if (this._hasVertical) {
this._verticalBar.rail!.innerHTML = '';
this._container.removeChild(this._verticalBar.rail!);
}
if (this._hasHorizontal) {
this._horizontalBar.rail!.innerHTML = '';
this._container.removeChild(this._horizontalBar.rail!);
}
}
private _calcNewBarSize(bar: ScrollbarInfo, newSize: number, newScrollSize: number, hasBoth: boolean): void {
if (hasBoth || this._hasHiddenScrollbar) {
newSize -= SCROLLER_NEGATIVE_MARGIN;
newScrollSize -= SCROLLER_NEGATIVE_MARGIN - Scrollbar.getNativeScrollbarWidth();
}
if (newScrollSize !== bar.scrollSize || newSize !== bar.size) {
bar.size = newSize;
bar.scrollSize = newScrollSize;
bar.scroll2Slider = newSize / newScrollSize;
bar.sliderSize = newSize * bar.scroll2Slider;
// Don't allow the sliders to overlap.
if (hasBoth) {
bar.sliderSize = Math.max(bar.sliderSize - SCROLLER_NEGATIVE_MARGIN + Scrollbar.getNativeScrollbarWidth(), 0);
}
if (bar.sliderSize < SCROLLER_MIN_SIZE) {
const railRange = newSize - SCROLLER_MIN_SIZE + bar.sliderSize;
bar.scroll2Slider = railRange / newScrollSize;
bar.slider2Scroll = newScrollSize / railRange;
} else {
bar.slider2Scroll = newScrollSize / newSize;
}
}
}
private _resize(): void {
if (this._hasHorizontal) {
this._calcNewBarSize(this._horizontalBar, this._viewport.offsetWidth, this._viewport.scrollWidth, this._hasVertical);
}
if (this._hasVertical) {
this._calcNewBarSize(this._verticalBar, this._viewport.offsetHeight, this._viewport.scrollHeight, this._hasHorizontal);
}
}
update(): void {
this._resize();
// We add one below to provide a small fudge factor because browsers round their scroll and offset values to the
// nearest integer, and IE sometimes ends up returning a scroll and offset value that are off by one.
if ((this._verticalBar && this._verticalBar.scrollSize! > this._verticalBar.size! + 1) ||
(this._horizontalBar && this._horizontalBar.scrollSize! > this._horizontalBar.size! + 1)) {
this.show();
this._updateSliders();
} else {
this.hide();
}
}
show(): void {
if (!this._scrollingVisible) {
this._container.classList.add('active');
this._addListeners();
this._scrollingVisible = true;
}
}
hide(): void {
if (this._scrollingVisible) {
this._container.classList.remove('active');
this._removeListeners();
this._scrollingVisible = false;
}
}
init(options?: ScrollbarOptions): void {
if (options) {
this._hasHorizontal = !!options.horizontal;
// Only if vertical is explicitly false as opposed to null, set it to false (default is true)
if (options.vertical === false) {
this._hasVertical = options.vertical;
}
// Our container may be scrollable even if the corresponding scrollbar is hidden (i.e. vertical
// or horizontal is false). We have to take it into account when calculating scroll bar sizes.
this._hasHiddenScrollbar = !!options.hiddenScrollbar;
}
Scrollbar._installStyleSheet();
this._addScrollbars();
this.show();
this._container.addEventListener('mouseenter', this._updateCallback);
// Defer remaining init work to avoid triggering sync layout
this._asyncInitTimer = Timers.setTimeout(() => {
this._asyncInitTimer = undefined;
this._tryLtrOverride();
this.update();
}, 0);
}
dispose(): void {
if (this._asyncInitTimer) {
Timers.clearInterval(this._asyncInitTimer);
this._asyncInitTimer = undefined;
}
this._stopDrag();
this._container.removeEventListener('mouseenter', this._updateCallback);
this.hide();
this._removeScrollbars();
// release DOM nodes
this._container = null!;
this._viewport = null!;
this._verticalBar = null!;
this._horizontalBar = null!;
}
}
export default Scrollbar;