--- sessionId: session-260928-192341-jvqx --- # Requirements ### Overview & Goals Introduce a dedicated **Faction Mode** to `ZeroSpace.MapEditor` that allows rapid visual painting and assignment of faction ownership to star systems on the galaxy map canvas. The user can switch the active faction using hotkeys (`A`, `S`, `D`) or toolbar controls, click on any system to assign the selected faction, immediately observe the updated faction color on the map and inspector, and have changes automatically persisted to the underlying markdown files. ### Scope - **In Scope:** - Active Faction Mode state in `MapEditorPage` supporting the three core factions: - `A` → **The Eden Accord** (Green: `#10b981`) - `S` → **The Keeper Council** (Blue: `#38bdf8`) - `D` → **The Obsidian Order** (Red: `#ef4444`) - Toolbar UI controls and indicators showing the current active faction mode and its associated hotkey. - Keyboard shortcut listeners for `A`, `S`, and `D` that activate the corresponding faction mode (with guards against triggering when typing in text fields like search or coordinate entries). - Applying the active faction to star system nodes upon single click / selection. - Applying the active faction directly to currently selected node(s) when `A`, `S`, or `D` is pressed. - Immediate visual feedback on the map canvas (`MapDrawable`) and inspector panel (`OwnerLabel`) reflecting the updated owner color. - Auto-saving owner modifications back to the markdown frontmatter in `zs.docs/StarSystem/*.md` via `StarSystemDocStore`. - **Out of Scope:** - Modifying gameplay balance or data generation outside of `ZeroSpace.MapEditor` and `StarSystemDocStore`. - Adding new factions beyond the defined three in `StarSystemOwners`. ### User Stories - **As a Map Designer**, I want to press `A`, `S`, or `D` to switch the active faction mode so that I can rapidly tag multiple star systems without tedious manual dropdown selection. - **As a Map Designer**, I want to click on a star system on the map canvas and have its faction immediately update with corresponding visual color changes so that I have real-time visual confirmation of galaxy ownership boundaries. - **As a Map Designer**, I want my faction changes to automatically save to the system markdown files so that I do not lose progress or have to manually click save after every edit. ### Functional Requirements 1. **Faction Mode State & Controls:** - The toolbar must display the currently active faction mode with appropriate faction accent coloring. - Interactive buttons for each faction (`[A] Eden Accord`, `[S] Keeper Council`, `[D] Obsidian Order`) allowing mouse-based activation as well as hotkey discovery. 2. **Hotkey Handling:** - Pressing `A` (or `a`) sets active faction to `"The Eden Accord"`. - Pressing `S` (or `s`) sets active faction to `"The Keeper Council"`. - Pressing `D` (or `d`) sets active faction to `"The Obsidian Order"`. - Hotkeys must not fire when focus is in an input field (`SearchControl`, `XEntry`, `YEntry`). 3. **Click-to-Assign:** - Clicking a star system node in faction mode assigns the active faction to that node's `Doc.Owner`. - If nodes are selected, pressing `A`, `S`, or `D` immediately updates the owner of all selected nodes. 4. **UI Color Synchronization:** - The star system circle on the map canvas immediately re-renders with the faction's color: - The Eden Accord: `#10b981` - The Keeper Council: `#38bdf8` - The Obsidian Order: `#ef4444` - If the system is displayed in the inspector panel, the `OwnerLabel` and its styling update in real time. 5. **Auto-Saving:** - Modifying a node's owner marks `Doc.IsDirty = true`. - Automatically triggers `AutoSaveAsync()` to persist the `owner: ` frontmatter property in the system's markdown file. - The Save button and status text reflect save progress and confirmation ("Saving...", "Saved", "Auto-saved X system(s)"). # Technical Design ### Current Implementation - `StarSystemDocStore`: Parses YAML frontmatter from markdown files in `zs.docs/StarSystem/`. Currently, `SavePositions` only updates `x:` and `y:` lines in frontmatter. `owner:` is read during `LoadFile` but not rewritten during save. - `MapDrawable`: Renders systems using `ColorForOwner(node.Doc.Owner)`. Supports node translation gizmo, marquee selection, background image, and connection lines. - `MapEditorPage`: Handles pointer gestures (`OnPointerPressed`, `OnPointerMoved`, `OnPointerReleased`), panning, selection, inspector binding, and debounced auto-saving for position edits. - `StarSystemOwners`: Defines constant strings for `"The Eden Accord"`, `"The Keeper Council"`, and `"The Obsidian Order"` along with standard hex colors. ### Key Decisions 1. **Faction Mode Model**: - Introduce an explicit active faction mode state in `MapEditorPage` (`_activeFaction`: string or enum, defaulting to `"The Eden Accord"` or toggleable mode). - Hotkeys `A`, `S`, `D` both switch the active painting faction and immediately apply it to any actively selected system(s). 2. **Keyboard Event Interception**: - Hook window / page key down events on Windows / MAUI (`Loaded` / platform key events / MAUI `KeyboardAccelerators`). - Check `IsFocused` on `SearchControl`, `XEntry`, and `YEntry` before handling hotkeys so normal text entry is never hindered. 3. **Markdown Frontmatter Persistence**: - Update `StarSystemDocStore` save logic to update or insert the `owner: ` frontmatter entry alongside `x:` and `y:` while preserving all other frontmatter fields and body markdown intact. 4. **Immediate Color Feedback**: - Mutating `node.Doc.Owner` directly triggers `MapView.Invalidate()` and `PopulateInspector(_selected)`, ensuring zero latency in UI color updates. ### Data Models & Contracts ```csharp public enum FactionMode { None, EdenAccord, // Hotkey A - #10b981 KeeperCouncil, // Hotkey S - #38bdf8 ObsidianOrder // Hotkey D - #ef4444 } ``` Frontmatter update in `StarSystemDocStore`: ```yaml --- category: StarSystem systemCategory: Side System owner: The Keeper Council occupationBuff: +50 Starting Hexite systemMastery: "[[Unit Health and Shields]]" x: 450.2 y: 310.8 --- ``` ### Components & File Structure - `ZeroSpace.MapEditor/Services/StarSystemDocStore.cs`: - Enhance `SaveDoc` / `SaveDocs` / `SavePosition` to serialize `owner` to the frontmatter. - `ZeroSpace.MapEditor/Views/MapEditorPage.xaml`: - Add Faction Mode UI toolbar buttons/indicators (`Eden Accord [A]`, `Keeper Council [S]`, `Obsidian Order [D]`) with visual active highlights and color badges. - `ZeroSpace.MapEditor/Views/MapEditorPage.xaml.cs`: - Manage active faction mode state and toolbar button styling. - Implement key press listeners for `A`, `S`, `D`. - Handle click-to-assign on star system hit test. - Refresh inspector and canvas colors. - Integrate with `AutoSaveAsync()`. ### Architecture Diagram ```mermaid graph TD UserKeyboard["User Press: A / S / D"] --> KeyHandler["MapEditorPage Key Handler"] UserClick["User Click on Star System Node"] --> PointerHandler["OnPointerPressed / Click Handler"] ToolbarButton["User Click Toolbar Faction Button"] --> FactionSelector["SetActiveFactionMode(...)"] KeyHandler --> FactionSelector KeyHandler --> ApplyFaction["Apply Faction to Selected Node(s)"] FactionSelector --> UpdateToolbarUI["Update Toolbar Mode Indicators & Badges"] PointerHandler --> ApplyFaction ApplyFaction --> UpdateDoc["Update Doc.Owner & Set Doc.IsDirty = true"] UpdateDoc --> RedrawMap["MapView.Invalidate() (MapDrawable.ColorForOwner)"] UpdateDoc --> UpdateInspector["PopulateInspector(node) (OwnerLabel Color)"] UpdateDoc --> AutoSave["AutoSaveAsync()"] AutoSave --> DocStore["StarSystemDocStore.SaveDocs(...)"] DocStore --> MarkdownFiles["Persist 'owner: ...' to zs.docs/StarSystem/*.md"] ``` ### Risks & Mitigations - **Risk:** Typing 'a', 's', or 'd' inside the search bar or coordinate entries could trigger faction mode changes. - *Mitigation:* Ensure key events check focus status on all input entries (`SearchControl.IsFocused`, `XEntry.IsFocused`, `YEntry.IsFocused`) before processing hotkeys. - **Risk:** Modifying frontmatter could accidentally reorder or corrupt markdown content. - *Mitigation:* Use regex/line-based frontmatter replacement in `StarSystemDocStore` matching existing `SavePosition` patterns to preserve line endings, spacing, and other YAML metadata. # Testing ### Validation Approach Verify faction mode switching, hotkey interactions, click-to-assign workflows, real-time UI color updating, and frontmatter persistence across unit tests and interactive workflows. ### Key Scenarios 1. **Hotkey Faction Switching:** - Press `A`: Faction mode switches to **The Eden Accord**; toolbar highlights the Accord button with green accent (`#10b981`). - Press `S`: Faction mode switches to **The Keeper Council**; toolbar highlights the Keeper button with blue accent (`#38bdf8`). - Press `D`: Faction mode switches to **The Obsidian Order**; toolbar highlights the Obsidian button with red accent (`#ef4444`). 2. **Click-to-Assign System Faction:** - Click an unassigned or Eden system while Keeper Council mode (`S`) is active. - Verify node color on map canvas immediately turns blue (`#38bdf8`). - Verify Inspector `OwnerLabel` updates to "The Keeper Council" with matching color. 3. **Multi-Selection Assignment:** - Marquee-select 3 systems and press `D`. - Verify all 3 systems immediately turn red (`#ef4444`). 4. **Auto-Saving to Markdown:** - Change a system's faction; verify the Save button transitions to "Saving..." and then "Saved" / "Auto-saved 1 system". - Inspect the `.md` file on disk in `zs.docs/StarSystem/` and confirm `owner: ...` has been updated with valid YAML frontmatter formatting. 5. **Text Input Protection:** - Focus `SearchControl` and type "Ashes"; verify 'A' and 's' are entered into the search box and do NOT trigger faction changes. ### Edge Cases - File with missing or malformed `owner` frontmatter key is gracefully updated and written. - Multiple rapid hotkey presses or clicks debounce auto-save properly without race conditions. - System with read-only attributes or special characters in name handles saving cleanly. # Delivery Steps ### ✓ Step 1: Update StarSystemDocStore to support owner serialization and dirty state tracking StarSystemDocStore supports persisting the `owner` property to markdown frontmatter, and StarSystemDoc dirty state tracks faction edits. - Extend `StarSystemDocStore` methods (`SaveDoc`, `SaveDocs`, or `SavePosition`) to update or add the `owner:` frontmatter key when writing changes to `.md` files. - Preserve all existing frontmatter keys, comments, and markdown body byte-for-byte when updating `owner`, `x`, and `y`. - Ensure `doc.IsDirty` is set to `true` whenever `doc.Owner` is modified. - Verify unit doc save logic parses and preserves the standard faction names (`The Eden Accord`, `The Keeper Council`, `The Obsidian Order`). ### ✓ Step 2: Add Faction Mode UI toolbar controls and visual indicators The MapEditorPage toolbar displays visual buttons and indicators for the active faction mode with distinct faction colors. - Add faction mode selection and indicator controls to the top toolbar in `MapEditorPage.xaml` (e.g., dedicated buttons/badges for Accord `[A]`, Keeper `[S]`, and Obsidian `[D]`, plus a mode toggle or active indicator). - Style the faction buttons/indicators with their corresponding colors: Green (`#10b981`) for The Eden Accord, Blue (`#38bdf8`) for The Keeper Council, and Red (`#ef4444`) for The Obsidian Order. - Update `OwnerLabel` (and optional badge) in the inspector panel to display the owner name with faction color coding. - Provide clear visual feedback indicating which faction mode is currently active. ### ✓ Step 3: Implement hotkeys, click-to-assign logic, and auto-save integration Pressing A, S, or D switches the active faction mode, and clicking any star system node immediately applies the faction and triggers auto-save. - Add keyboard event handling to `MapEditorPage` for hotkeys `A`, `S`, and `D` (switching active faction to Eden Accord, Keeper Council, and Obsidian Order respectively), ignoring hotkeys when text fields (`SearchControl`, `XEntry`, `YEntry`) are focused. - If one or more nodes are currently selected when pressing `A`, `S`, or `D`, apply the faction to the selection immediately. - Update `OnPointerPressed` / `OnPointerReleased` to apply the active faction to the clicked `MapNode` when in faction mode. - Invalidate the `MapView` canvas so the node's fill color updates immediately via `MapDrawable.ColorForOwner`. - Trigger `AutoSaveAsync()` (or debounced `ScheduleAutoSave()`) whenever a system's owner changes, keeping the Save button status and feedback message in sync.