Merge branch 'main' of github.com:theatre-js/theatre into theirmain

This commit is contained in:
jrkb 2023-09-07 11:08:47 +02:00
commit 085910d352
307 changed files with 12187 additions and 6628 deletions

View file

@ -23,11 +23,19 @@
*/
module.exports = {
root: true,
plugins: ['unused-imports', 'eslint-plugin-tsdoc'],
plugins: ['unused-imports', 'eslint-plugin-tsdoc', 'import', 'react'],
settings: {
react: {
version: '18.2',
},
},
extends: [],
rules: {
'unused-imports/no-unused-imports': 'warn',
'tsdoc/syntax': 'warn',
'no-debugger': 'error',
'react/no-deprecated': 'error',
'no-restricted-imports': [
'error',
{
@ -40,7 +48,7 @@ module.exports = {
},
],
},
ignorePatterns: ['*.d.ts', '*.ignore.ts', 'compatibility-tests/*'],
ignorePatterns: ['*.d.ts', '*.ignore.ts', 'compat-tests/*'],
overrides: [
{
files: ['*.ts', '*.tsx'],
@ -53,6 +61,7 @@ module.exports = {
'./packages/*/devEnv/tsconfig.json',
'./examples/*/tsconfig.json',
'./devEnv/tsconfig.json',
'./compat-tests/tsconfig.json',
],
},
rules: {
@ -66,6 +75,7 @@ module.exports = {
},
],
'@typescript-eslint/no-unused-vars': 'off',
'@typescript-eslint/no-floating-promises': 'warn',
},
},
{
@ -85,5 +95,18 @@ module.exports = {
},
},
},
{
files: [
`packages/*/**/*.ts`,
`packages/*/**/*.tsx`,
`packages/*/**/*.js`,
],
rules: {
'import/no-extraneous-dependencies': [
'error',
// {optionalDependencies: false, peerDependencies: false},
],
},
},
],
}

View file

@ -52,3 +52,7 @@ runs:
if: steps.cache-playwright-browsers.outputs.cache-hit != 'true'
shell: bash
run: yarn workspace playground run playwright install --with-deps
# - name: Update browserlist
# shell: bash
# run: npx browserslist@latest --update-db

View file

@ -12,7 +12,7 @@ jobs:
strategy:
matrix:
node-version: [16.x]
node-version: [18.x]
steps:
- uses: actions/checkout@v3
@ -22,13 +22,13 @@ jobs:
node-version: ${{ matrix.node-version }}
- uses: ./.github/actions/yarn-nm-install
- run: yarn build
- run: yarn cli build
Lint:
runs-on: ubuntu-latest
strategy:
matrix:
node-version: [16.x]
node-version: [18.x]
steps:
- uses: actions/checkout@v3
@ -38,14 +38,16 @@ jobs:
node-version: ${{ matrix.node-version }}
- uses: ./.github/actions/yarn-nm-install
- run: yarn lint:all --max-warnings 0
- run: |
export NODE_OPTIONS="--max_old_space_size=4096"
yarn lint:all --max-warnings 0
Test:
runs-on: ubuntu-latest
strategy:
matrix:
node-version: [16.x]
node-version: [18.x]
steps:
- uses: actions/checkout@v3
@ -61,7 +63,7 @@ jobs:
strategy:
matrix:
node-version: [16.x]
node-version: [18.x]
steps:
- uses: actions/checkout@v3
@ -78,7 +80,7 @@ jobs:
strategy:
matrix:
node-version: [16.x]
node-version: [18.x]
steps:
- uses: actions/checkout@v3
@ -88,19 +90,15 @@ jobs:
node-version: ${{ matrix.node-version }}
- uses: ./.github/actions/yarn-nm-install
- name: Run e2e tests with percy
uses: percy/exec-action@v0.3.1
with:
custom-command: 'yarn test:e2e:ci'
env:
PERCY_TOKEN: ${{ secrets.PERCY_TOKEN }}
- name: Run e2e tests
run: yarn test:e2e:ci
Compatibility-Tests:
runs-on: ubuntu-latest
strategy:
matrix:
node-version: [16.x]
node-version: [18.x]
steps:
- uses: actions/checkout@v3
@ -111,9 +109,7 @@ jobs:
- uses: ./.github/actions/yarn-nm-install
# re-enable the following line if we start to get EINTEGRITY errors again
# - run: npm cache clean || npm cache verify
# This will test whether `npm install`/`yarn install` can actually run on each compatibility test fixture. See `compatibility-tests/README.md` for more info.
- run:
yarn workspace @theatre/compatibility-tests run install-fixtures
--verbose
# This will test whether `npm install`/`yarn install` can actually run on each compatibility test fixture. See `compat-tests/README.md` for more info.
- run: yarn workspace @theatre/compat-tests run install-fixtures --verbose
# after that, we run the jest tests for each fixture
- run: yarn test:compat:run
- run: yarn test:compat:run --verbose

View file

@ -102,11 +102,11 @@ jobs:
- name: Use Node.js
uses: actions/setup-node@v3
with:
node-version: 16.x
node-version: 18.x
- uses: ./.github/actions/yarn-nm-install
- name: Build the Theatre.js packages
run: yarn build
run: yarn cli build
- name: Update .yarnrc.yml with the auth config for the npmPublishRegistry
run: cat .github/.yarnrc.publish.yml >> .yarnrc.yml
- name: Publish the Theatre.js packages

4
.gitignore vendored
View file

@ -23,5 +23,5 @@
# compatibility tests
.parcel-cache
/compatibility-tests/*/.yarn
/compatibility-tests/*/build
/compat-tests/*/.yarn
/compat-tests/*/build

View file

@ -1,4 +1,11 @@
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"
yarn lint-staged
yarn lint-staged
yarn workspace @theatre/dataverse run precommit
# if there are unstaged changes in ./packages/dataverse/docs, fail
if ! git diff --quiet --exit-code -- docs; then
echo "Please run 'yarn workspace @theatre/dataverse run doc' and commit the changes to the docs folder"
exit 1
fi

File diff suppressed because one or more lines are too long

874
.yarn/releases/yarn-3.6.3.cjs vendored Executable file

File diff suppressed because one or more lines are too long

View file

@ -1,7 +1,9 @@
nodeLinker: node-modules
plugins:
- path: .yarn/plugins/@yarnpkg/plugin-compat.cjs
spec: '@yarnpkg/plugin-compat'
- path: .yarn/plugins/@yarnpkg/plugin-interactive-tools.cjs
spec: '@yarnpkg/plugin-interactive-tools'
yarnPath: .yarn/releases/yarn-3.2.0.cjs
yarnPath: .yarn/releases/yarn-3.6.3.cjs

View file

@ -50,7 +50,7 @@ The quickest way to start tweaking things is to run the `playground` package.
```sh
$ cd ./packages/playground
$ yarn serve
$ yarn build
$ yarn cli build
# or, shortcut:
$ cd root
$ yarn playground
@ -73,7 +73,7 @@ examples.
You can do that by running the `build` command at the root of the repo:
```sh
$ yarn build
$ yarn cli build
```
Then build any of the examples:
@ -148,9 +148,9 @@ same version number. In order to publish to npm, you can run the `release`
script from the root of the repo:
```sh
$ yarn release x.y.z # npm publish version x.y.z
$ yarn release x.y.z-dev.w # npm publish version x.y.z-dev.w and tag it as "dev"
$ yarn release x.y.z-rc.w # npm publish version x.y.z-rc.w and tag it as "rc"
$ yarn cli release x.y.z # npm publish version x.y.z
$ yarn cli release x.y.z-dev.w # npm publish version x.y.z-dev.w and tag it as "dev"
$ yarn cli release x.y.z-rc.w # npm publish version x.y.z-rc.w and tag it as "rc"
```
@ -203,7 +203,7 @@ $ yarn lint:all
$ yarn lint:all --fix
# Build all the packages
$ yarn build
$ yarn cli build
```

View file

