Add vite's tests to parcel's and next's

This commit is contained in:
Aria Minaei 2023-07-29 22:52:19 +02:00 committed by Aria
parent c288ab9ffe
commit 29905d951f
58 changed files with 852 additions and 318 deletions

View file

@ -0,0 +1,69 @@
// @cspotcode/zx is zx in CommonJS
import {$, cd, path, ProcessPromise} from '@cspotcode/zx'
import {testServerAndPage} from '../../utils/testUtils'
$.verbose = false
const PATH_TO_PACKAGE = path.join(__dirname, `./package`)
describe(`next`, () => {
describe(`build`, () => {
test(`command runs without error`, async () => {
cd(PATH_TO_PACKAGE)
const {exitCode} = await $`npm run build`
// at this point, the build should have succeeded
expect(exitCode).toEqual(0)
})
describe(`next start`, () => {
testServerAndPage({
startServerOnPort: (port: number) => {
cd(PATH_TO_PACKAGE)
return $`npm run start -- --port ${port}`
},
waitTilServerIsReady: async (
process: ProcessPromise<unknown>,
port: number,
) => {
for await (const chunk of process.stdout) {
const chunkString = chunk.toString()
if (chunkString.includes(`started server`)) {
// next's server is running now
break
}
}
return {url: `http://localhost:${port}`}
},
})
})
})
// this test is not ready yet, so we'll skip it
describe(`$ next dev`, () => {
testServerAndPage({
startServerOnPort: (port: number) => {
cd(PATH_TO_PACKAGE)
return $`npm run dev -- --port ${port}`
},
waitTilServerIsReady: async (
process: ProcessPromise<unknown>,
port: number,
) => {
for await (const chunk of process.stdout) {
const chunkString = chunk.toString()
if (chunkString.includes(`compiled client and server successfully`)) {
// next's server is running now
break
}
}
return {url: `http://localhost:${port}`}
},
})
})
})

View file

@ -0,0 +1,5 @@
/// <reference types="next" />
/// <reference types="next/image-types/global" />
// NOTE: This file should not be edited
// see https://nextjs.org/docs/basic-features/typescript for more information.

View file

@ -0,0 +1,13 @@
import React from 'react'
import studio from '@theatre/studio'
import extension from '@theatre/r3f/dist/extension'
import App from '../src/App/App'
if (process.env.NODE_ENV === 'development' && typeof window !== 'undefined') {
studio.extend(extension)
studio.initialize({usePersistentStorage: false})
}
export default function Home() {
return <App></App>
}

View file

Before

Width:  |  Height:  |  Size: 15 KiB

After

Width:  |  Height:  |  Size: 15 KiB

View file

