0% found this document useful (0 votes)
17 views4 pages

Universe Graph Code Overview

The document is a React component for a 3D universe visualization using the react-three-fiber library. It incorporates various features such as camera controls, loading states, and user interactions, while also managing state through custom stores. The component is designed to render a canvas with adaptive performance settings and includes additional elements like a graph search and overlays.

Uploaded by

cosegad183
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views4 pages

Universe Graph Code Overview

The document is a React component for a 3D universe visualization using the react-three-fiber library. It incorporates various features such as camera controls, loading states, and user interactions, while also managing state through custom stores. The component is designed to render a canvas with adaptive performance settings and includes additional elements like a graph search and overlays.

Uploaded by

cosegad183
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

/* eslint-disable no-underscore-dangle */

/* eslint-disable import/no-extraneous-dependencies */
import { AdaptiveDpr, AdaptiveEvents, Html, Loader, Preload } from
'@react-three/drei'
import { Canvas, RootState } from '@react-three/fiber'
import { Leva } from 'leva'
import { Perf } from 'r3f-perf'
import { Suspense, memo, useCallback } from 'react'
import styled from 'styled-components'
import { isDevelopment } from '~/constants'
import { useAppStore } from '~/stores/useAppStore'
import { useControlStore } from '~/stores/useControlStore'
import { useDataStore } from '~/stores/useDataStore'
import { useGraphStore } from '~/stores/useGraphStore'
import { addToGlobalForE2e } from '~/utils/tests'
import { UniverseQuestion } from '../App/UniverseQuestion'
import { Flex } from '../common/Flex'
import { initialCameraPosition, selectionGraphCameraPosition } from
'./Controls/CameraAnimations/constants'
import { CursorTooltip } from './CursorTooltip/index'
import { GraphSearch } from './GraphSearch'
import { Overlay } from './Overlay'
import { Preloader } from './Preloader'
import { SelectionContent } from './SelectionContent'

const Fallback = () => (


<Html>
<Loader />
</Html>
)

// const Content = () => {


// const { universeColor } = useControls('universe', {
// universeColor: [Link],
// })

// const dataInitial = useDataStore((s) => [Link])

// const selectedNode = useSelectedNode()

// const outlineColor: number = useMemo(


// () => (selectedNode?.node_type ? (getNodeColorByType(selectedNode.node_type)
as number) : outlineEffectColor),
// [selectedNode],
// )

// return (
// <>
// <color args={[colors.BLUE_PRESS_STATE || universeColor]}
attach="transparent" />

// <Lights />

// <Controls />

// <Selection>
// {false && (
// <EffectComposer autoClear={false} multisampling={8}>
// <Vignette darkness={0.7} eskil={false} offset={0.05} />
// <Bloom
// luminanceThreshold={1} // luminance threshold. Raise this value to
mask out darker elements in the scene.
// // eslint-disable-next-line @typescript-eslint/ban-ts-comment
// // @ts-ignore
// mipmapBlur
// resolutionX={Resolution.AUTO_SIZE} // The horizontal resolution.
// resolutionY={Resolution.AUTO_SIZE} // The vertical resolution.
// />
// <Outline
// blendFunction={[Link]} // set this to
[Link] for dark outlines
// blur
// edgeStrength={4}
// hiddenEdgeColor={outlineColor}
// visibleEdgeColor={outlineColor} // the color of visible edges
// />
// </EffectComposer>
// )}
// {dataInitial?.nodes?.length ? <Graph /> : null}
// </Selection>
// </>
// )
// }

let wheelEventTimeout: ReturnType<typeof setTimeout> | null = null

const cameraProps = {
aspect: [Link] / [Link],
far: 30000,
near: 1,
position: [initialCameraPosition.x, initialCameraPosition.y,
initialCameraPosition.z],
} as const

const _Universe = () => {


const [setIsUserScrollingOnHtmlPanel, setIsUserScrolling, setUserMovedCamera] = [
useControlStore((s) => [Link]),
useControlStore((s) => [Link]),
useControlStore((s) => [Link]),
]

const showSelectionGraph = useGraphStore((s) => [Link])

const isLoading = useDataStore((s) => [Link])


const universeQuestionIsOpen = useAppStore((s) => [Link])

const onWheelHandler = useCallback(


(e: [Link]) => {
const { target } = e
const { offsetParent } = target as HTMLDivElement

if (wheelEventTimeout) {
clearTimeout(wheelEventTimeout)
}

if (offsetParent?.classList?.contains('html-panel')) {
// if overflowing on y, disable camera controls to scroll on div
if ([Link] < [Link]) {
setIsUserScrollingOnHtmlPanel(true)
}
}

setIsUserScrolling(true)
setUserMovedCamera(true)

wheelEventTimeout = setTimeout(() => {


setIsUserScrolling(false)
setIsUserScrollingOnHtmlPanel(false)
}, 200)
},
[setIsUserScrolling, setIsUserScrollingOnHtmlPanel, setUserMovedCamera],
)

const onCreatedHandler = useCallback((s: RootState) => addToGlobalForE2e(s,


'threeState'), [])

return (
<Wrapper>
<Suspense fallback={null}>
<Leva hidden isRoot />

<Canvas
camera={cameraProps}
frameloop={showSelectionGraph ? 'demand' : 'always'}
id="universe-canvas"
onCreated={onCreatedHandler}
onWheel={onWheelHandler}
>
{isDevelopment && <Perf position="top-right" style={{ top: '80px' }} />}
<Suspense fallback={<Fallback />}>
<Preload />

<AdaptiveDpr />

<AdaptiveEvents />

<Html fullscreen>
<Text>Hello</Text>
</Html>

{/* <Content /> */}


</Suspense>
</Canvas>
<GraphSearch />
<CursorTooltip />

{showSelectionGraph ? (
<SelectionWrapper>
<Canvas
camera={{
...cameraProps,
position: [
selectionGraphCameraPosition.x,
selectionGraphCameraPosition.y,
selectionGraphCameraPosition.z,
],
}}
id="selection-canvas"
onCreated={({ gl }) => {
[Link]('#000000')
[Link](0.8)
}}
>
{isDevelopment && <Perf position="top-right" style={{ top:
'80px' }} />}
<Suspense fallback={<Fallback />}>
<AdaptiveDpr />

<AdaptiveEvents />

<SelectionContent />
</Suspense>
</Canvas>
</SelectionWrapper>
) : null}
</Suspense>
{universeQuestionIsOpen && <UniverseQuestion />}
{isLoading && <Preloader fullSize={false} />}
<Overlay />
</Wrapper>
)
}