@ -1,24 +0,0 @@
module.exports = function (api) {
const env = api.env()
const config = {
presets: [['@babel/preset-react'], ['@babel/preset-typescript']],
babelrcRoots: ['.', './packages/*', './theatre/*', './examples/*'],
}
if (env === 'test') {
config.presets.unshift(['@babel/preset-env', {targets: {node: 'current'}}])
} else {
if (env === 'development' || env === 'production') {
config.plugins.unshift(
['@babel/plugin-proposal-class-properties', {loose: true}],
['@babel/plugin-proposal-optional-chaining'],
['@babel/plugin-proposal-nullish-coalescing-operator'],
['@babel/plugin-proposal-logical-assignment-operators'],
)
} else {
throw Error(`Babel env ` + env + ' is not yet configured.')
}
}
return config
}

View file

@ -8,6 +8,6 @@
</head>
<body>
<div id="root"></div>
<script src="./src/index.js"></script>
<script src="./src/index.tsx"></script>
</body>
</html>

View file

@ -0,0 +1,17 @@
{
"scripts": {
"dev": "parcel serve ./index.html",
"build": "NODE_ENV=production parcel build ./index.html --no-minify",
"start": "serve dist"
},
"dependencies": {
"@theatre/core": "0.0.1-COMPAT.1",
"@theatre/studio": "0.0.1-COMPAT.1",
"parcel-bundler": "^1.12.5",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"@types/react": "^17.0.0",
"@types/react-dom": "^17.0.0",
"serve": "14.2.0"
}
}

View file

@ -0,0 +1,135 @@
import type {IScrub} from '@theatre/studio'
import studio from '@theatre/studio'
import React, {useLayoutEffect, useMemo, useState} from 'react'
import type {ISheet, ISheetObject, IProject} from '@theatre/core'
import type {UseDragOpts} from './useDrag'
import useDrag from './useDrag'
studio.initialize()
const boxObjectConfig = {
x: 0,
y: 0,
}
const Box: React.FC<{
id: string
sheet: ISheet
selectedObject: ISheetObject<any> | undefined
}> = ({id, sheet, selectedObject}) => {
// This is cheap to call and always returns the same value, so no need for useMemo()
const obj = sheet.object(id, boxObjectConfig)
const isSelected = selectedObject === obj
const [pos, setPos] = useState<{x: number; y: number}>({x: 0, y: 0})
useLayoutEffect(() => {
const unsubscribeFromChanges = obj.onValuesChange((newValues) => {
setPos(newValues)
})
return unsubscribeFromChanges
}, [id])
const [divRef, setDivRef] = useState<HTMLElement | null>(null)
const dragOpts = useMemo((): UseDragOpts => {
let scrub: IScrub | undefined
let initial: typeof obj.value
let firstOnDragCalled = false
return {
onDragStart() {
scrub = studio.scrub()
initial = obj.value
firstOnDragCalled = false
},
onDrag(x, y) {
if (!firstOnDragCalled) {
studio.setSelection([obj])
firstOnDragCalled = true
}
scrub!.capture(({set}) => {
set(obj.props, {x: x + initial.x, y: y + initial.y})
})
},
onDragEnd(dragHappened) {
if (dragHappened) {
scrub!.commit()
} else {
scrub!.discard()
}
},
lockCursorTo: 'move',
}
}, [])
useDrag(divRef, dragOpts)
return (
<div
onClick={() => {
studio.setSelection([obj])
}}
ref={setDivRef}
style={{
width: 100,
height: 100,
background: 'gray',
position: 'absolute',
left: pos.x + 'px',
top: pos.y + 'px',
boxSizing: 'border-box',
border: isSelected ? '1px solid #5a92fa' : '1px solid transparent',
}}
></div>
)
}
let lastBoxId = 1
export const Scene: React.FC<{project: IProject}> = ({project}) => {
const [boxes, setBoxes] = useState<Array<string>>(['0', '1'])
// This is cheap to call and always returns the same value, so no need for useMemo()
const sheet = project.sheet('Scene', 'default')
const [selection, _setSelection] = useState<Array<ISheetObject>>([])
useLayoutEffect(() => {
return studio.onSelectionChange((newSelection) => {
_setSelection(
newSelection.filter(
(s): s is ISheetObject => s.type === 'Theatre_SheetObject_PublicAPI',
),
)
})
})
return (
<div
style={{
position: 'absolute',
left: 0,
right: 0,
top: 0,
bottom: 0,
background: '#575757',
}}
>
<button
onClick={() => {
setBoxes((boxes) => [...boxes, String(++lastBoxId)])
}}
>
Add
</button>
{boxes.map((id) => (
<Box
key={'box' + id}
id={id}
sheet={sheet}
selectedObject={selection[0]}
/>
))}
</div>
)
}

View file

@ -0,0 +1,150 @@
import {useLayoutEffect, useRef} from 'react'
const noop = () => {}
function createCursorLock(cursor: string) {
const el = document.createElement('div')
el.style.cssText = `
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
z-index: 9999999;`
el.style.cursor = cursor
document.body.appendChild(el)
const relinquish = () => {
document.body.removeChild(el)
}
return relinquish
}
export type UseDragOpts = {
disabled?: boolean
dontBlockMouseDown?: boolean
lockCursorTo?: string
onDragStart?: (event: MouseEvent) => void | false
onDragEnd?: (dragHappened: boolean) => void
onDrag: (dx: number, dy: number, event: MouseEvent) => void
}
export default function useDrag(
target: HTMLElement | undefined | null,
opts: UseDragOpts,
) {
const optsRef = useRef<typeof opts>(opts)
optsRef.current = opts
const modeRef = useRef<'dragStartCalled' | 'dragging' | 'notDragging'>(
'notDragging',
)
const stateRef = useRef<{
dragHappened: boolean
startPos: {
x: number
y: number
}
}>({dragHappened: false, startPos: {x: 0, y: 0}})
useLayoutEffect(() => {
if (!target) return
const getDistances = (event: MouseEvent): [number, number] => {
const {startPos} = stateRef.current
return [event.screenX - startPos.x, event.screenY - startPos.y]
}
let relinquishCursorLock = noop
const dragHandler = (event: MouseEvent) => {
if (!stateRef.current.dragHappened && optsRef.current.lockCursorTo) {
relinquishCursorLock = createCursorLock(optsRef.current.lockCursorTo)
}
if (!stateRef.current.dragHappened) stateRef.current.dragHappened = true
modeRef.current = 'dragging'
const deltas = getDistances(event)
optsRef.current.onDrag(deltas[0], deltas[1], event)
}
const dragEndHandler = () => {
removeDragListeners()
modeRef.current = 'notDragging'
optsRef.current.onDragEnd &&
optsRef.current.onDragEnd(stateRef.current.dragHappened)
relinquishCursorLock()
relinquishCursorLock = noop
}
const addDragListeners = () => {
document.addEventListener('mousemove', dragHandler)
document.addEventListener('mouseup', dragEndHandler)
}
const removeDragListeners = () => {
document.removeEventListener('mousemove', dragHandler)
document.removeEventListener('mouseup', dragEndHandler)
}
const preventUnwantedClick = (event: MouseEvent) => {
if (optsRef.current.disabled) return
if (stateRef.current.dragHappened) {
if (
!optsRef.current.dontBlockMouseDown &&
modeRef.current !== 'notDragging'
) {
event.stopPropagation()
event.preventDefault()
}
stateRef.current.dragHappened = false
}
}
const dragStartHandler = (event: MouseEvent) => {
const opts = optsRef.current
if (opts.disabled === true) return
if (event.button !== 0) return
const resultOfStart = opts.onDragStart && opts.onDragStart(event)
if (resultOfStart === false) return
if (!opts.dontBlockMouseDown) {
event.stopPropagation()
event.preventDefault()
}
modeRef.current = 'dragStartCalled'
const {screenX, screenY} = event
stateRef.current.startPos = {x: screenX, y: screenY}
stateRef.current.dragHappened = false
addDragListeners()
}
const onMouseDown = (e: MouseEvent) => {
dragStartHandler(e)
}
target.addEventListener('mousedown', onMouseDown)
target.addEventListener('click', preventUnwantedClick)
return () => {
removeDragListeners()
target.removeEventListener('mousedown', onMouseDown)
target.removeEventListener('click', preventUnwantedClick)
relinquishCursorLock()
if (modeRef.current !== 'notDragging') {
optsRef.current.onDragEnd &&
optsRef.current.onDragEnd(modeRef.current === 'dragging')
}
modeRef.current = 'notDragging'
}
}, [target])
}

