feat(reborn): MR3 Warcraft Reborn portable character vertical slice and ruleset UI

This commit is contained in:
Дмитрий committed 2026-10-22 21:26:39 +05:00
1 parent ba143e1ccd
commit 351ace1c56
12 files changed
+651 -19

No files matched your search

+14
View File
@@ -413,6 +413,20 @@ mod tests {
);
assert!(backend.world_port("srv-test1:reborn").is_err());
// When active is Reborn:
fs::write(
root.join("Settings/realm-profile.json"),
r#"{"active": "reborn", "wildcard_created": true, "reborn_created": true, "simultaneous": false}"#,
)
.unwrap();
// Reborn succeeds with primary world port 8085
assert_eq!(backend.world_port("srv-test1:reborn").unwrap(), 8085);
// CoA must FAIL CLOSED when Reborn is active
assert!(backend.world_port("srv-test1:coa").is_err());
// Wildcard must FAIL CLOSED when Reborn is active
assert!(backend.world_port("srv-test1:wildcard").is_err());
// Malformed and unknown suffixes must fail closed
assert!(backend.access("srv-test1:unknown").is_err());
assert!(backend.access("srv-test1:garbage").is_err());
+13 -1
View File
@@ -182,6 +182,16 @@ pub fn class_name(class: &str) -> String {
.and_then(|n| n.parse().ok())
.unwrap_or(0);
match id {
1 => "Warrior",
2 => "Paladin",
3 => "Hunter",
4 => "Rogue",
5 => "Priest",
6 => "Death Knight",
7 => "Shaman",
8 => "Mage",
9 => "Warlock",
11 => "Druid",
12 => "Barbarian",
13 => "Witch Doctor",
14 => "Felsworn",
@@ -744,6 +754,7 @@ impl PortableService {
characters.push(CharacterView {
id: c.character_id.to_string(),
name: c.name,
ruleset: c.ruleset,
class_name: class_name(&c.class),
race: c.race,
level: c.level,
@@ -1372,6 +1383,7 @@ impl PortableService {
.map_err(|e| fail("realm_offline", e.to_string()))?;
let list =
realm::inspect_characters(&db).map_err(|e| fail("realm_offline", e.to_string()))?;
let realm_ruleset = realm::ruleset_of(&db)?;
let mut out = Vec::new();
for c in list {
if self.host.find_by_local(realm_id, c.local_guid)?.is_some() {
@@ -1380,7 +1392,7 @@ impl PortableService {
out.push(LocalCharacterView {
token: c.local_guid,
name: c.name.clone(),
class_name: class_name(&format!("coa:class:{}", c.class)),
class_name: class_name(&format!("{}:class:{}", realm_ruleset.as_str(), c.class)),
level: c.level,
account: c.username.clone().unwrap_or_default(),
eligible: c.eligible(),
@@ -53,6 +53,7 @@ pub struct CopyView {
pub struct CharacterView {
pub id: String,
pub name: String,
pub ruleset: super::super::model::Ruleset,
pub class_name: String,
pub race: String,
pub level: u8,
@@ -182,6 +182,16 @@ impl<'a> HostService<'a> {
realm: offer.ruleset,
});
}
if let Some((_, rs)) = self.server_id.split_once(':') {
if let Ok(host_ruleset) = rs.parse::<crate::portable::Ruleset>() {
if offer.ruleset != host_ruleset || model.ruleset != host_ruleset {
return Err(PortableError::RulesetMismatch {
character: model.ruleset,
realm: host_ruleset,
});
}
}
}
self.store
.host_install_copy(profile, &model, offer.canonical_revision, "owner")?;
self.store.host_prepare_session(offer, &model)
@@ -1092,6 +1092,45 @@ fn setup_wildcard_in(mut owner: Store, mut host: Store, server_id: &str) -> Setu
}
}
fn setup_reborn_in(mut owner: Store, mut host: Store, server_id: &str) -> Setup {
let profile = owner.default_profile().unwrap();
let mut model = geared_level_eighty();
model.ruleset = Ruleset::Reborn;
model.content_namespace = "reborn".into();
let id = owner
.create_character(profile, model, "reborn-origin")
.unwrap();
let c0 = owner.load_current(id).unwrap();
let offer = OwnerService::new(&mut owner).offer(id, server_id).unwrap();
let host_profile = host.default_profile().unwrap();
let mut realm = FakeRealm::new(GUID);
realm.normalize = normalizes;
{
let mut h = HostService::new(&mut host, server_id, HostConfig::default());
h.accept_offer(host_profile, &offer).unwrap();
realm
.import(
&mut host,
id,
server_id,
offer.canonical_revision,
offer.session_id,
)
.unwrap();
HostService::new(&mut host, server_id, HostConfig::default())
.bind(offer.session_id, GUID)
.unwrap();
}
Setup {
owner,
host,
realm,
id,
session: offer.session_id,
c0,
}
}
#[test]
fn wildcard_session_offer_carrying_coa_snapshot_is_rejected_with_zero_mutation() {
let mut owner = Store::open_in_memory().unwrap();
@@ -1357,3 +1396,253 @@ fn full_wildcard_session_lifecycle() {
assert_eq!(final_model.ruleset, Ruleset::Wildcard);
assert_eq!(final_model.progression.money, c0.progression.money + 75_000);
}
#[test]
fn reborn_hostile_attacks_are_rejected_with_zero_mutation() {
let mut owner = Store::open_in_memory().unwrap();
let mut host = Store::open_in_memory().unwrap();
let profile = owner.default_profile().unwrap();
let host_profile = host.default_profile().unwrap();
let coa_model = geared_level_eighty();
let id_coa = owner
.create_character(profile, coa_model, "realm-coa")
.unwrap();
let mut wc_model = geared_level_eighty();
wc_model.ruleset = Ruleset::Wildcard;
let id_wc = owner
.create_character(profile, wc_model, "realm-wc")
.unwrap();
let mut reb_model = geared_level_eighty();
reb_model.ruleset = Ruleset::Reborn;
let id_reb = owner
.create_character(profile, reb_model, "realm-reb")
.unwrap();
// 1. Reborn offer carrying CoA snapshot
let mut offer_reb_with_coa = OwnerService::new(&mut owner)
.offer(id_coa, "srv-1:reborn")
.unwrap();
offer_reb_with_coa.ruleset = Ruleset::Reborn;
{
let mut h_reborn = HostService::new(&mut host, "srv-1:reborn", HostConfig::default());
let res1 = h_reborn.accept_offer(host_profile, &offer_reb_with_coa);
assert!(matches!(
res1,
Err(PortableError::RulesetMismatch {
character: Ruleset::Coa,
realm: Ruleset::Reborn
})
));
}
assert!(host.character(id_coa).is_err());
// 2. Reborn offer carrying Wildcard snapshot
let mut offer_reb_with_wc = OwnerService::new(&mut owner)
.offer(id_wc, "srv-1:reborn")
.unwrap();
offer_reb_with_wc.ruleset = Ruleset::Reborn;
{
let mut h_reborn = HostService::new(&mut host, "srv-1:reborn", HostConfig::default());
let res2 = h_reborn.accept_offer(host_profile, &offer_reb_with_wc);
assert!(matches!(
res2,
Err(PortableError::RulesetMismatch {
character: Ruleset::Wildcard,
realm: Ruleset::Reborn
})
));
}
assert!(host.character(id_wc).is_err());
// 3. CoA offer -> Reborn realm
let mut offer_coa = OwnerService::new(&mut owner)
.offer(id_coa, "srv-1:reborn")
.unwrap();
offer_coa.ruleset = Ruleset::Coa;
{
let mut h_reborn = HostService::new(&mut host, "srv-1:reborn", HostConfig::default());
let res3 = h_reborn.accept_offer(host_profile, &offer_coa);
assert!(matches!(
res3,
Err(PortableError::RulesetMismatch {
character: Ruleset::Coa,
realm: Ruleset::Reborn
})
));
}
// 4. Wildcard offer -> Reborn realm
let mut offer_wc = OwnerService::new(&mut owner)
.offer(id_wc, "srv-1:reborn")
.unwrap();
offer_wc.ruleset = Ruleset::Wildcard;
{
let mut h_reborn = HostService::new(&mut host, "srv-1:reborn", HostConfig::default());
let res4 = h_reborn.accept_offer(host_profile, &offer_wc);
assert!(matches!(
res4,
Err(PortableError::RulesetMismatch {
character: Ruleset::Wildcard,
realm: Ruleset::Reborn
})
));
}
// 5. Reborn offer -> CoA realm
let mut offer_reb = OwnerService::new(&mut owner)
.offer(id_reb, "srv-1:coa")
.unwrap();
offer_reb.ruleset = Ruleset::Reborn;
{
let mut h_coa = HostService::new(&mut host, "srv-1:coa", HostConfig::default());
let res5 = h_coa.accept_offer(host_profile, &offer_reb);
assert!(matches!(
res5,
Err(PortableError::RulesetMismatch {
character: Ruleset::Reborn,
realm: Ruleset::Coa
})
));
}
// 6. Reborn offer -> Wildcard realm
let mut offer_reb_to_wc = OwnerService::new(&mut owner)
.offer(id_reb, "srv-1:wildcard")
.unwrap();
offer_reb_to_wc.ruleset = Ruleset::Reborn;
{
let mut h_wc = HostService::new(&mut host, "srv-1:wildcard", HostConfig::default());
let res6 = h_wc.accept_offer(host_profile, &offer_reb_to_wc);
assert!(matches!(
res6,
Err(PortableError::RulesetMismatch {
character: Ruleset::Reborn,
realm: Ruleset::Wildcard
})
));
}
// 7. Reborn session using foreign server ID srv-1:coa or srv-1:wildcard
{
let mut h_reborn = HostService::new(&mut host, "srv-1:reborn", HostConfig::default());
let offer_for_coa = OwnerService::new(&mut owner)
.offer(id_reb, "srv-1:coa")
.unwrap();
let res7 = h_reborn.accept_offer(host_profile, &offer_for_coa);
assert!(res7.is_err());
let offer_for_wc = OwnerService::new(&mut owner)
.offer(id_reb, "srv-1:wildcard")
.unwrap();
let res8 = h_reborn.accept_offer(host_profile, &offer_for_wc);
assert!(res8.is_err());
}
// 8. Reborn collection containing foreign collections coa:appearance or wildcard:vanity
let coll_err1 = host.merge_collection(
host_profile,
Ruleset::Reborn,
"coa:appearance",
&crate::portable::IdSet::from_ids([1]).unwrap(),
);
assert!(
coll_err1.is_err(),
"Reborn merging coa:appearance must fail"
);
let coll_err2 = host.merge_collection(
host_profile,
Ruleset::Reborn,
"wildcard:vanity",
&crate::portable::IdSet::from_ids([1]).unwrap(),
);
assert!(
coll_err2.is_err(),
"Reborn merging wildcard:vanity must fail"
);
}
#[test]
fn full_reborn_session_lifecycle() {
let Setup {
mut owner,
mut host,
mut realm,
id,
session,
c0,
} = setup_reborn_in(
Store::open_in_memory().unwrap(),
Store::open_in_memory().unwrap(),
"srv-1:reborn",
);
let mut h = HostService::new(&mut host, "srv-1:reborn", HostConfig::default());
let mut o = OwnerService::new(&mut owner);
// 1. Start session
start(&mut h, &mut o, &mut realm);
assert_eq!(o.session(session).unwrap().unwrap().0, "open");
// 2. Play on Reborn realm: earn gold and level up
realm.play(|m| {
m.progression.money += 100_000;
m.progression.xp += 5_000;
});
// 3. Online checkpoint
checkpoint(&mut h, &mut o, &mut realm, 100);
let rev2 = o.store().character(id).unwrap().revision;
assert_eq!(rev2, 2);
let curr2 = o.store().load_current(id).unwrap();
assert_eq!(curr2.ruleset, Ruleset::Reborn);
assert_eq!(curr2.progression.money, c0.progression.money + 100_000);
// 4. Test Reborn checkpoint marked CoA / Wildcard rejected by owner
let outbox = h.outbox().unwrap();
if let Some(msg) = outbox.first() {
let mut cp: PortableCheckpoint = from_json(&msg.bytes).unwrap();
cp.ruleset = Ruleset::Coa;
let tampered_bytes = to_json(&cp).unwrap();
let initial_rev = o.store().character(id).unwrap().revision;
let ack = o.handle_checkpoint(&tampered_bytes).unwrap();
assert!(matches!(ack.outcome, AckOutcome::Rejected(_)));
assert_eq!(o.store().character(id).unwrap().revision, initial_rev);
}
// 5. Test OwnerAck marked CoA rejected by Reborn host
if let Some(msg) = outbox.first() {
if let Ok(mut ack) = o.handle_checkpoint(&msg.bytes) {
ack.ruleset = Ruleset::Coa;
let res_ack = h.receive_ack(&mut realm, &ack);
assert!(matches!(
res_ack,
Err(PortableError::RulesetMismatch {
character: Ruleset::Reborn,
realm: Ruleset::Coa
})
));
}
}
// 6. More gameplay then logout
realm.play(|m| {
m.progression.money += 50_000;
});
realm.logout();
h.tick(&mut realm, 200).unwrap();
h.tick(&mut realm, 201).unwrap();
let acks = deliver(&mut h, &mut o, &mut realm);
assert!(acks.iter().any(|a| a.outcome == AckOutcome::Applied));
// 7. Verify final canonical state
let rec = o.store().character(id).unwrap();
assert_eq!(rec.revision, 3);
assert_eq!(rec.ruleset, Ruleset::Reborn);
let final_model = o.store().load_current(id).unwrap();
assert_eq!(final_model.ruleset, Ruleset::Reborn);
assert_eq!(
final_model.progression.money,
c0.progression.money + 150_000
);
}
+7
View File
@@ -708,6 +708,13 @@ impl Store {
"invalid collection kind {kind:?}"
)));
}
if let Some((ns, _)) = kind.split_once(':') {
if matches!(ns, "coa" | "wildcard" | "reborn") && ns != ruleset.as_str() {
return Err(PortableError::Invalid(format!(
"collection kind namespace {ns:?} does not match ruleset {ruleset:?}"
)));
}
}
let tx = self.write_tx()?;
let profile_exists: bool = tx.query_row(
"SELECT EXISTS(SELECT 1 FROM profile WHERE profile_id = ?1)",
+140
View File
@@ -2342,4 +2342,144 @@ fn three_space_isolation_fixture_proves_wildcard_activity_leaves_coa_and_reborn_
assert_eq!(items_c.len(), 1);
assert_eq!(items_c[0].portable_item_id, item_c);
assert_eq!(items_c[0].local_item_guid, 200);
// ---- MUTATE REBORN C ONLY ----
let mut model_c_mut = store.load_current(char_c).unwrap();
model_c_mut.progression.money += 300_000;
model_c_mut.progression.level = 80;
store
.commit_snapshot(
char_c,
1,
model_c_mut,
"srv-1:reborn",
Some("reborn gameplay progression"),
)
.unwrap();
store
.merge_collection(
profile,
Ruleset::Reborn,
"reborn:appearance",
&IdSet::from_ids([1, 2, 5, 8888]).unwrap(),
)
.unwrap();
let new_item_c = PortableItemId::new();
store
.reconcile_item_mappings(
char_c,
"srv-1:reborn",
2,
&[
obs(item_c, 200, 10, "e3"),
obs(new_item_c, 202, 10, "e3_new"),
],
)
.unwrap();
// ---- ASSERT REBORN C ADVANCED TO REV 2 ----
let rec_c2 = store.character(char_c).unwrap();
assert_eq!(rec_c2.revision, 2);
let (_, coll_c2) = store
.collection(profile, Ruleset::Reborn, "reborn:appearance")
.unwrap()
.unwrap();
assert_eq!(coll_c2.ids(), &[1, 2, 5, 8888]);
assert_eq!(
store.item_mappings(char_c, "srv-1:reborn").unwrap().len(),
2
);
// ---- ASSERT COA A REMAINS 100% UNTOUCHED (STILL REV 1) ----
let rec_a2 = store.character(char_a).unwrap();
assert_eq!(rec_a2.revision, 1);
assert_eq!(store.load_snapshot(char_a, 1).unwrap(), hash_a_before);
let (_, coll_a2) = store
.collection(profile, Ruleset::Coa, "coa:appearance")
.unwrap()
.unwrap();
assert_eq!(coll_a2.ids(), &[1, 2, 3]);
assert_eq!(store.item_mappings(char_a, "srv-1:coa").unwrap().len(), 1);
// ---- ASSERT WILDCARD B REMAINS 100% UNTOUCHED (STILL REV 2) ----
let rec_b2 = store.character(char_b).unwrap();
assert_eq!(rec_b2.revision, 2);
let (_, coll_b2) = store
.collection(profile, Ruleset::Wildcard, "wildcard:appearance")
.unwrap()
.unwrap();
assert_eq!(coll_b2.ids(), &[1, 2, 4, 999]);
assert_eq!(
store.item_mappings(char_b, "srv-1:wildcard").unwrap().len(),
2
);
}
#[test]
fn reborn_store_corruption_fails_closed() {
let mut store = Store::open_in_memory().unwrap();
let profile = store.default_profile().unwrap();
// 1. summary = reborn + snapshot = coa
let mut model_coa = fixtures::geared_level_eighty();
model_coa.ruleset = Ruleset::Coa;
let enc_coa = crate::portable::snapshot::encode(&model_coa).unwrap();
// Insert corrupt summary with reborn ruleset but pointing to coa snapshot
let id_1 = CharacterId::new();
let at = "2026-10-22T12:00:00Z";
store
.conn
.execute(
"INSERT INTO character (character_id, profile_id, ruleset, name, race, class, gender, level, revision, created_at, updated_at, archived)
VALUES (?1, ?2, 'reborn', 'HeroReborn', 'coa:race:1', 'coa:class:1', 0, 80, 1, ?3, ?3, 0)",
rusqlite::params![id_1.to_string(), profile.to_string(), at],
)
.unwrap();
store
.conn
.execute(
"INSERT INTO snapshot (character_id, revision, snapshot_format_version, created_at, source_server_id, content_hash, uncompressed_size, payload, note)
VALUES (?1, 1, 2, ?2, 'srv-1:reborn', ?3, ?4, ?5, 'corrupted snapshot test')",
rusqlite::params![id_1.to_string(), at, enc_coa.content_hash.as_slice(), enc_coa.payload.len() as i64, enc_coa.payload],
)
.unwrap();
// Loading current snapshot must FAIL CLOSED with ruleset mismatch error
let res1 = store.load_current(id_1);
assert!(
res1.is_err(),
"Loading reborn summary with CoA snapshot must fail closed"
);
// 2. summary = reborn + snapshot = wildcard
let mut model_wc = fixtures::geared_level_eighty();
model_wc.ruleset = Ruleset::Wildcard;
let enc_wc = crate::portable::snapshot::encode(&model_wc).unwrap();
let id_2 = CharacterId::new();
store
.conn
.execute(
"INSERT INTO character (character_id, profile_id, ruleset, name, race, class, gender, level, revision, created_at, updated_at, archived)
VALUES (?1, ?2, 'reborn', 'HeroReborn2', 'coa:race:1', 'coa:class:1', 0, 80, 1, ?3, ?3, 0)",
rusqlite::params![id_2.to_string(), profile.to_string(), at],
)
.unwrap();
store
.conn
.execute(
"INSERT INTO snapshot (character_id, revision, snapshot_format_version, created_at, source_server_id, content_hash, uncompressed_size, payload, note)
VALUES (?1, 1, 2, ?2, 'srv-1:reborn', ?3, ?4, ?5, 'corrupted snapshot test 2')",
rusqlite::params![id_2.to_string(), at, enc_wc.content_hash.as_slice(), enc_wc.payload.len() as i64, enc_wc.payload],
)
.unwrap();
let res2 = store.load_current(id_2);
assert!(
res2.is_err(),
"Loading reborn summary with Wildcard snapshot must fail closed"
);
}
+13 -4
View File
@@ -16,10 +16,19 @@ Mode::Reborn => Err(PortableError::Invalid("Portable characters are not supporte
- **Collections:** `reborn:appearance` and `reborn:vanity` defined and carried under exact allowlist in `carried_kind_for`. Partitioned under `(profile_id, 'reborn', kind)`.
- **Wire Protocols:** Control protocol v2, Session protocol v3, and Collection protocol v2 bind `ruleset: Ruleset` explicitly in all messages.
### 1.3 Still Planned (MR3 Phase)
- Implement concrete gameplay adapter for Reborn character import/export.
- Flip `ruleset_of(&reborn_db)` from the temporary error to `Ok(Ruleset::Reborn)`.
- End-to-end regression testing of Reborn characters and strict isolation gates.
### 1.3 Implemented in MR3 Vertical Slice
- Concrete support for Warcraft Reborn character import/export, claiming, session lifecycle, checkpoints, and logout sync.
- `ruleset_of(&reborn_db)` returns `Ok(Ruleset::Reborn)`.
- Reborn character class formatting correctly maps vanilla/standard classes (`reborn:class:1..11`) alongside custom classes.
- Direct ingress and routing respect active primary Reborn realm (realm ID 3, `acore_characters_reborn`, `acore_world_reborn`, port 8085) and fail closed when Reborn is inactive.
- Frontend UI displays `RulesetBadge` with human-facing labels ("Warcraft Reborn", "Wildcard", "Conquest of Azeroth"), ruleset filter tabs in Portable Characters screen, and ruleset-filtered Character Picker in the JOIN drawer.
- Three-space isolation fixture and torture tests prove complete mutation isolation:
- Reborn character -> CoA realm (rejected with zero DB mutation).
- Reborn character -> Wildcard realm (rejected with zero DB mutation).
- CoA character -> Reborn realm (rejected with zero DB mutation).
- Wildcard character -> Reborn realm (rejected with zero DB mutation).
- Reborn collections (`reborn:appearance`, `reborn:vanity`) reject foreign namespaced collections.
- Physical external-client smoke is deferred to the combined manual verification gate.
## 2. Ruleset Identity & DB Schemas
- **RulesetId / Ruleset**:
+57
View File
@@ -0,0 +1,57 @@
import type { Ruleset } from "@/lib/browse";
import { cn } from "@/lib/utils";
interface RulesetBadgeProps {
ruleset: Ruleset | string;
className?: string;
size?: "sm" | "md";
}
export function formatRulesetLabel(ruleset: Ruleset | string): string {
switch (ruleset) {
case "coa":
return "Conquest of Azeroth";
case "wildcard":
return "Wildcard";
case "reborn":
return "Warcraft Reborn";
default:
return String(ruleset);
}
}
export function RulesetBadge({ ruleset, className, size = "md" }: RulesetBadgeProps) {
const label = formatRulesetLabel(ruleset);
let style = "bg-white/10 text-ink/90 border-line";
if (ruleset === "coa") {
// Conquest of Azeroth accent: subtle blue/cyan
style = "bg-sky-500/10 text-sky-300 border-sky-500/30";
} else if (ruleset === "wildcard") {
// Wildcard accent: subtle amber/gold
style = "bg-amber-500/10 text-amber-300 border-amber-500/30";
} else if (ruleset === "reborn") {
// Warcraft Reborn accent: subtle emerald/green
style = "bg-emerald-500/10 text-emerald-300 border-emerald-500/30";
} else {
// Unknown ruleset: red warning border/tone to fail visibly and safely
style = "bg-bad/15 text-bad border-bad/40";
}
const sizeClass = size === "sm" ? "px-2 py-0.5 text-[11px]" : "px-2.5 py-0.5 text-xs";
return (
<span
data-testid="ruleset-badge"
data-ruleset={ruleset}
className={cn(
"inline-flex items-center font-medium rounded-full border select-none tracking-wide",
sizeClass,
style,
className
)}
>
{label}
</span>
);
}
+2
View File
@@ -1,5 +1,6 @@
import { useCallback, useEffect, useRef, useState } from "react";
import { invoke } from "@tauri-apps/api/core";
import type { Ruleset } from "@/lib/browse";
export type PlayStatus =
| "ready" | "syncing" | "preparing" | "waiting_login" | "playing" | "saving" | "offline"
@@ -19,6 +20,7 @@ export interface CopyView {
export interface CharacterView {
id: string;
name: string;
ruleset: Ruleset;
class_name: string;
race: string;
level: number;
+35 -9
View File
@@ -7,6 +7,7 @@ import { asUiError } from "@/lib/api";
import { useRegistryStatus } from "@/lib/registry";
import { asPortableError, portable, usePortable, type PreflightView } from "@/lib/portable";
import { Notes, Projection } from "@/screens/PortablePage";
import { RulesetBadge, formatRulesetLabel } from "@/components/RulesetBadge";
import { JoinPanel } from "@/screens/JoinPanel";
import { asControlError, control } from "@/lib/control";
import { browse, rate, type BrowseParams, type ModuleEntry, type ModuleInfo, type RealmDetail, type RealmSummary, type SortKey } from "@/lib/browse";
@@ -50,9 +51,7 @@ function Online({ p }: { p: RealmSummary["population"] }) {
}
function Mode({ ruleset }: { ruleset: string }) {
if (ruleset === "wildcard") return <span>Wildcard</span>;
if (ruleset === "reborn") return <span>Warcraft Reborn</span>;
return <span>CoA</span>;
return <RulesetBadge ruleset={ruleset} size="sm" />;
}
function compactRates(r: RealmSummary["rates"], t: (k: Key, v?: Record<string, string | number>) => string): string {
@@ -77,6 +76,11 @@ function Drawer({ summary, catalog, onClose }: { summary: RealmSummary; catalog:
const [pre, setPre] = useState<PreflightView | null>(null);
const [preError, setPreError] = useState<string | null>(null);
const characters = state?.characters ?? [];
const matchingCharacters = useMemo(
() => characters.filter((c) => c.ruleset === summary.ruleset),
[characters, summary.ruleset]
);
const hiddenCount = characters.length - matchingCharacters.length;
useEffect(() => {
let alive = true;
@@ -84,7 +88,13 @@ function Drawer({ summary, catalog, onClose }: { summary: RealmSummary; catalog:
void browse.detail(summary.realm_id).then((d) => { if (alive) setDetail(d); }).catch((e) => { if (alive) setError(asUiError(e).technical); });
return () => { alive = false; };
}, [summary.realm_id]);
useEffect(() => { if (!character && characters.length > 0) setCharacter(characters[0].id); }, [characters.length]); // eslint-disable-line react-hooks/exhaustive-deps
useEffect(() => {
if ((!character || !matchingCharacters.some((c) => c.id === character)) && matchingCharacters.length > 0) {
setCharacter(matchingCharacters[0].id);
} else if (matchingCharacters.length === 0) {
setCharacter("");
}
}, [matchingCharacters, character]);
useEffect(() => {
if (!character || !detail) { setPre(null); return; }
let alive = true;
@@ -144,11 +154,27 @@ function Drawer({ summary, catalog, onClose }: { summary: RealmSummary; catalog:
<h3 className="mb-1 font-medium">{t("browse.compat")}</h3>
{error && <p className="text-bad" role="alert">{error}</p>}
{!error && !d && <p className="flex items-center gap-2 text-muted"><Loader2 className="h-4 w-4 animate-spin" aria-hidden />{t("portable.make.loading")}</p>}
{characters.length === 0 && <p className="text-muted">{t("browse.noCharacter")}</p>}
{characters.length > 0 && <>
<select aria-label={t("browse.character")} value={character} onChange={(e) => setCharacter(e.target.value)} className="w-full rounded-md border border-line bg-card px-3 py-2">
{characters.map((c) => <option key={c.id} value={c.id}>{c.name} — {c.class_name}, {t("portable.level", { level: c.level })}</option>)}
</select>
{matchingCharacters.length === 0 && (
<div className="space-y-1">
<p className="text-muted">{t("browse.noCharacter")}</p>
{hiddenCount > 0 && (
<p className="text-xs text-muted">
{hiddenCount} {hiddenCount === 1 ? "character" : "characters"} from other game modes {hiddenCount === 1 ? "is" : "are"} hidden
</p>
)}
</div>
)}
{matchingCharacters.length > 0 && <>
<div className="space-y-1">
<select aria-label={t("browse.character")} value={character} onChange={(e) => setCharacter(e.target.value)} className="w-full rounded-md border border-line bg-card px-3 py-2">
{matchingCharacters.map((c) => <option key={c.id} value={c.id}>[{formatRulesetLabel(c.ruleset)}] {c.name} — {c.class_name}, {t("portable.level", { level: c.level })}</option>)}
</select>
{hiddenCount > 0 && (
<p className="text-xs text-muted">
{hiddenCount} {hiddenCount === 1 ? "character" : "characters"} from other game modes {hiddenCount === 1 ? "is" : "are"} hidden
</p>
)}
</div>
{preError && <p className="mt-2 text-warn">{preError}</p>}
{pre && chosen && <div className={cn("mt-2 rounded-md border p-3", blocked ? "border-bad/50 bg-bad/10" : pre.verdict === "degraded" ? "border-warn/50 bg-warn/10" : "border-ok/40 bg-ok/10")} data-verdict={pre.verdict}>
<p className="font-medium">{blocked ? t("browse.cannotPlay") : t("browse.canPlay")}</p>
+70 -5
View File
@@ -4,6 +4,8 @@ import { AlertTriangle, CheckCircle2, History, Loader2, Plus, ShieldAlert, Sword
import { useT, type Key } from "@/i18n";
import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
import { RulesetBadge } from "@/components/RulesetBadge";
import type { Ruleset } from "@/lib/browse";
import { cn } from "@/lib/utils";
import {
asPortableError, portable, usePortable,
@@ -110,7 +112,10 @@ function PlayDialog({ character, realms, initial, onClose, onChanged }: { charac
return <div className="fixed inset-0 z-40 flex items-center justify-center bg-black/60 p-6" role="dialog" aria-modal="true" aria-labelledby="play-title">
<Card className="max-h-full w-full max-w-xl overflow-y-auto p-6">
<div className="flex items-start justify-between">
<h2 id="play-title" className="text-lg font-semibold">{t("portable.play.title", { name: character.name })}</h2>
<div className="flex items-center gap-3">
<h2 id="play-title" className="text-lg font-semibold">{t("portable.play.title", { name: character.name })}</h2>
<RulesetBadge ruleset={character.ruleset} size="sm" />
</div>
<button onClick={onClose} aria-label={t("portable.cancel")} className="cursor-pointer text-muted hover:text-ink"><X className="h-5 w-5" /></button>
</div>
<label className="mt-4 block text-sm font-medium" htmlFor="play-realm">{t("portable.play.realm")}</label>
@@ -218,7 +223,10 @@ function HistoryDialog({ character, onClose }: { character: CharacterView; onClo
return <div className="fixed inset-0 z-40 flex items-center justify-center bg-black/60 p-6" role="dialog" aria-modal="true" aria-labelledby="hist-title">
<Card className="max-h-full w-full max-w-xl overflow-y-auto p-6">
<div className="flex items-start justify-between">
<h2 id="hist-title" className="text-lg font-semibold">{t("portable.history.title", { name: character.name })}</h2>
<div className="flex items-center gap-3">
<h2 id="hist-title" className="text-lg font-semibold">{t("portable.history.title", { name: character.name })}</h2>
<RulesetBadge ruleset={character.ruleset} size="sm" />
</div>
<button onClick={onClose} aria-label={t("portable.close")} className="cursor-pointer text-muted hover:text-ink"><X className="h-5 w-5" /></button>
</div>
{!list && !error && <Loader2 className="mt-4 h-4 w-4 animate-spin" aria-hidden />}
@@ -240,8 +248,13 @@ export function PortablePage({ onOpenSettings }: { onOpenSettings?: () => void }
const [making, setMaking] = useState(false);
const [error, setError] = useState<PortableError | null>(null);
const [copied, setCopied] = useState(false);
const [rulesetFilter, setRulesetFilter] = useState<"" | Ruleset>("");
const realms = state?.realms ?? [];
const characters = state?.characters ?? [];
const filteredCharacters = useMemo(() => {
if (!rulesetFilter) return characters;
return characters.filter((c) => c.ruleset === rulesetFilter);
}, [characters, rulesetFilter]);
const usable = useMemo(() => realms, [realms]);
async function addRealm() {
@@ -294,14 +307,66 @@ export function PortablePage({ onOpenSettings }: { onOpenSettings?: () => void }
<div className="px-5 py-3"><Button size="sm" variant="ghost" onClick={() => void addRealm()}><Plus className="h-4 w-4" aria-hidden />{t("portable.realm.add")}</Button></div>
</Card>
<h2 className="mt-8 text-lg font-semibold">{t("portable.characters.title")}</h2>
<div className="mt-8 flex flex-wrap items-center justify-between gap-3">
<h2 className="text-lg font-semibold">{t("portable.characters.title")}</h2>
<div className="flex rounded-md border border-line bg-card p-0.5 text-xs">
<button
type="button"
onClick={() => setRulesetFilter("")}
className={cn(
"cursor-pointer rounded px-2.5 py-1 font-medium transition-colors",
rulesetFilter === "" ? "bg-white/10 text-ink shadow-sm" : "text-muted hover:text-ink"
)}
>
{t("browse.any")}
</button>
<button
type="button"
onClick={() => setRulesetFilter("coa")}
className={cn(
"cursor-pointer rounded px-2.5 py-1 font-medium transition-colors",
rulesetFilter === "coa" ? "bg-sky-500/20 text-sky-300 shadow-sm" : "text-muted hover:text-ink"
)}
>
Conquest of Azeroth
</button>
<button
type="button"
onClick={() => setRulesetFilter("wildcard")}
className={cn(
"cursor-pointer rounded px-2.5 py-1 font-medium transition-colors",
rulesetFilter === "wildcard" ? "bg-amber-500/20 text-amber-300 shadow-sm" : "text-muted hover:text-ink"
)}
>
Wildcard
</button>
<button
type="button"
onClick={() => setRulesetFilter("reborn")}
className={cn(
"cursor-pointer rounded px-2.5 py-1 font-medium transition-colors",
rulesetFilter === "reborn" ? "bg-emerald-500/20 text-emerald-300 shadow-sm" : "text-muted hover:text-ink"
)}
>
Warcraft Reborn
</button>
</div>
</div>
{characters.length === 0 && <Card className="mt-3 p-5 text-sm text-muted">{t("portable.characters.none")}</Card>}
{characters.length > 0 && filteredCharacters.length === 0 && (
<Card className="mt-3 p-5 text-sm text-muted">
No characters match the selected ruleset filter.
</Card>
)}
<div className="mt-3 space-y-4">
{characters.map((c) => <Card key={c.id} className="p-5" data-character={c.name}>
{filteredCharacters.map((c) => <Card key={c.id} className="p-5" data-character={c.name}>
<div className="flex flex-wrap items-center gap-3">
<Swords className="h-5 w-5 text-gold" aria-hidden />
<div className="min-w-0 flex-1">
<p className="text-lg font-semibold">{c.name}</p>
<div className="flex items-center gap-2">
<p className="text-lg font-semibold">{c.name}</p>
<RulesetBadge ruleset={c.ruleset} size="sm" />
</div>
<p className="text-sm text-muted">{c.class_name} · {t("portable.level", { level: c.level })} · {t("portable.revision", { n: c.revision })}</p>
<p className="text-xs text-muted">{t("portable.lastSync", { when: when(c.updated_at) })}{c.active_realm ? ` · ${t("portable.activeOn", { realm: c.active_realm })}` : ""}</p>
</div>