Create and delete procedural objects from the studio's entry list

A view's entries can now be created from a starter tree in a chosen folder and deleted from the browser. Deleting lists the pack files that still name the entry, then moves it to the desktop trash, or the pack's .iris/trash where there is none. An EditableSceneView opts in with SceneCreation; the host does the writing.

v3: d6e6fc3ef
This commit is contained in:
piexel committed 2026-11-10 13:42:30 +01:00
1 parent 7eb45cebf6
commit 3c03bba7e7
19 files changed
+760 -32

No files matched your search

+1 -1
View File
@@ -46,7 +46,7 @@ types that carry them and lists what the Iris adapter still owes.
| Dense chunk output | `Hunk<T>`, `GenerationContext.blocks`, reference `ArrayHunk<T>` |
| Positions, boxes and faces | `com.volmit.geometry`: `BlockPosition`, `BlockBox`, `BlockFace` |
| Sparse geometry | `GeneratedObject` |
| Studio views of what a module builds | `com.volmit.tooling`: `ModuleSetup.tooling()` (`ToolingRegistry.registerView`), sealed `StudioView` (`SceneView` with `SceneEntry`, `BakeRun` (`Stage`), `BlockParts`, `PatternView` with `PatternEntry`, `PatternArea`, `BlockPattern`), `EditableSceneView` (`SceneFile`, `NodeGraph`, `GraphNode` with `Link`, `NodeSettings`, `Edits`, `Addition`), `JsonText`, `JsonPath` (`Key`, `Index`), host `StudioViewRegistration` |
| Studio views of what a module builds | `com.volmit.tooling`: `ModuleSetup.tooling()` (`ToolingRegistry.registerView`), sealed `StudioView` (`SceneView` with `SceneEntry`, `BakeRun` (`Stage`), `BlockParts`, `PatternView` with `PatternEntry`, `PatternArea`, `BlockPattern`), `EditableSceneView` (`SceneFile`, `SceneCreation`, `NodeGraph`, `GraphNode` with `Link`, `NodeSettings`, `Edits`, `Addition`), `JsonText`, `JsonPath` (`Key`, `Index`), host `StudioViewRegistration` |
| Commands of a module | `com.volmit.tooling`: `ToolingRegistry.registerCommand`, immutable `Command` (`named`, `alias`, `describe`, `child`, `argument`, `runs`, `openToEveryone`), typed `Argument` (`word`, `text`, `integer`, `decimal`, `flag`, `choice`, `resource`, `registered`, `orElse`, `suggesting`), `CommandAction`, `CommandContext` (`get`, `sender`, `pack`, `world`, `platform`), plain-text `Sender`, `ToolPack` (`edit` with `PackEdit`, `outputFolder`, `objects` with `ObjectCodec`), host `CommandRegistration` in `FeatureCatalog.commands()` |
| Buffered placement writes | `PlacementRequest`, `PlacementAccess`, host-owned `PlacementEdit` |
| Typed generation and persistent storage | `mantle` package |
+4
View File
@@ -1373,6 +1373,10 @@ API now: `world.running()`, `world.seed(purpose)`, `TerrainSampler`, `FeatureSet
reads as nodes (`NodeGraph`). The studio makes every write, so one implementation keeps the author's layout,
checks the result is still JSON, refuses edits outside a studio world and moves the file in atomically for the pack
watcher. `JsonText` is in the API because a view reads positions from it; splicing text is not.
- **Creating and deleting are the host's too.** A view says only how its entries are made (`SceneCreation`: the kind
whose folder holds the files, the JSON a new one starts as, and the prefix other files name an entry by). The host
checks the key is a folder-safe name, writes the file, lists the files that still name an entry before it goes, and
moves it to the trash, so a view never touches the pack's files.
- **Paths are typed.** A `JsonPath` step is a `Key` or an `Index`, so a view cannot write a step the file cannot hold.
- **The wire is the host's.** The studio protocol may encode an absent part or block as it likes (Iris sends `-1`);
the API types say absent with `Optional`/`OptionalInt`.
+3 -1
View File
@@ -534,7 +534,9 @@ final class RuinScenes implements SceneView {
settings (`NodeSettings`, shown as the pack's schema describes their type), the nodes it holds and the `Edits` the
studio may make (a child list to move nodes into, whether it moves, the `Addition`s it offers). Places in the file
are `JsonPath`s of `Key` and `Index` steps. The studio writes the file itself, rewriting only what changes; the
view never writes.
view never writes. A view whose entries the studio may create and delete returns a `SceneCreation` from
`creation()`: the resource kind of its files, the starter JSON of a new entry and the text other files name an
entry by; the studio does the writing, listing of uses and trashing.
- Absent values are empty, never blank or `-1`: an entry without a group, a node that draws no part of the scene
(`GraphNode.part()`), a column a pattern places nothing at (`BlockPattern.pickAt`).
@@ -20,4 +20,9 @@ public interface EditableSceneView extends SceneView {
* @throws IllegalArgumentException when {@code text} does not hold what this view edits
*/
NodeGraph graph(PackWorld world, String key, JsonText text);
/** How the studio creates and removes entries of this view; empty when it may not, which is the default. */
default Optional<SceneCreation> creation() {
return Optional.empty();
}
}
@@ -0,0 +1,18 @@
package com.volmit.tooling;
import com.volmit.resource.ResourceKind;
import java.util.Objects;
/**
* How the studio creates and removes the entries of an editable scene view: each entry is a file of {@code kind}, a new
* one starts as the JSON text {@code starter}, and other files of the pack name an entry {@code key} as
* {@code referencePrefix + key}, which is how the studio finds what still uses an entry before it is removed.
*/
public record SceneCreation(ResourceKind<?> kind, String starter, String referencePrefix) {
public SceneCreation {
Objects.requireNonNull(kind, "kind");
Objects.requireNonNull(starter, "starter");
Objects.requireNonNull(referencePrefix, "referencePrefix");
}
}
@@ -237,6 +237,9 @@ 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 "scene-create" -> sendJson(exchange, STATUS_OK, sceneCreate(exchange, query));
case "scene-uses" -> sendJson(exchange, STATUS_OK, sceneUses(get(exchange).engine(), query));
case "scene-delete" -> sendJson(exchange, STATUS_OK, sceneDelete(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));
@@ -343,7 +346,7 @@ public final class StudioBridge implements AutoCloseable {
StudioEditors editors = StudioEditors.of(engine);
StudioScenes scenes = StudioScenes.of(engine);
return scenes.views().stream()
.map(view -> new SceneViewInfo(view.id(), view.label(), view.description(), editors.edits(view.id()), scenes.isBaked(view.id()), scenes.hasParts(view.id())))
.map(view -> new SceneViewInfo(view.id(), view.label(), view.description(), editors.edits(view.id()), editors.edits(view.id()) && editors.creates(view.id()), scenes.isBaked(view.id()), scenes.hasParts(view.id())))
.toList();
}
@@ -369,8 +372,25 @@ public final class StudioBridge implements AutoCloseable {
});
}
private MessageBody sceneCreate(HttpExchange exchange, Query query) throws IOException {
Engine engine = post(exchange).engine();
return editing(() -> {
StudioEditors.of(engine).create(query.text("view"), query.text("key"));
return new MessageBody("Created " + query.text("key"));
});
}
private static UsesBody sceneUses(Engine engine, Query query) throws IOException {
return editing(() -> new UsesBody(StudioEditors.of(engine).usesOf(query.text("view"), query.text("key"))));
}
private TrashedBody sceneDelete(HttpExchange exchange, Query query) throws IOException {
Engine engine = post(exchange).engine();
return editing(() -> new TrashedBody(StudioEditors.of(engine).delete(query.text("view"), query.text("key"))));
}
// A refused edit is the user's to fix, so it answers with why rather than as a failure of the bridge.
private static StudioEditors.EditorState editing(EditorTask task) throws IOException {
private static <T> T editing(EditorTask<T> task) throws IOException {
try {
return task.run();
} catch (NoSuchElementException unknown) {
@@ -385,8 +405,8 @@ public final class StudioBridge implements AutoCloseable {
}
@FunctionalInterface
private interface EditorTask {
StudioEditors.EditorState run() throws IOException;
private interface EditorTask<T> {
T run() throws IOException;
}
private static String readBody(HttpExchange exchange) throws IOException {
@@ -783,8 +803,14 @@ public final class StudioBridge implements AutoCloseable {
private record ErrorBody(String error) {
}
/** A scene view as the studio lists it; {@code editable} when its entries can be edited as nodes, {@code baked} when their bake can be timed, {@code parts} when the blocks of a scene can be told by the part that placed them. */
private record SceneViewInfo(String id, String label, String description, boolean editable, boolean baked, boolean parts) {
/** A scene view as the studio lists it; {@code editable} when its entries can be edited as nodes, {@code creatable} when they can also be created and deleted, {@code baked} when their bake can be timed, {@code parts} when the blocks of a scene can be told by the part that placed them. */
private record SceneViewInfo(String id, String label, String description, boolean editable, boolean creatable, boolean baked, boolean parts) {
}
private record UsesBody(List<String> files) {
}
private record TrashedBody(String to) {
}
/** A {@link SceneEntry} as the studio reads it, with a blank group for none. */
@@ -0,0 +1,157 @@
/*
* 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 <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.core.studio.scene;
import com.volmit.tooling.JsonText;
import com.volmit.tooling.SceneCreation;
import java.awt.Desktop;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.StandardCopyOption;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.regex.Pattern;
/**
* Creates the files of a scene view's entries and removes them safely: a new entry starts from the view's starter text,
* what still names an entry is found before it goes, and a removed entry goes to the trash rather than away for good.
* Keys are confined to folder-safe names, so no file outside the kind's folder of the pack is ever touched.
*/
final class SceneFiles {
private static final Pattern KEY = Pattern.compile("[a-z0-9_-]+(/[a-z0-9_-]+)*");
private static final String FILE_EXTENSION = ".json";
private static final String WRITING_SUFFIX = ".tmp";
private static final String GENERATED_FOLDER_PREFIX = ".";
private static final String PACK_TRASH = ".iris/trash";
private static final String DESKTOP_TRASH = "the trash";
/** Where the desktop moves a file to its trash; absent a desktop it moves nothing. */
@FunctionalInterface
interface DesktopTrash {
/** @return whether the desktop took {@code file} to its trash */
boolean take(Path file);
}
private final Path packFolder;
private final SceneCreation creation;
private final DesktopTrash desktopTrash;
SceneFiles(Path packFolder, SceneCreation creation, DesktopTrash desktopTrash) {
this.packFolder = packFolder;
this.creation = creation;
this.desktopTrash = desktopTrash;
}
static DesktopTrash systemTrash() {
return file -> Desktop.isDesktopSupported() && Desktop.getDesktop().isSupported(Desktop.Action.MOVE_TO_TRASH)
&& Desktop.getDesktop().moveToTrash(file.toFile());
}
/** @return why {@code key} can't name an entry, or null when it can */
static String refusalOfKey(String key) {
if (key.isBlank()) {
return "Give it a name";
}
return KEY.matcher(key).matches() ? null : "Use lower case letters, digits, - and _, with / between folders";
}
Path fileOf(String key) {
String refusal = refusalOfKey(key);
if (refusal != null) {
throw new IllegalArgumentException(refusal);
}
return packFolder.resolve(creation.kind().folder()).resolve(key + FILE_EXTENSION);
}
/**
* Writes a new entry from the starter text at {@code key}.
*
* @throws IllegalArgumentException naming why, when {@code key} can't name a new entry or the starter is not JSON
*/
Path create(String key) throws IOException {
Path file = fileOf(key);
if (Files.exists(file)) {
throw new IllegalArgumentException(key + " already exists");
}
JsonText.parse(creation.starter());
Files.createDirectories(file.getParent());
Path written = file.resolveSibling(file.getFileName() + WRITING_SUFFIX);
Files.writeString(written, creation.starter(), StandardCharsets.UTF_8);
Files.move(written, file, StandardCopyOption.ATOMIC_MOVE);
return file;
}
/**
* The pack's files that name the entry at {@code key}, such as the biomes that place it, below the pack. Folders
* starting with a dot hold what the studio generates, like the schema, and are left out.
*/
List<String> usesOf(String key) throws IOException {
String reference = "\"" + creation.referencePrefix() + key + "\"";
Path own = fileOf(key);
List<String> using = new ArrayList<>();
Files.walkFileTree(packFolder, new SimpleFileVisitor<>() {
@Override
public FileVisitResult preVisitDirectory(Path folder, BasicFileAttributes attributes) {
boolean generated = !folder.equals(packFolder) && folder.getFileName().toString().startsWith(GENERATED_FOLDER_PREFIX);
return generated ? FileVisitResult.SKIP_SUBTREE : FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attributes) throws IOException {
if (!file.equals(own) && file.getFileName().toString().endsWith(FILE_EXTENSION) && namesIn(file, reference)) {
using.add(packFolder.relativize(file).toString().replace('\\', '/'));
}
return FileVisitResult.CONTINUE;
}
});
using.sort(null);
return using;
}
private static boolean namesIn(Path file, String reference) throws IOException {
return new String(Files.readAllBytes(file), StandardCharsets.UTF_8).contains(reference);
}
/**
* Moves the entry at {@code key} to the desktop's trash, or where the desktop has none, to the pack's
* {@code .iris/trash}; returns where it went, to tell.
*
* @throws NoSuchElementException when the entry has no file
*/
String moveToTrash(String key) throws IOException {
Path file = fileOf(key);
if (!Files.isRegularFile(file)) {
throw new NoSuchElementException("Entry " + key + " has no file at " + packFolder.relativize(file));
}
if (desktopTrash.take(file)) {
return DESKTOP_TRASH;
}
Path trashed = packFolder.resolve(PACK_TRASH).resolve(key.replace('/', '_') + "-" + System.currentTimeMillis() + FILE_EXTENSION);
Files.createDirectories(trashed.getParent());
Files.move(file, trashed);
return PACK_TRASH;
}
}
@@ -25,6 +25,7 @@ import com.volmit.tooling.GraphNode;
import com.volmit.tooling.JsonPath;
import com.volmit.tooling.JsonText;
import com.volmit.tooling.NodeGraph;
import com.volmit.tooling.SceneCreation;
import com.volmit.tooling.SceneFile;
import java.io.IOException;
@@ -118,6 +119,49 @@ public final class StudioEditors {
return save(viewId, key, file, text);
}
/** Whether entries of {@code viewId} can be created and removed from the studio. */
public boolean creates(String viewId) {
return views.ask(viewId, "tell whether entries are created", view -> view.creation().isPresent());
}
/**
* Writes a new entry {@code key} of the view from its starter text. The entry shows once the pack has reloaded.
*
* @throws EditsLockedException when the world is not a studio world
* @throws IllegalArgumentException naming why, when {@code key} can't name a new entry
* @throws NoSuchElementException when there is no such view, or its entries can't be created
*/
public void create(String viewId, String key) throws IOException {
requireStudioWorld();
files(viewId).create(key);
}
/**
* The files of the pack that still name entry {@code key}, which a removal would leave without it.
*
* @throws NoSuchElementException when there is no such view, or its entries can't be removed
*/
public List<String> usesOf(String viewId, String key) throws IOException {
return files(viewId).usesOf(key);
}
/**
* Moves entry {@code key} to the trash and tells where it went.
*
* @throws EditsLockedException when the world is not a studio world
* @throws NoSuchElementException when there is no such view, or the entry has no file
*/
public String delete(String viewId, String key) throws IOException {
requireStudioWorld();
return files(viewId).moveToTrash(key);
}
private SceneFiles files(String viewId) {
SceneCreation creation = views.ask(viewId, "tell how entries are created", EditableSceneView::creation)
.orElseThrow(() -> new NoSuchElementException("The entries of " + viewId + " can't be created or removed"));
return new SceneFiles(packFolder, creation, SceneFiles.systemTrash());
}
private void requireStudioWorld() {
if (!studioWorld) {
throw new EditsLockedException(LOCKED_OUTSIDE_STUDIO);
@@ -0,0 +1,131 @@
package art.arcane.iris.core.studio.scene;
import art.arcane.iris.core.modules.JsonFormsCodecs;
import art.arcane.iris.engine.procedural.ProceduralObjectCatalog;
import art.arcane.iris.engine.procedural.part.PartOutline;
import art.arcane.iris.engine.procedural.part.ProceduralObject;
import art.arcane.iris.modules.objects.ProceduralObjectScenes;
import com.google.gson.GsonBuilder;
import com.volmit.tooling.SceneCreation;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.NoSuchElementException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
public class SceneFilesTest {
private static final SceneCreation CREATION = new ProceduralObjectScenes().creation().orElseThrow();
@Rule
public TemporaryFolder temporary = new TemporaryFolder();
private SceneFiles files(Path pack, SceneFiles.DesktopTrash trash) {
return new SceneFiles(pack, CREATION, trash);
}
@Test
public void keysMustBePlainFolderSafeNames() {
assertEquals(null, SceneFiles.refusalOfKey("trees/oak-2"));
assertEquals("Give it a name", SceneFiles.refusalOfKey(" "));
for (String key : List.of("Trees/Oak", "trees//oak", "/oak", "oak/", "../oak", "trees/../oak", "oak.json", "trees\\oak")) {
assertTrue(key, SceneFiles.refusalOfKey(key).startsWith("Use lower case"));
}
}
@Test
public void theStarterIsATreeWithAPartToGrowFrom() {
ProceduralObject tree = new GsonBuilder().registerTypeAdapterFactory(new JsonFormsCodecs()).create().fromJson(CREATION.starter(), ProceduralObject.class);
assertEquals(2, PartOutline.of(tree).nodeCount());
assertEquals(2, tree.materials().size());
}
@Test
public void aNewEntryIsWrittenInTheKindsFolderFromTheStarter() throws Exception {
Path pack = temporary.newFolder("pack").toPath();
Path created = files(pack, file -> false).create("trees/oak");
assertEquals(pack.resolve(ProceduralObjectCatalog.DEFINITIONS.folder()).resolve("trees/oak.json"), created);
assertEquals(CREATION.starter(), Files.readString(created));
try (var folder = Files.list(created.getParent())) {
assertEquals(List.of(created), folder.toList());
}
}
@Test
public void anEntryThatExistsOrHasNoPlainKeyIsNotCreated() throws Exception {
Path pack = temporary.newFolder("pack").toPath();
SceneFiles files = files(pack, file -> false);
Path created = files.create("trees/oak");
Files.writeString(created, "{}");
assertEquals("trees/oak already exists", assertThrows(IllegalArgumentException.class, () -> files.create("trees/oak")).getMessage());
assertEquals("{}", Files.readString(created));
assertThrows(IllegalArgumentException.class, () -> files.create("../escape"));
assertFalse(Files.exists(pack.resolveSibling("escape.json")));
}
@Test
public void usesAreTheJsonFilesNamingTheEntryOutsideItsOwnAndGeneratedFolders() throws Exception {
Path pack = temporary.newFolder("pack").toPath();
SceneFiles files = files(pack, file -> false);
files.create("trees/oak");
Files.createDirectories(pack.resolve("biomes/temperate"));
Files.writeString(pack.resolve("biomes/temperate/forest.json"), "{\"objects\": [\"procedural/trees/oak\"]}");
Files.writeString(pack.resolve("biomes/plains.json"), "{\"objects\": [\"procedural/trees/oak-tall\"]}");
Files.writeString(pack.resolve("biomes/notes.txt"), "procedural/trees/oak");
Files.createDirectories(pack.resolve(".iris/schema"));
Files.writeString(pack.resolve(".iris/schema/biome.json"), "{\"enum\": [\"procedural/trees/oak\"]}");
assertEquals(List.of("biomes/temperate/forest.json"), files.usesOf("trees/oak"));
}
@Test
public void aDeletedEntryGoesToThePacksTrashWhenTheDesktopHasNone() throws Exception {
Path pack = temporary.newFolder("pack").toPath();
SceneFiles files = files(pack, file -> false);
Path created = files.create("trees/oak");
assertEquals(".iris/trash", files.moveToTrash("trees/oak"));
assertFalse(Files.exists(created));
try (var trashed = Files.list(pack.resolve(".iris/trash"))) {
assertTrue(trashed.anyMatch(file -> file.getFileName().toString().startsWith("trees_oak-")));
}
}
@Test
public void aDeletedEntryTheDesktopTookIsLeftToIt() throws Exception {
Path pack = temporary.newFolder("pack").toPath();
SceneFiles files = files(pack, file -> {
try {
Files.delete(file);
} catch (java.io.IOException failed) {
throw new java.io.UncheckedIOException(failed);
}
return true;
});
Path created = files.create("trees/oak");
assertEquals("the trash", files.moveToTrash("trees/oak"));
assertFalse(Files.exists(created));
assertFalse(Files.exists(pack.resolve(".iris/trash")));
}
@Test
public void anEntryWithoutAFileCannotBeDeleted() throws Exception {
Path pack = temporary.newFolder("pack").toPath();
assertThrows(NoSuchElementException.class, () -> files(pack, file -> false).moveToTrash("trees/oak"));
}
}
@@ -31,6 +31,7 @@ import com.volmit.tooling.BlockParts;
import com.volmit.tooling.EditableSceneView;
import com.volmit.tooling.JsonText;
import com.volmit.tooling.NodeGraph;
import com.volmit.tooling.SceneCreation;
import com.volmit.tooling.SceneEntry;
import com.volmit.tooling.SceneFile;
import com.volmit.world.PackWorld;
@@ -46,6 +47,24 @@ import java.util.Optional;
public final class ProceduralObjectScenes implements EditableSceneView {
private static final ResourceId ID = ResourceId.parse("iris:objects/procedural");
private static final char FOLDER_SEPARATOR = '/';
private static final String STARTER = """
{
"materials": [
{"role": "wood", "block": "minecraft:oak_log"},
{"role": "leaves", "block": "minecraft:oak_leaves"}
],
"parts": [
{
"role": "wood",
"stem": {"length": [6, 9], "radius": 0.5},
"children": [
{"role": "leaves", "mode": "FILL", "blob": {"radius": 3}}
]
}
]
}
""";
private static final SceneCreation CREATION = new SceneCreation(ProceduralObjectCatalog.DEFINITIONS, STARTER, ProceduralObjectCatalog.KEY_PREFIX);
@Override
public ResourceId id() {
@@ -119,6 +138,11 @@ public final class ProceduralObjectScenes implements EditableSceneView {
return ProceduralObjectGraph.of(key.substring(key.lastIndexOf(FOLDER_SEPARATOR) + 1), text, read);
}
@Override
public Optional<SceneCreation> creation() {
return Optional.of(CREATION);
}
private static BakeRun runOf(BakeProfile profile) {
List<BakeRun.Stage> stages = Arrays.stream(BakeProfile.Stage.values())
.map(stage -> new BakeRun.Stage(stage.label(), profile.nanos(stage)))
@@ -160,6 +160,23 @@ export class BridgeClient {
return this.json(`scene-write?${new URLSearchParams({ view: viewId, key })}`, { method: 'POST', body: JSON.stringify({ revision, text }) })
}
/** Writes a new entry from its view's starter; it is listed once the pack has reloaded. Refused when the key can't name a new one. */
async sceneCreate(viewId: string, key: string): Promise<void> {
await this.json(`scene-create?${new URLSearchParams({ view: viewId, key })}`, { method: 'POST' })
}
/** The pack files that still name the entry, such as the biomes that place it. */
async sceneUses(viewId: string, key: string): Promise<string[]> {
const uses = await this.json<{ files: string[] }>(`scene-uses?${new URLSearchParams({ view: viewId, key })}`)
return uses.files
}
/** Moves the entry's file to the trash; says where it went. */
async sceneDelete(viewId: string, key: string): Promise<string> {
const trashed = await this.json<{ to: string }>(`scene-delete?${new URLSearchParams({ view: viewId, key })}`, { method: 'POST' })
return trashed.to
}
/** 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)}`)
+2 -1
View File
@@ -33,9 +33,10 @@ export interface SceneEntry {
variants: number
}
/** A scene view as the server lists it; `editable` when its entries can be edited as nodes, `baked` when their bake can be timed, `parts` when a block can be traced to the part that placed it. */
/** A scene view as the server lists it; `editable` when its entries can be edited as nodes, `creatable` when they can also be created and deleted, `baked` when their bake can be timed, `parts` when a block can be traced to the part that placed it. */
export interface SceneViewInfo extends ModuleViewInfo {
editable: boolean
creatable: boolean
baked: boolean
parts: boolean
}
@@ -0,0 +1,32 @@
import { describe, expect, it } from 'vitest'
import { folderPrefixOf, refusalOfNewKey } from './entryKeys'
describe('refusalOfNewKey', () => {
it('accepts a free, plain key', () => {
expect(refusalOfNewKey('trees/oak-2', ['trees/oak'])).toBeNull()
})
it('refuses a key that is taken', () => {
expect(refusalOfNewKey('trees/oak', ['trees/oak'])).toBe('trees/oak already exists')
})
it('refuses a blank name', () => {
expect(refusalOfNewKey(' ', [])).toBe('Give it a name')
})
it('refuses keys that could leave the folder or are not plain', () => {
for (const key of ['Trees/Oak', 'trees//oak', '/oak', 'oak/', '../oak', 'trees/../oak', 'oak.json', 'trees\\oak']) {
expect(refusalOfNewKey(key, []), key).toMatch(/^Use lower case/)
}
})
})
describe('folderPrefixOf', () => {
it('keeps the folders of a key with their closing slash', () => {
expect(folderPrefixOf('trees/oak/tall')).toBe('trees/oak/')
})
it('is empty for a key in no folder', () => {
expect(folderPrefixOf('oak')).toBe('')
})
})
@@ -0,0 +1,18 @@
const FOLDER_SEPARATOR = '/'
const KEY = /^[a-z0-9_-]+(\/[a-z0-9_-]+)*$/
/** Why `key` can't name a new entry beside the `existing` ones, or null when it can; the server checks the same. */
export function refusalOfNewKey(key: string, existing: readonly string[]): string | null {
if (key.trim() === '') {
return 'Give it a name'
}
if (!KEY.test(key)) {
return 'Use lower case letters, digits, - and _, with / between folders'
}
return existing.includes(key) ? `${key} already exists` : null
}
/** The folder of `key` as a start for naming a new entry in it, such as `trees/`; empty for an entry in no folder. */
export function folderPrefixOf(key: string): string {
return key.slice(0, key.lastIndexOf(FOLDER_SEPARATOR) + 1)
}
+101 -21
View File
@@ -1,9 +1,14 @@
import { Plus } from 'lucide-react'
import { useMemo, useState } from 'react'
import { Button } from '@/components/ui/button'
import { ContextMenu, ContextMenuContent, ContextMenuItem, ContextMenuTrigger } from '@/components/ui/context-menu'
import { Input } from '@/components/ui/input'
import { ScrollArea } from '@/components/ui/scroll-area'
import { cn } from '@/lib/utils'
import { folderPrefixOf } from '../editor/entryKeys'
const NUMBER = new Intl.NumberFormat('en-US')
const DELETE_KEY = 'Delete'
/** An entry of a module view: its key, the name it is listed by, and the heading it is listed under (empty for none). */
export interface BrowsableEntry {
@@ -12,23 +17,77 @@ export interface BrowsableEntry {
group: string
}
/** What the browser can do with the files of its entries, for a view whose entries are files of the pack. */
export interface EntryFileActions {
/** Asks for a new entry, offering `folderPrefix`, such as `trees/`, to name it in. */
onCreate(folderPrefix: string): void
/** Deletes the entry at `key`, once what still uses it was shown. */
onDelete(key: string): void
}
interface EntryBrowserProps {
title: string
entries: BrowsableEntry[]
current: string | null
onSelect(key: string): void
fileActions?: EntryFileActions
className?: string
}
type MenuTarget = { entry: string } | { folder: string } | null
/** A view's entries under their headings, with a search over keys, names and headings (v3e ObjectBrowser). */
export function EntryBrowser({ title, entries, current, onSelect, className }: EntryBrowserProps): React.JSX.Element {
export function EntryBrowser({ title, entries, current, onSelect, fileActions, className }: EntryBrowserProps): React.JSX.Element {
const [search, setSearch] = useState('')
const [menuTarget, setMenuTarget] = useState<MenuTarget>(null)
const wanted = search.trim().toLowerCase()
const groups = useMemo(() => groupedEntries(entries, wanted), [entries, wanted])
const list = (
<div
className="px-2 py-1.5"
onContextMenu={(event) => {
const target = menuTargetOf(event.target)
setMenuTarget(target)
if (target !== null && 'entry' in target) {
onSelect(target.entry)
}
}}
>
{groups.map(([group, members]) => (
<section key={group}>
{group !== '' && (
<h3 data-entry-folder={group} className="truncate px-2 pt-2 pb-1 text-[11px] font-semibold text-muted-foreground">
{group}
</h3>
)}
{members.map((entry) => (
<button
key={entry.key}
data-entry-key={entry.key}
title={entry.key}
onClick={() => onSelect(entry.key)}
onKeyDown={(event) => fileActions !== undefined && event.key === DELETE_KEY && fileActions.onDelete(entry.key)}
className={cn('flex h-[26px] w-full items-center rounded-md px-2 text-left', entry.key === current ? 'bg-selection' : 'hover:bg-accent')}
>
<span className="truncate">{entry.name}</span>
</button>
))}
</section>
))}
{groups.length === 0 && <p className="px-2 py-1 text-[12px] text-muted-foreground">{entries.length === 0 ? 'Nothing to show' : 'Nothing matches'}</p>}
</div>
)
return (
<section className={cn('flex min-h-0 flex-col border-b', className)}>
<section data-entry-browser className={cn('flex min-h-0 flex-col border-b', className)}>
<header className="px-4 pt-2.5 pb-2.5">
<h2 className="truncate text-[13px] font-semibold">{title}</h2>
<div className="flex items-center gap-1">
<h2 className="min-w-0 flex-1 truncate text-[13px] font-semibold">{title}</h2>
{fileActions !== undefined && (
<Button variant="ghost" size="icon-xs" title="New entry in the chosen one's folder" onClick={() => fileActions.onCreate(folderPrefixOf(current ?? ''))}>
<Plus />
</Button>
)}
</div>
<p className="truncate text-[11.5px] text-secondary-text">{NUMBER.format(entries.length)} in the pack</p>
<Input
className="mt-2 h-7 text-[12px]"
@@ -39,29 +98,50 @@ export function EntryBrowser({ title, entries, current, onSelect, className }: E
/>
</header>
<ScrollArea className="min-h-0 flex-1 border-t">
<div className="px-2 py-1.5">
{groups.map(([group, members]) => (
<section key={group}>
{group !== '' && <h3 className="truncate px-2 pt-2 pb-1 text-[11px] font-semibold text-muted-foreground">{group}</h3>}
{members.map((entry) => (
<button
key={entry.key}
title={entry.key}
onClick={() => onSelect(entry.key)}
className={cn('flex h-[26px] w-full items-center rounded-md px-2 text-left', entry.key === current ? 'bg-selection' : 'hover:bg-accent')}
>
<span className="truncate">{entry.name}</span>
</button>
))}
</section>
))}
{groups.length === 0 && <p className="px-2 py-1 text-[12px] text-muted-foreground">{entries.length === 0 ? 'Nothing to show' : 'Nothing matches'}</p>}
</div>
{fileActions === undefined ? (
list
) : (
<ContextMenu onOpenChange={(open) => !open && setMenuTarget(null)}>
<ContextMenuTrigger asChild>{list}</ContextMenuTrigger>
<EntryMenu target={menuTarget} actions={fileActions} />
</ContextMenu>
)}
</ScrollArea>
</section>
)
}
function EntryMenu({ target, actions }: { target: MenuTarget; actions: EntryFileActions }): React.JSX.Element {
if (target !== null && 'entry' in target) {
return (
<ContextMenuContent className="min-w-[180px]">
<ContextMenuItem onSelect={() => actions.onCreate(folderPrefixOf(target.entry))}>New entry beside it…</ContextMenuItem>
<ContextMenuItem variant="destructive" onSelect={() => actions.onDelete(target.entry)}>
Delete…
</ContextMenuItem>
</ContextMenuContent>
)
}
const folder = target === null ? '' : target.folder
return (
<ContextMenuContent className="min-w-[180px]">
<ContextMenuItem onSelect={() => actions.onCreate(folder === '' ? '' : `${folder}/`)}>{folder === '' ? 'New entry…' : `New entry in ${folder}…`}</ContextMenuItem>
</ContextMenuContent>
)
}
function menuTargetOf(eventTarget: EventTarget): MenuTarget {
if (!(eventTarget instanceof Element)) {
return null
}
const entry = eventTarget.closest<HTMLElement>('[data-entry-key]')?.dataset.entryKey
if (entry !== undefined) {
return { entry }
}
const folder = eventTarget.closest<HTMLElement>('[data-entry-folder]')?.dataset.entryFolder
return folder === undefined ? null : { folder }
}
function groupedEntries<Entry extends BrowsableEntry>(entries: Entry[], wanted: string): [string, Entry[]][] {
const groups = new Map<string, Entry[]>()
for (const entry of entries) {
@@ -0,0 +1,150 @@
import { useMemo, useState } from 'react'
import { Button } from '@/components/ui/button'
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog'
import { Input } from '@/components/ui/input'
import type { BridgeClient } from '../bridge/BridgeClient'
import { refusalOfNewKey } from '../editor/entryKeys'
import type { EntryFileActions } from './EntryBrowser'
const MOST_USES_LISTED = 8
type Ask = { kind: 'create'; folderPrefix: string } | { kind: 'delete'; key: string; uses: string[] }
interface EntryFiles {
actions: EntryFileActions
dialogs: React.JSX.Element | null
}
/**
* Creating and deleting a view's entries: asking for a new key, and listing what still uses an entry before it goes to
* the trash. The new entry is listed once the pack has reloaded, so `onCreated` names it to be chosen then.
*/
export function useEntryFiles(
client: BridgeClient,
viewId: string,
keys: string[],
onCreated: (key: string) => void,
tell: (message: string) => void
): EntryFiles {
const [ask, setAsk] = useState<Ask | null>(null)
const close = (): void => setAsk(null)
const actions = useMemo<EntryFileActions>(
() => ({
onCreate: (folderPrefix) => setAsk({ kind: 'create', folderPrefix }),
onDelete: (key) => {
client
.sceneUses(viewId, key)
.then((uses) => setAsk({ kind: 'delete', key, uses }))
.catch((failure: Error) => tell(failure.message))
}
}),
[client, viewId, tell]
)
const create = (key: string): void => {
close()
client
.sceneCreate(viewId, key)
.then(() => {
onCreated(key)
tell(`Created ${key}`)
})
.catch((failure: Error) => tell(failure.message))
}
const remove = (key: string): void => {
close()
client
.sceneDelete(viewId, key)
.then((to) => tell(`Moved ${key} to ${to}`))
.catch((failure: Error) => tell(failure.message))
}
const dialogs =
ask === null ? null : ask.kind === 'create' ? (
<NewEntryDialog initial={ask.folderPrefix} existing={keys} onCreate={create} onClose={close} />
) : (
<DeleteEntryDialog entryKey={ask.key} uses={ask.uses} onDelete={() => remove(ask.key)} onClose={close} />
)
return { actions, dialogs }
}
interface NewEntryDialogProps {
initial: string
existing: string[]
onCreate(key: string): void
onClose(): void
}
function NewEntryDialog({ initial, existing, onCreate, onClose }: NewEntryDialogProps): React.JSX.Element {
const [typed, setTyped] = useState(initial)
const key = typed.trim()
const refusal = refusalOfNewKey(key, existing)
return (
<Dialog open onOpenChange={(open) => !open && onClose()}>
<DialogContent className="sm:max-w-sm">
<form
className="grid gap-4"
onSubmit={(event) => {
event.preventDefault()
if (refusal === null) {
onCreate(key)
}
}}
>
<DialogHeader>
<DialogTitle className="text-[15px]">New entry</DialogTitle>
<DialogDescription>Name, with its folders, like trees/oak</DialogDescription>
</DialogHeader>
<Input autoFocus value={typed} onChange={(event) => setTyped(event.target.value)} />
<p className="h-4 text-[11.5px] text-secondary-text">{typed === initial ? '' : (refusal ?? '')}</p>
<DialogFooter>
<Button type="button" variant="ghost" onClick={onClose}>
Cancel
</Button>
<Button type="submit" disabled={refusal !== null}>
Create
</Button>
</DialogFooter>
</form>
</DialogContent>
</Dialog>
)
}
interface DeleteEntryDialogProps {
entryKey: string
uses: string[]
onDelete(): void
onClose(): void
}
// Used elsewhere, Cancel has the focus; nothing using it, moving it to the trash does.
function DeleteEntryDialog({ entryKey, uses, onDelete, onClose }: DeleteEntryDialogProps): React.JSX.Element {
const unused = uses.length === 0
return (
<Dialog open onOpenChange={(open) => !open && onClose()}>
<DialogContent className="sm:max-w-md">
<DialogHeader>
<DialogTitle className="text-[15px]">Delete {entryKey}?</DialogTitle>
<DialogDescription>{unused ? 'Nothing in the pack uses it.' : 'Still used by these files, which will warn that it is missing:'}</DialogDescription>
</DialogHeader>
{!unused && (
<ul className="flex flex-col gap-0.5 text-[12px]">
{uses.slice(0, MOST_USES_LISTED).map((file) => (
<li key={file} className="truncate">
{file}
</li>
))}
{uses.length > MOST_USES_LISTED && <li className="text-secondary-text">and {uses.length - MOST_USES_LISTED} more</li>}
</ul>
)}
<DialogFooter>
<Button variant="ghost" autoFocus={!unused} onClick={onClose}>
Cancel
</Button>
<Button variant="destructive" autoFocus={unused} onClick={onDelete}>
Move to trash
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}
+4 -1
View File
@@ -4,7 +4,7 @@ import { Button } from '@/components/ui/button'
import type { GraphNode } from '../bridge/types'
import type { NodeEditor } from '../editor/useNodeEditor'
import { NodeCanvas } from './NodeCanvas'
import { isTypingInto, nodeEditorActionFor, type NodeEditorAction } from './shortcuts'
import { isInEntryBrowser, isTypingInto, nodeEditorActionFor, type NodeEditorAction } from './shortcuts'
import { useBindings } from './useBindings'
interface NodePaneProps {
@@ -91,6 +91,9 @@ function useEditorKeys(
// Captured, so the editor's keys come before the window's own: F fits the nodes instead of following the player.
const down = (event: KeyboardEvent): void => {
const action = isTypingInto(event.target) ? null : nodeEditorActionFor(event, bindings)
if (action === 'deleteNode' && isInEntryBrowser(event.target)) {
return
}
if (action === 'dismiss') {
onSelect(null)
} else if (action === 'showAllNodes' && showAllRef.current !== null) {
+12 -1
View File
@@ -18,6 +18,7 @@ import { INTS_PER_BLOCK, type BlockScene } from '../scene/sceneDecoding'
import { buildSceneMesh, type SceneMesh } from '../scene/sceneMesh'
import { BakeMeter, useBakeTiming } from './BakeMeter'
import { EntryBrowser } from './EntryBrowser'
import { useEntryFiles } from './EntryFileDialogs'
import { NodeInspector } from './NodeInspector'
import { NodePane } from './NodePane'
import { SceneViewport, type PickedSurface } from './SceneViewport'
@@ -48,6 +49,8 @@ export function SceneStudio({ client, view, packRevision, onSummary, tell }: Sce
const [chosen, setChosen] = useState<{ key: string; variant: number } | null>(null)
const entry = entries.find((candidate) => candidate.key === chosen?.key) ?? entries[0] ?? null
const variant = entry !== null && chosen?.key === entry.key ? Math.min(chosen.variant, entry.variants - 1) : 0
const entryKeys = useMemo(() => entries.map((candidate) => candidate.key), [entries])
const files = useEntryFiles(client, view.id, entryKeys, (key) => setChosen({ key, variant: 0 }), tell)
const [farLeavesOnly, setFarLeavesOnly] = useState(false)
const chooseVariant = (next: number): void => {
if (entry !== null) {
@@ -122,7 +125,15 @@ export function SceneStudio({ client, view, packRevision, onSummary, tell }: Sce
)}
</div>
<aside className={cn('flex shrink-0 flex-col border-l bg-card', view.editable ? 'w-[300px]' : 'w-[250px]')}>
<EntryBrowser className={selected === null ? 'flex-[7]' : 'flex-[3]'} title={view.label} entries={entries} current={entry?.key ?? null} onSelect={(key) => setChosen({ key, variant: 0 })} />
<EntryBrowser
className={selected === null ? 'flex-[7]' : 'flex-[3]'}
title={view.label}
entries={entries}
current={entry?.key ?? null}
onSelect={(key) => setChosen({ key, variant: 0 })}
fileActions={view.creatable ? files.actions : undefined}
/>
{files.dialogs}
{view.baked && entry !== null && <BakeMeter timing={bakeTiming} />}
{selected !== null && editor.state !== null ? (
<NodeInspector key={JSON.stringify(selected.path)} node={selected} state={editor.state} values={values} suggestions={suggestions} onEdit={editor.edit} />
@@ -223,6 +223,11 @@ export function isTypingInto(target: EventTarget | null): boolean {
return target instanceof HTMLInputElement || target instanceof HTMLSelectElement || target instanceof HTMLTextAreaElement
}
/** Whether a key press goes to the list of a view's entries, where Delete is for the entry and not the chosen node. */
export function isInEntryBrowser(target: EventTarget | null): boolean {
return target instanceof Element && target.closest('[data-entry-browser]') !== null
}
function sharesKeys(first: ShortcutGroup, second: ShortcutGroup): boolean {
const a = GROUP_SCOPES[first]
const b = GROUP_SCOPES[second]