const Wrapper = styled(Flex)`


flex: 1 1 100%;
position: relative;
`

const SelectionWrapper = styled(Flex)`


position: absolute;
inset: 0;
`

const Text = styled.p`


color: white;
z-index: 1001;
position: absolute;
top: 100%;
left: 100%;
transform: translate(-50%, -50%);
font-size: 24px;
pointer-events: none;
user-select: none;
`

export const Universe = memo(_Universe)

Common questions

Powered by AI

In `Universe`, `styled-components` are used to define component styles that are encapsulated and scoped only to the component where they are applied. This approach leverages JavaScript to create CSS, enabling dynamic styling and theming capabilities based on component state or props. Advantages include avoiding CSS class name collisions, automatic vendor prefixing, and the ability to create reusable and easily maintainable styling patterns that are tightly coupled with the component logic .

The `Suspense` component in the `Universe` component is used to delay the rendering of its child components until some asynchronous operation completes, which in this case can be the loading of external resources or data. This allows for optimization of the rendering process by avoiding the rendering of incomplete or loading states to the user, improving perceived performance and user experience .

The camera properties in the `Universe` component are defined in the `cameraProps` object, which includes settings like `aspect`, `far`, `near`, and `position`. These properties are critical for setting up the camera perspective in the 3D rendering environment of the `Canvas` component from the `@react-three/fiber` library. By providing specific values for these properties, it ensures proper scaling and visibility of 3D objects within the canvas, maintaining a consistent user experience and visually accurate rendering of scenes .

The `setTimeout` mechanism within the `onWheelHandler` function enhances interactivity by providing debouncing functionality. It temporarily disables camera controls when the user scrolls within a panel that can itself scroll. By setting a timeout to reset scrolling states, it ensures that controls are re-enabled after a delay, accommodating both user interface interactions and camera manipulations, which prevents erratic behavior and improves user experience .

The `useGraphStore` hook is used within `_Universe` to access the application state related to graph visibility, specifically through the `showSelectionGraph` variable. By leveraging this hook, the component can conditionally control the rendering behavior of graph-related components, such as whether to display a separate selection graph canvas. This reduces unnecessary renders and enhances application performance by rendering graph components only when necessary, based on user interaction or existing state conditions .

Conditionally rendering components like `GraphSearch` and `CursorTooltip` ensures that they are only included in the DOM when necessary, reducing load and increasing efficiency. This practice is important for managing resources effectively, maintaining clean UI states, and avoiding unnecessary computations or components that may detract from performance and user experience, particularly in complex applications where state-dependent views are predominant .

The `Perf` component, used conditionally based on the `isDevelopment` variable, is intended to provide real-time performance metrics like FPS within the `Canvas`, predominantly during the development phase. Its presence offers developers insights into rendering performance, which can aid in identifying bottlenecks or inefficiencies. Conditionally rendering it ensures that such performance diagnostics do not impact production builds, thereby not interfering with end-user experiences while allowing developers to optimize and troubleshoot during development .

`useCallback` is used in the `Universe` component to memoize the event handler functions, such as `onWheelHandler` and `onCreatedHandler`. This ensures that the functions do not get recreated on every render, which can prevent unnecessary re-renders of components that depend on these handlers. It is crucial for performance optimization, especially when passing these handlers to deeply nested components or components that have expensive calculations .

The `Html` component within the `Canvas` of `Universe` acts as a bridge to render traditional HTML elements over or within the 3D scene managed by `@react-three/fiber`. This integration allows for the inclusion of interactivity and UI elements directly within the 3D scene, such as tooltips or loading indicators, without having to step out of the 3D context, enabling a seamless blend of 2D HTML and 3D content .

`AdaptiveDpr` and `AdaptiveEvents` are functionalities from `@react-three/drei` that optimize application performance by dynamically adjusting the device pixel ratio and event handling based on device capability and scene complexity. `AdaptiveDpr` adjusts rendering resolution to balance performance and visual quality, reducing load on lower-end devices. `AdaptiveEvents` optimizes event handling by reducing the frequency of expensive operations. Together, they enhance application performance by tailoring resource usage dynamically according to the needs of the application and the capacity of the device .

You might also like