Re-do bundling, compat tests, and extension API (#174)

This commit is contained in:
Aria 2022-05-25 00:37:18 +02:00 committed by GitHub
parent 5ee9a2543f
commit ec18687a98
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
83 changed files with 1138 additions and 886 deletions

5
compatibility-tests/.gitignore vendored Normal file
View file

@ -0,0 +1,5 @@
# these lock files include checksums of the @theatre/*@compat packages, which
# would change after every edit to their source, so we better not keep them
# in the repo
/*/package-lock.json
/*/yarn.lock

View file

@ -3,7 +3,8 @@
"private": true, "private": true,
"scripts": { "scripts": {
"registry:start": "zx ./scripts/start-registry.mjs", "registry:start": "zx ./scripts/start-registry.mjs",
"test:ci": "zx ./scripts/ci.mjs" "test:ci": "zx ./scripts/ci.mjs",
"clean": "zx ./scripts/clean.mjs"
}, },
"dependencies": { "dependencies": {
"node-cleanup": "^2.1.2", "node-cleanup": "^2.1.2",
@ -12,5 +13,6 @@
"verdaccio-auth-memory": "^10.2.0", "verdaccio-auth-memory": "^10.2.0",
"verdaccio-memory": "^10.2.0", "verdaccio-memory": "^10.2.0",
"zx": "^6.1.0" "zx": "^6.1.0"
} },
"version": "0.0.1-COMPAT.1"
} }

View file

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

View file

@ -2,9 +2,8 @@
* Utility functions for the compatibility tests * Utility functions for the compatibility tests
*/ */
import fs from 'fs'
import path from 'path' import path from 'path'
import {YAML} from 'zx' import {globby, YAML} from 'zx'
import onCleanup from 'node-cleanup' import onCleanup from 'node-cleanup'
import * as verdaccioPackage from 'verdaccio' import * as verdaccioPackage from 'verdaccio'
@ -14,6 +13,7 @@ const startVerdaccioServer = verdaccioPackage.default.default
export const VERDACCIO_PORT = 4823 export const VERDACCIO_PORT = 4823
export const VERDACCIO_HOST = `localhost` export const VERDACCIO_HOST = `localhost`
export const VERDACCIO_URL = `http://${VERDACCIO_HOST}:${VERDACCIO_PORT}/` export const VERDACCIO_URL = `http://${VERDACCIO_HOST}:${VERDACCIO_PORT}/`
export const PATH_TO_COMPAT_TESTS_ROOT = path.join(__dirname, '..')
export const MONOREPO_ROOT = path.join(__dirname, '../..') export const MONOREPO_ROOT = path.join(__dirname, '../..')
export const PATH_TO_YARNRC = path.join(MONOREPO_ROOT, '.yarnrc.yml') export const PATH_TO_YARNRC = path.join(MONOREPO_ROOT, '.yarnrc.yml')
@ -259,3 +259,23 @@ export function getCompatibilityTestSetups() {
return setupsAbsPaths return setupsAbsPaths
} }
/**
* Deletes ../test-*\/(node_modules|package-lock.json|yarn.lock)
*/
export async function clean() {
const toDelete = await globby(
'./test-*/(node_modules|yarn.lock|package-lock.json)',
{
cwd: PATH_TO_COMPAT_TESTS_ROOT,
// node_modules et al are gitignored, but we still want to clean them
gitignore: false,
// include directories too
onlyFiles: false,
},
)
toDelete.forEach((fileOrDir) => {
console.log('deleting', fileOrDir)
fs.removeSync(path.join(PATH_TO_COMPAT_TESTS_ROOT, fileOrDir))
})
}

View file

@ -0,0 +1 @@
Testing `@theatre/core` and `@theatre/studio` with `npm`, `create-react-app`, and `react@18`

View file

