Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions .changeset/gold-pets-wash.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
---
'@alfalab/core-components': minor
'@alfalab/core-components-lottie': major
---

##### Lottie

- Добавлен компонент `Lottie`
10 changes: 10 additions & 0 deletions .eslintrc.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,12 @@
const fs = require('node:fs');
const path = require('node:path');
const resolve = require('resolve');
const { getPackages } = require('./tools/monorepo.cjs');
const { isSamePath } = require('./tools/path.cjs');

const lottiePkg = getPackages().packages.find(
({ packageJson: { name } }) => name === '@alfalab/core-components-lottie',
);

const ignored = ['.eslintignore', '.gitignore']
.map((file) => path.join(process.cwd(), file))
Expand Down Expand Up @@ -66,6 +72,10 @@ const config = {
'@typescript-eslint/default-param-last': 'off',
'max-lines': 'off',
'max-params': 'off',
'react-hooks/exhaustive-deps':
lottiePkg && isSamePath(process.cwd(), lottiePkg.dir)
? ['warn', { additionalHooks: ['useLayoutEffect_SAFE_FOR_SSR'].join('|') }]
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Два вопроса по этому изменению:

  1. useLayoutEffect_SAFE_FOR_SSR из @alfalab/hooks используется во всём репозитории, не только в lottie. Если хук нужно добавить в additionalHooks — логичнее сделать это глобально для всех пакетов, а не только при isSamePath(..., lottiePkg.dir).

  2. ["useLayoutEffect_SAFE_FOR_SSR"].join("|") возвращает просто "useLayoutEffect_SAFE_FOR_SSR".join("|") на массиве из одного элемента избыточен.

: 'warn',
},
};

Expand Down
2,524 changes: 2,524 additions & 0 deletions .storybook/public/twitter-heart.json

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@
"packages/list",
"packages/list-header",
"packages/loader",
"packages/lottie",
"packages/markdown",
"packages/masked-input",
"packages/modal",
Expand Down
1 change: 1 addition & 0 deletions packages/lottie/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
# @alfalab/core-components-lottie
28 changes: 28 additions & 0 deletions packages/lottie/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
{
"name": "@alfalab/core-components-lottie",
"version": "0.0.1",
"description": "",
"keywords": [],
"license": "MIT",
"sideEffects": [
"**/*.css"
],
"main": "index.js",
"module": "./esm/index.js",
"dependencies": {
"@alfalab/core-components-shared": "^2.1.1",
"@alfalab/hooks": "^1.13.1",
"classnames": "^2.5.1",
"lottie-web": "^5.13.0",
"nanoevents": "^9.1.0",
"tslib": "^2.4.0"
},
"peerDependencies": {
"react": "^16.9.0 || ^17.0.1 || ^18.0.0 || ^19.0.0",
"react-dom": "^16.9.0 || ^17.0.1 || ^18.0.0 || ^19.0.0"
},
"publishConfig": {
"access": "public",
"directory": "dist"
}
}
192 changes: 192 additions & 0 deletions packages/lottie/src/component.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,192 @@
import React, { forwardRef, useEffect, useImperativeHandle, useRef, useState } from 'react';
import cn from 'classnames';
import { createNanoEvents } from 'nanoevents';

import { noop } from '@alfalab/core-components-shared';
import { useLayoutEffect_SAFE_FOR_SSR } from '@alfalab/hooks';

import { useLottie } from './react-lottie';
import {
type AnimationDirection,
LottieDataState,
type LottieEvents,
type LottieProps,
type LottieRef,
} from './types';

import styles from './index.module.css';

