From 7eb45cebf6c5fc14350b494d1a0ded7f32b9024d Mon Sep 17 00:00:00 2001 From: piexel Date: Tue, 10 Nov 2026 13:34:32 +0100 Subject: [PATCH] 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 --- .../core/modules/IrisPlatformRegistryIds.java | 4 +- .../iris/core/studio/bridge/StudioBridge.java | 13 + .../core/studio/scene/StudioSuggestions.java | 75 +++++ .../studio/scene/StudioSuggestionsTest.java | 31 +++ .../src/renderer/src/bridge/BridgeClient.ts | 5 + studio/src/renderer/src/editor/curves.test.ts | 84 ++++++ studio/src/renderer/src/editor/curves.ts | 217 +++++++++++++++ .../renderer/src/editor/settingFolds.test.ts | 79 ++++++ .../src/renderer/src/editor/settingFolds.ts | 128 +++++++++ .../renderer/src/editor/settingText.test.ts | 27 ++ studio/src/renderer/src/editor/settingText.ts | 48 ++++ .../src/editor/suggestionStore.test.ts | 25 ++ .../renderer/src/editor/suggestionStore.ts | 23 ++ .../renderer/src/editor/suggestions.test.ts | 82 ++++++ studio/src/renderer/src/editor/suggestions.ts | 79 ++++++ studio/src/renderer/src/studio/CurveField.tsx | 190 +++++++++++++ studio/src/renderer/src/studio/FieldRow.tsx | 41 +++ .../src/renderer/src/studio/NodeInspector.tsx | 256 +++++++++++------- .../src/renderer/src/studio/SceneStudio.tsx | 4 +- .../renderer/src/studio/SuggestionInput.tsx | 91 +++++++ 20 files changed, 1403 insertions(+), 99 deletions(-) create mode 100644 core/src/main/java/art/arcane/iris/core/studio/scene/StudioSuggestions.java create mode 100644 core/src/test/java/art/arcane/iris/core/studio/scene/StudioSuggestionsTest.java create mode 100644 studio/src/renderer/src/editor/curves.test.ts create mode 100644 studio/src/renderer/src/editor/curves.ts create mode 100644 studio/src/renderer/src/editor/settingFolds.test.ts create mode 100644 studio/src/renderer/src/editor/settingFolds.ts create mode 100644 studio/src/renderer/src/editor/settingText.test.ts create mode 100644 studio/src/renderer/src/editor/settingText.ts create mode 100644 studio/src/renderer/src/editor/suggestionStore.test.ts create mode 100644 studio/src/renderer/src/editor/suggestionStore.ts create mode 100644 studio/src/renderer/src/editor/suggestions.test.ts create mode 100644 studio/src/renderer/src/editor/suggestions.ts create mode 100644 studio/src/renderer/src/studio/CurveField.tsx create mode 100644 studio/src/renderer/src/studio/FieldRow.tsx create mode 100644 studio/src/renderer/src/studio/SuggestionInput.tsx diff --git a/core/src/main/java/art/arcane/iris/core/modules/IrisPlatformRegistryIds.java b/core/src/main/java/art/arcane/iris/core/modules/IrisPlatformRegistryIds.java index 0bee1d1fc..63f48b102 100644 --- a/core/src/main/java/art/arcane/iris/core/modules/IrisPlatformRegistryIds.java +++ b/core/src/main/java/art/arcane/iris/core/modules/IrisPlatformRegistryIds.java @@ -38,7 +38,7 @@ import java.util.function.Function; * The registries of the platform Iris runs on, as validators read them: the same lists studio completes options from. * Each registry is read once, when a validator first asks for it. */ -final class IrisPlatformRegistryIds implements PlatformRegistries { +public final class IrisPlatformRegistryIds implements PlatformRegistries { private static final String DEFAULT_NAMESPACE = "minecraft:"; private final IrisPlatform platform; @@ -49,7 +49,7 @@ final class IrisPlatformRegistryIds implements PlatformRegistries { } /** The bound platform's registries; empty when no platform is bound, such as in a build. */ - static Optional ofBoundPlatform() { + public static Optional ofBoundPlatform() { return IrisPlatforms.isBound() ? Optional.of(new IrisPlatformRegistryIds(IrisPlatforms.get())) : Optional.empty(); } diff --git a/core/src/main/java/art/arcane/iris/core/studio/bridge/StudioBridge.java b/core/src/main/java/art/arcane/iris/core/studio/bridge/StudioBridge.java index acd65c13b..51397a549 100644 --- a/core/src/main/java/art/arcane/iris/core/studio/bridge/StudioBridge.java +++ b/core/src/main/java/art/arcane/iris/core/studio/bridge/StudioBridge.java @@ -38,6 +38,7 @@ import art.arcane.iris.core.studio.saved.SavedWorlds; import art.arcane.iris.core.studio.scene.StudioEditors; import art.arcane.iris.core.studio.scene.StudioPatterns; import art.arcane.iris.core.studio.scene.StudioScenes; +import art.arcane.iris.core.studio.scene.StudioSuggestions; import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.framework.render.RenderType; import art.arcane.iris.engine.object.world.region.IrisRegion; @@ -236,6 +237,7 @@ public final class StudioBridge implements AutoCloseable { case "scene-file" -> sendJson(exchange, STATUS_OK, sceneFile(get(exchange).engine(), query)); case "scene-edit" -> sendJson(exchange, STATUS_OK, sceneEdit(exchange, query)); case "scene-write" -> sendJson(exchange, STATUS_OK, sceneWrite(exchange, query)); + case "suggestions" -> sendJson(exchange, STATUS_OK, suggestions(get(exchange).engine(), query)); case "scene-entries" -> sendJson(exchange, STATUS_OK, sceneEntries(get(exchange).engine(), query)); case "scene-bake" -> sendJson(exchange, STATUS_OK, sceneBake(get(exchange).engine(), query)); case "scene" -> sendBytes(exchange, "application/octet-stream", scene(get(exchange).engine(), query)); @@ -403,6 +405,17 @@ public final class StudioBridge implements AutoCloseable { } } + // What a setting naming a platform entry (reference) or a pack resource (resource) may be typed as. + private static List suggestions(Engine engine, Query query) { + try { + return query.has("reference") + ? StudioSuggestions.ofReference(query.text("reference")) + : StudioSuggestions.ofResource(engine, query.text("resource")); + } catch (NoSuchElementException unknown) { + throw new RequestError(STATUS_NOT_FOUND, unknown.getMessage()); + } + } + private static BakeRun sceneBake(Engine engine, Query query) { String key = query.text("key"); try { diff --git a/core/src/main/java/art/arcane/iris/core/studio/scene/StudioSuggestions.java b/core/src/main/java/art/arcane/iris/core/studio/scene/StudioSuggestions.java new file mode 100644 index 000000000..ca1bc14e1 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/core/studio/scene/StudioSuggestions.java @@ -0,0 +1,75 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.core.studio.scene; + +import art.arcane.iris.core.modules.IrisPackResources; +import art.arcane.iris.core.modules.IrisPlatformRegistryIds; +import art.arcane.iris.engine.framework.Engine; +import com.volmit.config.Reference; +import com.volmit.resource.ResourceId; + +import java.util.Collection; +import java.util.List; +import java.util.NoSuchElementException; + +/** What the studio offers while an author types a setting that names something: the platform's entries of a reference, or the pack's resources of a kind. */ +public final class StudioSuggestions { + private StudioSuggestions() { + } + + /** + * The ids of the platform's registry {@code referenceName} names, sorted. + * + * @throws NoSuchElementException when there is no such reference + */ + public static List ofReference(String referenceName) { + Reference reference; + try { + reference = Reference.valueOf(referenceName); + } catch (IllegalArgumentException unknown) { + throw new NoSuchElementException("No reference named " + referenceName); + } + return IrisPlatformRegistryIds.ofBoundPlatform() + .map(registries -> sortedKeys(registries.ids(reference), null)) + .orElse(List.of()); + } + + /** + * The keys of the pack's resources of the kind {@code kindId} names, as the pack writes them, sorted. + * + * @throws NoSuchElementException when the pack has no such kind + */ + public static List ofResource(Engine engine, String kindId) { + IrisPackResources resources = engine.getData().getPackResources(); + try { + return sortedKeys(resources.ids(ResourceId.parse(kindId)), resources.packId().namespace()); + } catch (IllegalArgumentException unknown) { + throw new NoSuchElementException(unknown.getMessage()); + } + } + + /** {@code ids} as written, sorted: a resource of the pack's own namespace by its path, any other id in full. */ + static List sortedKeys(Collection ids, String packNamespace) { + return ids.stream() + .map(id -> id.namespace().equals(packNamespace) ? id.path() : id.toString()) + .distinct() + .sorted() + .toList(); + } +} diff --git a/core/src/test/java/art/arcane/iris/core/studio/scene/StudioSuggestionsTest.java b/core/src/test/java/art/arcane/iris/core/studio/scene/StudioSuggestionsTest.java new file mode 100644 index 000000000..367e9b4ca --- /dev/null +++ b/core/src/test/java/art/arcane/iris/core/studio/scene/StudioSuggestionsTest.java @@ -0,0 +1,31 @@ +package art.arcane.iris.core.studio.scene; + +import com.volmit.resource.ResourceId; +import org.junit.Test; + +import java.util.List; +import java.util.NoSuchElementException; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThrows; + +public class StudioSuggestionsTest { + @Test + public void thePacksOwnResourcesAreOfferedByPathAndOthersInFull() { + List ids = List.of(ResourceId.parse("overworld:birch"), ResourceId.parse("other:oak"), ResourceId.parse("overworld:conifer/pine")); + + assertEquals(List.of("birch", "conifer/pine", "other:oak"), StudioSuggestions.sortedKeys(ids, "overworld")); + } + + @Test + public void platformEntriesAreOfferedInFull() { + List ids = List.of(ResourceId.parse("minecraft:stone"), ResourceId.parse("minecraft:dirt")); + + assertEquals(List.of("minecraft:dirt", "minecraft:stone"), StudioSuggestions.sortedKeys(ids, null)); + } + + @Test + public void aReferenceThatDoesNotExistIsRefused() { + assertThrows(NoSuchElementException.class, () -> StudioSuggestions.ofReference("NOT_A_REFERENCE")); + } +} diff --git a/studio/src/renderer/src/bridge/BridgeClient.ts b/studio/src/renderer/src/bridge/BridgeClient.ts index a80177bc2..dad1242a7 100644 --- a/studio/src/renderer/src/bridge/BridgeClient.ts +++ b/studio/src/renderer/src/bridge/BridgeClient.ts @@ -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 { + return this.json(`suggestions?${new URLSearchParams(of)}`) + } + sceneEntries(viewId: string): Promise { return this.json(`scene-entries?${new URLSearchParams({ view: viewId })}`) } diff --git a/studio/src/renderer/src/editor/curves.test.ts b/studio/src/renderer/src/editor/curves.test.ts new file mode 100644 index 000000000..8e00a484b --- /dev/null +++ b/studio/src/renderer/src/editor/curves.test.ts @@ -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]]) + }) +}) diff --git a/studio/src/renderer/src/editor/curves.ts b/studio/src/renderer/src/editor/curves.ts new file mode 100644 index 000000000..5cf2a1fc9 --- /dev/null +++ b/studio/src/renderer/src/editor/curves.ts @@ -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 { + 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 { + 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 { + 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, key: string): Record { + 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, name: string, number: number | undefined): Record { + 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)]]) +} diff --git a/studio/src/renderer/src/editor/settingFolds.test.ts b/studio/src/renderer/src/editor/settingFolds.test.ts new file mode 100644 index 000000000..90b180090 --- /dev/null +++ b/studio/src/renderer/src/editor/settingFolds.test.ts @@ -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 = { + 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']) + }) +}) diff --git a/studio/src/renderer/src/editor/settingFolds.ts b/studio/src/renderer/src/editor/settingFolds.ts new file mode 100644 index 000000000..f6a9dc943 --- /dev/null +++ b/studio/src/renderer/src/editor/settingFolds.ts @@ -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 { + return typeof value === 'object' && value !== null && !Array.isArray(value) +} + +function isObjects(value: unknown): value is Record[] { + 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, 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 + +function addFold(into: SettingsFold[], types: Record, values: unknown, head: FoldHead, shownAsNodes: Set): 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, 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): 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))) +} diff --git a/studio/src/renderer/src/editor/settingText.test.ts b/studio/src/renderer/src/editor/settingText.test.ts new file mode 100644 index 000000000..9b21e067c --- /dev/null +++ b/studio/src/renderer/src/editor/settingText.test.ts @@ -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\\""') + }) +}) diff --git a/studio/src/renderer/src/editor/settingText.ts b/studio/src/renderer/src/editor/settingText.ts new file mode 100644 index 000000000..d02ebe432 --- /dev/null +++ b/studio/src/renderer/src/editor/settingText.ts @@ -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() +} diff --git a/studio/src/renderer/src/editor/suggestionStore.test.ts b/studio/src/renderer/src/editor/suggestionStore.test.ts new file mode 100644 index 000000000..a61887c83 --- /dev/null +++ b/studio/src/renderer/src/editor/suggestionStore.test.ts @@ -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' }) + }) +}) diff --git a/studio/src/renderer/src/editor/suggestionStore.ts b/studio/src/renderer/src/editor/suggestionStore.ts new file mode 100644 index 000000000..de6b89aa8 --- /dev/null +++ b/studio/src/renderer/src/editor/suggestionStore.ts @@ -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 + +/** 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>() + + constructor(private readonly fetch: SuggestionFetch) {} + + load(source: ListedSource): Promise { + 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 + } +} diff --git a/studio/src/renderer/src/editor/suggestions.test.ts b/studio/src/renderer/src/editor/suggestions.test.ts new file mode 100644 index 000000000..a2ae79600 --- /dev/null +++ b/studio/src/renderer/src/editor/suggestions.test.ts @@ -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, ') + }) +}) diff --git a/studio/src/renderer/src/editor/suggestions.ts b/studio/src/renderer/src/editor/suggestions.ts new file mode 100644 index 000000000..cd71ead34 --- /dev/null +++ b/studio/src/renderer/src/editor/suggestions.ts @@ -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 = 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 + +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() + 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 : '') +} diff --git a/studio/src/renderer/src/studio/CurveField.tsx b/studio/src/renderer/src/studio/CurveField.tsx new file mode 100644 index 000000000..c270d9bbe --- /dev/null +++ b/studio/src/renderer/src/studio/CurveField.tsx @@ -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 ( + <> + + + + {open && onSet(JSON.stringify(next))} />} + + ) +} + +function Sparkline({ value }: { value: unknown }): React.JSX.Element { + const samples = samplesOf(value, SPARKLINE_SAMPLES) ?? [] + const low = Math.min(...samples) + const span = Math.max(...samples) - low + const drawable = SPARKLINE_HEIGHT - 2 * SPARKLINE_MARGIN + const points = samples.map((sample, index) => { + const x = (index / (samples.length - 1)) * SPARKLINE_WIDTH + const y = SPARKLINE_MARGIN + (span === 0 ? drawable / 2 : drawable - ((sample - low) / span) * drawable) + return `${x.toFixed(1)},${y.toFixed(1)}` + }) + return ( + + + + ) +} + +function CurveEditor({ value, locked, onWrite }: { value: unknown; locked: boolean; onWrite(next: unknown): void }): React.JSX.Element { + const byShape = isShape(value) + return ( +
+
+ + +
+ {isShape(value) ? : } +
+ ) +} + +function PointsEditor({ keys, locked, onWrite }: { keys: Keyframe[]; locked: boolean; onWrite(next: Keyframe[]): void }): React.JSX.Element { + return ( + <> + {keys.map(([t, value], index) => ( +
+ next !== undefined && onWrite(withKeyframe(keys, index, [next, value]))} /> + next !== undefined && onWrite(withKeyframe(keys, index, [t, next]))} /> + +
+ ))} + + + ) +} + +function ShapeEditor({ shape, locked, onWrite }: { shape: Record; locked: boolean; onWrite(next: unknown): void }): React.JSX.Element { + const named = shapeNamed(shape.shape)! + const numeric = (name: string): number | undefined => (typeof shape[name] === 'number' ? shape[name] : undefined) + return ( + <> + +
+ onWrite(withSetting(shape, 'from', next))} /> + onWrite(withSetting(shape, 'to', next))} /> +
+ {named.parameters.map((parameter) => ( + onWrite(withSetting(shape, parameter.name, next))} + /> + ))} + + ) +} + +interface NumberBoxProps { + label: string + value: number | undefined + placeholder?: string + disabled: boolean + /** The number typed, or undefined when it was emptied; text that is no number is dropped. */ + onCommit(next: number | undefined): void +} + +function NumberBox({ label, value, placeholder, disabled, onCommit }: NumberBoxProps): React.JSX.Element { + const shown = value === undefined ? '' : String(value) + const [draft, setDraft] = useState(shown) + const [seen, setSeen] = useState(shown) + if (seen !== shown) { + setSeen(shown) + setDraft(shown) + } + const commit = (): void => { + if (draft === shown) { + return + } + const next = draft.trim() === '' ? undefined : Number(draft) + if (next !== undefined && !Number.isFinite(next)) { + setDraft(shown) + return + } + onCommit(next) + } + return ( + + ) +} diff --git a/studio/src/renderer/src/studio/FieldRow.tsx b/studio/src/renderer/src/studio/FieldRow.tsx new file mode 100644 index 000000000..e0ff50dd0 --- /dev/null +++ b/studio/src/renderer/src/studio/FieldRow.tsx @@ -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 ( +
+
+ +
+ {children} + +
+
+ {problem !== null &&

{problem}

} +
+ ) +} + +export function defaultLabel(option: SettingOption): string { + if (option.defaultValue === null || option.defaultValue === undefined) { + return option.required ? 'Required' : 'Not set' + } + const text = typeof option.defaultValue === 'string' ? option.defaultValue : JSON.stringify(option.defaultValue) + return `Default ${text}` +} diff --git a/studio/src/renderer/src/studio/NodeInspector.tsx b/studio/src/renderer/src/studio/NodeInspector.tsx index 27cde9707..ace636e1f 100644 --- a/studio/src/renderer/src/studio/NodeInspector.tsx +++ b/studio/src/renderer/src/studio/NodeInspector.tsx @@ -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 + 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>(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 (
@@ -29,7 +67,7 @@ export function NodeInspector({ node, state, values, onEdit }: NodeInspectorProp
{node.settings.map((section) => ( - + ))}
@@ -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.title} -

- {options.map((option) => { - const value = valueAt(values, [...section.path, option.name]) - return ( - onEdit({ op: 'set', object: section.path, key: option.name, literal })} - onUnset={() => onEdit({ op: 'unset', object: section.path, key: option.name })} - /> + {folds.map((fold) => + fold.kind === 'own' ? ( +
+

+ {fold.title} +

+ +
+ ) : ( +
+ + {open.has(idOfFold(fold)) && } +
) - })} + )}
) } -interface SettingFieldProps { - option: SettingOption - /** What the file sets it to; undefined when it is not set. */ - value: unknown - locked: boolean - onSet(literal: string): void - onUnset(): void -} - -function SettingField(props: SettingFieldProps): React.JSX.Element { - const kind = props.option.kind.kind - return kind === 'boolean' || kind === 'enum' ? : -} - -function FieldRow({ option, value, locked, onUnset, problem, children }: SettingFieldProps & { problem: string | null; children: React.ReactNode }): React.JSX.Element { +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 ( -
-
- -
- {children} - -
-
- {problem !== null &&

{problem}

} +
+ + {fold.kind === 'list' && ( + + )} + {holder !== null && ( + + )} + {fold.kind === 'item' && ( + + )}
) } +function FoldFields({ fold, context }: { fold: SettingsFold; context: SectionContext }): React.JSX.Element { + const { values, locked, open, roles, suggestions, onToggle, onEdit } = context + return ( +
+ {fold.options.map((option) => { + const value = valueAt(values, [...fold.path, option.name]) + const curveId = JSON.stringify([...fold.path, option.name]) + return ( + onToggle(curveId)} + loadSuggestions={(source) => (source.from === 'roles' ? Promise.resolve(roles) : suggestions.load(source))} + onSet={(literal) => onEdit({ op: 'set', object: fold.path, key: option.name, literal })} + onUnset={() => onEdit({ op: 'unset', object: fold.path, key: option.name })} + /> + ) + })} +
+ ) +} + +interface FieldProps extends SettingFieldProps { + /** The schema type of the object the option is in. */ + owner: string + curveOpen: boolean + onToggleCurve(): void + loadSuggestions(source: SuggestionSource): Promise +} + +function SettingField(props: FieldProps): React.JSX.Element { + const kind = props.option.kind.kind + if (kind === 'boolean' || kind === 'enum') { + return + } + if (kind === 'any' && isCurve(props.value)) { + return + } + return +} + function ChoiceField(props: SettingFieldProps): React.JSX.Element { const { option, value, locked, onSet, onUnset } = props const choices = option.kind.kind === 'enum' ? option.kind.constants.map((constant) => constant.name) : ['true', 'false'] - const 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 ( 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) && ( + + )} ) } -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' diff --git a/studio/src/renderer/src/studio/SceneStudio.tsx b/studio/src/renderer/src/studio/SceneStudio.tsx index 2aa3d4b31..f56f0ffca 100644 --- a/studio/src/renderer/src/studio/SceneStudio.tsx +++ b/studio/src/renderer/src/studio/SceneStudio.tsx @@ -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(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 setChosen({ key, variant: 0 })} /> {view.baked && entry !== null && } {selected !== null && editor.state !== null ? ( - + ) : ( )} diff --git a/studio/src/renderer/src/studio/SuggestionInput.tsx b/studio/src/renderer/src/studio/SuggestionInput.tsx new file mode 100644 index 000000000..1fe7b5624 --- /dev/null +++ b/studio/src/renderer/src/studio/SuggestionInput.tsx @@ -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, '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) | 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(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 ( +
+ { + 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 && ( +
    + {offered.map((choice, index) => ( +
  • + +
  • + ))} +
+ )} +
+ ) +}