View file

@ -0,0 +1,12 @@
import React from 'react'
import ReactDOM from 'react-dom'
import studio from '@theatre/studio'
import {getProject} from '@theatre/core'
import {Scene} from './App/Scene'
studio.initialize()
ReactDOM.render(
<Scene project={getProject('Sample project')} />,
document.getElementById('root')!,
)

View file

@ -0,0 +1,5 @@
{
"compilerOptions": {
"jsx": "react"
}
}

View file

@ -0,0 +1,30 @@
// @cspotcode/zx is zx in CommonJS
import {$, cd, path, ProcessPromise} from '@cspotcode/zx'
import {defer, testServerAndPage} from '../../utils/testUtils'
const PATH_TO_PACKAGE = path.join(__dirname, `./package`)
describe(`react17`, () => {
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`, () => {
return
function startServerOnPort(port: number): ProcessPromise<unknown> {
cd(PATH_TO_PACKAGE)
return $`npm start -- -p ${port}`
}
testServerAndPage({
startServerOnPort,
checkServerStdoutToSeeIfItsReady: (chunk) =>
chunk.includes('Accepting connections'),
})
})
})

View file

@ -0,0 +1,42 @@
// @cspotcode/zx is zx in CommonJS
import {$, cd, path, ProcessPromise} from '@cspotcode/zx'
import {defer, testServerAndPage} from '../../utils/testUtils'
const PATH_TO_PACKAGE = path.join(__dirname, `./package`)
describe(`Create React App`, () => {
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)
})
describe(`build`, () => {
function startServerOnPort(port: number): ProcessPromise<unknown> {
cd(PATH_TO_PACKAGE)
return $`npm run serve -- -p ${port}`
}
testServerAndPage({
startServerOnPort,
checkServerStdoutToSeeIfItsReady: (chunk) =>
chunk.includes('Accepting connections'),
})
})
describe(`dev`, () => {
function startServerOnPort(port: number): ProcessPromise<unknown> {
cd(PATH_TO_PACKAGE)
return $`BROWSER=none PORT=${port} npm run start`
}
testServerAndPage({
startServerOnPort,
checkServerStdoutToSeeIfItsReady: (chunk) =>
chunk.includes('You can now view'),
})
})
})

View file

@ -6,18 +6,26 @@
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
"eject": "react-scripts eject",
"serve": "serve -s build"
},
"dependencies": {
"@react-three/drei": ">7.2.2",
"@react-three/drei": "^9.80.1",
"@react-three/fiber": "^8.13.6",
"three": "^0.155.0",
"@testing-library/jest-dom": "^5.11.4",
"@testing-library/react": "^11.1.0",
"@testing-library/user-event": "^12.1.10",
"@theatre/core": "0.0.1-COMPAT.1",
"@theatre/r3f": "0.0.1-COMPAT.1",
"@theatre/studio": "0.0.1-COMPAT.1",
"@types/jest": "^29.5.3",
"@types/node": "^20.4.5",
"@types/react": "^18.2.17",
"@types/react-dom": "^18.2.7",
"react-scripts": "^5.0.1",
"three": ">0.132.0",
"typescript": "^3.2.1",
"serve": "14.2.0",
"web-vitals": "^1.0.1"
},
"eslintConfig": {

View file

@ -1,28 +1,40 @@
import {getProject} from '@theatre/core'
import ReactDOM from 'react-dom/client'
import React from 'react'
import React, {useEffect, useRef} 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})
}
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 />
<boxGeometry />
<meshStandardMaterial color={color} />
</e.mesh>
)
}
function App() {
export default function App() {
const light2Ref = useRef<any>()
useEffect(() => {
const interval = setInterval(() => {
if (!light2Ref.current) return
clearInterval(interval)
const intensityInStateJson = 3
const currentIntensity = light2Ref.current.intensity
if (currentIntensity !== intensityInStateJson) {
console.error(`Test failed: light2.intensity is ${currentIntensity}`)
} else {
console.log(`Test passed: light2.intensity is ${intensityInStateJson}`)
}
}, 50)
// see the note on <e.pointLight theatreKey="Light 2" /> below to understand why we're doing this
}, [])
return (
<Canvas
gl={{preserveDrawingBuffer: true}}
@ -31,9 +43,11 @@ function App() {
dpr={[1.5, 2]}
style={{position: 'absolute', top: 0, left: 0}}
>
<SheetProvider sheet={getProject('Playground - R3F').sheet('R3F-Canvas')}>
<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]}
@ -44,10 +58,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={light2Ref}
/>
<group position={[0, -0.9, -3]}>
<Plane
color="hotpink"
@ -82,11 +100,3 @@ function App() {
</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

@ -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.tsx'
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,42 @@
// @cspotcode/zx is zx in CommonJS
import {$, cd, path, ProcessPromise} from '@cspotcode/zx'
import {testServerAndPage} from '../../utils/testUtils'
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}`
},
checkServerStdoutToSeeIfItsReady: (chunk) =>
chunk.includes('started server'),
})
})
})
// 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}`
},
checkServerStdoutToSeeIfItsReady: (chunk) =>
chunk.includes('compiled client and server successfully'),
})
})
})

View file

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

View file

@ -6,6 +6,9 @@
"start": "next start"
},
"dependencies": {
"@react-three/drei": "^9.80.1",
"@react-three/fiber": "^8.13.6",
"three": "^0.155.0",
"@theatre/core": "0.0.1-COMPAT.1",
"@theatre/r3f": "0.0.1-COMPAT.1",
"@theatre/studio": "0.0.1-COMPAT.1",

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,32 +1,40 @@
import {getProject} from '@theatre/core'
import React from 'react'
import React, {useEffect, useRef} 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 />
<boxGeometry />
<meshStandardMaterial color={color} />
</e.mesh>
)
}
function App() {
export default function App() {
const light2Ref = useRef<any>()
useEffect(() => {
const interval = setInterval(() => {
if (!light2Ref.current) return
clearInterval(interval)
const intensityInStateJson = 3
const currentIntensity = light2Ref.current.intensity
if (currentIntensity !== intensityInStateJson) {
console.error(`Test failed: light2.intensity is ${currentIntensity}`)
} else {
console.log(`Test passed: light2.intensity is ${intensityInStateJson}`)
}
}, 50)
// see the note on <e.pointLight theatreKey="Light 2" /> below to understand why we're doing this
}, [])
return (
<Canvas
gl={{preserveDrawingBuffer: true}}
@ -35,9 +43,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 +58,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={light2Ref}
/>
<group position={[0, -0.9, -3]}>
<Plane
color="hotpink"
@ -86,7 +100,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,37 @@
{
"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",
"plugins": [
{
"name": "next"
}
],
"strictNullChecks": true
},
"include": [
"next-env.d.ts",
"**/*.ts",
"**/*.tsx",
".next/types/**/*.ts"
],
"exclude": [
"node_modules"
]
}

View file

@ -8,6 +8,6 @@
</head>
<body>
<div id="root"></div>
<script src="./src/index.js"></script>
<script src="./src/index.tsx"></script>
</body>
</html>

View file

@ -0,0 +1,19 @@
{
"scripts": {
"dev": "parcel serve ./index.html",
"build": "NODE_ENV=production parcel build ./index.html --no-minify",
"start": "serve dist"
},
"dependencies": {
"@react-three/drei": "^9.80.1",
"@react-three/fiber": "^8.13.6",
"three": "^0.155.0",
"@theatre/core": "0.0.1-COMPAT.1",
"@theatre/r3f": "0.0.1-COMPAT.1",
"@theatre/studio": "0.0.1-COMPAT.1",
"parcel-bundler": "^1.12.5",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"serve": "14.2.0"
}
}

View file

@ -1,28 +1,40 @@
import {getProject} from '@theatre/core'
import ReactDOM from 'react-dom/client'
import React from 'react'
import React, {useEffect, useRef} 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})
}
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 />
<boxGeometry />
<meshStandardMaterial color={color} />
</e.mesh>
)
}
function App() {
export default function App() {
const light2Ref = useRef<any>()
useEffect(() => {
const interval = setInterval(() => {
if (!light2Ref.current) return
clearInterval(interval)
const intensityInStateJson = 3
const currentIntensity = light2Ref.current.intensity
if (currentIntensity !== intensityInStateJson) {
console.error(`Test failed: light2.intensity is ${currentIntensity}`)
} else {
console.log(`Test passed: light2.intensity is ${intensityInStateJson}`)
}
}, 50)
// see the note on <e.pointLight theatreKey="Light 2" /> below to understand why we're doing this
}, [])
return (
<Canvas
gl={{preserveDrawingBuffer: true}}
@ -31,9 +43,11 @@ function App() {
dpr={[1.5, 2]}
style={{position: 'absolute', top: 0, left: 0}}
>
<SheetProvider sheet={getProject('Playground - R3F').sheet('R3F-Canvas')}>
<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]}
@ -44,10 +58,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={light2Ref}
/>
<group position={[0, -0.9, -3]}>
<Plane
color="hotpink"
@ -82,11 +100,3 @@ function App() {
</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

@ -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,16 @@
import React from 'react'
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})
}
console.log('React', React)
const container = document.getElementById('root')
const root = ReactDOM.createRoot(container)
root.render(<App />)

