mirror of
https://github.com/VolmitSoftware/Iris.git
synced 2026-11-28 00:34:19 +00:00
Open views in tabs and split panes
- Show one stripe button per view group, with its name under it and its views in a list - Open views and entries as tabs in the island header, entries in an italic preview tab until kept - Split panes from a tab's menu or by dragging a tab to a pane's edge, and resize them by their gap - Let the side panels follow the pane last clicked - Keep hidden map tabs running and bring back a 3D tab's camera and a map's spot - Link maps to pan and zoom together - Close and step through tabs with Ctrl+F4, Alt+Left, Alt+Right and Ctrl+Tab
This commit is contained in:
1 parent
c408c01020
commit
df65c2d491
24 files changed
+1440
-460
No files matched your search
@@ -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) }
|
||||
}
|
||||
|
||||
@@ -38,6 +38,12 @@ export interface TileSpot<Tile> {
|
||||
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<Tile, Layer, Style> {
|
||||
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() }
|
||||
}
|
||||
|
||||
@@ -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<MenuTarget>(null)
|
||||
const [openFolders, setOpenFolders] = useState<ReadonlySet<string>>(new Set())
|
||||
const [openFolders, setOpenFolders] = useRememberedState<ReadonlySet<string>>(`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 = (
|
||||
<div
|
||||
className="px-2 py-1.5"
|
||||
@@ -145,6 +148,7 @@ interface TierContext {
|
||||
isOpen(path: string): boolean
|
||||
onToggle(path: string): void
|
||||
onSelect(key: string): void
|
||||
onKeep?(key: string): void
|
||||
fileActions?: EntryFileActions
|
||||
}
|
||||
|
||||
@@ -188,6 +192,7 @@ function EntryRow({ entry, depth, context }: { entry: BrowsableEntry; depth: num
|
||||
data-entry-key={entry.key}
|
||||
title={entry.key}
|
||||
onClick={() => 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 }}
|
||||
|
||||
@@ -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 !== '')
|
||||
})),
|
||||
|
||||
@@ -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<string | null>(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 }:
|
||||
</div>
|
||||
</ViewIsland>
|
||||
<SidebarPanel className="flex-1">
|
||||
<EntryBrowser className="flex-1" title={title} entries={entries} current={entry?.key ?? null} onSelect={setChosen} />
|
||||
<EntryBrowser className="flex-1" title={title} entries={entries} current={entry?.key ?? null} onSelect={(key) => tab.choose(key)} onKeep={(key) => tab.choose(key, true)} />
|
||||
</SidebarPanel>
|
||||
<Panel className="w-[250px]">{details !== null && <Facts details={details} />}</Panel>
|
||||
<DetailPanel className="w-[250px]">{details !== null && <Facts details={details} />}</DetailPanel>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -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 && <p className="text-muted-foreground">No shortcut matches</p>}
|
||||
{GROUPS.map((group) => {
|
||||
{SHORTCUT_GROUPS.map((group) => {
|
||||
const groupRows = shown.filter((row) => row.group === group)
|
||||
if (groupRows.length === 0) {
|
||||
return null
|
||||
|
||||
@@ -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<ContextSpot | null>(null)
|
||||
// A hidden or moved tab lets go of its map; this brings it back where it looked.
|
||||
const lastPlacement = useRememberedRef<MapPlacement | null>(`${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)
|
||||
|
||||
@@ -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<WorldRect | null>
|
||||
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<MapController | null>(null)
|
||||
const [viewId, setViewId] = useState(world.views[0]?.id ?? 'biomes')
|
||||
const [toggles, setToggles] = useState<StudioToggles>({ shading: true, regionBorders: false, grid: false, blocks: false, follow: false, entities: false })
|
||||
const [highlight, setHighlight] = useState<Highlight | null>(null)
|
||||
const [status, setStatus] = useState<MapStatus | null>(null)
|
||||
const [shares, setShares] = useState<Share[]>([])
|
||||
const [workbench, setWorkbench] = useState<Workbench>(() => workbenchWith({ viewId: world.views[0]?.id ?? 'biomes', entry: null }))
|
||||
const change = useCallback((next: WorkbenchChange) => setWorkbench(next), [])
|
||||
const [players, setPlayers] = useState<Marker[]>([])
|
||||
const [entities, setEntities] = useState<Marker[]>([])
|
||||
const [usage, setUsage] = useState<ServerUsage | null>(null)
|
||||
const [pointer, setPointer] = useState<CanvasPoint | null>(null)
|
||||
const [hover, setHover] = useState<MapHover | null>(null)
|
||||
const [detailed, setDetailed] = useState(false)
|
||||
const [helpOpen, setHelpOpen] = useState(false)
|
||||
const [settingsOpen, setSettingsOpen] = useState(false)
|
||||
const [notice, setNotice] = useState<string | null>(null)
|
||||
const [connected, setConnected] = useState(true)
|
||||
const [preview, setPreview] = useState<string | null>(null)
|
||||
const [area, setArea] = useState<WorldRect | null>(null)
|
||||
const [packRevision, setPackRevision] = useState(0)
|
||||
const [sceneSummary, setSceneSummary] = useState<string | null>(null)
|
||||
const [sceneProgress, setSceneProgress] = useState<number | null>(null)
|
||||
const [reports, setReports] = useState<Record<string, TabReport>>({})
|
||||
const [sidebarSlot, setSidebarSlot] = useState<HTMLElement | null>(null)
|
||||
const [detailSlot, setDetailSlot] = useState<HTMLElement | null>(null)
|
||||
const [openingPack, setOpeningPack] = useState<StudioPack | null>(null)
|
||||
const links = useMemo(() => new MapLinks(), [])
|
||||
const lastMapArea = useRef<WorldRect | null>(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<MapLayerQuery>(() => ({ 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<Shared>(
|
||||
() => ({ 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 (
|
||||
<SidebarSlot.Provider value={inFocus ? sidebarSlot : null}>
|
||||
<DetailSlot.Provider value={inFocus ? detailSlot : null}>
|
||||
<TabHost tab={tab} shown={shown} focused={inFocus} change={change} shared={shared} />
|
||||
</DetailSlot.Provider>
|
||||
</SidebarSlot.Provider>
|
||||
)
|
||||
},
|
||||
[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 (
|
||||
<div className="flex h-full flex-col">
|
||||
<StudioToolbar world={world} openingPack={openingPack} loadPacks={loadPacks} onOpenPack={openPack} onHelp={() => setHelpOpen(true)} onSettings={() => setSettingsOpen(true)} />
|
||||
<SidebarSlot.Provider value={sidebarSlot}>
|
||||
<div className={cn('relative flex min-h-0 flex-1 gap-1.5 pr-1.5', ISLAND_FLUSH_WITH_STRIPE)}>
|
||||
{openingPack !== null && (
|
||||
<div className="absolute inset-0 z-20 flex items-center justify-center bg-background/70 backdrop-motion">
|
||||
<div className="absolute inset-0 z-40 flex items-center justify-center bg-background/70 backdrop-motion">
|
||||
<div className="popup flex items-center gap-2 px-4 py-3 dialog-motion">
|
||||
<Glyph glyph="refresh" className="animate-spin" />
|
||||
Opening {openingPack.name}…
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<ViewList views={views} current={viewId} onSelect={selectView} slotRef={setSidebarSlot} />
|
||||
{viewId === 'regions' && regions.length > 1 && (
|
||||
<SidebarPanel className="flex-1 overflow-y-auto p-1.5">
|
||||
<RegionPreviewList regions={regions} current={layer.preview} onSelect={selectPreview} />
|
||||
</SidebarPanel>
|
||||
)}
|
||||
{sceneView !== null ? (
|
||||
<SceneStudio client={client} view={sceneView} packRevision={packRevision} onSummary={setSceneSummary} tell={tell} />
|
||||
) : patternView !== null ? (
|
||||
<PatternStudio client={client} view={patternView} packRevision={packRevision} onSummary={setSceneSummary} tell={tell} />
|
||||
) : viewId === WORLD_3D.id ? (
|
||||
<WorldStudio3D title={view.label} client={client} world={world} mapArea={area} packRevision={packRevision} onSummary={setSceneSummary} tell={tell} />
|
||||
) : viewId === SAVED_WORLD.id ? (
|
||||
<SavedWorldStudio title={view.label} client={client} world={world} onSummary={setSceneSummary} onProgress={setSceneProgress} tell={tell} />
|
||||
) : viewId === PREGEN_VIEW_ID ? (
|
||||
<PregenStudio title={view.label} client={client} onSummary={setSceneSummary} tell={tell} />
|
||||
) : viewId === IMAGE_MAPS_VIEW_ID ? (
|
||||
<ImageMapStudio title={view.label} client={client} packRevision={packRevision} onSummary={setSceneSummary} tell={tell} />
|
||||
) : viewId === NOISE.id ? (
|
||||
<NoiseStudio title={view.label} client={client} packRevision={packRevision} onSummary={setSceneSummary} tell={tell} />
|
||||
) : (
|
||||
<>
|
||||
<ViewIsland
|
||||
title={view.label}
|
||||
subtitle={previewName ?? undefined}
|
||||
tools={
|
||||
<MapTools
|
||||
toggles={toggles}
|
||||
hasPlayers={world.hasPlayers}
|
||||
onToggle={toggle}
|
||||
onRefresh={() => runShortcut('refresh')}
|
||||
onResetZoom={() => runShortcut('resetZoom')}
|
||||
/>
|
||||
}
|
||||
>
|
||||
<MapCanvas
|
||||
client={client}
|
||||
world={world}
|
||||
viewId={viewId}
|
||||
controllerRef={controller}
|
||||
listener={{ onStatus: setStatus, onShares: setShares, onArea: (next) => 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 && (
|
||||
<HoverCard hover={hover} point={pointer} viewId={viewId} previewing={layer.preview !== null} detailed={detailed} minY={world.minY} />
|
||||
)}
|
||||
{viewId === 'rivers' && !world.hydrology && (
|
||||
<div className="absolute inset-0 flex items-center justify-center bg-card">
|
||||
<div className="text-center">
|
||||
<Waves className="mx-auto mb-3 size-10" />
|
||||
<p className="font-medium">No rivers planned</p>
|
||||
<p className="mt-1 text-secondary-text">Enable hydrology in</p>
|
||||
<p className="font-mono text-[11.5px] text-secondary-text">dimensions/{world.dimension}.json</p>
|
||||
<p className="mt-1 text-muted-foreground">They appear here once the pack reloads.</p>
|
||||
</div>
|
||||
{!connected && (
|
||||
<div className="absolute inset-0 z-40 flex items-center justify-center bg-background/70 backdrop-motion">
|
||||
<div className="popup p-5 text-center dialog-motion">
|
||||
<p className="font-medium">Lost the connection to the server</p>
|
||||
<button className="mt-3 text-link hover:underline" onClick={onDisconnect}>
|
||||
Back to the world list
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
{!connected && (
|
||||
<div className="absolute inset-0 flex items-center justify-center bg-background/70 backdrop-motion">
|
||||
<div className="popup p-5 text-center dialog-motion">
|
||||
<p className="font-medium">Lost the connection to the server</p>
|
||||
<button className="mt-3 text-link hover:underline" onClick={onDisconnect}>
|
||||
Back to the world list
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</ViewIsland>
|
||||
<div className="flex w-[250px] shrink-0 flex-col gap-1.5">
|
||||
{inspectsPicks && hasPickSections(inspection) && (
|
||||
<Panel className="min-h-0 flex-[7]">
|
||||
<PickInspector title={previewName ?? view.label} inspection={inspection} />
|
||||
</Panel>
|
||||
)}
|
||||
<Panel className="min-h-0 flex-[3]">
|
||||
<Legend
|
||||
className="flex-1"
|
||||
title={legendTitle(layer)}
|
||||
shares={shares}
|
||||
selection={{ highlight, onSelect: (subject) => setHighlight((current) => (sameSubject(current, subject) ? null : subject)) }}
|
||||
/>
|
||||
</Panel>
|
||||
</div>
|
||||
</>
|
||||
</div>
|
||||
)}
|
||||
<ViewList views={views} current={focused.viewId} onSelect={openView} slotRef={setSidebarSlot} />
|
||||
<TabCommands.Provider value={commands.register}>
|
||||
<PaneLayout workbench={workbench} change={change} viewLabel={viewLabel} renderTab={renderTab} keepsRunning={(tab) => showsMapOf(tab.viewId)} />
|
||||
</TabCommands.Provider>
|
||||
<div ref={setDetailSlot} className="flex shrink-0 flex-col gap-1.5 empty:hidden" />
|
||||
</div>
|
||||
</SidebarSlot.Provider>
|
||||
<StatusBar viewLabel={statusLabel(view.label, previewName, showsMap ? null : sceneSummary)} status={showsMap ? status : null} notice={notice} usage={usage} progress={showsMap ? null : sceneProgress} />
|
||||
<StatusBar
|
||||
viewLabel={showsMap ? label : statusLabel(viewLabel(focused.viewId), focusedReport.summary ?? null)}
|
||||
status={showsMap ? (focusedReport.status ?? null) : null}
|
||||
notice={notice}
|
||||
usage={usage}
|
||||
progress={showsMap ? null : (focusedReport.progress ?? null)}
|
||||
/>
|
||||
<HelpDialog open={helpOpen} onOpenChange={setHelpOpen} views={views} />
|
||||
<SettingsDialog open={settingsOpen} onOpenChange={setSettingsOpen} views={views} theme={theme} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
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<TabHandle>(
|
||||
() => ({ id, viewId, entry: tab.entry, visible: shown, focused, choose, keep, settle }),
|
||||
[id, viewId, tab.entry, shown, focused, choose, keep, settle]
|
||||
)
|
||||
return (
|
||||
<TabContext.Provider value={handle}>
|
||||
<TabView tabId={id} viewId={viewId} shared={shared} />
|
||||
</TabContext.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
/** 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 <SceneStudio client={client} view={sceneView} packRevision={packRevision} onSummary={onSummary} tell={tell} />
|
||||
}
|
||||
const patternView = shared.patternViews.find((candidate) => candidate.id === viewId)
|
||||
if (patternView !== undefined) {
|
||||
return <PatternStudio client={client} view={patternView} packRevision={packRevision} onSummary={onSummary} tell={tell} />
|
||||
}
|
||||
if (view === undefined) {
|
||||
return null
|
||||
}
|
||||
switch (viewId) {
|
||||
case WORLD_3D.id:
|
||||
return <WorldStudio3D title={view.label} client={client} world={world} mapArea={openingArea} packRevision={packRevision} onSummary={onSummary} tell={tell} />
|
||||
case SAVED_WORLD.id:
|
||||
return <SavedWorldStudio title={view.label} client={client} world={world} onSummary={onSummary} onProgress={onProgress} tell={tell} />
|
||||
case PREGEN_VIEW_ID:
|
||||
return <PregenStudio title={view.label} client={client} onSummary={onSummary} tell={tell} />
|
||||
case IMAGE_MAPS_VIEW_ID:
|
||||
return <ImageMapStudio title={view.label} client={client} packRevision={packRevision} onSummary={onSummary} tell={tell} />
|
||||
case NOISE.id:
|
||||
return <NoiseStudio title={view.label} client={client} packRevision={packRevision} onSummary={onSummary} tell={tell} />
|
||||
default:
|
||||
return (
|
||||
<MapView
|
||||
client={client}
|
||||
world={world}
|
||||
view={view}
|
||||
packRevision={packRevision}
|
||||
regions={shared.regions}
|
||||
players={shared.players}
|
||||
detailed={shared.detailed}
|
||||
links={shared.links}
|
||||
onStatus={onStatus}
|
||||
onArea={onArea}
|
||||
tell={tell}
|
||||
/>
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** Drops what closed tabs left behind, so a closed tab opened again starts afresh. */
|
||||
function useForgetClosedTabs(workbench: Workbench, setReports: React.Dispatch<React.SetStateAction<Record<string, TabReport>>>): void {
|
||||
const open = useRef(new Set<string>())
|
||||
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<string, (action: string) => 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<React.SetStateAction<Workbench>>): { 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<View extends ModuleViewInfo>(load: () => Promise<View[]>, packRevision: number): View[] {
|
||||
const [views, setViews] = useState<View[]>([])
|
||||
@@ -406,22 +449,8 @@ function useModuleViews<View extends ModuleViewInfo>(load: () => Promise<View[]>
|
||||
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<MapController | null>,
|
||||
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<MapController | null>,
|
||||
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])
|
||||
}
|
||||
@@ -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<MapController | null>(null)
|
||||
const [toggles, setToggles] = useRememberedState<StudioToggles>(`${tab.id}:toggles`, OPENING_TOGGLES)
|
||||
const [highlight, setHighlight] = useState<Highlight | null>(null)
|
||||
const [shares, setShares] = useState<Share[]>([])
|
||||
const [entities, setEntities] = useState<Marker[]>([])
|
||||
const [pointer, setPointer] = useState<CanvasPoint | null>(null)
|
||||
const [hover, setHover] = useState<MapHover | null>(null)
|
||||
const [preview, setPreview] = useRememberedState<string | null>(`${tab.id}:preview`, null)
|
||||
const [area, setArea] = useState<WorldRect | null>(null)
|
||||
const [linked, setLinked] = useRememberedState(`${tab.id}:linked`, false)
|
||||
const layer = useMemo<MapLayerQuery>(() => ({ 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 && (
|
||||
<SidebarPanel className="flex-1 overflow-y-auto p-1.5">
|
||||
<RegionPreviewList regions={regions} current={layer.preview} onSelect={selectPreview} />
|
||||
</SidebarPanel>
|
||||
)}
|
||||
<ViewIsland
|
||||
title={view.label}
|
||||
subtitle={previewName ?? undefined}
|
||||
tools={
|
||||
<MapTools
|
||||
toggles={toggles}
|
||||
hasPlayers={world.hasPlayers}
|
||||
linked={linked}
|
||||
onLink={() => setLinked((current) => !current)}
|
||||
onToggle={toggle}
|
||||
onRefresh={() => run('refresh')}
|
||||
onResetZoom={() => run('resetZoom')}
|
||||
/>
|
||||
}
|
||||
>
|
||||
<MapCanvas
|
||||
client={client}
|
||||
world={world}
|
||||
viewId={view.id}
|
||||
controllerRef={controller}
|
||||
listener={{
|
||||
onStatus,
|
||||
onShares: setShares,
|
||||
onArea: (next) => {
|
||||
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 && (
|
||||
<HoverCard hover={hover} point={pointer} viewId={view.id} previewing={layer.preview !== null} detailed={detailed} minY={world.minY} />
|
||||
)}
|
||||
{view.id === 'rivers' && !world.hydrology && (
|
||||
<div className="absolute inset-0 flex items-center justify-center bg-card">
|
||||
<div className="text-center">
|
||||
<Waves className="mx-auto mb-3 size-10" />
|
||||
<p className="font-medium">No rivers planned</p>
|
||||
<p className="mt-1 text-secondary-text">Enable hydrology in</p>
|
||||
<p className="font-mono text-[11.5px] text-secondary-text">dimensions/{world.dimension}.json</p>
|
||||
<p className="mt-1 text-muted-foreground">They appear here once the pack reloads.</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</ViewIsland>
|
||||
{inspectsPicks && hasPickSections(inspection) && (
|
||||
<DetailPanel className="w-[250px] flex-[7]">
|
||||
<PickInspector title={previewName ?? view.label} inspection={inspection} />
|
||||
</DetailPanel>
|
||||
)}
|
||||
<DetailPanel className="w-[250px] flex-[3]">
|
||||
<Legend className="flex-1" title={legendTitle(layer)} shares={shares} selection={{ highlight, onSelect: choose }} />
|
||||
</DetailPanel>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
/** Draws the map again from the server when the pack reloaded, but not when a hidden tab comes back. */
|
||||
function usePackReload(controller: React.RefObject<MapController | null>, 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<MapController | null>,
|
||||
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])
|
||||
}
|
||||
@@ -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<string | null>(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<NoisePaletteId>('terrain')
|
||||
const [display, setDisplay] = useState<NoiseDisplay>('flat')
|
||||
@@ -123,12 +126,12 @@ export function NoiseStudio({ title, client, packRevision, onSummary, tell }: No
|
||||
<h2 className="text-[13px] font-semibold">Noise</h2>
|
||||
<p className="text-[11.5px] text-secondary-text">{NUMBER.format(sources.length)} sources</p>
|
||||
</header>
|
||||
<SourceList sources={sources} current={source?.id ?? null} onSelect={setChosenId} />
|
||||
<SourceList sources={sources} current={source?.id ?? null} onSelect={(id) => tab.choose(id)} onKeep={(id) => tab.choose(id, true)} />
|
||||
</SidebarPanel>
|
||||
<Panel className="w-[250px]">
|
||||
<DetailPanel className="w-[250px]">
|
||||
<SeedField seed={seed} usesSeed={source?.usesSeed ?? true} onChange={setSeed} />
|
||||
<PaletteList current={paletteId} source={source} scale={scale} onSelect={setPaletteId} />
|
||||
</Panel>
|
||||
</DetailPanel>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -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')}
|
||||
>
|
||||
<span className="truncate">{source.name}</span>
|
||||
|
||||
@@ -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<Dragging>({ 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<string | null>(null)
|
||||
const dragging: Dragging = { tabId: dragged, start: setDragged, end: () => setDragged(null) }
|
||||
const single = workbench.root.kind === 'pane' && workbench.root.tabs.length === 1
|
||||
return (
|
||||
<DraggingContext.Provider value={dragging}>
|
||||
<div className="flex min-h-0 min-w-0 flex-1">
|
||||
<LayoutBranch
|
||||
node={workbench.root}
|
||||
atLeftEdge
|
||||
workbench={workbench}
|
||||
single={single}
|
||||
change={change}
|
||||
viewLabel={viewLabel}
|
||||
renderTab={renderTab}
|
||||
keepsRunning={keepsRunning}
|
||||
/>
|
||||
</div>
|
||||
</DraggingContext.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
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 <PaneView {...props} pane={node} />
|
||||
}
|
||||
return <SplitView {...props} split={node} />
|
||||
}
|
||||
|
||||
function SplitView({ split, ...props }: BranchProps & { split: Split }): React.JSX.Element {
|
||||
const box = useRef<HTMLDivElement>(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 (
|
||||
<div ref={box} className={cn('flex min-h-0 min-w-0 flex-1', row ? 'flex-row' : 'flex-col')}>
|
||||
{split.children.map((child, index) => (
|
||||
<div key={child.id} className="contents">
|
||||
{index > 0 && <Divider row={row} onDrag={(delta) => resize(index - 1, delta)} />}
|
||||
<div className="flex min-h-0 min-w-0" style={{ flex: `${split.sizes[index]} 1 0px` }}>
|
||||
<LayoutBranch {...props} node={child} atLeftEdge={props.atLeftEdge && (!row || index === 0)} />
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** 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<number | null>(null)
|
||||
return (
|
||||
<div
|
||||
role="separator"
|
||||
aria-orientation={row ? 'vertical' : 'horizontal'}
|
||||
className={cn('group relative shrink-0', row ? 'w-1.5 cursor-col-resize' : 'h-1.5 cursor-row-resize')}
|
||||
onPointerDown={(event) => {
|
||||
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
|
||||
}}
|
||||
>
|
||||
<span className={cn('absolute rounded-full bg-primary opacity-0 transition-opacity group-hover:opacity-60', row ? 'inset-y-2 left-0.5 w-0.5' : 'inset-x-2 top-0.5 h-0.5')} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
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 = <TabStrip pane={pane} focused={focused} single={single} change={change} viewLabel={viewLabel} />
|
||||
return (
|
||||
<div
|
||||
data-pane={pane.id}
|
||||
data-focused={focused || undefined}
|
||||
className="relative flex min-h-0 min-w-0 flex-1"
|
||||
onPointerDownCapture={() => !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 (
|
||||
<div key={`${tab.id}:${tab.viewId}`} className={cn('flex min-h-0 min-w-0 flex-1', !shown && 'hidden')}>
|
||||
<Activity mode={shown || keepsRunning(tab) ? 'visible' : 'hidden'}>
|
||||
<PaneChromeContext.Provider value={shown ? { tabStrip, atLeftEdge } : null}>{renderTab(tab, pane, shown)}</PaneChromeContext.Provider>
|
||||
</Activity>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
{dragging.tabId !== null && <DropZones pane={pane} tabId={dragging.tabId} change={change} onDone={dragging.end} />}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** 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<DropTarget | null>(null)
|
||||
return (
|
||||
<div
|
||||
className="absolute inset-x-0 top-10 bottom-0 z-30"
|
||||
onDragOver={(event) => {
|
||||
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 && <span className={cn('pointer-events-none absolute rounded-[10px] border-2 border-primary bg-primary/15', DROP_AREAS[target.edge])} />}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const DROP_AREAS: Record<Edge | 'center', string> = {
|
||||
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<number | null>(null)
|
||||
const indexAt = (event: React.DragEvent): number => {
|
||||
const tabs = [...event.currentTarget.querySelectorAll<HTMLElement>('[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 (
|
||||
<div
|
||||
role="tablist"
|
||||
aria-label="Tabs"
|
||||
className="relative flex min-w-0 flex-1 items-stretch overflow-x-auto [scrollbar-width:none]"
|
||||
onDragOver={(event) => {
|
||||
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) => (
|
||||
<TabButton
|
||||
key={tab.id}
|
||||
tab={tab}
|
||||
active={tab.id === pane.activeId}
|
||||
focused={focused}
|
||||
closable={!single}
|
||||
label={tab.title ?? viewLabel(tab.viewId)}
|
||||
insertBefore={insertAt === index}
|
||||
change={change}
|
||||
paneId={pane.id}
|
||||
/>
|
||||
))}
|
||||
{insertAt === pane.tabs.length && <span className="w-0.5 shrink-0 self-stretch bg-primary" />}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
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 (
|
||||
<ContextMenu>
|
||||
<ContextMenuTrigger asChild>
|
||||
<div
|
||||
role="tab"
|
||||
aria-selected={active}
|
||||
data-tab={tab.id}
|
||||
data-preview={tab.preview || undefined}
|
||||
title={label}
|
||||
draggable
|
||||
onDragStart={(event) => {
|
||||
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'
|
||||
)}
|
||||
>
|
||||
<ViewIcon viewId={tab.viewId} className="size-3.5 shrink-0" />
|
||||
<span className={cn('truncate', tab.preview && 'italic')}>{label}</span>
|
||||
<button
|
||||
aria-label={`Close ${label}`}
|
||||
tabIndex={-1}
|
||||
onClick={(event) => {
|
||||
event.stopPropagation()
|
||||
change((workbench) => closeTab(workbench, tab.id))
|
||||
}}
|
||||
className={cn(
|
||||
'flex size-5 shrink-0 items-center justify-center rounded-sm hover:bg-accent',
|
||||
!closable && 'invisible',
|
||||
closable && !active && 'opacity-0 group-hover:opacity-100'
|
||||
)}
|
||||
>
|
||||
<Glyph glyph="close" small />
|
||||
</button>
|
||||
{active && <span className={cn('absolute inset-x-2 bottom-0 h-0.5 rounded-full', focused ? 'bg-primary' : 'bg-muted-foreground/50')} />}
|
||||
</div>
|
||||
</ContextMenuTrigger>
|
||||
<ContextMenuContent className="min-w-56">
|
||||
{tab.preview && <ContextMenuItem onSelect={() => change((workbench) => keepTab(workbench, tab.id))}>Keep Tab Open</ContextMenuItem>}
|
||||
<ContextMenuItem disabled={!closable} onSelect={() => change((workbench) => closeTab(workbench, tab.id))}>
|
||||
Close
|
||||
<ContextMenuShortcut>{keyText('closeTab')}</ContextMenuShortcut>
|
||||
</ContextMenuItem>
|
||||
<ContextMenuItem onSelect={() => change((workbench) => closeOtherTabs(workbench, tab.id))}>Close Other Tabs</ContextMenuItem>
|
||||
<ContextMenuSeparator />
|
||||
<ContextMenuItem onSelect={() => change((workbench) => splitTab(workbench, tab.id, paneId, 'right', true))}>Split Right</ContextMenuItem>
|
||||
<ContextMenuItem onSelect={() => change((workbench) => splitTab(workbench, tab.id, paneId, 'bottom', true))}>Split Down</ContextMenuItem>
|
||||
<ContextMenuItem onSelect={() => change((workbench) => splitTab(workbench, tab.id, paneId, 'right', false))}>Split and Move Right</ContextMenuItem>
|
||||
<ContextMenuItem onSelect={() => change((workbench) => splitTab(workbench, tab.id, paneId, 'bottom', false))}>Split and Move Down</ContextMenuItem>
|
||||
</ContextMenuContent>
|
||||
</ContextMenu>
|
||||
)
|
||||
}
|
||||
@@ -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<PatternLayer | null>(
|
||||
() => (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 && <div className={cn(PILL, 'right-3 bottom-3 tabular-nums')}>{readout(status)}</div>}
|
||||
</ViewIsland>
|
||||
<SidebarPanel className="flex-1">
|
||||
<EntryBrowser className="flex-1" title={view.label} entries={entries} current={entry?.key ?? null} onSelect={(key) => setChosen({ key, depth: 0 })} />
|
||||
<EntryBrowser className="flex-1" title={view.label} entries={entries} current={entry?.key ?? null} onSelect={(key) => tab.choose(key)} onKeep={(key) => tab.choose(key, true)} />
|
||||
</SidebarPanel>
|
||||
<Panel className="w-[250px]">
|
||||
<DetailPanel className="w-[250px]">
|
||||
<EntryFacts entry={entry} />
|
||||
<Legend blocks={legend} looks={blockColors} />
|
||||
</Panel>
|
||||
</DetailPanel>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -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 && <p className="text-[12px] text-secondary-text">No pregeneration is running. Start one with /iris pregen start.</p>}
|
||||
</div>
|
||||
</ViewIsland>
|
||||
<Panel className="w-[250px]">{snapshot !== null && <Progress snapshot={snapshot} onPause={() => void client.pregenPause().catch((failure: Error) => tell(failure.message))} />}</Panel>
|
||||
<DetailPanel className="w-[250px]">{snapshot !== null && <Progress snapshot={snapshot} onPause={() => void client.pregenPause().catch((failure: Error) => tell(failure.message))} />}</DetailPanel>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -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<string | null>(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<SavedTerrainColoring>('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,
|
||||
<p className="text-[11.5px] text-secondary-text">{NUMBER.format(worlds.length)} on the server</p>
|
||||
</header>
|
||||
<ScrollArea className="min-h-0 flex-1 border-t">
|
||||
<WorldList worlds={worlds} current={chosen?.id ?? null} onSelect={setChosenId} />
|
||||
<WorldList worlds={worlds} current={chosen?.id ?? null} onSelect={(id) => tab.choose(id)} onKeep={(id) => tab.choose(id, true)} />
|
||||
</ScrollArea>
|
||||
</SidebarPanel>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
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 (
|
||||
<div className="px-2 py-1.5">
|
||||
@@ -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')}
|
||||
>
|
||||
<span className="truncate">{world.name}</span>
|
||||
|
||||
@@ -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<typeof openEditor.edit>) => {
|
||||
keep()
|
||||
return openEditor.edit(...change)
|
||||
}
|
||||
}),
|
||||
[openEditor, keep]
|
||||
)
|
||||
const [selectedPath, setSelectedPath] = useState<JsonPath | null>(null)
|
||||
const selected = editor.state?.roots != null && selectedPath !== null ? nodeWithPath(editor.state.roots, selectedPath) : null
|
||||
const values = useMemo(() => (editor.state === null ? undefined : parsedText(editor.state.text)), [editor.state])
|
||||
@@ -75,7 +89,8 @@ export function SceneStudio({ client, view, packRevision, onSummary, tell }: Sce
|
||||
const [typed, setTyped] = useState<{ owner: string; values: Record<string, string> }>({ 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
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
<Panel className={view.form ? 'w-[300px]' : 'w-[250px]'}>
|
||||
<DetailPanel className={view.form ? 'w-[300px]' : 'w-[250px]'}>
|
||||
{view.form === true && <ProfileFormPanel className="flex-[5]" state={profileForm} onChange={changeSetting} onResetAll={() => setTyped({ owner: typedOwner, values: NO_OVERRIDES })} />}
|
||||
{view.baked && entry !== null && <BakeMeter timing={bakeTiming} />}
|
||||
<BlockList scene={scene} blocks={blockLooks} farLeavesOnly={farLeavesOnly} onFarLeavesOnly={setFarLeavesOnly} />
|
||||
</Panel>
|
||||
</DetailPanel>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -101,18 +101,56 @@ export function SceneViewport({ content, framing, onPick, spotActions }: SceneVi
|
||||
const [menuSpot, setMenuSpot] = useState<Vector3 | null>(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<CameraPose | null>(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()
|
||||
}
|
||||
|
||||
|
||||
@@ -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<HTMLElement | null>(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<HTMLElement | null>(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<PaneChrome | null>(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(<section className={cn('flex min-h-0 flex-col overflow-hidden', className)}>{children}</section>, 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(<Panel className={cn('min-h-0 flex-1', className)}>{children}</Panel>, 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 (
|
||||
<section className={cn('flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden rounded-[10px] bg-card', className)}>
|
||||
<header className="flex h-10 shrink-0 items-center gap-1 pr-1.5 pl-3">
|
||||
<h2 className="shrink-0 text-[13px] font-semibold">{title}</h2>
|
||||
{subtitle !== undefined && <span className="ml-1 truncate text-[12px] text-secondary-text">{subtitle}</span>}
|
||||
<span className="flex-1" />
|
||||
{tools}
|
||||
</header>
|
||||
<section data-left-edge={pane?.atLeftEdge || undefined} className={cn('flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden rounded-[10px] bg-card', className)}>
|
||||
{pane === null ? (
|
||||
<header className="flex h-10 shrink-0 items-center gap-1 pr-1.5 pl-3">
|
||||
<h2 className="shrink-0 text-[13px] font-semibold">{title}</h2>
|
||||
{subtitle !== undefined && <span className="ml-1 truncate text-[12px] text-secondary-text">{subtitle}</span>}
|
||||
<span className="flex-1" />
|
||||
{tools}
|
||||
</header>
|
||||
) : (
|
||||
<header className="flex h-10 shrink-0 items-stretch gap-1 border-b pr-1.5">
|
||||
{pane.tabStrip}
|
||||
{tools !== undefined && <span className="flex shrink-0 items-center gap-1">{tools}</span>}
|
||||
</header>
|
||||
)}
|
||||
<div className="relative min-h-0 flex-1 overflow-hidden">{children}</div>
|
||||
</section>
|
||||
)
|
||||
|
||||
@@ -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 (
|
||||
<>
|
||||
<ToolToggle action="grid" hint="Show chunk and region borders" pressed={toggles.grid} onPressed={() => onToggle('grid')}>
|
||||
@@ -87,6 +92,13 @@ export function MapTools({ toggles, hasPlayers, onToggle, onRefresh, onResetZoom
|
||||
<Glyph glyph="locate" />
|
||||
</ToolToggle>
|
||||
<Separator orientation="vertical" className="mx-1 h-4!" />
|
||||
<IconHint hint="Move and zoom with the other linked maps">
|
||||
<span>
|
||||
<Toggle size="sm" aria-label="Link pan and zoom" pressed={linked} onPressedChange={onLink} className={TOOL_TOGGLE}>
|
||||
<Link2 />
|
||||
</Toggle>
|
||||
</span>
|
||||
</IconHint>
|
||||
<ToolButton action="resetZoom" hint="Go back to the default zoom" onClick={onResetZoom}>
|
||||
<Glyph glyph="actualZoom" />
|
||||
</ToolButton>
|
||||
@@ -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}
|
||||
</Toggle>
|
||||
|
||||
@@ -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<unknown, unknown, unknown>
|
||||
|
||||
@@ -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<View extends AnyTiledView>({ create, viewRef, className }: TiledCanvasProps<View>): React.JSX.Element {
|
||||
const canvasRef = useRef<HTMLCanvasElement>(null)
|
||||
// A hidden or moved tab lets go of its view; this brings it back where it looked.
|
||||
const lastPlacement = useRememberedRef<TiledPlacement | null>(`${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 <canvas ref={canvasRef} className={className} />
|
||||
}
|
||||
|
||||
@@ -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<string, LucideIcon> = {
|
||||
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<string, LucideIcon> = {
|
||||
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 <Icon className={className} />
|
||||
}
|
||||
|
||||
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 (
|
||||
<>
|
||||
<nav className="flex w-10 shrink-0 flex-col items-center gap-2.5 overflow-y-auto pt-1 pb-1.5">
|
||||
{groups.map((group, index) => (
|
||||
<Fragment key={group.label}>
|
||||
{index > 0 && <StripeLine />}
|
||||
{group.views.map((view) => (
|
||||
<ViewButton key={view.id} view={view} selected={view.id === current} onSelect={() => onSelect(view.id)} />
|
||||
))}
|
||||
</Fragment>
|
||||
<nav aria-label="Views" className="flex w-16 shrink-0 flex-col items-center gap-1 overflow-y-auto pt-1 pb-1.5">
|
||||
{groupsOf(views).map((group) => (
|
||||
<GroupButton key={group.id} group={group} current={current} onSelect={onSelect} />
|
||||
))}
|
||||
<StripeLine />
|
||||
<NamedViews groups={groups} current={current} onSelect={onSelect} />
|
||||
</nav>
|
||||
<div ref={slotRef} className="flex w-60 shrink-0 flex-col overflow-hidden rounded-[10px] bg-card empty:hidden" />
|
||||
</>
|
||||
@@ -109,76 +103,57 @@ export function ViewList({ views, current, onSelect, slotRef }: ViewListProps):
|
||||
}
|
||||
|
||||
interface ViewGroup {
|
||||
id: string
|
||||
label: string
|
||||
views: ViewInfo[]
|
||||
}
|
||||
|
||||
function groupsOf(views: ViewInfo[]): ViewGroup[] {
|
||||
const labels = [...new Set(views.map((view) => view.groupLabel))]
|
||||
return labels.map((label) => ({ label, views: views.filter((view) => view.groupLabel === label) }))
|
||||
const ids = [...new Set(views.map((view) => view.group))]
|
||||
return ids.map((id) => {
|
||||
const members = views.filter((view) => view.group === id)
|
||||
return { id, label: members[0].groupLabel, views: members }
|
||||
})
|
||||
}
|
||||
|
||||
function StripeLine(): React.JSX.Element {
|
||||
return <span className="my-0.5 h-px w-5 shrink-0 bg-input" />
|
||||
}
|
||||
|
||||
function ViewButton({ view, selected, onSelect }: { view: ViewInfo; selected: boolean; onSelect(): void }): React.JSX.Element {
|
||||
const keyText = useKeyText()(viewShortcutId(view.id))
|
||||
return (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<button
|
||||
onClick={onSelect}
|
||||
aria-label={view.label}
|
||||
aria-pressed={selected}
|
||||
className={cn(STRIPE_BUTTON, selected ? 'icon-tint bg-primary text-primary-foreground' : 'hover:bg-accent')}
|
||||
>
|
||||
<ViewIcon viewId={view.id} className="size-5" />
|
||||
</button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="right" className="flex max-w-64 flex-col items-start gap-0.5">
|
||||
<span className="flex items-center gap-2 font-medium">
|
||||
{view.label}
|
||||
{keyText !== '' && <Kbd className="uppercase">{keyText}</Kbd>}
|
||||
</span>
|
||||
<span className="text-secondary-text">{view.description}</span>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
)
|
||||
}
|
||||
|
||||
/** Every view by name, for when its icon alone does not say which it is (IntelliJ's "more tool windows"). */
|
||||
function NamedViews({ groups, current, onSelect }: { groups: ViewGroup[]; current: string; onSelect(view: string): void }): React.JSX.Element {
|
||||
function GroupButton({ group, current, onSelect }: { group: ViewGroup; current: string; onSelect(view: string): void }): React.JSX.Element {
|
||||
const keyText = useKeyText()
|
||||
const [open, setOpen] = useState(false)
|
||||
const Icon = GROUP_ICONS[group.id] ?? FALLBACK_ICON
|
||||
const holdsCurrent = group.views.some((view) => view.id === current)
|
||||
return (
|
||||
<DropdownMenu.Root>
|
||||
<DropdownMenu.Root open={open} onOpenChange={setOpen}>
|
||||
<DropdownMenu.Trigger asChild>
|
||||
<button aria-label="All views" title="All views" className={cn(STRIPE_BUTTON, 'hover:bg-accent data-[state=open]:bg-accent')}>
|
||||
<Glyph glyph="more" />
|
||||
<button
|
||||
aria-label={group.label}
|
||||
className={cn(
|
||||
'flex w-[60px] shrink-0 flex-col items-center gap-0.5 rounded-lg px-0.5 pt-1.5 pb-1 outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-inset',
|
||||
holdsCurrent || open ? 'bg-accent text-foreground' : 'text-secondary-text hover:bg-accent hover:text-foreground'
|
||||
)}
|
||||
>
|
||||
<Icon className="size-5" strokeWidth={1.6} />
|
||||
<span className="line-clamp-2 w-full text-center text-[10px] leading-[1.15]">{group.label}</span>
|
||||
</button>
|
||||
</DropdownMenu.Trigger>
|
||||
<DropdownMenu.Portal>
|
||||
<DropdownMenu.Content side="right" align="end" sideOffset={8} className="popup z-50 w-56 p-1 popup-motion">
|
||||
{groups.map((group) => (
|
||||
<DropdownMenu.Group key={group.label}>
|
||||
<DropdownMenu.Label className="px-2 pt-1.5 pb-1 text-[11px] font-semibold text-muted-foreground">{group.label}</DropdownMenu.Label>
|
||||
{group.views.map((view) => (
|
||||
<DropdownMenu.Item
|
||||
key={view.id}
|
||||
onSelect={() => onSelect(view.id)}
|
||||
className={cn(
|
||||
'flex h-[26px] cursor-default items-center gap-2 rounded-md px-2 outline-none data-[highlighted]:bg-accent',
|
||||
view.id === current && 'bg-selection'
|
||||
)}
|
||||
>
|
||||
<ViewIcon viewId={view.id} className="size-3.5" />
|
||||
<span className="min-w-0 flex-1 truncate">{view.label}</span>
|
||||
{keyText(viewShortcutId(view.id)) !== '' && (
|
||||
<Kbd className="h-4 min-w-4 border border-input/60 bg-transparent text-[10px] uppercase">{keyText(viewShortcutId(view.id))}</Kbd>
|
||||
)}
|
||||
</DropdownMenu.Item>
|
||||
))}
|
||||
</DropdownMenu.Group>
|
||||
<DropdownMenu.Content side="right" align="start" sideOffset={6} className="popup z-50 w-60 p-1 popup-motion">
|
||||
<DropdownMenu.Label className="px-2 pt-1 pb-1 text-[11px] font-semibold text-muted-foreground">{group.label}</DropdownMenu.Label>
|
||||
{group.views.map((view) => (
|
||||
<DropdownMenu.Item
|
||||
key={view.id}
|
||||
title={view.description}
|
||||
onSelect={() => onSelect(view.id)}
|
||||
className={cn(
|
||||
'flex h-[26px] cursor-default items-center gap-2 rounded-md px-2 outline-none data-[highlighted]:bg-accent',
|
||||
view.id === current && 'bg-selection'
|
||||
)}
|
||||
>
|
||||
<ViewIcon viewId={view.id} className="size-3.5" />
|
||||
<span className="min-w-0 flex-1 truncate">{view.label}</span>
|
||||
{keyText(viewShortcutId(view.id)) !== '' && (
|
||||
<Kbd className="h-4 min-w-4 border border-input/60 bg-transparent text-[10px] uppercase">{keyText(viewShortcutId(view.id))}</Kbd>
|
||||
)}
|
||||
</DropdownMenu.Item>
|
||||
))}
|
||||
</DropdownMenu.Content>
|
||||
</DropdownMenu.Portal>
|
||||
|
||||
@@ -17,7 +17,7 @@ import { PickInspector, hasPickSections } from './PickInspector'
|
||||
import { SceneViewport } from './SceneViewport'
|
||||
import { usePickInspection } from './usePickInspection'
|
||||
import { useSpotActions } from './useSpotActions'
|
||||
import { HEADER_CHOICE, Panel, SizeChoice, ViewIsland } from './Sidebar'
|
||||
import { DetailPanel, HEADER_CHOICE, SizeChoice, ViewIsland } from './Sidebar'
|
||||
import { useGroundInView, useLongPending, useTerrainStream } from './useTerrainStream'
|
||||
import { caveBandShares, useWorldCaves, type CaveArea } from './useWorldCaves'
|
||||
|
||||
@@ -159,7 +159,7 @@ export function WorldStudio3D({ title, client, world, mapArea, packRevision, onS
|
||||
</div>
|
||||
)}
|
||||
</ViewIsland>
|
||||
<Panel className="w-[250px]">
|
||||
<DetailPanel className="w-[250px]">
|
||||
{showsCaves ? (
|
||||
<Legend title="Caves by height" shares={caveShares} emptyText={caves.status === null ? 'No caves here' : 'Generating the caves…'} className="flex-1" />
|
||||
) : inspectsPicks && hasPickSections(inspection) ? (
|
||||
@@ -167,7 +167,7 @@ export function WorldStudio3D({ title, client, world, mapArea, packRevision, onS
|
||||
) : (
|
||||
<Legend title="Heights in view" shares={heightShares} emptyText="Looking at the ground…" className="flex-1" />
|
||||
)}
|
||||
</Panel>
|
||||
</DetailPanel>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
import { useCallback, useState } from 'react'
|
||||
|
||||
const remembered = new Map<string, unknown>()
|
||||
|
||||
/**
|
||||
* State that outlives the component holding it, by {@code key}: a list's search stays as it was when the list comes
|
||||
* back for another tab of the same view, and a tab moved to another pane keeps what it showed.
|
||||
*/
|
||||
export function useRememberedState<Value>(key: string, initial: Value): [Value, (next: Value | ((current: Value) => Value)) => void] {
|
||||
const [value, setValue] = useState<Value>(() => (remembered.has(key) ? (remembered.get(key) as Value) : initial))
|
||||
const update = useCallback(
|
||||
(next: Value | ((current: Value) => Value)) =>
|
||||
setValue((current) => {
|
||||
const value = typeof next === 'function' ? (next as (current: Value) => Value)(current) : next
|
||||
remembered.set(key, value)
|
||||
return value
|
||||
}),
|
||||
[key]
|
||||
)
|
||||
return [value, update]
|
||||
}
|
||||
|
||||
/** A ref that outlives the component holding it, by {@code key}, as {@link useRememberedState} does for state. */
|
||||
export function useRememberedRef<Value>(key: string, initial: Value): { current: Value } {
|
||||
const known = remembered.get(key) as { current: Value } | undefined
|
||||
if (known !== undefined) {
|
||||
return known
|
||||
}
|
||||
const created = { current: initial }
|
||||
remembered.set(key, created)
|
||||
return created
|
||||
}
|
||||
|
||||
/** Forgets what a closed tab remembered, whose keys start with its id. */
|
||||
export function forgetTab(tabId: string): void {
|
||||
const prefix = `${tabId}:`
|
||||
for (const key of remembered.keys()) {
|
||||
if (key.startsWith(prefix)) {
|
||||
remembered.delete(key)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -19,8 +19,15 @@ export type ShortcutAction =
|
||||
| 'deleteNode'
|
||||
| 'duplicateNode'
|
||||
| 'showAllNodes'
|
||||
| 'closeTab'
|
||||
| 'previousTab'
|
||||
| 'nextTab'
|
||||
| 'recentTab'
|
||||
|
||||
export type ShortcutGroup = 'Views' | 'Everywhere' | 'Map' | 'Node editor'
|
||||
export type ShortcutGroup = 'Views' | 'Tabs' | 'Everywhere' | 'Map' | 'Node editor'
|
||||
|
||||
/** The groups in the order the keymap and the help list them. */
|
||||
export const SHORTCUT_GROUPS: ShortcutGroup[] = ['Views', 'Tabs', 'Everywhere', 'Map', 'Node editor']
|
||||
|
||||
/**
|
||||
* A key press as text: the modifiers in the order ctrl, alt, shift, then the key as {@code KeyboardEvent.key} names it,
|
||||
@@ -46,6 +53,10 @@ interface ShortcutDefinition extends ShortcutRow {
|
||||
|
||||
export const SHORTCUTS: ShortcutDefinition[] = [
|
||||
{ id: 'nextView', label: 'Next view', group: 'Views', chords: ['m'] },
|
||||
{ id: 'closeTab', label: 'Close the tab', group: 'Tabs', chords: ['ctrl+F4'] },
|
||||
{ id: 'previousTab', label: 'Previous tab', group: 'Tabs', chords: ['alt+ArrowLeft'] },
|
||||
{ id: 'nextTab', label: 'Next tab', group: 'Tabs', chords: ['alt+ArrowRight'] },
|
||||
{ id: 'recentTab', label: 'Switch to a recent tab', group: 'Tabs', chords: ['ctrl+Tab'] },
|
||||
{ id: 'refresh', label: 'Redraw the map with the latest pack files', group: 'Everywhere', chords: ['r'] },
|
||||
{ id: 'zoomIn', label: 'Zoom in', group: 'Everywhere', chords: ['=', '+'] },
|
||||
{ id: 'zoomOut', label: 'Zoom out', group: 'Everywhere', chords: ['-'] },
|
||||
@@ -94,6 +105,7 @@ export const MOUSE_HINTS: { gesture: string; label: string }[] = [
|
||||
*/
|
||||
const GROUP_SCOPES: Record<ShortcutGroup, { windowWide: boolean; nodeEditor: boolean }> = {
|
||||
Views: { windowWide: true, nodeEditor: false },
|
||||
Tabs: { windowWide: true, nodeEditor: false },
|
||||
Everywhere: { windowWide: true, nodeEditor: true },
|
||||
Map: { windowWide: true, nodeEditor: false },
|
||||
'Node editor': { windowWide: false, nodeEditor: true }
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
import { createContext, useContext, useEffect } from 'react'
|
||||
|
||||
/** The tab a view draws in: what it shows, and how the view opens other entries from its list. */
|
||||
export interface TabHandle {
|
||||
id: string
|
||||
viewId: string
|
||||
/** The entry the tab shows, or null while its view has not settled on one. */
|
||||
entry: string | null
|
||||
/** Shown in its pane, as opposed to hidden behind another tab. */
|
||||
visible: boolean
|
||||
/** Shown in the pane last clicked, the one the stripe, the keys and the side panels follow. */
|
||||
focused: boolean
|
||||
/** Opens an entry from the view's list: in the pane's preview tab, or in a tab of its own when {@code keep}. */
|
||||
choose(entry: string, keep?: boolean): void
|
||||
/** Keeps this tab once it is used, so the next click in the list opens another. */
|
||||
keep(): void
|
||||
/** Records the entry the view showed for a tab opened without one, and what the tab is called. */
|
||||
settle(entry: string | null, title: string | null): void
|
||||
}
|
||||
|
||||
const DETACHED: TabHandle = {
|
||||
id: '',
|
||||
viewId: '',
|
||||
entry: null,
|
||||
visible: true,
|
||||
focused: true,
|
||||
choose: () => undefined,
|
||||
keep: () => undefined,
|
||||
settle: () => undefined
|
||||
}
|
||||
|
||||
export const TabContext = createContext<TabHandle>(DETACHED)
|
||||
|
||||
/** Lets a tab's view take the keys meant for the focused view, such as the map's; returns how to stop. */
|
||||
export type CommandRegistry = (tabId: string, run: (action: string) => void) => () => void
|
||||
|
||||
export const TabCommands = createContext<CommandRegistry>(() => () => undefined)
|
||||
|
||||
/** Takes the keys meant for the focused view while this tab is the focused pane's shown one. */
|
||||
export function useTabCommands(tab: TabHandle, run: (action: string) => void): void {
|
||||
const register = useContext(TabCommands)
|
||||
useEffect(() => register(tab.id, run), [register, tab.id, run])
|
||||
}
|
||||
|
||||
export function useTab(): TabHandle {
|
||||
return useContext(TabContext)
|
||||
}
|
||||
|
||||
/** Names the tab after the entry its view shows, and records that entry for a tab opened without one. */
|
||||
export function useSettledEntry(tab: TabHandle, entry: string | null, title: string | null): void {
|
||||
const { settle } = tab
|
||||
useEffect(() => settle(entry, title), [settle, entry, title])
|
||||
}
|
||||
Reference in new issue
Block a user