diff --git a/.flow.toml b/.flow.toml new file mode 100644 index 00000000..6d948cc7 --- /dev/null +++ b/.flow.toml @@ -0,0 +1,55 @@ +# Flow modes for this repo: only what a session wouldn't otherwise know. +# Public repo: no secrets, no local paths. Check with `flow lint .flow.toml`. +private = false + +[modes.implement] +rules = [ + "CRLF repo: run git with -c core.autocrlf=true -c core.fileMode=false.", + "Every feature is a release slice (release-slices.json). Add new features behind a module and __SLICE_*__ flag, not in core.", + "Core never imports a slice's folder (src/hexflower, src/space, ...): reach it through module hooks.", + "Play mode never writes map data (src/workMode.ts ACTION_POLICY, modeGate). Classify every new action; workModeCoverage fails otherwise.", + "A new setting goes in both getSettingDefinitions() and display(). Modals extend DuckmageModal. Per-hex loops read layout first, then write.", +] + +[modes.verify] +description = "running this plugin's gates and hidden smoke suite on a change" +exit = "tsc, eslint, tests, the full build, test:slices, check:release and the smoke suite all pass." +rules = [ + "Gate: npm run build, npm run lint, npm test, npm run build:full, npm run test:slices, npm run check:release. Run heavy steps through jobq.", + "Behaviour: npm run smoke -- --slices all --jobs 2 --stamp drives a hidden Obsidian through 9 vault setups; npm run smoke:mobile adds touch. npm run premerge runs the merge gate.", + "Add a smoke check (dev/smoke/lib) for any new user flow. Type checks and unit tests alone don't count for UI work.", + "Performance claims need a benchmark on a large map, not a headless impression.", +] + +[modes.qa] +rules = [ + "Fresh-eyes rounds use the sandboxes in dev/smoke; they launch Obsidian hidden.", + "Check each release set as a built bundle: HEXMAKER_SLICES= node esbuild.config.mjs production, then npm run check:release -- --slices .", +] + +[modes.ship] +purpose = "Release to the Obsidian community store." +exit = "The GitHub release exists, and the Obsidian review on it passed." +rules = [ + "A push to master auto-releases. Never push or release without the owner's explicit approval for that change.", + "Follow .claude/commands/release.md. One bump per release, as its own tip commit. The owner decides what's in the release through released flags in release-slices.json.", + "Master releases are gated on the Obsidian review in CI; if it fails, follow .github/OBSIDIAN_REVIEW.md.", + "Before a release, run check:release: a slice built off must leave no trace in main.js or the release README.", +] + +[modes.coordinate] +rules = [ + "Public issues and PRs: never post, comment, close or label. Give the owner bullet points of what's relevant; the owner writes the reply.", +] + +[modes.import-tables] +description = "importing random tables into this plugin's table format from an outside source" +purpose = "Get outside tables into the vault as readable random tables." +exit = "The tables parse and roll in the plugin." +skills = ["hex-table-import"] + +[modes.docs-sync] +description = "bringing the plugin's bundled help and README in line with its tools" +purpose = "Keep the bundled help and README true to what's built." +exit = "Help and README match the commands and tools, with slice markers kept." +rules = ["Run /update-help. Text about an unreleased slice stays inside its slice markers. readmeCommands fails if README and commands differ."] diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 3f918c7c..d1fb9a44 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,28 +1,54 @@ -name: CI - -on: - push: - branches: - - "**" - pull_request: - -jobs: - test: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - - - name: Use Node.js - uses: actions/setup-node@v4 - with: - node-version: "lts/*" - cache: "npm" - - - name: Install dependencies - run: npm ci - - - name: Build & type-check - run: npm run build - - - name: Run tests - run: npm test +name: CI + +on: + push: + branches: + - "**" + pull_request: + +jobs: + test: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - name: Use Node.js + uses: actions/setup-node@v4 + with: + node-version: "lts/*" + cache: "npm" + + - name: Install dependencies + run: npm ci + + - name: Build & type-check + run: npm run build + + - name: Run tests + run: npm test + + # Feature switches (release-slices.json): the contract suite with each + # slice built off, the release set and none, then check:release for the + # same set (dev/release/test-slices.mjs). One set per job; a new slice adds + # its `off:` here (tests/releaseSlices.test.ts checks the list). + slices: + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + set: ["off:worldmaps", "off:space", "off:genpage", "off:manual", "off:play", "off:hexflower", "off:packs", "released", "none"] + name: slices (${{ matrix.set }}) + steps: + - uses: actions/checkout@v4 + + - name: Use Node.js + uses: actions/setup-node@v4 + with: + node-version: "lts/*" + cache: "npm" + + - name: Install dependencies + run: npm ci + + - name: Contract suite and check:release (${{ matrix.set }}) + run: node dev/release/test-slices.mjs --only "${{ matrix.set }}" --check-release diff --git a/.gitignore b/.gitignore index 8b01dc09..c09624fb 100644 --- a/.gitignore +++ b/.gitignore @@ -8,3 +8,18 @@ data.json .claude/worktrees/ .claude/worktrees/* .integration-out/ +dev/overworld-preview.js +dev/smoke/last-run.json +dev/smoke/last-pass.json +dev/smoke/last-run.*.json +dev/smoke/last-pass.*.json +dist/ +# Owner worksheet pages and their answers (local, not part of the plugin). +dev/*-calls.html +dev/.submissions/ +dev/icon-candidates.html +dev/inputs-tags.html +# Worldographer's own files for the bw-* icon set (not used by the plugin; +# in bw-icons.zip, see icons/CREDITS.md). Removed from the repo 2026-10-17. +icons/*.wxx +icons/*.properties diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index d3f9ab73..b6ab24e8 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -1,261 +1,283 @@ -# Architecture Overview — Duckmage Plugin +# Architecture Overview — Hexmap World Creator (Hexmaker) -A tabletop RPG world-building plugin for Obsidian. Three interconnected views (hex map, hex table, random tables/workflows) operate on a shared vault of Markdown notes. +A tabletop RPG world-building plugin for Obsidian (plugin id `hexmaker`; the repo, view types, CSS classes and protocol actions keep the older `duckmage` name). Its views — hex map, hex table, random tables/workflows, generator page, palette editor, setup wizard — work on one vault of plain Markdown notes. Map notes hold the map data; hex notes hold prose and links. --- -## Views - -### HexMapView -The primary interactive surface. Renders a hex grid where every cell corresponds to a `{hexFolder}/{region}/{x}_{y}.md` note on disk. Multiple regions are supported; the active region is tracked as `activeRegionName`. +## Layers -**DOM structure:** ``` -.duckmage-hex-map-container - ├── .duckmage-hex-map-clip ← overflow:hidden clipping layer - │ └── .duckmage-hex-map-viewport ← transform target (pan + zoom) - │ └── .duckmage-hex × N ← individual hex cells - └── .duckmage-hex-map-controls ← pointer-events:none overlay - ├── expand buttons (+) - └── drawing toolbar +HexmakerPlugin (thin shell: fields, onload, one-line delegations) + ├── src/plugin/ commands · protocolHandlers · vaultEvents · startup · settingsPersistence + ├── src/services/ MapsService · PaletteQueries · HexNotesService · TemplatesService · TerrainTablesService + ├── stores MapStore (maps/) · PaletteStore (palettes/) · TableStore + TableNotes (random-tables/) + │ · module stores (BiomeStore, WorldTypeStore, FlowerStore: NoteFolderStore subclasses) + │ · HexPropsSync (maps/) · PathsService + RoutePins (paths/) · UndoBook + ├── views HexMapView · HexTableView · RandomTableView · GeneratorView · PaletteEditorView · SetupWizardView + └── ports.ts bindPorts(): the module-level setters plain modules use to reach plugin state ``` -The clip/controls separation ensures toolbar buttons are never hidden by the viewport's CSS transform. - -**Drawing tools** — each follows the same pattern: - -| Tool | drawingMode | Opens | Section written | -|------|-------------|-------|-----------------| -| Road | `"road"` | (direct click) | `settings.roadChains` | -| River | `"river"` | (direct click) | `settings.riverChains` | -| Terrain | `"terrain"` | `TerrainPickerModal` | frontmatter `terrain:` | -| Icon | `"icon"` | `IconPickerModal` | frontmatter `icon:` | -| Link Table | `"tableLink"` | `TablePickerModal` | `### Encounters Table` | -| Factions | `"factionLink"` | `FactionPickerModal` | `### Factions` | - -**Tool lifecycle** (standard pattern): -1. Button click → `handle*Button()` opens picker modal -2. Picker callback sets `drawingMode` + paint target, calls `updateToolbarButtonStates()` -3. Hex left-click → `onHex*Click(x, y)` -4. Right-click (on any hex) → `exit*Mode()` → `drawingMode = null` -5. `updateToolbarButtonStates()` syncs active CSS and button labels - -**Write strategies:** -- Terrain/icon: synchronous DOM patch + coalescing async write queue (`scheduleTerrainWrite` / `scheduleIconWrite`). Only the latest value per hex is flushed, preventing stale writes. -- Link tools: purely async, no DOM patch needed (badge added directly after `await addLinkToSection`). -- Roads/rivers: written to `plugin.settings` and persisted via `saveSettings()`. - -**Visual feedback for link tools:** -- Persistent: accent-coloured outline + emoji badge (📋 table, ⚔️ faction) -- Transient: `.duckmage-hex-blip` — a CSS-animated circle that expands and fades, then self-removes on `animationend` +- **Start-up** (`HexmakerPlugin.onload`): `loadSettings` (settings-phase migrations on the raw data, then defaults) → table notes, route pins → `bindPorts` → `registerVaultEvents` → `onLayoutReady(startOnLayoutReady)` (icons, stores — held for the setup wizard on a fresh install, F19 — note-format upgrades, the one upgrade notice and upgrade note) → views, commands, settings tab, roller block, protocol handlers. +- **Vault events** (`src/plugin/vaultEvents.ts`): one handler per event for the whole plugin; each step is isolated (a throw is logged, the next runs) and the order is fixed and documented in the file header (e.g. delete: hex-note properties → icons → map store → palette store → module stores → callout memory → workflow steps). +- **Settings persistence** (`src/plugin/settingsPersistence.ts`): one read, no `await` between swapping in the settings and `mapStore.adoptAll()` (incident 2026-10-10); saves strip note-held paths (`withoutNotePaths`), skip writes that change nothing, recognise our own write echoed back by `onExternalSettingsChange`, and keep the `dataFormat` stamp. +- **Controllers and hosts.** Code split out of a big view or modal is a controller taking a narrow `*Host` interface (precedent: `PathToolHost` in `hex-map/pathTool.ts`). `HexMapView.viewFacade()` returns what most map controllers read (functions, read live); each host is `{ ...view, …extras }`. The hex editor's sections share `hex-map/editor/host.ts` (`EditorHexHost`, `EditorWriteHost`); the generator page's sections get one `GeneratorPageCtx` (`modules/gen-page/sections/ctx.ts`), and its selections live in `modules/gen-page/generatorPageState.ts` (survive re-render and reopen). --- -### HexTableView -A live spreadsheet of all hex notes found in `hexFolder`. Updates on vault `modify` events (300 ms debounce per file). - -**Columns:** Hex (coords + ◎ jump button), Terrain (colour swatch), then one column per section key from `COLUMNS`. - -Current columns in order: Description, Landmark, Towns, Dungeons, Features, Quests, Factions, Enc. Table, Hidden, Secret, Weather, Hooks & Rumors. - -The **Enc. Table** cell displays the basename of the linked table file (not the full path). Clicking a populated cell opens `RandomTableView` at that file via `openTable()`. - -**Filters (toolbar):** -- X / Y numeric range inputs -- Region selector (scoped to one region subfolder) -- Terrain multi-select modal — left-click to include, right-click to exclude (strikethrough + red) -- Has Town / Has Dungeon / Has Feature / Has Quest / Has Faction checkboxes -- Sort priority (X→Y or Y→X) and direction (Asc / Desc) +## Views -Filter state is stored as `dataset` attributes on each `` (`data-terrain`, `data-has-town`, etc.) and read by `applyFilters()` — no file I/O on filter change. +### HexMapView (`src/hex-map/HexMapView.ts` + `src/hex-map/view/`) +The interactive map. DOM: `contentEl` (`.duckmage-hex-map-container`) → `.duckmage-hex-map-clip` (overflow hidden) → `.duckmage-hex-map-viewport` (pan/zoom transform; zoom is baked into the grid's font size) → hexes and em-placed layers; `.duckmage-hex-map-controls` is a `pointer-events: none` overlay for the toolbar and edge buttons, so the transform never clips them. -**Jump button (◎):** Calls `HexMapView.centerOnHex(x, y)` on the first open map leaf, panning the viewport to that hex. +| Controller (`view/`) | Job | +|---|---| +| `gridRenderer` | full re-render (`renderGrid`), layers placed from measured geometry, empty state | +| `hexPainter` | terrain / icon / GM icon / biome / region-hex brushes, table and submap link clicks | +| `hexWrites` + `coalescingWriteQueue` | paint writes, one queue per field, only the latest value per hex lands, retried with backoff | +| `mapInput` | hover, wheel, drag-pan, paint strokes, gap clicks | +| `mapViewport` | pan/zoom, zoom bake, fit/centre, each map's last viewport | +| `toolState` + `mapToolbar` | the drawing mode (`DrawingMode` in `hex-map/toolMode.ts`: path, terrain, icon, tableLink, submapLink, factionLink, regionLink, swap, placeToken, biome) and its buttons / mode bar | +| `mapNavigation` | Back/Forward/Up, breadcrumb, neighbours, walking into new land, child maps | +| `mapShell` | shortcuts, top bar, side panels, workspace/store listeners | +| `pathOverlay`, `areaOverlay` + `areaShapes`, `gridLabels`, `neighbourShadow` | overlays (read-then-write) | +| `backgroundCalibration` + `calibrationDrag` | background image layer and grid calibration | +| `undoController` + `undoGroup` | strokes → `plugin.undoBook` (one queue per map per work mode); `grid` entries (a map grown from code, `hex-map/gridChange.ts`) shrink back only while their band is blank, then `gridResize` keeps the view still | +| `tokenLayer`, `hexContextMenu`, `hexSwap`, `gridEdgeButtons`, `workModeButton` | tokens and party travel, right-click menus, swap tool, +/− edges, Play/Build/God | ---- +Public: `centerOnHex(x, y)`, `activeMapName`, `renderGrid(...)`. The path tool is `hex-map/pathTool.ts`. -### RandomTableView -A two-column browser with two modes toggled by tab buttons: **Tables** and **Workflows**. +### HexEditorModal (`src/hex-map/HexEditorModal.ts` + `src/hex-map/editor/`) +Right-click per-hex editor: `TerrainIconSections` (terrain, icon override, GM icons — written to the map store), `LinkSection` (Towns, Dungeons, Quests, Factions, Features), `TextSection` (Description, Landmark, … and the note's own sections), `TableSections` (encounter / rolled tables: hex > area > terrain), `NeighbourFlower`, `MapsStrip`. All section data is read once (`getAllSectionData`) before the DOM is built. -**Tables mode:** -- Left: folder tree (collapsible) + search filter + new-table creator at the bottom. -- Right: selected table — entries with die-range (`dN` column) and percentage odds, die-size selector, Roll button, copy-result textarea, recent roll history. Edit button opens `RandomTableEditorModal`. -- Right-click a table in the tree → context menu with "Delete table". +### HexTableView (`src/hex-table/`) +Spreadsheet of the hex notes: Hex (coords + ◎ jump), Terrain, then Description, Landmark, Towns, Dungeons, Features, Quests, Factions, Enc. Table, Hidden, Secret, Weather, Hooks & Rumors. Filters (X/Y range, map, terrain include/exclude, has-link checkboxes) work on `dataset` attributes without file I/O. Live updates on `modify` (300 ms debounce per file). -**Workflows mode:** -- Left: folder tree of workflow files + new-workflow creator. New workflows created with "New workflow with this table" (from a table detail pane) pre-populate the first step including auto-derived label. -- Right: selected workflow — each step shown as a clickable link (opens that table in Tables mode) with `×N` roll count, "Roll workflow" button, Edit button opens `WorkflowEditorModal`. -- Right-click a workflow in the tree → context menu with "Delete workflow". +### RandomTableView (`src/random-tables/`) +Tables and Workflows tabs: folder tree, roll, edit (`RandomTableEditorModal`), workflow steps (`WorkflowEditorModal`, `WorkflowWizardModal`). `openTable(filePath)` is the public entry, used by the hex table, the hex editor, workflow step links and the `obsidian://duckmage-roll` handler. -**Public API:** -- `openTable(filePath)` — switches to Tables mode, expands all ancestor folders of the target file so it is visible in the tree, refreshes the list, and loads the specified table. Called from `HexTableView` (Enc. Table cell), `HexEditorModal`, workflow step links, and the `obsidian://duckmage-roll` protocol handler. +### Other views +`GeneratorView` (the generator page, the genpage slice: `modules/gen-page/GeneratorPanel.ts` + `sections/`, registered through `views[]` and opened only through `genPage()`), `PaletteEditorView` (`palettes/`), `SetupWizardView` (first run). Views are found and opened through `src/workspace/views.ts`. --- ## Modals -| Modal | Purpose | -|-------|---------| -| `HexEditorModal` | Right-click per-hex editor — terrain, all link sections, all text sections | -| `TerrainPickerModal` | Full terrain palette picker (toolbar terrain button) | -| `TerrainEntryEditorModal` | Edit a single palette entry — name, color, icon, icon color tint | -| `IconPickerModal` | Full icon picker with image previews (toolbar icon button) | -| `RegionModal` | Switch active region; create, rename, delete regions | -| `FileLinkSuggestModal` | Fuzzy-search file picker scoped to any folder | -| `RandomTableModal` | Inline roll modal — used from HexEditorModal 🎲 buttons | -| `RandomTableEditorModal` | Edit table entries (result + weight), linked folder, description, filter flags | -| `WorkflowEditorModal` | Edit workflow definition — steps, template, results folder. Draggable by title bar. Auto-saves on close. | -| `WorkflowWizardModal` | Execute a workflow — roll/pick each step, view filled template, save result as a vault note | +Every modal extends `HexmakerModal` (`src/HexmakerModal.ts`): drag by title bar (`makeDraggable`), placement (`place(id, el)`, `section(layer)` over `ui/placement.ts` + `ui/disclosure.ts`), icon search and pack tabs (`addIconFilter`). The one exception is `FileLinkSuggestModal` (a `SuggestModal`). Main ones: `HexEditorModal`, `MapModal` (maps tree and map properties), `TerrainPickerModal`, `IconPickerModal`, `TerrainEntryEditorModal`, `PathPickerModal` / `PathTypeEditorModal`, `AreaNotePickerModal` (factions and regions), `RegionNavigateModal`, `SubmapPickerModal`, `LocationsModal`, `TokenModal`, `NewMapSetupModal`, `MapExportModal`, `PackExportModal` / `PackImportModal`, `RandomTableModal`, `RandomTableEditorModal`, `WorkflowEditorModal`, `WorkflowWizardModal`, plus World maps' modals in `src/overworld/`. --- ## Data model -### Hex notes -Path: `{hexFolder}/{region}/{x}_{y}.md` +### Map notes — the source of truth for map data +Path `{hexFolder}/{map}/_{map}.md`, one per map, owned by `MapStore` (`src/maps/MapStore.ts`), parsed and written by `src/maps/mapNote.ts` (pure; its header has the full format history 1→6). -```yaml +```markdown --- -terrain: forest -icon: custom-castle.png # optional override +hexmaker-map: 6 +palette: Default +cols: 38 +rows: 25 +parent: "[[_the-north]]" +parent-hex: 3, 4 --- +# The Coast +> [!info]- How to edit this note +## Summary ← derived, regenerated on every write +## Hexes +| Hex | Name | Terrain | Icon | GM icons | Area | Locations | Locked | +| 3_4 | Glass Wastes | dunes | | | [[Basin]] | [[_saltmere]] | | +## Paths +| Path | Type | Route | Notes | +| King's Road | Road | 3, 4 → 9, 4 · 1 fork · 9 hexes | Paved. | +## Path routes +| Path | Branch | Anchors | +| King's Road | main | 3, 4 → 9, 4 | +``` -### Towns -[[My Town]] - -### Dungeons - -### Features - -### Quests +- Every per-hex map field (name, terrain, icon override, GM icons, area/region, region map, locations, locked) lives here. Read it through `plugin.mapStore` or the `src/frontmatter.ts` getters (→ `src/maps/hexData.ts`), never from hex-note frontmatter, and never gate it on a hex note existing. +- The map's settings (palette, size, parent, layer toggles, work `mode:`, seed, display name…) are frontmatter, one plain key each. Only per-session state (viewport) stays in `data.json`. +- Reading is forgiving (block YAML, `3, 4` for `3_4`, column order, yes/x/✓…); rows that can't be read stay as written and are listed in a warning callout; text and keys the plugin doesn't own survive rewrites. Older formats are read forever and rewritten on the next write after a backup. -### Factions -[[Iron Brotherhood]] +### Hex notes +Path `{hexFolder}/{map}/{x}_{y}.md`, made only when a hex first gets prose or links (from `src/defaultHexTemplate.md` or the user's template in `templatesFolder`; placeholders `{{x}}`, `{{y}}`, `{{title}}`). -### Encounters Table -[[forest-encounters]] +```markdown +--- +map: "[[_coast]]" +terrain: forest ← mirrored properties (MG4), for Dataview / Bases / search +area: Basin +icon: castle.png +name: Glass Wastes +--- +# Hex 3, 4 +> [!hexmaker] Map data +> Filled in from the map by Hexmaker. ### Description -Rolling hills... - ### Landmark ### Hidden ### Secret ### Weather ### Hooks & Rumors +### Encounters Table +### Towns +### Dungeons +### Quests +### Factions +### Features ``` -- `terrain` and `icon` live in YAML frontmatter (read via metadata cache, written via raw-text patching in `frontmatter.ts`). -- All other data lives under `###` headings (read/written via `sections.ts`). +- The properties are copies: `src/maps/hexPropsSync.ts` writes them on every map change (only into notes that exist) and sends a hand edit back to the map; on conflict the map wins (`hexProps.ts`). `hexNoteProperties: false` turns them off. +- The Map data callout is kept by `src/hexMapData.ts` / `maps/calloutSync.ts`; hand edits to its lines go to the map. +- Link sections (`LINK_SECTIONS`: Towns, Dungeons, Features, Quests, Factions, Encounters Table) hold wiki-links (`sections.ts`: `addLinkToSection`, `getLinksInSection`, `getAllSectionData`); text sections (`TEXT_SECTIONS` Description, Landmark, Hidden, Secret; `ROLLED_TEXT_SECTIONS` Weather, Hooks & Rumors) hold free text. -### Link sections (`LINK_SECTIONS`) -``` -"Towns" | "Dungeons" | "Features" | "Quests" | "Factions" | "Encounters Table" -``` -Each has a corresponding folder setting. The heading key used in files is the section name lowercased. +### Palettes and path types — notes +One note per palette in `palettesFolder` (default `{worldFolder}/palettes`; frontmatter `hexmaker-palette`, basename = name). A terrain table (`| Terrain | Color | Icon | Icon color | Category | Type | Impassable |`, colours as inline code) and a `## Path types` table (`| Path | Color | Width | Style | Routing | Avoid impassable | Auto-route |`). `PaletteStore` syncs notes ⇄ `settings.terrainPalettes` (working copy + data.json cache); code edits palettes in memory and calls `saveSettings()`. Presets: `src/palettes/presets.ts` and each module's `presets.ts`; `presetUpdates.ts` offers new preset content once. -### Text sections (`TEXT_SECTIONS`) -``` -description | landmark | hidden | secret -``` -Weather and Hooks & Rumors are also free-text sections under `###` headings but are not part of the `TEXT_SECTIONS` constant. +### Hex fields note +`{worldFolder}/Hex fields.md` (`hexmaker-fields: 1`): `## Fields` (`| Field | Type | Default | Table | Formula | Choices |`) and `## Place influences` (`| Place type | Field | Here | Nearby | Radius |`). The only copy of the declarations (`FieldStore`); the values are `## Hexes` columns of each map note named like the field, plus a `Field rolls` column (each rolled value before places changed it). A hex is filled when it gets terrain (`maps/fieldFill.ts`, inside `MapStore.set` / `setMany`, so it shares that write's work-mode gate and undo). -### Roads & rivers -Stored as `string[][]` in `settings.roadChains` / `settings.riverChains`. Each chain is an ordered array of `"x_y"` keys. Rendered as SVG polylines connecting adjacent hexes. +### Other notes +- **Areas:** faction and region notes (`factionsFolder`, `regionsFolder`), styled by `src/notes/areaStyle.ts`, with a Map data callout (`regionMapData.ts`). +- **Biomes and pools** (World maps, `BiomeStore`), **world types** (Space, `WorldTypeStore`), **hex flowers** (`FlowerStore`): folders of notes that are the only copy of their data, on `src/stores/NoteFolderStore.ts`. +- **Generators:** generator notes under the generators folder (`worldgen/generators.ts`); generator saves (`worldgen/saveFormat.ts`, listed and written by `modules/gen-page/saves.ts`). +- **Tokens:** token notes' frontmatter (`src/tokens/tokenNotes.ts`). **Play log:** one dated note per day in `logFolder`. ### Random tables -Markdown files with: -```yaml ---- -dice: 100 ---- -| Result | Weight | -|--------|--------| -| Dragons | 1 | -| Goblins | 5 | +```markdown +| d20 | Result | Weight | +|-------|---------|--------| +| 1–16 | crabmen | 4 | +| 17–20 | mage | 1 | +| — | kraken | 0 | ``` -Parsed by `randomTable.ts` into `{ dice, entries: [{result, weight}] }`. Terrain tables generated at `{tablesFolder}/terrain/{name} - description.md` and `…encounters.md`. +Weights are core; the roll column shows the ranges, and valid stored ranges are what's rolled (blank = filled from weights; unusable ranges are reported and the table rolls by weight). Older `| Result | Weight |` tables still parse. Optional frontmatter (`rows:`, `terrain-type:`, `pick: each`, `linked-folder:`…) and extra columns (Roll, Shown as, Once, When…) are row attributes. Parser/roller: `src/random-tables/randomTable.ts`; hand edits imported by `TableStore`; terrain tables under `{tablesFolder}/terrain/` (`TerrainTablesService`). ### Workflows -Markdown files with YAML frontmatter + a steps table: -```yaml +```markdown --- results-folder: world/results -template-file: world/workflows/templates/My Workflow.md +template-file: world/workflows/templates/npc.md --- - -| Table | Rolls | Label | -|-------|-------|-------| -| [[world/tables/forest-encounters]] | 2 | forest_encounters | -| [[world/tables/treasure]] | 1 | treasure | +| Table | Rolls | Label | Die | Fills | +|-------|-------|-------|-----|-------| +| [[world/tables/aspects]] | 3 | aspects | d12 | $aspects_1 $aspects_2 $aspects_3 | ``` -Parsed/serialized by `workflow.ts`. Template files live at `{workflowsFolder}/templates/{name}.md` and use `$label` / `$label_N` placeholders (multi-roll steps). `WorkflowEditorModal` auto-syncs the template when steps change: adding a step appends its section, changing a label updates the `## heading` and all `$var`/`$var_N` references, changing roll count adds or removes `_N`-suffixed placeholders. `WorkflowWizardModal` fills placeholders with roll results and saves the output as a new note. +Table, Rolls and Label are the steps; Die and Fills are derived and ignored on read. Templates use `$label` / `$label_N`. `src/random-tables/workflow.ts` parses and writes; `WorkflowEditorModal` keeps the template in step with the steps. ### Settings (`data.json`) +`HexmakerPluginSettings` (`src/types.ts`), defaults in `DEFAULT_SETTINGS` (`src/constants.ts`). Module settings keys have no default and are written only once set. -| Key | Purpose | +| Key(s) | Purpose | |-----|---------| -| `worldFolder` | Root vault folder — scopes file search | -| `hexFolder` | Where region subfolders and `x_y.md` notes live | -| `townsFolder` | Folder for the Towns dropdown | -| `dungeonsFolder` | Folder for the Dungeons dropdown | -| `questsFolder` | Folder for the Quests dropdown | -| `featuresFolder` | Folder for the Features dropdown | -| `factionsFolder` | Folder for the Factions dropdown | -| `tablesFolder` | Folder for random table files | -| `workflowsFolder` | Folder for workflow files (templates in `{workflowsFolder}/templates/`) | -| `iconsFolder` | User custom icons (merged with plugin `icons/`) | -| `templatePath` | Path to hex note template | -| `hexGap` | CSS gap between cells | -| `hexOrientation` | `"pointy"` or `"flat"` | -| `terrainPalette` | `[{name, color, icon?, iconColor?}]` | -| `gridSize` | `{cols, rows}` | -| `gridOffset` | `{x, y}` origin offset (adjusted by expand buttons) | -| `zoomLevel` | Current zoom | -| `roadChains` | `string[][]` road chains | -| `riverChains` | `string[][]` river chains | -| `roadColor` / `riverColor` | CSS colour strings | -| `defaultTableDice` | Die size for new table files | -| `regions` | `[{name}]` — named map regions (each maps to a subfolder under `hexFolder`) | +| `dataFormat` | Data stamp (`src/migrations/stamp.ts`): absent/1 = 1.5.x, 2 = map data in map notes. Never lowered; a higher one than the build knows = "written by a newer version" | +| `savedWith` | Plugin version that last saved | +| `migrationsRun` | Ids of the migrations that changed this vault, in order | +| `worldFolder`, `hexFolder`, `townsFolder`, `dungeonsFolder`, `questsFolder`, `featuresFolder`, `factionsFolder`, `regionsFolder`, `tablesFolder`, `workflowsFolder`, `palettesFolder`, `templatesFolder`, `exportFolder`, `iconsFolder`, `logFolder` | Vault folders (blank ones default under `worldFolder`); module folders: `biomesFolder`, `biomePoolsFolder`, `worldTypesFolder`, `hexFlowersFolder` | +| `templatePath` | Hex note template (else the templates folder, else built in) | +| `maps` | `MapData[]` — the map list and per-map fields; `paths`/`pathChains` are left out once the map note holds them (`withoutNotePaths`), hexes are never here | +| `terrainPalettes` | Working copy / cache of the palette notes; `paletteNotes` records which notes were written | +| `mapKinds`, `kindContent` | Map types turned on; whose shipped content is installed | +| `defaultMap`, `defaultPalette`, `defaultNewMapCols/Rows`, `defaultSubmapCols/Rows`, `defaultTableDice` | Defaults for new things | +| `hexOrientation`, `staggerOffset`, `hexGap`, `zoomLevel`, `coord*`, `hexName*`, `showTerrainLegend`, `terrainLegend*`, `hiddenIcons`, `iconOrder`, `linkSectionIcons` | Display | +| `hexEditor*Collapsed`, `rollTableExcludedFolders`, `encounterTableExcludedFolders`, `mapExportPrefs`, `hexNoteProperties` | UI state and options | +| `setupComplete`, `setupDismissed` | Setup wizard | +| `palettesMigrated`, `pathTypesExplicit`, `paletteColorsCode`, `paletteDataUpgraded`, `terrainTypesSeeded`, `tableRangesUpgraded`, `noteFormatUpgrades`, `presetTerrainsAdded`, `presetPathFieldsAdded`, `biomesSeeded`, `biomeClimatesSeeded`, `biomePoolSeeded`, `biomeColumnsFilled`, `worldTypesSeeded`, `expandedByDefault` | One-time upgrade / seeding flags (keep reading them) | +| `pathTypes` | Legacy global path types; read only by the path-type migrations | + +### Migrations (`src/migrations/`) +One file per stored-format step (`v-.ts`, `map-note--to--…`, `unreleased-…`), each with `info` (`change`, `phase`, `recordedBy`), listed in `registry.ts`. Phases run in order: settings (raw data, in `loadSettings`) → palettes (`PaletteStore`) → maps (`MapStore`) → notes (`noteRewrites.ts` runner) → tables. Back up first (`src/backup.ts`), keep old readers forever, re-plan edited notes; changes go into `migrationsRun` and the upgrade note (`upgradeNote.ts`). Modules run their own notes' upgrades from their runtime. Step list and rules: `src/migrations/README.md`; golden test `tests/migrationGolden.test.ts`. + +--- + +## Modules (`src/modules/`) + +Map types and whole features are **modules** (owner calls CM1–CM8, plan `plan-code-modules-and-legacy`): code that builds on the core and stays loosely coupled to it. The core never branches on a module by name; it asks the registry. + +| Module | Slice | What it brings | +|---|---|---| +| `world` | `foundation` (always built) | The World map type (fallback type: a palette that says nothing else is World), the Places icon pack (its sub-groups are pack data), the Expanded and Limited presets, Region detail and Overland (on the core's noise engine), first-map generator Overland, the Overland map scale | +| `world-maps` | `worldmaps` | No map type (works with any). Code in `src/overworld/`: World biomes generator and the Biomes scale, the `temperature` When key, the biome notes store, Biomes / Biome pools folder settings, New overworld…, the Biome columns upgrade (BC1), River's Carves path-field upgrade, biome seeding when map types are turned on, the sandbox demo builders, and its map-surface hooks (`worldMaps()`, below): overworld layer and minimap, biome brush, overworld clicks and menus, region walking, overworld paths, Edit region…, Make generator…, the Maps modal's overworld parts, arrival regions, the generator page's biome panel | +| `space` | `space` | Code in `src/space/`. The Space map type (section words, Region/Location card text, `planet` alias, generators offered in context, no path carry-over, `void` background), 16 space terrain types + the Space group, the space icon pack, Space - Sector/System/Planet presets, Star scatter/Orbits (engines in `src/space/`)/Planet surface, their table roles and engines, `routes`/`orbits` path roles, `zone`/`ring`/`star` When keys, the World types store, folder setting and commands, the one-time terrain type refinement, moon tethers (an overlay), Map properties → Convert world types to tables (Generator tables itself is the core's: Names is on every map; Space's roles list from its `tablesFolder` "space"), New map setup's Edit world types…, the arrival table source, the Sector-or-system and Planet map scales | + +**Two halves per module**, so the import graph has no cycles: +- **Data** — `src/modules//index.ts` → `HexmakerModule` (`types.ts`): map type info (`KindInfo`), terrain types and groups, icon pack (with optional sub-groups), palette presets, table roles, When keys, engines, path roles, map scales (the setup wizard's "What are you mapping?": label, size, palette, generator ids), Submap-defaults generator ids, path-type fields added after release, `owns` (settings keys, map-note keys, commands, and `strings`: text only it puts in `main.js`, for `check:release`). Imports types and pure data only. `src/modules/index.ts` lists them in order (`MODULES`) and builds `registry` (`ModuleRegistry`, `registry.ts`). Any core file may import `registry`. +- **Runtime** — `src/modules//runtime.ts` → `ModuleRuntime`: what needs the plugin — built-in generators (with a list `order` and engine `tuning` sliders), note stores (`ModuleStore`: init + the vault events), folder settings (rendered by both settings paths), commands (`onlyWhenOn` waits on the module's map type), ref-link rewriters for the NF3 note-format upgrade, `onEnabled` (install shipped content when its map type is turned on), `onKindsEnabled` (any map type turned on), `afterStoresReady` (one-time upgrades once the core's stores and its own load), `folders` (more note folders), `devTools` (sandbox only), and the map UI pieces (P5): `overlays` (drawn by the map view and the PNG export from the same `segments()`), `mapProperties` (Maps modal sections), `newMapSetup` (extras beside a generator option), `arrival.tableSourceFor`, `newMapOptionIds` (placement ids of its generators' options), `scaleSetup` (a map scale's own choices beside its generator and `afterCreate` once a map is made on it: World maps' Biomes turns the new map into an overworld through `finishNewOverworld`, the same path as New overworld…, with its region defaults `NEW_OVERWORLD_DEFAULTS`; "Make every region now" is off and in Advanced). `src/modules/runtime.ts` lists them; it is only read inside functions, never at import time. +- **World maps' hooks** — `src/modules/world-maps/api.ts`: the module's own functions and classes the core's map surfaces call by name (`HexMapView`, `HexEditorModal`, `MapModal`, `newChildMap`, `ArrivalService`, `GeneratorPanel`). The core gets them from `worldMaps()` in `src/modules/runtime.ts` and types them with `import type` only; the object is made on first use (the overworld code imports the core, so never at import time). Without the slice `worldMaps()` is undefined and those surfaces skip their overworld parts. This is the coupling still named after a module: each hook is a candidate for a generic contribution later. + +**What the core derives from the registry:** `MAP_KINDS`, `TERRAIN_TYPES` / `TERRAIN_GROUPS` (core land and water types first: they are shared schema, CM5), `PALETTE_PRESETS`, `BUNDLED_ICONS` and the icon-pack tabs, `ENGINE_ROLES`, the generator list (`listGeneratorKinds` = Blank + module generators + shipped/learned), When keys (`tableConditions.ts` keeps `type` and `terrain`), path role labels, the setup wizard and Settings → Map types lists, the wizard's first-map step (map scales then a generator list with Blank first, `src/mapScales.ts` and `src/wizardKinds.ts`; its Advanced holds each generator's `tuning` sliders, passed to the engine as `tune.` options whose defaults reproduce the engine exactly). New map (`NewMapSetupModal`) has the same split for new top-level maps (no scale for submaps, regions, or next to a map); both forms draw the scale cards, sliders and scale choices from `src/ui/mapScaleForm.ts` and resolve options with `optionsWithTuning`, `plugin.worldTypeStore` and `plugin.biomeStore` (getters over `plugin.moduleStores`, for module code). + +**One map-type rule (CM3)** — `mapKinds.ts`: +- `inferredKind(terrains)`: the map type a module's own terrain types say; land and water types say nothing. +- `paletteKind(p)`: declared `kind` (palette note `map-kind`), else inferred, else the fallback (World). +- `kindForChain(chain)` / `plugin.kindFor(map)`: walking from the map up its parents, the nearest palette that says a type (declared, else by its own types). Section words, Region/Location cards and the CM6 offer use it. +- `contextKindsOf(chain)` / `plugin.contextKinds(map)`: every palette's type along the chain. Generators of a type with `offerInContext` (Space) show on such maps even when the type is off; `visibleKinds` / `isGeneratorShown` take this set. + +**A module that's off (CM6):** its maps, notes and stores still load ("off hides, never deletes"). Opening such a map on purpose (maps picker, region list, hex menu Enter region / Open location, hex editor map chips — `navigateToMap(name, { offerModule: true })`) offers to turn it on (`src/maps/moduleOffer.ts`, `plugin.offerModuleFor`, `plugin.enableMapKind`); "Not now" holds for the session. "New …" flows never pass `offerModule` and never turn a module on (`tests/moduleOffer.test.ts`). + +**Release slices (P6) and the feature switches.** `release-slices.json` maps each slice to its modules, an esbuild define, whether it's `released`, the slices it `requires` and whether README/help mark its text (`docs`) (`foundation`: world, always built; `worldmaps`: `__SLICE_WORLDMAPS__`; `space`: `__SLICE_SPACE__`; `genpage`: `__SLICE_GENPAGE__`, the gen-page module (the generator page; New map and the wizard still list and run generators without it); `manual`: `__SLICE_MANUAL__`, the hexcrawl manual export, a Map export form part only; `play`: `__SLICE_PLAY__`, Solo play (party steps, visited hexes, the play log), not released yet; `hexflower`: `__SLICE_HEXFLOWER__`, the hex-flower module, not released yet, requires `genpage` and `play`; `packs`: `__SLICE_PACKS__`, content packs in `src/modules/packs/`, not released yet). One resolver, `resolveSlices` in `dev/release/slices.mjs`, decides what a build, a test run, the overworld preview, a smoke run and `check:release` compile in: `HEXMAKER_SLICES=released|all|none|` (a list read left to right; `+id` / `-id`; `--slices` on the command line, `--full` = all), then `HEXMAKER_SLICES_ON`, then `HEXMAKER_SLICES_OFF` (off wins). Defaults: `released` for `npm run build`, `all` for dev, `build:full` and the tests. foundation can't be turned off, unknown ids and a slice on without one it `requires` are errors (`offClosure` gives the dependents to turn off with it). The banner and the `__HEXMAKER_SLICES__` define name the channel (`release` / `full` / `custom +x -y`) and the slices built (`builtSlices()`, `src/modules/index.ts`). `src/modules/index.ts` and `runtime.ts` push a module only behind its flag; for a slice built off, esbuild loads the module's `index.ts` / `runtime.ts` as stubs (esbuild keeps `if (false)` branches and their imports unless minifying), so with no other import of its code nothing of it reaches `main.js`. A module's own rows of the placement map (`HexmakerModule.placement`) and of the work-mode tables (`modeActions`: commands, menu items, tools, its own actions) are merged after the core's (`CORE_PLACEMENT`, `CORE_*` in `src/workMode.ts`), so a build without it carries none of its ids; ids the core's own code names stay in the core. The runtime contribution points a slice plugs into, each with a call site in the core that does nothing while no module answers, are in `src/modules/contributions.ts`: settings (both settings paths, `src/settings/moduleSettings.ts`), views, Map export form parts, setup wizard offers, lifecycle, `genPage()`, and the Play hooks (party click, grid marks, token menu, roll targets, log writers). `help.md` and `README.md` blocks inside `…` are dropped for slices built off (markers removed otherwise): help.md as it is bundled, README.md as the release README a production build writes to `dist/README.md` beside main.js (`releaseReadme`, `dev/release/slices.mjs`). In README a table row's block opens at the end of the row before it, so removing it leaves the table whole. A module's settings keys have no `DEFAULT_SETTINGS` entry, so a build without it never writes them; its upgrades and seeding run only from its runtime. **`npm run check:release`** (`dev/release/check-release.mjs`) builds every slice on but one (each in turn, with its dependents off), the release set and foundation alone (or one build: `--off`, `--slices`, or the switch's env vars) and fails on any of the off modules' command ids, settings keys (not counting placement ids), map-note keys, `owns.strings`, placement ids or work-mode ids, and its release README on any off module's `owns.strings`, any marker, or any line of the off slices' README blocks (`sliceBlockText`); the full build must contain them all. Tests follow the switch (`tests/register.mjs`, default all); `tests/helpers/slices.ts` gives `sliceOn`, `describeWith` / `itWith` / `describeWithout` and `everyModule`; **`npm run test:slices`** (`dev/release/test-slices.mjs`) runs the contract suite (module*, placement*, releaseSlices, readmeCommands, workModeCoverage, the settings tab tests, `slice-*.test.ts`) with each slice off, the release set and none, and CI's `slices` matrix runs one set per job with `check:release`. `tests/releaseSlices.test.ts` checks the manifest, the resolver and the markers, `tests/integration/releaseSlices.integration.ts` runs `check:release`. Smoke: `--slices ` builds that set into the run folder and records it in `last-pass.json`; premerge runs the setups that exercise an unreleased slice on a full build (`last-pass.full.json`). + +**Still in the core for World maps** (documented remainder, P7): the Regions tab's region settings form and the `RegionSettings` type, region submaps and neighbours ("Next to", the d-pad; the walk into new land itself is World maps'), the biome brush's toolbar button with the `biome` tool mode and work-mode actions, the `projection` undo kind, the `Overworld path` column reader (`src/paths/pathColumns.ts`, so regeneration keeps projected paths whether or not the slice is built), River's `carves` in `DEFAULT_PATH_TYPES`, and World maps' placement ids in `src/ui/placement.ts`. None of these import module code. + +**Still in the core for Solo play** (slice `play`): the party token itself. Token notes' `token-party` / `token-log` are read and written by `src/tokens/tokenFields.ts` (as `party` / `partyLog`), so every build keeps them; the token layer selects and moves a party, and the token form shows its Party token and Log folder rows, only while a module moves parties (`partyTokensOn()`, `src/modules/runtime.ts`), else a party token is a plain token. The party controls bar is generic (`modulePartyControls`). A step runs `runPartyStep` (the module's `onStep`: visited marks, redrawn with `GridRenderer.refreshDecorations`, no full redraw) then `runPartyEntered` (`onEnter`: the move's log line, then Hex flower's fill), all one undo with the move. `MapData.visited` / `showVisited` stay declared in `src/types.ts` (types only); their map-note keys are the module's `mapNoteFields`, so a build without it keeps the lines as the user's (`tests/moduleKeysRoundTrip.test.ts`); the layers menu offers **Visited** only when a module keeps `showVisited`. The setup wizard asks for a module's folder setting that has `wizard` (`src/wizardFolders.ts`). + +**Boundary ratchet (CM8):** `tests/moduleBoundary.test.ts` scans `src/` for value imports from core files into a module's code (`src/space/`, `src/overworld/`, `src/modules//`; the registry entry points `index.ts`, `runtime.ts`, `registry.ts`, `types.ts` are allowed) and for map-type branches by name (`isSpaceMap`, `=== "space"`, `.has("world")`…). The counts live in `tests/fixtures/moduleBoundary.json`; a count may never go up, and when one goes down the list must be lowered with it. **Now 0 for every module** (P5 took Space from 4 to 0, P7 World maps from 68 to 0). **Adding a module:** write its `index.ts` (data) and `runtime.ts`, list it in both entry points, give its settings/commands placement ids, and never import it from the core. + +**Characterisation:** `tests/moduleCharacterisation.test.ts` pins the core's map-type answers over a matrix of map types × palettes × map trees (`tests/fixtures/moduleCharacterisation.json`, `UPDATE_SNAPSHOT=1` to rewrite after a deliberate change). --- ## Module responsibilities -| File | Responsibility | +| Path | Responsibility | |------|---------------| -| `DuckmagePlugin.ts` | Entry point, view registration, cross-view API, terrain table generation | -| `HexMapView.ts` | Grid rendering, all drawing tools, panning/zooming, expand, region switching | -| `HexEditorModal.ts` | Per-hex right-click editor | -| `HexTableView.ts` | Hex spreadsheet, filters, sort, jump, enc-table → RandomTableView navigation | -| `RegionModal.ts` | Region switcher and manager | -| `RandomTableView.ts` | Table + workflow browser, roll UI, public `openTable()` | -| `RandomTableModal.ts` | Inline roll from hex editor | -| `RandomTableEditorModal.ts` | Table entry editor | -| `WorkflowEditorModal.ts` | Workflow definition editor (steps, template, draggable modal) | -| `WorkflowWizardModal.ts` | Workflow execution — roll steps, fill template, save result note | -| `TerrainPickerModal.ts` | Full terrain palette picker | -| `TerrainEntryEditorModal.ts` | Single terrain palette entry editor | -| `IconPickerModal.ts` | Icon picker with previews | -| `FileLinkSuggestModal.ts` | Reusable fuzzy file picker | -| `randomTable.ts` | Pure parse/roll/weight logic (no Obsidian API) | -| `workflow.ts` | Pure workflow parse/serialize/template logic (no Obsidian API) | -| `frontmatter.ts` | `terrain:` and `icon:` read/write | -| `sections.ts` | `###` heading read/write (`addLinkToSection`, `getLinksInSection`, `getAllSectionData`, `setSectionContent`, `addBacklinkToFile`) | -| `utils.ts` | `normalizeFolder`, `getIconUrl`, `makeTableTemplate`, `createIconEl` | -| `types.ts` | `DuckmagePluginSettings`, `LINK_SECTIONS`, `TEXT_SECTIONS`, `TerrainColor` | -| `constants.ts` | `VIEW_TYPE_*`, `DEFAULT_TERRAIN_PALETTE`, `DEFAULT_SETTINGS` | -| `DuckmageSettingTab.ts` | Settings UI — "Generate folders", "Generate terrain tables", palette editor | +| `HexmakerPlugin.ts` | Plugin class: fields (stores, services), `onload`/`onunload`, one-line delegations | +| `plugin/commands.ts` | Ribbon icon, commands, file and editor menus | +| `plugin/protocolHandlers.ts` | `obsidian://duckmage-roll`, `duckmage-workflow`, map / hex links (`hexLink.ts`) | +| `plugin/vaultEvents.ts` | The single handler per vault/workspace event, fixed step order | +| `plugin/startup.ts` | Layout-ready start-up: icons, stores, note-format upgrades, upgrade notice | +| `plugin/settingsPersistence.ts` | data.json load/save, own-write echoes, data stamp, upgrade report | +| `services/MapsService.ts` | Map list: find, create (`createNewMap` options object), rename, restore, submap/region links, inheritance | +| `services/PaletteQueries.ts` | Palettes by name / per map, terrains, submap defaults, installing presets | +| `services/HexNotesService.ts` | Hex notes on use, names/aliases, Map data callouts, notes following renames | +| `services/TemplatesService.ts` | Hex and link-section templates, which notes pickers offer | +| `services/TerrainTablesService.ts` | Terrain/area tables, shipped tables, roller blocks, encounter links, terrain renames | +| `HexmakerModal.ts` | Modal base class (drag, placement, icon filter) | +| `HexmakerSettingTab.ts` | Settings tab: declarative `getSettingDefinitions()`, `display()` fallback draws the same definitions | +| `SetupWizardView.ts` | First-run setup (map types, folders, first map; `wizardKinds.ts`, `mapScales.ts`) | +| `ports.ts`, `log.ts` | `bindPorts` / `resetPorts`; `logError` / `logWarn` | +| `frontmatter.ts` | Barrel over `maps/hexData.ts` (hex map data), `notes/areaStyle.ts`, `tokens/tokenNotes.ts` | +| `hex-map/` | `HexMapView` + `view/` controllers, `HexEditorModal` + `editor/`, path tool, geometry and hit tests, map modals and pickers | +| `hex-table/` | `HexTableView`, link and terrain pickers | +| `maps/` | `MapStore`, `mapNote.ts` (pure format), `hexData`, `hexProps` / `hexPropsSync`, callouts, map tree, navigation, submaps, module offer | +| `migrations/` | Format steps, `registry.ts`, `stamp.ts`, `noteRewrites.ts`, upgrade report/note | +| `modules/` | `registry` (data), `runtime` (plugin side), `active.ts` (the runtimes for module code: `genPage()`, `worldMaps()`), `world/`, `world-maps/` (+ `api.ts` hooks), `space/`, `gen-page/` (the generator page: `GeneratorView`, `GeneratorPanel` + `sections/`, library, saves, `generatorPageState.ts`), `manual/` (the hexcrawl manual: model, HTML, exporter and its export form part), `play/` (Solo play: the party's steps, visited hexes, the play log), `hex-flower/`, `packs/` (content packs) | +| `worldgen/` | Generator registry and engines, `NewMapSetupModal`, previews, the saves format | +| `overworld/`, `space/`, `hexflower/` | Module code: World maps (biomes, regions, overworld layer), Space (orbits, star scatter, world types), hex flowers | +| `random-tables/` | `RandomTableView`, parse/roll (`randomTable.ts`, `resolve.ts`), `TableStore`, `TableNotes`, roller block, workflows | +| `fields/` | Custom hex fields (#52): the world's fields note (`fieldsNote.ts`, `FieldStore`), types, formulas, place influences, `near:` places, a hex / a map worked out (`hexFields.ts`, `mapFields.ts`); the plugin half is `services/FieldsService.ts`, the fill hook `maps/fieldFill.ts` | +| `palettes/` | `PaletteStore`, `paletteNote.ts`, `pathTypeTable.ts`, presets, palette editor view, renames | +| `paths/` | `PathsService`, router, route cache and pins, edits and gates, path columns, legacy readers | +| `arrival/` | Places made on arrival, events ledgers (Solo play is `modules/play/`) | +| `modules/packs/`, `export/` | Content pack export/import (slice `packs`); PNG / PDF / HTML / Markdown exports | +| `notes/`, `tokens/` | Area-note styling and frontmatter text; token notes | +| `ui/` | Shared controls: `sliders`, `shareSliders` (+ `shares`), `pickers`, `disclosure` (Advanced, Debug, `Fold`), `placement` (the placement map), `notify`, `numberBoxes`, `debugMode`, `mapScaleForm` | +| `md/tableRow.ts`, `stores/NoteFolderStore.ts`, `vault/ensureFolder.ts`, `workspace/views.ts` | Shared `splitRow`; note-folder store base; race-safe folder creation; finding/opening views | +| `hexKey.ts` | Hex-key (`"x_y"`) helpers (Lane L11, landing separately) | +| `sections.ts`, `utils.ts`, `types.ts`, `constants.ts` | `###` section read/write; `normalizeFolder`, `getIconUrl`…; types; `VIEW_TYPE_*`, `DEFAULT_SETTINGS` | --- ## Key conventions - Folder paths normalised (no leading/trailing slashes) via `normalizeFolder()`. -- All wiki-links use `metadataCache.fileToLinktext(file, sourcePath)` for vault-relative resolution. +- Wiki-links via `metadataCache.fileToLinktext(file, sourcePath)`. - `obsidian` is an esbuild external — never bundled. -- CSS classes use the `duckmage-` prefix. -- Views and modals import `DuckmagePlugin` as a type only (`import type`) to avoid circular runtime deps. -- Metadata-cache race after `vault.modify`: `HexEditorModal.onChanged()` defers `renderGrid()` by 300 ms when no terrain/icon overrides are passed. -- Modals that preload file content accept an optional `preloaded` / `initialContent` parameter to avoid redundant vault reads when the caller already holds the content. -- Notes whose `basename` starts with `"_"` are excluded from all dropdowns, file trees, and auto-generated lists. Pattern: `.filter(f => !f.basename.startsWith("_"))`. -- Draggable modals call `makeDraggable()` in `onOpen`, add the `duckmage-editor-modal-drag` class, and restrict drag to the title-bar area. +- CSS classes use the `duckmage-` prefix; dynamic values go through CSS custom properties, never `.style.x =`. +- Views, modals and helpers import `HexmakerPlugin` as a type only (`import type`); `tests/importCycles.test.ts` forbids new value-import cycles. +- New code goes in new focused files (`tests/fileSizes.test.ts` caps files over 800 lines); split-out code takes a narrow `*Host`. +- Map data only through `plugin.mapStore` / the `frontmatter.ts` getters; stored-format changes only through `src/migrations/`. +- Layout reads before DOM writes in any per-hex loop; hit tests in the drawing's units (em), tested at several zooms. +- Modals that preload file content accept an optional `preloaded` / `initialContent` parameter. +- Notes whose `basename` starts with `"_"` are excluded from dropdowns, file trees and generated lists: `.filter(f => !f.basename.startsWith("_"))`. +- Control placement comes from `src/ui/placement.ts` (main / more / advanced / debug / hidden); the same kind of input uses the same shared control. diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 00000000..b336fa0a --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,84 @@ +# Changelog + +One short sentence per change. The upgrade note a vault gets after updating +("Hexmaker upgrade ", in the world folder) lists the points newer than +the version it came from. + +## Unreleased + +### Before you update + +- Update every device that shares this vault first: older versions can't read the new map notes. +- The first start after updating moves your data into notes and backs everything up first; it can take a few minutes on a big vault. + +### Your data + +- Each map's terrain, icons, areas and paths now live in one map note, `_.md`, in the map's folder. +- Hex notes keep all their text and link their map note under `map:`. +- Terrain palettes are now notes in the palettes folder that you can read and edit. +- Random tables show each row's roll range for their die, so you can roll them by hand. +- Old filled Terrain and Region lines in hex notes move into the note's Map data box. +- Every upgrade backs up what it changes first, under the plugin's backups folder. +- A "Hexmaker upgrade " note in your world folder lists what changed, the backups, and anything to check. +- New commands open the backups folder and restore notes from an upgrade backup. +- Named zones on a map are called areas everywhere, in notes too (`> Area:`, an Area column); old names still read. +- data.json carries a data format number, so an older version can tell the vault was updated. + +### Maps + +- Maps can have region and location submaps, listed as a tree in the Maps list. +- The breadcrumb shows the maps above this one and the maps beside it. +- Maps can be each other's submaps; navigation handles it without changing anything. +- Hexes can have names, shown on the map with your choice of font. +- A small legend in the corner shows the map's terrains and folds to a chip. +- Maps have work modes (Build, Play, God) that decide what a click can change, each with its own undo. + +### Paths + +- Paths are named, with anchors, and the map routes the way between them. +- Path types belong to palettes, and every behaviour of a type is an option you set. +- Routes stay where they are when the terrain changes, unless you reroute them. + +### Generators and setup + +- The setup wizard asks what you'll map and installs only what that needs. +- New maps can be generated with a preview, Reroll and a few tuning sliders. +- Expanded is the default palette for new vaults, with savanna and river delta added to existing copies. +- New map → Next to has a Neighbour influence slider for how strongly the maps beside it steer it. +- A generated map keeps its recipe in its map note, so Reroll can make it again until your first edit. +- Overland lays out each of the palette's path types, with a row per type. + +### World maps + +- Overworlds: one biome per hex, each hex opening into a region that blends with its neighbours. +- Biomes are notes you can edit, with their own mix, climate and transitions. +- Paths that cross from one region into another show on the overworld. + + +### Space + +- Space maps: star sectors, star systems and planet surfaces, with their own palettes and generators. +- World types notes decide which worlds the space generators place. + + +### Tables and workflows + +- Tables can roll on other tables, with typed rows and conditions. +- Workflows write readable results notes and keep their template in step. +- Hex editor rolls can go straight into a section of the hex note. +- New tables start empty and can't be rolled until they have entries; an empty table offers Add entries. +- Encounters, Weather and Hooks & Rumors list every table that applies to the hex, to switch between. +- Note templates start barebones (title, Description, Notes) for you to shape. + +### Play + +- Any token can be the party: in Play it moves one hex at a time and marks the hexes it visits. +- A play log keeps one note per day of play, linked from the hexes it mentions. +- Show on map sets a hex's icon from its linked notes (towns, dungeons…). + +### Everything else + +- Each page has an Advanced dropdown for the less common options, and a Debug section in debug mode. +- Places icons: settlements, castles, towers, ruins, temples, camps and caves. +- Exported notes say where they came from. +- Exporting never replaces a file it didn't make: it saves a copy beside it, as "Name 2". diff --git a/CLAUDE.md b/CLAUDE.md index a9907ab9..ca976a52 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1,245 +1,252 @@ -# CLAUDE.md - -This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository. - -## Commands - -```bash -# Development (watch mode with inline sourcemaps) — use with Hot Reload (see below) -npm run dev - -# Production build (type-checks then bundles) -npm run build - -# Run tests (vitest) -npm test - -# Bump version (updates manifest.json and versions.json, stages both) -npm run version -``` - -Slash commands (invoke inside Claude Code): -- `/dev` — starts esbuild in watch mode (long-running; pairs with Hot Reload) -- `/rebuild` — one-off production build + test run; reports errors if either fails - -**Always run `/rebuild` after making code changes.** The TypeScript type-check and test suite are the only automated verification — catch errors before the user does. - -## Dev loop - -Each coding session: -1. Run `npm run dev` in a terminal (or `/dev` from Claude Code) — esbuild watches for changes and rebuilds `main.js` on every save -2. After a rebuild, reload the plugin in Obsidian: - ```bash - powershell.exe -Command "obsidian plugin:reload id=duckmage-plugin" - ``` -3. Use `/rebuild` for a final production build before committing (runs the TypeScript type-check and tests too) - -## Architecture - -The plugin source is split across `main.ts` (entry point re-export) and modules under `src/`. esbuild bundles everything into `main.js`, which Obsidian loads directly. - -See `ARCHITECTURE.md` for a full overview of the system. - -### Source layout - -``` -main.ts ← thin re-export: export { default } from "./src/DuckmagePlugin" -src/ - DuckmagePlugin.ts ← Plugin class (entry point, default export) - HexMapView.ts ← ItemView — hex grid, all drawing tools, inline modals - HexEditorModal.ts ← Modal — right-click per-hex editor (terrain, links, notes, icon override) - HexTableView.ts ← ItemView — spreadsheet view of all hex notes with filters/sort - TerrainPickerModal.ts ← Modal — full terrain palette picker for the terrain paint tool - TerrainEntryEditorModal.ts ← Modal — edit a single terrain palette entry (name, color, icon) - IconPickerModal.ts ← Modal — icon picker for the icon paint tool - RegionModal.ts ← Modal — switch active region, create/rename/delete regions - FileLinkSuggestModal.ts ← SuggestModal — file picker scoped to worldFolder - RandomTableView.ts ← ItemView — random table + workflow browser (tabbed: Tables / Workflows) - RandomTableModal.ts ← Modal — inline roll modal used from HexEditorModal - RandomTableEditorModal.ts ← Modal — edit entries of a random table file - WorkflowEditorModal.ts ← Modal — edit workflow definition (steps, template, results folder) - WorkflowWizardModal.ts ← Modal — execute a workflow (roll steps, fill template, save as note) - randomTable.ts ← Pure logic: parse, roll, weight, die-range helpers - workflow.ts ← Pure logic: parse/serialize workflows, generate templates, placeholder helpers - DuckmageSettingTab.ts ← PluginSettingTab — settings UI - types.ts ← Interfaces & type constants (TerrainColor, DuckmagePluginSettings, LINK_SECTIONS, TEXT_SECTIONS) - constants.ts ← Runtime constants (VIEW_TYPE_*, DEFAULT_TERRAIN_PALETTE, DEFAULT_SETTINGS) - defaultHexTemplate.md ← Built-in hex note template (imported as text via esbuild loader) - frontmatter.ts ← YAML frontmatter helpers (terrain + icon override read/write) - sections.ts ← Markdown section helpers (addLinkToSection, getLinksInSection, getAllSectionData, …) - utils.ts ← Shared utilities (normalizeFolder, getIconUrl, makeTableTemplate) - md.d.ts ← TypeScript declaration for "*.md" text imports -``` - -The `.md` loader is configured in `esbuild.config.mjs` (`loader: { '.md': 'text' }`), allowing `defaultHexTemplate.md` to be imported as a plain string. - -### Plugin purpose - -Renders an interactive hex-grid map for tabletop RPG world-building inside Obsidian. Each hex cell corresponds to a Markdown note on disk. The map supports terrain painting, icon painting, road/river chain drawing, link-to-hex tools (random tables, factions), panning, and zooming. A spreadsheet view summarises all hex notes with filtering. A random tables view lets users browse, roll, and edit weighted random tables, and execute multi-step workflows that chain table rolls into a filled template note. - -### Key classes - -- **`DuckmagePlugin`** (`src/DuckmagePlugin.ts`) — Main plugin entry point. Registers views (`HexMapView`, `HexTableView`, `RandomTableView`), ribbon icons, commands, and the settings tab. Key public API: - - `hexPath(x, y)` — vault-relative path for a hex note - - `createHexNote(x, y)` — creates hex note from template - - `loadAvailableIcons()` — merges plugin `icons/` with user custom icons folder into `availableIcons: string[]` - - `refreshHexMap()` — re-renders all open `HexMapView` instances - - `ensureTerrainTables()` — creates missing terrain table files under `tablesFolder/terrain/` - - `ensureAllRollerLinks()` — adds roller-link preamble to all table files - - `backfillTerrainLinks()` — links each hex note's terrain table into its Encounters Table section - - `buildRollerLink(path)` — generates the `[Roll]()` URI for a table file - -- **`HexMapView`** (`src/HexMapView.ts`, extends `ItemView`) — Renders the hex grid and handles all user interaction. - - **DOM structure**: `contentEl` (`.duckmage-hex-map-container`) → `.duckmage-hex-map-clip` (panning viewport, `overflow: hidden`) + `.duckmage-hex-map-controls` (overlay for buttons, `pointer-events: none`). This keeps toolbar/expand buttons unclipped by the viewport transform. - - **`renderGrid(terrainOverrides?, iconOverrides?)`** — full DOM re-render. Optional override Maps allow passing values not yet in the metadata cache. - - **Drawing tools**: `drawingMode` union `"road" | "river" | "terrain" | "icon" | "tableLink" | "factionLink" | null`. Toolbar buttons toggle mode; each mode has a `handle*Button()` opener, `exit*Mode()` closer, and `onHex*Click()` handler. - - **Write queues**: `scheduleTerrainWrite` / `scheduleIconWrite` coalesce rapid repaints — only the latest value per hex is written, preventing stale overwrites. - - **Link tools** (`tableLink`, `factionLink`): pick a file via folder-tree modal, then click hexes to add a wiki-link to the `Encounters Table` or `Factions` section. Visual feedback: badge span + CSS ripple blip animation (`duckmage-hex-blip`). - - Left-click: opens/creates hex note (normal), paints terrain/icon, extends road/river chain, or adds a link. - - Right-click: opens `HexEditorModal` (normal), deletes road/river node, or exits current tool mode. - - Expand buttons (+) grow the grid in four cardinal directions, adjusting `gridOffset` and `gridSize` in settings. - - **`centerOnHex(x, y)`** (public) — pans the viewport to centre on a given hex coordinate. - - **`activeRegionName`** (public) — the currently displayed region name. - -- **`HexEditorModal`** (`src/HexEditorModal.ts`, extends `Modal`) — The right-click per-hex editor: - - Terrain picker (2-row scrollable grid) with icon override and "Clear terrain". - - Dropdown link sections for **Towns, Dungeons, Features, Quests, Factions, Encounters Table** — each backed by its own configured folder, rendered via `renderDropdownSection`. Uses `LinkPickerModal` internally (file list + create-new). - - Free-text note sections: Description, Landmark, Hidden, Secret, Weather, Hooks & Rumors. - - Fetches all section data in a single read before touching the DOM (`getAllSectionData`). - -- **`HexTableView`** (`src/HexTableView.ts`, extends `ItemView`) — Spreadsheet of all hex notes: - - Columns: Hex (coords + jump button), Terrain, Description, Landmark, Towns, Dungeons, Features, Quests, Factions, Enc. Table, Hidden, Secret, Weather, Hooks & Rumors. - - Enc. Table cell shows the basename of the linked table file; clicking opens `RandomTableView` at that file. - - Toolbar filters: X/Y range inputs, terrain multi-select (left-click include / right-click exclude), Has Town/Dungeon/Feature/Quest/Faction checkboxes, region selector, X→Y / Y→X sort priority, Asc/Desc direction. - - Live updates on vault `modify` events (300 ms debounce per file). - - Jump button (◎) calls `HexMapView.centerOnHex(x, y)` on the open map view. - -- **`RandomTableView`** (`src/RandomTableView.ts`, extends `ItemView`) — Tabbed browser with two modes: - - **Tables mode**: folder tree + search + new-table creator. Detail pane shows entries with die-range and % odds, die-size selector, Roll button, copy result, roll history. Edit opens `RandomTableEditorModal`. Bottom of detail pane shows "Workflows using this table" links (each opens that workflow in Workflows mode) and a "+ New workflow with this table" link. - - **Workflows mode**: folder tree of workflow files. Detail pane shows each step as a clickable link (opens that table in Tables mode) with roll count. Edit opens `WorkflowEditorModal`. "Roll workflow" button opens `WorkflowWizardModal`. - - **`openTable(filePath)`** (public) — switches to Tables mode, expands ancestor folders so the target is visible, and loads the table detail; called from `HexTableView` (Enc. Table cell), `HexEditorModal`, workflow step links, and the protocol handler. - -- **`RandomTableModal`** (`src/RandomTableModal.ts`, extends `Modal`) — Lightweight inline roll modal opened from `HexEditorModal` (🎲 button per link section or 📖 for terrain description). Skips the picker if `initialFilePath` is supplied. - -- **`RandomTableEditorModal`** (`src/RandomTableEditorModal.ts`, extends `Modal`) — Edit table entries (result text + weight), linked folder, description, filter flags. Auto-saves on close. Accepts optional `initialContent` to avoid a redundant vault read when the caller already has the file content. - -- **`WorkflowEditorModal`** (`src/WorkflowEditorModal.ts`, extends `Modal`) — Edit a workflow definition: - - Rename workflow, set results folder, manage steps (table picker + roll count + label) with drag-to-reorder. - - Template textarea with live placeholder validation — shows missing `$placeholder` names. - - Template auto-syncs: new step appends `## label\n$label` block; label change updates the heading AND all `$var`/`$var_N` placeholder references; roll-count change adds or removes `_N` suffixed placeholders (reducing to 1 collapses back to bare `$var`). - - Auto-saves workflow file and template file on close. Modal is draggable by its title bar. - -- **`WorkflowWizardModal`** (`src/WorkflowWizardModal.ts`, extends `Modal`) — Execute a workflow: - - Shows each step with a manual-pick dropdown and a Roll button. Fixed-width controls to prevent layout shift on roll. - - Result textarea shows the template filled with rolled values. - - Save section writes the filled result as a new vault note in the configured results folder. - -- **`RegionModal`** (`src/RegionModal.ts`, extends `Modal`) — Manage hex map regions: - - Switch the active region displayed on the hex map. - - Create, rename, and delete regions. Regions map to subfolders under `hexFolder`. - -- **`TerrainEntryEditorModal`** (`src/TerrainEntryEditorModal.ts`, extends `Modal`) — Edit a single terrain palette entry: name, color, icon (with preview), and icon color tint. Changes are staged in pending fields and only written to the palette on Save. - -- **`TerrainPickerModal`** (`src/TerrainPickerModal.ts`) — Full terrain palette picker (no row cap). Includes "Clear" to erase terrain. - -- **`IconPickerModal`** (`src/IconPickerModal.ts`) — Full icon picker with image previews. Includes "Remove" option. - -- **`FileLinkSuggestModal`** (`src/FileLinkSuggestModal.ts`) — Reusable fuzzy-search file picker scoped to a configured folder. - -- **`DuckmageSettingTab`** (`src/DuckmageSettingTab.ts`) — Settings UI: - - "Generate folders" button — fills blank folder settings with defaults under `worldFolder` and creates the folders. - - Folder paths: world, hexes, towns, dungeons, quests, features, factions, tables, workflows. - - "Generate terrain tables & hex links" button — runs `ensureTerrainTables`, `ensureAllRollerLinks`, `backfillTerrainLinks`. - - Hex orientation, grid dimensions, hex gap, custom icons folder, road/river colors, terrain palette editor (drag-to-reorder, click entry to open `TerrainEntryEditorModal`). - -### Data model - -- **Hex notes**: `{hexFolder}/{region}/{x}_{y}.md`. Created via `createHexNote(x, y, region)` using the configured template or `defaultHexTemplate.md`. -- **Template placeholders**: `{{x}}`, `{{y}}`, `{{title}}`. Template must include `### Towns`, `### Dungeons`, `### Features`, `### Quests`, `### Factions`, `### Encounters Table` headings. -- **Terrain**: YAML frontmatter `terrain: `. Read via `getTerrainFromFile` (metadata cache); written via `setTerrainInFile` (raw text patch). Both in `frontmatter.ts`. -- **Icon override**: frontmatter `icon: `. Read via `getIconOverrideFromFile`; written via `setIconOverrideInFile`. -- **Terrain icons**: plugin `icons/` folder + user custom icons folder → `plugin.availableIcons`. URLs via `getIconUrl(plugin, filename)`. Vault-sourced filenames tracked in `plugin.vaultIconsSet`. -- **Roads & rivers**: `settings.roadChains` / `settings.riverChains` — arrays of `string[]` chains, each element `"x_y"`. Drawn as SVG polylines over the grid. -- **Link sections** (`LINK_SECTIONS`): `"Towns" | "Dungeons" | "Features" | "Quests" | "Factions" | "Encounters Table"`. Wiki-links inserted under the matching `###` heading via `addLinkToSection`. Read back via `getLinksInSection`. -- **Text sections** (`TEXT_SECTIONS`): Description, Landmark, Hidden, Secret. Free text stored under `###` headings. Weather and Hooks & Rumors are also text sections but not in the `TEXT_SECTIONS` constant. -- **Random tables**: Markdown files with YAML `dice: N` frontmatter and a `| Result | Weight |` table. Parsed by `randomTable.ts`. Stored under `tablesFolder` (default `world/tables`). Terrain tables live at `{tablesFolder}/terrain/{name} - {description|encounters}.md`. -- **Workflows**: Markdown files with YAML frontmatter (`results-folder`, `template-file`) and a `| Table | Rolls | Label |` steps table. Stored under `workflowsFolder`. Templates stored at `{workflowsFolder}/templates/{name}.md`. Parsed/serialized by `workflow.ts`. -- **Settings** (`data.json`): `worldFolder`, `hexFolder`, `townsFolder`, `dungeonsFolder`, `questsFolder`, `featuresFolder`, `factionsFolder`, `tablesFolder`, `workflowsFolder`, `iconsFolder`, `templatePath`, `hexGap`, `hexOrientation`, `terrainPalette`, `gridSize`, `gridOffset`, `zoomLevel`, `roadChains`, `riverChains`, `roadColor`, `riverColor`, `defaultTableDice`, `regions`. - -### Hex orientations - -- **Pointy-top**: points north/south, flat sides east/west. Odd rows offset right. Adjacency via odd-r offset. -- **Flat-top** (default): flat sides north/south, points east/west. Odd columns offset down. Adjacency via odd-q offset. -- `hexNeighbors(x, y)` in `HexMapView` branches on `settings.hexOrientation`. - -### Key conventions - -- Folder paths normalised (no leading/trailing slashes) via `normalizeFolder()`. -- Links use vault-relative paths via `metadataCache.fileToLinktext(file, sourcePath)`. -- `obsidian` is an esbuild external — never bundled; provided by Obsidian at runtime. -- CSS classes use the `duckmage-` prefix (styles in `styles.css`). -- View/modal/tab files use `import type DuckmagePlugin` to avoid circular runtime dependencies. -- Paint tool methods (`onHexPaintClick`, `onHexIconClick`) are synchronous — DOM patched immediately, file writes queued via coalescing queue. -- Link-tool click handlers (`onHexTableLinkClick`, `onHexFactionLinkClick`) are async — no coalescing needed (one-shot writes). -- `onChanged` callback from `HexEditorModal` defers `renderGrid()` 300 ms when no terrain/icon overrides are passed (link-only changes) to avoid a metadata-cache race after `vault.modify`. -- Modals that preload file content accept an optional `preloaded` / `initialContent` parameter — callers that already hold the file content pass it in to avoid a redundant vault read. -- Exclude notes whose `basename` starts with `"_"` whenever enumerating vault files for display, dropdowns, or linking. Pattern: `.filter(f => !f.basename.startsWith("_"))`. -- **All modals must extend `DuckmageModal`** (`src/DuckmageModal.ts`) rather than Obsidian's `Modal` directly. `DuckmageModal` is the single place for shared modal behaviour. Any functionality needed by more than one modal belongs there, not in `utils.ts` or duplicated across files. -- All modals call `this.makeDraggable()` in `onOpen` (inherited from `DuckmageModal`), which adds the `duckmage-editor-modal-drag` class and locks dragging to the title-bar area. (`FileLinkSuggestModal` is the sole exception — it extends `SuggestModal` and cannot inherit from `DuckmageModal`.) -- **NEVER interleave layout reads (`offsetWidth/Height/Left/Top`, `getBoundingClientRect`, `getComputedStyle`) with DOM writes (`createDiv`/`createEl`/`appendChild`/`setCssProps`/style changes) inside a per-hex loop.** Each read after a write forces a full synchronous layout flush → O(n²) thrash. On large maps (chult = 3843 hexes) this stalled the main thread for ~20s on open (regression in `renderCoordLabelsLayer`, commit 10475fd; fixed by batching). **Pattern:** read ALL geometry into a plain array first, THEN do all DOM writes. This is the established pattern in `renderPathOverlay`/`renderFactionOverlay` (build `centerMap` read-only, then build the SVG). The overlay/label builders in `HexMapView` are the hot path — any new one MUST follow read-then-write. Reproduce/validate with `dev/coord-label-thrash-bench.{html,mjs}` (~198× speedup batched vs interleaved). - -### Obsidian directory review in CI (never via the dashboard by hand) - -Every branch push runs Obsidian's automated review (preview scan) in CI, and -master releases are gated on it, then the published release scan is watched -(`.github/workflows/obsidian-review.yml`, `release.yml`, `dev/obsidian-review.mjs`). -**When an "Obsidian review" job fails, follow the Runbook in -`.github/OBSIDIAN_REVIEW.md`**: the failure message names the entry. The -common one is an expired session: the fix is `npm run obsidian:login` -(opens a browser, user logs in if asked, it sets the -`OBSIDIAN_COMMUNITY_COOKIE` secret), then re-run the job. Use -`gh` as `sbuffkin` (`GH_TOKEN=$(gh auth token --user sbuffkin)`) for this repo. - -### Obsidian reviewer-bot conventions (enforced beyond what eslint catches) - -The obsidianmd reviewer flags patterns the locally-installed -`eslint-plugin-obsidianmd` doesn't have rules for. Watch for these -in any new code; failing these means another bump-and-fix cycle. - -- **Keep `eslint-plugin-obsidianmd` AND `typescript-eslint` current.** The - reviewer bot runs the LATEST versions; stale pins let findings through - local lint twice on 2026-08-09 (obsidianmd 0.1.9 → 22 `prefer-create-el` - sites; typescript-eslint 8.58 → 6 unnecessary-assertion sites its newer - "receiver accepts the original type" check catches). When reviewer - warnings arrive that local lint missed, first `npm view version` - vs `npm ls ` for both packages and upgrade. -- **`prefer-create-el` + `@typescript-eslint/no-unnecessary-type-assertion` - are now enforced locally** (plugin 0.4.1 + type-aware rule in - eslint.config.mjs). Use `parent.createEl/createDiv/createSpan` (or the - global `createEl` for genuinely detached elements), never - `document.createElement`/`activeDocument.createElement`. -- **Settings tab is declarative (Obsidian ≥1.13).** `HexmakerSettingTab` - implements `getSettingDefinitions()`; on 1.13+ the tab renders FROM THE - DEFINITIONS and `display()` is never called (it remains only as the - pre-1.13 fallback). Any new setting must be added to BOTH paths until - minAppVersion reaches 1.13. Local `obsidian` typings are 1.12 — the - 1.13 shapes are mirrored as local interfaces in HexmakerSettingTab.ts; - delete them when the package is bumped. -- **CSS lint "css-clip-path partially supported" warnings are accepted** — - our clip-paths are basic `polygon()` hex shapes, fully supported in - desktop Electron, and the plugin is `isDesktopOnly`. Don't churn on them. - -- **`document` / `window` → `activeDocument` / `activeWindow`.** Required - for popout-window compatibility. Globals are listed in `eslint.config.mjs`. - Use `activeDocument.createElementNS(...)`, `activeDocument.body.createDiv(...)`, - `window.setTimeout(...)` is OK but prefer `activeWindow.setTimeout(...)` - inside view code where popouts could fire it. -- **Dynamic CSS: never `.style.foo = …` or `setCssProps({ transform: … })`.** - The local eslint rule (`obsidianmd/no-static-styles-assignment`) is - promoted to an error to catch this. The pattern is: declare the - `transform` / `opacity` / etc. in CSS using `var(--duckmage-..., default)` - fallbacks, and write the dynamic values to the custom properties from - JS. See `.duckmage-bg-image-layer`, `.duckmage-hex-map-grid`, - `.duckmage-hex-map-viewport` for the canonical examples. -- **`setDynamicTooltip()` is deprecated.** The slider value is now always - shown inline. Drop the call from any new `.addSlider(...)` chain. +# CLAUDE.md + +This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository. + +## Commands + +```bash +# Development (watch mode with inline sourcemaps, every release slice built) — use with Hot Reload (see below) +npm run dev + +# Release build (type-checks then bundles the slices marked released in release-slices.json) +npm run build + +# Full build: every slice, released or not (owner and test vaults) +npm run build:full + +# Prove a slice built off leaves no trace in main.js (each slice off, the release set, none) +npm run check:release # or: node dev/release/check-release.mjs --off space + +# Run tests (node:test via tsx; every slice on; runs every tests/*.test.ts) +npm test + +# The contract suite with each slice off, the release set and none (CI runs one set per job) +npm run test:slices # or: node dev/release/test-slices.mjs --only off:space + +# Type-check the tests (tsconfig.test.json; also in premerge) +npm run typecheck:tests + +# Bump version (updates manifest.json and versions.json, stages both) +npm run version +``` + +Slash commands (invoke inside Claude Code): +- `/dev` — starts esbuild in watch mode (long-running; pairs with Hot Reload) +- `/rebuild` — one-off production build + test run; reports errors if either fails + +**Always run `/rebuild` after making code changes.** The TypeScript type-check and test suite are the only automated verification — catch errors before the user does. + +## Dev loop + +Each coding session: +1. Run `npm run dev` in a terminal (or `/dev` from Claude Code) — esbuild watches for changes and rebuilds `main.js` on every save +2. After a rebuild, reload the plugin in Obsidian: + ```bash + powershell.exe -Command "obsidian eval code=\"(async()=>{await app.plugins.disablePlugin('hexmaker'); await app.plugins.enablePlugin('hexmaker'); return 'ok'})()\"" + ``` + The plugin **id is `hexmaker`** (the folder is `duckmage-plugin`). On this machine's Obsidian installer the CLI's `plugin:reload` / `plugin:disable` / `plugin:enable` and `dev:*` commands silently do nothing (exit 255, "installer out of date"); `obsidian eval` works. To check what's loaded: `obsidian eval code="Object.keys(app.commands.commands).filter(c=>c.startsWith('hexmaker:'))"`. Screenshot: `require('@electron/remote').getCurrentWebContents().capturePage()` inside `eval`. `app.plugins.plugins.hexmaker.manifest.version` is cached from startup — don't use it to tell builds apart. + **Before copying a build into this folder**, check which branch the current vault build came from — other sessions deploy from their own branches, and a deploy reverts theirs. +3. Use `/rebuild` for a final production build before committing (runs the TypeScript type-check and tests too) + +## Feature switches (release slices) + +Every major feature is a **slice** (`release-slices.json`): `foundation` (always built), `worldmaps`, `space`, `genpage` (the generator page), `play` (Solo play: party steps, visited hexes, the play log), `hexflower` (needs `genpage` and `play`) `packs` (content packs) and `manual` (the hexcrawl manual export) today. One switch picks which are built, read the same way by esbuild, the tests, the overworld preview, smoke and `check:release` (`dev/release/slices.mjs` `resolveSlices`): + +| Variable | Meaning | +|---|---| +| `HEXMAKER_SLICES` | The base set: `released`, `all`, `none`, or a list read left to right: `space,worldmaps` (exactly those), `+hexflower` / `-space` (on top of the default), `all,-space`, `none,+space` | +| `HEXMAKER_SLICES_ON` | Ids added on top (`a,b`) | +| `HEXMAKER_SLICES_OFF` | Ids removed last; **off wins** | +| `--slices ` / `--slices=` | On the esbuild command line, the same as `HEXMAKER_SLICES` and ahead of it; `--full` = `--slices all` | + +Defaults: `npm run build` → `released`; `npm run dev`, `build:full` and the tests → `all`. `foundation` can't be turned off; an unknown id is an error; a slice built on while a slice it `requires` is off is an error naming both (no silent cascade; turn the dependent off too). The bundle's banner says the channel (`release`, `full` or `custom +x -y`) and the slices built, as does the `__HEXMAKER_SLICES__` define (`builtSlices()`). + +```bash +HEXMAKER_SLICES_OFF=hexflower node esbuild.config.mjs production # release build without hex flowers +HEXMAKER_SLICES=none node esbuild.config.mjs production # foundation only +HEXMAKER_SLICES=all node dev/release/check-release.mjs # check that one build +HEXMAKER_SLICES_OFF=space npm test # the tests without Space +npm run smoke -- --slices all --only fresh # smoke a build with every slice +``` + +**Adding a slice:** the module goes in `src/modules//` (`index.ts` data, `runtime.ts` what needs the plugin) and its own folder in `tests/moduleBoundary.ts` `MODULE_DIRS`; add the slice to `release-slices.json` (`define`, `modules`, `released`, `requires`, `docs`), its flag to `src/slices.d.ts`, and one `if (__SLICE_X__) compiled.push(…)` line each in `src/modules/index.ts` and `runtime.ts`. It plugs into the core only through its contributions (`src/modules/types.ts` and `contributions.ts`: placement rows, work-mode rows, commands, settings, views, export form parts, wizard offers, lifecycle, Play hooks, `genPage()`), never by the core importing it. List what it owns in `owns` (`check:release` also takes its placement and work-mode ids), mark its README/help text `…`, add its `off:` set to the `slices` matrix in `.github/workflows/ci.yml`, and write `tests/slice-.test.ts` with an "off" twin (`describeWith` / `describeWithout` / `itWith` from `tests/helpers/slices.ts`). Before landing: `npm run test:slices` and `npm run check:release`. + +## Running from a Windows-native session + +`node_modules` is installed from WSL (Linux esbuild binary, no `.cmd` shims), so npm scripts fail when run from Windows. Run them through WSL: + +```bash +MSYS_NO_PATHCONV=1 wsl.exe -e bash -lc 'cd /mnt/c/Users/markr/Documents/KB/journal/.obsidian/plugins/duckmage-plugin && npm run build' +``` + +## Before merging or deploying: `npm run premerge` + +**Before merging into `feat/region-notes` (or master) or deploying a build into the live vault, run `npm run premerge`** (from WSL, like every npm script here) and only go ahead when it ends with `PREMERGE PASSED`. It runs build → lint → test type-check → unit tests → integration tests → the **smoke vault matrix**, stopping loudly at the first failure (owner decision WM5: the matrix runs locally, not in CI; CI keeps the Obsidian-free tests). + +- The matrix (`dev/smoke/run.mjs`, plan [[plan-work-modes]] §3) builds 9 vault setups (fresh install, a synthetic 1.5.5 vault, a copy of the owner's real data `C:/Users/markr/work/tmp/migtest/seedF` + a copy of the live `data.json`, space only, overworld + regions, neighbours world, a custom palette with no default names, everything deleted, 80 maps), each in its own sandboxed Obsidian (fresh-eyes `sandbox.mjs`, up to 4 at once), and checks: no plugin console errors; settings saved; every map opens and renders; untouched files unchanged on disk (migrations verified separately: map notes, backups, hex data vs the old frontmatter, paths resolve, palette upgrades keep every terrain); a restart rewrites nothing; paint → undo round trip; registered commands; Play refuses a path edit. ~5 minutes, mostly the real-data migration. +- Run parts of it: `npm run smoke -- --only fresh,v155 --jobs 2` (`--list` for the setup ids, `--keep` to keep run folders, `--build ` to test another build, `--slices ` to build a set of features into the run folder). A failed setup keeps its run folder (path in `dev/smoke/last-run.json`); a full pass writes `dev/smoke/last-pass.json` (commit, build hash, the slices built, per-check results). +- premerge also runs the setups that exercise an unreleased slice (a setup's `slices`; today `fresh`, for the party check C9 and the hex flower check C10) on a build with every slice, stamped `dev/smoke/last-pass.full.json`, before the release matrix. +- It only stops the sandboxes it started and checks every other Obsidian process is still there (`otherObsidianBefore == otherObsidianAfter`). Never point it at the main vault. +- A new feature with a user-visible write path (paint, paths, a new note type, a migration) should get a smoke check in `dev/smoke/lib/page.mjs` / `setups.mjs` as well as unit tests. + +## Architecture + +`main.ts` re-exports `src/HexmakerPlugin.ts`; esbuild bundles everything into `main.js` (`.md` files import as text: `loader: { '.md': 'text' }` in `esbuild.config.mjs`). The plugin id is `hexmaker`; view types, CSS classes and protocol actions keep the old `duckmage-` prefix. See `ARCHITECTURE.md` for the module table, the data formats and the modules/slices system. + +**Modules and release slices.** World (released), World maps (`src/overworld/`) and Space (`src/space/`) are modules (`src/modules/`); one module is one release slice (`release-slices.json`, esbuild defines `__SLICE_WORLDMAPS__` / `__SLICE_SPACE__` / `__SLICE_GENPAGE__` / `__SLICE_PLAY__` / `__SLICE_HEXFLOWER__` / `__SLICE_PACKS__`). The core never value-imports a module's code: it asks `registry` (data), the runtime contributions in `src/modules/runtime.ts`, World maps' hooks via `worldMaps()` or the generator page via `genPage()` (each undefined without its slice; type-only imports). Module code that needs another module's api (or the list of runtimes) imports `src/modules/active.ts`, never `runtime.ts` (that imports every module: an import cycle). `tests/moduleBoundary.test.ts` holds the import edges at 0. A module's settings keys get no `DEFAULT_SETTINGS` entry (written only once set); its user-visible names go in its `owns.strings`, and Space- or World-maps-only help text goes inside `…` in `help.md`. Run `npm run check:release` after touching a module. Comments inside object literals and class bodies reach `main.js`: don't name a module's features in core comments there. + +### Source layout + +``` +main.ts ← export { default } from "./src/HexmakerPlugin" +src/ + HexmakerPlugin.ts ← Plugin class, thin: fields, onload/onunload, one-line delegations to services + plugin/ ← what onload used to do: commands.ts (ribbon, commands, file/editor menus), + protocolHandlers.ts (duckmage-roll, duckmage-workflow, map/hex links), + vaultEvents.ts (ONE handler per vault event, fixed step order — see its header), + startup.ts (onLayoutReady: icons, stores, note-format upgrades, upgrade notice), + settingsPersistence.ts (data.json load/save, own-write echoes, stamp) + services/ ← MapsService (map list, createNewMap options object), PaletteQueries, + HexNotesService, TemplatesService, TerrainTablesService + HexmakerModal.ts ← base class of every modal (drag, place()/section(), icon filter) + HexmakerSettingTab.ts ← settings tab (declarative getSettingDefinitions + display() fallback) + SetupWizardView.ts ← first-run setup wizard + ports.ts ← bindPorts(plugin): the module-level setters plain modules use to reach plugin state + log.ts ← logError / logWarn ("Hexmaker: " prefix); user messages go via ui/notify.ts + frontmatter.ts ← re-export barrel over maps/hexData, notes/areaStyle, tokens/tokenNotes + types.ts constants.ts ← settings/map types, LINK_SECTIONS/TEXT_SECTIONS; VIEW_TYPE_*, DEFAULT_SETTINGS + hex-map/ ← HexMapView.ts (ItemView, ~1000 lines) + the map's modals, path tool, geometry + view/ ← the map view's controllers (gridRenderer, hexPainter, mapInput, mapViewport, + mapToolbar + toolState, mapNavigation, mapShell, pathOverlay, areaOverlay, + gridLabels, neighbourShadow, backgroundCalibration, undoController, + hexWrites + coalescingWriteQueue, tokenLayer, hexContextMenu, hexSwap, …) + editor/ ← HexEditorModal's sections (TerrainIconSections, LinkSection, TextSection, + TableSections, NeighbourFlower, MapsStrip; hosts in host.ts) + hex-table/ ← HexTableView (spreadsheet of hexes) and its pickers + maps/ ← MapStore (per-hex map data, one map note per map), mapNote.ts (pure parse/write), + hexData.ts (hex getters/setters routed to the store), hexProps + hexPropsSync + (hex-note properties both ways), callouts, map tree / navigation / submaps + migrations/ ← one file per stored-format step, registry.ts, stamp.ts (dataFormat), + upgradeNote.ts / upgradeReport.ts; rules in its README.md + modules/ ← registry (data half), runtime (plugin half), active.ts (the runtimes, for module code); + world/, world-maps/, space/, gen-page/ (the generator page: GeneratorView, GeneratorPanel + + sections/ renderers (GeneratorPageCtx), library, saves, generatorPageState.ts), play/ (Solo play), + hex-flower/, packs/ (content packs) + worldgen/ ← generators, engines (procedural/, builtin/), saveFormat, previews, NewMapSetupModal + (map creation is core: New map and the wizard run generators without the page) + overworld/ space/ hexflower/ ← module code (World maps, Space, hex flowers) + random-tables/ ← RandomTableView, table parse/roll (randomTable.ts), TableStore, workflows + fields/ ← custom hex fields (#52): fields note, types, formulas, place influences (FieldsService in services/) + palettes/ ← PaletteStore (palette notes ⇄ settings), paletteNote, pathTypeTable, presets + paths/ ← PathsService (resolved chains, route cache), router, path edits, legacy readers + arrival/ ← places made on arrival, events ledgers (Solo play is src/modules/play/) + export/ ← map/hex/workflow exports (PNG, PDF, HTML, Markdown); content packs are modules/packs/ + notes/ tokens/ ← area (faction/region) note styling, frontmatter text; token notes + ui/ ← shared kit: sliders.ts, shareSliders.ts (zero-sum), pickers.ts, disclosure.ts + (Advanced dropdown, Debug, Fold), placement.ts (the placement map), notify.ts, … + md/ stores/ vault/ workspace/ ← tableRow.splitRow; NoteFolderStore base; ensureFolder; views.ts (find/open views) + hexKey.ts ← hex-key ("x_y") helpers (Lane L11, landing separately) +``` + +### Patterns + +- **Plugin = thin shell.** New plugin behaviour goes in a service (`src/services/`) or `src/plugin/`; `HexmakerPlugin` keeps a one-line delegation (integration tests and many `plugin.getMap`-style call sites rely on them). +- **Controllers take a narrow `*Host`.** Code split out of a big view/modal gets an interface listing only what it uses (`PathToolHost`, `GridRendererHost`, `HexPainterHost`, `EditorWriteHost`, `GeneratorPageHost`…), never the whole view or plugin. `HexMapView.viewFacade()` returns the members most map controllers read (all functions, read live) and each host is built as `{ ...view, …extras }`. Fake hosts in tests implement the whole interface. +- **Vault events:** `src/plugin/vaultEvents.ts` is the only place that registers vault/workspace events; each step runs isolated, in the order its header lists. Add a step in the right slot rather than a new handler. +- **Ports:** plain modules that need plugin state get a setter bound in `ports.ts` `bindPorts()`; don't add module-level state set from elsewhere. +- **Views** are found/opened through `src/workspace/views.ts`, not `getLeavesOfType(...)[0].view as …`. + +### Data model + +- **Map notes are the source of truth for map data.** `{hexFolder}/{map}/_{map}.md`, frontmatter `hexmaker-map: 6` (format history in the `mapNote.ts` header). Frontmatter = the map's settings (palette, size, parent, layer toggles, mode, seed…); `## Hexes` table (Hex | Name | Terrain | Icon | GM icons | Area | Locations | Locked); `## Paths` + `## Path routes` (named paths with anchors); a derived `## Summary`. Readers are forgiving, unknown text/keys survive rewrites. Owned by `MapStore`; parsed/written by `src/maps/mapNote.ts`. +- **Hex notes** `{hexFolder}/{map}/{x}_{y}.md` exist only once a hex gets prose or links. Frontmatter `map: "[[_]]"` plus mirrored properties `terrain`/`area`/`icon`/`name` (copies for Dataview/Bases; `hexPropsSync.ts` keeps them in step both ways, the map wins on conflict). Body: a `> [!hexmaker] Map data` callout and `###` sections (Description, Landmark, Hidden, Secret, Weather, Hooks & Rumors, Encounters Table, Towns, Dungeons, Quests, Factions, Features; `sections.ts`). Template: `src/defaultHexTemplate.md` or the user's in `templatesFolder`; placeholders `{{x}}`, `{{y}}`, `{{title}}`. +- **Palettes are notes** (`palettesFolder`, default `{worldFolder}/palettes`, `hexmaker-palette: 1`): a terrain table (Terrain | Color | Icon | Icon color | Category | Type | Impassable) and a `## Path types` table. `PaletteStore` syncs notes ⇄ `settings.terrainPalettes` (the in-memory working copy and data.json cache): edit palettes in memory + `saveSettings()`, never write palette notes directly. Presets in `src/palettes/presets.ts` and each module's `presets.ts`. +- **Other note stores:** biome notes and pools (World maps, `BiomeStore`), world types (Space, `WorldTypeStore`) — hex flowers (`FlowerStore`) — all on `NoteFolderStore`; generator notes (`worldgen/generators.ts`); token notes; faction/region (area) notes. +- **Random tables:** notes with a roll column, Result and Weight (`| d20 | Result | Weight |`, ranges like `1–16`, `—` for weight 0). Weights are core; stored ranges are what's rolled, a blank range is filled from the weights; older `| Result | Weight |` tables still read. Optional frontmatter (`rows:`, `pick: each`, …) and extra columns are row attributes (`randomTable.ts` header). Hand edits are imported by `TableStore`. +- **Workflows:** frontmatter `results-folder` / `template-file`, a `| Table | Rolls | Label | Die | Fills |` table (Die and Fills are derived, ignored on read); templates use `$label` / `$label_N` (`random-tables/workflow.ts`). +- **Settings (`data.json`)** — `HexmakerPluginSettings` in `types.ts`, defaults in `constants.ts`: folders (`worldFolder`, `hexFolder`, `townsFolder`, `dungeonsFolder`, `questsFolder`, `featuresFolder`, `factionsFolder`, `regionsFolder`, `tablesFolder`, `workflowsFolder`, `palettesFolder`, `templatesFolder`, `exportFolder`, `iconsFolder`, `logFolder`…), `maps` (per-map `MapData` minus what the map note holds: `paths`/`pathChains` are stripped by `withoutNotePaths`, hexes live only in `MapStore`), `terrainPalettes`, display prefs (`hexOrientation`, `staggerOffset`, `hexGap`, `zoomLevel`, coord/hex-name/legend options), `mapKinds`, and one-time flags (`palettesMigrated`, `pathTypesExplicit`, `tableRangesUpgraded`, `noteFormatUpgrades`, …). `dataFormat` is the data stamp (`migrations/stamp.ts`, currently 2: map data in map notes), `savedWith` the version that saved, `migrationsRun` the ids of migrations that changed this vault. `settings.pathTypes` is only read by the path-type migrations. +- **Hex geometry:** `hexNeighbors(x, y, orientation, stagger)` in `src/hex-map/hexGeometry.ts`; flat-top (default) staggers columns, pointy-top rows; `staggerOffset` odd/even (per map or global). + +### Tests + +- `npm test` globs `tests/*.test.ts` (node's own glob, so the order is fixed): a new test file runs as soon as it exists. There is no file list in package.json to edit. Integration tests stay in `tests/integration/*.integration.ts` (`npm run test:integration`). +- Tests are type-checked: `npm run typecheck:tests` (`tsc -p tsconfig.test.json`; `obsidian` resolves to `tests/__mocks__/obsidian.ts`; import mock-only members like `Notice.shown` from `./__mocks__/obsidian`). It runs in premerge after lint. +- **Tests that assert on source text read a surface, never a file path:** `readSurface("map-view")` etc. from `tests/helpers/source.ts`. A surface is a big file plus the folder its code is being split into (e.g. `map-view` = `src/hex-map/HexMapView.ts` + `src/hex-map/view/**`, `plugin` = `src/HexmakerPlugin.ts` + `src/plugin/**` + `src/services/**`, `hex-editor`, `generator-page`, …; the list is `SURFACES`). Moving code inside a surface needs no test edit. When you extract code out of a surface file, put it in that surface's folder or add the new file to the surface in the same commit. Loops over file lists use `readSource(path)`; scans that report file paths map them with `ownerFile(path)`. +- **Ratchets:** `fileSizes` (files over 800 lines are capped and may only shrink; lower the cap in `tests/fixtures/fileSizes.json` when they do; prefer new focused files over growing a big one), `importCycles` (no new cycles; the list only shrinks), `pureFiles` (listed files never reach `obsidian` at run time), `moduleBoundary` (above). + +### Key conventions + +- Folder paths normalised (no leading/trailing slashes) via `normalizeFolder()`. Links via `metadataCache.fileToLinktext(file, sourcePath)`. +- `obsidian` is an esbuild external. CSS classes use the `duckmage-` prefix (`styles.css`, CRLF: stage with `git -c core.autocrlf=false add styles.css`). +- Views, modals and helpers use `import type HexmakerPlugin` to avoid runtime import cycles. +- Paint tools patch the DOM synchronously and queue file writes through `CoalescingWriteQueue` (`hex-map/view/hexWrites.ts`): only the latest value per hex is written. Link tools are one-shot async writes. +- Modals that preload file content accept an optional `preloaded` / `initialContent` parameter so callers that already hold the content skip a vault read. +- Exclude notes whose `basename` starts with `"_"` whenever enumerating vault files for display, dropdowns, or linking. Pattern: `.filter(f => !f.basename.startsWith("_"))`. +- **Map data lives in map notes, not hex notes.** Terrain, icon, GM icons, area/region, submap/locations, name and locked are stored in the map note (src/maps). Read/write them only through `plugin.mapStore` or the `src/frontmatter.ts` getters/setters (→ `maps/hexData.ts`) — never `cache.frontmatter.terrain` etc. (the hex-note properties are copies), and never gate the read on the hex note existing (most hexes have no note). This mistake caused four separate regressions (submap rings, hex locks, editor terrain, exports) — see the KB plan note `plan-map-notes`. +- **Note-only fields survive a settings reload; missing ≠ empty.** data.json leaves out what only the map note holds (each map's `paths`/`pathChains`, via `withoutNotePaths`; hexes live only in `MapStore`). So `loadSettings` / `onExternalSettingsChange` hand out fresh `MapData` objects WITHOUT those fields, and Obsidian fires `onExternalSettingsChange` for our own saves during a save burst. Never read a missing note-only field as "empty" (`map.paths ?? []` feeding a write is the trap): `MapStore.adopt()` carries the store's copy onto fresh objects, `SettingsPersistence.loadSettings` must not `await` between swapping `plugin.settings` and `mapStore.adoptAll()`, and `MapStore.writeNote` refuses to drop every path/hex a note holds unless an edit cleared them (`clearedPaths`/`clearedHexes`). Any new field stored only in the map note needs the same treatment. Incident: 2026-10-10 paths wiped when creating a region next to a map (KB `incident-2026-10-10-path-loss-on-external-reload`; regression tests `tests/pathLossReload.test.ts`). +- **A store never reads its own write back over newer memory, and writes made before it's ready are owned, not half-done.** A fresh install's stores wait for the setup wizard (F19), so maps can be made before `MapStore` is ready: `sync()` keeps the notes this session already wrote current, and `init()` loads those through `loadOwnNote` (memory wins, hand edits folded in), never `apply`. Any new store, gate or "load from disk" step must keep that. Test both ways (stores started, and held then released), as `tests/integration/regionDataAfterCreate.integration.ts` does. Incident 2026-10-14: every region lost `submap-kind`/world/`arrival` (KB `incident-2026-10-14-region-data-after-create`). New note-folder stores extend `src/stores/NoteFolderStore.ts` (one queue for reads and writes, so a hand edit is read before a write that follows it). +- **Stored formats change only through `src/migrations/`** (owner MG7). Any change to what the plugin stores (data.json keys, map/hex/palette/table/workflow/token/generator note formats, names written into notes) adds a migration file there, one per step, named `v-.ts` (or `map-note--to--…`, `unreleased-…`), with its `info` (one-sentence `change`, `recordedBy` flag) and an entry in `registry.ts` — never an upgrade inline in a store or view. Back up before rewriting notes (`src/backup.ts`), keep readers of every old form forever, re-plan notes edited since they were read, and update `tests/migrationGolden.test.ts` when the 1.5.6 upgrade's result changes on purpose. A vault from any released version must still have a path forward. Bump the data stamp (`DATA_FORMAT` in `src/migrations/stamp.ts`) when an older build would misread the new data. Changes are recorded in `migrationsRun` and reported in the upgrade note. Rules and the step list: `src/migrations/README.md`. +- **All modals must extend `HexmakerModal`** (`src/HexmakerModal.ts`) rather than Obsidian's `Modal` directly. `HexmakerModal` is the single place for shared modal behaviour (drag, `place(id, el)` / `section("advanced")` placement, `addIconFilter`). Any functionality needed by more than one modal belongs there, not in `utils.ts` or duplicated across files. +- All modals call `this.makeDraggable()` in `onOpen` (inherited from `HexmakerModal`), which adds the `duckmage-editor-modal-drag` class and locks dragging to the title-bar area. (`FileLinkSuggestModal` is the sole exception — it extends `SuggestModal` and cannot inherit from `HexmakerModal`.) +- **Placement, not feature levels.** Where a control sits (main / more / advanced / debug / hidden) comes from `src/ui/placement.ts`; use `place()` / `section()` (modals, pages) and the settings-tab equivalents. Same concept, same shared control: weights/shares that sum to a whole use `ShareSliders`, single values `ui/sliders.ts`, lists `ui/pickers.ts`, groups `Fold` (`ui/disclosure.ts`). +- **NEVER interleave layout reads (`offsetWidth/Height/Left/Top`, `getBoundingClientRect`, `getComputedStyle`) with DOM writes (`createDiv`/`createEl`/`appendChild`/`setCssProps`/style changes) inside a per-hex loop.** Each read after a write forces a full synchronous layout flush → O(n²) thrash. On large maps (chult = 3843 hexes) this stalled the main thread for ~20s on open (regression in `renderCoordLabelsLayer`, commit 10475fd; fixed by batching). **Pattern:** read ALL geometry into a plain array first, THEN do all DOM writes. The overlay/label builders in `src/hex-map/view/` (`pathOverlay`, `areaShapes`, `gridLabels`, `neighbourShadow`) are the hot path and follow read-then-write — any new one MUST too. Reproduce/validate with `dev/coord-label-thrash-bench.{html,mjs}`. +- **Hit tests live in the drawing's units.** The map's zoom is baked into the grid's font size, so anything placed in em/% follows it but geometry measured in px at render time goes stale. A pointer→cell lookup must re-measure or rescale cached px geometry by the em ratio, and be tested at several zoom factors. Data writers (`createRegion`, `setBiomeAt`, …) refuse coordinates outside the map rather than trusting the UI. (Incident 2026-10-12: region hover said "No region yet" and a click made a region off the map; KB `incident-2026-10-12-region-hit-test-drift`.) +- **Sandboxes are hidden.** Visual and e2e checks run in a throwaway vault via the fresh-eyes `sandbox.mjs` (`C:/Users/markr/work/tools/skills-share/ux-testing/fresh-eyes-tester/scripts/`), which starts Obsidian on its own hidden Windows desktop by default (`--visible` or `SANDBOX_VISIBLE=1` to watch). Never run the plugin against the main vault, never kill Obsidian by name; check `otherObsidianBefore == otherObsidianAfter` after `stop`. + +### Obsidian directory review in CI (never via the dashboard by hand) + +Every branch push runs Obsidian's automated review (preview scan) in CI, and +master releases are gated on it, then the published release scan is watched +(`.github/workflows/obsidian-review.yml`, `release.yml`, `dev/obsidian-review.mjs`). +**When an "Obsidian review" job fails, follow the Runbook in +`.github/OBSIDIAN_REVIEW.md`**: the failure message names the entry. The +common one is an expired session: the fix is `npm run obsidian:login` +(opens a browser, user logs in if asked, it sets the +`OBSIDIAN_COMMUNITY_COOKIE` secret), then re-run the job. Use +`gh` as `sbuffkin` (`GH_TOKEN=$(gh auth token --user sbuffkin)`) for this repo. + +### Obsidian reviewer-bot conventions (enforced beyond what eslint catches) + +The obsidianmd reviewer flags patterns the locally-installed +`eslint-plugin-obsidianmd` doesn't have rules for. Watch for these +in any new code; failing these means another bump-and-fix cycle. + +- **Keep `eslint-plugin-obsidianmd` AND `typescript-eslint` current.** The + reviewer bot runs the LATEST versions; stale pins let findings through + local lint twice on 2026-08-09 (obsidianmd 0.1.9 → 22 `prefer-create-el` + sites; typescript-eslint 8.58 → 6 unnecessary-assertion sites its newer + "receiver accepts the original type" check catches). When reviewer + warnings arrive that local lint missed, first `npm view version` + vs `npm ls ` for both packages and upgrade. +- **`prefer-create-el` + `@typescript-eslint/no-unnecessary-type-assertion` + are now enforced locally** (plugin 0.4.1 + type-aware rule in + eslint.config.mjs). Use `parent.createEl/createDiv/createSpan` (or the + global `createEl` for genuinely detached elements), never + `document.createElement`/`activeDocument.createElement`. +- **Settings tab is declarative (Obsidian ≥1.13).** `HexmakerSettingTab` + implements `getSettingDefinitions()`; on 1.13+ the tab renders FROM THE + DEFINITIONS and `display()` is never called (it remains only as the + pre-1.13 fallback). The fallback draws the SAME definitions + (`display()` → `renderDefinitions`), so a new setting goes in + `getSettingDefinitions()` only, tagged with its `Settings.` + placement id, and one placement entry places it on both paths. Local `obsidian` typings are 1.12 — the + 1.13 shapes are mirrored as local interfaces in HexmakerSettingTab.ts; + delete them when the package is bumped. +- **CSS lint "css-clip-path partially supported" warnings are accepted** — + our clip-paths are basic `polygon()` hex shapes, fully supported in + desktop Electron, and the plugin is `isDesktopOnly`. Don't churn on them. + +- **`document` / `window` → `activeDocument` / `activeWindow`.** Required + for popout-window compatibility. Globals are listed in `eslint.config.mjs`. + Use `activeDocument.createElementNS(...)`, `activeDocument.body.createDiv(...)`, + `window.setTimeout(...)` is OK but prefer `activeWindow.setTimeout(...)` + inside view code where popouts could fire it. +- **Dynamic CSS: never `.style.foo = …` or `setCssProps({ transform: … })`.** + The local eslint rule (`obsidianmd/no-static-styles-assignment`) is + promoted to an error to catch this. The pattern is: declare the + `transform` / `opacity` / etc. in CSS using `var(--duckmage-..., default)` + fallbacks, and write the dynamic values to the custom properties from + JS. See `.duckmage-bg-image-layer`, `.duckmage-hex-map-grid`, + `.duckmage-hex-map-viewport` for the canonical examples. +- **`setDynamicTooltip()` is deprecated.** The slider value is now always + shown inline. Drop the call from any new `.addSlider(...)` chain. diff --git a/README.md b/README.md index 768805dd..e4465a03 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # Hexmap World Creator -An Obsidian plugin for tabletop RPG hex-map world-building. Each hex on the map is a Markdown note in your vault — attach terrain, locations, paths, and prose directly to the geography of your world. +A hexmap maker and hexcrawl toolbox for Obsidian, for any TTRPG. Each map is a note in your vault, and any hex can get its own Markdown note — attach locations, paths, and prose directly to the geography of your world. ![A populated hex map showing multiple terrain types, icons, and drawn paths](docs/Hero.PNG) @@ -8,41 +8,50 @@ An Obsidian plugin for tabletop RPG hex-map world-building. Each hex on the map ## What it does -Hexmaker gives you an interactive hex grid that lives inside Obsidian. Paint terrain, draw roads and rivers, link town and dungeon notes to individual hexes, overlay faction and geographic region fills, drill into submaps, roll random encounters, and browse everything in a spreadsheet view — all without leaving your vault. Every hex is a plain Markdown file you own. +Hexmap World Creator gives you an interactive hex grid that lives inside Obsidian. Paint terrain, draw roads and rivers, link town and dungeon notes to individual hexes, overlay faction and area fills, drill into submaps, roll random encounters, and browse everything in a spreadsheet view — all without leaving your vault. Your map and every hex note are plain Markdown files you own. ### Hex editor -Right-click any hex to open the editor: set terrain, override the icon, link Towns, Dungeons, Features, Quests, Factions, and Encounters Tables, and write freeform notes (Description, Landmark, Hidden, Secret, Weather, Hooks & Rumors). A 🎲 button on each section lets you roll any random table and append the result inline. Link a submap to the hex and click the center dot in the hex flower to dive into it. +Click any hex to open the editor: set terrain, override the icon, link Towns, Dungeons, Features, Quests, Factions, and Encounters Tables, and write freeform notes (Description, Landmark, Hidden, Secret, plus Weather and Hooks & Rumors). Roll a table from the editor and **Add to this hex** puts the result in the section you pick. Link a submap to the hex and click the center dot in the hex flower to dive into it. There is no Save button: the editor saves a moment after you stop typing ("Saving shortly…", then "✓ All changes saved"), and closing it saves straight away. On space maps (a palette with space terrain types, or a map under one) the link sections show as **Settlements**, **Sites**, **Points of Interest** and **Missions** in the editor, the hex table, the badge legend and exports; the note keeps its usual headings. The words come from the map type, so another map type could bring its own. ![The hex editor showing terrain, links, and notes for a single hex](docs/Editor.PNG) ### Terrain painting -Switch to the Terrain tool, pick a colour from your palette, and drag across hexes to paint. Choose a 1×, 3×, or 7× brush for broad strokes. An eyedropper lets you sample an existing hex's terrain as your active brush. +Switch to the Terrain tool, pick a color from your palette, and drag across hexes to paint. Choose a 1×, 3×, or 7× brush for broad strokes. An eyedropper lets you sample an existing hex's terrain as your active brush. ![Terrain being painted across multiple hexes with the drag brush](docs/TerrainPaint.gif) ### Path drawing -Click the Path button to open the path picker. Select any defined path type — road, river, or anything you've created — then click hexes to lay down a chain. Each type has its own colour, width, line style (solid / dashed / dotted), and routing mode (through hex centres, meandering between them, or tracing hex edges). Edit types at any time from the map toolbar. +Click the Path button to open the path picker. Select any defined path type — road, river, or anything you've created — then click hexes to lay down a chain, or turn on **Auto-route** and click a start and an end to let the path find its own way around impassable terrain. Each type has its own color, width, line style (solid / dashed / dotted), and routing mode (through hex centres, meandering between them, or tracing hex edges). Edit types at any time from the map toolbar. ![A road path being drawn hex by hex across the map](docs/PathDraw.gif) ### Random tables -A two-panel view for rolling and managing weighted random tables. The left panel shows your tables folder as a collapsible folder tree — the same structure as your vault. Click any table to load it, hit Roll to highlight a result, and see percentage odds for every entry. Create new table files from the toolbar, edit entries inline, and chain tables together into multi-step **workflows** that fill a template note with rolled results. +A two-panel view for rolling and managing weighted random tables. The left panel shows your tables folder as a collapsible folder tree — the same structure as your vault. Click any table to load it, hit Roll to highlight a result, and see percentage odds for every entry. Create new table files from the toolbar, edit entries inline (the editor has Roll / Result / Weight / Odds column headers and opens with the cursor in a new row, not the table's name; a table is titled as the links to it read, so a terrain's encounter table is "forest encounters" everywhere), and chain tables together into multi-step **workflows** that fill a template note with rolled results. ![Rolling on a random table and seeing the result highlighted](docs/RandomTable.gif) +### Hex fields +Your own data on every hex: population, land value, a ruler, "has a ford"… Declare the fields once per world in **Settings → Hex fields** (or by hand in the note `Hex fields.md` in the world folder): each has a name, a type (number, whole number, text, yes/no or choice), a default, and either a random table to roll or a formula over the hex's other fields (`Population / 20`). + +- **Rolled when a hex gets terrain** (painted, generated or explored). A table row's **When** can say `near: town 2` (a town within 2 hexes). +- **Places change them:** each place type (town, city, camp, settlement, or your own) can add or multiply a field on its own hex (**Here**: `+400`, `x1.5`, `=yes`) and on the hexes within a radius (**Nearby**: `+40%`, fading with distance). A hex is a town when its terrain is called Town (or its terrain type is a settlement type), or its note links a town note under Towns (the town note's `place-type:` property names other types: `place-type: city`). +- **Recalculate fields** redoes a map after you add places. +- **Edit** them in the hex editor's **Fields** section (Build mode; Play shows them read-only), and sort and filter by them in the hex table. +- They are stored as columns of the map note's `## Hexes` table, named like the field, plain values; edits made to those columns by hand or by a script are kept. A "Field rolls" column remembers each roll before places changed it. + ### Hex table view A scrollable spreadsheet of every hex note — one row per hex, columns for terrain, description, towns, dungeons, features, quests, factions, encounters table, and all the freeform sections. Click any cell to edit it in place. Filter by map, terrain type, or the presence of specific link types. The ◎ button jumps the map view to that hex's position. ![The hex table view showing a grid of hex notes with populated columns](docs/Table.PNG) -### Faction and region overlays +### Faction and area overlays -Paint translucent colour fills over hexes to show political control or geographic regions. Adjacent hexes of the same faction or region merge into smooth blobs with a rendered legend. Toggle overlays from the map overlay panel; overlay state is saved per map. +Paint translucent color fills over hexes to show political control or named areas (a basin, a kingdom). Adjacent hexes of the same faction or area merge into smooth blobs with a rendered legend. Toggle overlays from the map overlay panel; overlay state is saved per map. ### GM layer @@ -53,7 +62,7 @@ Toggle the GM layer from the overlay panel to switch between player-facing and G ## Manual Installation 1. Download `main.js`, `manifest.json`, and `styles.css` from the [latest release](https://github.com/sbuffkin/hexmaker/releases/latest). -2. In your vault, create the folder `.obsidian/plugins/hexmaker-plugin/`. +2. In your vault, create the folder `.obsidian/plugins/hexmaker/`. 3. Copy the three downloaded files into that folder. 4. In Obsidian, open **Settings → Community plugins**, find **Hexmap World Creator** in the list, and enable it. @@ -61,19 +70,21 @@ Toggle the GM layer from the overlay panel to switch between player-facing and G ## Getting started -After enabling the plugin, do this once before you start mapping: +After enabling the plugin, a **setup wizard** opens. It asks what you'll map (a fantasy world, space, or both), where your world folder lives, and makes your first map. What it installs follows that choice: a world setup gets the Expanded and Limited palettes and the biome notes; a space-only setup gets the three space palettes (Sector, System, Planet) and nothing fantasy, and **Palette for new maps** starts on Space - Sector; both gets both. Turning a map type on later in **Settings → Map types** installs its content then (once: anything you delete stays deleted). A map type that's off only hides its generators, palettes and icons: its maps still open, and opening one from the Maps list or a hex's region menu asks whether to turn its type back on (**Not now** keeps it off for the session). Making a new map never turns a type on. Nothing is installed at startup: a vault set up without the wizard keeps exactly the palettes it has. That last step asks **What are you mapping?** (Overland or Biomes for a world; Sector or system, or Planet, for space; only the types you picked show), which sets the starting size and palette, then lists the generators for it, always with **Blank** first, so it can **generate the terrain** for you with a preview and a **Reroll** button, or start blank for painting by hand. **Biomes** makes an overworld, as **Maps → New overworld…** does: each hex opens into an 8 × 8 region that blends with its neighbours. A region is made when you first go to its hex; tick **Make every region now** (in **Advanced**) to make them all at once. The generator's options (water, climate and so on) sit right under it; its **Advanced** dropdown holds a few sliders that change the layout most (feature size, hills, warmth…), each with its default and a reset. The grid size steps with the mouse wheel while the pointer is on it (or it has focus), and **↺** puts it back to the scale's size. It also creates the terrain description and encounter tables. That's all you need to start. + +To set things up by hand instead (or later): ### 1. Set your world folder -Open **Settings → Hexmap World Creator** and enter a root folder name in **World folder** (e.g. `RPG/world`). This is the base for all other folders. +Open **Settings → Hexmap World Creator** and enter a root folder name in **World notes folder** (under **Setup**, e.g. `RPG/world`). This is the base for all other folders. ### 2. Generate folders -Click **Generate folders**. This fills in the hex, towns, dungeons, tables, and other folder settings with sensible defaults under your world folder and creates them in your vault. Any field you've already filled in is left untouched. +Open the **Advanced** dropdown near the bottom, then its **Folders** section, and click **Generate folders** (the **Set up folders** row). This fills in the hex, towns, dungeons, tables, and other folder settings with sensible defaults under your world folder and creates them in your vault. Any field you've already filled in is left untouched. ### 3. Open the Hex Map -Click the map icon in the left ribbon (or use the command palette: **Open Hexmaker hex map**). You'll be prompted to create your first map — give it a name, choose its size, and pick a terrain palette. +Click the map icon in the left ribbon (or use the command palette: **Hexmap World Creator: Open hex map**). You'll be prompted to create your first map — give it a name, choose its size, and pick a terrain palette. ### 4. Generate terrain tables -Once your folders are set, go back to **Settings → Hexmap World Creator** and click **Generate terrain tables & hex links**. This creates a description and encounters table file for every terrain type and links them into any existing hex notes. It's safe to run again at any time. +Once your folders are set, click **Generate** on **Generate terrain tables & hex links** (at the top of the same Advanced dropdown). This creates a description and encounters table file for every terrain type and links them into any existing hex notes. It's safe to run again at any time, and it's the fix whenever a table or table link is missing: a roller, roll window or workflow that can't find its table, or a hex editor link to a note that isn't there, says so and points here. You're ready to start mapping. @@ -84,43 +95,176 @@ You're ready to start mapping. ### Hex Map view An interactive hex grid rendered as an Obsidian panel. -- **Left-click** a hex to open (or create) its note. -- **Right-click** a hex to open the hex editor. +- **Left-click** a hex to open the hex editor. +- **Right-click** a hex for its menu: its region and locations first (**Enter region: …**, **Open: …**), then centre on it, **Copy link to this hex**, open its note, **New map from this hex…** (**Add another map…** once the hex has one), link an existing map, link a table, swap hexes, create a token here, **Add to play log…**, clear terrain. Right-clicking a token that covers a hex gives the token's items and then the hex's, under **This hex: …**. - **Pan** by clicking and dragging with the left or middle mouse button. - **Zoom** with the scroll wheel. - **Expand** the grid with the `+`/`−` buttons at the map edges. -- **Go to hex** (`⌖` button in the toolbar) — enter coordinates to centre the view on a specific hex. -- **Undo / Redo** (`↩` / `↪` buttons) — step back or forward through terrain and icon paint operations. +- **Center hex** (in the drawing tools panel, the pencil on the map's right edge) — enter coordinates to centre the view on a specific hex. For a hex you can see, right-click it → **Center on this hex**. +- **Undo / Redo** (`↩` / `↪` buttons, Ctrl/Cmd+Z) — step back or forward through this map's changes made in its current work mode (one queue per map per mode; see **Work modes** below). ### Maps Organise your world into multiple named hex maps, each stored as a subfolder under your hex folder. The active map name is shown in the top-left of the toolbar as a dropdown button. -- **Switch** — click the map name button to open the maps panel, then click any map in the list to make it active. -- **Create** — enter a name, choose a grid size and terrain palette, then click Create. -- **Rename** — update the name field and click Rename; all hex notes in the folder are moved automatically. +- **Switch** — click the map name button to open the maps panel, then click any map in the list to make it active. The list is a tree: submaps sit under the map they came from, and neighbouring regions are grouped together. Click ▸ / ▾ to fold a branch; with more than 10 maps a search box finds a map by name. +- **Create** — enter a name, choose a grid size and terrain palette, then click Create. The map keeps the name as you typed it ("Barony of Saltmere"); its folder and map note use a lower-case, dashed version (`barony-of-saltmere`). +- **Name** — change the name shown everywhere. Nothing moves on disk. The name is stored as `display-name:` in the map note. +- **Stagger offset** and the map's **arrival** and **generator tables** settings. +- **Background image** — one row: **Pick image…** or drop an image on it, **Clear**, opacity and calibration. - **Delete** — removes the map and moves all its hex notes to the trash. -- **Terrain theme** — assign a terrain type to a map. The swatch appears next to the map name in the switch list and sets the colour of the submap center dot when this map is linked as a submap from a parent map. +- **Missing maps** — if a map's folder and map note are deleted by hand (outside the plugin), the map is not quietly re-created empty. It shows in the list with a ⚠ and two buttons, and opening it shows the same: **Restore** writes its map note back from the last saved copy (the plugin keeps one in its folder, `map-cache/`, every time it saves a map note), so its hexes, paths and settings come back exactly; **Remove** drops it from the list (no files are deleted). A note put back by hand (or by sync) loads again on its own. +- **Advanced** (the dropdown at the bottom of Properties): + - **Terrain theme** — assign a terrain type to a map. The swatch appears next to the map name in the switch list and sets the color of the submap center dot when this map is linked as a submap from a parent map. + - **Weather and rumours** — the tables the hex editor rolls for Weather and Hooks & Rumors on this map (stored in the map note as `weather-table` and `rumors-table`). + - **Folder name** (in its **Debug** section, debug mode only) — rename the folder itself; its hex notes and map note move with it and links to the map are updated. +- Right-click a map in the list → **Advanced** for **Open generator** and **Make generator from this map…**. - **Back** (`← Back` button) — returns to the previously active map after following a submap link. -### Hex editor (right-click menu) +### Generators +Maps can be generated instead of painted hex by hex. When you create a map (**Maps → New map…**, or the setup wizard's first map) or a submap (right-click a hex → **New map from this hex…**), pick a generator and preview it before creating. A new map first asks **What are you mapping?**, as the setup wizard does: the scale sets the size and palette and lists its generators (submaps, regions and a map placed **Next to** another skip it). Then **Terrain**: **Generate it now** (the generator list), **Explore as you go** (see **Exploring with hex flowers**) or **Blank** to paint it all yourself. A new map starts on Overland (Star scatter for space-only setups). The list has a search box on top and scrolls inside a fixed height: starred (☆ on a row) and recently used generators first, then the built-in engines and your own, then the shipped **Biomes**, **Blends**, **Planets** and **Presets** and your subfolders as groups that start closed (a search opens the ones it finds). One line each, with a small *learned*, *blend* or *continues* tag; the picked one shows its description. The generator's options (water, climate, relief, sea, path types…) sit under the list. **Stagger offset** is under the form. Its **Advanced** dropdown has the starting coordinates, a background image (picked from the vault or dropped from your computer), the generator's tuning sliders (the few that change the layout most, each with its default and a reset), **Make every region now** for a Biomes map and, for a submap, the **Use this … for new submaps of hexes** boxes. The **folder name** (made from the name) is in its Debug section. A new submap is named after its hex, or its terrain and coordinates ("Barren world 12, 5") if the hex has no name, with " (2)" added if another map already has that name; click the name once to select it all and type your own. A palette a new map installs, and generated paths with no matching path type on the new map's palette (an orbit crossing a planet), are handled quietly, with no notice. + +- **World biomes** — an overworld: one biome per hex, laid out by temperature, moisture and height, with transition biomes (taiga between tundra and forest, savanna between jungle and badlands) where two shouldn't touch. Its hexes open into regions that blend with each other. +- **Overland** — a region from noise: seas, coasts, plains, forests, hills, mountains. Set water %, climate, and which side the sea is on. It draws your path types too: one row per path type (roads, rivers or any you've made), each set to how many (Auto picks by map size; None turns it off). Rivers run from high ground to water, roads join towns or cross the map. Paths from a neighbouring map still carry on across. +- **Explore as you go** (New map's **Terrain** choice, not a generator) — starts the map blank and fills each hex as the party explores, from the generators you pick to power it (see **Exploring with hex flowers** under Tokens). Hex flower notes of your own live in `{world folder}/hex flowers` (**Settings → Hex flowers folder**, in Debug). +- **Region detail** (submaps) — zooms into the parent hex: its terrain fills the map and each neighbouring hex shapes the matching edge, with that neighbour's own terrain (evergreen next to evergreen) along it; a land neighbour always shows as at least a small strip or corner patch on its side (a swamp to the south-west, say). +- **Star scatter**, **Orbits**, **Planet surface** (space maps) — a star sector, a star system around its star, and a planet's surface. They place terrain by type only: Orbits puts the star-type terrain in the middle, world / gas giant / asteroid belt types on the rings, moon-type terrain beside planets (a system with a planet always has at least one; the map draws a faint dashed tether from each moon to the world or gas giant beside it, hidden with the paths; the PNG export draws it too when it includes paths), a starport and station beside the main world, and a jump point and comet past the last orbit; the Star choice lists your palette's own stars. Space palettes made before these types existed are retyped once on load ("moon" typed world becomes moon, "jump limit" typed void becomes jump limit, and so on). +- **World types** — which worlds Star scatter and Orbits place and how often, and what each world's own map is made with, as an editable table note in `{world folder}/world-types`. Star scatter and Orbits roll on it: their **World types** option picks the table (**Default**: Default space, or your first table if you deleted it; **None**: equal odds over the palette's worlds, stars and planets, and the generator says so). **Default space** ships with the same odds the two generators used before they read the table (the draws differ, so an old seed gives a different map); **Restore default** puts it back. Each row is a world (a terrain of your palette) with a **Weight** (decimals are fine) and optional limits: **Map** (sector for Star scatter's systems, system for Orbits), **Orbit** (inner, habitable, outer, or rings like `2–4`), **Stars** and **Temperature** (the generators don't know a temperature yet, so it limits nothing there). A sector row's **Mainworld** names the body Orbits makes that system's mainworld (`ocean world` → `ocean planet`; blank: the world itself, if the system palette has it). No generator guesses anything from a terrain's name any more. A row can also say how that world's map is made: **Size** (`20×14`, or a range like `16–24 × 10–14` rolled per world), **Generator**, **Options** (`water=85, climate=lush`; the editor shows these two only in debug mode, the note always has them), **Palette** and **Base** terrain (Default space opens its planets on the **Space - Planet** palette). The same world can have several rows, so an ocean planet can be likelier and bigger around a yellow star. A row whose world isn't a terrain of the palette being generated is never placed, and the generator's warnings (and the editor's preview) name it. If no row fits the palette at all, the generator uses equal odds and says so. Edit it as text, or with **Edit world types…** (in the Star scatter and Orbits options, or the command): add, remove and reorder rows. The preview rolls for a palette (and, in debug mode, a chosen map, orbit, star and number of rolls) exactly the way the generators do, so the odds it shows are the odds you get. The same note has two more tables, each under its own heading: **Stars** (which star Orbits puts in the middle when its Star choice is Random, with a **Weight** each; red dwarfs are the most common) and **Sector features** (Star scatter's special hexes, each with a **Chance** per star system hex such as `1 in 50`, `2%` or `never`; Default space has a deep-space station 1 in 50, an anomaly 1 in 75 and a black hole 1 in 150, the 4% Star scatter has always used). The editor has a tab for each table, each with its own preview. Notes made before these tables existed get the shipped ones added once, and notes made before the Mainworld column get the shipped sector worlds' mainworlds filled in once (after a backup; a Mainworld you typed is never changed). Changes in the editor save automatically, like the hex editor (there is no Save button): a moment after you stop typing, and when you close it. A row that isn't finished yet (no world, or a value it can't read) is marked incomplete and isn't saved; it stays in the editor until you fix or remove it, and is dropped when you close it. Edits you make to the note by hand while the editor is open are kept. Rows that can't be read are reported and left in the note as written. Editing needs Build or God. +- **Space tables** — **Hexmap World Creator: Convert world types to tables** (or the button in a space map's properties) turns each World types note into ordinary random tables in a tidy tree under `{tables folder}/space//`: `Sector/Charted sector`, `Sector/Unexplored sector`, `Sector/Mainworlds`, `Sector/Uncharted`, `System/Stars` and `System/Inner orbits`, `Habitable orbits`, `Outer orbits`. They give the same odds the note did (different draws) and keep each row's Mainworld, Size, Generator, Options, Palette and Base as columns. The World types note is backed up first and kept: it gets a **Tables** list (role → table; edit a link to swap a table) and the tables embedded below it so they can be rolled there. Converting again changes nothing, and a table that already exists is never overwritten. An unconverted note keeps working as before. **Unexplored sector** leaves half its systems unknown: those rows have **Roll** `on arrival`, so the hex shows its **Shown as** terrain (a star system) or nothing (uncharted) and the map note's Hexes table gets an **On arrival** column naming the table to roll later. +- **Generator tables** (map properties) — one select per role: the table used for this map and every map under it. Unset follows the map above, then the role's default. Stored as plain keys in the map note (`sector-hexes-table: "[[…/Unexplored sector]]"`, `names-table: "[[Star names]]"`). + - **Names** (every map): maps made from a hex here (regions, locations, and submaps made on arrival) are named from this table, rolled with the hex's terrain and type as When context. A hex's own name still wins; with no table the name is the hex's terrain and coordinates. + - Space maps add Star scatter's and Orbits' roles. **Moons** (how many moons each planet gets: `none`, `1`, `2`…; a When column tells gas giants from rocky worlds) and **System extras** (starport, station, jump point, comet, each on its own Chance, **Where** beside the mainworld or outside) are optional: unset, they roll on the shipped tables in `space/Orbits/` (editing those changes the odds), which give the odds Orbits always had. An extra's Result can be a terrain or a terrain type, so they work on any palette. +- **Biomes and presets** — Grassland, Temperate forest, Taiga, Tundra, Alpine, Badlands, Savanna, Jungle, Swamp, Karst, River delta, Coastal fjord, Archipelago, Deep forest, Valley and Volcanic. They place terrain by terrain *type*, so they work with Limited, Expanded, or your own palette (as long as its terrains have types). On Limited, terrain kinds it lacks fold into the nearest one (marsh becomes grass, peaks become mountain). Streams and trails are drawn as your River and Road path types if you have no stream or trail type. +- **Learned generators** — made in the **Terrain generator** view (command palette: **Hexmap World Creator: Open terrain generator**) by learning from maps you've already painted, or by blending several. The page keeps the everyday controls on top (size, shape, guarantees, terrain mix, path types, then the generator's own name and palette). The **Terrain mix** lists only the terrains in the mix, as the biome page's Type mix does: **×** takes one out (bias ×0), **+ Add terrain** puts one back at ×1; its collapsed **Advanced** dropdown has **Engine tuning** (clumping, edge smoothing, small patches, rare terrain, edge strength, directional bias, scatter, spacing, randomness, near rules, mix strength), **Paths** (each path type's single routes: count, as, wiggle, length, follow terrain, avoid impassable) and **Seed** (the preview's seed and its lock). Headers count what's moved off its default (**Advanced · 2 set**, **Engine tuning · 2 set**). Each save keeps its seed, shown in the saves list. On a biome's page the preview seed is under Advanced → Seed too. + +**Regions and locations.** A hex can open into maps of its own: any number of **locations** (a town, a dungeon, a ship: each with its own size and palette) and one **region** (the hex itself, up close). Right-click a hex → **New map from this hex…** and pick Region or Location; a short line under each says which is which (on space maps: a star system, planet or station is a Location). If the hex already has maps, the dialog lists them first with an **Open** button each, and the menu item reads **Add another map…**. Inside a submap, the breadcrumb ends with what its hex was on the parent map ("from: barren world"). The first region of a map asks once for its **region settings**: hex flower (7, 19, 37, 61 or 91 hexes) or rectangle (6×6, 8×8, 10×10 or custom), palette and blend width. Every region of that map uses them, so they line up; they are fixed once a region exists (the map menu's **Regions** tab shows them, with the list of regions; blend stays editable). The right-click menu shows the region and up to two locations by name; from three on, **Locations (n)…** opens a list to search, open, unlink and reorder. Every submap made before this is a location; nothing about it changes. + +**Arriving somewhere new** (optional; off unless you turn it on). In a map's properties, **Arriving somewhere new → Make the submap, in any mode** (maps under it follow unless they set their own; stored as `on-arrival: make submaps` in the map note; the older `make places` still reads). Then right-click a hex that has no map → **Go there** (or Ctrl+click it): its On arrival table, if it has one, is rolled with the map's `seed:` (the same world gives the same result), what came up is written onto the hex (the sector learns what the system is), and the hex's map is made at once with no form and no preview: from the rolled row's Size, Generator, Options, Palette and Base, else the palette's submap settings, else the usual defaults. It works in Play, opens in the mode you were in, and the new map's note gets a plain-text **## Arrival** section (what was rolled, how the map was made). Until you lock it, the bar beside the mode switch offers **Reroll** (same setup, next seed; the map's terrain and paths are replaced) and **Lock**; after the lock (`arrival: locked`) only God mode can reroll it. Visiting again never rolls again, and a locked hex is never arrived into. **New map from this hex…** in Build still opens the form, starting from the same rolled row. On an **overworld**, going to a hex that has a biome but no region yet (click it, or right-click → **Go there**) makes its region the way the Biome painter does, from the hex's biome, seeded from the overworld's seed and with no form; it gets the same **Reroll** / **Lock** bar and rules (Reroll makes it again with the next seed; locked hand-painted hexes stay). Hexes whose On arrival roll is still to come show a small **?** (layers menu → Labels → **Uncharted (?)**, on by default). + +**Once-only rows** (optional). A table row whose **Once** column says `per world` or `per map` can come up only once; leave it blank for a row that can repeat. When a roll made by the map (arriving, or a generator such as Star scatter) lands on one, it is written as a row of a plain **## Events** table (`| Event | Where | When | From |`): in the top map of the map tree for `per world`, in the map's own note for `per map`. From then on that row is left out of the roll and the other rows' odds grow to fill in (the same as "roll again if you get it" by hand). Delete a row from **## Events** to make the event possible again. Rerolling a place takes out the events its old landscape found. Rolls you make by hand in the Random Tables view or a roll block aren't tracked: a once-only result says "once per world: not tracked here". + +**Rectangle regions join up.** Rectangles are laid like bricks: each region sits in its own slot of one grid shared with the regions around it, so walking off a region's edge (or clicking the dimmed hexes past it) lands in the next region at the right hex, and a hex flower on the toolbar shows all six neighbours in their directions (hover a petal for its name, click to go there). On a narrow pane the toolbar wraps onto a second line instead of squeezing, so nothing on it overlaps. An empty petal shows **+** ("New region to the north-east"): click it to walk into new land. It opens **New land to the north-east**, which is **Edit region…**'s new-region mode (below): pick the biome that lies there, or **Roll biome** (the seed is named, so a roll can be repeated, and can be typed in the Debug section; **Reroll** keeps the biome and tries a new seed), mix biomes, set the blend and **Neighbour influence**, check the live preview of the new region blended with every region around it, and **Create and go**. It starts on your region's own biome. A biome different from yours makes border country between the two. If that hex is past the overworld's edge, the overworld grows by a hex to fit it. The hex editor's neighbour flower offers the same walk on the hexes past a region's edge. Making a region needs Build or God; in Play the **+** is greyed out and says "Switch to Build to make a region." A new region is made from a short form: **New region** (Edit region… for a region not made yet): the biome tiles (starting on the hex's biome), **Mix biomes…**, blend, **Neighbour influence** and **Reroll** (how wiggly the borders are and the seed are in the Debug section), with a live preview of the region against its neighbours. Nothing is written until **Create**, which makes exactly what the preview shows; **Cancel** or × writes nothing. It blends with the overworld around it, and the regions already made around it are fixed ground it's made to fit: their hexes a few rows deep are read as context, so a coastline, a forest or open water carries on across the seam the way it lies next door (a coast whose land is on the right of the region above continues on the right), whatever order you make regions in, and whether the region is inside the overworld or past its old edge. Right at the seam, a hex whose neighbours across it are clearly land (or water) becomes land (or water) too, so a coastline carries on instead of stepping a hex sideways. Only the new region's own hexes are written. The neighbours count most at the seam and fade a hex or two in, and the region then keeps its own biome: its terrain is brought back to its biome's Mix, the hexes farthest from the seams first, while about half the seam keeps the neighbours' terrain running in and land and water at the seam never change. So Alpine set among forests gets its mountains and peaks, with the forest reaching into its edges. How deep, how strongly and how far in the neighbours count, and how fully the Mix is kept, are per biome (**Neighbour context depth**, default 3 rows; **Neighbour influence**, default 1; **Neighbour fade**, default 1 hex; **Keep the mix**, default 1; **Seam band keeps neighbours**, the share of the hexes right at the seam that keep the neighbours' terrain, default 0.5, higher for smoother seams and lower for more of the region's own biome; influence 0 makes regions the way they were before), in the biome page's Debug section under Borders & transitions. If the parent hex has no terrain yet, it gets the region's main terrain (painted hexes are never changed). Hex flowers can be set up but don't join their neighbours yet. + +**Overworlds.** **Maps → New overworld…** (or the command **Hexmap World Creator: New overworld…**) makes a map of biomes with the **World biomes** generator: rectangle or hex-shaped, a climate, water, land and which way is colder, previewed as a small map of biomes with transition hexes outlined in white and the river in blue. Pick the region size, and tick **Make every region now** to have them all made at once (the **Regions** tab's **Make the missing regions…** does the same later, with progress and a Stop button). On an overworld, the switch at the bottom right picks the view: + +- **Regions** (the full view): every region's own hexes, drawn small and stitched together, with blank bricks (just an outline) where there's no region yet; the overworld's own hexes and coordinates aren't drawn in this view. Hover for the region's name; click to go into that region at the spot you clicked (at any zoom). The gap past the overworld's edge does nothing: to add land there, walk into it from a region next to it. The terrain tool paints the regions' hexes directly, across seams, so a river valley or a road corridor through several regions is one stroke; undo takes it all back. Each hex is written to its region as you draw, so the overworld and any open view of those regions update during the stroke. The terrain tool only works in this view (the Biomes view shows biomes only); where there's no region yet the brush does nothing ("No region here yet; place a biome first"), and in Play it's locked ("Switch to Build to paint the regions."). In both views, clicking a hex or brick with a region goes into it in every mode; clicking an empty one opens **New region** (Build and God): Edit region… for a region that isn't made yet, with the biome tiles (starting on the hex's own biome), **Mix biomes…**, **Reroll** (a new seed in the preview), **Blend width**, **Neighbour influence** and the borders and seed in Debug, all drawn live in a preview against the regions around it. Nothing is written until **Create**, which makes exactly the previewed region; **Cancel** or × writes nothing. After **Create** the window carries on as **Edit region…** for the new, open region. **Neighbour influence** (0 to 2, default 1) scales the biome's own neighbour influence for this region only: 0 leaves only the seam cells, 2 doubles it. It's kept in the region's map note as `neighbour-influence: 1.5` (only when it isn't 1), rerolls and regenerating use it, and **Edit region…** shows it while the region is open (moving it remakes the region with its seed). Right-click a region for **Enter region** and **Edit region…**: one window with the region's name (editable), the overworld hex it's on, **Enter region** and **Open map note**, its biome, a few facts (size and shape, palette, terrain counts, neighbouring regions you can click to go to, locations) and its notes. The notes are kept in the region's map note under a plain `## Notes` heading, so you can also edit them there; they're editable in every mode. A new region stays open until you lock it (`arrival: open` in its map note): in Build the biome is a picker (choosing another remakes the region), with **Reroll**, **Settings…** (biome, blend, seed, live preview) and **Lock**, the overworld's right-click menu has **Reroll region** and **Lock region**, and the region's own map view shows the **Reroll** / **Lock** bar. Each Reroll says so ("Rerolled Demo Bricks 0, 4."), and **Edit region…** shows a small picture of the region as it is now, so the result shows even with the window over the map. It also locks by itself the first time you edit it by hand (paint terrain or icons on its hexes, draw a path in it, swap hexes), with one notice: "Region locked: your edits are kept. Rerolling it now needs God mode." Going into it, looking at it and rerolling it never lock it, and neither does making the regions next to it. Extending the world never needs God: a first biome, a new region, walking into new land (the overworld grows to fit) and arriving are all Build. Every new region starts open, however it was made (the Biome painter, **Set biome…**, walking into new land, making every region, arriving). Once locked (`arrival: locked`), and for regions made before this, changing it needs God: in God mode it's the same picker; in Build and Play it's shown with "Switch to God to change it." On an empty hex the menu offers **Set biome…** (Build and God), which opens **New region**. The overworld is the big-picture view, so it has no hex editor: right-click shows only these region-level items, **Center on this hex**, **Copy link to this hex** and the hex's **Locations**. Painted hexes are locked, so remaking a region keeps them. +- **Roads and rivers on an overworld** are drafts (drawn faded) until you confirm them. Select one with the path tool and click **Confirm into regions** (in the bar at the top, or right-click the path; **Edit region…** lists the paths through that hex with the same button). The path is routed through every region it crosses: neighbouring regions agree on the hex where it crosses their shared edge, so it joins up at every seam, and inside each region it follows that region's own terrain with the path type's routing. Each region gets one path of the same type and name (forks become its branches); its **Overworld path** column in the region's map note says where it came from. Paths you drew in a region yourself are never touched, and a region path you renamed keeps your name. If the type **carves** terrain (River carves water by default; see Path types), the hexes it crosses become that terrain, except locked (hand-painted) hexes. The overworld path's **Applied** column says it's confirmed; reshaping, retyping or renaming it makes it a draft again, and **Update regions** puts the new route in (the old one's carved hexes go back to their generated terrain). **Remove from regions** takes it out again. Regions made or rerolled later get every confirmed path that crosses them. Confirming needs Build or God, and undo takes the whole thing back in one step. +- **Roads and rivers between regions.** A path you drew in a region that runs on into the next region (it ends on the shared edge, next to the end of a path of the same type there) is drawn on the overworld as one line through every region it crosses, thinner than on the region maps (half its type's width) and in its type's color and dash. In the **Regions** view it follows the paths as drawn; in the **Biomes** view it's simplified to straight lines from hex to hex through the middle of each shared edge. Only paths that join two regions or more are drawn: one that stays inside one region never is. A type that comes out thinner than 1.25 px (width 2 or less) is left out, whatever it's called. A region path made by **Confirm into regions** isn't drawn again: the overworld path itself already shows. Hover a line for its name. Turn them off in the layers menu (**Paths between regions**, on by default); **Show paths** off hides them too. To draw one across a seam: with the path tool, draw up to the region's edge and click on the next region's hexes past the edge; the map goes there and the path carries on from the hex next to your end, with the same type and name. Or, in a region, click a neighbour's road or river where it ends at the edge (in the faded strip past the edge): a path of its type and name starts beside it, and your next clicks extend it. Starting a path by hand next to such an end, with the same type, takes its name too. The overworld shows the joined line straight away. +- **Biomes**: one biome per hex, labelled, with transitions outlined (no region outlines: every hex has one; hover a hex for its region's name). The terrain tool is off here. Click a hex with no region yet for **New region** (preview, then **Create**); click one that has a region to go in, and right-click it → **Edit region…** to change its biome (Build while it's new, **God** once it's locked, below), **Reroll** it or open **Settings…** (blend, borders, seed, with a preview). Right-click → **Set biome…** works in either view. The switch highlights the view that's showing. + +**Work modes: Play, Build, God.** Each map has a mode, shown on the toolbar next to the map button; click it to switch. The map keeps its mode (the `mode:` line in its map note) and opens in it next time; new maps are in **Build**. + +- **Play** is for running a game: move, place and remove tokens, open and edit notes, roll tables, link tables and factions to hexes, turn layers on and off. The map itself stays as it is. The drawing panel shows only the tools Play allows, with one line naming the mode for the rest ("Switch to Build to edit the map."); the grid's **+** / **−** buttons are hidden, the hex editor shows "Switch to Build to paint terrain." where the terrain and icon pickers were, the map's properties say "Switch to Build to change the map's properties.", and the right-click menu leaves out what's locked and ends with one such line. +- **Build** adds and edits: paint terrain, icons and areas, draw paths, link maps to hexes, grow the map, make maps and regions from a hex, change the map's properties, place a biome on an empty overworld hex. +- **God** can do everything, including changing a placed biome (**Reroll**, **Settings…**), swapping hexes, shrinking the grid and deleting the map. It's in the mode menu with Play and Build; where something needs God (swap a hex, shrink an edge, change a placed biome, regenerate, delete the map), the "Switch to God…" hint there has a **Switch to God for this map** button. + +Notes, settings and palettes are never locked. There are no confirm boxes for these: the mode is the safety catch. + +**Same control, same look, everywhere.** The plugin uses one control for each kind of input: +- **Shares of a whole** (Mix biomes, Blend into, the generator's map influence, a biome's Type mix and Terrain weights) are sliders that always add up to 100%. +- **Odds in a table** (random tables, world types) stay free weights you type, with a **%** beside each row that updates as you type, add or remove a row, or edit the note by hand. +- **A bias** on a learned or default amount (the generator's terrain **Bias**, its path knobs, biome pool weights) is a ×0–3 slider where ×1 means "as it is". +- **Every other slider** always shows its value, and scrolling over it nudges it. A value that's inherited or at its default shows dimmed, with one reset button (a rotate icon) to put it back. +- **Number boxes** (sizes, counts) can be dragged up or down or scrolled, and are kept in range when you leave them. +- With **Debug mode** on, every slider also gets a number box beside it, to type an exact value. +- **Dialog buttons:** the main action comes first, and there is only one main (highlighted) button. Editors that save as you go (the hex, table, workflow, path type, terrain, faction and area editors, world types and the biome page) have no Save or Close button: × closes, and a line says when it's saved. +- **No confirm boxes.** Deleting a generator or a table moves it to the trash. Deleting a path type and resetting a generator's settings each show a notice with **Undo**. A workflow result whose name is taken is saved as "Name 2". Deleting a map asks a second time on the button itself ("Click again to delete"). Only turning on a module for a map and turning on debug mode still ask first. +- **Pickers** with more than a handful of items (terrains, factions, areas, biomes, icons, maps, locations) have a **Filter** box at the top, and say "No … match." when nothing fits. Pickers you can edit switch with **Edit** / **Done editing**; rows you can reorder have the same ⠿ grip. +- **Groups that fold** (the generator and biome page sections, a path type's routes, Export's PDF table columns and Hexcrawl manual, the biome pool) all look the same: a chevron that points right when closed and down when open. They remember whether you left them open, and a group whose options differ from the defaults says so ("PDF table columns · 1 set"). +- **Words:** **Reroll** makes something again with a new seed; **Regenerate** makes it again on the same seed after you change a setting. A map inside a hex is a **submap**, of two kinds: a **Region** (the hex up close) or a **Location** (a town, a dungeon…). An **Area** is a named stretch of hexes you paint with the Areas tool (a basin, a kingdom). Notices start with "Hexmap World Creator:" only when they come from something running in the background, not from a click you just made. + +**Undo per mode.** Each map has its own undo queue in each mode, kept until you close the vault. Undo (**↩** or Ctrl+Z) and redo take back the last thing done on this map in the mode it's in now: undoing a token move in Play never undoes Build's terrain, and switching back to Build picks its queue up where you left it. If something was changed again in another mode since (a token moved in Build, then again in Play), Build's undo skips it rather than moving it back. Terrain, icons, areas, paths, tokens, swaps and hex editor edits, and biome changes (reroll, swap), are all undoable. The buttons' tooltips name the mode. + +Which biome a hex is comes from its terrain's **Type**, never its name: forest-type terrains are temperate forest, wetland swamp, and so on. Where a type has variants, the **last** terrains of that type in the palette stand for them, in this order: forest → taiga, deep forest; grassland → savanna; hills → karst; wetland → river delta. Reorder the palette to choose (on Expanded: evergreen, evergreen heavy, savanna, jungle hills, river delta). A terrain with no type has no biome. + +**Your own biomes.** Every biome is a plain note in the biomes folder (default `{world folder}/biomes`, see Settings). The built-in ones are written there once (when the setup picks World, World is turned on in Settings, or Regions and overworlds is turned on; never in a space-only setup), so you can edit them like any other note; delete one and it stays deleted. A biome note has a name, a color, a **Mix** table of terrain *types* with weights (never terrain names, so it works on any palette with types), a **Transitions** table (biomes it shouldn't touch and the biome put between them), and in its frontmatter `blend` (narrow, normal or wide), `land-share` and `min-islands` (for watery biomes) and an optional `generator: [[…]]` link. Rows that can't be read are reported and left as you wrote them; your own text in the note is kept. On an overworld's **Biomes** view, **Biomes…** lists them. There is one biome editor, the **biome page** (the generator page's **Biome (blend field)** view): **Edit…** opens it, and **New biome…** only asks for a name, a color and a biome to start from (or nothing), then writes the note and opens the page. The page has everything: name, color, **Made by** (**Built-in mixing** or one of your generators), **Regions start blank**, the **Type mix** (only the types in it: share sliders that always add up to 100%, with **Min patches** and a **×** to take a type out; **+ Add type** under the list puts one in, at an equal share), **Terrain weights** (for a type with more than one terrain in the palette: share sliders for how its share splits), blend width, land share, min islands, shore, **Climate** and transitions, with a live preview. It saves as you go (no Save button; the line under the header says when it's saved). Built-in biomes also have **Restore default**, which backs up the old note first. For a biome made by a generator, **Edit generator…** (also in **Edit region…**) opens that generator. Biomes linked to a generator say "available once generator regions land" and blend until then. Your biomes appear in the biome picker and make regions with the blend field straight away. Adding and editing biomes needs Build or God. A region keeps its biome when you rename the biome's note; if you delete the note, the region keeps its terrain and **Edit region…** shows "Unknown biome". Inside a region, click the middle of the hex flower to open **Edit region…** for it; the overworld's right-click menu has **Create token here** to mark the party. + +**Terrain weights.** A biome's Mix is by terrain type; an optional **Terrain weights** table (`| Terrain | Weight |`) says how one type's share is split between its terrains, so different forests can go together in different ratios: `Pine forest | 3` and `Oak forest | 1` make three pine hexes for every oak. Terrains not listed count 1, and 0 leaves one out. Names are matched ignoring case; rows that can't be read are reported. + +**Make a generator from a region.** Edit a region by hand, then **Edit region… → Make generator…** (or right-click the map in **Maps** → **Make generator from …**). It learns how the region's terrain fits together and asks: **New generator** (a name) or **Overwrite existing**, from a list with the most fitting first: the generator of the region's own biome, then its parent biomes', then generators learned from this region, then related biomes' (neighbours it was blended with, similar biomes), then the rest. Overwriting saves the old generator as a plain note in the plugin folder's `backups/` first, and biomes that use it keep using it. A new generator gets its own biome that starts as a copy of the region's biome: climate, land share, fewest islands, transitions, shore, blend, color and mix, with `parent:` naming the biome it came from and Terrain weights taken from the region. Edit it like any biome note. + +**Blend a region back into its biome.** After editing a region by hand, **Edit region… → Blend into …** (or right-click the map in **Maps** → **Blend into …**; both under Advanced) folds it into the biome it was made from. Two share sliders say how much the map counts against what's there (they add up to 100%, like every share in the plugin; default 25% this map, 75% the rest), with a live preview of a fresh region of the biome after the blend. If the biome links a generator, the map is learned and merged into that generator the way combined generators are. If it doesn't, the map's measured stats are blended into the biome's own settings at the same weight: the Mix shares (rows keep their order and Min patches), the Terrain weights, the land share (when the biome sets one) and the smoothing passes (fitted by making sample regions and matching how often the map's neighbouring hexes share a type); **Make a generator instead…** opens Make generator. Either way the old note is backed up to the plugin folder's `backups/` first, only the note's tables and settings change (its prose stays), and a **Blend of** table in the note records each map, its weight and the date. Re-learn, Re-blend and Overwrite now also change only a generator note's tables and settings. Needs Build or God. + +**Tuning a biome (Debug mode).** The generator page's **Biome (blend field)** view lists every biome (ones with a generator say so). With **Debug mode** on, its Advanced dropdown's Debug section has every setting that shapes the biome's regions, in collapsible sections: **Layout** (influence reach, wiggle scale, edge look-ahead), **Borders & transitions** (blend falloff, border wiggle, terrain pick sharpness), **Water & islands** (largest island, islands at the edge, beach cover, coast band width, shore lean, coastline raggedness), **Patches & detail** (smoothing passes, field hold, min patch size, largest patch, patches at the edge) and, for a biome that links a generator, **Engine** (clumping, mix strength, feature size, scatter, randomness, edge smoothing, speck size, keep rare, edge strength, directional bias, over the generator's own). Each control shows its value (dimmed while it's the default), has the reset button, redraws the preview and counts toward **· N set**. Values are saved per biome in its note as a readable **Tuning** table (`| Setting | Value | Default |`), only those that differ from the default; it's read forgivingly (a setting's label or key, `0.3` or `30%`; values out of range are clamped; rows it can't read are reported and kept). With nothing set, a seed gives exactly the region it gave before. To ship tuned built-in biomes, see `dev/biomes/README.md`. +**The Biome painter.** On an overworld the drawing tools have **Biome**: pick a biome in a palette like the terrain painter's, then click or drag over hexes in either view. Each hex gets the biome and its region is made as you go, no window. A hex with no region yet can be painted in Build or God; changing the biome of a hex that has a region needs God once the region is locked (Build while it's new) and only remakes that region when the biome is different (painting the same biome again does nothing). Regions remade by one stroke are one undo step, in the queue of the mode they were made in; making a region for the first time makes a map and isn't undone. After each stroke one notice says what it made ("Made Demo Bricks 2, 4.", "Made 3 regions."). **Edit region…** is still there for names, notes and settings, but setting a biome never needs it: the painter stays one click per hex (no preview), and its regions start open so you can edit or reroll them after. Arriving also makes its region with no window. + +**The Biome column.** An overworld's map note keeps every hex's biome in the **Hexes** table's **Biome** column, by name (`| 3_2 | | forest | Temperate forest |`), not only the ones a terrain can't tell apart. It's read forgivingly (a biome's name, id or note name, any case); a name that isn't a biome is left as written and that hex goes by its terrain. Overworlds made before this get the column filled once when the plugin starts. + +**Blank biomes.** **Custom (blank)** is a shipped biome with `blank: yes`: its regions start empty for you to paint, its overworld hex has no terrain (the Biome column names it), and neighbouring regions don't blend into it. Any biome can be blank (`blank: yes` in its note, or **Regions start blank** in its form); blank biomes are never placed by World biomes or listed in pools. They're offered wherever you pick a biome: the Biome painter, **Set biome…**, **Edit region…**, walking into new land, and **New overworld…**'s **Blank hexes** (that many hexes start blank, land first and spread out). + +**Mountain, desert and underground biomes.** The shipped biomes also include **Highlands**, **Volcanic peaks**, **Glacier**, **Canyon** and **Mesa** (high ground), **Steppe**, **Desert**, **Wasteland** and **Blighted lands** (lowlands) and **Reef** (warm coastal sea), each with a climate so World biomes places it, transitions to its neighbours and Min patches for the ground that gives it its character. The underground biomes, **Caverns** (big patches, little smoothing), **Underdark**, **Fungal forest**, **Underground lake**, **Mines and halls** and **Magma caves** (mostly lava, so it shows as lava on the overworld), carry `layer: underground` in their notes: World biomes never places an underground biome (not even from a pool), the shipped **All biomes** pool leaves them out, and walking into new land from an underground region rolls another underground biome. Set them by hand with the Biome painter or **Edit region…**. They paint with new terrain types (Cave floor, Solid rock, Underground water, Fungus, Crystal, Mine / hall, Chasm, Lava, Blight; types, not names, as everywhere), which fall back to the nearest land type on a palette without them, so they work on Limited and your own palettes too. A vault that already has biome notes gets each new one once (one you delete stays deleted), and the new surface ones are added once to an **All biomes** pool you already have. + +**Picking a biome.** Every biome list (the Biome painter, **Set biome…**, **Edit region…**, **Settings…**, walking into new land, **Biomes…**, the generator page) is grouped under **Surface**, **Mountains**, **Water**, **Underground** and **Blank**, worked out from each biome's own note (blank, layer, climate elevation, land share, or its Mix for a biome without a climate), so your own biomes are grouped too. Long lists get a **Filter biomes…** box. + +**Mixing biomes.** **Edit region… → Mix biomes…** lets you pick several biomes for one region, each with a slider for its share. The sliders always add up to 100%, as on the generator page: moving one shares the rest among the others in the proportions they had (a biome you add gets an equal share; arrow keys move 1%, scrolling 5%). The region's preview follows as you drag; **Apply mix** remakes the region (hand-painted hexes stay), with the same rule as changing its biome (Build while the region is new, God once it's locked). Each biome holds patches of the region about as big as its share (smooth noise per biome, so the same mix next door joins at the seam), and the region still blends with its neighbours. The region's own settings come from the weighted mix: its Mix shares and Terrain weights merged by weight, numbers (tuning, land share, islands, min patches) weighted, and its color, blend width, shore and layer from the heaviest biome. A mix is written readably wherever a biome is: `Alpine 2 + Taiga 1` (or `Alpine + Taiga` when the weights are equal; shares are saved as the smallest whole weights that give the same percentages, so 67% / 33% is `Alpine 2 + Taiga 1`) in the overworld's **Biome** column and the region note's `biome:`; hand edits read forgivingly (labels, ids or links, `×2`, `(2)`, `+` or `,`). The overworld labels the hex "Alpine + Taiga" and the minimap "Alpine+". A single biome is stored and made exactly as before. + +**Biome climates.** A biome note can say where generated overworlds put it, with optional plain keys: `temperature` (cold, cool, mild, warm, hot, a range like `cold–mild`, or numbers like `0.2–0.5`), `moisture` (dry, moderate, wet, or numbers), `elevation` (`low`, `mid` for hills, `high` for peaks, `sea`, or `mouth` for the river's mouth), `coastal: yes` (only next to the coast), `chance` (like `50%`: the share of fitting hexes it takes) and `rare: yes` (at most one hex in about 20). With any of them set, World biomes can choose the biome like a built-in one; left blank, the biome is only placed by hand. The built-in biomes carry their climates in their notes too (older built-in notes get them added once), so you can see and change why tundra goes north. Where several biomes fit a hex, the rarer and then the narrower one is tried first. The biome page has the same fields in its **Climate** section (**Chance** is in Debug). Values the plugin can't read are reported and ignored. + +**Generate overworld (first pass).** **New overworld…** lays out the biomes of a **biome pool**: a plain note in the biome pools folder (default `{world folder}/biome-pools`) with a `Biome | Weight | Notes` table linking biome notes. **All biomes** (every built-in) is written there once. In the form, pick a pool and add or remove biomes (built-in, your own, or ones made by a generator), set a weight with its slider (×1 as its note says, ×0.5 half as often, ×2 twice, ×0 never; the reset puts it back to ×1), and **Save** or **Save as…** a new pool; the preview updates as you go. Climate, land, which way is colder and water are the World biomes settings; **Reroll** tries another layout (the seed itself is in the Debug section, and the overworld keeps it as its `seed:`; **Generate overworld…** starts from it). **Biomes without a climate**, at the top of the form next to the name and pool, says what the pool's biomes with no climate do: **Fill gaps only** (default: only where no other biome in the pool fits) or **Never place them** (place them by hand with the Biome painter); the overworld keeps the choice as `no-climate-biomes: fill gaps` or `never`, and regenerating uses it. **Coast** has a climate (coastal lowland, roughly 3 in 10 land hexes by the sea), so it lines generated coasts; existing overworlds only change when regenerated. **Create** makes the map (it remembers its pool as `biome-pool: "[[…]]"`) and every region with its biome; every hex's biome is kept in the overworld's **Biome** column. It's only a first pass: edit, reroll or swap any region afterwards. To redo the whole map, open the map menu → **Regions** → **Generate overworld…** (God only): locked hexes keep their terrain and their regions are left alone, every other region is remade in place (its name, notes and locked hexes stay), and missing regions are made. + +A small **minimap** of the overworld (bottom right) shows on the overworld and on each of its regions, with the region you're in outlined; click a hex on it to go there. **Neighbouring maps** (below) and overworlds both stay available: pick per map. A map can have N/E/S/W neighbours and regions at once; a region itself joins its neighbours by itself, so it doesn't offer the neighbour tools. + +**Neighbouring maps.** In **Maps → New map…**, **Next to** makes the new map a region beside an existing one (same size and palette, lined up hex for hex); **Properties → New region here…** opens the form already placed. The generators tagged *continues* (Overland and learned generators; the line above the list says so once) carry the neighbour's terrain on across the shared border, and the preview shows the neighbour's edge faded around the new map. **Neighbour influence** under **Next to** (the same slider as on **New region**: ×0 to ×2, default ×1) sets how strongly the neighbour steers the new map: ×0 matches only the seam, ×2 carries its terrain twice as far in and, for learned generators, blends in more of its look (20% at ×1, 40% at ×2). The preview follows it, and the new map keeps it in its note (`neighbour-influence:`, only when it isn't ×1). Region detail is only offered for submaps, since it zooms into a parent hex. + +**Reroll a new map.** A map made with **Generate** (New map, a submap's form, or the setup wizard's first map) starts open, as a new region does (`arrival: open`): the bar beside the mode switch offers **Reroll** (the same generator, options, palette, size and neighbours, with a new seed; its terrain and paths are replaced) and **Lock**. Your first hand edit (painting, a path, a swap) locks it, with one notice; after that only God mode can reroll it. Its note keeps how it was made, readably: `generator: procedural:overland`, `generator-options: sea=west, water=30` and `generator-seed:`. **Open in generator** and Blank maps have no recipe and no bar. + +**Shared coordinates.** Neighbouring regions number their hexes on one grid, so a hex number is unique across the world: the map east of a 20-column map that starts at 0 starts at column 20. The placement note shows the range ("Hexes 20, 0 to 39, 13"). Maps joined before this, or two existing maps linked in **Properties → Neighbouring regions**, keep their own numbers; nothing is renamed. After the map button and the ← ↑ → arrows (back, parent, forward: always in that order, hover for the map each goes to), the neighbouring regions show as a small ◀ ▲ ▼ ▶ pad, one button per side; hover for the name, click to go there. An empty side shows its arrow with a **+** (**▲+**) and opens the same walk into new land (**New region**: pick or roll a biome, mix, preview, create). Inside a submap, the pad goes to its parent's neighbours, one click away. A road or river that ends on a region's edge, next to the end of the neighbour's path of the same type, is drawn on to the shared edge on both maps so they join. + +Generators only change hexes when a map is created or regenerated; you can always repaint by hand afterwards. + +### Hex editor (click a hex) A modal for editing a hex note without leaving the map. +- **Name** — give the hex a name ("Glass Wastes"). It shows on the map under the hex's icon, in the hover text and in the hex table, and is stored in the map note, so a hex doesn't need a note to have one. When the hex has a note, the name is also added to the note's `aliases`, so the quick switcher, search and `[[links]]` find the note by name (the file stays `x_y.md`). Renaming swaps that alias; aliases you added yourself are kept. Every hex note also gets its map name and coordinates as an alias ("Gloomwood 3, 4"), so the quick switcher finds a hex by its coordinates; renaming the map updates it. - **Terrain picker** — select the terrain type for the hex from the map's palette. -- **Icon override** — override the default terrain icon with any icon in your icons folder. -- **Submap link** — link another map to this hex. The hex flower widget shows a center dot coloured by the linked map's terrain theme. Click the dot to navigate directly to that map. +- **Icon override** — override the default terrain icon with any icon in your icons folder. Icon pickers have **All / Terrain / Places / Custom** tabs (plus **Space** when space maps are on); **Places** holds 55 settlement, castle, tower, ruin, temple, camp and cave icons (chips narrow it to Settlements, Castles, Towers, Ruins, Temples, Camps or Caves & mines; it is hidden in a space-only setup), and **Custom** holds the images in your icons folder. +- **Maps strip** — the maps this hex opens into: its region (outlined chip) and its locations. Click a chip to go there; **+** makes a new map from the hex, links an existing one, or opens the locations list. +- **Copy link to this hex** — click the centre dot of the hex flower (top right), or right-click the hex on the map: it copies a Markdown link to this hex. Paste it in any note; clicking it opens the map centred on the hex. - **Towns / Dungeons / Features / Quests / Factions** — link existing notes from their configured folders, or create a new note by name. Linked items are clickable and open in a new tab. Each entry has a remove button. -- **Encounters Table** — link random table files to a hex. Clicking a linked table opens the Random Tables view with that table pre-selected. -- **Notes sections** — Description, Landmark, Hidden, Secret, Weather, Hooks & Rumors — inline text areas with a 🎲 roll button to append a result from any random table. +- **Encounters** — every encounter table that applies to the hex, most specific first: the hex's own, its area's, its terrain's. With more than one, round buttons pick which one **🎲 Roll** uses (it starts on the most specific; the pick lasts the session and writes nothing, so it works in Play). **Change…** picks any table (your own first) or makes a new one, linked to this hex; **×** takes one off. Clicking a table's name opens it in the Random Tables view. +- **Notes sections** — Description, Landmark, Hidden, Secret — inline text areas; a 📖 button rolls the section's table where one exists. +- **Weather and Hooks & Rumors** — folded under Notes, each with the same table section as Encounters: the hex's own tables, then the map's (set in **Maps → Properties → Weather and rumours**), then the starter `weather.md` / `rumors.md` in your tables folder. **Change…** links any other table to this hex, so a weather table you made is one pick away. +- **Empty tables** — tables start empty for you to fill. An empty table's **Roll** is off, with **Add entries** to open it in the table editor; the same everywhere a table is rolled (the roll dialog, the Random Tables view, a note's roller, workflow steps). +- **Add to this hex** — any roll made from the editor (encounter tables, section tables) can be added to the **Play log** or a section of this hex's note, chosen from a list (in Play the play log comes first; otherwise the section you rolled from comes first). The note is created if the hex has none. **Copy** is always there too. +- **Add to log** — the link beside the hex title writes what happened here into today's play log (see **Solo play** under Tokens). +- **Show on map** — once a link section (Towns, Dungeons, Features…) has a link, a small button with that section's icon makes it the hex's icon in one click, in Play too. Each section's icon (or none) is set in **Settings → Map look → Icons for linked notes**. +- **Groups** — Terrain, Notes, Linked notes and Icons fold like every other group (chevron); each remembers whether you left it open. +- **Run workflow** — the link beside the hex title picks a workflow and runs it for this hex; **Add to this hex** puts the filled-in result into a section (its headings become bold lines so the section stays whole). - **Open note** link next to the hex coordinates opens the full note in a new tab. ### Random Tables view -Open via **Command palette → "Open Hexmaker random tables"** or the 🎲 ribbon button. +Open via **Command palette → "Hexmap World Creator: Open random tables"** or the 🎲 button in the hex map toolbar. A two-panel view for managing and rolling on random tables. -- **Left panel** — shows all `.md` files in the configured Tables folder as a collapsible folder tree. Click a folder header to expand or collapse it. Click a table to load it. The filter input at the top narrows results and temporarily expands all folders. **+ New** creates a file from the default template. -- **Right panel** — shows the table's entries with odds (percentage or die range). **Roll** button highlights the winning row and shows the result. The result is editable before use. Roll history shows the last 5 results. -- **Change die** dropdown — updates the `dice:` frontmatter and recalculates die ranges. +- **Left panel** — shows all `.md` files in the configured Tables folder as a collapsible folder tree. It keeps itself up to date: tables and folders added, renamed, moved or deleted, a changed linked folder or `table-type`, and workflows that start or stop using a table show within a moment (the old ↺ button is in Debug). Right-click a folder (or a table → **Advanced ▸**) to leave it out of the roll picker or the encounters table. Click a folder header to expand or collapse it. Click a table to load it. The filter input at the top narrows results and temporarily expands all folders. **+ New** creates a file from the default template (**Generate from folder or file**, under the list's Advanced dropdown, fills it from a folder's notes or a note's list). Your own tables come first; the description and encounter tables the map makes for every terrain, and the encounter table for every region, sit in one collapsed **Made by the map** section at the end (so do the workflow step and roll dropdowns, and the hex table's Encounters picker). They're told apart by their `table-type: description` / `encounters` line: delete it and the table counts as yours. +- **Right panel** — **Roll** (above the entries) rolls the die, highlights the row and shows the face (e.g. `d20 → 14`) and the result. The result is editable before use. Roll history shows the last 5 results. Below are the entries with their roll ranges and odds. A table with a linked folder syncs its rows when it's opened and whenever a note in the folder is added, renamed or deleted. **Copy link** (a roll link to paste in a note) is under the Advanced dropdown. +- **Change die** dropdown — updates the `dice:` frontmatter and redoes the roll column for the new die. +- **Problems** — if the ranges and weights disagree, or a range can't be read, a banner says so, with one-click fixes (**Keep ranges → set weights**, **Keep weights → redo ranges**). + +Table notes are meant to be rolled by hand, too. Each row shows its roll range for the table's die: + +``` +| d20 | Result | Weight | +|-------|---------|--------| +| 1–16 | crabmen | 4 | +| 17–20 | mage | 1 | +| — | kraken | 0 | +``` + +What you see in the roll column is what you get: the plugin rolls the same ranges. A range you type by hand is never overwritten; a blank range cell is filled in from the weights. Weight 0 (`—`) is never rolled. d100 accepts `01–05` and `00`; d66 is supported (`dice: d66`). Columns are found by name (Range/Roll/dN, Result/Entry, Weight/W), and extra columns and text around the table are kept. Older `| Result | Weight |` tables still work. The first time the plugin starts after an update, it backs them up and adds roll ranges once, without asking; **Add roll ranges to tables** does the same by hand (after making a backup), and **Check tables** (both are commands, offered while **Debug mode** is on) writes a report of anything that couldn't be read to `_table-check.md` in the tables folder. + +More a table can say, all optional (a table without them reads exactly as before): + +- **Weights** can be decimals (`3.5`, `0.5`) or percentages (`50%` is 0.5). +- **Extra columns** are kept and shown read-only in the Random Tables view; they travel with a row when something rolls on it (a world's **Size**, **Generator**, **Mainworld**…). +- Four column names will mean the same in every table: **Roll** (`now`, or `on arrival` for a row that stays unknown until someone visits), **Shown as** (what such a hex shows until then), **Once** (`per world` or `per map`) and **When** (`zone: outer`, `star: red dwarf, white dwarf`, `ring: 2–4`, `temperature: cold`, `type: gas-giant`, `near: town 2`; separate several with `;`; a row whose When doesn't fit is rolled again). They are read, kept and checked (**Check tables** lists a value it can't read). Roll and Shown as work when generating and arriving, and Once when the map rolls (see **Once-only rows**); When in the Random Tables view comes later. +- `rows:` in the frontmatter says what the rows are (`text`, `note`, `table`, `generator`, `terrain`, `biome` or `any`, the default), and `terrain-type:` narrows terrain rows (`star`). It is read and checked now; table pickers will use it to offer only tables that fit. +- `linked-folder:` works like `linkedFolder:`. +- `pick: each` in the frontmatter makes a "roll for each line" table: every row comes up on its own **Chance** column (`always`, `1 in 2`, `60%`; blank is always) instead of one row by weight. Orbits' **System extras** is one. + +Rolls made from a hex (the hex editor's 🎲 and 📖, **Add to this hex**) go through the same roller the generators use: a row that links another table (`[[Storms]]`) is rolled through and the chain is shown (`Weather → Storms → hail`), the hex's terrain and terrain type are the **When** context (`terrain: swamp`, `type: hills`), and a `pick: each` table gives one line per row that came up. + +**Shipped tables.** The starter `weather.md` and `rumors.md` (World maps) and Orbits' `space/Orbits/Moons.md`, `Gas giant moons.md` and `System extras.md` (Space) come with their map type as ordinary table notes, written into the tables folder when missing (by **Generate terrain tables** and when the type is turned on). A note already there is never written over, so edit them freely. ### Workflows view Open via the Workflows tab in the Random Tables panel. @@ -131,45 +275,59 @@ Chain multiple table rolls together into a filled template note. - **Roll a workflow** — each step shows a dropdown and a Roll button. The template fills in live as you roll. Save the result as a new vault note. ### Terrain tables & hex linking -Each terrain type has two auto-generated table files: `{terrain} - description.md` and `{terrain} - encounters.md`, stored under `{tablesFolder}/terrain/`. +Each terrain type has two auto-generated table files: `{terrain} - description.md` and `{terrain} - encounters.md`, stored under `{tablesFolder}/terrain/`. With only the Space map type on, tables are made for the space palettes' terrains only, not the fantasy ones (unless a map uses that palette). A terrain gets its two tables as soon as it's created, wherever: the terrain tool, the palette editor, a new or copied palette, or a row added to a palette note. They start empty, ready for you to fill. Renaming a terrain renames its tables too (links to them follow), and the hexes using it on that palette's maps follow it (maps on other palettes keep their own terrain of that name). A terrain renamed by hand in its palette note gets a **Rename everywhere** notice once you leave the note, when hexes, a map's base terrain or the terrain's tables still use the old name; nothing changes until you click it, and the map notes and tables it changes are backed up first (`backups/` in the plugin folder). > ⚠️ **Configure all folder settings before clicking Generate.** The Generate button (Settings → Hexmap World Creator → Generate world data) creates the terrain table files and links each hex note's terrain encounters table into its Encounters Table section. It is safe to run multiple times. ### Drawing tools (toolbar) -Click the **pencil** icon on the right edge of the map to open the drawing tools panel. **Right-click** off a hex (or click the active button again) to exit any tool. Tools that link or paint items show a **Remove** option at the start of the picker — selecting it enters erase mode so you can click hexes to remove that layer. +Click the **pencil** icon on the right edge of the map to open the drawing tools panel. **Right-click** off a hex, press **Esc** or click **✕** in the tool bar to exit any tool. Clicking **Terrain** or **Icon** again reopens its picker to switch (closing the picker without a pick keeps the tool as it was). The everyday tools come first; **Link table**, **Link submap** and **Areas** are in the panel's **Advanced** dropdown. Tools that link or paint items show a **Remove** option at the start of the picker — selecting it enters erase mode so you can click hexes to remove that layer. | Tool | Left-click | Right-click (on hex) | |------|------------|----------------------| | **Terrain** | Paint terrain (drag to paint multiple hexes) | — | | **Icon** | Paint an icon override | — | -| **Path** | Add hex to the active path chain | Remove hex from chain | +| **Path** | Add hex to the active path chain (or, with Auto-route, pick the start and then the end) | Remove hex from chain | | **Link table** | Add the selected random table to the hex's Encounters Table section | — | -| **Link submap** | Link the selected map to the hex as a submap | Remove submap link | -| **Factions** | Paint a faction colour (drag to paint multiple hexes) | Erase faction from hex | -| **Regions** | Paint a geographic region colour | Erase region from hex | +| **Link submap** | Add the selected map to the hex's locations | Remove that map from the hex (any map, if none is selected) | +| **Factions** | Paint a faction color (drag to paint multiple hexes) | Erase faction from hex | +| **Areas** | Paint an area note's color (a named area like a basin or a kingdom, not a region submap) | Erase the area from the hex | | **Token** | Open the token creator, then click a hex to place the new token | Cancel placement | +| **Center hex** | Asks for X, Y and centres the view on that hex (not a tool mode) | — | **Terrain painter extras:** -- Clicking the Terrain button always reopens the palette so you can switch colours mid-session. +- Clicking the Terrain button always reopens the palette so you can switch colors mid-session. - **Pick** (eyedropper) — samples the terrain from the next hex you click and sets it as the active brush. - **Clear** — paints the "no terrain" state. - **Brush size** — paint 1×, 3×, or 7× hex radius at once. -**Path tool:** Click the Path button to open the path type picker. Select a type to start drawing, or switch to edit mode to create, rename, recolour, or delete path types. Each path type has a name, colour, line width, line style (solid / dashed / dotted), and routing mode: +**Path tool:** Click the Path button to open the path type picker. Select a type to start drawing, or switch to edit mode to create, rename, recolor, or delete path types. Each path type has a name, color, line width, line style (solid / dashed / dotted), and routing mode: - **Through** — smooth Bezier curve through hex centres. - **Meander** — gentle curve through the midpoints between hex centres (good for rivers). - **Edge** — traces strictly along the hex polygon boundary lines between hexes. -**Link table / Link submap:** Clicking either button opens a picker. For tables, the picker shows your tables folder as a collapsible folder tree with a filter input. For submaps, the picker shows a filterable list of your maps with their terrain theme swatches. Once a table or map is selected, click any number of hexes to link it. The hex flashes a ripple animation on each successful link. +**Editing paths:** there is no separate edit mode. While the path tool is on a type, every path of that type shows its points as handles: drag a point to move it, drag the line to add a point there and move it, right-click a point to delete it (a branch or path left with one point goes too, with a notice; undo brings it back), click an end to carry on from it, and click empty ground to start a new path. Click a line to select that path, and click it again to start a fork. Forks stay attached: moving the point a fork leaves from takes the fork along, deleting it moves the fork to the nearest point left on the line, and if the main line goes its forks become paths of their own (still one undo step). Right-click a line (or Shift+right-click a point) for the path menu: Rename…, Delete path, Change type…, Delete this fork, and **Advanced ▸** with Split here and Reverse. Paths of other types are left alone while you work: a click on one is a click on the ground, and hovering it names the type to switch to (right-click it for **Switch to** that type). Each drag or delete is one undo step, and editing paths needs Build or God mode. The bar at the top of the map lists these actions. + +**Auto-route:** the picker (and the bar at the top of the map while drawing) switches between **Hex by hex** and **Auto-route**: in the picker, choose how to draw (step 1), then the path type (step 2). With Auto-route, click a start hex and then an end hex: the path takes the shortest way inside the map, around impassable terrain, keeping close to the straight line between the two, and then carries on from that end, so you can route leg by leg. Path types whose **Auto-route** option is *winding* (River, by default) wind gently instead of running straight; *direct* ones keep to the line. It's an option on each type, never a matter of its name. A route continues an existing path only when its start is that path's end; starting anywhere else (such as the first hex of another road) makes a new path, and existing paths are never changed. The result is an ordinary path: drag its points to reshape it, right-click a point to remove it, or click an end to extend it. + +- **Impassable terrain** — set per terrain in the palette editor (Impassable column) or the terrain editor. Defaults go by terrain *type*, never by name, so they work in any palette, custom ones included: every terrain of a water type (deep water, water, shallows) is impassable unless you untick it. A terrain with no type has no default (an untyped "Black Lake" is passable); give it a type, or use **Guess types from names** in the palette editor. A palette with no impassable terrain says so in the bar. Learned generators' **Connected land** uses the same impassable terrains until you save your own list. +- **Carves terrain** (in the path type editor; **Carve width** is in Debug) — a path type can also say what an overworld path of that type turns the hexes it crosses into when you confirm it into its regions (**Carves**: a terrain's name, or a terrain type such as `water` for the palette's first water terrain; **Carve width** 0 for the path's own hexes, 1 to take the hexes beside them too). New palettes' River carves `water`; Road carves nothing. It's an option of the type, never of its name. Palettes made before carving existed get it once, on the next load: their River (still the one the plugin wrote, same routing and auto-route) is set to carve `water` if it never had a Carves value. The palette notes are backed up first (`backups/` in the plugin folder), and a value you set or cleared to `none` is never changed. The columns appear in the palette note's Path types table once a type uses them. +- **Per path type** — each path type has **Avoid impassable terrain** and **Auto-route** (direct or winding) in its editor and in the palette note's Path types table. The built-in Road avoids impassable terrain and routes direct; River does neither. Any type can be set either way, whatever it's called. Path types saved by older versions get these filled in once, from how those versions treated them, so no map changes look. +- **Cross impassable** — a button in the bar at the top turns it on to let one route go through anyway. If no route exists the map tells you, and suggests this or changing which terrains are impassable. + +**Link table / Link submap:** these and **Areas** are in the drawing panel's **Advanced** dropdown. Clicking either button opens a picker. For tables, the picker shows your tables folder as a collapsible folder tree with a filter input. For submaps, the picker shows a filterable list of your maps with their terrain theme swatches. Once a table or map is selected, click any number of hexes to link it. The hex flashes a ripple animation on each successful link. ### Overlays (faction and region) Toggled from the **layers** panel on the right edge of the map. -- **Faction overlay** — paint a faction colour on any hex. Adjacent hexes of the same faction merge into smooth filled blobs with a coloured border. A legend lists each active faction. Edit faction names and colours from the overlay panel. Faction data is stored as wiki-links in each hex note's `### Factions` section. -- **Region overlay** — paint a geographic region colour on any hex. Regions render as filled blobs with a scaled label centred on the blob. Region data is stored in each hex note's frontmatter. +- **Faction overlay** — paint a faction color on any hex. Adjacent hexes of the same faction merge into smooth filled blobs with a colored border. A legend lists each active faction. Edit faction names and colors from the overlay panel. Faction data is stored as wiki-links in each hex note's `### Factions` section. +- **Area overlay** — paint an area's color on any hex (the **Areas** tool; area notes live in the Areas folder). Areas render as filled blobs with a scaled label centred on the blob. Area data is stored in the map note (see [Map notes](#map-notes)). Its toggle is in the layers panel's **Advanced** dropdown. - Both overlays can be shown simultaneously and toggled independently. -- Additional toggles: **Show coordinates**, **Show terrain icons**, **Show icon overrides**, **GM layer**, **Tokens**. +- Additional toggles: **Show terrain icons**, **Show icon overrides**, **Show paths**, **Show tokens**, **GM layer**. +- **Labels** group: **Coordinates**, **Hex names**, **Token names**, **Uncharted (?)** (a small ? on hexes whose On arrival roll is still to come) and **Visited** (a dot on hexes the party token has stood on) (all on by default). With token names off, a token's name still shows while you hover it. Hex names are always readable: never smaller than about 11px on screen, at any zoom. A long name shrinks and wraps at spaces onto up to three lines to fit inside its hex, clear of its badges and coordinates; when it still doesn't fit at a readable size (zoomed out, or a long name), it spills past the hex instead of being cut (words are never split, nothing is cut off). Their color follows the terrain (dark text on light terrain such as snow, light text on dark terrain). **Aa** beside the Labels heading sets the hex-name font for this map: Theme / Serif / Sans / Handwritten (common system fonts, nothing bundled), size **S / M / L / XL**, **B**old and **I**talic, and ↺ back to the default. The default for every map is in **Settings → Hex name font**. Saved in the map note (`name-font`, `name-size`, `name-style`); the PNG export uses the same font. +- **Show link badges** (on by default) — a colored icon badge at a hex's right side for each kind of link in its note: towns, dungeons, features, quests, factions. **S / M / L** beside the toggle sets their size (S by default; S is small and stays inside the hex, M and L sit on the hex's right edge so they stand out). Badges sit above hex names and coordinates, and names make room for them. The legend lists the badge kinds shown on the map. Hovering the hex names the linked notes ("Gullmouth · beach · hex 6, 6 · Town: Gullmouth"). Your hex icon stays as it is. The ▸ next to the toggle picks which kinds show. Saved per map. +- Opening or closing the layers panel (or the drawing tools) never moves the map; the panel may cover a few hexes at the right edge. +- **Show legend** (on by default) — a small terrain legend pinned to the bottom-left of the map view, listing only the terrains used on this map by their full names (only names longer than 18 characters are cut, keeping their start; hover a row for the full name). **S / M / L** sets its size; **–** folds it to a small **Legend** button (click to open it again); **×** hides it. The new-map and generator previews show the same legend. Size and visibility are remembered. ### GM layer Toggle from the overlay panel. When active: @@ -177,41 +335,101 @@ Toggle from the overlay panel. When active: - Hexes with Hidden or Secret content are visually highlighted. - The hex editor automatically expands the Hidden and Secret sections when opened. -GM layer state is stored per map and persists across sessions. +GM layer state is stored per map and persists across sessions. New maps start with it off; maps made before this keep it on until you turn it off. ### Tokens -Place movable tokens on the map — useful for tracking party position, NPCs, or any note-backed marker. +Place movable tokens on the map — useful for tracking party position, NPCs, or any note-backed marker. Each token's name shows beside it, on the side away from the hex coordinates (above the token with coordinates at the bottom, the default; under it otherwise), so the hex number stays readable (turn this off with **Labels → Token names** in the layers panel; the name still shows on hover). **Creating a token:** 1. Click the **Token** button in the drawing tools panel. -2. Fill in the token form: choose a note (existing or new), icon, shape (circle / square / hexagon), fill colour, and border colour. +2. Fill in the token form: choose a note (existing or new), icon, shape (circle / square / hexagon), fill color, and border color. The note list holds what a token stands for: notes in the tokens folder (`{world folder}/tokens`, where new ones go) and the towns, dungeons, features, quests, factions and areas folders. Tables, biomes, palettes, world types, generators and hex notes are never listed, here or in any other note picker; table pickers list the tables folder, the workflow picker the workflows folder, and a blank folder setting means its usual place under the world folder, not the whole vault. 3. Click **Next: place on map**, then click any hex to place the token there. **Interacting with tokens:** -- **Click** a token to open its info card — shows the linked note title and hex position, with a "Jump to hex" button and an "Open note" link. +- **Click** a token to open the hex it stands on, just like clicking the hex. - **Drag** a token to a different hex to move it. The target hex is highlighted as you drag. -- **Right-click** a token to edit its properties (icon, shape, colours) or remove it from the map. +- **Right-click** a token for its menu: **Token info** (the linked note title and hex position, with "Jump to hex" and "Open note"), edit its properties (icon, shape, colors), or remove it from the map. Below those, under **This hex: …**, are the items of the hex it sits on (open its maps, **Open hex note**, create a token here…), so you don't have to aim past the token. -Token state is stored in the linked note's frontmatter (`token`, `token-hex`, `token-map`, `token-icon`, `token-shape`, `token-color`, `token-border`, `token-visible`). Tokens follow the map they were placed on and persist with the note. +**Solo play:** +- **Party token** — tick **Party token** in the token form (or right-click a token → **Party token**). In **Play**, click the party to pick it up: the hexes it can step to light up; click one and it moves there (undoable). Click it again or press Esc to put it down. Dragging works as before. Tokens sit clear of their hex's coordinate so the hex number stays readable. +- **Visited** — every hex the party stands on gets a small dot. The map note keeps the list (`visited: ["3_4", "4_4"]`, first visit first; `show-visited: false` when hidden). **Layers → Labels → Visited** shows or hides them; right-click a hex → **Visited** (an Advanced item) marks one by hand. +- **Play log** — what happened goes to a dated note in the play log folder (**Settings → Play log folder**; blank = `{world folder}/log`), one per day, one line per entry: `- 14:32 · [[…/3_4|Vale 3, 4]] · [[Party]] · Wolves on the ridge.` The hex's note gets a link to the day under `### Log`. Add entries from the hex editor (**Add to log**, or **Add to this hex → Play log** after a roll), from a hex's right-click menu (**Add to play log…**), and open the day with **Open today's play log**. A party can keep its own log folder (token form → **Log folder**, an Advanced option; `token-log:` in its note). +- **Exploring with hex flowers** — a map can start blank and fill as the party walks. In **New map**, pick **Terrain → Explore as you go** and the generator that **powers** it (the same list as Generate it now): the map starts as big as the party can see (**Party sees**, 1 ring by default: 3 × 3), on the hex you click in the start grid (the middle by default; next to a map, its shared edge is marked), with a **Party** token there. **Add another area** puts a second generator's area **near** (5–8 hexes), **far** (10–15) or **really far** (20–30) in one of the six directions; its influence grows as the party nears it, borders mix, and coming back to an area gives its terrain again. In Play the party controls show **Area: **: click it to **Change area** (a generator, where it is, which way; a direction another area holds is off). Each area rolls on a hex flower made from its generator's terrain mix (19 cells, walked with 2d6 on the published navigation hex: 2–3 up-right, 4–5 down-right, 6–7 down, 8–9 down-left, 10–11 up-left, 12 up); **Advanced → Make your own flower** rolls on a flower note instead (new from your palette, or one you have). **Fill the whole map now** keeps the size choice. The map grows as the party nears an edge, up to the biggest map (200 × 200). Each blank hex the party steps into (clicked in Play, or dragged in any mode) is filled from the flower, with a notice and **Reroll** / **Undo**; Ctrl+Z takes back the step and what it filled together. Painted hexes are never changed. Right-click a blank hex → **Roll this hex**; a **?** marks the explored frontier. Edit flowers on the generator page's **Hex flowers** tab (paint cells, **Fill from palette**, **Use on this map**, **Test walk**, moves, edges, cell shares). The map note keeps `explore-with:` (rules such as `(realms) -> terrain`, `[[Wilds]] -> terrain`, `[[Weather]] -> play log, every step`), `explore-realms:` (`"Overland: procedural:overland at 1_1, home"`), `explore-blend:`, `hex-flower-at:` and `explore-reveal:`; **Map properties → Exploring** edits them and lists the areas. +- **Party controls while exploring** — select the party token in Play and the bar over the map has, all at the top: **Sees 0 · 1 · 2 · 3** (how many rings each step reveals; 0 is only the hex entered; the current one is highlighted) and **Look** (the same as clicking the party's own hex: a step in place that reveals what it sees now, e.g. Sees 2 after climbing a tree; the token doesn't move and no travel is logged), **Peek** (the GM sees the hidden land faintly), **Area** (a map powered by generators) and **Reveal hexes → Pick** (the GM's brush: click, tap or drag over hexes to fill or reveal exactly those, nothing around them; right-click or tap a revealed hex to hide it again; Esc stops). Each look, step or stroke is one undo. +- **Explore a finished map (fog of war)** — any map you already made or generated can be explored as it is: in Play, right-click a hex → **Start exploring from here…** (start hex, **Party sees**, the party token: one of the map's or a new one; a map explored before can carry on or start over). Everything the party hasn't seen is dark: terrain, icons, names, coordinates, other tokens, paths, area and faction overlays and GM icons. Each step reveals what the party sees; nothing on the map changes (the map note keeps only `explore-fog: on` and `explore-seen:`, runs per row like `"3: 4-9, 12"`). Right-click a hidden hex → **Reveal this hex** (a town, a quest's goal, nothing around it), a revealed one → **Hide again** (not while the party can see it). **Stop** on the party bar (or **Stop exploring** in the hex menu) lifts the fog and keeps what was seen. **Export** asks **Whole map** or **As the party has seen it** (hidden hexes blank on the PNG, left out of the PDF table and the hexcrawl manual). + + +Token state is stored in the linked note's frontmatter (`token`, `token-hex`, `token-map`, `token-icon`, `token-shape`, `token-color`, `token-border`, `token-visible`, and `token-party` / `token-log` for a party). `token-map` is a link to the map's note (`"[[_Overworld]]"`), so it follows the map when it's renamed; a plain map name is read too. Tokens follow the map they were placed on and persist with the note. ### Hex table view -Open via **Command palette → "Open Hexmaker hex table"**. +Open via **Command palette → "Hexmap World Creator: Open hex table"** or the ⊞ button in the hex map toolbar. A scrollable reference table of every hex note, with one row per hex and columns for all sections. -- **Coordinates column** — click to open the hex note. +- **Coordinates column** — click to open the hex note. A named hex shows its name beside the coordinates. - **Terrain column** — click to open the terrain picker. - **Town / Dungeon columns** — click an empty cell to add a link (pick existing or create new); click a populated cell to open the note (or a navigation list for multiple links). - **Text section columns** (Description, Landmark, etc.) — click any cell (including empty ones) to open an inline editor. Saves directly to the section in the hex note, creating the note and section if they don't exist yet. - **Resize columns** by dragging the border between column headers. - **Filter** by map, terrain type, or the presence of specific link types using the toolbar controls. -- **Refresh** button reloads all data from disk. +- **X / Y ranges** are in the toolbar's **Advanced** dropdown. The table updates as notes change; a **Refresh** button (reload everything from disk) is in its Debug section. + +### Export +Export a map for printing or for your players. + +- **Where:** the command **Hexmap World Creator: Export current map…** (any map; it starts on the one open in the hex map view), or the map-name button in the hex map toolbar → **Export** tab. Both show the same form. +- **Formats:** **Export PNG** (an image of the map) and **Export PDF with reference table** (the map, then a table per section listing each hex's linked notes and the start of its Description); **Export hexcrawl manual (PDF)** makes a printable gazetteer with legend, encounter tables and keyed hexes. +- **Options:** file name; **On the map**: coordinates, icons, paths (and bolder paths), hex names, tokens (with their names), link badges, legend (the terrains used and the badge kinds, beside the map), faction overlay; output size. **Area overlay** is under the form's Advanced dropdown. The export buttons come right after the options. The ticks start from what the map view shows (the overlays start off), and the form remembers your last file name, ticks and size for each map. Labels near the edge are kept inside the image. Roads and rivers are drawn bolder than on screen, scaled to the output size (with paths ticked, moon tethers are drawn too, as on screen), and badges use the map's badge size. **PDF table columns** picks which columns the reference table prints (name, terrain, towns, dungeons, features, quests, factions, encounters, description), so you can cut a handout down to what players should see. **Hexcrawl manual** holds the player-version switch and lets you leave out the legend, encounter tables, factions and areas, or index. The form lists the exact file names it will write; files go to the export folder and open in a tab. Exporting again under the same name replaces the file (the notice says "Replaced …") and refreshes the tab already showing it. +- **What players see:** the PNG never includes GM-layer icons, hidden tokens or any note text (Description, Landmark, Hidden, Secret), so it is safe as a handout. The faction and area overlays show their names when ticked; leave them off if those are secret. The PDF's table has no Hidden or Secret text. The hexcrawl manual is the full GM book unless you tick **player version**, which leaves out Hidden and Secret. +- A single note or hex can also be exported: **Hexmap World Creator: Export current note to PDF**, **… to Markdown**, **Export current hex (structured PDF / Markdown)**, or the **Export** link in the hex editor. + +### Content packs +Share your own content between vaults: random tables, workflows (with their templates), note templates, towns, dungeons, features, quests, factions, areas, palettes and path types, generators, and the notes of the other map types you use. Nothing comes pre-made: a pack holds what you made. + +- **Export:** **Hexmap World Creator: Export content pack…**, or **Export content pack…** at the end of the map export form. Name the pack, add a description if you like, and tick what goes in: each kind has a tick for all of it, a count, and its notes to tick one by one (**All** / **None** for everything). The pack is written to the export folder as `.zip`. +- **What's in the zip:** your notes exactly as they are, each kind in its own folder (`tables/…`, `towns/…`, subfolders kept), and a `pack.md` you can read: name, description, the version that made it, the date, a table of what's inside (with the folder each kind came from) and the list of files. Notes starting with `_` are left out. +- **Import:** **Hexmap World Creator: Import content pack…**, or **Import a content pack…** on the last step of the setup wizard. Pick a .zip, a folder (an unzipped pack), or one of the .zip files already in the vault. You see what goes where first: each kind goes into this vault's folder for it, whatever it's called here. A note that's already here and the same is left alone; for one that's different, pick **Keep both** (the pack's copy is added as "Name 2"; the default), **Skip** or **Replace** (one choice for all, or per note). Replaced notes are backed up first, in the plugin's `backups/pack-import-` folder. Nothing is ever deleted. +- **Checks:** only Markdown notes are imported; a file that isn't readable text, has an unsafe path, or is in a folder this vault has no place for is skipped and listed. Tables keep their rows and weights as written; an old "open in roller" link (which named the table's old path) becomes the roller block. Links written with a folder path (`[[world/tables/Weather]]`) are pointed at this vault's folder. A folder without a `pack.md` is read by its folder names. + +### Commands +Every command, as it appears in the command palette: + +| Command | What it does | +|---------|--------------| +| **Hexmap World Creator: Open hex map** | Opens the hex map view. | +| **Hexmap World Creator: Open hex table** | Opens the spreadsheet of hex notes. | +| **Hexmap World Creator: Open random tables** | Opens the random tables and workflows view. | +| **Hexmap World Creator: Open terrain generator** | Opens the terrain generator (learn, blend and run generators). | +| **Hexmap World Creator: Open palette editor** | Opens the terrain palette editor. | +| **Hexmap World Creator: Convert world types to tables** | Writes each World types note as random tables under `{tables folder}/space//` (backed up first; the notes are kept and link to the tables). Shown while a note is left to convert. | +| **Hexmap World Creator: Edit world types…** | Opens the world types table editor (which worlds the space generators place, how often, and how each world's map is made), with a preview. Space maps on. | +| **Hexmap World Creator: New overworld…** | Generate overworld (first pass): a map of biomes from a biome pool, laid out by climate, whose hexes open into regions that join up; can make every region at once. | +| **Hexmap World Creator: Recalculate fields** | Works out the open map's hex fields again after towns or cities were added or the fields changed: **Update places** keeps rolls and typed values, **Roll everything again** rolls every field. One undo step. See Hex fields. | +| **Hexmap World Creator: Go up to parent map** | From a submap, back to the map it belongs to. | +| **Hexmap World Creator: Go back to previous map** | Returns to the map you were on before. | +| **Hexmap World Creator: Go forward to the next map** | After going back, forward again (like a browser). | +| **Hexmap World Creator: Add map data to this map's hex notes** | Debug mode only. Adds a Map data box (terrain, region, name, from the map) under the title of every hex note of the open map, kept up to date when you open a hex. It runs at once (no confirm box) and says how many notes it changed. New hex notes from the built-in template already have one. Edits you typed into existing boxes are put on the map first (see Map data in hex notes). | +| **Hexmap World Creator: Update map data in region and faction notes** | Debug mode only. Adds or updates a Map data box under the title of every region and faction note: the maps that use it (with hex counts) and, for regions, the encounter table. Kept up to date when you open the note. It runs at once (no confirm box) and says how many notes it changed. | +| **Hexmap World Creator: Export current map…** | Opens the map export form (PNG, PDF, hexcrawl manual). | +| **Hexmap World Creator: Export content pack…** | Packs the notes you pick (tables, workflows, templates, towns…) into a .zip in the export folder. See Content packs. | +| **Hexmap World Creator: Import content pack…** | Brings a content pack (.zip or folder) into this vault's folders, with a preview first. See Content packs. | +| **Hexmap World Creator: Open today's play log** | Opens today's note in the play log folder (made if missing). | +| **Hexmap World Creator: Export current note to PDF** | Exports the open note as a PDF. | +| **Hexmap World Creator: Export current note to Markdown** | Exports the open note as Markdown. | +| **Hexmap World Creator: Export current hex (structured PDF / Markdown)** | Exports the open hex note with its sections. | +| **Hexmap World Creator: Export current workflow with rolled samples** | Exports the open workflow with example rolls. | +| **Hexmap World Creator: Add roll ranges to tables** | Debug mode only. Adds a roll column with die ranges (e.g. `1–6`) to older tables, after a backup. Asks first. | +| **Hexmap World Creator: Check tables** | Debug mode only. Writes `_table-check.md` listing tables whose ranges, weights or columns couldn't be read cleanly. | +| **Hexmap World Creator: Open backups folder** | Opens the plugin's backups folder (`.obsidian/plugins/hexmaker/backups`, hidden in Obsidian's file list) in your file manager. Every upgrade and bulk change saves the notes it changes there first. | +| **Hexmap World Creator: Restore from upgrade backup…** | Lists the backups that hold notes, newest first; pick one to see which notes it would put back (changed ones put back, deleted ones made again, unchanged ones left), then **Restore**. The notes as they are just before are backed up first, so a restore can be undone the same way. | + +Commands marked *Debug mode only* are offered in the command palette only while **Debug mode** is on (the last setting). Right-click a note in the file list for **Export note → PDF / Markdown**. --- ## Settings -Open **Settings → Hexmap World Creator** to configure: +Open **Settings → Hexmap World Creator** to configure the settings below. Everyday ones are at the top: **Terrain palettes** (pick, rename, edit, delete and add palettes), **Map look** (coordinate labels, hex names, spacing) and **Defaults**. Then the ones you set once: **Setup** (setup wizard, world folder, note templates, icons folder) and **Map types**. The collapsed **Advanced** dropdown near the bottom has **Generate terrain tables & hex links** at its top, then its own collapsible sections: **Folders** (Generate folders, the template path and every folder), **New map sizes** and **Palettes** (put the built-in palettes back, open a palette's note). Each stays open or closed as you left it, on this device. The Biomes and Biome pools folders are in its **Debug** section. The World types folder is in its **Debug** section. **Debug** shows only while **Debug mode** is on. There's no Simple or Advanced level: every feature is always there. | Setting | Description | |---------|-------------| @@ -221,34 +439,86 @@ Open **Settings → Hexmap World Creator** to configure: | **Dungeons folder** | Scopes the Dungeons picker to a specific folder. | | **Quests folder** | Scopes the Quests picker to a specific folder. | | **Factions folder** | Scopes the Factions picker to a specific folder. | +| **Play log folder** | One note per day of play (`2026-10-14.md`), with what happened, when, where and who. Asked in the setup wizard; blank = `{world folder}/log`. | +| **Icons for linked notes** | Under **Map look**: the icon each link section (Towns, Dungeons, Features…) offers with **Show on map** in the hex editor, or none. | +| **Areas folder** | Area notes (a basin, a kingdom) painted with the **Areas** tool and shown by the area overlay. New vaults get `{world folder}/areas`; a vault that already has its folder (often `{world folder}/regions`) keeps it, and nothing is moved. | | **Tables folder** | Folder for random table files. Terrain tables are created in a `terrain/` subfolder here. | | **Workflows folder** | Folder for workflow definition files and their templates. | +| **Templates folder** | One folder for the plugin's note templates, so they're easy to find and edit: `hex.md` (the hex note template, unless **Template path** points elsewhere) and one template for each kind of linked note: new notes made from the hex editor or a link picker start from it. Each starts barebones (a title, Description and Notes), with no lean towards any setting or ruleset: make them your own. **Note templates** (under **Setup**) opens each one, and each link field's list in the hex editor ends with **Edit the … template…**. Blank = `templates` in the world folder. Made by **Generate folders** and the setup wizard; Each one also appears the first time you create that kind of note. Workflow templates stay beside their workflows. | | **Default die** | Die size used when creating new table files (d4–d100). | | **Icons folder** | Folder containing `.png` icon files available as custom terrain/hex icons. | -| **Template path** | Path to a custom hex note template. Supports `{{x}}`, `{{y}}`, `{{title}}` placeholders. Leave blank to use the built-in template. | +| **Template path** | Path to a custom hex note template. Supports `{{x}}`, `{{y}}`, `{{title}}` and `{{map}}` placeholders. Leave blank to use `hex.md` in the templates folder (or the built-in template if there isn't one). A path you already set is kept. | | **Hex gap** | Gap between hexes in pixels. | | **Hex orientation** | `flat` (default) or `pointy` top hex style. | -| **Path types** | Named path types used by the Path drawing tool. Each type has a name, colour, width, line style, and routing mode. Manage them from the Path button on the hex map toolbar. | -| **Terrain palettes** | Named palettes of terrain types. Each palette has a name and a list of terrain entries (name, colour, optional icon and icon tint). Palettes are assigned to maps at creation time. Edit palette contents from the terrain tool on the hex map. | -| **Generate** | ⚠️ Configure all folders first. Creates missing terrain table files and links each hex's terrain encounters table into the hex note. | +| **Path types** | Named path types used by the Path drawing tool. Each type has a name, color, width, line style, and routing mode. Manage them from the Path button on the hex map toolbar. | +| **Palettes folder** | Folder holding one note per terrain palette (default `{world folder}/palettes`). | +| **Biomes folder** | Folder holding one note per overworld biome (default `{world folder}/biomes`). | +| **Biome pools folder** | Folder holding the biome pool notes used by Generate overworld (default `{world folder}/biome-pools`). | +| **World types folder** | Folder holding the world types tables used by the space generators (default `{world folder}/world-types`). | +| **Palette for new maps** | The palette a new map starts on. *First palette* = the first one listed (overland before space). New installs start on Expanded; any palette can be picked, and renaming it keeps the setting. | +| **Add default palettes** | Shown when Expanded or Limited isn't in the list: puts them back. Palettes you delete (in settings, or by deleting a palette note the plugin wrote) stay deleted, with a copy in the plugin folder's `backups/`; an empty palette list stays empty until you add one. A palette whose note isn't there yet for another reason (an upgrade, a new palettes folder, a note sync hasn't delivered) is kept: its note is written, or the palette comes back when the note arrives. | +| **Terrain palettes** | Named palettes of terrain types. Each palette has a name and a list of terrain entries (name, color, optional icon and icon tint). Palettes are assigned to maps at creation time. Edit palette contents from the terrain tool on the hex map, or as a table in the palette's note — copy a palette note into another vault's palettes folder to share it. Colors can be any CSS color; one the plugin can't read is drawn grey, kept as you typed it and named in a notice, and a slip with only one reading (`0x29507f`, `# 29507f`, `Dark Green`) is read that way and written back so. **Add palette** offers built-in presets: *Expanded* (the default fantasy overland palette on new installs; installs from before it keep their first palette as the new-map default: coasts, wetlands, forest and mountain kinds, and an underground set (cave floor, solid rock, chasm, underground lake, fungal forest, crystal cave, lava flow, mine shaft, dwarven hall) plus blighted land and dead forest, each with a terrain type of its own; matches the generators; an Expanded palette you already have gets terrains added later once, beside your own and never over one you made) and *Limited* (fewer, simpler terrains; quicker to paint), plus *Space - Sector* (star charts, one hex per parsec; adds Jump route and Trade route path types), *Space - System* (stars, planets, belts, stations) and *Space - Planet* (a planet's surface: seas, plains, regolith, dunes, ice, craters, lava fields, toxic marsh, crystal fields, ruins, colonies; typed for the Planet surface generator, and what planets and moons open on) for sci-fi games such as Traveller. A palette note's `map-kind:` line (`world` or `space`) says which map type it belongs to; without it, a palette with space terrain types counts as space. New-map palette menus list uninstalled presets too, and show the picked palette's terrains as a row of color swatches (names on hover) under the menu. | +| **Generate terrain tables & hex links** | Top of Advanced. Set the folders first. Creates missing terrain table files and links each hex's terrain encounters table into the hex note. Messages about a missing table point here. | +| **Debug mode** | The very last setting. Shows backend controls (storage folders, maintenance commands) in a **Debug** section inside each page's Advanced dropdown, and the maintenance commands in the command palette. The terrain generator's tuning doesn't need it: that's in the generator page's own Advanced dropdown. The first time it asks to make sure. While it's on, **Debug** shows in the status bar; click it to turn it off. Kept per device (Obsidian's local storage), never in `data.json`, never synced. | + +--- -### Vaults updated by a newer version +## Map notes -Newer versions store maps differently. If a synced vault was updated by a newer version on another device, this version goes read-only on this device: it shows a notice, its views and settings only say what happened, and it writes nothing (no settings, no hex notes, no tables). Update the plugin on this device to keep working. +Each map has one **map note** at `{hexFolder}/{map}/_{map}.md` (e.g. `RPG/world/hexes/Overworld/_Overworld.md`). It holds the map's settings in its frontmatter and a table with one row per hex that has map data: name, terrain, icon, GM icons, area, locations, region map (once a hex has one) and locked. Areas, locations and region maps are wikilinks (`[[Basin]]`, `[[_saltmere]], [[_old-mine]]`), so renaming a note in Obsidian updates them; plain names are read too and become links on the next save. Notes written before this (one Submap column, plain names; a **Region** column for the area, `show-region-overlay`, `on-arrival: make places`) are converted once, after a backup in the plugin's `backups/` folder; the old names are still read. Hexes with only the map's base terrain (or nothing) have no row. Painting updates the table; you can also edit the table by hand and the map follows. Anything you write in the note outside the "Hexes" and "Paths" tables is left alone. A collapsed **How to edit this note** box at the top explains the columns. ---- +Paths are stored by name in two tables. **Paths** has one row per path: *Path* (its name), *Type* (a path type from the palette), *Route* (written by the plugin) and *Notes* (yours). **Path routes** says where each path goes, as the hexes it passes through in order (`0, 8 → 9, 8 → 13, 8`); the map works out the way between them. A path's `main` row is its main line, and every other row of that path is a fork that leaves it at its first hex. The two tables are linked by the path's name, ignoring case and spacing, so to rename a path edit *Path* in both. Coordinates can be written `3, 4`, `3,4`, `3_4` or `(3, 4)`, separated by `→`, `->`, `>` or `;`. A routes row for a path missing from Paths makes that path (with no type until you give it one); a Paths row with no routes is kept as a path with no route yet. Terrain or a size typed into the note that would move a path keeps its route, as painting does (points are added, with **Reroute instead**); points you type into Path routes are routed on the map as it is, so when one edit adds both, only the stretches that were already drawn are held. Older notes, which listed every hex of every path (`| Type | Hexes |`), are converted once, after a backup: pieces of the same type that touch end to end become one path with forks, one-hex leftovers with no notes are dropped, and each path keeps exactly the hexes it had. A report of what changed is saved next to the backup. An old `Type | Hexes` table pasted into a note is still read. + +The plugin also writes a few things for you to read, worked out from the tables and the map's palette. A **Summary** section above the Hexes table shows the palette (as a link), the map's extent (`−7…30 × −8…16 (38×25)`), the base terrain, a terrain legend with hex counts, the regions on the map, its region settings, how many region maps and locations open from its hexes, and any terrain or path type that isn't in the palette (⚠). In **Paths**, the *Route* column shows where each path's main line starts and ends, how many forks it has and how many hexes it covers (`0, 8 → 13, 8 · 2 forks · 31 hexes`), with a ⚠ when its type isn't one of the palette's path types, it has no type yet, or a stretch can't be routed and is drawn straight. These are never read back: they're rewritten on each save, so edits to them are replaced, and a deleted Summary comes back. Text you type under the Summary, or a Summary heading of your own, is left alone. Map notes from before this are given them once, after a backup. + +**Map data in hex notes.** A hex note from the built-in template has a **Map data** box under its title: the hex's map and coordinates, terrain, area and name, plus its region map and locations (as links) when it has them, and its biome on an overworld (linked to the biome note). The map note is where these live; the box is a copy, refreshed when you open the hex in the hex editor or open the note. You can edit **Terrain**, **Area** and **Name** in the box (`Region:`, as older boxes say, reads the same): when you leave the note (or open the hex editor, or run *Add map data to this map's hex notes*), the change goes onto the map, as one undo step. It doesn't if the map has changed that value since the box was last written (the map's value is newer), if the map's mode locks it (Play can't paint terrain or regions; names are fine), or if the terrain isn't in the map's palette. Those edits stay in the box as a `Not applied:` line saying why, lines it can't read become `Not read:` lines, and a notice tells you; delete those lines when you're done with them. Change the map, region map and locations, and biome, on the map itself. The plugin keeps what each box last showed in `map-data-shown.json` in its folder; a note it has no record of (first run, another device) just gets its box refreshed from the map. + +Older hex templates had `**Terrain:**` and `**Region:**` lines to fill in by hand. The map is where terrain and region live now, so a filled-in line moves into the Map data box as an `Old terrain:` / `Old region:` line, under the map's own values: your words are kept, and they never change the map. Copy one onto the map by editing the box's Terrain or Region if you want it. This happens once for every hex note when you update (after a backup, see below), and again whenever a note gets such a line (when you leave the note or open the hex editor). Empty lines and template placeholders are left where they are. + +Hand edits are forgiving. Each setting is one plain property (the parent map and background image are links, e.g. `parent: "[[_coast]]"` with `parent-hex: 3, 4`), so the Properties panel can edit them too, and deleting a property resets that setting. In the tables, headers can be in any case and any order, you can add your own columns (they're kept), the `| --- |` row is optional, hexes can be written `3_4`, `3, 4` or as a link, and `yes`/`true`/`x`/`✓` all mean yes; the next save tidies the formatting without changing your values. Terrain and palette names in the wrong case are matched to the palette. A row or setting that can't be read is kept exactly as you wrote it and listed in a warning box in the note (and a notice), until you fix it. If the note can't be read at all (say the `---` lines around its properties get broken), the plugin won't write to it and shows a notice until you fix it; your text is never rebuilt over. + +Map notes written by earlier builds (with JSON values such as `parent: {"map":…}`) still load; the first start of this version converts them once, after saving a copy in the plugin folder's `backups/`. + +Older versions kept terrain and the rest in each hex note's frontmatter. The first time this version starts, it moves that data into map notes, keeps a JSON backup in the plugin folder's `backups/`, and replaces those frontmatter fields with a `map:` link to the map note. `terrain:` and `icon:` stay, as copies (see Hex notes; `region:` becomes `area:`). Note text is never changed or deleted. Older plugin versions on other devices don't read map notes, so update every device that shares the vault first. + +**After updating.** The first start of a new version that changes your notes leaves a note **Hexmaker upgrade ** in the world folder. Its first line is the reminder to update every device that shares the vault; then it lists what changed, every backup and where it is, things to check (a checkbox each), and what's new since the version you came from. The one notice the upgrade shows links to it. Backups stay in the plugin's folder (`.obsidian/plugins/hexmaker/backups/`, hidden in Obsidian's file list): **Open backups folder** opens it, and **Restore from upgrade backup…** puts notes back as they were, after backing up how they are now (so a restore can be undone the same way). `data.json` carries `"dataFormat": 2`, which tells an older version that the vault was updated by a newer one. Maps that are each other's submaps (a loop of parents) are left as they are: they're links like any other, and the breadcrumb and Maps list show each map once. ## Hex notes -Each hex note lives at `{hexFolder}/{map}/{x}_{y}.md` (e.g. `RPG/world/hexes/Overworld/3_7.md`). +Each hex note lives at `{hexFolder}/{map}/{x}_{y}.md` (e.g. `RPG/world/hexes/Overworld/3_7.md`). Hex notes hold descriptions and links, and are created when a hex first gets some (you open it, write in the editor, or link something); painting terrain doesn't create one. Its frontmatter links to the map note and shows the hex's terrain, area, icon and name as properties: -**Frontmatter:** ```yaml --- -terrain: Forest +map: "[[_Overworld]]" +terrain: forest +area: Basin +icon: castle.png +name: Glass Wastes --- ``` +**Properties for Dataview, Bases and search.** The properties are copies: the map note holds the data. The plugin writes them whenever the hex changes (painting, generators, rerolls, undo, renaming a terrain or area, editing the map note), only into hex notes that exist, and only the ones that changed. Edit one (in the Properties panel or as text) and the map follows, as one undo step, like painting it: the map's mode must allow it (Play can't paint terrain, areas or icons), the terrain must be in the map's palette and the icon one the plugin has. Otherwise the property is put back and a notice says why. While the note is open, a value that can't be used is left as you typed it until you leave the note. If the map and the note change the same value at the same time, the map wins. `region:` (what older versions wrote for the area) is read as `area:` and rewritten as `area:`. The plugin keeps what it last wrote in `hex-properties-shown.json` in its folder, to tell your edits from an old copy; a note it has no record of only fills in what the map doesn't have. **Settings → Advanced → Map data as hex note properties** turns them off: the plugin stops writing and reading them and leaves them in your notes as they are (nothing is removed). Turning it back on brings the notes in line with the map notes, rewriting only the ones that differ, after a backup; a value you typed into a note while it was off, where the map has none, is kept and taken onto the map. + +Older notes say `hexmaker-map: "[[_Overworld]]"` (map notes use `hexmaker-map:` for their format number). Both are read. A note that already uses `map:` for something of its own keeps it, and its link stays under `hexmaker-map:`. + +**Note format changes.** The first start after updating rewrites older notes once, so links survive renames: + +| What | Before | After | +|---|---|---| +| Hex notes: link to the map note | `hexmaker-map: "[[_coast]]"` | `map: "[[_coast]]"` | +| Hex notes: hand-filled terrain / region lines | `**Terrain:** forest` in the text | `> Old terrain: forest` in the Map data box | +| Hex notes: the hex's map data as properties (notes upgraded by a test build had none) | `map: "[[_coast]]"` | `map: "[[_coast]]"`, `terrain: forest`, `area: Basin`… | +| Token notes: the map a token is on | `token-map: coast` | `token-map: "[[_coast]]"` | +| Second tokens for a note: the note they stand for | `token-link: world/npcs/Ana.md` | `token-link: "[[world/npcs/Ana]]"` | +| Workflows: their template | `template-file: world/workflows/templates/npc.md` | `template-file: "[[world/workflows/templates/npc]]"` | +| Map notes: the palette (and region palette) | `palette: Default` | `palette: "[[world/palettes/Default]]"` | +| Palette notes: the palette for submaps | `child-palette: Space - System` | `child-palette: "[[world/palettes/Space - System]]"` | +| Generators: palette, source region(s), blended generators | `palette: Default`, `source-maps: coast + north`, `blend-of: valley + forest` | `palette: "[[world/palettes/Default]]"`, `source-maps: ["[[_coast]]", "[[_north]]"]`, `blend-of: ["[[world/generators/valley]]", "[[world/generators/forest]]"]` | +| Generator saves: their generator | `generator-path: world/generators/valley.md` | `generator-path: "[[world/generators/valley]]"` | +| World types tables: the Palette column | `Space - Planet` | `[[world/palettes/Space - Planet]]` | + +Before changing anything, the full text of every note it changes is saved in the plugin folder's `backups/note-formats-/` (one gzipped file per change). Each change runs once per vault (recorded in `data.json`); a vault with nothing to change has no note written. The old forms are still read, so notes from another device on an older version keep working. Notes skipped on purpose (a `map:` key of your own, a link to a note that doesn't exist) are listed in a notice. A palette, map or generator name that names no note (a palette that isn't installed, a shipped generator) stays as you wrote it. New notes and saves are written with links, so renaming a palette, map or generator note in Obsidian updates everything that names it. + **Sections** (used by the editor and table view): | Heading | Type | Purpose | @@ -260,11 +530,13 @@ terrain: Forest | `### Features` | Links | Other points of interest | | `### Quests` | Links | Active quest links | | `### Factions` | Links | Faction links (used by the faction overlay) | -| `### Encounters Table` | Links | Random table links (linked to terrain by Generate) | +| `### Encounters Table` | Links | Encounter tables for this hex: your own, plus its area's and terrain's (linked when painted) | | `### hidden` | Text | Discoverable with effort | | `### secret` | Text | Revealed only through investigation | | `### weather` | Text | Weather notes | | `### hooks & rumors` | Text | Adventure seeds | +| `### Weather Table` | Links | Optional: this hex's own weather tables (listed before the map's) | +| `### Rumors Table` | Links | Optional: this hex's own rumours tables | You can use your own template (configured in Settings). Any `### Heading` that matches a section name will be picked up automatically. @@ -278,15 +550,20 @@ npm run dev # watch mode — rebuilds main.js on every save npm run build # production build (type-check + bundle) npm run version # bump version (updates manifest.json and versions.json) npm test # run the test suite +npm run test:integration # integration tests +npm run smoke # smoke vault matrix in sandboxed Obsidian (Windows; see below) +npm run premerge # build + lint + tests + integration + smoke: run before merging or deploying ``` +**Before merging into the integration branch or deploying a build into a real vault, run `npm run premerge`** and wait for `PREMERGE PASSED`. The smoke matrix (`dev/smoke/run.mjs`) starts a throwaway, separately profiled Obsidian per vault setup (fresh install, an old 1.5.5 vault, space only, an overworld with regions, neighbour maps, a custom palette, a vault with its folders deleted, 80 maps…), up to 4 at once (fewer when free memory is low or the CPU is busy; `--jobs N` sets it), and checks the plugin loads without errors, every map opens, untouched notes stay byte-identical, a restart rewrites nothing, paint and undo round-trip, and Play mode refuses edits. It needs Windows Obsidian and the fresh-eyes tester's `sandbox.mjs` (set `UX_TOOLS_DIR` if it isn't in the default place); `npm run smoke -- --list` shows the setups and `--only ` runs some of them. Results go to `dev/smoke/last-run.json` (and `last-pass.json` on a full pass). It only counts and stops its own sandboxes' processes, so your Obsidian or another smoke run can start or stop while it runs; a sandbox slow to exit gets about 30 seconds more before the stop counts as failed. + The built output is `main.js` in the repo root. Obsidian loads this file directly from the plugin folder. **Reload the plugin after a build:** ```js // Paste in Obsidian developer console (Ctrl+Shift+I) -app.plugins.disablePlugin('hexmaker-plugin'); -app.plugins.enablePlugin('hexmaker-plugin'); +app.plugins.disablePlugin('hexmaker'); +app.plugins.enablePlugin('hexmaker'); ``` ### Source layout @@ -299,14 +576,15 @@ src/ HexmakerModal.ts ← base modal class (makeDraggable, shared behaviour) types.ts ← interfaces and type constants constants.ts ← runtime constants and defaults - frontmatter.ts ← terrain/icon/submap YAML read/write + frontmatter.ts ← map data getters/setters (via the map store) + token YAML sections.ts ← markdown section read/write helpers utils.ts ← shared utilities defaultHexTemplate.md ← built-in hex note template + noteTemplates.ts ← templates folder paths + built-in town template (PA3) hex-map/ HexMapView.ts ← interactive hex grid (ItemView) HexSidePanel.ts ← collapsible side panels (drawing tools, overlays) - HexEditorModal.ts ← right-click hex editor (Modal) + HexEditorModal.ts ← hex editor, opened by clicking a hex (Modal) MapModal.ts ← map management (switch, create, rename, delete, terrain theme) SubmapPickerModal.ts ← link submap to a hex (picker + create) TerrainPickerModal.ts ← terrain palette picker @@ -317,7 +595,7 @@ src/ FolderTreePickerModal.ts ← table picker (collapsible folder tree) FileLinkSuggestModal.ts ← file picker scoped to a folder PainterContextMenu.ts ← right-click context menu for painter tools - TokenModal.ts ← create/edit a token (icon, shape, colour) + TokenModal.ts ← create/edit a token (icon, shape, color) TokenInfoModal.ts ← token info card (jump to hex, open note) MapLinkModal.ts ← link an existing note to a hex section newMapFields.ts ← shared new-map form fields (name, size, palette) @@ -334,6 +612,12 @@ src/ WorkflowWizardModal.ts ← execute a workflow randomTable.ts ← parse/roll/odds utilities workflow.ts ← workflow parse/serialize utilities + modules/packs/ ← content packs (slice "packs"; index.ts / runtime.ts plug it in) + packKinds.ts ← what a content pack carries: kind → folder, mapping between vaults + packManifest.ts ← the manifest note, read and written + packPlan.ts / packIO.ts ← import plan (conflicts, checks) and export/import through hosts + zip.ts ← small .zip writer/reader (no dependency) + PackExportModal.ts / PackImportModal.ts ← the two dialogs ``` ### Troubleshooting @@ -346,3 +630,5 @@ src/ ## Third-party libraries This plugin bundles [MiniSearch](https://github.com/lucaong/minisearch) (© Luca Ongaro, MIT License) for in-memory full-text search. + +The Places icon pack (`icons/place-*`) uses icons from [game-icons.net](https://game-icons.net) by Delapouite, Lorc, Caro Asercion, Pepijn Poolman, HeavenlyDog and Quoting (CC BY 3.0). The space icon pack (`icons/space-*`) uses icons from [game-icons.net](https://game-icons.net) by Lorc and Delapouite (CC BY 3.0), [Material Design Icons](https://pictogrammers.com/library/mdi/) (Apache 2.0), [Tabler Icons](https://tabler.io/icons) (MIT), and [Kenney Simple Space](https://kenney.nl/assets/simple-space) (CC0). Full per-icon credits and licence texts are in [`icons/CREDITS.md`](icons/CREDITS.md). diff --git a/dev/biomes/README.md b/dev/biomes/README.md new file mode 100644 index 00000000..2fc87e85 --- /dev/null +++ b/dev/biomes/README.md @@ -0,0 +1,55 @@ +# Shipping tuned biomes + +Dev-only and git-only. Nothing here is bundled into `main.js`. + +The built-in biomes ship as data in the World maps module: +`src/modules/world-maps/biomePresets.ts`, one biome per line (`SHIPPED_BIOMES`). +`src/overworld/biomePresets.ts` reads them. Open sea's mix lives there too +(tables phase 6). On first run, the plugin writes each biome into a note in +the vault's biomes folder. From then on the notes are what counts. + +To ship the values you tuned in a vault: + +1. Tune the biomes in a test vault. Turn on Debug mode, open the generator + page's **Biome (blend field)** view, and use the Debug sections. You can + also edit the biome notes by hand, or use **Blend into …**. +2. Run a dry run against that vault's biomes folder. It shows what would + change, biome by biome and field by field, and writes nothing: + + ``` + node dev/biomes/export-tuned-biomes.mjs "/world/biomes" + node dev/biomes/export-tuned-biomes.mjs "/world/biomes" --only tundra,coast + ``` + +3. Write the changes: + + ``` + node dev/biomes/export-tuned-biomes.mjs "/world/biomes" --write + ``` + +4. Run `npm test`, then commit `src/modules/world-maps/biomePresets.ts`. + +## What it copies + +The script copies the fields that shape generation and placement: Mix, Terrain +weights, Transitions, `blend`, `land-share`, `min-islands`, `shore`, the +climate keys and the **Tuning** table. It leaves out the label, the colour, +`generator` (a vault link) and `parent`. + +It skips notes that aren't a shipped biome (your own biomes) and names them in +the output. If a note has rows it can't read, the output says so too. + +## Files + +- `export-tuned-biomes.mjs` is the command. It loads the TypeScript parser with + tsx. +- `exportTuned.mjs` holds the pure part: the diff (`planExport`), its text + (`formatPlan`) and the data file's format (`shippedBiomesSource`). It's + tested in `tests/biomeBlend.test.ts`, which also checks that the shipped + file is exactly what the script writes. + +## Notes + +Changing a shipped biome's tuning changes what new vaults get. Existing vaults +keep their notes. **Restore default** on the biome page rewrites a note from +the shipped data, after backing up the old note. diff --git a/dev/biomes/export-tuned-biomes.mjs b/dev/biomes/export-tuned-biomes.mjs new file mode 100644 index 00000000..026cb798 --- /dev/null +++ b/dev/biomes/export-tuned-biomes.mjs @@ -0,0 +1,48 @@ +#!/usr/bin/env node +/** + * Ship the owner's biome tuning (dev-only, git-only; never bundled). + * + * node dev/biomes/export-tuned-biomes.mjs [--only id,id] [--write] + * + * Reads every biome note in the folder, compares the fields that shape + * generation (Mix, Terrain weights, Transitions, blend, land-share, + * min-islands, shore, climate, Tuning) with the shipped biome data + * (src/modules/world-maps/biomePresets.ts) and prints the differences. + * Only with --write is the shipped file rewritten. Notes that aren't a + * shipped biome are skipped. See dev/biomes/README.md. + */ +import { readdirSync, readFileSync, writeFileSync, statSync } from "node:fs"; +import { join, resolve, dirname, basename } from "node:path"; +import { fileURLToPath } from "node:url"; +import { require as tsRequire } from "tsx/cjs/api"; +import { formatPlan, planExport, SHIPPED_FILE, shippedBiomesSource } from "./exportTuned.mjs"; + +const root = resolve(dirname(fileURLToPath(import.meta.url)), "../.."); +const args = process.argv.slice(2); +const write = args.includes("--write"); +const onlyAt = args.indexOf("--only"); +const only = onlyAt >= 0 ? (args[onlyAt + 1] ?? "").split(",").map((s) => s.trim()).filter(Boolean) : []; +const folder = args.find((a, i) => !a.startsWith("--") && args[i - 1] !== "--only"); +if (!folder || !statSync(folder, { throwIfNoEntry: false })?.isDirectory()) { + console.error("Usage: node dev/biomes/export-tuned-biomes.mjs [--only id,id] [--write]"); + process.exit(2); +} + +// The TypeScript is loaded in CommonJS mode, as the tests load it (extensionless imports). +const { parseBiomeNote } = tsRequire(join(root, "src/overworld/biomeNote.ts"), import.meta.url); +const { SHIPPED_BIOMES } = tsRequire(join(root, SHIPPED_FILE), import.meta.url); + +const notes = readdirSync(folder) + .filter((f) => f.endsWith(".md") && !f.startsWith("_")) + .sort() + .map((f) => ({ name: basename(f, ".md"), content: readFileSync(join(folder, f), "utf8") })); + +const plan = planExport(notes, SHIPPED_BIOMES, parseBiomeNote, only); +console.log(formatPlan(plan)); +if (!plan.changes.length) process.exit(0); +if (!write) { + console.log(`\nDry run: nothing written. Run again with --write to update ${SHIPPED_FILE}.`); + process.exit(0); +} +writeFileSync(join(root, SHIPPED_FILE), shippedBiomesSource(plan.next)); +console.log(`\nWrote ${SHIPPED_FILE} (${plan.changes.length} biome${plan.changes.length === 1 ? "" : "s"}). Run npm test, then commit.`); diff --git a/dev/biomes/exportTuned.mjs b/dev/biomes/exportTuned.mjs new file mode 100644 index 00000000..230d8db7 --- /dev/null +++ b/dev/biomes/exportTuned.mjs @@ -0,0 +1,99 @@ +/** + * The pure part of dev/biomes/export-tuned-biomes.mjs (dev-only, never + * bundled): compare tuned biome notes with the shipped biome data and write + * the shipped data file. Takes the biome-note parser as an argument so it + * stays plain JavaScript (the script loads the TypeScript with tsx). + */ + +/** The shipped data file, relative to the repo root. */ +export const SHIPPED_FILE = "src/modules/world-maps/biomePresets.ts"; + +/** + * Fields carried from a tuned note into the shipped data: everything that + * shapes generation and placement. Label, colour, the generator link (a + * vault path), parent and blank stay as shipped. + */ +export const EXPORT_FIELDS = ["mix", "terrainWeights", "transitions", "blend", "landShare", "minIslands", "shore", "climate", "tuning"]; + +/** A field as compared: missing, undefined and empty lists/objects alike. */ +function norm(v, field) { + if (v === undefined || v === null || v === false) return undefined; + // Transitions and Mix are always written (empty lists stay lists); other empties are "none". + if (Array.isArray(v) && !v.length) return field === "mix" || field === "transitions" ? [] : undefined; + if (typeof v === "object" && !Array.isArray(v) && !Object.keys(v).length) return undefined; + return v; +} + +const show = (v) => (v === undefined ? "(none)" : JSON.stringify(v)); + +/** + * What exporting `notes` would change. + * @param notes [{ name, content }] read from the vault folder + * @param shipped the shipped biomes (BIOME_PRESETS) + * @param parse parseBiomeNote(content, basename) → { fields, problems } + * @param only ids to export (empty: all) + * @returns { changes: [{ id, label, fields: [{ field, from, to }] }], skipped: [string], next: shipped list with the changes } + */ +export function planExport(notes, shipped, parse, only = []) { + const next = shipped.map((b) => ({ ...b })); + const changes = []; + const skipped = []; + for (const n of notes) { + const { fields, problems } = parse(n.content, n.name); + const i = next.findIndex((b) => b.id === fields.id); + if (i < 0) { skipped.push(`${n.name}: not a shipped biome (id ${fields.id})`); continue; } + if (only.length && !only.includes(fields.id)) continue; + if (problems.length) skipped.push(`${n.name}: ${problems.length} unreadable bit(s), e.g. ${problems[0].where}: ${problems[0].text}`); + const cur = next[i]; + const diff = []; + for (const f of EXPORT_FIELDS) { + const from = norm(cur[f], f), to = norm(fields[f], f); + if (JSON.stringify(from) === JSON.stringify(to)) continue; + diff.push({ field: f, from, to }); + if (to === undefined) delete cur[f]; + else cur[f] = to; + } + if (diff.length) changes.push({ id: cur.id, label: cur.label, fields: diff }); + } + return { changes, skipped, next }; +} + +/** The diff as text, for the terminal. */ +export function formatPlan(plan) { + const out = []; + for (const c of plan.changes) { + out.push(`${c.label} (${c.id})`); + for (const d of c.fields) { + out.push(` ${d.field}:`); + out.push(` - ${show(d.from)}`); + out.push(` + ${show(d.to)}`); + } + } + if (!plan.changes.length) out.push("No changes: the shipped biomes already match."); + for (const s of plan.skipped) out.push(`Skipped ${s}`); + return out.join("\n"); +} + +/** The shipped data file's text: one biome per line, so a diff shows which biome changed. */ +export function shippedBiomesSource(list) { + return [ + "/**", + " * The shipped biomes as data (#50): written into biome notes once by", + " * BiomeStore (seedBiomeNotes), then the notes are what counts. See", + " * src/overworld/biomePresets.ts for what each field means.", + " *", + " * Hand edits are fine; tuned values from a vault's biome notes are copied", + " * in with dev/biomes/export-tuned-biomes.mjs (see dev/biomes/README.md),", + " * which rewrites this file one biome per line.", + " *", + " * Pure data.", + " */", + "", + 'import type { BiomePreset } from "../../overworld/biomePresets";', + "", + "export const SHIPPED_BIOMES: readonly BiomePreset[] = [", + ...list.map((b) => ` ${JSON.stringify(b)},`), + "];", + "", + ].join("\n"); +} diff --git a/dev/build-place-icons.mjs b/dev/build-place-icons.mjs new file mode 100644 index 00000000..e1c438fa --- /dev/null +++ b/dev/build-place-icons.mjs @@ -0,0 +1,188 @@ +#!/usr/bin/env node +/** + * Rebuilds the bundled "Places" icon pack in icons/ (files named place-*.svg): + * settlements, castles, towers, ruins, temples, camps and caves picked by the + * owner from game-icons.net (dev/icon-candidates.html, 2026-10-10). + * + * node dev/build-place-icons.mjs + * + * SVGs come from the Iconify API (one batched request) in the same shape as + * the space set: explicit width/height so they rasterise in and canvas + * (PNG export), and black glyphs so tinted rendering can use them as a mask. + * + * Writes: + * icons/place-.svg + * src/modules/world/placeIcons.ts (imports + each icon's kind, for picker grouping) + * icons/CREDITS.md (the block between the place-icons markers) + * + * All icons are CC BY 3.0 (https://creativecommons.org/licenses/by/3.0/); + * every one is credited to its author. Zero dependencies (Node ≥ 22). + */ +import fs from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; + +const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), ".."); +const outDir = path.join(root, "icons"); + +/** Picker sub-groups, in display order: [id, label]. */ +export const PLACE_KINDS = [ + ["settlement", "Settlements"], + ["castle", "Castles"], + ["tower", "Towers"], + ["ruin", "Ruins"], + ["temple", "Temples"], + ["camp", "Camps"], + ["cave", "Caves & mines"], +]; + +const AUTHORS = { + "delapouite": "Delapouite", + "lorc": "Lorc", + "caro-asercion": "Caro Asercion", + "pepijn-poolman": "Pepijn Poolman", + "heavenly-dog": "HeavenlyDog", + "quoting": "Quoting", +}; + +// [game-icons name, author slug, kind] — bundled as place-.svg. +export const PLACE_ICONS = [ + ["village", "delapouite", "settlement"], + ["huts-village", "delapouite", "settlement"], + ["medieval-village-01", "caro-asercion", "settlement"], + ["house", "delapouite", "settlement"], + ["family-house", "delapouite", "settlement"], + ["hut", "delapouite", "settlement"], + ["viking-longhouse", "delapouite", "settlement"], + ["windmill", "delapouite", "settlement"], + ["harbor-dock", "delapouite", "settlement"], + ["tavern-sign", "delapouite", "settlement"], + ["treehouse", "caro-asercion", "settlement"], + ["castle", "delapouite", "castle"], + ["elven-castle", "pepijn-poolman", "castle"], + ["hill-fort", "delapouite", "castle"], + ["military-fort", "delapouite", "castle"], + ["locked-fortress", "lorc", "castle"], + ["medieval-gate", "delapouite", "castle"], + ["defensive-wall", "heavenly-dog", "castle"], + ["stone-tower", "lorc", "tower"], + ["watchtower", "delapouite", "tower"], + ["white-tower", "lorc", "tower"], + ["guarded-tower", "lorc", "tower"], + ["tower-flag", "delapouite", "tower"], + ["evil-tower", "delapouite", "tower"], + ["clock-tower", "caro-asercion", "tower"], + ["lighthouse", "delapouite", "tower"], + ["castle-ruins", "delapouite", "ruin"], + ["ancient-ruins", "delapouite", "ruin"], + ["tower-fall", "lorc", "ruin"], + ["broken-wall", "delapouite", "ruin"], + ["damaged-house", "quoting", "ruin"], + ["spooky-house", "delapouite", "ruin"], + ["tombstone", "lorc", "ruin"], + ["church", "delapouite", "temple"], + ["greek-temple", "delapouite", "temple"], + ["egyptian-temple", "delapouite", "temple"], + ["byzantin-temple", "delapouite", "temple"], + ["temple-gate", "delapouite", "temple"], + ["shinto-shrine", "delapouite", "temple"], + ["fire-shrine", "delapouite", "temple"], + ["crystal-shrine", "delapouite", "temple"], + ["mayan-pyramid", "delapouite", "temple"], + ["great-pyramid", "delapouite", "temple"], + ["egyptian-pyramids", "delapouite", "temple"], + ["camping-tent", "delapouite", "camp"], + ["campfire", "lorc", "camp"], + ["forest-camp", "delapouite", "camp"], + ["desert-camp", "delapouite", "camp"], + ["goblin-camp", "delapouite", "camp"], + ["barracks-tent", "delapouite", "camp"], + ["cave-entrance", "delapouite", "cave"], + ["mountain-cave", "delapouite", "cave"], + ["dungeon-gate", "delapouite", "cave"], + ["gold-mine", "delapouite", "cave"], + ["mine-wagon", "delapouite", "cave"], +]; + +const fileOf = (name) => `place-${name}.svg`; + +async function buildSvgs() { + const url = `https://api.iconify.design/game-icons.json?icons=${PLACE_ICONS.map(([n]) => n).join(",")}`; + const res = await fetch(url); + if (!res.ok) throw new Error(`${url}: HTTP ${res.status}`); + const data = await res.json(); + for (const [name] of PLACE_ICONS) { + const icon = data.icons?.[name] ?? data.icons?.[data.aliases?.[name]?.parent]; + if (!icon) throw new Error(`game-icons:${name} not found`); + const w = icon.width ?? data.width ?? 512; + const h = icon.height ?? data.height ?? 512; + const scale = Math.max(1, Math.round(128 / Math.max(w, h))); + const svg = + `` + + `${icon.body.replace(/currentColor/g, "#000")}\n`; + fs.writeFileSync(path.join(outDir, fileOf(name)), svg); + } + console.log(`game-icons: ${PLACE_ICONS.length} place icons`); +} + +/** Regenerate src/modules/world/placeIcons.ts from the list above. */ +function writeImports() { + const ident = (name) => "place" + name.replace(/(^|-)([a-z0-9])/g, (_, __, c) => c.toUpperCase()); + const lines = [ + "// Generated by dev/build-place-icons.mjs — Places icon pack (see icons/CREDITS.md).", + ...PLACE_ICONS.map(([n]) => `import ${ident(n)} from "../../../icons/${fileOf(n)}";`), + "", + "/** Sub-groups of the Places pack, in picker order: [id, label]. */", + "export const PLACE_KINDS: [string, string][] = [", + ...PLACE_KINDS.map(([id, label]) => `\t["${id}", "${label}"],`), + "];", + "", + "/** [file name, data URL, kind id] */", + "export const BUNDLED_PLACE_ICONS: [string, string, string][] = [", + ...PLACE_ICONS.map(([n, , kind]) => `\t["${fileOf(n)}", ${ident(n)}, "${kind}"],`), + "];", + "", + ]; + fs.writeFileSync(path.join(root, "src", "modules", "world", "placeIcons.ts"), lines.join("\n")); + console.log(`src/modules/world/placeIcons.ts: ${PLACE_ICONS.length} imports`); +} + +/** Rewrite the Places block of icons/CREDITS.md (between the markers). */ +function writeCredits() { + const file = path.join(outDir, "CREDITS.md"); + const raw = fs.readFileSync(file, "utf8"); + const eol = raw.includes("\r\n") ? "\r\n" : "\n"; + const text = raw.replace(/\r\n/g, "\n"); + const begin = ""; + const end = ""; + const block = [ + begin, + "", + "### Places pack (`place-*.svg`)", + "", + "Settlement, castle, tower, ruin, temple, camp and cave icons from https://game-icons.net,", + "licensed under Creative Commons Attribution 3.0 (https://creativecommons.org/licenses/by/3.0/).", + "Renamed with a `place-` prefix and set to black; otherwise unmodified.", + "Rebuild with `node dev/build-place-icons.mjs`.", + "", + ...PLACE_ICONS.map(([n, a]) => `- \`${fileOf(n)}\` ← [\`${n}\`](https://game-icons.net/1x1/${a}/${n}.html) — by ${AUTHORS[a] ?? a}`), + "", + end, + ].join("\n"); + const i = text.indexOf(begin); + const j = text.indexOf(end); + let next; + if (i >= 0 && j > i) next = text.slice(0, i) + block + text.slice(j + end.length); + else { + const anchor = "## Material Design Icons"; + const k = text.indexOf(anchor); + if (k < 0) throw new Error("CREDITS.md: no place to insert the Places block"); + next = text.slice(0, k) + block + "\n\n" + text.slice(k); + } + fs.writeFileSync(file, next.replace(/\n/g, eol)); + console.log("icons/CREDITS.md: Places block written"); +} + +await buildSvgs(); +writeImports(); +writeCredits(); diff --git a/dev/build-space-icons.mjs b/dev/build-space-icons.mjs new file mode 100644 index 00000000..6870948b --- /dev/null +++ b/dev/build-space-icons.mjs @@ -0,0 +1,166 @@ +#!/usr/bin/env node +/** + * Rebuilds the bundled space icon set in icons/ (files named space-*.svg / .png). + * + * node dev/build-space-icons.mjs + * + * SVGs come from the Iconify API (one batched request per collection) and are + * written with explicit width/height so they rasterise correctly in and + * canvas (PNG export). Kenney sprites are white; they are recoloured to black + * silhouettes (alpha kept) so they read like the other glyphs in untinted + * picker previews. Tinted map rendering uses them as a mask, so colour there + * comes from the terrain's icon colour either way. + * + * Sources and licences: see icons/CREDITS.md. Zero dependencies (Node ≥ 22). + */ +import fs from "node:fs"; +import path from "node:path"; +import zlib from "node:zlib"; +import { fileURLToPath } from "node:url"; + +const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), ".."); +const outDir = path.join(root, "icons"); +const kenneyDir = process.argv[2]; + +// [collection, source name, bundled basename] +export const SVG_ICONS = [ + // game-icons.net — CC BY 3.0 (Lorc, Delapouite) + ["game-icons", "uncertainty", "space-anomaly"], + ["game-icons", "black-hole-bolas", "space-black-hole"], + ["game-icons", "comet-spark", "space-comet"], + ["game-icons", "fragmented-meteor", "space-debris"], + ["game-icons", "dust-cloud", "space-dust-cloud"], + ["game-icons", "star-swirl", "space-star-swirl"], + ["game-icons", "world", "space-world"], + ["game-icons", "ringed-planet", "space-ringed-planet"], + ["game-icons", "frozen-orb", "space-frozen-orb"], + ["game-icons", "radial-balance", "space-radial-balance"], + ["game-icons", "portal", "space-portal"], + ["game-icons", "star-gate", "space-star-gate"], + ["game-icons", "planet-core", "space-planet-core"], + ["game-icons", "galaxy", "space-galaxy"], + ["game-icons", "stone-sphere", "space-stone-sphere"], + ["game-icons", "vortex", "space-vortex"], + ["game-icons", "sun", "space-sun"], + ["game-icons", "orbital", "space-orbital"], + ["game-icons", "defense-satellite", "space-defense-satellite"], + // Tabler Icons — MIT + ["tabler", "atom-2", "space-atom-outline"], + ["tabler", "circle-dot", "space-target-outline"], + ["tabler", "shield", "space-shield-outline"], + ["tabler", "meteor", "space-meteor-outline"], + ["tabler", "circle-dashed", "space-ring-dashed"], + ["tabler", "planet", "space-planet-outline"], + ["tabler", "moon", "space-moon-outline"], + ["tabler", "sun", "space-sun-outline"], + ["tabler", "orbit", "space-orbit-outline"], + ["tabler", "building-broadcast-tower", "space-beacon-outline"], + // Material Design Icons (Pictogrammers) — Apache 2.0 + ["mdi", "circle-double", "space-double-ring"], + ["mdi", "meteor", "space-meteor"], + ["mdi", "dots-hexagon", "space-dots-hex"], + ["mdi", "circle-slice-8", "space-ring-segments"], + ["mdi", "star-four-points-outline", "space-twinkle"], + ["mdi", "rocket-launch", "space-rocket"], + ["mdi", "earth", "space-earth"], + ["mdi", "planet", "space-planet"], + ["mdi", "circle-outline", "space-ring"], + ["mdi", "moon-full", "space-moon"], + ["mdi", "water-circle", "space-water-world"], + ["mdi", "ufo-outline", "space-ufo"], + ["mdi", "white-balance-sunny", "space-sun-rays"], + ["mdi", "orbit", "space-orbit"], + ["mdi", "space-station", "space-station"], + ["mdi", "radioactive", "space-radioactive"], +]; + +// Kenney Simple Space — CC0. [sprite, bundled basename] +export const KENNEY_ICONS = [ + ["meteor_detailedLarge", "space-asteroid"], + ["star_large", "space-star-large"], + ["star_medium", "space-star-medium"], + ["ship_sidesA", "space-ship-sides-a"], + ...["A", "B", "C", "D", "F", "G", "I", "J", "K", "L"].map((l) => [`ship_${l}`, `space-ship-${l.toLowerCase()}`]), + ...["A", "B", "C", "D"].map((l) => [`enemy_${l}`, `space-raider-${l.toLowerCase()}`]), + ...["A", "B", "C"].map((l) => [`station_${l}`, `space-station-${l.toLowerCase()}`]), + ...["A", "B", "C", "D"].map((l) => [`satellite_${l}`, `space-satellite-${l.toLowerCase()}`]), +]; + +async function buildSvgs() { + const byCollection = new Map(); + for (const [col, name, out] of SVG_ICONS) { + if (!byCollection.has(col)) byCollection.set(col, []); + byCollection.get(col).push([name, out]); + } + for (const [col, list] of byCollection) { + const url = `https://api.iconify.design/${col}.json?icons=${list.map(([n]) => n).join(",")}`; + const res = await fetch(url); + if (!res.ok) throw new Error(`${url}: HTTP ${res.status}`); + const data = await res.json(); + for (const [name, out] of list) { + const icon = data.icons?.[name] ?? data.icons?.[data.aliases?.[name]?.parent]; + if (!icon) throw new Error(`${col}:${name} not found`); + const w = icon.width ?? data.width ?? 24; + const h = icon.height ?? data.height ?? 24; + // Size up small-grid sets so /canvas rasterise them crisply. + const scale = Math.max(1, Math.round(128 / Math.max(w, h))); + const svg = + `` + + `${icon.body.replace(/currentColor/g, "#000")}\n`; + fs.writeFileSync(path.join(outDir, `${out}.svg`), svg); + } + console.log(`${col}: ${list.length} icons`); + } +} + +/** Blacken an indexed-colour PNG's palette; transparency (tRNS) is untouched. */ +function blackenIndexedPng(buf) { + if (buf[25] !== 3) throw new Error("expected an indexed-colour PNG"); + const out = Buffer.from(buf); + let off = 8; + while (off < out.length) { + const len = out.readUInt32BE(off); + const type = out.toString("latin1", off + 4, off + 8); + if (type === "PLTE") { + out.fill(0, off + 8, off + 8 + len); + const crc = zlib.crc32(out.subarray(off + 4, off + 8 + len)); + out.writeUInt32BE(crc >>> 0, off + 8 + len); + } + off += 12 + len; + } + return out; +} + +function buildKenney() { + if (!kenneyDir) { + console.log("kenney: skipped (pass the unzipped kenney_simple-space folder to rebuild)"); + return; + } + const src = path.join(kenneyDir, "PNG", "Retina"); + for (const [sprite, out] of KENNEY_ICONS) { + const png = fs.readFileSync(path.join(src, `${sprite}.png`)); + fs.writeFileSync(path.join(outDir, `${out}.png`), blackenIndexedPng(png)); + } + console.log(`kenney: ${KENNEY_ICONS.length} icons`); +} + +/** Regenerate src/modules/space/spaceIcons.ts from whatever space-* files are in icons/. */ +function writeImports() { + const files = fs.readdirSync(outDir).filter((f) => /^space-.*\.(svg|png)$/.test(f)).sort(); + const ident = (f) => f.replace(/\.(svg|png)$/, "").replace(/-([a-z0-9])/g, (_, c) => c.toUpperCase()); + const lines = [ + "// Generated by dev/build-space-icons.mjs — space icon pack (see icons/CREDITS.md).", + ...files.map((f) => `import ${ident(f)} from "../../../icons/${f}";`), + "", + "export const BUNDLED_SPACE_ICONS: [string, string][] = [", + ...files.map((f) => `\t["${f}", ${ident(f)}],`), + "];", + "", + ]; + fs.writeFileSync(path.join(root, "src", "modules", "space", "spaceIcons.ts"), lines.join("\n")); + console.log(`src/modules/space/spaceIcons.ts: ${files.length} imports`); +} + +await buildSvgs(); +buildKenney(); +writeImports(); diff --git a/dev/coord-label-thrash-bench.html b/dev/coord-label-thrash-bench.html index 488b1908..aebe9895 100644 --- a/dev/coord-label-thrash-bench.html +++ b/dev/coord-label-thrash-bench.html @@ -105,6 +105,23 @@ label.style.setProperty("--duckmage-coord-x", ((p.ox / gw) * 100).toFixed(3) + "%"); label.style.setProperty("--duckmage-coord-y", ((p.oy / gh) * 100).toFixed(3) + "%"); } + return { pos, gw, gh }; + } + + // ── batched + the uncharted marker layer (renderUnchartedLayer): it + // reuses the positions just read and only writes (a third of hexes) ── + function batchedWithUncharted() { + const { pos, gw, gh } = batched(); + grid.querySelector(".uncharted-layer")?.remove(); + const layer = grid.appendChild(document.createElement("div")); + layer.className = "uncharted-layer"; + pos.forEach((p, i) => { + if (i % 3) return; + const mark = layer.appendChild(document.createElement("span")); + mark.textContent = "?"; + mark.style.setProperty("--duckmage-uncharted-x", ((p.ox / gw) * 100).toFixed(3) + "%"); + mark.style.setProperty("--duckmage-uncharted-y", ((p.oy / gh) * 100).toFixed(3) + "%"); + }); } function time(fn, withBg, iters) { @@ -124,7 +141,7 @@ // One config per call so each puppeteer evaluate stays short (the thrash // path on a bg map can take seconds per iteration). window.__measure = (which, withBg, iters) => - time(which === "thrash" ? thrashing : batched, withBg, iters); + time(which === "thrash" ? thrashing : which === "uncharted" ? batchedWithUncharted : batched, withBg, iters); document.title = "ready"; diff --git a/dev/coord-label-thrash-bench.mjs b/dev/coord-label-thrash-bench.mjs index 42dd5cf3..611a1e19 100644 --- a/dev/coord-label-thrash-bench.mjs +++ b/dev/coord-label-thrash-bench.mjs @@ -24,6 +24,8 @@ const r = await withBrowser(async ({ page }) => { batch_noBg: await m("batch", false), thrash_bg: await m("thrash", true), batch_bg: await m("batch", true), + uncharted_noBg: await m("uncharted", false), + uncharted_bg: await m("uncharted", true), }; }); @@ -32,5 +34,6 @@ console.log(`\nrenderCoordLabelsLayer cost — hexes=${r.hexCount}, median of ${ console.log(` no bg image with bg image`); console.log(`thrash (current) ${f(r.thrash_noBg)} ${f(r.thrash_bg)} ← regression`); console.log(`batch (fixed) ${f(r.batch_noBg)} ${f(r.batch_bg)}`); +console.log(`batch + uncharted ${f(r.uncharted_noBg)} ${f(r.uncharted_bg)} (the ? layer reuses the read positions)`); console.log(`\nspeedup no-bg: ${(r.thrash_noBg / r.batch_noBg).toFixed(1)}× with-bg: ${(r.thrash_bg / r.batch_bg).toFixed(1)}×`); console.log(`bg amplifies thrash by ${(r.thrash_bg / r.thrash_noBg).toFixed(1)}× (vs ${(r.batch_bg / r.batch_noBg).toFixed(1)}× when batched)\n`); diff --git a/dev/decisions.html b/dev/decisions.html new file mode 100644 index 00000000..882e6d5a --- /dev/null +++ b/dev/decisions.html @@ -0,0 +1,141 @@ + + +loading + +

Hexmaker — open decisions

+

Click one option per card (add a note if you like). Picks save in this page; tell Claude when you're done and it reads them back.

+
+
+ diff --git a/dev/demo-seed/.hexmaker-sandbox b/dev/demo-seed/.hexmaker-sandbox new file mode 100644 index 00000000..a9102929 --- /dev/null +++ b/dev/demo-seed/.hexmaker-sandbox @@ -0,0 +1 @@ +This vault is a throwaway sandbox made by dev/demo-world.mjs. The Hexmap World Creator demo builders only run in vaults holding this file. diff --git a/dev/demo-seed/Start here.md b/dev/demo-seed/Start here.md new file mode 100644 index 00000000..c113f1f6 --- /dev/null +++ b/dev/demo-seed/Start here.md @@ -0,0 +1,17 @@ +# Overworld demo + +A sandbox vault. Nothing here touches your real vault. The map view opens on **Demo Bricks**: a 19-hex overworld from the World biomes generator. Every hex opens into an 8 × 8 region, and all 19 regions are already made. + +Things to try: + +- [ ] **The full view.** The overworld shows every region's hexes stitched together. Hover a hex for its region's name. Click anywhere to go into that region, at that spot. +- [ ] **The minimap** (bottom right). Click a hex on it to jump to that region. Inside a region it outlines where you are. +- [ ] **Cross a seam.** In a region, the names in the bar above the map are its neighbours ("North-east: …"). The dimmed hexes past the edge are the next region: click one to go there. +- [ ] **Find a transition.** Hexes with a white outline (Biomes view, or the minimap) are in-between biomes, like taiga between tundra and forest. +- [ ] **Paint across regions.** On the overworld, pick the terrain tool and paint a river valley or a road corridor straight over the stitched hexes. It writes into each region it crosses. Undo takes the whole stroke back. +- [ ] **Set a biome.** Switch to **Biomes** (bottom right) and click a hex. Pick another biome: the region is remade (it asks first). Your hand-painted hexes stay. +- [ ] **Reroll and tune.** In the same box, **Reroll** for a new layout, or **Settings…** for blend, wiggly borders and seed, with a live preview. +- [ ] **Locations.** The middle hex has three locations: right-click it for "Locations (3)…". +- [ ] **Go up.** From a region, the breadcrumb (or Go up) returns to the overworld and flashes the hex. + +Hex-flower regions (a hex of hexes per overworld hex) aren't in this demo yet. diff --git a/dev/demo-world.mjs b/dev/demo-world.mjs new file mode 100644 index 00000000..1c556602 --- /dev/null +++ b/dev/demo-world.mjs @@ -0,0 +1,99 @@ +#!/usr/bin/env node +/** + * Overworld demo world for playtesting (OW7), in a THROWAWAY sandbox vault. + * + * # build first (from WSL): npm run build + * node dev/demo-world.mjs [--seed 7] [--bench] [--no-launch-check] + * + * 1. `sandbox.mjs create` a new run from this worktree's built plugin, with + * dev/demo-seed (the `.hexmaker-sandbox` marker + "Start here.md"). + * 2. `sandbox.mjs launch` (separate Obsidian profile, its own CDP port). + * 3. Connects, checks the open vault IS the run's vault and holds the marker, + * then calls plugin.devTools.buildDemoWorld() (and buildBenchWorld() with + * --bench: 100 regions × 64 hexes, with layer timings). + * 4. Writes demo.json and a screenshot into the run folder, prints the run + * folder, and LEAVES OBSIDIAN RUNNING for the owner. Stop it with + * `node stop --run `. + * + * Never touches the main vault: sandbox.mjs refuses to create runs inside a + * vault, and this script refuses unless the open vault is the run's vault + * and has the marker file. + */ +import fs from "node:fs"; +import path from "node:path"; +import { execFileSync } from "node:child_process"; +import { fileURLToPath, pathToFileURL } from "node:url"; + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const ROOT = path.resolve(HERE, ".."); +const SB_DIR = process.env.UX_SANDBOX_DIR ?? "C:/Users/markr/work/tools/skills-share/ux-testing/fresh-eyes-tester/scripts"; +const SB = path.join(SB_DIR, "sandbox.mjs"); +const MARKER = ".hexmaker-sandbox"; +const PLUGIN_ID = JSON.parse(fs.readFileSync(path.join(ROOT, "manifest.json"), "utf8")).id; + +const args = process.argv.slice(2); +const flag = (k) => args.includes(`--${k}`); +const val = (k, d) => { const i = args.indexOf(`--${k}`); return i >= 0 && args[i + 1] ? args[i + 1] : d; }; +const seed = Number(val("seed", "7")); +const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); +const die = (m) => { console.error("ERROR: " + m); process.exit(1); }; + +if (!fs.existsSync(path.join(ROOT, "main.js"))) die("main.js missing: build first (npm run build)."); +const common = await import(pathToFileURL(path.join(SB_DIR, "lib", "common.mjs")).href); + +// 1. create +const created = JSON.parse(execFileSync(process.execPath, [SB, "create", "--plugin-dir", ROOT, "--seed", path.join(HERE, "demo-seed"), "--name", flag("bench") ? "demo-bench" : "demo-world"], { encoding: "utf8" })); +const runDir = created.runDir; +if (!fs.existsSync(path.join(created.vault, MARKER))) die(`marker ${MARKER} missing in ${created.vault}`); +// 2. launch +execFileSync(process.execPath, [SB, "launch", "--run", runDir, "--width", "1500", "--height", "950"], { stdio: "inherit" }); + +const run = common.readRun(runDir); +const { browser, page } = await common.connect(run); +try { + // 3. safety: the open vault is the sandbox vault, with the marker + const base = await common.assertSandboxVault(page, run); + if (!base || !common.samePath(base, run.vault)) die(`open vault ${base} is not the sandbox vault ${run.vault}`); + if (!fs.existsSync(path.join(base, MARKER))) die("open vault has no sandbox marker"); + + // wait for the plugin's dev tools (palettes + map store load first) + const t0 = Date.now(); + while (!(await page.evaluate((id) => !!window.app.plugins.plugins[id]?.devTools, PLUGIN_ID))) { + if (Date.now() - t0 > 30000) die("plugin devTools never appeared (is the marker in the vault root?)"); + await sleep(500); + } + const report = { runDir, vault: run.vault, seed }; + report.demo = await page.evaluate((id, s) => window.app.plugins.plugins[id].devTools.buildDemoWorld({ seed: s }), PLUGIN_ID, seed); + if (flag("bench")) report.bench = await page.evaluate((id) => window.app.plugins.plugins[id].devTools.buildBenchWorld({ side: 10 }), PLUGIN_ID); + + // open the map view on the overworld and time the region layer + const showAndTime = async (name) => { + await page.evaluate(async (id, n) => { + const p = window.app.plugins.plugins[id]; + document.querySelectorAll(".modal-container .modal-close-button").forEach((b) => b.click()); + await p.showMap(n); + }, PLUGIN_ID, name); + await sleep(2500); + // second draw: bitmaps cached (only the composite) + const first = await page.evaluate((id) => window.app.plugins.plugins[id].devTools.overworldStats(), PLUGIN_ID); + // Two redraws: the first may still follow the restored zoom; the second is the cached one. + for (let i = 0; i < 2; i++) { + await page.evaluate(() => window.app.workspace.getLeavesOfType("duckmage-hex-map")[0]?.view?.redraw?.()); + await sleep(1500); + } + const cached = await page.evaluate((id) => window.app.plugins.plugins[id].devTools.overworldStats(), PLUGIN_ID); + return { first, cached }; + }; + if (report.bench) { + report.benchLayer = await showAndTime(report.bench.name); + await page.screenshot({ path: path.join(runDir, "shots", "bench-overworld.png") }); + } + report.demoLayer = await showAndTime(report.demo.overworld); + await page.screenshot({ path: path.join(runDir, "shots", "demo-overworld.png") }); + fs.writeFileSync(path.join(runDir, "demo.json"), JSON.stringify(report, null, 2)); + console.log(JSON.stringify(report, null, 2)); + console.log(`\nDemo ready. Run folder: ${runDir}`); + console.log(`Obsidian is left running. Stop it with: node "${SB}" stop --run "${runDir}"`); +} finally { + browser.disconnect(); +} diff --git a/dev/hex-outline.html b/dev/hex-outline.html new file mode 100644 index 00000000..0c0e1017 --- /dev/null +++ b/dev/hex-outline.html @@ -0,0 +1,36 @@ + + +loading + + +
+

Before (2px border + clip-path)

+

After (current styles.css)

+
+ diff --git a/dev/measure-patches.ts b/dev/measure-patches.ts new file mode 100644 index 00000000..d46a6df1 --- /dev/null +++ b/dev/measure-patches.ts @@ -0,0 +1,41 @@ +/** + * Measure how often each biome's terrain types survive in a region (#50 + * min patches): for every shipped biome, 200 seeds of an 8×8 region ringed + * by the same biome and by grassland, the share of regions with no cell of + * each type. Run: npx tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs dev/measure-patches.ts + */ +import { DEFAULT_TERRAIN_PALETTE } from "../src/constants"; +import { BIOME_PRESETS } from "../src/overworld/biomePresets"; +import { noteBiomeProfiles, setBiomeSource } from "../src/overworld/biomes"; +import { BlendField, REGION_WARP } from "../src/overworld/blendField"; +import { generateRegion } from "../src/overworld/regionGen"; +import type { RegionLayout } from "../src/overworld/layout"; +import { hexDistance } from "../packages/hex-wfc/src/grid"; + +const strip = !!(globalThis as { process?: { argv: string[] } }).process?.argv.includes("--no-min"); +setBiomeSource(strip ? BIOME_PRESETS.map((b) => ({ ...b, mix: b.mix.map((r) => ({ type: r.type, weight: r.weight })) })) : BIOME_PRESETS); +const palette = DEFAULT_TERRAIN_PALETTE; +const profiles = noteBiomeProfiles(palette); +const typeOfMap = new Map(palette.map((t) => [t.name, t.type])); +const typeOf = (n: string) => typeOfMap.get(n); +const l: RegionLayout = { footprint: "rect", size: 8, orientation: "flat", parentStagger: "odd", childStagger: "odd" }; +const ringed = (centre: string, around: string) => { + const m = new Map(); + for (let x = 0; x < 5; x++) for (let y = 0; y < 5; y++) m.set(`${x}_${y}`, hexDistance([x, y], [2, 2], "flat", "odd") === 0 ? centre : around); + return m; +}; +for (const b of BIOME_PRESETS) { + const p = profiles.get(b.id); + if (!p) continue; + for (const around of [b.id, "grassland"]) { + const missing = new Map(); + for (let seed = 1; seed <= 200; seed++) { + const field = new BlendField(l, ringed(b.id, around), "normal", { warp: REGION_WARP, seed }); + const out = generateRegion({ layout: l, parent: [2, 2], field, profiles, typeOf, seed }); + const types = new Set([...out.values()].map(typeOf)); + for (const t of p.types.keys()) if (!types.has(t)) missing.set(t, (missing.get(t) ?? 0) + 1); + } + const row = [...p.types].map(([t, s]) => `${t} ${Math.round(s * 100)}%: ${Math.round(((missing.get(t) ?? 0) / 200) * 100)}%`).join(", "); + console.log(`${b.id} (ringed by ${around}) missing → ${row}`); + } +} diff --git a/dev/measureBiomeIdentity.ts b/dev/measureBiomeIdentity.ts new file mode 100644 index 00000000..1852c19e --- /dev/null +++ b/dev/measureBiomeIdentity.ts @@ -0,0 +1,90 @@ +/** + * Measure a region's biome identity among made neighbours (owner 2026-10-12: + * "new regions mesh with their neighbours at the seams, but the region must + * still clearly be its own biome"). The cases and measures live in + * tests/helpers/biomeIdentity.ts (shared with tests/biomeIdentity.test.ts). + * + * - ring: a region of biome X with all six neighbours (biome N) made first, + * e.g. Alpine among Temperate forest. Its type shares, the identity + * distance (mixDistance: half the summed share differences against its + * biome's Mix, 0 = exactly the Mix, 1 = nothing in common), the same + * region with no neighbour context (neighbour influence 0), and its seam + * continuity (edge hexes whose land/water class carries on). + * - owner: the owner's demo world, every region made, then 4, 2 remade as Alpine. + * - worlds: every parity world and the owner's: seam continuity and the + * mean identity distance of the regions made after a neighbour. + * + * npx tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs dev/measureBiomeIdentity.ts + */ + +import { mixDistance, seamContinuity, seamStats, interiorAgreement } from "../src/overworld/regionGen"; +import { paletteTypeOf, planRegion, regionOrder, worldSeed } from "../src/overworld/regionWorld"; +import { regionCells } from "../src/overworld/layout"; +import { SCENARIOS, scenarioBiomes, scenarioProfiles } from "../tests/biomeParityFixtures"; +import { OWNER_BIOMES, OWNER_LAYOUT, OWNER_WORLD_ID, ownerProfiles, ownerTypeOf } from "../tests/regionMeshFixtures"; +import { allProfiles, pct, ringCase, typeOf, typeShares } from "../tests/helpers/biomeIdentity"; + +const fmtShares = (s: Map) => [...s].sort((a, b) => b[1] - a[1]).map(([t, v]) => `${t} ${Math.round(v * 100)}`).join(", "); + +{ + console.log("## Ring: biome X with all six neighbours (biome N) made first; 8x8 regions"); + console.log("centre | around | identity no ctx | identity with ctx | continuity | shares with ctx"); + const RINGS: [string, string][] = [ + ["alpine", "temperate-forest"], ["alpine", "taiga"], ["alpine", "deep-forest"], ["alpine", "grassland"], + ["caverns", "temperate-forest"], ["underdark", "grassland"], ["fungal-forest", "temperate-forest"], + ["underground-lake", "grassland"], ["mines", "taiga"], ["magma-caves", "temperate-forest"], + ["volcanic", "jungle"], ["desert", "temperate-forest"], ["tundra", "taiga"], ["coast", "open-sea"], + ]; + for (const [c, a] of RINGS) { + const w = ringCase(c, a); + const solo = ringCase(c, a, { tuning: { "neighbour-influence": 0, "context-depth": 0 } }); + const sc = seamContinuity(w.layout, [2, 2], w.cells, w.pinned, typeOf); + console.log(`${c} | ${a} | ${mixDistance(solo.cells, w.profile, typeOf).toFixed(2)} | ${mixDistance(w.cells, w.profile, typeOf).toFixed(2)} | ${sc.matched}/${sc.edge} | ${fmtShares(typeShares(w.cells))}`); + if (process.argv.includes("--solo")) console.log(` no ctx: ${fmtShares(typeShares(solo.cells))}`); + } + + // The owner's demo world, every region made, then 4, 2 remade as Alpine. + console.log("\n## Owner demo world: 4, 2 remade as Alpine with every other region made"); + const ws = worldSeed(OWNER_WORLD_ID); + const plain = ownerProfiles(); + const order = regionOrder([...OWNER_BIOMES.keys()].map((k) => k.split("_").map(Number) as [number, number]), OWNER_LAYOUT.orientation, OWNER_LAYOUT.parentStagger); + const made = new Map(); + for (const [px, py] of order) { + const plan = planRegion({ layout: OWNER_LAYOUT, parent: [px, py], biomes: OWNER_BIOMES, profiles: plain, pinned: new Map(made), typeOf: ownerTypeOf, worldSeed: ws, seed: ws }); + for (const [k, t] of plan.cells) made.set(k, t); + } + const own = new Set(regionCells(OWNER_LAYOUT, 4, 2).map(([x, y]) => `${x}_${y}`)); + const pinned = new Map([...made].filter(([k]) => !own.has(k))); + const biomes = new Map(OWNER_BIOMES); + biomes.set("4_2", "alpine"); + const alp = allProfiles(); + const plan = planRegion({ layout: OWNER_LAYOUT, parent: [4, 2], biomes, profiles: alp, pinned, typeOf: ownerTypeOf, worldSeed: ws, seed: ws }); + const sc = seamContinuity(OWNER_LAYOUT, [4, 2], plan.cells, pinned, ownerTypeOf); + console.log(`identity ${mixDistance(plan.cells, alp.get("alpine")!, ownerTypeOf).toFixed(2)}, continuity ${sc.matched}/${sc.edge}, shares: ${fmtShares(typeShares(plan.cells, ownerTypeOf))}`); + + console.log("\n## Worlds: seam continuity, mean identity of regions made after a neighbour"); + console.log("world | continuity | seam type agreement | interior agreement | mean identity (with neighbours) | mean identity (first regions)"); + const worlds = [ + ...SCENARIOS.map((s) => { + const profiles = scenarioProfiles(s); + return { name: s.name, layout: s.layout, tOf: paletteTypeOf(s.palette), biomes: scenarioBiomes(s, [...profiles.keys()].sort()), profiles, ws: worldSeed(`parity-${s.name}`), seed: (px: number, py: number, w: number) => w ^ (px * 131 + py * 17), extra: { ...(s.blend ? { blend: s.blend } : {}), ...(s.warp !== undefined ? { warp: s.warp } : {}) } }; + }), + { name: "owner-demo", layout: OWNER_LAYOUT, tOf: ownerTypeOf, biomes: OWNER_BIOMES, profiles: ownerProfiles(), ws: worldSeed(OWNER_WORLD_ID), seed: (_x: number, _y: number, w: number) => w, extra: {} }, + ]; + for (const w of worlds) { + const pin = new Map(); + let edge = 0, matched = 0, dN = 0, nN = 0, dF = 0, nF = 0; + const hexes = [...w.biomes.keys()].map((k) => k.split("_").map(Number) as [number, number]); + for (const [px, py] of regionOrder(hexes, w.layout.orientation, w.layout.parentStagger)) { + const p = planRegion({ layout: w.layout, parent: [px, py], biomes: w.biomes, profiles: w.profiles, pinned: pin, typeOf: w.tOf, worldSeed: w.ws, seed: w.seed(px, py, w.ws), ...w.extra }); + const c = seamContinuity(w.layout, [px, py], p.cells, pin, w.tOf); + const prof = w.profiles.get(w.biomes.get(`${px}_${py}`)!); + const d = prof ? mixDistance(p.cells, prof, w.tOf) : 0; + if (c.edge) { dN += d; nN++; } else { dF += d; nF++; } + edge += c.edge; matched += c.matched; + for (const [k, t] of p.cells) pin.set(k, t); + } + const st = seamStats(w.layout, pin, w.tOf), pairs = st.reduce((s, x) => s + x.pairs, 0); + console.log(`${w.name} | ${pct(matched / edge)} (${matched}/${edge}) | ${pct(st.reduce((s, x) => s + x.typeAgreement * x.pairs, 0) / pairs)} | ${pct(interiorAgreement(w.layout, pin, w.tOf))} | ${(dN / Math.max(1, nN)).toFixed(3)} | ${(dF / Math.max(1, nF)).toFixed(3)}`); + } +} diff --git a/dev/measureRegionMesh.ts b/dev/measureRegionMesh.ts new file mode 100644 index 00000000..a1ab04c4 --- /dev/null +++ b/dev/measureRegionMesh.ts @@ -0,0 +1,78 @@ +/** + * Measure neighbour-conditioned generation (owner 2026-10-12, "super-region"): + * for each biome-tuning parity scenario and the owner's demo world, every + * region made after a neighbour, before (neighbour influence 0: the old + * generation) and with the tuning given. Prints seam continuity (edge hexes + * whose land/water class matches across the seam), seam type agreement, + * interior type agreement (the baseline a seam should match), the share of + * cells whose type the region's own biome has (so context doesn't wash the + * biome out), and ms per region. + * + * npx tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs dev/measureRegionMesh.ts [influence] [depth] + */ +import { SCENARIOS, scenarioBiomes, scenarioProfiles } from "../tests/biomeParityFixtures"; +import { OWNER_BIOMES, OWNER_LAYOUT, OWNER_WORLD_ID, ownerProfiles } from "../tests/regionMeshFixtures"; +import { DEFAULT_TERRAIN_PALETTE } from "../src/constants"; +import { interiorAgreement, seamContinuity, seamStats } from "../src/overworld/regionGen"; +import { paletteTypeOf, planRegion, regionOrder, worldSeed } from "../src/overworld/regionWorld"; +import type { BiomeProfile } from "../src/overworld/biomes"; +import type { RegionLayout } from "../src/overworld/layout"; +import type { TerrainColor } from "../src/types"; +import type { BiomeTuning } from "../src/overworld/biomeTuning"; + +const argv = (globalThis as { process?: { argv: string[] } }).process?.argv ?? []; +const nums = argv.slice(2).map(Number).filter((n) => Number.isFinite(n)); +const after: BiomeTuning = { ...(nums[0] !== undefined ? { "neighbour-influence": nums[0] } : {}), ...(nums[1] !== undefined ? { "context-depth": nums[1] } : {}) }; + +interface World { name: string; layout: RegionLayout; palette: TerrainColor[]; biomes: Map; seed: (px: number, py: number) => number; ws: number; profiles: (t: BiomeTuning) => Map; blend?: "narrow" | "normal" | "wide"; warp?: number } + +const tunedCopy = (m: Map, t: BiomeTuning) => new Map([...m].map(([k, p]) => [k, { ...p, tuning: { ...(p.tuning ?? {}), ...t } }])); + +const worlds: World[] = SCENARIOS.map((s) => { + const base = scenarioProfiles(s); + const ws = worldSeed(`parity-${s.name}`); + return { name: s.name, layout: s.layout, palette: s.palette, biomes: scenarioBiomes(s, [...base.keys()].sort()), ws, seed: (px, py) => ws ^ (px * 131 + py * 17), profiles: (t) => tunedCopy(scenarioProfiles(s), t), ...(s.blend ? { blend: s.blend } : {}), ...(s.warp !== undefined ? { warp: s.warp } : {}) }; +}); +const ows = worldSeed(OWNER_WORLD_ID); +worlds.push({ name: "owner-demo", layout: OWNER_LAYOUT, palette: DEFAULT_TERRAIN_PALETTE, biomes: OWNER_BIOMES, ws: ows, seed: () => ows, profiles: (t) => ownerProfiles(t) }); + +function run(w: World, tuning: BiomeTuning) { + const profiles = w.profiles(tuning); + const typeOf = paletteTypeOf(w.palette); + const pinned = new Map(); + const hexes = [...w.biomes.keys()].map((k) => k.split("_").map(Number) as [number, number]); + let edge = 0, matched = 0, ms = 0, n = 0, inBiome = 0, cellsN = 0; + for (const [px, py] of regionOrder(hexes, w.layout.orientation, w.layout.parentStagger)) { + const t0 = performance.now(); + const plan = planRegion({ layout: w.layout, parent: [px, py], biomes: w.biomes, profiles, pinned, typeOf, worldSeed: w.ws, seed: w.seed(px, py), ...(w.blend ? { blend: w.blend } : {}), ...(w.warp !== undefined ? { warp: w.warp } : {}) }); + ms += performance.now() - t0; + n++; + const c = seamContinuity(w.layout, [px, py], plan.cells, pinned, typeOf); + edge += c.edge; + matched += c.matched; + const own = profiles.get(w.biomes.get(`${px}_${py}`)!); + for (const t of plan.cells.values()) { + cellsN++; + if (own?.types.has(typeOf(t) ?? "")) inBiome++; + } + for (const [k, t] of plan.cells) pinned.set(k, t); + } + const seams = seamStats(w.layout, pinned, typeOf); + const pairs = seams.reduce((s, x) => s + x.pairs, 0); + return { + continuity: matched / Math.max(1, edge), + seamType: seams.reduce((s, x) => s + x.typeAgreement * x.pairs, 0) / Math.max(1, pairs), + interior: interiorAgreement(w.layout, pinned, typeOf), + inBiome: inBiome / Math.max(1, cellsN), + ms: ms / n, + }; +} + +const pct = (v: number) => `${(v * 100).toFixed(1)}%`; +console.log(`after = ${JSON.stringify(after)} (defaults when empty)`); +console.log("world | land/water continuity before → after | seam type agreement before → after | interior before → after | own-biome types before → after | ms/region before → after"); +for (const w of worlds) { + const b = run(w, { "neighbour-influence": 0 }); + const a = run(w, after); + console.log(`${w.name} | ${pct(b.continuity)} → ${pct(a.continuity)} | ${pct(b.seamType)} → ${pct(a.seamType)} | ${pct(b.interior)} → ${pct(a.interior)} | ${pct(b.inBiome)} → ${pct(a.inBiome)} | ${b.ms.toFixed(2)} → ${a.ms.toFixed(2)}`); +} diff --git a/dev/migration/audit.mts b/dev/migration/audit.mts new file mode 100644 index 00000000..48320b30 --- /dev/null +++ b/dev/migration/audit.mts @@ -0,0 +1,261 @@ +/** + * Migration audit: is a migrated vault 1:1 with the 1.5.x vault it came from? + * + * node node_modules/tsx/dist/cli.mjs --tsconfig ./tsconfig.test.json --import ./tests/register.mjs \ + * dev/migration/audit.mts --seed
 --data 
 (--plugin-dir  | --run ) [--out report.md]
+ *
+ * `--seed` is the vault before migration (a copy, never the live vault),
+ * `--data` its plugin data.json. With `--plugin-dir` (a folder with the built
+ * main.js, manifest.json, styles.css) a hidden sandbox is made from the seed
+ * and data, the plugin starts and migrates it, and nothing else is done in
+ * it. With `--run`, an existing sandbox run whose vault was migrated from
+ * that seed is started again instead.
+ *
+ * Checks, beyond the smoke suite's M-* checks (hex data, bodies, backups):
+ *   paths     every road/river step (pair of hexes) of every legacy chain is a
+ *             step of a routed path of the same type, and no routed step is new
+ *   settings  each map's data.json settings are what the plugin holds now
+ *   tables    a rewritten table rolls the same: same results, weights, die
+ *   files     nothing lost; every other rewritten note shown as a diff
+ * Exit 0 when paths, settings and tables are 1:1 and nothing was lost.
+ */
+import fs from "node:fs";
+import path from "node:path";
+import crypto from "node:crypto";
+import { execFileSync } from "node:child_process";
+const rtMod = await import("../../src/random-tables/randomTable.ts") as Record & { default?: Record };
+const parseRandomTable = (rtMod.parseRandomTable ?? rtMod.default?.parseRandomTable) as typeof import("../../src/random-tables/randomTable.ts").parseRandomTable;
+
+const args = process.argv.slice(2);
+const arg = (k: string): string | undefined => {
+  const i = args.indexOf(`--${k}`);
+  return i >= 0 ? args[i + 1] : undefined;
+};
+const seed = arg("seed"), dataFile = arg("data"), pluginDir = arg("plugin-dir");
+let runDir = arg("run");
+const outFile = arg("out");
+if (!seed || !dataFile || (!runDir && !pluginDir)) {
+  console.error("usage: audit.mts --seed 
 --data 
 (--plugin-dir  | --run ) [--out report.md]");
+  process.exit(2);
+}
+const ob = await import("../smoke/lib/obsidian.mjs");
+const P = await import("../smoke/lib/page.mjs");
+if (!runDir) {
+  // A copy of data.json: the sandbox never sees the given file.
+  const created = await ob.createSandbox({ pluginDir, seed, pluginData: dataFile, name: "migration-audit" });
+  runDir = created.runDir as string;
+  console.log(`sandbox ${runDir}`);
+}
+
+type LegacyMap = { name: string; pathChains?: { typeName?: string; type?: string; hexes?: string[] }[] } & Record;
+type Branch = { path: string; typeName: string; branch: number; hexes: string[] };
+type Probe = { maps: Record; branches: Branch[] | null }>; pluginId: string };
+
+const data = JSON.parse(fs.readFileSync(dataFile, "utf8")) as { maps?: LegacyMap[]; regions?: LegacyMap[]; hexFolder?: string };
+const run = JSON.parse(fs.readFileSync(path.join(runDir!, "run.json"), "utf8")) as { vault: string; pluginId: string };
+const post = run.vault;
+
+// ── what the plugin holds now (sandbox, hidden) ─────────────────────────────
+
+async function probe(): Promise {
+  await ob.launchSandbox(runDir);
+  const conn = await ob.connectPage(runDir);
+  try {
+    // Started: the migration runs; wait until the plugin is ready and the vault quiet.
+    const ready = await conn.page.evaluate(P.waitReady, run.pluginId, 900_000) as { ready: boolean; ms: number };
+    if (!ready.ready) throw new Error("plugin never became ready");
+    await conn.page.evaluate(P.settle, run.pluginId, 5000, 900_000);
+    const errors = ob.pluginErrors(conn.log, run.pluginId);
+    if (errors.length) console.log(`plugin errors: ${errors.map((e: { text: string }) => e.text.slice(0, 200)).join(" | ")}`);
+    // Plain text, not a function: tsx's keepNames helpers don't exist in the page.
+    return await conn.page.evaluate(`(async (id) => {
+      const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
+      const p = window.app.plugins.plugins[id];
+      const t0 = Date.now();
+      while (Date.now() - t0 < 600000 && !(p.settings.maps ?? []).every((m) => p.mapStore.isReady(m.name))) await sleep(500);
+      const out = {};
+      for (const m of p.settings.maps) {
+        if (out[m.name]) continue;
+        const settings = JSON.parse(JSON.stringify({ ...p.getMap(m.name), paths: undefined, pathChains: undefined }));
+        let branches = null;
+        try {
+          branches = (p.mapStore.resolved(m.name) ?? []).map((b) => ({ path: b.path, typeName: b.typeName, branch: b.branch, hexes: [...b.hexes] }));
+        } catch { branches = null; }
+        out[m.name] = { settings, branches };
+      }
+      return { maps: out, pluginId: id };
+    })(${JSON.stringify(run.pluginId)})`) as Probe;
+  } finally {
+    await conn.close();
+    await ob.stopSandbox(runDir);
+  }
+}
+
+// ── comparisons ─────────────────────────────────────────────────────────────
+
+const edge = (a: string, b: string) => (a < b ? `${a}|${b}` : `${b}|${a}`);
+const canon = (v: unknown): string => {
+  const sort = (x: unknown): unknown =>
+    Array.isArray(x) ? x.map(sort) : x && typeof x === "object" ? Object.fromEntries(Object.keys(x).sort().map((k) => [k, sort((x as Record)[k])])) : x;
+  return JSON.stringify(sort(v));
+};
+
+/**
+ * Legacy chains vs routed paths, step by step (an unordered pair of hexes).
+ * One-hex chains are `dots`: 1.5.x never drew a chain under two hexes and
+ * the migration leaves them out (listed in each map's paths report, kept in
+ * its backup), so they're information, not a loss.
+ */
+function comparePaths(legacy: LegacyMap, branches: Branch[] | null): { probs: string[]; dots: string[] } {
+  const probs: string[] = [], dotNotes: string[] = [];
+  if (branches === null) return { probs: ["paths didn't resolve"], dots: [] };
+  const oldEdges = new Map>(), oldDots = new Map>();
+  const newEdges = new Map>(), newHexes = new Map>();
+  const add = (m: Map>, t: string, v: string) => { if (!m.has(t)) m.set(t, new Set()); m.get(t)!.add(v); };
+  for (const c of legacy.pathChains ?? []) {
+    const t = String(c.typeName ?? c.type ?? "?").toLowerCase();
+    const hs = c.hexes ?? [];
+    if (hs.length === 1) add(oldDots, t, hs[0]);
+    for (let i = 1; i < hs.length; i++) if (hs[i] !== hs[i - 1]) add(oldEdges, t, edge(hs[i - 1], hs[i]));
+  }
+  for (const b of branches) {
+    const t = b.typeName.toLowerCase();
+    for (const h of b.hexes) add(newHexes, t, h);
+    for (let i = 1; i < b.hexes.length; i++) if (b.hexes[i] !== b.hexes[i - 1]) add(newEdges, t, edge(b.hexes[i - 1], b.hexes[i]));
+  }
+  for (const t of new Set([...oldEdges.keys(), ...newEdges.keys(), ...oldDots.keys()])) {
+    const o = oldEdges.get(t) ?? new Set(), n = newEdges.get(t) ?? new Set();
+    const missing = [...o].filter((e) => !n.has(e)), extra = [...n].filter((e) => !o.has(e));
+    // A one-hex legacy chain is a single hex: kept if that hex is on a path of its type.
+    const dots = [...(oldDots.get(t) ?? [])].filter((h) => !(newHexes.get(t)?.has(h)) && ![...o].some((e) => e.split("|").includes(h)));
+    if (missing.length) probs.push(`${t}: ${missing.length} steps lost (${missing.slice(0, 6).join(", ")})`);
+    if (extra.length) probs.push(`${t}: ${extra.length} steps added (${extra.slice(0, 6).join(", ")})`);
+    if (dots.length) dotNotes.push(`${t} ${dots.length}`);
+  }
+  return { probs, dots: dotNotes };
+}
+
+/** Map keys kept in the map note (or the plugin) under the same name and meaning. */
+const SKIP_SETTING = new Set(["pathChains", "paths", "savedViewport"]);
+function compareSettings(legacy: LegacyMap, now: Record): string[] {
+  const probs: string[] = [];
+  for (const [k, v] of Object.entries(legacy)) {
+    if (SKIP_SETTING.has(k)) continue;
+    if (!(k in now)) { probs.push(`${k} gone (was ${JSON.stringify(v)})`); continue; }
+    if (canon(v) !== canon(now[k])) probs.push(`${k}: ${JSON.stringify(v)} → ${JSON.stringify(now[k])}`);
+  }
+  return probs;
+}
+
+const sha = (f: string) => crypto.createHash("sha1").update(fs.readFileSync(f)).digest("hex");
+function walk(root: string, rel = "", out: string[] = []): string[] {
+  for (const e of fs.readdirSync(path.join(root, rel), { withFileTypes: true })) {
+    const r = rel ? `${rel}/${e.name}` : e.name;
+    if (e.name === ".obsidian" || e.name === ".git" || e.name === ".trash") continue;
+    if (e.isDirectory()) walk(root, r, out); else out.push(r);
+  }
+  return out;
+}
+
+function isTable(text: string): boolean {
+  return /^---[\s\S]*?\ndice:/m.test(text) || /\|\s*(Result|Weight)\s*\|/i.test(text);
+}
+function compareTable(before: string, after: string): string | null {
+  const a = parseRandomTable(before), b = parseRandomTable(after);
+  const rows = (t: typeof a) => t.entries.map((e) => `${e.result}\u0000${e.weight}`);
+  if (canon(rows(a)) !== canon(rows(b))) return `entries differ: ${a.entries.length} → ${b.entries.length}`;
+  if (a.dice !== b.dice) return `die d${a.dice} → d${b.dice}`;
+  return null;
+}
+
+// ── run ─────────────────────────────────────────────────────────────────────
+
+const report: string[] = [];
+let failed = false;
+const section = (title: string, lines: string[], ok: boolean) => {
+  report.push(`## ${ok ? "OK" : "PROBLEM"}: ${title}`, "", ...(lines.length ? lines : ["(nothing)"]), "");
+  if (!ok) failed = true;
+};
+
+// Twice: as migrated, then after a restart (read back from the map notes).
+const first = await probe();
+const state = await probe();
+{
+  const lines: string[] = [];
+  for (const name of Object.keys(first.maps)) {
+    const a = first.maps[name], b = state.maps[name];
+    if (!b) { lines.push(`- ${name}: gone after the restart`); continue; }
+    if (canon(a.settings) !== canon(b.settings)) lines.push(`- ${name}: settings differ after the restart`);
+    if (canon(a.branches) !== canon(b.branches)) lines.push(`- ${name}: paths differ after the restart`);
+  }
+  section("restart reads back the same maps", lines.length ? lines : [`- ${Object.keys(first.maps).length} maps identical after a restart`], lines.length === 0);
+}
+const legacyMaps: LegacyMap[] = [];
+const seen = new Set();
+for (const m of data.maps ?? data.regions ?? []) if (!seen.has(m.name)) { seen.add(m.name); legacyMaps.push(m); }
+
+{
+  const lines: string[] = [];
+  let ok = true, steps = 0;
+  for (const m of legacyMaps) {
+    const s = state.maps[m.name];
+    if (!s) { lines.push(`- ${m.name}: map missing after migration`); ok = false; continue; }
+    const { probs, dots } = comparePaths(m, s.branches);
+    const chains = (m.pathChains ?? []).length;
+    const dotNote = dots.length ? `; one-hex pieces left out (never drawn by 1.5.x): ${dots.join(", ")}` : "";
+    steps += (m.pathChains ?? []).reduce((n, c) => n + Math.max(0, (c.hexes ?? []).length - 1), 0);
+    if (probs.length) { ok = false; lines.push(`- ${m.name}: ${probs.join("; ")}${dotNote}`); }
+    else if (chains) lines.push(`- ${m.name}: ${chains} legacy chains → ${new Set((s.branches ?? []).map((b) => b.path)).size} paths, every drawn step kept, none added${dotNote}`);
+  }
+  section(`paths (${steps} legacy steps)`, lines, ok);
+}
+{
+  const lines: string[] = [];
+  let ok = true;
+  for (const m of legacyMaps) {
+    const s = state.maps[m.name];
+    if (!s) continue;
+    const probs = compareSettings(m, s.settings);
+    if (probs.length) { ok = false; lines.push(`- ${m.name}: ${probs.join("; ")}`); }
+  }
+  if (ok) lines.push(`- ${legacyMaps.length} maps: every data.json setting the same (paths and saved viewport checked separately/ignored)`);
+  section("map settings", lines, ok);
+}
+
+const before = walk(seed), after = new Set(walk(post));
+const lost = before.filter((f) => !after.has(f));
+section("files", lost.length ? lost.slice(0, 50).map((f) => `- lost: ${f}`) : [`- ${before.length} files, none lost; ${after.size - before.length + lost.length} new`], lost.length === 0);
+
+const changed = before.filter((f) => after.has(f) && sha(path.join(seed, f)) !== sha(path.join(post, f)));
+const hexFolder = (data.hexFolder ?? "").replace(/^\/+|\/+$/g, "");
+const isHexNote = (f: string) => f.startsWith(hexFolder + "/") && /\/-?\d+_-?\d+\.md$/.test(f);
+{
+  const lines: string[] = [];
+  let ok = true, n = 0;
+  for (const f of changed.filter((f) => !isHexNote(f))) {
+    const a = fs.readFileSync(path.join(seed, f), "utf8"), b = fs.readFileSync(path.join(post, f), "utf8");
+    if (!isTable(a)) continue;
+    n++;
+    const p = compareTable(a, b);
+    if (p) { ok = false; lines.push(`- ${f}: ${p}`); }
+  }
+  if (ok) lines.push(`- ${n} rewritten tables roll exactly as before`);
+  section("tables", lines, ok);
+}
+{
+  const others = changed.filter((f) => !isHexNote(f) && !isTable(fs.readFileSync(path.join(seed, f), "utf8")));
+  const lines = [`${others.length} other notes rewritten (hex notes are checked by the smoke suite's M-data). Diffs:`, ""];
+  for (const f of others) {
+    let d = "";
+    try { execFileSync("diff", ["-u", path.join(seed, f), path.join(post, f)], { encoding: "utf8" }); }
+    catch (e) { d = String((e as { stdout?: string }).stdout ?? ""); }
+    lines.push("```diff", `# ${f}`, d.split("\n").slice(2).join("\n").trimEnd(), "```", "");
+  }
+  section("other rewritten notes (for review)", lines, true);
+}
+
+const text = [`# Migration audit`, "", `seed ${seed}`, `data ${dataFile}`, `migrated ${post}`, "", ...report].join("\n");
+if (outFile) fs.writeFileSync(outFile, text);
+console.log(report.filter((l) => l.startsWith("## ")).join("\n"));
+console.log(failed ? "AUDIT: PROBLEMS FOUND" : "AUDIT: 1:1");
+process.exit(failed ? 1 : 0);
diff --git a/dev/overworld-preview.html b/dev/overworld-preview.html
new file mode 100644
index 00000000..8d783933
--- /dev/null
+++ b/dev/overworld-preview.html
@@ -0,0 +1,47 @@
+
+
+loading
+
+

Overworld preview (dev only): World biomes + regions, brick vs hex flower

+

A 19-hex overworld from the World biomes generator (left; white outline = transition biome, blue = river). Every region is generated from the blend field in spiral order, each pinning the cells of the regions made before it. Seam lines are coloured by how often facing hexes share a terrain type (red low, green high).

+
+ + + + + + +
+
+ + + + + +
+
+
Overworld
+
+
+
+
+ diff --git a/dev/overworld-preview.ts b/dev/overworld-preview.ts new file mode 100644 index 00000000..82e1f190 --- /dev/null +++ b/dev/overworld-preview.ts @@ -0,0 +1,312 @@ +/** + * Overworld preview (plan-overworld-regions §6.1, phase 0 checkpoint). + * Generates a 19-hex overworld with World biomes, then every region with + * the real blend field + region generator, and draws the stitched world for + * brick 8×8 and hex-flower r=4 regions, with per-seam continuity scores. + * + * Build: npx esbuild dev/overworld-preview.ts --bundle --format=iife --loader:.md=text --outfile=dev/overworld-preview.js + * Serve: npm run sandbox → /dev/overworld-preview.html + * Hooks: window.__runWorld(opts) → stats, window.__seamStats() → per-seam rows. + */ +import { hexCenter, hexDistance, type Orientation } from "../packages/hex-wfc/src/grid"; +import { mulberry32 } from "../packages/hex-wfc/src/rng"; +import { DEFAULT_TERRAIN_PALETTE } from "../src/constants"; +import { inferTerrainType } from "../src/terrainTypes"; +import { BUILTIN_GENERATORS, builtinModel } from "../src/worldgen/builtinGenerators"; +import { BIOMES, biomeInfo, biomeProfiles } from "../src/overworld/biomes"; +import { BlendField, REGION_WARP } from "../src/overworld/blendField"; +import { childNeighbours, parentOf, regionCellCount, type RegionLayout } from "../src/overworld/layout"; +import { generateRegion, interiorAgreement, seamStats, spiralOrder, type SeamStat } from "../src/overworld/regionGen"; +import { worldBiomes, type Climate } from "../src/overworld/worldBiomes"; + +const PALETTE = DEFAULT_TERRAIN_PALETTE; +const COLOR = new Map(PALETTE.map((t) => [t.name, t.color])); +const TYPE = new Map(PALETTE.map((t) => [t.name, t.type ?? inferTerrainType(t.name, t.category, "world")])); +const typeOf = (t: string) => TYPE.get(t); +const MODELS = new Map(BUILTIN_GENERATORS.map((g) => [g.slug, builtinModel(g.slug)])); +const PROFILES = biomeProfiles(MODELS, PALETTE); + +interface Opts { + seed: number; + k: number; + warp: number; + climate: Climate; + water: number; + view: "both" | "rect" | "hex"; + overworldOnly: boolean; + order: "spiral" | "shuffled"; + heat: string; + orientation: Orientation; +} +const opts: Opts = { seed: 7, k: 3.5, warp: REGION_WARP, climate: "varied", water: 0.25, view: "both", overworldOnly: false, order: "spiral", heat: "", orientation: "flat" }; + +interface Footprint { label: string; layout: RegionLayout; cells: Map; field: BlendField; seams: SeamStat[]; interior: number; ms: number } +let last: { parents: [number, number][]; world: ReturnType; prints: Footprint[] } | null = null; + +const OW_R = 2; // 19 overworld hexes +const CENTRE: [number, number] = [OW_R, OW_R]; + +function overworldCells(o: Orientation): [number, number][] { + const out: [number, number][] = []; + for (let x = 0; x <= 2 * OW_R; x++) for (let y = 0; y <= 2 * OW_R; y++) if (hexDistance([x, y], CENTRE, o, "odd") <= OW_R) out.push([x, y]); + return out; +} + +function run(o: Partial = {}) { + Object.assign(opts, o); + const parents = overworldCells(opts.orientation); + const world = worldBiomes(parents, opts.orientation, "odd", PALETTE, { seed: opts.seed, climate: opts.climate, water: opts.water }); + const layouts: [string, RegionLayout][] = [ + ["Brick 8×8", { footprint: "rect", size: 8, orientation: opts.orientation, parentStagger: "odd", childStagger: "odd" }], + ["Hex flower r=4", { footprint: "hex", size: 4, orientation: opts.orientation, parentStagger: "odd", childStagger: "odd" }], + ]; + const prints: Footprint[] = layouts.map(([label, layout]) => { + const t0 = performance.now(); + const field = new BlendField(layout, world.biomes, opts.k, { warp: opts.warp, seed: opts.seed }); + let order = spiralOrder(parents, CENTRE, (a, b) => hexDistance(a, b, opts.orientation, "odd")); + if (opts.order === "shuffled") { + const rng = mulberry32(opts.seed ^ 0xabc); + order = order.map((p) => [rng(), p] as [number, [number, number]]).sort((a, b) => a[0] - b[0]).map(([, p]) => p); + } + const cells = new Map(); + for (const p of order) { + for (const [k, v] of generateRegion({ layout, parent: p, field, profiles: PROFILES, pinned: cells, typeOf, seed: opts.seed })) cells.set(k, v); + } + return { label, layout, cells, field, seams: seamStats(layout, cells, typeOf), interior: interiorAgreement(layout, cells, typeOf), ms: performance.now() - t0 }; + }); + last = { parents, world, prints }; + draw(); + return stats(); +} + +function stats() { + if (!last) return null; + return { + seed: opts.seed, + k: opts.k, + warp: opts.warp, + overworld: Object.fromEntries([...last.world.biomes]), + footprints: last.prints.map((p) => ({ + label: p.label, + cellsPerRegion: regionCellCount(p.layout), + totalCells: p.cells.size, + ms: Math.round(p.ms), + seamTypeAgreement: weighted(p.seams, "typeAgreement"), + seamNameAgreement: weighted(p.seams, "nameAgreement"), + interiorTypeAgreement: p.interior, + worstSeam: [...p.seams].sort((a, b) => a.typeAgreement - b.typeAgreement)[0], + })), + }; +} +const weighted = (s: SeamStat[], f: "typeAgreement" | "nameAgreement") => s.reduce((a, x) => a + x[f] * x.pairs, 0) / Math.max(1, s.reduce((a, x) => a + x.pairs, 0)); + +// ── drawing ────────────────────────────────────────────────────────────── + +const $ = (id: string) => document.getElementById(id) as T; + +function hexPath(ctx: CanvasRenderingContext2D, cx: number, cy: number, s: number, o: Orientation) { + ctx.beginPath(); + for (let i = 0; i < 6; i++) { + const a = (Math.PI / 3) * i + (o === "pointy" ? Math.PI / 6 : 0); + const x = cx + s * Math.cos(a), y = cy + s * Math.sin(a); + if (i) ctx.lineTo(x, y); else ctx.moveTo(x, y); + } + ctx.closePath(); +} + +/** Red (0) → amber → green (1). */ +const scoreColour = (v: number) => `hsl(${Math.round(Math.max(0, Math.min(1, (v - 0.4) / 0.6)) * 120)}, 85%, 55%)`; + +function drawOverworld() { + const cv = $("ow"); + const ctx = cv.getContext("2d")!; + ctx.clearRect(0, 0, cv.width, cv.height); + if (!last) return; + const pts = last.parents.map(([x, y]) => hexCenter(x, y, opts.orientation, "odd")); + const minX = Math.min(...pts.map((p) => p[0])), minY = Math.min(...pts.map((p) => p[1])); + const s = 20; + last.parents.forEach(([x, y], i) => { + const k = `${x}_${y}`; + const cx = (pts[i][0] - minX) * s + 30, cy = (pts[i][1] - minY) * s + 30; + hexPath(ctx, cx, cy, s, opts.orientation); + ctx.fillStyle = COLOR.get(last!.world.terrain.get(k) ?? "") ?? "#333"; + ctx.fill(); + ctx.strokeStyle = last!.world.ecotones.has(k) ? "#fff" : "#111"; + ctx.lineWidth = last!.world.ecotones.has(k) ? 2.5 : 1; + ctx.stroke(); + ctx.fillStyle = "#000"; + ctx.font = "9px system-ui"; + ctx.textAlign = "center"; + ctx.fillText((biomeInfo(last!.world.biomes.get(k)!)?.label ?? "").slice(0, 10), cx, cy + 3); + }); + // river + if (last.world.river.length > 1) { + ctx.beginPath(); + last.world.river.forEach((k, i) => { + const [x, y] = k.split("_").map(Number); + const [px, py] = hexCenter(x, y, opts.orientation, "odd"); + const X = (px - minX) * s + 30, Y = (py - minY) * s + 30; + if (i) ctx.lineTo(X, Y); else ctx.moveTo(X, Y); + }); + ctx.strokeStyle = "#3b82f6"; + ctx.lineWidth = 3; + ctx.stroke(); + } +} + +function drawFootprint(fp: Footprint, cv: HTMLCanvasElement) { + const ctx = cv.getContext("2d")!; + const l = fp.layout; + const keys = [...fp.cells.keys()]; + const pts = keys.map((k) => { const [x, y] = k.split("_").map(Number); return hexCenter(x, y, l.orientation, l.childStagger); }); + const minX = Math.min(...pts.map((p) => p[0])), maxX = Math.max(...pts.map((p) => p[0])); + const minY = Math.min(...pts.map((p) => p[1])), maxY = Math.max(...pts.map((p) => p[1])); + const W = cv.width - 20, H = cv.height - 20; + const scale = Math.min(W / (maxX - minX + 2), H / (maxY - minY + 2)); + const X = (v: number) => (v - minX + 1) * scale + 10, Y = (v: number) => (v - minY + 1) * scale + 10; + ctx.clearRect(0, 0, cv.width, cv.height); + const owner = new Map(); + keys.forEach((k, i) => { + const [x, y] = k.split("_").map(Number); + const p = parentOf(l, x, y).join("_"); + owner.set(k, p); + const t = opts.overworldOnly ? last!.world.terrain.get(p) ?? "" : fp.cells.get(k)!; + hexPath(ctx, X(pts[i][0]), Y(pts[i][1]), scale * 1.02, l.orientation); + ctx.fillStyle = COLOR.get(t) ?? "#333"; + ctx.fill(); + if (opts.heat) { + const v = fp.field.at(x, y).get(opts.heat) ?? 0; + ctx.fillStyle = `rgba(255, 0, 200, ${(v * 0.75).toFixed(3)})`; + ctx.fill(); + } + }); + // Seams, coloured by that seam's type agreement. + const score = new Map(fp.seams.map((s) => [`${s.a}|${s.b}`, s.typeAgreement])); + ctx.lineWidth = Math.max(1.5, scale * 0.28); + keys.forEach((k, i) => { + const [x, y] = k.split("_").map(Number); + const me = owner.get(k)!; + for (const [a, b] of childNeighbours(l, x, y)) { + const nk = `${a}_${b}`; + const other = owner.get(nk); + if (!other || other === me || nk < k) continue; + const [qx, qy] = hexCenter(a, b, l.orientation, l.childStagger); + const mx = (pts[i][0] + qx) / 2, my = (pts[i][1] + qy) / 2; + const dx = qx - pts[i][0], dy = qy - pts[i][1]; + const len = Math.hypot(dx, dy); + const ux = -dy / len / 2, uy = dx / len / 2; // half an edge (edge = 1 unit) + const id = me < other ? `${me}|${other}` : `${other}|${me}`; + ctx.strokeStyle = scoreColour(score.get(id) ?? 1); + ctx.beginPath(); + ctx.moveTo(X(mx - ux), Y(my - uy)); + ctx.lineTo(X(mx + ux), Y(my + uy)); + ctx.stroke(); + } + }); +} + +function draw() { + if (!last) return; + drawOverworld(); + const wall = $("wall"); + wall.replaceChildren(); + for (const fp of last.prints) { + if (opts.view === "rect" && fp.layout.footprint !== "rect") continue; + if (opts.view === "hex" && fp.layout.footprint !== "hex") continue; + const fig = document.createElement("figure"); + const cv = document.createElement("canvas"); + cv.width = opts.view === "both" ? 620 : 1000; + cv.height = opts.view === "both" ? 620 : 900; + fig.appendChild(cv); + const cap = document.createElement("figcaption"); + cap.textContent = `${fp.label} · ${regionCellCount(fp.layout)} hexes per region · ${fp.cells.size} total · ${Math.round(fp.ms)} ms · seam type agreement ${(weighted(fp.seams, "typeAgreement") * 100).toFixed(0)}% (name ${(weighted(fp.seams, "nameAgreement") * 100).toFixed(0)}%) vs interior ${(fp.interior * 100).toFixed(0)}%`; + fig.appendChild(cap); + wall.appendChild(fig); + drawFootprint(fp, cv); + } + drawSeamTable(); + drawLegend(); + document.title = "ready"; +} + +function drawSeamTable() { + const box = $("seams"); + box.replaceChildren(); + if (!last) return; + for (const fp of last.prints) { + const t = document.createElement("table"); + const cap = t.createCaption(); + cap.textContent = `${fp.label}: per-seam continuity (worst first)`; + const head = t.insertRow(); + for (const h of ["Seam", "Biomes", "Pairs", "Type", "Name"]) { const th = document.createElement("th"); th.textContent = h; head.appendChild(th); } + for (const s of [...fp.seams].sort((a, b) => a.typeAgreement - b.typeAgreement)) { + const r = t.insertRow(); + const label = (k: string) => biomeInfo(last!.world.biomes.get(k) ?? "")?.label ?? k; + for (const v of [`${s.a} | ${s.b}`, `${label(s.a)} / ${label(s.b)}`, String(s.pairs), `${(s.typeAgreement * 100).toFixed(0)}%`, `${(s.nameAgreement * 100).toFixed(0)}%`]) r.insertCell().textContent = v; + (r.cells[3] as HTMLElement).style.color = scoreColour(s.typeAgreement); + } + box.appendChild(t); + } +} + +function drawLegend() { + const box = $("legend"); + box.replaceChildren(); + if (!last) return; + const used = new Set(); + for (const fp of last.prints) for (const t of fp.cells.values()) used.add(t); + for (const t of PALETTE) { + if (!used.has(t.name)) continue; + const s = document.createElement("span"); + const i = document.createElement("i"); + i.style.background = t.color; + s.append(i, t.name); + box.appendChild(s); + } +} + +// ── controls ───────────────────────────────────────────────────────────── + +function wire() { + const seed = $("seed"); + const k = $("k"); + const kv = $("kv"); + const warp = $("warp"); + const wv = $("wv"); + const heat = $("heat"); + for (const b of BIOMES) { const o = document.createElement("option"); o.value = b.id; o.textContent = b.label; heat.appendChild(o); } + const sync = () => { + seed.value = String(opts.seed); + k.value = String(opts.k); + warp.value = String(opts.warp); + wv.textContent = opts.warp.toFixed(2); + kv.textContent = `k = ${opts.k.toFixed(2)} ${opts.k >= 5.5 ? "(narrow)" : opts.k <= 2.25 ? "(wide)" : Math.abs(opts.k - 3.5) < 0.3 ? "(normal)" : ""}`; + }; + const go = (o: Partial) => { document.title = "drawing"; run(o); sync(); }; + seed.addEventListener("change", () => go({ seed: Number(seed.value) >>> 0 })); + $("reroll").addEventListener("click", () => go({ seed: Math.floor(Math.random() * 1e6) })); + k.addEventListener("input", () => { opts.k = Number(k.value); sync(); }); + k.addEventListener("change", () => go({ k: Number(k.value) })); + warp.addEventListener("input", () => { wv.textContent = Number(warp.value).toFixed(2); }); + warp.addEventListener("change", () => go({ warp: Number(warp.value) })); + $("climate").addEventListener("change", (e) => go({ climate: (e.target as HTMLSelectElement).value as Climate })); + $("water").addEventListener("change", (e) => go({ water: Number((e.target as HTMLInputElement).value) / 100 })); + $("view").addEventListener("change", (e) => { opts.view = (e.target as HTMLSelectElement).value as Opts["view"]; draw(); }); + $("order").addEventListener("change", (e) => go({ order: (e.target as HTMLSelectElement).value as Opts["order"] })); + $("orient").addEventListener("change", (e) => go({ orientation: (e.target as HTMLSelectElement).value as Orientation })); + $("owonly").addEventListener("change", (e) => { opts.overworldOnly = (e.target as HTMLInputElement).checked; draw(); }); + heat.addEventListener("change", () => { opts.heat = heat.value; draw(); }); + sync(); +} + +declare global { + interface Window { + __runWorld: (o?: Partial) => ReturnType; + __seamStats: () => { label: string; seams: SeamStat[] }[]; + } +} +window.__runWorld = (o) => run(o); +window.__seamStats = () => (last ? last.prints.map((p) => ({ label: p.label, seams: p.seams })) : []); + +wire(); +run(); diff --git a/dev/region-notes.html b/dev/region-notes.html new file mode 100644 index 00000000..96e69ddb --- /dev/null +++ b/dev/region-notes.html @@ -0,0 +1,167 @@ + + +loading + +

Region notes — design choices

+

Your idea: one note per map holds the per-hex data; hex notes only appear when a hex gets real content. Pick one option per card, add notes, then Submit (Claude is watching for it).

+
+ Where things stand in your vault: +
    +
  • 9,438 hex notes across 14 maps (chult 2,130 · aaaabab 1,374 · the-coast 960 …). In the-coast, only 686 of 960 differ from the template.
  • +
  • Per-hex data today lives in each hex note's frontmatter (terrain, icon, GM icons, region, submap) and 12 source files read it from there.
  • +
  • Map-level data (size, palette, paths, overlays, viewport…) lives in the plugin's data.json, not in notes.
  • +
+ Sketch of a region note (format is question 4): +
---
+hexmaker-map: 1
+palette: Default
+size: 38x25
+base-terrain: ocean
+---
+# the-coast
+
+| Hex  | Terrain | Icon | Region | Submap |
+| ---- | ------- | ---- | ------ | ------ |
+| 3_4  | dunes   |      | Basin  |        |
+| 12_9 | forest  | bw-castle.png | Fellwood | the-coast-12-9 |
+
+
+
+ diff --git a/dev/release/check-release.mjs b/dev/release/check-release.mjs new file mode 100644 index 00000000..0f3d78d1 --- /dev/null +++ b/dev/release/check-release.mjs @@ -0,0 +1,181 @@ +#!/usr/bin/env node +/** + * npm run check:release — proves a slice built off leaves no trace in + * main.js (plan-release-slicing §5.5, plan-code-modules P6). + * + * The builds checked (each slice's "off" set includes the slices that + * require it, dev/release/slices.mjs offClosure): + * - by default: every slice on but one (each in turn), the release set + * (HEXMAKER_SLICES=released) and foundation alone (none); + * - `--off space` / `--off space,worldmaps`: every slice on but those; + * - `--slices `, or HEXMAKER_SLICES / _ON / _OFF in the environment: + * that one build (the same switch as esbuild.config.mjs). + * For each: + * 1. build main.js into a temp folder (esbuild.config.mjs production); + * 2. for each module of a slice built off, look for what it owns + * (src/modules//index.ts): its command ids, its settings keys (as + * keys, not inside a placement id like "Settings.x" or "Token.x"), its map-note + * keys, its own strings, its placement ids and its work-mode ids. + * Any hit fails, naming the slice and the text; + * 3. the bundled help has no slice markers left; + * 4. the release README the build wrote (dist/README.md beside main.js, + * README.md with the off slices' marked blocks removed) has no marker + * left, none of the off modules' own strings, and none of the text of + * the off slices' blocks in README.md. + * A full build is checked too: it must contain every owned name, so the + * deny-list can't pass by accident (a renamed string would), and its + * README every slice's block text. + * + * Exit 0 when every build passes. Run from the repo root (uses node_modules). + */ + +import { execFileSync } from "node:child_process"; +import { mkdtempSync, readFileSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { dirname, join } from "node:path"; +import { fileURLToPath } from "node:url"; +import { flaggedSlices, offClosure, readSlices, releaseReadmePath, resolveSlices, sliceBlockText, sliceSpecArg } from "./slices.mjs"; + +const ROOT = join(dirname(fileURLToPath(import.meta.url)), "..", ".."); +const args = process.argv.slice(2); +const offArg = args.includes("--off") ? args[args.indexOf("--off") + 1] : undefined; + +const slices = readSlices(); +const flagged = flaggedSlices(slices); + +/** The switch's env vars cleared: each build here sets exactly what it checks. */ +const NO_SWITCH = { HEXMAKER_SLICES: "", HEXMAKER_SLICES_ON: "", HEXMAKER_SLICES_OFF: "" }; + +/** + * What each module owns, read from the source (every slice on). tsx runs + * through node (node_modules/.bin shims don't work where node_modules is + * a symlink, or on Windows without the .cmd). + */ +function readOwns() { + const tsx = join(ROOT, "node_modules", "tsx", "dist", "cli.mjs"); + const out = execFileSync(process.execPath, [tsx, "--tsconfig", "./tsconfig.test.json", "--import", "./tests/register.mjs", "dev/release/owns.ts"], { + cwd: ROOT, + encoding: "utf8", + env: { ...process.env, ...NO_SWITCH, HEXMAKER_SLICES: "all" }, + }); + return JSON.parse(out); +} + +/** Build main.js (and the release README beside it) into `dir` with slice spec `spec`; returns both. */ +function build(spec, dir) { + const outfile = join(dir, "main.js"); + execFileSync(process.execPath, ["esbuild.config.mjs", "production"], { + cwd: ROOT, + env: { ...process.env, ...NO_SWITCH, HEXMAKER_SLICES: spec, HEXMAKER_OUTFILE: outfile }, + stdio: ["ignore", "inherit", "inherit"], + }); + return { js: readFileSync(outfile, "utf8"), readme: readFileSync(releaseReadmePath(outfile), "utf8") }; +} + +/** README.md as written, with its slice markers. */ +const README = readFileSync(join(ROOT, "README.md"), "utf8"); +/** Each flagged slice's README block text (lines only its blocks hold). */ +const readmeText = (id) => sliceBlockText(README, id); + +const escape = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + +/** A string as written, or as esbuild writes it in main.js (non-ASCII as a \u escape). */ +const inBundle = (s) => { + const js = s.replace(/[^\x00-\x7f]/g, (c) => `\\u${c.charCodeAt(0).toString(16).padStart(4, "0")}`); + return js === s ? escape(s) : `${escape(s)}|${escape(js)}`; +}; + +/** Every place a module's owned text would show in a bundle. */ +function needles(mod) { + const o = mod.owns; + return [ + ...o.commands.map((c) => ({ what: `command ${c}`, re: new RegExp(`["'\`]${escape(c)}["'\`]`) })), + // A settings key read or written (settings.x / "x"), not a placement id ("Settings.x", "Token.x"). + ...o.settingsKeys.map((k) => ({ what: `settings key ${k}`, re: new RegExp(`(? ({ what: `map-note key ${k}`, re: new RegExp(`["'\`]${escape(k)}["'\`]`) })), + ...(o.strings ?? []).map((s) => ({ what: `string "${s}"`, re: new RegExp(inBundle(s)) })), + // Its own rows of the placement map and the work-mode tables (merged in only when it's built). + ...(mod.placementIds ?? []).map((id) => ({ what: `placement id ${id}`, re: new RegExp(`["'\`]${escape(id)}["'\`]`) })), + ...[...new Set(mod.modeActionIds ?? [])].filter((id) => !o.commands.includes(id)).map((id) => ({ what: `work-mode id ${id}`, re: new RegExp(`["'\`]${escape(id)}["'\`]`) })), + ]; +} + +const mods = readOwns(); +const ofSlice = (id) => mods.filter((m) => m.slice === id); +for (const m of mods) { + if (!slices[m.slice]) throw new Error(`module ${m.id}: slice "${m.slice}" isn't in release-slices.json`); + if (!slices[m.slice].modules.includes(m.id)) throw new Error(`release-slices.json: slice "${m.slice}" doesn't list module ${m.id}`); +} + +/** The builds to check: a label and the slice spec (the same grammar as HEXMAKER_SLICES). */ +const allBut = (ids) => { + const off = offClosure(ids, slices); + return { label: `every slice but ${off.join(" + ")}`, spec: ["all", ...off.map((id) => `-${id}`)].join(",") }; +}; +const asked = sliceSpecArg(args) ?? (["HEXMAKER_SLICES", "HEXMAKER_SLICES_ON", "HEXMAKER_SLICES_OFF"].some((k) => process.env[k]) ? "env" : undefined); +let runs; +if (offArg) runs = [allBut(offArg.split(",").filter(Boolean))]; +else if (asked) { + // The build the switch asks for, written out as one spec. + const r = asked === "env" ? resolveSlices({ spec: process.env.HEXMAKER_SLICES, on: process.env.HEXMAKER_SLICES_ON, off: process.env.HEXMAKER_SLICES_OFF }) : resolveSlices({ spec: asked }); + runs = [{ label: `the ${r.channel} build`, spec: r.slices.length ? r.slices.join(",") : "none" }]; +} else { + runs = [ + ...flagged.map((id) => allBut([id])), + { label: "the release build", spec: "released" }, + ...(flagged.length > 1 ? [{ label: "foundation alone", spec: "none" }] : []), + ]; +} +const tmp = mkdtempSync(join(tmpdir(), "hexmaker-release-")); +let failed = 0; +const report = (ok, line) => { + if (!ok) failed++; + console.log(`${ok ? "PASS" : "FAIL"} ${line}`); +}; + +try { + // The full build has every owned string (else the deny-list proves nothing). + const { js: full, readme: fullReadme } = build("all", tmp); + for (const id of flagged) { + for (const m of ofSlice(id)) { + const missing = needles(m).filter((n) => !n.re.test(full)).map((n) => n.what); + report(missing.length === 0, `full build holds ${m.id}'s ${needles(m).length} owned names${missing.length ? `; missing: ${missing.join(", ")}` : ""}`); + } + // README: the slice has marked text, and the full build's README keeps it (markers dropped). + const text = readmeText(id); + const lost = text.filter((t) => !fullReadme.includes(t)); + report(text.length > 0 && lost.length === 0 && !/…` (inline or over lines; HTML + * comments, so they don't show when the Markdown is rendered). + */ +export function stripSliceMarkers(text, off) { + return text.replace(/([\s\S]*?)/g, (_m, id, body) => (off.has(id) ? "" : body)); +} + +/** + * The README a build ships (release candidate artifact): README.md with + * the blocks of slices built off removed and the markers dropped, and the + * blank lines a removed paragraph leaves folded to one. + */ +export function releaseReadme(text, off) { + return stripSliceMarkers(text, off).replace(/(\r?\n)(?:[ \t]*\r?\n){2,}/g, "$1$1"); +} + +/** Where a build writes its release README: README.md in a `dist` folder beside main.js. */ +export function releaseReadmePath(outFile) { + return join(dirname(outFile), "dist", "README.md"); +} + +/** + * The text of slice `id`'s blocks in `text` (README.md): each non-blank + * line of each block, trimmed, of at least `min` characters, leaving out + * any that also shows outside the slice's blocks (shared wording). A + * release README with the slice off must contain none of them. + */ +export function sliceBlockText(text, id, min = 16) { + const without = stripSliceMarkers(text, new Set([id])); + const out = new Set(); + for (const m of text.matchAll(/([\s\S]*?)/g)) { + if (m[1] !== id) continue; + for (const raw of m[2].split(/\r?\n/)) { + const line = raw.trim(); + if (line.length >= min && !without.includes(line)) out.add(line); + } + } + return [...out]; +} diff --git a/dev/release/test-slices.mjs b/dev/release/test-slices.mjs new file mode 100644 index 00000000..31a7f028 --- /dev/null +++ b/dev/release/test-slices.mjs @@ -0,0 +1,89 @@ +#!/usr/bin/env node +/** + * npm run test:slices — the contract suite under each feature-switch set + * (plan "every major feature a slice", S0.2). The full suite runs once with + * every slice on (npm test); this runs the tests that say what each slice + * adds and what the core looks like without it: + * + * - each flagged slice off on its own (with the slices that require it); + * - HEXMAKER_SLICES=released (the release build's set); + * - HEXMAKER_SLICES=none (foundation only). + * + * Options: + * --only [,…] run only these sets ("off:space", "released", "none") + * --check-release after each set's tests, npm run check:release for the + * same set (CI's slices matrix: one set per job) + * --list print the sets and the contract files, then exit + * + * The contract suite (CONTRACT below): module*, releaseSlices, readmeCommands, + * workModeCoverage, placement*, the settings tab tests, and each slice's own + * tests/slice-.test.ts. Exit 0 when every set passes. + */ + +import { spawnSync } from "node:child_process"; +import { readdirSync } from "node:fs"; +import { dirname, join } from "node:path"; +import { fileURLToPath } from "node:url"; +import { flaggedSlices, offClosure } from "./slices.mjs"; + +const ROOT = join(dirname(fileURLToPath(import.meta.url)), "..", ".."); + +/** The contract suite: tests that must hold with any set of slices built. */ +export const CONTRACT = [ + /^module.*\.test\.ts$/, + /^releaseSlices\.test\.ts$/, + /^readmeCommands\.test\.ts$/, + /^workModeCoverage\.test\.ts$/, + /^placement.*\.test\.ts$/, + /^disclosure\.test\.ts$/, + /^uiControls\.test\.ts$/, + /^slice-.*\.test\.ts$/, +]; + +export function contractFiles() { + return readdirSync(join(ROOT, "tests")).filter((f) => CONTRACT.some((re) => re.test(f))).sort(); +} + +/** Each set the suite runs under: a name and the env it sets. */ +export function sliceRuns() { + return [ + ...flaggedSlices().map((id) => ({ name: `off:${id}`, env: { HEXMAKER_SLICES: "all", HEXMAKER_SLICES_OFF: offClosure([id]).join(",") }, check: ["--off", id] })), + { name: "released", env: { HEXMAKER_SLICES: "released" }, check: ["--slices", "released"] }, + { name: "none", env: { HEXMAKER_SLICES: "none" }, check: ["--slices", "none"] }, + ]; +} + +if (import.meta.url === `file://${process.argv[1]}` || process.argv[1]?.endsWith("test-slices.mjs")) { + const args = process.argv.slice(2); + const only = args.includes("--only") ? args[args.indexOf("--only") + 1].split(",") : undefined; + const runs = sliceRuns().filter((r) => !only || only.includes(r.name)); + const unknown = (only ?? []).filter((n) => !sliceRuns().some((r) => r.name === n)); + if (unknown.length) { + console.error(`test:slices: no set ${unknown.join(", ")} (have: ${sliceRuns().map((r) => r.name).join(", ")})`); + process.exit(2); + } + const files = contractFiles().map((f) => `tests/${f}`); + if (args.includes("--list")) { + for (const r of runs) console.log(`${r.name}\t${Object.entries(r.env).map(([k, v]) => `${k}=${v}`).join(" ")}`); + console.log(files.join("\n")); + process.exit(0); + } + const tsx = join(ROOT, "node_modules", "tsx", "dist", "cli.mjs"); + const results = []; + for (const r of runs) { + console.log(`\n── ${r.name} (${Object.entries(r.env).map(([k, v]) => `${k}=${v}`).join(" ")}) ──`); + // Clear the caller's switch so each set is exactly what it says. + const env = { ...process.env, HEXMAKER_SLICES: "", HEXMAKER_SLICES_ON: "", HEXMAKER_SLICES_OFF: "", ...r.env }; + const res = spawnSync(process.execPath, [tsx, "--tsconfig", "./tsconfig.test.json", "--import", "./tests/register.mjs", "--test", "--test-reporter=dot", ...files], { cwd: ROOT, env, stdio: "inherit" }); + results.push({ name: r.name, ok: res.status === 0 }); + if (args.includes("--check-release")) { + const chk = spawnSync(process.execPath, [join(ROOT, "dev", "release", "check-release.mjs"), ...r.check], { cwd: ROOT, env: { ...process.env, HEXMAKER_SLICES: "", HEXMAKER_SLICES_ON: "", HEXMAKER_SLICES_OFF: "" }, stdio: "inherit" }); + results.push({ name: `${r.name} check:release`, ok: chk.status === 0 }); + } + } + console.log(""); + for (const r of results) console.log(`${r.ok ? "PASS" : "FAIL"} ${r.name}`); + const failed = results.filter((r) => !r.ok).length; + console.log(failed ? `\ntest:slices FAILED (${failed} of ${results.length})` : `\ntest:slices PASSED (${results.length} sets)`); + process.exit(failed ? 1 : 0); +} diff --git a/dev/smoke/cli.mjs b/dev/smoke/cli.mjs new file mode 100644 index 00000000..041b7f55 --- /dev/null +++ b/dev/smoke/cli.mjs @@ -0,0 +1,32 @@ +#!/usr/bin/env node +/** + * `npm run smoke` entry. On Windows and native Linux (the Flathub + * Obsidian, run headless by sandbox.mjs) this just runs run.mjs; under + * WSL it hands over to node.exe with the same arguments and passes its + * exit code back, since WSL can't drive Linux Obsidian there. + */ +import fs from "node:fs"; +import path from "node:path"; +import { spawnSync, execFileSync } from "node:child_process"; +import { fileURLToPath, pathToFileURL } from "node:url"; + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const RUN = path.join(HERE, "run.mjs"); +const args = process.argv.slice(2); + +const isWsl = process.platform === "linux" && /microsoft/i.test(fs.readFileSync("/proc/version", "utf8")); +if (process.platform === "win32" || (process.platform === "linux" && !isWsl)) { + process.argv = [process.argv[0], RUN, ...args]; + await import(pathToFileURL(RUN).href); +} else if (isWsl) { + const winRun = execFileSync("wslpath", ["-w", RUN], { encoding: "utf8" }).trim(); + const r = spawnSync("node.exe", [winRun, ...args], { stdio: "inherit" }); + if (r.error) { + console.error(`Couldn't start Windows node (node.exe) from WSL: ${r.error.message}. Install Node on Windows, or run: node dev/smoke/run.mjs from a Windows shell.`); + process.exit(2); + } + process.exit(r.status ?? 1); +} else { + console.error("The smoke suite needs Obsidian on Windows or Linux."); + process.exit(2); +} diff --git a/dev/smoke/lib/compare.mjs b/dev/smoke/lib/compare.mjs new file mode 100644 index 00000000..dd0828ee --- /dev/null +++ b/dev/smoke/lib/compare.mjs @@ -0,0 +1,34 @@ +/** + * Pure comparison helpers for the smoke suite (unit-tested in + * tests/smokeSuite.test.ts). + */ + +/** Where two JSON values differ: "maps[2].savedViewport.zoom: 1 → 0.8" (first `max`). */ +export function jsonDiff(a, b, at = "", out = [], max = 8) { + if (out.length >= max) return out; + if (JSON.stringify(a) === JSON.stringify(b)) return out; + if (a && b && typeof a === "object" && typeof b === "object" && Array.isArray(a) === Array.isArray(b)) { + for (const k of new Set([...Object.keys(a), ...Object.keys(b)])) jsonDiff(a[k], b[k], Array.isArray(a) ? `${at}[${k}]` : at ? `${at}.${k}` : k, out, max); + } else out.push(`${at || "(root)"}: ${JSON.stringify(a)?.slice(0, 80)} → ${JSON.stringify(b)?.slice(0, 80)}`); + return out; +} + +/** Stable JSON: object keys sorted at every level (store dumps come back in another order after a reload). */ +export function canon(v) { + const sort = (x) => (Array.isArray(x) ? x.map(sort) : x && typeof x === "object" ? Object.fromEntries(Object.keys(x).sort().map((k) => [k, sort(x[k])])) : x); + return JSON.stringify(sort(v)); +} + +/** + * Settings the plugin sets once, on some later start (the one-time + * table-ranges upgrade, note format upgrades): a restart may write these + * to data.json. Anything else it writes is a rewrite. + */ +export const ONE_TIME_KEYS = new Set(["tableRangesUpgraded", "tableRangesPrompt", "noteFormatUpgrades"]); + + +/** data.json changed only in ONE_TIME_KEYS (top level). */ +export function oneTimeOnly(a, b) { + const keys = [...new Set(jsonDiff(a, b, "", [], 500).map((s) => s.split(/[.[:]/)[0]))]; + return keys.length > 0 && keys.every((k) => ONE_TIME_KEYS.has(k)); +} diff --git a/dev/smoke/lib/concurrency.mjs b/dev/smoke/lib/concurrency.mjs new file mode 100644 index 00000000..520b400e --- /dev/null +++ b/dev/smoke/lib/concurrency.mjs @@ -0,0 +1,83 @@ +/** + * How many sandboxes the smoke suite runs at once, and how it stops them. + * + * Each sandbox is a whole Obsidian (Electron) with its own profile: about + * 1.5 GB and a busy core while it loads. On a machine that is already busy + * (another smoke run, other Obsidian windows, a build) four at once time + * out, so the suite picks fewer. `--jobs N` overrides the pick. + * + * pickJobs and stopUntilGone are pure (tested in tests/smokeSuite.test.ts); + * machineLoad reads the machine. + */ +import os from "node:os"; + +export const MAX_JOBS = 4; +/** Memory one sandbox needs, bytes. */ +export const JOB_MEM_BYTES = 1.5 * 2 ** 30; +/** Memory left alone for everything else, bytes. */ +export const RESERVE_MEM_BYTES = 2 * 2 ** 30; + +/** + * Jobs to run at once. + * @param {{ requested?: number | null, freeMem: number, cpuBusy?: number | null, cpuCount?: number, max?: number }} m + * requested: --jobs (wins, within 1..max); freeMem: free bytes; cpuBusy: + * 0..1 share of CPU in use (null = unknown); cpuCount: logical cores. + * @returns {{ jobs: number, reason: string }} + */ +export function pickJobs({ requested = null, freeMem, cpuBusy = null, cpuCount = os.cpus().length, max = MAX_JOBS }) { + const clamp = (n) => Math.max(1, Math.min(max, Math.floor(n))); + if (requested !== null && requested !== undefined && Number.isFinite(Number(requested)) && Number(requested) > 0) { + return { jobs: clamp(Number(requested)), reason: "--jobs" }; + } + const byMem = Math.floor((freeMem - RESERVE_MEM_BYTES) / JOB_MEM_BYTES); + // About two cores per sandbox while it loads. + const byCores = Math.floor(cpuCount / 2); + let byCpu = max; + if (cpuBusy !== null && cpuBusy !== undefined) { + if (cpuBusy >= 0.85) byCpu = 1; + else if (cpuBusy >= 0.6) byCpu = Math.ceil(max / 2); + } + const jobs = clamp(Math.min(byMem, byCores, byCpu)); + const gb = (b) => (b / 2 ** 30).toFixed(1); + const why = [`${gb(freeMem)} GB free`, `${cpuCount} cores`]; + if (cpuBusy !== null && cpuBusy !== undefined) why.push(`CPU ${Math.round(cpuBusy * 100)}% busy`); + return { jobs, reason: why.join(", ") }; +} + +/** Free memory and how busy the CPU is over `sampleMs` (os.loadavg is always 0 on Windows). */ +export async function machineLoad(sampleMs = 1000) { + const times = () => os.cpus().map((c) => c.times); + const a = times(); + await new Promise((r) => setTimeout(r, sampleMs)); + const b = times(); + let busy = 0, total = 0; + b.forEach((t, i) => { + const d = (k) => t[k] - (a[i]?.[k] ?? 0); + const all = d("user") + d("nice") + d("sys") + d("idle") + d("irq"); + busy += all - d("idle"); + total += all; + }); + return { freeMem: os.freemem(), cpuBusy: total > 0 ? busy / total : null, cpuCount: b.length }; +} + +/** + * Stop a run, and keep at it while its processes are still there: a busy + * machine can take well over sandbox.mjs's own few seconds to let an + * Electron go. Stop is idempotent (it only kills that run's profile). + * @param {() => Promise<{ ok?: boolean }>} stop + * @param {{ attempts?: number, waitMs?: number, sleep?: (ms: number) => Promise }} [o] + * @returns {Promise<{ ok?: boolean, attempts: number }>} the last result + */ +export async function stopUntilGone(stop, { attempts = 6, waitMs = 5000, sleep = (ms) => new Promise((r) => setTimeout(r, ms)) } = {}) { + let last = { ok: false }; + for (let i = 1; i <= attempts; i++) { + try { + last = await stop(); + } catch (e) { + last = { ok: false, error: String(e?.message ?? e) }; + } + if (last.ok) return { ...last, attempts: i }; + if (i < attempts) await sleep(waitMs); + } + return { ...last, attempts }; +} diff --git a/dev/smoke/lib/disk.mjs b/dev/smoke/lib/disk.mjs new file mode 100644 index 00000000..bd1b4a6c --- /dev/null +++ b/dev/smoke/lib/disk.mjs @@ -0,0 +1,342 @@ +/** + * Disk truth for the smoke suite (promoted from the migration runs' + * C:/Users/markr/work/tmp/migtest/disk.mjs). + * + * - snapshot(): content hash + mtime of every vault file that is the user's + * (everything outside .obsidian) plus the plugin's own folder (data.json, + * backups), so "nothing changed" can be checked file by file. + * - legacyTruth(): the map data that pre-map-note hex notes carry in their + * frontmatter, plus a hash of each note's body and non-data keys, to + * verify a migration moved exactly that and touched nothing else. + */ +import fs from "node:fs"; +import path from "node:path"; +import crypto from "node:crypto"; +import zlib from "node:zlib"; +import { createRequire } from "node:module"; +import { fileURLToPath } from "node:url"; + +const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", "..", ".."); +const YAML = createRequire(path.join(ROOT, "package.json"))("yaml"); + +const BUILD_FILES = new Set(["main.js", "manifest.json", "styles.css"]); +export const DATA_KEYS = ["terrain", "icon", "gm-icons", "gm-icon", "region", "duckmage-submap", "locked"]; +/** Hex-note properties (MG4): copies of the map's data the plugin keeps in hex notes (`region` is read as `area`). */ +export const PROP_KEYS = ["terrain", "area", "icon", "name"]; +const FM = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/; +const sha = (buf) => crypto.createHash("sha1").update(buf).digest("hex").slice(0, 16); + +/** Vault-relative, forward slashes. */ +const rel = (vault, p) => path.relative(vault, p).split(path.sep).join("/"); + +/** + * { "": { h, m, size } } for the user's files and the plugin's + * folder (minus the three build files). Obsidian's own config (workspace + * layout etc.) is left out: it changes on every start. + */ +export function snapshot(vault, pluginId) { + const out = {}; + const pluginDir = path.join(vault, ".obsidian", "plugins", pluginId); + const walk = (dir) => { + for (const e of fs.readdirSync(dir, { withFileTypes: true })) { + const p = path.join(dir, e.name); + if (e.isDirectory()) { + if (dir === vault && (e.name === ".obsidian" || e.name === ".trash")) continue; + walk(p); + } else if (e.isFile()) add(p); + } + }; + const add = (p) => { + const st = fs.statSync(p); + const buf = fs.readFileSync(p); + const entry = { h: sha(buf), m: Math.round(st.mtimeMs), size: st.size }; + // Palette notes keep their text, so a format upgrade can be checked row by row. + if (p.endsWith(".md") && st.size < 512 * 1024) { + const text = buf.toString("utf8"); + if (/^---\r?\n[\s\S]*?hexmaker-palette\s*:/.test(text)) entry.text = text; + } + out[rel(vault, p)] = entry; + }; + walk(vault); + if (fs.existsSync(pluginDir)) { + const walkPlugin = (dir) => { + for (const e of fs.readdirSync(dir, { withFileTypes: true })) { + const p = path.join(dir, e.name); + if (e.isDirectory()) walkPlugin(p); + else if (e.isFile() && !(dir === pluginDir && BUILD_FILES.has(e.name))) add(p); + } + }; + walkPlugin(pluginDir); + } + return out; +} + +/** What changed between two snapshots. `touched` = rewritten with the same bytes. */ +export function diff(a, b) { + const added = [], removed = [], changed = [], touched = []; + for (const [p, x] of Object.entries(a)) { + const y = b[p]; + if (!y) removed.push(p); + else if (y.h !== x.h) changed.push(p); + else if (y.m !== x.m) touched.push(p); + } + for (const p of Object.keys(b)) if (!a[p]) added.push(p); + return { added, removed, changed, touched }; +} + +/** Hex data a legacy hex note's frontmatter carries (as MapStore.hexDataFromFrontmatter reads it). */ +export function hexDataFromFm(fm) { + const h = {}; + if (!fm) return h; + if (typeof fm.terrain === "string" && fm.terrain) h.terrain = fm.terrain; + if (typeof fm.icon === "string" && fm.icon) h.icon = fm.icon; + const gm = Array.isArray(fm["gm-icons"]) ? fm["gm-icons"].filter((v) => typeof v === "string") : typeof fm["gm-icon"] === "string" ? [fm["gm-icon"]] : []; + if (gm.length) h.gmIcons = gm; + if (typeof fm.region === "string" && fm.region) h.region = fm.region; + if (typeof fm["duckmage-submap"] === "string" && fm["duckmage-submap"]) h.locations = [fm["duckmage-submap"]]; + if (fm.locked === true || fm.locked === "true") h.locked = true; + return h; +} + +/** A link to a map note ("[[_coast]]"), as hex notes' map key holds (NF1). */ +const isMapLink = (v) => typeof v === "string" && /^\[\[(?:[^\]|#]*\/)?_[^\]]*\]\]$/.test(v.trim()); + +/** The hex note's link to its map note: `map:` (NF1) or the older `hexmaker-map:`. */ +export const hexNoteMapLink = (fm) => (isMapLink(fm?.map) ? fm.map : isMapLink(fm?.["hexmaker-map"]) ? fm["hexmaker-map"] : null); + +/** Filled "**Terrain:**" / "**Region:**" body lines (older templates), as [field, value]. */ +export function bodyFieldLines(body) { + const out = []; + for (const l of body.split(/\r?\n/)) { + const m = /^[ \t]*\*\*(Terrain|Region):?\*\*:?[ \t]*(.*?)[ \t]*$/i.exec(l); + if (!m) continue; + const v = m[2].trim(); + if (!v || /^\*?\(.*\)\*?$/.test(v) || /^_+$/.test(v) || v === "-" || v === "—") continue; + out.push([m[1].toLowerCase(), v]); + } + return out; +} + +/** + * A body as compared before/after the plugin's note-format work: without + * the Map data callout (the plugin's) and the filled Terrain/Region lines + * it moves into it (NF2), blank runs collapsed. Everything else must be + * identical. + */ +export function comparableBody(body) { + const lines = body.replace(/\r\n?/g, "\n").split("\n"); + const out = []; + let inCallout = false; + for (const l of lines) { + if (/^\s*>\s*\[!hexmaker\]/i.test(l)) { inCallout = true; continue; } + if (inCallout && /^\s*>/.test(l)) continue; + inCallout = false; + if (bodyFieldLines(l).length) continue; + if (l.trim() === "" && out.length && out[out.length - 1].trim() === "") continue; + out.push(l); + } + return out.join("\n").trim(); +} + +function parseNote(text) { + const mm = FM.exec(text); + let fm = null, err = null; + if (mm) { try { fm = YAML.parse(mm[1]) ?? {}; } catch (e) { err = String(e).slice(0, 80); } } + const body = mm ? text.slice(mm[0].length) : text; + const other = {}; + for (const [k, v] of Object.entries(fm ?? {})) if (!DATA_KEYS.includes(k) && !PROP_KEYS.includes(k) && k !== "hexmaker-map" && !(k === "map" && isMapLink(v))) other[k] = v; + return { fm, err, body, other }; +} + +/** + * Pre-migration truth: per map, the hex data in its hex notes; per note, + * hashes of body and non-data frontmatter. Maps are the unique names in + * data.json (first wins, like the plugin). + */ +export function legacyTruth(vault, data) { + const hexFolder = (data.hexFolder ?? "").replace(/^\/+|\/+$/g, ""); + const maps = [...new Set((data.maps ?? data.regions ?? []).map((m) => m.name))]; + const out = { maps: {}, notes: {} }; + for (const m of maps) { + const dir = path.join(vault, hexFolder, m); + out.maps[m] = {}; + if (!fs.existsSync(dir)) continue; + for (const f of fs.readdirSync(dir)) { + if (!/^-?\d+_-?\d+\.md$/.test(f)) continue; + const relPath = `${hexFolder ? hexFolder + "/" : ""}${m}/${f}`; + const text = fs.readFileSync(path.join(dir, f), "utf8"); + const n = parseNote(text); + const h = hexDataFromFm(n.fm); + if (Object.keys(h).length) out.maps[m][f.replace(/\.md$/, "")] = h; + out.notes[relPath] = { text: sha(text), body: sha(comparableBody(n.body)), bodyFields: bodyFieldLines(n.body), other: sha(JSON.stringify(n.other)), dataKeys: DATA_KEYS.filter((k) => n.fm && k in n.fm), yamlError: n.err }; + } + } + return out; +} + +/** A wikilink or plain name → the bare name ("[[_chult|Chult]]" → "chult"). */ +const bare = (s) => String(s ?? "").replace(/^\[\[|\]\]$/g, "").split("|")[0].split("/").pop().replace(/^_/, "").replace(/\.md$/, "").trim().toLowerCase(); + +/** A hex note's properties vs the store's hex (null when they agree). */ +function propDiff(fm, s) { + const h = s ?? {}; + const want = { terrain: h.terrain, area: h.region ? bare(h.region) : undefined, icon: h.icon, name: h.name }; + const probs = []; + for (const k of PROP_KEYS) { + const got = fm?.[k] === undefined || fm?.[k] === null ? undefined : k === "area" ? bare(fm[k]) : String(fm[k]); + // A value of the note's own the map lacks is left for the sync to take in. + if (got !== undefined && want[k] === undefined) continue; + if ((got ?? "") !== (want[k] ?? "")) probs.push(`${k} ${got} (map: ${want[k]})`); + } + return probs.length ? probs.join("; ") : null; +} + +/** Compare one hex: legacy truth vs what the store holds now. Returns a problem string or null. */ +function hexDiff(truth, store) { + const s = store ?? {}; + const probs = []; + for (const k of ["terrain", "icon"]) if ((truth[k] ?? null) !== (s[k] ?? null)) probs.push(`${k} ${truth[k]} → ${s[k]}`); + if (JSON.stringify(truth.gmIcons ?? []) !== JSON.stringify(s.gmIcons ?? [])) probs.push(`gmIcons ${truth.gmIcons} → ${s.gmIcons}`); + if (!!truth.locked !== !!s.locked) probs.push(`locked ${truth.locked} → ${s.locked}`); + if (truth.region && bare(truth.region) !== bare(s.region)) probs.push(`region ${truth.region} → ${s.region}`); + if (truth.locations) { + const have = new Set([...(s.locations ?? []), ...(s.regionMap ? [s.regionMap] : [])].map(bare)); + for (const l of truth.locations) if (!have.has(bare(l))) probs.push(`location ${l} missing`); + } + return probs.length ? probs.join("; ") : null; +} + +/** + * After migration: store data matches the truth, every note with data got + * cleaned (data keys gone, map link added), bodies and other keys + * untouched, no hex note created or lost. + */ +export function verifyMigration(vault, truth, store) { + const problems = []; + let hexes = 0, cleaned = 0, bodies = 0; + for (const [m, hs] of Object.entries(truth.maps)) { + for (const [k, h] of Object.entries(hs)) { + hexes++; + const p = hexDiff(h, store[m]?.[k]); + if (p) problems.push(`data ${m}/${k}: ${p}`); + } + for (const k of Object.keys(store[m] ?? {})) { + const s = store[m][k]; + // Only hexes the notes gave data to; a name-only or extra row is new data. + if (!hs[k] && (s.terrain || s.icon || s.gmIcons?.length)) problems.push(`extra hex in store ${m}/${k}: ${JSON.stringify(s)}`); + } + } + for (const [p, t] of Object.entries(truth.notes)) { + const file = path.join(vault, p); + if (!fs.existsSync(file)) { problems.push(`hex note missing: ${p}`); continue; } + const n = parseNote(fs.readFileSync(file, "utf8")); + if (sha(comparableBody(n.body)) !== t.body) problems.push(`body changed: ${p}`); else bodies++; + // NF2: filled Terrain/Region lines now sit in the Map data callout. + for (const [field, value] of t.bodyFields ?? []) { + if (!n.body.toLowerCase().includes(`> old ${field}: ${value}`.toLowerCase())) problems.push(`old ${field} line not in Map data: ${p}`); + } + if (sha(JSON.stringify(n.other)) !== t.other) problems.push(`user frontmatter changed: ${p}`); + // Data keys go, except the hex-note properties (MG4), which must say what the map says. + const left = DATA_KEYS.filter((k) => n.fm && k in n.fm && !PROP_KEYS.includes(k)); + if (left.length) problems.push(`data keys left: ${p} ${left}`); + const [m, key] = p.split("/").slice(-2); + const propProbs = propDiff(n.fm, store[m]?.[key.replace(/\.md$/, "")]); + if (propProbs) problems.push(`properties of ${p}: ${propProbs}`); + else if (!left.length && t.dataKeys.length) { + cleaned++; + if (!hexNoteMapLink(n.fm)) problems.push(`no map link: ${p}`); + } + } + return { hexesChecked: hexes, notesChecked: Object.keys(truth.notes).length, bodiesIdentical: bodies, cleaned, problems }; +} + +/** The migration's full-text backups (*.json.gz) hold each cleaned note exactly as it was. */ +export function verifyBackups(vault, pluginId, seedTexts) { + const bdir = path.join(vault, ".obsidian", "plugins", pluginId, "backups"); + const out = { backupDirs: 0, notes: 0, mismatches: 0, mapJson: 0 }; + if (!fs.existsSync(bdir)) return out; + for (const day of fs.readdirSync(bdir)) { + const d = path.join(bdir, day); + if (!fs.statSync(d).isDirectory()) continue; + out.backupDirs++; + for (const f of fs.readdirSync(d)) { + if (f.endsWith(".json") && !f.includes("hex-notes")) out.mapJson++; + if (!/hex-notes\.json(\.gz)?$/.test(f)) continue; + const buf = fs.readFileSync(path.join(d, f)); + const b = JSON.parse((f.endsWith(".gz") ? zlib.gunzipSync(buf) : buf).toString("utf8")); + for (const [p, text] of Object.entries(b.notes ?? {})) { + out.notes++; + if (seedTexts[p] !== undefined && seedTexts[p] !== sha(text)) out.mismatches++; + } + } + } + return out; +} + +/** + * Notes rewritten by the one-time note-format upgrades (NF1–NF3): path → + * hash of the original text in the `backups/note-formats-` files. + * A note may change on the first start only if its original is here. + */ +export function noteFormatBackups(vault, pluginId) { + return backupsUnder(vault, pluginId, "note-formats-"); +} + +/** Roll-range table upgrades (DJ-Q6, silent and backed up): note path → hash of the backed-up original. */ +export function tableRangeBackups(vault, pluginId) { + return backupsUnder(vault, pluginId, "table-ranges-"); +} + +/** note path → hash of the original text kept in the plugin backups folders starting with prefix. */ +function backupsUnder(vault, pluginId, prefix) { + const bdir = path.join(vault, ".obsidian", "plugins", pluginId, "backups"); + const out = {}; + if (!fs.existsSync(bdir)) return out; + for (const day of fs.readdirSync(bdir)) { + if (!day.startsWith(prefix)) continue; + const d = path.join(bdir, day); + for (const f of fs.readdirSync(d)) { + if (!/\.json(\.gz)?$/.test(f)) continue; + const buf = fs.readFileSync(path.join(d, f)); + const b = JSON.parse((f.endsWith(".gz") ? zlib.gunzipSync(buf) : buf).toString("utf8")); + for (const [p, text] of Object.entries(b.notes ?? {})) out[p] ??= sha(Buffer.from(text, "utf8")); + } + } + return out; +} + +/** note path → hash of its full text (for verifyBackups). */ +export const noteTextHashes = (truth) => Object.fromEntries(Object.entries(truth.notes).map(([p, t]) => [p, t.text])); + +/** A palette note's terrain rows: name → "color|icon|icon color|category|type" (backticks and derived "(…)" cells ignored). */ +export function paletteTerrains(text) { + const out = new Map(); + const lines = text.replace(/\r/g, "").split("\n"); + let cols = null; + for (const line of lines) { + if (!line.startsWith("|")) { if (cols) break; continue; } + const cells = line.slice(1, line.endsWith("|") ? -1 : undefined).split("|").map((c) => c.trim().replace(/^`|`$/g, "")); + if (!cols) { + if (cells[0].toLowerCase() !== "terrain") continue; + cols = cells.map((c) => c.toLowerCase()); + continue; + } + if (/^-+$/.test(cells[0])) continue; + const at = (name) => { const i = cols.indexOf(name); return i >= 0 ? (cells[i] ?? "").toLowerCase() : ""; }; + out.set(cells[0], [at("color"), at("icon"), at("icon color"), at("category"), at("type")].join("|")); + } + return out; +} + +/** Problems when a rewritten palette note lost or changed a terrain (a format upgrade may only add columns). */ +export function verifyPaletteUpgrade(before, after) { + const a = paletteTerrains(before), b = paletteTerrains(after); + const probs = []; + if (!a.size) probs.push("no terrain table before"); + for (const [name, v] of a) { + if (!b.has(name)) probs.push(`terrain "${name}" gone`); + else if (b.get(name) !== v) probs.push(`terrain "${name}": ${v} → ${b.get(name)}`); + } + for (const name of b.keys()) if (!a.has(name)) probs.push(`terrain "${name}" added`); + return probs; +} diff --git a/dev/smoke/lib/exports.mjs b/dev/smoke/lib/exports.mjs new file mode 100644 index 00000000..6d4381e8 --- /dev/null +++ b/dev/smoke/lib/exports.mjs @@ -0,0 +1,212 @@ +/** + * C11 exports, end to end in real Obsidian (security review #2 and #11). + * Runs in the page like the other helpers in page.mjs (sent as source + * text, so it must be self-contained). + * + * - A note with a vault image and a remote image is exported to PDF with + * the "Export current note to PDF" command: the PDF is written, carries + * the hexmaker-export marker, and has the vault image in it. The print + * webview has no nodeintegration, and its page refuses the remote image + * (a CSP report in the webview's console). + * - Overwrite rule: a hand-made file at the markdown export's name is kept + * and the export goes to " 2.md"; exporting again replaces that + * copy (no " 3"); a second PDF export replaces the first. + * - The map export form (Export current map…): PNG (with the marker + * chunk), the PDF with reference table and the hexcrawl manual are all + * written. + * Everything made here is deleted again, so the C5 restart compares a + * clean vault. + * + * PDF parts need Electron s, which never load in the headless + * Linux sandbox (not even about:blank, 2026-10-17), so on Linux they are + * skipped and reported as such; the markdown and PNG parts always run. + * The webview's set-up is unit tested in tests/pdfWebview.test.ts. + */ +export async function exportsRoundTrip(id, withMapForm = true, opts = {}) { + // The "manual" slice (Hexcrawl manual in the form): on unless the build says it's off. + const manual = opts.manual ?? true; + const app = window.app; + const p = app.plugins.plugins[id]; + const vault = app.vault; + const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); + const out = { ok: true, steps: [], problems: [] }; + const pdfs = window.process?.platform !== "linux"; + if (!pdfs) out.steps.push("PDF exports skipped: webviews don't load in the headless Linux sandbox"); + const fail = (m) => { out.ok = false; out.problems.push(m); }; + const norm = (f) => (f ?? "").replace(/^\/+|\/+$/g, ""); + const folder = norm(p.settings.exportFolder) || (norm(p.settings.worldFolder) ? `${norm(p.settings.worldFolder)}/exports` : "exports"); + const file = (path) => vault.getAbstractFileByPath(path); + const waitFile = async (path, ms = 60_000) => { + const t0 = performance.now(); + while (performance.now() - t0 < ms) { if (file(path)) return true; await sleep(250); } + return false; + }; + const bytes = async (path) => new Uint8Array(await vault.readBinary(file(path))); + const latin = (b) => new TextDecoder("latin1").decode(b); + const run = (cmd) => app.commands.executeCommandById(`${id}:${cmd}`); + const made = []; + const keep = (path) => { if (!made.includes(path)) made.push(path); }; + + // Every print webview: its attributes and what its page logs. + const webviews = []; + const mo = new MutationObserver((muts) => { + for (const m of muts) for (const n of m.addedNodes) { + if (n.tagName !== "WEBVIEW") continue; + const w = { nodeintegration: n.getAttribute("nodeintegration"), partition: n.getAttribute("partition"), src: n.getAttribute("src"), console: [] }; + n.addEventListener("console-message", (e) => w.console.push(String(e.message))); + webviews.push(w); + } + }); + mo.observe(activeDocument.body, { childList: true }); + + try { + // ── the probe note: a vault image and a remote one ── + const dir = "smoke-export"; + if (!file(dir)) await vault.createFolder(dir); + keep(dir); + const canvas = activeDocument.createElement("canvas"); + canvas.width = 64; canvas.height = 64; + const g = canvas.getContext("2d"); + g.fillStyle = "#c0392b"; g.fillRect(0, 0, 64, 64); + g.fillStyle = "#2c3e50"; g.fillRect(16, 16, 32, 32); + const png = await new Promise((r) => canvas.toBlob(r, "image/png")); + await vault.createBinary(`${dir}/probe.png`, await png.arrayBuffer()); + keep(`${dir}/probe.png`); + const note = await vault.create(`${dir}/Export probe.md`, "# Export probe\n\nSome text to print.\n\n![[probe.png]]\n\n![remote](https://example.invalid/remote-probe.png)\n"); + keep(note.path); + await sleep(500); + const leaf = app.workspace.getLeaf("tab"); + await leaf.openFile(note); + app.workspace.setActiveLeaf(leaf, { focus: true }); + await sleep(800); + + // ── PDF of the note ── + const pdfPath = `${folder}/Export probe.pdf`; + if (pdfs) { + if (!run("export-current-note-pdf")) fail("export-current-note-pdf didn't run"); + if (!(await waitFile(pdfPath))) fail(`no ${pdfPath} after 60 s`); + else { + keep(pdfPath); + const b = await bytes(pdfPath); + const t = latin(b); + const tail = t.slice(-200); + if (!t.startsWith("%PDF-")) fail("note PDF: not a PDF"); + if (!/%%EOF\s*%hexmaker-export\s*$/.test(tail)) fail(`note PDF: no export marker at the end (${JSON.stringify(tail.slice(-40))})`); + if (!/\/Subtype\s*\/Image/.test(t)) fail("note PDF: the vault image isn't in it"); + else out.steps.push(`note PDF ${b.length} bytes, marker, image`); + } + const w = webviews[0]; + if (!w) fail("no print webview seen"); + else { + if (w.nodeintegration !== null) fail(`webview nodeintegration="${w.nodeintegration}"`); + const refused = w.console.filter((m) => /Content Security Policy/i.test(m) && /example\.invalid/.test(m)); + if (!refused.length) fail(`remote image not refused by the CSP; webview console: ${w.console.slice(0, 5).join(" | ") || "(empty)"}`); + else out.steps.push("webview: no nodeintegration, remote image refused by the CSP"); + } + if (activeDocument.querySelector("webview")) fail("print webview left in the page"); + + // A second PDF export replaces the first. + await sleep(1500); + app.workspace.setActiveLeaf(leaf, { focus: true }); + run("export-current-note-pdf"); + await sleep(6000); + if (file(`${folder}/Export probe 2.pdf`)) { keep(`${folder}/Export probe 2.pdf`); fail("second PDF export didn't replace the first (wrote Export probe 2.pdf)"); } + else out.steps.push("re-export replaced the PDF"); + } + + // ── markdown: never over a file it didn't make ── + const own = "# Export probe\n\nMy own notes, not an export.\n"; + const ownPath = `${folder}/Export probe.md`; + if (!file(folder)) await vault.createFolder(folder); + await vault.create(ownPath, own); + keep(ownPath); + app.workspace.setActiveLeaf(leaf, { focus: true }); + run("export-current-note-markdown"); + const copy = `${folder}/Export probe 2.md`; + if (!(await waitFile(copy, 15_000))) fail(`markdown export: no ${copy}`); + else { + keep(copy); + await sleep(500); + if ((await vault.read(file(ownPath))) !== own) fail("markdown export changed the hand-made file"); + if (!/^---\n[\s\S]*hexmaker-export: note/.test(await vault.read(file(copy)))) fail("markdown copy has no hexmaker-export"); + app.workspace.setActiveLeaf(leaf, { focus: true }); + run("export-current-note-markdown"); + await sleep(3000); + if (file(`${folder}/Export probe 3.md`)) { keep(`${folder}/Export probe 3.md`); fail("re-export wrote Export probe 3.md instead of replacing its copy"); } + else out.steps.push("markdown: hand-made file kept, copy as 'Export probe 2.md', re-export replaced it"); + } + leaf.detach(); + + // ── the map export form ── + if (withMapForm) { + // The form opens on the map in the open map view (C3 left one open). + run("export-current-map"); + await sleep(1000); + const modal = () => activeDocument.querySelector(".modal-container .modal"); + const click = (label) => { + const b = [...(modal()?.querySelectorAll("button") ?? [])].find((x) => x.textContent.trim() === label); + if (!b) { fail(`map export form: no "${label}" button`); return false; } + b.click(); + return true; + }; + const before = new Set(vault.getFiles().map((f) => f.path)); + const newFile = async (ext, ms = 90_000) => { + const t0 = performance.now(); + while (performance.now() - t0 < ms) { + const f = vault.getFiles().find((x) => !before.has(x.path) && x.path.startsWith(`${folder}/`) && x.extension === ext && !made.includes(x.path)); + if (f) { keep(f.path); return f.path; } + await sleep(300); + } + return null; + }; + // The form's Hexcrawl manual part is there exactly when the build has the manual slice. + if (modal()) { + const text = modal().textContent; + const writes = [...modal().querySelectorAll(".duckmage-export-tab-preview")].map((e) => e.textContent).join(" "); + const has = { fold: text.includes("Hexcrawl manual"), button: [...modal().querySelectorAll("button")].some((b) => b.textContent.trim() === "Export hexcrawl manual (PDF)"), writes: writes.includes("(manual)") }; + if (manual && !(has.fold && has.button && has.writes)) fail(`map export form: the manual slice is built but its part is missing ${JSON.stringify(has)}`); + else if (!manual && (has.fold || has.button || has.writes)) fail(`map export form: the manual slice is off but its part shows ${JSON.stringify(has)}`); + else out.steps.push(manual ? "form has the Hexcrawl manual part" : "form has no Hexcrawl manual part (slice off)"); + } + if (modal() && click("Export PNG")) { + const f = await newFile("png"); + if (!f) fail("map PNG: not written"); + else { + const t = latin(await bytes(f)); + if (!t.includes("tEXthexmaker-export")) fail("map PNG: no export marker chunk"); + else out.steps.push(`map PNG ${f} with its marker`); + } + } + if (pdfs && !modal()) { run("export-current-map"); await sleep(1000); } + if (pdfs && modal() && click("Export PDF with reference table")) { + const f = await newFile("pdf"); + if (!f) fail("map PDF: not written"); + else if (!/%hexmaker-export\s*$/.test(latin(await bytes(f)).slice(-60))) fail(`map PDF ${f}: no export marker`); + else out.steps.push(`map PDF ${f}`); + } + if (pdfs && !modal()) { run("export-current-map"); await sleep(1000); } + if (pdfs && manual && modal() && click("Export hexcrawl manual (PDF)")) { + const f = await newFile("pdf", 120_000); + if (!f) fail("hexcrawl manual: not written"); + else out.steps.push(`manual ${f}`); + } + activeDocument.querySelectorAll(".modal-container .modal-close-button").forEach((b) => b.click()); + } + const open = webviews.filter((x) => x.nodeintegration !== null); + if (open.length) fail(`${open.length} print webviews with nodeintegration`); + else if (webviews.length) out.steps.push(`${webviews.length} print webviews, none with nodeintegration`); + } catch (e) { + fail(`crash: ${e?.stack ?? e}`); + } finally { + mo.disconnect(); + // Close tabs showing what was made, then delete it (files first). + app.workspace.getLeavesOfType("pdf").concat(app.workspace.getLeavesOfType("image"), app.workspace.getLeavesOfType("markdown")) + .filter((l) => made.includes(l.view?.file?.path)).forEach((l) => l.detach()); + await sleep(500); + for (const path of [...made].reverse()) { + const f = file(path); + if (f) { try { await vault.delete(f, true); } catch (e) { out.problems.push(`cleanup ${path}: ${e}`); } } + } + } + return out; +} diff --git a/dev/smoke/lib/hexFields.mjs b/dev/smoke/lib/hexFields.mjs new file mode 100644 index 00000000..2c04b2eb --- /dev/null +++ b/dev/smoke/lib/hexFields.mjs @@ -0,0 +1,132 @@ +/** + * C12 hex fields (plan-custom-hex-fields phase 1, #52). Runs in the page + * like the other helpers in page.mjs (sent as source text, so it must be + * self-contained). + * + * Declares a Population field (a one-row table: 100) and a Town influence + * (+1000 on its hex, x2 within 2) in the world's fields note; on a new + * map, paints three hexes through the map view's own mouse handler (each + * gets Population 100 and its Field rolls); types 250 into one hex's + * Fields box in the hex editor; links a town note under another hex's + * Towns; runs the "Recalculate fields" command and clicks Update places. + * Then: the town hex is 1100, its neighbour 200 (x2), the typed 250 is + * kept; the map note's Population and Field rolls columns say so; the + * map view's undo puts the recalculation back. The fields note is + * removed again afterwards (the map stays, for the C5 restart). + */ +export async function hexFieldsCheck(id) { + const app = window.app; + const p = app.plugins.plugins[id]; + const store = p.mapStore; + const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); + const waitFor = async (fn, ms = 5000) => { const t0 = performance.now(); while (performance.now() - t0 < ms) { const v = await fn(); if (v) return v; await sleep(100); } return fn(); }; + const out = { ok: true, steps: [], problems: [] }; + const fail = (m) => { out.ok = false; out.problems.push(m); }; + if (!p.fields) return { ok: true, skipped: "no hex fields in this build", steps: [], problems: [] }; + const modalsBefore = document.querySelectorAll(".modal-container").length; + // Close the modals this check opened (the top one each time: Escape, then its × if that didn't do it). + const closeOurs = async () => { + for (let i = 0; i < 10 && document.querySelectorAll(".modal-container").length > modalsBefore; i++) { + const all = document.querySelectorAll(".modal-container"); + const top = all[all.length - 1]; + document.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", code: "Escape", bubbles: true })); + await sleep(200); + if (top.isConnected) { top.querySelector(".modal-close-button")?.click(); await sleep(200); } + } + }; + const world = p.settings.worldFolder || "world"; + const tables = (p.settings.tablesFolder || `${world}/tables`).replace(/\/+$/, ""); + // 1. A table and the declarations. + const tablePath = `${tables}/fields/Smoke population.md`; + if (!app.vault.getAbstractFileByPath(`${tables}/fields`)) await app.vault.createFolder(`${tables}/fields`).catch(() => {}); + if (!app.vault.getAbstractFileByPath(tablePath)) await app.vault.create(tablePath, "| d1 | Result | Weight |\n| --- | --- | --- |\n| 1 | 100 | 1 |\n"); + await waitFor(() => p.tableNotes.lookup().table(tablePath.replace(/\.md$/, ""))); + await p.fields.store.save({ + fields: [{ name: "Population", type: "whole number", default: "0", table: tablePath.replace(/\.md$/, "") }], + influences: [{ place: "Town", field: "Population", here: "+1000", nearby: "x2", radius: 2 }], + }); + const notePath = p.fields.store.notePath(); + const noteText = (await app.vault.adapter.exists(notePath)) ? await app.vault.adapter.read(notePath) : ""; + if (!/\| Population \| whole number \|/.test(noteText)) fail(`fields note ${notePath}: ${noteText.slice(0, 200)}`); + else out.steps.push(`declared Population in ${notePath}`); + // 2. A map, three hexes painted with the map view's mouse handler. + const pal = p.settings.defaultPalette ?? p.settings.terrainPalettes[0].name; + const res = await p.createNewMap({ name: "Smoke Fields", cols: 9, rows: 7, palette: pal, quiet: true }); + if ("error" in res) return { ok: false, steps: out.steps, problems: [`new map: ${res.error}`] }; + const map = res.name; + await p.showMap(map); + await sleep(800); + const view = app.workspace.getLeavesOfType("duckmage-hex-map")[0]?.view; + if (!view || view.activeMapName !== map) return { ok: false, steps: out.steps, problems: ["map view did not open " + map] }; + app.workspace.setActiveLeaf(view.leaf, { focus: true }); + const terrain = p.getMapPalette(map).map((t) => t.name).find((t) => t.toLowerCase() !== "town"); + const hexEl = (k) => view.containerEl.querySelector(`.duckmage-hex[data-x="${k.split("_")[0]}"][data-y="${k.split("_")[1]}"]`); + const paint = async (k) => { + const el = hexEl(k); + if (!el) { fail(`no hex element ${k}`); return; } + view.leaveOtherToolFor?.("terrain"); + view.drawingMode = "terrain"; + view.isErasingMode = false; + view.terrainPickMode = false; + view.paintTerrainName = terrain; + view.paintBrushSize = 1; + el.scrollIntoView?.({ block: "center", inline: "center" }); + const r = el.getBoundingClientRect(); + const at = { bubbles: true, cancelable: true, button: 0, clientX: r.x + r.width / 2, clientY: r.y + r.height / 2 }; + el.dispatchEvent(new MouseEvent("mousedown", at)); + el.ownerDocument.dispatchEvent(new MouseEvent("mouseup", at)); + await view.terrainWritesSettled?.(); + await store.flush(); + }; + const pop = (k) => store.get(map, k)?.extra?.Population; + for (const k of ["2_3", "4_3", "5_3"]) await paint(k); + view.exitTerrainMode?.(); + view.drawingMode = null; + const painted = ["2_3", "4_3", "5_3"].map((k) => `${k}=${pop(k)}`); + if (["2_3", "4_3", "5_3"].some((k) => pop(k) !== "100")) fail(`painted hexes should roll Population 100: ${painted.join(", ")}`); + else out.steps.push(`painted ${painted.join(", ")}`); + // 3. Typed in the hex editor's Fields section. + view.openHexEditorModal(2, 3); + const box = await waitFor(() => document.querySelector(".modal .duckmage-editor-field-input")); + if (!box) fail("the hex editor has no Fields box"); + else { + box.value = "250"; + box.dispatchEvent(new Event("change", { bubbles: true })); + await waitFor(() => pop("2_3") === "250"); + if (pop("2_3") !== "250") fail(`typed 250 in the editor; the map has ${pop("2_3")}`); + else if (/Population/.test(store.get(map, "2_3")?.extra?.["Field rolls"] ?? "")) fail("a typed value kept its roll"); + else out.steps.push("typed 250 in the editor"); + } + await closeOurs(); + // 4. A town linked under 5_3's Towns, then Recalculate fields → Update places. + const link = await p.hexNotes.createAndLinkNote({ x: 5, y: 3, mapName: map, section: "Towns", folder: `${world}/towns`, name: "Smoke Fields Town" }); + await waitFor(() => p.fields.places(map).some((pl) => pl.key === "5_3" && pl.type === "town")); + if (!p.fields.places(map).some((pl) => pl.key === "5_3")) fail(`the town ${link} under 5_3's Towns isn't a place`); + app.workspace.setActiveLeaf(view.leaf, { focus: true }); + const ran = app.commands.executeCommandById(`${id}:recalculate-fields`); + const btn = await waitFor(() => document.querySelector(".modal .duckmage-recalc-modifiers")); + if (!ran || !btn) fail(`Recalculate fields: command ran ${ran}, Update places button ${!!btn}`); + else btn.click(); + await waitFor(() => pop("5_3") === "1100"); + await store.flush(); + const after = { "5_3": pop("5_3"), "4_3": pop("4_3"), "2_3": pop("2_3") }; + if (after["5_3"] !== "1100" || after["4_3"] !== "200" || after["2_3"] !== "250") fail(`after Recalculate: ${JSON.stringify(after)} (want town 1100, next door 200, typed 250)`); + else out.steps.push(`recalculated near the town: ${JSON.stringify(after)}`); + const text = await app.vault.adapter.read(store.notePath(map)); + const row = /^\|\s*4_3\s*\|.*$/m.exec(text)?.[0] ?? ""; + if (!/\| Population \|/.test(text) || !/\b200\b/.test(row) || !/Population: 100/.test(row)) fail(`map note row 4_3: ${row}`); + else out.steps.push("map note has the Population and Field rolls columns"); + // 5. Undo puts the recalculation back. + await view.undo(); + await store.flush(); + if (pop("4_3") !== "100" || pop("5_3") !== "100") fail(`undo of Recalculate: 4_3=${pop("4_3")}, 5_3=${pop("5_3")}`); + else out.steps.push("undo put the hexes back"); + await closeOurs(); + const left = document.querySelectorAll(".modal-container").length - modalsBefore; + if (left > 0) fail(`${left} modal(s) this check opened are still open`); + // Clean up the declarations (the map stays for the restart check). + const fnote = app.vault.getAbstractFileByPath(notePath); + if (fnote) await app.vault.delete(fnote); + await waitFor(() => p.fields.fields().length === 0); + return out; +} diff --git a/dev/smoke/lib/hexFlower.mjs b/dev/smoke/lib/hexFlower.mjs new file mode 100644 index 00000000..23b166db --- /dev/null +++ b/dev/smoke/lib/hexFlower.mjs @@ -0,0 +1,640 @@ +/** + * C10 hex flower solo (plan-hex-flower). Runs in the page like the other + * helpers in page.mjs (sent as source text, so it must be self-contained). + * + * In a build with the hexflower slice (skipped otherwise): the setup + * wizard doesn't list Hex flower (HF8: a kind of map, not a generator); a map made with it (as the + * wizard does: generate, createNewMap, afterCreate) has only its middle + * hex filled, a Party token there, a hex flower note and explore-with; in + * Play a party step into a blank neighbour fills it, and the view's undo + * (Ctrl+Z) takes the step and the fill back together; a hand-painted hex + * the party walks into is untouched. HF4: walking north off the edge grows + * the map (blank, no hex notes), Ctrl+Z shrinks it back, redo grows it + * again. The map stays, so the C5 restart then checks that nothing is + * rewritten (and the grown size is read back). + */ +export async function hexFlowerSolo(id) { + const app = window.app; + const p = app.plugins.plugins[id]; + const store = p.mapStore; + const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); + const waitFor = async (fn, ms = 4000) => { const t0 = performance.now(); while (performance.now() - t0 < ms) { const v = fn(); if (v) return v; await sleep(100); } return fn(); }; + const out = { ok: true, steps: [], problems: [] }; + const fail = (m) => { out.ok = false; out.problems.push(m); }; + const kinds = p.moduleGenerators({ toPaths: () => ({ paths: [], missing: [] }), procGrid: (g) => ({ ...g, orientation: p.settings.hexOrientation }) }); + const kind = kinds.find((k) => k.id === "procedural:hex-flower"); + if (!kind) return { ok: true, skipped: "the hexflower slice isn't in this build", steps: [], problems: [] }; + // HF8: exploring is a kind of map (New map's Explore as you go), never in a generator list. + const leaf = app.workspace.getLeavesOfType("duckmage-setup-wizard")[0]; + if (leaf) { + const wiz = leaf.view; + wiz.currentIndex = 2; + wiz.renderView(); + const gens = () => [...wiz.contentEl.querySelectorAll(".duckmage-setup-gen .duckmage-setup-gen-title")].map((e) => e.textContent); + await waitFor(() => gens().length > 1); + if (gens().includes("Hex flower")) fail(`wizard lists Hex flower: ${gens().join(", ")}`); + else out.steps.push("wizard: no Hex flower in the list"); + } + // Make the map as the wizard does. + const pal = p.settings.defaultPalette ?? p.settings.terrainPalettes[0].name; + const terrains = p.getPaletteOrPresetTerrains(pal); + const grid = { cols: 9, rows: 7, offset: { x: 0, y: 0 }, stagger: p.settings.staggerOffset ?? "odd" }; + const options = { flower: "new", start: "blank", party: "on", reveal: "entered" }; + const seed = 4242; + const gen = kind.generate({ terrains, grid, seed, options }); + if (!gen.ok) return { ok: false, steps: [], problems: ["generate: " + gen.message] }; + const res = await p.createNewMap({ name: "Smoke Flower", cols: 9, rows: 7, palette: pal, terrain: gen.cells, quiet: true }); + if ("error" in res) return { ok: false, steps: [], problems: ["create: " + res.error] }; + const name = res.name; + await kind.afterCreate(p, { mapName: name, generatorId: kind.id, options, seed, grid, paletteName: pal, choices: {}, onProgress: () => {} }); + await store.flush?.(); + await sleep(800); + const map = p.getMap(name); + const filled = [...store.all(name)].filter(([, h]) => h.terrain).map(([k]) => k); + if (filled.length !== 1 || filled[0] !== "4_3") fail(`filled at start: ${JSON.stringify(filled)}`); + if (!map.exploreWith?.length || !map.hexFlowerAt?.length || map.seed !== seed) fail(`map keys: ${JSON.stringify({ e: map.exploreWith, a: map.hexFlowerAt, s: map.seed })}`); + const note = await app.vault.adapter.read(store.notePath(name)); + if (!/^explore-with:/m.test(note) || !/^hex-flower-at:/m.test(note)) fail("the map note has no explore-with / hex-flower-at"); + const flowerNote = app.vault.getMarkdownFiles().find((f) => /\/hex flowers\//.test(f.path)); + if (!flowerNote || !/hexmaker-hex-flower: 1/.test(await app.vault.read(flowerNote))) fail("no hex flower note"); + const party = app.vault.getMarkdownFiles().find((f) => /\/tokens\/Party( \d+)?\.md$/.test(f.path)); + const partyText = party ? await app.vault.read(party) : ""; + if (!/token-party: true/.test(partyText) || !/token-hex: "?4_3"?/.test(partyText)) fail("no Party token on 4_3"); + if (out.ok) out.steps.push(`made ${name}: only 4_3 filled (${store.get(name, "4_3")?.terrain}), Party there, ${flowerNote?.path}`); + + // Play: step into a blank neighbour. + await p.showMap(name); + await sleep(800); + const view = app.workspace.getLeavesOfType("duckmage-hex-map")[0]?.view; + if (!view || view.activeMapName !== name) { fail("map view did not open " + name); return out; } + view.setWorkMode("play"); + await sleep(400); + const press = (el) => { + const r = el.getBoundingClientRect(); + const at = { bubbles: true, cancelable: true, button: 0, clientX: r.x + r.width / 2, clientY: r.y + r.height / 2 }; + el.dispatchEvent(new MouseEvent("mousedown", at)); + el.ownerDocument.dispatchEvent(new MouseEvent("mouseup", at)); + }; + // Pick the party up (if it isn't) and return the lit hexes. + const pickUp = async () => { + const t = await waitFor(() => view.containerEl.querySelector(".duckmage-token.is-party")); + if (!t) return []; + if (!view.containerEl.querySelector(".duckmage-token.is-party.is-selected")) press(t); + await sleep(700); + const lit = () => [...view.containerEl.querySelectorAll(".duckmage-hex-map-grid .duckmage-hex.duckmage-party-step")].filter((el) => el.isConnected); + await waitFor(() => lit().length > 0); + return lit(); + }; + const click = (el) => { + view.contentEl.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true, button: 0 })); + el.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true, button: 0 })); + }; + let lit = await pickUp(); + const blank = lit.find((el) => !store.get(name, `${el.dataset.x}_${el.dataset.y}`)?.terrain); + if (!blank) { fail("no blank neighbour lit"); return out; } + const to = `${blank.dataset.x}_${blank.dataset.y}`; + click(blank); + const got = await waitFor(() => store.get(name, to)?.terrain, 5000); + if (!got) fail(`stepping into ${to} didn't fill it`); + else out.steps.push(`play: party 4_3 → ${to}, filled ${got}`); + await sleep(600); + // Ctrl+Z: the step and the fill come back together. + await view.undo(); + await sleep(800); + const tokText = party ? await app.vault.read(party) : ""; + if (store.get(name, to)?.terrain) fail(`undo left ${to} filled`); + if (!/token-hex: "?4_3"?/.test(tokText)) fail("undo didn't take the party back to 4_3"); + if (out.ok) out.steps.push("undo: fill and step taken back together"); + // A hand-painted hex is untouched. + lit = await pickUp(); + const other = lit.find((el) => `${el.dataset.x}_${el.dataset.y}` !== to) ?? lit[0]; + if (!other) { fail("no neighbour lit after undo"); return out; } + const painted = `${other.dataset.x}_${other.dataset.y}`; + const paintWith = terrains[terrains.length - 1].name; + store.set(name, painted, { terrain: paintWith }); + await sleep(400); + lit = await pickUp(); + const again = lit.find((el) => `${el.dataset.x}_${el.dataset.y}` === painted); + if (!again) fail(`painted hex ${painted} wasn't lit`); + else { + click(again); + await sleep(1500); + if (store.get(name, painted)?.terrain !== paintWith) fail(`the painted hex ${painted} changed to ${store.get(name, painted)?.terrain}`); + else out.steps.push(`painted hex ${painted} kept ${paintWith}`); + } + // HF4: walk north to the edge; the map grows (blank), undo shrinks it, redo grows it again. + const gridNow = () => ({ ...p.getMap(name).gridOffset, ...p.getMap(name).gridSize }); + const start = gridNow(); + const partyNow = () => { view.tokens.loadTokensForMap(); return view.tokens.tokenEntries.find((t) => t.party); }; + let grewAt = null; + for (let i = 0; i < 12 && !grewAt; i++) { + const t = partyNow(); + if (!t) { fail("no party to walk north"); break; } + const [x, y] = t.hex.split("_").map(Number); + await view.tokens.moveParty(t, `${x}_${y - 1}`); + await sleep(500); + if (gridNow().y !== start.y) grewAt = `${x}_${y - 1}`; + } + if (!grewAt) fail(`walking north never grew the map (grid ${JSON.stringify(gridNow())})`); + else { + const grown = gridNow(); + const notes = app.vault.getMarkdownFiles().filter((f) => f.path.startsWith(store.mapFolder?.(name) ?? "\u0000") && /\/-?\d+_-\d+\.md$/.test(f.path)); + if (notes.length) fail(`growing made hex notes: ${notes.map((f) => f.path).join(", ")}`); + await view.undo(); + await sleep(800); + if (gridNow().y === grown.y) fail(`undo kept the grown rows (${JSON.stringify(gridNow())})`); + await view.redo(); + await sleep(800); + if (gridNow().y !== grown.y) fail(`redo didn't grow it again (${JSON.stringify(gridNow())})`); + if (out.ok) out.steps.push(`grew at ${grewAt}: rows ${start.rows} → ${grown.rows}, undo and redo`); + } + view.setWorkMode("build"); + await p.saveSettings(); + await store.flush?.(); + await sleep(500); + return out; +} + +/** + * C10b Explore as you go (HF8). Through the real New map form: Terrain → + * Explore as you go (the size row says the map starts 3 × 3, a start grid + * of 9 hexes), the generator list picks the home generator, Add another + * area puts a second one north and near, a click on a hex moves the start, + * Create. Then the map: 3 × 3, two areas in explore-realms, the realms rule, + * the start hex filled from the home area's terrains and the party there; + * in Play, five steps north fill each hex from the areas' terrains and grow + * the map. The map stays for the C5 restart (nothing rewritten). + */ +export async function exploreAsYouGo(id) { + const app = window.app; + const p = app.plugins.plugins[id]; + const store = p.mapStore; + const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); + const waitFor = async (fn, ms = 6000) => { const t0 = performance.now(); while (performance.now() - t0 < ms) { const v = fn(); if (v) return v; await sleep(100); } return fn(); }; + const out = { ok: true, steps: [], problems: [] }; + const fail = (m) => { out.ok = false; out.problems.push(m); }; + const kinds = p.moduleGenerators({ toPaths: () => ({ paths: [], missing: [] }), procGrid: (g) => ({ ...g, orientation: p.settings.hexOrientation }) }); + if (!kinds.some((k) => k.id === "procedural:hex-flower")) return { ok: true, skipped: "the hexflower slice isn't in this build", steps: [], problems: [] }; + const first = p.settings.maps[0]?.name; + if (!first) return { ok: false, steps: [], problems: ["no map to open New map from"] }; + await p.showMap(first); + await sleep(800); + const view = app.workspace.getLeavesOfType("duckmage-hex-map")[0]?.view; + if (!view) return { ok: false, steps: [], problems: ["no map view"] }; + view.setWorkMode("build"); + view.containerEl.querySelector(".duckmage-region-btn")?.click(); + const newBtn = await waitFor(() => document.querySelector(".duckmage-map-new-btn")); + if (!newBtn) return { ok: false, steps: [], problems: ["the Maps modal has no New map… button"] }; + newBtn.click(); + const modal = await waitFor(() => document.querySelector(".duckmage-setup-modal .duckmage-setup-form")?.closest(".modal")); + if (!modal) return { ok: false, steps: [], problems: ["New map didn't open"] }; + const q = (sel) => modal.querySelector(sel); + const qa = (sel) => [...modal.querySelectorAll(sel)]; + const visible = (el) => !!el && el.isConnected && el.offsetParent !== null; + const name = modal.querySelector(".duckmage-setup-name"); + name.value = "Smoke Explore"; + name.dispatchEvent(new Event("input", { bubbles: true })); + // Terrain: Generate it now / Explore as you go / Blank. + const cards = () => qa(".duckmage-wizard-scale-btn"); + const modes = cards().map((c) => c.querySelector(".duckmage-wizard-orient-label")?.textContent); + if (!["Generate it now", "Explore as you go", "Blank"].every((m) => modes.includes(m))) fail(`Terrain choices: ${modes.join(", ")}`); + cards().find((c) => c.querySelector(".duckmage-wizard-orient-label")?.textContent === "Explore as you go")?.click(); + const startGrid = await waitFor(() => qa(".duckmage-explore-start-hex").length === 9); + if (!startGrid) fail(`start grid: ${qa(".duckmage-explore-start-hex").length} hexes`); + const sizeSet = q(".duckmage-setup-size-set"); + if (!visible(sizeSet) || !/^Starts 3 × 3/.test(sizeSet.textContent)) fail(`size line: ${sizeSet?.textContent} (shown ${visible(sizeSet)})`); + if (visible(q(".duckmage-setup-size-custom input"))) fail("the size fields still show"); + // The home generator: the first row of the list (the default), its mix said under it. + // "Land: mostly grass, hills and mixed forest; also marsh and desert rocky." (HF10: the hidden tile's land) → the terrains named. + const mixOf = () => (q(".duckmage-explore-mix")?.textContent ?? "").replace(/^Land: (?:mostly |all )?/, "").replace(/\.$/, "").replace(/…/g, "") + .split(/; also |, | and /).map((t) => t.trim()).filter(Boolean); + const homeMix = mixOf(); + const homeName = q(".duckmage-explore-area.is-active")?.textContent?.replace(/^Home: /, ""); + if (!homeMix.length) fail(`no mix for home: ${q(".duckmage-explore-mix")?.textContent}`); + // Another area: north, near, a different generator. + q(".duckmage-explore-area-add")?.click(); + await waitFor(() => qa(".duckmage-explore-area").length === 2); + qa(".duckmage-explore-dir").find((d) => d.getAttribute("aria-label") === "north")?.click(); + await sleep(200); + const far = q(".duckmage-explore-where select"); + if (far) { far.value = "near"; far.dispatchEvent(new Event("change", { bubbles: true })); } + await sleep(200); + // The Explore setup's own list (the Generate list is on the form too, hidden): open its first group. + const groups = qa(".duckmage-setup-mode .duckmage-gen-pick-group"); + groups[0]?.click(); + await sleep(200); + const rows = qa(".duckmage-setup-mode .duckmage-gen-pick-row"); + const other = rows.find((r) => !r.classList.contains("is-active")); + const otherName = other?.querySelector(".duckmage-gen-pick-name")?.textContent ?? ""; + other?.click(); + await sleep(300); + const areaMix = mixOf(); + const areaChip = (qa(".duckmage-explore-area")[1]?.textContent ?? "").replace(/✕$/, ""); + if (areaChip !== `North, near: ${otherName}`) fail(`second area: ${areaChip} (picked ${otherName} of ${rows.length} rows, ${groups.length} groups)`); + // Start on the bottom-middle hex. + qa(".duckmage-explore-start-hex").find((h) => h.getAttribute("aria-label") === "1, 2")?.click(); + await sleep(300); + if (q(".duckmage-explore-start-hex.is-active")?.getAttribute("aria-label") !== "1, 2") fail("the start hex didn't move"); + if (out.ok) out.steps.push(`New map: Explore as you go, home ${homeName} (${homeMix.join(", ")}), ${areaChip} (${areaMix.join(", ")}), start 1, 2`); + q(".duckmage-setup-actions .mod-cta")?.click(); + const made = await waitFor(() => p.settings.maps.find((m) => p.mapLabel(m.name) === "Smoke Explore"), 10000); + if (!made) { fail("the map wasn't made"); return out; } + await store.flush?.(); + await sleep(1200); + const map = p.getMap(made.name); + if (map.gridSize.cols !== 3 || map.gridSize.rows !== 3) fail(`size ${map.gridSize.cols}×${map.gridSize.rows}`); + if ((map.exploreRealms ?? []).length !== 2) fail(`explore-realms: ${JSON.stringify(map.exploreRealms)}`); + if (JSON.stringify(map.exploreWith) !== JSON.stringify(["(realms) -> terrain"])) fail(`explore-with: ${JSON.stringify(map.exploreWith)}`); + const startTerrain = store.get(made.name, "1_2")?.terrain; + if (!startTerrain) fail("start hex 1_2 is blank"); + // Not out at sea: the start is the biggest terrain the party can walk on. + const startColor = p.getPaletteOrPresetTerrains(map.paletteName).find((t) => t.name === startTerrain); + if (startColor && (startColor.impassable ?? /water/.test(startColor.type ?? ""))) fail(`the party starts on ${startTerrain} (impassable)`); + // The start is land the home area holds (its hidden tile, as New map's Land line says). + if (startTerrain && !homeMix.includes(startTerrain)) fail(`the start's ${startTerrain} isn't in the home land the form named (${homeMix.join(", ")})`); + const note = await app.vault.adapter.read(store.notePath(made.name)); + if (!/^explore-realms:/m.test(note)) fail("the map note has no explore-realms"); + // HF10: hexes reveal the areas' hidden generated land (every terrain the + // generators make, not only the mix's top few): palette terrains only. + const palette = new Set(p.getPaletteOrPresetTerrains(map.paletteName).map((t) => t.name)); + const bad = [...store.all(made.name)].filter(([, h]) => h.terrain && !palette.has(h.terrain)).map(([k, h]) => `${k} ${h.terrain}`); + if (bad.length) fail(`terrain not in the palette: ${bad.join(", ")}`); + if (out.ok) out.steps.push(`made ${made.name}: 3×3, 2 areas, 1_2 ${startTerrain}, ${[...store.all(made.name)].filter(([, h]) => h.terrain).length} hexes seen`); + // Play: five steps north. + await waitFor(() => view.activeMapName === made.name, 4000); + if (view.activeMapName !== made.name) { await p.showMap(made.name); await sleep(800); } + view.setWorkMode("play"); + await sleep(400); + const partyNow = () => { view.tokens.loadTokensForMap(); return view.tokens.tokenEntries.find((t) => t.party); }; + if (partyNow()?.hex !== "1_2") fail(`party on ${partyNow()?.hex}`); + const rows0 = map.gridSize.rows; + const walked = []; + for (let i = 0; i < 5; i++) { + const t = partyNow(); + if (!t) { fail("no party"); break; } + const [x, y] = t.hex.split("_").map(Number); + await view.tokens.moveParty(t, `${x}_${y - 1}`); + await sleep(600); + walked.push(`${x}_${y - 1} ${store.get(made.name, `${x}_${y - 1}`)?.terrain ?? "?"}`); + } + const blank = walked.filter((w) => / \?$/.test(w)); + if (blank.length) fail(`steps left blank: ${blank.join(", ")}`); + const outside = [...store.all(made.name)].filter(([, h]) => h.terrain && !palette.has(h.terrain)).map(([k, h]) => `${k} ${h.terrain}`); + if (outside.length) fail(`after the walk, terrain not in the palette: ${outside.join(", ")}`); + // The GM's peek (HF10): Peek → Show tints the blank hexes with their hidden land, never a filled one. + p.getMap(made.name).explorePeek = "on"; + p.refreshHexMap(); + const peeked = await waitFor(() => { const els = [...view.containerEl.querySelectorAll(".duckmage-hex.duckmage-hex-peek")]; return els.length ? els : null; }, 10000); + if (!peeked) fail("peek on: no blank hex shows its hidden land"); + else { + const labels = peeked.map((el) => (el.getAttribute("aria-label") ?? "").replace(/^Hidden: /, "")); + const wrong = labels.filter((t) => !palette.has(t)); + if (wrong.length) fail(`peek shows terrain not in the palette: ${[...new Set(wrong)].join(", ")}`); + const onFilled = peeked.filter((el) => store.get(made.name, `${el.dataset.x}_${el.dataset.y}`)?.terrain); + if (onFilled.length) fail(`peek tints ${onFilled.length} filled hexes`); + if (out.ok) out.steps.push(`peek: ${peeked.length} blank hexes show hidden land (${[...new Set(labels)].slice(0, 4).join(", ")})`); + } + delete p.getMap(made.name).explorePeek; + p.refreshHexMap(); + await sleep(600); + // Owner addition (HF11): Sees 2 on the party bar, then a click on the party's own hex: ring 2 filled, the token unmoved. + { + const t = partyNow(); + const grid = () => view.containerEl.querySelector(".duckmage-hex-map-grid"); + const tokEl = await waitFor(() => grid()?.querySelector(".duckmage-token.is-party")); + if (tokEl && !grid().querySelector(".duckmage-token.is-party.is-selected")) { + const r = tokEl.getBoundingClientRect(); + const at = { bubbles: true, cancelable: true, button: 0, clientX: r.x + r.width / 2, clientY: r.y + r.height / 2 }; + tokEl.dispatchEvent(new MouseEvent("mousedown", at)); + tokEl.ownerDocument.dispatchEvent(new MouseEvent("mouseup", at)); + } + const sees2 = await waitFor(() => view.containerEl.querySelector('.duckmage-party-controls button[aria-label="Sees 2"]')); + if (!t || !sees2) fail(`no ${t ? "Sees 2 on the party bar" : "party"}`); + else { + sees2.click(); + await sleep(300); + const [x, y] = t.hex.split("_").map(Number); + const hexOf = (k) => { const [a, b] = k.split("_"); return grid()?.querySelector(`.duckmage-hex[data-x="${a}"][data-y="${b}"]`); }; + const stagger = p.getMap(made.name).staggerOffset ?? p.settings.staggerOffset ?? "odd"; + const flat = p.settings.hexOrientation === "flat"; + const near = (k) => { + const [a, b] = k.split("_").map(Number); + const sh = (n) => (stagger === "odd" ? n % 2 !== 0 : n % 2 === 0); + const d = flat + ? (!sh(a) ? [[0, -1], [0, 1], [1, -1], [1, 0], [-1, -1], [-1, 0]] : [[0, -1], [0, 1], [1, 0], [1, 1], [-1, 0], [-1, 1]]) + : (!sh(b) ? [[-1, 0], [1, 0], [-1, -1], [0, -1], [-1, 1], [0, 1]] : [[-1, 0], [1, 0], [0, -1], [1, -1], [0, 1], [1, 1]]); + return d.map(([dx, dy]) => `${a + dx}_${b + dy}`); + }; + const ring2 = () => { const seen = new Set([t.hex]); let edge = [t.hex]; for (let i = 0; i < 2; i++) { const nx = []; for (const k of edge) for (const n of near(k)) if (!seen.has(n)) { seen.add(n); nx.push(n); } edge = nx; } return [...seen].filter((k) => hexOf(k)); }; + const visited = JSON.stringify(p.getMap(made.name).visited ?? null); + const own = hexOf(t.hex); + view.contentEl.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true, button: 0 })); + own?.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true, button: 0 })); + await waitFor(() => ring2().every((k) => store.get(made.name, k)?.terrain), 8000); + const blankLeft = ring2().filter((k) => !store.get(made.name, k)?.terrain); + if (blankLeft.length) fail(`look from ${t.hex} with Sees 2: still blank ${blankLeft.slice(0, 5).join(", ")}`); + if (partyNow()?.hex !== t.hex) fail(`the party moved on a look: ${t.hex} → ${partyNow()?.hex}`); + if (JSON.stringify(p.getMap(made.name).visited ?? null) !== visited) fail("a look marked a visit"); + if (p.getMap(made.name).exploreReveal !== "2 rings") fail(`Sees 2 stored ${p.getMap(made.name).exploreReveal}`); + if (out.ok) out.steps.push(`Sees 2 + click on the party's hex ${x}_${y}: ${ring2().length} hexes within 2 rings filled, token unmoved`); + } + } + if (p.getMap(made.name).gridSize.rows <= rows0) fail(`the map didn't grow (rows ${p.getMap(made.name).gridSize.rows})`); + const areaBtn = view.containerEl.querySelector(".duckmage-party-controls")?.textContent ?? ""; + if (out.ok) out.steps.push(`walked north: ${walked.join(", ")}; rows ${rows0} → ${p.getMap(made.name).gridSize.rows}${areaBtn ? `; party controls: ${areaBtn.trim().slice(0, 60)}` : ""}`); + view.setWorkMode("build"); + await p.saveSettings(); + await store.flush?.(); + await sleep(500); + return out; +} + +/** + * C10c Explore a finished map with fog of war (HF11). On map `mapName`, in + * Play, through the real UI: the hex menu's "Start exploring from here…" + * (the dialog: Party sees 1, a new party token), then the fog: hidden hexes + * dark with no labels, no other tokens; three steps reveal the sight; Sees 2 + * and a click on the party's own hex reveal ring 2 with the token unmoved + * (owner addition); Peek draws the hidden hexes faded; the GM reveals one + * distant hex (only that hex); the Reveal hexes brush reveals a stroke as + * one undo; Stop lifts the fog. No map data (hexes, the map note's tables) + * changes. Render time with and without fog is measured (median of `runs`). + */ +export async function exploreFog(id, mapName, opts = {}) { + const app = window.app; + const p = app.plugins.plugins[id]; + const store = p.mapStore; + const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); + const waitFor = async (fn, ms = 6000) => { const t0 = performance.now(); while (performance.now() - t0 < ms) { const v = fn(); if (v) return v; await sleep(100); } return fn(); }; + const out = { ok: true, steps: [], problems: [], bench: {} }; + const fail = (m) => { out.ok = false; out.problems.push(m); }; + const kinds = p.moduleGenerators({ toPaths: () => ({ paths: [], missing: [] }), procGrid: (g) => ({ ...g, orientation: p.settings.hexOrientation }) }); + if (!kinds.some((k) => k.id === "procedural:hex-flower")) return { ok: true, skipped: "the hexflower slice isn't in this build", steps: [], problems: [] }; + const map0 = p.getMap(mapName); + if (!map0) return { ok: false, steps: [], problems: [`no map ${mapName}`] }; + const modeBefore = map0.workMode; + const canonHexes = () => JSON.stringify([...store.all(mapName)].sort(([a], [b]) => (a < b ? -1 : 1))); + const tables = async () => { const t = (await store.readNoteText?.(mapName)) ?? ""; return t.slice(t.indexOf("\n## ")); }; + const hexesBefore = canonHexes(); + const tablesBefore = await tables(); + await p.showMap(mapName); + await sleep(1200); + const view = app.workspace.getLeavesOfType("duckmage-hex-map")[0]?.view; + if (!view || view.activeMapName !== mapName) { fail(`map view did not open ${mapName}`); return out; } + // Shown and in front: the brush is hit-tested where the pointer is. + // A hidden sandbox window can start 1×1: give it a size (it stays on the hidden desktop). + if (innerWidth < 600) { try { window.require("@electron/remote").getCurrentWindow().setSize(1280, 900); } catch { /* not Electron */ } await sleep(800); } + // Nothing over the map (an upgrade report left open, say): a pointer lands on what's on top. + document.querySelectorAll(".modal-container .modal-close-button").forEach((b) => b.click()); + // The throwaway sandbox's "trust the author" prompt has no close button: take it off the page (never answered). + document.querySelectorAll(".modal-container").forEach((c) => { if (/trust the author/i.test(c.querySelector(".modal-title")?.textContent ?? "")) c.remove(); }); + await sleep(300); + app.workspace.leftSplit?.collapse?.(); + app.workspace.rightSplit?.collapse?.(); + await app.workspace.revealLeaf(view.leaf); + app.workspace.setActiveLeaf(view.leaf, { focus: true }); + view.setWorkMode("play"); + await sleep(600); + const grid = () => view.containerEl.querySelector(".duckmage-hex-map-grid"); + const hexEl = (k) => { const [x, y] = k.split("_"); return grid()?.querySelector(`.duckmage-hex[data-x="${x}"][data-y="${y}"]`); }; + const fogged = () => new Set([...(grid()?.querySelectorAll(".duckmage-hex-fogged") ?? [])].map((el) => `${el.dataset.x}_${el.dataset.y}`)); + const total = () => grid()?.querySelectorAll(".duckmage-hex[data-x]").length ?? 0; + const stagger = map0.staggerOffset ?? p.settings.staggerOffset ?? "odd"; + const flat = p.settings.hexOrientation === "flat"; + const near = (k) => { + const [x, y] = k.split("_").map(Number); + const sh = (n) => (stagger === "odd" ? n % 2 !== 0 : n % 2 === 0); + const d = flat + ? (!sh(x) ? [[0, -1], [0, 1], [1, -1], [1, 0], [-1, -1], [-1, 0]] : [[0, -1], [0, 1], [1, 0], [1, 1], [-1, 0], [-1, 1]]) + : (!sh(y) ? [[-1, 0], [1, 0], [-1, -1], [0, -1], [-1, 1], [0, 1]] : [[-1, 0], [1, 0], [0, -1], [1, -1], [0, 1], [1, 1]]); + return d.map(([dx, dy]) => `${x + dx}_${y + dy}`).filter((n) => !!hexEl(n)); + }; + const sight = (c, r) => { const seen = new Set([c]); let edge = [c]; for (let i = 0; i < r; i++) { const nx = []; for (const k of edge) for (const n of near(k)) if (!seen.has(n)) { seen.add(n); nx.push(n); } edge = nx; } return seen; }; + const press = (el) => { + const r = el.getBoundingClientRect(); + const at = { bubbles: true, cancelable: true, button: 0, clientX: r.x + r.width / 2, clientY: r.y + r.height / 2 }; + el.dispatchEvent(new MouseEvent("mousedown", at)); + el.ownerDocument.dispatchEvent(new MouseEvent("mouseup", at)); + }; + const click = (el) => { + view.contentEl.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true, button: 0 })); + el.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true, button: 0 })); + }; + const menuItem = async (k, title) => { + const el = hexEl(k); + if (!el) return false; + const r = el.getBoundingClientRect(); + el.dispatchEvent(new MouseEvent("contextmenu", { bubbles: true, cancelable: true, button: 2, clientX: r.x + r.width / 2, clientY: r.y + r.height / 2 })); + const item = await waitFor(() => [...document.querySelectorAll(".menu .menu-item")].find((i) => i.querySelector(".menu-item-title")?.textContent === title), 2000); + if (!item) { document.body.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true })); document.querySelector(".menu")?.remove(); return false; } + item.click(); + await sleep(300); + return true; + }; + const barButton = (label) => view.containerEl.querySelector(`.duckmage-party-controls button[aria-label="${label}"]`); + const seen = () => { + const s = new Set(); + for (const row of p.getMap(mapName).exploreSeen ?? []) { + const m = /^(-?\d+)\s*:\s*(.*)$/.exec(row); + if (!m) continue; + for (const part of m[2].split(",")) { + const r = /^\s*(-?\d+)\s*(?:-\s*(-?\d+))?\s*$/.exec(part); + if (r) for (let x = Number(r[1]); x <= Number(r[2] ?? r[1]); x++) s.add(`${x}_${Number(m[1])}`); + } + } + return s; + }; + const bench = (n) => { + const t = []; + for (let i = 0; i < n; i++) { + const t0 = performance.now(); + view.renderGrid(); + void document.body.offsetHeight; + t.push(performance.now() - t0); + } + t.sort((a, b) => a - b); + return Math.round(t[Math.floor(t.length / 2)]); + }; + const runs = opts.runs ?? 5; + try { + out.bench.noFog = bench(runs); + // Start exploring from the middle, through the hex menu and its dialog. + const o = map0.gridOffset ?? { x: 0, y: 0 }; + const start = opts.start ?? `${o.x + Math.floor(map0.gridSize.cols / 2)}_${o.y + Math.floor(map0.gridSize.rows / 2)}`; + if (!(await menuItem(start, "Start exploring from here…"))) { fail(`no "Start exploring from here…" on ${start}`); return out; } + const modal = await waitFor(() => document.querySelector(".modal.duckmage-start-exploring, .duckmage-start-exploring")?.closest(".modal")); + if (!modal) { fail("Start exploring didn't open its dialog"); return out; } + const startInput = modal.querySelector("#duckmage-explore-start"); + if (startInput?.value.replace(/\s/g, "") !== start.replace("_", ",")) fail(`the dialog starts at ${startInput?.value}, not ${start}`); + [...modal.querySelectorAll(".duckmage-explore-sees button")].find((b) => b.textContent === "1")?.click(); + const tokenSel = modal.querySelector("#duckmage-explore-token"); + if (tokenSel) { tokenSel.value = ""; tokenSel.dispatchEvent(new Event("change", { bubbles: true })); } + const reset = modal.querySelector("#duckmage-explore-reset"); + if (reset) { reset.value = "reset"; reset.dispatchEvent(new Event("change", { bubbles: true })); } + modal.querySelector(".mod-cta")?.click(); + await waitFor(() => p.getMap(mapName).exploreFog === "on" && fogged().size > 0, 8000); + await sleep(800); + const m = p.getMap(mapName); + if (m.exploreFog !== "on") { fail("the fog isn't on"); return out; } + const want = sight(start, 1); + const s0 = seen(); + if ([...want].some((k) => !s0.has(k)) || s0.size !== want.size) fail(`seen after start: ${s0.size} (want ${want.size} around ${start})`); + const f0 = fogged(); + if (f0.size !== total() - want.size) fail(`fogged ${f0.size} of ${total()} (want ${total() - want.size})`); + if ([...want].some((k) => f0.has(k))) fail("a hex in sight is fogged"); + // Nothing of a hidden hex's own: no coordinate label, no other token, no name. + const labels = [...(grid()?.querySelectorAll(".duckmage-coord-label-html") ?? [])].map((l) => l.textContent.replace(",", "_")); + const leaked = labels.filter((k) => f0.has(k)); + if (leaked.length) fail(`coordinates shown on hidden hexes: ${leaked.slice(0, 5).join(", ")}`); + view.tokens.loadTokensForMap(); + const party = view.tokens.tokenEntries.find((t) => t.party && t.hex === start); + if (!party) { fail(`no party token on ${start}`); return out; } + const others = view.tokens.tokenEntries.filter((t) => !t.party && t.visible && f0.has(t.hex)); + const drawnOthers = others.filter((t) => [...grid().querySelectorAll(".duckmage-token")].some((el) => el.title === t.title)); + if (drawnOthers.length) fail(`tokens drawn on hidden hexes: ${drawnOthers.map((t) => t.title).join(", ")}`); + out.bench.fog = bench(runs); + if (opts.benchOnly) { + out.steps.push(`${mapName} (${total()} hexes): render ${out.bench.noFog} ms → ${out.bench.fog} ms with fog (median of ${runs}); ${f0.size} fogged`); + if (!(await menuItem(start, "Stop exploring"))) fail("no Stop exploring in the hex menu"); + await waitFor(() => !p.getMap(mapName).exploreFog, 3000); + if (p.getMap(mapName).exploreFog) fail("Stop exploring left the fog on"); + return out; + } + out.steps.push(`started at ${start}: ${s0.size} hexes seen, ${f0.size} fogged; ${others.length} other tokens hidden; render ${out.bench.noFog} ms → ${out.bench.fog} ms with fog (median of ${runs})`); + // Three steps: each reveals the ring around the hex entered. + const pick = async () => { + // Our party's token (the vault may hold other parties). + // The token on the party's hex with its title (the vault may hold other parties, even of the same name). + const now = () => { view.tokens.loadTokensForMap(); return view.tokens.tokenEntries.find((t) => t.filePath === party.filePath)?.hex; }; + const mine = () => { const [x, y] = (now() ?? "").split("_"); const c = hexEl(`${x}_${y}`)?.getBoundingClientRect(); return [...(grid()?.querySelectorAll(".duckmage-token.is-party") ?? [])].filter((el) => el.title === `${party.title} (party)`).sort((a, b) => { const d = (el) => { const r = el.getBoundingClientRect(); return Math.hypot(r.x + r.width / 2 - (c?.x ?? 0) - (c?.width ?? 0) / 2, r.y + r.height / 2 - (c?.y ?? 0) - (c?.height ?? 0) / 2); }; return d(a) - d(b); })[0]; }; + const t = await waitFor(mine); + if (view.tokens.selectedParty !== party.filePath) { + if (t && t.classList.contains("is-selected")) press(t); + if (t) press(t); + await sleep(400); + } + if (view.tokens.selectedParty !== party.filePath) fail(`pressing the party token didn't select it (${t ? "pressed" : "no token element"}; selected ${view.tokens.selectedParty})`); + await sleep(300); + return [...grid().querySelectorAll(".duckmage-hex.duckmage-party-step")]; + }; + let at = start; + const walked = []; + for (let i = 0; i < 3; i++) { + const lit = await pick(); + const to = lit.map((el) => `${el.dataset.x}_${el.dataset.y}`).find((k) => k !== at && [...near(k)].some((n) => !seen().has(n))) ?? (lit[0] && `${lit[0].dataset.x}_${lit[0].dataset.y}`); + if (!to) { fail("no hex lit to step to"); break; } + click(hexEl(to)); + await waitFor(() => [...sight(to, 1)].every((k) => seen().has(k)), 4000); + if ([...sight(to, 1)].some((k) => !seen().has(k) || fogged().has(k))) fail(`step to ${to}: its ring isn't revealed`); + at = to; + walked.push(to); + await sleep(400); + } + out.steps.push(`walked ${walked.join(" → ")}: ${seen().size} seen`); + // Owner addition: Sees 2, then the party's own hex: ring 2 revealed, the token stays. + await pick(); + const sees2 = barButton("Sees 2"); + if (!sees2) fail("no Sees 2 on the party bar"); + else { + sees2.click(); + await sleep(300); + if (p.getMap(mapName).exploreReveal !== "2 rings") fail(`Sees 2 stored ${p.getMap(mapName).exploreReveal}`); + if (barButton("Sees 2")?.getAttribute("aria-pressed") !== "true") fail("Sees 2 isn't shown selected"); + const visited = JSON.stringify(p.getMap(mapName).visited ?? null); + const undoBefore = p.undoBook?.size(mapName, "play")?.undo; + click(hexEl(at)); + await waitFor(() => [...sight(at, 2)].every((k) => seen().has(k)), 4000); + const missing = [...sight(at, 2)].filter((k) => !seen().has(k)); + if (missing.length) fail(`look from ${at}: ring 2 not revealed (${missing.slice(0, 4).join(", ")})`); + view.tokens.loadTokensForMap(); + const still = view.tokens.tokenEntries.find((t) => t.filePath === party.filePath)?.hex; + if (still !== at) fail(`the party moved on a look: ${at} → ${still}`); + if (JSON.stringify(p.getMap(mapName).visited ?? null) !== visited) fail("a look marked a visit"); + await sleep(500); + const undoAfter = p.undoBook?.size(mapName, "play")?.undo; + if (typeof undoBefore === "number" && undoAfter !== undoBefore + 1) fail(`a look made ${undoAfter - undoBefore} undo entries`); + out.steps.push(`Sees 2 + click on the party's hex ${at}: ring 2 revealed (${sight(at, 2).size} hexes), token unmoved`); + } + // Peek: hidden hexes drawn faded. + const peekBtn = barButton("Peek Show"); + if (!peekBtn) fail("no Peek on the party bar"); + else { + peekBtn.click(); + await sleep(600); + const faded = grid()?.querySelectorAll(".duckmage-hex-fogged.duckmage-hex-peek").length ?? 0; + if (!faded) fail("Peek: no hidden hex drawn faded"); + barButton("Peek Hide")?.click(); + await sleep(400); + out.steps.push(`peek: ${faded} hidden hexes faded`); + } + // The GM reveals one distant hex: only that one. + const far = [...fogged()].filter((k) => near(k).every((n) => !seen().has(n)))[0]; + if (!far) fail("no distant hidden hex to reveal"); + else { + const before = seen(); + if (!(await menuItem(far, "Reveal this hex"))) fail(`no "Reveal this hex" on ${far}`); + await waitFor(() => seen().has(far), 3000); + const added = [...seen()].filter((k) => !before.has(k)); + if (added.length !== 1 || added[0] !== far) fail(`reveal ${far}: revealed ${added.join(", ")}`); + if (fogged().has(far)) fail(`${far} is still drawn fogged`); + if (near(far).some((n) => !fogged().has(n))) fail(`a neighbour of ${far} was revealed too`); + if (!(await menuItem(far, "Hide again"))) fail(`no "Hide again" on ${far}`); + await waitFor(() => !seen().has(far), 3000); + if (seen().has(far)) fail(`Hide again left ${far} revealed`); + out.steps.push(`GM revealed only ${far}, then hid it again`); + } + // The Reveal hexes brush: a press and drag over two hidden hexes, one undo. + await pick(); + const pickBtn = barButton("Reveal hexes Pick"); + // Two neighbouring hidden hexes, both on screen (a drag is hit-tested where the pointer is). + const clip = grid().closest(".duckmage-hex-map-clip").getBoundingClientRect(); + const onScreen = (k) => { const r = hexEl(k)?.getBoundingClientRect(); if (!r) return false; const cx = r.left + r.width / 2, cy = r.top + r.height / 2; return cx > clip.left + 2 && cx < clip.right - 2 && cy > clip.top + 2 && cy < clip.bottom - 2 && view.hexElAt(document.elementFromPoint(cx, cy), cx, cy) === hexEl(k); }; + const pair = [...fogged()].filter(onScreen).map((k) => [k, near(k).find((n) => fogged().has(n) && onScreen(n))]).find(([, n]) => n); + if (!pickBtn || !pair) fail(`brush: ${pickBtn ? `no pair of hidden hexes on screen (${fogged().size} hidden, ${(() => { const inClip = [...fogged()].filter((k) => { const r = hexEl(k).getBoundingClientRect(); const cx = r.left + r.width / 2, cy = r.top + r.height / 2; return cx > clip.left && cx < clip.right && cy > clip.top && cy < clip.bottom; }); const k = inClip[0]; if (!k) return "none in the clip"; const r = hexEl(k).getBoundingClientRect(); const at = document.elementFromPoint(r.left + r.width / 2, r.top + r.height / 2); return `${inClip.length} in the clip; modals: ${[...document.querySelectorAll(".modal")].map((m) => m.querySelector(".modal-title")?.textContent || m.className).join(" | ")}; ${k} hit ${at?.className} → ${view.hexElAt(at, r.left + r.width / 2, r.top + r.height / 2)?.dataset.x}`; })()}, clip ${Math.round(clip.width)}×${Math.round(clip.height)}, window ${innerWidth}×${innerHeight})` : "no Reveal hexes Pick"}`); + else { + pickBtn.click(); + await sleep(200); + if (view.drawingMode !== "hexBrush") fail(`the brush isn't on (${view.drawingMode})`); + const before = seen(); + const [a, b] = pair.map(hexEl); + const ra = a.getBoundingClientRect(), rb = b.getBoundingClientRect(); + a.dispatchEvent(new MouseEvent("mousedown", { bubbles: true, cancelable: true, button: 0, clientX: ra.x + ra.width / 2, clientY: ra.y + ra.height / 2 })); + document.dispatchEvent(new MouseEvent("mousemove", { bubbles: true, clientX: rb.x + rb.width / 2, clientY: rb.y + rb.height / 2 })); + document.dispatchEvent(new MouseEvent("mouseup", { bubbles: true, clientX: rb.x + rb.width / 2, clientY: rb.y + rb.height / 2 })); + await waitFor(() => pair.every((k) => seen().has(k)), 3000); + const added = [...seen()].filter((k) => !before.has(k)).sort(); + if (added.join() !== [...pair].sort().join()) fail(`brush stroke over ${pair.join(", ")} revealed ${added.join(", ")}`); + await view.undo(); + await sleep(600); + if (pair.some((k) => seen().has(k))) fail("one undo didn't take the whole stroke back"); + view.exitCurrentMode(); + await sleep(200); + if (view.drawingMode !== null) fail("the brush didn't stop"); + out.steps.push(`brush: ${pair.join(" + ")} in one stroke, one undo`); + } + // Stop lifts the fog; what was seen is kept. + const stop = barButton("Exploring Stop"); + if (!stop) fail("no Stop on the party bar"); + else { + const kept = seen().size; + stop.click(); + await waitFor(() => !p.getMap(mapName).exploreFog && fogged().size === 0, 3000); + if (fogged().size) fail(`Stop left ${fogged().size} hexes fogged (explore-fog ${p.getMap(mapName).exploreFog}, bar ${!!view.containerEl.querySelector(".duckmage-party-controls")})`); + if (seen().size !== kept) fail("Stop dropped what was seen"); + out.steps.push(`stopped: fog lifted, ${kept} seen kept`); + } + await p.saveSettings(); + await store.flush?.(); + await sleep(400); + if (canonHexes() !== hexesBefore) fail("map data (hexes) changed while exploring"); + if ((await tables()) !== tablesBefore) fail("the map note's tables changed while exploring"); + } catch (e) { + fail(String(e?.stack ?? e).slice(0, 400)); + } finally { + view.tokens.selectParty?.(null); + view.setWorkMode(modeBefore ?? "build"); + await p.saveSettings(); + await store.flush?.(); + } + return out; +} diff --git a/dev/smoke/lib/obsidian.mjs b/dev/smoke/lib/obsidian.mjs new file mode 100644 index 00000000..474365e6 --- /dev/null +++ b/dev/smoke/lib/obsidian.mjs @@ -0,0 +1,149 @@ +/** + * Sandboxed Obsidian for the smoke suite: wraps the fresh-eyes tester's + * sandbox.mjs (create / launch / stop) and its CDP helpers. + * + * SAFETY: every sandbox lives in its own run folder with its own Electron + * profile; `stop` kills only processes whose command line holds that + * profile path. Before anything runs in a page, the open vault is checked + * to be the run's own vault. + */ +import fs from "node:fs"; +import path from "node:path"; +import { execFile, execFileSync } from "node:child_process"; +import { pathToFileURL } from "node:url"; +import { stopUntilGone } from "./concurrency.mjs"; + +/** A default written as a Windows path, as this machine sees it: C:/… is /mnt/c/… on Linux. */ +export const hostPath = (p) => (process.platform === "linux" ? p.replace(/^([A-Za-z]):[\\/]/, (_m, d) => `/mnt/${d.toLowerCase()}/`) : p); + +export const TOOLS_DIR = process.env.UX_TOOLS_DIR + ?? process.env.UX_SANDBOX_DIR + ?? hostPath("C:/Users/markr/work/tools/skills-share/ux-testing/fresh-eyes-tester/scripts"); +export const SANDBOX = path.join(TOOLS_DIR, "sandbox.mjs"); + +let commonMod = null; +export async function common() { + if (!commonMod) commonMod = await import(pathToFileURL(path.join(TOOLS_DIR, "lib", "common.mjs")).href); + return commonMod; +} + +export const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); + +/** Run sandbox.mjs; resolves its stdout (the last JSON object it printed) or rejects with its stderr. */ +function sandbox(args, { timeout = 180_000 } = {}) { + return new Promise((resolve, reject) => { + execFile(process.execPath, [SANDBOX, ...args], { encoding: "utf8", timeout, maxBuffer: 16 << 20 }, (err, stdout, stderr) => { + if (err) { reject(new Error(`sandbox ${args[0]} failed: ${(stderr || err.message).trim().slice(-2000)}`)); return; } + const i = stdout.lastIndexOf("\n{"); + const json = stdout.slice(i >= 0 ? i + 1 : stdout.indexOf("{")); + try { resolve(JSON.parse(json)); } catch { resolve({ raw: stdout }); } + }); + }); +} + +export async function createSandbox({ pluginDir, seed, pluginData, name }) { + const args = ["create", "--plugin-dir", pluginDir, "--name", name]; + if (seed) args.push("--seed", seed); + if (pluginData) args.push("--plugin-data", pluginData); + return sandbox(args); +} + +export const launchSandbox = (runDir) => sandbox(["launch", "--run", runDir, "--width", "1400", "--height", "900"], { timeout: 240_000 }); +/** One stop (sandbox.mjs waits ~5 s for the processes to go). */ +export const stopSandboxOnce = (runDir) => sandbox(["stop", "--run", runDir], { timeout: 180_000 }); +/** + * Stop a run and keep at it (up to ~30 s more) while its processes are + * still there: on a busy machine an Electron can take a while to exit. + */ +export const stopSandbox = (runDir) => stopUntilGone(() => stopSandboxOnce(runDir), { attempts: 7, waitMs: 5000 }); + +/** + * Every Obsidian.exe process: { pid, main, cmd }. `main` = the browser + * (top) process; helpers carry `--type=`. Counting main processes is + * stable; helper processes come and go on their own. + */ +export function obsidianProcesses() { + if (process.platform === "linux") return linuxObsidianProcesses(); + const ps = "Get-CimInstance Win32_Process -Filter \"Name='Obsidian.exe'\" | ForEach-Object { [pscustomobject]@{ pid = $_.ProcessId; cmd = $_.CommandLine } } | ConvertTo-Json -Compress"; + const out = execFileSync("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", ps], { encoding: "utf8" }).trim(); + if (!out) return []; + const list = [].concat(JSON.parse(out)); + return list.map((p) => ({ pid: p.pid, cmd: p.cmd ?? "", main: !/--type=/.test(p.cmd ?? "") })); +} + +/** + * A connected sandbox page with console capture. A fresh CDP session's + * Runtime.enable replays the messages logged before it attached, so errors + * thrown while the plugin loaded (before we connected) are caught too. + */ +export async function connectPage(runDir) { + const c = await common(); + const run = c.readRun(runDir); + const { browser, page } = await c.connect(run); + const base = await c.assertSandboxVault(page, run); + if (!base || !c.samePath(base, run.vault)) { + browser.disconnect(); + throw new Error(`SAFETY: open vault ${base} is not the sandbox vault ${run.vault}`); + } + const log = []; + const session = await page.createCDPSession(); + session.on("Runtime.consoleAPICalled", (e) => { + if (e.type !== "error" && e.type !== "warning" && e.type !== "assert") return; + const text = e.args.map((a) => a.value ?? a.description ?? a.unserializableValue ?? "").join(" "); + const frames = (e.stackTrace?.callFrames ?? []).map((f) => f.url).join(" "); + log.push({ level: e.type === "warning" ? "warning" : "error", text: text.slice(0, 2000), where: frames.slice(0, 500), ts: e.timestamp }); + }); + session.on("Runtime.exceptionThrown", (e) => { + const d = e.exceptionDetails; + const text = d.exception?.description ?? d.text ?? "exception"; + const frames = (d.stackTrace?.callFrames ?? []).map((f) => f.url).join(" ") + " " + (d.url ?? ""); + log.push({ level: "pageerror", text: String(text).slice(0, 2000), where: frames.slice(0, 500), ts: d.timestamp }); + }); + await session.send("Runtime.enable"); + page.setDefaultTimeout(600_000); + return { + run, browser, page, log, + async close() { + try { await session.detach(); } catch { /* gone */ } + browser.disconnect(); + }, + }; +} + +/** Errors that belong to this plugin (its code, its id or its name in the text or stack). */ +export function pluginErrors(log, pluginId) { + const mine = new RegExp(`plugin:${pluginId}|hexmaker|hexmap world creator|duckmage`, "i"); + return log.filter((e) => e.level !== "warning" && (mine.test(e.text) || mine.test(e.where))); +} + +/** Screenshot to the run's shots folder; never throws. */ +export async function shot(page, runDir, name) { + try { + const file = path.join(runDir, "shots", `${name}.png`); + fs.mkdirSync(path.dirname(file), { recursive: true }); + await page.screenshot({ path: file }); + return file; + } catch { return null; } +} + +/** + * Linux (the Flathub build): the Obsidian processes from /proc. `main` is + * the Electron browser process (the obsidian binary without `--type=`); + * the Flatpak sandbox (bwrap) and launcher script around it are listed + * but not main, so a count of main processes means the same as on Windows. + */ +function linuxObsidianProcesses() { + const out = []; + for (const d of fs.readdirSync("/proc")) { + if (!/^\d+$/.test(d) || Number(d) === process.pid) continue; + let argv; + try { argv = fs.readFileSync(`/proc/${d}/cmdline`, "utf8").split("\0").filter(Boolean); } catch { continue; } + const prog = path.basename(argv[0] ?? ""); + const app = prog === "obsidian" || prog === "Obsidian"; + const wrapper = prog === "obsidian.sh" || ((prog === "bwrap" || prog === "flatpak") && argv.some((a) => a === "md.obsidian.Obsidian" || a === "obsidian.sh")); + if (!app && !wrapper) continue; + const cmd = argv.join(" "); + out.push({ pid: Number(d), cmd, main: app && !/--type=/.test(cmd) }); + } + return out; +} diff --git a/dev/smoke/lib/page.mjs b/dev/smoke/lib/page.mjs new file mode 100644 index 00000000..77e57d1b --- /dev/null +++ b/dev/smoke/lib/page.mjs @@ -0,0 +1,667 @@ +/** + * Functions evaluated INSIDE the sandboxed Obsidian (page.evaluate). Each + * must be self-contained: no imports, no closure over module scope; only + * `window.app` and its arguments. They drive the plugin the way its own + * UI does (the map view's mouse handlers, its path tool, its undo), and + * reach into private fields only to pick a tool without clicking through a + * picker modal. + */ + +/** Wait until the plugin's stores are loaded; installs a vault-write tracker. */ +export async function waitReady(id, timeoutMs) { + const t0 = Date.now(); + const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); + const app = window.app; + if (!window.__smoke) { + window.__smoke = { lastWrite: Date.now(), writes: [] }; + const note = (kind) => (f, old) => { + window.__smoke.lastWrite = Date.now(); + if (window.__smoke.writes.length < 5000) window.__smoke.writes.push({ kind, path: f.path, old, t: Date.now() }); + }; + for (const k of ["modify", "create", "delete", "rename"]) app.vault.on(k, note(k)); + } + while (Date.now() - t0 < timeoutMs) { + const p = app.plugins.plugins[id]; + // A fresh install holds its stores' first writes until the setup wizard + // confirms the world folder (F19). Note what was written meanwhile + // (should be nothing), then go on as a user confirming would. + if (app.workspace.layoutReady && p?.startupWritesHeld) { + await sleep(1500); + window.__smoke.held = { held: true, writes: window.__smoke.writes.map((w) => w.path) }; + p.releaseStartupWrites(); + } + if (app.workspace.layoutReady && p?.mapStore?.isReady?.() && p.paletteStore?.isReady?.()) { + return { ready: true, ms: Date.now() - t0 }; + } + await sleep(250); + } + const p = app.plugins.plugins[id]; + return { ready: false, ms: Date.now() - t0, loaded: !!p, mapStore: !!p?.mapStore?.isReady?.(), palettes: !!p?.paletteStore?.isReady?.() }; +} + +/** + * Wait for the layout and the plugin only: a fresh install's stores stay + * held (F19) until the caller releases them (setups with prepHeld). + */ +export async function waitLayout(id, timeoutMs) { + const t0 = Date.now(); + const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); + const app = window.app; + while (Date.now() - t0 < timeoutMs) { + const p = app.plugins.plugins[id]; + if (app.workspace.layoutReady && p?.paletteStore) return { ready: true, ms: Date.now() - t0, held: !!p.startupWritesHeld }; + await sleep(250); + } + return { ready: false, ms: Date.now() - t0 }; +} + +/** Wait for `quietMs` with no vault writes (max `maxMs`), flushing the map store. */ +export async function settle(id, quietMs, maxMs) { + const t0 = Date.now(); + const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); + const p = window.app.plugins.plugins[id]; + for (;;) { + try { await p?.mapStore?.flush?.(); } catch { /* reported by C1 */ } + const quiet = Date.now() - (window.__smoke?.lastWrite ?? 0); + const busy = [...document.querySelectorAll(".notice")].some((n) => /moving map data|Indexing/i.test(n.textContent ?? "")); + if (quiet >= quietMs && !busy) return { ms: Date.now() - t0, quiet: true }; + if (Date.now() - t0 > maxMs) return { ms: Date.now() - t0, quiet: false }; + await sleep(250); + } +} + +/** Close modals (wizard nudges, prompts) so they don't swallow input. */ +export function closeModals() { + const n = document.querySelectorAll(".modal-container").length; + document.querySelectorAll(".modal-container .modal-close-button").forEach((b) => b.click()); + return n; +} + +/** Notices on screen now. */ +export function notices() { + return [...document.querySelectorAll(".notice")].map((n) => (n.textContent ?? "").trim()).filter(Boolean); +} + +/** The plugin's settings as the checks need them. */ +export function state(id) { + const app = window.app; + const p = app.plugins.plugins[id]; + const s = p.settings; + const seen = new Set(); + const maps = s.maps.filter((m) => !seen.has(m.name) && !!seen.add(m.name)).map((m) => ({ + name: m.name, + cols: m.gridSize?.cols, rows: m.gridSize?.rows, + overworld: !!m.regions, + submapKind: m.submapKind ?? null, + parent: m.parent?.map ?? null, + world: m.world ? `${m.world.cx},${m.world.cy}` : null, + workMode: m.workMode ?? null, + paletteName: m.paletteName, + paths: p.mapStore.paths(m.name)?.length ?? 0, + hexes: p.mapStore.all(m.name).size, + broken: !!p.mapStore.broken?.has?.(m.name), + missing: !!p.mapStore.isMissing?.(m.name), + noteExists: !!app.vault.getAbstractFileByPath(p.mapStore.notePath(m.name)), + notePath: p.mapStore.notePath(m.name), + // contextKinds since the module registry (P2); isSpaceMap on older builds. + space: !!(p.contextKinds ? p.contextKinds(m.name).has("space") : p.isSpaceMap?.(m.name)), + })); + return { + version: p.manifest.version, + mapKinds: s.mapKinds, + palettes: s.terrainPalettes.map((x) => x.name), + pathTypes: (s.pathTypes ?? []).length, + defaultMap: s.defaultMap, + setupComplete: !!s.setupComplete, + maps, + mapEntries: s.maps.length, + wizardOpen: app.workspace.getLeavesOfType("duckmage-setup-wizard").length, + commands: Object.keys(app.commands.commands).filter((c) => c.startsWith(id + ":")), + }; +} + +/** Every map's hex data from the store: { map: { "x_y": HexData } }. */ +export function dumpStore(id) { + const p = window.app.plugins.plugins[id]; + const out = {}; + const seen = new Set(); + for (const m of p.settings.maps) { + if (seen.has(m.name)) continue; + seen.add(m.name); + out[m.name] = {}; + for (const [k, h] of p.mapStore.all(m.name)) out[m.name][k] = h; + } + return out; +} + +/** Path counts per map and whether each map's paths resolve to hex chains. */ +export function pathState(id) { + const p = window.app.plugins.plugins[id]; + const out = {}; + const seen = new Set(); + for (const m of p.settings.maps) { + if (seen.has(m.name)) continue; + seen.add(m.name); + const paths = p.mapStore.paths(m.name) ?? []; + let resolved = null; + try { resolved = paths.length ? p.mapStore.resolved(m.name) : []; } catch (e) { resolved = "error: " + e; } + out[m.name] = { paths: paths.length, resolved: Array.isArray(resolved) ? resolved.length : resolved }; + } + return out; +} + +/** + * Open a map in the map view and wait for its hexes to render. + * Returns { ms, hexes, expected, canvas, active }. + */ +export async function openMap(id, name, timeoutMs) { + const app = window.app; + const p = app.plugins.plugins[id]; + const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); + const t0 = performance.now(); + await p.showMap(name); + const view = () => app.workspace.getLeavesOfType("duckmage-hex-map")[0]?.view; + let last = -1, stable = 0, hexes = 0; + while (performance.now() - t0 < timeoutMs) { + const v = view(); + const root = v?.containerEl; + hexes = root ? root.querySelectorAll(".duckmage-hex[data-x]").length : 0; + const canvas = root ? root.querySelectorAll("canvas").length : 0; + // A missing map (SM-DEL) shows its empty state instead of a grid. + if (v?.activeMapName === name && root?.querySelector(".duckmage-map-missing-state")) break; + if (v?.activeMapName === name && (hexes > 0 || canvas > 0)) { + if (hexes === last) stable++; else stable = 0; + if (stable >= 3) break; + } + last = hexes; + await sleep(100); + } + const v = view(); + const m = p.getMap(name); + return { + ms: Math.round(performance.now() - t0), + active: v?.activeMapName ?? null, + hexes, + expected: m ? m.gridSize.cols * m.gridSize.rows : null, + canvas: v?.containerEl?.querySelectorAll("canvas").length ?? 0, + workModeBtn: !!v?.containerEl?.querySelector(".duckmage-work-mode-btn"), + missingState: !!v?.containerEl?.querySelector(".duckmage-map-missing-state"), + }; +} + +/** Run a command by id; true if it ran (errors land in the console log). */ +export async function runCommand(cmdId) { + const ok = window.app.commands.executeCommandById(cmdId); + await new Promise((r) => setTimeout(r, 600)); + return ok; +} + +/** + * C6 round trip on `name`, through the map view's own mouse handler and + * undo: (a) paint a blank hex, check the map-note row, undo, row gone; + * (b) paint over a painted hex, undo, the old terrain is back; + * (c) reload the store from the note: same data as before. + */ +export async function paintRoundTrip(id, name) { + const app = window.app; + const p = app.plugins.plugins[id]; + const store = p.mapStore; + const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); + await p.showMap(name); + await sleep(800); + const view = app.workspace.getLeavesOfType("duckmage-hex-map")[0]?.view; + if (!view || view.activeMapName !== name) return { ok: false, error: "map view did not open " + name }; + const palette = p.getMapPalette(name).map((t) => t.name); + if (palette.length < 2) return { ok: true, skipped: "palette has fewer than 2 terrains" }; + const notePath = store.notePath(name); + const readNote = async () => ((await app.vault.adapter.exists(notePath)) ? app.vault.adapter.read(notePath) : null); + const rowFor = (text, key) => { + // The Hexes table writes "3_4"; people may write "3, 4". + const [x, y] = key.split("_"); + const re = new RegExp(`^\\|\\s*${x}(?:_|,\\s*)${y}\\s*\\|.*$`, "m"); + return text ? (re.exec(text)?.[0] ?? null) : null; + }; + const hexEls = [...view.containerEl.querySelectorAll(".duckmage-hex[data-x]")]; + const keyOf = (el) => `${el.dataset.x}_${el.dataset.y}`; + const blankEl = hexEls.find((el) => !store.get(name, keyOf(el))); + // Order-free: a reload may list hexes (and fields) in another order. + const canon = () => JSON.stringify([...store.all(name)].map(([k, h]) => [k, Object.fromEntries(Object.entries(h).sort())]).sort((a, b) => (a[0] < b[0] ? -1 : 1))); + const before = canon(); + const textBefore = await readNote(); + const paint = async (el, terrain) => { + view.leaveOtherToolFor?.("terrain"); + view.drawingMode = "terrain"; + view.isErasingMode = false; + view.terrainPickMode = false; + view.paintTerrainName = terrain; + view.paintBrushSize = 1; + el.scrollIntoView?.({ block: "center", inline: "center" }); + const r = el.getBoundingClientRect(); + const at = { bubbles: true, cancelable: true, button: 0, clientX: r.x + r.width / 2, clientY: r.y + r.height / 2 }; + el.dispatchEvent(new MouseEvent("mousedown", at)); + el.ownerDocument.dispatchEvent(new MouseEvent("mouseup", at)); + await view.terrainWritesSettled?.(); + await store.flush(); + }; + const undo = async () => { + await view.undo(); + await view.terrainWritesSettled?.(); + await store.flush(); + }; + const out = { ok: true, steps: [], problems: [] }; + const fail = (m) => { out.ok = false; out.problems.push(m); }; + // (a) blank hex + if (!blankEl) out.steps.push("no blank hex on this map"); + else { + const key = keyOf(blankEl); + const t1 = palette[0]; + await paint(blankEl, t1); + const got = store.get(name, key)?.terrain; + if (got !== t1) fail(`paint ${key}: store has ${got}, wanted ${t1}`); + const row = rowFor(await readNote(), key); + if (!row || !row.includes(t1)) fail(`paint ${key}: map note row missing or wrong: ${row}`); + await undo(); + if (store.get(name, key)?.terrain) fail(`undo ${key}: store still has ${store.get(name, key)?.terrain}`); + if (rowFor(await readNote(), key)) fail(`undo ${key}: map note row still there`); + out.steps.push(`blank ${key}: painted ${t1}, undone`); + } + // (b) painted hex: the one painted before, or paint one first (and undo that too) + let paintedEl = hexEls.find((el) => store.get(name, keyOf(el))?.terrain && palette.includes(store.get(name, keyOf(el)).terrain)); + let seeded = false; + if (!paintedEl && blankEl) { + await paint(blankEl, palette[0]); + paintedEl = blankEl; + seeded = true; + } + if (paintedEl) { + const key = keyOf(paintedEl); + const t0 = store.get(name, key).terrain; + const t2 = palette.find((t) => t !== t0); + await paint(paintedEl, t2); + if (store.get(name, key)?.terrain !== t2) fail(`overpaint ${key}: store has ${store.get(name, key)?.terrain}, wanted ${t2}`); + await undo(); + const back = store.get(name, key)?.terrain ?? null; + if (back !== t0) fail(`undo overpaint ${key}: terrain is ${back}, wanted the old ${t0}`); + const row = rowFor(await readNote(), key); + if (back === t0 && (!row || !row.includes(t0))) fail(`undo overpaint ${key}: map note row ${row}`); + out.steps.push(`painted ${key}: ${t0} → ${t2}, undone → ${back}`); + if (seeded) { await undo(); out.steps.push("seed undone"); } + } + // (d) hex-note properties (MG4): paint → the note's terrain property; an + // edit of the property → the map; undo puts both back. + if (p.hexProps?.running) { + const fileOf = (el) => app.vault.getAbstractFileByPath(p.hexPath(+el.dataset.x, +el.dataset.y, name)); + const withNote = hexEls.find((el) => fileOf(el)); + if (!withNote) out.steps.push("properties: no hex with a note"); + else { + const key = keyOf(withNote); + const file = fileOf(withNote); + const prop = async () => { + const fm = /^---\r?\n([\s\S]*?)\r?\n---/.exec(await app.vault.read(file))?.[1] ?? ""; + return /^terrain:[ \t]*(.*)$/m.exec(fm)?.[1].replace(/^"(.*)"$/, "$1").trim() || null; + }; + const settle = async () => { await p.hexProps.flush(); await store.flush(); }; + const t0 = store.get(name, key)?.terrain ?? null; + const t1 = palette.find((t) => t !== t0); + await paint(withNote, t1); + await settle(); + if ((await prop()) !== t1) fail(`properties: paint ${key} ${t1}, the note says ${await prop()}`); + await undo(); + await settle(); + if ((await prop()) !== t0) fail(`properties: undo ${key}, the note says ${await prop()}, wanted ${t0}`); + const t2 = palette.find((t) => t !== t0 && t !== t1) ?? t1; + await app.vault.process(file, (text) => { + const m = /^---\r?\n([\s\S]*?)\r?\n---/.exec(text); + if (!m) return `---\nterrain: ${JSON.stringify(t2)}\n---\n${text}`; + const body = /^terrain:.*$/m.test(m[1]) ? m[1].replace(/^terrain:.*$/m, `terrain: ${JSON.stringify(t2)}`) : `${m[1]}\nterrain: ${JSON.stringify(t2)}`; + return text.replace(m[1], body); + }); + for (let i = 0; i < 30 && store.get(name, key)?.terrain !== t2; i++) { await sleep(100); await settle(); } + if (store.get(name, key)?.terrain !== t2) fail(`properties: typed terrain ${t2} into ${file.path}, the map has ${store.get(name, key)?.terrain}`); + await undo(); + await settle(); + if ((store.get(name, key)?.terrain ?? null) !== t0 || (await prop()) !== t0) fail(`properties: undo of the edit: map ${store.get(name, key)?.terrain}, note ${await prop()}, wanted ${t0}`); + out.steps.push(`properties ${key}: paint → note, note → map, undo → both ${t0 ?? "(none)"}`); + } + } + view.exitTerrainMode?.(); + view.drawingMode = null; + await store.flush(); + // (c) the note reads back to the same data + await store.reloadFromNotes(); + await sleep(300); + const after = canon(); + if (after !== before) { + const was = new Map(JSON.parse(before)), now = new Map(JSON.parse(after)); + const keys = [...new Set([...was.keys(), ...now.keys()])].filter((k) => JSON.stringify(was.get(k)) !== JSON.stringify(now.get(k))); + fail(`store after undo + reload differs from before: ${keys.slice(0, 5).map((k) => `${k} ${JSON.stringify(was.get(k))} → ${JSON.stringify(now.get(k))}`).join(", ")}`); + } + const textAfter = await readNote(); + out.noteUnchanged = textAfter === textBefore; + return out; +} + +/** + * C8 mode locks on `name` (a plain map): in Play the path tool's edits are + * refused and nothing is written; in Build the same edit goes through and + * undoes. Terrain paint likewise: Play refuses it, Build paints and undoes. + */ +export async function modeLocks(id, name) { + const app = window.app; + const p = app.plugins.plugins[id]; + const store = p.mapStore; + const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); + await p.showMap(name); + await sleep(600); + const view = app.workspace.getLeavesOfType("duckmage-hex-map")[0]?.view; + if (!view || view.activeMapName !== name) return { ok: false, problems: ["map view did not open " + name] }; + const out = { ok: true, problems: [], steps: [], gaps: [] }; + const fail = (m) => { out.ok = false; out.problems.push(m); }; + const map = p.getMap(name); + const startMode = map.workMode; + const notePath = store.notePath(name); + const readNote = async () => ((await app.vault.adapter.exists(notePath)) ? app.vault.adapter.read(notePath) : null); + const types = p.getMapPathTypes(name); + const cols = map.gridSize.cols, rows = map.gridSize.rows; + // Candidate start/end hexes: a route may be refused (impassable ends, + // no way round), so Build tries a few pairs and Play reuses the one that drew. + const ox = map.gridOffset.x, oy = map.gridOffset.y; + const at = (fx, fy) => `${ox + Math.min(cols - 1, Math.max(0, Math.round(fx * (cols - 1))))}_${oy + Math.min(rows - 1, Math.max(0, Math.round(fy * (rows - 1))))}`; + const pairs = [[at(0.2, 0.2), at(0.5, 0.4)], [at(0.5, 0.5), at(0.7, 0.6)], [at(0.1, 0.8), at(0.3, 0.8)], [at(0.8, 0.2), at(0.8, 0.4)], [at(0.4, 0.1), at(0.6, 0.1)], [at(0, 0), at(0.2, 0)]] + .filter(([a, b]) => a !== b); + const draw = async ([a, b]) => { + const tool = view.pathTool; + tool.reset(); + tool.setType(types[0].name); + for (const k of [a, b]) { + const [x, y] = k.split("_").map(Number); + tool.click(x, y, undefined, false); + await sleep(50); + } + tool.done(); + await store.flush(); + await sleep(200); + }; + const pathsJson = () => JSON.stringify(store.paths(name)); + try { + if (!types.length) out.steps.push("no path types: path lock not tested"); + else { + // Build: a path draws and undoes (so the lock isn't simply everything). + view.setWorkMode("build"); + await store.flush(); + await sleep(300); + const b0 = pathsJson(); + let drawn = null; + for (const pair of pairs) { + await draw(pair); + if (pathsJson() !== b0) { drawn = pair; break; } + } + if (!drawn) fail(`Build: no path could be drawn (tried ${pairs.map((x) => x.join("→")).join(", ")})`); + else { + await view.undo(); + await store.flush(); + await sleep(200); + if (pathsJson() !== b0) fail("Build: undo didn't remove the drawn path"); + out.steps.push(`build: path ${drawn.join("→")} drawn and undone`); + // Play: the same edit is refused and nothing is written. + view.setWorkMode("play"); + await store.flush(); + await sleep(300); + const before = pathsJson(), text = await readNote(); + await draw(drawn); + if (pathsJson() !== before) fail("Play: a path was drawn"); + if ((await readNote()) !== text) fail("Play: the map note changed after a refused path edit"); + else out.steps.push("play: the same path edit refused, map note unchanged"); + } + } + // Terrain paint on a plain map, through the real mouse handlers: Play + // refuses it (nothing written), Build paints it, and Build's undo takes + // it back (WM6: Play's queue is untouched). + const hexEl = view.containerEl.querySelector(".duckmage-hex[data-x]"); + if (hexEl) { + const key = `${hexEl.dataset.x}_${hexEl.dataset.y}`; + const terrain = p.getMapPalette(name).map((t) => t.name).find((t) => t !== store.get(name, key)?.terrain); + if (terrain) { + const paint = async () => { + view.leaveOtherToolFor?.("terrain"); + view.drawingMode = "terrain"; + view.isErasingMode = false; + view.terrainPickMode = false; + view.paintTerrainName = terrain; + view.paintBrushSize = 1; + const el = view.containerEl.querySelector(`.duckmage-hex[data-x="${hexEl.dataset.x}"][data-y="${hexEl.dataset.y}"]`) ?? hexEl; + const r = el.getBoundingClientRect(); + const at = { bubbles: true, cancelable: true, button: 0, clientX: r.x + r.width / 2, clientY: r.y + r.height / 2 }; + el.dispatchEvent(new MouseEvent("mousedown", at)); + el.ownerDocument.dispatchEvent(new MouseEvent("mouseup", at)); + await view.terrainWritesSettled?.(); + await sleep(100); + view.exitTerrainMode?.(); + view.drawingMode = null; + }; + const now = () => JSON.stringify(store.get(name, key) ?? null); + view.setWorkMode("play"); + await sleep(200); + const before = now(), text = await readNote(); + await paint(); + await store.flush(); + if (now() !== before) { + fail("Play: terrain paint was written"); + view.setWorkMode("build"); + await view.undo(); + await view.terrainWritesSettled?.(); + } else if ((await readNote()) !== text) fail("Play: the map note changed after a refused terrain paint"); + else out.steps.push("play: terrain paint refused, map note unchanged"); + view.setWorkMode("build"); + await sleep(200); + await paint(); + if (store.get(name, key)?.terrain !== terrain) fail("Build: terrain paint was not written"); + else { + out.steps.push("build: terrain paint written"); + await view.undo(); + await view.terrainWritesSettled?.(); + await sleep(100); + if (now() !== before) fail("Build: undo didn't take the paint back"); + else out.steps.push("build: undo took it back"); + } + } + } + } finally { + view.setWorkMode(startMode === "god" || startMode === "play" ? startMode : "build"); + + await store.flush(); + } + return out; +} + +/** + * C9 solo play on `name` (SF3/SF5), through the map view's own handlers: + * a party token note on a middle hex; in Play, a click on the token picks + * it up (its neighbours light up), a click on a lit hex moves it there + * (token note and the map note's `visited:` list); "Add to play log…" + * writes today's log note and links it from the hex note. Everything it + * made is removed again (the map's visited list and mode restored). + * In a build without the play slice: the party token is a plain token (no + * party mark, nothing picked up) and its note keeps `token-party`. + */ +export async function partyPlay(id, name) { + const app = window.app; + const p = app.plugins.plugins[id]; + const store = p.mapStore; + const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); + const waitFor = async (fn, ms = 4000) => { const t0 = performance.now(); while (performance.now() - t0 < ms) { const v = fn(); if (v) return v; await sleep(100); } return fn(); }; + await p.showMap(name); + await sleep(600); + const view = app.workspace.getLeavesOfType("duckmage-hex-map")[0]?.view; + if (!view || view.activeMapName !== name) return { ok: false, steps: [], problems: ["map view did not open " + name] }; + const out = { ok: true, steps: [], problems: [] }; + const fail = (m) => { out.ok = false; out.problems.push(m); }; + const map = p.getMap(name); + const startMode = map.workMode; + const visitedBefore = map.visited ? [...map.visited] : undefined; + const hexEls = [...view.containerEl.querySelectorAll(".duckmage-hex[data-x]")]; + const mid = hexEls[Math.floor(hexEls.length / 2)]; + if (!mid) return { ok: true, steps: ["no hexes: skipped"], problems: [] }; + const key = `${mid.dataset.x}_${mid.dataset.y}`; + const tokPath = "smoke-party-token.md"; + const made = [tokPath]; + // Solo play is a slice (release-slices.json "play"): its command is registered only when it's built. + const playOn = !!app.commands.commands[`${id}:open-play-log`]; + try { + await app.vault.create(tokPath, `---\ntoken: true\ntoken-hex: "${key}"\ntoken-map: "${name}"\ntoken-party: true\n---\n# Smoke party\n`); + view.setWorkMode("play"); + await sleep(300); + if (!playOn) { + const tokenEl = await waitFor(() => view.containerEl.querySelector(".duckmage-token")); + if (!tokenEl) fail("the token wasn't drawn"); + if (view.containerEl.querySelector(".duckmage-token.is-party")) fail("a party token is marked as the party without the play slice"); + if (view.containerEl.querySelector(".duckmage-hex.duckmage-hex-visited")) fail("visited marks without the play slice"); + if (!/^token-party: true$/m.test(await app.vault.adapter.read(tokPath))) fail("the token note lost token-party"); + if (out.ok) out.steps.push("play slice not built: the party token is a plain token, its note keeps token-party, no visited marks"); + return out; + } + const tokenEl = await waitFor(() => view.containerEl.querySelector(".duckmage-token.is-party")); + if (!tokenEl) { fail("the party token wasn't drawn"); return out; } + const press = (el) => { + const r = el.getBoundingClientRect(); + const at = { bubbles: true, cancelable: true, button: 0, clientX: r.x + r.width / 2, clientY: r.y + r.height / 2 }; + el.dispatchEvent(new MouseEvent("mousedown", at)); + el.ownerDocument.dispatchEvent(new MouseEvent("mouseup", at)); + }; + press(tokenEl); + // The map may still redraw after the mode switch: let it settle, then + // take the lit hex from the grid as it is now (not a detached one). + await sleep(800); + const step = await waitFor(() => [...view.containerEl.querySelectorAll(".duckmage-hex-map-grid .duckmage-hex.duckmage-party-step")].find((el) => el.isConnected)); + if (!view.containerEl.querySelector(".duckmage-token.is-party.is-selected")) fail("a click didn't pick the party up"); + if (!step) { fail("no neighbouring hex lit up"); return out; } + const to = `${step.dataset.x}_${step.dataset.y}`; + const party = view.activeParty?.(); + let reached = false; + const onHexClick = view.onHexClick; + view.onHexClick = function (...a) { reached = true; return onHexClick.apply(this, a); }; + try { + // A real mouseup is always followed by a click; the synthetic strokes + // of earlier checks aren't, which leaves the view's "that was a drag, + // swallow the next click" flag set. A click on the view's own box + // (no hex) clears it. + view.contentEl.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true, button: 0 })); + step.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true, button: 0 })); + } finally { view.onHexClick = onHexClick; } + if (!reached || !party) out.problems.push(`(click reached the map: ${reached}; target ${step.className} in ${step.parentElement?.className}; party picked up: ${party ? party.hex : "none"}; mode ${p.getMap(name).workMode})`); + const readTok = async () => (await app.vault.adapter.exists(tokPath)) ? app.vault.adapter.read(tokPath) : ""; + let moved = false; + for (let i = 0; i < 40 && !moved; i++) { moved = new RegExp(`^token-hex: "?${to}"?\\s*$`, "m").test(await readTok()); if (!moved) await sleep(100); } + if (!moved) fail(`the party didn't move to ${to}`); + await store.flush?.(); + await sleep(300); + const visited = p.getMap(name).visited ?? []; + if (!visited.includes(key) || !visited.includes(to)) fail(`visited is ${JSON.stringify(visited)}, wanted ${key} and ${to}`); + const note = await app.vault.adapter.read(store.notePath(name)); + if (!/^visited:/m.test(note)) fail("the map note has no visited: line"); + if (!view.containerEl.querySelector(`.duckmage-hex.duckmage-hex-visited[data-x="${step.dataset.x}"][data-y="${step.dataset.y}"]`)) fail("the new hex has no visited mark"); + if (out.ok) out.steps.push(`play: party picked up, stepped ${key} → ${to}, both visited`); + // The play log. + const stepPath = p.hexPath(Number(step.dataset.x), Number(step.dataset.y), name); + const hadStepNote = !!app.vault.getAbstractFileByPath(stepPath); + // Through the hex editor's Add to log link (the play module's log writer). + view.openHexEditorModal(Number(step.dataset.x), Number(step.dataset.y)); + const logLink = await waitFor(() => [...document.querySelectorAll(".modal a.duckmage-editor-open-link")].find((a) => a.textContent === "Add to log")); + if (!logLink) fail("the hex editor has no Add to log link"); + logLink?.click(); + const box = await waitFor(() => document.querySelector(".duckmage-play-log-text")); + if (!box) fail("Add to play log didn't open"); + else { + box.value = "Smoke: wolves on the ridge."; + box.closest(".modal")?.querySelector("button.mod-cta")?.click(); + let found = null; + for (let i = 0; i < 50 && !found; i++) { + await sleep(100); + for (const f of app.vault.getMarkdownFiles().filter((f) => /\/log\/\d{4}-\d\d-\d\d\.md$/.test(f.path))) { + if ((await app.vault.read(f)).includes("Smoke: wolves on the ridge.")) found = f; + } + } + await sleep(400); + if (!found) fail("no log note holds the entry"); + else { + const text = await app.vault.read(found); + if (!/\[\[smoke-party-token(\|[^\]]*)?\]\]/.test(text)) fail("the log entry doesn't name the party"); + const hexNote = app.vault.getAbstractFileByPath(stepPath); + const hexText = hexNote ? await app.vault.read(hexNote) : ""; + if (!/^#{1,6} Log\s*$/m.test(hexText) || !hexText.includes(found.basename)) fail("the hex note has no link to the log day"); + if (!hadStepNote) made.push(stepPath); + // The day's note: remove it only if this check made it (nothing else in it). + if (text.split("\n").filter((l) => l.startsWith("- ")).length === 1) made.push(found.path); + if (out.ok) out.steps.push(`log: entry in ${found.path}, hex links back`); + } + } + } finally { + document.querySelectorAll(".modal-close-button").forEach((b) => b.click()); + for (const path of made) { + const f = app.vault.getAbstractFileByPath(path); + if (f) await app.vault.delete(f); + } + const m = p.getMap(name); + if (visitedBefore) m.visited = visitedBefore; else delete m.visited; + view.setWorkMode(startMode === "god" || startMode === "play" ? startMode : "build"); + await p.saveSettings(); + await store.flush?.(); + await sleep(300); + } + return out; +} + +/** + * Overworld paint lock: in Play, the terrain brush over the Regions view + * is refused (Notice) and no region's data changes. + */ +export async function overworldPaintLock(id, name) { + const app = window.app; + const p = app.plugins.plugins[id]; + const store = p.mapStore; + const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); + await p.showMap(name); + await sleep(1500); + const view = app.workspace.getLeavesOfType("duckmage-hex-map")[0]?.view; + if (!view || view.activeMapName !== name) return { ok: false, problems: ["overworld did not open"] }; + const all = () => JSON.stringify(p.settings.maps.map((m) => [m.name, [...store.all(m.name)]])); + const startMode = p.getMap(name).workMode; + const out = { ok: true, problems: [], steps: [] }; + try { + view.setWorkMode("play"); + await store.flush(); + await sleep(300); + const before = all(); + view.showOverworldRegions?.(); + await sleep(800); + view.leaveOtherToolFor?.("terrain"); + view.drawingMode = "terrain"; + view.paintTerrainName = p.getMapPalette(name)[0]?.name ?? null; + const shown = view.overworldLayer?.showsRegions?.(view.getActiveMap?.()); + const box = view.containerEl.querySelector(".duckmage-hex-map-clip") ?? view.containerEl; + const r = box.getBoundingClientRect(); + const at = { bubbles: true, cancelable: true, button: 0, clientX: r.x + r.width / 2, clientY: r.y + r.height / 2 }; + const n0 = document.querySelectorAll(".notice").length; + box.dispatchEvent(new MouseEvent("mousedown", at)); + box.ownerDocument.dispatchEvent(new MouseEvent("mouseup", at)); + await sleep(400); + await store.flush(); + const said = [...document.querySelectorAll(".notice")].slice(n0).map((n) => n.textContent); + if (all() !== before) { out.ok = false; out.problems.push("Play: overworld paint changed region data"); } + out.steps.push(`regions view shown: ${shown}; notice: ${said.join(" | ") || "(none)"}`); + if (shown && !said.some((t) => /Switch to Build/i.test(t ?? ""))) { out.ok = false; out.problems.push("Play: no locked-paint notice"); } + view.exitTerrainMode?.(); + view.drawingMode = null; + } finally { + view.setWorkMode(startMode === "god" || startMode === "play" ? startMode : "build"); + + await store.flush(); + } + return out; +} + +// C10 hex flower solo lives in its own file (sent to the page with the rest). +export { exploreAsYouGo, exploreFog, hexFlowerSolo } from "./hexFlower.mjs"; +export { exportsRoundTrip } from "./exports.mjs"; +// C12 hex fields (#52) lives in its own file too. +export { hexFieldsCheck } from "./hexFields.mjs"; diff --git a/dev/smoke/lib/slices.mjs b/dev/smoke/lib/slices.mjs new file mode 100644 index 00000000..9fa5c021 --- /dev/null +++ b/dev/smoke/lib/slices.mjs @@ -0,0 +1,37 @@ +/** + * The feature switches in the smoke suite (release-slices.json; + * dev/release/slices.mjs): which slices a build under test has, and which + * setups exercise slices the release build leaves out. Pure node. + */ + +/** The slices a built main.js has, read from its banner ("build channel: …", "slices: [...]"); null when it doesn't say. */ +export function bannerSlices(mainJs) { + const head = String(mainJs).slice(0, 600); + const channel = /^build channel: (.+)$/m.exec(head)?.[1]?.trim() ?? null; + let on = null; + const list = /^slices: (\[.*\])$/m.exec(head)?.[1]; + if (list) { + try { + on = JSON.parse(list); + } catch { + on = null; + } + } + return { channel, on }; +} + +/** + * The setups a release build can't fully run: those that exercise a slice + * that isn't released (a setup's `slices`). premerge runs them on a build + * with every slice (`--slices all`). + */ +export function unreleasedSetups(setups, slices) { + const unreleased = new Set(Object.entries(slices).filter(([, s]) => s.define && !s.released).map(([id]) => id)); + return setups.filter((s) => (s.slices ?? []).some((id) => unreleased.has(id))).map((s) => s.id); +} + +/** The stamp files of a run: last-run / last-pass, or last-run. / last-pass. for a named stamp ("full"). */ +export function stampFiles(stamp) { + const suffix = stamp ? `.${stamp}` : ""; + return { run: `last-run${suffix}.json`, pass: `last-pass${suffix}.json` }; +} diff --git a/dev/smoke/mobile-emulation.mjs b/dev/smoke/mobile-emulation.mjs new file mode 100644 index 00000000..a36088a3 --- /dev/null +++ b/dev/smoke/mobile-emulation.mjs @@ -0,0 +1,289 @@ +#!/usr/bin/env node +/** + * Mobile emulation check (issue #20): the built plugin in a HIDDEN sandbox + * Obsidian with app.emulateMobile(true) and a phone-sized viewport. It + * checks the plugin reloads on "mobile" without console errors, then drives + * the hex map with CDP touch events: one-finger drag (pan), two-finger pinch + * (zoom), a tap, and a long-press that must open the hex editor. Screenshots + * go to the run's shots/ folder; the run folder is deleted at the end. + * + * UX_RUNS_DIR=~/hexmaker-runs node dev/smoke/mobile-emulation.mjs [--keep] + * + * Emulation is not a phone: it covers the plugin's own touch handling, not + * a real WebView's quirks (iOS Safari, the soft keyboard, safe areas). + */ +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { createSandbox, launchSandbox, stopSandbox, connectPage, pluginErrors, shot, sleep } from "./lib/obsidian.mjs"; + +const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", ".."); +const keep = process.argv.includes("--keep"); +const results = []; +const check = (name, ok, detail = "") => { results.push({ name, ok, detail }); console.log(`${ok ? "PASS" : "FAIL"} ${name}${detail ? " " + detail : ""}`); }; + +const work = path.join(os.homedir(), ".cache", "hexmaker-mobile", String(Date.now())); +const build = path.join(work, "build"); +const seed = path.join(work, "seed"); +fs.mkdirSync(build, { recursive: true }); +fs.mkdirSync(seed, { recursive: true }); +fs.writeFileSync(path.join(seed, ".hexmaker-sandbox"), "mobile emulation sandbox\n"); +for (const f of ["main.js", "manifest.json", "styles.css"]) fs.copyFileSync(path.join(ROOT, f), path.join(build, f)); +const manifest = JSON.parse(fs.readFileSync(path.join(build, "manifest.json"), "utf8")); +check("manifest isDesktopOnly is false", manifest.isDesktopOnly === false); + +let runDir = null, sess = null; +try { + const created = await createSandbox({ pluginDir: build, seed, name: "mobile-emulation" }); + runDir = created.runDir; + await launchSandbox(runDir); + sess = await connectPage(runDir); + const { page } = sess; + const id = manifest.id; + const ev = (fn, ...a) => page.evaluate(fn, ...a); + const ready = await ev(async (pid) => { + for (let i = 0; i < 300; i++) { const p = window.app.plugins.plugins[pid]; if (p?.mapStore) return true; await new Promise((r) => setTimeout(r, 200)); } + return false; + }, id); + check("plugin loaded (desktop mode)", ready); + + // A map, made on "desktop" so the store is ready. + const mapName = await ev(async (pid) => { + const p = window.app.plugins.plugins[pid]; + p.settings.setupComplete = true; + window.app.workspace.getLeavesOfType("duckmage-setup-wizard").forEach((l) => l.detach()); + const r = await p.createNewMap({ name: "Phone Map", cols: 14, rows: 12, quiet: true }); + if ("error" in r) throw new Error(r.error); + await p.saveSettings(); await p.mapStore.flush(); + return r.name; + }, id); + + // ── mobile ── + const mark = sess.log.length; + // emulateMobile reloads the window: the plugin then loads fresh, as it would on a phone. + await ev(() => { setTimeout(() => window.app.emulateMobile(true), 50); return true; }).catch(() => {}); + await sleep(4000); + let loaded = false; + for (let i = 0; i < 120 && !loaded; i++) { + loaded = await ev((pid) => !!window.app?.plugins?.plugins?.[pid]?.mapStore, id).catch(() => false); + if (!loaded) await sleep(500); + } + const isMobile = await ev(() => ({ body: document.body.classList.contains("is-mobile"), phone: document.body.classList.contains("is-phone") })); + check("app.emulateMobile(true): body.is-mobile", isMobile.body, JSON.stringify(isMobile)); + check("plugin loads on mobile", loaded); + const cdp = await page.createCDPSession(); + await cdp.send("Emulation.setDeviceMetricsOverride", { width: 390, height: 844, deviceScaleFactor: 2, mobile: true }); + await cdp.send("Emulation.setTouchEmulationEnabled", { enabled: true, maxTouchPoints: 5 }); + await sleep(1500); + + const opened = await ev(async (pid, name) => { + const p = window.app.plugins.plugins[pid]; + await p.showMap(name); + for (let i = 0; i < 200; i++) { + const v = window.app.workspace.getLeavesOfType("duckmage-hex-map")[0]?.view; + if (v?.containerEl.querySelectorAll(".duckmage-hex[data-x]").length > 20) return true; + await new Promise((r) => setTimeout(r, 100)); + } + return false; + }, id, mapName); + check("hex map renders on mobile", opened); + await sleep(800); + await shot(page, runDir, "01-map-mobile"); + + const geo = await ev(() => { + const v = window.app.workspace.getLeavesOfType("duckmage-hex-map")[0].view; + const clip = v.containerEl.querySelector(".duckmage-hex-map-clip"); + const r = clip.getBoundingClientRect(); + const hex = [...v.containerEl.querySelectorAll(".duckmage-hex[data-x]")].map((h) => ({ h, b: h.getBoundingClientRect() })) + .filter((o) => o.b.left > r.left + 30 && o.b.right < r.right - 30 && o.b.top > r.top + 30 && o.b.bottom < r.bottom - 30)[0]; + const b = hex.b; + return { cx: b.left + b.width / 2, cy: b.top + b.height / 2, clip: { l: r.left, t: r.top, w: r.width, h: r.height }, touchAction: getComputedStyle(clip).touchAction }; + }); + check("map clip has touch-action none", geo.touchAction === "none", geo.touchAction); + check("map fits a ~390px screen", geo.clip.w <= 392, `clip width ${Math.round(geo.clip.w)}`); + // The zoom is baked into the font size after a pause, so measure the drawn hex width. + const vp = () => ev(() => { const v = window.app.workspace.getLeavesOfType("duckmage-hex-map")[0].view; const h = v.containerEl.querySelector(".duckmage-hex[data-x]").getBoundingClientRect(); return { zoom: h.width, panX: v.viewport.panX, panY: v.viewport.panY }; }); + + const touch = (type, pts) => cdp.send("Input.dispatchTouchEvent", { type, touchPoints: pts.map(([x, y], i) => ({ x, y, id: i + 1 })) }); + const x0 = geo.clip.l + geo.clip.w / 2, y0 = geo.clip.t + geo.clip.h / 2; + + // one-finger drag pans + let a = await vp(); + await touch("touchStart", [[x0, y0]]); + for (let i = 1; i <= 8; i++) { await touch("touchMove", [[x0 + i * 8, y0 + i * 5]]); await sleep(16); } + await touch("touchEnd", []); + await sleep(200); + let b = await vp(); + check("one-finger drag pans the map", Math.abs(b.panX - a.panX - 64) < 8 && Math.abs(b.panY - a.panY - 40) < 8 && Math.abs(b.zoom - a.zoom) < 0.5, `pan ${a.panX.toFixed(0)},${a.panY.toFixed(0)} -> ${b.panX.toFixed(0)},${b.panY.toFixed(0)}`); + check("a drag does not open the hex editor", (await ev(() => document.querySelectorAll(".modal-container .modal").length)) === 0); + + // two-finger pinch zooms (spread) + a = await vp(); + await touch("touchStart", [[x0 - 30, y0], [x0 + 30, y0]]); + for (let i = 1; i <= 10; i++) { await touch("touchMove", [[x0 - 30 - i * 8, y0], [x0 + 30 + i * 8, y0]]); await sleep(16); } + await touch("touchEnd", []); + await sleep(500); + b = await vp(); + check("two-finger spread zooms in", b.zoom > a.zoom * 1.8, `zoom ${a.zoom.toFixed(2)} -> ${b.zoom.toFixed(2)}`); + await shot(page, runDir, "02-after-pinch-in"); + a = b; + await touch("touchStart", [[x0 - 110, y0], [x0 + 110, y0]]); + for (let i = 1; i <= 10; i++) { await touch("touchMove", [[x0 - 110 + i * 8, y0], [x0 + 110 - i * 8, y0]]); await sleep(16); } + await touch("touchEnd", []); + await sleep(500); + b = await vp(); + check("two-finger pinch zooms out", b.zoom < a.zoom * 0.75, `zoom ${a.zoom.toFixed(2)} -> ${b.zoom.toFixed(2)}`); + check("a pinch does not open a hex or editor", (await ev(() => document.querySelectorAll(".modal-container .modal").length)) === 0); + + // long-press opens the hex editor + const g2 = await ev(() => { + const v = window.app.workspace.getLeavesOfType("duckmage-hex-map")[0].view; + const r = v.containerEl.querySelector(".duckmage-hex-map-clip").getBoundingClientRect(); + const hex = [...v.containerEl.querySelectorAll(".duckmage-hex[data-x]")].map((h) => h.getBoundingClientRect()) + .filter((q) => q.left > r.left + 20 && q.right < r.right - 20 && q.top > r.top + 20 && q.bottom < r.bottom - 20)[0]; + return { x: hex.left + hex.width / 2, y: hex.top + hex.height / 2 }; + }); + await touch("touchStart", [[g2.x, g2.y]]); + await sleep(750); + await touch("touchEnd", []); + await sleep(900); + const menu = await ev(() => { const m = document.querySelector(".menu"); return m ? { items: [...m.querySelectorAll(".menu-item-title")].map((i) => i.textContent), w: m.getBoundingClientRect().width } : null; }); + const stray = await ev(() => document.querySelectorAll(".modal-container .modal").length); + check("long-press opens the hex menu (what right-click opens)", !!menu && menu.items.length > 2, menu ? `${menu.items.length} items: ${menu.items.slice(0, 4).join(", ")}…` : "no menu"); + check("the lift after a long-press doesn't click a menu item", stray === 0, `modals open: ${stray}`); + check("hex menu fits the phone width", !!menu && menu.w <= 390, menu ? `${Math.round(menu.w)}px` : ""); + await shot(page, runDir, "03-long-press-hex-menu"); + await ev(() => document.querySelector(".menu-item-title") && document.body.click()); + await page.keyboard.press("Escape"); + await sleep(500); + // the hex editor itself (Open hex editor / Edit hex…): is it narrow enough? + await ev((pid) => { const p = window.app.plugins.plugins[pid]; return p; }, id); + + // a quick tap on a hex still opens its note (click path intact) + const before = await ev(() => window.app.workspace.getLeavesOfType("markdown").length); + await touch("touchStart", [[g2.x, g2.y]]); + await sleep(60); + await touch("touchEnd", []); + await sleep(1500); + const after = await ev(() => ({ md: window.app.workspace.getLeavesOfType("markdown").length, modals: document.querySelectorAll(".modal-container .modal").length, menu: !!document.querySelector(".menu") })); + check("a tap still opens the hex (click path)", after.md > before || after.modals > 0 || after.menu, `markdown leaves ${before} -> ${after.md}, modals ${after.modals}`); + await shot(page, runDir, "04-after-tap"); + + // HF11 on a phone: Start exploring from the long-press menu, the party bar's Sees 2 is one tap, + // a tap on the party's own hex reveals ring 2 (token unmoved), and the Reveal hexes brush takes a finger drag. + const hasFog = await ev((pid) => window.app.plugins.plugins[pid].moduleGenerators({ toPaths: () => ({ paths: [], missing: [] }), procGrid: (g) => g }).some((k) => k.id === "procedural:hex-flower"), id); + if (hasFog) { + await ev(() => { document.querySelector(".menu") && document.body.click(); document.querySelectorAll(".modal-container .modal-close-button").forEach((b) => b.click()); window.app.workspace.getLeavesOfType("markdown").forEach((l) => l.detach()); }); + for (let i = 0; i < 3 && (await ev(() => document.querySelectorAll(".modal").length)); i++) { await page.keyboard.press("Escape"); await sleep(400); } + await ev(async (pid, name) => { const p = window.app.plugins.plugins[pid]; await p.showMap(name); window.app.workspace.getLeavesOfType("duckmage-hex-map")[0].view.setWorkMode("play"); }, id, mapName); + await sleep(1200); + const tapAt = async (x, y) => { await touch("touchStart", [[x, y]]); await sleep(40); await touch("touchEnd", []); await sleep(500); }; + const centreOf = (sel) => ev((q) => { const el = document.querySelector(q); if (!el) return null; const r = el.getBoundingClientRect(); return { x: r.left + r.width / 2, y: r.top + r.height / 2, w: r.width }; }, sel); + const g3 = await ev(() => { + const v = window.app.workspace.getLeavesOfType("duckmage-hex-map")[0].view; + const r = v.containerEl.querySelector(".duckmage-hex-map-clip").getBoundingClientRect(); + const mid = { x: r.left + r.width / 2, y: r.top + r.height / 2 }; + const hexes = [...v.containerEl.querySelectorAll(".duckmage-hex[data-x]")].map((h) => ({ k: `${h.dataset.x}_${h.dataset.y}`, b: h.getBoundingClientRect() })) + .filter((o) => o.b.left > r.left + 20 && o.b.right < r.right - 20 && o.b.top > r.top + 20 && o.b.bottom < r.bottom - 20) + .sort((a, b) => Math.hypot(a.b.left - mid.x, a.b.top - mid.y) - Math.hypot(b.b.left - mid.x, b.b.top - mid.y)); + const h = hexes[0]; + return { k: h.k, x: h.b.left + h.b.width / 2, y: h.b.top + h.b.height / 2 }; + }); + await touch("touchStart", [[g3.x, g3.y]]); + await sleep(750); + await touch("touchEnd", []); + await sleep(900); + const start = await ev(() => { const i = [...document.querySelectorAll(".menu .menu-item")].find((m) => m.textContent.includes("Start exploring")); if (!i) return null; const r = i.getBoundingClientRect(); return { x: r.left + r.width / 2, y: r.top + r.height / 2 }; }); + const why = start ? "" : await ev((pid, name) => JSON.stringify({ mode: window.app.plugins.plugins[pid].getMap(name).workMode, items: [...document.querySelectorAll(".menu .menu-item")].map((m) => m.textContent), modals: [...document.querySelectorAll(".modal")].map((m) => m.className) }), id, mapName); + check("long-press menu offers Start exploring (Play)", !!start, why); + if (start) { + await tapAt(start.x, start.y); + await sleep(600); + const dlg = await ev(() => { const m = document.querySelector(".duckmage-start-exploring")?.closest(".modal"); return m ? m.getBoundingClientRect().width : null; }); + check("Start exploring dialog fits the phone", dlg !== null && dlg <= 392, `${dlg}px`); + const cta = await centreOf(".duckmage-start-exploring .mod-cta"); + if (cta) await tapAt(cta.x, cta.y); + await sleep(1200); + const fog = await ev((pid, name) => { const p = window.app.plugins.plugins[pid]; return { on: p.getMap(name).exploreFog, fogged: document.querySelectorAll(".duckmage-hex-fogged").length }; }, id, mapName); + check("a tap on Start exploring fogs the map", fog.on === "on" && fog.fogged > 0, JSON.stringify(fog)); + const tok = await centreOf(".duckmage-token.is-party"); + if (tok) await tapAt(tok.x, tok.y); + await sleep(600); + const bar = await ev(() => { const b = document.querySelector(".duckmage-party-controls"); return b ? b.getBoundingClientRect().width : null; }); + check("tapping the party shows its bar, within the phone width", bar !== null && bar <= 390, `${bar}px`); + await shot(page, runDir, "05-fog-party-bar"); + const s2 = await centreOf('.duckmage-party-controls button[aria-label="Sees 2"]'); + if (s2) await tapAt(s2.x, s2.y); + const seesNow = await ev((pid, name) => window.app.plugins.plugins[pid].getMap(name).exploreReveal, id, mapName); + check("Sees 2 is one tap", seesNow === "2 rings", String(seesNow)); + // The party's own hex, away from the token. + const own = await ev((k) => { + const [x, y] = k.split("_"); + const h = document.querySelector(`.duckmage-hex[data-x="${x}"][data-y="${y}"]`); + const r = h.getBoundingClientRect(); + for (const [fx, fy] of [[0.5, 0.12], [0.5, 0.88], [0.2, 0.5], [0.8, 0.5], [0.3, 0.2], [0.7, 0.8]]) { + const px = r.left + r.width * fx, py = r.top + r.height * fy; + const at = document.elementFromPoint(px, py); + if (at && at.closest(".duckmage-hex") === h && !at.closest(".duckmage-token")) return { x: px, y: py }; + } + return null; + }, g3.k); + const seenBefore = await ev((pid, name) => (window.app.plugins.plugins[pid].getMap(name).exploreSeen ?? []).join(";"), id, mapName); + if (own) await tapAt(own.x, own.y); + await sleep(800); + const look = await ev((pid, name, k) => { + const p = window.app.plugins.plugins[pid]; + const n = (p.getMap(name).exploreSeen ?? []).reduce((a, row) => a + row.split(":")[1].split(",").reduce((c, r) => { const [x0, x1] = r.trim().split("-").map(Number); return c + (x1 === undefined ? 1 : x1 - x0 + 1); }, 0), 0); + const v = window.app.workspace.getLeavesOfType("duckmage-hex-map")[0].view; + v.tokens.loadTokensForMap(); + return { n, at: v.tokens.tokenEntries.find((t) => t.party)?.hex, k }; + }, id, mapName, g3.k); + check("a tap on the party's own hex reveals ring 2, token unmoved", !!own && look.n === 19 && look.at === g3.k, `${own ? "" : "no free spot on the hex; "}seen ${seenBefore.length ? "" : "0 "}→ ${look.n}, party on ${look.at}`); + await shot(page, runDir, "06-fog-look"); + // The brush: a one-finger drag over hidden hexes reveals them. + const pick = await centreOf('.duckmage-party-controls button[aria-label="Reveal hexes Pick"]'); + if (pick) await tapAt(pick.x, pick.y); + const path = await ev(() => { + const r = document.querySelector(".duckmage-hex-map-clip").getBoundingClientRect(); + const hid = [...document.querySelectorAll(".duckmage-hex-fogged")].map((h) => ({ k: `${h.dataset.x}_${h.dataset.y}`, b: h.getBoundingClientRect() })) + .filter((o) => o.b.left > r.left + 10 && o.b.right < r.right - 10 && o.b.top > r.top + 10 && o.b.bottom < r.bottom - 10); + const a = hid[0]; + const b = a && hid.find((o) => o.k !== a.k && Math.abs(o.b.left - a.b.left) < 2 && Math.abs(o.b.top - a.b.bottom) < a.b.height * 0.6); + return a && b ? { keys: [a.k, b.k], from: [a.b.left + a.b.width / 2, a.b.top + a.b.height / 2], to: [b.b.left + b.b.width / 2, b.b.top + b.b.height / 2] } : null; + }); + if (path) { + await touch("touchStart", [path.from]); + for (let i = 1; i <= 6; i++) { await touch("touchMove", [[path.from[0] + (path.to[0] - path.from[0]) * i / 6, path.from[1] + (path.to[1] - path.from[1]) * i / 6]]); await sleep(20); } + await touch("touchEnd", []); + await sleep(900); + } + const brushed = path ? await ev((ks) => ks.map((k) => { const [x, y] = k.split("_"); return document.querySelector(`.duckmage-hex[data-x="${x}"][data-y="${y}"]`)?.classList.contains("duckmage-hex-fogged"); }), path.keys) : null; + check("Reveal hexes: a finger drag reveals the hexes crossed", !!pick && !!brushed && brushed.every((f) => f === false), path ? `${path.keys.join(" + ")}: fogged ${JSON.stringify(brushed)}` : "no pair of hidden hexes on screen"); + await shot(page, runDir, "07-fog-brush"); + } + } + + const errs = pluginErrors(sess.log.slice(mark), id).filter((e) => !/emulateMobile/.test(e.text)); + check("no plugin console errors on mobile", errs.length === 0, errs.slice(0, 3).map((e) => e.text.slice(0, 160)).join(" | ")); +} catch (e) { + check("run completed", false, String(e?.stack ?? e).slice(0, 600)); +} finally { + try { await sess?.close(); } catch { /* gone */ } + if (runDir) { + const shots = path.join(runDir, "shots"); + if (keep && fs.existsSync(shots)) console.log("shots kept in " + shots); + else if (fs.existsSync(shots)) { + const out = path.join(os.homedir(), ".cache", "hexmaker-mobile", "shots"); + fs.mkdirSync(out, { recursive: true }); + for (const f of fs.readdirSync(shots)) fs.copyFileSync(path.join(shots, f), path.join(out, f)); + console.log("screenshots copied to " + out); + } + try { await stopSandbox(runDir); } catch (e) { console.log("stop failed: " + e.message); } + if (!keep) fs.rmSync(runDir, { recursive: true, force: true }); + } + fs.rmSync(work, { recursive: true, force: true }); +} +const failed = results.filter((r) => !r.ok); +console.log(`\n${results.length - failed.length}/${results.length} passed`); +process.exit(failed.length ? 1 : 0); diff --git a/dev/smoke/premerge.mjs b/dev/smoke/premerge.mjs new file mode 100644 index 00000000..ad3caca8 --- /dev/null +++ b/dev/smoke/premerge.mjs @@ -0,0 +1,52 @@ +#!/usr/bin/env node +/** + * `npm run premerge`: everything that must pass before merging into + * feat/region-notes or deploying a build into the live vault (owner + * decision WM5). Runs, in order, stopping at the first failure: + * build, lint, test type-check, unit tests, integration tests, the smoke + * setups that exercise unreleased slices on a build with every slice + * (--slices all, stamped last-pass.full.json), then the smoke vault matrix + * on the release build just made (--no-build; last-pass.json). + * Extra arguments go to both smoke runs (e.g. --jobs 2); --only applies to + * the release matrix only. + * Run it where npm works for this repo (WSL; see CLAUDE.md). + */ +import { spawnSync } from "node:child_process"; +import { readSlices } from "../release/slices.mjs"; +import { SETUPS } from "./setups.mjs"; +import { unreleasedSetups } from "./lib/slices.mjs"; + +const smokeArgs = process.argv.slice(2); +// The full build's run takes the shared arguments, not the release matrix's --only. +const sharedArgs = smokeArgs.filter((a, i) => a !== "--only" && smokeArgs[i - 1] !== "--only"); +const fullSetups = unreleasedSetups(SETUPS, readSlices()); +const npm = process.platform === "win32" ? "npm.cmd" : "npm"; +const steps = [ + ["build", npm, ["run", "build"]], + ["lint", npm, ["run", "lint"]], + ["test type-check", npm, ["run", "typecheck:tests"]], + ["unit tests", npm, ["test"]], + ["integration tests", npm, ["run", "test:integration"]], + ...(fullSetups.length + ? [["smoke, every slice (unreleased features)", process.execPath, ["dev/smoke/cli.mjs", "--slices", "all", "--stamp", "full", "--only", fullSetups.join(","), ...sharedArgs]]] + : []), + ["smoke vault matrix", process.execPath, ["dev/smoke/cli.mjs", "--no-build", ...smokeArgs]], +]; + +const banner = (lines) => { + const w = Math.max(...lines.map((l) => l.length)) + 4; + console.log("\n" + "#".repeat(w)); + for (const l of lines) console.log(`# ${l.padEnd(w - 4)} #`); + console.log("#".repeat(w) + "\n"); +}; + +const t0 = Date.now(); +for (const [name, cmd, args] of steps) { + console.log(`\n=== premerge: ${name} ===`); + const r = spawnSync(cmd, args, { stdio: "inherit", shell: process.platform === "win32" }); + if (r.status !== 0) { + banner([`PREMERGE FAILED at: ${name} (exit ${r.status ?? r.signal ?? r.error?.message})`, "Do NOT merge into feat/region-notes or deploy to the live vault."]); + process.exit(1); + } +} +banner([`PREMERGE PASSED in ${Math.round((Date.now() - t0) / 1000)} s`, `Stamp: dev/smoke/last-pass.json${fullSetups.length ? " (+ last-pass.full.json)" : ""}`]); diff --git a/dev/smoke/run.mjs b/dev/smoke/run.mjs new file mode 100644 index 00000000..8fed5cbf --- /dev/null +++ b/dev/smoke/run.mjs @@ -0,0 +1,526 @@ +#!/usr/bin/env node +/** + * Smoke-test vault matrix (plan-work-modes §3; owner decision WM5: run it + * LOCALLY before merging into feat/region-notes and before any live-vault + * deploy; CI keeps the Obsidian-free tests). + * + * node dev/smoke/run.mjs [--jobs N] [--only fresh,v155] [--build ] [--no-build] [--slices ] [--stamp ] [--keep] [--list] + * + * Windows node (Obsidian is a Windows app). From WSL use `npm run smoke`, + * which hands over to node.exe (dev/smoke/cli.mjs). + * + * 1. Builds the plugin through WSL (or takes --build , or the repo's + * current main.js with --no-build) and snapshots main.js / manifest.json / + * styles.css into a temp folder, so a running `npm run dev` can't change + * the plugin mid-suite. --slices builds that set of features + * instead (the HEXMAKER_SLICES grammar: all, released, none, +id/-id…) + * into the run folder, leaving the repo's main.js as it is. + * 2. Per vault setup (setups.mjs): builds the fixture, `sandbox.mjs create` + * (own vault + Electron profile), optionally a prep launch that builds + * maps through the plugin API, then a check launch running C1–C8, then a + * restart launch for C5. At most --jobs sandboxes at once (max 4); + * without --jobs, as many as free memory and CPU allow + * (lib/concurrency.mjs: fewer when the machine is busy). + * 3. Stops every sandbox it started (retrying while its processes linger) + * and checks none of ITS processes are left. Other Obsidian processes + * (the owner's, other sessions' runs) may start or stop meanwhile; they + * are only reported, never counted against the run. + * 4. Writes dev/smoke/last-run.json, and dev/smoke/last-pass.json when + * every setup passed: { commit, dirty, buildHash, slices, setups, results } + * (`slices`: the spec asked for, and the channel and slices the build's + * banner names). --stamp writes last-run..json / + * last-pass..json instead (premerge's full-build run: "full"). + * + * Never touches the main vault: fixtures are generated or copied into the + * sandbox's own run folder; the open vault is checked before any script runs. + */ +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import crypto from "node:crypto"; +import { execFileSync } from "node:child_process"; +import { fileURLToPath } from "node:url"; +import { + common, createSandbox, launchSandbox, stopSandbox, connectPage, obsidianProcesses, pluginErrors, shot, sleep, +} from "./lib/obsidian.mjs"; +import { machineLoad, pickJobs } from "./lib/concurrency.mjs"; +import { snapshot, diff, legacyTruth, verifyMigration, verifyBackups, noteTextHashes, verifyPaletteUpgrade, noteFormatBackups, tableRangeBackups } from "./lib/disk.mjs"; +import * as P from "./lib/page.mjs"; +import { canon, jsonDiff, oneTimeOnly } from "./lib/compare.mjs"; +import { SETUPS } from "./setups.mjs"; +import { bannerSlices, stampFiles } from "./lib/slices.mjs"; + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const ROOT = path.resolve(HERE, "..", ".."); +const PLUGIN_FILES = ["main.js", "manifest.json", "styles.css"]; + +// ── args ────────────────────────────────────────────────────────────────── +const argv = process.argv.slice(2); +const flag = (k) => argv.includes(`--${k}`); +const val = (k, d) => { const i = argv.indexOf(`--${k}`); return i >= 0 && argv[i + 1] && !argv[i + 1].startsWith("--") ? argv[i + 1] : d; }; +if (flag("help") || flag("h")) { + console.log("usage: node dev/smoke/run.mjs [--jobs N] [--only a,b] [--build ] [--no-build] [--slices ] [--stamp ] [--keep] [--list]"); + console.log(" --jobs N sandboxes at once (1-4); default: picked from free memory and CPU load"); + console.log(" --slices build these features (HEXMAKER_SLICES: all, released, none, +id/-id) into the run folder"); + console.log(" --stamp write last-run..json / last-pass..json"); + process.exit(0); +} +if (flag("list")) { + for (const s of SETUPS) console.log(`${s.id.padEnd(16)} ${s.title}`); + process.exit(0); +} +if (process.platform !== "win32" && process.platform !== "linux") { + console.error("dev/smoke/run.mjs drives Obsidian on Windows or Linux."); + process.exit(2); +} +const jobsPick = pickJobs({ requested: val("jobs", null), ...(await machineLoad()) }); +const jobs = jobsPick.jobs; +const only = val("only", null)?.split(",").map((s) => s.trim()).filter(Boolean) ?? null; +if (only) { + const unknown = only.filter((o) => !SETUPS.some((s) => s.id === o)); + if (unknown.length) { console.error(`unknown setup(s): ${unknown.join(", ")} (see --list)`); process.exit(2); } +} +const keep = flag("keep"); +const sliceSpec = val("slices", null); +if (sliceSpec && (flag("no-build") || val("build", null))) { + console.error("--slices builds its own main.js; leave out --no-build and --build"); + process.exit(2); +} +const stamps = stampFiles(val("stamp", null)); + +const log = (...a) => console.log(`[smoke ${new Date().toISOString().slice(11, 19)}]`, ...a); +const git = (...a) => { try { return execFileSync("git", ["-C", ROOT, ...a], { encoding: "utf8" }).trim(); } catch { return null; } }; +const toWsl = (p) => path.resolve(p).replace(/^([A-Za-z]):/, (_, d) => `/mnt/${d.toLowerCase()}`).replace(/\\/g, "/"); + +// ── 1. build + snapshot ─────────────────────────────────────────────────── +const stamp = new Date().toISOString().replace(/[-:]/g, "").replace(/\..*/, "").replace("T", "-"); +// Linux: the Flathub Obsidian has a private /tmp, so seeds go under the home folder. +const work = path.join(process.platform === "linux" ? path.join(os.homedir(), ".cache") : os.tmpdir(), "hexmaker-smoke", stamp); +fs.mkdirSync(work, { recursive: true }); +let source = val("build", null); +if (!source && sliceSpec) { + // That slice set, built into the run folder (the repo's main.js stays as it is). Type-checking is the caller's (premerge). + source = path.join(work, "slice-build"); + fs.mkdirSync(source); + log(`building with slices "${sliceSpec}"…`); + if (process.platform === "linux") { + execFileSync(process.execPath, ["esbuild.config.mjs", "production"], { cwd: ROOT, stdio: "inherit", env: { ...process.env, HEXMAKER_SLICES: sliceSpec, HEXMAKER_SLICES_ON: "", HEXMAKER_SLICES_OFF: "", HEXMAKER_OUTFILE: path.join(source, "main.js") } }); + } else { + const out = toWsl(path.join(source, "main.js")); + execFileSync("wsl.exe", ["-e", "bash", "-lc", `cd '${toWsl(ROOT)}' && HEXMAKER_SLICES='${sliceSpec.replace(/'/g, "")}' HEXMAKER_SLICES_ON= HEXMAKER_SLICES_OFF= HEXMAKER_OUTFILE='${out}' node esbuild.config.mjs production`], { stdio: "inherit", env: { ...process.env, MSYS_NO_PATHCONV: "1" } }); + } + for (const f of ["manifest.json", "styles.css"]) if (fs.existsSync(path.join(ROOT, f))) fs.copyFileSync(path.join(ROOT, f), path.join(source, f)); +} +if (!source) { + source = ROOT; + if (!flag("no-build")) { + if (process.platform === "linux") { + log("building (npm run build)…"); + execFileSync("npm", ["run", "build"], { cwd: ROOT, stdio: "inherit" }); + } else { + log("building (npm run build through WSL)…"); + execFileSync("wsl.exe", ["-e", "bash", "-lc", `cd '${toWsl(ROOT)}' && npm run build`], { stdio: "inherit", env: { ...process.env, MSYS_NO_PATHCONV: "1" } }); + } + } +} +const buildDir = path.join(work, "build"); +fs.mkdirSync(buildDir); +const hash = crypto.createHash("sha256"); +for (const f of PLUGIN_FILES) { + const s = path.join(source, f); + if (!fs.existsSync(s)) { if (f === "styles.css") continue; console.error(`${f} missing in ${source}`); process.exit(2); } + const buf = fs.readFileSync(s); + hash.update(f).update(buf); + fs.writeFileSync(path.join(buildDir, f), buf); +} +const buildHash = hash.digest("hex").slice(0, 16); +const manifest = JSON.parse(fs.readFileSync(path.join(buildDir, "manifest.json"), "utf8")); +const pluginId = manifest.id; +const mainJs = fs.readFileSync(path.join(buildDir, "main.js"), "utf8"); +// Commands are registered with addCommand, or addPlaced("", …) (src/ui/commandPlacement.ts). +// Modules' placed commands are contributions ({ id, name, placementId: "Plugin.cmd.…" }, src/modules//runtime.ts). +const expectedCommands = [...new Set([ + ...[...mainJs.matchAll(/(?:addCommand\(|addPlaced\("[^"]+",\s*)\{\s*id:\s*"([^"]+)"/g)].map((m) => m[1]), + ...[...mainJs.matchAll(/\{\s*id:\s*"([^"]+)",\s*name:\s*"[^"]*",\s*placementId:\s*"Plugin\.cmd\./g)].map((m) => m[1]), +].map((id) => `${pluginId}:${id}`))]; +const builtSlices = bannerSlices(mainJs); +log(`build ${buildHash} (${manifest.version}) from ${source}; ${expectedCommands.length} commands; channel ${builtSlices.channel ?? "?"}, slices ${JSON.stringify(builtSlices.on)}`); + +// ── 2. the matrix ───────────────────────────────────────────────────────── +const selected = SETUPS.filter((s) => !only || only.includes(s.id)).sort((a, b) => Number(!!b.slow) - Number(!!a.slow)); +const started = []; // { runDir, profile } +const procsBefore = obsidianProcesses(); +// sandbox.mjs points runs/LATEST at each run it makes; put the owner's back afterwards. +const latestFile = (await common()).LATEST_FILE; +const latestBefore = fs.existsSync(latestFile) ? fs.readFileSync(latestFile, "utf8") : null; + +/** Read-only commands run in C7 (open views; change nothing on disk). */ +const READ_ONLY = ["open-hex-map", "open-hex-table", "open-random-tables"]; +const ERROR_NOTICE = /couldn't|could not|error|failed|unreadable|can't read/i; + +/** data.json, read again if it is caught mid-write (empty or half written). */ +async function readJson(file) { + for (let i = 0; ; i++) { + if (!fs.existsSync(file)) return null; + try { return JSON.parse(fs.readFileSync(file, "utf8")); } catch (e) { if (i >= 20) throw e; await sleep(250); } + } +} + +async function runSetup(setup) { + const why = setup.unavailable?.(); + if (why) { + log(`${setup.id}: SKIPPED (${why})`); + return { id: setup.id, title: setup.title, ok: true, skipped: why, seconds: 0, runDir: null, checks: [] }; + } + const t0 = Date.now(); + const checks = []; + const rec = (check, ok, detail = "", extra = {}) => { + checks.push({ check, ok: !!ok, detail: String(detail).slice(0, 4000), ...extra }); + if (!ok) log(`${setup.id}: FAIL ${check}: ${String(detail).slice(0, 300)}`); + }; + const dir = path.join(work, setup.id); + fs.mkdirSync(dir, { recursive: true }); + let runDir = null, vault = null, sess = null, prepInfo = null; + const ev = (fn, ...args) => sess.page.evaluate(fn, ...args); + const stop = async () => { + if (sess) { await sess.close().catch(() => {}); sess = null; } + if (runDir) { + const r = await stopSandbox(runDir); + if (!r.ok) rec("stop", false, JSON.stringify(r)); + return r; + } + }; + const launch = async () => { + await launchSandbox(runDir); + sess = await connectPage(runDir); + // Expose the page helpers to setup extras (one object, re-sent per launch). + await sess.page.evaluate(`window.__smokePage = { ${Object.entries(P).map(([k, f]) => `${k}: ${f.toString()}`).join(",\n")} };`); + }; + try { + log(`${setup.id}: building fixture`); + const fx = await setup.build(dir); + const created = await createSandbox({ pluginDir: buildDir, seed: fx.seed, pluginData: fx.pluginData, name: `smoke-${setup.id}` }); + runDir = created.runDir; + vault = created.vault; + started.push({ runDir, profile: path.join(runDir, "profile") }); + log(`${setup.id}: sandbox ${runDir}`); + + // ── prep launch (recipe) ── + if (setup.recipe) { + await launch(); + // prepHeld: the recipe runs while a fresh install's stores still wait + // for the setup wizard (F19), as dev/demo-world.mjs does; it releases them. + const r = await ev(setup.prepHeld ? P.waitLayout : P.waitReady, pluginId, 120_000); + if (!r.ready) throw new Error(`prep: plugin not ready ${JSON.stringify(r)}`); + const info = await ev(setup.recipe, pluginId); + prepInfo = info; + await ev(P.settle, pluginId, 2500, 120_000); + const errs = pluginErrors(sess.log, pluginId); + rec("prep", errs.length === 0, errs.length ? errs.map((e) => e.text).join(" || ") : JSON.stringify(info).slice(0, 600)); + await stop(); + if (setup.postPrep) setup.postPrep(vault, info, pluginId); + } + + // ── inputs, before the check launch ── + const dataFile = path.join(vault, ".obsidian", "plugins", pluginId, "data.json"); + const dataIn = await readJson(dataFile); + const truth = setup.migration ? legacyTruth(vault, dataIn) : null; + const snap0 = snapshot(vault, pluginId); + + // ── check launch ── + await launch(); + const ready = await ev(P.waitReady, pluginId, setup.expect.readyMs ?? 120_000); + rec("C1-ready", ready.ready, `stores ready in ${ready.ms} ms`, { ms: ready.ms }); + if (!ready.ready) throw new Error("plugin never became ready"); + await ev(P.settle, pluginId, 3000, setup.expect.readyMs ?? 120_000); + let state = await ev(P.state, pluginId); + const wizardAtLoad = state.wizardOpen; + + // C2: settings resolved and saved; nothing in data.json lost. + { + const disk = await readJson(dataFile); + const probs = []; + if (!disk) probs.push("no data.json written"); + else { + const renamed = { regions: "maps", defaultRegion: "defaultMap" }; + // Dropped on purpose: RETIRED_SETTINGS_KEYS in src/plugin/settingsTidy.ts. + const retired = new Set(["mySetting", "zoomLevel", "hexEditorTerrainExpanded"]); + const lost = Object.keys(dataIn ?? {}).filter((k) => !(k in disk) && !retired.has(k) && !(renamed[k] && renamed[k] in disk)); + if (lost.length) probs.push(`keys lost from data.json: ${lost.join(", ")}`); + const inMaps = new Set((dataIn?.maps ?? dataIn?.regions ?? []).map((m) => m.name)); + const outMaps = new Set((disk.maps ?? []).map((m) => m.name)); + const goneMaps = [...inMaps].filter((m) => !outMaps.has(m)); + if (goneMaps.length) probs.push(`maps lost from data.json: ${goneMaps.join(", ")}`); + } + rec("C2-settings", probs.length === 0, probs.join("; ") || `${state.maps.length} maps, palettes ${state.palettes.length}, kinds ${state.mapKinds}`); + } + + // C3: every map opens and renders. + const opens = []; + let firstOpen = null; + { + const budget = setup.expect.openMs ?? 20_000; + const probs = []; + for (const m of state.maps) { + const r = await ev(P.openMap, pluginId, m.name, budget + 5000); + firstOpen ??= r; + opens.push({ map: m.name, ...r }); + if (r.active !== m.name) probs.push(`${m.name}: view shows ${r.active}`); + // Deleted by hand (SM-DEL): the view shows the missing empty state. + else if (m.missing) { if (!r.missingState) probs.push(`${m.name}: missing, but no missing-map state shown`); } + else if (m.broken) probs.push(`${m.name}: map note unreadable`); + else if (r.hexes === 0 && r.canvas === 0) probs.push(`${m.name}: nothing rendered`); + else if (!m.overworld && r.hexes !== r.expected) probs.push(`${m.name}: ${r.hexes} hexes, expected ${r.expected}`); + if (r.ms > budget) probs.push(`${m.name}: ${r.ms} ms > ${budget} ms`); + } + const slow = opens.slice().sort((a, b) => b.ms - a.ms)[0]; + rec("C3-maps-open", probs.length === 0 && opens.length > 0, probs.join("; ") || `${opens.length} maps opened; slowest ${slow?.map} ${slow?.ms} ms`, { opens: opens.map((o) => [o.map, o.ms, o.hexes]) }); + } + await ev(P.settle, pluginId, 2500, 60_000); + + // C4: untouched data unchanged on disk (migration rewrites checked separately). + const snap1 = snapshot(vault, pluginId); + { + const d = diff(snap0, snap1); + const pluginRel = `.obsidian/plugins/${pluginId}/`; + const migrated = new Set(truth ? Object.entries(truth.notes).filter(([, t]) => t.dataKeys.length).map(([p]) => p) : []); + // Palette notes in an older format are upgraded on load (new columns, + // the Path types table): allowed when every terrain row is unchanged. + const upgraded = [], paletteProbs = []; + for (const p of d.changed) { + if (snap0[p]?.text === undefined) continue; + const probs = verifyPaletteUpgrade(snap0[p].text, fs.readFileSync(path.join(vault, p), "utf8")); + if (probs.length) paletteProbs.push(`${p}: ${probs.slice(0, 4).join(", ")}`); else upgraded.push(p); + } + if (upgraded.length || paletteProbs.length) rec("M-palettes", paletteProbs.length === 0, paletteProbs.join("; ") || `${upgraded.length} palette notes upgraded, every terrain row kept: ${upgraded.join(", ")}`); + // Note-format upgrades (NF1–NF3) may rewrite a note once, backed up first. + const nfBackups = noteFormatBackups(vault, pluginId); + const reformatted = d.changed.filter((p) => nfBackups[p] !== undefined && nfBackups[p] === snap0[p]?.h); + if (reformatted.length) rec("M-note-formats", true, `${reformatted.length} notes rewritten to the new note formats, each backed up first: ${reformatted.slice(0, 6).join(", ")}${reformatted.length > 6 ? ", …" : ""}`); + // Older tables get roll ranges once on the first start, silently, backed up first (DJ-Q6). + const trBackups = tableRangeBackups(vault, pluginId); + const ranged = d.changed.filter((p) => trBackups[p] !== undefined && trBackups[p] === snap0[p]?.h); + if (ranged.length) rec("M-table-ranges", true, `${ranged.length} tables got roll ranges, each backed up first: ${ranged.slice(0, 6).join(", ")}${ranged.length > 6 ? ", …" : ""}`); + const allowed = (p) => p === `${pluginRel}data.json` || migrated.has(p) || upgraded.includes(p) || reformatted.includes(p) || ranged.includes(p); + const changed = d.changed.filter((p) => !allowed(p)); + // A backup rewritten with the same bytes loses nothing; other bytes would ("changed"). + const touched = d.touched.filter((p) => !allowed(p) && !p.startsWith(`${pluginRel}backups/`)); + const removed = d.removed.filter((p) => !allowed(p)); + const ok = changed.length === 0 && removed.length === 0 && touched.length === 0; + rec("C4-untouched", ok, + ok ? `${Object.keys(snap0).length} files unchanged; ${d.added.length} new (${d.added.slice(0, 6).join(", ")}${d.added.length > 6 ? ", …" : ""}); ${migrated.size} migrated notes checked below` + : `changed: ${changed.slice(0, 15).join(", ")}${changed.length > 15 ? ` (+${changed.length - 15})` : ""}; rewritten same bytes: ${touched.slice(0, 15).join(", ")}${touched.length > 15 ? ` (+${touched.length - 15})` : ""}; removed: ${removed.slice(0, 15).join(", ")}`, + { added: d.added.length, changed: changed.length, touched: touched.length, removed: removed.length }); + } + + // Migration: map notes written, data moved exactly, backups, paths. + if (truth) { + const store = await ev(P.dumpStore, pluginId); + const vm = verifyMigration(vault, truth, store); + rec("M-data", vm.problems.length === 0, vm.problems.length ? vm.problems.slice(0, 12).join("; ") : `${vm.hexesChecked} hexes match, ${vm.cleaned} notes cleaned, ${vm.bodiesIdentical}/${vm.notesChecked} bodies identical`); + const hexFolder = (dataIn.hexFolder ?? "").replace(/^\/+|\/+$/g, ""); + const noteProbs = []; + for (const m of Object.keys(truth.maps)) { + const np = path.join(vault, hexFolder, m, `_${m}.md`); + if (!fs.existsSync(np)) { noteProbs.push(`${m}: no map note`); continue; } + const head = fs.readFileSync(np, "utf8").slice(0, 400); + if (!/hexmaker-map:\s*\d+/.test(head)) noteProbs.push(`${m}: map note has no hexmaker-map format`); + } + rec("M-map-notes", noteProbs.length === 0, noteProbs.join("; ") || `${Object.keys(truth.maps).length} map notes written`); + const cleanedCount = Object.values(truth.notes).filter((t) => t.dataKeys.length).length; + const b = verifyBackups(vault, pluginId, noteTextHashes(truth)); + rec("M-backups", b.mismatches === 0 && b.notes >= cleanedCount && b.backupDirs > 0, `${b.notes} notes backed up (needed ${cleanedCount}), ${b.mismatches} mismatches, ${b.mapJson} map backups`); + const ps = await ev(P.pathState, pluginId); + const pathProbs = []; + let chains = 0, paths = 0; + for (const m of dataIn.maps ?? []) { + if (!(m.pathChains ?? []).some((c) => (c.hexes ?? []).length > 1)) continue; + chains += m.pathChains.length; + const s = ps[m.name]; + if (!s || s.paths === 0) pathProbs.push(`${m.name}: no paths after migration`); + else if (typeof s.resolved !== "number" || s.resolved === 0) pathProbs.push(`${m.name}: paths don't resolve (${s.resolved})`); + paths += s?.paths ?? 0; + } + rec("M-paths", pathProbs.length === 0, pathProbs.join("; ") || `${chains} legacy chains → ${paths} paths, all resolve`); + } + + // C7: registered commands; read-only ones run cleanly. + { + state = await ev(P.state, pluginId); + const missing = expectedCommands.filter((c) => !state.commands.includes(c)); + const errBefore = pluginErrors(sess.log, pluginId).length; + const ran = []; + for (const c of READ_ONLY) { + const id = `${pluginId}:${c}`; + if (!state.commands.includes(id)) continue; + ran.push(`${c}: ${await ev(P.runCommand, id)}`); + await ev(P.closeModals); + } + await sleep(500); + const errs = pluginErrors(sess.log, pluginId).slice(errBefore); + rec("C7-commands", missing.length === 0 && errs.length === 0, `${state.commands.length}/${expectedCommands.length} registered${missing.length ? `; missing ${missing.join(", ")}` : ""}; ran ${ran.join(", ")}${errs.length ? `; errors: ${errs.map((e) => e.text).join(" || ")}` : ""}`); + } + + // Setup-specific checks. + if (setup.extra) { + const ctx = { pluginId, state, ev, log: sess.log, readyMs: ready.ms, firstOpen, wizardAtLoad, runDir, vault, snap0, prepInfo, slices: builtSlices.on }; + for (const c of await setup.extra(ctx)) rec(c.check, c.ok, c.detail); + state = await ev(P.state, pluginId); + } + + // C6 + C8 on the smallest plain map. + const plain = state.maps.filter((m) => !m.overworld && m.cols * m.rows > 0).sort((a, b) => a.cols * a.rows - b.cols * b.rows); + const target = plain.find((m) => m.hexes > 0) ?? plain[0]; + if (!target) rec("C6-paint", false, "no plain map to paint on"); + else { + const r = await ev(P.paintRoundTrip, pluginId, target.name); + rec("C6-paint", r.ok, `${target.name}: ${[...(r.steps ?? []), ...(r.problems ?? []), r.skipped ?? "", r.error ?? ""].filter(Boolean).join("; ")}${r.noteUnchanged === false ? "; map note text differs after undo (data same)" : ""}`); + if (!setup.skipModeLocks) { + const l = await ev(P.modeLocks, pluginId, target.name); + rec("C8-mode-locks", l.ok, `${target.name}: ${[...l.steps, ...l.problems].join("; ")}`, { gaps: l.gaps }); + for (const g of l.gaps ?? []) checks.push({ check: "C8-gap", ok: true, gap: true, detail: g }); + // C9: solo play (party step, visited, play log), cleaned up after. + const pp = await ev(P.partyPlay, pluginId, target.name); + rec("C9-party-play", pp.ok, `${target.name}: ${[...pp.steps, ...pp.problems].join("; ")}`); + } + } + + // C1: no plugin errors, no error notices, over the whole check launch. + { + const errs = pluginErrors(sess.log, pluginId); + const others = sess.log.filter((e) => e.level !== "warning" && !errs.includes(e)); + const ns = (await ev(P.notices)).filter((n) => ERROR_NOTICE.test(n)); + rec("C1-no-errors", errs.length === 0 && ns.length === 0, + `${errs.length} plugin errors${errs.length ? ": " + errs.slice(0, 5).map((e) => e.text.split("\n")[0]).join(" || ") : ""}; error notices: ${ns.join(" | ") || "none"}; other console errors (not the plugin's): ${others.length}`, + { pluginErrors: errs.slice(0, 20), otherErrors: others.slice(0, 10).map((e) => e.text.slice(0, 300)) }); + } + + // ── C5: restart rewrites nothing ── + const storeBefore = canon(await ev(P.dumpStore, pluginId)); + await ev(P.settle, pluginId, 3000, 60_000); + await stop(); + const snapA = snapshot(vault, pluginId); + const dataA = await readJson(dataFile); + await launch(); + const r2 = await ev(P.waitReady, pluginId, setup.expect.readyMs ?? 120_000); + await ev(P.settle, pluginId, 4000, 90_000); + const storeAfter = canon(await ev(P.dumpStore, pluginId)); + const state2 = await ev(P.state, pluginId); + const errs2 = pluginErrors(sess.log, pluginId); + await stop(); + const snapB = snapshot(vault, pluginId); + const dataB = await readJson(dataFile); + { + const d = diff(snapA, snapB); + const probs = []; + if (!r2.ready) probs.push("not ready after restart"); + const dataRel = `.obsidian/plugins/${pluginId}/data.json`; + const dataOneTime = d.changed.includes(dataRel) && oneTimeOnly(dataA, dataB); + const changed = dataOneTime ? d.changed.filter((p) => p !== dataRel) : d.changed; + if (changed.length) probs.push(`changed: ${changed.slice(0, 12).join(", ")}`); + if (changed.includes(dataRel)) probs.push(`data.json: ${jsonDiff(dataA, dataB).join("; ")}`); + if (dataOneTime) checks.push({ check: "C5-one-time", ok: true, detail: `data.json one-time settings written on restart: ${jsonDiff(dataA, dataB).join("; ")}` }); + if (d.touched.length) probs.push(`rewritten same bytes: ${d.touched.slice(0, 12).join(", ")}`); + if (d.added.length) probs.push(`new: ${d.added.slice(0, 12).join(", ")}`); + if (d.removed.length) probs.push(`removed: ${d.removed.slice(0, 12).join(", ")}`); + if (storeAfter !== storeBefore) probs.push(`map data differs after restart: ${jsonDiff(JSON.parse(storeBefore), JSON.parse(storeAfter)).join("; ")}`); + if (errs2.length) probs.push(`plugin errors: ${errs2.slice(0, 3).map((e) => e.text.split("\n")[0]).join(" || ")}`); + rec("C5-restart", probs.length === 0, probs.join("; ") || `0 files rewritten, map data the same (ready ${r2.ms} ms)`); + } + } catch (e) { + rec("crash", false, e.stack ?? String(e)); + if (sess) await shot(sess.page, runDir, `${setup.id}-crash`); + } finally { + try { await stop(); } catch (e) { rec("stop", false, String(e)); } + } + const ok = checks.every((c) => c.ok); + log(`${setup.id}: ${ok ? "PASS" : "FAIL"} in ${Math.round((Date.now() - t0) / 1000)} s`); + return { id: setup.id, title: setup.title, ok, seconds: Math.round((Date.now() - t0) / 1000), runDir, checks }; +} + +async function pool(items, n, fn) { + const out = new Array(items.length); + let next = 0; + const worker = async () => { while (next < items.length) { const i = next++; out[i] = await fn(items[i]); } }; + await Promise.all(Array.from({ length: Math.min(n, items.length) }, worker)); + return out; +} + +const t0 = Date.now(); +log(`${selected.length} setups, ${jobs} at a time (${jobsPick.reason}): ${selected.map((s) => s.id).join(", ")}`); +let results; +const onSignal = async () => { + log("interrupted: stopping sandboxes"); + for (const s of started) await stopSandbox(s.runDir).catch(() => {}); + process.exit(130); +}; +process.on("SIGINT", onSignal); +try { + results = await pool(selected, jobs, runSetup); +} finally { + // Belt and braces: every run stopped (stop is idempotent). + for (const s of started) await stopSandbox(s.runDir).catch(() => {}); +} + +if (latestBefore !== null) fs.writeFileSync(latestFile, latestBefore); + +// ── 3. none of this suite's Obsidian processes left ────────────────────── +// Only processes of runs this suite created count. Other Obsidian processes +// (the owner's, another session's smoke run) can start or stop at any time +// while the suite runs; they are reported, never compared. +await sleep(1000); +const procsAfter = obsidianProcesses(); +const mineProfiles = started.map((s) => s.profile.toLowerCase()); +const isMine = (p) => mineProfiles.some((m) => p.cmd.toLowerCase().includes(m)); +const otherBefore = procsBefore.filter((p) => p.main && !isMine(p)); +const otherAfter = procsAfter.filter((p) => p.main && !isMine(p)); +const leftMine = procsAfter.filter(isMine); +const safety = { + // Information only (see above). + otherObsidianBefore: otherBefore.length, + otherObsidianAfter: otherAfter.length, + sandboxProcessesLeft: leftMine.length, + ok: leftMine.length === 0, +}; + +// ── 4. record ──────────────────────────────────────────────────────────── +const allOk = results.every((r) => r.ok) && safety.ok; +const record = { + ok: allOk, + ts: new Date().toISOString(), + commit: git("rev-parse", "HEAD"), + branch: git("rev-parse", "--abbrev-ref", "HEAD"), + dirty: (git("status", "--porcelain", "--untracked-files=no") ?? "") !== "", + buildHash, + buildSource: path.resolve(source), + // The features under test: the spec asked for (null: the build as given) and what the build's banner says. + slices: { spec: sliceSpec, channel: builtSlices.channel, on: builtSlices.on }, + version: manifest.version, + seconds: Math.round((Date.now() - t0) / 1000), + jobs, + jobsReason: jobsPick.reason, + setups: results.map((r) => r.id), + safety, + results: Object.fromEntries(results.map((r) => [r.id, { ok: r.ok, ...(r.skipped ? { skipped: r.skipped } : {}), title: r.title, seconds: r.seconds, runDir: r.ok && !keep ? null : r.runDir, checks: r.checks }])), +}; +fs.writeFileSync(path.join(HERE, stamps.run), JSON.stringify(record, null, 2)); +if (allOk) fs.writeFileSync(path.join(HERE, stamps.pass), JSON.stringify(record, null, 2)); + +// Passed runs are deleted (the real-data copy is ~150 MB); failed ones stay for a look. +if (!keep) { + for (const r of results) if (r.ok && r.runDir) fs.rmSync(r.runDir, { recursive: true, force: true }); + fs.rmSync(work, { recursive: true, force: true }); +} + +console.log("\n── smoke matrix ─────────────────────────────────────────────"); +for (const r of results) { + const fails = r.checks.filter((c) => !c.ok); + const gaps = r.checks.filter((c) => c.gap); + if (r.skipped) { console.log(`SKIP ${r.id.padEnd(15)} ${r.skipped}`); continue; } + console.log(`${r.ok ? "PASS" : "FAIL"} ${r.id.padEnd(15)} ${String(r.seconds).padStart(4)} s ${r.checks.length} checks${gaps.length ? `, ${gaps.length} known gap(s)` : ""}`); + for (const f of fails) console.log(` ✗ ${f.check}: ${f.detail.split("\n")[0].slice(0, 400)}`); +} +console.log(`sandbox processes left: ${safety.sandboxProcessesLeft} (other Obsidian, not counted: ${safety.otherObsidianBefore} before, ${safety.otherObsidianAfter} after)`); +const skipped = results.filter((r) => r.skipped).length; +console.log(`${allOk ? "SMOKE PASSED" : "SMOKE FAILED"}${skipped ? ` (${skipped} setup(s) SKIPPED)` : ""} (${record.seconds} s, build ${buildHash}${builtSlices.channel ? ` ${builtSlices.channel}` : ""}, commit ${record.commit?.slice(0, 7)}${record.dirty ? " +dirty" : ""}) → ${path.join(HERE, allOk ? stamps.pass : stamps.run)}`); +process.exit(allOk ? 0 : 1); diff --git a/dev/smoke/setups.mjs b/dev/smoke/setups.mjs new file mode 100644 index 00000000..25c9b991 --- /dev/null +++ b/dev/smoke/setups.mjs @@ -0,0 +1,750 @@ +/** + * The vault setups of the smoke matrix (plan-work-modes §3.1, F1–F9; F10, the Simple-level setup, went with the feature level). + * Every fixture is built from code into a temp folder, or copied; never the + * main vault. A setup can: + * build(dir) write seed notes / a data.json into `dir` → { seed?, pluginData? } + * recipe an in-page function run in a first "prep" launch (makes + * maps through the plugin's own API), then Obsidian stops + * postPrep(vault, prepInfo) change the vault on disk after prep + * migration the check launch migrates legacy hex notes (verified) + * expect what the checks assert for this setup + * extra setup-specific checks in the check launch + */ +import fs from "node:fs"; +import path from "node:path"; +import { hostPath } from "./lib/obsidian.mjs"; + +export const REAL_SEED = process.env.SMOKE_REAL_SEED ?? hostPath("C:/Users/markr/work/tmp/migtest/seedF"); +export const REAL_DATA = process.env.SMOKE_REAL_DATA ?? hostPath("C:/Users/markr/Documents/KB/journal/.obsidian/plugins/duckmage-plugin/data.json"); +export const MARKER = ".hexmaker-sandbox"; + +const write = (file, text) => { fs.mkdirSync(path.dirname(file), { recursive: true }); fs.writeFileSync(file, text); }; +const writeJson = (file, obj) => write(file, JSON.stringify(obj, null, 2)); +const seedDir = (dir) => { const s = path.join(dir, "seed"); fs.mkdirSync(s, { recursive: true }); write(path.join(s, MARKER), "smoke suite sandbox\n"); return s; }; + +// ── F2: a small vault as plugin 1.5.5 left it ───────────────────────────── + +const V155_TERRAINS = [ + { name: "ocean", color: "#29507f", category: "sea" }, + { name: "grass", color: "#69a168", icon: "bw-grassland.png", category: "lowlands" }, + { name: "hills", color: "#e0e8a1", icon: "bw-hills.png", category: "lowlands" }, + { name: "forest", color: "#2f6b3a", category: "forest" }, + { name: "mountains", color: "#8b7d6b", category: "mountains" }, + { name: "snow", color: "#e0f2fe", category: "snow" }, +]; + +/** Hex note text in the 1.5.5 shape: map data in frontmatter, old template body. */ +function v155Note(x, y, fm, body = "") { + const lines = ["---"]; + for (const [k, v] of Object.entries(fm)) { + if (Array.isArray(v)) { lines.push(`${k}:`); for (const i of v) lines.push(` - ${i}`); } + else lines.push(`${k}: ${v}`); + } + lines.push("---", "", `# Hex ${x}, ${y}`, "", "**Region:**", "**Terrain:**", "", "### description", "", body, "", "### Towns", "", "### Dungeons", "", "### Features", "", "### Quests", "", "### Factions", "", "### Encounters Table", ""); + return lines.join("\n"); +} + +function buildV155(dir) { + const seed = seedDir(dir); + const hexRoot = path.join(seed, "world", "hexes"); + const maps = [ + { name: "coast", cols: 8, rows: 6 }, + { name: "north", cols: 6, rows: 5 }, + { name: "harbour", cols: 4, rows: 4 }, + ]; + const terr = V155_TERRAINS.map((t) => t.name); + for (const m of maps) { + for (let y = 0; y < m.rows; y++) for (let x = 0; x < m.cols; x++) { + const i = x * 7 + y * 3 + m.name.length; + if (i % 5 === 4) continue; // some hexes have no note at all + const fm = { terrain: terr[i % terr.length] }; + if (i % 7 === 0) fm.icon = "bw-hills.png"; + if (i % 11 === 0) fm["gm-icons"] = ["I_Ruins.png", "I_Monolith.png"]; + if (m.name === "coast" && x < 3) fm.region = "Saltmarsh"; + if (i % 13 === 0) fm.locked = true; + if (i % 9 === 0) { fm.tags = "[hex, smoke]"; fm.aliases = `[Spot ${x}-${y}]`; } + const body = i % 4 === 0 ? `Old notes for ${m.name} ${x},${y}. Keep me exactly.` : ""; + write(path.join(hexRoot, m.name, `${x}_${y}.md`), v155Note(x, y, fm, body)); + } + } + // The harbour is a submap of coast 2_2 (1.5.5: duckmage-submap on the hex note). + write(path.join(hexRoot, "coast", "2_2.md"), v155Note(2, 2, { terrain: "grass", "duckmage-submap": "harbour" }, "The harbour town.")); + // A hex note with no frontmatter at all, and one with a typed body. + write(path.join(hexRoot, "north", "5_4.md"), "# Hex 5, 4\n\nJust prose, no frontmatter.\n"); + write(path.join(seed, "world", "Lore.md"), "# Lore\n\nA note that isn't a hex. [[coast]]\n"); + const data = { + mySetting: "default", + worldFolder: "world", + hexFolder: "world/hexes", + townsFolder: "", dungeonsFolder: "", questsFolder: "", featuresFolder: "", iconsFolder: "", + templatePath: "", + hexGap: "0.2", + terrainPalettes: [{ name: "Default", terrains: V155_TERRAINS }], + maps: [ + { + name: "coast", paletteName: "Default", gridSize: { cols: 8, rows: 6 }, gridOffset: { x: 0, y: 0 }, staggerOffset: "odd", + pathChains: [ + { typeName: "Road", hexes: ["0_1", "1_1", "2_2", "3_2", "4_3"] }, + { typeName: "River", hexes: ["6_0", "6_1", "5_2", "5_3"] }, + { typeName: "Road", hexes: ["2_2"] }, + ], + }, + { name: "north", paletteName: "Default", gridSize: { cols: 6, rows: 5 }, gridOffset: { x: 0, y: 0 }, pathChains: [{ typeName: "River", hexes: ["0_0", "1_0", "2_1"] }] }, + { name: "harbour", paletteName: "Default", gridSize: { cols: 4, rows: 4 }, gridOffset: { x: 0, y: 0 }, pathChains: [] }, + ], + zoomLevel: 1, + pathTypes: [ + { name: "Road", color: "#a16207", width: 5, lineStyle: "solid", routing: "through" }, + { name: "River", color: "#3b82f6", width: 6, lineStyle: "solid", routing: "through" }, + ], + hexOrientation: "flat", + staggerOffset: "odd", + tablesFolder: "world/tables", + factionsFolder: "", regionsFolder: "", + defaultTableDice: 100, + rollTableExcludedFolders: ["terrain"], + encounterTableExcludedFolders: ["terrain"], + defaultMap: "coast", + workflowsFolder: "", + setupComplete: true, + setupDismissed: false, + roadColor: "#a16207", + riverColor: "#3b82f6", + savedWith: "1.5.5", + }; + const pluginData = path.join(dir, "data.json"); + writeJson(pluginData, data); + return { seed, pluginData }; +} + +// ── in-page recipes (self-contained; run with (pluginId, args)) ─────────── + +function recipeSpace(id) { + return (async () => { + const p = window.app.plugins.plugins[id]; + p.settings.setupComplete = true; + window.app.workspace.getLeavesOfType("duckmage-setup-wizard").forEach((l) => l.detach()); + p.settings.mapKinds = ["space"]; + // As the wizard does (SP3): install what the picked map types ship, drop + // the fresh install's untouched fantasy palettes. + p.settings.setupComplete = false; + if (p.applyKindContent) await p.applyKindContent({ fromSetup: true }); + else p.onMapKindsChanged?.(); + p.settings.setupComplete = true; + const has = (n) => p.settings.terrainPalettes.some((x) => x.name === n); + const sector = has("Space - Sector") ? "Space - Sector" : await p.installPalettePreset("Space - Sector"); + const system = has("Space - System") ? "Space - System" : await p.installPalettePreset("Space - System"); + const made = []; + const mk = async (name, cols, rows, pal, parent) => { + const r = await p.createNewMap({ name, cols, rows, palette: pal, quiet: true, ...(parent ? { parent } : {}) }); + if ("error" in r) throw new Error(r.error); + made.push(r.name); + return r.name; + }; + const s = await mk("Rim Sector", 10, 8, sector); + const pal = p.getMapPalette(s).map((t) => t.name); + p.mapStore.setMany(s, [["2_2", { terrain: pal[1] ?? pal[0] }], ["3_3", { terrain: pal[2] ?? pal[0] }], ["5_4", { terrain: pal[0] }]]); + const sys = await mk("Vega System", 9, 9, system, { map: s, hex: "2_2" }); + await p.linkSubmap(s, 2, 2, sys); + // Planets open on Space - Planet (the system's submap defaults), else the old child palette. + const planetPal = p.getPaletteByName(system)?.submapDefaults?.["terrestrial planet"]?.palette ?? p.childPaletteFor(sys); + const planet = await mk("Vega IV", 8, 6, planetPal, { map: sys, hex: "4_4" }); + await p.linkSubmap(sys, 4, 4, planet); + await p.saveSettings(); + await p.mapStore.flush(); + const biomeFolder = p.biomeStore?.folder?.(); + const biomeNotes = biomeFolder ? window.app.vault.getMarkdownFiles().filter((f) => f.path.startsWith(biomeFolder + "/")).length : 0; + return { made, palettes: p.settings.terrainPalettes.map((x) => x.name), planetPal, defaultPalette: p.settings.defaultPalette, biomeNotes }; + })(); +} + +/** + * Built as dev/demo-world.mjs builds it: on a fresh install, while the + * stores still wait for the setup wizard (F19, setup prepHeld), then the + * wizard closes and the stores start. Incident 2026-10-14: every region + * lost its kind, world slot and arrival here (notes written at creation + * only, then read back over memory), and the overworld showed no regions. + */ +function recipeOverworld(id) { + return (async () => { + const p = window.app.plugins.plugins[id]; + const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); + const t0 = Date.now(); + while (!p.devTools && Date.now() - t0 < 30000) await sleep(300); + if (!p.devTools) throw new Error("devTools missing (sandbox marker?)"); + const heldAtBuild = !!p.startupWritesHeld && !p.mapStore.isReady(); + const demo = await p.devTools.buildDemoWorld({ seed: 7 }); + await p.saveSettings(); + await p.mapStore.flush(); + // The wizard closes: the stores start now. + window.app.workspace.getLeavesOfType("duckmage-setup-wizard").forEach((l) => l.detach()); + p.releaseStartupWrites?.(); + while (!p.mapStore.isReady() && Date.now() - t0 < 120_000) await sleep(250); + await p.mapStore.flush(); + const mine = p.settings.maps.filter((m) => m.parent?.map === demo.overworld); + const regionsAfterStart = mine.filter((m) => m.submapKind === "region" && m.world && m.arrival).length; + let regionNotes = 0; + for (const m of mine) { + const text = (await p.mapStore.readNoteText(m.name)) ?? ""; + if (/\nsubmap-kind: region\r?\n/.test(text) && /\nworld: /.test(text) && /\narrival: /.test(text)) regionNotes++; + } + await p.showMap(demo.overworld); + await sleep(2500); + const layerRegions = p.devTools.overworldStats?.()?.[0]?.regions ?? null; + return { overworld: demo.overworld, regions: demo.regions, hexes: demo.overworldHexes, heldAtBuild, regionsAfterStart, regionNotes, layerRegions }; + })(); +} + +function recipeNeighbours(id) { + return (async () => { + const p = window.app.plugins.plugins[id]; + p.settings.setupComplete = true; + window.app.workspace.getLeavesOfType("duckmage-setup-wizard").forEach((l) => l.detach()); + const pal = p.settings.defaultPalette ?? p.settings.terrainPalettes[0].name; + const wid = "wsmoke1"; + const names = []; + const slots = [[0, 0], [1, 0], [0, 1], [1, 1]]; + for (const [i, [cx, cy]] of slots.entries()) { + // Legacy worlds: every map numbers its own hexes from 0 (no shared coordinates). + const r = await p.createNewMap({ name: `Shire ${String.fromCharCode(65 + i)}`, cols: 10, rows: 8, palette: pal, stagger: "odd", quiet: true }); + if ("error" in r) throw new Error(r.error); + p.getMap(r.name).world = { id: wid, cx, cy }; + const terr = p.getMapPalette(r.name).map((t) => t.name); + const cells = []; + for (let x = 0; x < 10; x++) for (let y = 0; y < 8; y++) if ((x + y + i) % 3 === 0) cells.push([`${x}_${y}`, { terrain: terr[(x * 3 + y + i) % terr.length] }]); + p.mapStore.setMany(r.name, cells); + names.push(r.name); + } + await p.saveSettings(); + await p.mapStore.flush(); + return { maps: names }; + })(); +} + +function recipeCustomPalette(id) { + return (async () => { + const p = window.app.plugins.plugins[id]; + const app = window.app; + p.settings.setupComplete = true; + app.workspace.getLeavesOfType("duckmage-setup-wizard").forEach((l) => l.detach()); + const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); + p.settings.terrainPalettes.push({ + name: "Moorland", + terrains: [ + { name: "bog", color: "#556b2f" }, + { name: "crag", color: "#7a7a7a" }, + { name: "heath", color: "#9a7b9a", type: "grassland" }, + { name: "tarn", color: "#24466b", type: "water" }, + { name: "barrow", color: "#3b2f2f" }, + ], + }); + p.settings.defaultPalette = "Moorland"; + await p.saveSettings(); + await sleep(1500); + // Delete every other palette's note: the store drops them from settings. + for (const pal of p.settings.terrainPalettes.map((x) => x.name)) { + if (pal === "Moorland") continue; + const f = p.paletteStore.noteFor(pal); + if (f) await app.vault.delete(f); + await sleep(300); + } + await sleep(1500); + // The default map from a fresh install (on a default palette) goes too. + for (const m of [...p.settings.maps]) if (m.paletteName !== "Moorland") p.settings.maps.splice(p.settings.maps.indexOf(m), 1); + const r = await p.createNewMap({ name: "The Moor", cols: 9, rows: 7, palette: "Moorland", quiet: true }); + if ("error" in r) throw new Error(r.error); + p.settings.defaultMap = r.name; + const terr = ["bog", "crag", "heath", "tarn", "barrow"]; + const cells = []; + for (let x = 0; x < 9; x++) for (let y = 0; y < 7; y++) if ((x * y) % 2 === 0) cells.push([`${x}_${y}`, { terrain: terr[(x + y) % 5] }]); + p.mapStore.setMany(r.name, cells); + await p.saveSettings(); + await p.mapStore.flush(); + return { palettes: p.settings.terrainPalettes.map((x) => x.name), map: r.name }; + })(); +} + +function recipeDeleted(id) { + return (async () => { + const p = window.app.plugins.plugins[id]; + p.settings.setupComplete = true; + window.app.workspace.getLeavesOfType("duckmage-setup-wizard").forEach((l) => l.detach()); + const pal = p.settings.defaultPalette ?? p.settings.terrainPalettes[0].name; + const made = []; + for (const n of ["Gone One", "Gone Two"]) { + const r = await p.createNewMap({ name: n, cols: 8, rows: 6, palette: pal, quiet: true }); + if ("error" in r) throw new Error(r.error); + const terr = p.getMapPalette(r.name).map((t) => t.name); + p.mapStore.setMany(r.name, [["1_1", { terrain: terr[0] }], ["2_2", { terrain: terr[1] }], ["3_3", { terrain: terr[2] }]]); + made.push(r.name); + } + const types = p.getMapPathTypes(made[0]); + if (types.length) p.mapStore.setPaths(made[0], [{ name: "Old road", typeName: types[0].name, branches: [{ anchors: ["0_1", "4_3"] }] }]); + await p.saveSettings(); + await p.mapStore.flush(); + return { + made, + folders: [p.settings.hexFolder, p.paletteStore.folder(), p.settings.tablesFolder, p.settings.workflowsFolder, p.templatesFolder?.()].filter(Boolean), + }; + })(); +} + +function recipeManyMaps(id) { + return (async () => { + const p = window.app.plugins.plugins[id]; + p.settings.setupComplete = true; + window.app.workspace.getLeavesOfType("duckmage-setup-wizard").forEach((l) => l.detach()); + const pal = p.settings.defaultPalette ?? p.settings.terrainPalettes[0].name; + const made = []; + const errors = []; + const mk = async (raw, parent) => { + const r = await p.createNewMap({ name: raw, cols: 6, rows: 5, palette: pal, quiet: true, ...(parent ? { parent: { map: parent, hex: "2_2" } } : {}) }); + if ("error" in r) { errors.push(`${raw}: ${r.error}`); return null; } + const terr = p.getMapPalette(r.name).map((t) => t.name); + p.mapStore.setMany(r.name, [["0_0", { terrain: terr[made.length % terr.length] }], ["2_2", { terrain: terr[(made.length + 1) % terr.length] }]]); + if (parent) await p.linkSubmap(parent, 2, 2, r.name); + made.push(r.name); + return r.name; + }; + // Duplicate-ish names: same words, different case/spacing/punctuation. + const tops = ["Ash Vale", "Ash Vale!", "ash vale 2", "Ashvale", "Ash-Vale (old)", "Brine", "BRINE", "Brine 1", "Cinder", "Cinder Isle", + "Dune", "Dunes", "Elder", "Elder Wood", "Fen", "Fenn", "Gale", "Gale's End", "Hollow", "Hollows"]; + const topNames = []; + for (const t of tops) { const n = await mk(t); if (n) topNames.push(n); } + // Names that slug to a folder already taken are refused (as they should be): top up to 20. + for (let i = 1; topNames.length < 20; i++) { const n = await mk(`Isle ${i}`); if (n) topNames.push(n); } + // Nested locations four deep under the first 15 tops (15 × 4 = 60). + for (const top of topNames.slice(0, 15)) { + let parent = top; + for (let d = 1; d <= 4; d++) parent = (await mk(`${top} L${d}`, parent)) ?? parent; + } + await p.saveSettings(); + await p.mapStore.flush(); + return { made: made.length, errors }; + })(); +} + +// ── setup-specific checks (Node side; ctx.ev(fn, ...args) evaluates in page) ── + +async function freshExtra(ctx) { + const out = []; + const st = ctx.state; + out.push({ check: "F1-wizard", ok: st.wizardOpen > 0, detail: `setup wizard leaves: ${st.wizardOpen}` }); + // F19: nothing is written while the wizard still asks where the world goes. + const held = await ctx.ev(() => window.__smoke.held ?? null); + out.push({ check: "F1-nothing-before-folder", ok: !!held?.held && held.writes.length === 0, detail: held ? `held; wrote ${held.writes.join(", ") || "nothing"} meanwhile` : "stores were not held" }); + // Create a map + paint through the API: only the map note may be written. + const r = await ctx.ev((id) => (async () => { + const app = window.app, p = app.plugins.plugins[id]; + const t = Date.now(); + const pal = p.settings.defaultPalette ?? p.settings.terrainPalettes[0].name; + const res = await p.createNewMap({ name: "Smoke Fresh", cols: 8, rows: 6, palette: pal, quiet: true }); + if ("error" in res) return { error: res.error }; + const terr = p.getMapPalette(res.name).map((x) => x.name); + p.mapStore.set(res.name, "1_1", { terrain: terr[0] }); + p.mapStore.set(res.name, "2_3", { terrain: terr[1] }); + await p.mapStore.flush(); + await new Promise((r2) => setTimeout(r2, 1500)); + const files = [...new Set(window.__smoke.writes.filter((w) => w.t >= t && /\.md$/.test(w.path)).map((w) => w.path))]; + const note = p.mapStore.notePath(res.name); + // First hex note: links its map note; its terrain is a copy of the map's (hex-note properties, MG4). + await p.createHexNote(1, 1, res.name); + const hexPath = p.hexPath(1, 1, res.name); + const text = (await app.vault.adapter.exists(hexPath)) ? await app.vault.adapter.read(hexPath) : null; + return { map: res.name, files, note, hexPath, hasLink: !!text && /^map:\s*"\[\[_/m.test(text), terrainProp: text ? (/^terrain\s*:\s*"?([^"\r\n]*)"?\s*$/m.exec(text)?.[1] ?? null) : null, terrain: terr[0] }; + })(), ctx.pluginId); + if (r.error) out.push({ check: "F1-create-paint", ok: false, detail: r.error }); + else { + const others = r.files.filter((f) => f !== r.note); + out.push({ check: "F1-create-paint", ok: r.files.includes(r.note) && others.length === 0, detail: `wrote ${r.files.join(", ") || "(nothing)"}` }); + out.push({ check: "F1-first-hex-note", ok: r.hasLink && r.terrainProp === r.terrain, detail: `${r.hexPath}: map link ${r.hasLink}, terrain property ${r.terrainProp} (map: ${r.terrain})` }); + } + // P3: a link picker's "Create" on a hex without a note makes the hex note + // from the template (map link), the linked note in its folder (a typed + // "../" can't leave it), and links them. + if (!r.error) { + const lk = await ctx.ev((id, map) => (async () => { + const app = window.app, p = app.plugins.plugins[id]; + const folder = `${p.settings.worldFolder || "world"}/towns`; + const link = await p.hexNotes.createAndLinkNote({ x: 4, y: 4, mapName: map, section: "Towns", folder, name: "../Smoke Town" }); + const hexPath = p.hexPath(4, 4, map); + const hex = (await app.vault.adapter.exists(hexPath)) ? await app.vault.adapter.read(hexPath) : ""; + return { link, hexPath, town: app.vault.getAbstractFileByPath(`${folder}/Smoke Town.md`) ? `${folder}/Smoke Town.md` : null, mapLink: /^map:\s*"\[\[_/m.test(hex), linked: !!link && hex.includes(`[[${link}]]`), empty: hex.trim() === "" }; + })(), ctx.pluginId, r.map); + out.push({ check: "P3-link-picker-hex-note", ok: !!lk.town && lk.mapLink && lk.linked && !lk.empty, detail: `${lk.hexPath}: map link ${lk.mapLink}, linked ${lk.link} ${lk.linked}; town note ${lk.town}` }); + } + out.push(...(await wizardMapStepChecks(ctx))); + // C10: a hex flower map explored in Play (only in a build with the hexflower slice). + const hf = await ctx.ev((id) => window.__smokePage.hexFlowerSolo(id), ctx.pluginId); + out.push({ check: "C10-hex-flower", ok: hf.ok, detail: hf.skipped ? `skipped: ${hf.skipped}` : [...hf.steps, ...hf.problems].join("; ") }); + // C10b: New map's Explore as you go, powered by generators (HF8). + const ex = await ctx.ev((id) => window.__smokePage.exploreAsYouGo(id), ctx.pluginId); + out.push({ check: "C10b-explore-as-you-go", ok: ex.ok, detail: ex.skipped ? `skipped: ${ex.skipped}` : [...ex.steps, ...ex.problems].join("; ") }); + // C12: hex fields (#52): declare, paint, type in the editor, Recalculate near a town, undo. + const hf2 = await ctx.ev((id) => window.__smokePage.hexFieldsCheck(id), ctx.pluginId); + out.push({ check: "C12-hex-fields", ok: hf2.ok, detail: hf2.skipped ? `skipped: ${hf2.skipped}` : [...hf2.steps, ...hf2.problems].join("; ") }); + return out; +} + +/** + * The setup wizard's map step (owner 2026-10-12): "What are you mapping?" + * then a generator list (Blank first) that swaps with it; the grid size + * steps with the wheel and resets to the scale's size; the generator's + * options are above the fold and Advanced holds 5–10 tuning sliders that + * count in its header once moved. Nothing is created (no map name). + */ +async function wizardMapStepChecks(ctx) { + const r = await ctx.ev(() => (async () => { + const leaf = window.app.workspace.getLeavesOfType("duckmage-setup-wizard")[0]; + if (!leaf) return { error: "no wizard leaf" }; + // Shown and focused: a hidden leaf's fields can't take focus (the wheel steps a focused field). + await window.app.workspace.revealLeaf(leaf); + window.app.workspace.setActiveLeaf(leaf, { focus: true }); + const view = leaf.view; + const until = async (fn, ms = 8000) => { const t = Date.now(); while (Date.now() - t < ms) { const v = fn(); if (v) return v; await new Promise((r2) => setTimeout(r2, 100)); } return fn(); }; + view.currentIndex = 2; + view.renderView(); + const root = view.contentEl; + const scales = [...root.querySelectorAll(".duckmage-wizard-scale-btn")]; + const scaleLabels = scales.map((c) => c.querySelector(".duckmage-wizard-orient-label")?.textContent); + const gens = () => [...root.querySelectorAll(".duckmage-setup-gen .duckmage-setup-gen-title")].map((e) => e.textContent); + await until(() => gens().length > 0); + const first = { scale: root.querySelector(".duckmage-wizard-scale-btn.is-active")?.dataset.scale, gens: gens() }; + const cols = root.querySelector('input[aria-label="Columns"]'); + const colsAt = { start: cols.value }; + // Another scale (Biomes when World maps is built); a build with one scale only checks the size. + const other = scales.find((c) => c.dataset.scale === "biomes") ?? scales.find((c) => c.dataset.scale !== first.scale); + other?.click(); + // Biomes gets its biome notes when picked, then lists World biomes. + if (other) await until(() => gens()[1] !== first.gens[1] && (other.dataset.scale !== "biomes" || gens().includes("World biomes"))); + const second = { scale: root.querySelector(".duckmage-wizard-scale-btn.is-active")?.dataset.scale, gens: gens() }; + colsAt.biomes = cols.value; + cols.focus(); + colsAt.focused = document.activeElement === cols; + cols.dispatchEvent(new WheelEvent("wheel", { deltaY: -100, bubbles: true, cancelable: true })); + colsAt.wheel = cols.value; + root.querySelector(".duckmage-wizard-size-reset")?.click(); + colsAt.reset = cols.value; + // Back to the first scale: options main, Advanced = tuning sliders. + scales.find((c) => c.dataset.scale === first.scale)?.click(); + await until(() => gens()[1] === first.gens[1]); + const opts = [...root.querySelectorAll(".duckmage-wizard-generator-option")]; + const optsInAdvanced = opts.filter((o) => o.closest(".duckmage-disclosure")).length; + const sliders = [...root.querySelectorAll(".duckmage-wizard-tuning")]; + const slidersInAdvanced = sliders.filter((s) => s.closest(".duckmage-disclosure")).length; + const summary = () => root.querySelector(".duckmage-wizard-generator-options .duckmage-disclosure-summary")?.textContent ?? ""; + const before = summary(); + const range = sliders[0]?.querySelector('input[type="range"]'); + if (range) { range.value = String(Number(range.max)); range.dispatchEvent(new Event("input", { bubbles: true })); } + const after = summary(); + sliders[0]?.querySelector(".duckmage-reset-btn")?.click(); + const reset = summary(); + return { single: !other, scaleLabels, first, second, colsAt, opts: opts.length, optsInAdvanced, sliders: sliders.length, slidersInAdvanced, before, after, reset }; + })()); + if (r.error) return [{ check: "F1-wizard-scales", ok: false, detail: r.error }]; + return [ + { check: "F1-wizard-scales", ok: r.first.gens[0] === "Blank" && (r.single ? r.scaleLabels.length === 1 : r.second.gens[0] === "Blank" && r.first.scale !== r.second.scale && JSON.stringify(r.first.gens) !== JSON.stringify(r.second.gens) && (r.second.scale !== "biomes" || r.second.gens.includes("World biomes"))), + detail: `scales ${r.scaleLabels.join(", ")}; ${r.first.scale}: ${r.first.gens.join(", ")}; ${r.second.scale}: ${r.second.gens.join(", ")}` }, + { check: "F1-wizard-size", ok: (r.single || r.colsAt.biomes !== r.colsAt.start) && Number(r.colsAt.wheel) === Number(r.colsAt.biomes) + 1 && r.colsAt.reset === r.colsAt.biomes, + detail: `columns: start ${r.colsAt.start}, ${r.single ? "same scale" : r.second.scale} ${r.colsAt.biomes}, wheel up ${r.colsAt.wheel} (focused ${r.colsAt.focused}), reset ${r.colsAt.reset}` }, + { check: "F1-wizard-advanced", ok: r.opts > 0 && r.optsInAdvanced === 0 && r.sliders >= 5 && r.sliders <= 10 && r.slidersInAdvanced === r.sliders && /· 1 set/.test(r.after) && !/set/.test(r.reset), + detail: `options ${r.opts} (${r.optsInAdvanced} in Advanced); sliders ${r.sliders} (${r.slidersInAdvanced} in Advanced); header "${r.before}" → "${r.after}" → "${r.reset}"` }, + ]; +} + +async function spaceExtra(ctx) { + const st = ctx.state; + const out = []; + out.push({ check: "F4-kinds", ok: JSON.stringify(st.mapKinds) === JSON.stringify(["space"]), detail: `mapKinds ${JSON.stringify(st.mapKinds)}` }); + const spaceMaps = st.maps.filter((m) => m.space).map((m) => m.name); + out.push({ check: "F4-space-maps", ok: spaceMaps.length >= 2, detail: `space maps: ${spaceMaps.join(", ")}` }); + const chain = st.maps.filter((m) => m.parent).map((m) => `${m.parent} → ${m.name}`); + out.push({ check: "F4-chain", ok: chain.length >= 2, detail: chain.join("; ") }); + // SP3: a space-only setup has nothing fantasy. + const fantasy = st.palettes.filter((n) => n === "Expanded" || n === "Limited"); + out.push({ check: "F4-no-fantasy-palettes", ok: fantasy.length === 0, detail: `palettes: ${st.palettes.join(", ")}` }); + // After a restart: startup wrote no biome notes; planets sit on Space - Planet. + const r = await ctx.ev((id) => { + const p = window.app.plugins.plugins[id]; + const folder = p.biomeStore?.folder?.(); + return { + biomeNotes: folder ? window.app.vault.getMarkdownFiles().filter((f) => f.path.startsWith(folder + "/")).length : 0, + defaultPalette: p.settings.defaultPalette, + planet: p.getMap("vega-iv")?.paletteName ?? p.getMap("Vega IV")?.paletteName, + kindContent: p.settings.kindContent, + // Shipped tables come with their map type (phase 6): no fantasy starters here. + fantasyTables: ["weather.md", "rumors.md"].filter((n) => window.app.vault.getAbstractFileByPath(`${p.settings.tablesFolder}/${n}`)), + }; + }, ctx.pluginId); + out.push({ check: "F4-no-fantasy-tables", ok: r.fantasyTables.length === 0, detail: `starter tables: ${r.fantasyTables.join(", ") || "none"}` }); + out.push({ check: "F4-no-biome-notes", ok: r.biomeNotes === 0, detail: `biome notes: ${r.biomeNotes}` }); + out.push({ check: "F4-default-palette", ok: r.defaultPalette === "Space - Sector", detail: `Palette for new maps: ${r.defaultPalette}; kindContent ${JSON.stringify(r.kindContent)}` }); + out.push({ check: "F4-planet-palette", ok: r.planet === "Space - Planet", detail: `planet palette: ${r.planet}` }); + + // Tables everywhere phases 3-4: convert World types to tables, then arrive + // in Play at an unknown sector hex (SP4/SP5/GM4/T5). The C5 restart that + // follows checks none of it is rewritten on load. + const a = await ctx.ev(async (id) => { + const p = window.app.plugins.plugins[id]; + const steps = [], problems = []; + try { + if (!p.arrival || !p.worldTypeStore?.convertAll) return { skipped: "build has no arrival" }; + const s = p.settings.maps.find((m) => m.displayName === "Rim Sector" || m.name === "rim-sector")?.name; + if (!s) return { skipped: "no Rim Sector" }; + const sector = p.getMap(s); + if (p.arrival.canArrive(s, 6, 6)) problems.push("arrival on by default"); + await p.worldTypeStore.ensureDefault(); + const conv = await p.worldTypeStore.convertAll(); + steps.push(`converted ${conv.converted.join(", ")} (${conv.written.length} notes)`); + const again = await p.worldTypeStore.convertAll(); + if (again.converted.length || again.written.length) problems.push("converting twice wrote again"); + const mainworlds = conv.written.find((f) => f.endsWith("/Sector/Mainworlds.md")); + if (!mainworlds) return { steps, problems: [...problems, "no Mainworlds table written"] }; + const before = sector.workMode; + sector.arrivalMode = "make places"; + sector.workMode = "play"; + p.mapStore.set(s, "6_6", { terrain: "star system", onArrival: mainworlds.replace(/\.md$/, "") }); + await p.saveSettings(); + await p.mapStore.flush(); + const made = await p.arrival.arrive(s, 6, 6); + const hex = p.mapStore.get(s, "6_6") ?? {}; + if (!made) problems.push("no place made"); + else { + steps.push(`arrived: 6,6 is now ${hex.terrain}; made ${made}`); + if (hex.onArrival) problems.push("On arrival cell not cleared"); + if (!hex.terrain || hex.terrain === "star system") problems.push(`hex terrain ${hex.terrain}`); + if (!(hex.locations ?? []).includes(made)) problems.push("place not linked"); + const child = p.getMap(made); + if (child?.arrival !== "open" || child?.workMode !== "play") problems.push(`new place ${child?.arrival}/${child?.workMode}`); + const note = await p.mapStore.readNoteText(made); + if (!note?.includes("## Arrival")) problems.push("no Arrival section"); + if (!(await p.arrival.reroll(made))) problems.push("Play couldn't reroll an open place"); + await p.arrival.lock(made); + if (await p.arrival.reroll(made)) problems.push("Play rerolled a locked place"); + else steps.push("reroll then lock: Play can't reroll after the lock"); + if ((await p.arrival.arrive(s, 6, 6)) !== null) problems.push("second visit made another place"); + } + sector.workMode = before; + delete sector.arrivalMode; + await p.saveSettings(); + await p.mapStore.flush(); + } catch (e) { + problems.push(String(e?.stack ?? e).slice(0, 400)); + } + return { steps, problems }; + }, ctx.pluginId); + out.push({ check: "F13-arrival", ok: !a.skipped && a.problems.length === 0, detail: a.skipped ?? [...a.steps, ...a.problems].join("; ") }); + return out; +} + +/** The demo world's overworld is a radius-2 hex of 19 hexes, each with its region. */ +const DEMO_REGIONS = 19; + +async function overworldExtra(ctx) { + const ow = ctx.state.maps.find((m) => m.overworld); + if (!ow) return [{ check: "F5-overworld", ok: false, detail: "no overworld map" }]; + const regions = ctx.state.maps.filter((m) => m.submapKind === "region" && m.parent === ow.name && m.world); + // Incident 2026-10-14: the region fields (kind, world slot, arrival) reach the + // notes and survive the stores starting late and a restart; the overworld draws them all. + const prep = ctx.prepInfo ?? {}; + const out = [{ + check: "F5-regions-prep", + ok: prep.regions === DEMO_REGIONS && prep.regionsAfterStart === DEMO_REGIONS && prep.regionNotes === DEMO_REGIONS && prep.layerRegions === DEMO_REGIONS, + detail: `built ${prep.regions} (stores held: ${prep.heldAtBuild}); after the stores started: ${prep.regionsAfterStart} in memory, ${prep.regionNotes} notes, ${prep.layerRegions} on the overworld layer (want ${DEMO_REGIONS})`, + }]; + const layer = await ctx.ev(async (id, n) => { + const p = window.app.plugins.plugins[id]; + await p.showMap(n); + await new Promise((r) => setTimeout(r, 2500)); + return p.devTools?.overworldStats?.()?.[0]?.regions ?? null; + }, ctx.pluginId, ow.name); + out.push({ check: "F5-regions", ok: regions.length === DEMO_REGIONS && layer === DEMO_REGIONS, detail: `after a restart: ${ow.name}: ${regions.length} region maps with a world slot, ${layer} on the overworld layer (want ${DEMO_REGIONS})` }); + const lock = await ctx.ev((id, n) => window.__smokePage.overworldPaintLock(id, n), ctx.pluginId, ow.name); + out.push({ check: "C8-overworld-paint", ok: lock.ok, detail: [...lock.steps, ...lock.problems].join("; ") }); + + // GM4 on overworlds: with arrival on, going to a hex with a biome and no + // region makes the region in Play (seeded, no form); Reroll until Lock. + // The hex's unresolved On arrival cell shows the uncharted "?" first. + const a = await ctx.ev(async (id, owName) => { + const p = window.app.plugins.plugins[id]; + const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); + const steps = [], problems = []; + const ow = p.getMap(owName); + const before = { mode: ow.workMode, cols: ow.gridSize.cols }; + try { + if (!p.arrival?.isOverworld || !p.events) return { skipped: "build has no overworld arrival" }; + if (p.arrival.canArrive(owName, ow.gridOffset.x, ow.gridOffset.y)) problems.push("arrival on by default"); + const hasRegion = (k) => p.settings.maps.some((m) => m.submapKind === "region" && m.parent?.map === owName && m.parent.hex === k); + let key; + for (let y = ow.gridOffset.y; !key && y < ow.gridOffset.y + ow.gridSize.rows; y++) + for (let x = ow.gridOffset.x; !key && x < ow.gridOffset.x + ow.gridSize.cols; x++) if (!hasRegion(`${x}_${y}`)) key = `${x}_${y}`; + if (!key) { + // Every hex has a region: take in one more column. + ow.gridSize = { ...ow.gridSize, cols: ow.gridSize.cols + 1 }; + key = `${ow.gridOffset.x + ow.gridSize.cols - 1}_${ow.gridOffset.y}`; + steps.push("grew the overworld by a column"); + } + const [x, y] = key.split("_").map(Number); + const terrain = [...p.mapStore.all(owName).values()].find((h) => h.terrain)?.terrain; + ow.arrivalMode = "make places"; + ow.workMode = "play"; + p.mapStore.set(owName, key, { terrain, onArrival: "Smoke uncharted" }); + await p.saveSettings(); + await p.mapStore.flush(); + await p.showMap(owName); + p.refreshHexMap(); + await sleep(1500); + const marks = document.querySelectorAll(".duckmage-uncharted-layer .duckmage-uncharted-mark").length; + steps.push(`uncharted marks: ${marks}`); + if (marks < 1) problems.push("no uncharted mark on the unresolved hex"); + if (!p.arrival.canArrive(owName, x, y)) problems.push(`can't arrive at ${key}: ${p.arrival.blocker(owName, x, y)}`); + const made = await p.arrival.arrive(owName, x, y); + if (!made) problems.push("no region made"); + else { + const r = p.getMap(made); + steps.push(`arrived at ${key}: made ${made}`); + if (r?.submapKind !== "region" || r?.parent?.hex !== key) problems.push(`not the hex's region: ${r?.submapKind} ${r?.parent?.hex}`); + if (r?.arrival !== "open" || r?.workMode !== "play") problems.push(`new region ${r?.arrival}/${r?.workMode}`); + if (p.mapStore.get(owName, key)?.onArrival) problems.push("On arrival cell not cleared"); + if (!p.mapStore.all(made).size) problems.push("region has no terrain"); + const note = await p.mapStore.readNoteText(made); + if (!note?.includes("## Arrival")) problems.push("no Arrival section"); + const seed = r.regionSeed; + if (!(await p.arrival.reroll(made))) problems.push("Play couldn't reroll an open region"); + else if (r.regionSeed === seed) problems.push("reroll kept the seed"); + await p.arrival.lock(made); + if (await p.arrival.reroll(made)) problems.push("Play rerolled a locked region"); + else steps.push("reroll then lock: Play can't reroll after the lock"); + if (p.arrival.canArrive(owName, x, y)) problems.push("can arrive again"); + } + } catch (e) { + problems.push(String(e?.stack ?? e).slice(0, 400)); + } finally { + ow.workMode = before.mode; + delete ow.arrivalMode; + await p.saveSettings(); + await p.mapStore.flush(); + } + return { steps, problems }; + }, ctx.pluginId, ow.name); + out.push({ check: "GM4-overworld-arrival", ok: !a.skipped && a.problems.length === 0, detail: a.skipped ?? [...a.steps, ...a.problems].join("; ") }); + // C10c: explore a region of the demo world with fog of war (HF11). + const region = regions.slice().sort((x, y) => y.cols * y.rows - x.cols * x.rows)[0]; + if (region) out.push(fogCheck(await ctx.ev((id, n) => window.__smokePage.exploreFog(id, n), ctx.pluginId, region.name), `C10c-fog ${region.name}`)); + return out; +} + +/** A fog check's result as a smoke check line (render times in the detail). */ +function fogCheck(r, check) { + const bench = r.bench?.fog !== undefined ? ` [render ${r.bench.noFog} ms → ${r.bench.fog} ms with fog]` : ""; + return { check, ok: r.ok, detail: r.skipped ? `skipped: ${r.skipped}` : [...r.steps, ...r.problems].join("; ") + bench, bench: r.bench }; +} + +/** + * Real data (HF11): explore the coastal map with fog of war, and time its + * render with and without fog; chult (3843 hexes) for the render time only. + */ +async function realDataExtra(ctx) { + const out = []; + const names = ctx.state.maps.map((m) => m.name); + if (names.includes("the-coast")) out.push(fogCheck(await ctx.ev((id, n) => window.__smokePage.exploreFog(id, n, { runs: 5 }), ctx.pluginId, "the-coast"), "C10c-fog the-coast")); + if (names.includes("chult")) out.push(fogCheck(await ctx.ev((id, n) => window.__smokePage.exploreFog(id, n, { runs: 5, benchOnly: true }), ctx.pluginId, "chult"), "C10c-fog-bench chult")); + return out; +} + +async function neighboursExtra(ctx) { + const inWorld = ctx.state.maps.filter((m) => m.world); + return [{ check: "F6-world", ok: inWorld.length === 4, detail: inWorld.map((m) => `${m.name}@${m.world}`).join(", ") }]; +} + +async function customPaletteExtra(ctx) { + const st = ctx.state; + // C11: note PDF / markdown and the map export form, end to end (lib/exports.mjs). + const manual = ctx.slices ? ctx.slices.includes("manual") : true; + const ex = await ctx.ev((id, m) => window.__smokePage.exportsRoundTrip(id, true, { manual: m }), ctx.pluginId, manual); + return [ + { check: "F7-palettes", ok: st.palettes.length === 1 && st.palettes[0] === "Moorland", detail: `palettes: ${st.palettes.join(", ")}` }, + { check: "C11-exports", ok: ex.ok, detail: [...ex.steps, ...ex.problems].join("; ") }, + ]; +} + +async function deletedExtra(ctx) { + const st = ctx.state; + const notices = await ctx.ev(() => window.__smokePage.notices()); + const errLoop = ctx.log.length; + await new Promise((r) => setTimeout(r, 8000)); + const grew = ctx.log.length - errLoop; + const gone = st.maps.filter((m) => m.name.startsWith("gone-")); + // Owner call SM-DEL: maps whose folder and note are gone are marked missing, never re-created; + // an emptied palette list stays empty (no automatic defaults). + const out = [ + { check: "F8-missing", ok: gone.length === 2 && gone.every((m) => m.missing && !m.noteExists), detail: `maps: ${st.maps.map((m) => `${m.name} (${m.missing ? "missing" : !m.noteExists ? "no note" : ctx.snap0[m.notePath] ? "note kept" : "note re-created, " + m.hexes + " hexes"})`).join(", ")}` }, + { check: "F8-no-refill", ok: st.palettes.length === 0, detail: `palettes: ${st.palettes.join(", ") || "(none)"}; path types: ${st.pathTypes}` }, + { check: "F8-no-loop", ok: grew === 0, detail: `console errors/warnings added in 8 s idle: ${grew}; notices: ${notices.join(" | ") || "(none)"}` }, + ]; + // Restore one from its cached note: hexes and the path come back exactly; Remove the other. + const r = await ctx.ev((id) => (async () => { + const p = window.app.plugins.plugins[id]; + const ok = await p.restoreMissingMap("gone-one"); + await p.mapStore.flush(); + const hexes = [...p.mapStore.all("gone-one")].map(([k, h]) => `${k}=${h.terrain}`).sort(); + const paths = p.mapStore.paths("gone-one").map((x) => `${x.name}:${x.branches[0]?.anchors.join(">")}`); + const note = !!window.app.vault.getAbstractFileByPath(p.mapStore.notePath("gone-one")); + await p.removeMapEntry("gone-two"); + return { ok, hexes, paths, note, missing: p.mapStore.isMissing("gone-one"), maps: p.settings.maps.map((m) => m.name) }; + })(), ctx.pluginId); + out.push({ check: "F8-restore", ok: r.ok && r.note && !r.missing && r.hexes.length === 3 && r.paths.length === 1 && r.paths[0].startsWith("Old road:0_1>4_3"), detail: `restored gone-one: note ${r.note}, hexes ${r.hexes.join(" ")}, paths ${r.paths.join(" ")}` }); + out.push({ check: "F8-remove", ok: !r.maps.includes("gone-two"), detail: `maps now: ${r.maps.join(", ")}` }); + return out; +} + +async function manyMapsExtra(ctx) { + const n = ctx.state.maps.length; + const deep = ctx.state.maps.filter((m) => / L4$/i.test(m.name) || /-l4$/.test(m.name)).length; + return [{ check: "F9-count", ok: n >= 80, detail: `${n} maps, ${deep} at depth 4, store ready in ${ctx.readyMs} ms` }]; +} + +// ── the matrix ──────────────────────────────────────────────────────────── + +export const SETUPS = [ + { + id: "real-data", title: "Owner real-data copy (seedF + live data.json), migrates", slow: true, + // Private data on the owner's machine (SMOKE_REAL_SEED / SMOKE_REAL_DATA elsewhere): skipped, loudly, without it. + unavailable: () => (!fs.existsSync(REAL_SEED) ? `real seed missing: ${REAL_SEED}` : !fs.existsSync(REAL_DATA) ? `live data.json missing: ${REAL_DATA}` : null), + build(dir) { + if (!fs.existsSync(REAL_SEED)) throw new Error(`real seed missing: ${REAL_SEED}`); + if (!fs.existsSync(REAL_DATA)) throw new Error(`live data.json missing: ${REAL_DATA}`); + const pluginData = path.join(dir, "data.json"); + fs.copyFileSync(REAL_DATA, pluginData); // a COPY: the sandbox never sees the live file + return { seed: REAL_SEED, pluginData }; + }, + migration: true, + expect: { readyMs: 600_000, openMs: 60_000 }, + extra: realDataExtra, + }, + // `slices`: the slices a setup exercises beyond the foundation (premerge runs those with an unreleased one on a build with every slice). + { id: "fresh", title: "Fresh install", build: (dir) => ({ seed: seedDir(dir) }), expect: { wizard: true }, extra: freshExtra, skipPaint: true, slices: ["play", "hexflower"] }, + { id: "v155", title: "Synthetic 1.5.5 vault (hex-note frontmatter + data.json maps), migrates", build: buildV155, migration: true, expect: {} }, + { id: "space", title: "Space only (sector → system → planet)", build: (dir) => ({ seed: seedDir(dir) }), recipe: recipeSpace, expect: {}, extra: spaceExtra, slices: ["space"] }, + { id: "overworld", title: "Overworld + regions (demo world, seed 7)", build: (dir) => ({ seed: seedDir(dir) }), recipe: recipeOverworld, prepHeld: true, expect: { openMs: 60_000 }, extra: overworldExtra, slices: ["worldmaps"] }, + { id: "neighbours", title: "Neighbours world (legacy 2×2, own coordinates)", build: (dir) => ({ seed: seedDir(dir) }), recipe: recipeNeighbours, expect: {}, extra: neighboursExtra }, + { id: "custom-palette", title: "One custom palette, no default names", build: (dir) => ({ seed: seedDir(dir) }), recipe: recipeCustomPalette, expect: {}, extra: customPaletteExtra }, + { + id: "deleted", title: "Everything deleted (no palettes, path types or map folders)", + build: (dir) => ({ seed: seedDir(dir) }), recipe: recipeDeleted, + postPrep(vault, info, pluginId) { + for (const f of info.folders ?? []) { + const p = path.join(vault, f); + if (fs.existsSync(p) && path.resolve(p).startsWith(path.resolve(vault) + path.sep)) fs.rmSync(p, { recursive: true, force: true }); + } + const dataFile = path.join(vault, ".obsidian", "plugins", pluginId, "data.json"); + const data = JSON.parse(fs.readFileSync(dataFile, "utf8")); + data.terrainPalettes = []; + data.pathTypes = []; + fs.writeFileSync(dataFile, JSON.stringify(data, null, 2)); + }, + expect: {}, extra: deletedExtra, skipModeLocks: true, + }, + { id: "many-maps", title: "Many maps (80, nested 4 deep, look-alike names)", build: (dir) => ({ seed: seedDir(dir) }), recipe: recipeManyMaps, expect: {}, extra: manyMapsExtra }, +]; + diff --git a/dev/space-gen-preview.html b/dev/space-gen-preview.html new file mode 100644 index 00000000..95c52fdf --- /dev/null +++ b/dev/space-gen-preview.html @@ -0,0 +1,29 @@ + + +loading + +

Procedural generators sandbox (dev only): Star scatter, Orbits, Region detail

+
+ + + + + + +
+
+
+
+ diff --git a/dev/space-gen-preview.ts b/dev/space-gen-preview.ts new file mode 100644 index 00000000..1b9ccbcc --- /dev/null +++ b/dev/space-gen-preview.ts @@ -0,0 +1,164 @@ +/** + * Sandbox for the procedural space generators (Star scatter, Orbits), + * rendered with the same drawPreview the new-map setup modal uses. + * Build: npx esbuild dev/space-gen-preview.ts --bundle --format=iife --outfile=dev/space-gen-preview.js + * Serve: npm run sandbox → /dev/space-gen-preview.html + */ +import { SPACE_SECTOR_TERRAINS, SPACE_SYSTEM_TERRAINS, SPACE_PATH_TYPES, SYSTEM_PATH_TYPES } from "../src/modules/space/presets"; +import { starScatter, STAR_SCATTER_OPTIONS } from "../src/space/starScatter"; +import { orbits, orbitsOptions } from "../src/space/orbits"; +import type { GenerationContext, ProcGrid, ProcOption, Side } from "../src/worldgen/procedural/common"; +import { planetSurface, REGION_DETAIL_OPTIONS } from "../src/worldgen/procedural/planetSurface"; +import { DEFAULT_TERRAIN_PALETTE, DEFAULT_PATH_TYPES } from "../src/constants"; +import { routeContextPaths } from "../src/worldgen/procedural/contextPaths"; +import { drawPreview } from "../src/worldgen/preview"; +import { worldTypesSource } from "../src/space/worldTypesSource"; +import { DEFAULT_WORLD_TYPE_EXTRAS, DEFAULT_WORLD_TYPE_ROWS } from "../src/space/worldTypePresets"; + +type Gen = "sector" | "system" | "region"; +/** Region detail: the parent hex and its N/E/S/W neighbours (terrain names from Expanded). */ +const region: { parent: string; sides: Partial>; road: string; river: string } = { + parent: "forest", sides: { E: "ocean" }, road: "W-E", river: "N-S", +}; +/** "W-E" → { from: W, to: E }; "S-" → ends in the hex. */ +const pathSpec = (v: string) => { + const [from, to] = v.split("-") as [Side | "", Side | ""]; + return { from: from || undefined, to: to || undefined }; +}; +const state = { + gen: "sector" as Gen, + orientation: "flat" as "flat" | "pointy", + cols: 8, + rows: 10, + seed: 1, + options: {} as Record, +}; + +const paletteOf = (gen: Gen) => + gen === "sector" ? SPACE_SECTOR_TERRAINS : gen === "system" ? SPACE_SYSTEM_TERRAINS : DEFAULT_TERRAIN_PALETTE; +const colors = (gen: Gen) => new Map(paletteOf(gen).map((t) => [t.name, t.color])); +const typed = (name: string) => ({ terrain: name, type: DEFAULT_TERRAIN_PALETTE.find((t) => t.name === name)?.type }); +function regionContext(): GenerationContext { + const sides: GenerationContext["sides"] = {}; + for (const [s, name] of Object.entries(region.sides)) if (name) sides[s as Side] = typed(name); + return { parent: typed(region.parent), sides }; +} +const pathColors = new Map([...SPACE_PATH_TYPES, ...SYSTEM_PATH_TYPES, ...DEFAULT_PATH_TYPES].map((p) => [p.name, p.color])); + +function controls(): void { + const box = document.getElementById("controls")!; + box.replaceChildren(); + const opts: ProcOption[] = state.gen === "sector" ? STAR_SCATTER_OPTIONS : state.gen === "system" ? orbitsOptions(SPACE_SYSTEM_TERRAINS) : REGION_DETAIL_OPTIONS; + if (state.gen === "region") { + const names = ["", ...DEFAULT_TERRAIN_PALETTE.map((t) => t.name)]; + const pick = (label: string, value: string, set: (v: string) => void) => { + const l = document.createElement("label"); + l.textContent = label + " "; + const sel = document.createElement("select"); + for (const n of names) sel.add(new Option(n || "—", n)); + sel.value = value; + sel.onchange = () => { set(sel.value); render(); }; + l.append(sel); + box.append(l); + }; + pick("Parent hex", region.parent, (v) => { region.parent = v || "grass"; }); + const routes = ["", "W-E", "N-S", "NW-SE", "SW-NE", "W-", "S-"]; + const routePick = (label: string, value: string, set: (v: string) => void) => { + const l = document.createElement("label"); + l.textContent = label + " "; + const sel = document.createElement("select"); + for (const r of routes) sel.add(new Option(r ? r.replace("-", " → ").replace(/→ $/, "→ ends here") : "—", r)); + sel.value = value; + sel.onchange = () => { set(sel.value); render(); }; + l.append(sel); + box.append(l); + }; + routePick("Road", region.road, (v) => { region.road = v; }); + routePick("River", region.river, (v) => { region.river = v; }); + for (const s of ["N", "E", "S", "W"] as Side[]) pick(s, region.sides[s] ?? "", (v) => { region.sides[s] = v || undefined; }); + } + for (const o of opts) { + const label = document.createElement("label"); + label.textContent = o.label + " "; + const sel = document.createElement("select"); + for (const c of o.choices) sel.add(new Option(c.label, c.value)); + sel.value = state.options[o.key] ?? o.default; + sel.onchange = () => { state.options[o.key] = sel.value; render(); }; + label.append(sel); + box.append(label); + } +} + +/** Region mode: carry the parent hex's road / river across the generated map. */ +function withPaths; paths: { type: string; hexes: string[] }[] }>(r: T, grid: ProcGrid, seed: number): T { + const carry = [ + ...(region.road ? [{ type: "Road", routing: "through" as const, ...pathSpec(region.road) }] : []), + ...(region.river ? [{ type: "River", routing: "meander" as const, ...pathSpec(region.river) }] : []), + ]; + return { ...r, paths: [...r.paths, ...routeContextPaths(r.cells, DEFAULT_TERRAIN_PALETTE, grid, carry, seed)] }; +} + +/** The shipped World types table: the generators roll on it like in a vault (SP1). */ +const DEFAULT_SPACE = { name: "Default space", rows: [...DEFAULT_WORLD_TYPE_ROWS], ...DEFAULT_WORLD_TYPE_EXTRAS }; + +function render(): void { + const grid: ProcGrid = { + cols: state.cols, rows: state.rows, offset: { x: 0, y: 0 }, stagger: "odd", orientation: state.orientation, + }; + const wall = document.getElementById("wall")!; + wall.replaceChildren(); + // Six seeds side by side so the variety is visible at a glance. + for (let i = 0; i < 6; i++) { + const seed = state.seed + i; + const r = state.gen === "sector" + ? starScatter(SPACE_SECTOR_TERRAINS, grid, seed, state.options, "Jump route", worldTypesSource(DEFAULT_SPACE, SPACE_SECTOR_TERRAINS)) + : state.gen === "system" + ? orbits(SPACE_SYSTEM_TERRAINS, grid, seed, state.options, "Orbit", undefined, worldTypesSource(DEFAULT_SPACE, SPACE_SYSTEM_TERRAINS)) + : withPaths(planetSurface(DEFAULT_TERRAIN_PALETTE, grid, seed, state.options, regionContext()), grid, seed); + const fig = document.createElement("figure"); + const canvas = document.createElement("canvas"); + drawPreview(canvas, r.cells, grid, state.orientation, colors(state.gen), undefined, r.paths, pathColors, 300, 18); + const cap = document.createElement("figcaption"); + cap.textContent = `seed ${seed}` + (r.warnings.length ? ` — ${r.warnings.join(" ")}` : ""); + fig.append(canvas, cap); + wall.append(fig); + } + const legend = document.getElementById("legend")!; + legend.replaceChildren(...[...colors(state.gen)].map(([name, color]) => { + // DOM calls, not innerHTML: the Obsidian review scans dev files too. + const s = document.createElement("span"); + const swatch = document.createElement("i"); + swatch.style.setProperty("background", color); + s.append(swatch, document.createTextNode(name)); + return s; + })); +} + +function setGen(gen: Gen): void { + state.gen = gen; + state.options = {}; + [state.cols, state.rows] = gen === "sector" ? [8, 10] : gen === "system" ? [13, 13] : [20, 14]; + (document.getElementById("cols") as HTMLInputElement).value = String(state.cols); + (document.getElementById("rows") as HTMLInputElement).value = String(state.rows); + document.querySelectorAll("[data-gen]").forEach((b) => b.classList.toggle("on", b.dataset.gen === gen)); + controls(); + render(); +} + +document.querySelectorAll("[data-gen]").forEach((b) => (b.onclick = () => setGen(b.dataset.gen as Gen))); +(document.getElementById("reroll") as HTMLButtonElement).onclick = () => { state.seed += 6; render(); }; +(document.getElementById("orient") as HTMLSelectElement).onchange = (e) => { + state.orientation = (e.target as HTMLSelectElement).value as "flat" | "pointy"; + render(); +}; +for (const id of ["cols", "rows"] as const) { + (document.getElementById(id) as HTMLInputElement).onchange = (e) => { + state[id] = Math.max(3, Math.min(60, Number((e.target as HTMLInputElement).value) || 3)); + render(); + }; +} +(window as unknown as { __render: typeof render; __state: typeof state; __setGen: typeof setGen }).__render = render; +(window as unknown as { __state: typeof state }).__state = state; +(window as unknown as { __setGen: typeof setGen }).__setGen = setGen; +setGen("sector"); +document.title = "ready"; diff --git a/dev/ui-inventory/README.md b/dev/ui-inventory/README.md new file mode 100644 index 00000000..814c8d45 --- /dev/null +++ b/dev/ui-inventory/README.md @@ -0,0 +1,24 @@ +# UI inventory worksheet (owner tags, 2026-10-11) + +Every user-facing input, picker, command and menu item, tagged by the owner: +- keep: as today +- simple: everyone +- advanced: the page's Advanced dropdown +- overkill: Debug, only in debug mode +- drop: removed + +Built with the `ui-inventory` skill (`work/tools/skills-share/ux-testing/ui-inventory`). + +- `items.json`: the inventory (ids are permanent; `src/ui/placement.ts` is keyed by them) +- `config.json`: the tier scheme and page settings +- `inputs-tags.html`: the worksheet page (serve with `npm run sandbox`, open `/dev/ui-inventory/inputs-tags.html`) +- `submission-2026-10-11.json`: the owner's submission (group picks, own picks, notes) +- `inputs-tags-resolved.json` / `.csv` / `-summary.md`: effective tag per item, with source (own / group / twin) + +To review again, run the skill's `build-page.mjs` with `items.json` + `config.json` and load the last submission as progress, so the owner starts from these answers. Then apply the new resolved tags to `src/ui/placement.ts`. + +KB: `knowledgebase/projects/duckmage-plugin/notes/impl/audit-inputs-2026-10-11.md`. + +## Removed with the global level (ee28ebd) +These worksheet items described the old Simple/Advanced level, feature switches, hints and nudges. They're gone from the code and marked `removed` in the resolved JSON, so leave them out of the next round: +`Settings.featureLevel`, `Settings.featureGenerators`, `Settings.featureWorkflows`, `Settings.featurePalettes`, `Settings.featureRegions`, `Settings.showHintsAgain`, `Wizard.featureLevel`, `Hint.turnOnFeature`, `Hint.close`, `Hints.show`, `MoreFeatures.turnOn`, `MoreFeatures.turnOnAll`, `MoreFeatures.closeButtons`, `EnableFeature.turnOnOne`, `EnableFeature.turnOnAll`, `EnableFeature.closeButtons`, `Nudge.turnOnAdvanced`, `Nudge.closeButtons`, `Nudge.dontAskAgain`, `MapModal.propsNeighbourHint`, `NewMap.moreOptionsHint`, `ChildKind.regionsHint`, `GenPage.regionsHint`, `RTView.workflowsHintTurnOn`, `RTView.workflowsHintHide`. diff --git a/dev/ui-inventory/config.json b/dev/ui-inventory/config.json new file mode 100644 index 00000000..71b9c407 --- /dev/null +++ b/dev/ui-inventory/config.json @@ -0,0 +1,29 @@ +{ + "page": "inputs-tags", + "prefix": "hexmaker", + "title": "Hexmaker: tag every input and picker (round 6, SP3, tree view)", + "lead": "Every user-facing input, picker, button, command and menu item on `feat/region-notes`, as a tree: **screen › section › item**. Pick once for a whole screen or section, or open it and pick items one by one. Your 65 picks so far are kept as they were. Submit any time.", + "suggestionName": "suggestion", + "tiers": [ + { "v": "keep", "short": "Keep", "label": "Keep (as today)", "desc": "Whatever it does today, unchanged, including its feature switch or greyed-out rules. Feature switches that ramp Simple users up are keep.", "color": "#1f4d33" }, + { "v": "simple", "short": "Simple", "label": "Simple (show to everyone)", "desc": "Shown at every level. **Simple stays customizable**: palettes and palette management, look and feel, and defaults lean here.", "color": "#2f6b3e" }, + { "v": "advanced", "short": "Adv.", "label": "Advanced (hide from Simple)", "desc": "A real extra feature, or an option of one. When unsure between Advanced and Overkill, pick Advanced.", "color": "#1f4f6b" }, + { "v": "overkill", "short": "Overkill", "label": "Overkill (\"All\" level only)", "desc": "Backend-fiddler stuff: engine tuning, raw seeds and ids, maintenance and diagnostics. Shown only at the new All level.", "color": "#6b4f12" }, + { "v": "drop", "short": "Drop", "label": "Drop entirely", "desc": "Redundant or dead; removed at every level.", "color": "#6b1f1f" } + ], + "levels": { + "columns": ["Simple", "Advanced", "All (new)"], + "rows": { + "keep": ["as today", "as today", "shown"], + "simple": ["shown", "shown", "shown"], + "advanced": ["hidden", "shown", "shown"], + "overkill": ["hidden", "hidden", "shown, with a \"you probably don't need these\" caveat"], + "drop": ["removed", "removed", "removed"] + } + }, + "facts": [ + "**Legacy (pre-1.13)** items in Settings are the fallback copies of the same settings. Each follows its twin; you tagged them before twins existed, so they show as overrides. Use \"Follow twin\" on a row, or the filter \"Twins picked differently\", to line them up.", + "Blue chip: when the item shows today. Red **mixed list** chip: a picker that lists unrelated kinds of note.", + "Full inventory with reasons and line numbers: KB note `projects/duckmage-plugin/notes/impl/audit-inputs-2026-10-11`." + ] +} diff --git a/dev/ui-inventory/inputs-tags-resolved.csv b/dev/ui-inventory/inputs-tags-resolved.csv new file mode 100644 index 00000000..67caf4ea --- /dev/null +++ b/dev/ui-inventory/inputs-tags-resolved.csv @@ -0,0 +1,1143 @@ +id,group,subgroup,label,suggestion,choice,source,via,overrides,twinOf,loc,note +"Settings.rerunSetupWizard","Settings","Setup & feature switches","Re-run setup wizard","keep","keep","own","","","","src/HexmakerSettingTab.ts:247","" +"Settings.featureLevel","Settings","Setup & feature switches","Feature level","keep","keep","own","","","","src/HexmakerSettingTab.ts:894","" +"Settings.featureGenerators","Settings","Setup & feature switches","Terrain generators","keep","keep","own","","","","src/HexmakerSettingTab.ts:906","" +"Settings.featureWorkflows","Settings","Setup & feature switches","Workflows","keep","keep","own","","","","src/HexmakerSettingTab.ts:906","" +"Settings.featurePalettes","Settings","Setup & feature switches","Custom palettes","keep","keep","own","","","","src/HexmakerSettingTab.ts:906","" +"Settings.featureRegions","Settings","Setup & feature switches","Regions and overworlds","keep","keep","own","","","","src/HexmakerSettingTab.ts:906","" +"Settings.showHintsAgain","Settings","Setup & feature switches","Show hints again","keep","keep","own","","","","src/HexmakerSettingTab.ts:923","" +"Settings.mapKindWorld","Settings","Setup & feature switches","World / fantasy overland","keep","keep","own","","","","src/HexmakerSettingTab.ts:695","" +"Settings.mapKindSpace","Settings","Setup & feature switches","Space","keep","keep","own","","","","src/HexmakerSettingTab.ts:695","" +"Settings.hexOrientation","Settings","Look & labels","Hex orientation","keep","keep","own","","","","src/HexmakerSettingTab.ts:310","" +"Settings.staggerOffset","Settings","Look & labels","Stagger offset","advanced","simple","own","","","","src/HexmakerSettingTab.ts:320","" +"Settings.coordPlacement","Settings","Look & labels","Coordinate placement","advanced","simple","own","","","","src/HexmakerSettingTab.ts:339","" +"Settings.coordFontSize","Settings","Look & labels","Coordinate label size","overkill","simple","own","","","","src/HexmakerSettingTab.ts:349","" +"Settings.coordFontFamily","Settings","Look & labels","Coordinate label font","overkill","simple","own","","","","src/HexmakerSettingTab.ts:362","" +"Settings.coordFontColor","Settings","Look & labels","Coordinate label color","overkill","simple","own","","","","src/HexmakerSettingTab.ts:376","" +"Settings.hexNameFont","Settings","Look & labels","Hex name font","overkill","simple","own","","","","src/HexmakerSettingTab.ts:385","" +"Settings.hexNameSize","Settings","Look & labels","Hex name size","overkill","simple","own","","","","src/HexmakerSettingTab.ts:395","" +"Settings.hexNameStyle","Settings","Look & labels","Hex name style","overkill","simple","own","","","","src/HexmakerSettingTab.ts:405","" +"Settings.hexGap","Settings","Look & labels","Hex cell spacing","advanced","simple","own","","","","src/HexmakerSettingTab.ts:415","" +"Settings.defaultTableDice","Settings","Defaults","Default die for new tables","advanced","simple","own","","","","src/HexmakerSettingTab.ts:266","" +"Settings.collapseTerrain","Settings","Defaults","Terrain","advanced","simple","own","","","","src/HexmakerSettingTab.ts:989","" +"Settings.collapseFeatures","Settings","Defaults","Features","advanced","simple","own","","","","src/HexmakerSettingTab.ts:996","" +"Settings.collapseNotes","Settings","Defaults","Notes","advanced","simple","own","","","","src/HexmakerSettingTab.ts:1003","" +"Settings.templatePath","Settings","Defaults","Template path","advanced","advanced","own","","","","src/HexmakerSettingTab.ts:293","" +"Settings.defaultMap","Settings","Defaults","Default map","keep","keep","own","","","","src/HexmakerSettingTab.ts:300","" +"Settings.defaultNewMapCols","Settings","Defaults","Default new map columns","advanced","advanced","own","","","","src/HexmakerSettingTab.ts:428","" +"Settings.defaultNewMapRows","Settings","Defaults","Default new map rows","advanced","advanced","own","","","","src/HexmakerSettingTab.ts:440","" +"Settings.defaultSubmapCols","Settings","Defaults","Default submap columns","advanced","advanced","own","","","","src/HexmakerSettingTab.ts:452","" +"Settings.defaultSubmapRows","Settings","Defaults","Default submap rows","advanced","advanced","own","","","","src/HexmakerSettingTab.ts:464","" +"Settings.iconsFolder","Settings","Folders","Custom icons folder","keep","keep","own","","","","src/HexmakerSettingTab.ts:475","" +"Settings.worldFolder","Settings","Folders","World notes folder","keep","keep","own","","","","src/HexmakerSettingTab.ts:527","" +"Settings.hexFolder","Settings","Folders","Hex notes folder","advanced","advanced","own","","","","src/HexmakerSettingTab.ts:608","" +"Settings.townsFolder","Settings","Folders","Towns folder","advanced","advanced","own","","","","src/HexmakerSettingTab.ts:614","" +"Settings.dungeonsFolder","Settings","Folders","Dungeons folder","advanced","advanced","own","","","","src/HexmakerSettingTab.ts:620","" +"Settings.questsFolder","Settings","Folders","Quests folder","advanced","advanced","own","","","","src/HexmakerSettingTab.ts:626","" +"Settings.featuresFolder","Settings","Folders","Features folder","advanced","advanced","own","","","","src/HexmakerSettingTab.ts:632","" +"Settings.factionsFolder","Settings","Folders","Factions folder","advanced","advanced","own","","","","src/HexmakerSettingTab.ts:638","" +"Settings.regionsFolder","Settings","Folders","Regions folder","advanced","advanced","own","","","","src/HexmakerSettingTab.ts:644","" +"Settings.tablesFolder","Settings","Folders","Tables folder","advanced","advanced","own","","","","src/HexmakerSettingTab.ts:650","" +"Settings.workflowsFolder","Settings","Folders","Workflows folder","advanced","advanced","own","","","","src/HexmakerSettingTab.ts:656","" +"Settings.templatesFolder","Settings","Folders","Templates folder","advanced","advanced","own","","","","src/HexmakerSettingTab.ts:662","" +"Settings.palettesFolder","Settings","Folders","Palettes folder","advanced","advanced","own","","","","src/HexmakerSettingTab.ts:668","" +"Settings.biomesFolder","Settings","Folders","Biomes folder","overkill","overkill","own","","","","src/HexmakerSettingTab.ts:674","" +"Settings.biomePoolsFolder","Settings","Folders","Biome pools folder","overkill","overkill","own","","","","src/HexmakerSettingTab.ts:680","" +"Settings.worldTypesFolder","Settings","Folders","World types folder","overkill","overkill","own","","","","src/HexmakerSettingTab.ts:686","" +"Settings.defaultPalette","Settings","Palette management","Palette for new maps","advanced","simple","own","","","","src/HexmakerSettingTab.ts:721","" +"Settings.addDefaultPalettes","Settings","Palette management","Add ","advanced","advanced","own","","","","src/HexmakerSettingTab.ts:731","" +"Settings.paletteRowName","Settings","Palette management","(palette name)","advanced","simple","own","","","","src/HexmakerSettingTab.ts:212","" +"Settings.paletteRowEdit","Settings","Palette management","Edit","advanced","simple","own","","","","src/HexmakerSettingTab.ts:868","" +"Settings.paletteRowOpenNote","Settings","Palette management","Open note","advanced","advanced","own","","","","src/HexmakerSettingTab.ts:871","" +"Settings.paletteDelete","Settings","Palette management","Delete (list delete)","advanced","advanced","own","","","","src/HexmakerSettingTab.ts:748","" +"Settings.addPalette","Settings","Palette management","Add palette","advanced","simple","own","","","","src/HexmakerSettingTab.ts:767","" +"AddPalette.presetOption","Settings","Palette management","","simple","simple","own","","","","src/palettes/AddPaletteModal.ts:30","" +"AddPalette.copyOption","Settings","Palette management","Copy of ","simple","simple","own","","","","src/palettes/AddPaletteModal.ts:46","" +"AddPalette.emptyPalette","Settings","Palette management","Empty palette","simple","simple","own","","","","src/palettes/AddPaletteModal.ts:64","" +"AddPalette.preset","Settings","Palette management"," / (another copy)","keep","keep","own","","","","src/palettes/AddPaletteModal.ts:30","" +"AddPalette.closeButtons","Settings","Palette management","(modal ✕)","keep","keep","own","","","","src/palettes/AddPaletteModal.ts:20","" +"Settings.generateWorldData","Settings","Maintenance","Generate","overkill","overkill","own","","","","src/HexmakerSettingTab.ts:491","but note this might need to be surfaced in the case of debugging etc, we might need to point users to ""all"" if ""health""/""repair"" type settings hide there. " +"Settings.generateFolders","Settings","Maintenance","Generate folders","overkill","overkill","own","","","","src/HexmakerSettingTab.ts:534","" +"Settings.legacyCoordLabelSize","Settings","Legacy (pre-1.13)","Coordinate label (slider)","overkill","overkill","own","","simple (twin Settings.coordFontSize)","Settings.coordFontSize","src/HexmakerSettingTab.ts:1167","this and other stuff like it should just map to the same setting ideally. " +"Settings.legacyCoordLabelFont","Settings","Legacy (pre-1.13)","Coordinate label (font)","overkill","overkill","own","","simple (twin Settings.coordFontFamily)","Settings.coordFontFamily","src/HexmakerSettingTab.ts:1178","" +"Settings.legacyCoordLabelColor","Settings","Legacy (pre-1.13)","Coordinate label (color)","overkill","overkill","own","","simple (twin Settings.coordFontColor)","Settings.coordFontColor","src/HexmakerSettingTab.ts:1193","" +"Settings.legacyHexNameFont","Settings","Legacy (pre-1.13)","Hex name font (font)","overkill","overkill","own","","simple (twin Settings.hexNameFont)","Settings.hexNameFont","src/HexmakerSettingTab.ts:1214","" +"Settings.legacyHexNameSize","Settings","Legacy (pre-1.13)","Hex name font (size)","overkill","overkill","own","","simple (twin Settings.hexNameSize)","Settings.hexNameSize","src/HexmakerSettingTab.ts:1221","" +"Settings.legacyHexNameStyle","Settings","Legacy (pre-1.13)","Hex name font (style)","overkill","overkill","own","","simple (twin Settings.hexNameStyle)","Settings.hexNameStyle","src/HexmakerSettingTab.ts:1228","" +"Settings.legacyNewMapCols","Settings","Legacy (pre-1.13)","Default new map size (Cols)","advanced","advanced","own","","","Settings.defaultNewMapCols","src/HexmakerSettingTab.ts:1263","" +"Settings.legacyNewMapRows","Settings","Legacy (pre-1.13)","Default new map size (Rows)","advanced","advanced","own","","","Settings.defaultNewMapRows","src/HexmakerSettingTab.ts:1272","" +"Settings.legacySubmapCols","Settings","Legacy (pre-1.13)","Default submap size (Cols)","advanced","advanced","own","","","Settings.defaultSubmapCols","src/HexmakerSettingTab.ts:1285","" +"Settings.legacySubmapRows","Settings","Legacy (pre-1.13)","Default submap size (Rows)","advanced","advanced","own","","","Settings.defaultSubmapRows","src/HexmakerSettingTab.ts:1294","" +"Settings.legacyPaletteDeleteButton","Settings","Legacy (pre-1.13)","Delete","advanced","simple","own","","advanced (twin Settings.paletteDelete)","Settings.paletteDelete","src/HexmakerSettingTab.ts:1742","i think custom palettes should be simple. We want a streamlined but still customizable experience for simple, not to hide every little possible scary thing. " +"Wizard.mapKindWorld","Setup wizard","Welcome","World / fantasy overland","keep","keep","group","group:Setup wizard/Welcome","","","src/SetupWizardView.ts:243","" +"Wizard.mapKindSpace","Setup wizard","Welcome","Space","keep","keep","group","group:Setup wizard/Welcome","","","src/SetupWizardView.ts:243","" +"Wizard.featureLevel","Setup wizard","Welcome","How much do you want to start with? (Simple/Advanced)","keep","keep","group","group:Setup wizard/Welcome","","","src/SetupWizardView.ts:261","" +"Wizard.worldFolder","Setup wizard","Folders","World folder","keep","keep","group","group:Setup wizard/Folders","","","src/SetupWizardView.ts:304","" +"Wizard.configureFoldersIndividually","Setup wizard","Folders","Configure each folder path individually","advanced","advanced","group","group:Setup wizard/Folders","","","src/SetupWizardView.ts:324","" +"Wizard.folder.hex","Setup wizard","Folders","Hex notes","keep","keep","group","group:Setup wizard/Folders","","","src/SetupWizardView.ts:350","" +"Wizard.folder.towns","Setup wizard","Folders","Towns","keep","keep","group","group:Setup wizard/Folders","","","src/SetupWizardView.ts:350","" +"Wizard.folder.dungeons","Setup wizard","Folders","Dungeons","keep","keep","group","group:Setup wizard/Folders","","","src/SetupWizardView.ts:350","" +"Wizard.folder.quests","Setup wizard","Folders","Quests","keep","keep","group","group:Setup wizard/Folders","","","src/SetupWizardView.ts:350","" +"Wizard.folder.features","Setup wizard","Folders","Features","keep","keep","group","group:Setup wizard/Folders","","","src/SetupWizardView.ts:350","" +"Wizard.folder.factions","Setup wizard","Folders","Factions","keep","keep","group","group:Setup wizard/Folders","","","src/SetupWizardView.ts:350","" +"Wizard.folder.regions","Setup wizard","Folders","Regions","keep","keep","group","group:Setup wizard/Folders","","","src/SetupWizardView.ts:350","" +"Wizard.folder.tables","Setup wizard","Folders","Tables","keep","keep","group","group:Setup wizard/Folders","","","src/SetupWizardView.ts:350","" +"Wizard.folder.workflows","Setup wizard","Folders","Workflows","keep","keep","group","group:Setup wizard/Folders","","","src/SetupWizardView.ts:350","" +"Wizard.folder.templates","Setup wizard","Folders","Templates","keep","keep","group","group:Setup wizard/Folders","","","src/SetupWizardView.ts:350","" +"Wizard.folder.icons","Setup wizard","Folders","Icons","keep","keep","group","group:Setup wizard/Folders","","","src/SetupWizardView.ts:350","" +"Wizard.mapName","Setup wizard","Map","Map name","keep","keep","group","group:Setup wizard/Map","","","src/SetupWizardView.ts:440","" +"Wizard.gridCols","Setup wizard","Map","Grid size (columns)","keep","keep","group","group:Setup wizard/Map","","","src/SetupWizardView.ts:469","" +"Wizard.gridRows","Setup wizard","Map","Grid size (rows)","keep","keep","group","group:Setup wizard/Map","","","src/SetupWizardView.ts:479","" +"Wizard.hexOrientation","Setup wizard","Map","Hex orientation (Flat-top / Pointy-top)","keep","keep","group","group:Setup wizard/Map","","","src/SetupWizardView.ts:544","" +"Wizard.terrainPalette","Setup wizard","Map","Terrain palette","keep","keep","group","group:Setup wizard/Map","","","src/SetupWizardView.ts:579","" +"Wizard.generatorCards","Setup wizard","Map","Terrain (generator cards)","keep","keep","group","group:Setup wizard/Map","","","src/SetupWizardView.ts:633","" +"Wizard.genOptWater","Setup wizard","Map","Water","advanced","advanced","group","group:Setup wizard/Map","","","src/SetupWizardView.ts:647","" +"Wizard.genOptClimate","Setup wizard","Map","Climate","advanced","advanced","group","group:Setup wizard/Map","","","src/SetupWizardView.ts:647","" +"Wizard.genOptRelief","Setup wizard","Map","Relief","advanced","advanced","group","group:Setup wizard/Map","","","src/SetupWizardView.ts:647","" +"Wizard.genOptSea","Setup wizard","Map","Sea","advanced","advanced","group","group:Setup wizard/Map","","","src/SetupWizardView.ts:647","" +"Wizard.genOptOther","Setup wizard","Map","(other generator options)","advanced","advanced","group","group:Setup wizard/Map","","","src/SetupWizardView.ts:647","" +"Wizard.reroll","Setup wizard","Map","Re-roll (dice)","keep","keep","group","group:Setup wizard/Map","","","src/SetupWizardView.ts:607","" +"Wizard.openHexMap","Setup wizard","Done","Open hex map","keep","keep","group","group:Setup wizard/Done","","","src/SetupWizardView.ts:841","" +"Wizard.exploreOnOwn","Setup wizard","Done","I'll explore on my own","keep","keep","group","group:Setup wizard/Done","","","src/SetupWizardView.ts:847","" +"Wizard.back","Setup wizard","Navigation","back","keep","keep","group","group:Setup wizard/Navigation","","","src/SetupWizardView.ts:943","" +"Wizard.next","Setup wizard","Navigation","Next","keep","keep","group","group:Setup wizard/Navigation","","","src/SetupWizardView.ts:957","" +"Wizard.remindLater","Setup wizard","Navigation","Remind me later","keep","keep","group","group:Setup wizard/Navigation","","","src/SetupWizardView.ts:967","" +"Wizard.dontShowAgain","Setup wizard","Navigation","Don't show again","keep","keep","group","group:Setup wizard/Navigation","","","src/SetupWizardView.ts:975","" +"Hint.turnOnFeature","Feature hints","Inline hints","Turn on ","keep","keep","group","group:Feature hints/Inline hints","","","src/advancedHints.ts:158","" +"Hint.close","Feature hints","Inline hints","X (Hide this hint)","keep","keep","group","group:Feature hints/Inline hints","","","src/advancedHints.ts:160","" +"Hints.show","Feature hints","Inline hints","Show","keep","keep","group","group:Feature hints/Inline hints","","","src/advancedHints.ts:191","" +"MoreFeatures.turnOn","Feature hints","More options modal","Turn on","keep","keep","group","group:Feature hints/More options modal","","","src/advancedHints.ts:235","" +"MoreFeatures.turnOnAll","Feature hints","More options modal","Turn on all advanced features","keep","keep","group","group:Feature hints/More options modal","","","src/advancedHints.ts:241","" +"MoreFeatures.closeButtons","Feature hints","More options modal","Done","keep","keep","group","group:Feature hints/More options modal","","","src/advancedHints.ts:244","" +"EnableFeature.turnOnOne","Feature hints","Turn on ? modal","Turn on ","keep","keep","group","group:Feature hints/Turn on ? modal","","","src/advancedHints.ts:274","" +"EnableFeature.turnOnAll","Feature hints","Turn on ? modal","Turn on all advanced features","keep","keep","group","group:Feature hints/Turn on ? modal","","","src/advancedHints.ts:276","" +"EnableFeature.closeButtons","Feature hints","Turn on ? modal","Not now","keep","keep","group","group:Feature hints/Turn on ? modal","","","src/advancedHints.ts:277","" +"Nudge.turnOnAdvanced","Feature hints","Ready for more? modal","Turn on advanced features","keep","keep","group","group:Feature hints/Ready for more? modal","","","src/advancedHints.ts:318","" +"Nudge.closeButtons","Feature hints","Ready for more? modal","Not now","keep","keep","group","group:Feature hints/Ready for more? modal","","","src/advancedHints.ts:323","" +"Nudge.dontAskAgain","Feature hints","Ready for more? modal","Don't ask again","keep","keep","group","group:Feature hints/Ready for more? modal","","","src/advancedHints.ts:324","" +"Plugin.ribbonOpenHexMap","Commands & menus","Open views","Open hex map","simple","simple","group","group:Commands & menus/Open views","","","src/HexmakerPlugin.ts:278","" +"Plugin.cmd.openHexMap","Commands & menus","Open views","Open hex map","keep","keep","group","group:Commands & menus/Open views","","","src/HexmakerPlugin.ts:281","" +"Plugin.cmd.openHexTable","Commands & menus","Open views","Open hex table","simple","simple","group","group:Commands & menus/Open views","","","src/HexmakerPlugin.ts:286","" +"Plugin.cmd.openTerrainGenerator","Commands & menus","Open views","Open terrain generator","keep","keep","group","group:Commands & menus/Open views","","","src/HexmakerPlugin.ts:294","" +"Plugin.cmd.openPaletteEditor","Commands & menus","Open views","Open palette editor","simple","simple","group","group:Commands & menus/Open views","","","src/HexmakerPlugin.ts:299","" +"Plugin.cmd.editWorldTypes","Commands & menus","Open views","Edit world types...","keep","keep","group","group:Commands & menus/Open views","","","src/HexmakerPlugin.ts:304","" +"Plugin.cmd.newOverworld","Commands & menus","Open views","New overworld...","keep","keep","group","group:Commands & menus/Open views","","","src/HexmakerPlugin.ts:316","" +"Plugin.cmd.openRandomTables","Commands & menus","Open views","Open random tables","simple","simple","group","group:Commands & menus/Open views","","","src/HexmakerPlugin.ts:355","" +"WorldTypes.command","Commands & menus","Open views","Edit world types…","keep","keep","twin","Plugin.cmd.editWorldTypes","","Plugin.cmd.editWorldTypes","src/space/WorldTypesModal.ts:311","" +"Plugin.cmd.mapGoUp","Commands & menus","Map navigation commands","Go up to parent map","keep","keep","group","group:Commands & menus/Map navigation commands","","","src/HexmakerPlugin.ts:325","" +"Plugin.cmd.mapGoBack","Commands & menus","Map navigation commands","Go back to previous map","keep","keep","group","group:Commands & menus/Map navigation commands","","","src/HexmakerPlugin.ts:335","" +"Plugin.cmd.mapGoForward","Commands & menus","Map navigation commands","Go forward to the next map","keep","keep","group","group:Commands & menus/Map navigation commands","","","src/HexmakerPlugin.ts:345","" +"Plugin.cmd.addRollRanges","Commands & menus","Maintenance commands","Add roll ranges to tables","overkill","overkill","group","group:Commands & menus/Maintenance commands","","","src/HexmakerPlugin.ts:363","" +"Plugin.cmd.checkTables","Commands & menus","Maintenance commands","Check tables","overkill","overkill","group","group:Commands & menus/Maintenance commands","","","src/HexmakerPlugin.ts:368","" +"Plugin.cmd.addMapDataToHexNotes","Commands & menus","Maintenance commands","Add map data to this map's hex notes","overkill","overkill","group","group:Commands & menus/Maintenance commands","","","src/HexmakerPlugin.ts:416","" +"Plugin.cmd.updateRegionFactionMapData","Commands & menus","Maintenance commands","Update map data in region and faction notes","overkill","overkill","group","group:Commands & menus/Maintenance commands","","","src/HexmakerPlugin.ts:438","" +"Plugin.cmd.exportNotePdf","Commands & menus","Export commands","Export current note to PDF","advanced","advanced","group","group:Commands & menus/Export commands","","","src/HexmakerPlugin.ts:373","" +"Plugin.cmd.exportNoteMarkdown","Commands & menus","Export commands","Export current note to Markdown","advanced","advanced","group","group:Commands & menus/Export commands","","","src/HexmakerPlugin.ts:383","" +"Plugin.cmd.exportCurrentHex","Commands & menus","Export commands","Export current hex (structured PDF / Markdown)","simple","simple","group","group:Commands & menus/Export commands","","","src/HexmakerPlugin.ts:393","" +"Plugin.cmd.exportCurrentWorkflow","Commands & menus","Export commands","Export current workflow with rolled samples","advanced","advanced","group","group:Commands & menus/Export commands","","","src/HexmakerPlugin.ts:403","" +"Plugin.cmd.exportCurrentMap","Commands & menus","Export commands","Export current map...","simple","simple","group","group:Commands & menus/Export commands","","","src/HexmakerPlugin.ts:456","" +"Plugin.fileMenuExportPdf","Commands & menus","Note right-click menus","Export to PDF","advanced","advanced","group","group:Commands & menus/Note right-click menus","","","src/HexmakerPlugin.ts:473","" +"Plugin.fileMenuExportMarkdown","Commands & menus","Note right-click menus","Export to Markdown","advanced","advanced","group","group:Commands & menus/Note right-click menus","","","src/HexmakerPlugin.ts:480","" +"Plugin.editorMenuInsertRoller","Commands & menus","Note right-click menus","Insert table roller","keep","keep","group","group:Commands & menus/Note right-click menus","","","src/HexmakerPlugin.ts:506","" +"Plugin.editorMenuInsertMapLink","Commands & menus","Note right-click menus","Insert map link","keep","keep","group","group:Commands & menus/Note right-click menus","","","src/HexmakerPlugin.ts:523","" +"Plugin.insertRollerPicker","Commands & menus","Note right-click menus","Search for a file to link...","keep","keep","twin","Editor.insertTableRoller","","Editor.insertTableRoller","src/hex-map/FileLinkSuggestModal.ts:19","" +"Editor.insertTableRoller","Commands & menus","Note right-click menus","Search for a file to link...","keep","keep","group","group:Commands & menus/Note right-click menus","","","src/HexmakerPlugin.ts:512","" +"MapToolbar.hexTableBtn","Hex map view","Top bar","Open hex table (⊞)","simple","simple","group","group:Hex map view","","","src/hex-map/HexMapView.ts:1473","" +"MapToolbar.randomTablesBtn","Hex map view","Top bar","Open random tables (🎲)","simple","simple","group","group:Hex map view","","","src/hex-map/HexMapView.ts:1497","" +"MapToolbar.mapSwitcher","Hex map view","Top bar"," ▾ (Manage maps)","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:1529","" +"MapToolbar.workModeBtn","Hex map view","Top bar","Mode: Play / Build / God","simple","simple","group","group:Hex map view","","","src/hex-map/HexMapView.ts:1551","" +"MapToolbar.undo","Hex map view","Top bar","Undo (up to 20) ↩","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:1555","" +"MapToolbar.redo","Hex map view","Top bar","Redo ↪","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:1565","" +"MapToolbar.help","Hex map view","Top bar","Controls & tools (?)","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:1577","" +"MapToolbar.drawingToolsToggle","Hex map view","Top bar","Drawing tools (pencil)","keep","keep","group","group:Hex map view","","","src/hex-map/HexSidePanel.ts:22","" +"MapToolbar.layersToggle","Hex map view","Top bar","Map overlays (layers)","keep","keep","group","group:Hex map view","","","src/hex-map/HexSidePanel.ts:22","" +"MapNav.breadcrumb","Hex map view","Map navigation","Go to (breadcrumb)","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:690","" +"MapNav.back","Hex map view","Map navigation","← Back to (Alt+←)","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:723","" +"MapNav.up","Hex map view","Map navigation","↑ Up to (Alt+↑)","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:723","" +"MapNav.forward","Hex map view","Map navigation","→ Forward to (Alt+→)","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:723","" +"MapNav.regionFlowerHere","Hex map view","Map navigation","Here: . Click to edit this region.","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:859","" +"MapNav.regionFlowerPetal","Hex map view","Map navigation"," petal","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:878","" +"MapNav.regionFlowerNewLand","Hex map view","Map navigation","+ (new land petal)","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:878","" +"MapNav.mapPadGo","Hex map view","Map navigation","D-pad neighbour map (◀▲▶▼)","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:921","" +"MapNav.mapPadNew","Hex map view","Map navigation","+ (new neighbouring map)","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:921","" +"WorkModeMenu.play","Hex map view","Work modes","Play: Run a game…","simple","simple","group","group:Hex map view","","","src/hex-map/HexMapView.ts:758","" +"WorkModeMenu.build","Hex map view","Work modes","Build: Add to and edit the map…","simple","simple","group","group:Hex map view","","","src/hex-map/HexMapView.ts:758","" +"WorkModeMenu.god","Hex map view","Work modes","God: Change anything…","advanced","advanced","own","","","","src/hex-map/HexMapView.ts:758","Yes but ask to enable it and other things when they start poking around region/generators/etc." +"ModeBar.stop","Hex map view","Work modes","Stop this tool (✕)","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:1032","" +"ModeBar.autoRoute","Hex map view","Work modes","Auto-route","simple","simple","group","group:Hex map view","","","src/hex-map/pathTool.ts:1423","" +"ModeBar.crossImpassable","Hex map view","Work modes","Cross impassable","advanced","advanced","group","group:Hex map view","","","src/hex-map/pathTool.ts:1453","" +"ModeBar.pathNameChip","Hex map view","Work modes"," (Rename this path)","keep","keep","group","group:Hex map view","","","src/hex-map/pathTool.ts:1462","" +"ModeBar.newPath","Hex map view","Work modes","New path","simple","simple","group","group:Hex map view","","","src/hex-map/pathTool.ts:1469","" +"ModeBar.done","Hex map view","Work modes","Done","simple","simple","group","group:Hex map view","","","src/hex-map/pathTool.ts:1477","" +"ModeBar.confirmIntoRegions","Hex map view","Work modes","Confirm into regions / Update regions","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:6253","" +"DrawingPanel.centerHex","Hex map view","Drawing tools","Center hex","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:2023","" +"DrawingPanel.terrain","Hex map view","Drawing tools","Terrain","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:2031","" +"DrawingPanel.biome","Hex map view","Drawing tools","Biome","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:2043","" +"DrawingPanel.icon","Hex map view","Drawing tools","Icon","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:2051","" +"DrawingPanel.path","Hex map view","Drawing tools","Path","simple","simple","group","group:Hex map view","","","src/hex-map/HexMapView.ts:2062","" +"DrawingPanel.linkTable","Hex map view","Drawing tools","Link table","advanced","advanced","group","group:Hex map view","","","src/hex-map/HexMapView.ts:2073","" +"DrawingPanel.linkSubmap","Hex map view","Drawing tools","Link submap","advanced","advanced","group","group:Hex map view","","","src/hex-map/HexMapView.ts:2083","" +"DrawingPanel.factions","Hex map view","Drawing tools","Factions","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:2093","" +"DrawingPanel.regionAreas","Hex map view","Drawing tools","Region areas","advanced","advanced","group","group:Hex map view","","","src/hex-map/HexMapView.ts:2103","" +"DrawingPanel.token","Hex map view","Drawing tools","Token","simple","simple","group","group:Hex map view","","","src/hex-map/HexMapView.ts:2113","" +"MapView.tableLinkToolPicker","Hex map view","Drawing tools","Select table","advanced","advanced","twin","DrawingPanel.linkTable","","DrawingPanel.linkTable","src/hex-map/HexMapView.ts:2424","" +"PainterMenu.switchTerrain","Hex map view","Tool right-click menus","Switch terrain","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:2145","" +"PainterMenu.switchIcon","Hex map view","Tool right-click menus","Switch icon","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:2149","" +"PainterMenu.switchTable","Hex map view","Tool right-click menus","Switch table","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:2153","" +"PainterMenu.switchSubmap","Hex map view","Tool right-click menus","Switch submap","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:2157","" +"PainterMenu.switchFaction","Hex map view","Tool right-click menus","Switch faction","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:2161","" +"PainterMenu.switchRegion","Hex map view","Tool right-click menus","Switch region","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:2165","" +"PainterMenu.switchPathType","Hex map view","Tool right-click menus","Switch path type","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:2169","" +"PainterMenu.switchToken","Hex map view","Tool right-click menus","Switch token","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:2173","" +"PainterMenu.switchBiome","Hex map view","Tool right-click menus","Switch biome","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:2176","" +"PainterMenu.exitTool","Hex map view","Tool right-click menus","Exit tool","keep","keep","group","group:Hex map view","","","src/hex-map/PainterContextMenu.ts:24","" +"PainterMenu.eraseToggle","Hex map view","Tool right-click menus","Erase mode / Paint (Link, Draw) mode","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:2146","" +"PainterMenu.newPath","Hex map view","Tool right-click menus","New path","drop","drop","group","group:Hex map view","","","src/hex-map/HexMapView.ts:2171","" +"PathMenu.splitHere","Hex map view","Tool right-click menus","Split here","advanced","advanced","group","group:Hex map view","","","src/hex-map/pathTool.ts:296","" +"PathMenu.deleteBranch","Hex map view","Tool right-click menus","Delete this fork / Delete main line","keep","keep","group","group:Hex map view","","","src/hex-map/pathTool.ts:297","" +"PathMenu.deletePath","Hex map view","Tool right-click menus","Delete path: ","simple","simple","group","group:Hex map view","","","src/hex-map/pathTool.ts:299","" +"PathMenu.rename","Hex map view","Tool right-click menus","Rename…","simple","simple","group","group:Hex map view","","","src/hex-map/pathTool.ts:300","" +"PathMenu.changeType","Hex map view","Tool right-click menus","Change type…","keep","keep","group","group:Hex map view","","","src/hex-map/pathTool.ts:301","" +"PathMenu.reverse","Hex map view","Tool right-click menus","Reverse","advanced","advanced","group","group:Hex map view","","","src/hex-map/pathTool.ts:302","" +"PathMenu.switchToType","Hex map view","Tool right-click menus","Switch to to edit ","keep","keep","group","group:Hex map view","","","src/hex-map/pathTool.ts:1075","" +"PathMenu.confirmIntoRegions","Hex map view","Tool right-click menus","Confirm into regions / Update regions","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:6274","" +"PathMenu.removeFromRegions","Hex map view","Tool right-click menus","Remove from regions","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:6274","" +"HexMenu.center","Hex map view","Hex right-click menu","Center on this hex","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:4773","" +"HexMenu.openNote","Hex map view","Hex right-click menu","Open note","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:4777","" +"HexMenu.enterRegion","Hex map view","Hex right-click menu","Enter region: ","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:4792","" +"HexMenu.openLocation","Hex map view","Hex right-click menu","Open: ","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:4795","" +"HexMenu.locationsList","Hex map view","Hex right-click menu","Locations (n)…","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:4801","" +"HexMenu.newMap","Hex map view","Hex right-click menu","New map from this hex…","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:4803","" +"HexMenu.linkExistingMap","Hex map view","Hex right-click menu","Link existing map…","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:4804","" +"HexMenu.manageLocations","Hex map view","Hex right-click menu","Manage locations…","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:4807","" +"HexMenu.linkTable","Hex map view","Hex right-click menu","Link table","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:4810","" +"HexMenu.swapHex","Hex map view","Hex right-click menu","Swap hex","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:4828","" +"HexMenu.createToken","Hex map view","Hex right-click menu","Create token here","simple","simple","group","group:Hex map view","","","src/hex-map/HexMapView.ts:4833","" +"HexMenu.clearTerrain","Hex map view","Hex right-click menu","Clear terrain","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:4839","" +"HexMenu.removeIconOverride","Hex map view","Hex right-click menu","Remove icon override","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:4844","" +"HexMenu.lockedHint","Hex map view","Hex right-click menu","Switch to Build to … (disabled)","keep","keep","group","group:Hex map view","","","src/hex-map/modeMenu.ts:52","" +"MapView.linkTableMenuPicker","Hex map view","Hex right-click menu","Link table","keep","keep","twin","HexMenu.linkTable","","HexMenu.linkTable","src/hex-map/HexMapView.ts:4811","" +"OverworldMenu.enterRegion","Hex map view","Overworld menu & minimap","Enter region: ","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:4871","" +"OverworldMenu.editRegion","Hex map view","Overworld menu & minimap","Edit region…","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:4871","" +"OverworldMenu.setBiome","Hex map view","Overworld menu & minimap","Set biome…","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:4871","" +"OverworldMenu.center","Hex map view","Overworld menu & minimap","Center on this hex","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:4871","" +"OverworldMenu.locations","Hex map view","Overworld menu & minimap","Locations (n)…","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:4871","" +"OverworldMenu.createToken","Hex map view","Overworld menu & minimap","Create token here","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:4882","" +"Minimap.viewRegions","Hex map view","Overworld menu & minimap","View: Regions","keep","keep","group","group:Hex map view","","","src/hex-map/overworldMinimap.ts:61","" +"Minimap.viewBiomes","Hex map view","Overworld menu & minimap","View: Biomes","keep","keep","group","group:Hex map view","","","src/hex-map/overworldMinimap.ts:61","" +"Minimap.biomeLibrary","Hex map view","Overworld menu & minimap","Biomes…","keep","keep","group","group:Hex map view","","","src/hex-map/overworldMinimap.ts:71","" +"Minimap.toggle","Hex map view","Overworld menu & minimap","Show / Hide the overworld map","keep","keep","group","group:Hex map view","","","src/hex-map/overworldMinimap.ts:79","" +"Minimap.canvasClick","Hex map view","Overworld menu & minimap","Overworld minimap (click to go)","keep","keep","group","group:Hex map view","","","src/hex-map/overworldMinimap.ts:122","" +"OverworldMinimap.viewRegions","Hex map view","Overworld menu & minimap","View: Regions","keep","keep","twin","Minimap.viewRegions","","Minimap.viewRegions","src/hex-map/overworldMinimap.ts:393","" +"OverworldMinimap.viewBiomes","Hex map view","Overworld menu & minimap","View: Biomes","keep","keep","twin","Minimap.viewBiomes","","Minimap.viewBiomes","src/hex-map/overworldMinimap.ts:393","" +"OverworldMinimap.biomes","Hex map view","Overworld menu & minimap","Biomes…","keep","keep","twin","Minimap.biomeLibrary","","Minimap.biomeLibrary","src/hex-map/overworldMinimap.ts:403","" +"OverworldMinimap.toggle","Hex map view","Overworld menu & minimap","Show/Hide the overworld map","keep","keep","twin","Minimap.toggle","","Minimap.toggle","src/hex-map/overworldMinimap.ts:411","" +"OverworldMinimap.canvasClick","Hex map view","Overworld menu & minimap","(minimap hex click)","keep","keep","twin","Minimap.canvasClick","","Minimap.canvasClick","src/hex-map/overworldMinimap.ts:454","" +"OverworldMenu.enterRegion_2","Hex map view","Overworld menu & minimap","Enter region","keep","keep","twin","OverworldMenu.enterRegion","","OverworldMenu.enterRegion","src/overworld/overworldInput.ts:71","" +"OverworldMenu.editRegion_2","Hex map view","Overworld menu & minimap","Edit region…","keep","keep","twin","OverworldMenu.editRegion","","OverworldMenu.editRegion","src/overworld/overworldInput.ts:72","" +"OverworldMenu.setBiome_2","Hex map view","Overworld menu & minimap","Set biome…","keep","keep","twin","OverworldMenu.setBiome","","OverworldMenu.setBiome","src/overworld/overworldInput.ts:75","" +"OverworldMenu.center_2","Hex map view","Overworld menu & minimap","Center on this hex","keep","keep","twin","OverworldMenu.center","","OverworldMenu.center","src/overworld/overworldInput.ts:77","" +"OverworldMenu.locations_2","Hex map view","Overworld menu & minimap","Locations (n)…","keep","keep","twin","OverworldMenu.locations","","OverworldMenu.locations","src/overworld/overworldInput.ts:78","" +"TokenMenu.info","Hex map view","Token right-click menu","Token info","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:8010","" +"TokenMenu.edit","Hex map view","Token right-click menu","Edit token","simple","simple","group","group:Hex map view","","","src/hex-map/HexMapView.ts:8011","" +"TokenMenu.openNote","Hex map view","Token right-click menu","Open note","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:8012","" +"TokenMenu.remove","Hex map view","Token right-click menu","Remove token","simple","simple","group","group:Hex map view","","","src/hex-map/HexMapView.ts:8017","" +"LayersMenu.coordinates","Hex map view","Layers panel","Coordinates","keep","keep","group","group:Hex map view","","","src/hex-map/HexSidePanel.ts:105","" +"LayersMenu.hexNames","Hex map view","Layers panel","Hex names","keep","keep","group","group:Hex map view","","","src/hex-map/HexSidePanel.ts:106","" +"LayersMenu.tokenNames","Hex map view","Layers panel","Token names","keep","keep","group","group:Hex map view","","","src/hex-map/HexSidePanel.ts:107","" +"LayersMenu.nameFontBtn","Hex map view","Layers panel","Aa (Hex name font)","simple","simple","group","group:Hex map view","","","src/hex-map/HexSidePanel.ts:319","" +"LayersMenu.nameFontFamily","Hex map view","Layers panel","Font","keep","keep","group","group:Hex map view","","","src/hex-map/HexSidePanel.ts:337","" +"LayersMenu.nameSize","Hex map view","Layers panel","Name size S / M / L / XL","keep","keep","group","group:Hex map view","","","src/hex-map/HexSidePanel.ts:347","" +"LayersMenu.nameBold","Hex map view","Layers panel","Bold (B)","keep","keep","group","group:Hex map view","","","src/hex-map/HexSidePanel.ts:371","" +"LayersMenu.nameItalic","Hex map view","Layers panel","Italic (I)","keep","keep","group","group:Hex map view","","","src/hex-map/HexSidePanel.ts:372","" +"LayersMenu.nameFontReset","Hex map view","Layers panel","Use the default name font (settings)","keep","keep","group","group:Hex map view","","","src/hex-map/HexSidePanel.ts:374","" +"LayersMenu.terrainIcons","Hex map view","Layers panel","Show terrain icons","keep","keep","group","group:Hex map view","","","src/hex-map/HexSidePanel.ts:102","" +"LayersMenu.iconOverrides","Hex map view","Layers panel","Show icon overrides","keep","keep","group","group:Hex map view","","","src/hex-map/HexSidePanel.ts:103","" +"LayersMenu.paths","Hex map view","Layers panel","Show paths","keep","keep","group","group:Hex map view","","","src/hex-map/HexSidePanel.ts:104","" +"LayersMenu.tokens","Hex map view","Layers panel","Show tokens","keep","keep","group","group:Hex map view","","","src/hex-map/HexSidePanel.ts:153","" +"LayersMenu.factionOverlay","Hex map view","Layers panel","Show faction overlay","keep","keep","group","group:Hex map view","","","src/hex-map/HexSidePanel.ts:178","" +"LayersMenu.regionOverlay","Hex map view","Layers panel","Show region overlay","advanced","advanced","group","group:Hex map view","","","src/hex-map/HexSidePanel.ts:202","" +"LayersMenu.gmLayer","Hex map view","Layers panel","Show GM layer","keep","keep","group","group:Hex map view","","","src/hex-map/HexSidePanel.ts:226","" +"LayersMenu.linkBadges","Hex map view","Layers panel","Show link badges","keep","keep","group","group:Hex map view","","","src/hex-map/HexSidePanel.ts:430","" +"LayersMenu.badgeSize","Hex map view","Layers panel","Badge size S / M / L","simple","simple","group","group:Hex map view","","","src/hex-map/HexSidePanel.ts:436","" +"LayersMenu.badgeTypesMore","Hex map view","Layers panel","Pick badge types (▸)","simple","simple","group","group:Hex map view","","","src/hex-map/HexSidePanel.ts:451","" +"LayersMenu.badgeTowns","Hex map view","Layers panel","Towns badges","keep","keep","group","group:Hex map view","","","src/hex-map/HexSidePanel.ts:484","" +"LayersMenu.badgeDungeons","Hex map view","Layers panel","Dungeons badges","keep","keep","group","group:Hex map view","","","src/hex-map/HexSidePanel.ts:484","" +"LayersMenu.badgeFeatures","Hex map view","Layers panel","Features badges","keep","keep","group","group:Hex map view","","","src/hex-map/HexSidePanel.ts:484","" +"LayersMenu.badgeQuests","Hex map view","Layers panel","Quests badges","keep","keep","group","group:Hex map view","","","src/hex-map/HexSidePanel.ts:484","" +"LayersMenu.badgeFactions","Hex map view","Layers panel","Factions badges","keep","keep","group","group:Hex map view","","","src/hex-map/HexSidePanel.ts:484","" +"LayersMenu.legend","Hex map view","Layers panel","Show legend","keep","keep","group","group:Hex map view","","","src/hex-map/HexSidePanel.ts:251","" +"Legend.size","Hex map view","Legend, grid edges & notices","Legend size S / M / L","simple","simple","group","group:Hex map view","","","src/hex-map/terrainLegend.ts:160","" +"Legend.minimize","Hex map view","Legend, grid edges & notices","Minimize (–)","keep","keep","group","group:Hex map view","","","src/hex-map/terrainLegend.ts:171","" +"Legend.hide","Hex map view","Legend, grid edges & notices","Hide legend (×)","keep","keep","group","group:Hex map view","","","src/hex-map/terrainLegend.ts:183","" +"Legend.expandChip","Hex map view","Legend, grid edges & notices","Legend (Show the legend)","keep","keep","group","group:Hex map view","","","src/hex-map/terrainLegend.ts:145","" +"MapGrid.expand","Hex map view","Legend, grid edges & notices","+ (grow edge, 4 sides)","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:1961","" +"MapGrid.shrink","Hex map view","Legend, grid edges & notices","− / OK? (shrink edge, 4 sides)","simple","simple","group","group:Hex map view","","","src/hex-map/HexMapView.ts:1966","" +"PathTool.rerouteInstead","Hex map view","Legend, grid edges & notices","Reroute instead","keep","keep","group","group:Hex map view","","","src/paths/routePins.ts:196","" +"MapView.calibrationDone","Hex map view","Mouse & keyboard","Done calibrating (✓)","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:3680","" +"MapView.missingRestore","Hex map view","Mouse & keyboard","Restore","keep","keep","group","group:Hex map view","","","src/hex-map/MapModal.ts:46","" +"MapView.missingRemove","Hex map view","Mouse & keyboard","Remove","keep","keep","group","group:Hex map view","","","src/hex-map/MapModal.ts:52","" +"MapView.hexClick","Hex map view","Mouse & keyboard","Click hex","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:4897","" +"MapView.hexCtrlClick","Hex map view","Mouse & keyboard","Ctrl/Cmd+click hex","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:4953","" +"MapView.hexCtrlShiftClick","Hex map view","Mouse & keyboard","Ctrl/Cmd+Shift+click hex","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:4957","" +"MapView.hexRightClick","Hex map view","Mouse & keyboard","Right-click hex","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:1451","" +"MapView.locationBadge","Hex map view","Mouse & keyboard","Location badge (Enter location / Locations)","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:4423","" +"MapView.regionShadowHex","Hex map view","Mouse & keyboard","Neighbouring region hex (shadow)","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:4638","" +"MapView.overworldClick","Hex map view","Mouse & keyboard","Click overworld hex","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:4936","" +"MapView.tokenDrag","Hex map view","Mouse & keyboard","Drag token","simple","simple","group","group:Hex map view","","","src/hex-map/HexMapView.ts:7853","" +"MapView.tokenRightClick","Hex map view","Mouse & keyboard","Right-click token","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:7840","" +"MapView.wheelZoom","Hex map view","Mouse & keyboard","Mouse wheel","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:1100","" +"MapView.dragPan","Hex map view","Mouse & keyboard","Drag (left/middle/right)","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:1147","" +"MapView.dblRightClickExit","Hex map view","Mouse & keyboard","Double right-click","drop","drop","group","group:Hex map view","","","src/hex-map/HexMapView.ts:1395","" +"MapView.dblClickOffGridExit","Hex map view","Mouse & keyboard","Double-click off the grid","drop","drop","group","group:Hex map view","","","src/hex-map/HexMapView.ts:1458","" +"MapView.gmIconRightClick","Hex map view","Mouse & keyboard","Right-click hex (GM icon paint)","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:1408","" +"PathTool.anchorRightClick","Hex map view","Mouse & keyboard","Right-click path anchor","keep","keep","group","group:Hex map view","","","src/hex-map/pathTool.ts:1063","" +"PathTool.anchorDrag","Hex map view","Mouse & keyboard","Drag path point/line","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:1270","" +"Keys.escape","Hex map view","Mouse & keyboard","Esc","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:1043","" +"Keys.undoRedo","Hex map view","Mouse & keyboard","Ctrl/Cmd+Z, Ctrl/Cmd+Shift+Z","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:990","" +"Keys.altArrows","Hex map view","Mouse & keyboard","Alt+← / Alt+↑ / Alt+→","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:1001","" +"Keys.deleteAnchor","Hex map view","Mouse & keyboard","Backspace / Delete","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:1055","" +"Keys.altClickNewPath","Hex map view","Mouse & keyboard","Alt+click","keep","keep","group","group:Hex map view","","","src/hex-map/pathTool.ts:1472","" +"Keys.calibrationArrows","Hex map view","Mouse & keyboard","Arrow keys (Shift = 10px)","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:3605","" +"HexEditor.centerOnHex","Hex editor","Header","⌖","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:196","" +"HexEditor.openNote","Hex editor","Header","Open note","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:216","" +"HexEditor.exportHex","Hex editor","Header","Export","simple","simple","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:224","" +"HexEditor.runWorkflow","Hex editor","Header","Run workflow","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:236","" +"HexEditor.workflowPicker","Hex editor","Header","Pick a workflow to run…","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:1660","" +"HexEditor.neighborTile","Hex editor","Header","Neighbour hex tiles","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:578","" +"HexEditor.neighborCrossRegion","Hex editor","Header","Neighbour tile (other region)","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:600","" +"HexEditor.neighborWalkOverworld","Hex editor","Header","Neighbour tile (new region)","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:621","" +"HexEditor.neighborNewLand","Hex editor","Header","Neighbour tile (new land)","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:636","" +"HexEditor.neighborCentreDot","Hex editor","Header","Centre dot","drop","drop","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:660","do these actually link directly to a given hex? If a map is big enough I could see wanting to let a note direct-link a centered view on it, if this is the case then we should consider keeping this, maybe even as simple. " +"HexEditor.nameInput","Hex editor","Header","Name","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:449","" +"HexEditor.mapsChip","Hex editor","Header","Maps: region/location chips","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:694","" +"HexEditor.mapsAdd","Hex editor","Header","+ (Maps)","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:709","" +"HexEditor.mapsNewMap","Hex editor","Header","New map from this hex…","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:713","" +"HexEditor.mapsLinkExisting","Hex editor","Header","Link existing map…","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:715","" +"HexEditor.mapsManageLocations","Hex editor","Header","Manage locations (N)…","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:718","" +"HexEditor.closeButtons","Hex editor","Header","Close (×)","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:428","" +"HexEditor.collapseTerrain","Hex editor","Section headers","Terrain ▶/▼","keep","keep","group","group:Hex editor/Section headers","","","src/hex-map/HexEditorModal.ts:276","" +"HexEditor.collapseNotes","Hex editor","Section headers","Notes ▶/▼","keep","keep","group","group:Hex editor/Section headers","","","src/hex-map/HexEditorModal.ts:298","" +"HexEditor.collapseLinked","Hex editor","Section headers","Linked notes ▶/▼","keep","keep","group","group:Hex editor/Section headers","","","src/hex-map/HexEditorModal.ts:356","" +"HexEditor.collapseIcons","Hex editor","Section headers","Icons ▶/▼","keep","keep","group","group:Hex editor/Section headers","","","src/hex-map/HexEditorModal.ts:414","" +"HexEditor.terrainChangeHint","Hex editor","Terrain","▸ change","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:286","" +"HexEditor.terrainFilter","Hex editor","Terrain","Filter terrains…","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:815","" +"HexEditor.terrainPicker","Hex editor","Terrain","Terrain swatches","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:860","" +"HexEditor.terrainClear","Hex editor","Terrain","Clear","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:846","" +"HexEditor.bodyFieldUseOnMap","Hex editor","Terrain","Use ""X"" on the map","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:1493","" +"HexEditor.bodyFieldUpdateNote","Hex editor","Terrain","Change the note to ""X""","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:1510","" +"HexEditor.description","Hex editor","Notes","Description","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:1575","" +"HexEditor.descriptionRoll","Hex editor","Notes","📖","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:1584","" +"HexEditor.landmark","Hex editor","Notes","Landmark","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:1575","" +"HexEditor.landmarkRoll","Hex editor","Notes","📖","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:1584","" +"HexEditor.hidden","Hex editor","Notes","Hidden","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:1575","" +"HexEditor.hiddenRoll","Hex editor","Notes","📖","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:1584","" +"HexEditor.secret","Hex editor","Notes","Secret","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:1575","" +"HexEditor.secretRoll","Hex editor","Notes","📖","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:1584","" +"HexEditor.gmLayerShow","Hex editor","Notes","Show them","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:319","" +"HexEditor.rolledSectionsFold","Hex editor","Notes","Weather · Hooks & Rumors","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:329","" +"HexEditor.weather","Hex editor","Notes","Weather","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:332","" +"HexEditor.weatherRoll","Hex editor","Notes","🎲 (Weather)","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:1710","" +"HexEditor.weatherSource","Hex editor","Notes","⋯ (Weather)","advanced","advanced","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:1711","" +"HexEditor.hooks","Hex editor","Notes","Hooks & Rumors","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:332","" +"HexEditor.hooksRoll","Hex editor","Notes","🎲 (Hooks & Rumors)","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:1710","" +"HexEditor.hooksSource","Hex editor","Notes","⋯ (Hooks & Rumors)","advanced","advanced","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:1711","" +"HexEditor.rolledSetMapTable","Hex editor","Notes","Set/Change the map's … table…","advanced","advanced","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:1760","" +"HexEditor.rolledSetHexTable","Hex editor","Notes","Use a different table for this hex…","advanced","advanced","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:1761","" +"HexEditor.rolledUseMapTable","Hex editor","Notes","Use the map's table on this hex","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:1763","" +"HexEditor.rolledTablePicker","Hex editor","Notes","Weather/rumour table chooser","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:1722","" +"HexEditor.moreInNoteFold","Hex editor","Notes","More in this note (N)","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:345","" +"HexEditor.moreInNoteText","Hex editor","Notes"," (other sections)","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:348","" +"HexEditor.sectionTablePicker","Hex editor","Notes","(set map's / this hex's table)","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:1722","" +"HexEditor.encountersLink","Hex editor","Linked notes","Encounters Table","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:1144","" +"HexEditor.encountersShowAll","Hex editor","Linked notes","▾","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:1151","" +"HexEditor.encountersCreate","Hex editor","Linked notes","+ Create ""…""","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:1272","" +"HexEditor.encountersOpenLink","Hex editor","Linked notes","","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:1440","" +"HexEditor.encountersRemove","Hex editor","Linked notes","×","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:1459","" +"HexEditor.townsLink","Hex editor","Linked notes","Towns","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:1144","" +"HexEditor.townsShowAll","Hex editor","Linked notes","▾","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:1151","" +"HexEditor.townsCreate","Hex editor","Linked notes","+ Create ""…""","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:1272","" +"HexEditor.townsOpenLink","Hex editor","Linked notes","","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:1440","" +"HexEditor.townsRemove","Hex editor","Linked notes","×","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:1459","" +"HexEditor.dungeonsLink","Hex editor","Linked notes","Dungeons","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:1144","" +"HexEditor.dungeonsShowAll","Hex editor","Linked notes","▾","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:1151","" +"HexEditor.dungeonsCreate","Hex editor","Linked notes","+ Create ""…""","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:1272","" +"HexEditor.dungeonsOpenLink","Hex editor","Linked notes","","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:1440","" +"HexEditor.dungeonsRemove","Hex editor","Linked notes","×","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:1459","" +"HexEditor.questsLink","Hex editor","Linked notes","Quests","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:1144","" +"HexEditor.questsShowAll","Hex editor","Linked notes","▾","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:1151","" +"HexEditor.questsCreate","Hex editor","Linked notes","+ Create ""…""","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:1272","" +"HexEditor.questsOpenLink","Hex editor","Linked notes","","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:1440","" +"HexEditor.questsRemove","Hex editor","Linked notes","×","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:1459","" +"HexEditor.factionsLink","Hex editor","Linked notes","Factions","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:1144","" +"HexEditor.factionsShowAll","Hex editor","Linked notes","▾","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:1151","" +"HexEditor.factionsCreate","Hex editor","Linked notes","+ Create ""…""","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:1272","" +"HexEditor.factionsOpenLink","Hex editor","Linked notes","","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:1440","" +"HexEditor.factionsRemove","Hex editor","Linked notes","×","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:1459","" +"HexEditor.featuresLink","Hex editor","Linked notes","Features","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:1144","" +"HexEditor.featuresShowAll","Hex editor","Linked notes","▾","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:1151","" +"HexEditor.featuresCreate","Hex editor","Linked notes","+ Create ""…""","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:1272","" +"HexEditor.featuresOpenLink","Hex editor","Linked notes","","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:1440","" +"HexEditor.featuresRemove","Hex editor","Linked notes","×","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:1459","" +"HexEditor.encountersRoll","Hex editor","Linked notes","🎲 (Encounters)","simple","simple","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:1450","" +"HexEditor.iconOverride","Hex editor","Icons","Icon override","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:922","" +"HexEditor.iconTerrainDefault","Hex editor","Icons","— terrain default —","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:926","" +"HexEditor.iconPackTabs","Hex editor","Icons","All / / Custom tabs","keep","keep","group","group:Hex editor","","","src/HexmakerModal.ts:108","" +"HexEditor.iconPlaceKinds","Hex editor","Icons","All places / Settlements / Castles…","keep","keep","group","group:Hex editor","","","src/HexmakerModal.ts:133","" +"HexEditor.gmIcons","Hex editor","Icons","Game master icons","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:941","" +"HexEditor.gmIconsRemoveOne","Hex editor","Icons","Right-click icon","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:1037","" +"HexEditor.gmIconsClearAll","Hex editor","Icons","— clear all —","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:1050","" +"HexEditor.gmIconFilterSearch","Hex editor","Icons","Filter icons… (GM)","keep","keep","group","group:Hex editor","","","src/HexmakerModal.ts:45","" +"HexEditor.gmIconPackTabs","Hex editor","Icons","All / / Custom tabs (GM)","keep","keep","group","group:Hex editor","","","src/HexmakerModal.ts:108","" +"HexEditor.gmIconPlaceKinds","Hex editor","Icons","Place kind chips (GM)","keep","keep","group","group:Hex editor","","","src/HexmakerModal.ts:133","" +"HexTable.refresh","Hex table","Toolbar","Refresh","overkill","overkill","group","group:Hex table","","","src/hex-table/HexTableView.ts:143","" +"HexTable.xMin","Hex table","Toolbar","X: Min","advanced","advanced","group","group:Hex table","","","src/hex-table/HexTableView.ts:153","" +"HexTable.xMax","Hex table","Toolbar","X: Max","advanced","advanced","group","group:Hex table","","","src/hex-table/HexTableView.ts:164","" +"HexTable.yMin","Hex table","Toolbar","Y: Min","advanced","advanced","group","group:Hex table","","","src/hex-table/HexTableView.ts:179","" +"HexTable.yMax","Hex table","Toolbar","Y: Max","advanced","advanced","group","group:Hex table","","","src/hex-table/HexTableView.ts:190","" +"HexTable.terrainFilter","Hex table","Toolbar","Terrain: all","keep","keep","group","group:Hex table","","","src/hex-table/HexTableView.ts:204","" +"HexTable.hasTown","Hex table","Toolbar","Town","keep","keep","group","group:Hex table","","","src/hex-table/HexTableView.ts:240","" +"HexTable.hasDungeon","Hex table","Toolbar","Dungeon","keep","keep","group","group:Hex table","","","src/hex-table/HexTableView.ts:252","" +"HexTable.hasFeature","Hex table","Toolbar","Feature","keep","keep","group","group:Hex table","","","src/hex-table/HexTableView.ts:264","" +"HexTable.hasQuest","Hex table","Toolbar","Quest","keep","keep","group","group:Hex table","","","src/hex-table/HexTableView.ts:276","" +"HexTable.hasFaction","Hex table","Toolbar","Faction","keep","keep","group","group:Hex table","","","src/hex-table/HexTableView.ts:288","" +"HexTable.mapSelect","Hex table","Toolbar","All maps / ","keep","keep","group","group:Hex table","","","src/hex-table/HexTableView.ts:299","" +"HexTable.sortCycle","Hex table","Toolbar","Sort: xy / yx / type","keep","keep","group","group:Hex table","","","src/hex-table/HexTableView.ts:329","" +"HexTable.sortDirection","Hex table","Toolbar","↑ asc / ↓ desc","keep","keep","group","group:Hex table","","","src/hex-table/HexTableView.ts:341","" +"HexTable.clearFilters","Hex table","Toolbar","Clear filters","keep","keep","group","group:Hex table","","","src/hex-table/HexTableView.ts:355","" +"HexTable.jumpToHex","Hex table","Rows & cells","◎","keep","keep","group","group:Hex table","","","src/hex-table/HexTableView.ts:802","" +"HexTable.openHexNote","Hex table","Rows & cells","","keep","keep","group","group:Hex table","","","src/hex-table/HexTableView.ts:812","" +"HexTable.terrainCell","Hex table","Rows & cells","Terrain cell","keep","keep","group","group:Hex table","","","src/hex-table/HexTableView.ts:889","" +"HexTable.townsCell","Hex table","Rows & cells","Towns cell","keep","keep","group","group:Hex table","","","src/hex-table/HexTableView.ts:970","" +"HexTable.dungeonsCell","Hex table","Rows & cells","Dungeons cell","keep","keep","group","group:Hex table","","","src/hex-table/HexTableView.ts:970","" +"HexTable.encountersCell","Hex table","Rows & cells","Enc. Table cell","keep","keep","group","group:Hex table","","","src/hex-table/HexTableView.ts:970","" +"HexTable.encountersMiddleClick","Hex table","Rows & cells","Middle-click Enc. Table","keep","keep","group","group:Hex table","","","src/hex-table/HexTableView.ts:947","" +"HexTable.otherLinkCell","Hex table","Rows & cells","Features/Quests/Factions cell","keep","keep","group","group:Hex table","","","src/hex-table/HexTableView.ts:1031","" +"HexTable.textCell","Hex table","Rows & cells","Text cells (Description…Hooks)","keep","keep","group","group:Hex table","","","src/hex-table/HexTableView.ts:1054","" +"HexTable.columnResize","Hex table","Rows & cells","Column edge drag","keep","keep","group","group:Hex table","","","src/hex-table/HexTableView.ts:1119","" +"HexTable.hiddenSecretColumns","Hex table","Rows & cells","Hidden / Secret columns","keep","keep","group","group:Hex table","","","src/hex-table/HexTableView.ts:44","" +"HexTable.weatherHooksColumns","Hex table","Rows & cells","Weather / Hooks & Rumors columns","keep","keep","group","group:Hex table","","","src/hex-table/HexTableView.ts:46","" +"HexCell.textarea","Hex table","Rows & cells","
text","keep","keep","group","group:Hex table","","","src/hex-table/HexCellModal.ts:38","" +"HexCell.rollOnTable","Hex table","Rows & cells","🎲 Roll on table","keep","keep","group","group:Hex table","","","src/hex-table/HexCellModal.ts:46","" +"HexCell.linkList","Hex table","Rows & cells","","keep","keep","group","group:Hex table","","","src/hex-table/HexCellModal.ts:33","" +"HexCell.closeButtons","Hex table","Rows & cells","×","keep","keep","group","group:Hex table","","","src/hex-table/HexCellModal.ts:69","" +"TerrainFilter.noTerrain","Hex table","Terrain filter","No terrain","keep","keep","group","group:Hex table","","","src/hex-table/TerrainFilterModal.ts:156","" +"TerrainFilter.typeRow","Hex table","Terrain filter"," row","advanced","advanced","group","group:Hex table","","","src/hex-table/TerrainFilterModal.ts:160","" +"TerrainFilter.terrainRow","Hex table","Terrain filter"," rows","keep","keep","group","group:Hex table","","","src/hex-table/TerrainFilterModal.ts:168","" +"TerrainFilter.excludeRightClick","Hex table","Terrain filter","Right-click to exclude","keep","keep","group","group:Hex table","","","src/hex-table/TerrainFilterModal.ts:94","" +"TerrainFilter.categoryHeading","Hex table","Terrain filter"," heading","keep","keep","group","group:Hex table","","","src/hex-table/TerrainFilterModal.ts:130","" +"TerrainFilter.clearAll","Hex table","Terrain filter","Clear all","keep","keep","group","group:Hex table","","","src/hex-table/TerrainFilterModal.ts:206","" +"TerrainFilter.closeButtons","Hex table","Terrain filter","Done / ×","keep","keep","group","group:Hex table","","","src/hex-table/TerrainFilterModal.ts:216","" +"HexTerrainPicker.terrains","Hex table","Terrain filter","Select terrain","keep","keep","group","group:Hex table","","","src/hex-table/HexTerrainPickerModal.ts:129","" +"HexTerrainPicker.clear","Hex table","Terrain filter","Clear terrain","keep","keep","group","group:Hex table","","","src/hex-table/HexTerrainPickerModal.ts:160","" +"HexTerrainPicker.closeButtons","Hex table","Terrain filter","×","keep","keep","group","group:Hex table","","","src/hex-table/HexTerrainPickerModal.ts:120","" +"LinkPicker.townsList","Hex table","Linking","Select existing: (Towns)","keep","keep","group","group:Hex table","","","src/hex-table/LinkPickerModal.ts:206","" +"LinkPicker.dungeonsList","Hex table","Linking","Select existing: (Dungeons)","keep","keep","group","group:Hex table","","","src/hex-table/LinkPickerModal.ts:206","" +"LinkPicker.encountersList","Hex table","Linking","Select existing: (Encounters Table)","keep","keep","group","group:Hex table","","","src/hex-table/LinkPickerModal.ts:206","" +"LinkPicker.createName","Hex table","Linking","Or create new: ","keep","keep","group","group:Hex table","","","src/hex-table/LinkPickerModal.ts:232","" +"LinkPicker.createButton","Hex table","Linking","Create","keep","keep","group","group:Hex table","","","src/hex-table/LinkPickerModal.ts:237","" +"LinkPicker.closeButtons","Hex table","Linking","×","keep","keep","group","group:Hex table","","","src/hex-table/LinkPickerModal.ts:199","" +"MultiLinkNav.items","Hex table","Linking","","keep","keep","group","group:Hex table","","","src/hex-table/MultiLinkNavModal.ts:20","" +"MultiLinkNav.closeButtons","Hex table","Linking","×","keep","keep","group","group:Hex table","","","src/hex-table/MultiLinkNavModal.ts:13","" +"IconFilter.search","Map pickers & editors","Icons","Filter icons...","keep","keep","group","group:Map pickers & editors","","","src/HexmakerModal.ts:45","" +"IconFilter.packTabs","Map pickers & editors","Icons","All / Terrain / Places / Space / Custom (+counts)","keep","keep","group","group:Map pickers & editors","","","src/HexmakerModal.ts:108","" +"IconFilter.placeKindChips","Map pickers & editors","Icons","All places / Settlements / Castles / ...","keep","keep","group","group:Map pickers & editors","","","src/HexmakerModal.ts:134","" +"IconPicker.gmLayerOnly","Map pickers & editors","Icons","GM layer only","keep","keep","group","group:Map pickers & editors","","","src/hex-map/IconPickerModal.ts:45","" +"IconPicker.manageIcons","Map pickers & editors","Icons","Manage icons / ← pick icons","simple","simple","group","group:Map pickers & editors","","","src/hex-map/IconPickerModal.ts:57","" +"IconPicker.remove","Map pickers & editors","Icons","Remove","keep","keep","group","group:Map pickers & editors","","","src/hex-map/IconPickerModal.ts:79","" +"IconPicker.grid","Map pickers & editors","Icons","(icon tiles)","keep","keep","group","group:Map pickers & editors","","","src/hex-map/IconPickerModal.ts:89","" +"IconPicker.packTabs","Map pickers & editors","Icons","All / Terrain / Places / Space / Custom","keep","keep","group","group:Map pickers & editors","","","src/HexmakerModal.ts:109","" +"IconPicker.hideToggle","Map pickers & editors","Icons","eye / eye-off","keep","keep","group","group:Map pickers & editors","","","src/hex-map/IconPickerModal.ts:138","" +"IconPicker.dragReorder","Map pickers & editors","Icons","⠿ (drag to reorder)","keep","keep","group","group:Map pickers & editors","","","src/hex-map/IconPickerModal.ts:157","" +"IconPicker.uploadDropZone","Map pickers & editors","Icons","Drag & drop images here, or click to browse","keep","keep","group","group:Map pickers & editors","","","src/hex-map/IconPickerModal.ts:204","" +"IconPicker.closeButtons","Map pickers & editors","Icons","×","keep","keep","group","group:Map pickers & editors","","","src/hex-map/IconPickerModal.ts:29","" +"Token.notePicker","Map pickers & editors","Tokens","Note","keep","keep","group","group:Map pickers & editors","","","src/hex-map/TokenModal.ts:94","" +"Token.noteStatus","Map pickers & editors","Tokens","Links to … / Creates a new note: …","keep","keep","group","group:Map pickers & editors","","","src/hex-map/TokenModal.ts:115","" +"Token.iconPackTabs","Map pickers & editors","Tokens","All / Terrain / Places / Space / Custom","keep","keep","group","group:Map pickers & editors","","","src/HexmakerModal.ts:109","" +"Token.iconGrid","Map pickers & editors","Tokens","Icon","simple","simple","group","group:Map pickers & editors","","","src/hex-map/TokenModal.ts:199","" +"Token.shape","Map pickers & editors","Tokens","Shape","simple","simple","group","group:Map pickers & editors","","","src/hex-map/TokenModal.ts:233","" +"Token.size","Map pickers & editors","Tokens","Size","simple","simple","group","group:Map pickers & editors","","","src/hex-map/TokenModal.ts:244","" +"Token.fillColor","Map pickers & editors","Tokens","Fill color","simple","simple","group","group:Map pickers & editors","","","src/hex-map/TokenModal.ts:262","" +"Token.borderToggle","Map pickers & editors","Tokens","Border color (on/off)","simple","simple","group","group:Map pickers & editors","","","src/hex-map/TokenModal.ts:284","" +"Token.borderColor","Map pickers & editors","Tokens","Border color","simple","simple","group","group:Map pickers & editors","","","src/hex-map/TokenModal.ts:292","" +"Token.description","Map pickers & editors","Tokens","Description","advanced","advanced","group","group:Map pickers & editors","","","src/hex-map/TokenModal.ts:315","" +"Token.removeButton","Map pickers & editors","Tokens","Remove token","keep","keep","group","group:Map pickers & editors","","","src/hex-map/TokenModal.ts:333","" +"Token.saveButton","Map pickers & editors","Tokens","Next: place on map / Save","simple","simple","group","group:Map pickers & editors","","","src/hex-map/TokenModal.ts:340","" +"Token.closeButtons","Map pickers & editors","Tokens","Cancel","keep","keep","group","group:Map pickers & editors","","","src/hex-map/TokenModal.ts:372","" +"TokenInfo.jumpButton","Map pickers & editors","Tokens","⌖","keep","keep","group","group:Map pickers & editors","","","src/hex-map/TokenInfoModal.ts:31","" +"TokenInfo.openNoteLink","Map pickers & editors","Tokens","Open note","keep","keep","group","group:Map pickers & editors","","","src/hex-map/TokenInfoModal.ts:44","" +"TokenInfo.editButton","Map pickers & editors","Tokens","Edit token","keep","keep","group","group:Map pickers & editors","","","src/hex-map/TokenInfoModal.ts:56","" +"TokenInfo.noteLinks","Map pickers & editors","Tokens","(links inside the note preview)","keep","keep","group","group:Map pickers & editors","","","src/hex-map/TokenInfoModal.ts:91","" +"TokenInfo.removeButton","Map pickers & editors","Tokens","× remove / Confirm remove?","keep","keep","group","group:Map pickers & editors","","","src/hex-map/TokenInfoModal.ts:117","" +"TokenInfo.closeButtons","Map pickers & editors","Tokens","×","keep","keep","group","group:Map pickers & editors","","","src/hex-map/TokenInfoModal.ts:20","" +"PathName.nameInput","Map pickers & editors","Path types","(path name)","keep","keep","group","group:Map pickers & editors","","","src/hex-map/PathNameModal.ts:45","" +"PathName.saveButton","Map pickers & editors","Path types","Save","keep","keep","group","group:Map pickers & editors","","","src/hex-map/PathNameModal.ts:48","" +"PathName.closeButtons","Map pickers & editors","Path types","Cancel","keep","keep","group","group:Map pickers & editors","","","src/hex-map/PathNameModal.ts:49","" +"PathPicker.editToggle","Map pickers & editors","Path types","✏ Edit / ← Done","simple","simple","group","group:Map pickers & editors","","","src/hex-map/PathPickerModal.ts:158","" +"PathPicker.drawMode","Map pickers & editors","Path types","1. How to draw: Hex by hex / Auto-route","simple","simple","group","group:Map pickers & editors","","","src/hex-map/PathPickerModal.ts:107","" +"PathPicker.removeTile","Map pickers & editors","Path types","Remove","keep","keep","group","group:Map pickers & editors","","","src/hex-map/PathPickerModal.ts:187","" +"PathPicker.typeGrid","Map pickers & editors","Path types","2. Pick a path type to start drawing","simple","simple","group","group:Map pickers & editors","","","src/hex-map/PathPickerModal.ts:198","" +"PathPicker.pathsOnMap","Map pickers & editors","Path types","Paths on this map","advanced","advanced","group","group:Map pickers & editors","","","src/hex-map/PathPickerModal.ts:229","" +"PathPicker.editTypeTile","Map pickers & editors","Path types","(type tile, edit mode)","keep","keep","group","group:Map pickers & editors","","","src/hex-map/PathPickerModal.ts:268","" +"PathPicker.dragReorder","Map pickers & editors","Path types","⠿ (drag to reorder)","keep","keep","group","group:Map pickers & editors","","","src/hex-map/PathPickerModal.ts:285","" +"PathPicker.addTypeTile","Map pickers & editors","Path types","+ Add","keep","keep","group","group:Map pickers & editors","","","src/hex-map/PathPickerModal.ts:315","" +"PathPicker.closeButtons","Map pickers & editors","Path types","×","keep","keep","group","group:Map pickers & editors","","","src/hex-map/PathPickerModal.ts:133","" +"PathType.name","Map pickers & editors","Path types","Name","keep","keep","group","group:Map pickers & editors","","","src/hex-map/PathTypeEditorModal.ts:78","" +"PathType.color","Map pickers & editors","Path types","Color","keep","keep","group","group:Map pickers & editors","","","src/hex-map/PathTypeEditorModal.ts:88","" +"PathType.width","Map pickers & editors","Path types","Width","keep","keep","group","group:Map pickers & editors","","","src/hex-map/PathTypeEditorModal.ts:99","" +"PathType.lineStyle","Map pickers & editors","Path types","Line style","keep","keep","group","group:Map pickers & editors","","","src/hex-map/PathTypeEditorModal.ts:111","" +"PathType.routing","Map pickers & editors","Path types","Routing","keep","keep","group","group:Map pickers & editors","","","src/hex-map/PathTypeEditorModal.ts:125","" +"PathType.avoidImpassable","Map pickers & editors","Path types","Avoid impassable terrain","keep","keep","group","group:Map pickers & editors","","","src/hex-map/PathTypeEditorModal.ts:140","" +"PathType.autoRoute","Map pickers & editors","Path types","Auto-route","keep","keep","group","group:Map pickers & editors","","","src/hex-map/PathTypeEditorModal.ts:149","" +"PathType.carves","Map pickers & editors","Path types","Carves terrain","advanced","advanced","group","group:Map pickers & editors","","","src/hex-map/PathTypeEditorModal.ts:163","" +"PathType.carveWidth","Map pickers & editors","Path types","Carve width","overkill","overkill","group","group:Map pickers & editors","","","src/hex-map/PathTypeEditorModal.ts:173","" +"PathType.saveButton","Map pickers & editors","Path types","Save","keep","keep","group","group:Map pickers & editors","","","src/hex-map/PathTypeEditorModal.ts:185","" +"PathType.deleteButton","Map pickers & editors","Path types","Delete","keep","keep","group","group:Map pickers & editors","","","src/hex-map/PathTypeEditorModal.ts:194","" +"PathType.deleteConfirm","Map pickers & editors","Path types","Yes, delete / Cancel","keep","keep","group","group:Map pickers & editors","","","src/hex-map/PathTypeEditorModal.ts:212","" +"PathType.closeButtons","Map pickers & editors","Path types","×","keep","keep","group","group:Map pickers & editors","","","src/hex-map/PathTypeEditorModal.ts:225","" +"GotoHex.xInput","Map pickers & editors","Go to hex & help","X:","keep","keep","group","group:Map pickers & editors","","","src/hex-map/GotoHexModal.ts:21","" +"GotoHex.yInput","Map pickers & editors","Go to hex & help","Y:","keep","keep","group","group:Map pickers & editors","","","src/hex-map/GotoHexModal.ts:26","" +"GotoHex.goButton","Map pickers & editors","Go to hex & help","Go","keep","keep","group","group:Map pickers & editors","","","src/hex-map/GotoHexModal.ts:40","" +"GotoHex.closeButtons","Map pickers & editors","Go to hex & help","×","keep","keep","group","group:Map pickers & editors","","","src/hex-map/GotoHexModal.ts:14","" +"HexHelp.closeButtons","Map pickers & editors","Go to hex & help","×","keep","keep","group","group:Map pickers & editors","","","src/hex-map/HexHelpModal.ts:10","" +"Locations.search","Map pickers & editors","Locations","Find a location…","keep","keep","group","group:Map pickers & editors","","","src/hex-map/LocationsModal.ts:45","" +"Locations.list","Map pickers & editors","Locations","(location name)","keep","keep","group","group:Map pickers & editors","","","src/hex-map/LocationsModal.ts:111","" +"Locations.openButton","Map pickers & editors","Locations","Open","drop","drop","group","group:Map pickers & editors","","","src/hex-map/LocationsModal.ts:118","" +"Locations.unlink","Map pickers & editors","Locations","✕","keep","keep","group","group:Map pickers & editors","","","src/hex-map/LocationsModal.ts:122","" +"Locations.dragReorder","Map pickers & editors","Locations","⋮⋮ (drag)","keep","keep","group","group:Map pickers & editors","","","src/hex-map/LocationsModal.ts:89","" +"Locations.newLocation","Map pickers & editors","Locations","New location…","keep","keep","group","group:Map pickers & editors","","","src/hex-map/LocationsModal.ts:62","" +"Locations.linkExisting","Map pickers & editors","Locations","Link existing map…","keep","keep","group","group:Map pickers & editors","","","src/hex-map/LocationsModal.ts:66","" +"Locations.closeButtons","Map pickers & editors","Locations","×","keep","keep","group","group:Map pickers & editors","","","src/hex-map/LocationsModal.ts:42","" +"FactionPicker.grid","Map pickers & editors","Factions","(faction tiles)","keep","keep","group","group:Map pickers & editors","","","src/hex-map/FactionPickerModal.ts:207","" +"FactionPicker.removeTile","Map pickers & editors","Factions","Remove","keep","keep","group","group:Map pickers & editors","","","src/hex-map/FactionPickerModal.ts:193","" +"FactionPicker.editTile","Map pickers & editors","Factions","✏","keep","keep","group","group:Map pickers & editors","","","src/hex-map/FactionPickerModal.ts:221","" +"FactionPicker.newName","Map pickers & editors","Factions","New faction name…","keep","keep","group","group:Map pickers & editors","","","src/hex-map/FactionPickerModal.ts:270","" +"FactionPicker.createButton","Map pickers & editors","Factions","Create","keep","keep","group","group:Map pickers & editors","","","src/hex-map/FactionPickerModal.ts:274","" +"FactionPicker.closeButtons","Map pickers & editors","Factions","×","keep","keep","group","group:Map pickers & editors","","","src/hex-map/FactionPickerModal.ts:300","" +"FactionEditor.openNote","Map pickers & editors","Factions","Open note →","keep","keep","group","group:Map pickers & editors","","","src/hex-map/FactionPickerModal.ts:46","" +"FactionEditor.name","Map pickers & editors","Factions","Name","keep","keep","group","group:Map pickers & editors","","","src/hex-map/FactionPickerModal.ts:74","" +"FactionEditor.color","Map pickers & editors","Factions","Color","keep","keep","group","group:Map pickers & editors","","","src/hex-map/FactionPickerModal.ts:81","" +"FactionEditor.pattern","Map pickers & editors","Factions","Pattern","simple","simple","group","group:Map pickers & editors","","","src/hex-map/overlayPatternControls.ts:139","" +"FactionEditor.patternScale","Map pickers & editors","Factions","Pattern scale","simple","simple","group","group:Map pickers & editors","","","src/hex-map/overlayPatternControls.ts:149","" +"FactionEditor.opacity","Map pickers & editors","Factions","Opacity","simple","simple","group","group:Map pickers & editors","","","src/hex-map/overlayPatternControls.ts:159","" +"FactionEditor.outlineWidth","Map pickers & editors","Factions","Outline width","simple","simple","group","group:Map pickers & editors","","","src/hex-map/overlayPatternControls.ts:169","" +"FactionEditor.save","Map pickers & editors","Factions","Save","keep","keep","group","group:Map pickers & editors","","","src/hex-map/FactionPickerModal.ts:102","" +"FactionEditor.clearColor","Map pickers & editors","Factions","Clear color","simple","simple","group","group:Map pickers & editors","","","src/hex-map/FactionPickerModal.ts:126","" +"FactionEditor.closeButtons","Map pickers & editors","Factions","×","keep","keep","group","group:Map pickers & editors","","","src/hex-map/FactionPickerModal.ts:36","" +"TerrainPicker.editToggle","Map pickers & editors","Terrain","✏ Edit / ← Done","simple","simple","group","group:Map pickers & editors","","","src/hex-map/TerrainPickerModal.ts:52","" +"TerrainPicker.fullEditor","Map pickers & editors","Terrain","Full editor…","keep","keep","group","group:Map pickers & editors","","","src/hex-map/TerrainPickerModal.ts:63","" +"TerrainPicker.brushSize","Map pickers & editors","Terrain","Brush: 1× 3× 7×","keep","keep","group","group:Map pickers & editors","","","src/hex-map/TerrainPickerModal.ts:83","" +"TerrainPicker.eyedropper","Map pickers & editors","Terrain","⌖ Pick","keep","keep","group","group:Map pickers & editors","","","src/hex-map/TerrainPickerModal.ts:104","" +"TerrainPicker.clear","Map pickers & editors","Terrain","Clear","keep","keep","group","group:Map pickers & editors","","","src/hex-map/TerrainPickerModal.ts:119","" +"TerrainPicker.grid","Map pickers & editors","Terrain","(terrain tiles)","keep","keep","group","group:Map pickers & editors","","","src/hex-map/TerrainPickerModal.ts:132","" +"TerrainPicker.editTile","Map pickers & editors","Terrain","(terrain tile, edit mode)","keep","keep","group","group:Map pickers & editors","","","src/hex-map/TerrainPickerModal.ts:175","" +"TerrainPicker.dragReorder","Map pickers & editors","Terrain","⠿ (drag to reorder)","keep","keep","group","group:Map pickers & editors","","","src/hex-map/TerrainPickerModal.ts:198","" +"TerrainPicker.addTile","Map pickers & editors","Terrain","+ Add","keep","keep","group","group:Map pickers & editors","","","src/hex-map/TerrainPickerModal.ts:232","" +"TerrainPicker.refreshEncounterLinks","Map pickers & editors","Terrain","Refresh all encounter table links","overkill","overkill","group","group:Map pickers & editors","","","src/hex-map/TerrainPickerModal.ts:275","" +"TerrainPicker.closeButtons","Map pickers & editors","Terrain","×","keep","keep","group","group:Map pickers & editors","","","src/hex-map/TerrainPickerModal.ts:33","" +"TerrainTemplate.newBlank","Map pickers & editors","Terrain","New blank","keep","keep","group","group:Map pickers & editors","","","src/hex-map/TerrainPickerModal.ts:309","" +"TerrainTemplate.copyList","Map pickers & editors","Terrain","Or copy from an existing palette:","keep","keep","group","group:Map pickers & editors","","","src/hex-map/TerrainPickerModal.ts:329","" +"TerrainTemplate.closeButtons","Map pickers & editors","Terrain","×","keep","keep","group","group:Map pickers & editors","","","src/hex-map/TerrainPickerModal.ts:345","" +"TerrainEntry.name","Map pickers & editors","Terrain","Name","keep","keep","group","group:Map pickers & editors","","","src/hex-map/TerrainEntryEditorModal.ts:57","" +"TerrainEntry.type","Map pickers & editors","Terrain","Type","keep","keep","group","group:Map pickers & editors","","","src/hex-map/TerrainEntryEditorModal.ts:73","" +"TerrainEntry.impassable","Map pickers & editors","Terrain","Impassable","keep","keep","group","group:Map pickers & editors","","","src/hex-map/TerrainEntryEditorModal.ts:85","" +"TerrainEntry.color","Map pickers & editors","Terrain","Color","keep","keep","group","group:Map pickers & editors","","","src/hex-map/TerrainEntryEditorModal.ts:94","" +"TerrainEntry.icon","Map pickers & editors","Terrain","Icon","keep","keep","group","group:Map pickers & editors","","","src/hex-map/TerrainEntryEditorModal.ts:102","" +"TerrainEntry.iconTintToggle","Map pickers & editors","Terrain","Icon tint (on/off)","keep","keep","group","group:Map pickers & editors","","","src/hex-map/TerrainEntryEditorModal.ts:125","" +"TerrainEntry.iconTintColor","Map pickers & editors","Terrain","Icon tint","keep","keep","group","group:Map pickers & editors","","","src/hex-map/TerrainEntryEditorModal.ts:136","" +"TerrainEntry.category","Map pickers & editors","Terrain","Category","keep","keep","group","group:Map pickers & editors","","","src/hex-map/TerrainEntryEditorModal.ts:159","" +"TerrainEntry.save","Map pickers & editors","Terrain","Save / Updating hexes…","keep","keep","group","group:Map pickers & editors","","","src/hex-map/TerrainEntryEditorModal.ts:180","" +"TerrainEntry.delete","Map pickers & editors","Terrain","Delete","keep","keep","group","group:Map pickers & editors","","","src/hex-map/TerrainEntryEditorModal.ts:198","" +"TerrainEntry.closeButtons","Map pickers & editors","Terrain","Cancel","keep","keep","group","group:Map pickers & editors","","","src/hex-map/TerrainEntryEditorModal.ts:193","" +"MapModal.tabMaps","Maps modal","Tabs & general","Maps","keep","keep","group","group:Maps modal","","","src/hex-map/MapModal.ts:119","" +"MapModal.tabProperties","Maps modal","Tabs & general","Properties","keep","keep","group","group:Maps modal","","","src/hex-map/MapModal.ts:119","" +"MapModal.tabRegions","Maps modal","Tabs & general","Regions","keep","keep","group","group:Maps modal","","","src/hex-map/MapModal.ts:107","" +"MapModal.tabExport","Maps modal","Tabs & general","Export","keep","keep","group","group:Maps modal","","","src/hex-map/MapModal.ts:119","" +"MapModal.newMap","Maps modal","Tabs & general","New map…","keep","keep","group","group:Maps modal","","","src/hex-map/MapModal.ts:127","" +"MapModal.newOverworld","Maps modal","Tabs & general","New overworld…","keep","keep","group","group:Maps modal","","","src/hex-map/MapModal.ts:130","" +"MapModal.mapSearch","Maps modal","Maps list","Find a map…","keep","keep","group","group:Maps modal","","","src/hex-map/MapModal.ts:242","" +"MapModal.mapTree","Maps modal","Maps list","(map list)","keep","keep","group","group:Maps modal","","","src/hex-map/MapModal.ts:254","" +"MapModal.treeToggle","Maps modal","Maps list","▸ / ▾","keep","keep","group","group:Maps modal","","","src/hex-map/MapModal.ts:317","" +"MapModal.regionsGroupRow","Maps modal","Maps list","Regions of ","keep","keep","group","group:Maps modal","","","src/hex-map/MapModal.ts:290","" +"MapModal.neighboursGroupRow","Maps modal","Maps list","Neighbours: ","keep","keep","group","group:Maps modal","","","src/hex-map/MapModal.ts:299","" +"MapModal.mapRowContextGenerator","Maps modal","Maps list","Open generator """"","advanced","advanced","group","group:Maps modal","","","src/hex-map/MapModal.ts:355","" +"MapModal.mapRowContextMakeGenerator","Maps modal","Maps list","Make generator from …","advanced","advanced","group","group:Maps modal","","","src/hex-map/MapModal.ts:363","" +"MapModal.missingRemove","Maps modal","Maps list","Remove / Remove from list?","keep","keep","group","group:Maps modal","","","src/hex-map/MapModal.ts:52","" +"MapProps.sectionTablePicker","Maps modal","Properties","Pick table…","advanced","advanced","group","group:Maps modal","","","src/hex-map/MapModal.ts:624","" +"MapModal.propsName","Maps modal","Properties","Name","keep","keep","group","group:Maps modal","","","src/hex-map/MapModal.ts:425","" +"MapModal.propsSaveName","Maps modal","Properties","Save name","keep","keep","group","group:Maps modal","","","src/hex-map/MapModal.ts:430","" +"MapModal.propsFolderName","Maps modal","Properties","Folder name","overkill","overkill","group","group:Maps modal","","","src/hex-map/MapModal.ts:448","" +"MapModal.propsRenameFolder","Maps modal","Properties","Rename folder","overkill","overkill","group","group:Maps modal","","","src/hex-map/MapModal.ts:453","" +"MapModal.propsStagger","Maps modal","Properties","Stagger offset (Odd/Even)","simple","simple","group","group:Maps modal","","","src/hex-map/MapModal.ts:466","" +"MapModal.propsNeighbourHint","Maps modal","Properties","(enable Regions hint)","keep","keep","group","group:Maps modal","","","src/hex-map/MapModal.ts:696","" +"MapModal.propsTerrainTheme","Maps modal","Properties","Terrain theme","advanced","advanced","group","group:Maps modal","","","src/hex-map/MapModal.ts:494","" +"MapModal.propsDelete","Maps modal","Properties","Delete """"…","simple","simple","group","group:Maps modal","","","src/hex-map/MapModal.ts:660","" +"MapModal.propsDeleteConfirm","Maps modal","Properties","Delete / Cancel","simple","simple","group","group:Maps modal","","","src/hex-map/MapModal.ts:671","" +"MapModal.propsNeighbourNorth","Maps modal","Neighbouring regions","North","keep","keep","group","group:Maps modal","","","src/hex-map/MapModal.ts:711","" +"MapModal.propsNeighbourEast","Maps modal","Neighbouring regions","East","keep","keep","group","group:Maps modal","","","src/hex-map/MapModal.ts:711","" +"MapModal.propsNeighbourSouth","Maps modal","Neighbouring regions","South","keep","keep","group","group:Maps modal","","","src/hex-map/MapModal.ts:711","" +"MapModal.propsNeighbourWest","Maps modal","Neighbouring regions","West","keep","keep","group","group:Maps modal","","","src/hex-map/MapModal.ts:711","" +"MapModal.propsNewRegionHere","Maps modal","Neighbouring regions","New region here…","keep","keep","group","group:Maps modal","","","src/hex-map/MapModal.ts:733","" +"MapModal.propsDetach","Maps modal","Neighbouring regions","Detach from its neighbours","keep","keep","group","group:Maps modal","","","src/hex-map/MapModal.ts:740","" +"MapModal.propsWeatherTable","Maps modal","Weather & rumours","Weather: Pick table…","advanced","advanced","group","group:Maps modal","","","src/hex-map/MapModal.ts:623","" +"MapModal.propsWeatherClear","Maps modal","Weather & rumours","Clear (weather)","advanced","advanced","group","group:Maps modal","","","src/hex-map/MapModal.ts:635","" +"MapModal.propsRumoursTable","Maps modal","Weather & rumours","Rumours: Pick table…","advanced","advanced","group","group:Maps modal","","","src/hex-map/MapModal.ts:623","" +"MapModal.propsRumoursClear","Maps modal","Weather & rumours","Clear (rumours)","advanced","advanced","group","group:Maps modal","","","src/hex-map/MapModal.ts:635","" +"MapProps.backgroundImagePicker","Maps modal","Background image","Pick image…","advanced","advanced","group","group:Maps modal","","","src/hex-map/MapModal.ts:548","" +"MapModal.propsBgDrop","Maps modal","Background image","(drop an image here)","keep","keep","group","group:Maps modal","","","src/hex-map/MapModal.ts:567","" +"MapModal.propsBgClear","Maps modal","Background image","Clear","keep","keep","group","group:Maps modal","","","src/hex-map/MapModal.ts:556","" +"MapModal.propsBgOpacity","Maps modal","Background image","Opacity","keep","keep","group","group:Maps modal","","","src/hex-map/MapModal.ts:578","" +"MapModal.propsBgCalibrate","Maps modal","Background image","Calibrate position & scale","keep","keep","group","group:Maps modal","","","src/hex-map/MapModal.ts:590","" +"MapModal.regionsSetUp","Maps modal","Regions tab","Set up regions…","keep","keep","group","group:Maps modal","","","src/hex-map/MapModal.ts:169","" +"MapModal.regionsSettingsForm","Maps modal","Regions tab","(region settings form)","keep","keep","group","group:Maps modal","","","src/hex-map/MapModal.ts:182","" +"MapModal.regionsMakeMissing","Maps modal","Regions tab","Make the missing regions (N)…","keep","keep","group","group:Maps modal","","","src/hex-map/MapModal.ts:189","" +"MapModal.regionsGenerateOverworld","Maps modal","Regions tab","Generate overworld…","keep","keep","group","group:Maps modal","","","src/hex-map/MapModal.ts:200","" +"MapModal.regionsList","Maps modal","Regions tab","Regions (N) list","keep","keep","group","group:Maps modal","","","src/hex-map/MapModal.ts:209","" +"NewMap.name","New maps & map links","New map form","Name","keep","keep","group","group:New maps & map links","","","src/worldgen/NewMapSetupModal.ts:222","" +"NewMap.palette","New maps & map links","New map form","Palette","keep","keep","group","group:New maps & map links","","","src/worldgen/NewMapSetupModal.ts:247","" +"NewMap.rememberPalette","New maps & map links","New map form","Use this palette for new submaps of hexes","advanced","advanced","group","group:New maps & map links","","","src/worldgen/NewMapSetupModal.ts:259","" +"NewMap.sizePresets","New maps & map links","New map form","(size presets)","keep","keep","group","group:New maps & map links","","","src/worldgen/NewMapSetupModal.ts:274","" +"NewMap.size","New maps & map links","New map form","Size (columns × rows)","keep","keep","group","group:New maps & map links","","","src/worldgen/NewMapSetupModal.ts:266","" +"NewMap.rememberSize","New maps & map links","New map form","Use this size for new submaps…","advanced","advanced","group","group:New maps & map links","","","src/worldgen/NewMapSetupModal.ts:306","" +"NewMap.nextTo","New maps & map links","New map form","Next to","keep","keep","group","group:New maps & map links","","","src/worldgen/NewMapSetupModal.ts:324","" +"NewMap.nextToSide","New maps & map links","New map form","(side of the neighbouring map)","keep","keep","group","group:New maps & map links","","","src/worldgen/NewMapSetupModal.ts:327","" +"NewMap.generator","New maps & map links","New map form","Generator","keep","keep","group","group:New maps & map links","","","src/worldgen/NewMapSetupModal.ts:569","" +"NewMap.rememberGenerator","New maps & map links","New map form","Use this generator and its options for new submaps…","advanced","advanced","group","group:New maps & map links","","","src/worldgen/NewMapSetupModal.ts:398","" +"NewMap.moreOptionsHint","New maps & map links","New map form","More options: … Show / ✕","keep","keep","group","group:New maps & map links","","","src/worldgen/NewMapSetupModal.ts:401","" +"NewMap.baseTerrain","New maps & map links","New map form","Base terrain","keep","keep","group","group:New maps & map links","","","src/worldgen/NewMapSetupModal.ts:411","" +"NewMap.rememberBase","New maps & map links","New map form","Use this base terrain for new submaps…","advanced","advanced","group","group:New maps & map links","","","src/worldgen/NewMapSetupModal.ts:412","" +"NewMap.more","New maps & map links","New map form","More: folder name, starting coordinates, stagger, background image","keep","keep","group","group:New maps & map links","","","src/worldgen/NewMapSetupModal.ts:420","" +"NewMap.reroll","New maps & map links","New map form","🎲 Re-roll","keep","keep","group","group:New maps & map links","","","src/worldgen/NewMapSetupModal.ts:509","" +"NewMap.create","New maps & map links","New map form","Generate / Create (& enter)","keep","keep","group","group:New maps & map links","","","src/worldgen/NewMapSetupModal.ts:518","" +"NewMap.openInGenerator","New maps & map links","New map form","Open in generator","keep","keep","group","group:New maps & map links","","","src/worldgen/NewMapSetupModal.ts:519","" +"NewMap.closeButtons","New maps & map links","New map form","Cancel","keep","keep","group","group:New maps & map links","","","src/worldgen/NewMapSetupModal.ts:521","" +"NewMapSetup.backgroundImagePicker","New maps & map links","New map form: More","Pick image…","advanced","advanced","twin","NewMap.bgPick","","NewMap.bgPick","src/worldgen/NewMapSetupModal.ts:459","" +"NewMap.folderName","New maps & map links","New map form: More","Folder name","overkill","overkill","group","group:New maps & map links","","","src/worldgen/NewMapSetupModal.ts:425","" +"NewMap.startCoords","New maps & map links","New map form: More","Starting coordinates","advanced","advanced","group","group:New maps & map links","","","src/worldgen/NewMapSetupModal.ts:433","" +"NewMap.stagger","New maps & map links","New map form: More","Stagger offset","simple","simple","group","group:New maps & map links","","","src/worldgen/NewMapSetupModal.ts:444","" +"NewMap.bgPick","New maps & map links","New map form: More","Pick image…","advanced","advanced","group","group:New maps & map links","","","src/worldgen/NewMapSetupModal.ts:455","" +"NewMap.bgClear","New maps & map links","New map form: More","Clear","advanced","advanced","group","group:New maps & map links","","","src/worldgen/NewMapSetupModal.ts:456","" +"NewMap.overlandWater","New maps & map links","Generator options (world)","Water","advanced","advanced","group","group:New maps & map links","","","src/worldgen/procedural/planetSurface.ts:40","" +"NewMap.overlandClimate","New maps & map links","Generator options (world)","Climate","advanced","advanced","group","group:New maps & map links","","","src/worldgen/procedural/planetSurface.ts:52","" +"NewMap.overlandRelief","New maps & map links","Generator options (world)","Relief","advanced","advanced","group","group:New maps & map links","","","src/worldgen/procedural/planetSurface.ts:64","" +"NewMap.overlandSea","New maps & map links","Generator options (world)","Sea","advanced","advanced","group","group:New maps & map links","","","src/worldgen/procedural/planetSurface.ts:88","" +"NewMap.planetWater","New maps & map links","Generator options (world)","Water","keep","keep","group","group:New maps & map links","","","src/worldgen/procedural/planetSurface.ts:40","" +"NewMap.planetClimate","New maps & map links","Generator options (world)","Climate","keep","keep","group","group:New maps & map links","","","src/worldgen/procedural/planetSurface.ts:52","" +"NewMap.planetRelief","New maps & map links","Generator options (world)","Relief","advanced","advanced","group","group:New maps & map links","","","src/worldgen/procedural/planetSurface.ts:64","" +"NewMap.regionDetailInfluence","New maps & map links","Generator options (world)","Neighbour influence","advanced","advanced","group","group:New maps & map links","","","src/worldgen/procedural/planetSurface.ts:500","" +"NewMap.regionDetailVariety","New maps & map links","Generator options (world)","Variety","advanced","advanced","group","group:New maps & map links","","","src/worldgen/procedural/planetSurface.ts:510","" +"NewMap.worldBiomesClimate","New maps & map links","Generator options (world)","Climate","keep","keep","group","group:New maps & map links","","","src/overworld/worldBiomes.ts:576","" +"NewMap.worldBiomesWater","New maps & map links","Generator options (world)","Water %","keep","keep","group","group:New maps & map links","","","src/overworld/worldBiomes.ts:579","" +"NewMap.worldBiomesLand","New maps & map links","Generator options (world)","Land","keep","keep","group","group:New maps & map links","","","src/overworld/worldBiomes.ts:580","" +"NewMap.worldBiomesNorth","New maps & map links","Generator options (world)","North is","keep","keep","group","group:New maps & map links","","","src/overworld/worldBiomes.ts:583","" +"NewMap.starDensity","New maps & map links","Generator options (space)","System density","keep","keep","group","group:New maps & map links","","","src/worldgen/procedural/starScatter.ts:33","" +"NewMap.starNebulae","New maps & map links","Generator options (space)","Nebulae","keep","keep","group","group:New maps & map links","","","src/worldgen/procedural/starScatter.ts:43","" +"NewMap.starJumpRoutes","New maps & map links","Generator options (space)","Jump routes","keep","keep","group","group:New maps & map links","","","src/worldgen/procedural/starScatter.ts:53","" +"NewMap.starRouteType","New maps & map links","Generator options (space)","Path type for routes","advanced","advanced","group","group:New maps & map links","","","src/worldgen/generatorPathTypes.ts:27","" +"NewMap.orbitsStar","New maps & map links","Generator options (space)","Star","keep","keep","group","group:New maps & map links","","","src/worldgen/procedural/orbits.ts:37","" +"NewMap.orbitsPlanets","New maps & map links","Generator options (space)","Planets","keep","keep","group","group:New maps & map links","","","src/worldgen/procedural/orbits.ts:49","" +"NewMap.orbitsPathType","New maps & map links","Generator options (space)","Path type for orbits","advanced","advanced","group","group:New maps & map links","","","src/worldgen/generatorPathTypes.ts:28","" +"NewMap.editWorldTypes","New maps & map links","Generator options (space)","Edit world types…","keep","keep","group","group:New maps & map links","","","src/worldgen/NewMapSetupModal.ts:634","" +"ChildKind.region","New maps & map links","New map from a hex","Region","keep","keep","group","group:New maps & map links","","","src/hex-map/newChildMap.ts:104","" +"ChildKind.location","New maps & map links","New map from a hex","Location","keep","keep","group","group:New maps & map links","","","src/hex-map/newChildMap.ts:104","" +"ChildKind.enterRegion","New maps & map links","New map from a hex","Enter ","keep","keep","group","group:New maps & map links","","","src/hex-map/newChildMap.ts:124","" +"ChildKind.regionsHint","New maps & map links","New map from a hex","Turn on regions and overworlds / ✕","keep","keep","group","group:New maps & map links","","","src/hex-map/newChildMap.ts:128","" +"WalkOW.biome","New maps & map links","New land beside a map","Biome","keep","keep","group","group:New maps & map links","","","src/worldgen/WalkRegionModal.ts:97","" +"WalkOW.roll","New maps & map links","New land beside a map","Roll","keep","keep","group","group:New maps & map links","","","src/worldgen/WalkRegionModal.ts:101","" +"WalkOW.seed","New maps & map links","New land beside a map","Seed","overkill","overkill","group","group:New maps & map links","","","src/worldgen/WalkRegionModal.ts:105","" +"WalkOW.rerollTerrain","New maps & map links","New land beside a map","Re-roll terrain","keep","keep","group","group:New maps & map links","","","src/worldgen/WalkRegionModal.ts:107","" +"WalkOW.name","New maps & map links","New land beside a map","Name","keep","keep","group","group:New maps & map links","","","src/worldgen/WalkRegionModal.ts:117","" +"WalkOW.create","New maps & map links","New land beside a map","Create and go","keep","keep","group","group:New maps & map links","","","src/worldgen/WalkRegionModal.ts:123","" +"WalkOW.closeButtons","New maps & map links","New land beside a map","Cancel","keep","keep","group","group:New maps & map links","","","src/worldgen/WalkRegionModal.ts:124","" +"WalkSide.biome","New maps & map links","New land beside a map","Biome","keep","keep","group","group:New maps & map links","","","src/worldgen/WalkRegionModal.ts:222","" +"WalkSide.roll","New maps & map links","New land beside a map","Roll","keep","keep","group","group:New maps & map links","","","src/worldgen/WalkRegionModal.ts:225","" +"WalkSide.rerollTerrain","New maps & map links","New land beside a map","Re-roll terrain","keep","keep","group","group:New maps & map links","","","src/worldgen/WalkRegionModal.ts:230","" +"WalkSide.name","New maps & map links","New land beside a map","Name","keep","keep","group","group:New maps & map links","","","src/worldgen/WalkRegionModal.ts:234","" +"WalkSide.create","New maps & map links","New land beside a map","Create and go","keep","keep","group","group:New maps & map links","","","src/worldgen/WalkRegionModal.ts:237","" +"WalkSide.closeButtons","New maps & map links","New land beside a map","Cancel","keep","keep","group","group:New maps & map links","","","src/worldgen/WalkRegionModal.ts:238","" +"MapLink.map","New maps & map links","Link submap & insert map link","Map","keep","keep","group","group:New maps & map links","","","src/hex-map/MapLinkModal.ts:344","" +"MapLink.showAll","New maps & map links","Link submap & insert map link","▾ Show all","keep","keep","group","group:New maps & map links","","","src/hex-map/MapLinkModal.ts:351","" +"MapLink.linkText","New maps & map links","Link submap & insert map link","Link text","keep","keep","group","group:New maps & map links","","","src/hex-map/MapLinkModal.ts:420","" +"MapLink.insert","New maps & map links","Link submap & insert map link","Insert","keep","keep","group","group:New maps & map links","","","src/hex-map/MapLinkModal.ts:428","" +"MapLink.closeButtons","New maps & map links","Link submap & insert map link","Cancel","keep","keep","group","group:New maps & map links","","","src/hex-map/MapLinkModal.ts:441","" +"SubmapPicker.filter","New maps & map links","Link submap & insert map link","Filter maps…","keep","keep","group","group:New maps & map links","","","src/hex-map/SubmapPickerModal.ts:52","" +"SubmapPicker.mapList","New maps & map links","Link submap & insert map link","(map list)","keep","keep","group","group:New maps & map links","","","src/hex-map/SubmapPickerModal.ts:58","" +"SubmapPicker.newLocation","New maps & map links","Link submap & insert map link","New location…","keep","keep","group","group:New maps & map links","","","src/hex-map/SubmapPickerModal.ts:106","" +"SubmapPicker.removeLink","New maps & map links","Link submap & insert map link","Remove link","keep","keep","group","group:New maps & map links","","","src/hex-map/SubmapPickerModal.ts:272","" +"SubmapPicker.link","New maps & map links","Link submap & insert map link","Link","keep","keep","group","group:New maps & map links","","","src/hex-map/SubmapPickerModal.ts:275","" +"SubmapPicker.closeButtons","New maps & map links","Link submap & insert map link","Cancel","keep","keep","group","group:New maps & map links","","","src/hex-map/SubmapPickerModal.ts:281","" +"SubmapPicker.createSection","New maps & map links","Link submap: inline create form","Create & link new map","drop","drop","group","group:New maps & map links","","","src/hex-map/SubmapPickerModal.ts:115","" +"SubmapPicker.createName","New maps & map links","Link submap: inline create form","Name","drop","drop","group","group:New maps & map links","","","src/hex-map/SubmapPickerModal.ts:135","" +"SubmapPicker.createCols","New maps & map links","Link submap: inline create form","Size (columns)","drop","drop","group","group:New maps & map links","","","src/hex-map/SubmapPickerModal.ts:150","" +"SubmapPicker.createRows","New maps & map links","Link submap: inline create form","Size (rows)","drop","drop","group","group:New maps & map links","","","src/hex-map/SubmapPickerModal.ts:153","" +"SubmapPicker.createPalette","New maps & map links","Link submap: inline create form","Palette","drop","drop","group","group:New maps & map links","","","src/hex-map/SubmapPickerModal.ts:159","" +"SubmapPicker.createStartX","New maps & map links","Link submap: inline create form","Start at (x)","drop","drop","group","group:New maps & map links","","","src/hex-map/SubmapPickerModal.ts:170","" +"SubmapPicker.createStartY","New maps & map links","Link submap: inline create form","Start at (y)","drop","drop","group","group:New maps & map links","","","src/hex-map/SubmapPickerModal.ts:173","" +"SubmapPicker.createStagger","New maps & map links","Link submap: inline create form","Stagger (Odd/Even)","drop","drop","group","group:New maps & map links","","","src/hex-map/SubmapPickerModal.ts:180","" +"SubmapPicker.createTerrainTheme","New maps & map links","Link submap: inline create form","Map terrain theme","drop","drop","group","group:New maps & map links","","","src/hex-map/SubmapPickerModal.ts:192","" +"SubmapPicker.createAndLink","New maps & map links","Link submap: inline create form","Create & link / Create & enter","drop","drop","group","group:New maps & map links","","","src/hex-map/SubmapPickerModal.ts:241","" +"NewMapFields.name","New maps & map links","Dead code","Map name","drop","drop","group","group:New maps & map links","","","src/hex-map/newMapFields.ts:23","" +"NewMapFields.size","New maps & map links","Dead code","(cols × rows)","drop","drop","group","group:New maps & map links","","","src/hex-map/newMapFields.ts:28","" +"NewMapFields.palette","New maps & map links","Dead code","(palette)","drop","drop","group","group:New maps & map links","","","src/hex-map/newMapFields.ts:39","" +"GenerateRegions.makeThem","Regions, overworlds & biomes","Missing regions & go to region","Make them","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/OverworldModals.ts:62","" +"GenerateRegions.cancelStop","Regions, overworlds & biomes","Missing regions & go to region","Cancel / Stop / Close","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/OverworldModals.ts:61","" +"RegionNavigate.go","Regions, overworlds & biomes","Missing regions & go to region","Go to ","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/RegionNavigateModal.ts:378","" +"RegionNavigate.stay","Regions, overworlds & biomes","Missing regions & go to region","Stay","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/RegionNavigateModal.ts:383","" +"NewOverworld.name","Regions, overworlds & biomes","New overworld","Name","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/OverworldModals.ts:178","" +"NewOverworld.shape","Regions, overworlds & biomes","New overworld","Shape","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/OverworldModals.ts:182","" +"NewOverworld.hexCount","Regions, overworlds & biomes","New overworld","Hexes (N hexes)","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/OverworldModals.ts:190","" +"NewOverworld.columns","Regions, overworlds & biomes","New overworld","Columns","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/OverworldModals.ts:195","" +"NewOverworld.rows","Regions, overworlds & biomes","New overworld","Rows","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/OverworldModals.ts:197","" +"NewOverworld.palette","Regions, overworlds & biomes","New overworld","Palette","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/OverworldModals.ts:210","" +"NewOverworld.climate","Regions, overworlds & biomes","New overworld","Climate","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/OverworldModals.ts:287","" +"NewOverworld.land","Regions, overworlds & biomes","New overworld","Land","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/OverworldModals.ts:288","" +"NewOverworld.northIs","Regions, overworlds & biomes","New overworld","North is","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/OverworldModals.ts:289","" +"NewOverworld.water","Regions, overworlds & biomes","New overworld","Water","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/OverworldModals.ts:291","" +"NewOverworld.blankHexes","Regions, overworlds & biomes","New overworld","Blank hexes","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/OverworldModals.ts:300","" +"NewOverworld.blankBiome","Regions, overworlds & biomes","New overworld","Blank biome","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/OverworldModals.ts:303","" +"NewOverworld.seed","Regions, overworlds & biomes","New overworld","Seed","overkill","overkill","group","group:Regions, overworlds & biomes","","","src/hex-map/OverworldModals.ts:318","just make sure its saved for the saved rolls etc, its fine if it shows up on saves too. " +"NewOverworld.reroll","Regions, overworlds & biomes","New overworld","Reroll","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/OverworldModals.ts:320","" +"NewOverworld.regionSize","Regions, overworlds & biomes","New overworld","Each hex opens into","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/OverworldModals.ts:333","" +"NewOverworld.blend","Regions, overworlds & biomes","New overworld","Blend","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/OverworldModals.ts:337","" +"NewOverworld.makeAll","Regions, overworlds & biomes","New overworld","Make every region now / Remake the regions too","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/OverworldModals.ts:343","" +"NewOverworld.create","Regions, overworlds & biomes","New overworld","Create / Regenerate","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/OverworldModals.ts:351","" +"NewOverworld.closeButtons","Regions, overworlds & biomes","New overworld","Cancel","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/OverworldModals.ts:350","" +"NewOverworld.biomePool","Regions, overworlds & biomes","Biome pools","Biome pool","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/OverworldModals.ts:218","" +"NewOverworld.poolSave","Regions, overworlds & biomes","Biome pools","Save","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/OverworldModals.ts:219","" +"NewOverworld.poolSaveAs","Regions, overworlds & biomes","Biome pools","Save as…","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/OverworldModals.ts:220","" +"NewOverworld.unclimated","Regions, overworlds & biomes","Biome pools","Biomes without a climate","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/OverworldModals.ts:224","" +"NewOverworld.poolList","Regions, overworlds & biomes","Biome pools","Biomes in the pool (N)","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/OverworldModals.ts:374","" +"NewOverworld.poolWeight","Regions, overworlds & biomes","Biome pools","(weight per biome)","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/OverworldModals.ts:385","" +"NewOverworld.poolRemove","Regions, overworlds & biomes","Biome pools","✕ Remove ","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/OverworldModals.ts:393","" +"NewOverworld.poolAdd","Regions, overworlds & biomes","Biome pools","Add a biome…","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/OverworldModals.ts:404","" +"PoolName.name","Regions, overworlds & biomes","Biome pools","Pool name","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/OverworldModals.ts:529","" +"PoolName.closeButtons","Regions, overworlds & biomes","Biome pools","Save / Cancel","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/OverworldModals.ts:531","" +"BiomeLibrary.edit","Regions, overworlds & biomes","Biome library & biome form","Edit…","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/BiomeLibraryModal.ts:87","" +"BiomeLibrary.editGenerator","Regions, overworlds & biomes","Biome library & biome form","Edit generator…","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/BiomeLibraryModal.ts:93","" +"BiomeLibrary.add","Regions, overworlds & biomes","Biome library & biome form","Add biome…","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/BiomeLibraryModal.ts:99","" +"BiomeLibrary.biomeList","Regions, overworlds & biomes","Biome library & biome form","(biome list)","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/BiomeLibraryModal.ts:81","" +"BiomeForm.madeBy","Regions, overworlds & biomes","Biome library & biome form","Made by","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/BiomeLibraryModal.ts:162","" +"BiomeForm.regionsStartBlank","Regions, overworlds & biomes","Biome library & biome form","Regions start blank","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/BiomeLibraryModal.ts:173","" +"BiomeForm.name","Regions, overworlds & biomes","Biome library & biome form","Name","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/BiomeLibraryModal.ts:179","" +"BiomeForm.colour","Regions, overworlds & biomes","Biome library & biome form","Colour","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/BiomeLibraryModal.ts:182","" +"BiomeForm.mixSlider","Regions, overworlds & biomes","Biome library & biome form"," weight (slider)","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/BiomeLibraryModal.ts:195","" +"BiomeForm.mixNumber","Regions, overworlds & biomes","Biome library & biome form"," weight value","drop","drop","group","group:Regions, overworlds & biomes","","","src/hex-map/BiomeLibraryModal.ts:196","" +"BiomeForm.blend","Regions, overworlds & biomes","Biome library & biome form","Blend with neighbours","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/BiomeLibraryModal.ts:206","" +"BiomeForm.landShareOn","Regions, overworlds & biomes","Biome library & biome form","Set a land share","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/BiomeLibraryModal.ts:216","" +"BiomeForm.landShare","Regions, overworlds & biomes","Biome library & biome form","Land share","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/BiomeLibraryModal.ts:217","" +"BiomeForm.fewestIslands","Regions, overworlds & biomes","Biome library & biome form","Fewest islands","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/BiomeLibraryModal.ts:228","" +"BiomeForm.temperature","Regions, overworlds & biomes","Biome library & biome form","Temperature","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/BiomeLibraryModal.ts:244","" +"BiomeForm.moisture","Regions, overworlds & biomes","Biome library & biome form","Moisture","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/BiomeLibraryModal.ts:245","" +"BiomeForm.height","Regions, overworlds & biomes","Biome library & biome form","Height","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/BiomeLibraryModal.ts:246","" +"BiomeForm.chance","Regions, overworlds & biomes","Biome library & biome form","Chance %","overkill","overkill","group","group:Regions, overworlds & biomes","","","src/hex-map/BiomeLibraryModal.ts:250","" +"BiomeForm.coastOnly","Regions, overworlds & biomes","Biome library & biome form","Coast only","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/BiomeLibraryModal.ts:260","" +"BiomeForm.rare","Regions, overworlds & biomes","Biome library & biome form","Rare","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/BiomeLibraryModal.ts:261","" +"BiomeForm.transitionNext","Regions, overworlds & biomes","Biome library & biome form","Next to","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/BiomeLibraryModal.ts:284","" +"BiomeForm.transitionBetween","Regions, overworlds & biomes","Biome library & biome form","Put between","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/BiomeLibraryModal.ts:286","" +"BiomeForm.transitionRemove","Regions, overworlds & biomes","Biome library & biome form","Remove","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/BiomeLibraryModal.ts:289","" +"BiomeForm.transitionAdd","Regions, overworlds & biomes","Biome library & biome form","Add transition","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/BiomeLibraryModal.ts:294","" +"BiomeForm.previewReroll","Regions, overworlds & biomes","Biome library & biome form","Reroll","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/BiomeLibraryModal.ts:306","" +"BiomeForm.restoreDefault","Regions, overworlds & biomes","Biome library & biome form","Restore default","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/BiomeLibraryModal.ts:311","" +"BiomeForm.editGenerator","Regions, overworlds & biomes","Biome library & biome form","Edit generator…","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/BiomeLibraryModal.ts:321","" +"BiomeForm.save","Regions, overworlds & biomes","Biome library & biome form","Save","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/BiomeLibraryModal.ts:327","" +"BiomeForm.closeButtons","Regions, overworlds & biomes","Biome library & biome form","Cancel","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/BiomeLibraryModal.ts:326","" +"BiomePicker.biomeGrid","Regions, overworlds & biomes","Biome picker & paint","(biome tiles)","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/BiomeModals.ts:130","" +"BiomePicker.enterRegion","Regions, overworlds & biomes","Biome picker & paint","Enter region","simple","simple","group","group:Regions, overworlds & biomes","","","src/hex-map/BiomeModals.ts:146","" +"BiomePicker.reroll","Regions, overworlds & biomes","Biome picker & paint","Reroll","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/BiomeModals.ts:147","" +"BiomePicker.settings","Regions, overworlds & biomes","Biome picker & paint","Settings…","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/BiomeModals.ts:155","" +"BiomePicker.biomes","Regions, overworlds & biomes","Biome picker & paint","Biomes…","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/BiomeModals.ts:159","" +"BiomePalette.biomeTiles","Regions, overworlds & biomes","Biome picker & paint","(biome tiles)","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/BiomePaletteModal.ts:401","" +"BiomePalette.biomes","Regions, overworlds & biomes","Biome picker & paint","Biomes…","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/BiomePaletteModal.ts:421","" +"RegionGen.biome","Regions, overworlds & biomes","Region settings","Biome","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/BiomeModals.ts:212","" +"RegionGen.editGenerator","Regions, overworlds & biomes","Region settings","Edit generator…","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/BiomeModals.ts:219","" +"RegionGen.blend","Regions, overworlds & biomes","Region settings","Blend with neighbours","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/BiomeModals.ts:225","" +"RegionGen.wigglyBorders","Regions, overworlds & biomes","Region settings","Wiggly borders","overkill","overkill","group","group:Regions, overworlds & biomes","","","src/hex-map/BiomeModals.ts:231","" +"RegionGen.seed","Regions, overworlds & biomes","Region settings","Seed","overkill","overkill","group","group:Regions, overworlds & biomes","","","src/hex-map/BiomeModals.ts:238","" +"RegionGen.reroll","Regions, overworlds & biomes","Region settings","Reroll","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/BiomeModals.ts:241","" +"RegionGen.apply","Regions, overworlds & biomes","Region settings","Apply / Make region","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/BiomeModals.ts:254","" +"RegionGen.closeButtons","Regions, overworlds & biomes","Region settings","Cancel","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/BiomeModals.ts:253","" +"RegionSettings.shape","Regions, overworlds & biomes","Region settings","Shape (Rectangle / Hex flower)","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/regionSettingsForm.ts:52","" +"RegionSettings.sizePresets","Regions, overworlds & biomes","Region settings","Size","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/regionSettingsForm.ts:75","" +"RegionSettings.customSize","Regions, overworlds & biomes","Region settings","Hexes across (custom)","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/regionSettingsForm.ts:89","" +"RegionSettings.palette","Regions, overworlds & biomes","Region settings","Palette","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/regionSettingsForm.ts:119","" +"RegionSettings.blend","Regions, overworlds & biomes","Region settings","Blend","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/regionSettingsForm.ts:130","" +"RegionSettings.save","Regions, overworlds & biomes","Region settings","Save and continue","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/newChildMap.ts:173","" +"RegionSettings.closeButtons","Regions, overworlds & biomes","Region settings","Cancel","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/newChildMap.ts:172","" +"EditRegion.name","Regions, overworlds & biomes","Edit region","Region name","simple","simple","group","group:Regions, overworlds & biomes","","","src/hex-map/EditRegionModal.ts:82","" +"EditRegion.enterRegion","Regions, overworlds & biomes","Edit region","Enter region","simple","simple","group","group:Regions, overworlds & biomes","","","src/hex-map/EditRegionModal.ts:105","" +"EditRegion.openMapNote","Regions, overworlds & biomes","Edit region","Open map note","simple","simple","group","group:Regions, overworlds & biomes","","","src/hex-map/EditRegionModal.ts:112","" +"EditRegion.biomeGrid","Regions, overworlds & biomes","Edit region","(biome tiles)","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/EditRegionModal.ts:147","" +"EditRegion.reroll","Regions, overworlds & biomes","Edit region","Reroll","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/EditRegionModal.ts:176","" +"EditRegion.settings","Regions, overworlds & biomes","Edit region","Settings…","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/EditRegionModal.ts:180","" +"EditRegion.editGenerator","Regions, overworlds & biomes","Edit region","Edit generator…","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/EditRegionModal.ts:134","" +"EditRegion.makeGenerator","Regions, overworlds & biomes","Edit region","Make generator…","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/EditRegionModal.ts:140","" +"EditRegion.neighbourLinks","Regions, overworlds & biomes","Edit region","Next to: links","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/EditRegionModal.ts:220","" +"EditRegion.locationsList","Regions, overworlds & biomes","Edit region","List…","simple","simple","group","group:Regions, overworlds & biomes","","","src/hex-map/EditRegionModal.ts:237","" +"EditRegion.confirmPath","Regions, overworlds & biomes","Edit region","Confirm into regions / Update regions","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/EditRegionModal.ts:254","" +"EditRegion.notes","Regions, overworlds & biomes","Edit region","Region notes","simple","simple","group","group:Regions, overworlds & biomes","","","src/hex-map/EditRegionModal.ts:266","" +"GeoRegionPicker.regionTiles","Regions, overworlds & biomes","Region areas","(region note tiles)","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/GeoRegionPickerModal.ts:181","" +"GeoRegionPicker.remove","Regions, overworlds & biomes","Region areas","Remove","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/GeoRegionPickerModal.ts:184","" +"GeoRegionPicker.editTile","Regions, overworlds & biomes","Region areas","✏ Edit region","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/GeoRegionPickerModal.ts:210","" +"GeoRegionPicker.newName","Regions, overworlds & biomes","Region areas","New region name…","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/GeoRegionPickerModal.ts:257","" +"GeoRegionPicker.create","Regions, overworlds & biomes","Region areas","Create","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/GeoRegionPickerModal.ts:261","" +"GeoRegionEditor.openNote","Regions, overworlds & biomes","Region areas","Open note →","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/GeoRegionPickerModal.ts:42","" +"GeoRegionEditor.name","Regions, overworlds & biomes","Region areas","Name","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/GeoRegionPickerModal.ts:68","" +"GeoRegionEditor.color","Regions, overworlds & biomes","Region areas","Color","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/GeoRegionPickerModal.ts:77","" +"GeoRegionEditor.save","Regions, overworlds & biomes","Region areas","Save","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/GeoRegionPickerModal.ts:96","" +"GeoRegionEditor.clearColor","Regions, overworlds & biomes","Region areas","Clear color","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/GeoRegionPickerModal.ts:116","" +"WorldTypes.table","Space: world types","General","Table","keep","keep","group","group:Space: world types","","","src/space/WorldTypesModal.ts:232","" +"WorldTypes.newTable","Space: world types","General","New table…","keep","keep","group","group:Space: world types","","","src/space/WorldTypesModal.ts:241","" +"WorldTypes.newTableName","Space: world types","General","Table name","keep","keep","group","group:Space: world types","","","src/space/WorldTypesModal.ts:330","" +"WorldTypes.newTableCreate","Space: world types","General","Create","keep","keep","group","group:Space: world types","","","src/space/WorldTypesModal.ts:331","" +"WorldTypes.openNote","Space: world types","General","Open note","keep","keep","group","group:Space: world types","","","src/space/WorldTypesModal.ts:244","" +"WorldTypes.restoreDefault","Space: world types","General","Restore default","keep","keep","group","group:Space: world types","","","src/space/WorldTypesModal.ts:250","" +"WorldTypes.tabWorlds","Space: world types","General","Worlds (N)","keep","keep","group","group:Space: world types","","","src/space/WorldTypesModal.ts:279","" +"WorldTypes.tabStars","Space: world types","General","Stars (N)","keep","keep","group","group:Space: world types","","","src/space/WorldTypesModal.ts:279","" +"WorldTypes.tabFeatures","Space: world types","General","Sector features (N)","keep","keep","group","group:Space: world types","","","src/space/WorldTypesModal.ts:279","" +"WorldTypes.rowMoveUp","Space: world types","General","↑ Move up","keep","keep","group","group:Space: world types","","","src/space/WorldTypesModal.ts:414","" +"WorldTypes.rowMoveDown","Space: world types","General","↓ Move down","keep","keep","group","group:Space: world types","","","src/space/WorldTypesModal.ts:415","" +"WorldTypes.rowRemove","Space: world types","General","✕ Remove row","keep","keep","group","group:Space: world types","","","src/space/WorldTypesModal.ts:416","" +"WorldTypes.addRow","Space: world types","General","Add row","keep","keep","group","group:Space: world types","","","src/space/WorldTypesModal.ts:298","" +"WorldTypes.save","Space: world types","General","Save","keep","keep","group","group:Space: world types","","","src/space/WorldTypesModal.ts:309","" +"WorldTypes.worldName","Space: world types","Worlds tab","World","keep","keep","group","group:Space: world types","","","src/space/WorldTypesModal.ts:434","" +"WorldTypes.worldWeight","Space: world types","Worlds tab","Weight","keep","keep","group","group:Space: world types","","","src/space/WorldTypesModal.ts:434","" +"WorldTypes.worldMap","Space: world types","Worlds tab","Map","keep","keep","group","group:Space: world types","","","src/space/WorldTypesModal.ts:425","" +"WorldTypes.worldOrbit","Space: world types","Worlds tab","Orbit","keep","keep","group","group:Space: world types","","","src/space/WorldTypesModal.ts:434","" +"WorldTypes.worldStars","Space: world types","Worlds tab","Stars","keep","keep","group","group:Space: world types","","","src/space/WorldTypesModal.ts:434","" +"WorldTypes.worldTemperature","Space: world types","Worlds tab","Temperature","keep","keep","group","group:Space: world types","","","src/space/WorldTypesModal.ts:434","" +"WorldTypes.worldSize","Space: world types","Worlds tab","Size","keep","keep","group","group:Space: world types","","","src/space/WorldTypesModal.ts:434","" +"WorldTypes.worldGenerator","Space: world types","Worlds tab","Generator","overkill","overkill","group","group:Space: world types","","","src/space/WorldTypesModal.ts:434","" +"WorldTypes.worldOptions","Space: world types","Worlds tab","Options","overkill","overkill","group","group:Space: world types","","","src/space/WorldTypesModal.ts:434","" +"WorldTypes.worldPalette","Space: world types","Worlds tab","Palette","keep","keep","group","group:Space: world types","","","src/space/WorldTypesModal.ts:434","" +"WorldTypes.worldBase","Space: world types","Worlds tab","Base","keep","keep","group","group:Space: world types","","","src/space/WorldTypesModal.ts:434","" +"WorldTypes.worldNotes","Space: world types","Worlds tab","Notes","keep","keep","group","group:Space: world types","","","src/space/WorldTypesModal.ts:434","" +"WorldTypes.starName","Space: world types","Stars tab","Star","keep","keep","group","group:Space: world types","","","src/space/WorldTypesModal.ts:434","" +"WorldTypes.starWeight","Space: world types","Stars tab","Weight","keep","keep","group","group:Space: world types","","","src/space/WorldTypesModal.ts:434","" +"WorldTypes.starNotes","Space: world types","Stars tab","Notes","keep","keep","group","group:Space: world types","","","src/space/WorldTypesModal.ts:434","" +"WorldTypes.featureName","Space: world types","Sector features tab","Feature","keep","keep","group","group:Space: world types","","","src/space/WorldTypesModal.ts:434","" +"WorldTypes.featureChance","Space: world types","Sector features tab","Chance","keep","keep","group","group:Space: world types","","","src/space/WorldTypesModal.ts:434","" +"WorldTypes.featureNotes","Space: world types","Sector features tab","Notes","keep","keep","group","group:Space: world types","","","src/space/WorldTypesModal.ts:434","" +"WorldTypes.previewMap","Space: world types","Preview","Map","overkill","overkill","group","group:Space: world types","","","src/space/WorldTypesModal.ts:464","" +"WorldTypes.previewOrbit","Space: world types","Preview","Orbit","overkill","overkill","group","group:Space: world types","","","src/space/WorldTypesModal.ts:465","" +"WorldTypes.previewStar","Space: world types","Preview","Star","overkill","overkill","group","group:Space: world types","","","src/space/WorldTypesModal.ts:466","" +"WorldTypes.previewTemperature","Space: world types","Preview","Temperature","overkill","overkill","group","group:Space: world types","","","src/space/WorldTypesModal.ts:467","" +"WorldTypes.previewRolls","Space: world types","Preview","Rolls","overkill","overkill","group","group:Space: world types","","","src/space/WorldTypesModal.ts:473","" +"GenLib.generatorsTab","Generator page","Library","Generators","keep","keep","group","group:Generator page","","","src/worldgen/GeneratorLibrary.ts:70","" +"GenLib.mapsTab","Generator page","Library","Maps","keep","keep","group","group:Generator page","","","src/worldgen/GeneratorLibrary.ts:71","" +"GenLib.filter","Generator page","Library","Filter…","keep","keep","group","group:Generator page","","","src/worldgen/GeneratorLibrary.ts:50","" +"GenLib.generatorRow","Generator page","Library","(generator row: click to load)","keep","keep","group","group:Generator page","","","src/worldgen/GeneratorLibrary.ts:113","" +"GenLib.generatorRowTick","Generator page","Library","(row checkbox)","keep","keep","group","group:Generator page","","","src/worldgen/GeneratorLibrary.ts:263","" +"GenLib.selectAll","Generator page","Library","Select all shown","keep","keep","group","group:Generator page","","","src/worldgen/GeneratorLibrary.ts:246","" +"GenLib.openFile","Generator page","Library","Open file","keep","keep","group","group:Generator page","","","src/worldgen/GeneratorLibrary.ts:125","" +"GenLib.relearn","Generator page","Library","Re-learn","keep","keep","group","group:Generator page","","","src/worldgen/GeneratorLibrary.ts:126","" +"GenLib.blend","Generator page","Library","Blend","keep","keep","group","group:Generator page","","","src/worldgen/GeneratorLibrary.ts:127","" +"GenLib.delete","Generator page","Library","Delete","keep","keep","group","group:Generator page","","","src/worldgen/GeneratorLibrary.ts:131","" +"GenLib.mapRow","Generator page","Library","(map row: tick to learn from)","keep","keep","group","group:Generator page","","","src/worldgen/GeneratorLibrary.ts:192","" +"GenLib.learnName","Generator page","Library","Generator name","keep","keep","group","group:Generator page","","","src/worldgen/GeneratorLibrary.ts:206","" +"GenLib.learn","Generator page","Library","Learn generator","keep","keep","group","group:Generator page","","","src/worldgen/GeneratorLibrary.ts:210","" +"GenPage.saveDraft","Generator page","Recipe","Save generator","keep","keep","group","group:Generator page","","","src/worldgen/GeneratorPanel.ts:336","" +"GenPage.discardDraft","Generator page","Recipe","Discard","keep","keep","group","group:Generator page","","","src/worldgen/GeneratorPanel.ts:349","" +"GenPage.name","Generator page","Recipe","Name","keep","keep","group","group:Generator page","","","src/worldgen/GeneratorPanel.ts:358","" +"GenPage.rename","Generator page","Recipe","Rename","keep","keep","group","group:Generator page","","","src/worldgen/GeneratorPanel.ts:359","" +"GenPage.generatorPalette","Generator page","Recipe","Palette","keep","keep","group","group:Generator page","","","src/worldgen/GeneratorPanel.ts:395","" +"GenPage.relearn","Generator page","Recipe","Re-learn / Re-blend","keep","keep","group","group:Generator page","","","src/worldgen/GeneratorPanel.ts:417","" +"GenPage.openFile","Generator page","Recipe","Open file","keep","keep","group","group:Generator page","","","src/worldgen/GeneratorPanel.ts:436","" +"GenPage.sourceInfluence","Generator page","Recipe"," influence","keep","keep","group","group:Generator page","","","src/worldgen/GeneratorPanel.ts:457","" +"GenPage.sourceCompass","Generator page","Recipe","(direction arrows ↖↑↗←•→↙↓↘)","keep","keep","group","group:Generator page","","","src/worldgen/GeneratorPanel.ts:461","" +"GenPage.backToMapSize","Generator page","Recipe","Back to map size","keep","keep","group","group:Generator page","","","src/worldgen/GeneratorPanel.ts:522","" +"GenPage.resetSettings","Generator page","Recipe","Reset settings to defaults","keep","keep","group","group:Generator page","","","src/worldgen/GeneratorPanel.ts:536","" +"GenPage.sizePresets","Generator page","Recipe","(size presets)","keep","keep","group","group:Generator page","","","src/worldgen/GeneratorPanel.ts:593","" +"GenPage.connectTo","Generator page","Recipe","Connect to","keep","keep","group","group:Generator page","","","src/worldgen/GeneratorPanel.ts:619","" +"GenPage.connectSide","Generator page","Recipe","(side: east/west/north/south of it)","keep","keep","group","group:Generator page","","","src/worldgen/GeneratorPanel.ts:622","" +"GenPage.regionsHint","Generator page","Recipe","Turn on regions and overworlds / ✕","keep","keep","group","group:Generator page","","","src/worldgen/GeneratorPanel.ts:631","" +"GenPage.leanToNeighbours","Generator page","Recipe","Lean toward neighbours","keep","keep","group","group:Generator page","","","src/worldgen/GeneratorPanel.ts:665","" +"GenPage.guaranteedFeatures","Generator page","Recipe","Guaranteed features","keep","keep","group","group:Generator page","","","src/worldgen/GeneratorPanel.ts:1046","" +"GenPage.connectedLand","Generator page","Recipe","Connected land","keep","keep","group","group:Generator page","","","src/worldgen/GeneratorPanel.ts:1048","" +"GenPage.impassableSearch","Generator page","Recipe","Impassable terrain","keep","keep","group","group:Generator page","","","src/worldgen/GeneratorPanel.ts:1502","" +"GenPage.impassableRemove","Generator page","Recipe","× (remove chip)","keep","keep","group","group:Generator page","","","src/worldgen/GeneratorPanel.ts:1515","" +"GenPage.impassableSuggestAdd","Generator page","Recipe","Add / Add all","keep","keep","group","group:Generator page","","","src/worldgen/GeneratorPanel.ts:1064","" +"GenPage.mix","Generator page","Recipe","Mix","keep","keep","group","group:Generator page","","","src/worldgen/GeneratorPanel.ts:1118","" +"GenPage.minPatches","Generator page","Recipe","Min","keep","keep","group","group:Generator page","","","src/worldgen/GeneratorPanel.ts:1132","" +"GenPage.maxPatches","Generator page","Recipe","Max","keep","keep","group","group:Generator page","","","src/worldgen/GeneratorPanel.ts:1132","" +"GenPage.sectionFold","Generator page","Recipe","(section heading fold)","keep","keep","group","group:Generator page","","","src/worldgen/GeneratorPanel.ts:1415","" +"GenPage.seed","Generator page","Preview & saves","Seed","overkill","overkill","group","group:Generator page","","","src/worldgen/GeneratorPanel.ts:556","" +"GenPage.seedLock","Generator page","Preview & saves","(lock seed)","overkill","overkill","group","group:Generator page","","","src/worldgen/GeneratorPanel.ts:559","" +"GenPage.reroll","Generator page","Preview & saves","Re-roll / Regenerate","keep","keep","group","group:Generator page","","","src/worldgen/GeneratorPanel.ts:560","" +"GenPage.previewSize","Generator page","Preview & saves","Size (cols × rows)","keep","keep","group","group:Generator page","","","src/worldgen/GeneratorPanel.ts:562","" +"GenPage.previewPalette","Generator page","Preview & saves","Palette","keep","keep","group","group:Generator page","","","src/worldgen/GeneratorPanel.ts:567","" +"GenPage.newMapName","Generator page","Preview & saves","Name for the new map","keep","keep","group","group:Generator page","","","src/worldgen/GeneratorPanel.ts:690","" +"GenPage.createMap","Generator page","Preview & saves","Create map","keep","keep","group","group:Generator page","","","src/worldgen/GeneratorPanel.ts:691","" +"GenPage.saveName","Generator page","Preview & saves","Save name (optional)","keep","keep","group","group:Generator page","","","src/worldgen/GeneratorPanel.ts:697","" +"GenPage.saveSnapshot","Generator page","Preview & saves","Save","keep","keep","group","group:Generator page","","","src/worldgen/GeneratorPanel.ts:698","" +"GenPage.loadSelect","Generator page","Preview & saves","(saved snapshot list)","keep","keep","group","group:Generator page","","","src/worldgen/GeneratorPanel.ts:700","" +"GenPage.loadSnapshot","Generator page","Preview & saves","Load","keep","keep","group","group:Generator page","","","src/worldgen/GeneratorPanel.ts:701","" +"GenPage.featureSize","Generator page","Engine tuning","Feature size","keep","keep","group","group:Generator page/Engine tuning","","","src/worldgen/GeneratorPanel.ts:1012","" +"GenPage.clumping","Generator page","Engine tuning","Clumping","overkill","overkill","group","group:Generator page/Engine tuning","","","src/worldgen/GeneratorPanel.ts:1013","Engine tuning should have its own separate overkill setting. Basically all these ones marked ""overkill"" for generator settings should go into an ""advanced"" dropdown that defaults closed rather than them being gated under the global overkill setting. That way people can muck about with them when they wanna go a bit further on one gen or another, instead of having to flip and stick with a top-level setting. " +"GenPage.lineWidth","Generator page","Engine tuning","Line width","keep","keep","group","group:Generator page/Engine tuning","","","src/worldgen/GeneratorPanel.ts:1016","" +"GenPage.edgeSmoothing","Generator page","Engine tuning","Edge smoothing","overkill","overkill","group","group:Generator page/Engine tuning","","","src/worldgen/GeneratorPanel.ts:1021","" +"GenPage.removeSmallPatches","Generator page","Engine tuning","Remove small patches","overkill","overkill","group","group:Generator page/Engine tuning","","","src/worldgen/GeneratorPanel.ts:1023","" +"GenPage.keepRare","Generator page","Engine tuning","Keep rare terrain","overkill","overkill","group","group:Generator page/Engine tuning","","","src/worldgen/GeneratorPanel.ts:1025","" +"GenPage.symmetry","Generator page","Engine tuning","Symmetry","keep","keep","group","group:Generator page/Engine tuning","","","src/worldgen/GeneratorPanel.ts:1027","" +"GenPage.edgeStyle","Generator page","Engine tuning","Edge style","keep","keep","group","group:Generator page/Engine tuning","","","src/worldgen/GeneratorPanel.ts:1029","" +"GenPage.edgeStrength","Generator page","Engine tuning","Edge strength","overkill","overkill","group","group:Generator page/Engine tuning","","","src/worldgen/GeneratorPanel.ts:1032","" +"GenPage.directionalBias","Generator page","Engine tuning","Directional bias","overkill","overkill","group","group:Generator page/Engine tuning","","","src/worldgen/GeneratorPanel.ts:1036","" +"GenPage.scatter","Generator page","Engine tuning","Scatter","overkill","overkill","group","group:Generator page/Engine tuning","","","src/worldgen/GeneratorPanel.ts:1037","" +"GenPage.spacing","Generator page","Engine tuning","Spacing","overkill","overkill","group","group:Generator page/Engine tuning","","","src/worldgen/GeneratorPanel.ts:1039","" +"GenPage.randomness","Generator page","Engine tuning","Randomness","overkill","overkill","group","group:Generator page/Engine tuning","","","src/worldgen/GeneratorPanel.ts:1041","" +"GenPage.near","Generator page","Engine tuning","Near","overkill","overkill","group","group:Generator page/Engine tuning","","","src/worldgen/GeneratorPanel.ts:1146","" +"GenPage.mixStrength","Generator page","Engine tuning","Mix strength","overkill","overkill","group","group:Generator page/Engine tuning","","","src/worldgen/GeneratorPanel.ts:1176","" +"GenPage.drawPaths","Generator page","Paths","Draw paths","keep","keep","group","group:Generator page","","","src/worldgen/GeneratorPanel.ts:1204","" +"GenPage.pathTypeFold","Generator page","Paths","(show routes chevron)","overkill","overkill","group","group:Generator page","","","src/worldgen/GeneratorPanel.ts:1225","ditto for the above, make sure these go into an ""advanced"" section, Maybe the advanced section can have collapsible sub-sections as well so its clean to view. " +"GenPage.pathTypeOn","Generator page","Paths","Draw paths","keep","keep","group","group:Generator page","","","src/worldgen/GeneratorPanel.ts:1227","" +"GenPage.pathTypeAmount","Generator page","Paths","Amount","keep","keep","group","group:Generator page","","","src/worldgen/GeneratorPanel.ts:1261","" +"GenPage.pathTypeWiggle","Generator page","Paths","Wiggle","keep","keep","group","group:Generator page","","","src/worldgen/GeneratorPanel.ts:1277","" +"GenPage.pathTypeLength","Generator page","Paths","Length","keep","keep","group","group:Generator page","","","src/worldgen/GeneratorPanel.ts:1278","" +"GenPage.pathTypeFollow","Generator page","Paths","Follow terrain","keep","keep","group","group:Generator page","","","src/worldgen/GeneratorPanel.ts:1279","" +"GenPage.pathTypeAvoid","Generator page","Paths","Avoid impassable terrain and the map border","overkill","overkill","group","group:Generator page","","","src/worldgen/GeneratorPanel.ts:1290","" +"GenPage.routeOn","Generator page","Paths","(route checkbox)","overkill","overkill","group","group:Generator page","","","src/worldgen/GeneratorPanel.ts:1315","" +"GenPage.routeCount","Generator page","Paths","Count","overkill","overkill","group","group:Generator page","","","src/worldgen/GeneratorPanel.ts:1330","" +"GenPage.routeAs","Generator page","Paths","As","overkill","overkill","group","group:Generator page","","","src/worldgen/GeneratorPanel.ts:1347","" +"GenPage.routeWiggle","Generator page","Paths","Wiggle (route)","overkill","overkill","group","group:Generator page","","","src/worldgen/GeneratorPanel.ts:1373","" +"GenPage.routeLength","Generator page","Paths","Length (route)","overkill","overkill","group","group:Generator page","","","src/worldgen/GeneratorPanel.ts:1374","" +"GenPage.routeFollow","Generator page","Paths","Follow terrain (route)","overkill","overkill","group","group:Generator page","","","src/worldgen/GeneratorPanel.ts:1375","" +"BiomePage.biome","Generator page","Biome (blend field)","Biome","keep","keep","group","group:Generator page","","","src/worldgen/BiomePanel.ts:150","" +"BiomePage.openNote","Generator page","Biome (blend field)","Open note","keep","keep","group","group:Generator page","","","src/worldgen/BiomePanel.ts:160","" +"BiomePage.restoreDefault","Generator page","Biome (blend field)","Restore default","keep","keep","group","group:Generator page","","","src/worldgen/BiomePanel.ts:165","" +"BiomePage.back","Generator page","Biome (blend field)","Back to generators","keep","keep","group","group:Generator page","","","src/worldgen/BiomePanel.ts:173","" +"BiomePage.weightSlider","Generator page","Biome (blend field)","Weight","keep","keep","group","group:Generator page","","","src/worldgen/BiomePanel.ts:191","" +"BiomePage.weightNumber","Generator page","Biome (blend field)","(weight value)","drop","drop","group","group:Generator page","","","src/worldgen/BiomePanel.ts:192","" +"BiomePage.minPatches","Generator page","Biome (blend field)","Min patches","keep","keep","group","group:Generator page","","","src/worldgen/BiomePanel.ts:193","" +"BiomePage.blendWidth","Generator page","Biome (blend field)","Blend width","keep","keep","group","group:Generator page","","","src/worldgen/BiomePanel.ts:231","" +"BiomePage.landShareOn","Generator page","Biome (blend field)","Land share (on/off)","keep","keep","group","group:Generator page","","","src/worldgen/BiomePanel.ts:242","" +"BiomePage.landShare","Generator page","Biome (blend field)","Land share","keep","keep","group","group:Generator page","","","src/worldgen/BiomePanel.ts:243","" +"BiomePage.minIslands","Generator page","Biome (blend field)","Min islands","keep","keep","group","group:Generator page","","","src/worldgen/BiomePanel.ts:261","" +"BiomePage.shore","Generator page","Biome (blend field)","Shore","keep","keep","group","group:Generator page","","","src/worldgen/BiomePanel.ts:270","" +"BiomePage.transitionNext","Generator page","Biome (blend field)","Next to","keep","keep","group","group:Generator page","","","src/worldgen/BiomePanel.ts:299","" +"BiomePage.transitionBetween","Generator page","Biome (blend field)","put","keep","keep","group","group:Generator page","","","src/worldgen/BiomePanel.ts:301","" +"BiomePage.transitionRemove","Generator page","Biome (blend field)","Remove","keep","keep","group","group:Generator page","","","src/worldgen/BiomePanel.ts:309","" +"BiomePage.transitionAdd","Generator page","Biome (blend field)","Add transition","keep","keep","group","group:Generator page","","","src/worldgen/BiomePanel.ts:315","" +"BiomePage.seed","Generator page","Biome (blend field)","Seed","overkill","overkill","group","group:Generator page","","","src/worldgen/BiomePanel.ts:330","" +"BiomePage.reroll","Generator page","Biome (blend field)","Re-roll","keep","keep","group","group:Generator page","","","src/worldgen/BiomePanel.ts:332","" +"BiomePage.size","Generator page","Biome (blend field)","Size","keep","keep","group","group:Generator page","","","src/worldgen/BiomePanel.ts:338","" +"BiomePage.aroundIt","Generator page","Biome (blend field)","Around it","keep","keep","group","group:Generator page","","","src/worldgen/BiomePanel.ts:346","" +"BiomePage.palette","Generator page","Biome (blend field)","Palette","keep","keep","group","group:Generator page","","","src/worldgen/BiomePanel.ts:353","" +"MakeGen.newRadio","Generator page","Make generator from a map","New generator","keep","keep","group","group:Generator page","","","src/hex-map/MakeGeneratorModal.ts:68","" +"MakeGen.name","Generator page","Make generator from a map","Name","keep","keep","group","group:Generator page","","","src/hex-map/MakeGeneratorModal.ts:70","" +"MakeGen.overwriteRadio","Generator page","Make generator from a map","Overwrite existing","keep","keep","group","group:Generator page","","","src/hex-map/MakeGeneratorModal.ts:80","" +"MakeGen.overwriteList","Generator page","Make generator from a map","Generator to overwrite","keep","keep","group","group:Generator page","","","src/hex-map/MakeGeneratorModal.ts:96","" +"MakeGen.make","Generator page","Make generator from a map","Make generator / Overwrite","keep","keep","group","group:Generator page","","","src/hex-map/MakeGeneratorModal.ts:90","" +"MakeGen.closeButtons","Generator page","Make generator from a map","Cancel","keep","keep","group","group:Generator page","","","src/hex-map/MakeGeneratorModal.ts:92","" +"PaletteEditor.paletteSelect","Palette editor","Toolbar","Palette","keep","keep","group","group:Palette editor","","","src/palettes/PaletteEditorView.ts:99","" +"PaletteEditor.addPalette","Palette editor","Toolbar","Add palette…","keep","keep","group","group:Palette editor","","","src/palettes/PaletteEditorView.ts:103","" +"PaletteEditor.openNote","Palette editor","Toolbar","Open note","keep","keep","group","group:Palette editor","","","src/palettes/PaletteEditorView.ts:112","" +"PaletteEditor.filter","Palette editor","Toolbar","Filter terrains…","keep","keep","group","group:Palette editor","","","src/palettes/PaletteEditorView.ts:118","" +"PaletteEditor.guessTypes","Palette editor","Terrains","Guess types from names","keep","keep","group","group:Palette editor","","","src/palettes/PaletteEditorView.ts:140","" +"PaletteEditor.rowDrag","Palette editor","Terrains","Drag to reorder (⠿)","keep","keep","group","group:Palette editor","","","src/palettes/PaletteEditorView.ts:260","" +"PaletteEditor.color","Palette editor","Terrains"," color","keep","keep","group","group:Palette editor","","","src/palettes/PaletteEditorView.ts:277","" +"PaletteEditor.name","Palette editor","Terrains","Terrain name","keep","keep","group","group:Palette editor","","","src/palettes/PaletteEditorView.ts:283","" +"PaletteEditor.type","Palette editor","Terrains"," type","keep","keep","group","group:Palette editor","","","src/palettes/PaletteEditorView.ts:301","" +"PaletteEditor.category","Palette editor","Terrains"," category","keep","keep","group","group:Palette editor","","","src/palettes/PaletteEditorView.ts:312","" +"PaletteEditor.icon","Palette editor","Terrains","Choose icon","keep","keep","group","group:Palette editor","","","src/palettes/PaletteEditorView.ts:326","" +"PaletteEditor.tintOn","Palette editor","Terrains","Tint icon","keep","keep","group","group:Palette editor","","","src/palettes/PaletteEditorView.ts:345","" +"PaletteEditor.tintColor","Palette editor","Terrains","Icon tint","keep","keep","group","group:Palette editor","","","src/palettes/PaletteEditorView.ts:347","" +"PaletteEditor.impassable","Palette editor","Terrains"," impassable","keep","keep","group","group:Palette editor","","","src/palettes/PaletteEditorView.ts:361","" +"PaletteEditor.delete","Palette editor","Terrains","Delete terrain (×)","keep","keep","group","group:Palette editor","","","src/palettes/PaletteEditorView.ts:370","" +"PaletteEditor.addTerrain","Palette editor","Terrains","Add terrain","keep","keep","group","group:Palette editor","","","src/palettes/PaletteEditorView.ts:178","" +"PaletteEditor.submapPalette","Palette editor","Palette settings & path types","Submap palette","keep","keep","group","group:Palette editor","","","src/palettes/PaletteEditorView.ts:195","" +"PaletteEditor.pathTypeRow","Palette editor","Palette settings & path types","(path type row)","keep","keep","group","group:Palette editor","","","src/palettes/PaletteEditorView.ts:228","" +"PaletteEditor.addPathType","Palette editor","Palette settings & path types","Add path type","keep","keep","group","group:Palette editor","","","src/palettes/PaletteEditorView.ts:236","" +"PaletteEditor.submapDefaultPalette","Palette editor","Submap defaults","Palette","keep","keep","group","group:Palette editor","","","src/palettes/PaletteEditorView.ts:410","" +"PaletteEditor.submapDefaultCols","Palette editor","Submap defaults","Columns","keep","keep","group","group:Palette editor","","","src/palettes/PaletteEditorView.ts:417","" +"PaletteEditor.submapDefaultRows","Palette editor","Submap defaults","Rows","keep","keep","group","group:Palette editor","","","src/palettes/PaletteEditorView.ts:419","" +"PaletteEditor.submapDefaultGenerator","Palette editor","Submap defaults","Generator","keep","keep","group","group:Palette editor","","","src/palettes/PaletteEditorView.ts:429","" +"PaletteEditor.generatorOptions","Palette editor","Submap defaults","Generator options","overkill","overkill","group","group:Palette editor","","","src/palettes/PaletteEditorView.ts:444","" +"PaletteEditor.submapDefaultBaseTerrain","Palette editor","Submap defaults","Base terrain","keep","keep","group","group:Palette editor","","","src/palettes/PaletteEditorView.ts:455","" +"PaletteEditor.submapDefaultDelete","Palette editor","Submap defaults","Remove default (×)","keep","keep","group","group:Palette editor","","","src/palettes/PaletteEditorView.ts:459","" +"PaletteEditor.addDefaultTerrain","Palette editor","Submap defaults","Terrain to add a default for","keep","keep","group","group:Palette editor","","","src/palettes/PaletteEditorView.ts:473","" +"PaletteEditor.addDefault","Palette editor","Submap defaults","Add default","keep","keep","group","group:Palette editor","","","src/palettes/PaletteEditorView.ts:475","" +"RTView.refreshList","Random tables","Tables list","Refresh list (↺)","overkill","overkill","group","group:Random tables/Tables list","","","src/random-tables/RandomTableView.ts:149","we should confirm that it does it at a good cadence for all of these ""sink refresh"" bits " +"RTView.tablesTab","Random tables","Tables list","Tables","keep","keep","group","group:Random tables/Tables list","","","src/random-tables/RandomTableView.ts:156","" +"RTView.workflowsTab","Random tables","Tables list","Workflows","keep","keep","group","group:Random tables/Tables list","","","src/random-tables/RandomTableView.ts:160","" +"RTView.tabMiddleClick","Random tables","Tables list","(middle-click a tab)","keep","keep","group","group:Random tables/Tables list","","","src/random-tables/RandomTableView.ts:172","" +"RTView.workflowsHintTurnOn","Random tables","Tables list","Turn on workflows","keep","keep","group","group:Random tables/Tables list","","","src/random-tables/RandomTableView.ts:89","" +"RTView.workflowsHintHide","Random tables","Tables list","Hide this hint (✕)","keep","keep","group","group:Random tables/Tables list","","","src/advancedHints.ts:36","" +"RTView.filterSearch","Random tables","Tables list","Filter tables…","keep","keep","group","group:Random tables/Tables list","","","src/random-tables/RandomTableView.ts:198","" +"RTView.tablesTree","Random tables","Tables list","(table folder tree)","simple","simple","group","group:Random tables/Tables list","","","src/random-tables/RandomTableView.ts:607","" +"RTView.folderToggle","Random tables","Tables list","(folder ▶/▼)","keep","keep","group","group:Random tables/Tables list","","","src/random-tables/FolderTree.ts:161","" +"RTView.fileMiddleClick","Random tables","Tables list","(middle-click a table)","keep","keep","group","group:Random tables/Tables list","","","src/random-tables/RandomTableView.ts:1121","" +"RTView.dragToMove","Random tables","Tables list","(drag table onto folder)","keep","keep","group","group:Random tables/Tables list","","","src/random-tables/RandomTableView.ts:1137","" +"RTView.folderMenuRollPicker","Random tables","Tables list","Exclude from roll picker / Include in roll picker","advanced","advanced","group","group:Random tables/Tables list","","","src/random-tables/RandomTableView.ts:1153","" +"RTView.folderMenuEncounters","Random tables","Tables list","Exclude from encounters table / Include in encounters table","advanced","advanced","group","group:Random tables/Tables list","","","src/random-tables/RandomTableView.ts:1180","" +"RTView.fileMenuOpenNewTab","Random tables","Tables list","Open in new tab","keep","keep","group","group:Random tables/Tables list","","","src/random-tables/RandomTableView.ts:1213","" +"RTView.fileMenuRollPicker","Random tables","Tables list","Exclude from roll picker / Include in roll picker","advanced","advanced","group","group:Random tables/Tables list","","","src/random-tables/RandomTableView.ts:1227","" +"RTView.fileMenuEncounters","Random tables","Tables list","Exclude from encounters table / Include in encounters table","advanced","advanced","group","group:Random tables/Tables list","","","src/random-tables/RandomTableView.ts:1247","" +"RTView.fileMenuDelete","Random tables","Tables list","Delete table","keep","keep","group","group:Random tables/Tables list","","","src/random-tables/RandomTableView.ts:1270","" +"RTView.newTableName","Random tables","Tables list","New table name…","keep","keep","group","group:Random tables/Tables list","","","src/random-tables/RandomTableView.ts:283","" +"RTView.newTableButton","Random tables","Tables list","+ new","keep","keep","group","group:Random tables/Tables list","","","src/random-tables/RandomTableView.ts:305","" +"RTView.generateFromFolder","Random tables","Tables list","Generate from folder or file (optional)…","advanced","advanced","group","group:Random tables/Tables list","","","src/random-tables/RandomTableView.ts:367","" +"RTView.newWorkflow","Random tables","Tables list","+ new workflow","keep","keep","group","group:Random tables/Tables list","","","src/random-tables/RandomTableView.ts:271","" +"RTView.workflowsTree","Random tables","Tables list","(workflow folder tree)","keep","keep","group","group:Random tables/Tables list","","","src/random-tables/RandomTableView.ts:735","" +"RTView.workflowMenuOpenNewTab","Random tables","Tables list","Open in new tab","keep","keep","group","group:Random tables/Tables list","","","src/random-tables/RandomTableView.ts:781","" +"RTView.workflowMenuDelete","Random tables","Tables list","Delete workflow","keep","keep","group","group:Random tables/Tables list","","","src/random-tables/RandomTableView.ts:795","" +"RTView.workflowMiddleClick","Random tables","Tables list","(middle-click a workflow)","keep","keep","group","group:Random tables/Tables list","","","src/random-tables/RandomTableView.ts:769","" +"RTView.edit","Random tables","Table detail","Edit","keep","keep","group","group:Random tables","","","src/random-tables/RandomTableView.ts:1478","" +"RTView.openNote","Random tables","Table detail","Open note","keep","keep","group","group:Random tables","","","src/random-tables/RandomTableView.ts:1494","" +"RTView.exportPdf","Random tables","Table detail","Export PDF","keep","keep","group","group:Random tables","","","src/random-tables/RandomTableView.ts:1503","" +"RTView.exportMarkdown","Random tables","Table detail","Export Markdown","keep","keep","group","group:Random tables","","","src/random-tables/RandomTableView.ts:1513","" +"RTView.refreshLinked","Random tables","Table detail","Refresh","overkill","overkill","group","group:Random tables","","","src/random-tables/RandomTableView.ts:1523","" +"RTView.dieSelect","Random tables","Table detail","(die: — no die —, d4…d1000)","keep","keep","group","group:Random tables","","","src/random-tables/RandomTableView.ts:1537","" +"RTView.fixKeepRanges","Random tables","Table detail","Keep ranges → set weights","keep","keep","group","group:Random tables","","","src/random-tables/RandomTableView.ts:1428","" +"RTView.fixKeepWeights","Random tables","Table detail","Keep weights → redo ranges","keep","keep","group","group:Random tables","","","src/random-tables/RandomTableView.ts:1431","" +"RTView.fixBiggerDie","Random tables","Table detail","Use a d","keep","keep","group","group:Random tables","","","src/random-tables/RandomTableView.ts:1437","" +"RTView.fixAddRanges","Random tables","Table detail","Add roll ranges","keep","keep","group","group:Random tables","","","src/random-tables/RandomTableView.ts:1445","" +"RTView.fixRollerLink","Random tables","Table detail","Replace old roller link","keep","keep","group","group:Random tables","","","src/random-tables/RandomTableView.ts:1450","" +"RTView.descriptionCollapse","Random tables","Table detail","Collapse description (▼)","keep","keep","group","group:Random tables","","","src/random-tables/RandomTableView.ts:1569","" +"RTView.tableCollapse","Random tables","Table detail","Collapse table (▼)","keep","keep","group","group:Random tables","","","src/random-tables/RandomTableView.ts:1605","" +"RTView.entryLink","Random tables","Table detail","(result link)","keep","keep","group","group:Random tables","","","src/random-tables/RandomTableView.ts:1648","" +"RTView.entryCopy","Random tables","Table detail","Copy entry (⎘)","keep","keep","group","group:Random tables","","","src/random-tables/RandomTableView.ts:1676","" +"RTView.addEntriesEmpty","Random tables","Table detail","Add entries","keep","keep","group","group:Random tables","","","src/random-tables/RandomTableView.ts:1622","" +"RTView.copyRollLink","Random tables","Table detail","🎲 Copy link","advanced","advanced","group","group:Random tables","","","src/random-tables/RandomTableView.ts:1694","" +"RTView.roll","Random tables","Table detail","Roll","simple","simple","group","group:Random tables","","","src/random-tables/RandomTableView.ts:1708","" +"RTView.resultText","Random tables","Table detail","(roll result)","keep","keep","group","group:Random tables","","","src/random-tables/RandomTableView.ts:1721","" +"RTView.resultCopy","Random tables","Table detail","Copy","keep","keep","group","group:Random tables","","","src/random-tables/RandomTableView.ts:1727","" +"RTView.resultOpenNote","Random tables","Table detail","Open note","keep","keep","group","group:Random tables","","","src/random-tables/RandomTableView.ts:1737","" +"RTView.historyCopy","Random tables","Table detail","Copy (⎘) in Recent rolls","keep","keep","group","group:Random tables","","","src/random-tables/RandomTableView.ts:1876","" +"RTView.usedByWorkflowLink","Random tables","Table detail","(Workflows using this table)","keep","keep","group","group:Random tables","","","src/random-tables/RandomTableView.ts:1766","" +"RTView.newWorkflowWithTable","Random tables","Table detail","+ new workflow with this table","keep","keep","group","group:Random tables","","","src/random-tables/RandomTableView.ts:1779","" +"RollModal.tableSelect","Random tables","Rolling","— choose a table —","keep","keep","group","group:Random tables","","","src/random-tables/RandomTableModal.ts:116","" +"RollModal.openInRoller","Random tables","Rolling","Open in roller view","keep","keep","group","group:Random tables","","","src/random-tables/RandomTableModal.ts:125","" +"RollModal.edit","Random tables","Rolling","Edit","keep","keep","group","group:Random tables","","","src/random-tables/RandomTableModal.ts:184","" +"RollModal.roll","Random tables","Rolling","Roll","simple","simple","group","group:Random tables","","","src/random-tables/RandomTableModal.ts:135","" +"RollModal.resultText","Random tables","Rolling","(roll result)","keep","keep","group","group:Random tables","","","src/random-tables/RandomTableModal.ts:254","" +"RollModal.useResult","Random tables","Rolling","Use result","keep","keep","group","group:Random tables","","","src/random-tables/RandomTableModal.ts:262","" +"RollModal.addSectionSelect","Random tables","Rolling","Section to add the result to","keep","keep","group","group:Random tables","","","src/random-tables/RandomTableModal.ts:33","" +"RollModal.addToHex","Random tables","Rolling","Add to this hex","keep","keep","group","group:Random tables","","","src/random-tables/RandomTableModal.ts:41","" +"RollModal.copy","Random tables","Rolling","Copy","keep","keep","group","group:Random tables","","","src/random-tables/RandomTableModal.ts:280","" +"RollModal.entryCopy","Random tables","Rolling","Copy entry (⎘)","keep","keep","group","group:Random tables","","","src/random-tables/RandomTableModal.ts:350","" +"RollModal.addEntries","Random tables","Rolling","Add entries","keep","keep","group","group:Random tables","","","src/random-tables/RandomTableModal.ts:309","" +"RollModal.closeButtons","Random tables","Rolling","(modal ✕)","keep","keep","group","group:Random tables","","","src/random-tables/RandomTableModal.ts:84","" +"RollerBlock.roll","Random tables","Rolling","Roll","simple","simple","group","group:Random tables","","","src/random-tables/RollerBlock.ts:48","" +"RollerBlock.openTable","Random tables","Rolling","Open table","keep","keep","group","group:Random tables","","","src/random-tables/RollerBlock.ts:58","" +"RollerBlock.resultText","Random tables","Rolling","(roll result)","keep","keep","group","group:Random tables","","","src/random-tables/RollerBlock.ts:66","" +"RollerBlock.copy","Random tables","Rolling","Copy","keep","keep","group","group:Random tables","","","src/random-tables/RollerBlock.ts:73","" +"RollerBlock.historyCopy","Random tables","Rolling","Copy (⎘)","keep","keep","group","group:Random tables","","","src/random-tables/RollerBlock.ts:92","" +"TableEditor.importPicker","Random tables","Table editor","Search for a file to link...","keep","keep","group","group:Random tables","","","src/random-tables/RandomTableEditorModal.ts:210","" +"TableEditor.name","Random tables","Table editor","Name","keep","keep","group","group:Random tables","","","src/random-tables/RandomTableEditorModal.ts:94","" +"TableEditor.sortWeight","Random tables","Table editor","Wt ↑","keep","keep","group","group:Random tables","","","src/random-tables/RandomTableEditorModal.ts:149","" +"TableEditor.sortAlpha","Random tables","Table editor","A→z","keep","keep","group","group:Random tables","","","src/random-tables/RandomTableEditorModal.ts:166","" +"TableEditor.minusOneAll","Random tables","Table editor","-1","advanced","advanced","group","group:Random tables","","","src/random-tables/RandomTableEditorModal.ts:185","" +"TableEditor.plusOneAll","Random tables","Table editor","+1","advanced","advanced","group","group:Random tables","","","src/random-tables/RandomTableEditorModal.ts:194","" +"TableEditor.import","Random tables","Table editor","Import…","advanced","advanced","group","group:Random tables","","","src/random-tables/RandomTableEditorModal.ts:204","" +"TableEditor.rowDrag","Random tables","Table editor","Drag to reorder (⠿)","keep","keep","group","group:Random tables","","","src/random-tables/RandomTableEditorModal.ts:274","" +"TableEditor.rowResult","Random tables","Table editor","Result…","keep","keep","group","group:Random tables","","","src/random-tables/RandomTableEditorModal.ts:283","" +"TableEditor.rowWeight","Random tables","Table editor","Weight (0 = never rolled)","keep","keep","group","group:Random tables","","","src/random-tables/RandomTableEditorModal.ts:305","" +"TableEditor.rowDelete","Random tables","Table editor","Remove row (×)","keep","keep","group","group:Random tables","","","src/random-tables/RandomTableEditorModal.ts:317","" +"TableEditor.newResult","Random tables","Table editor","New result…","keep","keep","group","group:Random tables","","","src/random-tables/RandomTableEditorModal.ts:374","" +"TableEditor.newWeight","Random tables","Table editor","(new row weight)","keep","keep","group","group:Random tables","","","src/random-tables/RandomTableEditorModal.ts:380","" +"TableEditor.add","Random tables","Table editor","Add","keep","keep","group","group:Random tables","","","src/random-tables/RandomTableEditorModal.ts:387","" +"TableEditor.description","Random tables","Table editor","Description","keep","keep","group","group:Random tables","","","src/random-tables/RandomTableEditorModal.ts:405","" +"TableEditor.linkedFolder","Random tables","Table editor","Linked folder","advanced","advanced","group","group:Random tables","","","src/random-tables/RandomTableEditorModal.ts:467","" +"TableEditor.excludeRollPicker","Random tables","Table editor","Exclude from roll picker","advanced","advanced","group","group:Random tables","","","src/random-tables/RandomTableEditorModal.ts:486","" +"TableEditor.excludeEncounters","Random tables","Table editor","Exclude from encounters table","advanced","advanced","group","group:Random tables","","","src/random-tables/RandomTableEditorModal.ts:494","" +"TableEditor.closeButtons","Random tables","Table editor","Close","keep","keep","group","group:Random tables","","","src/random-tables/RandomTableEditorModal.ts:640","" +"TableRanges.addRanges","Random tables","Table editor","Add ranges (a backup is made first)","keep","keep","group","group:Random tables","","","src/random-tables/tableMaintenance.ts:260","" +"TableRanges.dontAskAgain","Random tables","Table editor","Don't ask again","keep","keep","group","group:Random tables","","","src/random-tables/tableMaintenance.ts:268","" +"TableRanges.closeButtons","Random tables","Table editor","Not now","keep","keep","group","group:Random tables","","","src/random-tables/tableMaintenance.ts:266","" +"FolderTree.openTablesView","Random tables","Table picker","🎲 Open tables view","drop","drop","group","group:Random tables","","","src/hex-map/FolderTreePickerModal.ts:85","" +"FolderTree.filter","Random tables","Table picker","Filter tables…","keep","keep","group","group:Random tables","","","src/hex-map/FolderTreePickerModal.ts:93","" +"FolderTree.folderToggles","Random tables","Table picker","(folder rows)","keep","keep","group","group:Random tables","","","src/hex-map/FolderTreePickerModal.ts:174","" +"FolderTree.newTableName","Random tables","Table picker","table-name","keep","keep","group","group:Random tables","","","src/hex-map/FolderTreePickerModal.ts:190","" +"FolderTree.createButton","Random tables","Table picker","+ create","keep","keep","group","group:Random tables","","","src/hex-map/FolderTreePickerModal.ts:194","" +"FolderTree.closeButtons","Random tables","Table picker","×","keep","keep","group","group:Random tables","","","src/hex-map/FolderTreePickerModal.ts:77","" +"RTView.workflowEdit","Workflows","Workflow detail","Edit","keep","keep","group","group:Workflows","","","src/random-tables/RandomTableView.ts:924","" +"RTView.workflowRoll","Workflows","Workflow detail","Roll workflow","keep","keep","group","group:Workflows","","","src/random-tables/RandomTableView.ts:955","" +"RTView.workflowCopyLink","Workflows","Workflow detail","🔗 Copy link","keep","keep","group","group:Workflows","","","src/random-tables/RandomTableView.ts:963","" +"RTView.workflowStepLink","Workflows","Workflow detail","(step table link)","keep","keep","group","group:Workflows","","","src/random-tables/RandomTableView.ts:1015","" +"RTView.workflowTemplateLink","Workflows","Workflow detail","(template link)","keep","keep","group","group:Workflows","","","src/random-tables/RandomTableView.ts:1053","" +"WorkflowEditor.name","Workflows","Workflow editor","Name","keep","keep","group","group:Workflows","","","src/random-tables/WorkflowEditorModal.ts:88","" +"WorkflowEditor.stepDrag","Workflows","Workflow editor","Drag to reorder (⠿)","keep","keep","group","group:Workflows","","","src/random-tables/WorkflowEditorModal.ts:343","" +"WorkflowEditor.stepFormula","Workflows","Workflow editor","E.g. 2D6+6","keep","keep","group","group:Workflows","","","src/random-tables/WorkflowEditorModal.ts:360","" +"WorkflowEditor.stepTable","Workflows","Workflow editor","— select table —","keep","keep","group","group:Workflows","","","src/random-tables/WorkflowEditorModal.ts:379","" +"WorkflowEditor.stepRolls","Workflows","Workflow editor","Number of rolls","keep","keep","group","group:Workflows","","","src/random-tables/WorkflowEditorModal.ts:420","" +"WorkflowEditor.stepLabel","Workflows","Workflow editor","Label…","keep","keep","group","group:Workflows","","","src/random-tables/WorkflowEditorModal.ts:434","" +"WorkflowEditor.stepDelete","Workflows","Workflow editor","Remove step (×)","keep","keep","group","group:Workflows","","","src/random-tables/WorkflowEditorModal.ts:454","" +"WorkflowEditor.addType","Workflows","Workflow editor","Table / Dice","keep","keep","group","group:Workflows","","","src/random-tables/WorkflowEditorModal.ts:505","" +"WorkflowEditor.addTable","Workflows","Workflow editor","— select table —","keep","keep","group","group:Workflows","","","src/random-tables/WorkflowEditorModal.ts:543","" +"WorkflowEditor.addFormula","Workflows","Workflow editor","E.g. 2D6+6","keep","keep","group","group:Workflows","","","src/random-tables/WorkflowEditorModal.ts:532","" +"WorkflowEditor.addRolls","Workflows","Workflow editor","Number of rolls","keep","keep","group","group:Workflows","","","src/random-tables/WorkflowEditorModal.ts:572","" +"WorkflowEditor.addLabel","Workflows","Workflow editor","Label (auto)…","keep","keep","group","group:Workflows","","","src/random-tables/WorkflowEditorModal.ts:578","" +"WorkflowEditor.addStep","Workflows","Workflow editor","Add step","keep","keep","group","group:Workflows","","","src/random-tables/WorkflowEditorModal.ts:585","" +"WorkflowEditor.template","Workflows","Workflow editor","Template","keep","keep","group","group:Workflows","","","src/random-tables/WorkflowEditorModal.ts:145","" +"WorkflowEditor.description","Workflows","Workflow editor","Description","keep","keep","group","group:Workflows","","","src/random-tables/WorkflowEditorModal.ts:164","" +"WorkflowEditor.resultsFolder","Workflows","Workflow editor","Results folder","keep","keep","group","group:Workflows","","","src/random-tables/WorkflowEditorModal.ts:200","" +"WorkflowEditor.export","Workflows","Workflow editor","Export…","keep","keep","group","group:Workflows","","","src/random-tables/WorkflowEditorModal.ts:690","" +"WorkflowEditor.closeButtons","Workflows","Workflow editor","Close","keep","keep","group","group:Workflows","","","src/random-tables/WorkflowEditorModal.ts:696","" +"WorkflowWizard.rollAll","Workflows","Workflow wizard","Roll all","keep","keep","group","group:Workflows","","","src/random-tables/WorkflowWizardModal.ts:148","" +"WorkflowWizard.rerollAll","Workflows","Workflow wizard","Reroll all","keep","keep","group","group:Workflows","","","src/random-tables/WorkflowWizardModal.ts:155","" +"WorkflowWizard.slotValue","Workflows","Workflow wizard","—","keep","keep","group","group:Workflows","","","src/random-tables/WorkflowWizardModal.ts:320","" +"WorkflowWizard.slotPick","Workflows","Workflow wizard","— pick —","keep","keep","group","group:Workflows","","","src/random-tables/WorkflowWizardModal.ts:337","" +"WorkflowWizard.slotRoll","Workflows","Workflow wizard","Roll / Reroll","keep","keep","group","group:Workflows","","","src/random-tables/WorkflowWizardModal.ts:359","" +"WorkflowWizard.slotSum","Workflows","Workflow wizard","sum","keep","keep","group","group:Workflows","","","src/random-tables/WorkflowWizardModal.ts:381","" +"WorkflowWizard.sumAll","Workflows","Workflow wizard","sum all","keep","keep","group","group:Workflows","","","src/random-tables/WorkflowWizardModal.ts:301","" +"WorkflowWizard.resultText","Workflows","Workflow wizard","Result","keep","keep","group","group:Workflows","","","src/random-tables/WorkflowWizardModal.ts:179","" +"WorkflowWizard.copyResult","Workflows","Workflow wizard","Copy result","keep","keep","group","group:Workflows","","","src/random-tables/WorkflowWizardModal.ts:186","" +"WorkflowWizard.addSectionSelect","Workflows","Workflow wizard","Section to add the result to","keep","keep","group","group:Workflows","","","src/random-tables/RandomTableModal.ts:33","" +"WorkflowWizard.addToHex","Workflows","Workflow wizard","Add to this hex","keep","keep","group","group:Workflows","","","src/random-tables/WorkflowWizardModal.ts:197","" +"WorkflowWizard.noteName","Workflows","Workflow wizard","Note name","keep","keep","group","group:Workflows","","","src/random-tables/WorkflowWizardModal.ts:216","" +"WorkflowWizard.resultsFolder","Workflows","Workflow wizard","Results folder","keep","keep","group","group:Workflows","","","src/random-tables/WorkflowWizardModal.ts:244","" +"WorkflowWizard.saveAsNote","Workflows","Workflow wizard","Save as note","keep","keep","group","group:Workflows","","","src/random-tables/WorkflowWizardModal.ts:254","" +"WorkflowWizard.closeButtons","Workflows","Workflow wizard","(modal ✕) / Replace confirm","keep","keep","group","group:Workflows","","","src/random-tables/WorkflowWizardModal.ts:524","" +"MapExport.mapSelect","Export","Map export","Map","keep","keep","group","group:Export","","","src/export/MapExportModal.ts:82","" +"MapExport.fileName","Export","Map export","File name","keep","keep","group","group:Export","","","src/export/MapExportModal.ts:94","" +"MapExport.showCoords","Export","Map export","Coordinates","keep","keep","group","group:Export","","","src/export/MapExportModal.ts:108","" +"MapExport.showIcons","Export","Map export","Icons","keep","keep","group","group:Export","","","src/export/MapExportModal.ts:109","" +"MapExport.showPaths","Export","Map export","Paths","keep","keep","group","group:Export","","","src/export/MapExportModal.ts:110","" +"MapExport.boldPaths","Export","Map export","Bolder paths","simple","simple","group","group:Export","","","src/export/MapExportModal.ts:111","" +"MapExport.showHexNames","Export","Map export","Hex names","keep","keep","group","group:Export","","","src/export/MapExportModal.ts:116","" +"MapExport.showTokens","Export","Map export","Tokens","keep","keep","group","group:Export","","","src/export/MapExportModal.ts:117","" +"MapExport.showLinkBadges","Export","Map export","Link badges","simple","simple","group","group:Export","","","src/export/MapExportModal.ts:118","" +"MapExport.showLegend","Export","Map export","Legend","keep","keep","group","group:Export","","","src/export/MapExportModal.ts:120","" +"MapExport.showFactionOverlay","Export","Map export","Faction overlay","simple","simple","group","group:Export","","","src/export/MapExportModal.ts:122","" +"MapExport.showRegionOverlay","Export","Map export","Region overlay","advanced","advanced","group","group:Export","","","src/export/MapExportModal.ts:124","" +"MapExport.pdfColumnsFold","Export","Map export","PDF table columns","simple","simple","group","group:Export","","","src/export/MapExportModal.ts:131","" +"MapExport.manualFold","Export","Map export","Hexcrawl manual","keep","keep","group","group:Export","","","src/export/MapExportModal.ts:137","" +"MapExport.outputSize","Export","Map export","Output size","keep","keep","group","group:Export","","","src/export/MapExportModal.ts:147","" +"MapExport.exportPng","Export","Map export","Export PNG","simple","simple","group","group:Export","","","src/export/MapExportModal.ts:239","" +"MapExport.exportPdf","Export","Map export","Export PDF with reference table","simple","simple","group","group:Export","","","src/export/MapExportModal.ts:244","" +"MapExport.exportManual","Export","Map export","Export hexcrawl manual (PDF)","simple","simple","group","group:Export","","","src/export/MapExportModal.ts:251","" +"MapExport.closeButtons","Export","Map export","×","keep","keep","group","group:Export","","","src/export/MapExportModal.ts:276","" +"MapModal.exportForm","Export","Map export","(export form)","keep","keep","group","group:Export","","","src/hex-map/MapModal.ts:226","" +"MapExport.pdfColumnName","Export","Map export: PDF table columns","Name","keep","keep","group","group:Export","","","src/export/MapExportModal.ts:134","" +"MapExport.pdfColumnTerrain","Export","Map export: PDF table columns","Terrain","keep","keep","group","group:Export","","","src/export/MapExportModal.ts:134","" +"MapExport.pdfColumnTowns","Export","Map export: PDF table columns","Towns","keep","keep","group","group:Export","","","src/export/MapExportModal.ts:134","" +"MapExport.pdfColumnDungeons","Export","Map export: PDF table columns","Dungeons","keep","keep","group","group:Export","","","src/export/MapExportModal.ts:134","" +"MapExport.pdfColumnFeatures","Export","Map export: PDF table columns","Features","keep","keep","group","group:Export","","","src/export/MapExportModal.ts:134","" +"MapExport.pdfColumnQuests","Export","Map export: PDF table columns","Quests","keep","keep","group","group:Export","","","src/export/MapExportModal.ts:134","" +"MapExport.pdfColumnFactions","Export","Map export: PDF table columns","Factions","keep","keep","group","group:Export","","","src/export/MapExportModal.ts:134","" +"MapExport.pdfColumnEncounters","Export","Map export: PDF table columns","Encounters","keep","keep","group","group:Export","","","src/export/MapExportModal.ts:134","" +"MapExport.pdfColumnDescription","Export","Map export: PDF table columns","Description","keep","keep","group","group:Export","","","src/export/MapExportModal.ts:134","" +"MapExport.playerEdition","Export","Map export: Hexcrawl manual","Player version (leave out the hidden and secret sections)","simple","simple","group","group:Export","","","src/export/MapExportModal.ts:139","" +"MapExport.manualPartLegend","Export","Map export: Hexcrawl manual","Map legend","simple","simple","group","group:Export","","","src/export/MapExportModal.ts:141","" +"MapExport.manualPartTables","Export","Map export: Hexcrawl manual","Encounter tables","simple","simple","group","group:Export","","","src/export/MapExportModal.ts:141","" +"MapExport.manualPartFactions","Export","Map export: Hexcrawl manual","Factions and regions","simple","simple","group","group:Export","","","src/export/MapExportModal.ts:141","" +"MapExport.manualPartIndex","Export","Map export: Hexcrawl manual","Index","simple","simple","group","group:Export","","","src/export/MapExportModal.ts:141","" +"HexExport.fileName","Export","Hex export","File name","keep","keep","group","group:Export","","","src/hex-map/HexExportModal.ts:55","" +"HexExport.includeGm","Export","Hex export","Include game master only sections (hidden, secret)","keep","keep","group","group:Export","","","src/hex-map/HexExportModal.ts:64","" +"HexExport.exportPdf","Export","Hex export","Export PDF","keep","keep","group","group:Export","","","src/hex-map/HexExportModal.ts:90","" +"HexExport.exportMarkdown","Export","Hex export","Export Markdown","advanced","simple","own","","advanced (group group:Export)","","src/hex-map/HexExportModal.ts:101","" +"HexExport.closeButtons","Export","Hex export","×","keep","keep","group","group:Export","","","src/hex-map/HexExportModal.ts:29","" +"WorkflowExport.fileName","Export","Workflow export","File name","keep","keep","group","group:Export","","","src/random-tables/WorkflowExportModal.ts:53","" +"WorkflowExport.sampleCount","Export","Workflow export","Number of sample outputs","keep","keep","group","group:Export","","","src/random-tables/WorkflowExportModal.ts:66","" +"WorkflowExport.includeTemplate","Export","Workflow export","Include the workflow template","keep","keep","group","group:Export","","","src/random-tables/WorkflowExportModal.ts:76","" +"WorkflowExport.includeBreakdown","Export","Workflow export","Include the per-sample rolls breakdown","keep","keep","group","group:Export","","","src/random-tables/WorkflowExportModal.ts:81","" +"WorkflowExport.exportPdf","Export","Workflow export","Export PDF","keep","keep","group","group:Export","","","src/random-tables/WorkflowExportModal.ts:104","" +"WorkflowExport.exportMarkdown","Export","Workflow export","Export Markdown","keep","keep","group","group:Export","","","src/random-tables/WorkflowExportModal.ts:112","" +"WorkflowExport.closeButtons","Export","Workflow export","×","keep","keep","group","group:Export","","","src/random-tables/WorkflowExportModal.ts:27","" +"ConfirmModal.confirm","Confirm dialogs","Confirm modal (shared)","","keep","keep","group","group:Confirm dialogs","","","src/worldgen/ConfirmModal.ts:421","" +"ConfirmModal.closeButtons","Confirm dialogs","Confirm modal (shared)","Cancel","keep","keep","group","group:Confirm dialogs","","","src/worldgen/ConfirmModal.ts:426","" +"ConfirmDelete.delete","Confirm dialogs","Confirm delete table modal","Delete","keep","keep","group","group:Confirm dialogs","","","src/random-tables/ConfirmDeleteModal.ts:451","" +"ConfirmDelete.closeButtons","Confirm dialogs","Confirm delete table modal","Cancel","keep","keep","group","group:Confirm dialogs","","","src/random-tables/ConfirmDeleteModal.ts:462","" +"GenConfirm.confirm","Confirm dialogs","Confirm dialog (Reset / Delete)","Reset / Delete","keep","keep","group","group:Confirm dialogs","","","src/worldgen/ConfirmModal.ts:22","" +"GenConfirm.closeButtons","Confirm dialogs","Confirm dialog (Reset / Delete)","Cancel","keep","keep","group","group:Confirm dialogs","","","src/worldgen/ConfirmModal.ts:27","" +"ConfirmDelete.delete_2","Confirm dialogs","Confirm delete modal","Delete","keep","keep","group","group:Confirm dialogs","","","src/random-tables/ConfirmDeleteModal.ts:19","" +"ConfirmDelete.closeButtons_2","Confirm dialogs","Confirm delete modal","Cancel","keep","keep","group","group:Confirm dialogs","","","src/random-tables/ConfirmDeleteModal.ts:30","" diff --git a/dev/ui-inventory/inputs-tags-resolved.json b/dev/ui-inventory/inputs-tags-resolved.json new file mode 100644 index 00000000..f243cf04 --- /dev/null +++ b/dev/ui-inventory/inputs-tags-resolved.json @@ -0,0 +1,17457 @@ +[ + { + "id": "Settings.rerunSetupWizard", + "group": "Settings", + "subgroup": "Setup & feature switches", + "label": "Re-run setup wizard", + "loc": "src/HexmakerSettingTab.ts:247", + "suggestion": "keep", + "choice": "keep", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Settings.featureLevel", + "group": "Settings", + "subgroup": "Setup & feature switches", + "label": "Feature level", + "loc": "src/HexmakerSettingTab.ts:894", + "suggestion": "keep", + "choice": "keep", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "", + "removed": "ee28ebd: global Simple/Advanced level, feature switches, hints and nudges removed (owner 2026-10-11)" + }, + { + "id": "Settings.featureGenerators", + "group": "Settings", + "subgroup": "Setup & feature switches", + "label": "Terrain generators", + "loc": "src/HexmakerSettingTab.ts:906", + "suggestion": "keep", + "choice": "keep", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "", + "removed": "ee28ebd: global Simple/Advanced level, feature switches, hints and nudges removed (owner 2026-10-11)" + }, + { + "id": "Settings.featureWorkflows", + "group": "Settings", + "subgroup": "Setup & feature switches", + "label": "Workflows", + "loc": "src/HexmakerSettingTab.ts:906", + "suggestion": "keep", + "choice": "keep", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "", + "removed": "ee28ebd: global Simple/Advanced level, feature switches, hints and nudges removed (owner 2026-10-11)" + }, + { + "id": "Settings.featurePalettes", + "group": "Settings", + "subgroup": "Setup & feature switches", + "label": "Custom palettes", + "loc": "src/HexmakerSettingTab.ts:906", + "suggestion": "keep", + "choice": "keep", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "", + "removed": "ee28ebd: global Simple/Advanced level, feature switches, hints and nudges removed (owner 2026-10-11)" + }, + { + "id": "Settings.featureRegions", + "group": "Settings", + "subgroup": "Setup & feature switches", + "label": "Regions and overworlds", + "loc": "src/HexmakerSettingTab.ts:906", + "suggestion": "keep", + "choice": "keep", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "", + "removed": "ee28ebd: global Simple/Advanced level, feature switches, hints and nudges removed (owner 2026-10-11)" + }, + { + "id": "Settings.showHintsAgain", + "group": "Settings", + "subgroup": "Setup & feature switches", + "label": "Show hints again", + "loc": "src/HexmakerSettingTab.ts:923", + "suggestion": "keep", + "choice": "keep", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "", + "removed": "ee28ebd: global Simple/Advanced level, feature switches, hints and nudges removed (owner 2026-10-11)" + }, + { + "id": "Settings.mapKindWorld", + "group": "Settings", + "subgroup": "Setup & feature switches", + "label": "World / fantasy overland", + "loc": "src/HexmakerSettingTab.ts:695", + "suggestion": "keep", + "choice": "keep", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Settings.mapKindSpace", + "group": "Settings", + "subgroup": "Setup & feature switches", + "label": "Space", + "loc": "src/HexmakerSettingTab.ts:695", + "suggestion": "keep", + "choice": "keep", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Settings.hexOrientation", + "group": "Settings", + "subgroup": "Look & labels", + "label": "Hex orientation", + "loc": "src/HexmakerSettingTab.ts:310", + "suggestion": "keep", + "choice": "keep", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Settings.staggerOffset", + "group": "Settings", + "subgroup": "Look & labels", + "label": "Stagger offset", + "loc": "src/HexmakerSettingTab.ts:320", + "suggestion": "advanced", + "choice": "simple", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Settings.coordPlacement", + "group": "Settings", + "subgroup": "Look & labels", + "label": "Coordinate placement", + "loc": "src/HexmakerSettingTab.ts:339", + "suggestion": "advanced", + "choice": "simple", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Settings.coordFontSize", + "group": "Settings", + "subgroup": "Look & labels", + "label": "Coordinate label size", + "loc": "src/HexmakerSettingTab.ts:349", + "suggestion": "overkill", + "choice": "simple", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Settings.coordFontFamily", + "group": "Settings", + "subgroup": "Look & labels", + "label": "Coordinate label font", + "loc": "src/HexmakerSettingTab.ts:362", + "suggestion": "overkill", + "choice": "simple", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Settings.coordFontColor", + "group": "Settings", + "subgroup": "Look & labels", + "label": "Coordinate label color", + "loc": "src/HexmakerSettingTab.ts:376", + "suggestion": "overkill", + "choice": "simple", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Settings.hexNameFont", + "group": "Settings", + "subgroup": "Look & labels", + "label": "Hex name font", + "loc": "src/HexmakerSettingTab.ts:385", + "suggestion": "overkill", + "choice": "simple", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Settings.hexNameSize", + "group": "Settings", + "subgroup": "Look & labels", + "label": "Hex name size", + "loc": "src/HexmakerSettingTab.ts:395", + "suggestion": "overkill", + "choice": "simple", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Settings.hexNameStyle", + "group": "Settings", + "subgroup": "Look & labels", + "label": "Hex name style", + "loc": "src/HexmakerSettingTab.ts:405", + "suggestion": "overkill", + "choice": "simple", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Settings.hexGap", + "group": "Settings", + "subgroup": "Look & labels", + "label": "Hex cell spacing", + "loc": "src/HexmakerSettingTab.ts:415", + "suggestion": "advanced", + "choice": "simple", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Settings.defaultTableDice", + "group": "Settings", + "subgroup": "Defaults", + "label": "Default die for new tables", + "loc": "src/HexmakerSettingTab.ts:266", + "suggestion": "advanced", + "choice": "simple", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Settings.collapseTerrain", + "group": "Settings", + "subgroup": "Defaults", + "label": "Terrain", + "loc": "src/HexmakerSettingTab.ts:989", + "suggestion": "advanced", + "choice": "simple", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Settings.collapseFeatures", + "group": "Settings", + "subgroup": "Defaults", + "label": "Features", + "loc": "src/HexmakerSettingTab.ts:996", + "suggestion": "advanced", + "choice": "simple", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Settings.collapseNotes", + "group": "Settings", + "subgroup": "Defaults", + "label": "Notes", + "loc": "src/HexmakerSettingTab.ts:1003", + "suggestion": "advanced", + "choice": "simple", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Settings.templatePath", + "group": "Settings", + "subgroup": "Defaults", + "label": "Template path", + "loc": "src/HexmakerSettingTab.ts:293", + "suggestion": "advanced", + "choice": "advanced", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Settings.defaultMap", + "group": "Settings", + "subgroup": "Defaults", + "label": "Default map", + "loc": "src/HexmakerSettingTab.ts:300", + "suggestion": "keep", + "choice": "keep", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Settings.defaultNewMapCols", + "group": "Settings", + "subgroup": "Defaults", + "label": "Default new map columns", + "loc": "src/HexmakerSettingTab.ts:428", + "suggestion": "advanced", + "choice": "advanced", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Settings.defaultNewMapRows", + "group": "Settings", + "subgroup": "Defaults", + "label": "Default new map rows", + "loc": "src/HexmakerSettingTab.ts:440", + "suggestion": "advanced", + "choice": "advanced", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Settings.defaultSubmapCols", + "group": "Settings", + "subgroup": "Defaults", + "label": "Default submap columns", + "loc": "src/HexmakerSettingTab.ts:452", + "suggestion": "advanced", + "choice": "advanced", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Settings.defaultSubmapRows", + "group": "Settings", + "subgroup": "Defaults", + "label": "Default submap rows", + "loc": "src/HexmakerSettingTab.ts:464", + "suggestion": "advanced", + "choice": "advanced", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Settings.iconsFolder", + "group": "Settings", + "subgroup": "Folders", + "label": "Custom icons folder", + "loc": "src/HexmakerSettingTab.ts:475", + "suggestion": "keep", + "choice": "keep", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Settings.worldFolder", + "group": "Settings", + "subgroup": "Folders", + "label": "World notes folder", + "loc": "src/HexmakerSettingTab.ts:527", + "suggestion": "keep", + "choice": "keep", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Settings.hexFolder", + "group": "Settings", + "subgroup": "Folders", + "label": "Hex notes folder", + "loc": "src/HexmakerSettingTab.ts:608", + "suggestion": "advanced", + "choice": "advanced", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Settings.townsFolder", + "group": "Settings", + "subgroup": "Folders", + "label": "Towns folder", + "loc": "src/HexmakerSettingTab.ts:614", + "suggestion": "advanced", + "choice": "advanced", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Settings.dungeonsFolder", + "group": "Settings", + "subgroup": "Folders", + "label": "Dungeons folder", + "loc": "src/HexmakerSettingTab.ts:620", + "suggestion": "advanced", + "choice": "advanced", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Settings.questsFolder", + "group": "Settings", + "subgroup": "Folders", + "label": "Quests folder", + "loc": "src/HexmakerSettingTab.ts:626", + "suggestion": "advanced", + "choice": "advanced", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Settings.featuresFolder", + "group": "Settings", + "subgroup": "Folders", + "label": "Features folder", + "loc": "src/HexmakerSettingTab.ts:632", + "suggestion": "advanced", + "choice": "advanced", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Settings.factionsFolder", + "group": "Settings", + "subgroup": "Folders", + "label": "Factions folder", + "loc": "src/HexmakerSettingTab.ts:638", + "suggestion": "advanced", + "choice": "advanced", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Settings.regionsFolder", + "group": "Settings", + "subgroup": "Folders", + "label": "Regions folder", + "loc": "src/HexmakerSettingTab.ts:644", + "suggestion": "advanced", + "choice": "advanced", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Settings.tablesFolder", + "group": "Settings", + "subgroup": "Folders", + "label": "Tables folder", + "loc": "src/HexmakerSettingTab.ts:650", + "suggestion": "advanced", + "choice": "advanced", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Settings.workflowsFolder", + "group": "Settings", + "subgroup": "Folders", + "label": "Workflows folder", + "loc": "src/HexmakerSettingTab.ts:656", + "suggestion": "advanced", + "choice": "advanced", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Settings.templatesFolder", + "group": "Settings", + "subgroup": "Folders", + "label": "Templates folder", + "loc": "src/HexmakerSettingTab.ts:662", + "suggestion": "advanced", + "choice": "advanced", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Settings.palettesFolder", + "group": "Settings", + "subgroup": "Folders", + "label": "Palettes folder", + "loc": "src/HexmakerSettingTab.ts:668", + "suggestion": "advanced", + "choice": "advanced", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Settings.biomesFolder", + "group": "Settings", + "subgroup": "Folders", + "label": "Biomes folder", + "loc": "src/HexmakerSettingTab.ts:674", + "suggestion": "overkill", + "choice": "overkill", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Settings.biomePoolsFolder", + "group": "Settings", + "subgroup": "Folders", + "label": "Biome pools folder", + "loc": "src/HexmakerSettingTab.ts:680", + "suggestion": "overkill", + "choice": "overkill", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Settings.worldTypesFolder", + "group": "Settings", + "subgroup": "Folders", + "label": "World types folder", + "loc": "src/HexmakerSettingTab.ts:686", + "suggestion": "overkill", + "choice": "overkill", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Settings.defaultPalette", + "group": "Settings", + "subgroup": "Palette management", + "label": "Palette for new maps", + "loc": "src/HexmakerSettingTab.ts:721", + "suggestion": "advanced", + "choice": "simple", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Settings.addDefaultPalettes", + "group": "Settings", + "subgroup": "Palette management", + "label": "Add ", + "loc": "src/HexmakerSettingTab.ts:731", + "suggestion": "advanced", + "choice": "advanced", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Settings.paletteRowName", + "group": "Settings", + "subgroup": "Palette management", + "label": "(palette name)", + "loc": "src/HexmakerSettingTab.ts:212", + "suggestion": "advanced", + "choice": "simple", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Settings.paletteRowEdit", + "group": "Settings", + "subgroup": "Palette management", + "label": "Edit", + "loc": "src/HexmakerSettingTab.ts:868", + "suggestion": "advanced", + "choice": "simple", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Settings.paletteRowOpenNote", + "group": "Settings", + "subgroup": "Palette management", + "label": "Open note", + "loc": "src/HexmakerSettingTab.ts:871", + "suggestion": "advanced", + "choice": "advanced", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Settings.paletteDelete", + "group": "Settings", + "subgroup": "Palette management", + "label": "Delete (list delete)", + "loc": "src/HexmakerSettingTab.ts:748", + "suggestion": "advanced", + "choice": "advanced", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Settings.addPalette", + "group": "Settings", + "subgroup": "Palette management", + "label": "Add palette", + "loc": "src/HexmakerSettingTab.ts:767", + "suggestion": "advanced", + "choice": "simple", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "AddPalette.presetOption", + "group": "Settings", + "subgroup": "Palette management", + "label": "", + "loc": "src/palettes/AddPaletteModal.ts:30", + "suggestion": "simple", + "choice": "simple", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "AddPalette.copyOption", + "group": "Settings", + "subgroup": "Palette management", + "label": "Copy of ", + "loc": "src/palettes/AddPaletteModal.ts:46", + "suggestion": "simple", + "choice": "simple", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "AddPalette.emptyPalette", + "group": "Settings", + "subgroup": "Palette management", + "label": "Empty palette", + "loc": "src/palettes/AddPaletteModal.ts:64", + "suggestion": "simple", + "choice": "simple", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "AddPalette.preset", + "group": "Settings", + "subgroup": "Palette management", + "label": " / (another copy)", + "loc": "src/palettes/AddPaletteModal.ts:30", + "suggestion": "keep", + "choice": "keep", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "AddPalette.closeButtons", + "group": "Settings", + "subgroup": "Palette management", + "label": "(modal ✕)", + "loc": "src/palettes/AddPaletteModal.ts:20", + "suggestion": "keep", + "choice": "keep", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Settings.generateWorldData", + "group": "Settings", + "subgroup": "Maintenance", + "label": "Generate", + "loc": "src/HexmakerSettingTab.ts:491", + "suggestion": "overkill", + "choice": "overkill", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "but note this might need to be surfaced in the case of debugging etc, we might need to point users to \"all\" if \"health\"/\"repair\" type settings hide there. " + }, + { + "id": "Settings.hexNoteProperties", + "group": "Settings", + "subgroup": "Maintenance", + "label": "Map data as hex note properties", + "loc": "src/settings/hexPropsSetting.ts", + "suggestion": "advanced", + "choice": "advanced", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "owner MG4 (2026-10-13): a setting (Advanced) to turn the hex-note property copies off, default on" + }, + { + "id": "Settings.generateFolders", + "group": "Settings", + "subgroup": "Maintenance", + "label": "Generate folders", + "loc": "src/HexmakerSettingTab.ts:534", + "suggestion": "overkill", + "choice": "overkill", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Settings.legacyCoordLabelSize", + "group": "Settings", + "subgroup": "Legacy (pre-1.13)", + "label": "Coordinate label (slider)", + "loc": "src/HexmakerSettingTab.ts:1167", + "suggestion": "overkill", + "choice": "overkill", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "simple (twin Settings.coordFontSize)", + "twinOf": "Settings.coordFontSize", + "note": "this and other stuff like it should just map to the same setting ideally. " + }, + { + "id": "Settings.legacyCoordLabelFont", + "group": "Settings", + "subgroup": "Legacy (pre-1.13)", + "label": "Coordinate label (font)", + "loc": "src/HexmakerSettingTab.ts:1178", + "suggestion": "overkill", + "choice": "overkill", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "simple (twin Settings.coordFontFamily)", + "twinOf": "Settings.coordFontFamily", + "note": "" + }, + { + "id": "Settings.legacyCoordLabelColor", + "group": "Settings", + "subgroup": "Legacy (pre-1.13)", + "label": "Coordinate label (color)", + "loc": "src/HexmakerSettingTab.ts:1193", + "suggestion": "overkill", + "choice": "overkill", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "simple (twin Settings.coordFontColor)", + "twinOf": "Settings.coordFontColor", + "note": "" + }, + { + "id": "Settings.legacyHexNameFont", + "group": "Settings", + "subgroup": "Legacy (pre-1.13)", + "label": "Hex name font (font)", + "loc": "src/HexmakerSettingTab.ts:1214", + "suggestion": "overkill", + "choice": "overkill", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "simple (twin Settings.hexNameFont)", + "twinOf": "Settings.hexNameFont", + "note": "" + }, + { + "id": "Settings.legacyHexNameSize", + "group": "Settings", + "subgroup": "Legacy (pre-1.13)", + "label": "Hex name font (size)", + "loc": "src/HexmakerSettingTab.ts:1221", + "suggestion": "overkill", + "choice": "overkill", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "simple (twin Settings.hexNameSize)", + "twinOf": "Settings.hexNameSize", + "note": "" + }, + { + "id": "Settings.legacyHexNameStyle", + "group": "Settings", + "subgroup": "Legacy (pre-1.13)", + "label": "Hex name font (style)", + "loc": "src/HexmakerSettingTab.ts:1228", + "suggestion": "overkill", + "choice": "overkill", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "simple (twin Settings.hexNameStyle)", + "twinOf": "Settings.hexNameStyle", + "note": "" + }, + { + "id": "Settings.legacyNewMapCols", + "group": "Settings", + "subgroup": "Legacy (pre-1.13)", + "label": "Default new map size (Cols)", + "loc": "src/HexmakerSettingTab.ts:1263", + "suggestion": "advanced", + "choice": "advanced", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "Settings.defaultNewMapCols", + "note": "" + }, + { + "id": "Settings.legacyNewMapRows", + "group": "Settings", + "subgroup": "Legacy (pre-1.13)", + "label": "Default new map size (Rows)", + "loc": "src/HexmakerSettingTab.ts:1272", + "suggestion": "advanced", + "choice": "advanced", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "Settings.defaultNewMapRows", + "note": "" + }, + { + "id": "Settings.legacySubmapCols", + "group": "Settings", + "subgroup": "Legacy (pre-1.13)", + "label": "Default submap size (Cols)", + "loc": "src/HexmakerSettingTab.ts:1285", + "suggestion": "advanced", + "choice": "advanced", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "Settings.defaultSubmapCols", + "note": "" + }, + { + "id": "Settings.legacySubmapRows", + "group": "Settings", + "subgroup": "Legacy (pre-1.13)", + "label": "Default submap size (Rows)", + "loc": "src/HexmakerSettingTab.ts:1294", + "suggestion": "advanced", + "choice": "advanced", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "Settings.defaultSubmapRows", + "note": "" + }, + { + "id": "Settings.legacyPaletteDeleteButton", + "group": "Settings", + "subgroup": "Legacy (pre-1.13)", + "label": "Delete", + "loc": "src/HexmakerSettingTab.ts:1742", + "suggestion": "advanced", + "choice": "simple", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "advanced (twin Settings.paletteDelete)", + "twinOf": "Settings.paletteDelete", + "note": "i think custom palettes should be simple. We want a streamlined but still customizable experience for simple, not to hide every little possible scary thing. " + }, + { + "id": "Wizard.mapKindWorld", + "group": "Setup wizard", + "subgroup": "Welcome", + "label": "World / fantasy overland", + "loc": "src/SetupWizardView.ts:243", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Setup wizard/Welcome", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Wizard.mapKindSpace", + "group": "Setup wizard", + "subgroup": "Welcome", + "label": "Space", + "loc": "src/SetupWizardView.ts:243", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Setup wizard/Welcome", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Wizard.featureLevel", + "group": "Setup wizard", + "subgroup": "Welcome", + "label": "How much do you want to start with? (Simple/Advanced)", + "loc": "src/SetupWizardView.ts:261", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Setup wizard/Welcome", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "", + "removed": "ee28ebd: global Simple/Advanced level, feature switches, hints and nudges removed (owner 2026-10-11)" + }, + { + "id": "Wizard.worldFolder", + "group": "Setup wizard", + "subgroup": "Folders", + "label": "World folder", + "loc": "src/SetupWizardView.ts:304", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Setup wizard/Folders", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Wizard.configureFoldersIndividually", + "group": "Setup wizard", + "subgroup": "Folders", + "label": "Configure each folder path individually", + "loc": "src/SetupWizardView.ts:324", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:Setup wizard/Folders", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Wizard.folder.hex", + "group": "Setup wizard", + "subgroup": "Folders", + "label": "Hex notes", + "loc": "src/SetupWizardView.ts:350", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Setup wizard/Folders", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Wizard.folder.towns", + "group": "Setup wizard", + "subgroup": "Folders", + "label": "Towns", + "loc": "src/SetupWizardView.ts:350", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Setup wizard/Folders", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Wizard.folder.dungeons", + "group": "Setup wizard", + "subgroup": "Folders", + "label": "Dungeons", + "loc": "src/SetupWizardView.ts:350", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Setup wizard/Folders", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Wizard.folder.quests", + "group": "Setup wizard", + "subgroup": "Folders", + "label": "Quests", + "loc": "src/SetupWizardView.ts:350", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Setup wizard/Folders", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Wizard.folder.features", + "group": "Setup wizard", + "subgroup": "Folders", + "label": "Features", + "loc": "src/SetupWizardView.ts:350", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Setup wizard/Folders", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Wizard.folder.factions", + "group": "Setup wizard", + "subgroup": "Folders", + "label": "Factions", + "loc": "src/SetupWizardView.ts:350", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Setup wizard/Folders", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Wizard.folder.regions", + "group": "Setup wizard", + "subgroup": "Folders", + "label": "Regions", + "loc": "src/SetupWizardView.ts:350", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Setup wizard/Folders", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Wizard.folder.tables", + "group": "Setup wizard", + "subgroup": "Folders", + "label": "Tables", + "loc": "src/SetupWizardView.ts:350", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Setup wizard/Folders", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Wizard.folder.workflows", + "group": "Setup wizard", + "subgroup": "Folders", + "label": "Workflows", + "loc": "src/SetupWizardView.ts:350", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Setup wizard/Folders", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Wizard.folder.templates", + "group": "Setup wizard", + "subgroup": "Folders", + "label": "Templates", + "loc": "src/SetupWizardView.ts:350", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Setup wizard/Folders", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Wizard.folder.icons", + "group": "Setup wizard", + "subgroup": "Folders", + "label": "Icons", + "loc": "src/SetupWizardView.ts:350", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Setup wizard/Folders", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Wizard.mapName", + "group": "Setup wizard", + "subgroup": "Map", + "label": "Map name", + "loc": "src/SetupWizardView.ts:440", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Setup wizard/Map", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Wizard.mapScale", + "group": "Setup wizard", + "subgroup": "Map", + "label": "What are you mapping?", + "loc": "src/SetupWizardView.ts", + "suggestion": "keep", + "choice": "keep", + "source": "owner", + "via": "owner 2026-10-12", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "Owner 2026-10-12: scale and generator are two choices." + }, + { + "id": "Wizard.gridCols", + "group": "Setup wizard", + "subgroup": "Map", + "label": "Grid size (columns)", + "loc": "src/SetupWizardView.ts:469", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Setup wizard/Map", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Wizard.gridRows", + "group": "Setup wizard", + "subgroup": "Map", + "label": "Grid size (rows)", + "loc": "src/SetupWizardView.ts:479", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Setup wizard/Map", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Wizard.gridSizeReset", + "group": "Setup wizard", + "subgroup": "Map", + "label": "Reset grid size", + "loc": "src/SetupWizardView.ts", + "suggestion": "keep", + "choice": "keep", + "source": "owner", + "via": "owner 2026-10-12", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "Owner 2026-10-12: grid size easy to reset." + }, + { + "id": "Wizard.hexOrientation", + "group": "Setup wizard", + "subgroup": "Map", + "label": "Hex orientation (Flat-top / Pointy-top)", + "loc": "src/SetupWizardView.ts:544", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Setup wizard/Map", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Wizard.terrainPalette", + "group": "Setup wizard", + "subgroup": "Map", + "label": "Terrain palette", + "loc": "src/SetupWizardView.ts:579", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Setup wizard/Map", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Wizard.generatorCards", + "group": "Setup wizard", + "subgroup": "Map", + "label": "Terrain (generator cards)", + "loc": "src/SetupWizardView.ts:633", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Setup wizard/Map", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Wizard.genOptWater", + "group": "Setup wizard", + "subgroup": "Map", + "label": "Water", + "loc": "src/SetupWizardView.ts:647", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:Setup wizard/Map", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Wizard.genOptClimate", + "group": "Setup wizard", + "subgroup": "Map", + "label": "Climate", + "loc": "src/SetupWizardView.ts:647", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:Setup wizard/Map", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Wizard.genOptRelief", + "group": "Setup wizard", + "subgroup": "Map", + "label": "Relief", + "loc": "src/SetupWizardView.ts:647", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:Setup wizard/Map", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Wizard.genOptSea", + "group": "Setup wizard", + "subgroup": "Map", + "label": "Sea", + "loc": "src/SetupWizardView.ts:647", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:Setup wizard/Map", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Wizard.genOptOther", + "group": "Setup wizard", + "subgroup": "Map", + "label": "(other generator options)", + "loc": "src/SetupWizardView.ts:647", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:Setup wizard/Map", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Wizard.tuning", + "group": "Setup wizard", + "subgroup": "Map", + "label": "Engine tuning sliders", + "loc": "src/SetupWizardView.ts", + "suggestion": "advanced", + "choice": "advanced", + "source": "owner", + "via": "owner 2026-10-12", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "Owner 2026-10-12: Advanced is a trimmed set of 5-10 tuning sliders." + }, + { + "id": "Wizard.makeAllRegions", + "group": "Setup wizard", + "subgroup": "Map", + "label": "Make every region now (Biomes)", + "loc": "src/overworld/scaleOverworld.ts", + "suggestion": "advanced", + "choice": "advanced", + "source": "owner", + "via": "owner 2026-10-12", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "Owner 2026-10-12: Biomes makes an overworld; making every region is off and out of the way so the step stays simple." + }, + { + "id": "Wizard.reroll", + "group": "Setup wizard", + "subgroup": "Map", + "label": "Re-roll (dice)", + "loc": "src/SetupWizardView.ts:607", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Setup wizard/Map", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Wizard.openHexMap", + "group": "Setup wizard", + "subgroup": "Done", + "label": "Open hex map", + "loc": "src/SetupWizardView.ts:841", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Setup wizard/Done", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Wizard.exploreOnOwn", + "group": "Setup wizard", + "subgroup": "Done", + "label": "I'll explore on my own", + "loc": "src/SetupWizardView.ts:847", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Setup wizard/Done", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Wizard.back", + "group": "Setup wizard", + "subgroup": "Navigation", + "label": "back", + "loc": "src/SetupWizardView.ts:943", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Setup wizard/Navigation", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Wizard.next", + "group": "Setup wizard", + "subgroup": "Navigation", + "label": "Next", + "loc": "src/SetupWizardView.ts:957", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Setup wizard/Navigation", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Wizard.remindLater", + "group": "Setup wizard", + "subgroup": "Navigation", + "label": "Remind me later", + "loc": "src/SetupWizardView.ts:967", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Setup wizard/Navigation", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Wizard.dontShowAgain", + "group": "Setup wizard", + "subgroup": "Navigation", + "label": "Don't show again", + "loc": "src/SetupWizardView.ts:975", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Setup wizard/Navigation", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Hint.turnOnFeature", + "group": "Feature hints", + "subgroup": "Inline hints", + "label": "Turn on ", + "loc": "src/advancedHints.ts:158", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Feature hints/Inline hints", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "", + "removed": "ee28ebd: global Simple/Advanced level, feature switches, hints and nudges removed (owner 2026-10-11)" + }, + { + "id": "Hint.close", + "group": "Feature hints", + "subgroup": "Inline hints", + "label": "X (Hide this hint)", + "loc": "src/advancedHints.ts:160", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Feature hints/Inline hints", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "", + "removed": "ee28ebd: global Simple/Advanced level, feature switches, hints and nudges removed (owner 2026-10-11)" + }, + { + "id": "Hints.show", + "group": "Feature hints", + "subgroup": "Inline hints", + "label": "Show", + "loc": "src/advancedHints.ts:191", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Feature hints/Inline hints", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "", + "removed": "ee28ebd: global Simple/Advanced level, feature switches, hints and nudges removed (owner 2026-10-11)" + }, + { + "id": "MoreFeatures.turnOn", + "group": "Feature hints", + "subgroup": "More options modal", + "label": "Turn on", + "loc": "src/advancedHints.ts:235", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Feature hints/More options modal", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "", + "removed": "ee28ebd: global Simple/Advanced level, feature switches, hints and nudges removed (owner 2026-10-11)" + }, + { + "id": "MoreFeatures.turnOnAll", + "group": "Feature hints", + "subgroup": "More options modal", + "label": "Turn on all advanced features", + "loc": "src/advancedHints.ts:241", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Feature hints/More options modal", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "", + "removed": "ee28ebd: global Simple/Advanced level, feature switches, hints and nudges removed (owner 2026-10-11)" + }, + { + "id": "MoreFeatures.closeButtons", + "group": "Feature hints", + "subgroup": "More options modal", + "label": "Done", + "loc": "src/advancedHints.ts:244", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Feature hints/More options modal", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "", + "removed": "ee28ebd: global Simple/Advanced level, feature switches, hints and nudges removed (owner 2026-10-11)" + }, + { + "id": "EnableFeature.turnOnOne", + "group": "Feature hints", + "subgroup": "Turn on ? modal", + "label": "Turn on ", + "loc": "src/advancedHints.ts:274", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Feature hints/Turn on ? modal", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "", + "removed": "ee28ebd: global Simple/Advanced level, feature switches, hints and nudges removed (owner 2026-10-11)" + }, + { + "id": "EnableFeature.turnOnAll", + "group": "Feature hints", + "subgroup": "Turn on ? modal", + "label": "Turn on all advanced features", + "loc": "src/advancedHints.ts:276", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Feature hints/Turn on ? modal", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "", + "removed": "ee28ebd: global Simple/Advanced level, feature switches, hints and nudges removed (owner 2026-10-11)" + }, + { + "id": "EnableFeature.closeButtons", + "group": "Feature hints", + "subgroup": "Turn on ? modal", + "label": "Not now", + "loc": "src/advancedHints.ts:277", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Feature hints/Turn on ? modal", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "", + "removed": "ee28ebd: global Simple/Advanced level, feature switches, hints and nudges removed (owner 2026-10-11)" + }, + { + "id": "Nudge.turnOnAdvanced", + "group": "Feature hints", + "subgroup": "Ready for more? modal", + "label": "Turn on advanced features", + "loc": "src/advancedHints.ts:318", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Feature hints/Ready for more? modal", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "", + "removed": "ee28ebd: global Simple/Advanced level, feature switches, hints and nudges removed (owner 2026-10-11)" + }, + { + "id": "Nudge.closeButtons", + "group": "Feature hints", + "subgroup": "Ready for more? modal", + "label": "Not now", + "loc": "src/advancedHints.ts:323", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Feature hints/Ready for more? modal", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "", + "removed": "ee28ebd: global Simple/Advanced level, feature switches, hints and nudges removed (owner 2026-10-11)" + }, + { + "id": "Nudge.dontAskAgain", + "group": "Feature hints", + "subgroup": "Ready for more? modal", + "label": "Don't ask again", + "loc": "src/advancedHints.ts:324", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Feature hints/Ready for more? modal", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "", + "removed": "ee28ebd: global Simple/Advanced level, feature switches, hints and nudges removed (owner 2026-10-11)" + }, + { + "id": "Plugin.ribbonOpenHexMap", + "group": "Commands & menus", + "subgroup": "Open views", + "label": "Open hex map", + "loc": "src/HexmakerPlugin.ts:278", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Commands & menus/Open views", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Plugin.cmd.openHexMap", + "group": "Commands & menus", + "subgroup": "Open views", + "label": "Open hex map", + "loc": "src/HexmakerPlugin.ts:281", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Commands & menus/Open views", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Plugin.cmd.openHexTable", + "group": "Commands & menus", + "subgroup": "Open views", + "label": "Open hex table", + "loc": "src/HexmakerPlugin.ts:286", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Commands & menus/Open views", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Plugin.cmd.openTerrainGenerator", + "group": "Commands & menus", + "subgroup": "Open views", + "label": "Open terrain generator", + "loc": "src/HexmakerPlugin.ts:294", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Commands & menus/Open views", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Plugin.cmd.openPaletteEditor", + "group": "Commands & menus", + "subgroup": "Open views", + "label": "Open palette editor", + "loc": "src/HexmakerPlugin.ts:299", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Commands & menus/Open views", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Plugin.cmd.editWorldTypes", + "group": "Commands & menus", + "subgroup": "Open views", + "label": "Edit world types...", + "loc": "src/HexmakerPlugin.ts:304", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Commands & menus/Open views", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Plugin.cmd.newOverworld", + "group": "Commands & menus", + "subgroup": "Open views", + "label": "New overworld...", + "loc": "src/HexmakerPlugin.ts:316", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Commands & menus/Open views", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Plugin.cmd.openRandomTables", + "group": "Commands & menus", + "subgroup": "Open views", + "label": "Open random tables", + "loc": "src/HexmakerPlugin.ts:355", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Commands & menus/Open views", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorldTypes.command", + "group": "Commands & menus", + "subgroup": "Open views", + "label": "Edit world types…", + "loc": "src/space/WorldTypesModal.ts:311", + "suggestion": "keep", + "choice": "keep", + "source": "twin", + "via": "Plugin.cmd.editWorldTypes", + "viaSuggested": false, + "overrides": "", + "twinOf": "Plugin.cmd.editWorldTypes", + "note": "" + }, + { + "id": "Plugin.cmd.mapGoUp", + "group": "Commands & menus", + "subgroup": "Map navigation commands", + "label": "Go up to parent map", + "loc": "src/HexmakerPlugin.ts:325", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Commands & menus/Map navigation commands", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Plugin.cmd.mapGoBack", + "group": "Commands & menus", + "subgroup": "Map navigation commands", + "label": "Go back to previous map", + "loc": "src/HexmakerPlugin.ts:335", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Commands & menus/Map navigation commands", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Plugin.cmd.mapGoForward", + "group": "Commands & menus", + "subgroup": "Map navigation commands", + "label": "Go forward to the next map", + "loc": "src/HexmakerPlugin.ts:345", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Commands & menus/Map navigation commands", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Plugin.cmd.addRollRanges", + "group": "Commands & menus", + "subgroup": "Maintenance commands", + "label": "Add roll ranges to tables", + "loc": "src/HexmakerPlugin.ts:363", + "suggestion": "overkill", + "choice": "overkill", + "source": "group", + "via": "group:Commands & menus/Maintenance commands", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Plugin.cmd.checkTables", + "group": "Commands & menus", + "subgroup": "Maintenance commands", + "label": "Check tables", + "loc": "src/HexmakerPlugin.ts:368", + "suggestion": "overkill", + "choice": "overkill", + "source": "group", + "via": "group:Commands & menus/Maintenance commands", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Plugin.cmd.addMapDataToHexNotes", + "group": "Commands & menus", + "subgroup": "Maintenance commands", + "label": "Add map data to this map's hex notes", + "loc": "src/HexmakerPlugin.ts:416", + "suggestion": "overkill", + "choice": "overkill", + "source": "group", + "via": "group:Commands & menus/Maintenance commands", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Plugin.cmd.updateRegionFactionMapData", + "group": "Commands & menus", + "subgroup": "Maintenance commands", + "label": "Update map data in region and faction notes", + "loc": "src/HexmakerPlugin.ts:438", + "suggestion": "overkill", + "choice": "overkill", + "source": "group", + "via": "group:Commands & menus/Maintenance commands", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Plugin.cmd.exportNotePdf", + "group": "Commands & menus", + "subgroup": "Export commands", + "label": "Export current note to PDF", + "loc": "src/HexmakerPlugin.ts:373", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:Commands & menus/Export commands", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Plugin.cmd.exportNoteMarkdown", + "group": "Commands & menus", + "subgroup": "Export commands", + "label": "Export current note to Markdown", + "loc": "src/HexmakerPlugin.ts:383", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:Commands & menus/Export commands", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Plugin.cmd.exportCurrentHex", + "group": "Commands & menus", + "subgroup": "Export commands", + "label": "Export current hex (structured PDF / Markdown)", + "loc": "src/HexmakerPlugin.ts:393", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Commands & menus/Export commands", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Plugin.cmd.exportCurrentWorkflow", + "group": "Commands & menus", + "subgroup": "Export commands", + "label": "Export current workflow with rolled samples", + "loc": "src/HexmakerPlugin.ts:403", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:Commands & menus/Export commands", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Plugin.cmd.exportCurrentMap", + "group": "Commands & menus", + "subgroup": "Export commands", + "label": "Export current map...", + "loc": "src/HexmakerPlugin.ts:456", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Commands & menus/Export commands", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Plugin.fileMenuExportPdf", + "group": "Commands & menus", + "subgroup": "Note right-click menus", + "label": "Export to PDF", + "loc": "src/HexmakerPlugin.ts:473", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:Commands & menus/Note right-click menus", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Plugin.fileMenuExportMarkdown", + "group": "Commands & menus", + "subgroup": "Note right-click menus", + "label": "Export to Markdown", + "loc": "src/HexmakerPlugin.ts:480", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:Commands & menus/Note right-click menus", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Plugin.editorMenuInsertRoller", + "group": "Commands & menus", + "subgroup": "Note right-click menus", + "label": "Insert table roller", + "loc": "src/HexmakerPlugin.ts:506", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Commands & menus/Note right-click menus", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Plugin.editorMenuInsertMapLink", + "group": "Commands & menus", + "subgroup": "Note right-click menus", + "label": "Insert map link", + "loc": "src/HexmakerPlugin.ts:523", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Commands & menus/Note right-click menus", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Plugin.insertRollerPicker", + "group": "Commands & menus", + "subgroup": "Note right-click menus", + "label": "Search for a file to link...", + "loc": "src/hex-map/FileLinkSuggestModal.ts:19", + "suggestion": "keep", + "choice": "keep", + "source": "twin", + "via": "Editor.insertTableRoller", + "viaSuggested": false, + "overrides": "", + "twinOf": "Editor.insertTableRoller", + "note": "" + }, + { + "id": "Editor.insertTableRoller", + "group": "Commands & menus", + "subgroup": "Note right-click menus", + "label": "Search for a file to link...", + "loc": "src/HexmakerPlugin.ts:512", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Commands & menus/Note right-click menus", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapToolbar.hexTableBtn", + "group": "Hex map view", + "subgroup": "Top bar", + "label": "Open hex table (⊞)", + "loc": "src/hex-map/HexMapView.ts:1473", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapToolbar.randomTablesBtn", + "group": "Hex map view", + "subgroup": "Top bar", + "label": "Open random tables (🎲)", + "loc": "src/hex-map/HexMapView.ts:1497", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapToolbar.mapSwitcher", + "group": "Hex map view", + "subgroup": "Top bar", + "label": " ▾ (Manage maps)", + "loc": "src/hex-map/HexMapView.ts:1529", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapToolbar.workModeBtn", + "group": "Hex map view", + "subgroup": "Top bar", + "label": "Mode: Play / Build / God", + "loc": "src/hex-map/HexMapView.ts:1551", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapToolbar.undo", + "group": "Hex map view", + "subgroup": "Top bar", + "label": "Undo (up to 20) ↩", + "loc": "src/hex-map/HexMapView.ts:1555", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapToolbar.redo", + "group": "Hex map view", + "subgroup": "Top bar", + "label": "Redo ↪", + "loc": "src/hex-map/HexMapView.ts:1565", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapToolbar.help", + "group": "Hex map view", + "subgroup": "Top bar", + "label": "Controls & tools (?)", + "loc": "src/hex-map/HexMapView.ts:1577", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapToolbar.drawingToolsToggle", + "group": "Hex map view", + "subgroup": "Top bar", + "label": "Drawing tools (pencil)", + "loc": "src/hex-map/HexSidePanel.ts:22", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapToolbar.layersToggle", + "group": "Hex map view", + "subgroup": "Top bar", + "label": "Map overlays (layers)", + "loc": "src/hex-map/HexSidePanel.ts:22", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapNav.breadcrumb", + "group": "Hex map view", + "subgroup": "Map navigation", + "label": "Go to (breadcrumb)", + "loc": "src/hex-map/HexMapView.ts:690", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapNav.back", + "group": "Hex map view", + "subgroup": "Map navigation", + "label": "← Back to (Alt+←)", + "loc": "src/hex-map/HexMapView.ts:723", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapNav.up", + "group": "Hex map view", + "subgroup": "Map navigation", + "label": "↑ Up to (Alt+↑)", + "loc": "src/hex-map/HexMapView.ts:723", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapNav.forward", + "group": "Hex map view", + "subgroup": "Map navigation", + "label": "→ Forward to (Alt+→)", + "loc": "src/hex-map/HexMapView.ts:723", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapNav.regionFlowerHere", + "group": "Hex map view", + "subgroup": "Map navigation", + "label": "Here: . Click to edit this region.", + "loc": "src/hex-map/HexMapView.ts:859", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapNav.regionFlowerPetal", + "group": "Hex map view", + "subgroup": "Map navigation", + "label": " petal", + "loc": "src/hex-map/HexMapView.ts:878", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapNav.regionFlowerNewLand", + "group": "Hex map view", + "subgroup": "Map navigation", + "label": "+ (new land petal)", + "loc": "src/hex-map/HexMapView.ts:878", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapNav.mapPadGo", + "group": "Hex map view", + "subgroup": "Map navigation", + "label": "D-pad neighbour map (◀▲▶▼)", + "loc": "src/hex-map/HexMapView.ts:921", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapNav.mapPadNew", + "group": "Hex map view", + "subgroup": "Map navigation", + "label": "+ (new neighbouring map)", + "loc": "src/hex-map/HexMapView.ts:921", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorkModeMenu.play", + "group": "Hex map view", + "subgroup": "Work modes", + "label": "Play: Run a game…", + "loc": "src/hex-map/HexMapView.ts:758", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorkModeMenu.build", + "group": "Hex map view", + "subgroup": "Work modes", + "label": "Build: Add to and edit the map…", + "loc": "src/hex-map/HexMapView.ts:758", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorkModeMenu.god", + "group": "Hex map view", + "subgroup": "Work modes", + "label": "God: Change anything…", + "loc": "src/hex-map/HexMapView.ts:758", + "suggestion": "advanced", + "choice": "advanced", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "Yes but ask to enable it and other things when they start poking around region/generators/etc." + }, + { + "id": "ModeBar.stop", + "group": "Hex map view", + "subgroup": "Work modes", + "label": "Stop this tool (✕)", + "loc": "src/hex-map/HexMapView.ts:1032", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "ModeBar.autoRoute", + "group": "Hex map view", + "subgroup": "Work modes", + "label": "Auto-route", + "loc": "src/hex-map/pathTool.ts:1423", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "ModeBar.crossImpassable", + "group": "Hex map view", + "subgroup": "Work modes", + "label": "Cross impassable", + "loc": "src/hex-map/pathTool.ts:1453", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "ModeBar.pathNameChip", + "group": "Hex map view", + "subgroup": "Work modes", + "label": " (Rename this path)", + "loc": "src/hex-map/pathTool.ts:1462", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "ModeBar.newPath", + "group": "Hex map view", + "subgroup": "Work modes", + "label": "New path", + "loc": "src/hex-map/pathTool.ts:1469", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "ModeBar.done", + "group": "Hex map view", + "subgroup": "Work modes", + "label": "Done", + "loc": "src/hex-map/pathTool.ts:1477", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "ModeBar.confirmIntoRegions", + "group": "Hex map view", + "subgroup": "Work modes", + "label": "Confirm into regions / Update regions", + "loc": "src/hex-map/HexMapView.ts:6253", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "DrawingPanel.centerHex", + "group": "Hex map view", + "subgroup": "Drawing tools", + "label": "Center hex", + "loc": "src/hex-map/HexMapView.ts:2023", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "DrawingPanel.terrain", + "group": "Hex map view", + "subgroup": "Drawing tools", + "label": "Terrain", + "loc": "src/hex-map/HexMapView.ts:2031", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "DrawingPanel.biome", + "group": "Hex map view", + "subgroup": "Drawing tools", + "label": "Biome", + "loc": "src/hex-map/HexMapView.ts:2043", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "DrawingPanel.icon", + "group": "Hex map view", + "subgroup": "Drawing tools", + "label": "Icon", + "loc": "src/hex-map/HexMapView.ts:2051", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "DrawingPanel.path", + "group": "Hex map view", + "subgroup": "Drawing tools", + "label": "Path", + "loc": "src/hex-map/HexMapView.ts:2062", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "DrawingPanel.linkTable", + "group": "Hex map view", + "subgroup": "Drawing tools", + "label": "Link table", + "loc": "src/hex-map/HexMapView.ts:2073", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "DrawingPanel.linkSubmap", + "group": "Hex map view", + "subgroup": "Drawing tools", + "label": "Link submap", + "loc": "src/hex-map/HexMapView.ts:2083", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "DrawingPanel.factions", + "group": "Hex map view", + "subgroup": "Drawing tools", + "label": "Factions", + "loc": "src/hex-map/HexMapView.ts:2093", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "DrawingPanel.regionAreas", + "group": "Hex map view", + "subgroup": "Drawing tools", + "label": "Region areas", + "loc": "src/hex-map/HexMapView.ts:2103", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "DrawingPanel.token", + "group": "Hex map view", + "subgroup": "Drawing tools", + "label": "Token", + "loc": "src/hex-map/HexMapView.ts:2113", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapView.tableLinkToolPicker", + "group": "Hex map view", + "subgroup": "Drawing tools", + "label": "Select table", + "loc": "src/hex-map/HexMapView.ts:2424", + "suggestion": "advanced", + "choice": "advanced", + "source": "twin", + "via": "DrawingPanel.linkTable", + "viaSuggested": false, + "overrides": "", + "twinOf": "DrawingPanel.linkTable", + "note": "" + }, + { + "id": "PainterMenu.switchTerrain", + "group": "Hex map view", + "subgroup": "Tool right-click menus", + "label": "Switch terrain", + "loc": "src/hex-map/HexMapView.ts:2145", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PainterMenu.switchIcon", + "group": "Hex map view", + "subgroup": "Tool right-click menus", + "label": "Switch icon", + "loc": "src/hex-map/HexMapView.ts:2149", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PainterMenu.switchTable", + "group": "Hex map view", + "subgroup": "Tool right-click menus", + "label": "Switch table", + "loc": "src/hex-map/HexMapView.ts:2153", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PainterMenu.switchSubmap", + "group": "Hex map view", + "subgroup": "Tool right-click menus", + "label": "Switch submap", + "loc": "src/hex-map/HexMapView.ts:2157", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PainterMenu.switchFaction", + "group": "Hex map view", + "subgroup": "Tool right-click menus", + "label": "Switch faction", + "loc": "src/hex-map/HexMapView.ts:2161", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PainterMenu.switchRegion", + "group": "Hex map view", + "subgroup": "Tool right-click menus", + "label": "Switch region", + "loc": "src/hex-map/HexMapView.ts:2165", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PainterMenu.switchPathType", + "group": "Hex map view", + "subgroup": "Tool right-click menus", + "label": "Switch path type", + "loc": "src/hex-map/HexMapView.ts:2169", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PainterMenu.switchToken", + "group": "Hex map view", + "subgroup": "Tool right-click menus", + "label": "Switch token", + "loc": "src/hex-map/HexMapView.ts:2173", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PainterMenu.switchBiome", + "group": "Hex map view", + "subgroup": "Tool right-click menus", + "label": "Switch biome", + "loc": "src/hex-map/HexMapView.ts:2176", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PainterMenu.exitTool", + "group": "Hex map view", + "subgroup": "Tool right-click menus", + "label": "Exit tool", + "loc": "src/hex-map/PainterContextMenu.ts:24", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PainterMenu.eraseToggle", + "group": "Hex map view", + "subgroup": "Tool right-click menus", + "label": "Erase mode / Paint (Link, Draw) mode", + "loc": "src/hex-map/HexMapView.ts:2146", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PainterMenu.newPath", + "group": "Hex map view", + "subgroup": "Tool right-click menus", + "label": "New path", + "loc": "src/hex-map/HexMapView.ts:2171", + "suggestion": "drop", + "choice": "drop", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PathMenu.splitHere", + "group": "Hex map view", + "subgroup": "Tool right-click menus", + "label": "Split here", + "loc": "src/hex-map/pathTool.ts:296", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PathMenu.deleteBranch", + "group": "Hex map view", + "subgroup": "Tool right-click menus", + "label": "Delete this fork / Delete main line", + "loc": "src/hex-map/pathTool.ts:297", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PathMenu.deletePath", + "group": "Hex map view", + "subgroup": "Tool right-click menus", + "label": "Delete path: ", + "loc": "src/hex-map/pathTool.ts:299", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PathMenu.rename", + "group": "Hex map view", + "subgroup": "Tool right-click menus", + "label": "Rename…", + "loc": "src/hex-map/pathTool.ts:300", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PathMenu.changeType", + "group": "Hex map view", + "subgroup": "Tool right-click menus", + "label": "Change type…", + "loc": "src/hex-map/pathTool.ts:301", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PathMenu.reverse", + "group": "Hex map view", + "subgroup": "Tool right-click menus", + "label": "Reverse", + "loc": "src/hex-map/pathTool.ts:302", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PathMenu.switchToType", + "group": "Hex map view", + "subgroup": "Tool right-click menus", + "label": "Switch to to edit ", + "loc": "src/hex-map/pathTool.ts:1075", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PathMenu.confirmIntoRegions", + "group": "Hex map view", + "subgroup": "Tool right-click menus", + "label": "Confirm into regions / Update regions", + "loc": "src/hex-map/HexMapView.ts:6274", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PathMenu.removeFromRegions", + "group": "Hex map view", + "subgroup": "Tool right-click menus", + "label": "Remove from regions", + "loc": "src/hex-map/HexMapView.ts:6274", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexMenu.center", + "group": "Hex map view", + "subgroup": "Hex right-click menu", + "label": "Center on this hex", + "loc": "src/hex-map/HexMapView.ts:4773", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexMenu.openNote", + "group": "Hex map view", + "subgroup": "Hex right-click menu", + "label": "Open note", + "loc": "src/hex-map/HexMapView.ts:4777", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexMenu.enterRegion", + "group": "Hex map view", + "subgroup": "Hex right-click menu", + "label": "Enter region: ", + "loc": "src/hex-map/HexMapView.ts:4792", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexMenu.openLocation", + "group": "Hex map view", + "subgroup": "Hex right-click menu", + "label": "Open: ", + "loc": "src/hex-map/HexMapView.ts:4795", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexMenu.locationsList", + "group": "Hex map view", + "subgroup": "Hex right-click menu", + "label": "Locations (n)…", + "loc": "src/hex-map/HexMapView.ts:4801", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexMenu.newMap", + "group": "Hex map view", + "subgroup": "Hex right-click menu", + "label": "New map from this hex…", + "loc": "src/hex-map/HexMapView.ts:4803", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexMenu.linkExistingMap", + "group": "Hex map view", + "subgroup": "Hex right-click menu", + "label": "Link existing map…", + "loc": "src/hex-map/HexMapView.ts:4804", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexMenu.manageLocations", + "group": "Hex map view", + "subgroup": "Hex right-click menu", + "label": "Manage locations…", + "loc": "src/hex-map/HexMapView.ts:4807", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexMenu.linkTable", + "group": "Hex map view", + "subgroup": "Hex right-click menu", + "label": "Link table", + "loc": "src/hex-map/HexMapView.ts:4810", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexMenu.swapHex", + "group": "Hex map view", + "subgroup": "Hex right-click menu", + "label": "Swap hex", + "loc": "src/hex-map/HexMapView.ts:4828", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexMenu.createToken", + "group": "Hex map view", + "subgroup": "Hex right-click menu", + "label": "Create token here", + "loc": "src/hex-map/HexMapView.ts:4833", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexMenu.clearTerrain", + "group": "Hex map view", + "subgroup": "Hex right-click menu", + "label": "Clear terrain", + "loc": "src/hex-map/HexMapView.ts:4839", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexMenu.removeIconOverride", + "group": "Hex map view", + "subgroup": "Hex right-click menu", + "label": "Remove icon override", + "loc": "src/hex-map/HexMapView.ts:4844", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexMenu.lockedHint", + "group": "Hex map view", + "subgroup": "Hex right-click menu", + "label": "Switch to Build to … (disabled)", + "loc": "src/hex-map/modeMenu.ts:52", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapView.linkTableMenuPicker", + "group": "Hex map view", + "subgroup": "Hex right-click menu", + "label": "Link table", + "loc": "src/hex-map/HexMapView.ts:4811", + "suggestion": "keep", + "choice": "keep", + "source": "twin", + "via": "HexMenu.linkTable", + "viaSuggested": false, + "overrides": "", + "twinOf": "HexMenu.linkTable", + "note": "" + }, + { + "id": "OverworldMenu.enterRegion", + "group": "Hex map view", + "subgroup": "Overworld menu & minimap", + "label": "Enter region: ", + "loc": "src/hex-map/HexMapView.ts:4871", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "OverworldMenu.editRegion", + "group": "Hex map view", + "subgroup": "Overworld menu & minimap", + "label": "Edit region…", + "loc": "src/hex-map/HexMapView.ts:4871", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "OverworldMenu.setBiome", + "group": "Hex map view", + "subgroup": "Overworld menu & minimap", + "label": "Set biome…", + "loc": "src/hex-map/HexMapView.ts:4871", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "OverworldMenu.center", + "group": "Hex map view", + "subgroup": "Overworld menu & minimap", + "label": "Center on this hex", + "loc": "src/hex-map/HexMapView.ts:4871", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "OverworldMenu.locations", + "group": "Hex map view", + "subgroup": "Overworld menu & minimap", + "label": "Locations (n)…", + "loc": "src/hex-map/HexMapView.ts:4871", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "OverworldMenu.createToken", + "group": "Hex map view", + "subgroup": "Overworld menu & minimap", + "label": "Create token here", + "loc": "src/hex-map/HexMapView.ts:4882", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Minimap.viewRegions", + "group": "Hex map view", + "subgroup": "Overworld menu & minimap", + "label": "View: Regions", + "loc": "src/hex-map/overworldMinimap.ts:61", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Minimap.viewBiomes", + "group": "Hex map view", + "subgroup": "Overworld menu & minimap", + "label": "View: Biomes", + "loc": "src/hex-map/overworldMinimap.ts:61", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Minimap.biomeLibrary", + "group": "Hex map view", + "subgroup": "Overworld menu & minimap", + "label": "Biomes…", + "loc": "src/hex-map/overworldMinimap.ts:71", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Minimap.toggle", + "group": "Hex map view", + "subgroup": "Overworld menu & minimap", + "label": "Show / Hide the overworld map", + "loc": "src/hex-map/overworldMinimap.ts:79", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Minimap.canvasClick", + "group": "Hex map view", + "subgroup": "Overworld menu & minimap", + "label": "Overworld minimap (click to go)", + "loc": "src/hex-map/overworldMinimap.ts:122", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "OverworldMinimap.viewRegions", + "group": "Hex map view", + "subgroup": "Overworld menu & minimap", + "label": "View: Regions", + "loc": "src/hex-map/overworldMinimap.ts:393", + "suggestion": "keep", + "choice": "keep", + "source": "twin", + "via": "Minimap.viewRegions", + "viaSuggested": false, + "overrides": "", + "twinOf": "Minimap.viewRegions", + "note": "" + }, + { + "id": "OverworldMinimap.viewBiomes", + "group": "Hex map view", + "subgroup": "Overworld menu & minimap", + "label": "View: Biomes", + "loc": "src/hex-map/overworldMinimap.ts:393", + "suggestion": "keep", + "choice": "keep", + "source": "twin", + "via": "Minimap.viewBiomes", + "viaSuggested": false, + "overrides": "", + "twinOf": "Minimap.viewBiomes", + "note": "" + }, + { + "id": "OverworldMinimap.biomes", + "group": "Hex map view", + "subgroup": "Overworld menu & minimap", + "label": "Biomes…", + "loc": "src/hex-map/overworldMinimap.ts:403", + "suggestion": "keep", + "choice": "keep", + "source": "twin", + "via": "Minimap.biomeLibrary", + "viaSuggested": false, + "overrides": "", + "twinOf": "Minimap.biomeLibrary", + "note": "" + }, + { + "id": "OverworldMinimap.toggle", + "group": "Hex map view", + "subgroup": "Overworld menu & minimap", + "label": "Show/Hide the overworld map", + "loc": "src/hex-map/overworldMinimap.ts:411", + "suggestion": "keep", + "choice": "keep", + "source": "twin", + "via": "Minimap.toggle", + "viaSuggested": false, + "overrides": "", + "twinOf": "Minimap.toggle", + "note": "" + }, + { + "id": "OverworldMinimap.canvasClick", + "group": "Hex map view", + "subgroup": "Overworld menu & minimap", + "label": "(minimap hex click)", + "loc": "src/hex-map/overworldMinimap.ts:454", + "suggestion": "keep", + "choice": "keep", + "source": "twin", + "via": "Minimap.canvasClick", + "viaSuggested": false, + "overrides": "", + "twinOf": "Minimap.canvasClick", + "note": "" + }, + { + "id": "OverworldMenu.enterRegion_2", + "group": "Hex map view", + "subgroup": "Overworld menu & minimap", + "label": "Enter region", + "loc": "src/overworld/overworldInput.ts:71", + "suggestion": "keep", + "choice": "keep", + "source": "twin", + "via": "OverworldMenu.enterRegion", + "viaSuggested": false, + "overrides": "", + "twinOf": "OverworldMenu.enterRegion", + "note": "" + }, + { + "id": "OverworldMenu.editRegion_2", + "group": "Hex map view", + "subgroup": "Overworld menu & minimap", + "label": "Edit region…", + "loc": "src/overworld/overworldInput.ts:72", + "suggestion": "keep", + "choice": "keep", + "source": "twin", + "via": "OverworldMenu.editRegion", + "viaSuggested": false, + "overrides": "", + "twinOf": "OverworldMenu.editRegion", + "note": "" + }, + { + "id": "OverworldMenu.setBiome_2", + "group": "Hex map view", + "subgroup": "Overworld menu & minimap", + "label": "Set biome…", + "loc": "src/overworld/overworldInput.ts:75", + "suggestion": "keep", + "choice": "keep", + "source": "twin", + "via": "OverworldMenu.setBiome", + "viaSuggested": false, + "overrides": "", + "twinOf": "OverworldMenu.setBiome", + "note": "" + }, + { + "id": "OverworldMenu.center_2", + "group": "Hex map view", + "subgroup": "Overworld menu & minimap", + "label": "Center on this hex", + "loc": "src/overworld/overworldInput.ts:77", + "suggestion": "keep", + "choice": "keep", + "source": "twin", + "via": "OverworldMenu.center", + "viaSuggested": false, + "overrides": "", + "twinOf": "OverworldMenu.center", + "note": "" + }, + { + "id": "OverworldMenu.locations_2", + "group": "Hex map view", + "subgroup": "Overworld menu & minimap", + "label": "Locations (n)…", + "loc": "src/overworld/overworldInput.ts:78", + "suggestion": "keep", + "choice": "keep", + "source": "twin", + "via": "OverworldMenu.locations", + "viaSuggested": false, + "overrides": "", + "twinOf": "OverworldMenu.locations", + "note": "" + }, + { + "id": "TokenMenu.info", + "group": "Hex map view", + "subgroup": "Token right-click menu", + "label": "Token info", + "loc": "src/hex-map/HexMapView.ts:8010", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TokenMenu.edit", + "group": "Hex map view", + "subgroup": "Token right-click menu", + "label": "Edit token", + "loc": "src/hex-map/HexMapView.ts:8011", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TokenMenu.openNote", + "group": "Hex map view", + "subgroup": "Token right-click menu", + "label": "Open note", + "loc": "src/hex-map/HexMapView.ts:8012", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TokenMenu.remove", + "group": "Hex map view", + "subgroup": "Token right-click menu", + "label": "Remove token", + "loc": "src/hex-map/HexMapView.ts:8017", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "LayersMenu.coordinates", + "group": "Hex map view", + "subgroup": "Layers panel", + "label": "Coordinates", + "loc": "src/hex-map/HexSidePanel.ts:105", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "LayersMenu.hexNames", + "group": "Hex map view", + "subgroup": "Layers panel", + "label": "Hex names", + "loc": "src/hex-map/HexSidePanel.ts:106", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "LayersMenu.tokenNames", + "group": "Hex map view", + "subgroup": "Layers panel", + "label": "Token names", + "loc": "src/hex-map/HexSidePanel.ts:107", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "LayersMenu.nameFontBtn", + "group": "Hex map view", + "subgroup": "Layers panel", + "label": "Aa (Hex name font)", + "loc": "src/hex-map/HexSidePanel.ts:319", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "LayersMenu.nameFontFamily", + "group": "Hex map view", + "subgroup": "Layers panel", + "label": "Font", + "loc": "src/hex-map/HexSidePanel.ts:337", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "LayersMenu.nameSize", + "group": "Hex map view", + "subgroup": "Layers panel", + "label": "Name size S / M / L / XL", + "loc": "src/hex-map/HexSidePanel.ts:347", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "LayersMenu.nameBold", + "group": "Hex map view", + "subgroup": "Layers panel", + "label": "Bold (B)", + "loc": "src/hex-map/HexSidePanel.ts:371", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "LayersMenu.nameItalic", + "group": "Hex map view", + "subgroup": "Layers panel", + "label": "Italic (I)", + "loc": "src/hex-map/HexSidePanel.ts:372", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "LayersMenu.nameFontReset", + "group": "Hex map view", + "subgroup": "Layers panel", + "label": "Use the default name font (settings)", + "loc": "src/hex-map/HexSidePanel.ts:374", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "LayersMenu.terrainIcons", + "group": "Hex map view", + "subgroup": "Layers panel", + "label": "Show terrain icons", + "loc": "src/hex-map/HexSidePanel.ts:102", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "LayersMenu.iconOverrides", + "group": "Hex map view", + "subgroup": "Layers panel", + "label": "Show icon overrides", + "loc": "src/hex-map/HexSidePanel.ts:103", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "LayersMenu.paths", + "group": "Hex map view", + "subgroup": "Layers panel", + "label": "Show paths", + "loc": "src/hex-map/HexSidePanel.ts:104", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "LayersMenu.tokens", + "group": "Hex map view", + "subgroup": "Layers panel", + "label": "Show tokens", + "loc": "src/hex-map/HexSidePanel.ts:153", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "LayersMenu.factionOverlay", + "group": "Hex map view", + "subgroup": "Layers panel", + "label": "Show faction overlay", + "loc": "src/hex-map/HexSidePanel.ts:178", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "LayersMenu.regionOverlay", + "group": "Hex map view", + "subgroup": "Layers panel", + "label": "Show region overlay", + "loc": "src/hex-map/HexSidePanel.ts:202", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "LayersMenu.gmLayer", + "group": "Hex map view", + "subgroup": "Layers panel", + "label": "Show GM layer", + "loc": "src/hex-map/HexSidePanel.ts:226", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "LayersMenu.linkBadges", + "group": "Hex map view", + "subgroup": "Layers panel", + "label": "Show link badges", + "loc": "src/hex-map/HexSidePanel.ts:430", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "LayersMenu.badgeSize", + "group": "Hex map view", + "subgroup": "Layers panel", + "label": "Badge size S / M / L", + "loc": "src/hex-map/HexSidePanel.ts:436", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "LayersMenu.badgeTypesMore", + "group": "Hex map view", + "subgroup": "Layers panel", + "label": "Pick badge types (▸)", + "loc": "src/hex-map/HexSidePanel.ts:451", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "LayersMenu.badgeTowns", + "group": "Hex map view", + "subgroup": "Layers panel", + "label": "Towns badges", + "loc": "src/hex-map/HexSidePanel.ts:484", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "LayersMenu.badgeDungeons", + "group": "Hex map view", + "subgroup": "Layers panel", + "label": "Dungeons badges", + "loc": "src/hex-map/HexSidePanel.ts:484", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "LayersMenu.badgeFeatures", + "group": "Hex map view", + "subgroup": "Layers panel", + "label": "Features badges", + "loc": "src/hex-map/HexSidePanel.ts:484", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "LayersMenu.badgeQuests", + "group": "Hex map view", + "subgroup": "Layers panel", + "label": "Quests badges", + "loc": "src/hex-map/HexSidePanel.ts:484", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "LayersMenu.badgeFactions", + "group": "Hex map view", + "subgroup": "Layers panel", + "label": "Factions badges", + "loc": "src/hex-map/HexSidePanel.ts:484", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "LayersMenu.legend", + "group": "Hex map view", + "subgroup": "Layers panel", + "label": "Show legend", + "loc": "src/hex-map/HexSidePanel.ts:251", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Legend.size", + "group": "Hex map view", + "subgroup": "Legend, grid edges & notices", + "label": "Legend size S / M / L", + "loc": "src/hex-map/terrainLegend.ts:160", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Legend.minimize", + "group": "Hex map view", + "subgroup": "Legend, grid edges & notices", + "label": "Minimize (–)", + "loc": "src/hex-map/terrainLegend.ts:171", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Legend.hide", + "group": "Hex map view", + "subgroup": "Legend, grid edges & notices", + "label": "Hide legend (×)", + "loc": "src/hex-map/terrainLegend.ts:183", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Legend.expandChip", + "group": "Hex map view", + "subgroup": "Legend, grid edges & notices", + "label": "Legend (Show the legend)", + "loc": "src/hex-map/terrainLegend.ts:145", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapGrid.expand", + "group": "Hex map view", + "subgroup": "Legend, grid edges & notices", + "label": "+ (grow edge, 4 sides)", + "loc": "src/hex-map/HexMapView.ts:1961", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapGrid.shrink", + "group": "Hex map view", + "subgroup": "Legend, grid edges & notices", + "label": "− / OK? (shrink edge, 4 sides)", + "loc": "src/hex-map/HexMapView.ts:1966", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PathTool.rerouteInstead", + "group": "Hex map view", + "subgroup": "Legend, grid edges & notices", + "label": "Reroute instead", + "loc": "src/paths/routePins.ts:196", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapView.calibrationDone", + "group": "Hex map view", + "subgroup": "Mouse & keyboard", + "label": "Done calibrating (✓)", + "loc": "src/hex-map/HexMapView.ts:3680", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapView.missingRestore", + "group": "Hex map view", + "subgroup": "Mouse & keyboard", + "label": "Restore", + "loc": "src/hex-map/MapModal.ts:46", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapView.missingRemove", + "group": "Hex map view", + "subgroup": "Mouse & keyboard", + "label": "Remove", + "loc": "src/hex-map/MapModal.ts:52", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapView.hexClick", + "group": "Hex map view", + "subgroup": "Mouse & keyboard", + "label": "Click hex", + "loc": "src/hex-map/HexMapView.ts:4897", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapView.hexCtrlClick", + "group": "Hex map view", + "subgroup": "Mouse & keyboard", + "label": "Ctrl/Cmd+click hex", + "loc": "src/hex-map/HexMapView.ts:4953", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapView.hexCtrlShiftClick", + "group": "Hex map view", + "subgroup": "Mouse & keyboard", + "label": "Ctrl/Cmd+Shift+click hex", + "loc": "src/hex-map/HexMapView.ts:4957", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapView.hexRightClick", + "group": "Hex map view", + "subgroup": "Mouse & keyboard", + "label": "Right-click hex", + "loc": "src/hex-map/HexMapView.ts:1451", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapView.locationBadge", + "group": "Hex map view", + "subgroup": "Mouse & keyboard", + "label": "Location badge (Enter location / Locations)", + "loc": "src/hex-map/HexMapView.ts:4423", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapView.regionShadowHex", + "group": "Hex map view", + "subgroup": "Mouse & keyboard", + "label": "Neighbouring region hex (shadow)", + "loc": "src/hex-map/HexMapView.ts:4638", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapView.overworldClick", + "group": "Hex map view", + "subgroup": "Mouse & keyboard", + "label": "Click overworld hex", + "loc": "src/hex-map/HexMapView.ts:4936", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapView.tokenDrag", + "group": "Hex map view", + "subgroup": "Mouse & keyboard", + "label": "Drag token", + "loc": "src/hex-map/HexMapView.ts:7853", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapView.tokenRightClick", + "group": "Hex map view", + "subgroup": "Mouse & keyboard", + "label": "Right-click token", + "loc": "src/hex-map/HexMapView.ts:7840", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapView.wheelZoom", + "group": "Hex map view", + "subgroup": "Mouse & keyboard", + "label": "Mouse wheel", + "loc": "src/hex-map/HexMapView.ts:1100", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapView.dragPan", + "group": "Hex map view", + "subgroup": "Mouse & keyboard", + "label": "Drag (left/middle/right)", + "loc": "src/hex-map/HexMapView.ts:1147", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapView.dblRightClickExit", + "group": "Hex map view", + "subgroup": "Mouse & keyboard", + "label": "Double right-click", + "loc": "src/hex-map/HexMapView.ts:1395", + "suggestion": "drop", + "choice": "drop", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapView.dblClickOffGridExit", + "group": "Hex map view", + "subgroup": "Mouse & keyboard", + "label": "Double-click off the grid", + "loc": "src/hex-map/HexMapView.ts:1458", + "suggestion": "drop", + "choice": "drop", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapView.gmIconRightClick", + "group": "Hex map view", + "subgroup": "Mouse & keyboard", + "label": "Right-click hex (GM icon paint)", + "loc": "src/hex-map/HexMapView.ts:1408", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PathTool.anchorRightClick", + "group": "Hex map view", + "subgroup": "Mouse & keyboard", + "label": "Right-click path anchor", + "loc": "src/hex-map/pathTool.ts:1063", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PathTool.anchorDrag", + "group": "Hex map view", + "subgroup": "Mouse & keyboard", + "label": "Drag path point/line", + "loc": "src/hex-map/HexMapView.ts:1270", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Keys.escape", + "group": "Hex map view", + "subgroup": "Mouse & keyboard", + "label": "Esc", + "loc": "src/hex-map/HexMapView.ts:1043", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Keys.undoRedo", + "group": "Hex map view", + "subgroup": "Mouse & keyboard", + "label": "Ctrl/Cmd+Z, Ctrl/Cmd+Shift+Z", + "loc": "src/hex-map/HexMapView.ts:990", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Keys.altArrows", + "group": "Hex map view", + "subgroup": "Mouse & keyboard", + "label": "Alt+← / Alt+↑ / Alt+→", + "loc": "src/hex-map/HexMapView.ts:1001", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Keys.deleteAnchor", + "group": "Hex map view", + "subgroup": "Mouse & keyboard", + "label": "Backspace / Delete", + "loc": "src/hex-map/HexMapView.ts:1055", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Keys.altClickNewPath", + "group": "Hex map view", + "subgroup": "Mouse & keyboard", + "label": "Alt+click", + "loc": "src/hex-map/pathTool.ts:1472", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Keys.calibrationArrows", + "group": "Hex map view", + "subgroup": "Mouse & keyboard", + "label": "Arrow keys (Shift = 10px)", + "loc": "src/hex-map/HexMapView.ts:3605", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.centerOnHex", + "group": "Hex editor", + "subgroup": "Header", + "label": "⌖", + "loc": "src/hex-map/HexEditorModal.ts:196", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.openNote", + "group": "Hex editor", + "subgroup": "Header", + "label": "Open note", + "loc": "src/hex-map/HexEditorModal.ts:216", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.exportHex", + "group": "Hex editor", + "subgroup": "Header", + "label": "Export", + "loc": "src/hex-map/HexEditorModal.ts:224", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.runWorkflow", + "group": "Hex editor", + "subgroup": "Header", + "label": "Run workflow", + "loc": "src/hex-map/HexEditorModal.ts:236", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.workflowPicker", + "group": "Hex editor", + "subgroup": "Header", + "label": "Pick a workflow to run…", + "loc": "src/hex-map/HexEditorModal.ts:1660", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.neighborTile", + "group": "Hex editor", + "subgroup": "Header", + "label": "Neighbour hex tiles", + "loc": "src/hex-map/HexEditorModal.ts:578", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.neighborCrossRegion", + "group": "Hex editor", + "subgroup": "Header", + "label": "Neighbour tile (other region)", + "loc": "src/hex-map/HexEditorModal.ts:600", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.neighborWalkOverworld", + "group": "Hex editor", + "subgroup": "Header", + "label": "Neighbour tile (new region)", + "loc": "src/hex-map/HexEditorModal.ts:621", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.neighborNewLand", + "group": "Hex editor", + "subgroup": "Header", + "label": "Neighbour tile (new land)", + "loc": "src/hex-map/HexEditorModal.ts:636", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.neighborCentreDot", + "group": "Hex editor", + "subgroup": "Header", + "label": "Centre dot", + "loc": "src/hex-map/HexEditorModal.ts:660", + "suggestion": "drop", + "choice": "drop", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "do these actually link directly to a given hex? If a map is big enough I could see wanting to let a note direct-link a centered view on it, if this is the case then we should consider keeping this, maybe even as simple. " + }, + { + "id": "HexEditor.nameInput", + "group": "Hex editor", + "subgroup": "Header", + "label": "Name", + "loc": "src/hex-map/HexEditorModal.ts:449", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.mapsChip", + "group": "Hex editor", + "subgroup": "Header", + "label": "Maps: region/location chips", + "loc": "src/hex-map/HexEditorModal.ts:694", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.mapsAdd", + "group": "Hex editor", + "subgroup": "Header", + "label": "+ (Maps)", + "loc": "src/hex-map/HexEditorModal.ts:709", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.mapsNewMap", + "group": "Hex editor", + "subgroup": "Header", + "label": "New map from this hex…", + "loc": "src/hex-map/HexEditorModal.ts:713", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.mapsLinkExisting", + "group": "Hex editor", + "subgroup": "Header", + "label": "Link existing map…", + "loc": "src/hex-map/HexEditorModal.ts:715", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.mapsManageLocations", + "group": "Hex editor", + "subgroup": "Header", + "label": "Manage locations (N)…", + "loc": "src/hex-map/HexEditorModal.ts:718", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.closeButtons", + "group": "Hex editor", + "subgroup": "Header", + "label": "Close (×)", + "loc": "src/hex-map/HexEditorModal.ts:428", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.collapseTerrain", + "group": "Hex editor", + "subgroup": "Section headers", + "label": "Terrain ▶/▼", + "loc": "src/hex-map/HexEditorModal.ts:276", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor/Section headers", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.collapseNotes", + "group": "Hex editor", + "subgroup": "Section headers", + "label": "Notes ▶/▼", + "loc": "src/hex-map/HexEditorModal.ts:298", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor/Section headers", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.collapseLinked", + "group": "Hex editor", + "subgroup": "Section headers", + "label": "Linked notes ▶/▼", + "loc": "src/hex-map/HexEditorModal.ts:356", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor/Section headers", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.collapseIcons", + "group": "Hex editor", + "subgroup": "Section headers", + "label": "Icons ▶/▼", + "loc": "src/hex-map/HexEditorModal.ts:414", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor/Section headers", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.terrainChangeHint", + "group": "Hex editor", + "subgroup": "Terrain", + "label": "▸ change", + "loc": "src/hex-map/HexEditorModal.ts:286", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.terrainFilter", + "group": "Hex editor", + "subgroup": "Terrain", + "label": "Filter terrains…", + "loc": "src/hex-map/HexEditorModal.ts:815", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.terrainPicker", + "group": "Hex editor", + "subgroup": "Terrain", + "label": "Terrain swatches", + "loc": "src/hex-map/HexEditorModal.ts:860", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.terrainClear", + "group": "Hex editor", + "subgroup": "Terrain", + "label": "Clear", + "loc": "src/hex-map/HexEditorModal.ts:846", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.bodyFieldUseOnMap", + "group": "Hex editor", + "subgroup": "Terrain", + "label": "Use \"X\" on the map", + "loc": "src/hex-map/HexEditorModal.ts:1493", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.bodyFieldUpdateNote", + "group": "Hex editor", + "subgroup": "Terrain", + "label": "Change the note to \"X\"", + "loc": "src/hex-map/HexEditorModal.ts:1510", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.description", + "group": "Hex editor", + "subgroup": "Notes", + "label": "Description", + "loc": "src/hex-map/HexEditorModal.ts:1575", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.descriptionRoll", + "group": "Hex editor", + "subgroup": "Notes", + "label": "📖", + "loc": "src/hex-map/HexEditorModal.ts:1584", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.landmark", + "group": "Hex editor", + "subgroup": "Notes", + "label": "Landmark", + "loc": "src/hex-map/HexEditorModal.ts:1575", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.landmarkRoll", + "group": "Hex editor", + "subgroup": "Notes", + "label": "📖", + "loc": "src/hex-map/HexEditorModal.ts:1584", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.hidden", + "group": "Hex editor", + "subgroup": "Notes", + "label": "Hidden", + "loc": "src/hex-map/HexEditorModal.ts:1575", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.hiddenRoll", + "group": "Hex editor", + "subgroup": "Notes", + "label": "📖", + "loc": "src/hex-map/HexEditorModal.ts:1584", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.secret", + "group": "Hex editor", + "subgroup": "Notes", + "label": "Secret", + "loc": "src/hex-map/HexEditorModal.ts:1575", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.secretRoll", + "group": "Hex editor", + "subgroup": "Notes", + "label": "📖", + "loc": "src/hex-map/HexEditorModal.ts:1584", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.gmLayerShow", + "group": "Hex editor", + "subgroup": "Notes", + "label": "Show them", + "loc": "src/hex-map/HexEditorModal.ts:319", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.rolledSectionsFold", + "group": "Hex editor", + "subgroup": "Notes", + "label": "Weather · Hooks & Rumors", + "loc": "src/hex-map/HexEditorModal.ts:329", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.weather", + "group": "Hex editor", + "subgroup": "Notes", + "label": "Weather", + "loc": "src/hex-map/HexEditorModal.ts:332", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.weatherRoll", + "group": "Hex editor", + "subgroup": "Notes", + "label": "🎲 (Weather)", + "loc": "src/hex-map/HexEditorModal.ts:1710", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.weatherSource", + "group": "Hex editor", + "subgroup": "Notes", + "label": "⋯ (Weather)", + "loc": "src/hex-map/HexEditorModal.ts:1711", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.hooks", + "group": "Hex editor", + "subgroup": "Notes", + "label": "Hooks & Rumors", + "loc": "src/hex-map/HexEditorModal.ts:332", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.hooksRoll", + "group": "Hex editor", + "subgroup": "Notes", + "label": "🎲 (Hooks & Rumors)", + "loc": "src/hex-map/HexEditorModal.ts:1710", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.hooksSource", + "group": "Hex editor", + "subgroup": "Notes", + "label": "⋯ (Hooks & Rumors)", + "loc": "src/hex-map/HexEditorModal.ts:1711", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.rolledSetMapTable", + "group": "Hex editor", + "subgroup": "Notes", + "label": "Set/Change the map's … table…", + "loc": "src/hex-map/HexEditorModal.ts:1760", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.rolledSetHexTable", + "group": "Hex editor", + "subgroup": "Notes", + "label": "Use a different table for this hex…", + "loc": "src/hex-map/HexEditorModal.ts:1761", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.rolledUseMapTable", + "group": "Hex editor", + "subgroup": "Notes", + "label": "Use the map's table on this hex", + "loc": "src/hex-map/HexEditorModal.ts:1763", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.rolledTablePicker", + "group": "Hex editor", + "subgroup": "Notes", + "label": "Weather/rumour table chooser", + "loc": "src/hex-map/HexEditorModal.ts:1722", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.moreInNoteFold", + "group": "Hex editor", + "subgroup": "Notes", + "label": "More in this note (N)", + "loc": "src/hex-map/HexEditorModal.ts:345", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.moreInNoteText", + "group": "Hex editor", + "subgroup": "Notes", + "label": " (other sections)", + "loc": "src/hex-map/HexEditorModal.ts:348", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.sectionTablePicker", + "group": "Hex editor", + "subgroup": "Notes", + "label": "(set map's / this hex's table)", + "loc": "src/hex-map/HexEditorModal.ts:1722", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.encountersLink", + "group": "Hex editor", + "subgroup": "Linked notes", + "label": "Encounters Table", + "loc": "src/hex-map/HexEditorModal.ts:1144", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.encountersShowAll", + "group": "Hex editor", + "subgroup": "Linked notes", + "label": "▾", + "loc": "src/hex-map/HexEditorModal.ts:1151", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.encountersCreate", + "group": "Hex editor", + "subgroup": "Linked notes", + "label": "+ Create \"…\"", + "loc": "src/hex-map/HexEditorModal.ts:1272", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.encountersOpenLink", + "group": "Hex editor", + "subgroup": "Linked notes", + "label": "", + "loc": "src/hex-map/HexEditorModal.ts:1440", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.encountersRemove", + "group": "Hex editor", + "subgroup": "Linked notes", + "label": "×", + "loc": "src/hex-map/HexEditorModal.ts:1459", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.townsLink", + "group": "Hex editor", + "subgroup": "Linked notes", + "label": "Towns", + "loc": "src/hex-map/HexEditorModal.ts:1144", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.townsShowAll", + "group": "Hex editor", + "subgroup": "Linked notes", + "label": "▾", + "loc": "src/hex-map/HexEditorModal.ts:1151", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.townsCreate", + "group": "Hex editor", + "subgroup": "Linked notes", + "label": "+ Create \"…\"", + "loc": "src/hex-map/HexEditorModal.ts:1272", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.townsOpenLink", + "group": "Hex editor", + "subgroup": "Linked notes", + "label": "", + "loc": "src/hex-map/HexEditorModal.ts:1440", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.townsRemove", + "group": "Hex editor", + "subgroup": "Linked notes", + "label": "×", + "loc": "src/hex-map/HexEditorModal.ts:1459", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.dungeonsLink", + "group": "Hex editor", + "subgroup": "Linked notes", + "label": "Dungeons", + "loc": "src/hex-map/HexEditorModal.ts:1144", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.dungeonsShowAll", + "group": "Hex editor", + "subgroup": "Linked notes", + "label": "▾", + "loc": "src/hex-map/HexEditorModal.ts:1151", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.dungeonsCreate", + "group": "Hex editor", + "subgroup": "Linked notes", + "label": "+ Create \"…\"", + "loc": "src/hex-map/HexEditorModal.ts:1272", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.dungeonsOpenLink", + "group": "Hex editor", + "subgroup": "Linked notes", + "label": "", + "loc": "src/hex-map/HexEditorModal.ts:1440", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.dungeonsRemove", + "group": "Hex editor", + "subgroup": "Linked notes", + "label": "×", + "loc": "src/hex-map/HexEditorModal.ts:1459", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.questsLink", + "group": "Hex editor", + "subgroup": "Linked notes", + "label": "Quests", + "loc": "src/hex-map/HexEditorModal.ts:1144", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.questsShowAll", + "group": "Hex editor", + "subgroup": "Linked notes", + "label": "▾", + "loc": "src/hex-map/HexEditorModal.ts:1151", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.questsCreate", + "group": "Hex editor", + "subgroup": "Linked notes", + "label": "+ Create \"…\"", + "loc": "src/hex-map/HexEditorModal.ts:1272", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.questsOpenLink", + "group": "Hex editor", + "subgroup": "Linked notes", + "label": "", + "loc": "src/hex-map/HexEditorModal.ts:1440", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.questsRemove", + "group": "Hex editor", + "subgroup": "Linked notes", + "label": "×", + "loc": "src/hex-map/HexEditorModal.ts:1459", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.factionsLink", + "group": "Hex editor", + "subgroup": "Linked notes", + "label": "Factions", + "loc": "src/hex-map/HexEditorModal.ts:1144", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.factionsShowAll", + "group": "Hex editor", + "subgroup": "Linked notes", + "label": "▾", + "loc": "src/hex-map/HexEditorModal.ts:1151", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.factionsCreate", + "group": "Hex editor", + "subgroup": "Linked notes", + "label": "+ Create \"…\"", + "loc": "src/hex-map/HexEditorModal.ts:1272", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.factionsOpenLink", + "group": "Hex editor", + "subgroup": "Linked notes", + "label": "", + "loc": "src/hex-map/HexEditorModal.ts:1440", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.factionsRemove", + "group": "Hex editor", + "subgroup": "Linked notes", + "label": "×", + "loc": "src/hex-map/HexEditorModal.ts:1459", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.featuresLink", + "group": "Hex editor", + "subgroup": "Linked notes", + "label": "Features", + "loc": "src/hex-map/HexEditorModal.ts:1144", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.featuresShowAll", + "group": "Hex editor", + "subgroup": "Linked notes", + "label": "▾", + "loc": "src/hex-map/HexEditorModal.ts:1151", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.featuresCreate", + "group": "Hex editor", + "subgroup": "Linked notes", + "label": "+ Create \"…\"", + "loc": "src/hex-map/HexEditorModal.ts:1272", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.featuresOpenLink", + "group": "Hex editor", + "subgroup": "Linked notes", + "label": "", + "loc": "src/hex-map/HexEditorModal.ts:1440", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.featuresRemove", + "group": "Hex editor", + "subgroup": "Linked notes", + "label": "×", + "loc": "src/hex-map/HexEditorModal.ts:1459", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.encountersRoll", + "group": "Hex editor", + "subgroup": "Linked notes", + "label": "🎲 (Encounters)", + "loc": "src/hex-map/HexEditorModal.ts:1450", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.iconOverride", + "group": "Hex editor", + "subgroup": "Icons", + "label": "Icon override", + "loc": "src/hex-map/HexEditorModal.ts:922", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.iconTerrainDefault", + "group": "Hex editor", + "subgroup": "Icons", + "label": "— terrain default —", + "loc": "src/hex-map/HexEditorModal.ts:926", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.iconPackTabs", + "group": "Hex editor", + "subgroup": "Icons", + "label": "All / / Custom tabs", + "loc": "src/HexmakerModal.ts:108", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.iconPlaceKinds", + "group": "Hex editor", + "subgroup": "Icons", + "label": "All places / Settlements / Castles…", + "loc": "src/HexmakerModal.ts:133", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.gmIcons", + "group": "Hex editor", + "subgroup": "Icons", + "label": "Game master icons", + "loc": "src/hex-map/HexEditorModal.ts:941", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.gmIconsRemoveOne", + "group": "Hex editor", + "subgroup": "Icons", + "label": "Right-click icon", + "loc": "src/hex-map/HexEditorModal.ts:1037", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.gmIconsClearAll", + "group": "Hex editor", + "subgroup": "Icons", + "label": "— clear all —", + "loc": "src/hex-map/HexEditorModal.ts:1050", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.gmIconFilterSearch", + "group": "Hex editor", + "subgroup": "Icons", + "label": "Filter icons… (GM)", + "loc": "src/HexmakerModal.ts:45", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.gmIconPackTabs", + "group": "Hex editor", + "subgroup": "Icons", + "label": "All / / Custom tabs (GM)", + "loc": "src/HexmakerModal.ts:108", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.gmIconPlaceKinds", + "group": "Hex editor", + "subgroup": "Icons", + "label": "Place kind chips (GM)", + "loc": "src/HexmakerModal.ts:133", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexTable.refresh", + "group": "Hex table", + "subgroup": "Toolbar", + "label": "Refresh", + "loc": "src/hex-table/HexTableView.ts:143", + "suggestion": "overkill", + "choice": "overkill", + "source": "group", + "via": "group:Hex table", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexTable.xMin", + "group": "Hex table", + "subgroup": "Toolbar", + "label": "X: Min", + "loc": "src/hex-table/HexTableView.ts:153", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:Hex table", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexTable.xMax", + "group": "Hex table", + "subgroup": "Toolbar", + "label": "X: Max", + "loc": "src/hex-table/HexTableView.ts:164", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:Hex table", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexTable.yMin", + "group": "Hex table", + "subgroup": "Toolbar", + "label": "Y: Min", + "loc": "src/hex-table/HexTableView.ts:179", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:Hex table", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexTable.yMax", + "group": "Hex table", + "subgroup": "Toolbar", + "label": "Y: Max", + "loc": "src/hex-table/HexTableView.ts:190", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:Hex table", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexTable.terrainFilter", + "group": "Hex table", + "subgroup": "Toolbar", + "label": "Terrain: all", + "loc": "src/hex-table/HexTableView.ts:204", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex table", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexTable.hasTown", + "group": "Hex table", + "subgroup": "Toolbar", + "label": "Town", + "loc": "src/hex-table/HexTableView.ts:240", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex table", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexTable.hasDungeon", + "group": "Hex table", + "subgroup": "Toolbar", + "label": "Dungeon", + "loc": "src/hex-table/HexTableView.ts:252", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex table", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexTable.hasFeature", + "group": "Hex table", + "subgroup": "Toolbar", + "label": "Feature", + "loc": "src/hex-table/HexTableView.ts:264", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex table", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexTable.hasQuest", + "group": "Hex table", + "subgroup": "Toolbar", + "label": "Quest", + "loc": "src/hex-table/HexTableView.ts:276", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex table", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexTable.hasFaction", + "group": "Hex table", + "subgroup": "Toolbar", + "label": "Faction", + "loc": "src/hex-table/HexTableView.ts:288", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex table", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexTable.mapSelect", + "group": "Hex table", + "subgroup": "Toolbar", + "label": "All maps / ", + "loc": "src/hex-table/HexTableView.ts:299", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex table", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexTable.sortCycle", + "group": "Hex table", + "subgroup": "Toolbar", + "label": "Sort: xy / yx / type", + "loc": "src/hex-table/HexTableView.ts:329", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex table", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexTable.sortDirection", + "group": "Hex table", + "subgroup": "Toolbar", + "label": "↑ asc / ↓ desc", + "loc": "src/hex-table/HexTableView.ts:341", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex table", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexTable.clearFilters", + "group": "Hex table", + "subgroup": "Toolbar", + "label": "Clear filters", + "loc": "src/hex-table/HexTableView.ts:355", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex table", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexTable.jumpToHex", + "group": "Hex table", + "subgroup": "Rows & cells", + "label": "◎", + "loc": "src/hex-table/HexTableView.ts:802", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex table", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexTable.openHexNote", + "group": "Hex table", + "subgroup": "Rows & cells", + "label": "", + "loc": "src/hex-table/HexTableView.ts:812", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex table", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexTable.terrainCell", + "group": "Hex table", + "subgroup": "Rows & cells", + "label": "Terrain cell", + "loc": "src/hex-table/HexTableView.ts:889", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex table", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexTable.townsCell", + "group": "Hex table", + "subgroup": "Rows & cells", + "label": "Towns cell", + "loc": "src/hex-table/HexTableView.ts:970", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex table", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexTable.dungeonsCell", + "group": "Hex table", + "subgroup": "Rows & cells", + "label": "Dungeons cell", + "loc": "src/hex-table/HexTableView.ts:970", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex table", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexTable.encountersCell", + "group": "Hex table", + "subgroup": "Rows & cells", + "label": "Enc. Table cell", + "loc": "src/hex-table/HexTableView.ts:970", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex table", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexTable.encountersMiddleClick", + "group": "Hex table", + "subgroup": "Rows & cells", + "label": "Middle-click Enc. Table", + "loc": "src/hex-table/HexTableView.ts:947", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex table", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexTable.otherLinkCell", + "group": "Hex table", + "subgroup": "Rows & cells", + "label": "Features/Quests/Factions cell", + "loc": "src/hex-table/HexTableView.ts:1031", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex table", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexTable.textCell", + "group": "Hex table", + "subgroup": "Rows & cells", + "label": "Text cells (Description…Hooks)", + "loc": "src/hex-table/HexTableView.ts:1054", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex table", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexTable.columnResize", + "group": "Hex table", + "subgroup": "Rows & cells", + "label": "Column edge drag", + "loc": "src/hex-table/HexTableView.ts:1119", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex table", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexTable.hiddenSecretColumns", + "group": "Hex table", + "subgroup": "Rows & cells", + "label": "Hidden / Secret columns", + "loc": "src/hex-table/HexTableView.ts:44", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex table", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexTable.weatherHooksColumns", + "group": "Hex table", + "subgroup": "Rows & cells", + "label": "Weather / Hooks & Rumors columns", + "loc": "src/hex-table/HexTableView.ts:46", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex table", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexCell.textarea", + "group": "Hex table", + "subgroup": "Rows & cells", + "label": "
text", + "loc": "src/hex-table/HexCellModal.ts:38", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex table", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexCell.rollOnTable", + "group": "Hex table", + "subgroup": "Rows & cells", + "label": "🎲 Roll on table", + "loc": "src/hex-table/HexCellModal.ts:46", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex table", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexCell.linkList", + "group": "Hex table", + "subgroup": "Rows & cells", + "label": "", + "loc": "src/hex-table/HexCellModal.ts:33", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex table", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexCell.closeButtons", + "group": "Hex table", + "subgroup": "Rows & cells", + "label": "×", + "loc": "src/hex-table/HexCellModal.ts:69", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex table", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TerrainFilter.noTerrain", + "group": "Hex table", + "subgroup": "Terrain filter", + "label": "No terrain", + "loc": "src/hex-table/TerrainFilterModal.ts:156", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex table", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TerrainFilter.typeRow", + "group": "Hex table", + "subgroup": "Terrain filter", + "label": " row", + "loc": "src/hex-table/TerrainFilterModal.ts:160", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:Hex table", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TerrainFilter.terrainRow", + "group": "Hex table", + "subgroup": "Terrain filter", + "label": " rows", + "loc": "src/hex-table/TerrainFilterModal.ts:168", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex table", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TerrainFilter.excludeRightClick", + "group": "Hex table", + "subgroup": "Terrain filter", + "label": "Right-click to exclude", + "loc": "src/hex-table/TerrainFilterModal.ts:94", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex table", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TerrainFilter.categoryHeading", + "group": "Hex table", + "subgroup": "Terrain filter", + "label": " heading", + "loc": "src/hex-table/TerrainFilterModal.ts:130", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex table", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TerrainFilter.clearAll", + "group": "Hex table", + "subgroup": "Terrain filter", + "label": "Clear all", + "loc": "src/hex-table/TerrainFilterModal.ts:206", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex table", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TerrainFilter.closeButtons", + "group": "Hex table", + "subgroup": "Terrain filter", + "label": "Done / ×", + "loc": "src/hex-table/TerrainFilterModal.ts:216", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex table", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexTerrainPicker.terrains", + "group": "Hex table", + "subgroup": "Terrain filter", + "label": "Select terrain", + "loc": "src/hex-table/HexTerrainPickerModal.ts:129", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex table", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexTerrainPicker.clear", + "group": "Hex table", + "subgroup": "Terrain filter", + "label": "Clear terrain", + "loc": "src/hex-table/HexTerrainPickerModal.ts:160", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex table", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexTerrainPicker.closeButtons", + "group": "Hex table", + "subgroup": "Terrain filter", + "label": "×", + "loc": "src/hex-table/HexTerrainPickerModal.ts:120", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex table", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "LinkPicker.townsList", + "group": "Hex table", + "subgroup": "Linking", + "label": "Select existing: (Towns)", + "loc": "src/hex-table/LinkPickerModal.ts:206", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex table", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "LinkPicker.dungeonsList", + "group": "Hex table", + "subgroup": "Linking", + "label": "Select existing: (Dungeons)", + "loc": "src/hex-table/LinkPickerModal.ts:206", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex table", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "LinkPicker.encountersList", + "group": "Hex table", + "subgroup": "Linking", + "label": "Select existing: (Encounters Table)", + "loc": "src/hex-table/LinkPickerModal.ts:206", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex table", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "LinkPicker.createName", + "group": "Hex table", + "subgroup": "Linking", + "label": "Or create new: ", + "loc": "src/hex-table/LinkPickerModal.ts:232", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex table", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "LinkPicker.createButton", + "group": "Hex table", + "subgroup": "Linking", + "label": "Create", + "loc": "src/hex-table/LinkPickerModal.ts:237", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex table", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "LinkPicker.closeButtons", + "group": "Hex table", + "subgroup": "Linking", + "label": "×", + "loc": "src/hex-table/LinkPickerModal.ts:199", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex table", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MultiLinkNav.items", + "group": "Hex table", + "subgroup": "Linking", + "label": "", + "loc": "src/hex-table/MultiLinkNavModal.ts:20", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex table", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MultiLinkNav.closeButtons", + "group": "Hex table", + "subgroup": "Linking", + "label": "×", + "loc": "src/hex-table/MultiLinkNavModal.ts:13", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex table", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "IconFilter.search", + "group": "Map pickers & editors", + "subgroup": "Icons", + "label": "Filter icons...", + "loc": "src/HexmakerModal.ts:45", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "IconFilter.packTabs", + "group": "Map pickers & editors", + "subgroup": "Icons", + "label": "All / Terrain / Places / Space / Custom (+counts)", + "loc": "src/HexmakerModal.ts:108", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "IconFilter.placeKindChips", + "group": "Map pickers & editors", + "subgroup": "Icons", + "label": "All places / Settlements / Castles / ...", + "loc": "src/HexmakerModal.ts:134", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "IconPicker.gmLayerOnly", + "group": "Map pickers & editors", + "subgroup": "Icons", + "label": "GM layer only", + "loc": "src/hex-map/IconPickerModal.ts:45", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "IconPicker.manageIcons", + "group": "Map pickers & editors", + "subgroup": "Icons", + "label": "Manage icons / ← pick icons", + "loc": "src/hex-map/IconPickerModal.ts:57", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "IconPicker.remove", + "group": "Map pickers & editors", + "subgroup": "Icons", + "label": "Remove", + "loc": "src/hex-map/IconPickerModal.ts:79", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "IconPicker.grid", + "group": "Map pickers & editors", + "subgroup": "Icons", + "label": "(icon tiles)", + "loc": "src/hex-map/IconPickerModal.ts:89", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "IconPicker.packTabs", + "group": "Map pickers & editors", + "subgroup": "Icons", + "label": "All / Terrain / Places / Space / Custom", + "loc": "src/HexmakerModal.ts:109", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "IconPicker.hideToggle", + "group": "Map pickers & editors", + "subgroup": "Icons", + "label": "eye / eye-off", + "loc": "src/hex-map/IconPickerModal.ts:138", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "IconPicker.dragReorder", + "group": "Map pickers & editors", + "subgroup": "Icons", + "label": "⠿ (drag to reorder)", + "loc": "src/hex-map/IconPickerModal.ts:157", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "IconPicker.uploadDropZone", + "group": "Map pickers & editors", + "subgroup": "Icons", + "label": "Drag & drop images here, or click to browse", + "loc": "src/hex-map/IconPickerModal.ts:204", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "IconPicker.closeButtons", + "group": "Map pickers & editors", + "subgroup": "Icons", + "label": "×", + "loc": "src/hex-map/IconPickerModal.ts:29", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Token.notePicker", + "group": "Map pickers & editors", + "subgroup": "Tokens", + "label": "Note", + "loc": "src/hex-map/TokenModal.ts:94", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Token.noteStatus", + "group": "Map pickers & editors", + "subgroup": "Tokens", + "label": "Links to … / Creates a new note: …", + "loc": "src/hex-map/TokenModal.ts:115", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Token.iconPackTabs", + "group": "Map pickers & editors", + "subgroup": "Tokens", + "label": "All / Terrain / Places / Space / Custom", + "loc": "src/HexmakerModal.ts:109", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Token.iconGrid", + "group": "Map pickers & editors", + "subgroup": "Tokens", + "label": "Icon", + "loc": "src/hex-map/TokenModal.ts:199", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Token.shape", + "group": "Map pickers & editors", + "subgroup": "Tokens", + "label": "Shape", + "loc": "src/hex-map/TokenModal.ts:233", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Token.size", + "group": "Map pickers & editors", + "subgroup": "Tokens", + "label": "Size", + "loc": "src/hex-map/TokenModal.ts:244", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Token.fillColor", + "group": "Map pickers & editors", + "subgroup": "Tokens", + "label": "Fill color", + "loc": "src/hex-map/TokenModal.ts:262", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Token.borderToggle", + "group": "Map pickers & editors", + "subgroup": "Tokens", + "label": "Border color (on/off)", + "loc": "src/hex-map/TokenModal.ts:284", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Token.borderColor", + "group": "Map pickers & editors", + "subgroup": "Tokens", + "label": "Border color", + "loc": "src/hex-map/TokenModal.ts:292", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Token.description", + "group": "Map pickers & editors", + "subgroup": "Tokens", + "label": "Description", + "loc": "src/hex-map/TokenModal.ts:315", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Token.removeButton", + "group": "Map pickers & editors", + "subgroup": "Tokens", + "label": "Remove token", + "loc": "src/hex-map/TokenModal.ts:333", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Token.saveButton", + "group": "Map pickers & editors", + "subgroup": "Tokens", + "label": "Next: place on map / Save", + "loc": "src/hex-map/TokenModal.ts:340", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Token.closeButtons", + "group": "Map pickers & editors", + "subgroup": "Tokens", + "label": "Cancel", + "loc": "src/hex-map/TokenModal.ts:372", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TokenInfo.jumpButton", + "group": "Map pickers & editors", + "subgroup": "Tokens", + "label": "⌖", + "loc": "src/hex-map/TokenInfoModal.ts:31", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TokenInfo.openNoteLink", + "group": "Map pickers & editors", + "subgroup": "Tokens", + "label": "Open note", + "loc": "src/hex-map/TokenInfoModal.ts:44", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TokenInfo.editButton", + "group": "Map pickers & editors", + "subgroup": "Tokens", + "label": "Edit token", + "loc": "src/hex-map/TokenInfoModal.ts:56", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TokenInfo.noteLinks", + "group": "Map pickers & editors", + "subgroup": "Tokens", + "label": "(links inside the note preview)", + "loc": "src/hex-map/TokenInfoModal.ts:91", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TokenInfo.removeButton", + "group": "Map pickers & editors", + "subgroup": "Tokens", + "label": "× remove / Confirm remove?", + "loc": "src/hex-map/TokenInfoModal.ts:117", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TokenInfo.closeButtons", + "group": "Map pickers & editors", + "subgroup": "Tokens", + "label": "×", + "loc": "src/hex-map/TokenInfoModal.ts:20", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PathName.nameInput", + "group": "Map pickers & editors", + "subgroup": "Path types", + "label": "(path name)", + "loc": "src/hex-map/PathNameModal.ts:45", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PathName.saveButton", + "group": "Map pickers & editors", + "subgroup": "Path types", + "label": "Save", + "loc": "src/hex-map/PathNameModal.ts:48", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PathName.closeButtons", + "group": "Map pickers & editors", + "subgroup": "Path types", + "label": "Cancel", + "loc": "src/hex-map/PathNameModal.ts:49", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PathPicker.editToggle", + "group": "Map pickers & editors", + "subgroup": "Path types", + "label": "✏ Edit / ← Done", + "loc": "src/hex-map/PathPickerModal.ts:158", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PathPicker.drawMode", + "group": "Map pickers & editors", + "subgroup": "Path types", + "label": "1. How to draw: Hex by hex / Auto-route", + "loc": "src/hex-map/PathPickerModal.ts:107", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PathPicker.removeTile", + "group": "Map pickers & editors", + "subgroup": "Path types", + "label": "Remove", + "loc": "src/hex-map/PathPickerModal.ts:187", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PathPicker.typeGrid", + "group": "Map pickers & editors", + "subgroup": "Path types", + "label": "2. Pick a path type to start drawing", + "loc": "src/hex-map/PathPickerModal.ts:198", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PathPicker.pathsOnMap", + "group": "Map pickers & editors", + "subgroup": "Path types", + "label": "Paths on this map", + "loc": "src/hex-map/PathPickerModal.ts:229", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PathPicker.editTypeTile", + "group": "Map pickers & editors", + "subgroup": "Path types", + "label": "(type tile, edit mode)", + "loc": "src/hex-map/PathPickerModal.ts:268", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PathPicker.dragReorder", + "group": "Map pickers & editors", + "subgroup": "Path types", + "label": "⠿ (drag to reorder)", + "loc": "src/hex-map/PathPickerModal.ts:285", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PathPicker.addTypeTile", + "group": "Map pickers & editors", + "subgroup": "Path types", + "label": "+ Add", + "loc": "src/hex-map/PathPickerModal.ts:315", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PathPicker.closeButtons", + "group": "Map pickers & editors", + "subgroup": "Path types", + "label": "×", + "loc": "src/hex-map/PathPickerModal.ts:133", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PathType.name", + "group": "Map pickers & editors", + "subgroup": "Path types", + "label": "Name", + "loc": "src/hex-map/PathTypeEditorModal.ts:78", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PathType.color", + "group": "Map pickers & editors", + "subgroup": "Path types", + "label": "Color", + "loc": "src/hex-map/PathTypeEditorModal.ts:88", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PathType.width", + "group": "Map pickers & editors", + "subgroup": "Path types", + "label": "Width", + "loc": "src/hex-map/PathTypeEditorModal.ts:99", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PathType.lineStyle", + "group": "Map pickers & editors", + "subgroup": "Path types", + "label": "Line style", + "loc": "src/hex-map/PathTypeEditorModal.ts:111", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PathType.routing", + "group": "Map pickers & editors", + "subgroup": "Path types", + "label": "Routing", + "loc": "src/hex-map/PathTypeEditorModal.ts:125", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PathType.avoidImpassable", + "group": "Map pickers & editors", + "subgroup": "Path types", + "label": "Avoid impassable terrain", + "loc": "src/hex-map/PathTypeEditorModal.ts:140", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PathType.autoRoute", + "group": "Map pickers & editors", + "subgroup": "Path types", + "label": "Auto-route", + "loc": "src/hex-map/PathTypeEditorModal.ts:149", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PathType.carves", + "group": "Map pickers & editors", + "subgroup": "Path types", + "label": "Carves terrain", + "loc": "src/hex-map/PathTypeEditorModal.ts:163", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PathType.carveWidth", + "group": "Map pickers & editors", + "subgroup": "Path types", + "label": "Carve width", + "loc": "src/hex-map/PathTypeEditorModal.ts:173", + "suggestion": "overkill", + "choice": "overkill", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PathType.saveButton", + "group": "Map pickers & editors", + "subgroup": "Path types", + "label": "Save", + "loc": "src/hex-map/PathTypeEditorModal.ts:185", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PathType.deleteButton", + "group": "Map pickers & editors", + "subgroup": "Path types", + "label": "Delete", + "loc": "src/hex-map/PathTypeEditorModal.ts:194", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PathType.deleteConfirm", + "group": "Map pickers & editors", + "subgroup": "Path types", + "label": "Yes, delete / Cancel", + "loc": "src/hex-map/PathTypeEditorModal.ts:212", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PathType.closeButtons", + "group": "Map pickers & editors", + "subgroup": "Path types", + "label": "×", + "loc": "src/hex-map/PathTypeEditorModal.ts:225", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GotoHex.xInput", + "group": "Map pickers & editors", + "subgroup": "Go to hex & help", + "label": "X:", + "loc": "src/hex-map/GotoHexModal.ts:21", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GotoHex.yInput", + "group": "Map pickers & editors", + "subgroup": "Go to hex & help", + "label": "Y:", + "loc": "src/hex-map/GotoHexModal.ts:26", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GotoHex.goButton", + "group": "Map pickers & editors", + "subgroup": "Go to hex & help", + "label": "Go", + "loc": "src/hex-map/GotoHexModal.ts:40", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GotoHex.closeButtons", + "group": "Map pickers & editors", + "subgroup": "Go to hex & help", + "label": "×", + "loc": "src/hex-map/GotoHexModal.ts:14", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexHelp.closeButtons", + "group": "Map pickers & editors", + "subgroup": "Go to hex & help", + "label": "×", + "loc": "src/hex-map/HexHelpModal.ts:10", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Locations.search", + "group": "Map pickers & editors", + "subgroup": "Locations", + "label": "Find a location…", + "loc": "src/hex-map/LocationsModal.ts:45", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Locations.list", + "group": "Map pickers & editors", + "subgroup": "Locations", + "label": "(location name)", + "loc": "src/hex-map/LocationsModal.ts:111", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Locations.openButton", + "group": "Map pickers & editors", + "subgroup": "Locations", + "label": "Open", + "loc": "src/hex-map/LocationsModal.ts:118", + "suggestion": "drop", + "choice": "drop", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Locations.unlink", + "group": "Map pickers & editors", + "subgroup": "Locations", + "label": "✕", + "loc": "src/hex-map/LocationsModal.ts:122", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Locations.dragReorder", + "group": "Map pickers & editors", + "subgroup": "Locations", + "label": "⋮⋮ (drag)", + "loc": "src/hex-map/LocationsModal.ts:89", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Locations.newLocation", + "group": "Map pickers & editors", + "subgroup": "Locations", + "label": "New location…", + "loc": "src/hex-map/LocationsModal.ts:62", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Locations.linkExisting", + "group": "Map pickers & editors", + "subgroup": "Locations", + "label": "Link existing map…", + "loc": "src/hex-map/LocationsModal.ts:66", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Locations.closeButtons", + "group": "Map pickers & editors", + "subgroup": "Locations", + "label": "×", + "loc": "src/hex-map/LocationsModal.ts:42", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "FactionPicker.grid", + "group": "Map pickers & editors", + "subgroup": "Factions", + "label": "(faction tiles)", + "loc": "src/hex-map/FactionPickerModal.ts:207", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "FactionPicker.removeTile", + "group": "Map pickers & editors", + "subgroup": "Factions", + "label": "Remove", + "loc": "src/hex-map/FactionPickerModal.ts:193", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "FactionPicker.editTile", + "group": "Map pickers & editors", + "subgroup": "Factions", + "label": "✏", + "loc": "src/hex-map/FactionPickerModal.ts:221", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "FactionPicker.newName", + "group": "Map pickers & editors", + "subgroup": "Factions", + "label": "New faction name…", + "loc": "src/hex-map/FactionPickerModal.ts:270", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "FactionPicker.createButton", + "group": "Map pickers & editors", + "subgroup": "Factions", + "label": "Create", + "loc": "src/hex-map/FactionPickerModal.ts:274", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "FactionPicker.closeButtons", + "group": "Map pickers & editors", + "subgroup": "Factions", + "label": "×", + "loc": "src/hex-map/FactionPickerModal.ts:300", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "FactionEditor.openNote", + "group": "Map pickers & editors", + "subgroup": "Factions", + "label": "Open note →", + "loc": "src/hex-map/FactionPickerModal.ts:46", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "FactionEditor.name", + "group": "Map pickers & editors", + "subgroup": "Factions", + "label": "Name", + "loc": "src/hex-map/FactionPickerModal.ts:74", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "FactionEditor.color", + "group": "Map pickers & editors", + "subgroup": "Factions", + "label": "Color", + "loc": "src/hex-map/FactionPickerModal.ts:81", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "FactionEditor.pattern", + "group": "Map pickers & editors", + "subgroup": "Factions", + "label": "Pattern", + "loc": "src/hex-map/overlayPatternControls.ts:139", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "FactionEditor.patternScale", + "group": "Map pickers & editors", + "subgroup": "Factions", + "label": "Pattern scale", + "loc": "src/hex-map/overlayPatternControls.ts:149", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "FactionEditor.opacity", + "group": "Map pickers & editors", + "subgroup": "Factions", + "label": "Opacity", + "loc": "src/hex-map/overlayPatternControls.ts:159", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "FactionEditor.outlineWidth", + "group": "Map pickers & editors", + "subgroup": "Factions", + "label": "Outline width", + "loc": "src/hex-map/overlayPatternControls.ts:169", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "FactionEditor.save", + "group": "Map pickers & editors", + "subgroup": "Factions", + "label": "Save", + "loc": "src/hex-map/FactionPickerModal.ts:102", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "FactionEditor.clearColor", + "group": "Map pickers & editors", + "subgroup": "Factions", + "label": "Clear color", + "loc": "src/hex-map/FactionPickerModal.ts:126", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "FactionEditor.closeButtons", + "group": "Map pickers & editors", + "subgroup": "Factions", + "label": "×", + "loc": "src/hex-map/FactionPickerModal.ts:36", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TerrainPicker.editToggle", + "group": "Map pickers & editors", + "subgroup": "Terrain", + "label": "✏ Edit / ← Done", + "loc": "src/hex-map/TerrainPickerModal.ts:52", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TerrainPicker.fullEditor", + "group": "Map pickers & editors", + "subgroup": "Terrain", + "label": "Full editor…", + "loc": "src/hex-map/TerrainPickerModal.ts:63", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TerrainPicker.brushSize", + "group": "Map pickers & editors", + "subgroup": "Terrain", + "label": "Brush: 1× 3× 7×", + "loc": "src/hex-map/TerrainPickerModal.ts:83", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TerrainPicker.eyedropper", + "group": "Map pickers & editors", + "subgroup": "Terrain", + "label": "⌖ Pick", + "loc": "src/hex-map/TerrainPickerModal.ts:104", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TerrainPicker.clear", + "group": "Map pickers & editors", + "subgroup": "Terrain", + "label": "Clear", + "loc": "src/hex-map/TerrainPickerModal.ts:119", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TerrainPicker.grid", + "group": "Map pickers & editors", + "subgroup": "Terrain", + "label": "(terrain tiles)", + "loc": "src/hex-map/TerrainPickerModal.ts:132", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TerrainPicker.editTile", + "group": "Map pickers & editors", + "subgroup": "Terrain", + "label": "(terrain tile, edit mode)", + "loc": "src/hex-map/TerrainPickerModal.ts:175", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TerrainPicker.dragReorder", + "group": "Map pickers & editors", + "subgroup": "Terrain", + "label": "⠿ (drag to reorder)", + "loc": "src/hex-map/TerrainPickerModal.ts:198", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TerrainPicker.addTile", + "group": "Map pickers & editors", + "subgroup": "Terrain", + "label": "+ Add", + "loc": "src/hex-map/TerrainPickerModal.ts:232", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TerrainPicker.refreshEncounterLinks", + "group": "Map pickers & editors", + "subgroup": "Terrain", + "label": "Refresh all encounter table links", + "loc": "src/hex-map/TerrainPickerModal.ts:275", + "suggestion": "overkill", + "choice": "overkill", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TerrainPicker.closeButtons", + "group": "Map pickers & editors", + "subgroup": "Terrain", + "label": "×", + "loc": "src/hex-map/TerrainPickerModal.ts:33", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TerrainTemplate.newBlank", + "group": "Map pickers & editors", + "subgroup": "Terrain", + "label": "New blank", + "loc": "src/hex-map/TerrainPickerModal.ts:309", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TerrainTemplate.copyList", + "group": "Map pickers & editors", + "subgroup": "Terrain", + "label": "Or copy from an existing palette:", + "loc": "src/hex-map/TerrainPickerModal.ts:329", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TerrainTemplate.closeButtons", + "group": "Map pickers & editors", + "subgroup": "Terrain", + "label": "×", + "loc": "src/hex-map/TerrainPickerModal.ts:345", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TerrainEntry.name", + "group": "Map pickers & editors", + "subgroup": "Terrain", + "label": "Name", + "loc": "src/hex-map/TerrainEntryEditorModal.ts:57", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TerrainEntry.type", + "group": "Map pickers & editors", + "subgroup": "Terrain", + "label": "Type", + "loc": "src/hex-map/TerrainEntryEditorModal.ts:73", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TerrainEntry.impassable", + "group": "Map pickers & editors", + "subgroup": "Terrain", + "label": "Impassable", + "loc": "src/hex-map/TerrainEntryEditorModal.ts:85", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TerrainEntry.color", + "group": "Map pickers & editors", + "subgroup": "Terrain", + "label": "Color", + "loc": "src/hex-map/TerrainEntryEditorModal.ts:94", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TerrainEntry.icon", + "group": "Map pickers & editors", + "subgroup": "Terrain", + "label": "Icon", + "loc": "src/hex-map/TerrainEntryEditorModal.ts:102", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TerrainEntry.iconTintToggle", + "group": "Map pickers & editors", + "subgroup": "Terrain", + "label": "Icon tint (on/off)", + "loc": "src/hex-map/TerrainEntryEditorModal.ts:125", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TerrainEntry.iconTintColor", + "group": "Map pickers & editors", + "subgroup": "Terrain", + "label": "Icon tint", + "loc": "src/hex-map/TerrainEntryEditorModal.ts:136", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TerrainEntry.category", + "group": "Map pickers & editors", + "subgroup": "Terrain", + "label": "Category", + "loc": "src/hex-map/TerrainEntryEditorModal.ts:159", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TerrainEntry.save", + "group": "Map pickers & editors", + "subgroup": "Terrain", + "label": "Save / Updating hexes…", + "loc": "src/hex-map/TerrainEntryEditorModal.ts:180", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TerrainEntry.delete", + "group": "Map pickers & editors", + "subgroup": "Terrain", + "label": "Delete", + "loc": "src/hex-map/TerrainEntryEditorModal.ts:198", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TerrainEntry.closeButtons", + "group": "Map pickers & editors", + "subgroup": "Terrain", + "label": "Cancel", + "loc": "src/hex-map/TerrainEntryEditorModal.ts:193", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapModal.tabMaps", + "group": "Maps modal", + "subgroup": "Tabs & general", + "label": "Maps", + "loc": "src/hex-map/MapModal.ts:119", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Maps modal", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapModal.tabProperties", + "group": "Maps modal", + "subgroup": "Tabs & general", + "label": "Properties", + "loc": "src/hex-map/MapModal.ts:119", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Maps modal", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapModal.tabRegions", + "group": "Maps modal", + "subgroup": "Tabs & general", + "label": "Regions", + "loc": "src/hex-map/MapModal.ts:107", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Maps modal", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapModal.tabExport", + "group": "Maps modal", + "subgroup": "Tabs & general", + "label": "Export", + "loc": "src/hex-map/MapModal.ts:119", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Maps modal", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapModal.newMap", + "group": "Maps modal", + "subgroup": "Tabs & general", + "label": "New map…", + "loc": "src/hex-map/MapModal.ts:127", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Maps modal", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapModal.newOverworld", + "group": "Maps modal", + "subgroup": "Tabs & general", + "label": "New overworld…", + "loc": "src/hex-map/MapModal.ts:130", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Maps modal", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapModal.mapSearch", + "group": "Maps modal", + "subgroup": "Maps list", + "label": "Find a map…", + "loc": "src/hex-map/MapModal.ts:242", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Maps modal", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapModal.mapTree", + "group": "Maps modal", + "subgroup": "Maps list", + "label": "(map list)", + "loc": "src/hex-map/MapModal.ts:254", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Maps modal", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapModal.treeToggle", + "group": "Maps modal", + "subgroup": "Maps list", + "label": "▸ / ▾", + "loc": "src/hex-map/MapModal.ts:317", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Maps modal", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapModal.regionsGroupRow", + "group": "Maps modal", + "subgroup": "Maps list", + "label": "Regions of ", + "loc": "src/hex-map/MapModal.ts:290", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Maps modal", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapModal.neighboursGroupRow", + "group": "Maps modal", + "subgroup": "Maps list", + "label": "Neighbours: ", + "loc": "src/hex-map/MapModal.ts:299", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Maps modal", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapModal.mapRowContextGenerator", + "group": "Maps modal", + "subgroup": "Maps list", + "label": "Open generator \"\"", + "loc": "src/hex-map/MapModal.ts:355", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:Maps modal", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapModal.mapRowContextMakeGenerator", + "group": "Maps modal", + "subgroup": "Maps list", + "label": "Make generator from …", + "loc": "src/hex-map/MapModal.ts:363", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:Maps modal", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapModal.missingRemove", + "group": "Maps modal", + "subgroup": "Maps list", + "label": "Remove / Remove from list?", + "loc": "src/hex-map/MapModal.ts:52", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Maps modal", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapProps.sectionTablePicker", + "group": "Maps modal", + "subgroup": "Properties", + "label": "Pick table…", + "loc": "src/hex-map/MapModal.ts:624", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:Maps modal", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapModal.propsName", + "group": "Maps modal", + "subgroup": "Properties", + "label": "Name", + "loc": "src/hex-map/MapModal.ts:425", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Maps modal", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapModal.propsSaveName", + "group": "Maps modal", + "subgroup": "Properties", + "label": "Save name", + "loc": "src/hex-map/MapModal.ts:430", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Maps modal", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapModal.propsFolderName", + "group": "Maps modal", + "subgroup": "Properties", + "label": "Folder name", + "loc": "src/hex-map/MapModal.ts:448", + "suggestion": "overkill", + "choice": "overkill", + "source": "group", + "via": "group:Maps modal", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapModal.propsRenameFolder", + "group": "Maps modal", + "subgroup": "Properties", + "label": "Rename folder", + "loc": "src/hex-map/MapModal.ts:453", + "suggestion": "overkill", + "choice": "overkill", + "source": "group", + "via": "group:Maps modal", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapModal.propsStagger", + "group": "Maps modal", + "subgroup": "Properties", + "label": "Stagger offset (Odd/Even)", + "loc": "src/hex-map/MapModal.ts:466", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Maps modal", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapModal.propsNeighbourHint", + "group": "Maps modal", + "subgroup": "Properties", + "label": "(enable Regions hint)", + "loc": "src/hex-map/MapModal.ts:696", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Maps modal", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "", + "removed": "ee28ebd: global Simple/Advanced level, feature switches, hints and nudges removed (owner 2026-10-11)" + }, + { + "id": "MapModal.propsTerrainTheme", + "group": "Maps modal", + "subgroup": "Properties", + "label": "Terrain theme", + "loc": "src/hex-map/MapModal.ts:494", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:Maps modal", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapModal.propsDelete", + "group": "Maps modal", + "subgroup": "Properties", + "label": "Delete \"\"…", + "loc": "src/hex-map/MapModal.ts:660", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Maps modal", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapModal.propsDeleteConfirm", + "group": "Maps modal", + "subgroup": "Properties", + "label": "Delete / Cancel", + "loc": "src/hex-map/MapModal.ts:671", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Maps modal", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapModal.propsNeighbourNorth", + "group": "Maps modal", + "subgroup": "Neighbouring regions", + "label": "North", + "loc": "src/hex-map/MapModal.ts:711", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Maps modal", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapModal.propsNeighbourEast", + "group": "Maps modal", + "subgroup": "Neighbouring regions", + "label": "East", + "loc": "src/hex-map/MapModal.ts:711", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Maps modal", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapModal.propsNeighbourSouth", + "group": "Maps modal", + "subgroup": "Neighbouring regions", + "label": "South", + "loc": "src/hex-map/MapModal.ts:711", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Maps modal", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapModal.propsNeighbourWest", + "group": "Maps modal", + "subgroup": "Neighbouring regions", + "label": "West", + "loc": "src/hex-map/MapModal.ts:711", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Maps modal", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapModal.propsNewRegionHere", + "group": "Maps modal", + "subgroup": "Neighbouring regions", + "label": "New region here…", + "loc": "src/hex-map/MapModal.ts:733", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Maps modal", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapModal.propsDetach", + "group": "Maps modal", + "subgroup": "Neighbouring regions", + "label": "Detach from its neighbours", + "loc": "src/hex-map/MapModal.ts:740", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Maps modal", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapModal.propsWeatherTable", + "group": "Maps modal", + "subgroup": "Weather & rumours", + "label": "Weather: Pick table…", + "loc": "src/hex-map/MapModal.ts:623", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:Maps modal", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapModal.propsWeatherClear", + "group": "Maps modal", + "subgroup": "Weather & rumours", + "label": "Clear (weather)", + "loc": "src/hex-map/MapModal.ts:635", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:Maps modal", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapModal.propsRumoursTable", + "group": "Maps modal", + "subgroup": "Weather & rumours", + "label": "Rumours: Pick table…", + "loc": "src/hex-map/MapModal.ts:623", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:Maps modal", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapModal.propsRumoursClear", + "group": "Maps modal", + "subgroup": "Weather & rumours", + "label": "Clear (rumours)", + "loc": "src/hex-map/MapModal.ts:635", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:Maps modal", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapProps.backgroundImagePicker", + "group": "Maps modal", + "subgroup": "Background image", + "label": "Pick image…", + "loc": "src/hex-map/MapModal.ts:548", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:Maps modal", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapModal.propsBgDrop", + "group": "Maps modal", + "subgroup": "Background image", + "label": "(drop an image here)", + "loc": "src/hex-map/MapModal.ts:567", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Maps modal", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapModal.propsBgClear", + "group": "Maps modal", + "subgroup": "Background image", + "label": "Clear", + "loc": "src/hex-map/MapModal.ts:556", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Maps modal", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapModal.propsBgOpacity", + "group": "Maps modal", + "subgroup": "Background image", + "label": "Opacity", + "loc": "src/hex-map/MapModal.ts:578", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Maps modal", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapModal.propsBgCalibrate", + "group": "Maps modal", + "subgroup": "Background image", + "label": "Calibrate position & scale", + "loc": "src/hex-map/MapModal.ts:590", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Maps modal", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapModal.regionsSetUp", + "group": "Maps modal", + "subgroup": "Regions tab", + "label": "Set up regions…", + "loc": "src/hex-map/MapModal.ts:169", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Maps modal", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapModal.regionsSettingsForm", + "group": "Maps modal", + "subgroup": "Regions tab", + "label": "(region settings form)", + "loc": "src/hex-map/MapModal.ts:182", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Maps modal", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapModal.regionsMakeMissing", + "group": "Maps modal", + "subgroup": "Regions tab", + "label": "Make the missing regions (N)…", + "loc": "src/hex-map/MapModal.ts:189", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Maps modal", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapModal.regionsGenerateOverworld", + "group": "Maps modal", + "subgroup": "Regions tab", + "label": "Generate overworld…", + "loc": "src/hex-map/MapModal.ts:200", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Maps modal", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapModal.regionsList", + "group": "Maps modal", + "subgroup": "Regions tab", + "label": "Regions (N) list", + "loc": "src/hex-map/MapModal.ts:209", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Maps modal", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewMap.name", + "group": "New maps & map links", + "subgroup": "New map form", + "label": "Name", + "loc": "src/worldgen/NewMapSetupModal.ts:222", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewMap.palette", + "group": "New maps & map links", + "subgroup": "New map form", + "label": "Palette", + "loc": "src/worldgen/NewMapSetupModal.ts:247", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewMap.rememberPalette", + "group": "New maps & map links", + "subgroup": "New map form", + "label": "Use this palette for new submaps of hexes", + "loc": "src/worldgen/NewMapSetupModal.ts:259", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewMap.sizePresets", + "group": "New maps & map links", + "subgroup": "New map form", + "label": "(size presets)", + "loc": "src/worldgen/NewMapSetupModal.ts:274", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewMap.size", + "group": "New maps & map links", + "subgroup": "New map form", + "label": "Size (columns × rows)", + "loc": "src/worldgen/NewMapSetupModal.ts:266", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewMap.rememberSize", + "group": "New maps & map links", + "subgroup": "New map form", + "label": "Use this size for new submaps…", + "loc": "src/worldgen/NewMapSetupModal.ts:306", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewMap.nextTo", + "group": "New maps & map links", + "subgroup": "New map form", + "label": "Next to", + "loc": "src/worldgen/NewMapSetupModal.ts:324", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewMap.nextToSide", + "group": "New maps & map links", + "subgroup": "New map form", + "label": "(side of the neighbouring map)", + "loc": "src/worldgen/NewMapSetupModal.ts:327", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewMap.generator", + "group": "New maps & map links", + "subgroup": "New map form", + "label": "Generator", + "loc": "src/worldgen/NewMapSetupModal.ts:569", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewMap.rememberGenerator", + "group": "New maps & map links", + "subgroup": "New map form", + "label": "Use this generator and its options for new submaps…", + "loc": "src/worldgen/NewMapSetupModal.ts:398", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewMap.moreOptionsHint", + "group": "New maps & map links", + "subgroup": "New map form", + "label": "More options: … Show / ✕", + "loc": "src/worldgen/NewMapSetupModal.ts:401", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "", + "removed": "ee28ebd: global Simple/Advanced level, feature switches, hints and nudges removed (owner 2026-10-11)" + }, + { + "id": "NewMap.baseTerrain", + "group": "New maps & map links", + "subgroup": "New map form", + "label": "Base terrain", + "loc": "src/worldgen/NewMapSetupModal.ts:411", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewMap.rememberBase", + "group": "New maps & map links", + "subgroup": "New map form", + "label": "Use this base terrain for new submaps…", + "loc": "src/worldgen/NewMapSetupModal.ts:412", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewMap.more", + "group": "New maps & map links", + "subgroup": "New map form", + "label": "More: folder name, starting coordinates, stagger, background image", + "loc": "src/worldgen/NewMapSetupModal.ts:420", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewMap.reroll", + "group": "New maps & map links", + "subgroup": "New map form", + "label": "🎲 Re-roll", + "loc": "src/worldgen/NewMapSetupModal.ts:509", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewMap.create", + "group": "New maps & map links", + "subgroup": "New map form", + "label": "Generate / Create (& enter)", + "loc": "src/worldgen/NewMapSetupModal.ts:518", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewMap.openInGenerator", + "group": "New maps & map links", + "subgroup": "New map form", + "label": "Open in generator", + "loc": "src/worldgen/NewMapSetupModal.ts:519", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewMap.closeButtons", + "group": "New maps & map links", + "subgroup": "New map form", + "label": "Cancel", + "loc": "src/worldgen/NewMapSetupModal.ts:521", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewMapSetup.backgroundImagePicker", + "group": "New maps & map links", + "subgroup": "New map form: More", + "label": "Pick image…", + "loc": "src/worldgen/NewMapSetupModal.ts:459", + "suggestion": "advanced", + "choice": "advanced", + "source": "twin", + "via": "NewMap.bgPick", + "viaSuggested": false, + "overrides": "", + "twinOf": "NewMap.bgPick", + "note": "" + }, + { + "id": "NewMap.folderName", + "group": "New maps & map links", + "subgroup": "New map form: More", + "label": "Folder name", + "loc": "src/worldgen/NewMapSetupModal.ts:425", + "suggestion": "overkill", + "choice": "overkill", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewMap.startCoords", + "group": "New maps & map links", + "subgroup": "New map form: More", + "label": "Starting coordinates", + "loc": "src/worldgen/NewMapSetupModal.ts:433", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewMap.stagger", + "group": "New maps & map links", + "subgroup": "New map form: More", + "label": "Stagger offset", + "loc": "src/worldgen/NewMapSetupModal.ts:444", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewMap.bgPick", + "group": "New maps & map links", + "subgroup": "New map form: More", + "label": "Pick image…", + "loc": "src/worldgen/NewMapSetupModal.ts:455", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewMap.bgClear", + "group": "New maps & map links", + "subgroup": "New map form: More", + "label": "Clear", + "loc": "src/worldgen/NewMapSetupModal.ts:456", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewMap.overlandWater", + "group": "New maps & map links", + "subgroup": "Generator options (world)", + "label": "Water", + "loc": "src/worldgen/procedural/planetSurface.ts:40", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewMap.overlandClimate", + "group": "New maps & map links", + "subgroup": "Generator options (world)", + "label": "Climate", + "loc": "src/worldgen/procedural/planetSurface.ts:52", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewMap.overlandRelief", + "group": "New maps & map links", + "subgroup": "Generator options (world)", + "label": "Relief", + "loc": "src/worldgen/procedural/planetSurface.ts:64", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewMap.overlandSea", + "group": "New maps & map links", + "subgroup": "Generator options (world)", + "label": "Sea", + "loc": "src/worldgen/procedural/planetSurface.ts:88", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewMap.planetWater", + "group": "New maps & map links", + "subgroup": "Generator options (world)", + "label": "Water", + "loc": "src/worldgen/procedural/planetSurface.ts:40", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewMap.planetClimate", + "group": "New maps & map links", + "subgroup": "Generator options (world)", + "label": "Climate", + "loc": "src/worldgen/procedural/planetSurface.ts:52", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewMap.planetRelief", + "group": "New maps & map links", + "subgroup": "Generator options (world)", + "label": "Relief", + "loc": "src/worldgen/procedural/planetSurface.ts:64", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewMap.regionDetailInfluence", + "group": "New maps & map links", + "subgroup": "Generator options (world)", + "label": "Neighbour influence", + "loc": "src/worldgen/procedural/planetSurface.ts:500", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewMap.regionDetailVariety", + "group": "New maps & map links", + "subgroup": "Generator options (world)", + "label": "Variety", + "loc": "src/worldgen/procedural/planetSurface.ts:510", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewMap.worldBiomesClimate", + "group": "New maps & map links", + "subgroup": "Generator options (world)", + "label": "Climate", + "loc": "src/overworld/worldBiomes.ts:576", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewMap.worldBiomesWater", + "group": "New maps & map links", + "subgroup": "Generator options (world)", + "label": "Water %", + "loc": "src/overworld/worldBiomes.ts:579", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewMap.worldBiomesLand", + "group": "New maps & map links", + "subgroup": "Generator options (world)", + "label": "Land", + "loc": "src/overworld/worldBiomes.ts:580", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewMap.worldBiomesNorth", + "group": "New maps & map links", + "subgroup": "Generator options (world)", + "label": "North is", + "loc": "src/overworld/worldBiomes.ts:583", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewMap.starDensity", + "group": "New maps & map links", + "subgroup": "Generator options (space)", + "label": "System density", + "loc": "src/worldgen/procedural/starScatter.ts:33", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewMap.starNebulae", + "group": "New maps & map links", + "subgroup": "Generator options (space)", + "label": "Nebulae", + "loc": "src/worldgen/procedural/starScatter.ts:43", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewMap.starJumpRoutes", + "group": "New maps & map links", + "subgroup": "Generator options (space)", + "label": "Jump routes", + "loc": "src/worldgen/procedural/starScatter.ts:53", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewMap.starRouteType", + "group": "New maps & map links", + "subgroup": "Generator options (space)", + "label": "Path type for routes", + "loc": "src/worldgen/generatorPathTypes.ts:27", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewMap.orbitsStar", + "group": "New maps & map links", + "subgroup": "Generator options (space)", + "label": "Star", + "loc": "src/worldgen/procedural/orbits.ts:37", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewMap.orbitsPlanets", + "group": "New maps & map links", + "subgroup": "Generator options (space)", + "label": "Planets", + "loc": "src/worldgen/procedural/orbits.ts:49", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewMap.orbitsPathType", + "group": "New maps & map links", + "subgroup": "Generator options (space)", + "label": "Path type for orbits", + "loc": "src/worldgen/generatorPathTypes.ts:28", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewMap.editWorldTypes", + "group": "New maps & map links", + "subgroup": "Generator options (space)", + "label": "Edit world types…", + "loc": "src/worldgen/NewMapSetupModal.ts:634", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewMap.tuning", + "group": "New maps & map links", + "subgroup": "Generator options (world)", + "label": "Engine tuning sliders", + "loc": "src/worldgen/NewMapSetupModal.ts", + "suggestion": "advanced", + "choice": "advanced", + "source": "owner", + "via": "owner 2026-10-12", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "Owner 2026-10-12: as the wizard, generator options above the fold and a trimmed set of 5-10 tuning sliders in Advanced." + }, + { + "id": "NewMap.makeAllRegions", + "group": "New maps & map links", + "subgroup": "Generator options (world)", + "label": "Make every region now (Biomes)", + "loc": "src/overworld/scaleOverworld.ts", + "suggestion": "advanced", + "choice": "advanced", + "source": "owner", + "via": "owner 2026-10-12", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "Owner 2026-10-12: as the wizard." + }, + { + "id": "ChildKind.region", + "group": "New maps & map links", + "subgroup": "New map from a hex", + "label": "Region", + "loc": "src/hex-map/newChildMap.ts:104", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "ChildKind.location", + "group": "New maps & map links", + "subgroup": "New map from a hex", + "label": "Location", + "loc": "src/hex-map/newChildMap.ts:104", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "ChildKind.enterRegion", + "group": "New maps & map links", + "subgroup": "New map from a hex", + "label": "Enter ", + "loc": "src/hex-map/newChildMap.ts:124", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "ChildKind.regionsHint", + "group": "New maps & map links", + "subgroup": "New map from a hex", + "label": "Turn on regions and overworlds / ✕", + "loc": "src/hex-map/newChildMap.ts:128", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "", + "removed": "ee28ebd: global Simple/Advanced level, feature switches, hints and nudges removed (owner 2026-10-11)" + }, + { + "id": "WalkOW.biome", + "group": "New maps & map links", + "subgroup": "New land beside a map", + "label": "Biome", + "loc": "src/worldgen/WalkRegionModal.ts:97", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WalkOW.roll", + "group": "New maps & map links", + "subgroup": "New land beside a map", + "label": "Roll", + "loc": "src/worldgen/WalkRegionModal.ts:101", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WalkOW.seed", + "group": "New maps & map links", + "subgroup": "New land beside a map", + "label": "Seed", + "loc": "src/worldgen/WalkRegionModal.ts:105", + "suggestion": "overkill", + "choice": "overkill", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WalkOW.rerollTerrain", + "group": "New maps & map links", + "subgroup": "New land beside a map", + "label": "Re-roll terrain", + "loc": "src/worldgen/WalkRegionModal.ts:107", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WalkOW.name", + "group": "New maps & map links", + "subgroup": "New land beside a map", + "label": "Name", + "loc": "src/worldgen/WalkRegionModal.ts:117", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WalkOW.create", + "group": "New maps & map links", + "subgroup": "New land beside a map", + "label": "Create and go", + "loc": "src/worldgen/WalkRegionModal.ts:123", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WalkOW.closeButtons", + "group": "New maps & map links", + "subgroup": "New land beside a map", + "label": "Cancel", + "loc": "src/worldgen/WalkRegionModal.ts:124", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WalkSide.biome", + "group": "New maps & map links", + "subgroup": "New land beside a map", + "label": "Biome", + "loc": "src/worldgen/WalkRegionModal.ts:222", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WalkSide.roll", + "group": "New maps & map links", + "subgroup": "New land beside a map", + "label": "Roll", + "loc": "src/worldgen/WalkRegionModal.ts:225", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WalkSide.rerollTerrain", + "group": "New maps & map links", + "subgroup": "New land beside a map", + "label": "Re-roll terrain", + "loc": "src/worldgen/WalkRegionModal.ts:230", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WalkSide.name", + "group": "New maps & map links", + "subgroup": "New land beside a map", + "label": "Name", + "loc": "src/worldgen/WalkRegionModal.ts:234", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WalkSide.create", + "group": "New maps & map links", + "subgroup": "New land beside a map", + "label": "Create and go", + "loc": "src/worldgen/WalkRegionModal.ts:237", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WalkSide.closeButtons", + "group": "New maps & map links", + "subgroup": "New land beside a map", + "label": "Cancel", + "loc": "src/worldgen/WalkRegionModal.ts:238", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapLink.map", + "group": "New maps & map links", + "subgroup": "Link submap & insert map link", + "label": "Map", + "loc": "src/hex-map/MapLinkModal.ts:344", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapLink.showAll", + "group": "New maps & map links", + "subgroup": "Link submap & insert map link", + "label": "▾ Show all", + "loc": "src/hex-map/MapLinkModal.ts:351", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapLink.linkText", + "group": "New maps & map links", + "subgroup": "Link submap & insert map link", + "label": "Link text", + "loc": "src/hex-map/MapLinkModal.ts:420", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapLink.insert", + "group": "New maps & map links", + "subgroup": "Link submap & insert map link", + "label": "Insert", + "loc": "src/hex-map/MapLinkModal.ts:428", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapLink.closeButtons", + "group": "New maps & map links", + "subgroup": "Link submap & insert map link", + "label": "Cancel", + "loc": "src/hex-map/MapLinkModal.ts:441", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "SubmapPicker.filter", + "group": "New maps & map links", + "subgroup": "Link submap & insert map link", + "label": "Filter maps…", + "loc": "src/hex-map/SubmapPickerModal.ts:52", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "SubmapPicker.mapList", + "group": "New maps & map links", + "subgroup": "Link submap & insert map link", + "label": "(map list)", + "loc": "src/hex-map/SubmapPickerModal.ts:58", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "SubmapPicker.newLocation", + "group": "New maps & map links", + "subgroup": "Link submap & insert map link", + "label": "New location…", + "loc": "src/hex-map/SubmapPickerModal.ts:106", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "SubmapPicker.removeLink", + "group": "New maps & map links", + "subgroup": "Link submap & insert map link", + "label": "Remove link", + "loc": "src/hex-map/SubmapPickerModal.ts:272", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "SubmapPicker.link", + "group": "New maps & map links", + "subgroup": "Link submap & insert map link", + "label": "Link", + "loc": "src/hex-map/SubmapPickerModal.ts:275", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "SubmapPicker.closeButtons", + "group": "New maps & map links", + "subgroup": "Link submap & insert map link", + "label": "Cancel", + "loc": "src/hex-map/SubmapPickerModal.ts:281", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "SubmapPicker.createSection", + "group": "New maps & map links", + "subgroup": "Link submap: inline create form", + "label": "Create & link new map", + "loc": "src/hex-map/SubmapPickerModal.ts:115", + "suggestion": "drop", + "choice": "drop", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "SubmapPicker.createName", + "group": "New maps & map links", + "subgroup": "Link submap: inline create form", + "label": "Name", + "loc": "src/hex-map/SubmapPickerModal.ts:135", + "suggestion": "drop", + "choice": "drop", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "SubmapPicker.createCols", + "group": "New maps & map links", + "subgroup": "Link submap: inline create form", + "label": "Size (columns)", + "loc": "src/hex-map/SubmapPickerModal.ts:150", + "suggestion": "drop", + "choice": "drop", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "SubmapPicker.createRows", + "group": "New maps & map links", + "subgroup": "Link submap: inline create form", + "label": "Size (rows)", + "loc": "src/hex-map/SubmapPickerModal.ts:153", + "suggestion": "drop", + "choice": "drop", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "SubmapPicker.createPalette", + "group": "New maps & map links", + "subgroup": "Link submap: inline create form", + "label": "Palette", + "loc": "src/hex-map/SubmapPickerModal.ts:159", + "suggestion": "drop", + "choice": "drop", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "SubmapPicker.createStartX", + "group": "New maps & map links", + "subgroup": "Link submap: inline create form", + "label": "Start at (x)", + "loc": "src/hex-map/SubmapPickerModal.ts:170", + "suggestion": "drop", + "choice": "drop", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "SubmapPicker.createStartY", + "group": "New maps & map links", + "subgroup": "Link submap: inline create form", + "label": "Start at (y)", + "loc": "src/hex-map/SubmapPickerModal.ts:173", + "suggestion": "drop", + "choice": "drop", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "SubmapPicker.createStagger", + "group": "New maps & map links", + "subgroup": "Link submap: inline create form", + "label": "Stagger (Odd/Even)", + "loc": "src/hex-map/SubmapPickerModal.ts:180", + "suggestion": "drop", + "choice": "drop", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "SubmapPicker.createTerrainTheme", + "group": "New maps & map links", + "subgroup": "Link submap: inline create form", + "label": "Map terrain theme", + "loc": "src/hex-map/SubmapPickerModal.ts:192", + "suggestion": "drop", + "choice": "drop", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "SubmapPicker.createAndLink", + "group": "New maps & map links", + "subgroup": "Link submap: inline create form", + "label": "Create & link / Create & enter", + "loc": "src/hex-map/SubmapPickerModal.ts:241", + "suggestion": "drop", + "choice": "drop", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewMapFields.name", + "group": "New maps & map links", + "subgroup": "Dead code", + "label": "Map name", + "loc": "src/hex-map/newMapFields.ts:23", + "suggestion": "drop", + "choice": "drop", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewMapFields.size", + "group": "New maps & map links", + "subgroup": "Dead code", + "label": "(cols × rows)", + "loc": "src/hex-map/newMapFields.ts:28", + "suggestion": "drop", + "choice": "drop", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewMapFields.palette", + "group": "New maps & map links", + "subgroup": "Dead code", + "label": "(palette)", + "loc": "src/hex-map/newMapFields.ts:39", + "suggestion": "drop", + "choice": "drop", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenerateRegions.makeThem", + "group": "Regions, overworlds & biomes", + "subgroup": "Missing regions & go to region", + "label": "Make them", + "loc": "src/hex-map/OverworldModals.ts:62", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenerateRegions.cancelStop", + "group": "Regions, overworlds & biomes", + "subgroup": "Missing regions & go to region", + "label": "Cancel / Stop / Close", + "loc": "src/hex-map/OverworldModals.ts:61", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RegionNavigate.go", + "group": "Regions, overworlds & biomes", + "subgroup": "Missing regions & go to region", + "label": "Go to ", + "loc": "src/hex-map/RegionNavigateModal.ts:378", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RegionNavigate.stay", + "group": "Regions, overworlds & biomes", + "subgroup": "Missing regions & go to region", + "label": "Stay", + "loc": "src/hex-map/RegionNavigateModal.ts:383", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewOverworld.name", + "group": "Regions, overworlds & biomes", + "subgroup": "New overworld", + "label": "Name", + "loc": "src/hex-map/OverworldModals.ts:178", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewOverworld.shape", + "group": "Regions, overworlds & biomes", + "subgroup": "New overworld", + "label": "Shape", + "loc": "src/hex-map/OverworldModals.ts:182", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewOverworld.hexCount", + "group": "Regions, overworlds & biomes", + "subgroup": "New overworld", + "label": "Hexes (N hexes)", + "loc": "src/hex-map/OverworldModals.ts:190", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewOverworld.columns", + "group": "Regions, overworlds & biomes", + "subgroup": "New overworld", + "label": "Columns", + "loc": "src/hex-map/OverworldModals.ts:195", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewOverworld.rows", + "group": "Regions, overworlds & biomes", + "subgroup": "New overworld", + "label": "Rows", + "loc": "src/hex-map/OverworldModals.ts:197", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewOverworld.palette", + "group": "Regions, overworlds & biomes", + "subgroup": "New overworld", + "label": "Palette", + "loc": "src/hex-map/OverworldModals.ts:210", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewOverworld.climate", + "group": "Regions, overworlds & biomes", + "subgroup": "New overworld", + "label": "Climate", + "loc": "src/hex-map/OverworldModals.ts:287", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewOverworld.land", + "group": "Regions, overworlds & biomes", + "subgroup": "New overworld", + "label": "Land", + "loc": "src/hex-map/OverworldModals.ts:288", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewOverworld.northIs", + "group": "Regions, overworlds & biomes", + "subgroup": "New overworld", + "label": "North is", + "loc": "src/hex-map/OverworldModals.ts:289", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewOverworld.water", + "group": "Regions, overworlds & biomes", + "subgroup": "New overworld", + "label": "Water", + "loc": "src/hex-map/OverworldModals.ts:291", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewOverworld.blankHexes", + "group": "Regions, overworlds & biomes", + "subgroup": "New overworld", + "label": "Blank hexes", + "loc": "src/hex-map/OverworldModals.ts:300", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewOverworld.blankBiome", + "group": "Regions, overworlds & biomes", + "subgroup": "New overworld", + "label": "Blank biome", + "loc": "src/hex-map/OverworldModals.ts:303", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewOverworld.seed", + "group": "Regions, overworlds & biomes", + "subgroup": "New overworld", + "label": "Seed", + "loc": "src/hex-map/OverworldModals.ts:318", + "suggestion": "overkill", + "choice": "overkill", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "just make sure its saved for the saved rolls etc, its fine if it shows up on saves too. " + }, + { + "id": "NewOverworld.reroll", + "group": "Regions, overworlds & biomes", + "subgroup": "New overworld", + "label": "Reroll", + "loc": "src/hex-map/OverworldModals.ts:320", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewOverworld.regionSize", + "group": "Regions, overworlds & biomes", + "subgroup": "New overworld", + "label": "Each hex opens into", + "loc": "src/hex-map/OverworldModals.ts:333", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewOverworld.blend", + "group": "Regions, overworlds & biomes", + "subgroup": "New overworld", + "label": "Blend", + "loc": "src/hex-map/OverworldModals.ts:337", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewOverworld.makeAll", + "group": "Regions, overworlds & biomes", + "subgroup": "New overworld", + "label": "Make every region now / Remake the regions too", + "loc": "src/hex-map/OverworldModals.ts:343", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewOverworld.create", + "group": "Regions, overworlds & biomes", + "subgroup": "New overworld", + "label": "Create / Regenerate", + "loc": "src/hex-map/OverworldModals.ts:351", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewOverworld.closeButtons", + "group": "Regions, overworlds & biomes", + "subgroup": "New overworld", + "label": "Cancel", + "loc": "src/hex-map/OverworldModals.ts:350", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewOverworld.biomePool", + "group": "Regions, overworlds & biomes", + "subgroup": "Biome pools", + "label": "Biome pool", + "loc": "src/hex-map/OverworldModals.ts:218", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewOverworld.poolSave", + "group": "Regions, overworlds & biomes", + "subgroup": "Biome pools", + "label": "Save", + "loc": "src/hex-map/OverworldModals.ts:219", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewOverworld.poolSaveAs", + "group": "Regions, overworlds & biomes", + "subgroup": "Biome pools", + "label": "Save as…", + "loc": "src/hex-map/OverworldModals.ts:220", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewOverworld.unclimated", + "group": "Regions, overworlds & biomes", + "subgroup": "Biome pools", + "label": "Biomes without a climate", + "loc": "src/hex-map/OverworldModals.ts:224", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewOverworld.poolList", + "group": "Regions, overworlds & biomes", + "subgroup": "Biome pools", + "label": "Biomes in the pool (N)", + "loc": "src/hex-map/OverworldModals.ts:374", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewOverworld.poolWeight", + "group": "Regions, overworlds & biomes", + "subgroup": "Biome pools", + "label": "(weight per biome)", + "loc": "src/hex-map/OverworldModals.ts:385", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewOverworld.poolRemove", + "group": "Regions, overworlds & biomes", + "subgroup": "Biome pools", + "label": "✕ Remove ", + "loc": "src/hex-map/OverworldModals.ts:393", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewOverworld.poolAdd", + "group": "Regions, overworlds & biomes", + "subgroup": "Biome pools", + "label": "Add a biome…", + "loc": "src/hex-map/OverworldModals.ts:404", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PoolName.name", + "group": "Regions, overworlds & biomes", + "subgroup": "Biome pools", + "label": "Pool name", + "loc": "src/hex-map/OverworldModals.ts:529", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PoolName.closeButtons", + "group": "Regions, overworlds & biomes", + "subgroup": "Biome pools", + "label": "Save / Cancel", + "loc": "src/hex-map/OverworldModals.ts:531", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "BiomeLibrary.edit", + "group": "Regions, overworlds & biomes", + "subgroup": "Biome library & biome form", + "label": "Edit…", + "loc": "src/hex-map/BiomeLibraryModal.ts:87", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "BiomeLibrary.editGenerator", + "group": "Regions, overworlds & biomes", + "subgroup": "Biome library & biome form", + "label": "Edit generator…", + "loc": "src/hex-map/BiomeLibraryModal.ts:93", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "BiomeLibrary.add", + "group": "Regions, overworlds & biomes", + "subgroup": "Biome library & biome form", + "label": "Add biome…", + "loc": "src/hex-map/BiomeLibraryModal.ts:99", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "BiomeLibrary.biomeList", + "group": "Regions, overworlds & biomes", + "subgroup": "Biome library & biome form", + "label": "(biome list)", + "loc": "src/hex-map/BiomeLibraryModal.ts:81", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "BiomeForm.madeBy", + "group": "Regions, overworlds & biomes", + "subgroup": "Biome library & biome form", + "label": "Made by", + "loc": "src/hex-map/BiomeLibraryModal.ts:162", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "BiomeForm.regionsStartBlank", + "group": "Regions, overworlds & biomes", + "subgroup": "Biome library & biome form", + "label": "Regions start blank", + "loc": "src/hex-map/BiomeLibraryModal.ts:173", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "BiomeForm.name", + "group": "Regions, overworlds & biomes", + "subgroup": "Biome library & biome form", + "label": "Name", + "loc": "src/hex-map/BiomeLibraryModal.ts:179", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "BiomeForm.colour", + "group": "Regions, overworlds & biomes", + "subgroup": "Biome library & biome form", + "label": "Colour", + "loc": "src/hex-map/BiomeLibraryModal.ts:182", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "BiomeForm.mixSlider", + "group": "Regions, overworlds & biomes", + "subgroup": "Biome library & biome form", + "label": " weight (slider)", + "loc": "src/hex-map/BiomeLibraryModal.ts:195", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "BiomeForm.mixNumber", + "group": "Regions, overworlds & biomes", + "subgroup": "Biome library & biome form", + "label": " weight value", + "loc": "src/hex-map/BiomeLibraryModal.ts:196", + "suggestion": "drop", + "choice": "drop", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "BiomeForm.blend", + "group": "Regions, overworlds & biomes", + "subgroup": "Biome library & biome form", + "label": "Blend with neighbours", + "loc": "src/hex-map/BiomeLibraryModal.ts:206", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "BiomeForm.landShareOn", + "group": "Regions, overworlds & biomes", + "subgroup": "Biome library & biome form", + "label": "Set a land share", + "loc": "src/hex-map/BiomeLibraryModal.ts:216", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "BiomeForm.landShare", + "group": "Regions, overworlds & biomes", + "subgroup": "Biome library & biome form", + "label": "Land share", + "loc": "src/hex-map/BiomeLibraryModal.ts:217", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "BiomeForm.fewestIslands", + "group": "Regions, overworlds & biomes", + "subgroup": "Biome library & biome form", + "label": "Fewest islands", + "loc": "src/hex-map/BiomeLibraryModal.ts:228", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "BiomeForm.temperature", + "group": "Regions, overworlds & biomes", + "subgroup": "Biome library & biome form", + "label": "Temperature", + "loc": "src/hex-map/BiomeLibraryModal.ts:244", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "BiomeForm.moisture", + "group": "Regions, overworlds & biomes", + "subgroup": "Biome library & biome form", + "label": "Moisture", + "loc": "src/hex-map/BiomeLibraryModal.ts:245", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "BiomeForm.height", + "group": "Regions, overworlds & biomes", + "subgroup": "Biome library & biome form", + "label": "Height", + "loc": "src/hex-map/BiomeLibraryModal.ts:246", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "BiomeForm.chance", + "group": "Regions, overworlds & biomes", + "subgroup": "Biome library & biome form", + "label": "Chance %", + "loc": "src/hex-map/BiomeLibraryModal.ts:250", + "suggestion": "overkill", + "choice": "overkill", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "BiomeForm.coastOnly", + "group": "Regions, overworlds & biomes", + "subgroup": "Biome library & biome form", + "label": "Coast only", + "loc": "src/hex-map/BiomeLibraryModal.ts:260", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "BiomeForm.rare", + "group": "Regions, overworlds & biomes", + "subgroup": "Biome library & biome form", + "label": "Rare", + "loc": "src/hex-map/BiomeLibraryModal.ts:261", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "BiomeForm.transitionNext", + "group": "Regions, overworlds & biomes", + "subgroup": "Biome library & biome form", + "label": "Next to", + "loc": "src/hex-map/BiomeLibraryModal.ts:284", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "BiomeForm.transitionBetween", + "group": "Regions, overworlds & biomes", + "subgroup": "Biome library & biome form", + "label": "Put between", + "loc": "src/hex-map/BiomeLibraryModal.ts:286", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "BiomeForm.transitionRemove", + "group": "Regions, overworlds & biomes", + "subgroup": "Biome library & biome form", + "label": "Remove", + "loc": "src/hex-map/BiomeLibraryModal.ts:289", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "BiomeForm.transitionAdd", + "group": "Regions, overworlds & biomes", + "subgroup": "Biome library & biome form", + "label": "Add transition", + "loc": "src/hex-map/BiomeLibraryModal.ts:294", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "BiomeForm.previewReroll", + "group": "Regions, overworlds & biomes", + "subgroup": "Biome library & biome form", + "label": "Reroll", + "loc": "src/hex-map/BiomeLibraryModal.ts:306", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "BiomeForm.restoreDefault", + "group": "Regions, overworlds & biomes", + "subgroup": "Biome library & biome form", + "label": "Restore default", + "loc": "src/hex-map/BiomeLibraryModal.ts:311", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "BiomeForm.editGenerator", + "group": "Regions, overworlds & biomes", + "subgroup": "Biome library & biome form", + "label": "Edit generator…", + "loc": "src/hex-map/BiomeLibraryModal.ts:321", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "BiomeForm.save", + "group": "Regions, overworlds & biomes", + "subgroup": "Biome library & biome form", + "label": "Save", + "loc": "src/hex-map/BiomeLibraryModal.ts:327", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "BiomeForm.closeButtons", + "group": "Regions, overworlds & biomes", + "subgroup": "Biome library & biome form", + "label": "Cancel", + "loc": "src/hex-map/BiomeLibraryModal.ts:326", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "BiomePicker.biomeGrid", + "group": "Regions, overworlds & biomes", + "subgroup": "Biome picker & paint", + "label": "(biome tiles)", + "loc": "src/hex-map/BiomeModals.ts:130", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "BiomePicker.enterRegion", + "group": "Regions, overworlds & biomes", + "subgroup": "Biome picker & paint", + "label": "Enter region", + "loc": "src/hex-map/BiomeModals.ts:146", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "BiomePicker.reroll", + "group": "Regions, overworlds & biomes", + "subgroup": "Biome picker & paint", + "label": "Reroll", + "loc": "src/hex-map/BiomeModals.ts:147", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "BiomePicker.settings", + "group": "Regions, overworlds & biomes", + "subgroup": "Biome picker & paint", + "label": "Settings…", + "loc": "src/hex-map/BiomeModals.ts:155", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "BiomePicker.biomes", + "group": "Regions, overworlds & biomes", + "subgroup": "Biome picker & paint", + "label": "Biomes…", + "loc": "src/hex-map/BiomeModals.ts:159", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "BiomePalette.biomeTiles", + "group": "Regions, overworlds & biomes", + "subgroup": "Biome picker & paint", + "label": "(biome tiles)", + "loc": "src/hex-map/BiomePaletteModal.ts:401", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "BiomePalette.biomes", + "group": "Regions, overworlds & biomes", + "subgroup": "Biome picker & paint", + "label": "Biomes…", + "loc": "src/hex-map/BiomePaletteModal.ts:421", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RegionGen.biome", + "group": "Regions, overworlds & biomes", + "subgroup": "Region settings", + "label": "Biome", + "loc": "src/hex-map/BiomeModals.ts:212", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RegionGen.editGenerator", + "group": "Regions, overworlds & biomes", + "subgroup": "Region settings", + "label": "Edit generator…", + "loc": "src/hex-map/BiomeModals.ts:219", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RegionGen.blend", + "group": "Regions, overworlds & biomes", + "subgroup": "Region settings", + "label": "Blend with neighbours", + "loc": "src/hex-map/BiomeModals.ts:225", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RegionGen.wigglyBorders", + "group": "Regions, overworlds & biomes", + "subgroup": "Region settings", + "label": "Wiggly borders", + "loc": "src/hex-map/BiomeModals.ts:231", + "suggestion": "overkill", + "choice": "overkill", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RegionGen.seed", + "group": "Regions, overworlds & biomes", + "subgroup": "Region settings", + "label": "Seed", + "loc": "src/hex-map/BiomeModals.ts:238", + "suggestion": "overkill", + "choice": "overkill", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RegionGen.reroll", + "group": "Regions, overworlds & biomes", + "subgroup": "Region settings", + "label": "Reroll", + "loc": "src/hex-map/BiomeModals.ts:241", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RegionGen.apply", + "group": "Regions, overworlds & biomes", + "subgroup": "Region settings", + "label": "Apply / Make region", + "loc": "src/hex-map/BiomeModals.ts:254", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RegionGen.closeButtons", + "group": "Regions, overworlds & biomes", + "subgroup": "Region settings", + "label": "Cancel", + "loc": "src/hex-map/BiomeModals.ts:253", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RegionSettings.shape", + "group": "Regions, overworlds & biomes", + "subgroup": "Region settings", + "label": "Shape (Rectangle / Hex flower)", + "loc": "src/hex-map/regionSettingsForm.ts:52", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RegionSettings.sizePresets", + "group": "Regions, overworlds & biomes", + "subgroup": "Region settings", + "label": "Size", + "loc": "src/hex-map/regionSettingsForm.ts:75", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RegionSettings.customSize", + "group": "Regions, overworlds & biomes", + "subgroup": "Region settings", + "label": "Hexes across (custom)", + "loc": "src/hex-map/regionSettingsForm.ts:89", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RegionSettings.palette", + "group": "Regions, overworlds & biomes", + "subgroup": "Region settings", + "label": "Palette", + "loc": "src/hex-map/regionSettingsForm.ts:119", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RegionSettings.blend", + "group": "Regions, overworlds & biomes", + "subgroup": "Region settings", + "label": "Blend", + "loc": "src/hex-map/regionSettingsForm.ts:130", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RegionSettings.save", + "group": "Regions, overworlds & biomes", + "subgroup": "Region settings", + "label": "Save and continue", + "loc": "src/hex-map/newChildMap.ts:173", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RegionSettings.closeButtons", + "group": "Regions, overworlds & biomes", + "subgroup": "Region settings", + "label": "Cancel", + "loc": "src/hex-map/newChildMap.ts:172", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "EditRegion.name", + "group": "Regions, overworlds & biomes", + "subgroup": "Edit region", + "label": "Region name", + "loc": "src/hex-map/EditRegionModal.ts:82", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "EditRegion.enterRegion", + "group": "Regions, overworlds & biomes", + "subgroup": "Edit region", + "label": "Enter region", + "loc": "src/hex-map/EditRegionModal.ts:105", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "EditRegion.openMapNote", + "group": "Regions, overworlds & biomes", + "subgroup": "Edit region", + "label": "Open map note", + "loc": "src/hex-map/EditRegionModal.ts:112", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "EditRegion.biomeGrid", + "group": "Regions, overworlds & biomes", + "subgroup": "Edit region", + "label": "(biome tiles)", + "loc": "src/hex-map/EditRegionModal.ts:147", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "EditRegion.reroll", + "group": "Regions, overworlds & biomes", + "subgroup": "Edit region", + "label": "Reroll", + "loc": "src/hex-map/EditRegionModal.ts:176", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "EditRegion.settings", + "group": "Regions, overworlds & biomes", + "subgroup": "Edit region", + "label": "Settings…", + "loc": "src/hex-map/EditRegionModal.ts:180", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "EditRegion.editGenerator", + "group": "Regions, overworlds & biomes", + "subgroup": "Edit region", + "label": "Edit generator…", + "loc": "src/hex-map/EditRegionModal.ts:134", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "EditRegion.makeGenerator", + "group": "Regions, overworlds & biomes", + "subgroup": "Edit region", + "label": "Make generator…", + "loc": "src/hex-map/EditRegionModal.ts:140", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "EditRegion.neighbourLinks", + "group": "Regions, overworlds & biomes", + "subgroup": "Edit region", + "label": "Next to: links", + "loc": "src/hex-map/EditRegionModal.ts:220", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "EditRegion.locationsList", + "group": "Regions, overworlds & biomes", + "subgroup": "Edit region", + "label": "List…", + "loc": "src/hex-map/EditRegionModal.ts:237", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "EditRegion.confirmPath", + "group": "Regions, overworlds & biomes", + "subgroup": "Edit region", + "label": "Confirm into regions / Update regions", + "loc": "src/hex-map/EditRegionModal.ts:254", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "EditRegion.notes", + "group": "Regions, overworlds & biomes", + "subgroup": "Edit region", + "label": "Region notes", + "loc": "src/hex-map/EditRegionModal.ts:266", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GeoRegionPicker.regionTiles", + "group": "Regions, overworlds & biomes", + "subgroup": "Region areas", + "label": "(region note tiles)", + "loc": "src/hex-map/GeoRegionPickerModal.ts:181", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GeoRegionPicker.remove", + "group": "Regions, overworlds & biomes", + "subgroup": "Region areas", + "label": "Remove", + "loc": "src/hex-map/GeoRegionPickerModal.ts:184", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GeoRegionPicker.editTile", + "group": "Regions, overworlds & biomes", + "subgroup": "Region areas", + "label": "✏ Edit region", + "loc": "src/hex-map/GeoRegionPickerModal.ts:210", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GeoRegionPicker.newName", + "group": "Regions, overworlds & biomes", + "subgroup": "Region areas", + "label": "New region name…", + "loc": "src/hex-map/GeoRegionPickerModal.ts:257", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GeoRegionPicker.create", + "group": "Regions, overworlds & biomes", + "subgroup": "Region areas", + "label": "Create", + "loc": "src/hex-map/GeoRegionPickerModal.ts:261", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GeoRegionEditor.openNote", + "group": "Regions, overworlds & biomes", + "subgroup": "Region areas", + "label": "Open note →", + "loc": "src/hex-map/GeoRegionPickerModal.ts:42", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GeoRegionEditor.name", + "group": "Regions, overworlds & biomes", + "subgroup": "Region areas", + "label": "Name", + "loc": "src/hex-map/GeoRegionPickerModal.ts:68", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GeoRegionEditor.color", + "group": "Regions, overworlds & biomes", + "subgroup": "Region areas", + "label": "Color", + "loc": "src/hex-map/GeoRegionPickerModal.ts:77", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GeoRegionEditor.save", + "group": "Regions, overworlds & biomes", + "subgroup": "Region areas", + "label": "Save", + "loc": "src/hex-map/GeoRegionPickerModal.ts:96", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GeoRegionEditor.clearColor", + "group": "Regions, overworlds & biomes", + "subgroup": "Region areas", + "label": "Clear color", + "loc": "src/hex-map/GeoRegionPickerModal.ts:116", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorldTypes.table", + "group": "Space: world types", + "subgroup": "General", + "label": "Table", + "loc": "src/space/WorldTypesModal.ts:232", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Space: world types", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorldTypes.newTable", + "group": "Space: world types", + "subgroup": "General", + "label": "New table…", + "loc": "src/space/WorldTypesModal.ts:241", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Space: world types", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorldTypes.newTableName", + "group": "Space: world types", + "subgroup": "General", + "label": "Table name", + "loc": "src/space/WorldTypesModal.ts:330", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Space: world types", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorldTypes.newTableCreate", + "group": "Space: world types", + "subgroup": "General", + "label": "Create", + "loc": "src/space/WorldTypesModal.ts:331", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Space: world types", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorldTypes.openNote", + "group": "Space: world types", + "subgroup": "General", + "label": "Open note", + "loc": "src/space/WorldTypesModal.ts:244", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Space: world types", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorldTypes.restoreDefault", + "group": "Space: world types", + "subgroup": "General", + "label": "Restore default", + "loc": "src/space/WorldTypesModal.ts:250", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Space: world types", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorldTypes.tabWorlds", + "group": "Space: world types", + "subgroup": "General", + "label": "Worlds (N)", + "loc": "src/space/WorldTypesModal.ts:279", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Space: world types", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorldTypes.tabStars", + "group": "Space: world types", + "subgroup": "General", + "label": "Stars (N)", + "loc": "src/space/WorldTypesModal.ts:279", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Space: world types", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorldTypes.tabFeatures", + "group": "Space: world types", + "subgroup": "General", + "label": "Sector features (N)", + "loc": "src/space/WorldTypesModal.ts:279", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Space: world types", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorldTypes.rowMoveUp", + "group": "Space: world types", + "subgroup": "General", + "label": "↑ Move up", + "loc": "src/space/WorldTypesModal.ts:414", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Space: world types", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorldTypes.rowMoveDown", + "group": "Space: world types", + "subgroup": "General", + "label": "↓ Move down", + "loc": "src/space/WorldTypesModal.ts:415", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Space: world types", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorldTypes.rowRemove", + "group": "Space: world types", + "subgroup": "General", + "label": "✕ Remove row", + "loc": "src/space/WorldTypesModal.ts:416", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Space: world types", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorldTypes.addRow", + "group": "Space: world types", + "subgroup": "General", + "label": "Add row", + "loc": "src/space/WorldTypesModal.ts:298", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Space: world types", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorldTypes.save", + "group": "Space: world types", + "subgroup": "General", + "label": "Save", + "loc": "src/space/WorldTypesModal.ts:309", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Space: world types", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorldTypes.worldName", + "group": "Space: world types", + "subgroup": "Worlds tab", + "label": "World", + "loc": "src/space/WorldTypesModal.ts:434", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Space: world types", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorldTypes.worldWeight", + "group": "Space: world types", + "subgroup": "Worlds tab", + "label": "Weight", + "loc": "src/space/WorldTypesModal.ts:434", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Space: world types", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorldTypes.worldMap", + "group": "Space: world types", + "subgroup": "Worlds tab", + "label": "Map", + "loc": "src/space/WorldTypesModal.ts:425", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Space: world types", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorldTypes.worldOrbit", + "group": "Space: world types", + "subgroup": "Worlds tab", + "label": "Orbit", + "loc": "src/space/WorldTypesModal.ts:434", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Space: world types", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorldTypes.worldStars", + "group": "Space: world types", + "subgroup": "Worlds tab", + "label": "Stars", + "loc": "src/space/WorldTypesModal.ts:434", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Space: world types", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorldTypes.worldTemperature", + "group": "Space: world types", + "subgroup": "Worlds tab", + "label": "Temperature", + "loc": "src/space/WorldTypesModal.ts:434", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Space: world types", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorldTypes.worldSize", + "group": "Space: world types", + "subgroup": "Worlds tab", + "label": "Size", + "loc": "src/space/WorldTypesModal.ts:434", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Space: world types", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorldTypes.worldGenerator", + "group": "Space: world types", + "subgroup": "Worlds tab", + "label": "Generator", + "loc": "src/space/WorldTypesModal.ts:434", + "suggestion": "overkill", + "choice": "overkill", + "source": "group", + "via": "group:Space: world types", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorldTypes.worldOptions", + "group": "Space: world types", + "subgroup": "Worlds tab", + "label": "Options", + "loc": "src/space/WorldTypesModal.ts:434", + "suggestion": "overkill", + "choice": "overkill", + "source": "group", + "via": "group:Space: world types", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorldTypes.worldPalette", + "group": "Space: world types", + "subgroup": "Worlds tab", + "label": "Palette", + "loc": "src/space/WorldTypesModal.ts:434", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Space: world types", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorldTypes.worldBase", + "group": "Space: world types", + "subgroup": "Worlds tab", + "label": "Base", + "loc": "src/space/WorldTypesModal.ts:434", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Space: world types", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorldTypes.worldNotes", + "group": "Space: world types", + "subgroup": "Worlds tab", + "label": "Notes", + "loc": "src/space/WorldTypesModal.ts:434", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Space: world types", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorldTypes.starName", + "group": "Space: world types", + "subgroup": "Stars tab", + "label": "Star", + "loc": "src/space/WorldTypesModal.ts:434", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Space: world types", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorldTypes.starWeight", + "group": "Space: world types", + "subgroup": "Stars tab", + "label": "Weight", + "loc": "src/space/WorldTypesModal.ts:434", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Space: world types", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorldTypes.starNotes", + "group": "Space: world types", + "subgroup": "Stars tab", + "label": "Notes", + "loc": "src/space/WorldTypesModal.ts:434", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Space: world types", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorldTypes.featureName", + "group": "Space: world types", + "subgroup": "Sector features tab", + "label": "Feature", + "loc": "src/space/WorldTypesModal.ts:434", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Space: world types", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorldTypes.featureChance", + "group": "Space: world types", + "subgroup": "Sector features tab", + "label": "Chance", + "loc": "src/space/WorldTypesModal.ts:434", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Space: world types", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorldTypes.featureNotes", + "group": "Space: world types", + "subgroup": "Sector features tab", + "label": "Notes", + "loc": "src/space/WorldTypesModal.ts:434", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Space: world types", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorldTypes.previewMap", + "group": "Space: world types", + "subgroup": "Preview", + "label": "Map", + "loc": "src/space/WorldTypesModal.ts:464", + "suggestion": "overkill", + "choice": "overkill", + "source": "group", + "via": "group:Space: world types", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorldTypes.previewOrbit", + "group": "Space: world types", + "subgroup": "Preview", + "label": "Orbit", + "loc": "src/space/WorldTypesModal.ts:465", + "suggestion": "overkill", + "choice": "overkill", + "source": "group", + "via": "group:Space: world types", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorldTypes.previewStar", + "group": "Space: world types", + "subgroup": "Preview", + "label": "Star", + "loc": "src/space/WorldTypesModal.ts:466", + "suggestion": "overkill", + "choice": "overkill", + "source": "group", + "via": "group:Space: world types", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorldTypes.previewTemperature", + "group": "Space: world types", + "subgroup": "Preview", + "label": "Temperature", + "loc": "src/space/WorldTypesModal.ts:467", + "suggestion": "overkill", + "choice": "overkill", + "source": "group", + "via": "group:Space: world types", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorldTypes.previewRolls", + "group": "Space: world types", + "subgroup": "Preview", + "label": "Rolls", + "loc": "src/space/WorldTypesModal.ts:473", + "suggestion": "overkill", + "choice": "overkill", + "source": "group", + "via": "group:Space: world types", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenLib.generatorsTab", + "group": "Generator page", + "subgroup": "Library", + "label": "Generators", + "loc": "src/worldgen/GeneratorLibrary.ts:70", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenLib.mapsTab", + "group": "Generator page", + "subgroup": "Library", + "label": "Maps", + "loc": "src/worldgen/GeneratorLibrary.ts:71", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenLib.filter", + "group": "Generator page", + "subgroup": "Library", + "label": "Filter…", + "loc": "src/worldgen/GeneratorLibrary.ts:50", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenLib.generatorRow", + "group": "Generator page", + "subgroup": "Library", + "label": "(generator row: click to load)", + "loc": "src/worldgen/GeneratorLibrary.ts:113", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenLib.generatorRowTick", + "group": "Generator page", + "subgroup": "Library", + "label": "(row checkbox)", + "loc": "src/worldgen/GeneratorLibrary.ts:263", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenLib.selectAll", + "group": "Generator page", + "subgroup": "Library", + "label": "Select all shown", + "loc": "src/worldgen/GeneratorLibrary.ts:246", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenLib.openFile", + "group": "Generator page", + "subgroup": "Library", + "label": "Open file", + "loc": "src/worldgen/GeneratorLibrary.ts:125", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenLib.relearn", + "group": "Generator page", + "subgroup": "Library", + "label": "Re-learn", + "loc": "src/worldgen/GeneratorLibrary.ts:126", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenLib.blend", + "group": "Generator page", + "subgroup": "Library", + "label": "Blend", + "loc": "src/worldgen/GeneratorLibrary.ts:127", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenLib.delete", + "group": "Generator page", + "subgroup": "Library", + "label": "Delete", + "loc": "src/worldgen/GeneratorLibrary.ts:131", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenLib.mapRow", + "group": "Generator page", + "subgroup": "Library", + "label": "(map row: tick to learn from)", + "loc": "src/worldgen/GeneratorLibrary.ts:192", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenLib.learnName", + "group": "Generator page", + "subgroup": "Library", + "label": "Generator name", + "loc": "src/worldgen/GeneratorLibrary.ts:206", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenLib.learn", + "group": "Generator page", + "subgroup": "Library", + "label": "Learn generator", + "loc": "src/worldgen/GeneratorLibrary.ts:210", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.saveDraft", + "group": "Generator page", + "subgroup": "Recipe", + "label": "Save generator", + "loc": "src/worldgen/GeneratorPanel.ts:336", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.discardDraft", + "group": "Generator page", + "subgroup": "Recipe", + "label": "Discard", + "loc": "src/worldgen/GeneratorPanel.ts:349", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.name", + "group": "Generator page", + "subgroup": "Recipe", + "label": "Name", + "loc": "src/worldgen/GeneratorPanel.ts:358", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.rename", + "group": "Generator page", + "subgroup": "Recipe", + "label": "Rename", + "loc": "src/worldgen/GeneratorPanel.ts:359", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.generatorPalette", + "group": "Generator page", + "subgroup": "Recipe", + "label": "Palette", + "loc": "src/worldgen/GeneratorPanel.ts:395", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.relearn", + "group": "Generator page", + "subgroup": "Recipe", + "label": "Re-learn / Re-blend", + "loc": "src/worldgen/GeneratorPanel.ts:417", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.openFile", + "group": "Generator page", + "subgroup": "Recipe", + "label": "Open file", + "loc": "src/worldgen/GeneratorPanel.ts:436", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.sourceInfluence", + "group": "Generator page", + "subgroup": "Recipe", + "label": " influence", + "loc": "src/worldgen/GeneratorPanel.ts:457", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.sourceCompass", + "group": "Generator page", + "subgroup": "Recipe", + "label": "(direction arrows ↖↑↗←•→↙↓↘)", + "loc": "src/worldgen/GeneratorPanel.ts:461", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.backToMapSize", + "group": "Generator page", + "subgroup": "Recipe", + "label": "Back to map size", + "loc": "src/worldgen/GeneratorPanel.ts:522", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.resetSettings", + "group": "Generator page", + "subgroup": "Recipe", + "label": "Reset settings to defaults", + "loc": "src/worldgen/GeneratorPanel.ts:536", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.sizePresets", + "group": "Generator page", + "subgroup": "Recipe", + "label": "(size presets)", + "loc": "src/worldgen/GeneratorPanel.ts:593", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.connectTo", + "group": "Generator page", + "subgroup": "Recipe", + "label": "Connect to", + "loc": "src/worldgen/GeneratorPanel.ts:619", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.connectSide", + "group": "Generator page", + "subgroup": "Recipe", + "label": "(side: east/west/north/south of it)", + "loc": "src/worldgen/GeneratorPanel.ts:622", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.regionsHint", + "group": "Generator page", + "subgroup": "Recipe", + "label": "Turn on regions and overworlds / ✕", + "loc": "src/worldgen/GeneratorPanel.ts:631", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "", + "removed": "ee28ebd: global Simple/Advanced level, feature switches, hints and nudges removed (owner 2026-10-11)" + }, + { + "id": "GenPage.leanToNeighbours", + "group": "Generator page", + "subgroup": "Recipe", + "label": "Lean toward neighbours", + "loc": "src/worldgen/GeneratorPanel.ts:665", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.guaranteedFeatures", + "group": "Generator page", + "subgroup": "Recipe", + "label": "Guaranteed features", + "loc": "src/worldgen/GeneratorPanel.ts:1046", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.connectedLand", + "group": "Generator page", + "subgroup": "Recipe", + "label": "Connected land", + "loc": "src/worldgen/GeneratorPanel.ts:1048", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.impassableSearch", + "group": "Generator page", + "subgroup": "Recipe", + "label": "Impassable terrain", + "loc": "src/worldgen/GeneratorPanel.ts:1502", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.impassableRemove", + "group": "Generator page", + "subgroup": "Recipe", + "label": "× (remove chip)", + "loc": "src/worldgen/GeneratorPanel.ts:1515", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.impassableSuggestAdd", + "group": "Generator page", + "subgroup": "Recipe", + "label": "Add / Add all", + "loc": "src/worldgen/GeneratorPanel.ts:1064", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.mix", + "group": "Generator page", + "subgroup": "Recipe", + "label": "Mix", + "loc": "src/worldgen/GeneratorPanel.ts:1118", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.minPatches", + "group": "Generator page", + "subgroup": "Recipe", + "label": "Min", + "loc": "src/worldgen/GeneratorPanel.ts:1132", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.maxPatches", + "group": "Generator page", + "subgroup": "Recipe", + "label": "Max", + "loc": "src/worldgen/GeneratorPanel.ts:1132", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.sectionFold", + "group": "Generator page", + "subgroup": "Recipe", + "label": "(section heading fold)", + "loc": "src/worldgen/GeneratorPanel.ts:1415", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.seed", + "group": "Generator page", + "subgroup": "Preview & saves", + "label": "Seed", + "loc": "src/worldgen/GeneratorPanel.ts:556", + "suggestion": "overkill", + "choice": "overkill", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.seedLock", + "group": "Generator page", + "subgroup": "Preview & saves", + "label": "(lock seed)", + "loc": "src/worldgen/GeneratorPanel.ts:559", + "suggestion": "overkill", + "choice": "overkill", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.reroll", + "group": "Generator page", + "subgroup": "Preview & saves", + "label": "Re-roll / Regenerate", + "loc": "src/worldgen/GeneratorPanel.ts:560", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.previewSize", + "group": "Generator page", + "subgroup": "Preview & saves", + "label": "Size (cols × rows)", + "loc": "src/worldgen/GeneratorPanel.ts:562", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.previewPalette", + "group": "Generator page", + "subgroup": "Preview & saves", + "label": "Palette", + "loc": "src/worldgen/GeneratorPanel.ts:567", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.newMapName", + "group": "Generator page", + "subgroup": "Preview & saves", + "label": "Name for the new map", + "loc": "src/worldgen/GeneratorPanel.ts:690", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.createMap", + "group": "Generator page", + "subgroup": "Preview & saves", + "label": "Create map", + "loc": "src/worldgen/GeneratorPanel.ts:691", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.saveName", + "group": "Generator page", + "subgroup": "Preview & saves", + "label": "Save name (optional)", + "loc": "src/worldgen/GeneratorPanel.ts:697", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.saveSnapshot", + "group": "Generator page", + "subgroup": "Preview & saves", + "label": "Save", + "loc": "src/worldgen/GeneratorPanel.ts:698", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.loadSelect", + "group": "Generator page", + "subgroup": "Preview & saves", + "label": "(saved snapshot list)", + "loc": "src/worldgen/GeneratorPanel.ts:700", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.loadSnapshot", + "group": "Generator page", + "subgroup": "Preview & saves", + "label": "Load", + "loc": "src/worldgen/GeneratorPanel.ts:701", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.featureSize", + "group": "Generator page", + "subgroup": "Engine tuning", + "label": "Feature size", + "loc": "src/worldgen/GeneratorPanel.ts:1012", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page/Engine tuning", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.clumping", + "group": "Generator page", + "subgroup": "Engine tuning", + "label": "Clumping", + "loc": "src/worldgen/GeneratorPanel.ts:1013", + "suggestion": "overkill", + "choice": "overkill", + "source": "group", + "via": "group:Generator page/Engine tuning", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "Engine tuning should have its own separate overkill setting. Basically all these ones marked \"overkill\" for generator settings should go into an \"advanced\" dropdown that defaults closed rather than them being gated under the global overkill setting. That way people can muck about with them when they wanna go a bit further on one gen or another, instead of having to flip and stick with a top-level setting. " + }, + { + "id": "GenPage.lineWidth", + "group": "Generator page", + "subgroup": "Engine tuning", + "label": "Line width", + "loc": "src/worldgen/GeneratorPanel.ts:1016", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page/Engine tuning", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.edgeSmoothing", + "group": "Generator page", + "subgroup": "Engine tuning", + "label": "Edge smoothing", + "loc": "src/worldgen/GeneratorPanel.ts:1021", + "suggestion": "overkill", + "choice": "overkill", + "source": "group", + "via": "group:Generator page/Engine tuning", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.removeSmallPatches", + "group": "Generator page", + "subgroup": "Engine tuning", + "label": "Remove small patches", + "loc": "src/worldgen/GeneratorPanel.ts:1023", + "suggestion": "overkill", + "choice": "overkill", + "source": "group", + "via": "group:Generator page/Engine tuning", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.keepRare", + "group": "Generator page", + "subgroup": "Engine tuning", + "label": "Keep rare terrain", + "loc": "src/worldgen/GeneratorPanel.ts:1025", + "suggestion": "overkill", + "choice": "overkill", + "source": "group", + "via": "group:Generator page/Engine tuning", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.symmetry", + "group": "Generator page", + "subgroup": "Engine tuning", + "label": "Symmetry", + "loc": "src/worldgen/GeneratorPanel.ts:1027", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page/Engine tuning", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.edgeStyle", + "group": "Generator page", + "subgroup": "Engine tuning", + "label": "Edge style", + "loc": "src/worldgen/GeneratorPanel.ts:1029", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page/Engine tuning", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.edgeStrength", + "group": "Generator page", + "subgroup": "Engine tuning", + "label": "Edge strength", + "loc": "src/worldgen/GeneratorPanel.ts:1032", + "suggestion": "overkill", + "choice": "overkill", + "source": "group", + "via": "group:Generator page/Engine tuning", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.directionalBias", + "group": "Generator page", + "subgroup": "Engine tuning", + "label": "Directional bias", + "loc": "src/worldgen/GeneratorPanel.ts:1036", + "suggestion": "overkill", + "choice": "overkill", + "source": "group", + "via": "group:Generator page/Engine tuning", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.scatter", + "group": "Generator page", + "subgroup": "Engine tuning", + "label": "Scatter", + "loc": "src/worldgen/GeneratorPanel.ts:1037", + "suggestion": "overkill", + "choice": "overkill", + "source": "group", + "via": "group:Generator page/Engine tuning", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.spacing", + "group": "Generator page", + "subgroup": "Engine tuning", + "label": "Spacing", + "loc": "src/worldgen/GeneratorPanel.ts:1039", + "suggestion": "overkill", + "choice": "overkill", + "source": "group", + "via": "group:Generator page/Engine tuning", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.randomness", + "group": "Generator page", + "subgroup": "Engine tuning", + "label": "Randomness", + "loc": "src/worldgen/GeneratorPanel.ts:1041", + "suggestion": "overkill", + "choice": "overkill", + "source": "group", + "via": "group:Generator page/Engine tuning", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.near", + "group": "Generator page", + "subgroup": "Engine tuning", + "label": "Near", + "loc": "src/worldgen/GeneratorPanel.ts:1146", + "suggestion": "overkill", + "choice": "overkill", + "source": "group", + "via": "group:Generator page/Engine tuning", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.mixStrength", + "group": "Generator page", + "subgroup": "Engine tuning", + "label": "Mix strength", + "loc": "src/worldgen/GeneratorPanel.ts:1176", + "suggestion": "overkill", + "choice": "overkill", + "source": "group", + "via": "group:Generator page/Engine tuning", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.drawPaths", + "group": "Generator page", + "subgroup": "Paths", + "label": "Draw paths", + "loc": "src/worldgen/GeneratorPanel.ts:1204", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.pathTypeFold", + "group": "Generator page", + "subgroup": "Paths", + "label": "(show routes chevron)", + "loc": "src/worldgen/GeneratorPanel.ts:1225", + "suggestion": "overkill", + "choice": "overkill", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "ditto for the above, make sure these go into an \"advanced\" section, Maybe the advanced section can have collapsible sub-sections as well so its clean to view. " + }, + { + "id": "GenPage.pathTypeOn", + "group": "Generator page", + "subgroup": "Paths", + "label": "Draw paths", + "loc": "src/worldgen/GeneratorPanel.ts:1227", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.pathTypeAmount", + "group": "Generator page", + "subgroup": "Paths", + "label": "Amount", + "loc": "src/worldgen/GeneratorPanel.ts:1261", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.pathTypeWiggle", + "group": "Generator page", + "subgroup": "Paths", + "label": "Wiggle", + "loc": "src/worldgen/GeneratorPanel.ts:1277", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.pathTypeLength", + "group": "Generator page", + "subgroup": "Paths", + "label": "Length", + "loc": "src/worldgen/GeneratorPanel.ts:1278", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.pathTypeFollow", + "group": "Generator page", + "subgroup": "Paths", + "label": "Follow terrain", + "loc": "src/worldgen/GeneratorPanel.ts:1279", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.pathTypeAvoid", + "group": "Generator page", + "subgroup": "Paths", + "label": "Avoid impassable terrain and the map border", + "loc": "src/worldgen/GeneratorPanel.ts:1290", + "suggestion": "overkill", + "choice": "overkill", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.routeOn", + "group": "Generator page", + "subgroup": "Paths", + "label": "(route checkbox)", + "loc": "src/worldgen/GeneratorPanel.ts:1315", + "suggestion": "overkill", + "choice": "overkill", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.routeCount", + "group": "Generator page", + "subgroup": "Paths", + "label": "Count", + "loc": "src/worldgen/GeneratorPanel.ts:1330", + "suggestion": "overkill", + "choice": "overkill", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.routeAs", + "group": "Generator page", + "subgroup": "Paths", + "label": "As", + "loc": "src/worldgen/GeneratorPanel.ts:1347", + "suggestion": "overkill", + "choice": "overkill", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.routeWiggle", + "group": "Generator page", + "subgroup": "Paths", + "label": "Wiggle (route)", + "loc": "src/worldgen/GeneratorPanel.ts:1373", + "suggestion": "overkill", + "choice": "overkill", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.routeLength", + "group": "Generator page", + "subgroup": "Paths", + "label": "Length (route)", + "loc": "src/worldgen/GeneratorPanel.ts:1374", + "suggestion": "overkill", + "choice": "overkill", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.routeFollow", + "group": "Generator page", + "subgroup": "Paths", + "label": "Follow terrain (route)", + "loc": "src/worldgen/GeneratorPanel.ts:1375", + "suggestion": "overkill", + "choice": "overkill", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "BiomePage.biome", + "group": "Generator page", + "subgroup": "Biome (blend field)", + "label": "Biome", + "loc": "src/worldgen/BiomePanel.ts:150", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "BiomePage.openNote", + "group": "Generator page", + "subgroup": "Biome (blend field)", + "label": "Open note", + "loc": "src/worldgen/BiomePanel.ts:160", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "BiomePage.restoreDefault", + "group": "Generator page", + "subgroup": "Biome (blend field)", + "label": "Restore default", + "loc": "src/worldgen/BiomePanel.ts:165", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "BiomePage.back", + "group": "Generator page", + "subgroup": "Biome (blend field)", + "label": "Back to generators", + "loc": "src/worldgen/BiomePanel.ts:173", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "BiomePage.weightSlider", + "group": "Generator page", + "subgroup": "Biome (blend field)", + "label": "Weight", + "loc": "src/worldgen/BiomePanel.ts:191", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "BiomePage.weightNumber", + "group": "Generator page", + "subgroup": "Biome (blend field)", + "label": "(weight value)", + "loc": "src/worldgen/BiomePanel.ts:192", + "suggestion": "drop", + "choice": "drop", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "BiomePage.minPatches", + "group": "Generator page", + "subgroup": "Biome (blend field)", + "label": "Min patches", + "loc": "src/worldgen/BiomePanel.ts:193", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "BiomePage.blendWidth", + "group": "Generator page", + "subgroup": "Biome (blend field)", + "label": "Blend width", + "loc": "src/worldgen/BiomePanel.ts:231", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "BiomePage.landShareOn", + "group": "Generator page", + "subgroup": "Biome (blend field)", + "label": "Land share (on/off)", + "loc": "src/worldgen/BiomePanel.ts:242", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "BiomePage.landShare", + "group": "Generator page", + "subgroup": "Biome (blend field)", + "label": "Land share", + "loc": "src/worldgen/BiomePanel.ts:243", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "BiomePage.minIslands", + "group": "Generator page", + "subgroup": "Biome (blend field)", + "label": "Min islands", + "loc": "src/worldgen/BiomePanel.ts:261", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "BiomePage.shore", + "group": "Generator page", + "subgroup": "Biome (blend field)", + "label": "Shore", + "loc": "src/worldgen/BiomePanel.ts:270", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "BiomePage.transitionNext", + "group": "Generator page", + "subgroup": "Biome (blend field)", + "label": "Next to", + "loc": "src/worldgen/BiomePanel.ts:299", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "BiomePage.transitionBetween", + "group": "Generator page", + "subgroup": "Biome (blend field)", + "label": "put", + "loc": "src/worldgen/BiomePanel.ts:301", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "BiomePage.transitionRemove", + "group": "Generator page", + "subgroup": "Biome (blend field)", + "label": "Remove", + "loc": "src/worldgen/BiomePanel.ts:309", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "BiomePage.transitionAdd", + "group": "Generator page", + "subgroup": "Biome (blend field)", + "label": "Add transition", + "loc": "src/worldgen/BiomePanel.ts:315", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "BiomePage.seed", + "group": "Generator page", + "subgroup": "Biome (blend field)", + "label": "Seed", + "loc": "src/worldgen/BiomePanel.ts:330", + "suggestion": "overkill", + "choice": "overkill", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "BiomePage.reroll", + "group": "Generator page", + "subgroup": "Biome (blend field)", + "label": "Re-roll", + "loc": "src/worldgen/BiomePanel.ts:332", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "BiomePage.size", + "group": "Generator page", + "subgroup": "Biome (blend field)", + "label": "Size", + "loc": "src/worldgen/BiomePanel.ts:338", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "BiomePage.aroundIt", + "group": "Generator page", + "subgroup": "Biome (blend field)", + "label": "Around it", + "loc": "src/worldgen/BiomePanel.ts:346", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "BiomePage.palette", + "group": "Generator page", + "subgroup": "Biome (blend field)", + "label": "Palette", + "loc": "src/worldgen/BiomePanel.ts:353", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MakeGen.newRadio", + "group": "Generator page", + "subgroup": "Make generator from a map", + "label": "New generator", + "loc": "src/hex-map/MakeGeneratorModal.ts:68", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MakeGen.name", + "group": "Generator page", + "subgroup": "Make generator from a map", + "label": "Name", + "loc": "src/hex-map/MakeGeneratorModal.ts:70", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MakeGen.overwriteRadio", + "group": "Generator page", + "subgroup": "Make generator from a map", + "label": "Overwrite existing", + "loc": "src/hex-map/MakeGeneratorModal.ts:80", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MakeGen.overwriteList", + "group": "Generator page", + "subgroup": "Make generator from a map", + "label": "Generator to overwrite", + "loc": "src/hex-map/MakeGeneratorModal.ts:96", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MakeGen.make", + "group": "Generator page", + "subgroup": "Make generator from a map", + "label": "Make generator / Overwrite", + "loc": "src/hex-map/MakeGeneratorModal.ts:90", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MakeGen.closeButtons", + "group": "Generator page", + "subgroup": "Make generator from a map", + "label": "Cancel", + "loc": "src/hex-map/MakeGeneratorModal.ts:92", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PaletteEditor.paletteSelect", + "group": "Palette editor", + "subgroup": "Toolbar", + "label": "Palette", + "loc": "src/palettes/PaletteEditorView.ts:99", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Palette editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PaletteEditor.addPalette", + "group": "Palette editor", + "subgroup": "Toolbar", + "label": "Add palette…", + "loc": "src/palettes/PaletteEditorView.ts:103", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Palette editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PaletteEditor.openNote", + "group": "Palette editor", + "subgroup": "Toolbar", + "label": "Open note", + "loc": "src/palettes/PaletteEditorView.ts:112", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Palette editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PaletteEditor.filter", + "group": "Palette editor", + "subgroup": "Toolbar", + "label": "Filter terrains…", + "loc": "src/palettes/PaletteEditorView.ts:118", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Palette editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PaletteEditor.guessTypes", + "group": "Palette editor", + "subgroup": "Terrains", + "label": "Guess types from names", + "loc": "src/palettes/PaletteEditorView.ts:140", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Palette editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PaletteEditor.rowDrag", + "group": "Palette editor", + "subgroup": "Terrains", + "label": "Drag to reorder (⠿)", + "loc": "src/palettes/PaletteEditorView.ts:260", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Palette editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PaletteEditor.color", + "group": "Palette editor", + "subgroup": "Terrains", + "label": " color", + "loc": "src/palettes/PaletteEditorView.ts:277", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Palette editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PaletteEditor.name", + "group": "Palette editor", + "subgroup": "Terrains", + "label": "Terrain name", + "loc": "src/palettes/PaletteEditorView.ts:283", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Palette editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PaletteEditor.type", + "group": "Palette editor", + "subgroup": "Terrains", + "label": " type", + "loc": "src/palettes/PaletteEditorView.ts:301", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Palette editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PaletteEditor.category", + "group": "Palette editor", + "subgroup": "Terrains", + "label": " category", + "loc": "src/palettes/PaletteEditorView.ts:312", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Palette editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PaletteEditor.icon", + "group": "Palette editor", + "subgroup": "Terrains", + "label": "Choose icon", + "loc": "src/palettes/PaletteEditorView.ts:326", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Palette editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PaletteEditor.tintOn", + "group": "Palette editor", + "subgroup": "Terrains", + "label": "Tint icon", + "loc": "src/palettes/PaletteEditorView.ts:345", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Palette editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PaletteEditor.tintColor", + "group": "Palette editor", + "subgroup": "Terrains", + "label": "Icon tint", + "loc": "src/palettes/PaletteEditorView.ts:347", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Palette editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PaletteEditor.impassable", + "group": "Palette editor", + "subgroup": "Terrains", + "label": " impassable", + "loc": "src/palettes/PaletteEditorView.ts:361", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Palette editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PaletteEditor.delete", + "group": "Palette editor", + "subgroup": "Terrains", + "label": "Delete terrain (×)", + "loc": "src/palettes/PaletteEditorView.ts:370", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Palette editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PaletteEditor.addTerrain", + "group": "Palette editor", + "subgroup": "Terrains", + "label": "Add terrain", + "loc": "src/palettes/PaletteEditorView.ts:178", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Palette editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PaletteEditor.submapPalette", + "group": "Palette editor", + "subgroup": "Palette settings & path types", + "label": "Submap palette", + "loc": "src/palettes/PaletteEditorView.ts:195", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Palette editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PaletteEditor.pathTypeRow", + "group": "Palette editor", + "subgroup": "Palette settings & path types", + "label": "(path type row)", + "loc": "src/palettes/PaletteEditorView.ts:228", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Palette editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PaletteEditor.addPathType", + "group": "Palette editor", + "subgroup": "Palette settings & path types", + "label": "Add path type", + "loc": "src/palettes/PaletteEditorView.ts:236", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Palette editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PaletteEditor.submapDefaultPalette", + "group": "Palette editor", + "subgroup": "Submap defaults", + "label": "Palette", + "loc": "src/palettes/PaletteEditorView.ts:410", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Palette editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PaletteEditor.submapDefaultCols", + "group": "Palette editor", + "subgroup": "Submap defaults", + "label": "Columns", + "loc": "src/palettes/PaletteEditorView.ts:417", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Palette editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PaletteEditor.submapDefaultRows", + "group": "Palette editor", + "subgroup": "Submap defaults", + "label": "Rows", + "loc": "src/palettes/PaletteEditorView.ts:419", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Palette editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PaletteEditor.submapDefaultGenerator", + "group": "Palette editor", + "subgroup": "Submap defaults", + "label": "Generator", + "loc": "src/palettes/PaletteEditorView.ts:429", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Palette editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PaletteEditor.generatorOptions", + "group": "Palette editor", + "subgroup": "Submap defaults", + "label": "Generator options", + "loc": "src/palettes/PaletteEditorView.ts:444", + "suggestion": "overkill", + "choice": "overkill", + "source": "group", + "via": "group:Palette editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PaletteEditor.submapDefaultBaseTerrain", + "group": "Palette editor", + "subgroup": "Submap defaults", + "label": "Base terrain", + "loc": "src/palettes/PaletteEditorView.ts:455", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Palette editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PaletteEditor.submapDefaultDelete", + "group": "Palette editor", + "subgroup": "Submap defaults", + "label": "Remove default (×)", + "loc": "src/palettes/PaletteEditorView.ts:459", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Palette editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PaletteEditor.addDefaultTerrain", + "group": "Palette editor", + "subgroup": "Submap defaults", + "label": "Terrain to add a default for", + "loc": "src/palettes/PaletteEditorView.ts:473", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Palette editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PaletteEditor.addDefault", + "group": "Palette editor", + "subgroup": "Submap defaults", + "label": "Add default", + "loc": "src/palettes/PaletteEditorView.ts:475", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Palette editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RTView.refreshList", + "group": "Random tables", + "subgroup": "Tables list", + "label": "Refresh list (↺)", + "loc": "src/random-tables/RandomTableView.ts:149", + "suggestion": "overkill", + "choice": "overkill", + "source": "group", + "via": "group:Random tables/Tables list", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "we should confirm that it does it at a good cadence for all of these \"sink refresh\" bits " + }, + { + "id": "RTView.tablesTab", + "group": "Random tables", + "subgroup": "Tables list", + "label": "Tables", + "loc": "src/random-tables/RandomTableView.ts:156", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables/Tables list", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RTView.workflowsTab", + "group": "Random tables", + "subgroup": "Tables list", + "label": "Workflows", + "loc": "src/random-tables/RandomTableView.ts:160", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables/Tables list", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RTView.tabMiddleClick", + "group": "Random tables", + "subgroup": "Tables list", + "label": "(middle-click a tab)", + "loc": "src/random-tables/RandomTableView.ts:172", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables/Tables list", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RTView.workflowsHintTurnOn", + "group": "Random tables", + "subgroup": "Tables list", + "label": "Turn on workflows", + "loc": "src/random-tables/RandomTableView.ts:89", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables/Tables list", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "", + "removed": "ee28ebd: global Simple/Advanced level, feature switches, hints and nudges removed (owner 2026-10-11)" + }, + { + "id": "RTView.workflowsHintHide", + "group": "Random tables", + "subgroup": "Tables list", + "label": "Hide this hint (✕)", + "loc": "src/advancedHints.ts:36", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables/Tables list", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "", + "removed": "ee28ebd: global Simple/Advanced level, feature switches, hints and nudges removed (owner 2026-10-11)" + }, + { + "id": "RTView.filterSearch", + "group": "Random tables", + "subgroup": "Tables list", + "label": "Filter tables…", + "loc": "src/random-tables/RandomTableView.ts:198", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables/Tables list", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RTView.tablesTree", + "group": "Random tables", + "subgroup": "Tables list", + "label": "(table folder tree)", + "loc": "src/random-tables/RandomTableView.ts:607", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Random tables/Tables list", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RTView.folderToggle", + "group": "Random tables", + "subgroup": "Tables list", + "label": "(folder ▶/▼)", + "loc": "src/random-tables/FolderTree.ts:161", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables/Tables list", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RTView.fileMiddleClick", + "group": "Random tables", + "subgroup": "Tables list", + "label": "(middle-click a table)", + "loc": "src/random-tables/RandomTableView.ts:1121", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables/Tables list", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RTView.dragToMove", + "group": "Random tables", + "subgroup": "Tables list", + "label": "(drag table onto folder)", + "loc": "src/random-tables/RandomTableView.ts:1137", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables/Tables list", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RTView.folderMenuRollPicker", + "group": "Random tables", + "subgroup": "Tables list", + "label": "Exclude from roll picker / Include in roll picker", + "loc": "src/random-tables/RandomTableView.ts:1153", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:Random tables/Tables list", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RTView.folderMenuEncounters", + "group": "Random tables", + "subgroup": "Tables list", + "label": "Exclude from encounters table / Include in encounters table", + "loc": "src/random-tables/RandomTableView.ts:1180", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:Random tables/Tables list", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RTView.fileMenuOpenNewTab", + "group": "Random tables", + "subgroup": "Tables list", + "label": "Open in new tab", + "loc": "src/random-tables/RandomTableView.ts:1213", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables/Tables list", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RTView.fileMenuRollPicker", + "group": "Random tables", + "subgroup": "Tables list", + "label": "Exclude from roll picker / Include in roll picker", + "loc": "src/random-tables/RandomTableView.ts:1227", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:Random tables/Tables list", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RTView.fileMenuEncounters", + "group": "Random tables", + "subgroup": "Tables list", + "label": "Exclude from encounters table / Include in encounters table", + "loc": "src/random-tables/RandomTableView.ts:1247", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:Random tables/Tables list", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RTView.fileMenuDelete", + "group": "Random tables", + "subgroup": "Tables list", + "label": "Delete table", + "loc": "src/random-tables/RandomTableView.ts:1270", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables/Tables list", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RTView.newTableName", + "group": "Random tables", + "subgroup": "Tables list", + "label": "New table name…", + "loc": "src/random-tables/RandomTableView.ts:283", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables/Tables list", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RTView.newTableButton", + "group": "Random tables", + "subgroup": "Tables list", + "label": "+ new", + "loc": "src/random-tables/RandomTableView.ts:305", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables/Tables list", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RTView.generateFromFolder", + "group": "Random tables", + "subgroup": "Tables list", + "label": "Generate from folder or file (optional)…", + "loc": "src/random-tables/RandomTableView.ts:367", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:Random tables/Tables list", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RTView.newWorkflow", + "group": "Random tables", + "subgroup": "Tables list", + "label": "+ new workflow", + "loc": "src/random-tables/RandomTableView.ts:271", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables/Tables list", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RTView.workflowsTree", + "group": "Random tables", + "subgroup": "Tables list", + "label": "(workflow folder tree)", + "loc": "src/random-tables/RandomTableView.ts:735", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables/Tables list", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RTView.workflowMenuOpenNewTab", + "group": "Random tables", + "subgroup": "Tables list", + "label": "Open in new tab", + "loc": "src/random-tables/RandomTableView.ts:781", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables/Tables list", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RTView.workflowMenuDelete", + "group": "Random tables", + "subgroup": "Tables list", + "label": "Delete workflow", + "loc": "src/random-tables/RandomTableView.ts:795", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables/Tables list", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RTView.workflowMiddleClick", + "group": "Random tables", + "subgroup": "Tables list", + "label": "(middle-click a workflow)", + "loc": "src/random-tables/RandomTableView.ts:769", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables/Tables list", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RTView.edit", + "group": "Random tables", + "subgroup": "Table detail", + "label": "Edit", + "loc": "src/random-tables/RandomTableView.ts:1478", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RTView.openNote", + "group": "Random tables", + "subgroup": "Table detail", + "label": "Open note", + "loc": "src/random-tables/RandomTableView.ts:1494", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RTView.exportPdf", + "group": "Random tables", + "subgroup": "Table detail", + "label": "Export PDF", + "loc": "src/random-tables/RandomTableView.ts:1503", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RTView.exportMarkdown", + "group": "Random tables", + "subgroup": "Table detail", + "label": "Export Markdown", + "loc": "src/random-tables/RandomTableView.ts:1513", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RTView.refreshLinked", + "group": "Random tables", + "subgroup": "Table detail", + "label": "Refresh", + "loc": "src/random-tables/RandomTableView.ts:1523", + "suggestion": "overkill", + "choice": "overkill", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RTView.dieSelect", + "group": "Random tables", + "subgroup": "Table detail", + "label": "(die: — no die —, d4…d1000)", + "loc": "src/random-tables/RandomTableView.ts:1537", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RTView.fixKeepRanges", + "group": "Random tables", + "subgroup": "Table detail", + "label": "Keep ranges → set weights", + "loc": "src/random-tables/RandomTableView.ts:1428", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RTView.fixKeepWeights", + "group": "Random tables", + "subgroup": "Table detail", + "label": "Keep weights → redo ranges", + "loc": "src/random-tables/RandomTableView.ts:1431", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RTView.fixBiggerDie", + "group": "Random tables", + "subgroup": "Table detail", + "label": "Use a d", + "loc": "src/random-tables/RandomTableView.ts:1437", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RTView.fixAddRanges", + "group": "Random tables", + "subgroup": "Table detail", + "label": "Add roll ranges", + "loc": "src/random-tables/RandomTableView.ts:1445", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RTView.fixRollerLink", + "group": "Random tables", + "subgroup": "Table detail", + "label": "Replace old roller link", + "loc": "src/random-tables/RandomTableView.ts:1450", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RTView.descriptionCollapse", + "group": "Random tables", + "subgroup": "Table detail", + "label": "Collapse description (▼)", + "loc": "src/random-tables/RandomTableView.ts:1569", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RTView.tableCollapse", + "group": "Random tables", + "subgroup": "Table detail", + "label": "Collapse table (▼)", + "loc": "src/random-tables/RandomTableView.ts:1605", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RTView.entryLink", + "group": "Random tables", + "subgroup": "Table detail", + "label": "(result link)", + "loc": "src/random-tables/RandomTableView.ts:1648", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RTView.entryCopy", + "group": "Random tables", + "subgroup": "Table detail", + "label": "Copy entry (⎘)", + "loc": "src/random-tables/RandomTableView.ts:1676", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RTView.addEntriesEmpty", + "group": "Random tables", + "subgroup": "Table detail", + "label": "Add entries", + "loc": "src/random-tables/RandomTableView.ts:1622", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RTView.copyRollLink", + "group": "Random tables", + "subgroup": "Table detail", + "label": "🎲 Copy link", + "loc": "src/random-tables/RandomTableView.ts:1694", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RTView.roll", + "group": "Random tables", + "subgroup": "Table detail", + "label": "Roll", + "loc": "src/random-tables/RandomTableView.ts:1708", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RTView.resultText", + "group": "Random tables", + "subgroup": "Table detail", + "label": "(roll result)", + "loc": "src/random-tables/RandomTableView.ts:1721", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RTView.resultCopy", + "group": "Random tables", + "subgroup": "Table detail", + "label": "Copy", + "loc": "src/random-tables/RandomTableView.ts:1727", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RTView.resultOpenNote", + "group": "Random tables", + "subgroup": "Table detail", + "label": "Open note", + "loc": "src/random-tables/RandomTableView.ts:1737", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RTView.historyCopy", + "group": "Random tables", + "subgroup": "Table detail", + "label": "Copy (⎘) in Recent rolls", + "loc": "src/random-tables/RandomTableView.ts:1876", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RTView.usedByWorkflowLink", + "group": "Random tables", + "subgroup": "Table detail", + "label": "(Workflows using this table)", + "loc": "src/random-tables/RandomTableView.ts:1766", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RTView.newWorkflowWithTable", + "group": "Random tables", + "subgroup": "Table detail", + "label": "+ new workflow with this table", + "loc": "src/random-tables/RandomTableView.ts:1779", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RollModal.tableSelect", + "group": "Random tables", + "subgroup": "Rolling", + "label": "— choose a table —", + "loc": "src/random-tables/RandomTableModal.ts:116", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RollModal.openInRoller", + "group": "Random tables", + "subgroup": "Rolling", + "label": "Open in roller view", + "loc": "src/random-tables/RandomTableModal.ts:125", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RollModal.edit", + "group": "Random tables", + "subgroup": "Rolling", + "label": "Edit", + "loc": "src/random-tables/RandomTableModal.ts:184", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RollModal.roll", + "group": "Random tables", + "subgroup": "Rolling", + "label": "Roll", + "loc": "src/random-tables/RandomTableModal.ts:135", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RollModal.resultText", + "group": "Random tables", + "subgroup": "Rolling", + "label": "(roll result)", + "loc": "src/random-tables/RandomTableModal.ts:254", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RollModal.useResult", + "group": "Random tables", + "subgroup": "Rolling", + "label": "Use result", + "loc": "src/random-tables/RandomTableModal.ts:262", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RollModal.addSectionSelect", + "group": "Random tables", + "subgroup": "Rolling", + "label": "Section to add the result to", + "loc": "src/random-tables/RandomTableModal.ts:33", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RollModal.addToHex", + "group": "Random tables", + "subgroup": "Rolling", + "label": "Add to this hex", + "loc": "src/random-tables/RandomTableModal.ts:41", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RollModal.copy", + "group": "Random tables", + "subgroup": "Rolling", + "label": "Copy", + "loc": "src/random-tables/RandomTableModal.ts:280", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RollModal.entryCopy", + "group": "Random tables", + "subgroup": "Rolling", + "label": "Copy entry (⎘)", + "loc": "src/random-tables/RandomTableModal.ts:350", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RollModal.addEntries", + "group": "Random tables", + "subgroup": "Rolling", + "label": "Add entries", + "loc": "src/random-tables/RandomTableModal.ts:309", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RollModal.closeButtons", + "group": "Random tables", + "subgroup": "Rolling", + "label": "(modal ✕)", + "loc": "src/random-tables/RandomTableModal.ts:84", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RollerBlock.roll", + "group": "Random tables", + "subgroup": "Rolling", + "label": "Roll", + "loc": "src/random-tables/RollerBlock.ts:48", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RollerBlock.openTable", + "group": "Random tables", + "subgroup": "Rolling", + "label": "Open table", + "loc": "src/random-tables/RollerBlock.ts:58", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RollerBlock.resultText", + "group": "Random tables", + "subgroup": "Rolling", + "label": "(roll result)", + "loc": "src/random-tables/RollerBlock.ts:66", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RollerBlock.copy", + "group": "Random tables", + "subgroup": "Rolling", + "label": "Copy", + "loc": "src/random-tables/RollerBlock.ts:73", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RollerBlock.historyCopy", + "group": "Random tables", + "subgroup": "Rolling", + "label": "Copy (⎘)", + "loc": "src/random-tables/RollerBlock.ts:92", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TableEditor.importPicker", + "group": "Random tables", + "subgroup": "Table editor", + "label": "Search for a file to link...", + "loc": "src/random-tables/RandomTableEditorModal.ts:210", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TableEditor.name", + "group": "Random tables", + "subgroup": "Table editor", + "label": "Name", + "loc": "src/random-tables/RandomTableEditorModal.ts:94", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TableEditor.sortWeight", + "group": "Random tables", + "subgroup": "Table editor", + "label": "Wt ↑", + "loc": "src/random-tables/RandomTableEditorModal.ts:149", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TableEditor.sortAlpha", + "group": "Random tables", + "subgroup": "Table editor", + "label": "A→z", + "loc": "src/random-tables/RandomTableEditorModal.ts:166", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TableEditor.minusOneAll", + "group": "Random tables", + "subgroup": "Table editor", + "label": "-1", + "loc": "src/random-tables/RandomTableEditorModal.ts:185", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TableEditor.plusOneAll", + "group": "Random tables", + "subgroup": "Table editor", + "label": "+1", + "loc": "src/random-tables/RandomTableEditorModal.ts:194", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TableEditor.import", + "group": "Random tables", + "subgroup": "Table editor", + "label": "Import…", + "loc": "src/random-tables/RandomTableEditorModal.ts:204", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TableEditor.rowDrag", + "group": "Random tables", + "subgroup": "Table editor", + "label": "Drag to reorder (⠿)", + "loc": "src/random-tables/RandomTableEditorModal.ts:274", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TableEditor.rowResult", + "group": "Random tables", + "subgroup": "Table editor", + "label": "Result…", + "loc": "src/random-tables/RandomTableEditorModal.ts:283", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TableEditor.rowWeight", + "group": "Random tables", + "subgroup": "Table editor", + "label": "Weight (0 = never rolled)", + "loc": "src/random-tables/RandomTableEditorModal.ts:305", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TableEditor.rowDelete", + "group": "Random tables", + "subgroup": "Table editor", + "label": "Remove row (×)", + "loc": "src/random-tables/RandomTableEditorModal.ts:317", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TableEditor.newResult", + "group": "Random tables", + "subgroup": "Table editor", + "label": "New result…", + "loc": "src/random-tables/RandomTableEditorModal.ts:374", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TableEditor.newWeight", + "group": "Random tables", + "subgroup": "Table editor", + "label": "(new row weight)", + "loc": "src/random-tables/RandomTableEditorModal.ts:380", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TableEditor.add", + "group": "Random tables", + "subgroup": "Table editor", + "label": "Add", + "loc": "src/random-tables/RandomTableEditorModal.ts:387", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TableEditor.description", + "group": "Random tables", + "subgroup": "Table editor", + "label": "Description", + "loc": "src/random-tables/RandomTableEditorModal.ts:405", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TableEditor.linkedFolder", + "group": "Random tables", + "subgroup": "Table editor", + "label": "Linked folder", + "loc": "src/random-tables/RandomTableEditorModal.ts:467", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TableEditor.excludeRollPicker", + "group": "Random tables", + "subgroup": "Table editor", + "label": "Exclude from roll picker", + "loc": "src/random-tables/RandomTableEditorModal.ts:486", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TableEditor.excludeEncounters", + "group": "Random tables", + "subgroup": "Table editor", + "label": "Exclude from encounters table", + "loc": "src/random-tables/RandomTableEditorModal.ts:494", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TableEditor.closeButtons", + "group": "Random tables", + "subgroup": "Table editor", + "label": "Close", + "loc": "src/random-tables/RandomTableEditorModal.ts:640", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TableRanges.addRanges", + "group": "Random tables", + "subgroup": "Table editor", + "label": "Add ranges (a backup is made first)", + "loc": "src/random-tables/tableMaintenance.ts:260", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TableRanges.dontAskAgain", + "group": "Random tables", + "subgroup": "Table editor", + "label": "Don't ask again", + "loc": "src/random-tables/tableMaintenance.ts:268", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TableRanges.closeButtons", + "group": "Random tables", + "subgroup": "Table editor", + "label": "Not now", + "loc": "src/random-tables/tableMaintenance.ts:266", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "FolderTree.openTablesView", + "group": "Random tables", + "subgroup": "Table picker", + "label": "🎲 Open tables view", + "loc": "src/hex-map/FolderTreePickerModal.ts:85", + "suggestion": "drop", + "choice": "drop", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "FolderTree.filter", + "group": "Random tables", + "subgroup": "Table picker", + "label": "Filter tables…", + "loc": "src/hex-map/FolderTreePickerModal.ts:93", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "FolderTree.folderToggles", + "group": "Random tables", + "subgroup": "Table picker", + "label": "(folder rows)", + "loc": "src/hex-map/FolderTreePickerModal.ts:174", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "FolderTree.newTableName", + "group": "Random tables", + "subgroup": "Table picker", + "label": "table-name", + "loc": "src/hex-map/FolderTreePickerModal.ts:190", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "FolderTree.createButton", + "group": "Random tables", + "subgroup": "Table picker", + "label": "+ create", + "loc": "src/hex-map/FolderTreePickerModal.ts:194", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "FolderTree.closeButtons", + "group": "Random tables", + "subgroup": "Table picker", + "label": "×", + "loc": "src/hex-map/FolderTreePickerModal.ts:77", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RTView.workflowEdit", + "group": "Workflows", + "subgroup": "Workflow detail", + "label": "Edit", + "loc": "src/random-tables/RandomTableView.ts:924", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Workflows", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RTView.workflowRoll", + "group": "Workflows", + "subgroup": "Workflow detail", + "label": "Roll workflow", + "loc": "src/random-tables/RandomTableView.ts:955", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Workflows", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RTView.workflowCopyLink", + "group": "Workflows", + "subgroup": "Workflow detail", + "label": "🔗 Copy link", + "loc": "src/random-tables/RandomTableView.ts:963", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Workflows", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RTView.workflowStepLink", + "group": "Workflows", + "subgroup": "Workflow detail", + "label": "(step table link)", + "loc": "src/random-tables/RandomTableView.ts:1015", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Workflows", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RTView.workflowTemplateLink", + "group": "Workflows", + "subgroup": "Workflow detail", + "label": "(template link)", + "loc": "src/random-tables/RandomTableView.ts:1053", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Workflows", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorkflowEditor.name", + "group": "Workflows", + "subgroup": "Workflow editor", + "label": "Name", + "loc": "src/random-tables/WorkflowEditorModal.ts:88", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Workflows", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorkflowEditor.stepDrag", + "group": "Workflows", + "subgroup": "Workflow editor", + "label": "Drag to reorder (⠿)", + "loc": "src/random-tables/WorkflowEditorModal.ts:343", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Workflows", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorkflowEditor.stepFormula", + "group": "Workflows", + "subgroup": "Workflow editor", + "label": "E.g. 2D6+6", + "loc": "src/random-tables/WorkflowEditorModal.ts:360", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Workflows", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorkflowEditor.stepTable", + "group": "Workflows", + "subgroup": "Workflow editor", + "label": "— select table —", + "loc": "src/random-tables/WorkflowEditorModal.ts:379", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Workflows", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorkflowEditor.stepRolls", + "group": "Workflows", + "subgroup": "Workflow editor", + "label": "Number of rolls", + "loc": "src/random-tables/WorkflowEditorModal.ts:420", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Workflows", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorkflowEditor.stepLabel", + "group": "Workflows", + "subgroup": "Workflow editor", + "label": "Label…", + "loc": "src/random-tables/WorkflowEditorModal.ts:434", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Workflows", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorkflowEditor.stepDelete", + "group": "Workflows", + "subgroup": "Workflow editor", + "label": "Remove step (×)", + "loc": "src/random-tables/WorkflowEditorModal.ts:454", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Workflows", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorkflowEditor.addType", + "group": "Workflows", + "subgroup": "Workflow editor", + "label": "Table / Dice", + "loc": "src/random-tables/WorkflowEditorModal.ts:505", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Workflows", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorkflowEditor.addTable", + "group": "Workflows", + "subgroup": "Workflow editor", + "label": "— select table —", + "loc": "src/random-tables/WorkflowEditorModal.ts:543", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Workflows", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorkflowEditor.addFormula", + "group": "Workflows", + "subgroup": "Workflow editor", + "label": "E.g. 2D6+6", + "loc": "src/random-tables/WorkflowEditorModal.ts:532", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Workflows", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorkflowEditor.addRolls", + "group": "Workflows", + "subgroup": "Workflow editor", + "label": "Number of rolls", + "loc": "src/random-tables/WorkflowEditorModal.ts:572", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Workflows", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorkflowEditor.addLabel", + "group": "Workflows", + "subgroup": "Workflow editor", + "label": "Label (auto)…", + "loc": "src/random-tables/WorkflowEditorModal.ts:578", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Workflows", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorkflowEditor.addStep", + "group": "Workflows", + "subgroup": "Workflow editor", + "label": "Add step", + "loc": "src/random-tables/WorkflowEditorModal.ts:585", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Workflows", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorkflowEditor.template", + "group": "Workflows", + "subgroup": "Workflow editor", + "label": "Template", + "loc": "src/random-tables/WorkflowEditorModal.ts:145", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Workflows", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorkflowEditor.description", + "group": "Workflows", + "subgroup": "Workflow editor", + "label": "Description", + "loc": "src/random-tables/WorkflowEditorModal.ts:164", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Workflows", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorkflowEditor.resultsFolder", + "group": "Workflows", + "subgroup": "Workflow editor", + "label": "Results folder", + "loc": "src/random-tables/WorkflowEditorModal.ts:200", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Workflows", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorkflowEditor.export", + "group": "Workflows", + "subgroup": "Workflow editor", + "label": "Export…", + "loc": "src/random-tables/WorkflowEditorModal.ts:690", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Workflows", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorkflowEditor.closeButtons", + "group": "Workflows", + "subgroup": "Workflow editor", + "label": "Close", + "loc": "src/random-tables/WorkflowEditorModal.ts:696", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Workflows", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorkflowWizard.rollAll", + "group": "Workflows", + "subgroup": "Workflow wizard", + "label": "Roll all", + "loc": "src/random-tables/WorkflowWizardModal.ts:148", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Workflows", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorkflowWizard.rerollAll", + "group": "Workflows", + "subgroup": "Workflow wizard", + "label": "Reroll all", + "loc": "src/random-tables/WorkflowWizardModal.ts:155", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Workflows", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorkflowWizard.slotValue", + "group": "Workflows", + "subgroup": "Workflow wizard", + "label": "—", + "loc": "src/random-tables/WorkflowWizardModal.ts:320", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Workflows", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorkflowWizard.slotPick", + "group": "Workflows", + "subgroup": "Workflow wizard", + "label": "— pick —", + "loc": "src/random-tables/WorkflowWizardModal.ts:337", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Workflows", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorkflowWizard.slotRoll", + "group": "Workflows", + "subgroup": "Workflow wizard", + "label": "Roll / Reroll", + "loc": "src/random-tables/WorkflowWizardModal.ts:359", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Workflows", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorkflowWizard.slotSum", + "group": "Workflows", + "subgroup": "Workflow wizard", + "label": "sum", + "loc": "src/random-tables/WorkflowWizardModal.ts:381", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Workflows", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorkflowWizard.sumAll", + "group": "Workflows", + "subgroup": "Workflow wizard", + "label": "sum all", + "loc": "src/random-tables/WorkflowWizardModal.ts:301", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Workflows", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorkflowWizard.resultText", + "group": "Workflows", + "subgroup": "Workflow wizard", + "label": "Result", + "loc": "src/random-tables/WorkflowWizardModal.ts:179", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Workflows", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorkflowWizard.copyResult", + "group": "Workflows", + "subgroup": "Workflow wizard", + "label": "Copy result", + "loc": "src/random-tables/WorkflowWizardModal.ts:186", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Workflows", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorkflowWizard.addSectionSelect", + "group": "Workflows", + "subgroup": "Workflow wizard", + "label": "Section to add the result to", + "loc": "src/random-tables/RandomTableModal.ts:33", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Workflows", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorkflowWizard.addToHex", + "group": "Workflows", + "subgroup": "Workflow wizard", + "label": "Add to this hex", + "loc": "src/random-tables/WorkflowWizardModal.ts:197", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Workflows", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorkflowWizard.noteName", + "group": "Workflows", + "subgroup": "Workflow wizard", + "label": "Note name", + "loc": "src/random-tables/WorkflowWizardModal.ts:216", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Workflows", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorkflowWizard.resultsFolder", + "group": "Workflows", + "subgroup": "Workflow wizard", + "label": "Results folder", + "loc": "src/random-tables/WorkflowWizardModal.ts:244", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Workflows", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorkflowWizard.saveAsNote", + "group": "Workflows", + "subgroup": "Workflow wizard", + "label": "Save as note", + "loc": "src/random-tables/WorkflowWizardModal.ts:254", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Workflows", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorkflowWizard.closeButtons", + "group": "Workflows", + "subgroup": "Workflow wizard", + "label": "(modal ✕) / Replace confirm", + "loc": "src/random-tables/WorkflowWizardModal.ts:524", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Workflows", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapExport.mapSelect", + "group": "Export", + "subgroup": "Map export", + "label": "Map", + "loc": "src/export/MapExportModal.ts:82", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Export", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapExport.fileName", + "group": "Export", + "subgroup": "Map export", + "label": "File name", + "loc": "src/export/MapExportModal.ts:94", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Export", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapExport.showCoords", + "group": "Export", + "subgroup": "Map export", + "label": "Coordinates", + "loc": "src/export/MapExportModal.ts:108", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Export", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapExport.showIcons", + "group": "Export", + "subgroup": "Map export", + "label": "Icons", + "loc": "src/export/MapExportModal.ts:109", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Export", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapExport.showPaths", + "group": "Export", + "subgroup": "Map export", + "label": "Paths", + "loc": "src/export/MapExportModal.ts:110", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Export", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapExport.boldPaths", + "group": "Export", + "subgroup": "Map export", + "label": "Bolder paths", + "loc": "src/export/MapExportModal.ts:111", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Export", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapExport.showHexNames", + "group": "Export", + "subgroup": "Map export", + "label": "Hex names", + "loc": "src/export/MapExportModal.ts:116", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Export", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapExport.showTokens", + "group": "Export", + "subgroup": "Map export", + "label": "Tokens", + "loc": "src/export/MapExportModal.ts:117", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Export", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapExport.showLinkBadges", + "group": "Export", + "subgroup": "Map export", + "label": "Link badges", + "loc": "src/export/MapExportModal.ts:118", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Export", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapExport.showLegend", + "group": "Export", + "subgroup": "Map export", + "label": "Legend", + "loc": "src/export/MapExportModal.ts:120", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Export", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapExport.showFactionOverlay", + "group": "Export", + "subgroup": "Map export", + "label": "Faction overlay", + "loc": "src/export/MapExportModal.ts:122", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Export", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapExport.showRegionOverlay", + "group": "Export", + "subgroup": "Map export", + "label": "Region overlay", + "loc": "src/export/MapExportModal.ts:124", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:Export", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapExport.pdfColumnsFold", + "group": "Export", + "subgroup": "Map export", + "label": "PDF table columns", + "loc": "src/export/MapExportModal.ts:131", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Export", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapExport.manualFold", + "group": "Export", + "subgroup": "Map export", + "label": "Hexcrawl manual", + "loc": "src/export/MapExportModal.ts:137", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Export", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapExport.outputSize", + "group": "Export", + "subgroup": "Map export", + "label": "Output size", + "loc": "src/export/MapExportModal.ts:147", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Export", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapExport.exportPng", + "group": "Export", + "subgroup": "Map export", + "label": "Export PNG", + "loc": "src/export/MapExportModal.ts:239", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Export", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapExport.exportPdf", + "group": "Export", + "subgroup": "Map export", + "label": "Export PDF with reference table", + "loc": "src/export/MapExportModal.ts:244", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Export", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapExport.exportManual", + "group": "Export", + "subgroup": "Map export", + "label": "Export hexcrawl manual (PDF)", + "loc": "src/export/MapExportModal.ts:251", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Export", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapExport.closeButtons", + "group": "Export", + "subgroup": "Map export", + "label": "×", + "loc": "src/export/MapExportModal.ts:276", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Export", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapModal.exportForm", + "group": "Export", + "subgroup": "Map export", + "label": "(export form)", + "loc": "src/hex-map/MapModal.ts:226", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Export", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapExport.pdfColumnName", + "group": "Export", + "subgroup": "Map export: PDF table columns", + "label": "Name", + "loc": "src/export/MapExportModal.ts:134", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Export", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapExport.pdfColumnTerrain", + "group": "Export", + "subgroup": "Map export: PDF table columns", + "label": "Terrain", + "loc": "src/export/MapExportModal.ts:134", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Export", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapExport.pdfColumnTowns", + "group": "Export", + "subgroup": "Map export: PDF table columns", + "label": "Towns", + "loc": "src/export/MapExportModal.ts:134", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Export", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapExport.pdfColumnDungeons", + "group": "Export", + "subgroup": "Map export: PDF table columns", + "label": "Dungeons", + "loc": "src/export/MapExportModal.ts:134", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Export", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapExport.pdfColumnFeatures", + "group": "Export", + "subgroup": "Map export: PDF table columns", + "label": "Features", + "loc": "src/export/MapExportModal.ts:134", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Export", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapExport.pdfColumnQuests", + "group": "Export", + "subgroup": "Map export: PDF table columns", + "label": "Quests", + "loc": "src/export/MapExportModal.ts:134", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Export", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapExport.pdfColumnFactions", + "group": "Export", + "subgroup": "Map export: PDF table columns", + "label": "Factions", + "loc": "src/export/MapExportModal.ts:134", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Export", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapExport.pdfColumnEncounters", + "group": "Export", + "subgroup": "Map export: PDF table columns", + "label": "Encounters", + "loc": "src/export/MapExportModal.ts:134", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Export", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapExport.pdfColumnDescription", + "group": "Export", + "subgroup": "Map export: PDF table columns", + "label": "Description", + "loc": "src/export/MapExportModal.ts:134", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Export", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapExport.playerEdition", + "group": "Export", + "subgroup": "Map export: Hexcrawl manual", + "label": "Player version (leave out the hidden and secret sections)", + "loc": "src/export/MapExportModal.ts:139", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Export", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapExport.manualPartLegend", + "group": "Export", + "subgroup": "Map export: Hexcrawl manual", + "label": "Map legend", + "loc": "src/export/MapExportModal.ts:141", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Export", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapExport.manualPartTables", + "group": "Export", + "subgroup": "Map export: Hexcrawl manual", + "label": "Encounter tables", + "loc": "src/export/MapExportModal.ts:141", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Export", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapExport.manualPartFactions", + "group": "Export", + "subgroup": "Map export: Hexcrawl manual", + "label": "Factions and regions", + "loc": "src/export/MapExportModal.ts:141", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Export", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapExport.manualPartIndex", + "group": "Export", + "subgroup": "Map export: Hexcrawl manual", + "label": "Index", + "loc": "src/export/MapExportModal.ts:141", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Export", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexExport.fileName", + "group": "Export", + "subgroup": "Hex export", + "label": "File name", + "loc": "src/hex-map/HexExportModal.ts:55", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Export", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexExport.includeGm", + "group": "Export", + "subgroup": "Hex export", + "label": "Include game master only sections (hidden, secret)", + "loc": "src/hex-map/HexExportModal.ts:64", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Export", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexExport.exportPdf", + "group": "Export", + "subgroup": "Hex export", + "label": "Export PDF", + "loc": "src/hex-map/HexExportModal.ts:90", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Export", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexExport.exportMarkdown", + "group": "Export", + "subgroup": "Hex export", + "label": "Export Markdown", + "loc": "src/hex-map/HexExportModal.ts:101", + "suggestion": "advanced", + "choice": "simple", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "advanced (group group:Export)", + "twinOf": "", + "note": "" + }, + { + "id": "HexExport.closeButtons", + "group": "Export", + "subgroup": "Hex export", + "label": "×", + "loc": "src/hex-map/HexExportModal.ts:29", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Export", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorkflowExport.fileName", + "group": "Export", + "subgroup": "Workflow export", + "label": "File name", + "loc": "src/random-tables/WorkflowExportModal.ts:53", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Export", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorkflowExport.sampleCount", + "group": "Export", + "subgroup": "Workflow export", + "label": "Number of sample outputs", + "loc": "src/random-tables/WorkflowExportModal.ts:66", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Export", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorkflowExport.includeTemplate", + "group": "Export", + "subgroup": "Workflow export", + "label": "Include the workflow template", + "loc": "src/random-tables/WorkflowExportModal.ts:76", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Export", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorkflowExport.includeBreakdown", + "group": "Export", + "subgroup": "Workflow export", + "label": "Include the per-sample rolls breakdown", + "loc": "src/random-tables/WorkflowExportModal.ts:81", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Export", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorkflowExport.exportPdf", + "group": "Export", + "subgroup": "Workflow export", + "label": "Export PDF", + "loc": "src/random-tables/WorkflowExportModal.ts:104", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Export", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorkflowExport.exportMarkdown", + "group": "Export", + "subgroup": "Workflow export", + "label": "Export Markdown", + "loc": "src/random-tables/WorkflowExportModal.ts:112", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Export", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorkflowExport.closeButtons", + "group": "Export", + "subgroup": "Workflow export", + "label": "×", + "loc": "src/random-tables/WorkflowExportModal.ts:27", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Export", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "ConfirmModal.confirm", + "group": "Confirm dialogs", + "subgroup": "Confirm modal (shared)", + "label": "", + "loc": "src/worldgen/ConfirmModal.ts:421", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Confirm dialogs", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "ConfirmModal.closeButtons", + "group": "Confirm dialogs", + "subgroup": "Confirm modal (shared)", + "label": "Cancel", + "loc": "src/worldgen/ConfirmModal.ts:426", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Confirm dialogs", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "ConfirmDelete.delete", + "group": "Confirm dialogs", + "subgroup": "Confirm delete table modal", + "label": "Delete", + "loc": "src/random-tables/ConfirmDeleteModal.ts:451", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Confirm dialogs", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "ConfirmDelete.closeButtons", + "group": "Confirm dialogs", + "subgroup": "Confirm delete table modal", + "label": "Cancel", + "loc": "src/random-tables/ConfirmDeleteModal.ts:462", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Confirm dialogs", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenConfirm.confirm", + "group": "Confirm dialogs", + "subgroup": "Confirm dialog (Reset / Delete)", + "label": "Reset / Delete", + "loc": "src/worldgen/ConfirmModal.ts:22", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Confirm dialogs", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenConfirm.closeButtons", + "group": "Confirm dialogs", + "subgroup": "Confirm dialog (Reset / Delete)", + "label": "Cancel", + "loc": "src/worldgen/ConfirmModal.ts:27", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Confirm dialogs", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "ConfirmDelete.delete_2", + "group": "Confirm dialogs", + "subgroup": "Confirm delete modal", + "label": "Delete", + "loc": "src/random-tables/ConfirmDeleteModal.ts:19", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Confirm dialogs", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "ConfirmDelete.closeButtons_2", + "group": "Confirm dialogs", + "subgroup": "Confirm delete modal", + "label": "Cancel", + "loc": "src/random-tables/ConfirmDeleteModal.ts:30", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Confirm dialogs", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Plugin.cmd.exportContentPack", + "group": "Commands & menus", + "subgroup": "Export commands", + "label": "Export content pack...", + "loc": "src/packs/packCommands.ts", + "suggestion": "simple", + "choice": "simple", + "source": "own", + "via": "agent 2026-10-14 (SF1)", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "New 2026-10-14 (content packs, owner call SF1); not tagged by the owner yet." + }, + { + "id": "Plugin.cmd.importContentPack", + "group": "Commands & menus", + "subgroup": "Export commands", + "label": "Import content pack...", + "loc": "src/packs/packCommands.ts", + "suggestion": "simple", + "choice": "simple", + "source": "own", + "via": "agent 2026-10-14 (SF1)", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "New 2026-10-14 (content packs, owner call SF1); not tagged by the owner yet." + }, + { + "id": "Wizard.importPack", + "group": "Setup wizard", + "subgroup": "Done", + "label": "Import a content pack...", + "loc": "src/packs/packOffer.ts", + "suggestion": "simple", + "choice": "simple", + "source": "own", + "via": "agent 2026-10-14 (SF1)", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "New 2026-10-14 (content packs, owner call SF1); not tagged by the owner yet." + }, + { + "id": "MapExport.contentPack", + "group": "Export", + "subgroup": "Map export", + "label": "Export content pack...", + "loc": "src/export/MapExportModal.ts", + "suggestion": "simple", + "choice": "simple", + "source": "own", + "via": "agent 2026-10-14 (SF1)", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "New 2026-10-14 (content packs, owner call SF1); not tagged by the owner yet." + }, + { + "id": "PackExport.name", + "group": "Export", + "subgroup": "Content pack export", + "label": "Pack name", + "loc": "src/packs/PackExportModal.ts", + "suggestion": "simple", + "choice": "simple", + "source": "own", + "via": "agent 2026-10-14 (SF1)", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "New 2026-10-14 (content packs, owner call SF1); not tagged by the owner yet." + }, + { + "id": "PackExport.description", + "group": "Export", + "subgroup": "Content pack export", + "label": "Description", + "loc": "src/packs/PackExportModal.ts", + "suggestion": "simple", + "choice": "simple", + "source": "own", + "via": "agent 2026-10-14 (SF1)", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "New 2026-10-14 (content packs, owner call SF1); not tagged by the owner yet." + }, + { + "id": "PackExport.selectAll", + "group": "Export", + "subgroup": "Content pack export", + "label": "All / None", + "loc": "src/packs/PackExportModal.ts", + "suggestion": "simple", + "choice": "simple", + "source": "own", + "via": "agent 2026-10-14 (SF1)", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "New 2026-10-14 (content packs, owner call SF1); not tagged by the owner yet." + }, + { + "id": "PackExport.export", + "group": "Export", + "subgroup": "Content pack export", + "label": "Export pack", + "loc": "src/packs/PackExportModal.ts", + "suggestion": "simple", + "choice": "simple", + "source": "own", + "via": "agent 2026-10-14 (SF1)", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "New 2026-10-14 (content packs, owner call SF1); not tagged by the owner yet." + }, + { + "id": "PackImport.pickZip", + "group": "Export", + "subgroup": "Content pack import", + "label": "Choose a .zip...", + "loc": "src/packs/PackImportModal.ts", + "suggestion": "simple", + "choice": "simple", + "source": "own", + "via": "agent 2026-10-14 (SF1)", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "New 2026-10-14 (content packs, owner call SF1); not tagged by the owner yet." + }, + { + "id": "PackImport.pickFolder", + "group": "Export", + "subgroup": "Content pack import", + "label": "Choose a folder...", + "loc": "src/packs/PackImportModal.ts", + "suggestion": "simple", + "choice": "simple", + "source": "own", + "via": "agent 2026-10-14 (SF1)", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "New 2026-10-14 (content packs, owner call SF1); not tagged by the owner yet." + }, + { + "id": "PackImport.vaultZips", + "group": "Export", + "subgroup": "Content pack import", + "label": "Packs in this vault", + "loc": "src/packs/PackImportModal.ts", + "suggestion": "simple", + "choice": "simple", + "source": "own", + "via": "agent 2026-10-14 (SF1)", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "New 2026-10-14 (content packs, owner call SF1); not tagged by the owner yet." + }, + { + "id": "PackImport.conflictAll", + "group": "Export", + "subgroup": "Content pack import", + "label": "Notes already here: Skip / Keep both / Replace", + "loc": "src/packs/PackImportModal.ts", + "suggestion": "simple", + "choice": "simple", + "source": "own", + "via": "agent 2026-10-14 (SF1)", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "New 2026-10-14 (content packs, owner call SF1); not tagged by the owner yet." + }, + { + "id": "PackImport.import", + "group": "Export", + "subgroup": "Content pack import", + "label": "Import", + "loc": "src/packs/PackImportModal.ts", + "suggestion": "simple", + "choice": "simple", + "source": "own", + "via": "agent 2026-10-14 (SF1)", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "New 2026-10-14 (content packs, owner call SF1); not tagged by the owner yet." + } +] \ No newline at end of file diff --git a/dev/ui-inventory/inputs-tags-summary.md b/dev/ui-inventory/inputs-tags-summary.md new file mode 100644 index 00000000..694b1a6f --- /dev/null +++ b/dev/ui-inventory/inputs-tags-summary.md @@ -0,0 +1,226 @@ +# inputs-tags: resolved picks + +- Submission: `inputs-tags.json`, submitted 2026-10-11T21:22:52.655Z +- 1142 items: 72 own, 1055 group, 15 twin, 0 suggestion-unreviewed +- Group-level picks: 31 + +## Effective choice by source + +| choice | own | group | twin | suggestion-unreviewed | total | +|---|---|---|---|---|---| +| Keep | 15 | 847 | 13 | 0 | 875 | +| Simple | 22 | 72 | 0 | 0 | 94 | +| Adv. | 24 | 68 | 2 | 0 | 94 | +| Overkill | 11 | 47 | 0 | 0 | 58 | +| Drop | 0 | 21 | 0 | 0 | 21 | + +## By section + +| section | items | reviewed | Keep | Simple | Adv. | Overkill | Drop | +|---|---|---|---|---|---|---|---| +| Settings › Setup & feature switches | 9 | 9 | 9 | 0 | 0 | 0 | 0 | +| Settings › Look & labels | 10 | 10 | 1 | 9 | 0 | 0 | 0 | +| Settings › Defaults | 10 | 10 | 1 | 4 | 5 | 0 | 0 | +| Settings › Folders | 16 | 16 | 2 | 0 | 11 | 3 | 0 | +| Settings › Palette management | 12 | 12 | 2 | 7 | 3 | 0 | 0 | +| Settings › Maintenance | 2 | 2 | 0 | 0 | 0 | 2 | 0 | +| Settings › Legacy (pre-1.13) | 11 | 11 | 0 | 1 | 4 | 6 | 0 | +| Setup wizard › Welcome | 3 | 3 | 3 | 0 | 0 | 0 | 0 | +| Setup wizard › Folders | 13 | 13 | 12 | 0 | 1 | 0 | 0 | +| Setup wizard › Map | 12 | 12 | 7 | 0 | 5 | 0 | 0 | +| Setup wizard › Done | 2 | 2 | 2 | 0 | 0 | 0 | 0 | +| Setup wizard › Navigation | 4 | 4 | 4 | 0 | 0 | 0 | 0 | +| Feature hints › Inline hints | 3 | 3 | 3 | 0 | 0 | 0 | 0 | +| Feature hints › More options modal | 3 | 3 | 3 | 0 | 0 | 0 | 0 | +| Feature hints › Turn on ? modal | 3 | 3 | 3 | 0 | 0 | 0 | 0 | +| Feature hints › Ready for more? modal | 3 | 3 | 3 | 0 | 0 | 0 | 0 | +| Commands & menus › Open views | 9 | 9 | 5 | 4 | 0 | 0 | 0 | +| Commands & menus › Map navigation commands | 3 | 3 | 3 | 0 | 0 | 0 | 0 | +| Commands & menus › Maintenance commands | 4 | 4 | 0 | 0 | 0 | 4 | 0 | +| Commands & menus › Export commands | 5 | 5 | 0 | 2 | 3 | 0 | 0 | +| Commands & menus › Note right-click menus | 6 | 6 | 4 | 0 | 2 | 0 | 0 | +| Hex map view › Top bar | 9 | 9 | 6 | 3 | 0 | 0 | 0 | +| Hex map view › Map navigation | 9 | 9 | 9 | 0 | 0 | 0 | 0 | +| Hex map view › Work modes | 10 | 10 | 3 | 5 | 2 | 0 | 0 | +| Hex map view › Drawing tools | 11 | 11 | 5 | 2 | 4 | 0 | 0 | +| Hex map view › Tool right-click menus | 21 | 21 | 16 | 2 | 2 | 0 | 1 | +| Hex map view › Hex right-click menu | 15 | 15 | 14 | 1 | 0 | 0 | 0 | +| Hex map view › Overworld menu & minimap | 21 | 21 | 21 | 0 | 0 | 0 | 0 | +| Hex map view › Token right-click menu | 4 | 4 | 2 | 2 | 0 | 0 | 0 | +| Hex map view › Layers panel | 25 | 25 | 21 | 3 | 1 | 0 | 0 | +| Hex map view › Legend, grid edges & notices | 7 | 7 | 5 | 2 | 0 | 0 | 0 | +| Hex map view › Mouse & keyboard | 25 | 25 | 22 | 1 | 0 | 0 | 2 | +| Hex editor › Header | 17 | 17 | 15 | 1 | 0 | 0 | 1 | +| Hex editor › Section headers | 4 | 4 | 4 | 0 | 0 | 0 | 0 | +| Hex editor › Terrain | 6 | 6 | 6 | 0 | 0 | 0 | 0 | +| Hex editor › Notes | 23 | 23 | 19 | 0 | 4 | 0 | 0 | +| Hex editor › Linked notes | 31 | 31 | 30 | 1 | 0 | 0 | 0 | +| Hex editor › Icons | 10 | 10 | 10 | 0 | 0 | 0 | 0 | +| Hex table › Toolbar | 15 | 15 | 10 | 0 | 4 | 1 | 0 | +| Hex table › Rows & cells | 16 | 16 | 16 | 0 | 0 | 0 | 0 | +| Hex table › Terrain filter | 10 | 10 | 9 | 0 | 1 | 0 | 0 | +| Hex table › Linking | 8 | 8 | 8 | 0 | 0 | 0 | 0 | +| Map pickers & editors › Icons | 12 | 12 | 11 | 1 | 0 | 0 | 0 | +| Map pickers & editors › Tokens | 19 | 19 | 11 | 7 | 1 | 0 | 0 | +| Map pickers & editors › Path types | 25 | 25 | 19 | 3 | 2 | 1 | 0 | +| Map pickers & editors › Go to hex & help | 5 | 5 | 5 | 0 | 0 | 0 | 0 | +| Map pickers & editors › Locations | 8 | 8 | 7 | 0 | 0 | 0 | 1 | +| Map pickers & editors › Factions | 16 | 16 | 11 | 5 | 0 | 0 | 0 | +| Map pickers & editors › Terrain | 25 | 25 | 23 | 1 | 0 | 1 | 0 | +| Maps modal › Tabs & general | 6 | 6 | 6 | 0 | 0 | 0 | 0 | +| Maps modal › Maps list | 8 | 8 | 6 | 0 | 2 | 0 | 0 | +| Maps modal › Properties | 10 | 10 | 3 | 3 | 2 | 2 | 0 | +| Maps modal › Neighbouring regions | 6 | 6 | 6 | 0 | 0 | 0 | 0 | +| Maps modal › Weather & rumours | 4 | 4 | 0 | 0 | 4 | 0 | 0 | +| Maps modal › Background image | 5 | 5 | 4 | 0 | 1 | 0 | 0 | +| Maps modal › Regions tab | 5 | 5 | 5 | 0 | 0 | 0 | 0 | +| New maps & map links › New map form | 18 | 18 | 14 | 0 | 4 | 0 | 0 | +| New maps & map links › New map form: More | 6 | 6 | 0 | 1 | 4 | 1 | 0 | +| New maps & map links › Generator options (world) | 13 | 13 | 6 | 0 | 7 | 0 | 0 | +| New maps & map links › Generator options (space) | 8 | 8 | 6 | 0 | 2 | 0 | 0 | +| New maps & map links › New map from a hex | 4 | 4 | 4 | 0 | 0 | 0 | 0 | +| New maps & map links › New land beside a map | 13 | 13 | 12 | 0 | 0 | 1 | 0 | +| New maps & map links › Link submap & insert map link | 11 | 11 | 11 | 0 | 0 | 0 | 0 | +| New maps & map links › Link submap: inline create form | 10 | 10 | 0 | 0 | 0 | 0 | 10 | +| New maps & map links › Dead code | 3 | 3 | 0 | 0 | 0 | 0 | 3 | +| Regions, overworlds & biomes › Missing regions & go to region | 4 | 4 | 4 | 0 | 0 | 0 | 0 | +| Regions, overworlds & biomes › New overworld | 19 | 19 | 18 | 0 | 0 | 1 | 0 | +| Regions, overworlds & biomes › Biome pools | 10 | 10 | 10 | 0 | 0 | 0 | 0 | +| Regions, overworlds & biomes › Biome library & biome form | 29 | 29 | 27 | 0 | 0 | 1 | 1 | +| Regions, overworlds & biomes › Biome picker & paint | 7 | 7 | 6 | 1 | 0 | 0 | 0 | +| Regions, overworlds & biomes › Region settings | 15 | 15 | 13 | 0 | 0 | 2 | 0 | +| Regions, overworlds & biomes › Edit region | 12 | 12 | 7 | 5 | 0 | 0 | 0 | +| Regions, overworlds & biomes › Region areas | 10 | 10 | 10 | 0 | 0 | 0 | 0 | +| Space: world types › General | 14 | 14 | 14 | 0 | 0 | 0 | 0 | +| Space: world types › Worlds tab | 12 | 12 | 10 | 0 | 0 | 2 | 0 | +| Space: world types › Stars tab | 3 | 3 | 3 | 0 | 0 | 0 | 0 | +| Space: world types › Sector features tab | 3 | 3 | 3 | 0 | 0 | 0 | 0 | +| Space: world types › Preview | 5 | 5 | 0 | 0 | 0 | 5 | 0 | +| Generator page › Library | 13 | 13 | 13 | 0 | 0 | 0 | 0 | +| Generator page › Recipe | 25 | 25 | 25 | 0 | 0 | 0 | 0 | +| Generator page › Preview & saves | 11 | 11 | 9 | 0 | 0 | 2 | 0 | +| Generator page › Engine tuning | 15 | 15 | 4 | 0 | 0 | 11 | 0 | +| Generator page › Paths | 14 | 14 | 6 | 0 | 0 | 8 | 0 | +| Generator page › Biome (blend field) | 21 | 21 | 19 | 0 | 0 | 1 | 1 | +| Generator page › Make generator from a map | 6 | 6 | 6 | 0 | 0 | 0 | 0 | +| Palette editor › Toolbar | 4 | 4 | 4 | 0 | 0 | 0 | 0 | +| Palette editor › Terrains | 12 | 12 | 12 | 0 | 0 | 0 | 0 | +| Palette editor › Palette settings & path types | 3 | 3 | 3 | 0 | 0 | 0 | 0 | +| Palette editor › Submap defaults | 9 | 9 | 8 | 0 | 0 | 1 | 0 | +| Random tables › Tables list | 25 | 25 | 18 | 1 | 5 | 1 | 0 | +| Random tables › Table detail | 24 | 24 | 21 | 1 | 1 | 1 | 0 | +| Random tables › Rolling | 17 | 17 | 15 | 2 | 0 | 0 | 0 | +| Random tables › Table editor | 22 | 22 | 16 | 0 | 6 | 0 | 0 | +| Random tables › Table picker | 6 | 6 | 5 | 0 | 0 | 0 | 1 | +| Workflows › Workflow detail | 5 | 5 | 5 | 0 | 0 | 0 | 0 | +| Workflows › Workflow editor | 18 | 18 | 18 | 0 | 0 | 0 | 0 | +| Workflows › Workflow wizard | 15 | 15 | 15 | 0 | 0 | 0 | 0 | +| Export › Map export | 20 | 20 | 12 | 7 | 1 | 0 | 0 | +| Export › Map export: PDF table columns | 9 | 9 | 9 | 0 | 0 | 0 | 0 | +| Export › Map export: Hexcrawl manual | 5 | 5 | 0 | 5 | 0 | 0 | 0 | +| Export › Hex export | 5 | 5 | 4 | 1 | 0 | 0 | 0 | +| Export › Workflow export | 7 | 7 | 7 | 0 | 0 | 0 | 0 | +| Confirm dialogs › Confirm modal (shared) | 2 | 2 | 2 | 0 | 0 | 0 | 0 | +| Confirm dialogs › Confirm delete table modal | 2 | 2 | 2 | 0 | 0 | 0 | 0 | +| Confirm dialogs › Confirm dialog (Reset / Delete) | 2 | 2 | 2 | 0 | 0 | 0 | 0 | +| Confirm dialogs › Confirm delete modal | 2 | 2 | 2 | 0 | 0 | 0 | 0 | + +## Group-level picks and notes + +- `Setup wizard/Welcome`: **Keep** +- `Setup wizard/Folders`: **use suggestions** +- `Setup wizard/Map`: **use suggestions** +- `Setup wizard/Done`: **use suggestions** +- `Setup wizard/Navigation`: **use suggestions** +- `Feature hints/Inline hints`: **use suggestions** +- `Feature hints/More options modal`: **use suggestions** +- `Feature hints/Turn on ? modal`: **use suggestions** +- `Feature hints/Ready for more? modal`: **use suggestions** +- `Commands & menus/Open views`: **use suggestions** +- `Commands & menus/Map navigation commands`: **use suggestions** +- `Commands & menus/Maintenance commands`: **use suggestions** +- `Commands & menus/Export commands`: **use suggestions** +- `Commands & menus/Note right-click menus`: **use suggestions** +- `Hex map view`: **use suggestions** +- `New maps & map links`: **use suggestions** +- `Hex editor/Section headers`: **use suggestions** +- `Hex editor`: **use suggestions** +- `Hex table`: **use suggestions** +- `Map pickers & editors`: **use suggestions** +- `Maps modal`: **use suggestions** +- `Regions, overworlds & biomes`: **use suggestions** +- `Space: world types`: **use suggestions** +- `Generator page`: **use suggestions** +- `Generator page/Engine tuning`: **use suggestions** +- `Palette editor`: **use suggestions** +- `Random tables/Tables list`: **use suggestions** +- `Random tables`: **use suggestions** +- `Workflows`: **use suggestions** +- `Export`: **use suggestions** +- `Confirm dialogs`: **use suggestions** + +## Item notes (verbatim) + +- `Settings.generateWorldData` (Generate; Overkill, own): "but note this might need to be surfaced in the case of debugging etc, we might need to point users to "all" if "health"/"repair" type settings hide there. " +- `Settings.legacyCoordLabelSize` (Coordinate label (slider); Overkill, own): "this and other stuff like it should just map to the same setting ideally. " +- `Settings.legacyPaletteDeleteButton` (Delete; Simple, own): "i think custom palettes should be simple. We want a streamlined but still customizable experience for simple, not to hide every little possible scary thing. " +- `WorkModeMenu.god` (God: Change anything…; Adv., own): "Yes but ask to enable it and other things when they start poking around region/generators/etc." +- `HexEditor.neighborCentreDot` (Centre dot; Drop, group): "do these actually link directly to a given hex? If a map is big enough I could see wanting to let a note direct-link a centered view on it, if this is the case then we should consider keeping this, maybe even as simple. " +- `NewOverworld.seed` (Seed; Overkill, group): "just make sure its saved for the saved rolls etc, its fine if it shows up on saves too. " +- `GenPage.clumping` (Clumping; Overkill, group): "Engine tuning should have its own separate overkill setting. Basically all these ones marked "overkill" for generator settings should go into an "advanced" dropdown that defaults closed rather than them being gated under the global overkill setting. That way people can muck about with them when they wanna go a bit further on one gen or another, instead of having to flip and stick with a top-level setting. " +- `GenPage.pathTypeFold` ((show routes chevron); Overkill, group): "ditto for the above, make sure these go into an "advanced" section, Maybe the advanced section can have collapsible sub-sections as well so its clean to view. " +- `RTView.refreshList` (Refresh list (↺); Overkill, group): "we should confirm that it does it at a good cadence for all of these "sink refresh" bits " + +## Overrides (own pick differs from group/twin) + +- `Settings.legacyCoordLabelSize`: Overkill instead of simple (twin Settings.coordFontSize) +- `Settings.legacyCoordLabelFont`: Overkill instead of simple (twin Settings.coordFontFamily) +- `Settings.legacyCoordLabelColor`: Overkill instead of simple (twin Settings.coordFontColor) +- `Settings.legacyHexNameFont`: Overkill instead of simple (twin Settings.hexNameFont) +- `Settings.legacyHexNameSize`: Overkill instead of simple (twin Settings.hexNameSize) +- `Settings.legacyHexNameStyle`: Overkill instead of simple (twin Settings.hexNameStyle) +- `Settings.legacyPaletteDeleteButton`: Simple instead of advanced (twin Settings.paletteDelete) +- `HexExport.exportMarkdown`: Simple instead of advanced (group group:Export) + +## Twins picked differently (decide: follow the twin or keep both) + +- `Settings.legacyCoordLabelSize` = Overkill, but its twin `Settings.coordFontSize` = Simple +- `Settings.legacyCoordLabelFont` = Overkill, but its twin `Settings.coordFontFamily` = Simple +- `Settings.legacyCoordLabelColor` = Overkill, but its twin `Settings.coordFontColor` = Simple +- `Settings.legacyHexNameFont` = Overkill, but its twin `Settings.hexNameFont` = Simple +- `Settings.legacyHexNameSize` = Overkill, but its twin `Settings.hexNameSize` = Simple +- `Settings.legacyHexNameStyle` = Overkill, but its twin `Settings.hexNameStyle` = Simple +- `Settings.legacyPaletteDeleteButton` = Simple, but its twin `Settings.paletteDelete` = Adv. + +## Reviewed and different from the suggestion + +- `Settings.staggerOffset` (Stagger offset): suggested Adv., now Simple (own) +- `Settings.coordPlacement` (Coordinate placement): suggested Adv., now Simple (own) +- `Settings.coordFontSize` (Coordinate label size): suggested Overkill, now Simple (own) +- `Settings.coordFontFamily` (Coordinate label font): suggested Overkill, now Simple (own) +- `Settings.coordFontColor` (Coordinate label color): suggested Overkill, now Simple (own) +- `Settings.hexNameFont` (Hex name font): suggested Overkill, now Simple (own) +- `Settings.hexNameSize` (Hex name size): suggested Overkill, now Simple (own) +- `Settings.hexNameStyle` (Hex name style): suggested Overkill, now Simple (own) +- `Settings.hexGap` (Hex cell spacing): suggested Adv., now Simple (own) +- `Settings.defaultTableDice` (Default die for new tables): suggested Adv., now Simple (own) +- `Settings.collapseTerrain` (Terrain): suggested Adv., now Simple (own) +- `Settings.collapseFeatures` (Features): suggested Adv., now Simple (own) +- `Settings.collapseNotes` (Notes): suggested Adv., now Simple (own) +- `Settings.defaultPalette` (Palette for new maps): suggested Adv., now Simple (own) +- `Settings.paletteRowName` ((palette name)): suggested Adv., now Simple (own) +- `Settings.paletteRowEdit` (Edit): suggested Adv., now Simple (own) +- `Settings.addPalette` (Add palette): suggested Adv., now Simple (own) +- `Settings.legacyPaletteDeleteButton` (Delete): suggested Adv., now Simple (own) +- `HexExport.exportMarkdown` (Export Markdown): suggested Adv., now Simple (own) + +## Apply list (reviewed, not keep) + +Hand-off input for implementation: one line per tier, ids only. + +- **Simple** (94): `Settings.staggerOffset`, `Settings.coordPlacement`, `Settings.coordFontSize`, `Settings.coordFontFamily`, `Settings.coordFontColor`, `Settings.hexNameFont`, `Settings.hexNameSize`, `Settings.hexNameStyle`, `Settings.hexGap`, `Settings.defaultTableDice`, `Settings.collapseTerrain`, `Settings.collapseFeatures`, `Settings.collapseNotes`, `Settings.defaultPalette`, `Settings.paletteRowName`, `Settings.paletteRowEdit`, `Settings.addPalette`, `AddPalette.presetOption`, `AddPalette.copyOption`, `AddPalette.emptyPalette`, `Settings.legacyPaletteDeleteButton`, `Plugin.ribbonOpenHexMap`, `Plugin.cmd.openHexTable`, `Plugin.cmd.openPaletteEditor`, `Plugin.cmd.openRandomTables`, `Plugin.cmd.exportCurrentHex`, `Plugin.cmd.exportCurrentMap`, `MapToolbar.hexTableBtn`, `MapToolbar.randomTablesBtn`, `MapToolbar.workModeBtn`, `WorkModeMenu.play`, `WorkModeMenu.build`, `ModeBar.autoRoute`, `ModeBar.newPath`, `ModeBar.done`, `DrawingPanel.path`, `DrawingPanel.token`, `PathMenu.deletePath`, `PathMenu.rename`, `HexMenu.createToken`, `TokenMenu.edit`, `TokenMenu.remove`, `LayersMenu.nameFontBtn`, `LayersMenu.badgeSize`, `LayersMenu.badgeTypesMore`, `Legend.size`, `MapGrid.shrink`, `MapView.tokenDrag`, `HexEditor.exportHex`, `HexEditor.encountersRoll`, `IconPicker.manageIcons`, `Token.iconGrid`, `Token.shape`, `Token.size`, `Token.fillColor`, `Token.borderToggle`, `Token.borderColor`, `Token.saveButton`, `PathPicker.editToggle`, `PathPicker.drawMode`, `PathPicker.typeGrid`, `FactionEditor.pattern`, `FactionEditor.patternScale`, `FactionEditor.opacity`, `FactionEditor.outlineWidth`, `FactionEditor.clearColor`, `TerrainPicker.editToggle`, `MapModal.propsStagger`, `MapModal.propsDelete`, `MapModal.propsDeleteConfirm`, `NewMap.stagger`, `BiomePicker.enterRegion`, `EditRegion.name`, `EditRegion.enterRegion`, `EditRegion.openMapNote`, `EditRegion.locationsList`, `EditRegion.notes`, `RTView.tablesTree`, `RTView.roll`, `RollModal.roll`, `RollerBlock.roll`, `MapExport.boldPaths`, `MapExport.showLinkBadges`, `MapExport.showFactionOverlay`, `MapExport.pdfColumnsFold`, `MapExport.exportPng`, `MapExport.exportPdf`, `MapExport.exportManual`, `MapExport.playerEdition`, `MapExport.manualPartLegend`, `MapExport.manualPartTables`, `MapExport.manualPartFactions`, `MapExport.manualPartIndex`, `HexExport.exportMarkdown` +- **Adv.** (94): `Settings.templatePath`, `Settings.defaultNewMapCols`, `Settings.defaultNewMapRows`, `Settings.defaultSubmapCols`, `Settings.defaultSubmapRows`, `Settings.hexFolder`, `Settings.townsFolder`, `Settings.dungeonsFolder`, `Settings.questsFolder`, `Settings.featuresFolder`, `Settings.factionsFolder`, `Settings.regionsFolder`, `Settings.tablesFolder`, `Settings.workflowsFolder`, `Settings.templatesFolder`, `Settings.palettesFolder`, `Settings.addDefaultPalettes`, `Settings.paletteRowOpenNote`, `Settings.paletteDelete`, `Settings.legacyNewMapCols`, `Settings.legacyNewMapRows`, `Settings.legacySubmapCols`, `Settings.legacySubmapRows`, `Wizard.configureFoldersIndividually`, `Wizard.genOptWater`, `Wizard.genOptClimate`, `Wizard.genOptRelief`, `Wizard.genOptSea`, `Wizard.genOptOther`, `Plugin.cmd.exportNotePdf`, `Plugin.cmd.exportNoteMarkdown`, `Plugin.cmd.exportCurrentWorkflow`, `Plugin.fileMenuExportPdf`, `Plugin.fileMenuExportMarkdown`, `WorkModeMenu.god`, `ModeBar.crossImpassable`, `DrawingPanel.linkTable`, `DrawingPanel.linkSubmap`, `DrawingPanel.regionAreas`, `MapView.tableLinkToolPicker`, `PathMenu.splitHere`, `PathMenu.reverse`, `LayersMenu.regionOverlay`, `HexEditor.weatherSource`, `HexEditor.hooksSource`, `HexEditor.rolledSetMapTable`, `HexEditor.rolledSetHexTable`, `HexTable.xMin`, `HexTable.xMax`, `HexTable.yMin`, `HexTable.yMax`, `TerrainFilter.typeRow`, `Token.description`, `PathPicker.pathsOnMap`, `PathType.carves`, `MapModal.mapRowContextGenerator`, `MapModal.mapRowContextMakeGenerator`, `MapProps.sectionTablePicker`, `MapModal.propsTerrainTheme`, `MapModal.propsWeatherTable`, `MapModal.propsWeatherClear`, `MapModal.propsRumoursTable`, `MapModal.propsRumoursClear`, `MapProps.backgroundImagePicker`, `NewMap.rememberPalette`, `NewMap.rememberSize`, `NewMap.rememberGenerator`, `NewMap.rememberBase`, `NewMapSetup.backgroundImagePicker`, `NewMap.startCoords`, `NewMap.bgPick`, `NewMap.bgClear`, `NewMap.overlandWater`, `NewMap.overlandClimate`, `NewMap.overlandRelief`, `NewMap.overlandSea`, `NewMap.planetRelief`, `NewMap.regionDetailInfluence`, `NewMap.regionDetailVariety`, `NewMap.starRouteType`, `NewMap.orbitsPathType`, `RTView.folderMenuRollPicker`, `RTView.folderMenuEncounters`, `RTView.fileMenuRollPicker`, `RTView.fileMenuEncounters`, `RTView.generateFromFolder`, `RTView.copyRollLink`, `TableEditor.minusOneAll`, `TableEditor.plusOneAll`, `TableEditor.import`, `TableEditor.linkedFolder`, `TableEditor.excludeRollPicker`, `TableEditor.excludeEncounters`, `MapExport.showRegionOverlay` +- **Overkill** (58): `Settings.biomesFolder`, `Settings.biomePoolsFolder`, `Settings.worldTypesFolder`, `Settings.generateWorldData`, `Settings.generateFolders`, `Settings.legacyCoordLabelSize`, `Settings.legacyCoordLabelFont`, `Settings.legacyCoordLabelColor`, `Settings.legacyHexNameFont`, `Settings.legacyHexNameSize`, `Settings.legacyHexNameStyle`, `Plugin.cmd.addRollRanges`, `Plugin.cmd.checkTables`, `Plugin.cmd.addMapDataToHexNotes`, `Plugin.cmd.updateRegionFactionMapData`, `HexTable.refresh`, `PathType.carveWidth`, `TerrainPicker.refreshEncounterLinks`, `MapModal.propsFolderName`, `MapModal.propsRenameFolder`, `NewMap.folderName`, `WalkOW.seed`, `NewOverworld.seed`, `BiomeForm.chance`, `RegionGen.wigglyBorders`, `RegionGen.seed`, `WorldTypes.worldGenerator`, `WorldTypes.worldOptions`, `WorldTypes.previewMap`, `WorldTypes.previewOrbit`, `WorldTypes.previewStar`, `WorldTypes.previewTemperature`, `WorldTypes.previewRolls`, `GenPage.seed`, `GenPage.seedLock`, `GenPage.clumping`, `GenPage.edgeSmoothing`, `GenPage.removeSmallPatches`, `GenPage.keepRare`, `GenPage.edgeStrength`, `GenPage.directionalBias`, `GenPage.scatter`, `GenPage.spacing`, `GenPage.randomness`, `GenPage.near`, `GenPage.mixStrength`, `GenPage.pathTypeFold`, `GenPage.pathTypeAvoid`, `GenPage.routeOn`, `GenPage.routeCount`, `GenPage.routeAs`, `GenPage.routeWiggle`, `GenPage.routeLength`, `GenPage.routeFollow`, `BiomePage.seed`, `PaletteEditor.generatorOptions`, `RTView.refreshList`, `RTView.refreshLinked` +- **Drop** (21): `PainterMenu.newPath`, `MapView.dblRightClickExit`, `MapView.dblClickOffGridExit`, `HexEditor.neighborCentreDot`, `Locations.openButton`, `SubmapPicker.createSection`, `SubmapPicker.createName`, `SubmapPicker.createCols`, `SubmapPicker.createRows`, `SubmapPicker.createPalette`, `SubmapPicker.createStartX`, `SubmapPicker.createStartY`, `SubmapPicker.createStagger`, `SubmapPicker.createTerrainTheme`, `SubmapPicker.createAndLink`, `NewMapFields.name`, `NewMapFields.size`, `NewMapFields.palette`, `BiomeForm.mixNumber`, `BiomePage.weightNumber`, `FolderTree.openTablesView` + +Unreviewed items whose suggestion is not keep: 0 (not in the apply list; they need a decision first). diff --git a/dev/ui-inventory/inputs-tags.html b/dev/ui-inventory/inputs-tags.html new file mode 100644 index 00000000..f8e5475f --- /dev/null +++ b/dev/ui-inventory/inputs-tags.html @@ -0,0 +1,501 @@ + + + +loading + + +

+

+
+
+ + + + +
+
+
+ diff --git a/dev/ui-inventory/items.json b/dev/ui-inventory/items.json new file mode 100644 index 00000000..8641d9a7 --- /dev/null +++ b/dev/ui-inventory/items.json @@ -0,0 +1,18398 @@ +[ + { + "id": "Settings.rerunSetupWizard", + "surface": "Settings tab", + "label": "Re-run setup wizard", + "kind": "button", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:247", + "desc": "Reopens the first-run setup wizard (both paths).", + "pick": "keep", + "why": "Easy way back to the guided start.", + "lists": "", + "focused": null, + "mix": "", + "group": "Settings", + "subgroup": "Setup & feature switches" + }, + { + "id": "Settings.featureLevel", + "surface": "Settings tab: Features", + "label": "Feature level", + "kind": "dropdown", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:894", + "desc": "Simple or Advanced; hides/shows power tools (both paths).", + "pick": "keep", + "why": "The master switch; natural home for a third 'All' level.", + "lists": "Simple, Advanced", + "focused": true, + "mix": "", + "group": "Settings", + "subgroup": "Setup & feature switches" + }, + { + "id": "Settings.featureGenerators", + "surface": "Settings tab: Features", + "label": "Terrain generators", + "kind": "toggle", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:906", + "desc": "Turns on terrain generators alone while in Simple; greyed out in Advanced.", + "pick": "keep", + "why": "This switch is how a Simple user turns on one power feature without going full Advanced; hiding it removes that ramp.", + "lists": "", + "focused": null, + "mix": "", + "group": "Settings", + "subgroup": "Setup & feature switches" + }, + { + "id": "Settings.featureWorkflows", + "surface": "Settings tab: Features", + "label": "Workflows", + "kind": "toggle", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:906", + "desc": "Turns on workflows alone while in Simple; greyed out in Advanced.", + "pick": "keep", + "why": "This switch is how a Simple user turns on one power feature without going full Advanced; hiding it removes that ramp.", + "lists": "", + "focused": null, + "mix": "", + "group": "Settings", + "subgroup": "Setup & feature switches" + }, + { + "id": "Settings.featurePalettes", + "surface": "Settings tab: Features", + "label": "Custom palettes", + "kind": "toggle", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:906", + "desc": "Turns on custom palettes alone while in Simple; greyed out in Advanced.", + "pick": "keep", + "why": "This switch is how a Simple user turns on one power feature without going full Advanced; hiding it removes that ramp.", + "lists": "", + "focused": null, + "mix": "", + "group": "Settings", + "subgroup": "Setup & feature switches" + }, + { + "id": "Settings.featureRegions", + "surface": "Settings tab: Features", + "label": "Regions and overworlds", + "kind": "toggle", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:906", + "desc": "Turns on regions/overworlds alone while in Simple; greyed out in Advanced.", + "pick": "keep", + "why": "This switch is how a Simple user turns on one power feature without going full Advanced; hiding it removes that ramp.", + "lists": "", + "focused": null, + "mix": "", + "group": "Settings", + "subgroup": "Setup & feature switches" + }, + { + "id": "Settings.showHintsAgain", + "surface": "Settings tab: Features", + "label": "Show hints again", + "kind": "button", + "level": "conditional: some hints were closed", + "loc": "src/HexmakerSettingTab.ts:923", + "desc": "Brings back closed 'turn on advanced feature' hints (both paths).", + "pick": "keep", + "why": "Only appears after hints were closed; it's the way back to the Simple-user ramp.", + "lists": "", + "focused": null, + "mix": "", + "group": "Settings", + "subgroup": "Setup & feature switches" + }, + { + "id": "Settings.mapKindWorld", + "surface": "Settings tab: Map types", + "label": "World / fantasy overland", + "kind": "toggle", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:695", + "desc": "Turns fantasy overland palettes, generators, icons on/off (both paths).", + "pick": "keep", + "why": "Core content switch; keeps unrelated content out.", + "lists": "", + "focused": null, + "mix": "", + "group": "Settings", + "subgroup": "Setup & feature switches" + }, + { + "id": "Settings.mapKindSpace", + "surface": "Settings tab: Map types", + "label": "Space", + "kind": "toggle", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:695", + "desc": "Turns space palettes, generators and icons on/off (both paths).", + "pick": "keep", + "why": "Core content switch.", + "lists": "", + "focused": null, + "mix": "", + "group": "Settings", + "subgroup": "Setup & feature switches" + }, + { + "id": "Settings.hexOrientation", + "surface": "Settings tab", + "label": "Hex orientation", + "kind": "dropdown", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:310", + "desc": "Pointy-top or flat-top hexes (both paths).", + "pick": "keep", + "why": "Basic map look; also asked in the wizard.", + "lists": "Pointy-top, Flat-top", + "focused": true, + "mix": "", + "group": "Settings", + "subgroup": "Look & labels" + }, + { + "id": "Settings.staggerOffset", + "surface": "Settings tab", + "label": "Stagger offset", + "kind": "button", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:320", + "desc": "Odd/Even toggle button: which rows/columns shift half a hex (both paths).", + "pick": "advanced", + "why": "Grid geometry choice beyond the basics; maps can also set it themselves.", + "lists": "", + "focused": null, + "mix": "", + "group": "Settings", + "subgroup": "Look & labels" + }, + { + "id": "Settings.coordPlacement", + "surface": "Settings tab", + "label": "Coordinate placement", + "kind": "dropdown", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:339", + "desc": "Where the hex coordinate label sits: top, middle, bottom (both paths).", + "pick": "advanced", + "why": "Map look option beyond the basics, not engine tuning.", + "lists": "Top, Middle, Bottom", + "focused": true, + "mix": "", + "group": "Settings", + "subgroup": "Look & labels" + }, + { + "id": "Settings.coordFontSize", + "surface": "Settings tab", + "label": "Coordinate label size", + "kind": "slider", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:349", + "desc": "Size of the coordinate label (declarative path only label).", + "pick": "overkill", + "why": "Font micro-tuning for the coordinate label.", + "lists": "", + "focused": null, + "mix": "", + "group": "Settings", + "subgroup": "Look & labels" + }, + { + "id": "Settings.coordFontFamily", + "surface": "Settings tab", + "label": "Coordinate label font", + "kind": "dropdown", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:362", + "desc": "Font for the coordinate label (declarative path label).", + "pick": "overkill", + "why": "Font micro-tuning for the coordinate label.", + "lists": "Interface, Serif, Monospace", + "focused": true, + "mix": "", + "group": "Settings", + "subgroup": "Look & labels" + }, + { + "id": "Settings.coordFontColor", + "surface": "Settings tab", + "label": "Coordinate label color", + "kind": "color", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:376", + "desc": "Colour of the coordinate label (declarative path label).", + "pick": "overkill", + "why": "Font micro-tuning for the coordinate label.", + "lists": "", + "focused": null, + "mix": "", + "group": "Settings", + "subgroup": "Look & labels" + }, + { + "id": "Settings.hexNameFont", + "surface": "Settings tab", + "label": "Hex name font", + "kind": "dropdown", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:385", + "desc": "Default font for hex names on maps and exports (declarative).", + "pick": "overkill", + "why": "Global font default for hex names; per-map layers menu covers normal use.", + "lists": "Name font families", + "focused": true, + "mix": "", + "group": "Settings", + "subgroup": "Look & labels" + }, + { + "id": "Settings.hexNameSize", + "surface": "Settings tab", + "label": "Hex name size", + "kind": "dropdown", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:395", + "desc": "Default size for hex names (declarative path label).", + "pick": "overkill", + "why": "Global font-size default for hex names; per-map layers menu covers normal use.", + "lists": "Small, Medium, Large, Huge", + "focused": true, + "mix": "", + "group": "Settings", + "subgroup": "Look & labels" + }, + { + "id": "Settings.hexNameStyle", + "surface": "Settings tab", + "label": "Hex name style", + "kind": "dropdown", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:405", + "desc": "Default bold/italic for hex names (declarative path label).", + "pick": "overkill", + "why": "Global font-style default for hex names; per-map layers menu covers normal use.", + "lists": "Name styles", + "focused": true, + "mix": "", + "group": "Settings", + "subgroup": "Look & labels" + }, + { + "id": "Settings.hexGap", + "surface": "Settings tab", + "label": "Hex cell spacing", + "kind": "slider", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:415", + "desc": "Gap between hex cells (both paths).", + "pick": "advanced", + "why": "Map look option beyond the basics, not engine tuning.", + "lists": "", + "focused": null, + "mix": "", + "group": "Settings", + "subgroup": "Look & labels" + }, + { + "id": "Settings.defaultTableDice", + "surface": "Settings tab", + "label": "Default die for new tables", + "kind": "dropdown", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:266", + "desc": "Die size new random tables start with, d4 to d1000 (both paths).", + "pick": "advanced", + "why": "A table-making preference beyond the basics; each table can still change its own die.", + "lists": "D4,D6,D8,D10,D12,D20,D100,D200,D500,D1000", + "focused": true, + "mix": "", + "group": "Settings", + "subgroup": "Defaults" + }, + { + "id": "Settings.collapseTerrain", + "surface": "Settings tab: Hex editor sections start collapsed", + "label": "Terrain", + "kind": "toggle", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:989", + "desc": "Hex editor opens with Terrain section collapsed (both paths).", + "pick": "advanced", + "why": "A layout preference for people who use the hex editor a lot; not needed to start.", + "lists": "", + "focused": null, + "mix": "", + "group": "Settings", + "subgroup": "Defaults" + }, + { + "id": "Settings.collapseFeatures", + "surface": "Settings tab: Hex editor sections start collapsed", + "label": "Features", + "kind": "toggle", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:996", + "desc": "Hex editor opens with Features section collapsed (both paths).", + "pick": "advanced", + "why": "A layout preference for people who use the hex editor a lot; not needed to start.", + "lists": "", + "focused": null, + "mix": "", + "group": "Settings", + "subgroup": "Defaults" + }, + { + "id": "Settings.collapseNotes", + "surface": "Settings tab: Hex editor sections start collapsed", + "label": "Notes", + "kind": "toggle", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:1003", + "desc": "Hex editor opens with Notes section collapsed (both paths).", + "pick": "advanced", + "why": "A layout preference for people who use the hex editor a lot; not needed to start.", + "lists": "", + "focused": null, + "mix": "", + "group": "Settings", + "subgroup": "Defaults" + }, + { + "id": "Settings.templatePath", + "surface": "Settings tab", + "label": "Template path", + "kind": "text", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:293", + "desc": "Path to a custom hex note template (both paths).", + "pick": "advanced", + "why": "Custom hex note templates are a real feature, just not a first-day one.", + "lists": "", + "focused": null, + "mix": "", + "group": "Settings", + "subgroup": "Defaults" + }, + { + "id": "Settings.defaultMap", + "surface": "Settings tab", + "label": "Default map", + "kind": "dropdown", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:300", + "desc": "Map shown when the hex map opens (both paths).", + "pick": "keep", + "why": "Useful once you have several maps.", + "lists": "All maps in settings (top-level, submaps, regions alike)", + "focused": false, + "mix": "submaps/region maps listed flat beside top-level maps", + "group": "Settings", + "subgroup": "Defaults" + }, + { + "id": "Settings.defaultNewMapCols", + "surface": "Settings tab", + "label": "Default new map columns", + "kind": "number", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:428", + "desc": "Starting columns for new top-level maps (declarative path).", + "pick": "advanced", + "why": "A convenience default for people who make many maps; the new-map form still asks.", + "lists": "", + "focused": null, + "mix": "", + "group": "Settings", + "subgroup": "Defaults" + }, + { + "id": "Settings.defaultNewMapRows", + "surface": "Settings tab", + "label": "Default new map rows", + "kind": "number", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:440", + "desc": "Starting rows for new top-level maps (declarative path).", + "pick": "advanced", + "why": "A convenience default for people who make many maps; the new-map form still asks.", + "lists": "", + "focused": null, + "mix": "", + "group": "Settings", + "subgroup": "Defaults" + }, + { + "id": "Settings.defaultSubmapCols", + "surface": "Settings tab", + "label": "Default submap columns", + "kind": "number", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:452", + "desc": "Starting columns for new submaps (declarative path).", + "pick": "advanced", + "why": "A convenience default for people who make many submaps; the form still asks.", + "lists": "", + "focused": null, + "mix": "", + "group": "Settings", + "subgroup": "Defaults" + }, + { + "id": "Settings.defaultSubmapRows", + "surface": "Settings tab", + "label": "Default submap rows", + "kind": "number", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:464", + "desc": "Starting rows for new submaps (declarative path).", + "pick": "advanced", + "why": "A convenience default for people who make many submaps; the form still asks.", + "lists": "", + "focused": null, + "mix": "", + "group": "Settings", + "subgroup": "Defaults" + }, + { + "id": "Settings.iconsFolder", + "surface": "Settings tab", + "label": "Custom icons folder", + "kind": "text", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:475", + "desc": "Folder of your own icon images added to the pickers (both paths).", + "pick": "keep", + "why": "Main way to add your own icons; pickers point users here.", + "lists": "", + "focused": null, + "mix": "", + "group": "Settings", + "subgroup": "Folders" + }, + { + "id": "Settings.worldFolder", + "surface": "Settings tab: folders", + "label": "World notes folder", + "kind": "text", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:527", + "desc": "Root folder for all world notes; scopes link search (both paths).", + "pick": "keep", + "why": "The one folder a newcomer should care about.", + "lists": "", + "focused": null, + "mix": "", + "group": "Settings", + "subgroup": "Folders" + }, + { + "id": "Settings.hexFolder", + "surface": "Settings tab: folders", + "label": "Hex notes folder", + "kind": "text", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:608", + "desc": "Where hex notes are stored (both paths).", + "pick": "advanced", + "why": "Folder layout choice beyond the defaults the wizard sets.", + "lists": "", + "focused": null, + "mix": "", + "group": "Settings", + "subgroup": "Folders" + }, + { + "id": "Settings.townsFolder", + "surface": "Settings tab: folders", + "label": "Towns folder", + "kind": "text", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:614", + "desc": "Folder that feeds the Towns picker (both paths).", + "pick": "advanced", + "why": "Folder layout choice beyond the defaults the wizard sets.", + "lists": "", + "focused": null, + "mix": "", + "group": "Settings", + "subgroup": "Folders" + }, + { + "id": "Settings.dungeonsFolder", + "surface": "Settings tab: folders", + "label": "Dungeons folder", + "kind": "text", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:620", + "desc": "Folder that feeds the Dungeons picker (both paths).", + "pick": "advanced", + "why": "Folder layout choice beyond the defaults the wizard sets.", + "lists": "", + "focused": null, + "mix": "", + "group": "Settings", + "subgroup": "Folders" + }, + { + "id": "Settings.questsFolder", + "surface": "Settings tab: folders", + "label": "Quests folder", + "kind": "text", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:626", + "desc": "Folder that feeds the Quests picker (both paths).", + "pick": "advanced", + "why": "Folder layout choice beyond the defaults the wizard sets.", + "lists": "", + "focused": null, + "mix": "", + "group": "Settings", + "subgroup": "Folders" + }, + { + "id": "Settings.featuresFolder", + "surface": "Settings tab: folders", + "label": "Features folder", + "kind": "text", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:632", + "desc": "Folder that feeds the Features picker (both paths).", + "pick": "advanced", + "why": "Folder layout choice beyond the defaults the wizard sets.", + "lists": "", + "focused": null, + "mix": "", + "group": "Settings", + "subgroup": "Folders" + }, + { + "id": "Settings.factionsFolder", + "surface": "Settings tab: folders", + "label": "Factions folder", + "kind": "text", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:638", + "desc": "Folder that feeds the Factions picker (both paths).", + "pick": "advanced", + "why": "Folder layout choice beyond the defaults the wizard sets.", + "lists": "", + "focused": null, + "mix": "", + "group": "Settings", + "subgroup": "Folders" + }, + { + "id": "Settings.regionsFolder", + "surface": "Settings tab: folders", + "label": "Regions folder", + "kind": "text", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:644", + "desc": "Folder for region notes used by the region overlay tool (both paths).", + "pick": "advanced", + "why": "Folder for the region areas overlay; beyond the defaults the wizard sets.", + "lists": "", + "focused": null, + "mix": "", + "group": "Settings", + "subgroup": "Folders" + }, + { + "id": "Settings.tablesFolder", + "surface": "Settings tab: folders", + "label": "Tables folder", + "kind": "text", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:650", + "desc": "Folder for random table notes (both paths).", + "pick": "advanced", + "why": "Folder layout choice beyond the defaults the wizard sets.", + "lists": "", + "focused": null, + "mix": "", + "group": "Settings", + "subgroup": "Folders" + }, + { + "id": "Settings.workflowsFolder", + "surface": "Settings tab: folders", + "label": "Workflows folder", + "kind": "text", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:656", + "desc": "Folder for workflow notes (both paths).", + "pick": "advanced", + "why": "Folder for workflows, an Advanced feature.", + "lists": "", + "focused": null, + "mix": "", + "group": "Settings", + "subgroup": "Folders" + }, + { + "id": "Settings.templatesFolder", + "surface": "Settings tab: folders", + "label": "Templates folder", + "kind": "text", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:662", + "desc": "Folder for hex/town note templates (both paths).", + "pick": "advanced", + "why": "Folder layout choice beyond the defaults the wizard sets.", + "lists": "", + "focused": null, + "mix": "", + "group": "Settings", + "subgroup": "Folders" + }, + { + "id": "Settings.palettesFolder", + "surface": "Settings tab: folders", + "label": "Palettes folder", + "kind": "text", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:668", + "desc": "Folder for palette notes (both paths).", + "pick": "advanced", + "why": "Folder for custom palettes, an Advanced feature.", + "lists": "", + "focused": null, + "mix": "", + "group": "Settings", + "subgroup": "Folders" + }, + { + "id": "Settings.biomesFolder", + "surface": "Settings tab: folders", + "label": "Biomes folder", + "kind": "text", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:674", + "desc": "Folder for overworld biome notes (both paths).", + "pick": "overkill", + "why": "Storage location for generator biome data; a normal user never moves it.", + "lists": "", + "focused": null, + "mix": "", + "group": "Settings", + "subgroup": "Folders" + }, + { + "id": "Settings.biomePoolsFolder", + "surface": "Settings tab: folders", + "label": "Biome pools folder", + "kind": "text", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:680", + "desc": "Folder for biome pools of generated overworlds (both paths).", + "pick": "overkill", + "why": "Storage location for generator biome-pool data; a normal user never moves it.", + "lists": "", + "focused": null, + "mix": "", + "group": "Settings", + "subgroup": "Folders" + }, + { + "id": "Settings.worldTypesFolder", + "surface": "Settings tab: folders", + "label": "World types folder", + "kind": "text", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:686", + "desc": "Folder for world-type notes used by space generators (both paths).", + "pick": "overkill", + "why": "Storage location for space world-type data; a normal user never moves it.", + "lists": "", + "focused": null, + "mix": "", + "group": "Settings", + "subgroup": "Folders" + }, + { + "id": "Settings.defaultPalette", + "surface": "Settings tab: Terrain palettes", + "label": "Palette for new maps", + "kind": "dropdown", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:721", + "desc": "Palette a new map starts with (both paths).", + "pick": "advanced", + "why": "Part of custom palettes; the new-map form picks a palette anyway.", + "lists": "'First palette' + all installed palettes (+ missing saved one)", + "focused": false, + "mix": "space palettes listed even with Space off (no isKindEnabled filter)", + "group": "Settings", + "subgroup": "Palette management" + }, + { + "id": "Settings.addDefaultPalettes", + "surface": "Settings tab: Terrain palettes", + "label": "Add ", + "kind": "button", + "level": "conditional: a built-in palette was deleted", + "loc": "src/HexmakerSettingTab.ts:731", + "desc": "Restores deleted built-in palettes (both paths).", + "pick": "advanced", + "why": "Palette management (restore a deleted built-in), part of custom palettes.", + "lists": "", + "focused": null, + "mix": "", + "group": "Settings", + "subgroup": "Palette management" + }, + { + "id": "Settings.paletteRowName", + "surface": "Settings tab: Terrain palettes", + "label": "(palette name)", + "kind": "text", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:212", + "desc": "Inline rename box on each palette row (both paths).", + "pick": "advanced", + "why": "Palette management, part of the custom palettes feature.", + "lists": "", + "focused": null, + "mix": "", + "group": "Settings", + "subgroup": "Palette management" + }, + { + "id": "Settings.paletteRowEdit", + "surface": "Settings tab: Terrain palettes", + "label": "Edit", + "kind": "button", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:868", + "desc": "Opens the palette editor (asks to enable palettes in Simple).", + "pick": "advanced", + "why": "Opens the palette editor, part of the custom palettes feature.", + "lists": "", + "focused": null, + "mix": "", + "group": "Settings", + "subgroup": "Palette management" + }, + { + "id": "Settings.paletteRowOpenNote", + "surface": "Settings tab: Terrain palettes", + "label": "Open note", + "kind": "button", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:871", + "desc": "Opens the palette's markdown note (both paths).", + "pick": "advanced", + "why": "Palette notes are editable as a table; part of custom palettes, not dead.", + "lists": "", + "focused": null, + "mix": "", + "group": "Settings", + "subgroup": "Palette management" + }, + { + "id": "Settings.paletteDelete", + "surface": "Settings tab: Terrain palettes", + "label": "Delete (list delete)", + "kind": "button", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:748", + "desc": "Deletes an unused palette (declarative list delete affordance).", + "pick": "advanced", + "why": "Palette management, part of the custom palettes feature.", + "lists": "", + "focused": null, + "mix": "", + "group": "Settings", + "subgroup": "Palette management" + }, + { + "id": "Settings.addPalette", + "surface": "Settings tab: Terrain palettes", + "label": "Add palette", + "kind": "button", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:767", + "desc": "Opens the Add palette chooser (both paths).", + "pick": "advanced", + "why": "Adding palettes is part of the custom palettes feature.", + "lists": "", + "focused": null, + "mix": "", + "group": "Settings", + "subgroup": "Palette management" + }, + { + "id": "AddPalette.presetOption", + "surface": "Add palette modal", + "label": "", + "kind": "picker", + "level": "always (from Settings > Add palette)", + "loc": "src/palettes/AddPaletteModal.ts:30", + "desc": "Install a built-in palette preset (filtered by enabled map types).", + "pick": "simple", + "why": "Custom palettes are Simple (owner); installing a preset is how you add one. Owner (pass 3): \"a streamlined but still customizable experience for simple, not to hide every little possible scary thing.\"", + "lists": "Built-in presets of enabled map types", + "focused": true, + "mix": "", + "group": "Settings", + "subgroup": "Palette management", + "prevPick": "advanced" + }, + { + "id": "AddPalette.copyOption", + "surface": "Add palette modal", + "label": "Copy of ", + "kind": "picker", + "level": "always (from Settings > Add palette)", + "loc": "src/palettes/AddPaletteModal.ts:46", + "desc": "Duplicate an existing palette.", + "pick": "simple", + "why": "Custom palettes are Simple (owner); copying one is the easy way to start your own. Owner (pass 3): \"a streamlined but still customizable experience for simple, not to hide every little possible scary thing.\"", + "lists": "Every installed palette (space ones too with Space off)", + "focused": true, + "mix": "", + "group": "Settings", + "subgroup": "Palette management", + "prevPick": "advanced" + }, + { + "id": "AddPalette.emptyPalette", + "surface": "Add palette modal", + "label": "Empty palette", + "kind": "button", + "level": "always (from Settings > Add palette)", + "loc": "src/palettes/AddPaletteModal.ts:64", + "desc": "Create an empty palette.", + "pick": "simple", + "why": "Custom palettes are Simple (owner). Owner (pass 3): \"a streamlined but still customizable experience for simple, not to hide every little possible scary thing.\"", + "lists": "", + "focused": null, + "mix": "", + "group": "Settings", + "subgroup": "Palette management", + "prevPick": "advanced" + }, + { + "id": "AddPalette.preset", + "surface": "Add palette modal", + "label": " / (another copy)", + "kind": "button", + "level": "feature:palettes", + "loc": "src/palettes/AddPaletteModal.ts:30", + "desc": "Installs a built-in palette preset.", + "pick": "keep", + "why": "Easiest start.", + "lists": "PALETTE_PRESETS of enabled map kinds; installed ones labelled '(another copy)'.", + "focused": true, + "mix": "", + "group": "Settings", + "subgroup": "Palette management" + }, + { + "id": "AddPalette.closeButtons", + "surface": "Add palette modal", + "label": "(modal ✕)", + "kind": "button", + "level": "feature:palettes", + "loc": "src/palettes/AddPaletteModal.ts:20", + "desc": "Closes without adding.", + "pick": "keep", + "why": "Required.", + "lists": "", + "focused": null, + "mix": "", + "group": "Settings", + "subgroup": "Palette management" + }, + { + "id": "Settings.generateWorldData", + "surface": "Settings tab: Generate world data", + "label": "Generate", + "kind": "button", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:491", + "desc": "Creates terrain tables, roller links, hex-to-table links (both paths).", + "pick": "overkill", + "why": "Maintenance button: the wizard and painting already create this data.", + "lists": "", + "focused": null, + "mix": "", + "group": "Settings", + "subgroup": "Maintenance" + }, + { + "id": "Settings.hexNoteProperties", + "surface": "Settings tab: Map data as hex note properties", + "label": "Map data as hex note properties", + "kind": "toggle", + "level": "always", + "loc": "src/settings/hexPropsSetting.ts", + "desc": "Hex notes carry their hex's terrain, area, icon and name as properties (copies of the map note's data), both ways.", + "pick": "advanced", + "why": "Owner MG4: on by default; off is for people who don't want the copies.", + "lists": "", + "focused": null, + "mix": "", + "group": "Settings", + "subgroup": "Maintenance" + }, + { + "id": "Settings.generateFolders", + "surface": "Settings tab: folders", + "label": "Generate folders", + "kind": "button", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:534", + "desc": "Fills blank folder settings, creates folders and hex notes (both paths).", + "pick": "overkill", + "why": "Maintenance button that redoes the wizard's folder work.", + "lists": "", + "focused": null, + "mix": "", + "group": "Settings", + "subgroup": "Maintenance" + }, + { + "id": "Settings.legacyCoordLabelSize", + "surface": "Settings tab: legacy display()", + "label": "Coordinate label (slider)", + "kind": "slider", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:1167", + "desc": "Legacy path: size slider in one combined 'Coordinate label' row.", + "pick": "overkill", + "why": "Pre-1.13 fallback copy of the same setting; follows Settings.coordFontSize (owner: \"should just map to the same setting\"). Earlier reason: Pre-1.13 copy of the coordinate label size; same tag as its twin.", + "lists": "", + "focused": null, + "mix": "", + "group": "Settings", + "subgroup": "Legacy (pre-1.13)", + "twinOf": "Settings.coordFontSize" + }, + { + "id": "Settings.legacyCoordLabelFont", + "surface": "Settings tab: legacy display()", + "label": "Coordinate label (font)", + "kind": "dropdown", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:1178", + "desc": "Legacy path: unlabelled font dropdown in the combined row.", + "pick": "overkill", + "why": "Pre-1.13 fallback copy of the same setting; follows Settings.coordFontFamily (owner: \"should just map to the same setting\"). Earlier reason: Pre-1.13 copy of the coordinate label font; same tag as its twin.", + "lists": "Interface, Serif, Monospace", + "focused": true, + "mix": "", + "group": "Settings", + "subgroup": "Legacy (pre-1.13)", + "twinOf": "Settings.coordFontFamily" + }, + { + "id": "Settings.legacyCoordLabelColor", + "surface": "Settings tab: legacy display()", + "label": "Coordinate label (color)", + "kind": "color", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:1193", + "desc": "Legacy path: unlabelled colour picker in the combined row.", + "pick": "overkill", + "why": "Pre-1.13 fallback copy of the same setting; follows Settings.coordFontColor (owner: \"should just map to the same setting\"). Earlier reason: Pre-1.13 copy of the coordinate label colour; same tag as its twin.", + "lists": "", + "focused": null, + "mix": "", + "group": "Settings", + "subgroup": "Legacy (pre-1.13)", + "twinOf": "Settings.coordFontColor" + }, + { + "id": "Settings.legacyHexNameFont", + "surface": "Settings tab: legacy display()", + "label": "Hex name font (font)", + "kind": "dropdown", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:1214", + "desc": "Legacy path: first of 3 unlabelled dropdowns in one row.", + "pick": "overkill", + "why": "Pre-1.13 fallback copy of the same setting; follows Settings.hexNameFont (owner: \"should just map to the same setting\"). Earlier reason: Pre-1.13 copy of the hex name font default; same tag as its twin.", + "lists": "Name font families", + "focused": true, + "mix": "", + "group": "Settings", + "subgroup": "Legacy (pre-1.13)", + "twinOf": "Settings.hexNameFont" + }, + { + "id": "Settings.legacyHexNameSize", + "surface": "Settings tab: legacy display()", + "label": "Hex name font (size)", + "kind": "dropdown", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:1221", + "desc": "Legacy path: size dropdown in the Hex name font row.", + "pick": "overkill", + "why": "Pre-1.13 fallback copy of the same setting; follows Settings.hexNameSize (owner: \"should just map to the same setting\"). Earlier reason: Pre-1.13 copy of the hex name size default; same tag as its twin.", + "lists": "Small..Huge", + "focused": true, + "mix": "", + "group": "Settings", + "subgroup": "Legacy (pre-1.13)", + "twinOf": "Settings.hexNameSize" + }, + { + "id": "Settings.legacyHexNameStyle", + "surface": "Settings tab: legacy display()", + "label": "Hex name font (style)", + "kind": "dropdown", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:1228", + "desc": "Legacy path: style dropdown in the Hex name font row.", + "pick": "overkill", + "why": "Pre-1.13 fallback copy of the same setting; follows Settings.hexNameStyle (owner: \"should just map to the same setting\"). Earlier reason: Pre-1.13 copy of the hex name style default; same tag as its twin.", + "lists": "Name styles", + "focused": true, + "mix": "", + "group": "Settings", + "subgroup": "Legacy (pre-1.13)", + "twinOf": "Settings.hexNameStyle" + }, + { + "id": "Settings.legacyNewMapCols", + "surface": "Settings tab: legacy display()", + "label": "Default new map size (Cols)", + "kind": "text", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:1263", + "desc": "Legacy path: text box (not number) for default columns.", + "pick": "advanced", + "why": "Pre-1.13 fallback copy of the same setting; follows Settings.defaultNewMapCols (owner: \"should just map to the same setting\"). Earlier reason: Pre-1.13 copy of the default new map size; same tag as its twin.", + "lists": "", + "focused": null, + "mix": "", + "group": "Settings", + "subgroup": "Legacy (pre-1.13)", + "twinOf": "Settings.defaultNewMapCols" + }, + { + "id": "Settings.legacyNewMapRows", + "surface": "Settings tab: legacy display()", + "label": "Default new map size (Rows)", + "kind": "text", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:1272", + "desc": "Legacy path: text box for default rows.", + "pick": "advanced", + "why": "Pre-1.13 fallback copy of the same setting; follows Settings.defaultNewMapRows (owner: \"should just map to the same setting\"). Earlier reason: Pre-1.13 copy of the default new map size; same tag as its twin.", + "lists": "", + "focused": null, + "mix": "", + "group": "Settings", + "subgroup": "Legacy (pre-1.13)", + "twinOf": "Settings.defaultNewMapRows" + }, + { + "id": "Settings.legacySubmapCols", + "surface": "Settings tab: legacy display()", + "label": "Default submap size (Cols)", + "kind": "text", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:1285", + "desc": "Legacy path: text box for submap columns.", + "pick": "advanced", + "why": "Pre-1.13 fallback copy of the same setting; follows Settings.defaultSubmapCols (owner: \"should just map to the same setting\"). Earlier reason: Pre-1.13 copy of the default submap size; same tag as its twin.", + "lists": "", + "focused": null, + "mix": "", + "group": "Settings", + "subgroup": "Legacy (pre-1.13)", + "twinOf": "Settings.defaultSubmapCols" + }, + { + "id": "Settings.legacySubmapRows", + "surface": "Settings tab: legacy display()", + "label": "Default submap size (Rows)", + "kind": "text", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:1294", + "desc": "Legacy path: text box for submap rows.", + "pick": "advanced", + "why": "Pre-1.13 fallback copy of the same setting; follows Settings.defaultSubmapRows (owner: \"should just map to the same setting\"). Earlier reason: Pre-1.13 copy of the default submap size; same tag as its twin.", + "lists": "", + "focused": null, + "mix": "", + "group": "Settings", + "subgroup": "Legacy (pre-1.13)", + "twinOf": "Settings.defaultSubmapRows" + }, + { + "id": "Settings.legacyPaletteDeleteButton", + "surface": "Settings tab: legacy display()", + "label": "Delete", + "kind": "button", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:1742", + "desc": "Legacy path: explicit Delete per palette row, disabled when in use.", + "pick": "advanced", + "why": "Pre-1.13 fallback copy of the same setting; follows Settings.paletteDelete (owner: \"should just map to the same setting\"). Earlier reason: Pre-1.13 copy of palette delete; palette management is custom palettes.", + "lists": "", + "focused": null, + "mix": "", + "group": "Settings", + "subgroup": "Legacy (pre-1.13)", + "twinOf": "Settings.paletteDelete" + }, + { + "id": "Wizard.mapKindWorld", + "surface": "Setup wizard: Welcome", + "label": "World / fantasy overland", + "kind": "checkbox", + "level": "always", + "loc": "src/SetupWizardView.ts:243", + "desc": "Include fantasy overland content.", + "pick": "keep", + "why": "Good first question; scopes everything after.", + "lists": "", + "focused": null, + "mix": "", + "group": "Setup wizard", + "subgroup": "Welcome" + }, + { + "id": "Wizard.mapKindSpace", + "surface": "Setup wizard: Welcome", + "label": "Space", + "kind": "checkbox", + "level": "always", + "loc": "src/SetupWizardView.ts:243", + "desc": "Include space content.", + "pick": "keep", + "why": "Good first question.", + "lists": "", + "focused": null, + "mix": "", + "group": "Setup wizard", + "subgroup": "Welcome" + }, + { + "id": "Wizard.featureLevel", + "surface": "Setup wizard: Welcome", + "label": "How much do you want to start with? (Simple/Advanced)", + "kind": "radio", + "level": "always", + "loc": "src/SetupWizardView.ts:261", + "desc": "Choose Simple or Advanced feature level.", + "pick": "keep", + "why": "Right place to set the level; descriptions are long.", + "lists": "Simple, Advanced", + "focused": true, + "mix": "", + "group": "Setup wizard", + "subgroup": "Welcome" + }, + { + "id": "Wizard.worldFolder", + "surface": "Setup wizard: Folders", + "label": "World folder", + "kind": "text", + "level": "always", + "loc": "src/SetupWizardView.ts:304", + "desc": "Root folder for all world data.", + "pick": "keep", + "why": "The one folder question that matters.", + "lists": "", + "focused": null, + "mix": "", + "group": "Setup wizard", + "subgroup": "Folders" + }, + { + "id": "Wizard.configureFoldersIndividually", + "surface": "Setup wizard: Folders", + "label": "Configure each folder path individually", + "kind": "checkbox", + "level": "always", + "loc": "src/SetupWizardView.ts:324", + "desc": "Reveals 11 per-folder path inputs.", + "pick": "advanced", + "why": "Per-folder setup is beyond what a newcomer needs; the defaults work.", + "lists": "", + "focused": null, + "mix": "", + "group": "Setup wizard", + "subgroup": "Folders" + }, + { + "id": "Wizard.folder.hex", + "surface": "Setup wizard: Folders", + "label": "Hex notes", + "kind": "text", + "level": "conditional: 'configure individually' ticked", + "loc": "src/SetupWizardView.ts:350", + "desc": "Custom path for the hex notes folder.", + "pick": "keep", + "why": "No change of its own: it only shows inside the 'configure individually' box (tagged advanced), so tagging that hides it too.", + "lists": "", + "focused": null, + "mix": "", + "group": "Setup wizard", + "subgroup": "Folders" + }, + { + "id": "Wizard.folder.towns", + "surface": "Setup wizard: Folders", + "label": "Towns", + "kind": "text", + "level": "conditional: 'configure individually' ticked", + "loc": "src/SetupWizardView.ts:350", + "desc": "Custom path for the towns folder.", + "pick": "keep", + "why": "No change of its own: it only shows inside the 'configure individually' box (tagged advanced), so tagging that hides it too.", + "lists": "", + "focused": null, + "mix": "", + "group": "Setup wizard", + "subgroup": "Folders" + }, + { + "id": "Wizard.folder.dungeons", + "surface": "Setup wizard: Folders", + "label": "Dungeons", + "kind": "text", + "level": "conditional: 'configure individually' ticked", + "loc": "src/SetupWizardView.ts:350", + "desc": "Custom path for the dungeons folder.", + "pick": "keep", + "why": "No change of its own: it only shows inside the 'configure individually' box (tagged advanced), so tagging that hides it too.", + "lists": "", + "focused": null, + "mix": "", + "group": "Setup wizard", + "subgroup": "Folders" + }, + { + "id": "Wizard.folder.quests", + "surface": "Setup wizard: Folders", + "label": "Quests", + "kind": "text", + "level": "conditional: 'configure individually' ticked", + "loc": "src/SetupWizardView.ts:350", + "desc": "Custom path for the quests folder.", + "pick": "keep", + "why": "No change of its own: it only shows inside the 'configure individually' box (tagged advanced), so tagging that hides it too.", + "lists": "", + "focused": null, + "mix": "", + "group": "Setup wizard", + "subgroup": "Folders" + }, + { + "id": "Wizard.folder.features", + "surface": "Setup wizard: Folders", + "label": "Features", + "kind": "text", + "level": "conditional: 'configure individually' ticked", + "loc": "src/SetupWizardView.ts:350", + "desc": "Custom path for the features folder.", + "pick": "keep", + "why": "No change of its own: it only shows inside the 'configure individually' box (tagged advanced), so tagging that hides it too.", + "lists": "", + "focused": null, + "mix": "", + "group": "Setup wizard", + "subgroup": "Folders" + }, + { + "id": "Wizard.folder.factions", + "surface": "Setup wizard: Folders", + "label": "Factions", + "kind": "text", + "level": "conditional: 'configure individually' ticked", + "loc": "src/SetupWizardView.ts:350", + "desc": "Custom path for the factions folder.", + "pick": "keep", + "why": "No change of its own: it only shows inside the 'configure individually' box (tagged advanced), so tagging that hides it too.", + "lists": "", + "focused": null, + "mix": "", + "group": "Setup wizard", + "subgroup": "Folders" + }, + { + "id": "Wizard.folder.regions", + "surface": "Setup wizard: Folders", + "label": "Regions", + "kind": "text", + "level": "conditional: 'configure individually' ticked", + "loc": "src/SetupWizardView.ts:350", + "desc": "Custom path for the regions folder.", + "pick": "keep", + "why": "No change of its own: it only shows inside the 'configure individually' box (tagged advanced), so tagging that hides it too.", + "lists": "", + "focused": null, + "mix": "", + "group": "Setup wizard", + "subgroup": "Folders" + }, + { + "id": "Wizard.folder.tables", + "surface": "Setup wizard: Folders", + "label": "Tables", + "kind": "text", + "level": "conditional: 'configure individually' ticked", + "loc": "src/SetupWizardView.ts:350", + "desc": "Custom path for the tables folder.", + "pick": "keep", + "why": "No change of its own: it only shows inside the 'configure individually' box (tagged advanced), so tagging that hides it too.", + "lists": "", + "focused": null, + "mix": "", + "group": "Setup wizard", + "subgroup": "Folders" + }, + { + "id": "Wizard.folder.workflows", + "surface": "Setup wizard: Folders", + "label": "Workflows", + "kind": "text", + "level": "conditional: 'configure individually' ticked", + "loc": "src/SetupWizardView.ts:350", + "desc": "Custom path for the workflows folder.", + "pick": "keep", + "why": "No change of its own: it only shows inside the 'configure individually' box (tagged advanced), so tagging that hides it too.", + "lists": "", + "focused": null, + "mix": "", + "group": "Setup wizard", + "subgroup": "Folders" + }, + { + "id": "Wizard.folder.templates", + "surface": "Setup wizard: Folders", + "label": "Templates", + "kind": "text", + "level": "conditional: 'configure individually' ticked", + "loc": "src/SetupWizardView.ts:350", + "desc": "Custom path for the templates folder.", + "pick": "keep", + "why": "No change of its own: it only shows inside the 'configure individually' box (tagged advanced), so tagging that hides it too.", + "lists": "", + "focused": null, + "mix": "", + "group": "Setup wizard", + "subgroup": "Folders" + }, + { + "id": "Wizard.folder.icons", + "surface": "Setup wizard: Folders", + "label": "Icons", + "kind": "text", + "level": "conditional: 'configure individually' ticked", + "loc": "src/SetupWizardView.ts:350", + "desc": "Custom path for the icons folder.", + "pick": "keep", + "why": "No change of its own: it only shows inside the 'configure individually' box (tagged advanced), so tagging that hides it too.", + "lists": "", + "focused": null, + "mix": "", + "group": "Setup wizard", + "subgroup": "Folders" + }, + { + "id": "Wizard.mapName", + "surface": "Setup wizard: Map", + "label": "Map name", + "kind": "text", + "level": "always", + "loc": "src/SetupWizardView.ts:440", + "desc": "Name of your first map.", + "pick": "keep", + "why": "Essential.", + "lists": "", + "focused": null, + "mix": "", + "group": "Setup wizard", + "subgroup": "Map" + }, + { + "kind": "radio cards", + "level": "always", + "pick": "keep", + "lists": "", + "focused": null, + "mix": "", + "group": "Setup wizard", + "subgroup": "Map", + "surface": "Setup wizard: Map", + "id": "Wizard.mapScale", + "label": "What are you mapping?", + "loc": "src/SetupWizardView.ts", + "desc": "Overland, Biomes, Sector or system, Planet (from the modules whose map types are on). Sets the size, palette and generator list.", + "why": "Owner 2026-10-12: scale and generator are two choices." + }, + { + "id": "Wizard.gridCols", + "surface": "Setup wizard: Map", + "label": "Grid size (columns)", + "kind": "number", + "level": "always", + "loc": "src/SetupWizardView.ts:469", + "desc": "Number of columns.", + "pick": "keep", + "why": "Essential map size.", + "lists": "", + "focused": null, + "mix": "", + "group": "Setup wizard", + "subgroup": "Map" + }, + { + "id": "Wizard.gridRows", + "surface": "Setup wizard: Map", + "label": "Grid size (rows)", + "kind": "number", + "level": "always", + "loc": "src/SetupWizardView.ts:479", + "desc": "Number of rows.", + "pick": "keep", + "why": "Essential map size.", + "lists": "", + "focused": null, + "mix": "", + "group": "Setup wizard", + "subgroup": "Map" + }, + { + "kind": "button", + "level": "always", + "pick": "keep", + "lists": "", + "focused": null, + "mix": "", + "group": "Setup wizard", + "subgroup": "Map", + "surface": "Setup wizard: Map", + "id": "Wizard.gridSizeReset", + "label": "Reset grid size", + "loc": "src/SetupWizardView.ts", + "desc": "Puts columns and rows back to the chosen scale size. The size fields also step with the mouse wheel while hovered or focused.", + "why": "Owner 2026-10-12: grid size easy to reset." + }, + { + "id": "Wizard.hexOrientation", + "surface": "Setup wizard: Map", + "label": "Hex orientation (Flat-top / Pointy-top)", + "kind": "radio", + "level": "always", + "loc": "src/SetupWizardView.ts:544", + "desc": "Choose flat-top or pointy-top hexes.", + "pick": "keep", + "why": "Clear choice with live preview.", + "lists": "Flat-top, Pointy-top", + "focused": true, + "mix": "", + "group": "Setup wizard", + "subgroup": "Map" + }, + { + "id": "Wizard.terrainPalette", + "surface": "Setup wizard: Map", + "label": "Terrain palette", + "kind": "dropdown", + "level": "always", + "loc": "src/SetupWizardView.ts:579", + "desc": "Palette for the first map (installed + presets of enabled kinds).", + "pick": "keep", + "why": "Core choice; preview swatches help.", + "lists": "Installed palettes + Presets optgroup (kind-filtered)", + "focused": true, + "mix": "", + "group": "Setup wizard", + "subgroup": "Map" + }, + { + "id": "Wizard.generatorCards", + "surface": "Setup wizard: Map", + "label": "Terrain (generator cards)", + "kind": "picker", + "level": "always (Simple: Blank + starter + every space gen)", + "loc": "src/SetupWizardView.ts:633", + "desc": "Pick how to fill the map: blank or a generator.", + "pick": "keep", + "why": "Good, but in Simple every space generator leaks through.", + "lists": "Blank, Overland/Star scatter; Advanced: all incl. learned", + "focused": false, + "mix": "Simple filter keeps all mapKind=space generators, not just the starter", + "group": "Setup wizard", + "subgroup": "Map" + }, + { + "id": "Wizard.genOptWater", + "surface": "Setup wizard: Map", + "label": "Water", + "kind": "dropdown", + "level": "conditional: Overland generator chosen", + "loc": "src/SetupWizardView.ts:647", + "desc": "How much of the map is water.", + "pick": "advanced", + "why": "Generator options are part of using generators; Simple gets the dice re-roll.", + "lists": "10%..85%", + "focused": true, + "mix": "", + "group": "Setup wizard", + "subgroup": "Map" + }, + { + "id": "Wizard.genOptClimate", + "surface": "Setup wizard: Map", + "label": "Climate", + "kind": "dropdown", + "level": "conditional: Overland generator chosen", + "loc": "src/SetupWizardView.ts:647", + "desc": "Overall climate of generated terrain.", + "pick": "advanced", + "why": "Generator options are part of using generators; Simple gets the dice re-roll.", + "lists": "Temperate, Lush, Arid, Frozen, Volcanic", + "focused": true, + "mix": "", + "group": "Setup wizard", + "subgroup": "Map" + }, + { + "id": "Wizard.genOptRelief", + "surface": "Setup wizard: Map", + "label": "Relief", + "kind": "dropdown", + "level": "conditional: Overland generator chosen", + "loc": "src/SetupWizardView.ts:647", + "desc": "How hilly or mountainous the map is.", + "pick": "advanced", + "why": "Generator options are part of using generators; Simple gets the dice re-roll.", + "lists": "Flat, Normal, Rugged", + "focused": true, + "mix": "", + "group": "Setup wizard", + "subgroup": "Map" + }, + { + "id": "Wizard.genOptSea", + "surface": "Setup wizard: Map", + "label": "Sea", + "kind": "dropdown", + "level": "conditional: Overland generator chosen", + "loc": "src/SetupWizardView.ts:647", + "desc": "Where the sea goes.", + "pick": "advanced", + "why": "Generator options are part of using generators; Simple gets the dice re-roll.", + "lists": "One side (random), N/E/S/W, island, scattered, none", + "focused": true, + "mix": "", + "group": "Setup wizard", + "subgroup": "Map" + }, + { + "id": "Wizard.genOptOther", + "surface": "Setup wizard: Map", + "label": "(other generator options)", + "kind": "dropdown", + "level": "conditional: another generator chosen", + "loc": "src/SetupWizardView.ts:647", + "desc": "Options of whichever other generator is picked (space, learned).", + "pick": "advanced", + "why": "Options of other generators are part of using generators; defaults and Re-roll cover Simple.", + "lists": "Per-generator option choices", + "focused": true, + "mix": "", + "group": "Setup wizard", + "subgroup": "Map" + }, + { + "id": "Wizard.tuning", + "surface": "Setup wizard: Map", + "label": "Engine tuning sliders", + "kind": "slider", + "level": "conditional: another generator chosen", + "loc": "src/SetupWizardView.ts:647", + "desc": "5 to 10 sliders per generator that most change the layout, each with its default and a reset.", + "pick": "advanced", + "why": "Owner 2026-10-12: Advanced is a trimmed set of tuning sliders.", + "lists": "Per-generator option choices", + "focused": true, + "mix": "", + "group": "Setup wizard", + "subgroup": "Map" + }, + { + "id": "Wizard.reroll", + "surface": "Setup wizard: Map", + "label": "Re-roll (dice)", + "kind": "button", + "level": "conditional: non-blank generator", + "loc": "src/SetupWizardView.ts:607", + "desc": "Generate again with a new random seed.", + "pick": "keep", + "why": "Simple and fun; replaces most generator options.", + "lists": "", + "focused": null, + "mix": "", + "group": "Setup wizard", + "subgroup": "Map" + }, + { + "id": "Wizard.openHexMap", + "surface": "Setup wizard: Done", + "label": "Open hex map", + "kind": "button", + "level": "always (final step)", + "loc": "src/SetupWizardView.ts:841", + "desc": "Finish and open the new map.", + "pick": "keep", + "why": "Obvious action.", + "lists": "", + "focused": null, + "mix": "", + "group": "Setup wizard", + "subgroup": "Done" + }, + { + "id": "Wizard.exploreOnOwn", + "surface": "Setup wizard: Done", + "label": "I'll explore on my own", + "kind": "button", + "level": "always (final step)", + "loc": "src/SetupWizardView.ts:847", + "desc": "Finish without opening the map.", + "pick": "keep", + "why": "Fine secondary action.", + "lists": "", + "focused": null, + "mix": "", + "group": "Setup wizard", + "subgroup": "Done" + }, + { + "id": "Wizard.back", + "surface": "Setup wizard", + "label": "back", + "kind": "button", + "level": "always (not final step)", + "loc": "src/SetupWizardView.ts:943", + "desc": "Go to the previous step.", + "pick": "keep", + "why": "Standard navigation.", + "lists": "", + "focused": null, + "mix": "", + "group": "Setup wizard", + "subgroup": "Navigation" + }, + { + "id": "Wizard.next", + "surface": "Setup wizard", + "label": "Next", + "kind": "button", + "level": "always (not final step)", + "loc": "src/SetupWizardView.ts:957", + "desc": "Continue (runs that step's setup).", + "pick": "keep", + "why": "Standard navigation.", + "lists": "", + "focused": null, + "mix": "", + "group": "Setup wizard", + "subgroup": "Navigation" + }, + { + "id": "Wizard.remindLater", + "surface": "Setup wizard", + "label": "Remind me later", + "kind": "button", + "level": "always", + "loc": "src/SetupWizardView.ts:967", + "desc": "Close the wizard; it returns next launch.", + "pick": "keep", + "why": "Reasonable escape.", + "lists": "", + "focused": null, + "mix": "", + "group": "Setup wizard", + "subgroup": "Navigation" + }, + { + "id": "Wizard.dontShowAgain", + "surface": "Setup wizard", + "label": "Don't show again", + "kind": "button", + "level": "always", + "loc": "src/SetupWizardView.ts:975", + "desc": "Close and never auto-open the wizard.", + "pick": "keep", + "why": "Reasonable escape; re-runnable from settings.", + "lists": "", + "focused": null, + "mix": "", + "group": "Setup wizard", + "subgroup": "Navigation" + }, + { + "id": "Hint.turnOnFeature", + "surface": "Advanced feature hints: Advanced hint (inline)", + "label": "Turn on ", + "kind": "button", + "level": "conditional: Simple, feature off, hint not closed", + "loc": "src/advancedHints.ts:158", + "desc": "Turns on the one hidden feature this hint is about.", + "pick": "keep", + "why": "Good ramp-up path, low cost.", + "lists": "", + "focused": null, + "mix": "", + "group": "Feature hints", + "subgroup": "Inline hints" + }, + { + "id": "Hint.close", + "surface": "Advanced feature hints: Advanced hint (inline, single and multi)", + "label": "X (Hide this hint)", + "kind": "button", + "level": "conditional: hint shown", + "loc": "src/advancedHints.ts:160", + "desc": "Hides this hint at this spot.", + "pick": "keep", + "why": "Must be dismissable.", + "lists": "", + "focused": null, + "mix": "", + "group": "Feature hints", + "subgroup": "Inline hints" + }, + { + "id": "Hints.show", + "surface": "Advanced feature hints: Advanced hints line (multi)", + "label": "Show", + "kind": "button", + "level": "conditional: Simple, 2+ features off", + "loc": "src/advancedHints.ts:191", + "desc": "Opens More options listing the hidden features.", + "pick": "keep", + "why": "One line instead of a stack of hints.", + "lists": "", + "focused": null, + "mix": "", + "group": "Feature hints", + "subgroup": "Inline hints" + }, + { + "id": "MoreFeatures.turnOn", + "surface": "Advanced feature hints: More options modal", + "label": "Turn on", + "kind": "button", + "level": "conditional: feature off", + "loc": "src/advancedHints.ts:235", + "desc": "Turns on one listed feature.", + "pick": "keep", + "why": "Focused, small modal.", + "lists": "", + "focused": null, + "mix": "", + "group": "Feature hints", + "subgroup": "More options modal" + }, + { + "id": "MoreFeatures.turnOnAll", + "surface": "Advanced feature hints: More options modal", + "label": "Turn on all advanced features", + "kind": "button", + "level": "always", + "loc": "src/advancedHints.ts:241", + "desc": "Switches to Advanced.", + "pick": "keep", + "why": "Clear shortcut.", + "lists": "", + "focused": null, + "mix": "", + "group": "Feature hints", + "subgroup": "More options modal" + }, + { + "id": "MoreFeatures.closeButtons", + "surface": "Advanced feature hints: More options modal", + "label": "Done", + "kind": "button", + "level": "always", + "loc": "src/advancedHints.ts:244", + "desc": "Closes the modal.", + "pick": "keep", + "why": "Standard close.", + "lists": "", + "focused": null, + "mix": "", + "group": "Feature hints", + "subgroup": "More options modal" + }, + { + "id": "EnableFeature.turnOnOne", + "surface": "Advanced feature hints: Turn on ? modal", + "label": "Turn on ", + "kind": "button", + "level": "conditional: Simple user reaches a hidden feature", + "loc": "src/advancedHints.ts:274", + "desc": "Turns on just this feature, then continues.", + "pick": "keep", + "why": "Right moment to ask.", + "lists": "", + "focused": null, + "mix": "", + "group": "Feature hints", + "subgroup": "Turn on ? modal" + }, + { + "id": "EnableFeature.turnOnAll", + "surface": "Advanced feature hints: Turn on ? modal", + "label": "Turn on all advanced features", + "kind": "button", + "level": "conditional: as above", + "loc": "src/advancedHints.ts:276", + "desc": "Switches to Advanced, then continues.", + "pick": "keep", + "why": "Clear shortcut.", + "lists": "", + "focused": null, + "mix": "", + "group": "Feature hints", + "subgroup": "Turn on ? modal" + }, + { + "id": "EnableFeature.closeButtons", + "surface": "Advanced feature hints: Turn on ? modal", + "label": "Not now", + "kind": "button", + "level": "conditional: as above", + "loc": "src/advancedHints.ts:277", + "desc": "Closes without enabling.", + "pick": "keep", + "why": "Standard cancel.", + "lists": "", + "focused": null, + "mix": "", + "group": "Feature hints", + "subgroup": "Turn on ? modal" + }, + { + "id": "Nudge.turnOnAdvanced", + "surface": "Advanced feature hints: Ready for more? modal", + "label": "Turn on advanced features", + "kind": "button", + "level": "conditional: Simple, 2+ maps or 14 days", + "loc": "src/advancedHints.ts:318", + "desc": "Switches to Advanced.", + "pick": "keep", + "why": "One-time check-in; fine.", + "lists": "", + "focused": null, + "mix": "", + "group": "Feature hints", + "subgroup": "Ready for more? modal" + }, + { + "id": "Nudge.closeButtons", + "surface": "Advanced feature hints: Ready for more? modal", + "label": "Not now", + "kind": "button", + "level": "conditional: as above", + "loc": "src/advancedHints.ts:323", + "desc": "Closes; asks again in 14 days.", + "pick": "keep", + "why": "Standard cancel.", + "lists": "", + "focused": null, + "mix": "", + "group": "Feature hints", + "subgroup": "Ready for more? modal" + }, + { + "id": "Nudge.dontAskAgain", + "surface": "Advanced feature hints: Ready for more? modal", + "label": "Don't ask again", + "kind": "button", + "level": "conditional: as above", + "loc": "src/advancedHints.ts:324", + "desc": "Never show the check-in again.", + "pick": "keep", + "why": "Respects users who said no.", + "lists": "", + "focused": null, + "mix": "", + "group": "Feature hints", + "subgroup": "Ready for more? modal" + }, + { + "id": "Plugin.ribbonOpenHexMap", + "surface": "Command palette and ribbon", + "label": "Open hex map", + "kind": "ribbon", + "level": "always", + "loc": "src/HexmakerPlugin.ts:278", + "desc": "Opens the hex map.", + "pick": "simple", + "why": "The way into the plugin; pin it so no level ever hides it.", + "lists": "", + "focused": null, + "mix": "", + "group": "Commands & menus", + "subgroup": "Open views" + }, + { + "id": "Plugin.cmd.openHexMap", + "surface": "Command palette and ribbon", + "label": "Open hex map", + "kind": "command", + "level": "always", + "loc": "src/HexmakerPlugin.ts:281", + "desc": "Opens the hex map.", + "pick": "keep", + "why": "Core.", + "lists": "", + "focused": null, + "mix": "", + "group": "Commands & menus", + "subgroup": "Open views" + }, + { + "id": "Plugin.cmd.openHexTable", + "surface": "Command palette and ribbon", + "label": "Open hex table", + "kind": "command", + "level": "always", + "loc": "src/HexmakerPlugin.ts:286", + "desc": "Opens the spreadsheet of hex notes.", + "pick": "simple", + "why": "The hex table is the basic overview of every hex; pin it.", + "lists": "", + "focused": null, + "mix": "", + "group": "Commands & menus", + "subgroup": "Open views" + }, + { + "id": "Plugin.cmd.openTerrainGenerator", + "surface": "Command palette and ribbon", + "label": "Open terrain generator", + "kind": "command", + "level": "always (prompts to enable in Simple)", + "loc": "src/HexmakerPlugin.ts:294", + "desc": "Opens the generator page.", + "pick": "keep", + "why": "Already feature-gated: in Simple it asks to turn generators on, which is the ramp.", + "lists": "", + "focused": null, + "mix": "", + "group": "Commands & menus", + "subgroup": "Open views" + }, + { + "id": "Plugin.cmd.openPaletteEditor", + "surface": "Command palette and ribbon", + "label": "Open palette editor", + "kind": "command", + "level": "always (prompts to enable in Simple)", + "loc": "src/HexmakerPlugin.ts:299", + "desc": "Opens the palette editor page.", + "pick": "simple", + "why": "Custom palettes are Simple (owner tagged Add palette and Edit simple); the command should just open the editor. Owner (pass 3): \"a streamlined but still customizable experience for simple, not to hide every little possible scary thing.\"", + "lists": "", + "focused": null, + "mix": "", + "group": "Commands & menus", + "subgroup": "Open views", + "prevPick": "keep" + }, + { + "id": "Plugin.cmd.editWorldTypes", + "surface": "Command palette and ribbon", + "label": "Edit world types...", + "kind": "command", + "level": "feature:generators", + "loc": "src/HexmakerPlugin.ts:304", + "desc": "Edits which worlds space generators place (Space on only).", + "pick": "keep", + "why": "World types are Advanced and this is already gated to generators and Space.", + "lists": "", + "focused": null, + "mix": "", + "group": "Commands & menus", + "subgroup": "Open views" + }, + { + "id": "Plugin.cmd.newOverworld", + "surface": "Command palette and ribbon", + "label": "New overworld...", + "kind": "command", + "level": "feature:regions", + "loc": "src/HexmakerPlugin.ts:316", + "desc": "Creates an overworld that joins maps.", + "pick": "keep", + "why": "Already gated to the regions feature.", + "lists": "", + "focused": null, + "mix": "", + "group": "Commands & menus", + "subgroup": "Open views" + }, + { + "id": "Plugin.cmd.openRandomTables", + "surface": "Command palette and ribbon", + "label": "Open random tables", + "kind": "command", + "level": "always", + "loc": "src/HexmakerPlugin.ts:355", + "desc": "Opens the random tables view.", + "pick": "simple", + "why": "Rolling tables is core to a hexcrawl; pin the command.", + "lists": "", + "focused": null, + "mix": "", + "group": "Commands & menus", + "subgroup": "Open views" + }, + { + "id": "WorldTypes.command", + "surface": "Command palette and ribbon", + "label": "Edit world types…", + "kind": "command", + "level": "space (src/HexmakerPlugin.ts:311)", + "loc": "src/space/WorldTypesModal.ts:311", + "desc": "Opens the World types editor.", + "pick": "keep", + "why": "Same control inventoried twice (another render path or pass); follows Plugin.cmd.editWorldTypes. Earlier reason: Same world types command as above; already gated to Space and generators.", + "lists": "", + "focused": null, + "mix": "", + "group": "Commands & menus", + "subgroup": "Open views", + "twinOf": "Plugin.cmd.editWorldTypes" + }, + { + "id": "Plugin.cmd.mapGoUp", + "surface": "Command palette and ribbon", + "label": "Go up to parent map", + "kind": "command", + "level": "conditional: map has a parent", + "loc": "src/HexmakerPlugin.ts:325", + "desc": "Navigate to the parent map.", + "pick": "keep", + "why": "Hotkey-able navigation.", + "lists": "", + "focused": null, + "mix": "", + "group": "Commands & menus", + "subgroup": "Map navigation commands" + }, + { + "id": "Plugin.cmd.mapGoBack", + "surface": "Command palette and ribbon", + "label": "Go back to previous map", + "kind": "command", + "level": "conditional: map history", + "loc": "src/HexmakerPlugin.ts:335", + "desc": "Back in map history.", + "pick": "keep", + "why": "Navigation.", + "lists": "", + "focused": null, + "mix": "", + "group": "Commands & menus", + "subgroup": "Map navigation commands" + }, + { + "id": "Plugin.cmd.mapGoForward", + "surface": "Command palette and ribbon", + "label": "Go forward to the next map", + "kind": "command", + "level": "conditional: map history", + "loc": "src/HexmakerPlugin.ts:345", + "desc": "Forward in map history.", + "pick": "keep", + "why": "Navigation.", + "lists": "", + "focused": null, + "mix": "", + "group": "Commands & menus", + "subgroup": "Map navigation commands" + }, + { + "id": "Plugin.cmd.addRollRanges", + "surface": "Command palette and ribbon", + "label": "Add roll ranges to tables", + "kind": "command", + "level": "always", + "loc": "src/HexmakerPlugin.ts:363", + "desc": "Adds roll-range columns to older tables.", + "pick": "overkill", + "why": "Migration/maintenance command; already offered automatically after an update.", + "lists": "", + "focused": null, + "mix": "", + "group": "Commands & menus", + "subgroup": "Maintenance commands" + }, + { + "id": "Plugin.cmd.checkTables", + "surface": "Command palette and ribbon", + "label": "Check tables", + "kind": "command", + "level": "always", + "loc": "src/HexmakerPlugin.ts:368", + "desc": "Checks table notes for problems.", + "pick": "overkill", + "why": "Diagnostic command for table notes.", + "lists": "", + "focused": null, + "mix": "", + "group": "Commands & menus", + "subgroup": "Maintenance commands" + }, + { + "id": "Plugin.cmd.addMapDataToHexNotes", + "surface": "Command palette and ribbon", + "label": "Add map data to this map's hex notes", + "kind": "command", + "level": "conditional: a map is open", + "loc": "src/HexmakerPlugin.ts:416", + "desc": "Adds a Map data box to every hex note (asks first).", + "pick": "overkill", + "why": "Backfill maintenance for older hex notes.", + "lists": "", + "focused": null, + "mix": "", + "group": "Commands & menus", + "subgroup": "Maintenance commands" + }, + { + "id": "Plugin.cmd.updateRegionFactionMapData", + "surface": "Command palette and ribbon", + "label": "Update map data in region and faction notes", + "kind": "command", + "level": "conditional: region/faction notes exist", + "loc": "src/HexmakerPlugin.ts:438", + "desc": "Adds/refreshes Map data boxes in region and faction notes.", + "pick": "overkill", + "why": "Backfill maintenance; notes refresh on open anyway.", + "lists": "", + "focused": null, + "mix": "", + "group": "Commands & menus", + "subgroup": "Maintenance commands" + }, + { + "id": "Plugin.cmd.exportNotePdf", + "surface": "Command palette and ribbon", + "label": "Export current note to PDF", + "kind": "command", + "level": "conditional: markdown note active", + "loc": "src/HexmakerPlugin.ts:373", + "desc": "Exports the active note as PDF.", + "pick": "advanced", + "why": "Export option beyond hexcrawl basics; Obsidian also exports notes itself.", + "lists": "", + "focused": null, + "mix": "", + "group": "Commands & menus", + "subgroup": "Export commands" + }, + { + "id": "Plugin.cmd.exportNoteMarkdown", + "surface": "Command palette and ribbon", + "label": "Export current note to Markdown", + "kind": "command", + "level": "conditional: markdown note active", + "loc": "src/HexmakerPlugin.ts:383", + "desc": "Exports the active note as Markdown.", + "pick": "advanced", + "why": "Export option beyond hexcrawl basics.", + "lists": "", + "focused": null, + "mix": "", + "group": "Commands & menus", + "subgroup": "Export commands" + }, + { + "id": "Plugin.cmd.exportCurrentHex", + "surface": "Command palette and ribbon", + "label": "Export current hex (structured PDF / Markdown)", + "kind": "command", + "level": "conditional: hex note active", + "loc": "src/HexmakerPlugin.ts:393", + "desc": "Structured export of a hex note.", + "pick": "simple", + "why": "Basic export of one hex.", + "lists": "", + "focused": null, + "mix": "", + "group": "Commands & menus", + "subgroup": "Export commands" + }, + { + "id": "Plugin.cmd.exportCurrentWorkflow", + "surface": "Command palette and ribbon", + "label": "Export current workflow with rolled samples", + "kind": "command", + "level": "conditional: workflow note active", + "loc": "src/HexmakerPlugin.ts:403", + "desc": "Exports a workflow with sample rolls.", + "pick": "advanced", + "why": "Workflow export belongs with workflows, an Advanced feature.", + "lists": "", + "focused": null, + "mix": "", + "group": "Commands & menus", + "subgroup": "Export commands" + }, + { + "id": "Plugin.cmd.exportCurrentMap", + "surface": "Command palette and ribbon", + "label": "Export current map...", + "kind": "command", + "level": "conditional: a map exists", + "loc": "src/HexmakerPlugin.ts:456", + "desc": "Opens map export (PNG / PDF / manual).", + "pick": "simple", + "why": "Basic export: the map export entry point.", + "lists": "", + "focused": null, + "mix": "", + "group": "Commands & menus", + "subgroup": "Export commands" + }, + { + "id": "Plugin.fileMenuExportPdf", + "surface": "Note right-click menus: File menu (right-click any note)", + "label": "Export to PDF", + "kind": "menu", + "level": "always (every .md file in vault)", + "loc": "src/HexmakerPlugin.ts:473", + "desc": "Exports any note as PDF.", + "pick": "advanced", + "why": "Export option beyond the basics; adds a menu item to every note.", + "lists": "", + "focused": null, + "mix": "", + "group": "Commands & menus", + "subgroup": "Note right-click menus" + }, + { + "id": "Plugin.fileMenuExportMarkdown", + "surface": "Note right-click menus: File menu (right-click any note)", + "label": "Export to Markdown", + "kind": "menu", + "level": "always (every .md file in vault)", + "loc": "src/HexmakerPlugin.ts:480", + "desc": "Exports any note as Markdown.", + "pick": "advanced", + "why": "Export option beyond the basics; adds a menu item to every note.", + "lists": "", + "focused": null, + "mix": "", + "group": "Commands & menus", + "subgroup": "Note right-click menus" + }, + { + "id": "Plugin.editorMenuInsertRoller", + "surface": "Note right-click menus: Editor menu (right-click in editor)", + "label": "Insert table roller", + "kind": "menu", + "level": "always (every editor)", + "loc": "src/HexmakerPlugin.ts:506", + "desc": "Inserts an embedded roller for a chosen table.", + "pick": "keep", + "why": "Useful in session notes.", + "lists": "", + "focused": null, + "mix": "", + "group": "Commands & menus", + "subgroup": "Note right-click menus" + }, + { + "id": "Plugin.editorMenuInsertMapLink", + "surface": "Note right-click menus: Editor menu (right-click in editor)", + "label": "Insert map link", + "kind": "menu", + "level": "always (every editor)", + "loc": "src/HexmakerPlugin.ts:523", + "desc": "Inserts a link that opens a map.", + "pick": "keep", + "why": "Useful linking.", + "lists": "", + "focused": null, + "mix": "", + "group": "Commands & menus", + "subgroup": "Note right-click menus" + }, + { + "id": "Plugin.insertRollerPicker", + "surface": "Note right-click menus: Insert table roller picker", + "label": "Search for a file to link...", + "kind": "picker", + "level": "conditional: from editor menu", + "loc": "src/hex-map/FileLinkSuggestModal.ts:19", + "desc": "Pick a table file to embed as a roller.", + "pick": "keep", + "why": "Same control inventoried twice (another render path or pass); follows Editor.insertTableRoller. Earlier reason: Scoped to the tables folder.", + "lists": "Files under the tables folder (any extension)", + "focused": true, + "mix": "", + "group": "Commands & menus", + "subgroup": "Note right-click menus", + "twinOf": "Editor.insertTableRoller" + }, + { + "id": "Editor.insertTableRoller", + "surface": "Note right-click menus: Editor context menu → Insert table roller", + "label": "Search for a file to link...", + "kind": "picker", + "level": "always", + "loc": "src/HexmakerPlugin.ts:512", + "desc": "Pick a table to embed a roller block in the note.", + "pick": "keep", + "why": "Focused on tables", + "lists": "every file (no extension filter) under tablesFolder minus templates/_ : user tables + per-terrain description/encounter tables + region tables", + "focused": true, + "mix": "", + "group": "Commands & menus", + "subgroup": "Note right-click menus" + }, + { + "id": "MapToolbar.hexTableBtn", + "surface": "Hex map view: top bar", + "label": "Open hex table (⊞)", + "kind": "button", + "level": "always", + "loc": "src/hex-map/HexMapView.ts:1473", + "desc": "Opens a spreadsheet of every hex note; middle-click for a new tab.", + "pick": "simple", + "why": "The hex table is the basic overview of every hex; pin its button.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Top bar" + }, + { + "id": "MapToolbar.randomTablesBtn", + "surface": "Hex map view: top bar", + "label": "Open random tables (🎲)", + "kind": "button", + "level": "always", + "loc": "src/hex-map/HexMapView.ts:1497", + "desc": "Opens the random tables browser to roll encounters and more.", + "pick": "simple", + "why": "Rolling tables is core to a hexcrawl; pin the toolbar entry.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Top bar" + }, + { + "id": "MapToolbar.mapSwitcher", + "surface": "Hex map view: top bar", + "label": " ▾ (Manage maps)", + "kind": "button", + "level": "always", + "loc": "src/hex-map/HexMapView.ts:1529", + "desc": "Opens the map list to switch, create, rename or set up maps.", + "pick": "keep", + "why": "The one place to pick/manage maps.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Top bar" + }, + { + "id": "MapToolbar.workModeBtn", + "surface": "Hex map view: top bar", + "label": "Mode: Play / Build / God", + "kind": "button", + "level": "always", + "loc": "src/hex-map/HexMapView.ts:1551", + "desc": "Shows this map's mode; click to switch between Play, Build and God.", + "pick": "simple", + "why": "Play/Build is how a newcomer stops editing during a game; pin it.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Top bar" + }, + { + "id": "MapToolbar.undo", + "surface": "Hex map view: top bar", + "label": "Undo (up to 20) ↩", + "kind": "button", + "level": "always", + "loc": "src/hex-map/HexMapView.ts:1555", + "desc": "Undo the last map change.", + "pick": "keep", + "why": "Essential safety net.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Top bar" + }, + { + "id": "MapToolbar.redo", + "surface": "Hex map view: top bar", + "label": "Redo ↪", + "kind": "button", + "level": "always", + "loc": "src/hex-map/HexMapView.ts:1565", + "desc": "Redo what you just undid.", + "pick": "keep", + "why": "Pairs with undo.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Top bar" + }, + { + "id": "MapToolbar.help", + "surface": "Hex map view: top bar", + "label": "Controls & tools (?)", + "kind": "button", + "level": "always", + "loc": "src/hex-map/HexMapView.ts:1577", + "desc": "Opens the help sheet of mouse controls and tools.", + "pick": "keep", + "why": "Newcomer lifeline.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Top bar" + }, + { + "id": "MapToolbar.drawingToolsToggle", + "surface": "Hex map view: top bar", + "label": "Drawing tools (pencil)", + "kind": "button", + "level": "always", + "loc": "src/hex-map/HexSidePanel.ts:22", + "desc": "Opens the panel of painting and drawing tools.", + "pick": "keep", + "why": "Entry point to all editing tools.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Top bar" + }, + { + "id": "MapToolbar.layersToggle", + "surface": "Hex map view: top bar", + "label": "Map overlays (layers)", + "kind": "button", + "level": "always", + "loc": "src/hex-map/HexSidePanel.ts:22", + "desc": "Opens the panel that shows or hides map layers and labels.", + "pick": "keep", + "why": "Entry to visibility toggles.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Top bar" + }, + { + "id": "MapNav.breadcrumb", + "surface": "Hex map view: map navigation", + "label": "Go to (breadcrumb)", + "kind": "button", + "level": "conditional: on a submap", + "loc": "src/hex-map/HexMapView.ts:690", + "desc": "Jump to any parent map above this one.", + "pick": "keep", + "why": "Clear way out of nested maps.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Map navigation" + }, + { + "id": "MapNav.back", + "surface": "Hex map view: map navigation", + "label": "← Back to (Alt+←)", + "kind": "button", + "level": "conditional: after moving between maps", + "loc": "src/hex-map/HexMapView.ts:723", + "desc": "Return to the map you were on before.", + "pick": "keep", + "why": "Expected browser-like navigation.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Map navigation" + }, + { + "id": "MapNav.up", + "surface": "Hex map view: map navigation", + "label": "↑ Up to (Alt+↑)", + "kind": "button", + "level": "conditional: after moving between maps", + "loc": "src/hex-map/HexMapView.ts:723", + "desc": "Go to the parent map of this one.", + "pick": "keep", + "why": "Core for nested maps.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Map navigation" + }, + { + "id": "MapNav.forward", + "surface": "Hex map view: map navigation", + "label": "→ Forward to (Alt+→)", + "kind": "button", + "level": "conditional: after moving between maps", + "loc": "src/hex-map/HexMapView.ts:723", + "desc": "Go forward again after going back.", + "pick": "keep", + "why": "Standard back/forward navigation; only shows after moving between maps.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Map navigation" + }, + { + "id": "MapNav.regionFlowerHere", + "surface": "Hex map view: map navigation", + "label": "Here: . Click to edit this region.", + "kind": "button", + "level": "conditional: inside a region of an overworld", + "loc": "src/hex-map/HexMapView.ts:859", + "desc": "Centre petal of the neighbour flower; opens the region editor.", + "pick": "keep", + "why": "Only shows inside an overworld region, already gated by the regions feature.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Map navigation" + }, + { + "id": "MapNav.regionFlowerPetal", + "surface": "Hex map view: map navigation", + "label": " petal", + "kind": "button", + "level": "conditional: inside a region of an overworld", + "loc": "src/hex-map/HexMapView.ts:878", + "desc": "Jump to the neighbouring region in that direction.", + "pick": "keep", + "why": "Fast walk between adjacent regions.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Map navigation" + }, + { + "id": "MapNav.regionFlowerNewLand", + "surface": "Hex map view: map navigation", + "label": "+ (new land petal)", + "kind": "button", + "level": "conditional: region of overworld; mode: build/god", + "loc": "src/hex-map/HexMapView.ts:878", + "desc": "Walk into empty land next door: pick or roll its biome and make a region.", + "pick": "keep", + "why": "Core overworld-building action.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Map navigation" + }, + { + "id": "MapNav.mapPadGo", + "surface": "Hex map view: map navigation", + "label": "D-pad neighbour map (◀▲▶▼)", + "kind": "button", + "level": "conditional: map on a side-by-side world grid", + "loc": "src/hex-map/HexMapView.ts:921", + "desc": "Jump to the neighbouring map on that side.", + "pick": "keep", + "why": "Only shows on side-by-side world grids, which are already an advanced setup.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Map navigation" + }, + { + "id": "MapNav.mapPadNew", + "surface": "Hex map view: map navigation", + "label": "+ (new neighbouring map)", + "kind": "button", + "level": "feature:regions", + "loc": "src/hex-map/HexMapView.ts:921", + "desc": "Make a new map on that side (asks for a terrain generator).", + "pick": "keep", + "why": "Already gated to the regions feature.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Map navigation" + }, + { + "id": "WorkModeMenu.play", + "surface": "Hex map view: work-mode menu", + "label": "Play: Run a game…", + "kind": "menu", + "level": "always", + "loc": "src/hex-map/HexMapView.ts:758", + "desc": "Lock the map; move tokens, read notes and roll only.", + "pick": "simple", + "why": "Play is the safe mode for running sessions; pin it (God stays Advanced).", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Work modes" + }, + { + "id": "WorkModeMenu.build", + "surface": "Hex map view: work-mode menu", + "label": "Build: Add to and edit the map…", + "kind": "menu", + "level": "always", + "loc": "src/hex-map/HexMapView.ts:758", + "desc": "Paint, draw paths, make maps and regions.", + "pick": "simple", + "why": "Build is where all map-making happens; pin it.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Work modes" + }, + { + "id": "WorkModeMenu.god", + "surface": "Hex map view: work-mode menu", + "label": "God: Change anything…", + "kind": "menu", + "level": "always", + "loc": "src/hex-map/HexMapView.ts:758", + "desc": "Unlocks rerolls, regenerating, swapping hexes and deleting.", + "pick": "advanced", + "why": "God mode is a real feature (rerolls, swaps, deletes) beyond what a newcomer needs.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Work modes" + }, + { + "id": "ModeBar.stop", + "surface": "Hex map view: mode bar", + "label": "Stop this tool (✕)", + "kind": "button", + "level": "conditional: a tool is on", + "loc": "src/hex-map/HexMapView.ts:1032", + "desc": "Turn off the active tool.", + "pick": "keep", + "why": "Obvious exit; shows what's active.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Work modes" + }, + { + "id": "ModeBar.autoRoute", + "surface": "Hex map view: mode bar", + "label": "Auto-route", + "kind": "toggle", + "level": "conditional: path tool on", + "loc": "src/hex-map/pathTool.ts:1423", + "desc": "On: a far click routes around terrain. Off: draw hex by hex.", + "pick": "simple", + "why": "Same basic path choice while drawing.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Work modes" + }, + { + "id": "ModeBar.crossImpassable", + "surface": "Hex map view: mode bar", + "label": "Cross impassable", + "kind": "checkbox", + "level": "conditional: path tool, palette has impassable terrain", + "loc": "src/hex-map/pathTool.ts:1453", + "desc": "Let new path legs go through impassable terrain like water.", + "pick": "advanced", + "why": "A path-drawing option beyond the basics; only shows when relevant.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Work modes" + }, + { + "id": "ModeBar.pathNameChip", + "surface": "Hex map view: mode bar", + "label": " (Rename this path)", + "kind": "button", + "level": "conditional: a path is selected", + "loc": "src/hex-map/pathTool.ts:1462", + "desc": "Shows the selected path's name; click to rename.", + "pick": "keep", + "why": "Shows which path is selected; a plain, useful label.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Work modes" + }, + { + "id": "ModeBar.newPath", + "surface": "Hex map view: mode bar", + "label": "New path", + "kind": "button", + "level": "conditional: path tool on", + "loc": "src/hex-map/pathTool.ts:1469", + "desc": "Start a separate path with the next click (Alt+click does the same).", + "pick": "simple", + "why": "Needed to draw a second road.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Work modes" + }, + { + "id": "ModeBar.done", + "surface": "Hex map view: mode bar", + "label": "Done", + "kind": "button", + "level": "conditional: path selected or drawing", + "loc": "src/hex-map/pathTool.ts:1477", + "desc": "Finish this branch or deselect the path (Esc).", + "pick": "simple", + "why": "Finishing a path is basic drawing.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Work modes" + }, + { + "id": "ModeBar.confirmIntoRegions", + "surface": "Hex map view: mode bar", + "label": "Confirm into regions / Update regions", + "kind": "button", + "level": "conditional: overworld path selected, build", + "loc": "src/hex-map/HexMapView.ts:6253", + "desc": "Copy this overworld path into every region it crosses.", + "pick": "keep", + "why": "Only shows for overworld paths, already gated by the regions feature.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Work modes" + }, + { + "id": "DrawingPanel.centerHex", + "surface": "Hex map view: drawing tools panel", + "label": "Center hex", + "kind": "button", + "level": "always", + "loc": "src/hex-map/HexMapView.ts:2023", + "desc": "Type coordinates to jump the view to that hex.", + "pick": "keep", + "why": "Plain navigation a normal user uses; placement can be fixed separately.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Drawing tools" + }, + { + "id": "DrawingPanel.terrain", + "surface": "Hex map view: drawing tools panel", + "label": "Terrain", + "kind": "button", + "level": "mode: build/god", + "loc": "src/hex-map/HexMapView.ts:2031", + "desc": "Pick a terrain and paint it on hexes (brush size, eyedropper).", + "pick": "keep", + "why": "Core map painting.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Drawing tools" + }, + { + "id": "DrawingPanel.biome", + "surface": "Hex map view: drawing tools panel", + "label": "Biome", + "kind": "button", + "level": "conditional: overworld; mode: build/god", + "loc": "src/hex-map/HexMapView.ts:2043", + "desc": "Pick a biome and paint it on the overworld; regions are made as you go.", + "pick": "keep", + "why": "The overworld's core paint tool.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Drawing tools" + }, + { + "id": "DrawingPanel.icon", + "surface": "Hex map view: drawing tools panel", + "label": "Icon", + "kind": "button", + "level": "mode: build/god", + "loc": "src/hex-map/HexMapView.ts:2051", + "desc": "Pick an icon and stamp it on hexes (optionally GM-only).", + "pick": "keep", + "why": "Core for marking features.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Drawing tools" + }, + { + "id": "DrawingPanel.path", + "surface": "Hex map view: drawing tools panel", + "label": "Path", + "kind": "button", + "level": "mode: build/god", + "loc": "src/hex-map/HexMapView.ts:2062", + "desc": "Draw roads, rivers and other paths across hexes.", + "pick": "simple", + "why": "Drawing roads and rivers is basic map-making.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Drawing tools" + }, + { + "id": "DrawingPanel.linkTable", + "surface": "Hex map view: drawing tools panel", + "label": "Link table", + "kind": "button", + "level": "always", + "loc": "src/hex-map/HexMapView.ts:2073", + "desc": "Pick a random table, then click hexes to link it as their encounter table.", + "pick": "advanced", + "why": "Bulk table linking is a real feature beyond the basics; the hex editor covers one-offs.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Drawing tools" + }, + { + "id": "DrawingPanel.linkSubmap", + "surface": "Hex map view: drawing tools panel", + "label": "Link submap", + "kind": "button", + "level": "mode: build/god", + "loc": "src/hex-map/HexMapView.ts:2083", + "desc": "Pick a map, then click hexes to link it as a location.", + "pick": "advanced", + "why": "Bulk submap linking is a real feature, though rarely used; the hex menu covers one-offs.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Drawing tools" + }, + { + "id": "DrawingPanel.factions", + "surface": "Hex map view: drawing tools panel", + "label": "Factions", + "kind": "button", + "level": "always", + "loc": "src/hex-map/HexMapView.ts:2093", + "desc": "Pick a faction and paint its territory on hexes.", + "pick": "keep", + "why": "Faction territory is a common hexcrawl layer.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Drawing tools" + }, + { + "id": "DrawingPanel.regionAreas", + "surface": "Hex map view: drawing tools panel", + "label": "Region areas", + "kind": "button", + "level": "mode: build/god", + "loc": "src/hex-map/HexMapView.ts:2103", + "desc": "Paint named geographic areas (overlay) onto hexes.", + "pick": "advanced", + "why": "Region areas overlay is a real feature beyond a newcomer's needs.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Drawing tools" + }, + { + "id": "DrawingPanel.token", + "surface": "Hex map view: drawing tools panel", + "label": "Token", + "kind": "button", + "level": "always", + "loc": "src/hex-map/HexMapView.ts:2113", + "desc": "Make or pick a token (party, NPC) and place it on a hex.", + "pick": "simple", + "why": "Placing the party is token basics.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Drawing tools" + }, + { + "id": "MapView.tableLinkToolPicker", + "surface": "Hex map view: Map toolbar › Link table tool", + "label": "Select table", + "kind": "picker", + "level": "always", + "loc": "src/hex-map/HexMapView.ts:2424", + "desc": "Pick a random table, then click hexes to link it.", + "pick": "advanced", + "why": "The picker this control opens; it follows DrawingPanel.linkTable. Earlier reason: Focused on tables, but terrain tables crowd it", + "lists": ".md under tablesFolder, linkable: user tables + 2 tables per terrain (terrain/…) + region tables + weather/hooks starters (FolderTreePickerModal.ts:105-113)", + "focused": true, + "mix": "", + "group": "Hex map view", + "subgroup": "Drawing tools", + "twinOf": "DrawingPanel.linkTable", + "prevPick": "keep" + }, + { + "id": "PainterMenu.switchTerrain", + "surface": "Hex map view: tool right-click menu", + "label": "Switch terrain", + "kind": "menu", + "level": "conditional: terrain tool on", + "loc": "src/hex-map/HexMapView.ts:2145", + "desc": "Re-open the terrain picker.", + "pick": "keep", + "why": "Natural in-tool action.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Tool right-click menus" + }, + { + "id": "PainterMenu.switchIcon", + "surface": "Hex map view: tool right-click menu", + "label": "Switch icon", + "kind": "menu", + "level": "conditional: icon tool on", + "loc": "src/hex-map/HexMapView.ts:2149", + "desc": "Re-open the icon picker.", + "pick": "keep", + "why": "Natural in-tool action.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Tool right-click menus" + }, + { + "id": "PainterMenu.switchTable", + "surface": "Hex map view: tool right-click menu", + "label": "Switch table", + "kind": "menu", + "level": "conditional: link-table tool on", + "loc": "src/hex-map/HexMapView.ts:2153", + "desc": "Pick a different table to link.", + "pick": "keep", + "why": "Matches its tool.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Tool right-click menus" + }, + { + "id": "PainterMenu.switchSubmap", + "surface": "Hex map view: tool right-click menu", + "label": "Switch submap", + "kind": "menu", + "level": "conditional: link-submap tool on", + "loc": "src/hex-map/HexMapView.ts:2157", + "desc": "Pick a different map to link.", + "pick": "keep", + "why": "Only shows while the Link submap tool is on; gating the tool covers it.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Tool right-click menus" + }, + { + "id": "PainterMenu.switchFaction", + "surface": "Hex map view: tool right-click menu", + "label": "Switch faction", + "kind": "menu", + "level": "conditional: factions tool on", + "loc": "src/hex-map/HexMapView.ts:2161", + "desc": "Pick a different faction to paint.", + "pick": "keep", + "why": "Matches its tool.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Tool right-click menus" + }, + { + "id": "PainterMenu.switchRegion", + "surface": "Hex map view: tool right-click menu", + "label": "Switch region", + "kind": "menu", + "level": "conditional: region areas tool on", + "loc": "src/hex-map/HexMapView.ts:2165", + "desc": "Pick a different region area to paint.", + "pick": "keep", + "why": "Only shows while the Region areas tool is on; gating the tool covers it.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Tool right-click menus" + }, + { + "id": "PainterMenu.switchPathType", + "surface": "Hex map view: tool right-click menu", + "label": "Switch path type", + "kind": "menu", + "level": "conditional: path tool on", + "loc": "src/hex-map/HexMapView.ts:2169", + "desc": "Pick a different path type (road, river…).", + "pick": "keep", + "why": "Natural in-tool action.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Tool right-click menus" + }, + { + "id": "PainterMenu.switchToken", + "surface": "Hex map view: tool right-click menu", + "label": "Switch token", + "kind": "menu", + "level": "conditional: token tool on", + "loc": "src/hex-map/HexMapView.ts:2173", + "desc": "Pick a different token to place.", + "pick": "keep", + "why": "Matches its tool.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Tool right-click menus" + }, + { + "id": "PainterMenu.switchBiome", + "surface": "Hex map view: tool right-click menu", + "label": "Switch biome", + "kind": "menu", + "level": "conditional: biome tool on", + "loc": "src/hex-map/HexMapView.ts:2176", + "desc": "Pick a different biome to paint.", + "pick": "keep", + "why": "Matches its tool.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Tool right-click menus" + }, + { + "id": "PainterMenu.exitTool", + "surface": "Hex map view: tool right-click menu", + "label": "Exit tool", + "kind": "menu", + "level": "conditional: any tool on", + "loc": "src/hex-map/PainterContextMenu.ts:24", + "desc": "Turn off the active tool.", + "pick": "keep", + "why": "Obvious; cheap.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Tool right-click menus" + }, + { + "id": "PainterMenu.eraseToggle", + "surface": "Hex map view: tool right-click menu", + "label": "Erase mode / Paint (Link, Draw) mode", + "kind": "menu", + "level": "conditional: terrain/icon/link/path tool on", + "loc": "src/hex-map/HexMapView.ts:2146", + "desc": "Flip the tool between adding and erasing.", + "pick": "keep", + "why": "Only way to erase with a tool.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Tool right-click menus" + }, + { + "id": "PainterMenu.newPath", + "surface": "Hex map view: tool right-click menu", + "label": "New path", + "kind": "menu", + "level": "conditional: path tool on, not erasing", + "loc": "src/hex-map/HexMapView.ts:2171", + "desc": "Start a separate path with the next click.", + "pick": "drop", + "why": "Third way to start a new path; the mode bar's New path button (and Alt+click) replace it.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Tool right-click menus" + }, + { + "id": "PathMenu.splitHere", + "surface": "Hex map view: tool right-click menu", + "label": "Split here", + "kind": "menu", + "level": "conditional: right-click on a path (path tool)", + "loc": "src/hex-map/pathTool.ts:296", + "desc": "Cut the path in two at this point.", + "pick": "advanced", + "why": "Path surgery is a real editing option beyond what a newcomer needs.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Tool right-click menus" + }, + { + "id": "PathMenu.deleteBranch", + "surface": "Hex map view: tool right-click menu", + "label": "Delete this fork / Delete main line", + "kind": "menu", + "level": "conditional: path with forks", + "loc": "src/hex-map/pathTool.ts:297", + "desc": "Remove just this branch of a forked path.", + "pick": "keep", + "why": "Only shows on forked paths; deleting a fork is normal path editing.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Tool right-click menus" + }, + { + "id": "PathMenu.deletePath", + "surface": "Hex map view: tool right-click menu", + "label": "Delete path: ", + "kind": "menu", + "level": "conditional: right-click on a path", + "loc": "src/hex-map/pathTool.ts:299", + "desc": "Delete the whole path.", + "pick": "simple", + "why": "Basic path fix: remove a path.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Tool right-click menus" + }, + { + "id": "PathMenu.rename", + "surface": "Hex map view: tool right-click menu", + "label": "Rename…", + "kind": "menu", + "level": "conditional: right-click on a path", + "loc": "src/hex-map/pathTool.ts:300", + "desc": "Give the path a name.", + "pick": "simple", + "why": "Named roads and rivers matter in play.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Tool right-click menus" + }, + { + "id": "PathMenu.changeType", + "surface": "Hex map view: tool right-click menu", + "label": "Change type…", + "kind": "menu", + "level": "conditional: right-click on a path", + "loc": "src/hex-map/pathTool.ts:301", + "desc": "Turn the path into another type (e.g. trail to road).", + "pick": "keep", + "why": "Normal path fix-up (trail to road), used by anyone drawing paths.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Tool right-click menus" + }, + { + "id": "PathMenu.reverse", + "surface": "Hex map view: tool right-click menu", + "label": "Reverse", + "kind": "menu", + "level": "conditional: right-click on a path", + "loc": "src/hex-map/pathTool.ts:302", + "desc": "Flip the path's direction.", + "pick": "advanced", + "why": "A real path option, but direction rarely matters to a newcomer.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Tool right-click menus" + }, + { + "id": "PathMenu.switchToType", + "surface": "Hex map view: tool right-click menu", + "label": "Switch to to edit ", + "kind": "menu", + "level": "conditional: right-click on another type's path", + "loc": "src/hex-map/pathTool.ts:1075", + "desc": "Switch the path tool to that path's type to edit it.", + "pick": "keep", + "why": "Resolves a confusing dead click.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Tool right-click menus" + }, + { + "id": "PathMenu.confirmIntoRegions", + "surface": "Hex map view: tool right-click menu", + "label": "Confirm into regions / Update regions", + "kind": "menu", + "level": "conditional: overworld path, build", + "loc": "src/hex-map/HexMapView.ts:6274", + "desc": "Copy this overworld path into the regions it crosses.", + "pick": "keep", + "why": "Only shows for overworld paths, already gated by the regions feature.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Tool right-click menus" + }, + { + "id": "PathMenu.removeFromRegions", + "surface": "Hex map view: tool right-click menu", + "label": "Remove from regions", + "kind": "menu", + "level": "conditional: confirmed overworld path", + "loc": "src/hex-map/HexMapView.ts:6274", + "desc": "Take this overworld path back out of its regions.", + "pick": "keep", + "why": "Only shows for confirmed overworld paths, already gated by the regions feature.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Tool right-click menus" + }, + { + "id": "HexMenu.center", + "surface": "Hex map view: hex right-click menu", + "label": "Center on this hex", + "kind": "menu", + "level": "always", + "loc": "src/hex-map/HexMapView.ts:4773", + "desc": "Pan the view so this hex is in the middle.", + "pick": "keep", + "why": "Harmless, standard map-menu action; not backend.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Hex right-click menu" + }, + { + "id": "HexMenu.openNote", + "surface": "Hex map view: hex right-click menu", + "label": "Open note", + "kind": "menu", + "level": "always", + "loc": "src/hex-map/HexMapView.ts:4777", + "desc": "Open (or create) this hex's note.", + "pick": "keep", + "why": "Core: notes are the content.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Hex right-click menu" + }, + { + "id": "HexMenu.enterRegion", + "surface": "Hex map view: hex right-click menu", + "label": "Enter region: ", + "kind": "menu", + "level": "conditional: hex has a region map", + "loc": "src/hex-map/HexMapView.ts:4792", + "desc": "Go into the region map made from this hex.", + "pick": "keep", + "why": "Core nested-map navigation.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Hex right-click menu" + }, + { + "id": "HexMenu.openLocation", + "surface": "Hex map view: hex right-click menu", + "label": "Open: ", + "kind": "menu", + "level": "conditional: hex has 1-2 linked maps", + "loc": "src/hex-map/HexMapView.ts:4795", + "desc": "Go to a map linked from this hex (town, dungeon).", + "pick": "keep", + "why": "Core nested-map navigation.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Hex right-click menu" + }, + { + "id": "HexMenu.locationsList", + "surface": "Hex map view: hex right-click menu", + "label": "Locations (n)…", + "kind": "menu", + "level": "conditional: hex has 3+ linked maps", + "loc": "src/hex-map/HexMapView.ts:4801", + "desc": "List every map linked from this hex.", + "pick": "keep", + "why": "Scales when many locations.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Hex right-click menu" + }, + { + "id": "HexMenu.newMap", + "surface": "Hex map view: hex right-click menu", + "label": "New map from this hex…", + "kind": "menu", + "level": "mode: build/god", + "loc": "src/hex-map/HexMapView.ts:4803", + "desc": "Make a new map (town, dungeon, region) linked to this hex.", + "pick": "keep", + "why": "Main way to add detail maps.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Hex right-click menu" + }, + { + "id": "HexMenu.linkExistingMap", + "surface": "Hex map view: hex right-click menu", + "label": "Link existing map…", + "kind": "menu", + "level": "mode: build/god", + "loc": "src/hex-map/HexMapView.ts:4804", + "desc": "Link a map you already have to this hex.", + "pick": "keep", + "why": "Standard way to attach a town or dungeon map you already made.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Hex right-click menu" + }, + { + "id": "HexMenu.manageLocations", + "surface": "Hex map view: hex right-click menu", + "label": "Manage locations…", + "kind": "menu", + "level": "conditional: hex has linked maps; build", + "loc": "src/hex-map/HexMapView.ts:4807", + "desc": "Open the list to unlink or reorder this hex's maps.", + "pick": "keep", + "why": "The way to unlink or reorder a hex's maps when it has only one or two.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Hex right-click menu" + }, + { + "id": "HexMenu.linkTable", + "surface": "Hex map view: hex right-click menu", + "label": "Link table", + "kind": "menu", + "level": "always", + "loc": "src/hex-map/HexMapView.ts:4810", + "desc": "Pick a random table to link as this hex's encounter table.", + "pick": "keep", + "why": "Linking an encounter table to a hex is standard hexcrawl use.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Hex right-click menu" + }, + { + "id": "HexMenu.swapHex", + "surface": "Hex map view: hex right-click menu", + "label": "Swap hex", + "kind": "menu", + "level": "mode: god", + "loc": "src/hex-map/HexMapView.ts:4828", + "desc": "Swap this hex's contents with another hex.", + "pick": "keep", + "why": "Already gated to God mode.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Hex right-click menu" + }, + { + "id": "HexMenu.createToken", + "surface": "Hex map view: hex right-click menu", + "label": "Create token here", + "kind": "menu", + "level": "always", + "loc": "src/hex-map/HexMapView.ts:4833", + "desc": "Make a new token on this hex.", + "pick": "simple", + "why": "Quickest way to put the party on a hex.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Hex right-click menu" + }, + { + "id": "HexMenu.clearTerrain", + "surface": "Hex map view: hex right-click menu", + "label": "Clear terrain", + "kind": "menu", + "level": "conditional: hex has terrain; build", + "loc": "src/hex-map/HexMapView.ts:4839", + "desc": "Remove this hex's terrain.", + "pick": "keep", + "why": "Standard one-hex fix; not everyone reaches for the erase tool.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Hex right-click menu" + }, + { + "id": "HexMenu.removeIconOverride", + "surface": "Hex map view: hex right-click menu", + "label": "Remove icon override", + "kind": "menu", + "level": "conditional: hex has icon override; build", + "loc": "src/hex-map/HexMapView.ts:4844", + "desc": "Remove the custom icon stamped on this hex.", + "pick": "keep", + "why": "Standard one-hex fix (the label could lose the jargon).", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Hex right-click menu" + }, + { + "id": "HexMenu.lockedHint", + "surface": "Hex map view: hex right-click menu", + "label": "Switch to Build to … (disabled)", + "kind": "menu", + "level": "conditional: mode hides items", + "loc": "src/hex-map/modeMenu.ts:52", + "desc": "One greyed line saying which mode unlocks hidden items.", + "pick": "keep", + "why": "Explains missing items without clutter.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Hex right-click menu" + }, + { + "id": "MapView.linkTableMenuPicker", + "surface": "Hex map view: Hex right-click › Link table", + "label": "Link table", + "kind": "picker", + "level": "always", + "loc": "src/hex-map/HexMapView.ts:4811", + "desc": "Link one table to this hex.", + "pick": "keep", + "why": "The picker this control opens; it follows HexMenu.linkTable. Earlier reason: Same list as the tool", + "lists": ".md under tablesFolder, linkable (same as tool)", + "focused": true, + "mix": "", + "group": "Hex map view", + "subgroup": "Hex right-click menu", + "twinOf": "HexMenu.linkTable" + }, + { + "id": "OverworldMenu.enterRegion", + "surface": "Hex map view: overworld hex right-click menu", + "label": "Enter region: ", + "kind": "menu", + "level": "conditional: hex has a region", + "loc": "src/hex-map/HexMapView.ts:4871", + "desc": "Go into this overworld hex's region map.", + "pick": "keep", + "why": "Core overworld navigation.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Overworld menu & minimap" + }, + { + "id": "OverworldMenu.editRegion", + "surface": "Hex map view: overworld hex right-click menu", + "label": "Edit region…", + "kind": "menu", + "level": "conditional: hex has a region", + "loc": "src/hex-map/HexMapView.ts:4871", + "desc": "Edit the region's name, biome and notes.", + "pick": "keep", + "why": "Main region editing entry.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Overworld menu & minimap" + }, + { + "id": "OverworldMenu.setBiome", + "surface": "Hex map view: overworld hex right-click menu", + "label": "Set biome…", + "kind": "menu", + "level": "conditional: empty overworld hex", + "loc": "src/hex-map/HexMapView.ts:4871", + "desc": "Pick a biome for an empty overworld hex (makes a region).", + "pick": "keep", + "why": "How empty land starts.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Overworld menu & minimap" + }, + { + "id": "OverworldMenu.center", + "surface": "Hex map view: overworld hex right-click menu", + "label": "Center on this hex", + "kind": "menu", + "level": "always", + "loc": "src/hex-map/HexMapView.ts:4871", + "desc": "Pan the view so this hex is in the middle.", + "pick": "keep", + "why": "Same harmless centre action as the hex menu; overworld already gated.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Overworld menu & minimap" + }, + { + "id": "OverworldMenu.locations", + "surface": "Hex map view: overworld hex right-click menu", + "label": "Locations (n)…", + "kind": "menu", + "level": "conditional: hex has linked maps", + "loc": "src/hex-map/HexMapView.ts:4871", + "desc": "List maps linked from this overworld hex.", + "pick": "keep", + "why": "Navigation.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Overworld menu & minimap" + }, + { + "id": "OverworldMenu.createToken", + "surface": "Hex map view: overworld hex right-click menu", + "label": "Create token here", + "kind": "menu", + "level": "always", + "loc": "src/hex-map/HexMapView.ts:4882", + "desc": "Put a token (e.g. the party) on this overworld hex.", + "pick": "keep", + "why": "Placing the party on the overworld is normal use; overworld already gated.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Overworld menu & minimap" + }, + { + "id": "Minimap.viewRegions", + "surface": "Hex map view: overworld minimap", + "label": "View: Regions", + "kind": "radio", + "level": "conditional: overworld", + "loc": "src/hex-map/overworldMinimap.ts:61", + "desc": "Show every region's hexes stitched together.", + "pick": "keep", + "why": "Core overworld view switch.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Overworld menu & minimap" + }, + { + "id": "Minimap.viewBiomes", + "surface": "Hex map view: overworld minimap", + "label": "View: Biomes", + "kind": "radio", + "level": "conditional: overworld", + "loc": "src/hex-map/overworldMinimap.ts:61", + "desc": "Show one biome per hex.", + "pick": "keep", + "why": "Core overworld view switch.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Overworld menu & minimap" + }, + { + "id": "Minimap.biomeLibrary", + "surface": "Hex map view: overworld minimap", + "label": "Biomes…", + "kind": "button", + "level": "conditional: overworld, Biomes view", + "loc": "src/hex-map/overworldMinimap.ts:71", + "desc": "Add your own biomes or edit the built-in ones.", + "pick": "keep", + "why": "Biome library, already only on overworlds (regions feature).", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Overworld menu & minimap" + }, + { + "id": "Minimap.toggle", + "surface": "Hex map view: overworld minimap", + "label": "Show / Hide the overworld map", + "kind": "button", + "level": "conditional: in a region of an overworld", + "loc": "src/hex-map/overworldMinimap.ts:79", + "desc": "Expand or collapse the overworld minimap.", + "pick": "keep", + "why": "Simple show/hide.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Overworld menu & minimap" + }, + { + "id": "Minimap.canvasClick", + "surface": "Hex map view: overworld minimap", + "label": "Overworld minimap (click to go)", + "kind": "button", + "level": "conditional: minimap expanded", + "loc": "src/hex-map/overworldMinimap.ts:122", + "desc": "Click a region on the minimap to go there.", + "pick": "keep", + "why": "Fast overworld navigation.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Overworld menu & minimap" + }, + { + "id": "OverworldMinimap.viewRegions", + "surface": "Overworld minimap", + "label": "View: Regions", + "kind": "button", + "level": "conditional: on an overworld (feature:regions)", + "loc": "src/hex-map/overworldMinimap.ts:393", + "desc": "Shows the overworld as stitched region hexes.", + "pick": "keep", + "why": "Same control inventoried twice (another render path or pass); follows Minimap.viewRegions. Earlier reason: Region basics on an overworld: shows today on any overworld at any level; pin so walking an existing overworld never hides.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Overworld menu & minimap", + "twinOf": "Minimap.viewRegions", + "prevPick": "simple" + }, + { + "id": "OverworldMinimap.viewBiomes", + "surface": "Overworld minimap", + "label": "View: Biomes", + "kind": "button", + "level": "conditional: on an overworld (feature:regions)", + "loc": "src/hex-map/overworldMinimap.ts:393", + "desc": "Shows the overworld as one biome per hex.", + "pick": "keep", + "why": "Same control inventoried twice (another render path or pass); follows Minimap.viewBiomes. Earlier reason: Region basics on an overworld: the other half of the view switch; pin it.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Overworld menu & minimap", + "twinOf": "Minimap.viewBiomes", + "prevPick": "simple" + }, + { + "id": "OverworldMinimap.biomes", + "surface": "Overworld minimap", + "label": "Biomes…", + "kind": "button", + "level": "conditional: overworld in Biomes view", + "loc": "src/hex-map/overworldMinimap.ts:403", + "desc": "Opens the biome library.", + "pick": "keep", + "why": "Same control inventoried twice (another render path or pass); follows Minimap.biomeLibrary. Earlier reason: Already regions-gated; the biome library.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Overworld menu & minimap", + "twinOf": "Minimap.biomeLibrary" + }, + { + "id": "OverworldMinimap.toggle", + "surface": "Overworld minimap", + "label": "Show/Hide the overworld map", + "kind": "button", + "level": "conditional: on an overworld or one of its regions", + "loc": "src/hex-map/overworldMinimap.ts:411", + "desc": "Collapses or expands the minimap.", + "pick": "keep", + "why": "Same control inventoried twice (another render path or pass); follows Minimap.toggle. Earlier reason: Region basics on an overworld: show or hide the minimap; pin it.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Overworld menu & minimap", + "twinOf": "Minimap.toggle", + "prevPick": "simple" + }, + { + "id": "OverworldMinimap.canvasClick", + "surface": "Overworld minimap", + "label": "(minimap hex click)", + "kind": "button", + "level": "conditional: minimap expanded", + "loc": "src/hex-map/overworldMinimap.ts:454", + "desc": "Click a hex to go to its region, or show it on the overworld.", + "pick": "keep", + "why": "Same control inventoried twice (another render path or pass); follows Minimap.canvasClick. Earlier reason: Region basics on an overworld: click to go there; pin it.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Overworld menu & minimap", + "twinOf": "Minimap.canvasClick", + "prevPick": "simple" + }, + { + "id": "OverworldMenu.enterRegion_2", + "surface": "Overworld hex right-click menu", + "label": "Enter region", + "kind": "menu", + "level": "conditional: hex has a region", + "loc": "src/overworld/overworldInput.ts:71", + "desc": "Goes into the hex's region map.", + "pick": "keep", + "why": "Same control inventoried twice (another render path or pass); follows OverworldMenu.enterRegion. Earlier reason: Core navigation (also left click).", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Overworld menu & minimap", + "twinOf": "OverworldMenu.enterRegion" + }, + { + "id": "OverworldMenu.editRegion_2", + "surface": "Overworld hex right-click menu", + "label": "Edit region…", + "kind": "menu", + "level": "conditional: hex has a region", + "loc": "src/overworld/overworldInput.ts:72", + "desc": "Opens name, biome, facts and notes for the region.", + "pick": "keep", + "why": "Same control inventoried twice (another render path or pass); follows OverworldMenu.editRegion. Earlier reason: Core.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Overworld menu & minimap", + "twinOf": "OverworldMenu.editRegion" + }, + { + "id": "OverworldMenu.setBiome_2", + "surface": "Overworld hex right-click menu", + "label": "Set biome…", + "kind": "menu", + "level": "mode: build/god (disabled in Play)", + "loc": "src/overworld/overworldInput.ts:75", + "desc": "Places a biome on an empty hex.", + "pick": "keep", + "why": "Same control inventoried twice (another render path or pass); follows OverworldMenu.setBiome. Earlier reason: Core build action.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Overworld menu & minimap", + "twinOf": "OverworldMenu.setBiome" + }, + { + "id": "OverworldMenu.center_2", + "surface": "Overworld hex right-click menu", + "label": "Center on this hex", + "kind": "menu", + "level": "always", + "loc": "src/overworld/overworldInput.ts:77", + "desc": "Pans the view to this hex.", + "pick": "keep", + "why": "Same control inventoried twice (another render path or pass); follows OverworldMenu.center. Earlier reason: Harmless, standard map-menu action; same as the hex menu.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Overworld menu & minimap", + "twinOf": "OverworldMenu.center" + }, + { + "id": "OverworldMenu.locations_2", + "surface": "Overworld hex right-click menu", + "label": "Locations (n)…", + "kind": "menu", + "level": "conditional: hex has locations", + "loc": "src/overworld/overworldInput.ts:78", + "desc": "Lists the hex's locations.", + "pick": "keep", + "why": "Same control inventoried twice (another render path or pass); follows OverworldMenu.locations. Earlier reason: Core navigation.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Overworld menu & minimap", + "twinOf": "OverworldMenu.locations" + }, + { + "id": "TokenMenu.info", + "surface": "Hex map view: token right-click menu", + "label": "Token info", + "kind": "menu", + "level": "always", + "loc": "src/hex-map/HexMapView.ts:8010", + "desc": "Show the token's info card.", + "pick": "keep", + "why": "Reading a token's card is normal play, especially when editing is locked.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Token right-click menu" + }, + { + "id": "TokenMenu.edit", + "surface": "Hex map view: token right-click menu", + "label": "Edit token", + "kind": "menu", + "level": "always", + "loc": "src/hex-map/HexMapView.ts:8011", + "desc": "Change the token's name, image, colour.", + "pick": "simple", + "why": "Token basics: change a token you placed.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Token right-click menu" + }, + { + "id": "TokenMenu.openNote", + "surface": "Hex map view: token right-click menu", + "label": "Open note", + "kind": "menu", + "level": "always", + "loc": "src/hex-map/HexMapView.ts:8012", + "desc": "Open the token's note.", + "pick": "keep", + "why": "Tokens are notes.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Token right-click menu" + }, + { + "id": "TokenMenu.remove", + "surface": "Hex map view: token right-click menu", + "label": "Remove token", + "kind": "menu", + "level": "always", + "loc": "src/hex-map/HexMapView.ts:8017", + "desc": "Take the token off the map.", + "pick": "simple", + "why": "Token basics: take a token off the map.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Token right-click menu" + }, + { + "id": "LayersMenu.coordinates", + "surface": "Hex map view: layers panel", + "label": "Coordinates", + "kind": "checkbox", + "level": "always", + "loc": "src/hex-map/HexSidePanel.ts:105", + "desc": "Show each hex's x,y numbers.", + "pick": "keep", + "why": "Coordinates are how GMs refer to hexes.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Layers panel" + }, + { + "id": "LayersMenu.hexNames", + "surface": "Hex map view: layers panel", + "label": "Hex names", + "kind": "checkbox", + "level": "always", + "loc": "src/hex-map/HexSidePanel.ts:106", + "desc": "Show hex names on the map.", + "pick": "keep", + "why": "Core label.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Layers panel" + }, + { + "id": "LayersMenu.tokenNames", + "surface": "Hex map view: layers panel", + "label": "Token names", + "kind": "checkbox", + "level": "always", + "loc": "src/hex-map/HexSidePanel.ts:107", + "desc": "Show names under tokens.", + "pick": "keep", + "why": "Plain layer toggle, same as the other label toggles.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Layers panel" + }, + { + "id": "LayersMenu.nameFontBtn", + "surface": "Hex map view: layers panel", + "label": "Aa (Hex name font)", + "kind": "button", + "level": "always", + "loc": "src/hex-map/HexSidePanel.ts:319", + "desc": "Unfolds font controls for hex names.", + "pick": "simple", + "why": "Hex name font is look and feel; the owner tagged the matching settings Simple. Owner (pass 3): \"a streamlined but still customizable experience for simple, not to hide every little possible scary thing.\"", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Layers panel", + "prevPick": "advanced" + }, + { + "id": "LayersMenu.nameFontFamily", + "surface": "Hex map view: layers panel", + "label": "Font", + "kind": "dropdown", + "level": "conditional: Aa unfolded", + "loc": "src/hex-map/HexSidePanel.ts:337", + "desc": "Font family for hex names.", + "pick": "keep", + "why": "No change of its own: it only shows inside the Aa fold (tagged advanced), so tagging that hides it too.", + "lists": "Name font families: Theme, Serif, Sans, Handwritten", + "focused": true, + "mix": "", + "group": "Hex map view", + "subgroup": "Layers panel" + }, + { + "id": "LayersMenu.nameSize", + "surface": "Hex map view: layers panel", + "label": "Name size S / M / L / XL", + "kind": "radio", + "level": "conditional: Aa unfolded", + "loc": "src/hex-map/HexSidePanel.ts:347", + "desc": "Size of hex names.", + "pick": "keep", + "why": "No change of its own: it only shows inside the Aa fold (tagged advanced), so tagging that hides it too.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Layers panel" + }, + { + "id": "LayersMenu.nameBold", + "surface": "Hex map view: layers panel", + "label": "Bold (B)", + "kind": "toggle", + "level": "conditional: Aa unfolded", + "loc": "src/hex-map/HexSidePanel.ts:371", + "desc": "Make hex names bold.", + "pick": "keep", + "why": "No change of its own: it only shows inside the Aa fold (tagged advanced), so tagging that hides it too.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Layers panel" + }, + { + "id": "LayersMenu.nameItalic", + "surface": "Hex map view: layers panel", + "label": "Italic (I)", + "kind": "toggle", + "level": "conditional: Aa unfolded", + "loc": "src/hex-map/HexSidePanel.ts:372", + "desc": "Make hex names italic.", + "pick": "keep", + "why": "No change of its own: it only shows inside the Aa fold (tagged advanced), so tagging that hides it too.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Layers panel" + }, + { + "id": "LayersMenu.nameFontReset", + "surface": "Hex map view: layers panel", + "label": "Use the default name font (settings)", + "kind": "button", + "level": "conditional: Aa unfolded", + "loc": "src/hex-map/HexSidePanel.ts:374", + "desc": "Reset this map's name font to the plugin default.", + "pick": "keep", + "why": "No change of its own: it only shows inside the Aa fold (tagged advanced), so tagging that hides it too.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Layers panel" + }, + { + "id": "LayersMenu.terrainIcons", + "surface": "Hex map view: layers panel", + "label": "Show terrain icons", + "kind": "checkbox", + "level": "always", + "loc": "src/hex-map/HexSidePanel.ts:102", + "desc": "Show the icon each terrain draws in its hexes.", + "pick": "keep", + "why": "Useful clean-up of a busy map.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Layers panel" + }, + { + "id": "LayersMenu.iconOverrides", + "surface": "Hex map view: layers panel", + "label": "Show icon overrides", + "kind": "checkbox", + "level": "always", + "loc": "src/hex-map/HexSidePanel.ts:103", + "desc": "Show the custom icons stamped on hexes.", + "pick": "keep", + "why": "Plain layer toggle.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Layers panel" + }, + { + "id": "LayersMenu.paths", + "surface": "Hex map view: layers panel", + "label": "Show paths", + "kind": "checkbox", + "level": "always", + "loc": "src/hex-map/HexSidePanel.ts:104", + "desc": "Show roads, rivers and other paths.", + "pick": "keep", + "why": "Common layer toggle.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Layers panel" + }, + { + "id": "LayersMenu.tokens", + "surface": "Hex map view: layers panel", + "label": "Show tokens", + "kind": "checkbox", + "level": "always", + "loc": "src/hex-map/HexSidePanel.ts:153", + "desc": "Show tokens on the map.", + "pick": "keep", + "why": "Common layer toggle.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Layers panel" + }, + { + "id": "LayersMenu.factionOverlay", + "surface": "Hex map view: layers panel", + "label": "Show faction overlay", + "kind": "checkbox", + "level": "always", + "loc": "src/hex-map/HexSidePanel.ts:178", + "desc": "Tint hexes by faction territory.", + "pick": "keep", + "why": "Main faction view.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Layers panel" + }, + { + "id": "LayersMenu.regionOverlay", + "surface": "Hex map view: layers panel", + "label": "Show region overlay", + "kind": "checkbox", + "level": "always", + "loc": "src/hex-map/HexSidePanel.ts:202", + "desc": "Tint hexes by painted region areas.", + "pick": "advanced", + "why": "Overlay for the Region areas tool, which is Advanced.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Layers panel" + }, + { + "id": "LayersMenu.gmLayer", + "surface": "Hex map view: layers panel", + "label": "Show GM layer", + "kind": "checkbox", + "level": "always", + "loc": "src/hex-map/HexSidePanel.ts:226", + "desc": "Show GM-only icons (hide when sharing with players).", + "pick": "keep", + "why": "Key for play.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Layers panel" + }, + { + "id": "LayersMenu.linkBadges", + "surface": "Hex map view: layers panel", + "label": "Show link badges", + "kind": "checkbox", + "level": "always", + "loc": "src/hex-map/HexSidePanel.ts:430", + "desc": "Show small icons for towns, dungeons etc. on hexes.", + "pick": "keep", + "why": "Shows where content is.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Layers panel" + }, + { + "id": "LayersMenu.badgeSize", + "surface": "Hex map view: layers panel", + "label": "Badge size S / M / L", + "kind": "radio", + "level": "always", + "loc": "src/hex-map/HexSidePanel.ts:436", + "desc": "Size of the link badges.", + "pick": "simple", + "why": "Badge size is look and feel, like the coordinate/name font settings the owner tagged Simple. Owner (pass 3): \"a streamlined but still customizable experience for simple, not to hide every little possible scary thing.\"", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Layers panel", + "prevPick": "overkill" + }, + { + "id": "LayersMenu.badgeTypesMore", + "surface": "Hex map view: layers panel", + "label": "Pick badge types (▸)", + "kind": "button", + "level": "always", + "loc": "src/hex-map/HexSidePanel.ts:451", + "desc": "Unfold per-type badge chips.", + "pick": "simple", + "why": "Choosing which badges show is look and feel. Owner (pass 3): \"a streamlined but still customizable experience for simple, not to hide every little possible scary thing.\"", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Layers panel", + "prevPick": "advanced" + }, + { + "id": "LayersMenu.badgeTowns", + "surface": "Hex map view: layers panel", + "label": "Towns badges", + "kind": "toggle", + "level": "conditional: badge types unfolded", + "loc": "src/hex-map/HexSidePanel.ts:484", + "desc": "Show or hide towns badges only.", + "pick": "keep", + "why": "No change of its own: it only shows inside the badge-types fold (tagged advanced), so tagging that hides it too.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Layers panel" + }, + { + "id": "LayersMenu.badgeDungeons", + "surface": "Hex map view: layers panel", + "label": "Dungeons badges", + "kind": "toggle", + "level": "conditional: badge types unfolded", + "loc": "src/hex-map/HexSidePanel.ts:484", + "desc": "Show or hide dungeons badges only.", + "pick": "keep", + "why": "No change of its own: it only shows inside the badge-types fold (tagged advanced), so tagging that hides it too.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Layers panel" + }, + { + "id": "LayersMenu.badgeFeatures", + "surface": "Hex map view: layers panel", + "label": "Features badges", + "kind": "toggle", + "level": "conditional: badge types unfolded", + "loc": "src/hex-map/HexSidePanel.ts:484", + "desc": "Show or hide features badges only.", + "pick": "keep", + "why": "No change of its own: it only shows inside the badge-types fold (tagged advanced), so tagging that hides it too.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Layers panel" + }, + { + "id": "LayersMenu.badgeQuests", + "surface": "Hex map view: layers panel", + "label": "Quests badges", + "kind": "toggle", + "level": "conditional: badge types unfolded", + "loc": "src/hex-map/HexSidePanel.ts:484", + "desc": "Show or hide quests badges only.", + "pick": "keep", + "why": "No change of its own: it only shows inside the badge-types fold (tagged advanced), so tagging that hides it too.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Layers panel" + }, + { + "id": "LayersMenu.badgeFactions", + "surface": "Hex map view: layers panel", + "label": "Factions badges", + "kind": "toggle", + "level": "conditional: badge types unfolded", + "loc": "src/hex-map/HexSidePanel.ts:484", + "desc": "Show or hide factions badges only.", + "pick": "keep", + "why": "No change of its own: it only shows inside the badge-types fold (tagged advanced), so tagging that hides it too.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Layers panel" + }, + { + "id": "LayersMenu.legend", + "surface": "Hex map view: layers panel", + "label": "Show legend", + "kind": "checkbox", + "level": "always", + "loc": "src/hex-map/HexSidePanel.ts:251", + "desc": "Show the terrain legend in the corner.", + "pick": "keep", + "why": "Helps read the map.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Layers panel" + }, + { + "id": "Legend.size", + "surface": "Hex map view: terrain legend", + "label": "Legend size S / M / L", + "kind": "radio", + "level": "conditional: legend shown", + "loc": "src/hex-map/terrainLegend.ts:160", + "desc": "Change the legend's size.", + "pick": "simple", + "why": "Legend size is look and feel. Owner (pass 3): \"a streamlined but still customizable experience for simple, not to hide every little possible scary thing.\"", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Legend, grid edges & notices", + "prevPick": "advanced" + }, + { + "id": "Legend.minimize", + "surface": "Hex map view: terrain legend", + "label": "Minimize (–)", + "kind": "button", + "level": "conditional: legend shown", + "loc": "src/hex-map/terrainLegend.ts:171", + "desc": "Fold the legend into a small chip.", + "pick": "keep", + "why": "Get it out of the way.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Legend, grid edges & notices" + }, + { + "id": "Legend.hide", + "surface": "Hex map view: terrain legend", + "label": "Hide legend (×)", + "kind": "button", + "level": "conditional: legend shown", + "loc": "src/hex-map/terrainLegend.ts:183", + "desc": "Turn the legend off (back on in layers).", + "pick": "keep", + "why": "Standard close button on a panel; the layers toggle brings it back.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Legend, grid edges & notices" + }, + { + "id": "Legend.expandChip", + "surface": "Hex map view: terrain legend", + "label": "Legend (Show the legend)", + "kind": "button", + "level": "conditional: legend minimized", + "loc": "src/hex-map/terrainLegend.ts:145", + "desc": "Unfold the minimized legend.", + "pick": "keep", + "why": "Pairs with minimize.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Legend, grid edges & notices" + }, + { + "id": "MapGrid.expand", + "surface": "Hex map view: grid edges", + "label": "+ (grow edge, 4 sides)", + "kind": "button", + "level": "mode: build/god", + "loc": "src/hex-map/HexMapView.ts:1961", + "desc": "Add a row or column of hexes on that side.", + "pick": "keep", + "why": "Basic map growing.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Legend, grid edges & notices" + }, + { + "id": "MapGrid.shrink", + "surface": "Hex map view: grid edges", + "label": "− / OK? (shrink edge, 4 sides)", + "kind": "button", + "level": "mode: god", + "loc": "src/hex-map/HexMapView.ts:1966", + "desc": "Remove the edge row/column (asks OK? if it has content).", + "pick": "simple", + "why": "Fixing an oversized map is basic; it's God-only today, so if God mode goes Advanced it must stay reachable (e.g. in Build, with its OK? confirm).", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Legend, grid edges & notices" + }, + { + "id": "PathTool.rerouteInstead", + "surface": "Hex map view: notice", + "label": "Reroute instead", + "kind": "button", + "level": "conditional: terrain stroke pinned a path", + "loc": "src/paths/routePins.ts:196", + "desc": "Let paths reroute around newly painted terrain instead of staying put.", + "pick": "keep", + "why": "Only appears right after painting pinned a path; it answers that moment.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Legend, grid edges & notices" + }, + { + "id": "MapView.calibrationDone", + "surface": "Hex map view: hex/grid interactions", + "label": "Done calibrating (✓)", + "kind": "button", + "level": "conditional: calibrating background image", + "loc": "src/hex-map/HexMapView.ts:3680", + "desc": "Finish lining up the background image with the grid.", + "pick": "keep", + "why": "Only exit for calibration.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Mouse & keyboard" + }, + { + "id": "MapView.missingRestore", + "surface": "Hex map view: hex/grid interactions", + "label": "Restore", + "kind": "button", + "level": "conditional: map note was deleted", + "loc": "src/hex-map/MapModal.ts:46", + "desc": "Write the missing map's note back from the last saved copy.", + "pick": "keep", + "why": "Recovery from accidental deletion.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Mouse & keyboard" + }, + { + "id": "MapView.missingRemove", + "surface": "Hex map view: hex/grid interactions", + "label": "Remove", + "kind": "button", + "level": "conditional: map note was deleted", + "loc": "src/hex-map/MapModal.ts:52", + "desc": "Drop the missing map from the list (no files deleted).", + "pick": "keep", + "why": "Recovery choice.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Mouse & keyboard" + }, + { + "id": "MapView.hexClick", + "surface": "Hex map view: hex/grid interactions", + "label": "Click hex", + "kind": "button", + "level": "always", + "loc": "src/hex-map/HexMapView.ts:4897", + "desc": "Open the hex editor for that hex.", + "pick": "keep", + "why": "Primary interaction.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Mouse & keyboard" + }, + { + "id": "MapView.hexCtrlClick", + "surface": "Hex map view: hex/grid interactions", + "label": "Ctrl/Cmd+click hex", + "kind": "button", + "level": "conditional: hex has a linked map", + "loc": "src/hex-map/HexMapView.ts:4953", + "desc": "Jump into the map linked from this hex.", + "pick": "keep", + "why": "Fast dive; hinted in tooltips.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Mouse & keyboard" + }, + { + "id": "MapView.hexCtrlShiftClick", + "surface": "Hex map view: hex/grid interactions", + "label": "Ctrl/Cmd+Shift+click hex", + "kind": "button", + "level": "conditional: hex has a linked map", + "loc": "src/hex-map/HexMapView.ts:4957", + "desc": "Open the linked map in a new tab.", + "pick": "keep", + "why": "Invisible shortcut; costs nothing.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Mouse & keyboard" + }, + { + "id": "MapView.hexRightClick", + "surface": "Hex map view: hex/grid interactions", + "label": "Right-click hex", + "kind": "menu", + "level": "always", + "loc": "src/hex-map/HexMapView.ts:1451", + "desc": "Open the hex's action menu.", + "pick": "keep", + "why": "Primary secondary action.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Mouse & keyboard" + }, + { + "id": "MapView.locationBadge", + "surface": "Hex map view: hex/grid interactions", + "label": "Location badge (Enter location / Locations)", + "kind": "button", + "level": "conditional: hex has linked maps", + "loc": "src/hex-map/HexMapView.ts:4423", + "desc": "Click the badge to enter the location, or list several.", + "pick": "keep", + "why": "Visible way into submaps.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Mouse & keyboard" + }, + { + "id": "MapView.regionShadowHex", + "surface": "Hex map view: hex/grid interactions", + "label": "Neighbouring region hex (shadow)", + "kind": "button", + "level": "conditional: region with neighbours", + "loc": "src/hex-map/HexMapView.ts:4638", + "desc": "Click a ghosted hex of a neighbouring region to go there.", + "pick": "keep", + "why": "Seamless region walking.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Mouse & keyboard" + }, + { + "id": "MapView.overworldClick", + "surface": "Hex map view: hex/grid interactions", + "label": "Click overworld hex", + "kind": "button", + "level": "conditional: overworld", + "loc": "src/hex-map/HexMapView.ts:4936", + "desc": "Enter that region, or set a biome on empty land.", + "pick": "keep", + "why": "Primary overworld action.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Mouse & keyboard" + }, + { + "id": "MapView.tokenDrag", + "surface": "Hex map view: hex/grid interactions", + "label": "Drag token", + "kind": "button", + "level": "always", + "loc": "src/hex-map/HexMapView.ts:7853", + "desc": "Drag a token to move it to another hex.", + "pick": "simple", + "why": "Moving the party is the core play action.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Mouse & keyboard" + }, + { + "id": "MapView.tokenRightClick", + "surface": "Hex map view: hex/grid interactions", + "label": "Right-click token", + "kind": "menu", + "level": "always", + "loc": "src/hex-map/HexMapView.ts:7840", + "desc": "Open the token's menu.", + "pick": "keep", + "why": "Primary token actions.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Mouse & keyboard" + }, + { + "id": "MapView.wheelZoom", + "surface": "Hex map view: hex/grid interactions", + "label": "Mouse wheel", + "kind": "slider", + "level": "always", + "loc": "src/hex-map/HexMapView.ts:1100", + "desc": "Zoom in and out.", + "pick": "keep", + "why": "Basic navigation.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Mouse & keyboard" + }, + { + "id": "MapView.dragPan", + "surface": "Hex map view: hex/grid interactions", + "label": "Drag (left/middle/right)", + "kind": "button", + "level": "always", + "loc": "src/hex-map/HexMapView.ts:1147", + "desc": "Pan the map.", + "pick": "keep", + "why": "Basic navigation.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Mouse & keyboard" + }, + { + "id": "MapView.dblRightClickExit", + "surface": "Hex map view: hex/grid interactions", + "label": "Double right-click", + "kind": "button", + "level": "conditional: a tool is on", + "loc": "src/hex-map/HexMapView.ts:1395", + "desc": "Turn off the active tool.", + "pick": "drop", + "why": "Fourth way to leave a tool; Esc, the ✕ and right-click Exit tool replace it.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Mouse & keyboard" + }, + { + "id": "MapView.dblClickOffGridExit", + "surface": "Hex map view: hex/grid interactions", + "label": "Double-click off the grid", + "kind": "button", + "level": "conditional: terrain/icon tool on", + "loc": "src/hex-map/HexMapView.ts:1458", + "desc": "Turn off terrain or icon painting.", + "pick": "drop", + "why": "Fifth way to leave a tool and easy to trigger by accident; Esc and ✕ replace it.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Mouse & keyboard" + }, + { + "id": "MapView.gmIconRightClick", + "surface": "Hex map view: hex/grid interactions", + "label": "Right-click hex (GM icon paint)", + "kind": "button", + "level": "conditional: icon tool in GM-only mode", + "loc": "src/hex-map/HexMapView.ts:1408", + "desc": "Remove one of the selected GM icon from that hex.", + "pick": "keep", + "why": "How you remove a GM icon while painting GM icons; only in that mode.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Mouse & keyboard" + }, + { + "id": "PathTool.anchorRightClick", + "surface": "Hex map view: hex/grid interactions", + "label": "Right-click path anchor", + "kind": "button", + "level": "conditional: path tool on", + "loc": "src/hex-map/pathTool.ts:1063", + "desc": "Delete that anchor point of the path.", + "pick": "keep", + "why": "Natural way to delete a path point while the path tool is on.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Mouse & keyboard" + }, + { + "id": "PathTool.anchorDrag", + "surface": "Hex map view: hex/grid interactions", + "label": "Drag path point/line", + "kind": "button", + "level": "conditional: path tool on", + "loc": "src/hex-map/HexMapView.ts:1270", + "desc": "Drag a point or line of the path to reshape it.", + "pick": "keep", + "why": "Natural path editing.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Mouse & keyboard" + }, + { + "id": "Keys.escape", + "surface": "Hex map view: keyboard shortcuts", + "label": "Esc", + "kind": "command", + "level": "conditional: a tool is on", + "loc": "src/hex-map/HexMapView.ts:1043", + "desc": "Step out of the active tool.", + "pick": "keep", + "why": "Expected.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Mouse & keyboard" + }, + { + "id": "Keys.undoRedo", + "surface": "Hex map view: keyboard shortcuts", + "label": "Ctrl/Cmd+Z, Ctrl/Cmd+Shift+Z", + "kind": "command", + "level": "always", + "loc": "src/hex-map/HexMapView.ts:990", + "desc": "Undo and redo on the map.", + "pick": "keep", + "why": "Expected.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Mouse & keyboard" + }, + { + "id": "Keys.altArrows", + "surface": "Hex map view: keyboard shortcuts", + "label": "Alt+← / Alt+↑ / Alt+→", + "kind": "command", + "level": "always", + "loc": "src/hex-map/HexMapView.ts:1001", + "desc": "Back, up to parent, forward between maps.", + "pick": "keep", + "why": "Invisible, cheap.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Mouse & keyboard" + }, + { + "id": "Keys.deleteAnchor", + "surface": "Hex map view: keyboard shortcuts", + "label": "Backspace / Delete", + "kind": "command", + "level": "conditional: path tool on", + "loc": "src/hex-map/HexMapView.ts:1055", + "desc": "Remove the hovered (or last) path anchor.", + "pick": "keep", + "why": "Invisible, cheap.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Mouse & keyboard" + }, + { + "id": "Keys.altClickNewPath", + "surface": "Hex map view: keyboard shortcuts", + "label": "Alt+click", + "kind": "command", + "level": "conditional: path tool on", + "loc": "src/hex-map/pathTool.ts:1472", + "desc": "Start a new path on top of another.", + "pick": "keep", + "why": "Invisible shortcut; costs nothing.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Mouse & keyboard" + }, + { + "id": "Keys.calibrationArrows", + "surface": "Hex map view: keyboard shortcuts", + "label": "Arrow keys (Shift = 10px)", + "kind": "command", + "level": "conditional: calibrating background", + "loc": "src/hex-map/HexMapView.ts:3605", + "desc": "Nudge the background image or grid during calibration.", + "pick": "keep", + "why": "Only during background calibration, where fine nudging is the point.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Mouse & keyboard" + }, + { + "id": "HexEditor.centerOnHex", + "surface": "Hex editor: header", + "label": "⌖", + "kind": "button", + "level": "always", + "loc": "src/hex-map/HexEditorModal.ts:196", + "desc": "Pan the map so this hex is in the middle.", + "pick": "keep", + "why": "Cheap, obvious orientation aid.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Header" + }, + { + "id": "HexEditor.openNote", + "surface": "Hex editor: header", + "label": "Open note", + "kind": "button", + "level": "conditional: hex note exists", + "loc": "src/hex-map/HexEditorModal.ts:216", + "desc": "Open this hex's Markdown note in a tab.", + "pick": "keep", + "why": "Core: the note is the real data.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Header" + }, + { + "id": "HexEditor.exportHex", + "surface": "Hex editor: header", + "label": "Export", + "kind": "button", + "level": "conditional: hex note exists", + "loc": "src/hex-map/HexEditorModal.ts:224", + "desc": "Export this one hex as a PDF or Markdown file.", + "pick": "simple", + "why": "Basic export of one hex from its editor.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Header" + }, + { + "id": "HexEditor.runWorkflow", + "surface": "Hex editor: header", + "label": "Run workflow", + "kind": "button", + "level": "feature:workflows", + "loc": "src/hex-map/HexEditorModal.ts:236", + "desc": "Pick a workflow and roll it, adding the result to this hex.", + "pick": "keep", + "why": "Workflows are Advanced and this is already gated to that feature.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Header" + }, + { + "id": "HexEditor.workflowPicker", + "surface": "Hex editor: header", + "label": "Pick a workflow to run…", + "kind": "picker", + "level": "feature:workflows", + "loc": "src/hex-map/HexEditorModal.ts:1660", + "desc": "Choose which workflow note to run for this hex.", + "pick": "keep", + "why": "Workflows are Advanced and this is already gated to that feature.", + "lists": "md notes under workflowsFolder; if that is blank (default) falls back to worldFolder. Excludes _ notes and template folders", + "focused": false, + "mix": "with workflowsFolder blank: every note under the world folder (hexes, towns, tables, biomes, palettes, generators, region notes)", + "group": "Hex editor", + "subgroup": "Header" + }, + { + "id": "HexEditor.neighborTile", + "surface": "Hex editor: header", + "label": "Neighbour hex tiles", + "kind": "button", + "level": "always", + "loc": "src/hex-map/HexEditorModal.ts:578", + "desc": "Jump the editor to one of the six neighbouring hexes.", + "pick": "keep", + "why": "Fast hex-by-hex stocking.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Header" + }, + { + "id": "HexEditor.neighborCrossRegion", + "surface": "Hex editor: header", + "label": "Neighbour tile (other region)", + "kind": "button", + "level": "conditional: a map joins past this edge", + "loc": "src/hex-map/HexEditorModal.ts:600", + "desc": "Cross into the neighbouring region's hex across the map edge.", + "pick": "keep", + "why": "Natural continuation of neighbour navigation.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Header" + }, + { + "id": "HexEditor.neighborWalkOverworld", + "surface": "Hex editor: header", + "label": "Neighbour tile (new region)", + "kind": "button", + "level": "conditional: region of an overworld, edge hex", + "loc": "src/hex-map/HexEditorModal.ts:621", + "desc": "Walk off the edge to make the next overworld region (pick/roll a biome).", + "pick": "keep", + "why": "Only in an overworld region, already gated by the regions feature.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Header" + }, + { + "id": "HexEditor.neighborNewLand", + "surface": "Hex editor: header", + "label": "Neighbour tile (new land)", + "kind": "button", + "level": "conditional: edge hex; asks to enable regions+generators", + "loc": "src/hex-map/HexEditorModal.ts:636", + "desc": "Walk off the map edge to create new land next door.", + "pick": "keep", + "why": "In Simple it asks to turn the feature on, which is the ramp.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Header" + }, + { + "id": "HexEditor.neighborCentreDot", + "surface": "Hex editor: header", + "label": "Centre dot", + "kind": "button", + "level": "conditional: hex has a region or one location map", + "loc": "src/hex-map/HexEditorModal.ts:660", + "desc": "Enter the map linked to this hex (its region or location).", + "pick": "drop", + "why": "Duplicates the Maps chips right below it in the same editor; the chips replace it.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Header" + }, + { + "id": "HexEditor.nameInput", + "surface": "Hex editor: header", + "label": "Name", + "kind": "text", + "level": "always", + "loc": "src/hex-map/HexEditorModal.ts:449", + "desc": "Give this hex a name (optional); autosaves.", + "pick": "keep", + "why": "Core and lightweight.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Header" + }, + { + "id": "HexEditor.mapsChip", + "surface": "Hex editor: header", + "label": "Maps: region/location chips", + "kind": "button", + "level": "conditional: hex has linked maps", + "loc": "src/hex-map/HexEditorModal.ts:694", + "desc": "Open a map linked to this hex (its region or a location).", + "pick": "keep", + "why": "Main way into child maps from a hex.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Header" + }, + { + "id": "HexEditor.mapsAdd", + "surface": "Hex editor: header", + "label": "+ (Maps)", + "kind": "menu", + "level": "conditional: host can make child maps", + "loc": "src/hex-map/HexEditorModal.ts:709", + "desc": "Menu to make, link or manage maps for this hex.", + "pick": "keep", + "why": "Single entry point for child maps.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Header" + }, + { + "id": "HexEditor.mapsNewMap", + "surface": "Hex editor: header", + "label": "New map from this hex…", + "kind": "command", + "level": "mode: build", + "loc": "src/hex-map/HexEditorModal.ts:713", + "desc": "Create a new map (e.g. a town or dungeon map) inside this hex.", + "pick": "keep", + "why": "Core for nested maps.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Header" + }, + { + "id": "HexEditor.mapsLinkExisting", + "surface": "Hex editor: header", + "label": "Link existing map…", + "kind": "command", + "level": "mode: build", + "loc": "src/hex-map/HexEditorModal.ts:715", + "desc": "Attach a map you already have to this hex.", + "pick": "keep", + "why": "Standard way to attach a map you already made (same as the hex menu).", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Header" + }, + { + "id": "HexEditor.mapsManageLocations", + "surface": "Hex editor: header", + "label": "Manage locations (N)…", + "kind": "command", + "level": "conditional: hex has locations; mode: build", + "loc": "src/hex-map/HexEditorModal.ts:718", + "desc": "Reorder or unlink location maps on this hex.", + "pick": "keep", + "why": "Only when the hex has locations; normal housekeeping.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Header" + }, + { + "id": "HexEditor.closeButtons", + "surface": "Hex editor: header", + "label": "Close (×)", + "kind": "button", + "level": "always", + "loc": "src/hex-map/HexEditorModal.ts:428", + "desc": "Close the editor (unsaved text is saved first).", + "pick": "keep", + "why": "Standard.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Header" + }, + { + "id": "HexEditor.collapseTerrain", + "surface": "Hex editor: section headers", + "label": "Terrain ▶/▼", + "kind": "toggle", + "level": "always", + "loc": "src/hex-map/HexEditorModal.ts:276", + "desc": "Fold or unfold the terrain picker; starts folded if the hex has terrain.", + "pick": "keep", + "why": "Keeps the big swatch grid out of the way.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Section headers" + }, + { + "id": "HexEditor.collapseNotes", + "surface": "Hex editor: section headers", + "label": "Notes ▶/▼", + "kind": "toggle", + "level": "always", + "loc": "src/hex-map/HexEditorModal.ts:298", + "desc": "Fold or unfold the note text boxes (remembered).", + "pick": "keep", + "why": "Cheap; state remembered.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Section headers" + }, + { + "id": "HexEditor.collapseLinked", + "surface": "Hex editor: section headers", + "label": "Linked notes ▶/▼", + "kind": "toggle", + "level": "always", + "loc": "src/hex-map/HexEditorModal.ts:356", + "desc": "Fold or unfold the six link fields (remembered).", + "pick": "keep", + "why": "Lets users hide the densest group.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Section headers" + }, + { + "id": "HexEditor.collapseIcons", + "surface": "Hex editor: section headers", + "label": "Icons ▶/▼", + "kind": "toggle", + "level": "always", + "loc": "src/hex-map/HexEditorModal.ts:414", + "desc": "Fold or unfold the icon pickers (remembered).", + "pick": "keep", + "why": "Icon grids are huge; should default folded.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Section headers" + }, + { + "id": "HexEditor.terrainChangeHint", + "surface": "Hex editor: terrain", + "label": "▸ change", + "kind": "button", + "level": "conditional: terrain folded; mode: build", + "loc": "src/hex-map/HexEditorModal.ts:286", + "desc": "Hint on the folded header that clicking opens the terrain picker.", + "pick": "keep", + "why": "Affordance only; no extra decision.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Terrain" + }, + { + "id": "HexEditor.terrainFilter", + "surface": "Hex editor: terrain", + "label": "Filter terrains…", + "kind": "search", + "level": "conditional: palette has >12 terrains; mode: build", + "loc": "src/hex-map/HexEditorModal.ts:815", + "desc": "Type to narrow the terrain swatches.", + "pick": "keep", + "why": "Scales a long palette instead of trimming it.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Terrain" + }, + { + "id": "HexEditor.terrainPicker", + "surface": "Hex editor: terrain", + "label": "Terrain swatches", + "kind": "picker", + "level": "mode: build", + "loc": "src/hex-map/HexEditorModal.ts:860", + "desc": "Click a terrain to paint this hex with it.", + "pick": "keep", + "why": "Core.", + "lists": "terrains of this map's palette (getMapPalette)", + "focused": true, + "mix": "", + "group": "Hex editor", + "subgroup": "Terrain" + }, + { + "id": "HexEditor.terrainClear", + "surface": "Hex editor: terrain", + "label": "Clear", + "kind": "button", + "level": "conditional: hex has terrain; mode: build", + "loc": "src/hex-map/HexEditorModal.ts:846", + "desc": "Remove this hex's terrain (back to the map's base).", + "pick": "keep", + "why": "Needed undo-ish action.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Terrain" + }, + { + "id": "HexEditor.bodyFieldUseOnMap", + "surface": "Hex editor: terrain", + "label": "Use \"X\" on the map", + "kind": "button", + "level": "conditional: note text disagrees with map; mode: build", + "loc": "src/hex-map/HexEditorModal.ts:1493", + "desc": "Old note says a different terrain/region: apply that to the map.", + "pick": "keep", + "why": "Only when the note and map disagree; resolves it without losing hand edits.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Terrain" + }, + { + "id": "HexEditor.bodyFieldUpdateNote", + "surface": "Hex editor: terrain", + "label": "Change the note to \"X\"", + "kind": "button", + "level": "conditional: note text disagrees with map", + "loc": "src/hex-map/HexEditorModal.ts:1510", + "desc": "Rewrite the note's Terrain/Region line to match the map.", + "pick": "keep", + "why": "Only when the note and map disagree; resolves it without losing hand edits.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Terrain" + }, + { + "id": "HexEditor.description", + "surface": "Hex editor: notes", + "label": "Description", + "kind": "textarea", + "level": "always", + "loc": "src/hex-map/HexEditorModal.ts:1575", + "desc": "What the party sees in this hex; autosaves.", + "pick": "keep", + "why": "Core hexcrawl content.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Notes" + }, + { + "id": "HexEditor.descriptionRoll", + "surface": "Hex editor: notes", + "label": "📖", + "kind": "button", + "level": "conditional: terrain description table exists", + "loc": "src/hex-map/HexEditorModal.ts:1584", + "desc": "Roll on this terrain's description table and add the result.", + "pick": "keep", + "why": "One-click content; core loop.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Notes" + }, + { + "id": "HexEditor.landmark", + "surface": "Hex editor: notes", + "label": "Landmark", + "kind": "textarea", + "level": "always", + "loc": "src/hex-map/HexEditorModal.ts:1575", + "desc": "A notable landmark visible in this hex.", + "pick": "keep", + "why": "Core hexcrawl content.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Notes" + }, + { + "id": "HexEditor.landmarkRoll", + "surface": "Hex editor: notes", + "label": "📖", + "kind": "button", + "level": "conditional: landmark table exists", + "loc": "src/hex-map/HexEditorModal.ts:1584", + "desc": "Roll on the landmark table and add the result.", + "pick": "keep", + "why": "Same pattern as Description.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Notes" + }, + { + "id": "HexEditor.hidden", + "surface": "Hex editor: notes", + "label": "Hidden", + "kind": "textarea", + "level": "conditional: GM layer on", + "loc": "src/hex-map/HexEditorModal.ts:1575", + "desc": "Things found only by searching this hex.", + "pick": "keep", + "why": "Core GM content; GM-gated already.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Notes" + }, + { + "id": "HexEditor.hiddenRoll", + "surface": "Hex editor: notes", + "label": "📖", + "kind": "button", + "level": "conditional: GM layer on + hidden table exists", + "loc": "src/hex-map/HexEditorModal.ts:1584", + "desc": "Roll on the hidden table and add the result.", + "pick": "keep", + "why": "Same pattern.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Notes" + }, + { + "id": "HexEditor.secret", + "surface": "Hex editor: notes", + "label": "Secret", + "kind": "textarea", + "level": "conditional: GM layer on", + "loc": "src/hex-map/HexEditorModal.ts:1575", + "desc": "GM-only secrets for this hex.", + "pick": "keep", + "why": "Core GM content.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Notes" + }, + { + "id": "HexEditor.secretRoll", + "surface": "Hex editor: notes", + "label": "📖", + "kind": "button", + "level": "conditional: GM layer on + secret table exists", + "loc": "src/hex-map/HexEditorModal.ts:1584", + "desc": "Roll on the secret table and add the result.", + "pick": "keep", + "why": "Same pattern.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Notes" + }, + { + "id": "HexEditor.gmLayerShow", + "surface": "Hex editor: notes", + "label": "Show them", + "kind": "button", + "level": "conditional: GM layer off", + "loc": "src/hex-map/HexEditorModal.ts:319", + "desc": "Turn on the GM layer so Hidden and Secret appear here.", + "pick": "keep", + "why": "Explains missing fields; one click.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Notes" + }, + { + "id": "HexEditor.rolledSectionsFold", + "surface": "Hex editor: notes", + "label": "Weather · Hooks & Rumors", + "kind": "toggle", + "level": "always", + "loc": "src/hex-map/HexEditorModal.ts:329", + "desc": "Fold/unfold the weather and rumours boxes (open if they have text).", + "pick": "keep", + "why": "Plain fold for a standard section.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Notes" + }, + { + "id": "HexEditor.weather", + "surface": "Hex editor: notes", + "label": "Weather", + "kind": "textarea", + "level": "always (folded)", + "loc": "src/hex-map/HexEditorModal.ts:332", + "desc": "Weather notes for this hex.", + "pick": "keep", + "why": "Weather is real hexcrawl content and starts folded.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Notes" + }, + { + "id": "HexEditor.weatherRoll", + "surface": "Hex editor: notes", + "label": "🎲 (Weather)", + "kind": "button", + "level": "always (folded)", + "loc": "src/hex-map/HexEditorModal.ts:1710", + "desc": "Roll weather from the hex/map/starter table; first click may ask for a table.", + "pick": "keep", + "why": "One-click weather roll, same pattern as the other rolls.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Notes" + }, + { + "id": "HexEditor.weatherSource", + "surface": "Hex editor: notes", + "label": "⋯ (Weather)", + "kind": "menu", + "level": "always (folded)", + "loc": "src/hex-map/HexEditorModal.ts:1711", + "desc": "Choose which table Weather rolls on (map's or this hex's).", + "pick": "advanced", + "why": "Per-hex table choice is a real option beyond the basics.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Notes" + }, + { + "id": "HexEditor.hooks", + "surface": "Hex editor: notes", + "label": "Hooks & Rumors", + "kind": "textarea", + "level": "always (folded)", + "loc": "src/hex-map/HexEditorModal.ts:332", + "desc": "Rumours and adventure hooks heard in this hex.", + "pick": "keep", + "why": "Real hexcrawl content.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Notes" + }, + { + "id": "HexEditor.hooksRoll", + "surface": "Hex editor: notes", + "label": "🎲 (Hooks & Rumors)", + "kind": "button", + "level": "always (folded)", + "loc": "src/hex-map/HexEditorModal.ts:1710", + "desc": "Roll a rumour from the hex/map/starter table and add it.", + "pick": "keep", + "why": "One-click content.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Notes" + }, + { + "id": "HexEditor.hooksSource", + "surface": "Hex editor: notes", + "label": "⋯ (Hooks & Rumors)", + "kind": "menu", + "level": "always (folded)", + "loc": "src/hex-map/HexEditorModal.ts:1711", + "desc": "Choose which table rumours roll on (map's or this hex's).", + "pick": "advanced", + "why": "Per-hex table choice is a real option beyond the basics.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Notes" + }, + { + "id": "HexEditor.rolledSetMapTable", + "surface": "Hex editor: notes", + "label": "Set/Change the map's … table…", + "kind": "command", + "level": "mode: build", + "loc": "src/hex-map/HexEditorModal.ts:1760", + "desc": "Pick the table the whole map uses for weather/rumours.", + "pick": "advanced", + "why": "A map property beyond the basics; the first roll asks for a table anyway.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Notes" + }, + { + "id": "HexEditor.rolledSetHexTable", + "surface": "Hex editor: notes", + "label": "Use a different table for this hex…", + "kind": "command", + "level": "always", + "loc": "src/hex-map/HexEditorModal.ts:1761", + "desc": "Override the weather/rumour table for this hex only.", + "pick": "advanced", + "why": "Per-hex table override is a real option beyond the basics.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Notes" + }, + { + "id": "HexEditor.rolledUseMapTable", + "surface": "Hex editor: notes", + "label": "Use the map's table on this hex", + "kind": "command", + "level": "conditional: hex has own table", + "loc": "src/hex-map/HexEditorModal.ts:1763", + "desc": "Remove this hex's own table so it uses the map's again.", + "pick": "keep", + "why": "Only when the hex has its own table; it's the way back.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Notes" + }, + { + "id": "HexEditor.rolledTablePicker", + "surface": "Hex editor: notes", + "label": "Weather/rumour table chooser", + "kind": "picker", + "level": "conditional: from ⋯ menu or 🎲 with no table", + "loc": "src/hex-map/HexEditorModal.ts:1722", + "desc": "Pick a random table for weather or rumours.", + "pick": "keep", + "why": "Needed once per map, but must list tables only.", + "lists": "FileLinkSuggestModal with folderOverride \"\" (not nullish) = whole vault, md only, minus _ notes and templates", + "focused": false, + "mix": "every note in the vault: hexes, map/region notes, biomes, palettes, tables, generators, towns", + "group": "Hex editor", + "subgroup": "Notes" + }, + { + "id": "HexEditor.moreInNoteFold", + "surface": "Hex editor: notes", + "label": "More in this note (N)", + "kind": "toggle", + "level": "conditional: note has unknown headings", + "loc": "src/hex-map/HexEditorModal.ts:345", + "desc": "Fold/unfold extra sections from the note the editor has no field for.", + "pick": "keep", + "why": "Nothing hidden; folded by default.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Notes" + }, + { + "id": "HexEditor.moreInNoteText", + "surface": "Hex editor: notes", + "label": " (other sections)", + "kind": "textarea", + "level": "conditional: note has unknown headings", + "loc": "src/hex-map/HexEditorModal.ts:348", + "desc": "Edit a custom section of the note under its own heading.", + "pick": "keep", + "why": "Respects hand edits.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Notes" + }, + { + "id": "HexEditor.sectionTablePicker", + "surface": "Hex editor: Weather/Rumours ⋯", + "label": "(set map's / this hex's table)", + "kind": "picker", + "level": "conditional: Weather/Hooks ⋯ menu", + "loc": "src/hex-map/HexEditorModal.ts:1722", + "desc": "Pick the random table the 🎲 rolls for Weather or Hooks & Rumors.", + "pick": "keep", + "why": "Needed, but must list only tables", + "lists": "every .md in the WHOLE vault (folderOverride \"\" disables the root) minus templates/_ (HexEditorModal.ts:1722)", + "focused": false, + "mix": "hex notes, biome notes, region notes, map tables, daily notes, any vault note — not just tables", + "group": "Hex editor", + "subgroup": "Notes" + }, + { + "id": "HexEditor.encountersLink", + "surface": "Hex editor: linked notes", + "label": "Encounters Table", + "kind": "picker", + "level": "always", + "loc": "src/hex-map/HexEditorModal.ts:1144", + "desc": "Search, pick or create an encounter table to link to this hex.", + "pick": "keep", + "why": "Core, but list should be encounter tables only.", + "lists": "md notes under tablesFolder (world/tables) minus _/templates, minus terrain/ subfolder and tables with encounter-filter:false (landmark/hidden/secret/weather/rumors/region tables)", + "focused": false, + "mix": "any other roll table (treasure, names, imported tables), not just encounter tables; the terrain encounter tables are excluded", + "group": "Hex editor", + "subgroup": "Linked notes" + }, + { + "id": "HexEditor.encountersShowAll", + "surface": "Hex editor: linked notes", + "label": "▾", + "kind": "button", + "level": "always", + "loc": "src/hex-map/HexEditorModal.ts:1151", + "desc": "Show every table available for Encounters Table.", + "pick": "keep", + "why": "Part of the combo box.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Linked notes" + }, + { + "id": "HexEditor.encountersCreate", + "surface": "Hex editor: linked notes", + "label": "+ Create \"…\"", + "kind": "button", + "level": "conditional: typed name has no match", + "loc": "src/hex-map/HexEditorModal.ts:1272", + "desc": "Make a new table with the typed name and link it.", + "pick": "keep", + "why": "Fast stocking without leaving the hex.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Linked notes" + }, + { + "id": "HexEditor.encountersOpenLink", + "surface": "Hex editor: linked notes", + "label": "", + "kind": "button", + "level": "conditional: hex has links here", + "loc": "src/hex-map/HexEditorModal.ts:1440", + "desc": "Open the linked table in the random tables view.", + "pick": "keep", + "why": "Obvious.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Linked notes" + }, + { + "id": "HexEditor.encountersRemove", + "surface": "Hex editor: linked notes", + "label": "×", + "kind": "button", + "level": "conditional: hex has links here", + "loc": "src/hex-map/HexEditorModal.ts:1459", + "desc": "Unlink this note from the hex.", + "pick": "keep", + "why": "Obvious.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Linked notes" + }, + { + "id": "HexEditor.townsLink", + "surface": "Hex editor: linked notes", + "label": "Towns", + "kind": "picker", + "level": "always", + "loc": "src/hex-map/HexEditorModal.ts:1144", + "desc": "Search, pick or create a town note to link to this hex.", + "pick": "keep", + "why": "Core link field.", + "lists": "md notes under townsFolder minus _/templates; townsFolder defaults to \"\" = whole vault", + "focused": false, + "mix": "only if Towns folder is blank (the default before setup): every note in the vault: hexes, map/region notes, biomes, palettes, tables, generators, towns", + "group": "Hex editor", + "subgroup": "Linked notes" + }, + { + "id": "HexEditor.townsShowAll", + "surface": "Hex editor: linked notes", + "label": "▾", + "kind": "button", + "level": "always", + "loc": "src/hex-map/HexEditorModal.ts:1151", + "desc": "Show every note available for Towns.", + "pick": "keep", + "why": "Part of the combo box.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Linked notes" + }, + { + "id": "HexEditor.townsCreate", + "surface": "Hex editor: linked notes", + "label": "+ Create \"…\"", + "kind": "button", + "level": "conditional: typed name has no match", + "loc": "src/hex-map/HexEditorModal.ts:1272", + "desc": "Make a new note with the typed name and link it.", + "pick": "keep", + "why": "Fast stocking without leaving the hex.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Linked notes" + }, + { + "id": "HexEditor.townsOpenLink", + "surface": "Hex editor: linked notes", + "label": "", + "kind": "button", + "level": "conditional: hex has links here", + "loc": "src/hex-map/HexEditorModal.ts:1440", + "desc": "Open the linked note.", + "pick": "keep", + "why": "Obvious.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Linked notes" + }, + { + "id": "HexEditor.townsRemove", + "surface": "Hex editor: linked notes", + "label": "×", + "kind": "button", + "level": "conditional: hex has links here", + "loc": "src/hex-map/HexEditorModal.ts:1459", + "desc": "Unlink this note from the hex.", + "pick": "keep", + "why": "Obvious.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Linked notes" + }, + { + "id": "HexEditor.dungeonsLink", + "surface": "Hex editor: linked notes", + "label": "Dungeons", + "kind": "picker", + "level": "always", + "loc": "src/hex-map/HexEditorModal.ts:1144", + "desc": "Search, pick or create a dungeon note to link to this hex.", + "pick": "keep", + "why": "Core link field.", + "lists": "md notes under dungeonsFolder minus _/templates; blank default = whole vault", + "focused": false, + "mix": "only if Dungeons folder is blank (default): every note in the vault: hexes, map/region notes, biomes, palettes, tables, generators, towns", + "group": "Hex editor", + "subgroup": "Linked notes" + }, + { + "id": "HexEditor.dungeonsShowAll", + "surface": "Hex editor: linked notes", + "label": "▾", + "kind": "button", + "level": "always", + "loc": "src/hex-map/HexEditorModal.ts:1151", + "desc": "Show every note available for Dungeons.", + "pick": "keep", + "why": "Part of the combo box.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Linked notes" + }, + { + "id": "HexEditor.dungeonsCreate", + "surface": "Hex editor: linked notes", + "label": "+ Create \"…\"", + "kind": "button", + "level": "conditional: typed name has no match", + "loc": "src/hex-map/HexEditorModal.ts:1272", + "desc": "Make a new note with the typed name and link it.", + "pick": "keep", + "why": "Fast stocking without leaving the hex.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Linked notes" + }, + { + "id": "HexEditor.dungeonsOpenLink", + "surface": "Hex editor: linked notes", + "label": "", + "kind": "button", + "level": "conditional: hex has links here", + "loc": "src/hex-map/HexEditorModal.ts:1440", + "desc": "Open the linked note.", + "pick": "keep", + "why": "Obvious.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Linked notes" + }, + { + "id": "HexEditor.dungeonsRemove", + "surface": "Hex editor: linked notes", + "label": "×", + "kind": "button", + "level": "conditional: hex has links here", + "loc": "src/hex-map/HexEditorModal.ts:1459", + "desc": "Unlink this note from the hex.", + "pick": "keep", + "why": "Obvious.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Linked notes" + }, + { + "id": "HexEditor.questsLink", + "surface": "Hex editor: linked notes", + "label": "Quests", + "kind": "picker", + "level": "always", + "loc": "src/hex-map/HexEditorModal.ts:1144", + "desc": "Search, pick or create a quest note to link to this hex.", + "pick": "keep", + "why": "Core link field.", + "lists": "md notes under questsFolder minus _/templates; blank default = whole vault", + "focused": false, + "mix": "only if Quests folder is blank (default): every note in the vault: hexes, map/region notes, biomes, palettes, tables, generators, towns", + "group": "Hex editor", + "subgroup": "Linked notes" + }, + { + "id": "HexEditor.questsShowAll", + "surface": "Hex editor: linked notes", + "label": "▾", + "kind": "button", + "level": "always", + "loc": "src/hex-map/HexEditorModal.ts:1151", + "desc": "Show every note available for Quests.", + "pick": "keep", + "why": "Part of the combo box.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Linked notes" + }, + { + "id": "HexEditor.questsCreate", + "surface": "Hex editor: linked notes", + "label": "+ Create \"…\"", + "kind": "button", + "level": "conditional: typed name has no match", + "loc": "src/hex-map/HexEditorModal.ts:1272", + "desc": "Make a new note with the typed name and link it.", + "pick": "keep", + "why": "Fast stocking without leaving the hex.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Linked notes" + }, + { + "id": "HexEditor.questsOpenLink", + "surface": "Hex editor: linked notes", + "label": "", + "kind": "button", + "level": "conditional: hex has links here", + "loc": "src/hex-map/HexEditorModal.ts:1440", + "desc": "Open the linked note.", + "pick": "keep", + "why": "Obvious.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Linked notes" + }, + { + "id": "HexEditor.questsRemove", + "surface": "Hex editor: linked notes", + "label": "×", + "kind": "button", + "level": "conditional: hex has links here", + "loc": "src/hex-map/HexEditorModal.ts:1459", + "desc": "Unlink this note from the hex.", + "pick": "keep", + "why": "Obvious.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Linked notes" + }, + { + "id": "HexEditor.factionsLink", + "surface": "Hex editor: linked notes", + "label": "Factions", + "kind": "picker", + "level": "always", + "loc": "src/hex-map/HexEditorModal.ts:1144", + "desc": "Search, pick or create a faction note to link to this hex.", + "pick": "keep", + "why": "Core link field.", + "lists": "md notes under factionsFolder minus _/templates; blank default = whole vault", + "focused": false, + "mix": "only if Factions folder is blank (default): every note in the vault: hexes, map/region notes, biomes, palettes, tables, generators, towns", + "group": "Hex editor", + "subgroup": "Linked notes" + }, + { + "id": "HexEditor.factionsShowAll", + "surface": "Hex editor: linked notes", + "label": "▾", + "kind": "button", + "level": "always", + "loc": "src/hex-map/HexEditorModal.ts:1151", + "desc": "Show every note available for Factions.", + "pick": "keep", + "why": "Part of the combo box.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Linked notes" + }, + { + "id": "HexEditor.factionsCreate", + "surface": "Hex editor: linked notes", + "label": "+ Create \"…\"", + "kind": "button", + "level": "conditional: typed name has no match", + "loc": "src/hex-map/HexEditorModal.ts:1272", + "desc": "Make a new note with the typed name and link it.", + "pick": "keep", + "why": "Fast stocking without leaving the hex.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Linked notes" + }, + { + "id": "HexEditor.factionsOpenLink", + "surface": "Hex editor: linked notes", + "label": "", + "kind": "button", + "level": "conditional: hex has links here", + "loc": "src/hex-map/HexEditorModal.ts:1440", + "desc": "Open the linked note.", + "pick": "keep", + "why": "Obvious.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Linked notes" + }, + { + "id": "HexEditor.factionsRemove", + "surface": "Hex editor: linked notes", + "label": "×", + "kind": "button", + "level": "conditional: hex has links here", + "loc": "src/hex-map/HexEditorModal.ts:1459", + "desc": "Unlink this note from the hex.", + "pick": "keep", + "why": "Obvious.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Linked notes" + }, + { + "id": "HexEditor.featuresLink", + "surface": "Hex editor: linked notes", + "label": "Features", + "kind": "picker", + "level": "always", + "loc": "src/hex-map/HexEditorModal.ts:1144", + "desc": "Search, pick or create a feature note to link to this hex.", + "pick": "keep", + "why": "Core link field.", + "lists": "md notes under featuresFolder minus _/templates; blank default = whole vault", + "focused": false, + "mix": "only if Features folder is blank (default): every note in the vault: hexes, map/region notes, biomes, palettes, tables, generators, towns", + "group": "Hex editor", + "subgroup": "Linked notes" + }, + { + "id": "HexEditor.featuresShowAll", + "surface": "Hex editor: linked notes", + "label": "▾", + "kind": "button", + "level": "always", + "loc": "src/hex-map/HexEditorModal.ts:1151", + "desc": "Show every note available for Features.", + "pick": "keep", + "why": "Part of the combo box.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Linked notes" + }, + { + "id": "HexEditor.featuresCreate", + "surface": "Hex editor: linked notes", + "label": "+ Create \"…\"", + "kind": "button", + "level": "conditional: typed name has no match", + "loc": "src/hex-map/HexEditorModal.ts:1272", + "desc": "Make a new note with the typed name and link it.", + "pick": "keep", + "why": "Fast stocking without leaving the hex.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Linked notes" + }, + { + "id": "HexEditor.featuresOpenLink", + "surface": "Hex editor: linked notes", + "label": "", + "kind": "button", + "level": "conditional: hex has links here", + "loc": "src/hex-map/HexEditorModal.ts:1440", + "desc": "Open the linked note.", + "pick": "keep", + "why": "Obvious.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Linked notes" + }, + { + "id": "HexEditor.featuresRemove", + "surface": "Hex editor: linked notes", + "label": "×", + "kind": "button", + "level": "conditional: hex has links here", + "loc": "src/hex-map/HexEditorModal.ts:1459", + "desc": "Unlink this note from the hex.", + "pick": "keep", + "why": "Obvious.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Linked notes" + }, + { + "id": "HexEditor.encountersRoll", + "surface": "Hex editor: linked notes", + "label": "🎲 (Encounters)", + "kind": "button", + "level": "conditional: hex has an encounter table", + "loc": "src/hex-map/HexEditorModal.ts:1450", + "desc": "Roll on the linked encounter table and add the result.", + "pick": "simple", + "why": "Rolling a hex's encounter is the core play-time action.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Linked notes" + }, + { + "id": "HexEditor.iconOverride", + "surface": "Hex editor: icons", + "label": "Icon override", + "kind": "picker", + "level": "mode: build", + "loc": "src/hex-map/HexEditorModal.ts:922", + "desc": "Pick an icon for this hex instead of the terrain's icon.", + "pick": "keep", + "why": "Common; but whole library is a lot (filter helps).", + "lists": "plugin.availableIcons minus hiddenIcons: bundled icons of enabled map kinds + custom icons folder", + "focused": true, + "mix": "", + "group": "Hex editor", + "subgroup": "Icons" + }, + { + "id": "HexEditor.iconTerrainDefault", + "surface": "Hex editor: icons", + "label": "— terrain default —", + "kind": "button", + "level": "mode: build", + "loc": "src/hex-map/HexEditorModal.ts:926", + "desc": "Remove the override so the terrain's own icon shows.", + "pick": "keep", + "why": "Needed reset.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Icons" + }, + { + "id": "HexEditor.iconPackTabs", + "surface": "Hex editor: icons", + "label": "All / / Custom tabs", + "kind": "radio", + "level": "mode: build", + "loc": "src/HexmakerModal.ts:108", + "desc": "Show icons from one pack only (with counts).", + "pick": "keep", + "why": "Scales a huge list.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Icons" + }, + { + "id": "HexEditor.iconPlaceKinds", + "surface": "Hex editor: icons", + "label": "All places / Settlements / Castles…", + "kind": "radio", + "level": "conditional: Places tab active", + "loc": "src/HexmakerModal.ts:133", + "desc": "Narrow the Places pack to one kind of place.", + "pick": "keep", + "why": "A plain picker filter that helps find a place icon.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Icons" + }, + { + "id": "HexEditor.gmIcons", + "surface": "Hex editor: icons", + "label": "Game master icons", + "kind": "picker", + "level": "conditional: GM layer on; mode: build", + "loc": "src/hex-map/HexEditorModal.ts:941", + "desc": "Click to add GM-only icons (repeatable, ×N badge).", + "pick": "keep", + "why": "GM-only icons are what the GM layer is for; already GM-layer gated.", + "lists": "same list as Icon override (availableIcons minus hiddenIcons)", + "focused": true, + "mix": "", + "group": "Hex editor", + "subgroup": "Icons" + }, + { + "id": "HexEditor.gmIconsRemoveOne", + "surface": "Hex editor: icons", + "label": "Right-click icon", + "kind": "button", + "level": "conditional: GM layer on; mode: build", + "loc": "src/hex-map/HexEditorModal.ts:1037", + "desc": "Right-click a GM icon to remove one copy.", + "pick": "keep", + "why": "How you remove one GM icon; only with the GM layer on.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Icons" + }, + { + "id": "HexEditor.gmIconsClearAll", + "surface": "Hex editor: icons", + "label": "— clear all —", + "kind": "button", + "level": "conditional: GM layer on; mode: build", + "loc": "src/hex-map/HexEditorModal.ts:1050", + "desc": "Remove every GM icon from this hex.", + "pick": "keep", + "why": "Clear for the GM icons; only with the GM layer on.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Icons" + }, + { + "id": "HexEditor.gmIconFilterSearch", + "surface": "Hex editor: icons", + "label": "Filter icons… (GM)", + "kind": "search", + "level": "conditional: GM layer on; mode: build", + "loc": "src/HexmakerModal.ts:45", + "desc": "Type to narrow the GM icon grid.", + "pick": "keep", + "why": "Filter for the GM icon grid; only with the GM layer on.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Icons" + }, + { + "id": "HexEditor.gmIconPackTabs", + "surface": "Hex editor: icons", + "label": "All / / Custom tabs (GM)", + "kind": "radio", + "level": "conditional: GM layer on; mode: build", + "loc": "src/HexmakerModal.ts:108", + "desc": "Show GM icons from one pack only.", + "pick": "keep", + "why": "Pack tabs for the GM icon grid; only with the GM layer on.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Icons" + }, + { + "id": "HexEditor.gmIconPlaceKinds", + "surface": "Hex editor: icons", + "label": "Place kind chips (GM)", + "kind": "radio", + "level": "conditional: GM layer on, Places tab", + "loc": "src/HexmakerModal.ts:133", + "desc": "Narrow GM Places icons to one kind.", + "pick": "keep", + "why": "A plain picker filter, same as on the main icon grid.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Icons" + }, + { + "id": "HexTable.refresh", + "surface": "Hex table: toolbar", + "label": "Refresh", + "kind": "button", + "level": "always", + "loc": "src/hex-table/HexTableView.ts:143", + "desc": "Reload every row from the notes.", + "pick": "overkill", + "why": "Refresh button; the table already live-updates.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex table", + "subgroup": "Toolbar" + }, + { + "id": "HexTable.xMin", + "surface": "Hex table: toolbar", + "label": "X: Min", + "kind": "number", + "level": "always", + "loc": "src/hex-table/HexTableView.ts:153", + "desc": "Only show hexes with X at least this.", + "pick": "advanced", + "why": "Coordinate range filters are a real option beyond the basic filters.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex table", + "subgroup": "Toolbar" + }, + { + "id": "HexTable.xMax", + "surface": "Hex table: toolbar", + "label": "X: Max", + "kind": "number", + "level": "always", + "loc": "src/hex-table/HexTableView.ts:164", + "desc": "Only show hexes with X at most this.", + "pick": "advanced", + "why": "Coordinate range filters are a real option beyond the basic filters.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex table", + "subgroup": "Toolbar" + }, + { + "id": "HexTable.yMin", + "surface": "Hex table: toolbar", + "label": "Y: Min", + "kind": "number", + "level": "always", + "loc": "src/hex-table/HexTableView.ts:179", + "desc": "Only show hexes with Y at least this.", + "pick": "advanced", + "why": "Coordinate range filters are a real option beyond the basic filters.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex table", + "subgroup": "Toolbar" + }, + { + "id": "HexTable.yMax", + "surface": "Hex table: toolbar", + "label": "Y: Max", + "kind": "number", + "level": "always", + "loc": "src/hex-table/HexTableView.ts:190", + "desc": "Only show hexes with Y at most this.", + "pick": "advanced", + "why": "Coordinate range filters are a real option beyond the basic filters.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex table", + "subgroup": "Toolbar" + }, + { + "id": "HexTable.terrainFilter", + "surface": "Hex table: toolbar", + "label": "Terrain: all", + "kind": "button", + "level": "always", + "loc": "src/hex-table/HexTableView.ts:204", + "desc": "Open a filter to show only (or hide) some terrains.", + "pick": "keep", + "why": "Most useful filter in the table.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex table", + "subgroup": "Toolbar" + }, + { + "id": "HexTable.hasTown", + "surface": "Hex table: toolbar", + "label": "Town", + "kind": "checkbox", + "level": "always", + "loc": "src/hex-table/HexTableView.ts:240", + "desc": "Only show hexes that link a town.", + "pick": "keep", + "why": "Quick 'where are my towns' answer.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex table", + "subgroup": "Toolbar" + }, + { + "id": "HexTable.hasDungeon", + "surface": "Hex table: toolbar", + "label": "Dungeon", + "kind": "checkbox", + "level": "always", + "loc": "src/hex-table/HexTableView.ts:252", + "desc": "Only show hexes that link a dungeon.", + "pick": "keep", + "why": "Same.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex table", + "subgroup": "Toolbar" + }, + { + "id": "HexTable.hasFeature", + "surface": "Hex table: toolbar", + "label": "Feature", + "kind": "checkbox", + "level": "always", + "loc": "src/hex-table/HexTableView.ts:264", + "desc": "Only show hexes that link a feature.", + "pick": "keep", + "why": "Same everyday 'which hexes have X' filter as Town and Dungeon.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex table", + "subgroup": "Toolbar" + }, + { + "id": "HexTable.hasQuest", + "surface": "Hex table: toolbar", + "label": "Quest", + "kind": "checkbox", + "level": "always", + "loc": "src/hex-table/HexTableView.ts:276", + "desc": "Only show hexes that link a quest.", + "pick": "keep", + "why": "Same everyday 'which hexes have X' filter as Town and Dungeon.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex table", + "subgroup": "Toolbar" + }, + { + "id": "HexTable.hasFaction", + "surface": "Hex table: toolbar", + "label": "Faction", + "kind": "checkbox", + "level": "always", + "loc": "src/hex-table/HexTableView.ts:288", + "desc": "Only show hexes that link a faction.", + "pick": "keep", + "why": "Same everyday 'which hexes have X' filter as Town and Dungeon.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex table", + "subgroup": "Toolbar" + }, + { + "id": "HexTable.mapSelect", + "surface": "Hex table: toolbar", + "label": "All maps / ", + "kind": "dropdown", + "level": "always", + "loc": "src/hex-table/HexTableView.ts:299", + "desc": "Choose which map's hexes the table lists.", + "pick": "keep", + "why": "Essential once there are several maps.", + "lists": "\"All maps\" + every map in settings.maps (overworlds, regions, locations, all kinds)", + "focused": true, + "mix": "", + "group": "Hex table", + "subgroup": "Toolbar" + }, + { + "id": "HexTable.sortCycle", + "surface": "Hex table: toolbar", + "label": "Sort: xy / yx / type", + "kind": "button", + "level": "always", + "loc": "src/hex-table/HexTableView.ts:329", + "desc": "Cycle the sort: by X, by Y, or by terrain type.", + "pick": "keep", + "why": "Sorting a table is standard use (the cycling button could be clearer).", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex table", + "subgroup": "Toolbar" + }, + { + "id": "HexTable.sortDirection", + "surface": "Hex table: toolbar", + "label": "↑ asc / ↓ desc", + "kind": "button", + "level": "always", + "loc": "src/hex-table/HexTableView.ts:341", + "desc": "Flip the sort direction.", + "pick": "keep", + "why": "Sort direction is standard table use.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex table", + "subgroup": "Toolbar" + }, + { + "id": "HexTable.clearFilters", + "surface": "Hex table: toolbar", + "label": "Clear filters", + "kind": "button", + "level": "always", + "loc": "src/hex-table/HexTableView.ts:355", + "desc": "Reset every filter in the toolbar.", + "pick": "keep", + "why": "Escape hatch for all the filters.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex table", + "subgroup": "Toolbar" + }, + { + "id": "HexTable.jumpToHex", + "surface": "Hex table: rows", + "label": "◎", + "kind": "button", + "level": "always", + "loc": "src/hex-table/HexTableView.ts:802", + "desc": "Center the hex map on this row's hex.", + "pick": "keep", + "why": "Core link between table and map.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex table", + "subgroup": "Rows & cells" + }, + { + "id": "HexTable.openHexNote", + "surface": "Hex table: rows", + "label": "", + "kind": "button", + "level": "conditional: hex note exists", + "loc": "src/hex-table/HexTableView.ts:812", + "desc": "Open this hex's note.", + "pick": "keep", + "why": "Obvious.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex table", + "subgroup": "Rows & cells" + }, + { + "id": "HexTable.terrainCell", + "surface": "Hex table: rows", + "label": "Terrain cell", + "kind": "button", + "level": "always", + "loc": "src/hex-table/HexTableView.ts:889", + "desc": "Click to change this hex's terrain.", + "pick": "keep", + "why": "Bulk terrain fixing from the table.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex table", + "subgroup": "Rows & cells" + }, + { + "id": "HexTable.townsCell", + "surface": "Hex table: rows", + "label": "Towns cell", + "kind": "button", + "level": "always", + "loc": "src/hex-table/HexTableView.ts:970", + "desc": "Empty: pick/create a town; one: open it; several: pick one.", + "pick": "keep", + "why": "Useful, though overloaded by link count.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex table", + "subgroup": "Rows & cells" + }, + { + "id": "HexTable.dungeonsCell", + "surface": "Hex table: rows", + "label": "Dungeons cell", + "kind": "button", + "level": "always", + "loc": "src/hex-table/HexTableView.ts:970", + "desc": "Empty: pick/create a dungeon; one: open it; several: pick one.", + "pick": "keep", + "why": "Same.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex table", + "subgroup": "Rows & cells" + }, + { + "id": "HexTable.encountersCell", + "surface": "Hex table: rows", + "label": "Enc. Table cell", + "kind": "button", + "level": "always", + "loc": "src/hex-table/HexTableView.ts:970", + "desc": "Empty: pick/create a table; one: open it in the tables view.", + "pick": "keep", + "why": "Same.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex table", + "subgroup": "Rows & cells" + }, + { + "id": "HexTable.encountersMiddleClick", + "surface": "Hex table: rows", + "label": "Middle-click Enc. Table", + "kind": "button", + "level": "conditional: exactly one table linked", + "loc": "src/hex-table/HexTableView.ts:947", + "desc": "Middle-click to open the encounter table in a new tab.", + "pick": "keep", + "why": "Invisible shortcut that follows Obsidian's middle-click habit; costs nothing.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex table", + "subgroup": "Rows & cells" + }, + { + "id": "HexTable.otherLinkCell", + "surface": "Hex table: rows", + "label": "Features/Quests/Factions cell", + "kind": "button", + "level": "conditional: cell has links", + "loc": "src/hex-table/HexTableView.ts:1031", + "desc": "Show the linked notes as a read-only list.", + "pick": "keep", + "why": "Shows which notes are linked; making it editable is a fix, not a cut.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex table", + "subgroup": "Rows & cells" + }, + { + "id": "HexTable.textCell", + "surface": "Hex table: rows", + "label": "Text cells (Description…Hooks)", + "kind": "button", + "level": "always", + "loc": "src/hex-table/HexTableView.ts:1054", + "desc": "Click to read and edit this note section in a popup.", + "pick": "keep", + "why": "Core quick-edit.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex table", + "subgroup": "Rows & cells" + }, + { + "id": "HexTable.columnResize", + "surface": "Hex table: rows", + "label": "Column edge drag", + "kind": "slider", + "level": "always", + "loc": "src/hex-table/HexTableView.ts:1119", + "desc": "Drag a header edge to resize the column (not remembered).", + "pick": "keep", + "why": "Standard table behaviour.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex table", + "subgroup": "Rows & cells" + }, + { + "id": "HexTable.hiddenSecretColumns", + "surface": "Hex table: rows", + "label": "Hidden / Secret columns", + "kind": "button", + "level": "always", + "loc": "src/hex-table/HexTableView.ts:44", + "desc": "Shown regardless of the GM layer; click to edit like other text cells.", + "pick": "keep", + "why": "Real hex content; following the GM layer is a fix, not a cut.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex table", + "subgroup": "Rows & cells" + }, + { + "id": "HexTable.weatherHooksColumns", + "surface": "Hex table: rows", + "label": "Weather / Hooks & Rumors columns", + "kind": "button", + "level": "always", + "loc": "src/hex-table/HexTableView.ts:46", + "desc": "Click to edit weather or rumours text for the hex.", + "pick": "keep", + "why": "Real hexcrawl content, same as the other text columns.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex table", + "subgroup": "Rows & cells" + }, + { + "id": "HexCell.textarea", + "surface": "Hex table: cell popup", + "label": "
text", + "kind": "textarea", + "level": "conditional: text column", + "loc": "src/hex-table/HexCellModal.ts:38", + "desc": "Read and edit the full section text; saves on close.", + "pick": "keep", + "why": "Core quick-edit.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex table", + "subgroup": "Rows & cells" + }, + { + "id": "HexCell.rollOnTable", + "surface": "Hex table: cell popup", + "label": "🎲 Roll on table", + "kind": "button", + "level": "conditional: description/landmark/hidden/secret table exists", + "loc": "src/hex-table/HexCellModal.ts:46", + "desc": "Roll on the matching table and append the result.", + "pick": "keep", + "why": "Same as hex editor 📖; no weather/rumour roll here.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex table", + "subgroup": "Rows & cells" + }, + { + "id": "HexCell.linkList", + "surface": "Hex table: cell popup", + "label": "", + "kind": "picker", + "level": "conditional: Features/Quests/Factions column", + "loc": "src/hex-table/HexCellModal.ts:33", + "desc": "Read-only list of linked notes (not clickable).", + "pick": "keep", + "why": "Shows which notes are linked; making it clickable is a fix, not a cut.", + "lists": "the links in that cell", + "focused": true, + "mix": "", + "group": "Hex table", + "subgroup": "Rows & cells" + }, + { + "id": "HexCell.closeButtons", + "surface": "Hex table: cell popup", + "label": "×", + "kind": "button", + "level": "always", + "loc": "src/hex-table/HexCellModal.ts:69", + "desc": "Close the popup (saves the text).", + "pick": "keep", + "why": "Standard.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex table", + "subgroup": "Rows & cells" + }, + { + "id": "TerrainFilter.noTerrain", + "surface": "Hex table: terrain filter", + "label": "No terrain", + "kind": "checkbox", + "level": "always", + "loc": "src/hex-table/TerrainFilterModal.ts:156", + "desc": "Include (click) or exclude (right-click) hexes with no terrain.", + "pick": "keep", + "why": "Finding unpainted hexes is common.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex table", + "subgroup": "Terrain filter" + }, + { + "id": "TerrainFilter.typeRow", + "surface": "Hex table: terrain filter", + "label": " row", + "kind": "checkbox", + "level": "conditional: palette has typed terrains", + "loc": "src/hex-table/TerrainFilterModal.ts:160", + "desc": "Include/exclude every terrain of one type (water, land…).", + "pick": "advanced", + "why": "Filtering by terrain type is a real option beyond the basic terrain filter.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex table", + "subgroup": "Terrain filter" + }, + { + "id": "TerrainFilter.terrainRow", + "surface": "Hex table: terrain filter", + "label": " rows", + "kind": "picker", + "level": "always", + "loc": "src/hex-table/TerrainFilterModal.ts:168", + "desc": "Include (click) or exclude (right-click) a terrain.", + "pick": "keep", + "why": "Core of the filter.", + "lists": "selected map's palette, or with All maps every terrain of every palette (getAllTerrains), deduped by name", + "focused": true, + "mix": "", + "group": "Hex table", + "subgroup": "Terrain filter" + }, + { + "id": "TerrainFilter.excludeRightClick", + "surface": "Hex table: terrain filter", + "label": "Right-click to exclude", + "kind": "button", + "level": "always", + "loc": "src/hex-table/TerrainFilterModal.ts:94", + "desc": "Right-click any row to exclude it instead of include.", + "pick": "keep", + "why": "Invisible right-click option on the filter; costs nothing.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex table", + "subgroup": "Terrain filter" + }, + { + "id": "TerrainFilter.categoryHeading", + "surface": "Hex table: terrain filter", + "label": " heading", + "kind": "button", + "level": "conditional: untyped terrains with categories", + "loc": "src/hex-table/TerrainFilterModal.ts:130", + "desc": "Click to include all in a category; right-click to exclude all.", + "pick": "keep", + "why": "Only shows when terrains have categories; a plain select-all for the group.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex table", + "subgroup": "Terrain filter" + }, + { + "id": "TerrainFilter.clearAll", + "surface": "Hex table: terrain filter", + "label": "Clear all", + "kind": "button", + "level": "always", + "loc": "src/hex-table/TerrainFilterModal.ts:206", + "desc": "Untick everything in the terrain filter.", + "pick": "keep", + "why": "Needed reset.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex table", + "subgroup": "Terrain filter" + }, + { + "id": "TerrainFilter.closeButtons", + "surface": "Hex table: terrain filter", + "label": "Done / ×", + "kind": "button", + "level": "always", + "loc": "src/hex-table/TerrainFilterModal.ts:216", + "desc": "Close the filter (it applies live).", + "pick": "keep", + "why": "Standard.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex table", + "subgroup": "Terrain filter" + }, + { + "id": "HexTerrainPicker.terrains", + "surface": "Hex table: select terrain", + "label": "Select terrain", + "kind": "picker", + "level": "always", + "loc": "src/hex-table/HexTerrainPickerModal.ts:129", + "desc": "Click a terrain to paint this hex with it.", + "pick": "keep", + "why": "Core; note no filter box unlike the hex editor.", + "lists": "terrains of the hex's map palette", + "focused": true, + "mix": "", + "group": "Hex table", + "subgroup": "Terrain filter" + }, + { + "id": "HexTerrainPicker.clear", + "surface": "Hex table: select terrain", + "label": "Clear terrain", + "kind": "button", + "level": "conditional: hex has terrain", + "loc": "src/hex-table/HexTerrainPickerModal.ts:160", + "desc": "Remove this hex's terrain.", + "pick": "keep", + "why": "Needed reset.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex table", + "subgroup": "Terrain filter" + }, + { + "id": "HexTerrainPicker.closeButtons", + "surface": "Hex table: select terrain", + "label": "×", + "kind": "button", + "level": "always", + "loc": "src/hex-table/HexTerrainPickerModal.ts:120", + "desc": "Close without changing terrain.", + "pick": "keep", + "why": "Standard.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex table", + "subgroup": "Terrain filter" + }, + { + "id": "LinkPicker.townsList", + "surface": "Hex table: add link", + "label": "Select existing: (Towns)", + "kind": "picker", + "level": "always", + "loc": "src/hex-table/LinkPickerModal.ts:206", + "desc": "Click a town note to link it to the hex.", + "pick": "keep", + "why": "Core; but no search box on a flat list.", + "lists": "md notes under townsFolder minus _/templates; blank folder (default) = whole vault", + "focused": false, + "mix": "only if Towns folder is blank (default): every note in the vault: hexes, map/region notes, biomes, palettes, tables, generators, towns", + "group": "Hex table", + "subgroup": "Linking" + }, + { + "id": "LinkPicker.dungeonsList", + "surface": "Hex table: add link", + "label": "Select existing: (Dungeons)", + "kind": "picker", + "level": "always", + "loc": "src/hex-table/LinkPickerModal.ts:206", + "desc": "Click a dungeon note to link it to the hex.", + "pick": "keep", + "why": "Core; no search box.", + "lists": "md notes under dungeonsFolder minus _/templates; blank folder (default) = whole vault", + "focused": false, + "mix": "only if Dungeons folder is blank (default): every note in the vault: hexes, map/region notes, biomes, palettes, tables, generators, towns", + "group": "Hex table", + "subgroup": "Linking" + }, + { + "id": "LinkPicker.encountersList", + "surface": "Hex table: add link", + "label": "Select existing: (Encounters Table)", + "kind": "picker", + "level": "always", + "loc": "src/hex-table/LinkPickerModal.ts:206", + "desc": "Click a table to link it as this hex's encounter table.", + "pick": "keep", + "why": "Core, but list is unfiltered.", + "lists": "every md note under tablesFolder minus _/templates; NO encounter filter (unlike the hex editor)", + "focused": false, + "mix": "terrain description + encounter tables, landmark/hidden/secret, weather/rumours, region tables and any other roll table", + "group": "Hex table", + "subgroup": "Linking" + }, + { + "id": "LinkPicker.createName", + "surface": "Hex table: add link", + "label": "Or create new: ", + "kind": "text", + "level": "always", + "loc": "src/hex-table/LinkPickerModal.ts:232", + "desc": "Type a name for a new note to create and link.", + "pick": "keep", + "why": "Fast stocking.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex table", + "subgroup": "Linking" + }, + { + "id": "LinkPicker.createButton", + "surface": "Hex table: add link", + "label": "Create", + "kind": "button", + "level": "always", + "loc": "src/hex-table/LinkPickerModal.ts:237", + "desc": "Create the typed note and link it to the hex.", + "pick": "keep", + "why": "Obvious.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex table", + "subgroup": "Linking" + }, + { + "id": "LinkPicker.closeButtons", + "surface": "Hex table: add link", + "label": "×", + "kind": "button", + "level": "always", + "loc": "src/hex-table/LinkPickerModal.ts:199", + "desc": "Close without linking.", + "pick": "keep", + "why": "Standard.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex table", + "subgroup": "Linking" + }, + { + "id": "MultiLinkNav.items", + "surface": "Hex table: pick linked note", + "label": "", + "kind": "picker", + "level": "conditional: cell has 2+ links", + "loc": "src/hex-table/MultiLinkNavModal.ts:20", + "desc": "Pick which of the linked notes to open.", + "pick": "keep", + "why": "Simple disambiguation.", + "lists": "the links already in that hex cell (towns, dungeons or encounter tables)", + "focused": true, + "mix": "", + "group": "Hex table", + "subgroup": "Linking" + }, + { + "id": "MultiLinkNav.closeButtons", + "surface": "Hex table: pick linked note", + "label": "×", + "kind": "button", + "level": "always", + "loc": "src/hex-table/MultiLinkNavModal.ts:13", + "desc": "Close the list.", + "pick": "keep", + "why": "Standard.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex table", + "subgroup": "Linking" + }, + { + "id": "IconFilter.search", + "surface": "Icon picker filter bar (shared)", + "label": "Filter icons...", + "kind": "search", + "level": "always (every icon grid using addIconFilter)", + "loc": "src/HexmakerModal.ts:45", + "desc": "Type to filter icons by name or kind.", + "pick": "keep", + "why": "Essential for large icon sets.", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Icons" + }, + { + "id": "IconFilter.packTabs", + "surface": "Icon picker filter bar (shared)", + "label": "All / Terrain / Places / Space / Custom (+counts)", + "kind": "radio", + "level": "always", + "loc": "src/HexmakerModal.ts:108", + "desc": "Tabs that filter icons by pack.", + "pick": "keep", + "why": "Scales the picker; check Space tab follows map kinds.", + "lists": "Icon packs with counts; Custom always shown", + "focused": true, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Icons" + }, + { + "id": "IconFilter.placeKindChips", + "surface": "Icon picker filter bar (shared)", + "label": "All places / Settlements / Castles / ...", + "kind": "radio", + "level": "conditional: Places tab active", + "loc": "src/HexmakerModal.ts:134", + "desc": "Sub-filter chips for place icons.", + "pick": "keep", + "why": "A plain picker filter that helps find a place icon; no cost when unused.", + "lists": "Place icon kinds present", + "focused": true, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Icons" + }, + { + "id": "IconPicker.gmLayerOnly", + "surface": "Icon picker modal", + "label": "GM layer only", + "kind": "checkbox", + "level": "mode: build/god", + "loc": "src/hex-map/IconPickerModal.ts:45", + "desc": "Paint the icon so only the GM sees it.", + "pick": "keep", + "why": "GM-only icons are what the GM layer is for; part of running a game.", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Icons" + }, + { + "id": "IconPicker.manageIcons", + "surface": "Icon picker modal", + "label": "Manage icons / ← pick icons", + "kind": "button", + "level": "mode: build/god", + "loc": "src/hex-map/IconPickerModal.ts:57", + "desc": "Switch to hiding, reordering and uploading icons.", + "pick": "simple", + "why": "Hiding, reordering and uploading icons is ordinary look-and-feel customization. Owner (pass 3): \"a streamlined but still customizable experience for simple, not to hide every little possible scary thing.\"", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Icons", + "prevPick": "advanced" + }, + { + "id": "IconPicker.remove", + "surface": "Icon picker modal", + "label": "Remove", + "kind": "button", + "level": "mode: build/god", + "loc": "src/hex-map/IconPickerModal.ts:79", + "desc": "Paint 'no icon' (erase).", + "pick": "keep", + "why": "Eraser", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Icons" + }, + { + "id": "IconPicker.grid", + "surface": "Icon picker modal", + "label": "(icon tiles)", + "kind": "picker", + "level": "mode: build/god", + "loc": "src/hex-map/IconPickerModal.ts:89", + "desc": "Choose the icon to paint on hexes.", + "pick": "keep", + "why": "The point of the form", + "lists": "plugin.availableIcons minus hiddenIcons: bundled terrain + places + space (if space kind on) + custom folder images", + "focused": true, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Icons" + }, + { + "id": "IconPicker.packTabs", + "surface": "Icon picker modal", + "label": "All / Terrain / Places / Space / Custom", + "kind": "button", + "level": "mode: build/god", + "loc": "src/HexmakerModal.ts:109", + "desc": "Narrow the grid to one icon pack.", + "pick": "keep", + "why": "Scales the picker", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Icons" + }, + { + "id": "IconPicker.hideToggle", + "surface": "Icon picker modal", + "label": "eye / eye-off", + "kind": "button", + "level": "conditional: manage mode", + "loc": "src/hex-map/IconPickerModal.ts:138", + "desc": "Hide or show an icon in every picker.", + "pick": "keep", + "why": "Only inside Manage icons; gating that mode covers it.", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Icons" + }, + { + "id": "IconPicker.dragReorder", + "surface": "Icon picker modal", + "label": "⠿ (drag to reorder)", + "kind": "button", + "level": "conditional: manage mode", + "loc": "src/hex-map/IconPickerModal.ts:157", + "desc": "Drag icons to set their order.", + "pick": "keep", + "why": "Only inside Manage icons; gating that mode covers it.", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Icons" + }, + { + "id": "IconPicker.uploadDropZone", + "surface": "Icon picker modal", + "label": "Drag & drop images here, or click to browse", + "kind": "button", + "level": "conditional: manage mode, icons folder set", + "loc": "src/hex-map/IconPickerModal.ts:204", + "desc": "Upload your own icon images.", + "pick": "keep", + "why": "Only inside Manage icons; gating that mode covers it.", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Icons" + }, + { + "id": "IconPicker.closeButtons", + "surface": "Icon picker modal", + "label": "×", + "kind": "button", + "level": "mode: build/god", + "loc": "src/hex-map/IconPickerModal.ts:29", + "desc": "Close.", + "pick": "keep", + "why": "Standard", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Icons" + }, + { + "id": "Token.notePicker", + "surface": "Token modal", + "label": "Note", + "kind": "picker", + "level": "conditional: new token only", + "loc": "src/hex-map/TokenModal.ts:94", + "desc": "Search for a note to link the token to, or type a name to make one.", + "pick": "keep", + "why": "Core, but the list must be focused on characters/places, not world plumbing", + "lists": "up to 50 .md under worldFolder (whole tree) + towns/dungeons/features/quests/factions/regions folders, minus tables, workflows, hexes, export, icons, palettes, generators, templates, _ notes (TokenModal.ts:379-402)", + "focused": false, + "mix": "biome notes (world/biomes), biome-pool notes (world/biome-pools), world-type notes (world/world-types), region notes, factions, quests, features, loose world/ notes", + "group": "Map pickers & editors", + "subgroup": "Tokens" + }, + { + "id": "Token.noteStatus", + "surface": "Token modal", + "label": "Links to … / Creates a new note: …", + "kind": "text", + "level": "conditional: new token only", + "loc": "src/hex-map/TokenModal.ts:115", + "desc": "Says whether Save will link an existing note or create a new one.", + "pick": "keep", + "why": "Prevents silent wrong-note links; cheap one-liner", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Tokens" + }, + { + "id": "Token.iconPackTabs", + "surface": "Token modal", + "label": "All / Terrain / Places / Space / Custom", + "kind": "button", + "level": "always", + "loc": "src/HexmakerModal.ts:109", + "desc": "Tabs that narrow the icon grid to one icon pack.", + "pick": "keep", + "why": "Scales the big icon list; Terrain/Space tabs are noise for a token though", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Tokens" + }, + { + "id": "Token.iconGrid", + "surface": "Token modal", + "label": "Icon", + "kind": "picker", + "level": "always", + "loc": "src/hex-map/TokenModal.ts:199", + "desc": "Pick the picture shown on the token.", + "pick": "simple", + "why": "Token basics: what the token looks like.", + "lists": "'no icon' + plugin.availableIcons minus settings.hiddenIcons (bundled terrain, places, space if enabled, custom folder) (TokenModal.ts:196-229)", + "focused": true, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Tokens" + }, + { + "id": "Token.shape", + "surface": "Token modal", + "label": "Shape", + "kind": "dropdown", + "level": "always", + "loc": "src/hex-map/TokenModal.ts:233", + "desc": "Circle, square or hexagon token.", + "pick": "simple", + "why": "Token look is ordinary customization. Owner (pass 3): \"a streamlined but still customizable experience for simple, not to hide every little possible scary thing.\"", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Tokens", + "prevPick": "advanced" + }, + { + "id": "Token.size", + "surface": "Token modal", + "label": "Size", + "kind": "radio", + "level": "always", + "loc": "src/hex-map/TokenModal.ts:244", + "desc": "Small, medium or large token.", + "pick": "simple", + "why": "Token basics: tells a party from a dragon.", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Tokens" + }, + { + "id": "Token.fillColor", + "surface": "Token modal", + "label": "Fill color", + "kind": "color", + "level": "always", + "loc": "src/hex-map/TokenModal.ts:262", + "desc": "Background color behind the icon.", + "pick": "simple", + "why": "Token basics: tells tokens apart.", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Tokens" + }, + { + "id": "Token.borderToggle", + "surface": "Token modal", + "label": "Border color (on/off)", + "kind": "toggle", + "level": "always", + "loc": "src/hex-map/TokenModal.ts:284", + "desc": "Turn a colored ring around the token on or off.", + "pick": "simple", + "why": "Token look is ordinary customization. Owner (pass 3): \"a streamlined but still customizable experience for simple, not to hide every little possible scary thing.\"", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Tokens", + "prevPick": "advanced" + }, + { + "id": "Token.borderColor", + "surface": "Token modal", + "label": "Border color", + "kind": "color", + "level": "always", + "loc": "src/hex-map/TokenModal.ts:292", + "desc": "Pick the ring color.", + "pick": "simple", + "why": "Token look is ordinary customization. Owner (pass 3): \"a streamlined but still customizable experience for simple, not to hide every little possible scary thing.\"", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Tokens", + "prevPick": "advanced" + }, + { + "id": "Token.description", + "surface": "Token modal", + "label": "Description", + "kind": "textarea", + "level": "always", + "loc": "src/hex-map/TokenModal.ts:315", + "desc": "Short text saved in the note's frontmatter, shown in token info.", + "pick": "advanced", + "why": "A real token field, but the linked note already holds text; more than a newcomer needs.", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Tokens" + }, + { + "id": "Token.removeButton", + "surface": "Token modal", + "label": "Remove token", + "kind": "button", + "level": "conditional: edit mode", + "loc": "src/hex-map/TokenModal.ts:333", + "desc": "Take this token off the map (the note stays).", + "pick": "keep", + "why": "Obvious action when editing", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Tokens" + }, + { + "id": "Token.saveButton", + "surface": "Token modal", + "label": "Next: place on map / Save", + "kind": "button", + "level": "always", + "loc": "src/hex-map/TokenModal.ts:340", + "desc": "Save the token (new: then click a hex to place it).", + "pick": "simple", + "why": "Token basics: the form does nothing without it.", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Tokens" + }, + { + "id": "Token.closeButtons", + "surface": "Token modal", + "label": "Cancel", + "kind": "button", + "level": "always", + "loc": "src/hex-map/TokenModal.ts:372", + "desc": "Close without saving.", + "pick": "keep", + "why": "Standard", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Tokens" + }, + { + "id": "TokenInfo.jumpButton", + "surface": "Token info modal", + "label": "⌖", + "kind": "button", + "level": "always", + "loc": "src/hex-map/TokenInfoModal.ts:31", + "desc": "Center the map on the token's hex.", + "pick": "keep", + "why": "Useful in play; unlabeled glyph though", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Tokens" + }, + { + "id": "TokenInfo.openNoteLink", + "surface": "Token info modal", + "label": "Open note", + "kind": "button", + "level": "conditional: note exists", + "loc": "src/hex-map/TokenInfoModal.ts:44", + "desc": "Open the token's note in a tab.", + "pick": "keep", + "why": "Obvious action", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Tokens" + }, + { + "id": "TokenInfo.editButton", + "surface": "Token info modal", + "label": "Edit token", + "kind": "button", + "level": "conditional: edit allowed", + "loc": "src/hex-map/TokenInfoModal.ts:56", + "desc": "Open the token editor.", + "pick": "keep", + "why": "Obvious action", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Tokens" + }, + { + "id": "TokenInfo.noteLinks", + "surface": "Token info modal", + "label": "(links inside the note preview)", + "kind": "button", + "level": "conditional: note has links", + "loc": "src/hex-map/TokenInfoModal.ts:91", + "desc": "Click a link in the note preview to open it in a new tab.", + "pick": "keep", + "why": "Natural reading behaviour", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Tokens" + }, + { + "id": "TokenInfo.removeButton", + "surface": "Token info modal", + "label": "× remove / Confirm remove?", + "kind": "button", + "level": "conditional: remove allowed", + "loc": "src/hex-map/TokenInfoModal.ts:117", + "desc": "Remove the token from the map, with a confirm click.", + "pick": "keep", + "why": "Fine; confirm is good", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Tokens" + }, + { + "id": "TokenInfo.closeButtons", + "surface": "Token info modal", + "label": "×", + "kind": "button", + "level": "always", + "loc": "src/hex-map/TokenInfoModal.ts:20", + "desc": "Close the info box.", + "pick": "keep", + "why": "Standard", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Tokens" + }, + { + "id": "PathName.nameInput", + "surface": "Rename path modal", + "label": "(path name)", + "kind": "text", + "level": "mode: build/god", + "loc": "src/hex-map/PathNameModal.ts:45", + "desc": "Type the path's new name.", + "pick": "keep", + "why": "Single-purpose form; drop the map-note-tables blurb above it", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Path types" + }, + { + "id": "PathName.saveButton", + "surface": "Rename path modal", + "label": "Save", + "kind": "button", + "level": "mode: build/god", + "loc": "src/hex-map/PathNameModal.ts:48", + "desc": "Save the new name (disabled while the name is taken or empty).", + "pick": "keep", + "why": "Primary action", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Path types" + }, + { + "id": "PathName.closeButtons", + "surface": "Rename path modal", + "label": "Cancel", + "kind": "button", + "level": "mode: build/god", + "loc": "src/hex-map/PathNameModal.ts:49", + "desc": "Close without renaming.", + "pick": "keep", + "why": "Standard", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Path types" + }, + { + "id": "PathPicker.editToggle", + "surface": "Path type picker modal", + "label": "✏ Edit / ← Done", + "kind": "button", + "level": "mode: build/god", + "loc": "src/hex-map/PathPickerModal.ts:158", + "desc": "Switch the picker into editing the palette's path types.", + "pick": "simple", + "why": "Editing path types is palette customization, which the owner wants in Simple. Owner (pass 3): \"a streamlined but still customizable experience for simple, not to hide every little possible scary thing.\"", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Path types", + "prevPick": "advanced" + }, + { + "id": "PathPicker.drawMode", + "surface": "Path type picker modal", + "label": "1. How to draw: Hex by hex / Auto-route", + "kind": "radio", + "level": "conditional: path tool", + "loc": "src/hex-map/PathPickerModal.ts:107", + "desc": "Choose drawing hex-by-hex or letting the path find its own way.", + "pick": "simple", + "why": "Hex-by-hex vs auto-route is the basic path choice.", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Path types" + }, + { + "id": "PathPicker.removeTile", + "surface": "Path type picker modal", + "label": "Remove", + "kind": "button", + "level": "conditional: erase allowed", + "loc": "src/hex-map/PathPickerModal.ts:187", + "desc": "Switch to erasing paths.", + "pick": "keep", + "why": "Standard eraser", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Path types" + }, + { + "id": "PathPicker.typeGrid", + "surface": "Path type picker modal", + "label": "2. Pick a path type to start drawing", + "kind": "picker", + "level": "mode: build/god", + "loc": "src/hex-map/PathPickerModal.ts:198", + "desc": "Choose road, river, etc. and start drawing.", + "pick": "simple", + "why": "Picking road or river is the start of every path.", + "lists": "path types of the map's palette (plugin.getPathTypes(paletteName), PathPickerModal.ts:176)", + "focused": true, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Path types" + }, + { + "id": "PathPicker.pathsOnMap", + "surface": "Path type picker modal", + "label": "Paths on this map", + "kind": "picker", + "level": "conditional: path tool", + "loc": "src/hex-map/PathPickerModal.ts:229", + "desc": "List of drawn paths; click one to select it on the map.", + "pick": "advanced", + "why": "A second way to find a path; useful, but beyond basic drawing.", + "lists": "every path on the open map with type swatch, name and summary (pathsOnMap.list)", + "focused": true, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Path types" + }, + { + "id": "PathPicker.editTypeTile", + "surface": "Path type picker modal", + "label": "(type tile, edit mode)", + "kind": "button", + "level": "conditional: edit mode", + "loc": "src/hex-map/PathPickerModal.ts:268", + "desc": "Click a path type to open its editor.", + "pick": "keep", + "why": "Only inside the path type edit mode; gating that toggle covers it.", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Path types" + }, + { + "id": "PathPicker.dragReorder", + "surface": "Path type picker modal", + "label": "⠿ (drag to reorder)", + "kind": "button", + "level": "conditional: edit mode", + "loc": "src/hex-map/PathPickerModal.ts:285", + "desc": "Drag path types to change their order.", + "pick": "keep", + "why": "Only inside the path type edit mode; gating that toggle covers it.", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Path types" + }, + { + "id": "PathPicker.addTypeTile", + "surface": "Path type picker modal", + "label": "+ Add", + "kind": "button", + "level": "conditional: edit mode", + "loc": "src/hex-map/PathPickerModal.ts:315", + "desc": "Add a new path type and open its editor.", + "pick": "keep", + "why": "Only inside the path type edit mode; gating that toggle covers it.", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Path types" + }, + { + "id": "PathPicker.closeButtons", + "surface": "Path type picker modal", + "label": "×", + "kind": "button", + "level": "mode: build/god", + "loc": "src/hex-map/PathPickerModal.ts:133", + "desc": "Close the picker (leaves the path tool if nothing picked).", + "pick": "keep", + "why": "Standard", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Path types" + }, + { + "id": "PathType.name", + "surface": "Path type editor modal", + "label": "Name", + "kind": "text", + "level": "conditional: editing a path type", + "loc": "src/hex-map/PathTypeEditorModal.ts:78", + "desc": "Name of this path type.", + "pick": "keep", + "why": "Basic identity", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Path types" + }, + { + "id": "PathType.color", + "surface": "Path type editor modal", + "label": "Color", + "kind": "color", + "level": "conditional: editing a path type", + "loc": "src/hex-map/PathTypeEditorModal.ts:88", + "desc": "Line color.", + "pick": "keep", + "why": "Basic look", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Path types" + }, + { + "id": "PathType.width", + "surface": "Path type editor modal", + "label": "Width", + "kind": "slider", + "level": "conditional: editing a path type", + "loc": "src/hex-map/PathTypeEditorModal.ts:99", + "desc": "Line thickness, 1-10.", + "pick": "keep", + "why": "Basic look; preview shows it", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Path types" + }, + { + "id": "PathType.lineStyle", + "surface": "Path type editor modal", + "label": "Line style", + "kind": "dropdown", + "level": "conditional: editing a path type", + "loc": "src/hex-map/PathTypeEditorModal.ts:111", + "desc": "Solid, dashed or dotted line.", + "pick": "keep", + "why": "Basic look (roads vs trails)", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Path types" + }, + { + "id": "PathType.routing", + "surface": "Path type editor modal", + "label": "Routing", + "kind": "dropdown", + "level": "conditional: editing a path type", + "loc": "src/hex-map/PathTypeEditorModal.ts:125", + "desc": "Whether the line runs through hex centres, edge middles or along borders.", + "pick": "keep", + "why": "Path types are Advanced and this editor is only reached through them; a visible line choice.", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Path types" + }, + { + "id": "PathType.avoidImpassable", + "surface": "Path type editor modal", + "label": "Avoid impassable terrain", + "kind": "toggle", + "level": "conditional: editing a path type", + "loc": "src/hex-map/PathTypeEditorModal.ts:140", + "desc": "Auto-route goes around water/impassable terrain.", + "pick": "keep", + "why": "Path types are Advanced and this editor is only reached through them; a real path option.", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Path types" + }, + { + "id": "PathType.autoRoute", + "surface": "Path type editor modal", + "label": "Auto-route", + "kind": "dropdown", + "level": "conditional: editing a path type", + "loc": "src/hex-map/PathTypeEditorModal.ts:149", + "desc": "Direct or winding auto-routed paths.", + "pick": "keep", + "why": "Path types are Advanced and this editor is only reached through them; a visible style choice.", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Path types" + }, + { + "id": "PathType.carves", + "surface": "Path type editor modal", + "label": "Carves terrain", + "kind": "text", + "level": "conditional: editing a path type", + "loc": "src/hex-map/PathTypeEditorModal.ts:163", + "desc": "Terrain the path stamps into regions when confirmed (free text).", + "pick": "advanced", + "why": "Overworld-only path option; belongs with the regions feature.", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Path types" + }, + { + "id": "PathType.carveWidth", + "surface": "Path type editor modal", + "label": "Carve width", + "kind": "dropdown", + "level": "conditional: editing a path type", + "loc": "src/hex-map/PathTypeEditorModal.ts:173", + "desc": "Carve only the path hexes (0) or their neighbours too (1).", + "pick": "overkill", + "why": "A 0/1 numeric internal for carving; nobody needs it to draw paths.", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Path types" + }, + { + "id": "PathType.saveButton", + "surface": "Path type editor modal", + "label": "Save", + "kind": "button", + "level": "conditional: editing a path type", + "loc": "src/hex-map/PathTypeEditorModal.ts:185", + "desc": "Save the path type.", + "pick": "keep", + "why": "Primary action (closing also autosaves)", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Path types" + }, + { + "id": "PathType.deleteButton", + "surface": "Path type editor modal", + "label": "Delete", + "kind": "button", + "level": "conditional: editing a path type", + "loc": "src/hex-map/PathTypeEditorModal.ts:194", + "desc": "Delete this path type (asks first; removes its paths).", + "pick": "keep", + "why": "Needed, has confirm", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Path types" + }, + { + "id": "PathType.deleteConfirm", + "surface": "Path type editor modal", + "label": "Yes, delete / Cancel", + "kind": "button", + "level": "conditional: after Delete", + "loc": "src/hex-map/PathTypeEditorModal.ts:212", + "desc": "Confirm or cancel deleting the type.", + "pick": "keep", + "why": "Safety confirm", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Path types" + }, + { + "id": "PathType.closeButtons", + "surface": "Path type editor modal", + "label": "×", + "kind": "button", + "level": "conditional: editing a path type", + "loc": "src/hex-map/PathTypeEditorModal.ts:225", + "desc": "Close (changes are autosaved).", + "pick": "keep", + "why": "Standard", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Path types" + }, + { + "id": "GotoHex.xInput", + "surface": "Go to hex modal", + "label": "X:", + "kind": "number", + "level": "always", + "loc": "src/hex-map/GotoHexModal.ts:21", + "desc": "Column of the hex to jump to.", + "pick": "keep", + "why": "Single-purpose and small", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Go to hex & help" + }, + { + "id": "GotoHex.yInput", + "surface": "Go to hex modal", + "label": "Y:", + "kind": "number", + "level": "always", + "loc": "src/hex-map/GotoHexModal.ts:26", + "desc": "Row of the hex to jump to.", + "pick": "keep", + "why": "Single-purpose and small", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Go to hex & help" + }, + { + "id": "GotoHex.goButton", + "surface": "Go to hex modal", + "label": "Go", + "kind": "button", + "level": "always", + "loc": "src/hex-map/GotoHexModal.ts:40", + "desc": "Center the map on that hex.", + "pick": "keep", + "why": "Primary action", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Go to hex & help" + }, + { + "id": "GotoHex.closeButtons", + "surface": "Go to hex modal", + "label": "×", + "kind": "button", + "level": "always", + "loc": "src/hex-map/GotoHexModal.ts:14", + "desc": "Close.", + "pick": "keep", + "why": "Standard", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Go to hex & help" + }, + { + "id": "HexHelp.closeButtons", + "surface": "Hex map help modal", + "label": "×", + "kind": "button", + "level": "always", + "loc": "src/hex-map/HexHelpModal.ts:10", + "desc": "Close the controls & tools help.", + "pick": "keep", + "why": "Read-only help; no inputs", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Go to hex & help" + }, + { + "id": "Locations.search", + "surface": "Locations modal", + "label": "Find a location…", + "kind": "search", + "level": "conditional: hex has locations", + "loc": "src/hex-map/LocationsModal.ts:45", + "desc": "Filter this hex's linked maps by name.", + "pick": "keep", + "why": "Only opened when a hex has many locations", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Locations" + }, + { + "id": "Locations.list", + "surface": "Locations modal", + "label": "(location name)", + "kind": "picker", + "level": "conditional: hex has locations", + "loc": "src/hex-map/LocationsModal.ts:111", + "desc": "Click a location to open its map.", + "pick": "keep", + "why": "The point of the form", + "lists": "maps linked to this hex (mapStore.get(map,x_y).locations, LocationsModal.ts:38)", + "focused": true, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Locations" + }, + { + "id": "Locations.openButton", + "surface": "Locations modal", + "label": "Open", + "kind": "button", + "level": "conditional: hex has locations", + "loc": "src/hex-map/LocationsModal.ts:118", + "desc": "Open that location's map.", + "pick": "drop", + "why": "Same row already opens the map when you click its name; the name replaces it.", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Locations" + }, + { + "id": "Locations.unlink", + "surface": "Locations modal", + "label": "✕", + "kind": "button", + "level": "mode: build/god", + "loc": "src/hex-map/LocationsModal.ts:122", + "desc": "Unlink the map from this hex (map is kept).", + "pick": "keep", + "why": "Needed management action", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Locations" + }, + { + "id": "Locations.dragReorder", + "surface": "Locations modal", + "label": "⋮⋮ (drag)", + "kind": "button", + "level": "mode: build/god", + "loc": "src/hex-map/LocationsModal.ts:89", + "desc": "Drag to reorder this hex's locations.", + "pick": "keep", + "why": "Normal housekeeping, only in build mode with several locations.", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Locations" + }, + { + "id": "Locations.newLocation", + "surface": "Locations modal", + "label": "New location…", + "kind": "button", + "level": "mode: build/god", + "loc": "src/hex-map/LocationsModal.ts:62", + "desc": "Make a new map for this hex.", + "pick": "keep", + "why": "Primary create action", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Locations" + }, + { + "id": "Locations.linkExisting", + "surface": "Locations modal", + "label": "Link existing map…", + "kind": "button", + "level": "mode: build/god", + "loc": "src/hex-map/LocationsModal.ts:66", + "desc": "Link a map you already have to this hex.", + "pick": "keep", + "why": "Common action", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Locations" + }, + { + "id": "Locations.closeButtons", + "surface": "Locations modal", + "label": "×", + "kind": "button", + "level": "conditional: hex has locations", + "loc": "src/hex-map/LocationsModal.ts:42", + "desc": "Close.", + "pick": "keep", + "why": "Standard", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Locations" + }, + { + "id": "FactionPicker.grid", + "surface": "Faction picker modal", + "label": "(faction tiles)", + "kind": "picker", + "level": "always", + "loc": "src/hex-map/FactionPickerModal.ts:207", + "desc": "Pick a faction to paint onto hexes.", + "pick": "keep", + "why": "The point of the form; dead-ends when factions folder is blank (default)", + "lists": ".md anywhere under factionsFolder (incl. subfolders), linkable (no _ / templates), sorted (FactionPickerModal.ts:180-183)", + "focused": true, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Factions" + }, + { + "id": "FactionPicker.removeTile", + "surface": "Faction picker modal", + "label": "Remove", + "kind": "button", + "level": "conditional: erase allowed", + "loc": "src/hex-map/FactionPickerModal.ts:193", + "desc": "Switch to erasing factions from hexes.", + "pick": "keep", + "why": "Standard eraser", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Factions" + }, + { + "id": "FactionPicker.editTile", + "surface": "Faction picker modal", + "label": "✏", + "kind": "button", + "level": "always", + "loc": "src/hex-map/FactionPickerModal.ts:221", + "desc": "Edit the faction's name, color and pattern.", + "pick": "keep", + "why": "Hover-only pencil; fine", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Factions" + }, + { + "id": "FactionPicker.newName", + "surface": "Faction picker modal", + "label": "New faction name…", + "kind": "text", + "level": "always", + "loc": "src/hex-map/FactionPickerModal.ts:270", + "desc": "Type a name for a new faction.", + "pick": "keep", + "why": "Quick create", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Factions" + }, + { + "id": "FactionPicker.createButton", + "surface": "Faction picker modal", + "label": "Create", + "kind": "button", + "level": "always", + "loc": "src/hex-map/FactionPickerModal.ts:274", + "desc": "Create the faction note and open its editor.", + "pick": "keep", + "why": "Quick create", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Factions" + }, + { + "id": "FactionPicker.closeButtons", + "surface": "Faction picker modal", + "label": "×", + "kind": "button", + "level": "always", + "loc": "src/hex-map/FactionPickerModal.ts:300", + "desc": "Close.", + "pick": "keep", + "why": "Standard", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Factions" + }, + { + "id": "FactionEditor.openNote", + "surface": "Faction editor modal", + "label": "Open note →", + "kind": "button", + "level": "always", + "loc": "src/hex-map/FactionPickerModal.ts:46", + "desc": "Open the faction's note.", + "pick": "keep", + "why": "Obvious action", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Factions" + }, + { + "id": "FactionEditor.name", + "surface": "Faction editor modal", + "label": "Name", + "kind": "text", + "level": "always", + "loc": "src/hex-map/FactionPickerModal.ts:74", + "desc": "Rename the faction (renames the note).", + "pick": "keep", + "why": "Basic", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Factions" + }, + { + "id": "FactionEditor.color", + "surface": "Faction editor modal", + "label": "Color", + "kind": "color", + "level": "always", + "loc": "src/hex-map/FactionPickerModal.ts:81", + "desc": "Faction overlay color on the map.", + "pick": "keep", + "why": "Basic look", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Factions" + }, + { + "id": "FactionEditor.pattern", + "surface": "Faction editor modal", + "label": "Pattern", + "kind": "dropdown", + "level": "always", + "loc": "src/hex-map/overlayPatternControls.ts:139", + "desc": "Fill pattern for the overlay (stripes, dots…; 10 options).", + "pick": "simple", + "why": "Faction look is ordinary customization. Owner (pass 3): \"a streamlined but still customizable experience for simple, not to hide every little possible scary thing.\"", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Factions", + "prevPick": "advanced" + }, + { + "id": "FactionEditor.patternScale", + "surface": "Faction editor modal", + "label": "Pattern scale", + "kind": "slider", + "level": "always", + "loc": "src/hex-map/overlayPatternControls.ts:149", + "desc": "Size of the pattern.", + "pick": "simple", + "why": "Faction look is ordinary customization. Owner (pass 3): \"a streamlined but still customizable experience for simple, not to hide every little possible scary thing.\"", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Factions", + "prevPick": "advanced" + }, + { + "id": "FactionEditor.opacity", + "surface": "Faction editor modal", + "label": "Opacity", + "kind": "slider", + "level": "always", + "loc": "src/hex-map/overlayPatternControls.ts:159", + "desc": "How see-through the overlay is.", + "pick": "simple", + "why": "Faction look is ordinary customization. Owner (pass 3): \"a streamlined but still customizable experience for simple, not to hide every little possible scary thing.\"", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Factions", + "prevPick": "advanced" + }, + { + "id": "FactionEditor.outlineWidth", + "surface": "Faction editor modal", + "label": "Outline width", + "kind": "slider", + "level": "always", + "loc": "src/hex-map/overlayPatternControls.ts:169", + "desc": "Thickness of the faction border.", + "pick": "simple", + "why": "Faction look is ordinary customization. Owner (pass 3): \"a streamlined but still customizable experience for simple, not to hide every little possible scary thing.\"", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Factions", + "prevPick": "advanced" + }, + { + "id": "FactionEditor.save", + "surface": "Faction editor modal", + "label": "Save", + "kind": "button", + "level": "always", + "loc": "src/hex-map/FactionPickerModal.ts:102", + "desc": "Save name, color and style.", + "pick": "keep", + "why": "Primary action", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Factions" + }, + { + "id": "FactionEditor.clearColor", + "surface": "Faction editor modal", + "label": "Clear color", + "kind": "button", + "level": "conditional: faction has a color", + "loc": "src/hex-map/FactionPickerModal.ts:126", + "desc": "Remove the faction's color and close.", + "pick": "simple", + "why": "Pairs with the faction colour, which is Simple. Owner (pass 3): \"a streamlined but still customizable experience for simple, not to hide every little possible scary thing.\"", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Factions", + "prevPick": "advanced" + }, + { + "id": "FactionEditor.closeButtons", + "surface": "Faction editor modal", + "label": "×", + "kind": "button", + "level": "always", + "loc": "src/hex-map/FactionPickerModal.ts:36", + "desc": "Close without saving.", + "pick": "keep", + "why": "Standard", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Factions" + }, + { + "id": "TerrainPicker.editToggle", + "surface": "Terrain picker modal", + "label": "✏ Edit / ← Done", + "kind": "button", + "level": "mode: build/god", + "loc": "src/hex-map/TerrainPickerModal.ts:52", + "desc": "Switch the paint picker into editing the palette.", + "pick": "simple", + "why": "Editing the palette from the paint picker is ordinary palette customization, which the owner wants in Simple. Owner (pass 3): \"a streamlined but still customizable experience for simple, not to hide every little possible scary thing.\"", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Terrain", + "prevPick": "advanced" + }, + { + "id": "TerrainPicker.fullEditor", + "surface": "Terrain picker modal", + "label": "Full editor…", + "kind": "button", + "level": "conditional: edit mode", + "loc": "src/hex-map/TerrainPickerModal.ts:63", + "desc": "Open the full palette editor.", + "pick": "keep", + "why": "Only inside the palette edit mode; gating that toggle covers it.", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Terrain" + }, + { + "id": "TerrainPicker.brushSize", + "surface": "Terrain picker modal", + "label": "Brush: 1× 3× 7×", + "kind": "radio", + "level": "mode: build/god", + "loc": "src/hex-map/TerrainPickerModal.ts:83", + "desc": "How many hexes one click paints.", + "pick": "keep", + "why": "Speeds up painting; small", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Terrain" + }, + { + "id": "TerrainPicker.eyedropper", + "surface": "Terrain picker modal", + "label": "⌖ Pick", + "kind": "button", + "level": "mode: build/god", + "loc": "src/hex-map/TerrainPickerModal.ts:104", + "desc": "Pick a terrain by clicking a hex on the map.", + "pick": "keep", + "why": "Handy and small", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Terrain" + }, + { + "id": "TerrainPicker.clear", + "surface": "Terrain picker modal", + "label": "Clear", + "kind": "button", + "level": "mode: build/god", + "loc": "src/hex-map/TerrainPickerModal.ts:119", + "desc": "Paint hexes back to no terrain.", + "pick": "keep", + "why": "Eraser", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Terrain" + }, + { + "id": "TerrainPicker.grid", + "surface": "Terrain picker modal", + "label": "(terrain tiles)", + "kind": "picker", + "level": "mode: build/god", + "loc": "src/hex-map/TerrainPickerModal.ts:132", + "desc": "Choose the terrain to paint.", + "pick": "keep", + "why": "The point of the form", + "lists": "terrains of the map's palette (or the region's palette on an overworld) (HexMapView.ts:2246)", + "focused": true, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Terrain" + }, + { + "id": "TerrainPicker.editTile", + "surface": "Terrain picker modal", + "label": "(terrain tile, edit mode)", + "kind": "button", + "level": "conditional: edit mode", + "loc": "src/hex-map/TerrainPickerModal.ts:175", + "desc": "Click a terrain to edit it.", + "pick": "keep", + "why": "Only inside the palette edit mode; gating that toggle covers it.", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Terrain" + }, + { + "id": "TerrainPicker.dragReorder", + "surface": "Terrain picker modal", + "label": "⠿ (drag to reorder)", + "kind": "button", + "level": "conditional: edit mode", + "loc": "src/hex-map/TerrainPickerModal.ts:198", + "desc": "Drag terrains to reorder the palette.", + "pick": "keep", + "why": "Only inside the palette edit mode; gating that toggle covers it.", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Terrain" + }, + { + "id": "TerrainPicker.addTile", + "surface": "Terrain picker modal", + "label": "+ Add", + "kind": "button", + "level": "conditional: edit mode", + "loc": "src/hex-map/TerrainPickerModal.ts:232", + "desc": "Add a terrain (blank or copied from another palette).", + "pick": "keep", + "why": "Only inside the palette edit mode; gating that toggle covers it.", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Terrain" + }, + { + "id": "TerrainPicker.refreshEncounterLinks", + "surface": "Terrain picker modal", + "label": "Refresh all encounter table links", + "kind": "button", + "level": "conditional: edit mode", + "loc": "src/hex-map/TerrainPickerModal.ts:275", + "desc": "Re-link every hex's encounter table to its terrain.", + "pick": "overkill", + "why": "Maintenance button that re-links tables; should run on its own.", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Terrain" + }, + { + "id": "TerrainPicker.closeButtons", + "surface": "Terrain picker modal", + "label": "×", + "kind": "button", + "level": "mode: build/god", + "loc": "src/hex-map/TerrainPickerModal.ts:33", + "desc": "Close (leaves the tool if nothing picked).", + "pick": "keep", + "why": "Standard", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Terrain" + }, + { + "id": "TerrainTemplate.newBlank", + "surface": "Add terrain (template) modal", + "label": "New blank", + "kind": "button", + "level": "conditional: edit mode → Add", + "loc": "src/hex-map/TerrainPickerModal.ts:309", + "desc": "Add an empty terrain.", + "pick": "keep", + "why": "Only inside palette edit mode → Add; gating that toggle covers it.", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Terrain" + }, + { + "id": "TerrainTemplate.copyList", + "surface": "Add terrain (template) modal", + "label": "Or copy from an existing palette:", + "kind": "picker", + "level": "conditional: edit mode → Add", + "loc": "src/hex-map/TerrainPickerModal.ts:329", + "desc": "Copy a terrain from another palette.", + "pick": "keep", + "why": "Only inside palette edit mode → Add; gating that toggle covers it.", + "lists": "terrains of every other palette not already in this one, grouped by palette name (TerrainPickerModal.ts:316-322)", + "focused": true, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Terrain" + }, + { + "id": "TerrainTemplate.closeButtons", + "surface": "Add terrain (template) modal", + "label": "×", + "kind": "button", + "level": "conditional: edit mode → Add", + "loc": "src/hex-map/TerrainPickerModal.ts:345", + "desc": "Close without adding.", + "pick": "keep", + "why": "Standard", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Terrain" + }, + { + "id": "TerrainEntry.name", + "surface": "Terrain entry editor modal", + "label": "Name", + "kind": "text", + "level": "conditional: editing a terrain", + "loc": "src/hex-map/TerrainEntryEditorModal.ts:57", + "desc": "Terrain name (renames it on every hex).", + "pick": "keep", + "why": "Basic", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Terrain" + }, + { + "id": "TerrainEntry.type", + "surface": "Terrain entry editor modal", + "label": "Type", + "kind": "dropdown", + "level": "conditional: editing a terrain", + "loc": "src/hex-map/TerrainEntryEditorModal.ts:73", + "desc": "What kind of terrain it is (forest, water…) for generators.", + "pick": "keep", + "why": "Only in the terrain editor (palette editing, Advanced); generators and biomes need it.", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Terrain" + }, + { + "id": "TerrainEntry.impassable", + "surface": "Terrain entry editor modal", + "label": "Impassable", + "kind": "toggle", + "level": "conditional: editing a terrain", + "loc": "src/hex-map/TerrainEntryEditorModal.ts:85", + "desc": "Auto-routed paths go around this terrain.", + "pick": "keep", + "why": "Only in the terrain editor (palette editing, Advanced); a real terrain option.", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Terrain" + }, + { + "id": "TerrainEntry.color", + "surface": "Terrain entry editor modal", + "label": "Color", + "kind": "color", + "level": "conditional: editing a terrain", + "loc": "src/hex-map/TerrainEntryEditorModal.ts:94", + "desc": "Hex fill color.", + "pick": "keep", + "why": "Basic look", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Terrain" + }, + { + "id": "TerrainEntry.icon", + "surface": "Terrain entry editor modal", + "label": "Icon", + "kind": "dropdown", + "level": "conditional: editing a terrain", + "loc": "src/hex-map/TerrainEntryEditorModal.ts:102", + "desc": "Icon drawn on hexes of this terrain.", + "pick": "keep", + "why": "Basic look, but a huge with the installed palettes, then any built-in + * presets not installed yet (labelled "(preset)"). Picking a preset is + * enough: createNewMap() installs it on first use. With no `selected`, + * the default for the enabled map types is picked (defaultPaletteFor). + */ +export function fillPaletteSelect( + plugin: HexmakerPlugin, + select: HTMLSelectElement, + selected?: string, +): void { + select.empty(); + const installed = new Set(plugin.settings.terrainPalettes.map((p) => p.name)); + // Installed palettes of a map type that's off are hidden too (space ones + // while Space is off, fantasy ones in a space-only setup) — unless + // selected, so a map or saved default using one still shows it. + for (const pal of plugin.settings.terrainPalettes) { + if (pal.name !== selected && !isKindEnabled(plugin.settings, paletteKind(pal))) continue; + const hint = paletteHint(pal.name); + select.createEl("option", { value: pal.name, text: pal.name, ...(hint ? { attr: { title: hint } } : {}) }); + } + // Presets of disabled map types are hidden — unless already selected (e.g. + // a saved submap default), so the dropdown can still show it. + const presets = PALETTE_PRESETS.filter( + (p) => !installed.has(p.name) && (isKindEnabled(plugin.settings, p.kind) || p.name === selected), + ); + if (presets.length > 0) { + const group = select.createEl("optgroup", { attr: { label: "Presets" } }); + for (const p of presets) { + group.createEl("option", { value: p.name, text: `${p.name} (preset)`, attr: { title: p.description } }); + } + } + if (selected) { + select.value = selected; + } else { + const fallback = defaultPaletteFor(plugin.settings); + if (Array.from(select.options).some((o) => o.value === fallback)) select.value = fallback; + } + hintUpdaters.get(select)?.(); +} + +/** + * A palette was renamed: repoint everything that names it (maps, the + * "Palette for new maps" setting, other palettes' child palette and + * Submap defaults), so a rename never silently drops a reference. + */ +export function repointPaletteName( + settings: { + maps: { paletteName: string }[]; + defaultPalette?: string; + terrainPalettes: { childPalette?: string; submapDefaults?: Record }[]; + }, + oldName: string, + newName: string, +): void { + if (oldName === newName) return; + for (const m of settings.maps) if (m.paletteName === oldName) m.paletteName = newName; + if (settings.defaultPalette === oldName) settings.defaultPalette = newName; + for (const p of settings.terrainPalettes) { + if (p.childPalette === oldName) p.childPalette = newName; + for (const row of Object.values(p.submapDefaults ?? {})) if (row.palette === oldName) row.palette = newName; + } +} diff --git a/src/palettes/paletteReadingView.ts b/src/palettes/paletteReadingView.ts new file mode 100644 index 00000000..b33d275b --- /dev/null +++ b/src/palettes/paletteReadingView.ts @@ -0,0 +1,122 @@ +import type { MarkdownPostProcessorContext } from "obsidian"; +import type HexmakerPlugin from "../HexmakerPlugin"; +import type { PathType } from "../types"; +import { buildPathPreviewSvg } from "../hex-map/pathPreviewSvg"; +import { createIconEl, getIconUrl } from "../utils"; +import { parsePaletteNote, PALETTE_NOTE_MARKER } from "./paletteNote"; +import { parsePathTypes } from "./pathTypeTable"; + +// Reading view for palette notes: a colour swatch beside each Color cell, an +// icon thumbnail beside each Icon cell, and a line-style preview in the Path +// types table. Display only: the note's text is never changed, and the +// tables are read with the same parsers the plugin uses, so what's drawn is +// what the plugin takes from the note. + +/** A table as plain text, rebuilt as markdown so the note parsers can read it. */ +export function tableMarkdown(headers: string[], rows: string[][]): string { + const esc = (c: string) => c.replace(/\|/g, "\\|").replace(/\r?\n/g, " "); + return [ + `| ${headers.map(esc).join(" | ")} |`, + `| ${headers.map(() => "---").join(" | ")} |`, + ...rows.map((r) => `| ${r.map(esc).join(" | ")} |`), + ].join("\n"); +} + +export type PaletteTableView = + | { + kind: "terrains"; + color: number; + icon: number; + /** Icon tint per row (by terrain name, lower case). */ + tints: Map; + name: number; + } + | { kind: "paths"; name: number; types: Map } + | null; + +const headerIndex = (headers: string[], re: RegExp) => headers.findIndex((h) => re.test(h.trim())); + +/** + * What a table in a palette note is (the terrain table, the path types + * table, or neither) and where its decorated columns are. + */ +export function classifyPaletteTable(headers: string[], rows: string[][]): PaletteTableView { + const md = tableMarkdown(headers, rows); + const terrains = parsePaletteNote(md); + if (terrains) { + return { + kind: "terrains", + name: headerIndex(headers, /^(terrain|name)$/i), + color: headerIndex(headers, /^colou?r$/i), + icon: headerIndex(headers, /^icon$/i), + tints: new Map(terrains.filter((t) => t.iconColor).map((t) => [t.name.toLowerCase(), t.iconColor!])), + }; + } + const paths = parsePathTypes(md); + if (paths) { + return { + kind: "paths", + name: headerIndex(headers, /^(path|paths|path type|name|type)$/i), + types: new Map(paths.types.map((t) => [t.name, t])), + }; + } + return null; +} + +/** Whether a note (by its frontmatter) is a palette note. */ +export function isPaletteFrontmatter(fm: unknown): boolean { + return !!fm && typeof fm === "object" && PALETTE_NOTE_MARKER in fm; +} + +function decorateTable(plugin: HexmakerPlugin, table: HTMLTableElement): void { + if (table.hasClass("duckmage-palette-table")) return; + const headers = Array.from(table.querySelectorAll("thead th")).map((th) => th.textContent?.trim() ?? ""); + const bodyRows = Array.from(table.querySelectorAll("tbody tr")); + const cellsOf = (tr: Element) => Array.from(tr.querySelectorAll("td")); + const rows = bodyRows.map((tr) => cellsOf(tr).map((td) => td.textContent?.trim() ?? "")); + const view = classifyPaletteTable(headers, rows); + if (!view) return; + table.addClass("duckmage-palette-table"); + bodyRows.forEach((tr, r) => { + const tds = cellsOf(tr); + if (view.kind === "terrains") { + const color = rows[r][view.color]; + const colorCell = tds[view.color]; + // An unreadable colour leaves the swatch empty (the custom property is + // invalid, so the background falls back to transparent). + if (colorCell && color) { + const swatch = colorCell.createSpan({ cls: "duckmage-palette-swatch", attr: { "aria-hidden": "true" } }); + swatch.setCssProps({ "--duckmage-palette-swatch": color }); + colorCell.prepend(swatch); + colorCell.addClass("duckmage-palette-color-cell"); + } + const icon = view.icon >= 0 ? rows[r][view.icon] : ""; + const iconCell = tds[view.icon]; + if (iconCell && icon) { + const holder = iconCell.createSpan({ cls: "duckmage-palette-icon" }); + const tint = view.tints.get((rows[r][view.name] ?? "").toLowerCase()); + createIconEl(holder, getIconUrl(plugin, icon), icon, tint, "duckmage-palette-icon-img"); + iconCell.prepend(holder); + } + } else { + const pt = view.types.get(rows[r][view.name] ?? ""); + const nameCell = tds[view.name]; + if (pt && nameCell) { + const holder = nameCell.createSpan({ cls: "duckmage-palette-path-preview", attr: { "aria-hidden": "true" } }); + holder.appendChild(buildPathPreviewSvg(pt)); + nameCell.prepend(holder); + } + } + }); +} + +/** Register the reading-view decorations for palette notes. */ +export function registerPaletteReadingView(plugin: HexmakerPlugin): void { + plugin.registerMarkdownPostProcessor((el: HTMLElement, ctx: MarkdownPostProcessorContext) => { + const tables = el.querySelectorAll("table"); + if (!tables.length) return; + const fm: unknown = ctx.frontmatter ?? plugin.app.metadataCache.getCache(ctx.sourcePath)?.frontmatter; + if (!isPaletteFrontmatter(fm)) return; + tables.forEach((t) => decorateTable(plugin, t)); + }); +} diff --git a/src/palettes/pathTypeTable.ts b/src/palettes/pathTypeTable.ts new file mode 100644 index 00000000..ff19f73c --- /dev/null +++ b/src/palettes/pathTypeTable.ts @@ -0,0 +1,306 @@ +import type { PathAutoRoute, PathLineStyle, PathRouting, PathType } from "../types"; +import { parseImpassableCell } from "../impassable"; +import { legacyAutoRoute, legacyAvoidsImpassable, legacyRouting } from "../migrations/v1.5-path-types-explicit"; +import { colorCell, readColor, wrapColorCellsInRows, writtenColor } from "./colorCell"; +import { SEPARATOR_ROW, splitRow } from "../md/tableRow"; + +// The "Path types" section of a palette note: the kinds of path (roads, +// rivers, jump routes…) that maps using this palette can draw. +// +// ## Path types +// +// | Path | Color | Width | Style | Routing | Avoid impassable | Auto-route | +// | --- | --- | --- | --- | --- | --- | --- | +// | Road | `#a16207` | 4 | solid | through | yes | direct | +// | River | `#3b82f6` | 3 | solid | meander | no | winding | +// +// Colours are inline code so Obsidian doesn't read them as tags (colorCell.ts). +// +// Every behaviour is a column, written out for every row: nothing follows a +// path type's name (PA5). A blank or missing cell reads as the plain default +// (through, yes, direct) and is written back filled in. Notes from before +// PA5 are read once with the old name rules instead (src/migrations/v1.5-path-types-explicit.ts). +// +// Read forgivingly, since people edit it by hand: columns by name in any +// order (Path or Name, Color or Colour, Style or Line…), values in any case, +// "dashed"/"dash"/"- -" alike, widths clamped to 1–10, a missing column means +// its default. Columns we don't know are kept, row by row, when the table is +// rewritten. Rows we can't use (no name) are reported, not silently lost. + +export const PATH_TYPES_HEADING = "## Path types"; + +export const PATH_TYPES_INTRO = + "Paths maps on this palette can draw. Width is 1 (thin) to 10 (thick). Style is solid, dashed or dotted. " + + "Routing is how the line is drawn: through (a smooth curve through hex centres), meander (a smooth curve " + + "through the middles of the edges between hexes) or edge (straight along the hex borders). Avoid impassable " + + "is yes or no: whether auto-route goes around impassable terrain (no also lets generated submaps run it " + + "through water, like a river). Auto-route is direct (keeps to the straight line) or winding (wanders). " + + "Carves is what an overworld path of this type turns the hexes it crosses into when you confirm it into " + + "its regions: a terrain's name, a terrain type (water), or none. Carve width is 0 (the path's hexes) or 1 " + + "(and the hexes beside them). " + + "To have no path types, delete the rows but keep the header line."; + +const HEADERS = ["Path", "Color", "Width", "Style", "Routing", "Avoid impassable", "Auto-route"] as const; +/** Written when a type carves, or the table already has them (kept compact otherwise). */ +const CARVE_HEADERS = ["Carves", "Carve width"] as const; + +type Column = "name" | "color" | "width" | "style" | "routing" | "avoid" | "autoRoute" | "carves" | "carveWidth"; + +function columnFor(header: string): Column | null { + const h = header.trim().toLowerCase().replace(/\s+/g, " "); + if (/^carves? ?(width|wide|size)$/.test(h)) return "carveWidth"; + if (/^carves?( terrain| into| to)?$/.test(h)) return "carves"; + if (["path", "paths", "path type", "name", "type"].includes(h)) return "name"; + if (h === "color" || h === "colour") return "color"; + if (h === "width" || h === "thickness" || h === "size") return "width"; + if (h === "style" || h === "line" || h === "line style" || h === "linestyle") return "style"; + if (/^auto[\s-]?rout(e|ing)$/.test(h) || h === "route style" || h === "auto") return "autoRoute"; + if (h === "routing" || h === "route" || h === "runs" || h === "drawn" || h === "draw") return "routing"; + if (h.startsWith("avoid")) return "avoid"; + return null; +} + +export interface PathTableSpan { + start: number; + end: number; + headers: string[]; + columns: (Column | null)[]; +} + +/** + * The path-types table: the first table under a "Path types" heading, or + * failing that any table with a Path column and a Width, Style or Routing + * column (so it never matches the terrain table). + */ +export function findPathTypesTable(lines: string[]): PathTableSpan | null { + const tableAt = (i: number): PathTableSpan | null => { + if (!lines[i]?.trim().startsWith("|") || !SEPARATOR_ROW.test(lines[i + 1] ?? "")) return null; + const headers = splitRow(lines[i]); + let end = i + 2; + while (end < lines.length && lines[end].trim().startsWith("|")) end++; + return { start: i, end, headers, columns: headers.map(columnFor) }; + }; + for (let h = 0; h < lines.length; h++) { + if (!/^#{1,6}\s+path\s*types?\s*$/i.test(lines[h].trim())) continue; + for (let i = h + 1; i < lines.length - 1; i++) { + if (/^#{1,6}\s/.test(lines[i])) break; + const span = tableAt(i); + if (span) return span; + } + } + for (let i = 0; i < lines.length - 1; i++) { + const span = tableAt(i); + if (!span) continue; + const c = span.columns; + // The terrain table never has Width, Style or Routing columns. + if (c.includes("name") && (c.includes("width") || c.includes("style") || c.includes("routing"))) return span; + } + return null; +} + +function parseStyle(raw: string | undefined): PathLineStyle { + const v = (raw ?? "").trim().toLowerCase(); + if (/dot|\.\s*\./.test(v)) return "dotted"; + if (/dash|-\s*-/.test(v)) return "dashed"; + return "solid"; +} + +function parseRouting(raw: string | undefined): PathRouting | undefined { + const v = (raw ?? "").trim().toLowerCase(); + if (/meander|curv|wind|river/.test(v)) return "meander"; + if (/edge|border|side/.test(v)) return "edge"; + if (/through|centre|center|straight/.test(v)) return "through"; + return undefined; +} + +function parseAutoRoute(raw: string | undefined): PathAutoRoute | undefined { + const v = (raw ?? "").trim().toLowerCase(); + if (/wind|wand|meander|curv|twist|river/.test(v)) return "winding"; + if (/direct|straight|short|road/.test(v)) return "direct"; + return undefined; +} + +/** A Carves cell: blank, none, no or - → nothing; anything else as typed. */ +function parseCarves(raw: string | undefined): string | undefined { + const v = (raw ?? "").trim(); + if (!v || /^(none|no|nothing|-+|off)$/i.test(v)) return undefined; + return v; +} + +/** A Carve width cell: 1 (or wide) → 1, else 0. */ +function parseCarveWidth(raw: string | undefined): number { + const v = (raw ?? "").trim().toLowerCase(); + return /^(1|wide|one)/.test(v) || Number.parseFloat(v) >= 1 ? 1 : 0; +} + +function parseWidth(raw: string | undefined): number { + const n = Number.parseFloat((raw ?? "").replace(/px$/i, "")); + if (!Number.isFinite(n)) return 3; + return Math.min(10, Math.max(1, Math.round(n))); +} + +export interface ParsedPathTypes { + types: PathType[]; + /** Unknown columns, per path name, kept when the table is rewritten. */ + extra: Map>; + /** Unknown column headers, in the order they appeared. */ + extraHeaders: string[]; + /** Rows that couldn't be read, as typed, for a notice. */ + skipped: string[]; + /** Some behaviour cell was blank or missing (filled with its default), so a rewrite would fill it in. */ + implicit: boolean; +} + +export interface ParsePathTypesOptions { + /** + * Read blank behaviour cells with the old name rules (notes saved before + * PA5, read once while migrating). Otherwise blanks are the plain defaults. + */ + legacy?: boolean; +} + +/** + * The note's path types, or null when it has no path-types table we can + * read (none, or one with no Path/Name column, e.g. a typo in the header): + * callers then keep the types they had rather than lose them all. + */ +export function parsePathTypes(content: string, opts: ParsePathTypesOptions = {}): ParsedPathTypes | null { + const lines = content.replace(/\r\n?/g, "\n").split("\n"); + const span = findPathTypesTable(lines); + if (!span || !span.columns.includes("name")) return null; + const types: PathType[] = []; + const extra = new Map>(); + const extraHeaders = span.headers.filter((_, i) => span.columns[i] === null && span.headers[i] !== ""); + const skipped: string[] = []; + const seen = new Set(); + let implicit = false; + for (let i = span.start + 2; i < span.end; i++) { + const cells = splitRow(lines[i]); + if (cells.every((c) => c === "")) continue; + const row: Partial> = {}; + const own: Record = {}; + span.columns.forEach((col, idx) => { + const v = cells[idx] ?? ""; + if (col) { if (v) row[col] = v; } + else if (span.headers[idx] && v) own[span.headers[idx]] = v; + }); + const name = row.name?.trim(); + if (!name || seen.has(name.toLowerCase())) { + skipped.push(lines[i].trim()); + continue; + } + seen.add(name.toLowerCase()); + const routing = parseRouting(row.routing); + const avoid = parseImpassableCell(row.avoid); + const auto = parseAutoRoute(row.autoRoute); + if (routing === undefined || avoid === undefined || auto === undefined) implicit = true; + const avoidImpassable = avoid ?? (opts.legacy ? legacyAvoidsImpassable(name) : true); + const t: PathType = { + name, + ...readColor(row.color), + width: parseWidth(row.width), + lineStyle: parseStyle(row.style), + routing: routing ?? (opts.legacy ? legacyRouting(name) : "through"), + avoidImpassable, + autoRoute: auto ?? (opts.legacy ? legacyAutoRoute(name, avoidImpassable) : "direct"), + }; + const carves = parseCarves(row.carves); + if (carves) t.carves = carves; + if (parseCarveWidth(row.carveWidth) === 1) t.carveWidth = 1; + types.push(t); + if (Object.keys(own).length) extra.set(name, own); + } + return { types, extra, extraHeaders, skipped, implicit }; +} + +function escapeCell(value: string | undefined): string { + return (value ?? "").replace(/\|/g, "\\|").replace(/\r?\n/g, " ").trim(); +} + +/** The table, keeping unknown columns (after ours) and their cells by path name. */ +export function serializePathTypes( + types: PathType[], + extra?: { headers: string[]; rows: Map> }, + opts: { carveColumns?: boolean } = {}, +): string { + const extraHeaders = extra?.headers ?? []; + const carving = !!opts.carveColumns || types.some((t) => !!t.carves?.trim() || t.carveWidth === 1); + const headers = [...HEADERS, ...(carving ? CARVE_HEADERS : []), ...extraHeaders]; + const lines = [`| ${headers.join(" | ")} |`, `| ${headers.map(() => "---").join(" | ")} |`]; + for (const t of types) { + const own = extra?.rows.get(t.name) ?? {}; + const avoid = t.avoidImpassable === false ? "no" : "yes"; + const carves = t.carves?.trim() || "none"; + const carveCells = carving ? [carves, String(t.carveWidth === 1 ? 1 : 0)] : []; + const cells = [t.name, colorCell(writtenColor(t)), String(t.width), t.lineStyle, t.routing, avoid, t.autoRoute ?? "direct", ...carveCells, ...extraHeaders.map((h) => own[h])]; + lines.push(`| ${cells.map(escapeCell).join(" | ")} |`); + } + return lines.join("\n"); +} + +/** Order-sensitive comparison key (order is the picker's order). */ +export function pathTypesKey(types: PathType[] | undefined): string { + return JSON.stringify((types ?? []).map((t) => [t.name, t.color, t.unreadColor ?? null, t.width, t.lineStyle, t.routing, t.avoidImpassable ?? null, t.autoRoute ?? null, t.carves?.trim() || null, t.carveWidth === 1 ? 1 : 0])); +} + +/** + * Write the path-types table into a palette note, replacing the old one in + * place (unknown columns and the text around it kept) or adding a "Path + * types" section at the end. Unchanged content is returned as is. + */ +export function setPathTypes(content: string, types: PathType[]): string { + const parsed = parsePathTypes(content); + if (parsed && pathTypesKey(parsed.types) === pathTypesKey(types) && !parsed.skipped.length && !parsed.implicit) { + return content; + } + const text = content.replace(/\r\n?/g, "\n"); + const lines = text.split("\n"); + const span = findPathTypesTable(lines); + if (span) { + const carveColumns = span.columns.includes("carves") || span.columns.includes("carveWidth"); + const table = serializePathTypes(types, parsed ? { headers: parsed.extraHeaders, rows: parsed.extra } : undefined, { carveColumns }); + // Whatever we couldn't read stays in the note under the table (as an + // indented block, so it isn't read as a table), so nothing typed is lost. + const unread = parsed ? parsed.skipped : lines.slice(span.start, span.end).map((l) => l.trim()); + const kept = unread.length + ? [ + "", + parsed + ? "Rows the plugin couldn't read (each needs a name):" + : "The path types table as it was (its header needs a Path column):", + "", + ...unread.map((r) => ` ${r}`), + ] + : []; + return [...lines.slice(0, span.start), table, ...kept, ...lines.slice(span.end)].join("\n"); + } + const base = text.endsWith("\n") ? text : text + "\n"; + return `${base}\n${PATH_TYPES_HEADING}\n\n${PATH_TYPES_INTRO}\n\n${serializePathTypes(types)}\n`; +} + +/** + * The note with the path types table's Color cells written as inline code + * (`` `#a16207` ``), so Obsidian doesn't read them as tags. Only those cells + * change: every other character, line endings included, is kept. Unchanged + * (the same string) when they already are. + */ +export function wrapPathTypeColors(content: string): string { + const lines = content.split("\n"); + const span = findPathTypesTable(lines.map((l) => l.replace(/\r$/, ""))); + if (!span || !span.columns.includes("name")) return content; + const cols = span.columns.flatMap((c, i) => (c === "color" ? [i] : [])); + const rows = Array.from({ length: span.end - span.start - 2 }, (_, k) => span.start + 2 + k); + return wrapColorCellsInRows(lines, rows, cols) ? lines.join("\n") : content; +} + +export const clonePathTypes = (types: readonly PathType[]): PathType[] => types.map((t) => ({ ...t })); + +/** + * Whether a palette note's path-types table has a column for `field`. A note + * without that column never had the field set (the column is written once + * any type has it, and kept from then on, even when cleared to "none"). + */ +export function pathTableHasColumn(content: string, field: "carves" | "carveWidth"): boolean { + const span = findPathTypesTable(content.replace(/\r\n?/g, "\n").split("\n")); + return !!span && span.columns.includes(field); +} diff --git a/src/palettes/presetUpdates.ts b/src/palettes/presetUpdates.ts new file mode 100644 index 00000000..182755d4 --- /dev/null +++ b/src/palettes/presetUpdates.ts @@ -0,0 +1,157 @@ +/** + * Terrains added to a bundled palette after people installed it (OW8: + * "savanna" and "river delta" in Expanded). Each is offered to an installed + * copy of that palette ONCE: added when the palette doesn't have a terrain + * of that name, then remembered as done, so a user who deletes or renames + * it never gets it back, and a terrain they already have (their own colour, + * type, icon) is never touched. + * + * Generic: any preset can list new terrains here; nothing is special-cased. + * A palette counts as a copy of the preset when it has the preset's name + * and still shares most of its terrains (an unrelated palette that happens + * to have the name is left alone). + * + * Pure: no Obsidian imports. PaletteStore backs up the palette notes before + * applying the result. + */ + +import type { PathType, TerrainColor, TerrainPalette } from "../types"; + +export interface AddedPresetTerrain { + /** Preset (palette) name. */ + preset: string; + /** Terrain name in the preset's terrain list. */ + terrain: string; +} + +/** Share of the preset's (older) terrains a palette must still have to count as its copy. */ +export const COPY_OVERLAP = 0.5; + +/** The once-only key for an entry (stored in settings.presetTerrainsAdded). */ +export const addedKey = (a: AddedPresetTerrain): string => `${a.preset}/${a.terrain}`.toLowerCase(); + +export interface PresetTerrainPlan { + /** Terrains to append, per palette (the palette objects themselves). */ + add: { palette: TerrainPalette; terrains: TerrainColor[] }[]; + /** Keys to remember as done (offered, whether added or not). */ + done: string[]; +} + +/** + * Which new preset terrains go into which installed palettes. `presetTerrains` + * looks a preset's current terrains up by name. Nothing is changed here. + */ +export function planPresetTerrains( + palettes: TerrainPalette[], + entries: AddedPresetTerrain[], + alreadyDone: ReadonlySet, + presetTerrains: (preset: string) => TerrainColor[] | undefined, +): PresetTerrainPlan { + const add = new Map(); + const done: string[] = []; + for (const e of entries) { + const key = addedKey(e); + if (alreadyDone.has(key)) continue; + const preset = presetTerrains(e.preset); + const fresh = preset?.find((t) => t.name.toLowerCase() === e.terrain.toLowerCase()); + if (!preset || !fresh) continue; // not shipped (yet): try again next time + done.push(key); + const pal = palettes.find((p) => p.name === e.preset); + if (!pal) continue; // not installed: a later install copies the preset as it is now + const names = new Set(pal.terrains.map((t) => t.name.toLowerCase())); + const newNames = new Set(entries.filter((x) => x.preset === e.preset).map((x) => x.terrain.toLowerCase())); + const older = preset.filter((t) => !newNames.has(t.name.toLowerCase())); + const kept = older.filter((t) => names.has(t.name.toLowerCase())).length; + if (older.length && kept / older.length < COPY_OVERLAP) continue; + if (names.has(fresh.name.toLowerCase())) continue; + const list = add.get(pal) ?? []; + if (!list.some((t) => t.name.toLowerCase() === fresh.name.toLowerCase())) list.push({ ...fresh }); + add.set(pal, list); + } + return { add: [...add].map(([palette, terrains]) => ({ palette, terrains })), done }; +} + +/** Apply a plan: append the terrains to each palette. */ +export function applyPresetTerrains(plan: PresetTerrainPlan): void { + for (const { palette, terrains } of plan.add) palette.terrains.push(...terrains.map((t) => ({ ...t }))); +} + +// ── Path-type fields added to the shipped path types ───────────────────────── +// +// The same idea for path types: a field the shipped path types gained after +// palettes copied them (River's "Carves: water"). The shipped entry +// (DEFAULT_PATH_TYPES) is the source of the value. A palette's path type gets +// it ONCE, and only when the palette's path types are still a copy of the +// shipped list and that field was never set there (the caller checks the +// palette note: no column for it). A value the user set, or cleared to +// "none", is never touched. The path type must still be the shipped record: +// same name and the same behaviour the plugin wrote (routing, auto-route, +// avoid impassable), so a type the user built or reshaped is left alone. + +export type PresetPathField = "carves" | "carveWidth"; + +export interface AddedPresetPathField { + /** Path type name in the shipped list. */ + pathType: string; + field: PresetPathField; +} + +/** The once-only key for an entry (stored in settings.presetPathFieldsAdded). */ +export const pathFieldKey = (a: AddedPresetPathField): string => `${a.pathType}/${a.field}`.toLowerCase(); + +export interface PresetPathFieldPlan { + /** Fields to set, per palette path type (the objects themselves). */ + set: { palette: TerrainPalette; pathType: PathType; field: PresetPathField; value: string | number }[]; + /** Keys to remember as done (offered, whether set anywhere or not). */ + done: string[]; +} + +/** Still the shipped path type: the behaviour fields the plugin wrote are unchanged. */ +const sameShippedRecord = (pt: PathType, shipped: PathType): boolean => + pt.routing === shipped.routing && pt.autoRoute === shipped.autoRoute && pt.avoidImpassable === shipped.avoidImpassable; + +const isSet = (v: unknown): boolean => (typeof v === "string" ? v.trim() !== "" : v !== undefined && v !== null); + +/** + * Which palettes' path types get which shipped field values. `neverSet` says + * whether a palette never had `field` set (its note has no column for it). + * Nothing is changed here. + */ +export function planPresetPathFields( + palettes: TerrainPalette[], + entries: AddedPresetPathField[], + alreadyDone: ReadonlySet, + shipped: readonly PathType[], + neverSet: (palette: TerrainPalette, field: PresetPathField) => boolean, +): PresetPathFieldPlan { + const set: PresetPathFieldPlan["set"] = []; + const done: string[] = []; + const shippedNames = shipped.map((t) => t.name.toLowerCase()); + for (const e of entries) { + const key = pathFieldKey(e); + if (alreadyDone.has(key)) continue; + const source = shipped.find((t) => t.name.toLowerCase() === e.pathType.toLowerCase()); + const value = source?.[e.field]; + if (!source || !isSet(value)) continue; // not shipped (yet): try again next time + done.push(key); + for (const pal of palettes) { + const types = pal.pathTypes ?? []; + // A copy of the shipped list: still has most of its types. + const names = new Set(types.map((t) => t.name.toLowerCase())); + const kept = shippedNames.filter((n) => names.has(n)).length; + if (!shippedNames.length || kept / shippedNames.length < COPY_OVERLAP) continue; + const pt = types.find((t) => t.name.toLowerCase() === source.name.toLowerCase()); + if (!pt || !sameShippedRecord(pt, source) || isSet(pt[e.field]) || !neverSet(pal, e.field)) continue; + set.push({ palette: pal, pathType: pt, field: e.field, value: value as string | number }); + } + } + return { set, done }; +} + +/** Apply a plan: set each field. */ +export function applyPresetPathFields(plan: PresetPathFieldPlan): void { + for (const { pathType, field, value } of plan.set) { + if (field === "carves") pathType.carves = String(value); + else pathType.carveWidth = Number(value); + } +} diff --git a/src/palettes/presets.ts b/src/palettes/presets.ts new file mode 100644 index 00000000..97455107 --- /dev/null +++ b/src/palettes/presets.ts @@ -0,0 +1,74 @@ +import type { PathType, SubmapDefault, TerrainColor, TerrainPalette } from "../types"; +import type { MapKind } from "../mapKinds"; +import { clonePathTypes } from "./pathTypeTable"; +import { DEFAULT_PATH_TYPES } from "../constants"; +import { registry } from "../modules"; + +/** + * A built-in palette users can install from "Add palette", the setup wizard, + * or any new-map palette dropdown. Installing copies the terrains into a new + * palette note and merges any preset path types (by name) into settings. + */ +export interface PalettePreset { + name: string; + description: string; + terrains: TerrainColor[]; + pathTypes?: PathType[]; + /** Palette suggested for submaps of maps using this one. */ + childPalette?: string; + /** Map type this preset belongs to (hidden when that type is off). */ + kind: MapKind; + /** Per-terrain submap setup (see SubmapDefault). */ + submapDefaults?: Record; + /** + * Which of the preset's own path types the built-in generators draw with + * by default (data, so nothing in code picks a path type by its name). + * Only a default: each generator has an option to pick any of the + * palette's path types, so a renamed type works through that option. + */ + pathRoles?: PresetPathRoles; +} + +/** + * The generator path roles a preset fills: role id → the preset's path + * type for it (Space: Star scatter's routes, Orbits' rings). The roles are + * a module's (HexmakerModule.pathRoles; see worldgen/generatorPathTypes.ts). + */ +export type PresetPathRoles = Partial>; + +/** + * Every preset, in module order (src/modules): World's Expanded and + * Limited, then Space's. A module that isn't there adds none. + */ +export const PALETTE_PRESETS: PalettePreset[] = registry.palettes(); + +export function getPreset(name: string): PalettePreset | undefined { + return PALETTE_PRESETS.find((p) => p.name === name); +} + +/** Deep copy of a preset's terrains, safe to mutate. */ +export function presetToPalette(preset: PalettePreset, name = preset.name): TerrainPalette { + const pal: TerrainPalette = { name, terrains: preset.terrains.map((t) => ({ ...t })), kind: preset.kind }; + if (preset.childPalette) pal.childPalette = preset.childPalette; + if (preset.submapDefaults) pal.submapDefaults = cloneSubmapDefaults(preset.submapDefaults); + pal.pathTypes = clonePathTypes(preset.pathTypes ?? DEFAULT_PATH_TYPES); + return pal; +} + +/** `base`, or `base 2`, `base 3`, … — first name not taken (case-insensitive). */ +export function uniquePaletteName(base: string, taken: Iterable): string { + const lower = new Set([...taken].map((n) => n.toLowerCase())); + if (!lower.has(base.toLowerCase())) return base; + for (let i = 2; ; i++) { + const candidate = `${base} ${i}`; + if (!lower.has(candidate.toLowerCase())) return candidate; + } +} + + +/** Deep copy of a submap-defaults map. */ +export function cloneSubmapDefaults(d: Record): Record { + return Object.fromEntries( + Object.entries(d).map(([k, v]) => [k, { ...v, ...(v.options ? { options: { ...v.options } } : {}) }]), + ); +} diff --git a/src/palettes/renameOffer.ts b/src/palettes/renameOffer.ts new file mode 100644 index 00000000..e0c56261 --- /dev/null +++ b/src/palettes/renameOffer.ts @@ -0,0 +1,139 @@ +/** + * "Rename everywhere" for terrains renamed by hand in a palette note (#43). + * + * The palette store tells this class about every hand edit (`noteEdit`). + * Renames are collected per note while the person is still typing in it + * and offered once they leave it (`offer`): one notice per rename, and only + * when something still uses the old name (hexes or the base terrain of a + * map on that palette, or terrain tables with rows). Nothing is changed + * until "Rename everywhere" is clicked; clicking the notice anywhere else + * dismisses it. Names waiting for an answer get no new terrain tables + * (`held`), so the old ones can move to them. + */ + +import { Notice, type TFile } from "obsidian"; +import type { MapData, TerrainColor } from "../types"; +import { parseRandomTable } from "../random-tables/randomTable"; +import { detectTerrainRenames, foldRenames, renameOfferText, terrainUse, type TerrainRename } from "./terrainRename"; + +export interface RenameOfferHost { + app: { vault: { read(f: TFile): Promise } }; + mapsOnPalette(palette: string): MapData[]; + mapStore: { all(map: string): ReadonlyMap }; + terrainTableFiles(name: string): TFile[]; + renameTerrainEverywhere(palette: string, from: string, to: string): Promise; + ensureTablesForNewTerrains(): Promise; +} + +interface Pending extends TerrainRename { + notice?: Notice; +} + +export class TerrainRenameOffers { + /** Per palette note path. */ + private pending = new Map(); + + constructor(private host: RenameOfferHost) {} + + /** A hand edit of the palette note at `path`: fold its renames in. */ + noteEdit(path: string, before: readonly TerrainColor[], after: readonly TerrainColor[]): void { + const found = detectTerrainRenames(before, after); + const list = this.pending.get(path) ?? []; + if (!found.length && !list.length) return; + const names = new Set(after.map((t) => t.name)); + const next = foldRenames(list, found, names); + // A rename whose target moved on, or that's gone: its notice no longer applies. + for (const p of list) { + const still = next.find((n) => n.from === p.from && n.to === p.to); + if (!still) p.notice?.hide(); + } + const kept: Pending[] = next.map((n) => list.find((p) => p.from === n.from && p.to === n.to) ?? n); + if (kept.length) this.pending.set(path, kept); + else this.pending.delete(path); + if (list.length && kept.length < list.length) void this.host.ensureTablesForNewTerrains(); + } + + /** Names waiting for an answer (their tables wait too). */ + held(): Set { + const out = new Set(); + for (const list of this.pending.values()) for (const p of list) out.add(p.to); + return out; + } + + /** Notes with renames waiting. */ + paths(): string[] { + return [...this.pending.keys()]; + } + + /** The note moved: keep its renames. */ + moved(oldPath: string, newPath: string): void { + const list = this.pending.get(oldPath); + if (!list) return; + this.pending.delete(oldPath); + this.pending.set(newPath, list); + } + + /** The note's renames that haven't been offered yet, as notices (call once the person left the note). */ + async offer(path: string, palette: string): Promise { + const list = this.pending.get(path); + if (!list) return; + let dropped = false; + for (const p of [...list]) { + if (p.notice) continue; + const use = terrainUse(p.from, this.host.mapsOnPalette(palette), (m) => this.host.mapStore.all(m)); + const tables = await this.tablesWithRows(p.from); + if (!use.hexes && !use.baseOf.length && !tables) { + list.splice(list.indexOf(p), 1); + dropped = true; + continue; + } + this.show(path, palette, p, renameOfferText(palette, p, use, tables)); + } + if (!list.length) this.pending.delete(path); + if (dropped) await this.host.ensureTablesForNewTerrains(); + } + + /** Terrain tables of `name` that have rows (empty ones aren't worth an offer). */ + private async tablesWithRows(name: string): Promise { + let n = 0; + for (const f of this.host.terrainTableFiles(name)) { + try { + if (parseRandomTable(await this.host.app.vault.read(f)).entries.length) n++; + } catch { /* unreadable: not counted */ } + } + return n; + } + + private show(path: string, palette: string, p: Pending, text: string): void { + const notice = new Notice(text, 0); + p.notice = notice; + const el = (notice as unknown as { noticeEl?: HTMLElement }).noticeEl; + const btn = el?.createEl("button", { text: "Rename everywhere", cls: "duckmage-notice-btn" }); + btn?.addEventListener("click", (ev) => { + ev.stopPropagation(); + notice.hide(); + void this.answer(path, p, true, palette); + }); + // Clicking the notice anywhere else closes it: that's a no. + el?.addEventListener("click", () => void this.answer(path, p, false, palette)); + } + + /** The person answered (tests call this directly). */ + async answer(path: string, p: TerrainRename, yes: boolean, palette: string): Promise { + const list = this.pending.get(path); + const i = list ? list.findIndex((q) => q.from === p.from && q.to === p.to) : -1; + if (!list || i < 0) return; // answered already, or the note changed since + list.splice(i, 1); + if (!list.length) this.pending.delete(path); + if (yes) { + const where = await this.host.renameTerrainEverywhere(palette, p.from, p.to); + if (where) new Notice(`Renamed "${p.from}" to "${p.to}" everywhere. A backup is in ${where}.`); + } + await this.host.ensureTablesForNewTerrains(); + } + + /** Every rename still waiting, by note (tests). */ + pendingFor(path: string): TerrainRename[] { + return (this.pending.get(path) ?? []).map(({ from, to }) => ({ from, to })); + } +} diff --git a/src/palettes/terrainRename.ts b/src/palettes/terrainRename.ts new file mode 100644 index 00000000..ca7540a0 --- /dev/null +++ b/src/palettes/terrainRename.ts @@ -0,0 +1,107 @@ +/** + * Terrains renamed by hand in a palette note (#43). + * + * Hexes name their terrain, so renaming a row in the palette note leaves + * every hex that used the old name with a terrain the palette no longer + * has. The palette store compares each revision of the note with the one + * before; a name that went and a name that came in its place (the same + * row, or the same colour) is a rename candidate. Nothing is changed until + * the person clicks "Rename everywhere" (renameOffer.ts). + * + * Pure: no Obsidian imports. + */ + +import type { TerrainColor } from "../types"; + +export interface TerrainRename { + from: string; + to: string; +} + +const sameColor = (a: string | undefined, b: string | undefined) => + !!a && !!b && a.trim().toLowerCase() === b.trim().toLowerCase(); + +/** + * Renames between two revisions of a palette's terrains: a name gone from + * `before` paired with a name new in `after` that sits in the same row or + * has the same colour. Only pairs with one possible reading count (two new + * terrains with the gone one's colour is no rename). Names are matched as + * written; a change of case is a rename too. + */ +export function detectTerrainRenames(before: readonly TerrainColor[], after: readonly TerrainColor[]): TerrainRename[] { + const beforeNames = new Set(before.map((t) => t.name)); + const afterNames = new Set(after.map((t) => t.name)); + const gone = before.map((t, i) => ({ t, i })).filter(({ t }) => !afterNames.has(t.name)); + const added = after.map((t, i) => ({ t, i })).filter(({ t }) => !beforeNames.has(t.name)); + if (!gone.length || !added.length) return []; + const fits = (g: { t: TerrainColor; i: number }, a: { t: TerrainColor; i: number }) => + g.i === a.i || sameColor(g.t.color, a.t.color); + const out: TerrainRename[] = []; + for (const g of gone) { + const forG = added.filter((a) => fits(g, a)); + if (forG.length !== 1) continue; + const a = forG[0]; + if (gone.filter((h) => fits(h, a)).length !== 1) continue; + out.push({ from: g.t.name, to: a.t.name }); + } + return out; +} + +/** + * Renames still waiting for an answer, with the latest ones folded in: a + * name typed a letter at a time ("forest" → "w" → "wo" → "woods") is one + * rename from the first name to the last. A rename is dropped once its old + * name is back in the palette, its new name has gone, or it was renamed + * back. `names` are the palette's terrain names now. + */ +export function foldRenames(pending: readonly TerrainRename[], found: readonly TerrainRename[], names: ReadonlySet): TerrainRename[] { + const out = pending.map((r) => ({ from: r.from, to: r.to })); + for (const f of found) { + const prev = out.find((r) => r.to === f.from); + if (prev) prev.to = f.to; + else out.push({ from: f.from, to: f.to }); + } + return out.filter((r) => r.from !== r.to && names.has(r.to) && !names.has(r.from)); +} + +/** How much still uses a terrain name on the maps of one palette. */ +export interface TerrainUse { + hexes: number; + /** Maps with hexes of that terrain. */ + hexMaps: string[]; + /** Maps whose base terrain (unpainted hexes) is the name. */ + baseOf: string[]; +} + +/** + * Count the hexes (and base terrains) using `name` on `maps`. `hexesOf` + * gives a map's hex data (MapStore.all). + */ +export function terrainUse( + name: string, + maps: readonly { name: string; baseTerrain?: string }[], + hexesOf: (map: string) => ReadonlyMap, +): TerrainUse { + const use: TerrainUse = { hexes: 0, hexMaps: [], baseOf: [] }; + for (const m of maps) { + let n = 0; + for (const h of hexesOf(m.name).values()) if (h.terrain === name) n++; + if (m.baseTerrain === name) use.baseOf.push(m.name); + if (n) use.hexMaps.push(m.name); + use.hexes += n; + } + return use; +} + +/** + * The offer's text, e.g. `"forest" is now "woods" in the Default palette. + * Still named "forest": 42 hexes on 2 maps, 2 tables.` + */ +export function renameOfferText(palette: string, r: TerrainRename, use: TerrainUse, tables: number): string { + const s = (n: number, one: string, many = `${one}s`) => `${n} ${n === 1 ? one : many}`; + const parts: string[] = []; + if (use.hexes) parts.push(`${s(use.hexes, "hex", "hexes")} on ${s(use.hexMaps.length, "map")}`); + if (use.baseOf.length) parts.push(`the base terrain of ${s(use.baseOf.length, "map")}`); + if (tables) parts.push(s(tables, "table")); + return `"${r.from}" is now "${r.to}" in the ${palette} palette. Still named "${r.from}": ${parts.join(", ")}.`; +} diff --git a/src/paths/PathsService.ts b/src/paths/PathsService.ts new file mode 100644 index 00000000..bba1fbbb --- /dev/null +++ b/src/paths/PathsService.ts @@ -0,0 +1,234 @@ +/** + * The plugin's paths service: every map's anchored paths, resolved to hex + * chains through one shared resolver and one route cache per map. The map + * view, the PNG export, the ghost strip, the hexcrawl manual and the + * read-only consumers (region navigate, region/submap context) all read + * `resolvedPathChains(map)` (the old PathChain shape). + * + * Pure (no Obsidian imports): the plugin hands it a PathsHost. + * + * Determinism: a map's routes depend only on its paths, its palette's + * impassable terrains, the terrain shown on each hex (own, else the map's + * base terrain), its bounds, the orientation, the stagger and each path + * type's explicit style. READINESS GATE: until the map's terrain and its + * palette are loaded, nothing is resolved (an empty list): routing with a + * half-loaded palette would draw a road straight through a lake and then + * jump when the palette arrives. Never an intermediate route. + */ + +import type { MapData, MapPath, PathChain, PathType, TerrainColor } from "../types"; +import { impassableNames } from "../impassable"; +import type { RouteContext, SegmentStyle } from "./router"; +import { contextSignature, DEFAULT_SEGMENT_STYLE } from "./router"; +import { RouteCache } from "./routeCache"; +import { resolvePaths, resolvedToChains, type ResolvedBranch, type StyleFor } from "./resolve"; +import { storedMapPaths } from "./mapPaths"; +import { buildPathStrokes, type LatticeGrid, type PathStroke, type StrokeOptions } from "./pathGeometry"; +import { UNKNOWN_PATH_TYPE } from "../constants"; +import { hexKey } from "../hexKey"; + +/** + * A path type's routing style: THE place the router's avoid/winding flags + * come from (the resolver's StyleFor is built from it). `undefined` for a + * type not in the palette (the resolver then uses DEFAULT_SEGMENT_STYLE). + * + * PA5 SWITCH (fix/46-palettes-generators): the return line below is today's + * effective mapping (the existing helpers in src/impassable.ts). When PA5 + * is merged it becomes exactly + * return t && { avoid: t.avoidImpassable, winding: t.autoRoute === "winding" }; + * and nothing else changes. No other code reads avoid or winding. + */ +export function pathTypeStyle(t: PathType | undefined): SegmentStyle | undefined { + return t && { avoid: t.avoidImpassable, winding: t.autoRoute === "winding" }; +} + +/** StyleFor over a map's path types (first of a name wins, as the palette does). */ +export function styleForTypes(types: readonly PathType[]): StyleFor { + const byName = new Map(); + for (const t of types) if (!byName.has(t.name)) byName.set(t.name, t); + return (name) => pathTypeStyle(byName.get(name)); +} + +/** What the service needs from the plugin. */ +export interface PathsHost { + /** + * The readiness gate: the map's terrain AND its palette are loaded. + * (Wired to MapStore.isReady() + PaletteStore.isReady(); Phase 3's + * per-map MapStore.isReady(map) slots in there.) + */ + isMapReady(map: string): boolean; + getMap(name: string): MapData | undefined; + orientation(): "flat" | "pointy"; + /** The stagger the map is drawn with (its own, else the plugin's). */ + stagger(map: MapData): "odd" | "even"; + /** The map's path types (its palette's). */ + pathTypes(map: string): readonly PathType[]; + /** The map's palette terrains. */ + palette(map: string): readonly TerrainColor[]; + /** The map's hexes with data (own terrain). */ + hexData(map: string): ReadonlyMap; + /** + * Called before a map's paths are resolved whenever its routing context + * or its types' routing styles differ from the last resolve (and on the + * first one): the plugin's chance to keep existing routes where they + * were (phase 7 pins) before anything draws the new ones. + */ + routesChanging?(map: string): void; +} + +interface Memo { + key: string; + resolved: ResolvedBranch[]; + chains: PathChain[]; +} + +export class PathsService { + private caches = new Map(); + private memo = new Map(); + /** Per map: the context signature and styles of the last resolve (see PathsHost.routesChanging). */ + private seen = new Map(); + /** Per map: paths drawn instead of the stored ones (the path tool's live drag preview). */ + private previews = new Map(); + + constructor(private host: PathsHost) {} + + /** The map's stored paths (anchors), whatever its readiness. */ + storedPaths(map: MapData): MapPath[] { + return storedMapPaths(map); + } + + /** + * Draw `paths` for this map instead of its stored ones until cleared + * (null). Nothing is saved: the path tool shows a drag's reroute live and + * commits once on release. + */ + setPreview(mapName: string, paths: MapPath[] | null): void { + if (paths) this.previews.set(mapName, paths); + else this.previews.delete(mapName); + } + + /** The paths being drawn for the map: the preview if any, else the stored ones. */ + shownPaths(map: MapData): MapPath[] { + return this.previews.get(map.name) ?? storedMapPaths(map); + } + + /** + * The map's router under its current context (cached segments), or null + * when the map isn't ready. Resolves first, so a pending context change + * has been dealt with. + */ + router(mapName: string): RouteCache | null { + if (!this.compute(mapName)) return null; + return this.cacheFor(mapName); + } + + /** The routing style of a type on this map (DEFAULT_SEGMENT_STYLE's when unknown). */ + styleOf(mapName: string, typeName: string): SegmentStyle { + return styleForTypes(this.host.pathTypes(mapName))(typeName) ?? DEFAULT_SEGMENT_STYLE; + } + + /** Can this map's paths be resolved yet (terrain and palette loaded)? */ + isReady(mapName: string): boolean { + return !!this.host.getMap(mapName) && this.host.isMapReady(mapName); + } + + /** The map's routing context now, or null when it isn't ready. */ + context(mapName: string): RouteContext | null { + const map = this.host.getMap(mapName); + if (!map || !this.host.isMapReady(mapName)) return null; + const { x: ox, y: oy } = map.gridOffset; + const { cols, rows } = map.gridSize; + const bounds = { minX: ox, minY: oy, maxX: ox + cols - 1, maxY: oy + rows - 1 }; + const names = new Set(impassableNames([...this.host.palette(mapName)])); + const blocked = new Set(); + if (names.size) { + const hexes = this.host.hexData(mapName); + const base = map.baseTerrain; + if (base && names.has(base)) { + // Every hex without its own terrain shows the base: walk the bounds. + for (let x = bounds.minX; x <= bounds.maxX; x++) { + for (let y = bounds.minY; y <= bounds.maxY; y++) { + const k = hexKey(x, y); + const t = hexes.get(k)?.terrain || base; + if (names.has(t)) blocked.add(k); + } + } + } else { + for (const [k, h] of hexes) if (h.terrain && names.has(h.terrain)) blocked.add(k); + } + } + return { orientation: this.host.orientation(), stagger: this.host.stagger(map), bounds, blocked }; + } + + /** The map's route cache (kept across calls; a context change keeps the old routes as previous()). */ + cacheFor(mapName: string): RouteCache { + let c = this.caches.get(mapName); + if (!c) this.caches.set(mapName, (c = new RouteCache())); + return c; + } + + /** The map's paths resolved to branches; [] until the map is ready. */ + resolved(mapName: string): ResolvedBranch[] { + return this.compute(mapName)?.resolved ?? []; + } + + /** The map's resolved branches as PathChains (for read-only consumers); [] until ready. */ + resolvedPathChains(mapName: string): PathChain[] { + return this.compute(mapName)?.chains ?? []; + } + + /** The map's lattice (orientation and stagger), or null for an unknown map. */ + lattice(mapName: string): LatticeGrid | null { + const map = this.host.getMap(mapName); + return map ? { orientation: this.host.orientation(), stagger: this.host.stagger(map) } : null; + } + + /** + * The map's path strokes in lattice units: what the map view and the PNG + * export both draw (only the final affine differs). [] until ready. + */ + strokes(mapName: string, opts: Omit = {}): PathStroke[] { + const grid = this.lattice(mapName); + if (!grid) return []; + return buildPathStrokes(this.resolved(mapName), this.host.pathTypes(mapName), grid, { ...opts, unknownType: UNKNOWN_PATH_TYPE }); + } + + /** Forget a map's cached routes (map deleted or renamed). */ + forget(mapName: string): void { + this.caches.delete(mapName); + this.memo.delete(mapName); + this.seen.delete(mapName); + this.previews.delete(mapName); + } + + private compute(mapName: string): Memo | null { + const map = this.host.getMap(mapName); + let ctx = this.context(mapName); + if (!map || !ctx) return null; + const types = this.host.pathTypes(mapName); + const styleFor = styleForTypes(types); + const stylesOf = (ps: readonly MapPath[]) => [...new Set(ps.map((p) => p.typeName))] + .map((n) => { const s = styleFor(n); return `${n}=${s ? `${+s.avoid}${+s.winding}` : "?"}`; }) + .join(","); + // Routing inputs changed since the last resolve: let the host keep the + // old routes (pins add anchors) before the new ones are drawn. + const inputs = `${contextSignature(ctx)}|${stylesOf(storedMapPaths(map))}`; + if (this.seen.get(mapName) !== inputs) { + this.seen.set(mapName, inputs); + if (this.host.routesChanging) { + this.host.routesChanging(mapName); + ctx = this.context(mapName); + if (!ctx) return null; + } + } + const paths = this.shownPaths(map); + const styles = stylesOf(paths); + const key = `${contextSignature(ctx)}|${styles}|${JSON.stringify(paths.map((p) => [p.name, p.typeName, p.branches.map((b) => b.anchors)]))}`; + const hit = this.memo.get(mapName); + if (hit && hit.key === key) return hit; + const resolved = resolvePaths(paths, ctx, styleFor, this.cacheFor(mapName)); + const memo: Memo = { key, resolved, chains: resolvedToChains(resolved) }; + this.memo.set(mapName, memo); + return memo; + } +} diff --git a/src/paths/anchorText.ts b/src/paths/anchorText.ts new file mode 100644 index 00000000..6399c51a --- /dev/null +++ b/src/paths/anchorText.ts @@ -0,0 +1,95 @@ +/** + * The text form of a branch's anchors, as written in a map note's + * `## Path routes` table: `0, 8 → 9, 8 → 13, 8`. Pure, no Obsidian imports. + * + * Reading is forgiving (plan-path-anchors section 2): + * - a coordinate may be written `3, 4`, `3,4`, `3 4`, `3_4` or `(3, 4)`, negatives too; + * - anchors are separated by `→`, `->`, `>` or `;`; + * - with no separators at all, the numbers are paired in order + * (`3, 4 9, 4` → two anchors); an odd count is an error. + * A cell is never half-read: any problem returns an error and no anchors. + * Writing is always the canonical `x, y → x, y`. + */ + +import type { HexKey } from "../types"; +import { hexKey } from "../hexKey"; + +export type ParseAnchorsResult = { anchors: HexKey[] } | { error: string }; + +/** The separator written between anchors. */ +export const ANCHOR_SEPARATOR = " → "; + +const SEPARATORS = /→|->|>|;/; + +/** One anchor as text: "3_4" → "3, 4". */ +export function formatAnchor(key: HexKey): string { + const [x, y] = key.split("_"); + return `${x}, ${y}`; +} + +/** A branch's anchors as text, in the canonical form `x, y → x, y`. */ +export function formatAnchors(anchors: readonly HexKey[]): string { + return anchors.map(formatAnchor).join(ANCHOR_SEPARATOR); +} + +/** + * The numbers in a piece of a cell, or an error message when the piece holds + * anything but integers, commas, underscores, brackets and spaces. + */ +function readNumbers(text: string): number[] | string { + const token = /\s*(?:(-?\d+)|[(),_])\s*/y; + const out: number[] = []; + let i = 0; + while (i < text.length) { + token.lastIndex = i; + const m = token.exec(text); + if (!m || m[0].length === 0) { + const at = text.slice(i).trim(); + return `can't read "${at.length > 12 ? at.slice(0, 12) + "…" : at}"`; + } + if (m[1] !== undefined) { + const n = Number(m[1]); + if (!Number.isSafeInteger(n)) return `"${m[1]}" is too large`; + out.push(n === 0 ? 0 : n); // -0 → 0 + } + i = token.lastIndex; + } + return out; +} + +/** + * Read a Path routes `Anchors` cell. Returns the anchors as hex keys, or an + * error message (for the map note's warning callout) when the cell can't be + * read in full. + */ +export function parseAnchors(cell: string): ParseAnchorsResult { + const text = cell.trim(); + if (!text) return { error: "no anchors" }; + + if (SEPARATORS.test(text)) { + const anchors: HexKey[] = []; + for (const raw of text.split(SEPARATORS)) { + const piece = raw.trim(); + // A stray separator (leading, trailing, doubled) is harmless. + if (!piece) continue; + const nums = readNumbers(piece); + if (typeof nums === "string") return { error: nums }; + if (nums.length !== 2) { + return { error: `"${piece}" isn't one coordinate (expected x, y)` }; + } + anchors.push(hexKey(nums[0], nums[1])); + } + if (!anchors.length) return { error: "no anchors" }; + return { anchors }; + } + + const nums = readNumbers(text); + if (typeof nums === "string") return { error: nums }; + if (!nums.length) return { error: "no anchors" }; + if (nums.length % 2 !== 0) { + return { error: `an odd number of coordinates (${nums.length}): every anchor needs an x and a y` }; + } + const anchors: HexKey[] = []; + for (let i = 0; i < nums.length; i += 2) anchors.push(hexKey(nums[i], nums[i + 1])); + return { anchors }; +} diff --git a/src/paths/chainView.ts b/src/paths/chainView.ts new file mode 100644 index 00000000..f04bb45a --- /dev/null +++ b/src/paths/chainView.ts @@ -0,0 +1,267 @@ +/** + * The COMPATIBILITY VIEW between the stored model (MapPath[]: named paths, + * anchors, branches) and the every-hex PathChain[] that code not yet + * switched to paths still reads and edits (map.pathChains: the path tool, + * generators, type rename/delete, exports). Pure, no Obsidian imports. + * + * - buildView: paths → one chain per resolved branch, remembering which + * (path, branch) each chain object came from. + * - reconcile: whatever was done to those chains since (hexes pushed or + * spliced in place, chains added, removed, split, replaced by undo + * snapshots, a type renamed) → the paths, keeping each path's name, + * notes, labels and extra columns. Unchanged branches keep their anchors + * exactly; a changed branch is re-anchored from its new hexes (anchorsOf, + * which the caller makes exact with fromHexes.anchorsFor). + * + * Matching a chain to where it came from, in order: the same object; else + * an unclaimed source with the same type and hexes (undo/redo snapshots are + * clones); else a recently removed branch with the same type and hexes + * (undoing a delete brings its path's name back); else an unclaimed source + * of the same type it shares a step with (a split: the pieces stay branches + * of that path); else it's a new path, named ``, ` 2`… + */ + +import type { HexKey, MapPath, PathBranch, PathChain } from "../types"; +import type { ResolvedBranch } from "./resolve"; +import { uniquePathName } from "./names"; +import { stepsOf } from "./fromHexes"; + +/** Where a handed-out chain came from, and what it held then. */ +export interface ChainSource { + path: string; + branch: number; + typeName: string; + hexes: HexKey[]; +} + +/** A branch that left the paths through the view (for undo). */ +interface RemovedBranch { + path: string; + typeName: string; + notes?: string; + extra?: Record; + branch: PathBranch; + hexes: HexKey[]; +} + +/** How many removed branches are remembered for undo. */ +const REMEMBER_REMOVED = 64; + +export interface PathView { + /** Every chain handed out, with its source as of the last build/reconcile. */ + sources: Map; + /** Branches removed through the view, newest last. */ + removed: RemovedBranch[]; +} + +export function emptyView(): PathView { + return { sources: new Map(), removed: [] }; +} + +/** The chains of resolved branches (one per branch with hexes) and their view. */ +export function buildView(resolved: readonly ResolvedBranch[], removed: RemovedBranch[] = []): { chains: PathChain[]; view: PathView } { + const chains: PathChain[] = []; + const sources = new Map(); + for (const r of resolved) { + if (!r.hexes.length) continue; + const c: PathChain = { typeName: r.typeName, hexes: [...r.hexes] }; + chains.push(c); + sources.set(c, { path: r.path, branch: r.branch, typeName: r.typeName, hexes: [...r.hexes] }); + } + return { chains, view: { sources, removed } }; +} + +const same = (a: readonly HexKey[], b: readonly HexKey[]) => a.length === b.length && a.every((k, i) => k === b[i]); + +function cloneBranch(b: PathBranch): PathBranch { + const out: PathBranch = { anchors: [...b.anchors] }; + if (b.label !== undefined) out.label = b.label; + if (b.extra) out.extra = { ...b.extra }; + return out; +} + +type Claim = + | { kind: "source"; src: ChainSource } + | { kind: "attach"; src: ChainSource } + | { kind: "restore"; dead: RemovedBranch } + | { kind: "new" }; + +interface OutBranch { + branch: PathBranch; + chain?: PathChain; +} + +/** + * Fold edits made to the view's chains back into the paths. Returns the new + * paths (the input is never mutated), the view to keep, and whether the + * paths changed. `anchorsOf(typeName, hexes)` turns a changed chain's hexes + * into anchors that route back to exactly those hexes. + */ +export function reconcile( + paths: readonly MapPath[], + chains: readonly PathChain[], + view: PathView, + anchorsOf: (typeName: string, hexes: HexKey[]) => HexKey[], +): { paths: MapPath[]; view: PathView; changed: boolean } { + const pathIdx = new Map(paths.map((p, i) => [p.name, i])); + const valid = (s: ChainSource) => { + const i = pathIdx.get(s.path); + return i !== undefined && s.branch >= 0 && s.branch < paths[i].branches.length; + }; + const sources = [...view.sources.values()].filter(valid); + const claimed = new Set(); + const removed = [...view.removed]; + const usedDead = new Set(); + const live = chains.filter((c) => c && Array.isArray(c.hexes) && c.hexes.length > 0); + const claims = new Map(); + + // 1. the same object + for (const c of live) { + const s = view.sources.get(c); + if (s && valid(s) && !claimed.has(s)) { + claimed.add(s); + claims.set(c, { kind: "source", src: s }); + } + } + // 2. an unclaimed source with the same type and hexes (snapshot clones) + for (const c of live) { + if (claims.has(c)) continue; + const s = sources.find((x) => !claimed.has(x) && x.typeName === c.typeName && same(x.hexes, c.hexes)); + if (s) { + claimed.add(s); + claims.set(c, { kind: "source", src: s }); + } + } + // 3. a removed branch with the same type and hexes (undo of a delete) + for (const c of live) { + if (claims.has(c)) continue; + for (let i = removed.length - 1; i >= 0; i--) { + const d = removed[i]; + if (!usedDead.has(d) && d.typeName === c.typeName && same(d.hexes, c.hexes)) { + usedDead.add(d); + claims.set(c, { kind: "restore", dead: d }); + break; + } + } + } + // 4. a step shared with an unclaimed source of the same type (split pieces) + for (const c of live) { + if (claims.has(c)) continue; + const steps = stepsOf([c.hexes]); + const s = sources.find((x) => !claimed.has(x) && x.typeName === c.typeName && [...stepsOf([x.hexes])].some((k) => steps.has(k))); + claims.set(c, s ? { kind: "attach", src: s } : { kind: "new" }); + } + + // Branch slots: ":" → the chain now holding it. + const slot = (s: ChainSource) => `${pathIdx.get(s.path)}:${s.branch}`; + const bySlot = new Map(); + const attached = new Map(); + for (const [c, cl] of claims) { + if (cl.kind === "source") bySlot.set(slot(cl.src), c); + else if (cl.kind === "attach") { + // The first piece takes the branch's place, the others follow it. + const k = slot(cl.src); + if (!bySlot.has(k) && !claimed.has(cl.src)) { bySlot.set(k, c); claimed.add(cl.src); } + else attached.set(k, [...(attached.get(k) ?? []), c]); + } + } + const viewed = new Set(sources.map(slot)); + + const changedHexes = (c: PathChain, s: ChainSource | undefined) => !s || !same(s.hexes, c.hexes); + const sourceOf = (c: PathChain): ChainSource | undefined => { + const cl = claims.get(c); + return cl && cl.kind === "source" ? cl.src : undefined; + }; + + const names = paths.map((p) => p.name); + const out: { path: MapPath; branches: OutBranch[] }[] = []; + const newPaths: { path: MapPath; branches: OutBranch[] }[] = []; + const forget = (p: MapPath, b: PathBranch, hexes: HexKey[]) => { + const d: RemovedBranch = { path: p.name, typeName: p.typeName, branch: cloneBranch(b), hexes: [...hexes] }; + if (p.notes !== undefined) d.notes = p.notes; + if (p.extra) d.extra = { ...p.extra }; + removed.push(d); + }; + + paths.forEach((p, i) => { + const branches: OutBranch[] = []; + let hadView = false; + p.branches.forEach((b, j) => { + const k = `${i}:${j}`; + if (viewed.has(k)) hadView = true; + const c = bySlot.get(k); + if (c) { + const src = sourceOf(c); + branches.push({ + branch: changedHexes(c, src) ? { ...cloneBranch(b), anchors: anchorsOf(c.typeName, [...c.hexes]) } : cloneBranch(b), + chain: c, + }); + } else if (viewed.has(k)) { + const src = sources.find((s) => slot(s) === k); + forget(p, b, src?.hexes ?? b.anchors); + } else { + branches.push({ branch: cloneBranch(b) }); // never handed out (no hexes yet): keep + } + for (const extraChain of attached.get(k) ?? []) { + branches.push({ branch: { anchors: anchorsOf(extraChain.typeName, [...extraChain.hexes]) }, chain: extraChain }); + } + }); + if (hadView && !branches.length) return; // every branch was removed: the path goes + const path: MapPath = { ...p, branches: [] }; + if (p.extra) path.extra = { ...p.extra }; + // A type changed on the chains: the path follows when all of them agree, + // else the branches of another type become a path of that type. + const types = new Set(branches.filter((b) => b.chain).map((b) => b.chain!.typeName)); + if (types.size === 1 && !types.has(p.typeName) && branches.every((b) => b.chain)) path.typeName = [...types][0]; + const keep: OutBranch[] = []; + const moved = new Map(); + for (const b of branches) { + const t = b.chain?.typeName; + if (t === undefined || t === path.typeName) keep.push(b); + else moved.set(t, [...(moved.get(t) ?? []), b]); + } + if (keep.length || !hadView) out.push({ path, branches: keep }); + for (const [t, bs] of moved) { + const name = uniquePathName(t, names); + names.push(name); + newPaths.push({ path: { name, typeName: t, branches: [] }, branches: bs }); + } + }); + + // Restored and new chains, in chain order. + for (const c of live) { + const cl = claims.get(c)!; + if (cl.kind === "restore") { + const d = cl.dead; + const host = [...out, ...newPaths].find((o) => o.path.name === d.path && o.path.typeName === d.typeName); + const ob: OutBranch = { branch: cloneBranch(d.branch), chain: c }; + if (host) host.branches.push(ob); + else { + const name = names.includes(d.path) && out.some((o) => o.path.name === d.path) ? uniquePathName(d.path, names) : d.path; + if (!names.includes(name)) names.push(name); + const path: MapPath = { name, typeName: d.typeName, branches: [] }; + if (d.notes !== undefined) path.notes = d.notes; + if (d.extra) path.extra = { ...d.extra }; + newPaths.push({ path, branches: [ob] }); + } + } else if (cl.kind === "new") { + const name = uniquePathName(c.typeName, names); + names.push(name); + newPaths.push({ path: { name, typeName: c.typeName, branches: [] }, branches: [{ branch: { anchors: anchorsOf(c.typeName, [...c.hexes]) }, chain: c }] }); + } + } + const restoredDead = new Set(usedDead); + const keptRemoved = removed.filter((d) => !restoredDead.has(d)).slice(-REMEMBER_REMOVED); + + const result: MapPath[] = []; + const nextSources = new Map(); + for (const o of [...out, ...newPaths]) { + const p: MapPath = { ...o.path, branches: o.branches.map((b) => b.branch) }; + result.push(p); + o.branches.forEach((b, j) => { + if (b.chain) nextSources.set(b.chain, { path: p.name, branch: j, typeName: b.chain.typeName, hexes: [...b.chain.hexes] }); + }); + } + const changed = JSON.stringify(result) !== JSON.stringify(paths); + return { paths: changed ? result : paths.map((p) => p), view: { sources: nextSources, removed: keptRemoved }, changed }; +} diff --git a/src/paths/edit.ts b/src/paths/edit.ts new file mode 100644 index 00000000..5394a436 --- /dev/null +++ b/src/paths/edit.ts @@ -0,0 +1,274 @@ +/** + * Edit operations on anchored paths. Pure: every op returns a new MapPath + * (or list) and never mutates its input, so an undo step is just the + * before/after values. Ops that would leave a path with no branches return + * null (the caller removes the path). Pure, no Obsidian imports. + * + * Ops that must not move the line (split, reverse, pin) re-anchor the + * affected hexes with anchorsFor, so the routed hexes stay exactly the same. + */ + +import type { HexKey, MapPath, PathBranch } from "../types"; +import type { RouteContext, SegmentRoute } from "./router"; +import type { SegmentRouter } from "./routeCache"; +import { anchorsFor, type RouteFn } from "./fromHexes"; +import { styleOf, type ResolvedBranch, type StyleFor } from "./resolve"; +import { uniquePathName } from "./names"; + +export { uniquePathName, pathNameKey } from "./names"; + +type Grid = Pick; +/** What the ops need of a resolved branch. */ +export type BranchRoute = Pick; + +function cloneBranch(b: PathBranch): PathBranch { + const out: PathBranch = { anchors: [...b.anchors] }; + if (b.label !== undefined) out.label = b.label; + if (b.extra) out.extra = { ...b.extra }; + return out; +} + +/** A deep copy (anchors, branches and extra columns). */ +export function clonePath(p: MapPath): MapPath { + const out: MapPath = { name: p.name, typeName: p.typeName, branches: p.branches.map(cloneBranch) }; + if (p.notes !== undefined) out.notes = p.notes; + if (p.extra) out.extra = { ...p.extra }; + return out; +} + +export function clonePaths(ps: readonly MapPath[]): MapPath[] { + return ps.map(clonePath); +} + +function checkBranch(p: MapPath, branch: number): void { + if (!Number.isInteger(branch) || branch < 0 || branch >= p.branches.length) { + throw new RangeError(`path "${p.name}" has no branch ${branch}`); + } +} + +function checkAnchor(p: MapPath, branch: number, anchor: number): void { + checkBranch(p, branch); + if (!Number.isInteger(anchor) || anchor < 0 || anchor >= p.branches[branch].anchors.length) { + throw new RangeError(`branch ${branch} of "${p.name}" has no anchor ${anchor}`); + } +} + +/** `p` with branch `branch` replaced by `make(copy of it)`. */ +function withBranch(p: MapPath, branch: number, make: (b: PathBranch) => PathBranch): MapPath { + checkBranch(p, branch); + const out = clonePath(p); + out.branches[branch] = make(out.branches[branch]); + return out; +} + +/** A new path of `typeName` with one anchor, named ``, ` 2`… unique against `taken`. */ +export function newPath(typeName: string, hex: HexKey, taken: Iterable): MapPath { + return { name: uniquePathName(typeName, taken), typeName, branches: [{ anchors: [hex] }] }; +} + +/** Add an anchor at the end of a branch (no-op when it's already the last one). */ +export function appendAnchor(p: MapPath, branch: number, hex: HexKey): MapPath { + checkBranch(p, branch); + const a = p.branches[branch].anchors; + if (a[a.length - 1] === hex) return p; + return withBranch(p, branch, (b) => ({ ...b, anchors: [...b.anchors, hex] })); +} + +/** Add an anchor at the start of a branch (no-op when it's already the first one). */ +export function prependAnchor(p: MapPath, branch: number, hex: HexKey): MapPath { + checkBranch(p, branch); + if (p.branches[branch].anchors[0] === hex) return p; + return withBranch(p, branch, (b) => ({ ...b, anchors: [hex, ...b.anchors] })); +} + +/** Start a fork: a new branch whose first anchor is `hex` (a hex on the path). */ +export function forkAt(p: MapPath, hex: HexKey, label?: string): { path: MapPath; branch: number } { + const out = clonePath(p); + const b: PathBranch = { anchors: [hex] }; + if (label !== undefined) b.label = label; + out.branches.push(b); + return { path: out, branch: out.branches.length - 1 }; +} + +/** + * Make the routed hex `hexIdx` of a branch an anchor (the start of a drag on + * the line): inserted between the anchors around it. When that hex already + * is an anchor, nothing changes and its index is returned. + */ +export function insertAnchorAt(p: MapPath, route: BranchRoute, hexIdx: number): { path: MapPath; anchor: number; inserted: boolean } { + checkBranch(p, route.branch); + if (!Number.isInteger(hexIdx) || hexIdx < 0 || hexIdx >= route.hexes.length) { + throw new RangeError(`hex index ${hexIdx} is not on branch ${route.branch} of "${p.name}"`); + } + let k = 0; + for (let i = 0; i < route.anchorIdx.length; i++) if (route.anchorIdx[i] <= hexIdx) k = i; + if (route.anchorIdx[k] === hexIdx) return { path: p, anchor: k, inserted: false }; + const hex = route.hexes[hexIdx]; + const path = withBranch(p, route.branch, (b) => { + const anchors = [...b.anchors]; + anchors.splice(k + 1, 0, hex); + return { ...b, anchors }; + }); + return { path, anchor: k + 1, inserted: true }; +} + +/** Move one anchor to another hex. */ +export function moveAnchor(p: MapPath, branch: number, anchor: number, hex: HexKey): MapPath { + checkAnchor(p, branch, anchor); + if (p.branches[branch].anchors[anchor] === hex) return p; + return withBranch(p, branch, (b) => { + const anchors = [...b.anchors]; + anchors[anchor] = hex; + return { ...b, anchors }; + }); +} + +/** Remove a branch; null when it was the path's last one. */ +export function deleteBranch(p: MapPath, branch: number): MapPath | null { + checkBranch(p, branch); + if (p.branches.length === 1) return null; + const out = clonePath(p); + out.branches.splice(branch, 1); + return out; +} + +/** + * Remove an anchor: its two segments become one route. A branch left with + * fewer than two anchors is removed; null when that was the path's last. + */ +export function deleteAnchor(p: MapPath, branch: number, anchor: number): MapPath | null { + checkAnchor(p, branch, anchor); + const anchors = p.branches[branch].anchors.filter((_, i) => i !== anchor); + if (anchors.length < 2) return deleteBranch(p, branch); + return withBranch(p, branch, (b) => ({ ...b, anchors })); +} + +/** + * Erase routed hex `hexIdx` from a branch: its two steps go, and the pieces + * on either side stay branches of the path (the first in place, the second + * right after it), each keeping its anchors plus just enough new ones that + * nothing else moves. Pieces of fewer than two hexes vanish; null when + * nothing is left of the path. + */ +export function splitBranchAt(p: MapPath, route: BranchRoute, hexIdx: number, routeFn: RouteFn, grid?: Grid): MapPath | null { + checkBranch(p, route.branch); + const { hexes, anchorIdx } = route; + if (!Number.isInteger(hexIdx) || hexIdx < 0 || hexIdx >= hexes.length) { + throw new RangeError(`hex index ${hexIdx} is not on branch ${route.branch} of "${p.name}"`); + } + const anchors = p.branches[route.branch].anchors; + const pieces: HexKey[][] = []; + if (hexIdx >= 2) { + // Anchors strictly before the erased hex, then the partial segment up to it. + let k = 0; + for (let i = 0; i < anchorIdx.length; i++) if (anchorIdx[i] < hexIdx) k = i; + const tail = anchorsFor(hexes.slice(anchorIdx[k], hexIdx), routeFn, grid); + pieces.push([...anchors.slice(0, k + 1), ...tail.slice(1)]); + } + if (hexIdx <= hexes.length - 3) { + let m = anchorIdx.length - 1; + for (let i = anchorIdx.length - 1; i >= 0; i--) if (anchorIdx[i] > hexIdx) m = i; + const head = anchorsFor(hexes.slice(hexIdx + 1, anchorIdx[m] + 1), routeFn, grid); + pieces.push([...head.slice(0, -1), ...anchors.slice(m)]); + } + if (!pieces.length) return deleteBranch(p, route.branch); + const out = clonePath(p); + const old = out.branches[route.branch]; + const replaced: PathBranch[] = pieces.map((a, i) => (i === 0 ? { ...old, anchors: a } : { anchors: a })); + out.branches.splice(route.branch, 1, ...replaced); + return out; +} + +/** + * Reverse a branch without moving it: its anchors in reverse order, plus + * whatever anchors each reversed segment needs to keep its hexes (a route + * from b to a may tie-break differently from a to b). + */ +export function reverseBranch(p: MapPath, route: BranchRoute, routeFn: RouteFn, grid?: Grid): MapPath { + checkBranch(p, route.branch); + const { hexes, anchorIdx } = route; + const out: HexKey[] = []; + for (let i = anchorIdx.length - 1; i >= 1; i--) { + const seg = hexes.slice(anchorIdx[i - 1], anchorIdx[i] + 1).reverse(); + const a = seg.length ? anchorsFor(seg, routeFn, grid) : []; + out.push(...(out.length ? a.slice(1) : a)); + } + if (!out.length) out.push(...p.branches[route.branch].anchors); + return withBranch(p, route.branch, (b) => ({ ...b, anchors: out })); +} + +// ── Pinning (Decision 3: keep the old route) ───────────────────────────────── + +/** A segment's route for a path type: (typeName, a, b) → route. */ +export type SegmentFn = (typeName: string, a: HexKey, b: HexKey) => SegmentRoute; + +/** A SegmentFn from a router (e.g. a RouteCache or its previous()) and the types' styles. */ +export function segmentFn(router: SegmentRouter, styleFor?: StyleFor): SegmentFn { + return (typeName, a, b) => router.route(a, b, styleOf(styleFor, typeName)); +} + +const sameHexes = (x: readonly HexKey[], y: readonly HexKey[]) => x.length === y.length && x.every((k, i) => k === y[i]); + +const segmentKey = (typeName: string, a: HexKey, b: HexKey) => `${typeName}\u0000${a}\u0000${b}`; + +/** Every segment (type, anchor, next anchor) of some paths. */ +function segmentKeys(paths: readonly MapPath[]): Set { + const out = new Set(); + for (const p of paths) { + for (const b of p.branches) for (let i = 1; i < b.anchors.length; i++) out.add(segmentKey(p.typeName, b.anchors[i - 1], b.anchors[i])); + } + return out; +} + +/** + * Before a context change (terrain or palette impassability, a resize, a + * type's avoid/winding style) takes effect: every segment whose route would + * change gets just enough extra anchors that the new routing reproduces its + * old hexes. Paths with nothing to pin are returned as the same objects. + * `pinned` lists each changed path and how many anchors it gained (for the + * "Kept the route of …" notice; dropping those anchors is "Reroute instead"). + * + * `drawnBefore`: when the paths changed in the same step as the context (a + * hand edit of the map note that moved anchors and painted terrain), the + * paths as they were. Only segments that were already there (same type, + * same two anchors in that order) had a route to keep; a segment the edit + * made is routed under the map as it is now, never pinned to the old one. + */ +export function pinChanged( + paths: readonly MapPath[], + oldSeg: SegmentFn, + newSeg: SegmentFn, + grid?: Grid, + drawnBefore?: readonly MapPath[], +): { paths: MapPath[]; pinned: { path: string; added: number }[] } { + const pinned: { path: string; added: number }[] = []; + const existed = drawnBefore ? segmentKeys(drawnBefore) : null; + const out = paths.map((p) => { + let added = 0; + const branches = p.branches.map((b) => { + const anchors: HexKey[] = b.anchors.length ? [b.anchors[0]] : []; + for (let i = 1; i < b.anchors.length; i++) { + const a = b.anchors[i - 1]; + const c = b.anchors[i]; + if (existed && !existed.has(segmentKey(p.typeName, a, c))) { + anchors.push(c); + continue; + } + const before = oldSeg(p.typeName, a, c).hexes; + if (!sameHexes(before, newSeg(p.typeName, a, c).hexes)) { + const inner = anchorsFor(before, (x, y) => newSeg(p.typeName, x, y), grid).slice(1, -1); + anchors.push(...inner); + added += inner.length; + } + anchors.push(c); + } + return anchors; + }); + if (!added) return p; + pinned.push({ path: p.name, added }); + const q = clonePath(p); + q.branches.forEach((b, i) => { b.anchors = branches[i]; }); + return q; + }); + return { paths: out, pinned }; +} diff --git a/src/paths/editGate.ts b/src/paths/editGate.ts new file mode 100644 index 00000000..0d7a5173 --- /dev/null +++ b/src/paths/editGate.ts @@ -0,0 +1,45 @@ +/** + * THE GATE for path edits. Every change to a map's stored paths made by + * the plugin at runtime goes through `canEditPaths` first: the path tool's + * edits (pathTool.ts applyEdit, including undo/redo of path steps), the + * keep-the-route pins when terrain, the palette, the map's size or a type's + * routing changes (routePins.ts), and "Reroute instead". + * + * It answers "is this allowed in this map's work mode?" (src/workMode.ts: + * Play / Build / God). Drawing, reshaping, undo/redo and "Reroute instead" + * count as Build, so they need Build or God. Keep-the-route pins only + * preserve what is already drawn, so they are allowed in every mode. + * The plugin registers how to look a map up (`setPathEditMapLookup`); with + * no lookup (tests, early load) everything is allowed. + * Pure, no Obsidian imports. + */ +import { mapAllows } from "../workMode"; + +/** What kind of path edit is being asked for. */ +export type PathEditAction = + /** The path tool: draw, extend, fork, drag, delete, split, rename, retype, reverse. */ + | "draw" + /** Undo or redo of a path step. */ + | "history" + /** Keep a route where it was after its routing inputs changed (Decision 3). */ + | "pin" + /** "Reroute instead": drop the anchors a pin added. */ + | "reroute"; + +type MapLookup = (mapName: string) => { workMode?: string } | undefined; +let lookup: MapLookup | null = null; + +/** Tell the gate how to find a map (and so its work mode). */ +export function setPathEditMapLookup(fn: MapLookup | null): void { + lookup = fn; +} + +/** Shown when a path edit is refused because of the map's mode. */ +export const PATH_EDIT_LOCKED_HINT = "Switch to Build to change paths on this map."; + +/** May `action` change the stored paths of map `mapName`? */ +export function canEditPaths(mapName: string, action: PathEditAction): boolean { + if (action === "pin") return true; // keeps what is drawn; never a user change + if (!lookup) return true; + return mapAllows(lookup(mapName), "edit-path"); +} diff --git a/src/paths/forks.ts b/src/paths/forks.ts new file mode 100644 index 00000000..494f2039 --- /dev/null +++ b/src/paths/forks.ts @@ -0,0 +1,172 @@ +/** + * Keeping forks attached to the branch they leave (owner decision + * 2026-10-11). A fork is a branch whose first anchor lies on another + * branch's route (a join: whose last anchor does); nothing else ties them. + * So when an edit changes one branch's route, the branches attached to it + * have to follow, or they're left hanging beside it: + * + * - keepForksAttached: a branch's route changed (an anchor moved, added or + * deleted). Forks and joins that were on its old route and aren't on the + * new one move: onto the moved anchor's new hex when they sat on that + * anchor, else onto the nearest hex of the new route. + * - splitOffOrphans: a branch was removed. Forks that hung off it (and + * their own forks) become paths of their own; when the main line went + * and nothing else is left, the first of them keeps the path's name. + * + * Pure, no Obsidian imports. The caller commits the result as one step. + */ + +import type { HexKey, MapPath, PathBranch } from "../types"; +import { latticeCenter, type LatticeGrid } from "./pathGeometry"; +import { uniquePathName } from "./names"; + +function cloneBranch(b: PathBranch): PathBranch { + const out: PathBranch = { anchors: [...b.anchors] }; + if (b.label !== undefined) out.label = b.label; + if (b.extra) out.extra = { ...b.extra }; + return out; +} + +/** The hex of `route` nearest `hex` (first on ties). */ +export function nearestOnRoute(hex: HexKey, route: readonly HexKey[], grid: LatticeGrid): HexKey | null { + const p = latticeCenter(hex, grid); + let best: HexKey | null = null; + let bestD = Infinity; + for (const k of route) { + const c = latticeCenter(k, grid); + const d = Math.hypot(p.cx - c.cx, p.cy - c.cy); + if (d < bestD - 1e-9) { + bestD = d; + best = k; + } + } + return best; +} + +/** + * Branch `branch` of `p` was re-routed from `oldRoute` to `newRoute` (p is + * the path after the edit; branch indices unchanged). Every other branch + * whose first anchor (fork) or last anchor (join) was on the old route but + * isn't on the new one is moved back onto it: to `moved.to` when it sat on + * `moved.from` (the dragged anchor), else to the nearest hex of the new + * route. An end that lands on its neighbour anchor merges with it; a branch + * left with fewer than two anchors is dropped. Returns `p` itself when + * nothing had to move. + */ +export function keepForksAttached( + p: MapPath, + branch: number, + oldRoute: readonly HexKey[], + newRoute: readonly HexKey[], + grid: LatticeGrid, + moved?: { from: HexKey; to: HexKey }, +): MapPath { + if (!newRoute.length) return p; + const was = new Set(oldRoute); + const now = new Set(newRoute); + const target = (hex: HexKey): HexKey | null => { + if (moved && hex === moved.from) return moved.to; + if (!was.has(hex) || now.has(hex)) return null; + return nearestOnRoute(hex, newRoute, grid); + }; + let changed = false; + const branches: PathBranch[] = []; + p.branches.forEach((b, i) => { + if (i === branch || b.anchors.length < 2) { + branches.push(b); + return; + } + const a = [...b.anchors]; + const head = target(a[0]); + const tail = target(a[a.length - 1]); + if (head === null && tail === null) { + branches.push(b); + return; + } + changed = true; + if (head !== null) { + a[0] = head; + if (a[1] === head) a.splice(1, 1); + } + if (tail !== null) { + a[a.length - 1] = tail; + if (a.length > 1 && a[a.length - 2] === tail) a.splice(a.length - 2, 1); + } + if (a.length < 2) return; // nothing left of it + branches.push({ ...cloneBranch(b), anchors: a }); + }); + if (!changed) return p; + const out: MapPath = { name: p.name, typeName: p.typeName, branches }; + if (p.notes !== undefined) out.notes = p.notes; + if (p.extra) out.extra = { ...p.extra }; + return out; +} + +/** + * Branch `removed` of `before` is being deleted (`routes[i]` = branch i's + * route before the edit). The branches that hung off it, and anything + * hanging off those, can't stay in the path detached: each such group + * becomes a path of its own (new names from `taken`), its root first so + * it's the new main line. When nothing but such groups is left, the first + * group keeps the path (its name, notes and extra columns). Returns the + * path that's left (null when none) and the new paths. + */ +export function splitOffOrphans( + before: MapPath, + removed: number, + routes: readonly (readonly HexKey[])[], + taken: Iterable, +): { path: MapPath | null; split: MapPath[] } { + const n = before.branches.length; + const onRoute = (hex: HexKey, j: number) => (routes[j] ?? before.branches[j].anchors).includes(hex); + // Each branch's parent: the first other surviving branch its start is on. + // Branches whose start was only on the removed branch are orphan roots. + const parent: (number | null)[] = []; + const root: boolean[] = []; + for (let i = 0; i < n; i++) { + parent.push(null); + root.push(false); + if (i === removed || i === 0) continue; + const start = before.branches[i].anchors[0]; + let p: number | null = null; + for (let j = 0; j < n && p === null; j++) if (j !== i && j !== removed && onRoute(start, j)) p = j; + parent[i] = p; + root[i] = p === null && onRoute(start, removed); + } + // Groups: each root and its descendants (by parent chain, in index order). + const groupOf = (i: number): number | null => { + const seen = new Set(); + let k: number | null = i; + while (k !== null && !seen.has(k)) { + if (root[k]) return k; + seen.add(k); + k = parent[k]; + } + return null; + }; + const groups = new Map(); + const stay: number[] = []; + for (let i = 0; i < n; i++) { + if (i === removed) continue; + const g = groupOf(i); + if (g === null) stay.push(i); + else groups.set(g, [...(groups.get(g) ?? []), i]); + } + // Roots first within their group (index order otherwise). + const ordered = [...groups.entries()].sort((a, b) => a[0] - b[0]).map(([g, members]) => [g, ...members.filter((m) => m !== g)]); + const branchesOf = (idx: number[]) => idx.map((i) => cloneBranch(before.branches[i])); + const names = [...taken]; + const fresh = (idx: number[]): MapPath => { + const name = uniquePathName(before.typeName, names); + names.push(name); + return { name, typeName: before.typeName, branches: branchesOf(idx) }; + }; + let path: MapPath | null = null; + if (stay.length) path = { name: before.name, typeName: before.typeName, branches: branchesOf(stay) }; + else if (ordered.length) path = { name: before.name, typeName: before.typeName, branches: branchesOf(ordered.shift()!) }; + if (path) { + if (before.notes !== undefined) path.notes = before.notes; + if (before.extra) path.extra = { ...before.extra }; + } + return { path, split: ordered.map(fresh) }; +} diff --git a/src/paths/fromGenerated.ts b/src/paths/fromGenerated.ts new file mode 100644 index 00000000..a76c1678 --- /dev/null +++ b/src/paths/fromGenerated.ts @@ -0,0 +1,91 @@ +/** + * Generated hex paths → anchored MapPaths (generators: map creation, a new + * region next to another, regenerating a map). Pure, no Obsidian imports. + * + * Generators keep their own routing (terrain-cost Dijkstra, WFC paths), so + * their hexes are not what the editor router would draw. Each generated + * chain is turned into the fewest anchors that make the editor router + * reproduce it exactly (fromHexes.anchorsFor) under the TARGET map's routing + * context (its terrain, palette, bounds, orientation and stagger), which is + * exactly what the map draws once the paths are stored. + * + * Chains of one type that touch end-on become one path with branches, the + * same stroke-preserving merge the migration uses (mergeChains). Names are + * ``, ` 2`… unique against `taken`. + * + * A chain with a step between hexes that aren't neighbours (Star scatter's + * jump routes link two systems) can't be reproduced hex for hex: its hexes + * become anchors and the router fills in between (listed in `inexact`). + */ + +import type { HexKey, MapPath } from "../types"; +import type { RouteContext } from "./router"; +import { contextRouter, type SegmentRouter } from "./routeCache"; +import { routeBranch, styleOf, type StyleFor } from "./resolve"; +import { anchorsFor, dedupeSteps, mergeChains, reproduces, routeFnFor } from "./fromHexes"; +import { uniquePathName } from "./names"; + +/** A generated path already typed as a map path type. */ +export interface TypedHexChain { + typeName: string; + hexes: readonly HexKey[]; +} + +export interface GeneratedToPathsOptions { + /** The types' explicit routing style (avoid impassable, winding). */ + styleFor?: StyleFor; + /** Names already used on the map (new names avoid them). */ + taken?: Iterable; + /** A router for `ctx` to reuse (e.g. the map's RouteCache); else an uncached one. */ + router?: SegmentRouter; +} + +/** + * Generated chains → MapPaths (see the module comment). Types come out in + * order of first appearance; within a type, merged groups in order of their + * first chain. Chains of fewer than two distinct hexes are dropped (they + * draw nothing). + */ +export function generatedToMapPaths( + chains: readonly TypedHexChain[], + ctx: RouteContext, + opts: GeneratedToPathsOptions = {}, +): { paths: MapPath[]; inexact: string[] } { + const router = opts.router ?? contextRouter(ctx); + const taken = [...(opts.taken ?? [])]; + const byType = new Map(); + for (const c of chains) { + const hexes = dedupeSteps(c.hexes); + if (hexes.length < 2) continue; + const list = byType.get(c.typeName); + if (list) list.push(hexes); + else byType.set(c.typeName, [hexes]); + } + const paths: MapPath[] = []; + const inexact: string[] = []; + for (const [typeName, list] of byType) { + const style = styleOf(opts.styleFor, typeName); + const route = routeFnFor(router, style); + for (const g of mergeChains(list)) { + let exact = true; + const branches = g.branches.map((hexes) => { + const anchors = anchorsFor(hexes, route, ctx); + if (reproduces(anchors, hexes, route)) return { anchors }; + exact = false; + return { anchors: dedupeSteps(hexes) }; + }); + const name = uniquePathName(typeName, taken); + taken.push(name); + paths.push({ name, typeName, branches }); + if (!exact) inexact.push(name); + } + } + return { paths, inexact }; +} + +/** The hex chains a path's branches route to under `ctx` (for checks and tests). */ +export function routedBranches(path: MapPath, ctx: RouteContext, styleFor?: StyleFor, router?: SegmentRouter): HexKey[][] { + const r = router ?? contextRouter(ctx); + const style = styleOf(styleFor, path.typeName); + return path.branches.map((b) => routeBranch(b.anchors, style, r).hexes); +} diff --git a/src/paths/fromHexes.ts b/src/paths/fromHexes.ts new file mode 100644 index 00000000..b627f555 --- /dev/null +++ b/src/paths/fromHexes.ts @@ -0,0 +1,346 @@ +/** + * Hex chains → anchors. `anchorsFor` is the only way hexes become anchors + * (migration, pinning, splitting, reversing, generators): a greedy longest + * match against the router, exact for any neighbour-connected chain. + * `mergeChains` joins same-type chains that touch end-on into one path with + * branches (stroke-preserving), and `compactLegacy` runs the whole legacy + * migration step over dense-anchor paths. Pure, no Obsidian imports. + */ + +import type { HexKey, MapPath } from "../types"; +import { hexDistance, type SegmentContext, type SegmentStyle, type RouteContext } from "./router"; +import { contextRouter, RouteCache, type SegmentRouter } from "./routeCache"; +import { routeBranch, styleOf, type StyleFor } from "./resolve"; +import { uniquePathName } from "./names"; +import { hexPair } from "../hexKey"; + +/** The route between two anchors under some fixed context and style. */ +export type RouteFn = (a: HexKey, b: HexKey) => { hexes: readonly HexKey[]; fallback?: string }; + +/** A RouteFn from a router and a style. */ +export function routeFnFor(router: SegmentRouter, style: SegmentStyle): RouteFn { + return (a, b) => router.route(a, b, style); +} + +function asRouteFn(r: SegmentContext | RouteFn): RouteFn { + if (typeof r === "function") return r; + const router = contextRouter(r); + return routeFnFor(router, r); +} + +/** The chain with consecutive repeats of a hex collapsed (they aren't steps). */ +export function dedupeSteps(hexes: readonly HexKey[]): HexKey[] { + const out: HexKey[] = []; + for (const h of hexes) if (out[out.length - 1] !== h) out.push(h); + return out; +} + +/** + * The fewest anchors (greedy, longest match first) whose routes reproduce + * `hexes`: from anchor i, take the largest j whose routed segment equals + * hexes[i..j] exactly (a fallback segment only counts for j = i + 1), else + * j = i + 1. Between neighbours the router always returns the direct step, + * so any neighbour-connected chain is reproduced exactly. Consecutive + * repeats are collapsed first. The first and last hexes are always anchors. + */ +export function anchorsFor( + hexes: readonly HexKey[], + route: SegmentContext | RouteFn, + grid?: Pick, +): HexKey[] { + const h = dedupeSteps(hexes); + if (h.length <= 1) return h; + const fn = asRouteFn(route); + // Only for skipping candidates that can't match (a route is never + // shorter than the hex distance); taken from the context when there is one. + const ctx = typeof route === "function" ? grid ?? null : route; + const anchors = [h[0]]; + let i = 0; + while (i < h.length - 1) { + let best = i + 1; + for (let j = h.length - 1; j > i + 1; j--) { + // A route is never shorter than the hex distance. + if (ctx && hexDistance(hexPair(h[i]), hexPair(h[j]), ctx.orientation, ctx.stagger) > j - i) continue; + const r = fn(h[i], h[j]); + if (r.fallback || r.hexes.length !== j - i + 1) continue; + let same = true; + for (let k = 0; k <= j - i; k++) { + if (r.hexes[k] !== h[i + k]) { same = false; break; } + } + if (same) { best = j; break; } + } + anchors.push(h[best]); + i = best; + } + return anchors; +} + +/** Whether `anchors` route to exactly `hexes` (consecutive repeats ignored). */ +export function reproduces(anchors: readonly HexKey[], hexes: readonly HexKey[], route: SegmentContext | RouteFn): boolean { + const fn = asRouteFn(route); + const want = dedupeSteps(hexes); + const got = routeBranch(anchors, { avoid: false, winding: false }, { route: (a, b) => { + const r = fn(a, b); + return { hexes: [...r.hexes] }; + } }).hexes; + return got.length === want.length && got.every((k, n) => k === want[n]); +} + +// ── Merging ────────────────────────────────────────────────────────────────── + +/** An undirected step "a|b" (a < b). */ +export function stepKey(a: HexKey, b: HexKey): string { + return a < b ? `${a}|${b}` : `${b}|${a}`; +} + +/** The set of undirected steps a set of chains draws. */ +export function stepsOf(chains: Iterable): Set { + const s = new Set(); + for (const c of chains) for (let i = 1; i < c.length; i++) if (c[i] !== c[i - 1]) s.add(stepKey(c[i - 1], c[i])); + return s; +} + +export interface MergedGroup { + /** Branch hex chains; branches[0] is the main line. */ + branches: HexKey[][]; + /** Indices (into the input) of the chains in this group, ascending. */ + members: number[]; + /** Members dropped because every one of their steps was already drawn. */ + duplicates: number[]; +} + +/** + * Merge chains (all of ONE type) that touch at an end: a chain whose first + * or last hex lies anywhere on another chain. Chains that only cross mid-way + * stay apart. Stroke-preserving: the longest chain of a group is the main + * line; a chain continuing a branch's tail is appended to it (reversed if + * needed; the main line can also grow at its head); a chain starting or + * ending on the path becomes a fork (reversed so it starts on the path); a + * chain whose every step is already drawn is dropped as a duplicate. The + * set of steps drawn is unchanged. Groups come out in order of their first + * member. Chains of fewer than 2 distinct hexes are each their own group. + */ +export function mergeChains(chains: readonly (readonly HexKey[])[]): MergedGroup[] { + const cs = chains.map(dedupeSteps); + const n = cs.length; + const parent = cs.map((_, i) => i); + const find = (i: number): number => (parent[i] === i ? i : (parent[i] = find(parent[i]))); + const sets = cs.map((c) => new Set(c)); + for (let a = 0; a < n; a++) { + if (cs[a].length < 2) continue; + const ends = [cs[a][0], cs[a][cs[a].length - 1]]; + for (let b = 0; b < n; b++) { + if (a === b || cs[b].length < 2) continue; + if (ends.some((e) => sets[b].has(e))) parent[find(a)] = find(b); + } + } + const groups = new Map(); + for (let i = 0; i < n; i++) { + const r = find(i); + const g = groups.get(r); + if (g) g.push(i); + else groups.set(r, [i]); + } + const out: MergedGroup[] = []; + for (const members of [...groups.values()].sort((x, y) => x[0] - y[0])) { + // Longest first; ties keep input order. + const pool = [...members].sort((x, y) => cs[y].length - cs[x].length || x - y); + const branches: HexKey[][] = [[...cs[pool.shift()!]]]; + const duplicates: number[] = []; + while (pool.length) { + const steps = stepsOf(branches); + const onPath = new Set(branches.flat()); + let placed = -1; + for (let p = 0; p < pool.length && placed < 0; p++) { + const c = cs[pool[p]]; + const first = c[0]; + const last = c[c.length - 1]; + if (c.length >= 2 && [...stepsOf([c])].every((s) => steps.has(s))) { + duplicates.push(pool[p]); + placed = p; + break; + } + for (const br of branches) { + const tail = br[br.length - 1]; + if (first === tail) { br.push(...c.slice(1)); placed = p; break; } + if (last === tail) { br.push(...[...c].reverse().slice(1)); placed = p; break; } + } + if (placed >= 0) break; + const main = branches[0]; + if (last === main[0]) { main.unshift(...c.slice(0, -1)); placed = p; break; } + if (first === main[0]) { main.unshift(...[...c].reverse().slice(0, -1)); placed = p; break; } + if (onPath.has(first)) { branches.push([...c]); placed = p; break; } + if (onPath.has(last)) { branches.push([...c].reverse()); placed = p; break; } + } + // Nothing attaches by an end yet (a chain touched only in its interior + // by a chain that is itself still waiting): take the first one that + // shares a hex with the path as its own stretch, else the first. + if (placed < 0) { + const touching = pool.findIndex((i) => cs[i].some((k) => onPath.has(k))); + placed = touching >= 0 ? touching : 0; + branches.push([...cs[pool[placed]]]); + } + pool.splice(placed, 1); + } + out.push({ branches, members: [...members].sort((x, y) => x - y), duplicates: duplicates.sort((x, y) => x - y) }); + } + return out; +} + +// ── Legacy compaction (the migration step) ─────────────────────────────────── + +export interface CompactReport { + pathsIn: number; + pathsOut: number; + branches: number; + anchors: number; + /** Merged groups: the new path's name and the legacy names it took in. */ + merged: { name: string; from: string[] }[]; + /** Legacy chains dropped because every step was already drawn by the path they joined. */ + duplicates: { name: string; into: string }[]; + /** One-hex leftovers dropped (no Notes, no extra columns). Still in the backup. */ + singlesDropped: { name: string; typeName: string; hex: HexKey }[]; + /** Paths whose new anchors don't reproduce the old steps (kept dense instead). */ + inexact: string[]; + /** Paths that combined differing Notes / extra values from merged chains. */ + combinedText: string[]; +} + +export interface CompactOptions { + /** Drop one-hex legacy paths that carry no Notes and no extra columns (Decision 2). */ + dropSingles: boolean; + /** The types' explicit routing style (see resolve.ts StyleFor). */ + styleFor?: StyleFor; + /** A cache for the map's routing context (optional). */ + cache?: RouteCache; +} + +const hasText = (p: MapPath) => !!p.notes?.trim() || Object.values(p.extra ?? {}).some((v) => v.trim()); + +/** Distinct non-empty values, joined; and whether more than one was combined. */ +function combine(values: (string | undefined)[]): [string | undefined, boolean] { + const seen: string[] = []; + for (const v of values) { + const t = v?.trim(); + if (t && !seen.includes(t)) seen.push(t); + } + return [seen.length ? seen.join("; ") : undefined, seen.length > 1]; +} + +/** + * The migration step for legacy paths (dense anchors, one branch each, as + * legacyChainsToPaths makes them): drop one-hex leftovers if asked (only + * those with no Notes and no extra columns), merge same-type paths that + * touch end-on, compress every branch with anchorsFor, and rename the + * results ``, ` 2`… in the old order. Every result is checked + * to route back to exactly the steps it came from; one that doesn't keeps + * its dense anchors and is listed in `inexact`. + * + * Paths that aren't legacy-shaped (several branches, or branch labels or + * extra columns) pass through unchanged. + */ +export function compactLegacy( + paths: readonly MapPath[], + ctx: RouteContext, + opts: CompactOptions, +): { paths: MapPath[]; report: CompactReport } { + const router: SegmentRouter = opts.cache ? opts.cache : contextRouter(ctx); + if (opts.cache) opts.cache.setContext(ctx); + const report: CompactReport = { + pathsIn: paths.length, pathsOut: 0, branches: 0, anchors: 0, + merged: [], duplicates: [], singlesDropped: [], inexact: [], combinedText: [], + }; + + const isLegacy = (p: MapPath) => + p.branches.length === 1 && !p.branches[0].label && !Object.keys(p.branches[0].extra ?? {}).length; + const isSingle = (p: MapPath) => isLegacy(p) && dedupeSteps(p.branches[0].anchors).length < 2; + + // Slots in input order; each holds the output path for that position (or null). + const slots: (MapPath | null)[] = paths.map(() => null); + const renamed: boolean[] = paths.map(() => false); + const byType = new Map(); + paths.forEach((p, i) => { + if (!isLegacy(p)) { + slots[i] = p; + return; + } + if (isSingle(p)) { + if (opts.dropSingles && !hasText(p)) { + report.singlesDropped.push({ name: p.name, typeName: p.typeName, hex: p.branches[0].anchors[0] }); + } else { + slots[i] = { ...p, branches: [{ anchors: dedupeSteps(p.branches[0].anchors) }] }; + renamed[i] = true; + } + return; + } + const list = byType.get(p.typeName); + if (list) list.push(i); + else byType.set(p.typeName, [i]); + }); + + for (const [typeName, idx] of byType) { + const style = styleOf(opts.styleFor, typeName); + const route = routeFnFor(router, style); + for (const g of mergeChains(idx.map((i) => paths[i].branches[0].anchors))) { + const members = g.members.map((m) => paths[idx[m]]); + const [notes, notesCombined] = combine(members.map((m) => m.notes)); + const extraKeys: string[] = []; + for (const m of members) for (const k of Object.keys(m.extra ?? {})) if (!extraKeys.includes(k)) extraKeys.push(k); + const extra: Record = {}; + let extraCombined = false; + for (const k of extraKeys) { + const [v, c] = combine(members.map((m) => m.extra?.[k])); + extra[k] = v ?? ""; + extraCombined ||= c; + } + const name = members[0].name; + const branches = g.branches.map((hexes) => { + const anchors = anchorsFor(hexes, route, ctx); + return reproduces(anchors, hexes, route) ? anchors : null; + }); + let exact = branches.every((b) => b !== null); + const finalBranches = g.branches.map((hexes, k) => ({ anchors: branches[k] ?? [...hexes] })); + // Segment-exact against the chains that went in. + if (exact) { + const want = stepsOf(g.members.map((m) => dedupeSteps(paths[idx[m]].branches[0].anchors))); + const got = stepsOf(finalBranches.map((b) => routeBranch(b.anchors, style, router).hexes)); + exact = want.size === got.size && [...want].every((s) => got.has(s)); + } + if (!exact) report.inexact.push(name); + const out: MapPath = { name, typeName, branches: finalBranches }; + if (notes !== undefined) out.notes = notes; + if (extraKeys.length) out.extra = extra; + if (notesCombined || extraCombined) report.combinedText.push(name); + const at = idx[g.members[0]]; + slots[at] = out; + renamed[at] = true; + if (g.members.length > 1) report.merged.push({ name, from: members.map((m) => m.name) }); + for (const d of g.duplicates) report.duplicates.push({ name: paths[idx[d]].name, into: name }); + } + } + + // Names: , 2… in the old order, unique against the paths + // that passed through unchanged. + const taken = slots.filter((p, i): p is MapPath => !!p && !renamed[i]).map((p) => p.name); + const finalNames = new Map(); + const result: MapPath[] = []; + slots.forEach((p, i) => { + if (!p) return; + if (renamed[i]) { + const name = uniquePathName(p.typeName, taken); + taken.push(name); + finalNames.set(p.name, name); + p = { ...p, name }; + } + result.push(p); + report.branches += p.branches.length; + for (const b of p.branches) report.anchors += b.anchors.length; + }); + const rename = (n: string) => finalNames.get(n) ?? n; + report.merged = report.merged.map((m) => ({ ...m, name: rename(m.name) })); + report.duplicates = report.duplicates.map((d) => ({ ...d, into: rename(d.into) })); + report.inexact = report.inexact.map(rename); + report.combinedText = report.combinedText.map(rename); + report.pathsOut = result.length; + return { paths: result, report }; +} diff --git a/src/paths/legacy.ts b/src/paths/legacy.ts new file mode 100644 index 00000000..cd4dcfe3 --- /dev/null +++ b/src/paths/legacy.ts @@ -0,0 +1,42 @@ +/** + * Legacy `| Type | Hexes |` rows (every hex stored) → anchored paths. + * Lossless and context-free: every hex becomes an anchor, so the path + * resolves to exactly the old chain (consecutive hexes are neighbours, and + * the router always returns the direct step between neighbours). Kept forever: + * the map-note reader uses it for old notes and pasted legacy tables. + * + * Compressing the dense anchors (and merging touching chains) needs terrain + * and the palette, so it's a separate step: compactLegacy in fromHexes.ts. + */ + +import type { MapPath, PathChain } from "../types"; +import { uniquePathName } from "./names"; + +/** + * One path per chain, in order. Names are `` for the first path of a + * type, then ` 2`, ` 3`… (unique ignoring case and spacing, also + * against `taken`). A legacy column named Notes (any case) becomes the + * path's notes; every other unknown column stays in `extra`. + */ +export function legacyChainsToPaths(chains: readonly PathChain[], taken: Iterable = []): MapPath[] { + const names = [...taken]; + const out: MapPath[] = []; + for (const c of chains) { + const name = uniquePathName(c.typeName, names); + names.push(name); + const path: MapPath = { name, typeName: c.typeName, branches: [{ anchors: [...c.hexes] }] }; + if (c.extra) { + const extra: Record = {}; + for (const [k, v] of Object.entries(c.extra)) { + if (k.trim().toLowerCase() === "notes" && path.notes === undefined) { + if (v.trim()) path.notes = v; + } else { + extra[k] = v; + } + } + if (Object.keys(extra).length) path.extra = extra; + } + out.push(path); + } + return out; +} diff --git a/src/paths/mapContext.ts b/src/paths/mapContext.ts new file mode 100644 index 00000000..b732e368 --- /dev/null +++ b/src/paths/mapContext.ts @@ -0,0 +1,90 @@ +/** + * A map's routing inputs, built in ONE place so every reader routes a map's + * paths the same way (MapStore's migration and compatibility view now, the + * plugin's paths service and the PNG export later). Pure, no Obsidian imports. + * + * Routes depend only on: orientation, stagger, the map's bounds, the hexes + * whose SHOWN terrain (own, else the map's base terrain) is impassable in + * the map's palette, and each path type's explicit style fields. Nothing + * here looks at a path's or a type's name. + */ + +import type { HexKey } from "../types"; +import { DEFAULT_SEGMENT_STYLE, type RouteContext, type SegmentStyle } from "./router"; +import type { StyleFor } from "./resolve"; +import { hexKey, hexXY } from "../hexKey"; + +export interface MapRouteInput { + orientation: "flat" | "pointy"; + stagger: "odd" | "even"; + gridSize: { cols: number; rows: number }; + gridOffset: { x: number; y: number }; + /** Terrain shown on hexes without their own. */ + baseTerrain?: string; + /** Hexes with their own terrain (hex key → terrain name). */ + terrainOf: Iterable<[HexKey, { terrain?: string } | undefined]>; + /** Names of the palette's impassable terrains. */ + impassable: Iterable; +} + +/** The routing context of a map (see the module comment). */ +export function mapRouteContext(m: MapRouteInput): RouteContext { + const bounds = { + minX: m.gridOffset.x, + minY: m.gridOffset.y, + maxX: m.gridOffset.x + m.gridSize.cols - 1, + maxY: m.gridOffset.y + m.gridSize.rows - 1, + }; + const impassable = new Set(m.impassable); + const blocked = new Set(); + if (impassable.size) { + const own = new Map(); + for (const [k, h] of m.terrainOf) own.set(k, h?.terrain || undefined); + const shown = (k: HexKey) => own.get(k) ?? m.baseTerrain; + if (m.baseTerrain && impassable.has(m.baseTerrain)) { + // Every hex without its own terrain shows the base: walk the grid. + for (let y = bounds.minY; y <= bounds.maxY; y++) { + for (let x = bounds.minX; x <= bounds.maxX; x++) { + const k = hexKey(x, y); + const t = shown(k); + if (t && impassable.has(t)) blocked.add(k); + } + } + } else { + for (const [k, t] of own) { + if (!t || !impassable.has(t)) continue; + const { x, y } = hexXY(k); + if (x >= bounds.minX && x <= bounds.maxX && y >= bounds.minY && y <= bounds.maxY) blocked.add(k); + } + } + } + return { orientation: m.orientation, stagger: m.stagger, bounds, blocked }; +} + +/** What the style needs of a path type (PA5's explicit fields, when present). */ +export interface PathTypeStyleFields { + name: string; + /** Explicit "go around impassable terrain" (PA5 makes it required). */ + avoidImpassable?: boolean; + /** PA5's auto-route style: "direct" | "winding". */ + autoRoute?: string; +} + +/** + * A StyleFor from a palette's path types, reading ONLY their explicit + * fields: `avoidImpassable` when set, `autoRoute === "winding"`. A field + * that isn't there (palettes from before PA5) takes DEFAULT_SEGMENT_STYLE's + * value, never a guess from the type's name. A type not in the list is + * undefined (the resolver uses DEFAULT_SEGMENT_STYLE). + */ +export function pathTypeStyleFor(types: readonly PathTypeStyleFields[]): StyleFor { + const byName = new Map(); + for (const t of types) { + if (byName.has(t.name)) continue; + byName.set(t.name, { + avoid: typeof t.avoidImpassable === "boolean" ? t.avoidImpassable : DEFAULT_SEGMENT_STYLE.avoid, + winding: t.autoRoute === undefined ? DEFAULT_SEGMENT_STYLE.winding : t.autoRoute === "winding", + }); + } + return (name) => byName.get(name); +} diff --git a/src/paths/mapPaths.ts b/src/paths/mapPaths.ts new file mode 100644 index 00000000..ab2aed03 --- /dev/null +++ b/src/paths/mapPaths.ts @@ -0,0 +1,18 @@ +/** + * The ONE place a map's stored paths are read as anchored MapPaths. + * Pure, no Obsidian imports. + */ + +import type { MapData, MapPath } from "../types"; +import { legacyChainsToPaths } from "./legacy"; + +/** + * A map's stored paths: `MapData.paths`, which MapStore loads from the map + * note (format 5) and keeps in step with edits made through `pathChains`. + * A map the store holds no paths for (its note can't be read, so its paths + * are still only data.json's chains) falls back to those chains, each one + * path with every hex as an anchor (lossless: it resolves to the old chain). + */ +export function storedMapPaths(map: Partial>): MapPath[] { + return map.paths ?? legacyChainsToPaths(map.pathChains ?? []); +} diff --git a/src/paths/names.ts b/src/paths/names.ts new file mode 100644 index 00000000..9a51a8ec --- /dev/null +++ b/src/paths/names.ts @@ -0,0 +1,26 @@ +/** + * Path names: unique within a map, compared ignoring case and spacing + * (a Path routes row matches its Paths row the same way). Names are labels + * only; nothing behaves differently because of what a path is called. + */ + +/** The comparison key of a path name: trimmed, lower case, runs of spaces collapsed. */ +export function pathNameKey(name: string): string { + return name.trim().replace(/\s+/g, " ").toLowerCase(); +} + +/** + * The first free name among `base`, `base 2`, `base 3`… (the smallest unused + * number), against `taken` (any names; compared with pathNameKey). + * An empty base becomes "Path". + */ +export function uniquePathName(base: string, taken: Iterable): string { + const stem = base.trim().replace(/\s+/g, " ") || "Path"; + const used = new Set(); + for (const n of taken) used.add(pathNameKey(n)); + if (!used.has(pathNameKey(stem))) return stem; + for (let i = 2; ; i++) { + const candidate = `${stem} ${i}`; + if (!used.has(pathNameKey(candidate))) return candidate; + } +} diff --git a/src/paths/pathColumns.ts b/src/paths/pathColumns.ts new file mode 100644 index 00000000..ef86ada3 --- /dev/null +++ b/src/paths/pathColumns.ts @@ -0,0 +1,39 @@ +/** + * Extra columns of a map note's Paths table, read by header ignoring case + * and spacing. The map-note format keeps every column it doesn't know; + * these helpers read and set one. `Overworld path` (a region path + * projected from an overworld path) is read here too, so regeneration + * keeps such paths whether or not World maps is built (off hides, never + * deletes). Pure. + */ + +import type { MapPath } from "../types"; + +/** Region Paths column: the overworld path a projected path came from. */ +export const OWNER_COL = "Overworld path"; + +/** An extra column's value, by header ignoring case and spacing. */ +export function extraCell(extra: Record | undefined, header: string): string | undefined { + if (!extra) return undefined; + const want = header.toLowerCase().replace(/\s+/g, ""); + for (const [h, v] of Object.entries(extra)) if (h.toLowerCase().replace(/\s+/g, "") === want) return v; + return undefined; +} + +/** `extra` with one column set (or removed, for undefined), keeping the header as the note spells it. */ +export function withExtraCell(extra: Record | undefined, header: string, value: string | undefined): Record | undefined { + const out: Record = {}; + let spelled = header; + const want = header.toLowerCase().replace(/\s+/g, ""); + for (const [h, v] of Object.entries(extra ?? {})) { + if (h.toLowerCase().replace(/\s+/g, "") === want) spelled = h; + else out[h] = v; + } + if (value) out[spelled] = value; + return Object.keys(out).length ? out : undefined; +} + +/** The overworld path a region path was projected from, if any. */ +export function ownerOf(p: Pick): string | undefined { + return extraCell(p.extra, OWNER_COL)?.trim() || undefined; +} diff --git a/src/paths/pathGeometry.ts b/src/paths/pathGeometry.ts new file mode 100644 index 00000000..49ce1d40 --- /dev/null +++ b/src/paths/pathGeometry.ts @@ -0,0 +1,468 @@ +/** + * Path geometry in LATTICE units: resolved hex chains → the polylines the + * map view and the PNG export draw. Pure, no Obsidian or DOM imports. + * + * The lattice is the hex grid with cell radius R = 1 (hexGeometry.hexCenter + * at radius 1, absolute "x_y" coordinates). Everything here (points, stroke + * widths, dashes, lane gaps, end dots) is in those units, so a polyline is + * the same at every zoom and in every export; only the final affine differs + * (screen: lattice → em, measured once per grid; PNG: × the export's R). + * + * Nothing here reads the DOM, the zoom or a path's name. + */ + +import type { HexKey, PathType } from "../types"; +import type { ResolvedBranch } from "./resolve"; +import { computeLaneOffsets, hexCenter, offsetPolyline } from "../hex-map/hexGeometry"; + +export type Pt = { cx: number; cy: number }; + +/** The map's hex radius on screen at zoom 1, px (2.2em at 16px). Path type + * widths are in screen px at that size, so width / this = lattice units. */ +export const SCREEN_HEX_RADIUS = 35.2; + +/** Ties in geometry compare within this (exact lattice coords + float noise). */ +export const GEOM_EPS = 1e-9; + +export interface LatticeGrid { + orientation: "flat" | "pointy"; + stagger: "odd" | "even"; +} + +/** px at the default zoom → lattice units. */ +export function pxToLattice(px: number): number { + return px / SCREEN_HEX_RADIUS; +} + +const parseKey = (key: HexKey): [number, number] => { + const i = key.indexOf("_"); + return [Number(key.slice(0, i)), Number(key.slice(i + 1))]; +}; + +/** Centre of hex `key` on the lattice (cell radius 1, absolute coordinates). */ +export function latticeCenter(key: HexKey, grid: LatticeGrid): Pt { + const [x, y] = parseKey(key); + return hexCenter(x, y, grid.orientation, 1, grid.stagger); +} + +/** Where two touching hexes share an edge. */ +const mid = (a: Pt, b: Pt): Pt => ({ cx: (a.cx + b.cx) / 2, cy: (a.cy + b.cy) / 2 }); + +// ── Drawing styles ─────────────────────────────────────────────────────────── + +/** "through": hex centres. */ +export function throughPoints(hexes: readonly HexKey[], grid: LatticeGrid): Pt[] { + return hexes.map((k) => latticeCenter(k, grid)); +} + +/** "meander": edge midpoints (curved by the smooth path); centres below 3 hexes. */ +export function meanderPoints(hexes: readonly HexKey[], grid: LatticeGrid): Pt[] { + const c = throughPoints(hexes, grid); + if (c.length < 3) return c; + const pts: Pt[] = []; + for (let i = 0; i < c.length - 1; i++) pts.push(mid(c[i], c[i + 1])); + return pts; +} + +/** Angle of vertex 0: flat-top 0°, pointy-top 30°. Vertices go clockwise (y down). */ +const vStartOf = (isFlat: boolean) => (isFlat ? 0 : Math.PI / 6); + +function hexVertices(c: Pt, isFlat: boolean, r: number): Pt[] { + const v0 = vStartOf(isFlat); + return Array.from({ length: 6 }, (_, i) => ({ + cx: c.cx + r * Math.cos(v0 + (i * Math.PI) / 3), + cy: c.cy + r * Math.sin(v0 + (i * Math.PI) / 3), + })); +} + +/** Shorter arc of vertex indices on the 6-cycle, both ends included (cw on a tie). */ +function shortArc(from: number, to: number): number[] { + if (from === to) return [from]; + const cw = (to - from + 6) % 6; + const ccw = (from - to + 6) % 6; + const out: number[] = []; + if (cw <= ccw) for (let k = 0; k <= cw; k++) out.push((from + k) % 6); + else for (let k = 0; k <= ccw; k++) out.push((from - k + 6) % 6); + return out; +} + +/** + * "edge": along the hex outlines, from centre to centre. `centers` are + * consecutive neighbours; `r` is the CELL radius (on the lattice 1, so the + * outline runs down the middle of the gap between hexes and two + * neighbours' vertices coincide). Ties (equal turn cost, equal distance) + * compare within GEOM_EPS and the lower index wins, so the same chain gives + * the same outline at every scale. + */ +export function edgePointsFromCenters(centers: readonly Pt[], isFlat: boolean, r: number): Pt[] { + if (centers.length < 2) return [...centers]; + const n = centers.length; + const TAU = 2 * Math.PI; + const v0 = vStartOf(isFlat); + const eps = GEOM_EPS * Math.max(1, r * r); + + // Edge of centers[i]'s hex facing centers[i+1] (edge i spans vertex i → i+1). + const snapEdge = (theta: number): number => { + let best = 0; + let bestD = Infinity; + for (let i = 0; i < 6; i++) { + const m = v0 + (i + 0.5) * (Math.PI / 3); + let d = (((theta - m) % TAU) + TAU) % TAU; + if (d > Math.PI) d = TAU - d; + if (d < bestD - GEOM_EPS) { + bestD = d; + best = i; + } + } + return best; + }; + const edgeIdx = centers.slice(0, -1).map((A, i) => { + const B = centers[i + 1]; + return snapEdge(Math.atan2(B.cy - A.cy, B.cx - A.cx)); + }); + + // Which of the two shared vertices each edge crossing uses: least turn + // (look-ahead one edge); the last edge takes the vertex nearer the line so far. + const choice: number[] = new Array(n - 1).fill(0); + let prev: Pt = centers[0]; + for (let i = 0; i < n - 1; i++) { + const vA = hexVertices(centers[i], isFlat, r); + const Va = vA[edgeIdx[i]]; + const Vb = vA[(edgeIdx[i] + 1) % 6]; + if (i < n - 2) { + const vB = hexVertices(centers[i + 1], isFlat, r); + const VaN = vB[edgeIdx[i + 1]]; + const VbN = vB[(edgeIdx[i + 1] + 1) % 6]; + const cost = (v: Pt, vn: Pt) => + Math.abs((v.cx - prev.cx) * (vn.cy - v.cy) - (v.cy - prev.cy) * (vn.cx - v.cx)); + let bestCost = Infinity; + let bestC = 0; + for (const [v, ci] of [[Va, 0], [Vb, 1]] as [Pt, number][]) { + for (const vn of [VaN, VbN]) { + const co = cost(v, vn); + if (co < bestCost - eps) { + bestCost = co; + bestC = ci; + } + } + } + choice[i] = bestC; + prev = vA[(edgeIdx[i] + bestC) % 6]; + } else { + const dA = (Va.cx - prev.cx) ** 2 + (Va.cy - prev.cy) ** 2; + const dB = (Vb.cx - prev.cx) ** 2 + (Vb.cy - prev.cy) ** 2; + choice[i] = dA <= dB + eps ? 0 : 1; + } + } + + // Each inner hex: the shorter arc of its outline from the entry vertex to + // the exit vertex. The entry vertex on hex k matching vertex + // (edgeIdx + choice) of hex k-1 is (edgeIdx + 4 - choice) % 6. + const result: Pt[] = [centers[0]]; + for (let k = 0; k < n; k++) { + const verts = hexVertices(centers[k], isFlat, r); + if (k === 0) { + result.push(verts[(edgeIdx[0] + choice[0]) % 6]); + } else if (k === n - 1) { + result.push(verts[(edgeIdx[n - 2] + 4 - choice[n - 2]) % 6]); + result.push(centers[k]); + } else { + const entry = (edgeIdx[k - 1] + 4 - choice[k - 1]) % 6; + const exit = (edgeIdx[k] + choice[k]) % 6; + const arc = shortArc(entry, exit); + for (let j = 1; j < arc.length; j++) result.push(verts[arc[j]]); + } + } + return result; +} + +/** "edge" on the lattice. */ +export function edgePoints(hexes: readonly HexKey[], grid: LatticeGrid): Pt[] { + return edgePointsFromCenters(throughPoints(hexes, grid), grid.orientation === "flat", 1); +} + +export type PathRouting = PathType["routing"]; + +/** One chain's polyline in a drawing style (lattice units). */ +export function chainPoints(hexes: readonly HexKey[], routing: PathRouting, grid: LatticeGrid): Pt[] { + if (routing === "meander") return meanderPoints(hexes, grid); + if (routing === "edge") return edgePoints(hexes, grid); + return throughPoints(hexes, grid); +} + +/** Smooth (curved through the points) or sharp, per drawing style. */ +export function isSmooth(routing: PathRouting): boolean { + return routing !== "edge"; +} + +// ── Forks and joins ────────────────────────────────────────────────────────── + +const near = (a: Pt, b: Pt, tol = 1e-6) => Math.abs(a.cx - b.cx) <= tol && Math.abs(a.cy - b.cy) <= tol; + +/** + * Where a branch that starts on another branch of its path (a fork) begins, + * so it leaves the parent's line instead of floating beside it: + * - through: the fork hex's centre (already shared, nothing to do); + * - meander: the midpoint between the fork hex and the parent's neighbour + * (in the parent chain) whose direction is closest to the fork's first + * step: a Y-shaped split; + * - edge: the vertex of the fork hex on the parent's outline nearest the + * fork's own exit vertex, then round the fork hex's outline to it. + * + * Returns the fork's points with its start adjusted (a new array), or the + * points unchanged. `parentIdx` is the fork hex's index in `parentHexes`. + */ +export function joinForkStart( + forkPts: readonly Pt[], + forkHexes: readonly HexKey[], + parentHexes: readonly HexKey[], + parentIdx: number, + parentPts: readonly Pt[], + routing: PathRouting, + grid: LatticeGrid, +): Pt[] { + if (forkHexes.length < 2 || forkPts.length < 1) return [...forkPts]; + if (routing === "meander") { + if (parentHexes.length < 3) return [...forkPts]; // parent drawn through centres + const c0 = latticeCenter(forkHexes[0], grid); + const c1 = latticeCenter(forkHexes[1], grid); + const sx = c1.cx - c0.cx; + const sy = c1.cy - c0.cy; + let best: Pt | null = null; + let bestDot = -Infinity; + for (const j of [parentIdx - 1, parentIdx + 1]) { + if (j < 0 || j >= parentHexes.length) continue; + const c = latticeCenter(parentHexes[j], grid); + const dx = c.cx - c0.cx; + const dy = c.cy - c0.cy; + const len = Math.hypot(dx, dy) || 1; + const dot = (dx * sx + dy * sy) / len; + if (dot > bestDot + GEOM_EPS) { + bestDot = dot; + best = c; + } + } + return best ? [mid(c0, best), ...forkPts] : [...forkPts]; + } + if (routing === "edge") { + const isFlat = grid.orientation === "flat"; + const c0 = latticeCenter(forkHexes[0], grid); + if (parentPts.some((p) => near(p, c0))) return [...forkPts]; // parent ends here + if (forkPts.length < 2) return [...forkPts]; + const exit = forkPts[1]; + let best: Pt | null = null; + let bestD = Infinity; + for (const p of parentPts) { + if (Math.abs(Math.hypot(p.cx - c0.cx, p.cy - c0.cy) - 1) > 1e-6) continue; + const d = (p.cx - exit.cx) ** 2 + (p.cy - exit.cy) ** 2; + if (d < bestD - GEOM_EPS) { + bestD = d; + best = p; + } + } + if (!best) return [...forkPts]; + const v0 = vStartOf(isFlat); + const idxOf = (p: Pt) => { + const a = Math.atan2(p.cy - c0.cy, p.cx - c0.cx) - v0; + return ((Math.round(a / (Math.PI / 3)) % 6) + 6) % 6; + }; + const verts = hexVertices(c0, isFlat, 1); + const arc = shortArc(idxOf(best), idxOf(exit)); + return [...arc.slice(0, -1).map((i) => verts[i]), ...forkPts.slice(1)]; + } + return [...forkPts]; +} + +// ── Strokes ────────────────────────────────────────────────────────────────── + +/** Stroke dash patterns in px at the default zoom (as the map always drew them). */ +export const DASH_PX: Record = { dashed: [8, 4], dotted: [2, 4] }; + +/** The end dot of the path being drawn: radius and outline, px at the default zoom. */ +export const END_DOT_PX = { r: 5, stroke: 1.5 }; + +/** The path tool's anchor handles on the selected path: radius (ends bigger) and outline, px at the default zoom. */ +export const HANDLE_PX = { r: 5, end: 7.5, stroke: 1.5 }; + +export interface PathStroke { + /** MapPath.name and branch index (data-path / data-branch on screen). */ + path: string; + branch: number; + typeName: string; + /** Lattice units; lane offset applied. */ + pts: Pt[]; + smooth: boolean; + color: string; + /** Stroke width, lattice units. */ + width: number; + /** Dash pattern, lattice units ([] = solid). */ + dash: number[]; +} + +export interface StrokeOptions { + /** For a type not in the palette (drawn plain grey under its own name). */ + unknownType: PathType; + /** + * The hex just across the seam (in this map's frame) where a branch end + * meets a neighbour's path of the same type, if any: that end is drawn on + * to the shared edge (round 6 U8). Not for the edge style. + */ + seamEnd?: (typeName: string, hex: HexKey) => HexKey | undefined; + /** Multiplies lane gaps (an export drawn bolder keeps lanes apart). Default 1. */ + laneScale?: number; + /** + * Fog (HF11): only the parts of a path between hexes this says are shown + * are drawn (a step from a shown hex into a hidden one isn't). Unset: all. + */ + visible?: (hex: HexKey) => boolean; +} + +/** + * The branches cut to their runs of shown hexes (`visible`): a step is + * kept only when both its hexes are shown, so a road stops at the fog. A + * cut branch loses its fork and join ties (its runs start and end where + * the fog does), and so does a branch tied to one that was cut. + */ +export function visibleBranches(resolved: readonly ResolvedBranch[], visible: (hex: HexKey) => boolean): ResolvedBranch[] { + const out: ResolvedBranch[] = []; + const cut = new Set(); + const id = (path: string, branch: number) => `${path}\u0000${branch}`; + for (const rb of resolved) { + if (rb.hexes.every(visible)) { out.push(rb); continue; } + cut.add(id(rb.path, rb.branch)); + let run: HexKey[] = []; + const flush = () => { + if (run.length >= 2) out.push({ ...rb, hexes: run, anchorIdx: [0, run.length - 1], forkFrom: undefined, joinTo: undefined, fallbackSegments: [] }); + run = []; + }; + for (const h of rb.hexes) { + if (visible(h)) run.push(h); + else flush(); + } + flush(); + } + return out.map((rb) => { + const forkCut = rb.forkFrom && cut.has(id(rb.path, rb.forkFrom.branch)); + const joinCut = rb.joinTo && cut.has(id(rb.path, rb.joinTo.branch)); + return forkCut || joinCut ? { ...rb, ...(forkCut ? { forkFrom: undefined } : {}), ...(joinCut ? { joinTo: undefined } : {}) } : rb; + }); +} + +/** + * Resolved branches → strokes, in draw order: the palette's type order, + * then types not in the palette (first seen first); within a type, the + * resolver's order. Lanes (computeLaneOffsets) separate different types + * sharing a route; same-type branches share a lane and merge. + */ +export function buildPathStrokes( + allResolved: readonly ResolvedBranch[], + types: readonly PathType[], + grid: LatticeGrid, + opts: StrokeOptions, +): PathStroke[] { + const resolved = opts.visible ? visibleBranches(allResolved, opts.visible) : allResolved; + const typeByName = new Map(); + for (const t of types) if (!typeByName.has(t.name)) typeByName.set(t.name, t); + const order: { rb: ResolvedBranch; pt: PathType }[] = []; + for (const t of typeByName.values()) { + for (const rb of resolved) if (rb.typeName === t.name) order.push({ rb, pt: t }); + } + const unknown: string[] = []; + for (const rb of resolved) if (!typeByName.has(rb.typeName) && !unknown.includes(rb.typeName)) unknown.push(rb.typeName); + for (const name of unknown) { + for (const rb of resolved) if (rb.typeName === name) order.push({ rb, pt: { ...opts.unknownType, name } }); + } + + const lanes = computeLaneOffsets(order.map(({ rb, pt }) => ({ hexes: rb.hexes, width: pt.width, typeName: pt.name }))); + const laneScale = opts.laneScale ?? 1; + + // Each branch's own polyline first (forks need their parent's). + const own = order.map(({ rb, pt }) => chainPoints(rb.hexes, pt.routing, grid)); + const indexOf = new Map(); + order.forEach(({ rb }, i) => indexOf.set(`${rb.path}\u0000${rb.branch}`, i)); + const parentOf = (rb: ResolvedBranch, branch: number) => indexOf.get(`${rb.path}\u0000${branch}`); + + const out: PathStroke[] = []; + order.forEach(({ rb, pt }, i) => { + let pts = own[i]; + if (rb.forkFrom) { + const p = parentOf(rb, rb.forkFrom.branch); + if (p !== undefined) pts = joinForkStart(pts, rb.hexes, order[p].rb.hexes, rb.forkFrom.hexIdx, own[p], pt.routing, grid); + } + if (rb.joinTo) { + const p = parentOf(rb, rb.joinTo.branch); + if (p !== undefined) { + pts = joinForkStart([...pts].reverse(), [...rb.hexes].reverse(), order[p].rb.hexes, rb.joinTo.hexIdx, own[p], pt.routing, grid).reverse(); + } + } + if (pt.routing !== "edge" && opts.seamEnd && pts.length >= 1) { + const head = rb.forkFrom ? undefined : opts.seamEnd(pt.name, rb.hexes[0]); + const last = rb.hexes[rb.hexes.length - 1]; + const tail = rb.hexes.length > 1 && !rb.joinTo ? opts.seamEnd(pt.name, last) : undefined; + if (head) pts = [mid(latticeCenter(rb.hexes[0], grid), latticeCenter(head, grid)), ...pts]; + if (tail) pts = [...pts, mid(latticeCenter(last, grid), latticeCenter(tail, grid))]; + } + if (pts.length < 2) return; + pts = offsetPolyline(pts, pxToLattice(lanes[i]) * laneScale); + out.push({ + path: rb.path, + branch: rb.branch, + typeName: pt.name, + pts, + smooth: isSmooth(pt.routing), + color: pt.color, + width: pxToLattice(pt.width), + dash: (DASH_PX[pt.lineStyle] ?? []).map(pxToLattice), + }); + }); + return out; +} + +// ── Affine (lattice → screen / export) ─────────────────────────────────────── + +/** An axis-aligned affine: X = tx + x·sx, Y = ty + y·sy. */ +export interface LatticeAffine { + sx: number; + sy: number; + tx: number; + ty: number; +} + +export function applyAffine(pts: readonly Pt[], a: LatticeAffine): Pt[] { + return pts.map((p) => ({ cx: a.tx + p.cx * a.sx, cy: a.ty + p.cy * a.sy })); +} + +/** + * The affine mapping lattice centres onto measured centres: the origin hex + * `o`, its right neighbour (x+1, same y) and the hex below (same x, y+1). + * Either neighbour may be missing (a one-column or one-row grid): its scale + * is then the other one's, else `fallback`. + */ +export function calibrateAffine( + origin: { key: HexKey; at: { x: number; y: number } }, + right: { key: HexKey; at: { x: number; y: number } } | null, + below: { key: HexKey; at: { x: number; y: number } } | null, + grid: LatticeGrid, + fallback: number, +): LatticeAffine { + const lo = latticeCenter(origin.key, grid); + let sx = 0; + let sy = 0; + if (right) { + const lr = latticeCenter(right.key, grid); + if (Math.abs(lr.cx - lo.cx) > GEOM_EPS) sx = (right.at.x - origin.at.x) / (lr.cx - lo.cx); + } + if (below) { + const lb = latticeCenter(below.key, grid); + if (Math.abs(lb.cy - lo.cy) > GEOM_EPS) sy = (below.at.y - origin.at.y) / (lb.cy - lo.cy); + } + if (!sx) sx = sy || fallback; + if (!sy) sy = sx; + return { sx, sy, tx: origin.at.x - lo.cx * sx, ty: origin.at.y - lo.cy * sy }; +} + +/** Round for SVG output: fixed decimals keep `d` stable and short. */ +export function fmt(n: number): string { + const r = Math.round(n * 1e4) / 1e4; + return Object.is(r, -0) ? "0" : String(r); +} diff --git a/src/paths/resolve.ts b/src/paths/resolve.ts new file mode 100644 index 00000000..38ebdc01 --- /dev/null +++ b/src/paths/resolve.ts @@ -0,0 +1,124 @@ +/** + * Anchored paths → routed hex chains. Pure: the result depends only on the + * paths, the map's routing context and each type's explicit style flags. + * + * Callers must not resolve a map's paths until its terrain AND palette are + * loaded (otherwise `blocked` is incomplete and routes jump when it arrives). + */ + +import type { HexKey, MapPath, PathChain } from "../types"; +import { DEFAULT_SEGMENT_STYLE, type RouteContext, type SegmentStyle } from "./router"; +import { contextRouter, RouteCache, type SegmentRouter } from "./routeCache"; + +/** + * A path type's routing style, looked up by the path's typeName (a + * reference into the palette; never interpreted). Return undefined for a + * type that isn't in the palette (DEFAULT_SEGMENT_STYLE is used). + * + * WIRING POINT for the explicit PathType fields (fix/46-palettes-generators + * PA5): the plugin's paths service / the MapStore migration hook builds this + * from the map's palette as + * (name) => { const t = palette.pathTypes.find((p) => p.name === name); + * return t && { avoid: t.avoidImpassable, winding: }; } + * Nothing else reads avoid or winding. + */ +export type StyleFor = (typeName: string) => SegmentStyle | undefined; + +export function styleOf(styleFor: StyleFor | undefined, typeName: string): SegmentStyle { + return styleFor?.(typeName) ?? DEFAULT_SEGMENT_STYLE; +} + +export interface ResolvedBranch { + /** MapPath.name */ + path: string; + typeName: string; + /** Index into the path's branches. */ + branch: number; + /** Full routed chain, anchors included, joints not duplicated. */ + hexes: HexKey[]; + /** Index into hexes of each anchor (non-decreasing). */ + anchorIdx: number[]; + /** When anchors[0] lies on another branch of the path (a fork). */ + forkFrom?: { branch: number; hexIdx: number }; + /** When the last anchor lies on another branch (a join: loops, reconnecting roads). */ + joinTo?: { branch: number; hexIdx: number }; + /** Segments (i = anchors i → i+1) drawn with the hex-line fallback. */ + fallbackSegments: number[]; +} + +/** One branch's anchors → its routed hexes. */ +export function routeBranch( + anchors: readonly HexKey[], + style: SegmentStyle, + router: SegmentRouter, +): { hexes: HexKey[]; anchorIdx: number[]; fallbackSegments: number[] } { + const hexes: HexKey[] = []; + const anchorIdx: number[] = []; + const fallbackSegments: number[] = []; + if (!anchors.length) return { hexes, anchorIdx, fallbackSegments }; + hexes.push(anchors[0]); + anchorIdx.push(0); + for (let i = 1; i < anchors.length; i++) { + const seg = router.route(anchors[i - 1], anchors[i], style); + if (seg.fallback) fallbackSegments.push(i - 1); + for (let k = 1; k < seg.hexes.length; k++) hexes.push(seg.hexes[k]); + anchorIdx.push(hexes.length - 1); + } + return { hexes, anchorIdx, fallbackSegments }; +} + +/** Where `hex` lies on another branch (lowest branch, then first index), if anywhere. */ +function onOtherBranch(hex: HexKey, self: number, chains: readonly HexKey[][]): { branch: number; hexIdx: number } | undefined { + for (let b = 0; b < chains.length; b++) { + if (b === self) continue; + const i = chains[b].indexOf(hex); + if (i >= 0) return { branch: b, hexIdx: i }; + } + return undefined; +} + +/** One path's branches, resolved. Empty branches resolve to no hexes (and no entry). */ +export function resolvePath(path: MapPath, router: SegmentRouter, styleFor?: StyleFor): ResolvedBranch[] { + const style = styleOf(styleFor, path.typeName); + const routed = path.branches.map((b) => routeBranch(b.anchors, style, router)); + const chains = routed.map((r) => r.hexes); + const out: ResolvedBranch[] = []; + routed.forEach((r, branch) => { + if (!r.hexes.length) return; + const rb: ResolvedBranch = { path: path.name, typeName: path.typeName, branch, ...r }; + const fork = onOtherBranch(r.hexes[0], branch, chains); + if (fork) rb.forkFrom = fork; + if (r.hexes.length > 1) { + const join = onOtherBranch(r.hexes[r.hexes.length - 1], branch, chains); + if (join) rb.joinTo = join; + } + out.push(rb); + }); + return out; +} + +/** + * Every path's branches, resolved, in path then branch order. Pass the map's + * RouteCache to reuse segments across calls (its context is switched to + * `ctx`; a changed context keeps the old routes as cache.previous()). + */ +export function resolvePaths( + paths: readonly MapPath[], + ctx: RouteContext, + styleFor?: StyleFor, + cache?: RouteCache, +): ResolvedBranch[] { + let router: SegmentRouter; + if (cache) { + cache.setContext(ctx); + router = cache; + } else { + router = contextRouter(ctx); + } + return paths.flatMap((p) => resolvePath(p, router, styleFor)); +} + +/** The resolved branches as the old PathChain shape (for read-only consumers). */ +export function resolvedToChains(resolved: readonly ResolvedBranch[]): PathChain[] { + return resolved.map((r) => ({ typeName: r.typeName, hexes: [...r.hexes] })); +} diff --git a/src/paths/routeCache.ts b/src/paths/routeCache.ts new file mode 100644 index 00000000..46a8335e --- /dev/null +++ b/src/paths/routeCache.ts @@ -0,0 +1,121 @@ +/** + * Segment route cache for one map. Routes are keyed `a>b|style` under the + * map's current context signature (router version, orientation, stagger, + * bounds, blocked hexes). A context change drops the segments but keeps + * them as the "previous" routes, which the pin check (edit.ts pinChanged) + * compares against so an unrelated edit never silently moves a path. + * Pure, no Obsidian imports. + */ + +import type { HexKey } from "../types"; +import { + contextSignature, + routeSegment, + type RouteContext, + type SegmentRoute, + type SegmentStyle, +} from "./router"; + +/** Anything that can route a segment under some fixed context. */ +export interface SegmentRouter { + route(a: HexKey, b: HexKey, style: SegmentStyle): SegmentRoute; +} + +/** The cache key of a segment: its ends (direction matters) and the style flags. */ +export function segmentKey(a: HexKey, b: HexKey, style: SegmentStyle): string { + return `${a}>${b}|${style.avoid ? "a" : "-"}${style.winding ? "w" : "-"}`; +} + +/** An uncached router for a context. */ +export function contextRouter(ctx: RouteContext): SegmentRouter { + return { route: (a, b, style) => routeSegment(a, b, { ...ctx, ...style }) }; +} + +/** Past this many segments the cache starts over (a long drag on a big map). */ +const MAX_SEGMENTS = 50_000; + +interface Generation { + ctx: RouteContext; + sig: string; + segs: Map; +} + +function cachedRoute(gen: Generation, a: HexKey, b: HexKey, style: SegmentStyle): SegmentRoute { + const k = segmentKey(a, b, style); + let r = gen.segs.get(k); + if (!r) { + r = routeSegment(a, b, { ...gen.ctx, ...style }); + if (gen.segs.size >= MAX_SEGMENTS) gen.segs.clear(); + gen.segs.set(k, r); + } + return r; +} + +/** + * Routes are returned by reference: callers must not mutate them (resolve + * copies what it keeps). + */ +export class RouteCache implements SegmentRouter { + private cur: Generation | null = null; + private prev: Generation | null = null; + + constructor(ctx?: RouteContext) { + if (ctx) this.setContext(ctx); + } + + /** The current context's signature ("" before the first setContext). */ + get signature(): string { + return this.cur?.sig ?? ""; + } + + get context(): RouteContext | null { + return this.cur?.ctx ?? null; + } + + /** Cached segments under the current context. */ + get size(): number { + return this.cur?.segs.size ?? 0; + } + + /** + * Switch to `ctx`. When its signature differs from the current one, the + * cached segments become the previous generation and the cache starts + * empty; returns true. Same signature: keeps everything (the new ctx + * object is adopted), returns false. + */ + setContext(ctx: RouteContext): boolean { + const sig = contextSignature(ctx); + if (this.cur && this.cur.sig === sig) { + this.cur.ctx = ctx; + return false; + } + if (this.cur) this.prev = this.cur; + this.cur = { ctx, sig, segs: new Map() }; + return true; + } + + route(a: HexKey, b: HexKey, style: SegmentStyle): SegmentRoute { + if (!this.cur) throw new Error("RouteCache: no context set"); + return cachedRoute(this.cur, a, b, style); + } + + /** + * A router for the context before the last change (its cached segments, + * computing any it lacks), or null when there was none. + */ + previous(): SegmentRouter | null { + const prev = this.prev; + if (!prev) return null; + return { route: (a, b, style) => cachedRoute(prev, a, b, style) }; + } + + /** Forget the previous generation (after the pin check has run). */ + dropPrevious(): void { + this.prev = null; + } + + clear(): void { + this.cur = null; + this.prev = null; + } +} diff --git a/src/paths/routePins.ts b/src/paths/routePins.ts new file mode 100644 index 00000000..f562e2db --- /dev/null +++ b/src/paths/routePins.ts @@ -0,0 +1,249 @@ +/** + * Phase 7 (Decision 3): keep a route where it was when its routing inputs + * change, and offer "Reroute instead". + * + * Routing inputs are the map's context (terrain shown as impassable, the + * palette's impassable flags, the map's bounds, the stagger) and each path + * type's explicit routing fields (avoidImpassable, autoRoute). When one of + * them would move a segment, `pinChanged` adds just enough anchors that the + * segment keeps its old hexes, and a notice says so with a "Reroute + * instead" button that drops those anchors again. + * + * Hooks: + * - context changes come from MapStore.onRouteContextChange (terrain painted + * or imported, and any change MapStore sees when it next routes the map). + * Hand edits of the map note come through here too: when one changed the + * anchors and the terrain at once, only the segments that were already + * drawn are pinned (RouteContextChange.drawnBefore), so anchors typed in + * are routed on the map as it is now; + * This class TAKES OVER the store's own silent pin (returns true): it + * pins the same way and also knows what it added, for the notice; + * - palette flags, resizes and type style edits are caught before the next + * draw: PathsService calls `sync(map)` whenever the map's context + * signature or its types' styles differ from its last resolve. `sync` + * asks MapStore to route under the current context (which fires the + * context hook above when it changed) and compares the types' styles with + * the last ones it saw. + * + * Every write goes through the path edit gate (editGate.ts). + */ + +import { logError } from "../log"; +import { Notice } from "obsidian"; +import type { HexKey, MapData, MapPath } from "../types"; +import type { SegmentStyle } from "./router"; +import type { RouteCache } from "./routeCache"; +import type { StyleFor } from "./resolve"; +import { clonePath, pinChanged, segmentFn } from "./edit"; +import { canEditPaths } from "./editGate"; +import type { RouteContextChange } from "../maps/MapStore"; + +/** What the pins need of the map store. */ +export interface PinStore { + isReady(map?: string): boolean; + paths(name: string): readonly MapPath[]; + setPaths(name: string, paths: MapPath[]): void; + routeCache(map: MapData): RouteCache; + pathStyleFor(map: MapData): StyleFor; + onRouteContextChange(fn: (e: RouteContextChange) => boolean | void): () => void; +} + +export interface PinHost { + getMap(name: string): MapData | undefined; + mapStore: PinStore; + /** Persist settings (maps whose paths still live in data.json). */ + saveSettings?(): Promise; +} + +/** One map's pin: the pinned paths as they were before, and how many anchors each gained. */ +export interface PinRecord { + map: string; + before: MapPath[]; + added: { path: string; added: number }[]; +} + +/** Is `sub` a subsequence of `seq`? */ +function isSubsequence(sub: readonly HexKey[], seq: readonly HexKey[]): boolean { + let i = 0; + for (const k of seq) if (i < sub.length && k === sub[i]) i++; + return i === sub.length; +} + +/** + * `current` with the anchors a pin added taken out again: each branch whose + * anchors before the pin are still all there, in order, goes back to them. + * Anything else (a branch edited since in other ways, a branch added or + * removed) is left as it is now. + */ +export function dropAddedAnchors(current: MapPath, before: MapPath): MapPath { + if (current.branches.length !== before.branches.length) return current; + let changed = false; + const out = clonePath(current); + out.branches.forEach((b, i) => { + const old = before.branches[i].anchors; + if (old.length < b.anchors.length && isSubsequence(old, b.anchors)) { + b.anchors = [...old]; + changed = true; + } + }); + return changed ? out : current; +} + +/** The styles of a map's types as a plain snapshot (type name → style). */ +function styleSnapshot(paths: readonly MapPath[], styleFor: StyleFor): Map { + const out = new Map(); + for (const p of paths) if (!out.has(p.typeName)) out.set(p.typeName, styleFor(p.typeName)); + return out; +} + +const sameStyle = (a: SegmentStyle | undefined, b: SegmentStyle | undefined) => + (!a && !b) || (!!a && !!b && a.avoid === b.avoid && a.winding === b.winding); + +/** How long pins are collected into one notice (a palette change pins many maps at once). */ +const BATCH_MS = 60; + +export class RoutePins { + private styles = new Map>(); + private batch: PinRecord[] = []; + private batchTimer: number | undefined; + private listeners = new Set<(r: PinRecord) => void>(); + private off: (() => void) | null = null; + + constructor(private host: PinHost) {} + + /** Start listening to the store's context changes. */ + attach(): void { + this.off?.(); + this.off = this.host.mapStore.onRouteContextChange((e) => this.onContextChange(e)); + } + + detach(): void { + this.off?.(); + this.off = null; + if (this.batchTimer !== undefined) window.clearTimeout(this.batchTimer); + this.batchTimer = undefined; + } + + /** Hear about each pin (the map view folds a pin into the undo step that caused it). */ + onPinned(fn: (r: PinRecord) => void): () => void { + this.listeners.add(fn); + return () => this.listeners.delete(fn); + } + + /** The store saw a context change: pin with a notice. Always handled here. */ + onContextChange(e: RouteContextChange): boolean { + if (!canEditPaths(e.map, "pin")) return true; // not allowed: the route moves + const paths = this.host.mapStore.paths(e.map); + if (!paths.length) return true; + // A hand edit that changed the paths too: only segments that were drawn + // before keep their route; the ones it added route on the map as it is. + const r = pinChanged(paths, segmentFn(e.previous, e.styleFor), segmentFn(e.current, e.styleFor), e.after, e.drawnBefore); + if (r.pinned.length) this.apply(e.map, paths, r.paths, r.pinned); + return true; + } + + /** + * Before a map's paths are drawn after its routing inputs changed: route + * it under the current context (the store then reports a context change + * to onContextChange), and pin against any type whose routing style + * changed since the last look. + */ + sync(mapName: string): void { + const map = this.host.getMap(mapName); + const store = this.host.mapStore; + if (!map || !store.isReady(mapName)) return; + const cache = store.routeCache(map); + if (!map.paths) return; + const paths = store.paths(mapName); + const styleFor = store.pathStyleFor(map); + const now = styleSnapshot(paths, styleFor); + const prev = this.styles.get(mapName); + this.styles.set(mapName, now); + if (!prev || !paths.length || !cache.context) return; + const changed = [...now].some(([t, s]) => prev.has(t) && !sameStyle(prev.get(t), s)); + if (!changed || !canEditPaths(mapName, "pin")) return; + const oldStyleFor: StyleFor = (t) => (prev.has(t) ? prev.get(t) : styleFor(t)); + const r = pinChanged(paths, segmentFn(cache, oldStyleFor), segmentFn(cache, styleFor), cache.context); + if (r.pinned.length) this.apply(mapName, paths, r.paths, r.pinned); + } + + /** Forget what was seen for a map (deleted or renamed). */ + forget(mapName: string): void { + this.styles.delete(mapName); + } + + private apply(mapName: string, before: readonly MapPath[], after: MapPath[], added: { path: string; added: number }[]): void { + const names = new Set(added.map((a) => a.path)); + const rec: PinRecord = { map: mapName, before: before.filter((p) => names.has(p.name)).map(clonePath), added }; + this.host.mapStore.setPaths(mapName, after); + void this.host.saveSettings?.(); + for (const fn of this.listeners) { + try { fn(rec); } catch (e) { logError("pin listener failed", e); } + } + this.batch.push(rec); + if (this.batchTimer === undefined) this.batchTimer = window.setTimeout(() => this.showNotice(), BATCH_MS); + } + + /** The pending pins, shown as one notice now (tests call this directly). */ + flushNotice(): PinRecord[] { + if (this.batchTimer !== undefined) window.clearTimeout(this.batchTimer); + this.batchTimer = undefined; + const recs = this.batch; + this.batch = []; + return recs; + } + + private showNotice(): void { + const recs = this.flushNotice(); + if (!recs.length) return; + const msg = pinNoticeText(recs); + const notice = new Notice(msg, 15000); + const el = (notice as unknown as { noticeEl?: HTMLElement }).noticeEl; + if (el) { + const btn = el.createEl("button", { text: "Reroute instead", cls: "duckmage-notice-btn" }); + btn.addEventListener("click", (ev) => { + ev.stopPropagation(); + this.rerouteInstead(recs); + notice.hide(); + }); + } + } + + /** "Reroute instead": take the pinned anchors out again (only those still there). */ + rerouteInstead(recs: readonly PinRecord[]): void { + const byMap = new Map(); + for (const r of recs) byMap.set(r.map, [...(byMap.get(r.map) ?? []), r]); + for (const [mapName, rs] of byMap) { + if (!this.host.getMap(mapName) || !canEditPaths(mapName, "reroute")) continue; + const current = this.host.mapStore.paths(mapName); + let changed = false; + const next = current.map((p) => { + let q = p; + for (const r of rs) { + const b = r.before.find((x) => x.name === p.name); + if (b) q = dropAddedAnchors(q, b); + } + if (q !== p) changed = true; + return q; + }); + if (changed) this.host.mapStore.setPaths(mapName, next); + } + void this.host.saveSettings?.(); + } +} + +/** "Kept the route of King's Road, Glass River (3 anchors added)." */ +export function pinNoticeText(recs: readonly PinRecord[]): string { + const names: string[] = []; + let added = 0; + for (const r of recs) { + for (const a of r.added) { + if (!names.includes(a.path)) names.push(a.path); + added += a.added; + } + } + const shown = names.length > 4 ? `${names.slice(0, 4).join(", ")} and ${names.length - 4} more` : names.join(", "); + const maps = new Set(recs.map((r) => r.map)).size; + return `Kept the route of ${shown}${maps > 1 ? ` on ${maps} maps` : ""} (${added} anchor${added === 1 ? "" : "s"} added).`; +} + diff --git a/src/paths/router.ts b/src/paths/router.ts new file mode 100644 index 00000000..64dcdff5 --- /dev/null +++ b/src/paths/router.ts @@ -0,0 +1,464 @@ +/** + * ROUTER v1: the route between two anchors of a path (A* inside the map's + * bounds, around blocked hexes), and the total `routeSegment` that falls back + * to a straight hex line when there's no route. Pure, no Obsidian imports. + * + * Anchored paths store only their anchors, so this function is part of the + * file format: the hexes a map draws are whatever it returns. It is frozen + * by golden tests (tests/pathRouter.golden.test.ts, tests/fixtures/ + * router-v1.json). Any change to what it returns is a ROUTER v2, which needs + * a re-anchoring migration (anchorsFor run under v2 keeps every route). + * + * The router never sees a path's name or type. Its only style inputs are + * the explicit `avoid` and `winding` flags of the segment context, which the + * caller takes from the path type's explicit fields. + * + * Hex keys are "x_y" offset coordinates, the same as everywhere else. + */ + +import type { HexKey } from "../types"; +import { hexNeighbors } from "../hex-map/hexGeometry"; +import { hexKey, hexPair, hexXY } from "../hexKey"; + +/** Bumped (with a re-anchoring migration) whenever routes would change. */ +export const ROUTER_VERSION = 1; + +export interface RouteBounds { + minX: number; + minY: number; + maxX: number; + maxY: number; +} + +export interface RouteOptions { + orientation: "flat" | "pointy"; + stagger?: "odd" | "even"; + bounds: RouteBounds; + /** True for hexes the route may not pass through. The start and end hexes + * are never blocked (a road may end at a port on the sea). */ + blocked?: (x: number, y: number) => boolean; + /** + * Wind gently instead of taking the straightest shortest route. The route + * follows a seeded wave between the ends, so it may take a few more steps. + * The seed defaults to one taken from the ends ("from>to"), so the same two + * anchors give the same route. + */ + meander?: boolean | { seed: number }; +} + +export type RouteResult = + | { ok: true; hexes: string[] } + | { ok: false; reason: "out-of-bounds" | "no-route" }; + +type Orientation = "flat" | "pointy"; +type Stagger = "odd" | "even"; + +const parity = (n: number) => ((n % 2) + 2) % 2; + +/** Axial (q, r) for an offset hex, so hex distance is easy to compute. */ +function toAxial(x: number, y: number, orientation: Orientation, stagger: Stagger): [number, number] { + // hexNeighbors: the "shifted" column (flat) / row (pointy) is odd for + // "odd" stagger, even for "even". Shifted lines sit half a hex down (flat) + // or right (pointy). + if (orientation === "flat") { + const r = stagger === "odd" ? y - (x - parity(x)) / 2 : y - (x + parity(x)) / 2; + return [x, r]; + } + const q = stagger === "odd" ? x - (y - parity(y)) / 2 : x - (y + parity(y)) / 2; + return [q, y]; +} + +/** The offset hex of an axial (q, r); the inverse of toAxial. */ +function fromAxial(q: number, r: number, orientation: Orientation, stagger: Stagger): [number, number] { + if (orientation === "flat") { + const y = stagger === "odd" ? r + (q - parity(q)) / 2 : r + (q + parity(q)) / 2; + return [q, y]; + } + const x = stagger === "odd" ? q + (r - parity(r)) / 2 : q + (r + parity(r)) / 2; + return [x, r]; +} + +/** Steps between two hexes on an unbounded grid. */ +export function hexDistance( + a: [number, number], + b: [number, number], + orientation: Orientation, + stagger: Stagger = "odd", +): number { + const [aq, ar] = toAxial(a[0], a[1], orientation, stagger); + const [bq, br] = toAxial(b[0], b[1], orientation, stagger); + const dq = aq - bq; + const dr = ar - br; + return (Math.abs(dq) + Math.abs(dr) + Math.abs(dq + dr)) / 2; +} + +/** + * A hex's centre in units of the hex's outer radius (so neighbouring centres + * are √3 apart). The router's own: it's an input of ROUTER v1, so rendering + * must not share it (rendering uses hexGeometry.hexCenter). + */ +export function hexCenter( + x: number, + y: number, + orientation: Orientation, + stagger: Stagger = "odd", +): [number, number] { + const [q, r] = toAxial(x, y, orientation, stagger); + return orientation === "flat" + ? [1.5 * q, Math.sqrt(3) * (r + q / 2)] + : [Math.sqrt(3) * (q + r / 2), 1.5 * r]; +} + +function inBounds(x: number, y: number, b: RouteBounds): boolean { + return x >= b.minX && x <= b.maxX && y >= b.minY && y <= b.maxY; +} + +/** + * A binary min-heap whose order is total and explicit: by `f`, then `p`, then + * the insertion counter `seq`. Ties never fall out of the heap's internals, + * so the routes don't change if the heap is ever rewritten. + */ +class MinHeap { + private items: { f: number; p: number; seq: number; value: T }[] = []; + private seq = 0; + get size(): number { return this.items.length; } + private less(i: number, j: number): boolean { + const a = this.items[i]; + const b = this.items[j]; + if (a.f !== b.f) return a.f < b.f; + if (a.p !== b.p) return a.p < b.p; + return a.seq < b.seq; + } + private swap(i: number, j: number): void { + const a = this.items; + [a[i], a[j]] = [a[j], a[i]]; + } + push(f: number, p: number, value: T): void { + const a = this.items; + a.push({ f, p, seq: this.seq++, value }); + let i = a.length - 1; + while (i > 0) { + const parent = (i - 1) >> 1; + if (!this.less(i, parent)) break; + this.swap(i, parent); + i = parent; + } + } + pop(): T | undefined { + const a = this.items; + if (!a.length) return undefined; + const top = a[0].value; + const last = a.pop()!; + if (a.length) { + a[0] = last; + let i = 0; + for (;;) { + const l = i * 2 + 1; + const r = l + 1; + let m = i; + if (l < a.length && this.less(l, m)) m = l; + if (r < a.length && this.less(r, m)) m = r; + if (m === i) break; + this.swap(m, i); + i = m; + } + } + return top; + } +} + +function walkBack(cameFrom: Map, end: string): string[] { + const hexes = [end]; + let k = end; + while (cameFrom.has(k)) { + k = cameFrom.get(k)!; + hexes.push(k); + } + return hexes.reverse(); +} + +/** + * Shortest route from `from` to `to` (both "x_y"), inclusive of both ends. + * Every step goes to a neighbouring hex. Between two neighbours the route is + * always the direct step (the ends are never blocked). + */ +export function findRoute(from: string, to: string, opts: RouteOptions): RouteResult { + const [fx, fy] = hexPair(from); + const [tx, ty] = hexPair(to); + const stagger = opts.stagger ?? "odd"; + if (!inBounds(fx, fy, opts.bounds) || !inBounds(tx, ty, opts.bounds)) { + return { ok: false, reason: "out-of-bounds" }; + } + if (from === to) return { ok: true, hexes: [from] }; + if (opts.meander) { + const seed = typeof opts.meander === "object" ? opts.meander.seed : hashString(`${from}>${to}`); + return meanderRoute(from, to, opts, seed); + } + + const h = (x: number, y: number) => hexDistance([x, y], [tx, ty], opts.orientation, stagger); + // Many routes are equally short on a hex grid. Among them, take the one + // that keeps closest to the straight line between the ends. Each hex + // entered adds its distance from that line to a secondary cost `p`; routes + // compare by steps first, then `p`, so the step count is still the shortest. + const [ax, ay] = hexCenter(fx, fy, opts.orientation, stagger); + const [bx, by] = hexCenter(tx, ty, opts.orientation, stagger); + const len = Math.hypot(bx - ax, by - ay) || 1; + const offLine = (x: number, y: number) => { + const [px, py] = hexCenter(x, y, opts.orientation, stagger); + return Math.abs((bx - ax) * (py - ay) - (by - ay) * (px - ax)) / len; + }; + const g = new Map([[from, 0]]); + const p = new Map([[from, 0]]); + const cameFrom = new Map(); + const closed = new Set(); + const open = new MinHeap(); + // Heap order: f (whole steps), then the off-line cost rounded to 1/100, + // then insertion order. + open.push(h(fx, fy), 0, from); + + while (open.size) { + const cur = open.pop()!; + if (closed.has(cur)) continue; + if (cur === to) return { ok: true, hexes: walkBack(cameFrom, cur) }; + closed.add(cur); + const [cx, cy] = hexPair(cur); + const gCur = g.get(cur)!; + const pCur = p.get(cur)!; + for (const [nx, ny] of hexNeighbors(cx, cy, opts.orientation, stagger)) { + if (!inBounds(nx, ny, opts.bounds)) continue; + const nk = hexKey(nx, ny); + if (closed.has(nk)) continue; + if (nk !== to && opts.blocked?.(nx, ny)) continue; + const gNext = gCur + 1; + const pNext = pCur + offLine(nx, ny); + const gOld = g.get(nk) ?? Infinity; + if (gNext > gOld || (gNext === gOld && pNext >= p.get(nk)!)) continue; + g.set(nk, gNext); + p.set(nk, pNext); + cameFrom.set(nk, cur); + open.push(gNext + h(nx, ny), Math.round(pNext * 100), nk); + } + } + return { ok: false, reason: "no-route" }; +} + +/** A small deterministic hash (FNV-1a) for seeding from the route's ends. */ +export function hashString(s: string): number { + let h = 0x811c9dc5; + for (let i = 0; i < s.length; i++) { + h ^= s.charCodeAt(i); + h = Math.imul(h, 0x01000193); + } + return h >>> 0; +} + +/** mulberry32: a tiny seeded PRNG, [0, 1). */ +function rng(seed: number): () => number { + let a = seed >>> 0; + return () => { + a = (a + 0x6d2b79f5) >>> 0; + let t = a; + t = Math.imul(t ^ (t >>> 15), t | 1); + t ^= t + Math.imul(t ^ (t >>> 7), t | 61); + return ((t ^ (t >>> 14)) >>> 0) / 4294967296; + }; +} + +/** Cost per hex (in steps) of being one hex away from the wave. */ +const MEANDER_PULL = 1.5; + +/** + * A winding route: the cheapest hex-by-hex route where each step costs 1 + * plus how far the hex lies from a seeded wave between the ends (a few + * half-waves, zero at both ends, about a fifth of the length high, capped). + * Costs are at least 1 a step, so hex distance stays an admissible A* + * heuristic and the result is a true shortest route for that cost. + */ +function meanderRoute(from: string, to: string, opts: RouteOptions, seed: number): RouteResult { + const [fx, fy] = hexPair(from); + const [tx, ty] = hexPair(to); + const stagger = opts.stagger ?? "odd"; + const SQ3 = Math.sqrt(3); + const [ax, ay] = hexCenter(fx, fy, opts.orientation, stagger); + const [bx, by] = hexCenter(tx, ty, opts.orientation, stagger); + const len = Math.hypot(bx - ax, by - ay) || 1; + const ux = (bx - ax) / len; + const uy = (by - ay) / len; + const lenHex = len / SQ3; + const rand = rng(seed); + const halfWaves = Math.max(1, Math.round(lenHex / 6)) + (rand() < 0.5 ? 0 : 1); + const amp = Math.min(2.5, Math.max(0.9, lenHex * 0.2)) * (0.8 + 0.4 * rand()) * (rand() < 0.5 ? -1 : 1); + /** How far (hexes) a hex lies from the wave. */ + const offWave = (x: number, y: number) => { + const [px, py] = hexCenter(x, y, opts.orientation, stagger); + const along = ((px - ax) * ux + (py - ay) * uy) / len; + const side = ((px - ax) * -uy + (py - ay) * ux) / SQ3; + const t = Math.min(1, Math.max(0, along)); + return Math.abs(side - amp * Math.sin(halfWaves * Math.PI * t)); + }; + + const h = (x: number, y: number) => hexDistance([x, y], [tx, ty], opts.orientation, stagger); + const g = new Map([[from, 0]]); + const cameFrom = new Map(); + const closed = new Set(); + const open = new MinHeap(); + // Heap order: f, then insertion order. + open.push(h(fx, fy), 0, from); + while (open.size) { + const cur = open.pop()!; + if (closed.has(cur)) continue; + if (cur === to) return { ok: true, hexes: walkBack(cameFrom, cur) }; + closed.add(cur); + const [cx, cy] = hexPair(cur); + const gCur = g.get(cur)!; + for (const [nx, ny] of hexNeighbors(cx, cy, opts.orientation, stagger)) { + if (!inBounds(nx, ny, opts.bounds)) continue; + const nk = hexKey(nx, ny); + if (closed.has(nk)) continue; + if (nk !== to && opts.blocked?.(nx, ny)) continue; + const gNext = gCur + 1 + MEANDER_PULL * offWave(nx, ny); + if (gNext >= (g.get(nk) ?? Infinity)) continue; + g.set(nk, gNext); + cameFrom.set(nk, cur); + open.push(gNext + h(nx, ny), 0, nk); + } + } + return { ok: false, reason: "no-route" }; +} + +// ── Hex line (the fallback) ────────────────────────────────────────────────── + +function cubeRound(fq: number, fr: number): [number, number] { + const fs = -fq - fr; + let q = Math.round(fq); + let r = Math.round(fr); + const s = Math.round(fs); + const dq = Math.abs(q - fq); + const dr = Math.abs(r - fr); + const ds = Math.abs(s - fs); + if (dq > dr && dq > ds) q = -r - s; + else if (dr > ds) r = -q - s; + return [q === 0 ? 0 : q, r === 0 ? 0 : r]; +} + +/** + * The straight line of hexes from `a` to `b`, inclusive, ignoring bounds and + * terrain: a cube-coordinate lerp with a fixed nudge, so a line that runs + * exactly along hex edges always breaks the same way. Consecutive hexes are + * neighbours. + */ +export function hexLine(a: HexKey, b: HexKey, orientation: Orientation, stagger: Stagger = "odd"): HexKey[] { + if (a === b) return [a]; + const [ax, ay] = hexPair(a); + const [bx, by] = hexPair(b); + const [aq, ar] = toAxial(ax, ay, orientation, stagger); + const [bq, br] = toAxial(bx, by, orientation, stagger); + const n = hexDistance([ax, ay], [bx, by], orientation, stagger); + // The nudge (+1e-6, +2e-6, -3e-6 in q, r, s) keeps the cube sum at zero. + const nq = aq + 1e-6; + const nr = ar + 2e-6; + const out: HexKey[] = []; + for (let i = 0; i <= n; i++) { + const t = i / n; + const [q, r] = cubeRound(nq + (bq - aq) * t, nr + (br - ar) * t); + const [x, y] = fromAxial(q, r, orientation, stagger); + out.push(hexKey(x, y)); + } + out[0] = a; + out[out.length - 1] = b; + return out; +} + +// ── Segments ───────────────────────────────────────────────────────────────── + +/** Everything about a map that routes depend on. */ +export interface RouteContext { + orientation: Orientation; + stagger: Stagger; + bounds: RouteBounds; + /** Hexes whose shown terrain (own, else the map's base) is impassable. */ + blocked: ReadonlySet; +} + +/** + * A segment's style flags, from the path type's EXPLICIT fields only (never + * from its name). Unknown type: DEFAULT_SEGMENT_STYLE. + * + * Wiring (when PathType gets them, fix/46-palettes-generators PA5): + * `avoid` = PathType.avoidImpassable, `winding` = the type's winding + * auto-route style. Built in one place by the caller's `styleFor` + * (see resolve.ts `StyleFor`). + */ +export interface SegmentStyle { + /** Go around blocked hexes (between anchors; anchors themselves never are). */ + avoid: boolean; + /** Wind (the router's meander) instead of hugging the straight line. */ + winding: boolean; +} + +/** For a type not in the palette: fixed values, never guessed from a name. */ +export const DEFAULT_SEGMENT_STYLE: Readonly = Object.freeze({ avoid: true, winding: false }); + +export type SegmentContext = RouteContext & SegmentStyle; + +export interface SegmentRoute { + /** From a to b inclusive; consecutive hexes are neighbours. */ + hexes: HexKey[]; + /** Set when the hex-line fallback was used, and why. */ + fallback?: "out-of-bounds" | "no-route"; +} + +/** The router options for a segment context. */ +export function routeOptions(ctx: SegmentContext): RouteOptions { + const blocked = ctx.avoid && ctx.blocked.size + ? (x: number, y: number) => ctx.blocked.has(hexKey(x, y)) + : undefined; + return { orientation: ctx.orientation, stagger: ctx.stagger, bounds: ctx.bounds, blocked, meander: ctx.winding }; +} + +/** + * The route between two consecutive anchors. Total: when the router can't + * route (an anchor off the map, or walled off), the segment is the straight + * hex line and `fallback` says why. Depends only on a, b and ctx (locality). + * `ctx.winding` is the only place the winding style reaches the router. + */ +export function routeSegment(a: HexKey, b: HexKey, ctx: SegmentContext): SegmentRoute { + const r = findRoute(a, b, routeOptions(ctx)); + if (r.ok) return { hexes: r.hexes }; + return { hexes: hexLine(a, b, ctx.orientation, ctx.stagger), fallback: r.reason }; +} + +/** cyrb53: a 53-bit string hash (fewer collisions than 32-bit FNV for cache keys). */ +function hash53(s: string): number { + let h1 = 0xdeadbeef; + let h2 = 0x41c6ce57; + for (let i = 0; i < s.length; i++) { + const c = s.charCodeAt(i); + h1 = Math.imul(h1 ^ c, 2654435761); + h2 = Math.imul(h2 ^ c, 1597334677); + } + h1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507) ^ Math.imul(h2 ^ (h2 >>> 13), 3266489909); + h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507) ^ Math.imul(h1 ^ (h1 >>> 13), 3266489909); + return 4294967296 * (2097151 & h2) + (h1 >>> 0); +} + +/** A signature of the blocked hexes inside the bounds (order-independent). */ +export function blockedSignature(blocked: ReadonlySet, bounds: RouteBounds): string { + const keys: string[] = []; + for (const k of blocked) { + const { x, y } = hexXY(k); + if (inBounds(x, y, bounds)) keys.push(k); + } + keys.sort(); + return `${keys.length}:${hash53(keys.join(",")).toString(36)}`; +} + +/** + * The key of a map's routing context: router version, orientation, stagger, + * bounds and the blocked hexes. Two contexts with the same signature route + * every segment the same (for the same avoid/winding flags). + */ +export function contextSignature(ctx: RouteContext): string { + const b = ctx.bounds; + return `v${ROUTER_VERSION}|${ctx.orientation}|${ctx.stagger}|${b.minX},${b.minY},${b.maxX},${b.maxY}|${blockedSignature(ctx.blocked, b)}`; +} diff --git a/src/paths/seamHook.ts b/src/paths/seamHook.ts new file mode 100644 index 00000000..2a42beaf --- /dev/null +++ b/src/paths/seamHook.ts @@ -0,0 +1,203 @@ +/** + * Hooking onto a neighbouring map's road or river across the seam (owner + * O1, 2026-10-14: "make sure you can hook to an existing road/river from a + * different region neighbour easily via the tool, clicking on it + * reactivating it and letting you extend it via more clicks"). + * + * A map that sits in a world (regions of one overworld, or maps placed next + * to each other) shows its neighbours' hexes just past its edges, the + * "strip" (neighbourShadow), with their paths on it (ghostPaths.ts). Each + * map keeps its own paths: a road that runs on into the next map is one + * path there and one here, their ends on touching hexes across the seam, + * the same type. The overworld joins them into one line (regionPaths.ts). + * + * - **Hook** (seamHooks / hookAt): a neighbour path's open end lying in the + * strip, touching this map. Clicking it with the path tool starts a path + * here on the hex next to that end (straight on from it where it can), + * with the neighbour path's type and name, so the next clicks extend it. + * - **Same hex, by hand** (hookFor): starting a path of the same type on a + * hex touching such an end takes the neighbour path's name too. + * - **Across** (crossFrom): drawing up to this map's edge, a click in the + * strip carries on in the neighbour, from its hex touching the end. + * + * Pure: no Obsidian imports. Keys in "this map's frame" are this map's hex + * keys; a strip hex also knows which map and hex it really is. + */ + +import type { HexKey } from "../types"; +import { hexNeighbors } from "../../packages/hex-wfc/src/grid"; +import { latticeCenter, type LatticeGrid, type Pt } from "./pathGeometry"; +import { pathNameKey } from "./names"; +import { hexKey } from "../hexKey"; + +/** A strip hex (this map's frame) → which map and hex it is. */ +export interface StripRef { + map: string; + x: number; + y: number; +} + +/** One routed branch of a neighbour's path, in that map's own frame. */ +export interface NeighbourBranch { + path: string; + typeName: string; + hexes: readonly HexKey[]; + /** Its start sits on another branch (a fork): not an open end. */ + forkFrom?: unknown; + /** Its end sits on another branch (a join): not an open end. */ + joinTo?: unknown; +} + +/** A neighbour path's open end in the strip, touching this map. */ +export interface SeamHook { + map: string; + path: string; + typeName: string; + /** The end hex, in this map's frame. */ + end: HexKey; + /** The hexes of this map touching the end. */ + touching: HexKey[]; + /** Where a path hooked on here starts: the touching hex straight on from the end. */ + start: HexKey; + /** The path's run across the strip up to its end (this map's frame), for the click test. */ + run: HexKey[]; +} + +const parse = (k: HexKey): [number, number] => { + const i = k.indexOf("_"); + return [Number(k.slice(0, i)), Number(k.slice(i + 1))]; +}; + +/** Neighbours of a hex in this map's lattice. */ +export function touchingKeys(key: HexKey, grid: LatticeGrid): HexKey[] { + return hexNeighbors(...parse(key), grid.orientation, grid.stagger).map(([x, y]) => hexKey(x, y)); +} + +/** Each neighbour map's offset into this map's frame (maps in a world sit on one grid, shifted). */ +function offsets(strip: ReadonlyMap): Map { + const out = new Map(); + for (const [key, ref] of strip) { + if (out.has(ref.map)) continue; + const [x, y] = parse(key); + out.set(ref.map, [x - ref.x, y - ref.y]); + } + return out; +} + +/** + * Every neighbour path end that a path here can hook onto. `inMap` says + * whether a key of this map's frame is one of its own hexes. + */ +export function seamHooks( + strip: ReadonlyMap, + branchesOf: (map: string) => readonly NeighbourBranch[], + inMap: (key: HexKey) => boolean, + grid: LatticeGrid, +): SeamHook[] { + const out: SeamHook[] = []; + for (const [map, [dx, dy]] of offsets(strip)) { + const inStrip = (k: HexKey) => strip.get(k)?.map === map; + for (const b of branchesOf(map)) { + if (!b.hexes.length) continue; + const local = b.hexes.map((k) => { + const [x, y] = parse(k); + return hexKey(x + dx, y + dy); + }); + const ends: { at: number; step: 1 | -1 }[] = []; + if (!b.forkFrom) ends.push({ at: 0, step: 1 }); + if (!b.joinTo && local.length > 1) ends.push({ at: local.length - 1, step: -1 }); + else if (!b.joinTo && b.forkFrom && local.length === 1) ends.push({ at: 0, step: 1 }); + for (const { at, step } of ends) { + const end = local[at]; + if (!inStrip(end)) continue; + const touching = touchingKeys(end, grid).filter(inMap); + if (!touching.length) continue; + // The run back from the end while it stays in the strip, end last. + const run: HexKey[] = []; + for (let i = at; i >= 0 && i < local.length && inStrip(local[i]); i += step) run.unshift(local[i]); + // Straight on: past the end, the way the path was heading. + const c = latticeCenter(end, grid); + const prev = run.length > 1 ? latticeCenter(run[run.length - 2], grid) : null; + const ahead: Pt = prev ? { cx: 2 * c.cx - prev.cx, cy: 2 * c.cy - prev.cy } : c; + const start = nearestKey(ahead, touching, grid) ?? touching[0]; + out.push({ map, path: b.path, typeName: b.typeName, end, touching, start, run }); + } + } + } + return out; +} + +/** The key of `keys` whose centre is nearest `p` (ties: the first), or null when empty. */ +export function nearestKey(p: Pt, keys: readonly HexKey[], grid: LatticeGrid): HexKey | null { + let best: HexKey | null = null; + let bestD = Infinity; + for (const k of keys) { + const c = latticeCenter(k, grid); + const d = Math.hypot(p.cx - c.cx, p.cy - c.cy); + if (d < bestD - 1e-9) { + bestD = d; + best = k; + } + } + return best; +} + +/** How near (lattice units, a hex's centre-to-corner is 1) a click must be to a hooked path's run. */ +export const HOOK_R = 0.8; + +function distToRun(p: Pt, run: readonly HexKey[], grid: LatticeGrid): number { + const pts = run.map((k) => latticeCenter(k, grid)); + let best = Math.hypot(p.cx - pts[0].cx, p.cy - pts[0].cy); + for (let i = 1; i < pts.length; i++) { + const a = pts[i - 1], b = pts[i]; + const dx = b.cx - a.cx, dy = b.cy - a.cy; + const len2 = dx * dx + dy * dy; + const t = len2 ? Math.max(0, Math.min(1, ((p.cx - a.cx) * dx + (p.cy - a.cy) * dy) / len2)) : 0; + best = Math.min(best, Math.hypot(a.cx + t * dx - p.cx, a.cy + t * dy - p.cy)); + } + return best; +} + +/** The hook whose run in the strip is under lattice point `p` (the nearest), or null. */ +export function hookAt(p: Pt, hooks: readonly SeamHook[], grid: LatticeGrid): SeamHook | null { + let best: SeamHook | null = null; + let bestD = Infinity; + for (const h of hooks) { + const d = distToRun(p, h.run, grid); + if (d <= HOOK_R && d < bestD - 1e-9) { + bestD = d; + best = h; + } + } + return best; +} + +/** A neighbour path of type `typeName` whose end touches hex `start` of this map (a path started there continues it). */ +export function hookFor(start: HexKey, typeName: string, hooks: readonly SeamHook[]): SeamHook | null { + return hooks.find((h) => h.typeName === typeName && h.touching.includes(start)) ?? null; +} + +/** The neighbour path's name for a path started here, unless this map already has a path called that. */ +export function hookedName(name: string, taken: Iterable): string | null { + const key = pathNameKey(name); + for (const t of taken) if (pathNameKey(t) === key) return null; + return name; +} + +/** + * Carrying a path on across the seam: the active end is on this map's + * edge and the click `p` is in the strip. The strip hex touching the end + * nearest the click, as the neighbour's own map and hex, or null when the + * end doesn't touch the strip (draw up to the edge first). + */ +export function crossFrom( + activeEnd: HexKey, + p: Pt, + strip: ReadonlyMap, + grid: LatticeGrid, +): { map: string; hex: HexKey; local: HexKey } | null { + const across = touchingKeys(activeEnd, grid).filter((k) => strip.has(k)); + const local = nearestKey(p, across, grid); + const ref = local ? strip.get(local) : undefined; + return local && ref ? { map: ref.map, hex: hexKey(ref.x, ref.y), local } : null; +} diff --git a/src/paths/typeRefs.ts b/src/paths/typeRefs.ts new file mode 100644 index 00000000..af773aaf --- /dev/null +++ b/src/paths/typeRefs.ts @@ -0,0 +1,49 @@ +/** + * A path type's references across a map's paths (PathTypeEditorModal: + * rename and delete a type). Type names are references into the palette, + * compared exactly; nothing here interprets them. Pure. + */ + +import type { MapPath, PathChain } from "../types"; + +/** How many paths use type `name`. */ +export function countPathsOfType(paths: readonly MapPath[], name: string): number { + return paths.filter((p) => p.typeName === name).length; +} + +/** Point every path of type `from` at `to` (in place). Returns how many changed. */ +export function renamePathTypeInPaths(paths: MapPath[], from: string, to: string): number { + let n = 0; + for (const p of paths) { + if (p.typeName === from) { + p.typeName = to; + n++; + } + } + return n; +} + +/** The paths without those of type `name` (a deleted type takes its paths with it). */ +export function removePathTypeFromPaths(paths: readonly MapPath[], name: string): MapPath[] { + return paths.filter((p) => p.typeName !== name); +} + +/** + * The same two edits on legacy chains, for as long as maps store + * `pathChains` (the Phase-3 adapter in mapPaths.ts). Phase 3 switches the + * modal to the MapPath functions above and deletes these. + */ +export function renamePathTypeInChains(chains: PathChain[], from: string, to: string): number { + let n = 0; + for (const c of chains) { + if (c.typeName === from) { + c.typeName = to; + n++; + } + } + return n; +} + +export function removePathTypeFromChains(chains: readonly PathChain[], name: string): PathChain[] { + return chains.filter((c) => c.typeName !== name); +} diff --git a/src/platform.ts b/src/platform.ts new file mode 100644 index 00000000..53172028 --- /dev/null +++ b/src/platform.ts @@ -0,0 +1,43 @@ +/** + * Which features need desktop Obsidian (Electron). The phone and tablet + * apps have no / printToPDF, so the PDF exports are off there; + * every Markdown and PNG export, and the whole map, work on mobile. + * Kept free of Obsidian imports (the pure-file ratchet, unit tests): the + * live platform is read from the `is-mobile` class Obsidian puts on + * (app.emulateMobile toggles it too). + */ +export interface PlatformLike { + isMobile: boolean; + isDesktopApp: boolean; +} + +/** Features switched off on mobile, with the one-line reason shown to the user. */ +export const DESKTOP_ONLY_FEATURES = { + pdf: "PDF export needs the desktop app (it prints through Electron). Use the Markdown or PNG export on mobile.", +} as const; + +export type DesktopOnlyFeature = keyof typeof DESKTOP_ONLY_FEATURES; + +/** Is this feature available on the given platform? (Desktop app: everything.) */ +export function featureAvailable(feature: DesktopOnlyFeature, p: PlatformLike): boolean { + if (!(feature in DESKTOP_ONLY_FEATURES)) return true; + return p.isDesktopApp && !p.isMobile; +} + +/** Why a feature is off on this platform, or null when it's available. */ +export function featureUnavailableReason(feature: DesktopOnlyFeature, p: PlatformLike): string | null { + return featureAvailable(feature, p) ? null : DESKTOP_ONLY_FEATURES[feature]; +} + +/** The platform as Obsidian reports it on (read live: emulateMobile can flip it). */ +export function bodyPlatform(body: { classList?: { contains(c: string): boolean } } | null | undefined): PlatformLike { + const isMobile = body?.classList?.contains("is-mobile") ?? false; + return { isMobile, isDesktopApp: !isMobile }; +} + +/** PDF export works here. */ +export function pdfAvailable(): boolean { + return featureAvailable("pdf", bodyPlatform(typeof activeDocument === "undefined" ? null : activeDocument.body)); +} + +export const PDF_UNAVAILABLE_MESSAGE = DESKTOP_ONLY_FEATURES.pdf; diff --git a/src/plugin/commands.ts b/src/plugin/commands.ts new file mode 100644 index 00000000..31b8448b --- /dev/null +++ b/src/plugin/commands.ts @@ -0,0 +1,272 @@ +/** + * The plugin's ribbon icon, commands, file menu and editor menu. Split from + * HexmakerPlugin.onload (plan-architecture-refactor L1a); same ids, names, + * placement and order as before. + */ +import { type Command, Editor, EventRef, MarkdownView, Menu, Notice, TFile } from "obsidian"; +import type HexmakerPlugin from "../HexmakerPlugin"; +import { exportSingleNoteAsPdf, exportSingleNoteAsMarkdown } from "../export/exporters/singleNote"; +import { HexExportModal } from "../hex-map/HexExportModal"; +import { MapExportModal } from "../export/MapExportModal"; +import { WorkflowExportModal } from "../random-tables/WorkflowExportModal"; +import { HexMapView } from "../hex-map/HexMapView"; +import { FileLinkSuggestModal } from "../hex-map/FileLinkSuggestModal"; +import { MapLinkModal } from "../hex-map/MapLinkModal"; +import { openTableRangesModal, runTableCheck } from "../random-tables/tableMaintenance"; +import { VIEW_TYPE_HEX_MAP, VIEW_TYPE_HEX_TABLE, VIEW_TYPE_RANDOM_TABLES } from "../constants"; +import { moduleCommands } from "../modules/runtime"; +import { enabledKinds } from "../mapKinds"; +import { isDebugMode } from "../ui/debugMode"; +import { addPlacedMenuItems, placeCommand } from "../ui/commandPlacement"; +import { RestoreBackupModal, openBackupsFolder } from "../BackupsModal"; +import { RecalculateFieldsModal } from "../fields/RecalculateFieldsModal"; +import { mapLinkUri } from "../hexLink"; +import { normalizeFolder } from "../utils"; +import { pdfAvailable } from "../platform"; + +/** The ribbon icon, every command and the file menu (in onload's order). */ +export function registerCommands(plugin: HexmakerPlugin): void { + plugin.addRibbonIcon("map", "Open hex map", () => + plugin.openHexMap(), + ); + // Commands are placed by id like every other control (src/ui/placement.ts): + // Debug ones are offered only in debug mode (src/ui/commandPlacement.ts). + const addPlaced = (id: string, cmd: Command) => { + const placed = placeCommand(id, cmd, () => isDebugMode(plugin.app)); + if (placed) plugin.addCommand(placed); + }; + addPlaced("Plugin.cmd.openHexMap", { + id: "open-hex-map", + name: "Open hex map", + callback: () => plugin.openHexMap(), + }); + addPlaced("Plugin.cmd.openHexTable", { + id: "open-hex-table", + name: "Open hex table", + callback: () => void plugin.app.workspace.getLeaf().setViewState({ type: VIEW_TYPE_HEX_TABLE }), + }); + addPlaced("Plugin.cmd.openPaletteEditor", { + id: "open-palette-editor", + name: "Open palette editor", + callback: () => void plugin.openPaletteEditor(), + }); + // Each module's commands (Space: Edit world types…, Convert world types to tables), + // placed by their placement id when they have one. + for (const { command, kind } of moduleCommands()) { + const cmd: Command = { + id: command.id, + name: command.name, + checkCallback: (checking) => { + if (kind !== undefined && !enabledKinds(plugin.settings).has(kind)) return false; + if (command.available && !command.available(plugin)) return false; + if (!checking) void command.run(plugin); + return true; + }, + }; + if (command.placementId) addPlaced(command.placementId, cmd); + else plugin.addCommand(cmd); + } + addPlaced("Plugin.cmd.mapGoUp", { + id: "map-go-up", + name: "Go up to parent map", + checkCallback: (checking) => { + const view = plugin.app.workspace.getActiveViewOfType(HexMapView); + if (!view?.canNavigateUp()) return false; + if (!checking) view.navigateUp(); + return true; + }, + }); + addPlaced("Plugin.cmd.mapGoBack", { + id: "map-go-back", + name: "Go back to previous map", + checkCallback: (checking) => { + const view = plugin.app.workspace.getActiveViewOfType(HexMapView); + if (!view?.canNavigateBack()) return false; + if (!checking) view.navigateBack(); + return true; + }, + }); + addPlaced("Plugin.cmd.mapGoForward", { + id: "map-go-forward", + name: "Go forward to the next map", + checkCallback: (checking) => { + const view = plugin.app.workspace.getActiveViewOfType(HexMapView); + if (!view?.canNavigateForward()) return false; + if (!checking) view.navigateForward(); + return true; + }, + }); + addPlaced("Plugin.cmd.openRandomTables", { + id: "open-random-tables", + name: "Open random tables", + callback: () => void plugin.app.workspace.getLeaf().setViewState({ type: VIEW_TYPE_RANDOM_TABLES }), + }); + addPlaced("Plugin.cmd.addRollRanges", { + id: "add-roll-ranges", + name: "Add roll ranges to tables", + callback: () => void openTableRangesModal(plugin), + }); + addPlaced("Plugin.cmd.checkTables", { + id: "check-tables", + name: "Check tables", + callback: () => void runTableCheck(plugin), + }); + // Hex fields (#52): redo the open map's fields after places changed. + addPlaced("Plugin.cmd.recalculateFields", { + id: "recalculate-fields", + name: "Recalculate fields", + checkCallback: (checking) => { + const map = plugin.activeMapName(); + if (!map) return false; + if (!checking) new RecalculateFieldsModal(plugin.app, plugin, map).open(); + return true; + }, + }); + // Backups stay in the plugin's folder; these reach them (owner MG2). + addPlaced("Plugin.cmd.openBackupsFolder", { + id: "open-backups-folder", + name: "Open backups folder", + callback: () => void openBackupsFolder(plugin), + }); + addPlaced("Plugin.cmd.restoreFromBackup", { + id: "restore-from-upgrade-backup", + name: "Restore from upgrade backup…", + callback: () => new RestoreBackupModal(plugin.app, plugin).open(), + }); + addPlaced("Plugin.cmd.exportNotePdf", { + id: "export-current-note-pdf", + name: "Export current note to PDF", + checkCallback: (checking) => { + const file = plugin.app.workspace.getActiveViewOfType(MarkdownView)?.file; + if (!file || !pdfAvailable()) return false; + if (!checking) void exportSingleNoteAsPdf(plugin, file); + return true; + }, + }); + addPlaced("Plugin.cmd.exportNoteMarkdown", { + id: "export-current-note-markdown", + name: "Export current note to Markdown", + checkCallback: (checking) => { + const file = plugin.app.workspace.getActiveViewOfType(MarkdownView)?.file; + if (!file) return false; + if (!checking) void exportSingleNoteAsMarkdown(plugin, file); + return true; + }, + }); + addPlaced("Plugin.cmd.exportCurrentHex", { + id: "export-current-hex", + name: "Export current hex (structured PDF / Markdown)", + checkCallback: (checking) => { + const file = plugin.app.workspace.getActiveViewOfType(MarkdownView)?.file; + if (!file || !plugin.isHexFile(file)) return false; + if (!checking) new HexExportModal(plugin.app, plugin, file).open(); + return true; + }, + }); + addPlaced("Plugin.cmd.exportCurrentWorkflow", { + id: "export-current-workflow", + name: "Export current workflow with rolled samples", + checkCallback: (checking) => { + const file = plugin.app.workspace.getActiveViewOfType(MarkdownView)?.file; + if (!file || !plugin.isWorkflowFile(file)) return false; + if (!checking) new WorkflowExportModal(plugin.app, plugin, file).open(); + return true; + }, + }); + // Map export (PNG / PDF / hexcrawl manual): the same form as Maps → + // Map data callouts (src/hexMapData.ts) in the open map's hex notes: an + // opt-in for notes made before the template had one. + addPlaced("Plugin.cmd.addMapDataToHexNotes", { + id: "add-map-data-to-hex-notes", + name: "Add map data to this map's hex notes", + checkCallback: (checking) => { + const open = plugin.app.workspace.getActiveViewOfType(HexMapView) + ?? plugin.app.workspace.getLeavesOfType(VIEW_TYPE_HEX_MAP).map((l) => l.view).find((v): v is HexMapView => v instanceof HexMapView); + const mapName = open?.activeMapName; + if (!mapName || !plugin.getMap(mapName)) return false; + // No confirm (owner Q6): it only adds a Map data box; the notice says what it did. + if (!checking) void plugin.addMapDataToHexNotes(mapName).then((n) => new Notice(`Map data added or updated in ${n} hex note${n === 1 ? "" : "s"} of "${plugin.mapLabel(mapName)}" (a box under each title; nothing else changed).`)); + return true; + }, + }); + // Map data callouts in region and faction notes (R1): which maps use + // them, with hex counts. Adds the callout where it's missing. + addPlaced("Plugin.cmd.updateRegionFactionMapData", { + id: "update-region-faction-map-data", + name: "Update map data in region and faction notes", + checkCallback: (checking) => { + if (!plugin.regionAndFactionNotes().length) return false; + // No confirm (owner Q6): it only adds or refreshes a Map data box; the notice says what it did. + if (!checking) void plugin.updateRegionFactionMapData().then((n) => new Notice(`Map data added or updated in ${n} area and faction note${n === 1 ? "" : "s"} (a box under each title; nothing else changed).`)); + return true; + }, + }); + // Export, for the map open in the hex map view (else the default map). + addPlaced("Plugin.cmd.exportCurrentMap", { + id: "export-current-map", + name: "Export current map…", + checkCallback: (checking) => { + const open = plugin.app.workspace.getActiveViewOfType(HexMapView) + ?? plugin.app.workspace.getLeavesOfType(VIEW_TYPE_HEX_MAP).map((l) => l.view).find((v): v is HexMapView => v instanceof HexMapView); + const mapName = [open?.activeMapName, plugin.settings.defaultMap, plugin.settings.maps[0]?.name] + .find((n): n is string => !!n && !!plugin.getMap(n)); + if (!mapName) return false; + if (!checking) new MapExportModal(plugin.app, plugin, mapName).open(); + return true; + }, + }); + // File-menu items: right-click any markdown file → Export to PDF / + // Markdown. Placed by id: Advanced ones go in one "Export note" submenu. + plugin.registerEvent( + plugin.app.workspace.on("file-menu", (menu, file) => { + if (!(file instanceof TFile) || file.extension !== "md") return; + addPlacedMenuItems(menu, "Export note", "file-down", [ + ...(pdfAvailable() ? [{ id: "Plugin.fileMenuExportPdf", title: "Export to PDF", short: "PDF", icon: "file-down", run: () => void exportSingleNoteAsPdf(plugin, file) }] : []), + { id: "Plugin.fileMenuExportMarkdown", title: "Export to Markdown", short: "Markdown", icon: "file-text", run: () => void exportSingleNoteAsMarkdown(plugin, file) }, + ], isDebugMode(plugin.app)); + }), + ); +} + +/** Right-click "Insert table roller" / "Insert map link" in any editor. */ +export function registerEditorMenu(plugin: HexmakerPlugin): void { + // "editor-menu" is a valid Obsidian workspace event not yet in the official types. + interface WorkspaceWithEditorMenu { + on(name: "editor-menu", callback: (menu: Menu, editor: Editor) => void): EventRef; + } + plugin.registerEvent( + (plugin.app.workspace as unknown as WorkspaceWithEditorMenu).on( + "editor-menu", + (menu: Menu, editor: Editor) => { + menu.addItem((item) => + item + .setTitle("Insert table roller") + .setIcon("dice") + .setSection("insert") + .onClick(() => { + new FileLinkSuggestModal( + plugin.app, + plugin, + (file) => { + const block = `\`\`\`duckmage-roller\n${file.path}\n\`\`\``; + editor.replaceSelection(block); + }, + normalizeFolder(plugin.settings.tablesFolder), + ).open(); + }), + ); + menu.addItem((item) => + item + .setTitle("Insert map link") + .setIcon("map") + .setSection("insert") + .onClick(() => { + new MapLinkModal(plugin.app, plugin, (mapName, linkText) => { + editor.replaceSelection(`[${linkText}](${mapLinkUri(plugin.app.vault.getName(), { map: mapName })})`); + }).open(); + }), + ); + }, + ), + ); +} diff --git a/src/plugin/protocolHandlers.ts b/src/plugin/protocolHandlers.ts new file mode 100644 index 00000000..20865b15 --- /dev/null +++ b/src/plugin/protocolHandlers.ts @@ -0,0 +1,50 @@ +/** + * The plugin's obsidian:// actions: duckmage-roll (a table), duckmage-workflow + * (a workflow) and the map / hex link (src/hexLink.ts). Split from + * HexmakerPlugin.onload (plan-architecture-refactor L1a). + */ +import type HexmakerPlugin from "../HexmakerPlugin"; +import { HexMapView } from "../hex-map/HexMapView"; +import { VIEW_TYPE_HEX_MAP } from "../constants"; +import { OPEN_MAP_ACTION, parseMapLinkParams } from "../hexLink"; +import { openRandomTablesAt } from "../workspace/views"; + +export function registerProtocolHandlers(plugin: HexmakerPlugin): void { + plugin.registerObsidianProtocolHandler("duckmage-roll", (params) => { + const filePath = params["file"]; + if (!filePath) return; + openRandomTablesAt(plugin.app.workspace, filePath, "tables"); + }); + + plugin.registerObsidianProtocolHandler("duckmage-workflow", (params) => { + const filePath = params["file"]; + if (!filePath) return; + openRandomTablesAt(plugin.app.workspace, filePath, "workflows"); + }); + + // A map link (`map=`), or a hex link (`map=&x=&y=`: the map centred on + // that hex, e.g. copied from the hex editor's centre dot). src/hexLink.ts. + plugin.registerObsidianProtocolHandler(OPEN_MAP_ACTION, (params) => { + const target = parseMapLinkParams(params); + if (!target) return; + const go = (view: HexMapView, record: boolean) => { + if (target.hex) view.goToHex(target.map, target.hex.x, target.hex.y, { recordHistory: record }); + else view.navigateToMap(target.map, { recordHistory: record }); + }; + const { workspace } = plugin.app; + const leaves = workspace.getLeavesOfType(VIEW_TYPE_HEX_MAP); + if (leaves.length > 0) { + // Revealing loads a deferred (restored, never shown) tab first. + void workspace.revealLeaf(leaves[0]).then(() => { + if (leaves[0].view instanceof HexMapView) go(leaves[0].view, true); + }); + } else { + void workspace.getLeaf("tab") + .setViewState({ type: VIEW_TYPE_HEX_MAP }) + .then(() => { + const view = workspace.getLeavesOfType(VIEW_TYPE_HEX_MAP)[0]?.view; + if (view instanceof HexMapView) go(view, false); + }); + } + }); +} diff --git a/src/plugin/saveFailure.ts b/src/plugin/saveFailure.ts new file mode 100644 index 00000000..64a5c48f --- /dev/null +++ b/src/plugin/saveFailure.ts @@ -0,0 +1,25 @@ +/** + * A save that failed after the caller moved on (saveSettings and the note + * syncs it starts are fired and forgotten): logged, and said in a notice so + * the user knows their change may not be on disk. Saves run on every edit, + * so a disk that keeps failing shows one notice per NOTICE_GAP_MS, not one + * per save; every failure is still logged. + */ +import { logError } from "../log"; +import { noticeBackground } from "../ui/notify"; + +const NOTICE_GAP_MS = 10_000; +let lastNoticeAt = -Infinity; + +/** `what`: what wasn't saved, as it reads in "Couldn't save ". */ +export function reportSaveFailure(what: string, e: unknown, now = Date.now()): void { + logError(`couldn't save ${what}`, e); + if (now - lastNoticeAt < NOTICE_GAP_MS) return; + lastNoticeAt = now; + noticeBackground(`couldn't save ${what} (${e instanceof Error ? e.message : String(e)}). Your last change may not be on disk; check the vault folder can be written to.`, 10_000); +} + +/** Tests: forget the last notice time. */ +export function resetSaveFailureNotices(): void { + lastNoticeAt = -Infinity; +} diff --git a/src/plugin/settingsPersistence.ts b/src/plugin/settingsPersistence.ts new file mode 100644 index 00000000..7a4f288a --- /dev/null +++ b/src/plugin/settingsPersistence.ts @@ -0,0 +1,263 @@ +/** + * The plugin's settings on disk (data.json): loading them (settings-phase + * migrations first, one read), saving them without the note-held paths, + * skipping writes that change nothing, telling our own write echoed back + * from an outside change, and recording the start-up upgrades. Split from + * HexmakerPlugin (plan-architecture-refactor L1b); the plugin keeps + * one-line delegations. + * + * INVARIANT (incident 2026-10-10): load() must not await between swapping + * in the new settings and mapStore.adoptAll(), or a save in between sees + * maps without their paths. tests/integration/settingsPersistence pins it. + */ +import { TFile } from "obsidian"; +import { endNoticeBatch, type NoticeLink } from "../ui/notify"; +import { HexMapView } from "../hex-map/HexMapView"; +import { HexTableView } from "../hex-table/HexTableView"; +import { fillLegacyPathTypes } from "../migrations/v1.5-path-types-explicit"; +import { + DEFAULT_PALETTE_NAME, + DEFAULT_PATH_TYPES, + DEFAULT_SETTINGS, + VIEW_TYPE_HEX_MAP, + VIEW_TYPE_HEX_TABLE, +} from "../constants"; +import { inferKindContent, resolveKindContent } from "../kindContent"; +import { palettesOnLoad } from "../palettes/PaletteStore"; +import { resolveMapKinds } from "../mapKinds"; +import { resolveDefaultPalette, resolveExpandedDefault } from "../palettes/paletteOptions"; +import { clonePathTypes } from "../palettes/pathTypeTable"; +import { normalizeFolder } from "../utils"; +import type { + HexmakerPluginSettings, +} from "../types"; +import { migrateMapData, pluginVersion } from "../compat"; +import { withoutNotePaths } from "../maps/MapStore"; +import { recordMigrationRun, runSettingsMigrations } from "../migrations/registry"; +import { dataFormatOf, newerDataText, stampToSave, writtenByNewer } from "../migrations/stamp"; +import { takeUpgradeReport } from "../migrations/upgradeReport"; +import { writeUpgradeNote } from "../migrations/upgradeNote"; +import changelog from "../../CHANGELOG.md"; +import type HexmakerPlugin from "../HexmakerPlugin"; +import { logError } from "../log"; +import { reportSaveFailure } from "./saveFailure"; +import { tidyLoadedSettings } from "./settingsTidy"; + +/** What SettingsPersistence uses of the plugin. */ +export type SettingsHost = HexmakerPlugin; + +export class SettingsPersistence { + /** `writeRaw` is Obsidian's own Plugin.saveData (the plugin's saveData override delegates here). */ + constructor(private readonly plugin: SettingsHost, private readonly writeRaw: (data: unknown) => Promise) {} + + async loadSettings(): Promise { + // The settings-phase migrations (src/migrations) run on the raw data + // BEFORE Object.assign, so a moved key wins over DEFAULT_SETTINGS. + // One read only: nothing may await between swapping in the new + // settings and handing their maps to the map store (adoptAll below), or a + // save in between would see maps without their paths (incident + // 2026-10-10). rawData is an untouched copy for the "fresh install?" checks. + const loaded = (await this.plugin.loadData()) as Record | null; + const rawData = loaded ? (JSON.parse(JSON.stringify(loaded)) as Record) : null; + this.onDisk = loaded ? JSON.stringify(loaded) : null; + // An existing vault (not a fresh install): the version that last saved it, for the upgrade note. + this.upgradeFrom = rawData ? { version: typeof rawData["savedWith"] === "string" ? rawData["savedWith"] : undefined } : null; + const data = loaded ?? {}; + // Written by a newer build (its data stamp is newer than this build knows): say so once loaded. + this.newerData = writtenByNewer(data) ? newerDataText(data["savedWith"], dataFormatOf(data)) : null; + this.settingsMigrationsRan = runSettingsMigrations(data); + + this.plugin.settings = Object.assign({}, DEFAULT_SETTINGS, data as Partial); + // The data stamp (src/migrations/stamp.ts): written with the next save, never lowered. + this.plugin.settings.dataFormat = stampToSave(this.plugin.settings.dataFormat); + // Own copy: the default is a shared constant, and editors push into lists. + // (Kept only as the fallback palettes are filled from; see getPathTypes.) + this.plugin.settings.pathTypes = clonePathTypes(this.plugin.settings.pathTypes ?? DEFAULT_PATH_TYPES); + + // Deep-clone the maps array so mutations to settings.maps never alias DEFAULT_SETTINGS.maps. + // Object.assign does a shallow copy, so on first run (data===null) settings.maps IS + // DEFAULT_SETTINGS.maps – pushing/mutating it would corrupt the constant for the session. + this.plugin.settings.maps = Array.isArray(this.plugin.settings.maps) + ? this.plugin.settings.maps + : []; + + this.plugin.settings.maps = this.plugin.settings.maps.map((r) => migrateMapData(r, DEFAULT_PALETTE_NAME)); + // Reloaded (onExternalSettingsChange): data.json doesn't hold the paths + // of maps whose note does, so the fresh map objects take the store's at + // once. Missing paths mean "not loaded", never "no paths". + this.plugin.mapStore.adoptAll(); + // Ensure terrainPalettes is valid. An empty list is the user's (every + // palette deleted, SM-DEL): it stays empty; "Add default palettes" in + // settings puts the defaults back on request. + this.plugin.settings.terrainPalettes = palettesOnLoad(this.plugin.settings.terrainPalettes, DEFAULT_SETTINGS.terrainPalettes); + // PA5: path types saved before every behaviour was an explicit option get + // them filled in from the old name rules (once), so no map changes look. + // Notes are migrated by PaletteStore on attach. + if (!this.plugin.settings.pathTypesExplicit) fillLegacyPathTypes(this.plugin.settings.terrainPalettes, this.plugin.settings.pathTypes); + // Unusable values fixed, retired keys dropped (missing keys already have their defaults). + tidyLoadedSettings(this.plugin.settings); + // Own copy (never alias DEFAULT_SETTINGS). Read from the raw data: unset + // (new install / older data) = world, plus space if a palette has space + // terrains already. + this.plugin.settings.mapKinds = resolveMapKinds(data["mapKinds"], this.plugin.settings.terrainPalettes); + // Shipped content per map type (SP3): an update has its types' content + // already; a fresh install writes none until its setup picks the types. + // Setup over without a pick: inferred, nothing installed (saved with the next save). + this.plugin.settings.kindContent = inferKindContent({ ...this.plugin.settings, kindContent: resolveKindContent(rawData, this.plugin.settings.mapKinds) }); + // New maps default to Expanded on fresh installs only (GEN1): decided + // once from the raw data, and saved with it. + this.plugin.settings.expandedByDefault = resolveExpandedDefault(rawData); + const firstExpanded = typeof rawData?.["expandedByDefault"] !== "boolean"; + // "Palette for new maps": seeded once from the above, then the user's. + this.plugin.settings.defaultPalette = resolveDefaultPalette(rawData); + const firstDefaultPalette = typeof rawData?.["defaultPalette"] !== "string"; + const firstKindContent = rawData?.["kindContent"] === undefined; + if (firstKindContent || firstExpanded || firstDefaultPalette) await this.plugin.saveData(this.plugin.settings); + } + + /** + * Settings go to data.json without the paths of maps whose note holds them + * (MapStore.holdsPaths): each map's roads and rivers live only in its map + * note, which a person can read and edit. Maps not yet in a note keep them. + */ + async saveData(data: unknown): Promise { + const ready = !!this.plugin.mapStore?.isReady(); + const out = data !== this.plugin.settings ? data : withoutNotePaths(this.plugin.settings, (name) => ready && this.plugin.mapStore.holdsPaths(name)); + // Same as what data.json holds (last loaded or written): don't touch the + // file. Startup saves that change nothing then leave it alone (smoke C5). + let text: string | null = null; + try { text = JSON.stringify(out); } catch { /* not JSON-able: write it */ } + if (text !== null && text === this.onDisk) return; + this.rememberWrite(out); + await this.writeRaw(out); + this.onDisk = text; + } + + /** Set when data.json was written by a newer build: the notice to show (see stamp.ts). */ + newerData: string | null = null; + + /** Settings-phase migrations that changed data.json on this load (recorded once settings exist). */ + private settingsMigrationsRan: string[] = []; + + /** Set for an existing vault: the version that last saved data.json (null: a fresh install). */ + private upgradeFrom: { version: string | undefined } | null = null; + + /** + * After the start-up upgrades (MG1): record which migrations changed the + * vault (data.json's migrationsRun), write the "Hexmaker upgrade " + * note when an existing vault was upgraded, and show the one combined + * notice, linking the note. A fresh install gets no note. + */ + async finishStartupUpgrades(): Promise { + const entries = takeUpgradeReport(); + let recorded = false; + for (const id of [...this.settingsMigrationsRan, ...entries.flatMap((e) => e.ids ?? [])]) { + if (recordMigrationRun(this.plugin.settings, id)) recorded = true; + } + this.settingsMigrationsRan = []; + let link: NoticeLink | undefined; + const now = pluginVersion(this.plugin); + const upgraded = !!this.upgradeFrom && entries.length > 0 && (entries.some((e) => e.ids?.length) || this.upgradeFrom.version !== now); + if (upgraded) { + try { + const path = await writeUpgradeNote(this.plugin.app, normalizeFolder(this.plugin.settings.worldFolder ?? ""), { + date: new Date(), + from: this.upgradeFrom?.version, + to: now, + entries, + backupsFolder: this.plugin.backupsFolder(), + changelog, + pluginName: this.plugin.manifest.name ?? "Hexmap World Creator", + }); + const name = path.slice(path.lastIndexOf("/") + 1).replace(/\.md$/, ""); + link = { text: `What changed, and the backups: ${name}`, open: () => void this.openVaultNote(path) }; + } catch (e) { + logError("couldn't write the upgrade note", e); + } + } + endNoticeBatch(link); + // Only data.json: the record must not make a fresh install write notes (F19). + if (recorded && this.upgradeFrom) await this.plugin.saveData(this.plugin.settings); + } + + /** Open a vault note in a new tab. */ + private async openVaultNote(path: string): Promise { + const file = this.plugin.app.vault.getAbstractFileByPath(path); + if (file instanceof TFile) await this.plugin.app.workspace.getLeaf("tab").openFile(file); + } + + /** data.json's content as last loaded or written by this session (compact JSON). */ + private onDisk: string | null = null; + + /** What we wrote to data.json lately (compact JSON), to tell our own writes from outside changes. */ + private recentWrites: string[] = []; + + private rememberWrite(data: unknown): void { + try { + this.recentWrites.push(JSON.stringify(data)); + if (this.recentWrites.length > 20) this.recentWrites.shift(); + } catch { /* not JSON-able: never matches */ } + } + + /** data.json holds exactly something this session wrote (an echo of our own save). */ + isOwnWrite(disk: unknown): boolean { + if (disk === null || disk === undefined) return false; + const text = JSON.stringify(disk); + return this.recentWrites.includes(text); + } + + async saveSettings(): Promise { + this.plugin.settings.savedWith = pluginVersion(this.plugin); + this.plugin.settings.dataFormat = stampToSave(this.plugin.settings.dataFormat); + // The setup just finished or was turned off without picking map types + // (e.g. "Don't show again", a recipe): record its types, install nothing. + this.plugin.settings.kindContent = inferKindContent(this.plugin.settings); + // Never rejects: callers fire and forget (`void saveSettings()`), so a + // failed write is logged and said here instead of going unhandled. + try { + await this.plugin.saveData(this.plugin.settings); + } catch (e) { + reportSaveFailure("the plugin's settings", e); + } + // Mirror palette edits (from any editor) into the palette notes. + void this.plugin.paletteStore.sync().catch((e) => reportSaveFailure("the palette notes", e)); + // A terrain added anywhere (palette editor, terrain editor, a new or + // imported palette) gets its empty tables (HG5). + void this.plugin.ensureTablesForNewTerrains().catch((e) => reportSaveFailure("the new terrains' tables", e)); + void this.plugin.mapStore.sync().catch((e) => reportSaveFailure("the map notes", e)); + // Settings hold map-level state (paths, palette, grid size, overlays). + // A save made from one view/window leaves sibling map views stale — + // flag them so they re-render on next activation (issue #32). The + // active map view (the one making the change) is skipped inside + // markStaleFromExternal. + this.plugin.app.workspace.getLeavesOfType(VIEW_TYPE_HEX_MAP).forEach((leaf) => { + if (leaf.view instanceof HexMapView) leaf.view.markStaleFromExternal(); + }); + } + + // Called by Obsidian Sync when it delivers a new data.json from another device. + // Reloads settings into memory and refreshes all open views so the user sees + // the synced state without a manual Obsidian restart. + async onExternalSettingsChange(): Promise { + // Obsidian also fires this for our own saves when several land close + // together (its watcher sees a write it hasn't recorded yet). Reloading + // our own data would at best do nothing and at worst roll back changes + // made since that save, so ignore anything we wrote ourselves. + const disk = (await this.plugin.loadData()) as unknown; + if (this.isOwnWrite(disk)) { + this.onDisk = JSON.stringify(disk); + return; + } + await this.plugin.loadSettings(); + // Map notes hold paths and map settings; the new data.json doesn't win. + // Queued before any sync, so nothing writes the bare copy over a note. + void this.plugin.mapStore.reloadFromNotes().catch((e) => logError("couldn't reload the map notes", e)); + // data.json carries a cached copy of the palettes; the notes win. + await this.plugin.paletteStore.reload(); + this.plugin.loadAvailableIcons(); + this.plugin.refreshHexMap(); + this.plugin.app.workspace.getLeavesOfType(VIEW_TYPE_HEX_TABLE).forEach((leaf) => { + if (leaf.view instanceof HexTableView) void leaf.view.loadTable(); + }); + } +} diff --git a/src/plugin/settingsTidy.ts b/src/plugin/settingsTidy.ts new file mode 100644 index 00000000..42fef1e5 --- /dev/null +++ b/src/plugin/settingsTidy.ts @@ -0,0 +1,31 @@ +/** + * Settings fixes applied on load, after data.json has been merged over + * DEFAULT_SETTINGS (settingsPersistence.loadSettings). Keys missing from + * data.json already have their defaults by then; these handle the keys + * that are present but unusable, and drop settings nothing reads any more. + */ +import type { HexmakerPluginSettings } from "../types"; + +/** + * Settings no build reads any more. Dropped from the settings on load, so + * the next save leaves them out of data.json. Safe for 1.5.x: it never + * read them either (it filled them from its own defaults). + * - mySetting: left over from Obsidian's sample plugin. + * - zoomLevel: the map's zoom is per view. + * - hexEditorTerrainExpanded: expanding Terrain is per hex (round 6). + */ +export const RETIRED_SETTINGS_KEYS = ["mySetting", "zoomLevel", "hexEditorTerrainExpanded"] as const; + +/** Fix up freshly loaded settings in place (see the module comment). */ +export function tidyLoadedSettings(settings: HexmakerPluginSettings): void { + const s = settings as unknown as Record; + for (const key of RETIRED_SETTINGS_KEYS) delete s[key]; + // A missing orientation is the default (flat). One saved but empty or + // unknown has always been read as pointy (1.5.x and earlier), so it stays so. + if (settings.hexOrientation !== "flat" && settings.hexOrientation !== "pointy") settings.hexOrientation = "pointy"; + if (!settings.tablesFolder) settings.tablesFolder = "world/tables"; + if (!settings.defaultTableDice) settings.defaultTableDice = 100; + if (!Array.isArray(settings.rollTableExcludedFolders)) settings.rollTableExcludedFolders = ["terrain"]; + if (!Array.isArray(settings.encounterTableExcludedFolders)) settings.encounterTableExcludedFolders = ["terrain"]; + if (!settings.defaultMap) settings.defaultMap = settings.maps[0]?.name ?? "default"; +} diff --git a/src/plugin/startup.ts b/src/plugin/startup.ts new file mode 100644 index 00000000..95b3405d --- /dev/null +++ b/src/plugin/startup.ts @@ -0,0 +1,93 @@ +/** + * What the plugin does once the workspace layout is ready (the body of + * HexmakerPlugin.onload's onLayoutReady, split out by plan-architecture- + * refactor L1a): the icon list, the stores (held for the setup wizard on a + * fresh install, F19), the one-time note-format upgrades (the migration + * runner) and the one combined upgrade notice. Same steps, same order. + */ +import type HexmakerPlugin from "../HexmakerPlugin"; +import { beginNoticeBatch, noticeBackground } from "../ui/notify"; +import { SANDBOX_MARKER } from "../sandbox"; +import { startupWritesWait } from "../setupPlaceholder"; +import { moduleDevTools, runAfterStoresReady } from "../modules/runtime"; +import { runNoteFormatUpgrades } from "../migrations/registry"; +import { migrate as migrateFlatHexNotes } from "../migrations/v1.0-flat-hex-notes-to-default-map"; +import { upgradeTableRangesOnce } from "../migrations/v1.5-table-roll-ranges"; +import { TableStore } from "../random-tables/TableStore"; +import { logError } from "../log"; + +/** + * Start-up, once the layout is ready. Defer until vault metadata cache is + * ready; calling before layout-ready returns null for all vault paths so + * custom icons are silently dropped. `newerData` is the "written by a + * newer version" notice, if any; `finish` runs once every upgrade is done. + */ +export function startOnLayoutReady(plugin: HexmakerPlugin, newerData: string | null, finish: () => Promise): void { + plugin.loadAvailableIcons(); + // data.json was written by a newer version (its data stamp, MG7): say so, and stay. + if (newerData) noticeBackground(newerData, 0); + // The one-time upgrades below report in ONE notice once they're all + // done, not a stack over the map's toolbar (fresh-eyes 2026-10-13 F2). + beginNoticeBatch(); + // Palettes first (maps reference them), then map notes — which may + // migrate per-hex data out of hex notes on the first run. + // Modules' note stores (biomes, world types) start first, as the + // biome store always did; then the tables and the core's stores. + const storeReady = new Map(plugin.moduleStores.map((st) => [st, st.init()] as const)); + const moduleStoresReady = Promise.all(storeReady.values()); + void plugin.tableNotes.init(); + // A fresh install with the setup wizard about to open: the stores' + // first writes (palette notes, the placeholder map's note) wait until + // the wizard confirms the world folder, or closes, or a map opens, so + // nothing appears in a folder the user hasn't agreed to (fresh-eyes F19). + const gate = startupWritesWait(plugin.settings, (p) => !!plugin.app.vault.getAbstractFileByPath(p)); + plugin.startupWritesHeld = gate.held; + plugin.releaseStartupWrites = () => { + plugin.startupWritesHeld = false; + gate.release(); + }; + // A fresh install has no older palettes to move into notes: its + // palettes are simply written, without the "now notes" notice. + if (gate.held) plugin.settings.palettesMigrated = true; + const storesReady = gate.wait.then(() => plugin.paletteStore.init()).then(() => plugin.mapStore.init()); + plugin.storesStarted = storesReady; + // The world's hex fields note (#52): read once the map store is in; it writes nothing by itself. + void storesReady.then(() => plugin.fields.init()).catch((e) => logError("hex fields", e)); + // Each module's one-time upgrades once its stores and the core's are in + // (World maps, BC1: every overworld hex's biome in its Biome column). + runAfterStoresReady(plugin, storesReady, plugin.moduleStores, storeReady); + void storesReady.then(() => plugin.ensureTablesForNewTerrains()); + // Terrains renamed in a palette note while Obsidian was closed: offer "Rename everywhere". + void storesReady.then(() => plugin.paletteStore.offerPendingRenames()).catch((e) => logError("terrain renames", e)); + // NF1–NF3, once per vault: older hex, token, workflow, map, palette, + // generator and modules' notes (world types) in the new note formats (backed up first). + const formatsDone = Promise.all([storesReady, moduleStoresReady.catch(() => undefined)]).then(() => runNoteFormatUpgrades(plugin)).catch((e) => logError("note format upgrades", e)); + // Hex-note properties follow the map once the notes are in their new formats (MG4). + void formatsDone.then(() => plugin.hexProps.start()); + // Sandbox vaults (dev/demo-world.mjs) get the demo builders; nothing else does. + void plugin.app.vault.adapter.exists(SANDBOX_MARKER).then((sandbox) => { + if (!sandbox) return; + plugin.devTools = moduleDevTools(plugin); + }); + const registered = plugin.autoRegisterMapsFromVault(); + // Hand edits to table notes (ranges, die, weights) are imported. + TableStore.register(plugin); + let rangesDone: Promise = Promise.resolve(); + if (!plugin.settings.setupComplete && !plugin.settings.setupDismissed) { + plugin.openSetupWizard(); + } else { + // Once after updating: add roll ranges to older tables, silently, + // after a backup (DJ-Q6). After the stores load, for the same reason. + rangesDone = storesReady.then(() => upgradeTableRangesOnce(plugin)); + } + void Promise.allSettled([storesReady, formatsDone, registered, rangesDone]).then(() => finish()); +} + +/** Pre-1.0 hex notes loose in the hexes folder move into the "default" map's folder. */ +export async function migrateHexFilesToDefaultRegion(plugin: HexmakerPlugin): Promise { + const moved = await migrateFlatHexNotes(plugin.app, plugin.settings.hexFolder); + if (moved > 0) + noticeBackground( + `migrated ${moved} hex file(s) to "default" region.`, + ); +} diff --git a/src/plugin/vaultEvents.ts b/src/plugin/vaultEvents.ts new file mode 100644 index 00000000..33634f56 --- /dev/null +++ b/src/plugin/vaultEvents.ts @@ -0,0 +1,170 @@ +/** + * ONE handler per vault / workspace event for the whole plugin (plan- + * architecture-refactor L1a). Each event runs its steps in the order the + * separate handlers used to be registered in HexmakerPlugin.onload, so + * who sees a change first is unchanged: + * + * metadata changed: pending-terrain cache → hex-note properties → hex fields' places + * file-open: hex-note properties → region/faction callout, hex callout focus + * create: icons → palette store → module stores → map store → fields note + * modify: palette store → module stores → map store → fields note + * delete: hex-note properties → icons → map store → palette store → module stores → callout memory → fields note → workflow steps + * rename: hex-note properties → icons → palette store → module stores → callout memory → region note → fields note → linkedFolder links + * active-leaf-change: palette store (derived cells) + * + * Each group that used to be its own handler is isolated as Obsidian + * isolated handlers: one throwing (logged) doesn't stop the next. + */ +import { Notice, TFile, type TAbstractFile } from "obsidian"; +import type HexmakerPlugin from "../HexmakerPlugin"; +import { clearPendingTerrain } from "../frontmatter"; +import { onTableDeleted, onTableFolderRenamed } from "../random-tables/tableVaultEvents"; +import { normalizeFolder } from "../utils"; +import { logError } from "../log"; +import { hexXY } from "../hexKey"; + +/** Run one former handler; an error is logged and the next still runs. */ +function step(run: () => void): void { + try { + run(); + } catch (e) { + logError("vault event handler", e); + } +} + +export function registerVaultEvents(plugin: HexmakerPlugin): void { + const { app } = plugin; + const sync = plugin.hexProps; + + // Live-refresh the icon list when image files appear in / leave the + // icons folder. Without this, icons dropped in via the OS file explorer + // needed an Obsidian restart to show up in the pickers (forum report). + const isIconFile = (path: string): boolean => { + const folder = normalizeFolder(plugin.settings.iconsFolder ?? ""); + if (!folder) return false; + return ( + path.startsWith(folder + "/") && + /\.(png|jpg|jpeg|gif|svg|webp)$/i.test(path) + ); + }; + const hexNoteFocus = hexNoteFocusTracker(plugin); + + plugin.registerEvent(app.metadataCache.on("changed", (file, data) => { + // Notes written by this plugin are read from memory until indexed (see frontmatter.ts). + step(() => clearPendingTerrain(file.path)); + // A hex note's properties edited (properties panel, text, sync). + step(() => sync.onMetadataChanged(file, data)); + // A Towns link or a place-type changed: hex fields find the places again. + step(() => plugin.fields.onMetadataChanged()); + })); + + plugin.registerEvent(app.workspace.on("file-open", (file) => { + // Leaving a note settles edits held while it was open. + step(() => sync.onFileOpen(file)); + // A region or faction note's Map data callout is refreshed when it's opened (R1). + step(() => { + if (file && plugin.regionOrFactionKind(file)) void plugin.refreshRegionMapData(file); + hexNoteFocus(file); + }); + })); + + plugin.registerEvent(app.vault.on("create", (f) => { + step(() => { + if (isIconFile(f.path)) plugin.loadAvailableIcons(); + plugin.paletteStore.onModify(f); + for (const st of plugin.moduleStores) st.onCreate?.(f); + plugin.mapStore.onCreate(f); + plugin.fields.store.onModify(f); + }); + })); + + plugin.registerEvent(app.vault.on("delete", (f) => { + step(() => sync.onDelete(f.path)); + step(() => { + if (isIconFile(f.path)) plugin.loadAvailableIcons(); + plugin.mapStore.onDelete(f); + plugin.paletteStore.onDelete(f); + for (const st of plugin.moduleStores) st.onDelete?.(f); + plugin.calloutMemory.forget(f.path); + plugin.fields.store.onDelete(f); + }); + // Remove workflow steps that reference a deleted table file. + step(() => void onTableDeleted(plugin, f)); + })); + + plugin.registerEvent(app.vault.on("rename", (f, oldPath) => { + step(() => sync.onRename(oldPath, f.path)); + step(() => { + if (isIconFile(f.path) || isIconFile(oldPath)) plugin.loadAvailableIcons(); + plugin.paletteStore.onRename(f, oldPath); + for (const st of plugin.moduleStores) st.onRename?.(f, oldPath); + plugin.calloutMemory.rename(oldPath, f.path); + if (f instanceof TFile) void onRegionNoteRenamed(plugin, f, oldPath); + plugin.fields.store.onRename(f, oldPath); + }); + // Keep linkedFolder frontmatter in sync when a folder is renamed. + step(() => void onTableFolderRenamed(plugin, f, oldPath)); + })); + + // Palette notes edited by hand (or by sync) flow back into the palettes. + plugin.registerEvent(app.vault.on("modify", (f: TAbstractFile) => { + step(() => { + plugin.paletteStore.onModify(f); + for (const st of plugin.moduleStores) st.onModify?.(f); + plugin.mapStore.onModify(f); + plugin.fields.store.onModify(f); + }); + })); + + // A hand-edited palette note's derived cells ("(yes)", "(mountains)") + // are refreshed once the user stops editing it. + plugin.registerEvent(app.workspace.on("active-leaf-change", () => plugin.paletteStore.flushPendingDerived())); +} + +/** + * A file opened in an editor: a hex note left behind has its Map data + * callout synced (hand edits made in it go to the map), and a hex note + * being opened gets its callout brought up to date before it's edited. + * Not while the user is still in the note: rewriting it mid-typing would + * fight the editor. + */ +function hexNoteFocusTracker(plugin: HexmakerPlugin): (file: TFile | null) => void { + /** The hex note last opened in an editor (its callout is synced when another file opens). */ + let focusedHexNote: string | null = null; + return (file) => { + const sync = (path: string) => { + const loc = plugin.mapStore.isReady() ? plugin.mapStore.resolve(path) : null; + if (!loc || !plugin.getMap(loc.map)) return; + const { x, y } = hexXY(loc.key); + void plugin.syncHexMapData(loc.map, x, y); + }; + const prev = focusedHexNote; + const next = file && plugin.mapStore.isReady() && plugin.mapStore.resolve(file.path) ? file.path : null; + if (prev && prev !== file?.path) sync(prev); + if (next && next !== prev) sync(next); + focusedHexNote = next; + }; +} + +/** + * A note in the regions folder was renamed (R2): its hexes keep their + * region, and its encounter table follows the name (unless the new name + * already has one). + */ +async function onRegionNoteRenamed(plugin: HexmakerPlugin, file: TFile, oldPath: string): Promise { + const folder = normalizeFolder(plugin.settings.regionsFolder ?? ""); + if (!folder || !oldPath.startsWith(folder + "/") || !/\.md$/i.test(oldPath)) return; + const oldName = oldPath.slice(oldPath.lastIndexOf("/") + 1).replace(/\.md$/i, ""); + const newName = file.basename; + if (oldName === newName || oldName.startsWith("_") || !plugin.mapStore.isReady()) return; + const n = plugin.renameRegionInMaps(oldName, newName); + const tables = normalizeFolder(plugin.settings.tablesFolder); + const sub = tables ? `${tables}/regions` : "regions"; + const table = plugin.app.vault.getAbstractFileByPath(`${sub}/${oldName}.md`); + if (table instanceof TFile && !plugin.app.vault.getAbstractFileByPath(`${sub}/${newName}.md`)) { + try { + await plugin.app.fileManager.renameFile(table, `${sub}/${newName}.md`); + } catch { /* the hexes still keep their region */ } + } + if (n) new Notice(`Region renamed: ${n} hex${n === 1 ? "" : "es"} now in "${newName}".`); +} diff --git a/src/ports.ts b/src/ports.ts new file mode 100644 index 00000000..fa8843f5 --- /dev/null +++ b/src/ports.ts @@ -0,0 +1,58 @@ +/** + * The module-level ports: functions the plugin hands to plain modules on + * load so they can reach plugin state without importing the plugin + * (hex data: maps/hexData.ts; hex field fills: maps/fieldFill.ts; the work-mode gates, palette previews, icon + * pickers, slider number boxes). + * + * The eighth port, setBiomeSource (overworld/biomes.ts), is not here: it + * is World maps module code (core may not import it: tests/moduleBoundary), + * and BiomeStore, not the plugin, feeds it as biome notes load. + * + * bindPorts(plugin) wires all of them in one place; HexmakerPlugin.onload + * calls it (in the order onload used to set them itself). resetPorts() puts + * every port back to its module default (for tests; onunload doesn't call + * it yet, as the plugin never did). + */ +import type HexmakerPlugin from "./HexmakerPlugin"; +import { setIconPackDefault } from "./HexmakerModal"; +import { setHexDataSource } from "./maps/hexData"; +import { setFieldFiller } from "./maps/fieldFill"; +import { setHandEditListener, setModeMapLookup } from "./modeGate"; +import { setPaletteTerrainSource } from "./palettes/paletteOptions"; +import { setPathEditMapLookup } from "./paths/editGate"; +import { isDebugMode } from "./ui/debugMode"; +import { setNumberBoxDebug } from "./ui/numberBoxes"; +import { defaultIconPack } from "./utils"; + +/** What the ports read from the plugin. */ +export type PortsHost = Pick & { fields?: Pick }; + +/** Point every plugin-fed port at `plugin`. */ +export function bindPorts(plugin: PortsHost): void { + // Icon pickers open on the Space tab for space-only setups. + setIconPackDefault(() => defaultIconPack(plugin.settings)); + // Number boxes beside sliders follow debug mode (src/ui/numberBoxes.ts). + setNumberBoxDebug(() => isDebugMode(plugin.app)); + // Palette pickers preview the picked palette's terrains (E4). + setPaletteTerrainSource((name) => plugin.getPaletteOrPresetTerrains(name)); + setHexDataSource(plugin.mapStore); + setPathEditMapLookup((name) => plugin.getMap(name)); + setModeMapLookup((name) => plugin.getMap(name)); + // The first hand edit of a new (open) place locks it (ArrivalService.lockOnHandEdit). + setHandEditListener((name) => plugin.arrival.lockOnHandEdit(name)); + // A hex that gets terrain has its blank hex fields worked out in the same write (#52). + const fields = plugin.fields; + setFieldFiller(fields ? (map, key, h) => fields.fillFor(map, key, h) : null); +} + +/** Every port back to its module default (nothing bound). */ +export function resetPorts(): void { + setIconPackDefault(() => "all"); + setNumberBoxDebug(() => false); + setPaletteTerrainSource(null); + setHexDataSource(null); + setPathEditMapLookup(null); + setModeMapLookup(null); + setHandEditListener(null); + setFieldFiller(null); +} diff --git a/src/provenance.ts b/src/provenance.ts new file mode 100644 index 00000000..4aa50733 --- /dev/null +++ b/src/provenance.ts @@ -0,0 +1,39 @@ +/** + * Where a note the plugin writes came from, recorded in its frontmatter so + * the raw note says it (workflow results, exports). Pure: no Obsidian + * imports. + */ + +import { escapeRegex } from "./textUtils"; + +/** Local date and time as Obsidian's date & time property writes it: 2026-10-10T14:03:00. */ +export function localIsoDateTime(d: Date = new Date()): string { + const p = (n: number) => String(n).padStart(2, "0"); + return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())}T${p(d.getHours())}:${p(d.getMinutes())}:${p(d.getSeconds())}`; +} + +/** A wiki-link to a vault path (".md" dropped), quoted for YAML: "[[world/tables/aspects]]". */ +export function yamlLink(path: string): string { + return JSON.stringify(`[[${path.replace(/\.md$/i, "")}]]`); +} + +/** + * Set top-level frontmatter keys to raw YAML values, adding a frontmatter + * block when there isn't one. Keys already there are replaced in place; + * every other line is kept as typed. + */ +export function withFrontmatterEntries(content: string, entries: [key: string, yaml: string][]): string { + // The block uses the note's first line ending; the rest is kept byte for byte. + const eol = /^[^\n]*\r\n/.test(content) ? "\r\n" : "\n"; + const m = /^---\r?\n([\s\S]*?)\r?\n?---[ \t]*(?:\r?\n|$)/.exec(content); + const lines = m ? (m[1] === "" ? [] : m[1].split(/\r?\n/)) : []; + for (const [key, yaml] of entries) { + const keyRe = new RegExp(`^${escapeRegex(key)}\\s*:`); + const at = lines.findIndex((l) => keyRe.test(l)); + const line = `${key}: ${yaml}`; + if (at >= 0) lines[at] = line; + else lines.push(line); + } + const rest = m ? content.slice(m[0].length) : content; + return ["---", ...lines, "---", ""].join(eol) + rest; +} diff --git a/src/random-tables/ConfirmDeleteModal.ts b/src/random-tables/ConfirmDeleteModal.ts deleted file mode 100644 index f0df83b8..00000000 --- a/src/random-tables/ConfirmDeleteModal.ts +++ /dev/null @@ -1,37 +0,0 @@ -import { App, Modal } from "obsidian"; - -export class ConfirmDeleteModal extends Modal { - constructor( - app: App, - private readonly tableName: string, - private readonly onConfirm: () => Promise, - ) { - super(app); - } - - onOpen(): void { - const { contentEl } = this; - contentEl.createEl("p", { - text: `Delete "${this.tableName}"? This cannot be undone.`, - }); - const btnRow = contentEl.createDiv({ cls: "duckmage-confirm-btn-row" }); - - const deleteBtn = btnRow.createEl("button", { - text: "Delete", - cls: "mod-warning", - }); - deleteBtn.addEventListener("click", () => { - void (async () => { - this.close(); - await this.onConfirm(); - })(); - }); - - const cancelBtn = btnRow.createEl("button", { text: "Cancel" }); - cancelBtn.addEventListener("click", () => this.close()); - } - - onClose(): void { - this.contentEl.empty(); - } -} diff --git a/src/random-tables/RandomTableEditorModal.ts b/src/random-tables/RandomTableEditorModal.ts index 4b5a207e..6839a008 100644 --- a/src/random-tables/RandomTableEditorModal.ts +++ b/src/random-tables/RandomTableEditorModal.ts @@ -1,20 +1,61 @@ import { App, Notice, TFile } from "obsidian"; import { HexmakerModal } from "../HexmakerModal"; -import { parseRandomTable, extractPostTableContent, parseMarkdownListItems } from "./randomTable"; -import type { RandomTableEntry } from "./randomTable"; +import { dragGrip } from "../ui/pickers"; +import { + parseRandomTableWithReport, + parseMarkdownListItems, + writeRollTable, + rangeCellTexts, + resolveTable, + dieLabel, + readTableWeight, + rowOdds, + type RandomTableEntry, + type TableWrite, +} from "./randomTable"; import { FileLinkSuggestModal } from "../hex-map/FileLinkSuggestModal"; +import { IMPORT_LIST_EXTENSIONS } from "../notePickers"; +import { processTableNote } from "./TableStore"; import type HexmakerPlugin from "../HexmakerPlugin"; import { normalizeFolder } from "../utils"; -import { escapeRegex, escapeTableCell } from "../textUtils"; +import { escapeRegex } from "../textUtils"; +import { oddsText } from "../ui/odds"; +import { renderSaveStatusLine } from "../ui/saveStatusLine"; +import { tableTitle } from "../encounterLinks"; +import { currentText, linkedFolderAllowed, missingRowNotes, renameUpdatedEntries, retireDeletedEntries, syncLinkedFolder } from "./tableEditor/linkedFolder"; + +/** How the editor writes the die column: ranges are redone when weights or rows change. */ +export function editorRangeMode(rowsOrWeightsChanged: boolean): TableWrite["ranges"] { + return rowsOrWeightsChanged ? "regenerate" : "keep"; +} + +/** + * Each row's % as the editor shows it: from the note's own roll ranges + * while the rows and weights are as written, else from the weights (the + * ranges are redone from them on save). Owner Q1: a % column beside the + * free weights, always up to date. + */ +export function editorOdds(dice: number, entries: readonly RandomTableEntry[], rowsOrWeightsChanged: boolean): string[] { + if (!rowsOrWeightsChanged) return rowOdds({ dice, entries: [...entries] }); + return oddsText(entries.map((e) => e.weight)); +} /** * Modal editor for a random table file. * Shows existing entries as editable rows and allows adding new ones. - * Saves back to the file, preserving frontmatter. + * Autosaves when closed (× only, no footer button: owner Q5), preserving + * frontmatter; a hand edit to the note while nothing was changed here + * redraws it from the note. */ export class RandomTableEditorModal extends HexmakerModal { + protected surfaceId = "TableEditor"; // Held so onClose can flush a pending "add row" entry and save it private flushAndSave: (() => Promise) | null = null; + /** Something was changed here (a hand edit to the note then doesn't redraw over it). */ + private touched = false; + private modifyRef: ReturnType | null = null; + /** The note text the editor was drawn from. */ + private shownContent = ""; constructor( app: App, @@ -27,29 +68,54 @@ export class RandomTableEditorModal extends HexmakerModal { } async onOpen(): Promise { - this.titleEl.setText(`Edit: ${this.file.basename}`); + this.titleEl.setText(`Edit: ${tableTitle(this.file.path)}`); const { contentEl } = this; contentEl.addClass("duckmage-table-editor"); const rawContent = this.initialContent ?? (await this.app.vault.read(this.file)); - const table = parseRandomTable(rawContent); + this.touched = false; + // Any typing or picking here counts as a change. + contentEl.addEventListener("input", () => { this.touched = true; }); + contentEl.addEventListener("change", () => { this.touched = true; }); + // A hand edit to the note while nothing changed here: redraw from it (its % column too). + if (!this.modifyRef) { + this.modifyRef = this.app.vault.on("modify", (f) => { + if (f !== this.file || this.touched) return; + void this.app.vault.read(this.file).then((text) => { + if (this.touched || text === this.shownContent) return; + this.initialContent = text; + contentEl.empty(); + this.resetDisclosure(); + this.flushAndSave = null; + void this.onOpen(); + }); + }); + } + this.shownContent = rawContent; + const report = parseRandomTableWithReport(rawContent); + const table = report.table; const frontmatter = this.extractFrontmatter(rawContent); - const preamble = this.extractPreamble(rawContent, frontmatter); // Working copy so edits don't mutate until Save const entries: RandomTableEntry[] = table.entries.map((e) => ({ ...e })); - - // If linked to a folder, silently drop entries whose note no longer exists - if (table.linkedFolder) { - const lf = normalizeFolder(table.linkedFolder); - for (let i = entries.length - 1; i >= 0; i--) { - if ( - !this.app.vault.getAbstractFileByPath(`${lf}/${entries[i].result}.md`) - ) { - entries.splice(i, 1); - } - } + // Which parsed row each entry came from (survives drag-reorder), so the + // writer keeps that row's raw text: extra columns, aliases, spacing. + const entrySource = new WeakMap(); + entries.forEach((e, i) => entrySource.set(e, i)); + + // Linked-folder rows whose note is missing are kept and reported, not + // deleted: the note may have been renamed or moved elsewhere. + const missingAtOpen = table.linkedFolder + ? missingRowNotes(this.app, normalizeFolder(table.linkedFolder), entries) + : new Set(); + if (missingAtOpen.size) { + const warn = contentEl.createDiv({ cls: "duckmage-table-editor-warning" }); + const names = [...missingAtOpen]; + warn.setText( + `${names.length === 1 ? "This row has" : "These rows have"} no note in ${table.linkedFolder}: ${names.slice(0, 8).join(", ")}${names.length > 8 ? ", …" : ""}. ` + + `${names.length === 1 ? "It's" : "They're"} kept; delete ${names.length === 1 ? "it" : "them"} here if the note is gone for good.`, + ); } // Track each entry's original result by object identity (survives drag-reorder) @@ -72,6 +138,8 @@ export class RandomTableEditorModal extends HexmakerModal { cls: "duckmage-table-editor-name-input", }); nameInput.value = this.file.basename; + // The shared autosave line (no Close button: × closes and saves). + renderSaveStatusLine(contentEl, { title: "Saves when you close this (×). There is no Save button." }); const doRename = async () => { const newName = nameInput.value.trim(); @@ -83,7 +151,7 @@ export class RandomTableEditorModal extends HexmakerModal { const newPath = dir + newName + ".md"; try { await this.app.fileManager.renameFile(this.file, newPath); - this.titleEl.setText(`Edit: ${this.file.basename}`); + this.titleEl.setText(`Edit: ${tableTitle(this.file.path)}`); this.onSaved?.(); } catch { nameInput.value = this.file.basename; // revert on error @@ -161,10 +229,10 @@ export class RandomTableEditorModal extends HexmakerModal { const subOneToAllBtn = entriesHeadingRow.createEl("button", { text: "-1", cls: "duckmage-table-editor-add-one-btn", - attr: { title: "Add 1 to every entry's weight" }, + attr: { title: "Subtract 1 from every entry's weight (stops at 0)" }, }); subOneToAllBtn.addEventListener("click", () => { - for (const e of entries) e.weight -= 1; + for (const e of entries) e.weight = Math.max(0, e.weight - 1); renderRows(); }); const addOneToAllBtn = entriesHeadingRow.createEl("button", { @@ -202,6 +270,8 @@ export class RandomTableEditorModal extends HexmakerModal { })(); }, "", + // Text it can read as entries (list items or lines), not images or PDFs. + IMPORT_LIST_EXTENSIONS, ).open(); }); @@ -216,8 +286,33 @@ export class RandomTableEditorModal extends HexmakerModal { el.setCssProps({ height: `${el.scrollHeight}px` }); }; + // Rows added, removed, reordered or reweighted: the ranges are redone. + const rowsOrWeightsChanged = (): boolean => + entries.length !== table.entries.length || + entries.some((e, i) => entrySource.get(e) !== i || e.weight !== table.entries[i].weight); + // Each row's roll range, as it will be written. + let rangeEls: HTMLElement[] = []; + // Each row's % (owner Q1), next to its weight. + let oddsEls: HTMLElement[] = []; + const onWeightsChanged = (): void => { + const changed = rowsOrWeightsChanged(); + const odds = editorOdds(table.dice, entries, changed); + oddsEls.forEach((el, i) => el.setText(odds[i] ?? "–")); + if (table.dice <= 0) return; + const labels = changed + ? rangeCellTexts(table.dice, entries, "regenerate") + : resolveTable({ dice: table.dice, entries }).labels; + rangeEls.forEach((el, i) => el.setText(labels[i] || "—")); + }; + + let drawn = false; const renderRows = () => { + // Every redraw after the first is a change made here (sort, ±1, add, remove, move). + if (drawn) this.touched = true; + drawn = true; rowsEl.empty(); + rangeEls = []; + oddsEls = []; if (entries.length === 0) { rowsEl.createSpan({ text: "No entries yet.", @@ -225,16 +320,27 @@ export class RandomTableEditorModal extends HexmakerModal { }); return; } + // Column headers, laid out like the rows (fresh-eyes F16 / C12: the + // weight column had no name). + const cols = rowsEl.createDiv({ cls: "duckmage-table-editor-row duckmage-table-editor-cols", attr: { "aria-hidden": "true" } }); + dragGrip(cols, "duckmage-table-editor-drag-handle duckmage-table-editor-col-spacer"); + if (table.dice > 0) cols.createSpan({ cls: "duckmage-table-editor-range", text: "Roll" }); + cols.createSpan({ cls: "duckmage-table-editor-col-result", text: "Result" }); + cols.createSpan({ cls: "duckmage-table-editor-weight duckmage-table-editor-col-weight", text: "Weight" }); + cols.createSpan({ cls: "duckmage-odds-percent duckmage-table-editor-odds", text: "Odds" }); + cols.createSpan({ cls: "duckmage-table-editor-del duckmage-table-editor-col-spacer", text: "×" }); for (let i = 0; i < entries.length; i++) { const entry = entries[i]; const row = rowsEl.createDiv({ cls: "duckmage-table-editor-row" }); row.draggable = true; - const handle = row.createSpan({ - cls: "duckmage-table-editor-drag-handle", - text: "⠿", - }); + const handle = dragGrip(row, "duckmage-table-editor-drag-handle"); handle.title = "Drag to reorder"; + if (table.dice > 0) { + const rangeEl = row.createSpan({ cls: "duckmage-table-editor-range" }); + rangeEl.title = `Roll range on the ${dieLabel(table.dice)} (from the weights)`; + rangeEls.push(rangeEl); + } const resultInput = row.createEl("textarea", { cls: "duckmage-table-editor-result", @@ -242,6 +348,7 @@ export class RandomTableEditorModal extends HexmakerModal { // Show [[path]] for link entries so the user can see and edit the link format resultInput.value = entry.isLink ? `[[${entry.result}]]` : entry.result; resultInput.placeholder = "Result…"; + resultInput.setAttr("aria-label", "Result"); resultInput.rows = 1; // Size to content immediately, then keep in sync as the user types window.requestAnimationFrame(() => autoResize(resultInput)); @@ -263,19 +370,15 @@ export class RandomTableEditorModal extends HexmakerModal { cls: "duckmage-table-editor-weight", }); weightInput.value = String(entry.weight); - //weightInput.min = "1"; + weightInput.min = "0"; + weightInput.step = "any"; + weightInput.title = "Weight (0 = never rolled)"; + weightInput.setAttr("aria-label", "Weight"); weightInput.addEventListener("input", () => { - entries[i].weight = Math.max(1, parseInt(weightInput.value, 10) || 1); + entries[i].weight = readWeight(weightInput.value); + onWeightsChanged(); }); - // weightInput.addEventListener("keydown", (e: KeyboardEvent) => { - // if (e.key === "ArrowDown" && entries[i].weight <= 1) { - // e.preventDefault(); - // for (let j = 0; j < entries.length; j++) { - // if (j !== i) entries[j].weight += 1; - // } - // renderRows(); - // } - // }); + oddsEls.push(row.createSpan({ cls: "duckmage-odds-percent duckmage-table-editor-odds", attr: { title: "This row's share of the rolls" } })); const delBtn = row.createEl("button", { text: "×", @@ -321,6 +424,7 @@ export class RandomTableEditorModal extends HexmakerModal { renderRows(); }); } + onWeightsChanged(); }; renderRows(); @@ -337,14 +441,21 @@ export class RandomTableEditorModal extends HexmakerModal { cls: "duckmage-table-editor-result", }); newResult.placeholder = "New result…"; + newResult.setAttr("aria-label", "New result"); newResult.rows = 1; - const newWeight = addRow.createEl("input", { + // The weight box is labelled (fresh-eyes F16: a bare "1" beside the result). + const newWeightLabel = addRow.createEl("label", { cls: "duckmage-table-editor-add-weight" }); + newWeightLabel.createSpan({ text: "Weight", cls: "duckmage-table-editor-add-weight-text" }); + + const newWeight = newWeightLabel.createEl("input", { type: "number", cls: "duckmage-table-editor-weight", + attr: { title: "Weight (0 = never rolled)" }, }); newWeight.value = "1"; - newWeight.min = "1"; + newWeight.min = "0"; + newWeight.step = "any"; const addBtn = addRow.createEl("button", { text: "Add", @@ -458,6 +569,19 @@ export class RandomTableEditorModal extends HexmakerModal { this.parseFrontmatterBool(frontmatter, "encounter-filter") === false; encFilterRow.createEl("label", { text: "Exclude from encounters table" }); + // ── Advanced: bulk weight steps, import, linked folder, filters ── + // (Placement map; the filters stay hidden on the map's own tables.) + this.place("TableEditor.minusOneAll", subOneToAllBtn); + this.place("TableEditor.plusOneAll", addOneToAllBtn); + this.place("TableEditor.import", importBtn); + // Set ones count in the header ("Advanced · 1 set"). + this.place("TableEditor.linkedFolder", folderRow, () => folderInput.value.trim() !== ""); + if (!isSystemTable) { + this.place("TableEditor.excludeRollPicker", rollFilterRow, () => rollFilterCb.checked); + this.place("TableEditor.excludeEncounters", encFilterRow, () => encFilterCb.checked); + } + this.disclosure.toEnd(); + const doAdd = () => { const raw = newResult.value.trim(); if (!raw) return; @@ -497,11 +621,11 @@ export class RandomTableEditorModal extends HexmakerModal { errorEl.hide(); // Store the vault-relative path without extension (canonical link form) const resolvedPath = found.path.replace(/\.md$/i, ""); - const weight = Math.max(1, parseInt(newWeight.value, 10) || 1); + const weight = readWeight(newWeight.value); entries.push({ result: resolvedPath, weight, isLink: true }); } else { errorEl.hide(); - const weight = Math.max(1, parseInt(newWeight.value, 10) || 1); + const weight = readWeight(newWeight.value); entries.push({ result: raw, weight }); } @@ -510,10 +634,10 @@ export class RandomTableEditorModal extends HexmakerModal { renderRows(); newResult.focus(); }; - // Expose so onClose always saves all changes (flushes pending "add row" text first) + // Expose so onClose saves all changes (flushes pending "add row" text + // first). Nothing is written unless something actually changed. this.flushAndSave = async () => { doAdd(); // flush pending "add row" text if any (no-op if empty) - const suffix = extractPostTableContent(rawContent) || undefined; let updatedFm = this.setFrontmatterBool( frontmatter, "roll-filter", @@ -525,47 +649,76 @@ export class RandomTableEditorModal extends HexmakerModal { encFilterCb.checked ? false : undefined, ); const linkedFolder = normalizeFolder(folderInput.value.trim()); - updatedFm = this.setFrontmatterString( - updatedFm, - "linkedFolder", - linkedFolder ? `"[[${linkedFolder}]]"` : undefined, - ); - if (linkedFolder) { - await this.renameUpdatedEntries( - entries, - entryOriginalResult, - linkedFolder, + if (linkedFolder !== normalizeFolder(table.linkedFolder ?? "")) { + updatedFm = this.setFrontmatterString( + updatedFm, + "linkedFolder", + linkedFolder ? `"[[${linkedFolder}]]"` : undefined, ); - await this.retireDeletedEntries(originalResults, entries, linkedFolder); - await this.syncLinkedFolder(entries, linkedFolder); } - // Rebuild preamble: preserve or insert roller block, replace user description - const rollerLinkMatch = - preamble.match(/```duckmage-roller[\s\S]*?```/) ?? - preamble.match(/\[.*?\]\(obsidian:\/\/duckmage-roll[^)]*\)/); - // Always include a roller — upgrade old URI links to the code block form - const rollerLink = - rollerLinkMatch?.index !== undefined && - /```duckmage-roller/.test(rollerLinkMatch[0]) - ? rollerLinkMatch[0] - : "```duckmage-roller\n```"; + // Edited elsewhere while this was open (a hand edit, a sync, a + // rename rewrite): keep that, write nothing, and say so. + const stale = () => new Notice(`${this.file.basename} was changed elsewhere while this was open, so your changes here weren't saved.`); + if ((await currentText(this.app, this.file)) !== rawContent) { stale(); return; } + let before = rawContent; + if (linkedFolder && !linkedFolderAllowed(linkedFolder, this.plugin.settings)) { + new Notice(`The linked folder ${linkedFolder} isn't inside the world folder, so its notes weren't synced.`); + } else if (linkedFolder) { + await renameUpdatedEntries(this.app, entries, entryOriginalResult, linkedFolder); + await retireDeletedEntries(this.app, originalResults, entries, linkedFolder); + await syncLinkedFolder(this.app, entries, linkedFolder, missingAtOpen); + // Renaming a row's note can rewrite its link in this table. + before = (await currentText(this.app, this.file)) ?? rawContent; + } + + // ── Table: only its own lines are rewritten, and only if it changed. + const orig = table.entries; + const reweighted = rowsOrWeightsChanged(); + const textChanged = entries.some((e) => { + const src = entrySource.get(e); + return src === undefined || orig[src].result !== e.result || !!orig[src].isLink !== !!e.isLink; + }); + let next = rawContent; + if (reweighted || textChanged) { + next = writeRollTable(rawContent, { + dice: table.dice, + rows: entries.map((entry) => ({ entry, source: entrySource.get(entry) })), + ranges: editorRangeMode(reweighted), + linkCells: !!linkedFolder, + dropPlaceholders: true, + }); + } + + // ── Description: only the text between frontmatter and table, only if edited. const newDescription = descInput.value.trim(); - const newPreamble = [rollerLink, newDescription] - .filter(Boolean) - .join("\n\n"); - const newContent = this.buildContent( - updatedFm, - newPreamble, - entries, - linkedFolder || undefined, - suffix, - ); + if (newDescription !== (table.description ?? "")) { + const eol = rawContent.includes("\r\n") ? "\r\n" : "\n"; + const fmEnd = frontmatter ? frontmatter.length : 0; + const tableStart = report.block ? report.block.start : fmEnd; + const preamble = rawContent.slice(fmEnd, tableStart); + // Keep the roller block; an old roller link becomes the block. + const roller = + /```duckmage-roller[\s\S]*?```/.exec(preamble)?.[0] ?? "```duckmage-roller" + eol + "```"; + const parts = [roller, newDescription.replace(/\r?\n/g, eol)].filter(Boolean); + const newPreamble = (frontmatter ? eol + eol : "") + parts.join(eol + eol) + (report.block ? eol + eol : eol); + // The table write above leaves everything before the table as it was. + next = next.slice(0, fmEnd) + newPreamble + next.slice(tableStart); + } + + if (updatedFm !== frontmatter) next = updatedFm + next.slice(frontmatter.length); + if (next === rawContent) return; + let wrote = false; try { - await this.app.vault.process(this.file, () => newContent); - this.onSaved?.(); + await processTableNote(this.app, this.file, (current) => { + if (current !== before) return current; + wrote = true; + return next; + }); } catch { - /* best-effort */ + return; /* best-effort */ } + if (wrote) this.onSaved?.(); + else stale(); }; addBtn.addEventListener("click", doAdd); @@ -577,103 +730,20 @@ export class RandomTableEditorModal extends HexmakerModal { } }); - // ── Footer: Close (auto-saves on close) ─────────────────────────── - const footer = contentEl.createDiv({ cls: "duckmage-table-editor-footer" }); - - footer - .createEl("button", { text: "Close", cls: "mod-cta" }) - .addEventListener("click", () => this.close()); - + // No footer (owner Q5): × closes, and closing saves. this.makeDraggable(); - } - - /** Sync entries ↔ notes in linkedFolder. Mutates entries in-place. */ - private async syncLinkedFolder( - entries: RandomTableEntry[], - folderPath: string, - ): Promise { - // Ensure folder exists - if (!this.app.vault.getAbstractFileByPath(folderPath)) { - try { - await this.app.vault.createFolder(folderPath); - } catch { - /* may already exist */ - } - } - - // Notes currently in the folder - const existing = this.app.vault - .getMarkdownFiles() - .filter( - (f) => f.parent?.path === folderPath && !f.basename.startsWith("_"), - ); - - // For each entry: create note if missing - for (const entry of entries) { - const notePath = `${folderPath}/${entry.result}.md`; - const noteFile = this.app.vault.getAbstractFileByPath(notePath); - if (!noteFile) { - try { - await this.app.vault.create(notePath, `# ${entry.result}\n`); - } catch { - continue; - } - } - } - - // For each note without a matching entry: add entry - const entryNames = new Set(entries.map((e) => e.result)); - for (const noteFile of existing) { - if (!entryNames.has(noteFile.basename)) { - entries.push({ result: noteFile.basename, weight: 1 }); - } - } - } - - /** Rename notes whose entry result text was changed, instead of creating a new note. */ - private async renameUpdatedEntries( - entries: RandomTableEntry[], - originalResults: WeakMap, - folderPath: string, - ): Promise { - for (const entry of entries) { - const orig = originalResults.get(entry); - if (!orig || orig === entry.result) continue; - const oldPath = `${folderPath}/${orig}.md`; - const newPath = `${folderPath}/${entry.result}.md`; - const noteFile = this.app.vault.getAbstractFileByPath(oldPath); - if (!(noteFile instanceof TFile)) continue; - if (this.app.vault.getAbstractFileByPath(newPath)) continue; // target already exists - try { - await this.app.fileManager.renameFile(noteFile, newPath); - } catch { - /* best-effort */ - } - } - } - - /** Prepend "_" to notes whose entries were deleted, so they are excluded from future syncs. */ - private async retireDeletedEntries( - originalResults: Set, - currentEntries: RandomTableEntry[], - folderPath: string, - ): Promise { - const currentNames = new Set(currentEntries.map((e) => e.result)); - for (const result of originalResults) { - if (currentNames.has(result)) continue; - const notePath = `${folderPath}/${result}.md`; - const noteFile = this.app.vault.getAbstractFileByPath(notePath); - if (!(noteFile instanceof TFile)) continue; - const newPath = `${folderPath}/_${result}.md`; - try { - await this.app.fileManager.renameFile(noteFile, newPath); - } catch { - /* already renamed or missing */ - } - } + // Typing on open goes to a new row, never the table's name (fresh-eyes + // C12: stray keys renamed the table). After Obsidian's own focus on + // open, which takes the first field. + newResult.focus(); + window.setTimeout(() => { + if (newResult.isConnected && activeDocument.activeElement === nameInput) newResult.focus(); + }, 0); } onClose(): void { + if (this.modifyRef) this.app.vault.offref(this.modifyRef); + this.modifyRef = null; // If the user typed something in "Add row" and closed without clicking Add, // flush it and save so the entry isn't lost. void this.flushAndSave?.(); @@ -703,19 +773,19 @@ export class RandomTableEditorModal extends HexmakerModal { key: string, value: boolean | undefined, ): string { - const lineRegex = new RegExp(`^${escapeRegex(key)}:.*$`, "m"); + const lineRegex = new RegExp(`^${escapeRegex(key)}:[^\\r\\n]*`, "m"); const hasKey = lineRegex.test(frontmatter); if (value === undefined) { if (!hasKey) return frontmatter; // Remove the line (and any trailing newline) - return frontmatter.replace(new RegExp(`^${escapeRegex(key)}:.*\\n?`, "m"), ""); + return frontmatter.replace(new RegExp(`^${escapeRegex(key)}:.*(?:\\r?\\n)?`, "m"), ""); } const line = `${key}: ${value}`; if (hasKey) { return frontmatter.replace(lineRegex, () => line); } // Insert before closing --- - return frontmatter.replace(/\n---$/, () => `\n${line}\n---`); + return frontmatter.replace(/(\r?\n)---$/, (_m, eol: string) => `${eol}${line}${eol}---`); } /** Set, remove, or update a string key in a frontmatter block string. */ @@ -724,50 +794,25 @@ export class RandomTableEditorModal extends HexmakerModal { key: string, value: string | undefined, ): string { - const lineRegex = new RegExp(`^${escapeRegex(key)}:.*$`, "m"); + const lineRegex = new RegExp(`^${escapeRegex(key)}:[^\\r\\n]*`, "m"); const hasKey = lineRegex.test(frontmatter); if (!value) { if (!hasKey) return frontmatter; - return frontmatter.replace(new RegExp(`^${escapeRegex(key)}:.*\\n?`, "m"), ""); + return frontmatter.replace(new RegExp(`^${escapeRegex(key)}:.*(?:\\r?\\n)?`, "m"), ""); } const line = `${key}: ${value}`; if (hasKey) return frontmatter.replace(lineRegex, () => line); - return frontmatter.replace(/\n---$/, () => `\n${line}\n---`); + return frontmatter.replace(/(\r?\n)---$/, (_m, eol: string) => `${eol}${line}${eol}---`); } private extractFrontmatter(content: string): string { - const match = content.match(/^---\n[\s\S]*?\n---/); + const match = /^---[ \t]*\r?\n[\s\S]*?\r?\n---[ \t]*(?=\r?\n|$)/.exec(content); return match ? match[0] : ""; } +} - private extractPreamble(content: string, frontmatter: string): string { - const afterFm = frontmatter ? content.slice(frontmatter.length) : content; - // Find first markdown table row (line starting with |) - const tableMatch = afterFm.match(/^[ \t]*\|/m); - if (!tableMatch || tableMatch.index === undefined) return ""; - return afterFm.slice(0, tableMatch.index).trim(); - } - - private buildContent( - frontmatter: string, - preamble: string, - entries: RandomTableEntry[], - linkedFolder?: string, - suffix?: string, - ): string { - const rows = entries - .map((e) => { - const cell = linkedFolder || e.isLink ? `[[${e.result}]]` : e.result; - return `| ${escapeTableCell(cell)} | ${e.weight} |`; - }) - .join("\n"); - const tableBlock = `| Result | Weight |\n|--------|--------|\n${rows}`; - const parts: string[] = []; - if (frontmatter) parts.push(frontmatter); - if (preamble) parts.push(preamble); - parts.push(tableBlock); - let result = parts.join("\n\n") + "\n"; - if (suffix) result += "\n" + suffix; - return result; - } +/** A typed weight: a number ≥ 0 (decimals too, T10); anything else counts as 1. */ +function readWeight(value: string): number { + const n = readTableWeight(value); + return Number.isFinite(n) ? n : 1; } diff --git a/src/random-tables/RandomTableModal.ts b/src/random-tables/RandomTableModal.ts index c6166cbf..0c05afe0 100644 --- a/src/random-tables/RandomTableModal.ts +++ b/src/random-tables/RandomTableModal.ts @@ -1,10 +1,75 @@ -import { App, TFile } from "obsidian"; +import { App, Notice, TFile } from "obsidian"; +import { handRollLabel } from "../arrival/eventsLedger"; import { HexmakerModal } from "../HexmakerModal"; import type HexmakerPlugin from "../HexmakerPlugin"; import { normalizeFolder } from "../utils"; -import { parseRandomTable, rollOnTable, getDieRanges } from "./randomTable"; +import { parseRandomTable, resolveTable, rowOdds, dieLabel } from "./randomTable"; +import { renderEmptyTableState, setRollEnabled } from "./emptyTable"; +import { rollForHex } from "./hexRoll"; +import { layeredLookup, notesLookup } from "./resolve"; import { VIEW_TYPE_RANDOM_TABLES } from "../constants"; import { RandomTableEditorModal } from "./RandomTableEditorModal"; +import { groupTableFiles } from "./tablePickerGroups"; +import { MAP_MADE_GROUP_LABEL } from "./resolve"; +import { withRepairHint } from "../ui/repairHint"; +import { tableTitle } from "../encounterLinks"; + +/** + * "Add to this hex" target for a roll made from a hex (P2): which sections + * the result may go to, the one picked first (where the roll came from), and + * how to add it (the hex editor appends to its own text box; elsewhere + * plugin.appendToHexSection creates the note if needed). + */ +export interface RollHexTarget { + /** "Hex 3, 4", shown on the button's tooltip. */ + label: string; + sections: readonly { key: string; label: string }[]; + defaultSection: string; + add: (sectionKey: string, text: string) => Promise | void; + /** The hex's terrain and terrain type: a table row's When can ask for them. */ + context?: { terrain?: string; type?: string }; +} + +/** + * Section picker + "Add to this hex" button (P2), for a roll result or a + * filled-in workflow (PA2). `getText` is read on click. + */ +export function renderAddToHex( + parent: HTMLElement, + target: RollHexTarget, + getText: () => string, + opts: { cta?: boolean; onAdded?: () => void } = {}, +): void { + const select = parent.createEl("select", { + cls: "duckmage-roll-add-section", + attr: { "aria-label": "Section to add the result to" }, + }); + for (const s of target.sections) select.createEl("option", { value: s.key, text: s.label }); + select.value = target.sections.some((s) => s.key === target.defaultSection) + ? target.defaultSection + : (target.sections[0]?.key ?? ""); + const addBtn = parent.createEl("button", { + text: "Add to this hex", + cls: opts.cta ? "mod-cta" : "", + attr: { title: `Append the result to a section of ${target.label}'s note` }, + }); + addBtn.addEventListener("click", () => { + const text = getText().trim(); + if (!text || !select.value) return; + addBtn.disabled = true; + void (async () => { + try { + await target.add(select.value, text); + const label = target.sections.find((s) => s.key === select.value)?.label ?? select.value; + new Notice(`Added to ${label} (${target.label}).`); + opts.onAdded?.(); + } catch (err) { + new Notice(`Could not add the result: ${String(err)}`); + addBtn.disabled = false; + } + })(); + }); +} /** * Lightweight inline roll modal — used by the 🎲 button inside HexEditorModal @@ -12,7 +77,8 @@ import { RandomTableEditorModal } from "./RandomTableEditorModal"; * * When `initialFilePath` is supplied the dropdown is skipped and that table is * loaded immediately (used for terrain description tables via the 📖 button). - * When `onInsert` is absent the result shows a Copy button instead of "Use result". + * The result always has Copy; "Use result" when `onInsert` is given, and + * "Add to this hex" with a section picker when `hexTarget` is given. */ export class RandomTableModal extends HexmakerModal { constructor( @@ -20,6 +86,7 @@ export class RandomTableModal extends HexmakerModal { private plugin: HexmakerPlugin, private onInsert?: (result: string) => void, private initialFilePath?: string, + private hexTarget?: RollHexTarget, ) { super(app); } @@ -51,7 +118,7 @@ export class RandomTableModal extends HexmakerModal { if (files.length === 0) { contentEl.createDiv({ cls: "duckmage-rt-empty", - text: `No tables found in "${this.plugin.settings.tablesFolder}".`, + text: withRepairHint(`No tables found in "${this.plugin.settings.tablesFolder}".`), }); return; } @@ -60,8 +127,14 @@ export class RandomTableModal extends HexmakerModal { cls: "duckmage-roll-modal-select", }); select.createEl("option", { value: "", text: "— choose a table —" }); - for (const file of files) { - select.createEl("option", { value: file.path, text: file.basename }); + // The user's tables first; any the map made (when not filtered out) grouped after them. + const { own, mapMade } = groupTableFiles(this.app, files); + for (const file of own) { + select.createEl("option", { value: file.path, text: tableTitle(file.path) }); + } + if (mapMade.length) { + const group = select.createEl("optgroup", { attr: { label: MAP_MADE_GROUP_LABEL } }); + for (const file of mapMade) group.createEl("option", { value: file.path, text: tableTitle(file.path) }); } // "Open in roller" link — hidden until a table is selected @@ -114,7 +187,7 @@ export class RandomTableModal extends HexmakerModal { if (!(file instanceof TFile)) { contentEl.createDiv({ cls: "duckmage-rt-empty", - text: "Table file not found.", + text: withRepairHint("Table file not found."), }); return; } @@ -123,7 +196,7 @@ export class RandomTableModal extends HexmakerModal { const headerRow = contentEl.createDiv({ cls: "duckmage-roll-modal-header-row", }); - headerRow.createEl("strong", { text: file.basename }); + headerRow.createEl("strong", { text: tableTitle(file.path) }); const editLink = headerRow.createEl("a", { text: "Edit", cls: "duckmage-roll-modal-edit-link", @@ -189,9 +262,11 @@ export class RandomTableModal extends HexmakerModal { private buildResultBox(contentEl: HTMLElement): { el: HTMLElement; textarea: HTMLTextAreaElement; + face: HTMLElement; } { const resultBox = contentEl.createDiv({ cls: "duckmage-roll-result" }); resultBox.hide(); + const face = resultBox.createDiv({ cls: "duckmage-roll-face" }); const resultTextarea = resultBox.createEl("textarea", { cls: "duckmage-roll-result-textarea", }); @@ -200,65 +275,87 @@ export class RandomTableModal extends HexmakerModal { }); if (this.onInsert) { + // Plain: Roll is this surface's one primary. const useBtn = resultBtns.createEl("button", { text: "Use result", - cls: "mod-cta", }); useBtn.addEventListener("click", () => { this.onInsert!(resultTextarea.value); this.close(); }); - } else { - const copyBtn = resultBtns.createEl("button", { - text: "Copy", - cls: "mod-cta", - }); - copyBtn.addEventListener("click", () => { - void navigator.clipboard.writeText(resultTextarea.value); + } + + const target = this.hexTarget; + if (target) { + renderAddToHex(resultBtns, target, () => resultTextarea.value, { + cta: false, // Roll is the one primary here + onAdded: () => this.close(), }); } - return { el: resultBox, textarea: resultTextarea }; + const copyBtn = resultBtns.createEl("button", { + text: "Copy", + }); + copyBtn.addEventListener("click", () => { + void navigator.clipboard.writeText(resultTextarea.value); + copyBtn.setText("Copied"); + window.setTimeout(() => copyBtn.setText("Copy"), 1200); + }); + + return { el: resultBox, textarea: resultTextarea, face }; } private async renderOddsTable( tableContainer: HTMLElement, - resultBox: { el: HTMLElement; textarea: HTMLTextAreaElement }, + resultBox: { el: HTMLElement; textarea: HTMLTextAreaElement; face: HTMLElement }, rollBtn: HTMLButtonElement, file: TFile, ): Promise { const content = await this.app.vault.read(file); const table = parseRandomTable(content); - const ranges = table.dice > 0 ? getDieRanges(table) : null; + const resolved = resolveTable(table); + // Ranges as stored in the note (blanks filled): the ones that are rolled. + const ranges = table.dice > 0 ? resolved.labels : null; + const odds = rowOdds(table, resolved); if (table.entries.length === 0) { - tableContainer.createSpan({ - text: "No entries found.", - cls: "duckmage-rt-empty", + // SF1: Roll stays disabled; the empty state opens the table editor. + setRollEnabled(rollBtn, false); + renderEmptyTableState(tableContainer, { + app: this.app, + plugin: this.plugin, + file, + content, + onSaved: () => { + void (async () => { + tableContainer.empty(); + resultBox.el.hide(); + await this.renderOddsTable(tableContainer, resultBox, rollBtn, file); + })(); + }, }); return; } + setRollEnabled(rollBtn, true); const tableEl = tableContainer.createEl("table", { cls: "duckmage-random-table", }); const thead = tableEl.createEl("thead"); const headerRow = thead.createEl("tr"); - if (ranges) headerRow.createEl("th", { text: `d${table.dice}` }); + if (ranges) headerRow.createEl("th", { text: dieLabel(table.dice) }); headerRow.createEl("th", { text: "Result" }); headerRow.createEl("th", { text: "Odds" }); headerRow.createEl("th", { cls: "duckmage-rt-copy-col-header" }); const tbody = tableEl.createEl("tbody"); - const total = table.entries.reduce((s, e) => s + e.weight, 0); table.entries.forEach((entry, i) => { const tr = tbody.createEl("tr"); tr.dataset.index = String(i); if (ranges) tr.createEl("td", { text: ranges[i], cls: "duckmage-rt-range-cell" }); tr.createEl("td", { text: entry.result }); - const pct = `${Math.round((entry.weight / total) * 100)}%`; - tr.createEl("td", { text: pct, cls: "duckmage-rt-odds-cell" }); + tr.createEl("td", { text: odds[i], cls: "duckmage-rt-odds-cell" }); const copyTd = tr.createEl("td", { cls: "duckmage-rt-entry-copy-cell" }); const copyBtn = copyTd.createEl("button", { text: "⎘", @@ -274,17 +371,26 @@ export class RandomTableModal extends HexmakerModal { }); rollBtn.disabled = false; + // The roll goes through the shared resolver (hexRoll.ts): a row that + // links another table is rolled through, and the hex's terrain is the + // When context. This note's own text wins over the tables folder's copy. + const lookup = layeredLookup(notesLookup({ [file.path]: content }), this.plugin.tableNotes.lookup()); rollBtn.onclick = () => { - const rolled = rollOnTable(table); - if (!rolled) return; + const roll = rollForHex(file.path, lookup, this.hexTarget?.context ?? {}); + if (!roll.results.length) return; + const taken = new Set(roll.rows.map(String)); tbody.querySelectorAll("tr").forEach((tr) => { - tr.toggleClass( - "is-rolled", - tr.textContent?.includes(rolled.result) || false, - ); + tr.toggleClass("is-rolled", taken.has(tr.dataset.index ?? "")); }); resultBox.el.show(); - resultBox.textarea.value = rolled.result; + const first = roll.rows.length === 1 ? roll.rows[0] : undefined; + const face = [ + first !== undefined ? handRollLabel(table, { entry: table.entries[first], index: first, ...(roll.face !== undefined ? { face: roll.face } : {}) }) : "", + ...roll.chains, + ].filter(Boolean).join(" · "); + resultBox.face.setText(face); + resultBox.face.toggle(!!face); + resultBox.textarea.value = roll.text; }; } diff --git a/src/random-tables/RandomTableView.ts b/src/random-tables/RandomTableView.ts index 47133e48..9f3d2af5 100644 --- a/src/random-tables/RandomTableView.ts +++ b/src/random-tables/RandomTableView.ts @@ -1,3 +1,4 @@ +import { handRollLabel } from "../arrival/eventsLedger"; import { ItemView, MarkdownRenderer, @@ -16,22 +17,45 @@ import { WorkflowEditorModal } from "./WorkflowEditorModal"; import { WorkflowWizardModal } from "./WorkflowWizardModal"; import { parseRandomTable, - rollOnTable, - getDieRanges, + parseRandomTableWithReport, + rollTable, + resolveTable, + rowOdds, + rowInfoOf, + dieLabel, + dieFaces, setDiceInFrontmatter, - extractPostTableContent, + syncLinkedRows, + writeRollTable, + withRollerBlock, parseMarkdownListItems, type RandomTable, + type ResolvedTable, + type TableReport, } from "./randomTable"; -import { parseWorkflow, generateDefaultTemplate } from "./workflow"; +import { planTableMigration } from "../migrations/v1.5-table-roll-ranges"; +import { processTableNote } from "./TableStore"; +import { groupTableFiles } from "./tablePickerGroups"; +import { MAP_MADE_GROUP_LABEL } from "./resolve"; +import { parseWorkflow } from "./workflow"; +import { resolveWorkflowTemplate } from "./workflowFiles"; import { Frontmatter } from "../frontmatter"; import { buildTree, renderFolderTree, type TreeNode } from "./FolderTree"; -import { ConfirmDeleteModal } from "./ConfirmDeleteModal"; import { exportRandomTableAsPdf, exportRandomTableAsMarkdown, } from "../export/exporters/randomTable"; -import { escapeTableCell } from "../textUtils"; +import { Disclosure } from "../ui/disclosure"; +import { isDebugMode } from "../ui/debugMode"; +import { PlacedMenu } from "../ui/placedMenu"; +import { DETAIL_REFRESH_MS, LIST_REFRESH_MS, ListSignatures, listSignature, touchesList, type ListFolders } from "./listRefresh"; +import { tableTitle } from "../encounterLinks"; +import { renderEmptyTableState, setRollEnabled } from "./emptyTable"; +import { ensureFolder } from "../vault/ensureFolder"; +import { pdfAvailable } from "../platform"; + +/** Collapse key (and key prefix) of the tree's "Made by the map" section. */ +const MAP_MADE_KEY = "map-made:"; export const DIE_OPTIONS = [ { label: "— no die —", value: 0 }, @@ -41,6 +65,7 @@ export const DIE_OPTIONS = [ { label: "d10", value: 10 }, { label: "d12", value: 12 }, { label: "d20", value: 20 }, + { label: "d66", value: 66 }, { label: "d100", value: 100 }, { label: "d200", value: 200 }, { label: "d500", value: 500 }, @@ -64,6 +89,8 @@ export class RandomTableView extends ItemView { private workflowsBtn: HTMLButtonElement | null = null; private tableFooterEl: HTMLElement | null = null; private workflowFooterEl: HTMLElement | null = null; + /** Each listed note's list inputs, so metadata changes redraw only when they matter. */ + private listSigs = new ListSignatures(); constructor( leaf: WorkspaceLeaf, @@ -77,7 +104,7 @@ export class RandomTableView extends ItemView { } getDisplayText() { return this.activeFile - ? `Random tables · ${this.activeFile.basename}` + ? `Random tables · ${tableTitle(this.activeFile.path)}` : "Random tables"; } getIcon() { @@ -98,8 +125,7 @@ export class RandomTableView extends ItemView { if (file instanceof TFile) { if (this.isInWorkflowsFolder(file.path)) { this.viewMode = "workflows"; - this.tablesBtn?.removeClass("is-active"); - this.workflowsBtn?.addClass("is-active"); + this.markModeTabs("workflows"); this.loadList(); await this.loadWorkflow(file); } else { @@ -123,23 +149,18 @@ export class RandomTableView extends ItemView { text: "Tables", cls: "duckmage-rt-list-title", }); - const refreshBtn = listHeader.createEl("button", { - text: "↺", - cls: "duckmage-rt-icon-btn", - }); - refreshBtn.title = "Refresh list"; - refreshBtn.addEventListener("click", () => void this.loadList()); // ── Mode toggle tabs ───────────────────────────────────────────────── const modeTabs = leftCol.createDiv({ cls: "duckmage-rt-mode-tabs" }); this.tablesBtn = modeTabs.createEl("button", { text: "Tables", - cls: "duckmage-rt-mode-tab is-active", + cls: "duckmage-rt-mode-tab", }); this.workflowsBtn = modeTabs.createEl("button", { text: "Workflows", cls: "duckmage-rt-mode-tab", }); + this.markModeTabs(this.viewMode); this.tablesBtn.addEventListener("click", () => this.setViewMode("tables")); this.workflowsBtn.addEventListener("click", () => this.setViewMode("workflows"), @@ -170,7 +191,7 @@ export class RandomTableView extends ItemView { }); const searchInput = leftCol.createEl("input", { - type: "text", + type: "search", cls: "duckmage-rt-search", }); searchInput.placeholder = "Filter tables…"; @@ -210,6 +231,8 @@ export class RandomTableView extends ItemView { }); const listFooter = leftCol.createDiv({ cls: "duckmage-rt-list-footer" }); + // The list's Advanced dropdown (and Debug inside it), at the end of the tables footer. + const listDisclosure = new Disclosure(this.app, "RTView.list", () => this.tableFooterEl ?? listFooter); // ── Workflow footer (shown in workflows mode) ────────────────────────── this.workflowFooterEl = listFooter.createDiv(); @@ -251,9 +274,12 @@ export class RandomTableView extends ItemView { text: "+ new", cls: "duckmage-rt-new-btn", }); + // "Generate from folder or file": Advanced (or not built at all). + const fromFolderHost = listDisclosure.target("RTView.generateFromFolder", this.tableFooterEl); + const fromFolderWrap = fromFolderHost ?? createDiv(); const fromFolderDatalistId = "duckmage-rt-folders-" + Math.random().toString(36).slice(2); - const fromFolderDatalist = this.tableFooterEl.createEl("datalist"); + const fromFolderDatalist = fromFolderWrap.createEl("datalist"); fromFolderDatalist.id = fromFolderDatalistId; const seenFromFolders = new Set(); // Add configured settings folders first (excluding hexFolder) @@ -309,7 +335,7 @@ export class RandomTableView extends ItemView { fromFolderDatalist.createEl("option", { value: pathNoExt }); } } - const fromFolderInput = this.tableFooterEl.createEl("input", { + const fromFolderInput = fromFolderWrap.createEl("input", { type: "text", cls: "duckmage-rt-from-folder-input", attr: { placeholder: "Generate from folder or file (optional)…" }, @@ -325,9 +351,7 @@ export class RandomTableView extends ItemView { let srcFolder = ""; if (!(file instanceof TFile)) { try { - if (folder && !this.app.vault.getAbstractFileByPath(folder)) { - await this.app.vault.createFolder(folder); - } + if (folder) await ensureFolder(this.app.vault, folder); const fromValue = fromFolderInput.value.trim(); let srcFile: TFile | null = null; if (fromValue) { @@ -345,9 +369,12 @@ export class RandomTableView extends ItemView { if (srcFile) { const rawContent = await this.app.vault.read(srcFile); const items = parseMarkdownListItems(rawContent); - const rollerLink = this.plugin.buildRollerLink(); - const entryRows = items.map((item) => `| ${escapeTableCell(item)} | 1 |`).join("\n"); - content = `---\ndice: ${this.plugin.settings.defaultTableDice}\n---\n\n${rollerLink}\n\n| Result | Weight |\n|--------|--------|\n${entryRows || "| | 1 |"}\n`; + content = makeTableTemplate( + this.plugin.settings.defaultTableDice, + undefined, + this.plugin.buildRollerLink(), + items.map((item) => [item, 1] as const), + ); } else if (srcFolder) { const folderFiles = this.app.vault .getMarkdownFiles() @@ -356,11 +383,12 @@ export class RandomTableView extends ItemView { f.parent?.path === srcFolder && !f.basename.startsWith("_"), ) .sort((a, b) => a.basename.localeCompare(b.basename)); - const rollerLink = this.plugin.buildRollerLink(); - const entryRows = folderFiles - .map((f) => `| [[${f.basename}]] | 1 |`) - .join("\n"); - content = `---\ndice: ${this.plugin.settings.defaultTableDice}\nlinkedFolder: "[[${srcFolder}]]"\n---\n\n${rollerLink}\n\n| Result | Weight |\n|--------|--------|\n${entryRows || "| | 1 |"}\n`; + content = makeTableTemplate( + this.plugin.settings.defaultTableDice, + { linkedFolder: `"[[${srcFolder}]]"` }, + this.plugin.buildRollerLink(), + folderFiles.map((f) => [`[[${f.basename}]]`, 1] as const), + ); } else { const rollerLink = this.plugin.buildRollerLink(); content = makeTableTemplate( @@ -388,6 +416,14 @@ export class RandomTableView extends ItemView { newBtn.addEventListener("click", () => { void createTable(); }); + + // "↺ Refresh list" is Debug: the list redraws on its own (see listRefresh.ts). + const debugEl = listDisclosure.target("RTView.refreshList", listFooter); + if (debugEl) { + const refreshBtn = debugEl.createEl("button", { text: "Refresh list", cls: "duckmage-rt-icon-btn" }); + refreshBtn.addEventListener("click", () => void this.loadList()); + } + listDisclosure.toEnd(); newInput.addEventListener("keydown", (e: KeyboardEvent) => { if (e.key === "Enter") void createTable(); }); @@ -401,53 +437,50 @@ export class RandomTableView extends ItemView { this.loadList(); - // ── Proactive tree refresh on vault changes ─────────────────────────── + // ── The list redraws on its own (listRefresh.ts): notes and folders + // added, removed or moved in the tables or workflows folder, and + // changes to what it shows from their metadata. ───────────────────── + const clearIfActive = (path: string) => { + if (this.activeFile?.path !== path) return; + this.activeFile = null; + this.detailEl?.empty(); + }; this.registerEvent( this.app.vault.on("create", (file) => { - if ( - file instanceof TFile && - !file.basename.startsWith("_") && - this.isInTablesFolder(file.path) - ) - this.scheduleListRefresh(); - if ( - file instanceof TFile && - !file.basename.startsWith("_") && - this.isInWorkflowsFolder(file.path) - ) - this.scheduleListRefresh(); + if (touchesList(file.path, this.listFolders())) this.scheduleListRefresh(); }), ); this.registerEvent( this.app.vault.on("delete", (file) => { - if (file instanceof TFile && this.isInWorkflowsFolder(file.path)) { - if (this.activeFile === file) { - this.activeFile = null; - this.detailEl?.empty(); - } - this.scheduleListRefresh(); - } - if (!(file instanceof TFile) || !this.isInTablesFolder(file.path)) - return; - if (this.activeFile === file) { - this.activeFile = null; - this.detailEl?.empty(); - } + if (!touchesList(file.path, this.listFolders())) return; + clearIfActive(file.path); + this.listSigs.forget(file.path); this.scheduleListRefresh(); }), ); this.registerEvent( this.app.vault.on("rename", (file, oldPath) => { - if (!(file instanceof TFile)) return; - const wasIn = this.isInTablesFolder(oldPath); - const isIn = this.isInTablesFolder(file.path); - const wasInWf = this.isInWorkflowsFolder(oldPath); - const isInWf = this.isInWorkflowsFolder(file.path); - if (!wasIn && !isIn && !wasInWf && !isInWf) return; - if (this.activeFile?.path === oldPath) this.activeFile = file; + const f = this.listFolders(); + if (!touchesList(oldPath, f) && !touchesList(file.path, f)) return; + if (file instanceof TFile && this.activeFile?.path === oldPath) this.activeFile = file; + this.listSigs.rename(oldPath, file.path); + this.scheduleListRefresh(); + }), + ); + this.registerEvent( + this.app.metadataCache.on("changed", (file, _data, cache) => { + if (!touchesList(file.path, this.listFolders()) || file.basename.startsWith("_")) return; + const sig = listSignature(this.isInWorkflowsFolder(file.path), cache); + if (!this.listSigs.changed(file.path, sig, true)) return; this.scheduleListRefresh(); + // The open table's linked folder changed: bring its rows in line now. + if (file === this.activeFile && this.viewMode === "tables") { + void this.autoSyncLinkedFolder(file).then(() => this.scheduleDetailRefresh()); + } }), ); + // Frontmatter may not be cached yet when the view opens at startup. + this.registerEvent(this.app.metadataCache.on("resolved", () => this.scheduleListRefresh())); this.registerEvent( this.app.vault.on("modify", (file) => { if (file instanceof TFile && file === this.activeFile) @@ -455,34 +488,33 @@ export class RandomTableView extends ItemView { }), ); - // ── Auto-sync: note renamed/deleted in a linked folder → rebuild table entries ── + // ── Auto-sync: note renamed/deleted in a linked folder → update its row ── + const baseOf = (path: string) => path.slice(path.lastIndexOf("/") + 1).replace(/\.md$/i, ""); + const dirOf = (path: string) => normalizeFolder(path.slice(0, Math.max(0, path.lastIndexOf("/")))); + const syncFolderTable = async (dir: string, change?: { removed?: string; renamed?: [string, string] }) => { + const tableFilePath = this.linkedFolderMap.get(dir); + if (!tableFilePath) return; + const tableFile = this.app.vault.getAbstractFileByPath(tableFilePath); + if (tableFile instanceof TFile) await this.autoSyncLinkedFolder(tableFile, change); + }; this.registerEvent( this.app.vault.on("rename", async (file, oldPath) => { - if (!(file instanceof TFile)) return; - const oldDir = normalizeFolder( - oldPath.slice(0, oldPath.lastIndexOf("/")), - ); + if (!(file instanceof TFile) || file.extension !== "md") return; + const oldDir = dirOf(oldPath); const newDir = normalizeFolder(file.parent?.path ?? ""); - for (const dir of new Set([oldDir, newDir])) { - const tableFilePath = this.linkedFolderMap.get(dir); - if (!tableFilePath) continue; - const tableFile = this.app.vault.getAbstractFileByPath(tableFilePath); - if (tableFile instanceof TFile) - await this.autoSyncLinkedFolder(tableFile); + if (oldDir === newDir) { + // Renamed in place: the row keeps its weight (a "_" name retires it). + await syncFolderTable(newDir, { renamed: [baseOf(oldPath), file.basename] }); + return; } + await syncFolderTable(oldDir, { removed: baseOf(oldPath) }); + await syncFolderTable(newDir); }), ); this.registerEvent( this.app.vault.on("delete", async (file) => { - if (!(file instanceof TFile)) return; - const dir = normalizeFolder( - file.path.slice(0, file.path.lastIndexOf("/")), - ); - const tableFilePath = this.linkedFolderMap.get(dir); - if (!tableFilePath) return; - const tableFile = this.app.vault.getAbstractFileByPath(tableFilePath); - if (tableFile instanceof TFile) - await this.autoSyncLinkedFolder(tableFile); + if (!(file instanceof TFile) || file.extension !== "md") return; + await syncFolderTable(dirOf(file.path), { removed: file.basename }); }), ); @@ -498,27 +530,8 @@ export class RandomTableView extends ItemView { const dir = normalizeFolder(createdFile.parent?.path ?? ""); const tableFilePath = this.linkedFolderMap.get(dir); if (!tableFilePath) return; - const tableFile = this.app.vault.getAbstractFileByPath(tableFilePath); - if (!(tableFile instanceof TFile)) return; - await this.app.vault.process(tableFile, (content) => { - const table = parseRandomTable(content); - if (table.entries.some((e) => e.result === createdFile.basename)) - return content; - const suffix = extractPostTableContent(content); - const newRow = `| ${createdFile.basename} | 1 |`; - const replaced = content.replace( - /(\| Result \| Weight \|\n\|[-| ]+\|\n)([\s\S]*)$/, - (_, hdr, body: string) => { - const tableLines = body - .split("\n") - .filter((l: string) => l.trimStart().startsWith("|")) - .join("\n"); - return `${hdr}${tableLines.trimEnd() ? tableLines.trimEnd() + "\n" : ""}${newRow}\n`; - }, - ); - return suffix ? replaced.trimEnd() + "\n\n" + suffix : replaced; - }); - this.loadList(); + await syncFolderTable(dir); + this.scheduleListRefresh(); if (this.activeFile?.path === tableFilePath) await this.renderDetail(); }), ); @@ -561,9 +574,11 @@ export class RandomTableView extends ItemView { // ── Helpers ─────────────────────────────────────────────────────────────── - private isInTablesFolder(filePath: string): boolean { - const folder = normalizeFolder(this.plugin.settings.tablesFolder); - return !folder || filePath.startsWith(folder + "/"); + private listFolders(): ListFolders { + return { + tables: normalizeFolder(this.plugin.settings.tablesFolder), + workflows: normalizeFolder(this.plugin.settings.workflowsFolder), + }; } private isInWorkflowsFolder(filePath: string): boolean { @@ -571,10 +586,17 @@ export class RandomTableView extends ItemView { return !!folder && filePath.startsWith(folder + "/"); } + /** The shown mode's tab is the selected one (is-active + aria-pressed). */ + private markModeTabs(mode: "tables" | "workflows"): void { + for (const [btn, m] of [[this.tablesBtn, "tables"], [this.workflowsBtn, "workflows"]] as const) { + btn?.toggleClass("is-active", mode === m); + btn?.setAttr("aria-pressed", String(mode === m)); + } + } + private setViewMode(mode: "tables" | "workflows"): void { this.viewMode = mode; - this.tablesBtn?.toggleClass("is-active", mode === "tables"); - this.workflowsBtn?.toggleClass("is-active", mode === "workflows"); + this.markModeTabs(mode); if (this.tableFooterEl) { if (mode === "tables") this.tableFooterEl.show(); else this.tableFooterEl.hide(); @@ -602,7 +624,7 @@ export class RandomTableView extends ItemView { this.listRefreshTimer = window.setTimeout(() => { this.listRefreshTimer = null; void this.loadList(); - }, 200); + }, LIST_REFRESH_MS); } private scheduleDetailRefresh(): void { @@ -614,7 +636,7 @@ export class RandomTableView extends ItemView { } else { void this.renderDetail(); } - }, 300); + }, DETAIL_REFRESH_MS); } // ── List ───────────────────────────────────────────────────────────────── @@ -649,9 +671,10 @@ export class RandomTableView extends ItemView { // Rebuild linked folder map this.linkedFolderMap.clear(); for (const file of files) { - const fm: Frontmatter | undefined = - this.app.metadataCache.getFileCache(file)?.frontmatter; - const lf = fm?.["linkedFolder"]; + const cache = this.app.metadataCache.getFileCache(file); + this.listSigs.changed(file.path, listSignature(false, cache)); + const fm: Frontmatter | undefined = cache?.frontmatter; + const lf: unknown = fm?.["linkedFolder"] ?? fm?.["linked-folder"]; if (lf && typeof lf === "string") { const wikiLinkMatch = /^\[\[(.+?)\]\]$/.exec(lf); const lfClean = wikiLinkMatch ? wikiLinkMatch[1].trim() : lf; @@ -689,23 +712,54 @@ export class RandomTableView extends ItemView { return; } - const tree = buildTree(files, prefix, vaultFolderPaths); + // The user's own tables first; the terrain and region tables the map + // made go under one collapsed "Made by the map" section at the end. + const { own, mapMade } = groupTableFiles(this.app, files); + // A folder holding only the map's tables isn't listed among the user's. + const under = (f: TFile, folderPath: string) => f.path.startsWith(folderPath + "/"); + const ownFolders = vaultFolderPaths.filter((p) => own.some((f) => under(f, p)) || !mapMade.some((f) => under(f, p))); + const tree = buildTree(own, prefix, ownFolders); + const mapTree = buildTree(mapMade, prefix); // Collapse all folders on first load if (!this.treeInitialized) { this.treeInitialized = true; - const collectFolders = (nodes: TreeNode[]) => { + const collectFolders = (nodes: TreeNode[], keyPrefix = "") => { for (const n of nodes) if (n.type === "folder") { - this.collapsedFolders.add(n.path); - collectFolders(n.children); + this.collapsedFolders.add(keyPrefix + n.path); + collectFolders(n.children, keyPrefix); } }; collectFolders(tree); + collectFolders(mapTree, MAP_MADE_KEY); + this.collapsedFolders.add(MAP_MADE_KEY); } // When filtering, render flat (expand all) so matches aren't hidden inside collapsed folders - this.renderTreeNodes(this.listEl, tree, this.filterQuery !== ""); + const forceExpanded = this.filterQuery !== ""; + this.renderTreeNodes(this.listEl, tree, forceExpanded); + if (mapMade.length) this.renderMapMadeSection(this.listEl, mapTree, mapMade.length, forceExpanded); + } + + /** The "Made by the map" section: one collapsible folder holding the map's own tables. */ + private renderMapMadeSection(container: HTMLElement, nodes: TreeNode[], count: number, forceExpanded: boolean): void { + const section = container.createDiv({ cls: "duckmage-rt-folder duckmage-rt-map-made" }); + const header = section.createDiv({ cls: "duckmage-rt-folder-header" }); + const collapsed = !forceExpanded && this.collapsedFolders.has(MAP_MADE_KEY); + const arrow = header.createSpan({ cls: "duckmage-rt-folder-arrow", text: collapsed ? "▶" : "▼" }); + header.createSpan({ cls: "duckmage-rt-folder-name", text: `${MAP_MADE_GROUP_LABEL} (${count})` }); + header.title = "Description and encounter tables made for each terrain, and encounter tables made for each region. Delete a table's table-type line to make it your own."; + const children = section.createDiv({ cls: "duckmage-rt-folder-children" }); + if (collapsed) children.hide(); + this.renderTreeNodes(children, nodes, forceExpanded, MAP_MADE_KEY); + header.addEventListener("click", () => { + const nowCollapsed = !this.collapsedFolders.has(MAP_MADE_KEY); + if (nowCollapsed) this.collapsedFolders.add(MAP_MADE_KEY); + else this.collapsedFolders.delete(MAP_MADE_KEY); + children.toggle(!nowCollapsed); + arrow.setText(nowCollapsed ? "▶" : "▼"); + }); } private rebuildWorkflowMap(allFiles?: TFile[]): void { @@ -716,7 +770,9 @@ export class RandomTableView extends ItemView { (f) => f.path.startsWith(wfFolder + "/") && !f.basename.startsWith("_"), ); for (const wf of wfFiles) { - const links = this.app.metadataCache.getFileCache(wf)?.links ?? []; + const cache = this.app.metadataCache.getFileCache(wf); + this.listSigs.changed(wf.path, listSignature(true, cache)); + const links = cache?.links ?? []; for (const link of links) { const dest = this.app.metadataCache.getFirstLinkpathDest( link.link, @@ -817,14 +873,8 @@ export class RandomTableView extends ItemView { menuItem.setTitle("Delete workflow"); menuItem.setIcon("trash"); menuItem.onClick(() => { - new ConfirmDeleteModal(this.app, file.basename, async () => { - await this.app.fileManager.trashFile(file); - if (this.activeFile === file) { - this.activeFile = null; - this.detailEl?.empty(); - } - this.loadList(); - }).open(); + // No confirm (owner Q6): it goes to the trash. + void this.trashAndForget(file); }); }); menu.showAtMouseEvent(e); @@ -833,19 +883,24 @@ export class RandomTableView extends ItemView { }); } + /** Move a table or workflow note to the trash (no confirm: owner Q6) and say so. */ + private async trashAndForget(file: TFile): Promise { + await this.app.fileManager.trashFile(file); + if (this.activeFile === file) { + this.activeFile = null; + this.detailEl?.empty(); + } + this.loadList(); + new Notice(`Moved "${file.basename}" to the trash.`); + } + private async createWorkflow(initialTablePath?: string): Promise { const wfFolder = normalizeFolder(this.plugin.settings.workflowsFolder); if (!wfFolder) { new Notice("Configure a workflows folder in settings first."); return; } - if (!this.app.vault.getAbstractFileByPath(wfFolder)) { - try { - await this.app.vault.createFolder(wfFolder); - } catch { - /* may exist */ - } - } + await ensureFolder(this.app.vault, wfFolder); // Find unique name let baseName = "New Workflow"; @@ -901,7 +956,7 @@ export class RandomTableView extends ItemView { cls: "duckmage-rt-detail-header", }); header.createEl("h3", { - text: file.basename, + text: tableTitle(file.path), cls: "duckmage-rt-detail-title", }); @@ -911,18 +966,8 @@ export class RandomTableView extends ItemView { }); editLink.addEventListener("click", () => { void (async () => { + // The editor reads the template itself (it checks it hasn't changed before saving). const content = await this.app.vault.read(file); - const wf = parseWorkflow(content, file.basename); - let tmplContent = ""; - if (wf.templateFile) { - const tmplFile = this.app.vault.getAbstractFileByPath( - wf.templateFile, - ); - if (tmplFile instanceof TFile) { - tmplContent = await this.app.vault.read(tmplFile); - } - } - if (!tmplContent) tmplContent = generateDefaultTemplate(wf.steps); new WorkflowEditorModal( this.app, this.plugin, @@ -931,7 +976,7 @@ export class RandomTableView extends ItemView { void this.loadList(); if (this.activeFile === file) void this.renderWorkflowDetail(); }, - { content, templateContent: tmplContent }, + { content }, ).open(); })(); }); @@ -1020,10 +1065,8 @@ export class RandomTableView extends ItemView { // ── Template link + preview ───────────────────────────────────────── if (workflow.templateFile) { - const tmplFile = this.app.vault.getAbstractFileByPath( - workflow.templateFile, - ); - if (tmplFile instanceof TFile) { + const tmplFile = resolveWorkflowTemplate(this.app, workflow.templateFile, file.path); + if (tmplFile) { const tmplSection = this.detailEl.createDiv({ cls: "duckmage-wf-template-section", }); @@ -1058,9 +1101,11 @@ export class RandomTableView extends ItemView { container: HTMLElement, nodes: TreeNode[], forceExpanded: boolean, + keyPrefix = "", ): void { renderFolderTree(container, nodes, { collapsedFolders: this.collapsedFolders, + keyPrefix, activeFile: this.activeFile, forceExpanded, onFileClick: (file) => void this.loadTable(file), @@ -1140,15 +1185,16 @@ export class RandomTableView extends ItemView { private showFolderContextMenu(e: MouseEvent, folderPath: string): void { const menu = new Menu(); + // Both items are Advanced; with nothing else in the menu they're shown directly. + const layers = new PlacedMenu(menu, isDebugMode(this.app)); const rollExcluded = this.plugin.settings.rollTableExcludedFolders.includes(folderPath); - menu.addItem((item) => { - item.setTitle( - rollExcluded ? "Include in roll picker" : "Exclude from roll picker", - ); - item.setIcon("dice"); - item.onClick(async () => { + layers.add("RTView.folderMenuRollPicker", { + label: rollExcluded ? "Include in roll picker" : "Exclude from roll picker", + icon: "dice", + isSet: rollExcluded, + onClick: () => void (async () => { const arr = this.plugin.settings.rollTableExcludedFolders; if (rollExcluded) { this.plugin.settings.rollTableExcludedFolders = arr.filter( @@ -1162,19 +1208,16 @@ export class RandomTableView extends ItemView { `Roll picker: "${folderPath}" ${rollExcluded ? "included" : "excluded"}.`, ); this.loadList(); - }); + })(), }); const encExcluded = this.plugin.settings.encounterTableExcludedFolders.includes(folderPath); - menu.addItem((item) => { - item.setTitle( - encExcluded - ? "Include in encounters table" - : "Exclude from encounters table", - ); - item.setIcon("sword"); - item.onClick(async () => { + layers.add("RTView.folderMenuEncounters", { + label: encExcluded ? "Include in encounters table" : "Exclude from encounters table", + icon: "sword", + isSet: encExcluded, + onClick: () => void (async () => { const arr = this.plugin.settings.encounterTableExcludedFolders; if (encExcluded) { this.plugin.settings.encounterTableExcludedFolders = arr.filter( @@ -1188,9 +1231,10 @@ export class RandomTableView extends ItemView { `Encounters table: "${folderPath}" ${encExcluded ? "included" : "excluded"}.`, ); this.loadList(); - }); + })(), }); + layers.finish(() => ({ x: e.clientX, y: e.clientY })); menu.showAtMouseEvent(e); } @@ -1201,8 +1245,9 @@ export class RandomTableView extends ItemView { const encExcluded = fm?.["encounter-filter"] === false; const isDefaultTable = fm?.["table-type"] != null; const menu = new Menu(); + const layers = new PlacedMenu(menu, isDebugMode(this.app)); - menu.addItem((item) => { + layers.addItem((item) => { item.setTitle("Open in new tab"); item.setIcon("external-link"); item.onClick(() => { @@ -1215,14 +1260,11 @@ export class RandomTableView extends ItemView { void this.app.workspace.revealLeaf(leaf); }); }); - menu.addSeparator(); - - menu.addItem((item) => { - item.setTitle( - rollExcluded ? "Include in roll picker" : "Exclude from roll picker", - ); - item.setIcon("dice"); - item.onClick(async () => { + layers.add("RTView.fileMenuRollPicker", { + label: rollExcluded ? "Include in roll picker" : "Exclude from roll picker", + icon: "dice", + isSet: rollExcluded, + onClick: () => void (async () => { await this.app.fileManager.processFrontMatter( file, (fmData: Frontmatter) => { @@ -1234,17 +1276,14 @@ export class RandomTableView extends ItemView { `Roll picker: "${file.basename}" ${rollExcluded ? "included" : "excluded"}.`, ); this.loadList(); - }); + })(), }); - menu.addItem((item) => { - item.setTitle( - encExcluded - ? "Include in encounters table" - : "Exclude from encounters table", - ); - item.setIcon("sword"); - item.onClick(async () => { + layers.add("RTView.fileMenuEncounters", { + label: encExcluded ? "Include in encounters table" : "Exclude from encounters table", + icon: "sword", + isSet: encExcluded, + onClick: () => void (async () => { await this.app.fileManager.processFrontMatter( file, (fmData: Frontmatter) => { @@ -1256,28 +1295,24 @@ export class RandomTableView extends ItemView { `Encounters table: "${file.basename}" ${encExcluded ? "included" : "excluded"}.`, ); this.loadList(); - }); + })(), }); if (!isDefaultTable) { - menu.addSeparator(); + layers.addSeparator(); - menu.addItem((item) => { + layers.addItem((item) => { item.setTitle("Delete table"); item.setIcon("trash"); item.onClick(() => { - new ConfirmDeleteModal(this.app, file.basename, async () => { - await this.app.fileManager.trashFile(file); - if (this.activeFile === file) { - this.activeFile = null; - this.detailEl?.empty(); - } - this.loadList(); - }).open(); + // No confirm (owner Q6): it goes to the trash. + void this.trashAndForget(file); }); }); } + // Roll picker / encounters filters: the Advanced ▸ submenu. + layers.finish(() => ({ x: e.clientX, y: e.clientY })); menu.showAtMouseEvent(e); } @@ -1322,49 +1357,120 @@ export class RandomTableView extends ItemView { } /** - * If tableFile has a linkedFolder, rebuild its entries from the folder: - * keep existing entries (preserving weights), add new notes, remove stale ones. - * No-op when there's no linked folder or nothing has changed. + * If tableFile has a linkedFolder, bring its rows in line with the folder: + * add rows for new notes; rename or remove the row of a note that was + * renamed or deleted (`change`). Rows whose note is missing for other + * reasons are kept and reported in the detail view. Only the table's own + * lines are rewritten, and nothing is written when nothing changed. */ - private async autoSyncLinkedFolder(tableFile: TFile): Promise { - await this.app.vault.process(tableFile, (content) => { - const table = parseRandomTable(content); - if (!table.linkedFolder) return content; - - const lf = normalizeFolder(table.linkedFolder); - const folderFiles = this.app.vault - .getMarkdownFiles() - .filter((f) => f.parent?.path === lf && !f.basename.startsWith("_")) - .sort((a, b) => a.basename.localeCompare(b.basename)); - - const folderBasenames = new Set(folderFiles.map((f) => f.basename)); - const currentNames = new Set(table.entries.map((e) => e.result)); - - const hasNew = folderFiles.some((f) => !currentNames.has(f.basename)); - const hasStale = table.entries.some( - (e) => !folderBasenames.has(e.result), - ); - if (!hasNew && !hasStale) return content; - - const kept = table.entries.filter((e) => folderBasenames.has(e.result)); - const added = folderFiles - .filter((f) => !currentNames.has(f.basename)) - .map((f) => ({ result: f.basename, weight: 1 })); - const newEntries = [...kept, ...added]; - - const suffix = extractPostTableContent(content); - const rows = newEntries - .map((e) => `| ${escapeTableCell(e.result)} | ${e.weight} |`) - .join("\n"); - const replaced = content.replace( - /(\| Result \| Weight \|\n\|[-| ]+\|\n)([\s\S]*)$/, - (_m: string, head: string) => `${head}${rows}\n`, - ); - const updated = suffix ? replaced.trimEnd() + "\n\n" + suffix : replaced; - return updated !== content ? updated : content; + private async autoSyncLinkedFolder( + tableFile: TFile, + change?: { removed?: string; renamed?: [string, string] }, + ): Promise { + const content = await this.app.vault.read(tableFile); + const table = parseRandomTable(content); + if (!table.linkedFolder) return; + const lf = normalizeFolder(table.linkedFolder); + const names = this.app.vault + .getMarkdownFiles() + .filter((f) => f.parent?.path === lf && !f.basename.startsWith("_")) + .map((f) => f.basename); + if (syncLinkedRows(content, names, change) === content) return; + await processTableNote(this.app, tableFile, (cur) => syncLinkedRows(cur, names, change)); + } + + /** + * Change the table's die: the frontmatter and the roll column (redone from + * the weights, header renamed). With no die the column is kept as typed. + */ + private async changeDie(file: TFile, newDice: number): Promise { + await processTableNote(this.app, file, (content) => { + const { table, block } = parseRandomTableWithReport(content); + const next = setDiceInFrontmatter(content, newDice); + if (!block?.recognized) return next; + return writeRollTable(next, { + dice: newDice, + rows: table.entries.map((entry, source) => ({ entry, source })), + ranges: newDice > 0 ? "regenerate" : "keep", + }); }); } + /** + * What couldn't be read, with one-click fixes. Ranges typed by hand are + * never changed without a click here. + */ + private renderIssues(file: TFile, report: TableReport, resolved: ResolvedTable): void { + if (!this.detailEl) return; + const { table, block } = report; + const issues = report.issues.filter((i) => i.code !== "no-table"); + const noRanges = table.dice > 0 && !!block?.recognized && block.cols.range < 0 && table.entries.length > 0; + if (!issues.length && !noRanges) return; + const banner = this.detailEl.createDiv({ cls: "duckmage-rt-banner" }); + if (issues.length) { + const list = banner.createEl("ul", { cls: "duckmage-rt-banner-list" }); + for (const i of issues.slice(0, 6)) list.createEl("li", { text: i.message }); + if (issues.length > 6) list.createEl("li", { text: `…and ${issues.length - 6} more. "Check tables" lists them all.` }); + } + if (noRanges) { + banner.createDiv({ + text: "This note has no roll column yet, so it can't be rolled by hand from the note. The ranges shown here are worked out from the weights.", + }); + } + const btns = banner.createDiv({ cls: "duckmage-rt-banner-btns" }); + const fix = (text: string, title: string, edit: (content: string) => string) => { + const b = btns.createEl("button", { text }); + b.title = title; + b.addEventListener("click", () => { + void processTableNote(this.app, file, edit).then(() => this.renderDetail()); + }); + }; + const codes = new Set(issues.map((i) => i.code)); + const rewrite = (content: string, ranges: "keep" | "regenerate", weights?: (i: number) => number) => { + const t = parseRandomTable(content); + return writeRollTable(content, { + dice: t.dice, + rows: t.entries.map((entry, source) => ({ entry: weights ? { ...entry, weight: weights(source) } : entry, source })), + ranges, + }); + }; + if (resolved.mode === "ranges" && (codes.has("range-weight-mismatch") || codes.has("range-gap"))) { + fix("Keep ranges → set weights", "Set each weight to the number of faces its range covers", (c) => + rewrite(c, "keep", (i) => resolveTable(parseRandomTable(c)).faces[i]?.length ?? 0), + ); + fix("Keep weights → redo ranges", "Work every range out again from the weights", (c) => rewrite(c, "regenerate")); + } + if (codes.has("too-many-rows")) { + const live = table.entries.filter((e) => e.weight > 0).length; + const bigger = DIE_OPTIONS.find((o) => o.value !== 66 && dieFaces(o.value).length >= live && o.value > table.dice); + if (bigger) { + const b = btns.createEl("button", { text: `Use a ${bigger.label}` }); + b.title = `${live} rows need at least ${live} faces`; + b.addEventListener("click", () => { + void this.changeDie(file, bigger.value).then(() => this.renderDetail()); + }); + } + } + if (noRanges && !issues.some((i) => i.code !== "legacy-roller-link")) { + fix("Add roll ranges", "Add a roll column worked out from the weights; weights and text stay as they are", (c) => { + const plan = planTableMigration(c); + return plan.action === "change" ? plan.content : c; + }); + } else if (codes.has("legacy-roller-link")) { + fix("Replace old roller link", "Swap the old obsidian:// link for the roller block", (c) => withRollerBlock(c)); + } + if (!btns.childElementCount) btns.remove(); + } + + /** Linked-folder rows whose note doesn't exist (kept, and shown in the view). */ + private missingLinkedRows(table: RandomTable): string[] { + if (!table.linkedFolder) return []; + const lf = normalizeFolder(table.linkedFolder); + return table.entries + .filter((e) => !(this.app.vault.getAbstractFileByPath(`${lf}/${e.result}.md`) instanceof TFile)) + .map((e) => e.result); + } + private renderDetailSeq = 0; private async renderDetail(): Promise { if (!this.detailEl || !this.activeFile) return; @@ -1375,8 +1481,15 @@ export class RandomTableView extends ItemView { if (seq !== this.renderDetailSeq) return; // superseded by a newer call this.detailEl.empty(); - const table = parseRandomTable(content); - const ranges = table.dice > 0 ? getDieRanges(table) : null; + // The detail's Advanced dropdown (and Debug inside it), at its end. + const detailEl = this.detailEl; + const detailDisclosure = new Disclosure(this.app, "RTView.detail", () => detailEl); + const report = parseRandomTableWithReport(content); + const table = report.table; + const resolved = resolveTable(table); + // The ranges shown are the ones rolled (stored as typed, blanks filled). + const ranges = table.dice > 0 ? resolved.labels : null; + const odds = rowOdds(table, resolved); // ── Header ───────────────────────────────────────────────────────── const header = this.detailEl.createDiv({ @@ -1419,9 +1532,8 @@ export class RandomTableView extends ItemView { }); exportPdfLink.title = "Export this table as a printable PDF"; - exportPdfLink.addEventListener("click", () => { - void exportRandomTableAsPdf(this.plugin, file); - }); + exportPdfLink.addEventListener("click", () => { void exportRandomTableAsPdf(this.plugin, file); }); + exportPdfLink.toggle(pdfAvailable()); const exportMdLink = header.createEl("a", { text: "Export Markdown", @@ -1432,10 +1544,13 @@ export class RandomTableView extends ItemView { void exportRandomTableAsMarkdown(this.plugin, file); }); - if (table.linkedFolder) { - const refreshBtn = header.createEl("a", { + // A linked folder's rows sync on their own (on open, and when notes in + // the folder are added, renamed or deleted), so "Refresh" is Debug. + const refreshHost = table.linkedFolder ? detailDisclosure.target("RTView.refreshLinked", header) : null; + if (refreshHost) { + const refreshBtn = refreshHost.createEl(refreshHost === header ? "a" : "button", { text: "Refresh", - cls: "duckmage-rt-edit-link", + cls: refreshHost === header ? "duckmage-rt-edit-link" : "", }); refreshBtn.title = `Sync entries from ${table.linkedFolder}`; refreshBtn.addEventListener("click", () => { @@ -1457,15 +1572,20 @@ export class RandomTableView extends ItemView { if (opt.value === table.dice) o.selected = true; } dieSelect.addEventListener("change", () => { - void (async () => { - const newDice = parseInt(dieSelect.value, 10); - await this.app.vault.process(file, (content) => - setDiceInFrontmatter(content, newDice), - ); - await this.renderDetail(); - })(); + void this.changeDie(file, parseInt(dieSelect.value, 10)).then(() => this.renderDetail()); }); + // Linked-folder rows whose note is gone are kept; say so. + const missing = this.missingLinkedRows(table); + if (missing.length) { + const them = missing.length === 1 ? "it" : "them"; + this.detailEl.createDiv({ + cls: "duckmage-rt-banner", + text: `${missing.length === 1 ? "1 row has" : `${missing.length} rows have`} no note in ${table.linkedFolder}: ${missing.slice(0, 6).join(", ")}${missing.length > 6 ? ", …" : ""}. Delete ${them} in the editor if the note is gone for good.`, + }); + } + this.renderIssues(file, report, resolved); + // ── Description ──────────────────────────────────────────────────── if (table.description) { const descSection = this.detailEl.createDiv({ @@ -1525,19 +1645,19 @@ export class RandomTableView extends ItemView { }); if (table.entries.length === 0) { - tableBody.createDiv({ - cls: "duckmage-rt-empty", - text: "No entries found. Check the table format.", - }); + renderEmptyTableState(tableBody, { app: this.app, plugin: this.plugin, file, content, onSaved: () => void this.renderDetail() }); } else { const tableEl = tableBody.createEl("table", { cls: "duckmage-random-table", }); const thead = tableEl.createEl("thead"); const headerRow = thead.createEl("tr"); - if (ranges) headerRow.createEl("th", { text: `d${table.dice}` }); + if (ranges) headerRow.createEl("th", { text: dieLabel(table.dice) }); headerRow.createEl("th", { text: "Result" }); headerRow.createEl("th", { text: "Odds" }); + // Row attributes and shared columns (Roll, Shown as, Once, When), read-only. + const attrCols = [...new Set((table.rowInfo ?? []).flatMap((r) => Object.keys(r.attrs ?? {})))]; + for (const c of attrCols) headerRow.createEl("th", { text: c, cls: "duckmage-rt-attr-col" }); headerRow.createEl("th", { cls: "duckmage-rt-copy-col-header" }); const tbody = tableEl.createEl("tbody"); @@ -1580,8 +1700,9 @@ export class RandomTableView extends ItemView { resultTd.setText(entry.result); } - const pct = `${Math.round((entry.weight / table.entries.reduce((s, e) => s + e.weight, 0)) * 100)}%`; - tr.createEl("td", { text: pct, cls: "duckmage-rt-odds-cell" }); + tr.createEl("td", { text: odds[i], cls: "duckmage-rt-odds-cell" }); + const attrs = rowInfoOf(table, i).attrs ?? {}; + for (const c of attrCols) tr.createEl("td", { text: attrs[c] ?? "", cls: "duckmage-rt-attr-cell" }); const copyTd = tr.createEl("td", { cls: "duckmage-rt-entry-copy-cell", }); @@ -1602,7 +1723,9 @@ export class RandomTableView extends ItemView { // ── Roll controls ────────────────────────────────────────────────── const rollArea = this.detailEl.createDiv({ cls: "duckmage-rt-roll-area" }); - const copyLinkBtn = rollArea.createEl("button", { + // Roll first (the simple job); "Copy link" is Advanced. + const copyLinkHost = detailDisclosure.target("RTView.copyRollLink", rollArea); + const copyLinkBtn = (copyLinkHost ?? createDiv()).createEl("button", { text: "🎲 Copy link", cls: "duckmage-rt-copy-link-btn", }); @@ -1621,9 +1744,14 @@ export class RandomTableView extends ItemView { text: "Roll", cls: "duckmage-rt-roll-btn mod-cta", }); + setRollEnabled(rollBtn, table.entries.length > 0); const resultBox = this.detailEl.createDiv({ cls: "duckmage-roll-result" }); resultBox.hide(); + // The simple job first: Roll and its result sit above the entries. + tableSection.before(rollArea, resultBox); + // "d20 → 14": the face rolled, so the roll can be checked against the note. + const faceEl = resultBox.createDiv({ cls: "duckmage-roll-face" }); const resultTextarea = resultBox.createEl("textarea", { cls: "duckmage-roll-result-textarea", }); @@ -1650,7 +1778,7 @@ export class RandomTableView extends ItemView { this.renderHistory(historyEl); rollBtn.addEventListener("click", () => { - this.doRoll(table, resultBox, resultTextarea, historyEl, openNoteBtn); + this.doRoll(table, resultBox, resultTextarea, historyEl, openNoteBtn, faceEl); }); // ── Used by workflows ─────────────────────────────────────────────── @@ -1695,6 +1823,7 @@ export class RandomTableView extends ItemView { })(); }); } + detailDisclosure.toEnd(); } private doRoll( @@ -1703,9 +1832,11 @@ export class RandomTableView extends ItemView { resultTextarea: HTMLTextAreaElement, historyEl: HTMLElement, openNoteBtn?: HTMLButtonElement, + faceEl?: HTMLElement, ): void { - const entry = rollOnTable(table); - if (!entry) return; + const outcome = rollTable(table); + if (!outcome) return; + const entry = outcome.entry; // Display label: basename for link entries, full result for plain entries const displayLabel = entry.isLink @@ -1713,15 +1844,17 @@ export class RandomTableView extends ItemView { : entry.result; this.detailEl - ?.querySelectorAll(".duckmage-random-table tbody tr") + ?.querySelectorAll(".duckmage-random-table tbody tr") .forEach((tr) => { - tr.toggleClass( - "is-rolled", - tr.textContent?.includes(displayLabel) ?? false, - ); + tr.toggleClass("is-rolled", tr.dataset.index === String(outcome.index)); }); resultBox.show(); + if (faceEl) { + const face = handRollLabel(table, outcome); + faceEl.setText(face); + faceEl.toggle(!!face); + } resultTextarea.value = displayLabel; resultTextarea.focus(); diff --git a/src/random-tables/RollerBlock.ts b/src/random-tables/RollerBlock.ts index bfd6919a..b5629ffc 100644 --- a/src/random-tables/RollerBlock.ts +++ b/src/random-tables/RollerBlock.ts @@ -1,7 +1,9 @@ import { TFile } from "obsidian"; +import { handRollLabel } from "../arrival/eventsLedger"; import type HexmakerPlugin from "../HexmakerPlugin"; -import { parseRandomTable, rollOnTable } from "./randomTable"; -import { DIE_OPTIONS } from "./RandomTableView"; +import { dieLabel, parseRandomTable, rollTable } from "./randomTable"; +import { renderEmptyTableState, setRollEnabled, tableIsEmpty } from "./emptyTable"; +import { withRepairHint } from "../ui/repairHint"; /** * Registers the `duckmage-roller` fenced code block processor. @@ -23,39 +25,27 @@ export function registerRollerBlock(plugin: HexmakerPlugin): void { if (!(file instanceof TFile)) { el.createDiv({ cls: "duckmage-rt-empty", - text: `Table not found: "${targetPath}"`, + text: withRepairHint(`Table not found: "${targetPath}"`), }); return; } - // Read initial table to seed the die selector + // The die is the table's own (its frontmatter / roll column header). const initialContent = await plugin.app.vault.read(file); const initialTable = parseRandomTable(initialContent); - // Local die state — cosmetic, not saved to file - let currentDice = initialTable.dice; - // ── Widget container ───────────────────────────────────────────── const block = el.createDiv({ cls: "duckmage-roller-block" }); - // Header: title + die selector + // Header: title + the table's die const header = block.createDiv({ cls: "duckmage-roller-header" }); header.createSpan({ cls: "duckmage-roller-title", text: `🎲 ${file.basename}`, }); - const dieSelect = header.createEl("select", { + const dieEl = header.createSpan({ cls: "duckmage-roller-die", - }); - for (const opt of DIE_OPTIONS) { - const o = dieSelect.createEl("option", { - value: String(opt.value), - text: opt.label, - }); - if (opt.value === currentDice) o.selected = true; - } - dieSelect.addEventListener("change", () => { - currentDice = parseInt(dieSelect.value, 10); + text: dieLabel(initialTable.dice), }); // Roll button @@ -64,6 +54,27 @@ export function registerRollerBlock(plugin: HexmakerPlugin): void { cls: "duckmage-roller-btn mod-cta", }); + // An empty table (tables ship empty, SF1): Roll is disabled and the + // shared empty state opens the table editor. Checked again after an + // edit there and before each roll. + const emptyWrap = block.createDiv(); + const showEmpty = (content: string): boolean => { + emptyWrap.empty(); + const empty = tableIsEmpty(content); + setRollEnabled(rollBtn, !empty); + if (empty) { + renderEmptyTableState(emptyWrap, { + app: plugin.app, + plugin, + file, + content, + onSaved: () => void plugin.app.vault.read(file).then(showEmpty), + }); + } + return empty; + }; + showEmpty(initialContent); + // Result area — hidden until first roll (reuses modal CSS classes) const resultBox = block.createDiv({ cls: "duckmage-roll-result" }); resultBox.hide(); @@ -71,10 +82,11 @@ export function registerRollerBlock(plugin: HexmakerPlugin): void { cls: "duckmage-roll-result-textarea", }); resultTextarea.readOnly = true; + const faceEl = resultBox.createDiv({ cls: "duckmage-roll-face" }); + resultTextarea.before(faceEl); const resultBtns = resultBox.createDiv({ cls: "duckmage-roll-result-btns" }); const copyBtn = resultBtns.createEl("button", { text: "Copy", - cls: "mod-cta", }); copyBtn.addEventListener("click", () => { void navigator.clipboard.writeText(resultTextarea.value); @@ -109,8 +121,13 @@ export function registerRollerBlock(plugin: HexmakerPlugin): void { void (async () => { const content = await plugin.app.vault.read(file); const table = parseRandomTable(content); - const rolled = rollOnTable(table); - if (!rolled) return; + dieEl.setText(dieLabel(table.dice)); + const outcome = rollTable(table); + const rolled = outcome?.entry; + if (showEmpty(content) || !outcome || !rolled) { + resultBox.hide(); + return; + } // For linked-folder / isLink entries strip the path prefix let display = rolled.result; @@ -119,6 +136,10 @@ export function registerRollerBlock(plugin: HexmakerPlugin): void { } resultTextarea.value = display; + // "d20 → 14": the face rolled, so it can be checked against the note. + const face = handRollLabel(table, outcome); + faceEl.setText(face); + faceEl.toggle(!!face); resultBox.show(); history.unshift(display); diff --git a/src/random-tables/TableChoice.ts b/src/random-tables/TableChoice.ts new file mode 100644 index 00000000..450fb66d --- /dev/null +++ b/src/random-tables/TableChoice.ts @@ -0,0 +1,144 @@ +import { TFile, type App } from "obsidian"; +import type HexmakerPlugin from "../HexmakerPlugin"; +import { choiceSourceLabel, type TableChoiceItem } from "../tableChoice"; +import { tableTitle } from "../encounterLinks"; +import { withRepairHint } from "../ui/repairHint"; +import { renderEmptyTableState, setRollEnabled, tableIsEmpty } from "./emptyTable"; + +/** Unique radio-group names. */ +let choiceSeq = 0; + +export interface TableChoiceOptions { + app: App; + plugin: HexmakerPlugin; + /** What the tables are for, in UI text ("encounter", "weather"). */ + noun: string; + items: TableChoiceItem[]; + /** Index of the item to start on (tableChoice.ts initialChoice). */ + start: number; + /** The user switched tables (remember it; nothing is written). */ + onChoose: (item: TableChoiceItem) => void; + onRoll: (item: TableChoiceItem) => void; + /** Open the table (its name was clicked). */ + onOpen: (item: TableChoiceItem) => void; + /** "change…": pick any other table. */ + onChange: () => void; + /** Remove a table linked in the hex note (items with `link`). */ + onRemove?: (item: TableChoiceItem) => void; +} + +/** + * One section's tables (owner SF2): the tables that apply to this hex, + * most specific first, as radio buttons when there are several; the chosen + * table's name; Roll; and "change…" to pick any other table. Roll is + * disabled on an empty table, with the shared empty state (SF1). + */ +export class TableChoice { + readonly el: HTMLElement; + private chosen: number; + private readonly name = `duckmage-table-choice-${++choiceSeq}`; + /** Bumped on every redraw so a late file read can't draw into a newer one. */ + private drawn = 0; + + constructor(parent: HTMLElement, private o: TableChoiceOptions) { + this.el = parent.createDiv({ cls: "duckmage-table-choice" }); + this.chosen = o.start; + this.render(); + } + + /** The chosen item, if any. */ + get current(): TableChoiceItem | undefined { + return this.o.items[this.chosen]; + } + + /** Show a new list (after a link was added or removed), starting on `start`. */ + setItems(items: TableChoiceItem[], start: number): void { + this.o.items = items; + this.chosen = start; + this.render(); + } + + private render(): void { + const { el, o } = this; + const run = ++this.drawn; + el.empty(); + const items = o.items; + + if (items.length === 0) { + el.createDiv({ cls: "duckmage-table-choice-none", text: `No ${o.noun} table yet.` }); + } else if (items.length === 1) { + this.renderItem(el.createDiv({ cls: "duckmage-table-choice-one" }), items[0]); + } else { + const list = el.createDiv({ cls: "duckmage-table-choice-options", attr: { role: "radiogroup", "aria-label": `${o.noun} tables` } }); + items.forEach((item, i) => { + const row = list.createEl("label", { cls: "duckmage-table-choice-option" }); + const radio = row.createEl("input", { type: "radio", attr: { name: this.name, value: String(i) } }); + radio.checked = i === this.chosen; + radio.addEventListener("change", () => { + if (!radio.checked) return; + this.chosen = i; + o.onChoose(item); + this.render(); + }); + this.renderItem(row, item); + }); + } + + const actions = el.createDiv({ cls: "duckmage-table-choice-actions" }); + const roll = actions.createEl("button", { text: "🎲 Roll", cls: "duckmage-table-choice-roll" }); + const change = actions.createEl("a", { text: "Change…", href: "#", cls: "duckmage-table-choice-change" }); + change.title = `Pick another ${o.noun} table for this hex`; + change.addEventListener("click", (e) => { + e.preventDefault(); + o.onChange(); + }); + + const current = this.current; + const file = current && !current.missing ? o.app.vault.getAbstractFileByPath(current.path) : null; + if (!current || !(file instanceof TFile)) { + roll.disabled = true; + roll.title = current ? withRepairHint(`${current.path}: no such note.`) : `Pick a ${o.noun} table first`; + return; + } + roll.title = `Roll on ${tableTitle(current.path)}`; + roll.addEventListener("click", () => o.onRoll(current)); + // Empty tables (SF1): Roll off, and a way to add entries right here. + roll.disabled = true; + const emptyWrap = el.createDiv(); + void o.app.vault.cachedRead(file).then((content) => { + if (run !== this.drawn) return; + const empty = tableIsEmpty(content); + setRollEnabled(roll, !empty); + if (!empty) { + roll.title = `Roll on ${tableTitle(current.path)}`; + return; + } + renderEmptyTableState(emptyWrap, { app: o.app, plugin: o.plugin, file, content, compact: true, onSaved: () => this.render() }); + }); + } + + /** A table's name (opens it), where it comes from, and × for a link in the hex note. */ + private renderItem(row: HTMLElement, item: TableChoiceItem): void { + const { o } = this; + const nameEl = row.createSpan({ cls: "duckmage-table-choice-name", text: tableTitle(item.path) }); + if (item.missing) { + nameEl.addClass("is-missing"); + nameEl.title = withRepairHint(`[[${item.link ?? item.path}]]: no such note.`); + } else { + nameEl.addClass("duckmage-link-item-clickable"); + nameEl.title = `Open ${item.path}`; + nameEl.addEventListener("click", (e) => { + e.preventDefault(); + o.onOpen(item); + }); + } + row.createSpan({ cls: "duckmage-table-choice-source", text: choiceSourceLabel(item.source) }); + if (item.link && o.onRemove) { + const remove = row.createEl("button", { text: "×", cls: "duckmage-link-remove-btn", attr: { "aria-label": `Remove ${tableTitle(item.path)} from this hex` } }); + remove.addEventListener("click", (e) => { + e.preventDefault(); + o.onRemove?.(item); + }); + } + } +} diff --git a/src/random-tables/TableNotes.ts b/src/random-tables/TableNotes.ts new file mode 100644 index 00000000..79da1893 --- /dev/null +++ b/src/random-tables/TableNotes.ts @@ -0,0 +1,99 @@ +/** + * The text of every note under the tables folder, kept in memory so the + * table resolver (resolve.ts, which is synchronous) can roll on vault + * tables: generators and their previews, and arrival rolls. Read once at + * start, then kept up to date from vault events. Never writes. + */ + +import { TFile, type TAbstractFile } from "obsidian"; +import type HexmakerPlugin from "../HexmakerPlugin"; +import { contentFolder } from "../notePickers"; +import { notesLookup, type TableLookup } from "./resolve"; +import { parseRandomTable, type RandomTable } from "./randomTable"; + +export class TableNotes { + private contents = new Map(); + private cached: TableLookup | null = null; + private ready = false; + + constructor(private plugin: HexmakerPlugin) {} + + static register(plugin: HexmakerPlugin): TableNotes { + const notes = new TableNotes(plugin); + const { vault } = plugin.app; + plugin.registerEvent(vault.on("modify", (f) => void notes.read(f))); + plugin.registerEvent(vault.on("create", (f) => void notes.read(f))); + plugin.registerEvent(vault.on("delete", (f) => notes.drop(f.path))); + plugin.registerEvent(vault.on("rename", (f, old) => { notes.drop(old); void notes.read(f); })); + return notes; + } + + private folder(): string { + return contentFolder(this.plugin.settings, "tablesFolder"); + } + + private inScope(path: string): boolean { + const folder = this.folder(); + return path.endsWith(".md") && (!folder || path.startsWith(`${folder}/`)); + } + + /** Read every note under the tables folder (again: the folder setting changed). */ + async init(): Promise { + this.contents.clear(); + for (const f of this.plugin.app.vault.getMarkdownFiles()) { + if (this.inScope(f.path)) this.contents.set(f.path, await this.plugin.app.vault.cachedRead(f)); + } + this.cached = null; + this.ready = true; + } + + isReady(): boolean { + return this.ready; + } + + private async read(f: TAbstractFile): Promise { + if (!(f instanceof TFile) || !this.inScope(f.path)) return; + this.put(f.path, await this.plugin.app.vault.cachedRead(f)); + } + + /** Take a note's text now (the plugin just wrote it). */ + put(path: string, content: string): void { + if (this.contents.get(path) === content) return; + this.contents.set(path, content); + this.cached = null; + } + + private drop(path: string): void { + if (this.contents.delete(path)) this.cached = null; + } + + /** The tables as a lookup for the resolver (links by path or note name). */ + lookup(): TableLookup { + if (!this.cached) this.cached = notesLookup(Object.fromEntries(this.contents)); + return this.cached; + } + + /** Every note that reads as a table, with its table (for pickers). */ + tables(): { path: string; table: RandomTable }[] { + const out: { path: string; table: RandomTable }[] = []; + const lookup = this.lookup(); + for (const path of [...this.contents.keys()].sort()) { + const name = path.slice(path.lastIndexOf("/") + 1); + if (name.startsWith("_")) continue; + const t = lookup.table(path); + if (t) out.push({ path, table: t.table }); + } + return out; + } + + /** A note's text, if it's under the tables folder. */ + text(path: string): string | undefined { + return this.contents.get(path); + } + + /** Parse a note's table (undefined when it isn't one we hold). */ + table(path: string): RandomTable | undefined { + const c = this.contents.get(path); + return c === undefined ? undefined : parseRandomTable(c); + } +} diff --git a/src/random-tables/TableStore.ts b/src/random-tables/TableStore.ts new file mode 100644 index 00000000..212f8f8d --- /dev/null +++ b/src/random-tables/TableStore.ts @@ -0,0 +1,137 @@ +/** + * Watches table notes so hand edits to the raw note are imported (issue #45, + * see tableImport.ts). Like PaletteStore, it keeps the content it last read + * or wrote per note: a change that isn't the plugin's own write is a hand + * edit, and is compared against that. + * + * Plugin code that rewrites a table goes through processTableNote, which + * records the result first, so the plugin's own writes are never imported + * back. Imports wait until typing has paused, and never rewrite the note + * under a focused editor. + */ + +import { MarkdownView, TFile, type App, type TAbstractFile } from "obsidian"; +import type HexmakerPlugin from "../HexmakerPlugin"; +import { normalizeFolder } from "../utils"; +import { importHandEdit, type ImportKind } from "./tableImport"; +import { isTableNotePath } from "./tableNotePaths"; + +/** Content the plugin last read or wrote, per table note path. */ +const lastContent = new Map(); + +/** + * vault.process for table notes: the result is recorded as the plugin's own + * write. An edit that changes nothing (returns the content as it is) isn't + * recorded, so a hand edit it declined to overwrite is still imported. + */ +export async function processTableNote(app: App, file: TFile, edit: (content: string) => string): Promise { + return app.vault.process(file, (content) => { + const next = edit(content); + if (next !== content) lastContent.set(file.path, next); + return next; + }); +} + +const QUIET_MS = 1500; + +export class TableStore { + private timers = new Map(); + + constructor( + private app: App, + private scope: () => { tablesFolder: string; workflowsFolder: string }, + /** Called after an import rewrote a note (for a notice or a refresh). */ + private onImported?: (path: string, kind: ImportKind) => void, + ) {} + + /** Hook into the plugin's vault events and remember every table note's content. */ + static register(plugin: HexmakerPlugin): TableStore { + const store = new TableStore(plugin.app, () => ({ + tablesFolder: normalizeFolder(plugin.settings.tablesFolder ?? ""), + workflowsFolder: normalizeFolder(plugin.settings.workflowsFolder ?? ""), + })); + const { vault } = plugin.app; + plugin.registerEvent(vault.on("modify", (f) => store.onModify(f))); + plugin.registerEvent(vault.on("create", (f) => void store.remember(f))); + plugin.registerEvent(vault.on("rename", (f, old) => store.onRename(f, old))); + plugin.registerEvent(vault.on("delete", (f) => lastContent.delete(f.path))); + void store.init(); + return store; + } + + isTable(path: string): boolean { + const s = this.scope(); + return isTableNotePath(path, s.tablesFolder, s.workflowsFolder); + } + + async init(): Promise { + for (const f of this.app.vault.getMarkdownFiles()) { + if (this.isTable(f.path) && !lastContent.has(f.path)) await this.remember(f); + } + } + + async remember(f: TAbstractFile): Promise { + if (f instanceof TFile && this.isTable(f.path)) lastContent.set(f.path, await this.app.vault.cachedRead(f)); + } + + onRename(f: TAbstractFile, oldPath: string): void { + const c = lastContent.get(oldPath); + lastContent.delete(oldPath); + if (c !== undefined && this.isTable(f.path)) lastContent.set(f.path, c); + } + + onModify(f: TAbstractFile): void { + if (!(f instanceof TFile) || !this.isTable(f.path)) return; + const prev = this.timers.get(f.path); + if (prev !== undefined) window.clearTimeout(prev); + this.timers.set( + f.path, + window.setTimeout(() => { + this.timers.delete(f.path); + void this.importNow(f); + }, QUIET_MS), + ); + } + + /** True while the note is open in an editor that has focus (don't rewrite under the cursor). */ + private beingTyped(file: TFile): boolean { + let typing = false; + this.app.workspace.iterateAllLeaves((leaf) => { + const v = leaf.view; + if (v instanceof MarkdownView && v.file?.path === file.path && v.getMode() === "source" && v.editor.hasFocus()) typing = true; + }); + return typing; + } + + /** + * Compare the note with the last content the plugin saw and import the + * edit. Returns what was done. + */ + async importNow(file: TFile, opts: { ignoreFocus?: boolean } = {}): Promise { + const cur = await this.app.vault.read(file); + const prev = lastContent.get(file.path); + if (prev === undefined || prev === cur) { + lastContent.set(file.path, cur); + return "none"; + } + if (!opts.ignoreFocus && this.beingTyped(file)) { + // Try again once the person stops typing (the next modify reschedules too). + this.onModify(file); + return "none"; + } + const result = importHandEdit(prev, cur); + if (result.content === cur) { + lastContent.set(file.path, cur); + return result.kind; + } + let wrote = false; + await this.app.vault.process(file, (now) => { + if (now !== cur) return now; // edited again meanwhile: the next modify handles it + wrote = true; + lastContent.set(file.path, result.content); + return result.content; + }); + if (wrote) this.onImported?.(file.path, result.kind); + return wrote ? result.kind : "none"; + } +} diff --git a/src/random-tables/WorkflowEditorModal.ts b/src/random-tables/WorkflowEditorModal.ts index ef90fe9a..b502e87d 100644 --- a/src/random-tables/WorkflowEditorModal.ts +++ b/src/random-tables/WorkflowEditorModal.ts @@ -1,5 +1,7 @@ import { App, TFile, Notice } from "obsidian"; import { HexmakerModal } from "../HexmakerModal"; +import { dragGrip } from "../ui/pickers"; +import { renderSaveStatusLine } from "../ui/saveStatusLine"; import type HexmakerPlugin from "../HexmakerPlugin"; import { normalizeFolder } from "../utils"; import { WorkflowExportModal } from "./WorkflowExportModal"; @@ -11,8 +13,14 @@ import { stepPlaceholder, stepVarName, isDiceFormula, + reconcileTemplate, + unfilledTokens, type WorkflowStep, } from "./workflow"; +import { isWritableTemplate, newTemplatePath, resolveWorkflowTemplate, saveWorkflowTemplate, stepDieLabels, templateRoots } from "./workflowFiles"; +import { noteLink } from "../noteFormats"; +import { groupTableFiles } from "./tablePickerGroups"; +import { MAP_MADE_GROUP_LABEL } from "./resolve"; import { escapeRegex, placeholderPattern } from "../textUtils"; /** Convert a table basename to a default label: spaces → underscores. */ @@ -29,7 +37,8 @@ export class WorkflowEditorModal extends HexmakerModal { private plugin: HexmakerPlugin, private file: TFile, private onSaved?: () => void, - private preloaded?: { content: string; templateContent: string }, + /** The workflow note's text when the caller already read it (the template is always read here). */ + private preloaded?: { content: string }, ) { super(app); } @@ -49,20 +58,31 @@ export class WorkflowEditorModal extends HexmakerModal { let description = workflow.description ?? ""; let templateContent = ""; - // Load template file if it exists - if (this.preloaded !== undefined) { - templateContent = this.preloaded.templateContent; - } else if (workflow.templateFile) { - const tmplFile = this.app.vault.getAbstractFileByPath( - workflow.templateFile, - ); - if (tmplFile instanceof TFile) { - templateContent = await this.app.vault.read(tmplFile); - } - } + // The template note (however its path was typed). It's written on + // close only when it's a note under the workflows or world folder: + // `template-file` is note text, and may come from someone else's pack. + const roots = templateRoots(this.plugin.settings); + const handSet = workflow.templateFile; + const tmplFile = handSet ? resolveWorkflowTemplate(this.app, handSet, this.file.path) : null; + const wfFolder = normalizeFolder(this.plugin.settings.workflowsFolder); + const templatePath = tmplFile?.path + ?? newTemplatePath(handSet) + ?? `${wfFolder}/templates/${this.file.basename}.md`; + const templateWritable = isWritableTemplate(templatePath, roots); + /** The template's text as read now (null: no note yet), to tell a later edit elsewhere from ours. */ + const templateAtOpen = tmplFile ? await this.app.vault.read(tmplFile) : null; + templateContent = templateAtOpen ?? ""; if (!templateContent) { templateContent = generateDefaultTemplate(steps); } + // Steps whose placeholders the template lacks get them (saved on close). + if (templateWritable) { + const reconciled = reconcileTemplate(templateContent, steps); + templateContent = reconciled.template; + if (reconciled.added.length) { + new Notice(`Added ${reconciled.added.join(", ")} to the template: no part of it showed those steps' results.`); + } + } // All table files in the tables folder for the picker const tablesFolder = normalizeFolder(this.plugin.settings.tablesFolder); @@ -71,6 +91,22 @@ export class WorkflowEditorModal extends HexmakerModal { .filter((f) => !tablesFolder || f.path.startsWith(tablesFolder + "/")) .filter((f) => !f.basename.startsWith("_")) .sort((a, b) => a.path.localeCompare(b.path)); + // The user's tables first; the terrain and region tables the map made + // in a "Made by the map" group at the end of each table dropdown. + const tableGroups = groupTableFiles(this.app, tableFiles); + const addTableOptions = (select: HTMLSelectElement, selected?: string) => { + const add = (parent: HTMLElement, tf: TFile) => { + const val = tf.path.slice(0, -3); + const text = tablesFolder ? tf.path.slice(tablesFolder.length + 1, -3) : val; + const opt = parent.createEl("option", { value: val, text }); + if (val === selected) opt.selected = true; + }; + for (const tf of tableGroups.own) add(select, tf); + if (tableGroups.mapMade.length) { + const group = select.createEl("optgroup", { attr: { label: MAP_MADE_GROUP_LABEL } }); + for (const tf of tableGroups.mapMade) add(group, tf); + } + }; // ── Name row ───────────────────────────────────────────────────── const nameRow = contentEl.createDiv({ @@ -141,6 +177,13 @@ export class WorkflowEditorModal extends HexmakerModal { cls: "duckmage-wf-template-area", }); templateArea.value = templateContent; + if (!templateWritable) { + templateArea.readOnly = true; + templateSectionWrap.createEl("p", { + text: `The template (${templatePath}) is outside the world and workflows folders, so it isn't changed here.`, + cls: "duckmage-table-editor-warning", + }); + } templateArea.addEventListener("input", () => { templateContent = templateArea.value; updateValidation(); @@ -208,15 +251,18 @@ export class WorkflowEditorModal extends HexmakerModal { const updateValidation = () => { const required = requiredPlaceholders(steps); const missing = required.filter((p) => !templateContent.includes(p)); - if (missing.length === 0) { + const unfilled = unfilledTokens(templateContent, steps); + validationEl.empty(); + if (missing.length === 0 && unfilled.length === 0) { validationEl.className = "duckmage-wf-validation-ok"; validationEl.setText( required.length > 0 ? "✓ All placeholders present" : "", ); - } else { - validationEl.className = "duckmage-wf-validation-err"; - validationEl.setText(`Missing: ${missing.join(", ")}`); + return; } + validationEl.className = "duckmage-wf-validation-err"; + if (missing.length) validationEl.createDiv({ text: `Missing: ${missing.join(", ")}` }); + if (unfilled.length) validationEl.createDiv({ text: `No step fills: ${unfilled.join(", ")}` }); }; const getTemplateLabel = (step: WorkflowStep): string => { @@ -332,10 +378,7 @@ export class WorkflowEditorModal extends HexmakerModal { const row = stepsEl.createDiv({ cls: "duckmage-wf-editor-step-row" }); row.draggable = true; - const handle = row.createSpan({ - cls: "duckmage-table-editor-drag-handle", - text: "⠿", - }); + const handle = dragGrip(row, "duckmage-table-editor-drag-handle"); handle.title = "Drag to reorder"; // Kind badge @@ -373,17 +416,7 @@ export class WorkflowEditorModal extends HexmakerModal { value: "", text: "— select table —", }); - for (const tf of tableFiles) { - const val = tf.path.slice(0, -3); - const optLabel = tablesFolder - ? tf.path.slice(tablesFolder.length + 1, -3) - : val; - const opt = tableSelect.createEl("option", { - value: val, - text: optLabel, - }); - if (val === step.tablePath) opt.selected = true; - } + addTableOptions(tableSelect, step.tablePath); if ( step.tablePath && !tableFiles.some((tf) => tf.path.slice(0, -3) === step.tablePath) @@ -537,13 +570,7 @@ export class WorkflowEditorModal extends HexmakerModal { value: "", text: "— select table —", }); - for (const tf of tableFiles) { - const val = tf.path.slice(0, -3); - const optLabel = tablesFolder - ? tf.path.slice(tablesFolder.length + 1, -3) - : val; - addTableSelect.createEl("option", { value: val, text: optLabel }); - } + addTableOptions(addTableSelect); addTableSelect.addEventListener("change", () => { if (!addLabelInput.value.trim() && addTableSelect!.value) { const basename = @@ -627,60 +654,51 @@ export class WorkflowEditorModal extends HexmakerModal { renderSteps(); updateValidation(); - // ── Footer ──────────────────────────────────────────────────────── - const footer = contentEl.createDiv({ cls: "duckmage-table-editor-footer" }); this.flushAndSave = async () => { - const wfFolder = normalizeFolder(this.plugin.settings.workflowsFolder); - const templatePath = `${wfFolder}/templates/${this.file.basename}.md`; - const updatedWorkflow = { name: this.file.basename, description: description || undefined, resultsFolder: resultsFolder || undefined, - templateFile: templatePath, + // A template-file set by hand is kept; one without gets the default + // beside its workflows, written as a link so renaming it keeps it (NF3). + templateFile: handSet || JSON.stringify(noteLink(templatePath)), steps, }; try { - await this.app.vault.process(this.file, () => - buildWorkflowContent(updatedWorkflow), + const dies = await stepDieLabels(this.app, steps, this.file.path); + await this.app.vault.process(this.file, (current) => + buildWorkflowContent(updatedWorkflow, { + existing: current, + dieFor: (step) => dies.get(step.tablePath), + }), ); - - const templateDir = `${wfFolder}/templates`; - if (!this.app.vault.getAbstractFileByPath(templateDir)) { - try { - await this.app.vault.createFolder(templateDir); - } catch { - /* may exist */ - } - } - const tmplFile = this.app.vault.getAbstractFileByPath(templatePath); - if (tmplFile instanceof TFile) { - await this.app.vault.process(tmplFile, () => templateContent); - } else { - await this.app.vault.create(templatePath, templateContent); - } - + if (templateWritable) await this.saveTemplate(tmplFile ?? templatePath, templateAtOpen, templateContent); this.onSaved?.(); } catch (err) { new Notice(`Could not save workflow: ${String(err)}`); } }; - footer - .createEl("button", { text: "Export…", cls: "mod-cta" }) - .addEventListener("click", () => { - new WorkflowExportModal(this.app, this.plugin, this.file).open(); - }); - - footer - .createEl("button", { text: "Close", cls: "mod-cta" }) - .addEventListener("click", () => this.close()); + // Footer: Export… only (owner Q5: no Close; × closes and saves), with the autosave line. + const foot = this.footer({ + secondary: [{ text: "Export…", onClick: () => new WorkflowExportModal(this.app, this.plugin, this.file).open() }], + }); + foot.el.prepend(renderSaveStatusLine(foot.el, { title: "Saves when you close this (×). There is no Save button." }).el); this.makeDraggable(); } + /** Write the template on close (workflowFiles.saveWorkflowTemplate); say so when it was changed elsewhere. */ + private async saveTemplate(target: TFile | string, atOpen: string | null, text: string): Promise { + const verdict = await saveWorkflowTemplate(this.app, target, atOpen, text); + if (verdict === "stale") { + const path = target instanceof TFile ? target.path : target; + new Notice(`${path} was changed elsewhere while this workflow was open, so your template changes weren't saved.`); + } + } + onClose(): void { void this.flushAndSave?.(); this.flushAndSave = null; diff --git a/src/random-tables/WorkflowExportModal.ts b/src/random-tables/WorkflowExportModal.ts index ae1097dd..ba0917e4 100644 --- a/src/random-tables/WorkflowExportModal.ts +++ b/src/random-tables/WorkflowExportModal.ts @@ -10,6 +10,7 @@ import { App, TFile } from "obsidian"; import { HexmakerModal } from "../HexmakerModal"; import type HexmakerPlugin from "../HexmakerPlugin"; +import { pdfAvailable } from "../platform"; import { exportWorkflowAsPdf, exportWorkflowAsMarkdown, @@ -101,16 +102,17 @@ export class WorkflowExportModal extends HexmakerModal { }); const actions = contentEl.createDiv({ cls: "duckmage-export-tab-actions" }); - const pdfBtn = actions.createEl("button", { - cls: "mod-cta", - text: "Export PDF", - }); - pdfBtn.addEventListener("click", () => { - void exportWorkflowAsPdf(this.plugin, this.workflowFile, collectOpts()); - this.close(); - }); + // A list of export choices: plain buttons (audit B1). + if (pdfAvailable()) { + const pdfBtn = actions.createEl("button", { + text: "Export PDF", + }); + pdfBtn.addEventListener("click", () => { + void exportWorkflowAsPdf(this.plugin, this.workflowFile, collectOpts()); + this.close(); + }); + } const mdBtn = actions.createEl("button", { - cls: "mod-cta", text: "Export Markdown", }); mdBtn.addEventListener("click", () => { diff --git a/src/random-tables/WorkflowWizardModal.ts b/src/random-tables/WorkflowWizardModal.ts index 56afb503..704d3628 100644 --- a/src/random-tables/WorkflowWizardModal.ts +++ b/src/random-tables/WorkflowWizardModal.ts @@ -8,17 +8,72 @@ import { stepPlaceholder, rollDiceFormulaWithBreakdown, type Workflow, + workflowResultAsSectionText, WorkflowStep, + reconcileTemplate, + unfilledTokens, + fillWorkflowTemplate, + buildResultsNote, + type FilledValue, + type RollRecord, } from "./workflow"; -import { parseRandomTable, rollOnTable } from "./randomTable"; -import { fillPlaceholders } from "../textUtils"; +import { dieLabel, parseRandomTable, rollTable } from "./randomTable"; +import { renderAddToHex, type RollHexTarget } from "./RandomTableModal"; +import { resolveStepTable, resolveWorkflowTemplate, resultsNotePlace } from "./workflowFiles"; +import { ensureFolder } from "../vault/ensureFolder"; +import { localIsoDateTime } from "../provenance"; +import { withRepairHint } from "../ui/repairHint"; +import { renderEmptyTableState, setRollEnabled } from "./emptyTable"; + +/** How a slot got its value, for the results note's Rolls table. */ +interface SlotInfo { + /** Link text of the note a linked result is. */ + link?: string; + /** The face rolled (rolls by ranges) or the dice breakdown. */ + roll?: string; + /** Picked from the list or typed, not rolled. */ + manual?: "picked" | "typed"; +} + +/** A table row offered in the manual-pick list. */ +interface PickEntry { + label: string; + link?: string; +} + +/** The note a table row links to, when the whole row is a link. */ +function rowLinkTarget(result: string, isLink?: boolean, linkedFolder?: string): string | undefined { + if (isLink) return result; + // A linked-folder table lists its notes by name. + if (linkedFolder) return `${normalizeFolder(linkedFolder)}/${result.replace(/\.md$/i, "")}`; + return /^\[\[([^\]|#]+)(?:[#|][^\]]*)?\]\]$/.exec(result.trim())?.[1]; +} + +/** + * A note name that isn't taken: the name itself, else "Name 2", "Name 3", … + * (owner Q6: auto-rename instead of asking to replace). Pure. + */ +export function freeNoteName(name: string, taken: (name: string) => boolean): string { + if (!taken(name)) return name; + for (let n = 2; ; n++) if (!taken(`${name} ${n}`)) return `${name} ${n}`; +} export class WorkflowWizardModal extends HexmakerModal { private workflow!: Workflow; // rolls[stepIdx][rollIdx] = result string or null (not yet rolled) private rolls: (string | null)[][] = []; private templateContent = ""; - private stepEntries: string[][] = []; // [stepIdx] → display labels from the table + private stepEntries: PickEntry[][] = []; // [stepIdx] → rows of the table + /** [stepIdx] → the step's table while it has no entries (SF1: its Roll is disabled). */ + private stepEmpty: ({ file: TFile; content: string } | null)[] = []; + /** slots[stepIdx][rollIdx]: how the value was got. */ + private slots: SlotInfo[][] = []; + /** Per step: its source (link or formula) and die, for the Rolls table. */ + private stepSource: { source: string; die: string }[] = []; + /** $tokens in the template no step fills. */ + private unfilled: string[] = []; + /** Placeholders the template lacked; added for this run. */ + private addedToTemplate: string[] = []; private resultTextarea!: HTMLTextAreaElement; private saveNoteNameInput!: HTMLInputElement; private saveResultsFolderInput!: HTMLInputElement; @@ -32,6 +87,8 @@ export class WorkflowWizardModal extends HexmakerModal { app: App, private plugin: HexmakerPlugin, private workflowFile: TFile, + /** Run from a hex (PA2): the result can be added to that hex's note. */ + private hexTarget?: RollHexTarget, ) { super(app); } @@ -50,44 +107,52 @@ export class WorkflowWizardModal extends HexmakerModal { this.sumOnly = this.workflow.steps.map((step: WorkflowStep) => Array.from({ length: step.rolls }, () => false), ); + this.slots = this.workflow.steps.map((step: WorkflowStep) => + Array.from({ length: step.rolls }, (): SlotInfo => ({})), + ); + this.stepSource = this.workflow.steps.map((step) => ({ + source: step.kind === "dice" ? (step.diceFormula ?? "") : `[[${step.tablePath}]]`, + die: step.kind === "dice" ? (step.diceFormula ?? "") : "", + })); // Preload table entries for each step (for the manual-pick dropdown; dice steps have no entries) - this.stepEntries = await Promise.all( - this.workflow.steps.map(async (step: WorkflowStep) => { - if (step.kind === "dice") return []; - const tableFile = - this.app.vault.getAbstractFileByPath(step.tablePath + ".md") ?? - this.app.metadataCache.getFirstLinkpathDest( - step.tablePath, - this.workflowFile.path, - ); - if (!(tableFile instanceof TFile)) return []; - const content = await this.app.vault.read(tableFile); - const table = parseRandomTable(content); - return table.entries.map((e) => - e.result.startsWith("[[") - ? (e.result.slice(2, -2).split("/").pop() ?? e.result.slice(2, -2)) - : e.result, - ); - }), - ); + this.stepEntries = await Promise.all(this.workflow.steps.map((step, si) => this.loadStepEntries(step, si))); - // Load template - if (this.workflow.templateFile) { - const tmplFile = this.app.vault.getAbstractFileByPath( - this.workflow.templateFile, - ); - if (tmplFile instanceof TFile) { - this.templateContent = await this.app.vault.read(tmplFile); - } - } + // Load the template (however its path was typed), and add any + // placeholders a step fills that it lacks, for this run. + const tmplFile = resolveWorkflowTemplate(this.app, this.workflow.templateFile, this.workflowFile.path); + if (tmplFile) this.templateContent = await this.app.vault.read(tmplFile); if (!this.templateContent) { this.templateContent = generateDefaultTemplate(this.workflow.steps); } + const reconciled = reconcileTemplate(this.templateContent, this.workflow.steps); + this.templateContent = reconciled.template; + this.addedToTemplate = reconciled.added; + this.unfilled = unfilledTokens(this.templateContent, this.workflow.steps); this.buildUI(); } + /** A step's table rows for the manual-pick list; notes an empty table (SF1). */ + private async loadStepEntries(step: WorkflowStep, si: number): Promise { + this.stepEmpty[si] = null; + if (step.kind === "dice") return []; + const tableFile = resolveStepTable(this.app, step, this.workflowFile.path); + if (!tableFile) return []; + const content = await this.app.vault.read(tableFile); + const table = parseRandomTable(content); + if (!table.entries.length) this.stepEmpty[si] = { file: tableFile, content }; + this.stepSource[si] = { + source: `[[${this.app.metadataCache.fileToLinktext(tableFile, this.workflowFile.path)}]]`, + die: dieLabel(table.dice), + }; + return table.entries.map((e) => { + const target = rowLinkTarget(e.result, e.isLink, table.linkedFolder); + if (!target) return { label: e.result }; + return { label: target.split("/").pop() ?? target, link: this.linkTextFor(target) }; + }); + } + private buildUI(): void { const { contentEl } = this; contentEl.empty(); @@ -98,7 +163,6 @@ export class WorkflowWizardModal extends HexmakerModal { const rollAllBtn = header.createEl("button", { text: "Roll all", - cls: "mod-cta", }); rollAllBtn.title = "Roll all unfilled slots"; rollAllBtn.addEventListener("click", () => { void this.rollAll(false); }); @@ -107,6 +171,17 @@ export class WorkflowWizardModal extends HexmakerModal { rerollAllBtn.title = "Reroll every slot"; rerollAllBtn.addEventListener("click", () => { void this.rollAll(true); }); + // The template and the steps disagree: say so (the editor fixes it). + if (this.unfilled.length || this.addedToTemplate.length) { + const warn = contentEl.createDiv({ cls: "duckmage-wf-validation-err duckmage-wf-wizard-warning" }); + if (this.unfilled.length) { + warn.createDiv({ text: `No step fills ${this.unfilled.join(", ")}, so it stays as typed.` }); + } + if (this.addedToTemplate.length) { + warn.createDiv({ text: `The template has no ${this.addedToTemplate.join(", ")}; added at the end for this run. Edit the workflow to keep them.` }); + } + } + // ── Steps area ──────────────────────────────────────────────────── this.stepsArea = contentEl.createDiv({ cls: "duckmage-wf-wizard-steps" }); this.renderSteps(); @@ -122,7 +197,8 @@ export class WorkflowWizardModal extends HexmakerModal { this.resultTextarea.readOnly = true; this.resultTextarea.value = this.assembleResult(); - const copyResultBtn = contentEl.createEl("button", { text: "Copy result" }); + const resultBtns = contentEl.createDiv({ cls: "duckmage-wf-result-buttons" }); + const copyResultBtn = resultBtns.createEl("button", { text: "Copy result" }); copyResultBtn.addEventListener("click", () => { void navigator.clipboard .writeText(this.resultTextarea?.value ?? "") @@ -131,6 +207,13 @@ export class WorkflowWizardModal extends HexmakerModal { window.setTimeout(() => copyResultBtn.setText("Copy result"), 1500); }); }); + // Run from a hex: put the filled-in result into one of its sections. + if (this.hexTarget) { + renderAddToHex(resultBtns, this.hexTarget, () => workflowResultAsSectionText(this.resultTextarea?.value ?? ""), { + cta: true, + onAdded: () => this.close(), + }); + } // ── Save section ────────────────────────────────────────────────── contentEl.createEl("p", { @@ -149,7 +232,7 @@ export class WorkflowWizardModal extends HexmakerModal { type: "text", cls: "duckmage-table-editor-name-input", }); - this.saveNoteNameInput.value = ""; + this.saveNoteNameInput.value = this.defaultNoteName(); const saveResultsFolderRow = contentEl.createDiv({ cls: "duckmage-table-editor-name-row", @@ -182,9 +265,10 @@ export class WorkflowWizardModal extends HexmakerModal { this.workflow.resultsFolder ?? "", ); + // Run from a hex, "Add to this hex" is the main action; saving a note is secondary. this.saveNoteBtn = contentEl.createEl("button", { text: "Save as note", - cls: "mod-cta", + cls: this.hexTarget ? "" : "mod-cta", }); this.saveStatusEl = contentEl.createDiv({ cls: "duckmage-wf-save-status" }); @@ -239,6 +323,25 @@ export class WorkflowWizardModal extends HexmakerModal { }); } + // An empty table: its Rolls are disabled and the empty state opens + // the table editor; after a save the step is reloaded (SF1). + const empty = this.stepEmpty[si]; + if (empty) { + renderEmptyTableState(stepEl, { + app: this.app, + plugin: this.plugin, + file: empty.file, + content: empty.content, + compact: true, + onSaved: () => { + void this.loadStepEntries(step, si).then((rows) => { + this.stepEntries[si] = rows; + this.renderSteps(); + }); + }, + }); + } + for (let ri = 0; ri < step.rolls; ri++) { const rollRow = stepEl.createDiv({ cls: "duckmage-wf-step-row" }); @@ -258,6 +361,7 @@ export class WorkflowWizardModal extends HexmakerModal { rollInput.placeholder = "—"; rollInput.addEventListener("input", () => { this.rolls[si][ri] = rollInput.value.trim() || null; + this.slots[si][ri] = { manual: "typed" }; this.updateResultTextarea(); this.updateSaveButton(); }); @@ -268,13 +372,15 @@ export class WorkflowWizardModal extends HexmakerModal { cls: "duckmage-wf-pick-select", }); pickerSelect.createEl("option", { value: "", text: "— pick —" }); - for (const label of this.stepEntries[si] ?? []) { - pickerSelect.createEl("option", { value: label, text: label }); - } + (this.stepEntries[si] ?? []).forEach((entry, ei) => { + pickerSelect.createEl("option", { value: String(ei), text: entry.label }); + }); pickerSelect.addEventListener("change", () => { - const picked = pickerSelect.value; - if (!picked) return; + const entry = pickerSelect.value === "" ? undefined : this.stepEntries[si]?.[Number(pickerSelect.value)]; + if (!entry) return; + const picked = entry.label; this.rolls[si][ri] = picked; + this.slots[si][ri] = { link: entry.link, manual: "picked" }; rollInput.value = picked; rollInput.classList.add("is-rolled"); rollBtn.setText("Reroll"); @@ -288,6 +394,7 @@ export class WorkflowWizardModal extends HexmakerModal { text: this.rolls[si][ri] !== null ? "Reroll" : "Roll", cls: "duckmage-wf-roll-btn", }); + if (empty) setRollEnabled(rollBtn, false); rollBtn.addEventListener("click", () => { void (async () => { rollBtn.disabled = true; @@ -324,33 +431,38 @@ export class WorkflowWizardModal extends HexmakerModal { const step = this.workflow.steps[stepIdx]; if (step.kind === "dice") { - this.rolls[stepIdx][rollIdx] = rollDiceFormulaWithBreakdown( - step.diceFormula ?? "1d6", - ); + const rolled = rollDiceFormulaWithBreakdown(step.diceFormula ?? "1d6"); + this.rolls[stepIdx][rollIdx] = rolled; + this.slots[stepIdx][rollIdx] = { roll: rolled }; return; } // Try exact path first, then Obsidian link resolution with workflow file as source - const tableFile = - this.app.vault.getAbstractFileByPath(step.tablePath + ".md") ?? - this.app.metadataCache.getFirstLinkpathDest( - step.tablePath, - this.workflowFile.path, - ); - if (!(tableFile instanceof TFile)) { - new Notice(`Table not found: ${step.tablePath}`); + const tableFile = resolveStepTable(this.app, step, this.workflowFile.path); + if (!tableFile) { + new Notice(withRepairHint(`Table not found: ${step.tablePath}`)); return; } const content = await this.app.vault.read(tableFile); const table = parseRandomTable(content); - const entry = rollOnTable(table); - if (!entry) return; - - const displayLabel = entry.isLink - ? (entry.result.split("/").pop() ?? entry.result) - : entry.result; + const outcome = rollTable(table); + if (!outcome) return; + const entry = outcome.entry; + + // A linked row keeps its link (shown by name in the wizard). + const target = rowLinkTarget(entry.result, entry.isLink, table.linkedFolder); + this.rolls[stepIdx][rollIdx] = target ? (target.split("/").pop() ?? target) : entry.result; + this.slots[stepIdx][rollIdx] = { + link: target ? this.linkTextFor(target) : undefined, + roll: outcome.face !== undefined ? String(outcome.face) : "", + }; + } - this.rolls[stepIdx][rollIdx] = displayLabel; + /** Shortest link text for a note path (the path itself if it doesn't resolve). */ + private linkTextFor(target: string): string { + const clean = target.replace(/\.md$/i, ""); + const file = this.app.metadataCache.getFirstLinkpathDest(clean, this.workflowFile.path); + return file ? this.app.metadataCache.fileToLinktext(file, this.workflowFile.path) : clean; } /** Roll all unfilled slots (rerollAll=false) or every slot (rerollAll=true). */ @@ -368,7 +480,35 @@ export class WorkflowWizardModal extends HexmakerModal { } private assembleResult(): string { - const values = new Map(); + return fillWorkflowTemplate(this.templateContent, this.filledValues()); + } + + /** One row per rolled slot, for the results note. */ + private rollRecords(): RollRecord[] { + const values = this.filledValues(); + const records: RollRecord[] = []; + this.workflow.steps.forEach((step, si) => { + for (let ri = 0; ri < step.rolls; ri++) { + if (this.rolls[si][ri] === null) continue; + const placeholder = stepPlaceholder(step, ri); + const v = values.get(placeholder); + const slot = this.slots[si]?.[ri] ?? {}; + records.push({ + placeholder, + source: this.stepSource[si]?.source ?? "", + die: this.stepSource[si]?.die ?? "", + roll: slot.manual ?? slot.roll ?? "", + // The result as it reads in the note (a link stays a link). + result: v ? fillWorkflowTemplate(placeholder, new Map([[placeholder, v]])) : "", + }); + } + }); + return records; + } + + /** What each placeholder gets: the value shown, and its link if it's a linked row. */ + private filledValues(): Map { + const values = new Map(); for (let si = 0; si < this.workflow.steps.length; si++) { const step = this.workflow.steps[si]; for (let ri = 0; ri < step.rolls; ri++) { @@ -379,10 +519,11 @@ export class WorkflowWizardModal extends HexmakerModal { // Extract just the sum from "(d1+d2+...)=N" format display = display.replace(/^\(.*\)=(-?\d+)$/, "$1"); } - values.set(placeholder, display !== null ? display : `[${placeholder}]`); + if (display === null) values.set(placeholder, { text: `[${placeholder}]` }); + else values.set(placeholder, { text: display, link: this.slots[si]?.[ri]?.link }); } } - return fillPlaceholders(this.templateContent, values); + return values; } private updateResultTextarea(): void { @@ -408,36 +549,38 @@ export class WorkflowWizardModal extends HexmakerModal { return `${this.workflowFile.basename} ${ts}`; } - private async saveAsNote(): Promise { - const noteName = this.saveNoteNameInput.value.trim(); - if (!noteName) { + private saveAsNote(): Promise { + const place = resultsNotePlace(this.saveResultsFolderInput.value, this.saveNoteNameInput.value, this.plugin.settings); + if ("error" in place) return this.writeNote(); + const { folder, name: noteName } = place; + // No "Replace note?" (owner Q6): a name that's taken gets a number ("Name 2"). + const free = freeNoteName(noteName, (n) => !!this.app.vault.getAbstractFileByPath(folder ? `${folder}/${n}.md` : `${n}.md`)); + this.saveNoteNameInput.value = free; + if (free !== noteName) new Notice(`"${noteName}" already exists, so this was saved as "${free}".`); + return this.writeNote(); + } + + private async writeNote(): Promise { + const place = resultsNotePlace(this.saveResultsFolderInput.value, this.saveNoteNameInput.value, this.plugin.settings); + if ("error" in place) { this.saveStatusEl.setCssProps({ color: "var(--color-red)" }); - this.saveStatusEl.setText("Note name is required."); + this.saveStatusEl.setText(place.error); return; } - - const folder = normalizeFolder(this.saveResultsFolderInput.value.trim()); + const { folder, name: noteName } = place; const notePath = folder ? `${folder}/${noteName}.md` : `${noteName}.md`; - if (folder && !this.app.vault.getAbstractFileByPath(folder)) { - try { - await this.app.vault.createFolder(folder); - } catch { - /* may already exist */ - } - } + if (folder) await ensureFolder(this.app.vault, folder); - const noteContent = this.resultTextarea.value; + const noteContent = buildResultsNote( + this.resultTextarea.value, + { workflowPath: this.workflowFile.path, rolled: localIsoDateTime() }, + this.rollRecords(), + ); try { - let savedFile: TFile; - const existing = this.app.vault.getAbstractFileByPath(notePath); - if (existing instanceof TFile) { - await this.app.vault.process(existing, () => noteContent); - savedFile = existing; - } else { - savedFile = await this.app.vault.create(notePath, noteContent); - } + // saveAsNote picked a free name, so this never writes over a note. + const savedFile: TFile = await this.app.vault.create(notePath, noteContent); this.close(); await this.app.workspace.getLeaf("tab").openFile(savedFile); } catch (err) { diff --git a/src/random-tables/emptyTable.ts b/src/random-tables/emptyTable.ts new file mode 100644 index 00000000..fb99a153 --- /dev/null +++ b/src/random-tables/emptyTable.ts @@ -0,0 +1,50 @@ +import type { App, TFile } from "obsidian"; +import type HexmakerPlugin from "../HexmakerPlugin"; +import { emptyTableMessage, parseRandomTable } from "./randomTable"; +import { RandomTableEditorModal } from "./RandomTableEditorModal"; + +/** + * An empty table, wherever it can be rolled (owner SF1, 2026-10-14): + * tables ship empty, so Roll is disabled, not a silent no-op, and a short + * empty state opens the table editor to add entries. The roll dialog, the + * random tables view, the in-note roller, workflows and the hex editor all + * use this one helper. + */ + +/** Tooltip on a disabled Roll button while its table is empty. */ +export const EMPTY_ROLL_TITLE = "Add entries to roll on this table"; + +/** Whether a table note has nothing to roll. */ +export function tableIsEmpty(content: string): boolean { + return parseRandomTable(content).entries.length === 0; +} + +/** Disable (or re-enable) a Roll button for an empty table. */ +export function setRollEnabled(btn: HTMLButtonElement, enabled: boolean): void { + btn.disabled = !enabled; + if (enabled) btn.removeAttribute("title"); + else btn.title = EMPTY_ROLL_TITLE; +} + +export interface EmptyTableStateOptions { + app: App; + plugin: HexmakerPlugin; + file: TFile; + /** The table note's text (for the message, and passed to the editor). */ + content: string; + /** After the editor saves: redraw with the new entries. */ + onSaved: () => void; + /** One line (the hex editor's table row), not the full message. */ + compact?: boolean; +} + +/** The empty state: what's wrong and an "Add entries" button that opens the table editor. */ +export function renderEmptyTableState(parent: HTMLElement, o: EmptyTableStateOptions): HTMLElement { + const el = parent.createDiv({ cls: `duckmage-rt-empty-state${o.compact ? " is-compact" : ""}` }); + el.createDiv({ cls: "duckmage-rt-empty", text: o.compact ? "No entries yet." : emptyTableMessage(o.content) }); + const add = el.createEl("button", { text: "Add entries", cls: "duckmage-rt-add-entries" }); + add.addEventListener("click", () => { + new RandomTableEditorModal(o.app, o.plugin, o.file, o.onSaved, o.content).open(); + }); + return el; +} diff --git a/src/random-tables/hexRoll.ts b/src/random-tables/hexRoll.ts new file mode 100644 index 00000000..cb5b2a09 --- /dev/null +++ b/src/random-tables/hexRoll.ts @@ -0,0 +1,62 @@ +/** + * Rolling a table for a hex: the hex editor's rolls (🎲 / 📖, weather and + * rumours, "Add to this hex") and the fields of the planned hex generator + * (plan-hex-generation-workflow) all go through this one function, which + * rolls on the shared resolver (resolve.ts, plan-tables-everywhere §2.3): + * + * - a row that links another table is rolled through (nested rolls, the + * loop guard shows ⟲), and the chain is said ("Weather → Storms → hail"); + * - the hex's terrain and terrain type are the When context, so a row + * marked `When: terrain: swamp` only comes up on swamp hexes ("roll + * again" otherwise); + * - a `pick: each` table gives one line per row that came up; + * - a (nothing) row gives no text. + * + * Pure: no Obsidian imports. + */ + +import { chainLabel, resolveEach, resolveRoll, type Resolved, type TableLookup } from "./resolve"; +import type { ConditionContext } from "./tableConditions"; + +export interface HexRollContext extends Pick { + rand?: () => number; + seed?: number; +} + +export interface HexRoll { + /** What to add to the hex: one line per result ("" when nothing came up). */ + text: string; + /** The rows taken in the table itself (to highlight), in order. */ + rows: number[]; + /** The die face of the table's own roll, when it rolled by its ranges. */ + face?: number; + /** "Weather → Storms → hail" for each result that went through another table. */ + chains: string[]; + /** The results, as the resolver gave them. */ + results: Resolved[]; +} + +/** A result as text for the hex: the row's own words (a link's name as written), nothing for (nothing). */ +function resultText(r: Resolved): string { + if (r.kind === "nothing" || r.kind === "empty") return ""; + if (r.kind === "note" || r.kind === "generator") return r.chain[r.chain.length - 1]?.result ?? r.value; + return r.value; +} + +/** Roll the table `link` for a hex (see the top of this file). */ +export function rollForHex(link: string, lookup: TableLookup, ctx: HexRollContext = {}): HexRoll { + const t = lookup.table(link); + const results = t?.table.pick === "each" ? resolveEach(link, lookup, ctx) : [resolveRoll(link, lookup, ctx)].filter((r) => r.kind !== "empty"); + const own = t?.key; + const rows = results.flatMap((r) => (r.chain[0] && r.chain[0].table === own ? [r.chain[0].index] : [])); + const face = results.length === 1 ? results[0].chain[0]?.face : undefined; + const chains = results.filter((r) => r.chain.length > 1).map((r) => chainLabel(r)); + const out: HexRoll = { + text: results.map(resultText).filter((s) => s.trim() !== "").join("\n"), + rows, + chains, + results, + }; + if (face !== undefined) out.face = face; + return out; +} diff --git a/src/random-tables/listRefresh.ts b/src/random-tables/listRefresh.ts new file mode 100644 index 00000000..0518f3d0 --- /dev/null +++ b/src/random-tables/listRefresh.ts @@ -0,0 +1,81 @@ +/** + * When the random tables view's list must redraw on its own, so the manual + * "↺ Refresh list" button is never needed (it's a Debug control now; owner + * note on RTView.refreshList: "confirm it does it at a good cadence"). + * + * The list shows: the tables folder's notes and subfolders (empty ones + * too), each table's group (the map's own tables by `table-type`/made-by + * frontmatter), linked folders (`linkedFolder`), and which workflows use + * each table (the workflow notes' links). So it redraws, debounced + * (LIST_REFRESH_MS), when + * - a note or folder is created, deleted, renamed or moved in or out of the + * tables or workflows folder (vault events), and + * - a table's or workflow's list inputs change (metadata cache "changed", + * compared by `listSignature`, so typing in a table's rows doesn't redraw + * the list), and + * - once when the metadata cache has finished loading ("resolved"), since + * the grouping reads frontmatter that may not be cached at startup. + */ + +/** Debounce for list redraws (a burst of vault events is one redraw). */ +export const LIST_REFRESH_MS = 200; +/** Debounce for the open table's detail redraw after the note changes. */ +export const DETAIL_REFRESH_MS = 300; + +export interface ListFolders { + /** Normalised tables folder ("" = the whole vault). */ + tables: string; + /** Normalised workflows folder ("" = none). */ + workflows: string; +} + +const inside = (path: string, folder: string) => path === folder || path.startsWith(folder + "/"); + +/** Is `path` (a note or folder) one the list shows or depends on? */ +export function touchesList(path: string, folders: ListFolders): boolean { + if (!path) return false; + if (!folders.tables) return true; + return inside(path, folders.tables) || (!!folders.workflows && inside(path, folders.workflows)); +} + +/** The bits of a note's metadata the list depends on. */ +export interface ListCache { + frontmatter?: Record; + links?: { link: string }[]; +} + +/** + * A note's list inputs as a string: a table's linked folder and table type, + * a workflow's links. Equal signatures = the list looks the same. + */ +export function listSignature(isWorkflow: boolean, cache: ListCache | null | undefined): string { + if (isWorkflow) return (cache?.links ?? []).map((l) => l.link).join("\n"); + const fm = cache?.frontmatter ?? {}; + const pick = (k: string) => { + const v = fm[k]; + return v === undefined || v === null ? "" : JSON.stringify(v); + }; + return ["linkedFolder", "linked-folder", "table-type"].map(pick).join("|"); +} + +/** Remembers each note's last signature; says when one changed. */ +export class ListSignatures { + private seen = new Map(); + + /** True when `path`'s signature differs from last time (a first sighting counts as a change only if `firstIsChange`). */ + changed(path: string, sig: string, firstIsChange = false): boolean { + const before = this.seen.get(path); + this.seen.set(path, sig); + return before === undefined ? firstIsChange : before !== sig; + } + + forget(path: string): void { + this.seen.delete(path); + } + + rename(oldPath: string, newPath: string): void { + const sig = this.seen.get(oldPath); + this.seen.delete(oldPath); + if (sig !== undefined) this.seen.set(newPath, sig); + } +} diff --git a/src/random-tables/randomTable.ts b/src/random-tables/randomTable.ts index e6e26229..dde2c21e 100644 --- a/src/random-tables/randomTable.ts +++ b/src/random-tables/randomTable.ts @@ -1,109 +1,929 @@ -import { splitTableRow } from "../textUtils"; +/** + * Random table notes: parse, roll, die ranges and a writer that only touches + * the roll table's own lines. + * + * The note format (issue #45) is meant to be rolled by hand from raw text: + * + * | d20 | Result | Weight | + * |-------|---------|--------| + * | 1–16 | crabmen | 4 | + * | 17–20 | mage | 1 | + * | — | kraken | 0 | + * + * - Columns are found by header name (aliases below), so extra columns and + * text around the table are left alone. + * - What you see in the roll column is what you get: valid stored ranges are + * what the plugin rolls. A blank range cell means "fill in from the + * weights". Ranges that can't be used are reported, and the table then + * rolls by weight. + * - Older `| Result | Weight |` tables still parse exactly as before. + * + * Extensions (plan-tables-everywhere §2.2), all optional and additive; a + * table without them reads exactly as before: + * - frontmatter `rows:` what the rows are (text, note, table, generator, + * terrain, biome or any; default any). A constraint for checks and + * pickers, never a parser switch. Each cell's own kind is worked out + * from what it links to (resolve.ts). `terrain-type:` narrows + * `rows: terrain` (`star`, or `world, gas-giant`). `shown-as:` is the + * default for the Shown as column. `linked-folder:` is read like + * `linkedFolder:`. + * - weights may be decimals (`3.5`, `0.5`) or percentages (`50%` = 0.5). + * - every column besides the roll, Result and Weight columns is a row + * attribute, returned with the roll ({column → cell}). Four of them mean + * the same everywhere: Roll (`now` or `on arrival`), Shown as, Once + * (`per world` or `per map`) and When (tableConditions.ts). + * - frontmatter `pick: each`: every row is rolled on its own `Chance` + * column (`always`, `1 in 2`, `60%`), not one row by weight ("roll for + * each line"); see resolveEach in resolve.ts. + * - `parseRandomTableWithReport(content, { heading })` reads the table + * under a heading (a link like `[[Tundra#Mix]]`). + * + * Pure: no Obsidian imports. + */ + +import { parseWhen, unreadableConditions, type TableCondition } from "./tableConditions"; + +/** What a table's rows are (`rows:` in the frontmatter). */ +export type RowType = "text" | "note" | "table" | "generator" | "terrain" | "biome" | "any"; +export const ROW_TYPES: readonly RowType[] = ["text", "note", "table", "generator", "terrain", "biome", "any"]; + export interface RandomTableEntry { result: string; weight: number; isLink?: boolean; // true when the result is a vault-relative note path (written as [[...]]) + /** The row's roll range as typed in the die column. Absent when blank or there's no die column. */ + range?: string; +} + +/** + * What a row says besides its result, weight and range (parallel to the + * table's entries, so an entry reads exactly as it always did). + */ +export interface RowInfo { + /** Every other column's non-blank cell, by header as written (shared columns included). */ + attrs?: Record; + /** Roll column: roll it through now (default) or leave it for arrival. */ + roll?: "now" | "on arrival"; + /** Shown as column: what an on-arrival row shows until it is rolled. */ + shownAs?: string; + /** Once column: the row fires once per world or once per map. */ + once?: "world" | "map"; + /** When column: the row only fits these contexts. */ + when?: TableCondition[]; + /** Chance column of a `pick: each` table (0..1). */ + chance?: number; } export interface RandomTable { - dice: number; // 0 = no die mapping, show % only + /** Die size: 0 = no die (show % only), 66 = d66. */ + dice: number; entries: RandomTableEntry[]; linkedFolder?: string; description?: string; // user-authored blurb shown above the table + /** `rows:` (absent = any). */ + rows?: RowType; + /** `terrain-type:` (lower case). */ + terrainTypes?: string[]; + /** `shown-as:`: the default for the Shown as column. */ + shownAs?: string; + /** `pick: each`: every row rolls its own Chance (absent: one row by weight). */ + pick?: "each"; + /** Per entry (same order): its other columns. Absent when no row has any. */ + rowInfo?: RowInfo[]; } -/** Parse a random-table markdown file into a RandomTable. */ -export function parseRandomTable(content: string): RandomTable { - // Extract dice from YAML frontmatter - let dice = 0; - const fmMatch = /^---\s*\n([\s\S]*?)\n---/.exec(content); - let linkedFolder: string | undefined; - if (fmMatch) { - const diceMatch = /^dice:\s*(\d+)\s*$/m.exec(fmMatch[1]); - if (diceMatch) dice = parseInt(diceMatch[1], 10); - const lfMatch = /^linkedFolder:\s*(.+)$/m.exec(fmMatch[1]); - if (lfMatch) { - const raw = lfMatch[1].trim(); - // Strip outer YAML quotes if present ("[[path]]" → [[path]]) - const unquoted = /^"(.*)"$/.exec(raw)?.[1] ?? raw; - const wikiLinkMatch = /^\[\[(.+?)\]\]$/.exec(unquoted); - linkedFolder = wikiLinkMatch ? wikiLinkMatch[1].trim() : unquoted; - } - } - - // Extract user description from preamble (text between frontmatter and table, excluding roller link) - const afterFm = fmMatch ? content.slice(fmMatch[0].length) : content; - const firstTableLine = /^[ \t]*\|/m.exec(afterFm); - const preambleText = firstTableLine - ? afterFm.slice(0, firstTableLine.index) - : ""; - const descriptionRaw = preambleText - .replace(/\[.*?\]\(obsidian:\/\/duckmage-roll[^)]*\)/g, "") - .replace(/```duckmage-roller[\s\S]*?```/g, "") - .trim(); - const description = descriptionRaw || undefined; +/** An entry's other columns (an empty object when it has none). */ +export function rowInfoOf(table: RandomTable, index: number): RowInfo { + return table.rowInfo?.[index] ?? {}; +} - // Find first markdown table — lines that start with | - const lines = content.split("\n"); - const entries: RandomTableEntry[] = []; - let inTable = false; - let headerParsed = false; +export type TableIssueCode = + | "no-table" + | "result-column-guessed" + | "die-from-header" + | "die-mismatch" + | "weight-unreadable" + | "range-unreadable" + | "range-out-of-die" + | "range-overlap" + | "range-gap" + | "range-weight-mismatch" + | "too-many-rows" + | "legacy-roller-link" + | "rows-unknown" + | "roll-unknown" + | "once-unknown" + | "when-unknown" + | "pick-unknown" + | "chance-unknown" + | "heading-missing"; + +export interface TableIssue { + code: TableIssueCode; + message: string; + /** 1-based entry number the issue is about, when it's about one row. */ + row?: number; +} + +/** Where the roll table sits in the note, for the writer. */ +export interface TableBlock { + /** Offset of the header line's first character. */ + start: number; + /** Offset just past the last table line (before its line break). */ + end: number; + eol: string; + /** The table's lines, without line breaks. lines[0] is the header. */ + lines: string[]; + /** Index in lines of the |---| row, or -1. */ + separator: number; + /** Header cells (trimmed, unescaped). */ + header: string[]; + /** Column indexes; -1 when the column is absent. */ + cols: { range: number; result: number; weight: number }; + /** Every other column (row attributes, shared columns included). */ + extra: number[]; + /** Line indexes (into lines) of the data rows. */ + rows: number[]; + /** For each entry, the index into rows of the row it came from. */ + entryRows: number[]; + /** True when the header names a result, roll or weight column. */ + recognized: boolean; +} + +export interface TableReport { + table: RandomTable; + issues: TableIssue[]; + block: TableBlock | null; +} + +// ── Dice ──────────────────────────────────────────────────────────────────── + +/** "d20", "d66", or "" for no die. */ +export function dieLabel(dice: number): string { + return dice > 0 ? `d${dice}` : ""; +} + +/** Every value the die can show, in order. d66 is 11–16, 21–26 … 61–66. */ +export function dieFaces(dice: number): number[] { + if (!(dice > 0)) return []; + if (dice === 66) { + const out: number[] = []; + for (let t = 1; t <= 6; t++) for (let o = 1; o <= 6; o++) out.push(t * 10 + o); + return out; + } + return Array.from({ length: dice }, (_, i) => i + 1); +} + +/** Read a die from `20`, `d20`, `1d20`, `d%` or `d66`. 0 when unreadable. */ +export function parseDie(text: string): number { + const m = /^\s*(?:1?d)?(\d+|%)\s*$/i.exec(text.replace(/^["']|["']$/g, "")); + if (!m) return 0; + if (m[1] === "%") return 100; + const n = parseInt(m[1], 10); + return n > 0 ? n : 0; +} + +// ── Header aliases ────────────────────────────────────────────────────────── + +const RANGE_HEADER = /^(?:range|roll|die|dice|#|d%|1?d\d+)$/; +const RESULT_HEADER = /^(?:results?|entry|entries|outcome|item)$/; +const WEIGHT_HEADER = /^(?:weights?|w|wt)$/; + +function headerKey(cell: string): string { + return cell.replace(/[*_`]/g, "").trim().toLowerCase(); +} + +// ── Cells ─────────────────────────────────────────────────────────────────── + +/** + * The raw text spans of a table row's cells (between the pipes), honouring + * `\|` escapes and `|` inside `[[link|alias]]`, like splitTableRow. + */ +export function cellSpans(line: string): { start: number; end: number }[] { + const first = line.indexOf("|"); + if (first < 0) return []; + const spans: { start: number; end: number }[] = []; + let start = first + 1; + let depth = 0; + for (let i = first + 1; i < line.length; i++) { + const ch = line[i]; + if (ch === "\\" && line[i + 1] === "|") i++; + else if (ch === "[" && line[i + 1] === "[") { depth++; i++; } + else if (ch === "]" && line[i + 1] === "]" && depth > 0) { depth--; i++; } + else if (ch === "|" && depth === 0) { + spans.push({ start, end: i }); + start = i + 1; + } + } + if (line.slice(start).trim()) spans.push({ start, end: line.length }); + return spans; +} + +/** A row's cells, trimmed and unescaped. */ +function rowCells(line: string): string[] { + return cellSpans(line).map((s) => line.slice(s.start, s.end).trim().replace(/\\\|/g, "|")); +} + +function isSeparator(trimmed: string): boolean { + return /^\|[\s|:-]+\|?$/.test(trimmed) && trimmed.includes("-"); +} + +// ── Frontmatter ───────────────────────────────────────────────────────────── + +const FRONTMATTER = /^---[ \t]*\r?\n([\s\S]*?)\r?\n---[ \t]*(?:\r?\n|$)/; + +function frontmatterOf(content: string): { body: string; length: number } | null { + const m = FRONTMATTER.exec(content); + return m ? { body: m[1], length: m[0].length } : null; +} + +/** The die named by `dice:` in the frontmatter (0 when absent or unreadable). */ +export function frontmatterDie(content: string): number { + const fm = frontmatterOf(content); + const m = fm ? /^dice:[ \t]*(.*?)[ \t]*$/m.exec(fm.body) : null; + return m ? parseDie(m[1]) : 0; +} + +/** The die named by the roll column's header (0 when there's no such column or it names none). */ +export function rangeHeaderDie(block: TableBlock | null): number { + if (!block || block.cols.range < 0) return 0; + return parseDie(headerKey(block.header[block.cols.range] ?? "").replace(/^#$/, "")); +} + +// ── Locating the roll table ───────────────────────────────────────────────── - for (const line of lines) { +interface TableRun { + start: number; + end: number; + lines: string[]; +} + +/** Every run of table lines outside frontmatter, code fences and callouts. */ +function findTableRuns(content: string): TableRun[] { + const runs: TableRun[] = []; + const fm = frontmatterOf(content); + let pos = fm ? fm.length : 0; + let fence: string | null = null; + let run: TableRun | null = null; + while (pos <= content.length) { + const nl = content.indexOf("\n", pos); + const lineEnd = nl < 0 ? content.length : nl; + const textEnd = lineEnd > pos && content[lineEnd - 1] === "\r" ? lineEnd - 1 : lineEnd; + const line = content.slice(pos, textEnd); const trimmed = line.trim(); - if (!trimmed.startsWith("|")) { - if (inTable) break; // table ended + const fenceMatch = /^(`{3,}|~{3,})/.exec(trimmed); + let isRow = false; + if (fence) { + if (fenceMatch && fenceMatch[1][0] === fence[0] && fenceMatch[1].length >= fence.length && !trimmed.slice(fenceMatch[1].length).trim()) fence = null; + } else if (fenceMatch) { + fence = fenceMatch[1]; + } else if (trimmed.startsWith("|")) { + isRow = true; + } + if (isRow) { + if (!run) run = { start: pos, end: textEnd, lines: [] }; + run.lines.push(line); + run.end = textEnd; + } else if (run) { + runs.push(run); + run = null; + } + if (nl < 0) break; + pos = nl + 1; + } + if (run) runs.push(run); + return runs; +} + +function blockFromRun(run: TableRun, content: string): TableBlock { + const firstBreak = content.indexOf("\n", run.start); + const eol = + firstBreak > 0 && firstBreak <= run.end + 1 + ? content[firstBreak - 1] === "\r" ? "\r\n" : "\n" + : content.includes("\r\n") ? "\r\n" : "\n"; + let headerIdx = 0; + // A stray separator before any header is skipped, as before. + while (headerIdx < run.lines.length - 1 && isSeparator(run.lines[headerIdx].trim())) headerIdx++; + const lines = run.lines.slice(headerIdx); + const header = lines.length ? rowCells(lines[0]) : []; + const keys = header.map(headerKey); + // "Roll" is both an old name for the die column and the shared Roll + // column (now / on arrival): with a die column beside it, it's the latter. + const dieCol = keys.findIndex((k) => RANGE_HEADER.test(k) && k !== "roll"); + let range = dieCol >= 0 ? dieCol : keys.findIndex((k) => RANGE_HEADER.test(k)); + let result = keys.findIndex((k) => RESULT_HEADER.test(k)); + let weight = keys.findIndex((k) => WEIGHT_HEADER.test(k)); + const recognized = range >= 0 || result >= 0 || weight >= 0; + if (!recognized) { + // Unknown header: read by position, as before (result, then weight). + result = 0; + weight = header.length > 1 ? 1 : -1; + range = -1; + } else if (result < 0) { + result = keys.findIndex((_, i) => i !== range && i !== weight); + } + let separator = -1; + const rows: number[] = []; + for (let i = 1; i < lines.length; i++) { + if (isSeparator(lines[i].trim())) { + if (separator < 0) separator = i; continue; } - inTable = true; + rows.push(i); + } + // A lone "Roll" column whose cells all say now / on arrival is the + // shared Roll column, not the die column. + if (range >= 0 && dieCol < 0) { + const cells = rows.map((i) => (rowCells(lines[i])[range] ?? "").trim().toLowerCase()).filter((c) => c !== ""); + if (cells.length && cells.every((c) => c in ROLL_WORDS)) range = -1; + } + // Offsets: start at the header line. + let start = run.start; + for (let i = 0; i < headerIdx; i++) start = content.indexOf("\n", start) + 1; + const extra = header.map((_, i) => i).filter((i) => i !== range && i !== result && i !== weight && header[i].trim() !== ""); + return { start, end: run.end, eol, lines, separator, header, cols: { range, result, weight }, extra, rows, entryRows: [], recognized }; +} + +const HEADING = /^(#{1,6})[ \t]+(.+?)[ \t]*#*[ \t]*$/; + +/** + * The span of the section under a heading (any level, any case): from the + * line after it to the next heading of the same or a higher level. Null + * when the note has no such heading. Headings in code fences don't count. + */ +export function headingSection(content: string, heading: string): { start: number; end: number } | null { + const want = heading.trim().toLowerCase(); + let pos = frontmatterOf(content)?.length ?? 0; + let fence: string | null = null; + let found: { level: number; start: number } | null = null; + while (pos <= content.length) { + const nl = content.indexOf("\n", pos); + const lineEnd = nl < 0 ? content.length : nl; + const line = content.slice(pos, lineEnd).replace(/\r$/, ""); + const t = line.trim(); + const f = /^(`{3,}|~{3,})/.exec(t); + if (fence) { + if (f && f[1][0] === fence[0]) fence = null; + } else if (f) { + fence = f[1]; + } else { + const h = HEADING.exec(t); + if (h) { + const level = h[1].length; + if (found && level <= found.level) return { start: found.start, end: pos }; + if (!found && h[2].trim().toLowerCase() === want) found = { level, start: nl < 0 ? content.length : nl + 1 }; + } + } + if (nl < 0) break; + pos = nl + 1; + } + return found ? { start: found.start, end: content.length } : null; +} - // Skip separator rows (|---|---| style) - if (/^\|[\s|:-]+\|$/.test(trimmed)) continue; +/** + * The roll table: the first table naming a result, roll or weight column, + * else the first table. With a heading, only tables in that heading's + * section count (null when there's no such heading or no table under it). + */ +export function locateRollTable(content: string, heading?: string): TableBlock | null { + let runs = findTableRuns(content); + if (heading !== undefined && heading.trim()) { + const section = headingSection(content, heading); + if (!section) return null; + runs = runs.filter((r) => r.start >= section.start && r.start < section.end); + } + if (!runs.length) return null; + const blocks = runs.map((r) => blockFromRun(r, content)); + const pick = + blocks.find((b) => b.recognized && b.cols.result >= 0 && RESULT_HEADER.test(headerKey(b.header[b.cols.result] ?? ""))) ?? + blocks.find((b) => b.recognized) ?? + blocks[0]; + return pick; +} - const cells = splitTableRow(trimmed) ?? []; - if (cells.length < 1) continue; +// ── Parsing ───────────────────────────────────────────────────────────────── - // First real row is the header — skip it - if (!headerParsed) { - headerParsed = true; - continue; +const LEGACY_ROLLER_LINK = /\[[^\]\n]*\]\(obsidian:\/\/duckmage-roll\?[^)\n]*\)/; +const ROLLER_BLOCK = /```duckmage-roller[\s\S]*?```/; + +/** Parse a random-table note into a RandomTable (see parseRandomTableWithReport). */ +export function parseRandomTable(content: string, opts: ParseOptions = {}): RandomTable { + return parseRandomTableWithReport(content, opts).table; +} + +export interface ParseOptions { + /** Read the table under this heading (a `[[Note#Heading]]` link) instead of the note's roll table. */ + heading?: string; +} + +/** A frontmatter value with outer quotes taken off. */ +function fmValue(body: string, key: string): string | undefined { + const m = new RegExp(`^${key}:[ \\t]*(.*?)[ \\t]*\\r?$`, "m").exec(body); + if (!m) return undefined; + const raw = m[1].trim(); + return /^"(.*)"$/.exec(raw)?.[1] ?? /^'(.*)'$/.exec(raw)?.[1] ?? raw; +} + +/** "3", "3.5", ".5", "50%" → a weight ≥ 0; NaN when unreadable. */ +export function readTableWeight(raw: string): number { + const t = raw.trim(); + if (!/^(?:\d+(?:\.\d*)?|\.\d+)\s*%?$/.test(t)) return NaN; + const n = Number(t.replace(/\s*%$/, "")); + return t.endsWith("%") ? n / 100 : n; +} + +const ROLL_WORDS: Record = { + now: "now", "": "now", generate: "now", "on generate": "now", + "on arrival": "on arrival", arrival: "on arrival", "on visit": "on arrival", visit: "on arrival", later: "on arrival", +}; +const ONCE_WORDS: Record = { + "": undefined, no: undefined, never: undefined, + "per world": "world", world: "world", "once per world": "world", yes: "world", + "per map": "map", map: "map", "once per map": "map", +}; + +/** + * Parse a random-table note and report anything that couldn't be read. + * Nothing the human typed is dropped: an unreadable weight counts as 1 and + * its text is kept in the note; unreadable ranges make the table roll by + * weight. See TableIssueCode for what's reported. + */ +export function parseRandomTableWithReport(content: string, opts: ParseOptions = {}): TableReport { + const issues: TableIssue[] = []; + let dice = 0; + let linkedFolder: string | undefined; + let rows: RowType | undefined; + let terrainTypes: string[] | undefined; + let shownAs: string | undefined; + let pick: "each" | undefined; + const fm = frontmatterOf(content); + let fmDice = 0; + if (fm) { + const diceMatch = /^dice:[ \t]*(.*?)[ \t]*$/m.exec(fm.body); + if (diceMatch) fmDice = parseDie(diceMatch[1]); + const lf = fmValue(fm.body, "linkedFolder") ?? fmValue(fm.body, "linked-folder"); + if (lf !== undefined && lf !== "") { + const wikiLinkMatch = /^\[\[(.+?)\]\]$/.exec(lf); + linkedFolder = wikiLinkMatch ? wikiLinkMatch[1].trim() : lf; + } + const rowsRaw = fmValue(fm.body, "rows"); + if (rowsRaw !== undefined && rowsRaw !== "") { + const r = rowsRaw.toLowerCase().replace(/s$/, "") as RowType; + if (ROW_TYPES.includes(r)) { + if (r !== "any") rows = r; + } else { + issues.push({ code: "rows-unknown", message: `"rows: ${rowsRaw}" isn't one of ${ROW_TYPES.join(", ")}; reading the rows as any.` }); + } + } + const tt = fmValue(fm.body, "terrain-type"); + if (tt) terrainTypes = tt.replace(/^\[|\]$/g, "").split(/\s*,\s*/).map((s) => s.trim().toLowerCase()).filter((s) => s !== ""); + const sa = fmValue(fm.body, "shown-as"); + if (sa) shownAs = sa; + const pk = fmValue(fm.body, "pick"); + if (pk && /^(?:each|every|all|each row)$/i.test(pk)) pick = "each"; + else if (pk && !/^(?:one|weight|weighted)$/i.test(pk)) issues.push({ code: "pick-unknown", message: `"pick: ${pk}" should be each or one; rolling one row.` }); + } + dice = fmDice; + + const heading = opts.heading?.trim() ? opts.heading.trim() : undefined; + const block = locateRollTable(content, heading); + + // Description: text between frontmatter (or the heading) and the table, minus the roller. + const section = heading ? headingSection(content, heading) : null; + const afterFmStart = section ? section.start : fm ? fm.length : 0; + const preambleEnd = block ? block.start : afterFmStart; + const preambleText = preambleEnd > afterFmStart ? content.slice(afterFmStart, preambleEnd) : ""; + const descriptionRaw = preambleText + .replace(new RegExp(LEGACY_ROLLER_LINK.source, "g"), "") + .replace(new RegExp(ROLLER_BLOCK.source, "g"), "") + .replace(/\r\n/g, "\n") + .trim(); + const description = descriptionRaw || undefined; + if (LEGACY_ROLLER_LINK.test(content)) { + issues.push({ code: "legacy-roller-link", message: "Has an old \"Open in Duckmage Roller\" link; it can be replaced by the roller block." }); + } + + const extras = (t: RandomTable): RandomTable => { + if (rows) t.rows = rows; + if (terrainTypes?.length) t.terrainTypes = terrainTypes; + if (shownAs) t.shownAs = shownAs; + if (pick) t.pick = pick; + return t; + }; + + if (!block) { + if (heading && !section) issues.push({ code: "heading-missing", message: `No heading "${heading}".` }); + issues.push({ code: "no-table", message: heading ? `No table under "${heading}".` : "No table found." }); + return { table: extras({ dice, entries: [], linkedFolder, description }), issues, block }; + } + + const { cols } = block; + if (block.recognized && cols.result >= 0 && !RESULT_HEADER.test(headerKey(block.header[cols.result] ?? ""))) { + issues.push({ code: "result-column-guessed", message: `No "Result" column; reading "${block.header[cols.result] ?? ""}" as the result.` }); + } + if (cols.range >= 0) { + const headerDie = parseDie(headerKey(block.header[cols.range] ?? "").replace(/^#$/, "")); + if (headerDie > 0 && fmDice === 0) { + dice = headerDie; + issues.push({ code: "die-from-header", message: `No "dice:" in the frontmatter; using the column header (${dieLabel(headerDie)}).` }); + } else if (headerDie > 0 && fmDice > 0 && headerDie !== fmDice) { + issues.push({ code: "die-mismatch", message: `The frontmatter says ${dieLabel(fmDice)} but the column header says ${dieLabel(headerDie)}; using ${dieLabel(fmDice)}.` }); } + } + const entries: RandomTableEntry[] = []; + const info: RowInfo[] = []; + block.rows.forEach((lineIdx, rowIdx) => { + const cells = rowCells(block.lines[lineIdx]); // Strip wiki-link syntax so [[Note Name]] → "Note Name" - const rawResult = cells[0] ?? ""; + const rawResult = cols.result >= 0 ? (cells[cols.result] ?? "") : ""; const linkMatch = /^\[\[(.+?)(?:\|[^\]]+)?\]\]$/.exec(rawResult); const result = linkMatch ? linkMatch[1] : rawResult; + if (!result) return; const isLink = linkMatch !== null && !linkedFolder; // linkedFolder entries already tracked separately - const rawWeight = cells[1] ?? "1"; - const weight = Math.max(1, parseInt(rawWeight, 10) || 1); - if (result) - entries.push({ result, weight, ...(isLink ? { isLink: true } : {}) }); + const entry: RandomTableEntry = { result, weight: 1, ...(isLink ? { isLink: true } : {}) }; + const rangeText = cols.range >= 0 ? (cells[cols.range] ?? "").trim() : ""; + if (rangeText) entry.range = rangeText; + if (cols.weight >= 0) { + const w = (cells[cols.weight] ?? "").trim(); + const n = w ? readTableWeight(w) : NaN; + if (Number.isFinite(n)) entry.weight = n; + else if (w) { + issues.push({ code: "weight-unreadable", row: entries.length + 1, message: `Row ${entries.length + 1} ("${result}"): weight "${w}" isn't a number; counting it as 1.` }); + } + } + info.push(readExtras(result, block.extra.map((i): [string, string] => [block.header[i].trim(), (cells[i] ?? "").trim()]), entries.length + 1, issues, pick === "each")); + entries.push(entry); + block.entryRows.push(rowIdx); + }); + + // No weight column: each row weighs what its range covers. + if (cols.weight < 0 && dice > 0) { + for (const e of entries) { + if (e.range === undefined) continue; + const p = parseRangeCell(e.range, dice); + if (p === "none") e.weight = 0; + else if (p && !p.outside) e.weight = p.faces.length; + } + } + + const table: RandomTable = extras({ dice, entries, linkedFolder, description }); + if (info.some((i) => Object.keys(i).length)) table.rowInfo = info; + issues.push(...resolveTable(table).issues); + return { table, issues, block }; +} + +/** A row's other columns: attributes, and the shared Roll / Shown as / Once / When. */ +function readExtras(result: string, cells: [string, string][], rowNo: number, issues: TableIssue[], each = false): RowInfo { + const entry: RowInfo = {}; + const name = `Row ${rowNo} ("${result}")`; + for (const [header, cell] of cells) { + if (!cell) continue; + (entry.attrs ??= {})[header] = cell; + const key = headerKey(header); + if (key === "roll") { + const r = ROLL_WORDS[cell.toLowerCase()]; + if (r) { + if (r !== "now") entry.roll = r; + } else { + issues.push({ code: "roll-unknown", row: rowNo, message: `${name}: Roll "${cell}" should be now or on arrival; rolling it now.` }); + } + } else if (key === "shown as") { + entry.shownAs = cell; + } else if (key === "once") { + const k = cell.toLowerCase(); + if (k in ONCE_WORDS) { + const o = ONCE_WORDS[k]; + if (o) entry.once = o; + } else { + issues.push({ code: "once-unknown", row: rowNo, message: `${name}: Once "${cell}" should be per world or per map; the row can repeat.` }); + } + } else if (key === "chance" && each) { + const c = readChance(cell); + if (c !== undefined) entry.chance = c; + else issues.push({ code: "chance-unknown", row: rowNo, message: `${name}: can't read Chance "${cell}" (like always, 1 in 2 or 60%), so the row never comes up.` }); + } else if (key === "when") { + const when = parseWhen(cell); + if (when.length) entry.when = when; + const bad = unreadableConditions(when); + if (bad.length) issues.push({ code: "when-unknown", row: rowNo, message: `${name}: can't read When "${bad.join("; ")}", so the row never comes up.` }); + } + } + return entry; +} + +/** + * A Chance cell (`pick: each` tables) → 0..1: `always`/`yes` 1, `never`/`no` + * 0, `1 in 2` or `1/2`, `60%`, or a fraction like `0.6`. Undefined when it + * can't be read. + */ +export function readChance(raw: string): number | undefined { + const t = raw.trim().toLowerCase(); + if (/^(?:always|yes|every time)$/.test(t)) return 1; + if (/^(?:never|no)$/.test(t)) return 0; + const inM = /^(\d+(?:\.\d+)?)\s*(?:in|\/|out of)\s*(\d+(?:\.\d+)?)$/.exec(t); + if (inM) { + const n = Number(inM[1]), d = Number(inM[2]); + return d > 0 && n <= d ? n / d : undefined; + } + const pct = /^(\d+(?:\.\d+)?)\s*%$/.exec(t); + if (pct) return Number(pct[1]) <= 100 ? Number(pct[1]) / 100 : undefined; + if (/^(?:0|1|0?\.\d+)$/.test(t)) return Number(t); + return undefined; +} + +// ── Ranges ────────────────────────────────────────────────────────────────── + +/** + * Read one range cell: `1–6`, `7-8`, `9`, `10, 12`, `19+`, d100 `01–05` and + * `00` (= 100), d10 `0` (= 10), `—` (never rolled). null when unreadable; + * `outside` when a number isn't on the die. + */ +export function parseRangeCell(text: string, dice: number): { faces: number[]; outside: boolean } | "none" | null { + const t = text.trim(); + if (!t || /^[—–-]+$/.test(t) || /^(?:none|n\/a)$/i.test(t)) return "none"; + const faces = dieFaces(dice); + if (!faces.length) return null; + const max = faces[faces.length - 1]; + const num = (s: string): number => { + const n = parseInt(s, 10); + if (dice === 100 && n === 0) return 100; + if (dice === 10 && n === 0) return 10; + return n; + }; + const out: number[] = []; + let outside = false; + for (const part of t.split(/\s*[,;]\s*/)) { + let lo: number, hi: number; + let m: RegExpExecArray | null; + if ((m = /^(\d+)\s*(?:[–—-]|to|\.\.)\s*(\d+)$/i.exec(part))) { + lo = num(m[1]); + hi = num(m[2]); + } else if ((m = /^(\d+)\s*\+$/.exec(part))) { + lo = num(m[1]); + hi = max; + } else if ((m = /^(\d+)$/.exec(part))) { + lo = hi = num(m[1]); + } else return null; + if (lo > hi) return null; + if (!faces.includes(lo) || !faces.includes(hi)) outside = true; + for (const f of faces) if (f >= lo && f <= hi && !out.includes(f)) out.push(f); } + return { faces: out, outside }; +} - return { dice, entries, linkedFolder, description }; +/** "3–5", "7", or "3–5, 9" for faces that aren't one run (in die order). */ +export function facesLabel(faces: number[], dice: number): string { + if (!faces.length) return "—"; + const all = dieFaces(dice); + const idx = faces.map((f) => all.indexOf(f)).sort((a, b) => a - b); + const parts: string[] = []; + let a = idx[0]; + let b = idx[0]; + const push = () => parts.push(a === b ? String(all[a]) : `${all[a]}–${all[b]}`); + for (let i = 1; i < idx.length; i++) { + if (idx[i] === b + 1) b = idx[i]; + else { + push(); + a = b = idx[i]; + } + } + push(); + return parts.join(", "); +} + +/** + * How many faces each row gets on a die with `faceCount` faces, by + * largest remainder. Never more than faceCount in total. Weight 0 gets 0; + * every other row gets at least 1. When there are more weighted rows than + * faces, the first faceCount of them get 1 and the rest get 0. + */ +export function allocateFaces(weights: number[], faceCount: number): number[] { + const counts = weights.map(() => 0); + const live = weights.map((w, i) => (w > 0 ? i : -1)).filter((i) => i >= 0); + if (!live.length || faceCount <= 0) return counts; + if (live.length > faceCount) { + for (const i of live.slice(0, faceCount)) counts[i] = 1; + return counts; + } + const total = live.reduce((s, i) => s + weights[i], 0); + const quota = weights.map((w) => (w > 0 ? (w / total) * faceCount : 0)); + for (const i of live) counts[i] = Math.max(1, Math.floor(quota[i])); + let used = live.reduce((s, i) => s + counts[i], 0); + while (used > faceCount) { + // Take back from the row most over its share (that can spare one). + let best = -1; + for (const i of live) { + if (counts[i] <= 1) continue; + if (best < 0 || counts[i] - quota[i] >= counts[best] - quota[best]) best = i; + } + if (best < 0) break; + counts[best]--; + used--; + } + while (used < faceCount) { + // Give to the row most under its share. + let best = live[0]; + for (const i of live) if (quota[i] - counts[i] > quota[best] - counts[best]) best = i; + counts[best]++; + used++; + } + return counts; } /** - * Return any content that appears after the markdown table in a random table file. - * Finds the last line starting with `|`, then returns everything after it (leading - * blank lines stripped). Returns "" if nothing follows the table. + * Die ranges worked out from the weights alone (ignoring stored ranges), as + * a parallel array of labels. Never past the die: weight 0 and rows that + * don't fit get "—". */ -export function extractPostTableContent(content: string): string { - const tableHeaderMatch = /\| Result \| Weight \|/m.exec(content); - if (!tableHeaderMatch) return ""; - const afterHeader = content.slice(tableHeaderMatch.index); - const lines = afterHeader.split("\n"); - let lastPipeIdx = -1; - for (let i = 0; i < lines.length; i++) { - if (lines[i].trimStart().startsWith("|")) lastPipeIdx = i; +export function getDieRanges(table: RandomTable): string[] { + const n = table.entries.length; + if (n === 0) return []; + const faces = dieFaces(table.dice); + const counts = allocateFaces(table.entries.map((e) => e.weight), faces.length); + const labels: string[] = []; + let cursor = 0; + for (const c of counts) { + labels.push(c ? facesLabel(faces.slice(cursor, cursor + c), table.dice) : "—"); + cursor += c; } - if (lastPipeIdx === -1) return ""; - return lines - .slice(lastPipeIdx + 1) - .join("\n") - .replace(/^\n+/, ""); + return labels; +} + +export interface ResolvedTable { + /** "ranges": roll the die and read the row; "weight": weighted pick. */ + mode: "ranges" | "weight"; + /** Per entry: the range to show (as typed when stored), "—" for never. Empty strings when there's no die. */ + labels: string[]; + /** Per entry: the faces it covers (empty in weight mode or for "—"). */ + faces: number[][]; + /** Every face that lands on a row (ranges mode). */ + covered: number[]; + issues: TableIssue[]; } +/** + * Work out what each row rolls on. Stored ranges are used as typed; blank + * ones are filled from the weights over the faces left. If any stored range + * can't be used, or the rows don't fit the die, the table rolls by weight. + */ +export function resolveTable(table: RandomTable): ResolvedTable { + const n = table.entries.length; + const all = dieFaces(table.dice); + if (!all.length) { + return { mode: "weight", labels: table.entries.map(() => ""), faces: table.entries.map(() => []), covered: [], issues: [] }; + } + const issues: TableIssue[] = []; + const faces: number[][] = table.entries.map(() => []); + const labels: string[] = table.entries.map(() => "—"); + const owner = new Map(); + const pending: number[] = []; + const stored: number[] = []; + let broken = false; + const name = (i: number) => `Row ${i + 1} ("${table.entries[i].result}")`; + + table.entries.forEach((e, i) => { + if (e.range === undefined || !e.range.trim()) { + pending.push(i); + return; + } + labels[i] = e.range.trim(); + const p = parseRangeCell(e.range, table.dice); + if (p === "none") { + stored.push(i); + return; + } + if (!p) { + issues.push({ code: "range-unreadable", row: i + 1, message: `${name(i)}: can't read the range "${e.range.trim()}".` }); + broken = true; + return; + } + if (p.outside) { + issues.push({ code: "range-out-of-die", row: i + 1, message: `${name(i)}: "${e.range.trim()}" goes past the ${dieLabel(table.dice)}.` }); + broken = true; + return; + } + stored.push(i); + for (const f of p.faces) { + const prev = owner.get(f); + if (prev !== undefined) { + issues.push({ code: "range-overlap", row: i + 1, message: `${name(i)} and row ${prev + 1} both cover ${f}.` }); + broken = true; + } else owner.set(f, i); + } + faces[i] = p.faces; + }); + + // Blank cells: fill from the weights over the faces nobody claimed. + const remaining = all.filter((f) => !owner.has(f)); + const counts = allocateFaces(pending.map((i) => table.entries[i].weight), remaining.length); + const livePending = pending.filter((i) => table.entries[i].weight > 0); + let cursor = 0; + pending.forEach((i, k) => { + const c = counts[k]; + faces[i] = remaining.slice(cursor, cursor + c); + cursor += c; + labels[i] = c ? facesLabel(faces[i], table.dice) : "—"; + }); + if (livePending.length > remaining.length) { + const unfit = livePending.length - remaining.length; + issues.push({ + code: "too-many-rows", + message: `${n} rows don't fit on a ${dieLabel(table.dice)}: ${unfit} row${unfit === 1 ? "" : "s"} can't get a number. It rolls by weight until the die is bigger.`, + }); + broken = true; + } + + if (broken) return { mode: "weight", labels, faces: table.entries.map(() => []), covered: [], issues }; + + const covered = all.filter((f) => faces.some((fs) => fs.includes(f))); + if (covered.length && covered.length < all.length) { + const gaps = all.filter((f) => !covered.includes(f)); + issues.push({ code: "range-gap", message: `No row covers ${facesLabel(gaps, table.dice)} on the ${dieLabel(table.dice)}; those rolls are rolled again.` }); + } + if (stored.length) { + const expected = allocateFaces(table.entries.map((e) => e.weight), all.length); + const off = stored.filter((i) => expected[i] !== faces[i].length); + if (off.length) { + issues.push({ + code: "range-weight-mismatch", + message: `The ranges and weights disagree (${off.slice(0, 3).map((i) => `"${table.entries[i].result}" covers ${faces[i].length} but weighs ${table.entries[i].weight}`).join("; ")}${off.length > 3 ? "; …" : ""}). Rolls follow the ranges.`, + }); + } + } + if (!covered.length) return { mode: "weight", labels, faces, covered, issues }; + return { mode: "ranges", labels, faces, covered, issues }; +} + +/** Per-entry odds as "25%", following how the table actually rolls. */ +export function rowOdds(table: RandomTable, resolved: ResolvedTable = resolveTable(table)): string[] { + if (resolved.mode === "ranges") { + return resolved.faces.map((f) => `${Math.round((f.length / resolved.covered.length) * 100)}%`); + } + const total = table.entries.reduce((s, e) => s + Math.max(0, e.weight), 0); + return table.entries.map((e) => (total > 0 ? `${Math.round((Math.max(0, e.weight) / total) * 100)}%` : "–")); +} + +// ── Rolling ───────────────────────────────────────────────────────────────── + +export interface RollOutcome { + entry: RandomTableEntry; + /** Index of the entry in table.entries. */ + index: number; + /** The die face rolled, when the table rolls by its ranges. */ + face?: number; +} + +/** + * Roll the table. With a die and usable ranges, rolls the die and returns + * the row whose range holds the face (what you see is what you get); + * otherwise a weighted pick. Weight-0 rows are never picked. + */ +export function rollTable(table: RandomTable, rng: () => number = Math.random): RollOutcome | null { + if (table.entries.length === 0) return null; + const resolved = resolveTable(table); + if (resolved.mode === "ranges") { + const face = resolved.covered[Math.min(resolved.covered.length - 1, Math.floor(rng() * resolved.covered.length))]; + const index = resolved.faces.findIndex((f) => f.includes(face)); + if (index >= 0) return { entry: table.entries[index], index, face }; + } + const live = table.entries.map((e, i) => ({ e, i })).filter(({ e }) => e.weight > 0); + if (!live.length) return null; + const total = live.reduce((s, { e }) => s + e.weight, 0); + let rand = rng() * total; + for (const { e, i } of live) { + rand -= e.weight; + if (rand < 0) return { entry: e, index: i }; + } + const last = live[live.length - 1]; + return { entry: last.e, index: last.i }; +} + +/** Weighted random selection (see rollTable). Returns a random entry. */ +export function rollOnTable(table: RandomTable): RandomTableEntry | null { + return rollTable(table)?.entry ?? null; +} + +/** "d20 → 14" for a roll by ranges, "" for a weighted pick. */ +export function rollLabel(table: RandomTable, outcome: RollOutcome): string { + return outcome.face !== undefined ? `${dieLabel(table.dice)} → ${outcome.face}` : ""; +} + +/** Return "25%" or "1–4" die range label for a single entry. */ +export function getOddsLabel( + entry: RandomTableEntry, + table: RandomTable, +): string { + const total = table.entries.reduce((s, e) => s + e.weight, 0); + if (total === 0) return "–"; + if (table.dice <= 0) { + return `${Math.round((entry.weight / total) * 100)}%`; + } + return ""; // caller uses getDieRanges for full table +} + +// ── Other readers ─────────────────────────────────────────────────────────── + /** * Extract entries from markdown content. * Primary: bullet/numbered list items (strips task-list markers). @@ -122,9 +942,9 @@ export function parseMarkdownListItems(content: string): string[] { if (results.length > 0) return results; // Fallback: plain line-per-entry files (e.g. a word list) - const noFm = content.replace(/^---\n[\s\S]*?\n---\n?/, ""); + const noFm = content.replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n?/, ""); let inFence = false; - for (const line of noFm.split("\n")) { + for (const line of noFm.split(/\r?\n/)) { const t = line.trim(); if (t.startsWith("```")) { inFence = !inFence; continue; } if (inFence || !t) continue; @@ -134,90 +954,37 @@ export function parseMarkdownListItems(content: string): string[] { return results; } -/** Weighted random selection. Returns a random entry. */ -export function rollOnTable(table: RandomTable): RandomTableEntry | null { - if (table.entries.length === 0) return null; - const total = table.entries.reduce((s, e) => s + e.weight, 0); - let rand = Math.random() * total; - for (const entry of table.entries) { - rand -= entry.weight; - if (rand <= 0) return entry; - } - return table.entries[table.entries.length - 1]; -} - -/** Return "25%" or "1–4" die range label for a single entry. */ -export function getOddsLabel( - entry: RandomTableEntry, - table: RandomTable, -): string { - const total = table.entries.reduce((s, e) => s + e.weight, 0); - if (total === 0) return "–"; - if (table.dice <= 0) { - return `${Math.round((entry.weight / total) * 100)}%`; - } - return ""; // caller uses getDieRanges for full table -} - /** - * Compute die ranges for every entry and return them as a parallel array. - * Each entry gets at least 1 die face; extras go to the heaviest entries first. + * What to tell the user when a table has nothing to roll (parseRandomTable + * found no entries). Setup creates terrain tables with an empty row, so the + * usual case is "not filled in yet", not a broken format (fresh-eyes E6: the + * old "Check the table format." read as if the user had broken something). */ -export function getDieRanges(table: RandomTable): string[] { - const n = table.entries.length; - if (n === 0) return []; - const total = table.entries.reduce((s, e) => s + e.weight, 0); - const faces = table.dice; - - // Allocate proportionally, floor each - const floored = table.entries.map((e) => - Math.max(1, Math.floor((e.weight / total) * faces)), - ); - let used = floored.reduce((s, v) => s + v, 0); - - // Distribute remaining faces by fractional remainder, largest first - if (used < faces) { - const remainders = table.entries - .map((e, i) => ({ - i, - r: (e.weight / total) * faces - floored[i], - })) - .sort((a, b) => b.r - a.r); - for (const { i } of remainders) { - if (used >= faces) break; - floored[i]++; - used++; - } - } - - // Build range strings - const ranges: string[] = []; - let cursor = 1; - for (const count of floored) { - const from = cursor; - const to = cursor + count - 1; - ranges.push(from === to ? String(from) : `${from}–${to}`); - cursor = to + 1; - } - return ranges; +export function emptyTableMessage(content: string): string { + return locateRollTable(content) + ? "This table has no entries yet. Add some results to roll on it." + : "This note has no table to roll on yet. Add some entries to start one."; } +// ── Writing ───────────────────────────────────────────────────────────────── + /** Update the `dice` value in a table file's YAML frontmatter. */ export function setDiceInFrontmatter(content: string, dice: number): string { - const fmRegex = /^(---\s*\n)([\s\S]*?)(\n---)/; + const fmRegex = /^(---[ \t]*\r?\n)([\s\S]*?)(\r?\n---)/; const diceLine = dice > 0 ? `dice: ${dice}` : ""; const match = fmRegex.exec(content); if (match) { + const eol = match[1].endsWith("\r\n") ? "\r\n" : "\n"; const existingFm = match[2]; - const hasDiceLine = /^dice:\s*\d*/m.test(existingFm); + const hasDiceLine = /^dice:/m.test(existingFm); let newFm: string; if (hasDiceLine) { newFm = diceLine - ? existingFm.replace(/^dice:\s*\d*/m, diceLine) - : existingFm.replace(/^dice:\s*\d*\n?/m, ""); + ? existingFm.replace(/^dice:[^\r\n]*/m, diceLine) + : existingFm.replace(/^dice:[^\r\n]*(?:\r?\n)?/m, ""); } else { - newFm = diceLine ? existingFm.trimEnd() + "\n" + diceLine : existingFm; + newFm = diceLine ? existingFm.trimEnd() + eol + diceLine : existingFm; } return ( content.slice(0, match.index) + @@ -233,3 +1000,294 @@ export function setDiceInFrontmatter(content: string, dice: number): string { } return content; } + +/** One row to write: an entry, and which parsed entry it came from (if any). */ +export interface TableRowWrite { + entry: RandomTableEntry; + /** Index into the parsed table's entries this row was read from. */ + source?: number; +} + +export interface TableWrite { + rows: TableRowWrite[]; + /** The die the table is written for. */ + dice: number; + /** + * "untouched": range cells are left as they are (no column is added). + * "keep": stored ranges stay; blank ones are filled from the weights; a + * die column is added when missing. + * "regenerate": every range is worked out from the weights. + */ + ranges: "untouched" | "keep" | "regenerate"; + /** Write results as [[links]] (linked-folder tables). */ + linkCells?: boolean; + /** Drop rows with no result and nothing in other columns (template rows). */ + dropPlaceholders?: boolean; +} + +/** + * The text to write in each row's range cell. "keep": stored ranges as + * typed, blank ones filled from the weights; "regenerate": all from the + * weights. Rows that don't fit the die stay blank (shown as "—"), so the + * table keeps rolling by weight until the die is bigger. + */ +export function rangeCellTexts(dice: number, entries: RandomTableEntry[], mode: "keep" | "regenerate"): string[] { + const faces = dieFaces(dice).length; + if (mode === "regenerate") { + const fits = entries.filter((e) => e.weight > 0).length <= faces; + return fits ? getDieRanges({ dice, entries }) : entries.map((e) => (e.weight > 0 ? "" : "—")); + } + const resolved = resolveTable({ dice, entries }); + const overflow = resolved.issues.some((i) => i.code === "too-many-rows"); + return entries.map((e, i) => + e.range !== undefined && e.range.trim() ? e.range.trim() : overflow && e.weight > 0 ? "" : resolved.labels[i], + ); +} + +function escapeCell(s: string): string { + return s.replace(/\\?\|/g, "\\|"); +} + +/** Replace cell contents in a row, leaving every other byte alone. */ +function setCells(line: string, edits: Map): string { + if (!edits.size) return line; + let spans = cellSpans(line); + let out = line; + const maxCol = Math.max(...edits.keys()); + if (maxCol >= spans.length) { + // Pad the row with empty cells up to the column being written. + const trimmed = out.replace(/\s+$/, ""); + const hasTrailingPipe = trimmed.endsWith("|") && spans.length > 0 && spans[spans.length - 1].end < trimmed.length; + let tail = hasTrailingPipe ? trimmed : trimmed + " |"; + for (let c = spans.length; c <= maxCol; c++) tail += " |"; + out = tail; + spans = cellSpans(out); + } + for (const col of [...edits.keys()].sort((a, b) => b - a)) { + const s = spans[col]; + out = out.slice(0, s.start) + ` ${edits.get(col) ?? ""} ` + out.slice(s.end); + } + return out; +} + +function prependCell(line: string, text: string): string { + const i = line.indexOf("|"); + return line.slice(0, i) + `| ${text} ` + line.slice(i); +} + +/** Text for an entry's result cell. */ +function resultCell(entry: RandomTableEntry, linkCells: boolean): string { + return escapeCell(linkCells || entry.isLink ? `[[${entry.result}]]` : entry.result); +} + +/** + * Write the roll table back into `content`, replacing only the table's own + * lines. Text before and after it stays byte for byte. Rows that came from + * the note keep their raw text (extra columns, `[[x|alias]]`, spacing); + * only cells whose value changed are rewritten. With no table in the note, + * one is added at the end. + */ +export function writeRollTable(content: string, write: TableWrite): string { + const parsed = parseRandomTableWithReport(content); + const block = parsed.block; + const dice = write.dice; + const entries = write.rows.map((r) => r.entry); + const linkCells = write.linkCells ?? false; + + // Range text per row (null = leave range cells alone). + const labels = write.ranges !== "untouched" && dice > 0 ? rangeCellTexts(dice, entries, write.ranges) : null; + + if (!block) { + const eol = content.includes("\r\n") ? "\r\n" : "\n"; + const head = labels ? [dieLabel(dice), "Result", "Weight"] : ["Result", "Weight"]; + const lines = [`| ${head.join(" | ")} |`, `|${head.map((h) => "-".repeat(Math.max(3, h.length + 2))).join("|")}|`]; + write.rows.forEach((r, i) => { + const cells = [resultCell(r.entry, linkCells), String(r.entry.weight)]; + if (labels) cells.unshift(labels[i]); + lines.push(`| ${cells.join(" | ")} |`); + }); + const sep = !content ? "" : content.endsWith(eol + eol) ? "" : content.endsWith(eol) ? eol : eol + eol; + return content + sep + lines.join(eol) + eol; + } + + const { cols } = block; + const origEntries = parsed.table.entries; + const addRange = labels !== null && cols.range < 0; + const addWeight = + cols.weight < 0 && + write.rows.some((r) => r.source === undefined || r.entry.weight !== origEntries[r.source]?.weight); + const shift = addRange ? 1 : 0; + const rangeCol = addRange ? 0 : cols.range; + const resultCol = cols.result + shift; + const weightCol = addWeight ? block.header.length + shift : cols.weight >= 0 ? cols.weight + shift : -1; + const width = Math.max(block.header.length + shift + (addWeight ? 1 : 0), resultCol + 1, weightCol + 1); + + /** Add the new columns to a line from the note. */ + const widen = (line: string, rangeText: string, weightText: string): string => { + let l = addRange ? prependCell(line, rangeText) : line; + if (addWeight) l = setCells(l, new Map([[weightCol, weightText]])); + return l; + }; + + const out: string[] = []; + let header = block.lines[0]; + if (labels && cols.range >= 0 && headerKey(block.header[cols.range] ?? "") !== dieLabel(dice)) { + header = setCells(header, new Map([[cols.range, dieLabel(dice)]])); + } else if (dice <= 0 && write.ranges !== "untouched" && cols.range >= 0 && parseDie(headerKey(block.header[cols.range] ?? "")) > 0) { + // No die any more: the column stays (nothing typed is lost) but stops naming one. + header = setCells(header, new Map([[cols.range, "Roll"]])); + } + out.push(widen(header, dieLabel(dice), "Weight")); + if (block.separator >= 0) { + let sep = block.lines[block.separator]; + if (addRange) { + const i = sep.indexOf("|"); + sep = sep.slice(0, i) + "|-----" + sep.slice(i); + } + if (addWeight) { + const t = sep.replace(/\s+$/, ""); + sep = t.endsWith("|") ? t + "--------|" : t + "|--------"; + } + out.push(sep); + } else { + out.push(`|${Array.from({ length: width }, () => "---").join("|")}|`); + } + + const indent = /^\s*/.exec(block.lines[0])?.[0] ?? ""; + const rowLines: string[] = []; + write.rows.forEach((r, i) => { + const rangeText = labels ? labels[i] : ""; + const weightText = String(r.entry.weight); + const rowIdx = r.source !== undefined ? block.entryRows[r.source] : undefined; + if (rowIdx !== undefined) { + const orig = origEntries[r.source as number]; + const edits = new Map(); + if (orig.result !== r.entry.result || !!orig.isLink !== !!r.entry.isLink) { + edits.set(cols.result, resultCell(r.entry, linkCells)); + } + if (cols.weight >= 0 && orig.weight !== r.entry.weight) edits.set(cols.weight, weightText); + if (labels && cols.range >= 0 && (orig.range ?? "") !== rangeText) edits.set(cols.range, rangeText); + rowLines.push(widen(setCells(block.lines[block.rows[rowIdx]], edits), rangeText, weightText)); + } else { + const cells = Array.from({ length: width }, () => ""); + cells[resultCol] = resultCell(r.entry, linkCells); + if (weightCol >= 0) cells[weightCol] = weightText; + if (rangeCol >= 0) cells[rangeCol] = rangeText; + rowLines.push(`${indent}| ${cells.join(" | ")} |`); + } + }); + + // Rows that aren't entries (no result) stay where they were, unless + // they're empty template rows and the caller drops those. + const used = new Set(block.entryRows); + let kept = 0; + block.rows.forEach((lineIdx, rowIdx) => { + if (used.has(rowIdx)) return; + const line = block.lines[lineIdx]; + const cells = rowCells(line); + const extra = cells.some((c, ci) => c && ci !== cols.weight && ci !== cols.range); + if (write.dropPlaceholders && !extra) return; + const before = block.entryRows.filter((er) => er < rowIdx).length; + rowLines.splice(Math.min(before + kept, rowLines.length), 0, widen(line, "", cols.weight >= 0 ? (cells[cols.weight] ?? "") : "")); + kept++; + }); + + out.push(...rowLines); + return content.slice(0, block.start) + out.join(block.eol) + content.slice(block.end); +} + +/** + * True when the table's stored ranges (if any) are all usable and agree + * with its weights, so redoing them from the weights loses nothing typed + * by hand. + */ +export function rangesFollowWeights(table: RandomTable): boolean { + if (!table.entries.some((e) => e.range !== undefined)) return true; + const { mode, issues } = resolveTable(table); + return mode === "ranges" && !issues.some((i) => i.code === "range-weight-mismatch" || i.code === "range-gap"); +} + +/** How automatic edits (linked-folder sync) write ranges. */ +export function autoRangeMode(table: RandomTable): TableWrite["ranges"] { + return rangesFollowWeights(table) ? "regenerate" : "keep"; +} + +/** + * Bring a linked-folder table in line with its folder's notes: rows for new + * notes are added (weight 1); a renamed note renames its row in place + * (keeping its weight); a deleted or retired (`_`) note removes its row. + * Other rows whose note is missing are kept (and reported elsewhere). + * Returns the content unchanged when there's nothing to do. + */ +export function syncLinkedRows( + content: string, + noteNames: string[], + change?: { removed?: string; renamed?: [string, string] }, +): string { + const { table, block } = parseRandomTableWithReport(content); + if (!table.linkedFolder) return content; + let rows: TableRowWrite[] = table.entries.map((entry, source) => ({ entry, source })); + let changed = false; + const removed = change?.removed ?? (change?.renamed && change.renamed[1].startsWith("_") ? change.renamed[0] : undefined); + if (removed !== undefined) { + const before = rows.length; + rows = rows.filter((r) => r.entry.result !== removed); + changed ||= rows.length !== before; + } else if (change?.renamed) { + const [from, to] = change.renamed; + if (!rows.some((r) => r.entry.result === to)) { + rows = rows.map((r) => (r.entry.result === from ? { ...r, entry: { ...r.entry, result: to } } : r)); + changed ||= rows.some((r) => r.entry.result === to); + } + } + const have = new Set(rows.map((r) => r.entry.result)); + for (const name of [...noteNames].sort((a, b) => a.localeCompare(b))) { + if (name.startsWith("_") || have.has(name)) continue; + rows.push({ entry: { result: name, weight: 1 } }); + have.add(name); + changed = true; + } + if (!changed) return content; + // New cells follow the table's style: [[links]] if its rows are links. + const firstRow = block && block.entryRows.length ? rowCells(block.lines[block.rows[block.entryRows[0]]])[block.cols.result] ?? "" : "[["; + return writeRollTable(content, { + dice: table.dice, + rows, + ranges: autoRangeMode(table), + linkCells: firstRow.startsWith("[["), + dropPlaceholders: true, + }); +} + +/** + * Give a table note the ```duckmage-roller``` block: an old + * "Open in Duckmage Roller" link on its own line is replaced by it (or just + * removed when the block is already there); otherwise the block goes right + * after the frontmatter. Returns the content unchanged when there's nothing + * to do. Links sharing a line with other text are left alone. + */ +export function withRollerBlock(content: string): string { + const eol = content.includes("\r\n") ? "\r\n" : "\n"; + const block = "```duckmage-roller" + eol + "```"; + const hasBlock = ROLLER_BLOCK.test(content); + const lineRe = new RegExp(`^[ \\t]*${LEGACY_ROLLER_LINK.source}[ \\t]*(?=\\r?$)`, "m"); + const m = lineRe.exec(content); + if (m) { + const end = m.index + m[0].length; + if (hasBlock) { + const next = content.startsWith("\r\n", end) ? 2 : content.startsWith("\n", end) ? 1 : 0; + return content.slice(0, m.index) + content.slice(end + next); + } + return content.slice(0, m.index) + block + content.slice(end); + } + if (hasBlock || LEGACY_ROLLER_LINK.test(content)) return content; + const fm = frontmatterOf(content); + const insertAt = fm ? fm.length : 0; + const lead = fm && !/\r?\n$/.test(content.slice(0, insertAt)) ? eol : ""; + return content.slice(0, insertAt) + lead + eol + block + eol + eol + content.slice(insertAt); +} + +/** True when the note has an old obsidian://duckmage-roll link. */ +export function hasLegacyRollerLink(content: string): boolean { + return LEGACY_ROLLER_LINK.test(content); +} diff --git a/src/random-tables/resolve.ts b/src/random-tables/resolve.ts new file mode 100644 index 00000000..ea32850c --- /dev/null +++ b/src/random-tables/resolve.ts @@ -0,0 +1,608 @@ +/** + * One resolver for every table reference (plan-tables-everywhere §2.3): + * roll a random table, follow a row that links another table (nested + * rolls), and say what came out — text, a note, a terrain, a generator, or + * nothing — with the row attributes and the chain of rows taken. + * + * - Seeded: the same seed (or random stream) gives the same chain. + * - Loop guard: a table already on the chain, or a chain deeper than + * `maxDepth` (5), stops with a `loop` result shown as ⟲. + * - When rows (tableConditions.ts) that don't fit the context, rows already + * used (`isUsed`, for Once) and, with `onlyTerrains`, rows that can't be + * a terrain of the palette are left out, and the rest renormalised: the + * hand-roller's "roll again". + * - `odds()` gives the exact distribution `roll()` samples, so a preview + * shows the real odds. + * + * Tables come from a TableLookup, so this file never touches the vault: + * the caller loads the tables (from notes, or from another format through + * an adapter like space/worldTypesSource.ts). + * + * Picker filtering by row type is not done here: tableFitsWant() is the + * seam the pickers call (plan §2.5). + * + * Pure: no Obsidian imports. + */ + +import { mulberry32 } from "../../packages/hex-wfc/src/rng"; +import { conditionsFit, type ConditionContext } from "./tableConditions"; +import type { OnceHit } from "../arrival/eventsLedger"; +import { locateRollTable, parseRandomTable, resolveTable, rollTable, rowInfoOf, type RandomTable, type RandomTableEntry, type RowType } from "./randomTable"; + +/** What a cell turned out to be. */ +export type CellKind = "text" | "note" | "table" | "generator" | "terrain" | "nothing"; + +export interface TableLookup { + /** + * The table a link points at (`Note`, `folder/Note` or `Note#Heading`), + * with a key that names it uniquely (its path; used for the loop guard). + * Undefined when the link isn't a table. + */ + table(link: string): { key: string; table: RandomTable } | undefined; + /** What a link that isn't a table points at. Missing: a note that doesn't exist (yet). */ + kindOf?(link: string): "generator" | "note" | "missing"; +} + +export interface ResolveContext extends ConditionContext { + /** The random stream; else one made from `seed` (else Math.random). */ + rand?: () => number; + seed?: number; + /** The palette's terrain names: plain text naming one is a terrain (the palette's spelling). */ + terrains?: readonly string[]; + /** Only rows that can come out as a terrain (or nothing) count; the rest are left out and reported. */ + onlyTerrains?: boolean; + /** Stop at a row whose Roll is "on arrival" instead of rolling it through. */ + deferArrival?: boolean; + /** Once rows already used (the ledger): those rows are left out. `scope` is the row's Once. */ + isUsed?: (tableKey: string, index: number, entry: RandomTableEntry, scope: "world" | "map") => boolean; + /** Deepest nesting followed (default 5). */ + maxDepth?: number; +} + +export interface ResolveStep { + /** The table's key. */ + table: string; + /** The entry's index in the table. */ + index: number; + result: string; + /** The die face, when the table rolled by its ranges. */ + face?: number; +} + +export interface Resolved { + /** `loop`: stopped by the loop guard; `deferred`: an on-arrival row; `empty`: no row could come up. */ + kind: CellKind | "loop" | "deferred" | "empty"; + /** The text, note link, terrain, generator ref, or (loop / deferred) the table link. */ + value: string; + /** The rows' attributes along the chain (an inner row's cell wins). */ + attrs: Record; + chain: ResolveStep[]; + /** The last Once row on the chain, for the caller's ledger. */ + once?: { table: string; index: number; scope: "world" | "map" }; + /** + * Every Once row on the chain, outermost first, with what it said (for + * the Events ledger, arrival/eventsLedger.ts). Not set for a deferred + * result: nothing has happened yet. + */ + onces?: OnceHit[]; + /** An on-arrival row: what the hex shows until then. */ + shownAs?: string; +} + +export const DEFAULT_MAX_DEPTH = 5; +export const LOOP_MARK = "⟲"; + +const NOTHING = /^\(?nothing\)?$|^\(none\)$/i; + +/** Whether a cell is a (nothing) row. */ +export const isNothing = (text: string): boolean => NOTHING.test(text.trim()); +const GENERATOR_ID = /^(?:procedural|wfc|builtin):\S/; +const lc = (s: string) => s.trim().toLowerCase(); + +/** The link a row's result stands for (a linked-folder row links a note in that folder), or undefined for plain text. */ +export function entryLink(table: RandomTable, entry: RandomTableEntry): string | undefined { + if (table.linkedFolder) return `${table.linkedFolder}/${entry.result}`; + return entry.isLink ? entry.result : undefined; +} + +/** What one cell is (T3: detected from what it links to). */ +export function cellKind(table: RandomTable, entry: RandomTableEntry, lookup: TableLookup, ctx: Pick = {}): { kind: CellKind; value: string } { + const link = entryLink(table, entry); + if (link !== undefined) { + if (lookup.table(link)) return { kind: "table", value: link }; + const k = lookup.kindOf?.(link) ?? "note"; + return { kind: k === "generator" ? "generator" : "note", value: link }; + } + const text = entry.result.trim(); + if (NOTHING.test(text)) return { kind: "nothing", value: "" }; + if (GENERATOR_ID.test(text)) return { kind: "generator", value: text }; + const terrain = ctx.terrains?.find((t) => lc(t) === lc(text)); + if (terrain !== undefined) return { kind: "terrain", value: terrain }; + if (table.rows === "terrain" && !ctx.terrains) return { kind: "terrain", value: text }; + return { kind: "text", value: text }; +} + +export interface RowSkip { + /** The table's key. */ + table: string; + index: number; + result: string; + why: "when" | "used" | "not-terrain" | "dead-end"; +} + +interface Fit { + weights: number[]; + /** Every row fits with its full weight (so the table can roll its die). */ + whole: boolean; + skipped: RowSkip[]; +} + +class Resolver { + private viable = new Map(); + constructor(private lookup: TableLookup, private ctx: ResolveContext) {} + + private get maxDepth() { + return this.ctx.maxDepth ?? DEFAULT_MAX_DEPTH; + } + + /** Each row's weight here (0 = can't come up), and why rows were left out. */ + fit(key: string, table: RandomTable, visited: readonly string[]): Fit { + const resolved = resolveTable(table); + const base = table.entries.map((e, i) => (resolved.mode === "ranges" ? resolved.faces[i].length : Math.max(0, e.weight))); + const skipped: RowSkip[] = []; + const weights = base.map((w, i) => { + if (w <= 0) return 0; + const e = table.entries[i]; + const info = rowInfoOf(table, i); + if (!conditionsFit(info.when, this.ctx)) { skipped.push({ table: key, index: i, result: e.result, why: "when" }); return 0; } + if (info.once && this.ctx.isUsed?.(key, i, e, info.once)) { skipped.push({ table: key, index: i, result: e.result, why: "used" }); return 0; } + if (this.ctx.onlyTerrains) { + const { kind, value } = cellKind(table, e, this.lookup, this.ctx); + if (kind === "table") { + if (!this.canYield(value, [...visited, key])) { skipped.push({ table: key, index: i, result: e.result, why: "dead-end" }); return 0; } + } else if (kind !== "terrain" && kind !== "nothing" && !(this.ctx.deferArrival && info.roll === "on arrival")) { + skipped.push({ table: key, index: i, result: e.result, why: "not-terrain" }); + return 0; + } + } + return w; + }); + return { weights, whole: weights.every((w, i) => w === base[i]), skipped }; + } + + /** Whether a linked table can give anything here (not a loop, not too deep, some row fits). */ + private canYield(link: string, visited: readonly string[]): boolean { + const t = this.lookup.table(link); + if (!t || visited.includes(t.key) || visited.length >= this.maxDepth) return false; + const memo = `${t.key}@${visited.length}`; + const known = this.viable.get(memo); + if (known !== undefined) return known; + this.viable.set(memo, false); // a cycle back here can't help + const ok = this.fit(t.key, t.table, visited).weights.some((w) => w > 0); + this.viable.set(memo, ok); + return ok; + } + + roll(link: string, rand: () => number, visited: string[], chain: ResolveStep[], attrs: Record): Resolved { + const t = this.lookup.table(link); + if (!t) return { kind: "empty", value: link, attrs, chain }; + if (visited.includes(t.key) || visited.length >= this.maxDepth) { + return { kind: "loop", value: `${LOOP_MARK} ${link}`, attrs, chain }; + } + const { table, key } = t; + const fit = this.fit(key, table, visited); + let index = -1; + let face: number | undefined; + if (fit.whole) { + const out = rollTable(table, rand); + if (out) { index = out.index; face = out.face; } + } else { + index = pickIndex(rand, fit.weights); + } + if (index < 0) return { kind: "empty", value: link, attrs, chain }; + const entry = table.entries[index]; + const info = rowInfoOf(table, index); + const step: ResolveStep = { table: key, index, result: entry.result }; + if (face !== undefined) step.face = face; + const nextChain = [...chain, step]; + const nextAttrs = { ...attrs, ...(info.attrs ?? {}) }; + const once = info.once ? { table: key, index, scope: info.once } : undefined; + const { kind, value } = cellKind(table, entry, this.lookup, this.ctx); + if (this.ctx.deferArrival && info.roll === "on arrival") { + const out: Resolved = { kind: "deferred", value: kind === "table" ? value : key, attrs: nextAttrs, chain: nextChain }; + const shown = info.shownAs ?? table.shownAs; + if (shown) out.shownAs = shown; + if (once) out.once = once; + return out; + } + const hit: OnceHit | undefined = info.once + ? { table: key, index, scope: info.once, result: entry.result, link: entryLink(table, entry) !== undefined } + : undefined; + if (kind === "table") { + const inner = this.roll(value, rand, [...visited, key], nextChain, nextAttrs); + if (!inner.once && once) inner.once = once; + if (hit && inner.kind !== "deferred" && inner.kind !== "empty" && inner.kind !== "loop") inner.onces = [hit, ...(inner.onces ?? [])]; + return inner; + } + const out: Resolved = { kind, value, attrs: nextAttrs, chain: nextChain }; + if (once) out.once = once; + if (hit) out.onces = [hit]; + return out; + } + + /** Each (link, tables above it) → its outcomes' odds, for odds(). */ + private oddsMemo = new Map(); + + /** + * Add the outcomes of rolling `link` (reached with probability `p`) to + * `out`. A linked table's own outcome odds are worked out once per link + * and set of tables above it (they only depend on those), then scaled: + * many rows linking the same table cost one walk of it, not one each + * (rows^depth on hostile fan-out tables, security review #7). + */ + odds(link: string, visited: string[], p: number, out: Map): void { + for (const o of this.oddsOf(link, visited)) addOdds(out, o.kind, o.value, p * o.odds); + } + + /** The outcomes of rolling `link` (as if reached for sure), in first-found order. */ + private oddsOf(link: string, visited: string[]): ResolvedOdds[] { + // Everything below depends on the link, the set of tables above and how many. + const memoKey = `${link}\u0000${[...visited].sort().join("\u0000")}`; + const known = this.oddsMemo.get(memoKey); + if (known) return known; + const out = new Map(); + const t = this.lookup.table(link); + if (!t) addOdds(out, "empty", link, 1); + else if (visited.includes(t.key) || visited.length >= this.maxDepth) addOdds(out, "loop", `${LOOP_MARK} ${link}`, 1); + else { + const { weights } = this.fit(t.key, t.table, visited); + const total = weights.reduce((a, b) => a + b, 0); + if (total <= 0) addOdds(out, "empty", link, 1); + else { + t.table.entries.forEach((e, i) => { + if (weights[i] <= 0) return; + const q = weights[i] / total; + const info = rowInfoOf(t.table, i); + const { kind, value } = cellKind(t.table, e, this.lookup, this.ctx); + if (this.ctx.deferArrival && info.roll === "on arrival") addOdds(out, "deferred", kind === "table" ? value : t.key, q); + else if (kind === "table") this.odds(value, [...visited, t.key], q, out); + else addOdds(out, kind, value, q); + }); + } + } + const list = [...out.values()]; + this.oddsMemo.set(memoKey, list); + return list; + } + + /** A `pick: each` table: every fitting row on its own Chance, in table order. */ + each(link: string, rand: () => number): Resolved[] { + const t = this.lookup.table(link); + if (!t) return []; + const { table, key } = t; + const out: Resolved[] = []; + table.entries.forEach((entry, index) => { + const info = rowInfoOf(table, index); + if (!conditionsFit(info.when, this.ctx)) return; + if (info.once && this.ctx.isUsed?.(key, index, entry, info.once)) return; + // A Chance cell that can't be read never comes up (reported by the parser). + const typed = Object.keys(info.attrs ?? {}).some((h) => h.trim().toLowerCase() === "chance"); + const chance = info.chance ?? (typed ? 0 : 1); + if (chance <= 0) return; + if (chance < 1 && rand() >= chance) return; + const step: ResolveStep = { table: key, index, result: entry.result }; + const attrs = { ...(info.attrs ?? {}) }; + const once = info.once ? { table: key, index, scope: info.once } : undefined; + const hit: OnceHit | undefined = info.once + ? { table: key, index, scope: info.once, result: entry.result, link: entryLink(table, entry) !== undefined } + : undefined; + const { kind, value } = cellKind(table, entry, this.lookup, this.ctx); + if (kind === "table") { + const inner = this.roll(value, rand, [key], [step], attrs); + if (inner.kind === "empty" || inner.kind === "loop") { out.push(inner); return; } + if (!inner.once && once) inner.once = once; + if (hit) inner.onces = [hit, ...(inner.onces ?? [])]; + out.push(inner); + return; + } + const r: Resolved = { kind, value, attrs, chain: [step] }; + if (once) r.once = once; + if (hit) r.onces = [hit]; + out.push(r); + }); + return out; + } + + /** Rows left out here, in this table and the tables it links (loop-guarded). */ + skippedRows(link: string, visited: string[] = []): RowSkip[] { + const t = this.lookup.table(link); + if (!t || visited.includes(t.key) || visited.length >= this.maxDepth) return []; + const own = this.fit(t.key, t.table, visited).skipped; + const nested = t.table.entries.flatMap((e) => { + const { kind, value } = cellKind(t.table, e, this.lookup, this.ctx); + return kind === "table" ? this.skippedRows(value, [...visited, t.key]) : []; + }); + return [...own, ...nested]; + } +} + +/** Add `q` to an outcome's odds (one entry per kind and value, case-insensitive). */ +function addOdds(out: Map, kind: ResolvedOdds["kind"], value: string, q: number): void { + const k = `${kind}:${lc(value)}`; + const o = out.get(k); + if (o) o.odds += q; + else out.set(k, { kind, value, odds: q }); +} + +/** Weighted pick of an index (one draw); -1 when nothing weighs anything. */ +function pickIndex(rand: () => number, weights: number[]): number { + const total = weights.reduce((a, b) => a + b, 0); + if (!(total > 0)) return -1; + let r = rand() * total; + let last = -1; + for (let i = 0; i < weights.length; i++) { + if (weights[i] <= 0) continue; + last = i; + r -= weights[i]; + if (r < 0) return i; + } + return last; +} + +function streamOf(ctx: ResolveContext): () => number { + if (ctx.rand) return ctx.rand; + if (ctx.seed !== undefined) return mulberry32(ctx.seed >>> 0); + return Math.random; +} + +/** + * Roll the table a link points at and follow it through: nested tables are + * rolled in turn (same stream), until a row that is text, a note, a + * terrain, a generator or nothing. + */ +export function resolveRoll(link: string, lookup: TableLookup, ctx: ResolveContext = {}): Resolved { + return new Resolver(lookup, ctx).roll(link, streamOf(ctx), [], [], {}); +} + +/** + * Roll a table "for each line": with `pick: each`, every row whose When + * fits (and isn't used up) comes up on its own Chance (no Chance column: + * always), in table order, each rolled through like resolveRoll. Any other + * table gives its one row (nothing when it has none). + */ +export function resolveEach(link: string, lookup: TableLookup, ctx: ResolveContext = {}): Resolved[] { + const t = lookup.table(link); + if (!t) return []; + if (t.table.pick !== "each") { + const r = resolveRoll(link, lookup, ctx); + return r.kind === "empty" ? [] : [r]; + } + return new Resolver(lookup, ctx).each(link, streamOf(ctx)); +} + +export interface ResolvedOdds { + kind: Resolved["kind"]; + value: string; + /** 0..1 */ + odds: number; +} + +/** The exact odds of every outcome resolveRoll can give for this link and context, most likely first. */ +export function resolveOdds(link: string, lookup: TableLookup, ctx: Omit = {}): ResolvedOdds[] { + const out = new Map(); + new Resolver(lookup, ctx).odds(link, [], 1, out); + return [...out.values()].sort((a, b) => b.odds - a.odds || a.value.localeCompare(b.value)); +} + +/** The rows of a table (and the tables it links) that this context leaves out, and why (for warnings: never drop a row silently). */ +export function skippedRows(link: string, lookup: TableLookup, ctx: Omit = {}): RowSkip[] { + return new Resolver(lookup, ctx).skippedRows(link); +} + +/** + * The first row naming `name` (any case) in a table or the tables it links + * (depth-first, loop-guarded): its attributes along the chain. For a + * lookup like "what does the sector row of this world say". + */ +export function findRow(link: string, name: string, lookup: TableLookup, maxDepth = DEFAULT_MAX_DEPTH): { attrs: Record; chain: ResolveStep[] } | undefined { + const want = lc(name); + const walk = (l: string, visited: string[], attrs: Record, chain: ResolveStep[]): ReturnType => { + const t = lookup.table(l); + if (!t || visited.includes(t.key) || visited.length >= maxDepth) return undefined; + const nested: [string, Record, ResolveStep[]][] = []; + for (let i = 0; i < t.table.entries.length; i++) { + const e = t.table.entries[i]; + const a = { ...attrs, ...(rowInfoOf(t.table, i).attrs ?? {}) }; + const c = [...chain, { table: t.key, index: i, result: e.result }]; + if (lc(e.result) === want) return { attrs: a, chain: c }; + const link = entryLink(t.table, e); + if (link !== undefined && lookup.table(link)) nested.push([link, a, c]); + } + for (const [l2, a, c] of nested) { + const hit = walk(l2, [...visited, t.key], a, c); + if (hit) return hit; + } + return undefined; + }; + return walk(link, [], {}, []); +} + +/** A readable chain: "Sector hexes → Mainworlds → ocean world". */ +export function chainLabel(r: Resolved, nameOf: (key: string) => string = (k) => k.replace(/^.*\//, "").replace(/\.md$/i, "")): string { + const parts = r.chain.map((s) => nameOf(s.table)); + const last = r.chain[r.chain.length - 1]; + if (last) parts.push(r.kind === "nothing" ? "(nothing)" : r.kind === "loop" ? r.value : last.result); + return parts.join(" → "); +} + +// ── row types (the seam for pickers, plan §2.5) ───────────────────────────── + +/** Who made a table, when it isn't the user: "map" for the tables made for every terrain and region. */ +export type TableMaker = "map"; + +/** + * The `table-type:` values of the tables the map makes for itself: two per + * terrain (`{tables}/terrain/description|encounters/.md`) and one + * per region (encounters, with `region:`). The starter tables (landmark, + * weather…) have other types and count as the user's. + */ +export const MAP_MADE_TABLE_TYPES: readonly string[] = ["description", "encounters"]; + +/** + * Who made a table, read from its frontmatter (never its name or folder): + * "map" when `table-type:` is one of MAP_MADE_TABLE_TYPES, else undefined + * (the user's). Deleting the `table-type:` line makes a table the user's. + */ +export function tableMadeBy(fm: Record | null | undefined): TableMaker | undefined { + const t = fm?.["table-type"]; + return typeof t === "string" && MAP_MADE_TABLE_TYPES.includes(lc(t)) ? "map" : undefined; +} + +/** What a picker wants: tables whose rows are one of these, optionally of a terrain type. */ +export interface TableWant { + rows?: readonly RowType[]; + terrainType?: string; + /** + * Tables the map made (tableMadeBy): "group" puts them in their own + * section after the user's tables ("Made by the map", collapsed where it + * can be), "hide" leaves them out. Unset: listed with the rest. + */ + mapMade?: "group" | "hide"; +} + +/** Heading of the section the map's own tables are grouped under. */ +export const MAP_MADE_GROUP_LABEL = "Made by the map"; + +/** + * How well a table fits a picker's want: "exact" (its `rows:` is wanted + * and, for terrain rows, its terrain-type fits), "any" (`rows: any`, which + * fits everything but sorts after exact matches) or "no" (with why, so a + * picker can list it disabled rather than hide it). `group: "map"` when the + * picker groups the map's own tables apart and this is one. + */ +export function tableFitsWant( + table: Pick & { madeBy?: TableMaker }, + want: TableWant, +): { fit: "exact" | "any" | "no"; why?: string; group?: "map" } { + if (table.madeBy === "map" && want.mapMade) { + if (want.mapMade === "hide") return { fit: "no", why: "the map made it for its terrains and regions" }; + const r = tableFitsWant({ rows: table.rows, terrainTypes: table.terrainTypes }, want); + return { ...r, group: "map" }; + } + if (!want.rows?.length) return { fit: table.rows ? "exact" : "any" }; + if (!table.rows) return { fit: "any" }; + if (!want.rows.includes(table.rows)) return { fit: "no", why: `its rows are ${table.rows}, not ${want.rows.join(" or ")}` }; + if (want.terrainType && table.rows === "terrain" && table.terrainTypes?.length && !table.terrainTypes.includes(lc(want.terrainType))) { + return { fit: "no", why: `its terrain type is ${table.terrainTypes.join(", ")}, not ${want.terrainType}` }; + } + return { fit: "exact" }; +} + +/** Which cell kinds a `rows:` type accepts. */ +const ACCEPTS: Record = { + any: ["text", "note", "table", "generator", "terrain", "nothing"], + text: ["text", "nothing"], + note: ["note", "table", "nothing"], + table: ["table", "nothing"], + generator: ["generator", "nothing"], + terrain: ["terrain", "table", "nothing"], + biome: ["note", "table", "nothing"], +}; + +/** + * Rows whose cell doesn't fit the table's `rows:` (a constraint, never a + * parser switch: the row still reads and rolls; this is what the editor + * and checks report). + */ +export function rowTypeProblems(table: RandomTable, lookup: TableLookup, ctx: Pick = {}): { index: number; message: string }[] { + const rows = table.rows ?? "any"; + const out: { index: number; message: string }[] = []; + table.entries.forEach((e, i) => { + const { kind } = cellKind(table, e, lookup, ctx); + if (ACCEPTS[rows].includes(kind)) return; + const what = kind === "text" && rows === "terrain" ? "isn't a terrain of the palette" : `is ${kind === "text" ? "plain text" : `a ${kind}`}`; + out.push({ index: i, message: `Row ${i + 1} ("${e.result}") ${what}, but the table's rows are ${rows}.` }); + }); + return out; +} + +const GENERATOR_MARKERS = /^(?:hex-wfc|hexmaker-recipe|hexmaker-generator|template-file|results-folder):/m; + +/** What a note is, from its text: a generator (generator note, recipe, workflow), a table, or another note. */ +export function noteKind(content: string): "generator" | "table" | "note" { + const fm = /^---[ \t]*\r?\n([\s\S]*?)\r?\n---/.exec(content)?.[1] ?? ""; + if (GENERATOR_MARKERS.test(fm)) return "generator"; + if (/^dice:/m.test(fm) || /^rows:/m.test(fm)) return "table"; + const block = locateRollTable(content); + return block?.recognized ? "table" : "note"; +} + +/** + * A lookup over notes held in memory (path → text). Links resolve by path + * (with or without `.md`) or by note name; `Note#Heading` reads the table + * under that heading, so a table inside another note (a biome's Mix) rolls + * like any table. + */ +export function notesLookup(notes: Record): TableLookup { + const paths = Object.keys(notes); + const find = (target: string): string | undefined => { + const t = lc(target).replace(/\.md$/, ""); + return paths.find((p) => lc(p).replace(/\.md$/, "") === t) + ?? paths.find((p) => lc(p).replace(/\.md$/, "").replace(/^.*\//, "") === t.replace(/^.*\//, "")); + }; + const split = (link: string) => { + const i = link.indexOf("#"); + return i < 0 ? { target: link, heading: undefined } : { target: link.slice(0, i), heading: link.slice(i + 1) }; + }; + const cache = new Map(); + return { + table(link) { + const { target, heading } = split(link); + const path = find(target); + if (!path) return undefined; + const key = heading ? `${path}#${heading}` : path; + if (!cache.has(key)) { + const content = notes[path]; + const isTable = heading ? !!locateRollTable(content, heading) : noteKind(content) === "table"; + cache.set(key, isTable ? { key, table: parseRandomTable(content, { heading }) } : null); + } + return cache.get(key) ?? undefined; + }, + kindOf(link) { + const path = find(split(link).target); + if (!path) return "missing"; + return noteKind(notes[path]) === "generator" ? "generator" : "note"; + }, + }; +} + +/** Several lookups as one: the first that knows a link answers. */ +export function layeredLookup(...lookups: (TableLookup | undefined)[]): TableLookup { + const ls = lookups.filter((l): l is TableLookup => !!l); + return { + table: (link) => { + for (const l of ls) { + const t = l.table(link); + if (t) return t; + } + return undefined; + }, + kindOf: (link) => { + for (const l of ls) { + const k = l.kindOf?.(link); + if (k && k !== "missing") return k; + } + return "missing"; + }, + }; +} + +/** A lookup over tables held in memory, by key (names match any case, with or without `.md`). */ +export function memoryLookup(tables: Record, kinds: Record = {}): TableLookup { + const norm = (s: string) => lc(s).replace(/\.md$/, ""); + const byKey = new Map(Object.entries(tables).map(([k, t]) => [norm(k), { key: k, table: t }])); + return { + table: (link) => byKey.get(norm(link)), + kindOf: (link) => kinds[link] ?? (byKey.has(norm(link)) ? "note" : "missing"), + }; +} diff --git a/src/random-tables/shippedTables.ts b/src/random-tables/shippedTables.ts new file mode 100644 index 00000000..a8247930 --- /dev/null +++ b/src/random-tables/shippedTables.ts @@ -0,0 +1,27 @@ +/** + * Installing the modules' shipped table notes (plan-tables-everywhere + * §2.9, phase 6): which ones a vault is missing. A note at the path is + * kept as it is, whatever it says (the user's copy wins; copy-on-edit), + * so running this again writes nothing. + * + * Pure: no Obsidian imports. + */ + +import type { ShippedTableDef } from "../modules/types"; + +/** The shipped tables to write: full vault paths under `tablesFolder`, only those not there yet. */ +export function shippedTablesToInstall( + tables: readonly ShippedTableDef[], + tablesFolder: string, + exists: (path: string) => boolean, +): ShippedTableDef[] { + const out: ShippedTableDef[] = []; + const seen = new Set(); + for (const t of tables) { + const path = tablesFolder ? `${tablesFolder}/${t.path}` : t.path; + if (seen.has(path) || exists(path)) continue; + seen.add(path); + out.push({ path, text: t.text }); + } + return out; +} diff --git a/src/random-tables/tableConditions.ts b/src/random-tables/tableConditions.ts new file mode 100644 index 00000000..2ec18567 --- /dev/null +++ b/src/random-tables/tableConditions.ts @@ -0,0 +1,150 @@ +/** + * The `When` column of a random table (plan-tables-everywhere §2.8): an + * escape hatch that limits a row to some contexts. Prefer one table per + * context; use When for the rare row that only fits sometimes. + * + * | d6 | Result | Weight | When | + * | 1–4 | gas giant | 4 | zone: outer | + * | 5 | ice moon | 1 | star: red dwarf, white dwarf; zone: outer | + * | 6 | hot jupiter | 1 | zone: inner; ring: 2–3 | + * + * - Conditions are `key: value`, separated by `;`. A comma lists choices + * (any of them fits). Every condition must fit. + * - Keys: type (terrain types), terrain (the parent hex's terrain) and + * near (`near: town 2`: a place of that type within 2 hexes; hex fields, + * src/fields/places.ts) are the core's; modules add theirs (Space: zone, + * ring, star; World maps: temperature), see TableConditionDef. + * - A key the roller doesn't know about here (no star, say) lets the row + * through, so a hand roll and the Tables view roll every row. + * - An unknown key, or a value that can't be read, is reported and that + * row never fires. + * + * The rule a hand-roller follows: "if a row's When doesn't fit, roll + * again". The code renormalises over the rows that fit, which is the same + * distribution. + * + * Pure: no Obsidian imports. + */ + +import type { OrbitZone } from "../modules/space/orbitZones"; +import type { TableConditionDef } from "../modules/types"; +import { registry } from "../modules"; + +export type TableCondition = + /** The core's list keys (type, terrain): any of the values fits. */ + | { key: "type" | "terrain"; values: string[] } + /** A module's key (zone, ring, star, temperature): its own reading of the value. */ + | { key: string; value: unknown } + /** Can't be read: the row never fires. */ + | { key: "unknown"; text: string }; + +/** What the roller knows where it rolls. Every field is optional. */ +export interface ConditionContext { + zone?: OrbitZone; + /** Hexes from the star. */ + ring?: number; + /** The system's star terrain. */ + star?: string; + /** The terrain type being placed or the parent hex's type. */ + type?: string; + /** The parent hex's terrain. */ + terrain?: string; + /** 0 (cold) … 1 (hot). */ + temperature?: number; + /** The places on the map and how far each is (hex fields' rolls). */ + near?: readonly { type: string; distance: number }[]; +} + +const lc = (s: string) => s.trim().toLowerCase(); +const list = (raw: string) => raw.split(/\s*,\s*/).map(lc).filter((s) => s !== ""); + +/** The core's list keys. */ +const CORE_LIST_KEYS = ["type", "terrain"] as const; + +/** `near: town 2` (also `near: town, city 3`; no number = 1): a place of one of the types within that many hexes. */ +export const NEAR_CONDITION: TableConditionDef = { + key: "near", + aliases: ["within"], + read(value) { + const m = /^(.*?)(?:\s+(\d+))?$/.exec(value.trim()); + const types = list(m?.[1] ?? ""); + if (!types.length) return undefined; + return { types, radius: m?.[2] ? Number(m[2]) : 1 }; + }, + fits(read, known) { + const { types, radius } = read as { types: string[]; radius: number }; + if (!Array.isArray(known)) return true; + return (known as { type: string; distance: number }[]).some((p) => types.includes(lc(p.type)) && p.distance <= radius); + }, + format(read) { + const { types, radius } = read as { types: string[]; radius: number }; + return `${types.join(", ")} ${radius}`; + }, +}; + +/** The core's own keys with a reading (the list keys aside). */ +const CORE_DEFS: readonly TableConditionDef[] = [NEAR_CONDITION]; + +/** A condition (the core's or a module's) for a key or one of its aliases (singular, lower case). */ +function conditionDef(key: string): TableConditionDef | undefined { + return [...CORE_DEFS, ...registry.tableConditions()].find((d) => d.key === key || (d.aliases ?? []).includes(key)); +} + +/** Every key a When cell may use: the core's and each module's, in module order. */ +export function conditionKeys(): string[] { + return [...registry.tableConditions().map((d) => d.key), ...CORE_LIST_KEYS, ...CORE_DEFS.map((d) => d.key)]; +} + +/** One `key: value` → a condition (key "unknown" when it can't be read). */ +function readCondition(part: string): TableCondition { + const m = /^([a-z ]+?)\s*[:=]\s*(.+)$/i.exec(part.trim()); + if (!m) return { key: "unknown", text: part.trim() }; + const key = lc(m[1]).replace(/s$/, ""); + const value = m[2].trim(); + if (key === "type" || key === "terrain") { + const values = list(value); + return values.length ? { key, values } : { key: "unknown", text: part.trim() }; + } + const def = conditionDef(key); + const read = def?.read(value); + return def && read !== undefined ? { key: def.key, value: read } : { key: "unknown", text: part.trim() }; +} + +/** A When cell → its conditions (empty for a blank cell or "any"). */ +export function parseWhen(raw: string): TableCondition[] { + const t = raw.trim(); + if (!t || /^(any|always|-|—)$/i.test(t)) return []; + return t.split(/\s*;\s*/).filter((p) => p !== "").map(readCondition); +} + +/** The parts of a When cell that can't be read (reported; the row never fires). */ +export function unreadableConditions(when: readonly TableCondition[]): string[] { + return when.flatMap((c) => ("text" in c ? [c.text] : [])); +} + +/** Whether a row's conditions fit the context. Conditions the context can't speak to pass; unreadable ones never do. */ +export function conditionsFit(when: readonly TableCondition[] | undefined, ctx: ConditionContext = {}): boolean { + if (!when?.length) return true; + const known = ctx as Record; + for (const c of when) { + if ("text" in c) return false; + const v = known[c.key]; + if (v === undefined) continue; + if ("values" in c) { + if (typeof v !== "string" || !c.values.includes(lc(v))) return false; + continue; + } + const def = conditionDef(c.key); + if (!def || !def.fits(c.value, v)) return false; + } + return true; +} + +/** Conditions back as a When cell. */ +export function formatWhen(when: readonly TableCondition[]): string { + return when.map((c) => { + if ("text" in c) return c.text; + if ("values" in c) return `${c.key}: ${c.values.join(", ")}`; + return `${c.key}: ${conditionDef(c.key)?.format(c.value) ?? String(c.value)}`; + }).join("; "); +} diff --git a/src/random-tables/tableEditor/linkedFolder.ts b/src/random-tables/tableEditor/linkedFolder.ts new file mode 100644 index 00000000..625ad908 --- /dev/null +++ b/src/random-tables/tableEditor/linkedFolder.ts @@ -0,0 +1,107 @@ +/** + * The table editor's linked-folder sync (a table whose rows are notes in a + * folder): stub notes for new rows, renamed notes for renamed rows, "_" + * for deleted rows, rows for notes added by hand. Split from + * RandomTableEditorModal. + * + * The folder and the row text come from the table note, which may come + * from someone else's pack, so the folder must be inside the world folder + * and not hidden, and row text is cleaned into a file name before it + * becomes a path. + */ +import { TFile, type App } from "obsidian"; +import type { RandomTableEntry } from "../randomTable"; +import { worldFolderOf } from "../../notePickers"; +import { ensureFolder } from "../../vault/ensureFolder"; +import { isFolderInside, noteFileName } from "../../vault/safePaths"; + +/** The note a row of a linked-folder table stands for: its text as a file name ("" = none). */ +export function rowNoteName(result: string): string { + return noteFileName(result); +} + +/** A row's note path in `folder`, or null when its text leaves no file name. */ +export function rowNotePath(folder: string, result: string): string | null { + const name = rowNoteName(result); + return name ? `${folder}/${name}.md` : null; +} + +/** Whether the editor may sync notes in `folder`: a folder inside the world folder, not hidden. */ +export function linkedFolderAllowed(folder: string, settings: { worldFolder?: string }): boolean { + return !!folder && isFolderInside(folder, [worldFolderOf(settings)]); +} + +/** Rows whose note isn't in the folder (kept and reported, never recreated). */ +export function missingRowNotes(app: App, folder: string, entries: readonly RandomTableEntry[]): Set { + const out = new Set(); + for (const e of entries) { + const p = rowNotePath(folder, e.result); + if (p && !app.vault.getAbstractFileByPath(p)) out.add(e.result); + } + return out; +} + +/** Sync entries ↔ notes in the folder: a stub note for each new row, a row for each note added by hand. Mutates entries. */ +export async function syncLinkedFolder(app: App, entries: RandomTableEntry[], folder: string, missingAtOpen: ReadonlySet): Promise { + await ensureFolder(app.vault, folder); + const existing = app.vault + .getMarkdownFiles() + .filter((f) => f.parent?.path === folder && !f.basename.startsWith("_")); + for (const entry of entries) { + // A row whose note was missing when the editor opened is reported, not recreated. + if (missingAtOpen.has(entry.result)) continue; + const notePath = rowNotePath(folder, entry.result); + if (!notePath || app.vault.getAbstractFileByPath(notePath)) continue; + try { + await app.vault.create(notePath, `# ${entry.result}\n`); + } catch { + /* made meanwhile, or a name the file system refuses: the row stays */ + } + } + const names = new Set(entries.map((e) => rowNoteName(e.result))); + for (const f of existing) { + if (!names.has(f.basename)) entries.push({ result: f.basename, weight: 1 }); + } +} + +/** Rename the notes of rows whose text was changed, instead of making new ones. */ +export async function renameUpdatedEntries(app: App, entries: readonly RandomTableEntry[], originalResults: WeakMap, folder: string): Promise { + for (const entry of entries) { + const orig = originalResults.get(entry); + if (!orig || orig === entry.result) continue; + const oldPath = rowNotePath(folder, orig); + const newPath = rowNotePath(folder, entry.result); + if (!oldPath || !newPath || oldPath === newPath) continue; + const note = app.vault.getAbstractFileByPath(oldPath); + if (!(note instanceof TFile)) continue; + if (app.vault.getAbstractFileByPath(newPath)) continue; // target already exists + try { + await app.fileManager.renameFile(note, newPath); + } catch { + /* best-effort */ + } + } +} + +/** Prepend "_" to the notes of deleted rows, so later syncs leave them out. */ +export async function retireDeletedEntries(app: App, originalResults: ReadonlySet, current: readonly RandomTableEntry[], folder: string): Promise { + const currentNames = new Set(current.map((e) => e.result)); + for (const result of originalResults) { + if (currentNames.has(result)) continue; + const name = rowNoteName(result); + if (!name) continue; + const note = app.vault.getAbstractFileByPath(`${folder}/${name}.md`); + if (!(note instanceof TFile)) continue; + try { + await app.fileManager.renameFile(note, `${folder}/_${name}.md`); + } catch { + /* already renamed or missing */ + } + } +} + +/** The note's text now, or null when it's gone. */ +export async function currentText(app: App, file: TFile): Promise { + const now = app.vault.getAbstractFileByPath(file.path); + return now instanceof TFile ? app.vault.read(now) : null; +} diff --git a/src/random-tables/tableImport.ts b/src/random-tables/tableImport.ts new file mode 100644 index 00000000..10cfbf41 --- /dev/null +++ b/src/random-tables/tableImport.ts @@ -0,0 +1,130 @@ +/** + * Importing hand edits to a table note (issue #45). + * + * The plugin's own UI regenerates the roll column from the weights. When a + * person edits the raw note instead, the edit is imported: the plugin brings + * the other columns in line on its next write, and never throws away what + * was typed. Given the content the plugin last read or wrote (`prev`) and + * the note now (`cur`): + * + * - Die changed (the `| dN |` header or `dice:`): the other one is updated to + * match and the ranges are redone from the weights — unless the ranges were + * also edited and are valid for the new die, in which case they're kept and + * the weights follow them. + * - Ranges edited and valid (every face once, no overlap or gap): adopted; + * each row's weight becomes its face count. + * - Only weights (or rows) changed, and the old ranges matched the old + * weights: the ranges are redone from the new weights. + * - Anything else (gaps, overlaps, unreadable ranges, more rows than faces, + * ranges that never matched the weights): nothing is changed; the table + * rolls as resolveTable says and the view shows the problem with its fixes. + * + * Pure: no Obsidian imports. TableStore decides when to call it. + */ + +import { + dieFaces, + frontmatterDie, + parseRandomTableWithReport, + rangeHeaderDie, + rangesFollowWeights, + resolveTable, + setDiceInFrontmatter, + writeRollTable, + type RandomTable, + type RandomTableEntry, + type TableRowWrite, +} from "./randomTable"; + +export type ImportKind = "none" | "die" | "ranges" | "weights" | "ambiguous"; + +export interface ImportResult { + kind: ImportKind; + /** The note after importing (unchanged for "none" and "ambiguous"). */ + content: string; +} + +/** Ranges that can be adopted as typed: usable, every face covered once. */ +function cleanRanges(table: RandomTable): boolean { + const r = resolveTable(table); + return r.mode === "ranges" && !r.issues.some((i) => i.code === "range-gap"); +} + +/** + * Pair each current row with its previous row: same result first (rows + * moved or deleted), then same position (a result renamed in place). + */ +function matchRows(prev: RandomTableEntry[], cur: RandomTableEntry[]): (RandomTableEntry | undefined)[] { + const used = new Set(); + const out: (RandomTableEntry | undefined)[] = cur.map((e) => { + const i = prev.findIndex((p, k) => !used.has(k) && p.result === e.result); + if (i < 0) return undefined; + used.add(i); + return prev[i]; + }); + out.forEach((m, i) => { + if (m || i >= prev.length || used.has(i)) return; + used.add(i); + out[i] = prev[i]; + }); + return out; +} + +export function importHandEdit(prev: string, cur: string): ImportResult { + const none: ImportResult = { kind: "none", content: cur }; + if (prev === cur) return none; + const p = parseRandomTableWithReport(prev); + const c = parseRandomTableWithReport(cur); + if (!c.block?.recognized || c.block.cols.range < 0) return none; + + const entries = c.table.entries; + const before = matchRows(p.table.entries, entries); + const rangesEdited = entries.some((e, i) => !!e.range?.trim() && (e.range ?? "") !== (before[i]?.range ?? "")); + const weightsEdited = + entries.length !== p.table.entries.length || entries.some((e, i) => !before[i] || before[i]?.weight !== e.weight); + + const rowsAs = (weights?: number[]): TableRowWrite[] => + entries.map((entry, source) => ({ entry: weights ? { ...entry, weight: weights[source] } : entry, source })); + const adopt = (dice: number): string => { + const faces = resolveTable({ dice, entries }).faces.map((f) => f.length); + return writeRollTable(cur, { dice, rows: rowsAs(faces), ranges: "keep" }); + }; + + // ── Die change: the header and dice: follow each other. + const pFm = frontmatterDie(prev); + const cFm = frontmatterDie(cur); + const pHd = rangeHeaderDie(p.block); + const cHd = rangeHeaderDie(c.block); + const fmChanged = pFm !== cFm && cFm > 0; + const hdChanged = p.block !== null && p.block.cols.range >= 0 && pHd !== cHd && cHd > 0; + if (fmChanged || hdChanged) { + if (fmChanged && hdChanged && cFm !== cHd) return { kind: "ambiguous", content: cur }; + const die = fmChanged ? cFm : cHd; + const keepTyped = rangesEdited && cleanRanges({ dice: die, entries }); + let next = keepTyped + ? adopt(die) + : writeRollTable(cur, { dice: die, rows: rowsAs(), ranges: "regenerate" }); + if (frontmatterDie(next) !== die) next = setDiceInFrontmatter(next, die); + return { kind: "die", content: next }; + } + + const dice = c.table.dice; + if (dice <= 0) return none; + + // ── Ranges typed by hand: adopt them if they're clean. + if (rangesEdited) { + if (!cleanRanges(c.table)) return { kind: "ambiguous", content: cur }; + const next = adopt(dice); + return { kind: next === cur ? "none" : "ranges", content: next }; + } + + // ── Only weights or rows changed: redo the ranges if they were in step. + if (weightsEdited) { + const fits = entries.filter((e) => e.weight > 0).length <= dieFaces(dice).length; + if (!rangesFollowWeights(p.table) || !fits) return { kind: "ambiguous", content: cur }; + const next = writeRollTable(cur, { dice, rows: rowsAs(), ranges: "regenerate" }); + return { kind: next === cur ? "none" : "weights", content: next }; + } + return none; +} + diff --git a/src/random-tables/tableMaintenance.ts b/src/random-tables/tableMaintenance.ts new file mode 100644 index 00000000..d1cd5e76 --- /dev/null +++ b/src/random-tables/tableMaintenance.ts @@ -0,0 +1,201 @@ +/** + * Table upkeep commands (issue #45): + * - "Check tables" writes a report note (`_table-check.md` in the tables + * folder) listing tables whose ranges, weights or columns couldn't be read. + * - "Add roll ranges to tables" upgrades older tables to `| dN | Result | + * Weight |`, after writing a gzipped full-text backup. It only runs from + * the user's click in TableRangesModal, and once, silently, on the first + * load after updating (src/migrations/v1.5-table-roll-ranges.ts; no + * prompt: DJ-Q6). + * + * Never adds to or alters `_` notes (other than the report it owns). + */ + +import { Notice, TFile, type App } from "obsidian"; +import { HexmakerModal } from "../HexmakerModal"; +import type HexmakerPlugin from "../HexmakerPlugin"; +import { normalizeFolder } from "../utils"; +import { parseRandomTableWithReport, type TableIssue } from "./randomTable"; +import { tableNotes, type TableScope } from "./tableNotePaths"; +import { backupDirFor, migrateTables, type MigrationResult, type MigrationSurvey, surveyTableMigration } from "../migrations/v1.5-table-roll-ranges"; +import { ensureFolder } from "../vault/ensureFolder"; + +export type { TableScope }; +export { migrateTables, surveyTableMigration, tableNotes, type MigrationResult, type MigrationSurvey }; + +export const TABLE_CHECK_NOTE = "_table-check.md"; + +export function tableScope(plugin: HexmakerPlugin): TableScope { + return { + tablesFolder: normalizeFolder(plugin.settings.tablesFolder ?? ""), + workflowsFolder: normalizeFolder(plugin.settings.workflowsFolder ?? ""), + }; +} + +export interface TableCheck { + path: string; + issues: TableIssue[]; +} + +/** Every table note's issues (tables with none are left out). */ +export async function checkTables(app: App, scope: TableScope): Promise<{ checked: number; problems: TableCheck[] }> { + const problems: TableCheck[] = []; + let checked = 0; + for (const file of tableNotes(app, scope)) { + const report = parseRandomTableWithReport(await app.vault.read(file)); + if (!report.block?.recognized) continue; + checked++; + if (report.issues.length) problems.push({ path: file.path, issues: report.issues }); + } + return { checked, problems }; +} + +const link = (path: string) => { + const stem = path.replace(/\.md$/i, ""); + return `[[${stem}|${stem.slice(stem.lastIndexOf("/") + 1)}]]`; +}; + +/** The report note's text. */ +export function formatTableReport( + when: Date, + check: { checked: number; problems: TableCheck[] }, + migration?: MigrationResult, +): string { + const stamp = `${when.toISOString().slice(0, 10)} ${when.toTimeString().slice(0, 5)}`; + const lines = [ + "# Table check", + "", + `Written by Hexmap World Creator on ${stamp}. This note is replaced each time the check runs, so notes made here will be lost.`, + "", + ]; + if (migration) { + lines.push("## Roll ranges added", ""); + if (migration.error) lines.push(`- ${migration.error}`); + lines.push(`- Changed: ${migration.changed.length} table${migration.changed.length === 1 ? "" : "s"}.`); + if (migration.backup) lines.push(`- Backup of the originals: \`${migration.backup}\``); + lines.push(`- Already had ranges: ${migration.unchanged}.`); + if (migration.skipped.length) { + lines.push(`- Left as they were (${migration.skipped.length}):`); + for (const s of migration.skipped) lines.push(` - ${link(s.path)}: ${s.reason}`); + } + lines.push(""); + } + lines.push("## Tables to look at", ""); + lines.push( + check.problems.length + ? `Checked ${check.checked} table${check.checked === 1 ? "" : "s"}; ${check.problems.length} ha${check.problems.length === 1 ? "s" : "ve"} something to look at.` + : `Checked ${check.checked} table${check.checked === 1 ? "" : "s"}; nothing to look at.`, + "", + ); + for (const p of check.problems) { + lines.push(`### ${link(p.path)}`, ""); + for (const i of p.issues) lines.push(`- ${i.message}`); + lines.push(""); + } + return lines.join("\n"); +} + +/** Write (or replace) the report note in the tables folder. Returns its path. */ +export async function writeTableReport(app: App, scope: TableScope, text: string): Promise { + const path = scope.tablesFolder ? `${scope.tablesFolder}/${TABLE_CHECK_NOTE}` : TABLE_CHECK_NOTE; + const existing = app.vault.getAbstractFileByPath(path); + if (existing instanceof TFile) await app.vault.modify(existing, text); + else { + if (scope.tablesFolder) await ensureFolder(app.vault, scope.tablesFolder); + await app.vault.create(path, text); + } + return path; +} + +/** "Check tables" command. */ +export async function runTableCheck(plugin: HexmakerPlugin): Promise { + const scope = tableScope(plugin); + const check = await checkTables(plugin.app, scope); + const path = await writeTableReport(plugin.app, scope, formatTableReport(new Date(), check)); + new Notice( + check.problems.length + ? `${check.problems.length} of ${check.checked} tables have something to look at. See ${path}.` + : `Checked ${check.checked} tables: nothing to look at.`, + ); + const file = plugin.app.vault.getAbstractFileByPath(path); + if (file instanceof TFile && check.problems.length) await plugin.app.workspace.getLeaf("tab").openFile(file); +} + +/** Run the migration (from the modal's button), then report. */ +async function runMigration(plugin: HexmakerPlugin): Promise { + const scope = tableScope(plugin); + const notice = new Notice("Adding roll ranges to tables…", 0); + try { + const result = await migrateTables(plugin.app, scope, backupDirFor(plugin)); + const check = await checkTables(plugin.app, scope); + const path = await writeTableReport(plugin.app, scope, formatTableReport(new Date(), check, result)); + if (!result.error && !plugin.settings.tableRangesUpgraded) { + plugin.settings.tableRangesUpgraded = true; + await plugin.saveSettings(); + } + new Notice( + result.error ?? + `Added roll ranges to ${result.changed.length} table${result.changed.length === 1 ? "" : "s"}` + + (result.skipped.length ? `; ${result.skipped.length} left as they were` : "") + + `. See ${path}.`, + ); + const file = plugin.app.vault.getAbstractFileByPath(path); + if (file instanceof TFile) await plugin.app.workspace.getLeaf("tab").openFile(file); + } finally { + notice.hide(); + } +} + +/** Shows what would change, then adds roll ranges on the click (the "Add roll ranges to tables" command). */ +export class TableRangesModal extends HexmakerModal { + constructor( + app: App, + private plugin: HexmakerPlugin, + private survey: MigrationSurvey, + ) { + super(app); + } + + onOpen(): void { + this.makeDraggable(); + this.titleEl.setText("Add roll ranges to tables?"); + const { contentEl } = this; + const n = this.survey.changes.size; + contentEl.createEl("p", { + text: + `Tables can now show each row's roll range for their die (for example "1–6"), so they can be rolled by hand from the note itself. ` + + `${n} table${n === 1 ? "" : "s"} would get a roll column. Weights, results, other columns and text around the tables stay as they are.`, + }); + if (this.survey.skipped.length) { + contentEl.createEl("p", { + cls: "duckmage-map-origin-desc", + text: `${this.survey.skipped.length} table${this.survey.skipped.length === 1 ? "" : "s"} would be left as they are (no die, too many rows for the die, or something that can't be read). They're listed in the report afterwards.`, + }); + } + this.footer({ + primary: { text: "Add ranges (a backup is made first)", disabled: n === 0, onClick: () => { + this.close(); + void runMigration(this.plugin); + } }, + cancel: () => this.close(), + }); + } + + onClose(): void { + this.contentEl.empty(); + } +} + +/** "Add roll ranges to tables" command: shows what would change, then asks. */ +export async function openTableRangesModal(plugin: HexmakerPlugin): Promise { + const survey = await surveyTableMigration(plugin.app, tableScope(plugin)); + if (!survey.changes.size) { + new Notice( + survey.skipped.length + ? `No table needs roll ranges; ${survey.skipped.length} can't take them yet. Run "Check tables" for details.` + : "Every table already has roll ranges.", + ); + return; + } + new TableRangesModal(plugin.app, plugin, survey).open(); +} diff --git a/src/random-tables/tableNotePaths.ts b/src/random-tables/tableNotePaths.ts new file mode 100644 index 00000000..4fe1a160 --- /dev/null +++ b/src/random-tables/tableNotePaths.ts @@ -0,0 +1,31 @@ +/** + * Which notes are table notes (the tables folder, minus "_" notes and the + * workflows folder), for the table store, "Check tables" and the roll + * ranges upgrade. Pure path logic plus one vault listing. + */ +import type { App, TFile } from "obsidian"; + +export interface TableScope { + tablesFolder: string; + workflowsFolder: string; +} + +/** Table notes in the tables folder ("_" notes and workflows excluded), by path. */ +export function tableNotes(app: App, scope: TableScope): TFile[] { + return app.vault + .getMarkdownFiles() + .filter((f) => isTableNotePath(f.path, scope.tablesFolder, scope.workflowsFolder)) + .sort((a, b) => a.path.localeCompare(b.path)); +} + +/** Whether a vault path is a table note the migration and checks look at. */ +export function isTableNotePath(path: string, tablesFolder: string, workflowsFolder: string): boolean { + if (!path.endsWith(".md")) return false; + const name = path.slice(path.lastIndexOf("/") + 1); + if (name.startsWith("_")) return false; + const tf = tablesFolder ? tablesFolder + "/" : ""; + if (tf && !path.startsWith(tf)) return false; + const wf = workflowsFolder ? workflowsFolder + "/" : ""; + if (wf && path.startsWith(wf)) return false; + return true; +} diff --git a/src/random-tables/tablePickerGroups.ts b/src/random-tables/tablePickerGroups.ts new file mode 100644 index 00000000..2698fd89 --- /dev/null +++ b/src/random-tables/tablePickerGroups.ts @@ -0,0 +1,12 @@ +import type { App, TFile } from "obsidian"; +import { groupTablesForPicker } from "../notePickers"; +import { tableMadeBy } from "./resolve"; + +/** + * Table files for a picker: the user's own, then the ones the map made + * (terrain and region tables, told apart by their `table-type:` + * frontmatter; see tableMadeBy). Order kept within each part. + */ +export function groupTableFiles(app: App, files: readonly TFile[]): { own: TFile[]; mapMade: TFile[] } { + return groupTablesForPicker(files, (f) => ({ madeBy: tableMadeBy(app.metadataCache.getFileCache(f)?.frontmatter) })); +} diff --git a/src/random-tables/tableVaultEvents.ts b/src/random-tables/tableVaultEvents.ts new file mode 100644 index 00000000..ea1751b5 --- /dev/null +++ b/src/random-tables/tableVaultEvents.ts @@ -0,0 +1,84 @@ +/** + * What the tables and workflows folders do on vault events (dispatched by + * src/plugin/vaultEvents.ts): a renamed folder's linkedFolder links in + * table notes follow it, and a deleted table leaves the workflows that + * rolled on it. Split from HexmakerPlugin.onload. + */ +import { TAbstractFile, TFile, TFolder, type App } from "obsidian"; +import type { HexmakerPluginSettings } from "../types"; +import { normalizeFolder } from "../utils"; +import { buildWorkflowContent, parseWorkflow } from "./workflow"; + +/** What the table events read. */ +export interface TableEventsHost { + app: App; + settings: Pick; +} + +/** Keep linkedFolder frontmatter in sync when a folder is renamed. */ +export async function onTableFolderRenamed(host: TableEventsHost, abstractFile: TAbstractFile, oldPath: string): Promise { + if (!(abstractFile instanceof TFolder)) return; + const oldFolder = normalizeFolder(oldPath); + const newFolder = normalizeFolder(abstractFile.path); + if (oldFolder === newFolder) return; + + const tablesPrefix = normalizeFolder(host.settings.tablesFolder); + const tableFiles = host.app.vault + .getMarkdownFiles() + .filter( + (f) => !tablesPrefix || f.path.startsWith(tablesPrefix + "/"), + ); + + for (const tableFile of tableFiles) { + const fm = host.app.metadataCache.getFileCache(tableFile)?.frontmatter; + const lf: unknown = fm?.["linkedFolder"] ?? fm?.["linked-folder"]; + if (!lf || typeof lf !== "string") continue; + const wikiLinkMatch = /^\[\[(.+?)\]\]$/.exec(lf); + const lfClean = wikiLinkMatch ? wikiLinkMatch[1].trim() : lf; + const lfNorm = normalizeFolder(lfClean); + if (lfNorm !== oldFolder && !lfNorm.startsWith(oldFolder + "/")) + continue; + const updatedLf = newFolder + lfNorm.slice(oldFolder.length); + await host.app.vault.process(tableFile, (content) => + content.replace( + /^((?:linkedFolder|linked-folder):\s*).*$/m, + `$1"[[${updatedLf}]]"`, + ), + ); + } +} + +/** Remove workflow steps that reference a deleted table file. */ +export async function onTableDeleted(host: TableEventsHost, abstractFile: TAbstractFile): Promise { + if (!(abstractFile instanceof TFile)) return; + const tablesPrefix = normalizeFolder(host.settings.tablesFolder); + if (tablesPrefix && !abstractFile.path.startsWith(tablesPrefix + "/")) + return; + + // The table path stored in workflows has no .md extension + const deletedTablePath = abstractFile.path.slice(0, -3); + + const wfPrefix = normalizeFolder(host.settings.workflowsFolder); + const templatesPath = wfPrefix ? `${wfPrefix}/templates` : "templates"; + const workflowFiles = host.app.vault + .getMarkdownFiles() + .filter( + (f) => + (!wfPrefix || f.path.startsWith(wfPrefix + "/")) && + !f.path.startsWith(templatesPath + "/") && + !f.basename.startsWith("_"), + ); + + for (const wfFile of workflowFiles) { + await host.app.vault.process(wfFile, (content) => { + const workflow = parseWorkflow(content, wfFile.basename); + const filtered = workflow.steps.filter( + (s) => s.tablePath !== deletedTablePath, + ); + if (filtered.length === workflow.steps.length) return content; + workflow.steps = filtered; + // Everything else in the note (other columns, text after the table) stays. + return buildWorkflowContent(workflow, { existing: content }); + }); + } +} diff --git a/src/random-tables/workflow.ts b/src/random-tables/workflow.ts index c4e88db6..a5e22333 100644 --- a/src/random-tables/workflow.ts +++ b/src/random-tables/workflow.ts @@ -1,4 +1,6 @@ -import { splitTableRow, escapeTableCell } from "../textUtils"; +import { splitTableRow, escapeTableCell, escapeRegex, placeholderPattern } from "../textUtils"; +import { withFrontmatterEntries, yamlLink } from "../provenance"; + export interface WorkflowStep { kind: "table" | "dice"; tablePath: string; // vault-relative path, no .md extension (kind=table), or "" (kind=dice) @@ -54,102 +56,260 @@ export function rollDiceFormulaWithBreakdown(formula: string): string { return `(${expr})=${total}`; } +// ── The workflow note ─────────────────────────────────────────────────────── +// +// --- +// results-folder: world/results +// template-file: world/workflows/templates/npc.md +// --- +// Optional description. +// +// | Table | Rolls | Label | Die | Fills | +// |-------|-------|-------|-----|-------| +// | [[world/tables/aspects]] | 3 | aspects | d12 | $aspects_1 $aspects_2 $aspects_3 | +// +// Anything after the table is the user's and is kept. +// +// Table, Rolls and Label are the steps; Die and Fills are derived (the +// table's die, the placeholders the step fills) and are ignored on read. +// They come after Label so older builds, which read the first three +// columns, still read the note. Other columns a person adds are kept. + +/** Columns the plugin writes, in order. The first three are the steps. */ +const STEP_COLUMNS = ["Table", "Rolls", "Label"] as const; +const DERIVED_COLUMNS = ["Die", "Fills"] as const; +/** Header names (lower case) the parser accepts for each column. */ +const COLUMN_ALIASES: Record = { + table: "table", source: "table", + rolls: "rolls", roll: "rolls", count: "rolls", times: "rolls", + label: "label", name: "label", + die: "die", dice: "die", + fills: "fills", placeholders: "fills", fill: "fills", +}; + +interface FrontmatterSpan { + /** The YAML between the fences (may be ""). */ + body: string; + /** Where the note after the closing fence starts. */ + end: number; +} + +function findFrontmatter(content: string): FrontmatterSpan | null { + const m = /^---\r?\n([\s\S]*?)\r?\n?---[ \t]*(?:\r?\n|$)/.exec(content); + return m ? { body: m[1], end: m[0].length } : null; +} + +interface StepsTable { + /** Offsets of the header line's start and of the line after the last row. */ + start: number; + end: number; + /** Header cell names as typed. */ + headers: string[]; + /** Column index per known column ("table", "rolls", …). */ + col: Map; + /** Data rows' cells (the separator is skipped). */ + rows: string[][]; +} + +/** + * Find the steps table: the first table whose header has a Table and a + * Rolls column (any case, any order, aliases allowed). + */ +function findStepsTable(content: string, from: number): StepsTable | null { + const lineRe = /[^\n]*(?:\n|$)/g; + lineRe.lastIndex = from; + const lines: { text: string; start: number; end: number }[] = []; + let m: RegExpExecArray | null; + while ((m = lineRe.exec(content)) !== null && m[0] !== "") { + lines.push({ text: m[0].replace(/\r?\n$/, ""), start: m.index, end: m.index + m[0].length }); + } + for (let i = 0; i < lines.length; i++) { + const headers = splitTableRow(lines[i].text); + if (!headers) continue; + const col = new Map(); + headers.forEach((h, idx) => { + const key = COLUMN_ALIASES[h.trim().toLowerCase()]; + if (key && !col.has(key)) col.set(key, idx); + }); + if (!col.has("table") || !col.has("rolls")) continue; + const rows: string[][] = []; + let j = i + 1; + if (j < lines.length && /^\s*\|?[\s:|-]+\|?\s*$/.test(lines[j].text) && lines[j].text.includes("-")) j++; + for (; j < lines.length; j++) { + const cells = splitTableRow(lines[j].text); + if (!cells) break; + rows.push(cells); + } + const end = j < lines.length ? lines[j].start : content.length; + return { start: lines[i].start, end, headers, col, rows }; + } + return null; +} + +/** A step from one row's cells, or null when the row isn't a usable step. */ +function stepFromCells(cells: string[], col: Map): WorkflowStep | null { + const rawTable = cells[col.get("table")!] ?? ""; + const rolls = parseInt(cells[col.get("rolls")!] ?? "", 10); + const label = col.has("label") ? (cells[col.get("label")!] ?? "") : ""; + if (!rawTable.trim() || isNaN(rolls) || rolls < 1) return null; + if (isDiceFormula(rawTable)) { + // Dice step — formula stored directly in the table cell + return { kind: "dice", tablePath: "", diceFormula: rawTable.trim(), rolls, label: label || undefined }; + } + // Table step — extract path from [[link]] syntax or plain text + const linkMatch = /\[\[([^\]|]+)(?:\|[^\]]*)?\]\]/.exec(rawTable); + const tablePath = linkMatch ? linkMatch[1].trim() : rawTable.trim(); + return { kind: "table", tablePath, rolls, label: label || undefined }; +} + +/** What identifies a row's step when the note is rewritten (its table or formula). */ +function stepKey(step: WorkflowStep): string { + return step.kind === "dice" ? `dice:${(step.diceFormula ?? "").toLowerCase()}` : `table:${step.tablePath.replace(/\.md$/i, "").toLowerCase()}`; +} + /** Parse a workflow markdown file into a Workflow. */ export function parseWorkflow(content: string, name: string): Workflow { const workflow: Workflow = { name, steps: [] }; // Extract YAML frontmatter - const fmMatch = /^---\r?\n([\s\S]*?)\r?\n---/.exec(content); - if (fmMatch) { - const fm = fmMatch[1]; - const rfMatch = /^results-folder:\s*(.+)$/m.exec(fm); + const fm = findFrontmatter(content); + if (fm) { + const rfMatch = /^results-folder:\s*(.+)$/m.exec(fm.body); if (rfMatch) workflow.resultsFolder = rfMatch[1].trim(); - const tfMatch = /^template-file:\s*(.+)$/m.exec(fm); + const tfMatch = /^template-file:\s*(.+)$/m.exec(fm.body); if (tfMatch) workflow.templateFile = tfMatch[1].trim(); } - // Extract description: text between frontmatter and the steps table - const tableMatch = /\|\s*Table\s*\|\s*Rolls\s*\|\s*Label\s*\|/i.exec(content); - if (tableMatch) { - const betweenFmAndTable = fmMatch - ? content.slice(fmMatch[0].length, tableMatch.index) - : content.slice(0, tableMatch.index); - const desc = betweenFmAndTable.trim(); - if (desc) workflow.description = desc; - } - if (!tableMatch) return workflow; - - const afterHeader = content.slice(tableMatch.index); - const lines = afterHeader.split("\n"); - - // Skip header line and separator line - for (let i = 2; i < lines.length; i++) { - const line = lines[i].trim(); - if (!line.startsWith("|")) break; - - const cols = splitTableRow(line) ?? []; - if (cols.length < 2) continue; - - const rawTable = cols[0]; - const rolls = parseInt(cols[1], 10); - const label = cols[2] ?? ""; - - if (!rawTable || isNaN(rolls) || rolls < 1) continue; - - if (isDiceFormula(rawTable)) { - // Dice step — formula stored directly in the table cell - workflow.steps.push({ - kind: "dice", - tablePath: "", - diceFormula: rawTable.trim(), - rolls, - label: label || undefined, - }); - } else { - // Table step — extract path from [[link]] syntax or plain text - const linkMatch = /\[\[([^\]|]+)(?:\|[^\]]*)?\]\]/.exec(rawTable); - const tablePath = linkMatch ? linkMatch[1].trim() : rawTable.trim(); - workflow.steps.push({ - kind: "table", - tablePath, - rolls, - label: label || undefined, - }); - } - } + const table = findStepsTable(content, fm?.end ?? 0); + if (!table) return workflow; + + // Description: text between frontmatter and the steps table + const desc = content.slice(fm?.end ?? 0, table.start).trim(); + if (desc) workflow.description = desc; + for (const cells of table.rows) { + const step = stepFromCells(cells, table.col); + if (step) workflow.steps.push(step); + } return workflow; } -/** Serialize a Workflow back to markdown. */ -export function buildWorkflowContent(workflow: Workflow): string { - const lines: string[] = []; +/** The placeholders a step fills, space separated (the Fills column). */ +export function stepFills(step: WorkflowStep): string { + return Array.from({ length: step.rolls }, (_, r) => stepPlaceholder(step, r)).join(" "); +} - // Frontmatter - lines.push("---"); - if (workflow.resultsFolder) lines.push(`results-folder: ${workflow.resultsFolder}`); - if (workflow.templateFile) lines.push(`template-file: ${workflow.templateFile}`); - lines.push("---"); - lines.push(""); +export interface BuildWorkflowOptions { + /** + * The note as it is now. Its other frontmatter, any text after the + * steps table and any extra columns are kept; only the steps, + * description and the two settings are rewritten. + */ + existing?: string; + /** + * The Die cell for a step ("d12"), when known. A dice step shows its + * formula. Without it, the cell the row had is kept. + */ + dieFor?: (step: WorkflowStep) => string | undefined; +} - // Description (optional) - if (workflow.description) { - lines.push(workflow.description); - lines.push(""); +/** Set or remove one `key: value` line in frontmatter YAML (other lines untouched). */ +function setYamlLine(body: string, key: string, value: string | undefined, current: string | undefined): string { + if ((value ?? "") === (current ?? "")) return body; + const lines = body === "" ? [] : body.split(/\r?\n/); + const at = lines.findIndex((l) => new RegExp(`^${key}\\s*:`).test(l)); + if (!value) { + if (at >= 0) lines.splice(at, 1); + } else if (at >= 0) { + lines[at] = `${key}: ${value}`; + } else { + lines.push(`${key}: ${value}`); + } + return lines.join("\n"); +} + +/** Serialize a Workflow back to markdown (see the note format above). */ +export function buildWorkflowContent(workflow: Workflow, opts: BuildWorkflowOptions = {}): string { + const existing = opts.existing?.replace(/\r\n/g, "\n"); + const eol = opts.existing?.includes("\r\n") ? "\r\n" : "\n"; + const fm = existing !== undefined ? findFrontmatter(existing) : null; + const old = existing !== undefined ? findStepsTable(existing, fm?.end ?? 0) : null; + const before = existing !== undefined ? parseWorkflow(existing, workflow.name) : null; + + // Frontmatter: the two settings; any other keys stay as they were. + let fmBody = fm?.body.replace(/\r\n/g, "\n") ?? ""; + if (fm) { + fmBody = setYamlLine(fmBody, "results-folder", workflow.resultsFolder, before?.resultsFolder); + fmBody = setYamlLine(fmBody, "template-file", workflow.templateFile, before?.templateFile); + } else { + fmBody = [ + workflow.resultsFolder ? `results-folder: ${workflow.resultsFolder}` : "", + workflow.templateFile ? `template-file: ${workflow.templateFile}` : "", + ].filter(Boolean).join("\n"); } - // Steps table - lines.push("| Table | Rolls | Label |"); - lines.push("|-------|-------|-------|"); + // Columns: the steps, the derived ones, then any the user added. + const known = new Set(Object.keys(COLUMN_ALIASES)); + const extraCols = old ? old.headers.map((h, i) => ({ name: h, i })).filter(({ name }) => !known.has(name.trim().toLowerCase()) && name.trim() !== "") : []; + const headers = [...STEP_COLUMNS, ...DERIVED_COLUMNS, ...extraCols.map((c) => c.name)]; + + // Each step keeps the extra cells (and last Die) of the row it came from. + const oldRows = (old?.rows ?? []).map((cells) => { + const step = old ? stepFromCells(cells, old.col) : null; + return { key: step ? stepKey(step) : null, cells, used: false }; + }); + const lines: string[] = []; + lines.push(`| ${headers.map(escapeTableCell).join(" | ")} |`); + lines.push(`|${headers.map((h) => "-".repeat(Math.max(3, h.length + 2))).join("|")}|`); for (const step of workflow.steps) { + const key = stepKey(step); + const row = oldRows.find((r) => !r.used && r.key === key); + if (row) row.used = true; const tableCell = step.kind === "dice" ? (step.diceFormula ?? "") : `[[${step.tablePath}]]`; - const label = escapeTableCell(step.label ?? ""); - lines.push(`| ${escapeTableCell(tableCell)} | ${step.rolls} | ${label} |`); + const oldDie = row && old?.col.has("die") ? row.cells[old.col.get("die")!] : undefined; + const die = step.kind === "dice" ? (step.diceFormula ?? "") : (opts.dieFor?.(step) ?? oldDie ?? ""); + const cells = [ + tableCell, + String(step.rolls), + step.label ?? "", + die, + stepFills(step), + ...extraCols.map((c) => row?.cells[c.i] ?? ""), + ]; + lines.push(`| ${cells.map(escapeTableCell).join(" | ")} |`); } + const table = lines.join("\n") + "\n"; - return lines.join("\n") + "\n"; + const withFm = existing === undefined || fm !== null || fmBody !== ""; + let out = withFm ? `---\n${fmBody ? fmBody + "\n" : ""}---\n\n` : ""; + out += (workflow.description ? `${workflow.description}\n\n` : "") + table; + if (existing !== undefined) { + // Whatever followed the table is the user's, kept as typed. A note + // with no steps table keeps its whole body, after the new table. + if (old) out += existing.slice(old.end); + else { + const body = existing.slice(fm?.end ?? 0).replace(/^\s*\n/, ""); + if (body.trim()) out += "\n" + body; + } + } + return eol === "\n" ? out : out.replace(/\n/g, "\r\n"); +} + +/** + * The note a workflow's `template-file` names, as paths to try: the value + * as typed (quotes and `[[ ]]` removed), then with ".md". Hand-set values + * like `"[[npc template]]"` work too (the caller can resolve the link). + */ +export function templateFileCandidates(raw: string | undefined): string[] { + if (!raw) return []; + let v = raw.trim().replace(/^["']|["']$/g, "").trim(); + const link = /^\[\[([^\]|#]+)(?:[#|][^\]]*)?\]\]$/.exec(v); + if (link) v = link[1].trim(); + v = v.replace(/^\/+/, ""); + if (!v) return []; + return /\.md$/i.test(v) ? [v] : [v, `${v}.md`]; } /** Derive the variable base name for a step: label if set, else table basename or sanitized formula. */ @@ -197,3 +357,169 @@ export function requiredPlaceholders(steps: WorkflowStep[]): string[] { } return placeholders; } + +/** + * A filled-in workflow made safe to add under one "### section" of a hex + * note (PA2): its headings become bold lines and its "---" rules go, since + * either would end the section early (sections.ts sectionText). + */ +export function workflowResultAsSectionText(text: string): string { + return text + .replace(/\r\n/g, "\n") + .split("\n") + .filter((line) => !/^\s*(?:-{3,}|\*{3,}|_{3,})\s*$/.test(line)) + .map((line) => { + const h = /^\s*#{1,6}\s+(.*?)\s*#*\s*$/.exec(line); + return h ? (h[1] ? `**${h[1]}**` : "") : line; + }) + .join("\n") + .replace(/\n{3,}/g, "\n\n") + .trim(); +} + +// ── Templates ─────────────────────────────────────────────────────────────── + +/** Heading for a step's block in a template: its label, else table name or formula. */ +function stepHeading(step: WorkflowStep, index: number): string { + if (step.label) return step.label; + if (step.kind === "dice") return step.diceFormula ?? `Step ${index + 1}`; + return step.tablePath.split("/").pop() || `Table ${index + 1}`; +} + +/** Is this placeholder written in the template (as a whole token)? */ +function hasPlaceholder(template: string, placeholder: string): boolean { + return new RegExp(placeholderPattern(placeholder)).test(template); +} + +/** + * `$tokens` in a template that no step fills, in order, once each (the + * wizard would leave them as typed). Money like "$5" isn't a token. + */ +export function unfilledTokens(template: string, steps: WorkflowStep[]): string[] { + const known = requiredPlaceholders(steps).sort((a, b) => b.length - a.length); + const out: string[] = []; + const re = /\$(?:\([^)\s]*\)(?:_\d+)?|[A-Za-z_]\w*(?:-\w+)*)/g; + let m: RegExpExecArray | null; + while ((m = re.exec(template)) !== null) { + const at = m.index; + const hit = known.find((p) => template.startsWith(p, at) && !/\w/.test(template[at + p.length] ?? "")); + if (hit) { + re.lastIndex = at + hit.length; + continue; + } + if (!out.includes(m[0])) out.push(m[0]); + } + return out; +} + +/** + * Bring a template in line with the steps: a step none of whose + * placeholders are in it gets a "## label" block at the end; a step with + * some missing gets them after its last one. Nothing is removed or + * rewritten. Returns the placeholders added. + */ +export function reconcileTemplate(template: string, steps: WorkflowStep[]): { template: string; added: string[] } { + let t = template; + const added: string[] = []; + steps.forEach((step, i) => { + const all = Array.from({ length: step.rolls }, (_, r) => stepPlaceholder(step, r)); + const present = all.filter((p) => hasPlaceholder(t, p)); + const missing = all.filter((p) => !present.includes(p)); + if (!missing.length) return; + added.push(...missing); + if (!present.length) { + const block = [`## ${stepHeading(step, i)}`, "", ...missing, ""].join("\n"); + t = t.trim() ? `${t.trimEnd()}\n\n${block}` : block; + return; + } + const last = present[present.length - 1]; + const re = new RegExp(placeholderPattern(last), "g"); + let end = -1; + let m: RegExpExecArray | null; + while ((m = re.exec(t)) !== null) end = m.index + m[0].length; + t = `${t.slice(0, end)}\n${missing.join("\n")}${t.slice(end)}`; + }); + return { template: t, added }; +} + +/** A value filled into a template: its text, and the note it links to, if any. */ +export interface FilledValue { + text: string; + /** Link text of the note the result is (a linked table row). */ + link?: string; +} + +/** A wiki-link to `link` that reads as `text` (escaped inside a table row). */ +function linkMarkup(link: string, text: string, inTableRow: boolean): string { + const shown = text.replace(/[[\]|]/g, "").trim(); + const base = link.split("/").pop() ?? link; + if (!shown || shown === link || (shown === base && base === link)) return `[[${link}]]`; + return `[[${link}${inTableRow ? "\\|" : "|"}${shown}]]`; +} + +/** + * Fill a workflow template. Like fillPlaceholders, plus links: a linked + * result goes in as a link, and where the template already wraps the + * placeholder in `[[ ]]` (older templates did, to link the bare name), + * only the link target goes in. + */ +export function fillWorkflowTemplate(template: string, values: Map): string { + if (!values.size) return template; + const keys = [...values.keys()].sort((a, b) => b.length - a.length); + const re = new RegExp(`(\\[\\[)?(?:${keys.map(escapeRegex).join("|")})(?![\\w])`, "g"); + return template.replace(re, (m: string, open: string | undefined, offset: number) => { + const ph = open ? m.slice(2) : m; + const v = values.get(ph); + if (!v) return m; + if (open) { + const rest = template.slice(offset + m.length); + return "[[" + (/^(?:\]\]|\||#)/.test(rest) ? (v.link ?? v.text) : v.text); + } + if (!v.link) return v.text; + const lineStart = template.lastIndexOf("\n", offset - 1) + 1; + const inTableRow = template.slice(lineStart, offset).trimStart().startsWith("|"); + return linkMarkup(v.link, v.text, inTableRow); + }); +} + +// ── Results notes ─────────────────────────────────────────────────────────── + +/** One rolled slot, for the results note's Rolls table. */ +export interface RollRecord { + placeholder: string; + /** Markdown: a link to the table, or the dice formula. */ + source: string; + /** "d12", a dice formula, or "" (no die). */ + die: string; + /** The face rolled, a dice breakdown, "picked"/"typed", or "" (a weighted pick). */ + roll: string; + /** The result as it went into the note (markdown). */ + result: string; +} + +/** The `## Rolls` table: what each placeholder got and how. */ +export function rollsSection(records: RollRecord[]): string { + const cell = (s: string) => escapeTableCell(s.replace(/\s*\r?\n\s*/g, " ").trim()) || "—"; + const lines = [ + "## Rolls", + "", + "| Placeholder | Source | Die | Roll | Result |", + "|-------------|--------|-----|------|--------|", + ...records.map((r) => `| \`${r.placeholder}\` | ${cell(r.source)} | ${cell(r.die)} | ${cell(r.roll)} | ${cell(r.result)} |`), + ]; + return lines.join("\n") + "\n"; +} + +/** + * A workflow results note: the filled template with `workflow` and + * `rolled` in its frontmatter (merged into the template's own, if it has + * one) and the Rolls table at the end. + */ +export function buildResultsNote(filled: string, meta: { workflowPath: string; rolled: string }, records: RollRecord[]): string { + const withMeta = withFrontmatterEntries(filled, [ + ["workflow", yamlLink(meta.workflowPath)], + ["rolled", meta.rolled], + ]); + const body = withMeta.replace(/\s*$/, ""); + return records.length ? `${body}\n\n${rollsSection(records)}` : `${body}\n`; +} diff --git a/src/random-tables/workflowFiles.ts b/src/random-tables/workflowFiles.ts new file mode 100644 index 00000000..889809a7 --- /dev/null +++ b/src/random-tables/workflowFiles.ts @@ -0,0 +1,131 @@ +import { TFile, type App } from "obsidian"; +import { templateFileCandidates, type WorkflowStep } from "./workflow"; +import { dieLabel, parseRandomTable } from "./randomTable"; +import { isFolderInside, isNoteInside, noteFileName } from "../vault/safePaths"; +import { ensureFolder } from "../vault/ensureFolder"; +import { contentFolder, worldFolderOf } from "../notePickers"; + +/** + * The note a workflow's `template-file` names, however it was typed (a + * path with or without ".md", a quoted wiki-link), or null. Only Markdown + * notes count: a template is text, never an image or a PDF. + */ +export function resolveWorkflowTemplate(app: App, raw: string | undefined, sourcePath: string): TFile | null { + const candidates = templateFileCandidates(raw); + const isNote = (f: unknown): f is TFile => f instanceof TFile && f.extension.toLowerCase() === "md"; + for (const p of candidates) { + const f = app.vault.getAbstractFileByPath(p); + if (isNote(f)) return f; + } + if (candidates[0]) { + const linked = app.metadataCache.getFirstLinkpathDest(candidates[0].replace(/\.md$/i, ""), sourcePath); + if (isNote(linked)) return linked; + } + return null; +} + +/** + * The folders the workflow editor may write a template in: the workflows + * folder and the world folder. A `template-file` comes from note text (a + * pack, a synced vault), so it must not aim the editor's save at any + * other note. + */ +export function templateRoots(settings: { worldFolder?: string; workflowsFolder?: string }): string[] { + return [contentFolder(settings, "workflowsFolder"), worldFolderOf(settings)]; +} + +/** Whether the workflow editor may write a template at `path` (a safe .md path under `roots`). */ +export function isWritableTemplate(path: string, roots: readonly string[]): boolean { + return isNoteInside(path, roots); +} + +/** What the template's save should do, given the text read at open and the text on disk now. */ +export type TemplateSave = "skip" | "write" | "stale"; + +/** + * The workflow editor's template save: nothing when the text wasn't + * changed, a write when the note on disk is still what was read at open + * (`null` = there was no note), else "stale" (it was edited elsewhere + * meanwhile, so the save would overwrite that: refuse, never merge + * silently). + */ +export function templateSave(readAtOpen: string | null, edited: string, onDiskNow: string | null): TemplateSave { + if (readAtOpen !== null && edited === readAtOpen) return "skip"; + return onDiskNow === readAtOpen ? "write" : "stale"; +} + +/** Where a new template file goes for a hand-set `template-file` that doesn't exist yet. */ +export function newTemplatePath(raw: string | undefined): string | null { + const candidates = templateFileCandidates(raw); + return candidates.length ? candidates[candidates.length - 1] : null; +} + +/** + * Save the workflow editor's template text to `target` (the note read at + * open, or the path a new one goes to). Nothing is written when the text + * wasn't changed; "stale" (nothing written) when the note was changed or + * made elsewhere since `atOpen` was read, checked again inside the write. + */ +export async function saveWorkflowTemplate(app: App, target: TFile | string, atOpen: string | null, text: string): Promise { + const path = target instanceof TFile ? target.path : target; + const now = app.vault.getAbstractFileByPath(path); + const onDisk = now instanceof TFile ? await app.vault.read(now) : null; + let verdict = templateSave(atOpen, text, onDisk); + if (verdict !== "write") return verdict; + if (now instanceof TFile) { + await app.vault.process(now, (current) => { + if (current === atOpen) return text; + verdict = "stale"; + return current; + }); + return verdict; + } + const dir = path.includes("/") ? path.slice(0, path.lastIndexOf("/")) : ""; + if (dir) await ensureFolder(app.vault, dir); + await app.vault.create(path, text); + return verdict; +} + +/** + * Where "Save as note" in the workflow wizard puts a result: the typed + * name cleaned into a file name, in the results folder. The folder comes + * pre-filled from the workflow note (maybe someone else's pack), so it + * must be inside the world folder and not hidden; blank is the vault root. + */ +export function resultsNotePlace( + folderText: string, + nameText: string, + settings: { worldFolder?: string }, +): { folder: string; name: string } | { error: string } { + const folder = folderText.trim().replace(/\/+/g, "/").replace(/^\/+|\/+$/g, ""); + const world = worldFolderOf(settings); + if (folder && !isFolderInside(folder, [world])) return { error: `Save the note inside the world folder (${world}).` }; + const name = noteFileName(nameText); + if (!name) return { error: "Note name is required." }; + return { folder, name }; +} + +/** A table step's table file (exact path first, then link resolution). */ +export function resolveStepTable(app: App, step: WorkflowStep, sourcePath: string): TFile | null { + if (step.kind !== "table" || !step.tablePath) return null; + const f = + app.vault.getAbstractFileByPath(step.tablePath + ".md") ?? + app.metadataCache.getFirstLinkpathDest(step.tablePath, sourcePath); + return f instanceof TFile ? f : null; +} + +/** Each table step's die ("d12", "" without one), by table path; for the Die column. */ +export async function stepDieLabels(app: App, steps: WorkflowStep[], sourcePath: string): Promise> { + const out = new Map(); + for (const step of steps) { + if (step.kind !== "table" || out.has(step.tablePath)) continue; + const file = resolveStepTable(app, step, sourcePath); + if (!file) continue; + try { + out.set(step.tablePath, dieLabel(parseRandomTable(await app.vault.cachedRead(file)).dice)); + } catch { + /* unreadable: the row keeps the die it had */ + } + } + return out; +} diff --git a/src/regionMapData.ts b/src/regionMapData.ts new file mode 100644 index 00000000..10b88fd7 --- /dev/null +++ b/src/regionMapData.ts @@ -0,0 +1,183 @@ +/** + * The "Map data" callout in a region or faction note (R1): where the map + * uses it, written into the note so the raw text shows it. + * + * > [!hexmaker] Map data + * > Maps: [[_the-coast|The Coast]] (12 hexes), [[_hills|Hills]] (1 hex) + * > Encounter table: [[world/tables/regions/Dustbowl|Dustbowl]] + * + * Regions: the hexes whose Region is this note's name, per map, and the + * region's encounter table. Factions: the hex notes that link the faction, + * per map. The map notes and hex notes are the truth; this is a copy the + * plugin refreshes when the note is opened and by the "Update map data in + * region and faction notes" command (which also adds it to notes that + * lack one). Hand edits inside it are overwritten; nothing outside it is + * touched. Pure: no Obsidian imports. + */ + +import { MAP_DATA_CALLOUT } from "./hexMapData"; + +export interface MapUse { + /** Map (folder) name, for the link to its map note. */ + map: string; + /** The map's display name. */ + label: string; + hexes: number; +} + +export interface RegionMapDataView { + kind: "region" | "faction"; + /** Maps using it, with how many hexes (maps with none left out). */ + maps: MapUse[]; + /** Regions: link text of the region's encounter table, if it has one. */ + encounterTable?: string; +} + +const NONE = "—"; +const clean = (s: string) => s.replace(/[|[\]]/g, ""); + +/** The callout's lines. */ +export function regionMapDataLines(v: RegionMapDataView): string[] { + const maps = v.maps.length + ? v.maps.map((m) => `[[_${m.map}|${clean(m.label)}]] (${m.hexes} ${m.hexes === 1 ? "hex" : "hexes"})`).join(", ") + : NONE; + const lines = [`> ${MAP_DATA_CALLOUT} Map data`, `> Maps: ${maps}`]; + if (v.kind === "region") { + const t = v.encounterTable; + lines.push(`> Encounter table: ${t ? `[[${t}|${clean(t.split("/").pop() ?? t)}]]` : NONE}`); + } + return lines; +} + +interface Span { start: number; end: number } + +function findCallout(lines: string[]): Span | null { + const start = lines.findIndex((l) => /^\s*>\s*\[!hexmaker\]/i.test(l)); + if (start < 0) return null; + let end = start + 1; + while (end < lines.length && /^\s*>/.test(lines[end])) end++; + return { start, end }; +} + +/** Does the note have a Map data callout? */ +export function hasRegionMapData(content: string): boolean { + return findCallout(content.replace(/\r\n?/g, "\n").split("\n")) !== null; +} + +/** + * The note with its Map data callout showing `v`. Without one, the note is + * returned unchanged unless `insert`, when the callout goes under the + * title (or the frontmatter). Unchanged content is returned as is. + */ +export function setRegionMapData(content: string, v: RegionMapDataView, insert = false): string { + const eol = content.includes("\r\n") ? "\r\n" : "\n"; + const lines = content.replace(/\r\n?/g, "\n").split("\n"); + const block = regionMapDataLines(v); + const span = findCallout(lines); + if (span) { + const current = lines.slice(span.start, span.end); + if (current.length === block.length && current.every((l, i) => l.trimEnd() === block[i])) return content; + lines.splice(span.start, span.end - span.start, ...block); + return lines.join(eol); + } + if (!insert) return content; + let at = 0; + if (lines[0]?.trim() === "---") { + const close = lines.findIndex((l, i) => i > 0 && l.trim() === "---"); + if (close > 0) at = close + 1; + } + const title = lines.findIndex((l, i) => i >= at && /^#\s/.test(l)); + if (title >= 0) at = title + 1; + const before = at > 0 && lines[at - 1]?.trim() !== "" ? [""] : []; + const after = lines[at] !== undefined && lines[at].trim() !== "" ? [""] : []; + lines.splice(at, 0, ...before, ...block, ...after); + return lines.join(eol); +} + +/** + * How many hexes of each map have this region (by name, ignoring case and + * a [[link]] around it). Maps are in the order given; maps with none are + * left out. + */ +export function regionUse( + region: string, + maps: { name: string; label: string }[], + hexesOf: (map: string) => Iterable<{ region?: string }>, +): MapUse[] { + const want = normRegion(region); + const out: MapUse[] = []; + const seen = new Set(); + for (const m of maps) { + if (seen.has(m.name)) continue; + seen.add(m.name); + let n = 0; + for (const h of hexesOf(m.name)) if (h.region && normRegion(h.region) === want) n++; + if (n) out.push({ map: m.name, label: m.label, hexes: n }); + } + return out; +} + +/** A Region value compared by name: "[[regions/Dustbowl|Dust]]" and "dustbowl" are the same. */ +export function normRegion(v: string): string { + const link = /^\s*\[\[([^\]|#]+)(?:[#|][^\]]*)?\]\]\s*$/.exec(v); + const name = link ? link[1].split("/").pop()! : v; + return name.replace(/\.md$/i, "").trim().toLowerCase(); +} + +/** + * The Region value to write when a region note is renamed, or null when + * `value` isn't that region. A plain name becomes the new name; a link + * keeps its form with the new name (Obsidian's own link updating covers + * links in note text, not values in map notes). + */ +export function renamedRegionValue(value: string, oldName: string, newName: string): string | null { + if (normRegion(value) !== normRegion(oldName)) return null; + const link = /^(\s*\[\[)([^\]|#]+)((?:[#|][^\]]*)?\]\]\s*)$/.exec(value); + if (!link) return newName; + const parts = link[2].split("/"); + parts[parts.length - 1] = newName; + return `${link[1]}${parts.join("/")}${link[3]}`; +} + +/** + * The `token-map` value after a map is renamed, or null when it names + * another map. Accepts the map's name or a link to its map note + * ("[[_name]]"), keeping the form it found. + */ +export function renamedTokenMap(value: unknown, oldName: string, newName: string): string | null { + if (typeof value !== "string") return null; + if (value.trim() === oldName) return newName; + const link = /^(\s*\[\[)([^\]|#]+)((?:[#|][^\]]*)?\]\]\s*)$/.exec(value); + if (!link) return null; + const parts = link[2].split("/"); + const base = parts[parts.length - 1].replace(/\.md$/i, ""); + if (base !== `_${oldName}` && base !== oldName) return null; + parts[parts.length - 1] = base.startsWith("_") ? `_${newName}` : newName; + return `${link[1]}${parts.join("/")}${link[3]}`; +} + +/** What renameRegionInStore needs from the map store (its public reads and set). */ +export interface RegionStore { + all(map: string): ReadonlyMap; + set(map: string, key: string, patch: { region?: string | null }): void; +} + +/** + * A region note was renamed: every hex whose Region named it gets the new + * name, through the store's set (so the map notes are rewritten the usual + * way). Returns how many hexes changed. + */ +export function renameRegionInStore(store: RegionStore, maps: string[], oldName: string, newName: string): number { + if (!oldName || !newName || oldName === newName) return 0; + let n = 0; + for (const map of new Set(maps)) { + for (const [key, h] of [...store.all(map)]) { + if (!h.region) continue; + const next = renamedRegionValue(h.region, oldName, newName); + if (next === null || next === h.region) continue; + store.set(map, key, { region: next }); + n++; + } + } + return n; +} diff --git a/src/regionTables.ts b/src/regionTables.ts new file mode 100644 index 00000000..0f502af2 --- /dev/null +++ b/src/regionTables.ts @@ -0,0 +1,67 @@ +import type { MapData } from "./types"; + +/** + * Weather and rumours come from tables attached to the region (the map), not + * to each hex (E2): a map note can name a weather table and a rumours table, + * and a hex can override either by linking its own table in its note (under + * "### Weather Table" / "### Rumors Table", like the Encounters Table). With + * neither, the starter table in the tables folder is used if it exists + * (shipped as data by the World module, src/modules/world/tables). + */ + +export type RolledSection = "weather" | "hooks & rumors"; + +export interface RolledSectionTables { + /** MapData field holding the region's table. */ + mapField: "weatherTable" | "rumorsTable"; + /** Link section in the hex note for a per-hex table. */ + hexSection: string; + /** Starter table file name in the tables folder. */ + starterFile: string; + /** Plain name used in UI text. */ + noun: string; +} + +export const ROLLED_SECTION_TABLES: Record = { + weather: { mapField: "weatherTable", hexSection: "Weather Table", starterFile: "weather.md", noun: "weather" }, + "hooks & rumors": { mapField: "rumorsTable", hexSection: "Rumors Table", starterFile: "rumors.md", noun: "rumours" }, +}; + +export function isRolledSection(key: string): key is RolledSection { + return key === "weather" || key === "hooks & rumors"; +} + +export type TableSource = "hex" | "map" | "starter"; + +export interface PickedTable { + path: string; + source: TableSource; +} + +/** + * The table to roll for a section: the hex's own link wins, then the map's + * table, then the starter table. Paths that don't exist are skipped (a + * renamed or deleted table falls through to the next one). + */ +export function pickSectionTable( + candidates: { hex?: string | null; map?: string | null; starter?: string | null }, + exists: (path: string) => boolean, +): PickedTable | null { + for (const source of ["hex", "map", "starter"] as const) { + const p = candidates[source]; + if (p && exists(p)) return { path: p, source }; + } + return null; +} + +/** The map's table for a section (undefined when unset or blank). */ +export function mapSectionTable(map: Pick | undefined, section: RolledSection): string | undefined { + const v = map?.[ROLLED_SECTION_TABLES[section].mapField]; + return v && v.trim() ? v : undefined; +} + +/** Starter-table path in the tables folder ("" = vault root). */ +export function starterTablePath(tablesFolder: string, section: RolledSection): string { + const file = ROLLED_SECTION_TABLES[section].starterFile; + return tablesFolder ? `${tablesFolder}/${file}` : file; +} diff --git a/src/safetyMode.ts b/src/safetyMode.ts deleted file mode 100644 index d2d1d661..00000000 --- a/src/safetyMode.ts +++ /dev/null @@ -1,79 +0,0 @@ -import { ItemView, WorkspaceLeaf } from "obsidian"; -import { isMapNoteText } from "./dataStamp"; - -/** - * Read-only safety mode, for a vault updated by a newer version (see - * dataStamp.ts). The plugin's views are replaced by this one, which only - * says what happened; nothing in here writes to the vault. - */ -export class SafetyModeView extends ItemView { - constructor( - leaf: WorkspaceLeaf, - private readonly viewType: string, - private readonly title: string, - private readonly message: () => string, - ) { - super(leaf); - } - - getViewType(): string { - return this.viewType; - } - - getDisplayText(): string { - return this.title; - } - - getIcon(): string { - return "alert-triangle"; - } - - onOpen(): Promise { - const el = this.contentEl; - el.empty(); - el.addClass("duckmage-safety-view"); - el.createEl("h3", { text: "Read-only on this device" }); - el.createEl("p", { text: this.message() }); - el.createEl("p", { - text: "Update the plugin from the community plugins settings (check for updates), then reload Obsidian.", - }); - return Promise.resolve(); - } -} - -/** The read-only file access the map-note check needs (Obsidian's DataAdapter fits). */ -export interface ReadOnlyAdapter { - exists(path: string): Promise; - list(path: string): Promise<{ files: string[]; folders: string[] }>; - read(path: string): Promise; -} - -/** Is `path` a possible map note: `{hexFolder}/{folder}/_{name}.md`? */ -export function isMapNotePath(path: string, hexFolder: string): boolean { - if (!hexFolder || !path.startsWith(hexFolder + "/")) return false; - const rest = path.slice(hexFolder.length + 1).split("/"); - return rest.length === 2 && /^_.+\.md$/i.test(rest[1]); -} - -/** - * Does the hex folder hold a map note written by a newer version? Reads the - * files directly (works before the metadata cache is ready, and when - * data.json isn't synced but the notes are). Never writes. - */ -export async function hasNewerMapNotes(adapter: ReadOnlyAdapter, hexFolder: string): Promise { - if (!hexFolder) return false; - try { - if (!(await adapter.exists(hexFolder))) return false; - const { folders } = await adapter.list(hexFolder); - for (const folder of folders) { - const { files } = await adapter.list(folder); - for (const file of files) { - if (!isMapNotePath(file, hexFolder)) continue; - if (isMapNoteText(await adapter.read(file))) return true; - } - } - } catch { - // Unreadable folder: nothing to go on. - } - return false; -} diff --git a/src/sandbox.ts b/src/sandbox.ts new file mode 100644 index 00000000..7e4abd71 --- /dev/null +++ b/src/sandbox.ts @@ -0,0 +1,2 @@ +/** The marker file at a sandbox vault's root (dev/demo-world.mjs): dev helpers are offered only there. */ +export const SANDBOX_MARKER = ".hexmaker-sandbox"; diff --git a/src/sections.ts b/src/sections.ts index 752ee29c..d0dd5ec0 100644 --- a/src/sections.ts +++ b/src/sections.ts @@ -1,160 +1,377 @@ -import { App, TFile } from "obsidian"; -import { escapeRegex } from "./textUtils"; - -/** Insert a wiki-link under the named ### section, creating the section if absent. */ -export async function addLinkToSection(app: App, filePath: string, section: string, linkText: string): Promise { - const file = app.vault.getAbstractFileByPath(filePath); - if (!(file instanceof TFile)) return; - await app.vault.process(file, (content) => { - const headingRegex = new RegExp(`^###\\s+${escapeRegex(section)}\\s*$`, "mi"); - const match = headingRegex.exec(content); - if (!match) { - return content.trimEnd() + `\n\n### ${section}\n\n${linkText}\n`; - } - const afterHeading = match.index + match[0].length; - const nextBoundaryMatch = /\n(?:#{1,6} |-{3,})/m.exec(content.slice(afterHeading)); - const sectionEnd = nextBoundaryMatch ? afterHeading + nextBoundaryMatch.index : content.length; - const sectionContent = content.slice(afterHeading, sectionEnd); - if (sectionContent.includes(linkText)) return content; - const trimmedSection = sectionContent.trimEnd(); - const insertAt = afterHeading + trimmedSection.length; - return content.slice(0, insertAt) + "\n\n" + linkText + content.slice(insertAt); - }); -} - -/** Remove a wiki-link from under the named ### section. Removes the whole line containing it. */ -export async function removeLinkFromSection(app: App, filePath: string, section: string, linkTarget: string): Promise { - const file = app.vault.getAbstractFileByPath(filePath); - if (!(file instanceof TFile)) return; - await app.vault.process(file, (content) => { - const headingRegex = new RegExp(`^###\\s+${escapeRegex(section)}\\s*$`, "mi"); - const match = headingRegex.exec(content); - if (!match) return content; - const afterHeading = match.index + match[0].length; - const nextBoundaryMatch = /\n(?:#{1,6} |-{3,})/m.exec(content.slice(afterHeading)); - const sectionEnd = nextBoundaryMatch ? afterHeading + nextBoundaryMatch.index : content.length; - const escapedTarget = linkTarget.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); - const lineRegex = new RegExp(`\\n[^\\n]*\\[\\[${escapedTarget}(?:\\|[^\\]]+)?\\]\\][^\\n]*`, "g"); - const sectionBody = content.slice(afterHeading, sectionEnd); - const newBody = sectionBody.replace(lineRegex, ""); - return content.slice(0, afterHeading) + newBody + content.slice(sectionEnd); - }); -} - -/** Return all wiki-link targets found under a named ### section. */ -export async function getLinksInSection(app: App, filePath: string, section: string): Promise { - const file = app.vault.getAbstractFileByPath(filePath); - if (!(file instanceof TFile)) return []; - const content = await app.vault.read(file); - - const headingRegex = new RegExp(`^###\\s+${escapeRegex(section)}\\s*$`, "mi"); - const match = headingRegex.exec(content); - if (!match) return []; - - const afterHeading = match.index + match[0].length; - const nextBoundaryMatch = /\n(?:#{1,6} |-{3,})/m.exec(content.slice(afterHeading)); - const sectionEnd = nextBoundaryMatch ? afterHeading + nextBoundaryMatch.index : content.length; - const sectionContent = content.slice(afterHeading, sectionEnd); - - const links: string[] = []; - const linkRegex = /\[\[([^\]|]+)(?:\|[^\]]+)?\]\]/g; - let m; - while ((m = linkRegex.exec(sectionContent)) !== null) { - links.push(m[1]); - } - return links; -} - -/** Return the plain text body of a named ### section (stops at next heading or ---). */ -export async function getSectionContent(app: App, filePath: string, section: string): Promise { - const file = app.vault.getAbstractFileByPath(filePath); - if (!(file instanceof TFile)) return ""; - const content = await app.vault.read(file); - - const headingRegex = new RegExp(`^###\\s+${escapeRegex(section)}\\s*$`, "mi"); - const match = headingRegex.exec(content); - if (!match) return ""; - - const afterHeading = match.index + match[0].length; - const nextBoundary = /\n(?:#{1,6} |-{3,})/m.exec(content.slice(afterHeading)); - const sectionEnd = nextBoundary ? afterHeading + nextBoundary.index : content.length; - return content.slice(afterHeading, sectionEnd).trim(); -} - -/** Read a file once and return all text and link section content in a single pass. */ -export async function getAllSectionData( - app: App, - filePath: string, - preloadedContent?: string, -): Promise<{ text: Map; links: Map }> { - const text = new Map(); - const links = new Map(); - const file = app.vault.getAbstractFileByPath(filePath); - if (!(file instanceof TFile)) return { text, links }; - const content = preloadedContent ?? await app.vault.read(file); - - // Find every ### heading and capture the body up to the next boundary - const headingRegex = /^###\s+(.+?)\s*$/gm; - const boundaryRegex = /\n(?:#{1,6} |-{3,})/m; - const linkRegex = /\[\[([^\]|]+)(?:\|[^\]]+)?\]\]/g; - let m: RegExpExecArray | null; - while ((m = headingRegex.exec(content)) !== null) { - const name = m[1].toLowerCase(); - const afterHeading = m.index + m[0].length; - const nextBoundary = boundaryRegex.exec(content.slice(afterHeading)); - const sectionEnd = nextBoundary ? afterHeading + nextBoundary.index : content.length; - const body = content.slice(afterHeading, sectionEnd); - - // Collect wiki-links - const sectionLinks: string[] = []; - let lm: RegExpExecArray | null; - const lr = new RegExp(linkRegex.source, "g"); - while ((lm = lr.exec(body)) !== null) sectionLinks.push(lm[1]); - - links.set(name, sectionLinks); - text.set(name, body.trim()); - } - return { text, links }; -} - -/** - * Append a backlink to hexFilePath at the end of targetFilePath, unless - * a link to the hex file already exists anywhere in the target note. - */ -export async function addBacklinkToFile(app: App, targetFilePath: string, hexFilePath: string): Promise { - const hexFile = app.vault.getAbstractFileByPath(hexFilePath); - const targetFile = app.vault.getAbstractFileByPath(targetFilePath); - if (!(hexFile instanceof TFile) || !(targetFile instanceof TFile)) return; - - // Skip if the target already links back to the hex - const cache = app.metadataCache.getFileCache(targetFile); - const alreadyLinked = cache?.links?.some( - l => app.metadataCache.getFirstLinkpathDest(l.link, targetFilePath) === hexFile, - ); - if (alreadyLinked) return; - - const linkText = `[[${app.metadataCache.fileToLinktext(hexFile, targetFilePath)}]]`; - await app.vault.process(targetFile, (content) => - content.trimEnd() + (content.trim() ? "\n\n" : "") + linkText + "\n", - ); -} - -/** Replace the body of a named ### section in-place, creating the section if absent. */ -export async function setSectionContent(app: App, filePath: string, section: string, newText: string): Promise { - const file = app.vault.getAbstractFileByPath(filePath); - if (!(file instanceof TFile)) return; - await app.vault.process(file, (content) => { - const headingRegex = new RegExp(`^###\\s+${escapeRegex(section)}\\s*$`, "mi"); - const match = headingRegex.exec(content); - if (!match) { - return newText.trim() - ? content.trimEnd() + `\n\n### ${section}\n${newText.trim()}\n` - : content; - } - const afterHeading = match.index + match[0].length; - const nextBoundary = /\n(?:#{1,6} |-{3,})/m.exec(content.slice(afterHeading)); - const sectionEnd = nextBoundary ? afterHeading + nextBoundary.index : content.length; - const replacement = newText.trim() ? `\n${newText.trim()}\n` : "\n"; - return content.slice(0, afterHeading) + replacement + content.slice(sectionEnd); - }); -} +import { App, TFile } from "obsidian"; +import { splitGuidance } from "./hexGuidance"; +import { escapeRegex } from "./textUtils"; +import { LINK_SECTIONS, ROLLED_TEXT_SECTIONS, TEXT_SECTIONS } from "./types"; + +/** + * Other names people give the plugin's sections. A note's own heading is + * matched to a section by these, in any case, at any heading level from ## + * to ###### (# is the note's title), with a trailing colon or "and" for "&" + * allowed, so a hand-written "## Encounters" or "#### Rumours:" is the + * section the plugin shows and writes to, not a duplicate it appends. + */ +const SECTION_ALIASES: Record = { + "encounters table": ["encounters", "encounter table", "encounter", "random encounters"], + "hooks & rumors": ["hooks & rumours", "rumors", "rumours", "hooks", "rumors & hooks", "rumours & hooks"], + "description": ["desc"], + "landmark": ["landmarks"], + "towns": ["town", "settlements", "settlement"], + "dungeons": ["dungeon"], + "features": ["feature"], + "quests": ["quest"], + "factions": ["faction"], +}; + +const normalizeHeading = (s: string): string => + s.trim().replace(/[::]+$/, "").replace(/\s+and\s+/gi, " & ").replace(/\s+/g, " ").toLowerCase(); + +const ALIAS_TO_SECTION = new Map(); +for (const [section, aliases] of Object.entries(SECTION_ALIASES)) for (const a of aliases) ALIAS_TO_SECTION.set(a, section); + +/** The section a heading names: one of the plugin's (by alias) or the heading itself, lowercased. */ +export function canonicalSection(heading: string): string { + const h = normalizeHeading(heading); + return ALIAS_TO_SECTION.get(h) ?? h; +} + +/** The plugin's own sections (link and text), canonical keys. */ +const PLUGIN_SECTIONS = new Set([ + ...LINK_SECTIONS.map((s) => s.toLowerCase()), + ...TEXT_SECTIONS.map((s) => s.key), + ...ROLLED_TEXT_SECTIONS.map((s) => s.key), +]); + +/** Whether a heading names one of the plugin's sections (by name or alias). */ +export function isPluginSection(heading: string): boolean { + return PLUGIN_SECTIONS.has(canonicalSection(heading)); +} + +const HEADING = /^(#{2,6})[ \t]+(.+?)[ \t]*#*[ \t]*$/gm; + +interface HeadingMatch { + /** Offset of the heading line. */ + index: number; + /** Offset just past the heading text (where the section body starts). */ + end: number; + /** The heading as written. */ + text: string; + /** Heading level (2 for ##, 3 for ###, ...). */ + level: number; +} + +/** + * The level the plugin (and its hex template) writes its sections at. + * Released 1.5.x read and wrote only "###" sections, so a "###" heading + * always wins over the same section at another level: a note with a + * hand-written "## Towns" above the plugin's "### Towns" reads exactly as + * it did in 1.5.6 (fresh-eyes 2026-10-13 F1, Slattville). + */ +export const PLUGIN_SECTION_LEVEL = 3; + +/** Every section heading in the note (## to ######), in order. */ +export function sectionHeadings(content: string): HeadingMatch[] { + const out: HeadingMatch[] = []; + const re = new RegExp(HEADING.source, "gm"); + let m: RegExpExecArray | null; + while ((m = re.exec(content)) !== null) out.push({ index: m.index, end: m.index + m[0].length, text: m[2], level: m[1].length }); + return out; +} + +/** + * How well a heading names `section` (lower is better), or null when it + * doesn't name it at all. Order: the heading exactly as asked for (an + * aliased section shown under its own name), then the section's own name, + * then an alias; within each, the plugin's own level (###) first, then + * document order. Shared by the note parser here and the metadata-cache + * readers (link badges) so the editor and the hover always agree. + */ +export function sectionHeadingRank(headingText: string, level: number, section: string): number | null { + const want = canonicalSection(section); + if (canonicalSection(headingText) !== want) return null; + const h = normalizeHeading(headingText); + const name = h === normalizeHeading(section) ? 0 : h === want ? 1 : 2; + return name * 2 + (level === PLUGIN_SECTION_LEVEL ? 0 : 1); +} + +/** The best-ranked of `headings` for `section` (first in order on a tie), or null. */ +export function pickSectionHeading( + headings: readonly T[], + section: string, + textOf: (h: T) => string, + levelOf: (h: T) => number, +): T | null { + let best: T | null = null; + let bestRank = Infinity; + for (const h of headings) { + const r = sectionHeadingRank(textOf(h), levelOf(h), section); + if (r !== null && r < bestRank) { best = h; bestRank = r; } + } + return best; +} + +/** + * The heading naming `section` (see canonicalSection), or null. A heading + * with the section's own name wins over an alias: a note with both an old + * template's "### encounters" and the plugin's "### Encounters Table" reads + * and writes the latter (the former shows as a section of its own). At the + * same name, "###" wins over other levels (see PLUGIN_SECTION_LEVEL). + */ +export function findSectionHeading(content: string, section: string): HeadingMatch | null { + return pickSectionHeading(sectionHeadings(content), section, (h) => h.text, (h) => h.level); +} + +/** + * Where a section's body ends: the next heading of any level, a --- rule, or + * the end. This is 1.5.6's rule, kept on purpose: a "## Dungeons" never + * swallows the "###" sections below it, and a section write never replaces + * a "####" subsection someone wrote inside it. + */ +function sectionEndAfter(content: string, afterHeading: number): number { + const next = /\n(?:#{1,6} |-{3,})/m.exec(content.slice(afterHeading)); + return next ? afterHeading + next.index : content.length; +} + +/** Insert a wiki-link under the named ### section, creating the section if absent. */ +export async function addLinkToSection(app: App, filePath: string, section: string, linkText: string): Promise { + const file = app.vault.getAbstractFileByPath(filePath); + if (!(file instanceof TFile)) return; + await app.vault.process(file, (content) => insertLinkInSection(content, section, linkText)); +} + +/** + * Note text with `linkText` added under the "### section" heading (the + * heading is appended if missing). Unchanged if the link is already there. + */ +export function insertLinkInSection(content: string, section: string, linkText: string): string { + const match = findSectionHeading(content, section); + if (!match) { + return separateRulesFromText(content.trimEnd() + `\n\n### ${section}\n\n${linkText}\n`); + } + const afterHeading = match.end; + const nextBoundaryMatch = /\n(?:#{1,6} |-{3,})/m.exec(content.slice(afterHeading)); + const sectionEnd = nextBoundaryMatch ? afterHeading + nextBoundaryMatch.index : content.length; + const sectionContent = content.slice(afterHeading, sectionEnd); + if (sectionContent.includes(linkText)) return separateRulesFromText(content); + const trimmedSection = sectionContent.trimEnd(); + const insertAt = afterHeading + trimmedSection.length; + // One blank line above the link (the heading match can swallow a newline + // of an empty section); the template's `---` usually follows the link, + // so keep a blank line before it too. + const before = content.slice(0, insertAt).replace(/[\r\n]+$/, ""); + return separateRulesFromText(before + "\n\n" + linkText + content.slice(insertAt)); +} + +/** + * Text directly above a `---` rule renders as a big setext heading in + * Markdown (fresh-eyes round 5: a Dungeons link written just above the hex + * template's rule showed as a heading). Puts a blank line between a text + * line and a following rule. Frontmatter and fenced code are left alone. + * Every section writer runs this, so older notes heal on their next write. + */ +export function separateRulesFromText(content: string): string { + const eol = content.includes("\r\n") ? "\r\n" : "\n"; + const lines = content.split(/\r?\n/); + const isRule = (l: string) => /^ {0,3}-{3,}\s*$/.test(l); + let start = 0; + if (lines.length > 1 && lines[0].trim() === "---") { + const close = lines.findIndex((l, i) => i > 0 && l.trim() === "---"); + if (close > 0) start = close + 1; + } + const out = lines.slice(0, start); + let inFence = false; + let changed = false; + for (let i = start; i < lines.length; i++) { + const line = lines[i]; + if (/^ {0,3}(```|~~~)/.test(line)) inFence = !inFence; + else if (!inFence && i > start && isRule(line)) { + const prev = lines[i - 1]; + if (prev.trim() !== "" && !/^ {0,3}#{1,6}(\s|$)/.test(prev) && !isRule(prev)) { + out.push(""); + changed = true; + } + } + out.push(line); + } + return changed ? out.join(eol) : content; +} + +/** Remove a wiki-link from under the named ### section. Removes the whole line containing it. */ +export async function removeLinkFromSection(app: App, filePath: string, section: string, linkTarget: string): Promise { + const file = app.vault.getAbstractFileByPath(filePath); + if (!(file instanceof TFile)) return; + await app.vault.process(file, (content) => { + const match = findSectionHeading(content, section); + if (!match) return content; + const afterHeading = match.end; + const nextBoundaryMatch = /\n(?:#{1,6} |-{3,})/m.exec(content.slice(afterHeading)); + const sectionEnd = nextBoundaryMatch ? afterHeading + nextBoundaryMatch.index : content.length; + const escapedTarget = escapeRegex(linkTarget); + const lineRegex = new RegExp(`\\n[^\\n]*\\[\\[${escapedTarget}(?:\\|[^\\]]+)?\\]\\][^\\n]*`, "g"); + const sectionBody = content.slice(afterHeading, sectionEnd); + const newBody = sectionBody.replace(lineRegex, ""); + return separateRulesFromText(content.slice(0, afterHeading) + newBody + content.slice(sectionEnd)); + }); +} + +/** Return all wiki-link targets found under a named ### section. */ +export async function getLinksInSection(app: App, filePath: string, section: string): Promise { + const file = app.vault.getAbstractFileByPath(filePath); + if (!(file instanceof TFile)) return []; + const content = await app.vault.read(file); + + const match = findSectionHeading(content, section); + if (!match) return []; + + const afterHeading = match.end; + const nextBoundaryMatch = /\n(?:#{1,6} |-{3,})/m.exec(content.slice(afterHeading)); + const sectionEnd = nextBoundaryMatch ? afterHeading + nextBoundaryMatch.index : content.length; + const sectionContent = content.slice(afterHeading, sectionEnd); + + const links: string[] = []; + const linkRegex = /\[\[([^\]|]+)(?:\|[^\]]+)?\]\]/g; + let m; + while ((m = linkRegex.exec(sectionContent)) !== null) { + links.push(m[1]); + } + return links; +} + +/** Read a file once and return all text and link section content in a single pass. */ +export async function getAllSectionData( + app: App, + filePath: string, + preloadedContent?: string, +): Promise<{ text: Map; links: Map; headings: Map }> { + const text = new Map(); + const links = new Map(); + /** Section key → the heading as written in the note (for sections shown under their own name). */ + const headings = new Map(); + const file = app.vault.getAbstractFileByPath(filePath); + if (!(file instanceof TFile)) return { text, links, headings }; + const content = preloadedContent ?? await app.vault.read(file); + + const linkRegex = /\[\[([^\]|]+)(?:\|[^\]]+)?\]\]/g; + const all = sectionHeadings(content); + // Per section, the heading the plugin reads and writes (findSectionHeading's + // choice); other headings that alias it are kept under their own names. + const primary = new Map(); + for (const key of new Set(all.map((h) => canonicalSection(h.text)))) { + const best = pickSectionHeading(all, key, (h) => h.text, (h) => h.level); + if (best) primary.set(key, best); + } + for (const h of all) { + const canon = canonicalSection(h.text); + const isPrimary = primary.get(canon) === h; + // A second heading with the section's own name (a hand-written + // "## Towns" beside the plugin's "### Towns") isn't shown: it would + // read and write the primary one. 1.5.6 didn't show it either; the + // note text is left as it is. + if (!isPrimary && normalizeHeading(h.text) === canon) continue; + const name = isPrimary ? canon : normalizeHeading(h.text); + if (headings.has(name)) continue; + const body = content.slice(h.end, sectionEndAfter(content, h.end)); + const sectionLinks: string[] = []; + let lm: RegExpExecArray | null; + const lr = new RegExp(linkRegex.source, "g"); + while ((lm = lr.exec(body)) !== null) sectionLinks.push(lm[1]); + headings.set(name, h.text); + links.set(name, sectionLinks); + // The template's guidance prompt under the heading isn't section text. + text.set(name, splitGuidance(body).text.trim()); + } + return { text, links, headings }; +} + +/** + * A back-link to a hex note that can't be mistaken for another map's hex: + * the full path, shown as `alias` (round 6 S2: a town note got a bare + * "[[7_7]]", the same on every map). "|", "[" and "]" are dropped from the + * alias so the link stays well-formed. + */ +export function hexBacklinkText(hexFilePath: string, alias: string): string { + const target = hexFilePath.replace(/\.md$/i, ""); + const shown = alias.replace(/[|[\]]/g, "").replace(/\s+/g, " ").trim(); + return shown ? `[[${target}|${shown}]]` : `[[${target}]]`; +} + +/** + * Append a backlink to hexFilePath at the end of targetFilePath, unless + * a link to the hex file already exists anywhere in the target note. With + * `alias`, the link is path-qualified and reads as the alias (see + * hexBacklinkText); without, it's Obsidian's shortest link. + */ +export async function addBacklinkToFile(app: App, targetFilePath: string, hexFilePath: string, alias?: string): Promise { + const hexFile = app.vault.getAbstractFileByPath(hexFilePath); + const targetFile = app.vault.getAbstractFileByPath(targetFilePath); + if (!(hexFile instanceof TFile) || !(targetFile instanceof TFile)) return; + + // Skip if the target already links back to the hex + const cache = app.metadataCache.getFileCache(targetFile); + const alreadyLinked = cache?.links?.some( + l => app.metadataCache.getFirstLinkpathDest(l.link, targetFilePath) === hexFile, + ); + if (alreadyLinked) return; + + const linkText = alias !== undefined + ? hexBacklinkText(hexFile.path, alias) + : `[[${app.metadataCache.fileToLinktext(hexFile, targetFilePath)}]]`; + // The cache lags a just-created note: its Location line (R3) may + // already link the hex by path. + const target = hexFile.path.replace(/\.md$/i, ""); + await app.vault.process(targetFile, (content) => + content.includes(`[[${target}]]`) || content.includes(`[[${target}|`) + ? content + : content.trimEnd() + (content.trim() ? "\n\n" : "") + linkText + "\n", + ); +} + +/** Replace the body of a named ### section in-place, creating the section if absent. */ +export async function setSectionContent(app: App, filePath: string, section: string, newText: string): Promise { + const file = app.vault.getAbstractFileByPath(filePath); + if (!(file instanceof TFile)) return; + await app.vault.process(file, (content) => replaceSectionText(content, section, newText)); +} + +/** Text of a named ### section in `content` (guidance prompt left out). */ +export function sectionText(content: string, section: string): string { + const match = findSectionHeading(content, section); + if (!match) return ""; + const afterHeading = match.end; + const nextBoundary = /\n(?:#{1,6} |-{3,})/m.exec(content.slice(afterHeading)); + const sectionEnd = nextBoundary ? afterHeading + nextBoundary.index : content.length; + return splitGuidance(content.slice(afterHeading, sectionEnd)).text.trim(); +} + +/** Note text with the body of "### section" replaced (heading appended if missing). */ +export function replaceSectionText(content: string, section: string, newText: string): string { + const match = findSectionHeading(content, section); + if (!match) { + return newText.trim() + ? content.trimEnd() + `\n\n### ${section}\n${newText.trim()}\n` + : content; + } + const afterHeading = match.end; + const nextBoundary = /\n(?:#{1,6} |-{3,})/m.exec(content.slice(afterHeading)); + const sectionEnd = nextBoundary ? afterHeading + nextBoundary.index : content.length; + // Keep the template's guidance prompt on top of the section. + const { guidance } = splitGuidance(content.slice(afterHeading, sectionEnd)); + const guide = guidance.length ? `${guidance.join("\n")}\n` : ""; + const replacement = newText.trim() + ? `\n${guide}${guide ? "\n" : ""}${newText.trim()}\n` + : `\n${guide}`; + return separateRulesFromText(content.slice(0, afterHeading) + replacement + content.slice(sectionEnd)); +} + +/** `existing` with `addition` on a new line (either may be empty). */ +export function joinSectionText(existing: string, addition: string): string { + const a = existing.trimEnd(); + const b = addition.trim(); + if (!b) return a; + return a ? `${a}\n${b}` : b; +} + +/** Note text with `addition` appended to the end of "### section" (P2 "Add to this hex"). */ +export function appendSectionText(content: string, section: string, addition: string): string { + if (!addition.trim()) return content; + return replaceSectionText(content, section, joinSectionText(sectionText(content, section), addition)); +} diff --git a/src/services/FieldsService.ts b/src/services/FieldsService.ts new file mode 100644 index 00000000..bb8bf0af --- /dev/null +++ b/src/services/FieldsService.ts @@ -0,0 +1,162 @@ +/** + * Custom hex fields (GitHub #52, plan-custom-hex-fields phase 1): the + * plugin's half. The decisions are pure (src/fields/mapFields.ts); this + * service hands them the map's hexes, places and the table roller, and + * writes what comes back. + * + * - The world's declarations: `store` (the fields note, FieldStore). + * - Filling: a hex that gets terrain has its blank fields worked out in the + * same write (MapStore → maps/fieldFill.ts, bound in ports.ts). + * - Editing: `setValue` (the hex editor), gated `edit-fields` (Build). + * - Recalculate fields: every hex with terrain on a map, keeping rolls or + * rolling again. + * + * Places come from terrain (synchronous, from the map store) and from the + * notes linked under a hex note's Towns (from the metadata cache); both + * are cached per map until the map or any note changes. + */ + +import { TFile, TFolder } from "obsidian"; +import type HexmakerPlugin from "../HexmakerPlugin"; +import type { HexData } from "../maps/mapNote"; +import { FieldStore } from "../fields/FieldStore"; +import { typedOnHex, workOutHex, workOutMap, type MapFieldsInput } from "../fields/mapFields"; +import { linksUnderHeading, notePlaceType, placeTypes, terrainPlaces } from "../fields/places"; +import type { FieldDef } from "../fields/fieldTypes"; +import type { Place } from "../fields/influence"; +import type { FieldPass } from "../fields/hexFields"; +import { rollForHex } from "../random-tables/hexRoll"; +import { hexDistance } from "../paths/router"; +import { hexPair } from "../hexKey"; +import { canonicalSection } from "../sections"; +import { guardWrite } from "../modeGate"; + +const HEX_NOTE = /^(-?\d+)_(-?\d+)$/; + +export interface RecalcReport { + hexes: number; + places: number; + refused?: boolean; +} + +export class FieldsService { + readonly store: FieldStore; + private placeCache = new Map(); + + constructor(private plugin: HexmakerPlugin) { + this.store = new FieldStore(plugin); + this.store.onChange(() => this.placeCache.clear()); + } + + /** Start: read the fields note; forget a map's places whenever it changes. */ + async init(): Promise { + this.plugin.mapStore.onChange((map) => this.placeCache.delete(map)); + await this.store.init(); + } + + /** Any note's metadata changed (a Towns link, a `place-type:`): places are found again. */ + onMetadataChanged(): void { + this.placeCache.clear(); + } + + /** The world's fields (empty without a fields note). */ + fields(): readonly FieldDef[] { + return this.store.get().fields; + } + + // ── what the pure side needs ─────────────────────────────────────────── + + /** Every place on a map (cached until the map or a note changes). */ + places(map: string): Place[] { + const hit = this.placeCache.get(map); + if (hit) return hit; + const types = placeTypes(this.store.get().influences); + const typeOf = this.typeOf(map); + const out = [...terrainPlaces(this.plugin.mapStore.all(map), types, typeOf), ...this.notePlaces(map, types)]; + this.placeCache.set(map, out); + return out; + } + + /** The places linked under each hex note's Towns: the note's `place-type:` (else town). */ + private notePlaces(map: string, types: ReadonlySet): Place[] { + const { vault, metadataCache } = this.plugin.app; + const folder = vault.getAbstractFileByPath(this.plugin.mapStore.mapFolder(map)); + if (!(folder instanceof TFolder)) return []; + const out: Place[] = []; + for (const f of folder.children) { + if (!(f instanceof TFile) || f.extension !== "md" || !HEX_NOTE.test(f.basename)) continue; + const links = linksUnderHeading(metadataCache.getFileCache(f), (h) => canonicalSection(h) === "towns"); + for (const link of links) { + const note = metadataCache.getFirstLinkpathDest(link.split("#")[0], f.path); + if (!note) continue; + const fm = metadataCache.getFileCache(note)?.frontmatter; + out.push({ key: f.basename, type: notePlaceType(fm, types), note: note.path, source: `[[${note.basename}]]` }); + } + } + return out; + } + + private typeOf(map: string): (terrain: string) => string | undefined { + const byName = new Map(this.plugin.getMapPalette(map).map((t) => [t.name.toLowerCase(), t.type])); + return (terrain) => byName.get(terrain.toLowerCase()); + } + + /** Everything the pure side reads for a map. */ + input(map: string): MapFieldsInput { + const orientation = this.plugin.settings.hexOrientation ?? "flat"; + const stagger = this.plugin.getMap(map)?.staggerOffset ?? this.plugin.settings.staggerOffset ?? "odd"; + const lookup = this.plugin.tableNotes.lookup(); + return { + decls: this.store.get(), + hexes: this.plugin.mapStore.all(map), + places: this.places(map), + distance: (a, b) => hexDistance(hexPair(a), hexPair(b), orientation, stagger), + typeOf: this.typeOf(map), + roll: (field, ctx) => { + if (!field.table) return undefined; + const text = rollForHex(field.table, lookup, ctx).text.split("\n")[0]?.trim(); + return text || undefined; + }, + }; + } + + // ── writes ───────────────────────────────────────────────────────────── + + /** A hex that just got terrain: its blank fields (MapStore's filler; no write of its own). */ + fillFor(map: string, key: string, h: HexData): Record | undefined { + if (!this.store.get().fields.length) return undefined; + return workOutHex(this.input(map), key, h, "fill"); + } + + /** A value typed in the hex editor (Build; formulas follow). False when the mode refuses it. */ + setValue(map: string, key: string, field: string, raw: string): boolean { + const next = typedOnHex(this.input(map), key, field, raw); + if (!next) return true; + return this.plugin.mapStore.set(map, key, { extra: Object.keys(next).length ? next : null }, "edit-fields"); + } + + /** Roll one field again on one hex (the editor's 🎲): its value and roll cleared, then filled. */ + rollField(map: string, key: string, field: string): boolean { + const input = this.input(map); + const cleared = typedOnHex(input, key, field, "") ?? input.hexes.get(key)?.extra; + const h = { ...(input.hexes.get(key) ?? {}), extra: cleared }; + const next = workOutHex(input, key, h, "fill") ?? cleared; + return this.plugin.mapStore.set(map, key, { extra: next && Object.keys(next).length ? next : null }, "edit-fields"); + } + + /** + * Recalculate fields on a map: `modifiers` keeps rolls and typed values + * and redoes the places' changes (filling blank fields); `reroll` rolls + * every field again. One undo step. + */ + async recalculate(map: string, pass: Extract): Promise { + if (!guardWrite(map, "edit-fields")) return { hexes: 0, places: 0, refused: true }; + this.placeCache.delete(map); + const input = this.input(map); + const cells = workOutMap(input, pass); + if (cells.length) { + await this.plugin.undoableEdit(map, () => this.plugin.mapStore.setMany(map, cells.map(([k, extra]) => [k, { extra: Object.keys(extra).length ? extra : undefined }]))); + } + return { hexes: cells.length, places: input.places.length }; + } +} diff --git a/src/services/HexNotesService.ts b/src/services/HexNotesService.ts new file mode 100644 index 00000000..3a034b10 --- /dev/null +++ b/src/services/HexNotesService.ts @@ -0,0 +1,486 @@ +/** + * Hex notes (made on use from the template, with their properties, Map + * data callout and encounter links), hex names and aliases, the Map data + * callouts of hex, region and faction notes, and notes that follow a map + * or region rename. Split from HexmakerPlugin (plan-architecture-refactor + * L1a); the plugin keeps one-line delegations. + */ +import { Notice, TFile, TFolder } from "obsidian"; +import { worldMaps } from "../modules/runtime"; +import { normalizeFolder } from "../utils"; +import { tokenMapValue } from "../frontmatter"; +import { withMapLink } from "../maps/mapNote"; +import { mapDataLines, mapDataSyncMessage, setMapData, shownValues, type HexMapDataView } from "../hexMapData"; +import { syncHexMapData as syncHexMapDataWith, type CalloutSyncResult } from "../maps/calloutSync"; +import { hasRegionMapData, regionUse, renameRegionInStore, renamedTokenMap, setRegionMapData, type RegionMapDataView } from "../regionMapData"; +import { cleanHexName, coordAlias, swapMapCoordAliases, syncHexAliases } from "../maps/hexNames"; +import { + insertLinkInSection, + appendSectionText, + addLinkToSection, + addBacklinkToFile, +} from "../sections"; +import { LOCATION_SECTIONS } from "../noteTemplates"; +import { noteFileName } from "../vault/safePaths"; +import type { LinkSection } from "../types"; +import type HexmakerPlugin from "../HexmakerPlugin"; +import { hexKey, hexXY, isHexKey } from "../hexKey"; +import { ensureFolder } from "../vault/ensureFolder"; + +/** What HexNotesService uses of the plugin. */ +export type HexNotesHost = HexmakerPlugin; + +export class HexNotesService { + constructor(private readonly plugin: HexNotesHost) {} + + /** + * Check whether a TFile is a hex note (lives under the configured hex + * folder, basename matches the `x_y` coord pattern). Used to gate the + * structured hex export command. + */ + isHexFile(file: TFile): boolean { + const hexFolder = normalizeFolder(this.plugin.settings.hexFolder); + if (hexFolder && !file.path.startsWith(hexFolder + "/")) return false; + return isHexKey(file.basename); + } + + hexPath(x: number, y: number, mapName: string): string { + const folder = normalizeFolder(this.plugin.settings.hexFolder); + return folder + ? `${folder}/${mapName}/${hexKey(x, y)}.md` + : `${mapName}/${hexKey(x, y)}.md`; + } + + /** + * Name (or rename, or with "" unname) a hex. The name lives in the map + * note; a hex that has a note also gets it as an alias, replacing the + * previous name's alias and keeping any the user added. + */ + async setHexName(mapName: string, x: number, y: number, raw: string): Promise { + const key = hexKey(x, y); + const name = cleanHexName(raw); + const old = this.plugin.mapStore.get(mapName, key)?.name; + if ((old ?? "") === name) return; + this.plugin.mapStore.set(mapName, key, { name: name || null }, "edit-note"); + // The " x, y" alias rides along (added if the note lacks it). + const coord = this.plugin.hexCoordAlias(mapName, x, y); + await syncHexAliases(this.plugin.app, this.plugin.hexPath(x, y, mapName), [ + { from: old, to: name }, + { from: coord, to: coord }, + ]); + } + + /** A hex note's " x, y" alias (NM2). */ + hexCoordAlias(mapName: string, x: number | string, y: number | string): string { + return coordAlias(this.plugin.mapLabel(mapName), x, y); + } + + /** A map's display name changed from `oldLabel`: swap the " x, y" alias on its hex notes (hexNames.ts). */ + async syncMapCoordAliases(mapName: string, oldLabel: string): Promise { + await swapMapCoordAliases(this.plugin.app, this.plugin.mapStore.mapFolder(mapName), oldLabel, this.plugin.mapLabel(mapName)); + } + + /** Create a hex note from the configured template (or the built-in default). */ + async createHexNote( + x: number, + y: number, + mapName: string, + preloadedTemplate?: string, + terrain?: string, + ): Promise { + const path = this.plugin.hexPath(x, y, mapName); + let content: string; + + if (preloadedTemplate !== undefined) { + content = preloadedTemplate; + } else { + content = await this.plugin.loadHexTemplate(); + } + + content = content + .replace(/\{\{x\}\}/g, String(x)) + .replace(/\{\{y\}\}/g, String(y)) + .replace(/\{\{title\}\}/g, `Hex ${x}, ${y}`) + .replace(/\{\{map\}\}/g, mapName); + // Map data lives in the map note: the hex note links there instead of + // carrying (possibly stale) terrain/region fields. + content = withMapLink(content, mapName); + if (terrain) this.plugin.mapStore.set(mapName, hexKey(x, y), { terrain }); + // Its terrain, area, icon and name as properties (MG4). + content = this.plugin.hexProps.withProps(content, mapName, x, y, path); + // The template's Map data callout shows what the map has for this hex. + const mapDataView = this.plugin.hexMapDataView(mapName, x, y); + const withMapData = setMapData(content, mapDataView); + // Remember what it shows, so a later hand edit is told from a stale copy. + if (withMapData !== content) this.plugin.calloutMemory.set(path, shownValues(mapDataLines(mapDataView))); + content = withMapData; + // The hex's terrain (just set, or painted before it had a note) gets + // its encounter-table link now rather than patched in later. + const encounterLink = this.plugin.terrainEncounterLinkFor(mapName, x, y, path); + if (encounterLink) { + content = insertLinkInSection(content, "Encounters Table", `[[${encounterLink}]]`); + } + // Likewise its area's table (painted before the hex had a note), so the + // hex editor's Encounters list doesn't lose it when the note is made. + const areaTable = this.plugin.areaEncounterTableFor(mapName, x, y); + if (areaTable) { + content = insertLinkInSection(content, "Encounters Table", `[[${this.plugin.app.metadataCache.fileToLinktext(areaTable, path)}]]`); + } + + const hexBase = normalizeFolder(this.plugin.settings.hexFolder); + const mapFolder = hexBase ? `${hexBase}/${mapName}` : mapName; + // A concurrent worker may have made the folder already (ensureFolder allows for it). + await ensureFolder(this.plugin.app.vault, mapFolder); + + try { + const file = await this.plugin.app.vault.create(path, content); + // A named hex's note gets its name as an alias (X4), and every hex + // note gets " x, y" (NM2). + const name = this.plugin.mapStore.get(mapName, hexKey(x, y))?.name; + await syncHexAliases(this.plugin.app, path, [ + { from: undefined, to: name }, + { from: undefined, to: this.plugin.hexCoordAlias(mapName, x, y) }, + ]); + return file; + } catch { + // A concurrent worker may have created this file between our existence check and + // this create call. If the file now exists, use it rather than treating it as an error. + const existing = this.plugin.app.vault.getAbstractFileByPath(path); + if (existing instanceof TFile) return existing; + new Notice("Could not create note at " + path); + return null; + } + } + + /** + * A note for a hex's link section, `/.md` (the name cleaned + * into a file name), made if it isn't there yet: from `template` when + * given, else the section's note template; places made from a hex get a + * Location line (PA3, F17, R3). Returns the note, or null after a notice. + */ + async createLinkedNote(section: string, folder: string, rawName: string, hexPath: string, template?: string): Promise { + const { vault } = this.plugin.app; + const name = noteFileName(rawName); + if (!name) return null; + const dir = normalizeFolder(folder); + const path = dir ? `${dir}/${name}.md` : `${name}.md`; + const existing = vault.getAbstractFileByPath(path); + if (existing instanceof TFile) return existing; + try { + if (dir) await ensureFolder(vault, dir); + const content = template + ? (LOCATION_SECTIONS.includes(section) ? this.plugin.withHexLocation(template, hexPath) : template) + : await this.plugin.newLinkedNoteContent(section, name, hexPath); + return await vault.create(path, content); + } catch (err) { + new Notice(`Could not create ${path}: ${String(err)}`); + return null; + } + } + + /** + * Link `file` into a hex's link section: the hex's note is made first if + * it has none (from the hex template, with its map link: never an empty + * note), then the link goes under the section and `file` gets a backlink + * to the hex. Returns the link text written, or null when the hex's note + * couldn't be made (createHexNote said so). + */ + async linkNoteToHex(file: TFile, x: number, y: number, mapName: string, section: LinkSection): Promise { + const { app } = this.plugin; + const hexPath = this.plugin.hexPath(x, y, mapName); + const hexNote = app.vault.getAbstractFileByPath(hexPath); + if (!(hexNote instanceof TFile) && !(await this.plugin.createHexNote(x, y, mapName))) return null; + const linkPath = app.metadataCache.fileToLinktext(file, hexPath); + await addLinkToSection(app, hexPath, section, `[[${linkPath}]]`); + await addBacklinkToFile(app, file.path, hexPath, this.plugin.hexLinkAlias(hexPath)); + return linkPath; + } + + /** + * "Create" in a hex's link picker (the hex editor's link sections, the + * hex table's picker): createLinkedNote, then linkNoteToHex. Returns the + * link text written, or null when nothing was linked. + */ + async createAndLinkNote( + o: { x: number; y: number; mapName: string; section: LinkSection; folder: string; name: string; template?: string }, + ): Promise { + const file = await this.createLinkedNote(o.section, o.folder, o.name, this.plugin.hexPath(o.x, o.y, o.mapName), o.template); + return file ? this.linkNoteToHex(file, o.x, o.y, o.mapName, o.section) : null; + } + + /** + * Append text to a section of a hex's note, creating the note first if + * the hex has none (P2 "Add to this hex"). + */ + async appendToHexSection(x: number, y: number, mapName: string, section: string, text: string): Promise { + const path = this.plugin.hexPath(x, y, mapName); + let file = this.plugin.app.vault.getAbstractFileByPath(path); + if (!(file instanceof TFile)) file = await this.plugin.createHexNote(x, y, mapName); + if (!(file instanceof TFile)) throw new Error(`Could not create the note for hex ${x}, ${y}`); + await this.plugin.app.vault.process(file, (content) => appendSectionText(content, section, text)); + } + + /** What the map has for a hex, for its note's Map data callout (src/hexMapData.ts). */ + hexMapDataView(mapName: string, x: number, y: number): HexMapDataView { + const h = this.plugin.mapStore.get(mapName, hexKey(x, y)) ?? {}; + const ref = (m: string) => ({ map: m, label: this.plugin.mapLabel(m) }); + return { + map: mapName, mapLabel: this.plugin.mapLabel(mapName), x, y, terrain: h.terrain, region: h.region, name: h.name, + regionMap: h.regionMap ? ref(h.regionMap) : undefined, + locations: h.locations?.length ? h.locations.map(ref) : undefined, + biome: this.hexBiomeRef(mapName, hexKey(x, y)), + }; + } + + /** An overworld hex's biome for its Map data callout (World maps), else nothing. */ + private hexBiomeRef(mapName: string, key: string): { label: string; note?: string } | undefined { + return worldMaps()?.hexBiomeRef(this.plugin, mapName, key); + } + + /** + * Bring a hex note's Map data callout up to date with the map (or add one + * when `insert`). Hand edits made inside the callout go to the map first + * (phase 2, see `syncHexMapData`). Only writes when something changed; a + * note without a callout is left alone unless `insert`. Returns whether + * it wrote. + */ + async refreshHexMapData(mapName: string, x: number, y: number, insert = false): Promise { + return (await this.plugin.syncHexMapData(mapName, x, y, { insert })).wrote; + } + + /** + * A hex note's Map data callout, both ways (phase 2): hand edits to + * Terrain, Region or Name made since the plugin last wrote it go to the + * map (through the work-mode gate, as one undo step), unless the map has + * changed them since (the map is newer); then the callout is rewritten + * to show the map. Edits that weren't applied stay in the callout as + * "Not applied:" lines and lines it can't read as "Not read:" lines, and + * a notice says so (unless `quiet`). + */ + async syncHexMapData( + mapName: string, x: number, y: number, opts: { insert?: boolean; quiet?: boolean } = {}, + ): Promise { + return syncHexMapDataWith(this.plugin, mapName, x, y, opts); + } + + /** Add (or update) the Map data callout in every hex note of a map. Returns how many notes changed. */ + async addMapDataToHexNotes(mapName: string): Promise { + const hexBase = normalizeFolder(this.plugin.settings.hexFolder); + const folder = this.plugin.app.vault.getAbstractFileByPath(hexBase ? `${hexBase}/${mapName}` : mapName); + if (!(folder instanceof TFolder)) return 0; + let n = 0; + const totals = { applied: [] as string[], notApplied: [] as string[], unreadable: [] as string[] }; + for (const f of folder.children) { + if (!(f instanceof TFile)) continue; + const m = /^(-?\d+)_(-?\d+)\.md$/.exec(f.name); + if (!m) continue; + const r = await this.plugin.syncHexMapData(mapName, Number(m[1]), Number(m[2]), { insert: true, quiet: true }); + if (r.wrote) n++; + totals.applied.push(...r.applied); + totals.notApplied.push(...r.notApplied); + totals.unreadable.push(...r.unreadable); + } + const msg = mapDataSyncMessage(this.plugin.mapLabel(mapName), totals); + if (msg) new Notice(msg, 8000); + return n; + } + + // ── Region and faction notes (R1, R2) ──────────────────────────────────── + + /** "region" / "faction" for a note in the regions / factions folder ("_" notes aren't). */ + regionOrFactionKind(file: TFile): "region" | "faction" | null { + if (file.extension !== "md" || file.basename.startsWith("_")) return null; + const inFolder = (setting: string) => { + const folder = normalizeFolder(setting ?? ""); + return !!folder && file.path.startsWith(folder + "/"); + }; + if (inFolder(this.plugin.settings.regionsFolder)) return "region"; + if (inFolder(this.plugin.settings.factionsFolder)) return "faction"; + return null; + } + + /** Every region and faction note. */ + regionAndFactionNotes(): TFile[] { + return this.plugin.app.vault.getMarkdownFiles().filter((f) => this.plugin.regionOrFactionKind(f) !== null); + } + + /** The maps that use a region or faction note, for its Map data callout. */ + regionMapDataView(file: TFile, kind: "region" | "faction"): RegionMapDataView { + const maps = this.plugin.settings.maps.map((m) => ({ name: m.name, label: this.plugin.mapLabel(m.name) })); + if (kind === "region") { + const folder = normalizeFolder(this.plugin.settings.tablesFolder); + const table = this.plugin.app.vault.getAbstractFileByPath(`${folder ? `${folder}/` : ""}regions/${file.basename}.md`); + return { + kind, + maps: regionUse(file.basename, maps, (m) => this.plugin.mapStore.all(m).values()), + encounterTable: table instanceof TFile ? this.plugin.app.metadataCache.fileToLinktext(table, file.path) : undefined, + }; + } + // Factions: hex notes that link the faction note, per map. + const counts = new Map(); + for (const [source, targets] of Object.entries(this.plugin.app.metadataCache.resolvedLinks)) { + if (!targets[file.path]) continue; + const loc = this.plugin.mapStore.resolve(source); + if (loc) counts.set(loc.map, (counts.get(loc.map) ?? 0) + 1); + } + return { + kind, + maps: maps + .filter((m, i) => counts.get(m.name) && maps.findIndex((o) => o.name === m.name) === i) + .map((m) => ({ map: m.name, label: m.label, hexes: counts.get(m.name) ?? 0 })), + }; + } + + /** + * Bring a region or faction note's Map data callout up to date (or add + * one when `insert`). Only writes when something changed. Returns + * whether it wrote. + */ + async refreshRegionMapData(file: TFile, insert = false): Promise { + const kind = this.plugin.regionOrFactionKind(file); + if (!kind || !this.plugin.mapStore.isReady()) return false; + const current = await this.plugin.app.vault.read(file); + if (!insert && !hasRegionMapData(current)) return false; + const view = this.plugin.regionMapDataView(file, kind); + // Read first: most notes need nothing, and a no-op process() still writes. + if (setRegionMapData(current, view, insert) === current) return false; + let wrote = false; + await this.plugin.app.vault.process(file, (content) => { + const next = setRegionMapData(content, view, insert); + wrote = next !== content; + return next; + }); + return wrote; + } + + /** Add or update the Map data callout in every region and faction note. Returns how many changed. */ + async updateRegionFactionMapData(): Promise { + await this.plugin.mapStore.flush(); + let n = 0; + for (const f of this.plugin.regionAndFactionNotes()) { + if (await this.plugin.refreshRegionMapData(f, true)) n++; + } + return n; + } + + /** + * A region note was renamed: hexes whose Region named it follow, through + * the map store (the map notes are rewritten from it). Returns how many + * hexes changed. + */ + renameRegionInMaps(oldName: string, newName: string): number { + return renameRegionInStore(this.plugin.mapStore, this.plugin.settings.maps.map((m) => m.name), oldName, newName); + } + + /** A map was renamed: tokens placed on it (`token-map`) follow. Returns how many notes changed. */ + async updateTokenMapReferences(oldName: string, newName: string): Promise { + let n = 0; + for (const file of this.plugin.app.vault.getMarkdownFiles()) { + if (file.basename.startsWith("_")) continue; + const fm = this.plugin.app.metadataCache.getFileCache(file)?.frontmatter; + if (!fm || renamedTokenMap(fm["token-map"], oldName, newName) === null) continue; + await this.plugin.app.fileManager.processFrontMatter(file, (front: Record) => { + const next = renamedTokenMap(front["token-map"], oldName, newName); + // An old plain name becomes a link to the map note (NF3); a link keeps its form. + if (next !== null) front["token-map"] = next === newName ? tokenMapValue(newName) : next; + }); + n++; + } + return n; + } + + /** + * Set terrain for specific hexes ("x_y" → terrain). With map notes this + * writes map data only — hex notes are created when a hex gets content — + * so it returns 0 notes created. Falls back to creating notes only if the + * map store isn't ready yet. + */ + async generateHexNotesAt( + mapName: string, + cells: [string, string][], + onProgress?: (done: number) => void, + ): Promise { + if (this.plugin.mapStore.isReady()) { + this.plugin.mapStore.setMany(mapName, cells.filter(([, t]) => t).map(([k, t]) => [k, { terrain: t }])); + onProgress?.(cells.length); + await this.plugin.mapStore.flush(); + return 0; + } + const template = await this.plugin.loadHexTemplate(); + if (template === null) return 0; + let created = 0; + let done = 0; + const CHUNK = 20; + for (let i = 0; i < cells.length; i += CHUNK) { + await Promise.all( + cells.slice(i, i + CHUNK).map(async ([key, terrain]) => { + const { x, y } = hexXY(key); + if (!this.plugin.app.vault.getAbstractFileByPath(this.plugin.hexPath(x, y, mapName))) { + if (await this.plugin.createHexNote(x, y, mapName, template, terrain)) created++; + } + done++; + }), + ); + onProgress?.(done); + } + return created; + } + + async generateHexNotes( + mapName: string, + xs: number[], + ys: number[], + onProgress?: (done: number) => void, + terrainAt?: Map, + ): Promise { + if (this.plugin.mapStore.isReady()) { + const cells: [string, string][] = []; + for (const x of xs) for (const y of ys) { + const t = terrainAt?.get(hexKey(x, y)); + if (t) cells.push([hexKey(x, y), t]); + } + if (cells.length) return this.plugin.generateHexNotesAt(mapName, cells); + onProgress?.(xs.length * ys.length); + return 0; + } + // Read template once — avoids N vault reads for the same file + const template = await this.plugin.loadHexTemplate(); + if (template === null) return 0; + + let created = 0; + let done = 0; + const CHUNK = 20; + const pairs: [number, number][] = []; + for (const x of xs) for (const y of ys) pairs.push([x, y]); + for (let i = 0; i < pairs.length; i += CHUNK) { + await Promise.all( + pairs.slice(i, i + CHUNK).map(async ([x, y]) => { + const path = this.plugin.hexPath(x, y, mapName); + if (!this.plugin.app.vault.getAbstractFileByPath(path)) { + const terrain = terrainAt?.get(hexKey(x, y)); + // createHexNote writes the terrain and its encounter link in one go. + if (await this.plugin.createHexNote(x, y, mapName, template, terrain)) created++; + } + done++; + }), + ); + onProgress?.(done); + } + return created; + } + + /** + * How a back-link to a hex note reads: the hex's name, else + * " x, y" (round 6 S2). Paths outside the hex folder fall back to + * the note's name. + */ + hexLinkAlias(hexPath: string): string { + const folder = normalizeFolder(this.plugin.settings.hexFolder); + const rel = folder && hexPath.startsWith(folder + "/") ? hexPath.slice(folder.length + 1) : hexPath; + const m = /^(.+)\/(-?\d+)_(-?\d+)\.md$/.exec(rel); + if (!m) return rel.replace(/^.*\//, "").replace(/\.md$/i, ""); + const [, map, x, y] = m; + const name = this.plugin.mapStore.get(map, `${x}_${y}`)?.name?.trim(); + return name || `${this.plugin.mapLabel(map)} ${x}, ${y}`; + } +} diff --git a/src/services/MapsService.ts b/src/services/MapsService.ts new file mode 100644 index 00000000..e86e7434 --- /dev/null +++ b/src/services/MapsService.ts @@ -0,0 +1,456 @@ +/** + * The map list and the links between maps: finding, creating, naming, + * restoring and removing maps, submap / region links and what a map + * inherits from the maps above it. Split from HexmakerPlugin (plan- + * architecture-refactor L1a); the plugin keeps one-line delegations. + */ +import { Notice, TFile, TFolder } from "obsidian"; +import { noticeUpgrade } from "../ui/notify"; +import { HexMapView } from "../hex-map/HexMapView"; +import { + DEFAULT_PALETTE_NAME, + VIEW_TYPE_HEX_MAP, +} from "../constants"; +import { defaultPaletteFor } from "../palettes/paletteOptions"; +import { normalizeFolder, slugify } from "../utils"; +import type { + MapData, +} from "../types"; +import { pluginVersion } from "../compat"; +import { workModeOf, type ModeAction, type WorkMode } from "../workMode"; +import { inheritedRoleTables, type RoleTablePick } from "../worldgen/tableSources"; +import { NAMES_ROLE, type RoleId } from "../worldgen/tableRoles"; +import { rollMapName } from "../maps/mapNames"; +import { effectiveTerrainType } from "../terrainTypes"; +import type { FiredEvent } from "../arrival/eventsLedger"; +import { effectiveArrivalMode, type ArrivalMode } from "../arrival/arrival"; +import { + addLocationPatch, + applyRegionSettingsEdit, + hexChildMaps, + regionMapAt, + regionsLocked, + removeMapPatch, + renameMapPatch, + setRegionPatch, +} from "../maps/submaps"; +import type { RegionSettings } from "../types"; +import { displayNameFor, mapLabel } from "../maps/mapTree"; +import type HexmakerPlugin from "../HexmakerPlugin"; +import { hexKey, strictHexXY } from "../hexKey"; +import { ensureFolder } from "../vault/ensureFolder"; + +/** What MapsService uses of the plugin. */ +export type MapsHost = Pick; + +/** What a new map is made with (createNewMap). */ +export interface NewMapOptions { + /** The name as typed (the folder is its slug, unless `slug`). */ + name: string; + cols: number; + rows: number; + /** Its palette (installed from the presets on first use). */ + palette: string; + /** Grid offset (default 0, 0). */ + offset?: { x: number; y: number }; + stagger?: "odd" | "even"; + onProgress?: (done: number, total: number) => void; + /** Optional generated terrain per hex, keyed "x_y". */ + terrain?: Map; + /** Terrain shown on unpainted hexes. Cells equal to it aren't + * written to the map note. Hex notes are created on use either way. */ + baseTerrain?: string; + parent?: { map: string; hex: string }; + /** Silence the "generated N notes" notice (caller reports instead). */ + quiet?: boolean; + /** Folder name (slug) to use instead of one made from the name (NAV2). */ + slug?: string; + /** Hexes left to roll on arrival ("x_y" → table link), for the On arrival column. */ + arrivals?: Map; + /** Once rows the generator fired (SP6), written to the Events ledgers once the map exists. */ + events?: FiredEvent[]; +} + +export class MapsService { + constructor(private readonly plugin: MapsHost) {} + + /** Show a map in the hex map view, opening the view if it isn't open. */ + async showMap(name: string): Promise { + let leaf = this.plugin.app.workspace.getLeavesOfType(VIEW_TYPE_HEX_MAP)[0]; + if (!leaf) { + leaf = this.plugin.app.workspace.getLeaf("tab"); + await leaf.setViewState({ type: VIEW_TYPE_HEX_MAP, active: true }); + } + await this.plugin.app.workspace.revealLeaf(leaf); + // Revealing loads a deferred tab, so this is the map view by now. + if (leaf.view instanceof HexMapView) leaf.view.switchMapFromModal(name); + } + + /** + * Switch a map's work mode (saved as `mode:` in its map note). An open map + * view showing it switches through its own setWorkMode (puts a locked tool + * down, refreshes its bars); otherwise the map is just saved. + */ + setMapWorkMode(mapName: string, mode: WorkMode): void { + const map = this.plugin.getMap(mapName); + if (!map) return; + let viaView = false; + for (const leaf of this.plugin.app.workspace.getLeavesOfType(VIEW_TYPE_HEX_MAP)) { + if (leaf.view instanceof HexMapView && leaf.view.activeMapName === mapName) { + leaf.view.setWorkMode(mode); + viaView = true; + } + } + if (viaView || workModeOf(map) === mode) return; + map.workMode = mode; + void this.plugin.saveSettings(); + } + + async autoRegisterMapsFromVault(): Promise { + const hexFolder = normalizeFolder(this.plugin.settings.hexFolder); + if (!hexFolder) return; + const root = this.plugin.app.vault.getAbstractFileByPath(hexFolder); + if (!(root instanceof TFolder)) return; + + const registered = new Set(this.plugin.settings.maps.map((m) => m.name)); + const added: string[] = []; + + for (const child of root.children) { + if (!(child instanceof TFolder)) continue; + if (registered.has(child.name)) continue; + + // Infer grid bounds from hex note filenames (pattern: x_y.md) + let minX = Infinity, maxX = -Infinity; + let minY = Infinity, maxY = -Infinity; + for (const file of child.children) { + if (!(file instanceof TFile)) continue; + const at = strictHexXY(file.basename); + if (!at) continue; + const { x, y } = at; + if (x < minX) minX = x; + if (x > maxX) maxX = x; + if (y < minY) minY = y; + if (y > maxY) maxY = y; + } + + const cols = isFinite(maxX) ? maxX - minX + 1 : 20; + const rows = isFinite(maxY) ? maxY - minY + 1 : 16; + const offsetX = isFinite(minX) ? minX : 0; + const offsetY = isFinite(minY) ? minY : 0; + const paletteName = + this.plugin.settings.terrainPalettes[0]?.name ?? DEFAULT_PALETTE_NAME; + + this.plugin.settings.maps.push({ + name: child.name, + paletteName, + gridSize: { cols, rows }, + gridOffset: { x: offsetX, y: offsetY }, + pathChains: [], + }); + added.push(child.name); + } + + if (added.length === 0) return; + + if (!this.plugin.settings.defaultMap || !registered.has(this.plugin.settings.defaultMap)) { + this.plugin.settings.defaultMap = added[0]; + } + await this.plugin.saveSettings(); + noticeUpgrade( + `auto-registered ${added.length} map${added.length > 1 ? "s" : ""} from vault: ${added.join(", ")}`, + ); + } + + /** A map was renamed: every hex's Region map / Locations link to it follows. */ + async updateSubmapReferences(oldName: string, newName: string): Promise { + for (const m of this.plugin.settings.maps) { + for (const [key, h] of [...this.plugin.mapStore.all(m.name)]) { + const patch = renameMapPatch(h, oldName, newName); + if (patch) this.plugin.mapStore.set(m.name, key, patch); + } + } + this.noParentMaps.clear(); + // Children of the renamed map keep their breadcrumb. + for (const m of this.plugin.settings.maps) { + if (m.parent?.map === oldName) m.parent.map = newName; + } + } + + /** + * Create hex notes for every (x, y) in the cartesian product of xs × ys, + * skipping any that already exist on disk. Returns the number of notes created. + */ + /** + * Restore a missing map (SM-DEL): its note is written back from the last + * saved copy (see MapStore.restoreMissing). Says what it did. + */ + async restoreMissingMap(name: string): Promise { + const r = await this.plugin.mapStore.restoreMissing(name); + if ("error" in r) { + new Notice(r.error); + return false; + } + const how = r.source === "settings" ? " from its settings (no saved copy of its hexes was found)" : r.source === "note" ? " (its note was back)" : ""; + new Notice(`Restored map "${this.plugin.mapLabel(name)}"${how}.`); + this.plugin.refreshHexMap(); + return true; + } + + /** + * Remove a map from the map list without touching files (a missing map's + * folder is already gone). Links to it in other maps are dropped and its + * regions and locations become top-level maps, as when deleting a map. + */ + async removeMapEntry(name: string): Promise { + this.plugin.settings.maps = this.plugin.settings.maps.filter((m) => m.name !== name); + if (this.plugin.settings.defaultMap === name) this.plugin.settings.defaultMap = this.plugin.settings.maps[0]?.name ?? ""; + this.plugin.mapStore.forgetMap(name); + this.plugin.undoBook.forgetMap(name); + for (const m of this.plugin.settings.maps) { + for (const [key, h] of [...this.plugin.mapStore.all(m.name)]) { + const patch = removeMapPatch(h, name); + if (Object.keys(patch).length) this.plugin.mapStore.set(m.name, key, patch); + } + if (m.parent?.map === name) { + delete m.parent; + delete m.submapKind; + } + } + for (const leaf of this.plugin.app.workspace.getLeavesOfType(VIEW_TYPE_HEX_MAP)) { + if (leaf.view instanceof HexMapView && leaf.view.activeMapName === name) leaf.view.activeMapName = this.plugin.settings.maps[0]?.name ?? ""; + } + await this.plugin.saveSettings(); + this.plugin.refreshHexMap(); + } + + async createNewMap(opts: NewMapOptions): Promise<{ name: string } | { error: string }> { + const { name: rawName, cols, rows, palette: paletteName, stagger: staggerOffset, onProgress, terrain: terrainAt } = opts; + const initialX = opts.offset?.x ?? 0; + const initialY = opts.offset?.y ?? 0; + if (!rawName.trim()) return { error: "Enter a map name." }; + const name = slugify(opts.slug?.trim() || rawName); + if (!name) return { error: opts.slug ? "Enter a folder name." : "Enter a map name." }; + if (this.plugin.settings.maps.some((r) => r.name === name)) + return { error: `Map "${name}" already exists.` }; + + await this.plugin.ensurePaletteInstalled(paletteName); + + const hexFolder = normalizeFolder(this.plugin.settings.hexFolder); + const folderPath = hexFolder ? `${hexFolder}/${name}` : name; + await ensureFolder(this.plugin.app.vault, folderPath); + + // The slug names the folder; the name as typed is what the UI shows. + const displayName = displayNameFor(rawName, name); + this.plugin.settings.maps.push({ + name, + ...(displayName ? { displayName } : {}), + paletteName, + gridSize: { cols, rows }, + gridOffset: { x: initialX, y: initialY }, + pathChains: [], + staggerOffset, + createdWith: pluginVersion(this.plugin), + // The GM layer starts off on a new map (round 6 S7: it was on for a + // tester who never turned it on). Maps without the key keep the old + // "on" default, so existing maps don't change. + showGmLayer: false, + ...(opts.baseTerrain ? { baseTerrain: opts.baseTerrain } : {}), + ...(opts.parent ? { parent: opts.parent } : {}), + }); + await this.plugin.saveSettings(); + + // Notes on use: a new map writes no hex notes — terrain goes into the + // map note, and a hex note appears when the hex first gets content. + const cells: [string, { terrain?: string; onArrival?: string }][] = [...(terrainAt ?? new Map())] + .filter(([, t]) => t && t !== opts.baseTerrain) + .map(([k, t]): [string, { terrain?: string; onArrival?: string }] => [k, { terrain: t }]); + for (const [k, table] of opts.arrivals ?? []) { + const c = cells.find(([key]) => key === k); + if (c) c[1].onArrival = table; + else cells.push([k, { onArrival: table }]); + } + this.plugin.mapStore.setMany(name, cells); + onProgress?.(cols * rows, cols * rows); + await this.plugin.mapStore.flush(); + await this.plugin.events.record(name, opts.events); + if (!opts.quiet) new Notice(`Created map "${displayName ?? name}".`); + + return { name }; + } + + getMap(name: string): MapData | undefined { + return this.plugin.settings.maps.find((r) => r.name === name); + } + + /** A map's name for the UI: its display name, else its slug (or `name` itself if unknown). */ + mapLabel(name: string): string { + return mapLabel(this.plugin.getMap(name), name); + } + + /** + * Rename a map for display only: the folder, map note and every + * reference keep the slug. Blank (or the slug itself) clears it. + */ + async setMapDisplayName(name: string, typed: string): Promise { + const map = this.plugin.getMap(name); + if (!map) return; + const oldLabel = this.plugin.mapLabel(name); + map.displayName = displayNameFor(typed, name); + await this.plugin.saveSettings(); + await this.plugin.syncMapCoordAliases(name, oldLabel); + } + + /** + * Add `childMap` to the Locations of hex (x, y) on `parentMap` (K7: any + * number per hex) and record the parent on the child map (first link + * wins, so linking a shared map from a second hex doesn't move its + * breadcrumb). + */ + async linkSubmap(parentMap: string, x: number, y: number, childMap: string, action: ModeAction = "link-map"): Promise { + if (childMap === parentMap) return; + const key = hexKey(x, y); + const patch = addLocationPatch(this.plugin.mapStore.get(parentMap, key), childMap); + if (patch.locations && !this.plugin.mapStore.set(parentMap, key, patch, action)) return; + this.noParentMaps.clear(); + const child = this.plugin.getMap(childMap); + if (child && !child.parent) { + child.parent = { map: parentMap, hex: key }; + child.submapKind = "location"; + await this.plugin.saveSettings(); + } + } + + /** + * Make `childMap` the Region map of hex (x, y) on `parentMap`: the child + * becomes a region of it (its record is the truth; the hex mirrors it). + * Refused when the hex already has another region (one per hex). + */ + async linkRegion(parentMap: string, x: number, y: number, childMap: string): Promise { + const key = hexKey(x, y); + const other = regionMapAt(this.plugin.settings.maps, parentMap, key); + if (childMap === parentMap || (other && other.name !== childMap)) return false; + const child = this.plugin.getMap(childMap); + if (!child) return false; + child.parent = { map: parentMap, hex: key }; + child.submapKind = "region"; + this.plugin.mapStore.set(parentMap, key, setRegionPatch(this.plugin.mapStore.get(parentMap, key), childMap)); + this.noParentMaps.clear(); + await this.plugin.saveSettings(); + return true; + } + + /** + * Unlink `childMap` (or, without one, every map) from hex (x, y): its + * region and/or locations. A child whose parent was this hex loses it. + */ + async unlinkSubmap(parentMap: string, x: number, y: number, childMap?: string): Promise { + const key = hexKey(x, y); + const h = this.plugin.mapStore.get(parentMap, key); + const names = childMap ? [childMap] : hexChildMaps(h); + let changed = false; + for (const n of names) { + const patch = removeMapPatch(this.plugin.mapStore.get(parentMap, key), n); + if (Object.keys(patch).length && !this.plugin.mapStore.set(parentMap, key, patch, "link-map")) continue; + const child = this.plugin.getMap(n); + if (child?.parent?.map === parentMap && child.parent.hex === key) { + delete child.parent; + // A region without its hex is just a map (it keeps its world slot). + delete child.submapKind; + changed = true; + } + } + this.noParentMaps.clear(); + if (changed) await this.plugin.saveSettings(); + } + + /** Reorder the Locations of hex (x, y). */ + setHexLocations(parentMap: string, x: number, y: number, locations: string[]): void { + this.plugin.mapStore.set(parentMap, hexKey(x, y), { locations: locations.length ? locations : null }, "link-map"); + } + + /** Save region settings on `mapName` (fixed fields stay put while it has regions). */ + async setRegionSettings(mapName: string, next: RegionSettings): Promise { + const map = this.plugin.getMap(mapName); + if (!map) return; + const locked = regionsLocked(this.plugin.settings.maps, mapName); + const first = !map.regions; + map.regions = map.regions ? applyRegionSettingsEdit(map.regions, next, locked) : next; + await this.plugin.saveSettings(); + // The first overworld: its biomes need the shipped biome notes (DJ-Q4). + if (first) await this.plugin.ensureOverworldBiomes(); + } + + /** + * The map `mapName` was opened from (as a region or location). Uses the + * stored parent; for maps linked before parents were stored, scans the + * hexes' Region map and Locations for it and remembers the first hit. + */ + parentOf(mapName: string): { map: string; hex: string } | undefined { + const map = this.plugin.getMap(mapName); + if (!map) return undefined; + if (map.parent && this.plugin.getMap(map.parent.map)) return map.parent; + // Root maps have no parent; don't rescan the hex notes on every switch. + if (this.noParentMaps.has(mapName)) return undefined; + for (const m of this.plugin.settings.maps) { + if (m.name === mapName) continue; + for (const [key, h] of this.plugin.mapStore.all(m.name)) { + if (h.regionMap !== mapName && !h.locations?.includes(mapName)) continue; + map.parent = { map: m.name, hex: key }; + void this.plugin.saveSettings(); + return map.parent; + } + } + this.noParentMaps.add(mapName); + return undefined; + } + + /** + * Each generator role's table set on `mapName` or the nearest map above + * it (Map properties → Tables, T11), with the map that set it. + */ + roleTablesFor(mapName: string): Partial> { + return inheritedRoleTables(mapName, (m) => this.plugin.getMap(m)?.roleTables, (m) => this.plugin.parentOf(m)?.map); + } + + /** + * A name for a map made from hex `hexKey` of `parentMap`, rolled on the + * Names table set there or on a map above it (the Names role), with the + * hex's terrain and type as When context. Undefined with no table (the + * caller uses the hex's terrain and coordinates). Seeded with `seed`. + */ + rolledMapName(parentMap: string, hexKey: string, seed?: number): string | undefined { + const link = this.plugin.roleTablesFor(parentMap)[NAMES_ROLE.id]?.link; + if (!link) return undefined; + const terrain = this.plugin.mapStore.get(parentMap, hexKey)?.terrain ?? this.plugin.getMap(parentMap)?.baseTerrain; + const entry = terrain ? this.plugin.getMapPalette(parentMap).find((t) => t.name === terrain) : undefined; + const type = entry ? effectiveTerrainType(entry) : undefined; + return rollMapName(link, this.plugin.tableNotes.lookup(), { + ...(terrain ? { terrain } : {}), + ...(type ? { type } : {}), + ...(seed !== undefined ? { seed } : {}), + }); + } + + /** "When you arrive somewhere new" for `mapName`: its own setting, else the nearest map above it's, else off. */ + arrivalModeFor(mapName: string): { mode: ArrivalMode; from?: string } { + return effectiveArrivalMode(mapName, (m) => this.plugin.getMap(m)?.arrivalMode, (m) => this.plugin.parentOf(m)?.map); + } + + /** Maps whose parent scan came up empty this session (cleared on any link change). */ + private noParentMaps = new Set(); + + getOrCreateMap(name: string): MapData { + let r = this.plugin.getMap(name); + if (!r) { + r = { + name, + paletteName: defaultPaletteFor(this.plugin.settings), + gridSize: { cols: 20, rows: 16 }, + gridOffset: { x: 0, y: 0 }, + pathChains: [], + }; + this.plugin.settings.maps.push(r); + } + return r; + } +} diff --git a/src/services/PaletteQueries.ts b/src/services/PaletteQueries.ts new file mode 100644 index 00000000..9bcd56dc --- /dev/null +++ b/src/services/PaletteQueries.ts @@ -0,0 +1,223 @@ +/** + * The palettes as the rest of the plugin asks for them: by name (installed + * or a preset), per map (its palette, terrains and path types), the + * terrains of every palette, submap defaults, and installing presets or + * the default palettes. Split from HexmakerPlugin (plan-architecture- + * refactor L1a); the plugin keeps one-line delegations. + */ +import { Notice } from "obsidian"; +import { + DEFAULT_PATH_TYPES, + DEFAULT_SETTINGS, +} from "../constants"; +import { clonePalette, missingDefaults } from "../palettes/PaletteStore"; +import { fillPalettePathTypes } from "../migrations/v1.5-palette-path-types"; +import { paletteKind, type MapKind } from "../mapKinds"; +import { defaultPaletteFor } from "../palettes/paletteOptions"; +import { + getPreset, + presetToPalette, + uniquePaletteName, +} from "../palettes/presets"; +import { clonePathTypes } from "../palettes/pathTypeTable"; +import type { + MapData, + PathType, + SubmapDefault, + TerrainColor, + TerrainPalette, +} from "../types"; +import type HexmakerPlugin from "../HexmakerPlugin"; + +/** What PaletteQueries uses of the plugin. */ +export type PaletteHost = Pick; + +export class PaletteQueries { + constructor(private readonly plugin: PaletteHost) {} + + getPaletteByName(name: string): TerrainPalette | undefined { + return this.plugin.settings.terrainPalettes.find((p) => p.name === name); + } + + /** + * Terrains for an installed palette, or for a built-in preset that isn't + * installed yet (lets new-map dropdowns preview presets before install). + */ + getPaletteOrPresetTerrains(name: string): TerrainColor[] { + return this.plugin.getPaletteByName(name)?.terrains ?? getPreset(name)?.terrains ?? []; + } + + /** The map type of a palette (or a preset not installed yet): see paletteKind. */ + getPaletteOrPresetKind(name: string): MapKind { + return paletteKind(this.plugin.getPaletteByName(name) ?? getPreset(name)); + } + + /** + * Path types maps on this palette can draw, in picker order: the palette's + * own list (the live array, so editors can change it in place), a preset's + * when it isn't installed, else the old plugin-wide list or Road and River. + */ + getPathTypes(paletteName: string | undefined): PathType[] { + const pal = paletteName ? this.plugin.getPaletteByName(paletteName) : this.plugin.settings.terrainPalettes[0]; + const fallback = this.plugin.settings.pathTypes?.length ? this.plugin.settings.pathTypes : DEFAULT_PATH_TYPES; + if (pal) return (pal.pathTypes ??= clonePathTypes(fallback)); + return (paletteName ? getPreset(paletteName)?.pathTypes : undefined) ?? fallback; + } + + /** The palette a map actually uses: its own when installed, else the first. */ + mapPaletteName(mapName: string | undefined): string { + const map = mapName ? this.plugin.getMap(mapName) : undefined; + if (map?.paletteName && this.plugin.getPaletteByName(map.paletteName)) return map.paletteName; + return this.plugin.settings.terrainPalettes[0]?.name ?? ""; + } + + /** Path types for a map: its palette's (see getPathTypes). */ + getMapPathTypes(mapName: string | undefined): PathType[] { + return this.plugin.getPathTypes(this.plugin.mapPaletteName(mapName)); + } + + /** Maps whose palette is `paletteName` (see mapPaletteName). */ + mapsOnPalette(paletteName: string): MapData[] { + return this.plugin.settings.maps.filter((m) => this.plugin.mapPaletteName(m.name) === paletteName); + } + + /** + * Add a copy of a built-in preset as a new palette (a unique name is chosen + * if the preset's name is taken), with the preset's path types. Saves; + * the palette note is written by the sync that follows. Returns the new + * palette's name. + */ + async installPalettePreset(presetName: string, asName?: string, opts: { quiet?: boolean } = {}): Promise { + const preset = getPreset(presetName); + if (!preset) return undefined; + const name = uniquePaletteName( + asName ?? preset.name, + this.plugin.settings.terrainPalettes.map((p) => p.name), + ); + const palette = presetToPalette(preset, name); + this.plugin.settings.terrainPalettes.push(palette); + await this.plugin.saveSettings(); + // Give the new terrains their description/encounters tables when the + // vault uses terrain tables, so a submap's hexes get an encounters + // table like the parent's (round 7: a system map installed "Space - + // System" and its "ice planet" hex showed Encounters Table "None"). + await this.plugin.ensureTablesForNewTerrains(); + // Installed on first use by a new map: expected, so no notice (F12). + if (!opts.quiet) new Notice(`Added palette "${name}".`); + return name; + } + + /** + * Palette to pre-select for a new submap of `parentMap`: the parent + * palette's `childPalette` (its note's `child-palette`; the preset's only + * while that preset isn't installed), else the parent's own palette, else + * the palette for new maps. An installed palette is never topped up from + * a same-named preset: clearing its child palette means none. + */ + childPaletteFor(parentMap: string): string { + const parentPaletteName = this.plugin.getMap(parentMap)?.paletteName; + const parentPalette = parentPaletteName ? this.plugin.getPaletteByName(parentPaletteName) : undefined; + const child = parentPalette + ? parentPalette.childPalette + : parentPaletteName ? getPreset(parentPaletteName)?.childPalette : undefined; + if (child && (this.plugin.getPaletteByName(child) || getPreset(child))) return child; + if (parentPalette) return parentPalette.name; + return defaultPaletteFor(this.plugin.settings); + } + + /** + * Saved setup for a new submap made from a `terrain` hex on `parentMap`: + * the parent palette's Submap defaults row for that terrain (from its + * note). Only a preset that isn't installed answers from its own rows; + * palettes installed before their preset gained defaults got the rows + * copied in once (PaletteStore, `paletteDataUpgraded`), so a row the user + * deletes stays deleted. + */ + submapDefaultFor(parentMap: string, terrain: string | null | undefined): SubmapDefault | undefined { + if (!terrain) return undefined; + const paletteName = this.plugin.getMap(parentMap)?.paletteName; + if (!paletteName) return undefined; + const pal = this.plugin.getPaletteByName(paletteName); + if (pal) return pal.submapDefaults?.[terrain]; + return getPreset(paletteName)?.submapDefaults?.[terrain]; + } + + /** + * Remember (or forget) choices for new submaps of `terrain` on the parent + * map's palette. `set` fields are stored; `clear` fields are removed. + * Saved into the palette note's Submap defaults table by the sync. + */ + async saveSubmapDefault( + parentMap: string, + terrain: string, + set: SubmapDefault, + clear: (keyof SubmapDefault)[], + ): Promise { + const paletteName = this.plugin.getMap(parentMap)?.paletteName; + const pal = paletteName ? this.plugin.getPaletteByName(paletteName) : undefined; + if (!pal) return; + // Start from what the user currently sees (see submapDefaultFor). + const current: SubmapDefault = { ...(this.plugin.submapDefaultFor(parentMap, terrain) ?? {}) }; + for (const k of clear) delete current[k]; + Object.assign(current, set); + const defaults = { ...(pal.submapDefaults ?? {}) }; + if (Object.keys(current).length) defaults[terrain] = current; + else delete defaults[terrain]; + if (Object.keys(defaults).length) pal.submapDefaults = defaults; + else delete pal.submapDefaults; + await this.plugin.saveSettings(); + } + + /** The built-in default palettes (a fresh install's) that aren't in the palette list. */ + missingDefaultPalettes(): string[] { + return missingDefaults(this.plugin.settings.terrainPalettes, DEFAULT_SETTINGS.terrainPalettes).map((p) => p.name); + } + + /** + * Put back the default palettes that aren't there (only ever on request: + * palettes the user deleted stay deleted). Returns the names added. + */ + async addDefaultPalettes(): Promise { + const add = this.plugin.missingDefaultPalettes(); + for (const p of missingDefaults(this.plugin.settings.terrainPalettes, DEFAULT_SETTINGS.terrainPalettes)) { + this.plugin.settings.terrainPalettes.push(clonePalette(p)); + } + if (!add.length) return add; + // Same as a fresh install's: path types from the shipped list. + fillPalettePathTypes(this.plugin.settings.terrainPalettes, this.plugin.settings.pathTypes); + await this.plugin.saveSettings(); + await this.plugin.ensureTablesForNewTerrains(); + new Notice(`Added ${add.join(" and ")}.`); + return add; + } + + /** Install `name` from the presets if no palette by that name exists yet. */ + async ensurePaletteInstalled(name: string): Promise { + if (this.plugin.getPaletteByName(name) || !getPreset(name)) return; + // A new map installing its palette is expected: no notice (F12). + await this.plugin.installPalettePreset(name, undefined, { quiet: true }); + } + + getMapPalette(mapName: string): TerrainColor[] { + const map = this.plugin.getMap(mapName); + return ( + this.plugin.getPaletteByName(map?.paletteName ?? "")?.terrains ?? + this.plugin.settings.terrainPalettes[0]?.terrains ?? + [] + ); + } + + getAllTerrains(): TerrainColor[] { + const seen = new Set(); + const result: TerrainColor[] = []; + for (const pal of this.plugin.settings.terrainPalettes) { + for (const t of pal.terrains) { + if (!seen.has(t.name)) { + seen.add(t.name); + result.push(t); + } + } + } + return result; + } +} diff --git a/src/services/TemplatesService.ts b/src/services/TemplatesService.ts new file mode 100644 index 00000000..aa17035c --- /dev/null +++ b/src/services/TemplatesService.ts @@ -0,0 +1,162 @@ +/** + * Note templates: the hex template (configured, in the templates folder, + * or built in), each link section's note template, filling a new linked + * note, and which notes a note picker may offer (templates only when + * picking one). Split from HexmakerPlugin (plan-architecture-refactor + * L1a); the plugin keeps one-line delegations. + */ +import { Notice, TFile } from "obsidian"; +import { generatorsFolder } from "../worldgen/generators"; +import { moduleFolders } from "../modules/runtime"; +import { normalizeFolder, makeTableTemplate } from "../utils"; +import DEFAULT_HEX_TEMPLATE from "../defaultHexTemplate.md"; +import { isLinkableNotePath, templateNoteRules, type NotePickPurpose, type TemplateNoteRules } from "../templateNotes"; +import { fillNoteTemplate, hexTemplatePathFor, LINK_NOTE_TEMPLATES, linkNoteTemplate, linkNoteTemplatePathFor, LOCATION_SECTIONS, templatesFolderFor, withLocationLine } from "../noteTemplates"; +import type HexmakerPlugin from "../HexmakerPlugin"; +import { ensureFolder } from "../vault/ensureFolder"; + +/** The plugin: the template rules hand it to module code (moduleFolders, generatorsFolder). */ +export type TemplatesHost = HexmakerPlugin; + +export class TemplatesService { + constructor(private readonly plugin: TemplatesHost) {} + + /** + * Whether a note may be offered in a note picker: never `_`-prefixed; + * templates (the hex template, workflow templates, the core Templates or + * Templater folder) only when the picker is for choosing a template + * (`purpose` "template"). Use in every note picker. + */ + isLinkableNote(file: TFile, purpose: NotePickPurpose = "link"): boolean { + return isLinkableNotePath(file.path, file.basename, this.templateRules(), purpose); + } + + private templateRules(): TemplateNoteRules { + type Loose = { + internalPlugins?: { + getPluginById?(id: string): { enabled?: boolean; instance?: { options?: { folder?: string } } } | null; + }; + plugins?: { plugins?: Record }; + }; + const loose = this.plugin.app as unknown as Loose; + const core = loose.internalPlugins?.getPluginById?.("templates"); + const coreFolder = core?.enabled ? core.instance?.options?.folder : undefined; + const templater = loose.plugins?.plugins?.["templater-obsidian"]?.settings?.templates_folder; + return templateNoteRules(this.plugin.settings, [coreFolder, templater], [ + this.plugin.paletteStore.folder(), + ...this.plugin.moduleStores.flatMap((st) => (st.folder ? [st.folder()] : [])), + ...moduleFolders(this.plugin), + generatorsFolder(this.plugin), + ]); + } + + async loadHexTemplate(): Promise { + const templatePath = normalizeFolder(this.plugin.settings.templatePath ?? ""); + if (templatePath) { + const templateFile = this.plugin.app.vault.getAbstractFileByPath(templatePath); + if (templateFile instanceof TFile) { + try { + return await this.plugin.app.vault.read(templateFile); + } catch { /* fall through */ } + } + new Notice(`Hex template not found at "${templatePath}" — using built-in default.`); + return DEFAULT_HEX_TEMPLATE; + } + // No path set: hex.md in the templates folder, if there is one (PA3). + const inFolder = this.plugin.app.vault.getAbstractFileByPath(hexTemplatePathFor(this.plugin.settings)); + if (inFolder instanceof TFile) { + try { + return await this.plugin.app.vault.read(inFolder); + } catch { /* fall through */ } + } + return DEFAULT_HEX_TEMPLATE; + } + + /** The plugin's templates folder (PA3; see src/noteTemplates.ts). */ + templatesFolder(): string { + return templatesFolderFor(this.plugin.settings); + } + + /** Create a note template file from its built-in default if it's missing. */ + private async ensureTemplateFile(path: string, content: string): Promise { + if (this.plugin.app.vault.getAbstractFileByPath(path)) return; + const folder = path.includes("/") ? path.slice(0, path.lastIndexOf("/")) : ""; + if (folder) await ensureFolder(this.plugin.app.vault, folder); + try { + await this.plugin.app.vault.create(path, content); + } catch { /* created concurrently — fine */ } + } + + /** + * Make sure the templates folder holds every plugin note template: the + * hex template (unless the user points templatePath elsewhere) and each + * link section's note template. Existing files are never overwritten. + */ + async ensureTemplates(): Promise { + await this.plugin.ensureHexTemplate(); + for (const section of Object.keys(LINK_NOTE_TEMPLATES)) { + const path = linkNoteTemplatePathFor(this.plugin.settings, section); + if (path) await this.ensureTemplateFile(path, LINK_NOTE_TEMPLATES[section].starter); + } + } + + /** + * Open a note template to edit it (SX1: easy to find and edit), making + * it from its built-in starter first if it isn't there yet. + */ + async openNoteTemplate(path: string): Promise { + await this.plugin.ensureTemplates(); + const file = this.plugin.app.vault.getAbstractFileByPath(path); + if (file instanceof TFile) await this.plugin.app.workspace.getLeaf("tab").openFile(file); + else new Notice(`No template at ${path}.`); + } + + /** + * Starting text for a note made from a link section's "create new": the + * section's note template (LINK_NOTE_TEMPLATES, written to the templates + * folder on first use); encounter tables get a table. `title` fills {{title}}. + */ + async newLinkedNoteContent(section: string, title: string, fromHex?: string): Promise { + if (section === "Encounters Table") return makeTableTemplate(this.plugin.settings.defaultTableDice); + // Made from a hex: a place says where it is (R3). + const located = (content: string) => + fromHex && LOCATION_SECTIONS.includes(section) ? this.plugin.withHexLocation(content, fromHex) : content; + const tpl = linkNoteTemplate(section); + const path = linkNoteTemplatePathFor(this.plugin.settings, section); + if (!tpl || !path) return located(""); + await this.ensureTemplateFile(path, tpl.starter); + const file = this.plugin.app.vault.getAbstractFileByPath(path); + let template = tpl.starter; + if (file instanceof TFile) { + try { + template = await this.plugin.app.vault.read(file); + } catch { /* use the default */ } + } + return located(fillNoteTemplate(template, title)); + } + + /** `content` with a `Location: [[hex| x, y]]` line under its title (R3). */ + withHexLocation(content: string, hexPath: string): string { + const loc = this.plugin.mapStore.resolve(hexPath); + const [x, y] = loc ? loc.key.split("_") : []; + const label = loc ? this.plugin.hexCoordAlias(loc.map, x, y) : this.plugin.hexLinkAlias(hexPath); + return withLocationLine(content, hexPath, label); + } + + /** + * Ensure a hex template file exists on disk. + * - If templatePath is set and the file exists: no-op. + * - If templatePath is set but the file is missing: create it from the built-in default. + * - If templatePath is blank: create hex.md in the templates folder (PA3) + * and persist the path. + */ + async ensureHexTemplate(): Promise { + let templatePath = normalizeFolder(this.plugin.settings.templatePath ?? ""); + if (!templatePath) { + templatePath = hexTemplatePathFor(this.plugin.settings); + this.plugin.settings.templatePath = templatePath; + await this.plugin.saveSettings(); + } + await this.ensureTemplateFile(templatePath, DEFAULT_HEX_TEMPLATE); + } +} diff --git a/src/services/TerrainTablesService.ts b/src/services/TerrainTablesService.ts new file mode 100644 index 00000000..2ebebc7b --- /dev/null +++ b/src/services/TerrainTablesService.ts @@ -0,0 +1,669 @@ +/** + * The tables the plugin keeps for terrains and areas: each terrain's + * description / encounters tables (made empty for new terrains, HG5; moved + * or copied on rename), the area encounter tables, the shipped tables, + * roller blocks, the encounter-table links in hex notes, and renaming a + * terrain everywhere. Split from HexmakerPlugin (plan-architecture- + * refactor L1c); the plugin keeps one-line delegations. + */ +import { Notice, TFile } from "obsidian"; +import { locateRollTable, withRollerBlock } from "../random-tables/randomTable"; +import { processTableNote } from "../random-tables/TableStore"; +import { enabledKinds, newTerrains, terrainsForTables } from "../mapKinds"; +import { registry } from "../modules"; +import { normalizeFolder, makeTableTemplate } from "../utils"; +import { shippedTablesToInstall } from "../random-tables/shippedTables"; +import type { + TerrainColor, +} from "../types"; +import { writeJsonBackup } from "../backup"; +import { getTerrainFromFile, getHexRegionFromFile } from "../frontmatter"; +import { migrate as migrateFlatTerrainTables } from "../migrations/v1.0-flat-terrain-tables-to-subfolders"; +import { + addLinkToSection, + getLinksInSection, + removeLinkFromSection, +} from "../sections"; +import type HexmakerPlugin from "../HexmakerPlugin"; +import { logError } from "../log"; +import { ensureFolder, ensureFolderPath } from "../vault/ensureFolder"; +import { hexKey, hexXY } from "../hexKey"; + +/** What TerrainTablesService uses of the plugin. */ +export type TerrainTablesHost = Pick; + +export class TerrainTablesService { + constructor(private readonly plugin: TerrainTablesHost) {} + + /** Terrain names that have (or were offered) tables; new ones get theirs (HG5). */ + tableTerrainNames: Set | null = null; + + /** Table creation runs one batch at a time; awaiting any call waits for those before it. */ + private terrainTablesQueue: Promise = Promise.resolve(); + + /** + * Filter a list of table files using a two-tier system: + * 1. Per-file frontmatter (`filterKey: false` excludes, `filterKey: true` forces include) + * 2. Folder-level exclusion list (paths relative to tablesFolder) + */ + filterTableFiles( + files: TFile[], + filterKey: "roll-filter" | "encounter-filter", + excludedFolders: string[], + ): TFile[] { + const folder = normalizeFolder(this.plugin.settings.tablesFolder); + const prefix = folder ? folder + "/" : ""; + return files.filter((f) => { + const fm = this.plugin.app.metadataCache.getFileCache(f)?.frontmatter; + if (fm != null) { + const val: unknown = fm[filterKey]; + if (val === false) return false; + if (val === true) return true; + } + const rel = prefix ? f.path.slice(prefix.length) : f.path; + return !excludedFolders.some((exc) => rel.startsWith(exc + "/")); + }); + } + + /** Build an embedded roller code block (path-less — reads the current file). */ + buildRollerLink(): string { + return "```duckmage-roller\n```"; + } + + /** + * Give a table note the roller block, replacing an old + * obsidian://duckmage-roll link. Never touches "_" notes or notes with no + * roll table. Returns true when the note changed. + */ + async ensureRollerLink(filePath: string): Promise { + const file = this.plugin.app.vault.getAbstractFileByPath(filePath); + if (!(file instanceof TFile) || file.basename.startsWith("_")) return false; + let changed = false; + await processTableNote(this.plugin.app, file, (content) => { + if (!locateRollTable(content)?.recognized) return content; + const next = withRollerBlock(content); + changed = next !== content; + return next; + }); + return changed; + } + + /** + * Write the shipped table notes of the modules of `kinds` (default: the + * map types that are on) that the tables folder doesn't have yet + * (plan-tables-everywhere phase 6). A note that's there, edited or not, + * is never touched; nothing is written when every one is there. + * Returns the paths written. + */ + async installShippedTables(kinds: readonly string[] = [...enabledKinds(this.plugin.settings)]): Promise { + const plan = shippedTablesToInstall(registry.shippedTables(kinds), normalizeFolder(this.plugin.settings.tablesFolder), (p) => !!this.plugin.app.vault.getAbstractFileByPath(p)); + const written: string[] = []; + for (const t of plan) { + const dir = t.path.split("/").slice(0, -1).join("/"); + if (dir) await ensureFolderPath(this.plugin.app.vault, dir); + try { + await this.plugin.app.vault.create(t.path, t.text); + this.plugin.tableNotes.put(t.path, t.text); + written.push(t.path); + } catch { + /* made meanwhile */ + } + } + return written; + } + + /** Add roller blocks to the table notes in the tables folder that lack one. */ + async ensureAllRollerLinks(): Promise { + const folder = normalizeFolder(this.plugin.settings.tablesFolder); + const prefix = folder ? folder + "/" : ""; + const files = this.plugin.app.vault + .getMarkdownFiles() + .filter((f) => !prefix || f.path.startsWith(prefix)); + + let count = 0; + for (const file of files) { + if (await this.plugin.ensureRollerLink(file.path)) count++; + } + // Nothing to report when every table already had its link (the setup + // wizard runs this right after creating tables that include one). + if (count > 0) + new Notice( + `Added roller links to ${count} table${count !== 1 ? "s" : ""}.`, + ); + } + + /** + * Create missing description/encounters table files for every terrain + * (`terrains`, default: those of the enabled map types — a Space-only + * vault gets none for the fantasy palettes; see terrainsForTables). + */ + async ensureTerrainTables( + terrains: TerrainColor[] = terrainsForTables(this.plugin.settings.terrainPalettes, enabledKinds(this.plugin.settings)), + kinds: Iterable = enabledKinds(this.plugin.settings), + ): Promise { + const folder = normalizeFolder(this.plugin.settings.tablesFolder); + + // Generic section tables (landmark, hidden, secret) at the root of the tables folder + for (const sectionType of ["landmark", "hidden", "secret"] as const) { + const path = folder ? `${folder}/${sectionType}.md` : `${sectionType}.md`; + if (!this.plugin.app.vault.getAbstractFileByPath(path)) { + if (folder) await ensureFolder(this.plugin.app.vault, folder); + try { + await this.plugin.app.vault.create( + path, + makeTableTemplate( + this.plugin.settings.defaultTableDice, + { + "table-type": sectionType, + "roll-filter": false, + "encounter-filter": false, + }, + this.buildRollerLink(), + ), + ); + } catch { + /* ignore */ + } + } + } + + // The modules' shipped tables: the starter weather and rumours tables + // (E2, rolled from the hex editor when the map and hex don't name their + // own) and the space generators' optional role tables. Data, never + // written over a note that's there. + await this.plugin.installShippedTables([...kinds]); + + // Terrain-specific tables + const subfolder = folder ? `${folder}/terrain` : "terrain"; + await ensureFolder(this.plugin.app.vault, subfolder); + + // Ensure type subfolders exist + for (const tableType of ["description", "encounters"] as const) { + await ensureFolder(this.plugin.app.vault, `${subfolder}/${tableType}`); + } + + // Old flat-named tables ({name} - {type}.md) move into the type folders. + await migrateFlatTerrainTables(this.plugin.app, subfolder, this.plugin.getAllTerrains().map((t) => t.name)); + + // Create any still-missing table files + await this.createTerrainTableFiles(terrains); + } + + /** + * Terrains whose description / encounter tables the vault keeps: those of + * the enabled map types' palettes (terrainsForTables), plus every palette + * a map uses. + */ + tableTerrains(): TerrainColor[] { + const inUse = this.plugin.settings.maps.map((m) => m.paletteName).filter((n): n is string => !!n); + return terrainsForTables(this.plugin.settings.terrainPalettes, enabledKinds(this.plugin.settings), inUse); + } + + /** + * Give terrains created since the last check their tables (HG5): a new + * terrain in any palette in use, from any editor, an imported palette or + * a palette note edited by hand. The tables start empty (the usual + * template, no rows). Only when the vault keeps tables (the tables folder + * exists). Awaiting it waits for the files. + */ + ensureTablesForNewTerrains(): Promise { + // A name a terrain was just renamed to by hand waits for the answer to + // "Rename everywhere" (its old tables may move to it), and names typed + // on the way there ("w", "wo"…) never get tables. + const held = this.plugin.paletteStore?.heldTerrainNames() ?? new Set(); + const terrains = this.plugin.tableTerrains().filter((t) => !held.has(t.name)); + const known = this.tableTerrainNames; + this.tableTerrainNames = new Set(terrains.map((t) => t.name)); + const added = known ? newTerrains(known, terrains) : []; + if (added.length) { + this.terrainTablesQueue = this.terrainTablesQueue.then(async () => { + const folder = normalizeFolder(this.plugin.settings.tablesFolder); + if (folder && !this.plugin.app.vault.getAbstractFileByPath(folder)) return; + await this.createTerrainTableFiles(added); + }).catch((e) => logError("terrain tables", e)); + } + return this.terrainTablesQueue; + } + + /** Create each terrain's missing description / encounter table (empty). */ + private async createTerrainTableFiles(terrains: readonly TerrainColor[]): Promise { + if (!terrains.length) return; + const folder = normalizeFolder(this.plugin.settings.tablesFolder); + const subfolder = folder ? `${folder}/terrain` : "terrain"; + for (const dir of [subfolder, `${subfolder}/description`, `${subfolder}/encounters`]) { + await ensureFolder(this.plugin.app.vault, dir); + } + for (const entry of terrains) { + for (const tableType of ["description", "encounters"] as const) { + const path = this.terrainTablePath(entry.name, tableType); + if (this.plugin.app.vault.getAbstractFileByPath(path)) continue; + try { + await this.plugin.app.vault.create( + path, + makeTableTemplate( + this.plugin.settings.defaultTableDice, + // No `terrain:` key (T2): the table's path + // ({tables}/terrain/{type}/{terrain}.md) links it to its terrain. + { + "table-type": tableType, + "roll-filter": false, + "encounter-filter": false, + }, + this.buildRollerLink(), + ), + ); + } catch { + /* ignore */ + } + } + } + } + + /** + * For every hex note that has a terrain set, link its terrain's encounters table into + * the hex's "Encounters Table" section (if not already linked). + */ + async backfillTerrainLinks(): Promise { + const hexFolder = normalizeFolder(this.plugin.settings.hexFolder); + const tablesFolder = normalizeFolder(this.plugin.settings.tablesFolder); + const subfolder = tablesFolder ? `${tablesFolder}/terrain` : "terrain"; + + const hexFiles = this.plugin.app.vault.getMarkdownFiles().filter((f) => { + if (hexFolder && !f.path.startsWith(hexFolder + "/")) return false; + return /^(-?\d+)_(-?\d+)\.md$/.test(f.name); + }); + + let linked = 0; + for (const file of hexFiles) { + const terrain = getTerrainFromFile(this.plugin.app, file.path); + if (!terrain) continue; + const tablePath = `${subfolder}/encounters/${terrain}.md`; + const tableFile = this.plugin.app.vault.getAbstractFileByPath(tablePath); + if (!(tableFile instanceof TFile)) continue; + + const target = this.plugin.app.metadataCache.fileToLinktext( + tableFile, + file.path, + ); + const linkText = `[[${target}]]`; + const existing = await getLinksInSection( + this.plugin.app, + file.path, + "Encounters Table", + ); + if (existing.includes(target)) continue; + + await addLinkToSection(this.plugin.app, file.path, "Encounters Table", linkText); + linked++; + } + new Notice( + `Linked encounter tables for ${linked} hex${linked !== 1 ? "es" : ""}.`, + ); + } + + /** + * Replace the terrain encounters-table link in a single hex's "Encounters Table" section. + * Removes any existing link that resolves to a file in the terrain subfolder, then adds + * the correct link for the new terrain (if non-null and the table file exists). + */ + /** Whether `{tablesFolder}/terrain/encounters/{terrain}.md` exists. */ + hasTerrainEncounterTable(terrain: string): boolean { + return this.plugin.terrainEncounterTable(terrain) !== null; + } + + /** The terrain's encounters table file, if it has one. */ + terrainEncounterTable(terrain: string): TFile | null { + const tablesFolder = normalizeFolder(this.plugin.settings.tablesFolder); + const subfolder = tablesFolder ? `${tablesFolder}/terrain` : "terrain"; + const file = this.plugin.app.vault.getAbstractFileByPath(`${subfolder}/encounters/${terrain}.md`); + return file instanceof TFile ? file : null; + } + + /** + * Link text (relative to `sourcePath`) of the encounters table for the + * hex's own terrain in the map note, or null. createHexNote links exactly + * this, and views show it for hexes that have no note yet + * (see displayedEncounterLinks). + */ + terrainEncounterLinkFor(mapName: string, x: number, y: number, sourcePath: string): string | null { + const terrain = this.plugin.mapStore.get(mapName, hexKey(x, y))?.terrain; + const table = terrain ? this.plugin.terrainEncounterTable(terrain) : null; + return table ? this.plugin.app.metadataCache.fileToLinktext(table, sourcePath) : null; + } + + /** The encounters table of the area hex (x, y) is in (`{tables}/regions/.md`), if it has one. */ + areaEncounterTableFor(mapName: string, x: number, y: number): TFile | null { + const area = this.plugin.mapStore.get(mapName, hexKey(x, y))?.region; + if (!area) return null; + const folder = normalizeFolder(this.plugin.settings.tablesFolder); + const file = this.plugin.app.vault.getAbstractFileByPath(`${folder ? `${folder}/` : ""}regions/${area}.md`); + return file instanceof TFile ? file : null; + } + + async syncHexEncounterTableLink( + hexFilePath: string, + terrain: string | null, + ): Promise { + // The link lives in the hex note's body; a hex without a note gets it + // when its note is created (createHexNote adds it). + if (!(this.plugin.app.vault.getAbstractFileByPath(hexFilePath) instanceof TFile)) return; + const tablesFolder = normalizeFolder(this.plugin.settings.tablesFolder); + const subfolder = tablesFolder ? `${tablesFolder}/terrain` : "terrain"; + + // Remove any links that point to a terrain encounters table + const existing = await getLinksInSection( + this.plugin.app, + hexFilePath, + "Encounters Table", + ); + for (const linkTarget of existing) { + const resolved = this.plugin.app.metadataCache.getFirstLinkpathDest( + linkTarget, + hexFilePath, + ); + if (resolved && resolved.path.startsWith(subfolder + "/encounters/")) { + await removeLinkFromSection( + this.plugin.app, + hexFilePath, + "Encounters Table", + linkTarget, + ); + } + } + + if (!terrain) return; + + const tablePath = `${subfolder}/encounters/${terrain}.md`; + const tableFile = this.plugin.app.vault.getAbstractFileByPath(tablePath); + if (!(tableFile instanceof TFile)) return; + const linkText = `[[${this.plugin.app.metadataCache.fileToLinktext(tableFile, hexFilePath)}]]`; + await addLinkToSection(this.plugin.app, hexFilePath, "Encounters Table", linkText); + } + + /** + * For every hex note on the map, replace its terrain encounters-table link with the + * one matching its current terrain. Intended as a one-shot repair tool. + */ + async refreshAllTerrainEncounterLinks(): Promise { + const hexFolder = normalizeFolder(this.plugin.settings.hexFolder); + const hexFiles = this.plugin.app.vault.getMarkdownFiles().filter((f) => { + if (hexFolder && !f.path.startsWith(hexFolder + "/")) return false; + return /^(-?\d+)_(-?\d+)\.md$/.test(f.name); + }); + + for (const file of hexFiles) { + const terrain = getTerrainFromFile(this.plugin.app, file.path) ?? null; + await this.plugin.syncHexEncounterTableLink(file.path, terrain); + } + new Notice( + `Refreshed encounter links for ${hexFiles.length} hex${hexFiles.length !== 1 ? "es" : ""}.`, + ); + } + + // ── Region encounter tables ──────────────────────────────────────────────── + + /** Create a region encounters table file if it does not already exist. */ + async ensureRegionTable(regionName: string): Promise { + const folder = normalizeFolder(this.plugin.settings.tablesFolder); + const subfolder = folder ? `${folder}/regions` : "regions"; + + await ensureFolder(this.plugin.app.vault, subfolder); + + const path = `${subfolder}/${regionName}.md`; + if (!this.plugin.app.vault.getAbstractFileByPath(path)) { + try { + await this.plugin.app.vault.create( + path, + makeTableTemplate( + this.plugin.settings.defaultTableDice, + { + region: regionName, + "table-type": "encounters", + "roll-filter": false, + "encounter-filter": false, + }, + this.buildRollerLink(), + ), + ); + } catch { + /* ignore */ + } + } + } + + /** + * Add the region's encounters table link to a hex's "Encounters Table" section, + * or remove it when regionName is null (hex removed from region). + * Any existing link pointing into the regions subfolder is replaced. + */ + async syncHexRegionTableLink( + hexFilePath: string, + regionName: string | null, + ): Promise { + const tablesFolder = normalizeFolder(this.plugin.settings.tablesFolder); + const subfolder = tablesFolder ? `${tablesFolder}/regions` : "regions"; + + // Remove any existing region table link + const existing = await getLinksInSection( + this.plugin.app, + hexFilePath, + "Encounters Table", + ); + for (const linkTarget of existing) { + const resolved = this.plugin.app.metadataCache.getFirstLinkpathDest( + linkTarget, + hexFilePath, + ); + if (resolved && resolved.path.startsWith(subfolder + "/")) { + await removeLinkFromSection( + this.plugin.app, + hexFilePath, + "Encounters Table", + linkTarget, + ); + } + } + + if (!regionName) return; + + const tablePath = `${subfolder}/${regionName}.md`; + const tableFile = this.plugin.app.vault.getAbstractFileByPath(tablePath); + if (!(tableFile instanceof TFile)) return; + + const linkText = `[[${this.plugin.app.metadataCache.fileToLinktext(tableFile, hexFilePath)}]]`; + await addLinkToSection(this.plugin.app, hexFilePath, "Encounters Table", linkText); + } + + /** + * For every region note in the regions folder, ensure its encounters table exists. + * For every hex note that has a `region` frontmatter key, ensure the region table + * link is present in its "Encounters Table" section. + */ + async backfillRegionLinks(): Promise { + const regionsFolder = normalizeFolder(this.plugin.settings.regionsFolder); + const hexFolder = normalizeFolder(this.plugin.settings.hexFolder); + + // Ensure tables for all region notes (even unpainted ones) + if (regionsFolder) { + const regionFiles = this.plugin.app.vault + .getMarkdownFiles() + .filter( + (f) => + !f.basename.startsWith("_") && + f.path.startsWith(regionsFolder + "/"), + ); + for (const f of regionFiles) { + await this.plugin.ensureRegionTable(f.basename); + } + } + + // Sync hex → region table links + const hexFiles = this.plugin.app.vault.getMarkdownFiles().filter((f) => { + if (hexFolder && !f.path.startsWith(hexFolder + "/")) return false; + return /^(-?\d+)_(-?\d+)\.md$/.test(f.name); + }); + + let linked = 0; + for (const file of hexFiles) { + const region = getHexRegionFromFile(this.plugin.app, file.path); + if (!region) continue; + await this.plugin.syncHexRegionTableLink(file.path, region); + linked++; + } + + new Notice( + `Linked area encounter tables for ${linked} hex${linked !== 1 ? "es" : ""}.`, + ); + } + + /** Update every hex note whose terrain matches oldName to newName. + * Reads file content directly (not the metadata cache) so successive renames + * don't miss hexes whose cache entry hasn't refreshed yet. + * Returns a Map of filePath → newName for use as terrain overrides when re-rendering. */ + async renameTerrainInHexes( + oldName: string, + newName: string, + paletteName?: string, + ): Promise> { + // Terrain lives in map notes: rename it there (in memory now, notes + // follow). Hex notes no longer carry terrain. Only maps drawn with + // `paletteName` (when given): another palette's terrain of the same + // name is a different terrain. + const overrides = new Map(); + for (const m of paletteName === undefined ? this.plugin.settings.maps : this.plugin.mapsOnPalette(paletteName)) { + for (const [key, h] of this.plugin.mapStore.all(m.name)) { + if (h.terrain !== oldName) continue; + this.plugin.mapStore.set(m.name, key, { terrain: newName }); + const { x, y } = hexXY(key); + overrides.set(this.plugin.hexPath(x, y, m.name), newName); + } + if (m.baseTerrain === oldName) m.baseTerrain = newName; + } + await this.plugin.mapStore.flush(); + return overrides; + } + + /** Re-render all open hex map views, passing terrain overrides to bypass the stale metadata cache. */ + /** + * Rename a palette terrain everywhere: hex notes using it, its terrain + * table files, then the entry itself (saved). Used by the terrain entry + * editor and the palette editor page. + */ + async renameTerrain(entry: TerrainColor, newName: string): Promise { + const oldName = entry.name; + if (!newName || newName === oldName) return; + // The palette the entry is in (an entry in none, e.g. a stray copy, + // renames on every map as before). + const palette = this.plugin.settings.terrainPalettes.find((p) => p.terrains.includes(entry))?.name; + const overrides = await this.plugin.renameTerrainInHexes(oldName, newName, palette); + // Another palette still has a terrain of the old name: its tables stay + // and the renamed one gets a copy. + const shared = this.plugin.settings.terrainPalettes.some((p) => p.terrains.some((t) => t !== entry && t.name === oldName)); + await this.renameTerrainTables(oldName, newName, shared); + entry.name = newName; + await this.plugin.saveSettings(); + this.plugin.refreshHexMapWithOverrides(overrides); + this.plugin.refreshHexTableTerrainRename(oldName, newName); + } + + /** The terrain table files of a name that exist (description, encounters). */ + terrainTableFiles(name: string): TFile[] { + return (["description", "encounters"] as const) + .map((type) => this.plugin.app.vault.getAbstractFileByPath(this.terrainTablePath(name, type))) + .filter((f): f is TFile => f instanceof TFile); + } + + /** + * "Rename everywhere" for a terrain already renamed in its palette (by + * hand in the palette note): the hexes and base terrains of that + * palette's maps, and the terrain's tables, follow it. The map notes and + * tables it changes are backed up first; nothing changes when the backup + * can't be saved. Returns the backup path, or null when it failed. + */ + async renameTerrainEverywhere(paletteName: string, oldName: string, newName: string): Promise { + const maps = this.plugin.mapsOnPalette(paletteName); + const notes: Record = {}; + let where: string; + try { + for (const m of maps) { + const text = await this.plugin.mapStore.readNoteText(m.name); + if (text !== null) notes[this.plugin.mapStore.notePath(m.name)] = text; + } + for (const f of this.plugin.terrainTableFiles(oldName)) notes[f.path] = await this.plugin.app.vault.read(f); + const dir = `${this.plugin.manifest.dir}/backups/terrain-rename-${new Date().toISOString().slice(0, 10)}`; + const json = JSON.stringify({ kind: "terrain-rename", palette: paletteName, from: oldName, to: newName, savedAt: new Date().toISOString(), notes }); + where = await writeJsonBackup(this.plugin.app.vault.adapter, dir, "before-rename", json); + } catch (e) { + logError("couldn't back up before renaming a terrain; nothing was changed", e); + new Notice(`Couldn't save a backup, so "${oldName}" wasn't renamed. Nothing was changed.`, 10000); + return null; + } + const overrides = await this.plugin.renameTerrainInHexes(oldName, newName, paletteName); + // A palette that still has a terrain of the old name keeps its tables + // (the renamed one gets a copy); otherwise they move. + const shared = this.plugin.settings.terrainPalettes.some((p) => p.terrains.some((t) => t.name === oldName)); + await this.renameTerrainTables(oldName, newName, shared); + await this.plugin.saveSettings(); + this.plugin.refreshHexMapWithOverrides(overrides); + this.plugin.refreshHexTableTerrainRename(oldName, newName); + return where; + } + + private terrainTablePath(name: string, type: "description" | "encounters"): string { + const folder = normalizeFolder(this.plugin.settings.tablesFolder); + const sub = folder ? `${folder}/terrain` : "terrain"; + return `${sub}/${type}/${name}.md`; + } + + /** + * A renamed terrain's tables follow it (HG5): moved when no other terrain + * has the old name (links to them are updated), copied when one does. + * When there are none, the new name gets empty ones (via the save). + */ + private async renameTerrainTables(oldName: string, newName: string, keepOld = true): Promise { + // Tables still being made for the old name (a just-added terrain) first. + await this.terrainTablesQueue; + const failed: string[] = []; + for (const type of ["description", "encounters"] as const) { + const oldPath = this.terrainTablePath(oldName, type); + const newPath = this.terrainTablePath(newName, type); + // Don't overwrite if the new terrain already has its own tables + if (this.plugin.app.vault.getAbstractFileByPath(newPath)) continue; + const oldFile = this.plugin.app.vault.getAbstractFileByPath(oldPath); + if (!(oldFile instanceof TFile)) continue; + if (!keepOld) { + try { + await this.plugin.app.fileManager.renameFile(oldFile, newPath); + await this.plugin.app.vault.process(oldFile, (content) => + content + .replace(/^terrain:[ \t].+$/m, `terrain: ${newName}`) + .replace(/^.*obsidian:\/\/duckmage-roll.*$\n?/m, ""), + ); + await this.plugin.ensureRollerLink(newPath); + } catch (e) { + logError(`couldn't move ${oldPath} to ${newPath} for the terrain rename`, e); + failed.push(oldPath); + } + continue; + } + try { + let content = await this.plugin.app.vault.read(oldFile); + // Update the terrain frontmatter property to the new name + content = content.replace(/^terrain:[ \t].+$/m, `terrain: ${newName}`); + // Strip the old roller link so ensureRollerLink can add one with the correct path + content = content.replace(/^.*obsidian:\/\/duckmage-roll.*$\n?/m, ""); + await this.plugin.app.vault.create(newPath, content); + await this.plugin.ensureRollerLink(newPath); + } catch (e) { + logError(`couldn't copy ${oldPath} to ${newPath} for the terrain rename`, e); + failed.push(oldPath); + } + } + if (failed.length) new Notice(renameTablesFailedText(oldName, newName, failed), 10000); + } +} + +/** The notice when a renamed terrain's tables couldn't follow it. */ +export function renameTablesFailedText(oldName: string, newName: string, failed: readonly string[]): string { + return `Renamed "${oldName}" to "${newName}", but couldn't move or copy ${failed.length === 1 ? "its table" : "its tables"} ${failed.join(", ")}: ${failed.length === 1 ? "it's" : "they're"} still under the old name.`; +} diff --git a/src/settings/hexFieldsSetting.ts b/src/settings/hexFieldsSetting.ts new file mode 100644 index 00000000..88844d0e --- /dev/null +++ b/src/settings/hexFieldsSetting.ts @@ -0,0 +1,152 @@ +/** + * Settings → Hex fields (plan-custom-hex-fields phase 1; phase 2 moves + * this to the New world page): edit the world's field declarations and + * place influences. Every edit is written to the fields note + * (`/Hex fields.md`, FieldStore), which stays the only copy, + * so the same rows can be edited there by hand. + * + * The tab draws the same definitions on both settings paths + * (getSettingDefinitions and the display() fallback), so these rows show + * in both. Placement ids: Settings.hexFields, Settings.placeInfluences, + * Settings.hexFieldsNote. + */ +import type { Setting } from "obsidian"; +import type HexmakerPlugin from "../HexmakerPlugin"; +import type { ModuleSettingRow } from "./moduleSettings"; +import { FIELD_TYPES, parseFieldType, type FieldDecls, type FieldDef, type InfluenceDef } from "../fields/fieldTypes"; +import { parseChange } from "../fields/influence"; +import { compileFormula } from "../fields/formula"; +import { linkTarget } from "../fields/fieldsNote"; + +export const HEX_FIELDS_SECTION = "Hex fields"; + +const FIELDS_DESC = + "Your own data on every hex (population, land value…). Each field is a column in every map note's Hexes table. A field rolls its table when a hex gets terrain (the table's When column can say near: town 2), or is worked out from a formula over the hex's other fields. Renaming a field doesn't rename the column in map notes that already have it."; +const INFLUENCES_DESC = + "What each kind of place does to a field: on its own hex (Here) and on the hexes within Radius (Nearby, fading with distance). +400 adds, +40% or x1.4 multiplies, =yes sets. Towns and cities are hexes whose terrain is named like a place type, or a note linked under a hex's Towns (its place-type property, else town). Run Recalculate fields after adding places."; +const NOTE_DESC = "The fields and influences live in one note in the world folder. Edit it by hand if you like; these rows follow it."; + +/** The settings rows of Hex fields, added as their own section. */ +export function addHexFieldSettings( + sections: { heading?: string; items: { id: string; item: T }[] }[], + row: (r: ModuleSettingRow) => T, + plugin: HexmakerPlugin, +): void { + sections.push({ + heading: HEX_FIELDS_SECTION, + items: [ + { id: "Settings.hexFields", item: row({ name: "Fields", desc: FIELDS_DESC, aliases: ["hex fields", "custom fields", "population", "columns"], render: (s) => renderFields(s, plugin) }) }, + { id: "Settings.placeInfluences", item: row({ name: "Place influences", desc: INFLUENCES_DESC, aliases: ["towns", "cities", "settlements", "influence"], render: (s) => renderInfluences(s, plugin) }) }, + { id: "Settings.hexFieldsNote", item: row({ name: "Open the fields note", desc: NOTE_DESC, render: (s) => renderOpenNote(s, plugin) }) }, + ], + }); +} + +/** The list area under a row's name, redrawn whenever the fields note changes. */ +function listArea(setting: Setting, plugin: HexmakerPlugin, cls: string, draw: (el: HTMLElement) => void): void { + setting.settingEl.addClass("duckmage-settings-fields-row"); + const el = setting.settingEl.createDiv({ cls: `duckmage-settings-fields ${cls}` }); + draw(el); + const off = plugin.fields.store.onChange(() => { + if (!el.isConnected) { off(); return; } + draw(el); + }); +} + +const save = (plugin: HexmakerPlugin, decls: FieldDecls) => void plugin.fields.store.save(decls); + +function textBox(parent: HTMLElement, value: string, placeholder: string, label: string, commit: (v: string, box: HTMLInputElement) => void): HTMLInputElement { + const box = parent.createEl("input", { type: "text", cls: "duckmage-settings-fields-input", attr: { placeholder, "aria-label": label } }); + box.value = value; + box.addEventListener("change", () => commit(box.value.trim(), box)); + return box; +} + +function renderFields(setting: Setting, plugin: HexmakerPlugin): void { + listArea(setting, plugin, "duckmage-settings-fields-list", (el) => { + el.empty(); + const decls = plugin.fields.store.get(); + const put = (i: number, patch: Partial) => { + const fields = decls.fields.map((f, j) => (j === i ? { ...f, ...patch } : f)); + save(plugin, { ...decls, fields }); + }; + decls.fields.forEach((f, i) => { + const r = el.createDiv({ cls: "duckmage-settings-fields-item" }); + textBox(r, f.name, "Name", "Field name", (v, box) => { + if (!v || decls.fields.some((o, j) => j !== i && o.name.toLowerCase() === v.toLowerCase())) { box.addClass("is-invalid"); return; } + put(i, { name: v }); + }); + const type = r.createEl("select", { cls: "dropdown duckmage-settings-fields-input", attr: { "aria-label": `${f.name} type` } }); + for (const t of FIELD_TYPES) type.createEl("option", { text: t, value: t }); + type.value = f.type; + type.addEventListener("change", () => put(i, { type: parseFieldType(type.value) ?? "text" })); + textBox(r, f.default, "Default", `${f.name} default`, (v) => put(i, { default: v })); + textBox(r, f.table ?? "", "Table (path)", `${f.name} table`, (v) => put(i, { table: linkTarget(v) || undefined })); + textBox(r, f.formula ?? "", "Formula", `${f.name} formula`, (v, box) => { + if (v && compileFormula(v, decls.fields.map((o) => o.name)).error) { box.addClass("is-invalid"); return; } + put(i, { formula: v || undefined }); + }); + if (f.type === "choice") textBox(r, (f.choices ?? []).join(", "), "Choices, comma separated", `${f.name} choices`, (v) => put(i, { choices: v.split(/\s*,\s*/).filter(Boolean) })); + r.createEl("button", { text: "Remove", cls: "duckmage-settings-fields-remove" }).addEventListener("click", () => { + save(plugin, { ...decls, fields: decls.fields.filter((_, j) => j !== i) }); + }); + }); + for (const p of plugin.fields.store.problems()) el.createDiv({ cls: "duckmage-settings-fields-problem", text: `${p.where}: ${p.text} — ${p.reason}` }); + el.createEl("button", { text: "Add field", cls: "duckmage-settings-fields-add" }).addEventListener("click", () => { + let n = decls.fields.length + 1; + while (decls.fields.some((f) => f.name.toLowerCase() === `field ${n}`)) n++; + save(plugin, { ...decls, fields: [...decls.fields, { name: `Field ${n}`, type: "whole number", default: "" }] }); + }); + }); +} + +function renderInfluences(setting: Setting, plugin: HexmakerPlugin): void { + listArea(setting, plugin, "duckmage-settings-influences-list", (el) => { + el.empty(); + const decls = plugin.fields.store.get(); + if (!decls.fields.length) { + el.createDiv({ cls: "duckmage-settings-fields-empty", text: "Add a field first." }); + return; + } + const put = (i: number, patch: Partial) => { + const influences = decls.influences.map((inf, j) => (j === i ? { ...inf, ...patch } : inf)); + save(plugin, { ...decls, influences }); + }; + const change = (v: string, box: HTMLInputElement) => { + if (parseChange(v) === undefined) { box.addClass("is-invalid"); return false; } + return true; + }; + decls.influences.forEach((inf, i) => { + const r = el.createDiv({ cls: "duckmage-settings-fields-item" }); + textBox(r, inf.place, "Place type", "Place type", (v, box) => (v ? put(i, { place: v }) : box.addClass("is-invalid"))); + const field = r.createEl("select", { cls: "dropdown duckmage-settings-fields-input", attr: { "aria-label": `${inf.place} field` } }); + for (const f of decls.fields) field.createEl("option", { text: f.name, value: f.name }); + field.value = decls.fields.find((f) => f.name.toLowerCase() === inf.field.toLowerCase())?.name ?? inf.field; + field.addEventListener("change", () => put(i, { field: field.value })); + textBox(r, inf.here, "Here (+400)", `${inf.place} here`, (v, box) => change(v, box) && put(i, { here: v })); + textBox(r, inf.nearby, "Nearby (+40%)", `${inf.place} nearby`, (v, box) => change(v, box) && put(i, { nearby: v })); + const radius = r.createEl("input", { type: "number", cls: "duckmage-settings-fields-input duckmage-settings-fields-radius", attr: { min: "0", step: "1", "aria-label": `${inf.place} radius` } }); + radius.value = String(inf.radius); + radius.addEventListener("change", () => put(i, { radius: Math.max(0, Math.round(Number(radius.value) || 0)) })); + r.createEl("button", { text: "Remove", cls: "duckmage-settings-fields-remove" }).addEventListener("click", () => { + save(plugin, { ...decls, influences: decls.influences.filter((_, j) => j !== i) }); + }); + }); + el.createEl("button", { text: "Add influence", cls: "duckmage-settings-fields-add" }).addEventListener("click", () => { + save(plugin, { ...decls, influences: [...decls.influences, { place: "Town", field: decls.fields[0].name, here: "", nearby: "", radius: 1 }] }); + }); + }); +} + +function renderOpenNote(setting: Setting, plugin: HexmakerPlugin): void { + setting.addButton((b) => + b.setButtonText("Open note").onClick(() => { + const open = async () => { + if (!plugin.fields.store.noteFile()) await plugin.fields.store.save(plugin.fields.store.get()); + const file = plugin.fields.store.noteFile(); + if (file) await plugin.app.workspace.getLeaf("tab").openFile(file); + }; + void open(); + }), + ); +} diff --git a/src/settings/hexPropsSetting.ts b/src/settings/hexPropsSetting.ts new file mode 100644 index 00000000..d52ca5ac --- /dev/null +++ b/src/settings/hexPropsSetting.ts @@ -0,0 +1,103 @@ +/** + * The "Map data as hex note properties" setting (Advanced; owner MG4) and + * what switching it does (owner HP3, 2026-10-16: "just stop updating + * them"; turning back on must not risk the notes). + * + * On (the default): hex notes carry their hex's terrain, area, icon and + * name as properties, kept up to date both ways (src/maps/hexPropsSync.ts). + * Off: the plugin stops writing and reading them. Nothing is removed; the + * notes keep what they show. Back on: the notes are brought in line with + * the map notes (the source), rewriting only the ones that differ, backed + * up first, every other key and the body untouched (resyncKeep). + */ +import { Notice, type Setting } from "obsidian"; +import type HexmakerPlugin from "../HexmakerPlugin"; +import { needsWrite, propsOf, readProps, resyncKeep, setPropsInText, type HexProps } from "../maps/hexProps"; +import { notePropsOfText } from "../maps/hexPropsSync"; +import { hexNotes, runRewrite, type NoteFormatHost, type NoteRewrite } from "../migrations/noteRewrites"; + +export const HEX_PROPS_SETTING_NAME = "Map data as hex note properties"; + +export const HEX_PROPS_SETTING_DESC = + "Hex notes show their hex's terrain, area, icon and name as properties, for Dataview, Bases and search. They're copies: the map note holds the data, and editing one of them changes the map. Off: the plugin stops updating them and leaves them in your notes as they are. Turning it back on updates only the notes that differ from the map (a backup is kept first)."; + +function propsAt(host: NoteFormatHost, map: string, key: string): HexProps { + return propsOf(host.mapStore.get?.(map, key)); +} + +/** A note's text brought in line with the map (its own values the map lacks kept, resyncKeep). */ +function resynced(host: NoteFormatHost, path: string, text: string, want: HexProps): string { + return setPropsInText(text, want, resyncKeep(notePropsOfText(text), want, host.hexProps?.shown?.(path))); +} + +/** Back on: the hex notes that differ from the map brought in line (not a migration; run by the setting). */ +export const resyncHexNoteProperties: NoteRewrite = { + info: { + id: "hex-note-properties-on", + from: "1.6", + to: "1.6", + phase: "notes", + change: "Hex note properties were turned back on and updated from the map notes where they differed.", + recordedBy: "the setting", + }, + recordId: "hex-properties-on", + label: "terrain, area, icon and name properties updated from the map", + async plan(host, add, skip) { + if (!host.mapStore.get) return; + for (const { file, map } of hexNotes(host)) { + if (!host.mapStore.isReady(map)) { skip(file.path, `its map (${map}) isn't loaded; it's updated when it is`); continue; } + const want = propsAt(host, map, file.basename); + const cache = host.app.metadataCache.getFileCache(file); + if (cache && !needsWrite(readProps(cache.frontmatter), want)) continue; + const text = await host.app.vault.cachedRead(file); + const after = resynced(host, file.path, text, want); + // Only values of its own differ: nothing to write; they go onto the map when the sync starts. + if (after === text) host.hexProps?.remember(file.path, want); + else add(file.path, text, after); + } + }, + replan(host, path, current) { + const loc = host.mapStore.resolve(path); + if (!loc || !host.mapStore.isReady(loc.map)) return current; + return resynced(host, path, current, propsAt(host, loc.map, loc.key)); + }, + written(host, path) { + const loc = host.mapStore.resolve(path); + if (loc) host.hexProps?.remember(path, propsAt(host, loc.map, loc.key)); + }, +}; + +/** + * Switch the properties on or off. Off: the sync stops; no note is + * touched. On: the notes that differ from the map are rewritten (backed + * up), then the sync starts again. + */ +export async function setHexNoteProperties(plugin: HexmakerPlugin, on: boolean): Promise { + if (on === plugin.hexProps.enabled) return; + if (on) delete plugin.settings.hexNoteProperties; + else plugin.settings.hexNoteProperties = false; + await plugin.saveSettings(); + plugin.hexProps.stop(); + if (!on) { + new Notice("Hex note properties are no longer updated. Your notes keep the ones they have.", 8000); + return; + } + await plugin.hexProps.memory.ready(); + const r = await runRewrite(plugin, resyncHexNoteProperties); + await plugin.hexProps.start(); + const n = r.changed.length; + if (r.error) new Notice(`Hex note properties: ${r.error}`, 10000); + else if (n) new Notice(`Hex note properties updated from the map in ${n} hex note${n === 1 ? "" : "s"}. Backup: ${r.backup}`, 8000); +} + +/** The settings row (the toggle). */ +export function hexPropsSettingItem(plugin: HexmakerPlugin): { name: string; desc: string; aliases: string[]; render: (setting: Setting) => void } { + return { + name: HEX_PROPS_SETTING_NAME, + desc: HEX_PROPS_SETTING_DESC, + aliases: ["dataview", "bases", "properties", "frontmatter", "terrain property", "area property"], + render: (setting) => { + setting.addToggle((t) => t.setValue(plugin.hexProps.enabled).onChange((v) => void setHexNoteProperties(plugin, v))); + }, + }; +} diff --git a/src/settings/moduleSettings.ts b/src/settings/moduleSettings.ts new file mode 100644 index 00000000..858b180a --- /dev/null +++ b/src/settings/moduleSettings.ts @@ -0,0 +1,69 @@ +/** + * The modules' settings in the settings tab (SettingContribution, + * src/modules/types.ts): one row each, in the section its module names + * ("Setup" when it names none), placed by its placement id like the core's + * rows. The tab draws the same definitions in both settings paths + * (getSettingDefinitions and the display() fallback), so a module's row + * shows in both. + */ +import type { Setting } from "obsidian"; +import type HexmakerPlugin from "../HexmakerPlugin"; +import { moduleSettings } from "../modules/runtime"; +import type { SettingContribution } from "../modules/types"; + +/** The section a module's setting joins when it names none. */ +export const MODULE_SETTINGS_SECTION = "Setup"; + +/** A settings row (the shape of the tab's setting definitions). */ +export interface ModuleSettingRow { + name: string; + desc: string; + aliases?: string[]; + control?: { type: "text"; key: string; placeholder: string } | { type: "toggle"; key: string; defaultValue: boolean }; + render?: (setting: Setting) => void; +} + +/** One module setting as a settings row. */ +export function moduleSettingRow(c: SettingContribution, plugin: HexmakerPlugin): ModuleSettingRow { + const base = { name: c.name, desc: c.desc, ...(c.aliases ? { aliases: [...c.aliases] } : {}) }; + const control = c.control; + if (control.type === "folder") return { ...base, control: { type: "text", key: control.key, placeholder: control.placeholder } }; + if (control.type === "toggle") return { ...base, control: { type: "toggle", key: control.key, defaultValue: control.defaultValue } }; + return { ...base, render: (setting) => control.render(setting, plugin) }; +} + +/** + * Add every module's settings to the tab's sections: each at the end of the + * section with its heading (default Setup); a heading the tab doesn't have + * gets a section of its own, after the others. + */ +export function addModuleSettings( + sections: { heading?: string; items: { id: string; item: T }[] }[], + row: (c: SettingContribution) => T, +): void { + for (const c of moduleSettings()) { + const heading = c.section ?? MODULE_SETTINGS_SECTION; + let section = sections.find((s) => s.heading === heading); + if (!section) sections.push((section = { heading, items: [] })); + section.items.push({ id: c.id, item: row(c) }); + } +} + +/** Is `key` a module's folder setting (normalised like the core's folder paths)? */ +export function isModuleFolderKey(key: string): boolean { + return moduleSettings().some((c) => c.control.type === "folder" && c.control.key === key); +} + +/** After a module setting's value was saved: its module's follow-up (re-read its notes). */ +export function moduleSettingChanged(plugin: HexmakerPlugin, key: string): void { + for (const c of moduleSettings()) if (c.control.type !== "custom" && c.control.key === key) c.changed?.(plugin); +} + +/** + * The modules' folder settings the setup wizard asks for with the core's + * folders (SettingContribution.wizard), in module order: key, label, and + * the subfolder of the world folder each starts as. + */ +export function moduleWizardFolders(): { key: string; label: string; suffix: string }[] { + return moduleSettings().flatMap((c) => (c.control.type === "folder" && c.wizard ? [{ key: c.control.key, ...c.wizard }] : [])); +} diff --git a/src/setupPlaceholder.ts b/src/setupPlaceholder.ts new file mode 100644 index 00000000..2993bb9a --- /dev/null +++ b/src/setupPlaceholder.ts @@ -0,0 +1,61 @@ +/** + * The "default" map: DEFAULT_SETTINGS ships one so a fresh install has a + * map to open, and the map-note store writes its note + * (`{hexFolder}/default/_default.md`) at startup. Once the setup wizard + * has made the user's own first map, an untouched "default" is just a + * mystery entry in the map list, so the wizard removes it. + */ + +import type { PathChain } from "./types"; +import { storedMapPaths } from "./paths/mapPaths"; + +export const PLACEHOLDER_MAP_NAME = "default"; + +/** + * Is this the shipped placeholder, never used? True only when it has no + * hex data, paths, parent / world slot or background, no other map + * points at it, and its folder holds nothing but its own map note. + */ +export function isUnusedPlaceholderMap( + map: { + name: string; + pathChains?: PathChain[]; + parent?: unknown; + world?: unknown; + backgroundImage?: unknown; + }, + usage: { + /** Hexes with data in the map store. */ + hexCount: number; + /** File / folder names directly inside the map's folder. */ + folderEntries: string[]; + /** Another map has it as parent, neighbour or submap. */ + referenced: boolean; + }, +): boolean { + if (map.name !== PLACEHOLDER_MAP_NAME) return false; + if (usage.hexCount > 0 || usage.referenced) return false; + if (storedMapPaths(map).length > 0 || map.parent || map.world || map.backgroundImage) return false; + return usage.folderEntries.every((n) => n === `_${PLACEHOLDER_MAP_NAME}.md`); +} + +/** + * When the stores may start (and so write their first notes). A fresh + * install that is about to show the setup wizard, with no world folder on + * disk yet, waits until `release()`: the wizard's folder step (once the + * user confirms the folder), the wizard closing for any reason, or a map + * view opening. Before this, the palette notes and the placeholder map's + * note appeared in `world/` while the wizard was still asking where the + * world should live (fresh-eyes F19). Anything else starts at once. + */ +export function startupWritesWait( + settings: { setupComplete?: boolean; setupDismissed?: boolean; worldFolder?: string }, + exists: (path: string) => boolean, +): { wait: Promise; release: () => void; held: boolean } { + const world = (settings.worldFolder ?? "").trim().replace(/^\/+|\/+$/g, "") || "world"; + const fresh = !settings.setupComplete && !settings.setupDismissed && !exists(world); + if (!fresh) return { wait: Promise.resolve(), release: () => {}, held: false }; + let release = () => {}; + const wait = new Promise((resolve) => { release = resolve; }); + return { wait, release: () => release(), held: true }; +} diff --git a/src/sizeInput.ts b/src/sizeInput.ts new file mode 100644 index 00000000..c8c1be68 --- /dev/null +++ b/src/sizeInput.ts @@ -0,0 +1,87 @@ +/** + * A grid-size number field read while the user types (live preview) and + * when it is committed (blur / Enter). + * + * While typing, a half-typed value ("1" on the way to "12", or an empty + * field) is not a size yet: return undefined so the preview keeps the last + * good size instead of flashing a 2-column map. On commit, clamp into + * range and fall back when the field is empty or not a number. + */ +export function sizeFromInput( + raw: string, + opts: { min: number; max: number; fallback: number; committed: boolean }, +): number | undefined { + const n = Math.floor(Number(raw)); + const valid = raw.trim() !== "" && Number.isFinite(n); + if (!opts.committed) return valid && n >= opts.min && n <= opts.max ? n : undefined; + if (!valid || n === 0) return opts.fallback; + return Math.max(opts.min, Math.min(opts.max, n)); +} + +/** + * Most columns (or rows) a map size field takes. A map note asking for + * more is read as this many and its note shows the problem: a note from + * someone else with `cols: 100000000` would otherwise freeze the app on + * open (every hex is drawn and counted). + */ +export const MAX_GRID_SIDE = 200; + +/** A map side read from a note, at most MAX_GRID_SIDE; `tooBig` gets the reason when it is cut. */ +export function gridSideFromNote(n: number, tooBig: (reason: string) => void): number { + if (n <= MAX_GRID_SIDE) return n; + tooBig(`should be ${MAX_GRID_SIDE} or less; the map shows ${MAX_GRID_SIDE}`); + return MAX_GRID_SIDE; +} + +/** How long typing in a size field waits before the preview redraws. */ +export const LIVE_PREVIEW_DELAY_MS = 300; + +/** + * One mouse-wheel step on a size field: up adds one, down takes one, + * clamped into range. A field that isn't a number starts from `min`. + */ +export function wheelSize(raw: string, deltaY: number, min: number, max: number): number { + const n = Math.floor(Number(raw)); + const base = raw.trim() !== "" && Number.isFinite(n) ? n : min; + if (!deltaY) return Math.max(min, Math.min(max, base)); + return Math.max(min, Math.min(max, base + (deltaY < 0 ? 1 : -1))); +} + +/** What a size field needs for wheelStep (an HTMLInputElement, or a stand-in in tests). */ +export interface WheelField { + value: string; + matches(selector: string): boolean; + addEventListener(type: "wheel", fn: (e: { deltaY: number; preventDefault(): void }) => void, opts: { passive: boolean }): void; + dispatchEvent(e: Event): boolean; +} + +/** + * Let the mouse wheel step a size field while it's hovered or focused + * (owner: "grid size on onboarding should be scroll adjustable"). Anywhere + * else the wheel scrolls the page as usual. Each step commits like typing + * a value and leaving the field (a `change` event). + */ +export function wheelStep(input: WheelField, min: number, max: number, isFocused: () => boolean): void { + input.addEventListener("wheel", (e) => { + if (!isFocused() && !input.matches(":hover")) return; + if (!e.deltaY) return; + e.preventDefault(); + const next = String(wheelSize(input.value, e.deltaY, min, max)); + if (next === input.value) return; + input.value = next; + input.dispatchEvent(new Event("change")); + }, { passive: false }); +} + +/** + * The size after another map scale is picked (Overland ↔ Biomes): the + * scale's own size, unless the user chose one (typed it, a preset): that + * is kept (critic C9: switching scale threw a typed 40 columns away). The + * size's reset button still goes back to the scale's size. + */ +export function sizeForScalePick( + chosen: { cols: number; rows: number } | null, + scaleSize: { cols: number; rows: number }, +): { cols: number; rows: number } { + return chosen ? { cols: chosen.cols, rows: chosen.rows } : { cols: scaleSize.cols, rows: scaleSize.rows }; +} diff --git a/src/slices.d.ts b/src/slices.d.ts new file mode 100644 index 00000000..515504d0 --- /dev/null +++ b/src/slices.d.ts @@ -0,0 +1,15 @@ +/** + * Release slice flags (release-slices.json), set at build time by + * esbuild's `define` (esbuild.config.mjs) and in tests by + * tests/register.mjs. A slice built off is dropped from main.js: only + * src/modules/index.ts and src/modules/runtime.ts read these. + */ +declare const __SLICE_WORLDMAPS__: boolean; +declare const __SLICE_SPACE__: boolean; +declare const __SLICE_PLAY__: boolean; +declare const __SLICE_HEXFLOWER__: boolean; +declare const __SLICE_GENPAGE__: boolean; +declare const __SLICE_PACKS__: boolean; +declare const __SLICE_MANUAL__: boolean; +/** The slices built on, as JSON text ('["worldmaps","space"]'); see src/modules/index.ts builtSlices(). */ +declare const __HEXMAKER_SLICES__: string; diff --git a/src/space/WorldTypeStore.ts b/src/space/WorldTypeStore.ts new file mode 100644 index 00000000..0952e0f5 --- /dev/null +++ b/src/space/WorldTypeStore.ts @@ -0,0 +1,422 @@ +/** + * World types tables in the vault: `/.md`, one + * note per table (worldTypes.ts has the format). The notes are the only + * copy; data.json only remembers that the shipped "Default space" table + * was written (`worldTypesSeeded`), so a deleted one isn't written again + * (Restore default brings it back). + * + * - init(): reads every note, then writes the shipped table once when + * space maps are on (ensureDefault() does it on demand otherwise). + * - Hand edits are read back live (vault events); rows that can't be read + * are reported once per edit, never used, and kept as written. + * - A note from before stars and sector features were rows (format 1) + * is given the shipped Stars and Sector features tables once, when read; + * one from before the Mainworld column (format 1 or 2) the shipped + * rows' mainworlds (backed up first). + * - sourceFor(): a table as the space generators' role tables (SP1). A + * converted note (its `## Tables` list, space/spaceTables.ts) gives the + * table notes it links; a map's own Tables (inherited down the map tree) + * win over both (worldgen/tableSources.ts). + * - convertAll(): the one-time Convert to tables (backed up first; the + * notes are kept and link out to the new tables). Never runs by itself. + * - Every change is told to onChange listeners. + */ + +import { logError } from "../log"; +import { Notice, TAbstractFile, TFile } from "obsidian"; +import { normalizeFolder } from "../utils"; +import { NoteFolderStore } from "../stores/NoteFolderStore"; +import { enabledKinds } from "../mapKinds"; +import { biomeFileName } from "../overworld/biomeNote"; +import { + DEFAULT_WORLD_TYPES, + buildWorldTypes, + copyFeatureRows, + copyStarRows, + copyWorldTypeRows, + featureCells, + parseWorldTypes, + sameOptional, + starCells, + worldTypeCells, + updateWorldTypes, + upgradeWorldTypes, + type SectorFeatureRow, + type StarTypeRow, + type WorldTypeExtras, + type WorldTypeLinks, + type WorldTypeProblem, + type WorldTypeRow, + type WorldTypeTable, +} from "./worldTypes"; +import { DEFAULT_WORLD_TYPE_EXTRAS, DEFAULT_WORLD_TYPE_ROWS } from "./worldTypePresets"; +import { chosenWorldTypes, defaultWorldTypesName, worldTypesSource } from "./worldTypesSource"; +import type { TableSource } from "../worldgen/tableRoles"; + +/** The World types store's id among the modules' stores. */ +export const WORLD_TYPES_STORE = "world-types"; +import { layeredSource, notesTableSource, withShippedRoleTables } from "../worldgen/tableSources"; +import { convertWorldTypes, isConverted, markConverted, readRoleTables } from "./spaceTables"; +import { contentFolder } from "../notePickers"; +import { PALETTE_PRESETS } from "../palettes/presets"; + +interface Entry { + path: string; + name: string; + rows: WorldTypeRow[]; + /** Undefined: the note has no Stars table. */ + stars?: StarTypeRow[]; + /** Undefined: the note has no Sector features table. */ + features?: SectorFeatureRow[]; + problems: WorldTypeProblem[]; +} + +/** An entry as a table (copies, so callers may change it). */ +function tableOf(e: Entry): WorldTypeTable { + const t: WorldTypeTable = { name: e.name, rows: copyWorldTypeRows(e.rows) }; + if (e.stars) t.stars = copyStarRows(e.stars); + if (e.features) t.features = copyFeatureRows(e.features); + return t; +} + +/** Settings the store reads (a subset of the plugin's). */ +interface StoreSettings { + worldFolder?: string; + worldTypesFolder?: string; + worldTypesSeeded?: boolean; + mapKinds?: string[]; +} + +/** The folder for world types notes: the setting, else `/world-types`. */ +export function worldTypesFolder(settings: StoreSettings): string { + const configured = normalizeFolder(settings.worldTypesFolder ?? ""); + if (configured) return configured; + const world = normalizeFolder(settings.worldFolder ?? ""); + return world ? `${world}/world-types` : "world-types"; +} + +export class WorldTypeStore extends NoteFolderStore { + /** Its id among the modules' stores (HexmakerPlugin.moduleStore). */ + readonly id = WORLD_TYPES_STORE; + protected readonly logLabel = "world types"; + protected readonly backupFolder = "world-types"; + protected readonly backupLabel = "world types"; + + private get settings(): StoreSettings { + return this.plugin.settings; + } + + /** Where the palettes the tables name have notes (the Palette column is written as links to them). */ + links(): WorldTypeLinks { + return { + paletteNote: (name) => { + const path = (this.plugin as { paletteStore?: { notePathOf(n: string): string | undefined } }).paletteStore?.notePathOf(name); + return path && this.plugin.app.vault.getAbstractFileByPath(path) instanceof TFile ? path : undefined; + }, + }; + } + + folder(): string { + return worldTypesFolder(this.settings); + } + + async init(): Promise { + await this.enqueue(async () => { + for (const f of this.files()) await this.load(f); + if (enabledKinds(this.settings).has("space")) await this.seed(); + this.ready = true; + this.publish(); + }); + } + + /** Write the shipped table if it never was (once). */ + async ensureDefault(): Promise { + await this.enqueue(() => this.seed()); + } + + // ── API ──────────────────────────────────────────────────────────────── + + /** Every table, by name. */ + list(): WorldTypeTable[] { + return this.sorted().map(tableOf); + } + + /** A table by name (any case) or note path. */ + get(name: string): WorldTypeTable | undefined { + const e = this.find(name); + return e ? tableOf(e) : undefined; + } + + pathOf(name: string): string | undefined { + return this.find(name)?.path; + } + + /** What couldn't be read in a table's note. */ + problemsOf(name: string): WorldTypeProblem[] { + return this.find(name)?.problems ?? []; + } + + /** What the generators' "Default" World types means now (Default space, else the first table). */ + defaultName(): string | undefined { + return defaultWorldTypesName(this.list().map((t) => t.name), DEFAULT_WORLD_TYPES); + } + + /** + * The space generators' role tables from the World types option's value + * (SP1), for a palette. `source` undefined: no table (None, or none at + * all), so equal odds; `missing`: the picked table isn't there. + */ + sourceFor(value: string | undefined, palette: readonly (string | { name: string })[], mapName?: string): { source?: TableSource; missing?: string } { + const name = chosenWorldTypes(value, this.list().map((t) => t.name), this.defaultName()); + const terrains = palette.map((t) => (typeof t === "string" ? t : t.name)); + const notes = this.plugin.tableNotes.lookup(); + let base: TableSource | undefined; + let missing: string | undefined; + if (name) { + const e = this.find(name); + if (!e) missing = name; + else { + const roles = readRoleTables(this.lastContent.get(e.path) ?? ""); + base = Object.keys(roles).length ? notesTableSource(roles, notes, terrains, `Tables: ${e.name}`) : worldTypesSource(tableOf(e), palette); + } + } + // The map's own Tables (and its ancestors') win over the setup's. + const own = mapName ? this.plugin.roleTablesFor(mapName) : {}; + const overrides = Object.fromEntries(Object.entries(own).flatMap(([r, p]) => (p ? [[r, p.link]] : []))); + // Roles nothing names roll on their shipped table's installed copy, when there is one (T12). + const source = withShippedRoleTables(layeredSource(base, overrides, notes, terrains), notes, terrains, contentFolder(this.plugin.settings, "tablesFolder")); + return { ...(source ? { source } : {}), ...(missing ? { missing } : {}) }; + } + + /** Whether a table's note was converted to tables (it has a `## Tables` list). */ + isConverted(name: string): boolean { + const e = this.find(name); + return !!e && isConverted(this.lastContent.get(e.path) ?? ""); + } + + /** + * Convert every World types note not yet converted into table notes + * under `{tables}/space//` (T1, T2). The notes are backed up + * first and kept; each gets a `## Tables` list linking its tables. A + * table note that already exists is never overwritten (it's listed in + * `kept`). Running it again changes nothing. + */ + async convertAll(): Promise<{ converted: string[]; written: string[]; kept: string[] }> { + const out = { converted: [] as string[], written: [] as string[], kept: [] as string[] }; + await this.queue; // hand edits read first + await this.enqueue(async () => { + const todo = this.sorted().filter((e) => !isConverted(this.lastContent.get(e.path) ?? "")); + if (!todo.length) return; + const vault = this.plugin.app.vault; + const notes: Record = {}; + for (const e of todo) { + const f = vault.getAbstractFileByPath(e.path); + if (f instanceof TFile) notes[e.path] = await vault.read(f); + } + await this.backup("convert", notes); + const tablesFolder = contentFolder(this.plugin.settings, "tablesFolder"); + const shownAs = this.starSystemTerrain(); + for (const e of todo) { + const f = vault.getAbstractFileByPath(e.path); + const content = notes[e.path]; + if (!(f instanceof TFile) || content === undefined) continue; + const set = convertWorldTypes(tableOf(e), { tablesFolder, shownAs, unreadable: parseWorldTypes(content).unreadable }); + for (const file of set.files) { + if (vault.getAbstractFileByPath(file.path)) { out.kept.push(file.path); continue; } + await this.ensureFolder(file.path.slice(0, file.path.lastIndexOf("/"))); + await vault.create(file.path, file.content); + this.plugin.tableNotes.put(file.path, file.content); + out.written.push(file.path); + } + const next = markConverted(content, set); + if (next !== content) await vault.modify(f, next); + this.take(f.path, next); + out.converted.push(e.name); + } + this.publish(); + }); + return out; + } + + /** A terrain of type star-system (what a somewhat known hex shows), found by type: installed palettes first, then the shipped ones. */ + private starSystemTerrain(): string | undefined { + const pals = [...this.plugin.settings.terrainPalettes, ...PALETTE_PRESETS]; + for (const p of pals) { + const t = p.terrains.find((x) => x.type === "star-system"); + if (t) return t.name; + } + return undefined; + } + + hasDefault(name: string): boolean { + return name.trim().toLowerCase() === DEFAULT_WORLD_TYPES.toLowerCase(); + } + + /** + * Set a table's rows, and its Stars / Sector features rows when given + * (rows the note has that can't be read are kept as written). + * + * `base`: the table as the caller last saw it. A table (Worlds, Stars, + * Sector features) the note no longer has as in `base` was hand-edited + * meanwhile, so it is left as the note has it (the caller hears of it + * through onChange). + */ + async update(name: string, rows: readonly WorldTypeRow[], extras: WorldTypeExtras = {}, base?: WorldTypeTable): Promise { + await this.queue; // hand edits read first + const e = this.find(name); + if (!e) return false; + const f = this.plugin.app.vault.getAbstractFileByPath(e.path); + if (!(f instanceof TFile)) return false; + await this.enqueue(async () => { + const content = await this.plugin.app.vault.read(f); + let put = rows; + const more: WorldTypeExtras = { ...extras }; + if (base) { + const now = parseWorldTypes(content); + if (!sameOptional(now.rows, base.rows, worldTypeCells)) put = now.rows; + if (!sameOptional(now.stars, base.stars, starCells)) delete more.stars; + if (!sameOptional(now.features, base.features, featureCells)) delete more.features; + } + const next = updateWorldTypes(content, put, more, this.links()); + if (next !== content) await this.plugin.app.vault.modify(f, next); + this.take(f.path, next); + this.publish(); + }); + return true; + } + + /** A new table note (rows default to a copy of the shipped table). Returns its name, or an error. */ + async create( + name: string, + rows: readonly WorldTypeRow[] = DEFAULT_WORLD_TYPE_ROWS, + extras: WorldTypeExtras = DEFAULT_WORLD_TYPE_EXTRAS, + ): Promise<{ name: string } | { error: string }> { + const clean = name.trim() ? biomeFileName(name.trim()) : ""; + if (!clean) return { error: "Give the table a name." }; + const folder = this.folder(); + const path = `${folder}/${clean}.md`; + if (this.find(clean) || this.plugin.app.vault.getAbstractFileByPath(path)) return { error: `There's already a table called ${clean}.` }; + await this.enqueue(async () => { + await this.ensureFolder(folder); + const text = buildWorldTypes(clean, copyWorldTypeRows(rows), extras, this.links()); + await this.plugin.app.vault.create(path, text); + this.take(path, text); + this.publish(); + }); + return { name: clean }; + } + + /** + * Put the shipped rows back into the "Default space" note (the old note + * is backed up first), or write the note again if it was deleted. + */ + async restoreDefault(name: string = DEFAULT_WORLD_TYPES): Promise { + if (!this.hasDefault(name)) return false; + await this.queue; + const e = this.find(DEFAULT_WORLD_TYPES); + const f = e ? this.plugin.app.vault.getAbstractFileByPath(e.path) : null; + await this.enqueue(async () => { + if (f instanceof TFile) { + const content = await this.plugin.app.vault.read(f); + await this.backup("default-space", { [f.path]: content }); + const next = updateWorldTypes(content, DEFAULT_WORLD_TYPE_ROWS, DEFAULT_WORLD_TYPE_EXTRAS, this.links()); + if (next !== content) await this.plugin.app.vault.modify(f, next); + this.take(f.path, next); + } else { + await this.writeDefault(); + } + this.publish(); + }); + return true; + } + + // ── vault events ─────────────────────────────────────────────────────── + + onRename(f: TAbstractFile, oldPath: string): void { + const had = this.entries.delete(oldPath); + this.lastContent.delete(oldPath); + if (!this.isNoteFile(f)) { + if (had) this.publish(); + return; + } + void this.enqueue(async () => { + await this.load(f); + this.publish(); + }); + } + + // ── internals ────────────────────────────────────────────────────────── + + private sorted(): Entry[] { + return [...this.entries.values()].sort((a, b) => a.name.localeCompare(b.name) || a.path.localeCompare(b.path)); + } + + private find(name: string): Entry | undefined { + const k = name.trim().replace(/\.md$/i, "").toLowerCase(); + const list = this.sorted(); + return list.find((e) => e.path.toLowerCase() === `${k}.md` || e.path.toLowerCase() === k) + ?? list.find((e) => e.name.toLowerCase() === k); + } + + protected isNoteFile(f: TAbstractFile): f is TFile { + return f instanceof TFile && f.extension === "md" && !f.basename.startsWith("_") + && f.path.startsWith(this.folder() + "/"); + } + + /** Read one note (upgrading a format 1 note first). True when what it says changed. */ + protected async load(f: TFile): Promise { + let content = await this.plugin.app.vault.read(f); + if (this.lastContent.get(f.path) === content && this.entries.has(f.path)) return false; + const upgraded = upgradeWorldTypes(content, { ...DEFAULT_WORLD_TYPE_EXTRAS, rows: DEFAULT_WORLD_TYPE_ROWS }, this.links()); + if (upgraded !== content) { + try { + await this.backup("upgrade", { [f.path]: content }); + await this.plugin.app.vault.modify(f, upgraded); + content = upgraded; + } catch (e) { + logError("couldn't add stars and sector features to", e, f.path); + } + } + this.take(f.path, content); + return true; + } + + private take(path: string, content: string): void { + const { rows, stars, features, problems } = parseWorldTypes(content); + const name = path.slice(path.lastIndexOf("/") + 1).replace(/\.md$/i, ""); + const entry: Entry = { path, name, rows, problems }; + if (stars) entry.stars = stars; + if (features) entry.features = features; + this.entries.set(path, entry); + this.lastContent.set(path, content); + this.report(path, name, problems); + } + + private report(path: string, name: string, problems: WorldTypeProblem[]): void { + const key = problems.map((p) => p.text).join("; "); + if (this.reported.get(path) === key) return; + this.reported.set(path, key); + if (key && this.ready) new Notice(`World types ${name}: couldn't read ${key}.`, 8000); + } + + private async seed(): Promise { + if (this.settings.worldTypesSeeded) return; + if (!this.find(DEFAULT_WORLD_TYPES)) await this.writeDefault(); + this.settings.worldTypesSeeded = true; + await this.plugin.saveSettings(); + } + + private async writeDefault(): Promise { + const folder = this.folder(); + const path = `${folder}/${DEFAULT_WORLD_TYPES}.md`; + if (this.plugin.app.vault.getAbstractFileByPath(path)) return; + await this.ensureFolder(folder); + const text = buildWorldTypes(DEFAULT_WORLD_TYPES, copyWorldTypeRows(DEFAULT_WORLD_TYPE_ROWS), DEFAULT_WORLD_TYPE_EXTRAS, this.links()); + try { + await this.plugin.app.vault.create(path, text); + this.take(path, text); + } catch (e) { + logError("couldn't write the world types note", e, path); + } + } +} diff --git a/src/space/WorldTypesModal.ts b/src/space/WorldTypesModal.ts new file mode 100644 index 00000000..c14237b0 --- /dev/null +++ b/src/space/WorldTypesModal.ts @@ -0,0 +1,680 @@ +/** + * "World types": edit a world types table (worldTypes.ts) — which worlds + * the space generators place, how often, and what each world's own map is + * made with — plus its Stars (Orbits' random star) and Sector features + * (Star scatter's special hexes), one tab each. Each tab has a small + * preview that rolls its table and shows what comes up: for a palette, + * through the same role tables and rolls as Star scatter and Orbits + * (worldTypesSource.ts, tableRoles.ts), so its odds are the generators' + * odds (F3). Rows the generators can't place (not terrains of the + * palette) are listed under it, never dropped silently. + * + * Rows are edited as their note cells (the same reading as the note), so + * anything typed here reads back the same from the note. Rows the note + * has that can't be read are listed, never touched. + * + * Changes save automatically, like the hex editor (SP2): a moment after + * typing stops, and when the dialog closes. Only rows that read are + * written; a row that doesn't is marked incomplete and stays here until + * it's fixed or removed (it's dropped on close). Hand edits to the note + * while the dialog is open are taken in, never overwritten + * (worldTypesDraft.ts has the rules). + * + * Opened from the space generators' options (New map / submap setup) and + * the "Edit world types…" command. Editing follows the map's work mode: + * Build and God (canAdd), not Play. + */ + +import { App, Notice, TFile } from "obsidian"; +import { HexmakerModal } from "../HexmakerModal"; +import type HexmakerPlugin from "../HexmakerPlugin"; +import { canAdd } from "../workMode"; +import { + DEFAULT_WORLD_TYPES, + FEATURE_COLUMNS, + ORBIT_ZONES, + STAR_COLUMNS, + WORLD_TYPE_COLUMNS, + formatChance, + type OrbitZone, + type WorldTypeColumn, + type WorldTypeMap, +} from "./worldTypes"; +import { worldTypesSource } from "./worldTypesSource"; +import { ZONE_ROLES, roleOdds, rollRole, type RoleId } from "../worldgen/tableRoles"; +import { starScatterOffered, starScatterRoles } from "./starScatter"; +import { orbitRoles, orbitsFits } from "./orbits"; +import { mulberry32 } from "../../packages/hex-wfc/src/rng"; +import type { TerrainColor } from "../types"; +import { TAB_ORDER, WorldTypesDraft, type WorldTypesTab } from "./worldTypesDraft"; +import { AUTOSAVE_MS, DebouncedSave, SAVE_STATUS_TEXT, SaveTracker, type SaveState } from "../hex-map/saveStatus"; +import { isDebugMode } from "../ui/debugMode"; +import { isShown, layerOf } from "../ui/placement"; +import { oddsText, readOddsWeight } from "../ui/odds"; +import { lockButton } from "../ui/lockButton"; + +/** Why world types can't be edited from this map now, or undefined. */ +export function worldTypesEditLock(plugin: HexmakerPlugin, mapName: string | undefined): string | undefined { + const map = mapName ? plugin.getMap(mapName) : undefined; + return canAdd(map) ? undefined : "Switch to Build to edit world types."; +} + +const PLACEHOLDERS: Record = { + World: "ocean planet", + Weight: "1", + Orbit: "any", + Stars: "any", + Temperature: "any", + Size: "20×14", + Generator: "none", + Options: "water=85, climate=lush", + Palette: "same", + Base: "none", + Notes: "", + Mainworld: "same", + Star: "red dwarf", + Feature: "black hole", + Chance: "1 in 50", +}; + +/** Columns shown on a row's first line (what is picked, and where); the rest are its map setup. */ +const PICK_COLUMNS: WorldTypeColumn[] = ["World", "Weight", "Map", "Orbit", "Stars", "Temperature"]; +const SETUP_COLUMNS: WorldTypeColumn[] = ["Mainworld", "Size", "Generator", "Options", "Palette", "Base", "Notes"]; +/** Per-row cells the placement map can move (a row can't have its own dropdown: Debug ones show inline only in debug mode). */ +const PLACED_CELLS: Partial> = { Generator: "WorldTypes.worldGenerator", Options: "WorldTypes.worldOptions" }; +/** The preview's controls, by label. */ +const PREVIEW_IDS: Record = { + Map: "WorldTypes.previewMap", + Orbit: "WorldTypes.previewOrbit", + Star: "WorldTypes.previewStar", + Temperature: "WorldTypes.previewTemperature", + Rolls: "WorldTypes.previewRolls", +}; + +const col = (c: WorldTypeColumn) => WORLD_TYPE_COLUMNS.indexOf(c); + +export type { WorldTypesTab }; + +/** One tab's table: its columns. */ +interface TabSpec { + label: string; + columns: readonly string[]; +} + +const TABS: Record = { + worlds: { label: "Worlds", columns: WORLD_TYPE_COLUMNS }, + stars: { label: "Stars", columns: STAR_COLUMNS }, + features: { label: "Sector features", columns: FEATURE_COLUMNS }, +}; + +/** Tooltip on the save status. */ +const SAVE_TITLE = "Saves a moment after you stop typing, and when you close the dialog. Rows marked incomplete aren't saved."; + +/** "1 incomplete row" / "2 incomplete rows". */ +const incompleteRows = (n: number) => `${n} incomplete row${n === 1 ? "" : "s"}`; + +/** Terrain types offered as suggestions for each name column. */ +const SUGGEST_TYPES: Record = { + World: ["world", "gas-giant", "asteroids", "moon", "star-system", "station", "starport", "anomaly"], + Stars: ["star"], + Star: ["star"], + Feature: ["station", "starport", "jump-point", "anomaly", "star-system", "rift"], +}; + +export class WorldTypesModal extends HexmakerModal { + protected surfaceId = "WorldTypes"; + private tableName: string; + private tab: WorldTypesTab; + /** The rows being edited and when they need saving (set once the store is ready). */ + private draft: WorldTypesDraft | undefined; + private off: (() => void) | undefined; + private rowsEl!: HTMLElement; + private previewEl!: HTMLElement; + private problemsEl: HTMLElement | undefined; + private statusEl: HTMLElement | undefined; + private incompleteEl: HTMLElement | undefined; + /** The table names the picker shows (re-drawn when they change). */ + private listed = ""; + private saves = new SaveTracker( + (state) => this.renderSaveStatus(state), + (fn, ms) => window.setTimeout(fn, ms), + (id) => window.clearTimeout(id), + ); + private debounce = new DebouncedSave( + () => this.saveNow(), + AUTOSAVE_MS, + (fn, ms) => window.setTimeout(fn, ms), + (id) => window.clearTimeout(id), + ); + private tabButtons = new Map(); + private preview: { map: WorldTypeMap; zone: OrbitZone; star: string; palette: string; n: number } = { map: "sector", zone: "habitable", star: "", palette: "", n: 200 }; + + /** `mapName`: the map it was opened for (work mode, preview's map kind). `tab`: the tab to open on. */ + constructor(app: App, private plugin: HexmakerPlugin, private mapName?: string, table?: string, previewMap?: WorldTypeMap, tab: WorldTypesTab = "worlds") { + super(app); + this.tableName = table ?? DEFAULT_WORLD_TYPES; + this.tab = tab; + if (previewMap) this.preview.map = previewMap; + } + + onOpen(): void { + this.makeDraggable(); + this.modalEl.addClass("duckmage-world-types-modal"); + this.titleEl.setText("World types"); + void this.plugin.worldTypeStore.ensureDefault().then(() => { + const store = this.plugin.worldTypeStore; + if (!store.get(this.tableName)) this.tableName = store.list()[0]?.name ?? this.tableName; + this.draft = new WorldTypesDraft(store, this.tableName); + this.render(); + // Hand edits to the note show up here (worldTypesDraft.ts: sync). + this.off = store.onChange(() => this.storeChanged()); + }); + } + + onClose(): void { + this.off?.(); + this.saveNow(); + this.noteDropped(); + this.saves.dispose(); + this.contentEl.empty(); + } + + private lock(): string | undefined { + return worldTypesEditLock(this.plugin, this.mapName); + } + + /** The rows being edited, as note cells, per tab. */ + private get cells(): Record { + return this.draft?.cells ?? { worlds: [], stars: [], features: [] }; + } + + /** Save now if anything that reads changed (incomplete rows never are). */ + private saveNow(): void { + this.debounce.cancel(); + const draft = this.draft; + if (!draft || this.lock() || !draft.hasChanges()) { + this.saves.settle(); + return; + } + void this.saves.track(draft.save().then((ok) => { + if (!ok) throw new Error(`world types table "${draft.name}" not found`); + })); + } + + /** Incomplete rows are about to be dropped (close, another table): say so. */ + private noteDropped(): void { + const n = this.draft?.incompleteCount() ?? 0; + if (n && !this.lock()) new Notice(`World types: ${incompleteRows(n)} weren't saved.`); + } + + /** Show another table (saving this one's changes first). */ + private switchTable(name: string): void { + this.saveNow(); + this.noteDropped(); + this.tableName = name; + this.draft?.load(name); + this.render(); + } + + /** The store changed: a hand edit, our own save coming back, or another table. */ + private storeChanged(): void { + const draft = this.draft; + if (!draft) return; + const { changed, replaced } = draft.sync(); + if (replaced.length) { + const tabs = replaced.map((t) => TABS[t].label).join(" and "); + new Notice(`The world types note was edited, so ${tabs} now show${replaced.length === 1 ? "s" : ""} the note's rows.`, 8000); + } + if (changed || this.tableNames() !== this.listed) { + this.render(); + } else { + this.renderProblems(); + this.updateStatus(); + } + } + + private tableNames(): string { + return this.plugin.worldTypeStore.list().map((t) => t.name).join("\n"); + } + + // ── rendering ────────────────────────────────────────────────────────── + + private render(): void { + const { contentEl, plugin } = this; + const store = plugin.worldTypeStore; + contentEl.empty(); + const lock = this.lock(); + + // Table picker and note actions. + const head = contentEl.createDiv({ cls: "duckmage-world-types-head" }); + const sel = head.createEl("select", { attr: { "aria-label": "Table" } }); + for (const t of store.list()) sel.createEl("option", { value: t.name, text: t.name }); + sel.value = this.tableName; + this.listed = this.tableNames(); + sel.addEventListener("change", () => this.switchTable(sel.value)); + const newBtn = head.createEl("button", { text: "New table…" }); + if (lock) lockButton(newBtn, lock); + newBtn.addEventListener("click", () => this.newTable(head)); + head.createEl("button", { text: "Open note" }).addEventListener("click", () => { + const path = store.pathOf(this.tableName); + const f = path ? plugin.app.vault.getAbstractFileByPath(path) : null; + if (f instanceof TFile) { this.close(); void plugin.app.workspace.getLeaf("tab").openFile(f); } + }); + if (store.hasDefault(this.tableName)) { + const restore = head.createEl("button", { text: "Restore default" }); + if (lock) lockButton(restore, lock); + restore.addEventListener("click", () => { + if (this.lock()) return; + this.debounce.cancel(); + void store.restoreDefault(this.tableName).then((ok) => { + if (!ok) return; + this.draft?.load(this.tableName); + this.saves.settle(); + this.render(); + new Notice("World types restored (the old note was backed up)."); + }); + }); + } + + contentEl.createEl("p", { + cls: "setting-item-description", + text: `What the space generators place and how often. Each table is a note in ${store.folder()}.`, + }); + if (lock) contentEl.createEl("p", { cls: "duckmage-locked-hint", text: lock }); + // Converted (phase 3): the generators roll on the tables the note links now. + if (store.isConverted(this.tableName)) { + contentEl.createEl("p", { + cls: "duckmage-locked-hint", + text: "This table was converted to random tables: the generators roll on the tables its note links; open the note to see them. Changes here only change the old copy.", + }); + } + this.problemsEl = contentEl.createDiv(); + this.renderProblems(); + + const tabs = contentEl.createDiv({ cls: "duckmage-world-types-tabs", attr: { role: "tablist" } }); + this.tabButtons.clear(); + for (const t of TAB_ORDER) { + const b = tabs.createEl("button", { + text: `${TABS[t].label} (${this.cells[t].length})`, + cls: "duckmage-world-types-tab", + attr: { role: "tab", "aria-selected": String(t === this.tab) }, + }); + b.toggleClass("is-active", t === this.tab); + this.tabButtons.set(t, b); + b.addEventListener("click", () => { + if (t === this.tab) return; + this.tab = t; + this.render(); + }); + } + contentEl.createEl("p", { cls: "setting-item-description", text: this.tabHint() }); + + this.rowsEl = contentEl.createDiv({ cls: "duckmage-world-types-rows" }); + this.renderRows(); + + const foot = this.footer({ secondary: [{ text: "Add row", onClick: () => { + if (this.lock()) return; + const blank = TABS[this.tab].columns.map(() => ""); + if (this.tab === "worlds" && this.preview.map) blank[col("Map")] = this.preview.map; + this.cells[this.tab].push(blank); + this.changed(); + // The new row is at the bottom of the list: show it and put the + // cursor in its first field (F9: it appeared off-screen). + this.renderRows({ row: this.cells[this.tab].length - 1, target: "first" }); + } }] }); + const buttons = foot.el; + const add = foot.buttons.get("Add row")!; + if (lock) lockButton(add, lock); + // Rows that can't be read yet, and the autosave status (as in the hex editor). + this.incompleteEl = buttons.createSpan({ cls: "duckmage-world-types-incomplete" }); + this.statusEl = undefined; + if (!lock) { + this.statusEl = buttons.createSpan({ + cls: "duckmage-editor-notes-status duckmage-world-types-status", + attr: { "aria-live": "polite", title: SAVE_TITLE }, + }); + this.renderSaveStatus(this.saves.current); + } + + contentEl.createEl("h4", { text: "Preview" }); + this.previewEl = contentEl.createDiv({ cls: "duckmage-world-types-preview" }); + this.renderPreview(); + this.updateStatus(); + } + + private tabHint(): string { + switch (this.tab) { + case "worlds": return "Which worlds Star scatter and Orbits place, and what each world's own map is made with. Weight is the odds against the other rows that fit; blank limits mean any."; + case "stars": return "The star Orbits puts at a system's centre when its Star option is Random. Weight is the odds against the other stars; 0 never rolls it."; + case "features": return "Star scatter's special hexes. Chance is how likely each star system hex is to be that feature instead, like 1 in 50, 2% or never."; + } + } + + /** What the note has that can't be read (kept as written, not shown as rows). */ + private renderProblems(): void { + const el = this.problemsEl; + if (!el) return; + el.empty(); + const problems = this.plugin.worldTypeStore.problemsOf(this.tableName); + if (!problems.length) return; + el.createEl("p", { + cls: "duckmage-world-types-problems", + text: `The note has ${problems.length} problem${problems.length === 1 ? "" : "s"} (rows that can't be read are kept as written): ${problems.map((p) => p.text).join("; ")}`, + }); + } + + private newTable(head: HTMLElement): void { + if (this.lock()) return; + const box = head.createDiv({ cls: "duckmage-world-types-new" }); + const input = box.createEl("input", { type: "text", attr: { placeholder: "Table name", "aria-label": "New table name" } }); + const ok = box.createEl("button", { text: "Create", cls: "mod-cta" }); + input.focus(); + const go = () => { + const draft = this.draft; + if (!draft) return; + this.saveNow(); + void this.plugin.worldTypeStore.create(input.value, draft.readable("worlds"), { stars: draft.readable("stars"), features: draft.readable("features") }).then((res) => { + if ("error" in res) { new Notice(res.error); return; } + this.switchTable(res.name); + }); + }; + ok.addEventListener("click", go); + input.addEventListener("keydown", (e) => { if (e.key === "Enter") go(); }); + } + + /** Rows were edited: save a moment later if anything that reads changed. */ + private changed(): void { + for (const [t, b] of this.tabButtons) b.setText(`${TABS[t].label} (${this.cells[t].length})`); + this.updateStatus(); + this.renderPreview(); + if (this.lock()) return; + if (this.draft?.hasChanges()) { + this.debounce.schedule(); + this.saves.markPending(); + } else { + // Nothing to write (only incomplete rows, or the edit was undone). + this.debounce.cancel(); + this.saves.settle(); + } + } + + /** How many rows can't be saved yet. */ + private updateStatus(): void { + const el = this.incompleteEl; + if (!el) return; + const n = this.draft?.incompleteCount() ?? 0; + el.setText(n ? `${incompleteRows(n)} not saved until finished.` : ""); + } + + private renderSaveStatus(state: SaveState): void { + const el = this.statusEl; + if (!el) return; + el.setText(SAVE_STATUS_TEXT[state]); + el.dataset["state"] = state; + } + + /** Terrain names (all palettes) of these types (any type when undefined), for suggestions. */ + private suggestions(types: string[] | undefined): string[] { + const out = new Set(); + for (const p of this.plugin.settings.terrainPalettes) { + for (const t of p.terrains) if (!types || types.includes(t.type ?? "")) out.add(t.name); + } + return [...out].sort((a, b) => a.localeCompare(b)); + } + + private datalist(id: string, values: string[]): string { + const full = `duckmage-world-types-${id}`; + activeDocument.getElementById(full)?.remove(); + const dl = this.contentEl.createEl("datalist", { attr: { id: full } }); + for (const v of values) dl.createEl("option", { value: v }); + return full; + } + + /** + * Draw the rows. Re-drawing keeps the list's scroll position; `focus` + * says where the cursor goes after: a row's first field (a new row, + * scrolled into view), its move button (moving again), or the list + * itself (after a delete, so typing never lands in the row that slid into + * the deleted one's place, F9). `keepHeight` keeps the list as tall as + * before (a delete) until the pointer leaves it, so rows above the + * deleted one don't shift under the pointer. + */ + private renderRows(focus?: { row: number; target: "first" | "up" | "down" | "list" }, keepHeight?: number): void { + const el = this.rowsEl; + const scrollTop = el.scrollTop; + el.empty(); + el.setAttr("tabindex", "-1"); + const lock = this.lock(); + const lists: Record = {}; + for (const [c, types] of Object.entries(SUGGEST_TYPES)) lists[c] = this.datalist(c.toLowerCase(), this.suggestions(types)); + lists.Base = this.datalist("base", this.suggestions(undefined)); + lists.Palette = this.datalist("palettes", this.plugin.settings.terrainPalettes.map((p) => p.name)); + const spec = TABS[this.tab]; + const rows = this.cells[this.tab]; + if (!rows.length) el.createDiv({ cls: "setting-item-description", text: "No rows yet." }); + rows.forEach((cells, i) => { + const row = el.createDiv({ cls: "duckmage-world-types-row" }); + const line = (cls: string, columns: readonly string[]) => { + const l = row.createDiv({ cls }); + for (const c of columns) this.cellInput(l, cells, spec, c, lists[c], !!lock, row); + return l; + }; + const top = this.tab === "worlds" + ? line("duckmage-world-types-line", PICK_COLUMNS) + : line("duckmage-world-types-line", spec.columns); + if (this.tab === "worlds") { + const debugOn = isDebugMode(this.app); + line("duckmage-world-types-line is-setup", SETUP_COLUMNS.filter((c) => { + const id = PLACED_CELLS[c]; + return !id || isShown(id, debugOn); + })); + } + const tools = top.createDiv({ cls: "duckmage-world-types-tools" }); + const btn = (text: string, label: string, fn: () => void, disabled: boolean, after: () => { row: number; target: "up" | "down" | "list" }, keep = false) => { + const b = tools.createEl("button", { text, attr: { "aria-label": label, title: label } }); + b.setAttr("data-tool", text === "↑" ? "up" : text === "↓" ? "down" : "remove"); + if (lock) lockButton(b, lock); + else b.disabled = disabled; + b.addEventListener("click", () => { + if (this.lock()) return; + const height = keep ? el.scrollHeight : undefined; + fn(); + this.changed(); + this.renderRows(after(), height); + }); + }; + btn("↑", "Move up", () => { [rows[i - 1], rows[i]] = [rows[i], rows[i - 1]]; }, i === 0, () => ({ row: i - 1, target: "up" })); + btn("↓", "Move down", () => { [rows[i + 1], rows[i]] = [rows[i], rows[i + 1]]; }, i === rows.length - 1, () => ({ row: i + 1, target: "down" })); + btn("✕", "Remove row", () => { rows.splice(i, 1); }, false, () => ({ row: i, target: "list" }), true); + this.markRow(row, cells); + }); + + // A delete keeps the list's height until the pointer leaves it. + const gap = keepHeight !== undefined ? keepHeight - el.scrollHeight : 0; + if (gap > 0) { + const spacer = el.createDiv({ cls: "duckmage-world-types-spacer" }); + spacer.setCssProps({ "--duckmage-wt-spacer": `${gap}px` }); + el.addEventListener("mouseleave", () => spacer.remove(), { once: true }); + } + el.scrollTop = scrollTop; + this.refreshOdds(); + + if (!focus) return; + const rowEl = el.querySelectorAll(".duckmage-world-types-row")[focus.row]; + if (focus.target === "list" || !rowEl) { el.focus({ preventScroll: true }); return; } + const target = focus.target === "first" + ? rowEl.querySelector("input, select") + : rowEl.querySelector(`button[data-tool="${focus.target}"]:not(:disabled)`); + rowEl.scrollIntoView({ block: "nearest" }); + (target ?? el).focus({ preventScroll: true }); + } + + private cellInput(parent: HTMLElement, cells: string[], spec: TabSpec, c: string, list: string | undefined, locked: boolean, row: HTMLElement): void { + const i = spec.columns.indexOf(c); + const wrap = parent.createEl("label", { cls: `duckmage-world-types-cell is-${c.toLowerCase()}` }); + wrap.createSpan({ cls: "duckmage-world-types-cell-label", text: c }); + if (spec === TABS.worlds && c === "Map") { + const sel = wrap.createEl("select", { attr: { "aria-label": c } }); + for (const [v, text] of [["", "Any"], ["sector", "Sector"], ["system", "System"]]) sel.createEl("option", { value: v, text }); + // A value the select doesn't list (typed in the note) stays as it was. + if (cells[i] && !["sector", "system"].includes(cells[i])) sel.createEl("option", { value: cells[i], text: cells[i] }); + sel.value = cells[i] ?? ""; + sel.disabled = locked; + sel.addEventListener("change", () => { cells[i] = sel.value; this.cellChanged(cells, row); }); + return; + } + const input = wrap.createEl("input", { type: "text", value: cells[i] ?? "", attr: { placeholder: PLACEHOLDERS[c] ?? "", "aria-label": c } }); + if (list) input.setAttr("list", list); + input.disabled = locked; + // Weights stay free; a % beside each says its share (owner Q1), live. + if (c === "Weight") wrap.createSpan({ cls: "duckmage-odds-percent", attr: { title: "Its share of the weights in this tab (among only the rows that fit a map, it's more)" } }); + input.addEventListener("input", () => { + cells[i] = input.value; + this.cellChanged(cells, row); + if (c === "Weight") this.refreshOdds(); + }); + } + + /** Every row's % beside its weight, from the weights as typed (blank = 1). */ + private refreshOdds(): void { + const w = TABS[this.tab].columns.indexOf("Weight"); + if (w < 0 || !this.rowsEl) return; + const odds = oddsText(this.cells[this.tab].map((cells) => readOddsWeight(cells[w] ?? ""))); + this.rowsEl.querySelectorAll(".duckmage-world-types-cell.is-weight .duckmage-odds-percent").forEach((el, i) => el.setText(odds[i] ?? "–")); + } + + private cellChanged(cells: string[], row: HTMLElement): void { + this.markRow(row, cells); + this.changed(); + } + + /** Mark a row that can't be read as incomplete, saying what's missing. */ + private markRow(row: HTMLElement, cells: readonly string[]): void { + const problem = this.draft?.problem(this.tab, cells); + row.toggleClass("is-invalid", !!problem); + let hint = row.querySelector(".duckmage-world-types-row-hint"); + if (!problem) { hint?.remove(); return; } + hint ??= row.createDiv({ cls: "duckmage-world-types-row-hint" }); + hint.setText(`Incomplete, not saved: ${problem}.`); + } + + // ── preview ──────────────────────────────────────────────────────────── + + /** + * The palette the preview rolls for: the one picked, else the map's own, + * else the first palette the previewed generator fits (by terrain types). + */ + private previewPalette(): { name: string; terrains: TerrainColor[] } | undefined { + const palettes = this.plugin.settings.terrainPalettes; + const fits = this.preview.map === "system" ? orbitsFits : starScatterOffered; + const mapPalette = this.mapName ? this.plugin.getMap(this.mapName)?.paletteName : undefined; + const p = palettes.find((x) => x.name === this.preview.palette) + ?? palettes.find((x) => x.name === mapPalette && fits(x.terrains)) + ?? palettes.find((x) => fits(x.terrains)) + ?? palettes[0]; + return p ? { name: p.name, terrains: p.terrains } : undefined; + } + + private renderPreview(): void { + const el = this.previewEl; + if (!el) return; + el.empty(); + const p = this.preview; + const controls = el.createDiv({ cls: "duckmage-world-types-preview-controls" }); + // Controls the placement map puts in Debug go in a preview box there. + const debugBox = (): HTMLElement | null => { + const dbg = this.section("debug"); + if (!dbg) return null; + let box = dbg.querySelector(":scope > .duckmage-world-types-preview-controls"); + if (!box) { + dbg.createDiv({ cls: "setting-item-description", text: "Preview" }); + box = dbg.createDiv({ cls: "duckmage-world-types-preview-controls" }); + } + return box; + }; + debugBox()?.empty(); + const select = (label: string, options: [string, string][], value: string, set: (v: string) => void) => { + const id = PREVIEW_IDS[label]; + const layer = id ? layerOf(id) : "main"; + const at = layer === "main" || layer === "more" ? controls : layer === "hidden" ? null : layer === "advanced" ? this.section("advanced") : debugBox(); + if (!at) return; + const l = at.createEl("label", { text: `${label} ` }); + const s = l.createEl("select", { attr: { "aria-label": `Preview ${label.toLowerCase()}` } }); + for (const [v, t] of options) s.createEl("option", { value: v, text: t }); + s.value = value; + s.addEventListener("change", () => { set(s.value); this.renderPreview(); }); + }; + if (this.tab === "worlds") { + select("Map", [["sector", "Sector (Star scatter)"], ["system", "System (Orbits)"]], p.map, (v) => { p.map = v as WorldTypeMap; p.palette = ""; }); + if (p.map === "system") { + select("Orbit", ORBIT_ZONES.map((z): [string, string] => [z, z[0].toUpperCase() + z.slice(1)]), p.zone, (v) => { p.zone = v as OrbitZone; }); + select("Star", [["", "Any"], ...this.suggestions(["star"]).map((s): [string, string] => [s, s])], p.star, (v) => { p.star = v; }); + } + } else { + p.map = this.tab === "stars" ? "system" : "sector"; + } + const palette = this.previewPalette(); + if (!palette) { + el.createDiv({ cls: "setting-item-description", text: "No palettes yet." }); + return; + } + select("Palette", this.plugin.settings.terrainPalettes.map((x): [string, string] => [x.name, x.name]), palette.name, (v) => { p.palette = v; }); + const rollChoices: [string, string][] = this.tab === "features" + ? [["100", "100 systems"], ["1000", "1000 systems"], ["10000", "10000 systems"]] + : [["100", "100"], ["200", "200"], ["1000", "1000"]]; + if (!rollChoices.some(([v]) => Number(v) === p.n)) p.n = Number(rollChoices[1][0]); + select("Rolls", rollChoices, String(p.n), (v) => { p.n = Number(v); }); + + // The generators' own roles, fallback and rolls (worldgen/tableRoles.ts). + const table = this.draft?.table() ?? { name: this.tableName, rows: [] }; + const source = worldTypesSource(table, palette.terrains); + const role: RoleId = this.tab === "stars" ? "star" : p.map === "system" ? ZONE_ROLES[p.zone] : "sector-hexes"; + const fallback = role === "sector-hexes" + ? starScatterRoles(palette.terrains)?.worlds ?? [] + : role === "star" ? orbitRoles(palette.terrains)?.stars ?? [] : orbitRoles(palette.terrains)?.bodies ?? []; + const ctx = role === "star" || role === "sector-hexes" ? {} : { zone: p.zone, ...(p.star ? { star: p.star } : {}) }; + const { odds, notes } = roleOdds(source, role, ctx, fallback); + const rolled = new Map(); + for (let i = 0; i < p.n; i++) { + const pick = rollRole(source, role, { ...ctx, rand: mulberry32(i + 1) }, fallback); + const k = pick ? pick.terrain.toLowerCase() : ""; + rolled.set(k, (rolled.get(k) ?? 0) + 1); + } + + const list = () => el.createDiv({ cls: "duckmage-world-types-dist" }); + const bar = (parent: HTMLElement, name: string, n: number, odds: string) => { + const r = parent.createDiv({ cls: "duckmage-world-types-dist-row" }); + r.createSpan({ cls: "duckmage-world-types-dist-name", text: name }); + const b = r.createSpan({ cls: "duckmage-world-types-dist-bar" }); + b.createSpan({ cls: "duckmage-world-types-dist-fill" }).setCssProps({ "--duckmage-dist": `${Math.round((n / p.n) * 100)}%` }); + r.createSpan({ cls: "duckmage-world-types-dist-num", text: `${n} of ${p.n}` }); + r.createSpan({ cls: "duckmage-world-types-dist-odds", text: odds }); + }; + const pct = (x: number) => `${Math.round(x * 1000) / 10}%`; + const showNotes = () => { + // Never silently: rows the generator can't place, and equal-odds fallbacks. + if (notes.length) el.createEl("p", { cls: "duckmage-world-types-problems", text: notes.join(" ") }); + }; + + if (!odds.length) { + el.createDiv({ cls: "setting-item-description", text: `Nothing on ${palette.name} fits: nothing would be placed here.` }); + showNotes(); + return; + } + const l = list(); + if (this.tab === "features") { + const featureNames = new Set((table.features ?? []).map((f) => f.feature.trim().toLowerCase())); + let systems = 0; + let systemOdds = 0; + for (const o of odds) { + const k = o.terrain.toLowerCase(); + if (featureNames.has(k)) bar(l, o.terrain, rolled.get(k) ?? 0, `${formatChance(o.odds)} (${pct(o.odds)})`); + else { systems += rolled.get(k) ?? 0; systemOdds += o.odds; } + } + bar(l, "an ordinary system", systems, pct(systemOdds)); + } else { + for (const o of odds) bar(l, o.terrain || "(nothing)", rolled.get(o.terrain.toLowerCase()) ?? 0, `odds ${pct(o.odds)}`); + } + showNotes(); + } +} diff --git a/src/space/moonLinks.ts b/src/space/moonLinks.ts new file mode 100644 index 00000000..9034da19 --- /dev/null +++ b/src/space/moonLinks.ts @@ -0,0 +1,88 @@ +/** + * Which planet a moon belongs to (S11): on a map, every hex whose terrain + * is of type moon is tied to each neighbouring hex whose terrain is a + * planet (type world or gas giant). The map view draws a faint tether + * across the edge they share. By terrain TYPE only, never names, so a + * custom palette ("Luna" typed moon) works the same as the shipped one. + * Pure: no Obsidian imports. + */ +import type { TerrainColor } from "../types"; +import type { MapOverlayDef } from "../modules/types"; +import { effectiveTerrainType } from "../terrainTypes"; +import { hexNeighbors, type Orientation, type Stagger } from "../../packages/hex-wfc/src/grid"; +import { latticeCenter, type LatticeGrid, type Pt } from "../paths/pathGeometry"; +import { hexKey, hexXY } from "../hexKey"; + +export const MOON_TYPES: readonly string[] = ["moon"]; +export const PLANET_TYPES: readonly string[] = ["world", "gas-giant"]; + +/** [moon hex, planet hex] pairs ("x_y" keys), in a stable order. */ +export function moonPlanetLinks( + terrainAt: ReadonlyMap, + palette: readonly TerrainColor[], + orientation: Orientation, + stagger: Stagger, +): [string, string][] { + const type = new Map(palette.map((t) => [t.name.toLowerCase(), effectiveTerrainType(t)])); + const typeAt = (key: string) => { + const t = terrainAt.get(key); + return t ? type.get(t.toLowerCase()) : undefined; + }; + const out: [string, string][] = []; + for (const key of [...terrainAt.keys()].sort()) { + if (!MOON_TYPES.includes(typeAt(key) ?? "")) continue; + const { x, y } = hexXY(key); + for (const [nx, ny] of hexNeighbors(x, y, orientation, stagger)) { + const n = hexKey(nx, ny); + if (PLANET_TYPES.includes(typeAt(n) ?? "")) out.push([key, n]); + } + } + return out; +} + +/** The tether between two hex centres: the middle part of the line joining them (from `t` to 1 - t). */ +export function tether(a: { cx: number; cy: number }, b: { cx: number; cy: number }, t = 0.3): [{ cx: number; cy: number }, { cx: number; cy: number }] { + const at = (f: number) => ({ cx: a.cx + (b.cx - a.cx) * f, cy: a.cy + (b.cy - a.cy) * f }); + return [at(t), at(1 - t)]; +} + +/** + * How a tether looks, in lattice units (× the hex radius when drawn). The + * map view sets width and dash from here; its colour and opacity live in + * styles.css (`.duckmage-moon-link`, kept equal by tests/moonLinks.test.ts). + * The PNG export draws all four from here, so it matches the screen. + */ +export const MOON_TETHER_STYLE = { + color: "#d7deff", + opacity: 0.55, + width: 0.07, + dash: [0.1, 0.08] as readonly number[], +} as const; + +/** + * Every moon tether on a map, in lattice units: the segment the map view and + * the PNG export both draw. `include` drops ties whose ends are not both + * drawn (an export of part of the map). + */ +export function moonTethers( + terrainAt: ReadonlyMap, + palette: readonly TerrainColor[], + grid: LatticeGrid, + include: (hexKey: string) => boolean = () => true, +): [Pt, Pt][] { + return moonPlanetLinks(terrainAt, palette, grid.orientation, grid.stagger) + .filter(([moon, planet]) => include(moon) && include(planet)) + .map(([moon, planet]) => tether(latticeCenter(moon, grid), latticeCenter(planet, grid))); +} + +/** + * Moon tethers as a map overlay (plan-code-modules P5): the Space module + * contributes it, and the map view and the PNG export draw every module's + * overlays the same way (registry.overlays()). + */ +export const MOON_TETHER_OVERLAY: MapOverlayDef = { + id: "moon-tethers", + cls: "duckmage-moon-link", + style: MOON_TETHER_STYLE, + segments: moonTethers, +}; diff --git a/src/space/orbits.ts b/src/space/orbits.ts new file mode 100644 index 00000000..b14b35ca --- /dev/null +++ b/src/space/orbits.ts @@ -0,0 +1,359 @@ +import { hexCenter, mulberry32 } from "../../packages/hex-wfc/src"; +import type { TerrainColor } from "../types"; +import { effectiveTerrainType, normalizeTerrainType } from "../terrainTypes"; +import { + cellKey, + centerHex, + distance, + gridKeys, + ofType, + type GenerationContext, + type ProcGrid, + type ProcOption, + type ProcPath, + type ProcResult, + type TuningDef, + tuned, +} from "../worldgen/procedural/common"; +import { ZONE_ROLES, readCount, roleOdds, roleValueOdds, rollRole, rollRoleEach, rollRoleValue, type TableSource } from "../worldgen/tableRoles"; +import { ORBIT_ZONES, orbitZone } from "./worldTypes"; + +/** + * Star-system "orbits": a star at the centre, then one body per orbit ring + * (hex distance from the star), typed by zone — hot inner rocks, a + * habitable middle, cold giants outside. Belts fill part of a ring; planets + * may get moons (the palette's moon terrain) on the hexes beside them — + * giants more often, and up to two; the mainworld may get a station or starport alongside; + * a comet and a jump point sit out past the last orbit. + * + * Works on any palette with a background (type void), at least one star + * (type star) and one body (world / gas-giant / asteroids). Every other + * role has its own type too — moon, comet, station, starport, jump point, + * jump limit — so it is the Type column, never a terrain's name, that + * decides what goes where. + * + * Which star, and which body on each orbit, are rolled on the Star and + * Inner / Habitable / Outer orbits roles (tableRoles.ts): the World types + * table when one is given, else equal odds over the palette's stars and + * bodies. The sector hex's row says which body is the mainworld (its + * Mainworld column). No terrain name is special. + * + * How many moons each planet gets, and the system's extras (starport, + * station, jump point, comet), are rolled on the Moons and System extras + * roles: the shipped tables (src/modules/space/tables, today's odds) unless + * a map or setup names its own (T12). An extra's Result is a terrain or a + * terrain type (the palette's first terrain of that type), so the shipped + * table works on any palette. + */ + +export const ORBITS_ID = "procedural:orbits"; + +export const ORBITS_OPTIONS: ProcOption[] = [ + { + key: "star", + label: "Star", + // The palette's own stars are added per palette (orbitsOptions). + choices: [{ value: "random", label: "Random" }], + default: "random", + }, + { + key: "bodies", + label: "Planets", + choices: [ + { value: "few", label: "Few" }, + { value: "normal", label: "Normal" }, + { value: "crowded", label: "Crowded" }, + ], + default: "normal", + }, +]; + +/** + * Orbits' tuning sliders (setup wizard Advanced): the ring layout. Moons + * and system extras roll on their tables (Moons, System extras), so their + * odds are edited there, not here. + */ +export const ORBITS_TUNING: readonly TuningDef[] = [ + { key: "firstOrbit", label: "First orbit", help: "Rings out from the star where the first planet may orbit.", min: 1, max: 4, step: 1, default: 2 }, + { key: "outerRoom", label: "Room past the orbits", help: "Rings left empty at the edge for the jump point and other outer extras.", min: 0, max: 4, step: 1, default: 0 }, + { key: "emptyOrbits", label: "More empty orbits", help: "Percentage points added to (or taken from) the chance a ring has no planet.", min: -40, max: 40, step: 5, default: 0 }, + { key: "beltLength", label: "Belt length", help: "The shortest share of its ring an asteroid belt fills.", min: 0, max: 0.6, step: 0.05, default: 0.3 }, + { key: "beltSpread", label: "Belt variety", help: "How much longer than the shortest a belt may be, as a share of its ring.", min: 0, max: 0.6, step: 0.05, default: 0.4 }, +]; + +/** + * Orbits' options for a palette: the Star choice lists that palette's own + * stars (star-typed terrains), so it only offers what it can place. With + * no palette given, only Random. + */ +export function orbitsOptions(terrains?: TerrainColor[]): ProcOption[] { + if (!terrains) return ORBITS_OPTIONS; + const stars = ofType(terrains, ["star"]); + return ORBITS_OPTIONS.map((o) => o.key !== "star" ? o : { + ...o, + choices: [{ value: "random", label: "Random" }, ...stars.map((s) => ({ value: s.toLowerCase(), label: s.charAt(0).toUpperCase() + s.slice(1) }))], + }); +} + +export interface OrbitRoles { + background: string; + stars: string[]; + bodies: string[]; + moon?: string; + comet?: string; + station?: string; + starport?: string; + jumpPoint?: string; + jumpLimit?: string; + belt?: string; + /** Bodies drawn as an arc of their ring (asteroid-belt type). */ + belts: string[]; + /** Bodies that may get two moons (gas-giant type). */ + giants: string[]; +} + +/** + * Roles by terrain type only: void (background), star, world / gas-giant / + * asteroids (bodies that take an orbit), and one terrain each for moon, + * comet, station, starport, jump point and jump limit. A terrain's name + * plays no part, so a custom palette ("Luna" typed moon) works the same as + * the shipped one, and an untyped terrain is never placed. + */ +export function orbitRoles(terrains: TerrainColor[]): OrbitRoles | undefined { + const background = ofType(terrains, ["void"])[0]; + const stars = ofType(terrains, ["star"]); + const bodies = ofType(terrains, ["world", "gas-giant", "asteroids"]); + if (!background || stars.length === 0 || bodies.length === 0) return undefined; + const first = (type: string) => ofType(terrains, [type])[0]; + const belts = ofType(terrains, ["asteroids"]); + return { + background, + stars, + bodies, + moon: first("moon"), + comet: first("comet"), + station: first("station"), + starport: first("starport"), + jumpPoint: first("jump-point"), + jumpLimit: first("jump-limit"), + belt: belts[0], + belts, + giants: ofType(terrains, ["gas-giant"]), + }; +} + +export function orbitsFits(terrains: TerrainColor[]): boolean { + return orbitRoles(terrains) !== undefined; +} + +export function orbits( + terrains: TerrainColor[], + grid: ProcGrid, + seed: number, + options: Record = {}, + /** Path type to draw occupied orbits with (e.g. "Orbit"); none = no rings. */ + orbitPathType?: string, + /** The sector hex this system sits in: its row's Mainworld picks the mainworld. */ + context?: GenerationContext, + /** The role tables (World types); none = equal odds over the palette's stars and bodies, said in the warnings. */ + tables?: TableSource, +): ProcResult { + const roles = orbitRoles(terrains); + if (!roles) { + return { cells: new Map(), paths: [], warnings: ["This palette has no void, star, or planet terrains."] }; + } + const rand = mulberry32(seed); + const bodyType = new Map(terrains.map((t) => [t.name, effectiveTerrainType(t)])); + const hexes = gridKeys(grid); + const center = centerHex(grid); + const cells = new Map(); + const dist = new Map(); + let maxD = 0; + for (const h of hexes) { + const k = cellKey(h[0], h[1]); + cells.set(k, roles.background); + const d = distance(center, h, grid); + dist.set(k, d); + maxD = Math.max(maxD, d); + } + // The largest ring that is complete on this grid — orbits beyond it would + // be clipped by the map edge. + const fullRing = Math.min( + ...hexes.filter((h) => h[0] === grid.offset.x || h[1] === grid.offset.y + || h[0] === grid.offset.x + grid.cols - 1 || h[1] === grid.offset.y + grid.rows - 1) + .map((h) => distance(center, h, grid)), + ); + const ring = (d: number) => hexes.filter((h) => dist.get(cellKey(h[0], h[1])) === d); + const set = (h: [number, number], t: string | undefined) => { if (t) cells.set(cellKey(h[0], h[1]), t); }; + + // Star. + const wanted = options.star && options.star !== "random" + ? roles.stars.find((s) => s.toLowerCase() === options.star) + : undefined; + const star = wanted ?? rollRole(tables, "star", { rand, where: cellKey(center[0], center[1]) }, roles.stars)?.terrain ?? roles.stars[0]; + set(center, star); + // The 100-diameter limit hugs the star: mark the first ring. + if (roles.jumpLimit && fullRing >= 3) for (const h of ring(1)) set(h, roles.jumpLimit); + + // Orbits from ring 2 out to the last full ring. + const first = Math.max(1, Math.round(tuned(options, "firstOrbit", 2))); + const last = Math.max(first, fullRing - Math.max(0, Math.round(tuned(options, "outerRoom", 0)))); + const baseSkip = options.bodies === "few" ? 0.45 : options.bodies === "crowded" ? 0.05 : 0.2; + const moreEmpty = tuned(options, "emptyOrbits", 0); + const skip = moreEmpty ? Math.min(1, Math.max(0, baseSkip + moreEmpty / 100)) : baseSkip; + const warnings: string[] = []; + // Rows that can't be placed, and roles with no table, are said (never dropped silently). + const notes = new Set(); + if (!wanted) for (const n of roleOdds(tables, "star", {}, roles.stars).notes) notes.add(n); + for (const z of ORBIT_ZONES) for (const n of roleOdds(tables, ZONE_ROLES[z], { zone: z, star }, roles.bodies).notes) notes.add(n); + warnings.push(...notes); + if (fullRing < 2) warnings.push("Map is too small for orbits — try Medium or Large."); + let mainworld: [number, number] | undefined; + const paths: ProcPath[] = []; + // The sector hex's row says what the mainworld is (its Mainworld: "ocean + // world" → an ocean planet), placed in the habitable zone; that orbit is + // never skipped. + const mainBody = mainworldFor(context?.parent?.terrain, roles.bodies, tables); + const mainRing = mainBody ? first + Math.round(0.45 * (last - first)) : -1; + /** Planets placed (not belts), for the moon guarantee below. */ + const planets: { pos: [number, number]; body: string }[] = []; + let moonCount = 0; + for (let d = first; d <= last; d++) { + if (d !== mainRing && rand() < skip) continue; + const zone = orbitZone(d, first, last); + const pick = d === mainRing ? { terrain: mainBody! } : rollRole(tables, ZONE_ROLES[zone], { rand, zone, ring: d, star }, roles.bodies); + // A (nothing) row: an empty orbit. + if (!pick?.terrain) continue; + const body = pick.terrain; + // Draw the orbit itself: the ring, in order around the star, closed. + if (orbitPathType) { + const around = sortAround(ring(d), center, grid).map((h) => cellKey(h[0], h[1])); + if (around.length > 2) paths.push({ type: orbitPathType, hexes: [...around, around[0]] }); + } + const hexesOnRing = ring(d); + if (hexesOnRing.length === 0) continue; + // A moon from the orbit inside may sit on this ring: leave it be. + const isFree = (h: [number, number]) => cells.get(cellKey(h[0], h[1])) === roles.background; + if (roles.belts.includes(body)) { + // Belts sweep an arc of the ring rather than sitting on one hex. + const start = Math.floor(rand() * hexesOnRing.length); + const span = Math.max(2, Math.floor(hexesOnRing.length * (tuned(options, "beltLength", 0.3) + rand() * tuned(options, "beltSpread", 0.4)))); + const sorted = sortAround(hexesOnRing, center, grid); + for (let i = 0; i < span; i++) { + const h = sorted[(start + i) % sorted.length]; + if (isFree(h)) set(h, body); + } + if (d === mainRing) mainworld = sorted[start]; + continue; + } + const open = hexesOnRing.filter(isFree); + const choices = open.length ? open : hexesOnRing; + const pos = choices[Math.floor(rand() * choices.length)]; + set(pos, body); + planets.push({ pos, body }); + if (d === mainRing) mainworld = pos; + else if (zone === "habitable" && !mainworld && mainRing < 0) mainworld = pos; + // Moons sit on free hexes next to their planet, as many as the Moons + // table says for the planet's type (shipped: giants often one or two, + // rocky worlds sometimes one). + if (roles.moon) { + const rolled = rollRoleValue(tables, "moons", { rand, type: bodyType.get(body), zone, ring: d, star }); + let moons = readCount(rolled) ?? 0; + if (rolled && readCount(rolled) === undefined) notes.add(`Moons: "${rolled.value}" isn't a number of moons, so none.`); + const free = hexes.filter((h) => distance(h, pos, grid) === 1 && isFree(h)); + for (; moons > 0 && free.length; moons--) { + set(free.splice(Math.floor(rand() * free.length), 1)[0], roles.moon); + moonCount++; + } + } + } + + // The description promises moons: a system with a planet always gets at + // least one (round 7: a generated system had none), unless the Moons + // table never gives one to any planet here. Giants first, then the other + // planets, in a seeded order; the first with a free neighbour. + const canHaveMoons = (body: string) => roleValueOdds(tables, "moons", { type: bodyType.get(body), star }) + .some((o) => o.odds > 0 && (readCount(o) ?? 0) > 0); + if (roles.moon && moonCount === 0 && planets.length && planets.some((p) => canHaveMoons(p.body))) { + const giants = planets.filter((p) => roles.giants.includes(p.body)); + const pool = giants.length ? giants : planets; + const start = Math.floor(rand() * pool.length); + const tryOrder = [...pool.slice(start), ...pool.slice(0, start), ...planets.filter((p) => !pool.includes(p))]; + for (const { pos } of tryOrder) { + const free = hexes.filter((h) => distance(h, pos, grid) === 1 + && cells.get(cellKey(h[0], h[1])) === roles.background); + if (!free.length) continue; + set(free[Math.floor(rand() * free.length)], roles.moon); + break; + } + } + + // System extras, each on its own Chance: beside the mainworld (or the + // first body if none was habitable), or out past the last orbit. + const anchor = mainworld ?? hexes.find((h) => roles.bodies.includes(cells.get(cellKey(h[0], h[1]))!)); + const isBackground = (h: [number, number]) => cells.get(cellKey(h[0], h[1])) === roles.background; + const spots = { + beside: () => (anchor ? hexes.filter((h) => distance(h, anchor, grid) === 1 && isBackground(h)) : []), + outside: () => hexes.filter((h) => (dist.get(cellKey(h[0], h[1])) ?? 0) > last && isBackground(h)), + }; + for (const extra of rollRoleEach(tables, "system-extras", { rand, star })) { + if (extra.kind === "nothing") continue; + const terrain = terrainOrType(extra.value, terrains); + if (!terrain) { + // A terrain type the palette has no terrain of is skipped quietly (no comets on this palette). + if (!normalizeTerrainType(extra.value)) notes.add(`System extras: "${extra.value}" isn't a terrain or terrain type of this palette, so it isn't placed.`); + continue; + } + const where = extraWhere(extra.attrs); + if (!where) notes.add(`System extras: Where "${extra.attrs.Where ?? ""}" should be beside mainworld or outside; ${terrain} goes outside.`); + const free = spots[where ?? "outside"](); + if (free.length) set(free[Math.floor(rand() * free.length)], terrain); + else if ((where ?? "outside") === "outside" && maxD > last + 1) warnings.push(`No room outside the orbits for ${terrain}.`); + } + for (const n of notes) if (!warnings.includes(n)) warnings.push(n); + + return { cells, paths, warnings }; +} + +/** + * A System extras result as a palette terrain: a terrain of that name (any + * case), else the first terrain of the terrain type it names ("jump point" + * → the palette's jump-point terrain). Undefined when neither. + */ +export function terrainOrType(value: string, terrains: readonly TerrainColor[]): string | undefined { + const v = value.trim().toLowerCase(); + const named = terrains.find((t) => t.name.trim().toLowerCase() === v); + if (named) return named.name; + const type = normalizeTerrainType(value); + return type ? terrains.find((t) => effectiveTerrainType(t) === type)?.name : undefined; +} + +/** Where a System extras row goes: its Where cell (blank: outside); undefined when it can't be read. */ +export function extraWhere(attrs: Record): "beside" | "outside" | undefined { + const raw = Object.entries(attrs).find(([k]) => k.trim().toLowerCase() === "where")?.[1]?.trim().toLowerCase() ?? ""; + if (raw === "" || /\b(?:outside|outer|past|beyond|edge)\b/.test(raw)) return "outside"; + if (/\b(?:mainworld|beside|near|next)\b/.test(raw)) return "beside"; + return undefined; +} + +/** Order hexes on a ring by angle around the centre, so arcs are contiguous. */ +function sortAround(hexes: [number, number][], center: [number, number], grid: ProcGrid): [number, number][] { + const [cx, cy] = hexCenter(center[0], center[1], grid.orientation, grid.stagger); + const angle = (h: [number, number]) => { + const [px, py] = hexCenter(h[0], h[1], grid.orientation, grid.stagger); + return Math.atan2(py - cy, px - cx); + }; + return [...hexes].sort((a, b) => angle(a) - angle(b)); +} + +/** + * The body that should be the system's mainworld: the Mainworld of the + * sector hex's row in the tables ("ocean world" → "ocean planet"), else + * the sector terrain itself; only when it is one of the palette's bodies. + * Data, not names: nothing here knows what an ocean is. + */ +export function mainworldFor(parentTerrain: string | undefined, bodies: string[], tables?: TableSource): string | undefined { + if (!parentTerrain?.trim()) return undefined; + const want = tables?.rowAttrs("sector-hexes", parentTerrain)?.Mainworld?.trim() || parentTerrain.trim(); + return bodies.find((b) => b.toLowerCase() === want.toLowerCase()); +} diff --git a/src/space/roleTablesSection.ts b/src/space/roleTablesSection.ts new file mode 100644 index 00000000..574c87ad --- /dev/null +++ b/src/space/roleTablesSection.ts @@ -0,0 +1,22 @@ +/** + * Map properties, after Generator tables (the core's, src/hex-map/ + * mapTablesForm.ts): "Convert world types to tables…" while a World types + * note isn't converted yet, on maps where Space's roles are listed (a map + * of the Space type, or one with a Space role table set here or above). + * Contributed through the module runtime (mapProperties). + */ + +import type { MapPropertiesSection } from "../modules/types"; +import { SPACE_TABLE_ROLES } from "../modules/space/tableRoles"; + +const SPACE_ROLES = new Set(SPACE_TABLE_ROLES.map((r) => r.id)); + +export const ROLE_TABLES_SECTION: MapPropertiesSection = { + id: "convert-world-types", + render(el, plugin, map, rerender) { + const shown = plugin.contextKinds(map.name).has("space") || Object.keys(plugin.roleTablesFor(map.name)).some((id) => SPACE_ROLES.has(id)); + if (!shown || !plugin.worldTypeStore.list().some((t) => !plugin.worldTypeStore.isConverted(t.name))) return; + const btn = el.createEl("button", { text: "Convert world types to tables…", attr: { title: "Write each world types table as random tables under the tables folder (backed up first; the old notes are kept)" } }); + btn.addEventListener("click", () => void plugin.runModuleCommand("convert-world-types").then(rerender)); + }, +}; diff --git a/src/space/spaceTables.ts b/src/space/spaceTables.ts new file mode 100644 index 00000000..5cf3a888 --- /dev/null +++ b/src/space/spaceTables.ts @@ -0,0 +1,389 @@ +/** + * The space set as random tables (plan-tables-everywhere §4, phase 3). + * + * A World types note converts, once, into ordinary random table notes in + * a tidy tree under the tables folder (T1): + * + * {tables}/space// + * Sector/Charted sector.md what a star system hex is (Star scatter) + * Sector/Unexplored sector.md the same, with some hexes left for arrival + * Sector/Mainworlds.md a system's mainworld, with its map setup + * Sector/Uncharted.md what an uncharted hex turns out to be + * System/Stars.md the star at a system's centre (Orbits) + * System/Inner orbits.md a body per orbit, by zone + * System/Habitable orbits.md + * System/Outer orbits.md + * + * The World types note is kept (T2). It gets a `## Tables` section that + * links each generator role to its table — that list is what the + * generators read from then on, so pointing Sector hexes at Unexplored + * sector is one edit — and the tables embedded below it, so they can be + * rolled from the note. + * + * The converted tables give the same odds as the note did (T4: different + * draws). Rows keep their setup columns (Mainworld, Size, Generator, + * Options, Palette, Base) as row attributes, and their limits as When. + * Weights are scaled to whole numbers where that keeps the odds exact. + * + * Nothing is special-cased by name: every set is built from the note's + * own rows. The Unexplored and Uncharted tables are built the same way + * for every note (their shares are just weights; edit them freely). + * + * Pure: no Obsidian imports. + */ + +import { rangeCellTexts, type RowType } from "../random-tables/randomTable"; +import { formatWhen } from "../random-tables/tableConditions"; +import { ENGINE_ROLES, type RoleId } from "../worldgen/tableRoles"; +import { attrsOf, conditionsOf } from "./worldTypesSource"; +import { ORBIT_ZONES, type OrbitZone, type WorldTypeRow, type WorldTypeTable } from "./worldTypes"; +import { escapeBarePipes, stripTrailingBarePipe } from "../barePipes"; + +/** The subfolder of the tables folder that holds space sets. */ +export const SPACE_TABLES_FOLDER = "space"; + +/** The folder a set named `name` converts into. */ +export function spaceSetFolder(tablesFolder: string, name: string): string { + const base = tablesFolder.replace(/^\/+|\/+$/g, ""); + return `${base ? `${base}/` : ""}${SPACE_TABLES_FOLDER}/${name}`; +} + +/** A table to write. */ +export interface TableSpec { + title: string; + /** Plain text under the title. */ + description: string; + rows?: RowType; + terrainTypes?: readonly string[]; + /** Extra columns after Weight, in order (only those a row fills are written). */ + columns: readonly string[]; + entries: { result: string; link?: string; weight: number; cells?: Record }[]; +} + +const STANDARD_DICE = [2, 3, 4, 6, 8, 10, 12, 20, 100]; +const SCALES = [1, 2, 3, 4, 5, 6, 8, 10, 12, 15, 20, 24, 25, 30, 40, 50, 60, 75, 100, 120, 150, 200, 300, 600, 1000]; +const near = (a: number, b: number) => Math.abs(a - b) < 1e-9; + +/** The smallest multiplier that makes every weight whole (1 when none does). */ +export function wholeScale(weights: readonly number[]): number { + return SCALES.find((n) => weights.every((w) => near(w * n, Math.round(w * n)))) ?? 1; +} + +const fmtWeight = (w: number) => (near(w, Math.round(w)) ? String(Math.round(w)) : String(Math.round(w * 1e6) / 1e6)); +const esc = (s: string) => escapeBarePipes(s.replace(/\r?\n/g, " ")); + +/** A link cell: `[[path\|Name]]` (the escaped pipe keeps the table whole). */ +export function linkCell(path: string): string { + const target = path.replace(/\.md$/i, ""); + const name = target.slice(target.lastIndexOf("/") + 1); + return `[[${target}\\|${name}]]`; +} + +/** A random table note (frontmatter, roller block, title, description, table). */ +export function tableNoteMarkdown(spec: TableSpec): string { + const scale = wholeScale(spec.entries.map((e) => e.weight)); + const entries = spec.entries.map((e) => ({ ...e, weight: e.weight * scale })); + const total = entries.reduce((a, e) => a + e.weight, 0); + const dice = near(total, Math.round(total)) && STANDARD_DICE.includes(Math.round(total)) ? Math.round(total) : 0; + const ranges = dice ? rangeCellTexts(dice, entries.map((e) => ({ result: e.result, weight: e.weight })), "regenerate") : []; + const cols = spec.columns.filter((c) => entries.some((e) => e.cells?.[c])); + const head = [...(dice ? [`d${dice}`] : []), "Result", "Weight", ...cols]; + const lines = [ + "---", + `dice: ${dice}`, + ...(spec.rows ? [`rows: ${spec.rows}`] : []), + ...(spec.terrainTypes?.length ? [`terrain-type: ${spec.terrainTypes.join(", ")}`] : []), + "---", + "", + "```duckmage-roller", + "```", + "", + `# ${spec.title}`, + "", + spec.description, + "", + `| ${head.join(" | ")} |`, + `| ${head.map((h) => (h === "Weight" ? "---:" : "---")).join(" | ")} |`, + ...entries.map((e, i) => { + const cells = [ + ...(dice ? [ranges[i] || "—"] : []), + e.link ? linkCell(e.link) : esc(e.result), + fmtWeight(e.weight), + ...cols.map((c) => esc(e.cells?.[c] ?? "")), + ]; + return `| ${cells.join(" | ")} |`; + }), + "", + ]; + return lines.join("\n"); +} + +// ── converting a World types note ──────────────────────────────────────── + +export interface SpaceSet { + /** The set's folder. */ + folder: string; + /** Notes to write (path → text). Existing notes are never overwritten. */ + files: { path: string; content: string }[]; + /** Each role's table (vault path with .md). */ + roles: Partial>; +} + +export interface ConvertOptions { + /** The tables folder (setting). */ + tablesFolder: string; + /** + * What a "somewhat known" hex of the Unexplored sector shows until + * someone arrives: a terrain of the sector palette whose type is + * star-system (found by type by the caller). Blank: the background. + */ + shownAs?: string; + /** Rows of the note that couldn't be read, as written (copied into the set's notes). */ + unreadable?: readonly string[]; +} + +const SETUP_COLUMNS = ["When", "Mainworld", "Size", "Generator", "Options", "Palette", "Base", "Notes"] as const; +const SECTOR_TYPES = ["world", "gas-giant", "asteroids", "station", "starport", "jump-point", "anomaly"]; +const BODY_TYPES = ["world", "gas-giant", "asteroids"]; +const ZONE_FILE: Record = { inner: "Inner orbits", habitable: "Habitable orbits", outer: "Outer orbits" }; +const ZONE_ROLE: Record = { inner: "inner-orbits", habitable: "habitable-orbits", outer: "outer-orbits" }; + +function worldEntry(r: WorldTypeRow): TableSpec["entries"][number] { + const cells: Record = { ...attrsOf(r) }; + const when = conditionsOf(r); + if (when.length) cells.When = formatWhen(when); + return { result: r.world.trim(), weight: r.weight ?? 1, cells }; +} + +const lc = (s: string) => s.trim().toLowerCase(); + +/** + * A World types table as a space set: the notes to write and each role's + * table. The same odds as the note (worldTypesSource reads it the same + * way). Pure: the caller writes the files. + */ +export function convertWorldTypes(table: WorldTypeTable, opts: ConvertOptions): SpaceSet { + const folder = spaceSetFolder(opts.tablesFolder, table.name); + const path = (rel: string) => `${folder}/${rel}.md`; + const P = { + charted: path("Sector/Charted sector"), + unexplored: path("Sector/Unexplored sector"), + mainworlds: path("Sector/Mainworlds"), + uncharted: path("Sector/Uncharted"), + stars: path("System/Stars"), + }; + const files: SpaceSet["files"] = []; + const roles: SpaceSet["roles"] = {}; + const unreadable = opts.unreadable?.length + ? `\n\nRows of the World types note that couldn't be read, copied as written:\n\n${opts.unreadable.map((l) => ` ${l}`).join("\n")}` + : ""; + + // Mainworlds: the rows for a sector (Map sector or blank). + const sectorRows = table.rows.filter((r) => r.map !== "system" && r.world.trim()); + files.push({ + path: P.mainworlds, + content: tableNoteMarkdown({ + title: "Mainworlds", + description: `A star system's mainworld, and what its own map is made with. Converted from the ${table.name} world types.${unreadable}`, + rows: "terrain", + terrainTypes: BODY_TYPES, + columns: SETUP_COLUMNS, + entries: sectorRows.map(worldEntry), + }), + }); + + // Sector features by their chance, then the systems (as worldTypesSource). + const features: { name: string; weight: number }[] = []; + let left = 1; + for (const f of table.features ?? []) { + const name = f.feature.trim(); + if (!name || !(f.chance > 0)) continue; + const chance = Math.max(0, Math.min(f.chance, left)); + left -= chance; + const same = features.find((x) => lc(x.name) === lc(name)); + if (same) same.weight += chance; + else if (chance > 0) features.push({ name, weight: chance }); + } + const rest = left > 1e-12 ? left : 0; + const featureEntries = features.map((f) => ({ result: f.name, weight: f.weight, cells: { Roll: "now" } })); + + files.push({ + path: P.charted, + content: tableNoteMarkdown({ + title: "Charted sector", + description: "What each star system hex of a sector is: a special hex, or a system typed by its mainworld. Everything is known from the start.", + rows: "terrain", + terrainTypes: SECTOR_TYPES, + columns: [], + entries: [ + ...features.map((f) => ({ result: f.name, weight: f.weight })), + ...(rest ? [{ result: "Mainworlds", link: P.mainworlds, weight: rest }] : []), + ], + }), + }); + roles["sector-hexes"] = P.charted; + + // Unexplored: the systems split charted / somewhat known / uncharted, 2 : 1 : 1. + const shown = opts.shownAs?.trim() ?? ""; + files.push({ + path: P.unexplored, + content: tableNoteMarkdown({ + title: "Unexplored sector", + description: "Like Charted sector, but only half the systems are known. A somewhat known hex shows a system whose world isn't known yet; an uncharted one shows nothing. Both are rolled the first time someone goes there (Roll: on arrival). Change the weights to make the sector more or less known.", + rows: "terrain", + terrainTypes: SECTOR_TYPES, + columns: ["Roll", "Shown as", "Notes"], + entries: [ + ...featureEntries, + ...(rest ? [ + { result: "Mainworlds", link: P.mainworlds, weight: rest / 2, cells: { Roll: "now", Notes: "charted" } }, + { result: "Mainworlds", link: P.mainworlds, weight: rest / 4, cells: { Roll: "on arrival", ...(shown ? { "Shown as": shown } : {}), Notes: "somewhat known: a system is there, its world isn't known" } }, + { result: "Uncharted", link: P.uncharted, weight: rest / 4, cells: { Roll: "on arrival", Notes: "uncharted" } }, + ] : []), + ], + }), + }); + + files.push({ + path: P.uncharted, + content: tableNoteMarkdown({ + title: "Uncharted", + description: "What an uncharted hex turns out to be when someone gets there.", + rows: "terrain", + terrainTypes: SECTOR_TYPES, + columns: ["Notes"], + entries: [ + { result: "Mainworlds", link: P.mainworlds, weight: 6, cells: { Notes: "an ordinary system after all" } }, + ...features.map((f) => ({ result: f.name, weight: 1 })), + { result: "(nothing)", weight: 2, cells: { Notes: "empty space" } }, + ], + }), + }); + + if (table.stars?.length) { + files.push({ + path: P.stars, + content: tableNoteMarkdown({ + title: "Stars", + description: "The star at the centre of a system, when Orbits' Star option is Random.", + rows: "terrain", + terrainTypes: ["star"], + columns: ["Notes"], + entries: table.stars.filter((s) => s.star.trim()).map((s) => ({ result: s.star.trim(), weight: s.weight ?? 1, ...(s.notes ? { cells: { Notes: s.notes } } : {}) })), + }), + }); + roles.star = P.stars; + } + + // Orbits by zone: the rows for a system (Map system or blank) whose Orbit allows the zone. + const systemRows = table.rows.filter((r) => r.map !== "sector" && r.world.trim()); + for (const z of ORBIT_ZONES) { + const p = path(`System/${ZONE_FILE[z]}`); + files.push({ + path: p, + content: tableNoteMarkdown({ + title: ZONE_FILE[z], + description: `The body on each orbit in the ${z} zone of a system, and what its own map is made with.`, + rows: "terrain", + terrainTypes: BODY_TYPES, + columns: SETUP_COLUMNS, + entries: systemRows.filter((r) => !r.zones?.length || r.zones.includes(z)).map(worldEntry), + }), + }); + roles[ZONE_ROLE[z]] = p; + } + return { folder, files, roles }; +} + +// ── the role list in a note (`## Tables`) ─────────────────────────────── + +const TABLES_HEADING = /^##\s+tables\s*$/i; +const roleByName = new Map(ENGINE_ROLES.flatMap((r) => [[lc(r.name), r.id], [r.id, r.id]] as [string, RoleId][])); + +const splitCells = (line: string): string[] => { + const out: string[] = []; + let cur = ""; + let depth = 0; + const s = stripTrailingBarePipe(line.trim().replace(/^\|/, "")); + for (let i = 0; i < s.length; i++) { + if (s[i] === "[" && s[i + 1] === "[") { depth++; cur += "[["; i++; continue; } + if (s[i] === "]" && s[i + 1] === "]" && depth) { depth--; cur += "]]"; i++; continue; } + if (s[i] === "\\" && s[i + 1] === "|") { cur += "|"; i++; continue; } + if (s[i] === "|" && !depth) { out.push(cur.trim()); cur = ""; continue; } + cur += s[i]; + } + out.push(cur.trim()); + return out; +}; + +/** A link cell's target (`[[a/b|c]]` → `a/b`), or the plain text. */ +export function linkTarget(cell: string): string { + const m = /^!?\[\[([^\]|#]+)(?:[#|][^\]]*)?\]\]$/.exec(cell.trim()); + return (m ? m[1] : cell).trim(); +} + +/** + * The `## Tables` section of a note: role → table link target (as written, + * without `.md`). Rows naming no known role are left out. Empty when the + * note has no such section. + */ +export function readRoleTables(content: string): Partial> { + const lines = content.replace(/\r\n?/g, "\n").split("\n"); + const out: Partial> = {}; + const start = lines.findIndex((l) => TABLES_HEADING.test(l.trim())); + if (start < 0) return out; + let i = start + 1; + while (i < lines.length && !lines[i].trim().startsWith("|") && !/^#{1,2}\s/.test(lines[i])) i++; + if (i >= lines.length || !lines[i].trim().startsWith("|")) return out; + const head = splitCells(lines[i]).map(lc); + const rc = head.indexOf("role"), tc = head.indexOf("table"); + if (rc < 0 || tc < 0) return out; + for (let j = i + 1; j < lines.length && lines[j].trim().startsWith("|"); j++) { + const c = splitCells(lines[j]); + const role = roleByName.get(lc(c[rc] ?? "")); + const target = linkTarget(c[tc] ?? ""); + if (role && target && !/^-+:?$/.test(target)) out[role] = target.replace(/\.md$/i, ""); + } + return out; +} + +/** Whether a World types note was converted (it has a role list). */ +export function isConverted(content: string): boolean { + return Object.keys(readRoleTables(content)).length > 0; +} + +/** + * The World types note after converting (T2): a short callout, the + * `## Tables` role list right under the title, the tables embedded so + * they can be rolled here, and `converted-to:` in the frontmatter. Every + * line of the old note stays. Unchanged when it was converted already. + */ +export function markConverted(content: string, set: Pick): string { + if (isConverted(content)) return content; + const eol = content.includes("\r\n") ? "\r\n" : "\n"; + const lines = content.replace(/\r\n?/g, "\n").split("\n"); + // converted-to: in the frontmatter. + if (lines[0]?.trim() === "---") { + const end = lines.indexOf("---", 1); + if (end > 0 && !lines.slice(1, end).some((l) => /^converted-to\s*:/.test(l))) lines.splice(end, 0, `converted-to: ${JSON.stringify(set.folder)}`); + } + const rows = ENGINE_ROLES.filter((r) => set.roles[r.id]).map((r) => `| ${r.name} | ${linkCell(set.roles[r.id]!)} |`); + const embeds = ENGINE_ROLES.filter((r) => set.roles[r.id]).map((r) => `![[${set.roles[r.id]!.replace(/\.md$/i, "")}]]`); + const block = [ + "> [!info] Converted to tables", + `> The space generators roll on the tables linked below (in ${set.folder}). To use another table for a role, change its link. The world types further down are the old copy, kept as they were.`, + "", + "## Tables", + "", + "| Role | Table |", + "| --- | --- |", + ...rows, + "", + ...embeds.flatMap((e) => [e, ""]), + ]; + const fmEnd = lines[0]?.trim() === "---" ? lines.indexOf("---", 1) + 1 : 0; + const h1 = lines.findIndex((l, i) => i >= fmEnd && /^#\s+\S/.test(l)); + const at = h1 >= 0 ? h1 + 1 : fmEnd; + lines.splice(at, 0, "", ...block.slice(0, -1)); + return lines.join(eol); +} diff --git a/src/space/starScatter.ts b/src/space/starScatter.ts new file mode 100644 index 00000000..be6956dd --- /dev/null +++ b/src/space/starScatter.ts @@ -0,0 +1,224 @@ +import { mulberry32 } from "../../packages/hex-wfc/src"; +import { orbitsFits } from "./orbits"; +import { roleOdds, rollRole, type TableSource } from "../worldgen/tableRoles"; +import type { TerrainColor } from "../types"; +import { + cellKey, + distance, + gridKeys, + ofType, + typeIndex, + type ProcGrid, + type ProcOption, + type ProcPath, + type ProcResult, + type TuningDef, + tuned, +} from "../worldgen/procedural/common"; + +/** + * Sector "star scatter": the classic subsector roll. Each hex holds a star + * system with some probability (standard = 50%, the 4+ on 1d6 rule). What + * each system hex is (its mainworld, or a special hex like a station) is + * rolled on the Sector hexes role (tableRoles.ts): the World types table + * when one is given, else equal odds over the palette's world terrains. + * A few nebula / dust patches thin out the systems inside them, and nearby + * systems can be joined by jump routes. + * + * Works on any palette with a background terrain (type void) and at least + * one world (type world / gas-giant / asteroids, or a star-system terrain). + */ + +export const STAR_SCATTER_ID = "procedural:star-scatter"; + +export const STAR_SCATTER_OPTIONS: ProcOption[] = [ + { + key: "density", + label: "System density", + choices: [ + { value: "sparse", label: "Sparse (1 in 3)" }, + { value: "standard", label: "Standard (1 in 2)" }, + { value: "dense", label: "Dense (2 in 3)" }, + { value: "cluster", label: "Cluster (5 in 6)" }, + ], + default: "standard", + }, + { + key: "clouds", + label: "Nebulae", + choices: [ + { value: "none", label: "None" }, + { value: "few", label: "A few" }, + { value: "many", label: "Many" }, + ], + default: "few", + }, + { + key: "routes", + label: "Jump routes", + choices: [ + { value: "none", label: "None" }, + { value: "1", label: "Jump-1 (neighbours)" }, + { value: "2", label: "Jump-2" }, + ], + default: "2", + }, +]; + +const DENSITY: Record = { sparse: 1 / 3, standard: 1 / 2, dense: 2 / 3, cluster: 5 / 6 }; + +/** Star scatter's tuning sliders (setup wizard Advanced). */ +export const STAR_SCATTER_TUNING: readonly TuningDef[] = [ + { key: "density", label: "More systems", help: "Percentage points added to (or taken from) the System density odds.", min: -30, max: 30, step: 5, default: 0 }, + { key: "nebulaAmount", label: "Nebula amount", help: "How many nebulae, times the Nebulae choice. 0 = none.", min: 0, max: 4, step: 0.25, default: 1 }, + { key: "nebulaSize", label: "Nebula size", help: "The smallest nebula radius, in hexes.", min: 0, max: 4, step: 1, default: 1 }, + { key: "nebulaEdge", label: "Nebula edge fill", help: "How much of each nebula's outer ring is filled. Lower gives ragged clouds.", min: 0, max: 1, step: 0.05, default: 0.45 }, + { key: "inNebula", label: "Systems in nebulae", help: "Odds of a system inside a nebula, as a share of the odds outside.", min: 0, max: 1, step: 0.05, default: 0.5 }, +]; + +export interface StarScatterRoles { + background: string; + worlds: string[]; + clouds: string[]; + features: string[]; +} + +/** Feature types that host a system (and so a jump route). */ +const HOSTS_SYSTEM = new Set(["station", "starport", "jump-point"]); + +/** + * Roles by terrain type only: void (background), world / gas-giant / + * asteroids (mainworlds; comets and debris have their own types and are + * left out), nebula (clouds), station / starport / jump point / anomaly + * (features). With no worlds, a star-system (or star) terrain marks the + * systems. Names and categories play no part; untyped terrains are unused. + */ +export function starScatterRoles(terrains: TerrainColor[]): StarScatterRoles | undefined { + const background = ofType(terrains, ["void"])[0]; + let worlds = ofType(terrains, ["world", "gas-giant", "asteroids"]); + if (worlds.length === 0) { + const system = ofType(terrains, ["star-system"])[0] ?? ofType(terrains, ["star"])[0]; + worlds = system ? [system] : []; + } + if (!background || worlds.length === 0) return undefined; + const clouds = ofType(terrains, ["nebula"]); + const features = ofType(terrains, ["station", "starport", "jump-point", "anomaly"]); + return { background, worlds, clouds, features }; +} + +export function starScatterFits(terrains: TerrainColor[]): boolean { + return starScatterRoles(terrains) !== undefined; +} + +export function starScatter( + terrains: TerrainColor[], + grid: ProcGrid, + seed: number, + options: Record = {}, + jumpRouteType?: string, + /** The role tables (World types); none = equal odds over the palette's worlds, said in the warnings. */ + tables?: TableSource, +): ProcResult { + const roles = starScatterRoles(terrains); + if (!roles) { + return { cells: new Map(), paths: [], warnings: ["This palette has no space background or world terrains."] }; + } + const rand = mulberry32(seed); + const types = typeIndex(terrains); + const warnings: string[] = [...roleOdds(tables, "sector-hexes", {}, roles.worlds).notes]; + // Stations host a system (and so a route); black holes and anomalies don't. + const hostsSystem = (t: string) => HOSTS_SYSTEM.has(types.get(t.toLowerCase()) ?? ""); + const isFeature = (t: string) => roles.features.some((f) => f.toLowerCase() === t.toLowerCase()); + const moreSystems = tuned(options, "density", 0); + const density = moreSystems + ? Math.min(1, Math.max(0, (DENSITY[options.density ?? "standard"] ?? 0.5) + moreSystems / 100)) + : DENSITY[options.density ?? "standard"] ?? 0.5; + const nebulaAmount = tuned(options, "nebulaAmount", 1); + const hexes = gridKeys(grid); + const cells = new Map(); + for (const [x, y] of hexes) cells.set(cellKey(x, y), roles.background); + + // Nebula / dust patches: a few blobs grown from random seeds. + const cloudCount = roles.clouds.length === 0 ? 0 + : options.clouds === "none" || nebulaAmount <= 0 ? 0 + : Math.max(1, Math.round((hexes.length / 80) * (options.clouds === "many" ? 2.5 : 1) * nebulaAmount)); + const nebulaSize = Math.round(tuned(options, "nebulaSize", 1)); + const nebulaEdge = tuned(options, "nebulaEdge", 0.45); + const inNebula = tuned(options, "inNebula", 0.5); + const inCloud = new Set(); + for (let c = 0; c < cloudCount; c++) { + const center = hexes[Math.floor(rand() * hexes.length)]; + const radius = nebulaSize + Math.floor(rand() * 2) + (rand() < 0.3 ? 1 : 0); + const terrain = roles.clouds[Math.floor(rand() * roles.clouds.length)]; + for (const h of hexes) { + const d = distance(center, h, grid); + // Ragged edge: the outer ring is only partly filled. + if (d < radius || (d === radius && rand() < nebulaEdge)) { + const k = cellKey(h[0], h[1]); + cells.set(k, terrain); + inCloud.add(k); + } + } + } + + // Systems: one roll per hex; nebulae halve the odds. + const systems: [number, number][] = []; + const arrivals = new Map(); + for (const [x, y] of hexes) { + const k = cellKey(x, y); + const odds = inCloud.has(k) ? density * inNebula : density; + if (rand() >= odds) continue; + const pick = rollRole(tables, "sector-hexes", { rand, deferArrival: true, where: k }, roles.worlds); + // A (nothing) row: empty space after all. + if (!pick || pick.nothing) continue; + if (pick.arrival) { + // Rolled when someone arrives: until then the hex shows its Shown as + // terrain (or stays background), and hosts a system for the routes. + arrivals.set(k, pick.arrival); + if (pick.terrain) cells.set(k, pick.terrain); + systems.push([x, y]); + continue; + } + cells.set(k, pick.terrain); + // A world hosts a system (and so a route); of the rest, only station-like types do. + if (!isFeature(pick.terrain) || hostsSystem(pick.terrain)) systems.push([x, y]); + } + + // Jump routes: each system links to its nearest neighbour within range. + const paths: ProcPath[] = []; + const range = options.routes === "none" ? 0 : Number(options.routes ?? 2) || 0; + if (range > 0 && systems.length > 1) { + if (!jumpRouteType) { + warnings.push("No path type for routes, so none were drawn. Pick one under Path type for routes (or add a path type to the palette)."); + } else { + const seen = new Set(); + for (const a of systems) { + let best: [number, number] | undefined; + let bestD = Infinity; + for (const b of systems) { + if (a === b) continue; + const d = distance(a, b, grid); + if (d <= range && d < bestD) { best = b; bestD = d; } + } + if (!best) continue; + const ka = cellKey(a[0], a[1]), kb = cellKey(best[0], best[1]); + const id = ka < kb ? `${ka}|${kb}` : `${kb}|${ka}`; + if (seen.has(id)) continue; + seen.add(id); + paths.push({ type: jumpRouteType, hexes: [ka, kb] }); + } + } + } + if (systems.length === 0) warnings.push("No systems rolled — try a higher density or another seed."); + return arrivals.size ? { cells, paths, warnings, arrivals } : { cells, paths, warnings }; +} + +/** + * Offer Star scatter on sector-style palettes only. Once terrains are + * typed, a system palette also "fits" (its bodies are world-typed), but + * scattering planets across a star system makes no sense — so a palette + * that Orbits fits (stars + bodies) is a system, not a sector. + */ +export function starScatterOffered(terrains: TerrainColor[]): boolean { + return starScatterFits(terrains) && !orbitsFits(terrains); +} diff --git a/src/space/worldTypePresets.ts b/src/space/worldTypePresets.ts new file mode 100644 index 00000000..d20a25ca --- /dev/null +++ b/src/space/worldTypePresets.ts @@ -0,0 +1,114 @@ +/** + * The shipped "Default space" world types table, as DATA: written into a + * note once (WorldTypeStore), then the note is what counts. Nothing here + * is read at run time except to seed a missing note and for "Restore + * default". + * + * It reproduces, exactly, the world odds Star scatter and Orbits had built + * in (their name tables for the shipped Space palettes) and the shipped + * palettes' submap defaults: + * - sector rows: Star scatter's mainworld weights (garden 3, ocean 2, …), + * each opening as a 13×13 Orbits system on Space - System, with the + * body Orbits makes its mainworld (the pairing Orbits used to guess + * from the names, now written down as data); + * - system rows: Orbits' zone weights per body (a body a zone didn't list + * weighed 0.5 there), the rocky ones opening as 20×14 Planet surface + * maps tuned to the planet; + * - the moon (weight 0: Orbits puts moons beside planets, it never rolls + * them) for its map setup; + * - Stars: Orbits' random star weights (red dwarfs dominate); + * - Sector features: Star scatter's special hexes, 1 in 25 star system + * hexes split 3 : 2 : 1 between station, anomaly and black hole. + * tests/worldTypes.test.ts holds a frozen copy of the old tables and + * checks this against it. + * + * Pure: no Obsidian imports. + */ + +import type { OrbitZone, SectorFeatureRow, StarTypeRow, WorldTypeRow } from "./worldTypes"; + +const SYSTEM_PALETTE = "Space - System"; +const SURFACE_PALETTE = "Space - Planet"; + +const system = (world: string, weight: number, mainworld: string): WorldTypeRow => ({ + world, + weight, + map: "sector", + mainworld, + size: { cols: { lo: 13, hi: 13 }, rows: { lo: 13, hi: 13 } }, + generator: { id: "procedural:orbits" }, + palette: SYSTEM_PALETTE, + baseTerrain: "void", +}); + +type Surface = Pick; +const surface = (water: string, climate: string, base: string, relief = "normal"): Surface => ({ + size: { cols: { lo: 20, hi: 20 }, rows: { lo: 14, hi: 14 } }, + generator: { id: "procedural:planet-surface" }, + options: { water, climate, relief }, + palette: SURFACE_PALETTE, + baseTerrain: base, +}); + +/** One body's rows: its weight per zone (zones with the same weight share a row). */ +function body(world: string, w: Record, setup: Surface = {}): WorldTypeRow[] { + const zones: OrbitZone[] = ["inner", "habitable", "outer"]; + const out: WorldTypeRow[] = []; + const done = new Set(); + for (const z of zones) { + if (done.has(z)) continue; + const same = zones.filter((o) => !done.has(o) && w[o] === w[z]); + same.forEach((o) => done.add(o)); + out.push({ world, weight: w[z], map: "system", zones: same, ...setup }); + } + return out; +} + +export const DEFAULT_WORLD_TYPE_ROWS: readonly WorldTypeRow[] = [ + // Sector: a hex's star system, typed by its mainworld (Star scatter). + system("garden world", 3, "terrestrial planet"), + system("ocean world", 2, "ocean planet"), + system("desert world", 3, "desert planet"), + system("ice world", 2, "ice planet"), + system("barren world", 3.5, "rocky planet"), + system("molten world", 1, "molten planet"), + system("asteroid belt", 1.5, "asteroid belt"), + system("gas giant", 1, "gas giant"), + // System: one body per orbit, by zone (Orbits). + ...body("terrestrial planet", { inner: 0.5, habitable: 4, outer: 0.5 }, surface("65", "temperate", "ocean")), + ...body("ocean planet", { inner: 0.5, habitable: 3, outer: 0.5 }, surface("85", "lush", "ocean")), + ...body("desert planet", { inner: 2, habitable: 3, outer: 0.5 }, surface("10", "arid", "dunes")), + ...body("ice planet", { inner: 0.5, habitable: 0.5, outer: 3 }, surface("30", "frozen", "ocean")), + ...body("rocky planet", { inner: 4, habitable: 2, outer: 1 }, surface("10", "arid", "regolith", "rugged")), + ...body("molten planet", { inner: 4, habitable: 0.5, outer: 0.5 }, surface("10", "volcanic", "regolith", "rugged")), + ...body("gas giant", { inner: 0.5, habitable: 0.5, outer: 4 }), + ...body("ice giant", { inner: 0.5, habitable: 0.5, outer: 3 }), + ...body("asteroid belt", { inner: 0.5, habitable: 1, outer: 1.5 }), + { world: "moon", weight: 0, map: "system", ...surface("10", "frozen", "regolith", "rugged"), notes: "placed beside planets, never rolled" }, +]; + +/** Orbits' random star (its old built-in weights). */ +export const DEFAULT_STAR_ROWS: readonly StarTypeRow[] = [ + { star: "red dwarf", weight: 6 }, + { star: "yellow star", weight: 3 }, + { star: "brown dwarf", weight: 1.5 }, + { star: "white dwarf", weight: 1 }, + { star: "blue giant", weight: 0.5 }, +]; + +/** + * Star scatter's special hexes: it made 4% (1 in 25) of star system hexes + * a feature, split 3 : 2 : 1 by weight. As chances per hex that is exactly + * 1 in 50, 1 in 75 and 1 in 150. + */ +export const DEFAULT_SECTOR_FEATURE_ROWS: readonly SectorFeatureRow[] = [ + { feature: "deep-space station", chance: 1 / 50 }, + { feature: "anomaly", chance: 1 / 75 }, + { feature: "black hole", chance: 1 / 150 }, +]; + +/** The shipped Stars and Sector features tables, together. */ +export const DEFAULT_WORLD_TYPE_EXTRAS = { + get stars(): StarTypeRow[] { return DEFAULT_STAR_ROWS.map((r) => ({ ...r })); }, + get features(): SectorFeatureRow[] { return DEFAULT_SECTOR_FEATURE_ROWS.map((r) => ({ ...r })); }, +}; diff --git a/src/space/worldTypes.ts b/src/space/worldTypes.ts new file mode 100644 index 00000000..1a6f3ec3 --- /dev/null +++ b/src/space/worldTypes.ts @@ -0,0 +1,1075 @@ +/** + * World types: which worlds space generators place, how often, and what a + * world's own map (its submap) is made with. One plain note per table at + * `/.md`: + * + * --- + * hexmaker-world-types: 1 + * --- + * + * # Default space + * + * > [!info] World types + * > … (short help) + * + * | World | Weight | Map | Orbit | Stars | Temperature | Size | Generator | Options | Palette | Base | Notes | + * | --- | ---: | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | + * | ocean planet | 3 | system | habitable | | | 20×14 | procedural:planet-surface | water=85, climate=lush | Space - Planet | ocean | | + * + * - *World*: the terrain the row places (matched to the palette's terrain + * names, any case). The same world may have several rows (different + * odds, sizes or generators per zone, star or temperature). + * - *Weight* (blank = 1): relative odds among the rows that fit. 0 = never + * rolled (the row still gives that world's map setup). + * - Filters, each optional (blank or "any" = no limit). A filter only + * applies when the generator knows that thing: + * *Map* `sector` (a sector's star systems: Star scatter) or `system` + * (an orbit around a star: Orbits); *Orbit* zone words `inner`, + * `habitable`, `outer` and/or ring distances like `2–4` (hexes from the + * star); *Stars* a list of star terrains (`red dwarf, white dwarf`); + * *Temperature* cold, cool, mild, warm, hot or 0.2–0.5 (as on biomes). + * - Map setup for the world's submap, each optional: *Size* `20×14` or a + * range `16–24 × 10–14` (rolled per world); *Generator* a generator note + * link (`[[My desert]]`), a generator id (`procedural:planet-surface`, + * `wfc:`, `builtin:`) or a shipped generator's slug + * (`preset-volcanic`); *Options* the generator's choices + * (`water=85, climate=lush`); *Palette* and *Base* (base terrain). + * - *Notes*: free text, kept as written. + * + * Reading is forgiving: columns by header name in any order, missing + * columns are fine, en dash / hyphen / "to" in ranges, × / x / "by" in + * sizes, weights like `2` or `50%`. A row that can't be read is never + * used, is reported, and stays in the note exactly as written (rewriting + * keeps it, after the rows the plugin wrote). + * + * Picking (pickWorldType) is deterministic for a seed and works like the + * generators' weighted pick: one draw over the fitting worlds, in palette + * order when a palette is given, so the shipped "Default space" table + * gives exactly the odds (and, for the same random stream, the same + * choices) Star scatter and Orbits had built in. + * + * Two more tables follow in the same note, each under its own heading + * (format 2; found by their header, so the heading is only for people): + * + * ## Stars + * | Star | Weight | Notes | + * | red dwarf | 6 | | + * + * ## Sector features + * | Feature | Chance | Notes | + * | deep-space station | 1 in 50 | | + * + * - *Stars*: which star Orbits puts at a system's centre (when its Star + * option is Random), by weight. pickStar. + * - *Sector features*: Star scatter's special hexes. Each star system hex + * has the row's *Chance* (`1 in 50`, `2%`, `0.02`) of being that feature + * instead of a system. pickSectorFeature. + * A format 1 note (no such tables yet) is given the shipped rows once + * (upgradeWorldTypes); after that a deleted table stays deleted. + * + * Pure: no Obsidian imports. + */ + +import { mulberry32 } from "../../packages/hex-wfc/src/rng"; +import { + TEMPERATURE_WORDS, + formatClimateRange, + inClimateRange, + parseClimateRange, + type ClimateRange, +} from "../overworld/biomeClimate"; +import { pathLink, refBasename } from "../noteFormats"; +import { + generatorRefId, + readGenerator, + readIntRange, + readOptions, + readSize, + type IntRange, + type WorldGeneratorRef, + type WorldSizeRange, +} from "../worldgen/cellReaders"; +import { ORBIT_ZONES, orbitZone, readOrbit, type OrbitZone } from "../modules/space/orbitZones"; +import { SEPARATOR_ROW, splitLinkRow as splitRow } from "../md/tableRow"; + +export { generatorRefId, readGenerator, readIntRange, readOptions, readSize, ORBIT_ZONES, orbitZone, readOrbit }; +export type { IntRange, OrbitZone, WorldGeneratorRef, WorldSizeRange }; + +export const WORLD_TYPES_MARKER = "hexmaker-world-types"; +/** 2: the note also has the Stars and Sector features tables. 3: a Mainworld column. */ +export const WORLD_TYPES_FORMAT = 3; +/** The shipped table's name (and note name). */ +export const DEFAULT_WORLD_TYPES = "Default space"; + + +/** Which kind of space map picks: a sector's systems, or a system's orbits. */ +export type WorldTypeMap = "sector" | "system"; + +export interface WorldTypeRow { + /** The terrain this row places, as written ("ocean planet"). */ + world: string; + /** Relative odds among the fitting rows; default 1; 0 = never rolled. */ + weight?: number; + /** Only on this kind of map. Unset: any. */ + map?: WorldTypeMap; + /** Only in these orbit zones. Unset: any. */ + zones?: OrbitZone[]; + /** Only this many hexes from the star (inclusive). Unset: any. */ + distance?: IntRange; + /** Only around these stars (terrain names, as written). Unset: any. */ + stars?: string[]; + /** Only at this temperature (0 cold … 1 hot). Unset: any. */ + temperature?: ClimateRange; + /** + * A sector world's mainworld: the body Orbits makes that system's + * mainworld ("ocean world" → "ocean planet"). Unset: the world itself, + * when the system palette has it. + */ + mainworld?: string; + /** The world's submap size. Unset: no preference. */ + size?: WorldSizeRange; + /** The world's submap generator. Unset: no preference. */ + generator?: WorldGeneratorRef; + /** The generator's options (`water` → `85`). */ + options?: Record; + /** The submap's palette. */ + palette?: string; + /** The submap's base terrain. */ + baseTerrain?: string; + notes?: string; +} + +/** A row of the Stars table: a star terrain and its odds. */ +export interface StarTypeRow { + /** The star terrain, as written ("red dwarf"). */ + star: string; + /** Relative odds among the stars; default 1; 0 = never rolled. */ + weight?: number; + notes?: string; +} + +/** A row of the Sector features table: a special hex and its chance per star system hex. */ +export interface SectorFeatureRow { + /** The feature terrain, as written ("black hole"). */ + feature: string; + /** Chance (0..1) that a star system hex is this feature instead. */ + chance: number; + notes?: string; +} + +export interface WorldTypeTable { + name: string; + rows: WorldTypeRow[]; + /** The Stars table (none = the note has none). */ + stars?: StarTypeRow[]; + /** The Sector features table (none = the note has none). */ + features?: SectorFeatureRow[]; +} + +export interface WorldTypeProblem { + /** 1-based line in the note, when it's a row. */ + line?: number; + text: string; +} + +export interface ParsedWorldTypes { + rows: WorldTypeRow[]; + problems: WorldTypeProblem[]; + /** Table rows that couldn't be read, exactly as written (kept on rewrite). */ + unreadable: string[]; + /** The Stars table's rows; undefined when the note has no Stars table. */ + stars?: StarTypeRow[]; + /** The Sector features table's rows; undefined when the note has none. */ + features?: SectorFeatureRow[]; + unreadableStars: string[]; + unreadableFeatures: string[]; + /** The `hexmaker-world-types:` number in the frontmatter, if any. */ + format?: number; +} + +/** What the generator knows where it is placing a world. Every field but `seed` is optional. */ +export interface WorldTypeContext { + map?: WorldTypeMap; + zone?: OrbitZone; + /** Hexes from the star (the orbit's ring). */ + distance?: number; + /** The system's star terrain. */ + starType?: string; + /** 0 (cold) … 1 (hot). */ + temperature?: number; + seed: number; + /** + * The generator's own random stream. When given, the pick takes exactly + * one draw from it (like weightedPick), so a generator's later rolls are + * unchanged; sizes and ties between rows use a stream made from `seed`. + */ + rand?: () => number; + /** + * The palette's terrains (names, or terrains with a name): only rows + * whose world is in it are picked, and the pick runs over them in + * palette order (the generators' order). + */ + palette?: readonly (string | { name: string })[]; +} + +export interface WorldTypePick { + row: WorldTypeRow; + /** The palette's own name for the world (its case), else the row's. */ + terrain: string; + /** Rolled from the row's size range; unset when the row has none. */ + size?: { cols: number; rows: number }; + generator?: WorldGeneratorRef; + options?: Record; + palette?: string; + baseTerrain?: string; +} + +// ── zones ──────────────────────────────────────────────────────────────── + +// ── matching and picking ───────────────────────────────────────────────── + +const lc = (s: string) => s.trim().toLowerCase(); + +/** Whether a row's filters allow this context (filters the context doesn't speak to pass). */ +export function worldTypeFits(row: WorldTypeRow, ctx: Omit & { seed?: number }): boolean { + if (row.map && ctx.map && row.map !== ctx.map) return false; + if (row.zones?.length && ctx.zone && !row.zones.includes(ctx.zone)) return false; + if (row.distance && ctx.distance !== undefined && (ctx.distance < row.distance.lo || ctx.distance > row.distance.hi)) return false; + if (row.stars?.length && ctx.starType && !row.stars.some((s) => lc(s) === lc(ctx.starType!))) return false; + if (row.temperature && ctx.temperature !== undefined && !inClimateRange(row.temperature, ctx.temperature)) return false; + return true; +} + +const paletteNames = (p: WorldTypeContext["palette"]) => p?.map((t) => (typeof t === "string" ? t : t.name)); + +/** + * The rows that fit the context (weight > 0), in pick order: palette order + * of their world when a palette is given (rows of worlds not in it left + * out), else table order. + */ +export function matchingWorldTypes(table: WorldTypeTable, ctx: Omit & { seed?: number }): WorldTypeRow[] { + const fit = table.rows.filter((r) => (r.weight ?? 1) > 0 && r.world.trim() && worldTypeFits(r, ctx)); + const names = paletteNames(ctx.palette); + if (!names) return fit; + const order = new Map(); + names.forEach((n, i) => { if (!order.has(lc(n))) order.set(lc(n), i); }); + return fit + .filter((r) => order.has(lc(r.world))) + .map((r, i) => ({ r, i })) + .sort((a, b) => order.get(lc(a.r.world))! - order.get(lc(b.r.world))! || a.i - b.i) + .map((x) => x.r); +} + +/** + * Each fitting world's total weight (lower-case name → weight), for a + * generator that mixes the table with its own weights for terrains the + * table doesn't name. + */ +export function worldTypeWeights(table: WorldTypeTable, ctx: Omit & { seed?: number }): Record { + const out: Record = {}; + for (const r of matchingWorldTypes(table, ctx)) out[lc(r.world)] = (out[lc(r.world)] ?? 0) + (r.weight ?? 1); + return out; +} + +/** Weighted pick of an index, the generators' way (one draw). */ +function pickIndex(rand: () => number, weights: number[]): number { + const total = weights.reduce((a, b) => a + b, 0); + if (total <= 0) return Math.floor(rand() * weights.length); + let r = rand() * total; + for (let i = 0; i < weights.length; i++) { + r -= weights[i]; + if (r < 0) return i; + } + return weights.length - 1; +} + +const rollInt = (rand: () => number, r: IntRange) => r.lo + Math.floor(rand() * (r.hi - r.lo + 1)); + +/** + * Pick a world for the context: one weighted draw over the fitting worlds + * (a world's rows add up), then, when that world has several fitting rows, + * one of them by weight, and its size within its range. Null when nothing + * fits. Deterministic for a seed (or for the given random stream). + */ +export function pickWorldType(table: WorldTypeTable, ctx: WorldTypeContext): WorldTypePick | null { + const rows = matchingWorldTypes(table, ctx); + if (!rows.length) return null; + const worlds: string[] = []; + const weight = new Map(); + for (const r of rows) { + const k = lc(r.world); + if (!weight.has(k)) worlds.push(k); + weight.set(k, (weight.get(k) ?? 0) + (r.weight ?? 1)); + } + const rand = ctx.rand ?? mulberry32(ctx.seed >>> 0); + const world = worlds[pickIndex(rand, worlds.map((k) => weight.get(k)!))]; + // Its own stream, so the caller's stream sees exactly one draw. + const side = mulberry32(((ctx.seed ^ 0x51e3d7a1) >>> 0)); + const own = rows.filter((r) => lc(r.world) === world); + const row = own.length === 1 ? own[0] : own[pickIndex(side, own.map((r) => r.weight ?? 1))]; + const names = paletteNames(ctx.palette); + const out: WorldTypePick = { row, terrain: names?.find((n) => lc(n) === world) ?? row.world.trim() }; + if (row.size) out.size = { cols: rollInt(side, row.size.cols), rows: rollInt(side, row.size.rows) }; + if (row.generator) out.generator = { ...row.generator }; + if (row.options) out.options = { ...row.options }; + if (row.palette) out.palette = row.palette; + if (row.baseTerrain) out.baseTerrain = row.baseTerrain; + return out; +} + +/** + * The row giving a world's map setup (for a submap made from a hex of that + * world): the first row naming it that fits the context, weight 0 rows + * included. + */ +export function worldTypeFor(table: WorldTypeTable, world: string, ctx: Omit & { seed?: number } = {}): WorldTypeRow | undefined { + return table.rows.find((r) => lc(r.world) === lc(world) && worldTypeFits(r, ctx)); +} + +/** A row's map setup in the palette's submap-default shape (types.ts SubmapDefault). */ +export function worldTypeSubmapDefault(row: WorldTypeRow, size?: { cols: number; rows: number }): { + palette?: string; cols?: number; rows?: number; generator?: string; options?: Record; baseTerrain?: string; +} { + const out: ReturnType = {}; + if (row.palette) out.palette = row.palette; + const s = size ?? (row.size ? { cols: row.size.cols.lo, rows: row.size.rows.lo } : undefined); + if (s) { out.cols = s.cols; out.rows = s.rows; } + if (row.generator) out.generator = generatorRefId(row.generator); + if (row.options && Object.keys(row.options).length) out.options = { ...row.options }; + if (row.baseTerrain) out.baseTerrain = row.baseTerrain; + return out; +} + +// ── stars and sector features ──────────────────────────────────────────── + +/** What a generator passes when picking a star or a sector feature. */ +export interface SpacePickContext { + seed: number; + /** + * The generator's own random stream. pickStar takes exactly one draw + * from it when it returns a star (none when nothing fits); + * pickSectorFeature always takes exactly one. + */ + rand?: () => number; + /** + * The palette's terrains (names, or terrains with a name): only rows + * naming one of them count, in palette order. + */ + palette?: readonly (string | { name: string })[]; +} + +/** + * Rows grouped by name (a name's rows add up), in palette order when a + * palette is given (names not in it left out), else table order. Each + * group keeps its first row and the palette's spelling of the name. + */ +function groupByName( + rows: readonly R[], + nameOf: (r: R) => string, + amountOf: (r: R) => number, + palette: SpacePickContext["palette"], +): { key: string; terrain: string; row: R; amount: number }[] { + const groups = new Map(); + for (const r of rows) { + const name = nameOf(r).trim(); + const amount = amountOf(r); + if (!name || !(amount > 0)) continue; + const k = lc(name); + const g = groups.get(k); + if (g) g.amount += amount; + else groups.set(k, { key: k, terrain: name, row: r, amount }); + } + const names = paletteNames(palette); + if (!names) return [...groups.values()]; + const out: { key: string; terrain: string; row: R; amount: number }[] = []; + const seen = new Set(); + for (const n of names) { + const g = groups.get(lc(n)); + if (!g || seen.has(g.key)) continue; + seen.add(g.key); + out.push({ ...g, terrain: n }); + } + return out; +} + +const starGroups = (table: WorldTypeTable, palette?: SpacePickContext["palette"]) => + groupByName(table.stars ?? [], (r) => r.star, (r) => r.weight ?? 1, palette); +const featureGroups = (table: WorldTypeTable, palette?: SpacePickContext["palette"]) => + groupByName(table.features ?? [], (r) => r.feature, (r) => r.chance, palette); + +export interface StarPick { + row: StarTypeRow; + /** The palette's own name for the star (its case), else the row's. */ + terrain: string; +} + +export interface SectorFeaturePick { + row: SectorFeatureRow; + /** The palette's own name for the feature (its case), else the row's. */ + terrain: string; +} + +/** Each star's total weight (lower-case name → weight), weight 0 left out. */ +export function starWeights(table: WorldTypeTable, ctx: Omit & { seed?: number } = {}): Record { + return Object.fromEntries(starGroups(table, ctx.palette).map((g) => [g.key, g.amount])); +} + +/** + * Pick the star at a system's centre: one weighted draw over the stars + * (in palette order when a palette is given). Null when no star row fits; + * then no draw is taken, so a generator can fall back to its own pick. + */ +export function pickStar(table: WorldTypeTable, ctx: SpacePickContext): StarPick | null { + const groups = starGroups(table, ctx.palette); + if (!groups.length) return null; + const rand = ctx.rand ?? mulberry32(ctx.seed >>> 0); + const g = groups[pickIndex(rand, groups.map((x) => x.amount))]; + return { row: g.row, terrain: g.terrain }; +} + +/** Each star's exact odds (0..1), most likely first. */ +export function starOdds(table: WorldTypeTable, ctx: Omit = {}): { star: string; odds: number }[] { + const groups = starGroups(table, ctx.palette); + const total = groups.reduce((a, g) => a + g.amount, 0); + if (total <= 0) return []; + return groups.map((g) => ({ star: g.terrain, odds: g.amount / total })).sort((a, b) => b.odds - a.odds || a.star.localeCompare(b.star)); +} + +/** Roll `n` stars (seeds `seed`, `seed + 1`, …) and count them, most rolled first. */ +export function rollStars(table: WorldTypeTable, ctx: Omit, n: number, seed = 1): { star: string; count: number }[] { + const counts = new Map(); + for (let i = 0; i < n; i++) { + const p = pickStar(table, { ...ctx, seed: seed + i }); + if (p) counts.set(p.terrain, (counts.get(p.terrain) ?? 0) + 1); + } + return [...counts].map(([star, count]) => ({ star, count })).sort((a, b) => b.count - a.count || a.star.localeCompare(b.star)); +} + +/** Each feature's chance per star system hex (lower-case name → 0..1), chance 0 left out. */ +export function sectorFeatureChances(table: WorldTypeTable, ctx: Omit & { seed?: number } = {}): Record { + return Object.fromEntries(featureGroups(table, ctx.palette).map((g) => [g.key, g.amount])); +} + +/** + * Whether a star system hex is a special feature instead, and which: + * exactly one draw `u`; the features (in palette order when a palette is + * given) take consecutive slices of 0..1 as wide as their chance, so `u` + * below the total chance lands on a feature, anything else is null (an + * ordinary system). The draw is taken even when no feature fits, so the + * generator's later rolls don't depend on the palette. + */ +export function pickSectorFeature(table: WorldTypeTable, ctx: SpacePickContext): SectorFeaturePick | null { + const rand = ctx.rand ?? mulberry32(ctx.seed >>> 0); + const u = rand(); + let edge = 0; + for (const g of featureGroups(table, ctx.palette)) { + edge += g.amount; + if (u < edge) return { row: g.row, terrain: g.terrain }; + } + return null; +} + +/** Each feature's chance per star system hex, most likely first, and their total (capped at 1). */ +export function sectorFeatureOdds(table: WorldTypeTable, ctx: Omit = {}): { features: { feature: string; chance: number }[]; total: number } { + const groups = featureGroups(table, ctx.palette); + let left = 1; + const features = groups.map((g) => { + const chance = Math.max(0, Math.min(g.amount, left)); + left -= chance; + return { feature: g.terrain, chance }; + }).filter((f) => f.chance > 0); + return { + features: features.sort((a, b) => b.chance - a.chance || a.feature.localeCompare(b.feature)), + total: features.reduce((a, f) => a + f.chance, 0), + }; +} + +/** Roll `n` star system hexes (seeds `seed`, `seed + 1`, …): how many became each feature, most first. */ +export function rollSectorFeatures(table: WorldTypeTable, ctx: Omit, n: number, seed = 1): { feature: string; count: number }[] { + const counts = new Map(); + for (let i = 0; i < n; i++) { + const p = pickSectorFeature(table, { ...ctx, seed: seed + i }); + if (p) counts.set(p.terrain, (counts.get(p.terrain) ?? 0) + 1); + } + return [...counts].map(([feature, count]) => ({ feature, count })).sort((a, b) => b.count - a.count || a.feature.localeCompare(b.feature)); +} + +// ── cells ──────────────────────────────────────────────────────────────── + +/** "2", "50%", "0.5" → a weight ≥ 0, or NaN. */ +export function readWeight(raw: string): number { + const t = raw.trim(); + const pct = t.endsWith("%"); + const n = Number(t.replace(/%$/, "").trim()); + if (!t || !Number.isFinite(n) || n < 0) return NaN; + return pct ? n / 100 : n; +} + +const fmtInt = (r: IntRange) => (r.lo === r.hi ? String(r.lo) : `${r.lo}–${r.hi}`); +export const formatSize = (s: WorldSizeRange) => `${fmtInt(s.cols)}×${fmtInt(s.rows)}`; + +export function formatOrbit(row: Pick): string { + const parts: string[] = [...(row.zones ?? [])]; + if (row.distance) parts.push(fmtInt(row.distance)); + return parts.join(", "); +} + +/** "sector", "systems", "any", "" → the map kind (undefined = any); null when unreadable. */ +export function readMap(raw: string): WorldTypeMap | undefined | null { + const t = raw.trim().toLowerCase().replace(/s$/, ""); + if (!t || t === "any" || t === "both") return undefined; + if (t === "sector") return "sector"; + if (t === "system" || t === "star system" || t === "orbit") return "system"; + return null; +} + +export function formatGenerator(g: WorldGeneratorRef | undefined): string { + if (!g) return ""; + if ("path" in g) return `[[${g.path}]]`; + if ("id" in g) return g.id; + return g.builtin; +} + +export const formatOptions = (o: Record | undefined) => + o ? Object.entries(o).map(([k, v]) => `${k}=${v}`).join(", ") : ""; + +/** + * A chance per star system hex: "1 in 50", "1/50", "2%", "0.02", "never" + * or "0" → 0..1; NaN when unreadable (blank, over 100%, a bare number + * above 1, or "0 in 5"). + */ +export function readChance(raw: string): number { + const t = raw.trim().toLowerCase(); + if (!t) return NaN; + if (t === "never" || t === "none") return 0; + const inN = /^(\d+(?:\.\d+)?)\s*(?:in|\/|out of)\s*(\d+(?:\.\d+)?)$/.exec(t); + if (inN) { + const a = Number(inN[1]), b = Number(inN[2]); + return b > 0 && a <= b ? a / b : NaN; + } + const pct = t.endsWith("%"); + const n = Number(t.replace(/%$/, "").trim()); + if (!Number.isFinite(n) || n < 0) return NaN; + const c = pct ? n / 100 : n; + return c <= 1 ? c : NaN; +} + +/** 1/50 → "1 in 50", 0.03 → "3%", 0 → "never". */ +export function formatChance(c: number): string { + if (!(c > 0)) return "never"; + if (c >= 1) return "100%"; + const inv = 1 / c; + const n = Math.round(inv); + if (n >= 2 && Math.abs(inv - n) < 1e-9 * n) return `1 in ${n}`; + return `${String(Math.round(c * 100 * 1000) / 1000)}%`; +} + +const readList = (raw: string) => { + const t = raw.trim(); + if (!t || t.toLowerCase() === "any") return []; + return t.split(/\s*[,;]\s*/).map((s) => s.trim()).filter((s) => s !== ""); +}; + +// ── the note ───────────────────────────────────────────────────────────── + +export const WORLD_TYPES_HELP = [ + "> [!info] World types", + "> Which worlds the space generators place and how often, and what each world's own map is made with. **World** is a terrain of the palette. **Weight** (1 if blank) is its odds against the other rows that fit; 0 never rolls it. Limits, all optional: **Map** sector (Star scatter's systems) or system (Orbits), **Orbit** inner, habitable, outer or rings like 2–4, **Stars** a list of star terrains, **Temperature** cold, cool, mild, warm, hot or 0.2–0.5. For the world's map: **Mainworld** (sector worlds) the body that is that system's mainworld, **Size** like 20×14 or 16–24 × 10–14, **Generator** a generator note link or id, **Options** like water=85, climate=lush, **Palette** and **Base** terrain. The same world can have several rows. Add, edit or delete rows freely.", +]; + +/** The note table's columns, in order (the editor keeps each row as these cells). */ +export const WORLD_TYPE_COLUMNS = ["World", "Weight", "Map", "Orbit", "Stars", "Temperature", "Mainworld", "Size", "Generator", "Options", "Palette", "Base", "Notes"] as const; +export type WorldTypeColumn = (typeof WORLD_TYPE_COLUMNS)[number]; +type Column = WorldTypeColumn; +const COLUMNS = WORLD_TYPE_COLUMNS; +const HEADER_ALIASES: Record = { + world: "World", worlds: "World", "world type": "World", type: "World", body: "World", terrain: "World", + weight: "Weight", odds: "Weight", chance: "Weight", + map: "Map", scale: "Map", + orbit: "Orbit", zone: "Orbit", orbits: "Orbit", "orbit zone": "Orbit", + stars: "Stars", star: "Stars", "star types": "Stars", + temperature: "Temperature", temp: "Temperature", + mainworld: "Mainworld", "main world": "Mainworld", mainworlds: "Mainworld", + size: "Size", + generator: "Generator", preset: "Generator", + options: "Options", + palette: "Palette", + base: "Base", "base terrain": "Base", + notes: "Notes", note: "Notes", comment: "Notes", +}; + +export const STARS_HEADING = "## Stars"; +export const STARS_HELP = [ + "> [!info] Stars", + "> Which star Orbits puts at the centre of a system when its Star option is Random. **Star** is a star terrain of the palette; **Weight** (1 if blank) is its odds against the other stars; 0 never rolls it.", +]; +export const FEATURES_HEADING = "## Sector features"; +export const FEATURES_HELP = [ + "> [!info] Sector features", + "> Star scatter's special hexes. **Feature** is a terrain of the palette; **Chance** is how likely each star system hex is to be that feature instead, like 1 in 50, 2% or never.", +]; + +/** The Stars table's columns, in order. */ +export const STAR_COLUMNS = ["Star", "Weight", "Notes"] as const; +export type StarColumn = (typeof STAR_COLUMNS)[number]; +const STAR_ALIASES: Record = { + star: "Star", stars: "Star", "star type": "Star", "star types": "Star", sun: "Star", + weight: "Weight", odds: "Weight", + notes: "Notes", note: "Notes", comment: "Notes", +}; + +/** The Sector features table's columns, in order. */ +export const FEATURE_COLUMNS = ["Feature", "Chance", "Notes"] as const; +export type FeatureColumn = (typeof FEATURE_COLUMNS)[number]; +const FEATURE_ALIASES: Record = { + feature: "Feature", features: "Feature", "sector feature": "Feature", "sector features": "Feature", special: "Feature", "special hex": "Feature", + chance: "Chance", odds: "Chance", "chance per system": "Chance", "per system": "Chance", "chance per system hex": "Chance", + notes: "Notes", note: "Notes", comment: "Notes", +}; + +const normHeader = (h: string) => h.trim().toLowerCase().replace(/[*_]/g, "").replace(/\s+/g, " "); + +interface Span { start: number; end: number; cols: (C | undefined)[] } + +type TableKind = "worlds" | "stars" | "features"; + +/** + * The note's first table of a kind, told apart by its header: Sector + * features has a Feature column; Stars a Star column and no World; + * the worlds table a World column and no Feature. + */ +function findKind(lines: string[], kind: TableKind, aliases: Record): Span | null { + for (let i = 0; i < lines.length - 1; i++) { + if (!lines[i].trim().startsWith("|") || !SEPARATOR_ROW.test(lines[i + 1])) continue; + const heads = splitRow(lines[i]).map(normHeader); + const isFeatures = heads.some((h) => FEATURE_ALIASES[h] === "Feature"); + const hasWorld = heads.some((h) => HEADER_ALIASES[h] === "World"); + const fits = kind === "features" ? isFeatures + : kind === "stars" ? !isFeatures && !hasWorld && heads.some((h) => STAR_ALIASES[h] === "Star") + : !isFeatures && hasWorld; + if (!fits) continue; + let end = i + 2; + while (end < lines.length && lines[end].trim().startsWith("|")) end++; + return { start: i, end, cols: heads.map((h) => aliases[h]) }; + } + return null; +} + +const findTable = (lines: string[]) => findKind(lines, "worlds", HEADER_ALIASES); +const findStars = (lines: string[]) => findKind(lines, "stars", STAR_ALIASES); +const findFeatures = (lines: string[]) => findKind(lines, "features", FEATURE_ALIASES); + +/** A cell by column name (blank when the column is missing). */ +const cellOf = (cells: string[], cols: (C | undefined)[], c: C) => { + const i = cols.indexOf(c); + return i >= 0 ? (cells[i] ?? "").trim() : ""; +}; +/** A name cell: a `[[link]]`'s target, else the text. */ +const nameCell = (raw: string) => (/\[\[([^\]|#]+)/.exec(raw)?.[1] ?? raw).trim(); + +function readStarRow(cells: string[], cols: (StarColumn | undefined)[]): { row?: StarTypeRow; problem?: string } { + const star = nameCell(cellOf(cells, cols, "Star")); + if (!star) return { problem: "no star" }; + const row: StarTypeRow = { star }; + const w = cellOf(cells, cols, "Weight"); + if (w) { + const n = readWeight(w); + if (!Number.isFinite(n)) return { problem: `weight "${w}" isn't a number` }; + row.weight = n; + } + const notes = cellOf(cells, cols, "Notes"); + if (notes) row.notes = notes; + return { row }; +} + +function readFeatureRow(cells: string[], cols: (FeatureColumn | undefined)[]): { row?: SectorFeatureRow; problem?: string } { + const feature = nameCell(cellOf(cells, cols, "Feature")); + if (!feature) return { problem: "no feature" }; + const c = cellOf(cells, cols, "Chance"); + const chance = readChance(c); + if (!Number.isFinite(chance)) return { problem: c ? `chance "${c}" should look like 1 in 50 or 2%` : "no chance (like 1 in 50 or 2%)" }; + const row: SectorFeatureRow = { feature, chance }; + const notes = cellOf(cells, cols, "Notes"); + if (notes) row.notes = notes; + return { row }; +} + +/** The frontmatter's `hexmaker-world-types:` number. */ +function readFormat(lines: string[]): number | undefined { + if (lines[0]?.trim() !== "---") return undefined; + for (let i = 1; i < lines.length && lines[i].trim() !== "---"; i++) { + const m = new RegExp(`^\\s*${WORLD_TYPES_MARKER}:\\s*(\\d+)\\s*$`).exec(lines[i]); + if (m) return Number(m[1]); + } + return undefined; +} + +/** The lines with the frontmatter's format number set to the current one (when it has one). */ +function withFormat(lines: string[]): string[] { + if (lines[0]?.trim() !== "---") return lines; + for (let i = 1; i < lines.length && lines[i].trim() !== "---"; i++) { + const m = new RegExp(`^(\\s*${WORLD_TYPES_MARKER}:\\s*)\\d+(\\s*)$`).exec(lines[i]); + if (!m) continue; + const out = [...lines]; + out[i] = `${m[1]}${WORLD_TYPES_FORMAT}${m[2]}`; + return out; + } + return lines; +} + +/** One table row → a row, or why it can't be read. */ +function readRow(cells: string[], cols: (Column | undefined)[]): { row?: WorldTypeRow; problem?: string } { + const cell = (c: Column) => { + const i = cols.indexOf(c); + return i >= 0 ? (cells[i] ?? "").trim() : ""; + }; + const worldRaw = cell("World"); + const world = (/\[\[([^\]|#]+)/.exec(worldRaw)?.[1] ?? worldRaw).trim(); + if (!world) return { problem: "no world" }; + const row: WorldTypeRow = { world }; + const w = cell("Weight"); + if (w) { + const n = readWeight(w); + if (!Number.isFinite(n)) return { problem: `weight "${w}" isn't a number` }; + row.weight = n; + } + const m = readMap(cell("Map")); + if (m === null) return { problem: `map "${cell("Map")}" should be sector or system` }; + if (m) row.map = m; + const o = readOrbit(cell("Orbit")); + if (!o) return { problem: `orbit "${cell("Orbit")}" should be inner, habitable, outer or rings like 2–4` }; + if (o.zones?.length) row.zones = o.zones; + if (o.distance) row.distance = o.distance; + const stars = readList(cell("Stars")); + if (stars.length) row.stars = stars; + const t = cell("Temperature"); + if (t) { + // Any doubt (even a range written backwards) leaves the row as written. + const r = parseClimateRange(t, TEMPERATURE_WORDS); + if (r.problem) return { problem: `temperature ${r.problem}` }; + if (r.range) row.temperature = r.range; + } + const mw = nameCell(cell("Mainworld")); + if (mw) row.mainworld = mw; + const s = cell("Size"); + if (s) { + const size = readSize(s); + if (!size) return { problem: `size "${s}" should look like 20×14 or 16–24 × 10–14` }; + row.size = size; + } + const g = readGenerator(cell("Generator")); + if (g) row.generator = g; + const opts = readOptions(cell("Options")); + if (!opts) return { problem: `options "${cell("Options")}" should look like water=85, climate=lush` }; + if (Object.keys(opts).length) row.options = opts; + // A link to the palette's note ([[world/palettes/Space - Planet]]) or its name. + if (cell("Palette")) row.palette = refBasename(cell("Palette")) || cell("Palette"); + if (cell("Base")) row.baseTerrain = cell("Base"); + if (cell("Notes")) row.notes = cell("Notes"); + return { row }; +} + +/** Read one table's rows into `rows`; rows that can't be read go to `unreadable` and `problems`. */ +function readInto( + lines: string[], + t: Span, + read: (cells: string[], cols: (C | undefined)[]) => { row?: R; problem?: string }, + label: string, + rows: R[], + problems: WorldTypeProblem[], + unreadable: string[], +): void { + for (let i = t.start + 2; i < t.end; i++) { + const cells = splitRow(lines[i]); + if (cells.every((c) => c === "")) continue; + const { row, problem } = read(cells, t.cols); + if (row) rows.push(row); + else { + problems.push({ line: i + 1, text: `${label}row ${i + 1}: ${problem ?? "can't be read"} (left as written, not used)` }); + unreadable.push(lines[i]); + } + } +} + +/** Read a world types note (worlds, and the Stars and Sector features tables when it has them). Never throws. */ +export function parseWorldTypes(content: string): ParsedWorldTypes { + const lines = content.replace(/\r\n?/g, "\n").split("\n"); + const out: ParsedWorldTypes = { rows: [], problems: [], unreadable: [], unreadableStars: [], unreadableFeatures: [] }; + const format = readFormat(lines); + if (format !== undefined) out.format = format; + const t = findTable(lines); + if (t) readInto(lines, t, readRow, "", out.rows, out.problems, out.unreadable); + else out.problems.push({ text: "no table with a World column" }); + const s = findStars(lines); + if (s) { + out.stars = []; + readInto(lines, s, readStarRow, "Stars ", out.stars, out.problems, out.unreadableStars); + } + const f = findFeatures(lines); + if (f) { + out.features = []; + readInto(lines, f, readFeatureRow, "Sector features ", out.features, out.problems, out.unreadableFeatures); + const total = out.features.reduce((a, r) => a + r.chance, 0); + if (total > 1 + 1e-9) out.problems.push({ text: `Sector features: the chances add up to over 100% (${Math.round(total * 1000) / 10}%), so the last ones come up less` }); + } + return out; +} + +const esc = (s: string) => s.replace(/\|/g, "\\|"); +const fmtNum = (n: number) => String(Math.round(n * 1000) / 1000); + +/** A row as the note's table cells, in COLUMNS order. */ +export function worldTypeCells(r: WorldTypeRow): string[] { + return [ + r.world, + r.weight === undefined ? "" : fmtNum(r.weight), + r.map ?? "", + formatOrbit(r), + (r.stars ?? []).join(", "), + r.temperature ? formatClimateRange(r.temperature, TEMPERATURE_WORDS) : "", + r.mainworld ?? "", + r.size ? formatSize(r.size) : "", + formatGenerator(r.generator), + formatOptions(r.options), + r.palette ?? "", + r.baseTerrain ?? "", + r.notes ?? "", + ]; +} + +/** A Stars row as the note's cells, in STAR_COLUMNS order. */ +export function starCells(r: StarTypeRow): string[] { + return [r.star, r.weight === undefined ? "" : fmtNum(r.weight), r.notes ?? ""]; +} + +/** A Sector features row as the note's cells, in FEATURE_COLUMNS order. */ +export function featureCells(r: SectorFeatureRow): string[] { + return [r.feature, formatChance(r.chance), r.notes ?? ""]; +} + +function markdownTable(columns: readonly string[], rightAligned: string, cells: string[][], keep: readonly string[]): string[] { + return [ + `| ${columns.join(" | ")} |`, + `| ${columns.map((c) => (c === rightAligned ? "---:" : "---")).join(" | ")} |`, + ...cells.map((row) => `| ${row.map((c) => (c.startsWith("[[") ? c : esc(c))).join(" | ")} |`), + ...keep, + ]; +} + +/** + * Where the notes a world types table names are: the Palette column is + * written as a link to the palette's note when it has one (NF3 follow-up), + * else the name as typed. Readers take both. + */ +export interface WorldTypeLinks { + /** A palette's note path, when it has one. */ + paletteNote?(name: string): string | undefined; +} + +/** A Palette cell: a link to the palette's note when `links` knows it, else the name. */ +export function paletteCell(name: string | undefined, links?: WorldTypeLinks): string { + if (!name) return ""; + const link = pathLink(links?.paletteNote?.(name)); + return link && refBasename(link) === name ? link : name; +} + +/** worldTypeCells, with the Palette cell a link where `links` can make one. */ +export function worldTypeCellsLinked(r: WorldTypeRow, links?: WorldTypeLinks): string[] { + const cells = worldTypeCells(r); + cells[COLUMNS.indexOf("Palette")] = paletteCell(r.palette, links); + return cells; +} + +const tableLines = (rows: readonly WorldTypeRow[], keep: readonly string[] = [], links?: WorldTypeLinks) => + markdownTable(COLUMNS, "Weight", rows.map((r) => worldTypeCellsLinked(r, links)), keep); +const starTableLines = (rows: readonly StarTypeRow[], keep: readonly string[] = []) => + markdownTable(STAR_COLUMNS, "Weight", rows.map(starCells), keep); +const featureTableLines = (rows: readonly SectorFeatureRow[], keep: readonly string[] = []) => + markdownTable(FEATURE_COLUMNS, "Chance", rows.map(featureCells), keep); + +/** The Stars and Sector features tables a note is given (each optional). */ +export interface WorldTypeExtras { + stars?: readonly StarTypeRow[]; + features?: readonly SectorFeatureRow[]; +} + +/** A fresh table note (Stars and Sector features are written even when empty). */ +export function buildWorldTypes(name: string, rows: readonly WorldTypeRow[], extras: WorldTypeExtras = {}, links?: WorldTypeLinks): string { + return [ + "---", `${WORLD_TYPES_MARKER}: ${WORLD_TYPES_FORMAT}`, "---", "", + `# ${name}`, "", + ...WORLD_TYPES_HELP, "", + ...tableLines(rows, [], links), "", + STARS_HEADING, "", + ...STARS_HELP, "", + ...starTableLines(extras.stars ?? []), "", + FEATURES_HEADING, "", + ...FEATURES_HELP, "", + ...featureTableLines(extras.features ?? []), "", + ].join("\n"); +} + +/** Rows compared as their cells (the name in any case). */ +export function sameRows(a: readonly R[], b: readonly R[], cellsOf: (r: R) => string[]): boolean { + const key = (r: R) => JSON.stringify(cellsOf(r).map((c, i) => (i === 0 ? c.toLowerCase() : c))); + return a.length === b.length && a.every((r, i) => key(r) === key(b[i])); +} + +/** Two tables' rows match (none and none match too). */ +export function sameOptional(a: readonly R[] | undefined, b: readonly R[] | undefined, cellsOf: (r: R) => string[]): boolean { + if (!a || !b) return !a && !b; + return sameRows(a, b, cellsOf); +} + +/** `table` in place of the span, or appended at the end after `head` (a heading and help). */ +function putTable(lines: string[], span: Span | null, table: string[], head: string[]): string[] { + if (span) return [...lines.slice(0, span.start), ...table, ...lines.slice(span.end)]; + const out = [...lines]; + while (out.length && out[out.length - 1].trim() === "") out.pop(); + out.push("", ...head, ...table, ""); + return out; +} + +/** + * The note with its worlds table set to `rows` and, when given, its Stars + * and Sector features tables set too (added under their heading when the + * note has none). Everything else is kept, and so are rows that couldn't + * be read (after the new rows of their table, as written). A table that + * didn't change isn't rewritten; same string when nothing changes. + */ +export function updateWorldTypes(content: string, rows: readonly WorldTypeRow[], extras: WorldTypeExtras = {}, links?: WorldTypeLinks): string { + const eol = content.includes("\r\n") ? "\r\n" : "\n"; + let lines = content.replace(/\r\n?/g, "\n").split("\n"); + const parsed = parseWorldTypes(content); + let changed = false; + const t = findTable(lines); + if (!t || !sameRows(parsed.rows, rows, worldTypeCells)) { + lines = putTable(lines, t, tableLines(rows, parsed.unreadable, links), []); + changed = true; + } + if (extras.stars && !(parsed.stars && sameRows(parsed.stars, extras.stars, starCells))) { + lines = putTable(lines, findStars(lines), starTableLines(extras.stars, parsed.unreadableStars), [STARS_HEADING, "", ...STARS_HELP, ""]); + changed = true; + } + if (extras.features && !(parsed.features && sameRows(parsed.features, extras.features, featureCells))) { + lines = putTable(lines, findFeatures(lines), featureTableLines(extras.features, parsed.unreadableFeatures), [FEATURES_HEADING, "", ...FEATURES_HELP, ""]); + changed = true; + } + if (!changed) return content; + if (findStars(lines) && findFeatures(lines)) lines = withFormat(lines); + return lines.join(eol); +} + +/** + * Sector rows without a Mainworld get the shipped row's (same world, any + * case), so a note written before the column keeps the old pairing + * ("ocean world" opens on an "ocean planet"). Rows the shipped table + * doesn't have, or that say something already, are left as they are. + */ +export function withShippedMainworlds(rows: readonly WorldTypeRow[], shipped: readonly WorldTypeRow[]): WorldTypeRow[] { + return copyWorldTypeRows(rows).map((r) => { + if (r.mainworld || r.map === "system") return r; + const s = shipped.find((d) => d.map !== "system" && d.mainworld && lc(d.world) === lc(r.world)); + return s?.mainworld ? { ...r, mainworld: s.mainworld } : r; + }); +} + +/** + * An older note brought up to date, so it keeps placing what the + * generators always did: a format 1 note (written before stars and sector + * features were rows) is given the shipped Stars and Sector features + * tables; a format 1 or 2 note (before the Mainworld column) is given the + * shipped rows' mainworlds. It is marked with the current format. Anything + * else (current, or a note without the marker) comes back as is. + */ +export function upgradeWorldTypes(content: string, defaults: Required & { rows?: readonly WorldTypeRow[] }, links?: WorldTypeLinks): string { + const p = parseWorldTypes(content); + if (p.format === undefined || p.format >= WORLD_TYPES_FORMAT) return content; + const old = p.format < 2; + const rows = defaults.rows ? withShippedMainworlds(p.rows, defaults.rows) : p.rows; + const next = updateWorldTypes(content, rows, { + stars: old && !p.stars ? defaults.stars : undefined, + features: old && !p.features ? defaults.features : undefined, + }, links); + const eol = next.includes("\r\n") ? "\r\n" : "\n"; + const marked = withFormat(next.replace(/\r\n?/g, "\n").split("\n")).join(eol); + return marked; +} + +/** + * The one-time rewrite (NF3 follow-up): plain Palette cells that name a + * palette with a note become links to it. The worlds table is written + * again only when some cell changes (rows that can't be read stay as + * written); same string otherwise. + */ +export function linkWorldTypePalettes(content: string, links: WorldTypeLinks): string { + const lines = content.replace(/\r\n?/g, "\n").split("\n"); + const t = findTable(lines); + if (!t) return content; + const col = t.cols.indexOf("Palette"); + if (col < 0) return content; + const plain = (cell: string) => !!cell && !cell.startsWith("[[") && paletteCell(cell, links) !== cell; + let any = false; + for (let i = t.start + 2; i < t.end && !any; i++) any = plain(splitRow(lines[i])[col] ?? ""); + if (!any) return content; + const parsed = parseWorldTypes(content); + const eol = content.includes("\r\n") ? "\r\n" : "\n"; + return putTable(lines, t, tableLines(parsed.rows, parsed.unreadable, links), []).join(eol); +} + +/** A deep copy of rows (callers may change it). */ +export function copyWorldTypeRows(rows: readonly WorldTypeRow[]): WorldTypeRow[] { + return rows.map((r) => { + const c: WorldTypeRow = { ...r }; + if (r.zones) c.zones = [...r.zones]; + if (r.distance) c.distance = { ...r.distance }; + if (r.stars) c.stars = [...r.stars]; + if (r.temperature) c.temperature = { ...r.temperature }; + if (r.size) c.size = { cols: { ...r.size.cols }, rows: { ...r.size.rows } }; + if (r.generator) c.generator = { ...r.generator }; + if (r.options) c.options = { ...r.options }; + return c; + }); +} + +/** + * Cells in WORLD_TYPE_COLUMNS order → a row, or what's wrong (the + * editor's check; the same reading as the note's). + */ +export function readWorldTypeCells(cells: readonly string[]): { row?: WorldTypeRow; problem?: string } { + return readRow([...cells], [...COLUMNS]); +} + +/** Cells in STAR_COLUMNS order → a Stars row, or what's wrong. */ +export function readStarCells(cells: readonly string[]): { row?: StarTypeRow; problem?: string } { + return readStarRow([...cells], [...STAR_COLUMNS]); +} + +/** Cells in FEATURE_COLUMNS order → a Sector features row, or what's wrong. */ +export function readFeatureCells(cells: readonly string[]): { row?: SectorFeatureRow; problem?: string } { + return readFeatureRow([...cells], [...FEATURE_COLUMNS]); +} + +export const copyStarRows = (rows: readonly StarTypeRow[]): StarTypeRow[] => rows.map((r) => ({ ...r })); +export const copyFeatureRows = (rows: readonly SectorFeatureRow[]): SectorFeatureRow[] => rows.map((r) => ({ ...r })); + +/** Each fitting world's exact odds (0..1) for a context, most likely first. */ +export function worldTypeOdds(table: WorldTypeTable, ctx: Omit & { seed?: number }): { world: string; odds: number }[] { + const w = worldTypeWeights(table, ctx); + const total = Object.values(w).reduce((a, b) => a + b, 0); + if (total <= 0) return []; + const names = new Map(matchingWorldTypes(table, ctx).map((r) => [lc(r.world), r.world.trim()])); + return Object.entries(w) + .map(([k, v]) => ({ world: names.get(k) ?? k, odds: v / total })) + .sort((a, b) => b.odds - a.odds || a.world.localeCompare(b.world)); +} + +/** Roll `n` worlds (seeds `seed`, `seed + 1`, …) and count them, most rolled first. */ +export function rollWorldTypes(table: WorldTypeTable, ctx: Omit, n: number, seed = 1): { world: string; count: number }[] { + const counts = new Map(); + for (let i = 0; i < n; i++) { + const p = pickWorldType(table, { ...ctx, seed: seed + i }); + if (p) counts.set(p.terrain, (counts.get(p.terrain) ?? 0) + 1); + } + return [...counts].map(([world, count]) => ({ world, count })).sort((a, b) => b.count - a.count || a.world.localeCompare(b.world)); +} diff --git a/src/space/worldTypesDraft.ts b/src/space/worldTypesDraft.ts new file mode 100644 index 00000000..7f3aea13 --- /dev/null +++ b/src/space/worldTypesDraft.ts @@ -0,0 +1,186 @@ +/** + * The World types dialog's rows while they're edited, and when to save + * them (SP2: autosave like the hex editor). DOM-free so it can be tested. + * + * - Rows are kept as their note cells. Only rows that read are ever + * written; a row that doesn't (half made, an unknown map kind) stays + * here, marked incomplete, until it's fixed or removed, and is dropped + * when the dialog closes. + * - `base` is each table as the note had it when last read or saved. A + * save writes only when the readable rows differ from it, so opening and + * closing (or undoing an edit) writes nothing. + * - Hand edits to the note while the dialog is open (sync()): a table the + * dialog hasn't changed takes the note's rows; one changed in both + * places takes the note's rows too (the note wins, and the caller says + * so). The store also skips a table the note changed under a save + * (WorldTypeStore.update's `base`), so a save never overwrites a hand + * edit it hasn't seen yet. + */ + +import { + featureCells, + readFeatureCells, + readStarCells, + readWorldTypeCells, + sameOptional, + starCells, + worldTypeCells, + type SectorFeatureRow, + type StarTypeRow, + type WorldTypeExtras, + type WorldTypeRow, + type WorldTypeTable, +} from "./worldTypes"; + +export type WorldTypesTab = "worlds" | "stars" | "features"; +export const TAB_ORDER: WorldTypesTab[] = ["worlds", "stars", "features"]; + +/** What the draft needs from WorldTypeStore. */ +export interface DraftStore { + get(name: string): WorldTypeTable | undefined; + update(name: string, rows: readonly WorldTypeRow[], extras: WorldTypeExtras, base?: WorldTypeTable): Promise; +} + +type AnyRow = WorldTypeRow | StarTypeRow | SectorFeatureRow; +interface Codec { + read: (cells: readonly string[]) => { row?: AnyRow; problem?: string }; + cells: (row: never) => string[]; +} +const CODECS: Record = { + worlds: { read: readWorldTypeCells, cells: worldTypeCells }, + stars: { read: readStarCells, cells: starCells }, + features: { read: readFeatureCells, cells: featureCells }, +}; + +/** A table's rows for a tab (undefined: the note has no such table). */ +function rowsOf(t: WorldTypeTable | undefined, tab: WorldTypesTab): AnyRow[] | undefined { + if (!t) return undefined; + return tab === "worlds" ? t.rows : tab === "stars" ? t.stars : t.features; +} + +function same(tab: WorldTypesTab, a: readonly AnyRow[] | undefined, b: readonly AnyRow[] | undefined): boolean { + return sameOptional(a, b, CODECS[tab].cells as (r: AnyRow) => string[]); +} + +export interface SyncResult { + /** The rows shown changed (re-draw). */ + changed: boolean; + /** Tabs where edits made here gave way to the note's hand edits. */ + replaced: WorldTypesTab[]; +} + +export class WorldTypesDraft { + /** The rows being edited, as note cells, per tab. */ + cells: Record = { worlds: [], stars: [], features: [] }; + /** The table as the note had it when last read or saved. */ + private base: WorldTypeTable | undefined; + /** What the save in flight is writing (to tell its echo from a hand edit). */ + private sent: WorldTypeTable | undefined; + + constructor(private store: DraftStore, public name: string) { + this.load(); + } + + /** Read the table from the store (dropping anything not saved). */ + load(name: string = this.name): void { + this.name = name; + this.base = this.store.get(name); + this.sent = undefined; + for (const tab of TAB_ORDER) this.cells[tab] = this.cellsOf(tab, rowsOf(this.base, tab)); + } + + private cellsOf(tab: WorldTypesTab, rows: readonly AnyRow[] | undefined): string[][] { + const toCells = CODECS[tab].cells as (r: AnyRow) => string[]; + return (rows ?? []).map((r) => toCells(r)); + } + + /** A tab's rows that read (the ones that would be saved). */ + readable(tab: "worlds"): WorldTypeRow[]; + readable(tab: "stars"): StarTypeRow[]; + readable(tab: "features"): SectorFeatureRow[]; + readable(tab: WorldTypesTab): AnyRow[]; + readable(tab: WorldTypesTab): AnyRow[] { + const out: AnyRow[] = []; + for (const c of this.cells[tab]) { + const { row } = CODECS[tab].read(c); + if (row) out.push(row); + } + return out; + } + + /** Why a row can't be read, or undefined. */ + problem(tab: WorldTypesTab, cells: readonly string[]): string | undefined { + return CODECS[tab].read(cells).problem; + } + + /** How many rows (all tabs) can't be read yet. */ + incompleteCount(): number { + let n = 0; + for (const tab of TAB_ORDER) for (const c of this.cells[tab]) if (this.problem(tab, c)) n++; + return n; + } + + /** The table as edited here (readable rows only), for the preview. */ + table(): WorldTypeTable { + return { name: this.name, rows: this.readable("worlds"), stars: this.readable("stars"), features: this.readable("features") }; + } + + /** + * What a save would write for a tab: undefined for Stars / Sector + * features when the note has no such table and none of its rows read + * (so a half-made first row doesn't add an empty table). + */ + private wanted(tab: WorldTypesTab): AnyRow[] | undefined { + const rows = this.readable(tab); + if (tab !== "worlds" && !rowsOf(this.base, tab) && !rows.length) return undefined; + return rows; + } + + /** Readable rows differ from the note's (a save would write). */ + hasChanges(): boolean { + if (!this.base) return false; + return TAB_ORDER.some((tab) => !same(tab, this.wanted(tab), rowsOf(this.base, tab))); + } + + /** Write the readable rows if they changed. True when a write was asked for. */ + async save(): Promise { + if (!this.hasChanges() || !this.base) return false; + const rows = this.readable("worlds"); + const extras: WorldTypeExtras = {}; + const stars = this.wanted("stars") as StarTypeRow[] | undefined; + const features = this.wanted("features") as SectorFeatureRow[] | undefined; + if (stars) extras.stars = stars; + if (features) extras.features = features; + this.sent = { name: this.name, rows, ...extras } as WorldTypeTable; + const base = this.base; + try { + return await this.store.update(this.name, rows, extras, base); + } finally { + this.sent = undefined; + } + } + + /** The store changed: take in hand edits (see the file comment). */ + sync(): SyncResult { + const theirs = this.store.get(this.name); + const out: SyncResult = { changed: false, replaced: [] }; + if (!theirs || !this.base) return out; + for (const tab of TAB_ORDER) { + const t = rowsOf(theirs, tab); + const b = rowsOf(this.base, tab); + if (same(tab, t, b)) continue; + // Our own save coming back: the note now matches what we wrote. + const echo = this.sent && same(tab, t, rowsOf(this.sent, tab)); + const ours = this.wanted(tab); + if (!echo && !same(tab, ours, t)) { + if (!same(tab, ours, b)) out.replaced.push(tab); + // Take the note's rows; rows still being made here stay, at the end. + const incomplete = this.cells[tab].filter((c) => this.problem(tab, c)); + this.cells[tab] = [...this.cellsOf(tab, t), ...incomplete]; + out.changed = true; + } + } + this.base = theirs; + return out; + } +} diff --git a/src/space/worldTypesSource.ts b/src/space/worldTypesSource.ts new file mode 100644 index 00000000..f9988707 --- /dev/null +++ b/src/space/worldTypesSource.ts @@ -0,0 +1,192 @@ +/** + * SP1: the World types note drives Star scatter and Orbits. An adapter + * that reads a world types table (worldTypes.ts) as the engines' role + * tables (worldgen/tableRoles.ts), so the generators roll on it through + * the table resolver today, before the space tables of phase 3 exist. + * + * The note's tables become in-memory random tables: + * - Mainworlds: the worlds rows for a sector (Map sector or blank). + * - Sector hexes: one row per sector feature (its Chance as the weight, + * so a star system hex is that feature with exactly that chance), and + * the rest of the odds a row that rolls on Mainworlds. Features that + * aren't terrains of the palette are left out (their chance goes to the + * systems, as before) and listed in the notes. + * - Stars: the Stars rows. + * - Inner / Habitable / Outer orbits: the worlds rows for a system (Map + * system or blank) whose Orbit allows that zone; ring, Stars and + * Temperature limits become When conditions. + * Every row keeps its setup columns (Mainworld, Size, Generator, …) as + * row attributes. + * + * The same odds as the old pick functions (pickWorldType, pickStar, + * pickSectorFeature), different draws (T4). + * + * Pure: no Obsidian imports. + */ + +import type { RandomTable, RandomTableEntry, RowInfo } from "../random-tables/randomTable"; +import { findRow, isNothing, memoryLookup } from "../random-tables/resolve"; +import type { TableCondition } from "../random-tables/tableConditions"; +import { EQUAL_ODDS, type RoleId, type TableSource } from "../worldgen/tableRoles"; +import type { ProcOption } from "../worldgen/procedural/common"; +import { + WORLD_TYPE_COLUMNS, + worldTypeCells, + type OrbitZone, + type WorldTypeRow, + type WorldTypeTable, +} from "./worldTypes"; + +const MAINWORLDS = "Mainworlds"; +const SECTOR_HEXES = "Sector hexes"; +const STARS = "Stars"; +const ZONE_TABLES: Record = { inner: "Inner orbits", habitable: "Habitable orbits", outer: "Outer orbits" }; +const ROLE_TABLE: Record = { + "sector-hexes": SECTOR_HEXES, + star: STARS, + "inner-orbits": ZONE_TABLES.inner, + "habitable-orbits": ZONE_TABLES.habitable, + "outer-orbits": ZONE_TABLES.outer, +}; + +/** The columns carried as row attributes. */ +const ATTR_COLUMNS = ["Mainworld", "Size", "Generator", "Options", "Palette", "Base", "Notes"] as const; + +const lc = (s: string) => s.trim().toLowerCase(); + +export function attrsOf(r: WorldTypeRow): Record { + const cells = worldTypeCells(r); + const out: Record = {}; + for (const c of ATTR_COLUMNS) { + const v = cells[WORLD_TYPE_COLUMNS.indexOf(c)]; + if (v) out[c] = v; + } + return out; +} + +/** A worlds row's limits other than map and zone, as When conditions. */ +export function conditionsOf(r: WorldTypeRow): TableCondition[] { + const out: TableCondition[] = []; + if (r.distance) out.push({ key: "ring", value: { ...r.distance } }); + if (r.stars?.length) out.push({ key: "star", value: r.stars.map(lc) }); + if (r.temperature) out.push({ key: "temperature", value: { ...r.temperature } }); + return out; +} + +function worldsTable(rows: readonly WorldTypeRow[]): RandomTable { + const entries: RandomTableEntry[] = []; + const rowInfo: RowInfo[] = []; + for (const r of rows) { + if (!r.world.trim()) continue; + entries.push({ result: r.world.trim(), weight: r.weight ?? 1 }); + const info: RowInfo = {}; + const attrs = attrsOf(r); + if (Object.keys(attrs).length) info.attrs = attrs; + const when = conditionsOf(r); + if (when.length) info.when = when; + rowInfo.push(info); + } + return { dice: 0, rows: "terrain", entries, rowInfo }; +} + +const paletteName = (t: string | { name: string }) => (typeof t === "string" ? t : t.name); + +// ── the space generators' "World types" option ──────────────────────────── + +/** Option key: which World types table Star scatter and Orbits roll on. */ +export const WORLD_TYPES_KEY = "worldTypes"; +/** The default table: "Default space" if there is one, else the first. */ +export const WORLD_TYPES_DEFAULT = "(default)"; +/** No table: equal odds (said in the generator's warnings). */ +export const WORLD_TYPES_NONE = "(none)"; + +/** The option, for these table names (`fallbackName` = what "Default" means now). */ +export function worldTypesOption(names: readonly string[], fallbackName?: string): ProcOption { + return { + key: WORLD_TYPES_KEY, + label: "World types", + choices: [ + { value: WORLD_TYPES_DEFAULT, label: fallbackName ? `Default (${fallbackName})` : "Default" }, + ...names.map((n) => ({ value: n, label: n })), + { value: WORLD_TYPES_NONE, label: "None (equal odds)" }, + ], + default: WORLD_TYPES_DEFAULT, + }; +} + +/** The table name an option value means (undefined = none). */ +export function chosenWorldTypes(value: string | undefined, names: readonly string[], fallbackName: string | undefined): string | undefined { + if (value === WORLD_TYPES_NONE) return undefined; + if (!value || value === WORLD_TYPES_DEFAULT) return fallbackName; + return value; +} + +/** What "Default" means: the shipped table's name if there is one, else the first table. */ +export function defaultWorldTypesName(names: readonly string[], shipped: string): string | undefined { + return names.find((n) => lc(n) === lc(shipped)) ?? names[0]; +} + +/** + * The role tables a world types table gives for a palette. `label` names + * it in notes (default "World types: "). + */ +export function worldTypesSource(table: WorldTypeTable, palette: readonly (string | { name: string })[], label = `World types: ${table.name}`): TableSource { + const terrains = palette.map(paletteName); + const inPalette = (n: string) => terrains.some((t) => lc(t) === lc(n)); + + const sectorRows = table.rows.filter((r) => r.map !== "system"); + const systemRows = table.rows.filter((r) => r.map !== "sector"); + const mainworlds = worldsTable(sectorRows); + const anyMainworld = sectorRows.some((r) => (r.weight ?? 1) > 0 && (inPalette(r.world) || isNothing(r.world))); + + // Sector hexes: features by their chance, then the systems. + const featureNotes: string[] = []; + const features: RandomTableEntry[] = []; + let left = 1; + const seen = new Set(); + for (const f of table.features ?? []) { + const name = f.feature.trim(); + if (!name || !(f.chance > 0)) continue; + if (!inPalette(name)) { featureNotes.push(name); continue; } + const key = lc(name); + const chance = Math.max(0, Math.min(f.chance, left)); + left -= chance; + if (seen.has(key)) { + const e = features.find((x) => lc(x.result) === key); + if (e) e.weight += chance; + continue; + } + seen.add(key); + if (chance > 0) features.push({ result: terrains.find((t) => lc(t) === key) ?? name, weight: chance }); + } + const sectorHexes: RandomTable = { + dice: 0, + rows: "terrain", + entries: [ + ...features, + ...(left > 1e-12 ? [{ result: anyMainworld ? MAINWORLDS : EQUAL_ODDS, weight: left, isLink: true }] : []), + ], + }; + + const stars: RandomTable | undefined = table.stars?.length + ? { dice: 0, rows: "terrain", entries: table.stars.filter((s) => s.star.trim()).map((s) => ({ result: s.star.trim(), weight: s.weight ?? 1 })) } + : undefined; + + const tables: Record = { [MAINWORLDS]: mainworlds, [SECTOR_HEXES]: sectorHexes }; + if (stars) tables[STARS] = stars; + for (const z of Object.keys(ZONE_TABLES) as OrbitZone[]) { + tables[ZONE_TABLES[z]] = worldsTable(systemRows.filter((r) => !r.zones?.length || r.zones.includes(z))); + } + const lookup = memoryLookup(tables); + + return { + label, + lookup, + terrains, + tableFor: (role) => (role === "star" && !stars ? undefined : ROLE_TABLE[role]), + rowAttrs: (role, name) => findRow(role === "sector-hexes" ? MAINWORLDS : ROLE_TABLE[role], name, lookup)?.attrs, + notes: (role) => role === "sector-hexes" && featureNotes.length + ? [`${label}: Sector features not a terrain of this palette, so never placed: ${[...new Set(featureNotes)].join(", ")}.`] + : [], + }; +} diff --git a/src/stores/NoteFolderStore.ts b/src/stores/NoteFolderStore.ts new file mode 100644 index 00000000..602cde6c --- /dev/null +++ b/src/stores/NoteFolderStore.ts @@ -0,0 +1,126 @@ +/** + * A store over a folder of notes that are the only copy of their data + * (biome notes, World types tables): every note is read into an entry, + * hand edits are read back live from vault events, and every change is + * told to onChange listeners. Reads and writes run one at a time on a + * queue, so a hand edit is always read before a write that follows it. + * + * Subclasses say where the folder is, which files are theirs, how a note + * is read (load), and the words used in logs and backup folder names. + */ + +import { TAbstractFile, TFile, TFolder } from "obsidian"; +import type HexmakerPlugin from "../HexmakerPlugin"; +import type { ModuleStore } from "../modules/types"; +import { writeJsonBackup } from "../backup"; +import { ensureFolderPath } from "../vault/ensureFolder"; +import { logError } from "../log"; + +export abstract class NoteFolderStore implements ModuleStore { + abstract readonly id: string; + /** Logged with a failed queued task: "Hexmaker: ". */ + protected abstract readonly logLabel: string; + /** Backups go to `/backups/-/`. */ + protected abstract readonly backupFolder: string; + /** Logged when a backup fails: "Hexmaker: backup failed". */ + protected abstract readonly backupLabel: string; + + protected entries = new Map(); + protected lastContent = new Map(); + protected reported = new Map(); + protected listeners = new Set<() => void>(); + protected ready = false; + protected queue: Promise = Promise.resolve(); + + constructor(protected plugin: HexmakerPlugin) {} + + abstract init(): Promise; + /** The folder the notes live in. */ + abstract folder(): string; + /** Whether a vault file is one of this store's notes. */ + protected abstract isNoteFile(f: TAbstractFile): f is TFile; + /** Read one note. True when what it says changed. */ + protected abstract load(f: TFile): Promise; + + isReady(): boolean { + return this.ready; + } + + /** Call `fn` after every change. Returns an unsubscribe. */ + onChange(fn: () => void): () => void { + this.listeners.add(fn); + return () => this.listeners.delete(fn); + } + + /** Re-read every note (the folder setting changed). */ + async reload(): Promise { + await this.enqueue(async () => { + this.entries.clear(); + this.lastContent.clear(); + for (const f of this.files()) await this.load(f); + this.publish(); + }); + } + + // ── vault events ─────────────────────────────────────────────────────── + + /** A new note is read like an edited one. */ + onCreate(f: TAbstractFile): void { + this.onModify(f); + } + + onModify(f: TAbstractFile): void { + if (!this.isNoteFile(f)) return; + void this.enqueue(async () => { + if (await this.load(f)) this.publish(); + }); + } + + onDelete(f: TAbstractFile): void { + if (!this.entries.has(f.path)) return; + this.entries.delete(f.path); + this.lastContent.delete(f.path); + this.publish(); + } + + // ── internals ────────────────────────────────────────────────────────── + + protected publish(): void { + for (const fn of this.listeners) fn(); + } + + /** Every note in the folder and its subfolders (not `_` notes), in path order. */ + protected files(): TFile[] { + const root = this.plugin.app.vault.getAbstractFileByPath(this.folder()); + if (!(root instanceof TFolder)) return []; + const out: TFile[] = []; + const walk = (folder: TFolder) => { + for (const child of folder.children) { + if (child instanceof TFolder) walk(child); + else if (child instanceof TFile && child.path.endsWith(".md") && !child.name.startsWith("_")) out.push(child); + } + }; + walk(root); + return out.sort((a, b) => a.path.localeCompare(b.path)); + } + + protected async ensureFolder(folder: string): Promise { + await ensureFolderPath(this.plugin.app.vault, folder); + } + + protected async backup(base: string, notes: Record): Promise { + try { + const dir = `${this.plugin.manifest.dir}/backups/${this.backupFolder}-${new Date().toISOString().slice(0, 10)}`; + await writeJsonBackup(this.plugin.app.vault.adapter, dir, base, JSON.stringify({ savedAt: new Date().toISOString(), notes })); + } catch (e) { + logError(`${this.backupLabel} backup failed`, e); + } + } + + protected enqueue(task: () => Promise): Promise { + this.queue = this.queue.then(task).catch((e) => { + logError(this.logLabel, e); + }); + return this.queue; + } +} diff --git a/src/tableChoice.ts b/src/tableChoice.ts new file mode 100644 index 00000000..8948040b --- /dev/null +++ b/src/tableChoice.ts @@ -0,0 +1,173 @@ +/** + * One section per kind of rolled table in the hex editor (owner SF2, + * 2026-10-14): instead of separate rolls per source, the hex lists every + * table that applies to it, most specific first (hex > area > map > + * terrain > default), and the user switches between them. Pure helpers; + * the hex editor gathers the data and draws it (random-tables/TableChoice.ts). + * + * Where each candidate comes from (the association data as stored): + * - hex: a link in the hex note's section for the kind ("### Encounters + * Table", "### Weather Table", "### Rumors Table"). + * - area: the area's table `{tables}/regions/.md`, linked into the + * hex's Encounters Table section when the hex is painted into the area. + * - map: the map note's `weather-table:` / `rumors-table:`. + * - terrain: the terrain's table `{tables}/terrain/encounters/.md`, + * linked into the Encounters Table section when the terrain is painted. + * - default: the starter table at the root of the tables folder. + * + * Once the hex has a note, its section is the truth for hex, area and + * terrain links (the user may have removed one); a hex with no note yet + * shows the area and terrain tables its note will get. + */ + +import { ROLLED_SECTION_TABLES, type RolledSection, type RolledSectionTables } from "./regionTables"; +import { hexKey } from "./hexKey"; + +export type ChoiceSource = "hex" | "area" | "map" | "terrain" | "default"; + +/** Most specific first. */ +export const SOURCE_ORDER: readonly ChoiceSource[] = ["hex", "area", "map", "terrain", "default"]; + +export interface TableChoiceItem { + /** Vault path of the table (the link text as written when it doesn't resolve). */ + path: string; + source: ChoiceSource; + /** The link as written in the hex note, when the item comes from there (removable). */ + link?: string; + /** The link doesn't resolve to a note. */ + missing?: boolean; +} + +/** Short words for where a table comes from, shown beside its name. */ +export function choiceSourceLabel(source: ChoiceSource): string { + switch (source) { + case "hex": return "this hex"; + case "area": return "area"; + case "map": return "map"; + case "terrain": return "terrain"; + default: return "default"; + } +} + +/** Where a table linked in the hex note comes from, by its folder. */ +export function classifyLinkedTable(path: string, folders: { area: string; terrain: string }): ChoiceSource { + const p = path.toLowerCase(); + const under = (f: string) => !!f && p.startsWith(f.toLowerCase().replace(/\/+$/, "") + "/"); + if (under(folders.area)) return "area"; + if (under(folders.terrain)) return "terrain"; + return "hex"; +} + +export interface ChoiceInput { + /** Whether the hex has a note (then its section is the truth for linked tables). */ + noteExists: boolean; + /** Links in the hex note's section for this kind, resolved (null = no such note). */ + noteLinks: readonly { link: string; path: string | null }[]; + /** The area's table, when the hex is in an area that has one. */ + area?: string | null; + /** The map's table for this kind. */ + map?: string | null; + /** The terrain's table for this kind. */ + terrain?: string | null; + /** The starter table. */ + fallback?: string | null; + /** Folders that tell area and terrain tables apart among the note's links. */ + folders: { area: string; terrain: string }; + exists: (path: string) => boolean; +} + +/** The tables that apply to a hex for one kind, most specific first, each path once. */ +export function tableChoices(input: ChoiceInput): TableChoiceItem[] { + const out: TableChoiceItem[] = []; + for (const { link, path } of input.noteLinks) { + if (path) out.push({ path, source: classifyLinkedTable(path, input.folders), link }); + else out.push({ path: link, source: "hex", link, missing: true }); + } + const add = (path: string | null | undefined, source: ChoiceSource) => { + if (path && input.exists(path)) out.push({ path, source }); + }; + // A hex with no note yet: the tables its note will get. + if (!input.noteExists) { + add(input.area, "area"); + add(input.terrain, "terrain"); + } + add(input.map, "map"); + add(input.fallback, "default"); + return orderChoices(out); +} + +/** Sorted most specific first (stable within a source); a path listed twice keeps its most specific entry. */ +export function orderChoices(items: readonly TableChoiceItem[]): TableChoiceItem[] { + const rank = (s: ChoiceSource) => SOURCE_ORDER.indexOf(s); + const sorted = items.map((it, i) => ({ it, i })).sort((a, b) => rank(a.it.source) - rank(b.it.source) || a.i - b.i).map((x) => x.it); + const seen = new Set(); + return sorted.filter((it) => { + const key = it.path.toLowerCase(); + if (seen.has(key)) return false; + seen.add(key); + return true; + }); +} + +/** The item to start on: the one chosen before (if still listed), else the most specific usable one. */ +export function initialChoice(items: readonly TableChoiceItem[], remembered?: string | null): number { + if (remembered) { + const i = items.findIndex((it) => it.path === remembered); + if (i >= 0) return i; + } + const usable = items.findIndex((it) => !it.missing); + return usable >= 0 ? usable : 0; +} + +/** + * The choice made per hex and kind, for this session (switching is a + * look at another table, not an edit: nothing is written, so it works in + * Play). Keyed by map, hex and kind. + */ +const chosen = new Map(); + +export function choiceKey(map: string, x: number, y: number, kind: string): string { + return `${map}\u0000${hexKey(x, y)}\u0000${kind}`; +} + +export function rememberChoice(key: string, path: string): void { + chosen.set(key, path); +} + +export function rememberedChoice(key: string): string | undefined { + return chosen.get(key); +} + +/** + * The kinds of rolled table a hex has, as data: where each kind's tables + * are linked and where a roll's result goes by default. Weather and + * rumours take their map field and starter file from ROLLED_SECTION_TABLES. + */ +export interface TableKind { + id: "encounters" | RolledSection; + /** Plain name in UI text ("encounter", "weather"). */ + noun: string; + /** The hex note's link section for a hex's own tables. */ + hexSection: string; + /** The map note field holding the map's table. */ + mapField?: RolledSectionTables["mapField"]; + /** Starter table file at the root of the tables folder. */ + starterFile?: string; + /** Area tables (`{tables}/regions/.md`) apply. */ + areaTables?: boolean; + /** Terrain encounter tables apply. */ + terrainTables?: boolean; + /** The text section a roll's result goes to first. */ + rollInto: string; +} + +export const TABLE_KINDS: Readonly> = { + encounters: { id: "encounters", noun: "encounter", hexSection: "Encounters Table", areaTables: true, terrainTables: true, rollInto: "description" }, + weather: { id: "weather", ...rolled("weather") }, + "hooks & rumors": { id: "hooks & rumors", ...rolled("hooks & rumors") }, +}; + +function rolled(section: RolledSection): Omit { + const s = ROLLED_SECTION_TABLES[section]; + return { noun: s.noun, hexSection: s.hexSection, mapField: s.mapField, starterFile: s.starterFile, rollInto: section }; +} diff --git a/src/templateNotes.ts b/src/templateNotes.ts new file mode 100644 index 00000000..53a046ef --- /dev/null +++ b/src/templateNotes.ts @@ -0,0 +1,67 @@ +/** + * Template notes (the hex template, workflow templates, the Templates / + * Templater folders) are scaffolding, not world notes: never offer them in + * a note picker. A round-7 tester's click in the token form landed on + * "hextemplate". Pure helpers; HexmakerPlugin.isLinkableNote wires them up. + */ + +import { templatesFolderFor } from "./noteTemplates"; + +export interface TemplateNoteRules { + /** Exact vault paths of template notes. */ + paths: string[]; + /** Folders whose notes are all templates (no trailing slash). */ + folders: string[]; +} + +const trimSlashes = (p: string): string => p.trim().replace(/^\/+|\/+$/g, ""); + +/** The template rules for the plugin's settings plus any template folders + * other plugins use (core Templates, Templater). Blank entries are dropped. */ +export function templateNoteRules( + settings: { templatePath?: string; workflowsFolder?: string; templatesFolder?: string; worldFolder?: string }, + extraFolders: (string | undefined)[] = [], + /** Folders of the plugin's own data notes (palettes, biomes, biome pools, + * world types, generators): never listed in a picker either (SP3). */ + dataFolders: (string | undefined)[] = [], +): TemplateNoteRules { + const paths: string[] = []; + const hexTemplate = trimSlashes(settings.templatePath ?? ""); + if (hexTemplate) paths.push(hexTemplate.endsWith(".md") ? hexTemplate : `${hexTemplate}.md`); + const folders: string[] = []; + const wf = trimSlashes(settings.workflowsFolder ?? ""); + folders.push(wf ? `${wf}/templates` : "templates"); + // The plugin's own templates folder (PA3: the hex and link-section note templates). + folders.push(templatesFolderFor(settings)); + for (const f of [...extraFolders, ...dataFolders]) { + const t = trimSlashes(f ?? ""); + if (t) folders.push(t); + } + return { paths, folders }; +} + +/** Whether `path` is a template note under `rules` (case-insensitive). */ +export function isTemplateNotePath(path: string, rules: TemplateNoteRules): boolean { + const p = path.toLowerCase(); + if (rules.paths.some((t) => t.toLowerCase() === p)) return true; + return rules.folders.some((f) => p.startsWith(f.toLowerCase() + "/")); +} + +/** + * What a note picker is for. "link" (the default): linking a note to a hex, + * token, section… — templates are hidden. "template": choosing a template + * (a template path, a workflow's template file) — templates are listed. + */ +export type NotePickPurpose = "link" | "template"; + +/** Whether a note may be listed in a picker for `purpose`: never when + * `_`-prefixed; templates only when choosing a template. */ +export function isLinkableNotePath( + path: string, + basename: string, + rules: TemplateNoteRules, + purpose: NotePickPurpose = "link", +): boolean { + if (basename.startsWith("_")) return false; + return purpose === "template" || !isTemplateNotePath(path, rules); +} diff --git a/src/terrainTypeSelect.ts b/src/terrainTypeSelect.ts new file mode 100644 index 00000000..fff2e022 --- /dev/null +++ b/src/terrainTypeSelect.ts @@ -0,0 +1,27 @@ +import { MAP_KINDS, enabledKinds } from "./mapKinds"; +import { TERRAIN_TYPES, terrainTypeInfo } from "./terrainTypes"; + +/** + * Fill a