View file

@ -0,0 +1,5 @@
{
"compilerOptions": {
"jsx": "react"
}
}

View file

@ -0,0 +1,42 @@
// @cspotcode/zx is zx in CommonJS
import {$, cd, path, ProcessPromise} from '@cspotcode/zx'
import {defer, testServerAndPage} from '../../utils/testUtils'
const PATH_TO_PACKAGE = path.join(__dirname, `./package`)
describe(`parcel1`, () => {
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)
})
describe(`build`, () => {
function startServerOnPort(port: number): ProcessPromise<unknown> {
cd(PATH_TO_PACKAGE)
return $`npm start -- -p ${port}`
}
testServerAndPage({
startServerOnPort,
checkServerStdoutToSeeIfItsReady: (chunk) =>
chunk.includes('Accepting connections'),
})
})
describe(`dev`, () => {
function startServerOnPort(port: number): ProcessPromise<unknown> {
cd(PATH_TO_PACKAGE)
return $`npm run dev -- -p ${port}`
}
testServerAndPage({
startServerOnPort,
checkServerStdoutToSeeIfItsReady: (chunk) =>
chunk.includes('Server running at'),
})
})
})

View file

@ -0,0 +1,19 @@
{
"scripts": {
"dev": "parcel serve ./index.html",
"build": "parcel build ./index.html",
"start": "serve dist"
},
"dependencies": {
"@react-three/drei": "^9.80.1",
"@react-three/fiber": "^8.13.6",
"three": "^0.155.0",
"@theatre/core": "0.0.1-COMPAT.1",
"@theatre/r3f": "0.0.1-COMPAT.1",
"@theatre/studio": "0.0.1-COMPAT.1",
"parcel": "^2.9.3",
"react": "^18.1.0",
"react-dom": "^18.1.0",
"serve": "14.2.0"
}
}

View file

@ -1,28 +1,40 @@
import {getProject} from '@theatre/core'
import ReactDOM from 'react-dom/client'
import React from 'react'
import React, {useEffect, useRef} 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})
}
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 />
<boxGeometry />
<meshStandardMaterial color={color} />
</e.mesh>
)
}
function App() {
export default function App() {
const light2Ref = useRef<any>()
useEffect(() => {
const interval = setInterval(() => {
if (!light2Ref.current) return
clearInterval(interval)
const intensityInStateJson = 3
const currentIntensity = light2Ref.current.intensity
if (currentIntensity !== intensityInStateJson) {
console.error(`Test failed: light2.intensity is ${currentIntensity}`)
} else {
console.log(`Test passed: light2.intensity is ${intensityInStateJson}`)
}
}, 50)
// see the note on <e.pointLight theatreKey="Light 2" /> below to understand why we're doing this
}, [])
return (
<Canvas
gl={{preserveDrawingBuffer: true}}
@ -31,9 +43,11 @@ function App() {
dpr={[1.5, 2]}
style={{position: 'absolute', top: 0, left: 0}}
>
<SheetProvider sheet={getProject('Playground - R3F').sheet('R3F-Canvas')}>
<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]}
@ -44,10 +58,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={light2Ref}
/>
<group position={[0, -0.9, -3]}>
<Plane
color="hotpink"
@ -82,11 +100,3 @@ function App() {
</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

@ -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,5 @@
{
"compilerOptions": {
"jsx": "react"
}
}

View file

@ -0,0 +1,63 @@
// @cspotcode/zx is zx in CommonJS
import {$, cd, path, ProcessPromise} from '@cspotcode/zx'
import {defer, testServerAndPage} from '../../utils/testUtils'
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.includes('Accepting connections')) {
// server is running now
d.resolve({url})
}
})
return d.promise
}
testServerAndPage({
startServerOnPort,
checkServerStdoutToSeeIfItsReady: (chunk) =>
chunk.includes('Accepting connections'),
})
})
describe(`dev`, () => {
function startServerOnPort(port: number): ProcessPromise<unknown> {
cd(PATH_TO_PACKAGE)
return $`npm run dev -- --port ${port}`
}
testServerAndPage({
startServerOnPort,
checkServerStdoutToSeeIfItsReady: (chunk) =>
chunk.includes('Server running'),
})
})
})

View file

@ -0,0 +1,26 @@
{
"private": true,
"version": "0.0.0",
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview"
},
"dependencies": {
"@react-three/drei": "^9.80.1",
"@react-three/fiber": "^8.13.6",
"three": "^0.155.0",
"@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"
},
"devDependencies": {
"@types/react": "^18.0.0",
"@types/react-dom": "^18.0.0",
"@vitejs/plugin-react": "^1.3.0",
"typescript": "^4.6.3",
"vite": "^2.9.9"
}
}

View file

@ -0,0 +1,102 @@
import {getProject} from '@theatre/core'
import React, {useEffect, useRef} 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}>
<boxGeometry />
<meshStandardMaterial color={color} />
</e.mesh>
)
}
export default function App() {
const light2Ref = useRef<any>()
useEffect(() => {
const interval = setInterval(() => {
if (!light2Ref.current) return
clearInterval(interval)
const intensityInStateJson = 3
const currentIntensity = light2Ref.current.intensity
if (currentIntensity !== intensityInStateJson) {
console.error(`Test failed: light2.intensity is ${currentIntensity}`)
} else {
console.log(`Test passed: light2.intensity is ${intensityInStateJson}`)
}
}, 50)
// see the note on <e.pointLight theatreKey="Light 2" /> below to understand why we're doing this
}, [])
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={light2Ref}
/>
<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,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,40 @@
// @cspotcode/zx is zx in CommonJS
import {$, cd, path, ProcessPromise} from '@cspotcode/zx'
import {testServerAndPage} from '../../utils/testUtils'
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}`
}
testServerAndPage({
startServerOnPort,
checkServerStdoutToSeeIfItsReady: (chunk) => chunk.includes('--host'),
})
})
describe(`vite dev`, () => {
function startServerOnPort(port: number): ProcessPromise<unknown> {
cd(PATH_TO_PACKAGE)
return $`npm run dev -- --port ${port}`
}
testServerAndPage({
startServerOnPort,
checkServerStdoutToSeeIfItsReady: (chunk) => chunk.includes('--host'),
})
})
})

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

@ -1,5 +1,4 @@
{
"name": "@compat/vite-react18",
"private": true,
"version": "0.0.0",
"scripts": {
@ -8,20 +7,20 @@
"preview": "vite preview"
},
"dependencies": {
"@react-three/drei": "^9.11.3",
"@react-three/fiber": "^8.0.19",
"@react-three/drei": "^9.80.1",
"@react-three/fiber": "^8.13.6",
"three": "^0.155.0",
"@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"
"react-dom": "^18.0.0"
},
"devDependencies": {
"@types/react": "^18.0.0",
"@types/react-dom": "^18.0.0",
"@vitejs/plugin-react": "^1.3.0",
"typescript": "^4.6.3",
"vite": "^2.9.9"
"vite": "^4.4.7"
}
}

View file

@ -0,0 +1,102 @@
import {getProject} from '@theatre/core'
import React, {useEffect, useRef} 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}>
<boxGeometry />
<meshStandardMaterial color={color} />
</e.mesh>
)
}
export default function App() {
const light2Ref = useRef<any>()
useEffect(() => {
const interval = setInterval(() => {
if (!light2Ref.current) return
clearInterval(interval)
const intensityInStateJson = 3
const currentIntensity = light2Ref.current.intensity
if (currentIntensity !== intensityInStateJson) {
console.error(`Test failed: light2.intensity is ${currentIntensity}`)
} else {
console.log(`Test passed: light2.intensity is ${intensityInStateJson}`)
}
}, 50)
// see the note on <e.pointLight theatreKey="Light 2" /> below to understand why we're doing this
}, [])
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={light2Ref}
/>
<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,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,40 @@
// @cspotcode/zx is zx in CommonJS
import {$, cd, path, ProcessPromise} from '@cspotcode/zx'
import {testServerAndPage} from '../../utils/testUtils'
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}`
}
testServerAndPage({
startServerOnPort,
checkServerStdoutToSeeIfItsReady: (chunk) => chunk.includes('--host'),
})
})
describe(`vite dev`, () => {
function startServerOnPort(port: number): ProcessPromise<unknown> {
cd(PATH_TO_PACKAGE)
return $`npm run dev -- --port ${port}`
}
testServerAndPage({
startServerOnPort,
checkServerStdoutToSeeIfItsReady: (chunk) => chunk.includes('--host'),
})
})
})

