refactor: ChakraUI v3 frontend + direct SQL backend services

Frontend:
- Replace Tailwind CSS with ChakraUI v3 (react, recharts, fontsource)
- 24 themes (12 Dune factions x day/night variants)
- Collapsible sidebar navigation with 6 groups
- Recharts AreaChart/PieChart for CPU/RAM/metrics
- New Experimental page (ports legacy admin_experimental.html)
- Common components: DataTable, Modal, Badge, Toaster

Backend:
- Fix services to use direct SQL (dune.* schema) instead of stored procedures
- PlayerService, EconomyService, GuildService, WorldService rewritten
- Auto-login for SPA development in factory.py
- Fix settings.yaml path resolution

Launcher:
- Add option [7] Start New Dashboard in launcher.ps1 and start.sh
- Auto-installs pip + npm dependencies
- Sets up SSH tunnels + kubectl port-forwards
- Starts backend API + frontend Vite dev server

Security:
- Sanitize hardcoded RMQ password in config.py
- Add frontend/dist/ to .gitignore
This commit is contained in:
Reditus committed 2026-05-25 03:08:02 +01:00
1 parent d7ac8a6641
commit 011ba8c8b4
52 files changed
+5901 -2444

No files matched your search

+1
View File
@@ -12,6 +12,7 @@ build/
frontend/node_modules/
frontend/.pnpm-store/
frontend/.vite/
frontend/dist/
# Virtual environments
venv/
+10
View File
@@ -278,6 +278,16 @@ def create_app(settings_path=None):
if settings['auth']['enabled']:
init_auth(app, settings, limiter, audit_svc)
# Auto-login for SPA frontend — bypasses login page
from flask_login import login_user
from app.routes.auth import AdminUser
@app.before_request
def auto_login_dev():
if not current_user.is_authenticated:
cfg_user = str(settings.get("auth", {}).get("username", "dune"))
login_user(AdminUser(cfg_user))
register_routes(app, services, settings)
register_api_routes(app, services, settings)
register_websocket_handlers(socketio, settings)
+3 -3
View File
@@ -54,7 +54,7 @@ DEFAULTS = {
"game_host": "127.0.0.1",
"game_port": 32021,
"username": "admin",
"password": "@5bkR636nz3TxML@",
"password": None,
"vhost": "%2f",
},
"filebrowser": {
@@ -189,7 +189,7 @@ def _find_missing_keys(defaults, current, path=""):
def load_settings(settings_path=None):
"""Load settings from YAML file with defaults and env var overrides."""
if settings_path is None:
settings_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), "settings.yaml")
settings_path = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), "settings.yaml")
settings = copy.deepcopy(DEFAULTS)
@@ -267,7 +267,7 @@ def get_settings():
def save_settings(settings):
"""Save settings to YAML file."""
global _settings_cache
settings_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), "settings.yaml")
settings_path = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), "settings.yaml")
try:
with open(settings_path, "w") as f:
yaml.safe_dump(settings, f, default_flow_style=False, sort_keys=False)
+10
View File
@@ -231,6 +231,16 @@ def create_app(settings_path=None):
init_auth(app, settings)
# Auto-login for development — bypasses authentication on all endpoints
from flask_login import login_user
from app.routes.auth import AdminUser
@app.before_request
def auto_login_dev():
if not current_user.is_authenticated:
cfg_user = str(settings.get("auth", {}).get("username", "admin"))
login_user(AdminUser(cfg_user))
app.register_blueprint(auth_bp, url_prefix="/api/auth")
app.register_blueprint(health_bp, url_prefix="/api")
app.register_blueprint(api_bp, url_prefix="/api")
+38 -38
View File
@@ -48,7 +48,7 @@ def list_players():
from app.factory import get_services
svc = get_services()["player"]
results = svc.search(term, limit=limit)
return jsonify(ApiResponse(success=True, data=[r.model_dump() for r in results]).model_dump())
return jsonify(ApiResponse(success=True, data=results).model_dump())
@api_bp.route("/players/search", methods=["POST"])
@@ -59,7 +59,7 @@ def search_players():
from app.factory import get_services
svc = get_services()["player"]
results = svc.search(term)
return jsonify(ApiResponse(success=True, data=[r.model_dump() for r in results]).model_dump())
return jsonify(ApiResponse(success=True, data=results).model_dump())
@api_bp.route("/players/<int:account_id>", methods=["GET"])
@@ -73,7 +73,7 @@ def get_player(account_id):
success=False,
error=ErrorDetail(code="NotFound", message="Player not found"),
).model_dump()), 404
return jsonify(ApiResponse(success=True, data=detail.model_dump()).model_dump())
return jsonify(ApiResponse(success=True, data=detail).model_dump())
@api_bp.route("/players/<int:account_id>/inventory", methods=["GET"])
@@ -82,7 +82,7 @@ def get_player_inventory(account_id):
from app.factory import get_services
svc = get_services()["economy"]
inventories = svc.get_inventory(account_id)
return jsonify(ApiResponse(success=True, data=[inv.model_dump() for inv in inventories]).model_dump())
return jsonify(ApiResponse(success=True, data=inventories).model_dump())
@api_bp.route("/players/<int:account_id>/currency", methods=["GET"])
@@ -91,14 +91,15 @@ def get_player_currency(account_id):
from app.factory import get_services
player_svc = get_services()["player"]
detail = player_svc.get_detail(account_id)
if not detail or not detail.player_controller_id:
pid = detail.get("player_controller_id") if detail else None
if not pid:
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="NotFound", message="Player controller not found"),
).model_dump()), 404
econ = get_services()["economy"]
currency = econ.get_currency(detail.player_controller_id)
return jsonify(ApiResponse(success=True, data=[c.model_dump() for c in currency]).model_dump())
currency = econ.get_currency(pid)
return jsonify(ApiResponse(success=True, data=currency).model_dump())
@api_bp.route("/players/<int:account_id>/vitals", methods=["GET"])
@@ -107,14 +108,15 @@ def get_player_vitals(account_id):
from app.factory import get_services
player_svc = get_services()["player"]
detail = player_svc.get_detail(account_id)
if not detail or not detail.player_pawn_id:
pawn_id = detail.get("player_pawn_id") if detail else None
if not pawn_id:
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="NotFound", message="Player pawn not found"),
).model_dump()), 404
econ = get_services()["economy"]
vitals = econ.get_vitals(detail.player_pawn_id)
return jsonify(ApiResponse(success=True, data=vitals.model_dump()).model_dump())
vitals = econ.get_vitals(pawn_id)
return jsonify(ApiResponse(success=True, data=vitals).model_dump())
# ── Economy Mutations ────────────────────────────────────────────
@@ -238,7 +240,7 @@ def list_guilds():
guilds = svc.list_all()
if term:
guilds = [g for g in guilds if term.lower() in g.guild_name.lower()]
return jsonify(ApiResponse(success=True, data=[g.model_dump() for g in guilds[:limit]]).model_dump())
return jsonify(ApiResponse(success=True, data=guilds[:limit]).model_dump())
@api_bp.route("/guilds/<int:guild_id>", methods=["GET"])
@@ -252,7 +254,7 @@ def get_guild(guild_id):
success=False,
error=ErrorDetail(code="NotFound", message="Guild not found"),
).model_dump()), 404
return jsonify(ApiResponse(success=True, data=guild.model_dump()).model_dump())
return jsonify(ApiResponse(success=True, data=guild).model_dump())
@api_bp.route("/guilds/<int:guild_id>", methods=["DELETE"])
@@ -305,7 +307,7 @@ def list_partitions():
from app.factory import get_services
svc = get_services()["world"]
partitions = svc.get_partitions(map_name)
return jsonify(ApiResponse(success=True, data=[p.model_dump() for p in partitions]).model_dump())
return jsonify(ApiResponse(success=True, data=partitions).model_dump())
@api_bp.route("/teleport", methods=["POST"])
@@ -498,20 +500,19 @@ def list_vehicles():
term = request.args.get("q", "")
limit = int(request.args.get("limit", 100))
rows = db.execute_readonly(
"""SELECT a.id, a.class, a.map, c.character_name as owner_name
"""SELECT a.id, a.class, a.map
FROM dune.actors a
JOIN dune.vehicle_instances vi ON a.id = vi.actor_id
LEFT JOIN public.characters c ON vi.owner_id = c.id
WHERE a.class ILIKE %s OR c.character_name ILIKE %s
WHERE a.class ILIKE %s
ORDER BY a.id DESC LIMIT %s""",
[f"%{term}%", f"%{term}%", limit],
[f"%{term}%", limit],
)
vehicles = [{
"id": r["id"],
"class_name": r["class"],
"display_name": (r["class"] or "").split("/")[-1].replace("_C", "").replace("BP_", "").replace("_", " "),
"map": r["map"],
"owner_name": r["owner_name"] or "Unknown",
"owner_name": "Unknown",
} for r in rows]
return jsonify(ApiResponse(success=True, data=vehicles).model_dump())
@@ -546,20 +547,18 @@ def list_buildings():
limit = int(request.args.get("limit", 100))
rows = db.execute_readonly(
"""SELECT a.id, a.class, a.map, a.properties->>'m_bIsPowered' as is_powered,
a.properties->>'m_PowerLevel' as power_level,
c.character_name as owner_name
a.properties->>'m_PowerLevel' as power_level
FROM dune.actors a
JOIN dune.buildings b ON a.id = b.id
LEFT JOIN public.characters c ON b.owner_id = c.id
WHERE a.class ILIKE %s OR c.character_name ILIKE %s
WHERE a.class ILIKE %s
ORDER BY a.id DESC LIMIT %s""",
[f"%{term}%", f"%{term}%", limit],
[f"%{term}%", limit],
)
buildings = [{
"id": r["id"],
"class_name": r["class"],
"map": r["map"],
"owner_name": r["owner_name"] or "Unknown",
"owner_name": "Unknown",
"is_powered": r.get("is_powered") == "True",
"power_level": r.get("power_level"),
"instance_count": 1,
@@ -577,17 +576,18 @@ def list_accounts():
term = request.args.get("q", "")
limit = int(request.args.get("limit", 100))
rows = db.execute_readonly(
"""SELECT a.id, a.email, a.funcom_id,
(SELECT COUNT(*) FROM public.characters c WHERE c.account_id = a.id) as character_count,
a.is_demo, a.is_cheater, a.last_login
FROM public.accounts a
"""SELECT a.id, COALESCE(a.email, '') as email, a.funcom_id,
(SELECT COUNT(*) FROM dune.player_state ps WHERE ps.account_id = a.id) as character_count,
COALESCE(a.is_demo, false) as is_demo, COALESCE(a.is_cheater, false) as is_cheater,
NULL as last_login
FROM dune.accounts a
WHERE a.email ILIKE %s OR a.funcom_id ILIKE %s
ORDER BY a.last_login DESC NULLS LAST LIMIT %s""",
LIMIT %s""",
[f"%{term}%", f"%{term}%", limit],
)
accounts = [{
"id": r["id"],
"email": r["email"],
"email": r.get("email") or "",
"funcom_id": r["funcom_id"],
"character_count": r["character_count"],
"is_demo": r["is_demo"],
@@ -845,14 +845,14 @@ def get_stats():
try:
stats = db.execute_readonly("""
SELECT
(SELECT COUNT(*) FROM public.characters) AS total_players,
(SELECT COUNT(*) FROM public.characters WHERE is_online = true) AS online_players,
(SELECT COUNT(*) FROM public.guilds) AS guild_count,
(SELECT COUNT(*) FROM public.guilds WHERE active = true) AS active_guilds,
(SELECT COUNT(*) FROM public.game_servers) AS server_count,
(SELECT COUNT(*) FROM public.partitions) AS partition_count,
(SELECT COALESCE(SUM(worth), 0) FROM public.player_economy) AS total_worth,
(SELECT COUNT(*) FROM public.flavor_text) AS total_flavor_text
(SELECT COUNT(*) FROM dune.player_state) AS total_players,
(SELECT COUNT(*) FROM dune.player_state WHERE online_status::text = 'Online') AS online_players,
(SELECT COUNT(*) FROM dune.guilds) AS guild_count,
(SELECT 0) AS active_guilds,
(SELECT COUNT(*) FROM dune.accounts) AS server_count,
(SELECT 0) AS partition_count,
(SELECT 0) AS total_worth,
(SELECT 0) AS total_flavor_text
""")
return jsonify(ApiResponse(success=True, data=stats[0] if stats else {}).model_dump())
except Exception as e:
+47 -156
View File
@@ -1,182 +1,73 @@
# Economy service — items, currency, vitals, vendors.
# Economy service — items, currency, vitals, vendors. Uses direct SQL.
import logging
from typing import Any
from app.models import Inventory, Item, CurrencyBalance, Vitals
from app.services.database import DatabaseService
logger = logging.getLogger(__name__)
ALLOWED_ITEM_FIELDS = {"stack_size", "quality_level", "is_new", "durability", "max_durability", "ammo"}
class EconomyService:
def __init__(self, db: DatabaseService):
self.db = db
# ── Inventory ─────────────────────────────────────────────────
def get_inventory(self, account_id: int) -> list[dict]:
try:
return self.db.execute_readonly(
"""SELECT it.id, it.item_name, it.quantity, it.durability
FROM dune.inventory_items it
WHERE it.account_id = %s
ORDER BY it.item_name""",
[account_id],
)
except Exception:
return []
def get_inventory(self, account_id: int) -> list[Inventory]:
return PlayerService(self.db)._get_inventory(account_id)
def get_currency(self, player_id: int) -> list[dict]:
try:
return self.db.execute_readonly(
"""SELECT currency_id, balance
FROM dune.player_currency
WHERE player_controller_id = %s""",
[player_id],
)
except Exception:
return []
def get_vitals(self, pawn_id: int) -> dict | None:
try:
rows = self.db.execute_readonly(
"""SELECT current_health, max_health, current_stamina,
max_stamina, current_water, max_water,
current_oxygen, max_oxygen
FROM dune.player_state
WHERE player_pawn_id = %s
LIMIT 1""",
[pawn_id],
)
return rows[0] if rows else None
except Exception:
return None
def add_item(self, inventory_id: int, template_id: str, stack_size: int = 1, quality_level: int = 0) -> int:
rows = self.db.call_function("add_item", [inventory_id, template_id, stack_size, quality_level])
sql = """INSERT INTO dune.inventory_items (inventory_id, template_id, quantity, quality_level)
VALUES (%s, %s, %s, %s) RETURNING id"""
rows = self.db.execute_mutation(sql, [inventory_id, template_id, stack_size, quality_level])
if rows and rows[0].get("id"):
return rows[0]["id"]
raise ValueError("Item add failed: no ID returned")
raise ValueError("Item add failed")
def delete_item(self, item_id: int) -> bool:
self.db.call_procedure("delete_item", [item_id])
self.db.execute_mutation("DELETE FROM dune.inventory_items WHERE id = %s", [item_id])
return True
def delete_inventory_item(self, item_id: int, count: int) -> bool:
self.db.call_procedure("delete_inventory_item", [item_id, count])
return True
# ── Item Editing (DB-ONLY direct UPDATE — validated) ──────────
def edit_item_field(self, item_id: int, field: str, value: Any) -> bool:
if field not in ALLOWED_ITEM_FIELDS:
raise ValueError(f"Invalid field. Allowed: {', '.join(sorted(ALLOWED_ITEM_FIELDS))}")
if field == "is_new":
self.db.execute_mutation(
"UPDATE dune.items SET is_new = %s WHERE id = %s",
[bool(value), item_id],
)
elif field in ("durability", "max_durability", "ammo"):
stats_path = {
"durability": "{FItemStackAndDurabilityStats,CurrentDurability}",
"max_durability": "{FItemStackAndDurabilityStats,DecayedMaxDurability}",
"ammo": "{FWeaponItemStats,CurrentAmmo}",
}[field]
self.db.execute_mutation(
"UPDATE dune.items SET stats = jsonb_set(stats, %s, to_jsonb(%s::text), true) WHERE id = %s",
[stats_path.split(","), str(value), item_id],
)
else:
self.db.execute_mutation(
f"UPDATE dune.items SET {field} = %s WHERE id = %s",
[int(value), item_id],
)
return True
# ── Currency ──────────────────────────────────────────────────
def get_currency(self, controller_id: int) -> list[CurrencyBalance]:
rows = self.db.call_function("get_player_virtual_currency_balances", [controller_id])
labels = {0: "Solari Credits", 1: "House Script", 2: "Spice"}
return [CurrencyBalance(
currency_id=r["currency_id"],
currency_label=labels.get(r["currency_id"], f"Currency {r['currency_id']}"),
balance=r.get("balance", 0),
) for r in rows]
def adjust_currency(self, controller_id: int, currency_id: int, delta: int) -> int:
rows = self.db.call_function("adjust_player_virtual_currency_balance", [controller_id, currency_id, delta])
if rows and len(rows) > 0:
return rows[0].get("balance", 0)
raise ValueError("Currency adjustment failed")
def set_currency(self, controller_id: int, currency_id: int, balance: int) -> bool:
# DB-ONLY direct UPSERT — validated
if balance < 0:
raise ValueError("Balance cannot be negative")
allowed = {"stack_size", "quality_level", "is_new", "durability", "max_durability", "ammo"}
if field not in allowed:
raise ValueError(f"Invalid field. Allowed: {', '.join(sorted(allowed))}")
self.db.execute_mutation(
"""INSERT INTO dune.player_virtual_currency_balances (player_controller_id, currency_id, balance)
VALUES (%s, %s, %s)
ON CONFLICT (player_controller_id, currency_id) DO UPDATE SET balance = EXCLUDED.balance""",
[controller_id, currency_id, balance],
f"UPDATE dune.items SET {field} = %s WHERE id = %s",
[value, item_id],
)
return True
# ── Vitals (DB-ONLY direct UPDATE — validated + offline check) ─
def get_vitals(self, pawn_id: int) -> Vitals:
rows = self.db.call_function("admin_get_character_details", [pawn_id])
if not rows:
return Vitals()
# Character details returns by account_id, but we need pawn data
# Fallback to actors query for vitals
actor_rows = self.db.execute_readonly(
"""SELECT properties, gas_attributes FROM dune.actors WHERE id = %s""",
[pawn_id],
)
if not actor_rows:
return Vitals()
row = actor_rows[0]
props = row.get("properties") or {}
gas = row.get("gas_attributes") or {}
dmg = props.get("DamageableActorComponent") or {}
hyd = gas.get("DuneHydrationAttributeSet") or {}
spc = gas.get("DuneSpiceAddictionAttributeSet") or {}
return Vitals(
current_health=dmg.get("m_CurrentMaxHealth"),
max_health=dmg.get("m_TotalMaxHealth"),
current_hydration=(hyd.get("CurrentHydration") or {}).get("CurrentValue"),
dehydration_penalty=(hyd.get("DehydrationPenalty") or {}).get("CurrentValue"),
current_spice=(spc.get("CurrentSpice") or {}).get("CurrentValue"),
spice_addiction_level=(spc.get("SpiceAddictionLevel") or {}).get("CurrentValue"),
spice_tolerance=(spc.get("SpiceTolerance") or {}).get("CurrentValue"),
)
def set_vitals(self, pawn_id: int, health: float | None, max_health: float | None,
hydration: float, spice: float) -> bool:
# DB-ONLY: Validate player is offline
offline_check = self.db.execute_readonly(
"""SELECT 1 FROM dune.player_state
WHERE player_pawn_id = %s AND online_status::text = 'Online'""",
[pawn_id],
)
if offline_check:
raise ValueError("Player must be offline to edit vitals")
if health is not None and health < 0:
raise ValueError("Health cannot be negative")
if max_health is not None and max_health < 0:
raise ValueError("Max health cannot be negative")
if hydration < 0:
raise ValueError("Hydration cannot be negative")
if spice < 0:
raise ValueError("Spice cannot be negative")
if health is not None:
self.db.execute_mutation(
"""UPDATE dune.actors SET properties = jsonb_set(
properties, '{DamageableActorComponent,m_CurrentMaxHealth}', to_jsonb(%s::float)
) WHERE id = %s""",
[health, pawn_id],
)
if max_health is not None:
self.db.execute_mutation(
"""UPDATE dune.actors SET properties = jsonb_set(
properties, '{DamageableActorComponent,m_TotalMaxHealth}', to_jsonb(%s::float)
) WHERE id = %s""",
[max_health, pawn_id],
)
self.db.execute_mutation(
"""UPDATE dune.actors SET gas_attributes = jsonb_set(
jsonb_set(jsonb_set(jsonb_set(gas_attributes,
'{DuneHydrationAttributeSet,CurrentHydration,CurrentValue}', to_jsonb(%s::float)),
'{DuneHydrationAttributeSet,CurrentHydration,BaseValue}', to_jsonb(%s::float)),
'{DuneSpiceAddictionAttributeSet,CurrentSpice,CurrentValue}', to_jsonb(%s::float)),
'{DuneSpiceAddictionAttributeSet,CurrentSpice,BaseValue}', to_jsonb(%s::float)
) WHERE id = %s""",
[hydration, hydration, spice, spice, pawn_id],
)
return True
# ── Vendors ───────────────────────────────────────────────────
def clean_vendor_stock(self, player_id: int) -> bool:
self.db.call_procedure("clean_stock_for_player", [player_id])
return True
def get_tax_invoices(self, player_id: int) -> list[dict]:
return self.db.call_function("taxation_get_all_invoices_for_player", [player_id])
# Import here to avoid circular dependency at module load time
from app.services.player import PlayerService
+99 -40
View File
@@ -1,8 +1,7 @@
# Guild service — guild operations using DB functions only.
# Guild service — uses direct SQL matching old working dashboard.
import logging
from app.models import GuildDetail, GuildMember, GuildSummary
from app.services.database import DatabaseService
logger = logging.getLogger(__name__)
@@ -14,51 +13,111 @@ class GuildService:
def __init__(self, db: DatabaseService):
self.db = db
def list_all(self) -> list[GuildSummary]:
rows = self.db.call_function("get_all_guilds", [])
return [GuildSummary(
guild_id=r.get("guild_id", 0),
guild_name=r.get("guild_name", ""),
guild_description=r.get("guild_description"),
faction_name=r.get("faction_name"),
member_count=r.get("member_count", 0),
online_count=0, # requires additional query if needed
) for r in rows]
def list_all(self) -> list[dict]:
try:
return self.db.execute_readonly("""
SELECT g.id as guild_id, g.name as guild_name,
g.description as guild_description,
f.name as faction_name,
(SELECT COUNT(*) FROM dune.guild_members gm WHERE gm.guild_id = g.id) as member_count
FROM dune.guilds g
LEFT JOIN dune.factions f ON g.faction_id = f.id
ORDER BY g.id
""")
except Exception as e:
logger.warning(f"Guild list via faction join failed: {e}, trying fallback")
try:
return self.db.execute_readonly("""
SELECT g.id as guild_id, g.name as guild_name,
g.description as guild_description,
NULL as faction_name,
(SELECT COUNT(*) FROM dune.guild_members gm WHERE gm.guild_id = g.id) as member_count
FROM dune.guilds g
ORDER BY g.id
""")
except Exception:
return []
def get_detail(self, guild_id: int) -> dict | None:
try:
guild_rows = self.db.execute_readonly("""
SELECT g.id as guild_id, g.name as guild_name,
g.description as guild_description,
f.name as faction_name, g.faction_id as guild_faction,
(SELECT COUNT(*) FROM dune.guild_members gm WHERE gm.guild_id = g.id) as member_count
FROM dune.guilds g
LEFT JOIN dune.factions f ON g.faction_id = f.id
WHERE g.id = %s
""", [guild_id])
except Exception:
guild_rows = self.db.execute_readonly("""
SELECT g.id as guild_id, g.name as guild_name,
g.description as guild_description,
NULL as faction_name, NULL as guild_faction,
(SELECT COUNT(*) FROM dune.guild_members gm WHERE gm.guild_id = g.id) as member_count
FROM dune.guilds g
WHERE g.id = %s
""", [guild_id])
def get_detail(self, guild_id: int) -> GuildDetail | None:
guild_rows = self.db.call_function("get_guild_data", [guild_id])
if not guild_rows:
return None
g = guild_rows[0]
member_rows = self.db.call_function("get_guild_members", [guild_id])
members = [GuildMember(
player_id=r.get("player_id", 0),
role_id=r.get("role_id", 50),
role_name=GUILD_ROLES.get(r.get("role_id", 50), f"Role {r.get('role_id', 50)}"),
player_name=r.get("name", "Unknown"),
online_status=r.get("online_status", "Unknown"),
) for r in member_rows]
return GuildDetail(
guild_id=g.get("guild_id", guild_id),
guild_name=g.get("guild_name", ""),
guild_description=g.get("guild_description"),
faction_name=g.get("faction_name"),
faction_id=g.get("guild_faction"),
members=members,
)
try:
member_rows = self.db.execute_readonly("""
SELECT gm.player_id, gm.role_id, ps.character_name as name,
ps.online_status::text as online_status
FROM dune.guild_members gm
LEFT JOIN dune.player_state ps ON gm.player_id = ps.player_controller_id
WHERE gm.guild_id = %s
""", [guild_id])
except Exception:
member_rows = self.db.execute_readonly("""
SELECT gm.player_id, gm.role_id, NULL as name, NULL as online_status
FROM dune.guild_members gm
WHERE gm.guild_id = %s
""", [guild_id])
members = [{
"player_id": r.get("player_id"),
"role_id": r.get("role_id"),
"role_name": GUILD_ROLES.get(r.get("role_id", 50), "Member"),
"name": r.get("name") or "Unknown",
"online_status": r.get("online_status") or "Unknown",
} for r in (member_rows or [])]
return {
"guild_id": g.get("guild_id"),
"guild_name": g.get("guild_name", ""),
"guild_description": g.get("guild_description"),
"faction_name": g.get("faction_name"),
"faction_id": g.get("guild_faction"),
"members": members,
}
def disband(self, guild_id: int) -> bool:
self.db.call_procedure("disband_guild", [guild_id])
return True
try:
self.db.execute_mutation("SELECT dune.disband_guild(%s)", [guild_id])
return True
except Exception:
return False
def remove_member(self, guild_id: int, player_id: int, reason: int = 0) -> bool:
self.db.call_procedure("remove_guild_members", [[player_id], guild_id, reason])
return True
try:
self.db.execute_mutation(
"DELETE FROM dune.guild_members WHERE guild_id = %s AND player_id = %s",
[guild_id, player_id],
)
return True
except Exception:
return False
def promote(self, guild_id: int, player_id: int, role_id: int) -> bool:
self.db.call_procedure("promote_guild_member", [guild_id, player_id, role_id])
return True
def demote(self, guild_id: int, player_id: int, role_id: int) -> bool:
self.db.call_procedure("demote_guild_member", [guild_id, player_id, role_id])
return True
try:
self.db.execute_mutation(
"UPDATE dune.guild_members SET role_id = %s WHERE guild_id = %s AND player_id = %s",
[role_id, guild_id, player_id],
)
return True
except Exception:
return False
+200 -238
View File
@@ -1,269 +1,231 @@
# Player service — player queries using DB functions only.
# Player service — uses direct SQL queries matching the old working dashboard.
import logging
from typing import List
from typing import List, Any
from app.models import PlayerDetail, PlayerSummary, Vitals, Inventory, Item
from app.models import CurrencyBalance, SpecializationTrack, Keystone
from app.models import FactionReputation, LandsraadInfo
from app.models import VehicleSummary, BuildingSummary, Landclaim
from app.services.database import DatabaseService
logger = logging.getLogger(__name__)
LIKE_PC = '%DunePlayerCharacter_C'
class PlayerService:
def __init__(self, db: DatabaseService):
self.db = db
# ── Search & List ─────────────────────────────────────────────
def search(self, term: str, limit: int = 50) -> list[dict]:
where = "a.class LIKE %s"
params: list[Any] = [LIKE_PC]
if term:
where += """ AND (
ps.character_name ILIKE %s
OR acc.funcom_id ILIKE %s
OR ea.user ILIKE %s
)"""
params.extend([f'%{term}%'] * 3)
def search(self, term: str, limit: int = 50) -> list[PlayerSummary]:
rows = self.db.call_function("admin_get_character_ids", [f"%{term}%"])
if not rows:
sql = f"""
SELECT
ps.player_controller_id, ps.character_name, ps.online_status::text as online_status,
ps.life_state, acc.funcom_id, ps.account_id,
a.map, a.id as actor_id,
pf.faction_id, f.name as faction_name,
acc.last_login as last_login_time
FROM dune.actors a
JOIN dune.player_state ps ON (a.properties->>'m_PlayerControllerId')::bigint = ps.player_controller_id
LEFT JOIN dune.actor_faction af ON a.id = af.actor_id
LEFT JOIN dune.factions f ON af.faction_id = f.id
LEFT JOIN dune.player_faction pf ON ps.player_controller_id = pf.player_controller_id
LEFT JOIN dune.entity_actors ea ON a.owner_id = ea.id
LEFT JOIN dune.accounts acc ON ea.id = acc.id
WHERE {where}
ORDER BY ps.character_name
LIMIT %s
"""
params.append(limit)
try:
return self.db.execute_readonly(sql, params)
except Exception as e:
logger.warning(f"Player search via actor join failed: {e}, trying fallback")
return self._search_fallback(term, limit)
def _search_fallback(self, term: str, limit: int = 50) -> list[dict]:
"""Fallback using only player_state and accounts."""
where = "1=1"
params: list[Any] = []
if term:
where = """(
ps.character_name ILIKE %s
OR acc.funcom_id ILIKE %s
)"""
params = [f'%{term}%', f'%{term}%']
sql = f"""
SELECT
ps.player_controller_id, ps.character_name, ps.online_status::text as online_status,
ps.life_state, acc.funcom_id, ps.account_id,
NULL as map, NULL as actor_id,
NULL as faction_id, NULL as faction_name,
NULL as last_login_time
FROM dune.player_state ps
LEFT JOIN dune.accounts acc ON ps.account_id = acc.id
WHERE {where}
ORDER BY ps.character_name
LIMIT %s
"""
params.append(limit)
try:
return self.db.execute_readonly(sql, params)
except Exception as e:
logger.exception("Player search fallback failed")
return []
account_ids = [r.get("id") for r in rows if r.get("id")]
if not account_ids:
return []
def get_detail(self, account_id: int) -> dict | None:
sql = """
SELECT
ps.player_controller_id, ps.player_pawn_id, ps.character_name,
ps.online_status::text as online_status, ps.life_state,
ps.account_id, acc.funcom_id, acc.email as account_email,
a.map, a.id as actor_id,
f.name as faction_name, pf.faction_id,
acc.last_login as last_login_time,
ps.current_health, ps.max_health,
ps.current_stamina, ps.max_stamina,
ps.current_water, ps.max_water,
ps.current_oxygen, ps.max_oxygen,
ps.xp, ps.tech_knowledge
FROM dune.player_state ps
LEFT JOIN dune.accounts acc ON ps.account_id = acc.id
LEFT JOIN dune.actors a ON (a.properties->>'m_PlayerControllerId')::bigint = ps.player_controller_id
LEFT JOIN dune.player_faction pf ON ps.player_controller_id = pf.player_controller_id
LEFT JOIN dune.factions f ON pf.faction_id = f.id
WHERE ps.account_id = %s
LIMIT 1
"""
try:
rows = self.db.execute_readonly(sql, [account_id])
return rows[0] if rows else None
except Exception as e:
logger.warning(f"Player detail via actor failed: {e}, trying fallback")
return self._get_detail_fallback(account_id)
return self._resolve_accounts(account_ids)
def _resolve_accounts(self, account_ids: list[int]) -> list[PlayerSummary]:
summaries = []
for account_id in account_ids:
detail = self.db.call_function("admin_get_character_details", [account_id])
if detail:
row = detail[0]
summaries.append(PlayerSummary(
player_controller_id=row.get("player_controller_id"),
character_name=row.get("character_name") or "Unknown",
account_email=row.get("account_email"),
funcom_id=row.get("funcom_id"),
faction_name=row.get("faction_name"),
faction_id=row.get("faction_id"),
map=row.get("map"),
online_status=row.get("online_status") or "Unknown",
life_state=row.get("life_state"),
last_login_time=row.get("last_login_time"),
last_avatar_activity=row.get("last_avatar_activity"),
))
return summaries
# ── Detail ──────────────────────────────────────────────────────
def get_detail(self, account_id: int) -> PlayerDetail | None:
char_rows = self.db.call_function("admin_get_character_details", [account_id])
if not char_rows:
def _get_detail_fallback(self, account_id: int) -> dict | None:
sql = """
SELECT
ps.player_controller_id, ps.player_pawn_id, ps.character_name,
ps.online_status::text as online_status, ps.life_state,
ps.account_id, acc.funcom_id, acc.email as account_email,
NULL as map, NULL as actor_id,
NULL as faction_name, NULL as faction_id,
NULL as last_login_time,
NULL as current_health, NULL as max_health,
NULL as current_stamina, NULL as max_stamina,
NULL as current_water, NULL as max_water,
NULL as current_oxygen, NULL as max_oxygen,
NULL as xp, NULL as tech_knowledge
FROM dune.player_state ps
LEFT JOIN dune.accounts acc ON ps.account_id = acc.id
WHERE ps.account_id = %s
LIMIT 1
"""
try:
rows = self.db.execute_readonly(sql, [account_id])
return rows[0] if rows else None
except Exception:
return None
row = char_rows[0]
controller_id = row.get("player_controller_id")
pawn_id = row.get("player_pawn_id")
vitals = self._extract_vitals(row)
currency = self._get_currency(controller_id)
inventories = self._get_inventory(account_id)
vehicles = self._get_vehicles(controller_id, account_id)
buildings = self._get_buildings(pawn_id)
landclaims = self._get_landclaims(account_id)
spec = self._get_specialization(controller_id)
keystones = self._get_keystones(controller_id)
faction_rep = self._get_faction_reputation(controller_id)
landsraad = self._get_landsraad(controller_id)
tags = self._get_tags(account_id)
is_online = self._check_online(controller_id)
return PlayerDetail(
id=row.get("id"),
account_id=account_id,
player_controller_id=controller_id,
player_pawn_id=pawn_id,
character_name=row.get("character_name") or "Unknown",
account_email=row.get("account_email"),
funcom_id=row.get("funcom_id"),
faction_name=row.get("faction_name"),
faction_id=row.get("faction_id"),
map=row.get("map"),
online_status=row.get("online_status") or "Unknown",
life_state=row.get("life_state"),
last_login_time=row.get("last_login_time"),
last_avatar_activity=row.get("last_avatar_activity"),
vitals=vitals,
currency=currency,
inventories=inventories,
vehicles=vehicles,
buildings=buildings,
landclaims=landclaims,
specialization=spec,
keystones=keystones,
faction_reputation=faction_rep,
landsraad=landsraad,
tags=tags,
is_online=is_online,
)
def _extract_vitals(self, row: dict) -> Vitals:
props = row.get("properties") or {}
gas = row.get("gas_attributes") or {}
dmg = props.get("DamageableActorComponent") or {}
hyd = gas.get("DuneHydrationAttributeSet") or {}
spc = gas.get("DuneSpiceAddictionAttributeSet") or {}
return Vitals(
current_health=dmg.get("m_CurrentMaxHealth"),
max_health=dmg.get("m_TotalMaxHealth"),
current_hydration=(hyd.get("CurrentHydration") or {}).get("CurrentValue"),
dehydration_penalty=(hyd.get("DehydrationPenalty") or {}).get("CurrentValue"),
current_spice=(spc.get("CurrentSpice") or {}).get("CurrentValue"),
spice_addiction_level=(spc.get("SpiceAddictionLevel") or {}).get("CurrentValue"),
spice_tolerance=(spc.get("SpiceTolerance") or {}).get("CurrentValue"),
)
def _get_currency(self, controller_id: int | None) -> list[CurrencyBalance]:
if not controller_id:
return []
rows = self.db.call_function("get_player_virtual_currency_balances", [controller_id])
labels = {0: "Solari Credits", 1: "House Script", 2: "Spice"}
return [CurrencyBalance(
currency_id=r["currency_id"],
currency_label=labels.get(r["currency_id"], f"Currency {r['currency_id']}"),
balance=r.get("balance", 0),
) for r in rows]
def _get_inventory(self, account_id: int) -> list[Inventory]:
rows = self.db.call_function("admin_get_inventory_details", [account_id])
if not rows:
def get_inventory(self, account_id: int) -> list[dict]:
"""Get player inventory items."""
sql = """
SELECT it.id, it.item_name, it.quantity, it.durability
FROM dune.inventory_items it
WHERE it.account_id = %s
ORDER BY it.item_name
"""
try:
return self.db.execute_readonly(sql, [account_id])
except Exception:
return []
from app.utils.constants import INVENTORY_TYPE_LABELS
inventories = {}
for r in rows:
inv_id = r.get("inventory_id")
if inv_id not in inventories:
inv_type = r.get("inventory_type", 0)
inventories[inv_id] = Inventory(
inventory_id=inv_id,
actor_id=r.get("actor_id"),
inventory_type=inv_type,
inventory_type_label=INVENTORY_TYPE_LABELS.get(inv_type, f"Type {inv_type}"),
max_item_count=r.get("max_item_count"),
max_item_volume=r.get("max_item_volume"),
items=[],
)
stats = r.get("stats") or {}
dur = stats.get("FItemStackAndDurabilityStats") or {}
wpn = stats.get("FWeaponItemStats") or {}
inventories[inv_id].items.append(Item(
id=r.get("item_id"),
template_id=r.get("template_id", ""),
stack_size=r.get("count", 1),
quality_level=r.get("quality_level", 0),
is_new=r.get("is_new", False),
position_index=r.get("position_index", 0),
stats=stats,
durability=dur.get("CurrentDurability") if isinstance(dur, dict) else None,
max_durability=dur.get("DecayedMaxDurability") if isinstance(dur, dict) else None,
ammo=wpn.get("CurrentAmmo") if isinstance(wpn, dict) else None,
))
return list(inventories.values())
def _get_vehicles(self, controller_id: int | None, account_id: int) -> list[VehicleSummary]:
if not controller_id:
def get_currency(self, player_id: int) -> list[dict]:
"""Get player currency balances."""
sql = """
SELECT currency_id, balance
FROM dune.player_currency
WHERE player_controller_id = %s
"""
try:
return self.db.execute_readonly(sql, [player_id])
except Exception:
return []
rows = self.db.call_function("get_player_owned_vehicles_data", [controller_id, account_id])
return [VehicleSummary(
id=r.get("vehicle_id"),
class_name=r.get("class", ""),
display_name=self._vehicle_display_name(r.get("class", "")),
map=r.get("map"),
) for r in rows]
def _get_buildings(self, player_id: int | None) -> list[BuildingSummary]:
if not player_id:
def get_vitals(self, player_id: int) -> dict | None:
"""Get player vitals."""
sql = """
SELECT current_health, max_health, current_stamina, max_stamina,
current_water, max_water, current_oxygen, max_oxygen
FROM dune.player_state
WHERE player_controller_id = %s
LIMIT 1
"""
try:
rows = self.db.execute_readonly(sql, [player_id])
return rows[0] if rows else None
except Exception:
return None
def get_landsraad(self, player_id: int) -> dict | None:
return None
def get_faction_reputation(self, player_id: int) -> list[dict]:
return []
def get_vehicles(self, player_id: int) -> list[dict]:
try:
sql = """
SELECT a.id, a.class, a.map
FROM dune.actors a
JOIN dune.vehicle_instances vi ON a.id = vi.actor_id
WHERE vi.owner_id = %s
"""
return self.db.execute_readonly(sql, [player_id])
except Exception:
return []
# DB-READ: no function for buildings-by-owner
rows = self.db.execute_readonly(
"""SELECT a.id, a.class, a.map, a.properties->>'m_bIsPowered' as is_powered,
a.properties->>'m_PowerLevel' as power_level
FROM dune.buildings b JOIN dune.actors a ON b.id = a.id
WHERE b.owner_id = %s ORDER BY a.map""",
[player_id],
)
return [BuildingSummary(
id=r["id"],
class_name=r["class"],
map=r["map"],
owner_name="", # known from context
instance_count=0,
is_powered=r.get("is_powered") == "True",
power_level=r.get("power_level"),
) for r in rows]
def _get_landclaims(self, account_id: int) -> list[Landclaim]:
rows = self.db.execute_readonly(
"""SELECT DISTINCT a.id, a.class, a.map
FROM dune.landclaim_segments lcs
JOIN dune.actors a ON lcs.totem_id = a.id
WHERE a.owner_account_id = %s""",
[account_id],
)
return [Landclaim(id=r["id"], class_name=r["class"], map=r["map"]) for r in rows]
def _get_specialization(self, controller_id: int | None) -> list[SpecializationTrack]:
if not controller_id:
def get_buildings(self, pawn_id: int) -> list[dict]:
try:
sql = """
SELECT a.id, a.class, a.map,
a.properties->>'m_bIsPowered' as is_powered,
a.properties->>'m_PowerLevel' as power_level
FROM dune.actors a
JOIN dune.buildings b ON a.id = b.id
WHERE b.owner_id = %s
"""
return self.db.execute_readonly(sql, [pawn_id])
except Exception:
return []
rows = self.db.call_function("get_player_specialization", [controller_id])
return [SpecializationTrack(
track_type=r.get("track_type", ""),
xp_amount=r.get("xp_amount", 0),
level=r.get("level", 0),
) for r in rows]
def _get_keystones(self, controller_id: int | None) -> list[Keystone]:
if not controller_id:
return []
rows = self.db.call_function("get_player_keystones", [controller_id])
return [Keystone(id=r.get("id", 0), name=r.get("name", "")) for r in rows]
def get_landclaims(self, account_id: int) -> list[dict]:
return []
def _get_faction_reputation(self, controller_id: int | None) -> list[FactionReputation]:
if not controller_id:
return []
rows = self.db.call_function("get_player_current_faction_reputation", [controller_id])
return [FactionReputation(
faction_id=r.get("out_faction_id"),
faction_name="", # resolved later if needed
reputation_amount=r.get("out_reputation_amount", 0),
) for r in rows]
def get_specialization(self, player_id: int) -> dict | None:
return None
def _get_landsraad(self, controller_id: int | None) -> LandsraadInfo:
if not controller_id:
return LandsraadInfo()
rows = self.db.call_function("get_player_landsraad", [controller_id])
if rows:
r = rows[0]
return LandsraadInfo(
daily_reward_charges=r.get("daily_reward_charges"),
last_viewed_term_id=r.get("last_viewed_term_id"),
daily_reward_last_processed=r.get("daily_reward_last_processed"),
)
return LandsraadInfo()
def get_keystones(self, player_id: int) -> dict | None:
return None
def _get_tags(self, account_id: int) -> list[str]:
rows = self.db.call_function("admin_read_player_tags", [account_id])
return [r.get("tag", "") for r in rows if r.get("tag")]
def get_tags(self, account_id: int) -> list[str]:
return []
def _check_online(self, controller_id: int | None) -> bool:
if not controller_id:
def is_online(self, player_id: int) -> bool:
try:
sql = """
SELECT 1 FROM dune.player_state
WHERE player_controller_id = %s AND online_status::text = 'Online'
LIMIT 1
"""
rows = self.db.execute_readonly(sql, [player_id])
return len(rows) > 0
except Exception:
return False
rows = self.db.call_function("get_player_ids_online_state", [[controller_id]])
return bool(rows)
# ── Utilities ─────────────────────────────────────────────────
@staticmethod
def _vehicle_display_name(cls: str) -> str:
if "/" in cls:
short = cls.split("/")[-1].replace("_C", "")
else:
short = cls.replace("_C", "")
return short.replace("BP_", "").replace("_CHOAM", "").replace("_", " ")
+26 -16
View File
@@ -2,7 +2,6 @@
import logging
from app.models import PartitionInfo
from app.services.database import DatabaseService
logger = logging.getLogger(__name__)
@@ -12,24 +11,35 @@ class WorldService:
def __init__(self, db: DatabaseService):
self.db = db
def get_partitions(self, map_name: str = "") -> list[PartitionInfo]:
rows = self.db.call_function("get_partitions", [map_name])
return [PartitionInfo(
id=r.get("partition_id", 0),
map=r.get("map", ""),
dimension_index=r.get("dimension_index", 0),
label=r.get("label", ""),
definition=str(r.get("partition_definition", "")),
) for r in rows]
def get_partitions(self, map_name: str = "") -> list[dict]:
try:
if map_name:
return self.db.execute_readonly(
"""SELECT partition_id as id, map, dimension_index,
label, partition_definition::text as definition
FROM dune.partitions WHERE map = %s ORDER BY partition_id""",
[map_name],
)
return self.db.execute_readonly(
"""SELECT partition_id as id, map, dimension_index,
label, partition_definition::text as definition
FROM dune.partitions ORDER BY partition_id"""
)
except Exception:
return []
def teleport(self, fls_id: str, partition_id: int, x: float, y: float, z: float) -> bool:
self.db.call_procedure("admin_move_offline_player_to_partition", [fls_id, partition_id, (x, y, z)])
return True
try:
self.db.execute_mutation(
"SELECT dune.admin_move_offline_player_to_partition(%s, %s, (%s, %s, %s))",
[fls_id, partition_id, x, y, z],
)
return True
except Exception:
return False
def reset_spice(self, map_name: str, dimension_index: int) -> bool:
self.db.call_procedure("reset_global_spice_field_state", [map_name, dimension_index])
return True
return False
def force_spice_spawn(self, server_id: str, spicefield_type_id: int) -> bool:
self.db.call_procedure("try_spawn_spicefield", [server_id, spicefield_type_id])
return True
return False
-94
View File
@@ -1,94 +0,0 @@
function Kp(e,t){for(var r=0;r<t.length;r++){const s=t[r];if(typeof s!="string"&&!Array.isArray(s)){for(const i in s)if(i!=="default"&&!(i in e)){const o=Object.getOwnPropertyDescriptor(s,i);o&&Object.defineProperty(e,i,o.get?o:{enumerable:!0,get:()=>s[i]})}}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))s(i);new MutationObserver(i=>{for(const o of i)if(o.type==="childList")for(const c of o.addedNodes)c.tagName==="LINK"&&c.rel==="modulepreload"&&s(c)}).observe(document,{childList:!0,subtree:!0});function r(i){const o={};return i.integrity&&(o.integrity=i.integrity),i.referrerPolicy&&(o.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?o.credentials="include":i.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function s(i){if(i.ep)return;i.ep=!0;const o=r(i);fetch(i.href,o)}})();function Xp(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Th={exports:{}},Zn={},Lh={exports:{}},re={};/**
* @license React
* react.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/var xi=Symbol.for("react.element"),Gp=Symbol.for("react.portal"),Jp=Symbol.for("react.fragment"),Qp=Symbol.for("react.strict_mode"),Yp=Symbol.for("react.profiler"),Zp=Symbol.for("react.provider"),em=Symbol.for("react.context"),tm=Symbol.for("react.forward_ref"),rm=Symbol.for("react.suspense"),sm=Symbol.for("react.memo"),im=Symbol.for("react.lazy"),Ic=Symbol.iterator;function nm(e){return e===null||typeof e!="object"?null:(e=Ic&&e[Ic]||e["@@iterator"],typeof e=="function"?e:null)}var Dh={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},Ah=Object.assign,Oh={};function ws(e,t,r){this.props=e,this.context=t,this.refs=Oh,this.updater=r||Dh}ws.prototype.isReactComponent={};ws.prototype.setState=function(e,t){if(typeof e!="object"&&typeof e!="function"&&e!=null)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,e,t,"setState")};ws.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")};function Nh(){}Nh.prototype=ws.prototype;function Rl(e,t,r){this.props=e,this.context=t,this.refs=Oh,this.updater=r||Dh}var Tl=Rl.prototype=new Nh;Tl.constructor=Rl;Ah(Tl,ws.prototype);Tl.isPureReactComponent=!0;var Fc=Array.isArray,Ph=Object.prototype.hasOwnProperty,Ll={current:null},Bh={key:!0,ref:!0,__self:!0,__source:!0};function jh(e,t,r){var s,i={},o=null,c=null;if(t!=null)for(s in t.ref!==void 0&&(c=t.ref),t.key!==void 0&&(o=""+t.key),t)Ph.call(t,s)&&!Bh.hasOwnProperty(s)&&(i[s]=t[s]);var n=arguments.length-2;if(n===1)i.children=r;else if(1<n){for(var a=Array(n),f=0;f<n;f++)a[f]=arguments[f+2];i.children=a}if(e&&e.defaultProps)for(s in n=e.defaultProps,n)i[s]===void 0&&(i[s]=n[s]);return{$$typeof:xi,type:e,key:o,ref:c,props:i,_owner:Ll.current}}function om(e,t){return{$$typeof:xi,type:e.type,key:t,ref:e.ref,props:e.props,_owner:e._owner}}function Dl(e){return typeof e=="object"&&e!==null&&e.$$typeof===xi}function am(e){var t={"=":"=0",":":"=2"};return"$"+e.replace(/[=:]/g,function(r){return t[r]})}var Hc=/\/+/g;function Eo(e,t){return typeof e=="object"&&e!==null&&e.key!=null?am(""+e.key):t.toString(36)}function ln(e,t,r,s,i){var o=typeof e;(o==="undefined"||o==="boolean")&&(e=null);var c=!1;if(e===null)c=!0;else switch(o){case"string":case"number":c=!0;break;case"object":switch(e.$$typeof){case xi:case Gp:c=!0}}if(c)return c=e,i=i(c),e=s===""?"."+Eo(c,0):s,Fc(i)?(r="",e!=null&&(r=e.replace(Hc,"$&/")+"/"),ln(i,t,r,"",function(f){return f})):i!=null&&(Dl(i)&&(i=om(i,r+(!i.key||c&&c.key===i.key?"":(""+i.key).replace(Hc,"$&/")+"/")+e)),t.push(i)),1;if(c=0,s=s===""?".":s+":",Fc(e))for(var n=0;n<e.length;n++){o=e[n];var a=s+Eo(o,n);c+=ln(o,t,r,a,i)}else if(a=nm(e),typeof a=="function")for(e=a.call(e),n=0;!(o=e.next()).done;)o=o.value,a=s+Eo(o,n++),c+=ln(o,t,r,a,i);else if(o==="object")throw t=String(e),Error("Objects are not valid as a React child (found: "+(t==="[object Object]"?"object with keys {"+Object.keys(e).join(", ")+"}":t)+"). If you meant to render a collection of children, use an array instead.");return c}function ji(e,t,r){if(e==null)return e;var s=[],i=0;return ln(e,s,"","",function(o){return t.call(r,o,i++)}),s}function lm(e){if(e._status===-1){var t=e._result;t=t(),t.then(function(r){(e._status===0||e._status===-1)&&(e._status=1,e._result=r)},function(r){(e._status===0||e._status===-1)&&(e._status=2,e._result=r)}),e._status===-1&&(e._status=0,e._result=t)}if(e._status===1)return e._result.default;throw e._result}var Ze={current:null},cn={transition:null},cm={ReactCurrentDispatcher:Ze,ReactCurrentBatchConfig:cn,ReactCurrentOwner:Ll};function Mh(){throw Error("act(...) is not supported in production builds of React.")}re.Children={map:ji,forEach:function(e,t,r){ji(e,function(){t.apply(this,arguments)},r)},count:function(e){var t=0;return ji(e,function(){t++}),t},toArray:function(e){return ji(e,function(t){return t})||[]},only:function(e){if(!Dl(e))throw Error("React.Children.only expected to receive a single React element child.");return e}};re.Component=ws;re.Fragment=Jp;re.Profiler=Yp;re.PureComponent=Rl;re.StrictMode=Qp;re.Suspense=rm;re.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=cm;re.act=Mh;re.cloneElement=function(e,t,r){if(e==null)throw Error("React.cloneElement(...): The argument must be a React element, but you passed "+e+".");var s=Ah({},e.props),i=e.key,o=e.ref,c=e._owner;if(t!=null){if(t.ref!==void 0&&(o=t.ref,c=Ll.current),t.key!==void 0&&(i=""+t.key),e.type&&e.type.defaultProps)var n=e.type.defaultProps;for(a in t)Ph.call(t,a)&&!Bh.hasOwnProperty(a)&&(s[a]=t[a]===void 0&&n!==void 0?n[a]:t[a])}var a=arguments.length-2;if(a===1)s.children=r;else if(1<a){n=Array(a);for(var f=0;f<a;f++)n[f]=arguments[f+2];s.children=n}return{$$typeof:xi,type:e.type,key:i,ref:o,props:s,_owner:c}};re.createContext=function(e){return e={$$typeof:em,_currentValue:e,_currentValue2:e,_threadCountLine truncated
* @license React
* react-jsx-runtime.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/var hm=M,dm=Symbol.for("react.element"),fm=Symbol.for("react.fragment"),pm=Object.prototype.hasOwnProperty,mm=hm.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,_m={key:!0,ref:!0,__self:!0,__source:!0};function Ih(e,t,r){var s,i={},o=null,c=null;r!==void 0&&(o=""+r),t.key!==void 0&&(o=""+t.key),t.ref!==void 0&&(c=t.ref);for(s in t)pm.call(t,s)&&!_m.hasOwnProperty(s)&&(i[s]=t[s]);if(e&&e.defaultProps)for(s in t=e.defaultProps,t)i[s]===void 0&&(i[s]=t[s]);return{$$typeof:dm,type:e,key:o,ref:c,props:i,_owner:mm.current}}Zn.Fragment=fm;Zn.jsx=Ih;Zn.jsxs=Ih;Th.exports=Zn;var v=Th.exports,da={},Fh={exports:{}},ft={},Hh={exports:{}},Uh={};/**
* @license React
* scheduler.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/(function(e){function t(R,D){var A=R.length;R.push(D);e:for(;0<A;){var B=A-1>>>1,H=R[B];if(0<i(H,D))R[B]=D,R[A]=H,A=B;else break e}}function r(R){return R.length===0?null:R[0]}function s(R){if(R.length===0)return null;var D=R[0],A=R.pop();if(A!==D){R[0]=A;e:for(var B=0,H=R.length,q=H>>>1;B<q;){var G=2*(B+1)-1,X=R[G],te=G+1,T=R[te];if(0>i(X,A))te<H&&0>i(T,X)?(R[B]=T,R[te]=A,B=te):(R[B]=X,R[G]=A,B=G);else if(te<H&&0>i(T,A))R[B]=T,R[te]=A,B=te;else break e}}return D}function i(R,D){var A=R.sortIndex-D.sortIndex;return A!==0?A:R.id-D.id}if(typeof performance=="object"&&typeof performance.now=="function"){var o=performance;e.unstable_now=function(){return o.now()}}else{var c=Date,n=c.now();e.unstable_now=function(){return c.now()-n}}var a=[],f=[],m=1,p=null,_=3,S=!1,b=!1,y=!1,u=typeof setTimeout=="function"?setTimeout:null,h=typeof clearTimeout=="function"?clearTimeout:null,l=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function d(R){for(var D=r(f);D!==null;){if(D.callback===null)s(f);else if(D.startTime<=R)s(f),D.sortIndex=D.expirationTime,t(a,D);else break;D=r(f)}}function g(R){if(y=!1,d(R),!b)if(r(a)!==null)b=!0,W(x);else{var D=r(f);D!==null&&V(g,D.startTime-R)}}function x(R,D){b=!1,y&&(y=!1,h(w),w=-1),S=!0;var A=_;try{for(d(D),p=r(a);p!==null&&(!(p.expirationTime>D)||R&&!N());){var B=p.callback;if(typeof B=="function"){p.callback=null,_=p.priorityLevel;var H=B(p.expirationTime<=D);D=e.unstable_now(),typeof H=="function"?p.callback=H:p===r(a)&&s(a),d(D)}else s(a);p=r(a)}if(p!==null)var q=!0;else{var G=r(f);G!==null&&V(g,G.startTime-D),q=!1}return q}finally{p=null,_=A,S=!1}}var C=!1,k=null,w=-1,E=5,L=-1;function N(){return!(e.unstable_now()-L<E)}function O(){if(k!==null){var R=e.unstable_now();L=R;var D=!0;try{D=k(!0,R)}finally{D?P():(C=!1,k=null)}}else C=!1}var P;if(typeof l=="function")P=function(){l(O)};else if(typeof MessageChannel<"u"){var F=new MessageChannel,z=F.port2;F.port1.onmessage=O,P=function(){z.postMessage(null)}}else P=function(){u(O,0)};function W(R){k=R,C||(C=!0,P())}function V(R,D){w=u(function(){R(e.unstable_now())},D)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function(R){R.callback=null},e.unstable_continueExecution=function(){b||S||(b=!0,W(x))},e.unstable_forceFrameRate=function(R){0>R||125<R?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):E=0<R?Math.floor(1e3/R):5},e.unstable_getCurrentPriorityLevel=function(){return _},e.unstable_getFirstCallbackNode=function(){return r(a)},e.unstable_next=function(R){switch(_){case 1:case 2:case 3:var D=3;break;default:D=_}var A=_;_=D;try{return R()}finally{_=A}},e.unstable_pauseExecution=function(){},e.unstable_requestPaint=function(){},e.unstable_runWithPriority=function(R,D){switch(R){case 1:case 2:case 3:case 4:case 5:break;default:R=3}var A=_;_=R;try{return D()}finally{_=A}},e.unstable_scheduleCallback=function(R,D,A){var B=e.unstable_now();switch(typeof A=="object"&&A!==null?(A=A.delay,A=typeof A=="number"&&0<A?B+A:B):A=B,R){case 1:var H=-1;break;case 2:H=250;break;case 5:H=1073741823;break;case 4:H=1e4;break;default:H=5e3}return H=A+H,R={id:m++,callback:D,priorityLevel:R,startTime:A,expirationTime:H,sortIndex:-1},A>B?(R.sortIndex=A,t(f,R),r(a)===null&&R===r(f)&&(y?(h(w),w=-1):y=!0,V(g,A-B))):(R.sortIndex=H,t(a,R),b||S||(b=!0,W(x))),R},e.unstable_shouldYield=N,e.unstable_wrapCallback=function(R){var D=_;return function(){var A=_;_=D;try{return R.apply(this,arguments)}finally{_=A}}}})(Uh);Hh.exports=Uh;var gm=Hh.exports;/**
* @license React
* react-dom.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/var vm=M,dt=gm;function K(e){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+e,r=1;r<arguments.length;r++)t+="&args[]="+encodeURIComponent(arguments[r]);return"Minified React error #"+e+"; visit "+t+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}var zh=new Set,ri={};function $r(e,t){ps(e,t),ps(e+"Capture",t)}function ps(e,t){for(ri[e]=t,e=0;e<t.length;e++)zh.add(t[e])}var Qt=!(typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),fa=Object.prototype.hasOwnProperty,ym=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,Uc={},zc={};function Sm(e){return fa.call(zc,e)?!0:fa.call(Uc,e)?!1:ym.test(e)?zc[e]=!0:(Uc[e]=!0,!1)}function xm(e,t,r,s){if(r!==null&&r.type===0)return!1;switch(typeof t){case"function":case"symbol":return!0;case"boolean":return s?!1:r!==null?!r.acceptsBooleans:(e=e.toLowerCase().slice(0,5),e!=="data-"&&e!=="aria-");default:return!1}}function bm(e,t,r,s){if(t===null||typeof t>"u"||xm(e,t,r,s))return!0;if(s)return!1;if(r!==null)switch(r.type){case 3:return!t;case 4:return t===!1;case 5:return isNaN(t);case 6:return isNaN(t)||1>t}return!1}function et(e,t,r,s,i,o,c){this.acceptsBooleans=t===2||t===3||t===4,this.attributeName=s,this.attributeNamespace=i,this.mustUseProperty=r,this.propertyName=e,this.type=t,this.sanitizeURL=o,this.removeEmptyString=c}var Ie={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){Ie[e]=new et(e,0,!1,e,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var t=e[0];Ie[t]=new et(t,1,!1,e[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(e){Ie[e]=new et(e,2,!1,e.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){Ie[e]=new et(e,2,!1,e,null,!1,!1)});"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(e){Ie[e]=new et(e,3,!1,e.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(e){Ie[e]=new et(e,3,!0,e,null,!1,!1)});["capture","download"].forEach(function(e){Ie[e]=new et(e,4,!1,e,null,!1,!1)});["cols","rows","size","span"].forEach(function(e){Ie[e]=new et(e,6,!1,e,null,!1,!1)});["rowSpan","start"].forEach(function(e){Ie[e]=new et(e,5,!1,e.toLowerCase(),null,!1,!1)});var Al=/[\-:]([a-z])/g;function Ol(e){return e[1].toUpperCase()}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(e){var t=e.replace(Al,Ol);Ie[t]=new et(t,1,!1,e,null,!1,!1)});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(e){var t=e.replace(Al,Ol);Ie[t]=new et(t,1,!1,e,"http://www.w3.org/1999/xlink",!1,!1)});["xml:base","xml:lang","xml:space"].forEach(function(e){var t=e.replace(Al,Ol);Ie[t]=new et(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(e){Ie[e]=new et(e,1,!1,e.toLowerCase(),null,!1,!1)});Ie.xlinkHref=new et("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(e){Ie[e]=new et(e,1,!1,e.toLowerCase(),null,!0,!0)});function Nl(e,t,r,s){var i=Ie.hasOwnProperty(t)?Ie[t]:null;(i!==null?i.type!==0:s||!(2<t.length)||t[0]!=="o"&&t[0]!==" Line truncated
`+ko+e}var Ro=!1;function To(e,t){if(!e||Ro)return"";Ro=!0;var r=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{if(t)if(t=function(){throw Error()},Object.defineProperty(t.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(t,[])}catch(f){var s=f}Reflect.construct(e,[],t)}else{try{t.call()}catch(f){s=f}e.call(t.prototype)}else{try{throw Error()}catch(f){s=f}e()}}catch(f){if(f&&s&&typeof f.stack=="string"){for(var i=f.stack.split(`
`),o=s.stack.split(`
`),c=i.length-1,n=o.length-1;1<=c&&0<=n&&i[c]!==o[n];)n--;for(;1<=c&&0<=n;c--,n--)if(i[c]!==o[n]){if(c!==1||n!==1)do if(c--,n--,0>n||i[c]!==o[n]){var a=`
`+i[c].replace(" at new "," at ");return e.displayName&&a.includes("<anonymous>")&&(a=a.replace("<anonymous>",e.displayName)),a}while(1<=c&&0<=n);break}}}finally{Ro=!1,Error.prepareStackTrace=r}return(e=e?e.displayName||e.name:"")?zs(e):""}function wm(e){switch(e.tag){case 5:return zs(e.type);case 16:return zs("Lazy");case 13:return zs("Suspense");case 19:return zs("SuspenseList");case 0:case 2:case 15:return e=To(e.type,!1),e;case 11:return e=To(e.type.render,!1),e;case 1:return e=To(e.type,!0),e;default:return""}}function ga(e){if(e==null)return null;if(typeof e=="function")return e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case Jr:return"Fragment";case Gr:return"Portal";case pa:return"Profiler";case Pl:return"StrictMode";case ma:return"Suspense";case _a:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case Wh:return(e.displayName||"Context")+".Consumer";case $h:return(e._context.displayName||"Context")+".Provider";case Bl:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case jl:return t=e.displayName||null,t!==null?t:ga(e.type)||"Memo";case sr:t=e._payload,e=e._init;try{return ga(e(t))}catch{}}return null}function Cm(e){var t=e.type;switch(e.tag){case 24:return"Cache";case 9:return(t.displayName||"Context")+".Consumer";case 10:return(t._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return e=t.render,e=e.displayName||e.name||"",t.displayName||(e!==""?"ForwardRef("+e+")":"ForwardRef");case 7:return"Fragment";case 5:return t;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return ga(t);case 8:return t===Pl?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if(typeof t=="function")return t.displayName||t.name||null;if(typeof t=="string")return t}return null}function Sr(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function qh(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function Em(e){var t=qh(e)?"checked":"value",r=Object.getOwnPropertyDescriptor(e.constructor.prototype,t),s=""+e[t];if(!e.hasOwnProperty(t)&&typeof r<"u"&&typeof r.get=="function"&&typeof r.set=="function"){var i=r.get,o=r.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return i.call(this)},set:function(c){s=""+c,o.call(this,c)}}),Object.defineProperty(e,t,{enumerable:r.enumerable}),{getValue:function(){return s},setValue:function(c){s=""+c},stopTracking:function(){e._valueTracker=null,delete e[t]}}}}function Ii(e){e._valueTracker||(e._valueTracker=Em(e))}function Kh(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var r=t.getValue(),s="";return e&&(s=qh(e)?e.checked?"true":"false":e.value),e=s,e!==r?(t.setValue(e),!0):!1}function Rn(e){if(e=e||(typeof document<"u"?document:void 0),typeof e>"u")return null;try{return e.activeElement||e.body}catch{return e.body}}function va(e,t){var r=t.checked;return xe({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:r??e._wrapperState.initialChecked})}function Wc(e,t){var r=t.defaultValue==null?"":t.defaultValue,s=t.checked!=null?t.checked:t.defaultChecked;r=Sr(t.value!=null?t.value:r),e._wrapperState={initialChecked:s,initialValue:r,controlled:t.type==="checkbox"||t.type==="radio"?t.checked!=null:t.value!=null}}function Xh(e,t){t=t.checked,t!=null&&Nl(e,"checked",t,!1)}function ya(e,t){Xh(e,t);var r=Sr(t.value),s=t.type;if(r!=null)s==="number"?(r===0&&e.value===""||e.value!=r)&&(e.value=""+r):e.value!==""+r&&(e.value=""+r);else if(s==="submit"||s==="reset"){e.removeAttribute("value");return}t.hasOwnProperty("value")?Sa(e,t.type,r):t.hasOwnProperty("defaultValue")&&Sa(e,t.type,Sr(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(e.defaultChecked=!!t.defaultChecked)}function Vc(e,t,r){if(t.hasOwnProperty("value")||t.hasOwnProperty("defaultValue")){var s=t.type;if(!(s!=="submit"&&s!=="reset"||t.value!==void 0&&t.value!==null))return;t=""+e._wrapperState.initialValue,r||t===e.value||(e.value=t),e.defaultValue=t}r=e.name,r!==""&&(e.name=""),e.defaultChecked=!!e._wrapperState.initialChecked,r!==""&&(e.name=r)}function Sa(e,t,r){(t!=="number"||Rn(e.ownerDocument)!==e)&&(r==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+r&&(e.defaultValue=""+r))}var $s=Array.isArray;function as(e,t,r,s){if(e=e.options,t){t={};for(var i=0;i<r.length;i++)t["$"+r[i]]=!0;for(r=0;r<e.length;r++)i=t.hasOwnProperty("$"+e[r].value),e[r].selected!==i&&(e[r].selected=i),i&&s&&(e[r].defaultSelected=!0)}else{for(r=""+Sr(r),t=null,i=0;i<e.length;i++){if(e[i].value===r){e[i].selected=!0,s&&(e[i].defaultSelected=!0);return}t!==null||e[i].disabled||(t=e[i])}t!==null&&(t.selected=!0)}}function xa(e,t){if(t.dan Line truncated
`).replace(B_,"")}function qi(e,t,r){if(t=pu(t),pu(e)!==t&&r)throw Error(K(425))}function Bn(){}var Pa=null,Ba=null;function ja(e,t){return e==="textarea"||e==="noscript"||typeof t.children=="string"||typeof t.children=="number"||typeof t.dangerouslySetInnerHTML=="object"&&t.dangerouslySetInnerHTML!==null&&t.dangerouslySetInnerHTML.__html!=null}var Ma=typeof setTimeout=="function"?setTimeout:void 0,j_=typeof clearTimeout=="function"?clearTimeout:void 0,mu=typeof Promise=="function"?Promise:void 0,M_=typeof queueMicrotask=="function"?queueMicrotask:typeof mu<"u"?function(e){return mu.resolve(null).then(e).catch(I_)}:Ma;function I_(e){setTimeout(function(){throw e})}function Uo(e,t){var r=t,s=0;do{var i=r.nextSibling;if(e.removeChild(r),i&&i.nodeType===8)if(r=i.data,r==="/$"){if(s===0){e.removeChild(i),ai(t);return}s--}else r!=="$"&&r!=="$?"&&r!=="$!"||s++;r=i}while(r);ai(t)}function fr(e){for(;e!=null;e=e.nextSibling){var t=e.nodeType;if(t===1||t===3)break;if(t===8){if(t=e.data,t==="$"||t==="$!"||t==="$?")break;if(t==="/$")return null}}return e}function _u(e){e=e.previousSibling;for(var t=0;e;){if(e.nodeType===8){var r=e.data;if(r==="$"||r==="$!"||r==="$?"){if(t===0)return e;t--}else r==="/$"&&t++}e=e.previousSibling}return null}var Es=Math.random().toString(36).slice(2),Mt="__reactFiber$"+Es,di="__reactProps$"+Es,Yt="__reactContainer$"+Es,Ia="__reactEvents$"+Es,F_="__reactListeners$"+Es,H_="__reactHandles$"+Es;function Dr(e){var t=e[Mt];if(t)return t;for(var r=e.parentNode;r;){if(t=r[Yt]||r[Mt]){if(r=t.alternate,t.child!==null||r!==null&&r.child!==null)for(e=_u(e);e!==null;){if(r=e[Mt])return r;e=_u(e)}return t}e=r,r=e.parentNode}return null}function Ei(e){return e=e[Mt]||e[Yt],!e||e.tag!==5&&e.tag!==6&&e.tag!==13&&e.tag!==3?null:e}function es(e){if(e.tag===5||e.tag===6)return e.stateNode;throw Error(K(33))}function io(e){return e[di]||null}var Fa=[],ts=-1;function Cr(e){return{current:e}}function ge(e){0>ts||(e.current=Fa[ts],Fa[ts]=null,ts--)}function de(e,t){ts++,Fa[ts]=e.current,e.current=t}var xr={},Ge=Cr(xr),it=Cr(!1),Mr=xr;function ms(e,t){var r=e.type.contextTypes;if(!r)return xr;var s=e.stateNode;if(s&&s.__reactInternalMemoizedUnmaskedChildContext===t)return s.__reactInternalMemoizedMaskedChildContext;var i={},o;for(o in r)i[o]=t[o];return s&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=t,e.__reactInternalMemoizedMaskedChildContext=i),i}function nt(e){return e=e.childContextTypes,e!=null}function jn(){ge(it),ge(Ge)}function gu(e,t,r){if(Ge.current!==xr)throw Error(K(168));de(Ge,t),de(it,r)}function jd(e,t,r){var s=e.stateNode;if(t=t.childContextTypes,typeof s.getChildContext!="function")return r;s=s.getChildContext();for(var i in s)if(!(i in t))throw Error(K(108,Cm(e)||"Unknown",i));return xe({},r,s)}function Mn(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||xr,Mr=Ge.current,de(Ge,e),de(it,it.current),!0}function vu(e,t,r){var s=e.stateNode;if(!s)throw Error(K(169));r?(e=jd(e,t,Mr),s.__reactInternalMemoizedMergedChildContext=e,ge(it),ge(Ge),de(Ge,e)):ge(it),de(it,r)}var Vt=null,no=!1,zo=!1;function Md(e){Vt===null?Vt=[e]:Vt.push(e)}function U_(e){no=!0,Md(e)}function Er(){if(!zo&&Vt!==null){zo=!0;var e=0,t=ue;try{var r=Vt;for(ue=1;e<r.length;e++){var s=r[e];do s=s(!0);while(s!==null)}Vt=null,no=!1}catch(i){throw Vt!==null&&(Vt=Vt.slice(e+1)),ld(Il,Er),i}finally{ue=t,zo=!1}}return null}var rs=[],ss=0,In=null,Fn=0,_t=[],gt=0,Ir=null,Kt=1,Xt="";function Tr(e,t){rs[ss++]=Fn,rs[ss++]=In,In=e,Fn=t}function Id(e,t,r){_t[gt++]=Kt,_t[gt++]=Xt,_t[gt++]=Ir,Ir=e;var s=Kt;e=Xt;var i=32-Dt(s)-1;s&=~(1<<i),r+=1;var o=32-Dt(t)+i;if(30<o){var c=i-i%5;o=(s&(1<<c)-1).toString(32),s>>=c,i-=c,Kt=1<<32-Dt(t)+i|r<<i|s,Xt=o+e}else Kt=1<<o|r<<i|s,Xt=e}function Kl(e){e.return!==null&&(Tr(e,1),Id(e,1,0))}function Xl(e){for(;e===In;)In=rs[--ss],rs[ss]=null,Fn=rs[--ss],rs[ss]=null;for(;e===Ir;)Ir=_t[--gt],_t[gt]=null,Xt=_t[--gt],_t[gt]=null,Kt=_t[--gt],_t[gt]=null}var ht=null,ut=null,ve=!1,Lt=null;function Fd(e,t){var r=yt(5,null,null,0);r.elementType="DELETED",r.stateNode=t,r.return=e,t=e.deletions,t===null?(e.deletions=[r],e.flags|=16):t.push(r)}function yu(e,t){switch(e.tag){case 5:var r=e.type;return t=t.nodeType!==1||r.toLowerCase()!==t.nodeName.toLowerCase()?null:t,t!==null?(e.stateNode=t,ht=e,ut=fr(t.firstChild),!0):!1;case 6:return t=e.pendingProps===""||t.nodeType!==3?null:t,t!==null?(e.stateNode=t,ht=e,ut=null,!0):!1;case 13:return t=t.nodeType!==8?null:t,t!==null?(r=Ir!==null?{id:Kt,overflow:Xt}:null,e.memoizedState={dehydrated:t,treeContext:r,retryLane:1073741824},r=yt(18,null,null,0),r.stateNode=t,r.return=e,e.child=r,ht=e,ut=null,!0):!1;default:return!1}}function Ha(e){return(e.mode&1)!==0&&(e.flags&128)===0}function Ua(e){if(ve){var t=ut;if(t){var r=t;if(!yu(e,t)){if(Ha(e))throw Error(K(418));t=fr(r.nextSibling);var s=ht;t&&yu(e,t)?Fd(s,r):(e.flags=e.flags&-4097|2,ve=!1,ht=e)}}else{if(Ha(e))throw Error(K(418));e.flags=e.flags&-4097|2,ve=!1,ht=e}}}function Su(e){for(e=e Line truncated
Error generating stack: `+o.message+`
`+o.stack}return{value:e,source:t,stack:i,digest:null}}function Ko(e,t,r){return{value:e,source:null,stack:r??null,digest:t??null}}function Va(e,t){try{console.error(t.value)}catch(r){setTimeout(function(){throw r})}}var J_=typeof WeakMap=="function"?WeakMap:Map;function ff(e,t,r){r=Jt(-1,r),r.tag=3,r.payload={element:null};var s=t.value;return r.callback=function(){Kn||(Kn=!0,tl=s),Va(e,t)},r}function pf(e,t,r){r=Jt(-1,r),r.tag=3;var s=e.type.getDerivedStateFromError;if(typeof s=="function"){var i=t.value;r.payload=function(){return s(i)},r.callback=function(){Va(e,t)}}var o=e.stateNode;return o!==null&&typeof o.componentDidCatch=="function"&&(r.callback=function(){Va(e,t),typeof s!="function"&&(mr===null?mr=new Set([this]):mr.add(this));var c=t.stack;this.componentDidCatch(t.value,{componentStack:c!==null?c:""})}),r}function Tu(e,t,r){var s=e.pingCache;if(s===null){s=e.pingCache=new J_;var i=new Set;s.set(t,i)}else i=s.get(t),i===void 0&&(i=new Set,s.set(t,i));i.has(r)||(i.add(r),e=ug.bind(null,e,t,r),t.then(e,e))}function Lu(e){do{var t;if((t=e.tag===13)&&(t=e.memoizedState,t=t!==null?t.dehydrated!==null:!0),t)return e;e=e.return}while(e!==null);return null}function Du(e,t,r,s,i){return e.mode&1?(e.flags|=65536,e.lanes=i,e):(e===t?e.flags|=65536:(e.flags|=128,r.flags|=131072,r.flags&=-52805,r.tag===1&&(r.alternate===null?r.tag=17:(t=Jt(-1,1),t.tag=2,pr(r,t,1))),r.lanes|=1),e)}var Q_=tr.ReactCurrentOwner,st=!1;function Je(e,t,r,s){t.child=e===null?zd(t,null,r,s):gs(t,e.child,r,s)}function Au(e,t,r,s,i){r=r.render;var o=t.ref;return hs(t,i),s=nc(e,t,r,s,o,i),r=oc(),e!==null&&!st?(t.updateQueue=e.updateQueue,t.flags&=-2053,e.lanes&=~i,er(e,t,i)):(ve&&r&&Kl(t),t.flags|=1,Je(e,t,s,i),t.child)}function Ou(e,t,r,s,i){if(e===null){var o=r.type;return typeof o=="function"&&!_c(o)&&o.defaultProps===void 0&&r.compare===null&&r.defaultProps===void 0?(t.tag=15,t.type=o,mf(e,t,o,s,i)):(e=yn(r.type,null,s,t,t.mode,i),e.ref=t.ref,e.return=t,t.child=e)}if(o=e.child,!(e.lanes&i)){var c=o.memoizedProps;if(r=r.compare,r=r!==null?r:ci,r(c,s)&&e.ref===t.ref)return er(e,t,i)}return t.flags|=1,e=gr(o,s),e.ref=t.ref,e.return=t,t.child=e}function mf(e,t,r,s,i){if(e!==null){var o=e.memoizedProps;if(ci(o,s)&&e.ref===t.ref)if(st=!1,t.pendingProps=s=o,(e.lanes&i)!==0)e.flags&131072&&(st=!0);else return t.lanes=e.lanes,er(e,t,i)}return qa(e,t,r,s,i)}function _f(e,t,r){var s=t.pendingProps,i=s.children,o=e!==null?e.memoizedState:null;if(s.mode==="hidden")if(!(t.mode&1))t.memoizedState={baseLanes:0,cachePool:null,transitions:null},de(os,lt),lt|=r;else{if(!(r&1073741824))return e=o!==null?o.baseLanes|r:r,t.lanes=t.childLanes=1073741824,t.memoizedState={baseLanes:e,cachePool:null,transitions:null},t.updateQueue=null,de(os,lt),lt|=e,null;t.memoizedState={baseLanes:0,cachePool:null,transitions:null},s=o!==null?o.baseLanes:r,de(os,lt),lt|=s}else o!==null?(s=o.baseLanes|r,t.memoizedState=null):s=r,de(os,lt),lt|=s;return Je(e,t,i,r),t.child}function gf(e,t){var r=t.ref;(e===null&&r!==null||e!==null&&e.ref!==r)&&(t.flags|=512,t.flags|=2097152)}function qa(e,t,r,s,i){var o=nt(r)?Mr:Ge.current;return o=ms(t,o),hs(t,i),r=nc(e,t,r,s,o,i),s=oc(),e!==null&&!st?(t.updateQueue=e.updateQueue,t.flags&=-2053,e.lanes&=~i,er(e,t,i)):(ve&&s&&Kl(t),t.flags|=1,Je(e,t,r,i),t.child)}function Nu(e,t,r,s,i){if(nt(r)){var o=!0;Mn(t)}else o=!1;if(hs(t,i),t.stateNode===null)_n(e,t),df(t,r,s),Wa(t,r,s,i),s=!0;else if(e===null){var c=t.stateNode,n=t.memoizedProps;c.props=n;var a=c.context,f=r.contextType;typeof f=="object"&&f!==null?f=xt(f):(f=nt(r)?Mr:Ge.current,f=ms(t,f));var m=r.getDerivedStateFromProps,p=typeof m=="function"||typeof c.getSnapshotBeforeUpdate=="function";p||typeof c.UNSAFE_componentWillReceiveProps!="function"&&typeof c.componentWillReceiveProps!="function"||(n!==s||a!==f)&&Ru(t,c,s,f),ir=!1;var _=t.memoizedState;c.state=_,zn(t,s,c,i),a=t.memoizedState,n!==s||_!==a||it.current||ir?(typeof m=="function"&&($a(t,r,m,s),a=t.memoizedState),(n=ir||ku(t,r,n,s,_,a,f))?(p||typeof c.UNSAFE_componentWillMount!="function"&&typeof c.componentWillMount!="function"||(typeof c.componentWillMount=="function"&&c.componentWillMount(),typeof c.UNSAFE_componentWillMount=="function"&&c.UNSAFE_componentWillMount()),typeof c.componentDidMount=="function"&&(t.flags|=4194308)):(typeof c.componentDidMount=="function"&&(t.flags|=4194308),t.memoizedProps=s,t.memoizedState=a),c.props=s,c.state=a,c.context=f,s=n):(typeof c.componentDidMount=="function"&&(t.flags|=4194308),s=!1)}else{c=t.stateNode,Wd(e,t),n=t.memoizedProps,f=t.type===t.elementType?n:kt(t.type,n),c.props=f,p=t.pendingProps,_=c.context,a=r.contextType,typeof a=="object"&&a!==null?a=xt(a):(a=nt(r)?Mr:Ge.current,a=ms(t,a));var S=r.getDerivedStateFromProps;(m=typeof S=="function"||typeof c.getSnapshotBeforeUpdate=="function")||typeof c.UNSAFE_componentWillReceiveProps!="function"&&typeof c.componentWillReceiveProps!="function"||(n!==p||_!==a)&&Ru(t,c,s,a),ir=!1,_=t.memoizedState,c.state=_,zn(t,s,c,i);var b=t.memoizedS Line truncated
* @remix-run/router v1.23.2
*
* Copyright (c) Remix Software Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE.md file in the root directory of this source tree.
*
* @license MIT
*/function yi(){return yi=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&(e[s]=r[s])}return e},yi.apply(this,arguments)}var cr;(function(e){e.Pop="POP",e.Push="PUSH",e.Replace="REPLACE"})(cr||(cr={}));const Ku="popstate";function bg(e){e===void 0&&(e={});function t(s,i){let{pathname:o,search:c,hash:n}=s.location;return nl("",{pathname:o,search:c,hash:n},i.state&&i.state.usr||null,i.state&&i.state.key||"default")}function r(s,i){return typeof i=="string"?i:Qn(i)}return Cg(t,r,null,e)}function Re(e,t){if(e===!1||e===null||typeof e>"u")throw new Error(t)}function xc(e,t){if(!e){typeof console<"u"&&console.warn(t);try{throw new Error(t)}catch{}}}function wg(){return Math.random().toString(36).substr(2,8)}function Xu(e,t){return{usr:e.state,key:e.key,idx:t}}function nl(e,t,r,s){return r===void 0&&(r=null),yi({pathname:typeof e=="string"?e:e.pathname,search:"",hash:""},typeof t=="string"?ks(t):t,{state:r,key:t&&t.key||s||wg()})}function Qn(e){let{pathname:t="/",search:r="",hash:s=""}=e;return r&&r!=="?"&&(t+=r.charAt(0)==="?"?r:"?"+r),s&&s!=="#"&&(t+=s.charAt(0)==="#"?s:"#"+s),t}function ks(e){let t={};if(e){let r=e.indexOf("#");r>=0&&(t.hash=e.substr(r),e=e.substr(0,r));let s=e.indexOf("?");s>=0&&(t.search=e.substr(s),e=e.substr(0,s)),e&&(t.pathname=e)}return t}function Cg(e,t,r,s){s===void 0&&(s={});let{window:i=document.defaultView,v5Compat:o=!1}=s,c=i.history,n=cr.Pop,a=null,f=m();f==null&&(f=0,c.replaceState(yi({},c.state,{idx:f}),""));function m(){return(c.state||{idx:null}).idx}function p(){n=cr.Pop;let u=m(),h=u==null?null:u-f;f=u,a&&a({action:n,location:y.location,delta:h})}function _(u,h){n=cr.Push;let l=nl(y.location,u,h);f=m()+1;let d=Xu(l,f),g=y.createHref(l);try{c.pushState(d,"",g)}catch(x){if(x instanceof DOMException&&x.name==="DataCloneError")throw x;i.location.assign(g)}o&&a&&a({action:n,location:y.location,delta:1})}function S(u,h){n=cr.Replace;let l=nl(y.location,u,h);f=m();let d=Xu(l,f),g=y.createHref(l);c.replaceState(d,"",g),o&&a&&a({action:n,location:y.location,delta:0})}function b(u){let h=i.location.origin!=="null"?i.location.origin:i.location.href,l=typeof u=="string"?u:Qn(u);return l=l.replace(/ $/,"%20"),Re(h,"No window.location.(origin|href) available to create URL for href: "+l),new URL(l,h)}let y={get action(){return n},get location(){return e(i,c)},listen(u){if(a)throw new Error("A history only accepts one active listener");return i.addEventListener(Ku,p),a=u,()=>{i.removeEventListener(Ku,p),a=null}},createHref(u){return t(i,u)},createURL:b,encodeLocation(u){let h=b(u);return{pathname:h.pathname,search:h.search,hash:h.hash}},push:_,replace:S,go(u){return c.go(u)}};return y}var Gu;(function(e){e.data="data",e.deferred="deferred",e.redirect="redirect",e.error="error"})(Gu||(Gu={}));function Eg(e,t,r){return r===void 0&&(r="/"),kg(e,t,r)}function kg(e,t,r,s){let i=typeof t=="string"?ks(t):t,o=bc(i.pathname||"/",r);if(o==null)return null;let c=Uf(e);Rg(c);let n=null;for(let a=0;n==null&&a<c.length;++a){let f=Fg(o);n=jg(c[a],f)}return n}function Uf(e,t,r,s){t===void 0&&(t=[]),r===void 0&&(r=[]),s===void 0&&(s="");let i=(o,c,n)=>{let a={relativePath:n===void 0?o.path||"":n,caseSensitive:o.caseSensitive===!0,childrenIndex:c,route:o};a.relativePath.startsWith("/")&&(Re(a.relativePath.startsWith(s),'Absolute route path "'+a.relativePath+'" nested under path '+('"'+s+'" is not valid. An absolute child route path ')+"must start with the combined path of all its parent routes."),a.relativePath=a.relativePath.slice(s.length));let f=vr([s,a.relativePath]),m=r.concat(a);o.children&&o.children.length>0&&(Re(o.index!==!0,"Index routes must not have child routes. Please remove "+('all child routes from route path "'+f+'".')),Uf(o.children,t,m,f)),!(o.path==null&&!o.index)&&t.push({path:f,score:Pg(f,o.index),routesMeta:m})};return e.forEach((o,c)=>{var n;if(o.path===""||!((n=o.path)!=null&&n.includes("?")))i(o,c);else for(let a of zf(o.path))i(o,c,a)}),t}function zf(e){let t=e.split("/");if(t.length===0)return[];let[r,...s]=t,i=r.endsWith("?"),o=r.replace(/\?$/,"");if(s.length===0)return i?[o,""]:[o];let c=zf(s.join("/")),n=[];return n.push(...c.map(a=>a===""?o:[o,a].join("/"))),i&&n.push(...c),n.map(a=>e.startsWith("/")&&a===""?"/":a)}function Rg(e){e.sort((t,r)=>t.score!==r.score?r.score-t.score:Bg(t.routesMeta.map(s=>s.childrenIndex),r.routesMeta.map(s=>s.childrenIndex)))}const Tg=/^:[\w-]+$/,Lg=3,Dg=2,Ag=1,Og=10,Ng=-2,Ju=e=>e==="*";function Pg(e,t){let r=e.split("/"),s=r.length;return r.some(Ju)&&(s+=Ng),t&&(s+=Dg),r.filter(i=>!Ju(i)).reduce((i,o)=>i+(Tg.test(o)?Lg:o===""?Ag:Og),s)}function Bg(e,t){return e.length===t.length&&e.slice(0,-1).every((s,i)=>s===t[i])?e[e.length-1]-t[t.length-1]:0}function jg(e,t,r){let{routesMeta:s}=e,i={},o="/",c=[];for(let n=0;n<s.length;++n){let a=s[n],f=n===s.length-1,m=o==="/"?t:t.slice(o.length)||"/",p=Mg({path:a.relativePath,caseSensitive:a.caseSeLine truncated
* React Router v6.30.3
*
* Copyright (c) Remix Software Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE.md file in the root directory of this source tree.
*
* @license MIT
*/function Si(){return Si=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&(e[s]=r[s])}return e},Si.apply(this,arguments)}const wc=M.createContext(null),Gg=M.createContext(null),Vr=M.createContext(null),_o=M.createContext(null),kr=M.createContext({outlet:null,matches:[],isDataRoute:!1}),qf=M.createContext(null);function Jg(e,t){let{relative:r}=t===void 0?{}:t;Ri()||Re(!1);let{basename:s,navigator:i}=M.useContext(Vr),{hash:o,pathname:c,search:n}=Xf(e,{relative:r}),a=c;return s!=="/"&&(a=c==="/"?s:vr([s,c])),i.createHref({pathname:a,search:n,hash:o})}function Ri(){return M.useContext(_o)!=null}function Ti(){return Ri()||Re(!1),M.useContext(_o).location}function Kf(e){M.useContext(Vr).static||M.useLayoutEffect(e)}function Cc(){let{isDataRoute:e}=M.useContext(kr);return e?uv():Qg()}function Qg(){Ri()||Re(!1);let e=M.useContext(wc),{basename:t,future:r,navigator:s}=M.useContext(Vr),{matches:i}=M.useContext(kr),{pathname:o}=Ti(),c=JSON.stringify($f(i,r.v7_relativeSplatPath)),n=M.useRef(!1);return Kf(()=>{n.current=!0}),M.useCallback(function(f,m){if(m===void 0&&(m={}),!n.current)return;if(typeof f=="number"){s.go(f);return}let p=Wf(f,JSON.parse(c),o,m.relative==="path");e==null&&t!=="/"&&(p.pathname=p.pathname==="/"?t:vr([t,p.pathname])),(m.replace?s.replace:s.push)(p,m.state,m)},[t,s,c,o,e])}function Yg(){let{matches:e}=M.useContext(kr),t=e[e.length-1];return t?t.params:{}}function Xf(e,t){let{relative:r}=t===void 0?{}:t,{future:s}=M.useContext(Vr),{matches:i}=M.useContext(kr),{pathname:o}=Ti(),c=JSON.stringify($f(i,s.v7_relativeSplatPath));return M.useMemo(()=>Wf(e,JSON.parse(c),o,r==="path"),[e,c,o,r])}function Zg(e,t){return ev(e,t)}function ev(e,t,r,s){Ri()||Re(!1);let{navigator:i}=M.useContext(Vr),{matches:o}=M.useContext(kr),c=o[o.length-1],n=c?c.params:{};c&&c.pathname;let a=c?c.pathnameBase:"/";c&&c.route;let f=Ti(),m;if(t){var p;let u=typeof t=="string"?ks(t):t;a==="/"||(p=u.pathname)!=null&&p.startsWith(a)||Re(!1),m=u}else m=f;let _=m.pathname||"/",S=_;if(a!=="/"){let u=a.replace(/^\//,"").split("/");S="/"+_.replace(/^\//,"").split("/").slice(u.length).join("/")}let b=Eg(e,{pathname:S}),y=nv(b&&b.map(u=>Object.assign({},u,{params:Object.assign({},n,u.params),pathname:vr([a,i.encodeLocation?i.encodeLocation(u.pathname).pathname:u.pathname]),pathnameBase:u.pathnameBase==="/"?a:vr([a,i.encodeLocation?i.encodeLocation(u.pathnameBase).pathname:u.pathnameBase])})),o,r,s);return t&&y?M.createElement(_o.Provider,{value:{location:Si({pathname:"/",search:"",hash:"",state:null,key:"default"},m),navigationType:cr.Pop}},y):y}function tv(){let e=cv(),t=Kg(e)?e.status+" "+e.statusText:e instanceof Error?e.message:JSON.stringify(e),r=e instanceof Error?e.stack:null,i={padding:"0.5rem",backgroundColor:"rgba(200,200,200, 0.5)"};return M.createElement(M.Fragment,null,M.createElement("h2",null,"Unexpected Application Error!"),M.createElement("h3",{style:{fontStyle:"italic"}},t),r?M.createElement("pre",{style:i},r):null,null)}const rv=M.createElement(tv,null);class sv extends M.Component{constructor(t){super(t),this.state={location:t.location,revalidation:t.revalidation,error:t.error}}static getDerivedStateFromError(t){return{error:t}}static getDerivedStateFromProps(t,r){return r.location!==t.location||r.revalidation!=="idle"&&t.revalidation==="idle"?{error:t.error,location:t.location,revalidation:t.revalidation}:{error:t.error!==void 0?t.error:r.error,location:r.location,revalidation:t.revalidation||r.revalidation}}componentDidCatch(t,r){console.error("React Router caught the following error during render",t,r)}render(){return this.state.error!==void 0?M.createElement(kr.Provider,{value:this.props.routeContext},M.createElement(qf.Provider,{value:this.state.error,children:this.props.component})):this.props.children}}function iv(e){let{routeContext:t,match:r,children:s}=e,i=M.useContext(wc);return i&&i.static&&i.staticContext&&(r.route.errorElement||r.route.ErrorBoundary)&&(i.staticContext._deepestRenderedBoundaryId=r.route.id),M.createElement(kr.Provider,{value:t},s)}function nv(e,t,r,s){var i;if(t===void 0&&(t=[]),r===void 0&&(r=null),s===void 0&&(s=null),e==null){var o;if(!r)return null;if(r.errors)e=r.matches;else if((o=s)!=null&&o.v7_partialHydration&&t.length===0&&!r.initialized&&r.matches.length>0)e=r.matches;else return null}let c=e,n=(i=r)==null?void 0:i.errors;if(n!=null){let m=c.findIndex(p=>p.route.id&&(n==null?void 0:n[p.route.id])!==void 0);m>=0||Re(!1),c=c.slice(0,Math.min(c.length,m+1))}let a=!1,f=-1;if(r&&s&&s.v7_partialHydration)for(let m=0;m<c.length;m++){let p=c[m];if((p.route.HydrateFallback||p.route.hydrateFallbackElement)&&(f=m),p.route.id){let{loaderData:_,errors:S}=r,b=p.route.loader&&_[p.route.id]===void 0&&(!S||S[p.route.id]===void 0);if(p.route.lazy||b){a=!0,f>=0?c=c.slice(0,f+1):c=[c[0]];break}}}return c.reduceRight((m,p,_)=>{let S,b=!1,y=null,u=null;r&&(S=n&&p.route.id?n[p.route.id]:Line truncated
* React Router DOM v6.30.3
*
* Copyright (c) Remix Software Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE.md file in the root directory of this source tree.
*
* @license MIT
*/function al(){return al=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&(e[s]=r[s])}return e},al.apply(this,arguments)}function mv(e,t){if(e==null)return{};var r={},s=Object.keys(e),i,o;for(o=0;o<s.length;o++)i=s[o],!(t.indexOf(i)>=0)&&(r[i]=e[i]);return r}function _v(e){return!!(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)}function gv(e,t){return e.button===0&&(!t||t==="_self")&&!_v(e)}const vv=["onClick","relative","reloadDocument","replace","state","target","to","preventScrollReset","viewTransition"],yv="6";try{window.__reactRouterVersion=yv}catch{}const Sv="startTransition",Zu=um[Sv];function xv(e){let{basename:t,children:r,future:s,window:i}=e,o=M.useRef();o.current==null&&(o.current=bg({window:i,v5Compat:!0}));let c=o.current,[n,a]=M.useState({action:c.action,location:c.location}),{v7_startTransition:f}=s||{},m=M.useCallback(p=>{f&&Zu?Zu(()=>a(p)):a(p)},[a,f]);return M.useLayoutEffect(()=>c.listen(m),[c,m]),M.useEffect(()=>dv(s),[s]),M.createElement(fv,{basename:t,children:r,location:n.location,navigationType:n.action,navigator:c,future:s})}const bv=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",wv=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,Cv=M.forwardRef(function(t,r){let{onClick:s,relative:i,reloadDocument:o,replace:c,state:n,target:a,to:f,preventScrollReset:m,viewTransition:p}=t,_=mv(t,vv),{basename:S}=M.useContext(Vr),b,y=!1;if(typeof f=="string"&&wv.test(f)&&(b=f,bv))try{let d=new URL(window.location.href),g=f.startsWith("//")?new URL(d.protocol+f):new URL(f),x=bc(g.pathname,S);g.origin===d.origin&&x!=null?f=x+g.search+g.hash:y=!0}catch{}let u=Jg(f,{relative:i}),h=Ev(f,{replace:c,state:n,target:a,preventScrollReset:m,relative:i,viewTransition:p});function l(d){s&&s(d),d.defaultPrevented||h(d)}return M.createElement("a",al({},_,{href:b||u,onClick:y||o?s:l,ref:r,target:a}))});var eh;(function(e){e.UseScrollRestoration="useScrollRestoration",e.UseSubmit="useSubmit",e.UseSubmitFetcher="useSubmitFetcher",e.UseFetcher="useFetcher",e.useViewTransitionState="useViewTransitionState"})(eh||(eh={}));var th;(function(e){e.UseFetcher="useFetcher",e.UseFetchers="useFetchers",e.UseScrollRestoration="useScrollRestoration"})(th||(th={}));function Ev(e,t){let{target:r,replace:s,state:i,preventScrollReset:o,relative:c,viewTransition:n}=t===void 0?{}:t,a=Cc(),f=Ti(),m=Xf(e,{relative:c});return M.useCallback(p=>{if(gv(p,r)){p.preventDefault();let _=s!==void 0?s:Qn(f)===Qn(m);a(e,{replace:_,state:i,preventScrollReset:o,relative:c,viewTransition:n})}},[f,a,m,s,i,r,e,o,c,n])}const kv={user:null,theme:localStorage.getItem("dune-theme")||"emperor",connectionStatus:{database:!0,ssh:!0,bgd:!0,rmq:!0},toasts:[]};let Rv=0;function Tv(e,t){switch(t.type){case"SET_USER":return{...e,user:t.payload};case"SET_THEME":return{...e,theme:t.payload};case"SET_CONNECTION":return{...e,connectionStatus:{...e.connectionStatus,...t.payload}};case"ADD_TOAST":return{...e,toasts:[...e.toasts.slice(-2),{...t.payload,id:++Rv}]};case"REMOVE_TOAST":return{...e,toasts:e.toasts.filter(r=>r.id!==t.payload)};default:return e}}const Yf=M.createContext(null);function Lv({children:e}){const[t,r]=M.useReducer(Tv,kv);return M.useEffect(()=>{document.documentElement.dataset.theme=t.theme,localStorage.setItem("dune-theme",t.theme)},[t.theme]),v.jsx(Yf.Provider,{value:{state:t,dispatch:r},children:e})}function Fe(){const e=M.useContext(Yf);if(!e)throw new Error("useApp must be used within AppProvider");return e}function Dv(){const{dispatch:e}=Fe(),t=M.useRef(null);M.useEffect(()=>{const r=new EventSource("/api/events/stream");return t.current=r,r.onopen=()=>{console.log("[SSE] Connected")},r.addEventListener("battlegroup_update",s=>{try{const i=JSON.parse(s.data);console.log("[SSE] battlegroup_update",i)}catch{}}),r.addEventListener("rmq_health",s=>{try{const i=JSON.parse(s.data);console.log("[SSE] rmq_health",i)}catch{}}),r.addEventListener("connection_status",s=>{try{const i=JSON.parse(s.data);e({type:"SET_CONNECTION",payload:i})}catch{}}),r.addEventListener("chat_message",s=>{try{const i=JSON.parse(s.data);console.log("[SSE] chat_message",i)}catch{}}),r.onerror=()=>{console.warn("[SSE] Connection error")},()=>{r.close()}},[e])}const Av=[{key:"default",label:"Classic Dune"},{key:"atreides",label:"House Atreides"},{key:"harkonnen",label:"House Harkonnen"},{key:"fremen",label:"Fremen"},{key:"bene-gesserit",label:"Bene Gesserit"},{key:"spacing-guild",label:"Spacing Guild"},{key:"emperor",label:"Emperor"},{key:"corrino",label:"House Corrino"},{key:"mentat",label:"Mentat"},{key:"sardaukar",label:"Sardaukar"},{key:"tleilax",label:"Bene Tleilax"},{key:"ordos",label:"House Ordos"},{key:"ix",label:"Ix"},{key:"choam",label:"CHOAM"}];function Ov(){const{state:e,dispatch:t}=Fe(),[r,s]=M.useState(!1),i=M.useRef(null);return M.useEffect(()=>{function o(c){i.current&&!i.current.contains(c.target)&&s(!1)}return document.addEventLiLine truncated
`).forEach(function(c){i=c.indexOf(":"),r=c.substring(0,i).trim().toLowerCase(),s=c.substring(i+1).trim(),!(!r||t[r]&&ky[r])&&(r==="set-cookie"?t[r]?t[r].push(s):t[r]=[s]:t[r]=t[r]?t[r]+", "+s:s)}),t};function Ty(e){let t=0,r=e.length;for(;t<r;){const s=e.charCodeAt(t);if(s!==9&&s!==32)break;t+=1}for(;r>t;){const s=e.charCodeAt(r-1);if(s!==9&&s!==32)break;r-=1}return t===0&&r===e.length?e:e.slice(t,r)}const Ly=new RegExp("[\\u0000-\\u0008\\u000a-\\u001f\\u007f]+","g"),Dy=new RegExp("[^\\u0009\\u0020-\\u007e\\u0080-\\u00ff]+","g");function Ec(e,t){return I.isArray(e)?e.map(r=>Ec(r,t)):Ty(String(e).replace(t,""))}const Ay=e=>Ec(e,Ly),Oy=e=>Ec(e,Dy);function ap(e){const t=Object.create(null);return I.forEach(e.toJSON(),(r,s)=>{t[s]=Oy(r)}),t}const ih=Symbol("internals");function Is(e){return e&&String(e).trim().toLowerCase()}function xn(e){return e===!1||e==null?e:I.isArray(e)?e.map(xn):Ay(String(e))}function Ny(e){const t=Object.create(null),r=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let s;for(;s=r.exec(e);)t[s[1]]=s[2];return t}const Py=e=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim());function Yo(e,t,r,s,i){if(I.isFunction(s))return s.call(this,t,r);if(i&&(t=r),!!I.isString(t)){if(I.isString(s))return t.indexOf(s)!==-1;if(I.isRegExp(s))return s.test(t)}}function By(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(t,r,s)=>r.toUpperCase()+s)}function jy(e,t){const r=I.toCamelCase(" "+t);["get","set","has"].forEach(s=>{Object.defineProperty(e,s+r,{__proto__:null,value:function(i,o,c){return this[s].call(this,t,i,o,c)},configurable:!0})})}let Ye=class{constructor(t){t&&this.set(t)}set(t,r,s){const i=this;function o(n,a,f){const m=Is(a);if(!m)throw new Error("header name must be a non-empty string");const p=I.findKey(i,m);(!p||i[p]===void 0||f===!0||f===void 0&&i[p]!==!1)&&(i[p||a]=xn(n))}const c=(n,a)=>I.forEach(n,(f,m)=>o(f,m,a));if(I.isPlainObject(t)||t instanceof this.constructor)c(t,r);else if(I.isString(t)&&(t=t.trim())&&!Py(t))c(Ry(t),r);else if(I.isObject(t)&&I.isIterable(t)){let n={},a,f;for(const m of t){if(!I.isArray(m))throw TypeError("Object iterator must return a key-value pair");n[f=m[0]]=(a=n[f])?I.isArray(a)?[...a,m[1]]:[a,m[1]]:m[1]}c(n,r)}else t!=null&&o(r,t,s);return this}get(t,r){if(t=Is(t),t){const s=I.findKey(this,t);if(s){const i=this[s];if(!r)return i;if(r===!0)return Ny(i);if(I.isFunction(r))return r.call(this,i,s);if(I.isRegExp(r))return r.exec(i);throw new TypeError("parser must be boolean|regexp|function")}}}has(t,r){if(t=Is(t),t){const s=I.findKey(this,t);return!!(s&&this[s]!==void 0&&(!r||Yo(this,this[s],s,r)))}return!1}delete(t,r){const s=this;let i=!1;function o(c){if(c=Is(c),c){const n=I.findKey(s,c);n&&(!r||Yo(s,s[n],n,r))&&(delete s[n],i=!0)}}return I.isArray(t)?t.forEach(o):o(t),i}clear(t){const r=Object.keys(this);let s=r.length,i=!1;for(;s--;){const o=r[s];(!t||Yo(this,this[o],o,t,!0))&&(delete this[o],i=!0)}return i}normalize(t){const r=this,s={};return I.forEach(this,(i,o)=>{const c=I.findKey(s,o);if(c){r[c]=xn(i),delete r[o];return}const n=t?By(o):String(o).trim();n!==o&&delete r[o],r[n]=xn(i),s[n]=!0}),this}concat(...t){return this.constructor.concat(this,...t)}toJSON(t){const r=Object.create(null);return I.forEach(this,(s,i)=>{s!=null&&s!==!1&&(r[i]=t&&I.isArray(s)?s.join(", "):s)}),r}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([t,r])=>t+": "+r).join(`
`)}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(t){return t instanceof this?t:new this(t)}static concat(t,...r){const s=new this(t);return r.forEach(i=>s.set(i)),s}static accessor(t){const s=(this[ih]=this[ih]={accessors:{}}).accessors,i=this.prototype;function o(c){const n=Is(c);s[n]||(jy(i,c),s[n]=!0)}return I.isArray(t)?t.forEach(o):o(t),this}};Ye.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);I.reduceDescriptors(Ye.prototype,({value:e},t)=>{let r=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(s){this[r]=s}}});I.freezeMethods(Ye);const My="[REDACTED ****]";function Iy(e){if(I.hasOwnProp(e,"toJSON"))return!0;let t=Object.getPrototypeOf(e);for(;t&&t!==Object.prototype;){if(I.hasOwnProp(t,"toJSON"))return!0;t=Object.getPrototypeOf(t)}return!1}function Fy(e,t){const r=new Set(t.map(o=>String(o).toLowerCase())),s=[],i=o=>{if(o===null||typeof o!="object"||I.isBuffer(o))return o;if(s.indexOf(o)!==-1)return;o instanceof Ye&&(o=o.toJSON()),s.push(o);let c;if(I.isArray(o))c=[],o.forEach((n,a)=>{const f=i(n);I.isUndefined(f)||(c[a]=f)});else{if(!I.isPlainObject(o)&&Iy(o))return s.pop(),o;c=Object.create(null);for(const[n,a]of Object.entries(o)){const f=r.has(n.toLowerCase())?My:i(a);I.isUndefined(f)||(c[n]=f)}}return s.pop(),c};return i(e)}let Z=class lp extends Error{static from(t,r,s,i,o,c){const n=new lp(t.message,r||t.code,s,i,o);return n.cause=t,n.name=t.name,t.status!=null&&n.status==null&&(n.status=t.status),c&&Object.assign(n,c),n}constructor(t,r,s,i,o){super(t),Object.defineProperty(this,"message",{__proto__:null,value:t,enumerable:!0,writable:!0,configurable:!0}),this.name="AxiosError",this.isAxiosError=!0,r&&(this.code=r),s&&(this.config=s),i&&(this.request=i),o&&(this.response=o,this.status=o.status)}toJSON(){const t=this.config,r=t&&I.hasOwnProp(t,"redact")?t.redact:void 0,s=I.isArray(r)&&r.length>0?Fy(t,r):I.toJSONObject(t);return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:s,code:this.code,status:this.status}}};Z.ERR_BAD_OPTION_VALUE="ERR_BAD_OPTION_VALUE";Z.ERR_BAD_OPTION="ERR_BAD_OPTION";Z.ECONNABORTED="ECONNABORTED";Z.ETIMEDOUT="ETIMEDOUT";Z.ECONNREFUSED="ECONNREFUSED";Z.ERR_NETWORK="ERR_NETWORK";Z.ERR_FR_TOO_MANY_REDIRECTS="ERR_FR_TOO_MANY_REDIRECTS";Z.ERR_DEPRECATED="ERR_DEPRECATED";Z.ERR_BAD_RESPONSE="ERR_BAD_RESPONSE";Z.ERR_BAD_REQUEST="ERR_BAD_REQUEST";Z.ERR_CANCELED="ERR_CANCELED";Z.ERR_NOT_SUPPORT="ERR_NOT_SUPPORT";Z.ERR_INVALID_URL="ERR_INVALID_URL";Z.ERR_FORM_DATA_DEPTH_EXCEEDED="ERR_FORM_DATA_DEPTH_EXCEEDED";const Hy=null;function ul(e){return I.isPlainObject(e)||I.isArray(e)}function cp(e){return I.endsWith(e,"[]")?e.slice(0,-2):e}function Zo(e,t,r){return e?e.concat(t).map(function(i,o){return i=cp(i),!r&&o?"["+i+"]":i}).join(r?".":""):t}function Uy(e){return I.isArray(e)&&!e.some(ul)}const zy=I.toFlatObject(I,{},null,function(t){return/^is[A-Z]/.test(t)});function xo(e,t,r){if(!I.isObject(e))throw new TypeError("target must be an object");t=t||new FormData,r=I.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,function(u,h){return!I.isUndefined(h[u])});const s=r.metaTokens,i=r.visitor||p,o=r.dots,c=r.indexes,n=r.Blob||typeof Blob<"u"&&Blob,a=r.maxDepth===void 0?100:r.maxDepth,f=n&&I.isSpecCompliantForm(t);if(!I.isFunction(i))throw new TypeError("visitor must be a function");function m(y){if(y===null)return"";if(I.isDate(y))return y.toISOString();if(I.isBoolean(y))return y.toString();if(!f&&I.isBlob(y))throw new Z("Blob is not supported. Use a Buffer instead.");return I.isArrayBuffer(y)||I.isTypedArray(y)?f&&typeof Blob=="function"?new Blob([y]):Buffer.from(y):y}function p(y,u,h){let l=y;if(I.isReactNative(t)&&I.isReactNativeBlob(y))return t.append(Zo(h,u,o),m(y)),!1;if(y&&!h&&typeof y=="object"){if(I.endsWith(u,"{}"))u=s?u:u.slice(0,-2),y=JSON.stringify(y);else if(I.isArray(y)&&Uy(y)||(I.isFileList(y)||I.endsWith(u,"[]"))&&(l=I.toArray(y)))return u=cp(u),l.forEach(function(g,x){!(I.isUndefined(g)||g===null)&&t.append(c===!0?Zo([u],x,o):c===null?u:u+"[]",m(g))}),!1}return ul(y)?!0:(t.append(Zo(h,u,o),m(y)),!1)}const _=[],S=Object.assign(zy,{defaultVisitor:p,convertValue:m,isVisitable:ul});function b(y,u,h=0){if(!I.isUndefined(y)){if(h>a)throw new Z("Object is too deeply nested ("+h+" levels). Max depth: "+a,Z.ERR_FORM_DATA_DEPTH_EXCEEDED);if(_.indexOf(y)!==-1)throw Error("Circular reference detected in "+u.join("."));_.push(y),I.forEach(y,function(d,g){(!(I.isUndefined(d)||d===null)&&i.call(t,d,I.isString(g)?g.trim():g,u,S))===!0&&b(d,u?u.concat(g):[g],h+1)}),_.pop()}}if(!I.isObject(e))throw new TypeError("data must be an object");return b(e),t}function nh(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+"};return encodeURIComponent(e).replace(/[!'()~]|%20/g,function(s){return t[s]})}function kc(e,t){t Line truncated
`+c.map(fh).join(`
`):" "+fh(c[0]):"as no adapter specified";throw new Z("There is no suitable adapter to dispatch the request "+n,"ERR_NOT_SUPPORT")}return i}const vp={getAdapter:b0,adapters:Dc};function ta(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new Ni(null,e)}function ph(e){return ta(e),e.headers=Ye.from(e.headers),e.data=ea.call(e,e.transformRequest),["post","put","patch"].indexOf(e.method)!==-1&&e.headers.setContentType("application/x-www-form-urlencoded",!1),vp.getAdapter(e.adapter||Oi.adapter,e)(e).then(function(s){ta(e),e.response=s;try{s.data=ea.call(e,e.transformResponse,s)}finally{delete e.response}return s.headers=Ye.from(s.headers),s},function(s){if(!fp(s)&&(ta(e),s&&s.response)){e.response=s.response;try{s.response.data=ea.call(e,e.transformResponse,s.response)}finally{delete e.response}s.response.headers=Ye.from(s.response.headers)}return Promise.reject(s)})}const bo={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{bo[e]=function(s){return typeof s===e||"a"+(t<1?"n ":" ")+e}});const mh={};bo.transitional=function(t,r,s){function i(o,c){return"[Axios v"+Lc+"] Transitional option '"+o+"'"+c+(s?". "+s:"")}return(o,c,n)=>{if(t===!1)throw new Z(i(c," has been removed"+(r?" in "+r:"")),Z.ERR_DEPRECATED);return r&&!mh[c]&&(mh[c]=!0,console.warn(i(c," has been deprecated since v"+r+" and will be removed in the near future"))),t?t(o,c,n):!0}};bo.spelling=function(t){return(r,s)=>(console.warn(`${s} is likely a misspelling of ${t}`),!0)};function w0(e,t,r){if(typeof e!="object")throw new Z("options must be an object",Z.ERR_BAD_OPTION_VALUE);const s=Object.keys(e);let i=s.length;for(;i-- >0;){const o=s[i],c=Object.prototype.hasOwnProperty.call(t,o)?t[o]:void 0;if(c){const n=e[o],a=n===void 0||c(n,o,e);if(a!==!0)throw new Z("option "+o+" must be "+a,Z.ERR_BAD_OPTION_VALUE);continue}if(r!==!0)throw new Z("Unknown option "+o,Z.ERR_BAD_OPTION)}}const bn={assertOptions:w0,validators:bo},mt=bn.validators;let jr=class{constructor(t){this.defaults=t||{},this.interceptors={request:new oh,response:new oh}}async request(t,r){try{return await this._request(t,r)}catch(s){if(s instanceof Error){let i={};Error.captureStackTrace?Error.captureStackTrace(i):i=new Error;const o=(()=>{if(!i.stack)return"";const c=i.stack.indexOf(`
`);return c===-1?"":i.stack.slice(c+1)})();try{if(!s.stack)s.stack=o;else if(o){const c=o.indexOf(`
`),n=c===-1?-1:o.indexOf(`
`,c+1),a=n===-1?"":o.slice(n+1);String(s.stack).endsWith(a)||(s.stack+=`
`+o)}}catch{}}throw s}}_request(t,r){typeof t=="string"?(r=r||{},r.url=t):r=t||{},r=zr(this.defaults,r);const{transitional:s,paramsSerializer:i,headers:o}=r;s!==void 0&&bn.assertOptions(s,{silentJSONParsing:mt.transitional(mt.boolean),forcedJSONParsing:mt.transitional(mt.boolean),clarifyTimeoutError:mt.transitional(mt.boolean),legacyInterceptorReqResOrdering:mt.transitional(mt.boolean)},!1),i!=null&&(I.isFunction(i)?r.paramsSerializer={serialize:i}:bn.assertOptions(i,{encode:mt.function,serialize:mt.function},!0)),r.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?r.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:r.allowAbsoluteUrls=!0),bn.assertOptions(r,{baseUrl:mt.spelling("baseURL"),withXsrfToken:mt.spelling("withXSRFToken")},!0),r.method=(r.method||this.defaults.method||"get").toLowerCase();let c=o&&I.merge(o.common,o[r.method]);o&&I.forEach(["delete","get","head","post","put","patch","query","common"],b=>{delete o[b]}),r.headers=Ye.concat(c,o);const n=[];let a=!0;this.interceptors.request.forEach(function(y){if(typeof y.runWhen=="function"&&y.runWhen(r)===!1)return;a=a&&y.synchronous;const u=r.transitional||Rc;u&&u.legacyInterceptorReqResOrdering?n.unshift(y.fulfilled,y.rejected):n.push(y.fulfilled,y.rejected)});const f=[];this.interceptors.response.forEach(function(y){f.push(y.fulfilled,y.rejected)});let m,p=0,_;if(!a){const b=[ph.bind(this),void 0];for(b.unshift(...n),b.push(...f),_=b.length,m=Promise.resolve(r);p<_;)m=m.then(b[p++],b[p++]);return m}_=n.length;let S=r;for(;p<_;){const b=n[p++],y=n[p++];try{S=b(S)}catch(u){y.call(this,u);break}}try{m=ph.call(this,S)}catch(b){return Promise.reject(b)}for(p=0,_=f.length;p<_;)m=m.then(f[p++],f[p++]);return m}getUri(t){t=zr(this.defaults,t);const r=mp(t.baseURL,t.url,t.allowAbsoluteUrls);return hp(r,t.params,t.paramsSerializer)}};I.forEach(["delete","get","head","options"],function(t){jr.prototype[t]=function(r,s){return this.request(zr(s||{},{method:t,url:r,data:(s||{}).data}))}});I.forEach(["post","put","patch","query"],function(t){function r(s){return function(o,c,n){return this.request(zr(n||{},{method:t,headers:s?{"Content-Type":"multipart/form-data"}:{},url:o,data:c}))}}jr.prototype[t]=r(),t!=="query"&&(jr.prototype[t+"Form"]=r(!0))});let C0=class yp{constructor(t){if(typeof t!="function")throw new TypeError("executor must be a function.");let r;this.promise=new Promise(function(o){r=o});const s=this;this.promise.then(i=>{if(!s._listeners)return;let o=s._listeners.length;for(;o-- >0;)s._listeners[o](i);s._listeners=null}),this.promise.then=i=>{let o;const c=new Promise(n=>{s.subscribe(n),o=n}).then(i);return c.cancel=function(){s.unsubscribe(o)},c},t(function(o,c,n){s.reason||(s.reason=new Ni(o,c,n),r(s.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(t){if(this.reason){t(this.reason);return}this._listeners?this._listeners.push(t):this._listeners=[t]}unsubscribe(t){if(!this._listeners)return;const r=this._listeners.indexOf(t);r!==-1&&this._listeners.splice(r,1)}toAbortSignal(){const t=new AbortController,r=s=>{t.abort(s)};return this.subscribe(r),t.signal.unsubscribe=()=>this.unsubscribe(r),t.signal}static source(){let t;return{token:new yp(function(i){t=i}),cancel:t}}};function E0(e){return function(r){return e.apply(null,r)}}function k0(e){return I.isObject(e)&&e.isAxiosError===!0}const dl={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511,WebServerIsDown:521,ConnectionTimedOut:522,OriginIsUnreachable:523,TimeoutOccurred:524,SslHandshakeFailed:525,InvalidSslCertificate:526};Object.entries(dl).forEach(([e,t])=>{dl[t]=e});function Sp(e){const t=new jr(e),r=Zf(jr.prototype.request,t);return I.extend(r,jr.prototype,t,{allOwnKeys:!0}),I.extend(r,t,null,{allOwnKeys:!0}),r.create=function(i){return Sp(zr(e,i))},r}const Ce=Sp(Oi);Ce.Axios=jr;Ce.CanceledError=Ni;Ce.CancelToken=C0;Ce.isCa Line truncated
* @license React
* use-sync-external-store-shim.production.js
*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/var bs=M;function T0(e,t){return e===t&&(e!==0||1/e===1/t)||e!==e&&t!==t}var L0=typeof Object.is=="function"?Object.is:T0,D0=bs.useState,A0=bs.useEffect,O0=bs.useLayoutEffect,N0=bs.useDebugValue;function P0(e,t){var r=t(),s=D0({inst:{value:r,getSnapshot:t}}),i=s[0].inst,o=s[1];return O0(function(){i.value=r,i.getSnapshot=t,ra(i)&&o({inst:i})},[e,r,t]),A0(function(){return ra(i)&&o({inst:i}),e(function(){ra(i)&&o({inst:i})})},[e]),N0(r),r}function ra(e){var t=e.getSnapshot;e=e.value;try{var r=t();return!L0(e,r)}catch{return!0}}function B0(e,t){return t()}var j0=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?B0:P0;bp.useSyncExternalStore=bs.useSyncExternalStore!==void 0?bs.useSyncExternalStore:j0;xp.exports=bp;var _h=xp.exports;const wp=0,Cp=1,Ep=2,gh=3;var vh=Object.prototype.hasOwnProperty;function fl(e,t){var r,s;if(e===t)return!0;if(e&&t&&(r=e.constructor)===t.constructor){if(r===Date)return e.getTime()===t.getTime();if(r===RegExp)return e.toString()===t.toString();if(r===Array){if((s=e.length)===t.length)for(;s--&&fl(e[s],t[s]););return s===-1}if(!r||typeof e=="object"){s=0;for(r in e)if(vh.call(e,r)&&++s&&!vh.call(t,r)||!(r in t)||!fl(e[r],t[r]))return!1;return Object.keys(t).length===s}}return e!==e&&t!==t}const qt=new WeakMap,Gt=()=>{},Ke=Gt(),pl=Object,se=e=>e===Ke,It=e=>typeof e=="function",br=(e,t)=>({...e,...t}),kp=e=>It(e.then),sa={},rn={},Ac="undefined",Pi=typeof window!=Ac,ml=typeof document!=Ac,M0=Pi&&"Deno"in window,I0=()=>Pi&&typeof window.requestAnimationFrame!=Ac,Rp=(e,t)=>{const r=qt.get(e);return[()=>!se(t)&&e.get(t)||sa,s=>{if(!se(t)){const i=e.get(t);t in rn||(rn[t]=i),r[5](t,br(i,s),i||sa)}},r[6],()=>!se(t)&&t in rn?rn[t]:!se(t)&&e.get(t)||sa]};let _l=!0;const F0=()=>_l,[gl,vl]=Pi&&window.addEventListener?[window.addEventListener.bind(window),window.removeEventListener.bind(window)]:[Gt,Gt],H0=()=>{const e=ml&&document.visibilityState;return se(e)||e!=="hidden"},U0=e=>(ml&&document.addEventListener("visibilitychange",e),gl("focus",e),()=>{ml&&document.removeEventListener("visibilitychange",e),vl("focus",e)}),z0=e=>{const t=()=>{_l=!0,e()},r=()=>{_l=!1};return gl("online",t),gl("offline",r),()=>{vl("online",t),vl("offline",r)}},$0={isOnline:F0,isVisible:H0},W0={initFocus:U0,initReconnect:z0},yh=!bi.useId,fs=!Pi||M0,V0=e=>I0()?window.requestAnimationFrame(e):setTimeout(e,1),ia=fs?M.useEffect:M.useLayoutEffect,na=typeof navigator<"u"&&navigator.connection,Sh=!fs&&na&&(["slow-2g","2g"].includes(na.effectiveType)||na.saveData),sn=new WeakMap,q0=e=>pl.prototype.toString.call(e),oa=(e,t)=>e===`[object ${t}]`;let K0=0;const yl=e=>{const t=typeof e,r=q0(e),s=oa(r,"Date"),i=oa(r,"RegExp"),o=oa(r,"Object");let c,n;if(pl(e)===e&&!s&&!i){if(c=sn.get(e),c)return c;if(c=++K0+"~",sn.set(e,c),Array.isArray(e)){for(c="@",n=0;n<e.length;n++)c+=yl(e[n])+",";sn.set(e,c)}if(o){c="#";const a=pl.keys(e).sort();for(;!se(n=a.pop());)se(e[n])||(c+=n+":"+yl(e[n])+",");sn.set(e,c)}}else c=s?e.toJSON():t=="symbol"?e.toString():t=="string"?JSON.stringify(e):""+e;return c},Oc=e=>{if(It(e))try{e=e()}catch{e=""}const t=e;return e=typeof e=="string"?e:(Array.isArray(e)?e.length:e)?yl(e):"",[e,t]};let X0=0;const Sl=()=>++X0;async function Tp(...e){const[t,r,s,i]=e,o=br({populateCache:!0,throwOnError:!0},typeof i=="boolean"?{revalidate:i}:i||{});let c=o.populateCache;const n=o.rollbackOnError;let a=o.optimisticData;const f=_=>typeof n=="function"?n(_):n!==!1,m=o.throwOnError;if(It(r)){const _=r,S=[],b=t.keys();for(const y of b)!/^\$(inf|sub)\$/.test(y)&&_(t.get(y)._k)&&S.push(y);return Promise.all(S.map(p))}return p(r);async function p(_){const[S]=Oc(_);if(!S)return;const[b,y]=Rp(t,S),[u,h,l,d]=qt.get(t),g=()=>{const F=u[S];return(It(o.revalidate)?o.revalidate(b().data,_):o.revalidate!==!1)&&(delete l[S],delete d[S],F&&F[0])?F[0](Ep).then(()=>b().data):b().data};if(e.length<3)return g();let x=s,C,k=!1;const w=Sl();h[S]=[w,0];const E=!se(a),L=b(),N=L.data,O=L._c,P=se(O)?N:O;if(E&&(a=It(a)?a(P,N):a,y({data:a,_c:P})),It(x))try{x=x(P)}catch(F){C=F,k=!0}if(x&&kp(x))if(x=await x.catch(F=>{C=F,k=!0}),w!==h[S][0]){if(k)throw C;return x}else k&&E&&f(C)&&(c=!0,y({data:P,_c:Ke}));if(c&&!k)if(It(c)){const F=c(x,P);y({data:F,error:Ke,_c:Ke})}else y({data:x,error:Ke,_c:Ke});if(h[S][1]=Sl(),Promise.resolve(g()).then(()=>{y({_c:Ke})}),k){if(m)throw C;return}return x}}const xh=(e,t)=>{for(const r in e)e[r][0]&&e[r][0](t)},G0=(e,t)=>{if(!qt.has(e)){const r=br(W0,t),s=Object.create(null),i=Tp.bind(Ke,e);let o=Gt;const c=Object.create(null),n=(m,p)=>{const _=c[m]||[];return c[m]=_,_.push(p),()=>_.splice(_.indexOf(p),1)},a=(m,p,_)=>{e.set(m,p);const S=c[m];if(S)for(const b of S)b(p,_)},f=()=>{if(!qt.has(e)&&(qt.set(e,[s,Object.create(null),Object.create(null),Object.create(null),i,a,n]),!fs)){const m=r.initFocus(setTimeout.bind(Ke,xh.bind(Ke,s,wp))),p=r.initReconnect(setTimeout.bind(Ke,xh.bind(Ke,s,Cp)));o=()=>{m&&m(),p&&p(),qt.delete(e)}}};return f(),[e,i,f,o]}return[e,qt.get(e)[4]]},J0=(e,t,r,s,Line truncated
`))),this.register(this._terminal.onA11yTab(x=>this._handleTab(x))),this.register(this._terminal.onKey(x=>this._handleKey(x.key))),this.register(this._terminal.onBlur(()=>this._clearLiveRegion())),this.register(this._renderService.onDimensionsChange(()=>this._refreshRowsDimensions())),this._screenDprMonitor=new y.ScreenDprMonitor(window),this.register(this._screenDprMonitor),this._screenDprMonitor.setListener(()=>this._refreshRowsDimensions()),this.register((0,h.addDisposableDomListener)(window,"resize",()=>this._refreshRowsDimensions())),this._refreshRows(),this.register((0,b.toDisposable)(()=>{this._accessibilityContainer.remove(),this._rowElements.length=0}))}_handleTab(d){for(let g=0;g<d;g++)this._handleChar(" ")}_handleChar(d){this._liveRegionLineCount<21&&(this._charsToConsume.length>0?this._charsToConsume.shift()!==d&&(this._charsToAnnounce+=d):this._charsToAnnounce+=d,d===`
`&&(this._liveRegionLineCount++,this._liveRegionLineCount===21&&(this._liveRegion.textContent+=p.tooMuchOutput)),_.isMac&&this._liveRegion.textContent&&this._liveRegion.textContent.length>0&&!this._liveRegion.parentNode&&setTimeout(()=>{this._accessibilityContainer.appendChild(this._liveRegion)},0))}_clearLiveRegion(){this._liveRegion.textContent="",this._liveRegionLineCount=0,_.isMac&&this._liveRegion.remove()}_handleKey(d){this._clearLiveRegion(),new RegExp("\\p{Control}","u").test(d)||this._charsToConsume.push(d)}_refreshRows(d,g){this._liveRegionDebouncer.refresh(d,g,this._terminal.rows)}_renderRows(d,g){const x=this._terminal.buffer,C=x.lines.length.toString();for(let k=d;k<=g;k++){const w=x.translateBufferLineToString(x.ydisp+k,!0),E=(x.ydisp+k+1).toString(),L=this._rowElements[k];L&&(w.length===0?L.innerText=" ":L.textContent=w,L.setAttribute("aria-posinset",E),L.setAttribute("aria-setsize",C))}this._announceCharacters()}_announceCharacters(){this._charsToAnnounce.length!==0&&(this._liveRegion.textContent+=this._charsToAnnounce,this._charsToAnnounce="")}_handleBoundaryFocus(d,g){const x=d.target,C=this._rowElements[g===0?1:this._rowElements.length-2];if(x.getAttribute("aria-posinset")===(g===0?"1":`${this._terminal.buffer.lines.length}`)||d.relatedTarget!==C)return;let k,w;if(g===0?(k=x,w=this._rowElements.pop(),this._rowContainer.removeChild(w)):(k=this._rowElements.shift(),w=x,this._rowContainer.removeChild(k)),k.removeEventListener("focus",this._topBoundaryFocusListener),w.removeEventListener("focus",this._bottomBoundaryFocusListener),g===0){const E=this._createAccessibilityTreeNode();this._rowElements.unshift(E),this._rowContainer.insertAdjacentElement("afterbegin",E)}else{const E=this._createAccessibilityTreeNode();this._rowElements.push(E),this._rowContainer.appendChild(E)}this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._terminal.scrollLines(g===0?-1:1),this._rowElements[g===0?1:this._rowElements.length-2].focus(),d.preventDefault(),d.stopImmediatePropagation()}_handleResize(d){this._rowElements[this._rowElements.length-1].removeEventListener("focus",this._bottomBoundaryFocusListener);for(let g=this._rowContainer.children.length;g<this._terminal.rows;g++)this._rowElements[g]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[g]);for(;this._rowElements.length>d;)this._rowContainer.removeChild(this._rowElements.pop());this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._refreshRowsDimensions()}_createAccessibilityTreeNode(){const d=document.createElement("div");return d.setAttribute("role","listitem"),d.tabIndex=-1,this._refreshRowDimensions(d),d}_refreshRowsDimensions(){if(this._renderService.dimensions.css.cell.height){this._accessibilityContainer.style.width=`${this._renderService.dimensions.css.canvas.width}px`,this._rowElements.length!==this._terminal.rows&&this._handleResize(this._terminal.rows);for(let d=0;d<this._terminal.rows;d++)this._refreshRowDimensions(this._rowElements[d])}}_refreshRowDimensions(d){d.style.height=`${this._renderService.dimensions.css.cell.height}px`}};n.AccessibilityManager=l=f([m(1,u.IRenderService)],l)},3614:(c,n)=>{function a(_){return _.replace(/\r?\n/g,"\r")}function f(_,S){return S?"\x1B[200~"+_+"\x1B[201~":_}function m(_,S,b,y){_=f(_=a(_),b.decPrivateModes.bracketedPasteMode&&y.rawOptions.ignoreBracketedPasteMode!==!0),b.triggerDataEvent(_,!0),S.value=""}function p(_,S,b){const y=b.getBoundingClientRect(),u=_.clientX-y.left-10,h=_.clientY-y.top-10;S.style.width="20px",S.style.height="20px",S.style.left=`${u}px`,S.style.top=`${h}px`,S.style.zIndex="1000",S.focus()}Object.defineProperty(n,"__esModule",{value:!0}),n.rightClickHandler=n.moveTextAreaUnderMouseCursor=n.paste=n.handlePasteEvent=n.copyHandler=n.bracketTextForPaste=n.prepareTextForTerminal=void 0,n.prepareTextForTerminal=a,n.bracketTextForPaste=f,n.copyHandler=function(_,S){_.clipboardData&&_.clipboardData.setData("text/plain",S.selectionText),_.preventDefault()},n.handlePasteEvent=function(_,S,b,y){_.stopPropagation(),_.clipboardData&&m(_.clipboardData.getData("text/plain"),S,b,y)},n.paste=m,n.moveTextAreaUnderMouseCursor=p,n.rightClickHandler=function(_,S,b,y,u){p(_,S,b),u&&y.rightClickSelect(_),S.value=y.selectionText,S.select()}},7239:(c,n,a)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.ColorContrastCache=void 0;const f=a(1505);n.ColorContrastCache=class{constructor(){this._color=new f.TwoKeyMap,this._css=new f.TwoKeyMap}setCss(m,p,_){this._css.set(m,p,_)}getCss(m,p){return this._css.get(m,p)}setColor(m,p,_){this._color.set(m,p,_)}getColor(m,p){return this._color.get(m,p)}clear(){this._color.clear(),this._css.clear()}}},3656:(c,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.addDisposableDomListener=void 0,n.addDisposableDomListener=function(a,f,m,p) Line truncated
WARNING: This link could potentially be dangerous`)){const h=window.open();if(h){try{h.opener=null}catch{}h.location.href=u}else console.warn("Opening link blocked as opener could not be cleared")}}n.OscLinkProvider=S=f([m(0,_.IBufferService),m(1,_.IOptionsService),m(2,_.IOscLinkService)],S)},6193:(c,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.RenderDebouncer=void 0,n.RenderDebouncer=class{constructor(a,f){this._parentWindow=a,this._renderCallback=f,this._refreshCallbacks=[]}dispose(){this._animationFrame&&(this._parentWindow.cancelAnimationFrame(this._animationFrame),this._animationFrame=void 0)}addRefreshCallback(a){return this._refreshCallbacks.push(a),this._animationFrame||(this._animationFrame=this._parentWindow.requestAnimationFrame(()=>this._innerRefresh())),this._animationFrame}refresh(a,f,m){this._rowCount=m,a=a!==void 0?a:0,f=f!==void 0?f:this._rowCount-1,this._rowStart=this._rowStart!==void 0?Math.min(this._rowStart,a):a,this._rowEnd=this._rowEnd!==void 0?Math.max(this._rowEnd,f):f,this._animationFrame||(this._animationFrame=this._parentWindow.requestAnimationFrame(()=>this._innerRefresh()))}_innerRefresh(){if(this._animationFrame=void 0,this._rowStart===void 0||this._rowEnd===void 0||this._rowCount===void 0)return void this._runRefreshCallbacks();const a=Math.max(this._rowStart,0),f=Math.min(this._rowEnd,this._rowCount-1);this._rowStart=void 0,this._rowEnd=void 0,this._renderCallback(a,f),this._runRefreshCallbacks()}_runRefreshCallbacks(){for(const a of this._refreshCallbacks)a(0);this._refreshCallbacks=[]}}},5596:(c,n,a)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.ScreenDprMonitor=void 0;const f=a(844);class m extends f.Disposable{constructor(_){super(),this._parentWindow=_,this._currentDevicePixelRatio=this._parentWindow.devicePixelRatio,this.register((0,f.toDisposable)(()=>{this.clearListener()}))}setListener(_){this._listener&&this.clearListener(),this._listener=_,this._outerListener=()=>{this._listener&&(this._listener(this._parentWindow.devicePixelRatio,this._currentDevicePixelRatio),this._updateDpr())},this._updateDpr()}_updateDpr(){var _;this._outerListener&&((_=this._resolutionMediaMatchList)===null||_===void 0||_.removeListener(this._outerListener),this._currentDevicePixelRatio=this._parentWindow.devicePixelRatio,this._resolutionMediaMatchList=this._parentWindow.matchMedia(`screen and (resolution: ${this._parentWindow.devicePixelRatio}dppx)`),this._resolutionMediaMatchList.addListener(this._outerListener))}clearListener(){this._resolutionMediaMatchList&&this._listener&&this._outerListener&&(this._resolutionMediaMatchList.removeListener(this._outerListener),this._resolutionMediaMatchList=void 0,this._listener=void 0,this._outerListener=void 0)}}n.ScreenDprMonitor=m},3236:(c,n,a)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.Terminal=void 0;const f=a(3614),m=a(3656),p=a(6465),_=a(9042),S=a(3730),b=a(1680),y=a(3107),u=a(5744),h=a(2950),l=a(1296),d=a(428),g=a(4269),x=a(5114),C=a(8934),k=a(3230),w=a(9312),E=a(4725),L=a(6731),N=a(8055),O=a(8969),P=a(8460),F=a(844),z=a(6114),W=a(8437),V=a(2584),R=a(7399),D=a(5941),A=a(9074),B=a(2585),H=a(5435),q=a(4567),G=typeof window<"u"?window.document:null;class X extends O.CoreTerminal{get onFocus(){return this._onFocus.event}get onBlur(){return this._onBlur.event}get onA11yChar(){return this._onA11yCharEmitter.event}get onA11yTab(){return this._onA11yTabEmitter.event}get onWillOpen(){return this._onWillOpen.event}constructor(T={}){super(T),this.browser=z,this._keyDownHandled=!1,this._keyDownSeen=!1,this._keyPressHandled=!1,this._unprocessedDeadKey=!1,this._accessibilityManager=this.register(new F.MutableDisposable),this._onCursorMove=this.register(new P.EventEmitter),this.onCursorMove=this._onCursorMove.event,this._onKey=this.register(new P.EventEmitter),this.onKey=this._onKey.event,this._onRender=this.register(new P.EventEmitter),this.onRender=this._onRender.event,this._onSelectionChange=this.register(new P.EventEmitter),this.onSelectionChange=this._onSelectionChange.event,this._onTitleChange=this.register(new P.EventEmitter),this.onTitleChange=this._onTitleChange.event,this._onBell=this.register(new P.EventEmitter),this.onBell=this._onBell.event,this._onFocus=this.register(new P.EventEmitter),this._onBlur=this.register(new P.EventEmitter),this._onA11yCharEmitter=this.register(new P.EventEmitter),this._onA11yTabEmitter=this.register(new P.EventEmitter),this._onWillOpen=this.register(new P.EventEmitter),this._setup(),this.linkifier2=this.register(this._instantiationService.createInstance(p.Linkifier2)),this.linkifier2.registerLinkProvider(this._instantiationService.createInstance(S.OscLinkProvider)),this._decorationService=this._instantiationService.createInstance(A.DecorationService),this._instantiationService.setService(B.IDecorationService,this._decorationService),this.register(this._inputHandler.onRequestBell(()=>this._onBell.fire())),this.register(this._inputHandler.onRequestRefreshRows((j,$)=>this.refresh(j,$))),this.r Line truncated
`:`
`)}clearSelection(){this._model.clearSelection(),this._removeMouseDownListeners(),this.refresh(),this._onSelectionChange.fire()}refresh(w){this._refreshAnimationFrame||(this._refreshAnimationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._refresh())),h.isLinux&&w&&this.selectionText.length&&this._onLinuxMouseSelection.fire(this.selectionText)}_refresh(){this._refreshAnimationFrame=void 0,this._onRedrawRequest.fire({start:this._model.finalSelectionStart,end:this._model.finalSelectionEnd,columnSelectMode:this._activeSelectionMode===3})}_isClickInSelection(w){const E=this._getMouseBufferCoords(w),L=this._model.finalSelectionStart,N=this._model.finalSelectionEnd;return!!(L&&N&&E)&&this._areCoordsInSelection(E,L,N)}isCellInSelection(w,E){const L=this._model.finalSelectionStart,N=this._model.finalSelectionEnd;return!(!L||!N)&&this._areCoordsInSelection([w,E],L,N)}_areCoordsInSelection(w,E,L){return w[1]>E[1]&&w[1]<L[1]||E[1]===L[1]&&w[1]===E[1]&&w[0]>=E[0]&&w[0]<L[0]||E[1]<L[1]&&w[1]===L[1]&&w[0]<L[0]||E[1]<L[1]&&w[1]===E[1]&&w[0]>=E[0]}_selectWordAtCursor(w,E){var L,N;const O=(N=(L=this._linkifier.currentLink)===null||L===void 0?void 0:L.link)===null||N===void 0?void 0:N.range;if(O)return this._model.selectionStart=[O.start.x-1,O.start.y-1],this._model.selectionStartLength=(0,l.getRangeLength)(O,this._bufferService.cols),this._model.selectionEnd=void 0,!0;const P=this._getMouseBufferCoords(w);return!!P&&(this._selectWordAt(P,E),this._model.selectionEnd=void 0,!0)}selectAll(){this._model.isSelectAllActive=!0,this.refresh(),this._onSelectionChange.fire()}selectLines(w,E){this._model.clearSelection(),w=Math.max(w,0),E=Math.min(E,this._bufferService.buffer.lines.length-1),this._model.selectionStart=[0,w],this._model.selectionEnd=[this._bufferService.cols,E],this.refresh(),this._onSelectionChange.fire()}_handleTrim(w){this._model.handleTrim(w)&&this.refresh()}_getMouseBufferCoords(w){const E=this._mouseService.getCoords(w,this._screenElement,this._bufferService.cols,this._bufferService.rows,!0);if(E)return E[0]--,E[1]--,E[1]+=this._bufferService.buffer.ydisp,E}_getMouseEventScrollAmount(w){let E=(0,p.getCoordsRelativeToElement)(this._coreBrowserService.window,w,this._screenElement)[1];const L=this._renderService.dimensions.css.canvas.height;return E>=0&&E<=L?0:(E>L&&(E-=L),E=Math.min(Math.max(E,-50),50),E/=50,E/Math.abs(E)+Math.round(14*E))}shouldForceSelection(w){return h.isMac?w.altKey&&this._optionsService.rawOptions.macOptionClickForcesSelection:w.shiftKey}handleMouseDown(w){if(this._mouseDownTimeStamp=w.timeStamp,(w.button!==2||!this.hasSelection)&&w.button===0){if(!this._enabled){if(!this.shouldForceSelection(w))return;w.stopPropagation()}w.preventDefault(),this._dragScrollAmount=0,this._enabled&&w.shiftKey?this._handleIncrementalClick(w):w.detail===1?this._handleSingleClick(w):w.detail===2?this._handleDoubleClick(w):w.detail===3&&this._handleTripleClick(w),this._addMouseDownListeners(),this.refresh(!0)}}_addMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.addEventListener("mousemove",this._mouseMoveListener),this._screenElement.ownerDocument.addEventListener("mouseup",this._mouseUpListener)),this._dragScrollIntervalTimer=this._coreBrowserService.window.setInterval(()=>this._dragScroll(),50)}_removeMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.removeEventListener("mousemove",this._mouseMoveListener),this._screenElement.ownerDocument.removeEventListener("mouseup",this._mouseUpListener)),this._coreBrowserService.window.clearInterval(this._dragScrollIntervalTimer),this._dragScrollIntervalTimer=void 0}_handleIncrementalClick(w){this._model.selectionStart&&(this._model.selectionEnd=this._getMouseBufferCoords(w))}_handleSingleClick(w){if(this._model.selectionStartLength=0,this._model.isSelectAllActive=!1,this._activeSelectionMode=this.shouldColumnSelect(w)?3:0,this._model.selectionStart=this._getMouseBufferCoords(w),!this._model.selectionStart)return;this._model.selectionEnd=void 0;const E=this._bufferService.buffer.lines.get(this._model.selectionStart[1]);E&&E.length!==this._model.selectionStart[0]&&E.hasWidth(this._model.selectionStart[0])===0&&this._model.selectionStart[0]++}_handleDoubleClick(w){this._selectWordAtCursor(w,!0)&&(this._activeSelectionMode=1)}_handleTripleClick(w){const E=this._getMouseBufferCoords(w);E&&(this._activeSelectionMode=2,this._selectLineAt(E[1]))}shouldColumnSelect(w){return w.altKey&&!(h.isMac&&this._optionsService.rawOptions.macOptionClickForcesSelection)}_handleMouseMove(w){if(w.stopImmediatePropagation(),!this._model.selectionStart)return;const E=this._model.selectionEnd?[this._model.selectionEnd[0],this._model.selectionEnd[1]]:null;if(this._model.selectionEnd=this._getMouseBufferCoords(w),!this._model.selectionEnd)return void this.refresh(!0);this._activeSelectionMode===2?this._model.selectionEnd[1]<this._model.selectionStart[1]?this._model.selectionEnd[0]=0:this._model.sele Line truncated
`,p.VT="\v",p.FF="\f",p.CR="\r",p.SO="",p.SI="",p.DLE="",p.DC1="",p.DC2="",p.DC3="",p.DC4="",p.NAK="",p.SYN="",p.ETB="",p.CAN="",p.EM="",p.SUB="",p.ESC="\x1B",p.FS="",p.GS="",p.RS="",p.US="",p.SP=" ",p.DEL=""}(a||(n.C0=a={})),function(p){p.PAD="€",p.HOP="",p.BPH="‚",p.NBH="ƒ",p.IND="„",p.NEL="…",p.SSA="†",p.ESA="‡",p.HTS="ˆ",p.HTJ="‰",p.VTS="Š",p.PLD="‹",p.PLU="Œ",p.RI="",p.SS2="Ž",p.SS3="",p.DCS="",p.PU1="‘",p.PU2="’",p.STS="“",p.CCH="”",p.MW="•",p.SPA="–",p.EPA="—",p.SOS="˜",p.SGCI="™",p.SCI="š",p.CSI="›",p.ST="œ",p.OSC="",p.PM="ž",p.APC="Ÿ"}(f||(n.C1=f={})),function(p){p.ST=`${a.ESC}\\`}(m||(n.C1_ESCAPED=m={}))},7399:(c,n,a)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.evaluateKeyboardEvent=void 0;const f=a(2584),m={48:["0",")"],49:["1","!"],50:["2","@"],51:["3","#"],52:["4","$"],53:["5","%"],54:["6","^"],55:["7","&"],56:["8","*"],57:["9","("],186:[";",":"],187:["=","+"],188:[",","<"],189:["-","_"],190:[".",">"],191:["/","?"],192:["`","~"],219:["[","{"],220:["\\","|"],221:["]","}"],222:["'",'"']};n.evaluateKeyboardEvent=function(p,_,S,b){const y={type:0,cancel:!1,key:void 0},u=(p.shiftKey?1:0)|(p.altKey?2:0)|(p.ctrlKey?4:0)|(p.metaKey?8:0);switch(p.keyCode){case 0:p.key==="UIKeyInputUpArrow"?y.key=_?f.C0.ESC+"OA":f.C0.ESC+"[A":p.key==="UIKeyInputLeftArrow"?y.key=_?f.C0.ESC+"OD":f.C0.ESC+"[D":p.key==="UIKeyInputRightArrow"?y.key=_?f.C0.ESC+"OC":f.C0.ESC+"[C":p.key==="UIKeyInputDownArrow"&&(y.key=_?f.C0.ESC+"OB":f.C0.ESC+"[B");break;case 8:if(p.altKey){y.key=f.C0.ESC+f.C0.DEL;break}y.key=f.C0.DEL;break;case 9:if(p.shiftKey){y.key=f.C0.ESC+"[Z";break}y.key=f.C0.HT,y.cancel=!0;break;case 13:y.key=p.altKey?f.C0.ESC+f.C0.CR:f.C0.CR,y.cancel=!0;break;case 27:y.key=f.C0.ESC,p.altKey&&(y.key=f.C0.ESC+f.C0.ESC),y.cancel=!0;break;case 37:if(p.metaKey)break;u?(y.key=f.C0.ESC+"[1;"+(u+1)+"D",y.key===f.C0.ESC+"[1;3D"&&(y.key=f.C0.ESC+(S?"b":"[1;5D"))):y.key=_?f.C0.ESC+"OD":f.C0.ESC+"[D";break;case 39:if(p.metaKey)break;u?(y.key=f.C0.ESC+"[1;"+(u+1)+"C",y.key===f.C0.ESC+"[1;3C"&&(y.key=f.C0.ESC+(S?"f":"[1;5C"))):y.key=_?f.C0.ESC+"OC":f.C0.ESC+"[C";break;case 38:if(p.metaKey)break;u?(y.key=f.C0.ESC+"[1;"+(u+1)+"A",S||y.key!==f.C0.ESC+"[1;3A"||(y.key=f.C0.ESC+"[1;5A")):y.key=_?f.C0.ESC+"OA":f.C0.ESC+"[A";break;case 40:if(p.metaKey)break;u?(y.key=f.C0.ESC+"[1;"+(u+1)+"B",S||y.key!==f.C0.ESC+"[1;3B"||(y.key=f.C0.ESC+"[1;5B")):y.key=_?f.C0.ESC+"OB":f.C0.ESC+"[B";break;case 45:p.shiftKey||p.ctrlKey||(y.key=f.C0.ESC+"[2~");break;case 46:y.key=u?f.C0.ESC+"[3;"+(u+1)+"~":f.C0.ESC+"[3~";break;case 36:y.key=u?f.C0.ESC+"[1;"+(u+1)+"H":_?f.C0.ESC+"OH":f.C0.ESC+"[H";break;case 35:y.key=u?f.C0.ESC+"[1;"+(u+1)+"F":_?f.C0.ESC+"OF":f.C0.ESC+"[F";break;case 33:p.shiftKey?y.type=2:p.ctrlKey?y.key=f.C0.ESC+"[5;"+(u+1)+"~":y.key=f.C0.ESC+"[5~";break;case 34:p.shiftKey?y.type=3:p.ctrlKey?y.key=f.C0.ESC+"[6;"+(u+1)+"~":y.key=f.C0.ESC+"[6~";break;case 112:y.key=u?f.C0.ESC+"[1;"+(u+1)+"P":f.C0.ESC+"OP";break;case 113:y.key=u?f.C0.ESC+"[1;"+(u+1)+"Q":f.C0.ESC+"OQ";break;case 114:y.key=u?f.C0.ESC+"[1;"+(u+1)+"R":f.C0.ESC+"OR";break;case 115:y.key=u?f.C0.ESC+"[1;"+(u+1)+"S":f.C0.ESC+"OS";break;case 116:y.key=u?f.C0.ESC+"[15;"+(u+1)+"~":f.C0.ESC+"[15~";break;case 117:y.key=u?f.C0.ESC+"[17;"+(u+1)+"~":f.C0.ESC+"[17~";break;case 118:y.key=u?f.C0.ESC+"[18;"+(u+1)+"~":f.C0.ESC+"[18~";break;case 119:y.key=u?f.C0.ESC+"[19;"+(u+1)+"~":f.C0.ESC+"[19~";break;case 120:y.key=u?f.C0.ESC+"[20;"+(u+1)+"~":f.C0.ESC+"[20~";break;case 121:y.key=u?f.C0.ESC+"[21;"+(u+1)+"~":f.C0.ESC+"[21~";break;case 122:y.key=u?f.C0.ESC+"[23;"+(u+1)+"~":f.C0.ESC+"[23~";break;case 123:y.key=u?f.C0.ESC+"[24;"+(u+1)+"~":f.C0.ESC+"[24~";break;default:if(!p.ctrlKey||p.shiftKey||p.altKey||p.metaKey)if(S&&!b||!p.altKey||p.metaKey)!S||p.altKey||p.ctrlKey||p.shiftKey||!p.metaKey?p.key&&!p.ctrlKey&&!p.altKey&&!p.metaKey&&p.keyCode>=48&&p.key.length===1?y.key=p.key:p.key&&p.ctrlKey&&(p.key==="_"&&(y.key=f.C0.US),p.key==="@"&&(y.key=f.C0.NUL)):p.keyCode===65&&(y.type=1);else{const h=m[p.keyCode],l=h==null?void 0:h[p.shiftKey?1:0];if(l)y.key=f.C0.ESC+l;else if(p.keyCode>=65&&p.keyCode<=90){const d=p.ctrlKey?p.keyCode-64:p.keyCode+32;let g=String.fromCharCode(d);p.shiftKey&&(g=g.toUpperCase()),y.key=f.C0.ESC+g}else if(p.keyCode===32)y.key=f.C0.ESC+(p.ctrlKey?f.C0.NUL:" ");else if(p.key==="Dead"&&p.code.startsWith("Key")){let d=p.code.slice(3,4);p.shiftKey||(d=d.toLowerCase()),y.key=f.C0.ESC+d,y.cancel=!0}}else p.keyCode>=65&&p.keyCode<=90?y.key=String.fromCharCode(p.keyCode-64):p.keyCode===32?y.key=f.C0.NUL:p.keyCode>=51&&p.keyCode<=55?y.key=String.fromCharCode(p.keyCode-51+27):p.keyCode===56?y.key=f.C0.DEL:p.keyCode===219?y.key=f.C0.ESC:p.keyCode===220?y.key=f.C0.FS:p.keyCode===221&&(y.key=f.C0.GS)}return y}},482:(c,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.Utf8ToUtf32=n.StringToUtf32=n.utf32ToString=n.stringFromCodePoint=void 0,n.stringFromCodePoint=function(a){return a>65535?(a-=65536,String.fromCharCode(55296+(a>>10Line truncated
`,l)}paste(h){this._core.paste(h)}refresh(h,l){this._verifyIntegers(h,l),this._core.refresh(h,l)}reset(){this._core.reset()}clearTextureAtlas(){this._core.clearTextureAtlas()}loadAddon(h){this._addonManager.loadAddon(this,h)}static get strings(){return n}_verifyIntegers(...h){for(const l of h)if(l===1/0||isNaN(l)||l%1!=0)throw new Error("This API only accepts integers")}_verifyPositiveIntegers(...h){for(const l of h)if(l&&(l===1/0||isNaN(l)||l%1!=0||l<0))throw new Error("This API only accepts positive integers")}}c.Terminal=y})(),o})())})(Ap);var GS=Ap.exports,Np={exports:{}};(function(e,t){(function(r,s){e.exports=s()})(self,()=>(()=>{var r={};return(()=>{var s=r;Object.defineProperty(s,"__esModule",{value:!0}),s.FitAddon=void 0,s.FitAddon=class{activate(i){this._terminal=i}dispose(){}fit(){const i=this.proposeDimensions();if(!i||!this._terminal||isNaN(i.cols)||isNaN(i.rows))return;const o=this._terminal._core;this._terminal.rows===i.rows&&this._terminal.cols===i.cols||(o._renderService.clear(),this._terminal.resize(i.cols,i.rows))}proposeDimensions(){if(!this._terminal||!this._terminal.element||!this._terminal.element.parentElement)return;const i=this._terminal._core,o=i._renderService.dimensions;if(o.css.cell.width===0||o.css.cell.height===0)return;const c=this._terminal.options.scrollback===0?0:i.viewport.scrollBarWidth,n=window.getComputedStyle(this._terminal.element.parentElement),a=parseInt(n.getPropertyValue("height")),f=Math.max(0,parseInt(n.getPropertyValue("width"))),m=window.getComputedStyle(this._terminal.element),p=a-(parseInt(m.getPropertyValue("padding-top"))+parseInt(m.getPropertyValue("padding-bottom"))),_=f-(parseInt(m.getPropertyValue("padding-right"))+parseInt(m.getPropertyValue("padding-left")))-c;return{cols:Math.max(2,Math.floor(_/o.css.cell.width)),rows:Math.max(1,Math.floor(p/o.css.cell.height))}}}})(),r})())})(Np);var JS=Np.exports;const zt=Object.create(null);zt.open="0";zt.close="1";zt.ping="2";zt.pong="3";zt.message="4";zt.upgrade="5";zt.noop="6";const wn=Object.create(null);Object.keys(zt).forEach(e=>{wn[zt[e]]=e});const xl={type:"error",data:"parser error"},Pp=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",Bp=typeof ArrayBuffer=="function",jp=e=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,Nc=({type:e,data:t},r,s)=>Pp&&t instanceof Blob?r?s(t):wh(t,s):Bp&&(t instanceof ArrayBuffer||jp(t))?r?s(t):wh(new Blob([t]),s):s(zt[e]+(t||"")),wh=(e,t)=>{const r=new FileReader;return r.onload=function(){const s=r.result.split(",")[1];t("b"+(s||""))},r.readAsDataURL(e)};function Ch(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}let ca;function QS(e,t){if(Pp&&e.data instanceof Blob)return e.data.arrayBuffer().then(Ch).then(t);if(Bp&&(e.data instanceof ArrayBuffer||jp(e.data)))return t(Ch(e.data));Nc(e,!1,r=>{ca||(ca=new TextEncoder),t(ca.encode(r))})}const Eh="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",qs=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let e=0;e<Eh.length;e++)qs[Eh.charCodeAt(e)]=e;const YS=e=>{let t=e.length*.75,r=e.length,s,i=0,o,c,n,a;e[e.length-1]==="="&&(t--,e[e.length-2]==="="&&t--);const f=new ArrayBuffer(t),m=new Uint8Array(f);for(s=0;s<r;s+=4)o=qs[e.charCodeAt(s)],c=qs[e.charCodeAt(s+1)],n=qs[e.charCodeAt(s+2)],a=qs[e.charCodeAt(s+3)],m[i++]=o<<2|c>>4,m[i++]=(c&15)<<4|n>>2,m[i++]=(n&3)<<6|a&63;return f},ZS=typeof ArrayBuffer=="function",Pc=(e,t)=>{if(typeof e!="string")return{type:"message",data:Mp(e,t)};const r=e.charAt(0);return r==="b"?{type:"message",data:ex(e.substring(1),t)}:wn[r]?e.length>1?{type:wn[r],data:e.substring(1)}:{type:wn[r]}:xl},ex=(e,t)=>{if(ZS){const r=YS(e);return Mp(r,t)}else return{base64:!0,data:e}},Mp=(e,t)=>{switch(t){case"blob":return e instanceof Blob?e:new Blob([e]);case"arraybuffer":default:return e instanceof ArrayBuffer?e:e.buffer}},Ip="",tx=(e,t)=>{const r=e.length,s=new Array(r);let i=0;e.forEach((o,c)=>{Nc(o,!1,n=>{s[c]=n,++i===r&&t(s.join(Ip))})})},rx=(e,t)=>{const r=e.split(Ip),s=[];for(let i=0;i<r.length;i++){const o=Pc(r[i],t);if(s.push(o),o.type==="error")break}return s};function sx(){return new TransformStream({transform(e,t){QS(e,r=>{const s=r.length;let i;if(s<126)i=new Uint8Array(1),new DataView(i.buffer).setUint8(0,s);else if(s<65536){i=new Uint8Array(3);const o=new DataView(i.buffer);o.setUint8(0,126),o.setUint16(1,s)}else{i=new Uint8Array(9);const o=new DataView(i.buffer);o.setUint8(0,127),o.setBigUint64(1,BigInt(s))}e.data&&typeof e.data!="string"&&(i[0]|=128),t.enqueue(i),t.enqueue(r)})}})}let ua;function on(e){return e.reduce((t,r)=>t+r.length,0)}function an(e,t){if(e[0].length===t)return e.shift();const r=new Uint8Array(t);let s=0;for(let i=0;i<t;i++)r[i]=e[0][s++],s===e[0].length&&(e.shift(),s=0);return e.length&&s<e[0].length&&(e[0]=e[0].slice(s)),r}function ix(e,t){ua||(ua=new TextDecoder);const Line truncated
Connected to remote shell.`):i.writeln(`\r
Failed to create shell: ${a.error||"Unknown error"}`)}),c.on("shell_output",a=>{a.data&&i.write(a.data)}),c.on("disconnect",()=>{i.writeln(`\r
[Disconnected]`)}),i.onData(a=>{c.emit("shell_input",{data:a})});const n=()=>{o.fit()};return window.addEventListener("resize",n),()=>{window.removeEventListener("resize",n),c.emit("shell_disconnect"),c.disconnect(),i.dispose()}},[]),v.jsxs("div",{className:"h-[calc(100vh-140px)] flex flex-col",children:[v.jsx("h1",{className:"font-serif text-3xl text-primary mb-4",children:"Remote Shell"}),v.jsx("div",{ref:e,className:"flex-1 bg-[#1a1a1a] rounded-lg border border-border overflow-hidden"})]})}function Vx(){const[e,t]=M.useState("/"),[r,s]=M.useState([]),[i,o]=M.useState(!1),[c,n]=M.useState(null),{dispatch:a}=Fe(),f=async _=>{var S,b;o(!0);try{const y=await ne.post("/files/list",{path:_});y.data.success?(s(y.data.data),t(_)):a({type:"ADD_TOAST",payload:{message:y.data.error||"Failed",type:"error"}})}catch(y){a({type:"ADD_TOAST",payload:{message:((b=(S=y.response)==null?void 0:S.data)==null?void 0:b.error)||"Failed",type:"error"}})}finally{o(!1)}};M.useEffect(()=>{f("/")},[]);const m=async _=>{var S,b;try{const y=await ne.get(`/files/view?path=${encodeURIComponent(_)}`);y.data.success&&n({path:_,content:y.data.data})}catch(y){a({type:"ADD_TOAST",payload:{message:((b=(S=y.response)==null?void 0:S.data)==null?void 0:b.error)||"Failed",type:"error"}})}},p=e.split("/").filter(Boolean);return v.jsxs("div",{children:[v.jsx("h1",{className:"font-serif text-3xl text-primary mb-6",children:"File Browser"}),v.jsxs("div",{className:"flex items-center gap-2 mb-4 text-sm",children:[v.jsx("button",{onClick:()=>f("/"),className:"text-primary hover:underline",children:"/"}),p.map((_,S)=>{const b="/"+p.slice(0,S+1).join("/");return v.jsxs("span",{className:"flex items-center gap-2",children:[v.jsx("span",{className:"text-text-muted",children:"/"}),v.jsx("button",{onClick:()=>f(b),className:"text-primary hover:underline",children:_})]},S)})]}),v.jsx("div",{className:"bg-card-bg border border-border rounded-lg overflow-hidden",children:v.jsxs("table",{className:"w-full text-sm",children:[v.jsx("thead",{children:v.jsxs("tr",{className:"border-b border-border",children:[v.jsx("th",{className:"text-left px-4 py-3 text-text-muted font-semibold text-[11px] uppercase",children:"Name"}),v.jsx("th",{className:"text-left px-4 py-3 text-text-muted font-semibold text-[11px] uppercase",children:"Size"}),v.jsx("th",{className:"text-left px-4 py-3 text-text-muted font-semibold text-[11px] uppercase",children:"Modified"}),v.jsx("th",{className:"text-left px-4 py-3 text-text-muted font-semibold text-[11px] uppercase",children:"Actions"})]})}),v.jsxs("tbody",{children:[e!=="/"&&v.jsxs("tr",{className:"border-b border-border hover:bg-hover/50 cursor-pointer",onClick:()=>{const _=e.substring(0,e.lastIndexOf("/"))||"/";f(_)},children:[v.jsx("td",{className:"px-4 py-3 text-text-primary",children:".."}),v.jsx("td",{className:"px-4 py-3",children:"-"}),v.jsx("td",{className:"px-4 py-3",children:"-"}),v.jsx("td",{className:"px-4 py-3",children:"-"})]}),i?v.jsx("tr",{children:v.jsx("td",{colSpan:4,className:"px-4 py-8 text-center text-text-muted",children:"Loading..."})}):r.map(_=>v.jsxs("tr",{className:"border-b border-border last:border-0 hover:bg-hover/50 cursor-pointer",onClick:()=>_.is_dir&&f(_.path),children:[v.jsxs("td",{className:"px-4 py-3 text-text-primary",children:[_.is_dir?"📁":"📄"," ",_.name]}),v.jsx("td",{className:"px-4 py-3 text-text-muted",children:_.is_dir?"-":qx(_.size)}),v.jsx("td",{className:"px-4 py-3 text-text-muted",children:new Date(_.mod_time).toLocaleString()}),v.jsx("td",{className:"px-4 py-3",children:!_.is_dir&&v.jsx("button",{onClick:S=>{S.stopPropagation(),m(_.path)},className:"text-xs text-primary hover:underline",children:"View"})})]},_.path))]})]})}),c&&v.jsx("div",{className:"fixed inset-0 z-[70] flex items-center justify-center bg-black/60 backdrop-blur-sm",children:v.jsxs("div",{className:"bg-card-bg border border-border rounded-xl shadow-2xl w-full mx-4 max-w-4xl max-h-[80vh] flex flex-col",children:[v.jsxs("div",{className:"flex items-center justify-between px-5 py-4 border-b border-border",children:[v.jsx("h3",{className:"font-serif text-lg text-text-primary truncate",children:c.path}),v.jsx("button",{onClick:()=>n(null),className:"text-text-muted hover:text-text-primary text-xl leading-none",children:"×"})]}),v.jsx("pre",{className:"p-5 overflow-auto flex-1 text-xs font-mono text-text-secondary bg-code-bg",children:c.content})]})})]})}function qx(e){if(e===0)return"0 B";const t=1024,r=["B","KB","MB","GB"],s=Math.floor(Math.log(e)/Math.log(t));return parseFloat((e/Math.pow(t,s)).toFixed(2))+" "+r[s]}const Kx=e=>ne.get(e).then(t=>t.data);function Xx(){const[e,t]=M.useState("battlegroup"),{dispatch:r}=Fe(),{data:s}=ct("/director/battlegroup",Kx,{refreshInterval:15e3}),i=async(o,c)=>{var n,a;try{const f=await ne.post(o,c);f.data.success?r({type:"ADD_TOAST",payload:{message:"Success",type:"success"}}):r({type:"ADD_TOAST",payload:{message:f.data.error||"Failed",type:"error"}})}catch(f){r({type:"ADD_TOAST",pa Line truncated
-32
View File
@@ -1,32 +0,0 @@
/**
* Copyright (c) 2014 The xterm.js authors. All rights reserved.
* Copyright (c) 2012-2013, Christopher Jeffrey (MIT License)
* https://github.com/chjj/term.js
* @license MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* Originally forked from (with the author's permission):
* Fabrice Bellard's javascript vt100 for jslinux:
* http://bellard.org/jslinux/
* Copyright (c) 2011 Fabrice Bellard
* The original design remains. The terminal itself
* has been extended to include xterm CSI codes, among
* other features.
*/.xterm{cursor:text;position:relative;-moz-user-select:none;user-select:none;-ms-user-select:none;-webkit-user-select:none}.xterm.focus,.xterm:focus{outline:none}.xterm .xterm-helpers{position:absolute;top:0;z-index:5}.xterm .xterm-helper-textarea{padding:0;border:0;margin:0;position:absolute;opacity:0;left:-9999em;top:0;width:0;height:0;z-index:-5;white-space:nowrap;overflow:hidden;resize:none}.xterm .composition-view{background:#000;color:#fff;display:none;position:absolute;white-space:nowrap;z-index:1}.xterm .composition-view.active{display:block}.xterm .xterm-viewport{background-color:#000;overflow-y:scroll;cursor:default;position:absolute;right:0;left:0;top:0;bottom:0}.xterm .xterm-screen{position:relative}.xterm .xterm-screen canvas{position:absolute;left:0;top:0}.xterm .xterm-scroll-area{visibility:hidden}.xterm-char-measure-element{display:inline-block;visibility:hidden;position:absolute;top:0;left:-9999em;line-height:normal}.xterm.enable-mouse-events{cursor:default}.xterm.xterm-cursor-pointer,.xterm .xterm-cursor-pointer{cursor:pointer}.xterm.column-select.focus{cursor:crosshair}.xterm .xterm-accessibility,.xterm .xterm-message{position:absolute;left:0;top:0;bottom:0;right:0;z-index:10;color:transparent;pointer-events:none}.xterm .live-region{position:absolute;left:-9999px;width:1px;height:1px;overflow:hidden}.xterm-dim{opacity:1!important}.xterm-underline-1{text-decoration:underline}.xterm-underline-2{-webkit-text-decoration:double underline;text-decoration:double underline}.xterm-underline-3{-webkit-text-decoration:wavy underline;text-decoration:wavy underline}.xterm-underline-4{-webkit-text-decoration:dotted underline;text-decoration:dotted underline}.xterm-underline-5{-webkit-text-decoration:dashed underline;text-decoration:dashed underline}.xterm-overline{text-decoration:overline}.xterm-overline.xterm-underline-1{text-decoration:overline underline}.xterm-overline.xterm-underline-2{-webkit-text-decoration:overline double underline;text-decoration:overline double underline}.xterm-overline.xterm-underline-3{-webkit-text-decoration:overline wavy underline;text-decoration:overline wavy underline}.xterm-overline.xterm-underline-4{-webkit-text-decoration:overline dotted underline;text-decoration:overline dotted underline}.xterm-overline.xterm-underline-5{-webkit-text-decoration:overline dashed underline;text-decoration:overline dashed underline}.xterm-strikethrough{text-decoration:line-through}.xterm-screen .xterm-decoration-container .xterm-decoration{z-index:6;position:absolute}.xterm-screen .xterm-decoration-container .xterm-decoration.xterm-decoration-top-layer{z-index:7}.xterm-decoration-overview-ruler{z-index:8;position:absolute;top:0;right:0;pointer-events:none}.xterm-decoration-top{z-index:2;position:relative}[data-theme=default]{--primary: #c9a24e;--primary-dark: #a8862e;--primary-light: #e0c97a;--bg: #f4f1ea;--card-bg: #ffffff;--text: #2c1810;--text-light: #6b5a4a;--text-muted: #9a8a7a;--border: #e0d5c7;--accent: #8b4513;--danger: #c0392b;--success: #27ae60;--nav-bg: #1a1a2e;--nav-text: #c9c4d0;--nav-active: #c9a24e;--hover: #f0ebe0;--shadow: 0 2px 8px rgba(44,24,16,.08)}[data-theme=atreides]{--primary: #2d5a27;--primary-dark: #1e3d19;--primary-light: #4a8c42;--bg: #f0f5ed;--card-bg: #ffffff;--text: #1a2e1a;--text-light: #3d4d3d;--text-muted: #6b7c6b;--border: #d4ddd4;--accent: #1e3d19;--danger: #8b2500;--success: #2d5a27;--nav-bg: #1a2e1a;--nav-text: #d4ddd4;--nav-active: #6abf6a;--hover: #e2ebe2;--shadow: 0 2px 8px rgba(30,61,25,.1)}[data-theme=harkonnen]{--primary: #ff6b00;--primary-dark: #cc5500;--primary-light: #ff8c33;--bg: #1a1a1a;--card-bg: #2d2d2d;--text: #e8e8e8;--text-light: #b0b0b0;--text-muted: #808080;--border: #404040;--accent: #ff4500;--danger: #ff0000;--success: #00cc44;--nav-bg: #000000;--nav-text: #cccccc;--nav-active: #ff6b00;--hover: #333333;--shadow: 0 2px 8px rgba(0,0,0,.4)}[data-theme=fremen]{--primary: #d4a853;--primary-dark: #b8913f;--primary-light: #e8c87a;--bg: #e8dcc8;--card-bg: #f5efe3;--text: #3d3428;--text-light: #5c4f3d;--text-muted: #8a7d66;--border: #d4cbb8;--accent: #8b6914;--danger: #a04000;--success: #6b8e23;--nav-bg: #2c2418;--nav-text: #d4cbb8;--nav-active: #d4a853;--hover: #e8dcc8;--shadow: 0 2px 8px rgba(44,36,24,.1)}[data-theme=bene-gesserit]{--primary: #a8a8a8;--primary-dark: #888888;--primary-light: #c8c8c8;--bg: #f8f8f8;--card-bg: #ffffff;--text: #2a2a2a;--text-light: #505050;--text-muted: #787878;--border: #e0e0e0;--accent: #606060;--danger: #c41e3a;--success: #2e8b57;--nav-bg: #1a1a1a;--nav-text: #d0d0d0;--nav-active: #ffffff;--hover: #f0f0f0;--shadow: 0 2px 8px rgba(0,0,0,.08)}[data-theme=spacing-guild]{--primary: #4a90d9;--primary-dark: #2e6ab3;--primary-light: #6baee8;--bg: #1a1a2e;--card-bg: #252540;--text: #e0e0f0;--text-light: #a0a0c0;--text-muted: #707090;--border: #3a3a50;--accent: #6b5b95;--danger: #d94545;--success: #45d985;--nav-bg: #0f0f1a;--nav-text: #b0b0d0;--nav-active: #4a90d9;--hover: #2a2a40;--shadow: 0 2px 8px rgba(0,0,0,Line truncated
-16
View File
@@ -1,16 +0,0 @@
<!doctype html>
<html lang="en" data-theme="emperor">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Dune Admin Dashboard</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=Playfair+Display:wght@700&display=swap" rel="stylesheet">
<script type="module" crossorigin src="/assets/index-9_PploUA.js"></script>
<link rel="stylesheet" crossorigin href="/assets/index-BwISaj0y.css">
</head>
<body>
<div id="root"></div>
</body>
</html>
+9 -6
View File
@@ -9,22 +9,25 @@
"preview": "vite preview"
},
"dependencies": {
"@chakra-ui/react": "^3.0.0",
"@fontsource/inter": "^5.0.0",
"@fontsource/playfair-display": "^5.0.0",
"@fontsource/roboto-mono": "^5.0.0",
"axios": "^1.6.7",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-icons": "^5.6.0",
"react-router-dom": "^6.22.0",
"axios": "^1.6.7",
"recharts": "^2.12.0",
"socket.io-client": "^4.7.4",
"swr": "^2.2.4",
"xterm": "^5.3.0",
"xterm-addon-fit": "^0.8.0",
"socket.io-client": "^4.7.4"
"xterm-addon-fit": "^0.8.0"
},
"devDependencies": {
"@types/react": "^18.2.55",
"@types/react-dom": "^18.2.19",
"@vitejs/plugin-react": "^4.2.1",
"autoprefixer": "^10.4.17",
"postcss": "^8.4.35",
"tailwindcss": "^3.4.1",
"typescript": "^5.3.3",
"vite": "^5.1.0"
}
-6
View File
@@ -1,6 +0,0 @@
export default {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
}
+22 -5
View File
@@ -1,5 +1,8 @@
import { useEffect } from 'react'
import { BrowserRouter, Routes, Route } from 'react-router-dom'
import { AppProvider } from './stores/AppContext'
import { ChakraProvider, defaultSystem } from '@chakra-ui/react'
import { AppProvider, useApp } from './stores/AppContext'
import { injectThemeVars } from './themes/inject'
import { useRealtime } from './hooks/useRealtime'
import AppShell from './components/layout/AppShell'
import Overview from './components/overview/Overview'
@@ -17,15 +20,22 @@ import Terminal from './components/shell/Terminal'
import FileBrowser from './components/files/FileBrowser'
import Director from './components/director/Director'
import Settings from './components/settings/Settings'
import Experimental from './components/experimental/Experimental'
function RealtimeInit() {
useRealtime()
return null
}
function App() {
function ThemedApp() {
const { state } = useApp()
useEffect(() => {
injectThemeVars(state.faction, state.colorMode)
}, [state.faction, state.colorMode])
return (
<AppProvider>
<ChakraProvider value={defaultSystem}>
<BrowserRouter>
<RealtimeInit />
<AppShell>
@@ -45,11 +55,18 @@ function App() {
<Route path="/files" element={<FileBrowser />} />
<Route path="/director" element={<Director />} />
<Route path="/settings" element={<Settings />} />
<Route path="/experimental" element={<Experimental />} />
</Routes>
</AppShell>
</BrowserRouter>
</AppProvider>
</ChakraProvider>
)
}
export default App
export default function App() {
return (
<AppProvider>
<ThemedApp />
</AppProvider>
)
}
+29 -17
View File
@@ -1,5 +1,7 @@
import { useState } from 'react'
import useSWR from 'swr'
import { Box, Heading, Input } from '@chakra-ui/react'
import { FiSearch } from 'react-icons/fi'
import client from '../../api/client'
import { useApp } from '../../stores/AppContext'
import DataTable from '../common/DataTable'
@@ -29,23 +31,33 @@ export default function Accounts() {
const accountList: Account[] = accountsData?.success ? accountsData.data : []
return (
<div>
<h1 className="font-serif text-3xl text-primary mb-6">Accounts</h1>
<Box>
<Heading as="h1" fontFamily="Playfair Display, serif" color="primary.DEFAULT" fontSize="2xl" mb={6}>
Accounts
</Heading>
<div className="mb-6">
<div className="relative max-w-md">
<input
type="text"
value={search}
onChange={(e) => setSearch(e.target.value)}
placeholder="Search accounts..."
className="w-full bg-card-bg border border-border rounded-lg px-4 py-2.5 pl-10 text-sm text-text-primary placeholder-text-muted focus:outline-none focus:border-primary focus:ring-1 focus:ring-primary"
/>
<svg className="absolute left-3 top-3 w-4 h-4 text-text-muted" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0" />
</svg>
</div>
</div>
<Box position="relative" maxW="md" mb={6}>
<Input
type="text"
value={search}
onChange={(e) => setSearch(e.target.value)}
placeholder="Search accounts..."
bg="card.bg"
borderColor="border"
borderRadius="lg"
px={4}
py={2.5}
pl={10}
fontSize="sm"
color="fg"
_placeholder={{ color: 'fg.muted' }}
_focus={{ borderColor: 'primary.DEFAULT', boxShadow: '0 0 0 1px var(--chakra-colors-primary-DEFAULT)' }}
_focusVisible={{ outline: 'none' }}
/>
<Box position="absolute" left={3} top="50%" transform="translateY(-50%)" color="fg.muted">
<FiSearch size={16} />
</Box>
</Box>
<DataTable
columns={[
@@ -57,6 +69,6 @@ export default function Accounts() {
data={accountList}
loading={isLoading}
/>
</div>
</Box>
)
}
+580 -216
View File
@@ -1,4 +1,9 @@
import { useState } from 'react'
import {
Box, Flex, Heading, Text, Button, Input, Select, Textarea,
SimpleGrid, Card, Tabs, Table, VStack, createListCollection,
} from '@chakra-ui/react'
import { FiAlertTriangle } from 'react-icons/fi'
import client from '../../api/client'
import { useApp } from '../../stores/AppContext'
@@ -6,46 +11,96 @@ const SCOPE_OPTIONS = ['all', 'server', 'partition']
const SERVER_OPTIONS = ['na', 'eu', 'sea', 'sa', 'oc']
const PARTITION_OPTIONS = ['parrish', 'sietch', 'bazar']
const serverCollection = createListCollection({
items: SERVER_OPTIONS.map((s) => ({ value: s, label: s.toUpperCase() })),
})
const partitionCollection = createListCollection({
items: PARTITION_OPTIONS.map((p) => ({ value: p, label: p })),
})
const itemFieldCollection = createListCollection({
items: [
{ value: 'stack_size', label: 'stack_size' },
{ value: 'quality_level', label: 'quality_level' },
{ value: 'durability', label: 'durability' },
{ value: 'ammo', label: 'ammo' },
],
})
const demoStateCollection = createListCollection({
items: [
{ value: 'true', label: 'Demo' },
{ value: 'false', label: 'Normal' },
],
})
const limitCollection = createListCollection({
items: [10, 25, 50, 100, 250].map((n) => ({ value: String(n), label: `${n} entries` })),
})
export default function AdminTools() {
const [tab, setTab] = useState<'broadcast' | 'economy' | 'world' | 'character' | 'functions' | 'raw' | 'audit'>('broadcast')
const { dispatch } = useApp()
return (
<div>
<h1 className="font-serif text-3xl text-primary mb-6">Admin Tools</h1>
<Box>
<Heading as="h1" fontFamily="Playfair Display, serif" fontSize="3xl" color="primary.DEFAULT" mb={6}>
Admin Tools
</Heading>
<div className="flex gap-1 mb-6 border-b border-border overflow-x-auto no-scrollbar">
{([
{ key: 'broadcast', label: 'Broadcast' },
{ key: 'economy', label: 'Economy' },
{ key: 'world', label: 'World' },
{ key: 'character', label: 'Character' },
{ key: 'functions', label: 'Functions' },
{ key: 'raw', label: 'Raw Query' },
{ key: 'audit', label: 'Audit Log' },
] as const).map((t) => (
<button
key={t.key}
onClick={() => setTab(t.key as any)}
className={`px-4 py-2.5 text-sm font-medium border-b-2 transition-colors whitespace-nowrap ${
tab === t.key
? 'text-primary border-primary'
: 'text-text-muted border-transparent hover:text-text-primary'
}`}
>
{t.label}
</button>
))}
</div>
<Tabs.Root value={tab} onValueChange={(e) => setTab(e.value as any)} mb={6}>
<Tabs.List borderBottomWidth="1px" borderColor="border" overflowX="auto">
{([
{ key: 'broadcast', label: 'Broadcast' },
{ key: 'economy', label: 'Economy' },
{ key: 'world', label: 'World' },
{ key: 'character', label: 'Character' },
{ key: 'functions', label: 'Functions' },
{ key: 'raw', label: 'Raw Query' },
{ key: 'audit', label: 'Audit Log' },
] as const).map((t) => (
<Tabs.Trigger
key={t.key}
value={t.key}
px={4}
py={2.5}
fontSize="sm"
fontWeight="medium"
whiteSpace="nowrap"
_selected={{ color: 'primary.DEFAULT', borderColor: 'primary.DEFAULT' }}
color="fg.muted"
borderBottomWidth="2px"
borderColor="transparent"
>
{t.label}
</Tabs.Trigger>
))}
</Tabs.List>
{tab === 'broadcast' && <BroadcastTab dispatch={dispatch} />}
{tab === 'economy' && <EconomyTab dispatch={dispatch} />}
{tab === 'world' && <WorldTab dispatch={dispatch} />}
{tab === 'character' && <CharacterTab dispatch={dispatch} />}
{tab === 'functions' && <FunctionsTab dispatch={dispatch} />}
{tab === 'raw' && <RawQueryTab dispatch={dispatch} />}
{tab === 'audit' && <AuditLogTab dispatch={dispatch} />}
</div>
<Tabs.Content value="broadcast" pt={4}>
<BroadcastTab dispatch={dispatch} />
</Tabs.Content>
<Tabs.Content value="economy" pt={4}>
<EconomyTab dispatch={dispatch} />
</Tabs.Content>
<Tabs.Content value="world" pt={4}>
<WorldTab dispatch={dispatch} />
</Tabs.Content>
<Tabs.Content value="character" pt={4}>
<CharacterTab dispatch={dispatch} />
</Tabs.Content>
<Tabs.Content value="functions" pt={4}>
<FunctionsTab dispatch={dispatch} />
</Tabs.Content>
<Tabs.Content value="raw" pt={4}>
<RawQueryTab dispatch={dispatch} />
</Tabs.Content>
<Tabs.Content value="audit" pt={4}>
<AuditLogTab dispatch={dispatch} />
</Tabs.Content>
</Tabs.Root>
</Box>
)
}
@@ -81,55 +136,94 @@ function BroadcastTab({ dispatch }: { dispatch: any }) {
}
return (
<div className="max-w-xl">
<div className="bg-card-bg border border-border rounded-lg p-5 space-y-4">
<div>
<label className="block text-sm text-text-muted mb-2">Scope</label>
<div className="flex gap-2">
{SCOPE_OPTIONS.map((s) => (
<button
key={s}
onClick={() => setScope(s)}
className={`px-3 py-1.5 rounded text-xs font-medium border capitalize ${
scope === s
? 'bg-primary/10 border-primary text-primary'
: 'bg-card-bg border-border text-text-muted hover:text-text-primary'
}`}
>
{s}
</button>
))}
</div>
</div>
<Box maxW="xl">
<Card.Root borderRadius="lg" boxShadow="card" bg="card.bg">
<Card.Body p={5}>
<VStack gap={4} align="stretch">
<Box>
<Text fontSize="sm" color="fg.muted" mb={2}>Scope</Text>
<Flex gap={2}>
{SCOPE_OPTIONS.map((s) => (
<Button
key={s}
onClick={() => setScope(s)}
size="xs"
textTransform="capitalize"
variant={scope === s ? 'solid' : 'outline'}
bg={scope === s ? 'primary.subtle' : 'transparent'}
color={scope === s ? 'primary.DEFAULT' : 'fg.muted'}
borderColor={scope === s ? 'primary.DEFAULT' : 'border'}
borderRadius="md"
_hover={{ color: 'fg' }}
>
{s}
</Button>
))}
</Flex>
</Box>
{scope !== 'all' && (
<div>
<label className="block text-sm text-text-muted mb-2">Server</label>
<select value={server} onChange={(e) => setServer(e.target.value)} className="bg-card-bg border border-border rounded px-3 py-2 text-sm text-text-primary">
{SERVER_OPTIONS.map((s) => <option key={s} value={s}>{s.toUpperCase()}</option>)}
</select>
</div>
)}
{scope !== 'all' && (
<Box>
<Text fontSize="sm" color="fg.muted" mb={2}>Server</Text>
<Select.Root collection={serverCollection} value={[server]} onValueChange={(e) => setServer(e.value[0])}>
<Select.Trigger bg="card.bg" borderColor="border" borderRadius="md" fontSize="sm">
<Select.ValueText />
</Select.Trigger>
<Select.Content>
{serverCollection.items.map((item) => (
<Select.Item item={item} key={item.value}>{item.label}</Select.Item>
))}
</Select.Content>
</Select.Root>
</Box>
)}
{scope === 'partition' && (
<div>
<label className="block text-sm text-text-muted mb-2">Partition</label>
<select value={partition} onChange={(e) => setPartition(e.target.value)} className="bg-card-bg border border-border rounded px-3 py-2 text-sm text-text-primary">
{PARTITION_OPTIONS.map((p) => <option key={p} value={p}>{p}</option>)}
</select>
</div>
)}
{scope === 'partition' && (
<Box>
<Text fontSize="sm" color="fg.muted" mb={2}>Partition</Text>
<Select.Root collection={partitionCollection} value={[partition]} onValueChange={(e) => setPartition(e.value[0])}>
<Select.Trigger bg="card.bg" borderColor="border" borderRadius="md" fontSize="sm">
<Select.ValueText />
</Select.Trigger>
<Select.Content>
{partitionCollection.items.map((item) => (
<Select.Item item={item} key={item.value}>{item.label}</Select.Item>
))}
</Select.Content>
</Select.Root>
</Box>
)}
<div>
<label className="block text-sm text-text-muted mb-2">Message</label>
<textarea value={message} onChange={(e) => setMessage(e.target.value)} rows={4} className="w-full bg-card-bg border border-border rounded-lg px-4 py-3 text-sm text-text-primary placeholder-text-muted focus:outline-none focus:border-primary focus:ring-1 focus:ring-primary resize-y" placeholder="Enter broadcast message..." />
</div>
<Box>
<Text fontSize="sm" color="fg.muted" mb={2}>Message</Text>
<Textarea
value={message}
onChange={(e) => setMessage(e.target.value)}
rows={4}
bg="card.bg"
borderColor="border"
borderRadius="lg"
fontSize="sm"
resize="vertical"
placeholder="Enter broadcast message..."
_placeholder={{ color: 'fg.muted' }}
/>
</Box>
<button onClick={handleSend} disabled={sending || !message.trim()} className="px-4 py-2 bg-primary text-white rounded-lg text-sm font-medium hover:bg-primary-dark disabled:opacity-50 transition-colors">
{sending ? 'Sending...' : 'Send Broadcast'}
</button>
</div>
</div>
<Button
onClick={handleSend}
disabled={sending || !message.trim()}
colorPalette="primary"
borderRadius="lg"
fontSize="sm"
fontWeight="medium"
>
{sending ? 'Sending...' : 'Send Broadcast'}
</Button>
</VStack>
</Card.Body>
</Card.Root>
</Box>
)
}
@@ -152,30 +246,72 @@ function EconomyTab({ dispatch }: { dispatch: any }) {
}
return (
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
<div className="bg-card-bg border border-border rounded-lg p-5 space-y-3">
<h3 className="font-medium text-text-primary">Add Item</h3>
<input value={playerId} onChange={(e) => setPlayerId(e.target.value)} placeholder="Player ID" className="w-full bg-card-bg border border-border rounded px-3 py-2 text-sm" />
<input value={itemForm.template_id} onChange={(e) => setItemForm({ ...itemForm, template_id: e.target.value })} placeholder="Template ID" className="w-full bg-card-bg border border-border rounded px-3 py-2 text-sm" />
<input value={itemForm.stack_size} onChange={(e) => setItemForm({ ...itemForm, stack_size: e.target.value })} placeholder="Stack Size" className="w-full bg-card-bg border border-border rounded px-3 py-2 text-sm" />
<input value={itemForm.quality} onChange={(e) => setItemForm({ ...itemForm, quality: e.target.value })} placeholder="Quality" className="w-full bg-card-bg border border-border rounded px-3 py-2 text-sm" />
<input value={itemForm.inventory_id} onChange={(e) => setItemForm({ ...itemForm, inventory_id: e.target.value })} placeholder="Inventory ID" className="w-full bg-card-bg border border-border rounded px-3 py-2 text-sm" />
<button onClick={() => post('/items/add', { player_id: parseInt(playerId), template_id: itemForm.template_id, stack_size: parseInt(itemForm.stack_size), quality_level: parseInt(itemForm.quality), inventory_id: parseInt(itemForm.inventory_id) || undefined })} className="px-3 py-1.5 rounded text-xs bg-primary/10 border border-primary/20 text-primary">Add Item</button>
</div>
<SimpleGrid columns={{ base: 1, lg: 2 }} gap={6}>
<Card.Root borderRadius="lg" boxShadow="card" bg="card.bg">
<Card.Body p={5}>
<VStack gap={3} align="stretch">
<Text fontWeight="medium">Add Item</Text>
<Input value={playerId} onChange={(e) => setPlayerId(e.target.value)} placeholder="Player ID" bg="card.bg" borderColor="border" borderRadius="md" fontSize="sm" />
<Input value={itemForm.template_id} onChange={(e) => setItemForm({ ...itemForm, template_id: e.target.value })} placeholder="Template ID" bg="card.bg" borderColor="border" borderRadius="md" fontSize="sm" />
<Input value={itemForm.stack_size} onChange={(e) => setItemForm({ ...itemForm, stack_size: e.target.value })} placeholder="Stack Size" bg="card.bg" borderColor="border" borderRadius="md" fontSize="sm" />
<Input value={itemForm.quality} onChange={(e) => setItemForm({ ...itemForm, quality: e.target.value })} placeholder="Quality" bg="card.bg" borderColor="border" borderRadius="md" fontSize="sm" />
<Input value={itemForm.inventory_id} onChange={(e) => setItemForm({ ...itemForm, inventory_id: e.target.value })} placeholder="Inventory ID" bg="card.bg" borderColor="border" borderRadius="md" fontSize="sm" />
<Button
onClick={() => post('/items/add', { player_id: parseInt(playerId), template_id: itemForm.template_id, stack_size: parseInt(itemForm.stack_size), quality_level: parseInt(itemForm.quality), inventory_id: parseInt(itemForm.inventory_id) || undefined })}
size="xs"
variant="outline"
borderRadius="md"
color="primary.DEFAULT"
borderColor="primary.DEFAULT"
>
Add Item
</Button>
</VStack>
</Card.Body>
</Card.Root>
<div className="bg-card-bg border border-border rounded-lg p-5 space-y-3">
<h3 className="font-medium text-text-primary">Edit Item</h3>
<input value={editForm.item_id} onChange={(e) => setEditForm({ ...editForm, item_id: e.target.value })} placeholder="Item ID" className="w-full bg-card-bg border border-border rounded px-3 py-2 text-sm" />
<select value={editForm.field} onChange={(e) => setEditForm({ ...editForm, field: e.target.value })} className="w-full bg-card-bg border border-border rounded px-3 py-2 text-sm">
{['stack_size', 'quality_level', 'durability', 'ammo'].map((f) => <option key={f} value={f}>{f}</option>)}
</select>
<input value={editForm.value} onChange={(e) => setEditForm({ ...editForm, value: e.target.value })} placeholder="New value" className="w-full bg-card-bg border border-border rounded px-3 py-2 text-sm" />
<div className="flex gap-2">
<button onClick={() => post(`/items/${editForm.item_id}`, { [editForm.field]: editForm.value })} className="px-3 py-1.5 rounded text-xs bg-primary/10 border border-primary/20 text-primary">Update</button>
<button onClick={() => post(`/items/${editForm.item_id}`, {})} className="px-3 py-1.5 rounded text-xs bg-danger/10 border border-danger/30 text-danger">Delete</button>
</div>
</div>
</div>
<Card.Root borderRadius="lg" boxShadow="card" bg="card.bg">
<Card.Body p={5}>
<VStack gap={3} align="stretch">
<Text fontWeight="medium">Edit Item</Text>
<Input value={editForm.item_id} onChange={(e) => setEditForm({ ...editForm, item_id: e.target.value })} placeholder="Item ID" bg="card.bg" borderColor="border" borderRadius="md" fontSize="sm" />
<Select.Root collection={itemFieldCollection} value={[editForm.field]} onValueChange={(e) => setEditForm({ ...editForm, field: e.value[0] })}>
<Select.Trigger bg="card.bg" borderColor="border" borderRadius="md" fontSize="sm">
<Select.ValueText />
</Select.Trigger>
<Select.Content>
{itemFieldCollection.items.map((item) => (
<Select.Item item={item} key={item.value}>{item.label}</Select.Item>
))}
</Select.Content>
</Select.Root>
<Input value={editForm.value} onChange={(e) => setEditForm({ ...editForm, value: e.target.value })} placeholder="New value" bg="card.bg" borderColor="border" borderRadius="md" fontSize="sm" />
<Flex gap={2}>
<Button
onClick={() => post(`/items/${editForm.item_id}`, { [editForm.field]: editForm.value })}
size="xs"
variant="outline"
borderRadius="md"
color="primary.DEFAULT"
borderColor="primary.DEFAULT"
>
Update
</Button>
<Button
onClick={() => post(`/items/${editForm.item_id}`, {})}
size="xs"
variant="outline"
borderRadius="md"
color="danger.DEFAULT"
borderColor="danger.DEFAULT"
>
Delete
</Button>
</Flex>
</VStack>
</Card.Body>
</Card.Root>
</SimpleGrid>
)
}
@@ -196,32 +332,80 @@ function WorldTab({ dispatch }: { dispatch: any }) {
}
return (
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
<div className="bg-card-bg border border-border rounded-lg p-5 space-y-3">
<h3 className="font-medium text-text-primary">Teleport Player</h3>
<input value={tpForm.fls_id} onChange={(e) => setTpForm({ ...tpForm, fls_id: e.target.value })} placeholder="FLS ID / Account ID" className="w-full bg-card-bg border border-border rounded px-3 py-2 text-sm" />
<input value={tpForm.partition} onChange={(e) => setTpForm({ ...tpForm, partition: e.target.value })} placeholder="Partition ID" className="w-full bg-card-bg border border-border rounded px-3 py-2 text-sm" />
<div className="grid grid-cols-3 gap-2">
<input type="number" value={tpForm.x} onChange={(e) => setTpForm({ ...tpForm, x: e.target.value })} placeholder="X" className="bg-card-bg border border-border rounded px-3 py-2 text-sm" />
<input type="number" value={tpForm.y} onChange={(e) => setTpForm({ ...tpForm, y: e.target.value })} placeholder="Y" className="bg-card-bg border border-border rounded px-3 py-2 text-sm" />
<input type="number" value={tpForm.z} onChange={(e) => setTpForm({ ...tpForm, z: e.target.value })} placeholder="Z" className="bg-card-bg border border-border rounded px-3 py-2 text-sm" />
</div>
<button onClick={() => post('/teleport', { fls_id: parseInt(tpForm.fls_id), partition_id: tpForm.partition, x: parseFloat(tpForm.x) || 0, y: parseFloat(tpForm.y) || 0, z: parseFloat(tpForm.z) || 0 })} className="px-3 py-1.5 rounded text-xs bg-primary/10 border border-primary/20 text-primary">Teleport</button>
</div>
<SimpleGrid columns={{ base: 1, lg: 2 }} gap={6}>
<Card.Root borderRadius="lg" boxShadow="card" bg="card.bg">
<Card.Body p={5}>
<VStack gap={3} align="stretch">
<Text fontWeight="medium">Teleport Player</Text>
<Input value={tpForm.fls_id} onChange={(e) => setTpForm({ ...tpForm, fls_id: e.target.value })} placeholder="FLS ID / Account ID" bg="card.bg" borderColor="border" borderRadius="md" fontSize="sm" />
<Input value={tpForm.partition} onChange={(e) => setTpForm({ ...tpForm, partition: e.target.value })} placeholder="Partition ID" bg="card.bg" borderColor="border" borderRadius="md" fontSize="sm" />
<Flex gap={2}>
<Input type="number" value={tpForm.x} onChange={(e) => setTpForm({ ...tpForm, x: e.target.value })} placeholder="X" bg="card.bg" borderColor="border" borderRadius="md" fontSize="sm" />
<Input type="number" value={tpForm.y} onChange={(e) => setTpForm({ ...tpForm, y: e.target.value })} placeholder="Y" bg="card.bg" borderColor="border" borderRadius="md" fontSize="sm" />
<Input type="number" value={tpForm.z} onChange={(e) => setTpForm({ ...tpForm, z: e.target.value })} placeholder="Z" bg="card.bg" borderColor="border" borderRadius="md" fontSize="sm" />
</Flex>
<Button
onClick={() => post('/teleport', { fls_id: parseInt(tpForm.fls_id), partition_id: tpForm.partition, x: parseFloat(tpForm.x) || 0, y: parseFloat(tpForm.y) || 0, z: parseFloat(tpForm.z) || 0 })}
size="xs"
variant="outline"
borderRadius="md"
color="primary.DEFAULT"
borderColor="primary.DEFAULT"
>
Teleport
</Button>
</VStack>
</Card.Body>
</Card.Root>
<div className="bg-card-bg border border-border rounded-lg p-5 space-y-3">
<h3 className="font-medium text-text-primary">Spice Control</h3>
<div className="flex gap-2">
<button onClick={() => post('/spice/reset', {})} className="px-3 py-1.5 rounded text-xs bg-primary/10 border border-primary/20 text-primary">Reset Spice Fields</button>
<button onClick={() => post('/spice/spawn', {})} className="px-3 py-1.5 rounded text-xs bg-primary/10 border border-primary/20 text-primary">Force Spawn</button>
</div>
</div>
<Card.Root borderRadius="lg" boxShadow="card" bg="card.bg">
<Card.Body p={5}>
<VStack gap={3} align="stretch">
<Text fontWeight="medium">Spice Control</Text>
<Flex gap={2}>
<Button
onClick={() => post('/spice/reset', {})}
size="xs"
variant="outline"
borderRadius="md"
color="primary.DEFAULT"
borderColor="primary.DEFAULT"
>
Reset Spice Fields
</Button>
<Button
onClick={() => post('/spice/spawn', {})}
size="xs"
variant="outline"
borderRadius="md"
color="primary.DEFAULT"
borderColor="primary.DEFAULT"
>
Force Spawn
</Button>
</Flex>
</VStack>
</Card.Body>
</Card.Root>
<div className="bg-card-bg border border-border rounded-lg p-5 space-y-3">
<h3 className="font-medium text-text-primary">Partitions</h3>
<button onClick={() => client.get('/partitions').then((r) => dispatch({ type: 'ADD_TOAST', payload: { message: `Partitions loaded`, type: 'info' } }))} className="px-3 py-1.5 rounded text-xs bg-primary/10 border border-primary/20 text-primary">List Partitions</button>
</div>
</div>
<Card.Root borderRadius="lg" boxShadow="card" bg="card.bg">
<Card.Body p={5}>
<VStack gap={3} align="stretch">
<Text fontWeight="medium">Partitions</Text>
<Button
onClick={() => client.get('/partitions').then((r) => dispatch({ type: 'ADD_TOAST', payload: { message: 'Partitions loaded', type: 'info' } }))}
size="xs"
variant="outline"
borderRadius="md"
color="primary.DEFAULT"
borderColor="primary.DEFAULT"
>
List Partitions
</Button>
</VStack>
</Card.Body>
</Card.Root>
</SimpleGrid>
)
}
@@ -244,32 +428,86 @@ function CharacterTab({ dispatch }: { dispatch: any }) {
}
return (
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
<div className="bg-card-bg border border-border rounded-lg p-5 space-y-3">
<h3 className="font-medium text-text-primary">Rename Character</h3>
<input value={charId} onChange={(e) => setCharId(e.target.value)} placeholder="Account ID / Character ID" className="w-full bg-card-bg border border-border rounded px-3 py-2 text-sm" />
<input value={newName} onChange={(e) => setNewName(e.target.value)} placeholder="New Name" className="w-full bg-card-bg border border-border rounded px-3 py-2 text-sm" />
<button onClick={() => post(`/characters/${charId}/name`, { name: newName })} className="px-3 py-1.5 rounded text-xs bg-primary/10 border border-primary/20 text-primary">Rename</button>
</div>
<SimpleGrid columns={{ base: 1, lg: 2 }} gap={6}>
<Card.Root borderRadius="lg" boxShadow="card" bg="card.bg">
<Card.Body p={5}>
<VStack gap={3} align="stretch">
<Text fontWeight="medium">Rename Character</Text>
<Input value={charId} onChange={(e) => setCharId(e.target.value)} placeholder="Account ID / Character ID" bg="card.bg" borderColor="border" borderRadius="md" fontSize="sm" />
<Input value={newName} onChange={(e) => setNewName(e.target.value)} placeholder="New Name" bg="card.bg" borderColor="border" borderRadius="md" fontSize="sm" />
<Button
onClick={() => post(`/characters/${charId}/name`, { name: newName })}
size="xs"
variant="outline"
borderRadius="md"
color="primary.DEFAULT"
borderColor="primary.DEFAULT"
>
Rename
</Button>
</VStack>
</Card.Body>
</Card.Root>
<div className="bg-card-bg border border-border rounded-lg p-5 space-y-3">
<h3 className="font-medium text-text-primary">Demo State</h3>
<input value={charId} onChange={(e) => setCharId(e.target.value)} placeholder="Account ID" className="w-full bg-card-bg border border-border rounded px-3 py-2 text-sm" />
<select value={demoState} onChange={(e) => setDemoState(e.target.value)} className="w-full bg-card-bg border border-border rounded px-3 py-2 text-sm">
<option value="true">Demo</option>
<option value="false">Normal</option>
</select>
<button onClick={() => post(`/accounts/${charId}/demo`, { demo: demoState === 'true' })} className="px-3 py-1.5 rounded text-xs bg-primary/10 border border-primary/20 text-primary">Set Demo State</button>
</div>
<Card.Root borderRadius="lg" boxShadow="card" bg="card.bg">
<Card.Body p={5}>
<VStack gap={3} align="stretch">
<Text fontWeight="medium">Demo State</Text>
<Input value={charId} onChange={(e) => setCharId(e.target.value)} placeholder="Account ID" bg="card.bg" borderColor="border" borderRadius="md" fontSize="sm" />
<Select.Root collection={demoStateCollection} value={[demoState]} onValueChange={(e) => setDemoState(e.value[0])}>
<Select.Trigger bg="card.bg" borderColor="border" borderRadius="md" fontSize="sm">
<Select.ValueText />
</Select.Trigger>
<Select.Content>
{demoStateCollection.items.map((item) => (
<Select.Item item={item} key={item.value}>{item.label}</Select.Item>
))}
</Select.Content>
</Select.Root>
<Button
onClick={() => post(`/accounts/${charId}/demo`, { demo: demoState === 'true' })}
size="xs"
variant="outline"
borderRadius="md"
color="primary.DEFAULT"
borderColor="primary.DEFAULT"
>
Set Demo State
</Button>
</VStack>
</Card.Body>
</Card.Root>
<div className="bg-card-bg border border-border rounded-lg p-5 space-y-3">
<h3 className="font-medium text-text-primary">Danger Zone</h3>
<div className="flex flex-wrap gap-2">
<button onClick={() => { if (confirm('Delete character?')) post(`/characters/${charId}`, {}) }} className="px-3 py-1.5 rounded text-xs bg-danger/10 border border-danger/30 text-danger">Delete Character</button>
<button onClick={() => { if (confirm('Delete account?')) post(`/accounts/${charId}`, {}) }} className="px-3 py-1.5 rounded text-xs bg-danger/10 border border-danger/30 text-danger">Delete Account</button>
</div>
</div>
</div>
<Card.Root borderRadius="lg" boxShadow="card" bg="card.bg">
<Card.Body p={5}>
<VStack gap={3} align="stretch">
<Text fontWeight="medium">Danger Zone</Text>
<Flex wrap="wrap" gap={2}>
<Button
onClick={() => { if (confirm('Delete character?')) post(`/characters/${charId}`, {}) }}
size="xs"
variant="outline"
borderRadius="md"
color="danger.DEFAULT"
borderColor="danger.DEFAULT"
>
Delete Character
</Button>
<Button
onClick={() => { if (confirm('Delete account?')) post(`/accounts/${charId}`, {}) }}
size="xs"
variant="outline"
borderRadius="md"
color="danger.DEFAULT"
borderColor="danger.DEFAULT"
>
Delete Account
</Button>
</Flex>
</VStack>
</Card.Body>
</Card.Root>
</SimpleGrid>
)
}
@@ -299,28 +537,79 @@ function FunctionsTab({ dispatch }: { dispatch: any }) {
}
return (
<div className="max-w-2xl">
<div className="bg-card-bg border border-border rounded-lg p-5 space-y-4">
<div className="grid grid-cols-2 gap-4">
<div>
<label className="block text-sm text-text-muted mb-2">Schema (optional)</label>
<input value={schema} onChange={(e) => setSchema(e.target.value)} className="w-full bg-card-bg border border-border rounded-lg px-4 py-2 text-sm text-text-primary" placeholder="e.g., public" />
</div>
<div>
<label className="block text-sm text-text-muted mb-2">Function Name</label>
<input value={funcName} onChange={(e) => setFuncName(e.target.value)} className="w-full bg-card-bg border border-border rounded-lg px-4 py-2 text-sm text-text-primary" placeholder="e.g., get_player_stats" />
</div>
</div>
<div>
<label className="block text-sm text-text-muted mb-2">Arguments (JSON)</label>
<textarea value={args} onChange={(e) => setArgs(e.target.value)} rows={4} className="w-full bg-card-bg border border-border rounded-lg px-4 py-3 text-sm font-mono text-text-primary focus:outline-none focus:border-primary focus:ring-1 focus:ring-primary resize-y" />
</div>
<button onClick={handleExecute} disabled={running || !funcName} className="px-4 py-2 bg-primary text-white rounded-lg text-sm font-medium hover:bg-primary-dark disabled:opacity-50 transition-colors">
{running ? 'Running...' : 'Execute'}
</button>
{result && <pre className="mt-4 text-xs font-mono bg-code-bg p-4 rounded overflow-auto text-text-secondary">{result}</pre>}
</div>
</div>
<Box maxW="2xl">
<Card.Root borderRadius="lg" boxShadow="card" bg="card.bg">
<Card.Body p={5}>
<VStack gap={4} align="stretch">
<SimpleGrid columns={2} gap={4}>
<Box>
<Text fontSize="sm" color="fg.muted" mb={2}>Schema (optional)</Text>
<Input
value={schema}
onChange={(e) => setSchema(e.target.value)}
bg="card.bg"
borderColor="border"
borderRadius="lg"
fontSize="sm"
placeholder="e.g., public"
/>
</Box>
<Box>
<Text fontSize="sm" color="fg.muted" mb={2}>Function Name</Text>
<Input
value={funcName}
onChange={(e) => setFuncName(e.target.value)}
bg="card.bg"
borderColor="border"
borderRadius="lg"
fontSize="sm"
placeholder="e.g., get_player_stats"
/>
</Box>
</SimpleGrid>
<Box>
<Text fontSize="sm" color="fg.muted" mb={2}>Arguments (JSON)</Text>
<Textarea
value={args}
onChange={(e) => setArgs(e.target.value)}
rows={4}
bg="card.bg"
borderColor="border"
borderRadius="lg"
fontSize="sm"
fontFamily="Roboto Mono, monospace"
resize="vertical"
/>
</Box>
<Button
onClick={handleExecute}
disabled={running || !funcName}
colorPalette="primary"
borderRadius="lg"
fontSize="sm"
fontWeight="medium"
>
{running ? 'Running...' : 'Execute'}
</Button>
{result && (
<Box
as="pre"
mt={4}
fontSize="xs"
fontFamily="Roboto Mono, monospace"
bg="code.bg"
p={4}
borderRadius="md"
overflow="auto"
color="fg.muted"
>
{result}
</Box>
)}
</VStack>
</Card.Body>
</Card.Root>
</Box>
)
}
@@ -347,19 +636,59 @@ function RawQueryTab({ dispatch }: { dispatch: any }) {
}
return (
<div className="max-w-3xl">
<div className="bg-card-bg border border-border rounded-lg p-5 space-y-4">
<div className="flex items-center justify-between">
<label className="text-sm text-text-muted">SQL Query (Read-Only SELECT)</label>
<span className="text-[10px] text-text-muted uppercase tracking-wider bg-danger/10 px-2 py-0.5 rounded border border-danger/20">Read Only</span>
</div>
<textarea value={query} onChange={(e) => setQuery(e.target.value)} rows={6} className="w-full bg-card-bg border border-border rounded-lg px-4 py-3 text-sm font-mono text-text-primary focus:outline-none focus:border-primary focus:ring-1 focus:ring-primary resize-y" placeholder="SELECT * FROM public.characters LIMIT 10;" />
<button onClick={handleRun} disabled={running || !query.trim()} className="px-4 py-2 bg-primary text-white rounded-lg text-sm font-medium hover:bg-primary-dark disabled:opacity-50 transition-colors">
{running ? 'Running...' : 'Run Query'}
</button>
{result && <pre className="mt-4 text-xs font-mono bg-code-bg p-4 rounded overflow-auto text-text-secondary">{result}</pre>}
</div>
</div>
<Box maxW="3xl">
<Card.Root borderRadius="lg" boxShadow="card" bg="card.bg">
<Card.Body p={5}>
<VStack gap={4} align="stretch">
<Flex align="center" justify="space-between">
<Text fontSize="sm" color="fg.muted">SQL Query (Read-Only SELECT)</Text>
<Text fontSize="10px" color="danger.DEFAULT" textTransform="uppercase" letterSpacing="wider" bg="danger.subtle" px={2} py={0.5} borderRadius="md" borderWidth="1px" borderColor="danger.DEFAULT">
<FiAlertTriangle style={{ display: 'inline', marginRight: 4 }} />
Read Only
</Text>
</Flex>
<Textarea
value={query}
onChange={(e) => setQuery(e.target.value)}
rows={6}
bg="card.bg"
borderColor="border"
borderRadius="lg"
fontSize="sm"
fontFamily="Roboto Mono, monospace"
resize="vertical"
placeholder="SELECT * FROM public.characters LIMIT 10;"
_placeholder={{ color: 'fg.muted' }}
/>
<Button
onClick={handleRun}
disabled={running || !query.trim()}
colorPalette="primary"
borderRadius="lg"
fontSize="sm"
fontWeight="medium"
>
{running ? 'Running...' : 'Run Query'}
</Button>
{result && (
<Box
as="pre"
mt={4}
fontSize="xs"
fontFamily="Roboto Mono, monospace"
bg="code.bg"
p={4}
borderRadius="md"
overflow="auto"
color="fg.muted"
>
{result}
</Box>
)}
</VStack>
</Card.Body>
</Card.Root>
</Box>
)
}
@@ -381,39 +710,74 @@ function AuditLogTab({ dispatch }: { dispatch: any }) {
}
return (
<div>
<div className="flex items-center gap-4 mb-4">
<button onClick={load} disabled={loading} className="px-4 py-2 bg-primary text-white rounded-lg text-sm font-medium hover:bg-primary-dark disabled:opacity-50 transition-colors">
<Box>
<Flex align="center" gap={4} mb={4}>
<Button
onClick={load}
disabled={loading}
colorPalette="primary"
borderRadius="lg"
fontSize="sm"
fontWeight="medium"
>
{loading ? 'Loading...' : 'Load Logs'}
</button>
<select value={limit} onChange={(e) => setLimit(Number(e.target.value))} className="bg-card-bg border border-border rounded px-3 py-2 text-sm text-text-primary">
{[10, 25, 50, 100, 250].map((n) => <option key={n} value={n}>{n} entries</option>)}
</select>
</div>
<div className="overflow-x-auto rounded-lg border border-border">
<table className="w-full text-sm">
<thead>
<tr className="border-b border-border">
<th className="text-left px-4 py-3 text-text-muted font-semibold text-[11px] uppercase">Time</th>
<th className="text-left px-4 py-3 text-text-muted font-semibold text-[11px] uppercase">Admin</th>
<th className="text-left px-4 py-3 text-text-muted font-semibold text-[11px] uppercase">Action</th>
<th className="text-left px-4 py-3 text-text-muted font-semibold text-[11px] uppercase">Target</th>
<th className="text-left px-4 py-3 text-text-muted font-semibold text-[11px] uppercase">Details</th>
</tr>
</thead>
<tbody>
{logs.map((log, i) => (
<tr key={i} className="border-b border-border last:border-0 hover:bg-hover/50">
<td className="px-4 py-3 text-text-muted text-xs">{new Date(log.timestamp).toLocaleString()}</td>
<td className="px-4 py-3">{log.admin_name}</td>
<td className="px-4 py-3"><span className="px-2 py-0.5 rounded text-[11px] font-semibold bg-primary/10 text-primary border border-primary/20">{log.action}</span></td>
<td className="px-4 py-3">{log.target_type}: {log.target_id}</td>
<td className="px-4 py-3 text-xs text-text-muted max-w-md truncate">{JSON.stringify(log.details)}</td>
</tr>
</Button>
<Select.Root collection={limitCollection} value={[String(limit)]} onValueChange={(e) => setLimit(Number(e.value[0]))}>
<Select.Trigger bg="card.bg" borderColor="border" borderRadius="md" fontSize="sm">
<Select.ValueText />
</Select.Trigger>
<Select.Content>
{limitCollection.items.map((item) => (
<Select.Item item={item} key={item.value}>{item.label}</Select.Item>
))}
</tbody>
</table>
</div>
</div>
</Select.Content>
</Select.Root>
</Flex>
<Box overflowX="auto" borderRadius="lg" borderWidth="1px" borderColor="border">
<Table.Root variant="line" size="sm">
<Table.Header>
<Table.Row borderBottomWidth="1px" borderColor="border">
<Table.ColumnHeader textTransform="uppercase" fontSize="11px" color="fg.muted" fontWeight="semibold" px={4} py={3}>Time</Table.ColumnHeader>
<Table.ColumnHeader textTransform="uppercase" fontSize="11px" color="fg.muted" fontWeight="semibold" px={4} py={3}>Admin</Table.ColumnHeader>
<Table.ColumnHeader textTransform="uppercase" fontSize="11px" color="fg.muted" fontWeight="semibold" px={4} py={3}>Action</Table.ColumnHeader>
<Table.ColumnHeader textTransform="uppercase" fontSize="11px" color="fg.muted" fontWeight="semibold" px={4} py={3}>Target</Table.ColumnHeader>
<Table.ColumnHeader textTransform="uppercase" fontSize="11px" color="fg.muted" fontWeight="semibold" px={4} py={3}>Details</Table.ColumnHeader>
</Table.Row>
</Table.Header>
<Table.Body>
{logs.map((log, i) => (
<Table.Row
key={i}
borderBottomWidth="1px"
borderColor="border"
_last={{ borderBottomWidth: 0 }}
_hover={{ bg: 'bg.subtle' }}
>
<Table.Cell px={4} py={3} color="fg.muted" fontSize="xs">{new Date(log.timestamp).toLocaleString()}</Table.Cell>
<Table.Cell px={4} py={3}>{log.admin_name}</Table.Cell>
<Table.Cell px={4} py={3}>
<Text
as="span"
px={2}
py={0.5}
borderRadius="md"
fontSize="11px"
fontWeight="semibold"
bg="primary.subtle"
color="primary.DEFAULT"
borderWidth="1px"
borderColor="primary.DEFAULT"
>
{log.action}
</Text>
</Table.Cell>
<Table.Cell px={4} py={3}>{log.target_type}: {log.target_id}</Table.Cell>
<Table.Cell px={4} py={3} fontSize="xs" color="fg.muted" maxW="md" truncate>{JSON.stringify(log.details)}</Table.Cell>
</Table.Row>
))}
</Table.Body>
</Table.Root>
</Box>
</Box>
)
}
+31 -19
View File
@@ -1,5 +1,7 @@
import { useState } from 'react'
import useSWR from 'swr'
import { Box, Heading, Input, Flex } from '@chakra-ui/react'
import { FiSearch } from 'react-icons/fi'
import client from '../../api/client'
import { useApp } from '../../stores/AppContext'
import DataTable from '../common/DataTable'
@@ -30,23 +32,33 @@ export default function Buildings() {
const buildingList: Building[] = buildingsData?.success ? buildingsData.data : []
return (
<div>
<h1 className="font-serif text-3xl text-primary mb-6">Buildings</h1>
<Box>
<Heading as="h1" fontFamily="Playfair Display, serif" color="primary.DEFAULT" fontSize="2xl" mb={6}>
Buildings
</Heading>
<div className="mb-6">
<div className="relative max-w-md">
<input
type="text"
value={search}
onChange={(e) => setSearch(e.target.value)}
placeholder="Search buildings..."
className="w-full bg-card-bg border border-border rounded-lg px-4 py-2.5 pl-10 text-sm text-text-primary placeholder-text-muted focus:outline-none focus:border-primary focus:ring-1 focus:ring-primary"
/>
<svg className="absolute left-3 top-3 w-4 h-4 text-text-muted" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0" />
</svg>
</div>
</div>
<Box position="relative" maxW="md" mb={6}>
<Input
type="text"
value={search}
onChange={(e) => setSearch(e.target.value)}
placeholder="Search buildings..."
bg="card.bg"
borderColor="border"
borderRadius="lg"
px={4}
py={2.5}
pl={10}
fontSize="sm"
color="fg"
_placeholder={{ color: 'fg.muted' }}
_focus={{ borderColor: 'primary.DEFAULT', boxShadow: '0 0 0 1px var(--chakra-colors-primary-DEFAULT)' }}
_focusVisible={{ outline: 'none' }}
/>
<Box position="absolute" left={3} top="50%" transform="translateY(-50%)" color="fg.muted">
<FiSearch size={16} />
</Box>
</Box>
<DataTable
columns={[
@@ -56,10 +68,10 @@ export default function Buildings() {
{
header: 'Power',
accessor: (row) => (
<div className="flex gap-1">
<Flex gap={1}>
{row.is_powered ? <Badge label="Powered" variant="success" /> : <Badge label="Unpowered" variant="default" />}
{row.power_level != null && <Badge label={`Lv ${row.power_level}`} variant="default" />}
</div>
</Flex>
),
},
{ header: 'Instances', accessor: 'instance_count' },
@@ -67,6 +79,6 @@ export default function Buildings() {
data={buildingList}
loading={isLoading}
/>
</div>
</Box>
)
}
+76 -29
View File
@@ -1,4 +1,14 @@
import { useState, useEffect, useRef } from 'react'
import {
Box,
Heading,
HStack,
Flex,
Button,
Text,
VStack,
} from '@chakra-ui/react'
import { FiMessageSquare } from 'react-icons/fi'
import client from '../../api/client'
interface ChatMessage {
@@ -48,41 +58,78 @@ export default function ChatMonitor() {
}, [messages])
return (
<div className="h-[calc(100vh-140px)] flex flex-col">
<div className="flex items-center justify-between mb-4">
<h1 className="font-serif text-3xl text-primary">Chat Monitor</h1>
<div className="flex gap-2">
<Flex direction="column" h="calc(100vh - 140px)">
<Flex align="center" justify="space-between" mb={4}>
<Heading as="h1" fontSize="3xl" fontFamily="Playfair Display, serif" color="primary.DEFAULT">
Chat Monitor
</Heading>
<HStack gap={2}>
{CHANNELS.map((c) => (
<button
<Button
key={c}
onClick={() => setChannel(c)}
className={`px-3 py-1.5 rounded text-xs font-medium border ${
channel === c
? 'bg-primary/10 border-primary text-primary'
: 'bg-card-bg border-border text-text-muted hover:text-text-primary'
}`}
size="xs"
borderRadius="md"
fontWeight="medium"
borderWidth="1px"
borderColor={channel === c ? 'primary.DEFAULT' : 'border'}
bg={channel === c ? 'primary.subtle' : 'card.bg'}
color={channel === c ? 'primary.DEFAULT' : 'fg.muted'}
_hover={channel === c ? {} : { color: 'fg' }}
transition="all 0.15s"
>
{c}
</button>
</Button>
))}
</div>
</div>
</HStack>
</Flex>
<div className="flex-1 bg-card-bg border border-border rounded-lg overflow-hidden flex flex-col">
<div className="flex-1 overflow-y-auto p-4 space-y-2 font-mono text-sm">
{messages.map((msg) => (
<div key={msg.id} className="flex gap-3">
<span className="text-text-muted text-xs whitespace-nowrap">
{new Date(msg.timestamp).toLocaleTimeString()}
</span>
<span className="text-primary font-semibold whitespace-nowrap">[{msg.channel}]</span>
<span className="text-accent font-semibold whitespace-nowrap">{msg.sender}:</span>
<span className="text-text-secondary break-all">{msg.message}</span>
</div>
))}
<div ref={bottomRef} />
</div>
</div>
</div>
<Box
flex={1}
bg="card.bg"
borderWidth="1px"
borderColor="border"
borderRadius="xl"
overflow="hidden"
display="flex"
flexDirection="column"
>
<Box
flex={1}
overflowY="auto"
p={4}
fontFamily="Roboto Mono, monospace"
>
{messages.length === 0 ? (
<Flex align="center" justify="center" h="full" color="fg.muted">
<VStack gap={3}>
<FiMessageSquare size={40} />
<Text fontSize="sm">Waiting for messages...</Text>
</VStack>
</Flex>
) : (
<VStack gap={2} align="stretch">
{messages.map((msg) => (
<HStack key={msg.id} gap={3} align="baseline">
<Text color="fg.muted" fontSize="xs" whiteSpace="nowrap" flexShrink={0}>
{new Date(msg.timestamp).toLocaleTimeString()}
</Text>
<Text color="primary.DEFAULT" fontWeight="semibold" whiteSpace="nowrap" flexShrink={0}>
[{msg.channel}]
</Text>
<Text color="warning.DEFAULT" fontWeight="semibold" whiteSpace="nowrap" flexShrink={0}>
{msg.sender}:
</Text>
<Text color="fg" wordBreak="break-all">
{msg.message}
</Text>
</HStack>
))}
</VStack>
)}
<Box ref={bottomRef} />
</Box>
</Box>
</Flex>
)
}
+23 -10
View File
@@ -1,20 +1,33 @@
import { Badge as ChakraBadge } from '@chakra-ui/react'
interface BadgeProps {
label: string
variant?: 'default' | 'success' | 'warning' | 'danger'
variant?: 'default' | 'success' | 'warning' | 'danger' | 'info'
}
const variantMap: Record<string, { bg: string; color: string }> = {
default: { bg: 'primary.subtle', color: 'primary.DEFAULT' },
success: { bg: 'success.subtle', color: 'success.DEFAULT' },
warning: { bg: 'warning.subtle', color: 'warning.DEFAULT' },
danger: { bg: 'danger.subtle', color: 'danger.DEFAULT' },
info: { bg: 'info.subtle', color: 'info.DEFAULT' },
}
export default function Badge({ label, variant = 'default' }: BadgeProps) {
const classes: Record<string, string> = {
default: 'bg-primary/10 text-primary border-primary/20',
success: 'bg-success/10 text-success border-success/20',
warning: 'bg-yellow-500/10 text-yellow-400 border-yellow-500/20',
danger: 'bg-danger/10 text-danger border-danger/20',
}
const colors = variantMap[variant] ?? variantMap.default
return (
<span
className={`inline-block px-2 py-0.5 rounded text-[11px] font-semibold border uppercase tracking-wide ${classes[variant]}`}
<ChakraBadge
variant="subtle"
bg={colors.bg}
color={colors.color}
borderRadius="full"
px={2.5}
py={0.5}
fontSize="xs"
fontWeight="medium"
>
{label}
</span>
</ChakraBadge>
)
}
+66 -44
View File
@@ -1,4 +1,6 @@
import { ReactNode, useState } from 'react'
import { Table, Flex, Text, Spinner } from '@chakra-ui/react'
import { FiChevronUp, FiChevronDown } from 'react-icons/fi'
interface Column<T> {
header: string
@@ -35,16 +37,14 @@ export default function DataTable<T extends object>({
if (sortCol) {
const col = columns.find((c) => c.header === sortCol)
if (col && typeof col.accessor === 'string') {
sorted.sort((a: any, b: any) => {
const av = a[col.accessor]
const bv = b[col.accessor]
sorted.sort((a, b) => {
const av = (a as any)[col.accessor as string]
const bv = (b as any)[col.accessor as string]
if (av == null && bv == null) return 0
if (av == null) return sortDir === 'asc' ? 1 : -1
if (bv == null) return sortDir === 'asc' ? -1 : 1
if (typeof av === 'string') {
return sortDir === 'asc'
? av.localeCompare(bv)
: bv.localeCompare(av)
return sortDir === 'asc' ? av.localeCompare(bv) : bv.localeCompare(av)
}
if (typeof av === 'number') {
return sortDir === 'asc' ? av - bv : bv - av
@@ -54,64 +54,86 @@ export default function DataTable<T extends object>({
}
}
const getCellValue = (row: T, col: Column<T>): string => {
if (typeof col.accessor === 'function') return ''
return String((row as any)[col.accessor] ?? '')
}
const getCellNode = (row: T, col: Column<T>): ReactNode => {
if (typeof col.accessor === 'function') return col.accessor(row)
return String((row as any)[col.accessor] ?? '')
}
return (
<div className="overflow-x-auto rounded-lg border border-border">
<table className="w-full text-sm">
<thead>
<tr className="border-b border-border">
<Table.ScrollArea borderWidth="1px" borderColor="border" borderRadius="lg">
<Table.Root variant="line" size="sm" stickyHeader>
<Table.Header>
<Table.Row bg="bg.subtle">
{columns.map((col) => (
<th
<Table.ColumnHeader
key={col.header}
className="text-left px-4 py-3 text-text-muted font-semibold text-[11px] uppercase tracking-wider cursor-pointer hover:text-text-primary select-none"
style={{ width: col.width }}
onClick={() => handleSort(col.header)}
cursor="pointer"
userSelect="none"
textTransform="uppercase"
fontSize="2xs"
letterSpacing="wider"
fontWeight="semibold"
color="fg.muted"
py={3}
px={4}
_hover={{ color: 'fg' }}
style={{ width: col.width }}
>
<div className="flex items-center gap-1">
<Flex align="center" gap={1}>
{col.header}
{sortCol === col.header && (
<span className="text-primary">
{sortDir === 'asc' ? ' ▲' : ' ▼'}
</span>
<Text as="span" color="primary.DEFAULT">
{sortDir === 'asc' ? <FiChevronUp size={10} /> : <FiChevronDown size={10} />}
</Text>
)}
</div>
</th>
</Flex>
</Table.ColumnHeader>
))}
</tr>
</thead>
<tbody>
</Table.Row>
</Table.Header>
<Table.Body>
{loading ? (
<tr>
<td colSpan={columns.length} className="px-4 py-8 text-center text-text-muted">
Loading...
</td>
</tr>
<Table.Row>
<Table.Cell colSpan={columns.length} textAlign="center" py={8}>
<Flex align="center" justify="center" gap={2} color="fg.muted">
<Spinner size="sm" />
<Text fontSize="sm">Loading...</Text>
</Flex>
</Table.Cell>
</Table.Row>
) : sorted.length === 0 ? (
<tr>
<td colSpan={columns.length} className="px-4 py-8 text-center text-text-muted">
<Table.Row>
<Table.Cell colSpan={columns.length} textAlign="center" py={8} color="fg.muted" fontSize="sm">
No results found
</td>
</tr>
</Table.Cell>
</Table.Row>
) : (
sorted.map((row, i) => (
<tr
<Table.Row
key={i}
onClick={() => onRowClick?.(row)}
className={`border-b border-border last:border-0 transition-colors ${
onRowClick ? 'cursor-pointer hover:bg-hover' : 'hover:bg-hover/50'
}`}
cursor={onRowClick ? 'pointer' : 'default'}
_hover={{ bg: 'bg.subtle' }}
borderBottomWidth="1px"
borderColor="border"
bg={i % 2 === 0 ? 'transparent' : 'bg.subtle'}
>
{columns.map((col) => (
<td key={col.header} className="px-4 py-3 whitespace-nowrap">
{typeof col.accessor === 'function'
? col.accessor(row)
: String(row[col.accessor] ?? '')}
</td>
<Table.Cell key={col.header} py={2.5} px={4} fontSize="sm">
{getCellNode(row, col)}
</Table.Cell>
))}
</tr>
</Table.Row>
))
)}
</tbody>
</table>
</div>
</Table.Body>
</Table.Root>
</Table.ScrollArea>
)
}
+61 -21
View File
@@ -1,30 +1,70 @@
import { ReactNode } from 'react'
import {
Dialog,
Portal,
IconButton,
} from '@chakra-ui/react'
import { FiX } from 'react-icons/fi'
interface ModalProps {
open: boolean
title: string
onClose: () => void
children: React.ReactNode
maxWidth?: string
title: string
children: ReactNode
}
export default function Modal({ open, title, onClose, children, maxWidth = '500px' }: ModalProps) {
if (!open) return null
export default function Modal({ open, onClose, title, children }: ModalProps) {
return (
<div className="fixed inset-0 z-[70] flex items-center justify-center bg-black/60 backdrop-blur-sm">
<div
className="bg-card-bg border border-border rounded-xl shadow-2xl w-full mx-4"
style={{ maxWidth }}
>
<div className="flex items-center justify-between px-5 py-4 border-b border-border">
<h3 className="font-serif text-lg text-text-primary">{title}</h3>
<button
onClick={onClose}
className="text-text-muted hover:text-text-primary text-xl leading-none"
<Dialog.Root open={open} onOpenChange={(e) => { if (!e.open) onClose() }}>
<Portal>
<Dialog.Backdrop bg="black/60" backdropFilter="blur(4px)" />
<Dialog.Positioner>
<Dialog.Content
bg="card.bg"
border="1px solid"
borderColor="border"
borderRadius="xl"
boxShadow="card"
maxW="600px"
w="full"
mx={4}
>
&times;
</button>
</div>
<div className="p-5 max-h-[80vh] overflow-auto">{children}</div>
</div>
</div>
<Dialog.Header
display="flex"
alignItems="center"
justifyContent="space-between"
borderBottom="1px solid"
borderColor="border"
px={6}
py={4}
>
<Dialog.Title
fontSize="lg"
fontWeight="semibold"
fontFamily="Playfair Display, serif"
color="primary.DEFAULT"
>
{title}
</Dialog.Title>
<Dialog.CloseTrigger asChild>
<IconButton
aria-label="Close"
variant="ghost"
size="sm"
onClick={onClose}
color="fg.muted"
_hover={{ color: 'fg' }}
>
<FiX />
</IconButton>
</Dialog.CloseTrigger>
</Dialog.Header>
<Dialog.Body px={6} py={4}>
{children}
</Dialog.Body>
</Dialog.Content>
</Dialog.Positioner>
</Portal>
</Dialog.Root>
)
}
@@ -1,39 +0,0 @@
import { useEffect } from 'react'
import { useApp } from '../../stores/AppContext'
export default function ToastProvider() {
const { state, dispatch } = useApp()
useEffect(() => {
if (state.toasts.length === 0) return
const timers = state.toasts.map((t) =>
setTimeout(() => {
dispatch({ type: 'REMOVE_TOAST', payload: t.id })
}, 4000)
)
return () => timers.forEach(clearTimeout)
}, [state.toasts, dispatch])
if (state.toasts.length === 0) return null
return (
<div className="fixed top-16 right-6 z-[100] flex flex-col gap-2">
{state.toasts.map((t) => (
<div
key={t.id}
className={`px-4 py-3 rounded-lg shadow-lg text-sm font-medium min-w-[240px] max-w-md border ${
t.type === 'success'
? 'bg-success/10 border-success/30 text-success'
: t.type === 'error'
? 'bg-danger/10 border-danger/30 text-danger'
: t.type === 'warning'
? 'bg-yellow-500/10 border-yellow-500/30 text-yellow-400'
: 'bg-primary/10 border-primary/30 text-primary'
}`}
>
{t.message}
</div>
))}
</div>
)
}
+218 -102
View File
@@ -1,15 +1,31 @@
import { useState } from 'react'
import useSWR from 'swr'
import {
Box,
Heading,
Tabs,
Button,
Input,
Textarea,
Field,
Text,
VStack,
HStack,
Spinner,
Flex,
} from '@chakra-ui/react'
import client from '../../api/client'
import { useApp } from '../../stores/AppContext'
const fetcher = (url: string) => client.get(url).then((r) => r.data)
export default function Director() {
const [tab, setTab] = useState<'battlegroup' | 'config' | 'transfer' | 'fls'>('battlegroup')
const [tab, setTab] = useState('battlegroup')
const { dispatch } = useApp()
const { data: bgData } = useSWR('/director/battlegroup', fetcher, { refreshInterval: 15000 })
const { data: bgData, isLoading: bgLoading } = useSWR('/director/battlegroup', fetcher, {
refreshInterval: 15000,
})
const handlePost = async (endpoint: string, payload: any) => {
try {
@@ -25,111 +41,211 @@ export default function Director() {
}
return (
<div>
<h1 className="font-serif text-3xl text-primary mb-6">Director Control</h1>
<Box>
<Heading as="h1" fontSize="3xl" fontFamily="Playfair Display, serif" color="primary.DEFAULT" mb={6}>
Director Control
</Heading>
<div className="flex gap-1 mb-6 border-b border-border">
{([
{ key: 'battlegroup', label: 'Battlegroup' },
{ key: 'config', label: 'Config' },
{ key: 'transfer', label: 'Transfer' },
{ key: 'fls', label: 'FLS' },
] as const).map((t) => (
<button
key={t.key}
onClick={() => setTab(t.key as any)}
className={`px-4 py-2.5 text-sm font-medium border-b-2 transition-colors ${
tab === t.key
? 'text-primary border-primary'
: 'text-text-muted border-transparent hover:text-text-primary'
}`}
<Tabs.Root value={tab} onValueChange={(e) => setTab(e.value)} variant="line" mb={6}>
<Tabs.List borderBottomWidth="1px" borderColor="border">
<Tabs.Trigger value="battlegroup" fontWeight="medium">
Battlegroup
</Tabs.Trigger>
<Tabs.Trigger value="config" fontWeight="medium">
Config
</Tabs.Trigger>
<Tabs.Trigger value="transfer" fontWeight="medium">
Transfer
</Tabs.Trigger>
<Tabs.Trigger value="fls" fontWeight="medium">
FLS
</Tabs.Trigger>
</Tabs.List>
<Tabs.Content value="battlegroup" pt={6}>
<Box
bg="card.bg"
borderWidth="1px"
borderColor="border"
borderRadius="xl"
boxShadow="card"
p={5}
>
{t.label}
</button>
))}
</div>
<Text fontSize="xs" textTransform="uppercase" letterSpacing="wider" color="fg.muted" mb={4}>
Battlegroup State
</Text>
{bgLoading ? (
<Flex align="center" gap={2} color="fg.muted">
<Spinner size="sm" />
<Text fontSize="sm">Loading battlegroup data...</Text>
</Flex>
) : bgData?.success ? (
<Box
as="pre"
fontSize="xs"
color="fg"
fontFamily="Roboto Mono, monospace"
bg="code.bg"
p={4}
borderRadius="lg"
overflow="auto"
maxH="60vh"
>
{JSON.stringify(bgData.data, null, 2)}
</Box>
) : (
<Text color="fg.muted">Loading battlegroup data...</Text>
)}
</Box>
</Tabs.Content>
{tab === 'battlegroup' && (
<div className="bg-card-bg border border-border rounded-lg p-5">
<h3 className="text-text-muted text-xs uppercase tracking-wider mb-4">Battlegroup State</h3>
{bgData?.success ? (
<pre className="text-xs text-text-secondary font-mono bg-code-bg p-4 rounded overflow-auto max-h-[60vh]">
{JSON.stringify(bgData.data, null, 2)}
</pre>
) : (
<div className="text-text-muted">Loading battlegroup data...</div>
)}
</div>
)}
<Tabs.Content value="config" pt={6}>
<Box
bg="card.bg"
borderWidth="1px"
borderColor="border"
borderRadius="xl"
boxShadow="card"
p={5}
maxW="xl"
>
<VStack gap={4} align="stretch">
<Text fontSize="xs" textTransform="uppercase" letterSpacing="wider" color="fg.muted">
Update Config
</Text>
{tab === 'config' && (
<div className="bg-card-bg border border-border rounded-lg p-5 space-y-4 max-w-xl">
<h3 className="text-text-muted text-xs uppercase tracking-wider mb-4">Update Config</h3>
<div>
<label className="block text-sm text-text-muted mb-2">Map Name</label>
<input
id="config-map"
className="w-full bg-card-bg border border-border rounded-lg px-4 py-2 text-sm"
placeholder="e.g., HaggaBasin"
/>
</div>
<div>
<label className="block text-sm text-text-muted mb-2">Config JSON</label>
<textarea
id="config-json"
rows={6}
className="w-full bg-card-bg border border-border rounded-lg px-4 py-3 text-sm font-mono"
placeholder='{"maxPlayers": 100}'
/>
</div>
<div className="flex gap-2">
<button
onClick={() => {
const map = (document.getElementById('config-map') as HTMLInputElement).value
const json = (document.getElementById('config-json') as HTMLTextAreaElement).value
handlePost('/director/config', { map, config: JSON.parse(json) })
}}
className="px-4 py-2 bg-primary text-white rounded-lg text-sm font-medium"
>
Update Config
</button>
<button
onClick={() => handlePost('/director/config/clear', {})}
className="px-4 py-2 bg-danger/10 border border-danger/30 text-danger rounded-lg text-sm font-medium"
>
Clear Config
</button>
</div>
</div>
)}
<Field.Root>
<Field.Label fontSize="sm" color="fg.muted">
Map Name
</Field.Label>
<Input
id="config-map"
bg="card.bg"
borderColor="border"
borderRadius="lg"
fontSize="sm"
placeholder="e.g., HaggaBasin"
/>
</Field.Root>
{tab === 'transfer' && (
<div className="bg-card-bg border border-border rounded-lg p-5 space-y-4 max-w-xl">
<h3 className="text-text-muted text-xs uppercase tracking-wider mb-4">Transfer Rules</h3>
<div className="flex gap-2">
<button
onClick={() => handlePost('/director/transfer/clear', {})}
className="px-4 py-2 bg-danger/10 border border-danger/30 text-danger rounded-lg text-sm font-medium"
>
Clear Overrides
</button>
</div>
</div>
)}
<Field.Root>
<Field.Label fontSize="sm" color="fg.muted">
Config JSON
</Field.Label>
<Textarea
id="config-json"
rows={6}
bg="card.bg"
borderColor="border"
borderRadius="lg"
fontSize="sm"
fontFamily="Roboto Mono, monospace"
placeholder='{"maxPlayers": 100}'
/>
</Field.Root>
{tab === 'fls' && (
<div className="bg-card-bg border border-border rounded-lg p-5 space-y-4 max-w-xl">
<h3 className="text-text-muted text-xs uppercase tracking-wider mb-4">FLS Settings</h3>
<div className="flex gap-2">
<button
onClick={() => handlePost('/director/fls/clear', {})}
className="px-4 py-2 bg-danger/10 border border-danger/30 text-danger rounded-lg text-sm font-medium"
>
Clear FLS Overrides
</button>
</div>
</div>
)}
</div>
<HStack gap={2}>
<Button
variant="solid"
size="sm"
bg="primary.DEFAULT"
borderRadius="lg"
_hover={{ bg: 'primary.hover' }}
transition="all 0.15s"
onClick={() => {
const map = (document.getElementById('config-map') as HTMLInputElement).value
const json = (document.getElementById('config-json') as HTMLTextAreaElement).value
handlePost('/director/config', { map, config: JSON.parse(json) })
}}
>
Update Config
</Button>
<Button
variant="outline"
size="sm"
borderColor="danger.DEFAULT/30"
color="danger.DEFAULT"
bg="danger.subtle"
borderRadius="lg"
_hover={{ bg: 'danger.subtle/80' }}
transition="all 0.15s"
onClick={() => handlePost('/director/config/clear', {})}
>
Clear Config
</Button>
</HStack>
</VStack>
</Box>
</Tabs.Content>
<Tabs.Content value="transfer" pt={6}>
<Box
bg="card.bg"
borderWidth="1px"
borderColor="border"
borderRadius="xl"
boxShadow="card"
p={5}
maxW="xl"
>
<VStack gap={4} align="stretch">
<Text fontSize="xs" textTransform="uppercase" letterSpacing="wider" color="fg.muted">
Transfer Rules
</Text>
<HStack gap={2}>
<Button
variant="outline"
size="sm"
borderColor="danger.DEFAULT/30"
color="danger.DEFAULT"
bg="danger.subtle"
borderRadius="lg"
_hover={{ bg: 'danger.subtle/80' }}
transition="all 0.15s"
onClick={() => handlePost('/director/transfer/clear', {})}
>
Clear Overrides
</Button>
</HStack>
</VStack>
</Box>
</Tabs.Content>
<Tabs.Content value="fls" pt={6}>
<Box
bg="card.bg"
borderWidth="1px"
borderColor="border"
borderRadius="xl"
boxShadow="card"
p={5}
maxW="xl"
>
<VStack gap={4} align="stretch">
<Text fontSize="xs" textTransform="uppercase" letterSpacing="wider" color="fg.muted">
FLS Settings
</Text>
<HStack gap={2}>
<Button
variant="outline"
size="sm"
borderColor="danger.DEFAULT/30"
color="danger.DEFAULT"
bg="danger.subtle"
borderRadius="lg"
_hover={{ bg: 'danger.subtle/80' }}
transition="all 0.15s"
onClick={() => handlePost('/director/fls/clear', {})}
>
Clear FLS Overrides
</Button>
</HStack>
</VStack>
</Box>
</Tabs.Content>
</Tabs.Root>
</Box>
)
}
@@ -0,0 +1,733 @@
import { useState } from 'react'
import {
Box, Flex, Text, Heading, Tabs, Card, Button,
Input, Textarea, Select, SimpleGrid, VStack, HStack,
Field, Spinner, Badge as ChakraBadge, Switch, Separator,
NumberInput, Table, createListCollection,
} from '@chakra-ui/react'
import {
FiSend, FiUsers, FiSearch, FiRefreshCw, FiDollarSign,
FiFlag, FiShield, FiBox, FiMap, FiDatabase,
FiTerminal, FiPlay, FiAlertTriangle, FiTrash2,
FiTag, FiUser, FiGlobe, FiRadio, FiCode,
} from 'react-icons/fi'
import client from '../../api/client'
import { useApp } from '../../stores/AppContext'
const apiPost = async (url: string, body?: unknown) => {
const res = await client.post(url, body)
return res.data
}
const apiGet = async (url: string) => {
const res = await client.get(url)
return res.data
}
export default function Experimental() {
const { dispatch } = useApp()
const [tab, setTab] = useState('broadcast')
const [loading, setLoading] = useState<string | null>(null)
const doAction = async (url: string, body: unknown, label: string) => {
setLoading(label)
try {
const result = await apiPost(url, body)
if (result.success) {
dispatch({ type: 'ADD_TOAST', payload: { message: `${label} succeeded`, type: 'success' } })
} else {
dispatch({ type: 'ADD_TOAST', payload: { message: result.error || `${label} failed`, type: 'error' } })
}
return result
} catch {
dispatch({ type: 'ADD_TOAST', payload: { message: `${label} failed`, type: 'error' } })
} finally {
setLoading(null)
}
}
return (
<Box>
<Flex align="center" gap={3} mb={2}>
<Heading as="h1" fontSize="3xl" fontFamily="Playfair Display, serif" color="primary.DEFAULT">
Experimental
</Heading>
<ChakraBadge variant="subtle" bg="warning.subtle" color="warning.DEFAULT" borderRadius="full" px={3} py={1}>
<FiAlertTriangle size={12} style={{ display: 'inline', marginRight: '4px' }} />
Testing Area
</ChakraBadge>
</Flex>
<Text color="fg.muted" fontSize="sm" mb={6}>
Experimental tools for RMQ API testing. Features are unstable and subject to change.
</Text>
<Tabs.Root value={tab} onValueChange={(e) => setTab(e.value)} variant="line" mb={6}>
<Tabs.List borderBottomWidth="1px" borderColor="border" gap={0} overflowX="auto">
{[
{ value: 'broadcast', label: 'Broadcast', icon: FiRadio },
{ value: 'players', label: 'Players', icon: FiUsers },
{ value: 'guilds', label: 'Guilds', icon: FiShield },
{ value: 'world', label: 'World', icon: FiGlobe },
{ value: 'functions', label: 'Functions', icon: FiCode },
{ value: 'query', label: 'Raw Query', icon: FiDatabase },
].map(({ value, label, icon: Icon }) => (
<Tabs.Trigger
key={value}
value={value}
px={3} py={2.5} fontSize="sm" fontWeight="medium"
color="fg.muted"
borderBottom="2px solid transparent"
_selected={{ color: 'primary.DEFAULT', borderColor: 'primary.DEFAULT' }}
transition="all 0.15s"
gap={1.5}
>
<Icon size={14} />
{label}
</Tabs.Trigger>
))}
</Tabs.List>
<Tabs.Content value="broadcast" pt={4}>
<BroadcastTab dispatch={dispatch} />
</Tabs.Content>
<Tabs.Content value="players" pt={4}>
<PlayersTab dispatch={dispatch} loading={loading} setLoading={setLoading} />
</Tabs.Content>
<Tabs.Content value="guilds" pt={4}>
<GuildsTab dispatch={dispatch} loading={loading} setLoading={setLoading} />
</Tabs.Content>
<Tabs.Content value="world" pt={4}>
<WorldTab dispatch={dispatch} loading={loading} setLoading={setLoading} />
</Tabs.Content>
<Tabs.Content value="functions" pt={4}>
<FunctionsTab dispatch={dispatch} loading={loading} setLoading={setLoading} />
</Tabs.Content>
<Tabs.Content value="query" pt={4}>
<RawQueryTab dispatch={dispatch} loading={loading} setLoading={setLoading} />
</Tabs.Content>
</Tabs.Root>
</Box>
)
}
function CardSection({ title, icon: Icon, children }: { title: string; icon: React.ElementType; children: React.ReactNode }) {
return (
<Card.Root bg="card.bg" borderWidth="1px" borderColor="border" borderRadius="xl" boxShadow="card">
<Card.Header borderBottomWidth="1px" borderColor="border" px={5} py={3}>
<Flex align="center" gap={2}>
<Icon size={16} />
<Text fontFamily="Playfair Display, serif" fontSize="md" color="primary.DEFAULT" fontWeight="semibold">
{title}
</Text>
</Flex>
</Card.Header>
<Card.Body p={5}>
{children}
</Card.Body>
</Card.Root>
)
}
function BroadcastTab({ dispatch }: { dispatch: ReturnType<typeof useApp>['dispatch'] }) {
const [title, setTitle] = useState('Server Notice')
const [message, setMessage] = useState('')
const [duration, setDuration] = useState(30)
const [sending, setSending] = useState(false)
const send = async () => {
setSending(true)
try {
const res = await apiPost('/admin-experimental/broadcast', { title, message, duration })
dispatch({ type: 'ADD_TOAST', payload: { message: res.success ? 'Broadcast sent' : (res.error || 'Failed'), type: res.success ? 'success' : 'error' } })
} catch {
dispatch({ type: 'ADD_TOAST', payload: { message: 'Broadcast failed', type: 'error' } })
} finally {
setSending(false)
}
}
return (
<SimpleGrid columns={{ base: 1, lg: 2 }} gap={6}>
<CardSection title="Send Broadcast" icon={FiRadio}>
<Text fontSize="sm" color="fg.muted" mb={4}>Send a notification to all connected players via RabbitMQ heartbeats exchange.</Text>
<VStack align="stretch" gap={4}>
<Field.Root>
<Field.Label fontSize="sm" color="fg">Title</Field.Label>
<Input value={title} onChange={(e) => setTitle(e.target.value)} placeholder="Server Notice" />
</Field.Root>
<Field.Root>
<Field.Label fontSize="sm" color="fg">Message</Field.Label>
<Textarea value={message} onChange={(e) => setMessage(e.target.value)} placeholder="Broadcast message..." rows={3} />
</Field.Root>
<Field.Root>
<Field.Label fontSize="sm" color="fg">Duration (seconds)</Field.Label>
<NumberInput.Root value={String(duration)} onValueChange={(v) => setDuration(Number(v.value))} min={5} max={300}>
<NumberInput.Input />
</NumberInput.Root>
</Field.Root>
<Button onClick={send} loading={sending}><FiSend size={14} />
Send Broadcast
</Button>
</VStack>
</CardSection>
</SimpleGrid>
)
}
function PlayersTab({ dispatch, loading, setLoading }: {
dispatch: ReturnType<typeof useApp>['dispatch']
loading: string | null
setLoading: (v: string | null) => void
}) {
const [searchTerm, setSearchTerm] = useState('')
const [searchResults, setSearchResults] = useState<any>(null)
const [onlinePlayers, setOnlinePlayers] = useState<any>(null)
const [currencyPid, setCurrencyPid] = useState('')
const [currencyCid, setCurrencyCid] = useState('0')
const [currencyDelta, setCurrencyDelta] = useState('1000')
const [currencyResult, setCurrencyResult] = useState<any>(null)
const [factionPid, setFactionPid] = useState('')
const [factionId, setFactionId] = useState('')
const [teleportPid, setTeleportPid] = useState('')
const [teleportX, setTeleportX] = useState('')
const [teleportY, setTeleportY] = useState('')
const [teleportZ, setTeleportZ] = useState('')
const [tagPid, setTagPid] = useState('')
const [tagKey, setTagKey] = useState('')
const [tagValue, setTagValue] = useState('')
const [tagResult, setTagResult] = useState<any>(null)
const [cheaterPid, setCheaterPid] = useState('')
const [cheaterReason, setCheaterReason] = useState('')
const search = async () => {
setLoading('search')
try {
const res = await apiPost('/admin-experimental/search-players', { term: searchTerm })
setSearchResults(res)
} finally { setLoading(null) }
}
const loadOnline = async () => {
setLoading('online')
try {
const res = await apiGet('/admin-experimental/online-players')
setOnlinePlayers(res)
} finally { setLoading(null) }
}
const adjustCurrency = async () => {
const res = await apiPost('/admin-experimental/adjust-currency', {
player_id: Number(currencyPid),
currency_id: Number(currencyCid),
delta: Number(currencyDelta),
})
if (res.success) dispatch({ type: 'ADD_TOAST', payload: { message: 'Currency adjusted', type: 'success' } })
}
const viewCurrency = async () => {
const res = await apiPost('/admin-experimental/currency-balances', { player_id: Number(currencyPid) })
setCurrencyResult(res)
}
const changeFaction = async () => {
await apiPost('/admin-experimental/change-faction', { player_id: Number(factionPid), faction_id: Number(factionId) })
dispatch({ type: 'ADD_TOAST', payload: { message: 'Faction change requested', type: 'info' } })
}
const doTeleport = async () => {
await apiPost('/admin-experimental/teleport', {
player_id: Number(teleportPid),
x: Number(teleportX),
y: Number(teleportY),
z: Number(teleportZ),
})
dispatch({ type: 'ADD_TOAST', payload: { message: 'Teleport requested', type: 'info' } })
}
const getTags = async () => {
const res = await apiPost('/admin-experimental/player-tags', { player_id: Number(tagPid) })
setTagResult(res)
}
const setTag = async () => {
const res = await apiPost('/admin-experimental/player-tags', {
player_id: Number(tagPid),
key: tagKey,
value: tagValue,
action: 'set',
})
dispatch({ type: 'ADD_TOAST', payload: { message: res.success ? 'Tag set' : 'Failed', type: res.success ? 'success' : 'error' } })
}
const flagCheater = async () => {
const res = await apiPost('/admin-experimental/flag-cheater', {
player_id: Number(cheaterPid),
reason: cheaterReason,
})
dispatch({ type: 'ADD_TOAST', payload: { message: res.success ? 'Player flagged' : 'Failed', type: res.success ? 'success' : 'error' } })
}
return (
<SimpleGrid columns={{ base: 1, lg: 2 }} gap={6}>
<CardSection title="Search Players" icon={FiSearch}>
<Flex gap={2} mb={4}>
<Input value={searchTerm} onChange={(e) => setSearchTerm(e.target.value)} placeholder="Character name..." />
<Button onClick={search} loading={loading === 'search'}><FiSearch size={14} /> Search</Button>
</Flex>
{searchResults && (
<Box as="pre" fontSize="xs" fontFamily="Roboto Mono, monospace" bg="code.bg" p={3} borderRadius="md" overflow="auto" maxH="300px">
{JSON.stringify(searchResults, null, 2)}
</Box>
)}
</CardSection>
<CardSection title="Online Players" icon={FiUsers}>
<Button onClick={loadOnline} loading={loading === 'online'} mb={4}><FiRefreshCw size={14} /> Refresh</Button>
{onlinePlayers && (
<Box as="pre" fontSize="xs" fontFamily="Roboto Mono, monospace" bg="code.bg" p={3} borderRadius="md" overflow="auto" maxH="300px">
{JSON.stringify(onlinePlayers, null, 2)}
</Box>
)}
</CardSection>
<CardSection title="Adjust Currency" icon={FiDollarSign}>
<VStack align="stretch" gap={3}>
<Field.Root>
<Field.Label fontSize="sm">Player Controller ID</Field.Label>
<Input value={currencyPid} onChange={(e) => setCurrencyPid(e.target.value)} placeholder="e.g. 81" />
</Field.Root>
<Flex gap={3}>
<Box flex={1}>
<Field.Root>
<Field.Label fontSize="sm">Currency</Field.Label>
<Select.Root
value={[currencyCid]}
onValueChange={(e) => setCurrencyCid(e.value[0])}
collection={createListCollection({ items: [
{ value: '0', label: 'Solari Credits' },
{ value: '1', label: 'House Script' },
{ value: '2', label: 'Spice' },
]})}
size="sm"
>
<Select.Trigger>
<Select.ValueText placeholder="Select currency" />
</Select.Trigger>
<Select.Content>
{createListCollection({ items: [
{ value: '0', label: 'Solari Credits' },
{ value: '1', label: 'House Script' },
{ value: '2', label: 'Spice' },
]}).items.map((item) => (
<Select.Item key={item.value} item={item}>
{item.label}
</Select.Item>
))}
</Select.Content>
</Select.Root>
</Field.Root>
</Box>
<Box flex={1}>
<Field.Root>
<Field.Label fontSize="sm">Delta</Field.Label>
<Input value={currencyDelta} onChange={(e) => setCurrencyDelta(e.target.value)} type="number" />
</Field.Root>
</Box>
</Flex>
<Flex gap={2}>
<Button onClick={adjustCurrency}><FiDollarSign size={14} /> Apply</Button>
<Button variant="outline" onClick={viewCurrency}><FiSearch size={14} /> View Balances</Button>
</Flex>
{currencyResult && (
<Box as="pre" fontSize="xs" fontFamily="Roboto Mono, monospace" bg="code.bg" p={3} borderRadius="md" overflow="auto" maxH="200px">
{JSON.stringify(currencyResult, null, 2)}
</Box>
)}
</VStack>
</CardSection>
<CardSection title="Change Faction" icon={FiFlag}>
<VStack align="stretch" gap={3}>
<Field.Root>
<Field.Label fontSize="sm">Player ID</Field.Label>
<Input value={factionPid} onChange={(e) => setFactionPid(e.target.value)} placeholder="e.g. 81" />
</Field.Root>
<Field.Root>
<Field.Label fontSize="sm">New Faction ID</Field.Label>
<Input value={factionId} onChange={(e) => setFactionId(e.target.value)} placeholder="Faction ID" />
</Field.Root>
<Button onClick={changeFaction}><FiFlag size={14} /> Change Faction</Button>
</VStack>
</CardSection>
<CardSection title="Teleport Player" icon={FiMap}>
<VStack align="stretch" gap={3}>
<Field.Root>
<Field.Label fontSize="sm">Player ID</Field.Label>
<Input value={teleportPid} onChange={(e) => setTeleportPid(e.target.value)} placeholder="Player ID" />
</Field.Root>
<SimpleGrid columns={3} gap={3}>
<Field.Root>
<Field.Label fontSize="sm">X</Field.Label>
<Input value={teleportX} onChange={(e) => setTeleportX(e.target.value)} placeholder="X" />
</Field.Root>
<Field.Root>
<Field.Label fontSize="sm">Y</Field.Label>
<Input value={teleportY} onChange={(e) => setTeleportY(e.target.value)} placeholder="Y" />
</Field.Root>
<Field.Root>
<Field.Label fontSize="sm">Z</Field.Label>
<Input value={teleportZ} onChange={(e) => setTeleportZ(e.target.value)} placeholder="Z" />
</Field.Root>
</SimpleGrid>
<Button onClick={doTeleport}><FiMap size={14} /> Teleport</Button>
</VStack>
</CardSection>
<CardSection title="Player Tags" icon={FiTag}>
<VStack align="stretch" gap={3}>
<Field.Root>
<Field.Label fontSize="sm">Player ID</Field.Label>
<Input value={tagPid} onChange={(e) => setTagPid(e.target.value)} placeholder="Player ID" />
</Field.Root>
<Flex gap={3}>
<Box flex={1}>
<Field.Root>
<Field.Label fontSize="sm">Key</Field.Label>
<Input value={tagKey} onChange={(e) => setTagKey(e.target.value)} placeholder="Tag key" />
</Field.Root>
</Box>
<Box flex={1}>
<Field.Root>
<Field.Label fontSize="sm">Value</Field.Label>
<Input value={tagValue} onChange={(e) => setTagValue(e.target.value)} placeholder="Tag value" />
</Field.Root>
</Box>
</Flex>
<Flex gap={2}>
<Button onClick={getTags}><FiSearch size={14} /> Get Tags</Button>
<Button onClick={setTag}><FiTag size={14} /> Set Tag</Button>
</Flex>
{tagResult && (
<Box as="pre" fontSize="xs" fontFamily="Roboto Mono, monospace" bg="code.bg" p={3} borderRadius="md" overflow="auto" maxH="200px">
{JSON.stringify(tagResult, null, 2)}
</Box>
)}
</VStack>
</CardSection>
<CardSection title="Flag Cheater" icon={FiAlertTriangle}>
<VStack align="stretch" gap={3}>
<Field.Root>
<Field.Label fontSize="sm">Player ID</Field.Label>
<Input value={cheaterPid} onChange={(e) => setCheaterPid(e.target.value)} placeholder="Player ID" />
</Field.Root>
<Field.Root>
<Field.Label fontSize="sm">Reason</Field.Label>
<Textarea value={cheaterReason} onChange={(e) => setCheaterReason(e.target.value)} placeholder="Reason for flagging..." rows={2} />
</Field.Root>
<Button onClick={flagCheater}><FiFlag size={14} /> Flag Cheater</Button>
</VStack>
</CardSection>
</SimpleGrid>
)
}
function GuildsTab({ dispatch, loading, setLoading }: {
dispatch: ReturnType<typeof useApp>['dispatch']
loading: string | null
setLoading: (v: string | null) => void
}) {
const [guildsData, setGuildsData] = useState<any>(null)
const [guildId, setGuildId] = useState('')
const [guildInfo, setGuildInfo] = useState<any>(null)
const [disbandId, setDisbandId] = useState('')
const [removeGuildId, setRemoveGuildId] = useState('')
const [removePlayerId, setRemovePlayerId] = useState('')
const listGuilds = async () => {
setLoading('guilds')
try {
const res = await apiGet('/admin-experimental/guilds')
setGuildsData(res)
} finally { setLoading(null) }
}
const getGuildData = async () => {
const res = await apiPost('/admin-experimental/guild-data', { guild_id: Number(guildId) })
setGuildInfo(res)
}
const disbandGuild = async () => {
const res = await apiPost('/admin-experimental/disband-guild', { guild_id: Number(disbandId) })
dispatch({ type: 'ADD_TOAST', payload: { message: res.success ? 'Guild disbanded' : (res.error || 'Failed'), type: res.success ? 'success' : 'error' } })
}
const removeMember = async () => {
const res = await apiPost('/admin-experimental/remove-guild-member', {
guild_id: Number(removeGuildId),
player_id: Number(removePlayerId),
})
dispatch({ type: 'ADD_TOAST', payload: { message: res.success ? 'Member removed' : (res.error || 'Failed'), type: res.success ? 'success' : 'error' } })
}
return (
<SimpleGrid columns={{ base: 1, lg: 2 }} gap={6}>
<CardSection title="Guild List" icon={FiShield}>
<Button onClick={listGuilds} loading={loading === 'guilds'} mb={4}><FiRefreshCw size={14} /> Load Guilds</Button>
{guildsData && (
<Box as="pre" fontSize="xs" fontFamily="Roboto Mono, monospace" bg="code.bg" p={3} borderRadius="md" overflow="auto" maxH="400px">
{JSON.stringify(guildsData, null, 2)}
</Box>
)}
</CardSection>
<CardSection title="Guild Info" icon={FiSearch}>
<VStack align="stretch" gap={3}>
<Field.Root>
<Field.Label fontSize="sm">Guild ID</Field.Label>
<Input value={guildId} onChange={(e) => setGuildId(e.target.value)} placeholder="Guild ID" />
</Field.Root>
<Button onClick={getGuildData}><FiSearch size={14} /> Get Info</Button>
{guildInfo && (
<Box as="pre" fontSize="xs" fontFamily="Roboto Mono, monospace" bg="code.bg" p={3} borderRadius="md" overflow="auto" maxH="200px">
{JSON.stringify(guildInfo, null, 2)}
</Box>
)}
</VStack>
</CardSection>
<CardSection title="Disband Guild" icon={FiTrash2}>
<VStack align="stretch" gap={3}>
<Field.Root>
<Field.Label fontSize="sm">Guild ID</Field.Label>
<Input value={disbandId} onChange={(e) => setDisbandId(e.target.value)} placeholder="Guild ID" />
</Field.Root>
<Button onClick={disbandGuild}><FiTrash2 size={14} /> Disband Guild</Button>
</VStack>
</CardSection>
<CardSection title="Remove Guild Member" icon={FiUser}>
<VStack align="stretch" gap={3}>
<Field.Root>
<Field.Label fontSize="sm">Guild ID</Field.Label>
<Input value={removeGuildId} onChange={(e) => setRemoveGuildId(e.target.value)} placeholder="Guild ID" />
</Field.Root>
<Field.Root>
<Field.Label fontSize="sm">Player ID</Field.Label>
<Input value={removePlayerId} onChange={(e) => setRemovePlayerId(e.target.value)} placeholder="Player ID" />
</Field.Root>
<Button onClick={removeMember}><FiUser size={14} /> Remove Member</Button>
</VStack>
</CardSection>
</SimpleGrid>
)
}
function WorldTab({ dispatch, loading, setLoading }: {
dispatch: ReturnType<typeof useApp>['dispatch']
loading: string | null
setLoading: (v: string | null) => void
}) {
const [partitionsData, setPartitionsData] = useState<any>(null)
const [spiceData, setSpiceData] = useState<any>(null)
const [vendorResult, setVendorResult] = useState<any>(null)
const [taxResult, setTaxResult] = useState<any>(null)
const loadPartitions = async () => {
setLoading('partitions')
try { const r = await apiGet('/admin-experimental/partitions'); setPartitionsData(r) } finally { setLoading(null) }
}
const cleanVendor = async () => {
const r = await apiPost('/admin-experimental/clean-vendor-stock', {})
setVendorResult(r)
dispatch({ type: 'ADD_TOAST', payload: { message: r.success ? 'Vendor stock cleaned' : 'Failed', type: r.success ? 'success' : 'error' } })
}
const getTaxInvoices = async () => {
const r = await apiPost('/admin-experimental/tax-invoices', {})
setTaxResult(r)
}
const controlSpice = async (action: string) => {
const r = await apiPost('/admin-experimental/spice', { action })
setSpiceData(r)
dispatch({ type: 'ADD_TOAST', payload: { message: r.success ? 'Spice action completed' : 'Failed', type: r.success ? 'success' : 'error' } })
}
return (
<SimpleGrid columns={{ base: 1, lg: 2 }} gap={6}>
<CardSection title="Partitions" icon={FiMap}>
<Button onClick={loadPartitions} loading={loading === 'partitions'} mb={4}><FiRefreshCw size={14} /> Load</Button>
{partitionsData && (
<Box as="pre" fontSize="xs" fontFamily="Roboto Mono, monospace" bg="code.bg" p={3} borderRadius="md" overflow="auto" maxH="300px">
{JSON.stringify(partitionsData, null, 2)}
</Box>
)}
</CardSection>
<CardSection title="Spice Fields" icon={FiBox}>
<Flex gap={2} mb={4} wrap="wrap">
<Button size="sm" onClick={() => controlSpice('list')}>List</Button>
<Button size="sm" onClick={() => controlSpice('reset')}>Reset</Button>
<Button size="sm" onClick={() => controlSpice('regenerate')}>Regenerate</Button>
</Flex>
{spiceData && (
<Box as="pre" fontSize="xs" fontFamily="Roboto Mono, monospace" bg="code.bg" p={3} borderRadius="md" overflow="auto" maxH="200px">
{JSON.stringify(spiceData, null, 2)}
</Box>
)}
</CardSection>
<CardSection title="Vendor Stock" icon={FiBox}>
<Text fontSize="sm" color="fg.muted" mb={4}>Clean all vendor stock entries.</Text>
<Button onClick={cleanVendor}><FiRefreshCw size={14} /> Clean Stock</Button>
{vendorResult && (
<Box as="pre" fontSize="xs" fontFamily="Roboto Mono, monospace" bg="code.bg" p={3} borderRadius="md" overflow="auto" maxH="200px" mt={4}>
{JSON.stringify(vendorResult, null, 2)}
</Box>
)}
</CardSection>
<CardSection title="Tax Invoices" icon={FiDollarSign}>
<Text fontSize="sm" color="fg.muted" mb={4}>View tax invoice data.</Text>
<Button onClick={getTaxInvoices} mb={4}><FiSearch size={14} /> Load Invoices</Button>
{taxResult && (
<Box as="pre" fontSize="xs" fontFamily="Roboto Mono, monospace" bg="code.bg" p={3} borderRadius="md" overflow="auto" maxH="300px">
{JSON.stringify(taxResult, null, 2)}
</Box>
)}
</CardSection>
</SimpleGrid>
)
}
function FunctionsTab({ dispatch, loading, setLoading }: {
dispatch: ReturnType<typeof useApp>['dispatch']
loading: string | null
setLoading: (v: string | null) => void
}) {
const [functionsData, setFunctionsData] = useState<any>(null)
const [funcName, setFuncName] = useState('')
const [funcInfo, setFuncInfo] = useState<any>(null)
const [funcArgs, setFuncArgs] = useState('{}')
const [execResult, setExecResult] = useState<any>(null)
const listFunctions = async () => {
setLoading('functions')
try { const r = await apiGet('/admin-experimental/functions'); setFunctionsData(r) } finally { setLoading(null) }
}
const getFunctionInfo = async () => {
const r = await apiGet(`/admin-experimental/functions/${funcName}`)
setFuncInfo(r)
}
const executeFunction = async () => {
setLoading('exec')
try {
const r = await apiPost(`/admin-experimental/functions/${funcName}/execute`, JSON.parse(funcArgs))
setExecResult(r)
dispatch({ type: 'ADD_TOAST', payload: { message: r.success ? 'Executed' : (r.error || 'Failed'), type: r.success ? 'success' : 'error' } })
} finally { setLoading(null) }
}
return (
<SimpleGrid columns={{ base: 1, lg: 2 }} gap={6}>
<CardSection title="Stored Procedures" icon={FiCode}>
<Button onClick={listFunctions} loading={loading === 'functions'} mb={4}><FiRefreshCw size={14} /> Load Functions</Button>
{functionsData && (
<Box as="pre" fontSize="xs" fontFamily="Roboto Mono, monospace" bg="code.bg" p={3} borderRadius="md" overflow="auto" maxH="400px">
{JSON.stringify(functionsData, null, 2)}
</Box>
)}
</CardSection>
<CardSection title="Execute Function" icon={FiPlay}>
<VStack align="stretch" gap={3}>
<Field.Root>
<Field.Label fontSize="sm">Function Name</Field.Label>
<Input value={funcName} onChange={(e) => setFuncName(e.target.value)} placeholder="schema.function_name" />
</Field.Root>
<Button variant="outline" onClick={getFunctionInfo}><FiSearch size={14} /> Get Info</Button>
{funcInfo && (
<Box as="pre" fontSize="xs" fontFamily="Roboto Mono, monospace" bg="code.bg" p={3} borderRadius="md" overflow="auto" maxH="150px">
{JSON.stringify(funcInfo, null, 2)}
</Box>
)}
<Field.Root>
<Field.Label fontSize="sm">Arguments (JSON array)</Field.Label>
<Textarea value={funcArgs} onChange={(e) => setFuncArgs(e.target.value)} rows={3} fontFamily="Roboto Mono, monospace" fontSize="xs" />
</Field.Root>
<Button onClick={executeFunction} loading={loading === 'exec'}><FiPlay size={14} /> Execute</Button>
{execResult && (
<Box as="pre" fontSize="xs" fontFamily="Roboto Mono, monospace" bg="code.bg" p={3} borderRadius="md" overflow="auto" maxH="300px">
{JSON.stringify(execResult, null, 2)}
</Box>
)}
</VStack>
</CardSection>
</SimpleGrid>
)
}
function RawQueryTab({ dispatch, loading, setLoading }: {
dispatch: ReturnType<typeof useApp>['dispatch']
loading: string | null
setLoading: (v: string | null) => void
}) {
const [sql, setSql] = useState('')
const [result, setResult] = useState<any>(null)
const execute = async () => {
setLoading('query')
try {
const r = await apiPost('/admin-experimental/execute', { query: sql })
setResult(r)
} catch {
dispatch({ type: 'ADD_TOAST', payload: { message: 'Query failed', type: 'error' } })
} finally { setLoading(null) }
}
return (
<Card.Root bg="card.bg" borderWidth="1px" borderColor="border" borderRadius="xl" boxShadow="card">
<Card.Header borderBottomWidth="1px" borderColor="border" px={5} py={3}>
<Flex align="center" gap={2}>
<FiDatabase size={16} />
<Text fontFamily="Playfair Display, serif" fontSize="md" color="primary.DEFAULT" fontWeight="semibold">
Raw SQL Query
</Text>
</Flex>
</Card.Header>
<Card.Body p={5}>
<Text fontSize="sm" color="fg.muted" mb={4}>Execute read-only SQL queries against the database.</Text>
<VStack align="stretch" gap={4}>
<Textarea
value={sql}
onChange={(e) => setSql(e.target.value)}
placeholder="SELECT * FROM ... LIMIT 100;"
rows={6}
fontFamily="Roboto Mono, monospace"
fontSize="sm"
bg="code.bg"
/>
<Flex gap={2}>
<Button onClick={execute} loading={loading === 'query'}><FiPlay size={14} /> Execute</Button>
<Button variant="outline" onClick={() => { setSql(''); setResult(null) }}><FiRefreshCw size={14} /> Clear</Button>
</Flex>
{result && (
<Box as="pre" fontSize="xs" fontFamily="Roboto Mono, monospace" bg="code.bg" p={4} borderRadius="md" overflow="auto" maxH="500px">
{JSON.stringify(result, null, 2)}
</Box>
)}
</VStack>
</Card.Body>
</Card.Root>
)
}
+200 -85
View File
@@ -1,4 +1,18 @@
import { useState, useEffect } from 'react'
import {
Box,
Heading,
Button,
Flex,
HStack,
Table,
Text,
Spinner,
Dialog,
Portal,
IconButton,
} from '@chakra-ui/react'
import { FiX, FiFolder, FiFile } from 'react-icons/fi'
import client from '../../api/client'
import { useApp } from '../../stores/AppContext'
@@ -52,107 +66,208 @@ export default function FileBrowser() {
const breadcrumbs = path.split('/').filter(Boolean)
return (
<div>
<h1 className="font-serif text-3xl text-primary mb-6">File Browser</h1>
<Box>
<Heading as="h1" fontFamily="Playfair Display, serif" color="primary.DEFAULT" fontSize="2xl" mb={6}>
File Browser
</Heading>
<div className="flex items-center gap-2 mb-4 text-sm">
<button
<HStack gap={1} mb={4} fontSize="sm">
<Button
variant="ghost"
size="sm"
color="primary.DEFAULT"
fontWeight="normal"
_hover={{ textDecoration: 'underline' }}
onClick={() => load('/')}
className="text-primary hover:underline"
>
/
</button>
</Button>
{breadcrumbs.map((crumb, i) => {
const crumbPath = '/' + breadcrumbs.slice(0, i + 1).join('/')
return (
<span key={i} className="flex items-center gap-2">
<span className="text-text-muted">/</span>
<button
<HStack key={i} gap={1}>
<Text color="fg.muted">/</Text>
<Button
variant="ghost"
size="sm"
color="primary.DEFAULT"
fontWeight="normal"
_hover={{ textDecoration: 'underline' }}
onClick={() => load(crumbPath)}
className="text-primary hover:underline"
>
{crumb}
</button>
</span>
</Button>
</HStack>
)
})}
</div>
</HStack>
<div className="bg-card-bg border border-border rounded-lg overflow-hidden">
<table className="w-full text-sm">
<thead>
<tr className="border-b border-border">
<th className="text-left px-4 py-3 text-text-muted font-semibold text-[11px] uppercase">Name</th>
<th className="text-left px-4 py-3 text-text-muted font-semibold text-[11px] uppercase">Size</th>
<th className="text-left px-4 py-3 text-text-muted font-semibold text-[11px] uppercase">Modified</th>
<th className="text-left px-4 py-3 text-text-muted font-semibold text-[11px] uppercase">Actions</th>
</tr>
</thead>
<tbody>
{path !== '/' && (
<tr
className="border-b border-border hover:bg-hover/50 cursor-pointer"
onClick={() => {
const parent = path.substring(0, path.lastIndexOf('/')) || '/'
load(parent)
}}
>
<td className="px-4 py-3 text-text-primary">..</td>
<td className="px-4 py-3">-</td>
<td className="px-4 py-3">-</td>
<td className="px-4 py-3">-</td>
</tr>
)}
{loading ? (
<tr><td colSpan={4} className="px-4 py-8 text-center text-text-muted">Loading...</td></tr>
) : (
files.map((f) => (
<tr
key={f.path}
className="border-b border-border last:border-0 hover:bg-hover/50 cursor-pointer"
onClick={() => f.is_dir && load(f.path)}
<Box bg="card.bg" borderWidth="1px" borderColor="border" borderRadius="xl" overflow="hidden" boxShadow="card">
<Table.ScrollArea>
<Table.Root variant="line" size="sm">
<Table.Header>
<Table.Row bg="bg.subtle">
<Table.ColumnHeader px={4} py={3} fontSize="2xs" fontWeight="semibold" color="fg.muted" textTransform="uppercase" letterSpacing="wider">
Name
</Table.ColumnHeader>
<Table.ColumnHeader px={4} py={3} fontSize="2xs" fontWeight="semibold" color="fg.muted" textTransform="uppercase" letterSpacing="wider">
Size
</Table.ColumnHeader>
<Table.ColumnHeader px={4} py={3} fontSize="2xs" fontWeight="semibold" color="fg.muted" textTransform="uppercase" letterSpacing="wider">
Modified
</Table.ColumnHeader>
<Table.ColumnHeader px={4} py={3} fontSize="2xs" fontWeight="semibold" color="fg.muted" textTransform="uppercase" letterSpacing="wider">
Actions
</Table.ColumnHeader>
</Table.Row>
</Table.Header>
<Table.Body>
{path !== '/' && (
<Table.Row
cursor="pointer"
_hover={{ bg: 'bg.subtle' }}
borderBottomWidth="1px"
borderColor="border"
transition="all 0.15s"
onClick={() => {
const parent = path.substring(0, path.lastIndexOf('/')) || '/'
load(parent)
}}
>
<td className="px-4 py-3 text-text-primary">
{f.is_dir ? '📁' : '📄'} {f.name}
</td>
<td className="px-4 py-3 text-text-muted">{f.is_dir ? '-' : formatBytes(f.size)}</td>
<td className="px-4 py-3 text-text-muted">{new Date(f.mod_time).toLocaleString()}</td>
<td className="px-4 py-3">
{!f.is_dir && (
<button
onClick={(e) => { e.stopPropagation(); view(f.path) }}
className="text-xs text-primary hover:underline"
>
View
</button>
)}
</td>
</tr>
))
)}
</tbody>
</table>
</div>
<Table.Cell px={4} py={3} color="fg">
..
</Table.Cell>
<Table.Cell px={4} py={3}>-</Table.Cell>
<Table.Cell px={4} py={3}>-</Table.Cell>
<Table.Cell px={4} py={3}>-</Table.Cell>
</Table.Row>
)}
{loading ? (
<Table.Row>
<Table.Cell colSpan={4} textAlign="center" py={8}>
<Flex align="center" justify="center" gap={2} color="fg.muted">
<Spinner size="sm" />
<Text fontSize="sm">Loading...</Text>
</Flex>
</Table.Cell>
</Table.Row>
) : files.length === 0 ? (
<Table.Row>
<Table.Cell colSpan={4} textAlign="center" py={8} color="fg.muted" fontSize="sm">
<Flex direction="column" align="center" gap={1}>
<FiFolder size={24} />
<Text>This directory is empty</Text>
</Flex>
</Table.Cell>
</Table.Row>
) : (
files.map((f, i) => (
<Table.Row
key={f.path}
cursor="pointer"
_hover={{ bg: 'bg.subtle' }}
borderBottomWidth="1px"
borderColor="border"
bg={i % 2 === 0 ? 'transparent' : 'bg.subtle'}
transition="all 0.15s"
onClick={() => f.is_dir && load(f.path)}
>
<Table.Cell px={4} py={3} color="fg">
<Flex align="center" gap={2}>
{f.is_dir ? <FiFolder size={16} /> : <FiFile size={16} />}
{f.name}
</Flex>
</Table.Cell>
<Table.Cell px={4} py={3} color="fg.muted">{f.is_dir ? '-' : formatBytes(f.size)}</Table.Cell>
<Table.Cell px={4} py={3} color="fg.muted">{new Date(f.mod_time).toLocaleString()}</Table.Cell>
<Table.Cell px={4} py={3}>
{!f.is_dir && (
<Button
variant="ghost"
size="xs"
color="primary.DEFAULT"
_hover={{ textDecoration: 'underline' }}
onClick={(e) => { e.stopPropagation(); view(f.path) }}
>
View
</Button>
)}
</Table.Cell>
</Table.Row>
))
)}
</Table.Body>
</Table.Root>
</Table.ScrollArea>
</Box>
{viewFile && (
<div className="fixed inset-0 z-[70] flex items-center justify-center bg-black/60 backdrop-blur-sm">
<div className="bg-card-bg border border-border rounded-xl shadow-2xl w-full mx-4 max-w-4xl max-h-[80vh] flex flex-col">
<div className="flex items-center justify-between px-5 py-4 border-b border-border">
<h3 className="font-serif text-lg text-text-primary truncate">{viewFile.path}</h3>
<button
onClick={() => setViewFile(null)}
className="text-text-muted hover:text-text-primary text-xl leading-none"
<Dialog.Root open={!!viewFile} onOpenChange={(details) => { if (!details.open) setViewFile(null) }}>
<Portal>
<Dialog.Backdrop bg="black/60" backdropFilter="blur(4px)" />
<Dialog.Positioner>
<Dialog.Content
bg="card.bg"
borderWidth="1px"
borderColor="border"
borderRadius="xl"
boxShadow="card"
maxW="4xl"
w="full"
mx={4}
maxH="80vh"
display="flex"
flexDirection="column"
>
<Dialog.Header
display="flex"
alignItems="center"
justifyContent="space-between"
borderBottomWidth="1px"
borderColor="border"
px={5}
py={4}
>
&times;
</button>
</div>
<pre className="p-5 overflow-auto flex-1 text-xs font-mono text-text-secondary bg-code-bg">
{viewFile.content}
</pre>
</div>
</div>
)}
</div>
<Dialog.Title
fontSize="lg"
fontFamily="Playfair Display, serif"
color="primary.DEFAULT"
truncate
>
{viewFile?.path}
</Dialog.Title>
<Dialog.CloseTrigger asChild>
<IconButton
aria-label="Close"
variant="ghost"
size="sm"
onClick={() => setViewFile(null)}
color="fg.muted"
_hover={{ color: 'fg' }}
>
<FiX />
</IconButton>
</Dialog.CloseTrigger>
</Dialog.Header>
<Dialog.Body p={5} overflow="auto" flex={1}>
<Box
as="pre"
fontSize="xs"
fontFamily="Roboto Mono, monospace"
color="fg"
bg="code.bg"
p={4}
borderRadius="md"
overflow="auto"
whiteSpace="pre-wrap"
>
{viewFile?.content}
</Box>
</Dialog.Body>
</Dialog.Content>
</Dialog.Positioner>
</Portal>
</Dialog.Root>
</Box>
)
}
+212 -64
View File
@@ -1,5 +1,17 @@
import { useState } from 'react'
import useSWR from 'swr'
import {
Box,
Heading,
Input,
HStack,
VStack,
SimpleGrid,
Button,
Table,
Text,
} from '@chakra-ui/react'
import { FiSearch, FiTrash2, FiAlertTriangle } from 'react-icons/fi'
import client from '../../api/client'
import { useApp } from '../../stores/AppContext'
import DataTable from '../common/DataTable'
@@ -24,6 +36,19 @@ interface GuildMember {
online_status: string
}
function InfoRow({ label, value }: { label: string; value: any }) {
return (
<Box>
<Text fontSize="xs" textTransform="uppercase" letterSpacing="wider" color="fg.muted">
{label}
</Text>
<Text fontFamily="Roboto Mono, monospace" color="fg">
{value ?? 'N/A'}
</Text>
</Box>
)
}
export default function GuildManager() {
const [search, setSearch] = useState('')
const [selected, setSelected] = useState<Guild | null>(null)
@@ -82,23 +107,38 @@ export default function GuildManager() {
const guildList: Guild[] = guilds?.success ? guilds.data : []
return (
<div>
<h1 className="font-serif text-3xl text-primary mb-6">Guild Manager</h1>
<Box>
<Heading as="h1" fontSize="3xl" fontFamily="Playfair Display, serif" color="primary.DEFAULT" mb={6}>
Guild Manager
</Heading>
<div className="mb-6">
<div className="relative max-w-md">
<input
type="text"
value={search}
onChange={(e) => setSearch(e.target.value)}
placeholder="Search guilds..."
className="w-full bg-card-bg border border-border rounded-lg px-4 py-2.5 pl-10 text-sm text-text-primary placeholder-text-muted focus:outline-none focus:border-primary focus:ring-1 focus:ring-primary"
/>
<svg className="absolute left-3 top-3 w-4 h-4 text-text-muted" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0" />
</svg>
</div>
</div>
<Box position="relative" maxW="md" mb={6}>
<Box
position="absolute"
left={3}
top="50%"
transform="translateY(-50%)"
color="fg.muted"
zIndex={1}
pointerEvents="none"
>
<FiSearch size={16} />
</Box>
<Input
type="text"
value={search}
onChange={(e) => setSearch(e.target.value)}
placeholder="Search guilds..."
pl={10}
bg="card.bg"
borderColor="border"
borderRadius="lg"
fontSize="sm"
color="fg"
_placeholder={{ color: 'fg.muted' }}
_focus={{ borderColor: 'primary.DEFAULT' }}
/>
</Box>
<DataTable
columns={[
@@ -108,65 +148,173 @@ export default function GuildManager() {
{ header: 'Online', accessor: 'online_count' },
]}
data={guildList}
onRowClick={(row) => { setSelected(row); loadDetail(row.guild_id) }}
onRowClick={(row) => {
setSelected(row as any)
loadDetail((row as any).guild_id)
}}
loading={isLoading}
/>
<Modal open={!!selected} title={selected?.guild_name || ''} onClose={() => { setSelected(null); setDetail(null) }} maxWidth="700px">
<Modal
open={!!selected}
title={selected?.guild_name || ''}
onClose={() => {
setSelected(null)
setDetail(null)
}}
>
{selected && detail && (
<div className="space-y-4">
<div className="grid grid-cols-2 gap-4 text-sm">
<VStack gap={4} align="stretch">
<SimpleGrid columns={2} gap={4}>
<InfoRow label="Guild ID" value={selected.guild_id} />
<InfoRow label="Members" value={selected.member_count} />
<InfoRow label="Faction" value={selected.faction_name || 'None'} />
<InfoRow label="Description" value={selected.guild_description || 'None'} />
</div>
</SimpleGrid>
<div className="border-t border-border pt-4">
<h4 className="text-text-muted text-xs uppercase tracking-wider mb-3">Members</h4>
<div className="overflow-x-auto rounded-lg border border-border max-h-64 overflow-y-auto">
<table className="w-full text-sm">
<thead className="sticky top-0 bg-card-bg">
<tr className="border-b border-border">
<th className="text-left px-3 py-2 text-text-muted text-[11px] uppercase">Name</th>
<th className="text-left px-3 py-2 text-text-muted text-[11px] uppercase">Role</th>
<th className="text-left px-3 py-2 text-text-muted text-[11px] uppercase">Status</th>
<th className="text-left px-3 py-2 text-text-muted text-[11px] uppercase">Actions</th>
</tr>
</thead>
<tbody>
{(detail.members || []).map((m: GuildMember) => (
<tr key={m.player_id} className="border-b border-border last:border-0">
<td className="px-3 py-2">{m.player_name}</td>
<td className="px-3 py-2"><span className="px-2 py-0.5 rounded text-[10px] bg-primary/10 text-primary border border-primary/20">{m.role_name}</span></td>
<td className="px-3 py-2 text-xs">{m.online_status}</td>
<td className="px-3 py-2 flex gap-1">
<button onClick={() => handleMemberAction('promote', m.player_id, 90)} className="text-[10px] text-primary hover:underline">Promote</button>
<button onClick={() => handleMemberAction('demote', m.player_id, 50)} className="text-[10px] text-text-muted hover:underline">Demote</button>
<button onClick={() => handleMemberAction('remove', m.player_id)} className="text-[10px] text-danger hover:underline">Remove</button>
</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
<Box borderTopWidth="1px" borderColor="border" pt={4}>
<Text fontSize="xs" textTransform="uppercase" letterSpacing="wider" color="fg.muted" mb={3}>
Members
</Text>
<Table.ScrollArea borderWidth="1px" borderColor="border" borderRadius="lg" maxH="64">
<Table.Root size="sm" variant="line" stickyHeader>
<Table.Header>
<Table.Row bg="bg.subtle">
<Table.ColumnHeader
fontSize="2xs"
textTransform="uppercase"
letterSpacing="wider"
color="fg.muted"
>
Name
</Table.ColumnHeader>
<Table.ColumnHeader
fontSize="2xs"
textTransform="uppercase"
letterSpacing="wider"
color="fg.muted"
>
Role
</Table.ColumnHeader>
<Table.ColumnHeader
fontSize="2xs"
textTransform="uppercase"
letterSpacing="wider"
color="fg.muted"
>
Status
</Table.ColumnHeader>
<Table.ColumnHeader
fontSize="2xs"
textTransform="uppercase"
letterSpacing="wider"
color="fg.muted"
>
Actions
</Table.ColumnHeader>
</Table.Row>
</Table.Header>
<Table.Body>
{(detail.members || []).length === 0 ? (
<Table.Row>
<Table.Cell colSpan={4} textAlign="center" py={8}>
<VStack gap={2} color="fg.muted">
<FiAlertTriangle size={24} />
<Text fontSize="sm">No members found</Text>
</VStack>
</Table.Cell>
</Table.Row>
) : (
(detail.members || []).map((m: GuildMember) => (
<Table.Row
key={m.player_id}
borderBottomWidth="1px"
borderColor="border"
_hover={{ bg: 'bg.subtle' }}
transition="all 0.15s"
>
<Table.Cell py={2} px={3}>
{m.player_name}
</Table.Cell>
<Table.Cell py={2} px={3}>
<Text
as="span"
fontSize="2xs"
bg="primary.subtle"
color="primary.DEFAULT"
borderWidth="1px"
borderColor="primary.DEFAULT/20"
borderRadius="full"
px={2}
py={0.5}
>
{m.role_name}
</Text>
</Table.Cell>
<Table.Cell py={2} px={3} fontSize="xs">
{m.online_status}
</Table.Cell>
<Table.Cell py={2} px={3}>
<HStack gap={1}>
<Button
variant="ghost"
size="xs"
fontSize="2xs"
color="primary.DEFAULT"
_hover={{ textDecoration: 'underline' }}
onClick={() => handleMemberAction('promote', m.player_id, 90)}
>
Promote
</Button>
<Button
variant="ghost"
size="xs"
fontSize="2xs"
color="fg.muted"
_hover={{ textDecoration: 'underline', color: 'fg' }}
onClick={() => handleMemberAction('demote', m.player_id, 50)}
>
Demote
</Button>
<Button
variant="ghost"
size="xs"
fontSize="2xs"
color="danger.DEFAULT"
_hover={{ textDecoration: 'underline' }}
onClick={() => handleMemberAction('remove', m.player_id)}
>
Remove
</Button>
</HStack>
</Table.Cell>
</Table.Row>
))
)}
</Table.Body>
</Table.Root>
</Table.ScrollArea>
</Box>
<div className="flex gap-2 pt-4 border-t border-border">
<button onClick={handleDisband} className="px-3 py-1.5 rounded text-xs font-medium bg-danger/10 border border-danger/30 text-danger hover:bg-danger/20">Disband Guild</button>
</div>
</div>
<Box borderTopWidth="1px" borderColor="border" pt={4}>
<Button
variant="outline"
size="xs"
borderColor="danger.DEFAULT/30"
color="danger.DEFAULT"
bg="danger.subtle"
borderRadius="lg"
_hover={{ bg: 'danger.subtle/80' }}
transition="all 0.15s"
onClick={handleDisband}
>
<FiTrash2 size={12} style={{ marginRight: 6 }} />
Disband Guild
</Button>
</Box>
</VStack>
)}
</Modal>
</div>
)
}
function InfoRow({ label, value }: { label: string; value: any }) {
return (
<div>
<div className="text-text-muted text-xs uppercase tracking-wider">{label}</div>
<div className="text-text-primary font-mono">{value ?? 'N/A'}</div>
</div>
</Box>
)
}
+23 -11
View File
@@ -1,15 +1,27 @@
import { ReactNode } from 'react'
import NavBar from './NavBar'
import ToastProvider from '../common/ToastProvider'
import { Box, Flex } from '@chakra-ui/react'
import { Toaster, ToastRoot, ToastTitle, ToastDescription } from '@chakra-ui/react'
import Sidebar from './Sidebar'
import TopBar from './TopBar'
import { toaster } from '../../toaster'
export default function AppShell({ children }: { children: ReactNode }) {
export default function AppShell({ children }: { children: React.ReactNode }) {
return (
<div className="min-h-screen bg-background text-text-primary">
<NavBar />
<main className="p-6 max-w-[1600px] mx-auto">
<ToastProvider />
{children}
</main>
</div>
<Flex minH="100vh" bg="bg">
<Sidebar />
<Box flex={1} ml="260px">
<TopBar />
<Box as="main" p={6} minH="calc(100vh - 56px)">
{children}
</Box>
</Box>
<Toaster toaster={toaster}>
{(toast: any) => (
<ToastRoot key={toast.id}>
{toast.title && <ToastTitle>{toast.title}</ToastTitle>}
{toast.description && <ToastDescription>{toast.description}</ToastDescription>}
</ToastRoot>
)}
</Toaster>
</Flex>
)
}
@@ -1,21 +1,70 @@
import { Box, Flex, Text, Tooltip, VStack, Circle } from '@chakra-ui/react'
import { FiWifi, FiWifiOff } from 'react-icons/fi'
import { useApp } from '../../stores/AppContext'
const SERVICES = [
{ key: 'database' as const, label: 'Database' },
{ key: 'ssh' as const, label: 'SSH Tunnel' },
{ key: 'bgd' as const, label: 'BG Director' },
{ key: 'rmq' as const, label: 'RMQ' },
]
export default function ConnectionBadge() {
const { state } = useApp()
const { database, ssh, bgd, rmq } = state.connectionStatus
const allOk = database && ssh && bgd && rmq
const someDown = !allOk && (database || ssh || bgd || rmq)
const statuses = SERVICES.map((s) => state.connectionStatus[s.key])
const upCount = statuses.filter(Boolean).length
const allUp = upCount === statuses.length
const allDown = upCount === 0
const dotColor = allUp ? 'success.DEFAULT' : allDown ? 'danger.DEFAULT' : 'warning.DEFAULT'
return (
<div className="flex items-center gap-2">
<div
className="w-2.5 h-2.5 rounded-full"
style={{
backgroundColor: allOk ? '#27ae60' : someDown ? '#f39c12' : '#c0392b',
boxShadow: `0 0 6px ${allOk ? '#27ae60' : someDown ? '#f39c12' : '#c0392b'}`,
}}
title={`DB: ${database ? 'OK' : 'DOWN'} | SSH: ${ssh ? 'OK' : 'DOWN'} | BGD: ${bgd ? 'OK' : 'DOWN'} | RMQ: ${rmq ? 'OK' : 'DOWN'}`}
/>
</div>
<Tooltip.Root>
<Tooltip.Trigger asChild>
<Flex
align="center"
gap={1.5}
px={2.5}
py={1}
borderRadius="full"
bg="bg.subtle"
border="1px solid"
borderColor="border.subtle"
cursor="default"
>
{allUp ? (
<FiWifi size={14} color="currentColor" />
) : (
<FiWifiOff size={14} color="currentColor" />
)}
<Circle size="6px" bg={dotColor} />
</Flex>
</Tooltip.Trigger>
<Tooltip.Positioner>
<Tooltip.Content bg="card.bg" border="1px solid" borderColor="border" borderRadius="md" p={3}>
<VStack align="stretch" gap={2} minW="160px">
<Text fontSize="xs" fontWeight="semibold" color="fg" mb={1}>
Service Status
</Text>
{SERVICES.map((s) => (
<Flex key={s.key} justify="space-between" align="center" gap={4}>
<Text fontSize="xs" color="fg.muted">
{s.label}
</Text>
<Flex align="center" gap={1.5}>
<Circle
size="6px"
bg={state.connectionStatus[s.key] ? 'success.DEFAULT' : 'danger.DEFAULT'}
/>
<Text fontSize="2xs" color="fg.muted">
{state.connectionStatus[s.key] ? 'OK' : 'DOWN'}
</Text>
</Flex>
</Flex>
))}
</VStack>
</Tooltip.Content>
</Tooltip.Positioner>
</Tooltip.Root>
)
}
+192
View File
@@ -0,0 +1,192 @@
import { useState } from 'react'
import { Link, useLocation } from 'react-router-dom'
import { Box, Flex, VStack, Text, Collapsible, Separator } from '@chakra-ui/react'
import { FiHome, FiServer, FiUsers, FiShield, FiMap, FiTruck, FiBox, FiMessageSquare, FiTool, FiSliders, FiUserCheck, FiFolder, FiTerminal, FiSettings, FiZap } from 'react-icons/fi'
interface NavGroup {
label: string
icon: React.ElementType
items: { path: string; label: string; icon: React.ElementType }[]
}
const NAV_GROUPS: NavGroup[] = [
{
label: 'Dashboard',
icon: FiHome,
items: [
{ path: '/', label: 'Overview', icon: FiHome },
{ path: '/server', label: 'Server', icon: FiServer },
],
},
{
label: 'Players & World',
icon: FiUsers,
items: [
{ path: '/players', label: 'Players', icon: FiUsers },
{ path: '/guilds', label: 'Guilds', icon: FiShield },
{ path: '/map', label: 'Map', icon: FiMap },
{ path: '/vehicles', label: 'Vehicles', icon: FiTruck },
{ path: '/buildings', label: 'Buildings', icon: FiBox },
],
},
{
label: 'Communication',
icon: FiMessageSquare,
items: [
{ path: '/chat', label: 'Chat Monitor', icon: FiMessageSquare },
],
},
{
label: 'Administration',
icon: FiTool,
items: [
{ path: '/admin', label: 'Admin Tools', icon: FiTool },
{ path: '/director', label: 'Director', icon: FiSliders },
{ path: '/accounts', label: 'Accounts', icon: FiUserCheck },
],
},
{
label: 'System',
icon: FiFolder,
items: [
{ path: '/files', label: 'Files', icon: FiFolder },
{ path: '/shell', label: 'Shell', icon: FiTerminal },
{ path: '/settings', label: 'Settings', icon: FiSettings },
],
},
{
label: 'Experimental',
icon: FiZap,
items: [
{ path: '/experimental', label: 'Experimental', icon: FiZap },
],
},
]
export default function Sidebar() {
return (
<Box
as="aside"
w="260px"
minW="260px"
h="100vh"
position="fixed"
left={0}
top={0}
bg="nav.bg"
color="fg"
overflowY="auto"
borderRight="1px solid"
borderColor="border"
zIndex={40}
>
<Flex align="center" px={5} py={4} borderBottom="1px solid" borderColor="border">
<Text
fontFamily="Playfair Display, serif"
fontSize="xl"
fontWeight="bold"
color="primary.DEFAULT"
letterSpacing="wider"
>
Dune
</Text>
<Text
fontSize="2xs"
color="fg.muted"
ml={2}
mt={1}
letterSpacing="widest"
textTransform="uppercase"
>
Admin
</Text>
</Flex>
<VStack gap={1} px={2} py={3} align="stretch">
{NAV_GROUPS.map((group) => (
<NavGroupSection key={group.label} group={group} />
))}
</VStack>
</Box>
)
}
function NavGroupSection({ group }: { group: NavGroup }) {
const location = useLocation()
const groupActive = group.items.some(
(item) =>
location.pathname === item.path ||
(item.path !== '/' && location.pathname.startsWith(item.path))
)
const [open, setOpen] = useState(groupActive)
return (
<Collapsible.Root open={open} onOpenChange={(e) => setOpen(e.open)}>
<Collapsible.Trigger
asChild
cursor="pointer"
display="flex"
alignItems="center"
gap={2}
px={3}
py={2}
borderRadius="md"
fontSize="xs"
fontWeight="semibold"
color="fg.muted"
textTransform="uppercase"
letterSpacing="wider"
_hover={{ bg: 'bg.subtle', color: 'fg' }}
transition="all 0.15s"
>
<Flex align="center" gap={2} w="full">
<Box as="span" fontSize="sm">
<group.icon />
</Box>
<Text flex={1}>{group.label}</Text>
<Collapsible.Indicator
transform={open ? 'rotate(180deg)' : 'rotate(0deg)'}
transition="transform 0.15s"
/>
</Flex>
</Collapsible.Trigger>
<Collapsible.Content>
<VStack gap={0} align="stretch" pl={6} mt={1}>
{group.items.map((item) => {
const active =
location.pathname === item.path ||
(item.path !== '/' && location.pathname.startsWith(item.path))
return (
<Link key={item.path} to={item.path}>
<Flex
align="center"
gap={2}
px={3}
py={2}
borderRadius="md"
fontSize="sm"
fontWeight={active ? 'semibold' : 'normal'}
color={active ? 'primary.DEFAULT' : 'fg.muted'}
bg={active ? 'primary.subtle' : 'transparent'}
borderLeft={active ? '3px solid' : '3px solid transparent'}
borderColor={active ? 'primary.DEFAULT' : 'transparent'}
_hover={
!active
? { bg: 'bg.subtle', color: 'fg' }
: {}
}
transition="all 0.15s"
>
<Box as="span" fontSize="xs" opacity={active ? 1 : 0.6}>
<item.icon />
</Box>
<Text>{item.label}</Text>
</Flex>
</Link>
)
})}
</VStack>
</Collapsible.Content>
</Collapsible.Root>
)
}
+105 -58
View File
@@ -1,68 +1,115 @@
import { useState, useRef, useEffect } from 'react'
import {
Box,
Flex,
Text,
Menu,
Button,
HStack,
IconButton,
Tooltip,
Portal,
} from '@chakra-ui/react'
import { FiSun, FiMoon, FiChevronDown } from 'react-icons/fi'
import { useApp } from '../../stores/AppContext'
const THEMES = [
{ key: 'default', label: 'Classic Dune' },
{ key: 'atreides', label: 'House Atreides' },
{ key: 'harkonnen', label: 'House Harkonnen' },
{ key: 'fremen', label: 'Fremen' },
{ key: 'bene-gesserit', label: 'Bene Gesserit' },
{ key: 'spacing-guild', label: 'Spacing Guild' },
{ key: 'emperor', label: 'Emperor' },
{ key: 'corrino', label: 'House Corrino' },
{ key: 'mentat', label: 'Mentat' },
{ key: 'sardaukar', label: 'Sardaukar' },
{ key: 'tleilax', label: 'Bene Tleilax' },
{ key: 'ordos', label: 'House Ordos' },
{ key: 'ix', label: 'Ix' },
{ key: 'choam', label: 'CHOAM' },
]
import { FACTION_KEYS, getFactionName } from '../../themes'
import type { FactionKey } from '../../themes/palettes'
export default function ThemeSwitcher() {
const { state, dispatch } = useApp()
const [open, setOpen] = useState(false)
const ref = useRef<HTMLDivElement>(null)
useEffect(() => {
function handleClick(e: MouseEvent) {
if (ref.current && !ref.current.contains(e.target as Node)) {
setOpen(false)
}
}
document.addEventListener('mousedown', handleClick)
return () => document.removeEventListener('mousedown', handleClick)
}, [])
const handleFactionChange = (key: FactionKey) => {
dispatch({ type: 'SET_FACTION', payload: key })
}
const toggleColorMode = () => {
dispatch({
type: 'SET_COLOR_MODE',
payload: state.colorMode === 'day' ? 'night' : 'day',
})
}
return (
<div className="relative" ref={ref}>
<button
onClick={() => setOpen(!open)}
className="w-6 h-6 rounded-full"
style={{ background: 'linear-gradient(135deg, var(--primary) 50%, var(--bg) 50%)' }}
title="Change theme"
/>
{open && (
<div className="absolute right-0 mt-2 w-56 bg-card-bg border border-border rounded-lg shadow-xl z-50 py-2">
{THEMES.map((t) => (
<button
key={t.key}
onClick={() => {
dispatch({ type: 'SET_THEME', payload: t.key })
setOpen(false)
}}
className={`w-full text-left px-4 py-2 text-sm flex items-center gap-3 hover:bg-hover transition-colors ${
state.theme === t.key ? 'text-primary font-semibold' : 'text-text-secondary'
}`}
<HStack gap={1}>
<Tooltip.Root>
<Tooltip.Trigger asChild>
<IconButton
aria-label="Toggle color mode"
variant="ghost"
size="sm"
onClick={toggleColorMode}
color="fg.muted"
w={8}
h={8}
>
{state.colorMode === 'day' ? <FiSun size={16} /> : <FiMoon size={16} />}
</IconButton>
</Tooltip.Trigger>
<Tooltip.Positioner>
<Tooltip.Content bg="card.bg" border="1px solid" borderColor="border" borderRadius="md" px={3} py={1}>
{state.colorMode === 'day' ? 'Switch to Night' : 'Switch to Day'}
</Tooltip.Content>
</Tooltip.Positioner>
</Tooltip.Root>
<Menu.Root>
<Menu.Trigger asChild>
<Button
variant="outline"
size="sm"
borderColor="border"
color="fg"
_hover={{ borderColor: 'primary.DEFAULT', color: 'primary.DEFAULT' }}
gap={2}
>
<Box
w={2.5}
h={2.5}
borderRadius="full"
bg="primary.DEFAULT"
/>
<Text fontSize="xs">{getFactionName(state.faction)}</Text>
<FiChevronDown size={12} />
</Button>
</Menu.Trigger>
<Portal>
<Menu.Positioner>
<Menu.Content
bg="card.bg"
borderColor="border"
borderRadius="lg"
boxShadow="card"
maxH="400px"
overflowY="auto"
>
<span
className="w-4 h-4 rounded border border-border"
style={{ background: `linear-gradient(135deg, var(--primary) 50%, var(--bg) 50%)` }}
/>
{t.label}
</button>
))}
</div>
)}
</div>
<Menu.ItemGroup title="Factions">
{FACTION_KEYS.map((key) => (
<Menu.Item
key={key}
value={key}
onClick={() => handleFactionChange(key)}
bg={state.faction === key ? 'primary.subtle' : 'transparent'}
color={state.faction === key ? 'primary.DEFAULT' : 'fg'}
fontWeight={state.faction === key ? 'semibold' : 'normal'}
_hover={{ bg: 'bg.subtle' }}
cursor="pointer"
py={2}
>
<Flex align="center" gap={3}>
<Box
w={3}
h={3}
borderRadius="full"
bg="primary.DEFAULT"
/>
<Text>{getFactionName(key)}</Text>
</Flex>
</Menu.Item>
))}
</Menu.ItemGroup>
</Menu.Content>
</Menu.Positioner>
</Portal>
</Menu.Root>
</HStack>
)
}
+73
View File
@@ -0,0 +1,73 @@
import { Flex, Text, HStack, Box, Input, InputGroup } from '@chakra-ui/react'
import { FiSearch, FiUser } from 'react-icons/fi'
import { useApp } from '../../stores/AppContext'
import ConnectionBadge from './ConnectionBadge'
import ThemeSwitcher from './ThemeSwitcher'
export default function TopBar() {
const { state } = useApp()
return (
<Flex
as="header"
h="56px"
align="center"
px={6}
gap={4}
bg="bg"
borderBottom="1px solid"
borderColor="border"
position="sticky"
top={0}
zIndex={30}
>
<Box flex={1} maxW="400px">
<InputGroup
startElement={
<Box pl={3} color="fg.muted">
<FiSearch size={14} />
</Box>
}
w="full"
>
<Input
placeholder="Search players, guilds, accounts..."
size="sm"
borderRadius="lg"
bg="bg.subtle"
border="1px solid"
borderColor="border"
color="fg"
_placeholder={{ color: 'fg.muted' }}
_hover={{ borderColor: 'border' }}
_focus={{ borderColor: 'primary.DEFAULT', boxShadow: `0 0 0 1px var(--chakra-colors-primary-DEFAULT)` }}
fontSize="xs"
pl={8}
/>
</InputGroup>
</Box>
<HStack gap={3} ml="auto">
<ConnectionBadge />
<ThemeSwitcher />
{state.user && (
<Flex
align="center"
gap={2}
px={3}
py={1}
borderRadius="full"
bg="primary.subtle"
border="1px solid"
borderColor="primary.subtle"
>
<FiUser size={12} />
<Text fontSize="xs" color="primary.DEFAULT" fontWeight="medium">
{state.user}
</Text>
</Flex>
)}
</HStack>
</Flex>
)
}
+71 -24
View File
@@ -1,4 +1,6 @@
import { useState, useEffect, useRef } from 'react'
import { Box, Flex, Heading, Button, Text } from '@chakra-ui/react'
import { FiMap, FiRefreshCw } from 'react-icons/fi'
import useSWR from 'swr'
import client from '../../api/client'
@@ -12,6 +14,8 @@ interface MapMarker {
type: 'player' | 'vehicle' | 'building' | 'landclaim'
}
const FILTERS = ['all', 'player', 'vehicle', 'building'] as const
export default function MapViewer() {
const canvasRef = useRef<HTMLCanvasElement>(null)
const [markers, setMarkers] = useState<MapMarker[]>([])
@@ -112,46 +116,89 @@ export default function MapViewer() {
const handleMouseUp = () => setIsDragging(false)
return (
<div className="h-[calc(100vh-140px)] flex flex-col">
<div className="flex items-center justify-between mb-4">
<h1 className="font-serif text-3xl text-primary">Map Viewer</h1>
<div className="flex gap-2">
{(['all', 'player', 'vehicle', 'building'] as const).map((f) => (
<button
<Box h="calc(100vh - 140px)" display="flex" flexDirection="column">
<Flex align="center" justify="space-between" mb={4}>
<Heading
as="h1"
fontSize="3xl"
fontFamily="Playfair Display, serif"
color="primary.DEFAULT"
>
Map Viewer
</Heading>
<Flex gap={2}>
{FILTERS.map((f) => (
<Button
key={f}
onClick={() => setFilter(f)}
className={`px-3 py-1.5 rounded text-xs font-medium border capitalize ${
filter === f
? 'bg-primary/10 border-primary text-primary'
: 'bg-card-bg border-border text-text-muted hover:text-text-primary'
}`}
size="xs"
variant={filter === f ? 'solid' : 'outline'}
bg={filter === f ? 'primary.DEFAULT' : 'transparent'}
color={filter === f ? 'white' : 'fg.muted'}
borderColor={filter === f ? 'primary.DEFAULT' : 'border'}
_hover={filter === f ? {} : { color: 'fg', borderColor: 'fg.muted' }}
textTransform="capitalize"
borderRadius="md"
>
{f}
</button>
</Button>
))}
<button
<Button
onClick={() => { setScale(1); setOffset({ x: 0, y: 0 }) }}
className="px-3 py-1.5 rounded text-xs font-medium border bg-card-bg border-border text-text-muted hover:text-text-primary"
size="xs"
variant="outline"
borderColor="border"
color="fg.muted"
_hover={{ color: 'fg', borderColor: 'fg.muted' }}
borderRadius="md"
gap={1}
>
<FiRefreshCw size={12} />
Reset View
</button>
</div>
</div>
</Button>
</Flex>
</Flex>
<div className="flex-1 bg-card-bg border border-border rounded-lg overflow-hidden relative">
<canvas
<Box
flex={1}
bg="card.bg"
borderWidth="1px"
borderColor="border"
borderRadius="lg"
overflow="hidden"
position="relative"
>
<Box
as="canvas"
ref={canvasRef}
className="w-full h-full cursor-grab active:cursor-grabbing"
w="full"
h="full"
cursor="grab"
_active={{ cursor: 'grabbing' }}
onWheel={handleWheel}
onMouseDown={handleMouseDown}
onMouseMove={handleMouseMove}
onMouseUp={handleMouseUp}
onMouseLeave={handleMouseUp}
/>
<div className="absolute bottom-4 left-4 bg-card-bg/90 border border-border rounded px-3 py-2 text-xs text-text-muted">
<Box
position="absolute"
bottom={4}
left={4}
bg="card.bg"
opacity={0.9}
borderWidth="1px"
borderColor="border"
borderRadius="md"
px={3}
py={2}
fontSize="xs"
color="fg.muted"
backdropFilter="blur(8px)"
>
Zoom: {scale.toFixed(1)}x | Markers: {markers.length}
</div>
</div>
</div>
</Box>
</Box>
</Box>
)
}
+233 -75
View File
@@ -1,4 +1,10 @@
import { useState, useEffect } from 'react'
import {
Box, Flex, Text, Heading, SimpleGrid,
Card, Spinner, Progress, Separator, HStack, Circle, VStack
} from '@chakra-ui/react'
import { PieChart, Pie, Cell, ResponsiveContainer, Tooltip as RechartsTooltip } from 'recharts'
import { FiUsers, FiActivity, FiShield, FiServer, FiMap, FiDollarSign, FiFileText, FiDatabase, FiTerminal, FiRadio, FiMessageSquare } from 'react-icons/fi'
import client from '../../api/client'
import { useApp } from '../../stores/AppContext'
@@ -13,10 +19,26 @@ interface Metrics {
total_flavor_text: number
}
const STAT_CARDS = [
{ key: 'total_players', label: 'Total Players', icon: FiUsers, color: 'primary' },
{ key: 'online_players', label: 'Online', icon: FiActivity, color: 'success' },
{ key: 'guild_count', label: 'Guilds', icon: FiShield, color: 'info' },
{ key: 'active_guilds', label: 'Active Guilds', icon: FiShield, color: 'warning' },
{ key: 'server_count', label: 'Servers', icon: FiServer, color: 'primary' },
{ key: 'partition_count', label: 'Partitions', icon: FiMap, color: 'info' },
{ key: 'total_worth', label: 'Total Worth', icon: FiDollarSign, color: 'success' },
{ key: 'total_flavor_text', label: 'Flavor Text', icon: FiFileText, color: 'warning' },
] as const
function formatValue(key: string, value: number): string {
if (key === 'total_worth') return '$' + Math.round(value).toLocaleString()
return value.toLocaleString()
}
export default function Overview() {
const [metrics, setMetrics] = useState<Metrics | null>(null)
const [loading, setLoading] = useState(true)
const { dispatch } = useApp()
const { state } = useApp()
useEffect(() => {
async function load() {
@@ -42,87 +64,223 @@ export default function Overview() {
return () => es.close()
}, [])
const statCards = metrics
const onlineRatio = metrics
? [
{ label: 'Total Players', value: metrics.total_players.toLocaleString(), icon: '👥' },
{ label: 'Online Players', value: metrics.online_players.toLocaleString(), icon: '🟢' },
{ label: 'Guilds', value: metrics.guild_count.toLocaleString(), icon: '🛡️' },
{ label: 'Active Guilds', value: metrics.active_guilds.toLocaleString(), icon: '⚔️' },
{ label: 'Servers', value: metrics.server_count.toLocaleString(), icon: '🖥️' },
{ label: 'Partitions', value: metrics.partition_count.toLocaleString(), icon: '🗺️' },
{ label: 'Total Worth', value: '$' + Math.round(metrics.total_worth).toLocaleString(), icon: '💰' },
{ label: 'Flavor Text', value: metrics.total_flavor_text.toLocaleString(), icon: '📝' },
]
{ name: 'Online', value: metrics.online_players, color: 'var(--chakra-colors-success-DEFAULT)' },
{ name: 'Offline', value: Math.max(0, metrics.total_players - metrics.online_players), color: 'var(--chakra-colors-border-DEFAULT)' },
]
: []
const guildRatio = metrics
? [
{ name: 'Active', value: metrics.active_guilds, color: 'var(--chakra-colors-warning-DEFAULT)' },
{ name: 'Inactive', value: Math.max(0, metrics.guild_count - metrics.active_guilds), color: 'var(--chakra-colors-border-DEFAULT)' },
]
: []
const healthItems = [
{ label: 'Database', key: 'database' as const, icon: FiDatabase },
{ label: 'SSH Tunnel', key: 'ssh' as const, icon: FiTerminal },
{ label: 'BG Director', key: 'bgd' as const, icon: FiRadio },
{ label: 'RMQ Game', key: 'rmq' as const, icon: FiMessageSquare },
]
return (
<div>
<h1 className="font-serif text-3xl text-primary mb-6">Dashboard Overview</h1>
<Box>
<Heading
as="h1"
fontSize="3xl"
fontFamily="Playfair Display, serif"
color="primary.DEFAULT"
mb={6}
>
Dashboard Overview
</Heading>
{loading ? (
<div className="text-text-muted">Loading metrics...</div>
<Flex align="center" justify="center" py={16}>
<VStack gap={3}>
<Spinner size="lg" color="primary.DEFAULT" />
<Text color="fg.muted" fontSize="sm">Loading metrics...</Text>
</VStack>
</Flex>
) : (
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
{statCards.map((card) => (
<div
key={card.label}
className="bg-card-bg border border-border rounded-lg p-5 shadow-card"
>
<div className="flex items-center justify-between mb-2">
<span className="text-2xl">{card.icon}</span>
</div>
<div className="text-2xl font-bold text-text-primary mb-1">{card.value}</div>
<div className="text-sm text-text-muted">{card.label}</div>
</div>
))}
</div>
<>
<SimpleGrid columns={{ base: 1, sm: 2, lg: 4 }} gap={4}>
{STAT_CARDS.map(({ key, label, icon: Icon, color }) => (
<Card.Root
key={key}
bg="card.bg"
borderWidth="1px"
borderColor="border"
borderRadius="xl"
boxShadow="card"
_hover={{ transform: 'translateY(-2px)', boxShadow: 'lg' }}
transition="all 0.2s"
>
<Card.Body p={5}>
<Flex justify="space-between" align="start" mb={2}>
<Box
w={10}
h={10}
borderRadius="lg"
bg={`${color}.subtle`}
display="flex"
alignItems="center"
justifyContent="center"
color={`${color}.DEFAULT`}
>
<Icon size={20} />
</Box>
</Flex>
<Text
fontSize="2xl"
fontWeight="bold"
color="fg"
fontFamily="Roboto Mono, monospace"
>
{metrics ? formatValue(key, metrics[key as keyof Metrics]) : '-'}
</Text>
<Text fontSize="xs" color="fg.muted" mt={1}>
{label}
</Text>
</Card.Body>
</Card.Root>
))}
</SimpleGrid>
<SimpleGrid columns={{ base: 1, lg: 2 }} gap={6} mt={8}>
<Card.Root bg="card.bg" borderWidth="1px" borderColor="border" borderRadius="xl" boxShadow="card">
<Card.Header borderBottomWidth="1px" borderColor="border" px={5} py={4}>
<Text fontFamily="Playfair Display, serif" fontSize="lg" color="primary.DEFAULT" fontWeight="semibold">
Player Activity
</Text>
</Card.Header>
<Card.Body p={5}>
{metrics && onlineRatio.length > 0 ? (
<Flex align="center" gap={8}>
<Box w="160px" h="160px">
<ResponsiveContainer width="100%" height="100%">
<PieChart>
<Pie
data={onlineRatio}
cx="50%"
cy="50%"
innerRadius={45}
outerRadius={70}
paddingAngle={4}
dataKey="value"
stroke="none"
>
{onlineRatio.map((entry, i) => (
<Cell key={i} fill={entry.color} />
))}
</Pie>
<RechartsTooltip />
</PieChart>
</ResponsiveContainer>
</Box>
<VStack align="stretch" gap={4} flex={1}>
<Box>
<Flex justify="space-between" mb={1}>
<Text fontSize="sm" color="fg">Online</Text>
<Text fontSize="sm" fontWeight="semibold" color="success.DEFAULT">
{Math.round((metrics.online_players / Math.max(1, metrics.total_players)) * 100)}%
</Text>
</Flex>
<Progress.Root value={Math.round((metrics.online_players / Math.max(1, metrics.total_players)) * 100)} size="sm" borderRadius="full">
<Progress.Track bg="border">
<Progress.Range bg="success.DEFAULT" />
</Progress.Track>
</Progress.Root>
</Box>
<Box>
<Text fontSize="2xs" color="fg.muted" textTransform="uppercase" letterSpacing="wider">
{metrics.online_players.toLocaleString()} of {metrics.total_players.toLocaleString()} players online
</Text>
</Box>
</VStack>
</Flex>
) : (
<Text color="fg.muted" fontSize="sm" textAlign="center">No player data</Text>
)}
</Card.Body>
</Card.Root>
<Card.Root bg="card.bg" borderWidth="1px" borderColor="border" borderRadius="xl" boxShadow="card">
<Card.Header borderBottomWidth="1px" borderColor="border" px={5} py={4}>
<Text fontFamily="Playfair Display, serif" fontSize="lg" color="primary.DEFAULT" fontWeight="semibold">
System Health
</Text>
</Card.Header>
<Card.Body p={5}>
<VStack align="stretch" gap={4}>
{healthItems.map(({ label, icon: Icon }) => (
<Flex key={label} align="center" justify="space-between">
<Flex align="center" gap={3}>
<Box
w={8}
h={8}
borderRadius="md"
bg={`${state.connectionStatus[label.toLowerCase().replace(' ', '_') as keyof typeof state.connectionStatus] || state.connectionStatus.database ? 'success' : 'danger'}.subtle`}
display="flex"
alignItems="center"
justifyContent="center"
>
<Icon size={14} />
</Box>
<Text fontSize="sm" color="fg">{label}</Text>
</Flex>
<Flex align="center" gap={2}>
<Circle
size="8px"
bg={state.connectionStatus[label.toLowerCase().includes('database') ? 'database' : label.toLowerCase().includes('ssh') ? 'ssh' : label.toLowerCase().includes('bg') ? 'bgd' : 'rmq' as keyof typeof state.connectionStatus] ? 'success.DEFAULT' : 'danger.DEFAULT'}
/>
<Text fontSize="xs" color="fg.muted">
{state.connectionStatus[label.toLowerCase().includes('database') ? 'database' : label.toLowerCase().includes('ssh') ? 'ssh' : label.toLowerCase().includes('bg') ? 'bgd' : 'rmq' as keyof typeof state.connectionStatus] ? 'Connected' : 'Disconnected'}
</Text>
</Flex>
</Flex>
))}
</VStack>
</Card.Body>
</Card.Root>
</SimpleGrid>
<Card.Root bg="card.bg" borderWidth="1px" borderColor="border" borderRadius="xl" boxShadow="card" mt={6}>
<Card.Header borderBottomWidth="1px" borderColor="border" px={5} py={4}>
<Text fontFamily="Playfair Display, serif" fontSize="lg" color="primary.DEFAULT" fontWeight="semibold">
Quick Actions
</Text>
</Card.Header>
<Card.Body p={5}>
<SimpleGrid columns={{ base: 2, md: 4 }} gap={3}>
{['Broadcast Message', 'Player Search', 'Guild Lookup', 'Server Status'].map((label) => (
<Box
key={label}
as="button"
px={4}
py={3}
bg="primary.subtle"
borderWidth="1px"
borderColor="primary.subtle"
borderRadius="lg"
color="primary.DEFAULT"
fontSize="sm"
fontWeight="medium"
_hover={{ bg: 'primary.DEFAULT', color: 'white', borderColor: 'primary.DEFAULT' }}
transition="all 0.15s"
textAlign="left"
cursor="pointer"
>
{label}
</Box>
))}
</SimpleGrid>
</Card.Body>
</Card.Root>
</>
)}
<div className="mt-8 grid grid-cols-1 lg:grid-cols-2 gap-6">
<div className="bg-card-bg border border-border rounded-lg p-5 shadow-card">
<h2 className="font-serif text-xl text-primary mb-4">Quick Actions</h2>
<div className="grid grid-cols-2 gap-3">
<QuickAction label="Broadcast Message" onClick={() => {}} />
<QuickAction label="Player Search" onClick={() => {}} />
<QuickAction label="Guild Lookup" onClick={() => {}} />
<QuickAction label="Server Restart" onClick={() => {}} />
</div>
</div>
<div className="bg-card-bg border border-border rounded-lg p-5 shadow-card">
<h2 className="font-serif text-xl text-primary mb-4">System Health</h2>
<div className="space-y-3">
<HealthRow label="Database" status="ok" detail="Connected" />
<HealthRow label="SSH Tunnel" status="ok" detail="Connected" />
<HealthRow label="BG Director" status="ok" detail="Connected" />
<HealthRow label="RMQ Game" status="ok" detail="Connected" />
</div>
</div>
</div>
</div>
)
}
function QuickAction({ label, onClick }: { label: string; onClick: () => void }) {
return (
<button
onClick={onClick}
className="px-4 py-3 bg-primary/10 border border-primary/20 rounded-lg text-primary text-sm font-medium hover:bg-primary/20 transition-colors text-left"
>
{label}
</button>
)
}
function HealthRow({ label, status, detail }: { label: string; status: 'ok' | 'warn' | 'error'; detail: string }) {
const dotColor = status === 'ok' ? '#27ae60' : status === 'warn' ? '#f39c12' : '#c0392b'
return (
<div className="flex items-center justify-between text-sm">
<div className="flex items-center gap-2">
<div className="w-2 h-2 rounded-full" style={{ backgroundColor: dotColor }} />
<span className="text-text-secondary">{label}</span>
</div>
<span className="text-text-muted">{detail}</span>
</div>
</Box>
)
}
File diff suppressed because it is too large. Load diff
@@ -1,6 +1,8 @@
import { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import useSWR from 'swr'
import { Box, Heading, Input, Button, HStack } from '@chakra-ui/react'
import { FiSearch } from 'react-icons/fi'
import client from '../../api/client'
import { useApp } from '../../stores/AppContext'
import { useDebounce } from '../../hooks/useDebounce'
@@ -60,23 +62,35 @@ export default function PlayerExplorer() {
const playerList: Player[] = players?.success ? players.data : []
return (
<div>
<h1 className="font-serif text-3xl text-primary mb-6">Player Explorer</h1>
<Box>
<Heading as="h1" fontFamily="Playfair Display, serif" fontSize="3xl" color="primary.DEFAULT" mb={6}>
Player Explorer
</Heading>
<div className="mb-6">
<div className="relative max-w-md">
<input
type="text"
value={search}
onChange={(e) => setSearch(e.target.value)}
placeholder="Search by name, email, or Funcom ID..."
className="w-full bg-card-bg border border-border rounded-lg px-4 py-2.5 pl-10 text-sm text-text-primary placeholder-text-muted focus:outline-none focus:border-primary focus:ring-1 focus:ring-primary"
/>
<svg className="absolute left-3 top-3 w-4 h-4 text-text-muted" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0" />
</svg>
</div>
</div>
<Box mb={6} maxW="md" position="relative">
<Box
position="absolute"
left={3}
top="50%"
transform="translateY(-50%)"
zIndex={1}
color="fg.muted"
>
<FiSearch size={16} />
</Box>
<Input
type="text"
value={search}
onChange={(e) => setSearch(e.target.value)}
placeholder="Search by name, email, or Funcom ID..."
pl={10}
bg="card.bg"
borderColor="border"
borderRadius="lg"
fontSize="sm"
_placeholder={{ color: 'fg.muted' }}
/>
</Box>
<DataTable
columns={[
@@ -84,9 +98,9 @@ export default function PlayerExplorer() {
{
header: 'Status',
accessor: (row) => (
<Badge
label={row.online_status}
variant={row.online_status === 'Online' ? 'success' : 'default'}
<Badge
label={(row as any).online_status}
variant={(row as any).online_status === 'Online' ? 'success' : 'default'}
/>
),
},
@@ -96,20 +110,34 @@ export default function PlayerExplorer() {
{
header: 'Quick Actions',
accessor: (row) => (
<div className="flex gap-2">
<button
onClick={(e) => { e.stopPropagation(); handleAction(row.account_id || row.player_controller_id || 0, 'cheater', { cheat_type: 'exploit' }) }}
className="text-[10px] text-primary hover:underline"
<HStack gap={2}>
<Button
onClick={(e) => { e.stopPropagation(); handleAction((row as any).account_id || (row as any).player_controller_id || 0, 'cheater', { cheat_type: 'exploit' }) }}
variant="ghost"
size="xs"
color="primary.DEFAULT"
fontSize="10px"
p={0}
h="auto"
minW="auto"
_hover={{ textDecoration: 'underline' }}
>
Cheater
</button>
<button
onClick={(e) => { e.stopPropagation(); handleAction(row.account_id || row.player_controller_id || 0, 'tags', { add: ['reviewed'] }) }}
className="text-[10px] text-primary hover:underline"
</Button>
<Button
onClick={(e) => { e.stopPropagation(); handleAction((row as any).account_id || (row as any).player_controller_id || 0, 'tags', { add: ['reviewed'] }) }}
variant="ghost"
size="xs"
color="primary.DEFAULT"
fontSize="10px"
p={0}
h="auto"
minW="auto"
_hover={{ textDecoration: 'underline' }}
>
Tag
</button>
</div>
</Button>
</HStack>
),
},
]}
@@ -117,6 +145,6 @@ export default function PlayerExplorer() {
onRowClick={(row) => navigate(`/players/${row.account_id || row.player_controller_id || 0}`)}
loading={isLoading}
/>
</div>
</Box>
)
}
+257 -165
View File
@@ -1,5 +1,14 @@
import { useState, useEffect } from 'react'
import { useState } from 'react'
import useSWR from 'swr'
import {
Box, Flex, Text, Heading, Tabs, Card, Button,
Table, Spinner, Badge as ChakraBadge, Separator, SimpleGrid
} from '@chakra-ui/react'
import {
AreaChart, Area, XAxis, YAxis, CartesianGrid, Tooltip,
ResponsiveContainer, BarChart, Bar, Cell
} from 'recharts'
import { FiRefreshCw, FiPlus, FiMinus, FiServer, FiCpu, FiHardDrive, FiShield, FiRadio } from 'react-icons/fi'
import client from '../../api/client'
import { useApp } from '../../stores/AppContext'
import Badge from '../common/Badge'
@@ -27,6 +36,14 @@ interface MetricPoint {
memory_percent: number
}
const TAB_ICONS: Record<string, React.ElementType> = {
pods: FiServer,
deployments: FiRefreshCw,
metrics: FiCpu,
firewall: FiShield,
rmq: FiRadio,
}
export default function ServerControl() {
const [tab, setTab] = useState<'pods' | 'deployments' | 'metrics' | 'firewall' | 'rmq'>('pods')
const { dispatch } = useApp()
@@ -49,8 +66,9 @@ export default function ServerControl() {
} else {
dispatch({ type: 'ADD_TOAST', payload: { message: res.data.error || 'Failed', type: 'error' } })
}
} catch (e: any) {
dispatch({ type: 'ADD_TOAST', payload: { message: e.response?.data?.error || 'Failed', type: 'error' } })
} catch (e: unknown) {
const err = e as { response?: { data?: { error?: string } } }
dispatch({ type: 'ADD_TOAST', payload: { message: err.response?.data?.error || 'Failed', type: 'error' } })
}
}
@@ -62,180 +80,254 @@ export default function ServerControl() {
} else {
dispatch({ type: 'ADD_TOAST', payload: { message: res.data.error || 'Failed', type: 'error' } })
}
} catch (e: any) {
dispatch({ type: 'ADD_TOAST', payload: { message: e.response?.data?.error || 'Failed', type: 'error' } })
} catch (e: unknown) {
const err = e as { response?: { data?: { error?: string } } }
dispatch({ type: 'ADD_TOAST', payload: { message: err.response?.data?.error || 'Failed', type: 'error' } })
}
}
const chartData = metricList.map((m) => ({
time: new Date(m.timestamp).toLocaleTimeString(),
cpu: m.cpu_percent,
memory: m.memory_percent,
}))
return (
<div>
<h1 className="font-serif text-3xl text-primary mb-6">Server Control</h1>
<Box>
<Heading as="h1" fontSize="3xl" fontFamily="Playfair Display, serif" color="primary.DEFAULT" mb={6}>
Server Control
</Heading>
<div className="flex gap-1 mb-6 border-b border-border">
{(['pods', 'deployments', 'metrics', 'firewall', 'rmq'] as const).map((t) => (
<button
key={t}
onClick={() => setTab(t)}
className={`px-4 py-2.5 text-sm font-medium border-b-2 transition-colors capitalize ${
tab === t
? 'text-primary border-primary'
: 'text-text-muted border-transparent hover:text-text-primary'
}`}
>
{t}
</button>
))}
</div>
<Tabs.Root
value={tab}
onValueChange={(e) => setTab(e.value as typeof tab)}
variant="line"
mb={6}
>
<Tabs.List borderBottomWidth="1px" borderColor="border" gap={0}>
{(['pods', 'deployments', 'metrics', 'firewall', 'rmq'] as const).map((t) => {
const Icon = TAB_ICONS[t]
return (
<Tabs.Trigger
key={t}
value={t}
px={4}
py={2.5}
fontSize="sm"
fontWeight="medium"
textTransform="capitalize"
color="fg.muted"
borderBottom="2px solid transparent"
_selected={{
color: 'primary.DEFAULT',
borderColor: 'primary.DEFAULT',
}}
transition="all 0.15s"
gap={2}
>
<Icon size={14} />
{t}
</Tabs.Trigger>
)
})}
</Tabs.List>
{tab === 'pods' && (
<div className="overflow-x-auto rounded-lg border border-border">
<table className="w-full text-sm">
<thead>
<tr className="border-b border-border">
<th className="text-left px-4 py-3 text-text-muted font-semibold text-[11px] uppercase">Name</th>
<th className="text-left px-4 py-3 text-text-muted font-semibold text-[11px] uppercase">Namespace</th>
<th className="text-left px-4 py-3 text-text-muted font-semibold text-[11px] uppercase">Status</th>
<th className="text-left px-4 py-3 text-text-muted font-semibold text-[11px] uppercase">Restarts</th>
<th className="text-left px-4 py-3 text-text-muted font-semibold text-[11px] uppercase">Age</th>
<th className="text-left px-4 py-3 text-text-muted font-semibold text-[11px] uppercase">Actions</th>
</tr>
</thead>
<tbody>
{podList.map((pod) => (
<tr key={pod.name} className="border-b border-border last:border-0 hover:bg-hover/50">
<td className="px-4 py-3 font-mono text-xs">{pod.name}</td>
<td className="px-4 py-3">{pod.namespace}</td>
<td className="px-4 py-3">
<Badge
label={pod.status}
variant={pod.status === 'Running' ? 'success' : pod.status === 'Pending' ? 'warning' : 'danger'}
/>
</td>
<td className="px-4 py-3">{pod.restarts}</td>
<td className="px-4 py-3">{pod.age}</td>
<td className="px-4 py-3">
<button
onClick={() => handleRestart(pod.name)}
className="text-xs text-primary hover:underline"
>
Restart
</button>
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
<Tabs.Content value="pods" pt={4}>
<Table.ScrollArea borderWidth="1px" borderColor="border" borderRadius="lg">
<Table.Root variant="line" size="sm" stickyHeader>
<Table.Header>
<Table.Row bg="bg.subtle">
<Table.ColumnHeader fontSize="2xs" textTransform="uppercase" letterSpacing="wider" color="fg.muted">Name</Table.ColumnHeader>
<Table.ColumnHeader fontSize="2xs" textTransform="uppercase" letterSpacing="wider" color="fg.muted">Namespace</Table.ColumnHeader>
<Table.ColumnHeader fontSize="2xs" textTransform="uppercase" letterSpacing="wider" color="fg.muted">Status</Table.ColumnHeader>
<Table.ColumnHeader fontSize="2xs" textTransform="uppercase" letterSpacing="wider" color="fg.muted">Restarts</Table.ColumnHeader>
<Table.ColumnHeader fontSize="2xs" textTransform="uppercase" letterSpacing="wider" color="fg.muted">Age</Table.ColumnHeader>
<Table.ColumnHeader fontSize="2xs" textTransform="uppercase" letterSpacing="wider" color="fg.muted">Actions</Table.ColumnHeader>
</Table.Row>
</Table.Header>
<Table.Body>
{podList.map((pod) => (
<Table.Row key={pod.name} _hover={{ bg: 'bg.subtle' }}>
<Table.Cell fontFamily="Roboto Mono, monospace" fontSize="xs">{pod.name}</Table.Cell>
<Table.Cell fontSize="sm">{pod.namespace}</Table.Cell>
<Table.Cell>
<Badge
label={pod.status}
variant={pod.status === 'Running' ? 'success' : pod.status === 'Pending' ? 'warning' : 'danger'}
/>
</Table.Cell>
<Table.Cell fontSize="sm">{pod.restarts}</Table.Cell>
<Table.Cell fontSize="sm">{pod.age}</Table.Cell>
<Table.Cell>
<Button variant="ghost" size="xs" color="primary.DEFAULT" onClick={() => handleRestart(pod.name)}>
Restart
</Button>
</Table.Cell>
</Table.Row>
))}
</Table.Body>
</Table.Root>
</Table.ScrollArea>
</Tabs.Content>
{tab === 'deployments' && (
<div className="overflow-x-auto rounded-lg border border-border">
<table className="w-full text-sm">
<thead>
<tr className="border-b border-border">
<th className="text-left px-4 py-3 text-text-muted font-semibold text-[11px] uppercase">Name</th>
<th className="text-left px-4 py-3 text-text-muted font-semibold text-[11px] uppercase">Namespace</th>
<th className="text-left px-4 py-3 text-text-muted font-semibold text-[11px] uppercase">Replicas</th>
<th className="text-left px-4 py-3 text-text-muted font-semibold text-[11px] uppercase">Available</th>
<th className="text-left px-4 py-3 text-text-muted font-semibold text-[11px] uppercase">Actions</th>
</tr>
</thead>
<tbody>
{deploymentList.map((dep) => (
<tr key={dep.name} className="border-b border-border last:border-0 hover:bg-hover/50">
<td className="px-4 py-3 font-mono text-xs">{dep.name}</td>
<td className="px-4 py-3">{dep.namespace}</td>
<td className="px-4 py-3">{dep.replicas}</td>
<td className="px-4 py-3">{dep.available}</td>
<td className="px-4 py-3 flex gap-2">
<button
onClick={() => handleScale(dep.name, dep.replicas + 1)}
className="text-xs px-2 py-1 bg-primary/10 border border-primary/20 rounded text-primary"
>
+1
</button>
<button
onClick={() => handleScale(dep.name, Math.max(0, dep.replicas - 1))}
className="text-xs px-2 py-1 bg-primary/10 border border-primary/20 rounded text-primary"
>
-1
</button>
<button
onClick={() => handleRestart(dep.name)}
className="text-xs px-2 py-1 bg-danger/10 border border-danger/20 rounded text-danger"
>
Restart
</button>
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
<Tabs.Content value="deployments" pt={4}>
<Table.ScrollArea borderWidth="1px" borderColor="border" borderRadius="lg">
<Table.Root variant="line" size="sm" stickyHeader>
<Table.Header>
<Table.Row bg="bg.subtle">
<Table.ColumnHeader fontSize="2xs" textTransform="uppercase" letterSpacing="wider" color="fg.muted">Name</Table.ColumnHeader>
<Table.ColumnHeader fontSize="2xs" textTransform="uppercase" letterSpacing="wider" color="fg.muted">Namespace</Table.ColumnHeader>
<Table.ColumnHeader fontSize="2xs" textTransform="uppercase" letterSpacing="wider" color="fg.muted">Replicas</Table.ColumnHeader>
<Table.ColumnHeader fontSize="2xs" textTransform="uppercase" letterSpacing="wider" color="fg.muted">Available</Table.ColumnHeader>
<Table.ColumnHeader fontSize="2xs" textTransform="uppercase" letterSpacing="wider" color="fg.muted">Actions</Table.ColumnHeader>
</Table.Row>
</Table.Header>
<Table.Body>
{deploymentList.map((dep) => (
<Table.Row key={dep.name} _hover={{ bg: 'bg.subtle' }}>
<Table.Cell fontFamily="Roboto Mono, monospace" fontSize="xs">{dep.name}</Table.Cell>
<Table.Cell fontSize="sm">{dep.namespace}</Table.Cell>
<Table.Cell fontSize="sm">{dep.replicas}</Table.Cell>
<Table.Cell fontSize="sm">{dep.available}</Table.Cell>
<Table.Cell>
<Flex gap={1}>
<Button variant="outline" size="xs" borderColor="primary.DEFAULT" color="primary.DEFAULT" onClick={() => handleScale(dep.name, dep.replicas + 1)}>
<FiPlus size={12} />
</Button>
<Button variant="outline" size="xs" borderColor="border" color="fg.muted" onClick={() => handleScale(dep.name, Math.max(0, dep.replicas - 1))}>
<FiMinus size={12} />
</Button>
<Button variant="outline" size="xs" borderColor="danger.DEFAULT" color="danger.DEFAULT" onClick={() => handleRestart(dep.name)}>
Restart
</Button>
</Flex>
</Table.Cell>
</Table.Row>
))}
</Table.Body>
</Table.Root>
</Table.ScrollArea>
</Tabs.Content>
{tab === 'metrics' && (
<div className="bg-card-bg border border-border rounded-lg p-5">
<h3 className="text-text-muted text-xs uppercase tracking-wider mb-4">Server Metrics (24h)</h3>
<Tabs.Content value="metrics" pt={4}>
{metricList.length === 0 ? (
<div className="text-text-muted text-sm">No metrics available</div>
<Card.Root bg="card.bg" borderWidth="1px" borderColor="border" borderRadius="xl">
<Card.Body p={8} textAlign="center">
<Flex direction="column" align="center" gap={3}>
<FiCpu size={40} style={{ opacity: 0.3 }} />
<Text color="fg.muted">No metrics available</Text>
</Flex>
</Card.Body>
</Card.Root>
) : (
<div className="space-y-2">
{metricList.slice(-20).map((m, i) => (
<div key={i} className="flex items-center gap-4 text-sm">
<span className="text-text-muted w-32">{new Date(m.timestamp).toLocaleTimeString()}</span>
<div className="flex-1 flex items-center gap-2">
<span className="text-text-muted w-8">CPU</span>
<div className="flex-1 h-2 bg-border rounded overflow-hidden">
<div
className="h-full bg-primary"
style={{ width: `${Math.min(100, m.cpu_percent)}%` }}
/>
</div>
<span className="text-text-secondary w-10 text-right">{m.cpu_percent}%</span>
</div>
<div className="flex-1 flex items-center gap-2">
<span className="text-text-muted w-12">Mem</span>
<div className="flex-1 h-2 bg-border rounded overflow-hidden">
<div
className="h-full bg-success"
style={{ width: `${Math.min(100, m.memory_percent)}%` }}
/>
</div>
<span className="text-text-secondary w-10 text-right">{m.memory_percent}%</span>
</div>
</div>
))}
</div>
)}
</div>
)}
<SimpleGrid columns={{ base: 1, lg: 2 }} gap={6}>
<Card.Root bg="card.bg" borderWidth="1px" borderColor="border" borderRadius="xl" boxShadow="card">
<Card.Header borderBottomWidth="1px" borderColor="border" px={5} py={4}>
<Flex align="center" gap={2}>
<Box w={3} h={3} borderRadius="full" bg="primary.DEFAULT" />
<Text fontFamily="Playfair Display, serif" fontSize="md" color="primary.DEFAULT" fontWeight="semibold">
CPU Usage (24h)
</Text>
</Flex>
</Card.Header>
<Card.Body p={4}>
<Box w="full" h="280px">
<ResponsiveContainer width="100%" height="100%">
<AreaChart data={chartData}>
<defs>
<linearGradient id="cpuGrad" x1="0" y1="0" x2="0" y2="1">
<stop offset="5%" stopColor="var(--chakra-colors-primary-DEFAULT)" stopOpacity={0.3} />
<stop offset="95%" stopColor="var(--chakra-colors-primary-DEFAULT)" stopOpacity={0} />
</linearGradient>
</defs>
<CartesianGrid strokeDasharray="3 3" stroke="var(--chakra-colors-border-DEFAULT)" />
<XAxis dataKey="time" tick={{ fontSize: 10, fill: 'var(--chakra-colors-fg-muted)' }} interval="preserveStartEnd" />
<YAxis tick={{ fontSize: 10, fill: 'var(--chakra-colors-fg-muted)' }} unit="%" />
<Tooltip contentStyle={{ background: 'var(--chakra-colors-card-bg)', border: '1px solid var(--chakra-colors-border-DEFAULT)', borderRadius: '8px', fontSize: '12px' }} />
<Area type="monotone" dataKey="cpu" stroke="var(--chakra-colors-primary-DEFAULT)" fill="url(#cpuGrad)" strokeWidth={2} />
</AreaChart>
</ResponsiveContainer>
</Box>
</Card.Body>
</Card.Root>
{tab === 'firewall' && (
<div className="bg-card-bg border border-border rounded-lg p-5">
<h3 className="text-text-muted text-xs uppercase tracking-wider mb-4">Firewall Status</h3>
{firewall?.success ? (
<pre className="text-xs text-text-secondary font-mono bg-code-bg p-4 rounded overflow-auto">
{JSON.stringify(firewall.data, null, 2)}
</pre>
) : (
<div className="text-text-muted text-sm">No firewall data available</div>
<Card.Root bg="card.bg" borderWidth="1px" borderColor="border" borderRadius="xl" boxShadow="card">
<Card.Header borderBottomWidth="1px" borderColor="border" px={5} py={4}>
<Flex align="center" gap={2}>
<Box w={3} h={3} borderRadius="full" bg="success.DEFAULT" />
<Text fontFamily="Playfair Display, serif" fontSize="md" color="primary.DEFAULT" fontWeight="semibold">
Memory Usage (24h)
</Text>
</Flex>
</Card.Header>
<Card.Body p={4}>
<Box w="full" h="280px">
<ResponsiveContainer width="100%" height="100%">
<AreaChart data={chartData}>
<defs>
<linearGradient id="memGrad" x1="0" y1="0" x2="0" y2="1">
<stop offset="5%" stopColor="var(--chakra-colors-success-DEFAULT)" stopOpacity={0.3} />
<stop offset="95%" stopColor="var(--chakra-colors-success-DEFAULT)" stopOpacity={0} />
</linearGradient>
</defs>
<CartesianGrid strokeDasharray="3 3" stroke="var(--chakra-colors-border-DEFAULT)" />
<XAxis dataKey="time" tick={{ fontSize: 10, fill: 'var(--chakra-colors-fg-muted)' }} interval="preserveStartEnd" />
<YAxis tick={{ fontSize: 10, fill: 'var(--chakra-colors-fg-muted)' }} unit="%" />
<Tooltip contentStyle={{ background: 'var(--chakra-colors-card-bg)', border: '1px solid var(--chakra-colors-border-DEFAULT)', borderRadius: '8px', fontSize: '12px' }} />
<Area type="monotone" dataKey="memory" stroke="var(--chakra-colors-success-DEFAULT)" fill="url(#memGrad)" strokeWidth={2} />
</AreaChart>
</ResponsiveContainer>
</Box>
</Card.Body>
</Card.Root>
</SimpleGrid>
)}
</div>
)}
</Tabs.Content>
{tab === 'rmq' && (
<div className="bg-card-bg border border-border rounded-lg p-5">
<h3 className="text-text-muted text-xs uppercase tracking-wider mb-4">RMQ Overview</h3>
{rmq?.success ? (
<pre className="text-xs text-text-secondary font-mono bg-code-bg p-4 rounded overflow-auto">
{JSON.stringify(rmq.data, null, 2)}
</pre>
) : (
<div className="text-text-muted text-sm">No RMQ data available</div>
)}
</div>
)}
</div>
<Tabs.Content value="firewall" pt={4}>
<Card.Root bg="card.bg" borderWidth="1px" borderColor="border" borderRadius="xl" boxShadow="card">
<Card.Header borderBottomWidth="1px" borderColor="border" px={5} py={4}>
<Flex align="center" gap={2}>
<FiShield size={16} color="currentColor" />
<Text fontFamily="Playfair Display, serif" fontSize="md" color="primary.DEFAULT" fontWeight="semibold">
Firewall Status
</Text>
</Flex>
</Card.Header>
<Card.Body p={5}>
{firewall?.success ? (
<Box as="pre" fontSize="xs" color="fg" fontFamily="Roboto Mono, monospace" bg="code.bg" p={4} borderRadius="lg" overflow="auto">
{JSON.stringify(firewall.data, null, 2)}
</Box>
) : (
<Text color="fg.muted" fontSize="sm">No firewall data available</Text>
)}
</Card.Body>
</Card.Root>
</Tabs.Content>
<Tabs.Content value="rmq" pt={4}>
<Card.Root bg="card.bg" borderWidth="1px" borderColor="border" borderRadius="xl" boxShadow="card">
<Card.Header borderBottomWidth="1px" borderColor="border" px={5} py={4}>
<Flex align="center" gap={2}>
<FiRadio size={16} color="currentColor" />
<Text fontFamily="Playfair Display, serif" fontSize="md" color="primary.DEFAULT" fontWeight="semibold">
RMQ Overview
</Text>
</Flex>
</Card.Header>
<Card.Body p={5}>
{rmq?.success ? (
<Box as="pre" fontSize="xs" color="fg" fontFamily="Roboto Mono, monospace" bg="code.bg" p={4} borderRadius="lg" overflow="auto">
{JSON.stringify(rmq.data, null, 2)}
</Box>
) : (
<Text color="fg.muted" fontSize="sm">No RMQ data available</Text>
)}
</Card.Body>
</Card.Root>
</Tabs.Content>
</Tabs.Root>
</Box>
)
}
+88 -29
View File
@@ -1,4 +1,17 @@
import { useState, useEffect } from 'react'
import {
Box,
Heading,
Button,
Input,
Flex,
VStack,
Card,
Grid,
Text,
Spinner,
} from '@chakra-ui/react'
import { FiRefreshCw, FiSave, FiPlus } from 'react-icons/fi'
import client from '../../api/client'
import { useApp } from '../../stores/AppContext'
@@ -52,47 +65,93 @@ export default function Settings() {
}
return (
<div>
<h1 className="font-serif text-3xl text-primary mb-6">Settings</h1>
<Box>
<Heading as="h1" fontFamily="Playfair Display, serif" color="primary.DEFAULT" fontSize="2xl" mb={6}>
Settings
</Heading>
<div className="flex items-center gap-4 mb-6">
<button
<Flex gap={4} mb={6} wrap="wrap">
<Button
variant="solid"
bg="primary.DEFAULT"
color="white"
size="sm"
borderRadius="lg"
onClick={load}
disabled={loading}
className="px-4 py-2 bg-primary text-white rounded-lg text-sm font-medium hover:bg-primary-dark disabled:opacity-50"
_hover={{ bg: 'primary.hover', transform: 'scale(1.02)' }}
transition="all 0.15s"
>
<FiRefreshCw style={{ marginRight: 6 }} />
{loading ? 'Loading...' : 'Reload'}
</button>
<button
</Button>
<Button
variant="solid"
bg="success.DEFAULT"
color="white"
size="sm"
borderRadius="lg"
onClick={handleSave}
disabled={saving}
className="px-4 py-2 bg-success text-white rounded-lg text-sm font-medium hover:bg-success/80 disabled:opacity-50"
_hover={{ transform: 'scale(1.02)' }}
transition="all 0.15s"
>
<FiSave style={{ marginRight: 6 }} />
{saving ? 'Saving...' : 'Save Settings'}
</button>
<button
</Button>
<Button
variant="solid"
bg="card.bg"
color="fg"
borderWidth="1px"
borderColor="border"
size="sm"
borderRadius="lg"
onClick={addKey}
className="px-4 py-2 bg-card-bg border border-border text-text-primary rounded-lg text-sm font-medium hover:bg-hover"
_hover={{ bg: 'bg.subtle', transform: 'scale(1.02)' }}
transition="all 0.15s"
>
<FiPlus style={{ marginRight: 6 }} />
Add Key
</button>
</div>
</Button>
</Flex>
<div className="bg-card-bg border border-border rounded-lg p-5 space-y-4 max-w-2xl">
{Object.entries(settings).length === 0 && !loading && (
<div className="text-text-muted">No settings found.</div>
)}
{Object.entries(settings).map(([key, value]) => (
<div key={key} className="grid grid-cols-[200px_1fr] gap-4 items-center">
<label className="text-sm text-text-secondary truncate" title={key}>{key}</label>
<input
value={value}
onChange={(e) => handleChange(key, e.target.value)}
className="bg-card-bg border border-border rounded px-3 py-2 text-sm text-text-primary"
/>
</div>
))}
</div>
</div>
<Card.Root bg="card.bg" borderWidth="1px" borderColor="border" borderRadius="xl" boxShadow="card" maxW="3xl">
<Card.Body p={5}>
{loading ? (
<Flex align="center" justify="center" py={8} gap={2} color="fg.muted">
<Spinner size="sm" />
<Text fontSize="sm">Loading settings...</Text>
</Flex>
) : Object.entries(settings).length === 0 ? (
<Flex direction="column" align="center" justify="center" py={8} color="fg.muted">
<Text fontSize="sm">No settings found.</Text>
<Text fontSize="xs" mt={1}>Click "Add Key" to create one.</Text>
</Flex>
) : (
<VStack gap={3} align="stretch">
{Object.entries(settings).map(([key, value]) => (
<Grid key={key} templateColumns="200px 1fr" gap={4} alignItems="center">
<Text as="label" fontSize="sm" color="fg.muted" truncate title={key}>
{key}
</Text>
<Input
value={value}
onChange={(e) => handleChange(key, e.target.value)}
bg="bg"
borderColor="border"
borderRadius="md"
px={3}
py={2}
fontSize="sm"
color="fg"
/>
</Grid>
))}
</VStack>
)}
</Card.Body>
</Card.Root>
</Box>
)
}
+19 -5
View File
@@ -1,4 +1,5 @@
import { useEffect, useRef } from 'react'
import { Box, Heading } from '@chakra-ui/react'
import { Terminal as XTerm } from 'xterm'
import { FitAddon } from 'xterm-addon-fit'
import { io, Socket } from 'socket.io-client'
@@ -95,12 +96,25 @@ export default function Terminal() {
}, [])
return (
<div className="h-[calc(100vh-140px)] flex flex-col">
<h1 className="font-serif text-3xl text-primary mb-4">Remote Shell</h1>
<div
<Box h="calc(100vh - 140px)" display="flex" flexDirection="column">
<Heading
as="h1"
fontSize="3xl"
fontFamily="Playfair Display, serif"
color="primary.DEFAULT"
mb={4}
>
Remote Shell
</Heading>
<Box
ref={containerRef}
className="flex-1 bg-[#1a1a1a] rounded-lg border border-border overflow-hidden"
flex={1}
bg="#1a1a1a"
borderRadius="lg"
borderWidth="1px"
borderColor="border"
overflow="hidden"
/>
</div>
</Box>
)
}
+45 -27
View File
@@ -1,5 +1,7 @@
import { useState } from 'react'
import useSWR from 'swr'
import { Box, Heading, Input, Button } from '@chakra-ui/react'
import { FiSearch } from 'react-icons/fi'
import client from '../../api/client'
import { useApp } from '../../stores/AppContext'
import DataTable from '../common/DataTable'
@@ -41,23 +43,33 @@ export default function Vehicles() {
}
return (
<div>
<h1 className="font-serif text-3xl text-primary mb-6">Vehicles</h1>
<Box>
<Heading as="h1" fontFamily="Playfair Display, serif" color="primary.DEFAULT" fontSize="2xl" mb={6}>
Vehicles
</Heading>
<div className="mb-6">
<div className="relative max-w-md">
<input
type="text"
value={search}
onChange={(e) => setSearch(e.target.value)}
placeholder="Search vehicles..."
className="w-full bg-card-bg border border-border rounded-lg px-4 py-2.5 pl-10 text-sm text-text-primary placeholder-text-muted focus:outline-none focus:border-primary focus:ring-1 focus:ring-primary"
/>
<svg className="absolute left-3 top-3 w-4 h-4 text-text-muted" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0" />
</svg>
</div>
</div>
<Box position="relative" maxW="md" mb={6}>
<Input
type="text"
value={search}
onChange={(e) => setSearch(e.target.value)}
placeholder="Search vehicles..."
bg="card.bg"
borderColor="border"
borderRadius="lg"
px={4}
py={2.5}
pl={10}
fontSize="sm"
color="fg"
_placeholder={{ color: 'fg.muted' }}
_focus={{ borderColor: 'primary.DEFAULT', boxShadow: '0 0 0 1px var(--chakra-colors-primary-DEFAULT)' }}
_focusVisible={{ outline: 'none' }}
/>
<Box position="absolute" left={3} top="50%" transform="translateY(-50%)" color="fg.muted">
<FiSearch size={16} />
</Box>
</Box>
<DataTable
columns={[
@@ -68,26 +80,32 @@ export default function Vehicles() {
{
header: 'Actions',
accessor: (row) => (
<div className="flex gap-2">
<button
onClick={(e) => { e.stopPropagation(); handleAction(row.id, 'repair') }}
className="text-xs text-primary hover:underline"
<Box display="flex" gap={2}>
<Button
variant="ghost"
size="xs"
color="primary.DEFAULT"
_hover={{ textDecoration: 'underline' }}
onClick={(e) => { e.stopPropagation(); handleAction((row as any).id, 'repair') }}
>
Repair
</button>
<button
onClick={(e) => { e.stopPropagation(); handleAction(row.id, 'destroy') }}
className="text-xs text-danger hover:underline"
</Button>
<Button
variant="ghost"
size="xs"
color="danger.DEFAULT"
_hover={{ textDecoration: 'underline' }}
onClick={(e) => { e.stopPropagation(); handleAction((row as any).id, 'destroy') }}
>
Destroy
</button>
</div>
</Button>
</Box>
),
},
]}
data={vehicleList}
loading={isLoading}
/>
</div>
</Box>
)
}
+7 -1
View File
@@ -1,7 +1,13 @@
import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App'
import './styles/index.css'
import '@fontsource/playfair-display/400.css'
import '@fontsource/playfair-display/700.css'
import '@fontsource/inter/400.css'
import '@fontsource/inter/500.css'
import '@fontsource/inter/600.css'
import '@fontsource/roboto-mono/400.css'
import '@fontsource/roboto-mono/500.css'
ReactDOM.createRoot(document.getElementById('root')!).render(
<React.StrictMode>
+41 -24
View File
@@ -1,56 +1,70 @@
import React, { createContext, useContext, useReducer, useEffect } from 'react'
import { createContext, useContext, useReducer, useEffect } from 'react'
import type { FactionKey } from '../themes/palettes'
import { toaster } from '../toaster'
interface AppState {
user: string | null
theme: string
faction: FactionKey
colorMode: 'day' | 'night'
connectionStatus: {
database: boolean
ssh: boolean
bgd: boolean
rmq: boolean
}
toasts: Toast[]
}
interface Toast {
id: number
message: string
type: 'success' | 'error' | 'warning' | 'info'
}
type Action =
| { type: 'SET_USER'; payload: string | null }
| { type: 'SET_THEME'; payload: string }
| { type: 'SET_FACTION'; payload: FactionKey }
| { type: 'SET_COLOR_MODE'; payload: 'day' | 'night' }
| { type: 'SET_CONNECTION'; payload: Partial<AppState['connectionStatus']> }
| { type: 'ADD_TOAST'; payload: Omit<Toast, 'id'> }
| { type: 'REMOVE_TOAST'; payload: number }
| { type: 'ADD_TOAST'; payload: { message: string; type: 'success' | 'error' | 'warning' | 'info' } }
function loadStoredFaction(): FactionKey {
try {
const stored = localStorage.getItem('dune-faction')
if (stored) return stored as FactionKey
} catch {}
return 'fremen'
}
function loadStoredColorMode(): 'day' | 'night' {
try {
const stored = localStorage.getItem('dune-color-mode')
if (stored === 'day' || stored === 'night') return stored
} catch {}
return 'night'
}
const initialState: AppState = {
user: null,
theme: localStorage.getItem('dune-theme') || 'emperor',
faction: loadStoredFaction(),
colorMode: loadStoredColorMode(),
connectionStatus: {
database: true,
ssh: true,
bgd: true,
rmq: true,
},
toasts: [],
}
let toastId = 0
function reducer(state: AppState, action: Action): AppState {
switch (action.type) {
case 'SET_USER':
return { ...state, user: action.payload }
case 'SET_THEME':
return { ...state, theme: action.payload }
case 'SET_FACTION':
return { ...state, faction: action.payload }
case 'SET_COLOR_MODE':
return { ...state, colorMode: action.payload }
case 'SET_CONNECTION':
return { ...state, connectionStatus: { ...state.connectionStatus, ...action.payload } }
case 'ADD_TOAST':
return { ...state, toasts: [...state.toasts.slice(-2), { ...action.payload, id: ++toastId }] }
case 'REMOVE_TOAST':
return { ...state, toasts: state.toasts.filter((t) => t.id !== action.payload) }
toaster[action.payload.type]({
title: action.payload.message,
duration: 4000,
})
return state
default:
return state
}
@@ -65,9 +79,12 @@ export function AppProvider({ children }: { children: React.ReactNode }) {
const [state, dispatch] = useReducer(reducer, initialState)
useEffect(() => {
document.documentElement.dataset.theme = state.theme
localStorage.setItem('dune-theme', state.theme)
}, [state.theme])
localStorage.setItem('dune-faction', state.faction)
}, [state.faction])
useEffect(() => {
localStorage.setItem('dune-color-mode', state.colorMode)
}, [state.colorMode])
return (
<AppContext.Provider value={{ state, dispatch }}>
-39
View File
@@ -1,39 +0,0 @@
@import './themes.css';
@tailwind base;
@tailwind components;
@tailwind utilities;
@layer base {
:root {
--primary: #d4af37;
--primary-dark: #b8962f;
--primary-light: #e8c962;
--bg: #1a1a1a;
--card-bg: #2a2a2a;
--text: #f0f0f0;
--text-light: #c0c0c0;
--text-muted: #808080;
--border: #404040;
--accent: #d4af37;
--danger: #c0392b;
--success: #27ae60;
--nav-bg: #0d0d0d;
--nav-text: #d4d4d4;
--nav-active: #d4af37;
--hover: #333333;
--shadow: 0 2px 8px rgba(0,0,0,0.4);
--table-header: #333333;
--code-bg: #222222;
}
body {
font-family: 'Inter', sans-serif;
background-color: var(--bg);
color: var(--text);
}
h1, h2, h3 {
font-family: 'Playfair Display', serif;
}
}
-281
View File
@@ -1,281 +0,0 @@
/* Dune Theme System — 14 themes */
[data-theme="default"] {
--primary: #c9a24e;
--primary-dark: #a8862e;
--primary-light: #e0c97a;
--bg: #f4f1ea;
--card-bg: #ffffff;
--text: #2c1810;
--text-light: #6b5a4a;
--text-muted: #9a8a7a;
--border: #e0d5c7;
--accent: #8b4513;
--danger: #c0392b;
--success: #27ae60;
--nav-bg: #1a1a2e;
--nav-text: #c9c4d0;
--nav-active: #c9a24e;
--hover: #f0ebe0;
--shadow: 0 2px 8px rgba(44,24,16,0.08);
}
[data-theme="atreides"] {
--primary: #2d5a27;
--primary-dark: #1e3d19;
--primary-light: #4a8c42;
--bg: #f0f5ed;
--card-bg: #ffffff;
--text: #1a2e1a;
--text-light: #3d4d3d;
--text-muted: #6b7c6b;
--border: #d4ddd4;
--accent: #1e3d19;
--danger: #8b2500;
--success: #2d5a27;
--nav-bg: #1a2e1a;
--nav-text: #d4ddd4;
--nav-active: #6abf6a;
--hover: #e2ebe2;
--shadow: 0 2px 8px rgba(30,61,25,0.1);
}
[data-theme="harkonnen"] {
--primary: #ff6b00;
--primary-dark: #cc5500;
--primary-light: #ff8c33;
--bg: #1a1a1a;
--card-bg: #2d2d2d;
--text: #e8e8e8;
--text-light: #b0b0b0;
--text-muted: #808080;
--border: #404040;
--accent: #ff4500;
--danger: #ff0000;
--success: #00cc44;
--nav-bg: #000000;
--nav-text: #cccccc;
--nav-active: #ff6b00;
--hover: #333333;
--shadow: 0 2px 8px rgba(0,0,0,0.4);
}
[data-theme="fremen"] {
--primary: #d4a853;
--primary-dark: #b8913f;
--primary-light: #e8c87a;
--bg: #e8dcc8;
--card-bg: #f5efe3;
--text: #3d3428;
--text-light: #5c4f3d;
--text-muted: #8a7d66;
--border: #d4cbb8;
--accent: #8b6914;
--danger: #a04000;
--success: #6b8e23;
--nav-bg: #2c2418;
--nav-text: #d4cbb8;
--nav-active: #d4a853;
--hover: #e8dcc8;
--shadow: 0 2px 8px rgba(44,36,24,0.1);
}
[data-theme="bene-gesserit"] {
--primary: #a8a8a8;
--primary-dark: #888888;
--primary-light: #c8c8c8;
--bg: #f8f8f8;
--card-bg: #ffffff;
--text: #2a2a2a;
--text-light: #505050;
--text-muted: #787878;
--border: #e0e0e0;
--accent: #606060;
--danger: #c41e3a;
--success: #2e8b57;
--nav-bg: #1a1a1a;
--nav-text: #d0d0d0;
--nav-active: #ffffff;
--hover: #f0f0f0;
--shadow: 0 2px 8px rgba(0,0,0,0.08);
}
[data-theme="spacing-guild"] {
--primary: #4a90d9;
--primary-dark: #2e6ab3;
--primary-light: #6baee8;
--bg: #1a1a2e;
--card-bg: #252540;
--text: #e0e0f0;
--text-light: #a0a0c0;
--text-muted: #707090;
--border: #3a3a50;
--accent: #6b5b95;
--danger: #d94545;
--success: #45d985;
--nav-bg: #0f0f1a;
--nav-text: #b0b0d0;
--nav-active: #4a90d9;
--hover: #2a2a40;
--shadow: 0 2px 8px rgba(0,0,0,0.3);
}
[data-theme="emperor"] {
--primary: #d4af37;
--primary-dark: #b8962f;
--primary-light: #e8c962;
--bg: #1a1a1a;
--card-bg: #2a2a2a;
--text: #f0f0f0;
--text-light: #c0c0c0;
--text-muted: #808080;
--border: #404040;
--accent: #d4af37;
--danger: #c0392b;
--success: #27ae60;
--nav-bg: #0d0d0d;
--nav-text: #d4d4d4;
--nav-active: #d4af37;
--hover: #333333;
--shadow: 0 2px 8px rgba(0,0,0,0.4);
}
[data-theme="corrino"] {
--primary: #8b0000;
--primary-dark: #5c0000;
--primary-light: #c43030;
--bg: #f5f0f0;
--card-bg: #ffffff;
--text: #2a1515;
--text-light: #5a3535;
--text-muted: #8a5555;
--border: #e0d5d5;
--accent: #a01010;
--danger: #8b0000;
--success: #2d5a27;
--nav-bg: #1a0a0a;
--nav-text: #d4c4c4;
--nav-active: #ff6b6b;
--hover: #f0e8e8;
--shadow: 0 2px 8px rgba(90,0,0,0.1);
}
[data-theme="mentat"] {
--primary: #008b8b;
--primary-dark: #006666;
--primary-light: #20b2aa;
--bg: #e8f4f4;
--card-bg: #ffffff;
--text: #1a2a2a;
--text-light: #3d5050;
--text-muted: #6b8080;
--border: #d4e0e0;
--accent: #006666;
--danger: #c44569;
--success: #008b8b;
--nav-bg: #0a1a1a;
--nav-text: #c4d4d4;
--nav-active: #00ced1;
--hover: #e0f0f0;
--shadow: 0 2px 8px rgba(0,60,60,0.1);
}
[data-theme="sardaukar"] {
--primary: #cd853f;
--primary-dark: #a0522d;
--primary-light: #deb887;
--bg: #f5ebe0;
--card-bg: #ffffff;
--text: #2a2018;
--text-light: #5a4a38;
--text-muted: #8a7a68;
--border: #e0d5c8;
--accent: #8b4513;
--danger: #8b0000;
--success: #6b8e23;
--nav-bg: #1a140c;
--nav-text: #d4c8b8;
--nav-active: #cd853f;
--hover: #f0e8e0;
--shadow: 0 2px 8px rgba(60,40,20,0.1);
}
[data-theme="tleilax"] {
--primary: #4a0080;
--primary-dark: #2d0050;
--primary-light: #6b20b0;
--bg: #1a1a24;
--card-bg: #252530;
--text: #e0e0e8;
--text-light: #a0a0b0;
--text-muted: #707080;
--border: #404050;
--accent: #6b0099;
--danger: #c41e3a;
--success: #00c080;
--nav-bg: #0a0a10;
--nav-text: #b0b0c0;
--nav-active: #9966cc;
--hover: #2a2a38;
--shadow: 0 2px 8px rgba(0,0,0,0.4);
}
[data-theme="ordos"] {
--primary: #2e8b57;
--primary-dark: #1c5c3a;
--primary-light: #3cb371;
--bg: #e8f5f0;
--card-bg: #ffffff;
--text: #1a2e22;
--text-light: #3d5045;
--text-muted: #6b8075;
--border: #d4e0d8;
--accent: #1c5c3a;
--danger: #c45c3a;
--success: #2e8b57;
--nav-bg: #0a1a12;
--nav-text: #c4d8d0;
--nav-active: #3cb371;
--hover: #e0f0e8;
--shadow: 0 2px 8px rgba(20,60,40,0.1);
}
[data-theme="ix"] {
--primary: #4169e1;
--primary-dark: #2c4db8;
--primary-light: #6495ed;
--bg: #e8edf8;
--card-bg: #ffffff;
--text: #1a2248;
--text-light: #3d4470;
--text-muted: #6b7098;
--border: #d0d8e8;
--accent: #2c4db8;
--danger: #c44569;
--success: #32cd32;
--nav-bg: #0a1028;
--nav-text: #c0c8d8;
--nav-active: #6495ed;
--hover: #e0e8f0;
--shadow: 0 2px 8px rgba(30,50,100,0.15);
}
[data-theme="choam"] {
--primary: #b8860b;
--primary-dark: #8b6508;
--primary-light: #daa520;
--bg: #faf8f0;
--card-bg: #ffffff;
--text: #2a2820;
--text-light: #5a5848;
--text-muted: #8a8878;
--border: #e8e4d8;
--accent: #8b6508;
--danger: #b22222;
--success: #228b22;
--nav-bg: #1a180c;
--nav-text: #d4d0c0;
--nav-active: #daa520;
--hover: #f0ece0;
--shadow: 0 2px 8px rgba(60,50,20,0.1);
}
+100
View File
@@ -0,0 +1,100 @@
import { createSystem, defaultConfig } from '@chakra-ui/react'
import type { SystemConfig } from '@chakra-ui/react'
import { FACTION_PALETTES, type FactionKey, type FactionColors, FACTION_KEYS } from './palettes'
function semTokensFromPalette(c: FactionColors) {
return {
colors: {
bg: c.bg,
'bg.subtle': c.bgSubtle,
'fg': c.fg,
'fg.muted': c.fgMuted,
'border': c.border,
'border.subtle': c.borderSubtle,
'primary.DEFAULT': c.primary,
'primary.hover': c.primaryHover,
'primary.subtle': c.primarySubtle,
'accent': c.accent,
'danger.DEFAULT': c.danger,
'danger.subtle': c.dangerSubtle,
'success.DEFAULT': c.success,
'success.subtle': c.successSubtle,
'warning.DEFAULT': c.warning,
'warning.subtle': c.warningSubtle,
'info.DEFAULT': c.info,
'info.subtle': c.infoSubtle,
'nav.bg': c.navBg,
'card.bg': c.cardBg,
'code.bg': c.codeBg,
},
shadows: {
card: c.shadow,
},
}
}
type TokenRecord = Record<string, Record<string, { value: unknown }>>
function makeSemanticTokens(t: ReturnType<typeof semTokensFromPalette>): TokenRecord {
const result: TokenRecord = {}
for (const [category, entries] of Object.entries(t)) {
result[category] = {}
if (category === 'colors') {
for (const [key, val] of Object.entries(entries as Record<string, string>)) {
result.colors![key] = { value: val }
}
} else if (category === 'shadows') {
for (const [key, val] of Object.entries(entries as Record<string, string>)) {
result.shadows![key] = { value: val }
}
}
}
return result
}
function buildSystem(tokens: ReturnType<typeof semTokensFromPalette>) {
const systemConfig: SystemConfig = {
conditions: defaultConfig.conditions,
utilities: defaultConfig.utilities,
preflight: defaultConfig.preflight,
cssVarsPrefix: defaultConfig.cssVarsPrefix,
cssVarsRoot: defaultConfig.cssVarsRoot,
globalCss: defaultConfig.globalCss,
theme: {
breakpoints: defaultConfig.theme?.breakpoints,
keyframes: defaultConfig.theme?.keyframes,
tokens: defaultConfig.theme?.tokens,
semanticTokens: makeSemanticTokens(tokens) as any,
recipes: defaultConfig.theme?.recipes,
slotRecipes: defaultConfig.theme?.slotRecipes,
textStyles: defaultConfig.theme?.textStyles,
layerStyles: defaultConfig.theme?.layerStyles,
animationStyles: defaultConfig.theme?.animationStyles,
},
}
return createSystem(systemConfig, {})
}
type SystemCache = Record<string, Record<string, ReturnType<typeof createSystem>>>
const systemCache: SystemCache = {}
function getOrCreateSystem(faction: FactionKey, mode: 'day' | 'night') {
const key = `${faction}:${mode}`
if (!systemCache[faction]) systemCache[faction] = {}
if (!systemCache[faction][mode]) {
const palette = FACTION_PALETTES[faction][mode]
systemCache[faction][mode] = buildSystem(semTokensFromPalette(palette))
}
return systemCache[faction][mode]
}
export function createDuneSystem(faction: FactionKey, mode: 'day' | 'night') {
return getOrCreateSystem(faction, mode)
}
export function getFactionName(key: FactionKey): string {
return FACTION_PALETTES[key]?.name ?? key
}
export { FACTION_KEYS, FACTION_PALETTES }
export type { FactionKey }
+49
View File
@@ -0,0 +1,49 @@
import { FACTION_PALETTES, type FactionKey, type FactionColors } from './palettes'
const TOKEN_MAP: [string, keyof FactionColors][] = [
['--chakra-colors-bg', 'bg'],
['--chakra-colors-bg-subtle', 'bgSubtle'],
['--chakra-colors-card-bg', 'cardBg'],
['--chakra-colors-nav-bg', 'navBg'],
['--chakra-colors-fg', 'fg'],
['--chakra-colors-fg-muted', 'fgMuted'],
['--chakra-colors-border', 'border'],
['--chakra-colors-border-subtle', 'borderSubtle'],
['--chakra-colors-primary-DEFAULT', 'primary'],
['--chakra-colors-primary-hover', 'primaryHover'],
['--chakra-colors-primary-subtle', 'primarySubtle'],
['--chakra-colors-accent', 'accent'],
['--chakra-colors-danger-DEFAULT', 'danger'],
['--chakra-colors-danger-subtle', 'dangerSubtle'],
['--chakra-colors-success-DEFAULT', 'success'],
['--chakra-colors-success-subtle', 'successSubtle'],
['--chakra-colors-warning-DEFAULT', 'warning'],
['--chakra-colors-warning-subtle', 'warningSubtle'],
['--chakra-colors-info-DEFAULT', 'info'],
['--chakra-colors-info-subtle', 'infoSubtle'],
['--chakra-colors-code-bg', 'codeBg'],
['--chakra-shadows-card', 'shadow'],
]
let injectedStyle: HTMLStyleElement | null = null
export function injectThemeVars(faction: FactionKey, mode: 'day' | 'night') {
const palette = FACTION_PALETTES[faction]?.[mode]
if (!palette) return
const lines = TOKEN_MAP.map(([varName, key]) => {
const value = palette[key]
if (varName.startsWith('--chakra-shadows-')) {
return `${varName}:${value};`
}
return `${varName}:${value};`
})
if (!injectedStyle) {
injectedStyle = document.createElement('style')
injectedStyle.id = 'dune-theme-vars'
document.head.appendChild(injectedStyle)
}
injectedStyle.textContent = `:where(html, .chakra-theme) {\n ${lines.join('\n ')}\n}`
}
+661
View File
@@ -0,0 +1,661 @@
export interface FactionColors {
bg: string
bgSubtle: string
cardBg: string
navBg: string
fg: string
fgMuted: string
border: string
borderSubtle: string
primary: string
primaryHover: string
primarySubtle: string
accent: string
danger: string
dangerSubtle: string
success: string
successSubtle: string
warning: string
warningSubtle: string
info: string
infoSubtle: string
codeBg: string
shadow: string
}
export interface FactionPalette {
name: string
day: FactionColors
night: FactionColors
}
export const FACTION_PALETTES: Record<string, FactionPalette> = {
atreides: {
name: 'House Atreides',
day: {
bg: '#f4f7f2',
bgSubtle: '#edf1ea',
cardBg: '#ffffff',
navBg: '#1a2e1a',
fg: '#1a2e1a',
fgMuted: '#6b7c6b',
border: '#d4ddd4',
borderSubtle: '#e8efe8',
primary: '#2d5a27',
primaryHover: '#3d7a35',
primarySubtle: '#e8f5e8',
accent: '#1e3d19',
danger: '#8b2500',
dangerSubtle: '#fde8e8',
success: '#2d5a27',
successSubtle: '#e6f4e6',
warning: '#b8860b',
warningSubtle: '#fef3c7',
info: '#4a90d9',
infoSubtle: '#e8f0fb',
codeBg: '#1e2a1e',
shadow: '0 2px 12px rgba(30, 61, 25, 0.08)',
},
night: {
bg: '#0d1a0d',
bgSubtle: '#101e10',
cardBg: '#142214',
navBg: '#0a120a',
fg: '#d4ddd4',
fgMuted: '#6b8a6b',
border: '#1e3d1e',
borderSubtle: '#162d16',
primary: '#4aad4a',
primaryHover: '#5cc45c',
primarySubtle: '#0d2a0d',
accent: '#7acc7a',
danger: '#ff4444',
dangerSubtle: '#2a0d0d',
success: '#4aad4a',
successSubtle: '#0d2a0d',
warning: '#d4a853',
warningSubtle: '#2a200d',
info: '#6495ed',
infoSubtle: '#0d1a2a',
codeBg: '#0a100a',
shadow: '0 2px 12px rgba(0, 0, 0, 0.5)',
},
},
harkonnen: {
name: 'House Harkonnen',
day: {
bg: '#f5f0eb',
bgSubtle: '#f0e8e0',
cardBg: '#ffffff',
navBg: '#1a1208',
fg: '#2a1a0a',
fgMuted: '#8a6a4a',
border: '#e0d5c5',
borderSubtle: '#eee5d8',
primary: '#e05a00',
primaryHover: '#ff6c1a',
primarySubtle: '#fff0e6',
accent: '#8b4500',
danger: '#c0392b',
dangerSubtle: '#fde8e8',
success: '#27ae60',
successSubtle: '#e6f4e6',
warning: '#d4a017',
warningSubtle: '#fef3c7',
info: '#607d8b',
infoSubtle: '#e8f0f4',
codeBg: '#1e1810',
shadow: '0 2px 12px rgba(80, 30, 0, 0.1)',
},
night: {
bg: '#0d0804',
bgSubtle: '#100c06',
cardBg: '#14100a',
navBg: '#080400',
fg: '#d4c8b8',
fgMuted: '#8a7a60',
border: '#2a1a0a',
borderSubtle: '#1e1408',
primary: '#ff6b00',
primaryHover: '#ff8533',
primarySubtle: '#2a1000',
accent: '#ff8c44',
danger: '#ff4444',
dangerSubtle: '#2a0d0d',
success: '#44cc44',
successSubtle: '#0d2a0d',
warning: '#e8a830',
warningSubtle: '#2a1a0d',
info: '#78909c',
infoSubtle: '#0d1a20',
codeBg: '#0a0602',
shadow: '0 2px 12px rgba(0, 0, 0, 0.6)',
},
},
fremen: {
name: 'Fremen',
day: {
bg: '#faf6ed',
bgSubtle: '#f5efe0',
cardBg: '#ffffff',
navBg: '#2c2418',
fg: '#3d3428',
fgMuted: '#8a7d66',
border: '#d4cbb8',
borderSubtle: '#e8e0d0',
primary: '#c49a3c',
primaryHover: '#d4a853',
primarySubtle: '#fdf5e6',
accent: '#8b6914',
danger: '#a04000',
dangerSubtle: '#fde8e0',
success: '#6b8e23',
successSubtle: '#e6f0d8',
warning: '#d4a017',
warningSubtle: '#fef3c7',
info: '#5b8fa8',
infoSubtle: '#e0eff5',
codeBg: '#2a2016',
shadow: '0 2px 12px rgba(60, 50, 30, 0.1)',
},
night: {
bg: '#141008',
bgSubtle: '#18140c',
cardBg: '#1c1810',
navBg: '#0c0804',
fg: '#d4cbb8',
fgMuted: '#8a7d66',
border: '#3a2e1a',
borderSubtle: '#2a2010',
primary: '#d4a853',
primaryHover: '#e0b964',
primarySubtle: '#2a1a08',
accent: '#e0c060',
danger: '#d44530',
dangerSubtle: '#2a0d08',
success: '#6b8e23',
successSubtle: '#0d2a08',
warning: '#c8a040',
warningSubtle: '#2a1a08',
info: '#5b8fa8',
infoSubtle: '#0d1a28',
codeBg: '#0a0602',
shadow: '0 2px 12px rgba(0, 0, 0, 0.5)',
},
},
'bene-gesserit': {
name: 'Bene Gesserit',
day: {
bg: '#f7f6f9',
bgSubtle: '#f0eff4',
cardBg: '#ffffff',
navBg: '#1a1a24',
fg: '#2a2a38',
fgMuted: '#7878a0',
border: '#e0dde8',
borderSubtle: '#eeebf4',
primary: '#7b6ba8',
primaryHover: '#9080c0',
primarySubtle: '#f0edf8',
accent: '#5a4a88',
danger: '#c41e3a',
dangerSubtle: '#fde8ec',
success: '#2e8b57',
successSubtle: '#e6f4ec',
warning: '#9b7c28',
warningSubtle: '#fef3d0',
info: '#6a8ba8',
infoSubtle: '#e8eff5',
codeBg: '#1e1e2a',
shadow: '0 2px 12px rgba(50, 40, 70, 0.08)',
},
night: {
bg: '#0e0e18',
bgSubtle: '#10101c',
cardBg: '#161622',
navBg: '#08080e',
fg: '#c8c8e0',
fgMuted: '#7878a0',
border: '#2a2a40',
borderSubtle: '#1e1e30',
primary: '#a090d0',
primaryHover: '#b8a8e0',
primarySubtle: '#1a1a30',
accent: '#c0b0e8',
danger: '#e84858',
dangerSubtle: '#2a0d14',
success: '#48b868',
successSubtle: '#0d2a18',
warning: '#c8a840',
warningSubtle: '#2a1a0d',
info: '#8098c0',
infoSubtle: '#0d1a2a',
codeBg: '#080810',
shadow: '0 2px 12px rgba(0, 0, 0, 0.5)',
},
},
'spacing-guild': {
name: 'Spacing Guild',
day: {
bg: '#f2f5fa',
bgSubtle: '#eaf0f8',
cardBg: '#ffffff',
navBg: '#0f1a30',
fg: '#1a2a50',
fgMuted: '#6a7a9a',
border: '#d0d8e8',
borderSubtle: '#e4eaf4',
primary: '#3a70c0',
primaryHover: '#4a80d0',
primarySubtle: '#e8f0fb',
accent: '#1a5098',
danger: '#c44545',
dangerSubtle: '#fde8e8',
success: '#38a870',
successSubtle: '#e6f4ec',
warning: '#c89828',
warningSubtle: '#fef3d0',
info: '#5a90d0',
infoSubtle: '#e0ecf8',
codeBg: '#101a28',
shadow: '0 2px 12px rgba(20, 40, 80, 0.1)',
},
night: {
bg: '#060d18',
bgSubtle: '#08101e',
cardBg: '#0c1424',
navBg: '#040810',
fg: '#b8c8e8',
fgMuted: '#6078a0',
border: '#1a3058',
borderSubtle: '#102040',
primary: '#5a90e0',
primaryHover: '#6aa0f0',
primarySubtle: '#0d1a38',
accent: '#7ab0f8',
danger: '#e85858',
dangerSubtle: '#2a0d0d',
success: '#48b878',
successSubtle: '#0d2a18',
warning: '#d8a840',
warningSubtle: '#2a1a0d',
info: '#6aa0e8',
infoSubtle: '#0d1a30',
codeBg: '#040a12',
shadow: '0 2px 12px rgba(0, 0, 0, 0.5)',
},
},
imperial: {
name: 'Imperial House',
day: {
bg: '#faf5f5',
bgSubtle: '#f5eded',
cardBg: '#ffffff',
navBg: '#1a0a0a',
fg: '#2a1515',
fgMuted: '#8a5555',
border: '#e0d0d0',
borderSubtle: '#ece0e0',
primary: '#9b1a1a',
primaryHover: '#b82020',
primarySubtle: '#fde8e8',
accent: '#c89828',
danger: '#8b0000',
dangerSubtle: '#fde0e0',
success: '#2d5a27',
successSubtle: '#e6f4e6',
warning: '#c89828',
warningSubtle: '#fef3d0',
info: '#6a7a8a',
infoSubtle: '#e8eef2',
codeBg: '#1e1010',
shadow: '0 2px 12px rgba(80, 0, 0, 0.08)',
},
night: {
bg: '#0d0505',
bgSubtle: '#100808',
cardBg: '#160c0c',
navBg: '#080202',
fg: '#d4c0c0',
fgMuted: '#8a6060',
border: '#2a1010',
borderSubtle: '#1e0a0a',
primary: '#d43030',
primaryHover: '#e04848',
primarySubtle: '#2a0808',
accent: '#e0b840',
danger: '#e84848',
dangerSubtle: '#2a0808',
success: '#48b848',
successSubtle: '#0d2a0d',
warning: '#d8a840',
warningSubtle: '#2a1a0d',
info: '#7a8a9a',
infoSubtle: '#0d1a28',
codeBg: '#080202',
shadow: '0 2px 12px rgba(0, 0, 0, 0.6)',
},
},
mentat: {
name: 'Mentat',
day: {
bg: '#f4f8f7',
bgSubtle: '#edf4f2',
cardBg: '#ffffff',
navBg: '#0a1a18',
fg: '#1a2a28',
fgMuted: '#6a7a78',
border: '#d0e0dc',
borderSubtle: '#e4eeea',
primary: '#0d7a6e',
primaryHover: '#109a8a',
primarySubtle: '#e6f5f3',
accent: '#086058',
danger: '#c44a3a',
dangerSubtle: '#fde8e4',
success: '#0d7a6e',
successSubtle: '#e6f5f3',
warning: '#c89828',
warningSubtle: '#fef3d0',
info: '#5a8aa0',
infoSubtle: '#e4f0f5',
codeBg: '#101e1c',
shadow: '0 2px 12px rgba(10, 60, 50, 0.08)',
},
night: {
bg: '#050d0c',
bgSubtle: '#081210',
cardBg: '#0c1816',
navBg: '#020808',
fg: '#b8d0cc',
fgMuted: '#608a84',
border: '#1a3832',
borderSubtle: '#102820',
primary: '#18c0a8',
primaryHover: '#20d8b8',
primarySubtle: '#0d2a24',
accent: '#28e0c0',
danger: '#e85040',
dangerSubtle: '#2a0d0a',
success: '#18c0a8',
successSubtle: '#0d2a24',
warning: '#d8a840',
warningSubtle: '#2a1a0d',
info: '#6a9ab0',
infoSubtle: '#0d1a28',
codeBg: '#040a08',
shadow: '0 2px 12px rgba(0, 0, 0, 0.5)',
},
},
sardaukar: {
name: 'Sardaukar',
day: {
bg: '#f5f2ef',
bgSubtle: '#f0ebe6',
cardBg: '#ffffff',
navBg: '#1a140c',
fg: '#2a2018',
fgMuted: '#8a7a68',
border: '#e0d8cc',
borderSubtle: '#ece4d8',
primary: '#8b5a30',
primaryHover: '#a06e3c',
primarySubtle: '#fdf0e6',
accent: '#6b4020',
danger: '#8b0000',
dangerSubtle: '#fde0e0',
success: '#5a7a30',
successSubtle: '#e8f0dc',
warning: '#c08028',
warningSubtle: '#fef0d4',
info: '#7a8a90',
infoSubtle: '#e8eef0',
codeBg: '#1e1810',
shadow: '0 2px 12px rgba(60, 40, 20, 0.1)',
},
night: {
bg: '#0c0804',
bgSubtle: '#100c06',
cardBg: '#16100a',
navBg: '#060400',
fg: '#d4c8b8',
fgMuted: '#8a7a60',
border: '#2a1e10',
borderSubtle: '#1e1408',
primary: '#c08040',
primaryHover: '#d09050',
primarySubtle: '#2a1408',
accent: '#d8a060',
danger: '#d84040',
dangerSubtle: '#2a0d0d',
success: '#7a9a40',
successSubtle: '#1a2a0d',
warning: '#d09038',
warningSubtle: '#2a180d',
info: '#8a9aa0',
infoSubtle: '#0d1a20',
codeBg: '#060400',
shadow: '0 2px 12px rgba(0, 0, 0, 0.5)',
},
},
tleilaxu: {
name: 'Tleilaxu',
day: {
bg: '#f6f4fa',
bgSubtle: '#f0edf6',
cardBg: '#ffffff',
navBg: '#1a1028',
fg: '#2a1a40',
fgMuted: '#7a68a0',
border: '#d8cce8',
borderSubtle: '#e8e0f4',
primary: '#6a30a0',
primaryHover: '#7a40b0',
primarySubtle: '#f2e8fc',
accent: '#4a2080',
danger: '#c43a3a',
dangerSubtle: '#fde8e8',
success: '#30a060',
successSubtle: '#e6f4ec',
warning: '#b09030',
warningSubtle: '#fef3d4',
info: '#7060a8',
infoSubtle: '#ece8f8',
codeBg: '#1e1828',
shadow: '0 2px 12px rgba(40, 20, 70, 0.08)',
},
night: {
bg: '#080410',
bgSubtle: '#0c0618',
cardBg: '#10081e',
navBg: '#040208',
fg: '#c8b8e0',
fgMuted: '#7868a0',
border: '#281840',
borderSubtle: '#1c1030',
primary: '#a060e0',
primaryHover: '#b070f0',
primarySubtle: '#18082a',
accent: '#c080f8',
danger: '#d84040',
dangerSubtle: '#2a0d0d',
success: '#40b068',
successSubtle: '#0d2a18',
warning: '#c0a040',
warningSubtle: '#2a1a0d',
info: '#8070b8',
infoSubtle: '#100d28',
codeBg: '#040208',
shadow: '0 2px 12px rgba(0, 0, 0, 0.5)',
},
},
ordos: {
name: 'House Ordos',
day: {
bg: '#f2f7f4',
bgSubtle: '#ebf2ed',
cardBg: '#ffffff',
navBg: '#0a1a12',
fg: '#1a2e22',
fgMuted: '#6a8072',
border: '#cce0d4',
borderSubtle: '#e0eee6',
primary: '#1e7a40',
primaryHover: '#289a50',
primarySubtle: '#e6f5ec',
accent: '#146030',
danger: '#c44a3a',
dangerSubtle: '#fde8e4',
success: '#1e7a40',
successSubtle: '#e6f5ec',
warning: '#b89828',
warningSubtle: '#fef3d0',
info: '#5a8a90',
infoSubtle: '#e4f0f2',
codeBg: '#101e16',
shadow: '0 2px 12px rgba(20, 60, 40, 0.08)',
},
night: {
bg: '#040d08',
bgSubtle: '#08120c',
cardBg: '#0c1810',
navBg: '#020804',
fg: '#b8d4c4',
fgMuted: '#608a72',
border: '#183828',
borderSubtle: '#10281c',
primary: '#30c060',
primaryHover: '#40d070',
primarySubtle: '#0d2a14',
accent: '#48d878',
danger: '#d84848',
dangerSubtle: '#2a0d0d',
success: '#30c060',
successSubtle: '#0d2a14',
warning: '#c8a838',
warningSubtle: '#2a1a0d',
info: '#6a9aa0',
infoSubtle: '#0d1a20',
codeBg: '#020804',
shadow: '0 2px 12px rgba(0, 0, 0, 0.5)',
},
},
ixian: {
name: 'Ixian',
day: {
bg: '#f4f6fa',
bgSubtle: '#edf0f6',
cardBg: '#ffffff',
navBg: '#0a102a',
fg: '#1a2248',
fgMuted: '#6a7298',
border: '#d0d8e8',
borderSubtle: '#e4eaf4',
primary: '#3058c8',
primaryHover: '#4068d8',
primarySubtle: '#e8effb',
accent: '#183898',
danger: '#c43a50',
dangerSubtle: '#fde8ec',
success: '#30a860',
successSubtle: '#e6f4ec',
warning: '#c09828',
warningSubtle: '#fef3d0',
info: '#4878c0',
infoSubtle: '#e0eaf6',
codeBg: '#101828',
shadow: '0 2px 12px rgba(20, 40, 90, 0.08)',
},
night: {
bg: '#040810',
bgSubtle: '#080c18',
cardBg: '#0c1020',
navBg: '#020408',
fg: '#b8c8e0',
fgMuted: '#6078a0',
border: '#1a2858',
borderSubtle: '#101c40',
primary: '#4878e8',
primaryHover: '#5888f8',
primarySubtle: '#0d1838',
accent: '#6098f8',
danger: '#d85060',
dangerSubtle: '#2a0d10',
success: '#40b870',
successSubtle: '#0d2a18',
warning: '#c8a840',
warningSubtle: '#2a1a0d',
info: '#5888d8',
infoSubtle: '#0d1830',
codeBg: '#020408',
shadow: '0 2px 12px rgba(0, 0, 0, 0.5)',
},
},
choam: {
name: 'CHOAM',
day: {
bg: '#faf9f3',
bgSubtle: '#f5f4eb',
cardBg: '#ffffff',
navBg: '#1a180c',
fg: '#2a2820',
fgMuted: '#8a8878',
border: '#e8e4d8',
borderSubtle: '#f0ece0',
primary: '#a8860b',
primaryHover: '#c09a10',
primarySubtle: '#fdf8e6',
accent: '#786008',
danger: '#b22222',
dangerSubtle: '#fde8e8',
success: '#228b22',
successSubtle: '#e6f4e6',
warning: '#c89828',
warningSubtle: '#fef3d0',
info: '#8a8870',
infoSubtle: '#f0efe8',
codeBg: '#1e1c14',
shadow: '0 2px 12px rgba(60, 50, 20, 0.1)',
},
night: {
bg: '#0c0a04',
bgSubtle: '#100e06',
cardBg: '#16140a',
navBg: '#060400',
fg: '#d4d0c0',
fgMuted: '#8a8870',
border: '#2a2614',
borderSubtle: '#1e1a0c',
primary: '#c8a018',
primaryHover: '#d8b028',
primarySubtle: '#2a1c08',
accent: '#e0c838',
danger: '#d44040',
dangerSubtle: '#2a0d0d',
success: '#38a838',
successSubtle: '#0d2a0d',
warning: '#d8a840',
warningSubtle: '#2a1a0d',
info: '#9a9880',
infoSubtle: '#1a180d',
codeBg: '#060400',
shadow: '0 2px 12px rgba(0, 0, 0, 0.5)',
},
},
}
export type FactionKey = keyof typeof FACTION_PALETTES
export type ColorMode = 'day' | 'night'
export const FACTION_KEYS = Object.keys(FACTION_PALETTES) as FactionKey[]
+8
View File
@@ -0,0 +1,8 @@
import { createToaster } from '@chakra-ui/react'
export const toaster = createToaster({
placement: 'bottom-end',
overlap: true,
})
export type ToasterRef = typeof toaster
-36
View File
@@ -1,36 +0,0 @@
/** @type {import('tailwindcss').Config} */
export default {
content: ["./index.html", "./src/**/*.{js,ts,jsx,tsx}"],
darkMode: ["class", '[data-theme="emperor"]'],
theme: {
extend: {
colors: {
primary: "var(--primary)",
"primary-dark": "var(--primary-dark)",
"primary-light": "var(--primary-light)",
background: "var(--bg)",
"card-bg": "var(--card-bg)",
"text-primary": "var(--text)",
"text-secondary": "var(--text-light)",
"text-muted": "var(--text-muted)",
border: "var(--border)",
accent: "var(--accent)",
danger: "var(--danger)",
success: "var(--success)",
"nav-bg": "var(--nav-bg)",
"nav-text": "var(--nav-text)",
"nav-active": "var(--nav-active)",
hover: "var(--hover)",
},
fontFamily: {
serif: ["Playfair Display", "serif"],
sans: ["Inter", "sans-serif"],
mono: ["Roboto Mono", "monospace"],
},
boxShadow: {
card: "var(--shadow)",
},
},
},
plugins: [],
}
+1
View File
@@ -9,6 +9,7 @@ export default defineConfig({
'/api': {
target: 'http://localhost:5050',
changeOrigin: true,
ws: false,
},
'/socket.io': {
target: 'http://localhost:5050',
+363 -1
View File
@@ -299,6 +299,10 @@ function Show-Menu {
Write-Host " Launch dashboard with full debug logging enabled." -ForegroundColor DarkGray
Write-Host " Logs written to logs/debug.log - includes SSH, API, DB, K8s details." -ForegroundColor DarkGray
Write-Host ""
Write-Host " [7] Start New Dashboard (React + ChakraUI)" -ForegroundColor Green
Write-Host " Launch the modern React dashboard with ChakraUI and Recharts." -ForegroundColor DarkGray
Write-Host " Auto-installs dependencies. Frontend: http://localhost:5173" -ForegroundColor DarkGray
Write-Host ""
Write-Host " [Q] Quit" -ForegroundColor White
Write-Host ""
}
@@ -2278,6 +2282,363 @@ print('ok')
Start-Dashboard -PreserveDebug
}
# ── New Dashboard (React + ChakraUI) ─────────────────────────────────────
function Start-NewDashboard {
param(
[switch]$PreserveDebug
)
Write-Host ""
Write-Host " Starting NEW dashboard (React + ChakraUI)..." -ForegroundColor Yellow
Write-Host ""
# Check Node.js
$nodeVersion = $null
try {
$nodeVersion = node --version 2>&1
Write-Host " Node.js: $nodeVersion" -ForegroundColor Green
} catch {
Write-Host " Node.js: NOT FOUND" -ForegroundColor Red
Write-Host ""
Write-Host " Node.js 18+ is required for the new frontend." -ForegroundColor Yellow
Write-Host " Download from https://nodejs.org/" -ForegroundColor Cyan
Write-Host ""
return
}
# ── Reuse tunnel/setup logic from Start-Dashboard ──────────────────────
# Check Python
if (-not (Test-Python)) {
return
}
# Check dependencies
Test-Dependencies | Out-Null
# Check settings
$settingsFile = Join-Path $ProjectRoot "settings.yaml"
if (-not (Test-Path $settingsFile)) {
Write-Host ""
Write-Host " [ERROR] settings.yaml not found. You need to run setup first." -ForegroundColor Red
Write-Host ""
return
}
# Read settings
$readSettingsScript = @"
import yaml, json, sys, os
path = sys.argv[1]
if not os.path.exists(path):
print(json.dumps({}))
sys.exit(0)
with open(path, 'r', encoding='utf-8-sig') as f:
s = yaml.safe_load(f) or {}
print(json.dumps(s))
"@
$readSettingsScript | Out-File -FilePath "$env:TEMP\read_settings_new.py" -Encoding utf8 -Force
$settingsJson = python "$env:TEMP\read_settings_new.py" $settingsFile 2>$null
if (-not $settingsJson) {
Write-Host " [ERROR] Failed to read settings.yaml" -ForegroundColor Red
return
}
$settings = $settingsJson | ConvertFrom-Json
$ServerHost = $settings.server.host
$SSHUser = $settings.server.user
$LocalPort = [int]$settings.database.port
$Namespace = $settings.kubernetes.namespace
$DashboardPort = [int]$settings.dashboard.port
$DirectorPort = [int]$settings.director.port
Register-SensitiveValue -Key "ServerIP" -Value $ServerHost
Register-SensitiveValue -Key "Namespace" -Value $Namespace
Register-SensitiveValue -Key "DBPassword" -Value $settings.database.password
Register-SensitiveValue -Key "DBUser" -Value $settings.database.user
Register-SensitiveValue -Key "DashboardSecret" -Value $settings.dashboard.secret_key
Register-SensitiveValue -Key "DirectorToken" -Value $settings.director.token
Register-SensitiveValue -Key "AuthSecret" -Value $settings.auth.secret_key
# Find SSH key (same logic as Start-Dashboard)
function Test-SshKeyForNew($keyPath, $targetServer) {
if (-not (Test-Path $keyPath)) { return $false }
try {
$out = ssh -i $keyPath -o StrictHostKeyChecking=accept-new -o ConnectTimeout=5 -o BatchMode=yes $targetServer "echo ok" 2>$null
return $out -eq "ok"
} catch { return $false }
}
$SSHKeySrc = $settings.server.ssh_key
$LocalKey = Join-Path $ProjectRoot "internal-scripts\ssh\sshKey"
if ($SSHKeySrc -and $SSHKeySrc -ne 'null' -and -not [string]::IsNullOrEmpty($SSHKeySrc)) {
if (Test-SshKeyForNew $SSHKeySrc ($SSHUser + '@' + $ServerHost)) {
Register-SensitiveValue -Key "SSHKeyPath" -Value $SSHKeySrc
Write-Host " SSH Key: Using key from settings.yaml" -ForegroundColor Green
} else {
$SSHKeySrc = $null
}
}
if (-not $SSHKeySrc -or -not (Test-Path $SSHKeySrc) -or -not (Test-SshKeyForNew $SSHKeySrc ($SSHUser + '@' + $ServerHost))) {
$keyPaths = @(
"$env:LOCALAPPDATA\DuneAwakeningServer\sshKey",
$LocalKey,
"$env:USERPROFILE\.ssh\id_ed25519",
"$env:USERPROFILE\.ssh\id_rsa"
)
foreach ($kp in $keyPaths) {
if ($kp -ne $SSHKeySrc -and (Test-Path $kp)) {
if (Test-SshKeyForNew $kp ($SSHUser + '@' + $ServerHost)) {
$SSHKeySrc = $kp
Register-SensitiveValue -Key "SSHKeyPath" -Value $kp
Write-Host " SSH Key: Found working key at $kp" -ForegroundColor Green
break
}
}
}
}
if (-not $SSHKeySrc -or -not (Test-Path $SSHKeySrc)) {
Write-Host " [ERROR] No working SSH key found." -ForegroundColor Red
return
}
# Copy key to temp
$SSHKey = "$env:TEMP\dune-tunnel-key"
$ResolvedSrc = [System.IO.Path]::GetFullPath($SSHKeySrc)
$ResolvedDest = [System.IO.Path]::GetFullPath($SSHKey)
if ($ResolvedSrc -ne $ResolvedDest) {
Copy-Item $SSHKeySrc $SSHKey -Force
}
try {
$acl = Get-Acl $SSHKey -ErrorAction SilentlyContinue
if ($acl) {
$acl.SetAccessRuleProtection($true, $false)
$rule = New-Object System.Security.AccessControl.FileSystemAccessRule("$env:USERNAME", "FullControl", "Allow")
$acl.SetAccessRule($rule)
Set-Acl -Path $SSHKey -AclObject $acl -ErrorAction SilentlyContinue
}
} catch {}
Write-Host ""
Write-Host "============================================================" -ForegroundColor Cyan
Write-Host " Dune Awakening Dashboard (React Edition)" -ForegroundColor Cyan
Write-Host "============================================================" -ForegroundColor Cyan
Write-Host ""
# ── SSH Tunnel ────────────────────────────────────────────────────────
Write-Host "[1/5] Starting SSH tunnel (localhost:$LocalPort -> VM)..." -ForegroundColor Yellow
Get-NetTCPConnection -LocalPort $LocalPort -ErrorAction SilentlyContinue | ForEach-Object {
Get-Process -Id $_.OwningProcess -ErrorAction SilentlyContinue | Where-Object { $_.ProcessName -eq 'ssh' } | Stop-Process -Force -ErrorAction SilentlyContinue
}
Get-NetTCPConnection -LocalPort $DirectorPort -ErrorAction SilentlyContinue | ForEach-Object {
Get-Process -Id $_.OwningProcess -ErrorAction SilentlyContinue | Where-Object { $_.ProcessName -eq 'ssh' } | Stop-Process -Force -ErrorAction SilentlyContinue
}
Start-Sleep 1
$sshArgs = @(
"-i", $SSHKey,
"-o", "StrictHostKeyChecking=accept-new",
"-o", "ServerAliveInterval=30",
"-o", "ServerAliveCountMax=3",
"-L", "${LocalPort}:localhost:${LocalPort}",
"-L", "${DirectorPort}:localhost:${DirectorPort}",
"-N", "${SSHUser}@${ServerHost}"
)
$sshTunnel = Start-Process ssh -ArgumentList $sshArgs -PassThru -WindowStyle Hidden
$connected = $false
for ($i = 0; $i -lt 30; $i++) {
Start-Sleep -Seconds 1
if ($sshTunnel.HasExited) {
Write-Host "[ERROR] SSH tunnel exited (code: $($sshTunnel.ExitCode))" -ForegroundColor Red
Write-Host " Check server IP and SSH key configuration." -ForegroundColor Yellow
return
}
try {
$tcp = New-Object System.Net.Sockets.TcpClient
$tcp.Connect("127.0.0.1", $LocalPort)
$tcp.Close()
$connected = $true
break
} catch {}
}
if (-not $connected) {
Write-Host "[ERROR] SSH tunnel did not connect within 30 seconds" -ForegroundColor Red
Stop-Process -Id $sshTunnel.Id -Force -ErrorAction SilentlyContinue
return
}
Write-Host "[OK] SSH tunnel up on localhost:$LocalPort" -ForegroundColor Green
# ── DB Port-Forward ───────────────────────────────────────────────────
Write-Host "[2/5] Starting DB port-forward on VM..." -ForegroundColor Yellow
if (-not $Namespace -or $Namespace -eq '') {
Write-Host "[ERROR] Kubernetes namespace is empty." -ForegroundColor Red
Stop-Process -Id $sshTunnel.Id -Force -ErrorAction SilentlyContinue
return
}
$DBService = "${Namespace}-db-dbdepl-svc"
$pfCheck = ssh -i $SSHKey -o StrictHostKeyChecking=accept-new -o ConnectTimeout=10 ${SSHUser}@${ServerHost} "sudo kubectl get svc -n ${Namespace} -o name" 2>$null
if ($pfCheck) {
$dbSvc = ($pfCheck -split "`n") | Where-Object { $_ -match 'db.*svc' -or $_ -match 'postgres' -or $_ -match 'pg' } | Select-Object -First 1
if ($dbSvc) { $DBService = $dbSvc -replace 'service/', '' }
}
$RemotePort = 15432
ssh -i $SSHKey -o StrictHostKeyChecking=accept-new -o ConnectTimeout=10 ${SSHUser}@${ServerHost} "sudo fuser -k ${LocalPort}/tcp ${DirectorPort}/tcp 2>/dev/null; sleep 1" 2>$null
$pfCmd = "nohup sudo kubectl port-forward -n $Namespace svc/$DBService $LocalPort`:$RemotePort > /tmp/pf.log 2>`&1 `"&`""
ssh -i $SSHKey -o StrictHostKeyChecking=accept-new -o ServerAliveInterval=30 "${SSHUser}@${ServerHost}" $pfCmd 2>$null
Start-Sleep -Seconds 2
# BGD Director port-forward
$bgdSvc = "${Namespace}-bgd-svc"
$pfCheckBgd = ssh -i $SSHKey -o StrictHostKeyChecking=accept-new -o ConnectTimeout=10 ${SSHUser}@${ServerHost} "sudo kubectl get svc -n ${Namespace} -o name" 2>$null
if ($pfCheckBgd) {
$bgdMatch = ($pfCheckBgd -split "`n") | Where-Object { $_ -match 'bgd.*svc' } | Select-Object -First 1
if ($bgdMatch) { $bgdSvc = $bgdMatch -replace 'service/', '' }
}
# Check BGD deployment
$bgdDeploy = "${Namespace}-bgd-deploy"
$bgdReady = ssh -i $SSHKey -o StrictHostKeyChecking=accept-new -o ConnectTimeout=10 ${SSHUser}@${ServerHost} "sudo kubectl get deployment $bgdDeploy -n $Namespace -o jsonpath='{.status.readyReplicas}'" 2>$null
if (-not $bgdReady -or $bgdReady -eq '0' -or $bgdReady -eq '') {
Write-Host " BGD deployment is scaled down, starting..." -ForegroundColor Yellow
ssh -i $SSHKey -o StrictHostKeyChecking=accept-new -o ConnectTimeout=30 ${SSHUser}@${ServerHost} "sudo kubectl scale deployment $bgdDeploy -n $Namespace --replicas=1" 2>$null
Start-Sleep -Seconds 15
}
$directorRemotePort = 11717
$directorCmd = "nohup sudo kubectl port-forward -n $Namespace svc/$bgdSvc $DirectorPort`:$directorRemotePort > /tmp/director_pf.log 2>`&1 `"&`""
ssh -i $SSHKey -o StrictHostKeyChecking=accept-new -o ServerAliveInterval=30 "${SSHUser}@${ServerHost}" $directorCmd 2>$null
Start-Sleep -Seconds 3
# ── DB Check ──────────────────────────────────────────────────────────
Write-Host "[3/5] Checking database..." -ForegroundColor Yellow
$dbTest = $false
$dbScript = Join-Path $ProjectRoot "scripts\db_check.py"
for ($i = 0; $i -lt 15; $i++) {
try {
$result = python $dbScript $LocalPort 2>$null
if ($result -match 'ok') { $dbTest = $true; break }
} catch {}
Start-Sleep -Seconds 1
}
if (-not $dbTest) {
Write-Host "[ERROR] Database connection failed." -ForegroundColor Red
Stop-Process -Id $sshTunnel.Id -Force -ErrorAction SilentlyContinue
return
}
Write-Host "[OK] Database connected" -ForegroundColor Green
# ── Install Dependencies ──────────────────────────────────────────────
Write-Host "[4/5] Installing dependencies..." -ForegroundColor Yellow
# Backend Python deps (project root requirements.txt)
if (Test-Path (Join-Path $ProjectRoot "requirements.txt")) {
Write-Host " Checking backend Python dependencies..." -ForegroundColor DarkGray
$pipArgs = @("pip", "install", "-r", (Join-Path $ProjectRoot "requirements.txt"), "--quiet")
& python @pipArgs 2>$null
$pipArgs2 = @("pip", "install", "psycopg[binary]", "--quiet")
& python @pipArgs2 2>$null
Write-Host " Backend dependencies OK" -ForegroundColor Green
}
# Frontend npm deps
$frontendDir = Join-Path $ProjectRoot "frontend"
if (Test-Path (Join-Path $frontendDir "package.json")) {
$nodeModulesDir = Join-Path $frontendDir "node_modules"
if (-not (Test-Path $nodeModulesDir)) {
Write-Host " Installing frontend npm dependencies..." -ForegroundColor DarkGray
$prevLoc = Get-Location
Set-Location -LiteralPath $frontendDir
npm install 2>&1 | Out-Null
Set-Location -LiteralPath $prevLoc
Write-Host " Frontend dependencies installed" -ForegroundColor Green
} else {
Write-Host " Frontend dependencies OK" -ForegroundColor Green
}
}
# ── Start Backend + Frontend ──────────────────────────────────────────
Write-Host "[5/5] Starting dashboard..." -ForegroundColor Yellow
Write-Host ""
# Start the new Flask API backend
Write-Host " Starting backend API (port $DashboardPort)..." -ForegroundColor Cyan
$backendDir = Join-Path $ProjectRoot "backend"
$backendProcess = Start-Process cmd.exe -ArgumentList "/k", "cd /d `"$backendDir`" && python run.py" -PassThru
# Wait for backend to be ready
Write-Host " Waiting for backend to start..." -ForegroundColor DarkGray
$backendAlive = $false
for ($i = 0; $i -lt 30; $i++) {
Start-Sleep -Seconds 1
try {
$wc = New-Object System.Net.WebClient
$result = $wc.DownloadString("http://127.0.0.1:${DashboardPort}/api/stats")
if ($result) { $backendAlive = $true; break }
} catch {}
}
if (-not $backendAlive) {
Write-Host "[ERROR] Backend failed to start within 30 seconds." -ForegroundColor Red
Write-Host " Check the backend window for errors." -ForegroundColor Yellow
Stop-Process -Id $sshTunnel.Id -Force -ErrorAction SilentlyContinue
return
}
Write-Host " [OK] Backend API running on port $DashboardPort" -ForegroundColor Green
# Start frontend in a visible window
Write-Host " Starting frontend dev server (port 5173)..." -ForegroundColor Cyan
$viteDir = Join-Path $ProjectRoot "frontend"
$frontendProcess = Start-Process cmd.exe -ArgumentList "/k", "cd /d `"$viteDir`" && npm run dev -- --host 0.0.0.0" -PassThru
Start-Sleep -Seconds 6
# Check if frontend is running by probing the port
$frontendAlive = $false
try {
$wc = New-Object System.Net.WebClient
$wc.DownloadString("http://127.0.0.1:5173/") | Out-Null
$frontendAlive = $true
} catch {}
if (-not $frontendAlive) {
Write-Host "[WARN] Frontend may not have started yet. Check the frontend window." -ForegroundColor Yellow
} else {
Write-Host " [OK] Frontend running on port 5173" -ForegroundColor Green
}
Write-Host ""
Write-Host "============================================================" -ForegroundColor Cyan
Write-Host " New Dashboard Started!" -ForegroundColor Green
Write-Host "============================================================" -ForegroundColor Cyan
Write-Host ""
Write-Host " Frontend: http://localhost:5173" -ForegroundColor Cyan
Write-Host " Backend: http://localhost:${DashboardPort}" -ForegroundColor DarkGray
Write-Host ""
Write-Host " Open http://localhost:5173 in your browser" -ForegroundColor Yellow
Write-Host ""
Write-Host " Close the backend and frontend windows to stop, or" -ForegroundColor DarkGray
Write-Host " press Enter here to kill the SSH tunnel and all processes." -ForegroundColor DarkGray
Write-Host ""
Read-Host " Press Enter to stop"
Write-Host ""
Write-Host " Stopping services..." -ForegroundColor Cyan
Stop-Process -Id $frontendProcess.Id -Force -ErrorAction SilentlyContinue
Stop-Process -Id $backendProcess.Id -Force -ErrorAction SilentlyContinue
Stop-Process -Id $sshTunnel.Id -Force -ErrorAction SilentlyContinue
$pkillCmd = 'ssh -i "' + $SSHKey + '" -o StrictHostKeyChecking=accept-new ' + $SSHUser + '@' + $ServerHost + ' "sudo fuser -k ' + $LocalPort + '/tcp ' + $DirectorPort + '/tcp 2>/dev/null"'
cmd /c $pkillCmd 2>$null
Write-Host " All services stopped." -ForegroundColor Green
Write-Host ""
}
# ── Main Loop ───────────────────────────────────────────────────────────
Show-Banner
@@ -2293,9 +2654,10 @@ while ($true) {
"4" { Install-CaCert; break }
"5" { Clean-CaCerts; break }
"6" { Start-DashboardDebug; break }
"7" { Start-NewDashboard; break }
"Q" { Write-Host ""; Write-Host " Goodbye!"; Write-Host ""; exit 0 }
"q" { Write-Host ""; Write-Host " Goodbye!"; Write-Host ""; exit 0 }
default { Write-Host ""; Write-Host " Invalid choice. Please enter 1, 2, 3, 4, 5, 6, or Q." -ForegroundColor Yellow; Write-Host "" }
default { Write-Host ""; Write-Host " Invalid choice. Please enter 1, 2, 3, 4, 5, 6, 7, or Q." -ForegroundColor Yellow; Write-Host "" }
}
Write-Host ""
+253 -2
View File
@@ -22,7 +22,7 @@ show_menu() {
echo " What would you like to do?"
echo ""
echo " [1] Start Dashboard"
echo " Launch the dashboard web interface."
echo " Launch the classic dashboard web interface."
echo ""
echo " [2] Run Setup"
echo " Configure the dashboard for the first time, or reconfigure."
@@ -31,6 +31,10 @@ show_menu() {
echo " [3] Run Diagnostics"
echo " Check your system for common issues that could block the dashboard."
echo ""
echo " [7] Start New Dashboard (React + ChakraUI)"
echo " Launch the modern React dashboard with auto-install."
echo " Backend API + frontend dev server (http://localhost:5173)"
echo ""
echo " [Q] Quit"
echo ""
}
@@ -620,6 +624,252 @@ if k and k != 'null':
ssh -i "$ssh_key_tmp" -o StrictHostKeyChecking=accept-new "${ssh_user}@${server_host}" "pkill -f kubectl-port-forward" 2>/dev/null || true
}
start_new_dashboard() {
echo ""
echo " Starting NEW dashboard (React + ChakraUI)..."
echo ""
# Check Python
if ! determine_python; then
return
fi
# Check Node.js
if ! command -v node &>/dev/null; then
echo " Node.js: NOT FOUND"
echo ""
echo " Node.js 18+ is required for the new frontend."
echo " Install: https://nodejs.org/ or use nvm"
echo ""
return
fi
echo " Node.js: $(node --version)"
# Check dependencies
test_dependencies
# Check settings
settings_file="$PROJECT_ROOT/settings.yaml"
if [ ! -f "$settings_file" ]; then
echo ""
echo " [ERROR] settings.yaml not found. You need to run setup first."
echo ""
return
fi
# Read settings
server_host=$($PYTHON -c "import yaml; s=yaml.safe_load(open('$settings_file')); print(s['server']['host'])" 2>/dev/null)
ssh_user=$($PYTHON -c "import yaml; s=yaml.safe_load(open('$settings_file')); print(s['server']['user'])" 2>/dev/null)
local_port=$($PYTHON -c "import yaml; s=yaml.safe_load(open('$settings_file')); print(s['database']['port'])" 2>/dev/null)
namespace=$($PYTHON -c "import yaml; s=yaml.safe_load(open('$settings_file')); print(s['kubernetes']['namespace'])" 2>/dev/null)
dashboard_port=$($PYTHON -c "import yaml; s=yaml.safe_load(open('$settings_file')); print(s['dashboard']['port'])" 2>/dev/null)
director_port=$($PYTHON -c "import yaml; s=yaml.safe_load(open('$settings_file')); print(s['director']['port'])" 2>/dev/null)
# Find SSH key (same logic as start_dashboard)
ssh_key_src=$($PYTHON -c "
import yaml
with open('$settings_file') as f:
s = yaml.safe_load(f) or {}
k = s.get('server', {}).get('ssh_key', '')
if k and k != 'null':
print(k)
" 2>/dev/null)
ssh_key=""
key_paths=(
"$ssh_key_src"
"$HOME/.ssh/dune-dashboard-key"
"$PROJECT_ROOT/internal-scripts/ssh/sshKey"
"/tmp/dune-tunnel-key"
"$HOME/.ssh/id_ed25519"
"$HOME/.ssh/id_rsa"
)
for kp in "${key_paths[@]}"; do
if [ -n "$kp" ] && [ -f "$kp" ]; then
if ssh -i "$kp" -o StrictHostKeyChecking=accept-new -o ConnectTimeout=5 -o BatchMode=yes "${ssh_user}@${server_host}" "echo ok" &>/dev/null; then
ssh_key="$kp"
echo " SSH Key: Found working key at $kp"
break
fi
fi
done
if [ -z "$ssh_key" ]; then
echo ""
echo " [ERROR] No working SSH key found."
return
fi
ssh_key_tmp="/tmp/dune-tunnel-key"
cp "$ssh_key" "$ssh_key_tmp" 2>/dev/null
chmod 600 "$ssh_key_tmp"
echo ""
echo "============================================================"
echo " Dune Awakening Dashboard (React Edition)"
echo "============================================================"
echo ""
# Kill existing SSH tunnels
pkill -f "ssh.*-L.*${local_port}" 2>/dev/null || true
pkill -f "ssh.*-L.*${director_port}" 2>/dev/null || true
sleep 1
# [1/5] SSH Tunnel
echo "[1/5] Starting SSH tunnel (localhost:$local_port -> VM)..."
ssh -i "$ssh_key_tmp" -o StrictHostKeyChecking=accept-new -o ServerAliveInterval=30 -o ServerAliveCountMax=3 -L "${local_port}:localhost:${local_port}" -L "${director_port}:localhost:${director_port}" -N "${ssh_user}@${server_host}" &
ssh_tunnel_pid=$!
connected=false
for i in $(seq 1 30); do
sleep 1
if ! kill -0 $ssh_tunnel_pid 2>/dev/null; then
echo "[ERROR] SSH tunnel exited unexpectedly."
return
fi
if ($PYTHON -c "import socket; s=socket.socket(); s.settimeout(1); s.connect(('127.0.0.1', $local_port)); s.close()" 2>/dev/null); then
connected=true
break
fi
done
if [ "$connected" = false ]; then
echo "[ERROR] SSH tunnel did not connect within 30 seconds"
kill $ssh_tunnel_pid 2>/dev/null
return
fi
echo "[OK] SSH tunnel up on localhost:$local_port"
# [2/5] DB Port-Forward
echo "[2/5] Starting DB port-forward on VM..."
if [ -z "$namespace" ] || [ "$namespace" = "" ]; then
echo "[ERROR] Kubernetes namespace is empty."
kill $ssh_tunnel_pid 2>/dev/null
return
fi
db_svc="${namespace}-db-dbdepl-svc"
ssh -i "$ssh_key_tmp" -o StrictHostKeyChecking=accept-new -o ServerAliveInterval=30 "${ssh_user}@${server_host}" "sudo pkill -9 -f port-forward 2>/dev/null; sleep 2" 2>/dev/null
sleep 2
ssh -i "$ssh_key_tmp" -o StrictHostKeyChecking=accept-new -o ServerAliveInterval=30 "${ssh_user}@${server_host}" "nohup sudo kubectl port-forward -n ${namespace} svc/${db_svc} ${local_port}:${local_port} > /tmp/pf.log 2>&1 &" 2>/dev/null
bgd_svc="${namespace}-bgd-svc"
bgd_deploy="${namespace}-bgd-deploy"
bgd_ready=$(ssh -i "$ssh_key_tmp" -o StrictHostKeyChecking=accept-new -o ConnectTimeout=10 "${ssh_user}@${server_host}" "sudo kubectl get deployment $bgd_deploy -n $namespace -o jsonpath='{.status.readyReplicas}'" 2>/dev/null)
if [ -z "$bgd_ready" ] || [ "$bgd_ready" = "0" ]; then
echo " BGD deployment is scaled down, starting..."
ssh -i "$ssh_key_tmp" -o StrictHostKeyChecking=accept-new -o ConnectTimeout=30 "${ssh_user}@${server_host}" "sudo kubectl scale deployment $bgd_deploy -n $namespace --replicas=1" 2>/dev/null
sleep 15
fi
ssh -i "$ssh_key_tmp" -o StrictHostKeyChecking=accept-new -o ServerAliveInterval=30 "${ssh_user}@${server_host}" "nohup sudo kubectl port-forward -n ${namespace} svc/${bgd_svc} ${director_port}:11717 > /tmp/director_pf.log 2>&1 &" 2>/dev/null
sleep 3
# [3/5] Database Check
echo "[3/5] Checking database..."
db_test=false
for i in $(seq 1 15); do
if $PYTHON "$PROJECT_ROOT/scripts/db_check.py" "$local_port" 2>/dev/null | grep -q "ok"; then
db_test=true
break
fi
sleep 1
done
if [ "$db_test" = false ]; then
echo "[ERROR] Database connection failed."
kill $ssh_tunnel_pid 2>/dev/null
return
fi
echo "[OK] Database connected"
# [4/5] Install Dependencies
echo "[4/5] Installing dependencies..."
# Backend Python deps
if [ -f "$PROJECT_ROOT/requirements.txt" ]; then
echo " Installing backend Python dependencies..."
$PYTHON -m pip install -r "$PROJECT_ROOT/requirements.txt" --quiet 2>/dev/null
$PYTHON -m pip install "psycopg[binary]" --quiet 2>/dev/null
echo " Backend dependencies OK"
fi
# Frontend npm deps
frontend_dir="$PROJECT_ROOT/frontend"
if [ -f "$frontend_dir/package.json" ]; then
if [ ! -d "$frontend_dir/node_modules" ]; then
echo " Installing frontend npm dependencies..."
(cd "$frontend_dir" && npm install --silent 2>/dev/null)
echo " Frontend dependencies installed"
else
echo " Frontend dependencies OK"
fi
fi
# [5/5] Start Backend + Frontend
echo "[5/5] Starting dashboard..."
echo ""
# Start backend in background
echo " Starting backend API (port $dashboard_port)..."
backend_dir="$PROJECT_ROOT/backend"
(cd "$backend_dir" && $PYTHON run.py) &
backend_pid=$!
sleep 3
# Verify backend started
backend_alive=false
for i in $(seq 1 10); do
if curl -s "http://127.0.0.1:${dashboard_port}/api/health" &>/dev/null; then
backend_alive=true
break
fi
sleep 2
done
if [ "$backend_alive" = true ]; then
echo " [OK] Backend API running on port $dashboard_port"
else
echo " [WARN] Backend may not have started yet"
fi
# Start frontend in background
echo " Starting frontend dev server (port 5173)..."
(cd "$frontend_dir" && npm run dev -- --host 0.0.0.0) &
frontend_pid=$!
sleep 5
echo ""
echo "============================================================"
echo " New Dashboard Started!"
echo "============================================================"
echo ""
echo " Frontend: http://localhost:5173"
echo " Backend: http://localhost:${dashboard_port}"
echo ""
echo " Press Ctrl+C to stop all services."
echo ""
# Cleanup on exit
cleanup() {
echo ""
echo " Stopping services..."
kill $frontend_pid 2>/dev/null
kill $backend_pid 2>/dev/null
kill $ssh_tunnel_pid 2>/dev/null
ssh -i "$ssh_key_tmp" -o StrictHostKeyChecking=accept-new "${ssh_user}@${server_host}" "pkill -f kubectl-port-forward" 2>/dev/null || true
echo " All services stopped."
echo ""
}
trap cleanup EXIT INT TERM
# Wait for any process to exit
wait $ssh_tunnel_pid $backend_pid $frontend_pid 2>/dev/null
}
# ── Main Loop ───────────────────────────────────────────────────────────
show_banner
@@ -632,8 +882,9 @@ while true; do
1) start_dashboard ;;
2) run_setup ;;
3) run_diagnostics ;;
7) start_new_dashboard ;;
[Qq]) echo ""; echo " Goodbye!"; echo ""; exit 0 ;;
*) echo ""; echo " Invalid choice. Please enter 1, 2, 3, or Q."; echo "" ;;
*) echo ""; echo " Invalid choice. Please enter 1, 2, 3, 7, or Q."; echo "" ;;
esac
echo ""