/
PostStreamScrubber.js
330 lines (275 loc) · 12.2 KB
/
PostStreamScrubber.js
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
import app from '../../forum/app';
import Component from '../../common/Component';
import icon from '../../common/helpers/icon';
import formatNumber from '../../common/utils/formatNumber';
import ScrollListener from '../../common/utils/ScrollListener';
/**
* The `PostStreamScrubber` component displays a scrubber which can be used to
* navigate/scrub through a post stream.
*
* ### Attrs
*
* - `stream`
* - `className`
*/
export default class PostStreamScrubber extends Component {
oninit(vnode) {
super.oninit(vnode);
this.stream = this.attrs.stream;
this.handlers = {};
this.scrollListener = new ScrollListener(this.updateScrubberValues.bind(this, { fromScroll: true, forceHeightChange: true }));
}
view() {
const count = this.stream.count();
// Index is left blank for performance reasons, it is filled in in updateScubberValues
const viewing = app.translator.trans('core.forum.post_scrubber.viewing_text', {
count,
index: <span className="Scrubber-index"></span>,
formattedCount: <span className="Scrubber-count">{formatNumber(count)}</span>,
});
const unreadCount = this.stream.discussion.unreadCount();
const unreadPercent = count ? Math.min(count - this.stream.index, unreadCount) / count : 0;
function styleUnread(vnode) {
const $element = $(vnode.dom);
const newStyle = {
top: 100 - unreadPercent * 100 + '%',
height: unreadPercent * 100 + '%',
opacity: unreadPercent ? 1 : 0,
};
if (vnode.state.oldStyle) {
$element.stop(true).css(vnode.state.oldStyle).animate(newStyle);
} else {
$element.css(newStyle);
}
vnode.state.oldStyle = newStyle;
}
const classNames = ['PostStreamScrubber', 'Dropdown'];
if (this.attrs.className) classNames.push(this.attrs.className);
return (
<div className={classNames.join(' ')}>
<button className="Button Dropdown-toggle" data-toggle="dropdown">
{viewing} {icon('fas fa-sort')}
</button>
<div className="Dropdown-menu dropdown-menu">
<div className="Scrubber">
<a className="Scrubber-first" onclick={this.goToFirst.bind(this)}>
{icon('fas fa-angle-double-up')} {app.translator.trans('core.forum.post_scrubber.original_post_link')}
</a>
<div className="Scrubber-scrollbar">
<div className="Scrubber-before" />
<div className="Scrubber-handle">
<div className="Scrubber-bar" />
<div className="Scrubber-info">
<strong>{viewing}</strong>
<span className="Scrubber-description"></span>
</div>
</div>
<div className="Scrubber-after" />
<div className="Scrubber-unread" oncreate={styleUnread} onupdate={styleUnread}>
{app.translator.trans('core.forum.post_scrubber.unread_text', { count: unreadCount })}
</div>
</div>
<a className="Scrubber-last" onclick={this.goToLast.bind(this)}>
{icon('fas fa-angle-double-down')} {app.translator.trans('core.forum.post_scrubber.now_link')}
</a>
</div>
</div>
</div>
);
}
onupdate(vnode) {
super.onupdate(vnode);
if (this.stream.forceUpdateScrubber) {
this.stream.forceUpdateScrubber = false;
this.stream.loadPromise.then(() => this.updateScrubberValues({ animate: true, forceHeightChange: true }));
}
}
oncreate(vnode) {
super.oncreate(vnode);
// Whenever the window is resized, adjust the height of the scrollbar
// so that it fills the height of the sidebar.
$(window)
.on('resize', (this.handlers.onresize = this.onresize.bind(this)))
.resize();
// When any part of the whole scrollbar is clicked, we want to jump to
// that position.
this.$('.Scrubber-scrollbar')
.bind('click', this.onclick.bind(this))
// Now we want to make the scrollbar handle draggable. Let's start by
// preventing default browser events from messing things up.
.bind('dragstart mousedown touchstart', (e) => e.preventDefault());
// When the mouse is pressed on the scrollbar handle, we capture some
// information about its current position. We will store this
// information in an object and pass it on to the document's
// mousemove/mouseup events later.
this.dragging = false;
this.mouseStart = 0;
this.indexStart = 0;
this.$('.Scrubber-handle')
.bind('mousedown touchstart', this.onmousedown.bind(this))
// Exempt the scrollbar handle from the 'jump to' click event.
.click((e) => e.stopPropagation());
// When the mouse moves and when it is released, we pass the
// information that we captured when the mouse was first pressed onto
// some event handlers. These handlers will move the scrollbar/stream-
// content as appropriate.
$(document)
.on('mousemove touchmove', (this.handlers.onmousemove = this.onmousemove.bind(this)))
.on('mouseup touchend', (this.handlers.onmouseup = this.onmouseup.bind(this)));
setTimeout(() => this.scrollListener.start());
this.stream.loadPromise.then(() => this.updateScrubberValues({ animate: false, forceHeightChange: true }));
}
onremove(vnode) {
super.onremove(vnode);
this.scrollListener.stop();
$(window).off('resize', this.handlers.onresize);
$(document).off('mousemove touchmove', this.handlers.onmousemove).off('mouseup touchend', this.handlers.onmouseup);
}
/**
* Update the scrollbar's position to reflect the current values of the
* index/visible properties.
*
* @param {Partial<{fromScroll: boolean, forceHeightChange: boolean, animate: boolean}>} options
*/
updateScrubberValues(options = {}) {
const index = this.stream.index;
const count = this.stream.count();
const visible = this.stream.visible || 1;
const percentPerPost = this.percentPerPost();
const $scrubber = this.$();
$scrubber.find('.Scrubber-index').text(formatNumber(this.stream.sanitizeIndex(Math.max(1, index))));
$scrubber.find('.Scrubber-description').text(this.stream.description);
$scrubber.toggleClass('disabled', this.stream.disabled());
const heights = {};
heights.before = Math.max(0, percentPerPost.index * Math.min(index - 1, count - visible));
heights.handle = Math.min(100 - heights.before, percentPerPost.visible * visible);
heights.after = 100 - heights.before - heights.handle;
// If the stream is paused, don't change height on scroll, as the viewport is being scrolled by the JS
// If a height change animation is already in progress, don't adjust height unless overriden
if ((options.fromScroll && this.stream.paused) || (this.adjustingHeight && !options.forceHeightChange)) return;
const func = options.animate ? 'animate' : 'css';
this.adjustingHeight = true;
const animationPromises = [];
for (const part in heights) {
const $part = $scrubber.find(`.Scrubber-${part}`);
animationPromises.push(
$part
.stop(true, true)
[func]({ height: heights[part] + '%' }, 'fast')
.promise()
);
// jQuery likes to put overflow:hidden, but because the scrollbar handle
// has a negative margin-left, we need to override.
if (func === 'animate') $part.css('overflow', 'visible');
}
Promise.all(animationPromises).then(() => (this.adjustingHeight = false));
}
/**
* Go to the first post in the discussion.
*/
goToFirst() {
this.stream.goToFirst();
this.updateScrubberValues({ animate: true, forceHeightChange: true });
}
/**
* Go to the last post in the discussion.
*/
goToLast() {
this.stream.goToLast();
this.updateScrubberValues({ animate: true, forceHeightChange: true });
}
onresize() {
// Adjust the height of the scrollbar so that it fills the height of
// the sidebar and doesn't overlap the footer.
const scrubber = this.$();
const scrollbar = this.$('.Scrubber-scrollbar');
scrollbar.css(
'max-height',
$(window).height() -
scrubber.offset().top +
$(window).scrollTop() -
parseInt($('#app').css('padding-bottom'), 10) -
(scrubber.outerHeight() - scrollbar.outerHeight())
);
}
onmousedown(e) {
e.redraw = false;
this.mouseStart = e.clientY || e.originalEvent.touches[0].clientY;
this.indexStart = this.stream.index;
this.dragging = true;
$('body').css('cursor', 'move');
this.$().toggleClass('dragging', this.dragging);
}
onmousemove(e) {
if (!this.dragging) return;
// Work out how much the mouse has moved by - first in pixels, then
// convert it to a percentage of the scrollbar's height, and then
// finally convert it into an index. Add this delta index onto
// the index at which the drag was started, and then scroll there.
const deltaPixels = (e.clientY || e.originalEvent.touches[0].clientY) - this.mouseStart;
const deltaPercent = (deltaPixels / this.$('.Scrubber-scrollbar').outerHeight()) * 100;
const deltaIndex = deltaPercent / this.percentPerPost().index || 0;
const newIndex = Math.min(this.indexStart + deltaIndex, this.stream.count() - 1);
this.stream.index = Math.max(0, newIndex);
this.updateScrubberValues();
}
onmouseup() {
this.$().toggleClass('dragging', this.dragging);
if (!this.dragging) return;
this.mouseStart = 0;
this.indexStart = 0;
this.dragging = false;
$('body').css('cursor', '');
this.$().removeClass('open');
// If the index we've landed on is in a gap, then tell the stream-
// content that we want to load those posts.
const intIndex = Math.floor(this.stream.index);
this.stream.goToIndex(intIndex);
}
onclick(e) {
// Calculate the index which we want to jump to based on the click position.
// 1. Get the offset of the click from the top of the scrollbar, as a
// percentage of the scrollbar's height.
const $scrollbar = this.$('.Scrubber-scrollbar');
const offsetPixels = (e.pageY || e.originalEvent.touches[0].pageY) - $scrollbar.offset().top + $('body').scrollTop();
let offsetPercent = (offsetPixels / $scrollbar.outerHeight()) * 100;
// 2. We want the handle of the scrollbar to end up centered on the click
// position. Thus, we calculate the height of the handle in percent and
// use that to find a new offset percentage.
offsetPercent = offsetPercent - parseFloat($scrollbar.find('.Scrubber-handle')[0].style.height) / 2;
// 3. Now we can convert the percentage into an index, and tell the stream-
// content component to jump to that index.
let offsetIndex = offsetPercent / this.percentPerPost().index;
offsetIndex = Math.max(0, Math.min(this.stream.count() - 1, offsetIndex));
this.stream.goToIndex(Math.floor(offsetIndex));
this.updateScrubberValues({ animate: true, forceHeightChange: true });
this.$().removeClass('open');
}
/**
* Get the percentage of the height of the scrubber that should be allocated
* to each post.
*
* @return {{ index: number, visible: number }}
* @property {Number} index The percent per post for posts on either side of
* the visible part of the scrubber.
* @property {Number} visible The percent per post for the visible part of the
* scrubber.
*/
percentPerPost() {
const count = this.stream.count() || 1;
const visible = this.stream.visible || 1;
// To stop the handle of the scrollbar from getting too small when there
// are many posts, we define a minimum percentage height for the handle
// calculated from a 50 pixel limit. From this, we can calculate the
// minimum percentage per visible post. If this is greater than the actual
// percentage per post, then we need to adjust the 'before' percentage to
// account for it.
const minPercentVisible = (50 / this.$('.Scrubber-scrollbar').outerHeight()) * 100;
const percentPerVisiblePost = Math.max(100 / count, minPercentVisible / visible);
const percentPerPost = count === visible ? 0 : (100 - percentPerVisiblePost * visible) / (count - visible);
return {
index: percentPerPost,
visible: percentPerVisiblePost,
};
}
}