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
This commit is contained in:
piexel committed 2026-11-25 09:44:27 +01:00
1 parent fadbcb8bb5
commit 8fe8942f5d
30 files changed
+2197 -858

No files matched your search

@@ -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<typeof DropdownMenuPrimitive.Root>) {
return <DropdownMenuPrimitive.Root data-slot="dropdown-menu" {...props} />
}
function DropdownMenuTrigger(props: React.ComponentProps<typeof DropdownMenuPrimitive.Trigger>) {
return <DropdownMenuPrimitive.Trigger data-slot="dropdown-menu-trigger" {...props} />
}
function DropdownMenuContent({ className, sideOffset = 2, ...props }: React.ComponentProps<typeof DropdownMenuPrimitive.Content>) {
return (
<DropdownMenuPrimitive.Portal>
<DropdownMenuPrimitive.Content
data-slot="dropdown-menu-content"
sideOffset={sideOffset}
className={cn(MENU_SURFACE, "max-h-(--radix-dropdown-menu-content-available-height)", className)}
{...props}
/>
</DropdownMenuPrimitive.Portal>
)
}
function DropdownMenuItem({ className, ...props }: React.ComponentProps<typeof DropdownMenuPrimitive.Item>) {
return <DropdownMenuPrimitive.Item data-slot="dropdown-menu-item" className={cn(MENU_ROW, className)} {...props} />
}
function DropdownMenuSub(props: React.ComponentProps<typeof DropdownMenuPrimitive.Sub>) {
return <DropdownMenuPrimitive.Sub data-slot="dropdown-menu-sub" {...props} />
}
function DropdownMenuSubTrigger({ className, children, ...props }: React.ComponentProps<typeof DropdownMenuPrimitive.SubTrigger>) {
return (
<DropdownMenuPrimitive.SubTrigger
data-slot="dropdown-menu-sub-trigger"
className={cn(MENU_ROW, "data-[state=open]:bg-accent data-[state=open]:text-accent-foreground", className)}
{...props}
>
{children}
<IdeIcon name="chevronRight" className="ml-auto size-3.5" />
</DropdownMenuPrimitive.SubTrigger>
)
}
function DropdownMenuSubContent({ className, ...props }: React.ComponentProps<typeof DropdownMenuPrimitive.SubContent>) {
return (
<DropdownMenuPrimitive.Portal>
<DropdownMenuPrimitive.SubContent data-slot="dropdown-menu-sub-content" className={cn(MENU_SURFACE, "shadow-lg", className)} {...props} />
</DropdownMenuPrimitive.Portal>
)
}
export { DropdownMenu, DropdownMenuTrigger, DropdownMenuContent, DropdownMenuItem, DropdownMenuSub, DropdownMenuSubTrigger, DropdownMenuSubContent }
@@ -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<typeof PopoverPrimitive.Root>) {
return <PopoverPrimitive.Root data-slot="popover" {...props} />
}
function PopoverAnchor(props: React.ComponentProps<typeof PopoverPrimitive.Anchor>) {
return <PopoverPrimitive.Anchor data-slot="popover-anchor" {...props} />
}
function PopoverContent({ className, align = "start", sideOffset = 4, ...props }: React.ComponentProps<typeof PopoverPrimitive.Content>) {
return (
<PopoverPrimitive.Portal>
<PopoverPrimitive.Content
data-slot="popover-content"
align={align}
sideOffset={sideOffset}
className={cn(
"z-50 rounded-md border bg-popover p-2 text-popover-foreground shadow-md outline-hidden data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:animate-in data-[state=open]:fade-in-0",
className
)}
{...props}
/>
</PopoverPrimitive.Portal>
)
}
export { Popover, PopoverAnchor, PopoverContent }
+18 -1
View File
@@ -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')
})
})
+18
View File
@@ -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)) {
@@ -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<typeof layoutNodes>, 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)
})
})
+103 -30
View File
@@ -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<string, Point> = 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
}
@@ -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)
})
})
@@ -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<Record<string, Point>>
/**
* 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<string, Point> = {}
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
}
@@ -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<string, SettingsType> = {
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)
})
})
@@ -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<string, SettingsType>, values: unknown, open: ReadonlySet<string>, 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) }
})
}
@@ -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<string, SettingsType> = { ...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<string, SettingsType> = { ...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'])
})
})
+37 -18
View File
@@ -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<string, unknown> {
@@ -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<string, SettingsType>, values: unknown): SettingsFold[] {
const folds: SettingsFold[] = []
@@ -56,7 +67,8 @@ export function foldedSections(section: NodeSettings, types: Record<string, Sett
type FoldHead = Pick<SettingsFold, 'title' | 'path' | 'type' | 'kind' | 'depth' | 'holder'>
function addFold(into: SettingsFold[], types: Record<string, SettingsType>, values: unknown, head: FoldHead, shownAsNodes: Set<string>): 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<string, SettingsType>, 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<string, SettingsType>, 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<string, SettingsType>, 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(
@@ -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> = {}): 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()
})
})
+138 -8
View File
@@ -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<string, unknown> {
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()
}
@@ -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 (
<>
<svg viewBox={`0 0 ${PREVIEW_WIDTH} ${PREVIEW_HEIGHT}`} preserveAspectRatio="none" className="h-3 min-w-4 flex-1 overflow-visible text-primary" aria-hidden>
<polyline points={points.join(' ')} fill="none" stroke="currentColor" strokeWidth={1.4} strokeLinecap="round" strokeLinejoin="round" vectorEffect="non-scaling-stroke" />
</svg>
<span className="shrink-0 text-muted-foreground tabular-nums">
{roundedNumber(samples[0])} → {roundedNumber(samples[samples.length - 1])}
</span>
</>
)
}
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 (
<div className="w-[300px] space-y-2">
<div className="flex gap-1">
<Button variant={byShape ? 'ghost' : 'secondary'} size="xs" disabled={locked} onClick={() => byShape && onWrite(keyframesFrom(value))}>
Points
</Button>
<Button variant={byShape ? 'secondary' : 'ghost'} size="xs" disabled={locked} onClick={() => !byShape && onWrite(shapeFrom(value))}>
Shape
</Button>
</div>
<CurvePlot value={value} locked={locked || byShape} onWrite={onWrite} />
{byShape ? <ShapeForm shape={value as Record<string, unknown>} locked={locked} onWrite={onWrite} /> : <PointsForm keys={value as Keyframe[]} locked={locked} onWrite={onWrite} />}
</div>
)
}
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<PlotDrag | null>(null)
const [hint, setHint] = useState(POINTS_HINT)
const plot = useRef<SVGSVGElement>(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 (
<div>
<svg
ref={plot}
viewBox={`0 0 ${PLOT_WIDTH} ${PLOT_HEIGHT}`}
className="block w-full touch-none rounded-md bg-background"
onPointerMove={dragTo}
onPointerUp={finishDrag}
onDoubleClick={(event) => !locked && onWrite(sortedKeyframes([...keys, keyframeAt(event)]))}
>
{GUIDE_LEVELS.map((level) => (
<g key={level}>
<line x1={area.left} x2={area.left + area.width} y1={screenY(level)} y2={screenY(level)} className="stroke-border" strokeWidth={1} />
<text x={area.left + 2} y={screenY(level) - 2} className="fill-muted-foreground text-[10px]">
{level}
</text>
</g>
))}
<polyline
points={samples.map((sample, index) => `${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) => (
<circle
key={index}
cx={screenX(t)}
cy={screenY(level)}
r={POINT_RADIUS}
className={drag?.index === index ? 'fill-primary stroke-primary' : 'fill-popover stroke-primary hover:fill-primary'}
strokeWidth={1.5}
onPointerDown={(event) => {
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))
}}
/>
))}
</svg>
{!isShape(value) && <p className="pt-1 text-[11px] text-secondary-text">{hint}</p>}
</div>
)
}
function PointsForm({ keys, locked, onWrite }: { keys: Keyframe[]; locked: boolean; onWrite(next: Keyframe[]): void }): React.JSX.Element {
return (
<div className="space-y-1">
{keys.map(([t, value], index) => (
<div key={index} className="flex items-center gap-1">
<NumberBox label="at" value={t} disabled={locked} onCommit={(next) => next !== undefined && onWrite(withKeyframe(keys, index, [next, value]))} />
<NumberBox label="value" value={value} disabled={locked} onCommit={(next) => next !== undefined && onWrite(withKeyframe(keys, index, [t, next]))} />
<Button variant="ghost" size="icon-sm" title="Remove the point" className="size-6 shrink-0" disabled={locked || keys.length <= 1} onClick={() => onWrite(withoutKeyframe(keys, index))}>
<IdeIcon name="delete" className="size-3.5" />
</Button>
</div>
))}
<Button variant="ghost" size="xs" disabled={locked} onClick={() => onWrite(withAddedKeyframe(keys))}>
<IdeIcon name="add" className="size-3.5" /> Point
</Button>
</div>
)
}
function ShapeForm({ shape, locked, onWrite }: { shape: Record<string, unknown>; 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 (
<div className="space-y-1">
<select
className="h-7 w-full min-w-0 rounded-md border border-input bg-transparent px-1.5 text-[12px] outline-none focus-visible:border-ring dark:bg-input/30"
value={named.key}
disabled={locked}
onChange={(event) => onWrite(withShape(shape, event.target.value))}
>
{CURVE_SHAPES.map((candidate) => (
<option key={candidate.key} value={candidate.key}>
{candidate.key}
</option>
))}
</select>
<div className="flex items-center gap-1">
<NumberBox label="from" value={numeric('from')} placeholder="0" disabled={locked} onCommit={(next) => onWrite(withSetting(shape, 'from', next))} />
<NumberBox label="to" value={numeric('to')} placeholder="1" disabled={locked} onCommit={(next) => onWrite(withSetting(shape, 'to', next))} />
</div>
{named.parameters.map((parameter) => (
<NumberBox
key={parameter.name}
label={parameter.name}
value={numeric(parameter.name)}
placeholder={String(parameter.fallback)}
disabled={locked}
onCommit={(next) => onWrite(withSetting(shape, parameter.name, next))}
/>
))}
</div>
)
}
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 (
<label className="flex min-w-0 flex-1 items-center gap-1 text-[11px] text-secondary-text">
{label}
<Input
value={draft}
disabled={disabled}
placeholder={placeholder}
inputMode="decimal"
className="h-6 px-1.5 text-[11.5px] tabular-nums md:text-[11.5px]"
onChange={(event) => setDraft(event.target.value)}
onBlur={commit}
onKeyDown={(event) => {
if (event.key === 'Enter') {
commit()
} else if (event.key === 'Escape') {
setDraft(shown)
}
}}
/>
</label>
)
}
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))
}
@@ -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 (
<>
<FieldRow {...props} problem={null}>
<button
type="button"
title="Edit the curve"
className="flex h-7 min-w-0 flex-1 items-center gap-1 rounded-md border border-input px-1.5 hover:bg-accent/50 dark:bg-input/30"
onClick={onToggle}
>
<Sparkline value={value} />
<IdeIcon name="chevronRight" className={cn('size-3.5 transition-transform', open && 'rotate-90')} />
</button>
</FieldRow>
{open && <CurveEditor value={value} locked={locked} onWrite={(next) => 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 (
<svg viewBox={`0 0 ${SPARKLINE_WIDTH} ${SPARKLINE_HEIGHT}`} preserveAspectRatio="none" className="h-5 min-w-0 flex-1 text-primary" aria-hidden>
<polyline points={points.join(' ')} fill="none" stroke="currentColor" strokeWidth={1.5} vectorEffect="non-scaling-stroke" />
</svg>
)
}
function CurveEditor({ value, locked, onWrite }: { value: unknown; locked: boolean; onWrite(next: unknown): void }): React.JSX.Element {
const byShape = isShape(value)
return (
<div className="mb-1 ml-2 space-y-1.5 rounded-md border bg-muted/40 p-2">
<div className="flex gap-1">
<Button variant={byShape ? 'ghost' : 'secondary'} size="xs" disabled={locked} onClick={() => byShape && onWrite(keyframesFrom(value))}>
Points
</Button>
<Button variant={byShape ? 'secondary' : 'ghost'} size="xs" disabled={locked} onClick={() => !byShape && onWrite(shapeFrom(value))}>
Shape
</Button>
</div>
{isShape(value) ? <ShapeEditor shape={value} locked={locked} onWrite={onWrite} /> : <PointsEditor keys={value as Keyframe[]} locked={locked} onWrite={onWrite} />}
</div>
)
}
function PointsEditor({ keys, locked, onWrite }: { keys: Keyframe[]; locked: boolean; onWrite(next: Keyframe[]): void }): React.JSX.Element {
return (
<>
{keys.map(([t, value], index) => (
<div key={index} className="flex items-center gap-1">
<NumberBox label="at" value={t} disabled={locked} onCommit={(next) => next !== undefined && onWrite(withKeyframe(keys, index, [next, value]))} />
<NumberBox label="value" value={value} disabled={locked} onCommit={(next) => next !== undefined && onWrite(withKeyframe(keys, index, [t, next]))} />
<Button variant="ghost" size="icon-sm" title="Remove the point" className="size-6 shrink-0" disabled={locked || keys.length <= 1} onClick={() => onWrite(withoutKeyframe(keys, index))}>
<IdeIcon name="delete" className="size-3.5" />
</Button>
</div>
))}
<Button variant="ghost" size="xs" disabled={locked} onClick={() => onWrite(withAddedKeyframe(keys))}>
<IdeIcon name="add" className="size-3.5" /> Point
</Button>
</>
)
}
function ShapeEditor({ shape, locked, onWrite }: { shape: Record<string, unknown>; 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 (
<>
<select
className="h-7 w-full min-w-0 rounded-md border border-input bg-transparent px-1.5 text-[12px] outline-none focus-visible:border-ring dark:bg-input/30"
value={named.key}
disabled={locked}
onChange={(event) => onWrite(withShape(shape, event.target.value))}
>
{CURVE_SHAPES.map((candidate) => (
<option key={candidate.key} value={candidate.key}>
{candidate.key}
</option>
))}
</select>
<div className="flex items-center gap-1">
<NumberBox label="from" value={numeric('from')} placeholder="0" disabled={locked} onCommit={(next) => onWrite(withSetting(shape, 'from', next))} />
<NumberBox label="to" value={numeric('to')} placeholder="1" disabled={locked} onCommit={(next) => onWrite(withSetting(shape, 'to', next))} />
</div>
{named.parameters.map((parameter) => (
<NumberBox
key={parameter.name}
label={parameter.name}
value={numeric(parameter.name)}
placeholder={String(parameter.fallback)}
disabled={locked}
onCommit={(next) => 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 (
<label className="flex min-w-0 flex-1 items-center gap-1 text-[11px] text-secondary-text">
{label}
<Input
value={draft}
disabled={disabled}
placeholder={placeholder}
inputMode="decimal"
className="h-6 px-1.5 text-[11.5px] tabular-nums md:text-[11.5px]"
onChange={(event) => setDraft(event.target.value)}
onBlur={commit}
onKeyDown={(event) => {
if (event.key === 'Enter') {
commit()
} else if (event.key === 'Escape') {
setDraft(shown)
}
}}
/>
</label>
)
}
@@ -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 (
<div className="py-0.5">
<div className="flex h-7 items-center gap-2">
<label className={cn('min-w-0 flex-[4] truncate text-[12px]', option.required && 'font-medium')} title={option.description}>
{option.name}
</label>
<div className="flex min-w-0 flex-[6] items-center gap-1">
{children}
<Button variant="ghost" size="icon-sm" title="Unset" className={cn('size-6 shrink-0', value === undefined && 'invisible')} disabled={locked} onClick={onUnset}>
<IdeIcon name="reset" className="size-3.5" />
</Button>
</div>
</div>
{problem !== null && <p className="pt-0.5 text-right text-[11px] text-destructive">{problem}</p>}
</div>
)
}
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}`
}
@@ -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 (
<div
data-node-id={placed.id}
className={cn(
'absolute cursor-move rounded-md bg-popover text-[11.5px] outline -outline-offset-1 dark:bg-secondary',
dropTarget ? 'outline-2 outline-success' : selected ? 'outline-2 outline-primary' : 'outline-1 outline-overlay-border',
offset !== null && 'z-10 shadow-lg'
)}
style={{ left: placed.x + (offset?.x ?? 0), top: placed.y + (offset?.y ?? 0), width: NODE_WIDTH, height: placed.height }}
>
<div className="rounded-t-md" style={{ height: NODE_STRIPE, background: colorOfKind(node.kind) }} />
<NodeHeader node={node} />
{rows.rows.map((row) => (
<NodeRowView key={row.id} row={row} addable={rows.addable} editable={editable} />
))}
{placed.grown && <InputPort handle={node.movable && !locked} />}
{placed.growing && <span className="absolute rounded-full bg-secondary-text" style={portStyle('right')} />}
</div>
)
})
function NodeHeader({ node }: { node: GraphNode }): React.JSX.Element {
return (
<div className="flex items-center gap-1 px-2" style={{ height: NODE_HEADER }}>
<span className="min-w-0 flex-1 truncate text-[12.5px] font-semibold" title={node.title}>
{node.title}
</span>
{node.roles.map((role) => (
<RoleChip key={role} role={role} />
))}
</div>
)
}
function RoleChip({ role }: { role: string }): React.JSX.Element {
const color = colorOfRole(role)
return (
<span className="max-w-[96px] shrink-0 truncate rounded-full border px-[7px] text-[11px] leading-4" style={{ borderColor: color, background: color + CHIP_FILL_ALPHA }}>
{role}
</span>
)
}
// 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 (
<span
data-port={handle ? 'regrow' : 'input'}
title={handle ? 'Drag onto another node to grow from it' : undefined}
className={cn(
'absolute rounded-full border-[1.5px] border-secondary-text transition-transform',
handle ? 'cursor-pointer bg-popover hover:scale-[1.35] hover:border-primary dark:bg-secondary' : 'bg-secondary-text'
)}
style={portStyle('left')}
/>
)
}
function portStyle(side: 'left' | 'right'): React.CSSProperties {
return { [side]: -PORT_SIZE / 2, top: PORT_TOP - PORT_SIZE / 2, width: PORT_SIZE, height: PORT_SIZE }
}
+222 -243
View File
@@ -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<string, IdeIconName> = {
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<string, SettingsType>
/** 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<HTMLDivElement>(null)
const [camera, setCamera] = useCamera(frame, layout, fileKey)
const [drag, setDrag] = useState<NodeDrag | null>(null)
const [menuNode, setMenuNode] = useState<GraphNode | null>(null)
const pan = useRef<{ x: number; y: number } | null>(null)
const showAll = useCallback(() => setCamera(fitted(frame.current!, layout)), [setCamera, layout])
const [open, setOpen] = useState<ReadonlySet<string>>(new Set())
const [openCurve, setOpenCurve] = useState<string | null>(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<NodeGesture | null>(null)
const [menu, setMenu] = useState<MenuTarget | null>(null)
const panFrom = useRef<Point | null>(null)
const settingUnderMenu = useRef<SettingRow | null>(null)
const chosenHere = useRef<string | null>(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<HTMLDivElement>): 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<HTMLDivElement>): 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 (
<ContextMenu onOpenChange={(open) => !open && setMenuNode(null)}>
<ContextMenu onOpenChange={(isOpen) => !isOpen && setMenu(null)}>
<ContextMenuTrigger asChild>
<div
ref={frame}
className="relative h-full w-full touch-none overflow-hidden bg-background select-none"
style={{
backgroundImage: 'radial-gradient(var(--overlay-border) 1px, transparent 1px)',
backgroundSize: `${GRID_SPACING * camera.scale}px ${GRID_SPACING * camera.scale}px`,
backgroundPosition: `${camera.x}px ${camera.y}px`
}}
className="relative h-full w-full touch-none overflow-hidden bg-card select-none"
style={gridStyle(camera)}
onPointerDown={pointerDown}
onPointerMove={pointerMove}
onPointerUp={pointerUp}
onPointerCancel={() => {
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()}
>
<div className="absolute top-0 left-0 origin-top-left" style={{ transform: `translate(${camera.x}px, ${camera.y}px) scale(${camera.scale})` }}>
<Wires layout={layout} />
{layout.nodes.map((placed) => (
<NodeBox
key={placed.id}
placed={placed}
selected={placed.id === selectedId}
target={drag?.target?.id === placed.id}
offset={dragging && drag.placed.id === placed.id ? dragOffset : null}
/>
))}
<NodeEditingContext.Provider value={editing}>
<NodeWires wires={layout.wires} selectedId={selectedId} moved={moved} regrow={regrow} />
{layout.nodes.map((placed) => (
<NodeBox
key={placed.id}
placed={placed}
rows={rowsById.get(placed.id)!}
selected={placed.id === selectedId}
dropTarget={placed.id === dropTargetId}
offset={moved?.id === placed.id ? moved.offset : null}
locked={locked}
/>
))}
</NodeEditingContext.Provider>
</div>
{Math.abs(camera.scale - 1) > 0.001 && (
<span className="pointer-events-none absolute right-2 bottom-1.5 text-[11px] text-muted-foreground tabular-nums">{Math.round(camera.scale * 100)}%</span>
)}
</div>
</ContextMenuTrigger>
{menuNode !== null && <NodeMenu node={menuNode} locked={locked} onEdit={onEdit} />}
{menu !== null && (
<NodeMenu
target={menu}
locked={locked}
onEdit={edit}
onOpenCurve={setOpenCurve}
onArrange={() => setPositions({})}
onShowAll={showEveryNode}
onResetZoom={view.resetZoom}
/>
)}
</ContextMenu>
)
}
function NodeBox({ placed, selected, target, offset }: { placed: PlacedNode; selected: boolean; target: boolean; offset: { x: number; y: number } | null }): React.JSX.Element {
const { node } = placed
const icon = KIND_ICONS[node.kind] ?? PART_ICON
const detail = node.roles.length > 0 ? node.roles.join(', ') : node.title === node.kind ? null : node.kind
return (
<div
className={cn(
'absolute flex items-center gap-2 rounded-md border bg-card px-2.5 shadow-xs',
selected ? 'border-primary ring-1 ring-primary' : 'border-overlay-border',
target && 'border-primary bg-selection',
offset !== null && 'z-10 opacity-80 shadow-md'
)}
style={{
left: placed.x + (offset?.x ?? 0),
top: placed.y + (offset?.y ?? 0),
width: NODE_WIDTH,
height: NODE_HEIGHT,
cursor: node.movable ? 'grab' : 'default'
}}
>
<IdeIcon name={icon} />
<div className="min-w-0 leading-tight">
<div className="truncate text-[12.5px] font-medium">{node.title}</div>
{detail !== null && <div className="truncate text-[11px] text-secondary-text">{detail}</div>}
</div>
</div>
)
}
function Wires({ layout }: { layout: NodeLayout }): React.JSX.Element {
return (
<svg className="pointer-events-none absolute top-0 left-0 overflow-visible" width={layout.width} height={layout.height}>
{layout.wires.map(({ from, to, label }) => {
const [startX, startY] = [from.x + NODE_WIDTH, from.y + NODE_HEIGHT / 2]
const [endX, endY] = [to.x, to.y + NODE_HEIGHT / 2]
const bend = (endX - startX) / 2
return (
<g key={`${from.id}>${to.id}`}>
<path d={`M${startX},${startY} C${startX + bend},${startY} ${endX - bend},${endY} ${endX},${endY}`} className="fill-none stroke-input" strokeWidth={1.5} />
{label !== '' && (
<text x={endX - 6} y={endY - 6} textAnchor="end" className="fill-secondary-text text-[10.5px]">
{label}
</text>
)}
</g>
)
})}
</svg>
)
}
function NodeMenu({ node, locked, onEdit }: { node: GraphNode; locked: boolean; onEdit(edit: GraphEdit): void }): React.JSX.Element {
const keyText = useKeyText()
const removable = node.duplicable
return (
<ContextMenuContent className="min-w-[180px]">
{node.additions.length > 0 && (
<ContextMenuSub>
<ContextMenuSubTrigger disabled={locked}>Add</ContextMenuSubTrigger>
<ContextMenuSubContent>
{node.additions.map((addition) => (
<ContextMenuItem key={`${idOf(addition.list)}:${addition.label}`} onSelect={() => onEdit({ op: 'append', list: addition.list, literal: addition.literal })}>
{addition.label}
</ContextMenuItem>
))}
</ContextMenuSubContent>
</ContextMenuSub>
)}
<ContextMenuItem disabled={locked || !node.duplicable} onSelect={() => onEdit({ op: 'duplicate', path: node.path })}>
Duplicate
<ContextMenuShortcut>{keyText('duplicateNode')}</ContextMenuShortcut>
</ContextMenuItem>
<ContextMenuSeparator />
<ContextMenuItem variant="destructive" disabled={locked || !removable} onSelect={() => onEdit({ op: 'delete', path: node.path })}>
Delete
<ContextMenuShortcut>{keyText('deleteNode')}</ContextMenuShortcut>
</ContextMenuItem>
</ContextMenuContent>
)
}
function nodeAt(layout: NodeLayout, point: { x: number; y: number }): PlacedNode | null {
return layout.nodes.find((placed) => point.x >= placed.x && point.x <= placed.x + NODE_WIDTH && point.y >= placed.y && point.y <= placed.y + NODE_HEIGHT) ?? null
}
// A node can grow from any other that takes children, except from inside itself or from where it already grows.
function moveTarget(layout: NodeLayout, dragged: PlacedNode, point: { x: number; y: number }): PlacedNode | null {
const over = nodeAt(layout, point)
const toList = over?.node.childList
if (over === null || toList === null || toList === undefined || isWithin(toList, dragged.node.path) || isParentList(dragged.node.path, toList)) {
return null
function rowsOfNodes(roots: GraphNode[], types: Record<string, SettingsType>, values: unknown, open: ReadonlySet<string>, editable: boolean): Map<string, NodeRows> {
const rows = new Map<string, NodeRows>()
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<HTMLDivElement | null>, layout: NodeLayout, fileKey: string): [Camera, React.Dispatch<React.SetStateAction<Camera>>] {
const [camera, setCamera] = useState<Camera>({ x: FIT_MARGIN, y: FIT_MARGIN, scale: 1 })
const fittedFile = useRef<string | null>(null)
// 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<string | null>, reveal: (area: { left: number; top: number; right: number; bottom: number }) => void): void {
const handled = useRef<string | null>(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<React.SetStateAction<ReadonlySet<string>>>
edit(change: GraphEdit): void
suggestions: SuggestionStore
settingUnderMenu: React.RefObject<SettingRow | null>
}
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]
)
}
@@ -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<string>
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<ReadonlySet<string>>(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 (
<section className="flex min-h-0 flex-[7] flex-col">
<header className="px-4 pt-2.5 pb-1.5">
<h2 className="truncate text-[13px] font-semibold">{node.title}</h2>
<p className="truncate text-[11.5px] text-secondary-text">{node.roles.length > 0 ? node.roles.join(', ') : node.kind}</p>
</header>
<ScrollArea className="min-h-0 flex-1 border-t">
<div className="pb-3">
{node.settings.map((section) => (
<SettingsSection key={JSON.stringify(section.path) + section.type} section={section} context={context} />
))}
</div>
</ScrollArea>
</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 (
<section className="px-4 pt-3">
{folds.map((fold) =>
fold.kind === 'own' ? (
<div key={idOfFold(fold)}>
<h3 className="pb-1 text-[11px] font-semibold text-muted-foreground" title={state.types[fold.type]?.description}>
{fold.title}
</h3>
<FoldFields fold={fold} context={context} />
</div>
) : (
<div key={idOfFold(fold)}>
<FoldHeader fold={fold} context={context} />
{open.has(idOfFold(fold)) && <FoldFields fold={fold} context={context} />}
</div>
)
)}
</section>
)
}
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 (
<div className="flex h-7 items-center gap-1" style={{ paddingLeft: (fold.depth - 1) * FOLD_INDENT_PX }}>
<button type="button" className="flex min-w-0 flex-1 items-center gap-1 text-left" onClick={() => onToggle(id)}>
<IdeIcon name="chevronRight" className={cn('size-3.5 transition-transform', unfolded && 'rotate-90')} />
<span className="shrink-0 text-[12px] font-medium">{fold.title}</span>
{!unfolded && <span className="min-w-0 truncate text-[11px] text-secondary-text">{fold.summary}</span>}
</button>
{fold.kind === 'list' && (
<Button variant="ghost" size="icon-sm" title="Add an item" className="size-6 shrink-0" disabled={locked} onClick={() => onEdit({ op: 'append', list: fold.path, literal: '{}' })}>
<IdeIcon name="add" className="size-3.5" />
</Button>
)}
{holder !== null && (
<Button variant="ghost" size="icon-sm" title="Unset" className="size-6 shrink-0" disabled={locked} onClick={() => onEdit({ op: 'unset', object: holder.object, key: holder.key })}>
<IdeIcon name="reset" className="size-3.5" />
</Button>
)}
{fold.kind === 'item' && (
<Button variant="ghost" size="icon-sm" title="Delete the item" className="size-6 shrink-0" disabled={locked} onClick={() => onEdit({ op: 'delete', path: fold.path })}>
<IdeIcon name="delete" className="size-3.5" />
</Button>
)}
</div>
)
}
function FoldFields({ fold, context }: { fold: SettingsFold; context: SectionContext }): React.JSX.Element {
const { values, locked, open, roles, suggestions, onToggle, onEdit } = context
return (
<div style={{ paddingLeft: fold.depth * FOLD_INDENT_PX }}>
{fold.options.map((option) => {
const value = valueAt(values, [...fold.path, option.name])
const curveId = JSON.stringify([...fold.path, option.name])
return (
<SettingField
key={`${idOfFold(fold)}/${option.name}=${JSON.stringify(value)}`}
owner={fold.type}
option={option}
value={value}
locked={locked}
curveOpen={open.has(curveId)}
onToggleCurve={() => 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 })}
/>
)
})}
</div>
)
}
interface FieldProps extends SettingFieldProps {
/** The schema type of the object the option is in. */
owner: string
curveOpen: boolean
onToggleCurve(): void
loadSuggestions(source: SuggestionSource): Promise<string[]>
}
function SettingField(props: FieldProps): React.JSX.Element {
const kind = props.option.kind.kind
if (kind === 'boolean' || kind === 'enum') {
return <ChoiceField {...props} />
}
if (kind === 'any' && isCurve(props.value)) {
return <CurveField {...props} open={props.curveOpen} onToggle={props.onToggleCurve} />
}
return <TypedField {...props} />
}
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 (
<FieldRow {...props} problem={null}>
<select
className="h-7 w-full min-w-0 rounded-md border border-input bg-transparent px-1.5 text-[12px] outline-none focus-visible:border-ring dark:bg-input/30"
value={value === undefined ? NOT_SET : String(value)}
disabled={locked}
title={option.description}
onChange={(event) => (event.target.value === NOT_SET ? onUnset() : onSet(literalOfChoice(event.target.value)))}
>
<option value={NOT_SET}>{defaultLabel(option)}</option>
{choices.map((choice) => (
<option key={choice} value={choice}>
{choice}
</option>
))}
</select>
</FieldRow>
)
}
// Numbers, text and anything else are typed in; a draft that does not fit the option says why and is not written.
// 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 (
<FieldRow {...props} problem={problem}>
<SuggestionInput
value={draft}
onValue={setDraft}
isList={isStringList(option.kind)}
load={source === null ? null : () => 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) && (
<Button
variant="ghost"
size="icon-sm"
title="Make it a curve"
className="size-6 shrink-0"
disabled={locked}
onClick={() => {
onSet(JSON.stringify(curveFrom(value)))
onToggleCurve()
}}
>
<IdeIcon name="views/noise" className="size-3.5" />
</Button>
)}
</FieldRow>
)
}
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
}
}
@@ -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 <ContextMenuContent className="min-w-[200px]">{target.on === 'node' ? <NodeItems {...props} node={target.node} setting={target.setting} /> : <BackgroundItems {...props} root={target.root} />}</ContextMenuContent>
}
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 && <CurveItems setting={setting} locked={locked} onEdit={onEdit} onOpenCurve={onOpenCurve} />}
<AdditionItems node={node} locked={locked} onEdit={onEdit} />
{!isRoot && (
<>
{node.additions.length > 0 && <ContextMenuSeparator />}
<ContextMenuItem disabled={locked || !node.duplicable} onSelect={() => onEdit({ op: 'duplicate', path: node.path })}>
Duplicate
<ContextMenuShortcut>{keyText('duplicateNode')}</ContextMenuShortcut>
</ContextMenuItem>
<ContextMenuItem variant="destructive" disabled={locked || !node.duplicable} onSelect={() => onEdit({ op: 'delete', path: node.path })}>
{node.children.length === 0 ? 'Delete' : 'Delete with what grows from it'}
<ContextMenuShortcut>{keyText('deleteNode')}</ContextMenuShortcut>
</ContextMenuItem>
</>
)}
</>
)
}
// 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) ? (
<ContextMenuItem disabled={locked} onSelect={() => set(roundedNumber(samplesOf(current, 1)![0]))}>
Make it one number
</ContextMenuItem>
) : (
<ContextMenuItem disabled={locked} onSelect={makeCurve}>
Make it a curve
</ContextMenuItem>
)}
<ContextMenuSeparator />
</>
)
}
/**
* 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<string, GraphNode['additions']>()
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 ? (
<ContextMenuSub key={list}>
<ContextMenuSubTrigger disabled={locked}>{partsTitle}</ContextMenuSubTrigger>
<ContextMenuSubContent>
{additions.map((addition) => (
<ContextMenuItem key={addition.label} onSelect={() => onEdit({ op: 'append', list: addition.list, literal: addition.literal })}>
{addition.label}
</ContextMenuItem>
))}
</ContextMenuSubContent>
</ContextMenuSub>
) : (
<ContextMenuItem key={list} disabled={locked} onSelect={() => onEdit({ op: 'append', list: additions[0].list, literal: additions[0].literal })}>
{ADD_PREFIX + additions[0].label.toLowerCase()}
</ContextMenuItem>
)
)}
</>
)
}
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 && (
<>
<AdditionItems node={root} locked={locked} onEdit={onEdit} />
<ContextMenuSeparator />
</>
)}
<ContextMenuItem onSelect={onArrange}>Arrange nodes</ContextMenuItem>
<ContextMenuItem onSelect={onShowAll}>
Show every node
<ContextMenuShortcut>{keyText('showAllNodes')}</ContextMenuShortcut>
</ContextMenuItem>
<ContextMenuItem onSelect={onResetZoom}>
Reset zoom
<ContextMenuShortcut>{keyText('resetZoom')}</ContextMenuShortcut>
</ContextMenuItem>
</>
)
}
+16 -5
View File
@@ -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
<h2 className="text-[12px] font-semibold">Nodes</h2>
<span className="min-w-0 truncate text-[11.5px] text-secondary-text">{state?.file ?? entryKey}</span>
<span className="flex-1" />
{!locked && <span className="min-w-0 truncate text-[11.5px] text-muted-foreground">Right-click to add or delete · Drag a ring onto a node to regrow · {keyText('undo')} undoes</span>}
{state?.locked != null && (
<span className="flex shrink-0 items-center gap-1 text-[11.5px] whitespace-nowrap text-secondary-text" title={state.locked}>
<IdeIcon name="locked" className="size-3.5" />
@@ -52,10 +59,14 @@ export function NodePane({ editor, entryKey, selected, onSelect }: NodePaneProps
)}
{state !== null && state.roots !== null && (
<NodeCanvas
key={state.file}
roots={state.roots}
fileKey={entryKey}
selectedId={selected === null ? null : JSON.stringify(selected.path)}
types={state.types}
values={values}
file={state.file}
selectedId={selected === null ? null : idOf(selected.path)}
locked={locked}
suggestions={suggestions}
showAllRef={showAllRef}
onSelect={onSelect}
onEdit={editor.edit}
+113
View File
@@ -0,0 +1,113 @@
import { IdeIcon } from '@/components/IdeIcon'
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSub, DropdownMenuSubContent, DropdownMenuSubTrigger, DropdownMenuTrigger } from '@/components/ui/dropdown-menu'
import { cn } from '@/lib/utils'
import type { SettingOption } from '../bridge/types'
import { NODE_HEADING, NODE_ROW, type NodeRow } from '../editor/nodeRows'
import { idOfFold, type SettingsFold } from '../editor/settingFolds'
import { defaultLiteral, defaultText } from '../editor/settingText'
import { useNodeEditing } from './nodeEditing'
import { NodeSettingRow, ROW_INDENT, RowButton } from './NodeSettingRow'
const ADD_SETTING_TEXT = '+ Setting'
interface NodeRowViewProps {
row: NodeRow
addable: SettingsFold[]
editable: boolean
}
export function NodeRowView({ row, addable, editable }: NodeRowViewProps): React.JSX.Element {
switch (row.kind) {
case 'heading':
return <HeadingRow title={row.fold.title} />
case 'fold':
return <FoldRow fold={row.fold} open={row.open} editable={editable} />
case 'setting':
return <NodeSettingRow row={row} editable={editable} />
case 'addSetting':
return <AddSettingRow addable={addable} />
}
}
function HeadingRow({ title }: { title: string }): React.JSX.Element {
return (
<div className="flex items-end px-2 pb-0.5 text-[11px] text-muted-foreground" style={{ height: NODE_HEADING }}>
{title}
</div>
)
}
// ▸ 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 (
<div className="flex items-center px-2" style={{ height: NODE_ROW }}>
<button
type="button"
data-node-control
className="group flex min-w-0 flex-1 items-center gap-1 text-left"
style={{ paddingLeft: (fold.depth - 1) * ROW_INDENT }}
onClick={() => onToggleFold(idOfFold(fold))}
>
<IdeIcon name="chevronRight" className={cn('size-3 shrink-0 text-secondary-text group-hover:text-foreground', open && 'rotate-90')} />
<span className="shrink-0">{fold.kind === 'item' ? `#${fold.title}` : fold.title}</span>
{showsSummary && <span className="ml-1 min-w-0 truncate text-muted-foreground">{fold.summary}</span>}
</button>
{fold.kind === 'list' && <RowButton glyph="+" tone="add" hidden={!editable} title="Add one more, like the last" onClick={() => onEdit({ op: 'addItem', list: fold.path })} />}
{fold.kind === 'item' && <RowButton glyph="×" tone="remove" hidden={!editable} title={`Remove #${fold.title}`} onClick={() => onEdit({ op: 'delete', path: fold.path })} />}
{fold.kind === 'group' && holder !== null && (
<RowButton glyph="×" tone="remove" hidden={!editable} title={`Remove ${fold.title}`} onClick={() => onEdit({ op: 'unset', object: holder.object, key: holder.key })} />
)}
</div>
)
}
/** 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 (
<div className="flex items-center px-2" style={{ height: NODE_ROW }}>
<DropdownMenu modal={false}>
<DropdownMenuTrigger asChild>
<button type="button" data-node-control title="Set one of the settings left at its default" className="text-link hover:underline">
{ADD_SETTING_TEXT}
</button>
</DropdownMenuTrigger>
<DropdownMenuContent align="start" className="min-w-[180px]">
{addable.length === 1 ? (
<UnsetItems fold={addable[0]} />
) : (
addable.map((fold) => (
<DropdownMenuSub key={idOfFold(fold)}>
<DropdownMenuSubTrigger>{sectionLabel(fold)}</DropdownMenuSubTrigger>
<DropdownMenuSubContent className="min-w-[180px]">
<UnsetItems fold={fold} />
</DropdownMenuSubContent>
</DropdownMenuSub>
))
)}
</DropdownMenuContent>
</DropdownMenu>
</div>
)
}
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) => (
<DropdownMenuItem key={option.name} title={option.description || undefined} onSelect={() => add(option)}>
{option.name}
<span className="ml-auto max-w-[120px] truncate pl-4 text-muted-foreground">{defaultText(option)}</span>
</DropdownMenuItem>
))}
</>
)
}
function sectionLabel(fold: SettingsFold): string {
return fold.kind === 'item' ? `${String(fold.path.at(-2))} #${fold.title}` : fold.title
}
@@ -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 (
<div className="flex items-center px-2" style={{ height: NODE_ROW }}>
<span className="shrink-0 truncate pr-1 text-secondary-text" style={{ width: ROW_LABEL_WIDTH, paddingLeft: fold.depth * ROW_INDENT }} title={option.description || undefined}>
{option.name}
</span>
<div className="ml-1 flex min-w-0 flex-1 items-center">
<SettingValue row={row} editable={editable} />
</div>
<RowButton
glyph="×"
tone="remove"
hidden={!editable || value === undefined}
title={`Remove ${option.name}, so it goes back to ${fallback === NOT_SET ? 'empty' : fallback}`}
onClick={() => onEdit({ op: 'unset', object: fold.path, key: option.name })}
/>
</div>
)
}
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 (
<button
type="button"
data-node-control
title={title}
className={cn(
'ml-1 flex size-4 shrink-0 items-center justify-center rounded-full text-[13px] leading-none',
tone === 'remove' ? 'text-muted-foreground hover:bg-destructive/20 hover:text-destructive' : 'text-link hover:bg-link/20',
hidden && 'invisible'
)}
onClick={onClick}
>
{glyph}
</button>
)
}
function SettingValue({ row, editable }: SettingRowProps): React.JSX.Element {
const kind = row.option.kind.kind
if (kind === 'boolean') {
return <CheckValue row={row} editable={editable} />
}
if (kind === 'enum') {
return <ChoiceValue row={row} editable={editable} />
}
if (kind === 'any' && isCurve(row.value)) {
return <CurveValue row={row} editable={editable} />
}
return <TypedValue row={row} editable={editable} />
}
/** 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 <span className={cn('min-w-0 flex-1 truncate', isSet ? 'text-foreground' : 'text-muted-foreground', isNumber(row.option.kind) && 'tabular-nums')}>{text}</span>
}
function CheckValue({ row, editable }: SettingRowProps): React.JSX.Element {
const { onEdit } = useNodeEditing()
const checked = (row.value ?? row.option.defaultValue) === true
return (
<button
type="button"
data-node-control
role="checkbox"
aria-checked={checked}
disabled={!editable}
title={row.value === undefined ? 'Default' : undefined}
className={cn('flex size-3.5 items-center justify-center rounded-[4px] border', checked ? 'border-primary bg-primary' : 'border-input bg-muted', editable && 'hover:border-primary', row.value === undefined && 'opacity-60')}
onClick={() => onEdit({ op: 'set', object: row.fold.path, key: row.option.name, literal: String(!checked) })}
>
{checked && (
<svg viewBox="0 0 14 14" className="size-3.5 text-primary-foreground" aria-hidden>
<path d="M3.5 7 L6 9.5 L10.5 4" fill="none" stroke="currentColor" strokeWidth={1.6} strokeLinecap="round" strokeLinejoin="round" />
</svg>
)}
</button>
)
}
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 (
<DropdownMenu modal={false}>
<DropdownMenuTrigger asChild disabled={!editable}>
<button type="button" data-node-control className={cn(FIELD, editable && EDITABLE_FIELD)}>
<ShownText row={row} />
<IdeIcon name="chevronRight" className="size-3 shrink-0 rotate-90 text-secondary-text" />
</button>
</DropdownMenuTrigger>
<DropdownMenuContent align="start">
{constants.map((constant) => (
<DropdownMenuItem
key={constant.name}
title={constant.description || undefined}
className={cn(constant.name === current && 'font-semibold')}
onSelect={() => onEdit({ op: 'set', object: row.fold.path, key: row.option.name, literal: JSON.stringify(constant.name) })}
>
{constant.name}
</DropdownMenuItem>
))}
</DropdownMenuContent>
</DropdownMenu>
)
}
function CurveValue({ row, editable }: SettingRowProps): React.JSX.Element {
const { openCurve, onOpenCurve, onEdit, onSettingMenu } = useNodeEditing()
return (
<Popover open={openCurve === row.id} onOpenChange={(open) => onOpenCurve(open ? row.id : null)}>
<PopoverAnchor asChild>
<button
type="button"
data-node-control
title={CURVE_HINT}
className={cn(FIELD, editable && EDITABLE_FIELD)}
onClick={() => onOpenCurve(row.id)}
onContextMenu={() => onSettingMenu(row)}
>
<CurvePreview value={row.value} />
</button>
</PopoverAnchor>
<PopoverContent onOpenAutoFocus={(event) => event.preventDefault()}>
<CurveEditor value={row.value} locked={!editable} onWrite={(next) => onEdit({ op: 'set', object: row.fold.path, key: row.option.name, literal: JSON.stringify(next) })} />
</PopoverContent>
</Popover>
)
}
// 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 <ValueInput row={row} onDone={() => setTyping(false)} />
}
return (
<button
type="button"
data-node-control
disabled={!editable}
title={row.value === undefined ? 'Default' : textOf(row.option.kind, row.value)}
className={cn(FIELD, editable && cn(EDITABLE_FIELD, 'cursor-text'))}
onClick={() => setTyping(true)}
onContextMenu={() => onSettingMenu(row)}
>
<ShownText row={row} />
</button>
)
}
/**
* 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<string | null>(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 (
<div className="relative min-w-0 flex-1" data-node-control>
<SuggestionInput
value={draft}
onValue={(next) => {
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 && (
<p className="absolute top-full left-0 z-30 mt-1 w-max max-w-[260px] rounded-sm border border-destructive bg-popover px-1.5 py-1 text-[11px] whitespace-normal text-foreground shadow-md">
{shownProblem}
</p>
)}
</div>
)
}
@@ -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 (
<svg className="pointer-events-none absolute top-0 left-0 overflow-visible" width={1} height={1}>
{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 (
<path
key={`${from.id}>${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 && (
<path
d={curve(regrow.pointer, { x: regrow.part.x, y: regrow.part.y + PORT_TOP })}
className={cn('fill-none', regrow.onTarget ? 'stroke-success' : 'stroke-primary')}
strokeWidth={2}
strokeDasharray={COPY_DASH}
strokeLinecap="round"
/>
)}
</svg>
)
})
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}`
}
@@ -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<string | null>(null)
@@ -150,6 +149,8 @@ export function SceneStudio({ client, view, packRevision, onSummary, tell }: Sce
<NodePane
editor={editor}
entryKey={entry.key}
values={values}
suggestions={suggestions}
selected={selected}
onSelect={(node) => {
setSelectedPath(node?.path ?? null)
@@ -158,14 +159,10 @@ export function SceneStudio({ client, view, packRevision, onSummary, tell }: Sce
/>
)}
</div>
<Panel className={view.editable || view.form ? 'w-[300px]' : 'w-[250px]'}>
<Panel className={view.form ? 'w-[300px]' : 'w-[250px]'}>
{view.form === true && <ProfileFormPanel className="flex-[5]" state={profileForm} onChange={changeSetting} onResetAll={() => setTyped({ owner: typedOwner, values: NO_OVERRIDES })} />}
{view.baked && entry !== null && <BakeMeter timing={bakeTiming} />}
{selected !== null && editor.state !== null ? (
<NodeInspector key={JSON.stringify(selected.path)} node={selected} state={editor.state} values={values} suggestions={suggestions} onEdit={editor.edit} />
) : (
<BlockList scene={scene} blocks={blockLooks} farLeavesOnly={farLeavesOnly} onFarLeavesOnly={setFarLeavesOnly} />
)}
<BlockList scene={scene} blocks={blockLooks} farLeavesOnly={farLeavesOnly} onFarLeavesOnly={setFarLeavesOnly} />
</Panel>
</>
)
@@ -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<string, string> = {
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<string, string> = { 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
}
@@ -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<NodeRow, { kind: 'setting' }>
/** 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<string[]>
/** 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<NodeEditing | null>(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
}
@@ -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<HTMLDivElement | null>, opening: Bounds | null): NodeCamera {
const [camera, setCamera] = useState<Camera>(() => ({ 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))
}
@@ -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<string, unknown>).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<React.SetStateAction<NodePositions>>] {
const [positions, setPositions] = useState<NodePositions>(() => 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]
}