Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(@yourssu/react): create useFunnel #67

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 3 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
3 changes: 2 additions & 1 deletion apps/docs/src/pages/react/hooks/_meta.en.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
{
"useInterval": "useInterval",
"useMediaQuery": "useMediaQuery",
"useSecTimer": "useSecTimer"
"useSecTimer": "useSecTimer",
"useFunnel": "useFunnel"
}
3 changes: 2 additions & 1 deletion apps/docs/src/pages/react/hooks/_meta.ko.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
{
"useInterval": "useInterval",
"useMediaQuery": "useMediaQuery",
"useSecTimer": "useSecTimer"
"useSecTimer": "useSecTimer",
"useFunnel": "useFunnel"
}
52 changes: 52 additions & 0 deletions apps/docs/src/pages/react/hooks/useFunnel.en.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
# useFunnel

`useFunnel` is a custom hook that helps manage components with multiple steps or processes. It makes it easy to handle transitions between components with steps, providing `next`, `prev`, and `setStep` functions for navigation.

## API

```ts
function useFunnel(initialStep: string, steps: string[]);
```

#### Parameters
initialStep (string): Sets the initial step of the funnel.
steps (string[]): Defines all the steps in the funnel.


#### Return Value
- Funnel: The funnel component object that is used as a parent component.
- next: Moves to the next step's component.
- prev: Moves to the previous step's component.
- setStep: Manually moves to a specific step's component.


## Example
```jsx
const MyComponent = () => {
const { Funnel, next, prev, setStep }
= useFunnel('step1', ['step1', 'step2', 'step3']);

return (
<Funnel>
<Funnel.Step name="step1">
<div>Step1 Component</div>
<button onClick={next}>Next</button>
</Funnel.Step>
<Funnel.Step name="step2">
<div>Step2 Component</div>
<button onClick={prev}>Prev</button>
<button onClick={next}>Next</button>
</Funnel.Step>
<Funnel.Step name="step3">
<div>Step3 Component</div>
<button onClick={prev}>Prev</button>
</Funnel.Step>
</Funnel>
);
};
```

## Notes
1. Define each step component by setting the name property of Funnel.Step.
2. If prev is called on the first step or next is called on the last step, the component will not transition.

54 changes: 54 additions & 0 deletions apps/docs/src/pages/react/hooks/useFunnel.ko.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
# useFunnel

`useFunnel`은 여러 단계나 프로세스를 가진 컴포넌트를 관리하는 데 도움을 주는 커스텀 훅입니다.
단계가 존재하는 컴포넌트 간 전환을 쉽게 관리할 수 있으며, `next`, `prev`, `setStep` 함수들을 제공하여 네비게이션을 지원합니다.

## API

```ts
function useFunnel(initialStep: string, steps: string[]);
```

#### Parameters

- `initialStep` (string): 퍼널의 초기 스텝을 설정합니다.
- `totalSteps` (string[]): 퍼널의 전체 스텝을 설정합니다.

#### Return value

- Funnel: 퍼널 객체입니다. 상위 컴포넌트로 활용합니다.
- next: 다음 스텝의 컴포넌트로 이동합니다.
- prev: 이전 스텝의 컴포넌트로 이동합니다.
- setStep: 특정 스텝의 컴포넌트로 이동합니다.

## Example

```jsx
const MyComponent = () => {
const { Funnel, next, prev, setStep }
= useFunnel('step1', ['step1', 'step2', 'step3']);

return (
<Funnel>
<Funnel.Step name="step1">
<div>Step1 Component</div>
<button onClick={next}>Next</button>
</Funnel.step>
<Funnel.Step name="step2">
<div>Step2 Component</div>
<button onClick={next}>Prev</button>
</Funnel.step>
<Funnel.Step name="step3">
<div>Step3 Component</div>
<button onClick={prev}>Prev</button>
<button onClick={next}>Next</button>
</Funnel.step>
</Funnel>
);
};
```

## Notes

1. Funnel.Step의 name 속성을 통해 각 스텝의 컴포넌트를 정의합니다.
2. 첫번째 컴포넌트에서 prev를 호출하거나 마지막 컴포넌트에서 next를 호출하면 이동하지 않습니다.
7 changes: 6 additions & 1 deletion packages/react/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,12 @@
"test": "vitest"
},
"devDependencies": {
"@testing-library/jest-dom": "^6.6.2",
"@testing-library/react": "^15.0.7",
"@yourssu/utils": "workspace:*"
"@testing-library/react-hooks": "^8.0.1",
"@types/testing-library__react": "^10.2.0",
"@types/testing-library__react-hooks": "^4.0.0",
"@yourssu/utils": "workspace:*",
"vitest": "^1.6.0"
}
}
146 changes: 146 additions & 0 deletions packages/react/src/hooks/useFunnel.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
import { act } from '@testing-library/react-hooks';
import { render } from '@testing-library/react';
import { describe, it, expect } from 'vitest';
import { useFunnel } from './useFunnel';
import '@testing-library/jest-dom';

const steps = ['Step1', 'Step2', 'Step3'] as const;

