Skip to content

Commit 090ecce

Browse files
authored
Add Element component for rendering 2D screen space UI elements (#173)
- Introduced the Element component to allow entities to render UI elements in screen space. - Implemented prop validation and component definition for the Element component. - Updated index.ts to export the new Element component alongside existing components.
1 parent e1eecdf commit 090ecce

File tree

2 files changed

+49
-1
lines changed

2 files changed

+49
-1
lines changed
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
"use client"
2+
3+
import { FC } from "react";
4+
import { useComponent } from "../hooks";
5+
import { Entity, ElementComponent } from "playcanvas";
6+
import { PublicProps, Serializable } from "../utils/types-utils";
7+
import { validatePropsWithDefaults, createComponentDefinition, getStaticNullApplication, Schema } from "../utils/validation";
8+
9+
/**
10+
* The Screen component allows an entity to render a 2D screen space UI element.
11+
* This is useful for creating UI elements that are rendered in screen space rather than world space.
12+
*
13+
* @param {ElementProps} props - The props to pass to the screen component.
14+
* @see https://api.playcanvas.com/engine/classes/ElementComponent.html
15+
*
16+
* @example
17+
* <Entity>
18+
* <Screen screenSpace={true} />
19+
* <Element>Hey</Element>
20+
* </Screen>
21+
* </Entity>
22+
*/
23+
export const Element: FC<ElementProps> = (props) => {
24+
const safeProps = validatePropsWithDefaults(props, componentDefinition);
25+
26+
useComponent("element", safeProps, componentDefinition.schema);
27+
return null;
28+
};
29+
30+
type ElementProps = Partial<Serializable<PublicProps<ElementComponent>>>
31+
32+
const componentDefinition = createComponentDefinition<ElementProps, ElementComponent>(
33+
"Element",
34+
() => new Entity("mock-element", getStaticNullApplication()).addComponent("element") as ElementComponent,
35+
(component) => (component as ElementComponent).system.destroy(),
36+
"ElementComponent"
37+
);
38+
39+
40+
componentDefinition.schema = {
41+
...componentDefinition.schema,
42+
children: {
43+
validate: (value: unknown) => typeof value === "string",
44+
errorMsg: (value: unknown) => `Invalid value for prop "children": ${value}. Expected a string.`,
45+
default: "Invalid children"
46+
}
47+
} as Schema<ElementProps, ElementComponent>;

packages/lib/src/components/index.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,4 +11,5 @@ export { Align } from './Align'
1111
export { Anim } from './Anim'
1212
export { RigidBody } from './RigidBody'
1313
export { Collision } from './Collision'
14-
export { Screen } from './Screen'
14+
export { Screen } from './Screen'
15+
export { Element } from './Element'

0 commit comments

Comments
 (0)