View file

@ -0,0 +1,51 @@
import * as path from 'path'
import * as fs from 'fs'
describe(`Compat tests`, () => {
test(`all fixtures prefixed with 'r3f-' should have an App/ directory identical to that of vite4's`, async () => {
const vite4AppDir = path.join(
__dirname,
'./fixtures/r3f-vite4/package/src/App',
)
const vite4FilesContents = fs
.readdirSync(vite4AppDir)
.map((file) => [
file,
fs.readFileSync(path.join(vite4AppDir, file), 'utf-8'),
])
const allFixtures = fs
.readdirSync(path.join(__dirname, './fixtures'))
.filter(
(fixture) =>
fixture !== 'r3f-vite4' &&
fixture.startsWith('r3f-') &&
// item is a folder
fs
.lstatSync(path.join(__dirname, './fixtures', fixture))
.isDirectory(),
)
for (const fixture of allFixtures) {
const appDir = path.join(
__dirname,
`./fixtures/${fixture}/package/src/App`,
)
if (!fs.existsSync(appDir)) {
throw new Error(`Fixture ${fixture} does not have an App/ directory`)
}
for (const [file, contents] of vite4FilesContents) {
const fixtureFileContents = fs.readFileSync(
path.join(appDir, file),
'utf-8',
)
if (fixtureFileContents !== contents) {
throw new Error(
`The file ${file} in fixture ${fixture} is not identical to that of vite4's`,
)
}
}
}
})
})

21
compat-tests/package.json Normal file
View file

@ -0,0 +1,21 @@
{
"name": "@theatre/compat-tests",
"private": true,
"scripts": {
"install-fixtures": "node -r esbuild-register ./scripts/install-fixtures.ts",
"clean": "node -r esbuild-register ./scripts/clean.ts"
},
"dependencies": {
"@cspotcode/zx": "^6.1.2",
"@verdaccio/types": "^10.8.0",
"esbuild": "^0.18.18",
"esbuild-register": "^3.4.2",
"node-cleanup": "^2.1.2",
"playwright": "^1.29.1",
"prettier": "^2.6.2",
"verdaccio": "^5.26.1",
"verdaccio-auth-memory": "^10.2.2",
"verdaccio-memory": "^10.3.2"
},
"version": "0.0.1-COMPAT.1"
}

View file

@ -0,0 +1,3 @@
import {clean} from './scripts'
clean()

View file

@ -0,0 +1,3 @@
import {installFixtures} from './scripts'
installFixtures()

View file