describe('useFunnel', () => {

it('올바른 initialStep이 랜더링', () => {
const TestComponent = () => {
const { Funnel, next } = useFunnel({
initialStep: 'Step2',
steps,
});

return (
<div>
<Funnel>
<Funnel.Step name="Step1">
<div>Content of Step1</div>
</Funnel.Step>
<Funnel.Step name="Step2">
<div>Content of Step2</div>
</Funnel.Step>
<Funnel.Step name="Step3">
<div>Content of Step3</div>
</Funnel.Step>
</Funnel>
<button onClick={next}>Next</button>
</div>
);
};

const { getByText } = render(<TestComponent />);


expect(getByText('Content of Step2')).toBeInTheDocument();
});

it('next 함수 호출 시 다음 스텝으로 이동', () => {
const TestComponent = () => {
const { Funnel, next } = useFunnel({
initialStep: 'Step1',
steps,
});

return (
<div>
<Funnel>
<Funnel.Step name="Step1">
<div>Content of Step1</div>
</Funnel.Step>
<Funnel.Step name="Step2">
<div>Content of Step2</div>
</Funnel.Step>
<Funnel.Step name="Step3">
<div>Content of Step3</div>
</Funnel.Step>
</Funnel>
<button onClick={next}>Next</button>
</div>
);
};

const { getByText, queryByText } = render(<TestComponent />);

act(() => {
getByText('Next').click();
});

expect(getByText('Content of Step2')).toBeInTheDocument();
expect(queryByText('Content of Step1')).not.toBeInTheDocument();
});

it('prev 함수 호출 시 이전 스텝으로 이동', () => {
const TestComponent = () => {
const { Funnel, next, prev } = useFunnel({
initialStep: 'Step2',
steps,
});

return (
<div>
<Funnel>
<Funnel.Step name="Step1">
<div>Content of Step1</div>
</Funnel.Step>
<Funnel.Step name="Step2">
<div>Content of Step2</div>
</Funnel.Step>
<Funnel.Step name="Step3">
<div>Content of Step3</div>
</Funnel.Step>
</Funnel>
<button onClick={next}>Next</button>
<button onClick={prev}>Prev</button>
</div>
);
};

const { getByText, queryByText } = render(<TestComponent />);

act(() => {
getByText('Prev').click();
});

expect(getByText('Content of Step1')).toBeInTheDocument();
expect(queryByText('Content of Step2')).not.toBeInTheDocument();
});

it('첫번째 스텝에서 prev 함수 호출 시 이전 스텝으로 이동하지 않음', () => {
const TestComponent = () => {
const { Funnel, prev } = useFunnel({
initialStep: 'Step1',
steps,
});

return (
<div>
<Funnel>
<Funnel.Step name="Step1">
<div>Content of Step1</div>
</Funnel.Step>
<Funnel.Step name="Step2">
<div>Content of Step2</div>
</Funnel.Step>
<Funnel.Step name="Step3">
<div>Content of Step3</div>
</Funnel.Step>
</Funnel>
<button onClick={prev}>Prev</button>
</div>
);
};

const { getByText } = render(<TestComponent />);

act(() => {
getByText('Prev').click();
});

expect(getByText('Content of Step1')).toBeInTheDocument();
});
});
60 changes: 60 additions & 0 deletions packages/react/src/hooks/useFunnel.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import { useState, Children, ReactElement, ReactNode } from 'react';

interface StepProps<StepName extends string> {
name: StepName;
children: React.ReactNode;
}

type StepElementType<StepName extends string> = ReactElement<StepProps<StepName>>;

interface FunnelProps<StepName extends string> {
children: StepElementType<StepName>[] | StepElementType<StepName>;
}

export const useFunnel = <Steps extends readonly string[]>({
initialStep,
steps,
}: {
initialStep: Steps[number];
steps: Steps;
}) => {
const [currentStep, setCurrentStep] = useState<Steps[number]>(initialStep);

const next = () => {
const currentIndex = steps.indexOf(currentStep);
if (currentIndex < steps.length - 1) {
setCurrentStep(steps[currentIndex + 1]);
}
};

const prev = () => {
const currentIndex = steps.indexOf(currentStep);
if (currentIndex > 0) {
setCurrentStep(steps[currentIndex - 1]);
}
};

const Step = (props: StepProps<Steps[number]>) => {
return <>{props.children}</>;
};

const isFunnelStep = (child: ReactNode): child is StepElementType<Steps[number]> => {
return (child as StepElementType<Steps[number]>).props.name !== undefined;
};

const Funnel = ({ children }: FunnelProps<Steps[number]>) => {
const targetStep = Children.toArray(children).find((child) => {
if (!isFunnelStep(child)) return false;
return child.props.name === currentStep;
}) as StepElementType<Steps[number]> | undefined;

return targetStep || null;
};

return {
Funnel: Object.assign(Funnel, { Step }),
next,
prev,
setStep : setCurrentStep,
};
Copy link

@fecapark fecapark Oct 27, 2024

Choose a reason for hiding this comment

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

p4) 여기서 리턴 방식을 객체로 변경하신 이유가 있을까요?
이 훅같은 경우는 사용처에 따라 Funnel 컴포넌트의 이름이 바뀔 가능성이 큰데 배열로 리턴하면 그런 변경에 좀 더 유연하지 않을까 싶어요.

ex)

// 리턴 부분
return [Object.assign(Funnel, { Step }), { next, prev, setStep }] as const;

// 사용 부분
const [회원가입퍼널, { setStep }] = useFunnel(...)

느낌으로요.

Copy link
Author

Choose a reason for hiding this comment

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

반영했습니다!
dbc872c

};
1 change: 1 addition & 0 deletions packages/react/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
export { useInterval } from './hooks/useInterval.ts';
export { useSecTimer } from './hooks/useSecTimer.ts';
export { useMediaQuery } from './hooks/useMediaQuery.ts';
export { useFunnel } from './hooks/useFunnel';
2 changes: 1 addition & 1 deletion packages/react/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"extends": "../../tsconfig.json",
"compilerOptions": {
"rootDir": "./src",
"outDir": "./dist"
"outDir": "./dist",
},
"include": ["src"]
}
Loading
Loading