mirror of
https://github.com/VolmitSoftware/Iris.git
synced 2026-12-01 02:04:51 +00:00
Add the node editor to the procedural scene view
Under the 3D scene the entry's file shows as a tree of nodes, laid out left to right. Clicking a node shows its settings on the right, a field per schema option with defaults, ranges and enums; right click adds, duplicates and deletes; dragging a node onto another regrows it there. Undo and redo write earlier texts back. Edits are queued so quick ones never refuse each other, and a file changed elsewhere is read again. Context menus blur what is behind them, and submenus are portalled so the menu no longer clips them.
This commit is contained in:
1 parent
1aba430153
commit
922fe5e4cf
15 files changed
+1179
-29
No files matched your search
@@ -4,6 +4,8 @@ import { decodePattern } from './patternDecoding'
|
|||||||
import { decodeSavedTile } from './savedTileDecoding'
|
import { decodeSavedTile } from './savedTileDecoding'
|
||||||
import { decodeTile } from './tileDecoding'
|
import { decodeTile } from './tileDecoding'
|
||||||
import type {
|
import type {
|
||||||
|
EditorState,
|
||||||
|
GraphEdit,
|
||||||
MapHover,
|
MapHover,
|
||||||
MapLabel,
|
MapLabel,
|
||||||
MapTile,
|
MapTile,
|
||||||
@@ -18,10 +20,12 @@ import type {
|
|||||||
SavedTile,
|
SavedTile,
|
||||||
SavedWorldInfo,
|
SavedWorldInfo,
|
||||||
SceneEntry,
|
SceneEntry,
|
||||||
|
SceneViewInfo,
|
||||||
WorldInfo
|
WorldInfo
|
||||||
} from './types'
|
} from './types'
|
||||||
|
|
||||||
export const STATUS_NOT_FOUND = 404
|
export const STATUS_NOT_FOUND = 404
|
||||||
|
export const STATUS_CONFLICT = 409
|
||||||
export const STATUS_UNAVAILABLE = 503
|
export const STATUS_UNAVAILABLE = 503
|
||||||
|
|
||||||
export class BridgeError extends Error {
|
export class BridgeError extends Error {
|
||||||
@@ -134,10 +138,25 @@ export class BridgeClient {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/** The scene views the pack's modules show, such as its objects. */
|
/** The scene views the pack's modules show, such as its objects. */
|
||||||
sceneViews(): Promise<ModuleViewInfo[]> {
|
sceneViews(): Promise<SceneViewInfo[]> {
|
||||||
return this.json('scenes')
|
return this.json('scenes')
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** An editable entry's file, as nodes. */
|
||||||
|
sceneFile(viewId: string, key: string, signal?: AbortSignal): Promise<EditorState> {
|
||||||
|
return this.json(`scene-file?${new URLSearchParams({ view: viewId, key })}`, { signal })
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Makes {@code edit} on the file as it was at {@code revision} and saves it; refused with STATUS_CONFLICT when it changed since. */
|
||||||
|
sceneEdit(viewId: string, key: string, revision: string, edit: GraphEdit): Promise<EditorState> {
|
||||||
|
return this.json(`scene-edit?${new URLSearchParams({ view: viewId, key })}`, { method: 'POST', body: JSON.stringify({ revision, edit }) })
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Replaces the whole file, as undoing does; refused with STATUS_CONFLICT when it changed since {@code revision}. */
|
||||||
|
sceneWrite(viewId: string, key: string, revision: string, text: string): Promise<EditorState> {
|
||||||
|
return this.json(`scene-write?${new URLSearchParams({ view: viewId, key })}`, { method: 'POST', body: JSON.stringify({ revision, text }) })
|
||||||
|
}
|
||||||
|
|
||||||
sceneEntries(viewId: string): Promise<SceneEntry[]> {
|
sceneEntries(viewId: string): Promise<SceneEntry[]> {
|
||||||
return this.json(`scene-entries?${new URLSearchParams({ view: viewId })}`)
|
return this.json(`scene-entries?${new URLSearchParams({ view: viewId })}`)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -33,6 +33,96 @@ export interface SceneEntry {
|
|||||||
variants: number
|
variants: number
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** A scene view as the server lists it; `editable` when its entries can be edited as nodes. */
|
||||||
|
export interface SceneViewInfo extends ModuleViewInfo {
|
||||||
|
editable: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Where a value sits in a JSON file: member names and element indices from the root. */
|
||||||
|
export type JsonPath = (string | number)[]
|
||||||
|
|
||||||
|
/** An entry's file as the node editor shows it (StudioEditors.EditorState). */
|
||||||
|
export interface EditorState {
|
||||||
|
/** Where it is below the pack folder. */
|
||||||
|
file: string
|
||||||
|
/** Tells this text from any other; an edit sent with an older one is refused. */
|
||||||
|
revision: string
|
||||||
|
text: string
|
||||||
|
/** The file as nodes, or null when it can't be read as nodes and `problem` says why. */
|
||||||
|
roots: GraphNode[] | null
|
||||||
|
problem: string | null
|
||||||
|
/** Why the file can't be edited here, such as outside a studio world; null when it can. */
|
||||||
|
locked: string | null
|
||||||
|
types: Record<string, SettingsType>
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface GraphNode {
|
||||||
|
kind: string
|
||||||
|
title: string
|
||||||
|
path: JsonPath
|
||||||
|
/** The scene part it draws, or NO_PART. */
|
||||||
|
partId: number
|
||||||
|
roles: string[]
|
||||||
|
settings: NodeSettings[]
|
||||||
|
children: { wire: string; node: GraphNode }[]
|
||||||
|
/** The array a node moved under this one joins; null when nothing can move here. */
|
||||||
|
childList: JsonPath | null
|
||||||
|
movable: boolean
|
||||||
|
duplicable: boolean
|
||||||
|
additions: { label: string; list: JsonPath; literal: string }[]
|
||||||
|
}
|
||||||
|
|
||||||
|
export const NO_PART = -1
|
||||||
|
|
||||||
|
/** The settings of the object at `path`, of schema type `type`, without the members shown as nodes. */
|
||||||
|
export interface NodeSettings {
|
||||||
|
title: string
|
||||||
|
path: JsonPath
|
||||||
|
type: string
|
||||||
|
shownAsNodes: string[]
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A settings type of the pack's schema (SchemaTypes.TypeWire). */
|
||||||
|
export interface SettingsType {
|
||||||
|
description: string
|
||||||
|
options: SettingOption[]
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface SettingOption {
|
||||||
|
name: string
|
||||||
|
description: string
|
||||||
|
required: boolean
|
||||||
|
minimum: number | null
|
||||||
|
maximum: number | null
|
||||||
|
minItems: number | null
|
||||||
|
defaultValue: unknown
|
||||||
|
kind: ValueKind
|
||||||
|
}
|
||||||
|
|
||||||
|
export type ValueKind =
|
||||||
|
| { kind: 'boolean' }
|
||||||
|
| { kind: 'integer' }
|
||||||
|
| { kind: 'decimal' }
|
||||||
|
| { kind: 'text'; format: string }
|
||||||
|
| { kind: 'reference'; reference: string; format: string }
|
||||||
|
| { kind: 'resource'; resource: string }
|
||||||
|
| { kind: 'enum'; constants: { name: string; description: string }[] }
|
||||||
|
| { kind: 'list'; element: ValueKind; unique: boolean }
|
||||||
|
| { kind: 'map'; value: ValueKind }
|
||||||
|
| { kind: 'object'; type: string }
|
||||||
|
| { kind: 'host'; type: string }
|
||||||
|
| { kind: 'any' }
|
||||||
|
|
||||||
|
/** One change the node editor makes (GraphEditRequest). */
|
||||||
|
export type GraphEdit =
|
||||||
|
| { op: 'set'; object: JsonPath; key: string; literal: string }
|
||||||
|
| { op: 'unset'; object: JsonPath; key: string }
|
||||||
|
| { op: 'append'; list: JsonPath; literal: string }
|
||||||
|
| { op: 'addItem'; list: JsonPath }
|
||||||
|
| { op: 'delete'; path: JsonPath }
|
||||||
|
| { op: 'duplicate'; path: JsonPath }
|
||||||
|
| { op: 'move'; path: JsonPath; toList: JsonPath }
|
||||||
|
|
||||||
/** Something a pattern view lays out, such as one of a biome's palettes (IrisApi PatternEntry). */
|
/** Something a pattern view lays out, such as one of a biome's palettes (IrisApi PatternEntry). */
|
||||||
export interface PatternEntry {
|
export interface PatternEntry {
|
||||||
key: string
|
key: string
|
||||||
|
|||||||
@@ -78,15 +78,18 @@ function ContextMenuSubContent({
|
|||||||
className,
|
className,
|
||||||
...props
|
...props
|
||||||
}: React.ComponentProps<typeof ContextMenuPrimitive.SubContent>) {
|
}: React.ComponentProps<typeof ContextMenuPrimitive.SubContent>) {
|
||||||
|
// Portalled like the menu itself: inside it, the menu's blur and scrolling would clip the submenu away.
|
||||||
return (
|
return (
|
||||||
<ContextMenuPrimitive.SubContent
|
<ContextMenuPrimitive.Portal>
|
||||||
data-slot="context-menu-sub-content"
|
<ContextMenuPrimitive.SubContent
|
||||||
className={cn(
|
data-slot="context-menu-sub-content"
|
||||||
"z-50 min-w-[8rem] origin-(--radix-context-menu-content-transform-origin) overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95",
|
className={cn(
|
||||||
className
|
"z-50 min-w-[8rem] origin-(--radix-context-menu-content-transform-origin) overflow-hidden rounded-md border bg-popover p-1 backdrop-blur-sm text-popover-foreground shadow-lg data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95",
|
||||||
)}
|
className
|
||||||
{...props}
|
)}
|
||||||
/>
|
{...props}
|
||||||
|
/>
|
||||||
|
</ContextMenuPrimitive.Portal>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -99,7 +102,7 @@ function ContextMenuContent({
|
|||||||
<ContextMenuPrimitive.Content
|
<ContextMenuPrimitive.Content
|
||||||
data-slot="context-menu-content"
|
data-slot="context-menu-content"
|
||||||
className={cn(
|
className={cn(
|
||||||
"z-50 max-h-(--radix-context-menu-content-available-height) min-w-[8rem] origin-(--radix-context-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95",
|
"z-50 max-h-(--radix-context-menu-content-available-height) min-w-[8rem] origin-(--radix-context-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border bg-popover p-1 text-popover-foreground backdrop-blur-sm shadow-md data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95",
|
||||||
className
|
className
|
||||||
)}
|
)}
|
||||||
{...props}
|
{...props}
|
||||||
|
|||||||
@@ -0,0 +1,35 @@
|
|||||||
|
import { describe, expect, it } from 'vitest'
|
||||||
|
import { EditHistory } from './EditHistory'
|
||||||
|
|
||||||
|
describe('EditHistory', () => {
|
||||||
|
it('undoes back to the text before an edit and redoes forward again', () => {
|
||||||
|
const history = new EditHistory()
|
||||||
|
history.edited('a')
|
||||||
|
|
||||||
|
expect(history.nextUndo()).toBe('a')
|
||||||
|
history.undone('b')
|
||||||
|
expect(history.canUndo).toBe(false)
|
||||||
|
expect(history.nextRedo()).toBe('b')
|
||||||
|
history.redone('a')
|
||||||
|
expect(history.nextUndo()).toBe('a')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('forgets what could be redone once a new edit is made', () => {
|
||||||
|
const history = new EditHistory()
|
||||||
|
history.edited('a')
|
||||||
|
history.undone('b')
|
||||||
|
|
||||||
|
history.edited('a')
|
||||||
|
|
||||||
|
expect(history.canRedo).toBe(false)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('keeps the history as it was when an undo is never written', () => {
|
||||||
|
const history = new EditHistory()
|
||||||
|
history.edited('a')
|
||||||
|
|
||||||
|
history.nextUndo()
|
||||||
|
|
||||||
|
expect(history.canUndo).toBe(true)
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
const KEPT_STEPS = 100
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The texts a file had before each edit, so undoing writes an earlier text back whole. A step is only taken once its
|
||||||
|
* write succeeded, so a refused undo leaves the history as it was.
|
||||||
|
*/
|
||||||
|
export class EditHistory {
|
||||||
|
private readonly undos: string[] = []
|
||||||
|
private readonly redos: string[] = []
|
||||||
|
|
||||||
|
get canUndo(): boolean {
|
||||||
|
return this.undos.length > 0
|
||||||
|
}
|
||||||
|
|
||||||
|
get canRedo(): boolean {
|
||||||
|
return this.redos.length > 0
|
||||||
|
}
|
||||||
|
|
||||||
|
edited(before: string): void {
|
||||||
|
this.undos.push(before)
|
||||||
|
if (this.undos.length > KEPT_STEPS) {
|
||||||
|
this.undos.shift()
|
||||||
|
}
|
||||||
|
this.redos.length = 0
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The text undoing writes, if there is one. */
|
||||||
|
nextUndo(): string | undefined {
|
||||||
|
return this.undos.at(-1)
|
||||||
|
}
|
||||||
|
|
||||||
|
undone(before: string): void {
|
||||||
|
this.undos.pop()
|
||||||
|
this.redos.push(before)
|
||||||
|
}
|
||||||
|
|
||||||
|
nextRedo(): string | undefined {
|
||||||
|
return this.redos.at(-1)
|
||||||
|
}
|
||||||
|
|
||||||
|
redone(before: string): void {
|
||||||
|
this.redos.pop()
|
||||||
|
this.undos.push(before)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
import type { JsonPath } from '../bridge/types'
|
||||||
|
|
||||||
|
/** The value at {@code path} in a parsed file; undefined where nothing is written. */
|
||||||
|
export function valueAt(root: unknown, path: JsonPath): unknown {
|
||||||
|
let current = root
|
||||||
|
for (const step of path) {
|
||||||
|
if (current === null || typeof current !== 'object') {
|
||||||
|
return undefined
|
||||||
|
}
|
||||||
|
current = (current as Record<string | number, unknown>)[step]
|
||||||
|
}
|
||||||
|
return current
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The file parsed, or undefined when it is not JSON (the editor then shows why instead). */
|
||||||
|
export function parsedText(text: string): unknown {
|
||||||
|
try {
|
||||||
|
return JSON.parse(text)
|
||||||
|
} catch {
|
||||||
|
return undefined
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
import { describe, expect, it } from 'vitest'
|
||||||
|
import type { GraphNode, JsonPath } from '../bridge/types'
|
||||||
|
import { NO_PART } from '../bridge/types'
|
||||||
|
import { isWithin, layoutNodes, NODE_WIDTH } from './nodeLayout'
|
||||||
|
|
||||||
|
function node(path: JsonPath, children: GraphNode[] = []): GraphNode {
|
||||||
|
return {
|
||||||
|
kind: 'Stem',
|
||||||
|
title: 'Stem',
|
||||||
|
path,
|
||||||
|
partId: NO_PART,
|
||||||
|
roles: [],
|
||||||
|
settings: [],
|
||||||
|
children: children.map((child) => ({ wire: '', node: child })),
|
||||||
|
childList: null,
|
||||||
|
movable: true,
|
||||||
|
duplicable: true,
|
||||||
|
additions: []
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('layoutNodes', () => {
|
||||||
|
it('sets a parent level with the middle of its children, a column to their left', () => {
|
||||||
|
const layout = layoutNodes([node([], [node(['parts', 0]), node(['parts', 1]), node(['parts', 2])])])
|
||||||
|
const [first, , last, parent] = layout.nodes
|
||||||
|
|
||||||
|
expect(parent.y).toBe((first.y + last.y) / 2)
|
||||||
|
expect(first.x - parent.x).toBeGreaterThan(NODE_WIDTH)
|
||||||
|
expect(layout.wires).toHaveLength(3)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('lays the next root out under the tree before it', () => {
|
||||||
|
const layout = layoutNodes([node([], [node(['parts', 0])]), node(['materials', 0])])
|
||||||
|
const material = layout.nodes.find((placed) => placed.id === JSON.stringify(['materials', 0]))!
|
||||||
|
|
||||||
|
expect(material.x).toBe(0)
|
||||||
|
expect(material.y).toBeGreaterThan(Math.max(...layout.nodes.filter((placed) => placed !== material).map((placed) => placed.y)))
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('isWithin', () => {
|
||||||
|
it('holds for the path itself and what sits inside it, not for a sibling', () => {
|
||||||
|
expect(isWithin(['parts', 0, 'children', 1], ['parts', 0])).toBe(true)
|
||||||
|
expect(isWithin(['parts', 0], ['parts', 0])).toBe(true)
|
||||||
|
expect(isWithin(['parts', 1], ['parts', 0])).toBe(false)
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -0,0 +1,91 @@
|
|||||||
|
import type { GraphNode, JsonPath } from '../bridge/types'
|
||||||
|
|
||||||
|
export const NODE_WIDTH = 168
|
||||||
|
export const NODE_HEIGHT = 46
|
||||||
|
const COLUMN_GAP = 64
|
||||||
|
const ROW_GAP = 10
|
||||||
|
const TREE_GAP = 26
|
||||||
|
|
||||||
|
/** A node where the canvas draws it, by its top left corner; `id` tells it from every other node of the file. */
|
||||||
|
export interface PlacedNode {
|
||||||
|
id: string
|
||||||
|
node: GraphNode
|
||||||
|
x: number
|
||||||
|
y: number
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface PlacedWire {
|
||||||
|
from: PlacedNode
|
||||||
|
to: PlacedNode
|
||||||
|
label: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface NodeLayout {
|
||||||
|
nodes: PlacedNode[]
|
||||||
|
wires: PlacedWire[]
|
||||||
|
width: number
|
||||||
|
height: number
|
||||||
|
}
|
||||||
|
|
||||||
|
export function idOf(path: JsonPath): string {
|
||||||
|
return JSON.stringify(path)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The node at {@code path} among the trees of {@code roots}, or null when there is none, such as after it was deleted. */
|
||||||
|
export function nodeWithPath(roots: GraphNode[], path: JsonPath): GraphNode | null {
|
||||||
|
const id = idOf(path)
|
||||||
|
for (const root of roots) {
|
||||||
|
if (idOf(root.path) === id) {
|
||||||
|
return root
|
||||||
|
}
|
||||||
|
const found = nodeWithPath(
|
||||||
|
root.children.map((link) => link.node),
|
||||||
|
path
|
||||||
|
)
|
||||||
|
if (found !== null) {
|
||||||
|
return found
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Whether {@code path} is {@code ancestor} or sits inside it. */
|
||||||
|
export function isWithin(path: JsonPath, ancestor: JsonPath): boolean {
|
||||||
|
return ancestor.length <= path.length && ancestor.every((step, index) => path[index] === step)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Lays each root's tree out from left to right, a column per generation, one tree under the other. Leaves take a row
|
||||||
|
* each and a parent sits level with the middle of its children, so wires never cross.
|
||||||
|
*/
|
||||||
|
export function layoutNodes(roots: GraphNode[]): NodeLayout {
|
||||||
|
const nodes: PlacedNode[] = []
|
||||||
|
const wires: PlacedWire[] = []
|
||||||
|
let nextTop = 0
|
||||||
|
let width = 0
|
||||||
|
|
||||||
|
const place = (node: GraphNode, depth: number): PlacedNode => {
|
||||||
|
const x = depth * (NODE_WIDTH + COLUMN_GAP)
|
||||||
|
width = Math.max(width, x + NODE_WIDTH)
|
||||||
|
const children = node.children.map((link) => ({ label: link.wire, placed: place(link.node, depth + 1) }))
|
||||||
|
const y = children.length === 0 ? takeRow() : (children[0].placed.y + children[children.length - 1].placed.y) / 2
|
||||||
|
const placed: PlacedNode = { id: idOf(node.path), node, x, y }
|
||||||
|
nodes.push(placed)
|
||||||
|
for (const child of children) {
|
||||||
|
wires.push({ from: placed, to: child.placed, label: child.label })
|
||||||
|
}
|
||||||
|
return placed
|
||||||
|
}
|
||||||
|
|
||||||
|
const takeRow = (): number => {
|
||||||
|
const top = nextTop
|
||||||
|
nextTop += NODE_HEIGHT + ROW_GAP
|
||||||
|
return top
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const root of roots) {
|
||||||
|
place(root, 0)
|
||||||
|
nextTop += TREE_GAP
|
||||||
|
}
|
||||||
|
return { nodes, wires, width, height: Math.max(0, nextTop - ROW_GAP - TREE_GAP) }
|
||||||
|
}
|
||||||
@@ -0,0 +1,122 @@
|
|||||||
|
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||||
|
import { BridgeError, STATUS_CONFLICT, type BridgeClient } from '../bridge/BridgeClient'
|
||||||
|
import type { EditorState, GraphEdit } from '../bridge/types'
|
||||||
|
import { EditHistory } from './EditHistory'
|
||||||
|
|
||||||
|
export interface NodeEditor {
|
||||||
|
/** The entry's file as it is now; null while it is read. */
|
||||||
|
state: EditorState | null
|
||||||
|
saving: boolean
|
||||||
|
canUndo: boolean
|
||||||
|
canRedo: boolean
|
||||||
|
edit(edit: GraphEdit): void
|
||||||
|
undo(): void
|
||||||
|
redo(): void
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Reads an entry's file as nodes and edits it. Edits are sent one after another, each on the text the one before left,
|
||||||
|
* so quick edits never refuse each other; one refused because the file changed elsewhere reads the file again.
|
||||||
|
*/
|
||||||
|
export function useNodeEditor(client: BridgeClient, viewId: string, key: string | null, packRevision: number, tell: (message: string) => void): NodeEditor {
|
||||||
|
const [state, setState] = useState<EditorState | null>(null)
|
||||||
|
const [saving, setSaving] = useState(false)
|
||||||
|
const [, setHistoryChanges] = useState(0)
|
||||||
|
const history = useRef(new EditHistory())
|
||||||
|
const shown = useRef<EditorState | null>(null)
|
||||||
|
const queue = useRef<Promise<void>>(Promise.resolve())
|
||||||
|
const entry = useRef({ viewId, key })
|
||||||
|
|
||||||
|
const run = useCallback(
|
||||||
|
(task: (current: EditorState | null) => Promise<EditorState | null>): void => {
|
||||||
|
const asked = entry.current
|
||||||
|
queue.current = queue.current.then(async () => {
|
||||||
|
if (entry.current !== asked) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
setSaving(true)
|
||||||
|
try {
|
||||||
|
const next = await task(shown.current)
|
||||||
|
if (entry.current === asked && next !== null) {
|
||||||
|
shown.current = next
|
||||||
|
setState(next)
|
||||||
|
}
|
||||||
|
} catch (failure) {
|
||||||
|
if (entry.current !== asked) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
tell((failure as Error).message)
|
||||||
|
if (failure instanceof BridgeError && failure.status === STATUS_CONFLICT && asked.key !== null) {
|
||||||
|
const reread = await client.sceneFile(asked.viewId, asked.key).catch(() => null)
|
||||||
|
if (reread !== null && entry.current === asked) {
|
||||||
|
shown.current = reread
|
||||||
|
setState(reread)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
setSaving(false)
|
||||||
|
setHistoryChanges((changes) => changes + 1)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
},
|
||||||
|
[client, tell]
|
||||||
|
)
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
entry.current = { viewId, key }
|
||||||
|
history.current = new EditHistory()
|
||||||
|
shown.current = null
|
||||||
|
setState(null)
|
||||||
|
}, [viewId, key])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (key !== null) {
|
||||||
|
run(() => client.sceneFile(viewId, key))
|
||||||
|
}
|
||||||
|
}, [client, viewId, key, packRevision, run])
|
||||||
|
|
||||||
|
const edit = useCallback(
|
||||||
|
(change: GraphEdit) =>
|
||||||
|
run(async (current) => {
|
||||||
|
if (current === null || key === null) {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
const next = await client.sceneEdit(viewId, key, current.revision, change)
|
||||||
|
if (next.text !== current.text) {
|
||||||
|
history.current.edited(current.text)
|
||||||
|
}
|
||||||
|
return next
|
||||||
|
}),
|
||||||
|
[client, viewId, key, run]
|
||||||
|
)
|
||||||
|
|
||||||
|
const undo = useCallback(
|
||||||
|
() =>
|
||||||
|
run(async (current) => {
|
||||||
|
const earlier = history.current.nextUndo()
|
||||||
|
if (current === null || key === null || earlier === undefined) {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
const next = await client.sceneWrite(viewId, key, current.revision, earlier)
|
||||||
|
history.current.undone(current.text)
|
||||||
|
return next
|
||||||
|
}),
|
||||||
|
[client, viewId, key, run]
|
||||||
|
)
|
||||||
|
|
||||||
|
const redo = useCallback(
|
||||||
|
() =>
|
||||||
|
run(async (current) => {
|
||||||
|
const later = history.current.nextRedo()
|
||||||
|
if (current === null || key === null || later === undefined) {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
const next = await client.sceneWrite(viewId, key, current.revision, later)
|
||||||
|
history.current.redone(current.text)
|
||||||
|
return next
|
||||||
|
}),
|
||||||
|
[client, viewId, key, run]
|
||||||
|
)
|
||||||
|
|
||||||
|
return { state, saving, canUndo: history.current.canUndo, canRedo: history.current.canRedo, edit, undo, redo }
|
||||||
|
}
|
||||||
@@ -16,7 +16,7 @@ import { PatternStudio } from './PatternStudio'
|
|||||||
import { SavedWorldStudio } from './SavedWorldStudio'
|
import { SavedWorldStudio } from './SavedWorldStudio'
|
||||||
import { SceneStudio } from './SceneStudio'
|
import { SceneStudio } from './SceneStudio'
|
||||||
import { WorldStudio3D } from './WorldStudio3D'
|
import { WorldStudio3D } from './WorldStudio3D'
|
||||||
import { actionForKey, viewForKey, type ShortcutAction } from './shortcuts'
|
import { actionForKey, isTypingInto, viewForKey, type ShortcutAction } from './shortcuts'
|
||||||
import { StatusBar } from './StatusBar'
|
import { StatusBar } from './StatusBar'
|
||||||
import { StudioToolbar } from './StudioToolbar'
|
import { StudioToolbar } from './StudioToolbar'
|
||||||
import { ViewList } from './ViewList'
|
import { ViewList } from './ViewList'
|
||||||
@@ -335,8 +335,8 @@ function statusLabel(viewLabel: string, previewName: string | null, sceneSummary
|
|||||||
}
|
}
|
||||||
|
|
||||||
/** Views the pack's modules show, read again after the pack reloads; keep {@code load} stable. */
|
/** Views the pack's modules show, read again after the pack reloads; keep {@code load} stable. */
|
||||||
function useModuleViews(load: () => Promise<ModuleViewInfo[]>, packRevision: number): ModuleViewInfo[] {
|
function useModuleViews<View extends ModuleViewInfo>(load: () => Promise<View[]>, packRevision: number): View[] {
|
||||||
const [views, setViews] = useState<ModuleViewInfo[]>([])
|
const [views, setViews] = useState<View[]>([])
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
let active = true
|
let active = true
|
||||||
load()
|
load()
|
||||||
@@ -503,7 +503,7 @@ function useKeyboard(
|
|||||||
if (event.key === 'Shift') {
|
if (event.key === 'Shift') {
|
||||||
setDetailed(true)
|
setDetailed(true)
|
||||||
}
|
}
|
||||||
if (event.ctrlKey || event.metaKey || event.altKey || event.target instanceof HTMLInputElement) {
|
if (event.ctrlKey || event.metaKey || event.altKey || isTypingInto(event.target)) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
const viewId = viewForKey(event.key)
|
const viewId = viewForKey(event.key)
|
||||||
|
|||||||
@@ -0,0 +1,300 @@
|
|||||||
|
import { Box, Circle, Flower2, GitCommitVertical, GitFork, Group, Link2, Paintbrush, Sparkles, type LucideIcon } from 'lucide-react'
|
||||||
|
import { useEffect, useMemo, useRef, useState } from 'react'
|
||||||
|
import { ContextMenu, ContextMenuContent, ContextMenuItem, ContextMenuSeparator, ContextMenuSub, ContextMenuSubContent, ContextMenuSubTrigger, ContextMenuTrigger } from '@/components/ui/context-menu'
|
||||||
|
import { cn } from '@/lib/utils'
|
||||||
|
import type { GraphEdit, GraphNode, JsonPath } from '../bridge/types'
|
||||||
|
import { idOf, isWithin, layoutNodes, NODE_HEIGHT, NODE_WIDTH, type NodeLayout, type PlacedNode } from '../editor/nodeLayout'
|
||||||
|
|
||||||
|
const KIND_ICONS: Record<string, LucideIcon> = {
|
||||||
|
Object: Box,
|
||||||
|
Stem: GitCommitVertical,
|
||||||
|
Blob: Circle,
|
||||||
|
Branches: GitFork,
|
||||||
|
Cluster: Sparkles,
|
||||||
|
Group: Group,
|
||||||
|
'Shared part': Link2,
|
||||||
|
Material: Paintbrush,
|
||||||
|
Decoration: Flower2
|
||||||
|
}
|
||||||
|
const FIT_MARGIN = 24
|
||||||
|
const LARGEST_FIT_SCALE = 1
|
||||||
|
// Below this the node text can't be read; a larger tree is panned instead of shrunk further.
|
||||||
|
const SMALLEST_FIT_SCALE = 0.8
|
||||||
|
const SMALLEST_SCALE = 0.25
|
||||||
|
const LARGEST_SCALE = 2
|
||||||
|
const WHEEL_ZOOM_PER_PIXEL = 0.0015
|
||||||
|
const DRAG_START_PIXELS = 4
|
||||||
|
const GRID_SPACING = 16
|
||||||
|
|
||||||
|
interface Camera {
|
||||||
|
x: number
|
||||||
|
y: number
|
||||||
|
scale: number
|
||||||
|
}
|
||||||
|
|
||||||
|
interface NodeDrag {
|
||||||
|
placed: PlacedNode
|
||||||
|
startX: number
|
||||||
|
startY: number
|
||||||
|
pointerX: number
|
||||||
|
pointerY: number
|
||||||
|
moved: boolean
|
||||||
|
target: PlacedNode | null
|
||||||
|
}
|
||||||
|
|
||||||
|
interface NodeCanvasProps {
|
||||||
|
roots: GraphNode[]
|
||||||
|
/** Tells files apart, so a new one is fitted into view. */
|
||||||
|
fileKey: string
|
||||||
|
selectedId: string | null
|
||||||
|
locked: boolean
|
||||||
|
onSelect(node: GraphNode | null): void
|
||||||
|
onEdit(edit: GraphEdit): void
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The file as a tree of nodes: drag the background to look around, drag a node onto another to grow it from there. */
|
||||||
|
export function NodeCanvas({ roots, fileKey, selectedId, locked, onSelect, onEdit }: NodeCanvasProps): React.JSX.Element {
|
||||||
|
const layout = useMemo(() => layoutNodes(roots), [roots])
|
||||||
|
const frame = useRef<HTMLDivElement>(null)
|
||||||
|
const [camera, setCamera] = useCamera(frame, layout, fileKey)
|
||||||
|
const [drag, setDrag] = useState<NodeDrag | null>(null)
|
||||||
|
const [menuNode, setMenuNode] = useState<GraphNode | null>(null)
|
||||||
|
const pan = useRef<{ x: number; y: number } | null>(null)
|
||||||
|
|
||||||
|
const canvasPoint = (clientX: number, clientY: number): { x: number; y: number } => {
|
||||||
|
const bounds = frame.current!.getBoundingClientRect()
|
||||||
|
return { x: (clientX - bounds.left - camera.x) / camera.scale, y: (clientY - bounds.top - camera.y) / camera.scale }
|
||||||
|
}
|
||||||
|
|
||||||
|
const pointerDown = (event: React.PointerEvent): void => {
|
||||||
|
if (event.button !== 0) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
event.currentTarget.setPointerCapture(event.pointerId)
|
||||||
|
const placed = nodeAt(layout, canvasPoint(event.clientX, event.clientY))
|
||||||
|
if (placed === null) {
|
||||||
|
pan.current = { x: event.clientX, y: event.clientY }
|
||||||
|
return
|
||||||
|
}
|
||||||
|
setDrag({ placed, startX: event.clientX, startY: event.clientY, pointerX: event.clientX, pointerY: event.clientY, moved: false, target: null })
|
||||||
|
}
|
||||||
|
|
||||||
|
const pointerMove = (event: React.PointerEvent): void => {
|
||||||
|
if (pan.current !== null) {
|
||||||
|
const [dx, dy] = [event.clientX - pan.current.x, event.clientY - pan.current.y]
|
||||||
|
pan.current = { x: event.clientX, y: event.clientY }
|
||||||
|
setCamera((current) => ({ ...current, x: current.x + dx, y: current.y + dy }))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (drag === null) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
const moved = drag.moved || Math.hypot(event.clientX - drag.startX, event.clientY - drag.startY) > DRAG_START_PIXELS
|
||||||
|
const canMove = moved && !locked && drag.placed.node.movable
|
||||||
|
const target = canMove ? moveTarget(layout, drag.placed, canvasPoint(event.clientX, event.clientY)) : null
|
||||||
|
setDrag({ ...drag, pointerX: event.clientX, pointerY: event.clientY, moved, target })
|
||||||
|
}
|
||||||
|
|
||||||
|
const pointerUp = (): void => {
|
||||||
|
pan.current = null
|
||||||
|
if (drag === null) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (!drag.moved) {
|
||||||
|
onSelect(drag.placed.node)
|
||||||
|
} else if (drag.target !== null) {
|
||||||
|
onEdit({ op: 'move', path: drag.placed.node.path, toList: drag.target.node.childList! })
|
||||||
|
}
|
||||||
|
setDrag(null)
|
||||||
|
}
|
||||||
|
|
||||||
|
const dragging = drag !== null && drag.moved && drag.placed.node.movable && !locked
|
||||||
|
const dragOffset = dragging ? { x: (drag.pointerX - drag.startX) / camera.scale, y: (drag.pointerY - drag.startY) / camera.scale } : null
|
||||||
|
|
||||||
|
return (
|
||||||
|
<ContextMenu onOpenChange={(open) => !open && setMenuNode(null)}>
|
||||||
|
<ContextMenuTrigger asChild>
|
||||||
|
<div
|
||||||
|
ref={frame}
|
||||||
|
className="relative h-full w-full touch-none overflow-hidden bg-background select-none"
|
||||||
|
style={{
|
||||||
|
backgroundImage: 'radial-gradient(var(--overlay-border) 1px, transparent 1px)',
|
||||||
|
backgroundSize: `${GRID_SPACING * camera.scale}px ${GRID_SPACING * camera.scale}px`,
|
||||||
|
backgroundPosition: `${camera.x}px ${camera.y}px`
|
||||||
|
}}
|
||||||
|
onPointerDown={pointerDown}
|
||||||
|
onPointerMove={pointerMove}
|
||||||
|
onPointerUp={pointerUp}
|
||||||
|
onPointerCancel={() => {
|
||||||
|
pan.current = null
|
||||||
|
setDrag(null)
|
||||||
|
}}
|
||||||
|
onContextMenu={(event) => {
|
||||||
|
const placed = nodeAt(layout, canvasPoint(event.clientX, event.clientY))
|
||||||
|
setMenuNode(placed?.node ?? null)
|
||||||
|
if (placed === null) {
|
||||||
|
event.preventDefault()
|
||||||
|
} else {
|
||||||
|
onSelect(placed.node)
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
onDoubleClick={(event) => nodeAt(layout, canvasPoint(event.clientX, event.clientY)) === null && setCamera(fitted(frame.current!, layout))}
|
||||||
|
>
|
||||||
|
<div className="absolute top-0 left-0 origin-top-left" style={{ transform: `translate(${camera.x}px, ${camera.y}px) scale(${camera.scale})` }}>
|
||||||
|
<Wires layout={layout} />
|
||||||
|
{layout.nodes.map((placed) => (
|
||||||
|
<NodeBox
|
||||||
|
key={placed.id}
|
||||||
|
placed={placed}
|
||||||
|
selected={placed.id === selectedId}
|
||||||
|
target={drag?.target?.id === placed.id}
|
||||||
|
offset={dragging && drag.placed.id === placed.id ? dragOffset : null}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</ContextMenuTrigger>
|
||||||
|
{menuNode !== null && <NodeMenu node={menuNode} locked={locked} onEdit={onEdit} />}
|
||||||
|
</ContextMenu>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function NodeBox({ placed, selected, target, offset }: { placed: PlacedNode; selected: boolean; target: boolean; offset: { x: number; y: number } | null }): React.JSX.Element {
|
||||||
|
const { node } = placed
|
||||||
|
const Icon = KIND_ICONS[node.kind] ?? Box
|
||||||
|
const detail = node.roles.length > 0 ? node.roles.join(', ') : node.title === node.kind ? null : node.kind
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
className={cn(
|
||||||
|
'absolute flex items-center gap-2 rounded-md border bg-card px-2.5 shadow-xs',
|
||||||
|
selected ? 'border-primary ring-1 ring-primary' : 'border-overlay-border',
|
||||||
|
target && 'border-primary bg-selection',
|
||||||
|
offset !== null && 'z-10 opacity-80 shadow-md'
|
||||||
|
)}
|
||||||
|
style={{
|
||||||
|
left: placed.x + (offset?.x ?? 0),
|
||||||
|
top: placed.y + (offset?.y ?? 0),
|
||||||
|
width: NODE_WIDTH,
|
||||||
|
height: NODE_HEIGHT,
|
||||||
|
cursor: node.movable ? 'grab' : 'default'
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Icon className="size-4 shrink-0 text-secondary-text" />
|
||||||
|
<div className="min-w-0 leading-tight">
|
||||||
|
<div className="truncate text-[12.5px] font-medium">{node.title}</div>
|
||||||
|
{detail !== null && <div className="truncate text-[11px] text-secondary-text">{detail}</div>}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function Wires({ layout }: { layout: NodeLayout }): React.JSX.Element {
|
||||||
|
return (
|
||||||
|
<svg className="pointer-events-none absolute top-0 left-0 overflow-visible" width={layout.width} height={layout.height}>
|
||||||
|
{layout.wires.map(({ from, to, label }) => {
|
||||||
|
const [startX, startY] = [from.x + NODE_WIDTH, from.y + NODE_HEIGHT / 2]
|
||||||
|
const [endX, endY] = [to.x, to.y + NODE_HEIGHT / 2]
|
||||||
|
const bend = (endX - startX) / 2
|
||||||
|
return (
|
||||||
|
<g key={`${from.id}>${to.id}`}>
|
||||||
|
<path d={`M${startX},${startY} C${startX + bend},${startY} ${endX - bend},${endY} ${endX},${endY}`} className="fill-none stroke-input" strokeWidth={1.5} />
|
||||||
|
{label !== '' && (
|
||||||
|
<text x={endX - 6} y={endY - 6} textAnchor="end" className="fill-secondary-text text-[10.5px]">
|
||||||
|
{label}
|
||||||
|
</text>
|
||||||
|
)}
|
||||||
|
</g>
|
||||||
|
)
|
||||||
|
})}
|
||||||
|
</svg>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function NodeMenu({ node, locked, onEdit }: { node: GraphNode; locked: boolean; onEdit(edit: GraphEdit): void }): React.JSX.Element {
|
||||||
|
const removable = node.duplicable
|
||||||
|
return (
|
||||||
|
<ContextMenuContent className="min-w-[180px]">
|
||||||
|
{node.additions.length > 0 && (
|
||||||
|
<ContextMenuSub>
|
||||||
|
<ContextMenuSubTrigger disabled={locked}>Add</ContextMenuSubTrigger>
|
||||||
|
<ContextMenuSubContent>
|
||||||
|
{node.additions.map((addition) => (
|
||||||
|
<ContextMenuItem key={`${idOf(addition.list)}:${addition.label}`} onSelect={() => onEdit({ op: 'append', list: addition.list, literal: addition.literal })}>
|
||||||
|
{addition.label}
|
||||||
|
</ContextMenuItem>
|
||||||
|
))}
|
||||||
|
</ContextMenuSubContent>
|
||||||
|
</ContextMenuSub>
|
||||||
|
)}
|
||||||
|
<ContextMenuItem disabled={locked || !node.duplicable} onSelect={() => onEdit({ op: 'duplicate', path: node.path })}>
|
||||||
|
Duplicate
|
||||||
|
</ContextMenuItem>
|
||||||
|
<ContextMenuSeparator />
|
||||||
|
<ContextMenuItem variant="destructive" disabled={locked || !removable} onSelect={() => onEdit({ op: 'delete', path: node.path })}>
|
||||||
|
Delete
|
||||||
|
</ContextMenuItem>
|
||||||
|
</ContextMenuContent>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function nodeAt(layout: NodeLayout, point: { x: number; y: number }): PlacedNode | null {
|
||||||
|
return layout.nodes.find((placed) => point.x >= placed.x && point.x <= placed.x + NODE_WIDTH && point.y >= placed.y && point.y <= placed.y + NODE_HEIGHT) ?? null
|
||||||
|
}
|
||||||
|
|
||||||
|
// A node can grow from any other that takes children, except from inside itself or from where it already grows.
|
||||||
|
function moveTarget(layout: NodeLayout, dragged: PlacedNode, point: { x: number; y: number }): PlacedNode | null {
|
||||||
|
const over = nodeAt(layout, point)
|
||||||
|
const toList = over?.node.childList
|
||||||
|
if (over === null || toList === null || toList === undefined || isWithin(toList, dragged.node.path) || isParentList(dragged.node.path, toList)) {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
return over
|
||||||
|
}
|
||||||
|
|
||||||
|
function isParentList(path: JsonPath, list: JsonPath): boolean {
|
||||||
|
return path.length === list.length + 1 && isWithin(path, list)
|
||||||
|
}
|
||||||
|
|
||||||
|
function useCamera(frame: React.RefObject<HTMLDivElement | null>, layout: NodeLayout, fileKey: string): [Camera, React.Dispatch<React.SetStateAction<Camera>>] {
|
||||||
|
const [camera, setCamera] = useState<Camera>({ x: FIT_MARGIN, y: FIT_MARGIN, scale: 1 })
|
||||||
|
const fittedFile = useRef<string | null>(null)
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (frame.current === null || layout.nodes.length === 0 || fittedFile.current === fileKey) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
fittedFile.current = fileKey
|
||||||
|
setCamera(fitted(frame.current, layout))
|
||||||
|
}, [frame, layout, fileKey])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const element = frame.current
|
||||||
|
if (element === null) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
const wheel = (event: WheelEvent): void => {
|
||||||
|
event.preventDefault()
|
||||||
|
const bounds = element.getBoundingClientRect()
|
||||||
|
const [pointerX, pointerY] = [event.clientX - bounds.left, event.clientY - bounds.top]
|
||||||
|
setCamera((current) => {
|
||||||
|
const scale = clamp(current.scale * Math.exp(-event.deltaY * WHEEL_ZOOM_PER_PIXEL), SMALLEST_SCALE, LARGEST_SCALE)
|
||||||
|
const ratio = scale / current.scale
|
||||||
|
return { scale, x: pointerX - (pointerX - current.x) * ratio, y: pointerY - (pointerY - current.y) * ratio }
|
||||||
|
})
|
||||||
|
}
|
||||||
|
element.addEventListener('wheel', wheel, { passive: false })
|
||||||
|
return () => element.removeEventListener('wheel', wheel)
|
||||||
|
}, [frame])
|
||||||
|
|
||||||
|
return [camera, setCamera]
|
||||||
|
}
|
||||||
|
|
||||||
|
function fitted(frame: HTMLDivElement, layout: NodeLayout): Camera {
|
||||||
|
const [width, height] = [frame.clientWidth - 2 * FIT_MARGIN, frame.clientHeight - 2 * FIT_MARGIN]
|
||||||
|
const scale = clamp(Math.min(width / Math.max(layout.width, 1), height / Math.max(layout.height, 1)), SMALLEST_FIT_SCALE, LARGEST_FIT_SCALE)
|
||||||
|
return { scale, x: FIT_MARGIN, y: FIT_MARGIN + Math.max(0, (height - layout.height * scale) / 2) }
|
||||||
|
}
|
||||||
|
|
||||||
|
function clamp(value: number, lowest: number, highest: number): number {
|
||||||
|
return Math.min(highest, Math.max(lowest, value))
|
||||||
|
}
|
||||||
@@ -0,0 +1,231 @@
|
|||||||
|
import { RotateCcw } from 'lucide-react'
|
||||||
|
import { useState } from 'react'
|
||||||
|
import { Button } from '@/components/ui/button'
|
||||||
|
import { Input } from '@/components/ui/input'
|
||||||
|
import { ScrollArea } from '@/components/ui/scroll-area'
|
||||||
|
import { cn } from '@/lib/utils'
|
||||||
|
import type { EditorState, GraphEdit, GraphNode, NodeSettings, SettingOption, ValueKind } from '../bridge/types'
|
||||||
|
import { valueAt } from '../editor/jsonValues'
|
||||||
|
|
||||||
|
const NOT_SET = ''
|
||||||
|
|
||||||
|
interface NodeInspectorProps {
|
||||||
|
node: GraphNode
|
||||||
|
state: EditorState
|
||||||
|
/** The file parsed, to read what each setting is set to. */
|
||||||
|
values: unknown
|
||||||
|
onEdit(edit: GraphEdit): void
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The settings of the chosen node, a field per option of its schema type; an empty field leaves the option unset. */
|
||||||
|
export function NodeInspector({ node, state, values, onEdit }: NodeInspectorProps): React.JSX.Element {
|
||||||
|
const locked = state.locked !== null
|
||||||
|
return (
|
||||||
|
<section className="flex min-h-0 flex-[7] flex-col">
|
||||||
|
<header className="px-4 pt-2.5 pb-1.5">
|
||||||
|
<h2 className="truncate text-[13px] font-semibold">{node.title}</h2>
|
||||||
|
<p className="truncate text-[11.5px] text-secondary-text">{node.roles.length > 0 ? node.roles.join(', ') : node.kind}</p>
|
||||||
|
</header>
|
||||||
|
<ScrollArea className="min-h-0 flex-1 border-t">
|
||||||
|
<div className="pb-3">
|
||||||
|
{node.settings.map((section) => (
|
||||||
|
<SettingsSection key={JSON.stringify(section.path) + section.type} section={section} state={state} values={values} locked={locked} onEdit={onEdit} />
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</ScrollArea>
|
||||||
|
</section>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function SettingsSection({
|
||||||
|
section,
|
||||||
|
state,
|
||||||
|
values,
|
||||||
|
locked,
|
||||||
|
onEdit
|
||||||
|
}: {
|
||||||
|
section: NodeSettings
|
||||||
|
state: EditorState
|
||||||
|
values: unknown
|
||||||
|
locked: boolean
|
||||||
|
onEdit(edit: GraphEdit): void
|
||||||
|
}): React.JSX.Element {
|
||||||
|
const type = state.types[section.type]
|
||||||
|
const options = type?.options.filter((option) => !section.shownAsNodes.includes(option.name)) ?? []
|
||||||
|
return (
|
||||||
|
<section className="px-4 pt-3">
|
||||||
|
<h3 className="pb-1 text-[11px] font-semibold text-muted-foreground" title={type?.description}>
|
||||||
|
{section.title}
|
||||||
|
</h3>
|
||||||
|
{options.map((option) => {
|
||||||
|
const value = valueAt(values, [...section.path, option.name])
|
||||||
|
return (
|
||||||
|
<SettingField
|
||||||
|
key={`${option.name}=${JSON.stringify(value)}`}
|
||||||
|
option={option}
|
||||||
|
value={value}
|
||||||
|
locked={locked}
|
||||||
|
onSet={(literal) => onEdit({ op: 'set', object: section.path, key: option.name, literal })}
|
||||||
|
onUnset={() => onEdit({ op: 'unset', object: section.path, key: option.name })}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
})}
|
||||||
|
</section>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
interface SettingFieldProps {
|
||||||
|
option: SettingOption
|
||||||
|
/** What the file sets it to; undefined when it is not set. */
|
||||||
|
value: unknown
|
||||||
|
locked: boolean
|
||||||
|
onSet(literal: string): void
|
||||||
|
onUnset(): void
|
||||||
|
}
|
||||||
|
|
||||||
|
function SettingField(props: SettingFieldProps): React.JSX.Element {
|
||||||
|
const kind = props.option.kind.kind
|
||||||
|
return kind === 'boolean' || kind === 'enum' ? <ChoiceField {...props} /> : <TypedField {...props} />
|
||||||
|
}
|
||||||
|
|
||||||
|
function FieldRow({ option, value, locked, onUnset, problem, children }: SettingFieldProps & { problem: string | null; children: React.ReactNode }): React.JSX.Element {
|
||||||
|
return (
|
||||||
|
<div className="py-0.5">
|
||||||
|
<div className="flex h-7 items-center gap-2">
|
||||||
|
<label className={cn('min-w-0 flex-[4] truncate text-[12px]', option.required && 'font-medium')} title={option.description}>
|
||||||
|
{option.name}
|
||||||
|
</label>
|
||||||
|
<div className="flex min-w-0 flex-[6] items-center gap-1">
|
||||||
|
{children}
|
||||||
|
<Button variant="ghost" size="icon-sm" title="Unset" className={cn('size-6 shrink-0', value === undefined && 'invisible')} disabled={locked} onClick={onUnset}>
|
||||||
|
<RotateCcw className="size-3.5" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{problem !== null && <p className="pt-0.5 text-right text-[11px] text-destructive">{problem}</p>}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function ChoiceField(props: SettingFieldProps): React.JSX.Element {
|
||||||
|
const { option, value, locked, onSet, onUnset } = props
|
||||||
|
const choices = option.kind.kind === 'enum' ? option.kind.constants.map((constant) => constant.name) : ['true', 'false']
|
||||||
|
const literalOf = (choice: string): string => (option.kind.kind === 'enum' ? JSON.stringify(choice) : choice)
|
||||||
|
return (
|
||||||
|
<FieldRow {...props} problem={null}>
|
||||||
|
<select
|
||||||
|
className="h-7 w-full min-w-0 rounded-md border border-input bg-transparent px-1.5 text-[12px] outline-none focus-visible:border-ring dark:bg-input/30"
|
||||||
|
value={value === undefined ? NOT_SET : String(value)}
|
||||||
|
disabled={locked}
|
||||||
|
title={option.description}
|
||||||
|
onChange={(event) => (event.target.value === NOT_SET ? onUnset() : onSet(literalOf(event.target.value)))}
|
||||||
|
>
|
||||||
|
<option value={NOT_SET}>{defaultLabel(option)}</option>
|
||||||
|
{choices.map((choice) => (
|
||||||
|
<option key={choice} value={choice}>
|
||||||
|
{choice}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
</FieldRow>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Numbers, text and anything else are typed in; a draft that does not fit the option says why and is not written.
|
||||||
|
function TypedField(props: SettingFieldProps): React.JSX.Element {
|
||||||
|
const { option, value, locked, onSet, onUnset } = props
|
||||||
|
const shown = textOf(option.kind, value)
|
||||||
|
const [draft, setDraft] = useState(shown)
|
||||||
|
const problem = draft.trim() === NOT_SET ? null : problemWith(option, draft)
|
||||||
|
const commit = (): void => {
|
||||||
|
if (draft === shown || problem !== null) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (draft.trim() === NOT_SET) {
|
||||||
|
onUnset()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
onSet(literalOf(option.kind, draft))
|
||||||
|
}
|
||||||
|
return (
|
||||||
|
<FieldRow {...props} problem={problem}>
|
||||||
|
<Input
|
||||||
|
value={draft}
|
||||||
|
disabled={locked}
|
||||||
|
placeholder={defaultLabel(option)}
|
||||||
|
aria-invalid={problem !== null}
|
||||||
|
title={option.description}
|
||||||
|
inputMode={isNumber(option.kind) ? 'decimal' : undefined}
|
||||||
|
className={cn('h-7 px-2 text-[12px] md:text-[12px]', isNumber(option.kind) ? 'tabular-nums' : !isText(option.kind) && 'font-mono text-[11.5px] placeholder:font-sans md:text-[11.5px]')}
|
||||||
|
onChange={(event) => setDraft(event.target.value)}
|
||||||
|
onBlur={commit}
|
||||||
|
onKeyDown={(event) => {
|
||||||
|
if (event.key === 'Enter') {
|
||||||
|
commit()
|
||||||
|
} else if (event.key === 'Escape') {
|
||||||
|
setDraft(shown)
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</FieldRow>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function defaultLabel(option: SettingOption): string {
|
||||||
|
if (option.defaultValue === null || option.defaultValue === undefined) {
|
||||||
|
return option.required ? 'Required' : 'Not set'
|
||||||
|
}
|
||||||
|
const text = typeof option.defaultValue === 'string' ? option.defaultValue : JSON.stringify(option.defaultValue)
|
||||||
|
return `Default ${text}`
|
||||||
|
}
|
||||||
|
|
||||||
|
function isNumber(kind: ValueKind): boolean {
|
||||||
|
return kind.kind === 'integer' || kind.kind === 'decimal'
|
||||||
|
}
|
||||||
|
|
||||||
|
function isText(kind: ValueKind): boolean {
|
||||||
|
return kind.kind === 'text' || kind.kind === 'reference' || kind.kind === 'resource'
|
||||||
|
}
|
||||||
|
|
||||||
|
function textOf(kind: ValueKind, value: unknown): string {
|
||||||
|
if (value === undefined) {
|
||||||
|
return NOT_SET
|
||||||
|
}
|
||||||
|
return isText(kind) && typeof value === 'string' ? value : JSON.stringify(value)
|
||||||
|
}
|
||||||
|
|
||||||
|
function literalOf(kind: ValueKind, draft: string): string {
|
||||||
|
return isText(kind) ? JSON.stringify(draft) : draft.trim()
|
||||||
|
}
|
||||||
|
|
||||||
|
function problemWith(option: SettingOption, draft: string): string | null {
|
||||||
|
if (isText(option.kind)) {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
if (!isNumber(option.kind)) {
|
||||||
|
return isJson(draft) ? null : 'Not JSON'
|
||||||
|
}
|
||||||
|
const number = Number(draft)
|
||||||
|
if (draft.trim() === '' || !Number.isFinite(number)) {
|
||||||
|
return 'Not a number'
|
||||||
|
}
|
||||||
|
if (option.kind.kind === 'integer' && !Number.isInteger(number)) {
|
||||||
|
return 'Not a whole number'
|
||||||
|
}
|
||||||
|
if (option.minimum !== null && number < option.minimum) {
|
||||||
|
return `At least ${option.minimum}`
|
||||||
|
}
|
||||||
|
if (option.maximum !== null && number > option.maximum) {
|
||||||
|
return `At most ${option.maximum}`
|
||||||
|
}
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
function isJson(text: string): boolean {
|
||||||
|
try {
|
||||||
|
JSON.parse(text)
|
||||||
|
return true
|
||||||
|
} catch {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,95 @@
|
|||||||
|
import { Lock, Redo2, Undo2 } from 'lucide-react'
|
||||||
|
import { useEffect } from 'react'
|
||||||
|
import { Button } from '@/components/ui/button'
|
||||||
|
import type { GraphNode } from '../bridge/types'
|
||||||
|
import type { NodeEditor } from '../editor/useNodeEditor'
|
||||||
|
import { NodeCanvas } from './NodeCanvas'
|
||||||
|
import { isTypingInto } from './shortcuts'
|
||||||
|
|
||||||
|
interface NodePaneProps {
|
||||||
|
editor: NodeEditor
|
||||||
|
/** The entry the file belongs to. */
|
||||||
|
entryKey: string
|
||||||
|
selected: GraphNode | null
|
||||||
|
onSelect(node: GraphNode | null): void
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The node editor under the scene: the entry's file as nodes, with undo and redo. */
|
||||||
|
export function NodePane({ editor, entryKey, selected, onSelect }: NodePaneProps): React.JSX.Element {
|
||||||
|
const { state } = editor
|
||||||
|
const locked = state === null || state.locked !== null
|
||||||
|
useEditorKeys(editor, selected, locked)
|
||||||
|
|
||||||
|
return (
|
||||||
|
<section className="flex min-h-0 flex-[9] flex-col border-t">
|
||||||
|
<header className="flex h-9 shrink-0 items-center gap-2 border-b bg-card px-3">
|
||||||
|
<h2 className="text-[12px] font-semibold">Nodes</h2>
|
||||||
|
<span className="min-w-0 truncate text-[11.5px] text-secondary-text">{state?.file ?? entryKey}</span>
|
||||||
|
<span className="flex-1" />
|
||||||
|
{state?.locked != null && (
|
||||||
|
<span className="flex items-center gap-1 text-[11.5px] text-secondary-text">
|
||||||
|
<Lock className="size-3.5" />
|
||||||
|
{state.locked}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
{editor.saving && <span className="text-[11.5px] text-secondary-text">Saving…</span>}
|
||||||
|
<Button variant="ghost" size="icon-sm" title="Undo (Ctrl+Z)" disabled={locked || !editor.canUndo} onClick={editor.undo}>
|
||||||
|
<Undo2 />
|
||||||
|
</Button>
|
||||||
|
<Button variant="ghost" size="icon-sm" title="Redo (Ctrl+Shift+Z)" disabled={locked || !editor.canRedo} onClick={editor.redo}>
|
||||||
|
<Redo2 />
|
||||||
|
</Button>
|
||||||
|
</header>
|
||||||
|
<div className="relative min-h-0 flex-1">
|
||||||
|
{state === null && <p className="p-4 text-[12px] text-muted-foreground">Reading the file…</p>}
|
||||||
|
{state !== null && state.roots === null && (
|
||||||
|
<div className="p-4 text-[12px]">
|
||||||
|
<p className="font-medium">This file can't be shown as nodes</p>
|
||||||
|
<p className="pt-1 text-secondary-text">{state.problem}</p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{state !== null && state.roots !== null && (
|
||||||
|
<NodeCanvas
|
||||||
|
roots={state.roots}
|
||||||
|
fileKey={entryKey}
|
||||||
|
selectedId={selected === null ? null : JSON.stringify(selected.path)}
|
||||||
|
locked={locked}
|
||||||
|
onSelect={onSelect}
|
||||||
|
onEdit={editor.edit}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function useEditorKeys(editor: NodeEditor, selected: GraphNode | null, locked: boolean): void {
|
||||||
|
const { undo, redo, edit } = editor
|
||||||
|
useEffect(() => {
|
||||||
|
if (locked) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
const down = (event: KeyboardEvent): void => {
|
||||||
|
if (isTypingInto(event.target)) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
const command = event.ctrlKey || event.metaKey
|
||||||
|
if (command && event.key.toLowerCase() === 'z') {
|
||||||
|
event.preventDefault()
|
||||||
|
if (event.shiftKey) {
|
||||||
|
redo()
|
||||||
|
} else {
|
||||||
|
undo()
|
||||||
|
}
|
||||||
|
} else if (command && event.key.toLowerCase() === 'y') {
|
||||||
|
event.preventDefault()
|
||||||
|
redo()
|
||||||
|
} else if (event.key === 'Delete' && selected !== null && selected.duplicable) {
|
||||||
|
event.preventDefault()
|
||||||
|
edit({ op: 'delete', path: selected.path })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
window.addEventListener('keydown', down)
|
||||||
|
return () => window.removeEventListener('keydown', down)
|
||||||
|
}, [undo, redo, edit, selected, locked])
|
||||||
|
}
|
||||||
@@ -2,13 +2,19 @@ import { ChevronLeft, ChevronRight } from 'lucide-react'
|
|||||||
import { useEffect, useMemo, useState } from 'react'
|
import { useEffect, useMemo, useState } from 'react'
|
||||||
import { Button } from '@/components/ui/button'
|
import { Button } from '@/components/ui/button'
|
||||||
import { ScrollArea } from '@/components/ui/scroll-area'
|
import { ScrollArea } from '@/components/ui/scroll-area'
|
||||||
|
import { cn } from '@/lib/utils'
|
||||||
import type { BridgeClient } from '../bridge/BridgeClient'
|
import type { BridgeClient } from '../bridge/BridgeClient'
|
||||||
import type { ModuleViewInfo, SceneEntry } from '../bridge/types'
|
import type { JsonPath, SceneEntry, SceneViewInfo } from '../bridge/types'
|
||||||
|
import { parsedText } from '../editor/jsonValues'
|
||||||
|
import { nodeWithPath } from '../editor/nodeLayout'
|
||||||
|
import { useNodeEditor } from '../editor/useNodeEditor'
|
||||||
import { BlockModels } from '../scene/blockModels'
|
import { BlockModels } from '../scene/blockModels'
|
||||||
import { BridgeAssets } from '../scene/BridgeAssets'
|
import { BridgeAssets } from '../scene/BridgeAssets'
|
||||||
import { INTS_PER_BLOCK, type BlockScene } from '../scene/sceneDecoding'
|
import { INTS_PER_BLOCK, type BlockScene } from '../scene/sceneDecoding'
|
||||||
import { buildSceneMesh, type SceneMesh } from '../scene/sceneMesh'
|
import { buildSceneMesh, type SceneMesh } from '../scene/sceneMesh'
|
||||||
import { EntryBrowser } from './EntryBrowser'
|
import { EntryBrowser } from './EntryBrowser'
|
||||||
|
import { NodeInspector } from './NodeInspector'
|
||||||
|
import { NodePane } from './NodePane'
|
||||||
import { SceneViewport } from './SceneViewport'
|
import { SceneViewport } from './SceneViewport'
|
||||||
|
|
||||||
const NUMBER = new Intl.NumberFormat('en-US')
|
const NUMBER = new Intl.NumberFormat('en-US')
|
||||||
@@ -16,7 +22,7 @@ const DEFAULT_NAMESPACE_PREFIX = 'minecraft:'
|
|||||||
|
|
||||||
interface SceneStudioProps {
|
interface SceneStudioProps {
|
||||||
client: BridgeClient
|
client: BridgeClient
|
||||||
view: ModuleViewInfo
|
view: SceneViewInfo
|
||||||
/** Changes when the pack reloads, so the entries and the scene are read again. */
|
/** Changes when the pack reloads, so the entries and the scene are read again. */
|
||||||
packRevision: number
|
packRevision: number
|
||||||
/** What the status bar says about the scene, or null while none is shown. */
|
/** What the status bar says about the scene, or null while none is shown. */
|
||||||
@@ -24,7 +30,10 @@ interface SceneStudioProps {
|
|||||||
tell(message: string): void
|
tell(message: string): void
|
||||||
}
|
}
|
||||||
|
|
||||||
/** A scene view: its entries on the right, the chosen one in 3D in the middle, with the blocks it is made of. */
|
/**
|
||||||
|
* A scene view: its entries on the right, the chosen one in 3D in the middle, with the blocks it is made of. An
|
||||||
|
* editable view shows the entry's file as nodes under the scene, and the chosen node's settings on the right.
|
||||||
|
*/
|
||||||
export function SceneStudio({ client, view, packRevision, onSummary, tell }: SceneStudioProps): React.JSX.Element {
|
export function SceneStudio({ client, view, packRevision, onSummary, tell }: SceneStudioProps): React.JSX.Element {
|
||||||
const [waiting, setWaiting] = useState<string | null>(null)
|
const [waiting, setWaiting] = useState<string | null>(null)
|
||||||
const images = useMemo(() => new BridgeAssets(client, setWaiting), [client])
|
const images = useMemo(() => new BridgeAssets(client, setWaiting), [client])
|
||||||
@@ -40,37 +49,73 @@ export function SceneStudio({ client, view, packRevision, onSummary, tell }: Sce
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const editor = useNodeEditor(client, view.id, view.editable ? (entry?.key ?? null) : null, packRevision, tell)
|
||||||
|
const [selectedPath, setSelectedPath] = useState<JsonPath | null>(null)
|
||||||
|
const selected = editor.state?.roots != null && selectedPath !== null ? nodeWithPath(editor.state.roots, selectedPath) : null
|
||||||
|
const values = useMemo(() => (editor.state === null ? undefined : parsedText(editor.state.text)), [editor.state])
|
||||||
|
|
||||||
useEffect(() => onSummary(entry === null || scene === null ? null : summaryOf(entry, scene)), [entry, scene, onSummary])
|
useEffect(() => onSummary(entry === null || scene === null ? null : summaryOf(entry, scene)), [entry, scene, onSummary])
|
||||||
useEffect(() => () => onSummary(null), [onSummary])
|
useEffect(() => () => onSummary(null), [onSummary])
|
||||||
|
useEffect(() => setSelectedPath(null), [entry?.key])
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<div className="relative min-w-0 flex-1">
|
<div className="flex min-w-0 flex-1 flex-col">
|
||||||
<SceneViewport content={mesh?.content ?? null} framing={mesh} />
|
<SceneArea
|
||||||
|
entry={entry}
|
||||||
|
variant={variant}
|
||||||
|
mesh={mesh}
|
||||||
|
status={building && entry !== null ? (waiting ?? `Building ${entry.name}`) : null}
|
||||||
|
onVariant={chooseVariant}
|
||||||
|
/>
|
||||||
|
{view.editable && entry !== null && (
|
||||||
|
<NodePane editor={editor} entryKey={entry.key} selected={selected} onSelect={(node) => setSelectedPath(node?.path ?? null)} />
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<aside className={cn('flex shrink-0 flex-col border-l bg-card', view.editable ? 'w-[300px]' : 'w-[250px]')}>
|
||||||
|
<EntryBrowser className={selected === null ? 'flex-[7]' : 'flex-[3]'} title={view.label} entries={entries} current={entry?.key ?? null} onSelect={(key) => setChosen({ key, variant: 0 })} />
|
||||||
|
{selected !== null && editor.state !== null ? (
|
||||||
|
<NodeInspector key={JSON.stringify(selected.path)} node={selected} state={editor.state} values={values} onEdit={editor.edit} />
|
||||||
|
) : (
|
||||||
|
<BlockList scene={scene} />
|
||||||
|
)}
|
||||||
|
</aside>
|
||||||
|
</>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
interface SceneAreaProps {
|
||||||
|
entry: SceneEntry | null
|
||||||
|
variant: number
|
||||||
|
mesh: SceneMesh | null
|
||||||
|
/** What is being built, or null when nothing is. */
|
||||||
|
status: string | null
|
||||||
|
onVariant(variant: number): void
|
||||||
|
}
|
||||||
|
|
||||||
|
function SceneArea({ entry, variant, mesh, status, onVariant }: SceneAreaProps): React.JSX.Element {
|
||||||
|
return (
|
||||||
|
<div className="relative min-h-0 flex-[11]">
|
||||||
|
<SceneViewport content={mesh?.content ?? null} framing={mesh} />
|
||||||
{entry !== null && entry.variants > 1 && (
|
{entry !== null && entry.variants > 1 && (
|
||||||
<div className="absolute top-3 left-3 flex items-center gap-1 rounded-md border border-overlay-border bg-card/90 p-1 text-[12px] tabular-nums">
|
<div className="absolute top-3 left-3 flex items-center gap-1 rounded-md border border-overlay-border bg-card/90 p-1 text-[12px] tabular-nums">
|
||||||
<Button variant="ghost" size="icon-sm" title="Previous variant" onClick={() => chooseVariant(variant - 1)}>
|
<Button variant="ghost" size="icon-sm" title="Previous variant" onClick={() => onVariant(variant - 1)}>
|
||||||
<ChevronLeft />
|
<ChevronLeft />
|
||||||
</Button>
|
</Button>
|
||||||
<span className="px-1">
|
<span className="px-1">
|
||||||
Variant {variant + 1} of {entry.variants}
|
Variant {variant + 1} of {entry.variants}
|
||||||
</span>
|
</span>
|
||||||
<Button variant="ghost" size="icon-sm" title="Next variant" onClick={() => chooseVariant(variant + 1)}>
|
<Button variant="ghost" size="icon-sm" title="Next variant" onClick={() => onVariant(variant + 1)}>
|
||||||
<ChevronRight />
|
<ChevronRight />
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
{building && entry !== null && (
|
{status !== null && (
|
||||||
<div className="pointer-events-none absolute top-3 left-1/2 -translate-x-1/2 rounded-md border border-overlay-border bg-card/90 px-3 py-1.5 text-[12px] text-secondary-text">
|
<div className="pointer-events-none absolute top-3 left-1/2 -translate-x-1/2 rounded-md border border-overlay-border bg-card/90 px-3 py-1.5 text-[12px] text-secondary-text">
|
||||||
{waiting ?? `Building ${entry.name}`}
|
{status}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
<aside className="flex w-[250px] shrink-0 flex-col border-l bg-card">
|
|
||||||
<EntryBrowser className="flex-[7]" title={view.label} entries={entries} current={entry?.key ?? null} onSelect={(key) => setChosen({ key, variant: 0 })} />
|
|
||||||
<BlockList scene={scene} />
|
|
||||||
</aside>
|
|
||||||
</>
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -70,3 +70,8 @@ export function actionForKey(key: string): ShortcutAction | null {
|
|||||||
export function viewForKey(key: string): string | null {
|
export function viewForKey(key: string): string | null {
|
||||||
return Object.entries(VIEW_KEYS).find(([, viewKey]) => viewKey === key)?.[0] ?? null
|
return Object.entries(VIEW_KEYS).find(([, viewKey]) => viewKey === key)?.[0] ?? null
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Whether a key press goes to a field being typed into, so the studio's keys leave it alone. */
|
||||||
|
export function isTypingInto(target: EventTarget | null): boolean {
|
||||||
|
return target instanceof HTMLInputElement || target instanceof HTMLSelectElement || target instanceof HTMLTextAreaElement
|
||||||
|
}
|
||||||
Reference in new issue
Block a user