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(next-app-router) implement an adapter for next-app-router #75

Open
wants to merge 14 commits into
base: main
Choose a base branch
from
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
5 changes: 4 additions & 1 deletion examples/nextjs-app-router/app/layout.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import type { Metadata } from 'next';
import './globals.css';
import { Providers } from '~/src/providers';

export const metadata: Metadata = {
title: 'Create Next App',
Expand All @@ -13,7 +14,9 @@ export default function RootLayout({
}>) {
return (
<html lang="en">
<body>{children}</body>
<body>
<Providers>{children}</Providers>
</body>
</html>
);
}
10 changes: 10 additions & 0 deletions examples/nextjs-app-router/app/overlay/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { Suspense } from 'react';
import { OverlayFunnel } from '../../src/overlay/OverlayCaseFunnel';

export default function Page() {
return (
<Suspense>
<OverlayFunnel />;
</Suspense>
);
}
15 changes: 8 additions & 7 deletions examples/nextjs-app-router/app/page.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
'use client';
import dynamic from 'next/dynamic';
const TestAppRouterFunnel = dynamic(() =>
import('../src/funnel').then(({ TestAppRouterFunnel }) => TestAppRouterFunnel),
);
import { Suspense } from 'react';
import { TestAppRouterFunnel } from '~/src/funnel';

export default function Home() {
//A pre-render error occurs in @use-funnel/browser 0.0.5 version.
return <TestAppRouterFunnel />;
return (
<Suspense>
<TestAppRouterFunnel />
</Suspense>
);
}
13 changes: 13 additions & 0 deletions examples/nextjs-app-router/e2e/app-router-funnel.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,17 @@ test('can move the steps of the funnel using history.push.', async ({ page }) =>
await page.goBack();

await expect(page.getByText('start')).toBeVisible();

await page.getByRole('button', { name: 'navigate to overlay funnel' }).click();

await expect(page.getByText(/Select Your School/)).toBeVisible();
await page.getByRole('button', { name: /school next/ }).click();
await expect(page.getByText(/overlay next/)).toBeVisible();
await expect(page.getByText(/school next/)).toBeVisible();

await page.click('input[type="date"]');
await page.fill('input[type="date"]', '2024-01-01');
await page.getByRole('button', { name: 'overlay next' }).click();
await expect(page.getByText(/school: A/)).toBeVisible();
await expect(page.getByText(/startDate: 2024-01-01/)).toBeVisible();
});
3 changes: 2 additions & 1 deletion examples/nextjs-app-router/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,10 @@
"e2e": "pnpm exec playwright test"
},
"dependencies": {
"@use-funnel/browser": "workspace:^",
"@use-funnel/core": "workspace:^",
"@use-funnel/next-app-router": "workspace:^",
"next": "14.2.13",
"overlay-kit": "^1.4.1",
"react": "^18",
"react-dom": "^18"
},
Expand Down
26 changes: 15 additions & 11 deletions examples/nextjs-app-router/src/funnel.tsx
Original file line number Diff line number Diff line change
@@ -1,19 +1,23 @@
'use client';
import { useFunnel } from '@use-funnel/browser';
import { useFunnel } from '@use-funnel/next-app-router';
import { useRouter } from 'next/navigation';

export const TestAppRouterFunnel = () => {
const funnel = useFunnel<FunnelState>({ id: FUNNEL_ID, initial: { step: 'start', context: {} } });
const router = useRouter();
return (
<funnel.Render
start={({ history }) => (
<div>
<p>start</p>

<button onClick={() => history.push('end')}>next</button>
</div>
)}
end={() => <div>end</div>}
/>
<>
<funnel.Render
start={({ history }) => (
<div>
<p>start</p>
<button onClick={() => history.push('end')}>next</button>
</div>
)}
end={() => <div>end</div>}
/>
<button onClick={() => router.push('/overlay')}>navigate to overlay funnel</button>
</>
);
};

Expand Down
33 changes: 33 additions & 0 deletions examples/nextjs-app-router/src/overlay/OverlayCaseFunnel.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
'use client';

