adding initial world map frontend
This commit is contained in:
+101
-59
@@ -1,11 +1,12 @@
|
||||
import { parseLlmJson, ensureArray, flattenValue } from "../lib/llm-parse";
|
||||
import { useState } from "react";
|
||||
import { useState, useEffect } from "react";
|
||||
import { invoke } from "@tauri-apps/api/core";
|
||||
import { addToLore } from "../lib/lore";
|
||||
import { useToast } from "./Toast";
|
||||
import { addGeneration, extractTitle, type Generation } from "../lib/generations";
|
||||
import { usePrefillEffect } from "../lib/usePrefill";
|
||||
import { usePersistentState } from "../lib/usePersistentState";
|
||||
import { WorldMap } from "./WorldMap";
|
||||
|
||||
interface WorldResponse {
|
||||
name: string;
|
||||
@@ -14,6 +15,9 @@ interface WorldResponse {
|
||||
landmarks: string[];
|
||||
conflicts: string[];
|
||||
cultures: string[];
|
||||
// ponytail: DM-placed pin positions (normalized 0..1). UI-managed, not
|
||||
// returned by the LLM. Persisted with the world.
|
||||
pins?: Record<string, { x: number; y: number }>;
|
||||
}
|
||||
|
||||
interface Props {
|
||||
@@ -26,8 +30,22 @@ export function WorldBuilder({ prefill, onPrefillConsumed }: Props = {}) {
|
||||
const [theme, setTheme] = usePersistentState<string>("world.theme", "high fantasy");
|
||||
const [world, setWorld] = usePersistentState<WorldResponse | null>("world.last", null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [selected, setSelected] = useState<string | null>(null);
|
||||
const { addToast } = useToast();
|
||||
|
||||
// ponytail: record a dragged pin's position into the world so it persists.
|
||||
function onPinMove(name: string, x: number, y: number) {
|
||||
setWorld((w) => w ? { ...w, pins: { ...(w.pins ?? {}), [name]: { x, y } } } : w);
|
||||
}
|
||||
|
||||
// ponytail: drop a selection that no longer exists on the map (e.g.
|
||||
// after a regenerate or loading a different world from history).
|
||||
useEffect(() => {
|
||||
if (!world || !selected) return;
|
||||
const names = [...ensureArray(world.regions), ...ensureArray(world.landmarks)].map(flattenValue);
|
||||
if (!names.includes(selected)) setSelected(null);
|
||||
}, [world, selected]);
|
||||
|
||||
// ponytail: genre presets as a quick-pick row.
|
||||
const THEME_PRESETS = [
|
||||
"high fantasy", "dark fantasy", "sword & sorcery",
|
||||
@@ -140,69 +158,93 @@ IMPORTANT: Return ONLY a raw JSON object. NO markdown fences, NO code blocks, NO
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Regions */}
|
||||
{world.regions?.length > 0 && (
|
||||
<div>
|
||||
<h4 className="text-[var(--color-text-secondary)] text-xs font-medium mb-1.5">
|
||||
🏔 Regions
|
||||
</h4>
|
||||
<div className="flex flex-col gap-1.5">
|
||||
{ensureArray(world.regions).map((r, i) => (
|
||||
<div key={i} className="rounded-lg bg-[var(--color-bg-surface)] border border-[var(--color-border-subtle)] px-3 py-2 text-sm text-[var(--color-text-primary)]">
|
||||
{flattenValue(r)}
|
||||
{/* Map + side details. Two-pane on wide screens; stacked on narrow. */}
|
||||
<div className="grid grid-cols-1 lg:grid-cols-3 gap-3">
|
||||
<div className="lg:col-span-2">
|
||||
<WorldMap
|
||||
regions={ensureArray(world.regions).map(flattenValue)}
|
||||
landmarks={ensureArray(world.landmarks).map(flattenValue)}
|
||||
pins={world.pins ?? {}}
|
||||
selected={selected}
|
||||
onSelect={setSelected}
|
||||
onPinMove={onPinMove}
|
||||
/>
|
||||
<p className="text-[10px] text-[var(--color-text-dim)] mt-1">
|
||||
Drag pins to place regions (●) and landmarks (✦). Click a pin to select it.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-2">
|
||||
{/* Selected pin detail, or a hint to pick one. */}
|
||||
<div className="rounded-lg bg-[var(--color-bg-surface)] border border-[var(--color-border-glass)] p-3">
|
||||
{selected ? (
|
||||
<>
|
||||
<span className="text-[10px] uppercase tracking-wider text-[var(--color-gold-muted)]">
|
||||
{ensureArray(world.regions).map(flattenValue).includes(selected) ? "Region" : "Landmark"}
|
||||
</span>
|
||||
<p className="text-[var(--color-text-primary)] text-sm mt-1">{selected}</p>
|
||||
</>
|
||||
) : (
|
||||
<p className="text-[var(--color-text-dim)] text-xs italic">
|
||||
Click a pin on the map to inspect it here.
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Regions (clickable → select on map) */}
|
||||
{world.regions?.length > 0 && (
|
||||
<div>
|
||||
<h4 className="text-[var(--color-text-secondary)] text-xs font-medium mb-1.5">🏔 Regions</h4>
|
||||
<div className="flex flex-col gap-1">
|
||||
{ensureArray(world.regions).map((r, i) => {
|
||||
const name = flattenValue(r);
|
||||
return (
|
||||
<button
|
||||
key={i}
|
||||
onClick={() => setSelected(name)}
|
||||
className={`text-left rounded-lg px-3 py-1.5 text-xs cursor-pointer transition-colors ${
|
||||
selected === name
|
||||
? "bg-[var(--color-gold-glow)] text-[var(--color-gold-bright)] border border-[var(--color-gold-bright)]"
|
||||
: "bg-[var(--color-bg-surface)] border border-[var(--color-border-subtle)] text-[var(--color-text-primary)] hover:border-[var(--color-gold-muted)]"
|
||||
}`}
|
||||
>
|
||||
{name}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Landmarks */}
|
||||
{world.landmarks?.length > 0 && (
|
||||
<div>
|
||||
<h4 className="text-[var(--color-text-secondary)] text-xs font-medium mb-1.5">
|
||||
🏛 Landmarks
|
||||
</h4>
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
{ensureArray(world.landmarks).map((l, i) => (
|
||||
<span key={i} className="rounded-full bg-[var(--color-gold-glow)] text-[var(--color-gold-bright)] px-3 py-1 text-xs">
|
||||
{flattenValue(l)}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Conflicts */}
|
||||
{world.conflicts?.length > 0 && (
|
||||
<div>
|
||||
<h4 className="text-[var(--color-text-secondary)] text-xs font-medium mb-1.5">
|
||||
⚔ Conflicts
|
||||
</h4>
|
||||
<div className="flex flex-col gap-1.5">
|
||||
{ensureArray(world.conflicts).map((c, i) => (
|
||||
<div key={i} className="rounded-lg bg-[var(--color-bg-surface)] border-l-2 border-[var(--color-danger)] px-3 py-2 text-sm text-[var(--color-text-primary)]">
|
||||
{flattenValue(c)}
|
||||
{/* Conflicts */}
|
||||
{world.conflicts?.length > 0 && (
|
||||
<div>
|
||||
<h4 className="text-[var(--color-text-secondary)] text-xs font-medium mb-1.5">⚔ Conflicts</h4>
|
||||
<div className="flex flex-col gap-1">
|
||||
{ensureArray(world.conflicts).map((c, i) => (
|
||||
<div key={i} className="rounded-lg bg-[var(--color-bg-surface)] border-l-2 border-[var(--color-danger)] px-3 py-1.5 text-xs text-[var(--color-text-primary)]">
|
||||
{flattenValue(c)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Cultures */}
|
||||
{world.cultures?.length > 0 && (
|
||||
<div>
|
||||
<h4 className="text-[var(--color-text-secondary)] text-xs font-medium mb-1.5">
|
||||
👥 Cultures
|
||||
</h4>
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
{ensureArray(world.cultures).map((c, i) => (
|
||||
<span key={i} className="rounded-full bg-[var(--color-bg-surface)] border border-[var(--color-info)]/30 text-[var(--color-info)] px-3 py-1 text-xs">
|
||||
{flattenValue(c)}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
{/* Cultures */}
|
||||
{world.cultures?.length > 0 && (
|
||||
<div>
|
||||
<h4 className="text-[var(--color-text-secondary)] text-xs font-medium mb-1.5">👥 Cultures</h4>
|
||||
<div className="flex flex-wrap gap-1">
|
||||
{ensureArray(world.cultures).map((c, i) => (
|
||||
<span key={i} className="rounded-full bg-[var(--color-bg-surface)] border border-[var(--color-info)]/30 text-[var(--color-info)] px-2.5 py-1 text-[11px]">
|
||||
{flattenValue(c)}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,158 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { Stage, Layer, Rect, Circle, Text, Group, Line, Star } from "react-konva";
|
||||
import type { KonvaEventObject } from "konva/lib/Node";
|
||||
import { buildPins, clamp, type PinPos } from "../lib/worldMap";
|
||||
|
||||
interface Props {
|
||||
regions: string[];
|
||||
landmarks: string[];
|
||||
pins: Record<string, { x: number; y: number }>;
|
||||
selected: string | null;
|
||||
onSelect: (name: string | null) => void;
|
||||
onPinMove: (name: string, x: number, y: number) => void;
|
||||
}
|
||||
|
||||
export function WorldMap({ regions, landmarks, pins, selected, onSelect, onPinMove }: Props) {
|
||||
const containerRef = useRef<HTMLDivElement>(null);
|
||||
const [size, setSize] = useState({ w: 600, h: 420 });
|
||||
|
||||
// Measure the container so the canvas is responsive. 5:7-ish aspect.
|
||||
useEffect(() => {
|
||||
const el = containerRef.current;
|
||||
if (!el) return;
|
||||
const update = () => {
|
||||
const w = el.clientWidth;
|
||||
setSize({ w, h: Math.round(w * 0.62) });
|
||||
};
|
||||
update();
|
||||
const ro = new ResizeObserver(update);
|
||||
ro.observe(el);
|
||||
return () => ro.disconnect();
|
||||
}, []);
|
||||
|
||||
// Build the pin list: saved positions win, else auto-layout. Pure helper so
|
||||
// the layout math has a runnable self-check (see src/lib/worldMap.ts).
|
||||
const pinList: PinPos[] = buildPins(regions, landmarks, pins);
|
||||
|
||||
const { w, h } = size;
|
||||
|
||||
return (
|
||||
<div ref={containerRef} className="w-full">
|
||||
<Stage
|
||||
width={w}
|
||||
height={h}
|
||||
onClick={(e: KonvaEventObject<MouseEvent>) => {
|
||||
// Click on empty canvas deselects.
|
||||
if (e.target === e.target.getStage()) onSelect(null);
|
||||
}}
|
||||
className="rounded-xl border border-[var(--color-border-glass)]"
|
||||
>
|
||||
<Layer>
|
||||
{/* Parchment-style chart background: deep navy with a faint gold grid. */}
|
||||
<Rect x={0} y={0} width={w} height={h} fill="#0d1424" />
|
||||
{/* Faint grid lines */}
|
||||
{Array.from({ length: 9 }, (_, i) => {
|
||||
const gx = (i + 1) * (w / 10);
|
||||
const gy = (i + 1) * (h / 10);
|
||||
return (
|
||||
<Group key={`grid-${i}`}>
|
||||
<Line points={[gx, 0, gx, h]} stroke="#d4af37" opacity={0.05} />
|
||||
<Line points={[0, gy, w, gy]} stroke="#d4af37" opacity={0.05} />
|
||||
</Group>
|
||||
);
|
||||
})}
|
||||
{/* Vignette frame */}
|
||||
<Rect
|
||||
x={0}
|
||||
y={0}
|
||||
width={w}
|
||||
height={h}
|
||||
stroke="#d4af37"
|
||||
strokeWidth={2}
|
||||
opacity={0.3}
|
||||
listening={false}
|
||||
cornerRadius={6}
|
||||
/>
|
||||
{/* Compass rose (top-right) */}
|
||||
<Group x={w - 36} y={32} listening={false}>
|
||||
<Circle radius={14} stroke="#d4af37" opacity={0.4} />
|
||||
<Line points={[0, -14, 0, 14]} stroke="#d4af37" opacity={0.5} />
|
||||
<Line points={[-14, 0, 14, 0]} stroke="#d4af37" opacity={0.5} />
|
||||
<Text text="N" x={-4} y={-26} fontSize={9} fill="#d4af37" />
|
||||
</Group>
|
||||
</Layer>
|
||||
|
||||
<Layer>
|
||||
{pinList.map((pin) => {
|
||||
const px = pin.x * w;
|
||||
const py = pin.y * h;
|
||||
const isRegion = pin.kind === "region";
|
||||
const isSelected = pin.name === selected;
|
||||
return (
|
||||
<Group
|
||||
key={`${pin.kind}-${pin.name}`}
|
||||
x={px}
|
||||
y={py}
|
||||
draggable
|
||||
onClick={(e) => {
|
||||
e.cancelBubble = true;
|
||||
onSelect(pin.name);
|
||||
}}
|
||||
onTap={(e) => {
|
||||
e.cancelBubble = true;
|
||||
onSelect(pin.name);
|
||||
}}
|
||||
onDragEnd={(e) => {
|
||||
// ponytail: record the clamped normalized position; the React
|
||||
// re-render repositions the node, so no manual snap-back here
|
||||
// (the closure `pin` would be stale and snap it to the old spot).
|
||||
onPinMove(pin.name, clamp(e.target.x() / w), clamp(e.target.y() / h));
|
||||
}}
|
||||
>
|
||||
{isRegion ? (
|
||||
<>
|
||||
<Circle
|
||||
radius={isSelected ? 11 : 8}
|
||||
fill="#d4af37"
|
||||
stroke={isSelected ? "#fff" : "#0a0e1a"}
|
||||
strokeWidth={isSelected ? 2 : 1}
|
||||
shadowColor="#d4af37"
|
||||
shadowBlur={isSelected ? 16 : 6}
|
||||
shadowOpacity={0.6}
|
||||
/>
|
||||
<Circle radius={3} fill="#0a0e1a" />
|
||||
</>
|
||||
) : (
|
||||
<Star
|
||||
numPoints={5}
|
||||
innerRadius={4}
|
||||
outerRadius={isSelected ? 9 : 7}
|
||||
fill="#8b9bb4"
|
||||
stroke={isSelected ? "#d4af37" : "#0a0e1a"}
|
||||
strokeWidth={isSelected ? 2 : 1}
|
||||
/>
|
||||
)}
|
||||
<Text
|
||||
text={pin.name}
|
||||
x={-60}
|
||||
y={isRegion ? 12 : 10}
|
||||
width={120}
|
||||
align="center"
|
||||
fontSize={isRegion ? 11 : 10}
|
||||
fontStyle={isRegion ? "bold" : "normal"}
|
||||
fill={isSelected ? "#d4af37" : "#e8e0d0"}
|
||||
stroke="#0a0e1a"
|
||||
strokeWidth={3}
|
||||
// ponytail: paint fill over stroke so the label gets a dark
|
||||
// outline and reads over grid lines + other pins.
|
||||
fillAfterStrokeEnabled
|
||||
listening={false}
|
||||
/>
|
||||
</Group>
|
||||
);
|
||||
})}
|
||||
</Layer>
|
||||
</Stage>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
// ponytail: pure layout math for the WorldMap, extracted so it's testable
|
||||
// without konva. Positions are normalized 0..1 so the map survives a resize.
|
||||
|
||||
export type PinKind = "region" | "landmark";
|
||||
|
||||
export interface PinPos {
|
||||
name: string;
|
||||
x: number; // 0..1
|
||||
y: number; // 0..1
|
||||
kind: PinKind;
|
||||
}
|
||||
|
||||
// Clamp a normalized coordinate into the canvas with a small margin so a pin
|
||||
// can't be dragged half-off the edge.
|
||||
export function clamp(v: number): number {
|
||||
return Math.max(0.04, Math.min(0.96, v));
|
||||
}
|
||||
|
||||
// Distribute N items on a centered ellipse so an unedited world reads as a
|
||||
// map rather than a stacked list. Deterministic by index.
|
||||
export function autoLayout(index: number, total: number, kind: PinKind): { x: number; y: number } {
|
||||
if (total <= 0) return { x: 0.5, y: 0.5 };
|
||||
if (total === 1) return { x: 0.5, y: 0.5 };
|
||||
if (kind === "region") {
|
||||
const angle = (index / total) * Math.PI * 2 - Math.PI / 2;
|
||||
return { x: 0.5 + Math.cos(angle) * 0.32, y: 0.5 + Math.sin(angle) * 0.34 };
|
||||
}
|
||||
// landmarks: inner ring, offset by half a step so they don't overlap regions
|
||||
const angle = (index / total) * Math.PI * 2;
|
||||
return { x: 0.5 + Math.cos(angle) * 0.18, y: 0.5 + Math.sin(angle) * 0.2 };
|
||||
}
|
||||
|
||||
// Build the pin list: saved positions win, else auto-layout. Returns one pin
|
||||
// per name; duplicates keep distinct pins by kind+index but share a position
|
||||
// key, so the last duplicate's saved position wins for that name.
|
||||
export function buildPins(
|
||||
regions: string[],
|
||||
landmarks: string[],
|
||||
pins: Record<string, { x: number; y: number }>,
|
||||
): PinPos[] {
|
||||
const out: PinPos[] = [];
|
||||
regions.forEach((name, i) => {
|
||||
const pos = pins[name] ?? autoLayout(i, regions.length, "region");
|
||||
out.push({ name, x: clamp(pos.x), y: clamp(pos.y), kind: "region" });
|
||||
});
|
||||
landmarks.forEach((name, i) => {
|
||||
const pos = pins[name] ?? autoLayout(i, landmarks.length, "landmark");
|
||||
out.push({ name, x: clamp(pos.x), y: clamp(pos.y), kind: "landmark" });
|
||||
});
|
||||
return out;
|
||||
}
|
||||
|
||||
// ─── Self-check (run: node src/lib/worldMap.ts) ──────────────
|
||||
// ponytail: the smallest thing that fails if the layout math breaks. No
|
||||
// framework — plain asserts. Verifies clamp bounds, auto-layout spread, and
|
||||
// that saved positions survive a buildPins round-trip.
|
||||
function assert(cond: boolean, msg: string): void {
|
||||
if (!cond) throw new Error(`worldMap self-check failed: ${msg}`);
|
||||
}
|
||||
|
||||
export function demo(): void {
|
||||
assert(clamp(-1) === 0.04, "clamp floors at margin");
|
||||
assert(clamp(2) === 0.96, "clamp ceilings at margin");
|
||||
assert(clamp(0.5) === 0.5, "clamp passes through mid");
|
||||
|
||||
// Single item centers; many items spread (no two identical on a ring).
|
||||
const single = autoLayout(0, 1, "region");
|
||||
assert(single.x === 0.5 && single.y === 0.5, "single item centers");
|
||||
|
||||
const many = Array.from({ length: 6 }, (_, i) => autoLayout(i, 6, "region"));
|
||||
const uniq = new Set(many.map((p) => `${p.x.toFixed(3)},${p.y.toFixed(3)}`));
|
||||
assert(uniq.size === 6, "6 regions spread to 6 distinct spots");
|
||||
|
||||
// Saved positions survive buildPins; unsaved ones get auto-laid-out + clamped.
|
||||
const built = buildPins(["A", "B"], ["X"], { A: { x: 0.2, y: 0.3 } });
|
||||
assert(built.length === 3, "buildPins returns regions + landmarks");
|
||||
const a = built.find((p) => p.name === "A")!;
|
||||
assert(a.x === 0.2 && a.y === 0.3, "saved position preserved");
|
||||
const b = built.find((p) => p.name === "B")!;
|
||||
assert(b.x >= 0.04 && b.x <= 0.96, "auto-laid-out pin is clamped");
|
||||
|
||||
console.log("worldMap self-check passed ✓");
|
||||
}
|
||||
Reference in New Issue
Block a user