Initial I Want to Heal app

This commit is contained in:
Warren H
2026-06-17 20:04:36 -04:00
parent 3880db1b58
commit 3c90998a61
109 changed files with 32775 additions and 0 deletions
+766
View File
@@ -0,0 +1,766 @@
import { useEffect, useState } from 'react'
type AdminItem = {
id: number
slug: string
name: string
slot: string
rarity: string
itemLevel: number
healingPower: number
maxResourceBonus: number
glyph: string
imageUrl: string
description: string
}
type AdminEncounter = {
id: number
dungeonId: number
sequence: number
slug: string
enemyName: string
encounterType: string
imageUrl: string
}
type AdminDifficulty = {
id: number
slug: string
name: string
droppedItemLevel: number
}
type AdminLootEntry = {
encounterId: number
itemId: number
difficultyId: number
dropWeight: number
dropChance: number
}
type AdminRecipeComponent = {
itemId: number
quantity: number
}
type AdminRecipe = {
id: number
itemId: number
difficultyId: number | null
sourceDungeonId: number | null
sourceEncounterId: number | null
components: AdminRecipeComponent[]
}
type AdminDungeon = {
id: number
slug: string
name: string
}
type AdminData = {
items: AdminItem[]
encounters: AdminEncounter[]
difficulties: AdminDifficulty[]
encounterLoot: AdminLootEntry[]
craftingRecipes: AdminRecipe[]
dungeons: AdminDungeon[]
}
const API = '/api/admin'
async function fetchJson<T>(url: string, init?: RequestInit): Promise<T> {
const res = await fetch(url, init)
const body = await res.json()
if (!res.ok) throw new Error(body.error ?? 'Request failed')
return body
}
export function AdminScreen({ onBack }: { onBack: () => void }) {
const [data, setData] = useState<AdminData | null>(null)
const [tab, setTab] = useState<'items' | 'bosses' | 'loot' | 'crafting'>('items')
const [error, setError] = useState('')
const [saving, setSaving] = useState<Record<string, boolean>>({})
useEffect(() => {
fetchJson<AdminData>(`${API}/data`)
.then(setData)
.catch((e: unknown) => setError(e instanceof Error ? e.message : 'Failed to load'))
}, [])
if (error) return <section className="content-screen"><p className="error-message">{error}</p></section>
if (!data) return <section className="content-screen"><p>Loading admin data...</p></section>
return (
<section className="content-screen admin-screen">
<div className="screen-heading">
<div><p className="eyebrow">Developer Tools</p><h1>Admin Panel</h1></div>
<button className="back-button" onClick={onBack} type="button">Back</button>
</div>
<nav className="admin-tabs">
{(['items', 'bosses', 'loot', 'crafting'] as const).map((t) => (
<button key={t} className={`admin-tab ${tab === t ? 'active' : ''}`}
onClick={() => setTab(t)} type="button">
{t === 'items' ? 'Items' : t === 'bosses' ? 'Boss Images' : t === 'loot' ? 'Boss Loot' : 'Crafting'}
</button>
))}
</nav>
{tab === 'items' && <ItemsTab data={data} setData={setData} setSaving={setSaving} saving={saving} />}
{tab === 'bosses' && <BossImagesTab data={data} setData={setData} setSaving={setSaving} saving={saving} />}
{tab === 'loot' && <LootTab data={data} setData={setData} setSaving={setSaving} saving={saving} />}
{tab === 'crafting' && <CraftingTab data={data} setData={setData} setSaving={setSaving} saving={saving} />}
</section>
)
}
function ItemsTab({ data, setData, setSaving, saving }: {
data: AdminData | null
setData: React.Dispatch<React.SetStateAction<AdminData | null>>
setSaving: (s: Record<string, boolean> | ((prev: Record<string, boolean>) => Record<string, boolean>)) => void
saving: Record<string, boolean>
}) {
if (!data) return null
const [filter, setFilter] = useState('')
const [editId, setEditId] = useState<number | null>(null)
const [form, setForm] = useState<Partial<AdminItem>>({})
const groups = groupBy(data.items.filter((i) =>
i.name.toLowerCase().includes(filter.toLowerCase()) || i.slug.includes(filter)),
(i) => i.slot,
)
async function saveItem(id: number) {
setSaving((prev) => ({ ...prev, [`item-${id}`]: true }))
try {
const body: Record<string, string | number> = {}
if (form.name !== undefined) body.name = form.name
if (form.glyph !== undefined) body.glyph = form.glyph
if (form.description !== undefined) body.description = form.description
if (form.rarity !== undefined) body.rarity = form.rarity
if (form.slot !== undefined) body.slot = form.slot
if (form.itemLevel !== undefined) body.item_level = form.itemLevel
if (form.healingPower !== undefined) body.healing_power = form.healingPower
if (form.maxResourceBonus !== undefined) body.max_resource_bonus = form.maxResourceBonus
await fetchJson(`${API}/items/${id}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
})
setData((prev) => prev ? {
...prev,
items: prev.items.map((i) => i.id === id ? { ...i, ...form } : i),
} : prev)
setEditId(null)
setForm({})
} catch (e: unknown) {
alert(e instanceof Error ? e.message : 'Save failed')
} finally {
setSaving((prev) => ({ ...prev, [`item-${id}`]: false }))
}
}
return (
<div className="admin-panel">
<input className="admin-search" placeholder="Search items..." value={filter}
onChange={(e) => setFilter(e.target.value)} />
{Object.entries(groups).map(([slot, items]) => (
<details key={slot} open>
<summary className="admin-group-header">{slot} ({items.length})</summary>
<div className="admin-grid">
{items.map((item) => (
<div key={item.id} className="admin-card">
{editId === item.id ? (
<div className="admin-edit-form">
<label>Glyph <input value={form.glyph ?? item.glyph} onChange={(e) => setForm({ ...form, glyph: e.target.value })} /></label>
<label>Name <input value={form.name ?? item.name} onChange={(e) => setForm({ ...form, name: e.target.value })} /></label>
<label>Slot
<select value={form.slot ?? item.slot} onChange={(e) => setForm({ ...form, slot: e.target.value })}>
{['weapon', 'helmet', 'chest', 'gloves', 'boots', 'pants', 'ring', 'necklace', 'trinket', 'component'].map((s) => (
<option key={s} value={s}>{s}</option>
))}
</select>
</label>
<label>Rarity
<select value={form.rarity ?? item.rarity} onChange={(e) => setForm({ ...form, rarity: e.target.value })}>
{['common', 'uncommon', 'rare', 'epic'].map((r) => (
<option key={r} value={r}>{r}</option>
))}
</select>
</label>
<label>iLvl <input type="number" value={form.itemLevel ?? item.itemLevel} onChange={(e) => setForm({ ...form, itemLevel: Number(e.target.value) })} /></label>
<label>Healing <input type="number" value={form.healingPower ?? item.healingPower} onChange={(e) => setForm({ ...form, healingPower: Number(e.target.value) })} /></label>
<label>Resource <input type="number" value={form.maxResourceBonus ?? item.maxResourceBonus} onChange={(e) => setForm({ ...form, maxResourceBonus: Number(e.target.value) })} /></label>
<label>Description <textarea value={form.description ?? item.description} onChange={(e) => setForm({ ...form, description: e.target.value })} /></label>
<div className="admin-edit-actions">
<button className="primary-button" onClick={() => saveItem(item.id)} disabled={saving[`item-${item.id}`]} type="button">
{saving[`item-${item.id}`] ? 'Saving...' : 'Save'}
</button>
<button className="text-button" onClick={() => { setEditId(null); setForm({}) }} type="button">Cancel</button>
</div>
</div>
) : (
<>
<div className="admin-item-header">
<span className={`admin-glyph rarity-${item.rarity}`}>{item.glyph}</span>
<div>
<strong>{item.name}</strong>
<small className="admin-item-meta">{item.slot} · iLvl {item.itemLevel} · {item.rarity}</small>
</div>
</div>
<p className="admin-item-desc">{item.description}</p>
<div className="admin-item-stats">
<span>+{item.healingPower} healing</span>
<span>+{item.maxResourceBonus} resource</span>
</div>
<button className="text-button" onClick={() => { setEditId(item.id); setForm({}) }} type="button">Edit</button>
</>
)}
</div>
))}
</div>
</details>
))}
</div>
)
}
function BossImagesTab({ data, setData, setSaving, saving }: {
data: AdminData | null
setData: React.Dispatch<React.SetStateAction<AdminData | null>>
setSaving: (s: Record<string, boolean> | ((prev: Record<string, boolean>) => Record<string, boolean>)) => void
saving: Record<string, boolean>
}) {
if (!data) return null
async function uploadBossImage(encounterId: number, file: File | undefined) {
if (!file) return
setSaving((prev) => ({ ...prev, [`boss-image-${encounterId}`]: true }))
try {
const imageData = await fileToDataUrl(file)
const result = await fetchJson<{ imageUrl: string }>(`${API}/encounters/${encounterId}/image`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ imageData }),
})
setData((prev) => prev ? {
...prev,
encounters: prev.encounters.map((encounter) => (
encounter.id === encounterId
? { ...encounter, imageUrl: result.imageUrl }
: encounter
)),
} : prev)
} catch (e: unknown) {
alert(e instanceof Error ? e.message : 'Upload failed')
} finally {
setSaving((prev) => ({ ...prev, [`boss-image-${encounterId}`]: false }))
}
}
const bosses = data.encounters.filter((encounter) => encounter.encounterType === 'boss')
return (
<div className="admin-panel">
<div className="admin-grid boss-image-grid">
{bosses.map((boss) => (
<div key={boss.id} className="admin-card boss-image-card">
<img src={boss.imageUrl} alt={`${boss.enemyName} icon`} />
<div>
<strong>{boss.enemyName}</strong>
<small className="admin-item-meta">Dungeon {boss.dungeonId} · Encounter {boss.sequence}</small>
</div>
<label className="boss-upload-button">
{saving[`boss-image-${boss.id}`] ? 'Uploading...' : 'Upload Image'}
<input
accept="image/png,image/jpeg,image/webp,image/gif"
disabled={saving[`boss-image-${boss.id}`]}
onChange={(event) => uploadBossImage(boss.id, event.target.files?.[0])}
type="file"
/>
</label>
</div>
))}
</div>
</div>
)
}
function LootTab({ data, setData, setSaving, saving }: {
data: AdminData | null
setData: React.Dispatch<React.SetStateAction<AdminData | null>>
setSaving: (s: Record<string, boolean> | ((prev: Record<string, boolean>) => Record<string, boolean>)) => void
saving: Record<string, boolean>
}) {
const [encounterId, setEncounterId] = useState(data?.encounters.filter(e => e.encounterType === 'boss')[0]?.id ?? 0)
const [difficultyId, setDifficultyId] = useState(data?.difficulties[0]?.id ?? 0)
const [addItemId, setAddItemId] = useState(0)
const [addDropWeight, setAddDropWeight] = useState(100)
const [addDropChance, setAddDropChance] = useState(1)
const [renameItemId, setRenameItemId] = useState<number | null>(null)
const [renameValue, setRenameValue] = useState('')
const [bossSort, setBossSort] = useState<'dungeon' | 'boss'>('dungeon')
if (!data) return null
const enc = data.encounters.find(e => e.id === encounterId)
const bossOptions = data.encounters
.filter((e) => e.encounterType === 'boss')
.sort((a, b) => bossSort === 'boss'
? a.enemyName.localeCompare(b.enemyName) || a.dungeonId - b.dungeonId || a.sequence - b.sequence
: a.dungeonId - b.dungeonId || a.sequence - b.sequence || a.enemyName.localeCompare(b.enemyName))
const bossLoot = data.encounterLoot.filter(
(l) => l.encounterId === encounterId && l.difficultyId === difficultyId,
)
const items = data.items
function itemName(id: number) { return items.find(i => i.id === id)?.name ?? `#${id}` }
function itemGlyph(id: number) { return items.find(i => i.id === id)?.glyph ?? '?' }
async function renameItem(itemId: number) {
if (renameValue.trim() === '' || renameValue === itemName(itemId)) return
setSaving((prev) => ({ ...prev, [`loot-rename-${itemId}`]: true }))
try {
await fetchJson(`${API}/items/${itemId}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: renameValue.trim() }),
})
setData((prev) => prev ? {
...prev,
items: prev.items.map((item) =>
item.id === itemId ? { ...item, name: renameValue.trim() } : item,
),
} : prev)
setRenameItemId(null)
setRenameValue('')
} catch (e: unknown) {
alert(e instanceof Error ? e.message : 'Rename failed')
} finally {
setSaving((prev) => ({ ...prev, [`loot-rename-${itemId}`]: false }))
}
}
async function deleteLoot(eId: number, dId: number, iId: number) {
try {
await fetchJson(`${API}/encounter-loot/${eId}/${dId}/${iId}`, { method: 'DELETE' })
setData((prev) => prev ? {
...prev,
encounterLoot: prev.encounterLoot.filter(
(l) => !(l.encounterId === eId && l.difficultyId === dId && l.itemId === iId),
),
} : prev)
} catch (e: unknown) {
alert(e instanceof Error ? e.message : 'Delete failed')
}
}
async function addLoot() {
if (!addItemId) return
try {
await fetchJson(`${API}/encounter-loot`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ encounterId, itemId: addItemId, difficultyId, dropWeight: addDropWeight, dropChance: addDropChance }),
})
setData((prev) => prev ? {
...prev,
encounterLoot: [
...prev.encounterLoot.filter(
(l) => !(l.encounterId === encounterId && l.difficultyId === difficultyId && l.itemId === addItemId),
),
{ encounterId, itemId: addItemId, difficultyId, dropWeight: addDropWeight, dropChance: addDropChance },
],
} : prev)
setAddItemId(0)
setAddDropWeight(100)
setAddDropChance(1)
} catch (e: unknown) {
alert(e instanceof Error ? e.message : 'Add failed')
}
}
return (
<div className="admin-panel">
<div className="admin-loot-selectors">
<label>Boss
<select value={encounterId} onChange={(e) => setEncounterId(Number(e.target.value))}>
{bossOptions.map((e) => (
<option key={e.id} value={e.id}>{e.enemyName} (dungeon {e.dungeonId})</option>
))}
</select>
</label>
<label>Sort Bosses
<select value={bossSort} onChange={(e) => setBossSort(e.target.value as 'dungeon' | 'boss')}>
<option value="dungeon">Dungeon order</option>
<option value="boss">Boss name</option>
</select>
</label>
<label>Difficulty
<select value={difficultyId} onChange={(e) => setDifficultyId(Number(e.target.value))}>
{data.difficulties.map((d) => (
<option key={d.id} value={d.id}>{d.name} (iLvl {d.droppedItemLevel})</option>
))}
</select>
</label>
</div>
<h3 className="admin-loot-title">
{enc?.enemyName ?? 'Unknown'} {data.difficulties.find(d => d.id === difficultyId)?.name ?? '?'}
</h3>
{bossLoot.length === 0 && <p className="admin-empty">No loot entries for this boss + difficulty.</p>}
<div className="admin-loot-list">
{bossLoot.map((entry) => (
<div key={`${entry.itemId}`} className="admin-loot-row">
<span className={`admin-glyph rarity-${data.items.find(i => i.id === entry.itemId)?.rarity ?? 'common'}`}>
{itemGlyph(entry.itemId)}
</span>
{renameItemId === entry.itemId ? (
<span className="admin-loot-name">
<input
className="admin-rename-input"
ref={(node) => {
if (node) window.requestAnimationFrame(() => node.focus({ preventScroll: true }))
}}
value={renameValue}
onChange={(e) => setRenameValue(e.target.value)}
onKeyDown={(e) => { if (e.key === 'Enter') renameItem(entry.itemId); if (e.key === 'Escape') { setRenameItemId(null); setRenameValue('') } }}
/>
</span>
) : (
<span className="admin-loot-name">{itemName(entry.itemId)}</span>
)}
<span className="admin-loot-weight">Weight: {entry.dropWeight}</span>
<span className="admin-loot-chance">Chance: {(entry.dropChance * 100).toFixed(0)}%</span>
{renameItemId === entry.itemId ? (
<>
<button className="primary-button" disabled={saving[`loot-rename-${entry.itemId}`]} onClick={() => renameItem(entry.itemId)} type="button">
{saving[`loot-rename-${entry.itemId}`] ? 'Saving...' : 'Save'}
</button>
<button className="text-button" onClick={() => { setRenameItemId(null); setRenameValue('') }} type="button">Cancel</button>
</>
) : (
<>
<button className="text-button" onClick={() => { setRenameItemId(entry.itemId); setRenameValue(itemName(entry.itemId)) }} type="button">Rename</button>
<button className="danger-button" onClick={() => deleteLoot(entry.encounterId, entry.difficultyId, entry.itemId)} type="button">X</button>
</>
)}
</div>
))}
</div>
<details className="admin-add-section">
<summary>Add Item to Loot Table</summary>
<div className="admin-add-form">
<label>Item
<select value={addItemId} onChange={(e) => setAddItemId(Number(e.target.value))}>
<option value={0}>Select item...</option>
{data.items.filter((i) => !bossLoot.some((l) => l.itemId === i.id)).map((i) => (
<option key={i.id} value={i.id}>[{i.glyph}] {i.name} ({i.slot})</option>
))}
</select>
</label>
<label>Drop Weight <input type="number" value={addDropWeight} onChange={(e) => setAddDropWeight(Number(e.target.value))} /></label>
<label>Drop Chance <input type="number" min="0" max="1" step="0.05" value={addDropChance} onChange={(e) => setAddDropChance(Number(e.target.value))} /></label>
<button className="primary-button" onClick={addLoot} disabled={!addItemId} type="button">Add</button>
</div>
</details>
</div>
)
}
function CraftingTab({ data, setData, setSaving, saving }: {
data: AdminData | null
setData: React.Dispatch<React.SetStateAction<AdminData | null>>
setSaving: (s: Record<string, boolean> | ((prev: Record<string, boolean>) => Record<string, boolean>)) => void
saving: Record<string, boolean>
}) {
const [recipeId, setRecipeId] = useState(data?.craftingRecipes[0]?.id ?? 0)
const [itemLevelFilter, setItemLevelFilter] = useState('all')
const [bossFilterId, setBossFilterId] = useState(0)
const [addItemId, setAddItemId] = useState(0)
const [addQty, setAddQty] = useState(1)
const [outputNameByItem, setOutputNameByItem] = useState<Record<number, string>>({})
if (!data) return null
const bossEncounters = data.encounters.filter((encounter) => encounter.encounterType === 'boss')
const bossLootItemIds = new Set(
data.encounterLoot
.filter((entry) => bossEncounters.some((boss) => boss.id === entry.encounterId))
.map((entry) => entry.itemId),
)
const itemLevels = Array.from(new Set(
data.craftingRecipes
.map((candidate) => data.items.find((item) => item.id === candidate.itemId)?.itemLevel)
.filter((itemLevel): itemLevel is number => itemLevel !== undefined),
)).sort((a, b) => a - b)
const filteredRecipes = data.craftingRecipes.filter((candidate) => {
const item = data.items.find((i) => i.id === candidate.itemId)
if (!item) return false
if (itemLevelFilter !== 'all' && item.itemLevel !== Number(itemLevelFilter)) return false
if (bossFilterId === 0) return true
return candidate.sourceEncounterId === bossFilterId
|| candidate.components.some((component) => data.encounterLoot.some(
(entry) => entry.encounterId === bossFilterId && entry.itemId === component.itemId,
))
})
const recipe = filteredRecipes.find((r) => r.id === recipeId) ?? filteredRecipes[0] ?? null
const outputItem = recipe ? data.items.find((i) => i.id === recipe.itemId) : null
const outputName = outputItem ? outputNameByItem[outputItem.id] ?? outputItem.name : ''
const bossComponentOptions = data.items.filter((item) => (
item.slot === 'component'
&& bossLootItemIds.has(item.id)
&& !recipe?.components.some((component) => component.itemId === item.id)
))
const addComponentIsValid = bossComponentOptions.some((item) => item.id === addItemId)
const items = data.items
function itemName(id: number) { return items.find(i => i.id === id)?.name ?? `#${id}` }
function itemGlyph(id: number) { return items.find(i => i.id === id)?.glyph ?? '?' }
function bossName(id: number | null) {
return id ? bossEncounters.find((boss) => boss.id === id)?.enemyName ?? `Boss #${id}` : 'Any boss'
}
function componentBossNames(itemId: number) {
return (data!).encounterLoot
.filter((entry) => entry.itemId === itemId)
.map((entry) => bossEncounters.find((boss) => boss.id === entry.encounterId)?.enemyName ?? `Boss #${entry.encounterId}`)
.join(', ')
}
async function saveOutputName() {
if (!outputItem || outputName.trim() === '' || outputName === outputItem.name) return
setSaving((prev) => ({ ...prev, [`item-name-${outputItem.id}`]: true }))
try {
await fetchJson(`${API}/items/${outputItem.id}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: outputName.trim() }),
})
setData((prev) => prev ? {
...prev,
items: prev.items.map((item) => (
item.id === outputItem.id ? { ...item, name: outputName.trim() } : item
)),
} : prev)
setOutputNameByItem((prev) => ({ ...prev, [outputItem.id]: outputName.trim() }))
} catch (e: unknown) {
alert(e instanceof Error ? e.message : 'Rename failed')
} finally {
setSaving((prev) => ({ ...prev, [`item-name-${outputItem.id}`]: false }))
}
}
async function uploadItemImage(itemId: number, file: File | undefined) {
if (!file) return
setSaving((prev) => ({ ...prev, [`item-image-${itemId}`]: true }))
try {
const imageData = await fileToDataUrl(file)
const result = await fetchJson<{ imageUrl: string }>(`${API}/items/${itemId}/image`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ imageData }),
})
setData((prev) => prev ? {
...prev,
items: prev.items.map((item) => (
item.id === itemId ? { ...item, imageUrl: result.imageUrl } : item
)),
} : prev)
} catch (e: unknown) {
alert(e instanceof Error ? e.message : 'Upload failed')
} finally {
setSaving((prev) => ({ ...prev, [`item-image-${itemId}`]: false }))
}
}
async function deleteComponent(rId: number, iId: number) {
try {
await fetchJson(`${API}/crafting-recipes/${rId}/components/${iId}`, { method: 'DELETE' })
setData((prev) => prev ? {
...prev,
craftingRecipes: prev.craftingRecipes.map((r) =>
r.id === rId ? { ...r, components: r.components.filter((c) => c.itemId !== iId) } : r,
),
} : prev)
} catch (e: unknown) {
alert(e instanceof Error ? e.message : 'Delete failed')
}
}
async function addComponent() {
if (!addComponentIsValid || !recipe) return
try {
await fetchJson(`${API}/crafting-recipes/${recipe.id}/components`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ itemId: addItemId, quantity: addQty }),
})
setData((prev) => prev ? {
...prev,
craftingRecipes: prev.craftingRecipes.map((r) =>
r.id === recipe!.id
? { ...r, components: [...r.components.filter((c) => c.itemId !== addItemId), { itemId: addItemId, quantity: addQty }] }
: r,
),
} : prev)
setAddItemId(0)
setAddQty(1)
} catch (e: unknown) {
alert(e instanceof Error ? e.message : 'Add failed')
}
}
async function updateQty(rId: number, iId: number, quantity: number) {
try {
await fetchJson(`${API}/crafting-recipes/${rId}/components`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ itemId: iId, quantity }),
})
setData((prev) => prev ? {
...prev,
craftingRecipes: prev.craftingRecipes.map((r) =>
r.id === rId ? {
...r,
components: r.components.map((c) => c.itemId === iId ? { ...c, quantity } : c),
} : r,
),
} : prev)
} catch (e: unknown) {
alert(e instanceof Error ? e.message : 'Update failed')
}
}
return (
<div className="admin-panel">
<div className="admin-crafting-filters">
<label>Item Level
<select value={itemLevelFilter} onChange={(e) => setItemLevelFilter(e.target.value)}>
<option value="all">All levels</option>
{itemLevels.map((itemLevel) => (
<option key={itemLevel} value={itemLevel}>iLvl {itemLevel}</option>
))}
</select>
</label>
<label>Boss
<select value={bossFilterId} onChange={(e) => setBossFilterId(Number(e.target.value))}>
<option value={0}>All bosses</option>
{bossEncounters.map((boss) => (
<option key={boss.id} value={boss.id}>{boss.enemyName}</option>
))}
</select>
</label>
<label>Recipe
<select value={recipe?.id ?? 0} onChange={(e) => setRecipeId(Number(e.target.value))}>
{filteredRecipes.length === 0 && <option value={0}>No matching recipes</option>}
{filteredRecipes.map((r) => (
<option key={r.id} value={r.id}>
[{itemGlyph(r.itemId)}] {itemName(r.itemId)} - {bossName(r.sourceEncounterId)}
</option>
))}
</select>
</label>
</div>
{outputItem && (
<div className="admin-recipe-header">
<img className="admin-recipe-image" src={outputItem.imageUrl || '/equipment-placeholder.svg'} alt={`${outputItem.name} icon`} />
<div>
<label className="admin-inline-field">Name
<input
value={outputName}
onChange={(e) => {
if (!outputItem) return
setOutputNameByItem((prev) => ({ ...prev, [outputItem.id]: e.target.value }))
}}
/>
</label>
<small className="admin-item-meta">{outputItem.slot} · iLvl {outputItem.itemLevel} · {outputItem.rarity}</small>
</div>
<div className="admin-recipe-actions">
<button
className="primary-button"
disabled={saving[`item-name-${outputItem.id}`] || outputName.trim() === '' || outputName === outputItem.name}
onClick={saveOutputName}
type="button"
>
{saving[`item-name-${outputItem.id}`] ? 'Saving...' : 'Rename'}
</button>
<label className="boss-upload-button">
{saving[`item-image-${outputItem.id}`] ? 'Uploading...' : 'Upload Image'}
<input
accept="image/png,image/jpeg,image/webp,image/gif"
disabled={saving[`item-image-${outputItem.id}`]}
onChange={(event) => uploadItemImage(outputItem.id, event.target.files?.[0])}
type="file"
/>
</label>
</div>
</div>
)}
<h3 className="admin-loot-title">Required Components</h3>
{(!recipe || recipe.components.length === 0) && (
<p className="admin-empty">No component requirements.</p>
)}
<div className="admin-loot-list">
{recipe?.components.map((comp) => (
<div key={comp.itemId} className="admin-loot-row">
<span className={`admin-glyph rarity-${data.items.find(i => i.id === comp.itemId)?.rarity ?? 'common'}`}>
{itemGlyph(comp.itemId)}
</span>
<span className="admin-loot-name">{itemName(comp.itemId)}</span>
<span className="admin-loot-weight">Qty:
<input className="admin-qty-input" type="number" min="1" value={comp.quantity}
onChange={(e) => updateQty(recipe.id, comp.itemId, Number(e.target.value))} />
</span>
<button className="danger-button" onClick={() => deleteComponent(recipe.id, comp.itemId)} type="button">X</button>
</div>
))}
</div>
<details className="admin-add-section">
<summary>Add Component</summary>
<div className="admin-add-form">
<label>Component
<select value={addItemId} onChange={(e) => setAddItemId(Number(e.target.value))}>
<option value={0}>Select component...</option>
{bossComponentOptions.map((i) => (
<option key={i.id} value={i.id}>[{i.glyph}] {i.name} ({componentBossNames(i.id)})</option>
))}
</select>
</label>
<label>Quantity <input type="number" min="1" value={addQty} onChange={(e) => setAddQty(Number(e.target.value))} /></label>
<button className="primary-button" onClick={addComponent} disabled={!recipe || !addComponentIsValid} type="button">Add</button>
</div>
</details>
</div>
)
}
function fileToDataUrl(file: File) {
return new Promise<string>((resolve, reject) => {
const reader = new FileReader()
reader.addEventListener('load', () => {
if (typeof reader.result === 'string') resolve(reader.result)
else reject(new Error('Unable to read image.'))
})
reader.addEventListener('error', () => reject(reader.error ?? new Error('Unable to read image.')))
reader.readAsDataURL(file)
})
}
function groupBy<T>(items: T[], keyFn: (item: T) => string): Record<string, T[]> {
const groups: Record<string, T[]> = {}
for (const item of items) {
const key = keyFn(item)
if (!groups[key]) groups[key] = []
groups[key].push(item)
}
return groups
}
+193
View File
@@ -0,0 +1,193 @@
import { useState } from 'react'
import {
loginAccount,
registerAccount,
type AuthSession,
} from '../profile'
import {
createOfflineCharacter,
hasOfflineCharacter,
resumeOfflineCharacter,
selectOnlineMode,
} from '../gameRepository'
type Props = {
onAuthenticated: (session: AuthSession) => void
serverMessage?: string
}
export function AuthScreen({ onAuthenticated, serverMessage = '' }: Props) {
const [mode, setMode] = useState<'login' | 'register'>('login')
const [username, setUsername] = useState('')
const [password, setPassword] = useState('')
const [characterName, setCharacterName] = useState('')
const [offlineName, setOfflineName] = useState('')
const [busy, setBusy] = useState(false)
const [message, setMessage] = useState('')
const offlineCharacterExists = hasOfflineCharacter()
async function submit(event: React.FormEvent) {
event.preventDefault()
setBusy(true)
setMessage('')
try {
selectOnlineMode()
const session = mode === 'login'
? await loginAccount(username, password)
: await registerAccount(username, password, characterName)
onAuthenticated(session)
} catch (reason) {
setMessage(reason instanceof Error ? reason.message : 'Unable to authenticate.')
} finally {
setBusy(false)
}
}
function beginOffline() {
setMessage('')
try {
onAuthenticated(createOfflineCharacter(offlineName))
} catch (reason) {
setMessage(reason instanceof Error ? reason.message : 'Unable to create an offline character.')
}
}
function resumeOffline() {
const session = resumeOfflineCharacter()
if (session) onAuthenticated(session)
}
return (
<main className="auth-shell">
<section className="auth-panel">
<div className="auth-brand">
<p className="eyebrow">Healer RPG</p>
<h1>I want to Heal</h1>
<p>
Build your healer, master each dungeon, and compete for the most
efficient clears.
</p>
</div>
<div className="auth-card">
<div className="auth-tabs">
<button
className={mode === 'login' ? 'selected' : ''}
onClick={() => {
setMode('login')
setMessage('')
}}
type="button"
>
Sign In
</button>
<button
className={mode === 'register' ? 'selected' : ''}
onClick={() => {
setMode('register')
setMessage('')
}}
type="button"
>
Create Account
</button>
</div>
<form onSubmit={submit}>
<label>
Username
<input
autoComplete="username"
maxLength={20}
minLength={3}
onChange={(event) => setUsername(event.target.value)}
pattern="[A-Za-z0-9_]+"
required
value={username}
/>
</label>
{mode === 'register' && (
<label>
Character Name
<input
autoComplete="nickname"
maxLength={20}
minLength={2}
onChange={(event) => setCharacterName(event.target.value)}
required
value={characterName}
/>
</label>
)}
<label>
Password
<input
autoComplete={mode === 'login' ? 'current-password' : 'new-password'}
maxLength={128}
minLength={10}
onChange={(event) => setPassword(event.target.value)}
required
type="password"
value={password}
/>
</label>
<button className="primary-button" disabled={busy} type="submit">
{busy
? 'Working...'
: mode === 'login'
? 'Enter Chronicle'
: 'Begin Adventure'}
</button>
</form>
<p className={`auth-message ${message ? 'error' : ''}`}>
{message || serverMessage || (
mode === 'register'
? 'The first account keeps the current local character and save.'
: 'Sign in to continue your character.'
)}
</p>
<div className="offline-divider"><span>or</span></div>
<section className="offline-entry">
<div>
<p className="eyebrow">Local Save</p>
<h2>Play Offline</h2>
<p>
No account or connection required. Offline progress stays on
this device and is excluded from online leaderboards.
</p>
</div>
{offlineCharacterExists && (
<button
className="offline-resume-button"
onClick={resumeOffline}
type="button"
>
Continue Offline Character
</button>
)}
<label>
{offlineCharacterExists ? 'New Character Name' : 'Character Name'}
<input
maxLength={20}
minLength={2}
onChange={(event) => setOfflineName(event.target.value)}
placeholder="Mira"
value={offlineName}
/>
</label>
<button
className="text-button offline-new-button"
onClick={beginOffline}
type="button"
>
{offlineCharacterExists ? 'Replace Offline Character' : 'Begin Offline Adventure'}
</button>
</section>
</div>
</section>
</main>
)
}
File diff suppressed because it is too large Load Diff
+102
View File
@@ -0,0 +1,102 @@
import type { CSSProperties } from 'react'
import {
bindingLabel,
compactBindingLabel,
type ControllerIconStyle,
} from '../input'
const FACE_BUTTONS: Record<ControllerIconStyle, Partial<Record<number, { color: string; label: string }>>> = {
xbox: {
0: { color: '#107c10', label: 'A' },
1: { color: '#d13438', label: 'B' },
2: { color: '#0078d4', label: 'X' },
3: { color: '#ffb900', label: 'Y' },
},
playstation: {
0: { color: '#0070d1', label: '×' },
1: { color: '#df0024', label: '○' },
2: { color: '#f27ab8', label: '□' },
3: { color: '#00a35a', label: '△' },
},
nintendo: {
0: { color: '#e60012', label: 'B' },
1: { color: '#e60012', label: 'A' },
2: { color: '#e60012', label: 'Y' },
3: { color: '#e60012', label: 'X' },
},
}
function faceButtonFor(binding: string, iconStyle: ControllerIconStyle) {
if (!binding.startsWith('Button')) return null
return FACE_BUTTONS[iconStyle][Number(binding.slice(6))] ?? null
}
function FaceIcon({
color,
iconStyle,
label,
title,
}: {
color: string
iconStyle: ControllerIconStyle
label: string
title: string
}) {
return (
<span
aria-label={title}
className={`controller-face-icon controller-face-${iconStyle}`}
role="img"
style={{ '--button-color': color } as CSSProperties}
>
{label}
</span>
)
}
export function ControllerBindingLabel({
binding,
compact = false,
iconStyle,
}: {
binding: string
compact?: boolean
iconStyle: ControllerIconStyle
}) {
const faceButton = faceButtonFor(binding, iconStyle)
const title = bindingLabel(binding, iconStyle)
if (faceButton) {
return (
<FaceIcon
color={faceButton.color}
iconStyle={iconStyle}
label={faceButton.label}
title={title}
/>
)
}
return <>{compact ? compactBindingLabel(binding, iconStyle) : title}</>
}
export function ControllerStylePreview({ iconStyle }: { iconStyle: ControllerIconStyle }) {
return (
<span className="controller-style-preview" aria-hidden="true">
{[0, 1, 2, 3].map((button) => {
const faceButton = FACE_BUTTONS[iconStyle][button]
if (!faceButton) return null
return (
<FaceIcon
color={faceButton.color}
iconStyle={iconStyle}
key={button}
label={faceButton.label}
title=""
/>
)
})}
</span>
)
}
+235
View File
@@ -0,0 +1,235 @@
import { useEffect, useMemo, useRef, useState } from 'react'
import {
saveProfile,
type CharacterProfile,
type GameClass,
} from '../profile'
import { EquipmentScreen } from './EquipmentScreen'
import { TalentScreen } from './TalentScreen'
type Props = {
profile: CharacterProfile
onBack: () => void
onSaved: (profile: CharacterProfile) => void
}
export function CustomizeScreen({ profile, onBack, onSaved }: Props) {
const [activeTab, setActiveTab] = useState<'equipment' | 'talents' | 'class'>('class')
const [classId, setClassId] = useState(profile.character.classId)
const [slots, setSlots] = useState<Array<number | null>>(profile.abilitySlots)
const [selectedSlot, setSelectedSlot] = useState(0)
const [message, setMessage] = useState('')
const [saving, setSaving] = useState(false)
const scrollRef = useRef<number>(0)
const gameClass = profile.classes.find((candidate) => candidate.id === classId)!
const abilityMap = useMemo(
() => new Map(gameClass.spells.map((ability) => [ability.id, ability])),
[gameClass],
)
useEffect(() => {
window.scrollTo(0, scrollRef.current)
}, [profile])
function saveScroll() {
scrollRef.current = window.scrollY
}
function chooseClass(nextClass: GameClass) {
const starterAbilities = nextClass.spells
.filter((ability) => ability.unlockLevel <= profile.character.level)
.slice(0, 5)
.map((ability) => ability.id)
setClassId(nextClass.id)
setSlots([...starterAbilities, ...Array(6 - starterAbilities.length).fill(null)])
setSelectedSlot(0)
setMessage('')
}
function equipAbility(abilityId: number) {
if (slots.includes(abilityId)) {
setMessage('That ability is already equipped.')
return
}
setSlots((current) =>
current.map((spellId, index) => index === selectedSlot ? abilityId : spellId),
)
setMessage('')
}
function clearSlot() {
setSlots((current) =>
current.map((spellId, index) => index === selectedSlot ? null : spellId),
)
}
async function persistChanges() {
saveScroll()
setSaving(true)
setMessage('')
try {
const updated = await saveProfile(classId, slots)
onSaved(updated)
setMessage('Character saved.')
} catch (reason) {
setMessage(reason instanceof Error ? reason.message : 'Unable to save character.')
} finally {
setSaving(false)
}
}
return (
<section className="content-screen customize-screen">
<div className="screen-heading">
<div>
<p className="eyebrow">Character Workshop</p>
<h1>Customize Character</h1>
</div>
<button className="back-button" onClick={onBack} type="button">Back</button>
</div>
<div className="customize-tabs" role="tablist" aria-label="Customize character sections">
{([
{ key: 'equipment', label: 'Equipment' },
{ key: 'talents', label: 'Talents' },
{ key: 'class', label: 'Class' },
] as const).map((tab) => (
<button
aria-selected={activeTab === tab.key}
className={activeTab === tab.key ? 'active' : ''}
key={tab.key}
onClick={() => setActiveTab(tab.key)}
role="tab"
type="button"
>
{tab.label}
</button>
))}
</div>
{activeTab === 'equipment' && (
<EquipmentScreen
embedded
profile={profile}
onUpdated={onSaved}
/>
)}
{activeTab === 'talents' && (
<TalentScreen
embedded
profile={profile}
onUpdated={onSaved}
/>
)}
{activeTab === 'class' && (
<div className="customize-layout">
<aside className="class-picker">
<p className="eyebrow">Healing Class</p>
{profile.classes.map((candidate) => (
<button
className={candidate.id === classId ? 'active' : ''}
key={candidate.id}
onClick={() => chooseClass(candidate)}
style={{ '--class-color': candidate.themeColor } as React.CSSProperties}
type="button"
>
<span>{candidate.name[0]}</span>
<div>
<strong>{candidate.name}</strong>
<small>{candidate.resourceName}</small>
</div>
</button>
))}
</aside>
<div className="loadout-editor">
<div className="class-detail">
<div
className="class-portrait"
style={{ borderColor: gameClass.themeColor, color: gameClass.themeColor }}
>
{gameClass.name[0]}
</div>
<div>
<p className="eyebrow">Level {profile.character.level} Healer</p>
<h2>{gameClass.name}</h2>
<p>{gameClass.description}</p>
</div>
</div>
<div className="loadout-heading">
<div>
<p className="eyebrow">Active Loadout</p>
<h2>Ability Bar</h2>
</div>
<span>Select a slot, then choose an ability.</span>
</div>
<div className="ability-slots">
{slots.map((abilityId, index) => {
const ability = abilityId ? abilityMap.get(abilityId) : undefined
return (
<button
className={selectedSlot === index ? 'selected' : ''}
key={index}
onClick={() => setSelectedSlot(index)}
type="button"
>
<kbd>{index + 1}</kbd>
<span>{ability?.glyph ?? '-'}</span>
<strong>{ability?.name ?? 'Empty Slot'}</strong>
</button>
)
})}
</div>
<div className="ability-library-heading">
<div>
<p className="eyebrow">Class Abilities</p>
<h2>Ability Library</h2>
</div>
<button className="text-button" onClick={clearSlot} type="button">Clear Selected Slot</button>
</div>
<div className="ability-library">
{gameClass.spells.map((ability) => {
const locked = ability.unlockLevel > profile.character.level
const equipped = slots.includes(ability.id)
return (
<button
className={`${locked ? 'locked' : ''} ${equipped ? 'equipped' : ''}`}
disabled={locked}
key={ability.id}
onClick={() => equipAbility(ability.id)}
type="button"
>
<span>{locked ? 'L' : ability.glyph}</span>
<div>
<strong>{ability.name}</strong>
<small>{ability.description}</small>
</div>
<i>{locked ? `Level ${ability.unlockLevel}` : equipped ? 'Equipped' : `${ability.cost} ${gameClass.resourceName}`}</i>
</button>
)
})}
</div>
<div className="save-row">
<span>{message}</span>
<button
className="primary-button"
disabled={saving}
onClick={persistChanges}
type="button"
>
{saving ? 'Saving...' : 'Save Character'}
</button>
</div>
</div>
</div>
)}
</section>
)
}
+537
View File
@@ -0,0 +1,537 @@
import { useEffect, useMemo, useRef, useState } from 'react'
import {
breakdownItem,
craftItem,
equipItem,
loadProfile,
type CharacterProfile,
type EquipmentSlot,
type Item,
} from '../profile'
const SLOT_LABELS: Record<EquipmentSlot, string> = {
weapon: 'Weapon',
helmet: 'Helmet',
chest: 'Chest',
gloves: 'Gloves',
boots: 'Boots',
pants: 'Pants',
ring: 'Ring',
necklace: 'Necklace',
trinket: 'Trinket',
component: 'Component',
}
type Props = {
profile: CharacterProfile
onBack?: () => void
onUpdated: (profile: CharacterProfile) => void
embedded?: boolean
}
export function EquipmentScreen({ profile, onBack, onUpdated, embedded = false }: Props) {
const totalItemCount = profile.inventory.reduce(
(total, item) => total + item.quantity,
0,
)
const firstItem = profile.inventory.find((item) => !item.equipped)
?? profile.inventory[0]
const [selectedItemId, setSelectedItemId] = useState<number | null>(
firstItem?.id ?? null,
)
const [selectedSlot, setSelectedSlot] = useState<EquipmentSlot | null>(null)
const [equipping, setEquipping] = useState(false)
const [breakingDown, setBreakingDown] = useState(false)
const [crafting, setCrafting] = useState(false)
const [showSetBonuses, setShowSetBonuses] = useState(false)
const [equipmentTab, setEquipmentTab] = useState<'equipment' | 'crafting'>('equipment')
const [message, setMessage] = useState('')
const scrollRef = useRef<number>(0)
const selectedItem = profile.inventory.find((item) => item.id === selectedItemId)
const firstRecipe = profile.craftingRecipes.find((recipe) => recipe.canCraft)
?? profile.craftingRecipes[0]
const [selectedRecipeId, setSelectedRecipeId] = useState<number | null>(
firstRecipe?.id ?? null,
)
const selectedRecipe = profile.craftingRecipes.find((recipe) => recipe.id === selectedRecipeId)
const equippedBySlot = useMemo(
() => new Map(
profile.inventory
.filter((item) => item.equipped)
.map((item) => [item.slot, item]),
),
[profile.inventory],
)
const comparisonItem = selectedItem
? equippedBySlot.get(selectedItem.slot)
: undefined
const visibleInventory = useMemo(
() => selectedSlot
? profile.inventory.filter((item) => item.slot === selectedSlot)
: profile.inventory,
[profile.inventory, selectedSlot],
)
const visibleItemCount = visibleInventory.reduce(
(total, item) => total + item.quantity,
0,
)
const [slotFilter, setSlotFilter] = useState<EquipmentSlot | 'all'>('all')
const [levelFilter, setLevelFilter] = useState<number | null>(null)
const availableLevels = useMemo(
() => [...new Set(profile.craftingRecipes.map((r) => r.item.itemLevel))].sort((a, b) => b - a),
[profile.craftingRecipes],
)
const filteredRecipes = useMemo(
() => {
let result = [...profile.craftingRecipes]
if (slotFilter !== 'all') result = result.filter((r) => r.item.slot === slotFilter)
if (levelFilter !== null) result = result.filter((r) => r.item.itemLevel === levelFilter)
result.sort((a, b) => b.item.itemLevel - a.item.itemLevel)
return result
},
[profile.craftingRecipes, slotFilter, levelFilter],
)
useEffect(() => {
window.scrollTo(0, scrollRef.current)
}, [profile])
useEffect(() => {
if (equipmentTab === 'crafting') {
loadProfile().then((fresh) => onUpdated(fresh)).catch(() => {})
}
}, [equipmentTab])
function saveScroll() {
scrollRef.current = window.scrollY
}
async function equipSelected() {
if (!selectedItem || selectedItem.equipped) return
saveScroll()
setEquipping(true)
setMessage('')
try {
const updated = await equipItem(selectedItem.id)
onUpdated(updated)
setMessage(`${selectedItem.name} equipped.`)
} catch (reason) {
setMessage(reason instanceof Error ? reason.message : 'Unable to equip item.')
} finally {
setEquipping(false)
}
}
async function breakdownSelected() {
if (!selectedItem) return
saveScroll()
setBreakingDown(true)
setMessage('')
try {
const updated = await breakdownItem(selectedItem.id)
onUpdated(updated)
setMessage(
selectedItem.quantity > 1
? `One duplicate ${selectedItem.name} broken down into components.`
: `${selectedItem.name} broken down into components.`,
)
} catch (reason) {
setMessage(reason instanceof Error ? reason.message : 'Unable to break down item.')
} finally {
setBreakingDown(false)
}
}
async function craftSelected() {
if (!selectedRecipe) return
saveScroll()
setCrafting(true)
setMessage('')
try {
const updated = await craftItem(selectedRecipe.id)
onUpdated(updated)
setSelectedItemId(selectedRecipe.item.id)
setMessage(`${selectedRecipe.item.name} crafted.`)
} catch (reason) {
setMessage(reason instanceof Error ? reason.message : 'Unable to craft item.')
} finally {
setCrafting(false)
}
}
const content = (
<>
{!embedded && (
<div className="screen-heading">
<div>
<p className="eyebrow">Character Loadout</p>
<h1>Equipment</h1>
</div>
<button className="back-button" onClick={onBack} type="button">Back</button>
</div>
)}
<div className="gear-summary">
<div className="gear-character">
<span style={{ borderColor: profile.character.themeColor, color: profile.character.themeColor }}>
{profile.character.className[0]}
</span>
<div>
<p className="eyebrow">{profile.character.className}</p>
<h2>{profile.character.name}</h2>
</div>
</div>
<GearStat value={profile.gearStats.averageItemLevel.toFixed(1)} label="Average Item Level" />
<GearStat value={`+${profile.gearStats.healingPower}`} label="Healing Power" />
<GearStat value={`+${profile.gearStats.maxResourceBonus}`} label={`Max ${profile.character.resourceName}`} />
</div>
<nav className="equipment-tabs">
<button
className={`equipment-tab ${equipmentTab === 'equipment' ? 'active' : ''}`}
onClick={() => setEquipmentTab('equipment')}
type="button"
>
Equipment
</button>
<button
className={`equipment-tab ${equipmentTab === 'crafting' ? 'active' : ''}`}
onClick={() => setEquipmentTab('crafting')}
type="button"
>
Crafting
</button>
</nav>
{equipmentTab === 'equipment' ? (
<>
<section className="item-comparison">
{selectedItem ? (
selectedItem.slot === 'component' ? (
<>
<ItemDetail title="Crafting Component" item={selectedItem} />
<div className="equip-action">
<p className="component-note">Used in crafting.</p>
</div>
</>
) : (
<>
<ItemDetail title={selectedItem.equipped ? 'Selected Equipment' : 'Inventory Item'} item={selectedItem} />
<div className="comparison-arrow">vs</div>
{comparisonItem && comparisonItem.id !== selectedItem.id ? (
<ItemDetail title="Currently Equipped" item={comparisonItem} />
) : (
<div className="item-detail empty-comparison">
<p className="eyebrow">Comparison</p>
<h2>{selectedItem.equipped ? 'Already Equipped' : 'Empty Slot'}</h2>
</div>
)}
<div className="equip-action">
<ComparisonDelta selected={selectedItem} equipped={comparisonItem} />
<button
className="primary-button"
disabled={selectedItem.equipped || equipping || breakingDown}
onClick={equipSelected}
type="button"
>
{selectedItem.equipped ? 'Equipped' : equipping ? 'Equipping...' : 'Equip Item'}
</button>
{(!selectedItem.equipped || selectedItem.quantity > 1) && (
<button
className="breakdown-button"
disabled={equipping || breakingDown}
onClick={breakdownSelected}
type="button"
>
{breakingDown
? 'Breaking Down...'
: selectedItem.quantity > 1
? 'Break Down Duplicate'
: 'Break Down'}
</button>
)}
</div>
</>
)
) : (
<p>Select an item to inspect it.</p>
)}
</section>
<div className="equipment-layout">
<section className="equipped-panel">
<EquipmentHeading eyebrow="Currently Worn" title="Equipment Slots" />
<div className="equipment-slots">
{profile.equipmentSlots.map((slot) => {
const item = equippedBySlot.get(slot)
return (
<button
className={`${item ? `rarity-${item.rarity}` : 'empty'} ${selectedSlot === slot ? 'selected-slot' : ''}`}
key={slot}
onClick={() => {
setSelectedSlot(slot)
const firstSlotItem = profile.inventory.find(
(candidate) => candidate.slot === slot,
)
setSelectedItemId(item?.id ?? firstSlotItem?.id ?? null)
}}
type="button"
>
<span>{item?.glyph ?? '-'}</span>
<div>
<strong>{item?.name ?? SLOT_LABELS[slot]}</strong>
<small>{SLOT_LABELS[slot]}{item ? ` - iLvl ${item.itemLevel}` : ' - Empty'}</small>
</div>
<div className="item-status">
{item && <i>Equipped</i>}
</div>
</button>
)
})}
</div>
</section>
<section className="inventory-panel">
<EquipmentHeading
eyebrow="Owned Items"
title={selectedSlot ? `${SLOT_LABELS[selectedSlot]} Inventory` : 'Inventory'}
detail={selectedSlot
? `${visibleItemCount} items - ${visibleInventory.length} types`
: `${totalItemCount} items - ${profile.inventory.length} types`}
/>
{selectedSlot && (
<button
className="inventory-filter-clear"
onClick={() => setSelectedSlot(null)}
type="button"
>
Show All Items
</button>
)}
<div className="inventory-list">
{visibleInventory.map((item) => (
<button
className={`${selectedItemId === item.id ? 'selected' : ''} rarity-${item.rarity}`}
key={item.id}
onClick={() => setSelectedItemId(item.id)}
type="button"
>
<span>{item.glyph}</span>
<div>
<strong>{item.name}</strong>
<small>{SLOT_LABELS[item.slot]} - Item Level {item.itemLevel}</small>
</div>
<div className="item-status">
{item.equipped && <i>Equipped</i>}
{item.quantity > 1 && <i className="item-quantity">x{item.quantity}</i>}
</div>
</button>
))}
{visibleInventory.length === 0 && (
<p className="inventory-empty">
No {SLOT_LABELS[selectedSlot ?? 'component'].toLowerCase()} items owned.
</p>
)}
</div>
</section>
</div>
</>
) : (
<section className="crafting-panel">
<EquipmentHeading
eyebrow="Crafting"
title="Recipes"
detail={`${filteredRecipes.filter((recipe) => recipe.canCraft).length} ready`}
/>
<div className="crafting-filter-bar">
<select
className="filter-select"
value={slotFilter}
onChange={(e) => setSlotFilter(e.target.value as EquipmentSlot | 'all')}
>
<option value="all">All Slots</option>
{(Object.entries(SLOT_LABELS) as [EquipmentSlot, string][]).map(([slot, label]) => (
<option key={slot} value={slot}>{label}</option>
))}
</select>
<select
className="filter-select"
value={levelFilter ?? ''}
onChange={(e) => setLevelFilter(e.target.value === '' ? null : Number(e.target.value))}
>
<option value="">All Levels</option>
{availableLevels.map((level) => (
<option key={level} value={level}>Item Level {level}</option>
))}
</select>
</div>
{filteredRecipes.length === 0 && (
<p className="inventory-empty">No crafting recipes match filters.</p>
)}
{filteredRecipes.length > 0 && (
<div className="crafting-layout">
<div className="crafting-list">
{filteredRecipes.map((recipe) => (
<button
className={`${selectedRecipeId === recipe.id ? 'selected' : ''} rarity-${recipe.item.rarity}`}
key={recipe.id}
onClick={() => setSelectedRecipeId(recipe.id)}
type="button"
>
<span>{recipe.item.glyph}</span>
<div>
<strong>{recipe.item.name}</strong>
<small>
{SLOT_LABELS[recipe.item.slot]} - Item Level {recipe.item.itemLevel}
{recipe.item.setName ? ` - ${recipe.item.setName}` : ''}
</small>
</div>
<i>{recipe.canCraft ? 'Ready' : 'Needs materials'}</i>
</button>
))}
</div>
{selectedRecipe && (
<div className={`crafting-detail rarity-${selectedRecipe.item.rarity}`}>
<ItemDetail title="Craft Output" item={{ ...selectedRecipe.item, quantity: 1, equipped: false }} />
<div className="crafting-components">
{selectedRecipe.components.map((component) => (
<div
className={component.owned >= component.quantity ? 'ready' : 'missing'}
key={component.item.id}
>
<span>{component.item.glyph}</span>
<strong>{component.item.name}</strong>
<i>{component.owned}/{component.quantity}</i>
</div>
))}
</div>
<button
className="primary-button"
disabled={!selectedRecipe.canCraft || crafting}
onClick={craftSelected}
type="button"
>
{crafting ? 'Crafting...' : 'Craft Item'}
</button>
</div>
)}
</div>
)}
</section>
)}
{profile.setBonuses.length > 0 && (
<section className="set-bonus-panel">
<div className="equipment-heading toggle-heading">
<div>
<p className="eyebrow">Set Bonuses</p>
<h2>Raid Sets</h2>
</div>
<button
className="text-button"
onClick={() => setShowSetBonuses((current) => !current)}
type="button"
>
{showSetBonuses ? 'Hide Raid Sets' : 'Show Raid Sets'}
</button>
</div>
{showSetBonuses && (
<div className="set-bonus-list">
{profile.setBonuses.map((bonus) => (
<div className={bonus.active ? 'active' : ''} key={`${bonus.setId}-${bonus.requiredPieces}`}>
<strong>{bonus.requiredPieces} pieces</strong>
<span>{bonus.description}</span>
<i>{bonus.equippedPieces}/{bonus.requiredPieces}</i>
</div>
))}
</div>
)}
</section>
)}
<footer className="equipment-footer">
{message || 'Equipment changes are saved immediately.'}
</footer>
</>
)
if (embedded) {
return <div className="equipment-screen embedded-screen">{content}</div>
}
return (
<section className="content-screen equipment-screen">
{content}
</section>
)
}
function GearStat({ value, label }: { value: string; label: string }) {
return (
<div className="gear-stat">
<strong>{value}</strong>
<span>{label}</span>
</div>
)
}
function EquipmentHeading({
eyebrow,
title,
detail,
}: {
eyebrow: string
title: string
detail?: string
}) {
return (
<div className="equipment-heading">
<div><p className="eyebrow">{eyebrow}</p><h2>{title}</h2></div>
{detail && <span>{detail}</span>}
</div>
)
}
function ItemDetail({ title, item }: { title: string; item: Item }) {
return (
<article className={`item-detail rarity-${item.rarity}`}>
<p className="eyebrow">{title}</p>
<div className="item-title">
<span>{item.glyph}</span>
<div>
<h2>{item.name}</h2>
<small>{SLOT_LABELS[item.slot]} - Item Level {item.itemLevel}</small>
</div>
</div>
<p>{item.description}</p>
{item.quantity > 1 && <p className="owned-quantity">Owned: {item.quantity}</p>}
{item.slot !== 'component' && (
<ul>
<li>+{item.healingPower} Healing Power</li>
<li>+{item.maxResourceBonus} Max Resource</li>
</ul>
)}
</article>
)
}
function ComparisonDelta({
selected,
equipped,
}: {
selected: Item
equipped?: Item
}) {
const healingDelta = selected.healingPower - (equipped?.healingPower ?? 0)
const resourceDelta = selected.maxResourceBonus - (equipped?.maxResourceBonus ?? 0)
return (
<div className="comparison-delta">
<span className={healingDelta >= 0 ? 'positive' : 'negative'}>
{healingDelta >= 0 ? '+' : ''}{healingDelta} Healing
</span>
<span className={resourceDelta >= 0 ? 'positive' : 'negative'}>
{resourceDelta >= 0 ? '+' : ''}{resourceDelta} Resource
</span>
</div>
)
}
File diff suppressed because it is too large Load Diff
+245
View File
@@ -0,0 +1,245 @@
import { useEffect, useState } from 'react'
import {
ACTION_LABELS,
INPUT_ACTIONS,
useInput,
type InputDevice,
} from '../input'
import {
ControllerBindingLabel,
ControllerStylePreview,
} from './ControllerIcons'
const CONTROLLER_STYLE_LABELS = {
xbox: 'Xbox',
playstation: 'PlayStation',
nintendo: 'Nintendo',
} as const
import { useDualScreen } from '../dualScreen'
import {
getNativeDisplays,
hasNativeDualScreenBridge,
type AndroidDisplay,
} from '../nativeDualScreen'
export function SettingsScreen({ onBack }: { onBack: () => void }) {
const [device, setDevice] = useState<InputDevice>('controller')
const [displayMessage, setDisplayMessage] = useState('')
const [androidDisplays, setAndroidDisplays] = useState<AndroidDisplay[]>([])
const {
bindings,
capture,
controllerIconStyle,
directPartyTargeting,
beginCapture,
cancelCapture,
resetBindings,
setControllerIconStyle,
setDirectPartyTargeting,
} = useInput()
const {
enabled: dualScreenEnabled,
connected: topDisplayConnected,
setEnabled: setDualScreenEnabled,
openTopDisplay,
} = useDualScreen()
const nativeDualScreen = hasNativeDualScreenBridge()
const directTargetActions = new Set([
'targetParty1',
'targetParty2',
'targetParty3',
'targetParty4',
'targetParty5',
'toggleTargetGroup',
])
const visibleActions = INPUT_ACTIONS.filter((action) => (
directPartyTargeting
? action !== 'previousTarget' && action !== 'nextTarget'
: !directTargetActions.has(action)
))
async function refreshNativeDisplays() {
if (!nativeDualScreen) return
try {
const result = await getNativeDisplays()
setAndroidDisplays(result.displays)
} catch {
setAndroidDisplays([])
}
}
useEffect(() => {
if (!nativeDualScreen) return
getNativeDisplays()
.then((result) => setAndroidDisplays(result.displays))
.catch(() => setAndroidDisplays([]))
}, [nativeDualScreen])
async function launchTopDisplay() {
const opened = await openTopDisplay()
setDisplayMessage(opened
? nativeDualScreen
? 'Android placed the game on the larger display and controls on the smaller display.'
: 'Companion display opened. Move it to the Thor screen you want and select Fullscreen.'
: 'No usable second display was found. Check the Thor display mode and try again.')
await refreshNativeDisplays()
}
return (
<section className="content-screen settings-screen">
<div className="screen-heading">
<div>
<p className="eyebrow">Game Options</p>
<h1>Settings</h1>
</div>
<button className="back-button" onClick={onBack} type="button">Back</button>
</div>
<section className="dual-screen-settings">
<div>
<p className="eyebrow">Display</p>
<h2>AYN Thor Dual-Screen Mode</h2>
<p>
The upper display shows enemy and party health. The lower display
keeps targeting, resources, skills, and cooldowns.
</p>
</div>
<div className="dual-screen-actions">
<button
className={dualScreenEnabled ? 'selected' : ''}
onClick={() => {
setDualScreenEnabled(!dualScreenEnabled)
setDisplayMessage('')
}}
type="button"
>
{dualScreenEnabled ? 'Dual-Screen Enabled' : 'Enable Dual-Screen'}
</button>
<button onClick={launchTopDisplay} type="button">
{topDisplayConnected ? 'Companion Connected' : 'Open Companion Display'}
</button>
</div>
<small>
{displayMessage || (
topDisplayConnected
? 'The companion display is connected and receiving live combat data.'
: 'Open the companion display before starting combat.'
)}
</small>
{nativeDualScreen && androidDisplays.length > 0 && (
<div className="android-display-list">
{androidDisplays.map((display) => (
<span key={display.id}>
<strong>{display.isCurrent ? 'Current' : 'Secondary'} #{display.id}</strong>
{display.width}×{display.height} at {Math.round(display.refreshRate)} Hz
{display.isPresentation ? ' - Presentation' : ''}
</span>
))}
</div>
)}
</section>
<div className="settings-heading">
<div>
<p className="eyebrow">Input</p>
<h2>Keybindings</h2>
</div>
<p>Select an action, then press the new key or controller control.</p>
</div>
<section className="controller-preferences">
<div>
<p className="eyebrow">Targeting</p>
<h3>Direct Party Keybinds</h3>
<p>
Assign party slots directly. In raids, use the group-switch binding
to alternate between members 1-5 and 6-10.
</p>
</div>
<button
aria-pressed={directPartyTargeting}
className={directPartyTargeting ? 'selected' : ''}
onClick={() => setDirectPartyTargeting(!directPartyTargeting)}
type="button"
>
{directPartyTargeting ? 'Direct Targeting On' : 'Direct Targeting Off'}
</button>
<div className="controller-icon-options">
<span>Controller Icons</span>
{(['xbox', 'playstation', 'nintendo'] as const).map((style) => (
<button
aria-pressed={controllerIconStyle === style}
className={controllerIconStyle === style ? 'selected' : ''}
key={style}
onClick={() => setControllerIconStyle(style)}
type="button"
>
<ControllerStylePreview iconStyle={style} />
<span className="controller-style-name">{CONTROLLER_STYLE_LABELS[style]}</span>
</button>
))}
</div>
</section>
<div className="binding-tabs">
<button
className={device === 'controller' ? 'selected' : ''}
onClick={() => setDevice('controller')}
type="button"
>
Controller
</button>
<button
className={device === 'pc' ? 'selected' : ''}
onClick={() => setDevice('pc')}
type="button"
>
PC
</button>
</div>
<div className="binding-list">
{visibleActions.map((action) => (
<button
className={capture?.device === device && capture.action === action ? 'listening' : ''}
key={action}
onClick={() => beginCapture(device, action)}
type="button"
>
<span>{ACTION_LABELS[action]}</span>
<kbd>
{capture?.device === device && capture.action === action
? 'Press a control...'
: (
<ControllerBindingLabel
binding={bindings[device][action]}
iconStyle={controllerIconStyle}
/>
)}
</kbd>
</button>
))}
</div>
<footer className="settings-footer">
<span>Bindings are saved automatically on this device.</span>
<button className="text-button" onClick={() => resetBindings(device)} type="button">
Reset {device === 'pc' ? 'PC' : 'Controller'} Defaults
</button>
</footer>
{capture && (
<div className="binding-capture" role="dialog" aria-modal="true">
<div>
<p className="eyebrow">Remapping</p>
<h2>{ACTION_LABELS[capture.action]}</h2>
<p>
Press any {capture.device === 'pc' ? 'keyboard key' : 'controller button or move a stick'}.
</p>
<button onClick={cancelCapture} type="button">Cancel</button>
</div>
</div>
)}
</section>
)
}
+202
View File
@@ -0,0 +1,202 @@
import { useEffect, useRef, useState } from 'react'
import {
allocateTalent,
resetTalents,
type CharacterProfile,
type Talent,
} from '../profile'
type Props = {
profile: CharacterProfile
onBack?: () => void
onUpdated: (profile: CharacterProfile) => void
embedded?: boolean
}
export function TalentScreen({ profile, onBack, onUpdated, embedded = false }: Props) {
const [busyTalentId, setBusyTalentId] = useState<number | null>(null)
const [resetting, setResetting] = useState(false)
const [message, setMessage] = useState('')
const scrollRef = useRef<number>(0)
const gameClass = profile.classes.find(
(candidate) => candidate.id === profile.character.classId,
)!
const classPointsSpent = gameClass.talents.reduce(
(total, talent) => total + talent.rank,
0,
)
const tiers = Array.from(
new Set(gameClass.talents.map((talent) => talent.tier)),
).sort((a, b) => a - b)
useEffect(() => {
window.scrollTo(0, scrollRef.current)
}, [profile])
function saveScroll() {
scrollRef.current = window.scrollY
}
function lowerTierPoints(talent: Talent) {
return gameClass.talents
.filter((candidate) => candidate.tier < talent.tier)
.reduce((total, candidate) => total + candidate.rank, 0)
}
function lockReason(talent: Talent) {
if (talent.rank >= talent.maxRank) return 'Maximum rank'
const requiredTierPoints = (talent.tier - 1) * 5
if (lowerTierPoints(talent) < requiredTierPoints) {
return `Requires ${requiredTierPoints} earlier-tier points`
}
if (talent.prerequisiteTalentId) {
const prerequisite = gameClass.talents.find(
(candidate) => candidate.id === talent.prerequisiteTalentId,
)
if ((prerequisite?.rank ?? 0) < talent.prerequisiteRank) {
return `Requires ${talent.prerequisiteName} rank ${talent.prerequisiteRank}`
}
}
if (profile.character.talentPoints <= 0) return 'No points available'
return ''
}
async function purchaseRank(talent: Talent) {
saveScroll()
setBusyTalentId(talent.id)
setMessage('')
try {
const updated = await allocateTalent(talent.id)
onUpdated(updated)
setMessage(`${talent.name} increased to rank ${talent.rank + 1}.`)
} catch (reason) {
setMessage(reason instanceof Error ? reason.message : 'Unable to allocate talent.')
} finally {
setBusyTalentId(null)
}
}
async function refundTree() {
saveScroll()
setResetting(true)
setMessage('')
try {
const updated = await resetTalents()
onUpdated(updated)
setMessage('All points in this talent tree were refunded.')
} catch (reason) {
setMessage(reason instanceof Error ? reason.message : 'Unable to reset talents.')
} finally {
setResetting(false)
}
}
const content = (
<>
{!embedded && (
<div className="screen-heading">
<div>
<p className="eyebrow">Character Growth</p>
<h1>Talents</h1>
</div>
<button className="back-button" onClick={onBack} type="button">Back</button>
</div>
)}
<div className="talent-toolbar">
<div className="talent-class-summary">
<span style={{ borderColor: gameClass.themeColor, color: gameClass.themeColor }}>
{gameClass.name[0]}
</span>
<div>
<p className="eyebrow">{gameClass.name} Tree</p>
<h2>Shape Your Healing Style</h2>
</div>
</div>
<div className="talent-points">
<strong>{profile.character.talentPoints}</strong>
<span>Available</span>
<small>{classPointsSpent} spent in this tree</small>
</div>
</div>
<div className="talent-tree">
{tiers.map((tier) => {
const requiredPoints = (tier - 1) * 5
return (
<section className="talent-tier" key={tier}>
<div className="tier-label">
<span>Tier {tier}</span>
<small>
{tier === 1 ? 'Open' : `${requiredPoints} earlier-tier points`}
</small>
</div>
<div className="tier-talents">
{gameClass.talents
.filter((talent) => talent.tier === tier)
.sort((a, b) => a.branch - b.branch)
.map((talent) => {
const reason = lockReason(talent)
const isBusy = busyTalentId === talent.id
return (
<article
className={`talent-node ${reason ? 'locked' : 'available'} ${talent.rank > 0 ? 'invested' : ''}`}
key={talent.id}
style={{ gridColumn: talent.branch }}
>
<div className="talent-node-header">
<span>{talent.glyph}</span>
<div>
<strong>{talent.name}</strong>
<small>Rank {talent.rank}/{talent.maxRank}</small>
</div>
</div>
<p>{talent.description}</p>
<div className="rank-pips">
{Array.from({ length: talent.maxRank }, (_, index) => (
<i className={index < talent.rank ? 'filled' : ''} key={index} />
))}
</div>
<button
disabled={Boolean(reason) || isBusy}
onClick={() => purchaseRank(talent)}
type="button"
>
{isBusy ? 'Saving...' : reason || 'Add Rank'}
</button>
</article>
)
})}
</div>
</section>
)
})}
</div>
<footer className="talent-footer">
<span>{message || 'Talent changes are saved immediately.'}</span>
<button
className="text-button"
disabled={classPointsSpent === 0 || resetting}
onClick={refundTree}
type="button"
>
{resetting ? 'Refunding...' : 'Reset Tree'}
</button>
</footer>
</>
)
if (embedded) {
return <div className="talent-screen embedded-screen">{content}</div>
}
return (
<section className="content-screen talent-screen">
{content}
</section>
)
}