@octanejs/lottie-react 0.0.0-stage → 0.0.2

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) 2026 Dominic Gannaway
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,46 @@
1
+ The MIT License
2
+
3
+ Copyright David Gamote and other contributors.
4
+
5
+ This software consists of voluntary contributions made by many
6
+ individuals. For exact contribution history, see the revision history
7
+ available on GitHub.
8
+
9
+ The following license applies to all parts of this software except as
10
+ documented below:
11
+
12
+ ====
13
+
14
+ Permission is hereby granted, free of charge, to any person obtaining
15
+ a copy of this software and associated documentation files (the
16
+ "Software"), to deal in the Software without restriction, including
17
+ without limitation the rights to use, copy, modify, merge, publish,
18
+ distribute, sublicense, and/or sell copies of the Software, and to
19
+ permit persons to whom the Software is furnished to do so, subject to
20
+ the following conditions:
21
+
22
+ The above copyright notice and this permission notice shall be
23
+ included in all copies or substantial portions of the Software.
24
+
25
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
26
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
27
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
28
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
29
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
30
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
31
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
32
+
33
+ ====
34
+
35
+ Copyright and related rights for sample code are waived via CC0. Sample
36
+ code is defined as all source code displayed within the prose of the
37
+ documentation.
38
+
39
+ CC0: http://creativecommons.org/publicdomain/zero/1.0/
40
+
41
+ ====
42
+
43
+ Files located in the node_modules and vendor directories are externally
44
+ maintained libraries used by this software which have their own
45
+ licenses; we recommend you read them, as their terms may differ from the
46
+ terms above.
package/README.md CHANGED
@@ -1,3 +1,36 @@
1
- # Temporary Holding Version
1
+ # @octanejs/lottie-react
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Render Lottie animations in Octane. The binding provides the `Lottie` component, the `useLottie` and `useLottieInteractivity` hooks, and the `LottiePlayer` export from `lottie-web`.
4
+
5
+ ```sh
6
+ npm install @octanejs/lottie-react
7
+ ```
8
+
9
+ ```sh
10
+ pnpm add @octanejs/lottie-react
11
+ ```
12
+
13
+ ```tsrx
14
+ import Lottie from '@octanejs/lottie-react';
15
+ import animationData from './animation.json';
16
+
17
+ export function LoadingAnimation() {
18
+ return (
19
+ <Lottie
20
+ animationData={animationData}
21
+ aria-label="Loading"
22
+ autoplay
23
+ loop
24
+ style={{ width: '8rem' }}
25
+ />
26
+ );
27
+ }
28
+ ```
29
+
30
+ Pass an object ref as `lottieRef` to control playback through methods such as `play`, `pause`, and `goToAndStop`. Use `useLottie` when you need the rendered `View` and the playback methods in the same component. Pass the hook result as `lottieObj` to `useLottieInteractivity` to attach scroll or cursor actions.
31
+
32
+ When migrating from `lottie-react`, update the import after confirming that Octane renders the component and owns the returned `View`.
33
+
34
+ Animation callbacks such as `onComplete` and `onEnterFrame` receive Lottie player events. Container props and event handlers use Octane's native DOM types. Server rendering emits the container and initializes playback on the client.
35
+
36
+ This binding ports `lottie-react@2.4.1` by David Gamote and contributors. Its [upstream license](./LICENSE.upstream) and [source and test evidence](./UPSTREAM.md) accompany the package.
package/UPSTREAM.md ADDED
@@ -0,0 +1,38 @@
1
+ # lottie-react upstream evidence
2
+
3
+ | Item | Pin |
4
+ | --- | --- |
5
+ | npm package | `lottie-react@2.4.1` |
6
+ | npm integrity | `sha512-LQrH7jlkigIIv++wIyrOYFLHSKQpEY4zehPicL9bQsrt1rnoKRYCYgpCUe5maqylNtacy58/sQDZTkwMcTRxZw==` |
7
+ | npm tarball SHA-256 | `8c28c26157e5e69a6d93111005ad78044f9ae3492e9b20edd78ac4da288e513b` |
8
+ | Source commit | `bd794d226e14c714e7d740a1f7fa9dcf284d7235` from npm's `gitHead` |
9
+ | Published declaration SHA-256 | `d114d7f758e0ae8f0a2070004c89cc92810580fab416a470a78bbcf34f315357` |
10
+ | License | MIT, David Gamote and other contributors |
11
+ | Animation engine | `lottie-web@5.13.0` |
12
+ | React oracle | `react@19.2.7`, `react-dom@19.2.7`, `@types/react@19.2.17`, `@types/react-dom@19.2.3` |
13
+
14
+ ## Source boundary
15
+
16
+ The [pinned source](https://github.com/Gamote/lottie-react/tree/bd794d226e14c714e7d740a1f7fa9dcf284d7235) supplies the component, hooks, types, and upstream Jest tests. The lock records their Git blobs. The original npm tarball and a byte-exact copy of its `build/index.d.ts` live under `upstream-artifact/`. The npm declaration is authoritative for the released callback types. `LICENSE.upstream` preserves the upstream notice byte for byte, including its CC0 provision for sample code.
17
+
18
+ The binding adapts the React view, hooks, and public types in `src/`. It uses the published animation engine directly.
19
+
20
+ ## Published surface
21
+
22
+ | Release export | Octane binding |
23
+ | --- | --- |
24
+ | Default `Lottie` | `Lottie` with Octane container props and animation event callbacks |
25
+ | `useLottie` | Renderer options, animation lifecycle, playback methods, refs, and the Octane `View` |
26
+ | `useLottieInteractivity` | Scroll and cursor actions on the hook's player and view |
27
+ | `LottiePlayer` | The `lottie-web` player export |
28
+ | `Action`, `Axis`, `InteractivityProps`, `Position` | Interactivity types |
29
+ | `LottieComponentProps`, `LottieOptions`, `LottieRef`, `LottieRefCurrentProps`, `PartialLottieComponentProps`, `PartialLottieOptions` | Component, hook, and player handle types |
30
+ | `Listener`, `PartialListener` | Player event listener types |
31
+
32
+ The binding publishes authored sources through its root entry. Octane element, ref, DOM event, and style types describe the framework-facing portions of the API.
33
+
34
+ ## Evidence
35
+
36
+ The pinned suite contains five component, eight animation-hook, and eighteen interactivity registrations. The runtime crosswalk maps those Jest registrations to the React and Octane lanes. The release has zero dedicated upstream type-test registrations. Paired declaration checks exercise the published React and Octane signatures, and the public type project asserts all sixteen exports. The repository pack check compiles the installed binding and its consumer in both Node and browser ambient configurations.
37
+
38
+ Run `pnpm --dir packages/lottie-react upstream:verify` to check the pristine source lock, artifact hashes, and upstream license.
package/package.json CHANGED
@@ -1,6 +1,55 @@
1
1
  {
2
2
  "name": "@octanejs/lottie-react",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.0.2",
4
+ "description": "Octane bindings for Lottie animations, ported from lottie-react 2.4.1.",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "engines": {
8
+ "node": ">=22.22.2"
9
+ },
10
+ "publishConfig": {
11
+ "access": "public"
12
+ },
13
+ "repository": {
14
+ "type": "git",
15
+ "url": "git+https://github.com/octanejs/octane.git",
16
+ "directory": "packages/lottie-react"
17
+ },
18
+ "main": "./src/index.ts",
19
+ "module": "./src/index.ts",
20
+ "types": "./src/index.ts",
21
+ "files": [
22
+ "src",
23
+ "LICENSE",
24
+ "LICENSE.upstream",
25
+ "README.md",
26
+ "UPSTREAM.md"
27
+ ],
28
+ "exports": {
29
+ ".": "./src/index.ts"
30
+ },
31
+ "dependencies": {
32
+ "lottie-web": "5.13.0"
33
+ },
34
+ "peerDependencies": {
35
+ "octane": "^0.18.0"
36
+ },
37
+ "devDependencies": {
38
+ "@octanejs/testing-library": "0.1.70",
39
+ "@testing-library/react": "16.3.2",
40
+ "@types/react": "19.2.17",
41
+ "@types/react-dom": "19.2.3",
42
+ "lottie-react": "2.4.1",
43
+ "octane": "0.18.0",
44
+ "playwright": "^1.61.1",
45
+ "react": "19.2.7",
46
+ "react-dom": "19.2.7",
47
+ "vite": "^8.1.5",
48
+ "vitest": "^4.1.10"
49
+ },
50
+ "scripts": {
51
+ "test": "vitest run --root ../.. --project lottie-react --project lottie-react-pristine --project lottie-react-server --project lottie-react-browser",
52
+ "typecheck": "octane-tsc -p tsconfig.json",
53
+ "upstream:verify": "node ../../scripts/react-parity/verify-provenance.mjs --package-dir ."
54
+ }
6
55
  }
@@ -0,0 +1,77 @@
1
+ import { useEffect } from 'octane';
2
+ import useLottie from '../hooks/useLottie.tsrx';
3
+ import useLottieInteractivity from '../hooks/useLottieInteractivity.tsrx';
4
+ import type { LottieComponentProps } from '../types.js';
5
+
6
+ const Lottie = (props: LottieComponentProps) => {
7
+ const { style, interactivity, ...lottieProps } = props;
8
+
9
+ /**
10
+ * Initialize the 'useLottie' hook
11
+ */
12
+ const {
13
+ View,
14
+ play,
15
+ stop,
16
+ pause,
17
+ setSpeed,
18
+ goToAndStop,
19
+ goToAndPlay,
20
+ setDirection,
21
+ playSegments,
22
+ setSubframe,
23
+ getDuration,
24
+ destroy,
25
+ animationContainerRef,
26
+ animationLoaded,
27
+ animationItem,
28
+ } = useLottie(lottieProps, style);
29
+
30
+ /**
31
+ * Make the hook variables/methods available through the provided 'lottieRef'
32
+ */
33
+ useEffect(() => {
34
+ if (props.lottieRef) {
35
+ props.lottieRef.current = {
36
+ play,
37
+ stop,
38
+ pause,
39
+ setSpeed,
40
+ goToAndPlay,
41
+ goToAndStop,
42
+ setDirection,
43
+ playSegments,
44
+ setSubframe,
45
+ getDuration,
46
+ destroy,
47
+ animationContainerRef,
48
+ animationLoaded,
49
+ animationItem,
50
+ };
51
+ }
52
+ }, [props.lottieRef?.current]);
53
+
54
+ return useLottieInteractivity({
55
+ lottieObj: {
56
+ View,
57
+ play,
58
+ stop,
59
+ pause,
60
+ setSpeed,
61
+ goToAndStop,
62
+ goToAndPlay,
63
+ setDirection,
64
+ playSegments,
65
+ setSubframe,
66
+ getDuration,
67
+ destroy,
68
+ animationContainerRef,
69
+ animationLoaded,
70
+ animationItem,
71
+ },
72
+ actions: interactivity?.actions ?? [],
73
+ mode: interactivity?.mode ?? 'scroll',
74
+ });
75
+ };
76
+
77
+ export default Lottie;
@@ -0,0 +1,255 @@
1
+ import lottie, {
2
+ type AnimationConfigWithData,
3
+ type AnimationItem,
4
+ type AnimationDirection,
5
+ type AnimationSegment,
6
+ type RendererType,
7
+ } from 'lottie-web';
8
+ import { useEffect, useRef, useState, type CSSProperties, type OctaneElement } from 'octane';
9
+ import type { Listener, LottieOptions, LottieRefCurrentProps, PartialListener } from '../types.js';
10
+
11
+ export default function useLottie<T extends RendererType = 'svg'>(
12
+ props: LottieOptions<T>,
13
+ style?: CSSProperties,
14
+ ): { View: OctaneElement } & LottieRefCurrentProps {
15
+ const {
16
+ animationData,
17
+ loop,
18
+ autoplay,
19
+ initialSegment,
20
+
21
+ onComplete,
22
+ onLoopComplete,
23
+ onEnterFrame,
24
+ onSegmentStart,
25
+ onConfigReady,
26
+ onDataReady,
27
+ onDataFailed,
28
+ onLoadedImages,
29
+ onDOMLoaded,
30
+ onDestroy,
31
+
32
+ // Specified here to take them out from the 'rest'
33
+ lottieRef: _lottieRef,
34
+ renderer: _renderer,
35
+ name: _name,
36
+ assetsPath: _assetsPath,
37
+ rendererSettings: _rendererSettings,
38
+
39
+ ...rest
40
+ } = props;
41
+
42
+ const [animationLoaded, setAnimationLoaded] = useState(false);
43
+ const animationInstanceRef = useRef<AnimationItem>();
44
+ const animationContainer = useRef<HTMLDivElement>(null);
45
+
46
+ const play = (): void => {
47
+ animationInstanceRef.current?.play();
48
+ };
49
+
50
+ const stop = (): void => {
51
+ animationInstanceRef.current?.stop();
52
+ };
53
+
54
+ const pause = (): void => {
55
+ animationInstanceRef.current?.pause();
56
+ };
57
+
58
+ const setSpeed = (speed: number): void => {
59
+ animationInstanceRef.current?.setSpeed(speed);
60
+ };
61
+
62
+ const goToAndPlay = (value: number, isFrame?: boolean): void => {
63
+ animationInstanceRef.current?.goToAndPlay(value, isFrame);
64
+ };
65
+
66
+ const goToAndStop = (value: number, isFrame?: boolean): void => {
67
+ animationInstanceRef.current?.goToAndStop(value, isFrame);
68
+ };
69
+
70
+ const setDirection = (direction: AnimationDirection): void => {
71
+ animationInstanceRef.current?.setDirection(direction);
72
+ };
73
+
74
+ const playSegments = (
75
+ segments: AnimationSegment | AnimationSegment[],
76
+ forceFlag?: boolean,
77
+ ): void => {
78
+ animationInstanceRef.current?.playSegments(segments, forceFlag);
79
+ };
80
+
81
+ const setSubframe = (useSubFrames: boolean): void => {
82
+ animationInstanceRef.current?.setSubframe(useSubFrames);
83
+ };
84
+
85
+ const getDuration = (inFrames?: boolean): number | undefined =>
86
+ animationInstanceRef.current?.getDuration(inFrames);
87
+
88
+ const destroy = (): void => {
89
+ animationInstanceRef.current?.destroy();
90
+
91
+ // Removing the reference to the animation so separate cleanups are skipped.
92
+ // Without it the internal `lottie-react` instance throws exceptions as it already cleared itself on destroy.
93
+ animationInstanceRef.current = undefined;
94
+ };
95
+
96
+ /**
97
+ * Load a new animation, and if it's the case, destroy the previous one
98
+ */
99
+ const loadAnimation = () => {
100
+ // Return if the container ref is null
101
+ if (!animationContainer.current) {
102
+ return;
103
+ }
104
+
105
+ // Destroy any previous instance
106
+ animationInstanceRef.current?.destroy();
107
+
108
+ // Build the animation configuration
109
+ const config: AnimationConfigWithData<T> = {
110
+ ...props,
111
+ container: animationContainer.current,
112
+ };
113
+
114
+ // Save the animation instance
115
+ animationInstanceRef.current = lottie.loadAnimation(config);
116
+
117
+ setAnimationLoaded(!!animationInstanceRef.current);
118
+
119
+ // Return a function that will clean up
120
+ return () => {
121
+ animationInstanceRef.current?.destroy();
122
+ animationInstanceRef.current = undefined;
123
+ };
124
+ };
125
+
126
+ /**
127
+ * (Re)Initialize when animation data changed
128
+ */
129
+ useEffect(() => {
130
+ const onUnmount = loadAnimation();
131
+
132
+ // Clean up on unmount
133
+ return () => onUnmount?.();
134
+ }, [animationData, loop]);
135
+
136
+ // Update the autoplay state
137
+ useEffect(() => {
138
+ if (!animationInstanceRef.current) {
139
+ return;
140
+ }
141
+
142
+ animationInstanceRef.current.autoplay = !!autoplay;
143
+ }, [autoplay]);
144
+
145
+ // Update the initial segment state
146
+ useEffect(() => {
147
+ if (!animationInstanceRef.current) {
148
+ return;
149
+ }
150
+
151
+ // When null should reset to default animation length
152
+ if (!initialSegment) {
153
+ animationInstanceRef.current.resetSegments(true);
154
+ return;
155
+ }
156
+
157
+ // If it's not a valid segment, do nothing
158
+ if (!Array.isArray(initialSegment) || !initialSegment.length) {
159
+ return;
160
+ }
161
+
162
+ // If the current position it's not in the new segment
163
+ // set the current position to start
164
+ if (
165
+ animationInstanceRef.current.currentRawFrame < initialSegment[0] ||
166
+ animationInstanceRef.current.currentRawFrame > initialSegment[1]
167
+ ) {
168
+ animationInstanceRef.current.currentRawFrame = initialSegment[0];
169
+ }
170
+
171
+ // Update the segment
172
+ animationInstanceRef.current.setSegment(initialSegment[0], initialSegment[1]);
173
+ }, [initialSegment]);
174
+
175
+ /**
176
+ * Reinitialize listener on change
177
+ */
178
+ useEffect(() => {
179
+ const partialListeners: PartialListener[] = [
180
+ { name: 'complete', handler: onComplete },
181
+ { name: 'loopComplete', handler: onLoopComplete },
182
+ { name: 'enterFrame', handler: onEnterFrame },
183
+ { name: 'segmentStart', handler: onSegmentStart },
184
+ { name: 'config_ready', handler: onConfigReady },
185
+ { name: 'data_ready', handler: onDataReady },
186
+ { name: 'data_failed', handler: onDataFailed },
187
+ { name: 'loaded_images', handler: onLoadedImages },
188
+ { name: 'DOMLoaded', handler: onDOMLoaded },
189
+ { name: 'destroy', handler: onDestroy },
190
+ ];
191
+
192
+ const listeners = partialListeners.filter(
193
+ (listener: PartialListener): listener is Listener => listener.handler != null,
194
+ );
195
+
196
+ if (!listeners.length) {
197
+ return;
198
+ }
199
+
200
+ const deregisterList = listeners.map(
201
+ /**
202
+ * Handle the process of adding an event listener
203
+ * @param {Listener} listener
204
+ * @return {Function} Function that deregister the listener
205
+ */
206
+ (listener) => {
207
+ animationInstanceRef.current?.addEventListener(listener.name, listener.handler);
208
+
209
+ // Return a function to deregister this listener
210
+ return () => {
211
+ animationInstanceRef.current?.removeEventListener(listener.name, listener.handler);
212
+ };
213
+ },
214
+ );
215
+
216
+ // Deregister listeners on unmount
217
+ return () => {
218
+ deregisterList.forEach((deregister) => deregister());
219
+ };
220
+ }, [
221
+ onComplete,
222
+ onLoopComplete,
223
+ onEnterFrame,
224
+ onSegmentStart,
225
+ onConfigReady,
226
+ onDataReady,
227
+ onDataFailed,
228
+ onLoadedImages,
229
+ onDOMLoaded,
230
+ onDestroy,
231
+ ]);
232
+
233
+ /**
234
+ * Build the animation view
235
+ */
236
+ const View = <div style={style} ref={animationContainer} {...rest} />;
237
+
238
+ return {
239
+ View,
240
+ play,
241
+ stop,
242
+ pause,
243
+ setSpeed,
244
+ goToAndStop,
245
+ goToAndPlay,
246
+ setDirection,
247
+ playSegments,
248
+ setSubframe,
249
+ getDuration,
250
+ destroy,
251
+ animationContainerRef: animationContainer,
252
+ animationLoaded,
253
+ animationItem: animationInstanceRef.current,
254
+ };
255
+ }
@@ -0,0 +1,235 @@
1
+ import type { AnimationSegment } from 'lottie-web';
2
+ import { useEffect, type OctaneElement, type RefObject } from 'octane';
3
+ import type { InteractivityProps } from '../types.js';
4
+
5
+ // helpers
6
+ export function getContainerVisibility(container: Element): number {
7
+ const { top, height } = container.getBoundingClientRect();
8
+
9
+ const current = window.innerHeight - top;
10
+ const max = window.innerHeight + height;
11
+ return current / max;
12
+ }
13
+
14
+ export function getContainerCursorPosition(
15
+ container: Element,
16
+ cursorX: number,
17
+ cursorY: number,
18
+ ): { x: number; y: number } {
19
+ const { top, left, width, height } = container.getBoundingClientRect();
20
+
21
+ const x = (cursorX - left) / width;
22
+ const y = (cursorY - top) / height;
23
+
24
+ return { x, y };
25
+ }
26
+
27
+ export type InitInteractivity = {
28
+ wrapperRef: RefObject<HTMLDivElement | null>;
29
+ animationItem: InteractivityProps['lottieObj']['animationItem'];
30
+ actions: InteractivityProps['actions'];
31
+ mode: InteractivityProps['mode'];
32
+ };
33
+
34
+ export const useInitInteractivity = ({
35
+ wrapperRef,
36
+ animationItem,
37
+ mode,
38
+ actions,
39
+ }: InitInteractivity) => {
40
+ useEffect(() => {
41
+ const wrapper = wrapperRef.current;
42
+
43
+ if (!wrapper || !animationItem || !actions.length) {
44
+ return;
45
+ }
46
+
47
+ animationItem.stop();
48
+
49
+ const scrollModeHandler = () => {
50
+ let assignedSegment: number[] | null = null;
51
+
52
+ const scrollHandler = () => {
53
+ const currentPercent = getContainerVisibility(wrapper);
54
+ // Find the first action that satisfies the current position conditions
55
+ const action = actions.find(
56
+ ({ visibility }) =>
57
+ visibility && currentPercent >= visibility[0] && currentPercent <= visibility[1],
58
+ );
59
+
60
+ // Skip if no matching action was found!
61
+ if (!action) {
62
+ return;
63
+ }
64
+
65
+ if (action.type === 'seek' && action.visibility && action.frames.length === 2) {
66
+ // Seek: Go to a frame based on player scroll position action
67
+ const frameToGo =
68
+ action.frames[0] +
69
+ Math.ceil(
70
+ ((currentPercent - action.visibility[0]) /
71
+ (action.visibility[1] - action.visibility[0])) *
72
+ action.frames[1],
73
+ );
74
+
75
+ //! goToAndStop must be relative to the start of the current segment
76
+ animationItem.goToAndStop(frameToGo - animationItem.firstFrame - 1, true);
77
+ }
78
+
79
+ if (action.type === 'loop') {
80
+ // Loop: Loop a given frames
81
+ if (assignedSegment === null) {
82
+ // if not playing any segments currently. play those segments and save to state
83
+ animationItem.playSegments(action.frames as AnimationSegment, true);
84
+ assignedSegment = action.frames;
85
+ } else {
86
+ // if playing any segments currently.
87
+ //check if segments in state are equal to the frames selected by action
88
+ if (assignedSegment !== action.frames) {
89
+ // if they are not equal. new segments are to be loaded
90
+ animationItem.playSegments(action.frames as AnimationSegment, true);
91
+ assignedSegment = action.frames;
92
+ } else if (animationItem.isPaused) {
93
+ // if they are equal the play method must be called only if lottie is paused
94
+ animationItem.playSegments(action.frames as AnimationSegment, true);
95
+ assignedSegment = action.frames;
96
+ }
97
+ }
98
+ }
99
+
100
+ if (action.type === 'play' && animationItem.isPaused) {
101
+ // Play: Reset segments and continue playing full animation from current position
102
+ animationItem.resetSegments(true);
103
+ animationItem.play();
104
+ }
105
+
106
+ if (action.type === 'stop') {
107
+ // Stop: Stop playback
108
+ animationItem.goToAndStop(action.frames[0] - animationItem.firstFrame - 1, true);
109
+ }
110
+ };
111
+
112
+ document.addEventListener('scroll', scrollHandler);
113
+
114
+ return () => {
115
+ document.removeEventListener('scroll', scrollHandler);
116
+ };
117
+ };
118
+
119
+ const cursorModeHandler = () => {
120
+ const handleCursor = (_x: number, _y: number) => {
121
+ let x = _x;
122
+ let y = _y;
123
+
124
+ // Resolve cursor position if cursor is inside container
125
+ if (x !== -1 && y !== -1) {
126
+ // Get container cursor position
127
+ const pos = getContainerCursorPosition(wrapper, x, y);
128
+
129
+ // Use the resolved position
130
+ x = pos.x;
131
+ y = pos.y;
132
+ }
133
+
134
+ // Find the first action that satisfies the current position conditions
135
+ const action = actions.find(({ position }) => {
136
+ if (position && Array.isArray(position.x) && Array.isArray(position.y)) {
137
+ return (
138
+ x >= position.x[0] && x <= position.x[1] && y >= position.y[0] && y <= position.y[1]
139
+ );
140
+ }
141
+
142
+ if (position && !Number.isNaN(position.x) && !Number.isNaN(position.y)) {
143
+ return x === position.x && y === position.y;
144
+ }
145
+
146
+ return false;
147
+ });
148
+
149
+ // Skip if no matching action was found!
150
+ if (!action) {
151
+ return;
152
+ }
153
+
154
+ // Process action types:
155
+ if (
156
+ action.type === 'seek' &&
157
+ action.position &&
158
+ Array.isArray(action.position.x) &&
159
+ Array.isArray(action.position.y) &&
160
+ action.frames.length === 2
161
+ ) {
162
+ // Seek: Go to a frame based on player scroll position action
163
+ const xPercent =
164
+ (x - action.position.x[0]) / (action.position.x[1] - action.position.x[0]);
165
+ const yPercent =
166
+ (y - action.position.y[0]) / (action.position.y[1] - action.position.y[0]);
167
+
168
+ animationItem.playSegments(action.frames as AnimationSegment, true);
169
+ animationItem.goToAndStop(
170
+ Math.ceil(((xPercent + yPercent) / 2) * (action.frames[1] - action.frames[0])),
171
+ true,
172
+ );
173
+ }
174
+
175
+ if (action.type === 'loop') {
176
+ animationItem.playSegments(action.frames as AnimationSegment, true);
177
+ }
178
+
179
+ if (action.type === 'play') {
180
+ // Play: Reset segments and continue playing full animation from current position
181
+ if (animationItem.isPaused) {
182
+ animationItem.resetSegments(false);
183
+ }
184
+ animationItem.playSegments(action.frames as AnimationSegment);
185
+ }
186
+
187
+ if (action.type === 'stop') {
188
+ animationItem.goToAndStop(action.frames[0], true);
189
+ }
190
+ };
191
+
192
+ const mouseMoveHandler = (ev: MouseEvent) => {
193
+ handleCursor(ev.clientX, ev.clientY);
194
+ };
195
+
196
+ const mouseOutHandler = () => {
197
+ handleCursor(-1, -1);
198
+ };
199
+
200
+ wrapper.addEventListener('mousemove', mouseMoveHandler);
201
+ wrapper.addEventListener('mouseout', mouseOutHandler);
202
+
203
+ return () => {
204
+ wrapper.removeEventListener('mousemove', mouseMoveHandler);
205
+ wrapper.removeEventListener('mouseout', mouseOutHandler);
206
+ };
207
+ };
208
+
209
+ switch (mode) {
210
+ case 'scroll':
211
+ return scrollModeHandler();
212
+ case 'cursor':
213
+ return cursorModeHandler();
214
+ }
215
+ }, [mode, animationItem]);
216
+ };
217
+
218
+ const useLottieInteractivity = ({
219
+ actions,
220
+ mode,
221
+ lottieObj,
222
+ }: InteractivityProps): OctaneElement => {
223
+ const { animationItem, View, animationContainerRef } = lottieObj;
224
+
225
+ useInitInteractivity({
226
+ actions,
227
+ animationItem,
228
+ mode,
229
+ wrapperRef: animationContainerRef,
230
+ });
231
+
232
+ return View;
233
+ };
234
+
235
+ export default useLottieInteractivity;
package/src/index.ts ADDED
@@ -0,0 +1,5 @@
1
+ export { default as LottiePlayer } from 'lottie-web';
2
+ export { default } from './components/Lottie.tsrx';
3
+ export { default as useLottie } from './hooks/useLottie.tsrx';
4
+ export { default as useLottieInteractivity } from './hooks/useLottieInteractivity.tsrx';
5
+ export type * from './types.js';
package/src/types.ts ADDED
@@ -0,0 +1,87 @@
1
+ import type {
2
+ AnimationConfigWithData,
3
+ AnimationEventCallback,
4
+ AnimationEvents,
5
+ AnimationDirection,
6
+ AnimationEventName,
7
+ AnimationItem,
8
+ AnimationSegment,
9
+ RendererType,
10
+ } from 'lottie-web';
11
+ import type { CSSProperties, HTMLProps, MutableRefObject, OctaneElement, RefObject } from 'octane';
12
+
13
+ type AnimationEventHandler = AnimationEventCallback<AnimationEvents[AnimationEventName]>;
14
+
15
+ export type LottieRefCurrentProps = {
16
+ play: () => void;
17
+ stop: () => void;
18
+ pause: () => void;
19
+ setSpeed: (speed: number) => void;
20
+ goToAndStop: (value: number, isFrame?: boolean) => void;
21
+ goToAndPlay: (value: number, isFrame?: boolean) => void;
22
+ setDirection: (direction: AnimationDirection) => void;
23
+ playSegments: (segments: AnimationSegment | AnimationSegment[], forceFlag?: boolean) => void;
24
+ setSubframe: (useSubFrames: boolean) => void;
25
+ getDuration: (inFrames?: boolean) => number | undefined;
26
+ destroy: () => void;
27
+ animationContainerRef: RefObject<HTMLDivElement | null>;
28
+ animationLoaded: boolean;
29
+ animationItem: AnimationItem | undefined;
30
+ };
31
+
32
+ export type LottieRef = MutableRefObject<LottieRefCurrentProps | null>;
33
+
34
+ export type LottieOptions<T extends RendererType = 'svg'> = Omit<
35
+ AnimationConfigWithData<T>,
36
+ 'container' | 'animationData'
37
+ > & {
38
+ animationData: unknown;
39
+ lottieRef?: LottieRef;
40
+ onComplete?: AnimationEventHandler | null;
41
+ onLoopComplete?: AnimationEventHandler | null;
42
+ onEnterFrame?: AnimationEventHandler | null;
43
+ onSegmentStart?: AnimationEventHandler | null;
44
+ onConfigReady?: AnimationEventHandler | null;
45
+ onDataReady?: AnimationEventHandler | null;
46
+ onDataFailed?: AnimationEventHandler | null;
47
+ onLoadedImages?: AnimationEventHandler | null;
48
+ onDOMLoaded?: AnimationEventHandler | null;
49
+ onDestroy?: AnimationEventHandler | null;
50
+ } & Omit<HTMLProps<HTMLDivElement>, 'loop' | 'style'> & { style?: CSSProperties };
51
+
52
+ export type PartialLottieOptions = Omit<LottieOptions, 'animationData'> & {
53
+ animationData?: LottieOptions['animationData'];
54
+ };
55
+
56
+ // Interactivity
57
+ export type Axis = 'x' | 'y';
58
+ export type Position = { [key in Axis]: number | [number, number] };
59
+
60
+ export type Action = {
61
+ type: 'seek' | 'play' | 'stop' | 'loop';
62
+ frames: [number] | [number, number];
63
+ visibility?: [number, number];
64
+ position?: Position;
65
+ };
66
+
67
+ export type InteractivityProps = {
68
+ lottieObj: { View: OctaneElement } & LottieRefCurrentProps;
69
+ actions: Action[];
70
+ mode: 'scroll' | 'cursor';
71
+ };
72
+
73
+ export type LottieComponentProps = LottieOptions & {
74
+ interactivity?: Omit<InteractivityProps, 'lottieObj'>;
75
+ };
76
+
77
+ export type PartialLottieComponentProps = Omit<LottieComponentProps, 'animationData'> & {
78
+ animationData?: LottieOptions['animationData'];
79
+ };
80
+
81
+ export type Listener = {
82
+ name: AnimationEventName;
83
+ handler: AnimationEventHandler;
84
+ };
85
+ export type PartialListener = Omit<Listener, 'handler'> & {
86
+ handler?: Listener['handler'] | null;
87
+ };