From 8fe8942f5de0d4007be0793a66ba47f379c63a1d Mon Sep 17 00:00:00 2001 From: piexel Date: Sun, 15 Nov 2026 15:46:30 +0100 Subject: [PATCH] Edit procedural settings inside the node boxes - Draw each node with a kind stripe, role chips, sockets and a row per set setting - Edit values in place: text with suggestions, checkboxes, choice menus and curves - Fold object and list settings, add and remove list items, add settings from a menu - Lay nodes out on a grid with roots in the first column and parts growing right - Drag nodes to place them, kept per file, and drag a part's ring onto a node to regrow it - Add part, duplicate and delete from node menus, arrange and fit from the canvas menu - Open the curve editor from a curve value, with draggable points on its plot - Remove the side settings panel and its field rows --- .../src/components/ui/dropdown-menu.tsx | 61 +++ .../renderer/src/components/ui/popover.tsx | 30 ++ studio/src/renderer/src/editor/curves.test.ts | 19 +- studio/src/renderer/src/editor/curves.ts | 18 + .../renderer/src/editor/nodeLayout.test.ts | 68 ++- studio/src/renderer/src/editor/nodeLayout.ts | 133 +++-- .../renderer/src/editor/nodePositions.test.ts | 40 ++ .../src/renderer/src/editor/nodePositions.ts | 45 ++ .../src/renderer/src/editor/nodeRows.test.ts | 69 +++ studio/src/renderer/src/editor/nodeRows.ts | 67 +++ .../renderer/src/editor/settingFolds.test.ts | 35 +- .../src/renderer/src/editor/settingFolds.ts | 55 ++- .../renderer/src/editor/settingText.test.ts | 68 ++- studio/src/renderer/src/editor/settingText.ts | 146 +++++- .../src/renderer/src/studio/CurveEditor.tsx | 298 +++++++++++ studio/src/renderer/src/studio/CurveField.tsx | 190 ------- studio/src/renderer/src/studio/FieldRow.tsx | 41 -- studio/src/renderer/src/studio/NodeBox.tsx | 94 ++++ studio/src/renderer/src/studio/NodeCanvas.tsx | 465 +++++++++--------- .../src/renderer/src/studio/NodeInspector.tsx | 295 ----------- studio/src/renderer/src/studio/NodeMenus.tsx | 135 +++++ studio/src/renderer/src/studio/NodePane.tsx | 21 +- studio/src/renderer/src/studio/NodeRows.tsx | 113 +++++ .../renderer/src/studio/NodeSettingRow.tsx | 266 ++++++++++ studio/src/renderer/src/studio/NodeWires.tsx | 69 +++ .../src/renderer/src/studio/SceneStudio.tsx | 13 +- studio/src/renderer/src/studio/nodeColors.ts | 33 ++ studio/src/renderer/src/studio/nodeEditing.ts | 29 ++ .../src/renderer/src/studio/useNodeCamera.ts | 105 ++++ .../renderer/src/studio/useNodePositions.ts | 34 ++ 30 files changed, 2197 insertions(+), 858 deletions(-) create mode 100644 studio/src/renderer/src/components/ui/dropdown-menu.tsx create mode 100644 studio/src/renderer/src/components/ui/popover.tsx create mode 100644 studio/src/renderer/src/editor/nodePositions.test.ts create mode 100644 studio/src/renderer/src/editor/nodePositions.ts create mode 100644 studio/src/renderer/src/editor/nodeRows.test.ts create mode 100644 studio/src/renderer/src/editor/nodeRows.ts create mode 100644 studio/src/renderer/src/studio/CurveEditor.tsx delete mode 100644 studio/src/renderer/src/studio/CurveField.tsx delete mode 100644 studio/src/renderer/src/studio/FieldRow.tsx create mode 100644 studio/src/renderer/src/studio/NodeBox.tsx delete mode 100644 studio/src/renderer/src/studio/NodeInspector.tsx create mode 100644 studio/src/renderer/src/studio/NodeMenus.tsx create mode 100644 studio/src/renderer/src/studio/NodeRows.tsx create mode 100644 studio/src/renderer/src/studio/NodeSettingRow.tsx create mode 100644 studio/src/renderer/src/studio/NodeWires.tsx create mode 100644 studio/src/renderer/src/studio/nodeColors.ts create mode 100644 studio/src/renderer/src/studio/nodeEditing.ts create mode 100644 studio/src/renderer/src/studio/useNodeCamera.ts create mode 100644 studio/src/renderer/src/studio/useNodePositions.ts diff --git a/studio/src/renderer/src/components/ui/dropdown-menu.tsx b/studio/src/renderer/src/components/ui/dropdown-menu.tsx new file mode 100644 index 000000000..70d71881a --- /dev/null +++ b/studio/src/renderer/src/components/ui/dropdown-menu.tsx @@ -0,0 +1,61 @@ +import * as React from "react" +import { cn } from "@/lib/utils" +import { IdeIcon } from "@/components/IdeIcon" +import { DropdownMenu as DropdownMenuPrimitive } from "radix-ui" + +const MENU_SURFACE = + "z-50 min-w-[8rem] overflow-x-hidden overflow-y-auto rounded-md border bg-popover p-1 text-popover-foreground shadow-md backdrop-blur-sm data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:animate-in data-[state=open]:fade-in-0" +const MENU_ROW = + "relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50" + +function DropdownMenu(props: React.ComponentProps) { + return +} + +function DropdownMenuTrigger(props: React.ComponentProps) { + return +} + +function DropdownMenuContent({ className, sideOffset = 2, ...props }: React.ComponentProps) { + return ( + + + + ) +} + +function DropdownMenuItem({ className, ...props }: React.ComponentProps) { + return +} + +function DropdownMenuSub(props: React.ComponentProps) { + return +} + +function DropdownMenuSubTrigger({ className, children, ...props }: React.ComponentProps) { + return ( + + {children} + + + ) +} + +function DropdownMenuSubContent({ className, ...props }: React.ComponentProps) { + return ( + + + + ) +} + +export { DropdownMenu, DropdownMenuTrigger, DropdownMenuContent, DropdownMenuItem, DropdownMenuSub, DropdownMenuSubTrigger, DropdownMenuSubContent } diff --git a/studio/src/renderer/src/components/ui/popover.tsx b/studio/src/renderer/src/components/ui/popover.tsx new file mode 100644 index 000000000..7598a30a8 --- /dev/null +++ b/studio/src/renderer/src/components/ui/popover.tsx @@ -0,0 +1,30 @@ +import * as React from "react" +import { cn } from "@/lib/utils" +import { Popover as PopoverPrimitive } from "radix-ui" + +function Popover(props: React.ComponentProps) { + return +} + +function PopoverAnchor(props: React.ComponentProps) { + return +} + +function PopoverContent({ className, align = "start", sideOffset = 4, ...props }: React.ComponentProps) { + return ( + + + + ) +} + +export { Popover, PopoverAnchor, PopoverContent } diff --git a/studio/src/renderer/src/editor/curves.test.ts b/studio/src/renderer/src/editor/curves.test.ts index 8e00a484b..690ba967d 100644 --- a/studio/src/renderer/src/editor/curves.test.ts +++ b/studio/src/renderer/src/editor/curves.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vitest' -import { canBecomeCurve, curveAt, curveFrom, isCurve, keyframesFrom, samplesOf, shapeFrom, withAddedKeyframe, withKeyframe, withoutKeyframe, withSetting, withShape } from './curves' +import { canBecomeCurve, curveAt, curveFrom, isCurve, keyframesFrom, plotRange, roundedNumber, samplesOf, shapeFrom, withAddedKeyframe, withKeyframe, withoutKeyframe, withSetting, withShape } from './curves' describe('isCurve', () => { it('holds only for keyframes and named shapes', () => { @@ -82,3 +82,20 @@ describe('editing keyframes', () => { expect(withoutKeyframe([[1, 3]], 0)).toEqual([[1, 3]]) }) }) + +describe('plotRange', () => { + it('spans 0 to 1 at least, a tenth past the highest, and below 0 only when the curve goes there', () => { + const rounded = (range: [number, number]): number[] => range.map((end) => Math.round(end * 100) / 100) + + expect(rounded(plotRange([0.2, 0.5]))).toEqual([0, 1.1]) + expect(rounded(plotRange([0, 3]))).toEqual([0, 3.3]) + expect(rounded(plotRange([-1, 1]))).toEqual([-1.2, 1.2]) + }) +}) + +describe('roundedNumber', () => { + it('reads a number with two decimals at most', () => { + expect(roundedNumber(1.3333)).toBe('1.33') + expect(roundedNumber(2)).toBe('2') + }) +}) diff --git a/studio/src/renderer/src/editor/curves.ts b/studio/src/renderer/src/editor/curves.ts index 5cf2a1fc9..44d79d7d3 100644 --- a/studio/src/renderer/src/editor/curves.ts +++ b/studio/src/renderer/src/editor/curves.ts @@ -21,6 +21,8 @@ const NARROWEST_BELL = 1e-6 const SHAPE_STOPS = 5 const FIRST_STOP = 0 const LAST_STOP = 1 +const PLOT_MARGIN = 0.1 +const READ_PRECISION = 100 export const CURVE_SHAPES: CurveShape[] = [ { key: 'linear', parameters: [], at: (t) => t }, @@ -157,6 +159,22 @@ export function samplesOf(value: unknown, count: number): number[] | null { return Array.from({ length: count }, (_, index) => curveAt(value, count === 1 ? 0 : index / (count - 1))) } +/** + * The values a plot of the curve with {@code samples} spans: from 0 to 1 at least and a tenth past its highest. It goes + * below 0 only when the curve already does, since most values along a part, like a radius, can't be negative. + */ +export function plotRange(samples: number[]): [number, number] { + const low = Math.min(0, ...samples) + const high = Math.max(1, ...samples) + const margin = (high - low) * PLOT_MARGIN + return [low < 0 ? low - margin : 0, high + margin] +} + +/** A number only to be read, never typed back: two decimals at most, like 1.3 or 0.25. */ +export function roundedNumber(value: number): string { + return String(Math.round(value * READ_PRECISION) / READ_PRECISION) +} + /** The curve as keyframes, such as to move a named curve's shape by hand: its values at evenly spaced points. */ export function keyframesFrom(value: unknown): Keyframe[] { if (isKeyframes(value)) { diff --git a/studio/src/renderer/src/editor/nodeLayout.test.ts b/studio/src/renderer/src/editor/nodeLayout.test.ts index 78e4d8f97..e13463f28 100644 --- a/studio/src/renderer/src/editor/nodeLayout.test.ts +++ b/studio/src/renderer/src/editor/nodeLayout.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from 'vitest' import type { GraphNode, JsonPath } from '../bridge/types' import { NO_PART } from '../bridge/types' -import { isWithin, layoutNodes, nodeDrawingPart, NODE_WIDTH } from './nodeLayout' +import { canRegrow, GRID, isWithin, layoutNodes, nodeAt, nodeDrawingPart, NODE_WIDTH, type PlacedNode } from './nodeLayout' function node(path: JsonPath, children: GraphNode[] = []): GraphNode { return { @@ -20,21 +20,65 @@ function node(path: JsonPath, children: GraphNode[] = []): GraphNode { } 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 + const height = (): number => 50 + const placedAt = (layout: ReturnType, path: JsonPath): PlacedNode => layout.nodes.find((placed) => placed.id === JSON.stringify(path))! - expect(parent.y).toBe((first.y + last.y) / 2) - expect(first.x - parent.x).toBeGreaterThan(NODE_WIDTH) - expect(layout.wires).toHaveLength(3) + it('sets a node level with its first child, a column to its left, and each next child on the rows below', () => { + const layout = layoutNodes([node([], [node(['parts', 0]), node(['parts', 1])])], height) + const [parent, first, second] = [placedAt(layout, []), placedAt(layout, ['parts', 0]), placedAt(layout, ['parts', 1])] + + expect(first.y).toBe(parent.y) + expect(first.x - parent.x).toBe(NODE_WIDTH + 2 * GRID) + expect(second.y).toBeGreaterThanOrEqual(first.y + 50 + 10) + expect(layout.wires).toHaveLength(2) }) - 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]))! + it('stacks the other roots under the first, in its column, and starts every node on a grid point', () => { + const layout = layoutNodes([node([], [node(['parts', 0])]), node(['materials', 0])], height) + const [object, material] = [placedAt(layout, []), placedAt(layout, ['materials', 0])] - expect(material.x).toBe(0) - expect(material.y).toBeGreaterThan(Math.max(...layout.nodes.filter((placed) => placed !== material).map((placed) => placed.y))) + expect(material.x).toBe(object.x) + expect(material.y).toBeGreaterThan(object.y + 50) + expect(layout.nodes.every((placed) => placed.x % GRID === 0 && placed.y % GRID === 0)).toBe(true) + }) + + it('makes room below a tall node before its next sibling', () => { + const tall = (graphNode: GraphNode): number => (graphNode.path.length === 2 && graphNode.path[1] === 0 ? 300 : 50) + const layout = layoutNodes([node([], [node(['parts', 0]), node(['parts', 1])])], tall) + + expect(placedAt(layout, ['parts', 1]).y).toBeGreaterThan(placedAt(layout, ['parts', 0]).y + 300) + }) + + it('puts a node where it was dragged, and marks which nodes have ports', () => { + const layout = layoutNodes([node([], [node(['parts', 0])])], height, new Map([[JSON.stringify(['parts', 0]), { x: 500, y: 44 }]])) + const part = placedAt(layout, ['parts', 0]) + + expect([part.x, part.y]).toEqual([500, 44]) + expect([part.grown, part.growing]).toEqual([true, false]) + expect([placedAt(layout, []).grown, placedAt(layout, []).growing]).toEqual([false, true]) + }) +}) + +describe('nodeAt', () => { + it('finds the node under a point by its own height', () => { + const layout = layoutNodes([node([], [node(['parts', 0])])], () => 50) + const part = layout.nodes[1] + + expect(nodeAt(layout.nodes, { x: part.x + 5, y: part.y + 49 })?.id).toBe(part.id) + expect(nodeAt(layout.nodes, { x: part.x + 5, y: part.y + 51 })).toBeNull() + }) +}) + +describe('canRegrow', () => { + const withList = (path: JsonPath, children: GraphNode[] = []): GraphNode => ({ ...node(path, children), childList: [...path, 'children'] }) + + it('lets a part grow from another that takes children, but not from inside itself or where it already grows', () => { + const part = withList(['parts', 0]) + + expect(canRegrow(part, withList(['parts', 1]))).toBe(true) + expect(canRegrow(part, withList(['parts', 0, 'children', 0]))).toBe(false) + expect(canRegrow(withList(['parts', 1, 'children', 0]), withList(['parts', 1]))).toBe(false) + expect(canRegrow({ ...part, movable: false }, withList(['parts', 1]))).toBe(false) }) }) diff --git a/studio/src/renderer/src/editor/nodeLayout.ts b/studio/src/renderer/src/editor/nodeLayout.ts index 4f300a441..ba78d9b13 100644 --- a/studio/src/renderer/src/editor/nodeLayout.ts +++ b/studio/src/renderer/src/editor/nodeLayout.ts @@ -1,10 +1,16 @@ 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 +/** The spacing nodes snap to, and the dots of the canvas mark. */ +export const GRID = 22 +export const NODE_WIDTH = 12 * GRID +const MARGIN = GRID +const COLUMN_GAP = 2 * GRID +const MIN_ROW_GAP = 10 + +export interface Point { + x: number + y: number +} /** 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 { @@ -12,6 +18,11 @@ export interface PlacedNode { node: GraphNode x: number y: number + height: number + /** Whether it grows from another node, so it has an input port. */ + grown: boolean + /** Whether other nodes grow from it, so it has an output port. */ + growing: boolean } export interface PlacedWire { @@ -23,8 +34,13 @@ export interface PlacedWire { export interface NodeLayout { nodes: PlacedNode[] wires: PlacedWire[] - width: number - height: number +} + +export interface Bounds { + left: number + top: number + right: number + bottom: number } export function idOf(path: JsonPath): string { @@ -71,38 +87,95 @@ export function isWithin(path: JsonPath, ancestor: JsonPath): boolean { return ancestor.length <= path.length && ancestor.every((step, index) => path[index] === step) } +export function snappedToGrid(coordinate: number): number { + return Math.round(coordinate / GRID) * GRID +} + +function nextRowBelow(bottom: number): number { + return Math.ceil((bottom + MIN_ROW_GAP) / GRID) * GRID +} + +function columnLeft(column: number): number { + return MARGIN + column * (NODE_WIDTH + COLUMN_GAP) +} + /** - * 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. + * Lays the nodes out on the grid: the roots, such as the object, its materials and its decorations, stacked in the + * first column, and what grows from them to the right, a column per generation. Each subtree takes the rows below the + * last, and a node sits level with its first child, so it is read beside what grows from it. A node in + * {@code placed}, by its id, sits where it was dragged instead. */ -export function layoutNodes(roots: GraphNode[]): NodeLayout { +export function layoutNodes(roots: GraphNode[], heightOf: (node: GraphNode) => number, placed: ReadonlyMap = new Map()): 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 }) + const add = (node: GraphNode, x: number, y: number, grown: boolean): PlacedNode => { + const id = idOf(node.path) + const at = placed.get(id) ?? { x, y } + const box: PlacedNode = { id, node, x: at.x, y: at.y, height: heightOf(node), grown, growing: node.children.length > 0 } + nodes.push(box) + return box + } + + // Returns the bottom of the subtree as laid out, which a node dragged elsewhere does not change. + const placeTree = (link: GraphNode['children'][number], parent: PlacedNode, column: number, top: number): number => { + const box = add(link.node, columnLeft(column), top, true) + wires.push({ from: parent, to: box, label: link.wire }) + let bottom = top + box.height + let childTop = top + for (const child of link.node.children) { + const childBottom = placeTree(child, box, column + 1, childTop) + bottom = Math.max(bottom, childBottom) + childTop = nextRowBelow(childBottom) } - return placed + return bottom } - const takeRow = (): number => { - const top = nextTop - nextTop += NODE_HEIGHT + ROW_GAP - return top + let firstColumnTop = MARGIN + const rootBoxes = roots.map((root) => { + const box = add(root, MARGIN, firstColumnTop, false) + firstColumnTop = nextRowBelow(firstColumnTop + box.height) + return box + }) + let treeTop = MARGIN + roots.forEach((root, index) => { + for (const link of root.children) { + treeTop = nextRowBelow(placeTree(link, rootBoxes[index], 1, treeTop)) + } + }) + return { nodes, wires } +} + +/** The smallest rectangle around every node; null when there are none. */ +export function boundsOf(nodes: PlacedNode[]): Bounds | null { + if (nodes.length === 0) { + return null + } + return { + left: Math.min(...nodes.map((node) => node.x)), + top: Math.min(...nodes.map((node) => node.y)), + right: Math.max(...nodes.map((node) => node.x + NODE_WIDTH)), + bottom: Math.max(...nodes.map((node) => node.y + node.height)) + } +} + +/** The node under {@code point}, the one drawn last when they overlap; null over the background. */ +export function nodeAt(nodes: PlacedNode[], point: Point): PlacedNode | null { + for (let index = nodes.length - 1; index >= 0; index--) { + const box = nodes[index] + if (point.x >= box.x && point.x <= box.x + NODE_WIDTH && point.y >= box.y && point.y <= box.y + box.height) { + return box + } } + return null +} - for (const root of roots) { - place(root, 0) - nextTop += TREE_GAP +/** Whether {@code dragged} may grow from {@code over}: it takes children, and is neither inside it nor already its parent. */ +export function canRegrow(dragged: GraphNode, over: GraphNode): boolean { + const toList = over.childList + if (!dragged.movable || toList === null || isWithin(toList, dragged.path)) { + return false } - return { nodes, wires, width, height: Math.max(0, nextTop - ROW_GAP - TREE_GAP) } + const alreadyThere = dragged.path.length === toList.length + 1 && isWithin(dragged.path, toList) + return !alreadyThere } diff --git a/studio/src/renderer/src/editor/nodePositions.test.ts b/studio/src/renderer/src/editor/nodePositions.test.ts new file mode 100644 index 000000000..c73495e97 --- /dev/null +++ b/studio/src/renderer/src/editor/nodePositions.test.ts @@ -0,0 +1,40 @@ +import { describe, expect, it } from 'vitest' +import { idOf } from './nodeLayout' +import { pathAfterRemoval, positionsAfterEdit } from './nodePositions' + +const at = { x: 44, y: 88 } + +describe('pathAfterRemoval', () => { + it('moves an element after the removed one, and what it holds, up an index', () => { + expect(pathAfterRemoval(['parts', 2, 'children', 0], ['parts', 1])).toEqual(['parts', 1, 'children', 0]) + }) + + it('leaves an element before it and one of another array alone', () => { + expect(pathAfterRemoval(['parts', 0], ['parts', 1])).toEqual(['parts', 0]) + expect(pathAfterRemoval(['materials', 3], ['parts', 1])).toEqual(['materials', 3]) + }) +}) + +describe('positionsAfterEdit', () => { + it('drops a deleted node and what grows from it, and moves the later ones up', () => { + const positions = { [idOf(['parts', 0])]: at, [idOf(['parts', 0, 'children', 0])]: at, [idOf(['parts', 1])]: at } + + expect(positionsAfterEdit(positions, { op: 'delete', path: ['parts', 0] }, {})).toEqual({ [idOf(['parts', 0])]: at }) + }) + + it('keeps a moved node where it was, under the path it gets at the end of the list it joins', () => { + const values = { parts: [{}, { children: [{}] }] } + const positions = { [idOf(['parts', 0])]: at, [idOf(['parts', 0, 'children', 0])]: { x: 0, y: 0 } } + + expect(positionsAfterEdit(positions, { op: 'move', path: ['parts', 0], toList: ['parts', 1, 'children'] }, values)).toEqual({ + [idOf(['parts', 0, 'children', 1])]: at, + [idOf(['parts', 0, 'children', 1, 'children', 0])]: { x: 0, y: 0 } + }) + }) + + it('leaves the positions as they were for an edit that moves no node', () => { + const positions = { [idOf(['parts', 0])]: at } + + expect(positionsAfterEdit(positions, { op: 'set', object: ['parts', 0], key: 'role', literal: '"a"' }, {})).toBe(positions) + }) +}) diff --git a/studio/src/renderer/src/editor/nodePositions.ts b/studio/src/renderer/src/editor/nodePositions.ts new file mode 100644 index 000000000..321a4e94c --- /dev/null +++ b/studio/src/renderer/src/editor/nodePositions.ts @@ -0,0 +1,45 @@ +import type { GraphEdit, JsonPath } from '../bridge/types' +import { valueAt } from './jsonValues' +import { idOf, isWithin, type Point } from './nodeLayout' + +/** Where nodes were dragged to, by the id of their path in the file. */ +export type NodePositions = Readonly> + +/** + * The positions after {@code edit} changed the file {@code values} holds. A deleted node's position goes; the + * elements after a removed one move up an index, and so do the positions named by them. A moved node keeps its + * position under its new path, at the end of the list it joins. + */ +export function positionsAfterEdit(positions: NodePositions, edit: GraphEdit, values: unknown): NodePositions { + if (edit.op === 'delete') { + return remapped(positions, (path) => (isWithin(path, edit.path) ? null : pathAfterRemoval(path, edit.path))) + } + if (edit.op !== 'move') { + return positions + } + const joined = valueAt(values, edit.toList) + const newPath = [...pathAfterRemoval(edit.toList, edit.path), Array.isArray(joined) ? joined.length : 0] + return remapped(positions, (path) => (isWithin(path, edit.path) ? [...newPath, ...path.slice(edit.path.length)] : pathAfterRemoval(path, edit.path))) +} + +/** {@code path} once the array element at {@code removed} is gone: one index lower when it is after it in that array. */ +export function pathAfterRemoval(path: JsonPath, removed: JsonPath): JsonPath { + const index = removed.at(-1) + const array = removed.slice(0, -1) + const step = path[array.length] + if (typeof index !== 'number' || path.length <= array.length || !isWithin(path, array) || typeof step !== 'number' || step <= index) { + return path + } + return [...array, step - 1, ...path.slice(array.length + 1)] +} + +function remapped(positions: NodePositions, newPathOf: (path: JsonPath) => JsonPath | null): NodePositions { + const next: Record = {} + for (const [id, position] of Object.entries(positions)) { + const newPath = newPathOf(JSON.parse(id) as JsonPath) + if (newPath !== null) { + next[idOf(newPath)] = position + } + } + return next +} diff --git a/studio/src/renderer/src/editor/nodeRows.test.ts b/studio/src/renderer/src/editor/nodeRows.test.ts new file mode 100644 index 000000000..3dd7edc24 --- /dev/null +++ b/studio/src/renderer/src/editor/nodeRows.test.ts @@ -0,0 +1,69 @@ +import { describe, expect, it } from 'vitest' +import type { GraphNode, SettingOption, SettingsType, ValueKind } from '../bridge/types' +import { NODE_HEADER, NODE_HEADING, NODE_PADDING, NODE_ROW, NODE_STRIPE, nodeRows } from './nodeRows' + +function option(name: string, kind: ValueKind): SettingOption { + return { name, description: '', required: false, minimum: null, maximum: null, minItems: null, defaultValue: null, kind } +} + +const any: ValueKind = { kind: 'any' } +const types: Record = { + Part: { description: '', options: [option('role', { kind: 'text', format: 'PLAIN' }), option('offset', { kind: 'object', type: 'Offset' })] }, + Stem: { description: '', options: [option('length', any), option('taper', any)] }, + Offset: { description: '', options: [option('x', any), option('y', any)] } +} + +const stem: GraphNode = { + kind: 'Stem', + title: 'Stem', + path: ['parts', 0], + partId: 0, + roles: ['wood'], + settings: [ + { title: 'Part', path: ['parts', 0], type: 'Part', shownAsNodes: [] }, + { title: 'Stem', path: ['parts', 0, 'stem'], type: 'Stem', shownAsNodes: [] } + ], + children: [], + childList: null, + movable: true, + duplicable: true, + additions: [] +} + +const file = { parts: [{ role: 'wood', offset: { x: 2 }, stem: { length: 6 } }] } + +describe('nodeRows', () => { + it('lists the first section plainly, a later one under its heading, and a folded section as one row', () => { + const { rows } = nodeRows(stem, types, file, new Set(), true) + + expect(rows.map((row) => row.kind)).toEqual(['setting', 'fold', 'heading', 'setting', 'addSetting']) + expect(rows.flatMap((row) => (row.kind === 'setting' ? [row.option.name, row.value] : []))).toEqual(['role', 'wood', 'length', 6]) + }) + + it('lists what an unfolded section holds right under it', () => { + const { rows } = nodeRows(stem, types, file, new Set([JSON.stringify(['parts', 0, 'offset'])]), true) + + expect(rows.map((row) => (row.kind === 'setting' ? row.option.name : row.kind))).toEqual(['role', 'fold', 'x', 'heading', 'length', 'addSetting']) + }) + + it('adds up its height from its rows', () => { + const { height } = nodeRows(stem, types, file, new Set(), true) + + expect(height).toBe(NODE_STRIPE + NODE_HEADER + 4 * NODE_ROW + NODE_HEADING + NODE_PADDING) + }) + + it('offers the sections with settings left to add, but no row to add them while the file is read only', () => { + const editable = nodeRows(stem, types, file, new Set(), true) + const readOnly = nodeRows(stem, types, file, new Set(), false) + + expect(editable.addable.map((fold) => fold.title)).toEqual(['offset', 'Stem']) + expect(readOnly.rows.some((row) => row.kind === 'addSetting')).toBe(false) + }) + + it('draws a node without settings, such as a shared part, as its header alone', () => { + const { rows, height } = nodeRows({ ...stem, settings: [] }, types, file, new Set(), true) + + expect(rows).toEqual([]) + expect(height).toBe(NODE_STRIPE + NODE_HEADER + NODE_PADDING) + }) +}) diff --git a/studio/src/renderer/src/editor/nodeRows.ts b/studio/src/renderer/src/editor/nodeRows.ts new file mode 100644 index 000000000..df996e488 --- /dev/null +++ b/studio/src/renderer/src/editor/nodeRows.ts @@ -0,0 +1,67 @@ +import type { GraphNode, SettingOption, SettingsType } from '../bridge/types' +import { valueAt } from './jsonValues' +import { idOf } from './nodeLayout' +import { foldedSections, idOfFold, visibleFolds, type SettingsFold } from './settingFolds' + +export const NODE_STRIPE = 3 +export const NODE_HEADER = 28 +export const NODE_ROW = 24 +export const NODE_HEADING = 20 +export const NODE_PADDING = 8 + +export type NodeRow = + | { kind: 'heading'; id: string; fold: SettingsFold } + | { kind: 'fold'; id: string; fold: SettingsFold; open: boolean } + | { kind: 'setting'; id: string; fold: SettingsFold; option: SettingOption; value: unknown } + | { kind: 'addSetting'; id: string } + +/** What a node lists below its header, how tall that makes it, and the sections that have settings left to add. */ +export interface NodeRows { + rows: NodeRow[] + height: number + addable: SettingsFold[] +} + +const ADD_SETTING_ID = 'add-setting' + +export function heightOfRow(row: NodeRow): number { + return row.kind === 'heading' ? NODE_HEADING : NODE_ROW +} + +/** + * The rows of {@code node}: each of its sections' settings, the first section's plainly, a later one's under its + * heading, and a folding section's only while it is in {@code open}. An editable node with settings left to add ends + * in a row to add one. + */ +export function nodeRows(node: GraphNode, types: Record, values: unknown, open: ReadonlySet, editable: boolean): NodeRows { + const rows: NodeRow[] = [] + const addable: SettingsFold[] = [] + let ownSections = 0 + for (const section of node.settings) { + const folds = foldedSections(section, types, values) + addable.push(...folds.filter((fold) => fold.unset.length > 0)) + for (const fold of visibleFolds(folds, open)) { + const id = idOfFold(fold) + if (fold.kind !== 'own') { + rows.push({ kind: 'fold', id: `fold:${id}`, fold, open: open.has(id) }) + } else if (ownSections++ > 0) { + rows.push({ kind: 'heading', id: `heading:${id}`, fold }) + } + if (fold.kind === 'own' || open.has(id)) { + rows.push(...settingRows(fold, values)) + } + } + } + if (editable && addable.length > 0) { + rows.push({ kind: 'addSetting', id: ADD_SETTING_ID }) + } + const height = NODE_STRIPE + NODE_HEADER + rows.reduce((sum, row) => sum + heightOfRow(row), 0) + NODE_PADDING + return { rows, height, addable } +} + +function settingRows(fold: SettingsFold, values: unknown): NodeRow[] { + return fold.settings.map((option) => { + const path = [...fold.path, option.name] + return { kind: 'setting', id: idOf(path), fold, option, value: valueAt(values, path) } + }) +} diff --git a/studio/src/renderer/src/editor/settingFolds.test.ts b/studio/src/renderer/src/editor/settingFolds.test.ts index 90b180090..00664109a 100644 --- a/studio/src/renderer/src/editor/settingFolds.test.ts +++ b/studio/src/renderer/src/editor/settingFolds.test.ts @@ -1,6 +1,7 @@ import { describe, expect, it } from 'vitest' import type { NodeSettings, SettingOption, SettingsType, ValueKind } from '../bridge/types' import { foldedSections, idOfFold, visibleFolds } from './settingFolds' +import { SPAN_TYPE } from './settingText' function option(name: string, kind: ValueKind): SettingOption { return { name, description: '', required: false, minimum: null, maximum: null, minItems: null, defaultValue: null, kind } @@ -47,10 +48,34 @@ describe('foldedSections', () => { expect(folds[2].holder).toEqual({ object: ['materials', 0], key: 'rules' }) }) - it('leaves the folded settings and the ones shown as nodes out of the fields of the section that holds them', () => { + it('leaves the folded settings and the ones shown as nodes out of the rows of the section that holds them', () => { const [own] = foldedSections(material, types, file) - expect(own.options.map((setting) => setting.name)).toEqual(['role', 'block']) + expect(own.settings.map((setting) => setting.name)).toEqual(['role', 'block']) + }) + + it('lists only what is written, and keeps the rest to add', () => { + const [own] = foldedSections(material, types, { materials: [{ block: 'minecraft:stone' }] }) + + expect(own.settings.map((setting) => setting.name)).toEqual(['block']) + expect(own.unset.map((setting) => setting.name)).toEqual(['role', 'offset', 'rules']) + }) + + it('lists a plain setting the type requires even while it is unset, so its default shows', () => { + const required: Record = { ...types, Material: { ...types.Material, options: [{ ...option('role', text), required: true }] } } + const [own] = foldedSections(material, required, { materials: [{}] }) + + expect(own.settings.map((setting) => setting.name)).toEqual(['role']) + expect(own.unset).toEqual([]) + }) + + it('keeps a span a row rather than a section, since it is typed as a range', () => { + const spanned: Record = { ...types, Material: { description: '', options: [option('along', { kind: 'object', type: SPAN_TYPE })] }, [SPAN_TYPE]: { description: '', options: [option('from', any), option('to', any)] } } + const folds = foldedSections(material, spanned, { materials: [{ along: { from: 0.2, to: 0.8 } }] }) + + expect(folds).toHaveLength(1) + expect(folds[0].settings.map((setting) => setting.name)).toEqual(['along']) + expect(folds[0].summary).toBe('along 0.2 – 0.8') }) it('sums a section up by what it holds, a curve as curve and the default namespace left off', () => { @@ -61,11 +86,11 @@ describe('foldedSections', () => { expect(folds[2].summary).toBe('2 items') }) - it('keeps a setting that is not written as an object a field', () => { - const [own, ...inside] = foldedSections(material, types, { materials: [{ role: 'wood' }] }) + it('keeps an object setting that is not written as an object a row', () => { + const [own, ...inside] = foldedSections(material, types, { materials: [{ offset: 3 }] }) expect(inside).toEqual([]) - expect(own.options.map((setting) => setting.name)).toEqual(['role', 'block', 'offset', 'rules']) + expect(own.settings.map((setting) => setting.name)).toEqual(['offset']) }) }) diff --git a/studio/src/renderer/src/editor/settingFolds.ts b/studio/src/renderer/src/editor/settingFolds.ts index f6a9dc943..27eab1fcb 100644 --- a/studio/src/renderer/src/editor/settingFolds.ts +++ b/studio/src/renderer/src/editor/settingFolds.ts @@ -1,7 +1,7 @@ -import type { JsonPath, NodeSettings, SettingOption, SettingsType } from '../bridge/types' +import type { JsonPath, NodeSettings, SettingOption, SettingsType, ValueKind } from '../bridge/types' import { isCurve } from './curves' import { isWithin } from './nodeLayout' -import { textOf } from './settingText' +import { isSpan, textOf } from './settingText' import { valueAt } from './jsonValues' const SUMMARY_SETTINGS = 3 @@ -14,7 +14,7 @@ const DEFAULT_NAMESPACE = 'minecraft:' */ export type FoldKind = 'own' | 'group' | 'list' | 'item' -/** One object of the file whose settings the inspector shows, below the ones that hold it. */ +/** One object of the file whose settings a node lists, below the ones that hold it. */ export interface SettingsFold { title: string path: JsonPath @@ -26,8 +26,10 @@ export interface SettingsFold { summary: string /** The object and member that hold a group or list, to unset it; null for the rest. */ holder: { object: JsonPath; key: string } | null - /** The settings written plainly in it, as fields; those that are folds of their own are not among them. */ - options: SettingOption[] + /** The settings listed as rows: those written plainly in it, and the plain ones it requires but leaves unset. */ + settings: SettingOption[] + /** What it could set but leaves at the default, to add. */ + unset: SettingOption[] } function isObject(value: unknown): value is Record { @@ -42,10 +44,19 @@ export function idOfFold(fold: SettingsFold): string { return JSON.stringify(fold.path) } +/** The schema type of a setting that folds open as a section of its own when written; null for one that is a row. */ +function groupTypeOf(kind: ValueKind): string | null { + return kind.kind === 'object' && !isSpan(kind) ? kind.type : null +} + +function itemTypeOf(kind: ValueKind): string | null { + return kind.kind === 'list' && kind.element.kind === 'object' ? kind.element.type : null +} + /** * The sections of one object of a node and the objects inside it, in file order, each followed by those inside it. A - * setting that is itself an object whose type the schema describes is a section of its own one level deeper, and so is - * each element of a list of objects; one that is not written stays a field. + * setting written as an object whose type the schema describes is a section of its own one level deeper, and so is + * each element of a list of objects. Only what is written is listed; the rest can be added. */ export function foldedSections(section: NodeSettings, types: Record, values: unknown): SettingsFold[] { const folds: SettingsFold[] = [] @@ -56,7 +67,8 @@ export function foldedSections(section: NodeSettings, types: Record function addFold(into: SettingsFold[], types: Record, values: unknown, head: FoldHead, shownAsNodes: Set): void { - const options: SettingOption[] = [] + const settings: SettingOption[] = [] + const unset: SettingOption[] = [] const inside: SettingsFold[] = [] const summary: string[] = [] for (const option of types[head.type]?.options ?? []) { @@ -66,10 +78,18 @@ function addFold(into: SettingsFold[], types: Record, valu const path = [...head.path, option.name] const value = valueAt(values, path) const holder = { object: head.path, key: option.name } - const objectType = option.kind.kind === 'object' ? option.kind.type : null - const itemType = option.kind.kind === 'list' && option.kind.element.kind === 'object' ? option.kind.element.type : null - if (objectType !== null && isObject(value) && types[objectType] !== undefined) { - addFold(inside, types, values, { title: option.name, path, type: objectType, kind: 'group', depth: head.depth + 1, holder }, new Set()) + const groupType = groupTypeOf(option.kind) + const itemType = itemTypeOf(option.kind) + if (value === undefined) { + if (option.required && groupType === null && itemType === null) { + settings.push(option) + } else { + unset.push(option) + } + continue + } + if (groupType !== null && isObject(value) && types[groupType] !== undefined) { + addFold(inside, types, values, { title: option.name, path, type: groupType, kind: 'group', depth: head.depth + 1, holder }, new Set()) continue } if (itemType !== null && isObjects(value) && types[itemType] !== undefined) { @@ -77,12 +97,10 @@ function addFold(into: SettingsFold[], types: Record, valu summary.push(`${option.name} ${value.length}`) continue } - options.push(option) - if (value !== undefined) { - summary.push(`${option.name} ${shortText(option, value)}`) - } + settings.push(option) + summary.push(`${option.name} ${shortText(option, value)}`) } - into.push({ ...head, summary: summary.slice(0, SUMMARY_SETTINGS).join(SUMMARY_SEPARATOR), options }) + into.push({ ...head, summary: summary.slice(0, SUMMARY_SETTINGS).join(SUMMARY_SEPARATOR), settings, unset }) into.push(...inside) } @@ -104,7 +122,8 @@ function addList(into: SettingsFold[], types: Record, valu depth: list.depth, summary: `${list.count} ${list.count === 1 ? 'item' : 'items'}`, holder: list.holder, - options: [] + settings: [], + unset: [] }) for (let index = 0; index < list.count; index++) { addFold( diff --git a/studio/src/renderer/src/editor/settingText.test.ts b/studio/src/renderer/src/editor/settingText.test.ts index 9b21e067c..9adfc125e 100644 --- a/studio/src/renderer/src/editor/settingText.test.ts +++ b/studio/src/renderer/src/editor/settingText.test.ts @@ -1,8 +1,14 @@ import { describe, expect, it } from 'vitest' -import type { ValueKind } from '../bridge/types' -import { literalOf, textOf } from './settingText' +import type { SettingOption, ValueKind } from '../bridge/types' +import { defaultLiteral, defaultText, literalOf, problemWith, SPAN_TYPE, textOf } from './settingText' const roles: ValueKind = { kind: 'list', element: { kind: 'text', format: 'PLAIN' }, unique: false } +const any: ValueKind = { kind: 'any' } +const span: ValueKind = { kind: 'object', type: SPAN_TYPE } + +function option(kind: ValueKind, changes: Partial = {}): SettingOption { + return { name: 'radius', description: '', required: false, minimum: null, maximum: null, minItems: null, defaultValue: null, kind, ...changes } +} describe('string lists', () => { it('read as commas and are written back quoted', () => { @@ -25,3 +31,61 @@ describe('text', () => { expect(literalOf(text, 'wood "a"')).toBe('"wood \\"a\\""') }) }) + +describe('ranges', () => { + it('show a [min, max] value and a span with a dash', () => { + expect(textOf(any, [5, 7])).toBe('5 – 7') + expect(textOf(span, { from: 0.45, to: 0.95 })).toBe('0.45 – 0.95') + expect(textOf(span, { to: 0.5 })).toBe('0 – 0.5') + }) + + it('are read back however the dash is typed', () => { + expect(literalOf(any, '2 – 4')).toBe('[2, 4]') + expect(literalOf(any, '2-4')).toBe('[2, 4]') + expect(literalOf(any, '2 to 4')).toBe('[2, 4]') + expect(literalOf(any, '-1, 3.5')).toBe('[-1, 3.5]') + expect(literalOf(span, '0.2 – 0.8')).toBe('{"from": 0.2, "to": 0.8}') + }) + + it('leave a plain number and a curve as typed', () => { + expect(literalOf(any, ' 3 ')).toBe('3') + expect(literalOf(any, '[[0, 1], [1, 0]]')).toBe('[[0, 1], [1, 0]]') + }) +}) + +describe('defaults', () => { + it('start an added setting at its default, or at an empty value of its kind', () => { + expect(defaultLiteral(option(any, { defaultValue: 2 }))).toBe('2') + expect(defaultLiteral(option({ kind: 'boolean' }))).toBe('false') + expect(defaultLiteral(option({ kind: 'enum', constants: [{ name: 'ROUND', description: '' }] }))).toBe('"ROUND"') + expect(defaultLiteral(option(roles))).toBe('[]') + expect(defaultLiteral(option({ kind: 'object', type: 'Offset' }))).toBe('{}') + }) + + it('show what an unset setting falls back to, or nothing', () => { + expect(defaultText(option({ kind: 'text', format: 'PLAIN' }, { defaultValue: 'main' }))).toBe('main') + expect(defaultText(option(any))).toBe('') + }) +}) + +describe('problemWith', () => { + it('holds a number to its kind and limits', () => { + const count = option({ kind: 'integer' }, { minimum: 1, maximum: 64 }) + + expect(problemWith(count, 'a')).toBe('Not a number') + expect(problemWith(count, '2.5')).toBe('Not a whole number') + expect(problemWith(count, '0')).toBe('At least 1') + expect(problemWith(count, '65')).toBe('At most 64') + expect(problemWith(count, '6')).toBeNull() + }) + + it('takes a number, a range or JSON for a value that may be a curve', () => { + expect(problemWith(option(any), '4 – 6')).toBeNull() + expect(problemWith(option(any), '[[0, 1]]')).toBeNull() + expect(problemWith(option(any), 'tall')).toBe('Takes a number, or a range like 4 – 6') + }) + + it('lets an empty draft through, since it unsets the setting', () => { + expect(problemWith(option({ kind: 'integer' }), ' ')).toBeNull() + }) +}) diff --git a/studio/src/renderer/src/editor/settingText.ts b/studio/src/renderer/src/editor/settingText.ts index d02ebe432..8f105ef1b 100644 --- a/studio/src/renderer/src/editor/settingText.ts +++ b/studio/src/renderer/src/editor/settingText.ts @@ -1,30 +1,71 @@ -import type { ValueKind } from '../bridge/types' +import type { SettingOption, ValueKind } from '../bridge/types' export const NOT_SET = '' export const LIST_SEPARATOR = ', ' +export const RANGE_DASH = ' – ' +/** The schema type of a stretch along a part from 0 to 1, shown and typed as a range rather than folded open. */ +export const SPAN_TYPE = 'art.arcane.iris.generation.procedural.part.ProceduralSpan' + +const NUMBER = '(-?\\d+(?:\\.\\d+)?)' +const RANGE = new RegExp(`^\\s*${NUMBER}\\s*(?:–|—|\\.\\.|to|,|-)\\s*${NUMBER}\\s*$`) +const RANGE_SIZE = 2 +const SPAN_FROM = 'from' +const SPAN_TO = 'to' +const SPAN_DEFAULT_FROM = 0 +const SPAN_DEFAULT_TO = 1 /** Whether {@code kind} is a string naming something, typed as text. */ export function isText(kind: ValueKind): boolean { return kind.kind === 'text' || kind.kind === 'reference' || kind.kind === 'resource' } +export function isNumber(kind: ValueKind): boolean { + return kind.kind === 'integer' || kind.kind === 'decimal' +} + /** Whether {@code kind} is a list of strings, such as the roles a decoration goes on, which is typed as {@code a, b}. */ export function isStringList(kind: ValueKind): boolean { return kind.kind === 'list' && isText(kind.element) } +/** Whether {@code kind} is a stretch from 0 to 1, written {@code {"from": a, "to": b}} and typed {@code a – b}. */ +export function isSpan(kind: ValueKind): boolean { + return kind.kind === 'object' && kind.type === SPAN_TYPE +} + function isStrings(value: unknown): value is string[] { return Array.isArray(value) && value.every((element) => typeof element === 'string') } -/** What the field shows for the value the file holds. */ +function isRecord(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value) +} + +/** The two ends of a {@code [min, max]} value, or of a span; null for anything else. */ +export function rangeOf(kind: ValueKind, value: unknown): [number, number] | null { + if (kind.kind === 'any' && Array.isArray(value) && value.length === RANGE_SIZE && value.every((end) => typeof end === 'number')) { + return [value[0], value[1]] + } + if (!isSpan(kind) || !isRecord(value)) { + return null + } + const from = value[SPAN_FROM] ?? SPAN_DEFAULT_FROM + const to = value[SPAN_TO] ?? SPAN_DEFAULT_TO + return typeof from === 'number' && typeof to === 'number' ? [from, to] : null +} + +/** What the node shows for the value the file holds: strings unquoted, ranges as {@code 2 – 4}, anything else as JSON. */ export function textOf(kind: ValueKind, value: unknown): string { if (value === undefined) { return NOT_SET } - if (isText(kind) && typeof value === 'string') { + if ((isText(kind) || kind.kind === 'enum') && typeof value === 'string') { return value } + const range = rangeOf(kind, value) + if (range !== null) { + return range.join(RANGE_DASH) + } return isStringList(kind) && isStrings(value) ? value.join(LIST_SEPARATOR) : JSON.stringify(value) } @@ -36,13 +77,102 @@ export function itemsOf(draft: string): string[] { .filter((item) => item !== '') } -/** What the field holds as JSON to write; a list typed as {@code a, b} is written as an array unless it already is one. */ +/** + * What was typed as JSON to write. A range may be typed {@code 2 – 4}, {@code 2-4}, {@code 2 to 4} or {@code 2, 4}; a + * list typed as {@code a, b} or without its brackets gets them. + */ export function literalOf(kind: ValueKind, draft: string): string { - if (isText(kind)) { + if (isText(kind) || kind.kind === 'enum') { return JSON.stringify(draft) } - if (isStringList(kind) && !draft.trim().startsWith('[')) { - return JSON.stringify(itemsOf(draft)) + const typed = draft.trim() + if (isStringList(kind) && !typed.startsWith('[')) { + return JSON.stringify(itemsOf(typed)) + } + const range = RANGE.exec(typed) + if (range !== null && kind.kind === 'any') { + return `[${range[1]}, ${range[2]}]` + } + if (range !== null && isSpan(kind)) { + return `{"${SPAN_FROM}": ${range[1]}, "${SPAN_TO}": ${range[2]}}` + } + return !isJson(typed) && isJson(`[${typed}]`) ? `[${typed}]` : typed +} + +/** What a setting added from the node starts at: its default, or an empty value of its kind when it has none. */ +export function defaultLiteral(option: SettingOption): string { + if (option.defaultValue !== null && option.defaultValue !== undefined) { + return JSON.stringify(option.defaultValue) + } + return placeholderOf(option.kind) +} + +function placeholderOf(kind: ValueKind): string { + switch (kind.kind) { + case 'boolean': + return 'false' + case 'text': + case 'reference': + case 'resource': + return '""' + case 'enum': + return JSON.stringify(kind.constants[0]?.name ?? '') + case 'list': + return '[]' + case 'integer': + case 'decimal': + case 'any': + return '0' + default: + return '{}' + } +} + +/** What an unset setting falls back to, as the node shows it; empty when it has no default. */ +export function defaultText(option: SettingOption): string { + return option.defaultValue === null || option.defaultValue === undefined ? NOT_SET : textOf(option.kind, option.defaultValue) +} + +/** Why {@code draft} can't be written as the value of {@code option}, or null when it can; an empty draft unsets it. */ +export function problemWith(option: SettingOption, draft: string): string | null { + const { kind } = option + if (draft.trim() === NOT_SET || isText(kind) || kind.kind === 'enum') { + return null + } + if (isNumber(kind)) { + return numberProblem(option, draft) + } + if (isJson(literalOf(kind, draft))) { + return null + } + if (kind.kind === 'any') { + return `Takes a number, or a range like 4${RANGE_DASH}6` + } + return isSpan(kind) ? `Takes a stretch from 0 to 1, like 0.2${RANGE_DASH}0.8` : 'Not JSON' +} + +function numberProblem(option: SettingOption, draft: string): string | null { + const number = Number(draft) + if (!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 } - return draft.trim() } diff --git a/studio/src/renderer/src/studio/CurveEditor.tsx b/studio/src/renderer/src/studio/CurveEditor.tsx new file mode 100644 index 000000000..cc236074e --- /dev/null +++ b/studio/src/renderer/src/studio/CurveEditor.tsx @@ -0,0 +1,298 @@ +import { IdeIcon } from '@/components/IdeIcon' +import { useRef, useState } from 'react' +import { Button } from '@/components/ui/button' +import { Input } from '@/components/ui/input' +import { + CURVE_SHAPES, + isShape, + keyframesFrom, + plotRange, + roundedNumber, + samplesOf, + shapeFrom, + shapeNamed, + sortedKeyframes, + withAddedKeyframe, + withKeyframe, + withoutKeyframe, + withSetting, + withShape, + type Keyframe +} from '../editor/curves' + +const PREVIEW_SAMPLES = 40 +const PREVIEW_WIDTH = 100 +const PREVIEW_HEIGHT = 12 +const PLOT_WIDTH = 280 +const PLOT_HEIGHT = 140 +const PLOT_INSET = 10 +const PLOT_SAMPLES = 96 +const POINT_RADIUS = 4 +const POINTS_HINT = 'Drag a point · Double-click adds · Right-click removes' +const GUIDE_LEVELS = [0, 1] +const DRAGGED_PRECISION = 1000 + +/** A curve drawn across a value's field, its lowest to highest filling the height, with what it starts and ends at beside it. */ +export function CurvePreview({ value }: { value: unknown }): React.JSX.Element { + const samples = samplesOf(value, PREVIEW_SAMPLES) ?? [0] + const low = Math.min(...samples) + const span = Math.max(...samples) - low + const points = samples.map((sample, index) => { + const x = (index / Math.max(1, samples.length - 1)) * PREVIEW_WIDTH + const y = span === 0 ? PREVIEW_HEIGHT / 2 : PREVIEW_HEIGHT - ((sample - low) / span) * PREVIEW_HEIGHT + return `${x.toFixed(1)},${y.toFixed(1)}` + }) + return ( + <> + + + + + {roundedNumber(samples[0])} → {roundedNumber(samples[samples.length - 1])} + + + ) +} + +interface CurveEditorProps { + value: unknown + locked: boolean + /** Called with the curve after every change, so the object bakes again while it is shaped. */ + onWrite(next: unknown): void +} + +/** Edits a value that changes along a part as a curve: points to drag or type, or a named shape with its settings. */ +export function CurveEditor({ value, locked, onWrite }: CurveEditorProps): React.JSX.Element { + const byShape = isShape(value) + return ( +
+
+ + +
+ + {byShape ? } locked={locked} onWrite={onWrite} /> : } +
+ ) +} + +interface PlotDrag { + index: number + keys: Keyframe[] + range: [number, number] +} + +/** The curve from t = 0 to 1, with its points to drag while it is made of points; a drag is written when it ends. */ +function CurvePlot({ value, locked, onWrite }: CurveEditorProps): React.JSX.Element { + const [drag, setDrag] = useState(null) + const [hint, setHint] = useState(POINTS_HINT) + const plot = useRef(null) + const shown = drag?.keys ?? value + const samples = samplesOf(shown, PLOT_SAMPLES) ?? [] + const range = drag?.range ?? plotRange(samples) + const keys = isShape(shown) ? [] : sortedKeyframes(shown as Keyframe[]) + const area = { left: PLOT_INSET, top: PLOT_INSET, width: PLOT_WIDTH - 2 * PLOT_INSET, height: PLOT_HEIGHT - 2 * PLOT_INSET } + const screenX = (t: number): number => area.left + t * area.width + const screenY = (level: number): number => area.top + area.height - ((level - range[0]) / (range[1] - range[0])) * area.height + const keyframeAt = (event: React.PointerEvent | React.MouseEvent): Keyframe => { + const bounds = plot.current!.getBoundingClientRect() + const x = ((event.clientX - bounds.left) / bounds.width) * PLOT_WIDTH + const y = ((event.clientY - bounds.top) / bounds.height) * PLOT_HEIGHT + const t = clamp((x - area.left) / area.width, 0, 1) + const level = range[0] + ((area.top + area.height - y) / area.height) * (range[1] - range[0]) + return [roundTo(t), roundTo(clamp(level, range[0], range[1]))] + } + + // A point stays between its neighbours along t, so the points never swap order under the pointer. + const dragTo = (event: React.PointerEvent): void => { + if (drag === null) { + return + } + const [t, level] = keyframeAt(event) + const earliest = drag.index === 0 ? 0 : drag.keys[drag.index - 1][0] + const latest = drag.index === drag.keys.length - 1 ? 1 : drag.keys[drag.index + 1][0] + const moved: Keyframe = [clamp(t, earliest, latest), level] + setDrag({ ...drag, keys: withKeyframe(drag.keys, drag.index, moved) }) + setHint(`t ${roundedNumber(moved[0])} · ${roundedNumber(moved[1])}`) + } + + const finishDrag = (): void => { + if (drag !== null) { + onWrite(drag.keys) + } + setDrag(null) + setHint(POINTS_HINT) + } + + return ( +
+ !locked && onWrite(sortedKeyframes([...keys, keyframeAt(event)]))} + > + {GUIDE_LEVELS.map((level) => ( + + + + {level} + + + ))} + `${screenX(index / (samples.length - 1)).toFixed(1)},${screenY(sample).toFixed(1)}`).join(' ')} + fill="none" + className="stroke-primary" + strokeWidth={2} + strokeLinecap="round" + strokeLinejoin="round" + /> + {!locked && + keys.map(([t, level], index) => ( + { + event.stopPropagation() + if (event.button === 2) { + return + } + event.currentTarget.ownerSVGElement?.setPointerCapture(event.pointerId) + setDrag({ index, keys, range }) + }} + onContextMenu={(event) => { + event.preventDefault() + event.stopPropagation() + onWrite(withoutKeyframe(keys, index)) + }} + /> + ))} + + {!isShape(value) &&

{hint}

} +
+ ) +} + +function PointsForm({ keys, locked, onWrite }: { keys: Keyframe[]; locked: boolean; onWrite(next: Keyframe[]): void }): React.JSX.Element { + return ( +
+ {keys.map(([t, value], index) => ( +
+ next !== undefined && onWrite(withKeyframe(keys, index, [next, value]))} /> + next !== undefined && onWrite(withKeyframe(keys, index, [t, next]))} /> + +
+ ))} + +
+ ) +} + +function ShapeForm({ shape, locked, onWrite }: { shape: Record; locked: boolean; onWrite(next: unknown): void }): React.JSX.Element { + const named = shapeNamed(shape.shape)! + const numeric = (name: string): number | undefined => (typeof shape[name] === 'number' ? shape[name] : undefined) + return ( +
+ +
+ onWrite(withSetting(shape, 'from', next))} /> + onWrite(withSetting(shape, 'to', next))} /> +
+ {named.parameters.map((parameter) => ( + onWrite(withSetting(shape, parameter.name, next))} + /> + ))} +
+ ) +} + +interface NumberBoxProps { + label: string + value: number | undefined + placeholder?: string + disabled: boolean + /** The number typed, or undefined when it was emptied; text that is no number is dropped. */ + onCommit(next: number | undefined): void +} + +function NumberBox({ label, value, placeholder, disabled, onCommit }: NumberBoxProps): React.JSX.Element { + const shown = value === undefined ? '' : String(value) + const [draft, setDraft] = useState(shown) + const [seen, setSeen] = useState(shown) + if (seen !== shown) { + setSeen(shown) + setDraft(shown) + } + const commit = (): void => { + if (draft === shown) { + return + } + const next = draft.trim() === '' ? undefined : Number(draft) + if (next !== undefined && !Number.isFinite(next)) { + setDraft(shown) + return + } + onCommit(next) + } + return ( + + ) +} + +function roundTo(value: number): number { + return Math.round(value * DRAGGED_PRECISION) / DRAGGED_PRECISION +} + +function clamp(value: number, lowest: number, highest: number): number { + return Math.min(highest, Math.max(lowest, value)) +} diff --git a/studio/src/renderer/src/studio/CurveField.tsx b/studio/src/renderer/src/studio/CurveField.tsx deleted file mode 100644 index a88f6d010..000000000 --- a/studio/src/renderer/src/studio/CurveField.tsx +++ /dev/null @@ -1,190 +0,0 @@ -import { IdeIcon } from '@/components/IdeIcon' -import { useState } from 'react' -import { Button } from '@/components/ui/button' -import { Input } from '@/components/ui/input' -import { cn } from '@/lib/utils' -import { - CURVE_SHAPES, - isShape, - keyframesFrom, - samplesOf, - shapeFrom, - shapeNamed, - withAddedKeyframe, - withKeyframe, - withoutKeyframe, - withSetting, - withShape, - type Keyframe -} from '../editor/curves' -import { FieldRow, type SettingFieldProps } from './FieldRow' - -const SPARKLINE_WIDTH = 100 -const SPARKLINE_HEIGHT = 24 -const SPARKLINE_SAMPLES = 40 -const SPARKLINE_MARGIN = 2 - -interface CurveFieldProps extends SettingFieldProps { - open: boolean - onToggle(): void -} - -/** A value written as a curve: a sparkline of it that opens an editor for its keyframes, or for the named shape it follows. */ -export function CurveField(props: CurveFieldProps): React.JSX.Element { - const { value, locked, open, onToggle, onSet } = props - return ( - <> - - - - {open && onSet(JSON.stringify(next))} />} - - ) -} - -function Sparkline({ value }: { value: unknown }): React.JSX.Element { - const samples = samplesOf(value, SPARKLINE_SAMPLES) ?? [] - const low = Math.min(...samples) - const span = Math.max(...samples) - low - const drawable = SPARKLINE_HEIGHT - 2 * SPARKLINE_MARGIN - const points = samples.map((sample, index) => { - const x = (index / (samples.length - 1)) * SPARKLINE_WIDTH - const y = SPARKLINE_MARGIN + (span === 0 ? drawable / 2 : drawable - ((sample - low) / span) * drawable) - return `${x.toFixed(1)},${y.toFixed(1)}` - }) - return ( - - - - ) -} - -function CurveEditor({ value, locked, onWrite }: { value: unknown; locked: boolean; onWrite(next: unknown): void }): React.JSX.Element { - const byShape = isShape(value) - return ( -
-
- - -
- {isShape(value) ? : } -
- ) -} - -function PointsEditor({ keys, locked, onWrite }: { keys: Keyframe[]; locked: boolean; onWrite(next: Keyframe[]): void }): React.JSX.Element { - return ( - <> - {keys.map(([t, value], index) => ( -
- next !== undefined && onWrite(withKeyframe(keys, index, [next, value]))} /> - next !== undefined && onWrite(withKeyframe(keys, index, [t, next]))} /> - -
- ))} - - - ) -} - -function ShapeEditor({ shape, locked, onWrite }: { shape: Record; locked: boolean; onWrite(next: unknown): void }): React.JSX.Element { - const named = shapeNamed(shape.shape)! - const numeric = (name: string): number | undefined => (typeof shape[name] === 'number' ? shape[name] : undefined) - return ( - <> - -
- onWrite(withSetting(shape, 'from', next))} /> - onWrite(withSetting(shape, 'to', next))} /> -
- {named.parameters.map((parameter) => ( - onWrite(withSetting(shape, parameter.name, next))} - /> - ))} - - ) -} - -interface NumberBoxProps { - label: string - value: number | undefined - placeholder?: string - disabled: boolean - /** The number typed, or undefined when it was emptied; text that is no number is dropped. */ - onCommit(next: number | undefined): void -} - -function NumberBox({ label, value, placeholder, disabled, onCommit }: NumberBoxProps): React.JSX.Element { - const shown = value === undefined ? '' : String(value) - const [draft, setDraft] = useState(shown) - const [seen, setSeen] = useState(shown) - if (seen !== shown) { - setSeen(shown) - setDraft(shown) - } - const commit = (): void => { - if (draft === shown) { - return - } - const next = draft.trim() === '' ? undefined : Number(draft) - if (next !== undefined && !Number.isFinite(next)) { - setDraft(shown) - return - } - onCommit(next) - } - return ( - - ) -} diff --git a/studio/src/renderer/src/studio/FieldRow.tsx b/studio/src/renderer/src/studio/FieldRow.tsx deleted file mode 100644 index 08a16163a..000000000 --- a/studio/src/renderer/src/studio/FieldRow.tsx +++ /dev/null @@ -1,41 +0,0 @@ -import { IdeIcon } from '@/components/IdeIcon' -import { Button } from '@/components/ui/button' -import { cn } from '@/lib/utils' -import type { SettingOption } from '../bridge/types' - -export 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 -} - -/** A setting's name on the left and, on the right, what edits it, with the button that unsets it and why the draft is refused. */ -export function FieldRow({ option, value, locked, onUnset, problem, children }: SettingFieldProps & { problem: string | null; children: React.ReactNode }): React.JSX.Element { - return ( -
-
- -
- {children} - -
-
- {problem !== null &&

{problem}

} -
- ) -} - -export 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}` -} diff --git a/studio/src/renderer/src/studio/NodeBox.tsx b/studio/src/renderer/src/studio/NodeBox.tsx new file mode 100644 index 000000000..8081b5eec --- /dev/null +++ b/studio/src/renderer/src/studio/NodeBox.tsx @@ -0,0 +1,94 @@ +import { memo } from 'react' +import { cn } from '@/lib/utils' +import type { GraphNode } from '../bridge/types' +import { NODE_WIDTH, type PlacedNode, type Point } from '../editor/nodeLayout' +import { NODE_HEADER, NODE_STRIPE, type NodeRows } from '../editor/nodeRows' +import { colorOfKind, colorOfRole } from './nodeColors' +import { NodeRowView } from './NodeRows' + +/** Where a node's ports sit below its top: level with the middle of its header. */ +export const PORT_TOP = NODE_STRIPE + NODE_HEADER / 2 +const PORT_SIZE = 9 +const CHIP_FILL_ALPHA = '47' + +interface NodeBoxProps { + placed: PlacedNode + rows: NodeRows + selected: boolean + /** Whether the part being dragged would grow from it if dropped now. */ + dropTarget: boolean + /** How far it is being dragged from where it sits, or null. */ + offset: Point | null + /** Whether the file can be written. */ + locked: boolean +} + +/** + * One node as the editor draws it: a stripe in the colour of its kind, a header with its title and roles, and a row + * per setting, edited in place. A part has an input port on its left, a ring to drag when it can grow elsewhere; a + * node others grow from has an output port on its right. + */ +export const NodeBox = memo(function NodeBox({ placed, rows, selected, dropTarget, offset, locked }: NodeBoxProps): React.JSX.Element { + const { node } = placed + const editable = !locked && node.settings.length > 0 + return ( +
+
+ + {rows.rows.map((row) => ( + + ))} + {placed.grown && } + {placed.growing && } +
+ ) +}) + +function NodeHeader({ node }: { node: GraphNode }): React.JSX.Element { + return ( +
+ + {node.title} + + {node.roles.map((role) => ( + + ))} +
+ ) +} + +function RoleChip({ role }: { role: string }): React.JSX.Element { + const color = colorOfRole(role) + return ( + + {role} + + ) +} + +// A part that can grow elsewhere has a ring for an input, a handle to drag onto the node it should grow from. +function InputPort({ handle }: { handle: boolean }): React.JSX.Element { + return ( + + ) +} + +function portStyle(side: 'left' | 'right'): React.CSSProperties { + return { [side]: -PORT_SIZE / 2, top: PORT_TOP - PORT_SIZE / 2, width: PORT_SIZE, height: PORT_SIZE } +} diff --git a/studio/src/renderer/src/studio/NodeCanvas.tsx b/studio/src/renderer/src/studio/NodeCanvas.tsx index 8b357bd2f..19fd9df10 100644 --- a/studio/src/renderer/src/studio/NodeCanvas.tsx +++ b/studio/src/renderer/src/studio/NodeCanvas.tsx @@ -1,314 +1,293 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react' -import { ContextMenu, ContextMenuContent, ContextMenuItem, ContextMenuSeparator, ContextMenuShortcut, ContextMenuSub, ContextMenuSubContent, ContextMenuSubTrigger, ContextMenuTrigger } from '@/components/ui/context-menu' -import { IdeIcon, type IdeIconName } from '@/components/IdeIcon' -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' -import { useKeyText } from './useBindings' +import { ContextMenu, ContextMenuTrigger } from '@/components/ui/context-menu' +import type { GraphEdit, GraphNode, SettingsType } from '../bridge/types' +import { boundsOf, canRegrow, GRID, idOf, layoutNodes, NODE_WIDTH, nodeAt, snappedToGrid, type PlacedNode, type Point } from '../editor/nodeLayout' +import { positionsAfterEdit } from '../editor/nodePositions' +import { nodeRows, type NodeRows } from '../editor/nodeRows' +import type { SuggestionStore } from '../editor/suggestionStore' +import { rolesOf, type SuggestionSource } from '../editor/suggestions' +import { NodeBox } from './NodeBox' +import { NodeEditingContext, type NodeEditing, type SettingRow } from './nodeEditing' +import { NodeMenu, type MenuTarget } from './NodeMenus' +import { NodeWires } from './NodeWires' +import { useNodeCamera, type Camera } from './useNodeCamera' +import { useNodePositions } from './useNodePositions' -const PART_ICON: IdeIconName = 'views/procedural' -const KIND_ICONS: Record = { - Object: 'views/objects', - Stem: PART_ICON, - Blob: PART_ICON, - Branches: PART_ICON, - Cluster: PART_ICON, - Group: 'groups', - 'Shared part': 'symlink', - Material: 'views/palettes', - Decoration: 'decoration' -} -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 +const DRAG_START_PIXELS = 3 +const MIDDLE_BUTTON = 1 +const SMALLEST_DOT_SPACING = 6 +const DOT_RADIUS = 1 -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 -} +/** A node being dragged to another place, or a part's ring being dragged onto the node it should grow from. */ +type NodeGesture = + | { kind: 'moving'; placed: PlacedNode; start: Point; moved: boolean; offset: Point } + | { kind: 'regrowing'; placed: PlacedNode; pointer: Point; target: PlacedNode | null } interface NodeCanvasProps { roots: GraphNode[] - /** Tells files apart, so a new one is fitted into view. */ - fileKey: string + types: Record + /** The file parsed, to read what each setting is set to. */ + values: unknown + /** The file, by its place in the pack, which keeps where its nodes were dragged. */ + file: string selectedId: string | null locked: boolean + suggestions: SuggestionStore /** Filled with the way to fit every node into view, for the keys that live outside the canvas. */ showAllRef: React.RefObject<(() => void) | null> 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, showAllRef, onSelect, onEdit }: NodeCanvasProps): React.JSX.Element { - const layout = useMemo(() => layoutNodes(roots), [roots]) +/** + * The file's nodes on a grid, each listing its settings to edit in place, wired to the nodes they grow from. Drag the + * background to look around, a node to move it, and a part's ring onto another node to grow it from there. + */ +export function NodeCanvas({ roots, types, values, file, selectedId, locked, suggestions, showAllRef, onSelect, onEdit }: NodeCanvasProps): React.JSX.Element { 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 showAll = useCallback(() => setCamera(fitted(frame.current!, layout)), [setCamera, layout]) + const [open, setOpen] = useState>(new Set()) + const [openCurve, setOpenCurve] = useState(null) + const [positions, setPositions] = useNodePositions(file) + const rowsById = useMemo(() => rowsOfNodes(roots, types, values, open, !locked), [roots, types, values, open, locked]) + const layout = useMemo(() => layoutNodes(roots, (node) => rowsById.get(idOf(node.path))!.height, new Map(Object.entries(positions))), [roots, rowsById, positions]) + const view = useNodeCamera(frame, boundsOf(layout.nodes)) + const [gesture, setGesture] = useState(null) + const [menu, setMenu] = useState(null) + const panFrom = useRef(null) + const settingUnderMenu = useRef(null) + const chosenHere = useRef(null) + + const edit = useCallback( + (change: GraphEdit) => { + setPositions((current) => positionsAfterEdit(current, change, values)) + onEdit(change) + }, + [setPositions, onEdit, values] + ) + const select = useCallback( + (node: GraphNode) => { + chosenHere.current = idOf(node.path) + onSelect(node) + }, + [onSelect] + ) + const { showAll } = view + const showEveryNode = useCallback(() => showAll(boundsOf(layout.nodes)), [showAll, layout]) useEffect(() => { - showAllRef.current = showAll + showAllRef.current = showEveryNode return () => { showAllRef.current = null } - }, [showAllRef, showAll]) + }, [showAllRef, showEveryNode]) + useRevealChosen(layout.nodes, selectedId, chosenHere, view.reveal) + const editing = useEditing({ roots, locked, openCurve, setOpenCurve, setOpen, edit, suggestions, settingUnderMenu }) - 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) { + const pointerDown = (event: React.PointerEvent): void => { + const target = event.target as Element + if (!event.currentTarget.contains(target) || (event.button !== 0 && event.button !== MIDDLE_BUTTON)) { + return + } + const placed = event.button === 0 ? placedUnder(target, layout.nodes) : null + if (placed === null) { + event.currentTarget.setPointerCapture(event.pointerId) + panFrom.current = { x: event.clientX, y: event.clientY } + return + } + select(placed.node) + if (target.closest('[data-node-control]') !== null) { 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 + if (target.closest('[data-port="regrow"]') !== null) { + setGesture({ kind: 'regrowing', placed, pointer: view.graphPoint(event.clientX, event.clientY), target: null }) + } else { + setGesture({ kind: 'moving', placed, start: { x: event.clientX, y: event.clientY }, moved: false, offset: { x: 0, y: 0 } }) } - 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 })) + if (panFrom.current !== null) { + view.panBy(event.clientX - panFrom.current.x, event.clientY - panFrom.current.y) + panFrom.current = { x: event.clientX, y: event.clientY } return } - if (drag === null) { - return + if (gesture?.kind === 'moving') { + const [dx, dy] = [event.clientX - gesture.start.x, event.clientY - gesture.start.y] + const moved = gesture.moved || Math.hypot(dx, dy) > DRAG_START_PIXELS + setGesture({ ...gesture, moved, offset: moved ? { x: dx / view.camera.scale, y: dy / view.camera.scale } : gesture.offset }) + } else if (gesture?.kind === 'regrowing') { + const pointer = view.graphPoint(event.clientX, event.clientY) + const over = nodeAt(layout.nodes, pointer) + const takesIt = over !== null && over !== gesture.placed && canRegrow(gesture.placed.node, over.node) + setGesture({ ...gesture, pointer, target: takesIt ? over : null }) } - 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 + panFrom.current = null + setGesture(null) + if (gesture?.kind === 'moving' && gesture.moved) { + const { placed, offset } = gesture + const dropped = { x: snappedToGrid(placed.x + offset.x), y: snappedToGrid(placed.y + offset.y) } + if (dropped.x !== placed.x || dropped.y !== placed.y) { + setPositions((current) => ({ ...current, [placed.id]: dropped })) + } + } else if (gesture?.kind === 'regrowing' && gesture.target !== null) { + edit({ op: 'move', path: gesture.placed.node.path, toList: gesture.target.node.childList! }) } - 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 + const contextMenu = (event: React.MouseEvent): void => { + const target = event.target as Element + const setting = settingUnderMenu.current + settingUnderMenu.current = null + if (!event.currentTarget.contains(target)) { + event.preventDefault() + return + } + const placed = placedUnder(target, layout.nodes) + if (placed === null) { + setMenu({ on: 'background', root: roots[0] ?? null }) + return + } + select(placed.node) + setMenu({ on: 'node', node: placed.node, setting }) + } + + const moved = gesture?.kind === 'moving' && gesture.moved ? { id: gesture.placed.id, offset: gesture.offset } : null + const regrow = gesture?.kind === 'regrowing' ? { part: gesture.placed, pointer: gesture.pointer, onTarget: gesture.target !== null } : null + const dropTargetId = gesture?.kind === 'regrowing' ? (gesture.target?.id ?? null) : null + const { camera } = view return ( - !open && setMenuNode(null)}> + !isOpen && setMenu(null)}>
{ - pan.current = null - setDrag(null) + panFrom.current = null + setGesture(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 && showAll()} + onContextMenu={contextMenu} + onDoubleClick={(event) => placedUnder(event.target as Element, layout.nodes) === null && event.currentTarget.contains(event.target as Element) && showEveryNode()} >
- - {layout.nodes.map((placed) => ( - - ))} + + + {layout.nodes.map((placed) => ( + + ))} +
+ {Math.abs(camera.scale - 1) > 0.001 && ( + {Math.round(camera.scale * 100)}% + )}
- {menuNode !== null && } + {menu !== null && ( + setPositions({})} + onShowAll={showEveryNode} + onResetZoom={view.resetZoom} + /> + )}
) } -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] ?? PART_ICON - 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 keyText = useKeyText() - 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 - {keyText('duplicateNode')} - - - onEdit({ op: 'delete', path: node.path })}> - Delete - {keyText('deleteNode')} - - - ) -} - -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 +function rowsOfNodes(roots: GraphNode[], types: Record, values: unknown, open: ReadonlySet, editable: boolean): Map { + const rows = new Map() + const visit = (node: GraphNode): void => { + rows.set(idOf(node.path), nodeRows(node, types, values, open, editable)) + node.children.forEach((link) => visit(link.node)) } - return over + roots.forEach(visit) + return rows } -function isParentList(path: JsonPath, list: JsonPath): boolean { - return path.length === list.length + 1 && isWithin(path, list) +function placedUnder(target: Element, nodes: PlacedNode[]): PlacedNode | null { + const id = target.closest('[data-node-id]')?.getAttribute('data-node-id') + return nodes.find((placed) => placed.id === id) ?? null } -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) +// Each dot sits on a point nodes snap to, so they stay on the dots at any zoom. +function gridStyle(camera: Camera): React.CSSProperties { + const spacing = GRID * camera.scale + if (spacing < SMALLEST_DOT_SPACING) { + return {} + } + return { + backgroundImage: `radial-gradient(circle at ${DOT_RADIUS}px ${DOT_RADIUS}px, var(--overlay-border) ${DOT_RADIUS}px, transparent ${DOT_RADIUS + 0.5}px)`, + backgroundSize: `${spacing}px ${spacing}px`, + backgroundPosition: `${camera.x - DOT_RADIUS}px ${camera.y - DOT_RADIUS}px` + } +} +// A node chosen elsewhere, such as by picking its part in the scene, is brought into sight; one chosen here already is. +function useRevealChosen(nodes: PlacedNode[], selectedId: string | null, chosenHere: React.RefObject, reveal: (area: { left: number; top: number; right: number; bottom: number }) => void): void { + const handled = useRef(null) useEffect(() => { - if (frame.current === null || layout.nodes.length === 0 || fittedFile.current === fileKey) { + if (selectedId === handled.current) { return } - fittedFile.current = fileKey - setCamera(fitted(frame.current, layout)) - }, [frame, layout, fileKey]) - - useEffect(() => { - const element = frame.current - if (element === null) { + handled.current = selectedId + const placed = nodes.find((candidate) => candidate.id === selectedId) + if (placed === undefined || selectedId === chosenHere.current) { 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] + reveal({ left: placed.x, top: placed.y, right: placed.x + NODE_WIDTH, bottom: placed.y + placed.height }) + }, [nodes, selectedId, chosenHere, reveal]) } -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) } +interface EditingInputs { + roots: GraphNode[] + locked: boolean + openCurve: string | null + setOpenCurve(rowId: string | null): void + setOpen: React.Dispatch>> + edit(change: GraphEdit): void + suggestions: SuggestionStore + settingUnderMenu: React.RefObject } -function clamp(value: number, lowest: number, highest: number): number { - return Math.min(highest, Math.max(lowest, value)) +function useEditing({ roots, locked, openCurve, setOpenCurve, setOpen, edit, suggestions, settingUnderMenu }: EditingInputs): NodeEditing { + const roles = useMemo(() => rolesOf(roots), [roots]) + return useMemo( + () => ({ + locked, + openCurve, + onOpenCurve: setOpenCurve, + onToggleFold: (foldId: string) => + setOpen((current) => { + const next = new Set(current) + if (!next.delete(foldId)) { + next.add(foldId) + } + return next + }), + onEdit: edit, + loadSuggestions: (source: SuggestionSource) => (source.from === 'roles' ? Promise.resolve(roles) : suggestions.load(source)), + onSettingMenu: (row: SettingRow) => { + settingUnderMenu.current = row + } + }), + [locked, openCurve, setOpenCurve, setOpen, edit, roles, suggestions, settingUnderMenu] + ) } diff --git a/studio/src/renderer/src/studio/NodeInspector.tsx b/studio/src/renderer/src/studio/NodeInspector.tsx deleted file mode 100644 index c3f60c7ae..000000000 --- a/studio/src/renderer/src/studio/NodeInspector.tsx +++ /dev/null @@ -1,295 +0,0 @@ -import { IdeIcon } from '@/components/IdeIcon' -import { useMemo, useState } from 'react' -import { Button } from '@/components/ui/button' -import { ScrollArea } from '@/components/ui/scroll-area' -import { cn } from '@/lib/utils' -import type { EditorState, GraphEdit, GraphNode, NodeSettings, SettingOption, ValueKind } from '../bridge/types' -import { canBecomeCurve, curveFrom, isCurve } from '../editor/curves' -import { valueAt } from '../editor/jsonValues' -import { foldedSections, idOfFold, visibleFolds, type SettingsFold } from '../editor/settingFolds' -import { NOT_SET, isStringList, isText, literalOf, textOf } from '../editor/settingText' -import type { SuggestionStore } from '../editor/suggestionStore' -import { rolesOf, suggestionSourceOf, type SuggestionSource } from '../editor/suggestions' -import { CurveField } from './CurveField' -import { FieldRow, defaultLabel, type SettingFieldProps } from './FieldRow' -import { SuggestionInput } from './SuggestionInput' - -const FOLD_INDENT_PX = 10 - -interface NodeInspectorProps { - node: GraphNode - state: EditorState - /** The file parsed, to read what each setting is set to. */ - values: unknown - suggestions: SuggestionStore - onEdit(edit: GraphEdit): void -} - -/** What the fields of a section share: the file and the edits made to it, and which folds and curves are open. */ -interface SectionContext { - state: EditorState - values: unknown - locked: boolean - open: ReadonlySet - roles: string[] - suggestions: SuggestionStore - onToggle(id: string): void - 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, suggestions, onEdit }: NodeInspectorProps): React.JSX.Element { - const [open, setOpen] = useState>(new Set()) - const roles = useMemo(() => rolesOf(state.roots ?? []), [state.roots]) - const context: SectionContext = { - state, - values, - locked: state.locked !== null, - open, - roles, - suggestions, - onToggle: (id) => - setOpen((current) => { - const next = new Set(current) - if (!next.delete(id)) { - next.add(id) - } - return next - }), - onEdit - } - return ( -
-
-

{node.title}

-

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

-
- -
- {node.settings.map((section) => ( - - ))} -
-
-
- ) -} - -function SettingsSection({ section, context }: { section: NodeSettings; context: SectionContext }): React.JSX.Element { - const { state, values, open } = context - const folds = visibleFolds(foldedSections(section, state.types, values), open) - return ( -
- {folds.map((fold) => - fold.kind === 'own' ? ( -
-

- {fold.title} -

- -
- ) : ( -
- - {open.has(idOfFold(fold)) && } -
- ) - )} -
- ) -} - -function FoldHeader({ fold, context }: { fold: SettingsFold; context: SectionContext }): React.JSX.Element { - const { open, locked, onToggle, onEdit } = context - const id = idOfFold(fold) - const unfolded = open.has(id) - const holder = fold.holder - return ( -
- - {fold.kind === 'list' && ( - - )} - {holder !== null && ( - - )} - {fold.kind === 'item' && ( - - )} -
- ) -} - -function FoldFields({ fold, context }: { fold: SettingsFold; context: SectionContext }): React.JSX.Element { - const { values, locked, open, roles, suggestions, onToggle, onEdit } = context - return ( -
- {fold.options.map((option) => { - const value = valueAt(values, [...fold.path, option.name]) - const curveId = JSON.stringify([...fold.path, option.name]) - return ( - onToggle(curveId)} - loadSuggestions={(source) => (source.from === 'roles' ? Promise.resolve(roles) : suggestions.load(source))} - onSet={(literal) => onEdit({ op: 'set', object: fold.path, key: option.name, literal })} - onUnset={() => onEdit({ op: 'unset', object: fold.path, key: option.name })} - /> - ) - })} -
- ) -} - -interface FieldProps extends SettingFieldProps { - /** The schema type of the object the option is in. */ - owner: string - curveOpen: boolean - onToggleCurve(): void - loadSuggestions(source: SuggestionSource): Promise -} - -function SettingField(props: FieldProps): React.JSX.Element { - const kind = props.option.kind.kind - if (kind === 'boolean' || kind === 'enum') { - return - } - if (kind === 'any' && isCurve(props.value)) { - return - } - return -} - -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 literalOfChoice = (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. -// A number or range of an option that takes any JSON value can be made a curve, which a curve is an option's to take. -function TypedField(props: FieldProps): React.JSX.Element { - const { option, value, locked, owner, onSet, onUnset, onToggleCurve, loadSuggestions } = props - const shown = textOf(option.kind, value) - const [draft, setDraft] = useState(shown) - const problem = draft.trim() === NOT_SET ? null : problemWith(option, draft) - const source = suggestionSourceOf(owner, option) - const commit = (): void => { - if (draft === shown || problem !== null) { - return - } - if (draft.trim() === NOT_SET) { - onUnset() - return - } - onSet(literalOf(option.kind, draft)) - } - return ( - - loadSuggestions(source)} - 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]')} - onBlur={commit} - onKeyDown={(event) => { - if (event.key === 'Enter') { - commit() - } else if (event.key === 'Escape') { - setDraft(shown) - } - }} - /> - {option.kind.kind === 'any' && canBecomeCurve(value) && ( - - )} - - ) -} - -function isNumber(kind: ValueKind): boolean { - return kind.kind === 'integer' || kind.kind === 'decimal' -} - -function problemWith(option: SettingOption, draft: string): string | null { - if (isText(option.kind) || isStringList(option.kind)) { - return isStringList(option.kind) && draft.trim().startsWith('[') && !isJson(draft) ? 'Not JSON' : 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/studio/src/renderer/src/studio/NodeMenus.tsx b/studio/src/renderer/src/studio/NodeMenus.tsx new file mode 100644 index 000000000..e0cdcec0c --- /dev/null +++ b/studio/src/renderer/src/studio/NodeMenus.tsx @@ -0,0 +1,135 @@ +import { ContextMenuContent, ContextMenuItem, ContextMenuSeparator, ContextMenuShortcut, ContextMenuSub, ContextMenuSubContent, ContextMenuSubTrigger } from '@/components/ui/context-menu' +import type { GraphEdit, GraphNode } from '../bridge/types' +import { canBecomeCurve, curveFrom, isCurve, roundedNumber, samplesOf } from '../editor/curves' +import { idOf } from '../editor/nodeLayout' +import type { SettingRow } from './nodeEditing' +import { useKeyText } from './useBindings' + +const ADD_PREFIX = 'Add ' + +/** What a right-click is on: a node, and the setting under the pointer if any; or the background, with the file's first node. */ +export type MenuTarget = { on: 'node'; node: GraphNode; setting: SettingRow | null } | { on: 'background'; root: GraphNode | null } + +interface NodeMenuProps { + target: MenuTarget + locked: boolean + onEdit(edit: GraphEdit): void + onOpenCurve(rowId: string): void + onArrange(): void + onShowAll(): void + onResetZoom(): void +} + +export function NodeMenu(props: NodeMenuProps): React.JSX.Element { + const { target } = props + return {target.on === 'node' ? : } +} + +function NodeItems({ node, setting, locked, onEdit, onOpenCurve }: NodeMenuProps & { node: GraphNode; setting: SettingRow | null }): React.JSX.Element { + const keyText = useKeyText() + const isRoot = node.path.length === 0 + return ( + <> + {setting !== null && } + + {!isRoot && ( + <> + {node.additions.length > 0 && } + onEdit({ op: 'duplicate', path: node.path })}> + Duplicate + {keyText('duplicateNode')} + + onEdit({ op: 'delete', path: node.path })}> + {node.children.length === 0 ? 'Delete' : 'Delete with what grows from it'} + {keyText('deleteNode')} + + + )} + + ) +} + +// A value that runs along a part can be turned into a curve and back, at the top of its node's menu. +function CurveItems({ setting, locked, onEdit, onOpenCurve }: { setting: SettingRow; locked: boolean; onEdit(edit: GraphEdit): void; onOpenCurve(rowId: string): void }): React.JSX.Element | null { + const { option, fold, value } = setting + const current = value ?? option.defaultValue + if (option.kind.kind !== 'any' || (!isCurve(current) && !canBecomeCurve(current))) { + return null + } + const set = (literal: string): void => onEdit({ op: 'set', object: fold.path, key: option.name, literal }) + const makeCurve = (): void => { + set(JSON.stringify(curveFrom(current))) + onOpenCurve(setting.id) + } + return ( + <> + {isCurve(current) ? ( + set(roundedNumber(samplesOf(current, 1)![0]))}> + Make it one number + + ) : ( + + Make it a curve + + )} + + + ) +} + +/** + * What can be added under the node: the parts it can grow in one submenu, anything else, like the object's materials + * and decorations, as an item each. + */ +function AdditionItems({ node, locked, onEdit }: { node: GraphNode; locked: boolean; onEdit(edit: GraphEdit): void }): React.JSX.Element { + const byList = new Map() + for (const addition of node.additions) { + byList.set(idOf(addition.list), [...(byList.get(idOf(addition.list)) ?? []), addition]) + } + const partsTitle = node.path.length === 0 ? 'Add part' : 'Add part growing from this' + return ( + <> + {[...byList.entries()].map(([list, additions]) => + additions.length > 1 ? ( + + {partsTitle} + + {additions.map((addition) => ( + onEdit({ op: 'append', list: addition.list, literal: addition.literal })}> + {addition.label} + + ))} + + + ) : ( + onEdit({ op: 'append', list: additions[0].list, literal: additions[0].literal })}> + {ADD_PREFIX + additions[0].label.toLowerCase()} + + ) + )} + + ) +} + +function BackgroundItems({ root, locked, onEdit, onArrange, onShowAll, onResetZoom }: NodeMenuProps & { root: GraphNode | null }): React.JSX.Element { + const keyText = useKeyText() + return ( + <> + {root !== null && root.additions.length > 0 && ( + <> + + + + )} + Arrange nodes + + Show every node + {keyText('showAllNodes')} + + + Reset zoom + {keyText('resetZoom')} + + + ) +} diff --git a/studio/src/renderer/src/studio/NodePane.tsx b/studio/src/renderer/src/studio/NodePane.tsx index cec2168a0..60f9dcbcf 100644 --- a/studio/src/renderer/src/studio/NodePane.tsx +++ b/studio/src/renderer/src/studio/NodePane.tsx @@ -2,24 +2,30 @@ import { IdeIcon } from '@/components/IdeIcon' import { useEffect, useRef } from 'react' import { Button } from '@/components/ui/button' import type { GraphNode } from '../bridge/types' +import { idOf } from '../editor/nodeLayout' +import type { SuggestionStore } from '../editor/suggestionStore' import type { NodeEditor } from '../editor/useNodeEditor' import { NodeCanvas } from './NodeCanvas' import { isInEntryBrowser, isTypingInto, nodeEditorActionFor, type NodeEditorAction } from './shortcuts' -import { useBindings } from './useBindings' +import { useBindings, useKeyText } from './useBindings' interface NodePaneProps { editor: NodeEditor /** The entry the file belongs to. */ entryKey: string + /** The file parsed, to read what each setting is set to. */ + values: unknown + suggestions: SuggestionStore 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 { +/** The node editor under the scene: the entry's file as nodes, their settings edited in place, with undo and redo. */ +export function NodePane({ editor, entryKey, values, suggestions, selected, onSelect }: NodePaneProps): React.JSX.Element { const { state } = editor const locked = state === null || state.locked !== null const showAllRef = useRef<(() => void) | null>(null) + const keyText = useKeyText() useEditorKeys(editor, selected, locked, showAllRef, onSelect) return ( @@ -28,6 +34,7 @@ export function NodePane({ editor, entryKey, selected, onSelect }: NodePaneProps

Nodes

{state?.file ?? entryKey} + {!locked && Right-click to add or delete · Drag a ring onto a node to regrow · {keyText('undo')} undoes} {state?.locked != null && ( @@ -52,10 +59,14 @@ export function NodePane({ editor, entryKey, selected, onSelect }: NodePaneProps )} {state !== null && state.roots !== null && ( + case 'fold': + return + case 'setting': + return + case 'addSetting': + return + } +} + +function HeadingRow({ title }: { title: string }): React.JSX.Element { + return ( +
+ {title} +
+ ) +} + +// ▸ palette zoom 2 · palette 3 folded; ▾ palette open. A list gets a + to add an element, an element a × to remove it. +function FoldRow({ fold, open, editable }: { fold: SettingsFold; open: boolean; editable: boolean }): React.JSX.Element { + const { onToggleFold, onEdit } = useNodeEditing() + const holder = fold.holder + const showsSummary = !open || fold.kind === 'list' + return ( +
+ + {fold.kind === 'list' &&
+ ) +} + +/** Offers the settings left at their default, a submenu per section when more than one has some. */ +function AddSettingRow({ addable }: { addable: SettingsFold[] }): React.JSX.Element { + return ( +
+ + + + + + {addable.length === 1 ? ( + + ) : ( + addable.map((fold) => ( + + {sectionLabel(fold)} + + + + + )) + )} + + +
+ ) +} + +function UnsetItems({ fold }: { fold: SettingsFold }): React.JSX.Element { + const { onEdit } = useNodeEditing() + const add = (option: SettingOption): void => onEdit({ op: 'set', object: fold.path, key: option.name, literal: defaultLiteral(option) }) + return ( + <> + {fold.unset.map((option) => ( + add(option)}> + {option.name} + {defaultText(option)} + + ))} + + ) +} + +function sectionLabel(fold: SettingsFold): string { + return fold.kind === 'item' ? `${String(fold.path.at(-2))} #${fold.title}` : fold.title +} diff --git a/studio/src/renderer/src/studio/NodeSettingRow.tsx b/studio/src/renderer/src/studio/NodeSettingRow.tsx new file mode 100644 index 000000000..272c353b4 --- /dev/null +++ b/studio/src/renderer/src/studio/NodeSettingRow.tsx @@ -0,0 +1,266 @@ +import { IdeIcon } from '@/components/IdeIcon' +import { useRef, useState } from 'react' +import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from '@/components/ui/dropdown-menu' +import { Popover, PopoverAnchor, PopoverContent } from '@/components/ui/popover' +import { cn } from '@/lib/utils' +import { isCurve } from '../editor/curves' +import { NODE_ROW } from '../editor/nodeRows' +import { defaultText, isNumber, isStringList, literalOf, NOT_SET, problemWith, textOf } from '../editor/settingText' +import { suggestionSourceOf } from '../editor/suggestions' +import { CurveEditor, CurvePreview } from './CurveEditor' +import { useNodeEditing, type SettingRow } from './nodeEditing' +import { SuggestionInput } from './SuggestionInput' + +export const ROW_LABEL_WIDTH = 86 +export const ROW_INDENT = 10 +const FIELD = 'flex h-5 w-full min-w-0 items-center gap-1.5 rounded-sm border border-input bg-muted px-1.5 text-left' +const EDITABLE_FIELD = 'hover:border-secondary-text' +const CURVE_HINT = 'Click to shape the curve · right-click to make it one number' + +interface SettingRowProps { + row: SettingRow + /** Whether its value can be changed: the file can be written and the node has settings of its own. */ + editable: boolean +} + +/** One setting of a node: its name, its value edited in place, and a control to remove it so it falls back to its default. */ +export function NodeSettingRow({ row, editable }: SettingRowProps): React.JSX.Element { + const { onEdit } = useNodeEditing() + const { option, fold, value } = row + const fallback = defaultText(option) + return ( +
+ + {option.name} + +
+ +
+
+ ) +} + +interface RowButtonProps { + glyph: '×' | '+' + tone: 'remove' | 'add' + hidden?: boolean + title: string + onClick(): void +} + +/** The small round control at a row's right end: × removes, + adds. */ +export function RowButton({ glyph, tone, hidden = false, title, onClick }: RowButtonProps): React.JSX.Element { + return ( + + ) +} + +function SettingValue({ row, editable }: SettingRowProps): React.JSX.Element { + const kind = row.option.kind.kind + if (kind === 'boolean') { + return + } + if (kind === 'enum') { + return + } + if (kind === 'any' && isCurve(row.value)) { + return + } + return +} + +/** The value as the field shows it, or the default it falls back to, dimmed, while it is unset. */ +function ShownText({ row }: { row: SettingRow }): React.JSX.Element { + const isSet = row.value !== undefined + const text = isSet ? textOf(row.option.kind, row.value) : defaultText(row.option) + return {text} +} + +function CheckValue({ row, editable }: SettingRowProps): React.JSX.Element { + const { onEdit } = useNodeEditing() + const checked = (row.value ?? row.option.defaultValue) === true + return ( + + ) +} + +function ChoiceValue({ row, editable }: SettingRowProps): React.JSX.Element { + const { onEdit } = useNodeEditing() + const constants = row.option.kind.kind === 'enum' ? row.option.kind.constants : [] + const current = row.value ?? row.option.defaultValue + return ( + + + + + + {constants.map((constant) => ( + onEdit({ op: 'set', object: row.fold.path, key: row.option.name, literal: JSON.stringify(constant.name) })} + > + {constant.name} + + ))} + + + ) +} + +function CurveValue({ row, editable }: SettingRowProps): React.JSX.Element { + const { openCurve, onOpenCurve, onEdit, onSettingMenu } = useNodeEditing() + return ( + onOpenCurve(open ? row.id : null)}> + + + + event.preventDefault()}> + onEdit({ op: 'set', object: row.fold.path, key: row.option.name, literal: JSON.stringify(next) })} /> + + + ) +} + +// Clicked, the value turns into a text field over the same spot until it is saved or given up. +function TypedValue({ row, editable }: SettingRowProps): React.JSX.Element { + const { onSettingMenu } = useNodeEditing() + const [typing, setTyping] = useState(false) + if (typing) { + return setTyping(false)} /> + } + return ( + + ) +} + +/** + * The value being typed. Enter saves it, or keeps it open to fix with why it was refused; leaving the field saves it + * too, or puts back what was saved when it is refused. Escape gives it up, and an emptied value is removed. + */ +function ValueInput({ row, onDone }: { row: SettingRow; onDone(): void }): React.JSX.Element { + const { onEdit, loadSuggestions } = useNodeEditing() + const { option, fold, value } = row + const saved = textOf(option.kind, value) + const [draft, setDraft] = useState(saved) + const [shownProblem, setShownProblem] = useState(null) + const finished = useRef(false) + const source = suggestionSourceOf(fold.type, option) + + // The field leaving the page can blur it once more, which must not save a second time. + const finish = (): void => { + finished.current = true + onDone() + } + + const commit = (stayOnRefusal: boolean): void => { + if (finished.current) { + return + } + const problem = problemWith(option, draft) + if (problem !== null && stayOnRefusal) { + setShownProblem(problem) + return + } + finish() + if (problem !== null || draft.trim() === saved.trim()) { + return + } + if (draft.trim() === NOT_SET) { + onEdit({ op: 'unset', object: fold.path, key: option.name }) + return + } + onEdit({ op: 'set', object: fold.path, key: option.name, literal: literalOf(option.kind, draft) }) + } + + return ( +
+ { + setDraft(next) + setShownProblem(null) + }} + isList={isStringList(option.kind)} + load={source === null ? null : () => loadSuggestions(source)} + autoFocus + placeholder={defaultText(option)} + aria-invalid={shownProblem !== null} + inputMode={isNumber(option.kind) ? 'decimal' : undefined} + className="h-5 rounded-sm bg-popover px-1.5 py-0 text-[11.5px] shadow-none focus-visible:ring-2 md:text-[11.5px] dark:bg-popover" + onFocus={(event) => event.currentTarget.select()} + onBlur={() => commit(false)} + onKeyDown={(event) => { + if (event.key === 'Enter') { + commit(true) + } else if (event.key === 'Escape') { + event.stopPropagation() + finish() + } + }} + /> + {shownProblem !== null && ( +

+ {shownProblem} +

+ )} +
+ ) +} diff --git a/studio/src/renderer/src/studio/NodeWires.tsx b/studio/src/renderer/src/studio/NodeWires.tsx new file mode 100644 index 000000000..c07bfd1ec --- /dev/null +++ b/studio/src/renderer/src/studio/NodeWires.tsx @@ -0,0 +1,69 @@ +import { memo } from 'react' +import { cn } from '@/lib/utils' +import { NODE_WIDTH, type PlacedNode, type PlacedWire, type Point } from '../editor/nodeLayout' +import { colorOfKind } from './nodeColors' +import { PORT_TOP } from './NodeBox' + +/** The wire to a part placed once per copy, such as a branch of branches, rather than once. */ +export const EACH_COPY_WIRE = 'each copy' +const SMALLEST_BEND = 30 +const COPY_DASH = '5 5' + +/** A node being dragged: how far it is from where it sits. */ +export interface MovedNode { + id: string + offset: Point +} + +/** A part's ring being dragged to grow it elsewhere: the pointer, and whether it is over a node that takes it. */ +export interface RegrowLine { + part: PlacedNode + pointer: Point + onTarget: boolean +} + +interface NodeWiresProps { + wires: PlacedWire[] + selectedId: string | null + moved: MovedNode | null + regrow: RegrowLine | null +} + +/** The wires from each node to the nodes that grow from it; a copy's is dashed in its parent's colour. */ +export const NodeWires = memo(function NodeWires({ wires, selectedId, moved, regrow }: NodeWiresProps): React.JSX.Element { + const at = (placed: PlacedNode): Point => (moved?.id === placed.id ? { x: placed.x + moved.offset.x, y: placed.y + moved.offset.y } : placed) + return ( + + {wires.map(({ from, to, label }) => { + const lit = selectedId === from.id || selectedId === to.id + const copies = label === EACH_COPY_WIRE + const [start, end] = [at(from), at(to)] + return ( + ${to.id}`} + d={curve({ x: start.x + NODE_WIDTH, y: start.y + PORT_TOP }, { x: end.x, y: end.y + PORT_TOP })} + className={cn('fill-none', lit ? 'stroke-primary' : !copies && 'stroke-input')} + style={copies && !lit ? { stroke: colorOfKind(from.node.kind) } : undefined} + strokeWidth={lit ? 2 : 1.5} + strokeDasharray={copies ? COPY_DASH : undefined} + strokeLinecap="round" + /> + ) + })} + {regrow !== null && ( + + )} + + ) +}) + +function curve(from: Point, to: Point): string { + const bend = Math.max(SMALLEST_BEND, Math.abs(to.x - from.x) / 2) + return `M${from.x},${from.y} C${from.x + bend},${from.y} ${to.x - bend},${to.y} ${to.x},${to.y}` +} diff --git a/studio/src/renderer/src/studio/SceneStudio.tsx b/studio/src/renderer/src/studio/SceneStudio.tsx index 27903d64d..5ce5bca74 100644 --- a/studio/src/renderer/src/studio/SceneStudio.tsx +++ b/studio/src/renderer/src/studio/SceneStudio.tsx @@ -19,7 +19,6 @@ import { BakeMeter, useBakeTiming } from './BakeMeter' import { BlockIcon } from './BlockIcon' import { EntryBrowser } from './EntryBrowser' import { useEntryFiles } from './EntryFileDialogs' -import { NodeInspector } from './NodeInspector' import { NodePane } from './NodePane' import { ProfileFormPanel } from './ProfileFormPanel' import { Panel, SidebarPanel, SizeChoice, Stepper, ViewIsland } from './Sidebar' @@ -41,7 +40,7 @@ interface SceneStudioProps { /** * 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. + * editable view shows the entry's file as nodes under the scene, each with its settings edited in place. */ export function SceneStudio({ client, view, packRevision, onSummary, tell }: SceneStudioProps): React.JSX.Element { const [waiting, setWaiting] = useState(null) @@ -150,6 +149,8 @@ export function SceneStudio({ client, view, packRevision, onSummary, tell }: Sce { setSelectedPath(node?.path ?? null) @@ -158,14 +159,10 @@ export function SceneStudio({ client, view, packRevision, onSummary, tell }: Sce /> )}
- + {view.form === true && setTyped({ owner: typedOwner, values: NO_OVERRIDES })} />} {view.baked && entry !== null && } - {selected !== null && editor.state !== null ? ( - - ) : ( - - )} + ) diff --git a/studio/src/renderer/src/studio/nodeColors.ts b/studio/src/renderer/src/studio/nodeColors.ts new file mode 100644 index 000000000..1852c32d8 --- /dev/null +++ b/studio/src/renderer/src/studio/nodeColors.ts @@ -0,0 +1,33 @@ +/** The colours of the node editor: one per kind of node, and one per role so its nodes are found at a glance. */ +const PRIMARY = 'var(--primary)' +const BY_KIND: Record = { + Object: PRIMARY, + Stem: '#c08552', + Blob: '#5fb865', + Branches: '#d9a23f', + Cluster: '#9c7bd6', + Group: '#8c9099', + 'Shared part': '#548af7', + Material: '#d8709a', + Decoration: '#4fb6c6' +} +const ROLE_COLORS = ['#c08552', '#5fb865', '#548af7', '#d9a23f', '#9c7bd6', '#4fb6c6', '#d8709a', '#a3b84f'] +const KNOWN_ROLES: Record = { wood: ROLE_COLORS[0], leaves: ROLE_COLORS[1] } +const FALLBACK_KIND_COLOR = BY_KIND.Group + +export function colorOfKind(kind: string): string { + return BY_KIND[kind] ?? FALLBACK_KIND_COLOR +} + +/** The same role always gets the same colour, wherever it is used. */ +export function colorOfRole(role: string): string { + return KNOWN_ROLES[role] ?? ROLE_COLORS[hashOf(role) % ROLE_COLORS.length] +} + +function hashOf(text: string): number { + let hash = 0 + for (let index = 0; index < text.length; index++) { + hash = (Math.imul(hash, 31) + text.charCodeAt(index)) >>> 0 + } + return hash +} diff --git a/studio/src/renderer/src/studio/nodeEditing.ts b/studio/src/renderer/src/studio/nodeEditing.ts new file mode 100644 index 000000000..1f8195b94 --- /dev/null +++ b/studio/src/renderer/src/studio/nodeEditing.ts @@ -0,0 +1,29 @@ +import { createContext, useContext } from 'react' +import type { GraphEdit } from '../bridge/types' +import type { NodeRow } from '../editor/nodeRows' +import type { SuggestionSource } from '../editor/suggestions' + +export type SettingRow = Extract + +/** What the nodes' rows share: the edits they make to the file, and which curve editor is open. */ +export interface NodeEditing { + locked: boolean + /** The id of the setting row whose curve editor is open, or null. */ + openCurve: string | null + onOpenCurve(rowId: string | null): void + onToggleFold(foldId: string): void + onEdit(edit: GraphEdit): void + loadSuggestions(source: SuggestionSource): Promise + /** Notes the setting a right-click is on, so the node's menu can offer to make it a curve or one number. */ + onSettingMenu(row: SettingRow): void +} + +export const NodeEditingContext = createContext(null) + +export function useNodeEditing(): NodeEditing { + const editing = useContext(NodeEditingContext) + if (editing === null) { + throw new Error('A node row was drawn outside a node canvas') + } + return editing +} diff --git a/studio/src/renderer/src/studio/useNodeCamera.ts b/studio/src/renderer/src/studio/useNodeCamera.ts new file mode 100644 index 000000000..c8ff7b293 --- /dev/null +++ b/studio/src/renderer/src/studio/useNodeCamera.ts @@ -0,0 +1,105 @@ +import { useCallback, useEffect, useState } from 'react' +import { GRID, type Bounds, type Point } from '../editor/nodeLayout' + +const MARGIN = GRID +const SMALLEST_SCALE = 0.25 +const LARGEST_SCALE = 2.5 +const WHEEL_ZOOM_PER_PIXEL = 0.0015 + +/** Where the canvas looks: the screen offset of the graph's origin, and how much it is zoomed. */ +export interface Camera { + x: number + y: number + scale: number +} + +export interface NodeCamera { + camera: Camera + panBy(dx: number, dy: number): void + /** Zooms out, never in past 100%, until every node fits, and centres them. */ + showAll(bounds: Bounds | null): void + resetZoom(): void + /** Moves the view so the rectangle is in sight, when it is not already. */ + reveal(area: Bounds): void + /** The graph point under a point of the window. */ + graphPoint(clientX: number, clientY: number): Point +} + +/** The view of the node canvas in {@code frame}: dragged to pan, zoomed by the wheel around the pointer; it opens at 100% on the top left node. */ +export function useNodeCamera(frame: React.RefObject, opening: Bounds | null): NodeCamera { + const [camera, setCamera] = useState(() => ({ x: MARGIN - (opening?.left ?? MARGIN), y: MARGIN - (opening?.top ?? MARGIN), scale: 1 })) + + useEffect(() => { + const element = frame.current + if (element === null) { + return + } + const wheel = (event: WheelEvent): void => { + event.preventDefault() + const bounds = element.getBoundingClientRect() + setCamera((current) => zoomedAround(current, { x: event.clientX - bounds.left, y: event.clientY - bounds.top }, Math.exp(-event.deltaY * WHEEL_ZOOM_PER_PIXEL))) + } + element.addEventListener('wheel', wheel, { passive: false }) + return () => element.removeEventListener('wheel', wheel) + }, [frame]) + + const panBy = useCallback((dx: number, dy: number) => setCamera((current) => ({ ...current, x: current.x + dx, y: current.y + dy })), []) + + const showAll = useCallback( + (bounds: Bounds | null) => { + const element = frame.current + if (element === null || bounds === null) { + return + } + const [width, height] = [bounds.right - bounds.left + 2 * MARGIN, bounds.bottom - bounds.top + 2 * MARGIN] + const scale = clamp(Math.min(element.clientWidth / width, element.clientHeight / height), SMALLEST_SCALE, 1) + setCamera({ scale, x: element.clientWidth / 2 - ((bounds.left + bounds.right) / 2) * scale, y: element.clientHeight / 2 - ((bounds.top + bounds.bottom) / 2) * scale }) + }, + [frame] + ) + + const resetZoom = useCallback(() => { + const element = frame.current + if (element !== null) { + setCamera((current) => zoomedAround(current, { x: element.clientWidth / 2, y: element.clientHeight / 2 }, 1 / current.scale)) + } + }, [frame]) + + const reveal = useCallback( + (area: Bounds) => { + const element = frame.current + if (element === null) { + return + } + setCamera((current) => { + const [left, top] = [current.x + area.left * current.scale, current.y + area.top * current.scale] + const [right, bottom] = [current.x + area.right * current.scale, current.y + area.bottom * current.scale] + const height = Math.min(bottom - top, element.clientHeight) + const dx = left < 0 || right > element.clientWidth ? MARGIN - left : 0 + const dy = top < 0 || top + height > element.clientHeight ? MARGIN - top : 0 + return dx === 0 && dy === 0 ? current : { ...current, x: current.x + dx, y: current.y + dy } + }) + }, + [frame] + ) + + const graphPoint = useCallback( + (clientX: number, clientY: number): Point => { + const bounds = frame.current!.getBoundingClientRect() + return { x: (clientX - bounds.left - camera.x) / camera.scale, y: (clientY - bounds.top - camera.y) / camera.scale } + }, + [frame, camera] + ) + + return { camera, panBy, showAll, resetZoom, reveal, graphPoint } +} + +function zoomedAround(current: Camera, anchor: Point, factor: number): Camera { + const scale = clamp(current.scale * factor, SMALLEST_SCALE, LARGEST_SCALE) + const ratio = scale / current.scale + return { scale, x: anchor.x - (anchor.x - current.x) * ratio, y: anchor.y - (anchor.y - current.y) * ratio } +} + +function clamp(value: number, lowest: number, highest: number): number { + return Math.min(highest, Math.max(lowest, value)) +} diff --git a/studio/src/renderer/src/studio/useNodePositions.ts b/studio/src/renderer/src/studio/useNodePositions.ts new file mode 100644 index 000000000..325efc777 --- /dev/null +++ b/studio/src/renderer/src/studio/useNodePositions.ts @@ -0,0 +1,34 @@ +import { useEffect, useState } from 'react' +import type { Point } from '../editor/nodeLayout' +import type { NodePositions } from '../editor/nodePositions' + +const STORAGE_PREFIX = 'iris-studio.node-positions:' + +function isPoint(value: unknown): value is Point { + return typeof value === 'object' && value !== null && typeof (value as Point).x === 'number' && typeof (value as Point).y === 'number' +} + +// Unreadable positions just mean every node sits where the layout puts it. +function storedPositions(file: string): NodePositions { + try { + const stored: unknown = JSON.parse(localStorage.getItem(STORAGE_PREFIX + file) ?? '{}') + return Object.fromEntries(Object.entries(stored as Record).filter(([, position]) => isPoint(position))) as NodePositions + } catch { + return {} + } +} + +/** Where the nodes of {@code file} were dragged to, kept by the studio so the file only holds settings. */ +export function useNodePositions(file: string): [NodePositions, React.Dispatch>] { + const [positions, setPositions] = useState(() => storedPositions(file)) + + useEffect(() => { + if (Object.keys(positions).length === 0) { + localStorage.removeItem(STORAGE_PREFIX + file) + } else { + localStorage.setItem(STORAGE_PREFIX + file, JSON.stringify(positions)) + } + }, [file, positions]) + + return [positions, setPositions] +}