forked from material-components/material-components-web
-
Notifications
You must be signed in to change notification settings - Fork 0
/
foundation.js
515 lines (448 loc) · 15.4 KB
/
foundation.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
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
/**
* @license
* Copyright 2016 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import MDCFoundation from '@material/base/foundation';
import MDCRippleAdapter from './adapter';
import {cssClasses, strings, numbers} from './constants';
import {getNormalizedEventCoords} from './util';
/**
* @typedef {!{
* isActivated: (boolean|undefined),
* hasDeactivationUXRun: (boolean|undefined),
* wasActivatedByPointer: (boolean|undefined),
* wasElementMadeActive: (boolean|undefined),
* activationStartTime: (number|undefined),
* activationEvent: Event,
* isProgrammatic: (boolean|undefined)
* }}
*/
let ActivationStateType;
/**
* @typedef {!{
* activate: (string|undefined),
* deactivate: (string|undefined),
* focus: (string|undefined),
* blur: (string|undefined)
* }}
*/
let ListenerInfoType;
/**
* @typedef {!{
* activate: function(!Event),
* deactivate: function(!Event),
* focus: function(),
* blur: function()
* }}
*/
let ListenersType;
/**
* @typedef {!{
* x: number,
* y: number
* }}
*/
let PointType;
/**
* @enum {string}
*/
const DEACTIVATION_ACTIVATION_PAIRS = {
mouseup: 'mousedown',
pointerup: 'pointerdown',
touchend: 'touchstart',
keyup: 'keydown',
blur: 'focus',
};
/**
* @extends {MDCFoundation<!MDCRippleAdapter>}
*/
class MDCRippleFoundation extends MDCFoundation {
static get cssClasses() {
return cssClasses;
}
static get strings() {
return strings;
}
static get numbers() {
return numbers;
}
static get defaultAdapter() {
return {
browserSupportsCssVars: () => /* boolean - cached */ {},
isUnbounded: () => /* boolean */ {},
isSurfaceActive: () => /* boolean */ {},
isSurfaceDisabled: () => /* boolean */ {},
addClass: (/* className: string */) => {},
removeClass: (/* className: string */) => {},
registerInteractionHandler: (/* evtType: string, handler: EventListener */) => {},
deregisterInteractionHandler: (/* evtType: string, handler: EventListener */) => {},
registerResizeHandler: (/* handler: EventListener */) => {},
deregisterResizeHandler: (/* handler: EventListener */) => {},
updateCssVariable: (/* varName: string, value: string */) => {},
computeBoundingRect: () => /* ClientRect */ {},
getWindowPageOffset: () => /* {x: number, y: number} */ {},
};
}
constructor(adapter) {
super(Object.assign(MDCRippleFoundation.defaultAdapter, adapter));
/** @private {number} */
this.layoutFrame_ = 0;
/** @private {!ClientRect} */
this.frame_ = /** @type {!ClientRect} */ ({width: 0, height: 0});
/** @private {!ActivationStateType} */
this.activationState_ = this.defaultActivationState_();
/** @private {number} */
this.xfDuration_ = 0;
/** @private {number} */
this.initialSize_ = 0;
/** @private {number} */
this.maxRadius_ = 0;
/** @private {!Array<{ListenerInfoType}>} */
this.listenerInfos_ = [
{activate: 'touchstart', deactivate: 'touchend'},
{activate: 'pointerdown', deactivate: 'pointerup'},
{activate: 'mousedown', deactivate: 'mouseup'},
{activate: 'keydown', deactivate: 'keyup'},
{focus: 'focus', blur: 'blur'},
];
/** @private {!ListenersType} */
this.listeners_ = {
activate: (e) => this.activate_(e),
deactivate: (e) => this.deactivate_(e),
focus: () => requestAnimationFrame(
() => this.adapter_.addClass(MDCRippleFoundation.cssClasses.BG_FOCUSED)
),
blur: () => requestAnimationFrame(
() => this.adapter_.removeClass(MDCRippleFoundation.cssClasses.BG_FOCUSED)
),
};
/** @private {!Function} */
this.resizeHandler_ = () => this.layout();
/** @private {!{left: number, top:number}} */
this.unboundedCoords_ = {
left: 0,
top: 0,
};
/** @private {number} */
this.fgScale_ = 0;
/** @private {number} */
this.activationTimer_ = 0;
/** @private {number} */
this.fgDeactivationRemovalTimer_ = 0;
/** @private {boolean} */
this.activationAnimationHasEnded_ = false;
/** @private {!Function} */
this.activationTimerCallback_ = () => {
this.activationAnimationHasEnded_ = true;
this.runDeactivationUXLogicIfReady_();
};
}
/**
* We compute this property so that we are not querying information about the client
* until the point in time where the foundation requests it. This prevents scenarios where
* client-side feature-detection may happen too early, such as when components are rendered on the server
* and then initialized at mount time on the client.
* @return {boolean}
* @private
*/
isSupported_() {
return this.adapter_.browserSupportsCssVars();
}
/**
* @return {!ActivationStateType}
*/
defaultActivationState_() {
return {
isActivated: false,
hasDeactivationUXRun: false,
wasActivatedByPointer: false,
wasElementMadeActive: false,
activationStartTime: 0,
activationEvent: null,
isProgrammatic: false,
};
}
init() {
if (!this.isSupported_()) {
return;
}
this.addEventListeners_();
const {ROOT, UNBOUNDED} = MDCRippleFoundation.cssClasses;
requestAnimationFrame(() => {
this.adapter_.addClass(ROOT);
if (this.adapter_.isUnbounded()) {
this.adapter_.addClass(UNBOUNDED);
}
this.layoutInternal_();
});
}
/** @private */
addEventListeners_() {
this.listenerInfos_.forEach((info) => {
Object.keys(info).forEach((k) => {
this.adapter_.registerInteractionHandler(info[k], this.listeners_[k]);
});
});
this.adapter_.registerResizeHandler(this.resizeHandler_);
}
/**
* @param {Event} e
* @private
*/
activate_(e) {
if (this.adapter_.isSurfaceDisabled()) {
return;
}
const {activationState_: activationState} = this;
if (activationState.isActivated) {
return;
}
activationState.isActivated = true;
activationState.isProgrammatic = e === null;
activationState.activationEvent = e;
activationState.wasActivatedByPointer = activationState.isProgrammatic ? false : (
e.type === 'mousedown' || e.type === 'touchstart' || e.type === 'pointerdown'
);
activationState.activationStartTime = Date.now();
requestAnimationFrame(() => {
// This needs to be wrapped in an rAF call b/c web browsers
// report active states inconsistently when they're called within
// event handling code:
// - https://bugs.chromium.org/p/chromium/issues/detail?id=635971
// - https://bugzilla.mozilla.org/show_bug.cgi?id=1293741
activationState.wasElementMadeActive = (e && e.type === 'keydown') ? this.adapter_.isSurfaceActive() : true;
if (activationState.wasElementMadeActive) {
this.animateActivation_();
} else {
// Reset activation state immediately if element was not made active.
this.activationState_ = this.defaultActivationState_();
}
});
}
/**
* @param {?Event=} event Optional event containing position information.
*/
activate(event = null) {
this.activate_(event);
}
/** @private */
animateActivation_() {
const {VAR_FG_TRANSLATE_START, VAR_FG_TRANSLATE_END} = MDCRippleFoundation.strings;
const {
BG_ACTIVE_FILL,
FG_DEACTIVATION,
FG_ACTIVATION,
} = MDCRippleFoundation.cssClasses;
const {DEACTIVATION_TIMEOUT_MS} = MDCRippleFoundation.numbers;
let translateStart = '';
let translateEnd = '';
if (!this.adapter_.isUnbounded()) {
const {startPoint, endPoint} = this.getFgTranslationCoordinates_();
translateStart = `${startPoint.x}px, ${startPoint.y}px`;
translateEnd = `${endPoint.x}px, ${endPoint.y}px`;
}
this.adapter_.updateCssVariable(VAR_FG_TRANSLATE_START, translateStart);
this.adapter_.updateCssVariable(VAR_FG_TRANSLATE_END, translateEnd);
// Cancel any ongoing activation/deactivation animations
clearTimeout(this.activationTimer_);
clearTimeout(this.fgDeactivationRemovalTimer_);
this.rmBoundedActivationClasses_();
this.adapter_.removeClass(FG_DEACTIVATION);
// Force layout in order to re-trigger the animation.
this.adapter_.computeBoundingRect();
this.adapter_.addClass(BG_ACTIVE_FILL);
this.adapter_.addClass(FG_ACTIVATION);
this.activationTimer_ = setTimeout(() => this.activationTimerCallback_(), DEACTIVATION_TIMEOUT_MS);
}
/**
* @private
* @return {{startPoint: PointType, endPoint: PointType}}
*/
getFgTranslationCoordinates_() {
const {activationState_: activationState} = this;
const {activationEvent, wasActivatedByPointer} = activationState;
let startPoint;
if (wasActivatedByPointer) {
startPoint = getNormalizedEventCoords(
/** @type {!Event} */ (activationEvent),
this.adapter_.getWindowPageOffset(), this.adapter_.computeBoundingRect()
);
} else {
startPoint = {
x: this.frame_.width / 2,
y: this.frame_.height / 2,
};
}
// Center the element around the start point.
startPoint = {
x: startPoint.x - (this.initialSize_ / 2),
y: startPoint.y - (this.initialSize_ / 2),
};
const endPoint = {
x: (this.frame_.width / 2) - (this.initialSize_ / 2),
y: (this.frame_.height / 2) - (this.initialSize_ / 2),
};
return {startPoint, endPoint};
}
/** @private */
runDeactivationUXLogicIfReady_() {
const {FG_DEACTIVATION} = MDCRippleFoundation.cssClasses;
const {hasDeactivationUXRun, isActivated} = this.activationState_;
const activationHasEnded = hasDeactivationUXRun || !isActivated;
if (activationHasEnded && this.activationAnimationHasEnded_) {
this.rmBoundedActivationClasses_();
this.adapter_.addClass(FG_DEACTIVATION);
this.fgDeactivationRemovalTimer_ = setTimeout(() => {
this.adapter_.removeClass(FG_DEACTIVATION);
}, numbers.FG_DEACTIVATION_MS);
}
}
/** @private */
rmBoundedActivationClasses_() {
const {BG_ACTIVE_FILL, FG_ACTIVATION} = MDCRippleFoundation.cssClasses;
this.adapter_.removeClass(BG_ACTIVE_FILL);
this.adapter_.removeClass(FG_ACTIVATION);
this.activationAnimationHasEnded_ = false;
this.adapter_.computeBoundingRect();
}
/**
* @param {Event} e
* @private
*/
deactivate_(e) {
const {activationState_: activationState} = this;
// This can happen in scenarios such as when you have a keyup event that blurs the element.
if (!activationState.isActivated) {
return;
}
// Programmatic deactivation.
if (activationState.isProgrammatic) {
const evtObject = null;
const state = /** @type {!ActivationStateType} */ (Object.assign({}, activationState));
requestAnimationFrame(() => this.animateDeactivation_(evtObject, state));
this.activationState_ = this.defaultActivationState_();
return;
}
const actualActivationType = DEACTIVATION_ACTIVATION_PAIRS[e.type];
const expectedActivationType = activationState.activationEvent.type;
// NOTE: Pointer events are tricky - https://patrickhlauke.github.io/touch/tests/results/
// Essentially, what we need to do here is decouple the deactivation UX from the actual
// deactivation state itself. This way, touch/pointer events in sequence do not trample one
// another.
const needsDeactivationUX = actualActivationType === expectedActivationType;
let needsActualDeactivation = needsDeactivationUX;
if (activationState.wasActivatedByPointer) {
needsActualDeactivation = e.type === 'mouseup';
}
const state = /** @type {!ActivationStateType} */ (Object.assign({}, activationState));
requestAnimationFrame(() => {
if (needsDeactivationUX) {
this.activationState_.hasDeactivationUXRun = true;
this.animateDeactivation_(e, state);
}
if (needsActualDeactivation) {
this.activationState_ = this.defaultActivationState_();
}
});
}
/**
* @param {?Event=} event Optional event containing position information.
*/
deactivate(event = null) {
this.deactivate_(event);
}
/**
* @param {Event} e
* @param {!ActivationStateType} options
* @private
*/
animateDeactivation_(e, {wasActivatedByPointer, wasElementMadeActive}) {
const {BG_FOCUSED} = MDCRippleFoundation.cssClasses;
if (wasActivatedByPointer || wasElementMadeActive) {
// Remove class left over by element being focused
this.adapter_.removeClass(BG_FOCUSED);
this.runDeactivationUXLogicIfReady_();
}
}
destroy() {
if (!this.isSupported_()) {
return;
}
this.removeEventListeners_();
const {ROOT, UNBOUNDED} = MDCRippleFoundation.cssClasses;
requestAnimationFrame(() => {
this.adapter_.removeClass(ROOT);
this.adapter_.removeClass(UNBOUNDED);
this.removeCssVars_();
});
}
/** @private */
removeEventListeners_() {
this.listenerInfos_.forEach((info) => {
Object.keys(info).forEach((k) => {
this.adapter_.deregisterInteractionHandler(info[k], this.listeners_[k]);
});
});
this.adapter_.deregisterResizeHandler(this.resizeHandler_);
}
/** @private */
removeCssVars_() {
const {strings} = MDCRippleFoundation;
Object.keys(strings).forEach((k) => {
if (k.indexOf('VAR_') === 0) {
this.adapter_.updateCssVariable(strings[k], null);
}
});
}
layout() {
if (this.layoutFrame_) {
cancelAnimationFrame(this.layoutFrame_);
}
this.layoutFrame_ = requestAnimationFrame(() => {
this.layoutInternal_();
this.layoutFrame_ = 0;
});
}
/** @private */
layoutInternal_() {
this.frame_ = this.adapter_.computeBoundingRect();
const maxDim = Math.max(this.frame_.height, this.frame_.width);
const surfaceDiameter = Math.sqrt(Math.pow(this.frame_.width, 2) + Math.pow(this.frame_.height, 2));
// 60% of the largest dimension of the surface
this.initialSize_ = maxDim * MDCRippleFoundation.numbers.INITIAL_ORIGIN_SCALE;
// Diameter of the surface + 10px
this.maxRadius_ = surfaceDiameter + MDCRippleFoundation.numbers.PADDING;
this.fgScale_ = this.maxRadius_ / this.initialSize_;
this.xfDuration_ = 1000 * Math.sqrt(this.maxRadius_ / 1024);
this.updateLayoutCssVars_();
}
/** @private */
updateLayoutCssVars_() {
const {
VAR_FG_SIZE, VAR_LEFT, VAR_TOP, VAR_FG_SCALE,
} = MDCRippleFoundation.strings;
this.adapter_.updateCssVariable(VAR_FG_SIZE, `${this.initialSize_}px`);
this.adapter_.updateCssVariable(VAR_FG_SCALE, this.fgScale_);
if (this.adapter_.isUnbounded()) {
this.unboundedCoords_ = {
left: Math.round((this.frame_.width / 2) - (this.initialSize_ / 2)),
top: Math.round((this.frame_.height / 2) - (this.initialSize_ / 2)),
};
this.adapter_.updateCssVariable(VAR_LEFT, `${this.unboundedCoords_.left}px`);
this.adapter_.updateCssVariable(VAR_TOP, `${this.unboundedCoords_.top}px`);
}
}
}
export default MDCRippleFoundation;