Skip to content

Commit

Permalink
feat: Add vanilla React adapter sandbox
Browse files Browse the repository at this point in the history
Showcasing two adapters: plain client-side React (no framework)
and unit testing with Vitest.
  • Loading branch information
franky47 committed Oct 22, 2024
1 parent a101370 commit e603a4d
Show file tree
Hide file tree
Showing 18 changed files with 903 additions and 53 deletions.
24 changes: 24 additions & 0 deletions packages/adapters/react/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*

node_modules
dist
dist-ssr
*.local

# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
50 changes: 50 additions & 0 deletions packages/adapters/react/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
# React + TypeScript + Vite

This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.

Currently, two official plugins are available:

- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react/README.md) uses [Babel](https://babeljs.io/) for Fast Refresh
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react-swc) uses [SWC](https://swc.rs/) for Fast Refresh

## Expanding the ESLint configuration

If you are developing a production application, we recommend updating the configuration to enable type aware lint rules:

- Configure the top-level `parserOptions` property like this:

```js
export default tseslint.config({
languageOptions: {
// other options...
parserOptions: {
project: ['./tsconfig.node.json', './tsconfig.app.json'],
tsconfigRootDir: import.meta.dirname,
},
},
})
```

- Replace `tseslint.configs.recommended` to `tseslint.configs.recommendedTypeChecked` or `tseslint.configs.strictTypeChecked`
- Optionally add `...tseslint.configs.stylisticTypeChecked`
- Install [eslint-plugin-react](https://github.com/jsx-eslint/eslint-plugin-react) and update the config:

```js
// eslint.config.js
import react from 'eslint-plugin-react'

export default tseslint.config({
// Set the react version
settings: { react: { version: '18.3' } },
plugins: {
// Add the react plugin
react,
},
rules: {
// other rules...
// Enable its recommended rules
...react.configs.recommended.rules,
...react.configs['jsx-runtime'].rules,
},
})
```
13 changes: 13 additions & 0 deletions packages/adapters/react/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vite + React + TS</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
32 changes: 32 additions & 0 deletions packages/adapters/react/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
{
"name": "adapters-react",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite --port 4000",
"build": "tsc -b && vite build",
"preview": "vite preview",
"test": "vitest"
},
"dependencies": {
"nuqs": "workspace:*",
"react": "rc",
"react-dom": "rc"
},
"devDependencies": {
"@testing-library/dom": "^10.1.0",
"@testing-library/jest-dom": "^6.4.5",
"@testing-library/react": "^15.0.7",
"@testing-library/user-event": "^14.5.2",
"@types/node": "^20.16.3",
"@types/react": "^18.3.7",
"@types/react-dom": "^18.3.0",
"@vitejs/plugin-react": "^4.3.1",
"globals": "^15.9.0",
"jsdom": "^24.1.0",
"typescript": "^5.5.3",
"vite": "^5.4.1",
"vitest": "^1.6.0"
}
}
14 changes: 14 additions & 0 deletions packages/adapters/react/src/App.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { CounterButton } from './components/counter-button'
import { SearchInput } from './components/search-input'

export default function App() {
return (
<>
<h1>Vite + React + nuqs</h1>
<div>
<CounterButton />
<SearchInput />
</div>
</>
)
}
36 changes: 36 additions & 0 deletions packages/adapters/react/src/components/counter-button.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { NuqsTestingAdapter, type UrlUpdateEvent } from 'nuqs/adapters/testing'
import { describe, expect, it, vi } from 'vitest'
import { CounterButton } from './counter-button'

describe('CounterButton', () => {
it('should render the button with state loaded from the URL', () => {
render(<CounterButton />, {
wrapper: ({ children }) => (
<NuqsTestingAdapter searchParams="?count=42">
{children}
</NuqsTestingAdapter>
)
})
expect(screen.getByRole('button')).toHaveTextContent('count is 42')
})
it('should increment the count when clicked', async () => {
const user = userEvent.setup()
const onUrlUpdate = vi.fn<[UrlUpdateEvent]>()
render(<CounterButton />, {
wrapper: ({ children }) => (
<NuqsTestingAdapter searchParams="?count=42" onUrlUpdate={onUrlUpdate}>
{children}
</NuqsTestingAdapter>
)
})
const button = screen.getByRole('button')
await user.click(button)
expect(button).toHaveTextContent('count is 43')
expect(onUrlUpdate).toHaveBeenCalledOnce()
expect(onUrlUpdate.mock.calls[0][0].queryString).toBe('?count=43')
expect(onUrlUpdate.mock.calls[0][0].searchParams.get('count')).toBe('43')
expect(onUrlUpdate.mock.calls[0][0].options.history).toBe('push')
})
})
9 changes: 9 additions & 0 deletions packages/adapters/react/src/components/counter-button.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { parseAsInteger, useQueryState } from 'nuqs'

export function CounterButton() {
const [count, setCount] = useQueryState(
'count',
parseAsInteger.withDefault(0).withOptions({ history: 'push' })
)
return <button onClick={() => setCount(c => c + 1)}>count is {count}</button>
}
45 changes: 45 additions & 0 deletions packages/adapters/react/src/components/search-input.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { NuqsTestingAdapter, type UrlUpdateEvent } from 'nuqs/adapters/testing'
import { describe, expect, it, vi } from 'vitest'
import { SearchInput } from './search-input'

describe('SearchInput', () => {
it('should render the input with state loaded from the URL', () => {
render(<SearchInput />, {
wrapper: ({ children }) => (
<NuqsTestingAdapter
searchParams={{
search: 'nuqs'
}}
>
{children}
</NuqsTestingAdapter>
)
})
const input = screen.getByRole('search')
expect(input).toHaveValue('nuqs')
})
it('should follow the user typing text', async () => {
const user = userEvent.setup()
const onUrlUpdate = vi.fn<[UrlUpdateEvent]>()
render(<SearchInput />, {
wrapper: ({ children }) => (
<NuqsTestingAdapter onUrlUpdate={onUrlUpdate} rateLimitFactor={0}>
{children}
</NuqsTestingAdapter>
)
})
const expectedState = 'Hello, world!'
const expectedParam = 'Hello,+world!'
const searchInput = screen.getByRole('search')
await user.type(searchInput, expectedState)
expect(searchInput).toHaveValue(expectedState)
expect(onUrlUpdate).toHaveBeenCalledTimes(expectedParam.length)
for (let i = 0; i < expectedParam.length; i++) {
expect(onUrlUpdate.mock.calls[i][0].queryString).toBe(
`?search=${expectedParam.slice(0, i + 1)}`
)
}
})
})
15 changes: 15 additions & 0 deletions packages/adapters/react/src/components/search-input.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { parseAsString, useQueryStates } from 'nuqs'

export function SearchInput() {
const [{ search }, setSearch] = useQueryStates({
search: parseAsString.withDefault('').withOptions({ clearOnDefault: true })
})
return (
<input
role="search"
type="search"
value={search}
onChange={e => setSearch({ search: e.target.value })}
/>
)
}
12 changes: 12 additions & 0 deletions packages/adapters/react/src/main.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { NuqsAdapter } from 'nuqs/adapters/react'
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import App from './App.tsx'

createRoot(document.getElementById('root')!).render(
<StrictMode>
<NuqsAdapter>
<App />
</NuqsAdapter>
</StrictMode>
)
1 change: 1 addition & 0 deletions packages/adapters/react/src/vite-env.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
/// <reference types="vite/client" />
25 changes: 25 additions & 0 deletions packages/adapters/react/tsconfig.app.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
{
"compilerOptions": {
"target": "ES2020",
"useDefineForClassFields": true,
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"types": ["node", "@testing-library/jest-dom"],
"module": "ESNext",
"skipLibCheck": true,

/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"isolatedModules": true,
"moduleDetection": "force",
"noEmit": true,
"jsx": "react-jsx",

/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true
},
"include": ["src"]
}
7 changes: 7 additions & 0 deletions packages/adapters/react/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"files": [],
"references": [
{ "path": "./tsconfig.app.json" },
{ "path": "./tsconfig.node.json" }
]
}
23 changes: 23 additions & 0 deletions packages/adapters/react/tsconfig.node.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
{
"compilerOptions": {
"target": "ES2022",
"lib": ["ES2023"],
"types": ["node", "@testing-library/jest-dom"],
"module": "ESNext",
"skipLibCheck": true,

/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"isolatedModules": true,
"moduleDetection": "force",
"noEmit": true,

/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true
},
"include": ["vite.config.ts"]
}
17 changes: 17 additions & 0 deletions packages/adapters/react/vite.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import react from '@vitejs/plugin-react'
import { defineConfig } from 'vite'

// https://vitejs.dev/config/
export default defineConfig(() => ({
plugins: [react()],
// Vitest configuration
test: {
globals: true,
environment: 'jsdom',
setupFiles: ['vitest.setup.ts'],
include: ['**/*.test.?(c|m)[jt]s?(x)'],
env: {
IS_REACT_ACT_ENVIRONMENT: 'true'
}
}
}))
8 changes: 8 additions & 0 deletions packages/adapters/react/vitest.setup.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import * as matchers from '@testing-library/jest-dom/matchers'
import { cleanup } from '@testing-library/react'
import { afterEach, expect } from 'vitest'

expect.extend(matchers)

// https://testing-library.com/docs/react-testing-library/api/#cleanup
afterEach(cleanup)
Loading

0 comments on commit e603a4d

Please sign in to comment.