@ -2,12 +2,12 @@
* Utility functions for the compatibility tests
*/
import prettier from 'prettier'
import path from 'path'
import {globby, argv, YAML, $, fs, cd, os, within} from 'zx'
import * as prettier from 'prettier'
import * as path from 'path'
import {globby, argv, YAML, $, fs, cd, os} from '@cspotcode/zx'
import onCleanup from 'node-cleanup'
import * as verdaccioPackage from 'verdaccio'
import {chromium, devices} from 'playwright'
import startVerdaccioServer from 'verdaccio'
import {defer} from '../utils/testUtils'
/**
* @param {string} pkg
@ -25,10 +25,6 @@ if (!verbose) {
)
}
// 'verdaccio' is not an es module so we have to do this:
// @ts-ignore
const startVerdaccioServer = verdaccioPackage.default.default
const config = {
VERDACCIO_PORT: 4823,
VERDACCIO_HOST: `localhost`,
@ -50,14 +46,18 @@ process.env.NPM_CONFIG_REGISTRY = config.VERDACCIO_URL
const tempVersion =
'0.0.1-COMPAT.' +
// a random integer between 1 and 50000
(Math.floor(Math.random() * 50000) + 1).toString()
(typeof argv['version'] === 'number'
? argv['version'].toString()
: // a random integer between 1 and 50000
(Math.floor(Math.random() * 50000) + 1).toString())
const keepAlive = !!argv['keep-alive']
/**
* This script starts verdaccio and publishes all the packages in the monorepo to it, then
* it runs `npm install` on all the test packages, and finally it closes verdaccio.
*/
export async function installFixtures() {
export async function installFixtures(): Promise<void> {
onCleanup((exitCode, signal) => {
onCleanup.uninstall()
restoreTestPackageJsons()
@ -65,7 +65,9 @@ export async function installFixtures() {
return false
})
console.log('Using temporary version: ' + tempVersion)
console.log(
`Using temporary version: ${tempVersion} . Use --version=[NUMBER] to change.`,
)
console.log('Patching package.json files in ./test-*')
const restoreTestPackageJsons = await patchTestPackageJsons()
@ -78,29 +80,75 @@ export async function installFixtures() {
console.log('Running `$ npm install` on test packages')
await runNpmInstallOnTestPackages()
console.log('All tests installed successfully')
await verdaccioServer.close()
restoreTestPackageJsons()
if (keepAlive) {
console.log('Keeping verdaccio alive. Press Ctrl+C to exit.')
// wait for ctrl+c
await new Promise((resolve) => {})
} else {
console.log('Closing verdaccio. Use --keep-alive to keep it running.')
await verdaccioServer.close()
}
console.log('Done')
}
async function runNpmInstallOnTestPackages() {
const packagePaths = await getCompatibilityTestSetups()
for (const pathToPackageDir of packagePaths) {
cd(pathToPackageDir)
const promises = packagePaths.map(async (pathToPackageDir) => {
await fs.remove(path.join(pathToPackageDir, 'node_modules'))
await fs.remove(path.join(pathToPackageDir, 'package-lock.json'))
cd(path.join(pathToPackageDir, '../'))
const tempPath = fs.mkdtempSync(
path.join(os.tmpdir(), 'theatre-compat-test-'),
)
await fs.copy(pathToPackageDir, tempPath)
cd(path.join(tempPath))
try {
console.log('Running npm install on ' + pathToPackageDir + '...')
await $`npm install --registry ${config.VERDACCIO_URL} --loglevel ${
verbose ? 'warn' : 'error'
} --fund false`
console.log('npm install finished successfully in' + tempPath)
await fs.move(
path.join(tempPath, 'node_modules'),
path.join(pathToPackageDir, 'node_modules'),
)
await fs.move(
path.join(tempPath, 'package-lock.json'),
path.join(pathToPackageDir, 'package-lock.json'),
)
} catch (error) {
console.error(`Failed to install dependencies for ${pathToPackageDir}
Try running \`npm install\` in that directory manually via:
cd ${pathToPackageDir}
npm install --registry ${config.VERDACCIO_URL}
Original error: ${error}`)
throw new Error(`Failed to install dependencies for ${pathToPackageDir}`)
} finally {
await fs.remove(tempPath)
}
})
const result = await Promise.allSettled(promises)
const failed = result.filter((x) => x.status === 'rejected')
if (failed.length > 0) {
console.error(
`Failed to install dependencies for the following packages:`,
result
.map((result, i) => [packagePaths[i], result])
.filter(
([p, result]) =>
// @ts-ignore
result.status === 'rejected',
)
.map(([path]) => path),
)
}
}
@ -146,7 +194,7 @@ async function patchTheatreDependencies(pathToPackageJson, version) {
fs.writeFileSync(pathToPackageJson, jsonStringPrettified, {encoding: 'utf-8'})
}
async function patchTestPackageJsons() {
async function patchTestPackageJsons(): Promise<() => void> {
const packagePaths = (await getCompatibilityTestSetups()).map(
(pathToPackageDir) => path.join(pathToPackageDir, 'package.json'),
)
@ -169,45 +217,49 @@ async function patchTestPackageJsons() {
*
* Credit: https://github.com/storybookjs/storybook/blob/92b23c080d03433765cbc7a60553d036a612a501/scripts/run-registry.ts
*/
const startVerdaccio = (port) => {
async function startVerdaccio(port: number): Promise<{close: () => void}> {
let resolved = false
return Promise.race([
new Promise((resolve) => {
const config = {
...YAML.parse(
fs.readFileSync(path.join(__dirname, '../verdaccio.yml'), 'utf8'),
),
}
if (verbose) {
config.logs.level = 'warn'
}
const deferred = defer<{close: () => void}>()
const onReady = (webServer) => {
webServer.listen(port, () => {
resolved = true
resolve(webServer)
})
}
const config = {
...YAML.parse(
fs.readFileSync(path.join(__dirname, '../verdaccio.yml'), 'utf8'),
),
}
startVerdaccioServer(
config,
6000,
undefined,
'1.0.0',
'verdaccio',
onReady,
)
}),
if (verbose) {
config.logs.level = 'warn'
}
const cache = path.join(__dirname, '../.verdaccio-cache')
config.self_path = cache
startVerdaccioServer(
config,
'6000',
cache,
'1.0.0',
'verdaccio',
(webServer) => {
webServer.listen(port, () => {
resolved = true
deferred.resolve(webServer)
})
},
)
await Promise.race([
deferred.promise,
new Promise((_, rej) => {
setTimeout(() => {
if (!resolved) {
resolved = true
rej(new Error(`TIMEOUT - verdaccio didn't start within 10s`))
}
rej(new Error(`TIMEOUT - verdaccio didn't start within 10s`))
}, 10000)
}),
])
return deferred.promise
}
const packagesToPublish = [
@ -224,11 +276,14 @@ const packagesToPublish = [
* Assigns a new version to each of @theatre/* packages. If there a package depends on another package in this monorepo,
* this function makes sure the dependency version is fixed at "version"
*
* @param {{name: string, location: string}[]} workspacesListObjects - An Array of objects containing information about the workspaces
* @param {string} version - Version of the latest commit (or any other string)
* @returns {Promise<() => void>} - An async function that restores the package.json files to their original version
* @param workspacesListObjects - An Array of objects containing information about the workspaces
* @param version - Version of the latest commit (or any other string)
* @returns - An async function that restores the package.json files to their original version
*/
async function writeVersionsToPackageJSONs(workspacesListObjects, version) {
async function writeVersionsToPackageJSONs(
workspacesListObjects: Array<{name: string; location: string}>,
version: string,
): Promise<() => void> {
/**
* An array of functions each of which restores a certain package.json to its original state
* @type {Array<() => void>}
@ -309,8 +364,8 @@ async function releaseToVerdaccio() {
})
try {
await $`yarn clean`
await $`yarn build`
await $`yarn cli build clean`
await $`yarn cli build`
await Promise.all(
packagesToPublish.map(async (workspaceName) => {
@ -324,11 +379,11 @@ async function releaseToVerdaccio() {
}
/**
* Get all the setups from `./compatibility-tests/`
* Get all the setups from `./compat-tests/`
*
* @returns {Promise<Array<string>>} An array containing the absolute paths to the compatibility test setups
* @returns An array containing the absolute paths to the compatibility test setups
*/
export async function getCompatibilityTestSetups() {
export async function getCompatibilityTestSetups(): Promise<Array<string>> {
const fixturePackageJsonFiles = await globby(
'./fixtures/*/package/package.json',
{
@ -348,7 +403,7 @@ export async function getCompatibilityTestSetups() {
*/
export async function clean() {
const toDelete = await globby(
'./fixtures/*/package/(node_modules|yarn.lock|package-lock.json)',
'./fixtures/*/package/(node_modules|yarn.lock|package-lock.json|.parcel-cache)',
{
cwd: config.PATH_TO_COMPAT_TESTS_ROOT,
// node_modules et al are gitignored, but we still want to clean them

View file

@ -0,0 +1,19 @@
{
"compilerOptions": {
"outDir": "dist",
"lib": ["ESNext", "DOM"],
"rootDir": ".",
"types": ["jest", "node"],
"target": "es6",
"noEmit": true,
"composite": true,
"moduleResolution": "node",
"skipLibCheck": true
},
"include": [
"./scripts/*.ts",
"./*.compat-test.ts",
"./fixtures/*/*.compat-test.ts",
"./utils/**/*.ts"
]
}

View file

@ -0,0 +1,191 @@
import {Browser, chromium, ConsoleMessage, devices, Page} from 'playwright'
import {ProcessPromise} from '@cspotcode/zx'
export function testServerAndPage({
startServerOnPort,
checkServerStdoutToSeeIfItsReady,
}: {
startServerOnPort: (port: number) => ProcessPromise<unknown>
checkServerStdoutToSeeIfItsReady: (chunk: string) => boolean
}) {
if (checkServerStdoutToSeeIfItsReady('') !== false) {
throw new Error(
`Incorrect test setup. checkServerStdoutToSeeIfItsReady should return false for an empty string.`,
)
}
const waitTilServerIsReady = async (
process: ProcessPromise<unknown>,
): Promise<void> => {
const d = defer<void>()
process.stdout.on('data', (chunk) => {
if (checkServerStdoutToSeeIfItsReady(chunk.toString())) {
// server is ready
d.resolve()
}
})
await Promise.race([
d.promise,
new Promise((_, reject) =>
setTimeout(
() => reject(`Server wasn't ready after two minutes`),
1000 * 60 * 2,
),
),
])
return d.promise
}
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}`)
}
const url = `http://localhost:${port}`
try {
await waitTilServerIsReady(process)
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: 1000 * 60 * 2,
})
// give the console listener 3 seconds to resolve, otherwise fail the test
await Promise.race([
d.promise,
new Promise((_, reject) =>
setTimeout(
() => reject('Did not intercept any test-related console logs'),
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
}

View file

@ -1,6 +1,6 @@
store:
memory:
limit: 1000
limit: 10000
auth:
auth-memory:
users:

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,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,17 +0,0 @@
{
"name": "@compat/parcel1-react17",
"scripts": {
"dev": "parcel serve ./index.html"
},
"dependencies": {
"@react-three/drei": "^7.3.1",
"@react-three/fiber": "^7.0.6",
"@theatre/core": "0.0.1-COMPAT.1",
"@theatre/r3f": "0.0.1-COMPAT.1",
"@theatre/studio": "0.0.1-COMPAT.1",
"parcel-bundler": "^1.12.5",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"three": "^0.137.0"
}
}

View file

@ -1,91 +0,0 @@
import {getProject} from '@theatre/core'
import ReactDOM from 'react-dom'
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>
)
}
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root'),
)

View file

@ -1,14 +0,0 @@
{
"name": "@compat/parcel1-react18",
"scripts": {
"dev": "parcel serve ./index.html"
},
"dependencies": {
"@theatre/core": "0.0.1-COMPAT.1",
"@theatre/r3f": "0.0.1-COMPAT.1",
"@theatre/studio": "0.0.1-COMPAT.1",
"parcel-bundler": "^1.12.5",
"react": "^18.1.0",
"react-dom": "^18.1.0"
}
}

View file

@ -1,14 +0,0 @@
{
"name": "@compat/parcel2-react18",
"scripts": {
"dev": "parcel serve ./index.html"
},
"dependencies": {
"@theatre/core": "0.0.1-COMPAT.1",
"@theatre/r3f": "0.0.1-COMPAT.1",
"@theatre/studio": "0.0.1-COMPAT.1",
"parcel": "^2.5.0",
"react": "^18.1.0",
"react-dom": "^18.1.0"
}
}

View file

@ -1,20 +0,0 @@
{
"name": "@theatre/compatibility-tests",
"private": true,
"type": "module",
"scripts": {
"install-fixtures": "zx ./scripts/install-fixtures.mjs",
"clean": "zx ./scripts/clean.mjs"
},
"dependencies": {
"@cspotcode/zx": "^6.1.2",
"node-cleanup": "^2.1.2",
"playwright": "^1.28.1",
"prettier": "^2.6.2",
"verdaccio": "^5.10.2",
"verdaccio-auth-memory": "^10.2.0",
"verdaccio-memory": "^10.2.0",
"zx": "^7.1.1"
},
"version": "0.0.1-COMPAT.1"
}

View file

@ -1,39 +0,0 @@
/**
* Build the test setups
*/
import path from 'path'
import {cd, fs, $} from 'zx'
import {getCompatibilityTestSetups} from './utils.mjs'
const absPathOfCompatibilityTestSetups = getCompatibilityTestSetups()
const setupsWithErros = []
// Try building the setups
;(async function () {
for (const setupDir of absPathOfCompatibilityTestSetups) {
try {
cd(setupDir)
const pathToSetup = path.join(setupDir, setupDir)
fs.removeSync(path.join(pathToSetup, 'node_modules'))
fs.removeSync(path.join(pathToSetup, 'package-lock.json'))
fs.removeSync(path.join(pathToSetup, 'yarn.lock'))
await $`npm install`
await $`npm run build`
} catch (err) {
console.error(err)
setupsWithErros.push(setupDir)
}
}
// Stop if there were any errors during the build process,
// and print all of them to the console.
if (setupsWithErros.length !== 0) {
throw new Error(
`The following setups had problems when their dependencies were being installed:\n${(
setupsWithErros.join('\n'),
)}`,
)
}
})()

View file

@ -1,5 +0,0 @@
import {installTests} from './scripts.mjs'
;(async function runCI() {
await installTests()
process.exit(0)
})()

View file

@ -1,3 +0,0 @@
import {clean} from './scripts.mjs'
await clean()

View file

@ -1,3 +0,0 @@
import {installFixtures} from './scripts.mjs'
installFixtures()

471
devEnv/cli.ts Normal file
View file

@ -0,0 +1,471 @@
import sade from 'sade'
import {$, fs, path} from '@cspotcode/zx'
import * as core from '@actions/core'
import * as os from 'os'
const root = path.join(__dirname, '..')
const prog = sade('cli').describe('CLI for Theatre.js development')
// better quote function from https://github.com/google/zx/pull/167
$.quote = function quote(arg) {
if (/^[a-z0-9/_.-]+$/i.test(arg)) {
return arg
}
return (
`$'` +
arg
.replace(/\\/g, '\\\\')
.replace(/'/g, "\\'")
.replace(/\f/g, '\\f')
.replace(/\n/g, '\\n')
.replace(/\r/g, '\\r')
.replace(/\t/g, '\\t')
.replace(/\v/g, '\\v')
.replace(/\0/g, '\\0') +
`'`
)
}
prog
.command(
'build clean',
'Cleans the build artifacts and output directories of all the main packages',
)
.action(async () => {
const packages = [
'theatre',
'@theatre/dataverse',
'@theatre/react',
'@theatre/browser-bundles',
'@theatre/r3f',
'theatric',
]
await Promise.all([
...packages.map((workspace) => $`yarn workspace ${workspace} run clean`),
])
})
prog.command('build', 'Builds all the main packages').action(async () => {
const packagesToBuild = [
'theatre',
'@theatre/dataverse',
'@theatre/react',
'@theatre/browser-bundles',
'@theatre/r3f',
'theatric',
]
async function build() {
await Promise.all([
$`yarn run build:ts`,
...packagesToBuild.map(
(workspace) => $`yarn workspace ${workspace} run build`,
),
])
}
void build()
})
prog
.command('release <version>', 'Releases all the main packages to npm')
.option('--skip-ts', 'Skip emitting typescript declarations')
.option('--skip-lint', 'Skip typecheck and lint')
.action(async (version, opts) => {
/**
* This script publishes all packages to npm.
*
* It assigns the same version number to all packages (like lerna's fixed mode).
**/
const packagesToBuild = [
'theatre',
'@theatre/dataverse',
'@theatre/react',
'@theatre/browser-bundles',
'@theatre/r3f',
'theatric',
]
const packagesToPublish = [
'@theatre/core',
'@theatre/studio',
'@theatre/dataverse',
'@theatre/react',
'@theatre/browser-bundles',
'@theatre/r3f',
'theatric',
]
/**
* All these packages will have the same version from monorepo/package.json
*/
const packagesWhoseVersionsShouldBump = [
'.',
'theatre',
'theatre/core',
'theatre/studio',
'packages/dataverse',
'packages/react',
'packages/browser-bundles',
'packages/r3f',
'packages/theatric',
]
// our packages will check for this env variable to make sure their
// prepublish script is only called from the `$ cd /path/to/monorepo; yarn run release`
// @ts-ignore ignore
process.env.THEATRE_IS_PUBLISHING = true
async function release() {
$.verbose = false
const gitTags = (await $`git tag --list`).toString().split('\n')
if (typeof version !== 'string') {
console.error(
`You need to specify a version, like: $ yarn cli release 1.2.0-rc.4`,
)
process.exit(1)
} else if (
!version.match(/^[0-9]+\.[0-9]+\.[0-9]+(\-(dev|rc)\.[0-9]+)?$/)
) {
console.error(
`Use a semver version, like 1.2.3-rc.4. Provided: ${version}`,
)
process.exit(1)
}
const previousVersion = require('../package.json').version
if (version === previousVersion) {
console.error(
`Version ${version} is already assigned to root/package.json`,
)
process.exit(1)
}
if (gitTags.some((tag) => tag === version)) {
console.error(`There is already a git tag for version ${version}`)
process.exit(1)
}
let npmTag = 'latest'
if (version.match(/^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$/)) {
console.log('npm tag: latest')
} else {
const matches = version.match(
/^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\-(dev|rc|beta)\.[0-9]{1,3}$/,
)
if (!matches) {
console.log(
'Invalid version. Currently xx.xx.xx or xx.xx.xx-(dev|rc|beta).xx is allowed',
)
process.exit(1)
}
npmTag = matches[1]
console.log('npm tag: ' + npmTag)
}
if ((await $`git status -s`).toString().length > 0) {
console.error(`Git working directory contains uncommitted changes:`)
$.verbose = true
await $`git status -s`
console.log('Commit/stash them and try again.')
process.exit(1)
}
$.verbose = true
if (opts['skip-lint'] !== true) {
console.log('Running a typecheck and lint pass')
await Promise.all([$`yarn run typecheck`, $`yarn run lint:all`])
} else {
console.log('Skipping typecheck and lint')
}
const skipTypescriptEmit = opts['skip-ts'] === true
console.log('Assigning versions')
await writeVersionsToPackageJSONs(version)
console.log('Building all packages')
await Promise.all(
packagesToBuild.map((workspace) =>
skipTypescriptEmit
? $`yarn workspace ${workspace} run build:js`
: $`yarn workspace ${workspace} run build`,
),
)
// temporarily rolling back the version assignments to make sure they don't show
// up in `$ git status`. (would've been better to just ignore hese particular changes
// but i'm lazy)
await restoreVersions()
console.log(
'Checking if the build produced artifacts that must first be comitted to git',
)
$.verbose = false
if ((await $`git status -s`).toString().length > 0) {
$.verbose = true
await $`git status -s`
console.error(`Git directory contains uncommitted changes.`)
process.exit(1)
}
$.verbose = true
await writeVersionsToPackageJSONs(version)
console.log('Committing/tagging')
await $`git add .`
await $`git commit -m ${version}`
await $`git tag ${version}`
// if (!gitTags.some((tag) => tag === version)) {
// console.log(
// `No git tag found for version "${version}". Run \`$ git tag ${version}\` and try again.`,
// )
// process.exit()
// }
console.log('Publishing to npm')
await Promise.all(
packagesToPublish.map(
(workspace) =>
$`yarn workspace ${workspace} npm publish --access public --tag ${npmTag}`,
),
)
}
void release()
async function writeVersionsToPackageJSONs(monorepoVersion: string) {
for (const packagePathRelativeFromRoot of packagesWhoseVersionsShouldBump) {
const pathToPackage = path.resolve(
__dirname,
'../',
packagePathRelativeFromRoot,
'./package.json',
)
const original = JSON.parse(
fs.readFileSync(pathToPackage, {encoding: 'utf-8'}),
)
const newJson = {...original, version: monorepoVersion}
fs.writeFileSync(
path.join(pathToPackage),
JSON.stringify(newJson, undefined, 2),
{encoding: 'utf-8'},
)
await $`prettier --write ${
packagePathRelativeFromRoot + '/package.json'
}`
}
}
async function restoreVersions() {
const wasVerbose = $.verbose
$.verbose = false
for (const packagePathRelativeFromRoot of packagesWhoseVersionsShouldBump) {
const pathToPackageInGit = packagePathRelativeFromRoot + '/package.json'
await $`git checkout ${pathToPackageInGit}`
}
$.verbose = wasVerbose
}
})
prog
.command(
'prerelease ci',
"This script publishes the insider packages from the CI. You can't run it locally unless you have a a valid npm access token and you store its value in the `NPM_TOKEN` environmental variable.",
)
.action(async () => {
const packagesToPublish = [
'@theatre/core',
'@theatre/studio',
'@theatre/dataverse',
'@theatre/react',
'@theatre/browser-bundles',
'@theatre/r3f',
'theatric',
]
/**
* Receives a version number and returns it without the tags, if there are any
*
* @param version - Version number
* @returns Version number without the tags
*
* @example
* ```javascript
* const version_1 = '0.4.8-dev3-ec175817'
* const version_2 = '0.4.8'
*
* stripTag(version_1) === stripTag(version_2) === '0.4.8' // returns `true`
* ```
*/
function stripTag(version: string) {
const regExp = /^[0-9]+\.[0-9]+\.[0-9]+/g
const matches = version.match(regExp)
if (!matches) {
throw new Error(`Version number not found in "${version}"`)
}
return matches[0]
}
/**
* Creates a version number like `0.4.8-insiders.ec175817`
*
* @param packageName - Name of the package
* @param commitHash - A commit hash
*/
function getNewVersionName(packageName: string, commitHash: string) {
// The `r3f` package has its own release schedule, so its version numbers
// are almost always different from the rest of the packages.
const pathToPackageJson =
packageName === '@theatre/r3f'
? path.resolve(__dirname, '../', 'packages', 'r3f', 'package.json')
: path.resolve(__dirname, '../', './package.json')
const jsonData = JSON.parse(
fs.readFileSync(pathToPackageJson, {encoding: 'utf-8'}),
)
const strippedVersion = stripTag(jsonData.version)
return `${strippedVersion}-insiders.${commitHash}`
}
/**
* Assigns the latest version names ({@link getNewVersionName}) to the packages' `package.json`s
*
* @param workspacesListObjects - An Array of objects containing information about the workspaces
* @param latestCommitHash - Hash of the latest commit
* @returns - A record of `{[packageId]: assignedVersion}`
*/
async function writeVersionsToPackageJSONs(
workspacesListObjects: {name: string; location: string}[],
latestCommitHash: string,
): Promise<Record<string, string>> {
const assignedVersionByPackageName: Record<string, string> = {}
for (const workspaceData of workspacesListObjects) {
const pathToPackage = path.resolve(
__dirname,
'../',
workspaceData.location,
'./package.json',
)
const original = JSON.parse(
fs.readFileSync(pathToPackage, {encoding: 'utf-8'}),
)
let {version, dependencies, peerDependencies, devDependencies} =
original
// The @theatre/r3f package curently doesn't track the same version number of the other packages like @theatre/core,
// so we need to generate version numbers independently for each package
version = getNewVersionName(workspaceData.name, latestCommitHash)
assignedVersionByPackageName[workspaceData.name] = version
// Normally we don't have to override the package versions in dependencies because yarn would already convert
// all the "workspace:*" versions to a fixed version before publishing. However, packages like @theatre/studio
// have a peerDependency on @theatre/core set to "*" (meaning they would work with any version of @theatre/core).
// This is not the desired behavior in pre-release versions, so here, we'll fix those "*" versions to the set version.
for (const deps of [dependencies, peerDependencies, devDependencies]) {
if (!deps) continue
for (const wpObject of workspacesListObjects) {
if (deps[wpObject.name]) {
deps[wpObject.name] = getNewVersionName(
wpObject.name,
latestCommitHash,
)
}
}
}
const newJson = {
...original,
version,
dependencies,
peerDependencies,
devDependencies,
}
fs.writeFileSync(
path.join(pathToPackage),
JSON.stringify(newJson, undefined, 2),
{encoding: 'utf-8'},
)
await $`prettier --write ${workspaceData.location + '/package.json'}`
}
return assignedVersionByPackageName
}
async function prerelease() {
// @ts-ignore ignore
process.env.THEATRE_IS_PUBLISHING = true
// In the CI `git log -1` points to a fake merge commit,
// so we have to use the value of a special GitHub context variable
// through the `GITHUB_SHA` environmental variable.
// The length of the abbreviated commit hash can change, that's why we
// need the length of the fake merge commit's abbreviated hash.
const fakeMergeCommitHashLength = (await $`git log -1 --pretty=format:%h`)
.stdout.length
if (!process.env.GITHUB_SHA)
throw new Error(
'expected `process.env.GITHUB_SHA` to be defined but it was not',
)
const latestCommitHash = process.env.GITHUB_SHA.slice(
0,
fakeMergeCommitHashLength,
)
const workspacesListString = await $`yarn workspaces list --json`
const workspacesListObjects = workspacesListString.stdout
.split(os.EOL)
// strip out empty lines
.filter(Boolean)
.map((x) => JSON.parse(x))
const assignedVersionByPackageName = await writeVersionsToPackageJSONs(
workspacesListObjects,
latestCommitHash,
)
await Promise.all(
packagesToPublish.map(async (workspaceName) => {
const npmTag = 'insiders'
if (process.env.GITHUB_ACTIONS) {
await $`yarn workspace ${workspaceName} npm publish --access public --tag ${npmTag}`
}
}),
)
if (process.env.GITHUB_ACTIONS) {
const data = packagesToPublish.map((packageName) => ({
packageName,
version: assignedVersionByPackageName[packageName],
}))
// set the output for github actions.
core.setOutput('data', JSON.stringify(data))
} else {
for (const packageName of packagesToPublish) {
await $`echo ${`Published ${packageName}@${assignedVersionByPackageName[packageName]}`}`
}
}
}
void prerelease()
})
prog
.command('dev all', 'Starts all services to develop all of the packages')
.action(async () => {
await $`yarn workspace playground run serve`
})
prog.parse(process.argv)

View file

@ -4,7 +4,7 @@
"outDir": "dist",
"lib": ["ESNext", "DOM"],
"rootDir": ".",
"types": ["node"],
"types": ["node", "jest"],
"noEmit": true,
"target": "es6",
"composite": true

Some files were not shown because too many files have changed in this diff Show more