mirror of
https://github.com/VolmitSoftware/Iris.git
synced 2026-11-27 00:04:42 +00:00
Studio map app: Electron studio for the Iris bridge
A standalone Electron + React + Tailwind + shadcn/ui app that connects to the localhost bridge `/iris studio map` opens and draws the world map with the v3e studio's views, shortcuts, hover card, legend and styling. - Finds running bridges from ~/.iris/studio/bridges and iris-studio:// links - Biome, region, height and biome layer views from 128-pixel tiles - Coarser previews first, so the screen fills sooner, then sharpens - Hover card with Shift details, legend census with click to highlight - Ctrl+click teleport, Alt+click open file, right-click menu - Light, dark and system themes from the v3e studio palette
This commit is contained in:
commit
f1171307cd
47 files changed
+8388
No files matched your search
@@ -0,0 +1,4 @@
|
||||
node_modules/
|
||||
out/
|
||||
dist/
|
||||
*.log
|
||||
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"$schema": "https://ui.shadcn.com/schema.json",
|
||||
"style": "new-york",
|
||||
"rsc": false,
|
||||
"tsx": true,
|
||||
"tailwind": {
|
||||
"config": "",
|
||||
"css": "src/renderer/src/styles.css",
|
||||
"baseColor": "neutral",
|
||||
"cssVariables": true,
|
||||
"prefix": ""
|
||||
},
|
||||
"aliases": {
|
||||
"components": "@/components",
|
||||
"utils": "@/lib/utils",
|
||||
"ui": "@/components/ui",
|
||||
"lib": "@/lib",
|
||||
"hooks": "@/hooks"
|
||||
},
|
||||
"iconLibrary": "lucide"
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import { resolve } from 'node:path'
|
||||
import { defineConfig } from 'electron-vite'
|
||||
import react from '@vitejs/plugin-react'
|
||||
import tailwindcss from '@tailwindcss/vite'
|
||||
|
||||
export default defineConfig({
|
||||
main: {},
|
||||
preload: {
|
||||
build: {
|
||||
rollupOptions: {
|
||||
output: { format: 'cjs', entryFileNames: '[name].cjs' }
|
||||
}
|
||||
}
|
||||
},
|
||||
renderer: {
|
||||
resolve: {
|
||||
alias: { '@': resolve(import.meta.dirname, 'src/renderer/src') }
|
||||
},
|
||||
plugins: [react(), tailwindcss()]
|
||||
}
|
||||
})
|
||||
Generated
+4525
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,39 @@
|
||||
{
|
||||
"name": "iris-studio",
|
||||
"productName": "Iris Studio",
|
||||
"version": "0.1.0",
|
||||
"description": "The studio app for Iris worlds: maps, objects and editors, connected to a running server",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "out/main/index.js",
|
||||
"scripts": {
|
||||
"dev": "electron-vite dev",
|
||||
"build": "electron-vite build",
|
||||
"start": "electron-vite preview",
|
||||
"typecheck": "tsc --noEmit -p tsconfig.json",
|
||||
"test": "vitest run"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@tailwindcss/vite": "^4.3.4",
|
||||
"@types/node": "^26.6.6",
|
||||
"@types/react": "^19.3.0",
|
||||
"@types/react-dom": "^19.3.0",
|
||||
"@vitejs/plugin-react": "^6.2.1",
|
||||
"electron": "^45.2.3",
|
||||
"electron-vite": "^6.0.0",
|
||||
"tailwindcss": "^4.3.4",
|
||||
"typescript": "^7.0.2",
|
||||
"vite": "^8.3.6",
|
||||
"vitest": "^5.1.0"
|
||||
},
|
||||
"dependencies": {
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
"cn": "^0.5.2",
|
||||
"lucide-react": "^1.69.0",
|
||||
"radix-ui": "^1.8.1",
|
||||
"react": "^19.3.1",
|
||||
"react-dom": "^19.3.1",
|
||||
"tailwind-merge": "^3.7.0"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
import { app, BrowserWindow, clipboard, ipcMain, nativeTheme, shell } from 'electron'
|
||||
import { readdir, readFile } from 'node:fs/promises'
|
||||
import { homedir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import type { BridgeConnection, ThemeChoice } from '../shared/bridge'
|
||||
|
||||
const CONNECTION_FOLDER = join(homedir(), '.iris', 'studio', 'bridges')
|
||||
const LINK_PREFIX = 'iris-studio://'
|
||||
const DARK_BACKGROUND = '#1e1f22'
|
||||
const WINDOW_SIZE = { width: 1440, height: 880, minWidth: 820, minHeight: 520 }
|
||||
|
||||
let window: BrowserWindow | null = null
|
||||
let pendingLink: string | null = findLink(process.argv)
|
||||
|
||||
function findLink(argv: string[]): string | null {
|
||||
return argv.find((argument) => argument.startsWith(LINK_PREFIX)) ?? null
|
||||
}
|
||||
|
||||
function isRunning(pid: unknown): boolean {
|
||||
if (typeof pid !== 'number') {
|
||||
return true
|
||||
}
|
||||
try {
|
||||
process.kill(pid, 0)
|
||||
return true
|
||||
} catch (error) {
|
||||
return (error as NodeJS.ErrnoException).code === 'EPERM'
|
||||
}
|
||||
}
|
||||
|
||||
/** The bridges announced on this machine whose server still runs, newest first. */
|
||||
async function listBridges(): Promise<BridgeConnection[]> {
|
||||
let files: string[]
|
||||
try {
|
||||
files = (await readdir(CONNECTION_FOLDER)).filter((name) => name.endsWith('.json'))
|
||||
} catch {
|
||||
return []
|
||||
}
|
||||
const bridges = await Promise.all(files.map(readConnection))
|
||||
return bridges
|
||||
.filter((bridge): bridge is BridgeConnection => bridge !== null)
|
||||
.sort((first, second) => (second.startedMillis ?? 0) - (first.startedMillis ?? 0))
|
||||
}
|
||||
|
||||
async function readConnection(name: string): Promise<BridgeConnection | null> {
|
||||
try {
|
||||
const file = JSON.parse(await readFile(join(CONNECTION_FOLDER, name), 'utf8'))
|
||||
if (!isRunning(file.pid) || typeof file.port !== 'number' || typeof file.token !== 'string') {
|
||||
return null
|
||||
}
|
||||
return { world: String(file.world ?? ''), port: file.port, token: file.token, startedMillis: file.startedMillis }
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
function createWindow(): void {
|
||||
window = new BrowserWindow({
|
||||
...WINDOW_SIZE,
|
||||
title: 'Iris Studio',
|
||||
backgroundColor: DARK_BACKGROUND,
|
||||
autoHideMenuBar: true,
|
||||
show: false,
|
||||
webPreferences: {
|
||||
preload: join(import.meta.dirname, '../preload/index.cjs'),
|
||||
sandbox: true,
|
||||
contextIsolation: true
|
||||
}
|
||||
})
|
||||
window.once('ready-to-show', () => window?.show())
|
||||
window.webContents.setWindowOpenHandler(({ url }) => {
|
||||
void shell.openExternal(url)
|
||||
return { action: 'deny' }
|
||||
})
|
||||
if (process.env.ELECTRON_RENDERER_URL) {
|
||||
void window.loadURL(process.env.ELECTRON_RENDERER_URL)
|
||||
} else {
|
||||
void window.loadFile(join(import.meta.dirname, '../renderer/index.html'))
|
||||
}
|
||||
}
|
||||
|
||||
function deliverLink(link: string): void {
|
||||
if (window === null) {
|
||||
pendingLink = link
|
||||
return
|
||||
}
|
||||
window.webContents.send('studio:link', link)
|
||||
if (window.isMinimized()) {
|
||||
window.restore()
|
||||
}
|
||||
window.focus()
|
||||
}
|
||||
|
||||
if (!app.requestSingleInstanceLock()) {
|
||||
app.quit()
|
||||
} else {
|
||||
app.setAsDefaultProtocolClient('iris-studio')
|
||||
app.on('second-instance', (_event, argv) => {
|
||||
const link = findLink(argv)
|
||||
if (link !== null) {
|
||||
deliverLink(link)
|
||||
} else {
|
||||
window?.focus()
|
||||
}
|
||||
})
|
||||
app.on('open-url', (event, url) => {
|
||||
event.preventDefault()
|
||||
deliverLink(url)
|
||||
})
|
||||
|
||||
ipcMain.handle('studio:list-bridges', listBridges)
|
||||
ipcMain.handle('studio:initial-link', () => {
|
||||
const link = pendingLink
|
||||
pendingLink = null
|
||||
return link
|
||||
})
|
||||
ipcMain.on('studio:set-theme', (_event, theme: ThemeChoice) => {
|
||||
nativeTheme.themeSource = theme
|
||||
})
|
||||
ipcMain.on('studio:copy-text', (_event, text: string) => clipboard.writeText(text))
|
||||
|
||||
void app.whenReady().then(createWindow)
|
||||
app.on('window-all-closed', () => app.quit())
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import { contextBridge, ipcRenderer, type IpcRendererEvent } from 'electron'
|
||||
import type { StudioHost, ThemeChoice } from '../shared/bridge'
|
||||
|
||||
const host: StudioHost = {
|
||||
listBridges: () => ipcRenderer.invoke('studio:list-bridges'),
|
||||
initialLink: () => ipcRenderer.invoke('studio:initial-link'),
|
||||
onLink: (listener) => {
|
||||
const forward = (_event: IpcRendererEvent, link: string): void => listener(link)
|
||||
ipcRenderer.on('studio:link', forward)
|
||||
return () => ipcRenderer.removeListener('studio:link', forward)
|
||||
},
|
||||
setTheme: (theme: ThemeChoice) => ipcRenderer.send('studio:set-theme', theme),
|
||||
copyText: (text: string) => ipcRenderer.send('studio:copy-text', text)
|
||||
}
|
||||
|
||||
contextBridge.exposeInMainWorld('studio', host)
|
||||
@@ -0,0 +1,15 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta
|
||||
http-equiv="Content-Security-Policy"
|
||||
content="default-src 'self'; connect-src 'self' http://127.0.0.1:* ws://localhost:*; img-src 'self' data: blob:; style-src 'self' 'unsafe-inline'"
|
||||
/>
|
||||
<title>Iris Studio</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,63 @@
|
||||
import { useCallback, useEffect, useState } from 'react'
|
||||
import { parseStudioLink, type BridgeConnection } from '../../shared/bridge'
|
||||
import { BridgeClient } from './bridge/BridgeClient'
|
||||
import type { WorldInfo } from './bridge/types'
|
||||
import { ConnectScreen } from './studio/ConnectScreen'
|
||||
import { MapStudio } from './studio/MapStudio'
|
||||
import { useTheme } from './studio/theme'
|
||||
|
||||
interface Session {
|
||||
client: BridgeClient
|
||||
world: WorldInfo
|
||||
}
|
||||
|
||||
/** The studio: a connect screen until a bridge answers, then the map of its world. */
|
||||
export function App(): React.JSX.Element {
|
||||
const theme = useTheme()
|
||||
const [session, setSession] = useState<Session | null>(null)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [connecting, setConnecting] = useState(false)
|
||||
|
||||
const connect = useCallback(async (connection: BridgeConnection) => {
|
||||
setConnecting(true)
|
||||
setError(null)
|
||||
const client = new BridgeClient(connection)
|
||||
try {
|
||||
setSession({ client, world: await client.world() })
|
||||
} catch (failure) {
|
||||
setError(failure instanceof Error ? failure.message : String(failure))
|
||||
} finally {
|
||||
setConnecting(false)
|
||||
}
|
||||
}, [])
|
||||
|
||||
const connectLink = useCallback(
|
||||
(link: string) => {
|
||||
const connection = parseStudioLink(link)
|
||||
if (connection === null) {
|
||||
setError('That is not a studio link')
|
||||
return
|
||||
}
|
||||
void connect(connection)
|
||||
},
|
||||
[connect]
|
||||
)
|
||||
|
||||
useEffect(() => {
|
||||
void window.studio.initialLink().then((link) => link !== null && connectLink(link))
|
||||
return window.studio.onLink(connectLink)
|
||||
}, [connectLink])
|
||||
|
||||
if (session === null) {
|
||||
return <ConnectScreen connecting={connecting} error={error} onConnect={connect} onLink={connectLink} />
|
||||
}
|
||||
return (
|
||||
<MapStudio
|
||||
key={`${session.client.connection.port}`}
|
||||
client={session.client}
|
||||
world={session.world}
|
||||
theme={theme}
|
||||
onDisconnect={() => setSession(null)}
|
||||
/>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
import type { BridgeConnection } from '../../../shared/bridge'
|
||||
import { decodeTile } from './tileDecoding'
|
||||
import type { MapHover, MapTile, Marker, WorldInfo } from './types'
|
||||
|
||||
export class BridgeError extends Error {
|
||||
constructor(
|
||||
readonly status: number,
|
||||
message: string
|
||||
) {
|
||||
super(message)
|
||||
}
|
||||
}
|
||||
|
||||
export interface TileRequest {
|
||||
view: string
|
||||
tileX: number
|
||||
tileZ: number
|
||||
blocksPerPixel: number
|
||||
size: number
|
||||
heights: boolean
|
||||
}
|
||||
|
||||
export interface BridgeEvents {
|
||||
onWorld(running: boolean): void
|
||||
onPlayers(players: Marker[]): void
|
||||
onClosed(): void
|
||||
}
|
||||
|
||||
const EVENT_SEPARATOR = '\n\n'
|
||||
|
||||
/** One connection to a world's bridge, over HTTP on the loopback interface. */
|
||||
export class BridgeClient {
|
||||
private readonly base: string
|
||||
private readonly authorization: string
|
||||
|
||||
constructor(readonly connection: BridgeConnection) {
|
||||
this.base = `http://127.0.0.1:${connection.port}/v1/`
|
||||
this.authorization = `Bearer ${connection.token}`
|
||||
}
|
||||
|
||||
world(): Promise<WorldInfo> {
|
||||
return this.json('world')
|
||||
}
|
||||
|
||||
hover(worldX: number, worldZ: number, signal?: AbortSignal): Promise<MapHover> {
|
||||
return this.json(`hover?x=${worldX}&z=${worldZ}`, { signal })
|
||||
}
|
||||
|
||||
entities(): Promise<Marker[]> {
|
||||
return this.json('entities')
|
||||
}
|
||||
|
||||
async teleport(worldX: number, worldZ: number): Promise<void> {
|
||||
await this.json(`teleport?x=${worldX}&z=${worldZ}`, { method: 'POST' })
|
||||
}
|
||||
|
||||
/** Opens the file of the biome or region at a spot on the server's machine; the server's answer, if any. */
|
||||
async openInEditor(worldX: number, worldZ: number, view: string): Promise<string | null> {
|
||||
const answer = await this.json<{ message: string | null }>(`open?x=${worldX}&z=${worldZ}&view=${view}`, { method: 'POST' })
|
||||
return answer.message
|
||||
}
|
||||
|
||||
async tile(request: TileRequest, signal: AbortSignal): Promise<MapTile> {
|
||||
const query = new URLSearchParams({
|
||||
view: request.view,
|
||||
x: String(request.tileX),
|
||||
z: String(request.tileZ),
|
||||
scale: String(request.blocksPerPixel),
|
||||
size: String(request.size),
|
||||
heights: request.heights ? '1' : '0'
|
||||
})
|
||||
const response = await this.fetch(`tile?${query}`, { signal })
|
||||
return decodeTile(await response.arrayBuffer())
|
||||
}
|
||||
|
||||
/** Streams the bridge's events until {@code signal} aborts or the bridge goes away. */
|
||||
async listen(events: BridgeEvents, signal: AbortSignal): Promise<void> {
|
||||
try {
|
||||
const response = await this.fetch('events', { signal })
|
||||
const reader = response.body!.pipeThrough(new TextDecoderStream()).getReader()
|
||||
let pending = ''
|
||||
for (;;) {
|
||||
const { value, done } = await reader.read()
|
||||
if (done) {
|
||||
break
|
||||
}
|
||||
pending += value
|
||||
let end: number
|
||||
while ((end = pending.indexOf(EVENT_SEPARATOR)) >= 0) {
|
||||
dispatch(pending.slice(0, end), events)
|
||||
pending = pending.slice(end + EVENT_SEPARATOR.length)
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
if (signal.aborted) {
|
||||
return
|
||||
}
|
||||
console.warn('Studio events stopped', error)
|
||||
}
|
||||
if (!signal.aborted) {
|
||||
events.onClosed()
|
||||
}
|
||||
}
|
||||
|
||||
private async json<T>(endpoint: string, init: RequestInit = {}): Promise<T> {
|
||||
const response = await this.fetch(endpoint, init)
|
||||
return (await response.json()) as T
|
||||
}
|
||||
|
||||
private async fetch(endpoint: string, init: RequestInit): Promise<Response> {
|
||||
const response = await fetch(this.base + endpoint, {
|
||||
...init,
|
||||
headers: { Authorization: this.authorization }
|
||||
})
|
||||
if (!response.ok) {
|
||||
const body = await response.json().catch(() => ({ error: response.statusText }))
|
||||
throw new BridgeError(response.status, String(body.error ?? response.statusText))
|
||||
}
|
||||
return response
|
||||
}
|
||||
}
|
||||
|
||||
function dispatch(block: string, events: BridgeEvents): void {
|
||||
let name = 'message'
|
||||
let data = ''
|
||||
for (const line of block.split('\n')) {
|
||||
if (line.startsWith('event: ')) {
|
||||
name = line.slice('event: '.length)
|
||||
} else if (line.startsWith('data: ')) {
|
||||
data += line.slice('data: '.length)
|
||||
}
|
||||
}
|
||||
if (data === '') {
|
||||
return
|
||||
}
|
||||
if (name === 'world') {
|
||||
events.onWorld((JSON.parse(data) as { running: boolean }).running)
|
||||
} else if (name === 'players') {
|
||||
events.onPlayers(JSON.parse(data) as Marker[])
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
import type { LabelKind, MapLabel, MapTile } from './types'
|
||||
|
||||
const ALIGNMENT_BYTES = 4
|
||||
|
||||
interface TileHeader {
|
||||
size: number
|
||||
blocksPerPixel: number
|
||||
subjectKind: LabelKind
|
||||
labels: MapLabel[]
|
||||
heights: boolean
|
||||
}
|
||||
|
||||
function aligned(bytes: number): number {
|
||||
return Math.ceil(bytes / ALIGNMENT_BYTES) * ALIGNMENT_BYTES
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads a tile as the bridge writes it (MapTileEncoding): a u32 header length, the JSON header, then the subject,
|
||||
* region and height grids, each starting on a multiple of 4 bytes. The grids are views into the buffer, not copies.
|
||||
*/
|
||||
export function decodeTile(buffer: ArrayBuffer): MapTile {
|
||||
const view = new DataView(buffer)
|
||||
const headerLength = view.getUint32(0, true)
|
||||
const header = JSON.parse(new TextDecoder().decode(new Uint8Array(buffer, 4, headerLength))) as TileHeader
|
||||
const gridSize = header.size + 2
|
||||
const cells = gridSize * gridSize
|
||||
const subjectsAt = aligned(4 + headerLength)
|
||||
const regionsAt = aligned(subjectsAt + cells * Int16Array.BYTES_PER_ELEMENT)
|
||||
const heightsAt = aligned(regionsAt + cells * Int16Array.BYTES_PER_ELEMENT)
|
||||
return {
|
||||
size: header.size,
|
||||
blocksPerPixel: header.blocksPerPixel,
|
||||
subjectKind: header.subjectKind,
|
||||
labels: header.labels,
|
||||
subjects: new Int16Array(buffer, subjectsAt, cells),
|
||||
regions: new Int16Array(buffer, regionsAt, cells),
|
||||
heights: header.heights ? new Float32Array(buffer, heightsAt, cells) : null
|
||||
}
|
||||
}
|
||||
|
||||
/** The grid index of a pixel; pixel coordinates run from -1 to size, the ring being the neighbours'. */
|
||||
export function gridIndex(tile: MapTile, pixelX: number, pixelZ: number): number {
|
||||
return (pixelZ + 1) * (tile.size + 2) + pixelX + 1
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
/** The shapes the Iris bridge answers with (Iris core, art.arcane.iris.core.studio). */
|
||||
|
||||
export type LabelKind = 'BIOME' | 'REGION'
|
||||
|
||||
export interface MapLabel {
|
||||
kind: LabelKind
|
||||
key: string
|
||||
name: string
|
||||
/** 0xRRGGBB */
|
||||
color: number
|
||||
}
|
||||
|
||||
export interface ViewInfo {
|
||||
id: string
|
||||
label: string
|
||||
description: string
|
||||
group: string
|
||||
groupLabel: string
|
||||
}
|
||||
|
||||
export interface WorldInfo {
|
||||
world: string
|
||||
dimension: string
|
||||
dimensionName: string
|
||||
seed: string
|
||||
minY: number
|
||||
height: number
|
||||
fluidHeight: number
|
||||
tileSize: number
|
||||
hasPlayers: boolean
|
||||
views: ViewInfo[]
|
||||
}
|
||||
|
||||
export interface MapHover {
|
||||
worldX: number
|
||||
worldZ: number
|
||||
biome: MapLabel | null
|
||||
caveBiome: MapLabel | null
|
||||
region: MapLabel | null
|
||||
vanillaBiome: string | null
|
||||
height: number
|
||||
fluidHeight: number
|
||||
slopeDegrees: number
|
||||
biomeFile: string | null
|
||||
regionFile: string | null
|
||||
}
|
||||
|
||||
export interface Marker {
|
||||
label: string
|
||||
worldX: number
|
||||
worldY: number
|
||||
worldZ: number
|
||||
health: number
|
||||
maxHealth: number
|
||||
}
|
||||
|
||||
/**
|
||||
* A decoded map tile. Grids hold (size + 2)² cells, the tile's pixels inside a ring of its neighbours' edge pixels.
|
||||
*/
|
||||
export interface MapTile {
|
||||
size: number
|
||||
blocksPerPixel: number
|
||||
subjectKind: LabelKind
|
||||
labels: MapLabel[]
|
||||
subjects: Int16Array
|
||||
regions: Int16Array
|
||||
heights: Float32Array | null
|
||||
}
|
||||
|
||||
export const NO_LABEL = -1
|
||||
@@ -0,0 +1,63 @@
|
||||
import * as React from "react"
|
||||
import { cva, type VariantProps } from "class-variance-authority"
|
||||
import { cn } from "@/lib/utils"
|
||||
import { Slot } from "radix-ui"
|
||||
|
||||
const buttonVariants = cva(
|
||||
"inline-flex shrink-0 items-center justify-center gap-2 rounded-md text-sm font-medium whitespace-nowrap transition-all outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default: "bg-primary text-primary-foreground hover:bg-primary/90",
|
||||
destructive:
|
||||
"bg-destructive text-white hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:bg-destructive/60 dark:focus-visible:ring-destructive/40",
|
||||
outline:
|
||||
"border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:border-input dark:bg-input/30 dark:hover:bg-input/50",
|
||||
secondary:
|
||||
"bg-secondary text-secondary-foreground hover:bg-secondary/80",
|
||||
ghost:
|
||||
"hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",
|
||||
link: "text-primary underline-offset-4 hover:underline",
|
||||
},
|
||||
size: {
|
||||
default: "h-9 px-4 py-2 has-[>svg]:px-3",
|
||||
xs: "h-6 gap-1 rounded-md px-2 text-xs has-[>svg]:px-1.5 [&_svg:not([class*='size-'])]:size-3",
|
||||
sm: "h-8 gap-1.5 rounded-md px-3 has-[>svg]:px-2.5",
|
||||
lg: "h-10 rounded-md px-6 has-[>svg]:px-4",
|
||||
icon: "size-9",
|
||||
"icon-xs": "size-6 rounded-md [&_svg:not([class*='size-'])]:size-3",
|
||||
"icon-sm": "size-8",
|
||||
"icon-lg": "size-10",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
size: "default",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
function Button({
|
||||
className,
|
||||
variant = "default",
|
||||
size = "default",
|
||||
asChild = false,
|
||||
...props
|
||||
}: React.ComponentProps<"button"> &
|
||||
VariantProps<typeof buttonVariants> & {
|
||||
asChild?: boolean
|
||||
}) {
|
||||
const Comp = asChild ? Slot.Root : "button"
|
||||
|
||||
return (
|
||||
<Comp
|
||||
data-slot="button"
|
||||
data-variant={variant}
|
||||
data-size={size}
|
||||
className={cn(buttonVariants({ variant, size, className }))}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Button, buttonVariants }
|
||||
@@ -0,0 +1,249 @@
|
||||
import * as React from "react"
|
||||
import { cn } from "@/lib/utils"
|
||||
import { CheckIcon, ChevronRightIcon, CircleIcon } from "lucide-react"
|
||||
import { ContextMenu as ContextMenuPrimitive } from "radix-ui"
|
||||
|
||||
function ContextMenu({
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.Root>) {
|
||||
return <ContextMenuPrimitive.Root data-slot="context-menu" {...props} />
|
||||
}
|
||||
|
||||
function ContextMenuTrigger({
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.Trigger>) {
|
||||
return (
|
||||
<ContextMenuPrimitive.Trigger data-slot="context-menu-trigger" {...props} />
|
||||
)
|
||||
}
|
||||
|
||||
function ContextMenuGroup({
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.Group>) {
|
||||
return (
|
||||
<ContextMenuPrimitive.Group data-slot="context-menu-group" {...props} />
|
||||
)
|
||||
}
|
||||
|
||||
function ContextMenuPortal({
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.Portal>) {
|
||||
return (
|
||||
<ContextMenuPrimitive.Portal data-slot="context-menu-portal" {...props} />
|
||||
)
|
||||
}
|
||||
|
||||
function ContextMenuSub({
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.Sub>) {
|
||||
return <ContextMenuPrimitive.Sub data-slot="context-menu-sub" {...props} />
|
||||
}
|
||||
|
||||
function ContextMenuRadioGroup({
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.RadioGroup>) {
|
||||
return (
|
||||
<ContextMenuPrimitive.RadioGroup
|
||||
data-slot="context-menu-radio-group"
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function ContextMenuSubTrigger({
|
||||
className,
|
||||
inset,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.SubTrigger> & {
|
||||
inset?: boolean
|
||||
}) {
|
||||
return (
|
||||
<ContextMenuPrimitive.SubTrigger
|
||||
data-slot="context-menu-sub-trigger"
|
||||
data-inset={inset}
|
||||
className={cn(
|
||||
"flex cursor-default items-center rounded-sm px-2 py-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[inset]:pl-8 data-[state=open]:bg-accent data-[state=open]:text-accent-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<ChevronRightIcon className="ml-auto" />
|
||||
</ContextMenuPrimitive.SubTrigger>
|
||||
)
|
||||
}
|
||||
|
||||
function ContextMenuSubContent({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.SubContent>) {
|
||||
return (
|
||||
<ContextMenuPrimitive.SubContent
|
||||
data-slot="context-menu-sub-content"
|
||||
className={cn(
|
||||
"z-50 min-w-[8rem] origin-(--radix-context-menu-content-transform-origin) overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function ContextMenuContent({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.Content>) {
|
||||
return (
|
||||
<ContextMenuPrimitive.Portal>
|
||||
<ContextMenuPrimitive.Content
|
||||
data-slot="context-menu-content"
|
||||
className={cn(
|
||||
"z-50 max-h-(--radix-context-menu-content-available-height) min-w-[8rem] origin-(--radix-context-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
</ContextMenuPrimitive.Portal>
|
||||
)
|
||||
}
|
||||
|
||||
function ContextMenuItem({
|
||||
className,
|
||||
inset,
|
||||
variant = "default",
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.Item> & {
|
||||
inset?: boolean
|
||||
variant?: "default" | "destructive"
|
||||
}) {
|
||||
return (
|
||||
<ContextMenuPrimitive.Item
|
||||
data-slot="context-menu-item"
|
||||
data-inset={inset}
|
||||
data-variant={variant}
|
||||
className={cn(
|
||||
"relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 data-[variant=destructive]:focus:text-destructive dark:data-[variant=destructive]:focus:bg-destructive/20 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground data-[variant=destructive]:*:[svg]:text-destructive!",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function ContextMenuCheckboxItem({
|
||||
className,
|
||||
children,
|
||||
checked,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.CheckboxItem>) {
|
||||
return (
|
||||
<ContextMenuPrimitive.CheckboxItem
|
||||
data-slot="context-menu-checkbox-item"
|
||||
className={cn(
|
||||
"relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className
|
||||
)}
|
||||
checked={checked}
|
||||
{...props}
|
||||
>
|
||||
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
|
||||
<ContextMenuPrimitive.ItemIndicator>
|
||||
<CheckIcon className="size-4" />
|
||||
</ContextMenuPrimitive.ItemIndicator>
|
||||
</span>
|
||||
{children}
|
||||
</ContextMenuPrimitive.CheckboxItem>
|
||||
)
|
||||
}
|
||||
|
||||
function ContextMenuRadioItem({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.RadioItem>) {
|
||||
return (
|
||||
<ContextMenuPrimitive.RadioItem
|
||||
data-slot="context-menu-radio-item"
|
||||
className={cn(
|
||||
"relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
|
||||
<ContextMenuPrimitive.ItemIndicator>
|
||||
<CircleIcon className="size-2 fill-current" />
|
||||
</ContextMenuPrimitive.ItemIndicator>
|
||||
</span>
|
||||
{children}
|
||||
</ContextMenuPrimitive.RadioItem>
|
||||
)
|
||||
}
|
||||
|
||||
function ContextMenuLabel({
|
||||
className,
|
||||
inset,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.Label> & {
|
||||
inset?: boolean
|
||||
}) {
|
||||
return (
|
||||
<ContextMenuPrimitive.Label
|
||||
data-slot="context-menu-label"
|
||||
data-inset={inset}
|
||||
className={cn(
|
||||
"px-2 py-1.5 text-sm font-medium text-foreground data-[inset]:pl-8",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function ContextMenuSeparator({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.Separator>) {
|
||||
return (
|
||||
<ContextMenuPrimitive.Separator
|
||||
data-slot="context-menu-separator"
|
||||
className={cn("-mx-1 my-1 h-px bg-border", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function ContextMenuShortcut({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"span">) {
|
||||
return (
|
||||
<span
|
||||
data-slot="context-menu-shortcut"
|
||||
className={cn(
|
||||
"ml-auto text-xs tracking-widest text-muted-foreground",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
ContextMenu,
|
||||
ContextMenuTrigger,
|
||||
ContextMenuContent,
|
||||
ContextMenuItem,
|
||||
ContextMenuCheckboxItem,
|
||||
ContextMenuRadioItem,
|
||||
ContextMenuLabel,
|
||||
ContextMenuSeparator,
|
||||
ContextMenuShortcut,
|
||||
ContextMenuGroup,
|
||||
ContextMenuPortal,
|
||||
ContextMenuSub,
|
||||
ContextMenuSubContent,
|
||||
ContextMenuSubTrigger,
|
||||
ContextMenuRadioGroup,
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { cn } from "@/lib/utils"
|
||||
import { XIcon } from "lucide-react"
|
||||
import { Dialog as DialogPrimitive } from "radix-ui"
|
||||
|
||||
import { Button } from "@/components/ui/button"
|
||||
|
||||
function Dialog({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Root>) {
|
||||
return <DialogPrimitive.Root data-slot="dialog" {...props} />
|
||||
}
|
||||
|
||||
function DialogTrigger({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Trigger>) {
|
||||
return <DialogPrimitive.Trigger data-slot="dialog-trigger" {...props} />
|
||||
}
|
||||
|
||||
function DialogPortal({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Portal>) {
|
||||
return <DialogPrimitive.Portal data-slot="dialog-portal" {...props} />
|
||||
}
|
||||
|
||||
function DialogClose({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Close>) {
|
||||
return <DialogPrimitive.Close data-slot="dialog-close" {...props} />
|
||||
}
|
||||
|
||||
function DialogOverlay({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Overlay>) {
|
||||
return (
|
||||
<DialogPrimitive.Overlay
|
||||
data-slot="dialog-overlay"
|
||||
className={cn(
|
||||
"fixed inset-0 z-50 bg-black/50 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:animate-in data-[state=open]:fade-in-0",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DialogContent({
|
||||
className,
|
||||
children,
|
||||
showCloseButton = true,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Content> & {
|
||||
showCloseButton?: boolean
|
||||
}) {
|
||||
return (
|
||||
<DialogPortal data-slot="dialog-portal">
|
||||
<DialogOverlay />
|
||||
<DialogPrimitive.Content
|
||||
data-slot="dialog-content"
|
||||
className={cn(
|
||||
"fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border bg-background p-6 shadow-lg duration-200 outline-none data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95 sm:max-w-lg",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
{showCloseButton && (
|
||||
<DialogPrimitive.Close
|
||||
data-slot="dialog-close"
|
||||
className="absolute top-4 right-4 rounded-xs opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:ring-2 focus:ring-ring focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4"
|
||||
>
|
||||
<XIcon />
|
||||
<span className="sr-only">Close</span>
|
||||
</DialogPrimitive.Close>
|
||||
)}
|
||||
</DialogPrimitive.Content>
|
||||
</DialogPortal>
|
||||
)
|
||||
}
|
||||
|
||||
function DialogHeader({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="dialog-header"
|
||||
className={cn("flex flex-col gap-2 text-center sm:text-left", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DialogFooter({
|
||||
className,
|
||||
showCloseButton = false,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<"div"> & {
|
||||
showCloseButton?: boolean
|
||||
}) {
|
||||
return (
|
||||
<div
|
||||
data-slot="dialog-footer"
|
||||
className={cn(
|
||||
"flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
{showCloseButton && (
|
||||
<DialogPrimitive.Close asChild>
|
||||
<Button variant="outline">Close</Button>
|
||||
</DialogPrimitive.Close>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function DialogTitle({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Title>) {
|
||||
return (
|
||||
<DialogPrimitive.Title
|
||||
data-slot="dialog-title"
|
||||
className={cn("text-lg leading-none font-semibold", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DialogDescription({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Description>) {
|
||||
return (
|
||||
<DialogPrimitive.Description
|
||||
data-slot="dialog-description"
|
||||
className={cn("text-sm text-muted-foreground", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
Dialog,
|
||||
DialogClose,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogOverlay,
|
||||
DialogPortal,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import * as React from "react"
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Input({ className, type, ...props }: React.ComponentProps<"input">) {
|
||||
return (
|
||||
<input
|
||||
type={type}
|
||||
data-slot="input"
|
||||
className={cn(
|
||||
"h-9 w-full min-w-0 rounded-md border border-input bg-transparent px-3 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none selection:bg-primary selection:text-primary-foreground file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm dark:bg-input/30",
|
||||
"focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50",
|
||||
"aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Input }
|
||||
@@ -0,0 +1,28 @@
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Kbd({ className, ...props }: React.ComponentProps<"kbd">) {
|
||||
return (
|
||||
<kbd
|
||||
data-slot="kbd"
|
||||
className={cn(
|
||||
"pointer-events-none inline-flex h-5 w-fit min-w-5 items-center justify-center gap-1 rounded-sm bg-muted px-1 font-sans text-xs font-medium text-muted-foreground select-none",
|
||||
"[&_svg:not([class*='size-'])]:size-3",
|
||||
"[[data-slot=tooltip-content]_&]:bg-background/20 [[data-slot=tooltip-content]_&]:text-background dark:[[data-slot=tooltip-content]_&]:bg-background/10",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function KbdGroup({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<kbd
|
||||
data-slot="kbd-group"
|
||||
className={cn("inline-flex items-center gap-1", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Kbd, KbdGroup }
|
||||
@@ -0,0 +1,57 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { cn } from "@/lib/utils"
|
||||
import { ScrollArea as ScrollAreaPrimitive } from "radix-ui"
|
||||
|
||||
function ScrollArea({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ScrollAreaPrimitive.Root>) {
|
||||
return (
|
||||
<ScrollAreaPrimitive.Root
|
||||
data-slot="scroll-area"
|
||||
className={cn("relative", className)}
|
||||
{...props}
|
||||
>
|
||||
<ScrollAreaPrimitive.Viewport
|
||||
data-slot="scroll-area-viewport"
|
||||
className="size-full rounded-[inherit] [&>div]:block! transition-[color,box-shadow] outline-none focus-visible:ring-[3px] focus-visible:ring-ring/50 focus-visible:outline-1"
|
||||
>
|
||||
{children}
|
||||
</ScrollAreaPrimitive.Viewport>
|
||||
<ScrollBar />
|
||||
<ScrollAreaPrimitive.Corner />
|
||||
</ScrollAreaPrimitive.Root>
|
||||
)
|
||||
}
|
||||
|
||||
function ScrollBar({
|
||||
className,
|
||||
orientation = "vertical",
|
||||
...props
|
||||
}: React.ComponentProps<typeof ScrollAreaPrimitive.ScrollAreaScrollbar>) {
|
||||
return (
|
||||
<ScrollAreaPrimitive.ScrollAreaScrollbar
|
||||
data-slot="scroll-area-scrollbar"
|
||||
orientation={orientation}
|
||||
className={cn(
|
||||
"flex touch-none p-px transition-colors select-none",
|
||||
orientation === "vertical" &&
|
||||
"h-full w-2.5 border-l border-l-transparent",
|
||||
orientation === "horizontal" &&
|
||||
"h-2.5 flex-col border-t border-t-transparent",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<ScrollAreaPrimitive.ScrollAreaThumb
|
||||
data-slot="scroll-area-thumb"
|
||||
className="relative flex-1 rounded-full bg-border"
|
||||
/>
|
||||
</ScrollAreaPrimitive.ScrollAreaScrollbar>
|
||||
)
|
||||
}
|
||||
|
||||
export { ScrollArea, ScrollBar }
|
||||
@@ -0,0 +1,25 @@
|
||||
import * as React from "react"
|
||||
import { cn } from "@/lib/utils"
|
||||
import { Separator as SeparatorPrimitive } from "radix-ui"
|
||||
|
||||
function Separator({
|
||||
className,
|
||||
orientation = "horizontal",
|
||||
decorative = true,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SeparatorPrimitive.Root>) {
|
||||
return (
|
||||
<SeparatorPrimitive.Root
|
||||
data-slot="separator"
|
||||
decorative={decorative}
|
||||
orientation={orientation}
|
||||
className={cn(
|
||||
"shrink-0 bg-border data-[orientation=horizontal]:h-px data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-px",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Separator }
|
||||
@@ -0,0 +1,44 @@
|
||||
import * as React from "react"
|
||||
import { cva, type VariantProps } from "class-variance-authority"
|
||||
import { cn } from "@/lib/utils"
|
||||
import { Toggle as TogglePrimitive } from "radix-ui"
|
||||
|
||||
const toggleVariants = cva(
|
||||
"inline-flex items-center justify-center gap-2 rounded-md text-sm font-medium whitespace-nowrap transition-[color,box-shadow] outline-none hover:bg-muted hover:text-muted-foreground focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 data-[state=on]:bg-accent data-[state=on]:text-accent-foreground dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default: "bg-transparent",
|
||||
outline:
|
||||
"border border-input bg-transparent shadow-xs hover:bg-accent hover:text-accent-foreground",
|
||||
},
|
||||
size: {
|
||||
default: "h-9 min-w-9 px-2",
|
||||
sm: "h-8 min-w-8 px-1.5",
|
||||
lg: "h-10 min-w-10 px-2.5",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
size: "default",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
function Toggle({
|
||||
className,
|
||||
variant,
|
||||
size,
|
||||
...props
|
||||
}: React.ComponentProps<typeof TogglePrimitive.Root> &
|
||||
VariantProps<typeof toggleVariants>) {
|
||||
return (
|
||||
<TogglePrimitive.Root
|
||||
data-slot="toggle"
|
||||
className={cn(toggleVariants({ variant, size, className }))}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Toggle, toggleVariants }
|
||||
@@ -0,0 +1,56 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { cn } from "@/lib/utils"
|
||||
import { Tooltip as TooltipPrimitive } from "radix-ui"
|
||||
|
||||
function TooltipProvider({
|
||||
delayDuration = 0,
|
||||
...props
|
||||
}: React.ComponentProps<typeof TooltipPrimitive.Provider>) {
|
||||
return (
|
||||
<TooltipPrimitive.Provider
|
||||
data-slot="tooltip-provider"
|
||||
delayDuration={delayDuration}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function Tooltip({
|
||||
...props
|
||||
}: React.ComponentProps<typeof TooltipPrimitive.Root>) {
|
||||
return <TooltipPrimitive.Root data-slot="tooltip" {...props} />
|
||||
}
|
||||
|
||||
function TooltipTrigger({
|
||||
...props
|
||||
}: React.ComponentProps<typeof TooltipPrimitive.Trigger>) {
|
||||
return <TooltipPrimitive.Trigger data-slot="tooltip-trigger" {...props} />
|
||||
}
|
||||
|
||||
function TooltipContent({
|
||||
className,
|
||||
sideOffset = 0,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof TooltipPrimitive.Content>) {
|
||||
return (
|
||||
<TooltipPrimitive.Portal>
|
||||
<TooltipPrimitive.Content
|
||||
data-slot="tooltip-content"
|
||||
sideOffset={sideOffset}
|
||||
className={cn(
|
||||
"z-50 w-fit origin-(--radix-tooltip-content-transform-origin) animate-in rounded-md bg-foreground px-3 py-1.5 text-xs text-balance text-background fade-in-0 zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<TooltipPrimitive.Arrow className="z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px] bg-foreground fill-foreground" />
|
||||
</TooltipPrimitive.Content>
|
||||
</TooltipPrimitive.Portal>
|
||||
)
|
||||
}
|
||||
|
||||
export { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider }
|
||||
Vendored
+1
@@ -0,0 +1 @@
|
||||
declare module '*.css'
|
||||
Vendored
+9
@@ -0,0 +1,9 @@
|
||||
import type { StudioHost } from '../../shared/bridge'
|
||||
|
||||
declare global {
|
||||
interface Window {
|
||||
studio: StudioHost
|
||||
}
|
||||
}
|
||||
|
||||
export {}
|
||||
@@ -0,0 +1,6 @@
|
||||
import { clsx, type ClassValue } from 'clsx'
|
||||
import { twMerge } from 'tailwind-merge'
|
||||
|
||||
export function cn(...inputs: ClassValue[]): string {
|
||||
return twMerge(clsx(inputs))
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import { StrictMode } from 'react'
|
||||
import { createRoot } from 'react-dom/client'
|
||||
import { TooltipProvider } from '@/components/ui/tooltip'
|
||||
import { App } from './App'
|
||||
import './styles.css'
|
||||
|
||||
createRoot(document.getElementById('root')!).render(
|
||||
<StrictMode>
|
||||
<TooltipProvider delayDuration={400}>
|
||||
<App />
|
||||
</TooltipProvider>
|
||||
</StrictMode>
|
||||
)
|
||||
@@ -0,0 +1,406 @@
|
||||
import type { BridgeClient } from '../bridge/BridgeClient'
|
||||
import { gridIndex } from '../bridge/tileDecoding'
|
||||
import { NO_LABEL, type MapLabel, type Marker, type WorldInfo } from '../bridge/types'
|
||||
import { countShares, type PlacedTile, type Share } from './census'
|
||||
import { bandIndexOf, HEIGHT_BANDS } from './heightColors'
|
||||
import type { Highlight, TileStyle } from './tileStyle'
|
||||
import { TileStore, type TileLayer } from './TileStore'
|
||||
import {
|
||||
clampBlocksPerPixel,
|
||||
coarserTile,
|
||||
previewsFor,
|
||||
DEFAULT_BLOCKS_PER_PIXEL,
|
||||
renderBlocksPerPixel,
|
||||
screenToWorldX,
|
||||
screenToWorldZ,
|
||||
visibleTiles,
|
||||
worldToScreenX,
|
||||
worldToScreenZ,
|
||||
type TileAddress,
|
||||
type Viewport
|
||||
} from './viewport'
|
||||
|
||||
export interface MapStatus {
|
||||
blocksPerPixel: number
|
||||
widthBlocks: number
|
||||
heightBlocks: number
|
||||
tilesReady: number
|
||||
tilesTotal: number
|
||||
cursorX: number
|
||||
cursorZ: number
|
||||
}
|
||||
|
||||
export interface MapListener {
|
||||
onStatus(status: MapStatus): void
|
||||
onShares(shares: Share[]): void
|
||||
onError(message: string): void
|
||||
}
|
||||
|
||||
/** What the map shows at a spot, read from the tiles already drawn. */
|
||||
export interface SpotSubjects {
|
||||
subject: Highlight | null
|
||||
region: Highlight | null
|
||||
}
|
||||
|
||||
export interface MapToggles {
|
||||
shading: boolean
|
||||
regionBorders: boolean
|
||||
grid: boolean
|
||||
}
|
||||
|
||||
// While a tile is on its way, a coarser one already drawn stands in, up to this many zoom levels out.
|
||||
const COARSER_FALLBACK_LEVELS = 6
|
||||
const CENSUS_INTERVAL_MILLIS = 250
|
||||
const CHUNK_BLOCKS = 16
|
||||
const REGION_BLOCKS = 512
|
||||
const SMALLEST_GRID_GAP_PIXELS = 8
|
||||
const CHUNK_LINE = 'rgba(255, 255, 255, 0.14)'
|
||||
const REGION_LINE = 'rgba(255, 255, 255, 0.38)'
|
||||
const PLAYER_FILL = '#3574f0'
|
||||
const ENTITY_FILL = '#f75464'
|
||||
const MARKER_OUTLINE = '#ffffff'
|
||||
const PLAYER_RADIUS_PIXELS = 6
|
||||
const ENTITY_RADIUS_PIXELS = 3
|
||||
|
||||
/**
|
||||
* The 2D map on a canvas: which tiles to fetch for the view, drawing them in the current style, and the grid and
|
||||
* markers on top. Kept outside React, as it redraws on every drag and wheel step.
|
||||
*/
|
||||
export class MapController {
|
||||
private readonly context: CanvasRenderingContext2D
|
||||
private readonly store: TileStore
|
||||
private readonly view: Viewport = { centerX: 0, centerZ: 0, blocksPerPixel: DEFAULT_BLOCKS_PER_PIXEL, width: 1, height: 1 }
|
||||
private layer: TileLayer
|
||||
private toggles: MapToggles = { shading: true, regionBorders: false, grid: false }
|
||||
private highlight: Highlight | null = null
|
||||
private players: Marker[] = []
|
||||
private entities: Marker[] = []
|
||||
private cursor: { x: number; y: number } | null = null
|
||||
private frameRequested = false
|
||||
private lastCensusMillis = 0
|
||||
private censusTimer: number | undefined
|
||||
private closed = false
|
||||
|
||||
constructor(
|
||||
private readonly canvas: HTMLCanvasElement,
|
||||
client: BridgeClient,
|
||||
private readonly world: WorldInfo,
|
||||
view: string,
|
||||
private readonly listener: MapListener
|
||||
) {
|
||||
this.context = canvas.getContext('2d')!
|
||||
this.layer = { view, heights: this.needsHeights(view, this.toggles), revision: 0 }
|
||||
this.store = new TileStore(client, world.tileSize, () => this.redraw(), (message) => listener.onError(message))
|
||||
}
|
||||
|
||||
close(): void {
|
||||
this.closed = true
|
||||
window.clearTimeout(this.censusTimer)
|
||||
this.store.clear()
|
||||
}
|
||||
|
||||
resize(width: number, height: number): void {
|
||||
const ratio = window.devicePixelRatio
|
||||
this.canvas.width = Math.round(width * ratio)
|
||||
this.canvas.height = Math.round(height * ratio)
|
||||
this.view.width = width
|
||||
this.view.height = height
|
||||
this.redraw()
|
||||
}
|
||||
|
||||
setView(view: string): void {
|
||||
this.layer = { ...this.layer, view, heights: this.needsHeights(view, this.toggles) }
|
||||
this.redraw()
|
||||
}
|
||||
|
||||
setToggles(toggles: MapToggles): void {
|
||||
this.toggles = toggles
|
||||
this.layer = { ...this.layer, heights: this.needsHeights(this.layer.view, toggles) }
|
||||
this.redraw()
|
||||
}
|
||||
|
||||
// Heights are the costly part of a tile, so they are only asked for when something draws with them.
|
||||
private needsHeights(view: string, toggles: MapToggles): boolean {
|
||||
return toggles.shading || view === 'height'
|
||||
}
|
||||
|
||||
setHighlight(highlight: Highlight | null): void {
|
||||
this.highlight = highlight
|
||||
this.redraw()
|
||||
}
|
||||
|
||||
setMarkers(players: Marker[], entities: Marker[]): void {
|
||||
this.players = players
|
||||
this.entities = entities
|
||||
this.redraw()
|
||||
}
|
||||
|
||||
setCursor(cursor: { x: number; y: number } | null): void {
|
||||
this.cursor = cursor
|
||||
this.reportStatus()
|
||||
}
|
||||
|
||||
/** Draws everything again from the server, after the pack changed. */
|
||||
refresh(): void {
|
||||
this.store.clear()
|
||||
this.layer = { ...this.layer, revision: this.layer.revision + 1 }
|
||||
this.redraw()
|
||||
}
|
||||
|
||||
panBy(screenDeltaX: number, screenDeltaZ: number): void {
|
||||
this.view.centerX -= screenDeltaX * this.view.blocksPerPixel
|
||||
this.view.centerZ -= screenDeltaZ * this.view.blocksPerPixel
|
||||
this.redraw()
|
||||
}
|
||||
|
||||
centerOn(worldX: number, worldZ: number): void {
|
||||
this.view.centerX = worldX
|
||||
this.view.centerZ = worldZ
|
||||
this.redraw()
|
||||
}
|
||||
|
||||
/** Zooms by {@code factor} (above 1 zooms in) keeping the world spot under the screen point where it is. */
|
||||
zoomAt(factor: number, screenX = this.view.width / 2, screenZ = this.view.height / 2): void {
|
||||
const worldX = screenToWorldX(this.view, screenX)
|
||||
const worldZ = screenToWorldZ(this.view, screenZ)
|
||||
this.view.blocksPerPixel = clampBlocksPerPixel(this.view.blocksPerPixel / factor)
|
||||
this.view.centerX = worldX - (screenX - this.view.width / 2) * this.view.blocksPerPixel
|
||||
this.view.centerZ = worldZ - (screenZ - this.view.height / 2) * this.view.blocksPerPixel
|
||||
this.redraw()
|
||||
}
|
||||
|
||||
resetZoom(): void {
|
||||
this.view.blocksPerPixel = DEFAULT_BLOCKS_PER_PIXEL
|
||||
this.redraw()
|
||||
}
|
||||
|
||||
worldAt(screenX: number, screenZ: number): { x: number; z: number } {
|
||||
return { x: screenToWorldX(this.view, screenX), z: screenToWorldZ(this.view, screenZ) }
|
||||
}
|
||||
|
||||
/** The biome or region and the region at a screen point, from the tile drawn there; nulls before it arrived. */
|
||||
subjectsAt(screenX: number, screenZ: number): SpotSubjects {
|
||||
const worldX = screenToWorldX(this.view, screenX)
|
||||
const worldZ = screenToWorldZ(this.view, screenZ)
|
||||
const scale = this.renderScale()
|
||||
const span = this.world.tileSize * scale
|
||||
const address = { tileX: Math.floor(worldX / span), tileZ: Math.floor(worldZ / span), blocksPerPixel: scale }
|
||||
const tile = this.store.get(address, this.layer)
|
||||
if (tile === null) {
|
||||
return { subject: null, region: null }
|
||||
}
|
||||
const pixelX = Math.min(tile.size - 1, Math.floor((worldX - address.tileX * span) / scale))
|
||||
const pixelZ = Math.min(tile.size - 1, Math.floor((worldZ - address.tileZ * span) / scale))
|
||||
const cell = gridIndex(tile, pixelX, pixelZ)
|
||||
const region = labelAt(tile.labels, tile.regions[cell])
|
||||
if (this.isHeightView() && tile.heights !== null) {
|
||||
const band = HEIGHT_BANDS[bandIndexOf(tile.heights[cell], this.world.fluidHeight)]
|
||||
return { subject: { kind: 'HEIGHT', key: band.key, name: band.name }, region }
|
||||
}
|
||||
return { subject: labelAt(tile.labels, tile.subjects[cell]), region }
|
||||
}
|
||||
|
||||
private isHeightView(): boolean {
|
||||
return this.layer.view === 'height'
|
||||
}
|
||||
|
||||
private renderScale(): number {
|
||||
return renderBlocksPerPixel(this.view.blocksPerPixel, window.devicePixelRatio)
|
||||
}
|
||||
|
||||
private style(): TileStyle {
|
||||
return {
|
||||
byHeight: this.isHeightView(),
|
||||
shading: this.toggles.shading,
|
||||
regionBorders: this.toggles.regionBorders,
|
||||
highlight: this.highlight,
|
||||
seaLevel: this.world.fluidHeight
|
||||
}
|
||||
}
|
||||
|
||||
private redraw(): void {
|
||||
if (this.frameRequested || this.closed) {
|
||||
return
|
||||
}
|
||||
this.frameRequested = true
|
||||
requestAnimationFrame(() => {
|
||||
this.frameRequested = false
|
||||
if (!this.closed) {
|
||||
this.draw()
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
private draw(): void {
|
||||
const ratio = window.devicePixelRatio
|
||||
const context = this.context
|
||||
context.setTransform(ratio, 0, 0, ratio, 0, 0)
|
||||
context.fillStyle = getComputedStyle(this.canvas).getPropertyValue('--map-background') || '#16171a'
|
||||
context.fillRect(0, 0, this.view.width, this.view.height)
|
||||
|
||||
const scale = this.renderScale()
|
||||
const tiles = visibleTiles(this.view, scale, this.world.tileSize)
|
||||
const style = this.style()
|
||||
context.imageSmoothingEnabled = this.view.blocksPerPixel > scale
|
||||
let ready = 0
|
||||
const blank: TileAddress[] = []
|
||||
for (const address of tiles) {
|
||||
const picture = this.store.picture(address, this.layer, style)
|
||||
if (picture !== null) {
|
||||
this.drawTile(picture, address, 0, 0, picture.width)
|
||||
ready++
|
||||
} else if (!this.drawFallback(address, style)) {
|
||||
blank.push(address)
|
||||
}
|
||||
}
|
||||
this.store.want([...previewsFor(blank), ...tiles], this.layer)
|
||||
if (this.toggles.grid) {
|
||||
this.drawGrid()
|
||||
}
|
||||
this.drawMarkers()
|
||||
this.reportStatus(ready, tiles.length)
|
||||
this.scheduleCensus(tiles)
|
||||
}
|
||||
|
||||
/** Draws the part of a tile picture from (sourceX, sourceZ), {@code sourceSize} pixels wide, over {@code address}. */
|
||||
private drawTile(picture: HTMLCanvasElement, address: TileAddress, sourceX: number, sourceZ: number, sourceSize: number): void {
|
||||
const span = this.world.tileSize * address.blocksPerPixel
|
||||
const left = Math.round(worldToScreenX(this.view, address.tileX * span))
|
||||
const top = Math.round(worldToScreenZ(this.view, address.tileZ * span))
|
||||
const right = Math.round(worldToScreenX(this.view, (address.tileX + 1) * span))
|
||||
const bottom = Math.round(worldToScreenZ(this.view, (address.tileZ + 1) * span))
|
||||
this.context.drawImage(picture, sourceX, sourceZ, sourceSize, sourceSize, left, top, right - left, bottom - top)
|
||||
}
|
||||
|
||||
/** Draws the part of a coarser tile that covers {@code address}; false when no coarser tile has arrived either. */
|
||||
private drawFallback(address: TileAddress, style: TileStyle): boolean {
|
||||
for (let levels = 1; levels <= COARSER_FALLBACK_LEVELS; levels++) {
|
||||
const coarser = coarserTile(address, levels)
|
||||
const picture = this.store.picture(coarser, this.layer, style)
|
||||
if (picture === null) {
|
||||
continue
|
||||
}
|
||||
const factor = 2 ** levels
|
||||
const sourceSize = picture.width / factor
|
||||
const sourceX = (address.tileX - coarser.tileX * factor) * sourceSize
|
||||
const sourceZ = (address.tileZ - coarser.tileZ * factor) * sourceSize
|
||||
this.drawTile(picture, address, sourceX, sourceZ, sourceSize)
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
private drawGrid(): void {
|
||||
this.drawLines(CHUNK_BLOCKS, CHUNK_LINE, 1)
|
||||
this.drawLines(REGION_BLOCKS, REGION_LINE, 1.5)
|
||||
}
|
||||
|
||||
private drawLines(gapBlocks: number, color: string, width: number): void {
|
||||
if (gapBlocks / this.view.blocksPerPixel < SMALLEST_GRID_GAP_PIXELS) {
|
||||
return
|
||||
}
|
||||
const context = this.context
|
||||
context.strokeStyle = color
|
||||
context.lineWidth = width
|
||||
context.beginPath()
|
||||
const firstX = Math.ceil(screenToWorldX(this.view, 0) / gapBlocks) * gapBlocks
|
||||
for (let worldX = firstX; worldX <= screenToWorldX(this.view, this.view.width); worldX += gapBlocks) {
|
||||
const screenX = Math.round(worldToScreenX(this.view, worldX)) + 0.5
|
||||
context.moveTo(screenX, 0)
|
||||
context.lineTo(screenX, this.view.height)
|
||||
}
|
||||
const firstZ = Math.ceil(screenToWorldZ(this.view, 0) / gapBlocks) * gapBlocks
|
||||
for (let worldZ = firstZ; worldZ <= screenToWorldZ(this.view, this.view.height); worldZ += gapBlocks) {
|
||||
const screenZ = Math.round(worldToScreenZ(this.view, worldZ)) + 0.5
|
||||
context.moveTo(0, screenZ)
|
||||
context.lineTo(this.view.width, screenZ)
|
||||
}
|
||||
context.stroke()
|
||||
}
|
||||
|
||||
private drawMarkers(): void {
|
||||
for (const entity of this.entities) {
|
||||
this.drawMarker(entity, ENTITY_FILL, ENTITY_RADIUS_PIXELS, false)
|
||||
}
|
||||
for (const player of this.players) {
|
||||
this.drawMarker(player, PLAYER_FILL, PLAYER_RADIUS_PIXELS, true)
|
||||
}
|
||||
}
|
||||
|
||||
private drawMarker(marker: Marker, fill: string, radius: number, named: boolean): void {
|
||||
const context = this.context
|
||||
const x = worldToScreenX(this.view, marker.worldX)
|
||||
const z = worldToScreenZ(this.view, marker.worldZ)
|
||||
context.beginPath()
|
||||
context.arc(x, z, radius, 0, Math.PI * 2)
|
||||
context.fillStyle = fill
|
||||
context.fill()
|
||||
context.lineWidth = 2
|
||||
context.strokeStyle = MARKER_OUTLINE
|
||||
context.stroke()
|
||||
if (!named) {
|
||||
return
|
||||
}
|
||||
context.font = '600 12px Inter, "Segoe UI", system-ui, sans-serif'
|
||||
context.textAlign = 'center'
|
||||
context.lineWidth = 3
|
||||
context.strokeStyle = 'rgba(0, 0, 0, 0.7)'
|
||||
context.strokeText(marker.label, x, z - radius - 6)
|
||||
context.fillStyle = MARKER_OUTLINE
|
||||
context.fillText(marker.label, x, z - radius - 6)
|
||||
}
|
||||
|
||||
private lastReady = 0
|
||||
private lastTotal = 0
|
||||
|
||||
private reportStatus(ready = this.lastReady, total = this.lastTotal): void {
|
||||
this.lastReady = ready
|
||||
this.lastTotal = total
|
||||
const cursor = this.cursor === null ? { x: this.view.width / 2, y: this.view.height / 2 } : this.cursor
|
||||
this.listener.onStatus({
|
||||
blocksPerPixel: this.view.blocksPerPixel,
|
||||
widthBlocks: Math.round(this.view.width * this.view.blocksPerPixel),
|
||||
heightBlocks: Math.round(this.view.height * this.view.blocksPerPixel),
|
||||
tilesReady: ready,
|
||||
tilesTotal: total,
|
||||
cursorX: Math.floor(screenToWorldX(this.view, cursor.x)),
|
||||
cursorZ: Math.floor(screenToWorldZ(this.view, cursor.y))
|
||||
})
|
||||
}
|
||||
|
||||
// Counting what is on screen is cheap but not free, so it runs at most a few times a second and once more at rest.
|
||||
private scheduleCensus(tiles: TileAddress[]): void {
|
||||
window.clearTimeout(this.censusTimer)
|
||||
const wait = Math.max(0, this.lastCensusMillis + CENSUS_INTERVAL_MILLIS - performance.now())
|
||||
this.censusTimer = window.setTimeout(() => {
|
||||
this.lastCensusMillis = performance.now()
|
||||
this.listener.onShares(this.census(tiles))
|
||||
}, wait)
|
||||
}
|
||||
|
||||
private census(tiles: TileAddress[]): Share[] {
|
||||
const placed: PlacedTile[] = []
|
||||
for (const address of tiles) {
|
||||
const tile = this.store.get(address, this.layer)
|
||||
if (tile !== null) {
|
||||
const span = this.world.tileSize * address.blocksPerPixel
|
||||
placed.push({ tile, worldX: address.tileX * span, worldZ: address.tileZ * span })
|
||||
}
|
||||
}
|
||||
const area = {
|
||||
minimumX: screenToWorldX(this.view, 0),
|
||||
minimumZ: screenToWorldZ(this.view, 0),
|
||||
maximumX: screenToWorldX(this.view, this.view.width),
|
||||
maximumZ: screenToWorldZ(this.view, this.view.height)
|
||||
}
|
||||
return countShares(placed, area, this.isHeightView(), this.world.fluidHeight)
|
||||
}
|
||||
}
|
||||
|
||||
function labelAt(labels: MapLabel[], index: number): Highlight | null {
|
||||
if (index === NO_LABEL) {
|
||||
return null
|
||||
}
|
||||
const label = labels[index]
|
||||
return { kind: label.kind, key: label.key, name: label.name }
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
import { BridgeError, type BridgeClient } from '../bridge/BridgeClient'
|
||||
import type { MapTile } from '../bridge/types'
|
||||
import { stylePixels, styleKey, type TileStyle } from './tileStyle'
|
||||
import type { TileAddress } from './viewport'
|
||||
|
||||
/** What one tile request needs besides where the tile is. */
|
||||
export interface TileLayer {
|
||||
view: string
|
||||
heights: boolean
|
||||
/** Bumped when the pack is hotloaded, so older tiles are not used again. */
|
||||
revision: number
|
||||
}
|
||||
|
||||
interface StoredTile {
|
||||
tile: MapTile
|
||||
bytes: number
|
||||
lastUsed: number
|
||||
picture: HTMLCanvasElement | null
|
||||
pictureStyle: string
|
||||
}
|
||||
|
||||
// Drawing a few hundred tiles at once only queues them on the server; a handful in flight keeps it busy.
|
||||
const MAXIMUM_IN_FLIGHT = 6
|
||||
const CACHE_BYTES = 256 * 1024 * 1024
|
||||
|
||||
/**
|
||||
* The map's tiles: fetched from the bridge as the view needs them, kept within a memory budget, and drawn as the
|
||||
* current style asks. A tile that leaves the view before it arrives is not fetched.
|
||||
*/
|
||||
export class TileStore {
|
||||
private readonly tiles = new Map<string, StoredTile>()
|
||||
private readonly inFlight = new Map<string, AbortController>()
|
||||
/** Asked for again only after a refresh, which changes every key, so a broken tile is not fetched on every frame. */
|
||||
private readonly failed = new Set<string>()
|
||||
private wanted: { key: string; address: TileAddress; layer: TileLayer }[] = []
|
||||
private storedBytes = 0
|
||||
private useClock = 0
|
||||
|
||||
constructor(
|
||||
private readonly client: BridgeClient,
|
||||
private readonly tileSize: number,
|
||||
private readonly onChange: () => void,
|
||||
private readonly onError: (message: string) => void
|
||||
) {}
|
||||
|
||||
key(address: TileAddress, layer: TileLayer): string {
|
||||
return `${layer.revision}/${layer.view}/${layer.heights}/${address.blocksPerPixel}/${address.tileX}/${address.tileZ}`
|
||||
}
|
||||
|
||||
/** The tile if it has arrived, marked as just used. */
|
||||
get(address: TileAddress, layer: TileLayer): MapTile | null {
|
||||
const stored = this.tiles.get(this.key(address, layer))
|
||||
if (stored === undefined) {
|
||||
return null
|
||||
}
|
||||
stored.lastUsed = ++this.useClock
|
||||
return stored.tile
|
||||
}
|
||||
|
||||
/** The tile drawn in {@code style}; restyled only when the style changed since it was last drawn. */
|
||||
picture(address: TileAddress, layer: TileLayer, style: TileStyle): HTMLCanvasElement | null {
|
||||
const stored = this.tiles.get(this.key(address, layer))
|
||||
if (stored === undefined) {
|
||||
return null
|
||||
}
|
||||
stored.lastUsed = ++this.useClock
|
||||
const wantedStyle = styleKey(style)
|
||||
if (stored.picture === null || stored.pictureStyle !== wantedStyle) {
|
||||
stored.picture = stored.picture ?? document.createElement('canvas')
|
||||
paint(stored.picture, stored.tile, style)
|
||||
stored.pictureStyle = wantedStyle
|
||||
}
|
||||
return stored.picture
|
||||
}
|
||||
|
||||
/** Fetches the tiles the view shows, in the order given, and gives up on the ones it no longer shows. */
|
||||
want(addresses: TileAddress[], layer: TileLayer): void {
|
||||
this.wanted = addresses
|
||||
.map((address) => ({ key: this.key(address, layer), address, layer }))
|
||||
.filter((entry) => !this.tiles.has(entry.key) && !this.failed.has(entry.key))
|
||||
const stillWanted = new Set(this.wanted.map((entry) => entry.key))
|
||||
for (const [key, controller] of this.inFlight) {
|
||||
if (!stillWanted.has(key)) {
|
||||
controller.abort()
|
||||
this.inFlight.delete(key)
|
||||
}
|
||||
}
|
||||
this.startRequests()
|
||||
}
|
||||
|
||||
/** How many of the wanted tiles are still on their way. */
|
||||
pending(): number {
|
||||
return this.wanted.length
|
||||
}
|
||||
|
||||
clear(): void {
|
||||
for (const controller of this.inFlight.values()) {
|
||||
controller.abort()
|
||||
}
|
||||
this.inFlight.clear()
|
||||
this.failed.clear()
|
||||
this.tiles.clear()
|
||||
this.wanted = []
|
||||
this.storedBytes = 0
|
||||
}
|
||||
|
||||
private startRequests(): void {
|
||||
for (const entry of this.wanted) {
|
||||
if (this.inFlight.size >= MAXIMUM_IN_FLIGHT) {
|
||||
return
|
||||
}
|
||||
if (!this.inFlight.has(entry.key)) {
|
||||
this.fetchTile(entry.key, entry.address, entry.layer)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fetchTile(key: string, address: TileAddress, layer: TileLayer): void {
|
||||
const controller = new AbortController()
|
||||
this.inFlight.set(key, controller)
|
||||
const request = { view: layer.view, ...address, size: this.tileSize, heights: layer.heights }
|
||||
this.client
|
||||
.tile(request, controller.signal)
|
||||
.then((tile) => this.store(key, tile))
|
||||
.catch((error: unknown) => {
|
||||
if (!controller.signal.aborted) {
|
||||
this.failed.add(key)
|
||||
this.onError(error instanceof BridgeError ? error.message : 'The server did not answer')
|
||||
}
|
||||
})
|
||||
.finally(() => {
|
||||
if (this.inFlight.get(key) === controller) {
|
||||
this.inFlight.delete(key)
|
||||
}
|
||||
this.wanted = this.wanted.filter((entry) => entry.key !== key)
|
||||
this.startRequests()
|
||||
this.onChange()
|
||||
})
|
||||
}
|
||||
|
||||
private store(key: string, tile: MapTile): void {
|
||||
const bytes = tile.subjects.byteLength * 2 + (tile.heights?.byteLength ?? 0) + tile.size * tile.size * 4
|
||||
this.tiles.set(key, { tile, bytes, lastUsed: ++this.useClock, picture: null, pictureStyle: '' })
|
||||
this.storedBytes += bytes
|
||||
this.evictOldest()
|
||||
}
|
||||
|
||||
private evictOldest(): void {
|
||||
if (this.storedBytes <= CACHE_BYTES) {
|
||||
return
|
||||
}
|
||||
const byAge = [...this.tiles.entries()].sort((first, second) => first[1].lastUsed - second[1].lastUsed)
|
||||
for (const [key, stored] of byAge) {
|
||||
if (this.storedBytes <= CACHE_BYTES * 0.8) {
|
||||
return
|
||||
}
|
||||
this.tiles.delete(key)
|
||||
this.storedBytes -= stored.bytes
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function paint(canvas: HTMLCanvasElement, tile: MapTile, style: TileStyle): void {
|
||||
canvas.width = tile.size
|
||||
canvas.height = tile.size
|
||||
canvas.getContext('2d')!.putImageData(new ImageData(stylePixels(tile, style), tile.size, tile.size), 0, 0)
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
import { gridIndex } from '../bridge/tileDecoding'
|
||||
import { NO_LABEL, type MapTile } from '../bridge/types'
|
||||
import { bandIndexOf, HEIGHT_BANDS } from './heightColors'
|
||||
import type { Highlight } from './tileStyle'
|
||||
|
||||
/** How much of the screen one biome, region or height band covers. */
|
||||
export interface Share {
|
||||
subject: Highlight
|
||||
color: number
|
||||
fraction: number
|
||||
}
|
||||
|
||||
/** A loaded tile and where its top left pixel lies in the world. */
|
||||
export interface PlacedTile {
|
||||
tile: MapTile
|
||||
worldX: number
|
||||
worldZ: number
|
||||
}
|
||||
|
||||
export interface WorldArea {
|
||||
minimumX: number
|
||||
minimumZ: number
|
||||
maximumX: number
|
||||
maximumZ: number
|
||||
}
|
||||
|
||||
// Enough samples that a share is right to a fraction of a percent, few enough to count every frame the map settles.
|
||||
const MAXIMUM_COUNTED_PIXELS = 250_000
|
||||
|
||||
/**
|
||||
* The shares of what the tiles show inside {@code area}, largest first: their subjects (biomes or regions), or their
|
||||
* height bands when {@code byHeight} is set.
|
||||
*/
|
||||
export function countShares(tiles: PlacedTile[], area: WorldArea, byHeight: boolean, seaLevel: number): Share[] {
|
||||
const counts = new Map<string, { subject: Highlight; color: number; count: number }>()
|
||||
const totalPixels = tiles.reduce((sum, placed) => sum + placed.tile.size * placed.tile.size, 0)
|
||||
const stride = Math.max(1, Math.ceil(Math.sqrt(totalPixels / MAXIMUM_COUNTED_PIXELS)))
|
||||
let counted = 0
|
||||
for (const { tile, worldX, worldZ } of tiles) {
|
||||
const scale = tile.blocksPerPixel
|
||||
const firstX = Math.max(0, Math.ceil((area.minimumX - worldX) / scale))
|
||||
const endX = Math.min(tile.size, Math.ceil((area.maximumX - worldX) / scale))
|
||||
const firstZ = Math.max(0, Math.ceil((area.minimumZ - worldZ) / scale))
|
||||
const endZ = Math.min(tile.size, Math.ceil((area.maximumZ - worldZ) / scale))
|
||||
for (let pixelZ = firstZ; pixelZ < endZ; pixelZ += stride) {
|
||||
for (let pixelX = firstX; pixelX < endX; pixelX += stride) {
|
||||
const subject = subjectAt(tile, gridIndex(tile, pixelX, pixelZ), byHeight, seaLevel)
|
||||
if (subject === null) {
|
||||
continue
|
||||
}
|
||||
const id = `${subject.subject.kind}:${subject.subject.key}`
|
||||
const entry = counts.get(id) ?? { ...subject, count: 0 }
|
||||
entry.count++
|
||||
counts.set(id, entry)
|
||||
counted++
|
||||
}
|
||||
}
|
||||
}
|
||||
return [...counts.values()]
|
||||
.map((entry) => ({ subject: entry.subject, color: entry.color, fraction: entry.count / Math.max(1, counted) }))
|
||||
.sort((first, second) => second.fraction - first.fraction)
|
||||
}
|
||||
|
||||
function subjectAt(tile: MapTile, cell: number, byHeight: boolean, seaLevel: number): { subject: Highlight; color: number } | null {
|
||||
if (byHeight) {
|
||||
if (tile.heights === null) {
|
||||
return null
|
||||
}
|
||||
const band = HEIGHT_BANDS[bandIndexOf(tile.heights[cell], seaLevel)]
|
||||
return { subject: { kind: 'HEIGHT', key: band.key, name: band.name }, color: band.color }
|
||||
}
|
||||
const index = tile.subjects[cell]
|
||||
if (index === NO_LABEL) {
|
||||
return null
|
||||
}
|
||||
const label = tile.labels[index]
|
||||
return { subject: { kind: label.kind, key: label.key, name: label.name }, color: label.color }
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
/** The height scale of the map, from deep water to snowy peaks, measured from sea level (v3e HeightColors). */
|
||||
|
||||
const DEEPEST_BELOW_SEA_BLOCKS = 90
|
||||
const HIGHEST_ABOVE_SEA_BLOCKS = 300
|
||||
const DEPTH_BLOCKS = [0, 10, 40, DEEPEST_BELOW_SEA_BLOCKS]
|
||||
const DEPTH_COLORS = [0x7db8d8, 0x4c8dba, 0x2a5e8f, 0x15304f]
|
||||
const ABOVE_SEA_BLOCKS = [0, 8, 30, 70, 130, 200, HIGHEST_ABOVE_SEA_BLOCKS]
|
||||
const LAND_COLORS = [0x7fa35a, 0x5e8c44, 0x8fa65a, 0xc2ae78, 0x8e7663, 0xa9a6a2, 0xf4f4f4]
|
||||
// Where each band ends, in blocks above sea; they follow the colour stops, merging the deepest two.
|
||||
const BAND_TOPS_ABOVE_SEA = [-40, -10, 0, 8, 30, 70, 130, 200, 300, Number.POSITIVE_INFINITY]
|
||||
|
||||
/** A stretch of heights between two of the scale's stops, for telling how much ground lies at each height. */
|
||||
export interface HeightBand {
|
||||
/** The band's place from the deepest, as text that sorts the same way. */
|
||||
key: string
|
||||
name: string
|
||||
color: number
|
||||
}
|
||||
|
||||
export function heightColor(height: number, seaLevel: number): number {
|
||||
if (height <= seaLevel) {
|
||||
return along(DEPTH_BLOCKS, DEPTH_COLORS, seaLevel - height)
|
||||
}
|
||||
return along(ABOVE_SEA_BLOCKS, LAND_COLORS, height - seaLevel)
|
||||
}
|
||||
|
||||
export const HEIGHT_BANDS: readonly HeightBand[] = createBands()
|
||||
|
||||
export function bandIndexOf(height: number, seaLevel: number): number {
|
||||
const aboveSea = height - seaLevel
|
||||
const index = BAND_TOPS_ABOVE_SEA.findIndex((top) => aboveSea <= top)
|
||||
return index < 0 ? BAND_TOPS_ABOVE_SEA.length - 1 : index
|
||||
}
|
||||
|
||||
function createBands(): HeightBand[] {
|
||||
const bands: HeightBand[] = []
|
||||
let bottom = -DEEPEST_BELOW_SEA_BLOCKS
|
||||
BAND_TOPS_ABOVE_SEA.forEach((top, band) => {
|
||||
const colorHeight = Number.isFinite(top) ? (bottom + top) / 2 : bottom
|
||||
bands.push({ key: String(band).padStart(2, '0'), name: bandName(band, bottom, top), color: heightColor(colorHeight, 0) })
|
||||
bottom = top
|
||||
})
|
||||
return bands
|
||||
}
|
||||
|
||||
function bandName(band: number, bottom: number, top: number): string {
|
||||
if (band === 0) {
|
||||
return `${Math.round(-top)}+ below sea`
|
||||
}
|
||||
if (!Number.isFinite(top)) {
|
||||
return `${Math.round(bottom)}+ above sea`
|
||||
}
|
||||
if (top <= 0) {
|
||||
return `${Math.round(-top)}–${Math.round(-bottom)} below sea`
|
||||
}
|
||||
return `${Math.round(bottom)}–${Math.round(top)} above sea`
|
||||
}
|
||||
|
||||
function along(stops: number[], colors: number[], blocks: number): number {
|
||||
if (blocks <= stops[0]) {
|
||||
return colors[0]
|
||||
}
|
||||
for (let stop = 1; stop < stops.length; stop++) {
|
||||
if (blocks <= stops[stop]) {
|
||||
return blend(colors[stop - 1], colors[stop], (blocks - stops[stop - 1]) / (stops[stop] - stops[stop - 1]))
|
||||
}
|
||||
}
|
||||
return colors[colors.length - 1]
|
||||
}
|
||||
|
||||
export function blend(first: number, second: number, amount: number): number {
|
||||
const red = Math.round(((first >> 16) & 0xff) * (1 - amount) + ((second >> 16) & 0xff) * amount)
|
||||
const green = Math.round(((first >> 8) & 0xff) * (1 - amount) + ((second >> 8) & 0xff) * amount)
|
||||
const blue = Math.round((first & 0xff) * (1 - amount) + (second & 0xff) * amount)
|
||||
return (red << 16) | (green << 8) | blue
|
||||
}
|
||||
@@ -0,0 +1,178 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { decodeTile, gridIndex } from '../bridge/tileDecoding'
|
||||
import type { MapLabel, MapTile } from '../bridge/types'
|
||||
import { countShares } from './census'
|
||||
import { bandIndexOf, HEIGHT_BANDS, heightColor } from './heightColors'
|
||||
import { stylePixels, type TileStyle } from './tileStyle'
|
||||
import { coarserTile, previewsFor, renderBlocksPerPixel, screenToWorldX, visibleTiles, worldToScreenX, type Viewport } from './viewport'
|
||||
|
||||
const PLAINS: MapLabel = { kind: 'BIOME', key: 'plains', name: 'Plains', color: 0x00ff00 }
|
||||
const DESERT: MapLabel = { kind: 'BIOME', key: 'desert', name: 'Desert', color: 0xffff00 }
|
||||
const WARM: MapLabel = { kind: 'REGION', key: 'warm', name: 'Warm', color: 0xff0000 }
|
||||
const FLAT: TileStyle = { byHeight: false, shading: false, regionBorders: false, highlight: null, seaLevel: 63 }
|
||||
|
||||
/** A tile whose left half is plains and right half desert, all in one region, at height 70. */
|
||||
function splitTile(size = 4): MapTile {
|
||||
const cells = (size + 2) ** 2
|
||||
const subjects = new Int16Array(cells)
|
||||
for (let cell = 0; cell < cells; cell++) {
|
||||
subjects[cell] = cell % (size + 2) <= size / 2 ? 0 : 1
|
||||
}
|
||||
return {
|
||||
size,
|
||||
blocksPerPixel: 1,
|
||||
subjectKind: 'BIOME',
|
||||
labels: [PLAINS, DESERT, WARM],
|
||||
subjects,
|
||||
regions: new Int16Array(cells).fill(2),
|
||||
heights: new Float32Array(cells).fill(70)
|
||||
}
|
||||
}
|
||||
|
||||
/** A tile as the bridge sends it: u32 header length, JSON header, aligned grids. */
|
||||
function encode(size: number, withHeights: boolean): ArrayBuffer {
|
||||
const header = new TextEncoder().encode(JSON.stringify({ size, blocksPerPixel: 2, subjectKind: 'BIOME', labels: [PLAINS], heights: withHeights }))
|
||||
const cells = (size + 2) ** 2
|
||||
const align = (bytes: number): number => Math.ceil(bytes / 4) * 4
|
||||
const subjectsAt = align(4 + header.length)
|
||||
const regionsAt = align(subjectsAt + cells * 2)
|
||||
const heightsAt = align(regionsAt + cells * 2)
|
||||
const buffer = new ArrayBuffer(heightsAt + (withHeights ? cells * 4 : 0))
|
||||
new DataView(buffer).setUint32(0, header.length, true)
|
||||
new Uint8Array(buffer, 4).set(header)
|
||||
new Int16Array(buffer, subjectsAt, cells).fill(0)
|
||||
new Int16Array(buffer, regionsAt, cells).fill(-1)
|
||||
if (withHeights) {
|
||||
new Float32Array(buffer, heightsAt, cells).fill(81.5)
|
||||
}
|
||||
return buffer
|
||||
}
|
||||
|
||||
describe('tile decoding', () => {
|
||||
it('reads the header and views each grid where the bridge put it', () => {
|
||||
const tile = decodeTile(encode(3, true))
|
||||
|
||||
expect(tile.size).toBe(3)
|
||||
expect(tile.blocksPerPixel).toBe(2)
|
||||
expect(tile.labels[0].key).toBe('plains')
|
||||
expect(tile.subjects.length).toBe(25)
|
||||
expect(tile.regions[0]).toBe(-1)
|
||||
expect(tile.heights?.[24]).toBe(81.5)
|
||||
})
|
||||
|
||||
it('has no heights when the header says so', () => {
|
||||
expect(decodeTile(encode(3, false)).heights).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('height colours', () => {
|
||||
it('runs from deep water to snow and stays at the ends beyond them', () => {
|
||||
expect(heightColor(63, 63)).toBe(0x7db8d8)
|
||||
expect(heightColor(-1000, 63)).toBe(0x15304f)
|
||||
expect(heightColor(1000, 63)).toBe(0xf4f4f4)
|
||||
})
|
||||
|
||||
it('puts each height in the band the legend names', () => {
|
||||
expect(HEIGHT_BANDS[bandIndexOf(63, 63)].name).toBe('0–10 below sea')
|
||||
expect(HEIGHT_BANDS[bandIndexOf(64, 63)].name).toBe('0–8 above sea')
|
||||
expect(HEIGHT_BANDS[bandIndexOf(500, 63)].name).toBe('300+ above sea')
|
||||
expect(HEIGHT_BANDS[bandIndexOf(-500, 63)].name).toBe('40+ below sea')
|
||||
})
|
||||
})
|
||||
|
||||
describe('tile style', () => {
|
||||
const pixel = (pixels: Uint8ClampedArray, size: number, x: number, z: number): number => {
|
||||
const at = (z * size + x) * 4
|
||||
return (pixels[at] << 16) | (pixels[at + 1] << 8) | pixels[at + 2]
|
||||
}
|
||||
|
||||
it('paints each pixel in its label colour', () => {
|
||||
const pixels = stylePixels(splitTile(), FLAT)
|
||||
|
||||
expect(pixel(pixels, 4, 0, 0)).toBe(PLAINS.color)
|
||||
expect(pixel(pixels, 4, 3, 3)).toBe(DESERT.color)
|
||||
})
|
||||
|
||||
it('dims everything but the highlight, and tints the highlight edge', () => {
|
||||
const pixels = stylePixels(splitTile(), { ...FLAT, highlight: { kind: 'BIOME', key: 'plains', name: 'Plains' } })
|
||||
|
||||
expect(pixel(pixels, 4, 3, 3)).not.toBe(DESERT.color)
|
||||
expect(pixel(pixels, 4, 0, 1)).toBe(PLAINS.color)
|
||||
expect(pixel(pixels, 4, 1, 1)).not.toBe(PLAINS.color)
|
||||
})
|
||||
|
||||
it('leaves flat ground almost as it is when shading', () => {
|
||||
const pixels = stylePixels(splitTile(), { ...FLAT, shading: true })
|
||||
const green = (pixel(pixels, 4, 0, 0) >> 8) & 0xff
|
||||
|
||||
expect(green).toBeGreaterThan(200)
|
||||
})
|
||||
})
|
||||
|
||||
describe('viewport', () => {
|
||||
const view: Viewport = { centerX: 100, centerZ: -50, blocksPerPixel: 2, width: 800, height: 600 }
|
||||
|
||||
it('maps screen and world both ways', () => {
|
||||
expect(screenToWorldX(view, 400)).toBe(100)
|
||||
expect(worldToScreenX(view, screenToWorldX(view, 123))).toBe(123)
|
||||
})
|
||||
|
||||
it('draws tiles at the power of two nearest a device pixel, never finer than a block', () => {
|
||||
expect(renderBlocksPerPixel(4, 1)).toBe(4)
|
||||
expect(renderBlocksPerPixel(4, 2)).toBe(2)
|
||||
expect(renderBlocksPerPixel(0.25, 1)).toBe(1)
|
||||
expect(renderBlocksPerPixel(5.5, 1)).toBe(4)
|
||||
})
|
||||
|
||||
it('covers the screen, starting from the middle', () => {
|
||||
const tiles = visibleTiles(view, 2, 128)
|
||||
|
||||
// 1600 × 1200 blocks around (100, -50) in tiles of 256 blocks: x -3 to 3, z -3 to 2.
|
||||
expect(tiles.length).toBe(7 * 6)
|
||||
expect(tiles[0]).toEqual({ tileX: 0, tileZ: -1, blocksPerPixel: 2 })
|
||||
})
|
||||
|
||||
it('finds the coarser tile that covers a tile', () => {
|
||||
expect(coarserTile({ tileX: -3, tileZ: 5, blocksPerPixel: 2 }, 2)).toEqual({ tileX: -1, tileZ: 1, blocksPerPixel: 8 })
|
||||
})
|
||||
|
||||
it('previews four blank tiles with one tile a level out, never past the coarsest scale', () => {
|
||||
const blank = [
|
||||
{ tileX: 0, tileZ: 0, blocksPerPixel: 2 },
|
||||
{ tileX: 1, tileZ: 0, blocksPerPixel: 2 },
|
||||
{ tileX: 0, tileZ: 1, blocksPerPixel: 2 },
|
||||
{ tileX: -1, tileZ: 0, blocksPerPixel: 2 },
|
||||
{ tileX: 0, tileZ: 0, blocksPerPixel: 4096 }
|
||||
]
|
||||
|
||||
expect(previewsFor(blank)).toEqual([
|
||||
{ tileX: 0, tileZ: 0, blocksPerPixel: 4 },
|
||||
{ tileX: -1, tileZ: 0, blocksPerPixel: 4 }
|
||||
])
|
||||
})
|
||||
})
|
||||
|
||||
describe('census', () => {
|
||||
it('shares the visible pixels between the labels', () => {
|
||||
const tile = splitTile(4)
|
||||
const shares = countShares([{ tile, worldX: 0, worldZ: 0 }], { minimumX: 0, minimumZ: 0, maximumX: 4, maximumZ: 4 }, false, 63)
|
||||
|
||||
expect(shares.map((share) => share.subject.key).sort()).toEqual(['desert', 'plains'])
|
||||
expect(shares[0].fraction).toBeCloseTo(0.5)
|
||||
expect(gridIndex(tile, -1, -1)).toBe(0)
|
||||
})
|
||||
|
||||
it('counts only the part of a tile inside the area, largest share first', () => {
|
||||
const shares = countShares([{ tile: splitTile(4), worldX: 0, worldZ: 0 }], { minimumX: 0, minimumZ: 0, maximumX: 3, maximumZ: 4 }, false, 63)
|
||||
|
||||
expect(shares.map((share) => share.subject.key)).toEqual(['plains', 'desert'])
|
||||
expect(shares[0].fraction).toBeCloseTo(2 / 3)
|
||||
})
|
||||
|
||||
it('counts height bands in the height view', () => {
|
||||
const shares = countShares([{ tile: splitTile(4), worldX: 0, worldZ: 0 }], { minimumX: 0, minimumZ: 0, maximumX: 4, maximumZ: 4 }, true, 63)
|
||||
|
||||
expect(shares).toHaveLength(1)
|
||||
expect(shares[0].subject).toMatchObject({ kind: 'HEIGHT', name: '0–8 above sea' })
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,150 @@
|
||||
import { gridIndex } from '../bridge/tileDecoding'
|
||||
import { NO_LABEL, type MapTile } from '../bridge/types'
|
||||
import { bandIndexOf, blend, heightColor } from './heightColors'
|
||||
|
||||
/** What a highlight picks out: a biome or region by key, or a height band in the height view. */
|
||||
export interface Highlight {
|
||||
kind: 'BIOME' | 'REGION' | 'HEIGHT'
|
||||
key: string
|
||||
name: string
|
||||
}
|
||||
|
||||
export interface TileStyle {
|
||||
/** Colour by height instead of by label. */
|
||||
byHeight: boolean
|
||||
shading: boolean
|
||||
regionBorders: boolean
|
||||
highlight: Highlight | null
|
||||
seaLevel: number
|
||||
}
|
||||
|
||||
export function styleKey(style: TileStyle): string {
|
||||
const highlight = style.highlight === null ? '' : `${style.highlight.kind}:${style.highlight.key}`
|
||||
return `${style.byHeight}|${style.shading}|${style.regionBorders}|${highlight}|${style.seaLevel}`
|
||||
}
|
||||
|
||||
const UNKNOWN_SUBJECT = 0x5a5c62
|
||||
const SHADING_EXAGGERATION = 2
|
||||
const LIGHT_X = -0.5
|
||||
const LIGHT_Y = 0.7
|
||||
const LIGHT_Z = -0.5
|
||||
const LIGHT_LENGTH = Math.sqrt(LIGHT_X * LIGHT_X + LIGHT_Y * LIGHT_Y + LIGHT_Z * LIGHT_Z)
|
||||
const AMBIENT_LIGHT = 0.35
|
||||
const DIRECT_LIGHT = 0.75
|
||||
const DARKEST_SHADE = 0.25
|
||||
const BRIGHTEST_SHADE = 1.15
|
||||
// Water lies flat over the seafloor, so only a hint of the relief beneath shows through.
|
||||
const UNDERWATER_RELIEF = 0.15
|
||||
const DIM_TARGET = 0x1e1f22
|
||||
const DIM_AMOUNT = 0.72
|
||||
const DIM_DESATURATION = 0.6
|
||||
const HIGHLIGHT_EDGE = 0xffffff
|
||||
// A solid outline turns biomes that are scattered pixel by pixel into white noise, so the edge only tints.
|
||||
const HIGHLIGHT_EDGE_STRENGTH = 0.55
|
||||
const REGION_BORDER = 0x101114
|
||||
const REGION_BORDER_STRENGTH = 0.6
|
||||
|
||||
/** The tile's pixels as RGBA, as {@code style} draws them (v3e MapTile.styledPixels). */
|
||||
export function stylePixels(tile: MapTile, style: TileStyle): Uint8ClampedArray<ArrayBuffer> {
|
||||
const { size, heights } = tile
|
||||
const pixels = new Uint8ClampedArray(size * size * 4)
|
||||
const colors = tile.labels.map((label) => label.color)
|
||||
const byHeight = style.byHeight && heights !== null
|
||||
const shading = (style.shading || byHeight) && heights !== null
|
||||
const highlighted = highlightCells(tile, style)
|
||||
for (let pixelZ = 0; pixelZ < size; pixelZ++) {
|
||||
for (let pixelX = 0; pixelX < size; pixelX++) {
|
||||
const cell = gridIndex(tile, pixelX, pixelZ)
|
||||
let color = byHeight ? heightColor(heights[cell], style.seaLevel) : labelColor(colors, tile.subjects[cell])
|
||||
if (shading) {
|
||||
color = shade(tile, heights, cell, color, style.seaLevel)
|
||||
}
|
||||
if (highlighted !== null) {
|
||||
color = highlight(tile, highlighted, cell, color)
|
||||
}
|
||||
if (style.regionBorders && isRegionEdge(tile, cell)) {
|
||||
color = blend(color, REGION_BORDER, REGION_BORDER_STRENGTH)
|
||||
}
|
||||
const at = (pixelZ * size + pixelX) * 4
|
||||
pixels[at] = (color >> 16) & 0xff
|
||||
pixels[at + 1] = (color >> 8) & 0xff
|
||||
pixels[at + 2] = color & 0xff
|
||||
pixels[at + 3] = 0xff
|
||||
}
|
||||
}
|
||||
return pixels
|
||||
}
|
||||
|
||||
function labelColor(colors: number[], index: number): number {
|
||||
return index === NO_LABEL ? UNKNOWN_SUBJECT : colors[index]
|
||||
}
|
||||
|
||||
// Lit from the north west like a relief map, so slopes read as hills and valleys at a glance.
|
||||
function shade(tile: MapTile, heights: Float32Array, cell: number, color: number, seaLevel: number): number {
|
||||
const row = tile.size + 2
|
||||
const slopeX = (heights[cell + 1] - heights[cell - 1]) / (2 * tile.blocksPerPixel)
|
||||
const slopeZ = (heights[cell + row] - heights[cell - row]) / (2 * tile.blocksPerPixel)
|
||||
const normalX = -slopeX * SHADING_EXAGGERATION
|
||||
const normalZ = -slopeZ * SHADING_EXAGGERATION
|
||||
const normalLength = Math.sqrt(normalX * normalX + 1 + normalZ * normalZ)
|
||||
const light = (normalX * LIGHT_X + LIGHT_Y + normalZ * LIGHT_Z) / (normalLength * LIGHT_LENGTH)
|
||||
let factor = Math.min(BRIGHTEST_SHADE, Math.max(DARKEST_SHADE, AMBIENT_LIGHT + DIRECT_LIGHT * light))
|
||||
if (heights[cell] <= seaLevel) {
|
||||
factor = 1 - (1 - factor) * UNDERWATER_RELIEF
|
||||
}
|
||||
return scale(color, factor)
|
||||
}
|
||||
|
||||
/** Which cells the highlight covers, as one flag per grid cell; null when nothing is highlighted. */
|
||||
function highlightCells(tile: MapTile, style: TileStyle): Uint8Array | null {
|
||||
const target = style.highlight
|
||||
if (target === null) {
|
||||
return null
|
||||
}
|
||||
const cells = new Uint8Array(tile.subjects.length)
|
||||
if (target.kind === 'HEIGHT') {
|
||||
if (tile.heights !== null) {
|
||||
const band = Number(target.key)
|
||||
tile.heights.forEach((height, cell) => {
|
||||
cells[cell] = bandIndexOf(height, style.seaLevel) === band ? 1 : 0
|
||||
})
|
||||
}
|
||||
return cells
|
||||
}
|
||||
// Every view knows its regions, so a region can be highlighted in a biome view too.
|
||||
const grid = target.kind === tile.subjectKind ? tile.subjects : target.kind === 'REGION' ? tile.regions : null
|
||||
const index = tile.labels.findIndex((label) => label.kind === target.kind && label.key === target.key)
|
||||
if (grid !== null && index >= 0) {
|
||||
grid.forEach((label, cell) => {
|
||||
cells[cell] = label === index ? 1 : 0
|
||||
})
|
||||
}
|
||||
return cells
|
||||
}
|
||||
|
||||
function highlight(tile: MapTile, highlighted: Uint8Array, cell: number, color: number): number {
|
||||
if (highlighted[cell] === 0) {
|
||||
return dim(color)
|
||||
}
|
||||
const row = tile.size + 2
|
||||
const edge = highlighted[cell + 1] === 0 || highlighted[cell - 1] === 0 || highlighted[cell + row] === 0 || highlighted[cell - row] === 0
|
||||
return edge ? blend(color, HIGHLIGHT_EDGE, HIGHLIGHT_EDGE_STRENGTH) : color
|
||||
}
|
||||
|
||||
function isRegionEdge(tile: MapTile, cell: number): boolean {
|
||||
const region = tile.regions[cell]
|
||||
return tile.regions[cell + 1] !== region || tile.regions[cell + tile.size + 2] !== region
|
||||
}
|
||||
|
||||
function dim(color: number): number {
|
||||
const gray = Math.floor((((color >> 16) & 0xff) + ((color >> 8) & 0xff) + (color & 0xff)) / 3)
|
||||
const desaturated = blend(color, (gray << 16) | (gray << 8) | gray, DIM_DESATURATION)
|
||||
return blend(desaturated, DIM_TARGET, DIM_AMOUNT)
|
||||
}
|
||||
|
||||
function scale(color: number, factor: number): number {
|
||||
const red = Math.min(255, Math.floor(((color >> 16) & 0xff) * factor))
|
||||
const green = Math.min(255, Math.floor(((color >> 8) & 0xff) * factor))
|
||||
const blue = Math.min(255, Math.floor((color & 0xff) * factor))
|
||||
return (red << 16) | (green << 8) | blue
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
/** Where the map looks and how far it is zoomed; screen sizes are CSS pixels. */
|
||||
export interface Viewport {
|
||||
centerX: number
|
||||
centerZ: number
|
||||
blocksPerPixel: number
|
||||
width: number
|
||||
height: number
|
||||
}
|
||||
|
||||
export interface TileAddress {
|
||||
tileX: number
|
||||
tileZ: number
|
||||
blocksPerPixel: number
|
||||
}
|
||||
|
||||
export const MINIMUM_VIEW_BLOCKS_PER_PIXEL = 1 / 8
|
||||
export const MAXIMUM_BLOCKS_PER_PIXEL = 4096
|
||||
export const DEFAULT_BLOCKS_PER_PIXEL = 4
|
||||
// Iris has nothing finer than a block, so closer views magnify the block-sized tiles.
|
||||
const MINIMUM_RENDER_BLOCKS_PER_PIXEL = 1
|
||||
|
||||
export function clampBlocksPerPixel(blocksPerPixel: number): number {
|
||||
return Math.min(MAXIMUM_BLOCKS_PER_PIXEL, Math.max(MINIMUM_VIEW_BLOCKS_PER_PIXEL, blocksPerPixel))
|
||||
}
|
||||
|
||||
export function screenToWorldX(view: Viewport, screenX: number): number {
|
||||
return view.centerX + (screenX - view.width / 2) * view.blocksPerPixel
|
||||
}
|
||||
|
||||
export function screenToWorldZ(view: Viewport, screenZ: number): number {
|
||||
return view.centerZ + (screenZ - view.height / 2) * view.blocksPerPixel
|
||||
}
|
||||
|
||||
export function worldToScreenX(view: Viewport, worldX: number): number {
|
||||
return (worldX - view.centerX) / view.blocksPerPixel + view.width / 2
|
||||
}
|
||||
|
||||
export function worldToScreenZ(view: Viewport, worldZ: number): number {
|
||||
return (worldZ - view.centerZ) / view.blocksPerPixel + view.height / 2
|
||||
}
|
||||
|
||||
/**
|
||||
* The scale tiles are drawn at for a view: the nearest power of two to one tile pixel per device pixel, so tiles stay
|
||||
* sharp on dense screens and every zoom between two levels reuses the same tiles.
|
||||
*/
|
||||
export function renderBlocksPerPixel(viewBlocksPerPixel: number, devicePixelRatio: number): number {
|
||||
const level = 2 ** Math.round(Math.log2(viewBlocksPerPixel / devicePixelRatio))
|
||||
return Math.min(MAXIMUM_BLOCKS_PER_PIXEL, Math.max(MINIMUM_RENDER_BLOCKS_PER_PIXEL, level))
|
||||
}
|
||||
|
||||
/** The tiles covering the view, nearest the centre first so the middle of the screen fills in first. */
|
||||
export function visibleTiles(view: Viewport, renderScale: number, tileSize: number): TileAddress[] {
|
||||
const span = tileSize * renderScale
|
||||
const firstX = Math.floor(screenToWorldX(view, 0) / span)
|
||||
const lastX = Math.floor(screenToWorldX(view, view.width) / span)
|
||||
const firstZ = Math.floor(screenToWorldZ(view, 0) / span)
|
||||
const lastZ = Math.floor(screenToWorldZ(view, view.height) / span)
|
||||
const middleX = view.centerX / span - 0.5
|
||||
const middleZ = view.centerZ / span - 0.5
|
||||
const tiles: TileAddress[] = []
|
||||
for (let tileZ = firstZ; tileZ <= lastZ; tileZ++) {
|
||||
for (let tileX = firstX; tileX <= lastX; tileX++) {
|
||||
tiles.push({ tileX, tileZ, blocksPerPixel: renderScale })
|
||||
}
|
||||
}
|
||||
const distance = (tile: TileAddress): number => (tile.tileX - middleX) ** 2 + (tile.tileZ - middleZ) ** 2
|
||||
return tiles.sort((first, second) => distance(first) - distance(second))
|
||||
}
|
||||
|
||||
/**
|
||||
* One tile a level out for each group of blank tiles, in their order: a quarter of the pixels, so the screen fills
|
||||
* about four times sooner and sharpens as the tiles themselves arrive.
|
||||
*/
|
||||
export function previewsFor(blankTiles: TileAddress[]): TileAddress[] {
|
||||
const previews = new Map<string, TileAddress>()
|
||||
for (const tile of blankTiles) {
|
||||
const preview = coarserTile(tile, 1)
|
||||
if (preview.blocksPerPixel <= MAXIMUM_BLOCKS_PER_PIXEL) {
|
||||
previews.set(`${preview.tileX}/${preview.tileZ}/${preview.blocksPerPixel}`, preview)
|
||||
}
|
||||
}
|
||||
return [...previews.values()]
|
||||
}
|
||||
|
||||
/** The coarser tile that covers {@code tile}, {@code levels} zoom levels out. */
|
||||
export function coarserTile(tile: TileAddress, levels: number): TileAddress {
|
||||
const factor = 2 ** levels
|
||||
return {
|
||||
tileX: Math.floor(tile.tileX / factor),
|
||||
tileZ: Math.floor(tile.tileZ / factor),
|
||||
blocksPerPixel: tile.blocksPerPixel * factor
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { Globe2, Loader2 } from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import type { BridgeConnection } from '../../../shared/bridge'
|
||||
|
||||
const BRIDGE_POLL_MILLIS = 2000
|
||||
|
||||
interface ConnectScreenProps {
|
||||
connecting: boolean
|
||||
error: string | null
|
||||
onConnect(connection: BridgeConnection): void
|
||||
onLink(link: string): void
|
||||
}
|
||||
|
||||
/**
|
||||
* Lists the worlds servers on this machine opened to the studio, and takes a pasted link for any other. A single
|
||||
* world is opened right away, once.
|
||||
*/
|
||||
export function ConnectScreen({ connecting, error, onConnect, onLink }: ConnectScreenProps): React.JSX.Element {
|
||||
const [bridges, setBridges] = useState<BridgeConnection[]>([])
|
||||
const [link, setLink] = useState('')
|
||||
const openedOnItsOwn = useRef(false)
|
||||
|
||||
useEffect(() => {
|
||||
let active = true
|
||||
const refresh = (): void => {
|
||||
void window.studio.listBridges().then((found) => {
|
||||
if (!active) {
|
||||
return
|
||||
}
|
||||
setBridges(found)
|
||||
if (found.length === 1 && !openedOnItsOwn.current) {
|
||||
openedOnItsOwn.current = true
|
||||
onConnect(found[0])
|
||||
}
|
||||
})
|
||||
}
|
||||
refresh()
|
||||
const timer = window.setInterval(refresh, BRIDGE_POLL_MILLIS)
|
||||
return () => {
|
||||
active = false
|
||||
window.clearInterval(timer)
|
||||
}
|
||||
}, [onConnect])
|
||||
|
||||
return (
|
||||
<div className="flex h-full items-center justify-center bg-background">
|
||||
<div className="w-[440px] rounded-xl border border-overlay-border bg-card p-6 shadow-lg">
|
||||
<h1 className="text-[15px] font-semibold">Open a world</h1>
|
||||
<p className="mt-1 text-secondary-text">
|
||||
Run <code className="rounded bg-secondary px-1 font-mono text-[12px]">/iris studio map</code> in game or in the
|
||||
server console.
|
||||
</p>
|
||||
|
||||
<div className="mt-4 flex flex-col gap-1">
|
||||
{bridges.length === 0 ? (
|
||||
<div className="flex items-center gap-2 rounded-md px-3 py-2 text-muted-foreground">
|
||||
<Loader2 className="size-4 animate-spin" /> Waiting for a server on this machine
|
||||
</div>
|
||||
) : (
|
||||
bridges.map((bridge) => (
|
||||
<button
|
||||
key={bridge.port}
|
||||
disabled={connecting}
|
||||
onClick={() => onConnect(bridge)}
|
||||
className="flex items-center gap-3 rounded-md px-3 py-2 text-left hover:bg-accent disabled:opacity-60"
|
||||
>
|
||||
<Globe2 className="size-4 text-secondary-text" />
|
||||
<span className="flex-1 truncate font-medium">{bridge.world}</span>
|
||||
<span className="text-[11px] text-muted-foreground">port {bridge.port}</span>
|
||||
</button>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
|
||||
<form
|
||||
className="mt-4 flex gap-2"
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault()
|
||||
onLink(link)
|
||||
}}
|
||||
>
|
||||
<Input value={link} onChange={(event) => setLink(event.target.value)} placeholder="iris-studio://…" className="h-8" />
|
||||
<Button type="submit" size="sm" disabled={connecting || link.trim() === ''}>
|
||||
{connecting ? <Loader2 className="animate-spin" /> : 'Connect'}
|
||||
</Button>
|
||||
</form>
|
||||
{error !== null && <p className="mt-2 text-[12px] text-destructive">{error}</p>}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'
|
||||
import { Kbd } from '@/components/ui/kbd'
|
||||
import type { ViewInfo } from '../bridge/types'
|
||||
import { MOUSE_HINTS, SHORTCUTS, VIEW_KEYS } from './shortcuts'
|
||||
|
||||
interface HelpDialogProps {
|
||||
open: boolean
|
||||
onOpenChange(open: boolean): void
|
||||
views: ViewInfo[]
|
||||
}
|
||||
|
||||
/** Every key and mouse gesture of the map. */
|
||||
export function HelpDialog({ open, onOpenChange, views }: HelpDialogProps): React.JSX.Element {
|
||||
const viewRows = views.filter((view) => VIEW_KEYS[view.id] !== undefined).map((view) => ({ key: VIEW_KEYS[view.id], label: view.label }))
|
||||
const groups = [
|
||||
{ title: 'Views', rows: [...viewRows, ...rowsOf('Views')] },
|
||||
{ title: 'Everywhere', rows: rowsOf('Everywhere') },
|
||||
{ title: 'Map', rows: rowsOf('Map') },
|
||||
{ title: 'Mouse', rows: MOUSE_HINTS.map((hint) => ({ key: hint.gesture, label: hint.label })) }
|
||||
]
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-[640px] bg-card">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="text-[15px]">Shortcuts</DialogTitle>
|
||||
</DialogHeader>
|
||||
<div className="grid grid-cols-2 gap-x-8 gap-y-4">
|
||||
{groups.map((group) => (
|
||||
<section key={group.title}>
|
||||
<h3 className="mb-1.5 text-[11px] font-semibold text-muted-foreground">{group.title}</h3>
|
||||
<ul className="flex flex-col gap-1">
|
||||
{group.rows.map((row) => (
|
||||
<li key={row.label} className="flex items-center justify-between gap-3">
|
||||
<span className="text-secondary-text">{row.label}</span>
|
||||
<Kbd>{row.key}</Kbd>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</section>
|
||||
))}
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
|
||||
function rowsOf(group: 'Views' | 'Everywhere' | 'Map'): { key: string; label: string }[] {
|
||||
return SHORTCUTS.filter((shortcut) => shortcut.group === group).map((shortcut) => ({ key: shortcut.keyText, label: shortcut.label }))
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
import { useLayoutEffect, useRef, useState } from 'react'
|
||||
import { Kbd } from '@/components/ui/kbd'
|
||||
import type { MapHover, MapLabel } from '../bridge/types'
|
||||
import { hexColor } from './colors'
|
||||
import type { CanvasPoint } from './MapCanvas'
|
||||
import { shortcutFor } from './shortcuts'
|
||||
|
||||
interface HoverCardProps {
|
||||
hover: MapHover
|
||||
point: CanvasPoint
|
||||
viewId: string
|
||||
detailed: boolean
|
||||
minY: number
|
||||
}
|
||||
|
||||
const CURSOR_GAP_PIXELS = 18
|
||||
const EDGE_MARGIN_PIXELS = 8
|
||||
|
||||
interface Row {
|
||||
label: string
|
||||
value: string
|
||||
mono?: boolean
|
||||
}
|
||||
|
||||
/** The spot under the cursor: its biome and ground, and with Shift held, the rest of what the server knows. */
|
||||
export function HoverCard({ hover, point, viewId, detailed, minY }: HoverCardProps): React.JSX.Element {
|
||||
const card = useRef<HTMLDivElement>(null)
|
||||
const [position, setPosition] = useState({ left: point.x + CURSOR_GAP_PIXELS, top: point.y + CURSOR_GAP_PIXELS })
|
||||
|
||||
useLayoutEffect(() => {
|
||||
const element = card.current
|
||||
const parent = element?.parentElement
|
||||
if (!element || !parent) {
|
||||
return
|
||||
}
|
||||
const fitsRight = point.x + CURSOR_GAP_PIXELS + element.offsetWidth + EDGE_MARGIN_PIXELS <= parent.clientWidth
|
||||
const fitsBelow = point.y + CURSOR_GAP_PIXELS + element.offsetHeight + EDGE_MARGIN_PIXELS <= parent.clientHeight
|
||||
setPosition({
|
||||
left: fitsRight ? point.x + CURSOR_GAP_PIXELS : Math.max(EDGE_MARGIN_PIXELS, point.x - CURSOR_GAP_PIXELS - element.offsetWidth),
|
||||
top: fitsBelow ? point.y + CURSOR_GAP_PIXELS : Math.max(EDGE_MARGIN_PIXELS, point.y - CURSOR_GAP_PIXELS - element.offsetHeight)
|
||||
})
|
||||
}, [point, hover, detailed])
|
||||
|
||||
const subject = viewId === 'caveBiomes' ? hover.caveBiome : viewId === 'regions' ? hover.region : hover.biome
|
||||
const groups = detailed ? detailGroups(hover, viewId) : []
|
||||
return (
|
||||
<div
|
||||
ref={card}
|
||||
className="pointer-events-none absolute z-10 w-72 rounded-[10px] border border-overlay-border bg-popover px-3.5 py-3 text-popover-foreground shadow-xl backdrop-blur-sm"
|
||||
style={position}
|
||||
>
|
||||
<Header subject={subject} region={viewId === 'regions' ? null : hover.region} />
|
||||
<p className="mt-0.5 text-[12px] text-secondary-text tabular-nums">{ground(hover, minY)}</p>
|
||||
{groups.map((group) => (
|
||||
<section key={group.title} className="mt-2.5">
|
||||
<h3 className="text-[11px] font-semibold text-muted-foreground">{group.title}</h3>
|
||||
<dl className="mt-1 grid grid-cols-[auto_1fr] gap-x-3 gap-y-0.5 text-[12px]">
|
||||
{group.rows.map((row) => (
|
||||
<div key={row.label} className="contents">
|
||||
<dt className="text-secondary-text">{row.label}</dt>
|
||||
<dd className={row.mono ? 'truncate font-mono text-[11.5px]' : 'truncate'}>{row.value}</dd>
|
||||
</div>
|
||||
))}
|
||||
</dl>
|
||||
</section>
|
||||
))}
|
||||
<div className="mt-2.5 flex flex-wrap gap-x-3 gap-y-1 text-[11px] text-muted-foreground">
|
||||
{!detailed && <Hint keyText="Shift" label="More" />}
|
||||
<Hint keyText={shortcutFor('highlight').keyText} label="Highlight" />
|
||||
<Hint keyText="Alt+Click" label="Open file" />
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function Header({ subject, region }: { subject: MapLabel | null; region: MapLabel | null }): React.JSX.Element {
|
||||
return (
|
||||
<div className="flex items-baseline gap-2">
|
||||
{subject !== null && <span className="size-2.5 shrink-0 translate-y-[1px] rounded-[3px]" style={{ backgroundColor: hexColor(subject.color) }} />}
|
||||
<span className="min-w-0 flex-1 truncate text-[13.5px] font-semibold">{subject?.name ?? 'Nothing here'}</span>
|
||||
{region !== null && <span className="shrink-0 truncate text-[12px] text-secondary-text">{region.name}</span>}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function Hint({ keyText, label }: { keyText: string; label: string }): React.JSX.Element {
|
||||
return (
|
||||
<span className="flex items-center gap-1">
|
||||
<Kbd className="h-4 min-w-4 text-[10.5px]">{keyText}</Kbd>
|
||||
{label}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
/** Height as the world's Y, how far above or below the water, and how steep. */
|
||||
function ground(hover: MapHover, minY: number): string {
|
||||
const aboveWater = Math.round(hover.height - hover.fluidHeight)
|
||||
const signed = aboveWater > 0 ? `+${aboveWater}` : String(aboveWater)
|
||||
return `Y ${Math.round(hover.height + minY)} · ${signed} from water · ${Math.round(hover.slopeDegrees)}°`
|
||||
}
|
||||
|
||||
function detailGroups(hover: MapHover, viewId: string): { title: string; rows: Row[] }[] {
|
||||
const groups: { title: string; rows: Row[] }[] = []
|
||||
const terrain: Row[] = []
|
||||
if (viewId === 'caveBiomes' && hover.biome !== null) {
|
||||
terrain.push({ label: 'Surface biome', value: hover.biome.name })
|
||||
} else if (hover.caveBiome !== null && hover.caveBiome.key !== hover.biome?.key) {
|
||||
terrain.push({ label: 'Cave biome', value: hover.caveBiome.name })
|
||||
}
|
||||
if (hover.vanillaBiome !== null) {
|
||||
terrain.push({ label: 'Minecraft', value: hover.vanillaBiome.replace('minecraft:', '').replaceAll('_', ' ') })
|
||||
}
|
||||
if (terrain.length > 0) {
|
||||
groups.push({ title: 'Terrain', rows: terrain })
|
||||
}
|
||||
const blockX = Math.floor(hover.worldX)
|
||||
const blockZ = Math.floor(hover.worldZ)
|
||||
groups.push({
|
||||
title: 'Location',
|
||||
rows: [
|
||||
{ label: 'Block', value: `${blockX}, ${blockZ}` },
|
||||
{ label: 'Chunk', value: `${blockX >> 4}, ${blockZ >> 4}` },
|
||||
{ label: 'Region file', value: `r.${blockX >> 9}.${blockZ >> 9}.mca`, mono: true }
|
||||
]
|
||||
})
|
||||
const files: Row[] = []
|
||||
if (hover.biomeFile !== null) {
|
||||
files.push({ label: 'Biome', value: hover.biomeFile, mono: true })
|
||||
}
|
||||
if (hover.regionFile !== null) {
|
||||
files.push({ label: 'Region', value: hover.regionFile, mono: true })
|
||||
}
|
||||
if (files.length > 0) {
|
||||
groups.push({ title: 'Files', rows: files })
|
||||
}
|
||||
return groups
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
import { ScrollArea } from '@/components/ui/scroll-area'
|
||||
import { cn } from '@/lib/utils'
|
||||
import type { Share } from '../map/census'
|
||||
import type { Highlight } from '../map/tileStyle'
|
||||
import { hexColor } from './colors'
|
||||
|
||||
interface LegendProps {
|
||||
title: string
|
||||
shares: Share[]
|
||||
highlight: Highlight | null
|
||||
onSelect(subject: Highlight): void
|
||||
}
|
||||
|
||||
/** What is on screen and how much of it each covers; clicking one highlights it on the map. */
|
||||
export function Legend({ title, shares, highlight, onSelect }: LegendProps): React.JSX.Element {
|
||||
const sharedNames = namesUsedMoreThanOnce(shares)
|
||||
return (
|
||||
<aside className="flex w-[250px] shrink-0 flex-col border-l bg-card">
|
||||
<h2 className="px-4 pt-2.5 pb-1.5 text-[11px] font-semibold text-muted-foreground">{title}</h2>
|
||||
<ScrollArea className="min-h-0 flex-1">
|
||||
<ul className="px-1.5 pb-1">
|
||||
{shares.length === 0 && <li className="px-2.5 py-1 text-muted-foreground">Drawing the map…</li>}
|
||||
{shares.map((share) => {
|
||||
const selected = highlight !== null && highlight.kind === share.subject.kind && highlight.key === share.subject.key
|
||||
return (
|
||||
<li key={`${share.subject.kind}:${share.subject.key}`}>
|
||||
<button
|
||||
onClick={() => onSelect(share.subject)}
|
||||
title={share.subject.key}
|
||||
className={cn('flex h-[26px] w-full items-center gap-2 rounded-md px-2.5 text-left', selected ? 'bg-selection' : 'hover:bg-accent')}
|
||||
>
|
||||
<span className="size-3 shrink-0 rounded-[3px]" style={{ backgroundColor: hexColor(share.color) }} />
|
||||
<span className="flex min-w-0 flex-1 items-baseline gap-1.5">
|
||||
<span className={cn('truncate', sharedNames.has(share.subject.name) && 'max-w-[60%] shrink-0')}>{share.subject.name}</span>
|
||||
{sharedNames.has(share.subject.name) && (
|
||||
<span className="min-w-0 truncate text-[11.5px] text-secondary-text">{fileName(share.subject.key)}</span>
|
||||
)}
|
||||
</span>
|
||||
<span className="w-[42px] shrink-0 text-right text-[11.5px] text-secondary-text tabular-nums">{percent(share.fraction)}</span>
|
||||
</button>
|
||||
</li>
|
||||
)
|
||||
})}
|
||||
</ul>
|
||||
</ScrollArea>
|
||||
<p className="px-4 pt-1.5 pb-2 text-[11px] text-muted-foreground">Click to highlight · Esc clears</p>
|
||||
</aside>
|
||||
)
|
||||
}
|
||||
|
||||
function namesUsedMoreThanOnce(shares: Share[]): Set<string> {
|
||||
const seen = new Set<string>()
|
||||
const repeated = new Set<string>()
|
||||
for (const share of shares) {
|
||||
if (seen.has(share.subject.name)) {
|
||||
repeated.add(share.subject.name)
|
||||
}
|
||||
seen.add(share.subject.name)
|
||||
}
|
||||
return repeated
|
||||
}
|
||||
|
||||
function fileName(key: string): string {
|
||||
return key.slice(key.lastIndexOf('/') + 1)
|
||||
}
|
||||
|
||||
function percent(fraction: number): string {
|
||||
if (fraction < 0.001) {
|
||||
return '<0.1%'
|
||||
}
|
||||
return fraction < 0.1 ? `${(fraction * 100).toFixed(1)}%` : `${Math.round(fraction * 100)}%`
|
||||
}
|
||||
@@ -0,0 +1,203 @@
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import {
|
||||
ContextMenu,
|
||||
ContextMenuContent,
|
||||
ContextMenuItem,
|
||||
ContextMenuSeparator,
|
||||
ContextMenuTrigger
|
||||
} 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 type { Highlight } from '../map/tileStyle'
|
||||
|
||||
export interface CanvasPoint {
|
||||
x: number
|
||||
y: number
|
||||
}
|
||||
|
||||
interface MapCanvasProps {
|
||||
client: BridgeClient
|
||||
world: WorldInfo
|
||||
viewId: string
|
||||
controllerRef: React.RefObject<MapController | null>
|
||||
listener: MapListener
|
||||
highlight: Highlight | null
|
||||
onPointer(point: CanvasPoint | null): void
|
||||
onDragged(): void
|
||||
onTeleport(point: CanvasPoint): void
|
||||
onOpenFile(point: CanvasPoint): void
|
||||
onHighlight(subject: Highlight): void
|
||||
onCopy(text: string): void
|
||||
}
|
||||
|
||||
// A press that moves less than this is a click, not a drag.
|
||||
const CLICK_SLOP_PIXELS = 4
|
||||
// One wheel notch is about 100; this zooms about 15% per notch, and smoothly on touchpads.
|
||||
const WHEEL_ZOOM_PER_DELTA = 0.002
|
||||
|
||||
interface ContextSpot {
|
||||
point: CanvasPoint
|
||||
subjects: SpotSubjects
|
||||
blockX: number
|
||||
blockZ: number
|
||||
}
|
||||
|
||||
/** The map canvas and its mouse: drag to move, wheel to zoom, Ctrl+click to teleport, Alt+click to open a file. */
|
||||
export function MapCanvas(props: MapCanvasProps): React.JSX.Element {
|
||||
const { client, world, viewId, controllerRef } = props
|
||||
const canvasRef = useRef<HTMLCanvasElement>(null)
|
||||
const latest = useRef(props)
|
||||
latest.current = props
|
||||
const [contextSpot, setContextSpot] = useState<ContextSpot | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
const canvas = canvasRef.current!
|
||||
const map = new MapController(canvas, client, world, viewId, {
|
||||
onStatus: (status) => latest.current.listener.onStatus(status),
|
||||
onShares: (shares) => latest.current.listener.onShares(shares),
|
||||
onError: (message) => latest.current.listener.onError(message)
|
||||
})
|
||||
controllerRef.current = map
|
||||
const resize = new ResizeObserver(([entry]) => map.resize(entry.contentRect.width, entry.contentRect.height))
|
||||
resize.observe(canvas)
|
||||
return () => {
|
||||
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])
|
||||
|
||||
useMouse(canvasRef, controllerRef, latest)
|
||||
|
||||
return (
|
||||
<ContextMenu
|
||||
onOpenChange={(open) => {
|
||||
if (!open) {
|
||||
setContextSpot(null)
|
||||
}
|
||||
}}
|
||||
>
|
||||
<ContextMenuTrigger asChild>
|
||||
<canvas
|
||||
ref={canvasRef}
|
||||
className="absolute inset-0 size-full cursor-grab active:cursor-grabbing"
|
||||
onContextMenu={(event) => {
|
||||
const map = controllerRef.current
|
||||
if (map === null) {
|
||||
return
|
||||
}
|
||||
const point = canvasPoint(event)
|
||||
const spot = map.worldAt(point.x, point.y)
|
||||
setContextSpot({ point, subjects: map.subjectsAt(point.x, point.y), blockX: Math.floor(spot.x), blockZ: Math.floor(spot.z) })
|
||||
}}
|
||||
/>
|
||||
</ContextMenuTrigger>
|
||||
<ContextMenuContent className="min-w-56">
|
||||
{contextSpot !== null && <SpotMenu spot={contextSpot} viewId={viewId} props={props} />}
|
||||
</ContextMenuContent>
|
||||
</ContextMenu>
|
||||
)
|
||||
}
|
||||
|
||||
function SpotMenu({ spot, viewId, props }: { spot: ContextSpot; viewId: string; props: MapCanvasProps }): React.JSX.Element {
|
||||
const { subject, region } = spot.subjects
|
||||
const coordinates = `${spot.blockX}, ${spot.blockZ}`
|
||||
return (
|
||||
<>
|
||||
{subject !== null && <ContextMenuItem onSelect={() => props.onHighlight(subject)}>{highlightText(subject, props.highlight)}</ContextMenuItem>}
|
||||
{region !== null && subject?.kind !== 'REGION' && (
|
||||
<ContextMenuItem onSelect={() => props.onHighlight(region)}>{highlightText(region, props.highlight)}</ContextMenuItem>
|
||||
)}
|
||||
<ContextMenuItem onSelect={() => props.onTeleport(spot.point)}>Teleport here</ContextMenuItem>
|
||||
<ContextMenuItem onSelect={() => props.onOpenFile(spot.point)}>{viewId === 'regions' ? 'Open region file' : 'Open biome file'}</ContextMenuItem>
|
||||
<ContextMenuSeparator />
|
||||
<ContextMenuItem onSelect={() => props.onCopy(coordinates)}>Copy coordinates ({coordinates})</ContextMenuItem>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
function highlightText(subject: Highlight, current: Highlight | null): string {
|
||||
const highlighted = current !== null && current.kind === subject.kind && current.key === subject.key
|
||||
return `${highlighted ? 'Clear highlight of' : 'Highlight'} ${subject.name}`
|
||||
}
|
||||
|
||||
function canvasPoint(event: { clientX: number; clientY: number; currentTarget: Element }): CanvasPoint {
|
||||
const bounds = event.currentTarget.getBoundingClientRect()
|
||||
return { x: event.clientX - bounds.left, y: event.clientY - bounds.top }
|
||||
}
|
||||
|
||||
function useMouse(
|
||||
canvasRef: React.RefObject<HTMLCanvasElement | null>,
|
||||
controllerRef: React.RefObject<MapController | null>,
|
||||
latest: React.RefObject<MapCanvasProps>
|
||||
): void {
|
||||
useEffect(() => {
|
||||
const canvas = canvasRef.current!
|
||||
let press: { x: number; y: number; lastX: number; lastY: number; dragged: boolean } | null = null
|
||||
|
||||
const down = (event: PointerEvent): void => {
|
||||
if (event.button !== 0) {
|
||||
return
|
||||
}
|
||||
canvas.setPointerCapture(event.pointerId)
|
||||
press = { x: event.clientX, y: event.clientY, lastX: event.clientX, lastY: event.clientY, dragged: false }
|
||||
}
|
||||
const move = (event: PointerEvent): void => {
|
||||
const point = canvasPoint({ clientX: event.clientX, clientY: event.clientY, currentTarget: canvas })
|
||||
controllerRef.current?.setCursor(point)
|
||||
latest.current.onPointer(point)
|
||||
if (press === null) {
|
||||
return
|
||||
}
|
||||
if (!press.dragged && Math.hypot(event.clientX - press.x, event.clientY - press.y) >= CLICK_SLOP_PIXELS) {
|
||||
press.dragged = true
|
||||
latest.current.onDragged()
|
||||
}
|
||||
if (press.dragged) {
|
||||
controllerRef.current?.panBy(event.clientX - press.lastX, event.clientY - press.lastY)
|
||||
}
|
||||
press.lastX = event.clientX
|
||||
press.lastY = event.clientY
|
||||
}
|
||||
const up = (event: PointerEvent): void => {
|
||||
if (press === null || event.button !== 0) {
|
||||
return
|
||||
}
|
||||
const wasClick = !press.dragged
|
||||
press = null
|
||||
if (!wasClick) {
|
||||
return
|
||||
}
|
||||
const point = canvasPoint({ clientX: event.clientX, clientY: event.clientY, currentTarget: canvas })
|
||||
if (event.ctrlKey || event.metaKey) {
|
||||
latest.current.onTeleport(point)
|
||||
} else if (event.altKey) {
|
||||
latest.current.onOpenFile(point)
|
||||
}
|
||||
}
|
||||
const leave = (): void => {
|
||||
controllerRef.current?.setCursor(null)
|
||||
latest.current.onPointer(null)
|
||||
}
|
||||
const wheel = (event: WheelEvent): void => {
|
||||
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)
|
||||
}
|
||||
|
||||
canvas.addEventListener('pointerdown', down)
|
||||
canvas.addEventListener('pointermove', move)
|
||||
canvas.addEventListener('pointerup', up)
|
||||
canvas.addEventListener('pointerleave', leave)
|
||||
canvas.addEventListener('wheel', wheel, { passive: false })
|
||||
return () => {
|
||||
canvas.removeEventListener('pointerdown', down)
|
||||
canvas.removeEventListener('pointermove', move)
|
||||
canvas.removeEventListener('pointerup', up)
|
||||
canvas.removeEventListener('pointerleave', leave)
|
||||
canvas.removeEventListener('wheel', wheel)
|
||||
}
|
||||
}, [canvasRef, controllerRef, latest])
|
||||
}
|
||||
@@ -0,0 +1,358 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
import type { ThemeChoice } from '../../../shared/bridge'
|
||||
import type { BridgeClient } from '../bridge/BridgeClient'
|
||||
import type { MapHover, Marker, 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 { HelpDialog } from './HelpDialog'
|
||||
import { HoverCard } from './HoverCard'
|
||||
import { Legend } from './Legend'
|
||||
import { MapCanvas, type CanvasPoint } from './MapCanvas'
|
||||
import { actionForKey, viewForKey, type ShortcutAction } from './shortcuts'
|
||||
import { StatusBar } from './StatusBar'
|
||||
import { StudioToolbar } from './StudioToolbar'
|
||||
import { ViewList } from './ViewList'
|
||||
|
||||
const KEYBOARD_ZOOM_FACTOR = 2 ** 0.25
|
||||
const ENTITY_POLL_MILLIS = 2000
|
||||
const NOTICE_MILLIS = 4000
|
||||
|
||||
interface MapStudioProps {
|
||||
client: BridgeClient
|
||||
world: WorldInfo
|
||||
theme: { choice: ThemeChoice; next: () => void }
|
||||
onDisconnect(): void
|
||||
}
|
||||
|
||||
export interface StudioToggles extends MapToggles {
|
||||
follow: boolean
|
||||
entities: boolean
|
||||
}
|
||||
|
||||
/** The map of one world: views on the left, the map in the middle, what is on screen on the right. */
|
||||
export function MapStudio({ client, world, theme, 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, follow: false, entities: false })
|
||||
const [highlight, setHighlight] = useState<Highlight | null>(null)
|
||||
const [status, setStatus] = useState<MapStatus | null>(null)
|
||||
const [shares, setShares] = useState<Share[]>([])
|
||||
const [players, setPlayers] = useState<Marker[]>([])
|
||||
const [entities, setEntities] = useState<Marker[]>([])
|
||||
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 [notice, setNotice] = useState<string | null>(null)
|
||||
const [connected, setConnected] = useState(true)
|
||||
const view = world.views.find((candidate) => candidate.id === viewId) ?? world.views[0]
|
||||
|
||||
const tell = useCallback((message: string) => setNotice(message), [])
|
||||
|
||||
useEffect(() => {
|
||||
if (notice === null) {
|
||||
return
|
||||
}
|
||||
const timer = window.setTimeout(() => setNotice(null), NOTICE_MILLIS)
|
||||
return () => window.clearTimeout(timer)
|
||||
}, [notice])
|
||||
|
||||
useEffect(() => controller.current?.setView(viewId), [viewId])
|
||||
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])
|
||||
|
||||
useServerEvents(client, controller, setPlayers, tell, setConnected)
|
||||
useEntities(client, toggles.entities, setEntities)
|
||||
useHover(client, controller, pointer, setHover)
|
||||
|
||||
const selectView = useCallback((nextViewId: string) => {
|
||||
setViewId(nextViewId)
|
||||
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 runShortcut = useCallback(
|
||||
(action: ShortcutAction) => {
|
||||
const map = controller.current
|
||||
switch (action) {
|
||||
case 'nextView':
|
||||
selectView(world.views[(world.views.findIndex((candidate) => candidate.id === viewId) + 1) % world.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 'borders':
|
||||
toggle('regionBorders')
|
||||
return
|
||||
case 'help':
|
||||
setHelpOpen((open) => !open)
|
||||
}
|
||||
},
|
||||
[world.views, viewId, selectView, toggle, highlightUnderCursor, tell]
|
||||
)
|
||||
|
||||
useKeyboard(runShortcut, selectView, setDetailed, world)
|
||||
|
||||
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))
|
||||
},
|
||||
[client, tell]
|
||||
)
|
||||
|
||||
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 on the server'))
|
||||
.catch((failure: Error) => tell(failure.message))
|
||||
},
|
||||
[client, viewId, tell]
|
||||
)
|
||||
|
||||
return (
|
||||
<div className="flex h-full flex-col bg-background">
|
||||
<StudioToolbar
|
||||
title={view.label}
|
||||
world={world}
|
||||
toggles={toggles}
|
||||
hasPlayers={world.hasPlayers}
|
||||
theme={theme}
|
||||
onToggle={toggle}
|
||||
onRefresh={() => runShortcut('refresh')}
|
||||
onResetZoom={() => runShortcut('resetZoom')}
|
||||
onHelp={() => setHelpOpen(true)}
|
||||
onDisconnect={onDisconnect}
|
||||
/>
|
||||
<div className="flex min-h-0 flex-1">
|
||||
<ViewList views={world.views} current={viewId} onSelect={selectView} />
|
||||
<div className="relative min-w-0 flex-1">
|
||||
<MapCanvas
|
||||
client={client}
|
||||
world={world}
|
||||
viewId={viewId}
|
||||
controllerRef={controller}
|
||||
listener={{ onStatus: setStatus, onShares: setShares, 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} detailed={detailed} minY={world.minY} />
|
||||
)}
|
||||
{!connected && (
|
||||
<div className="absolute inset-0 flex items-center justify-center bg-background/70">
|
||||
<div className="rounded-xl border border-overlay-border bg-card p-5 text-center shadow-lg">
|
||||
<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>
|
||||
)}
|
||||
</div>
|
||||
<Legend
|
||||
title={legendTitle(viewId)}
|
||||
shares={shares}
|
||||
highlight={highlight}
|
||||
onSelect={(subject) => setHighlight((current) => (sameSubject(current, subject) ? null : subject))}
|
||||
/>
|
||||
</div>
|
||||
<StatusBar viewLabel={view.label} status={status} notice={notice} />
|
||||
<HelpDialog open={helpOpen} onOpenChange={setHelpOpen} views={world.views} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function sameSubject(first: Highlight | null, second: Highlight | null): boolean {
|
||||
return first !== null && second !== null && first.kind === second.kind && first.key === second.key
|
||||
}
|
||||
|
||||
function legendTitle(viewId: string): string {
|
||||
if (viewId === 'regions') {
|
||||
return 'Regions on screen'
|
||||
}
|
||||
return viewId === 'height' ? 'Heights on screen' : 'Biomes on screen'
|
||||
}
|
||||
|
||||
/** Players 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,
|
||||
tell: (message: string) => void,
|
||||
setConnected: (connected: boolean) => void
|
||||
): void {
|
||||
useEffect(() => {
|
||||
const stop = new AbortController()
|
||||
let firstWorldEvent = true
|
||||
void client.listen(
|
||||
{
|
||||
onWorld: (running) => {
|
||||
if (firstWorldEvent) {
|
||||
firstWorldEvent = false
|
||||
return
|
||||
}
|
||||
if (running) {
|
||||
controller.current?.refresh()
|
||||
tell('Pack reloaded, redrawing')
|
||||
} else {
|
||||
tell('The world stopped')
|
||||
}
|
||||
},
|
||||
onPlayers: setPlayers,
|
||||
onClosed: () => setConnected(false)
|
||||
},
|
||||
stop.signal
|
||||
)
|
||||
return () => stop.abort()
|
||||
}, [client, controller, setPlayers, tell, setConnected])
|
||||
}
|
||||
|
||||
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>,
|
||||
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(Math.floor(spot.x), Math.floor(spot.z), stop.signal)
|
||||
.then(setHover)
|
||||
.catch(() => undefined)
|
||||
return () => stop.abort()
|
||||
}, [client, controller, pointer, setHover])
|
||||
}
|
||||
|
||||
function useKeyboard(
|
||||
runShortcut: (action: ShortcutAction) => void,
|
||||
selectView: (view: string) => void,
|
||||
setDetailed: (detailed: boolean) => void,
|
||||
world: WorldInfo
|
||||
): void {
|
||||
useEffect(() => {
|
||||
const down = (event: KeyboardEvent): void => {
|
||||
if (event.key === 'Shift') {
|
||||
setDetailed(true)
|
||||
}
|
||||
if (event.ctrlKey || event.metaKey || event.altKey || event.target instanceof HTMLInputElement) {
|
||||
return
|
||||
}
|
||||
const viewId = viewForKey(event.key)
|
||||
if (viewId !== null && world.views.some((view) => view.id === viewId)) {
|
||||
selectView(viewId)
|
||||
return
|
||||
}
|
||||
const action = actionForKey(event.key)
|
||||
if (action !== null) {
|
||||
event.preventDefault()
|
||||
runShortcut(action)
|
||||
}
|
||||
}
|
||||
const up = (event: KeyboardEvent): void => {
|
||||
if (event.key === 'Shift') {
|
||||
setDetailed(false)
|
||||
}
|
||||
}
|
||||
const blur = (): void => setDetailed(false)
|
||||
window.addEventListener('keydown', down)
|
||||
window.addEventListener('keyup', up)
|
||||
window.addEventListener('blur', blur)
|
||||
return () => {
|
||||
window.removeEventListener('keydown', down)
|
||||
window.removeEventListener('keyup', up)
|
||||
window.removeEventListener('blur', blur)
|
||||
}
|
||||
}, [runShortcut, selectView, setDetailed, world])
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
import type { MapStatus } from '../map/MapController'
|
||||
|
||||
interface StatusBarProps {
|
||||
viewLabel: string
|
||||
status: MapStatus | null
|
||||
notice: string | null
|
||||
}
|
||||
|
||||
const NUMBER = new Intl.NumberFormat('en-US')
|
||||
|
||||
/** What the map shows, what it is busy with, and where the cursor is (v3e StudioStatusBar). */
|
||||
export function StatusBar({ viewLabel, status, notice }: StatusBarProps): React.JSX.Element {
|
||||
const drawing = status !== null && status.tilesReady < status.tilesTotal
|
||||
return (
|
||||
<footer className="flex h-6 shrink-0 items-center gap-6 border-t bg-card px-3 text-[11.5px] text-secondary-text tabular-nums">
|
||||
<span className="truncate">
|
||||
{viewLabel}
|
||||
{status !== null && (
|
||||
<>
|
||||
<Gap />
|
||||
{formatScale(status.blocksPerPixel)} blocks/px
|
||||
<Gap />
|
||||
{NUMBER.format(status.widthBlocks)} × {NUMBER.format(status.heightBlocks)} blocks
|
||||
</>
|
||||
)}
|
||||
</span>
|
||||
<span className="flex min-w-0 flex-1 items-center justify-center gap-2 truncate">
|
||||
{notice ?? (drawing ? `Drawing ${status.tilesReady} of ${status.tilesTotal} tiles` : '')}
|
||||
{notice === null && drawing && (
|
||||
<span className="h-1 w-24 overflow-hidden rounded-full bg-secondary">
|
||||
<span className="block h-full bg-primary" style={{ width: `${(status.tilesReady / status.tilesTotal) * 100}%` }} />
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
{status !== null && (
|
||||
<span>
|
||||
X {NUMBER.format(status.cursorX)}
|
||||
<Gap />Z {NUMBER.format(status.cursorZ)}
|
||||
</span>
|
||||
)}
|
||||
</footer>
|
||||
)
|
||||
}
|
||||
|
||||
function Gap(): React.JSX.Element {
|
||||
return <span className="inline-block w-3" />
|
||||
}
|
||||
|
||||
function formatScale(blocksPerPixel: number): string {
|
||||
if (blocksPerPixel >= 10) {
|
||||
return String(Math.round(blocksPerPixel))
|
||||
}
|
||||
return blocksPerPixel >= 1 ? blocksPerPixel.toFixed(1) : blocksPerPixel.toFixed(2)
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
import { CircleHelp, Grid3x3, LocateFixed, LogOut, Monitor, Moon, Mountain, PawPrint, RefreshCw, Spline, Sun, ZoomIn } from 'lucide-react'
|
||||
import type { ReactNode } from 'react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Kbd } from '@/components/ui/kbd'
|
||||
import { Separator } from '@/components/ui/separator'
|
||||
import { Toggle } from '@/components/ui/toggle'
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip'
|
||||
import type { ThemeChoice } from '../../../shared/bridge'
|
||||
import type { WorldInfo } from '../bridge/types'
|
||||
import type { StudioToggles } from './MapStudio'
|
||||
import { shortcutFor, type ShortcutAction } from './shortcuts'
|
||||
|
||||
interface StudioToolbarProps {
|
||||
title: string
|
||||
world: WorldInfo
|
||||
toggles: StudioToggles
|
||||
hasPlayers: boolean
|
||||
theme: { choice: ThemeChoice; next: () => void }
|
||||
onToggle(name: keyof StudioToggles): void
|
||||
onRefresh(): void
|
||||
onResetZoom(): void
|
||||
onHelp(): void
|
||||
onDisconnect(): void
|
||||
}
|
||||
|
||||
const THEME_ICONS: Record<ThemeChoice, ReactNode> = { system: <Monitor />, light: <Sun />, dark: <Moon /> }
|
||||
const THEME_NAMES: Record<ThemeChoice, string> = { system: 'Theme: system', light: 'Theme: light', dark: 'Theme: dark' }
|
||||
|
||||
export function StudioToolbar(props: StudioToolbarProps): React.JSX.Element {
|
||||
const { toggles, onToggle } = props
|
||||
return (
|
||||
<header className="flex h-10 shrink-0 items-center gap-1 border-b bg-card px-2">
|
||||
<span className="px-1.5 pr-3 text-[14px] font-semibold">{props.title}</span>
|
||||
<ToolButton action="refresh" hint="Redraw the map with the latest pack files" onClick={props.onRefresh}>
|
||||
<RefreshCw />
|
||||
</ToolButton>
|
||||
<ToolButton action="resetZoom" hint="Go back to the default zoom" onClick={props.onResetZoom}>
|
||||
<ZoomIn />
|
||||
</ToolButton>
|
||||
<ToolToggle action="grid" hint="Show chunk and region borders" pressed={toggles.grid} onPressed={() => onToggle('grid')}>
|
||||
<Grid3x3 /> Grid
|
||||
</ToolToggle>
|
||||
<ToolToggle action="entities" hint="Show mobs and other entities" pressed={toggles.entities} disabled={!props.hasPlayers} onPressed={() => onToggle('entities')}>
|
||||
<PawPrint /> Entities
|
||||
</ToolToggle>
|
||||
<ToolToggle action="follow" hint="Keep your player in the middle" pressed={toggles.follow} disabled={!props.hasPlayers} onPressed={() => onToggle('follow')}>
|
||||
<LocateFixed /> Follow
|
||||
</ToolToggle>
|
||||
<Separator orientation="vertical" className="mx-1 h-5! bg-input" />
|
||||
<ToolToggle action="shading" hint="Shade hills and valleys" pressed={toggles.shading} onPressed={() => onToggle('shading')}>
|
||||
<Mountain /> Shading
|
||||
</ToolToggle>
|
||||
<ToolToggle action="borders" hint="Outline the regions on every view" pressed={toggles.regionBorders} onPressed={() => onToggle('regionBorders')}>
|
||||
<Spline /> Borders
|
||||
</ToolToggle>
|
||||
|
||||
<div className="flex-1" />
|
||||
<span className="truncate px-2 text-[12px] text-secondary-text" title={`${props.world.dimensionName} · seed ${props.world.seed}`}>
|
||||
{props.world.world}
|
||||
</span>
|
||||
<IconHint hint={THEME_NAMES[props.theme.choice]}>
|
||||
<Button variant="ghost" size="icon-sm" onClick={props.theme.next}>
|
||||
{THEME_ICONS[props.theme.choice]}
|
||||
</Button>
|
||||
</IconHint>
|
||||
<ToolButton action="help" hint="Show every mouse and key shortcut" onClick={props.onHelp}>
|
||||
<CircleHelp />
|
||||
</ToolButton>
|
||||
<IconHint hint="Back to the world list">
|
||||
<Button variant="ghost" size="icon-sm" onClick={props.onDisconnect}>
|
||||
<LogOut />
|
||||
</Button>
|
||||
</IconHint>
|
||||
</header>
|
||||
)
|
||||
}
|
||||
|
||||
function IconHint({ hint, keyText, children }: { hint: string; keyText?: string; children: ReactNode }): React.JSX.Element {
|
||||
return (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>{children}</TooltipTrigger>
|
||||
<TooltipContent className="flex items-center gap-2">
|
||||
{hint}
|
||||
{keyText !== undefined && <Kbd>{keyText}</Kbd>}
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
)
|
||||
}
|
||||
|
||||
function ToolButton({ action, hint, onClick, children }: { action: ShortcutAction; hint: string; onClick(): void; children: ReactNode }): React.JSX.Element {
|
||||
return (
|
||||
<IconHint hint={hint} keyText={shortcutFor(action).keyText}>
|
||||
<Button variant="ghost" size="icon-sm" onClick={onClick}>
|
||||
{children}
|
||||
</Button>
|
||||
</IconHint>
|
||||
)
|
||||
}
|
||||
|
||||
interface ToolToggleProps {
|
||||
action: ShortcutAction
|
||||
hint: string
|
||||
pressed: boolean
|
||||
disabled?: boolean
|
||||
onPressed(): void
|
||||
children: ReactNode
|
||||
}
|
||||
|
||||
function ToolToggle({ action, hint, pressed, disabled, onPressed, children }: ToolToggleProps): React.JSX.Element {
|
||||
return (
|
||||
<IconHint hint={disabled ? 'This server has no players to show' : hint} keyText={shortcutFor(action).keyText}>
|
||||
<span>
|
||||
<Toggle
|
||||
size="sm"
|
||||
pressed={pressed}
|
||||
disabled={disabled}
|
||||
onPressedChange={onPressed}
|
||||
className="h-7 gap-1.5 px-2 text-[12.5px] font-normal data-[state=on]:bg-selection data-[state=on]:text-foreground [&_svg:not([class*='size-'])]:size-3.5"
|
||||
>
|
||||
{children}
|
||||
</Toggle>
|
||||
</span>
|
||||
</IconHint>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
import { Gem, Map as MapIcon, Mountain, Sprout, Trees, Waves, type LucideIcon } from 'lucide-react'
|
||||
import { Kbd } from '@/components/ui/kbd'
|
||||
import { ScrollArea } from '@/components/ui/scroll-area'
|
||||
import { cn } from '@/lib/utils'
|
||||
import type { ViewInfo } from '../bridge/types'
|
||||
import { VIEW_KEYS } from './shortcuts'
|
||||
|
||||
const VIEW_ICONS: Record<string, LucideIcon> = {
|
||||
biomes: Trees,
|
||||
regions: MapIcon,
|
||||
height: Mountain,
|
||||
landBiomes: Sprout,
|
||||
seaBiomes: Waves,
|
||||
caveBiomes: Gem
|
||||
}
|
||||
|
||||
interface ViewListProps {
|
||||
views: ViewInfo[]
|
||||
current: string
|
||||
onSelect(view: string): void
|
||||
}
|
||||
|
||||
/** The views the server offers, in its groups, each with what it shows and its key. */
|
||||
export function ViewList({ views, current, onSelect }: ViewListProps): React.JSX.Element {
|
||||
const groups = [...new Set(views.map((view) => view.groupLabel))]
|
||||
return (
|
||||
<aside className="w-60 shrink-0 border-r bg-card">
|
||||
<ScrollArea className="h-full">
|
||||
<nav className="flex flex-col gap-3 p-2">
|
||||
{groups.map((group) => (
|
||||
<section key={group}>
|
||||
<h2 className="px-2 pt-1 pb-1.5 text-[11px] font-semibold text-muted-foreground">{group}</h2>
|
||||
{views
|
||||
.filter((view) => view.groupLabel === group)
|
||||
.map((view) => (
|
||||
<ViewRow key={view.id} view={view} selected={view.id === current} onSelect={() => onSelect(view.id)} />
|
||||
))}
|
||||
</section>
|
||||
))}
|
||||
</nav>
|
||||
</ScrollArea>
|
||||
</aside>
|
||||
)
|
||||
}
|
||||
|
||||
function ViewRow({ view, selected, onSelect }: { view: ViewInfo; selected: boolean; onSelect(): void }): React.JSX.Element {
|
||||
const Icon = VIEW_ICONS[view.id] ?? MapIcon
|
||||
return (
|
||||
<button
|
||||
onClick={onSelect}
|
||||
className={cn('flex w-full items-start gap-2.5 rounded-md px-2 py-1.5 text-left', selected ? 'bg-selection' : 'hover:bg-accent')}
|
||||
>
|
||||
<Icon className="mt-0.5 size-4 shrink-0 text-secondary-text" />
|
||||
<span className="min-w-0 flex-1">
|
||||
<span className="block font-medium">{view.label}</span>
|
||||
<span className="block text-[11.5px] leading-snug text-secondary-text">{view.description}</span>
|
||||
</span>
|
||||
{VIEW_KEYS[view.id] !== undefined && <Kbd className="mt-0.5">{VIEW_KEYS[view.id]}</Kbd>}
|
||||
</button>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
/** A 0xRRGGBB colour as CSS. */
|
||||
export function hexColor(color: number): string {
|
||||
return `#${color.toString(16).padStart(6, '0')}`
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
/** The studio's keys, as v3e's studio had them (StudioShortcut). */
|
||||
export type ShortcutAction =
|
||||
| 'nextView'
|
||||
| 'refresh'
|
||||
| 'zoomIn'
|
||||
| 'zoomOut'
|
||||
| 'resetZoom'
|
||||
| 'dismiss'
|
||||
| 'follow'
|
||||
| 'grid'
|
||||
| 'entities'
|
||||
| 'highlight'
|
||||
| 'shading'
|
||||
| 'borders'
|
||||
| 'help'
|
||||
|
||||
export interface Shortcut {
|
||||
action: ShortcutAction
|
||||
label: string
|
||||
group: 'Views' | 'Everywhere' | 'Map'
|
||||
/** The key as shown, then every KeyboardEvent.key that triggers it. */
|
||||
keyText: string
|
||||
keys: string[]
|
||||
}
|
||||
|
||||
export const SHORTCUTS: Shortcut[] = [
|
||||
{ action: 'nextView', label: 'Next view', group: 'Views', keyText: 'M', keys: ['m'] },
|
||||
{ action: 'refresh', label: 'Redraw the map with the latest pack files', group: 'Everywhere', keyText: 'R', keys: ['r'] },
|
||||
{ action: 'zoomIn', label: 'Zoom in', group: 'Everywhere', keyText: '=', keys: ['=', '+'] },
|
||||
{ action: 'zoomOut', label: 'Zoom out', group: 'Everywhere', keyText: '-', keys: ['-'] },
|
||||
{ action: 'resetZoom', label: 'Reset zoom', group: 'Everywhere', keyText: '\\', keys: ['\\'] },
|
||||
{ action: 'dismiss', label: 'Clear the highlight', group: 'Everywhere', keyText: 'Esc', keys: ['Escape'] },
|
||||
{ action: 'follow', label: 'Follow your player', group: 'Map', keyText: 'F', keys: ['f'] },
|
||||
{ action: 'grid', label: 'Chunk and region grid', group: 'Map', keyText: 'G', keys: ['g'] },
|
||||
{ action: 'entities', label: 'Show entities', group: 'Map', keyText: 'E', keys: ['e'] },
|
||||
{ action: 'highlight', label: 'Highlight what is under the cursor', group: 'Map', keyText: 'H', keys: ['h'] },
|
||||
{ action: 'shading', label: 'Terrain shading', group: 'Map', keyText: 'S', keys: ['s'] },
|
||||
{ action: 'borders', label: 'Region borders', group: 'Map', keyText: 'B', keys: ['b'] },
|
||||
{ action: 'help', label: 'Show the shortcuts', group: 'Map', keyText: '/', keys: ['/', '?'] }
|
||||
]
|
||||
|
||||
/** The key of each view; 4 stays free for the 3D world, as in v3e. */
|
||||
export const VIEW_KEYS: Record<string, string> = {
|
||||
biomes: '1',
|
||||
regions: '2',
|
||||
height: '3',
|
||||
landBiomes: '5',
|
||||
seaBiomes: '6',
|
||||
caveBiomes: '7'
|
||||
}
|
||||
|
||||
export const MOUSE_HINTS: { gesture: string; label: string }[] = [
|
||||
{ gesture: 'Drag', label: 'Move the map' },
|
||||
{ gesture: 'Wheel', label: 'Zoom around the cursor' },
|
||||
{ gesture: 'Shift', label: 'More about the spot under the cursor' },
|
||||
{ gesture: 'Ctrl+Click', label: 'Teleport there' },
|
||||
{ gesture: 'Alt+Click', label: 'Open the biome or region file' },
|
||||
{ gesture: 'Right click', label: 'Highlight, teleport, open or copy' }
|
||||
]
|
||||
|
||||
export function shortcutFor(action: ShortcutAction): Shortcut {
|
||||
return SHORTCUTS.find((shortcut) => shortcut.action === action)!
|
||||
}
|
||||
|
||||
export function actionForKey(key: string): ShortcutAction | null {
|
||||
const pressed = key.length === 1 ? key.toLowerCase() : key
|
||||
return SHORTCUTS.find((shortcut) => shortcut.keys.includes(pressed))?.action ?? null
|
||||
}
|
||||
|
||||
export function viewForKey(key: string): string | null {
|
||||
return Object.entries(VIEW_KEYS).find(([, viewKey]) => viewKey === key)?.[0] ?? null
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import type { ThemeChoice } from '../../../shared/bridge'
|
||||
|
||||
const STORAGE_KEY = 'iris-studio.theme'
|
||||
const DARK_QUERY = '(prefers-color-scheme: dark)'
|
||||
const ORDER: ThemeChoice[] = ['system', 'light', 'dark']
|
||||
|
||||
function storedChoice(): ThemeChoice {
|
||||
const stored = localStorage.getItem(STORAGE_KEY)
|
||||
return stored === 'light' || stored === 'dark' ? stored : 'system'
|
||||
}
|
||||
|
||||
function apply(choice: ThemeChoice): void {
|
||||
const dark = choice === 'dark' || (choice === 'system' && matchMedia(DARK_QUERY).matches)
|
||||
document.documentElement.classList.toggle('dark', dark)
|
||||
}
|
||||
|
||||
/** The light or dark look, following the system unless chosen; the choice outlives the window. */
|
||||
export function useTheme(): { choice: ThemeChoice; next: () => void } {
|
||||
const [choice, setChoice] = useState<ThemeChoice>(storedChoice)
|
||||
|
||||
useEffect(() => {
|
||||
apply(choice)
|
||||
window.studio.setTheme(choice)
|
||||
localStorage.setItem(STORAGE_KEY, choice)
|
||||
const media = matchMedia(DARK_QUERY)
|
||||
const follow = (): void => apply(choice)
|
||||
media.addEventListener('change', follow)
|
||||
return () => media.removeEventListener('change', follow)
|
||||
}, [choice])
|
||||
|
||||
return { choice, next: () => setChoice(ORDER[(ORDER.indexOf(choice) + 1) % ORDER.length]) }
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
@import "tailwindcss";
|
||||
|
||||
@custom-variant dark (&:is(.dark *));
|
||||
|
||||
/* The studio's colours, taken from the Swing studio (StudioTheme) so both look alike. */
|
||||
:root {
|
||||
--background: #ffffff;
|
||||
--foreground: #000000;
|
||||
--card: #f7f8fa;
|
||||
--card-foreground: #000000;
|
||||
--popover: rgb(255 255 255 / 0.94);
|
||||
--popover-foreground: #000000;
|
||||
--primary: #3574f0;
|
||||
--primary-foreground: #ffffff;
|
||||
--secondary: #dfe1e5;
|
||||
--secondary-foreground: #000000;
|
||||
--muted: #f7f8fa;
|
||||
--muted-foreground: #818594;
|
||||
--secondary-text: #6c707e;
|
||||
--accent: #dfe1e5;
|
||||
--accent-foreground: #000000;
|
||||
--selection: #d4e2ff;
|
||||
--destructive: #db3b4b;
|
||||
--warning: #c27d04;
|
||||
--success: #208a3c;
|
||||
--link: #315fbd;
|
||||
--border: #ebecf0;
|
||||
--input: #c9ccd6;
|
||||
--ring: #3574f0;
|
||||
--overlay-border: #dfe1e5;
|
||||
--map-background: #e4e6eb;
|
||||
--radius: 10px;
|
||||
}
|
||||
|
||||
.dark {
|
||||
--background: #1e1f22;
|
||||
--foreground: #dfe1e5;
|
||||
--card: #2b2d30;
|
||||
--card-foreground: #dfe1e5;
|
||||
--popover: rgb(43 45 48 / 0.93);
|
||||
--popover-foreground: #dfe1e5;
|
||||
--primary: #3574f0;
|
||||
--primary-foreground: #ffffff;
|
||||
--secondary: #393b40;
|
||||
--secondary-foreground: #dfe1e5;
|
||||
--muted: #2b2d30;
|
||||
--muted-foreground: #6f737a;
|
||||
--secondary-text: #9da0a8;
|
||||
--accent: #393b40;
|
||||
--accent-foreground: #dfe1e5;
|
||||
--selection: #2e436e;
|
||||
--destructive: #f75464;
|
||||
--warning: #f2c55c;
|
||||
--success: #5fb865;
|
||||
--link: #548af7;
|
||||
--border: #1e1f22;
|
||||
--input: #4e5157;
|
||||
--ring: #3574f0;
|
||||
--overlay-border: #43454a;
|
||||
--map-background: #16171a;
|
||||
}
|
||||
|
||||
@theme inline {
|
||||
--color-background: var(--background);
|
||||
--color-foreground: var(--foreground);
|
||||
--color-card: var(--card);
|
||||
--color-card-foreground: var(--card-foreground);
|
||||
--color-popover: var(--popover);
|
||||
--color-popover-foreground: var(--popover-foreground);
|
||||
--color-primary: var(--primary);
|
||||
--color-primary-foreground: var(--primary-foreground);
|
||||
--color-secondary: var(--secondary);
|
||||
--color-secondary-foreground: var(--secondary-foreground);
|
||||
--color-muted: var(--muted);
|
||||
--color-muted-foreground: var(--muted-foreground);
|
||||
--color-secondary-text: var(--secondary-text);
|
||||
--color-accent: var(--accent);
|
||||
--color-accent-foreground: var(--accent-foreground);
|
||||
--color-selection: var(--selection);
|
||||
--color-destructive: var(--destructive);
|
||||
--color-warning: var(--warning);
|
||||
--color-success: var(--success);
|
||||
--color-link: var(--link);
|
||||
--color-border: var(--border);
|
||||
--color-input: var(--input);
|
||||
--color-ring: var(--ring);
|
||||
--color-overlay-border: var(--overlay-border);
|
||||
--color-map-background: var(--map-background);
|
||||
--radius-sm: calc(var(--radius) - 4px);
|
||||
--radius-md: calc(var(--radius) - 2px);
|
||||
--radius-lg: var(--radius);
|
||||
--radius-xl: calc(var(--radius) + 4px);
|
||||
--font-sans: "Inter", "Segoe UI", system-ui, sans-serif;
|
||||
--font-mono: "JetBrains Mono", ui-monospace, monospace;
|
||||
}
|
||||
|
||||
@layer base {
|
||||
* {
|
||||
@apply border-border outline-ring/50;
|
||||
}
|
||||
|
||||
html,
|
||||
body,
|
||||
#root {
|
||||
@apply h-full overflow-hidden;
|
||||
}
|
||||
|
||||
body {
|
||||
@apply bg-background text-foreground text-[13px] antialiased select-none;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
/** A bridge a running Iris server opened, as its connection file or a studio link describes it. */
|
||||
export interface BridgeConnection {
|
||||
world: string
|
||||
port: number
|
||||
token: string
|
||||
startedMillis?: number
|
||||
}
|
||||
|
||||
export type ThemeChoice = 'system' | 'light' | 'dark'
|
||||
|
||||
/** What the preload script hands the renderer. */
|
||||
export interface StudioHost {
|
||||
listBridges(): Promise<BridgeConnection[]>
|
||||
/** The studio link the app was started with, if any. */
|
||||
initialLink(): Promise<string | null>
|
||||
onLink(listener: (link: string) => void): () => void
|
||||
setTheme(theme: ThemeChoice): void
|
||||
copyText(text: string): void
|
||||
}
|
||||
|
||||
const LINK_PROTOCOL = 'iris-studio:'
|
||||
|
||||
/** The bridge a link such as {@code iris-studio://127.0.0.1:44503/?token=...} names; null for anything else. */
|
||||
export function parseStudioLink(text: string): BridgeConnection | null {
|
||||
let url: URL
|
||||
try {
|
||||
url = new URL(text.trim())
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
const port = Number(url.port)
|
||||
const token = url.searchParams.get('token')
|
||||
if (url.protocol !== LINK_PROTOCOL || !Number.isInteger(port) || port <= 0 || !token) {
|
||||
return null
|
||||
}
|
||||
return { world: url.searchParams.get('world') ?? '', port, token }
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2023",
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "Bundler",
|
||||
"lib": ["ES2023", "DOM", "DOM.Iterable"],
|
||||
"jsx": "react-jsx",
|
||||
"strict": true,
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"skipLibCheck": true,
|
||||
"isolatedModules": true,
|
||||
"resolveJsonModule": true,
|
||||
"types": ["node"],
|
||||
"paths": { "@/*": ["./src/renderer/src/*"] }
|
||||
},
|
||||
"include": ["src", "electron.vite.config.ts"]
|
||||
}
|
||||
Reference in new issue
Block a user