diff --git a/Server/src/SOR.Admin/Components/Pages/Cards/AbilityBuilder.razor b/Server/src/SOR.Admin/Components/Pages/Cards/AbilityBuilder.razor index 136b9fe..5ce69eb 100644 --- a/Server/src/SOR.Admin/Components/Pages/Cards/AbilityBuilder.razor +++ b/Server/src/SOR.Admin/Components/Pages/Cards/AbilityBuilder.razor @@ -1,4 +1,5 @@ @* AbilityBuilder.razor — structured UI for AbilityDefinition[] / Action[] JSON *@ +@using Microsoft.AspNetCore.Components.Rendering
@if (_abilities.Count == 0) @@ -82,12 +83,41 @@
-
-
- - + + +
+
+ +
+ @if (ab.Costs.Count == 0) + { +

Free (no cost).

+ } + else + { + @for (int ci = 0; ci < ab.Costs.Count; ci++) + { + var cidx = ci; + var cost = ab.Costs[cidx]; +
+ + + +
+ } + }
} else if (ab.TypeStr == "Aura") @@ -128,14 +158,49 @@
} - +
- - +
+ + +
+ @if (ab.Conditions.Count == 0) + { +

None (always activatable).

+ } + else + { + @for (int condI = 0; condI < ab.Conditions.Count; condI++) + { + var condIdx = condI; + var cond = ab.Conditions[condIdx]; +
+ + + @RenderConditionFields(cond) + +
+ } + }
@@ -186,9 +251,9 @@
- +
@@ -202,8 +267,9 @@ var effect = action.Effects[effectIdx];
-
-
+
+ +
+ +
+ +
+ @RenderEffectFields(effect) +
-
+ +
- -
- - + +
+
+ + +
+ @if (action.Conditions.Count == 0) + { +

None.

+ } + else + { + @for (int acI = 0; acI < action.Conditions.Count; acI++) + { + var acIdx = acI; + var ac = action.Conditions[acIdx]; +
+ + + @RenderConditionFields(ac) + +
+ } + }
@@ -304,22 +404,39 @@ private string _lastJson = ""; private bool _showRaw; - // ── Enum string options ────────────────────────────────────────────────────── + // ── Static enum options ────────────────────────────────────────────────────── - private static readonly string[] AbilityTypes = - ["Active", "Passive", "Aura", "Triggered"]; + private static readonly string[] AbilityTypes = ["Active", "Passive", "Aura", "Triggered"]; + private static readonly string[] TargetScopes = ["Hand", "Deck", "Discard", "Battlefield", "Player", "AnyZone"]; + private static readonly string[] TargetTypes = ["Unit", "ArchSpirit", "Spirit", "SpiritToken", "Ruin", "Tile", "Card", "Player"]; + private static readonly string[] TargetOwnerships= ["Self", "Owner", "Ally", "Enemy", "Any", "Random", "Target"]; - private static readonly string[] TargetScopes = - ["Hand", "Deck", "Discard", "Battlefield", "Player", "AnyZone"]; + private static readonly string[] AffinityValues = [ + "Void", "Aether", "Lake", "Hill", "Forest", "Field", + "Ocean", "Island", "Marsh", "Swamp", "Mountain", "Steppe", + "Fort", "Plains", "Grove", "Jungle", + "UnstableAether", "PerfectAether", "PureVoid", + ]; + private static readonly string[] MovementTypeValues = ["Walk", "Flight", "Jump", "Teleport"]; + private static readonly string[] DirectionValues = ["North", "South", "East", "West", "NorthEast", "NorthWest", "SouthEast", "SouthWest"]; + private static readonly string[] ComparatorValues = ["Equal", "NotEqual", "LessThan", "LessThanOrEqual", "GreaterThan", "GreaterThanOrEqual"]; + private static readonly string[] DurationTypeValues = ["Instant", "UntilEndOfTurn", "UntilStartOfOwnerTurn", "UntilStartOfSourceOwnerTurn", "ForNTurns", "PermanentInMatch"]; + private static readonly string[] StatTargetValues = ["Current", "Base", "Max"]; + private static readonly string[] StatValues = ["Damage", "Defense", "Health", "MP"]; + private static readonly string[] PositionValues = ["Top", "Bottom"]; + private static readonly string[] PlayerValues = ["Owner", "Opponent", "Both", "Any"]; + private static readonly string[] OwnershipValues = ["Any", "Owner", "Ally", "Enemy"]; + private static readonly string[] UnitTypeValues = ["Unit", "Spirit", "ArchSpirit", "SpiritToken"]; + private static readonly string[] ControllerValues = ["Owner", "Opponent"]; + private static readonly string[] ZoneValues = ["Hand", "Deck", "Discard", "Battlefield"]; - private static readonly string[] TargetTypes = - ["Unit", "ArchSpirit", "Spirit", "SpiritToken", "Ruin", "Tile", "Card", "Player"]; + private static readonly string[] CostTypes = [ + "SpiritPoints", "SacrificeTokens", "DiscardFromHand", "MillTopOfDeck", + "MillBottomOfDeck", "SendSpiritFromBattlefieldToDiscard", + "DealDamageToOwnArchSpirit", "DealDamageToOwnSpirit", + ]; - private static readonly string[] TargetOwnerships = - ["Self", "Owner", "Ally", "Enemy", "Any", "Random", "Target"]; - - private static readonly string[] TriggerTypesList = - [ + private static readonly string[] TriggerTypesList = [ "OnTurnStart", "OnTurnEnd", "OnChanneled", "OnAscend", "OnTransition", "OnUnitMove", "OnUnitAttack", "OnUnitAbilityActivated", "OnUnitMPSpent", @@ -334,7 +451,7 @@ "OnTargetedByAbility", "OnEffectApplied", "OnEnterAuraRange", "OnLeaveAuraRange", ]; - // ── Effect groups and templates ────────────────────────────────────────────── + // ── Effect groups ──────────────────────────────────────────────────────────── private sealed record EffectGroup(string Label, string[] Types); @@ -362,77 +479,38 @@ new("Token & Deferred", ["SummonToken", "ApplyOnEvent"]), ]; - private static readonly Dictionary EffectTemplates = new() - { - ["DealDamage"] = """{"Amount":{"Fixed":1},"BypassDefense":false}""", - ["Heal"] = """{"Amount":{"Fixed":1}}""", - ["DealDamageToSelf"] = """{"Amount":{"Fixed":1},"BypassDefense":false}""", - ["DOT"] = """{"Amount":{"Fixed":1},"BypassDefense":false,"Duration":{"Type":"UntilEndOfTurn"}}""", - ["HOT"] = """{"Amount":{"Fixed":1},"Duration":{"Type":"UntilEndOfTurn"}}""", - ["ModifyHealth"] = """{"Amount":{"Fixed":1},"StatTarget":"Current"}""", - ["ModifyDefense"] = """{"Amount":{"Fixed":1},"StatTarget":"Current"}""", - ["ModifyDamage"] = """{"Amount":{"Fixed":1}}""", - ["ModifyMP"] = """{"Amount":{"Fixed":1},"StatTarget":"Current"}""", - ["ModifySP"] = """{"Amount":{"Fixed":1}}""", - ["ModifyST"] = """{"Amount":{"Fixed":1}}""", - ["GrantAdditionalAttack"] = """{"N":1}""", - ["SetAttackRange"] = """{"Min":1,"Max":2}""", - ["SetMovementType"] = """{"MovementType":"Walk"}""", - ["ModifyCost"] = """{"Sp":null,"St":null}""", - ["SetStatModMultiplier"] = """{"Stat":"Damage","Multiplier":1.5}""", - ["SetCanMove"] = """{"Value":true}""", - ["SetCanAttack"] = """{"Value":true}""", - ["SetCanDefend"] = """{"Value":true}""", - ["SetCanBeAttacked"] = """{"Value":true}""", - ["SetCanBeBlocked"] = """{"Value":true}""", - ["SetCanBeObstructed"] = """{"Value":true}""", - ["SetCanUseAbility"] = """{"Value":true}""", - ["SetCanBeSacrificed"] = """{"Value":true}""", - ["SetCanDrawCards"] = """{"Value":true}""", - ["SetAccumulatesSP"] = """{"Value":true}""", - ["SetCanChannelSpirit"] = """{"Value":true}""", - ["SetCanSacrificeSpirit"] = """{"Value":true}""", - ["SetCanAscendArchSpirit"] = """{"Value":true}""", - ["SetCanTransitionArchSpirit"] = """{"Value":true}""", - ["SetCanChannelRepentance"] = """{"Value":true}""", - ["SetCanChannelInstinct"] = """{"Value":true}""", - ["SetCanChannelRuin"] = """{"Value":true}""", - ["SetCanChannelTerramorphaMono"] = """{"Value":true}""", - ["SetCanChannelTerramorphaDi"] = """{"Value":true}""", - ["SetCanChannelTerramorphaTri"] = """{"Value":true}""", - ["ModifyCardsDrawnPerTurn"] = """{"Amount":{"Fixed":1}}""", - ["ModifySPAccumulation"] = """{"Amount":{"Fixed":1}}""", - ["DrawCards"] = """{"N":1,"Player":"Owner"}""", - ["DiscardCards"] = """{"N":1,"Player":"Owner"}""", - ["ReturnToHand"] = """{}""", - ["ReturnToDeck"] = """{"Position":"top"}""", - ["SendToDiscard"] = """{}""", - ["ShuffleDeck"] = """{"Player":"Owner"}""", - ["ReturnToBattlefield"] = """{"Controller":"Owner"}""", - ["SearchDeck"] = """{"Count":1}""", - ["RevealCards"] = """{"N":1}""", - ["PlaceOnDeck"] = """{"Position":"top"}""", - ["ChannelCard"] = """{"PayCost":true}""", - ["AddGenus"] = """{"Tag":"Elemental"}""", - ["RemoveGenus"] = """{"Tag":"Elemental"}""", - ["SetAffinity"] = """{"Affinity":{"Fixed":"Aether"}}""", - ["SetBaseAffinity1"] = """{"Affinity":{"Fixed":"Aether"}}""", - ["SetBaseAffinity2"] = """{"Affinity":{"Fixed":"Lake"}}""", - ["PushAffinity"] = """{"Affinity":{"Fixed":"Aether"}}""", - ["PushFinalAffinity"] = """{"Affinity":{"Fixed":"Aether"}}""", - ["AddAbility"] = """{"AbilityDef":{"Type":"Passive","Actions":[]}}""", - ["RemoveAbility"] = """{"AbilityRef":"AbilityName"}""", - ["EnableAbility"] = """{"AbilityRef":"AbilityName"}""", - ["DisableAbility"] = """{"AbilityRef":"AbilityName"}""", - ["PushUnit"] = """{"Tiles":1,"BlockedDamage":0}""", - ["PullUnit"] = """{"Tiles":1,"BlockedDamage":0}""", - ["DisplaceUnit"] = """{"Tiles":1,"Direction":"North"}""", - ["TakeControl"] = """{"Duration":{"Type":"UntilEndOfTurn"}}""", - ["GrantMovementControl"] = """{"N":1}""", - ["SetFixedSacrificeReturn"] = """{"StAmount":1}""", - ["SummonToken"] = """{"TokenDefJson":"{}"}""", - ["ApplyOnEvent"] = """{"Trigger":{"$type":"OnTurnStart","Player":"Owner"},"Effects":[]}""", - }; + // ── Condition groups ───────────────────────────────────────────────────────── + + private static readonly EffectGroup[] ConditionGroups = + [ + new("Turn / Timing", ["IsOwnTurn", "IsOpponentTurn", "IsAllyTurn", "IsActivePlayerTurn"]), + new("Unit", ["HealthBelow", "HealthAbove", "DefenseIs", "HasGenus", "HasAbility", + "IsOnTileWithAffinity", "IsAdjacentTo", "WithinRangeOf", "MovementTypeIs"]), + new("Player", ["SPAtLeast", "SPAtMost", "STAtLeast", "STAtMost", + "HandSizeAtLeast", "HandSizeAtMost", "DeckSizeAtLeast", "DiscardSizeAtLeast"]), + new("Tile", ["TileAffinityMatches", "TileIsOccupied", "TileIsUnoccupied"]), + new("Battlefield", ["UnitCountOnBattlefield", "CardInZone"]), + new("Composite", ["AND", "OR", "XOR"]), + ]; + + // ── Effect type categories for rendering ───────────────────────────────────── + + private static readonly HashSet _amountBypassTypes = ["DealDamage", "DealDamageToSelf"]; + private static readonly HashSet _amountOnlyTypes = ["Heal", "ModifyDamage", "ModifySP", "ModifyST", "ModifyCardsDrawnPerTurn", "ModifySPAccumulation"]; + private static readonly HashSet _amountStatTypes = ["ModifyHealth", "ModifyDefense", "ModifyMP"]; + private static readonly HashSet _valueTypes = [ + "SetCanMove", "SetCanAttack", "SetCanDefend", "SetCanBeAttacked", + "SetCanBeBlocked", "SetCanBeObstructed", "SetCanUseAbility", "SetCanBeSacrificed", + "SetCanDrawCards", "SetAccumulatesSP", "SetCanChannelSpirit", "SetCanSacrificeSpirit", + "SetCanAscendArchSpirit", "SetCanTransitionArchSpirit", + "SetCanChannelRepentance", "SetCanChannelInstinct", "SetCanChannelRuin", + "SetCanChannelTerramorphaMono", "SetCanChannelTerramorphaDi", "SetCanChannelTerramorphaTri", + ]; + private static readonly HashSet _affinityTypes = ["SetAffinity", "SetBaseAffinity1", "SetBaseAffinity2", "PushAffinity", "PushFinalAffinity"]; + private static readonly HashSet _rawJsonTypes = ["AddAbility", "ApplyOnEvent", "SummonToken"]; + private static readonly HashSet _noFieldTypes = ["ReturnToHand", "SendToDiscard"]; + + // ── Trigger templates ──────────────────────────────────────────────────────── private static readonly Dictionary TriggerTemplates = new() { @@ -501,19 +579,16 @@ { var ab = new AbilityDraft { - TypeStr = node["Type"]?.GetValue() ?? "Active", - Name = node["Name"]?.GetValue() ?? "", - Description = node["Description"]?.GetValue() ?? "", - UsesPerTurn = node["UsesPerTurn"]?.GetValue() ?? 1, - RangeMin = node["Range"]?["Min"]?.GetValue(), - RangeMax = node["Range"]?["Max"]?.GetValue(), - RangeRequiresLos = node["Range"]?["RequiresLos"]?.GetValue() ?? false, - RangeLinearOnly = node["Range"]?["LinearOnly"]?.GetValue() ?? false, - AuraRangeMin = node["AuraRange"]?["Min"]?.GetValue(), - AuraRangeMax = node["AuraRange"]?["Max"]?.GetValue(), - CostJson = node["Cost"] is JsonNode cost ? cost.ToJsonString() : "", - ConditionsJson = node["ActivationConditions"] is JsonNode cond - ? cond.ToJsonString() : "", + TypeStr = node["Type"]?.GetValue() ?? "Active", + Name = node["Name"]?.GetValue() ?? "", + Description = node["Description"]?.GetValue() ?? "", + UsesPerTurn = node["UsesPerTurn"]?.GetValue() ?? 1, + RangeMin = node["Range"]?["Min"]?.GetValue(), + RangeMax = node["Range"]?["Max"]?.GetValue(), + RangeRequiresLos = node["Range"]?["RequiresLos"]?.GetValue() ?? false, + RangeLinearOnly = node["Range"]?["LinearOnly"]?.GetValue() ?? false, + AuraRangeMin = node["AuraRange"]?["Min"]?.GetValue(), + AuraRangeMax = node["AuraRange"]?["Max"]?.GetValue(), }; if (node["TriggerEvent"] is JsonNode trig) @@ -522,52 +597,197 @@ ab.TriggerType = trig["$type"]?.GetValue() ?? ""; } + if (node["Cost"] is JsonArray costs) + foreach (var c in costs.OfType()) + ab.Costs.Add(new CostDraft + { + TypeStr = c["Type"]?.GetValue() ?? "SpiritPoints", + Amount = c["Amount"]?.GetValue() ?? 1, + }); + + if (node["ActivationConditions"] is JsonArray aconds) + foreach (var c in aconds.OfType()) + ab.Conditions.Add(ParseCondition(c)); + if (node["Actions"] is JsonArray actions) - { foreach (var actionNode in actions.OfType()) { var target = actionNode["Target"] as JsonObject; var act = new ActionDraft { - Scope = target?["Scope"]?.GetValue() ?? "Battlefield", - TargetType = target?["Type"]?.GetValue() ?? "Unit", - Ownership = target?["Ownership"]?.GetValue() ?? "Enemy", - Count = target?["Count"]?["N"]?.GetValue() ?? 1, - All = target?["Count"]?["All"]?.GetValue() ?? false, - ConditionsJson = actionNode["Conditions"] is JsonNode ac ? ac.ToJsonString() : "", + Scope = target?["Scope"]?.GetValue() ?? "Battlefield", + TargetType = target?["Type"]?.GetValue() ?? "Unit", + Ownership = target?["Ownership"]?.GetValue() ?? "Enemy", + Count = target?["Count"]?["N"]?.GetValue() ?? 1, + All = target?["Count"]?["All"]?.GetValue() ?? false, }; - if (actionNode["Effects"] is JsonArray effects) - { - foreach (var eff in effects.OfType()) - { - var typeKey = eff["$type"]?.GetValue() ?? ""; - var fields = new JsonObject(); - foreach (var prop in eff) - if (prop.Key != "$type") - fields[prop.Key] = prop.Value?.DeepClone(); + if (actionNode["Conditions"] is JsonArray actionConds) + foreach (var c in actionConds.OfType()) + act.Conditions.Add(ParseCondition(c)); - act.Effects.Add(new EffectDraft - { - TypeKey = typeKey, - FieldsJson = fields.ToJsonString(), - }); - } - } + if (actionNode["Effects"] is JsonArray effects) + foreach (var eff in effects.OfType()) + act.Effects.Add(ParseEffect(eff)); ab.Actions.Add(act); } - } _abilities.Add(ab); } _compiledJson = json; } - catch + catch { /* invalid JSON — keep existing state */ } + } + + private static ConditionDraft ParseCondition(JsonObject c) => new() + { + TypeStr = c["$type"]?.GetValue() ?? "IsOwnTurn", + Subject = c["Subject"]?.GetValue() ?? "Self", + N = c["N"]?.GetValue() ?? 1, + Min = c["Min"]?.GetValue() ?? 1, + Max = c["Max"]?.GetValue() ?? 1, + Tag = c["Tag"]?.GetValue() ?? "", + AbilityRef = c["AbilityRef"]?.GetValue() ?? "", + Affinity = c["Affinity"]?.GetValue() ?? "Aether", + UnitType = c["UnitType"]?.GetValue() ?? "Unit", + Ownership = c["Ownership"]?.GetValue() ?? "Any", + Target = c["Target"]?.GetValue() ?? "Self", + MovementType = c["MovementType"]?.GetValue() ?? "Walk", + Comparator = c["Comparator"]?.GetValue() ?? "GreaterThanOrEqual", + Zone = c["Zone"]?.GetValue() ?? "Hand", + CardRef = c["CardRef"]?.GetValue() ?? "", + }; + + private static EffectDraft ParseEffect(JsonObject eff) + { + var typeKey = eff["$type"]?.GetValue() ?? "DealDamage"; + var d = new EffectDraft { TypeKey = typeKey }; + + // ValueExpr helper: reads {"Fixed": N} + int ReadFixed(string key, int def = 1) => + eff[key]?["Fixed"]?.GetValue() ?? eff[key]?.GetValue() ?? def; + + string ReadStr(string key, string def = "") => + eff[key]?.GetValue() ?? def; + + bool ReadBool(string key, bool def = false) => + eff[key]?.GetValue() ?? def; + + int ReadInt(string key, int def = 1) => + eff[key]?.GetValue() ?? def; + + string ReadDurType() => + eff["Duration"]?["Type"]?.GetValue() ?? "UntilEndOfTurn"; + + int ReadDurN() => + eff["Duration"]?["N"]?.GetValue() ?? 1; + + if (_amountBypassTypes.Contains(typeKey)) { - // Invalid JSON — keep existing state. + d.Amount = ReadFixed("Amount"); d.BypassDefense = ReadBool("BypassDefense"); } + else if (typeKey == "DOT") + { + d.Amount = ReadFixed("Amount"); d.BypassDefense = ReadBool("BypassDefense"); + d.DurationType = ReadDurType(); d.DurationN = ReadDurN(); + } + else if (typeKey == "HOT") + { + d.Amount = ReadFixed("Amount"); d.DurationType = ReadDurType(); d.DurationN = ReadDurN(); + } + else if (_amountStatTypes.Contains(typeKey)) + { + d.Amount = ReadFixed("Amount"); d.StatTarget = ReadStr("StatTarget", "Current"); + } + else if (_amountOnlyTypes.Contains(typeKey)) + { + d.Amount = ReadFixed("Amount"); + } + else if (typeKey is "DrawCards" or "DiscardCards") + { + d.N = ReadInt("N"); d.Player = ReadStr("Player", "Owner"); + } + else if (typeKey is "GrantAdditionalAttack" or "SearchDeck" or "RevealCards" or "GrantMovementControl") + { + d.N = ReadInt("N"); + } + else if (_valueTypes.Contains(typeKey)) + { + d.Value = ReadBool("Value", true); + } + else if (typeKey is "PushUnit" or "PullUnit") + { + d.Tiles = ReadInt("Tiles"); d.BlockedDamage = ReadInt("BlockedDamage", 0); + } + else if (typeKey == "DisplaceUnit") + { + d.Tiles = ReadInt("Tiles"); d.Direction = ReadStr("Direction", "North"); + } + else if (typeKey == "SetAttackRange") + { + d.Min = ReadInt("Min"); d.Max = ReadInt("Max", 2); + } + else if (_affinityTypes.Contains(typeKey)) + { + d.Affinity = eff["Affinity"]?["Fixed"]?.GetValue() + ?? eff["Affinity"]?.GetValue() ?? "Aether"; + } + else if (typeKey is "AddGenus" or "RemoveGenus") + { + d.Tag = ReadStr("Tag"); + } + else if (typeKey == "SetMovementType") + { + d.MovementType = ReadStr("MovementType", "Walk"); + } + else if (typeKey == "ShuffleDeck") + { + d.Player = ReadStr("Player", "Owner"); + } + else if (typeKey is "ReturnToDeck" or "PlaceOnDeck") + { + d.Position = ReadStr("Position", "Top"); + } + else if (typeKey == "ReturnToBattlefield") + { + d.Controller = ReadStr("Controller", "Owner"); + } + else if (typeKey == "ChannelCard") + { + d.PayCost = ReadBool("PayCost", true); + } + else if (typeKey == "TakeControl") + { + d.DurationType = ReadDurType(); d.DurationN = ReadDurN(); + } + else if (typeKey == "SetFixedSacrificeReturn") + { + d.StAmount = ReadInt("StAmount"); + } + else if (typeKey == "ModifyCost") + { + d.Sp = eff["Sp"]?.GetValue(); d.St = eff["St"]?.GetValue(); + } + else if (typeKey == "SetStatModMultiplier") + { + d.Stat = ReadStr("Stat", "Damage"); d.Multiplier = eff["Multiplier"]?.GetValue() ?? 1.5f; + } + else if (typeKey is "RemoveAbility" or "EnableAbility" or "DisableAbility") + { + d.AbilityRef = ReadStr("AbilityRef"); + } + else if (_rawJsonTypes.Contains(typeKey)) + { + var fields = new JsonObject(); + foreach (var prop in eff) + if (prop.Key != "$type") + fields[prop.Key] = prop.Value?.DeepClone(); + d.RawJson = fields.ToJsonString(); + } + + return d; } // ── Compile ────────────────────────────────────────────────────────────────── @@ -601,8 +821,14 @@ node["Range"] = rangeNode; } node["UsesPerTurn"] = ab.UsesPerTurn; - if (!string.IsNullOrWhiteSpace(ab.CostJson)) - try { node["Cost"] = JsonNode.Parse(ab.CostJson); } catch { } + + if (ab.Costs.Count > 0) + { + var costsArr = new JsonArray(); + foreach (var cost in ab.Costs) + costsArr.Add(new JsonObject { ["Type"] = cost.TypeStr, ["Amount"] = cost.Amount }); + node["Cost"] = costsArr; + } } else if (ab.TypeStr == "Aura") { @@ -618,8 +844,12 @@ try { node["TriggerEvent"] = JsonNode.Parse(ab.TriggerJson); } catch { } } - if (!string.IsNullOrWhiteSpace(ab.ConditionsJson)) - try { node["ActivationConditions"] = JsonNode.Parse(ab.ConditionsJson); } catch { } + if (ab.Conditions.Count > 0) + { + var ca = new JsonArray(); + foreach (var c in ab.Conditions) ca.Add(CompileCondition(c)); + node["ActivationConditions"] = ca; + } var actionsArr = new JsonArray(); foreach (var action in ab.Actions) @@ -640,29 +870,16 @@ }, }; - if (!string.IsNullOrWhiteSpace(action.ConditionsJson)) - try { actionNode["Conditions"] = JsonNode.Parse(action.ConditionsJson); } catch { } + if (action.Conditions.Count > 0) + { + var ca = new JsonArray(); + foreach (var c in action.Conditions) ca.Add(CompileCondition(c)); + actionNode["Conditions"] = ca; + } var effectsArr = new JsonArray(); foreach (var eff in action.Effects) - { - try - { - var effNode = new JsonObject { ["$type"] = eff.TypeKey }; - if (!string.IsNullOrWhiteSpace(eff.FieldsJson)) - { - var fields = JsonNode.Parse(eff.FieldsJson)?.AsObject(); - if (fields != null) - foreach (var prop in fields) - effNode[prop.Key] = prop.Value?.DeepClone(); - } - effectsArr.Add(effNode); - } - catch - { - effectsArr.Add(new JsonObject { ["$type"] = eff.TypeKey }); - } - } + effectsArr.Add(CompileEffect(eff)); actionNode["Effects"] = effectsArr; actionsArr.Add(actionNode); } @@ -677,7 +894,504 @@ catch { /* keep last valid */ } } - // ── Event helpers (extracted from Razor to avoid raw-string / brace parse errors) ── + private static JsonObject CompileCondition(ConditionDraft c) + { + var node = new JsonObject { ["$type"] = c.TypeStr }; + if (c.Subject != "Self") node["Subject"] = c.Subject; + + switch (c.TypeStr) + { + case "HealthBelow": case "HealthAbove": case "DefenseIs": + case "SPAtLeast": case "SPAtMost": case "STAtLeast": case "STAtMost": + case "HandSizeAtLeast": case "HandSizeAtMost": + case "DeckSizeAtLeast": case "DiscardSizeAtLeast": + node["N"] = c.N; break; + case "HasGenus": + node["Tag"] = c.Tag; break; + case "HasAbility": + node["AbilityRef"] = c.AbilityRef; break; + case "IsOnTileWithAffinity": + case "TileAffinityMatches": + node["Affinity"] = c.Affinity; break; + case "IsAdjacentTo": + node["UnitType"] = c.UnitType; node["Ownership"] = c.Ownership; break; + case "WithinRangeOf": + node["Target"] = c.Target; node["Min"] = c.Min; node["Max"] = c.Max; break; + case "MovementTypeIs": + node["MovementType"] = c.MovementType; break; + case "TileIsOccupied": + if (!string.IsNullOrEmpty(c.UnitType)) node["UnitType"] = c.UnitType; break; + case "IsActivePlayerTurn": + node["Ownership"] = c.Ownership; break; + case "UnitCountOnBattlefield": + node["Ownership"] = c.Ownership; node["UnitType"] = c.UnitType; + node["Comparator"] = c.Comparator; node["N"] = c.N; break; + case "CardInZone": + node["CardRef"] = c.CardRef; node["Zone"] = c.Zone; break; + } + return node; + } + + private static JsonObject CompileEffect(EffectDraft d) + { + var node = new JsonObject { ["$type"] = d.TypeKey }; + + JsonObject Fixed(int v) => new() { ["Fixed"] = v }; + JsonObject Duration() => d.DurationType == "ForNTurns" + ? new JsonObject { ["Type"] = d.DurationType, ["N"] = d.DurationN } + : new JsonObject { ["Type"] = d.DurationType }; + + if (_amountBypassTypes.Contains(d.TypeKey)) + { + node["Amount"] = Fixed(d.Amount); node["BypassDefense"] = d.BypassDefense; + } + else if (d.TypeKey == "DOT") + { + node["Amount"] = Fixed(d.Amount); node["BypassDefense"] = d.BypassDefense; + node["Duration"] = Duration(); + } + else if (d.TypeKey == "HOT") + { + node["Amount"] = Fixed(d.Amount); node["Duration"] = Duration(); + } + else if (_amountStatTypes.Contains(d.TypeKey)) + { + node["Amount"] = Fixed(d.Amount); node["StatTarget"] = d.StatTarget; + } + else if (_amountOnlyTypes.Contains(d.TypeKey)) + { + node["Amount"] = Fixed(d.Amount); + } + else if (d.TypeKey is "DrawCards" or "DiscardCards") + { + node["N"] = d.N; node["Player"] = d.Player; + } + else if (d.TypeKey is "GrantAdditionalAttack" or "SearchDeck" or "RevealCards" or "GrantMovementControl") + { + node["N"] = d.N; + } + else if (_valueTypes.Contains(d.TypeKey)) + { + node["Value"] = d.Value; + } + else if (d.TypeKey is "PushUnit" or "PullUnit") + { + node["Tiles"] = d.Tiles; + if (d.BlockedDamage > 0) node["BlockedDamage"] = d.BlockedDamage; + } + else if (d.TypeKey == "DisplaceUnit") + { + node["Tiles"] = d.Tiles; node["Direction"] = d.Direction; + } + else if (d.TypeKey == "SetAttackRange") + { + node["Min"] = d.Min; node["Max"] = d.Max; + } + else if (_affinityTypes.Contains(d.TypeKey)) + { + node["Affinity"] = new JsonObject { ["Fixed"] = d.Affinity }; + } + else if (d.TypeKey is "AddGenus" or "RemoveGenus") + { + node["Tag"] = d.Tag; + } + else if (d.TypeKey == "SetMovementType") + { + node["MovementType"] = d.MovementType; + } + else if (d.TypeKey == "ShuffleDeck") + { + node["Player"] = d.Player; + } + else if (d.TypeKey is "ReturnToDeck" or "PlaceOnDeck") + { + node["Position"] = d.Position; + } + else if (d.TypeKey == "ReturnToBattlefield") + { + node["Controller"] = d.Controller; + } + else if (d.TypeKey == "ChannelCard") + { + node["PayCost"] = d.PayCost; + } + else if (d.TypeKey == "TakeControl") + { + node["Duration"] = Duration(); + } + else if (d.TypeKey == "SetFixedSacrificeReturn") + { + node["StAmount"] = d.StAmount; + } + else if (d.TypeKey == "ModifyCost") + { + if (d.Sp.HasValue) node["Sp"] = d.Sp.Value; + if (d.St.HasValue) node["St"] = d.St.Value; + } + else if (d.TypeKey == "SetStatModMultiplier") + { + node["Stat"] = d.Stat; node["Multiplier"] = d.Multiplier; + } + else if (d.TypeKey is "RemoveAbility" or "EnableAbility" or "DisableAbility") + { + node["AbilityRef"] = d.AbilityRef; + } + else if (_rawJsonTypes.Contains(d.TypeKey)) + { + if (!string.IsNullOrWhiteSpace(d.RawJson)) + { + try + { + var fields = JsonNode.Parse(d.RawJson)?.AsObject(); + if (fields != null) + foreach (var prop in fields) + node[prop.Key] = prop.Value?.DeepClone(); + } + catch { } + } + } + // _noFieldTypes: nothing extra to add + + return node; + } + + // ── Per-type field renderers (RenderFragment) ───────────────────────────────── + + private RenderFragment RenderConditionFields(ConditionDraft c) => __builder => + { + var t = c.TypeStr; + + if (t is "HealthBelow" or "HealthAbove" or "DefenseIs" or + "SPAtLeast" or "SPAtMost" or "STAtLeast" or "STAtMost" or + "HandSizeAtLeast" or "HandSizeAtMost" or + "DeckSizeAtLeast" or "DiscardSizeAtLeast") + { + __builder.OpenElement(0, "input"); + __builder.AddAttribute(1, "type", "number"); + __builder.AddAttribute(2, "class", "form-control form-control-sm"); + __builder.AddAttribute(3, "style", "width:80px"); + __builder.AddAttribute(4, "placeholder", "N"); + __builder.AddAttribute(5, "title", "N"); + __builder.AddAttribute(6, "value", c.N); + __builder.AddAttribute(7, "onchange", EventCallback.Factory.Create( + this, e => { c.N = int.TryParse(e.Value?.ToString(), out var v) ? v : c.N; Compile(); })); + __builder.CloseElement(); + } + else if (t == "HasGenus") + { + __builder.OpenElement(0, "input"); + __builder.AddAttribute(1, "class", "form-control form-control-sm"); + __builder.AddAttribute(2, "style", "width:120px"); + __builder.AddAttribute(3, "placeholder", "Tag"); + __builder.AddAttribute(4, "value", c.Tag); + __builder.AddAttribute(5, "onchange", EventCallback.Factory.Create( + this, e => { c.Tag = e.Value?.ToString() ?? ""; Compile(); })); + __builder.CloseElement(); + } + else if (t == "HasAbility") + { + __builder.OpenElement(0, "input"); + __builder.AddAttribute(1, "class", "form-control form-control-sm"); + __builder.AddAttribute(2, "style", "width:150px"); + __builder.AddAttribute(3, "placeholder", "AbilityRef"); + __builder.AddAttribute(4, "value", c.AbilityRef); + __builder.AddAttribute(5, "onchange", EventCallback.Factory.Create( + this, e => { c.AbilityRef = e.Value?.ToString() ?? ""; Compile(); })); + __builder.CloseElement(); + } + else if (t is "IsOnTileWithAffinity" or "TileAffinityMatches") + { + BuildSelect(__builder, AffinityValues, c.Affinity, v => { c.Affinity = v; Compile(); }, 120); + } + else if (t == "IsAdjacentTo") + { + BuildSelect(__builder, UnitTypeValues, c.UnitType, v => { c.UnitType = v; Compile(); }, 100); + BuildSelect(__builder, OwnershipValues, c.Ownership, v => { c.Ownership = v; Compile(); }, 90); + } + else if (t == "WithinRangeOf") + { + BuildIntInput(__builder, c.Min, v => { c.Min = v; Compile(); }, 60, "Min"); + BuildIntInput(__builder, c.Max, v => { c.Max = v; Compile(); }, 60, "Max"); + } + else if (t == "MovementTypeIs") + { + BuildSelect(__builder, MovementTypeValues, c.MovementType, v => { c.MovementType = v; Compile(); }, 100); + } + else if (t == "TileIsOccupied") + { + BuildSelect(__builder, UnitTypeValues, c.UnitType, v => { c.UnitType = v; Compile(); }, 110); + } + else if (t == "IsActivePlayerTurn") + { + BuildSelect(__builder, OwnershipValues, c.Ownership, v => { c.Ownership = v; Compile(); }, 90); + } + else if (t == "UnitCountOnBattlefield") + { + BuildSelect(__builder, OwnershipValues, c.Ownership, v => { c.Ownership = v; Compile(); }, 90); + BuildSelect(__builder, UnitTypeValues, c.UnitType, v => { c.UnitType = v; Compile(); }, 100); + BuildSelect(__builder, ComparatorValues, c.Comparator, v => { c.Comparator = v; Compile(); }, 150); + BuildIntInput(__builder, c.N, v => { c.N = v; Compile(); }, 60, "N"); + } + else if (t == "CardInZone") + { + __builder.OpenElement(0, "input"); + __builder.AddAttribute(1, "class", "form-control form-control-sm"); + __builder.AddAttribute(2, "style", "width:130px"); + __builder.AddAttribute(3, "placeholder", "CardRef"); + __builder.AddAttribute(4, "value", c.CardRef); + __builder.AddAttribute(5, "onchange", EventCallback.Factory.Create( + this, e => { c.CardRef = e.Value?.ToString() ?? ""; Compile(); })); + __builder.CloseElement(); + BuildSelect(__builder, ZoneValues, c.Zone, v => { c.Zone = v; Compile(); }, 110); + } + // AND/OR/XOR + no-field types: no extra inputs + }; + + private RenderFragment RenderEffectFields(EffectDraft d) => __builder => + { + var t = d.TypeKey; + + if (_amountBypassTypes.Contains(t)) + { + BuildFixedAmountInput(__builder, d.Amount, v => { d.Amount = v; Compile(); }); + BuildCheckbox(__builder, "BypassDefense", d.BypassDefense, v => { d.BypassDefense = v; Compile(); }); + } + else if (t == "DOT") + { + BuildFixedAmountInput(__builder, d.Amount, v => { d.Amount = v; Compile(); }); + BuildCheckbox(__builder, "BypassDefense", d.BypassDefense, v => { d.BypassDefense = v; Compile(); }); + BuildDuration(__builder, d); + } + else if (t == "HOT") + { + BuildFixedAmountInput(__builder, d.Amount, v => { d.Amount = v; Compile(); }); + BuildDuration(__builder, d); + } + else if (_amountStatTypes.Contains(t)) + { + BuildFixedAmountInput(__builder, d.Amount, v => { d.Amount = v; Compile(); }); + BuildSelect(__builder, StatTargetValues, d.StatTarget, v => { d.StatTarget = v; Compile(); }, 100); + } + else if (_amountOnlyTypes.Contains(t)) + { + BuildFixedAmountInput(__builder, d.Amount, v => { d.Amount = v; Compile(); }); + } + else if (t is "DrawCards" or "DiscardCards") + { + BuildIntInput(__builder, d.N, v => { d.N = v; Compile(); }, 70, "N"); + BuildSelect(__builder, PlayerValues, d.Player, v => { d.Player = v; Compile(); }, 100); + } + else if (t is "GrantAdditionalAttack" or "SearchDeck" or "RevealCards" or "GrantMovementControl") + { + BuildIntInput(__builder, d.N, v => { d.N = v; Compile(); }, 70, "N"); + } + else if (_valueTypes.Contains(t)) + { + BuildCheckbox(__builder, "Value", d.Value, v => { d.Value = v; Compile(); }); + } + else if (t is "PushUnit" or "PullUnit") + { + BuildIntInput(__builder, d.Tiles, v => { d.Tiles = v; Compile(); }, 70, "Tiles"); + BuildIntInput(__builder, d.BlockedDamage, v => { d.BlockedDamage = v; Compile(); }, 90, "BlockedDmg"); + } + else if (t == "DisplaceUnit") + { + BuildIntInput(__builder, d.Tiles, v => { d.Tiles = v; Compile(); }, 70, "Tiles"); + BuildSelect(__builder, DirectionValues, d.Direction, v => { d.Direction = v; Compile(); }, 110); + } + else if (t == "SetAttackRange") + { + BuildIntInput(__builder, d.Min, v => { d.Min = v; Compile(); }, 70, "Min"); + BuildIntInput(__builder, d.Max, v => { d.Max = v; Compile(); }, 70, "Max"); + } + else if (_affinityTypes.Contains(t)) + { + BuildSelect(__builder, AffinityValues, d.Affinity, v => { d.Affinity = v; Compile(); }, 150); + } + else if (t is "AddGenus" or "RemoveGenus") + { + __builder.OpenElement(0, "input"); + __builder.AddAttribute(1, "class", "form-control form-control-sm"); + __builder.AddAttribute(2, "style", "width:130px"); + __builder.AddAttribute(3, "placeholder", "Tag"); + __builder.AddAttribute(4, "value", d.Tag); + __builder.AddAttribute(5, "onchange", EventCallback.Factory.Create( + this, e => { d.Tag = e.Value?.ToString() ?? ""; Compile(); })); + __builder.CloseElement(); + } + else if (t == "SetMovementType") + { + BuildSelect(__builder, MovementTypeValues, d.MovementType, v => { d.MovementType = v; Compile(); }, 110); + } + else if (t == "ShuffleDeck") + { + BuildSelect(__builder, PlayerValues, d.Player, v => { d.Player = v; Compile(); }, 110); + } + else if (t is "ReturnToDeck" or "PlaceOnDeck") + { + BuildSelect(__builder, PositionValues, d.Position, v => { d.Position = v; Compile(); }, 90); + } + else if (t == "ReturnToBattlefield") + { + BuildSelect(__builder, ControllerValues, d.Controller, v => { d.Controller = v; Compile(); }, 110); + } + else if (t == "ChannelCard") + { + BuildCheckbox(__builder, "Pay Cost", d.PayCost, v => { d.PayCost = v; Compile(); }); + } + else if (t == "TakeControl") + { + BuildDuration(__builder, d); + } + else if (t == "SetFixedSacrificeReturn") + { + BuildIntInput(__builder, d.StAmount, v => { d.StAmount = v; Compile(); }, 80, "ST Amount"); + } + else if (t == "ModifyCost") + { + // SP nullable + __builder.OpenElement(0, "input"); + __builder.AddAttribute(1, "type", "number"); + __builder.AddAttribute(2, "class", "form-control form-control-sm"); + __builder.AddAttribute(3, "style", "width:80px"); + __builder.AddAttribute(4, "placeholder", "SP"); + __builder.AddAttribute(5, "title", "SP delta (leave blank = no change)"); + __builder.AddAttribute(6, "value", d.Sp?.ToString() ?? ""); + __builder.AddAttribute(7, "onchange", EventCallback.Factory.Create( + this, e => { d.Sp = int.TryParse(e.Value?.ToString(), out var v) ? v : null; Compile(); })); + __builder.CloseElement(); + // ST nullable + __builder.OpenElement(8, "input"); + __builder.AddAttribute(9, "type", "number"); + __builder.AddAttribute(10, "class", "form-control form-control-sm"); + __builder.AddAttribute(11, "style", "width:80px"); + __builder.AddAttribute(12, "placeholder", "ST"); + __builder.AddAttribute(13, "title", "ST delta (leave blank = no change)"); + __builder.AddAttribute(14, "value", d.St?.ToString() ?? ""); + __builder.AddAttribute(15, "onchange", EventCallback.Factory.Create( + this, e => { d.St = int.TryParse(e.Value?.ToString(), out var v) ? v : null; Compile(); })); + __builder.CloseElement(); + } + else if (t == "SetStatModMultiplier") + { + BuildSelect(__builder, StatValues, d.Stat, v => { d.Stat = v; Compile(); }, 100); + __builder.OpenElement(0, "input"); + __builder.AddAttribute(1, "type", "number"); + __builder.AddAttribute(2, "class", "form-control form-control-sm"); + __builder.AddAttribute(3, "style", "width:90px"); + __builder.AddAttribute(4, "step", "0.1"); + __builder.AddAttribute(5, "title", "Multiplier"); + __builder.AddAttribute(6, "value", d.Multiplier.ToString("F1", System.Globalization.CultureInfo.InvariantCulture)); + __builder.AddAttribute(7, "onchange", EventCallback.Factory.Create( + this, e => { d.Multiplier = float.TryParse(e.Value?.ToString(), System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out var v) ? v : d.Multiplier; Compile(); })); + __builder.CloseElement(); + } + else if (t is "RemoveAbility" or "EnableAbility" or "DisableAbility") + { + __builder.OpenElement(0, "input"); + __builder.AddAttribute(1, "class", "form-control form-control-sm"); + __builder.AddAttribute(2, "style", "width:160px"); + __builder.AddAttribute(3, "placeholder", "AbilityRef"); + __builder.AddAttribute(4, "value", d.AbilityRef); + __builder.AddAttribute(5, "onchange", EventCallback.Factory.Create( + this, e => { d.AbilityRef = e.Value?.ToString() ?? ""; Compile(); })); + __builder.CloseElement(); + } + else if (_rawJsonTypes.Contains(t)) + { + __builder.OpenElement(0, "textarea"); + __builder.AddAttribute(1, "class", "form-control form-control-sm font-monospace"); + __builder.AddAttribute(2, "rows", "3"); + __builder.AddAttribute(3, "style", "min-width:260px"); + __builder.AddAttribute(4, "placeholder", "Fields JSON (omit $type)"); + __builder.AddContent(5, d.RawJson); + __builder.AddAttribute(6, "onchange", EventCallback.Factory.Create( + this, e => { d.RawJson = e.Value?.ToString() ?? "{}"; Compile(); })); + __builder.CloseElement(); + } + else if (_noFieldTypes.Contains(t)) + { + __builder.OpenElement(0, "span"); + __builder.AddAttribute(1, "class", "text-muted small fst-italic"); + __builder.AddContent(2, "No fields."); + __builder.CloseElement(); + } + }; + + // ── Builder helper methods (emit common UI patterns) ───────────────────────── + + private void BuildSelect(RenderTreeBuilder b, string[] options, string current, + Action onChange, int widthPx) + { + b.OpenElement(0, "select"); + b.AddAttribute(1, "class", "form-select form-select-sm"); + b.AddAttribute(2, "style", $"width:{widthPx}px"); + b.AddAttribute(3, "value", current); + b.AddAttribute(4, "onchange", EventCallback.Factory.Create( + this, e => onChange(e.Value?.ToString() ?? current))); + foreach (var opt in options) + { + b.OpenElement(5, "option"); + b.AddAttribute(6, "value", opt); + if (opt == current) b.AddAttribute(7, "selected", true); + b.AddContent(8, opt); + b.CloseElement(); + } + b.CloseElement(); + } + + private void BuildIntInput(RenderTreeBuilder b, int value, Action onChange, int widthPx, string placeholder) + { + b.OpenElement(0, "input"); + b.AddAttribute(1, "type", "number"); + b.AddAttribute(2, "class", "form-control form-control-sm"); + b.AddAttribute(3, "style", $"width:{widthPx}px"); + b.AddAttribute(4, "placeholder", placeholder); + b.AddAttribute(5, "title", placeholder); + b.AddAttribute(6, "value", value); + b.AddAttribute(7, "onchange", EventCallback.Factory.Create( + this, e => { if (int.TryParse(e.Value?.ToString(), out var v)) onChange(v); })); + b.CloseElement(); + } + + private void BuildFixedAmountInput(RenderTreeBuilder b, int value, Action onChange) + { + b.OpenElement(0, "div"); + b.AddAttribute(1, "class", "d-flex align-items-center gap-1"); + b.OpenElement(2, "label"); + b.AddAttribute(3, "class", "form-label small mb-0 text-nowrap"); + b.AddContent(4, "Amt"); + b.CloseElement(); + BuildIntInput(b, value, onChange, 70, "Fixed value"); + b.CloseElement(); + } + + private void BuildCheckbox(RenderTreeBuilder b, string label, bool value, Action onChange) + { + b.OpenElement(0, "div"); + b.AddAttribute(1, "class", "form-check d-flex align-items-center gap-1 mb-0"); + b.OpenElement(2, "input"); + b.AddAttribute(3, "type", "checkbox"); + b.AddAttribute(4, "class", "form-check-input"); + b.AddAttribute(5, "checked", value); + b.AddAttribute(6, "onchange", EventCallback.Factory.Create( + this, e => onChange(e.Value is bool bv ? bv : bool.Parse(e.Value?.ToString() ?? "false")))); + b.CloseElement(); + b.OpenElement(7, "label"); + b.AddAttribute(8, "class", "form-check-label small"); + b.AddContent(9, label); + b.CloseElement(); + b.CloseElement(); + } + + private void BuildDuration(RenderTreeBuilder b, EffectDraft d) + { + BuildSelect(b, DurationTypeValues, d.DurationType, v => { d.DurationType = v; Compile(); }, 190); + if (d.DurationType == "ForNTurns") + BuildIntInput(b, d.DurationN, v => { d.DurationN = v; Compile(); }, 60, "N"); + } + + // ── Event helpers ───────────────────────────────────────────────────────────── private void SelectTrigger(AbilityDraft ab, string triggerType) { @@ -690,13 +1404,20 @@ private void SelectEffectType(EffectDraft effect, string typeKey) { - effect.TypeKey = typeKey; - effect.FieldsJson = EffectTemplates.GetValueOrDefault(typeKey, "{}"); + // Reset all typed fields so we start fresh for the new type + effect.TypeKey = typeKey; + effect.Amount = 1; effect.N = 1; effect.Tiles = 1; effect.BlockedDamage = 0; + effect.BypassDefense = false; effect.Value = true; effect.PayCost = true; + effect.Min = 1; effect.Max = 2; effect.StAmount = 1; + effect.Player = "Owner"; effect.Controller = "Owner"; effect.StatTarget = "Current"; + effect.Direction = "North"; effect.MovementType = "Walk"; effect.Position = "Top"; + effect.Affinity = "Aether"; effect.Tag = ""; effect.AbilityRef = ""; + effect.Stat = "Damage"; effect.Multiplier = 1.5f; effect.Sp = null; effect.St = null; + effect.DurationType = "UntilEndOfTurn"; effect.DurationN = 1; + effect.RawJson = "{}"; Compile(); } - // ── Actions ────────────────────────────────────────────────────────────────── - private void AddAbility() { _abilities.Add(new AbilityDraft()); @@ -731,29 +1452,79 @@ public bool RangeRequiresLos { get; set; } = false; public bool RangeLinearOnly { get; set; } = false; public int UsesPerTurn { get; set; } = 1; - public string CostJson { get; set; } = ""; public int? AuraRangeMin { get; set; } public int? AuraRangeMax { get; set; } public string TriggerType { get; set; } = ""; public string TriggerJson { get; set; } = ""; - public string ConditionsJson { get; set; } = ""; - public List Actions { get; set; } = new(); + public List Costs { get; set; } = new(); + public List Conditions { get; set; } = new(); + public List Actions { get; set; } = new(); } private sealed class ActionDraft { - public string Scope { get; set; } = "Battlefield"; - public string TargetType { get; set; } = "Unit"; - public string Ownership { get; set; } = "Enemy"; - public int Count { get; set; } = 1; - public bool All { get; set; } - public string ConditionsJson { get; set; } = ""; - public List Effects { get; set; } = new(); + public string Scope { get; set; } = "Battlefield"; + public string TargetType { get; set; } = "Unit"; + public string Ownership { get; set; } = "Enemy"; + public int Count { get; set; } = 1; + public bool All { get; set; } + public List Conditions { get; set; } = new(); + public List Effects { get; set; } = new(); } private sealed class EffectDraft { - public string TypeKey { get; set; } = "DealDamage"; - public string FieldsJson { get; set; } = """{"Amount":{"Fixed":1},"BypassDefense":false}"""; + public string TypeKey { get; set; } = "DealDamage"; + public int Amount { get; set; } = 1; + public int N { get; set; } = 1; + public bool BypassDefense{ get; set; } = false; + public bool Value { get; set; } = true; + public bool PayCost { get; set; } = true; + public int Tiles { get; set; } = 1; + public int BlockedDamage{ get; set; } = 0; + public string Direction { get; set; } = "North"; + public int Min { get; set; } = 1; + public int Max { get; set; } = 2; + public string DurationType { get; set; } = "UntilEndOfTurn"; + public int DurationN { get; set; } = 1; + public string Player { get; set; } = "Owner"; + public string Controller { get; set; } = "Owner"; + public string StatTarget { get; set; } = "Current"; + public string MovementType { get; set; } = "Walk"; + public string Position { get; set; } = "Top"; + public string Tag { get; set; } = ""; + public string Affinity { get; set; } = "Aether"; + public string AbilityRef { get; set; } = ""; + public string Stat { get; set; } = "Damage"; + public float Multiplier { get; set; } = 1.5f; + public int StAmount { get; set; } = 1; + public int? Sp { get; set; } + public int? St { get; set; } + public string RawJson { get; set; } = "{}"; + } + + private sealed class ConditionDraft + { + public string TypeStr { get; set; } = "IsOwnTurn"; + public string Subject { get; set; } = "Self"; + public int N { get; set; } = 1; + public int Min { get; set; } = 1; + public int Max { get; set; } = 1; + public string Tag { get; set; } = ""; + public string AbilityRef { get; set; } = ""; + public string Affinity { get; set; } = "Aether"; + public string UnitType { get; set; } = "Unit"; + public string Ownership { get; set; } = "Any"; + public string Target { get; set; } = "Self"; + public string MovementType { get; set; } = "Walk"; + public string Comparator { get; set; } = "GreaterThanOrEqual"; + public string Zone { get; set; } = "Hand"; + public string CardRef { get; set; } = ""; + } + + private sealed class CostDraft + { + public string TypeStr { get; set; } = "SpiritPoints"; + public int Amount { get; set; } = 1; } } diff --git a/Server/src/SOR.Admin/Components/Pages/Chat/ChatChannelViewer.razor b/Server/src/SOR.Admin/Components/Pages/Chat/ChatChannelViewer.razor index 259a61e..9a26e0d 100644 --- a/Server/src/SOR.Admin/Components/Pages/Chat/ChatChannelViewer.razor +++ b/Server/src/SOR.Admin/Components/Pages/Chat/ChatChannelViewer.razor @@ -1,10 +1,14 @@ @page "/chat/channel/{ChannelId:guid}" @using Microsoft.EntityFrameworkCore +@using Microsoft.AspNetCore.Components.Authorization +@using Microsoft.AspNetCore.Identity @using SOR.Database.Contexts @using SOR.Database.Entities.Chat @using SOR.Database.Entities.Identity @inject ChatDbContext ChatDb @inject SorIdentityDbContext IdentityDb +@inject UserManager UserManager +@inject AuthenticationStateProvider AuthState Channel Viewer — SOR Admin @@ -36,29 +40,68 @@ else
Created @_channel.CreatedAt.ToString("yyyy-MM-dd HH:mm")
- @if (_channel.ChannelType != SOR.Database.Enums.ChatChannelType.Match) { -
-
- Post System Message +
+ +
+
+
+ Post System Message + shows as [System] +
+
+ + @if (!string.IsNullOrEmpty(_systemError)) + { +
@_systemError
+ } + @if (_systemSuccess) + { +
Message posted.
+ } +
+ +
+
+
-
- - @if (!string.IsNullOrEmpty(_systemError)) - { -
@_systemError
- } - @if (_systemSuccess) - { -
Message posted.
- } - + + +
+
+
+ Send as Admin + @if (_adminDisplayName != null) + { + @_adminDisplayName + } +
+
+ + @if (!string.IsNullOrEmpty(_adminError)) + { +
@_adminError
+ } + @if (_adminSuccess) + { +
Message sent.
+ } +
+ +
+
+
} @@ -73,25 +116,48 @@ else - - + + - + @foreach (var m in _messages) { - + - + @@ -120,21 +186,25 @@ else @code { [Parameter] public Guid ChannelId { get; set; } - private bool _loading = true; - private bool _loadingMore = false; - private bool _posting = false; + private bool _loading = true; + private bool _loadingMore = false; + private bool _posting = false; + private bool _postingAdmin = false; private bool _systemSuccess = false; + private bool _adminSuccess = false; private string _systemError = ""; + private string _adminError = ""; private string _systemMessageText = ""; + private string _adminMessageText = ""; + private string? _adminDisplayName; + private Guid? _adminAccountId; private ChatChannel? _channel; - private List _messages = new(); + private List _messages = new(); private Dictionary _senderNames = new(); private bool _hasMore = false; private const int PageSize = 50; - // Sentinel: a fixed Guid used as the "system" sender for admin-injected messages. - // All-zeros so it's obvious in the DB this was a server-posted message. private static readonly Guid SystemSenderId = Guid.Empty; protected override async Task OnInitializedAsync() @@ -149,6 +219,19 @@ else return; } + // Resolve the logged-in admin's account for attributed sends + var authState = await AuthState.GetAuthenticationStateAsync(); + var email = authState.User.Identity?.Name; + if (email != null) + { + var account = await UserManager.FindByNameAsync(email); + if (account != null) + { + _adminAccountId = account.Id; + _adminDisplayName = account.DisplayName ?? account.Email; + } + } + await LoadPageAsync(null); _loading = false; } @@ -196,7 +279,6 @@ else foreach (var kv in found) _senderNames[kv.Key] = kv.Value; - // Mark system messages if (!_senderNames.ContainsKey(SystemSenderId)) _senderNames[SystemSenderId] = "[System]"; } @@ -229,15 +311,62 @@ else ChatDb.Messages.Add(msg); await ChatDb.SaveChangesAsync(); - // Prepend to the visible list. _messages.Insert(0, msg); _senderNames[SystemSenderId] = "[System]"; - _systemMessageText = ""; _systemSuccess = true; _posting = false; } + private async Task PostAdminMessageAsync() + { + _adminError = ""; + _adminSuccess = false; + + if (_adminAccountId == null) + { + _adminError = "Could not resolve admin account."; + return; + } + if (string.IsNullOrWhiteSpace(_adminMessageText)) + { + _adminError = "Message cannot be empty."; + return; + } + if (_adminMessageText.Length > 500) + { + _adminError = "Message must be 500 characters or fewer."; + return; + } + + _postingAdmin = true; + + var msg = new ChatMessage + { + ChannelId = ChannelId, + SenderAccountId = _adminAccountId.Value, + Content = _adminMessageText.Trim(), + SentAt = DateTimeOffset.UtcNow, + }; + ChatDb.Messages.Add(msg); + await ChatDb.SaveChangesAsync(); + + if (!_senderNames.ContainsKey(_adminAccountId.Value)) + _senderNames[_adminAccountId.Value] = _adminDisplayName ?? "[Admin]"; + + _messages.Insert(0, msg); + _adminMessageText = ""; + _adminSuccess = true; + _postingAdmin = false; + } + + private async Task ToggleDeleteAsync(ChatMessage msg, bool deleted) + { + msg.IsDeleted = deleted; + ChatDb.Messages.Update(msg); + await ChatDb.SaveChangesAsync(); + } + private static string TypeBadge(SOR.Database.Enums.ChatChannelType t) => t switch { SOR.Database.Enums.ChatChannelType.Global => "bg-primary",
SentSenderSentSender ContentDeleted
@m.SentAt.ToString("MM-dd HH:mm:ss") - @(_senderNames.GetValueOrDefault(m.SenderAccountId, m.SenderAccountId.ToString()[..8])) + + @(_senderNames.GetValueOrDefault(m.SenderAccountId, m.SenderAccountId.ToString()[..8])) + @(m.IsDeleted ? "[deleted]" : m.Content) @if (m.IsDeleted) { - yes + [deleted] + } + else + { + @m.Content + } + + @if (m.IsDeleted) + { + + } + else + { + }