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

chore: examples for @kubb/react #1388

Merged
merged 1 commit into from
Nov 12, 2024
Merged
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: 5 additions & 0 deletions .changeset/shiny-rules-invent.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@kubb/react": patch
---

Better error logging + wider range for `@kubb/react` peerDependency
1 change: 1 addition & 0 deletions .codesandbox/ci.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
"/examples/react-query",
"/examples/typescript",
"/examples/simple-single",
"/examples/react",
"/examples/solid-query",
"/examples/svelte-query",
"/examples/swr",
Expand Down
4 changes: 4 additions & 0 deletions docs/.vitepress/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -309,6 +309,10 @@ const examplesSidebar = [
text: 'Generators <span class="new">new</span>',
link: '/examples/generators',
},
{
text: 'React <span class="new">new</span>',
link: '/examples/react',
},
]

const blogSidebar = [
Expand Down
3 changes: 3 additions & 0 deletions docs/changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@ title: Changelog

# Changelog

## 3.0.4
- [`react`](/helpers/react//): Better error logging + wider range for `@kubb/react` peerDependency

## 3.0.3
- [`plugin-ts`](/plugins/plugin-ts/): `@deprecated` jsdoc tag for schemas

Expand Down
18 changes: 18 additions & 0 deletions docs/examples/react.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
---
title: React
aside: false
---

<iframe
src="https://codesandbox.io/embed/github/kubb-labs/kubb/tree/main/examples/react?fontsize=14&module=%2Fsrc%2Fgen%2Fmodels%2FPerson.ts&theme=dark&view=editor"
:style="{
width: '100%',
height: '700px',
border: 0,
borderRadius: '4px',
overflow: 'hidden'
}"
title="React"
allow="accelerometer; ambient-light-sensor; camera; encrypted-media; geolocation; gyroscope; hid; microphone; midi; payment; usb; vr; xr-spatial-tracking"
sandbox="allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts"
/>
16 changes: 16 additions & 0 deletions docs/helpers/react/hooks/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,22 @@ outline: deep
Some hooks that can be used with `@kubb/react`.


## useLifecycle

`useLifecycle` will return some helpers to exit/restart the generation.


```tsx
import { useCli } from '@kubb/react'

function Component() {
const { exit } = useLifecycle()

return null
}
```


## useApp

`useApp` will return the current App with plugin, pluginManager, fileManager, mode, ...
Expand Down
2 changes: 1 addition & 1 deletion docs/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@
"cross-env": "^7.0.3",
"react": "^18.3.1",
"unplugin-kubb": "workspace:^",
"vite": "^5.4.10"
"vite": "^5.4.11"
},
"packageManager": "pnpm@9.12.0",
"engines": {
Expand Down
2 changes: 1 addition & 1 deletion e2e/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@
"@tanstack/svelte-query": "^5.59.20",
"@tanstack/vue-query": "^5.59.20",
"axios": "^1.7.7",
"msw": "^2.6.3",
"msw": "^2.6.4",
"react": "^18.3.1",
"solid-js": "^1.9.3",
"svelte": "^3.59.2",
Expand Down
2 changes: 1 addition & 1 deletion examples/advanced/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@
"@tanstack/svelte-query": "^5.59.20",
"@tanstack/vue-query": "^5.59.20",
"axios": "^1.7.7",
"msw": "^2.6.3",
"msw": "^2.6.4",
"react": "^18.3.1",
"solid-js": "^1.9.3",
"svelte": "^3.59.2",
Expand Down
2 changes: 1 addition & 1 deletion examples/msw/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@
"@kubb/plugin-oas": "workspace:*",
"@kubb/plugin-ts": "workspace:*",
"@mswjs/http-middleware": "^0.9.2",
"msw": "^2.6.3",
"msw": "^2.6.4",
"react": "^18.3.1",
"tsup": "^8.3.5"
},
Expand Down
2 changes: 2 additions & 0 deletions examples/react/.codesandbox/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
FROM node:20-bullseye
RUN npm i -g pnpm
20 changes: 20 additions & 0 deletions examples/react/.codesandbox/build.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import fs from 'node:fs'

const pkgJsonPaths = ['package.json']
try {
for (const pkgJsonPath of pkgJsonPaths) {
const pkg = JSON.parse(fs.readFileSync(pkgJsonPath, 'utf-8'))
const oldVersion = 'workspace:*'
const newVersion = 'alpha'

const content = JSON.stringify(pkg, null, '\t') + '\n'
const newContent = content
// @ts-ignore
.replaceAll(`"${oldVersion}"`, `"${newVersion}"`)

fs.writeFileSync(pkgJsonPath, newContent)
}
} catch (error) {
console.error(error)
process.exit(1)
}
33 changes: 33 additions & 0 deletions examples/react/.codesandbox/tasks.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
{
"$schema": "https://codesandbox.io/schemas/tasks.json",
"setupTasks": [
{
"name": "Replace workspace:* by latest",
"command": "node ./.codesandbox/build.js"
},
{
"name": "Install Dependencies",
"command": "pnpm install"
}
],
"tasks": {
"dev": {
"name": "dev",
"command": "pnpm dev",
"runAtStart": true,
"preview": {
"port": 5173
}
},
"build": {
"name": "build",
"command": "pnpm build",
"runAtStart": false
},
"update": {
"name": "update",
"command": "pnpm update",
"runAtStart": false
}
}
}
43 changes: 43 additions & 0 deletions examples/react/example1/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { useEffect, useRef, useState } from 'react'

