forked from deanhet/react-native-text-ticker
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
437 lines (410 loc) · 11.6 KB
/
index.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
import React, { PureComponent } from "react";
import {
Animated,
Easing,
StyleSheet,
Text,
View,
ScrollView,
I18nManager,
} from "react-native";
export const TextTickAnimationType = Object.freeze({
auto: "auto",
scroll: "scroll",
bounce: "bounce",
});
export default class TextMarquee extends PureComponent {
static defaultProps = {
style: {},
loop: true,
bounce: true,
scroll: true,
marqueeOnMount: true,
marqueeDelay: 0,
isInteraction: true,
useNativeDriver: true,
repeatSpacer: 50,
easing: Easing.ease,
animationType: "auto",
bounceSpeed: 50,
scrollSpeed: 150,
bouncePadding: undefined,
bounceDelay: 0,
shouldAnimateTreshold: 0,
disabled: false,
isRTL: undefined,
};
animatedValue = new Animated.Value(0);
distance = null;
textRef = null;
containerRef = null;
state = {
animating: false,
contentFits: true,
shouldBounce: false,
isScrolling: false,
};
constructor(props) {
super(props);
this.calculateMetricsPromise = null;
}
componentDidMount() {
this.invalidateMetrics();
const { disabled, marqueeDelay, marqueeOnMount } = this.props;
if (!disabled && marqueeOnMount) {
this.startAnimation(marqueeDelay);
}
}
componentDidUpdate(prevProps) {
if (this.props.children !== prevProps.children) {
this.resetScroll();
} else if (this.props.disabled !== prevProps.disabled) {
if (!this.props.disabled && this.props.marqueeOnMount) {
this.startAnimation(this.props.marqueeDelay);
} else if (this.props.disabled) {
// Cancel any promises
if (this.calculateMetricsPromise !== null) {
this.calculateMetricsPromise.cancel();
this.calculateMetricsPromise = null;
}
this.stopAnimation();
this.clearTimeout();
}
}
}
componentWillUnmount() {
// Cancel promise to stop setState after unmount
if (this.calculateMetricsPromise !== null) {
this.calculateMetricsPromise.cancel();
this.calculateMetricsPromise = null;
}
this.stopAnimation();
// always stop timers when unmounting, common source of crash
this.clearTimeout();
}
makeCancelable = (promise) => {
let cancel = () => {};
const wrappedPromise = new Promise((resolve, reject) => {
cancel = () => {
resolve = null;
reject = null;
};
promise.then(
(value) => {
if (resolve) {
resolve(value);
}
},
(error) => {
if (reject) {
reject(error);
}
}
);
});
wrappedPromise.cancel = cancel;
return wrappedPromise;
};
startAnimation = () => {
if (this.state.animating) {
return;
}
this.start();
};
animateScroll = () => {
const {
duration,
marqueeDelay,
loop,
isInteraction,
useNativeDriver,
repeatSpacer,
easing,
children,
scrollSpeed,
onMarqueeComplete,
isRTL,
} = this.props;
this.setTimeout(() => {
const scrollToValue =
isRTL ?? I18nManager.isRTL
? this.textWidth + repeatSpacer
: -this.textWidth - repeatSpacer;
if (!isNaN(scrollToValue)) {
Animated.timing(this.animatedValue, {
toValue: scrollToValue,
duration: duration || this.textWidth * scrollSpeed,
easing: easing,
isInteraction: isInteraction,
useNativeDriver: useNativeDriver,
}).start(({ finished }) => {
if (finished) {
if (onMarqueeComplete) {
onMarqueeComplete();
}
if (loop) {
this.animatedValue.setValue(0);
this.animateScroll();
}
}
});
} else {
this.start();
}
}, marqueeDelay);
};
animateBounce = () => {
const {
duration,
marqueeDelay,
loop,
isInteraction,
useNativeDriver,
easing,
bounceSpeed,
bouncePadding,
bounceDelay,
isRTL,
} = this.props;
const rtl = isRTL ?? I18nManager.isRTL;
const bounceEndPadding = rtl ? bouncePadding?.left : bouncePadding?.right;
const bounceStartPadding = rtl ? bouncePadding?.right : bouncePadding?.left;
this.setTimeout(
() => {
Animated.sequence([
Animated.timing(this.animatedValue, {
toValue: rtl
? this.distance + (bounceEndPadding ?? 10)
: -this.distance - (bounceEndPadding ?? 10),
duration: duration || this.distance * bounceSpeed,
easing: easing,
isInteraction: isInteraction,
useNativeDriver: useNativeDriver,
}),
Animated.timing(this.animatedValue, {
toValue: rtl
? -(bounceStartPadding ?? 10)
: bounceStartPadding ?? 10,
duration: duration || this.distance * bounceSpeed,
easing: easing,
isInteraction: isInteraction,
useNativeDriver: useNativeDriver,
delay: bounceDelay,
}),
]).start(({ finished }) => {
if (finished) {
this.hasFinishedFirstLoop = true;
}
if (loop) {
this.animateBounce();
}
});
},
this.hasFinishedFirstLoop
? bounceDelay > 0
? bounceDelay
: 0
: marqueeDelay
);
};
start = async () => {
this.setState({ animating: true });
this.setTimeout(async () => {
await this.calculateMetrics();
if (!this.state.contentFits) {
const { onScrollStart } = this.props;
if (onScrollStart && typeof onScrollStart === "function") {
onScrollStart();
}
if (this.props.animationType === "auto") {
if (this.state.shouldBounce && this.props.bounce) {
this.animateBounce();
} else {
this.animateScroll();
}
} else if (this.props.animationType === "bounce") {
this.animateBounce();
} else if (this.props.animationType === "scroll") {
this.animateScroll();
}
}
}, 100);
};
stopAnimation() {
this.animatedValue.setValue(0);
this.setState({ animating: false, shouldBounce: false });
}
async calculateMetrics() {
const { shouldAnimateTreshold } = this.props;
this.calculateMetricsPromise = this.makeCancelable(
new Promise(async (resolve, reject) => {
try {
const measureWidth = (node) =>
new Promise(async (resolve, reject) => {
node.measure((x, y, w) => {
// console.log('Width: ' + w)
return resolve(w);
});
});
const [containerWidth, textWidth] = await Promise.all([
measureWidth(this.containerRef),
measureWidth(this.textRef),
]);
if (containerWidth === undefined || containerWidth === 0) {
console.warn(
"react-native-text-ticker: could not calculate container width. resolves to no animation."
);
this.props.onWidthResolveError?.();
resolve({
contentFits: true,
shouldBounce: false,
});
}
this.containerWidth = containerWidth;
this.textWidth = textWidth;
this.distance = textWidth - containerWidth + shouldAnimateTreshold;
// console.log(`distance: ${this.distance}, contentFits: ${this.state.contentFits}`)
resolve({
// Is 1 instead of 0 to get round rounding errors from:
// https://github.com/facebook/react-native/commit/a534672
contentFits: this.distance <= 1,
shouldBounce: this.distance < this.containerWidth / 8,
});
} catch (error) {
console.warn(
"react-native-text-ticker: could not calculate metrics",
error
);
resolve({
contentFits: true,
shouldBounce: false,
});
}
})
);
await this.calculateMetricsPromise.then((result) => {
this.setState({
contentFits: result.contentFits,
shouldBounce: result.shouldBounce,
});
return [];
});
}
invalidateMetrics = () => {
this.distance = null;
this.setState({ contentFits: true });
};
clearTimeout() {
if (this.timer) {
clearTimeout(this.timer);
this.timer = null;
}
}
setTimeout(fn, time = 0) {
this.clearTimeout();
this.timer = setTimeout(fn, time);
}
scrollBegin = () => {
this.setState({ isScrolling: true });
this.animatedValue.setValue(0);
};
scrollEnd = () => {
const { marqueeDelay } = this.props;
this.setTimeout(
() => {
this.setState({ isScrolling: false });
this.start();
},
marqueeDelay >= 0 ? marqueeDelay : 3000
);
};
resetScroll = () => {
this.scrollBegin();
this.scrollEnd();
};
render() {
const {
style,
children,
repeatSpacer,
scroll,
shouldAnimateTreshold,
disabled,
isRTL,
...props
} = this.props;
const { animating, contentFits, isScrolling } = this.state;
const additionalContainerStyle = {
// This is useful for shouldAnimateTreshold only:
// we use flex: 1 to make the container take all the width available
// without this, if the children have a width smaller that this component's parent's,
// the container would have the width of the children (the text)
// In this case, it would be impossible to determine if animating is necessary based on the width of the container
// (contentFits in calculateMetrics() would always be true)
flex: shouldAnimateTreshold ? 1 : undefined,
};
const animatedText = disabled ? null : (
<ScrollView
ref={(c) => (this.containerRef = c)}
horizontal
scrollEnabled={scroll ? !this.state.contentFits : false}
scrollEventThrottle={16}
onScrollBeginDrag={this.scrollBegin}
onScrollEndDrag={this.scrollEnd}
showsHorizontalScrollIndicator={false}
style={[
StyleSheet.absoluteFillObject,
(isRTL ?? I18nManager.isRTL) && { flexDirection: "row-reverse" },
]}
display={animating ? "flex" : "none"}
onContentSizeChange={() => this.calculateMetrics()}
>
<Animated.Text
ref={(c) => (this.textRef = c)}
numberOfLines={1}
{...props}
style={[
style,
{ transform: [{ translateX: this.animatedValue }], width: null },
]}
>
{this.props.children}
</Animated.Text>
{!contentFits && !isScrolling ? (
<View style={{ paddingLeft: repeatSpacer }}>
<Animated.Text
numberOfLines={1}
{...props}
style={[
style,
{
transform: [{ translateX: this.animatedValue }],
width: null,
},
]}
>
{this.props.children}
</Animated.Text>
</View>
) : null}
</ScrollView>
);
return (
<View style={[styles.container, additionalContainerStyle]}>
<Text
{...props}
numberOfLines={1}
style={[style, { opacity: !disabled && animating ? 0 : 1 }]}
>
{this.props.children}
</Text>
{animatedText}
</View>
);
}
}
const styles = StyleSheet.create({
container: {
overflow: "hidden",
},
});