import { useFunnel } from '@use-funnel/next-app-router';
import { SchoolInput } from './SchoolInput';
import { StartDate } from './StartDate';

export const OverlayFunnel = () => {
const funnel = useFunnel<{
SelectSchool: { school?: string };
StartDate: { school: string; startDate?: string };
Confirm: { school: string; startDate: string };
}>({ id: 'general', initial: { context: {}, step: 'SelectSchool' } });

return (
<funnel.Render
SelectSchool={({ history }) => <SchoolInput onNext={(school) => history.push('StartDate', { school: school })} />}
StartDate={funnel.Render.overlay({
render: ({ history, context }) => (
<StartDate
startDate={context.startDate}
onNext={(startDate) => history.push('Confirm', { school: context.school, startDate: startDate })}
/>
),
})}
Confirm={({ context }) => (
<div>
<div>school: {context.school}</div>
<div>startDate: {context.startDate}</div>
</div>
)}
/>
);
};
18 changes: 18 additions & 0 deletions examples/nextjs-app-router/src/overlay/SchoolInput.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { useState } from 'react';

interface Props {
onNext: (school: string) => void;
}

export function SchoolInput({ onNext }: Props) {
const [school, setSchool] = useState('A');
return (
<div>
<h2>Select Your School</h2>
<input type="radio" value={'A'} checked={school === 'A'} onChange={(e) => setSchool(e.target.value)} />
<input type="radio" value={'B'} checked={school === 'B'} onChange={(e) => setSchool(e.target.value)} />
<input type="radio" value={'C'} checked={school === 'C'} onChange={(e) => setSchool(e.target.value)} />
<button onClick={() => onNext(school)}>school next</button>
</div>
);
}
12 changes: 12 additions & 0 deletions examples/nextjs-app-router/src/overlay/StartDate.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { ReactNode, useState } from 'react';

export const StartDate = ({ startDate, onNext }: { startDate?: string; onNext: (startDate: string) => void }) => {
const [date, setDate] = useState(startDate ?? '');

return (
<div>
<input type="date" value={date} onChange={(e) => setDate(e.target.value)} />
<button onClick={() => onNext(date)}>overlay next</button>
</div>
);
};
5 changes: 5 additions & 0 deletions examples/nextjs-app-router/src/providers.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
'use client';
import { OverlayProvider } from 'overlay-kit';
export const Providers = ({ children }: { children: React.ReactNode }) => {
return <OverlayProvider>{children}</OverlayProvider>;
};
65 changes: 65 additions & 0 deletions packages/next-app-router/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
{
"name": "@use-funnel/next-app-router",
"version": "0.0.0",
"description": "",
"type": "module",
"main": "./dist/index.js",
"publishConfig": {
"access": "public",
"main": "./dist/index.js",
"types": "./dist/index.d.ts",
"module": "./dist/index.js",
"exports": {
".": {
"types": "./dist/index.d.ts",
"default": "./dist/index.js"
},
"./package.json": "./package.json"
}
},
"files": [
"dist",
"package.json"
],
"scripts": {
"test": "vitest run",
"test:unit": "vitest --root test/",
"build": "rimraf dist && concurrently \"pnpm:build:*\"",
"build:dist": "tsup",
"build:types": "tsc -p tsconfig.build.json --emitDeclarationOnly",
"prepublish": "pnpm test && pnpm build"
},
"keywords": [],
"author": "",
"repository": {
"type": "git",
"url": "https://github.com/toss/use-funnel.git",
"directory": "packages/next-app-router"
},
"license": "MIT",
"homepage": "https://use-funnel.slash.page/",
"bugs": "https://github.com/toss/use-funnel/issues",
"dependencies": {
"@use-funnel/core": "workspace:^"
},
"devDependencies": {
"@testing-library/react": "^15.0.7",
"@testing-library/user-event": "^14.5.2",
"@types/react": "^18.3.2",
"@types/react-dom": "^18.3.0",
"concurrently": "^8.2.2",
"globals": "^15.3.0",
"jsdom": "^24.1.0",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"rimraf": "^5.0.7",
"tsup": "^8.0.2",
"typescript": "^5.1.6",
"vitest": "^1.6.0"
},
"peerDependencies": {
"next": ">=13",
"react": ">=16.8"
},
"sideEffects": false
}
75 changes: 75 additions & 0 deletions packages/next-app-router/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
'use client';
import { createUseFunnel } from '@use-funnel/core';
import { useSearchParams } from 'next/navigation';
import { useLayoutEffect, useMemo, useState } from 'react';

