Edit node values as curves, folded sections and suggestions in the studio

Nested settings fold into sections and lists of objects into items. Curve
values show a sparkline and open a points or shape editor, and a number or
range can be made a curve. Blocks, resources and roles are suggested while
typing, and string lists are typed as a, b. The studio asks the bridge for
the platform and pack lists (suggestions endpoint).

No terrain, pin, golden or digest moved; the files written are the same JSON.

v3: db53f834a
This commit is contained in:
piexel committed 2026-11-10 13:34:32 +01:00
1 parent dbfc1d0c34
commit 7eb45cebf6
20 files changed
+1403 -99

No files matched your search

@@ -160,6 +160,11 @@ export class BridgeClient {
return this.json(`scene-write?${new URLSearchParams({ view: viewId, key })}`, { method: 'POST', body: JSON.stringify({ revision, text }) })
}
/** What a setting naming an entry of a platform registry (reference) or a resource of the pack (resource) may be typed as, sorted. */
suggestions(of: { reference: string } | { resource: string }): Promise<string[]> {
return this.json(`suggestions?${new URLSearchParams(of)}`)
}
sceneEntries(viewId: string): Promise<SceneEntry[]> {
return this.json(`scene-entries?${new URLSearchParams({ view: viewId })}`)
}
@@ -0,0 +1,84 @@
import { describe, expect, it } from 'vitest'
import { canBecomeCurve, curveAt, curveFrom, isCurve, keyframesFrom, samplesOf, shapeFrom, withAddedKeyframe, withKeyframe, withoutKeyframe, withSetting, withShape } from './curves'
describe('isCurve', () => {
it('holds only for keyframes and named shapes', () => {
expect(isCurve([[0, 1.3], [1, 0.2]])).toBe(true)
expect(isCurve({ shape: 'power', exponent: 3 })).toBe(true)
expect(isCurve([15, 20])).toBe(false)
expect(isCurve(4)).toBe(false)
expect(isCurve({ min: 3, max: 8 })).toBe(false)
expect(isCurve({ shape: 'zigzag' })).toBe(false)
})
})
describe('samplesOf', () => {
it('runs from the start of the curve to its end', () => {
expect(samplesOf([[0, 1.3], [1, 0.2]], 3)).toEqual([1.3, 0.75, 0.2].map((expected) => expect.closeTo(expected, 9)))
})
it('has none for a value that is no curve', () => {
expect(samplesOf(4, 3)).toBeNull()
})
it('follows a named curve between its from and to', () => {
expect(curveAt({ shape: 'power', exponent: 2, from: 10, to: 20 }, 0.5)).toBeCloseTo(12.5, 9)
expect(curveAt({ shape: 'linear' }, 0.25)).toBeCloseTo(0.25, 9)
})
it('holds the first and last values beyond the keyframes', () => {
expect(curveAt([[0.2, 5], [0.8, 9]], 0)).toBe(5)
expect(curveAt([[0.2, 5], [0.8, 9]], 1)).toBe(9)
})
})
describe('curveFrom', () => {
it('makes a number a flat curve and a range a rising one', () => {
expect(curveFrom(4)).toEqual([[0, 4], [1, 4]])
expect(curveFrom([15, 20])).toEqual([[0, 15], [1, 20]])
expect(curveFrom({ min: 3, max: 8 })).toEqual([[0, 3], [1, 8]])
})
it('leaves what is not a number or range alone', () => {
expect(curveFrom('wood')).toBeNull()
expect(canBecomeCurve([[0, 1], [1, 2]])).toBe(false)
expect(canBecomeCurve(4)).toBe(true)
})
})
describe('changing how a curve is written', () => {
it('turns keyframes into a linear shape between their ends, and back into sampled keyframes', () => {
const shape = shapeFrom([[1, 8], [0, 2]])
expect(shape).toEqual({ shape: 'linear', from: 2, to: 8 })
expect(keyframesFrom(shape).map(([t, value]) => [t, value])).toEqual([[0, 2], [0.25, 3.5], [0.5, 5], [0.75, 6.5], [1, 8]])
})
it('sets a shape setting, or leaves it out so the default applies', () => {
expect(withSetting({ shape: 'power', exponent: 3 }, 'exponent', 4)).toEqual({ shape: 'power', exponent: 4 })
expect(withSetting({ shape: 'power', exponent: 3 }, 'exponent', undefined)).toEqual({ shape: 'power' })
})
it('keeps from and to when the shape changes, but not the old shape settings', () => {
expect(withShape({ shape: 'power', exponent: 3, from: 1, to: 4 }, 'sine')).toEqual({ shape: 'sine', from: 1, to: 4 })
})
})
describe('editing keyframes', () => {
const keys: [number, number][] = [[0, 1], [1, 3]]
it('adds a keyframe halfway across the widest gap, on the curve', () => {
expect(withAddedKeyframe(keys)).toEqual([[0, 1], [0.5, 2], [1, 3]])
expect(withAddedKeyframe([[0, 1], [0.25, 1], [1, 3]])[2]).toEqual([0.625, expect.closeTo(1 + (2 * 0.375) / 0.75, 9)])
})
it('gives a lone keyframe a partner at the other end', () => {
expect(withAddedKeyframe([[0, 4]])).toEqual([[0, 4], [1, 4]])
})
it('sets and removes a keyframe but never removes the last one', () => {
expect(withKeyframe(keys, 1, [0.9, 5])).toEqual([[0, 1], [0.9, 5]])
expect(withoutKeyframe(keys, 0)).toEqual([[1, 3]])
expect(withoutKeyframe([[1, 3]], 0)).toEqual([[1, 3]])
})
})
+217
View File
@@ -0,0 +1,217 @@
/** One keyframe of a curve: where it is from 0 to 1, and the value there. */
export type Keyframe = [number, number]
export interface ShapeParameter {
name: string
fallback: number
}
/** A named curve (ProceduralValue.CurveShape): from 0 at t = 0 toward 1, stretched between a value's from and to. */
export interface CurveShape {
key: string
parameters: ShapeParameter[]
at(t: number, parameter: (name: string) => number): number
}
const DEFAULT_FROM = 0
const DEFAULT_TO = 1
const KEYFRAME_SIZE = 2
const RANGE_SIZE = 2
const NARROWEST_BELL = 1e-6
const SHAPE_STOPS = 5
const FIRST_STOP = 0
const LAST_STOP = 1
export const CURVE_SHAPES: CurveShape[] = [
{ key: 'linear', parameters: [], at: (t) => t },
{ key: 'smooth', parameters: [], at: (t) => t * t * (3 - 2 * t) },
{ key: 'power', parameters: [{ name: 'exponent', fallback: 2 }], at: (t, p) => Math.pow(t, p('exponent')) },
{
key: 'sigmoid',
parameters: [
{ name: 'steepness', fallback: 10 },
{ name: 'mid', fallback: 0.5 }
],
at: (t, p) => 1 / (1 + Math.exp(-p('steepness') * (t - p('mid'))))
},
{
key: 'bell',
parameters: [
{ name: 'mid', fallback: 0.5 },
{ name: 'width', fallback: 0.15 }
],
at: (t, p) => Math.exp(-0.5 * Math.pow((t - p('mid')) / Math.max(NARROWEST_BELL, p('width')), 2))
},
{
key: 'periodic',
parameters: [
{ name: 'periods', fallback: 4 },
{ name: 'sharpness', fallback: 8 }
],
at: (t, p) => Math.pow(Math.max(0, Math.sin(2 * Math.PI * t * p('periods'))), p('sharpness'))
},
{ key: 'sine', parameters: [{ name: 'periods', fallback: 1 }], at: (t, p) => 0.5 + 0.5 * Math.sin(2 * Math.PI * t * p('periods')) }
]
export function shapeNamed(key: unknown): CurveShape | undefined {
return typeof key === 'string' ? CURVE_SHAPES.find((shape) => shape.key === key.toLowerCase()) : undefined
}
function isObject(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value)
}
function isKeyframe(value: unknown): value is Keyframe {
return Array.isArray(value) && value.length === KEYFRAME_SIZE && value.every((part) => typeof part === 'number')
}
/** Whether {@code value} is keyframes [[t, value], ...], which a range [min, max] and a number are not. */
export function isKeyframes(value: unknown): value is Keyframe[] {
return Array.isArray(value) && value.length > 0 && value.every(isKeyframe)
}
/** Whether {@code value} is a named curve {"shape": ...} the studio knows. */
export function isShape(value: unknown): value is Record<string, unknown> {
return isObject(value) && shapeNamed(value.shape) !== undefined
}
/** Whether {@code value} is a curve, as opposed to a number or a [min, max] range. */
export function isCurve(value: unknown): boolean {
return isKeyframes(value) || isShape(value)
}
/** Whether {@code value} is a number or a range, which {@link curveFrom} makes a curve. */
export function canBecomeCurve(value: unknown): boolean {
return typeof value === 'number' || rangeOf(value) !== null
}
function rangeOf(value: unknown): [number, number] | null {
if (Array.isArray(value) && value.length === RANGE_SIZE && value.every((part) => typeof part === 'number')) {
return [value[0], value[1]]
}
if (isObject(value) && typeof value.min === 'number' && typeof value.max === 'number') {
return [value.min, value.max]
}
return null
}
/** A number as a curve that stays at it, a range as a curve rising from its low end to its high end; null for anything else. */
export function curveFrom(value: unknown): Keyframe[] | null {
if (typeof value === 'number') {
return [
[0, value],
[1, value]
]
}
const range = rangeOf(value)
return range === null
? null
: [
[0, range[0]],
[1, range[1]]
]
}
function numberOf(written: unknown, fallback: number): number {
return typeof written === 'number' ? written : fallback
}
/** The value of a curve at {@code t}, from 0 to 1; NaN for a value that is no curve. */
export function curveAt(value: unknown, t: number): number {
if (isKeyframes(value)) {
return keyframesAt(sortedKeyframes(value), t)
}
if (!isShape(value)) {
return Number.NaN
}
const shape = shapeNamed(value.shape)!
const from = numberOf(value.from, DEFAULT_FROM)
const to = numberOf(value.to, DEFAULT_TO)
const parameter = (name: string): number => numberOf(value[name], shape.parameters.find((candidate) => candidate.name === name)!.fallback)
return from + (to - from) * shape.at(Math.max(0, Math.min(1, t)), parameter)
}
export function sortedKeyframes(keys: Keyframe[]): Keyframe[] {
return [...keys].sort((a, b) => a[0] - b[0])
}
function keyframesAt(keys: Keyframe[], t: number): number {
if (t <= keys[0][0]) {
return keys[0][1]
}
for (let index = 1; index < keys.length; index++) {
if (t <= keys[index][0]) {
const span = keys[index][0] - keys[index - 1][0]
const blend = span <= 0 ? 1 : (t - keys[index - 1][0]) / span
return keys[index - 1][1] + (keys[index][1] - keys[index - 1][1]) * blend
}
}
return keys[keys.length - 1][1]
}
/** {@code count} values of the curve, from its start to its end; null for a value that is no curve. */
export function samplesOf(value: unknown, count: number): number[] | null {
if (!isCurve(value)) {
return null
}
return Array.from({ length: count }, (_, index) => curveAt(value, count === 1 ? 0 : index / (count - 1)))
}
/** 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)) {
return value
}
const stops = Array.from({ length: SHAPE_STOPS }, (_, index) => FIRST_STOP + ((LAST_STOP - FIRST_STOP) * index) / (SHAPE_STOPS - 1))
return stops.map((t): Keyframe => [t, curveAt(value, t)])
}
/** A linear named curve between the first and last keyframes' values, or the shape itself. */
export function shapeFrom(value: unknown): Record<string, unknown> {
if (isShape(value)) {
return value
}
const keys = isKeyframes(value) ? sortedKeyframes(value) : []
return { shape: 'linear', from: keys.length > 0 ? keys[0][1] : DEFAULT_FROM, to: keys.length > 0 ? keys[keys.length - 1][1] : DEFAULT_TO }
}
/** The shape with {@code key}, keeping its from and to; the other settings of the old shape do not carry over. */
export function withShape(shape: Record<string, unknown>, key: string): Record<string, unknown> {
return { shape: key, from: numberOf(shape.from, DEFAULT_FROM), to: numberOf(shape.to, DEFAULT_TO) }
}
/** The shape with {@code name} set to {@code number}, or left out when it is undefined so the shape's own default applies. */
export function withSetting(shape: Record<string, unknown>, name: string, number: number | undefined): Record<string, unknown> {
const { [name]: _replaced, ...others } = shape
return number === undefined ? others : { ...others, [name]: number }
}
/** The keyframes with the one at {@code index} (as listed) set to {@code keyframe}. */
export function withKeyframe(keys: Keyframe[], index: number, keyframe: Keyframe): Keyframe[] {
return keys.map((existing, position) => (position === index ? keyframe : existing))
}
/** The keyframes without the one at {@code index}; the last one stays, since a curve needs a keyframe. */
export function withoutKeyframe(keys: Keyframe[], index: number): Keyframe[] {
return keys.length <= 1 ? keys : keys.filter((_, position) => position !== index)
}
/** The keyframes with one more halfway across the widest gap, on the curve as it is; a lone keyframe gets one at the other end. */
export function withAddedKeyframe(keys: Keyframe[]): Keyframe[] {
const sorted = sortedKeyframes(keys)
if (sorted.length === 1) {
const t = sorted[0][0] === LAST_STOP ? FIRST_STOP : LAST_STOP
return sortedKeyframes([...sorted, [t, sorted[0][1]]])
}
let widest = 0
let before = 0
for (let index = 1; index < sorted.length; index++) {
const gap = sorted[index][0] - sorted[index - 1][0]
if (gap > widest) {
widest = gap
before = index - 1
}
}
const t = sorted[before][0] + widest / 2
return sortedKeyframes([...sorted, [t, keyframesAt(sorted, t)]])
}
@@ -0,0 +1,79 @@
import { describe, expect, it } from 'vitest'
import type { NodeSettings, SettingOption, SettingsType, ValueKind } from '../bridge/types'
import { foldedSections, idOfFold, visibleFolds } from './settingFolds'
function option(name: string, kind: ValueKind): SettingOption {
return { name, description: '', required: false, minimum: null, maximum: null, minItems: null, defaultValue: null, kind }
}
const text: ValueKind = { kind: 'text', format: 'PLAIN' }
const any: ValueKind = { kind: 'any' }
const types: Record<string, SettingsType> = {
Material: {
description: '',
options: [
option('role', text),
option('block', { kind: 'reference', reference: 'BLOCK', format: 'BLOCK_ID' }),
option('offset', { kind: 'object', type: 'Offset' }),
option('rules', { kind: 'list', element: { kind: 'object', type: 'Rule' }, unique: false }),
option('parts', { kind: 'list', element: { kind: 'object', type: 'Rule' }, unique: false })
]
},
Offset: { description: '', options: [option('x', any), option('y', any)] },
Rule: { description: '', options: [option('chance', any), option('face', text)] }
}
const material: NodeSettings = { title: 'Material', path: ['materials', 0], type: 'Material', shownAsNodes: ['parts'] }
const file = {
materials: [
{
role: 'wood',
block: 'minecraft:birch_wood',
offset: { x: 2, y: [[0, 1], [1, 0]] },
rules: [{ chance: 0.5 }, { face: 'top' }]
}
]
}
describe('foldedSections', () => {
it('folds an object setting into a section, and a list of objects into a section of items', () => {
const folds = foldedSections(material, types, file)
expect(folds.map((fold) => fold.title)).toEqual(['Material', 'offset', 'rules', '1', '2'])
expect(folds.map((fold) => fold.kind)).toEqual(['own', 'group', 'list', 'item', 'item'])
expect(folds.map((fold) => fold.depth)).toEqual([0, 1, 1, 2, 2])
expect(folds[4].path).toEqual(['materials', 0, 'rules', 1])
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', () => {
const [own] = foldedSections(material, types, file)
expect(own.options.map((setting) => setting.name)).toEqual(['role', 'block'])
})
it('sums a section up by what it holds, a curve as curve and the default namespace left off', () => {
const folds = foldedSections(material, types, file)
expect(folds[0].summary).toBe('role wood · block birch_wood · rules 2')
expect(folds[1].summary).toBe('x 2 · y curve')
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' }] })
expect(inside).toEqual([])
expect(own.options.map((setting) => setting.name)).toEqual(['role', 'block', 'offset', 'rules'])
})
})
describe('visibleFolds', () => {
it('hides what is inside a fold that is folded', () => {
const folds = foldedSections(material, types, file)
expect(visibleFolds(folds, new Set()).map((fold) => fold.title)).toEqual(['Material', 'offset', 'rules'])
expect(visibleFolds(folds, new Set([idOfFold(folds[2])])).map((fold) => fold.title)).toEqual(['Material', 'offset', 'rules', '1', '2'])
})
})
@@ -0,0 +1,128 @@
import type { JsonPath, NodeSettings, SettingOption, SettingsType } from '../bridge/types'
import { isCurve } from './curves'
import { isWithin } from './nodeLayout'
import { textOf } from './settingText'
import { valueAt } from './jsonValues'
const SUMMARY_SETTINGS = 3
const SUMMARY_SEPARATOR = ' · '
const DEFAULT_NAMESPACE = 'minecraft:'
/**
* What a section is: a node's own settings, a setting written as an object, a setting written as a list of objects, or
* one element of such a list. All but the first fold.
*/
export type FoldKind = 'own' | 'group' | 'list' | 'item'
/** One object of the file whose settings the inspector shows, below the ones that hold it. */
export interface SettingsFold {
title: string
path: JsonPath
type: string
kind: FoldKind
/** 0 for a node's own sections, one more for each object it is inside. */
depth: number
/** A short reading of what it holds, shown while it is folded. */
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[]
}
function isObject(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value)
}
function isObjects(value: unknown): value is Record<string, unknown>[] {
return Array.isArray(value) && value.every(isObject)
}
export function idOfFold(fold: SettingsFold): string {
return JSON.stringify(fold.path)
}
/**
* 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.
*/
export function foldedSections(section: NodeSettings, types: Record<string, SettingsType>, values: unknown): SettingsFold[] {
const folds: SettingsFold[] = []
addFold(folds, types, values, { title: section.title, path: section.path, type: section.type, kind: 'own', depth: 0, holder: null }, new Set(section.shownAsNodes))
return folds
}
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 inside: SettingsFold[] = []
const summary: string[] = []
for (const option of types[head.type]?.options ?? []) {
if (shownAsNodes.has(option.name)) {
continue
}
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())
continue
}
if (itemType !== null && isObjects(value) && types[itemType] !== undefined) {
addList(inside, types, values, { option, path, itemType, count: value.length, depth: head.depth + 1, holder })
summary.push(`${option.name} ${value.length}`)
continue
}
options.push(option)
if (value !== undefined) {
summary.push(`${option.name} ${shortText(option, value)}`)
}
}
into.push({ ...head, summary: summary.slice(0, SUMMARY_SETTINGS).join(SUMMARY_SEPARATOR), options })
into.push(...inside)
}
interface ListFold {
option: SettingOption
path: JsonPath
itemType: string
count: number
depth: number
holder: { object: JsonPath; key: string }
}
function addList(into: SettingsFold[], types: Record<string, SettingsType>, values: unknown, list: ListFold): void {
into.push({
title: list.option.name,
path: list.path,
type: list.itemType,
kind: 'list',
depth: list.depth,
summary: `${list.count} ${list.count === 1 ? 'item' : 'items'}`,
holder: list.holder,
options: []
})
for (let index = 0; index < list.count; index++) {
addFold(
into,
types,
values,
{ title: String(index + 1), path: [...list.path, index], type: list.itemType, kind: 'item', depth: list.depth + 1, holder: null },
new Set()
)
}
}
function shortText(option: SettingOption, value: unknown): string {
return isCurve(value) ? 'curve' : textOf(option.kind, value).replaceAll(DEFAULT_NAMESPACE, '')
}
/** The folds shown while the ones in {@code open} are unfolded: a fold inside another that is folded is hidden. */
export function visibleFolds(folds: SettingsFold[], open: ReadonlySet<string>): SettingsFold[] {
const foldable = folds.filter((fold) => fold.kind !== 'own')
return folds.filter((fold) => !foldable.some((outer) => outer !== fold && !open.has(idOfFold(outer)) && outer.path.length < fold.path.length && isWithin(fold.path, outer.path)))
}
@@ -0,0 +1,27 @@
import { describe, expect, it } from 'vitest'
import type { ValueKind } from '../bridge/types'
import { literalOf, textOf } from './settingText'
const roles: ValueKind = { kind: 'list', element: { kind: 'text', format: 'PLAIN' }, unique: false }
describe('string lists', () => {
it('read as commas and are written back quoted', () => {
expect(textOf(roles, ['wood', 'leaves'])).toBe('wood, leaves')
expect(literalOf(roles, 'wood, leaves, ')).toBe('["wood","leaves"]')
expect(literalOf(roles, ',')).toBe('[]')
})
it('keep a list typed as JSON, and show a list of anything else as JSON', () => {
expect(literalOf(roles, '["a", "b"]')).toBe('["a", "b"]')
expect(textOf(roles, [1, 2])).toBe('[1,2]')
})
})
describe('text', () => {
it('shows a string as it is and writes it quoted', () => {
const text: ValueKind = { kind: 'text', format: 'PLAIN' }
expect(textOf(text, 'wood')).toBe('wood')
expect(literalOf(text, 'wood "a"')).toBe('"wood \\"a\\""')
})
})
@@ -0,0 +1,48 @@
import type { ValueKind } from '../bridge/types'
export const NOT_SET = ''
export const LIST_SEPARATOR = ', '
/** 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'
}
/** 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)
}
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. */
export function textOf(kind: ValueKind, value: unknown): string {
if (value === undefined) {
return NOT_SET
}
if (isText(kind) && typeof value === 'string') {
return value
}
return isStringList(kind) && isStrings(value) ? value.join(LIST_SEPARATOR) : JSON.stringify(value)
}
/** The strings a list is typed as, each trimmed, and none left empty. */
export function itemsOf(draft: string): string[] {
return draft
.split(',')
.map((item) => item.trim())
.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. */
export function literalOf(kind: ValueKind, draft: string): string {
if (isText(kind)) {
return JSON.stringify(draft)
}
if (isStringList(kind) && !draft.trim().startsWith('[')) {
return JSON.stringify(itemsOf(draft))
}
return draft.trim()
}
@@ -0,0 +1,25 @@
import { describe, expect, it, vi } from 'vitest'
import { SuggestionStore } from './suggestionStore'
describe('SuggestionStore', () => {
it('asks once for a list however often it is read', async () => {
const fetch = vi.fn().mockResolvedValue(['minecraft:stone'])
const store = new SuggestionStore(fetch)
await store.load({ from: 'reference', reference: 'BLOCK' })
const again = await store.load({ from: 'reference', reference: 'BLOCK' })
expect(again).toEqual(['minecraft:stone'])
expect(fetch).toHaveBeenCalledTimes(1)
expect(fetch).toHaveBeenCalledWith({ reference: 'BLOCK' })
})
it('asks again after a list could not be read', async () => {
const fetch = vi.fn().mockRejectedValueOnce(new Error('down')).mockResolvedValue(['birch'])
const store = new SuggestionStore(fetch)
await expect(store.load({ from: 'resource', resource: 'iris:object' })).rejects.toThrow('down')
await expect(store.load({ from: 'resource', resource: 'iris:object' })).resolves.toEqual(['birch'])
expect(fetch).toHaveBeenLastCalledWith({ resource: 'iris:object' })
})
})
@@ -0,0 +1,23 @@
import { sourceKey, type ListedSource } from './suggestions'
/** What the server lists for the suggestions of a source that names platform or pack entries. */
export type SuggestionFetch = (of: { reference: string } | { resource: string }) => Promise<string[]>
/** The suggestion lists, each asked for once; a list that could not be read is asked for again next time. */
export class SuggestionStore {
private readonly lists = new Map<string, Promise<string[]>>()
constructor(private readonly fetch: SuggestionFetch) {}
load(source: ListedSource): Promise<string[]> {
const key = sourceKey(source)
const known = this.lists.get(key)
if (known !== undefined) {
return known
}
const asked = this.fetch(source.from === 'reference' ? { reference: source.reference } : { resource: source.resource })
this.lists.set(key, asked)
asked.catch(() => this.lists.delete(key))
return asked
}
}
@@ -0,0 +1,82 @@
import { describe, expect, it } from 'vitest'
import type { GraphNode, SettingOption } from '../bridge/types'
import { NO_PART } from '../bridge/types'
import { completed, matching, rolesOf, suggestionSourceOf, wordBeingTyped } from './suggestions'
function option(name: string, kind: SettingOption['kind']): SettingOption {
return { name, description: '', required: false, minimum: null, maximum: null, minItems: null, defaultValue: null, kind }
}
function node(roles: string[], children: GraphNode[] = []): GraphNode {
return {
kind: 'Stem',
title: 'Stem',
path: [],
partId: NO_PART,
roles,
settings: [],
children: children.map((child) => ({ wire: '', node: child })),
childList: null,
movable: false,
duplicable: false,
additions: []
}
}
describe('suggestionSourceOf', () => {
it('names the registry of a reference, the kind of a resource and the roles of the object', () => {
expect(suggestionSourceOf('Material', option('block', { kind: 'reference', reference: 'BLOCK', format: 'BLOCK_ID' }))).toEqual({ from: 'reference', reference: 'BLOCK' })
expect(suggestionSourceOf('Part', option('skin', { kind: 'resource', resource: 'iris:object' }))).toEqual({ from: 'resource', resource: 'iris:object' })
})
it('takes the roles for the settings that name one', () => {
const on = option('on', { kind: 'list', element: { kind: 'text', format: 'PLAIN' }, unique: false })
expect(suggestionSourceOf('art.arcane.iris.engine.procedural.part.ProceduralDecoration', on)).toEqual({ from: 'roles' })
expect(suggestionSourceOf('art.arcane.iris.engine.procedural.part.ProceduralDecoration', option('at', { kind: 'text', format: 'PLAIN' }))).toBeNull()
})
it('takes the elements of a list of references, and nothing for free text', () => {
expect(suggestionSourceOf('Rule', option('blocks', { kind: 'list', element: { kind: 'reference', reference: 'BLOCK', format: 'BLOCK_ID' }, unique: false }))).toEqual({ from: 'reference', reference: 'BLOCK' })
expect(suggestionSourceOf('Rule', option('note', { kind: 'text', format: 'PLAIN' }))).toBeNull()
})
})
describe('rolesOf', () => {
it('lists each role of the whole tree once, sorted', () => {
expect(rolesOf([node(['wood', 'leaves'], [node(['wood', 'bark'])]), node(['moss'])])).toEqual(['bark', 'leaves', 'moss', 'wood'])
})
})
describe('matching', () => {
const blocks = ['minecraft:oak_log', 'minecraft:birch_log', 'minecraft:oak_leaves', 'minecraft:stone']
it('puts what starts with the typed text before what holds it', () => {
expect(matching(blocks, 'minecraft:oak')).toEqual(['minecraft:oak_log', 'minecraft:oak_leaves'])
expect(matching(blocks, 'oak')).toEqual(['minecraft:oak_log', 'minecraft:oak_leaves'])
expect(matching(['a_log', 'log'], 'log')).toEqual([])
expect(matching(['a_log', 'logs'], 'log')).toEqual(['logs', 'a_log'])
})
it('suggests nothing for nothing typed or a choice that is already typed out', () => {
expect(matching(blocks, '')).toEqual([])
expect(matching(blocks, 'MINECRAFT:STONE')).toEqual([])
})
it('shows only the first few', () => {
expect(matching(Array.from({ length: 30 }, (_, index) => `block_${index}`), 'block')).toHaveLength(8)
})
})
describe('the word being typed', () => {
it('is the whole text, or for a list the item after the last comma', () => {
expect(wordBeingTyped('oak', false)).toEqual({ start: 0, typed: 'oak' })
expect(wordBeingTyped('wood, lea', true)).toEqual({ start: 6, typed: 'lea' })
expect(wordBeingTyped('wood, ', true)).toEqual({ start: 6, typed: '' })
})
it('is replaced by the choice, a list ready for its next item', () => {
expect(completed('minecraft:oa', 'minecraft:oak_log', false)).toBe('minecraft:oak_log')
expect(completed('wood, lea', 'leaves', true)).toBe('wood, leaves, ')
})
})
@@ -0,0 +1,79 @@
import type { GraphNode, SettingOption, ValueKind } from '../bridge/types'
import { LIST_SEPARATOR } from './settingText'
/** What an option may be typed as: the entries of a platform registry, the keys of the pack's resources of a kind, or the roles of the object. */
export type SuggestionSource = { from: 'reference'; reference: string } | { from: 'resource'; resource: string } | { from: 'roles' }
/** Settings that name a role of the object being edited, by the schema type and option (ProceduralPart, ProceduralMaterial and ProceduralDecoration). */
const ROLE_OPTIONS: ReadonlySet<string> = new Set([
'art.arcane.iris.engine.procedural.part.ProceduralPart.role',
'art.arcane.iris.engine.procedural.part.ProceduralMaterial.role',
'art.arcane.iris.engine.procedural.part.ProceduralDecoration.on'
])
/** A source the server lists, as opposed to the roles, which the studio reads from the nodes. */
export type ListedSource = Exclude<SuggestionSource, { from: 'roles' }>
const MOST_SHOWN = 8
/** Where the suggestions for {@code option} of the schema type {@code type} come from; null when it is typed freely. */
export function suggestionSourceOf(type: string, option: SettingOption): SuggestionSource | null {
if (ROLE_OPTIONS.has(`${type}.${option.name}`)) {
return { from: 'roles' }
}
const kind: ValueKind = option.kind.kind === 'list' ? option.kind.element : option.kind
if (kind.kind === 'reference') {
return { from: 'reference', reference: kind.reference }
}
return kind.kind === 'resource' ? { from: 'resource', resource: kind.resource } : null
}
export function sourceKey(source: ListedSource): string {
return source.from === 'reference' ? `reference:${source.reference}` : `resource:${source.resource}`
}
/** Every role the nodes place or decorate, once each and sorted. */
export function rolesOf(roots: GraphNode[]): string[] {
const roles = new Set<string>()
const visit = (node: GraphNode): void => {
node.roles.forEach((role) => roles.add(role))
node.children.forEach((link) => visit(link.node))
}
roots.forEach(visit)
return [...roles].sort()
}
/** The word being typed: from where it starts in {@code draft}, with what is typed of it. For a list that is the item after the last comma. */
export function wordBeingTyped(draft: string, isList: boolean): { start: number; typed: string } {
const start = isList ? draft.lastIndexOf(',') + 1 : 0
const typed = draft.slice(start)
return { start: start + (typed.length - typed.trimStart().length), typed: typed.trim() }
}
/** The choices that hold what is typed, those that start with it first; none while nothing is typed or it is already a choice. */
export function matching(choices: readonly string[], typed: string): string[] {
const wanted = typed.toLowerCase()
if (wanted === '') {
return []
}
const starting: string[] = []
const containing: string[] = []
for (const choice of choices) {
const lower = choice.toLowerCase()
if (lower === wanted) {
return []
}
if (lower.startsWith(wanted)) {
starting.push(choice)
} else if (lower.includes(wanted)) {
containing.push(choice)
}
}
return [...starting, ...containing].slice(0, MOST_SHOWN)
}
/** The draft with the word being typed replaced by {@code choice}; a list gets its separator ready for the next item. */
export function completed(draft: string, choice: string, isList: boolean): string {
const { start } = wordBeingTyped(draft, isList)
return draft.slice(0, start) + choice + (isList ? LIST_SEPARATOR : '')
}
@@ -0,0 +1,190 @@
import { ChevronRight, Plus, Trash2 } from 'lucide-react'
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} />
<ChevronRight className={cn('size-3.5 shrink-0 text-secondary-text 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))}>
<Trash2 className="size-3.5" />
</Button>
</div>
))}
<Button variant="ghost" size="xs" disabled={locked} onClick={() => onWrite(withAddedKeyframe(keys))}>
<Plus /> 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>
)
}
@@ -0,0 +1,41 @@
import { RotateCcw } from 'lucide-react'
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}>
<RotateCcw 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}`
}
+160 -96
View File
@@ -1,25 +1,63 @@
import { RotateCcw } from 'lucide-react'
import { useState } from 'react'
import { ChevronRight, Plus, RotateCcw, Spline, Trash2 } from 'lucide-react'
import { useMemo, useState } from 'react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { ScrollArea } from '@/components/ui/scroll-area'
import { cn } from '@/lib/utils'
import type { EditorState, GraphEdit, GraphNode, NodeSettings, SettingOption, ValueKind } from '../bridge/types'
import { 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 NOT_SET = ''
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, onEdit }: NodeInspectorProps): React.JSX.Element {
const locked = state.locked !== null
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">
@@ -29,7 +67,7 @@ export function NodeInspector({ node, state, values, onEdit }: NodeInspectorProp
<ScrollArea className="min-h-0 flex-1 border-t">
<div className="pb-3">
{node.settings.map((section) => (
<SettingsSection key={JSON.stringify(section.path) + section.type} section={section} state={state} values={values} locked={locked} onEdit={onEdit} />
<SettingsSection key={JSON.stringify(section.path) + section.type} section={section} context={context} />
))}
</div>
</ScrollArea>
@@ -37,80 +75,110 @@ export function NodeInspector({ node, state, values, onEdit }: NodeInspectorProp
)
}
function SettingsSection({
section,
state,
values,
locked,
onEdit
}: {
section: NodeSettings
state: EditorState
values: unknown
locked: boolean
onEdit(edit: GraphEdit): void
}): React.JSX.Element {
const type = state.types[section.type]
const options = type?.options.filter((option) => !section.shownAsNodes.includes(option.name)) ?? []
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">
<h3 className="pb-1 text-[11px] font-semibold text-muted-foreground" title={type?.description}>
{section.title}
</h3>
{options.map((option) => {
const value = valueAt(values, [...section.path, option.name])
return (
<SettingField
key={`${option.name}=${JSON.stringify(value)}`}
option={option}
value={value}
locked={locked}
onSet={(literal) => onEdit({ op: 'set', object: section.path, key: option.name, literal })}
onUnset={() => onEdit({ op: 'unset', object: section.path, key: option.name })}
/>
{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>
)
}
interface SettingFieldProps {
option: SettingOption
/** What the file sets it to; undefined when it is not set. */
value: unknown
locked: boolean
onSet(literal: string): void
onUnset(): void
}
function SettingField(props: SettingFieldProps): React.JSX.Element {
const kind = props.option.kind.kind
return kind === 'boolean' || kind === 'enum' ? <ChoiceField {...props} /> : <TypedField {...props} />
}
function FieldRow({ option, value, locked, onUnset, problem, children }: SettingFieldProps & { problem: string | null; children: React.ReactNode }): React.JSX.Element {
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="py-0.5">
<div className="flex h-7 items-center gap-2">
<label className={cn('min-w-0 flex-[4] truncate text-[12px]', option.required && 'font-medium')} title={option.description}>
{option.name}
</label>
<div className="flex min-w-0 flex-[6] items-center gap-1">
{children}
<Button variant="ghost" size="icon-sm" title="Unset" className={cn('size-6 shrink-0', value === undefined && 'invisible')} disabled={locked} onClick={onUnset}>
<RotateCcw className="size-3.5" />
</Button>
</div>
</div>
{problem !== null && <p className="pt-0.5 text-right text-[11px] text-destructive">{problem}</p>}
<div 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)}>
<ChevronRight className={cn('size-3.5 shrink-0 text-secondary-text 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: '{}' })}>
<Plus 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 })}>
<RotateCcw 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 })}>
<Trash2 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 literalOf = (choice: string): string => (option.kind.kind === 'enum' ? JSON.stringify(choice) : choice)
const literalOfChoice = (choice: string): string => (option.kind.kind === 'enum' ? JSON.stringify(choice) : choice)
return (
<FieldRow {...props} problem={null}>
<select
@@ -118,7 +186,7 @@ function ChoiceField(props: SettingFieldProps): React.JSX.Element {
value={value === undefined ? NOT_SET : String(value)}
disabled={locked}
title={option.description}
onChange={(event) => (event.target.value === NOT_SET ? onUnset() : onSet(literalOf(event.target.value)))}
onChange={(event) => (event.target.value === NOT_SET ? onUnset() : onSet(literalOfChoice(event.target.value)))}
>
<option value={NOT_SET}>{defaultLabel(option)}</option>
{choices.map((choice) => (
@@ -132,11 +200,13 @@ function ChoiceField(props: SettingFieldProps): React.JSX.Element {
}
// Numbers, text and anything else are typed in; a draft that does not fit the option says why and is not written.
function TypedField(props: SettingFieldProps): React.JSX.Element {
const { option, value, locked, onSet, onUnset } = props
// 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
@@ -149,15 +219,17 @@ function TypedField(props: SettingFieldProps): React.JSX.Element {
}
return (
<FieldRow {...props} problem={problem}>
<Input
<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]')}
onChange={(event) => setDraft(event.target.value)}
onBlur={commit}
onKeyDown={(event) => {
if (event.key === 'Enter') {
@@ -167,40 +239,32 @@ function TypedField(props: SettingFieldProps): React.JSX.Element {
}
}}
/>
{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()
}}
>
<Spline className="size-3.5" />
</Button>
)}
</FieldRow>
)
}
function defaultLabel(option: SettingOption): string {
if (option.defaultValue === null || option.defaultValue === undefined) {
return option.required ? 'Required' : 'Not set'
}
const text = typeof option.defaultValue === 'string' ? option.defaultValue : JSON.stringify(option.defaultValue)
return `Default ${text}`
}
function isNumber(kind: ValueKind): boolean {
return kind.kind === 'integer' || kind.kind === 'decimal'
}
function isText(kind: ValueKind): boolean {
return kind.kind === 'text' || kind.kind === 'reference' || kind.kind === 'resource'
}
function textOf(kind: ValueKind, value: unknown): string {
if (value === undefined) {
return NOT_SET
}
return isText(kind) && typeof value === 'string' ? value : JSON.stringify(value)
}
function literalOf(kind: ValueKind, draft: string): string {
return isText(kind) ? JSON.stringify(draft) : draft.trim()
}
function problemWith(option: SettingOption, draft: string): string | null {
if (isText(option.kind)) {
return null
if (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'
@@ -7,6 +7,7 @@ import type { BridgeClient } from '../bridge/BridgeClient'
import { NO_PART, type JsonPath, type SceneEntry, type SceneViewInfo } from '../bridge/types'
import { parsedText } from '../editor/jsonValues'
import { nodeDrawingPart, nodeWithPath } from '../editor/nodeLayout'
import { SuggestionStore } from '../editor/suggestionStore'
import { useNodeEditor } from '../editor/useNodeEditor'
import { BlockIndex, blockAtHit, NO_BLOCK } from '../scene/blockPick'
import { BlockModels } from '../scene/blockModels'
@@ -60,6 +61,7 @@ export function SceneStudio({ client, view, packRevision, onSummary, tell }: Sce
const [selectedPath, setSelectedPath] = useState<JsonPath | null>(null)
const selected = editor.state?.roots != null && selectedPath !== null ? nodeWithPath(editor.state.roots, selectedPath) : null
const values = useMemo(() => (editor.state === null ? undefined : parsedText(editor.state.text)), [editor.state])
const suggestions = useMemo(() => new SuggestionStore((of) => client.suggestions(of)), [client, packRevision])
const [pickedPart, setPickedPart] = useState(NO_PART)
const highlightedPart = view.parts ? (selected?.partId ?? pickedPart) : NO_PART
@@ -123,7 +125,7 @@ export function SceneStudio({ client, view, packRevision, onSummary, tell }: Sce
<EntryBrowser className={selected === null ? 'flex-[7]' : 'flex-[3]'} title={view.label} entries={entries} current={entry?.key ?? null} onSelect={(key) => setChosen({ key, variant: 0 })} />
{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} onEdit={editor.edit} />
<NodeInspector key={JSON.stringify(selected.path)} node={selected} state={editor.state} values={values} suggestions={suggestions} onEdit={editor.edit} />
) : (
<BlockList scene={scene} farLeavesOnly={farLeavesOnly} onFarLeavesOnly={setFarLeavesOnly} />
)}
@@ -0,0 +1,91 @@
import { useState } from 'react'
import { Input } from '@/components/ui/input'
import { cn } from '@/lib/utils'
import { completed, matching, wordBeingTyped } from '../editor/suggestions'
const NO_CHOICE = -1
type InputProps = Omit<React.ComponentProps<'input'>, 'value' | 'onChange'>
interface SuggestionInputProps extends InputProps {
value: string
onValue(value: string): void
/** Whether the text is a list typed as {@code a, b}, which completes the item being typed. */
isList: boolean
/** Reads what the text may be completed with, when the field is first used; null for a field typed freely. */
load: (() => Promise<string[]>) | null
}
/** A text field that offers what it may be typed as while it is typed; Arrow keys and Enter or Tab choose, a click chooses too. */
export function SuggestionInput({ value, onValue, isList, load, onKeyDown, onFocus, onBlur, className, ...props }: SuggestionInputProps): React.JSX.Element {
const [choices, setChoices] = useState<string[] | null>(null)
const [focused, setFocused] = useState(false)
const [highlighted, setHighlighted] = useState(NO_CHOICE)
const offered = focused && choices !== null ? matching(choices, wordBeingTyped(value, isList).typed) : []
const pick = (choice: string): void => {
onValue(completed(value, choice, isList))
setHighlighted(NO_CHOICE)
}
return (
<div className="relative min-w-0 flex-1">
<Input
{...props}
value={value}
className={className}
onChange={(event) => {
onValue(event.target.value)
setHighlighted(NO_CHOICE)
}}
onFocus={(event) => {
setFocused(true)
if (load !== null && choices === null) {
load()
.then(setChoices)
.catch(() => setChoices([]))
}
onFocus?.(event)
}}
onBlur={(event) => {
setFocused(false)
setHighlighted(NO_CHOICE)
onBlur?.(event)
}}
onKeyDown={(event) => {
if (offered.length > 0 && (event.key === 'ArrowDown' || event.key === 'ArrowUp')) {
event.preventDefault()
const step = event.key === 'ArrowDown' ? 1 : -1
setHighlighted((current) => ((current + step + offered.length + 2) % (offered.length + 1)) - 1)
return
}
if (highlighted >= 0 && highlighted < offered.length && (event.key === 'Enter' || event.key === 'Tab')) {
event.preventDefault()
pick(offered[highlighted])
return
}
onKeyDown?.(event)
}}
/>
{offered.length > 0 && (
<ul className="absolute top-full right-0 left-0 z-30 mt-0.5 overflow-hidden rounded-md border bg-popover py-0.5 text-popover-foreground shadow-md">
{offered.map((choice, index) => (
<li key={choice}>
<button
type="button"
tabIndex={-1}
className={cn('block w-full truncate px-2 py-1 text-left font-mono text-[11.5px]', index === highlighted ? 'bg-accent text-accent-foreground' : 'hover:bg-accent/60')}
onMouseDown={(event) => {
event.preventDefault()
pick(choice)
}}
>
{choice}
</button>
</li>
))}
</ul>
)}
</div>
)
}