forked from FrontendMatter/material-design-kit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathheader.js
More file actions
412 lines (354 loc) · 10.4 KB
/
Copy pathheader.js
File metadata and controls
412 lines (354 loc) · 10.4 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
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
import { scrollTargetBehavior } from '../scroll-target-behavior'
import { scrollEffectBehavior } from '../scroll-effect-behavior'
import { handler } from 'dom-factory'
// SCROLL EFFECTS
import { SCROLL_EFFECTS } from '../scroll-effects'
// HEADER SCROLL EFFECTS
import { HEADER_SCROLL_EFFECTS } from '../header-scroll-effects'
const MODULE = 'mdk-header'
const CONTENT = `.${ MODULE }__content`
const BG = `.${ MODULE }__bg`
const FRONT_LAYER = `${ BG }-front`
const REAR_LAYER = `${ BG }-rear`
const MODIFIER_FIXED = `${ MODULE }--fixed`
/**
* A container element for navigation and other content at the top
* of the screen with visual effects based on scroll position
*
* @param {HTMLElement} element
* @return {Object}
*/
export const headerComponent = (element) => ({
/**
* Public properties.
* @type {Object}
*/
properties: {
/**
* Collapse the header when scrolling down, leaving only the `[primary]` element visible.
* If there is no `[primary]` element, the first child remains visibile.
* @type {Object}
*/
condenses: {
type: Boolean,
reflectToAttribute: true
},
/**
* Slides back the header when scrolling back up.
* @type {Object}
*/
reveals: {
type: Boolean,
reflectToAttribute: true
},
/**
* Mantains the header fixed at the top.
* @type {Object}
*/
fixed: {
type: Boolean,
reflectToAttribute: true
},
/**
* Disables all scroll effects.
* @type {Object}
*/
disabled: {
type: Boolean,
reflectToAttribute: true
}
},
/**
* Property change observers.
* @type {Array}
*/
observers: [
'_handleFixedPositionedScroll(scrollTargetSelector)',
'_reset(condenses, reveals, fixed)'
],
/**
* Event listeners
* @type {Array}
*/
listeners: [
'window._debounceResize(resize)'
],
/**
* Compose mixins
* @type {Array}
*/
mixins: [
scrollTargetBehavior(element),
scrollEffectBehavior(element)
],
// A cached offsetHeight of the element
_height: 0,
// The distance in pixels the header will be translated to when scrolling
_dHeight: 0,
// The offsetTop of `_primaryElement`
_primaryElementTop: 0,
// The element that remains visibile when the header condenses
_primaryElement: null,
// The header's top value used for the `transformY`
_top: 0,
// The current scroll progress
_progress: 0,
_wasScrollingDown: false,
_initScrollTop: 0,
_initTimestamp: 0,
_lastTimestamp: 0,
_lastScrollTop: 0,
/**
* Disables transform effects
* @return {Boolean}
*/
get transformDisabled () {
return this.disabled || this.element.hasAttribute('transform-disabled') || !this._isPositionedFixed
},
/**
* Update `transform-disabled` attribute on `element`
* @param {Boolean} value
*/
set transformDisabled (value) {
this.element[value ? 'setAttribute' : 'removeAttribute']('transform-disabled', 'transform-disabled')
},
/**
* The distance the header is allowed to move away.
* @return {number}
*/
get _maxHeaderTop () {
return this.fixed ? this._dHeight : this._height + 5
},
get _isPositionedFixed () {
return this.fixed || this.condenses || this.reveals
},
/**
* Returns true if the header will condense based on the size of the header
* @return {Boolean}
*/
willCondense () {
return this._dHeight > 0 && this.condenses
},
/**
* Returns true if the element is visible in the current viewport.
* @return {Boolean}
*/
isOnScreen () {
return this._height !== 0 && this._top < this._height
},
/**
* Returns true if there's content below the element.
* @return {Boolean}
*/
isContentBelow () {
if (this._top === 0) {
return this._clampedScrollTop > 0
}
return this._clampedScrollTop - this._maxHeaderTop >= 0
},
/**
* Returns an object containing the progress value of the scroll
* and the top position of the header.
* @return {Object}
*/
getScrollState () {
return {
progress: this._progress,
top: this._top
}
},
_setupBackgrounds () {
let bgNode = document.createElement('DIV')
this.element.insertBefore(bgNode, this.element.childNodes[0])
bgNode.classList.add(BG.substr(1))
const bgLayerClassNames = [FRONT_LAYER.substr(1), REAR_LAYER.substr(1)]
bgLayerClassNames.map(className => {
let bgNodeLayer = document.createElement('DIV')
bgNode.appendChild(bgNodeLayer)
bgNodeLayer.classList.add(className)
})
},
_reset () {
if (this.element.offsetWidth === 0 && this.element.offsetHeight === 0) {
return
}
this.element.classList[this._isPositionedFixed ? 'add' : 'remove'](MODIFIER_FIXED)
this._transform('translate3d(0, 0, 0)')
if (this._primaryElement) {
this._transform('translate3d(0, 0, 0)', this._primaryElement)
}
let scrollTop = this._clampedScrollTop
let firstSetup = this._height === 0 || scrollTop === 0
this._height = this.element.offsetHeight
this._primaryElement = this._getPrimaryElement()
this._primaryElementTop = this._primaryElement ? this._primaryElement.offsetTop : 0
this._dHeight = 0
if (this._mayMove()) {
this._dHeight = this._primaryElement ? this._height - this._primaryElement.offsetHeight : 0
}
this._setUpEffects()
this._updateScrollState(firstSetup ? scrollTop : this._lastScrollTop, true)
},
/**
* Pass MouseWheel events from the scroll target
* when the header is fixed and the scroll target is not the document
*/
_handleFixedPositionedScroll () {
if (this._fixedPositionedScrollHandler !== undefined) {
this.element.removeEventListener('wheel', this._fixedPositionedScrollHandler)
}
if (this._isValidScrollTarget() && this._isPositionedFixed && this.scrollTarget !== this._doc) {
this._fixedPositionedScrollHandler = (e) => {
let passMouseEvent = new WheelEvent(e.type, e)
this.scrollTarget.dispatchEvent(passMouseEvent)
}
this.element.addEventListener('wheel', this._fixedPositionedScrollHandler)
}
},
/**
* Returns a reference to the element that remains visible when the header condenses.
* @return {HTMLElement}
*/
_getPrimaryElement () {
let primaryElement
let nodes = this.element.querySelector(CONTENT).children
for (let i = 0; i < nodes.length; i++) {
if (nodes[i].nodeType === Node.ELEMENT_NODE) {
let node = nodes[i]
if (node.hasAttribute('primary')) {
primaryElement = node
break
}
else if (!primaryElement) {
primaryElement = node
}
}
}
return primaryElement
},
/**
* Updates the scroll state.
* @param {number} scrollTop
* @param {Boolean} forceUpdate
*/
_updateScrollState (scrollTop, forceUpdate) {
if (this._height === 0 || this.disabled) {
return
}
let progress = 0
let top = 0
let lastTop = this._top
let lastScrollTop = this._lastScrollTop
let maxHeaderTop = this._maxHeaderTop
let dScrollTop = scrollTop - lastScrollTop
let absDScrollTop = Math.abs(dScrollTop)
let isScrollingDown = scrollTop > lastScrollTop
let now = Date.now()
if (!forceUpdate && scrollTop === lastScrollTop) {
return
}
if (this._mayMove()) {
top = this._clamp(this.reveals ? lastTop + dScrollTop : scrollTop, 0, maxHeaderTop)
}
if (scrollTop >= this._dHeight) {
top = this.condenses ? Math.max(this._dHeight, top) : top
this.element.style.transitionDuration = '0ms'
}
if (this.reveals && absDScrollTop < 100) {
if (now - this._initTimestamp > 300 || this._wasScrollingDown !== isScrollingDown) {
this._initScrollTop = scrollTop
this._initTimestamp = now
}
if (scrollTop >= maxHeaderTop) {
if (Math.abs(this._initScrollTop - scrollTop) > 30 || absDScrollTop > 10) {
if (isScrollingDown && scrollTop >= maxHeaderTop) {
top = maxHeaderTop
}
else if (!isScrollingDown && scrollTop >= this._dHeight) {
top = this.condenses ? this._dHeight : 0
}
let scrollVelocity = dScrollTop / (now - this._lastTimestamp)
this.element.style.transitionDuration = `${ this._clamp((top - lastTop) / scrollVelocity, 0, 300) }ms`
}
else {
top = this._top
}
}
}
if (this._dHeight === 0) {
progress = scrollTop > 0 ? 1 : 0
}
else {
progress = top / this._dHeight
}
if (!forceUpdate) {
this._lastScrollTop = scrollTop
this._top = top
this._wasScrollingDown = isScrollingDown
this._lastTimestamp = now
}
if (forceUpdate || progress !== this._progress || lastTop !== top || scrollTop === 0) {
this._progress = progress
requestAnimationFrame(() => {
this._runEffects(progress, top)
this._transformHeader(top)
})
}
},
/**
* Transforms the header.
* @param {number} top
*/
_transformHeader (top) {
if (this.transformDisabled) {
return
}
this._transform(`translate3d(0, ${ -top }px, 0)`)
if (this._primaryElement && this.condenses && top >= this._primaryElementTop) {
this._transform(`translate3d(0, ${ Math.min(top, this._dHeight) - this._primaryElementTop }px, 0)`, this._primaryElement)
}
},
_clamp (v, min, max) {
return Math.min(max, Math.max(min, v))
},
/**
* Returns true if the current header is allowed to move as the user scrolls.
* @return {Boolean}
*/
_mayMove () {
return this.condenses || !this.fixed
},
/**
* Handle the resize event every 50ms
*/
_debounceResize () {
clearTimeout(this._onResizeTimeout)
if (this._resizeWidth !== window.innerWidth) {
this._onResizeTimeout = setTimeout(() => {
this._resizeWidth = window.innerWidth
this._reset()
}, 50)
}
},
/**
* Initialize component
*/
init () {
this._resizeWidth = window.innerWidth
this.attachToScrollTarget()
this._handleFixedPositionedScroll()
this._setupBackgrounds()
this._reset()
SCROLL_EFFECTS.concat(HEADER_SCROLL_EFFECTS).map(effect => {
this.registerEffect(effect.name, effect)
})
},
/**
* Destroy component
*/
destroy () {
clearTimeout(this._onResizeTimeout)
this.detachFromScrollTarget()
}
})
handler.register(MODULE, headerComponent)