export const useFunnel = createUseFunnel(({ id, initialState }) => {
const searchParams = useSearchParams();
const [state, setState] = useState<Record<string, any>>({});
useLayoutEffect(() => {
if (typeof window !== 'undefined') {
setState(window.history.state);
}

function handlePopState(event: PopStateEvent) {
setState(event.state);
}
window.addEventListener('popstate', handlePopState);
return () => {
window.removeEventListener('popstate', handlePopState);
};
}, []);

const currentStep = searchParams.get(`${id}.step`);
const currentContext = state?.[`${id}.context`];

const currentState = useMemo(() => {
return currentStep != null && currentContext != null
? ({
step: currentStep,
context: currentContext,
} as typeof initialState)
: initialState;
}, [currentStep, currentContext, initialState]);

const history: (typeof initialState)[] = useMemo(
() => state?.[`${id}.histories`] ?? [currentState],
[state, currentState],
);

const currentIndex = history.length - 1;
return useMemo(
() => ({
history,
currentIndex,
currentState,
push(newState) {
const newSearchParams = new URLSearchParams(searchParams);
const newHistoryState = {
...state,
[`${id}.context`]: newState.context,
[`${id}.histories`]: [...(history ?? []), newState],
};

newSearchParams.set(`${id}.step`, newState.step);
window.history.pushState(newHistoryState, '', `?${newSearchParams.toString()}`);
setState(newHistoryState);
},
replace(newState) {
const newSearchParams = new URLSearchParams(searchParams);
newSearchParams.set(`${id}.step`, newState.step);
const newHistoryState = {
...state,
[`${id}.context`]: newState.context,
[`${id}.histories`]: [...(history ?? []), newState],
};
window.history.replaceState(newHistoryState, '', `?${newSearchParams.toString()}`);
setState(newHistoryState);
},
go(index) {
window.history.go(index);
},
}),
[history, currentIndex, currentState, searchParams, id, state],
);
});
55 changes: 55 additions & 0 deletions packages/next-app-router/test/index.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import { render, screen } from '@testing-library/react';
import { userEvent } from '@testing-library/user-event';
import { describe, expect, test } from 'vitest';

import { useFunnel } from '../src/index.js';

describe('Test useFunnel next-app-router router', () => {
test('should work', async () => {
function FunnelTest() {
const funnel = useFunnel<{
A: { id?: string };
B: { id: string };
}>({
id: 'vitest',
initial: {
step: 'A',
context: {},
},
});
switch (funnel.step) {
case 'A': {
return <button onClick={() => funnel.history.push('B', { id: 'vitest' })}>Go B</button>;
}
case 'B': {
return (
<div>
<button onClick={() => window.history.back()}>Go Back</button>
<div>{funnel.context.id}</div>
</div>
);
}
default: {
throw new Error('Invalid step');
}
}
}

render(<FunnelTest />);

expect(screen.queryByText('Go B')).not.toBeNull();

const user = userEvent.setup();
await user.click(screen.getByText('Go B'));

expect(screen.queryByText('vitest')).not.toBeNull();
await user.click(screen.getByText('Go Back'));

expect(screen.queryByText('vitest')).toBeNull();
expect(screen.queryByText('Go B')).not.toBeNull();
});

test('hello' , async () => {

})
});
4 changes: 4 additions & 0 deletions packages/next-app-router/tsconfig.build.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"extends": "./tsconfig.json",
"exclude": ["test"]
}
Loading