From 922fe5e4cf05e7bcfb60c9bfd0c81e33700d5306 Mon Sep 17 00:00:00 2001 From: piexel Date: Fri, 6 Nov 2026 05:06:28 +0100 Subject: [PATCH] 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. --- src/renderer/src/bridge/BridgeClient.ts | 21 +- src/renderer/src/bridge/types.ts | 90 ++++++ .../src/components/ui/context-menu.tsx | 21 +- src/renderer/src/editor/EditHistory.test.ts | 35 ++ src/renderer/src/editor/EditHistory.ts | 45 +++ src/renderer/src/editor/jsonValues.ts | 22 ++ src/renderer/src/editor/nodeLayout.test.ts | 47 +++ src/renderer/src/editor/nodeLayout.ts | 91 ++++++ src/renderer/src/editor/useNodeEditor.ts | 122 +++++++ src/renderer/src/studio/MapStudio.tsx | 8 +- src/renderer/src/studio/NodeCanvas.tsx | 300 ++++++++++++++++++ src/renderer/src/studio/NodeInspector.tsx | 231 ++++++++++++++ src/renderer/src/studio/NodePane.tsx | 95 ++++++ src/renderer/src/studio/SceneStudio.tsx | 75 ++++- src/renderer/src/studio/shortcuts.ts | 5 + 15 files changed, 1179 insertions(+), 29 deletions(-) create mode 100644 src/renderer/src/editor/EditHistory.test.ts create mode 100644 src/renderer/src/editor/EditHistory.ts create mode 100644 src/renderer/src/editor/jsonValues.ts create mode 100644 src/renderer/src/editor/nodeLayout.test.ts create mode 100644 src/renderer/src/editor/nodeLayout.ts create mode 100644 src/renderer/src/editor/useNodeEditor.ts create mode 100644 src/renderer/src/studio/NodeCanvas.tsx create mode 100644 src/renderer/src/studio/NodeInspector.tsx create mode 100644 src/renderer/src/studio/NodePane.tsx diff --git a/src/renderer/src/bridge/BridgeClient.ts b/src/renderer/src/bridge/BridgeClient.ts index 142a0b005..f094118a5 100644 --- a/src/renderer/src/bridge/BridgeClient.ts +++ b/src/renderer/src/bridge/BridgeClient.ts @@ -4,6 +4,8 @@ import { decodePattern } from './patternDecoding' import { decodeSavedTile } from './savedTileDecoding' import { decodeTile } from './tileDecoding' import type { + EditorState, + GraphEdit, MapHover, MapLabel, MapTile, @@ -18,10 +20,12 @@ import type { SavedTile, SavedWorldInfo, SceneEntry, + SceneViewInfo, WorldInfo } from './types' export const STATUS_NOT_FOUND = 404 +export const STATUS_CONFLICT = 409 export const STATUS_UNAVAILABLE = 503 export class BridgeError extends Error { @@ -134,10 +138,25 @@ export class BridgeClient { } /** The scene views the pack's modules show, such as its objects. */ - sceneViews(): Promise { + sceneViews(): Promise { return this.json('scenes') } + /** An editable entry's file, as nodes. */ + sceneFile(viewId: string, key: string, signal?: AbortSignal): Promise { + 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 { + 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 { + return this.json(`scene-write?${new URLSearchParams({ view: viewId, key })}`, { method: 'POST', body: JSON.stringify({ revision, text }) }) + } + sceneEntries(viewId: string): Promise { return this.json(`scene-entries?${new URLSearchParams({ view: viewId })}`) } diff --git a/src/renderer/src/bridge/types.ts b/src/renderer/src/bridge/types.ts index 7b24d5887..a428efa21 100644 --- a/src/renderer/src/bridge/types.ts +++ b/src/renderer/src/bridge/types.ts @@ -33,6 +33,96 @@ export interface SceneEntry { 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 +} + +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). */ export interface PatternEntry { key: string diff --git a/src/renderer/src/components/ui/context-menu.tsx b/src/renderer/src/components/ui/context-menu.tsx index c8d0ff606..d3d0f9c5b 100644 --- a/src/renderer/src/components/ui/context-menu.tsx +++ b/src/renderer/src/components/ui/context-menu.tsx @@ -78,15 +78,18 @@ function ContextMenuSubContent({ className, ...props }: React.ComponentProps) { + // Portalled like the menu itself: inside it, the menu's blur and scrolling would clip the submenu away. return ( - + + + ) } @@ -99,7 +102,7 @@ function ContextMenuContent({ { + 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) + }) +}) diff --git a/src/renderer/src/editor/EditHistory.ts b/src/renderer/src/editor/EditHistory.ts new file mode 100644 index 000000000..b1b002caa --- /dev/null +++ b/src/renderer/src/editor/EditHistory.ts @@ -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) + } +} diff --git a/src/renderer/src/editor/jsonValues.ts b/src/renderer/src/editor/jsonValues.ts new file mode 100644 index 000000000..418f01b2d --- /dev/null +++ b/src/renderer/src/editor/jsonValues.ts @@ -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)[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 + } +} diff --git a/src/renderer/src/editor/nodeLayout.test.ts b/src/renderer/src/editor/nodeLayout.test.ts new file mode 100644 index 000000000..7eb18f73f --- /dev/null +++ b/src/renderer/src/editor/nodeLayout.test.ts @@ -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) + }) +}) diff --git a/src/renderer/src/editor/nodeLayout.ts b/src/renderer/src/editor/nodeLayout.ts new file mode 100644 index 000000000..df108ce23 --- /dev/null +++ b/src/renderer/src/editor/nodeLayout.ts @@ -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) } +} diff --git a/src/renderer/src/editor/useNodeEditor.ts b/src/renderer/src/editor/useNodeEditor.ts new file mode 100644 index 000000000..e0bd74f82 --- /dev/null +++ b/src/renderer/src/editor/useNodeEditor.ts @@ -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(null) + const [saving, setSaving] = useState(false) + const [, setHistoryChanges] = useState(0) + const history = useRef(new EditHistory()) + const shown = useRef(null) + const queue = useRef>(Promise.resolve()) + const entry = useRef({ viewId, key }) + + const run = useCallback( + (task: (current: EditorState | null) => Promise): 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 } +} diff --git a/src/renderer/src/studio/MapStudio.tsx b/src/renderer/src/studio/MapStudio.tsx index 762f4440e..63e39b959 100644 --- a/src/renderer/src/studio/MapStudio.tsx +++ b/src/renderer/src/studio/MapStudio.tsx @@ -16,7 +16,7 @@ import { PatternStudio } from './PatternStudio' import { SavedWorldStudio } from './SavedWorldStudio' import { SceneStudio } from './SceneStudio' import { WorldStudio3D } from './WorldStudio3D' -import { actionForKey, viewForKey, type ShortcutAction } from './shortcuts' +import { actionForKey, isTypingInto, viewForKey, type ShortcutAction } from './shortcuts' import { StatusBar } from './StatusBar' import { StudioToolbar } from './StudioToolbar' 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. */ -function useModuleViews(load: () => Promise, packRevision: number): ModuleViewInfo[] { - const [views, setViews] = useState([]) +function useModuleViews(load: () => Promise, packRevision: number): View[] { + const [views, setViews] = useState([]) useEffect(() => { let active = true load() @@ -503,7 +503,7 @@ function useKeyboard( if (event.key === 'Shift') { setDetailed(true) } - if (event.ctrlKey || event.metaKey || event.altKey || event.target instanceof HTMLInputElement) { + if (event.ctrlKey || event.metaKey || event.altKey || isTypingInto(event.target)) { return } const viewId = viewForKey(event.key) diff --git a/src/renderer/src/studio/NodeCanvas.tsx b/src/renderer/src/studio/NodeCanvas.tsx new file mode 100644 index 000000000..96e8cf571 --- /dev/null +++ b/src/renderer/src/studio/NodeCanvas.tsx @@ -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 = { + 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(null) + const [camera, setCamera] = useCamera(frame, layout, fileKey) + const [drag, setDrag] = useState(null) + const [menuNode, setMenuNode] = useState(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 ( + !open && setMenuNode(null)}> + +
{ + 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))} + > +
+ + {layout.nodes.map((placed) => ( + + ))} +
+
+
+ {menuNode !== null && } +
+ ) +} + +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 ( +
+ +
+
{node.title}
+ {detail !== null &&
{detail}
} +
+
+ ) +} + +function Wires({ layout }: { layout: NodeLayout }): React.JSX.Element { + return ( + + {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 ( + ${to.id}`}> + + {label !== '' && ( + + {label} + + )} + + ) + })} + + ) +} + +function NodeMenu({ node, locked, onEdit }: { node: GraphNode; locked: boolean; onEdit(edit: GraphEdit): void }): React.JSX.Element { + const removable = node.duplicable + return ( + + {node.additions.length > 0 && ( + + Add + + {node.additions.map((addition) => ( + onEdit({ op: 'append', list: addition.list, literal: addition.literal })}> + {addition.label} + + ))} + + + )} + onEdit({ op: 'duplicate', path: node.path })}> + Duplicate + + + onEdit({ op: 'delete', path: node.path })}> + Delete + + + ) +} + +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, layout: NodeLayout, fileKey: string): [Camera, React.Dispatch>] { + const [camera, setCamera] = useState({ x: FIT_MARGIN, y: FIT_MARGIN, scale: 1 }) + const fittedFile = useRef(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)) +} diff --git a/src/renderer/src/studio/NodeInspector.tsx b/src/renderer/src/studio/NodeInspector.tsx new file mode 100644 index 000000000..27cde9707 --- /dev/null +++ b/src/renderer/src/studio/NodeInspector.tsx @@ -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 ( +
+
+

{node.title}

+

{node.roles.length > 0 ? node.roles.join(', ') : node.kind}

+
+ +
+ {node.settings.map((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.title} +

+ {options.map((option) => { + const value = valueAt(values, [...section.path, option.name]) + return ( + onEdit({ op: 'set', object: section.path, key: option.name, literal })} + onUnset={() => onEdit({ op: 'unset', object: section.path, key: option.name })} + /> + ) + })} +
+ ) +} + +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' ? : +} + +function FieldRow({ option, value, locked, onUnset, problem, children }: SettingFieldProps & { problem: string | null; children: React.ReactNode }): React.JSX.Element { + return ( +
+
+ +
+ {children} + +
+
+ {problem !== null &&

{problem}

} +
+ ) +} + +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 ( + + + + ) +} + +// 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 ( + + setDraft(event.target.value)} + onBlur={commit} + onKeyDown={(event) => { + if (event.key === 'Enter') { + commit() + } else if (event.key === 'Escape') { + setDraft(shown) + } + }} + /> + + ) +} + +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 + } +} diff --git a/src/renderer/src/studio/NodePane.tsx b/src/renderer/src/studio/NodePane.tsx new file mode 100644 index 000000000..122603a70 --- /dev/null +++ b/src/renderer/src/studio/NodePane.tsx @@ -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 ( +
+
+

Nodes

+ {state?.file ?? entryKey} + + {state?.locked != null && ( + + + {state.locked} + + )} + {editor.saving && Saving…} + + +
+
+ {state === null &&

Reading the file…

} + {state !== null && state.roots === null && ( +
+

This file can't be shown as nodes

+

{state.problem}

+
+ )} + {state !== null && state.roots !== null && ( + + )} +
+
+ ) +} + +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]) +} diff --git a/src/renderer/src/studio/SceneStudio.tsx b/src/renderer/src/studio/SceneStudio.tsx index a282b0fc8..79f5077e3 100644 --- a/src/renderer/src/studio/SceneStudio.tsx +++ b/src/renderer/src/studio/SceneStudio.tsx @@ -2,13 +2,19 @@ import { ChevronLeft, ChevronRight } from 'lucide-react' import { useEffect, useMemo, useState } from 'react' import { Button } from '@/components/ui/button' import { ScrollArea } from '@/components/ui/scroll-area' +import { cn } from '@/lib/utils' 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 { BridgeAssets } from '../scene/BridgeAssets' import { INTS_PER_BLOCK, type BlockScene } from '../scene/sceneDecoding' import { buildSceneMesh, type SceneMesh } from '../scene/sceneMesh' import { EntryBrowser } from './EntryBrowser' +import { NodeInspector } from './NodeInspector' +import { NodePane } from './NodePane' import { SceneViewport } from './SceneViewport' const NUMBER = new Intl.NumberFormat('en-US') @@ -16,7 +22,7 @@ const DEFAULT_NAMESPACE_PREFIX = 'minecraft:' interface SceneStudioProps { client: BridgeClient - view: ModuleViewInfo + view: SceneViewInfo /** Changes when the pack reloads, so the entries and the scene are read again. */ packRevision: number /** What the status bar says about the scene, or null while none is shown. */ @@ -24,7 +30,10 @@ interface SceneStudioProps { 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 { const [waiting, setWaiting] = useState(null) 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(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(null), [onSummary]) + useEffect(() => setSelectedPath(null), [entry?.key]) return ( <> -
- +
+ + {view.editable && entry !== null && ( + setSelectedPath(node?.path ?? null)} /> + )} +
+ + + ) +} + +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 ( +
+ {entry !== null && entry.variants > 1 && (
- Variant {variant + 1} of {entry.variants} -
)} - {building && entry !== null && ( + {status !== null && (
- {waiting ?? `Building ${entry.name}`} + {status}
)} -
- - +
) } diff --git a/src/renderer/src/studio/shortcuts.ts b/src/renderer/src/studio/shortcuts.ts index 14bd71831..18ad2b85d 100644 --- a/src/renderer/src/studio/shortcuts.ts +++ b/src/renderer/src/studio/shortcuts.ts @@ -70,3 +70,8 @@ export function actionForKey(key: string): ShortcutAction | null { export function viewForKey(key: string): string | 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 +}