Skip to content

Commit

Permalink
remove dataLayer from sdk context
Browse files Browse the repository at this point in the history
  • Loading branch information
gonpombo8 committed Jun 19, 2023
1 parent c5d9062 commit 5577f45
Show file tree
Hide file tree
Showing 10 changed files with 68 additions and 57 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import { RxCross2 } from 'react-icons/rx'
import { IoIosImage } from 'react-icons/io'

import FileInput from '../FileInput'
import { withSdk } from '../../hoc/withSdk'
import { Container } from '../Container'
import { TextField } from '../EntityInspector/TextField'
import { Block } from '../Block'
Expand All @@ -16,6 +15,8 @@ import { GLTFValidation } from '@babylonjs/loaders'
import './ImportAsset.css'
import classNames from 'classnames'
import { withAssetDir } from '../../lib/data-layer/host/fs-utils'
import { getDataLayer } from '../../redux/data-layer'
import { useAppSelector } from '../../redux/hooks'

const ONE_MB_IN_BYTES = 1_048_576
const ONE_GB_IN_BYTES = ONE_MB_IN_BYTES * 1024
Expand Down Expand Up @@ -59,8 +60,10 @@ async function validateGltf(data: ArrayBuffer): Promise<ValidationError> {
}
}

const ImportAsset = withSdk<PropTypes>(({ sdk, onSave }) => {
const ImportAsset: React.FC<PropTypes> = ({ onSave }) => {
// TODO: multiple files
const dataLayer = useAppSelector(getDataLayer)

const [file, setFile] = useState<File>()
const [validationError, setValidationError] = useState<ValidationError>(null)
const [assetName, setAssetName] = useState<string>('')
Expand Down Expand Up @@ -100,9 +103,9 @@ const ImportAsset = withSdk<PropTypes>(({ sdk, onSave }) => {
const content: Map<string, Uint8Array> = new Map()
content.set(assetName + '.' + assetExtension, new Uint8Array(binary))

const basePath = withAssetDir((await sdk!.dataLayer.getProjectData({})).path)
const basePath = withAssetDir((await dataLayer!.getProjectData({})).path)

await sdk!.dataLayer.importAsset({
await dataLayer?.importAsset({
content,
basePath,
assetPackageName: ''
Expand Down Expand Up @@ -165,6 +168,6 @@ const ImportAsset = withSdk<PropTypes>(({ sdk, onSave }) => {
</FileInput>
</div>
)
})
}

export default ImportAsset
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ import { AssetNode, AssetNodeFolder } from './types'
import { getFullNodePath } from './utils'
import Search from '../Search'
import { withAssetDir } from '../../lib/data-layer/host/fs-utils'
import { getDataLayer } from '../../redux/data-layer'
import { useAppSelector } from '../../redux/hooks'

function noop() {}

Expand All @@ -36,6 +38,8 @@ const FilesTree = Tree<string>()

function ProjectView({ folders }: Props) {
const sdk = useSdk()
const dataLayer = useAppSelector(getDataLayer)

const [open, setOpen] = useState(new Set<string>())
const [modal, setModal] = useState<ModalState | undefined>(undefined)
const [lastSelected, setLastSelected] = useState<string>()
Expand Down Expand Up @@ -146,12 +150,11 @@ function ProjectView({ folders }: Props) {

const removeAsset = useCallback(
async (path: string, _: Entity[] = []) => {
if (!sdk) return
const { dataLayer } = sdk
if (!dataLayer) return
await dataLayer.removeAsset({ path })
fileSystemEvent.emit('change')
},
[sdk]
[dataLayer]
)

const handleConfirm = useCallback(async () => {
Expand Down Expand Up @@ -249,7 +252,7 @@ function ProjectView({ folders }: Props) {
<Tile
valueId={lastSelected}
value={selectedTreeNode}
getDragContext= {handleDragContext}
getDragContext={handleDragContext}
onSelect={handleClickFolder(selectedTreeNode.name)}
onRemove={handleRemove}
dndType={DRAG_N_DROP_ASSET_KEY}
Expand All @@ -264,15 +267,18 @@ function ProjectView({ folders }: Props) {
function NodeIcon({ value }: { value?: TreeNode }) {
if (!value) return null
if (value.type === 'folder') {
return <div style={{ marginRight: '4px', marginLeft: '2px', marginTop: '2px' }}><FolderIcon /></div>
}
else
return (
<>
<svg style={{ width: '4px', height: '4px' }} />
<IoIosImage style={{ marginRight: '4px'}} />
</>
)
return (
<div style={{ marginRight: '4px', marginLeft: '2px', marginTop: '2px' }}>
<FolderIcon />
</div>
)
} else
return (
<>
<svg style={{ width: '4px', height: '4px' }} />
<IoIosImage style={{ marginRight: '4px' }} />
</>
)
}

export default React.memo(ProjectView)
8 changes: 6 additions & 2 deletions packages/@dcl/inspector/src/components/Renderer/Renderer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@ import { Vector3 } from '@babylonjs/core'
import { Loader } from 'decentraland-ui/dist/components/Loader/Loader'
import { Dimmer } from 'decentraland-ui/dist/components/Dimmer/Dimmer'

import { withAssetDir } from '../../lib/data-layer/host/fs-utils'
import { useAppSelector } from '../../redux/hooks'
import { getDataLayer } from '../../redux/data-layer'
import { BuilderAsset, DROP_TYPES, IDrop, ProjectAssetDrop, isDropType } from '../../lib/sdk/drag-drop'
import { useRenderer } from '../../hooks/sdk/useRenderer'
import { useSdk } from '../../hooks/sdk/useSdk'
Expand All @@ -20,14 +23,15 @@ import { Warnings } from '../Warnings'
import { CameraSpeed } from './CameraSpeed'

import './Renderer.css'
import { withAssetDir } from '../../lib/data-layer/host/fs-utils'

const fixedNumber = (val: number) => Math.round(val * 1e2) / 1e2

const Renderer: React.FC = () => {
const canvasRef = React.useRef<HTMLCanvasElement>(null)
useRenderer(() => canvasRef)
const sdk = useSdk()
const dataLayer = useAppSelector(getDataLayer)

const [isLoading, setIsLoading] = useState(false)
const isMounted = useIsMounted()
const [files, init] = useFileSystem()
Expand Down Expand Up @@ -84,7 +88,7 @@ const Renderer: React.FC = () => {
})
)

await sdk!.dataLayer.importAsset({
await dataLayer?.importAsset({
content: new Map(Object.entries(fileContent)),
basePath: withAssetDir(destFolder),
assetPackageName
Expand Down
14 changes: 9 additions & 5 deletions packages/@dcl/inspector/src/components/Toolbar/Toolbar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,13 @@ import { withSdk } from '../../hoc/withSdk'
import { Gizmos } from './Gizmos'
import { Camera } from './Camera'
import { ToolbarButton } from './ToolbarButton'

import './Toolbar.css'
import { getDataLayer } from '../../redux/data-layer'
import { useAppSelector } from '../../redux/hooks'
import { DataLayerRpcClient } from '../../lib/data-layer/types'

const Toolbar = withSdk(({ sdk }) => {
const dataLayer = useAppSelector(getDataLayer)
const [save, isDirty] = useSave()
const handleInspector = useCallback(() => {
const { debugLayer } = sdk.scene
Expand All @@ -23,25 +26,26 @@ const Toolbar = withSdk(({ sdk }) => {
}, [])

const handleUndoRedo = useCallback(
(fn: typeof sdk.dataLayer.undo) => async () => {
(fn?: DataLayerRpcClient['undo']) => async () => {
if (!fn) return
const { type } = await fn({})
if (type === 'file') {
fileSystemEvent.emit('change')
}
saveEvent.emit('change', true)
},
[sdk.dataLayer]
[dataLayer]
)

return (
<div className="Toolbar">
<ToolbarButton className="save" onClick={save}>
{isDirty ? <BiSave /> : <BiBadgeCheck />}
</ToolbarButton>
<ToolbarButton className="undo" onClick={handleUndoRedo(sdk?.dataLayer.undo)}>
<ToolbarButton className="undo" onClick={handleUndoRedo(dataLayer?.undo)}>
<BiUndo />
</ToolbarButton>
<ToolbarButton className="redo" onClick={handleUndoRedo(sdk?.dataLayer.redo)}>
<ToolbarButton className="redo" onClick={handleUndoRedo(dataLayer?.redo)}>
<BiRedo />
</ToolbarButton>
<Gizmos />
Expand Down
22 changes: 12 additions & 10 deletions packages/@dcl/inspector/src/hooks/catalog/useFileSystem.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import mitt from 'mitt'
import { useState } from 'react'
import { useCallback, useState } from 'react'

import { useSdk } from '../sdk/useSdk'
import { AssetCatalogResponse } from '../../tooling-entrypoint'
import { useAppSelector } from '../../redux/hooks'
import { getDataLayer } from '../../redux/data-layer'

type FileSystemEvent = { change: unknown }
export const fileSystemEvent = mitt<FileSystemEvent>()
Expand All @@ -14,15 +15,16 @@ export const removeBasePath = (basePath: string, path: string) => {
/* istanbul ignore next */
export const useFileSystem = (): [AssetCatalogResponse, boolean] => {
const [files, setFiles] = useState<AssetCatalogResponse>({ basePath: '', assets: [] })
const dataLayer = useAppSelector(getDataLayer)

const [init, setInit] = useState(false)
useSdk(({ dataLayer }) => {
async function fetchFiles() {
const assets = await dataLayer.getAssetCatalog({})
setFiles(assets)
}
fileSystemEvent.on('change', fetchFiles)
void fetchFiles().then(() => setInit(true))
})
const fetchFiles = useCallback(async () => {
if (!dataLayer) return
const assets = await dataLayer.getAssetCatalog({})
setFiles(assets)
}, [dataLayer])
fileSystemEvent.on('change', fetchFiles)
void fetchFiles().then(() => setInit(true))

return [files, init]
}
9 changes: 5 additions & 4 deletions packages/@dcl/inspector/src/hooks/editor/useSave.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,20 @@
import mitt from 'mitt'
import { useCallback, useState } from 'react'

import { useSdk } from '../sdk/useSdk'
import { useAppSelector } from '../../redux/hooks'
import { getDataLayer } from '../../redux/data-layer'

type SaveEvent = { change: boolean }
export const saveEvent = mitt<SaveEvent>()

export const useSave = (): [() => Promise<void>, boolean] => {
const sdk = useSdk()
const dataLayer = useAppSelector(getDataLayer)
const [isDirty, setIsDirty] = useState(false)

const saveFn = useCallback(async () => {
await sdk?.dataLayer.save({})
await dataLayer?.save({})
setIsDirty(false)
}, [sdk])
}, [dataLayer])

saveEvent.on('change', (value: boolean) => setIsDirty(value))

Expand Down
2 changes: 1 addition & 1 deletion packages/@dcl/inspector/src/hooks/sdk/useSdkContext.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ export const useSdkContext = () => {
setError(e)
})
.finally(() => setIsLoading(false))
}, [catalog, canvas, sdk, isLoading, dispatch])
}, [catalog, canvas, sdk, isLoading, dispatch, dataLayer])

const renderer = useCallback(
(ref: React.RefObject<HTMLCanvasElement>) => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,10 @@ import { putBillboardComponent } from './sdkComponents/billboard'
import { putGltfContainerComponent } from './sdkComponents/gltf-container'
import { putMeshRendererComponent } from './sdkComponents/mesh-renderer'
import { putTransformComponent } from './sdkComponents/transform'
import { consumeAllMessagesInto } from '../../logic/consume-stream'
import { putSceneComponent } from './editorComponents/scene'
import { createOperations } from '../../sdk/operations'
import { createGizmoManager } from './gizmo-manager'
import { store } from '../../../redux/store'

export type LoadableScene = {
readonly entity: Readonly<Omit<Schemas.Entity, 'id'>>
Expand Down Expand Up @@ -68,12 +68,7 @@ export class SceneContext {
// this future is resolved when the scene is disposed
readonly stopped = future<void>()

constructor(
public babylon: BABYLON.Engine,
public scene: BABYLON.Scene,
public loadableScene: LoadableScene,
public dataLayer: DataLayerRpcClient
) {
constructor(public babylon: BABYLON.Engine, public scene: BABYLON.Scene, public loadableScene: LoadableScene) {
this.rootNode = new EcsEntity(0 as Entity, this.#weakThis, scene)
Object.assign(globalThis, { babylon: this.engine })
}
Expand Down Expand Up @@ -152,7 +147,9 @@ export class SceneContext {
async getFile(src: string): Promise<Uint8Array | null> {
if (!src) return null
try {
const response = await this.dataLayer.getAssetData({ path: src })
const { dataLayer } = store.getState().dataLayer
if (!dataLayer) return null
const response = await dataLayer.getAssetData({ path: src })
return response.data
} catch (err) {
console.error('Error fetching file ' + src, err)
Expand Down
7 changes: 2 additions & 5 deletions packages/@dcl/inspector/src/lib/sdk/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@ export type SdkContextValue = {
sceneContext: SceneContext
events: Emitter<SdkContextEvents>
dispose(): void
dataLayer: DataLayerRpcClient
operations: ReturnType<typeof createOperations>
gizmos: Gizmos
editorCamera: CameraManager
Expand All @@ -51,13 +50,12 @@ export async function createSdkContext(
getHardcodedLoadableScene(
'urn:decentraland:entity:bafkreid44xhavttoz4nznidmyj3rjnrgdza7v6l7kd46xdmleor5lmsxfm1',
catalog
),
dataLayer
)
)
ctx.rootNode.position.set(0, 0, 0)

// create inspector engine context and components
const { engine, components, events, dispose } = createInspectorEngine(dataLayer)
const { engine, components, events, dispose } = createInspectorEngine()

// register some globals for debugging
Object.assign(globalThis, { dataLayer, inspectorEngine: engine })
Expand All @@ -69,7 +67,6 @@ export async function createSdkContext(
scene,
sceneContext: ctx,
dispose,
dataLayer,
operations: createOperations(engine),
gizmos: ctx.gizmos,
editorCamera: renderer.editorCamera,
Expand Down
5 changes: 1 addition & 4 deletions packages/@dcl/inspector/src/lib/sdk/inspector-engine.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,9 @@
import mitt from 'mitt'

import { DataLayerRpcClient } from '../data-layer/types'
import { SdkContextEvents, SdkContextValue } from './context'
import { createEngineContext } from '../data-layer/host/utils/engine'

export function createInspectorEngine(
_dataLayer: DataLayerRpcClient
): Omit<
export function createInspectorEngine(): Omit<
SdkContextValue,
'scene' | 'sceneContext' | 'dataLayer' | 'operations' | 'gizmos' | 'editorCamera' | 'preferences'
> {
Expand Down

0 comments on commit 5577f45

Please sign in to comment.