Bootstrap Image Generator application (#53)

This PR begins scaffolding the Stable Diffusion Turbo application (title
TBD), which is a separate frontend for Storyteller Engine which focuses
on image generation.

### Design Overview

* The application renders a "split-screen" view, with Storyteller Studio
  on the left, and the Stable Diffusion Turbo output on the right
* When changes are made in the Studio editor:
  - A screenshot is taken from the Bevy application
  - Screenshot is piped into Stable Diffusion Turbo model
  - Model output is rendered to the screen
* This all happens in as close to real-time as possible

### Work completed in this PR

* The `studio-frontend` project has been (somewhat crudely) refactored
  to split most of its components into reusable libraries
  - `studio-ui` is a use-case-agnostic design system library for core UI
    components. These are "dumb" components which are controlled
    via `@property` inputs and send `CustomEvent`s in response to user
    input.
  - `studio-frontend` is a collection of reusable Storyteller Studio
    widgets. These are "smart" components which depend on
    `@storyteller/studio` directly, manage their own state, and require very
    little configuration or styling. They are designed to be drop-in
    building blocks that can be reused between various frontends.
* The new application has been bootstrapped as `image-generator-demo`
  - Currently, this simply grabs screenshots from the Bevy application and
    renders those screenshots on the right side of the split-screen view. A
    future PR will wire up to the Storyteller.ai backend to pipe these
    screenshots through Stable Diffusion Turbo, and render that model's
    output instead.

### Testing

* Install dependencies as described in the repo's README
* Run `npx nx serve image-generator-demo`
* Open [localhost:4200](http://localhost:4200) in your browser
  - Use the camera controller in the left side of the view to manipulate
    the Bevy scene
  - Verify the right side of the view updates with a fresh screenshot at a
    rate of ~5 fps
* Toggle the "Realtime Capture" checkbox
  - Verify the right side view no longer updates while the user is
    actively manipulating the editor
  - This should allow the app to run smoother on lower-spec hardware

---------

Co-authored-by: Danny McGee <dannymcgee@gmail.com>
This commit is contained in:
Brooks Palin
2024-02-26 15:13:07 -07:00
committed by GitHub
parent 7b06d48c5d
commit d51eec52c3
71 changed files with 1331 additions and 579 deletions
@@ -5,10 +5,10 @@ import { LitElement, type PropertyValues, html, unsafeCSS } from "lit";
import { customElement, state } from "lit/decorators.js";
import { styleMap } from "lit/directives/style-map.js";
import "@storyteller/studio-ui/button";
import "@storyteller/studio-ui/toolbar";
import "@storyteller/studio-ui/tree";
import "./anim-timeline.element";
import "./button.element";
import "./toolbar.element";
import "./tree.element";
import styles from "./anim-editor.element.scss?inline";
-24
View File
@@ -35,33 +35,9 @@ sts-button.active {
// Hierarchy (TODO: Probably move this)
.hierarchy {
overflow: auto;
box-sizing: border-box;
width: $hierarchy-width;
max-height: calc(100vh - 32px);
padding: 10px 15px;
background: #0006;
backdrop-filter: blur(16px);
border: 8px solid transparent;
border-radius: 0.5rem;
pointer-events: auto;
&::-webkit-scrollbar {
width: 8px;
height: 8px;
&-thumb {
border-radius: 2px;
background: #FFF2;
&:hover {
background: #FFF3;
}
}
}
}
.loading {
+31 -215
View File
@@ -1,17 +1,12 @@
import { on } from "@storyteller/framework";
import * as studio from "@storyteller/studio";
import {
type EntityDespawnEvent,
type EntityMultiSpawnEvent,
type EntitySelectEvent,
type EntitySpawnEvent,
type SceneSavedEvent,
type SceneStateEvent,
TransformSpace,
TransformType,
SceneState,
StudioMode,
} from "@storyteller/studio";
import { StudioURLParams } from "@storyteller/studio-web";
import { CanvasProvider } from "@storyteller/studio-web/canvas-provider";
import { match } from "@storyteller/utility";
import { LitElement, html, nothing } from "lit";
@@ -20,144 +15,35 @@ import { classMap } from "lit-html/directives/class-map.js";
import { Ref, createRef, ref } from "lit-html/directives/ref.js";
import { v4 as uuid } from "uuid";
import "@storyteller/studio-ui/button";
import "@storyteller/studio-ui/icon";
import "@storyteller/studio-ui/toolbar";
import "@storyteller/studio-ui/tree";
import "@storyteller/studio-web/canvas-provider";
import "@storyteller/studio-web/viewer";
import "@storyteller/studio-web/bvh-viewer";
import "@storyteller/studio-web/editor";
import "@storyteller/studio-web/mixamo-viewer";
import "@storyteller/studio-web/scene-hierarchy";
import "@storyteller/studio-web/transform-toolbar";
import "./anim-editor.element";
import "./button.element";
import "./help.element";
import "./icon.element";
import "./toolbar.element";
import "./transform-toolbar.element";
import "./tree.element";
import "./app.element.scss";
interface SceneObject extends Omit<studio.SceneObject, "children"> {
children: SceneObject[];
}
@customElement("app-root")
export class AppElement extends LitElement {
@state() showHelp = false;
@state() loading = true;
@state() transformSpace = TransformSpace.Local;
@state() transformType = TransformType.Translate;
@state() sceneObjects: SceneObject[] = [];
@state() selection?: string | null;
@state() bvhPath?: string;
@state() mixamoPath?: string;
@state() scenePath?: string;
@state() mode?: StudioMode;
#sceneObjects: studio.SceneObject[] = [];
#entityMap = new Map<string, SceneObject>();
#params = new StudioURLParams();
#canvasProvider: Ref<CanvasProvider> = createRef();
get #studioCanvas(): HTMLCanvasElement | null {
const provider = this.#canvasProvider.value;
if (!provider) return null;
return document.getElementById(provider.canvasId) as HTMLCanvasElement | null;
}
override connectedCallback(): void {
super.connectedCallback();
const params = new URLSearchParams(document.location.search);
if (params.has("bvh"))
this.bvhPath = params.get("bvh")!;
if (params.has("mixamo"))
this.mixamoPath = params.get("mixamo")!;
if (params.has("scene"))
this.scenePath = params.get("scene")!;
this.mode = match (params.get("mode"), {
"studio": () => StudioMode.Editor,
"viewer": () => StudioMode.Viewer,
_: () => StudioMode.Viewer,
});
this.#redirectBodyFocus();
}
protected override createRenderRoot(): Element | ShadowRoot {
return this;
}
@on("keydown")
@on("keyup")
pipeKeyboardEvents(event: KeyboardEvent): void {
// When the user interacts with one of the web UI elements, the Bevy
// canvas will lose focus, preventing it from receiving keyboard events.
// As a workaround, we can listen for any events that have bubbled up to
// the app root and repeat them for the canvas.
//
// This does unfortunately burden the web front-end with some additional
// responsibility: when we handle a keyboard event and _don't_ want the
// Bevy app to receive it, we'll need to call `event.stopPropagation()` in
// the handler to prevent it from reaching this listener.
const {
type,
code, charCode, key, keyCode, location, repeat,
altKey, ctrlKey, metaKey, shiftKey,
} = event;
this.#studioCanvas?.dispatchEvent(new KeyboardEvent(type, {
code, charCode, key, keyCode, location, repeat,
altKey, ctrlKey, metaKey, shiftKey,
bubbles: true,
cancelable: true,
composed: true,
}));
}
onSceneStateChange({ detail: state }: SceneStateEvent): void {
console.log("scene state change:", SceneState[state]);
this.loading = match (state, {
[SceneState.Active]: () => false,
_: () => true,
});
}
@on("window:entity-select")
onEntitySelectionChange({ detail: entity }: EntitySelectEvent): void {
const sceneObject = this.#entityMap.get(entity!);
console.log("Entity selection changed:", sceneObject);
this.selection = entity;
}
@on("window:entity-spawn")
onEntitySpawned({ detail: value }: EntitySpawnEvent): void {
console.log("Entity spawned:", value);
this.#sceneObjects = this.#sceneObjects.concat(value).sort(sortByName);
this.#updateHierarchy();
}
@on("window:entity-multi-spawn")
onEntitiesSpawned({ detail: values }: EntityMultiSpawnEvent): void {
console.log("Entities spawned:", values);
this.#sceneObjects = this.#sceneObjects.concat(values).sort(sortByName);
this.#updateHierarchy();
}
@on("window:entity-despawn")
onEntityDespawned({ detail: entity }: EntityDespawnEvent): void {
console.log("Entity despawned:", entity);
this.#sceneObjects = this.#sceneObjects.filter(({ id }) => id !== entity);
this.#updateHierarchy();
}
@on("window:scene-saved")
@on("scene-saved")
async onSceneSaved({ detail: scene }: SceneSavedEvent): Promise<void> {
const file = new File([scene], "scene.scn.ron", { type: "text/ron" });
const formData = new FormData();
@@ -179,98 +65,52 @@ export class AppElement extends LitElement {
}
}
@on("scene-state")
onSceneStateChange({ detail: state }: SceneStateEvent): void {
console.log("scene state change:", SceneState[state]);
this.loading = match (state, {
[SceneState.Active]: () => false,
_: () => true,
});
}
toggleHelp(): void {
this.showHelp = !this.showHelp;
}
onTransformSpaceChange({ detail: space }: CustomEvent<TransformSpace>): void {
this.transformSpace = space;
studio.setTransformSpace(space);
}
onTransformTypeChange({ detail: type }: CustomEvent<TransformType>): void {
this.transformType = type;
studio.setTransformType(type);
}
// TODO: Get some help from someone who knows what an algorithm is
#updateHierarchy(): void {
this.#entityMap.clear();
for (let obj of this.#sceneObjects)
this.#entityMap.set(obj.id, { ...obj, children: [] });
for (let obj of this.#entityMap.values()) {
if (obj.parent != null) {
const parent = this.#entityMap.get(obj.parent);
if (!parent)
throw new Error(`Missing parent: ${obj.parent}`);
parent.children.push(obj);
}
}
for (let obj of this.#entityMap.values())
obj.children.sort(sortByName);
this.sceneObjects = Array
.from(this.#entityMap.values())
.filter(obj => obj.parent == null)
.sort(sortByName);
console.log("Hierarchy:", this.sceneObjects);
}
#redirectBodyFocus(): void {
// If user focus lands on the `document.body`, neither the frontend app
// nor the Bevy app will properly handle keyboard events. Thie function
// runs every tick to ensure that user focus never becomes "stranded" in
// this way.
if (document.activeElement === document.body) {
const canvasId = this.#canvasProvider.value?.canvasId;
if (canvasId)
document.getElementById(canvasId)?.focus();
}
requestAnimationFrame(() => this.#redirectBodyFocus());
}
protected override render = () => html`
<sts-canvas-provider
class="app-root"
${ref(this.#canvasProvider as any)}
>
<!-- Scene view -->
${this.bvhPath ? html`
${this.#params.bvh ? html`
<sts-bvh-viewer
bvhPath=${this.bvhPath}
bvhPath=${this.#params.bvh}
skyboxId="test_scene"
@scene-state=${this.onSceneStateChange}
></sts-bvh-viewer>
` : this.mixamoPath ? html`
` : this.#params.mixamo ? html`
<sts-mixamo-viewer
mixamoPath=${this.mixamoPath}
mixamoPath=${this.#params.mixamo}
skyboxId="test_scene"
@scene-state=${this.onSceneStateChange}
></sts-mixamo-viewer>
` : this.scenePath ? html`
` : this.#params.scene ? html`
<sts-editor
scenePath=${this.scenePath}
@scene-state=${this.onSceneStateChange}
scenePath=${this.#params.scene}
></sts-editor>
` : html`
<sts-viewer
objectId="sample-room.gltf"
skyboxId="test_scene"
.mode=${this.mode}
@scene-state=${this.onSceneStateChange}
.mode=${this.#params.mode}
></sts-viewer>
`}
<!-- Actions toolbar -->
<sts-toolbar class="v-start h-start">
<sts-toolbar-group>
${this.mode === StudioMode.Editor ? html`
${this.#params.mode === StudioMode.Editor ? html`
<sts-button
icon="floppy-disk"
@click=${() => studio.saveScene()}
@@ -288,30 +128,10 @@ export class AppElement extends LitElement {
</sts-toolbar-group>
</sts-toolbar>
${this.mode === StudioMode.Editor ? html`
<!-- Transform toolbar -->
<sts-transform-toolbar
class="v-start h-center"
.type=${this.transformType}
@type-change=${this.onTransformTypeChange}
.space=${this.transformSpace}
@space-change=${this.onTransformSpaceChange}
></sts-transform-toolbar>
<!-- Hierarchy and inspector -->
<div class="hierarchy v-start h-end">
${this.sceneObjects.map(obj => html`
<sts-tree class="scene-object"
id=${obj.id}
.name=${obj.name}
.treeChildren=${obj.children}
></sts-tree>
`)}
</div>
` : nothing}
<!-- Animation timeline -->
${this.mode === StudioMode.Editor ? html`
<!-- Studio-mode-only elements -->
${this.#params.mode === StudioMode.Editor ? html`
<sts-transform-toolbar class="v-start h-center"></sts-transform-toolbar>
<sts-scene-hierarchy class="hierarchy v-start h-end"></sts-scene-hierarchy>
<sts-anim-editor class="timeline v-end h-start h-before-hierarchy"></sts-anim-editor>
` : nothing}
@@ -329,7 +149,3 @@ export class AppElement extends LitElement {
</sts-canvas-provider>
`;
}
function sortByName(a: { name: string }, b: { name: string }): number {
return a.name.localeCompare(b.name);
}
@@ -1,36 +0,0 @@
:host {
display: inline-flex;
align-items: center;
gap: 0.75rem;
padding: 0.5rem 1rem;
border-radius: 0.5rem;
font: {
family: "Fira Sans", sans-serif;
size: 15px;
weight: 500;
}
line-height: 1.5;
pointer-events: auto;
cursor: pointer;
user-select: none;
background: #0006;
color: #FFFC;
backdrop-filter: blur(16px);
transition: {
property: background, color;
duration: 0.1s;
timing-function: linear;
}
}
:host(:hover) {
background: #0008;
color: #FFFF;
}
.icon {
fill: currentColor;
}
-32
View File
@@ -1,32 +0,0 @@
import { on } from "@storyteller/framework";
import { LitElement, html, nothing, unsafeCSS } from "lit";
import { customElement, property } from "lit/decorators.js";
import styles from "./button.element.scss?inline";
import "./icon.element";
@customElement("sts-button")
export class ButtonElement extends LitElement {
static override styles = unsafeCSS(styles);
@property() icon?: string;
override role = "button";
override tabIndex = 0;
@on("keydown")
onKeyDown(event: KeyboardEvent) {
if (/^( |Enter)$/.test(event.key)) {
event.stopPropagation();
this.click();
}
}
protected override render = () => html`
${this.icon
? html`<sts-icon icon=${this.icon} aria-hidden="true"></sts-icon>`
: nothing}
<slot></slot>
`
}
-28
View File
@@ -1,28 +0,0 @@
:host {
display: flex;
width: auto;
align-items: center;
justify-content: center;
height: 1em;
}
.a11y-label {
position: absolute;
overflow: hidden;
width: 1px;
height: 1px;
margin: -1px;
padding: 0;
clip: rect(1px, 1px, 1px, 1px);
border: 0;
white-space: nowrap;
}
.svg-wrapper {
display: flex;
}
svg {
height: 1em;
fill: currentColor;
}
-87
View File
@@ -1,87 +0,0 @@
import { spread } from "@storyteller/framework";
import { match } from "@storyteller/utility";
import { LitElement, TemplateResult, html, nothing, unsafeCSS } from "lit";
import { customElement, property } from "lit/decorators.js";
import { unsafeSVG } from "lit/directives/unsafe-svg.js";
import farCrosshairs from "@fortawesome/fontawesome-pro/svgs/regular/crosshairs.svg?raw";
import farVideo from "@fortawesome/fontawesome-pro/svgs/regular/video.svg?raw";
import fasCircleQuestion from "@fortawesome/fontawesome-pro/svgs/solid/circle-question.svg?raw";
import fasKey from "@fortawesome/fontawesome-pro/svgs/solid/key.svg?raw";
import farCube from "@fortawesome/fontawesome-pro/svgs/regular/cube.svg?raw";
import farGlobe from "@fortawesome/fontawesome-pro/svgs/regular/globe.svg?raw";
import farUpDownLeftRight from "@fortawesome/fontawesome-pro/svgs/regular/arrows-up-down-left-right.svg?raw";
import fasPlay from "@fortawesome/fontawesome-pro/svgs/solid/play.svg?raw";
import fasFwdStep from "@fortawesome/fontawesome-pro/svgs/solid/forward-step.svg?raw";
import fasFwdFast from "@fortawesome/fontawesome-pro/svgs/solid/forward-fast.svg?raw";
import fasBwdStep from "@fortawesome/fontawesome-pro/svgs/solid/backward-step.svg?raw";
import fasBwdFast from "@fortawesome/fontawesome-pro/svgs/solid/backward-fast.svg?raw";
import fasQuestion from "@fortawesome/fontawesome-pro/svgs/solid/question.svg?raw";
import farRotate from "@fortawesome/fontawesome-pro/svgs/regular/arrows-rotate.svg?raw";
import farScale from "@fortawesome/fontawesome-pro/svgs/regular/arrow-up-right-and-arrow-down-left-from-center.svg?raw";
import fasCaretRight from "@fortawesome/fontawesome-pro/svgs/solid/caret-right.svg?raw";
import fasFloppyDisk from "@fortawesome/fontawesome-pro/svgs/solid/floppy-disk.svg?raw";
import styles from "./icon.element.scss?inline";
@customElement("sts-icon")
export class IconElement extends LitElement {
static override styles = unsafeCSS(styles);
@property() icon = "";
protected override render = () => html`
<span class="a11y-label">
<slot></slot>
</span>
<div class="svg-wrapper" role="presentation">
${renderSvg(this.icon)}
</div>
`;
}
const RENDER_RESULTS = new Map<string, TemplateResult>();
function renderSvg(iconId: string) {
if (RENDER_RESULTS.has(iconId))
return RENDER_RESULTS.get(iconId)!;
const svgSrc = match (iconId, {
"bwd-fast": () => fasBwdFast,
"bwd-step": () => fasBwdStep,
"circle-question": () => fasCircleQuestion,
"caret-right": () => fasCaretRight,
"crosshairs": () => farCrosshairs,
"cube": () => farCube,
"floppy-disk": () => fasFloppyDisk,
"fwd-fast": () => fasFwdFast,
"fwd-step": () => fasFwdStep,
"key": () => fasKey,
"globe": () => farGlobe,
"play": () => fasPlay,
"question": () => fasQuestion,
"rotate": () => farRotate,
"scale": () => farScale,
"up-down-left-right": () => farUpDownLeftRight,
"video": () => farVideo,
_: () => null,
});
if (!svgSrc) return nothing;
const [, attrsString, body] = svgSrc.match(/<svg(.+?)>(.+?)<\/svg>/)!;
const attrs = Object.fromEntries(
Array.from(attrsString.matchAll(/([-:_a-zA-Z0-9]+)(?:=['"]?([^'"]*)['"]?)/g))
.map(([, attr, value]) => [attr, value])
);
const result = html`
<svg ${spread(attrs)}>
${unsafeSVG(body)}
</svg>
`;
RENDER_RESULTS.set(iconId, result);
return result;
}
@@ -1,22 +0,0 @@
:host {
display: flex;
gap: 2px;
}
::slotted(*) {
border-radius: 0;
}
::slotted(:first-child) {
border: {
top-left-radius: 8px;
bottom-left-radius: 8px;
}
}
::slotted(:last-child) {
border: {
top-right-radius: 8px;
bottom-right-radius: 8px;
}
}
@@ -1,4 +0,0 @@
:host {
display: flex;
gap: 16px;
}
@@ -1,21 +0,0 @@
import { LitElement, html, unsafeCSS } from "lit";
import { customElement } from "lit/decorators.js";
import toolbarStyles from "./toolbar.element.scss?inline";
import toolbarGroupStyles from "./toolbar-group.element.scss?inline";
// TODO: A11y - https://www.w3.org/WAI/ARIA/apg/patterns/toolbar/
@customElement("sts-toolbar")
export class ToolbarElement extends LitElement {
static override styles = unsafeCSS(toolbarStyles);
override role = "toolbar";
protected override render = () => html`<slot></slot>`;
}
@customElement("sts-toolbar-group")
export class ToolbarGroupElement extends LitElement {
static override styles = unsafeCSS(toolbarGroupStyles);
override role = "group";
protected override render = () => html`<slot></slot>`;
}
@@ -1,57 +0,0 @@
.btn-toggle {
display: inline-flex;
align-items: center;
justify-content: center;
position: relative;
font-size: 16px;
padding: 10px 12px;
pointer-events: auto;
// TODO: Copypasta
background: #0006;
color: #FFFC;
backdrop-filter: blur(16px);
transition: {
property: background, color;
duration: 0.1s;
timing-function: linear;
}
&:hover {
background: #0008;
color: #FFF;
}
&:has(:focus-visible) {
z-index: 1;
outline: 4px solid #2F83FFBF;
}
&:has(:checked) {
background: #7A2C34E3;
color: #FFF;
&:hover {
background: #90363F;
}
}
&:has(:disabled) {
background: #0003 !important;
color: #FFF6 !important;
}
input {
display: block;
appearance: none;
border: 0;
margin: 0;
padding: 0;
opacity: 0;
position: absolute;
inset: 0;
width: 100%;
height: 100%;
z-index: 1;
}
}
@@ -1,105 +0,0 @@
import { TransformSpace, TransformType } from "@storyteller/studio";
import { match } from "@storyteller/utility";
import { LitElement, html, unsafeCSS } from "lit";
import { customElement, property } from "lit/decorators.js";
import styles from "./transform-toolbar.element.scss?inline";
@customElement("sts-transform-toolbar")
export class TransformToolbarElement extends LitElement {
static override styles = unsafeCSS(styles);
@property({ type: Number }) space = TransformSpace.Local;
@property({ type: Number }) type = TransformType.Translate;
#onSpaceChange(event: InputEvent): void {
const { value } = event.target as HTMLInputElement;
const space = match (value, {
"local": () => TransformSpace.Local,
"world": () => TransformSpace.World,
_: () => {
throw new Error(`Unknown transform space: "${value}"`);
}
});
this.dispatchEvent(new CustomEvent<TransformSpace>("space-change", {
detail: space,
bubbles: true,
composed: true,
}));
}
#onTypeChange(event: InputEvent): void {
const { name, checked } = event.target as HTMLInputElement;
const flag = match (name, {
"translate": () => TransformType.Translate,
"rotate": () => TransformType.Rotate,
"scale": () => TransformType.Scale,
_: () => {
throw new Error(`Unknown transform type: "${name}"`);
}
});
const type = checked
? this.type | flag
: this.type & ~flag;
this.dispatchEvent(new CustomEvent<TransformType>("type-change", {
detail: type,
bubbles: true,
composed: true,
}));
}
protected override render = () => html`
<sts-toolbar>
<sts-toolbar-group>
<label class="btn-toggle">
<sts-icon icon="cube">Local</sts-icon>
<input type="radio"
name="transform-space"
value="local"
?checked=${this.space === TransformSpace.Local}
@input=${this.#onSpaceChange}
/>
</label>
<label class="btn-toggle">
<sts-icon icon="globe">Global</sts-icon>
<input type="radio"
name="transform-space"
value="world"
?checked=${this.space === TransformSpace.World}
@input=${this.#onSpaceChange}
/>
</label>
</sts-toolbar-group>
<sts-toolbar-group>
<label class="btn-toggle">
<sts-icon icon="up-down-left-right">Translate</sts-icon>
<input type="checkbox"
name="translate"
?checked=${Boolean(this.type & TransformType.Translate)}
@input=${this.#onTypeChange}
/>
</label>
<label class="btn-toggle">
<sts-icon icon="rotate">Rotate</sts-icon>
<input type="checkbox"
name="rotate"
?checked=${Boolean(this.type & TransformType.Rotate)}
@input=${this.#onTypeChange}
/>
</label>
<label class="btn-toggle">
<sts-icon icon="scale">Scale</sts-icon>
<input type="checkbox"
name="scale"
disabled
?checked=${Boolean(this.type & TransformType.Scale)}
@input=${this.#onTypeChange}
/>
</label>
</sts-toolbar-group>
</sts-toolbar>
`;
}
-90
View File
@@ -1,90 +0,0 @@
$item-height: 24px;
:host, .children {
display: flex;
flex-direction: column;
}
:host {
min-width: min-content;
}
header {
display: flex;
align-items: center;
border-radius: 4px;
font: {
family: "Fira Sans", sans-serif;
size: 14px;
weight: 400;
}
line-height: 1;
white-space: nowrap;
pointer-events: auto;
cursor: default;
user-select: none;
color: #FFFC;
transition: {
property: background, color;
duration: 0.1s;
timing-function: linear;
}
&.selectable:hover:not(:has(.toggle-expanded:hover)) {
background: #0000001F;
}
&.selected {
background: #7A2C34E3;
color: #FFF;
font-weight: 500;
&:hover {
background: #90363F !important;
}
}
}
.toggle-expanded {
display: flex;
align-items: center;
justify-content: center;
flex: 0 0 auto;
width: 16px;
height: $item-height;
margin-block: -5px;
padding-inline-start: 4px;
appearance: none;
background: transparent;
border: none;
font: inherit;
color: #FFFC;
&:hover {
color: #FFF;
}
}
.icon.expanded {
transform: rotate(90deg);
}
.label {
display: flex;
flex: 1 0 0;
height: $item-height;
align-items: center;
gap: 8px;
padding-inline-start: 5px;
}
.children {
margin-inline-start: 7px;
padding-inline-start: 9px;
border-inline-start: 1px solid #FFF2;
}
-88
View File
@@ -1,88 +0,0 @@
import { on } from "@storyteller/framework";
import * as studio from "@storyteller/studio";
import { type EntitySelectEvent } from "@storyteller/studio";
import { LitElement, html, nothing, unsafeCSS } from "lit";
import { customElement, property, state } from "lit/decorators.js";
import { classMap } from "lit/directives/class-map.js";
import { ifDefined } from "lit/directives/if-defined.js";
import "./icon.element";
import styles from "./tree.element.scss?inline";
export interface Tree {
id?: string;
name: string;
children?: Tree[];
}
@customElement("sts-tree")
export class TreeElement extends LitElement {
static override styles = unsafeCSS(styles);
@property() name = "";
@property() icon?: string;
@property({ attribute: false }) treeChildren?: Tree[];
@property({ type: Boolean }) expanded = false;
@state() selected = false;
toggleExpanded(): void {
this.expanded = !this.expanded;
}
@on("window:entity-select")
onEntitySelect({ detail: entity }: EntitySelectEvent): void {
this.selected = this.id === entity;
}
selectEntity(): void {
if (this.id)
studio.select(this.id);
}
// TODO: A11y
protected override render = () => html`
<header
class=${classMap({
selected: this.selected,
selectable: !!this.id,
})}
>
${this.treeChildren?.length ? html`
<button class="toggle-expanded"
@click=${this.toggleExpanded}
>
<sts-icon
class=${classMap({
icon: true,
expanded: this.expanded,
})}
icon="caret-right"
aria-label=${this.expanded ? "Expand" : "Collapse"}
></sts-icon>
</button>
` : nothing}
<span class="label"
@click=${this.selectEntity}
>
${this.icon ? html`
<sts-icon icon=${this.icon}></sts-icon>
` : nothing}
${this.name}
</span>
</header>
${this.expanded && this.treeChildren?.length ? html`
<div class="children">
${this.treeChildren?.map(tree => html`
<sts-tree
id=${ifDefined(tree.id)}
.name=${tree.name}
.treeChildren=${tree.children}
></sts-tree>
`)}
</div>
` : nothing}
`;
}