-
Notifications
You must be signed in to change notification settings - Fork 33
/
Copy pathMarqueeDecorator.js
760 lines (681 loc) · 19.8 KB
/
MarqueeDecorator.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
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
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
import deprecate from '@enact/core/internal/deprecate';
import hoc from '@enact/core/hoc';
import {forward} from '@enact/core/handle';
import {childrenEquals} from '@enact/core/util';
import {isRtlText} from '@enact/i18n/util';
import React from 'react';
import PropTypes from 'prop-types';
import {contextTypes as stateContextTypes} from '@enact/core/internal/PubSub';
import Marquee from './Marquee';
import {contextTypes} from './MarqueeController';
/**
* Default configuration parameters for {@link moonstone/Marquee.MarqueeDecorator}
*
* @type {Object}
* @memberof moonstone/Marquee.MarqueeDecorator
* @hocconfig
*/
const defaultConfig = {
/**
* Property containing the callback to stop the animation when `marqueeOn` is `'focus'`
*
* @type {String}
* @default 'onBlur'
* @memberof moonstone/Marquee.MarqueeDecorator.defaultConfig
*/
blur: 'onBlur',
/**
* Optional CSS class to apply to the marqueed element
*
* @type {String}
* @default null
* @memberof moonstone/Marquee.MarqueeDecorator.defaultConfig
*/
className: null,
/**
* Property containing the callback to start the animation when `marqueeOn` is `'hover'`
*
* @type {String}
* @default 'onMouseEnter'
* @memberof moonstone/Marquee.MarqueeDecorator.defaultConfig
*/
enter: 'onMouseEnter',
/**
* Property containing the callback to start the animation when `marqueeOn` is `'focus'`
*
* @type {String}
* @default 'onFocus'
* @memberof moonstone/Marquee.MarqueeDecorator.defaultConfig
*/
focus: 'onFocus',
/**
* Invalidate the distance if any property (like 'inline') changes.
* Expects an array of props which on change trigger invalidateMetrics.
*
* @type {Array}
* @default ['remeasure']
* @memberof moonstone/Marquee.MarqueeDecorator.defaultConfig
*/
invalidateProps: ['remeasure'],
/**
* Property containing the callback to stop the animation when `marqueeOn` is `'hover'`
*
* @type {String}
* @default 'onMouseLeave'
* @memberof moonstone/Marquee.MarqueeDecorator.defaultConfig
*/
leave: 'onMouseLeave'
};
/**
* Checks whether any of the invalidateProps has changed or not
*
* @param {Array} propList An array of invalidateProps
* @param {Object} prev Previous props
* @param {Object} next Next props
* @returns {Boolean} `true` if any of the props changed
* @private
*/
const didPropChange = (propList, prev, next) => {
const hasPropsChanged = propList.map(i => prev[i] !== next[i]);
return hasPropsChanged.indexOf(true) !== -1;
};
/*
* There's only one timer shared for Marquee so we need to keep track of what we may be using it
* for. We may need to clean up certain things as we move among states.
*/
const TimerState = {
CLEAR: 0, // No timers pending
START_PENDING: 1, // A start request is pending
RESET_PENDING: 2, // Marquee finished, waiting for reset delay
SYNCSTART_PENDING: 3 // Waiting to alert Controller that we want to start marqueeing
};
/**
* {@link moonstone/Marquee.MarqueeDecorator} is a Higher-order Component which makes
* the Wrapped component's children marquee.
*
* @class MarqueeDecorator
* @memberof moonstone/Marquee
* @hoc
* @public
*/
const MarqueeDecorator = hoc(defaultConfig, (config, Wrapped) => {
const {blur, className: marqueeClassName, enter, focus, invalidateProps, leave} = config;
// Generate functions to forward events to containers
const forwardBlur = forward(blur);
const forwardFocus = forward(focus);
const forwardEnter = forward(enter);
const forwardLeave = forward(leave);
return class extends React.Component {
static displayName = 'MarqueeDecorator'
static contextTypes = {
...contextTypes,
...stateContextTypes
}
static propTypes = /** @lends moonstone/Marquee.MarqueeDecorator.prototype */ {
/**
* Text alignment value of the marquee. Valid values are `'left'`, `'right'` and `'center'`.
*
* @type {String}
* @public
*/
alignment: PropTypes.oneOf(['left', 'right', 'center']),
/**
* Children to be marqueed
*
* @type {Node}
* @public
*/
children: PropTypes.node,
/**
* Disables all marquee behavior except when `marqueeOn` is `'hover'` or `'focus'`. Will
* be forwarded onto the wrapped component as well.
*
* @type {Boolean}
* @public
*/
disabled: PropTypes.bool,
/**
* Forces the `direction` of the marquee. Valid values are `'rtl'` and `'ltr'`. This
* includes non-text elements as well. The default behavior, if this prop is unset, is
* to evaluate the text content for directionality using {@link i18n/util.isRtlText}.
*
* @type {String}
* @public
*/
forceDirection: PropTypes.oneOf(['rtl', 'ltr']),
/**
* When `true`, the contents will be centered regardless of the text directionality.
*
* @type {Boolean}
* @public
* @deprecated replaced by `alignment`
*/
marqueeCentered: PropTypes.bool,
/**
* Number of milliseconds to wait before starting marquee when `marqueeOn` is `'hover'` or
* `'focus'` or before restarting any marquee.
*
* @type {Number}
* @default 1000
* @public
*/
marqueeDelay: PropTypes.number,
/**
* Disables all marquee behavior and removes supporting markup.
*
* @type {Boolean}
*/
marqueeDisabled: PropTypes.bool,
/**
* Determines what triggers the marquee to start its animation. Valid values are
* `'focus'`, `'hover'` and `'render'`. The default is `'focus'`.
*
* @type {String}
* @default 'focus'
* @public
*/
marqueeOn: PropTypes.oneOf(['focus', 'hover', 'render']),
/**
* Number of milliseconds to wait before starting marquee the first time. Has no effect
* if `marqueeOn` is not `'render'`
*
* @type {Number}
* @default 1000
* @public
*/
marqueeOnRenderDelay: PropTypes.number,
/**
* Number of milliseconds to wait before resetting the marquee position after it
* finishes. A minimum of 40 milliseconds is enforced.
*
* @type {Number}
* @default 1000
* @public
*/
marqueeResetDelay: PropTypes.number,
/**
* Rate of marquee measured in pixels/second.
*
* @type {Number}
* @default 60
* @public
*/
marqueeSpeed: PropTypes.number,
/**
* Used to signal for a remeasurement inside of marquee. The value
* must change for the remeasurement to take place. The value
* type is `any` because it does not matter. It is only used to
* check for changes.
*
* @private
*/
remeasure: PropTypes.any
}
static defaultProps = {
marqueeDelay: 1000,
marqueeOn: 'focus',
marqueeOnRenderDelay: 1000,
marqueeResetDelay: 1000,
marqueeSpeed: 60
}
constructor (props) {
super(props);
this.state = {
animating: false,
overflow: 'ellipsis',
rtl: false
};
this.textDirectionValidated = false;
this.sync = false;
this.forceRestartMarquee = false;
this.timerState = TimerState.CLEAR;
this.invalidateMetrics();
if (this.props.marqueeCentered) {
deprecate({name: 'marqueeCentered', since: '1.7.0', message: 'Use `alignment` instead', until: '2.0.0'});
}
}
componentWillMount () {
if (this.context.Subscriber) {
this.context.Subscriber.subscribe('resize', this.handleResize);
this.context.Subscriber.subscribe('i18n', this.handleLocaleChange);
}
}
componentDidMount () {
if (this.context.register) {
this.sync = true;
this.context.register(this, {
start: this.start,
stop: this.stop
});
}
this.validateTextDirection(this.props);
if (this.props.marqueeOn === 'render') {
this.startAnimation(this.props.marqueeOnRenderDelay);
}
}
componentWillReceiveProps (next) {
const {marqueeOn, marqueeDisabled, marqueeSpeed} = this.props;
this.validateTextDirection(next);
if ((!childrenEquals(this.props.children, next.children)) || (invalidateProps && didPropChange(invalidateProps, this.props, next))) {
// restart marqueeOn="render" marquees or synced marquees that were animating
this.forceRestartMarquee = next.marqueeOn === 'render' || (
this.sync && (this.state.animating || this.timerState > TimerState.CLEAR)
);
this.invalidateMetrics();
this.cancelAnimation();
this.textDirectionValidated = false;
} else if (next.marqueeOn !== marqueeOn || next.marqueeDisabled !== marqueeDisabled || next.marqueeSpeed !== marqueeSpeed) {
this.cancelAnimation();
} else if (next.disabled && this.isHovered && marqueeOn === 'focus' && this.sync) {
this.context.enter(this);
}
}
componentDidUpdate () {
// if text directionality was invalidated by a prop change, we need to revalidate now
// potentially causing a re-render if rtl changes
if (this.textDirectionValidated === false) {
this.validateTextDirection(this.props);
}
if (this.distance === null) {
this.calculateMetrics();
}
if (this.shouldStartMarquee()) {
this.tryStartingAnimation(this.props.marqueeOn === 'render' ? this.props.marqueeOnRenderDelay : this.props.marqueeDelay);
}
this.forceRestartMarquee = false;
}
componentWillUnmount () {
this.clearTimeout();
if (this.sync) {
this.sync = false;
this.context.unregister(this);
}
if (this.context.Subscriber) {
this.context.Subscriber.unsubscribe('resize', this.handleResize);
this.context.Subscriber.unsubscribe('i18n', this.handleLocaleChange);
}
}
/*
* Clears the timer
*
* @returns {undefined}
*/
clearTimeout () {
if (window && this.timer) {
window.clearTimeout(this.timer);
this.timer = null;
}
this.timerState = TimerState.CLEAR;
}
/*
* Starts a new timer
*
* @param {Function} fn Callback
* @param {Number} time Delay in milliseconds
* @returns {undefined}
*/
setTimeout (fn, time = 0, state = TimerState.CLEAR) {
this.clearTimeout();
if (window) {
this.timerState = state;
this.timer = window.setTimeout(() => {
this.timerState = TimerState.CLEAR;
fn();
}, time);
}
}
/*
* Checks to see if the children changed during a condition that should cause us to re-check
* the animation state
*
* @returns {Boolean} - `true` if a possible marquee condition exists
*/
shouldStartMarquee () {
return (
this.forceRestartMarquee ||
!this.sync && (
(this.isFocused && this.props.marqueeOn === 'focus') ||
(this.isHovered && this.props.marqueeOn === 'hover') ||
(this.isHovered && this.props.marqueeOn === 'focus' && this.props.disabled)
)
);
}
/*
* Invalidates marquee metrics requiring them to be recalculated
*
* @returns {undefined}
*/
invalidateMetrics () {
// Null distance is the special value to allow recalculation
this.distance = null;
// Assume the marquee does not fit until calculations show otherwise
this.contentFits = false;
}
/*
* Determines if the component should marquee and the distance to animate
*
* @returns {undefined}
*/
calculateMetrics () {
const node = this.node;
// TODO: absolute showing check (or assume that it won't be rendered if it isn't showing?)
if (node && this.distance == null && !this.props.marqueeDisabled) {
this.distance = this.calculateDistance(node);
this.contentFits = !this.shouldAnimate(this.distance);
// TODO: Replace with functional setState with React 16
const overflow = this.calculateTextOverflow(this.distance);
if (overflow !== this.state.overflow) {
this.setState({overflow});
}
}
}
/*
* Calculates the distance the marquee must travel to reveal all of the content
*
* @param {DOMNode} node DOM Node to measure
* @returns {Number} Distance to travel in pixels
*/
calculateDistance (node) {
const rect = node.getBoundingClientRect();
const distance = Math.floor(Math.abs(node.scrollWidth - rect.width));
return distance;
}
/*
* Calculates the text overflow to use to correctly render the ellipsis. If the distance is
* exactly 0, then the ellipsis is most likely hiding the content, and marquee does not need
* to animate.
*
* @param {Number} distance Amount of overflow in pixels
* @returns {String} text-overflow value
*/
calculateTextOverflow (distance) {
return distance === 0 ? 'clip' : 'ellipsis';
}
/*
* Calculates if the marquee should animate
*
* @param {Number} distance Amount of overflow in pixels
* @returns {Boolean} `true` if it should animated
*/
shouldAnimate (distance) {
return distance > 0;
}
/*
* Starts the animation without synchronizing
*
* @param {Number} [delay] Milliseconds to wait before animating
* @returns {undefined}
*/
start = (delay = this.props.marqueeDelay) => {
if (this.props.marqueeDisabled || this.contentFits) {
// if marquee isn't necessary (contentFits), do not set `animating` but return
// `true` to mark it complete if its synchronized so it doesn't block other
// instances.
return true;
} else if (!this.state.animating) {
// Don't need to worry about this.timerState because if we're sync, we were just
// told to start, so our state is correct already. If we're not sync, this will
// restart us anyhow. If we were waiting to tell sync to start us, someone else in
// our group already did it.
this.setTimeout(() => {
this.calculateMetrics();
if (!this.contentFits) {
this.setState({
animating: true
});
} else if (this.sync) {
this.context.complete(this);
}
}, delay, TimerState.START_PENDING);
}
}
/*
* Stops the animation
*
* @returns {undefined}
*/
stop = () => {
this.clearTimeout();
this.setState({
animating: false
});
}
/*
* Starts marquee animation with synchronization, if not already animating
*
* @param {Number} [delay] Milliseconds to wait before animating
* @returns {undefined}
*/
tryStartingAnimation = (delay) => {
if (this.state.animating) return;
this.startAnimation(delay);
}
/*
* Starts marquee animation with synchronization
*
* @param {Number} [delay] Milliseconds to wait before animating
* @returns {undefined}
*/
startAnimation = (delay) => {
if (this.sync) {
// If we're running a timer for anything, we should let that finish, unless it's
// another syncstart request. We should probably check to see if the start request
// is further in the future than we are so we can choose the nearer one. But, we're
// assuming the condition is we're waiting on render delay and someone just hovered
// us, so we can start with the (hopefully) faster hover delay.
if (this.timerState !== TimerState.CLEAR &&
this.timerState !== TimerState.SYNCSTART_PENDING) {
return;
}
this.setTimeout(() => {
this.context.start();
}, delay, TimerState.SYNCSTART_PENDING);
} else {
this.start(delay);
}
}
/*
* Resets the marquee and restarts it after `marqueeDelay` millisecons.
*
* @returns {undefined}
*/
restartAnimation = () => {
this.setState({
animating: false
});
// synchronized Marquees defer to the controller to restart them
if (this.sync) {
this.context.complete(this);
} else {
this.setState((prevState) => {
if (!prevState.animating) {
this.startAnimation();
}
return null;
});
}
}
/*
* Resets and restarts the marquee after `marqueeResetDelay` milliseconds
*
* @returns {undefined}
*/
resetAnimation = () => {
const marqueeResetDelay = Math.max(40, this.props.marqueeResetDelay);
// If we're already timing a start action, don't reset. Start actions will clear us if
// sync.
if (this.timerState === TimerState.CLEAR) {
this.setTimeout(this.restartAnimation, marqueeResetDelay, TimerState.RESET_PENDING);
}
}
/*
* Cancels the marquee
*
* @returns {undefined}
*/
cancelAnimation = () => {
if (this.sync) {
this.context.cancel(this);
return;
}
this.stop();
}
handleResize = () => {
if (this.node && !this.props.marqueeDisabled) {
this.invalidateMetrics();
this.calculateMetrics();
}
}
handleLocaleChange = ({message: {rtl}}) => {
this.rtlLocale = rtl;
this.validateTextDirection(this.props);
}
handleMarqueeComplete = (ev) => {
this.resetAnimation();
ev.stopPropagation();
}
handleFocus = (ev) => {
this.isFocused = true;
if (!this.sync) {
this.setState((prevState) => {
if (!prevState.animating) {
this.startAnimation();
}
return null;
});
}
forwardFocus(ev, this.props);
}
handleBlur = (ev) => {
this.isFocused = false;
if (!this.sync) {
this.cancelAnimation();
}
forwardBlur(ev, this.props);
}
handleEnter = (ev) => {
this.isHovered = true;
if (this.props.disabled || this.props.marqueeOn === 'hover') {
if (this.sync) {
this.context.enter(this);
} else {
this.setState((prevState) => {
if (!prevState.animating) {
this.startAnimation();
}
return null;
});
}
}
forwardEnter(ev, this.props);
}
handleLeave = (ev) => {
this.isHovered = false;
if (this.props.disabled || this.props.marqueeOn === 'hover') {
if (this.sync) {
this.context.leave(this);
} else {
this.cancelAnimation();
}
}
forwardLeave(ev, this.props);
}
cacheNode = (node) => {
this.node = node;
}
validateTextDirection = ({forceDirection}) => {
// @TODO: replace with functional setState with React 16
// Text directionality is a function of locale (this.rtlLocale), content
// (this.node.textContent), and props (this.props.forceDirection) in increasing order of
// significance.
let rtl = this.rtlLocale;
if (forceDirection) {
rtl = forceDirection === 'rtl';
} else if (this.node) {
rtl = isRtlText(this.node.textContent);
this.textDirectionValidated = true;
}
// prevent re-render when text direction matches locale direction
if (rtl !== this.state.rtl) {
// eslint-disable-next-line react/no-did-update-set-state
this.setState({rtl});
}
}
renderMarquee () {
const {
alignment,
children,
disabled,
forceDirection,
marqueeOn,
marqueeSpeed,
...rest
} = this.props;
const marqueeOnFocus = marqueeOn === 'focus';
const marqueeOnHover = marqueeOn === 'hover';
const marqueeOnRender = marqueeOn === 'render';
if (marqueeOnFocus && !disabled) {
rest[focus] = this.handleFocus;
rest[blur] = this.handleBlur;
}
// TODO: cancel others on hover
if (marqueeOnHover || marqueeOnFocus) {
rest[enter] = this.handleEnter;
rest[leave] = this.handleLeave;
}
if (marqueeOnRender) {
rest[enter] = this.handleEnter;
}
delete rest.marqueeCentered;
delete rest.marqueeDelay;
delete rest.marqueeDisabled;
delete rest.marqueeOnRenderDelay;
delete rest.marqueeResetDelay;
delete rest.marqueeSpeed;
delete rest.remeasure;
let {rtl} = this.state;
if (forceDirection) {
rtl = forceDirection === 'rtl';
}
return (
<Wrapped {...rest} disabled={disabled}>
<Marquee
alignment={alignment}
animating={this.state.animating}
className={marqueeClassName}
clientRef={this.cacheNode}
distance={this.distance}
onMarqueeComplete={this.handleMarqueeComplete}
overflow={this.state.overflow}
rtl={rtl}
speed={marqueeSpeed}
>
{children}
</Marquee>
</Wrapped>
);
}
renderWrapped () {
const props = Object.assign({}, this.props);
delete props.alignment;
delete props.marqueeCentered;
delete props.marqueeDelay;
delete props.marqueeDisabled;
delete props.marqueeOn;
delete props.marqueeOnRenderDelay;
delete props.marqueeResetDelay;
delete props.marqueeSpeed;
delete props.remeasure;
return <Wrapped {...props} />;
}
render () {
if (this.props.marqueeDisabled) {
return this.renderWrapped();
} else {
return this.renderMarquee();
}
}
};
});
export default MarqueeDecorator;
export {MarqueeDecorator};