@ -1,5 +1,5 @@
import {getProject} from '@theatre/core'
import React from 'react'
import React, {useEffect} from 'react'
import {Canvas} from '@react-three/fiber'
import {editable as e, SheetProvider, PerspectiveCamera} from '@theatre/r3f'
import state from './state.json'
@ -16,6 +16,20 @@ function Plane({color, theatreKey, ...props}: any) {
}
export default function App() {
const [light2, setLight2] = React.useState<any>(null)
useEffect(() => {
if (!light2) return
// see the note on <e.pointLight theatreKey="Light 2" /> below to understand why we're doing this
const intensityInStateJson = 3
const currentIntensity = light2.intensity
if (currentIntensity !== intensityInStateJson) {
console.error(`Test failed: light2.intensity is ${currentIntensity}`)
} else {
console.log(`Test passed: light2.intensity is ${intensityInStateJson}`)
}
}, [light2])
return (
<Canvas
gl={{preserveDrawingBuffer: true}}
@ -27,6 +41,7 @@ export default function App() {
<SheetProvider
sheet={getProject('Playground - R3F', {state}).sheet('R3F-Canvas')}
>
{/* @ts-ignore */}
<PerspectiveCamera makeDefault theatreKey="Camera" />
<ambientLight intensity={0.4} />
<e.pointLight
@ -38,9 +53,12 @@ export default function App() {
<e.pointLight
position={[0, 0.5, -1]}
distance={1}
// the intensity is statically set to 2, but in the state.json file we'll set it to 3,
// and we'll use that as a test to make sure the state is being loaded correctly
intensity={2}
color="#e4be00"
theatreKey="Light 2"
ref={setLight2}
/>
<group position={[0, -0.9, -3]}>

View file

@ -0,0 +1,19 @@
{
"sheetsById": {
"R3F-Canvas": {
"staticOverrides": {
"byObject": {
"Light 2": {
"intensity": 3
}
}
}
}
},
"definitionVersion": "0.4.0",
"revisionHistory": [
"jVNB3VWU34BIQK7M",
"-NXkC2GceSVBoVqa",
"Bw7ng1kdcWmMO5DN"
]
}

View file

@ -0,0 +1,30 @@
{
"compilerOptions": {
"target": "es5",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true,
"skipLibCheck": true,
"strict": false,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"incremental": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve"
},
"include": [
"next-env.d.ts",
"**/*.ts",
"**/*.tsx"
],
"exclude": [
"node_modules"
]
}

View file

@ -1,24 +0,0 @@
{
"sheetsById": {
"R3F-Canvas": {
"staticOverrides": {
"byObject": {
"plane1": {
"position": {
"x": -0.06000000000000002
}
},
"plane2": {
"position": {
"x": 0,
"y": -1.1043953439330743,
"z": 6.322692591942688
}
}
}
}
}
},
"definitionVersion": "0.4.0",
"revisionHistory": ["lSnZ_QVusR3qNnVN"]
}

View file

@ -1,77 +0,0 @@
import {button, initialize, useControls} from 'theatric'
import {render} from 'react-dom'
import React, {useState} from 'react'
// initialize()
function SomeComponent({id}) {
const {foo, $get, $set} = useControls(
{
foo: 0,
bar: 0,
bez: button(() => {
$set((p) => p.foo, 2)
$set((p) => p.bar, 3)
console.log($get((p) => p.foo))
}),
},
{folder: id},
)
return (
<div>
{id}: {foo}
</div>
)
}
export default function App() {
const {bar, $set, $get} = useControls({
bar: {foo: 'bar'},
baz: button(() => console.log($get((p) => p.bar))),
})
const {another, panel, yo} = useControls(
{
another: '',
panel: '',
yo: 0,
},
{panel: 'My panel'},
)
const {} = useControls({})
const [showComponent, setShowComponent] = useState(false)
return (
<div
style={{
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
justifyContent: 'center',
}}
>
<div>{JSON.stringify(bar)}</div>
<SomeComponent id="first" />
<SomeComponent id="second" />
<button
onClick={() => {
setShowComponent(!showComponent)
}}
>
Show another component
</button>
<button
onClick={() => {
$set((p) => p.bar.foo, $get((p) => p.bar.foo) + 1)
}}
>
Increment stuff
</button>
{showComponent && <SomeComponent id="hidden" />}
{yo}
</div>
)
}

View file

@ -1,69 +0,0 @@
// @cspotcode/zx is zx in CommonJS
import {$, cd, path} from '@cspotcode/zx'
import {chromium, devices} from 'playwright'
$.verbose = true
const PATH_TO_PACKAGE = path.join(__dirname, `./package`)
describe(`next / production`, () => {
test(`\`$ next build\` should succeed and have a predictable output`, async () => {
cd(PATH_TO_PACKAGE)
const {exitCode, stdout} = await $`npm run build`
// at this point, the build should have succeeded
expect(exitCode).toEqual(0)
// now let's check the output to make sure it's what we expect
// all of stdout until the line that contains "Route (pages)". That's because what comes after that
// line is a list of all the pages that were built, and we don't want to snapshot that because it changes every time.
const stdoutUntilRoutePages = stdout.split(`Route (pages)`)[0]
// This test will fail if `next build` outputs anything unexpected.
// I'm commenting this out because the output of `next build` is not predictable
// TOOD: figure out a different way to test this
// expect(stdoutUntilRoutePages).toMatchSnapshot()
})
// this test is not ready yet, so we'll skip it
describe.skip(`$ next start`, () => {
let browser, page
beforeAll(async () => {
browser = await chromium.launch()
})
afterAll(async () => {
await browser.close()
})
beforeEach(async () => {
page = await browser.newPage()
})
afterEach(async () => {
await page.close()
})
// just a random port I'm hoping is free everywhere.
const port = 30978
test('`$ next start` serves the app, and the app works', async () => {
// run the production server but don't wait for it to finish
cd(PATH_TO_PACKAGE)
const p = $`npm run start -- --port ${port}`
// await p
try {
page.on('console', (msg) => console.log('PAGE LOG:', msg.text()))
await page.goto(`http://localhost:${port}`)
// wait three seconds
await page.waitForTimeout(3000)
} finally {
p.kill()
}
try {
await p
} catch (e) {
if (e.signal !== 'SIGKILL' && e.signal !== 'SIGTERM') {
throw e
}
}
})
})
})

View file

@ -1,5 +1,4 @@
{
"name": "@compat/parcel1-react18",
"scripts": {
"dev": "parcel serve ./index.html"
},

View file

@ -1,92 +0,0 @@
import {getProject} from '@theatre/core'
import ReactDOM from 'react-dom/client'
import React from 'react'
import {Canvas} from '@react-three/fiber'
import studio from '@theatre/studio'
import {editable as e, SheetProvider} from '@theatre/r3f'
import extension from '@theatre/r3f/dist/extension'
if (process.env.NODE_ENV === 'development' && typeof window !== 'undefined') {
studio.extend(extension)
studio.initialize({usePersistentStorage: false})
}
// credit: https://codesandbox.io/s/camera-pan-nsb7f
function Plane({color, theatreKey, ...props}) {
return (
<e.mesh {...props} theatreKey={theatreKey}>
<boxBufferGeometry />
<meshStandardMaterial color={color} />
</e.mesh>
)
}
function App() {
return (
<Canvas
gl={{preserveDrawingBuffer: true}}
linear
frameloop="demand"
dpr={[1.5, 2]}
style={{position: 'absolute', top: 0, left: 0}}
>
<SheetProvider sheet={getProject('Playground - R3F').sheet('R3F-Canvas')}>
{/* @ts-ignore */}
<e.orthographicCamera makeDefault theatreKey="Camera" />
<ambientLight intensity={0.4} />
<e.pointLight
position={[-10, -10, 5]}
intensity={2}
color="#ff20f0"
theatreKey="Light 1"
/>
<e.pointLight
position={[0, 0.5, -1]}
distance={1}
intensity={2}
color="#e4be00"
theatreKey="Light 2"
/>
<group position={[0, -0.9, -3]}>
<Plane
color="hotpink"
rotation-x={-Math.PI / 2}
position-z={2}
scale={[4, 20, 0.2]}
theatreKey="plane1"
/>
<Plane
color="#e4be00"
rotation-x={-Math.PI / 2}
position-y={1}
scale={[4.2, 0.2, 4]}
theatreKey="plane2"
/>
<Plane
color="#736fbd"
rotation-x={-Math.PI / 2}
position={[-1.7, 1, 3.5]}
scale={[0.5, 4, 4]}
theatreKey="plane3"
/>
<Plane
color="white"
rotation-x={-Math.PI / 2}
position={[0, 4.5, 3]}
scale={[2, 0.03, 4]}
theatreKey="plane4"
/>
</group>
</SheetProvider>
</Canvas>
)
}
const project = getProject('Project')
const sheet = project.sheet('Sheet')
const obj = sheet.object('Obj', {str: 'some string', num: 0})
const container = document.getElementById('root')
const root = ReactDOM.createRoot(container)
root.render(<App obj={obj}>hi</App>)

View file

@ -1,5 +1,4 @@
{
"name": "@compat/parcel1-react17",
"scripts": {
"dev": "parcel serve ./index.html"
},

View file

@ -1,7 +1,8 @@
{
"name": "@compat/parcel2-react18",
"scripts": {
"dev": "parcel serve ./index.html"
"dev": "parcel serve ./index.html",
"build": "parcel build ./index.html",
"start": "serve dist"
},
"dependencies": {
"@theatre/core": "0.0.1-COMPAT.1",
@ -9,6 +10,7 @@
"@theatre/studio": "0.0.1-COMPAT.1",
"parcel": "^2.5.0",
"react": "^18.1.0",
"react-dom": "^18.1.0"
"react-dom": "^18.1.0",
"serve": "14.2.0"
}
}

View file

@ -1,23 +1,12 @@
import {getProject} from '@theatre/core'
import React from 'react'
import React, {useEffect} from 'react'
import {Canvas} from '@react-three/fiber'
import studio from '@theatre/studio'
import {editable as e, SheetProvider} from '@theatre/r3f'
import extension from '@theatre/r3f/dist/extension'
import playgroundState from './playgroundState.json'
if (process.env.NODE_ENV === 'development' && typeof window !== 'undefined') {
studio.extend(extension)
studio.initialize({usePersistentStorage: false})
}
const sheet = getProject('Playground - R3F', {state: playgroundState}).sheet(
'R3F-Canvas',
)
import {editable as e, SheetProvider, PerspectiveCamera} from '@theatre/r3f'
import state from './state.json'
// credit: https://codesandbox.io/s/camera-pan-nsb7f
function Plane({color, theatreKey, ...props}) {
function Plane({color, theatreKey, ...props}: any) {
return (
<e.mesh {...props} theatreKey={theatreKey}>
<boxBufferGeometry />
@ -26,7 +15,21 @@ function Plane({color, theatreKey, ...props}) {
)
}
function App() {
export default function App() {
const [light2, setLight2] = React.useState<any>(null)
useEffect(() => {
if (!light2) return
// see the note on <e.pointLight theatreKey="Light 2" /> below to understand why we're doing this
const intensityInStateJson = 3
const currentIntensity = light2.intensity
if (currentIntensity !== intensityInStateJson) {
console.error(`Test failed: light2.intensity is ${currentIntensity}`)
} else {
console.log(`Test passed: light2.intensity is ${intensityInStateJson}`)
}
}, [light2])
return (
<Canvas
gl={{preserveDrawingBuffer: true}}
@ -35,9 +38,11 @@ function App() {
dpr={[1.5, 2]}
style={{position: 'absolute', top: 0, left: 0}}
>
<SheetProvider sheet={sheet}>
<SheetProvider
sheet={getProject('Playground - R3F', {state}).sheet('R3F-Canvas')}
>
{/* @ts-ignore */}
<e.orthographicCamera makeDefault theatreKey="Camera" />
<PerspectiveCamera makeDefault theatreKey="Camera" />
<ambientLight intensity={0.4} />
<e.pointLight
position={[-10, -10, 5]}
@ -48,10 +53,14 @@ function App() {
<e.pointLight
position={[0, 0.5, -1]}
distance={1}
// the intensity is statically set to 2, but in the state.json file we'll set it to 3,
// and we'll use that as a test to make sure the state is being loaded correctly
intensity={2}
color="#e4be00"
theatreKey="Light 2"
ref={setLight2}
/>
<group position={[0, -0.9, -3]}>
<Plane
color="hotpink"
@ -86,7 +95,3 @@ function App() {
</Canvas>
)
}
export default function Home() {
return <App></App>
}

View file

@ -0,0 +1,19 @@
{
"sheetsById": {
"R3F-Canvas": {
"staticOverrides": {
"byObject": {
"Light 2": {
"intensity": 3
}
}
}
}
},
"definitionVersion": "0.4.0",
"revisionHistory": [
"jVNB3VWU34BIQK7M",
"-NXkC2GceSVBoVqa",
"Bw7ng1kdcWmMO5DN"
]
}

View file

@ -0,0 +1,13 @@
import ReactDOM from 'react-dom/client'
import studio from '@theatre/studio'
import extension from '@theatre/r3f/dist/extension'
import App from './App/App'
if (process.env.NODE_ENV === 'development' && typeof window !== 'undefined') {
studio.extend(extension)
studio.initialize({usePersistentStorage: false})
}
const container = document.getElementById('root')
const root = ReactDOM.createRoot(container)
root.render(<App />)

View file

@ -0,0 +1,47 @@
// @cspotcode/zx is zx in CommonJS
import {$, cd, path, ProcessPromise} from '@cspotcode/zx'
import {defer, testServerAndPage} from '../../utils/testUtils'
$.verbose = false
const PATH_TO_PACKAGE = path.join(__dirname, `./package`)
describe(`react18`, () => {
test(`build succeeds`, async () => {
cd(PATH_TO_PACKAGE)
const {exitCode} = await $`npm run build`
// at this point, the build should have succeeded
expect(exitCode).toEqual(0)
})
// this one is failing for some reason, but manually running the server works fine
describe(`build`, () => {
function startServerOnPort(port: number): ProcessPromise<unknown> {
cd(PATH_TO_PACKAGE)
return $`npm start -- -p ${port}`
}
function waitTilServerIsReady(
process: ProcessPromise<unknown>,
port: number,
): Promise<{
url: string
}> {
const d = defer<{url: string}>()
const url = `http://localhost:${port}`
process.stdout.on('data', (chunk) => {
if (chunk.toString().includes('Accepting connections')) {
// server is running now
d.resolve({url})
}
})
return d.promise
}
testServerAndPage({startServerOnPort, waitTilServerIsReady})
})
})

View file

@ -1,26 +0,0 @@
{
"sheetsById": {
"R3F-Canvas": {
"staticOverrides": {
"byObject": {
"Camera": {
"position": {
"x": -1.9718646329873923,
"y": 0,
"z": 5.6728262108991725
}
},
"plane3": {
"rotation": {
"x": -1.5707963267948966,
"y": -1.6653345369377348e-16,
"z": -0.9115259508891379
}
}
}
}
}
},
"definitionVersion": "0.4.0",
"revisionHistory": ["-NXkC2GceSVBoVqa", "Bw7ng1kdcWmMO5DN"]
}

View file

@ -1,5 +1,4 @@
{
"name": "@compat/vite-react18",
"private": true,
"version": "0.0.0",
"scripts": {

View file

@ -0,0 +1,97 @@
import {getProject} from '@theatre/core'
import React, {useEffect} from 'react'
import {Canvas} from '@react-three/fiber'
import {editable as e, SheetProvider, PerspectiveCamera} from '@theatre/r3f'
import state from './state.json'
// credit: https://codesandbox.io/s/camera-pan-nsb7f
function Plane({color, theatreKey, ...props}: any) {
return (
<e.mesh {...props} theatreKey={theatreKey}>
<boxBufferGeometry />
<meshStandardMaterial color={color} />
</e.mesh>
)
}
export default function App() {
const [light2, setLight2] = React.useState<any>(null)
useEffect(() => {
if (!light2) return
// see the note on <e.pointLight theatreKey="Light 2" /> below to understand why we're doing this
const intensityInStateJson = 3
const currentIntensity = light2.intensity
if (currentIntensity !== intensityInStateJson) {
console.error(`Test failed: light2.intensity is ${currentIntensity}`)
} else {
console.log(`Test passed: light2.intensity is ${intensityInStateJson}`)
}
}, [light2])
return (
<Canvas
gl={{preserveDrawingBuffer: true}}
linear
frameloop="demand"
dpr={[1.5, 2]}
style={{position: 'absolute', top: 0, left: 0}}
>
<SheetProvider
sheet={getProject('Playground - R3F', {state}).sheet('R3F-Canvas')}
>
{/* @ts-ignore */}
<PerspectiveCamera makeDefault theatreKey="Camera" />
<ambientLight intensity={0.4} />
<e.pointLight
position={[-10, -10, 5]}
intensity={2}
color="#ff20f0"
theatreKey="Light 1"
/>
<e.pointLight
position={[0, 0.5, -1]}
distance={1}
// the intensity is statically set to 2, but in the state.json file we'll set it to 3,
// and we'll use that as a test to make sure the state is being loaded correctly
intensity={2}
color="#e4be00"
theatreKey="Light 2"
ref={setLight2}
/>
<group position={[0, -0.9, -3]}>
<Plane
color="hotpink"
rotation-x={-Math.PI / 2}
position-z={2}
scale={[4, 20, 0.2]}
theatreKey="plane1"
/>
<Plane
color="#e4be00"
rotation-x={-Math.PI / 2}
position-y={1}
scale={[4.2, 0.2, 4]}
theatreKey="plane2"
/>
<Plane
color="#736fbd"
rotation-x={-Math.PI / 2}
position={[-1.7, 1, 3.5]}
scale={[0.5, 4, 4]}
theatreKey="plane3"
/>
<Plane
color="white"
rotation-x={-Math.PI / 2}
position={[0, 4.5, 3]}
scale={[2, 0.03, 4]}
theatreKey="plane4"
/>
</group>
</SheetProvider>
</Canvas>
)
}

View file

@ -0,0 +1,19 @@
{
"sheetsById": {
"R3F-Canvas": {
"staticOverrides": {
"byObject": {
"Light 2": {
"intensity": 3
}
}
}
}
},
"definitionVersion": "0.4.0",
"revisionHistory": [
"jVNB3VWU34BIQK7M",
"-NXkC2GceSVBoVqa",
"Bw7ng1kdcWmMO5DN"
]
}

View file

@ -1,7 +1,7 @@
import ReactDOM from 'react-dom/client'
import studio from '@theatre/studio'
import extension from '@theatre/r3f/dist/extension'
import App from './App'
import App from './App/App'
if (process.env.NODE_ENV === 'development' && typeof window !== 'undefined') {
studio.extend(extension)

View file

@ -0,0 +1,42 @@
// @cspotcode/zx is zx in CommonJS
import {$, cd, path, ProcessPromise} from '@cspotcode/zx'
import {testServerAndPage} from '../../utils/testUtils'
$.verbose = false
const PATH_TO_PACKAGE = path.join(__dirname, `./package`)
describe(`vite2`, () => {
test(`\`$ vite build\` should succeed`, async () => {
cd(PATH_TO_PACKAGE)
const {exitCode} = await $`npm run build`
// at this point, the build should have succeeded
expect(exitCode).toEqual(0)
})
describe(`vite preview`, () => {
function startServerOnPort(port: number): ProcessPromise<unknown> {
cd(PATH_TO_PACKAGE)
return $`npm run preview -- --port ${port}`
}
async function waitTilServerIsReady(
process: ProcessPromise<unknown>,
port: number,
): Promise<{
url: string
}> {
for await (const chunk of process.stdout) {
if (chunk.toString().includes('--host')) {
// vite's server is running now
break
}
}
return {url: `http://localhost:${port}`}
}
testServerAndPage({startServerOnPort, waitTilServerIsReady})
})
})

View file

@ -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?

View file

@ -0,0 +1,12 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vite App</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>

View file

@ -0,0 +1,26 @@
{
"private": true,
"version": "0.0.0",
"scripts": {
"dev": "vite",
"build": "tsc && vite build",
"preview": "vite preview"
},
"dependencies": {
"@react-three/drei": "^9.11.3",
"@react-three/fiber": "^8.0.19",
"@theatre/core": "0.0.1-COMPAT.1",
"@theatre/r3f": "0.0.1-COMPAT.1",
"@theatre/studio": "0.0.1-COMPAT.1",
"react": "^18.0.0",
"react-dom": "^18.0.0",
"three": "^0.141.0"
},
"devDependencies": {
"@types/react": "^18.0.0",
"@types/react-dom": "^18.0.0",
"@vitejs/plugin-react": "^1.3.0",
"typescript": "^4.6.3",
"vite": "^4.4.7"
}
}

View file

@ -0,0 +1,97 @@
import {getProject} from '@theatre/core'
import React, {useEffect} from 'react'
import {Canvas} from '@react-three/fiber'
import {editable as e, SheetProvider, PerspectiveCamera} from '@theatre/r3f'
import state from './state.json'
// credit: https://codesandbox.io/s/camera-pan-nsb7f
function Plane({color, theatreKey, ...props}: any) {
return (
<e.mesh {...props} theatreKey={theatreKey}>
<boxBufferGeometry />
<meshStandardMaterial color={color} />
</e.mesh>
)
}
export default function App() {
const [light2, setLight2] = React.useState<any>(null)
useEffect(() => {
if (!light2) return
// see the note on <e.pointLight theatreKey="Light 2" /> below to understand why we're doing this
const intensityInStateJson = 3
const currentIntensity = light2.intensity
if (currentIntensity !== intensityInStateJson) {
console.error(`Test failed: light2.intensity is ${currentIntensity}`)
} else {
console.log(`Test passed: light2.intensity is ${intensityInStateJson}`)
}
}, [light2])
return (
<Canvas
gl={{preserveDrawingBuffer: true}}
linear
frameloop="demand"
dpr={[1.5, 2]}
style={{position: 'absolute', top: 0, left: 0}}
>
<SheetProvider
sheet={getProject('Playground - R3F', {state}).sheet('R3F-Canvas')}
>
{/* @ts-ignore */}
<PerspectiveCamera makeDefault theatreKey="Camera" />
<ambientLight intensity={0.4} />
<e.pointLight
position={[-10, -10, 5]}
intensity={2}
color="#ff20f0"
theatreKey="Light 1"
/>
<e.pointLight
position={[0, 0.5, -1]}
distance={1}
// the intensity is statically set to 2, but in the state.json file we'll set it to 3,
// and we'll use that as a test to make sure the state is being loaded correctly
intensity={2}
color="#e4be00"
theatreKey="Light 2"
ref={setLight2}
/>
<group position={[0, -0.9, -3]}>
<Plane
color="hotpink"
rotation-x={-Math.PI / 2}
position-z={2}
scale={[4, 20, 0.2]}
theatreKey="plane1"
/>
<Plane
color="#e4be00"
rotation-x={-Math.PI / 2}
position-y={1}
scale={[4.2, 0.2, 4]}
theatreKey="plane2"
/>
<Plane
color="#736fbd"
rotation-x={-Math.PI / 2}
position={[-1.7, 1, 3.5]}
scale={[0.5, 4, 4]}
theatreKey="plane3"
/>
<Plane
color="white"
rotation-x={-Math.PI / 2}
position={[0, 4.5, 3]}
scale={[2, 0.03, 4]}
theatreKey="plane4"
/>
</group>
</SheetProvider>
</Canvas>
)
}

View file

@ -0,0 +1,19 @@
{
"sheetsById": {
"R3F-Canvas": {
"staticOverrides": {
"byObject": {
"Light 2": {
"intensity": 3
}
}
}
}
},
"definitionVersion": "0.4.0",
"revisionHistory": [
"jVNB3VWU34BIQK7M",
"-NXkC2GceSVBoVqa",
"Bw7ng1kdcWmMO5DN"
]
}

View file

@ -0,0 +1,13 @@
import ReactDOM from 'react-dom/client'
import studio from '@theatre/studio'
import extension from '@theatre/r3f/dist/extension'
import App from './App/App'
if (process.env.NODE_ENV === 'development' && typeof window !== 'undefined') {
studio.extend(extension)
studio.initialize({usePersistentStorage: false})
}
const container = document.getElementById('root')!
const root = ReactDOM.createRoot(container)
root.render(<App />)

View file

@ -0,0 +1 @@
/// <reference types="vite/client" />

View file

@ -0,0 +1,21 @@
{
"compilerOptions": {
"target": "ESNext",
"useDefineForClassFields": true,
"lib": ["DOM", "DOM.Iterable", "ESNext"],
"allowJs": false,
"skipLibCheck": true,
"esModuleInterop": false,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"module": "ESNext",
"moduleResolution": "Node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx"
},
"include": ["src"],
"references": [{ "path": "./tsconfig.node.json" }]
}

View file

@ -0,0 +1,8 @@
{
"compilerOptions": {
"composite": true,
"module": "esnext",
"moduleResolution": "node"
},
"include": ["vite.config.ts"]
}

View file

@ -0,0 +1,7 @@
import {defineConfig} from 'vite'
import react from '@vitejs/plugin-react'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [react()],
})

View file

@ -0,0 +1,42 @@
// @cspotcode/zx is zx in CommonJS
import {$, cd, path, ProcessPromise} from '@cspotcode/zx'
import {testServerAndPage} from '../../utils/testUtils'
$.verbose = false
const PATH_TO_PACKAGE = path.join(__dirname, `./package`)
describe(`vite4`, () => {
test(`\`$ vite build\` should succeed`, async () => {
cd(PATH_TO_PACKAGE)
const {exitCode} = await $`npm run build`
// at this point, the build should have succeeded
expect(exitCode).toEqual(0)
})
describe(`vite preview`, () => {
function startServerOnPort(port: number): ProcessPromise<unknown> {
cd(PATH_TO_PACKAGE)
return $`npm run preview -- --port ${port}`
}
async function waitTilServerIsReady(
process: ProcessPromise<unknown>,
port: number,
): Promise<{
url: string
}> {
for await (const chunk of process.stdout) {
if (chunk.toString().includes('--host')) {
// vite's server is running now
break
}
}
return {url: `http://localhost:${port}`}
}
testServerAndPage({startServerOnPort, waitTilServerIsReady})
})
})

View file

@ -0,0 +1,157 @@
import {Browser, chromium, ConsoleMessage, devices, Page} from 'playwright'
import {ProcessPromise} from '@cspotcode/zx'
export function testServerAndPage({
startServerOnPort,
waitTilServerIsReady,
}: {
startServerOnPort: (port: number) => ProcessPromise<unknown>
waitTilServerIsReady: (
process: ProcessPromise<unknown>,
port: number,
) => Promise<{url: string}>
}) {
let browser: Browser, page: Page
beforeAll(async () => {
browser = await chromium.launch()
})
afterAll(async () => {
await browser.close()
})
beforeEach(async () => {
page = await browser.newPage()
})
afterEach(async () => {
await page.close()
})
test('The server runs, and the r3f setup works', async () => {
// run the production server but don't wait for it to finish
// just a random port I'm hoping is free everywhere.
const port = await findOpenPort()
let process: ProcessPromise<unknown> | undefined
try {
process = startServerOnPort(port)
} catch (err) {
throw new Error(`Failed to start server: ${err}`)
}
try {
const {url} = await waitTilServerIsReady(process, port)
await testTheatreOnPage(page, {url})
} finally {
// kill the server
await process.kill('SIGTERM')
}
try {
await process
} catch (e) {
if (e.signal !== 'SIGTERM') {
console.log('process exited with error', e)
// if it exited for any reason other than us killing it, re-throw the error
throw e
}
// otherwise, process exited because we killed it, which is what we wanted
}
})
}
async function testTheatreOnPage(page: Page, {url}: {url: string}) {
const d = defer<string>()
const processConsoleEvents = (msg: ConsoleMessage) => {
const text = msg.text()
if (text.startsWith('Test passed: light2.intensity')) {
d.resolve('Passed')
} else if (text.startsWith('Test failed: light2.intensity')) {
d.reject(text)
}
}
page.on('console', processConsoleEvents)
try {
await page.goto(url, {
waitUntil: 'domcontentloaded',
timeout: 3000,
})
// give the console listener 3 seconds to resolve, otherwise fail the test
await Promise.race([
d.promise,
new Promise((_, reject) => setTimeout(() => reject('Timed out'), 30000)),
])
} finally {
page.off('console', processConsoleEvents)
}
}
export function findOpenPort(): Promise<number> {
return new Promise<number>((resolve, reject) => {
const server = require('net').createServer()
server.unref()
server.on('error', reject)
server.listen(0, () => {
const {port} = server.address() as {port: number}
server.close(() => {
resolve(port)
})
})
})
}
interface Deferred<PromiseType> {
resolve: (d: PromiseType) => void
reject: (d: unknown) => void
promise: Promise<PromiseType>
status: 'pending' | 'resolved' | 'rejected'
}
/**
* A simple imperative API for resolving/rejecting a promise.
*
* Example:
* ```ts
* function doSomethingAsync() {
* const deferred = defer()
*
* setTimeout(() => {
* if (Math.random() > 0.5) {
* deferred.resolve('success')
* } else {
* deferred.reject('Something went wrong')
* }
* }, 1000)
*
* // we're just returning the promise, so that the caller cannot resolve/reject it
* return deferred.promise
* }
*
* ```
*/
export function defer<PromiseType>(): Deferred<PromiseType> {
let resolve: (d: PromiseType) => void
let reject: (d: unknown) => void
const promise = new Promise<PromiseType>((rs, rj) => {
resolve = (v) => {
rs(v)
deferred.status = 'resolved'
}
reject = (v) => {
rj(v)
deferred.status = 'rejected'
}
})
const deferred: Deferred<PromiseType> = {
resolve: resolve!,
reject: reject!,
promise,
status: 'pending',
}
return deferred
}