@ -1,5 +1,5 @@
{ {
"name": "@theatre-build-tests/react-app", "name": "@compat/cra-react18",
"version": "0.1.0", "version": "0.1.0",
"private": true, "private": true,
"scripts": { "scripts": {
@ -15,7 +15,6 @@
"@testing-library/user-event": "^12.1.10", "@testing-library/user-event": "^12.1.10",
"@theatre/core": "^0.0.1-COMPAT.1", "@theatre/core": "^0.0.1-COMPAT.1",
"@theatre/studio": "^0.0.1-COMPAT.1", "@theatre/studio": "^0.0.1-COMPAT.1",
"@theatre/r3f": "^0.0.1-COMPAT.1",
"react-scripts": "^5.0.1", "react-scripts": "^5.0.1",
"three": ">0.132.0", "three": ">0.132.0",
"web-vitals": "^1.0.1" "web-vitals": "^1.0.1"

View file

@ -2,19 +2,13 @@
<html lang="en"> <html lang="en">
<head> <head>
<meta charset="utf-8" /> <meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" /> <meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" /> <meta name="theme-color" content="#000000" />
<meta <meta
name="description" name="description"
content="Web site created using create-react-app" content="Web site created using create-react-app"
/> />
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
<!--
manifest.json provides metadata used when your web app is installed on a
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
-->
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<!-- <!--
Notice the use of %PUBLIC_URL% in the tags above. Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build. It will be replaced with the URL of the `public` folder during the build.

View file

@ -0,0 +1,6 @@
import React from 'react'
export default function App({obj}) {
console.log(obj)
return <div>hi</div>
}

View file

@ -0,0 +1,19 @@
// import ReactDOM from 'react-dom'
import studio from '@theatre/studio'
import {getProject} from '@theatre/core'
// import React from 'react'
// import App from './App'
studio.initialize({usePersistentStorage: false})
const project = getProject('Project')
const sheet = project.sheet('Sheet')
const obj = sheet.object('Obj', {str: 'some string', num: 0})
// ReactDOM.render(
// <React.StrictMode>
// <App obj={obj} />
// </React.StrictMode>,
// document.getElementById('root'),
// )

View file

@ -1,16 +0,0 @@
# Theatre.js project with `create-react-app` using the `r3f extension`
## Setup
Please refer to [this guide](../README.md#testing-the-configurations-locally).
## Usage
- start the development server:
```sh
yarn start
```
- build the project:
```sh
yarn build
```

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.4 KiB

View file

@ -1,25 +0,0 @@
{
"short_name": "React App",
"name": "Create React App Sample",
"icons": [
{
"src": "favicon.ico",
"sizes": "64x64 32x32 24x24 16x16",
"type": "image/x-icon"
},
{
"src": "logo192.png",
"type": "image/png",
"sizes": "192x192"
},
{
"src": "logo512.png",
"type": "image/png",
"sizes": "512x512"
}
],
"start_url": ".",
"display": "standalone",
"theme_color": "#000000",
"background_color": "#ffffff"
}

View file

@ -1,3 +0,0 @@
# https://www.robotstxt.org/robotstxt.html
User-agent: *
Disallow:

View file

@ -1,38 +0,0 @@
.App {
text-align: center;
}
.App-logo {
height: 40vmin;
pointer-events: none;
}
@media (prefers-reduced-motion: no-preference) {
.App-logo {
animation: App-logo-spin infinite 20s linear;
}
}
.App-header {
background-color: #282c34;
min-height: 100vh;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
font-size: calc(10px + 2vmin);
color: white;
}
.App-link {
color: #61dafb;
}
@keyframes App-logo-spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}

View file

@ -1,150 +0,0 @@
import {getProject} from '@theatre/core'
import * as THREE from 'three'
import {useState, useEffect, useRef} from 'react'
import {useFrame, Canvas} from '@react-three/fiber'
import {Shadow, softShadows} from '@react-three/drei'
import React from 'react'
import studio from '@theatre/studio'
import {editable as e, SheetProvider, extension} from '@theatre/r3f'
if (process.env.NODE_ENV === 'development') {
studio.extend(extension)
studio.initialize()
}
// Soft shadows are expensive, comment and refresh when it's too slow
softShadows()
// credit: https://codesandbox.io/s/camera-pan-nsb7f
function Button() {
const vec = new THREE.Vector3()
const light = useRef(undefined)
const [active, setActive] = useState(false)
const [zoom, set] = useState(true)
useEffect(
() => void (document.body.style.cursor = active ? 'pointer' : 'auto'),
[active],
)
useFrame((state) => {
const step = 0.1
const camera = state.camera
camera.fov = THREE.MathUtils.lerp(camera.fov, zoom ? 10 : 42, step)
camera.position.lerp(
vec.set(zoom ? 25 : 10, zoom ? 1 : 5, zoom ? 0 : 10),
step,
)
state.camera.lookAt(0, 0, 0)
state.camera.updateProjectionMatrix()
light.current.position.lerp(
vec.set(zoom ? 4 : 0, zoom ? 3 : 8, zoom ? 3 : 5),
step,
)
})
return (
<e.mesh
receiveShadow
castShadow
onClick={() => set(!zoom)}
onPointerOver={() => setActive(true)}
onPointerOut={() => setActive(false)}
uniqueName="The Button"
>
<sphereBufferGeometry args={[0.75, 64, 64]} />
<meshPhysicalMaterial
color={active ? 'purple' : '#e7b056'}
clearcoat={1}
clearcoatRoughness={0}
/>
<Shadow
position-y={-0.79}
rotation-x={-Math.PI / 2}
opacity={0.6}
scale={[0.8, 0.8, 1]}
/>
<directionalLight
ref={light}
castShadow
intensity={1.5}
shadow-camera-far={70}
/>
</e.mesh>
)
}
function Plane({color, uniqueName, ...props}) {
return (
<e.mesh receiveShadow castShadow {...props} uniqueName={uniqueName}>
<boxBufferGeometry />
<meshStandardMaterial color={color} />
</e.mesh>
)
}
const sheet = getProject('Playground - R3F').sheet('R3F-Canvas')
function App() {
return (
<div>
<Canvas
// @ts-ignore
shadowMap
>
<SheetProvider sheet={sheet}>
{/* @ts-ignore */}
<e.perspectiveCamera makeDefault uniqueName="Camera" />
<ambientLight intensity={0.4} />
<e.pointLight
position={[-10, -10, 5]}
intensity={2}
color="#ff20f0"
uniqueName="Light 1"
/>
<e.pointLight
position={[0, 0.5, -1]}
distance={1}
intensity={2}
color="#e4be00"
uniqueName="Light 2"
/>
<group position={[0, -0.9, -3]}>
<Plane
color="hotpink"
rotation-x={-Math.PI / 2}
position-z={2}
scale={[4, 20, 0.2]}
uniqueName="plane1"
/>
<Plane
color="#e4be00"
rotation-x={-Math.PI / 2}
position-y={1}
scale={[4.2, 0.2, 4]}
uniqueName="plane2"
/>
<Plane
color="#736fbd"
rotation-x={-Math.PI / 2}
position={[-1.7, 1, 3.5]}
scale={[0.5, 4, 4]}
uniqueName="plane3"
/>
<Plane
color="white"
rotation-x={-Math.PI / 2}
position={[0, 4.5, 3]}
scale={[2, 0.03, 4]}
uniqueName="plane4"
/>
</group>
<Button />
</SheetProvider>
</Canvas>
</div>
)
}
export default App

View file

@ -1,7 +0,0 @@
import {render, screen} from '@testing-library/react'
test('renders learn react link', () => {
render(<App />)
const linkElement = screen.getByText(/learn react/i)
expect(linkElement).toBeInTheDocument()
})

View file

@ -1,13 +0,0 @@
body {
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
code {
font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
monospace;
}

View file

@ -1,19 +0,0 @@
import ReactDOM from 'react-dom'
import './index.css'
import reportWebVitals from './reportWebVitals'
import '@theatre/studio'
import {getProject} from '@theatre/core'
import React from 'react'
import App from './App'
ReactDOM.render(
<React.StrictMode>
<App project={getProject('CRA project')} />
</React.StrictMode>,
document.getElementById('root'),
)
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals()

View file

@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 841.9 595.3"><g fill="#61DAFB"><path d="M666.3 296.5c0-32.5-40.7-63.3-103.1-82.4 14.4-63.6 8-114.2-20.2-130.4-6.5-3.8-14.1-5.6-22.4-5.6v22.3c4.6 0 8.3.9 11.4 2.6 13.6 7.8 19.5 37.5 14.9 75.7-1.1 9.4-2.9 19.3-5.1 29.4-19.6-4.8-41-8.5-63.5-10.9-13.5-18.5-27.5-35.3-41.6-50 32.6-30.3 63.2-46.9 84-46.9V78c-27.5 0-63.5 19.6-99.9 53.6-36.4-33.8-72.4-53.2-99.9-53.2v22.3c20.7 0 51.4 16.5 84 46.6-14 14.7-28 31.4-41.3 49.9-22.6 2.4-44 6.1-63.6 11-2.3-10-4-19.7-5.2-29-4.7-38.2 1.1-67.9 14.6-75.8 3-1.8 6.9-2.6 11.5-2.6V78.5c-8.4 0-16 1.8-22.6 5.6-28.1 16.2-34.4 66.7-19.9 130.1-62.2 19.2-102.7 49.9-102.7 82.3 0 32.5 40.7 63.3 103.1 82.4-14.4 63.6-8 114.2 20.2 130.4 6.5 3.8 14.1 5.6 22.5 5.6 27.5 0 63.5-19.6 99.9-53.6 36.4 33.8 72.4 53.2 99.9 53.2 8.4 0 16-1.8 22.6-5.6 28.1-16.2 34.4-66.7 19.9-130.1 62-19.1 102.5-49.9 102.5-82.3zm-130.2-66.7c-3.7 12.9-8.3 26.2-13.5 39.5-4.1-8-8.4-16-13.1-24-4.6-8-9.5-15.8-14.4-23.4 14.2 2.1 27.9 4.7 41 7.9zm-45.8 106.5c-7.8 13.5-15.8 26.3-24.1 38.2-14.9 1.3-30 2-45.2 2-15.1 0-30.2-.7-45-1.9-8.3-11.9-16.4-24.6-24.2-38-7.6-13.1-14.5-26.4-20.8-39.8 6.2-13.4 13.2-26.8 20.7-39.9 7.8-13.5 15.8-26.3 24.1-38.2 14.9-1.3 30-2 45.2-2 15.1 0 30.2.7 45 1.9 8.3 11.9 16.4 24.6 24.2 38 7.6 13.1 14.5 26.4 20.8 39.8-6.3 13.4-13.2 26.8-20.7 39.9zm32.3-13c5.4 13.4 10 26.8 13.8 39.8-13.1 3.2-26.9 5.9-41.2 8 4.9-7.7 9.8-15.6 14.4-23.7 4.6-8 8.9-16.1 13-24.1zM421.2 430c-9.3-9.6-18.6-20.3-27.8-32 9 .4 18.2.7 27.5.7 9.4 0 18.7-.2 27.8-.7-9 11.7-18.3 22.4-27.5 32zm-74.4-58.9c-14.2-2.1-27.9-4.7-41-7.9 3.7-12.9 8.3-26.2 13.5-39.5 4.1 8 8.4 16 13.1 24 4.7 8 9.5 15.8 14.4 23.4zM420.7 163c9.3 9.6 18.6 20.3 27.8 32-9-.4-18.2-.7-27.5-.7-9.4 0-18.7.2-27.8.7 9-11.7 18.3-22.4 27.5-32zm-74 58.9c-4.9 7.7-9.8 15.6-14.4 23.7-4.6 8-8.9 16-13 24-5.4-13.4-10-26.8-13.8-39.8 13.1-3.1 26.9-5.8 41.2-7.9zm-90.5 125.2c-35.4-15.1-58.3-34.9-58.3-50.6 0-15.7 22.9-35.6 58.3-50.6 8.6-3.7 18-7 27.7-10.1 5.7 19.6 13.2 40 22.5 60.9-9.2 20.8-16.6 41.1-22.2 60.6-9.9-3.1-19.3-6.5-28-10.2zM310 490c-13.6-7.8-19.5-37.5-14.9-75.7 1.1-9.4 2.9-19.3 5.1-29.4 19.6 4.8 41 8.5 63.5 10.9 13.5 18.5 27.5 35.3 41.6 50-32.6 30.3-63.2 46.9-84 46.9-4.5-.1-8.3-1-11.3-2.7zm237.2-76.2c4.7 38.2-1.1 67.9-14.6 75.8-3 1.8-6.9 2.6-11.5 2.6-20.7 0-51.4-16.5-84-46.6 14-14.7 28-31.4 41.3-49.9 22.6-2.4 44-6.1 63.6-11 2.3 10.1 4.1 19.8 5.2 29.1zm38.5-66.7c-8.6 3.7-18 7-27.7 10.1-5.7-19.6-13.2-40-22.5-60.9 9.2-20.8 16.6-41.1 22.2-60.6 9.9 3.1 19.3 6.5 28.1 10.2 35.4 15.1 58.3 34.9 58.3 50.6-.1 15.7-23 35.6-58.4 50.6zM320.8 78.4z"/><circle cx="420.9" cy="296.5" r="45.7"/><path d="M520.5 78.1z"/></g></svg>

Before

Width:  |  Height:  |  Size: 2.6 KiB

View file

@ -1 +0,0 @@
/// <reference types="react-scripts" />

View file

@ -1,13 +0,0 @@
const reportWebVitals = (onPerfEntry) => {
if (onPerfEntry && onPerfEntry instanceof Function) {
import('web-vitals').then(({getCLS, getFID, getFCP, getLCP, getTTFB}) => {
getCLS(onPerfEntry)
getFID(onPerfEntry)
getFCP(onPerfEntry)
getLCP(onPerfEntry)
getTTFB(onPerfEntry)
})
}
}
export default reportWebVitals

View file

@ -1,5 +0,0 @@
// jest-dom adds custom jest matchers for asserting on DOM nodes.
// allows you to do things like:
// expect(element).toHaveTextContent(/react/i)
// learn more: https://github.com/testing-library/jest-dom
import '@testing-library/jest-dom'

View file

@ -1,130 +0,0 @@
import {useLayoutEffect, useRef} from 'react'
const noop = () => {}
function createCursorLock(cursor) {
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 default function useDrag(target, opts) {
const optsRef = useRef(opts)
optsRef.current = opts
const modeRef = useRef('notDragging')
const stateRef = useRef({dragHappened: false, startPos: {x: 0, y: 0}})
useLayoutEffect(() => {
if (!target) return
const getDistances = (event) => {
const {startPos} = stateRef.current
return [event.screenX - startPos.x, event.screenY - startPos.y]
}
let relinquishCursorLock = noop
const dragHandler = (event) => {
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) => {
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) => {
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) => {
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,31 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.js
# testing
/coverage
# next.js
/.next/
/out/
# production
/build
# misc
.DS_Store
# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# local env files
.env.local
.env.development.local
.env.test.local
.env.production.local

View file

@ -0,0 +1 @@
This is a starter template for [Learn Next.js](https://nextjs.org/learn).

View file

@ -0,0 +1,15 @@
{
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start"
},
"dependencies": {
"@theatre/core": "^0.0.1-COMPAT.1",
"@theatre/studio": "^0.0.1-COMPAT.1",
"next": "latest",
"react": "17.0.2",
"react-dom": "17.0.2"
}
}

View file

@ -0,0 +1,23 @@
import Head from 'next/head'
// import ReactDOM from 'react-dom'
import studio from '@theatre/studio'
import {getProject} from '@theatre/core'
// import React from 'react'
// import App from './App'
studio.initialize({usePersistentStorage: false})
const project = getProject('Project')
const sheet = project.sheet('Sheet')
const obj = sheet.object('Obj', {str: 'some string', num: 0})
function App({obj}) {
console.log(obj)
return <div>hi</div>
}
export default function Home() {
return <App obj={obj}>hi</App>
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

View file

@ -0,0 +1,3 @@
/.cache
/dist
/package-lock.json

View file

@ -0,0 +1,13 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Theatre.js Example - DOM</title>
</head>
<body>
<div id="root"></div>
<script src="./src/index.js"></script>
</body>
</html>

View file

@ -0,0 +1,13 @@
{
"name": "@compat/parcel1-react18",
"scripts": {
"dev": "parcel serve ./index.html"
},
"dependencies": {
"@theatre/core": "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

@ -0,0 +1,6 @@
import React from 'react'
export default function App({obj}) {
console.log(obj)
return <div>hi</div>
}

View file

@ -0,0 +1,19 @@
// import ReactDOM from 'react-dom'
import studio from '@theatre/studio'
import {getProject} from '@theatre/core'
// import React from 'react'
// import App from './App'
studio.initialize({usePersistentStorage: false})
const project = getProject('Project')
const sheet = project.sheet('Sheet')
const obj = sheet.object('Obj', {str: 'some string', num: 0})
// ReactDOM.render(
// <React.StrictMode>
// <App obj={obj} />
// </React.StrictMode>,
// document.getElementById('root'),
// )

View file

@ -0,0 +1,4 @@
/.parcel-cache
/.cache
/dist
/package-lock.json

View file

@ -0,0 +1,13 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Theatre.js Example - DOM</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="./src/index.js"></script>
</body>
</html>

View file

@ -0,0 +1,13 @@
{
"name": "@compat/parcel2-react18",
"scripts": {
"dev": "parcel serve ./index.html"
},
"dependencies": {
"@theatre/core": "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

@ -0,0 +1,6 @@
import React from 'react'
export default function App({obj}) {
console.log(obj)
return <div>hi</div>
}

View file

@ -0,0 +1,19 @@
// import ReactDOM from 'react-dom'
import studio from '@theatre/studio'
import {getProject} from '@theatre/core'
// import React from 'react'
// import App from './App'
studio.initialize({usePersistentStorage: false})
const project = getProject('Project')
const sheet = project.sheet('Sheet')
const obj = sheet.object('Obj', {str: 'some string', num: 0})
// ReactDOM.render(
// <React.StrictMode>
// <App obj={obj} />
// </React.StrictMode>,
// document.getElementById('root'),
// )

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,23 @@
{
"name": "@compat/vite-react18",
"private": true,
"version": "0.0.0",
"scripts": {
"dev": "vite",
"build": "tsc && vite build",
"preview": "vite preview"
},
"dependencies": {
"@theatre/core": "^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,6 @@
import React from 'react'
export default function App({obj}) {
console.log(obj)
return <div>hi</div>
}

View file

@ -0,0 +1,19 @@
// import ReactDOM from 'react-dom'
import studio from '@theatre/studio'
import {getProject} from '@theatre/core'
// import React from 'react'
// import App from './App'
studio.initialize({usePersistentStorage: false})
const project = getProject('Project')
const sheet = project.sheet('Sheet')
const obj = sheet.object('Obj', {str: 'some string', num: 0})
// ReactDOM.render(
// <React.StrictMode>
// <App obj={obj} />
// </React.StrictMode>,
// document.getElementById('root'),
// )

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

@ -1,9 +1,7 @@
import * as path from 'path' import * as path from 'path'
import {build} from 'esbuild' import {build} from 'esbuild'
const definedGlobals = { const definedGlobals = {}
global: 'window',
}
function createBundles(watch: boolean) { function createBundles(watch: boolean) {
const pathToPackage = path.join(__dirname, '../') const pathToPackage = path.join(__dirname, '../')

View file

@ -1,10 +1,42 @@
type ICallback = (t: number) => void type ICallback = (t: number) => void
function createRafTicker() {
const ticker = new Ticker()
if (typeof window !== 'undefined') {
/**
* @remarks
* TODO users should also be able to define their own ticker.
*/
const onAnimationFrame = (t: number) => {
ticker.tick(t)
window.requestAnimationFrame(onAnimationFrame)
}
window.requestAnimationFrame(onAnimationFrame)
} else {
ticker.tick(0)
setTimeout(() => ticker.tick(1), 0)
console.log(
`@theatre/dataverse is running in a server rather than in a browser. We haven't gotten around to testing server-side rendering, so if something is working in the browser but not on the server, please file a bug: https://github.com/theatre-js/theatre/issues/new`,
)
}
return ticker
}
let rafTicker: undefined | Ticker
/** /**
* The Ticker class helps schedule callbacks. Scheduled callbacks are executed per tick. Ticks can be triggered by an * The Ticker class helps schedule callbacks. Scheduled callbacks are executed per tick. Ticks can be triggered by an
* external scheduling strategy, e.g. a raf. * external scheduling strategy, e.g. a raf.
*/ */
export default class Ticker { export default class Ticker {
static get raf(): Ticker {
if (!rafTicker) {
rafTicker = createRafTicker()
}
return rafTicker
}
private _scheduledForThisOrNextTick: Set<ICallback> private _scheduledForThisOrNextTick: Set<ICallback>
private _scheduledForNextTick: Set<ICallback> private _scheduledForNextTick: Set<ICallback>
private _timeAtCurrentTick: number private _timeAtCurrentTick: number

View file

@ -62,10 +62,16 @@ function createMechanism() {
function getSharedMechanism(): ReturnType<typeof createMechanism> { function getSharedMechanism(): ReturnType<typeof createMechanism> {
const varName = '__dataverse_discoveryMechanism_sharedStack' const varName = '__dataverse_discoveryMechanism_sharedStack'
if (global) { const root =
typeof window !== 'undefined'
? window
: typeof global !== 'undefined'
? global
: {}
if (root) {
const existingMechanism: ReturnType<typeof createMechanism> | undefined = const existingMechanism: ReturnType<typeof createMechanism> | undefined =
// @ts-ignore ignore // @ts-ignore ignore
global[varName] root[varName]
if ( if (
existingMechanism && existingMechanism &&
typeof existingMechanism === 'object' && typeof existingMechanism === 'object' &&
@ -75,7 +81,7 @@ function getSharedMechanism(): ReturnType<typeof createMechanism> {
} else { } else {
const mechanism = createMechanism() const mechanism = createMechanism()
// @ts-ignore ignore // @ts-ignore ignore
global[varName] = mechanism root[varName] = mechanism
return mechanism return mechanism
} }
} else { } else {

View file

@ -39,5 +39,8 @@ export default defineConfig({
*/ */
alias: [...getAliasesFromTsConfigForRollup()], alias: [...getAliasesFromTsConfigForRollup()],
}, },
define: {...definedGlobals, 'window.__IS_VISUAL_REGRESSION_TESTING': 'true'}, define: {
...definedGlobals,
'window.__IS_VISUAL_REGRESSION_TESTING': 'true',
},
}) })

View file

@ -99,7 +99,7 @@ const ReferenceWindow: VFC<ReferenceWindowProps> = ({height}) => {
const ctx = canvasRef.current!.getContext('2d')! const ctx = canvasRef.current!.getContext('2d')!
console.log(gl.domElement.getContext('webgl2')!.getContextAttributes()) // console.log(gl.domElement.getContext('webgl2')!.getContextAttributes())
// https://stackoverflow.com/questions/17861447/html5-canvas-drawimage-how-to-apply-antialiasing // https://stackoverflow.com/questions/17861447/html5-canvas-drawimage-how-to-apply-antialiasing
ctx.imageSmoothingQuality = 'high' ctx.imageSmoothingQuality = 'high'

View file

@ -1,4 +1,4 @@
import {useCallback, useEffect, useLayoutEffect, useMemo} from 'react' import {useCallback, useEffect, useLayoutEffect, useMemo, useState} from 'react'
import React from 'react' import React from 'react'
import {Canvas, useThree} from '@react-three/fiber' import {Canvas, useThree} from '@react-three/fiber'
import type {BaseSheetObjectType} from '../store' import type {BaseSheetObjectType} from '../store'
@ -6,7 +6,7 @@ import {allRegisteredObjects, useEditorStore} from '../store'
import shallow from 'zustand/shallow' import shallow from 'zustand/shallow'
import root from 'react-shadow/styled-components' import root from 'react-shadow/styled-components'
import ProxyManager from './ProxyManager' import ProxyManager from './ProxyManager'
import studio, {ToolbarIconButton} from '@theatre/studio' import studio from '@theatre/studio'
import {useVal} from '@theatre/react' import {useVal} from '@theatre/react'
import styled, {createGlobalStyle, StyleSheetManager} from 'styled-components' import styled, {createGlobalStyle, StyleSheetManager} from 'styled-components'
import type {ISheet} from '@theatre/core' import type {ISheet} from '@theatre/core'
@ -16,7 +16,6 @@ import type {$IntentionalAny} from '@theatre/shared/utils/types'
import {InfiniteGridHelper} from '../InfiniteGridHelper' import {InfiniteGridHelper} from '../InfiniteGridHelper'
import {DragDetectorProvider} from './DragDetector' import {DragDetectorProvider} from './DragDetector'
import TooltipPortalProvider from './TooltipPortalProvider' import TooltipPortalProvider from './TooltipPortalProvider'
import {FiRefreshCw} from 'react-icons/fi'
import ReferenceWindow from './ReferenceWindow/ReferenceWindow' import ReferenceWindow from './ReferenceWindow/ReferenceWindow'
const GlobalStyle = createGlobalStyle` const GlobalStyle = createGlobalStyle`
@ -168,6 +167,14 @@ const SnapshotEditor: React.FC<{paneId: string}> = (props) => {
} }
}, []) }, [])
const [toolsContainer, setToolsContainer] = useState<null | HTMLElement>()
useEffect(() => {
if (!toolsContainer) return
return studio.ui.renderToolset('snapshot-editor', toolsContainer)
}, [toolsContainer])
if (!editorObject) return <></> if (!editorObject) return <></>
return ( return (
@ -178,14 +185,7 @@ const SnapshotEditor: React.FC<{paneId: string}> = (props) => {
<TooltipPortalProvider> <TooltipPortalProvider>
<Wrapper> <Wrapper>
<Overlay> <Overlay>
<Tools> <Tools ref={setToolsContainer} />
<ToolbarIconButton
title="Refresh Snapshot"
onClick={createSnapshot}
>
<FiRefreshCw />
</ToolbarIconButton>
</Tools>
{showReferenceWindow && ( {showReferenceWindow && (
<ReferenceWindowContainer> <ReferenceWindowContainer>
<ReferenceWindow height={120} /> <ReferenceWindow height={120} />

View file

@ -1,118 +0,0 @@
import type {VFC} from 'react'
import React from 'react'
import {IoCameraOutline} from 'react-icons/io5'
import studio, {ToolbarIconButton} from '@theatre/studio'
import {useVal} from '@theatre/react'
import TransformControlsModeSelect from './TransformControlsModeSelect'
import ViewportShadingSelect from './ViewportShadingSelect'
import TransformControlsSpaceSelect from './TransformControlsSpaceSelect'
import {getEditorSheetObject} from '../editorStuff'
const Toolbar: VFC = () => {
const editorObject = getEditorSheetObject()
const transformControlsMode =
useVal(editorObject?.props.transformControls.mode) ?? 'translate'
const transformControlsSpace =
useVal(editorObject?.props.transformControls.space) ?? 'world'
const viewportShading =
useVal(editorObject?.props.viewport.shading) ?? 'rendered'
if (!editorObject) return <></>
return (
<>
<ToolbarIconButton
onClick={() => {
studio.createPane('snapshot')
}}
title="Create snapshot"
>
<IoCameraOutline />
</ToolbarIconButton>
<TransformControlsModeSelect
value={transformControlsMode}
onChange={(value) =>
studio.transaction(({set}) =>
set(editorObject!.props.transformControls.mode, value),
)
}
/>
<TransformControlsSpaceSelect
value={transformControlsSpace}
onChange={(space) => {
studio.transaction(({set}) => {
set(editorObject.props.transformControls.space, space)
})
}}
/>
<ViewportShadingSelect
value={viewportShading}
onChange={(shading) => {
studio.transaction(({set}) => {
set(editorObject.props.viewport.shading, shading)
})
}}
/>
{/* <ToolbarIconButton
label="Focus on selected"
icon={<RiFocus3Line />}
onClick={() => {
const orbitControls =
useEditorStore.getState().orbitControlsRef?.current
const selected = getSelected()
let focusObject
if (selected) {
focusObject =
useEditorStore.getState().editablesSnapshot![selected].proxyObject
}
if (orbitControls && focusObject) {
focusObject.getWorldPosition(
// @ts-ignore TODO
orbitControls.target as Vector3,
)
}
}}
/> */}
{/* <ToolbarIconButton
label="Align object to view"
icon={<GiPocketBow />}
onClick={() => {
const camera = (
useEditorStore.getState().orbitControlsRef?.current as $FixMe
)?.object
const selected = getSelected()
let proxyObject
if (selected) {
proxyObject =
useEditorStore.getState().editablesSnapshot![selected].proxyObject
if (proxyObject && camera) {
const direction = new Vector3()
const position = camera.position.clone()
camera.getWorldDirection(direction)
proxyObject.position.set(0, 0, 0)
proxyObject.lookAt(direction)
proxyObject.parent!.worldToLocal(position)
proxyObject.position.copy(position)
proxyObject.updateMatrix()
}
}
}}
/> */}
</>
)
}
export default Toolbar

View file

@ -1,41 +0,0 @@
import {ToolbarSwitchSelect} from '@theatre/studio'
import type {VFC} from 'react'
import React from 'react'
import {GiClockwiseRotation, GiMove, GiResize} from 'react-icons/gi'
import type {TransformControlsMode} from '../../store'
export interface TransformControlsModeSelectProps {
value: TransformControlsMode
onChange: (value: string) => void
}
const TransformControlsModeSelect: VFC<TransformControlsModeSelectProps> = ({
value,
onChange,
}) => {
return (
<ToolbarSwitchSelect
value={value}
onChange={onChange}
options={[
{
value: 'translate',
label: 'Tool: Translate',
icon: <GiMove />,
},
{
value: 'rotate',
label: 'Tool: Rotate',
icon: <GiClockwiseRotation />,
},
{
value: 'scale',
label: 'Tool: Scale',
icon: <GiResize />,
},
]}
/>
)
}
export default TransformControlsModeSelect

View file

@ -1,34 +0,0 @@
import type {VFC} from 'react'
import React from 'react'
import type {TransformControlsSpace} from '../../store'
import {BiCube, BiGlobe} from 'react-icons/bi'
import {ToolbarSwitchSelect} from '@theatre/studio'
export interface TransformControlsSpaceSelectProps {
value: TransformControlsSpace
onChange: (value: TransformControlsSpace) => void
}
const TransformControlsSpaceSelect: VFC<TransformControlsSpaceSelectProps> = ({
value,
onChange,
}) => (
<ToolbarSwitchSelect
value={value}
onChange={onChange}
options={[
{
value: 'world',
label: 'Space: World',
icon: <BiGlobe />,
},
{
value: 'local',
label: 'Space: Local',
icon: <BiCube />,
},
]}
/>
)
export default TransformControlsSpaceSelect

View file

@ -1,46 +0,0 @@
import type {VFC} from 'react'
import React from 'react'
import type {ViewportShading} from '../../store'
import {FaCube} from 'react-icons/fa'
import {GiCube, GiIceCube} from 'react-icons/gi'
import {BiCube} from 'react-icons/bi'
import {ToolbarSwitchSelect} from '@theatre/studio'
export interface ViewportShadingSelectProps {
value: ViewportShading
onChange: (value: ViewportShading) => void
}
const ViewportShadingSelect: VFC<ViewportShadingSelectProps> = ({
value,
onChange,
}) => (
<ToolbarSwitchSelect
value={value}
onChange={onChange}
options={[
{
value: 'wireframe',
label: 'Display: Wireframe',
icon: <BiCube />,
},
{
value: 'flat',
label: 'Display: Flat',
icon: <GiCube />,
},
{
value: 'solid',
label: 'Display: Solid',
icon: <FaCube />,
},
{
value: 'rendered',
label: 'Display: Rendered',
icon: <GiIceCube />,
},
]}
/>
)
export default ViewportShadingSelect

View file

@ -1,16 +1,150 @@
import SnapshotEditor from './components/SnapshotEditor' import SnapshotEditor from './components/SnapshotEditor'
import type {IExtension} from '@theatre/studio' import type {IExtension} from '@theatre/studio'
import Toolbar from './components/Toolbar/Toolbar' import {prism, Ticker, val} from '@theatre/dataverse'
import {getEditorSheetObject} from './components/editorStuff'
import {useEditorStore} from './store'
import ReactDOM from 'react-dom'
import React from 'react'
import type {ToolsetConfig} from '@theatre/studio'
const io5CameraOutline = `<svg xmlns="http://www.w3.org/2000/svg" class="ionicon" viewBox="0 0 512 512"><title>Camera</title><path d="M350.54 148.68l-26.62-42.06C318.31 100.08 310.62 96 302 96h-92c-8.62 0-16.31 4.08-21.92 10.62l-26.62 42.06C155.85 155.23 148.62 160 140 160H80a32 32 0 00-32 32v192a32 32 0 0032 32h352a32 32 0 0032-32V192a32 32 0 00-32-32h-59c-8.65 0-16.85-4.77-22.46-11.32z" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="32"/><circle cx="256" cy="272" r="80" fill="none" stroke="currentColor" stroke-miterlimit="10" stroke-width="32"/><path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="32" d="M124 158v-22h-24v22"/></svg>`
const gameIconMove = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><path fill="currentColor" d="M256 34.47l-90.51 90.51h67.883v108.393H124.98V165.49L34.47 256l90.51 90.51v-67.883h108.393V387.02H165.49L256 477.53l90.51-90.51h-67.883V278.627H387.02v67.883L477.53 256l-90.51-90.51v67.883H278.627V124.98h67.883L256 34.47z"/></svg>`
const gameIconClockwiseRotation = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><path fill="currentColor" d="M263.09 50c-11.882-.007-23.875 1.018-35.857 3.13C142.026 68.156 75.156 135.026 60.13 220.233 45.108 305.44 85.075 391.15 160.005 434.41c32.782 18.927 69.254 27.996 105.463 27.553 46.555-.57 92.675-16.865 129.957-48.15l-30.855-36.768c-50.95 42.75-122.968 49.05-180.566 15.797-57.597-33.254-88.152-98.777-76.603-164.274 11.55-65.497 62.672-116.62 128.17-128.168 51.656-9.108 103.323 7.98 139.17 43.862L327 192h128V64l-46.34 46.342C370.242 71.962 317.83 50.03 263.09 50z"/></svg>`
const gameIconResize = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><path fill="currentColor" d="M29 30l1 90h36V66h26V30H29zm99 0v36h72V30h-72zm108 0v36h72V30h-72zm108 0v36h72V30h-72zm102 0v78h36V30h-36zm-206 80v36h100.543l-118 118H30v218h218V289.457l118-118V272h36V110H240zm206 34v72h36v-72h-36zM30 156v72h36v-72H30zm416 96v72h36v-72h-36zm0 108v72h36v-72h-36zm-166 86v36h72v-36h-72zm108 0v36h72v-36h-72z"/></svg>`
const boxIconsGlobe = `<svg stroke="currentColor" fill="currentColor" stroke-width="0" viewBox="0 0 24 24" height="1em" width="1em" xmlns="http://www.w3.org/2000/svg"><path d="M12 2C6.486 2 2 6.486 2 12s4.486 10 10 10 10-4.486 10-10S17.514 2 12 2zm7.931 9h-2.764a14.67 14.67 0 0 0-1.792-6.243A8.013 8.013 0 0 1 19.931 11zM12.53 4.027c1.035 1.364 2.427 3.78 2.627 6.973H9.03c.139-2.596.994-5.028 2.451-6.974.172-.01.344-.026.519-.026.179 0 .354.016.53.027zm-3.842.7C7.704 6.618 7.136 8.762 7.03 11H4.069a8.013 8.013 0 0 1 4.619-6.273zM4.069 13h2.974c.136 2.379.665 4.478 1.556 6.23A8.01 8.01 0 0 1 4.069 13zm7.381 6.973C10.049 18.275 9.222 15.896 9.041 13h6.113c-.208 2.773-1.117 5.196-2.603 6.972-.182.012-.364.028-.551.028-.186 0-.367-.016-.55-.027zm4.011-.772c.955-1.794 1.538-3.901 1.691-6.201h2.778a8.005 8.005 0 0 1-4.469 6.201z"></path></svg>`
const boxIconsCube = `<svg stroke="currentColor" fill="currentColor" stroke-width="0" viewBox="0 0 24 24" height="1em" width="1em" xmlns="http://www.w3.org/2000/svg"><path d="M12 2C6.486 2 2 6.486 2 12s4.486 10 10 10 10-4.486 10-10S17.514 2 12 2zm7.931 9h-2.764a14.67 14.67 0 0 0-1.792-6.243A8.013 8.013 0 0 1 19.931 11zM12.53 4.027c1.035 1.364 2.427 3.78 2.627 6.973H9.03c.139-2.596.994-5.028 2.451-6.974.172-.01.344-.026.519-.026.179 0 .354.016.53.027zm-3.842.7C7.704 6.618 7.136 8.762 7.03 11H4.069a8.013 8.013 0 0 1 4.619-6.273zM4.069 13h2.974c.136 2.379.665 4.478 1.556 6.23A8.01 8.01 0 0 1 4.069 13zm7.381 6.973C10.049 18.275 9.222 15.896 9.041 13h6.113c-.208 2.773-1.117 5.196-2.603 6.972-.182.012-.364.028-.551.028-.186 0-.367-.016-.55-.027zm4.011-.772c.955-1.794 1.538-3.901 1.691-6.201h2.778a8.005 8.005 0 0 1-4.469 6.201z"></path></svg>`
const gameIconsCube = `<svg stroke="currentColor" fill="currentColor" stroke-width="0" viewBox="0 0 512 512" height="1em" width="1em" xmlns="http://www.w3.org/2000/svg"><path d="M256 24.585L51.47 118.989 256 213.394l204.53-94.405zM38.998 133.054v258.353L247 487.415V229.063zm434.004 0L265 229.062v258.353l208.002-96.008z"></path></svg>`
const fontAwesomeCube = `<svg stroke="currentColor" fill="currentColor" stroke-width="0" viewBox="0 0 512 512" height="1em" width="1em" xmlns="http://www.w3.org/2000/svg"><path d="M239.1 6.3l-208 78c-18.7 7-31.1 25-31.1 45v225.1c0 18.2 10.3 34.8 26.5 42.9l208 104c13.5 6.8 29.4 6.8 42.9 0l208-104c16.3-8.1 26.5-24.8 26.5-42.9V129.3c0-20-12.4-37.9-31.1-44.9l-208-78C262 2.2 250 2.2 239.1 6.3zM256 68.4l192 72v1.1l-192 78-192-78v-1.1l192-72zm32 356V275.5l160-65v133.9l-160 80z"></path></svg>`
const gameIconsIceCube = `<svg stroke="currentColor" fill="currentColor" stroke-width="0" viewBox="0 0 512 512" height="1em" width="1em" xmlns="http://www.w3.org/2000/svg"><path d="M238.406 26.844c-9.653.12-18.926 2.69-30.437 7.062l-157.282 57c-20.984 7.65-21.587 11.834-22.344 33.28L20.937 358.22c-1.207 27.514-.654 33.187 23.25 43.56L229.97 483.19c19.34 8.29 31.906 7.655 45.186 3.218l181.938-56.53c21.95-7.295 25.04-9.627 25.875-36.845l7.686-250.155c.662-17.37-5.667-24.695-18.78-29.625L271.062 34.375c-12.977-5.344-23.003-7.653-32.657-7.53zm.813 24.875c23.637-.053 45.564 8.434 87.874 24.874 95.545 37.123 131.71 53.8 69.687 77.937-74.002 28.802-128.175 45.115-172.28 25.814L113.47 131.75c-34.57-15.127-44.69-27.46 17.843-50.094 55.64-20.14 82.742-29.882 107.906-29.937zm44.718 43.75c-38.284.402-55.285 21.205-56.813 38.936-.873 10.132 2.95 19.6 12.406 26.25 9.456 6.65 25.355 10.56 48.97 5.938 35.817-7.01 61.536-15.056 77.5-22.844 7.982-3.894 13.464-7.737 16.5-10.844 3.036-3.107 3.453-4.942 3.438-6-.016-1.057-.44-2.675-3.313-5.406-2.873-2.73-8.03-6.04-15.22-9.156-14.378-6.233-36.757-11.877-65.717-15.72-6.355-.842-12.28-1.213-17.75-1.155zM59.25 134c10.372-.29 29.217 7.2 63.906 22.656 140.925 62.786 140.52 65.876 130.97 200.656-7.783 109.81-8.797 109.85-128.47 59.282-73.15-30.91-86.806-40.853-85.187-88.97l5.468-162.937c.674-20.034 1.557-30.358 13.312-30.687zm381.938 30.906c29.172-.384 29.1 28.075 26.75 105.25-4.118 135.132-9.05 140.184-120.375 173.72-70.42 21.21-81.49 25.614-78.97-12.032l11-164.156c3.217-48.034 7.588-51.508 94.813-83.907 31.323-11.633 52.534-18.686 66.78-18.874zm-20.438 40.688c-.332-.002-.674.015-1 .03-5.22.263-10.226 2.77-14.188 8.407-3.96 5.638-6.81 14.71-5.687 27.907 1.448 17.033-4.507 38.11-15.156 56.938-10.65 18.827-26.502 35.91-47.814 38.813-29.127 3.968-42.41 23.58-43.5 42.062-.545 9.24 2.108 18.03 7.688 24.594s14.088 11.335 27.187 12.03c41.146 2.185 71.336-10.766 91.595-39.155 20.26-28.39 30.396-73.76 25.875-136.595-1.876-26.076-14.708-34.977-25-35.03zm-246.25 8.844c-.644 0-1.218.063-1.72.187-2.003.494-3.685 1.53-5.655 4.813-1.913 3.186-3.688 8.618-4.406 16.343l-.064.657c-1.388 16.732-8.098 28.602-17.844 35.063-9.745 6.46-20.794 7.808-31.125 9.094-10.33 1.286-20.177 2.39-28.156 5.75-7.977 3.36-14.36 8.38-19.468 19.78-7.2 16.076-7.143 28.027-3.124 38.563 4.018 10.537 12.688 20.106 24.687 28.75 23.998 17.29 60.27 29.956 88.906 41.844 11.386 4.727 20.496 6.484 27.282 6.126 6.787-.358 11.278-2.423 15.375-6.562 8.195-8.28 14.057-27.692 15-57.344 2.024-63.623-18.84-110.284-38.656-130.875-8.668-9.008-16.52-12.193-21.03-12.188zm184.22 6.812c-.95-.003-1.927.035-2.97.094-35.464 1.99-48.477 12.867-52.5 24.062-4.023 11.196.826 27.07 10.844 39.78 11.488 14.58 20.59 15.736 30.437 12.283 9.848-3.455 20.542-14.108 27.376-26.908s9.512-27.397 7.188-36.28c-1.163-4.443-3.144-7.422-6.47-9.626-2.908-1.928-7.274-3.388-13.905-3.406z"></path></svg>`
const r3fExtension: IExtension = { const r3fExtension: IExtension = {
id: '@theatre/r3f', id: '@theatre/r3f',
globalToolbar: { toolbars: {
component: Toolbar, global(set, studio) {
const calc = prism<ToolsetConfig>(() => {
const editorObject = getEditorSheetObject()
const transformControlsMode =
val(editorObject?.props.transformControls.mode) ?? 'translate'
const transformControlsSpace =
val(editorObject?.props.transformControls.space) ?? 'world'
const viewportShading =
val(editorObject?.props.viewport.shading) ?? 'rendered'
return [
{
type: 'Icon',
title: 'Create Snapshot',
svgSource: io5CameraOutline,
onClick: () => {
studio.createPane('snapshot')
},
},
{
type: 'Switch',
value: transformControlsMode,
onChange: (value) =>
studio.transaction(({set}) =>
set(editorObject!.props.transformControls.mode, value),
),
options: [
{
value: 'translate',
label: 'Tool: Translate',
svgSource: gameIconMove,
},
{
value: 'rotate',
label: 'Tool: Rotate',
svgSource: gameIconClockwiseRotation,
},
{
value: 'scale',
label: 'Tool: Scale',
svgSource: gameIconResize,
},
],
},
{
type: 'Switch',
value: transformControlsSpace,
onChange: (space) =>
studio.transaction(({set}) => {
set(editorObject!.props.transformControls.space, space)
}),
options: [
{
value: 'world',
label: 'Space: World',
svgSource: boxIconsGlobe,
},
{
value: 'local',
label: 'Space: Local',
svgSource: boxIconsCube,
},
],
},
{
type: 'Switch',
value: viewportShading,
onChange: (shading) =>
studio.transaction(({set}) => {
set(editorObject!.props.viewport.shading, shading)
}),
options: [
{
value: 'wireframe',
label: 'Display: Wireframe',
svgSource: boxIconsCube,
},
{
value: 'flat',
label: 'Display: Flat',
svgSource: gameIconsCube,
},
{
value: 'solid',
label: 'Display: Solid',
svgSource: fontAwesomeCube,
},
{
value: 'rendered',
label: 'Display: Rendered',
svgSource: gameIconsIceCube,
},
],
},
]
})
return calc.tapImmediate(Ticker.raf, () => {
set(calc.getValue())
})
},
'snapshot-editor': (set) => {
const {createSnapshot} = useEditorStore.getState()
const onClick = createSnapshot
set([
{
type: 'Icon',
onClick,
title: 'Refresh Snapshot',
svgSource: `<svg stroke="currentColor" fill="none" stroke-width="2" viewBox="0 0 24 24" stroke-linecap="round" stroke-linejoin="round" height="1em" width="1em" xmlns="http://www.w3.org/2000/svg"><polyline points="23 4 23 10 17 10"></polyline><polyline points="1 20 1 14 7 14"></polyline><path d="M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"></path></svg>`,
},
])
return () => {}
},
}, },
panes: [ panes: [
{ {
class: 'snapshot', class: 'snapshot',
component: SnapshotEditor, mount: ({paneId, node}) => {
ReactDOM.render(React.createElement(SnapshotEditor, {paneId}), node)
function unmount() {
ReactDOM.unmountComponentAtNode(node)
}
return unmount
},
}, },
], ],
} }

View file

@ -1,15 +1,5 @@
import {Ticker} from '@theatre/dataverse' import {Ticker} from '@theatre/dataverse'
const coreTicker = new Ticker() const coreTicker = Ticker.raf
export default coreTicker export default coreTicker
/**
* @remarks
* TODO users should also be able to define their own ticker.
*/
const onAnimationFrame = (t: number) => {
coreTicker.tick(t)
window.requestAnimationFrame(onAnimationFrame)
}
window.requestAnimationFrame(onAnimationFrame)

View file

@ -308,6 +308,11 @@ async function resolveAudioBuffer(args: IAttachAudioArgs): Promise<{
// AudioContext is suspended, probably because the browser // AudioContext is suspended, probably because the browser
// has blocked it since it is not initiated by a user gesture // has blocked it since it is not initiated by a user gesture
// if in SSR, just resolve the promise, as there is not much more to be done
if (typeof window === 'undefined') {
return Promise.resolve(ctx)
}
return new Promise<AudioContext>((resolve) => { return new Promise<AudioContext>((resolve) => {
const listener = () => { const listener = () => {
ctx.resume() ctx.resume()

View file

@ -2,10 +2,12 @@ import path from 'path'
import {build} from 'esbuild' import {build} from 'esbuild'
export const definedGlobals = { export const definedGlobals = {
global: 'window',
'process.env.version': JSON.stringify( 'process.env.version': JSON.stringify(
require('../studio/package.json').version, require('../studio/package.json').version,
), ),
// json-touch-patch (an unmaintained package) reads this value. We patch it to just 'Set', becauce
// this is only used in `@theatre/studio`, which only supports evergreen browsers
'global.Set': 'Set',
} }
export function createBundles(watch: boolean) { export function createBundles(watch: boolean) {
@ -17,7 +19,10 @@ export function createBundles(watch: boolean) {
loader: {'.png': 'file', '.svg': 'dataurl'}, loader: {'.png': 'file', '.svg': 'dataurl'},
bundle: true, bundle: true,
sourcemap: true, sourcemap: true,
define: {...definedGlobals, __IS_VISUAL_REGRESSION_TESTING: 'false'}, define: {
...definedGlobals,
__IS_VISUAL_REGRESSION_TESTING: 'false',
},
watch, watch,
external: [ external: [
'@theatre/dataverse', '@theatre/dataverse',
@ -38,9 +43,9 @@ export function createBundles(watch: boolean) {
* It's probably possible to bundle our own react version and somehow share it * It's probably possible to bundle our own react version and somehow share it
* with the plugins, but that's not urgent atm. * with the plugins, but that's not urgent atm.
*/ */
'react', // 'react',
'react-dom', // 'react-dom',
'styled-components', // 'styled-components',
], ],
} }

View file

@ -26,10 +26,7 @@
"@theatre/core": "*" "@theatre/core": "*"
}, },
"dependencies": { "dependencies": {
"@theatre/dataverse": "workspace:*", "@theatre/dataverse": "workspace:*"
"react": "^17.0.2",
"react-dom": "^17.0.2",
"styled-components": "^5.3.0"
}, },
"//": "Add packages here to make them externals of studio. Add them to theatre/package.json if you want to bundle them with studio." "//": "Add packages here to make them externals of studio. Add them to theatre/package.json if you want to bundle them with studio."
} }

View file

@ -52,7 +52,7 @@ export class Studio {
this.address = {studioId: nanoid(10)} this.address = {studioId: nanoid(10)}
this.publicApi = new TheatreStudio(this) this.publicApi = new TheatreStudio(this)
if (process.env.NODE_ENV !== 'test') { if (process.env.NODE_ENV !== 'test' && typeof window !== 'undefined') {
this.ui = new UI(this) this.ui = new UI(this)
} }
@ -170,6 +170,7 @@ export class Studio {
if (drafts.ephemeral.extensions.byId[extension.id]) { if (drafts.ephemeral.extensions.byId[extension.id]) {
throw new Error(`Extension id "${extension.id}" is already defined`) throw new Error(`Extension id "${extension.id}" is already defined`)
} }
drafts.ephemeral.extensions.byId[extension.id] = extension drafts.ephemeral.extensions.byId[extension.id] = extension
const allPaneClasses = drafts.ephemeral.extensions.paneClasses const allPaneClasses = drafts.ephemeral.extensions.paneClasses

View file

@ -13,7 +13,6 @@ import {
import {getOutlineSelection} from './selectors' import {getOutlineSelection} from './selectors'
import type SheetObject from '@theatre/core/sheetObjects/SheetObject' import type SheetObject from '@theatre/core/sheetObjects/SheetObject'
import getStudio from './getStudio' import getStudio from './getStudio'
import type React from 'react'
import {debounce} from 'lodash-es' import {debounce} from 'lodash-es'
import type Sheet from '@theatre/core/sheets/Sheet' import type Sheet from '@theatre/core/sheets/Sheet'
import type {PaneInstanceId, ProjectId} from '@theatre/shared/utils/ids' import type {PaneInstanceId, ProjectId} from '@theatre/shared/utils/ids'
@ -67,21 +66,45 @@ export interface PaneClassDefinition {
* Each pane has a `class`, which is a string. * Each pane has a `class`, which is a string.
*/ */
class: string class: string
/** // /**
* A react component that renders the content of the pane. It is given // * A react component that renders the content of the pane. It is given
* a single prop, `paneId`, which is a unique identifier for the pane. // * a single prop, `paneId`, which is a unique identifier for the pane.
* // *
* If you wish to store and persist the state of the pane, // * If you wish to store and persist the state of the pane,
* simply use a sheet and an object. // * simply use a sheet and an object.
*/ // */
component: React.ComponentType<{ // component: React.ComponentType<{
/** // /**
* The unique identifier of the pane // * The unique identifier of the pane
*/ // */
paneId: string // paneId: string
}> // }>
mount: (opts: {paneId: string; node: HTMLElement}) => () => void
} }
export type ToolConfigIcon = {
type: 'Icon'
svgSource: string
title: string
onClick: () => void
}
export type ToolConfigSwitch = {
type: 'Switch'
value: string
onChange: (value: string) => void
options: {
value: string
label: string
svgSource: string
}[]
}
export type ToolConfig = ToolConfigIcon | ToolConfigSwitch
export type ToolsetConfig = Array<ToolConfig>
/** /**
* A Theatre.js Studio extension. You can define one either * A Theatre.js Studio extension. You can define one either
* in a separate package, or within your project. * in a separate package, or within your project.
@ -98,15 +121,13 @@ export interface IExtension {
* @example * @example
* TODO * TODO
*/ */
globalToolbar?: { toolbars?: {
/** [key in 'global' | string]: (
* A basic react component. set: (config: ToolsetConfig) => void,
* studio: IStudio,
* @example ) => () => void
* TODO
*/
component: React.ComponentType<{}>
} }
/** /**
* Introduces new pane types. * Introduces new pane types.
* @example * @example
@ -134,6 +155,8 @@ export interface IStudioUI {
* Makes the studio visible again. * Makes the studio visible again.
*/ */
restore(): void restore(): void
renderToolset(toolsetId: string, htmlNode: HTMLElement): () => void
} }
export interface _StudioInitializeOpts { export interface _StudioInitializeOpts {
@ -359,6 +382,10 @@ export default class TheatreStudio implements IStudio {
restore() { restore() {
getStudio().ui.restore() getStudio().ui.restore()
}, },
renderToolset(toolsetId: string, htmlNode: HTMLElement) {
return getStudio().ui.renderToolset(toolsetId, htmlNode)
},
} }
private readonly _cache = new SimpleCache() private readonly _cache = new SimpleCache()

View file

@ -4,6 +4,9 @@ import React from 'react'
import ReactDOM from 'react-dom' import ReactDOM from 'react-dom'
import type {Studio} from './Studio' import type {Studio} from './Studio'
import {val} from '@theatre/dataverse' import {val} from '@theatre/dataverse'
import {getMounter} from './utils/renderInPortalInContext'
import {Toolbar} from './toolbars/GlobalToolbar/GlobalToolbar'
import {withStyledShadow} from './css'
export default class UI { export default class UI {
readonly containerEl = document.createElement('div') readonly containerEl = document.createElement('div')
@ -86,4 +89,12 @@ export default class UI {
val(this.studio.atomP.ahistoric.visibilityState) === 'everythingIsHidden' val(this.studio.atomP.ahistoric.visibilityState) === 'everythingIsHidden'
) )
} }
renderToolset(toolsetId: string, htmlNode: HTMLElement) {
const s = getMounter()
s.mountOrRender(withStyledShadow(Toolbar), {toolbarId: toolsetId}, htmlNode)
return s.unmount
}
} }

View file

@ -2,9 +2,8 @@ import getStudio from '@theatre/studio/getStudio'
import {usePrism, useVal} from '@theatre/react' import {usePrism, useVal} from '@theatre/react'
import {val} from '@theatre/dataverse' import {val} from '@theatre/dataverse'
import React, {useEffect} from 'react' import React, {useEffect} from 'react'
import styled, {createGlobalStyle, StyleSheetManager} from 'styled-components' import styled, {createGlobalStyle} from 'styled-components'
import PanelsRoot from './PanelsRoot' import PanelsRoot from './PanelsRoot'
import ProvideTheme from './ProvideTheme'
import GlobalToolbar from '@theatre/studio/toolbars/GlobalToolbar/GlobalToolbar' import GlobalToolbar from '@theatre/studio/toolbars/GlobalToolbar/GlobalToolbar'
import useRefAndState from '@theatre/studio/utils/useRefAndState' import useRefAndState from '@theatre/studio/utils/useRefAndState'
import {PortalContext} from 'reakit' import {PortalContext} from 'reakit'
@ -13,25 +12,17 @@ import useKeyboardShortcuts from './useKeyboardShortcuts'
import PointerEventsHandler from '@theatre/studio/uiComponents/PointerEventsHandler' import PointerEventsHandler from '@theatre/studio/uiComponents/PointerEventsHandler'
import TooltipContext from '@theatre/studio/uiComponents/Popover/TooltipContext' import TooltipContext from '@theatre/studio/uiComponents/Popover/TooltipContext'
import {ProvidePointerCapturing} from './PointerCapturing' import {ProvidePointerCapturing} from './PointerCapturing'
import {MountAll} from '@theatre/studio/utils/renderInPortalInContext'
import {PortalLayer, ProvideStyles} from '@theatre/studio/css'
const GlobalStyle = createGlobalStyle` const MakeRootHostContainStatic =
typeof window !== 'undefined'
? createGlobalStyle`
:host { :host {
all: initial;
contain: strict; contain: strict;
color: white;
font: 11px -apple-system, BlinkMacSystemFont, Segoe WPC, Segoe Editor,
HelveticaNeue-Light, Ubuntu, Droid Sans, sans-serif;
}
* {
padding: 0;
margin: 0;
font-size: 100%;
font: inherit;
vertical-align: baseline;
list-style: none;
} }
` `
: ({} as ReturnType<typeof createGlobalStyle>)
const Container = styled(PointerEventsHandler)` const Container = styled(PointerEventsHandler)`
z-index: 50; z-index: 50;
@ -48,24 +39,11 @@ const Container = styled(PointerEventsHandler)`
} }
` `
const PortalLayer = styled.div`
z-index: 51;
position: fixed;
top: 0px;
right: 0px;
bottom: 0px;
left: 0px;
pointer-events: none;
`
export default function UIRoot() { export default function UIRoot() {
const studio = getStudio() const studio = getStudio()
const [portalLayerRef, portalLayer] = useRefAndState<HTMLDivElement>( const [portalLayerRef, portalLayer] = useRefAndState<HTMLDivElement>(
undefined as $IntentionalAny, undefined as $IntentionalAny,
) )
const [containerRef, container] = useRefAndState<HTMLDivElement>(
undefined as $IntentionalAny,
)
useKeyboardShortcuts() useKeyboardShortcuts()
@ -85,37 +63,39 @@ export default function UIRoot() {
const initialised = val(studio.atomP.ephemeral.initialised) const initialised = val(studio.atomP.ephemeral.initialised)
return !initialised ? null : ( return !initialised ? null : (
<StyleSheetManager <TooltipContext>
disableVendorPrefixes <ProvidePointerCapturing>
target={ <MountExtensionComponents />
window.__IS_VISUAL_REGRESSION_TESTING === true <PortalContext.Provider value={portalLayer}>
? undefined <ProvideStyles
: getStudio()!.ui.containerShadow target={
} window.__IS_VISUAL_REGRESSION_TESTING === true
> ? undefined
<> : getStudio()!.ui.containerShadow
<GlobalStyle /> }
<ProvidePointerCapturing> >
<ProvideTheme> <>
<PortalContext.Provider value={portalLayer}> <MakeRootHostContainStatic />
<TooltipContext> <Container
<Container className={
className={ visiblityState === 'everythingIsHidden' ? 'invisible' : ''
visiblityState === 'everythingIsHidden' ? 'invisible' : '' }
} >
> <PortalLayer ref={portalLayerRef} />
<PortalLayer ref={portalLayerRef} /> {<GlobalToolbar />}
{<GlobalToolbar />} {<PanelsRoot />}
{<PanelsRoot />} </Container>
</Container> </>
</TooltipContext> </ProvideStyles>
</PortalContext.Provider> </PortalContext.Provider>
</ProvideTheme> </ProvidePointerCapturing>
</ProvidePointerCapturing> </TooltipContext>
</>
</StyleSheetManager>
) )
}, [studio, portalLayerRef, portalLayer]) }, [studio, portalLayerRef, portalLayer])
return inside return inside
} }
const MountExtensionComponents: React.FC<{}> = () => {
return <MountAll />
}

View file

@ -1,45 +0,0 @@
import {lighten} from 'polished'
import {css} from 'styled-components'
/**
* This CSS string is used to correctly set pointer-events on an element
* when the pointer is dragging something.
* Naming explanation: "NormalMode" as opposed to dragging mode.
*
* @see PointerEventsHandler - the place that sets `.normal` on #pointer-root
*/
export const pointerEventsAutoInNormalMode = css`
#pointer-root & {
pointer-events: none;
}
#pointer-root.normal & {
pointer-events: auto;
}
`
export const theme = {
panel: {
bg: `#282b2f`,
head: {
title: {
color: `#bbb`,
},
punctuation: {
color: `#808080`,
},
},
body: {
compoudThing: {
label: {
get color(): string {
return lighten(0.6, theme.panel.bg)
},
},
},
},
},
}
export const panelUtils = {
panelBorder: `2px solid #1f1f1f`,
}

146
theatre/studio/src/css.tsx Normal file
View file

@ -0,0 +1,146 @@
import {lighten} from 'polished'
import {css} from 'styled-components'
import styled, {createGlobalStyle, StyleSheetManager} from 'styled-components'
import React, {useLayoutEffect, useState} from 'react'
import ReactDOM from 'react-dom'
import type {$IntentionalAny} from '@theatre/shared/utils/types'
import {PortalContext} from 'reakit'
import useRefAndState from './utils/useRefAndState'
/**
* This CSS string is used to correctly set pointer-events on an element
* when the pointer is dragging something.
* Naming explanation: "NormalMode" as opposed to dragging mode.
*
* @see PointerEventsHandler - the place that sets `.normal` on #pointer-root
*/
export const pointerEventsAutoInNormalMode = css`
#pointer-root & {
pointer-events: none;
}
#pointer-root.normal & {
pointer-events: auto;
}
`
export const theme = {
panel: {
bg: `#282b2f`,
head: {
title: {
color: `#bbb`,
},
punctuation: {
color: `#808080`,
},
},
body: {
compoudThing: {
label: {
get color(): string {
return lighten(0.6, theme.panel.bg)
},
},
},
},
},
}
export const panelUtils = {
panelBorder: `2px solid #1f1f1f`,
}
const GlobalStyle =
typeof window !== 'undefined'
? createGlobalStyle`
:host {
all: initial;
color: white;
font: 11px -apple-system, BlinkMacSystemFont, Segoe WPC, Segoe Editor,
HelveticaNeue-Light, Ubuntu, Droid Sans, sans-serif;
}
* {
padding: 0;
margin: 0;
font-size: 100%;
font: inherit;
vertical-align: baseline;
list-style: none;
}
`
: ({} as ReturnType<typeof createGlobalStyle>)
export const PortalLayer = styled.div`
z-index: 51;
position: fixed;
top: 0px;
right: 0px;
bottom: 0px;
left: 0px;
pointer-events: none;
`
export const ProvideStyles: React.FC<{target: undefined | HTMLElement}> = (
props,
) => {
return (
<StyleSheetManager disableVendorPrefixes target={props.target}>
<>
<GlobalStyle />
{props.children}
</>
</StyleSheetManager>
)
}
export function withStyledShadow<Props>(
Comp: React.ComponentType<Props>,
): React.ComponentType<Props> {
return (props) => (
<ProvideStyledShadow>
<Comp {...props} />
</ProvideStyledShadow>
)
}
const ProvideStyledShadow: React.FC<{}> = (props) => {
const [template, ref] = useState<null | HTMLTemplateElement>(null)
const [shadowRoot, setShadowRoot] = useState<null | ShadowRoot>(null)
useLayoutEffect(() => {
if (!template) return
const shadowRoot = (template.parentNode as HTMLElement).attachShadow({
mode: 'open',
})
setShadowRoot(shadowRoot)
return () => {
template.parentNode?.removeChild(shadowRoot)
}
}, [template])
const [portalLayerRef, portalLayer] = useRefAndState<HTMLDivElement>(
undefined as $IntentionalAny,
)
if (!shadowRoot) {
return (
<template ref={ref} shadow-root={'open'}>
{props.children}
</template>
)
}
return ReactDOM.createPortal(
<ProvideStyles target={shadowRoot as $IntentionalAny as HTMLElement}>
<>
<PortalLayer ref={portalLayerRef} />
<PortalContext.Provider value={portalLayer}>
{props.children}
</PortalContext.Provider>
</>
</ProvideStyles>,
shadowRoot as $IntentionalAny as HTMLElement,
)
}

View file

@ -69,9 +69,10 @@ function registerStudioBundle() {
} }
} }
export {default as ToolbarSwitchSelect} from './uiComponents/toolbar/ToolbarSwitchSelect' // export {default as ToolbarSwitchSelect} from './uiComponents/toolbar/ToolbarSwitchSelect'
export {default as ToolbarIconButton} from './uiComponents/toolbar/ToolbarIconButton' // export {default as ToolbarIconButton} from './uiComponents/toolbar/ToolbarIconButton'
export {default as ToolbarDropdownSelect} from './uiComponents/toolbar/ToolbarDropdownSelect' export {default as ToolbarDropdownSelect} from './uiComponents/toolbar/ToolbarDropdownSelect'
export type {IScrub} from '@theatre/studio/Scrub' export type {IScrub} from '@theatre/studio/Scrub'
export type { export type {
IStudio, IStudio,
@ -80,4 +81,8 @@ export type {
PaneClassDefinition, PaneClassDefinition,
IStudioUI, IStudioUI,
_StudioInitializeOpts, _StudioInitializeOpts,
ToolsetConfig,
ToolConfig,
ToolConfigIcon,
ToolConfigSwitch,
} from '@theatre/studio/TheatreStudio' } from '@theatre/studio/TheatreStudio'

View file

@ -1,7 +1,7 @@
import type {$FixMe} from '@theatre/shared/utils/types' import type {$FixMe} from '@theatre/shared/utils/types'
import type {PanelPosition} from '@theatre/studio/store/types' import type {PanelPosition} from '@theatre/studio/store/types'
import type {PaneInstance} from '@theatre/studio/TheatreStudio' import type {PaneInstance} from '@theatre/studio/TheatreStudio'
import React, {useCallback} from 'react' import React, {useCallback, useLayoutEffect, useState} from 'react'
import styled from 'styled-components' import styled from 'styled-components'
import {F2 as F2Impl, TitleBar} from './common' import {F2 as F2Impl, TitleBar} from './common'
import BasePanel from './BasePanel' import BasePanel from './BasePanel'
@ -136,7 +136,21 @@ const ErrorFallback: React.FC<{error: Error}> = (props) => {
const Content: React.FC<{paneInstance: PaneInstance<$FixMe>}> = ({ const Content: React.FC<{paneInstance: PaneInstance<$FixMe>}> = ({
paneInstance, paneInstance,
}) => { }) => {
const Comp = paneInstance.definition.component const [mountingPoint, setMountingPoint] = useState<HTMLElement | null>(null)
const mount = paneInstance.definition.mount
useLayoutEffect(() => {
if (!mountingPoint) return
const unmount = mount({
paneId: paneInstance.instanceId,
node: mountingPoint!,
})
if (typeof unmount === 'function') {
return unmount
}
}, [mountingPoint, mount, paneInstance.instanceId])
const closePane = useCallback(() => { const closePane = useCallback(() => {
getStudio().paneManager.destroyPane( getStudio().paneManager.destroyPane(
paneInstance.instanceId as PaneInstanceId, paneInstance.instanceId as PaneInstanceId,
@ -155,11 +169,9 @@ const Content: React.FC<{paneInstance: PaneInstance<$FixMe>}> = ({
<Title>{paneInstance.instanceId}</Title> <Title>{paneInstance.instanceId}</Title>
</TitleBar> </TitleBar>
</PanelDragZone> </PanelDragZone>
<F2> <ErrorBoundary FallbackComponent={ErrorFallback}>
<ErrorBoundary FallbackComponent={ErrorFallback}> <F2 ref={setMountingPoint} />
<Comp paneId={paneInstance.instanceId} /> </ErrorBoundary>
</ErrorBoundary>
</F2>
</Container> </Container>
) )
} }

View file

@ -1,14 +1,5 @@
import {Ticker} from '@theatre/dataverse' import {Ticker} from '@theatre/dataverse'
const studioTicker = new Ticker() const studioTicker = Ticker.raf
export default studioTicker export default studioTicker
/**
* TODO users should also be able to define their own ticker.
*/
const onAnimationFrame = (t: number) => {
studioTicker.tick(t)
window.requestAnimationFrame(onAnimationFrame)
}
window.requestAnimationFrame(onAnimationFrame)

View file

@ -1,9 +1,13 @@
import {Box} from '@theatre/dataverse'
import {useVal} from '@theatre/react' import {useVal} from '@theatre/react'
import type {IExtension} from '@theatre/studio'
import {pointerEventsAutoInNormalMode} from '@theatre/studio/css' import {pointerEventsAutoInNormalMode} from '@theatre/studio/css'
import getStudio from '@theatre/studio/getStudio' import getStudio from '@theatre/studio/getStudio'
import {panelZIndexes} from '@theatre/studio/panels/BasePanel/common' import {panelZIndexes} from '@theatre/studio/panels/BasePanel/common'
import React from 'react' import type {ToolsetConfig} from '@theatre/studio/TheatreStudio'
import React, {useLayoutEffect, useMemo} from 'react'
import styled from 'styled-components' import styled from 'styled-components'
import Toolset from './Toolset'
const Container = styled.div` const Container = styled.div`
position: fixed; position: fixed;
@ -36,28 +40,54 @@ const Bg = styled.div`
} }
` `
const ExtensionToolsetRender: React.FC<{
extension: IExtension
toolbarId: string
}> = ({extension, toolbarId}) => {
const toolsetConfigBox = useMemo(() => new Box<ToolsetConfig>([]), [])
useLayoutEffect(() => {
const detach = extension.toolbars?.[toolbarId]?.(
toolsetConfigBox.set.bind(toolsetConfigBox),
getStudio()!.publicApi,
)
if (typeof detach === 'function') return detach
}, [extension, toolbarId])
const config = useVal(toolsetConfigBox.derivation)
return <Toolset config={config} />
}
const GlobalToolbar: React.FC<{}> = (props) => { const GlobalToolbar: React.FC<{}> = (props) => {
const groups: Array<React.ReactNode> = []
const extensionsById = useVal(getStudio().atomP.ephemeral.extensions.byId)
for (const [, extension] of Object.entries(extensionsById)) {
if (!extension) continue
if (extension.globalToolbar) {
groups.push(
<extension.globalToolbar.component
key={'extensionToolbar-' + extension.id}
/>,
)
}
}
if (groups.length === 0) return null
return ( return (
<Container> <Container>
<Bg>{groups}</Bg> <Bg>
<Toolbar toolbarId="global" />
</Bg>
</Container> </Container>
) )
} }
export const Toolbar: React.FC<{toolbarId: string}> = ({toolbarId}) => {
const groups: Array<React.ReactNode> = []
const extensionsById = useVal(getStudio().atomP.ephemeral.extensions.byId)
for (const [, extension] of Object.entries(extensionsById)) {
if (!extension || !extension.toolbars?.[toolbarId]) continue
groups.push(
<ExtensionToolsetRender
extension={extension}
key={'extensionToolbar-' + extension.id}
toolbarId={toolbarId}
/>,
)
}
if (groups.length === 0) return null
return <>{groups}</>
}
export default GlobalToolbar export default GlobalToolbar

View file

@ -0,0 +1,53 @@
import didYouMean from '@theatre/shared/utils/didYouMean'
import type {$IntentionalAny} from '@theatre/shared/utils/types'
import userReadableTypeOfValue from '@theatre/shared/utils/userReadableTypeOfValue'
import type {ToolConfig, ToolsetConfig} from '@theatre/studio/TheatreStudio'
import React from 'react'
import IconButton from './tools/IconButton'
import Switch from './tools/Switch'
const Toolset: React.FC<{
config: ToolsetConfig
}> = (props) => {
return (
<>
{props.config.map((toolConfig, i) => {
return <Tool config={toolConfig} key={i} />
})}
</>
)
}
const toolByType: {
[Key in ToolConfig['type']]: React.FC<{
config: Extract<ToolConfig, {type: Key}>
}>
} = {
Icon: IconButton,
Switch: Switch,
}
function getToolByType<Type extends ToolConfig['type']>(
type: Type,
): React.FC<{config: Extract<ToolConfig, {type: Type}>}> {
return toolByType[type] as $IntentionalAny
}
const Tool: React.FC<{config: ToolConfig}> = ({config}) => {
const Comp = getToolByType(config.type)
if (!Comp) {
throw new Error(
`No tool with tool.type ${userReadableTypeOfValue(
config.type,
)} exists. Did you mean ${didYouMean(
config.type,
Object.keys(toolByType),
)}`,
)
}
return <Comp config={config} />
}
export default Toolset

View file

@ -0,0 +1,28 @@
import React from 'react'
import ToolbarIconButton from '@theatre/studio/uiComponents/toolbar/ToolbarIconButton'
import styled from 'styled-components'
import {pointerEventsAutoInNormalMode} from '@theatre/studio/css'
import type {ToolConfigIcon} from '@theatre/studio/TheatreStudio'
const Container = styled(ToolbarIconButton)`
${pointerEventsAutoInNormalMode};
& > svg {
width: 1em;
height: 1em;
pointer-events: none;
}
`
const IconButton: React.FC<{
config: ToolConfigIcon
}> = ({config}) => {
return (
<Container
onClick={config.onClick}
title={config.title}
dangerouslySetInnerHTML={{__html: config['svgSource'] ?? ''}}
/>
)
}
export default IconButton

View file

@ -0,0 +1,32 @@
import React from 'react'
import styled from 'styled-components'
import {pointerEventsAutoInNormalMode} from '@theatre/studio/css'
import type {ToolConfigSwitch} from '@theatre/studio/TheatreStudio'
import ToolbarSwitchSelect from '@theatre/studio/uiComponents/toolbar/ToolbarSwitchSelect'
const IconContainer = styled.div`
${pointerEventsAutoInNormalMode};
& > svg {
width: 1em;
height: 1em;
pointer-events: none;
}
`
const IconButton: React.FC<{
config: ToolConfigSwitch
}> = ({config}) => {
return (
<ToolbarSwitchSelect
onChange={config.onChange}
options={config.options.map(({label, value, svgSource}) => ({
label,
value,
icon: <IconContainer dangerouslySetInnerHTML={{__html: svgSource}} />,
}))}
value={config.value}
/>
)
}
export default IconButton

View file

@ -1,3 +1,3 @@
export const isSafari = /^((?!chrome|android).)*safari/i.test( export const isSafari =
navigator.userAgent, typeof window !== 'undefined' &&
) /^((?!chrome|android).)*safari/i.test(navigator.userAgent)

View file

@ -0,0 +1,58 @@
import type {$IntentionalAny} from '@theatre/shared/utils/types'
import type React from 'react'
import {getMounter} from './renderInPortalInContext'
export function registerContextualWebComponent<Props>(
ReactComponent: React.ComponentType<Props>,
componentName: string,
// currently only supporting string prop types
propKeys: {[propKey in keyof Props]: 'string'},
): void {
if (typeof window === 'undefined' || typeof customElements === 'undefined')
return
const propList = Object.keys(propKeys)
class CustomWebComponent extends HTMLElement {
_mounted = false
_mountOrRender: ReturnType<typeof getMounter>['mountOrRender']
_unmount: ReturnType<typeof getMounter>['unmount']
static get observedAttributes() {
return propList
}
constructor() {
super()
const {mountOrRender, unmount} = getMounter()
this._mountOrRender = mountOrRender
this._unmount = unmount
}
connectedCallback() {
// const shadow = this.attachShadow({mode: 'open'})
this._mounted = true
this._render()
}
_render() {
const props = Object.fromEntries(
propList.map((propName) => [
propName,
this.getAttribute(propName as $IntentionalAny),
]),
)
this._mountOrRender(ReactComponent, props as $IntentionalAny, this)
}
attributeChangedCallback() {
if (!this._mounted) return
this._render()
}
disconnectedCallback() {
this._mounted = false
this._unmount()
}
}
customElements.define(componentName, CustomWebComponent)
}

View file

@ -1,2 +1,3 @@
export const isMac = export const isMac =
navigator && navigator.platform.toUpperCase().indexOf('MAC') >= 0 typeof navigator !== 'undefined' &&
navigator.platform.toUpperCase().indexOf('MAC') >= 0

View file

@ -0,0 +1,66 @@
import {Atom} from '@theatre/dataverse'
import {useVal} from '@theatre/react'
import type {$FixMe, $IntentionalAny} from '@theatre/shared/utils/types'
import React from 'react'
import {createPortal} from 'react-dom'
type ElToRenderInContext = {
comp: React.ComponentType<$IntentionalAny>
props: {}
portalNode: HTMLElement | SVGElement
}
const theAtom = new Atom<{
set: Record<number, true>
byId: Record<number, ElToRenderInContext>
}>({
set: {},
byId: {},
})
let lastId = 1
export const getMounter = () => {
const id = lastId++
function mountOrRender<Props>(
comp: React.ComponentType<Props>,
props: Props,
portalNode: HTMLElement,
) {
theAtom.reduceState([], (s) => {
return {
byId: {...s.byId, [id]: {comp, props, portalNode}},
set: {...s.set, [id]: true},
}
})
}
function unmount() {
theAtom.reduceState([], (s) => {
const set = {...s.set}
const byId = {...s.byId}
delete set[id]
return {byId, set}
})
}
return {mountOrRender, unmount}
}
export const MountAll = () => {
const ids = Object.keys(useVal(theAtom.pointer.set))
return (
<>
{ids.map((id) => (
<Mount key={'id-' + id} id={id} />
))}
</>
)
}
const Mount = ({id}: {id: number}) => {
const {comp, portalNode, props} = useVal(theAtom.pointer.byId[id])
const Comp = comp as $FixMe
return createPortal(<Comp {...props} />, portalNode)
}

View file

@ -6663,9 +6663,6 @@ __metadata:
resolution: "@theatre/studio@workspace:theatre/studio" resolution: "@theatre/studio@workspace:theatre/studio"
dependencies: dependencies:
"@theatre/dataverse": "workspace:*" "@theatre/dataverse": "workspace:*"
react: ^17.0.2
react-dom: ^17.0.2
styled-components: ^5.3.0
peerDependencies: peerDependencies:
"@theatre/core": "*" "@theatre/core": "*"
languageName: unknown languageName: unknown