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

@@ -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]