import { Text, createRoot, useLifecycle } from '@kubb/react'

// attach node stdout with Kubb's internal one
const root = createRoot({ stdout: process.stdout })

/**
* Render component that will count down from 5
*/
function Component() {
const timer = useRef<NodeJS.Timer>()
const [counter, setCounter] = useState(5)
const { exit } = useLifecycle()

useEffect(() => {
timer.current = setInterval(() => {
setCounter((previousCounter) => {
return previousCounter - 1
})
}, 1000)

return () => {
clearInterval(timer.current)
}
}, [])

useEffect(() => {
if (counter === 0) {
// trigger unmount
exit()
clearInterval(timer.current)
}
}, [counter, exit])

if (counter === 0) {
return <Text indentSize={2}>Finished</Text>
}

return <Text>Counter: {counter}</Text>
}

root.render(<Component />)
28 changes: 28 additions & 0 deletions examples/react/example2/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import process from 'node:process'
import React from 'react'

import path from 'node:path'
import { Const, File, createRoot } from '@kubb/react'

const root = createRoot({ stdout: process.stdout })

/**
* Create a simple file and write it to the file-system
*/
function Component() {
return (
<File path={path.resolve(__dirname, 'result.ts')} baseName={'result.ts'}>
<File.Source>
<Const name={'hello'}>"World!"</Const>
</File.Source>
</File>
)
}

async function start() {
root.render(<Component />)
console.log('\nFiles: ', root.files.length)
await root.write()
}

start()
1 change: 1 addition & 0 deletions examples/react/example2/result.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
const hello = 'World!'
42 changes: 42 additions & 0 deletions examples/react/example3/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import process from 'node:process'
import React from 'react'

import path from 'node:path'
import { Const, File, createRoot } from '@kubb/react'

const root = createRoot({ stdout: process.stdout })

/**
* Create 2 files and write them to the file-system
*/
function Component() {
const namesPath = path.resolve(__dirname, 'name.ts')
const helloWorldPath = path.resolve(__dirname, 'result.ts')

return (
<>
<File path={namesPath} baseName={'name.ts'}>
<File.Source>
<Const export asConst name={'name'}>
"Lily"
</Const>
</File.Source>
</File>

<File path={helloWorldPath} baseName={'result.ts'}>
<File.Import root={helloWorldPath} name={['name']} path={namesPath} />
<File.Source>
<Const name={'hello'}>name</Const>
</File.Source>
</File>
</>
)
}

async function start() {
root.render(<Component />)
console.log('\nFiles: ', root.files.length)
await root.write()
}

start()
1 change: 1 addition & 0 deletions examples/react/example3/name.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export const name = 'Lily' as const
3 changes: 3 additions & 0 deletions examples/react/example3/result.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import { name } from './name'

const hello = name
67 changes: 67 additions & 0 deletions examples/react/example4/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import process from 'node:process'
import React, { useEffect, useState } from 'react'

import path from 'node:path'
import { Const, File, Function, createRoot, useLifecycle } from '@kubb/react'

const root = createRoot({ stdout: process.stdout })

const fetchNames = async (): Promise<string[]> => {
return new Promise((resolve) => {
setTimeout(() => {
resolve(['Lily', 'Jan'])
}, 2000)
})
}

/**
* Create a file and append data based on a promise
*/
function Component() {
const [names, setNames] = useState<string[]>([])
const { exit } = useLifecycle()

useEffect(() => {
fetchNames().then((newNames) => {
setNames(newNames)
exit()
})
}, [exit])

return (
<File path={path.resolve(__dirname, 'result.ts')} baseName={'result.ts'}>
<File.Source>
<Const name={'names'}>"{names.join(' and ')}"</Const>
<br />
<Function.Arrow name={'getNames'} export singleLine>
names
</Function.Arrow>
<Function.Arrow name={'getFirstChar'} export>
return names.charAt(0)
</Function.Arrow>
<br />
<Function
name={'getNamesTyped'}
export
returnType={'TNames'}
JSDoc={{
comments: ['Returns the names'],
}}
generics={['TNames extends string']}
>
return names as TNames
</Function>
</File.Source>
</File>
)
}

async function start() {
root.render(<Component />)

await root.waitUntilExit()
console.log('\nFiles: ', root.files.length)
await root.write()
}

start()
12 changes: 12 additions & 0 deletions examples/react/example4/result.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
const names = 'Lily and Jan'
export const getNames = () => names
export const getFirstChar = () => {
return names.charAt(0)
}

/**
* Returns the names
*/
export function getNamesTyped<TNames extends string>(): TNames {
return names as TNames
}
3 changes: 3 additions & 0 deletions examples/react/example5/App.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export function Users() {
return <div className="test" />
}
Loading
Loading