@hanzogui/animations-react-native 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2020 Nate Wienert
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,389 @@
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __getProtoOf = Object.getPrototypeOf,
6
+ __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __export = (target, all) => {
8
+ for (var name in all) __defProp(target, name, {
9
+ get: all[name],
10
+ enumerable: !0
11
+ });
12
+ },
13
+ __copyProps = (to, from, except, desc) => {
14
+ if (from && typeof from == "object" || typeof from == "function") for (let key of __getOwnPropNames(from)) !__hasOwnProp.call(to, key) && key !== except && __defProp(to, key, {
15
+ get: () => from[key],
16
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
17
+ });
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
26
+ value: mod,
27
+ enumerable: !0
28
+ }) : target, mod)),
29
+ __toCommonJS = mod => __copyProps(__defProp({}, "__esModule", {
30
+ value: !0
31
+ }), mod);
32
+ var createAnimations_exports = {};
33
+ __export(createAnimations_exports, {
34
+ AnimatedText: () => AnimatedText,
35
+ AnimatedView: () => AnimatedView,
36
+ createAnimations: () => createAnimations,
37
+ useAnimatedNumber: () => useAnimatedNumber,
38
+ useAnimatedNumberReaction: () => useAnimatedNumberReaction,
39
+ useAnimatedNumberStyle: () => useAnimatedNumberStyle
40
+ });
41
+ module.exports = __toCommonJS(createAnimations_exports);
42
+ var import_animation_helpers = require("@hanzogui/animation-helpers"),
43
+ import_constants = require("@hanzogui/constants"),
44
+ import_use_presence = require("@hanzogui/use-presence"),
45
+ import_web = require("@hanzogui/web"),
46
+ import_react = __toESM(require("react"), 1),
47
+ import_react_native = require("react-native-web");
48
+ const isFabric = !import_constants.isWeb && typeof global < "u" && !!global.__nativeFabricUIManager,
49
+ resolveDynamicValue = (value, isDark) => value && typeof value == "object" && "dynamic" in value ? isDark ? value.dynamic.dark : value.dynamic.light : value,
50
+ animatedStyleKey = {
51
+ transform: !0,
52
+ opacity: !0
53
+ },
54
+ colorStyleKey = {
55
+ backgroundColor: !0,
56
+ color: !0,
57
+ borderColor: !0,
58
+ borderLeftColor: !0,
59
+ borderRightColor: !0,
60
+ borderTopColor: !0,
61
+ borderBottomColor: !0
62
+ },
63
+ costlyToAnimateStyleKey = {
64
+ borderRadius: !0,
65
+ borderTopLeftRadius: !0,
66
+ borderTopRightRadius: !0,
67
+ borderBottomLeftRadius: !0,
68
+ borderBottomRightRadius: !0,
69
+ borderWidth: !0,
70
+ borderLeftWidth: !0,
71
+ borderRightWidth: !0,
72
+ borderTopWidth: !0,
73
+ borderBottomWidth: !0,
74
+ ...colorStyleKey
75
+ },
76
+ AnimatedView = import_react_native.Animated.View,
77
+ AnimatedText = import_react_native.Animated.Text;
78
+ function useAnimatedNumber(initial) {
79
+ const state = import_react.default.useRef(null);
80
+ return state.current || (state.current = {
81
+ composite: null,
82
+ val: new import_react_native.Animated.Value(initial),
83
+ strategy: {
84
+ type: "spring"
85
+ }
86
+ }), {
87
+ getInstance() {
88
+ return state.current.val;
89
+ },
90
+ getValue() {
91
+ return state.current.val._value;
92
+ },
93
+ stop() {
94
+ state.current.composite?.stop(), state.current.composite = null;
95
+ },
96
+ setValue(next, {
97
+ type,
98
+ ...config
99
+ } = {
100
+ type: "spring"
101
+ }, onFinish) {
102
+ const val = state.current.val,
103
+ handleFinish = onFinish ? ({
104
+ finished
105
+ }) => finished ? onFinish() : null : void 0;
106
+ if (type === "direct") val.setValue(next);else if (type === "spring") {
107
+ state.current.composite?.stop();
108
+ const composite = import_react_native.Animated.spring(val, {
109
+ ...config,
110
+ toValue: next,
111
+ useNativeDriver: isFabric
112
+ });
113
+ composite.start(handleFinish), state.current.composite = composite;
114
+ } else {
115
+ state.current.composite?.stop();
116
+ const composite = import_react_native.Animated.timing(val, {
117
+ ...config,
118
+ toValue: next,
119
+ useNativeDriver: isFabric
120
+ });
121
+ composite.start(handleFinish), state.current.composite = composite;
122
+ }
123
+ }
124
+ };
125
+ }
126
+ const useAnimatedNumberReaction = ({
127
+ value
128
+ }, onValue) => {
129
+ const onChange = (0, import_web.useEvent)(current => {
130
+ onValue(current.value);
131
+ });
132
+ import_react.default.useEffect(() => {
133
+ const id = value.getInstance().addListener(onChange);
134
+ return () => {
135
+ value.getInstance().removeListener(id);
136
+ };
137
+ }, [value, onChange]);
138
+ },
139
+ useAnimatedNumberStyle = (value, getStyle) => getStyle(value.getInstance());
140
+ function createAnimations(animations, options) {
141
+ const nativeDriver = options?.useNativeDriver ?? isFabric;
142
+ return {
143
+ isReactNative: !0,
144
+ inputStyle: "value",
145
+ outputStyle: "inline",
146
+ avoidReRenders: !0,
147
+ animations,
148
+ needsCustomComponent: !0,
149
+ View: AnimatedView,
150
+ Text: AnimatedText,
151
+ useAnimatedNumber,
152
+ useAnimatedNumberReaction,
153
+ useAnimatedNumberStyle,
154
+ usePresence: import_use_presence.usePresence,
155
+ ResetPresence: import_use_presence.ResetPresence,
156
+ useAnimations: ({
157
+ props,
158
+ onDidAnimate,
159
+ style,
160
+ componentState,
161
+ presence,
162
+ useStyleEmitter
163
+ }) => {
164
+ const isDisabled = import_constants.isWeb && componentState.unmounted === !0,
165
+ isExiting = presence?.[0] === !1,
166
+ sendExitComplete = presence?.[1],
167
+ [, themeState] = (0, import_web.useThemeWithState)({}),
168
+ isDark = themeState?.scheme === "dark" || themeState?.name?.startsWith("dark"),
169
+ animateStyles = import_react.default.useRef({}),
170
+ animatedTranforms = import_react.default.useRef([]),
171
+ animationsState = import_react.default.useRef(/* @__PURE__ */new WeakMap()),
172
+ exitCycleIdRef = import_react.default.useRef(0),
173
+ exitCompletedRef = import_react.default.useRef(!1),
174
+ wasExitingRef = import_react.default.useRef(!1),
175
+ justStartedExiting = isExiting && !wasExitingRef.current,
176
+ justStoppedExiting = !isExiting && wasExitingRef.current;
177
+ justStartedExiting && (exitCycleIdRef.current++, exitCompletedRef.current = !1), justStoppedExiting && exitCycleIdRef.current++;
178
+ const animateOnly = props.animateOnly || [],
179
+ hasTransitionOnly = !!props.animateOnly,
180
+ isEntering = !!componentState.unmounted,
181
+ wasEnteringRef = import_react.default.useRef(isEntering),
182
+ justFinishedEntering = wasEnteringRef.current && !isEntering;
183
+ import_react.default.useEffect(() => {
184
+ wasEnteringRef.current = isEntering;
185
+ });
186
+ const args = [JSON.stringify(style), componentState, isExiting, !!onDidAnimate, isDark, justFinishedEntering, hasTransitionOnly],
187
+ res = import_react.default.useMemo(() => {
188
+ const runners = [],
189
+ completions = [],
190
+ animationState = isExiting ? "exit" : isEntering || justFinishedEntering ? "enter" : "default",
191
+ nonAnimatedStyle = {};
192
+ for (const key in style) {
193
+ const rawVal = style[key],
194
+ val = resolveDynamicValue(rawVal, isDark);
195
+ if (val !== void 0 && !isDisabled) {
196
+ if (animatedStyleKey[key] == null && !costlyToAnimateStyleKey[key]) {
197
+ nonAnimatedStyle[key] = val;
198
+ continue;
199
+ }
200
+ if (hasTransitionOnly && !animateOnly.includes(key)) {
201
+ nonAnimatedStyle[key] = val;
202
+ continue;
203
+ }
204
+ if (key !== "transform") {
205
+ animateStyles.current[key] = update(key, animateStyles.current[key], val);
206
+ continue;
207
+ }
208
+ if (val) {
209
+ if (typeof val == "string") {
210
+ console.warn("Warning: Hanzo GUI can't animate string transforms yet!");
211
+ continue;
212
+ }
213
+ for (const [index, transform] of val.entries()) {
214
+ if (!transform) continue;
215
+ const tkey = Object.keys(transform)[0],
216
+ currentTransform = animatedTranforms.current[index]?.[tkey];
217
+ animatedTranforms.current[index] = {
218
+ [tkey]: update(tkey, currentTransform, transform[tkey])
219
+ }, animatedTranforms.current = [...animatedTranforms.current];
220
+ }
221
+ }
222
+ }
223
+ }
224
+ const animatedTransformStyle = animatedTranforms.current.length > 0 ? {
225
+ transform: animatedTranforms.current.map(r => {
226
+ const key = Object.keys(r)[0],
227
+ val = animationsState.current.get(r[key])?.interpolation || r[key];
228
+ return {
229
+ [key]: val
230
+ };
231
+ })
232
+ } : {},
233
+ animatedStyle = {
234
+ ...Object.fromEntries(Object.entries(animateStyles.current).map(([k, v]) => [k, animationsState.current.get(v)?.interpolation || v])),
235
+ ...animatedTransformStyle
236
+ };
237
+ return {
238
+ runners,
239
+ completions,
240
+ style: [nonAnimatedStyle, animatedStyle]
241
+ };
242
+ function update(key, animated, valIn) {
243
+ const isColorStyleKey = colorStyleKey[key],
244
+ [val, type] = isColorStyleKey ? [0, void 0] : getValue(valIn);
245
+ let animateToValue = val;
246
+ const value = animated || new import_react_native.Animated.Value(val),
247
+ curInterpolation = animationsState.current.get(value);
248
+ let interpolateArgs;
249
+ if (type && (interpolateArgs = getInterpolated(curInterpolation?.current ?? value._value, val, type), animationsState.current.set(value, {
250
+ interpolation: value.interpolate(interpolateArgs),
251
+ current: val
252
+ })), isColorStyleKey && (animateToValue = curInterpolation?.animateToValue ? 0 : 1, interpolateArgs = getColorInterpolated(curInterpolation?.current,
253
+ // valIn is the next color
254
+ valIn, animateToValue), animationsState.current.set(value, {
255
+ current: valIn,
256
+ interpolation: value.interpolate(interpolateArgs),
257
+ animateToValue: curInterpolation?.animateToValue ? 0 : 1
258
+ })), value) {
259
+ const animationConfig = getAnimationConfig(key, animations, props.transition, animationState);
260
+ let resolve;
261
+ const promise = new Promise(res2 => {
262
+ resolve = res2;
263
+ });
264
+ completions.push(promise), runners.push(() => {
265
+ value.stopAnimation();
266
+ function getAnimation() {
267
+ return import_react_native.Animated[animationConfig.type || "spring"](value, {
268
+ toValue: animateToValue,
269
+ useNativeDriver: nativeDriver,
270
+ ...animationConfig
271
+ });
272
+ }
273
+ (animationConfig.delay ? import_react_native.Animated.sequence([import_react_native.Animated.delay(animationConfig.delay), getAnimation()]) : getAnimation()).start(({
274
+ finished
275
+ }) => {
276
+ (finished || isExiting) && resolve();
277
+ });
278
+ });
279
+ }
280
+ return process.env.NODE_ENV === "development" && props.debug === "verbose" && console.info(" \u{1F4A0} animate", key, `from (${value._value}) to`, valIn, `(${val})`, "type", type, "interpolate", interpolateArgs), value;
281
+ }
282
+ }, args);
283
+ return import_react.default.useEffect(() => {
284
+ wasExitingRef.current = isExiting;
285
+ }), (0, import_constants.useIsomorphicLayoutEffect)(() => {
286
+ res.runners.forEach(r => r());
287
+ const cycleId = exitCycleIdRef.current;
288
+ if (res.completions.length === 0) {
289
+ onDidAnimate?.(), isExiting && !exitCompletedRef.current && (exitCompletedRef.current = !0, sendExitComplete?.());
290
+ return;
291
+ }
292
+ let cancel = !1;
293
+ return Promise.all(res.completions).then(() => {
294
+ cancel || isExiting && cycleId !== exitCycleIdRef.current || isExiting && exitCompletedRef.current || (onDidAnimate?.(), isExiting && (exitCompletedRef.current = !0, sendExitComplete?.()));
295
+ }), () => {
296
+ cancel = !0;
297
+ };
298
+ }, args), useStyleEmitter?.(nextStyle => {
299
+ for (const key in nextStyle) {
300
+ const rawVal = nextStyle[key],
301
+ val = resolveDynamicValue(rawVal, isDark);
302
+ if (val !== void 0) if (key === "transform" && Array.isArray(val)) for (const [index, transform] of val.entries()) {
303
+ if (!transform) continue;
304
+ const tkey = Object.keys(transform)[0],
305
+ currentTransform = animatedTranforms.current[index]?.[tkey];
306
+ animatedTranforms.current[index] = {
307
+ [tkey]: update(tkey, currentTransform, transform[tkey])
308
+ };
309
+ } else (animatedStyleKey[key] != null || costlyToAnimateStyleKey[key]) && (animateStyles.current[key] = update(key, animateStyles.current[key], val));
310
+ }
311
+ res.runners.forEach(r => r());
312
+ function update(key, animated, valIn) {
313
+ const isColor = colorStyleKey[key],
314
+ [numVal, type] = isColor ? [0, void 0] : getValue(valIn);
315
+ let animateToValue = numVal;
316
+ const value = animated || new import_react_native.Animated.Value(numVal),
317
+ curInterpolation = animationsState.current.get(value);
318
+ type && animationsState.current.set(value, {
319
+ interpolation: value.interpolate(getInterpolated(curInterpolation?.current ?? value._value, numVal, type)),
320
+ current: numVal
321
+ }), isColor && (animateToValue = curInterpolation?.animateToValue ? 0 : 1, animationsState.current.set(value, {
322
+ current: valIn,
323
+ interpolation: value.interpolate(getColorInterpolated(curInterpolation?.current, valIn, animateToValue)),
324
+ animateToValue: curInterpolation?.animateToValue ? 0 : 1
325
+ }));
326
+ const animationConfig = getAnimationConfig(key, animations, props.transition, "default");
327
+ return res.runners.push(() => {
328
+ value.stopAnimation();
329
+ const anim = import_react_native.Animated[animationConfig.type || "spring"](value, {
330
+ toValue: animateToValue,
331
+ useNativeDriver: nativeDriver,
332
+ ...animationConfig
333
+ });
334
+ (animationConfig.delay ? import_react_native.Animated.sequence([import_react_native.Animated.delay(animationConfig.delay), anim]) : anim).start();
335
+ }), value;
336
+ }
337
+ }), process.env.NODE_ENV === "development" && props.debug === "verbose" && console.info("Animated", {
338
+ response: res,
339
+ inputStyle: style,
340
+ isExiting
341
+ }), res;
342
+ }
343
+ };
344
+ }
345
+ function getColorInterpolated(currentColor, nextColor, animateToValue) {
346
+ const inputRange = [0, 1],
347
+ outputRange = [currentColor || nextColor, nextColor];
348
+ return animateToValue === 0 && outputRange.reverse(), {
349
+ inputRange,
350
+ outputRange
351
+ };
352
+ }
353
+ function getInterpolated(current, next, postfix = "deg") {
354
+ next === current && (current = next - 1e-9);
355
+ const inputRange = [current, next],
356
+ outputRange = [`${current}${postfix}`, `${next}${postfix}`];
357
+ return next < current && (inputRange.reverse(), outputRange.reverse()), {
358
+ inputRange,
359
+ outputRange
360
+ };
361
+ }
362
+ function getAnimationConfig(key, animations, transition, animationState = "default") {
363
+ const normalized = (0, import_animation_helpers.normalizeTransition)(transition),
364
+ shortKey = transformShorthands[key],
365
+ propAnimation = normalized.properties[key] ?? normalized.properties[shortKey];
366
+ let animationType = null,
367
+ extraConf = {};
368
+ return typeof propAnimation == "string" ? animationType = propAnimation : propAnimation && typeof propAnimation == "object" ? (animationType = propAnimation.type || (0, import_animation_helpers.getEffectiveAnimation)(normalized, animationState), extraConf = propAnimation) : animationType = (0, import_animation_helpers.getEffectiveAnimation)(normalized, animationState), normalized.delay && !extraConf.delay && (extraConf = {
369
+ ...extraConf,
370
+ delay: normalized.delay
371
+ }), {
372
+ ...(animationType ? animations[animationType] : {}),
373
+ // Apply global spring config overrides (from transition={['bouncy', { stiffness: 1000 }]})
374
+ ...normalized.config,
375
+ // Property-specific config takes highest precedence
376
+ ...extraConf
377
+ };
378
+ }
379
+ const transformShorthands = {
380
+ x: "translateX",
381
+ y: "translateY",
382
+ translateX: "x",
383
+ translateY: "y"
384
+ };
385
+ function getValue(input, isColor = !1) {
386
+ if (typeof input != "string") return [input];
387
+ const [_, number, after] = input.match(/([-0-9]+)(deg|%|px)/) ?? [];
388
+ return [+number, after];
389
+ }