export const Lottie = forwardRef<LottieRef, LottieProps>(
(
{
play = true,
speed = 1,
startFrame = 0,
initialFrame: initialFrameFromProps = startFrame,
endFrame,
iterations: iterationsFromProps = 0,
direction,
animation: animationData,
placeholder,
scale = 'fill',
size,
className,
},
forwardedRef,
) => {
const iterations = Math.max(
Math.max(iterationsFromProps, 0) === 0 ? Number.POSITIVE_INFINITY : iterationsFromProps,
1,
);
const [containerRef, animation, reset] = useLottie<HTMLDivElement>({
initialSegment: typeof endFrame === 'number' ? [startFrame, endFrame] : undefined,
autoplay: false,
loop: false,
path: animationData.path,
animationData: animationData.data,
rendererSettings: {
preserveAspectRatio: scale === 'fit' ? 'xMidYMid meet' : 'xMidYMid slice',
},
});
const playCountRef = useRef(animation?.playCount ?? 0);
const [dataState, setDataState] = useState(LottieDataState.INITIAL);
const [events] = useState(() => createNanoEvents<LottieEvents>());
let initialFrame = Math.max(startFrame, initialFrameFromProps);

initialFrame =
typeof endFrame === 'number' ? Math.min(endFrame, initialFrame) : initialFrame;

useImperativeHandle(
forwardedRef,
() => ({
reset,
subscribe(name, callback) {
return events.on(name, callback);
},
}),
[events, reset],
);

useEffect(() => {
playCountRef.current = animation?.playCount ?? 0;
}, [animation]);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

useImperativeHandle предназначен для кастомизации хендла, прокидываемого наружу через forwardRef. Использование его на внутреннем playCountRef нестандартно и вводит в заблуждение. Достаточно обычного эффекта:

useEffect(() => {
    playCountRef.current = animation?.playCount ?? 0;
}, [animation]);

// set loading state
useLayoutEffect_SAFE_FOR_SSR(() => {
if (animation) {
setDataState(animation.isLoaded ? LottieDataState.OK : LottieDataState.LOADING);
} else {
setDataState(LottieDataState.INITIAL);
}
}, [animation]);

// handle direction and speed
useLayoutEffect_SAFE_FOR_SSR(() => {
if (animation && playCountRef.current < iterations) {
if (typeof direction === 'number') {
animation.setDirection(direction);
}
animation.setSpeed(speed);
}
}, [animation, direction, iterations, speed]);

// handle play
useLayoutEffect_SAFE_FOR_SSR(() => {
const playCount = playCountRef.current;

if (
animation &&
dataState === LottieDataState.OK &&
playCount < iterations &&
play &&
animation.isPaused
) {
if (playCount === 0) {
const playFrame = Math.max(animation.currentFrame, initialFrame);

if (playFrame === animation.currentFrame) {
animation.play();
} else {
animation.goToAndPlay(playFrame, true);
}

events.emit(playFrame === initialFrame ? 'started' : 'resumed');
} else {
animation.play();
events.emit('resumed');
}
}
}, [animation, dataState, events, initialFrame, iterations, play]);

// handle pause
useLayoutEffect_SAFE_FOR_SSR(() => {
if (
animation &&
dataState === LottieDataState.OK &&
playCountRef.current < iterations &&
!play &&
!animation.isPaused
) {
animation.pause();
events.emit('stopped');
}
}, [animation, dataState, events, iterations, play]);

// handle listeners
useLayoutEffect_SAFE_FOR_SSR(() => {
if (animation) {
const subscriptions = [
animation.addEventListener('complete', () => {
playCountRef.current += 1;

events.emit('ended');

if (playCountRef.current < iterations) {
if (direction === 'reverseOnRepeat') {
animation.setDirection(
(animation.playDirection * -1) as AnimationDirection,
);
}
animation.goToAndPlay(
animation[
animation.playDirection === 1 ? 'firstFrame' : 'totalFrames'
],
true,
);
events.emit('started');
}
}),
animation.addEventListener('DOMLoaded', () => {
setDataState(LottieDataState.OK);
}),
animation.addEventListener('data_failed', () => {
setDataState(LottieDataState.ERROR);
}),
animation.addEventListener('enterFrame', ({ currentTime }) => {
events.emit('frame', { currentFrame: currentTime });
}),
];

return () => {
subscriptions.forEach((unsubscribe) => unsubscribe());
};
}

return noop;
}, [animation, direction, events, iterations]);

return (
<div className={cn(styles.component, className)} style={size}>
<div
ref={containerRef}
className={cn(styles.container, {
[styles.show]: dataState === LottieDataState.OK,
})}
/>
{(dataState === LottieDataState.LOADING || dataState === LottieDataState.ERROR) && (
<div className={styles.placeholder}>{placeholder?.(dataState)}</div>
)}
</div>
);
},
);
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Не хватает displayName — это стандарт библиотеки (см. Button, Checkbox и др.):

Lottie.displayName = "Lottie";

17 changes: 17 additions & 0 deletions packages/lottie/src/docs/Component.docs.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { Meta, Markdown } from '@storybook/addon-docs';
import { ComponentHeader, Tabs } from 'storybook/blocks';
import * as Stories from './Component.stories';

import Description from './description.mdx';
import Development from './development.mdx';
import Changelog from '../../CHANGELOG.md?raw';

<Meta of={Stories} />

<ComponentHeader name='Lottie' children='TODO' />

<Tabs
description={<Description />}
changelog={<Markdown>{Changelog}</Markdown>}
development={<Development />}
/>
21 changes: 21 additions & 0 deletions packages/lottie/src/docs/Component.stories.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import React from 'react';
import type { Meta, StoryObj } from '@storybook/react';

import { Lottie } from '@alfalab/core-components-lottie';

const meta: Meta<typeof Lottie> = {
title: 'Components/Lottie',
component: Lottie,
id: 'Lottie',
};

type Story = StoryObj<typeof Lottie>;

export const lottie: Story = {
name: 'Lottie',
render: () => {
return <Lottie animation={{ path: 'http://localhost:9009/twitter-heart.json' }} />;
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Хардкод localhost — в задеплоенном Storybook это сломается. Нужно использовать относительный путь, аналогично тому как сделано в description.mdx (./twitter-heart.json).

},
};

export default meta;
26 changes: 26 additions & 0 deletions packages/lottie/src/docs/description.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
## Lottie

```jsx live
render(() => {
const [{ play, direction }, setData] = React.useState({ play: true, direction: 1 });
const handleTooglePlay = () => {
setData((data) => ({ ...data, play: !data.play }));
};

return (
<React.StrictMode>
<div>
<Button onClick={handleTooglePlay}>{play ? 'Pause' : 'Play'}</Button>
<Lottie
play={play}
direction={direction}
speed={1}
iterations={0}
animation={{ path: './twitter-heart.json' }}
size={{ width: 400, height: 400 }}
/>
</div>
</React.StrictMode>
);
});
```
17 changes: 17 additions & 0 deletions packages/lottie/src/docs/development.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { ArgTypes } from '@storybook/addon-docs';
import { CssVars } from 'storybook/blocks';
import { Lottie } from '@alfalab/core-components-lottie';

## Подключениe

```jsx
import { Lottie } from '@alfalab/core-components-lottie';
```

## Использование

TODO

## Свойства

<ArgTypes of={Lottie} />
22 changes: 22 additions & 0 deletions packages/lottie/src/index.module.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
.component {
position: relative;
overflow: hidden;
}

.container {
position: absolute;
width: 100%;
height: 100%;
overflow: hidden;

&:not(.show) {
display: none;
}
}

.placeholder {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
2 changes: 2 additions & 0 deletions packages/lottie/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export { Lottie } from './component';
export { type LottieProps, LottieDataState } from './types';
Loading
Loading