diff --git a/studio/src/renderer/src/map/MapController.ts b/studio/src/renderer/src/map/MapController.ts index 417695385..9daea732f 100644 --- a/studio/src/renderer/src/map/MapController.ts +++ b/studio/src/renderer/src/map/MapController.ts @@ -30,6 +30,12 @@ export interface MapStatus { cursorZ: number } +export interface MapPlacement { + centerX: number + centerZ: number + blocksPerPixel: number +} + export interface MapListener { onStatus(status: MapStatus): void onShares(shares: Share[]): void @@ -208,6 +214,18 @@ export class MapController { this.redraw() } + /** Where the map looks and how far it is zoomed, to look there again or to show another map there. */ + placement(): MapPlacement { + return { centerX: this.view.centerX, centerZ: this.view.centerZ, blocksPerPixel: this.view.blocksPerPixel } + } + + place(placement: MapPlacement): void { + this.view.centerX = placement.centerX + this.view.centerZ = placement.centerZ + this.view.blocksPerPixel = clampBlocksPerPixel(placement.blocksPerPixel) + this.redraw() + } + worldAt(screenX: number, screenZ: number): { x: number; z: number } { return { x: screenToWorldX(this.view, screenX), z: screenToWorldZ(this.view, screenZ) } } diff --git a/studio/src/renderer/src/map/TiledView.ts b/studio/src/renderer/src/map/TiledView.ts index faedff9dc..9baa85eab 100644 --- a/studio/src/renderer/src/map/TiledView.ts +++ b/studio/src/renderer/src/map/TiledView.ts @@ -38,6 +38,12 @@ export interface TileSpot { pixelZ: number } +export interface TiledPlacement { + centerX: number + centerZ: number + blocksPerPixel: number +} + /** Where a view looks and the scale its tiles are drawn at. */ export interface TiledFraming { centerX: number @@ -118,6 +124,18 @@ export class TiledView { this.reportFrame() } + /** Where the view looks and how far it is zoomed, to look there again after the view was made anew. */ + placement(): TiledPlacement { + return { centerX: this.view.centerX, centerZ: this.view.centerZ, blocksPerPixel: this.view.blocksPerPixel } + } + + place(placement: TiledPlacement): void { + this.view.centerX = placement.centerX + this.view.centerZ = placement.centerZ + this.view.blocksPerPixel = placement.blocksPerPixel + this.redraw() + } + framing(): TiledFraming { return { centerX: this.view.centerX, centerZ: this.view.centerZ, renderScale: this.renderScale() } } diff --git a/studio/src/renderer/src/studio/EntryBrowser.tsx b/studio/src/renderer/src/studio/EntryBrowser.tsx index bf198da45..00a42a6b8 100644 --- a/studio/src/renderer/src/studio/EntryBrowser.tsx +++ b/studio/src/renderer/src/studio/EntryBrowser.tsx @@ -6,6 +6,7 @@ import { ScrollArea } from '@/components/ui/scroll-area' import { cn } from '@/lib/utils' import { folderPrefixOf } from '../editor/entryKeys' import { Glyph } from './Glyph' +import { useRememberedState } from './rememberedState' const NUMBER = new Intl.NumberFormat('en-US') const DELETE_KEY = 'Delete' @@ -34,6 +35,8 @@ interface EntryBrowserProps { entries: BrowsableEntry[] current: string | null onSelect(key: string): void + /** Opens the entry in a tab that stays, on a double click. */ + onKeep?(key: string): void fileActions?: EntryFileActions className?: string } @@ -41,16 +44,16 @@ interface EntryBrowserProps { type MenuTarget = { entry: string } | { folder: string } | null /** A view's entries in a tree of their folders, with a search over keys, names and folders that opens every folder holding a match. */ -export function EntryBrowser({ title, entries, current, onSelect, fileActions, className }: EntryBrowserProps): React.JSX.Element { - const [search, setSearch] = useState('') +export function EntryBrowser({ title, entries, current, onSelect, onKeep, fileActions, className }: EntryBrowserProps): React.JSX.Element { + const [search, setSearch] = useRememberedState(`entries:${title}:search`, '') const [menuTarget, setMenuTarget] = useState(null) - const [openFolders, setOpenFolders] = useState>(new Set()) + const [openFolders, setOpenFolders] = useRememberedState>(`entries:${title}:open`, new Set()) const wanted = search.trim().toLowerCase() const tree = useMemo(() => folderTreeOf(entries, wanted), [entries, wanted]) const currentGroup = useMemo(() => entries.find((entry) => entry.key === current)?.group ?? '', [entries, current]) useEffect(() => setOpenFolders((open) => withFolderAndAncestors(open, currentGroup)), [currentGroup]) const toggleFolder = (path: string): void => setOpenFolders((open) => toggled(open, path)) - const tier: TierContext = { current, isOpen: (path) => wanted !== '' || openFolders.has(path), onToggle: toggleFolder, onSelect, fileActions } + const tier: TierContext = { current, isOpen: (path) => wanted !== '' || openFolders.has(path), onToggle: toggleFolder, onSelect, onKeep, fileActions } const list = (
context.onSelect(entry.key)} + onDoubleClick={() => context.onKeep?.(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 === context.current ? 'bg-selection' : 'hover:bg-accent')} style={{ paddingLeft: indentOf(depth) + CHEVRON_SLOT_PX }} diff --git a/studio/src/renderer/src/studio/HelpDialog.tsx b/studio/src/renderer/src/studio/HelpDialog.tsx index 18c215bea..edd240b3f 100644 --- a/studio/src/renderer/src/studio/HelpDialog.tsx +++ b/studio/src/renderer/src/studio/HelpDialog.tsx @@ -1,7 +1,7 @@ import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog' import { Kbd } from '@/components/ui/kbd' import type { ViewInfo } from '../bridge/types' -import { MOUSE_HINTS, keyTextOf, shortcutRows, type ShortcutGroup } from './shortcuts' +import { MOUSE_HINTS, SHORTCUT_GROUPS, keyTextOf, shortcutRows } from './shortcuts' import { useBindings } from './useBindings' interface HelpDialogProps { @@ -10,14 +10,13 @@ interface HelpDialogProps { views: ViewInfo[] } -const KEY_GROUPS: ShortcutGroup[] = ['Views', 'Everywhere', 'Map', 'Node editor'] /** Every key and mouse gesture of the map, with the keys as they are set now. */ export function HelpDialog({ open, onOpenChange, views }: HelpDialogProps): React.JSX.Element { const bindings = useBindings() const rows = shortcutRows(views) const groups = [ - ...KEY_GROUPS.map((group) => ({ + ...SHORTCUT_GROUPS.map((group) => ({ title: group, rows: rows.filter((row) => row.group === group).map((row) => ({ key: keyTextOf(row.id, bindings), label: row.label })).filter((row) => row.key !== '') })), diff --git a/studio/src/renderer/src/studio/ImageMapStudio.tsx b/studio/src/renderer/src/studio/ImageMapStudio.tsx index 4294d4457..58a3c3c06 100644 --- a/studio/src/renderer/src/studio/ImageMapStudio.tsx +++ b/studio/src/renderer/src/studio/ImageMapStudio.tsx @@ -2,7 +2,8 @@ import { useEffect, useState } from 'react' import type { BridgeClient } from '../bridge/BridgeClient' import type { ImageMapDetails, SceneEntry } from '../bridge/types' import { EntryBrowser } from './EntryBrowser' -import { Panel, SidebarPanel, ViewIsland } from './Sidebar' +import { DetailPanel, SidebarPanel, ViewIsland } from './Sidebar' +import { useSettledEntry, useTab } from './tabContext' const PREVIEW_PIXELS = 1024 const NUMBER = new Intl.NumberFormat('en-US') @@ -19,8 +20,9 @@ interface ImageMapStudioProps { /** The pack's image maps: the list on the left, the chosen one painted over the world area it covers in the middle, what it is on the right. */ export function ImageMapStudio({ title, client, packRevision, onSummary, tell }: ImageMapStudioProps): React.JSX.Element { const entries = useImageMapEntries(client, packRevision, tell) - const [chosen, setChosen] = useState(null) - const entry = entries.find((candidate) => candidate.key === chosen) ?? entries[0] ?? null + const tab = useTab() + const entry = entries.find((candidate) => candidate.key === tab.entry) ?? entries[0] ?? null + useSettledEntry(tab, entry?.key ?? null, entry?.name ?? null) const { details, picture } = useImageMap(client, entry?.key ?? null, packRevision, tell) useEffect(() => onSummary(entry === null ? null : entry.key), [entry, onSummary]) @@ -35,9 +37,9 @@ export function ImageMapStudio({ title, client, packRevision, onSummary, tell }:
- + tab.choose(key)} onKeep={(key) => tab.choose(key, true)} /> - {details !== null && } + {details !== null && } ) } diff --git a/studio/src/renderer/src/studio/KeymapSettings.tsx b/studio/src/renderer/src/studio/KeymapSettings.tsx index e0190fa71..558ca66db 100644 --- a/studio/src/renderer/src/studio/KeymapSettings.tsx +++ b/studio/src/renderer/src/studio/KeymapSettings.tsx @@ -4,7 +4,7 @@ import { Input } from '@/components/ui/input' import { cn } from '@/lib/utils' import type { ViewInfo } from '../bridge/types' import { Glyph } from './Glyph' -import { chordOf, chordText, chordsOf, chordsText, clashesWith, defaultChords, shortcutRows, type Bindings, type ShortcutGroup, type ShortcutRow } from './shortcuts' +import { SHORTCUT_GROUPS, chordOf, chordText, chordsOf, chordsText, clashesWith, defaultChords, shortcutRows, type Bindings, type ShortcutRow } from './shortcuts' import { SettingGroup, SettingsPage } from './SettingsLayout' import { shortcutStore, useBindings } from './useBindings' @@ -13,7 +13,6 @@ interface Note { warning: boolean } -const GROUPS: ShortcutGroup[] = ['Views', 'Everywhere', 'Map', 'Node editor'] const RECORDING_TEXT = 'Press a key…' const NO_KEYS_TEXT = 'None' @@ -76,7 +75,7 @@ export function KeymapPage({ views }: { views: ViewInfo[] }): React.JSX.Element } > {shown.length === 0 &&

No shortcut matches

} - {GROUPS.map((group) => { + {SHORTCUT_GROUPS.map((group) => { const groupRows = shown.filter((row) => row.group === group) if (groupRows.length === 0) { return null diff --git a/studio/src/renderer/src/studio/MapCanvas.tsx b/studio/src/renderer/src/studio/MapCanvas.tsx index 99ad5228c..cb193b2e3 100644 --- a/studio/src/renderer/src/studio/MapCanvas.tsx +++ b/studio/src/renderer/src/studio/MapCanvas.tsx @@ -8,8 +8,10 @@ import { } from '@/components/ui/context-menu' import type { BridgeClient } from '../bridge/BridgeClient' import type { WorldInfo } from '../bridge/types' -import { MapController, type MapListener, type SpotSubjects } from '../map/MapController' +import { MapController, type MapListener, type MapPlacement, type SpotSubjects } from '../map/MapController' import type { Highlight } from '../map/tileStyle' +import { useRememberedRef } from './rememberedState' +import { useTab } from './tabContext' export interface CanvasPoint { x: number @@ -25,6 +27,8 @@ interface MapCanvasProps { highlight: Highlight | null onPointer(point: CanvasPoint | null): void onDragged(): void + /** Called after the mouse moved or zoomed the map. */ + onMoved(): void onTeleport(point: CanvasPoint): void onOpenFile(point: CanvasPoint): void onHighlight(subject: Highlight): void @@ -50,6 +54,8 @@ export function MapCanvas(props: MapCanvasProps): React.JSX.Element { const latest = useRef(props) latest.current = props const [contextSpot, setContextSpot] = useState(null) + // A hidden or moved tab lets go of its map; this brings it back where it looked. + const lastPlacement = useRememberedRef(`${useTab().id}:placement`, null) useEffect(() => { const canvas = canvasRef.current! @@ -59,16 +65,20 @@ export function MapCanvas(props: MapCanvasProps): React.JSX.Element { onArea: (area) => latest.current.listener.onArea(area), onError: (message) => latest.current.listener.onError(message) }) + if (lastPlacement.current !== null) { + map.place(lastPlacement.current) + } controllerRef.current = map const resize = new ResizeObserver(([entry]) => map.resize(entry.contentRect.width, entry.contentRect.height)) resize.observe(canvas) return () => { + lastPlacement.current = map.placement() resize.disconnect() map.close() controllerRef.current = null } // The controller lives as long as the connection; later view changes go through setView, not a new controller. - }, [client, world, controllerRef]) + }, [client, world, controllerRef, lastPlacement]) useMouse(canvasRef, controllerRef, latest) @@ -158,6 +168,7 @@ function useMouse( } if (press.dragged) { controllerRef.current?.panBy(event.clientX - press.lastX, event.clientY - press.lastY) + latest.current.onMoved() } press.lastX = event.clientX press.lastY = event.clientY @@ -186,6 +197,7 @@ function useMouse( event.preventDefault() const point = canvasPoint({ clientX: event.clientX, clientY: event.clientY, currentTarget: canvas }) controllerRef.current?.zoomAt(2 ** (-event.deltaY * WHEEL_ZOOM_PER_DELTA), point.x, point.y) + latest.current.onMoved() } canvas.addEventListener('pointerdown', down) diff --git a/studio/src/renderer/src/studio/MapStudio.tsx b/studio/src/renderer/src/studio/MapStudio.tsx index 6c6a0e3f3..b236aca27 100644 --- a/studio/src/renderer/src/studio/MapStudio.tsx +++ b/studio/src/renderer/src/studio/MapStudio.tsx @@ -1,42 +1,55 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react' -import type { BridgeClient, MapLayerQuery, WorldRect } from '../bridge/BridgeClient' -import type { MapHover, MapLabel, Marker, ModuleViewInfo, ServerUsage, StudioPack, ViewInfo, WorldInfo } from '../bridge/types' -import type { Share } from '../map/census' -import type { MapController, MapStatus, MapToggles } from '../map/MapController' -import type { Highlight } from '../map/tileStyle' -import { Waves } from 'lucide-react' +import type { BridgeClient, WorldRect } from '../bridge/BridgeClient' +import type { MapLabel, Marker, ModuleViewInfo, SceneViewInfo, ServerUsage, StudioPack, ViewInfo, WorldInfo } from '../bridge/types' +import type { MapStatus, MapToggles } from '../map/MapController' +import { MapLinks } from '../map/mapLinks' import { cn } from '@/lib/utils' -import { HelpDialog } from './HelpDialog' -import { HoverCard } from './HoverCard' import { Glyph } from './Glyph' -import { Legend } from './Legend' -import { MapCanvas, type CanvasPoint } from './MapCanvas' -import { PickInspector, hasPickSections } from './PickInspector' -import { RegionPreviewList } from './RegionPreviewList' +import { HelpDialog } from './HelpDialog' import { ImageMapStudio } from './ImageMapStudio' +import { MapView } from './MapView' import { NoiseStudio } from './NoiseStudio' -import { PregenStudio } from './PregenStudio' +import { PaneLayout, type WorkbenchChange } from './PaneLayout' import { PatternStudio } from './PatternStudio' +import { PregenStudio } from './PregenStudio' import { SavedWorldStudio } from './SavedWorldStudio' import { SceneStudio } from './SceneStudio' -import { WorldStudio3D } from './WorldStudio3D' -import { isTypingInto, shortcutRows, viewOfShortcutId, windowShortcutFor, type ShortcutAction } from './shortcuts' import { SettingsDialog } from './SettingsDialog' -import { Panel, SidebarPanel, SidebarSlot, ViewIsland } from './Sidebar' +import { isTypingInto, shortcutRows, viewOfShortcutId, windowShortcutFor, type ShortcutAction } from './shortcuts' +import { forgetTab } from './rememberedState' +import { DetailSlot, SidebarSlot } from './Sidebar' import { StatusBar } from './StatusBar' -import { MapTools, StudioToolbar } from './StudioToolbar' +import { StudioToolbar } from './StudioToolbar' +import { TabCommands, TabContext, type TabHandle } from './tabContext' import type { Theme } from './theme' import { useBindings } from './useBindings' -import { usePickInspection } from './usePickInspection' import { ViewList } from './ViewList' +import { WorldStudio3D } from './WorldStudio3D' +import { + activateTab, + closeTab, + focusedPane, + focusedTab, + keepTab, + openTab, + panesOf, + peekTab, + settleEntry, + showView, + stepTab, + titleTab, + workbenchWith, + type Pane, + type Tab, + type Workbench +} from './workbench' -const KEYBOARD_ZOOM_FACTOR = 2 ** 0.25 -/** The island beside the stripe meets it flush with square corners, as IntelliJ's tool windows meet theirs; the row's gap is 1.5. */ -const ISLAND_FLUSH_WITH_STRIPE = '[&>nav]:-mr-1.5 [&>nav+div:not(:empty)]:rounded-l-none [&>nav+div:empty+*]:rounded-l-none' -const ENTITY_POLL_MILLIS = 2000 +/** + * The island beside the stripe meets it flush with square corners, as IntelliJ's tool windows meet theirs, and so do + * the panes on the left edge while there is no island there; the row's gap is 1.5. + */ +const ISLAND_FLUSH_WITH_STRIPE = '[&>nav]:-mr-1.5 [&>nav+div:not(:empty)]:rounded-l-none [&:has(>nav+div:empty)_[data-left-edge]]:rounded-l-none' const NOTICE_MILLIS = 4000 -/** The views whose spots a noise picks, which the pick inspector explains. */ -const PICK_VIEWS = new Set(['biomes', 'regions']) interface MapStudioProps { client: BridgeClient @@ -52,31 +65,48 @@ export interface StudioToggles extends MapToggles { entities: boolean } -/** The map of one world: views on the left, the map in the middle, what is on screen on the right. */ +/** What a tab's view says for the status bar. */ +interface TabReport { + summary?: string | null + progress?: number | null + status?: MapStatus | null +} + +/** What every tab's view draws from: the server, the world, and what the studio knows about both. */ +interface Shared { + client: BridgeClient + world: WorldInfo + views: ViewInfo[] + sceneViews: SceneViewInfo[] + patternViews: ModuleViewInfo[] + packRevision: number + regions: MapLabel[] + players: Marker[] + detailed: boolean + links: MapLinks + lastMapArea: React.RefObject + report(tabId: string, report: TabReport): void + tell(message: string): void +} + +/** The studio of one world: the views on the left, their tabs in panes in the middle, what the focused one shows on the right. */ export function MapStudio({ client, world, theme, onOpenPack, onDisconnect }: MapStudioProps): React.JSX.Element { - const controller = useRef(null) - const [viewId, setViewId] = useState(world.views[0]?.id ?? 'biomes') - const [toggles, setToggles] = useState({ shading: true, regionBorders: false, grid: false, blocks: false, follow: false, entities: false }) - const [highlight, setHighlight] = useState(null) - const [status, setStatus] = useState(null) - const [shares, setShares] = useState([]) + const [workbench, setWorkbench] = useState(() => workbenchWith({ viewId: world.views[0]?.id ?? 'biomes', entry: null })) + const change = useCallback((next: WorkbenchChange) => setWorkbench(next), []) const [players, setPlayers] = useState([]) - const [entities, setEntities] = useState([]) const [usage, setUsage] = useState(null) - const [pointer, setPointer] = useState(null) - const [hover, setHover] = useState(null) const [detailed, setDetailed] = useState(false) const [helpOpen, setHelpOpen] = useState(false) const [settingsOpen, setSettingsOpen] = useState(false) const [notice, setNotice] = useState(null) const [connected, setConnected] = useState(true) - const [preview, setPreview] = useState(null) - const [area, setArea] = useState(null) const [packRevision, setPackRevision] = useState(0) - const [sceneSummary, setSceneSummary] = useState(null) - const [sceneProgress, setSceneProgress] = useState(null) + const [reports, setReports] = useState>({}) const [sidebarSlot, setSidebarSlot] = useState(null) + const [detailSlot, setDetailSlot] = useState(null) const [openingPack, setOpeningPack] = useState(null) + const links = useMemo(() => new MapLinks(), []) + const lastMapArea = useRef(null) const loadSceneViews = useCallback(() => client.sceneViews(), [client]) const loadPatternViews = useCallback(() => client.patternViews(), [client]) const sceneViews = useModuleViews(loadSceneViews, packRevision) @@ -85,17 +115,18 @@ export function MapStudio({ client, world, theme, onOpenPack, onDisconnect }: Ma () => [...withAppViews(world.views), ...patternViews.map(asViewInfo), ...sceneViews.map(asViewInfo)], [world.views, patternViews, sceneViews] ) - const sceneView = sceneViews.find((candidate) => candidate.id === viewId) ?? null - const patternView = patternViews.find((candidate) => candidate.id === viewId) ?? null - const showsMap = sceneView === null && patternView === null && !APP_VIEW_IDS.has(viewId) - const view = views.find((candidate) => candidate.id === viewId) ?? views[0] - const layer = useMemo(() => ({ view: viewId, preview: viewId === 'regions' ? preview : null }), [viewId, preview]) + const entryViews = useMemo(() => new Set([...ENTRY_VIEW_IDS, ...sceneViews.map((view) => view.id), ...patternViews.map((view) => view.id)]), [sceneViews, patternViews]) const regions = usePreviewableRegions(client, packRevision) - const inspectsPicks = PICK_VIEWS.has(viewId) - const inspection = usePickInspection(client, layer, area, inspectsPicks, packRevision) - const previewName = layer.preview === null ? null : (regions.find((region) => region.key === layer.preview)?.name ?? layer.preview) + const focused = focusedTab(workbench) + const viewOf = useCallback((viewId: string) => views.find((candidate) => candidate.id === viewId) ?? null, [views]) + const viewLabel = useCallback((viewId: string) => viewOf(viewId)?.label ?? viewId, [viewOf]) + const showsMapOf = useCallback((viewId: string) => !APP_VIEW_IDS.has(viewId) && !entryViews.has(viewId), [entryViews]) const tell = useCallback((message: string) => setNotice(message), []) + const report = useCallback( + (tabId: string, next: TabReport) => setReports((current) => ({ ...current, [tabId]: { ...current[tabId], ...next } })), + [] + ) const loadPacks = useCallback(() => client.packs(), [client]) const openPack = useCallback( @@ -117,239 +148,256 @@ export function MapStudio({ client, world, theme, onOpenPack, onDisconnect }: Ma return () => window.clearTimeout(timer) }, [notice]) - useEffect(() => controller.current?.setView(layer.view, layer.preview), [layer]) - useEffect(() => controller.current?.setToggles(toggles), [toggles]) - useEffect(() => controller.current?.setHighlight(highlight), [highlight]) - useEffect(() => controller.current?.setMarkers(players, toggles.entities ? entities : []), [players, entities, toggles.entities]) - - useEffect(() => { - if (toggles.follow && players.length > 0) { - controller.current?.centerOn(players[0].worldX, players[0].worldZ) - } - }, [players, toggles.follow]) - const packReloaded = useCallback(() => setPackRevision((revision) => revision + 1), []) - useServerEvents(client, controller, setPlayers, setUsage, tell, setConnected, packReloaded) - useEntities(client, toggles.entities, setEntities) - useHover(client, controller, layer, pointer, setHover) + useServerEvents(client, setPlayers, setUsage, tell, setConnected, packReloaded) - const selectView = useCallback((nextViewId: string) => { - setViewId(nextViewId) - setHighlight(null) - }, []) - - const selectPreview = useCallback((regionKey: string | null) => { - setPreview(regionKey) - setHighlight(null) - }, []) - - const toggle = useCallback((name: keyof StudioToggles) => setToggles((current) => ({ ...current, [name]: !current[name] })), []) - - const highlightUnderCursor = useCallback(() => { - if (pointer === null || controller.current === null) { - return - } - const { subject } = controller.current.subjectsAt(pointer.x, pointer.y) - setHighlight((current) => (subject === null || sameSubject(current, subject) ? null : subject)) - }, [pointer]) + const openView = useCallback((viewId: string) => setWorkbench((current) => showView(current, viewId, entryViews.has(viewId))), [entryViews]) + const commands = useCommandRegistry() + const recent = useRecentTabs(setWorkbench) const runShortcut = useCallback( (action: ShortcutAction) => { - const map = controller.current switch (action) { - case 'nextView': - selectView(views[(views.findIndex((candidate) => candidate.id === viewId) + 1) % views.length].id) - return - case 'refresh': - map?.refresh() - tell('Redrawing with the latest pack files') - return - case 'zoomIn': - map?.zoomAt(KEYBOARD_ZOOM_FACTOR) - return - case 'zoomOut': - map?.zoomAt(1 / KEYBOARD_ZOOM_FACTOR) - return - case 'resetZoom': - map?.resetZoom() - return - case 'dismiss': - setHighlight(null) - return - case 'follow': - toggle('follow') - return - case 'grid': - toggle('grid') - return - case 'entities': - toggle('entities') - return - case 'highlight': - highlightUnderCursor() - return - case 'shading': - toggle('shading') - return - case 'blocks': - toggle('blocks') - return - case 'borders': - toggle('regionBorders') + case 'nextView': { + const at = views.findIndex((candidate) => candidate.id === focused.viewId) + openView(views[(at + 1) % views.length].id) return + } case 'help': setHelpOpen((open) => !open) + return + case 'closeTab': + setWorkbench((current) => closeTab(current, focusedTab(current).id)) + return + case 'previousTab': + setWorkbench((current) => stepTab(current, -1)) + return + case 'nextTab': + setWorkbench((current) => stepTab(current, 1)) + return + case 'recentTab': + recent.step(workbench) + return + default: + commands.run(focused.id, action) } }, - [views, viewId, selectView, toggle, highlightUnderCursor, tell] + [views, focused, openView, recent, workbench, commands] ) - useKeyboard(runShortcut, selectView, setDetailed, views) + useKeyboard(runShortcut, openView, setDetailed, recent.settle, views) - const teleport = useCallback( - (point: CanvasPoint) => { - const spot = controller.current?.worldAt(point.x, point.y) - if (spot === undefined) { - return - } - client - .teleport(Math.floor(spot.x), Math.floor(spot.z)) - .then(() => tell(`Teleporting to ${Math.floor(spot.x)}, ${Math.floor(spot.z)}`)) - .catch((failure: Error) => tell(failure.message)) + const shared = useMemo( + () => ({ client, world, views, sceneViews, patternViews, packRevision, regions, players, detailed, links, lastMapArea, report, tell }), + [client, world, views, sceneViews, patternViews, packRevision, regions, players, detailed, links, report, tell] + ) + const renderTab = useCallback( + (tab: Tab, pane: Pane, shown: boolean) => { + const inFocus = shown && workbench.focusedPaneId === pane.id + return ( + + + + + + ) }, - [client, tell] + [workbench.focusedPaneId, sidebarSlot, detailSlot, change, shared] ) - const openFile = useCallback( - (point: CanvasPoint) => { - const spot = controller.current?.worldAt(point.x, point.y) - if (spot === undefined) { - return - } - client - .openInEditor(spot.x, spot.z, viewId) - .then((message) => tell(message ?? 'Opened')) - .catch((failure: Error) => tell(failure.message)) - }, - [client, viewId, tell] - ) + useForgetClosedTabs(workbench, setReports) + const focusedReport = reports[focused.id] ?? {} + const showsMap = showsMapOf(focused.viewId) + const label = focused.title ?? viewLabel(focused.viewId) return (
setHelpOpen(true)} onSettings={() => setSettingsOpen(true)} /> -
{openingPack !== null && ( -
+
Opening {openingPack.name}…
)} - - {viewId === 'regions' && regions.length > 1 && ( - - - - )} - {sceneView !== null ? ( - - ) : patternView !== null ? ( - - ) : viewId === WORLD_3D.id ? ( - - ) : viewId === SAVED_WORLD.id ? ( - - ) : viewId === PREGEN_VIEW_ID ? ( - - ) : viewId === IMAGE_MAPS_VIEW_ID ? ( - - ) : viewId === NOISE.id ? ( - - ) : ( - <> - runShortcut('refresh')} - onResetZoom={() => runShortcut('resetZoom')} - /> - } - > - setArea((current) => (sameRect(current, next) ? current : next)), onError: tell }} - onPointer={setPointer} - onDragged={() => setToggles((current) => (current.follow ? { ...current, follow: false } : current))} - onTeleport={teleport} - onOpenFile={openFile} - onHighlight={(subject) => setHighlight((current) => (sameSubject(current, subject) ? null : subject))} - highlight={highlight} - onCopy={(text) => { - window.studio.copyText(text) - tell(`Copied ${text}`) - }} - /> - {pointer !== null && hover !== null && ( - - )} - {viewId === 'rivers' && !world.hydrology && ( -
-
- -

No rivers planned

-

Enable hydrology in

-

dimensions/{world.dimension}.json

-

They appear here once the pack reloads.

-
+ {!connected && ( +
+
+

Lost the connection to the server

+
- )} - {!connected && ( -
-
-

Lost the connection to the server

- -
-
- )} - -
- {inspectsPicks && hasPickSections(inspection) && ( - - - - )} - - setHighlight((current) => (sameSubject(current, subject) ? null : subject)) }} - /> - -
- +
)} + + + showsMapOf(tab.viewId)} /> + +
- - +
) } +interface TabHostProps { + tab: Tab + shown: boolean + focused: boolean + change(change: WorkbenchChange): void + shared: Shared +} + +/** Gives a tab's view its tab: what it shows, and how it opens other entries. */ +function TabHost({ tab, shown, focused, change, shared }: TabHostProps): React.JSX.Element { + const { id, viewId } = tab + const choose = useCallback( + (entry: string, keep?: boolean) => + change((current) => { + const opened = openTab(current, { viewId, entry }, keep !== true) + return keep === true ? keepTab(opened, focusedTab(opened).id) : opened + }), + [change, viewId] + ) + const keep = useCallback(() => change((current) => keepTab(current, id)), [change, id]) + const settle = useCallback( + (entry: string | null, title: string | null) => change((current) => titleTab(entry === null ? current : settleEntry(current, id, entry), id, title)), + [change, id] + ) + const handle = useMemo( + () => ({ id, viewId, entry: tab.entry, visible: shown, focused, choose, keep, settle }), + [id, viewId, tab.entry, shown, focused, choose, keep, settle] + ) + return ( + + + + ) +} + +/** The view a tab shows. */ +function TabView({ tabId, viewId, shared }: { tabId: string; viewId: string; shared: Shared }): React.JSX.Element | null { + const { client, world, packRevision, report, tell } = shared + const onSummary = useCallback((summary: string | null) => report(tabId, { summary }), [report, tabId]) + const onProgress = useCallback((progress: number | null) => report(tabId, { progress }), [report, tabId]) + const onStatus = useCallback((status: MapStatus | null) => report(tabId, { status }), [report, tabId]) + const onArea = useCallback((area: WorldRect) => (shared.lastMapArea.current = area), [shared.lastMapArea]) + // The 3D world opens around where a map looked last, and stays there as maps move on. + const [openingArea] = useState(() => shared.lastMapArea.current) + const view = shared.views.find((candidate) => candidate.id === viewId) + const sceneView = shared.sceneViews.find((candidate) => candidate.id === viewId) + if (sceneView !== undefined) { + return + } + const patternView = shared.patternViews.find((candidate) => candidate.id === viewId) + if (patternView !== undefined) { + return + } + if (view === undefined) { + return null + } + switch (viewId) { + case WORLD_3D.id: + return + case SAVED_WORLD.id: + return + case PREGEN_VIEW_ID: + return + case IMAGE_MAPS_VIEW_ID: + return + case NOISE.id: + return + default: + return ( + + ) + } +} + +/** Drops what closed tabs left behind, so a closed tab opened again starts afresh. */ +function useForgetClosedTabs(workbench: Workbench, setReports: React.Dispatch>>): void { + const open = useRef(new Set()) + useEffect(() => { + const now = new Set(panesOf(workbench.root).flatMap((pane) => pane.tabs.map((tab) => tab.id))) + const closed = [...open.current].filter((id) => !now.has(id)) + open.current = now + if (closed.length === 0) { + return + } + closed.forEach(forgetTab) + setReports((current) => Object.fromEntries(Object.entries(current).filter(([id]) => now.has(id)))) + }, [workbench.root, setReports]) +} + +/** The keys each tab's view takes while it is the focused one, such as the map's. */ +function useCommandRegistry(): { register(tabId: string, run: (action: string) => void): () => void; run(tabId: string, action: string): void } { + const handlers = useRef(new Map void>()) + const register = useCallback((tabId: string, run: (action: string) => void) => { + handlers.current.set(tabId, run) + return () => { + if (handlers.current.get(tabId) === run) { + handlers.current.delete(tabId) + } + } + }, []) + const run = useCallback((tabId: string, action: string) => handlers.current.get(tabId)?.(action), []) + return useMemo(() => ({ register, run }), [register, run]) +} + +/** + * Ctrl+Tab steps through the tabs from the most recently used while Ctrl is held, as IntelliJ's switcher does, and + * the tab shown when Ctrl comes up counts as used. + */ +function useRecentTabs(setWorkbench: React.Dispatch>): { step(workbench: Workbench): void; settle(): void } { + const stepping = useRef<{ order: string[]; at: number } | null>(null) + const step = useCallback( + (workbench: Workbench) => { + const order = stepping.current?.order ?? workbench.used + if (order.length < 2) { + return + } + const at = ((stepping.current?.at ?? 0) + 1) % order.length + stepping.current = { order, at } + setWorkbench((current) => peekTab(current, order[at])) + }, + [setWorkbench] + ) + const settle = useCallback(() => { + if (stepping.current === null) { + return + } + stepping.current = null + setWorkbench((current) => activateTab(current, focusedPane(current).activeId)) + }, [setWorkbench]) + return useMemo(() => ({ step, settle }), [step, settle]) +} + +/** The app's views with entries to list; every module view has them too. */ +const ENTRY_VIEW_IDS = ['noise', 'imageMaps', 'savedWorld'] + const SCENE_GROUP = { group: 'BLOCKS', groupLabel: 'Blocks' } /** The app draws the 3D world from the server's biome tiles, so the server does not list it among its views. */ const WORLD_3D: ViewInfo = { @@ -386,11 +434,6 @@ function asViewInfo(view: ModuleViewInfo): ViewInfo { return { ...view, ...SCENE_GROUP } } -function statusLabel(viewLabel: string, previewName: string | null, sceneSummary: string | null): string { - const detail = sceneSummary ?? previewName - return detail === null ? viewLabel : `${viewLabel} · ${detail}` -} - /** Views the pack's modules show, read again after the pack reloads; keep {@code load} stable. */ function useModuleViews(load: () => Promise, packRevision: number): View[] { const [views, setViews] = useState([]) @@ -406,22 +449,8 @@ function useModuleViews(load: () => Promise return views } -function sameSubject(first: Highlight | null, second: Highlight | null): boolean { - return first !== null && second !== null && first.kind === second.kind && first.key === second.key -} - -function sameRect(first: WorldRect | null, second: WorldRect): boolean { - return first !== null && first.minX === second.minX && first.minZ === second.minZ && first.maxX === second.maxX && first.maxZ === second.maxZ -} - -function legendTitle(layer: MapLayerQuery): string { - if (layer.view === 'regions' && layer.preview === null) { - return 'Regions on screen' - } - if (layer.view === 'rivers') { - return 'Water on screen' - } - return 'Biomes on screen' +function statusLabel(viewLabel: string, summary: string | null): string { + return summary === null ? viewLabel : `${viewLabel} · ${summary}` } /** The regions the region view can preview, read again after the pack reloads. */ @@ -443,7 +472,6 @@ function usePreviewableRegions(client: BridgeClient, packRevision: number): MapL /** Players, usage and hotloads from the server; the first world event only says the world runs, which is known. */ function useServerEvents( client: BridgeClient, - controller: React.RefObject, setPlayers: (players: Marker[]) => void, setUsage: (usage: ServerUsage) => void, tell: (message: string) => void, @@ -461,7 +489,6 @@ function useServerEvents( return } if (running) { - controller.current?.refresh() onPackReloaded() tell('Pack reloaded, redrawing') } else { @@ -475,57 +502,14 @@ function useServerEvents( stop.signal ) return () => stop.abort() - }, [client, controller, setPlayers, setUsage, tell, setConnected, onPackReloaded]) -} - -function useEntities(client: BridgeClient, visible: boolean, setEntities: (entities: Marker[]) => void): void { - useEffect(() => { - if (!visible) { - return - } - let active = true - const refresh = (): void => { - client - .entities() - .then((found) => active && setEntities(found)) - .catch(() => undefined) - } - refresh() - const timer = window.setInterval(refresh, ENTITY_POLL_MILLIS) - return () => { - active = false - window.clearInterval(timer) - } - }, [client, visible, setEntities]) -} - -/** Asks the server about the spot under the cursor; a newer spot aborts the question about an older one. */ -function useHover( - client: BridgeClient, - controller: React.RefObject, - layer: MapLayerQuery, - pointer: CanvasPoint | null, - setHover: (hover: MapHover | null) => void -): void { - useEffect(() => { - if (pointer === null || controller.current === null) { - setHover(null) - return - } - const spot = controller.current.worldAt(pointer.x, pointer.y) - const stop = new AbortController() - client - .hover(layer, Math.floor(spot.x), Math.floor(spot.z), stop.signal) - .then(setHover) - .catch(() => undefined) - return () => stop.abort() - }, [client, controller, layer, pointer, setHover]) + }, [client, setPlayers, setUsage, tell, setConnected, onPackReloaded]) } function useKeyboard( runShortcut: (action: ShortcutAction) => void, - selectView: (view: string) => void, + openView: (view: string) => void, setDetailed: (detailed: boolean) => void, + settleRecent: () => void, views: ViewInfo[] ): void { const bindings = useBindings() @@ -547,15 +531,21 @@ function useKeyboard( if (viewId === null) { runShortcut(id as ShortcutAction) } else { - selectView(viewId) + openView(viewId) } } const up = (event: KeyboardEvent): void => { if (event.key === 'Shift') { setDetailed(false) } + if (event.key === 'Control' || event.key === 'Meta') { + settleRecent() + } + } + const blur = (): void => { + setDetailed(false) + settleRecent() } - const blur = (): void => setDetailed(false) window.addEventListener('keydown', down) window.addEventListener('keyup', up) window.addEventListener('blur', blur) @@ -564,5 +554,5 @@ function useKeyboard( window.removeEventListener('keyup', up) window.removeEventListener('blur', blur) } - }, [runShortcut, selectView, setDetailed, views, bindings]) + }, [runShortcut, openView, setDetailed, settleRecent, views, bindings]) } diff --git a/studio/src/renderer/src/studio/MapView.tsx b/studio/src/renderer/src/studio/MapView.tsx new file mode 100644 index 000000000..e58400571 --- /dev/null +++ b/studio/src/renderer/src/studio/MapView.tsx @@ -0,0 +1,334 @@ +import { useCallback, useEffect, useMemo, useRef, useState } from 'react' +import { Waves } from 'lucide-react' +import type { BridgeClient, MapLayerQuery, WorldRect } from '../bridge/BridgeClient' +import type { MapHover, MapLabel, Marker, ViewInfo, WorldInfo } from '../bridge/types' +import type { Share } from '../map/census' +import type { MapController, MapStatus } from '../map/MapController' +import type { MapLinks } from '../map/mapLinks' +import type { Highlight } from '../map/tileStyle' +import { HoverCard } from './HoverCard' +import { Legend } from './Legend' +import { MapCanvas, type CanvasPoint } from './MapCanvas' +import { PickInspector, hasPickSections } from './PickInspector' +import { RegionPreviewList } from './RegionPreviewList' +import type { StudioToggles } from './MapStudio' +import type { ShortcutAction } from './shortcuts' +import { DetailPanel, SidebarPanel, ViewIsland } from './Sidebar' +import { MapTools } from './StudioToolbar' +import { useRememberedState } from './rememberedState' +import { useSettledEntry, useTab, useTabCommands } from './tabContext' +import { usePickInspection } from './usePickInspection' + +const KEYBOARD_ZOOM_FACTOR = 2 ** 0.25 +const ENTITY_POLL_MILLIS = 2000 +/** The views whose spots a noise picks, which the pick inspector explains. */ +const PICK_VIEWS = new Set(['biomes', 'regions']) +const OPENING_TOGGLES: StudioToggles = { shading: true, regionBorders: false, grid: false, blocks: false, follow: false, entities: false } + +interface MapViewProps { + client: BridgeClient + world: WorldInfo + view: ViewInfo + packRevision: number + /** The regions the region view can preview everywhere. */ + regions: MapLabel[] + players: Marker[] + /** Whether Shift is held, for more about the spot under the cursor. */ + detailed: boolean + links: MapLinks + onStatus(status: MapStatus | null): void + /** Where the map looks, which the 3D world opens around. */ + onArea(area: WorldRect): void + tell(message: string): void +} + +/** One map tab: the map of a view in the middle, the regions it previews on the left, what is on screen on the right. */ +export function MapView({ client, world, view, packRevision, regions, players, detailed, links, onStatus, onArea, tell }: MapViewProps): React.JSX.Element { + const tab = useTab() + const controller = useRef(null) + const [toggles, setToggles] = useRememberedState(`${tab.id}:toggles`, OPENING_TOGGLES) + const [highlight, setHighlight] = useState(null) + const [shares, setShares] = useState([]) + const [entities, setEntities] = useState([]) + const [pointer, setPointer] = useState(null) + const [hover, setHover] = useState(null) + const [preview, setPreview] = useRememberedState(`${tab.id}:preview`, null) + const [area, setArea] = useState(null) + const [linked, setLinked] = useRememberedState(`${tab.id}:linked`, false) + const layer = useMemo(() => ({ view: view.id, preview: view.id === 'regions' ? preview : null }), [view.id, preview]) + const inspectsPicks = PICK_VIEWS.has(view.id) + const inspection = usePickInspection(client, layer, area, inspectsPicks, packRevision) + const previewName = layer.preview === null ? null : (regions.find((region) => region.key === layer.preview)?.name ?? layer.preview) + useSettledEntry(tab, null, previewName === null ? null : `${view.label} · ${previewName}`) + + useEffect(() => controller.current?.setView(layer.view, layer.preview), [layer]) + useEffect(() => controller.current?.setToggles(toggles), [toggles]) + useEffect(() => controller.current?.setHighlight(highlight), [highlight]) + useEffect(() => controller.current?.setMarkers(players, toggles.entities ? entities : []), [players, entities, toggles.entities]) + useEffect(() => () => onStatus(null), [onStatus]) + usePackReload(controller, packRevision) + useEntities(client, toggles.entities, setEntities) + useHover(client, controller, layer, pointer, setHover) + + useEffect(() => { + if (toggles.follow && players.length > 0) { + controller.current?.centerOn(players[0].worldX, players[0].worldZ) + } + }, [players, toggles.follow]) + + useEffect(() => { + if (!linked) { + return + } + const joined = links.join(tab.id, (placement) => controller.current?.place(placement)) + if (joined !== null) { + controller.current?.place(joined) + } else if (controller.current !== null) { + links.moved(tab.id, controller.current.placement()) + } + return () => links.leave(tab.id) + }, [linked, links, tab.id]) + + const moved = useCallback(() => { + if (controller.current !== null) { + links.moved(tab.id, controller.current.placement()) + } + }, [links, tab.id]) + + const toggle = useCallback((name: keyof StudioToggles) => setToggles((current) => ({ ...current, [name]: !current[name] })), [setToggles]) + const selectPreview = (regionKey: string | null): void => { + setPreview(regionKey) + setHighlight(null) + } + + const highlightUnderCursor = useCallback(() => { + if (pointer === null || controller.current === null) { + return + } + const { subject } = controller.current.subjectsAt(pointer.x, pointer.y) + setHighlight((current) => (subject === null || sameSubject(current, subject) ? null : subject)) + }, [pointer]) + + const run = useCallback( + (action: string) => { + const map = controller.current + switch (action as ShortcutAction) { + case 'refresh': + map?.refresh() + tell('Redrawing with the latest pack files') + return + case 'zoomIn': + map?.zoomAt(KEYBOARD_ZOOM_FACTOR) + moved() + return + case 'zoomOut': + map?.zoomAt(1 / KEYBOARD_ZOOM_FACTOR) + moved() + return + case 'resetZoom': + map?.resetZoom() + moved() + return + case 'dismiss': + setHighlight(null) + return + case 'follow': + toggle('follow') + return + case 'grid': + toggle('grid') + return + case 'entities': + toggle('entities') + return + case 'highlight': + highlightUnderCursor() + return + case 'shading': + toggle('shading') + return + case 'blocks': + toggle('blocks') + return + case 'borders': + toggle('regionBorders') + } + }, + [toggle, highlightUnderCursor, moved, tell] + ) + useTabCommands(tab, run) + + const spotAt = (point: CanvasPoint): { x: number; z: number } | null => { + const spot = controller.current?.worldAt(point.x, point.y) + return spot === undefined ? null : { x: Math.floor(spot.x), z: Math.floor(spot.z) } + } + const teleport = (point: CanvasPoint): void => { + const spot = spotAt(point) + if (spot === null) { + return + } + client + .teleport(spot.x, spot.z) + .then(() => tell(`Teleporting to ${spot.x}, ${spot.z}`)) + .catch((failure: Error) => tell(failure.message)) + } + const openFile = (point: CanvasPoint): void => { + const spot = controller.current?.worldAt(point.x, point.y) + if (spot === undefined) { + return + } + client + .openInEditor(spot.x, spot.z, view.id) + .then((message) => tell(message ?? 'Opened')) + .catch((failure: Error) => tell(failure.message)) + } + const choose = (subject: Highlight): void => setHighlight((current) => (sameSubject(current, subject) ? null : subject)) + + return ( + <> + {view.id === 'regions' && regions.length > 1 && ( + + + + )} + setLinked((current) => !current)} + onToggle={toggle} + onRefresh={() => run('refresh')} + onResetZoom={() => run('resetZoom')} + /> + } + > + { + setArea((current) => (sameRect(current, next) ? current : next)) + onArea(next) + }, + onError: tell + }} + onPointer={setPointer} + onDragged={() => setToggles((current) => (current.follow ? { ...current, follow: false } : current))} + onMoved={moved} + onTeleport={teleport} + onOpenFile={openFile} + onHighlight={choose} + highlight={highlight} + onCopy={(text) => { + window.studio.copyText(text) + tell(`Copied ${text}`) + }} + /> + {pointer !== null && hover !== null && ( + + )} + {view.id === 'rivers' && !world.hydrology && ( +
+
+ +

No rivers planned

+

Enable hydrology in

+

dimensions/{world.dimension}.json

+

They appear here once the pack reloads.

+
+
+ )} +
+ {inspectsPicks && hasPickSections(inspection) && ( + + + + )} + + + + + ) +} + +/** Draws the map again from the server when the pack reloaded, but not when a hidden tab comes back. */ +function usePackReload(controller: React.RefObject, packRevision: number): void { + const drawnFor = useRef(packRevision) + useEffect(() => { + if (drawnFor.current === packRevision) { + return + } + drawnFor.current = packRevision + controller.current?.refresh() + }, [controller, packRevision]) +} + +function sameSubject(first: Highlight | null, second: Highlight | null): boolean { + return first !== null && second !== null && first.kind === second.kind && first.key === second.key +} + +function sameRect(first: WorldRect | null, second: WorldRect): boolean { + return first !== null && first.minX === second.minX && first.minZ === second.minZ && first.maxX === second.maxX && first.maxZ === second.maxZ +} + +function legendTitle(layer: MapLayerQuery): string { + if (layer.view === 'regions' && layer.preview === null) { + return 'Regions on screen' + } + if (layer.view === 'rivers') { + return 'Water on screen' + } + return 'Biomes on screen' +} + +function useEntities(client: BridgeClient, visible: boolean, setEntities: (entities: Marker[]) => void): void { + useEffect(() => { + if (!visible) { + return + } + let active = true + const refresh = (): void => { + client + .entities() + .then((found) => active && setEntities(found)) + .catch(() => undefined) + } + refresh() + const timer = window.setInterval(refresh, ENTITY_POLL_MILLIS) + return () => { + active = false + window.clearInterval(timer) + } + }, [client, visible, setEntities]) +} + +/** Asks the server about the spot under the cursor; a newer spot aborts the question about an older one. */ +function useHover( + client: BridgeClient, + controller: React.RefObject, + layer: MapLayerQuery, + pointer: CanvasPoint | null, + setHover: (hover: MapHover | null) => void +): void { + useEffect(() => { + if (pointer === null || controller.current === null) { + setHover(null) + return + } + const spot = controller.current.worldAt(pointer.x, pointer.y) + const stop = new AbortController() + client + .hover(layer, Math.floor(spot.x), Math.floor(spot.z), stop.signal) + .then(setHover) + .catch(() => undefined) + return () => stop.abort() + }, [client, controller, layer, pointer, setHover]) +} diff --git a/studio/src/renderer/src/studio/NoiseStudio.tsx b/studio/src/renderer/src/studio/NoiseStudio.tsx index 424c1472a..268e5562d 100644 --- a/studio/src/renderer/src/studio/NoiseStudio.tsx +++ b/studio/src/renderer/src/studio/NoiseStudio.tsx @@ -16,7 +16,9 @@ import { hexColor } from './colors' import { SceneViewport } from './SceneViewport' import { TiledCanvas } from './TiledCanvas' import { Separator } from '@/components/ui/separator' -import { HEADER_CHOICE, Panel, SidebarPanel, ViewIsland } from './Sidebar' +import { DetailPanel, HEADER_CHOICE, SidebarPanel, ViewIsland } from './Sidebar' +import { useRememberedState } from './rememberedState' +import { useSettledEntry, useTab } from './tabContext' import { useLongPending, useTerrainStream } from './useTerrainStream' type NoiseDisplay = 'flat' | 'terrain' @@ -44,8 +46,9 @@ interface NoiseStudioProps { /** The pack's noise and the built-in styles, from above or as terrain. */ export function NoiseStudio({ title, client, packRevision, onSummary, tell }: NoiseStudioProps): React.JSX.Element { const sources = useNoiseSources(client, packRevision, tell) - const [chosenId, setChosenId] = useState(null) - const source = sources.find((candidate) => candidate.id === chosenId) ?? sources[0] ?? null + const tab = useTab() + const source = sources.find((candidate) => candidate.id === tab.entry) ?? sources[0] ?? null + useSettledEntry(tab, source?.id ?? null, source?.name ?? null) const [seed, setSeed] = useState(DEFAULT_SEED) const [paletteId, setPaletteId] = useState('terrain') const [display, setDisplay] = useState('flat') @@ -123,12 +126,12 @@ export function NoiseStudio({ title, client, packRevision, onSummary, tell }: No

Noise

{NUMBER.format(sources.length)} sources

- + tab.choose(id)} onKeep={(id) => tab.choose(id, true)} /> - + - + ) } @@ -225,8 +228,16 @@ function gradientOf(scale: NoiseScale): string { return `linear-gradient(to right, ${stops.join(', ')})` } -function SourceList({ sources, current, onSelect }: { sources: NoiseSource[]; current: string | null; onSelect(id: string): void }): React.JSX.Element { - const [filter, setFilter] = useState('') +interface SourceListProps { + sources: NoiseSource[] + current: string | null + onSelect(id: string): void + /** Opens the source in a tab that stays, on a double click. */ + onKeep(id: string): void +} + +function SourceList({ sources, current, onSelect, onKeep }: SourceListProps): React.JSX.Element { + const [filter, setFilter] = useRememberedState('noise:filter', '') const shown = sources.filter((source) => source.name.toLowerCase().includes(filter.trim().toLowerCase())) const categories = [...new Set(shown.map((source) => source.category))] return ( @@ -249,6 +260,7 @@ function SourceList({ sources, current, onSelect }: { sources: NoiseSource[]; cu key={source.id} title={source.id} onClick={() => onSelect(source.id)} + onDoubleClick={() => onKeep(source.id)} className={cn('flex h-[26px] w-full items-center rounded-md px-2 text-left', source.id === current ? 'bg-selection' : 'hover:bg-accent')} > {source.name} diff --git a/studio/src/renderer/src/studio/PaneLayout.tsx b/studio/src/renderer/src/studio/PaneLayout.tsx new file mode 100644 index 000000000..4ecdfb37b --- /dev/null +++ b/studio/src/renderer/src/studio/PaneLayout.tsx @@ -0,0 +1,369 @@ +import { Activity, createContext, useContext, useRef, useState } from 'react' +import { ContextMenu, ContextMenuContent, ContextMenuItem, ContextMenuSeparator, ContextMenuShortcut, ContextMenuTrigger } from '@/components/ui/context-menu' +import { cn } from '@/lib/utils' +import { Glyph } from './Glyph' +import { PaneChromeContext } from './Sidebar' +import { useKeyText } from './useBindings' +import { ViewIcon } from './ViewList' +import { + activateTab, + closeOtherTabs, + closeTab, + focusPane, + keepTab, + moveTab, + resizeSplit, + splitTab, + type Edge, + type LayoutNode, + type Pane, + type Split, + type Tab, + type Workbench +} from './workbench' + +/** A change to the panes and tabs, as the workbench functions make them. */ +export type WorkbenchChange = (workbench: Workbench) => Workbench + +interface PaneLayoutProps { + workbench: Workbench + change(change: WorkbenchChange): void + /** What a tab's view is called, for a tab its view did not name yet. */ + viewLabel(viewId: string): string + /** Draws a tab's view; called for every open tab, as a hidden tab keeps its state. */ + renderTab(tab: Tab, pane: Pane, shown: boolean): React.ReactNode + /** Whether a hidden tab's view keeps running, for a view cheap to keep that would be slow to draw again. */ + keepsRunning(tab: Tab): boolean +} + +type DropTarget = { paneId: string; edge: Edge | 'center' } + +interface Dragging { + tabId: string | null + start(tabId: string): void + end(): void +} + +const DraggingContext = createContext({ tabId: null, start: () => undefined, end: () => undefined }) +const TAB_DRAG_TYPE = 'application/x-iris-tab' +// Within this share of a pane's width or height from its edge, a dropped tab splits the pane there. +const EDGE_DROP_SHARE = 0.25 + +/** The panes and their tabs, split side by side or above each other, as IntelliJ's editor splits are. */ +export function PaneLayout({ workbench, change, viewLabel, renderTab, keepsRunning }: PaneLayoutProps): React.JSX.Element { + const [dragged, setDragged] = useState(null) + const dragging: Dragging = { tabId: dragged, start: setDragged, end: () => setDragged(null) } + const single = workbench.root.kind === 'pane' && workbench.root.tabs.length === 1 + return ( + +
+ +
+
+ ) +} + +interface BranchProps { + node: LayoutNode + atLeftEdge: boolean + workbench: Workbench + /** Whether only one tab is open in all, which then has no close button. */ + single: boolean + change(change: WorkbenchChange): void + viewLabel(viewId: string): string + renderTab(tab: Tab, pane: Pane, shown: boolean): React.ReactNode + keepsRunning(tab: Tab): boolean +} + +function LayoutBranch(props: BranchProps): React.JSX.Element { + const { node } = props + if (node.kind === 'pane') { + return + } + return +} + +function SplitView({ split, ...props }: BranchProps & { split: Split }): React.JSX.Element { + const box = useRef(null) + const row = split.direction === 'row' + const resize = (index: number, delta: number): void => { + const length = row ? box.current!.clientWidth : box.current!.clientHeight + const share = delta / Math.max(1, length) + const sizes = [...split.sizes] + sizes[index] += share + sizes[index + 1] -= share + props.change((workbench) => resizeSplit(workbench, split.id, sizes)) + } + return ( +
+ {split.children.map((child, index) => ( +
+ {index > 0 && resize(index - 1, delta)} />} +
+ +
+
+ ))} +
+ ) +} + +/** The gap between two panes, dragged to share the room between them differently. */ +function Divider({ row, onDrag }: { row: boolean; onDrag(delta: number): void }): React.JSX.Element { + const last = useRef(null) + return ( +
{ + event.currentTarget.setPointerCapture(event.pointerId) + last.current = row ? event.clientX : event.clientY + }} + onPointerMove={(event) => { + if (last.current === null) { + return + } + const at = row ? event.clientX : event.clientY + onDrag(at - last.current) + last.current = at + }} + onPointerUp={() => { + last.current = null + }} + > + +
+ ) +} + +function PaneView({ pane, atLeftEdge, workbench, single, change, viewLabel, renderTab, keepsRunning }: BranchProps & { pane: Pane }): React.JSX.Element { + const dragging = useContext(DraggingContext) + const focused = workbench.focusedPaneId === pane.id + const tabStrip = + return ( +
!focused && change((current) => focusPane(current, pane.id))} + > + {pane.tabs.map((tab) => { + const shown = tab.id === pane.activeId + // A hidden tab lets go of what it drew with, its renderer and its tiles, unless its view is cheap to keep. + return ( +
+ + {renderTab(tab, pane, shown)} + +
+ ) + })} + {dragging.tabId !== null && } +
+ ) +} + +/** Where a dragged tab lands on a pane: at an edge it splits the pane there, in the middle it joins the pane's tabs. */ +function DropZones({ pane, tabId, change, onDone }: { pane: Pane; tabId: string; change(change: WorkbenchChange): void; onDone(): void }): React.JSX.Element { + const [target, setTarget] = useState(null) + return ( +
{ + event.preventDefault() + event.dataTransfer.dropEffect = 'move' + const edge = edgeAt(event.currentTarget.getBoundingClientRect(), event.clientX, event.clientY) + setTarget((current) => (current?.edge === edge ? current : { paneId: pane.id, edge })) + }} + onDragLeave={() => setTarget(null)} + onDrop={(event) => { + event.preventDefault() + const edge = edgeAt(event.currentTarget.getBoundingClientRect(), event.clientX, event.clientY) + change((workbench) => (edge === 'center' ? moveTab(workbench, tabId, pane.id) : splitTab(workbench, tabId, pane.id, edge, false))) + setTarget(null) + onDone() + }} + > + {target !== null && } +
+ ) +} + +const DROP_AREAS: Record = { + left: 'inset-y-0 left-0 w-1/2', + right: 'inset-y-0 right-0 w-1/2', + top: 'inset-x-0 top-0 h-1/2', + bottom: 'inset-x-0 bottom-0 h-1/2', + center: 'inset-0' +} + +function edgeAt(bounds: DOMRect, clientX: number, clientY: number): Edge | 'center' { + const x = (clientX - bounds.left) / bounds.width + const y = (clientY - bounds.top) / bounds.height + const nearest = Math.min(x, 1 - x, y, 1 - y) + if (nearest > EDGE_DROP_SHARE) { + return 'center' + } + if (nearest === x) { + return 'left' + } + if (nearest === 1 - x) { + return 'right' + } + return nearest === y ? 'top' : 'bottom' +} + +interface TabStripProps { + pane: Pane + focused: boolean + single: boolean + change(change: WorkbenchChange): void + viewLabel(viewId: string): string +} + +/** A pane's tabs, in the header of the island of the one it shows. */ +function TabStrip({ pane, focused, single, change, viewLabel }: TabStripProps): React.JSX.Element { + const dragging = useContext(DraggingContext) + const [insertAt, setInsertAt] = useState(null) + const indexAt = (event: React.DragEvent): number => { + const tabs = [...event.currentTarget.querySelectorAll('[role=tab]')] + const after = tabs.findIndex((tab) => { + const bounds = tab.getBoundingClientRect() + return event.clientX < bounds.left + bounds.width / 2 + }) + return after < 0 ? tabs.length : after + } + return ( +
{ + if (dragging.tabId === null) { + return + } + event.preventDefault() + setInsertAt(indexAt(event)) + }} + onDragLeave={() => setInsertAt(null)} + onDrop={(event) => { + const tabId = event.dataTransfer.getData(TAB_DRAG_TYPE) || dragging.tabId + if (tabId === null) { + return + } + event.preventDefault() + const index = indexAt(event) + const from = pane.tabs.findIndex((tab) => tab.id === tabId) + change((workbench) => moveTab(workbench, tabId, pane.id, from >= 0 && from < index ? index - 1 : index)) + setInsertAt(null) + dragging.end() + }} + > + {pane.tabs.map((tab, index) => ( + + ))} + {insertAt === pane.tabs.length && } +
+ ) +} + +interface TabButtonProps { + tab: Tab + paneId: string + active: boolean + focused: boolean + closable: boolean + label: string + insertBefore: boolean + change(change: WorkbenchChange): void +} + +function TabButton({ tab, paneId, active, focused, closable, label, insertBefore, change }: TabButtonProps): React.JSX.Element { + const dragging = useContext(DraggingContext) + const keyText = useKeyText() + return ( + + +
{ + event.dataTransfer.setData(TAB_DRAG_TYPE, tab.id) + event.dataTransfer.effectAllowed = 'move' + dragging.start(tab.id) + }} + onDragEnd={dragging.end} + onMouseDown={(event) => { + if (event.button === 1) { + event.preventDefault() + change((workbench) => closeTab(workbench, tab.id)) + } + }} + onClick={() => change((workbench) => activateTab(workbench, tab.id))} + onDoubleClick={() => change((workbench) => keepTab(workbench, tab.id))} + className={cn( + 'group relative flex max-w-56 shrink-0 cursor-default items-center gap-1.5 pr-1 pl-3 text-[13px] select-none', + insertBefore && 'shadow-[inset_2px_0_0_var(--primary)]', + active ? 'text-foreground' : 'text-secondary-text hover:bg-accent/60 hover:text-foreground' + )} + > + + {label} + + {active && } +
+
+ + {tab.preview && change((workbench) => keepTab(workbench, tab.id))}>Keep Tab Open} + change((workbench) => closeTab(workbench, tab.id))}> + Close + {keyText('closeTab')} + + change((workbench) => closeOtherTabs(workbench, tab.id))}>Close Other Tabs + + change((workbench) => splitTab(workbench, tab.id, paneId, 'right', true))}>Split Right + change((workbench) => splitTab(workbench, tab.id, paneId, 'bottom', true))}>Split Down + change((workbench) => splitTab(workbench, tab.id, paneId, 'right', false))}>Split and Move Right + change((workbench) => splitTab(workbench, tab.id, paneId, 'bottom', false))}>Split and Move Down + +
+ ) +} diff --git a/studio/src/renderer/src/studio/PatternStudio.tsx b/studio/src/renderer/src/studio/PatternStudio.tsx index 452eb6573..b69a3347b 100644 --- a/studio/src/renderer/src/studio/PatternStudio.tsx +++ b/studio/src/renderer/src/studio/PatternStudio.tsx @@ -11,7 +11,8 @@ import { BridgeAssets } from '../scene/BridgeAssets' import { BlockIcon } from './BlockIcon' import { EntryBrowser } from './EntryBrowser' import { Glyph } from './Glyph' -import { Panel, SidebarPanel, Stepper, ViewIsland } from './Sidebar' +import { DetailPanel, SidebarPanel, Stepper, ViewIsland } from './Sidebar' +import { useSettledEntry, useTab } from './tabContext' import { TiledCanvas } from './TiledCanvas' const DEFAULT_NAMESPACE_PREFIX = 'minecraft:' @@ -39,8 +40,10 @@ interface PatternStudioProps { /** A pattern view: its entries on the right, what the chosen one places from above in the middle. */ export function PatternStudio({ client, view, packRevision, onSummary, tell }: PatternStudioProps): React.JSX.Element { const entries = usePatternEntries(client, view.id, packRevision, tell) + const tab = useTab() const [chosen, setChosen] = useState<{ key: string; depth: number } | null>(null) - const entry = entries.find((candidate) => candidate.key === chosen?.key) ?? entries[0] ?? null + const entry = entries.find((candidate) => candidate.key === tab.entry) ?? entries[0] ?? null + useSettledEntry(tab, entry?.key ?? null, entry?.name ?? null) const depth = entry !== null && chosen?.key === entry.key ? Math.min(chosen.depth, entry.depths - 1) : 0 const layer = useMemo( () => (entry === null ? null : { viewId: view.id, key: entry.key, depth, revision: packRevision }), @@ -80,12 +83,12 @@ export function PatternStudio({ client, view, packRevision, onSummary, tell }: P {status !== null && entry !== null &&
{readout(status)}
}
- setChosen({ key, depth: 0 })} /> + tab.choose(key)} onKeep={(key) => tab.choose(key, true)} /> - + - + ) } diff --git a/studio/src/renderer/src/studio/PregenStudio.tsx b/studio/src/renderer/src/studio/PregenStudio.tsx index c4d318d3e..2eb521ce7 100644 --- a/studio/src/renderer/src/studio/PregenStudio.tsx +++ b/studio/src/renderer/src/studio/PregenStudio.tsx @@ -2,7 +2,7 @@ import { useEffect, useState } from 'react' import { Button } from '@/components/ui/button' import type { BridgeClient } from '../bridge/BridgeClient' import type { PregenSnapshot } from '../bridge/types' -import { Panel, ViewIsland } from './Sidebar' +import { DetailPanel, ViewIsland } from './Sidebar' const POLL_MILLIS = 1000 const MILLIS_PER_SECOND = 1000 @@ -43,7 +43,7 @@ export function PregenStudio({ title, client, onSummary, tell }: PregenStudioPro {snapshot === null &&

No pregeneration is running. Start one with /iris pregen start.

}
- {snapshot !== null && void client.pregenPause().catch((failure: Error) => tell(failure.message))} />} + {snapshot !== null && void client.pregenPause().catch((failure: Error) => tell(failure.message))} />} ) } diff --git a/studio/src/renderer/src/studio/SavedWorldStudio.tsx b/studio/src/renderer/src/studio/SavedWorldStudio.tsx index 17b8de7ca..9c8ba28e1 100644 --- a/studio/src/renderer/src/studio/SavedWorldStudio.tsx +++ b/studio/src/renderer/src/studio/SavedWorldStudio.tsx @@ -18,6 +18,7 @@ import { Glyph } from './Glyph' import { SceneViewport } from './SceneViewport' import { Separator } from '@/components/ui/separator' import { HEADER_CHOICE, SidebarPanel, ViewIsland } from './Sidebar' +import { useSettledEntry, useTab } from './tabContext' import { useSpotActions } from './useSpotActions' import { useTerrainStream } from './useTerrainStream' @@ -40,8 +41,9 @@ interface SavedWorldStudioProps { /** A world as its region files hold it, in 3D, around the region nearest its origin. */ export function SavedWorldStudio({ title, client, world, onSummary, onProgress, tell }: SavedWorldStudioProps): React.JSX.Element { const worlds = useSavedWorlds(client, tell) - const [chosenId, setChosenId] = useState(null) - const chosen = worlds.find((candidate) => candidate.id === chosenId) ?? ownWorldAmong(worlds, world) ?? worlds[0] ?? null + const tab = useTab() + const chosen = worlds.find((candidate) => candidate.id === tab.entry) ?? ownWorldAmong(worlds, world) ?? worlds[0] ?? null + useSettledEntry(tab, chosen?.id ?? null, chosen?.name ?? null) const [coloring, setColoring] = useState('biomes') const [readings, setReadings] = useState(0) const { start, looking } = useSavedStart(client, chosen?.id ?? null, readings, tell) @@ -123,14 +125,14 @@ export function SavedWorldStudio({ title, client, world, onSummary, onProgress,

{NUMBER.format(worlds.length)} on the server

- + tab.choose(id)} onKeep={(id) => tab.choose(id, true)} /> ) } -function WorldList({ worlds, current, onSelect }: { worlds: SavedWorldInfo[]; current: string | null; onSelect(id: string): void }): React.JSX.Element { +function WorldList({ worlds, current, onSelect, onKeep }: { worlds: SavedWorldInfo[]; current: string | null; onSelect(id: string): void; onKeep(id: string): void }): React.JSX.Element { const namespaces = [...new Set(worlds.map((world) => world.namespace))] return (
@@ -144,6 +146,7 @@ function WorldList({ worlds, current, onSelect }: { worlds: SavedWorldInfo[]; cu key={world.id} title={world.id} onClick={() => onSelect(world.id)} + onDoubleClick={() => onKeep(world.id)} className={cn('flex h-[26px] w-full items-center rounded-md px-2 text-left', world.id === current ? 'bg-selection' : 'hover:bg-accent')} > {world.name} diff --git a/studio/src/renderer/src/studio/SceneStudio.tsx b/studio/src/renderer/src/studio/SceneStudio.tsx index 2a0e99ddf..e83f5c02c 100644 --- a/studio/src/renderer/src/studio/SceneStudio.tsx +++ b/studio/src/renderer/src/studio/SceneStudio.tsx @@ -21,7 +21,8 @@ import { EntryBrowser } from './EntryBrowser' import { useEntryFiles } from './EntryFileDialogs' import { NodePane } from './NodePane' import { ProfileFormPanel } from './ProfileFormPanel' -import { Panel, SidebarPanel, SizeChoice, Stepper, ViewIsland } from './Sidebar' +import { DetailPanel, SidebarPanel, SizeChoice, Stepper, ViewIsland } from './Sidebar' +import { useSettledEntry, useTab } from './tabContext' import { SceneViewport, type PickedSurface } from './SceneViewport' const NUMBER = new Intl.NumberFormat('en-US') @@ -48,11 +49,13 @@ export function SceneStudio({ client, view, packRevision, onSummary, tell }: Sce const models = useMemo(() => new BlockModels(images), [images]) const blockLooks = useMemo(() => new BlockColors(models, images), [models, images]) const entries = useSceneEntries(client, view.id, packRevision, tell) + const tab = useTab() const [chosen, setChosen] = useState<{ key: string; variant: number } | null>(null) - const entry = entries.find((candidate) => candidate.key === chosen?.key) ?? entries[0] ?? null + const entry = entries.find((candidate) => candidate.key === tab.entry) ?? entries[0] ?? null + useSettledEntry(tab, entry?.key ?? null, entry?.name ?? 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 files = useEntryFiles(client, view.id, entryKeys, (key) => tab.choose(key, true), tell) const [farLeavesOnly, setFarLeavesOnly] = useState(false) const [chosenSize, setChosenSize] = useState<{ viewId: string; size: number } | null>(null) const size = chosenSize?.viewId === view.id ? chosenSize.size : (view.sizes?.opening ?? null) @@ -64,7 +67,18 @@ export function SceneStudio({ client, view, packRevision, onSummary, tell }: Sce const bakeTiming = useBakeTiming(client, view.id, entry?.key ?? null, view.baked, packRevision, tell) - const editor = useNodeEditor(client, view.id, view.editable ? (entry?.key ?? null) : null, packRevision, tell) + const openEditor = useNodeEditor(client, view.id, view.editable ? (entry?.key ?? null) : null, packRevision, tell) + const { keep } = tab + const editor = useMemo( + () => ({ + ...openEditor, + edit: (...change: Parameters) => { + keep() + return openEditor.edit(...change) + } + }), + [openEditor, keep] + ) 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]) @@ -75,7 +89,8 @@ export function SceneStudio({ client, view, packRevision, onSummary, tell }: Sce const [typed, setTyped] = useState<{ owner: string; values: Record }>({ owner: '', values: NO_OVERRIDES }) const typedOwner = `${view.id}:${entry?.key ?? ''}` const overrides = typed.owner === typedOwner ? typed.values : NO_OVERRIDES - const changeSetting = (name: string, value: string | null): void => + const changeSetting = (name: string, value: string | null): void => { + keep() setTyped((current) => { const next = { ...(current.owner === typedOwner ? current.values : NO_OVERRIDES) } if (value === null) { @@ -85,6 +100,7 @@ export function SceneStudio({ client, view, packRevision, onSummary, tell }: Sce } return { owner: typedOwner, values: next } }) + } const profileForm = useProfileForm(client, view, entry?.key ?? null, overrides, packRevision, tell) const { scene, shown, sceneParts, building } = useSceneMesh(client, view, entry, variant, size, overrides, packRevision, models, images, farLeavesOnly, highlightedPart, tell) const shownScene = shown?.scene ?? null @@ -127,7 +143,8 @@ export function SceneStudio({ client, view, packRevision, onSummary, tell }: Sce title={view.label} entries={entries} current={entry?.key ?? null} - onSelect={(key) => setChosen({ key, variant: 0 })} + onSelect={(key) => tab.choose(key)} + onKeep={(key) => tab.choose(key, true)} fileActions={view.creatable ? files.actions : undefined} /> {files.dialogs} @@ -159,11 +176,11 @@ export function SceneStudio({ client, view, packRevision, onSummary, tell }: Sce /> )}
- + {view.form === true && setTyped({ owner: typedOwner, values: NO_OVERRIDES })} />} {view.baked && entry !== null && } - + ) } diff --git a/studio/src/renderer/src/studio/SceneViewport.tsx b/studio/src/renderer/src/studio/SceneViewport.tsx index b87c80d86..80df2a416 100644 --- a/studio/src/renderer/src/studio/SceneViewport.tsx +++ b/studio/src/renderer/src/studio/SceneViewport.tsx @@ -101,18 +101,56 @@ export function SceneViewport({ content, framing, onPick, spotActions }: SceneVi const [menuSpot, setMenuSpot] = useState(null) const latestSpotActions = useRef(spotActions) latestSpotActions.current = spotActions + // A hidden tab lets go of its renderer and its view builds what it shows again; the camera comes back where it was + // for as long as what is shown takes up the same box, until the camera is moved. + const lastPose = useRef(null) useEffect(() => { const created = new Stage(host.current!) stage.current = created return () => { + lastPose.current = created.pose() created.dispose() stage.current = null } }, []) - useEffect(() => stage.current?.show(content), [content]) - useEffect(() => stage.current?.frameShown(), [framing]) + useEffect(() => { + const current = stage.current + if (current === null) { + return + } + current.show(content) + const pose = lastPose.current + if (pose !== null && current.shows(pose.bounds)) { + current.restorePose(pose) + } + }, [content]) + useEffect(() => { + const current = stage.current + const pose = lastPose.current + if (current === null) { + return + } + if (pose !== null && current.shows(pose.bounds)) { + current.restorePose(pose) + return + } + lastPose.current = null + current.frameShown() + }, [framing]) + useEffect(() => { + const forgetPose = (): void => { + lastPose.current = null + } + const element = host.current! + element.addEventListener('pointerdown', forgetPose) + element.addEventListener('wheel', forgetPose) + return () => { + element.removeEventListener('pointerdown', forgetPose) + element.removeEventListener('wheel', forgetPose) + } + }, []) useEffect(() => stage.current?.onPick(onPick ?? null), [onPick]) const offersSpotActions = spotActions !== undefined @@ -159,6 +197,14 @@ function openMenuAt(host: HTMLElement, clientX: number, clientY: number): void { host.dispatchEvent(new MouseEvent('contextmenu', { bubbles: true, cancelable: true, clientX, clientY })) } +interface CameraPose { + position: Vector3 + target: Vector3 + framedFar: number + /** The box of what was shown, null when nothing was. */ + bounds: Box3 | null +} + /** The renderer, camera and controls of one viewport. What it shows belongs to whoever built it, who frees it. */ class Stage { private readonly renderer = new WebGLRenderer({ antialias: true, alpha: true }) @@ -273,6 +319,26 @@ class Stage { this.requestFrame() } + pose(): CameraPose { + return { position: this.camera.position.clone(), target: this.controls.target.clone(), framedFar: this.framedFar, bounds: this.shown?.bounds.clone() ?? null } + } + + /** Whether what is shown takes up {@code bounds}, or nothing is shown yet to say otherwise. */ + shows(bounds: Box3 | null): boolean { + return this.shown === null || (bounds !== null && this.shown.bounds.equals(bounds)) + } + + restorePose(pose: CameraPose): void { + this.framed = true + this.framedFar = pose.framedFar + this.camera.position.copy(pose.position) + this.controls.target.copy(pose.target) + this.controls.update() + this.fitClipToOrbit() + this.notifyMoved() + this.requestFrame() + } + onPick(listener: ((picked: PickedSurface) => void) | null): void { this.pickListener = listener } @@ -353,6 +419,8 @@ class Stage { this.resizes.disconnect() this.controls.dispose() this.renderer.dispose() + // Chromium keeps only so many WebGL contexts, so a closed tab's goes now instead of whenever it is collected. + this.renderer.forceContextLoss() this.renderer.domElement.remove() } diff --git a/studio/src/renderer/src/studio/Sidebar.tsx b/studio/src/renderer/src/studio/Sidebar.tsx index 50cce167e..f2614f6d3 100644 --- a/studio/src/renderer/src/studio/Sidebar.tsx +++ b/studio/src/renderer/src/studio/Sidebar.tsx @@ -5,9 +5,21 @@ import { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group' import { cn } from '@/lib/utils' import { Glyph } from './Glyph' -/** Where a view puts its own lists: under the views in the left island. */ +/** Where a view puts its own lists: the island beside the stripe. Null for a tab that is not the focused pane's shown one. */ export const SidebarSlot = createContext(null) +/** Where a view puts what it says about what it shows: the column on the window's right. Null as for {@link SidebarSlot}. */ +export const DetailSlot = createContext(null) + +/** What a pane gives the island of the tab it shows: its tabs, which stand in for the island's title. */ +export interface PaneChrome { + tabStrip: React.ReactNode + /** Whether the pane meets the left island or the stripe, where its corners go square. */ + atLeftEdge: boolean +} + +export const PaneChromeContext = createContext(null) + /** A section of the left island under the views, filled by the view that is shown. */ export function SidebarPanel({ className, children }: { className?: string; children: React.ReactNode }): React.JSX.Element | null { const slot = useContext(SidebarSlot) @@ -17,6 +29,15 @@ export function SidebarPanel({ className, children }: { className?: string; chil return createPortal(
{children}
, slot) } +/** A card in the column on the window's right, shown while its tab is the focused one. */ +export function DetailPanel({ className, children }: { className?: string; children: React.ReactNode }): React.JSX.Element | null { + const slot = useContext(DetailSlot) + if (slot === null) { + return null + } + return createPortal({children}, slot) +} + /** One choice of a switch in an island's header: plain until chosen and filled then. */ export const HEADER_CHOICE = 'h-6 flex-none rounded-md! border border-transparent px-2 text-[12px] font-normal hover:bg-accent hover:text-foreground data-[state=on]:bg-secondary data-[state=on]:text-foreground' @@ -77,14 +98,22 @@ interface ViewIslandProps { /** The island a view draws in, under a header with its name and its tools, as an IntelliJ tool window has. */ export function ViewIsland({ title, subtitle, tools, className, children }: ViewIslandProps): React.JSX.Element { + const pane = useContext(PaneChromeContext) return ( -
-
-

{title}

- {subtitle !== undefined && {subtitle}} - - {tools} -
+
+ {pane === null ? ( +
+

{title}

+ {subtitle !== undefined && {subtitle}} + + {tools} +
+ ) : ( +
+ {pane.tabStrip} + {tools !== undefined && {tools}} +
+ )}
{children}
) diff --git a/studio/src/renderer/src/studio/StudioToolbar.tsx b/studio/src/renderer/src/studio/StudioToolbar.tsx index 39e654f27..009e80830 100644 --- a/studio/src/renderer/src/studio/StudioToolbar.tsx +++ b/studio/src/renderer/src/studio/StudioToolbar.tsx @@ -1,5 +1,5 @@ import type { ReactNode } from 'react' -import { Blocks, Mountain, PawPrint, SquareDashed } from 'lucide-react' +import { Blocks, Link2, Mountain, PawPrint, SquareDashed } from 'lucide-react' import { Button } from '@/components/ui/button' import { Kbd } from '@/components/ui/kbd' import { Separator } from '@/components/ui/separator' @@ -14,6 +14,8 @@ import { IrisLogo } from './IrisLogo' import { PackSwitcher } from './PackSwitcher' import { badgeColour } from './packBadges' +const TOOL_TOGGLE = 'size-6 min-w-6 p-0 hover:bg-accent hover:text-foreground data-[state=on]:bg-selection data-[state=on]:text-foreground' + /** How strongly the open pack's colour tints the bar behind its name, as IntelliJ tints its toolbar with the project colour. */ const PACK_TINT_PERCENT = 28 @@ -58,13 +60,16 @@ function PackTint({ colour }: { colour: string }): React.JSX.Element { interface MapToolsProps { toggles: StudioToggles hasPlayers: boolean + /** Whether the map moves with the other linked maps. */ + linked: boolean + onLink(): void onToggle(name: keyof StudioToggles): void onRefresh(): void onResetZoom(): void } /** The map's own buttons, for the header of its island. */ -export function MapTools({ toggles, hasPlayers, onToggle, onRefresh, onResetZoom }: MapToolsProps): React.JSX.Element { +export function MapTools({ toggles, hasPlayers, linked, onLink, onToggle, onRefresh, onResetZoom }: MapToolsProps): React.JSX.Element { return ( <> onToggle('grid')}> @@ -87,6 +92,13 @@ export function MapTools({ toggles, hasPlayers, onToggle, onRefresh, onResetZoom + + + + + + + @@ -152,7 +164,7 @@ function ToolToggle({ action, hint, pressed, disabled, onPressed, children }: To pressed={pressed} disabled={disabled} onPressedChange={onPressed} - className="size-6 min-w-6 p-0 hover:bg-accent hover:text-foreground data-[state=on]:bg-selection data-[state=on]:text-foreground" + className={TOOL_TOGGLE} > {children} diff --git a/studio/src/renderer/src/studio/TiledCanvas.tsx b/studio/src/renderer/src/studio/TiledCanvas.tsx index 79a291f1f..edcef547e 100644 --- a/studio/src/renderer/src/studio/TiledCanvas.tsx +++ b/studio/src/renderer/src/studio/TiledCanvas.tsx @@ -1,5 +1,7 @@ import { useEffect, useRef } from 'react' -import type { TiledView } from '../map/TiledView' +import type { TiledPlacement, TiledView } from '../map/TiledView' +import { useRememberedRef } from './rememberedState' +import { useTab } from './tabContext' type AnyTiledView = TiledView @@ -16,21 +18,27 @@ const WHEEL_ZOOM_PER_DELTA = 0.002 /** A tiled view from above: drag to move, wheel to zoom. */ export function TiledCanvas({ create, viewRef, className }: TiledCanvasProps): React.JSX.Element { const canvasRef = useRef(null) + // A hidden or moved tab lets go of its view; this brings it back where it looked. + const lastPlacement = useRememberedRef(`${useTab().id}:placement`, null) useEffect(() => { const canvas = canvasRef.current! const view = create(canvas) + if (lastPlacement.current !== null) { + view.place(lastPlacement.current) + } viewRef.current = view const resize = new ResizeObserver(([entry]) => view.resize(entry.contentRect.width, entry.contentRect.height)) resize.observe(canvas) const stopMouse = followMouse(canvas, view) return () => { + lastPlacement.current = view.placement() stopMouse() resize.disconnect() view.close() viewRef.current = null } - }, [create, viewRef]) + }, [create, viewRef, lastPlacement]) return } diff --git a/studio/src/renderer/src/studio/ViewList.tsx b/studio/src/renderer/src/studio/ViewList.tsx index 96a2d1961..e2a9144c7 100644 --- a/studio/src/renderer/src/studio/ViewList.tsx +++ b/studio/src/renderer/src/studio/ViewList.tsx @@ -1,5 +1,5 @@ import { DropdownMenu } from 'radix-ui' -import { Fragment } from 'react' +import { useState } from 'react' import { AudioWaveform, Box, @@ -7,7 +7,9 @@ import { Droplets, Fish, Flower2, + Gauge, Gem, + Globe, HardDrive, ImageIcon, Layers, @@ -28,10 +30,8 @@ import { type LucideIcon } from 'lucide-react' import { Kbd } from '@/components/ui/kbd' -import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip' import { cn } from '@/lib/utils' import type { ViewInfo } from '../bridge/types' -import { Glyph } from './Glyph' import { viewShortcutId } from './shortcuts' import { useKeyText } from './useBindings' @@ -60,48 +60,42 @@ const VIEW_ICONS: Record = { imageMaps: ImageIcon, pregen: Zap } -const FALLBACK_ICON: LucideIcon = Shapes -/** Inset, because the stripe scrolls and so clips anything drawn outside its buttons. */ -const STRIPE_BUTTON = 'flex size-[30px] shrink-0 items-center justify-center rounded-lg outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-inset' - -/** The icon a view has in the stripe and in the list of every view. */ -function viewIcon(viewId: string): LucideIcon { - return VIEW_ICONS[viewId] ?? FALLBACK_ICON +const GROUP_ICONS: Record = { + WORLD: Globe, + BIOME_LAYERS: Layers, + DIAGNOSTICS: Gauge, + PACK: AudioWaveform, + BLOCKS: Boxes } +const FALLBACK_ICON: LucideIcon = Shapes -function ViewIcon({ viewId, className }: { viewId: string; className: string }): React.JSX.Element { - const Icon = viewIcon(viewId) +/** The icon a view has on its tabs and in its group's list. */ +export function ViewIcon({ viewId, className }: { viewId: string; className: string }): React.JSX.Element { + const Icon = VIEW_ICONS[viewId] ?? FALLBACK_ICON return } interface ViewListProps { views: ViewInfo[] + /** The view of the focused tab. */ current: string onSelect(view: string): void - /** Receives the element the shown view fills with its own lists, beside the views. */ + /** Receives the element the shown view fills with its own lists, beside the stripe. */ slotRef(element: HTMLElement | null): void } /** - * The views the server offers, as a stripe of buttons on the window's edge in their groups with a list of their names - * under them, and beside it the island the shown view fills with its own lists, which is not there for a view without - * any (IntelliJ's tool window stripe). + * The views the server offers, as one button for each of their groups on the window's edge with the group's name under + * it, each opening the list of its views; beside it the island the focused tab's view fills with its own lists, which + * is not there for a view without any (IntelliJ's tool window stripe with its names shown). */ export function ViewList({ views, current, onSelect, slotRef }: ViewListProps): React.JSX.Element { - const groups = groupsOf(views) return ( <> -