BlueGit

timfa questward

Merge branch 'cursor/editor-palette-sidebar-9e42' into 'master'

Add a Palette tab to the world editor sidebar

See merge request Timfa/questward!4

timfa Tim Falken · pushed by timfa

Authored 2026-10-06 · 6 weeks ago

Hash
ac10a7daa9e497cd7f9f7746e95e7b18aa56167a
8 files changed +649 −167
client/editor.html +7 −1
@@ -70,9 +70,15 @@
70 70 </aside>
71 71 <section id="side-panels">
72 72 <div class="side-panel-tabs" role="tablist">
73 <button type="button" class="side-panel-tab" id="side-tab-palette" data-side-panel="palette" role="tab" aria-selected="false">Palette</button>
73 74 <button type="button" class="side-panel-tab active" data-side-panel="changelog" role="tab" aria-selected="true">Changelog</button>
74 75 <button type="button" class="side-panel-tab" data-side-panel="console" role="tab" aria-selected="false">Console</button>
75 76 </div>
77 <div id="palette-wrap" class="side-panel-body palette-panel" data-side-panel-body="palette" hidden>
78 <input id="palette-panel-search" class="palette-search" type="search" placeholder="Search by name…" autocomplete="off" aria-label="Search placeables">
79 <div id="palette-panel-tabs" class="settings-tabs" role="tablist"></div>
80 <div id="palette-panel-results"></div>
81 </div>
76 82 <div id="changelog-wrap" class="side-panel-body" data-side-panel-body="changelog">
77 83 <div id="changelog"></div>
78 84 </div>
@@ -242,7 +248,7 @@
242 248 <h2>Select placeable</h2>
243 249 <button id="palette-close" type="button">Close</button>
244 250 </header>
245 <input id="palette-search" type="search" placeholder="Search by name…" autocomplete="off">
251 <input id="palette-search" class="palette-search" type="search" placeholder="Search by name…" autocomplete="off">
246 252 <div id="palette-tabs" class="settings-tabs" role="tablist"></div>
247 253 <div id="palette-panels"></div>
248 254 </div>
@@ -70,9 +70,15 @@
70 </aside>
70 </aside>
71 <section id="side-panels">
71 <section id="side-panels">
72 <div class="side-panel-tabs" role="tablist">
72 <div class="side-panel-tabs" role="tablist">
73 <button type="button" class="side-panel-tab" id="side-tab-palette" data-side-panel="palette" role="tab" aria-selected="false">Palette</button>
73 <button type="button" class="side-panel-tab active" data-side-panel="changelog" role="tab" aria-selected="true">Changelog</button>
74 <button type="button" class="side-panel-tab active" data-side-panel="changelog" role="tab" aria-selected="true">Changelog</button>
74 <button type="button" class="side-panel-tab" data-side-panel="console" role="tab" aria-selected="false">Console</button>
75 <button type="button" class="side-panel-tab" data-side-panel="console" role="tab" aria-selected="false">Console</button>
75 </div>
76 </div>
77 <div id="palette-wrap" class="side-panel-body palette-panel" data-side-panel-body="palette" hidden>
78 <input id="palette-panel-search" class="palette-search" type="search" placeholder="Search by name…" autocomplete="off" aria-label="Search placeables">
79 <div id="palette-panel-tabs" class="settings-tabs" role="tablist"></div>
80 <div id="palette-panel-results"></div>
81 </div>
76 <div id="changelog-wrap" class="side-panel-body" data-side-panel-body="changelog">
82 <div id="changelog-wrap" class="side-panel-body" data-side-panel-body="changelog">
77 <div id="changelog"></div>
83 <div id="changelog"></div>
78 </div>
84 </div>
@@ -242,7 +248,7 @@
242 <h2>Select placeable</h2>
248 <h2>Select placeable</h2>
243 <button id="palette-close" type="button">Close</button>
249 <button id="palette-close" type="button">Close</button>
244 </header>
250 </header>
245 <input id="palette-search" type="search" placeholder="Search by name…" autocomplete="off">
251 <input id="palette-search" class="palette-search" type="search" placeholder="Search by name…" autocomplete="off">
246 <div id="palette-tabs" class="settings-tabs" role="tablist"></div>
252 <div id="palette-tabs" class="settings-tabs" role="tablist"></div>
247 <div id="palette-panels"></div>
253 <div id="palette-panels"></div>
248 </div>
254 </div>
client/src/editor/main.js +47 −33
@@ -44,6 +44,7 @@ import { loadSpriteCatalog, preloadCatalogImages, applySpriteSheets, useNearestN
44 44 import { WorldView } from "../render/worldView.js";
45 45 import { initSettingsModal, initDimensionSettings } from "./settingsModal.js";
46 46 import { initPaletteModal } from "./paletteModal.js";
47 import { initPalettePanel } from "./palettePanel.js";
47 48 import { initTileConfigModal } from "./tileConfigModal.js";
48 49 import { initQuestsModal } from "./questsModal.js";
49 50 import { initDialoguesModal } from "./dialoguesModal.js";
@@ -106,6 +107,7 @@ let dimensionSettings = null;
106 107 let tool = { kind: "ground", typeId: GroundType.grass, state: null };
107 108 let settingsModal;
108 109 let paletteModal;
110 let palettePanel;
109 111 let tileConfigModal;
110 112 let questsModal;
111 113 let dialoguesModal;
@@ -232,28 +234,36 @@ function selectedToolLabel ()
232 234 return def.displayName;
233 235 }
234 236
237 function notifyToolChanged ()
238 {
239 const label = $("tool");
240 if (label)
241 { label.textContent = selectedToolLabel(); }
242 palettePanel?.sync();
243 }
244
235 245 function selectTool (next)
236 246 {
237 247 if (next.kind === "erase")
238 {
239 tool = { kind: "erase" };
240 return;
241 }
242 if (next.kind === "spawner")
248 { tool = { kind: "erase" }; }
249 else if (next.kind === "spawner")
243 250 {
244 251 if (next.spawnerKind === "item")
245 252 { tool = { kind: "spawner", spawnerKind: "item" }; }
246 253 else
247 254 { tool = { kind: "spawner", mobTypeId: next.mobTypeId }; }
248 return;
249 255 }
250 const layer = next.kind === "ground" ? "ground" : "block";
251 const def = next.kind === "ground" ? GROUND_DEFINITIONS[next.typeId] : BLOCK_DEFINITIONS[next.typeId];
252 tool = {
253 kind: next.kind,
254 typeId: next.typeId,
255 state: next.state ?? defaultStateForType(catalog, layer, def.key)
256 };
256 else
257 {
258 const layer = next.kind === "ground" ? "ground" : "block";
259 const def = next.kind === "ground" ? GROUND_DEFINITIONS[next.typeId] : BLOCK_DEFINITIONS[next.typeId];
260 tool = {
261 kind: next.kind,
262 typeId: next.typeId,
263 state: next.state ?? defaultStateForType(catalog, layer, def.key)
264 };
265 }
266 notifyToolChanged();
257 267 }
258 268
259 269 function placeableToolState ()
@@ -942,6 +952,7 @@ function syncDimensionUi ()
942 952 { openToggle.disabled = softDeleted; }
943 953 dimensionPicker?.setValue(selectedDimensionId);
944 954 dimensionSettings?.refresh();
955 palettePanel?.sync();
945 956 syncSaveButton();
946 957 }
947 958
@@ -1550,30 +1561,34 @@ async function main ()
1550 1561 view.setGraphicsPrefs(loadGraphicsSettings());
1551 1562 syncSeasonControls(view.worldSeason ?? seasonIdAt());
1552 1563 layoutScene();
1553 selectTool(tool);
1554 $("tool").textContent = selectedToolLabel();
1555 1564
1556 paletteModal = initPaletteModal({
1557 catalog,
1558 imageUrlFor (name)
1565 function editorImageUrl (name)
1566 {
1567 const sprite = game.images[name];
1568 const html = sprite?.g_image;
1569 if (html && typeof html.toDataURL === "function")
1559 1570 {
1560 const sprite = game.images[name];
1561 const html = sprite?.g_image;
1562 if (html && typeof html.toDataURL === "function")
1563 {
1564 try
1565 { return html.toDataURL("image/png"); }
1566 catch (_)
1567 { /* fall through */ }
1568 }
1569 return imageUrlByName.get(name) ?? null;
1570 },
1571 try
1572 { return html.toDataURL("image/png"); }
1573 catch (_)
1574 { /* fall through */ }
1575 }
1576 return imageUrlByName.get(name) ?? null;
1577 }
1578
1579 const paletteOptions = {
1580 catalog,
1581 imageUrlFor: editorImageUrl,
1582 getSelection: () => tool,
1583 getDimensionId: () => selectedDimensionId,
1571 1584 onSelect (next)
1572 1585 {
1573 1586 selectTool(next);
1574 $("tool").textContent = selectedToolLabel();
1575 1587 }
1576 });
1588 };
1589 palettePanel = initPalettePanel(paletteOptions);
1590 paletteModal = initPaletteModal(paletteOptions);
1591 selectTool(tool);
1577 1592
1578 1593 tileConfigModal = initTileConfigModal({
1579 1594 socket: {
@@ -2125,7 +2140,6 @@ $("tool").textContent = selectedToolLabel();
2125 2140 $("tool-erase").addEventListener("click", () =>
2126 2141 {
2127 2142 selectTool({ kind: "erase" });
2128 $("tool").textContent = selectedToolLabel();
2129 2143 });
2130 2144
2131 2145 $("north").addEventListener("click", () => loadNeighborhood(chunkX, chunkY - 1));
@@ -2375,7 +2389,7 @@ function cycleToolState (direction)
2375 2389 if (states.length < 2)
2376 2390 { return; }
2377 2391 tool.state = cycleState(states, tool.state, direction);
2378 $("tool").textContent = selectedToolLabel();
2392 notifyToolChanged();
2379 2393 const season = seasonIdFromVisualState(tool.state);
2380 2394 if (season)
2381 2395 { applySeasonPreview(season); }
@@ -44,6 +44,7 @@ import { loadSpriteCatalog, preloadCatalogImages, applySpriteSheets, useNearestN
44import { WorldView } from "../render/worldView.js";
44import { WorldView } from "../render/worldView.js";
45import { initSettingsModal, initDimensionSettings } from "./settingsModal.js";
45import { initSettingsModal, initDimensionSettings } from "./settingsModal.js";
46import { initPaletteModal } from "./paletteModal.js";
46import { initPaletteModal } from "./paletteModal.js";
47import { initPalettePanel } from "./palettePanel.js";
47import { initTileConfigModal } from "./tileConfigModal.js";
48import { initTileConfigModal } from "./tileConfigModal.js";
48import { initQuestsModal } from "./questsModal.js";
49import { initQuestsModal } from "./questsModal.js";
49import { initDialoguesModal } from "./dialoguesModal.js";
50import { initDialoguesModal } from "./dialoguesModal.js";
@@ -106,6 +107,7 @@ let dimensionSettings = null;
106let tool = { kind: "ground", typeId: GroundType.grass, state: null };
107let tool = { kind: "ground", typeId: GroundType.grass, state: null };
107let settingsModal;
108let settingsModal;
108let paletteModal;
109let paletteModal;
110let palettePanel;
109let tileConfigModal;
111let tileConfigModal;
110let questsModal;
112let questsModal;
111let dialoguesModal;
113let dialoguesModal;
@@ -232,28 +234,36 @@ function selectedToolLabel ()
232 return def.displayName;
234 return def.displayName;
233}
235}
234
236
237function notifyToolChanged ()
238{
239 const label = $("tool");
240 if (label)
241 { label.textContent = selectedToolLabel(); }
242 palettePanel?.sync();
243}
244
235function selectTool (next)
245function selectTool (next)
236{
246{
237 if (next.kind === "erase")
247 if (next.kind === "erase")
238 {
248 { tool = { kind: "erase" }; }
239 tool = { kind: "erase" };
249 else if (next.kind === "spawner")
240 return;
241 }
242 if (next.kind === "spawner")
243 {
250 {
244 if (next.spawnerKind === "item")
251 if (next.spawnerKind === "item")
245 { tool = { kind: "spawner", spawnerKind: "item" }; }
252 { tool = { kind: "spawner", spawnerKind: "item" }; }
246 else
253 else
247 { tool = { kind: "spawner", mobTypeId: next.mobTypeId }; }
254 { tool = { kind: "spawner", mobTypeId: next.mobTypeId }; }
248 return;
249 }
255 }
250 const layer = next.kind === "ground" ? "ground" : "block";
256 else
251 const def = next.kind === "ground" ? GROUND_DEFINITIONS[next.typeId] : BLOCK_DEFINITIONS[next.typeId];
257 {
252 tool = {
258 const layer = next.kind === "ground" ? "ground" : "block";
253 kind: next.kind,
259 const def = next.kind === "ground" ? GROUND_DEFINITIONS[next.typeId] : BLOCK_DEFINITIONS[next.typeId];
254 typeId: next.typeId,
260 tool = {
255 state: next.state ?? defaultStateForType(catalog, layer, def.key)
261 kind: next.kind,
256 };
262 typeId: next.typeId,
263 state: next.state ?? defaultStateForType(catalog, layer, def.key)
264 };
265 }
266 notifyToolChanged();
257}
267}
258
268
259function placeableToolState ()
269function placeableToolState ()
@@ -942,6 +952,7 @@ function syncDimensionUi ()
942 { openToggle.disabled = softDeleted; }
952 { openToggle.disabled = softDeleted; }
943 dimensionPicker?.setValue(selectedDimensionId);
953 dimensionPicker?.setValue(selectedDimensionId);
944 dimensionSettings?.refresh();
954 dimensionSettings?.refresh();
955 palettePanel?.sync();
945 syncSaveButton();
956 syncSaveButton();
946}
957}
947
958
@@ -1550,30 +1561,34 @@ async function main ()
1550 view.setGraphicsPrefs(loadGraphicsSettings());
1561 view.setGraphicsPrefs(loadGraphicsSettings());
1551 syncSeasonControls(view.worldSeason ?? seasonIdAt());
1562 syncSeasonControls(view.worldSeason ?? seasonIdAt());
1552 layoutScene();
1563 layoutScene();
1553 selectTool(tool);
1554 $("tool").textContent = selectedToolLabel();
1555
1564
1556 paletteModal = initPaletteModal({
1565 function editorImageUrl (name)
1557 catalog,
1566 {
1558 imageUrlFor (name)
1567 const sprite = game.images[name];
1568 const html = sprite?.g_image;
1569 if (html && typeof html.toDataURL === "function")
1559 {
1570 {
1560 const sprite = game.images[name];
1571 try
1561 const html = sprite?.g_image;
1572 { return html.toDataURL("image/png"); }
1562 if (html && typeof html.toDataURL === "function")
1573 catch (_)
1563 {
1574 { /* fall through */ }
1564 try
1575 }
1565 { return html.toDataURL("image/png"); }
1576 return imageUrlByName.get(name) ?? null;
1566 catch (_)
1577 }
1567 { /* fall through */ }
1578
1568 }
1579 const paletteOptions = {
1569 return imageUrlByName.get(name) ?? null;
1580 catalog,
1570 },
1581 imageUrlFor: editorImageUrl,
1582 getSelection: () => tool,
1583 getDimensionId: () => selectedDimensionId,
1571 onSelect (next)
1584 onSelect (next)
1572 {
1585 {
1573 selectTool(next);
1586 selectTool(next);
1574 $("tool").textContent = selectedToolLabel();
1575 }
1587 }
1576 });
1588 };
1589 palettePanel = initPalettePanel(paletteOptions);
1590 paletteModal = initPaletteModal(paletteOptions);
1591 selectTool(tool);
1577
1592
1578 tileConfigModal = initTileConfigModal({
1593 tileConfigModal = initTileConfigModal({
1579 socket: {
1594 socket: {
@@ -2125,7 +2140,6 @@ $("tool").textContent = selectedToolLabel();
2125$("tool-erase").addEventListener("click", () =>
2140$("tool-erase").addEventListener("click", () =>
2126{
2141{
2127 selectTool({ kind: "erase" });
2142 selectTool({ kind: "erase" });
2128 $("tool").textContent = selectedToolLabel();
2129});
2143});
2130
2144
2131$("north").addEventListener("click", () => loadNeighborhood(chunkX, chunkY - 1));
2145$("north").addEventListener("click", () => loadNeighborhood(chunkX, chunkY - 1));
@@ -2375,7 +2389,7 @@ function cycleToolState (direction)
2375 if (states.length < 2)
2389 if (states.length < 2)
2376 { return; }
2390 { return; }
2377 tool.state = cycleState(states, tool.state, direction);
2391 tool.state = cycleState(states, tool.state, direction);
2378 $("tool").textContent = selectedToolLabel();
2392 notifyToolChanged();
2379 const season = seasonIdFromVisualState(tool.state);
2393 const season = seasonIdFromVisualState(tool.state);
2380 if (season)
2394 if (season)
2381 { applySeasonPreview(season); }
2395 { applySeasonPreview(season); }
client/src/editor/paletteCard.js added +51 −0
@@ -0,0 +1,51 @@
1 /**
2 * One placeable card (sprite thumb + name), shared by the sidebar and the modal.
3 */
4 export function createPaletteCard ({ label, url, key, selected = false, onClick })
5 {
6 const button = document.createElement("button");
7 button.type = "button";
8 button.className = "palette-card";
9 button.title = label;
10 button.dataset.paletteKey = key ?? "";
11 button.setAttribute("aria-pressed", selected ? "true" : "false");
12 if (selected)
13 { button.classList.add("selected"); }
14
15 const thumb = document.createElement("div");
16 thumb.className = "palette-thumb";
17 if (url)
18 {
19 const img = document.createElement("img");
20 img.alt = "";
21 img.src = url;
22 img.onerror = () =>
23 {
24 img.remove();
25 thumb.textContent = label.slice(0, 1);
26 };
27 thumb.append(img);
28 }
29 else
30 { thumb.textContent = label.slice(0, 1); }
31
32 const caption = document.createElement("span");
33 caption.textContent = label;
34 button.append(thumb, caption);
35 button.addEventListener("click", onClick);
36 return button;
37 }
38
39 /** First sprite name that resolves to a URL. */
40 export function firstSpriteUrl (names, imageUrlFor)
41 {
42 if (typeof imageUrlFor !== "function")
43 { return null; }
44 for (const name of names ?? [])
45 {
46 const url = imageUrlFor(name);
47 if (url)
48 { return url; }
49 }
50 return null;
51 }
@@ -0,0 +1,51 @@
1/**
2 * One placeable card (sprite thumb + name), shared by the sidebar and the modal.
3 */
4export function createPaletteCard ({ label, url, key, selected = false, onClick })
5{
6 const button = document.createElement("button");
7 button.type = "button";
8 button.className = "palette-card";
9 button.title = label;
10 button.dataset.paletteKey = key ?? "";
11 button.setAttribute("aria-pressed", selected ? "true" : "false");
12 if (selected)
13 { button.classList.add("selected"); }
14
15 const thumb = document.createElement("div");
16 thumb.className = "palette-thumb";
17 if (url)
18 {
19 const img = document.createElement("img");
20 img.alt = "";
21 img.src = url;
22 img.onerror = () =>
23 {
24 img.remove();
25 thumb.textContent = label.slice(0, 1);
26 };
27 thumb.append(img);
28 }
29 else
30 { thumb.textContent = label.slice(0, 1); }
31
32 const caption = document.createElement("span");
33 caption.textContent = label;
34 button.append(thumb, caption);
35 button.addEventListener("click", onClick);
36 return button;
37}
38
39/** First sprite name that resolves to a URL. */
40export function firstSpriteUrl (names, imageUrlFor)
41{
42 if (typeof imageUrlFor !== "function")
43 { return null; }
44 for (const name of names ?? [])
45 {
46 const url = imageUrlFor(name);
47 if (url)
48 { return url; }
49 }
50 return null;
51}
client/src/editor/paletteEntries.js added +159 −0
@@ -0,0 +1,159 @@
1 import { listPlaceableGrounds, listPlaceableBlockPaletteEntries } from "../../../shared/definitions/tiles.js";
2 import { listSpawnableMobTypes, mobSpriteName } from "../../../shared/definitions/mobs.js";
3 import
4 {
5 defaultStateForType,
6 resolveState,
7 spriteImageName,
8 palettePreviewImageName
9 } from "../../../shared/definitions/tileSprites.js";
10 import { itemSpawnerPreviewSpriteName } from "../../../shared/definitions/itemSpawners.js";
11
12 /**
13 * Sidebar / modal categories. Labels match the existing Select placeable dialog.
14 */
15 export const PALETTE_TABS = Object.freeze([
16 { id: "grounds", label: "Ground tiles" },
17 { id: "blocks", label: "Blocks" },
18 { id: "spawners", label: "Spawners" }
19 ]);
20
21 /**
22 * Placeable cards for one palette category, built from the live registries.
23 *
24 * Tile, block, and mob registries are shared by every dimension (a cave can
25 * place the same grounds and spawners as the overworld). `dimensionId` is
26 * part of the query so the editor re-lists for the dimension being edited
27 * instead of freezing an overworld-only snapshot.
28 *
29 * @param {"grounds"|"blocks"|"spawners"} tabId
30 * @param {{ catalog?: object|null, dimensionId?: string|null }} [context]
31 * @returns {{ key: string, label: string, spriteNames: string[], selection: object }[]}
32 */
33 export function listPaletteEntries (tabId, context = {})
34 {
35 const catalog = context.catalog ?? null;
36 // Accepted so callers bind this list to the dimension currently open.
37 // Nothing in the registries is dimension-scoped today.
38 void context.dimensionId;
39
40 if (tabId === "grounds")
41 { return listGroundEntries(catalog); }
42 if (tabId === "blocks")
43 { return listBlockEntries(catalog); }
44 if (tabId === "spawners")
45 { return listSpawnerEntries(); }
46 return [];
47 }
48
49 /**
50 * Case-insensitive name filter used by the palette search box.
51 * @param {string} label
52 * @param {string} query
53 */
54 export function paletteLabelMatches (label, query)
55 {
56 const q = String(query ?? "").trim().toLowerCase();
57 if (!q)
58 { return true; }
59 return String(label ?? "").toLowerCase().includes(q);
60 }
61
62 /**
63 * Keys of visible cards that represent the active placement tool.
64 * A single card for a type stays highlighted when the editor cycles a visual
65 * state that is not its own card (seasonal grounds, one tree sprite, …).
66 * Types with several cards (ores, herbs, doors) highlight only the exact state.
67 *
68 * @param {ReturnType<typeof listPaletteEntries>} visibleEntries
69 * @param {ReturnType<typeof listPaletteEntries>} allEntries
70 * @param {object|null} tool
71 * @returns {Set<string>}
72 */
73 export function matchingPaletteEntryKeys (visibleEntries, allEntries, tool)
74 {
75 const pool = Array.isArray(allEntries) ? allEntries : (visibleEntries ?? []);
76 const visibleKeys = new Set((visibleEntries ?? []).map((entry) => entry.key));
77 let matched = pool.filter((entry) => paletteEntryMatchesTool(entry, tool));
78 if (!matched.length && tool && (tool.kind === "ground" || tool.kind === "block"))
79 {
80 const sameType = pool.filter((entry) =>
81 entry.selection?.kind === tool.kind && entry.selection?.typeId === tool.typeId
82 );
83 if (sameType.length === 1)
84 { matched = sameType; }
85 }
86 return new Set(matched.map((entry) => entry.key).filter((key) => visibleKeys.has(key)));
87 }
88
89 function paletteEntryMatchesTool (entry, tool)
90 {
91 const selection = entry?.selection;
92 if (!selection || !tool || selection.kind !== tool.kind)
93 { return false; }
94 if (selection.kind === "ground")
95 { return selection.typeId === tool.typeId; }
96 if (selection.kind === "block")
97 { return selection.typeId === tool.typeId && selection.state === tool.state; }
98 if (selection.kind === "spawner")
99 {
100 if (selection.spawnerKind === "item")
101 { return tool.spawnerKind === "item"; }
102 return tool.spawnerKind !== "item" && selection.mobTypeId === tool.mobTypeId;
103 }
104 return false;
105 }
106
107 function listGroundEntries (catalog)
108 {
109 const entries = [];
110 for (const def of listPlaceableGrounds())
111 {
112 const state = defaultStateForType(catalog, "ground", def.key);
113 const name = spriteImageName("ground", def.key, resolveState(
114 catalog?.grounds?.[def.key]?.states ?? [],
115 state
116 ));
117 entries.push({
118 key: `ground:${def.id}`,
119 label: def.displayName,
120 spriteNames: [palettePreviewImageName("ground", def.key), name],
121 selection: { kind: "ground", typeId: def.id }
122 });
123 }
124 return entries;
125 }
126
127 function listBlockEntries (catalog)
128 {
129 return listPlaceableBlockPaletteEntries(catalog).map((entry) => ({
130 key: `block:${entry.typeId}:${entry.state ?? ""}`,
131 label: entry.displayName,
132 spriteNames: [entry.spriteName],
133 selection: {
134 kind: "block",
135 typeId: entry.typeId,
136 state: entry.state
137 }
138 }));
139 }
140
141 function listSpawnerEntries ()
142 {
143 const entries = [{
144 key: "spawner:item",
145 label: "Item Spawner",
146 spriteNames: [itemSpawnerPreviewSpriteName()],
147 selection: { kind: "spawner", spawnerKind: "item" }
148 }];
149 for (const def of listSpawnableMobTypes())
150 {
151 entries.push({
152 key: `spawner:${def.mobTypeId}`,
153 label: def.displayName,
154 spriteNames: [mobSpriteName(def.mobTypeId)],
155 selection: { kind: "spawner", mobTypeId: def.mobTypeId }
156 });
157 }
158 return entries;
159 }
@@ -0,0 +1,159 @@
1import { listPlaceableGrounds, listPlaceableBlockPaletteEntries } from "../../../shared/definitions/tiles.js";
2import { listSpawnableMobTypes, mobSpriteName } from "../../../shared/definitions/mobs.js";
3import
4{
5 defaultStateForType,
6 resolveState,
7 spriteImageName,
8 palettePreviewImageName
9} from "../../../shared/definitions/tileSprites.js";
10import { itemSpawnerPreviewSpriteName } from "../../../shared/definitions/itemSpawners.js";
11
12/**
13 * Sidebar / modal categories. Labels match the existing Select placeable dialog.
14 */
15export const PALETTE_TABS = Object.freeze([
16 { id: "grounds", label: "Ground tiles" },
17 { id: "blocks", label: "Blocks" },
18 { id: "spawners", label: "Spawners" }
19]);
20
21/**
22 * Placeable cards for one palette category, built from the live registries.
23 *
24 * Tile, block, and mob registries are shared by every dimension (a cave can
25 * place the same grounds and spawners as the overworld). `dimensionId` is
26 * part of the query so the editor re-lists for the dimension being edited
27 * instead of freezing an overworld-only snapshot.
28 *
29 * @param {"grounds"|"blocks"|"spawners"} tabId
30 * @param {{ catalog?: object|null, dimensionId?: string|null }} [context]
31 * @returns {{ key: string, label: string, spriteNames: string[], selection: object }[]}
32 */
33export function listPaletteEntries (tabId, context = {})
34{
35 const catalog = context.catalog ?? null;
36 // Accepted so callers bind this list to the dimension currently open.
37 // Nothing in the registries is dimension-scoped today.
38 void context.dimensionId;
39
40 if (tabId === "grounds")
41 { return listGroundEntries(catalog); }
42 if (tabId === "blocks")
43 { return listBlockEntries(catalog); }
44 if (tabId === "spawners")
45 { return listSpawnerEntries(); }
46 return [];
47}
48
49/**
50 * Case-insensitive name filter used by the palette search box.
51 * @param {string} label
52 * @param {string} query
53 */
54export function paletteLabelMatches (label, query)
55{
56 const q = String(query ?? "").trim().toLowerCase();
57 if (!q)
58 { return true; }
59 return String(label ?? "").toLowerCase().includes(q);
60}
61
62/**
63 * Keys of visible cards that represent the active placement tool.
64 * A single card for a type stays highlighted when the editor cycles a visual
65 * state that is not its own card (seasonal grounds, one tree sprite, …).
66 * Types with several cards (ores, herbs, doors) highlight only the exact state.
67 *
68 * @param {ReturnType<typeof listPaletteEntries>} visibleEntries
69 * @param {ReturnType<typeof listPaletteEntries>} allEntries
70 * @param {object|null} tool
71 * @returns {Set<string>}
72 */
73export function matchingPaletteEntryKeys (visibleEntries, allEntries, tool)
74{
75 const pool = Array.isArray(allEntries) ? allEntries : (visibleEntries ?? []);
76 const visibleKeys = new Set((visibleEntries ?? []).map((entry) => entry.key));
77 let matched = pool.filter((entry) => paletteEntryMatchesTool(entry, tool));
78 if (!matched.length && tool && (tool.kind === "ground" || tool.kind === "block"))
79 {
80 const sameType = pool.filter((entry) =>
81 entry.selection?.kind === tool.kind && entry.selection?.typeId === tool.typeId
82 );
83 if (sameType.length === 1)
84 { matched = sameType; }
85 }
86 return new Set(matched.map((entry) => entry.key).filter((key) => visibleKeys.has(key)));
87}
88
89function paletteEntryMatchesTool (entry, tool)
90{
91 const selection = entry?.selection;
92 if (!selection || !tool || selection.kind !== tool.kind)
93 { return false; }
94 if (selection.kind === "ground")
95 { return selection.typeId === tool.typeId; }
96 if (selection.kind === "block")
97 { return selection.typeId === tool.typeId && selection.state === tool.state; }
98 if (selection.kind === "spawner")
99 {
100 if (selection.spawnerKind === "item")
101 { return tool.spawnerKind === "item"; }
102 return tool.spawnerKind !== "item" && selection.mobTypeId === tool.mobTypeId;
103 }
104 return false;
105}
106
107function listGroundEntries (catalog)
108{
109 const entries = [];
110 for (const def of listPlaceableGrounds())
111 {
112 const state = defaultStateForType(catalog, "ground", def.key);
113 const name = spriteImageName("ground", def.key, resolveState(
114 catalog?.grounds?.[def.key]?.states ?? [],
115 state
116 ));
117 entries.push({
118 key: `ground:${def.id}`,
119 label: def.displayName,
120 spriteNames: [palettePreviewImageName("ground", def.key), name],
121 selection: { kind: "ground", typeId: def.id }
122 });
123 }
124 return entries;
125}
126
127function listBlockEntries (catalog)
128{
129 return listPlaceableBlockPaletteEntries(catalog).map((entry) => ({
130 key: `block:${entry.typeId}:${entry.state ?? ""}`,
131 label: entry.displayName,
132 spriteNames: [entry.spriteName],
133 selection: {
134 kind: "block",
135 typeId: entry.typeId,
136 state: entry.state
137 }
138 }));
139}
140
141function listSpawnerEntries ()
142{
143 const entries = [{
144 key: "spawner:item",
145 label: "Item Spawner",
146 spriteNames: [itemSpawnerPreviewSpriteName()],
147 selection: { kind: "spawner", spawnerKind: "item" }
148 }];
149 for (const def of listSpawnableMobTypes())
150 {
151 entries.push({
152 key: `spawner:${def.mobTypeId}`,
153 label: def.displayName,
154 spriteNames: [mobSpriteName(def.mobTypeId)],
155 selection: { kind: "spawner", mobTypeId: def.mobTypeId }
156 });
157 }
158 return entries;
159}
client/src/editor/paletteModal.js +40 −131
@@ -1,12 +1,23 @@
1 import { listPlaceableGrounds, listPlaceableBlockPaletteEntries } from "/shared/definitions/tiles.js";
2 import { listSpawnableMobTypes, mobSpriteName } from "/shared/definitions/mobs.js";
3 import { defaultStateForType, resolveState, spriteImageName, palettePreviewImageName } from "/shared/definitions/tileSprites.js";
4 import { itemSpawnerPreviewSpriteName } from "/shared/definitions/itemSpawners.js";
1 import { OVERWORLD_ID, normalizeDimensionId } from "/shared/world/dimensions.js";
2 import
3 {
4 PALETTE_TABS,
5 listPaletteEntries,
6 paletteLabelMatches,
7 matchingPaletteEntryKeys
8 } from "./paletteEntries.js";
9 import { createPaletteCard, firstSpriteUrl } from "./paletteCard.js";
5 10
6 11 /**
7 12 * Select-tool modal: Ground / Blocks / Spawners, auto-built from definitions.
8 13 */
9 export function initPaletteModal ({ onSelect, catalog, imageUrlFor })
14 export function initPaletteModal ({
15 onSelect,
16 catalog,
17 imageUrlFor,
18 getSelection,
19 getDimensionId
20 })
10 21 {
11 22 const backdrop = document.getElementById("palette-backdrop");
12 23 const modal = document.getElementById("palette-modal");
@@ -17,12 +28,6 @@ export function initPaletteModal ({ onSelect, catalog, imageUrlFor })
17 28 let activeTab = "grounds";
18 29 let searchQuery = "";
19 30
20 const tabsSpec = [
21 { id: "grounds", label: "Ground tiles" },
22 { id: "blocks", label: "Blocks" },
23 { id: "spawners", label: "Spawners" }
24 ];
25
26 31 function show (visible)
27 32 {
28 33 open = visible;
@@ -38,18 +43,10 @@ export function initPaletteModal ({ onSelect, catalog, imageUrlFor })
38 43 }
39 44 }
40 45
41 function matchesSearch (label)
42 {
43 const q = searchQuery.trim().toLowerCase();
44 if (!q)
45 { return true; }
46 return String(label ?? "").toLowerCase().includes(q);
47 }
48
49 46 function render ()
50 47 {
51 48 tabs.innerHTML = "";
52 for (const tab of tabsSpec)
49 for (const tab of PALETTE_TABS)
53 50 {
54 51 const button = document.createElement("button");
55 52 button.type = "button";
@@ -64,87 +61,10 @@ export function initPaletteModal ({ onSelect, catalog, imageUrlFor })
64 61 }
65 62
66 63 panels.innerHTML = "";
67 const grid = document.createElement("div");
68 grid.className = "palette-grid";
69 let shown = 0;
70 if (activeTab === "grounds")
71 {
72 for (const def of listPlaceableGrounds())
73 {
74 if (!matchesSearch(def.displayName))
75 { continue; }
76 shown += 1;
77 const state = defaultStateForType(catalog, "ground", def.key);
78 const name = spriteImageName("ground", def.key, resolveState(
79 catalog.grounds?.[def.key]?.states ?? [],
80 state
81 ));
82 const previewName = palettePreviewImageName("ground", def.key);
83 grid.append(tileCard({
84 label: def.displayName,
85 url: imageUrlFor?.(previewName) ?? imageUrlFor?.(name),
86 onClick ()
87 {
88 onSelect({ kind: "ground", typeId: def.id });
89 show(false);
90 }
91 }));
92 }
93 }
94 else if (activeTab === "blocks")
95 {
96 for (const entry of listPlaceableBlockPaletteEntries(catalog))
97 {
98 if (!matchesSearch(entry.displayName))
99 { continue; }
100 shown += 1;
101 grid.append(tileCard({
102 label: entry.displayName,
103 url: imageUrlFor?.(entry.spriteName),
104 onClick ()
105 {
106 onSelect({
107 kind: "block",
108 typeId: entry.typeId,
109 state: entry.state
110 });
111 show(false);
112 }
113 }));
114 }
115 }
116 else
117 {
118 if (matchesSearch("Item Spawner"))
119 {
120 shown += 1;
121 grid.append(tileCard({
122 label: "Item Spawner",
123 url: imageUrlFor?.(itemSpawnerPreviewSpriteName()),
124 onClick ()
125 {
126 onSelect({ kind: "spawner", spawnerKind: "item" });
127 show(false);
128 }
129 }));
130 }
131 for (const def of listSpawnableMobTypes())
132 {
133 if (!matchesSearch(def.displayName))
134 { continue; }
135 shown += 1;
136 grid.append(tileCard({
137 label: def.displayName,
138 url: imageUrlFor?.(mobSpriteName(def.mobTypeId)),
139 onClick ()
140 {
141 onSelect({ kind: "spawner", mobTypeId: def.mobTypeId });
142 show(false);
143 }
144 }));
145 }
146 }
147 if (shown === 0)
64 const dimensionId = normalizeDimensionId(getDimensionId?.() ?? OVERWORLD_ID);
65 const all = listPaletteEntries(activeTab, { catalog, dimensionId });
66 const visible = all.filter((entry) => paletteLabelMatches(entry.label, searchQuery));
67 if (!visible.length)
148 68 {
149 69 const empty = document.createElement("p");
150 70 empty.className = "hint";
@@ -152,9 +72,26 @@ export function initPaletteModal ({ onSelect, catalog, imageUrlFor })
152 72 ? "No matches for that search."
153 73 : "Nothing to show.";
154 74 panels.append(empty);
75 return;
76 }
77 const selected = matchingPaletteEntryKeys(visible, all, getSelection?.() ?? null);
78 const grid = document.createElement("div");
79 grid.className = "palette-grid";
80 for (const entry of visible)
81 {
82 grid.append(createPaletteCard({
83 label: entry.label,
84 url: firstSpriteUrl(entry.spriteNames, imageUrlFor),
85 key: entry.key,
86 selected: selected.has(entry.key),
87 onClick ()
88 {
89 onSelect(entry.selection);
90 show(false);
91 }
92 }));
155 93 }
156 else
157 { panels.append(grid); }
94 panels.append(grid);
158 95 }
159 96
160 97 document.getElementById("open-palette").addEventListener("click", () => show(true));
@@ -171,31 +108,3 @@ export function initPaletteModal ({ onSelect, catalog, imageUrlFor })
171 108 close: () => show(false)
172 109 };
173 110 }
174
175 function tileCard ({ label, url, onClick })
176 {
177 const button = document.createElement("button");
178 button.type = "button";
179 button.className = "palette-card";
180 const thumb = document.createElement("div");
181 thumb.className = "palette-thumb";
182 if (url)
183 {
184 const img = document.createElement("img");
185 img.alt = "";
186 img.src = url;
187 img.onerror = () =>
188 {
189 img.remove();
190 thumb.textContent = label.slice(0, 1);
191 };
192 thumb.append(img);
193 }
194 else
195 { thumb.textContent = label.slice(0, 1); }
196 const caption = document.createElement("span");
197 caption.textContent = label;
198 button.append(thumb, caption);
199 button.addEventListener("click", onClick);
200 return button;
201 }
@@ -1,12 +1,23 @@
1import { listPlaceableGrounds, listPlaceableBlockPaletteEntries } from "/shared/definitions/tiles.js";
1import { OVERWORLD_ID, normalizeDimensionId } from "/shared/world/dimensions.js";
2import { listSpawnableMobTypes, mobSpriteName } from "/shared/definitions/mobs.js";
2import
3import { defaultStateForType, resolveState, spriteImageName, palettePreviewImageName } from "/shared/definitions/tileSprites.js";
3{
4import { itemSpawnerPreviewSpriteName } from "/shared/definitions/itemSpawners.js";
4 PALETTE_TABS,
5 listPaletteEntries,
6 paletteLabelMatches,
7 matchingPaletteEntryKeys
8} from "./paletteEntries.js";
9import { createPaletteCard, firstSpriteUrl } from "./paletteCard.js";
5
10
6/**
11/**
7 * Select-tool modal: Ground / Blocks / Spawners, auto-built from definitions.
12 * Select-tool modal: Ground / Blocks / Spawners, auto-built from definitions.
8 */
13 */
9export function initPaletteModal ({ onSelect, catalog, imageUrlFor })
14export function initPaletteModal ({
15 onSelect,
16 catalog,
17 imageUrlFor,
18 getSelection,
19 getDimensionId
20})
10{
21{
11 const backdrop = document.getElementById("palette-backdrop");
22 const backdrop = document.getElementById("palette-backdrop");
12 const modal = document.getElementById("palette-modal");
23 const modal = document.getElementById("palette-modal");
@@ -17,12 +28,6 @@ export function initPaletteModal ({ onSelect, catalog, imageUrlFor })
17 let activeTab = "grounds";
28 let activeTab = "grounds";
18 let searchQuery = "";
29 let searchQuery = "";
19
30
20 const tabsSpec = [
21 { id: "grounds", label: "Ground tiles" },
22 { id: "blocks", label: "Blocks" },
23 { id: "spawners", label: "Spawners" }
24 ];
25
26 function show (visible)
31 function show (visible)
27 {
32 {
28 open = visible;
33 open = visible;
@@ -38,18 +43,10 @@ export function initPaletteModal ({ onSelect, catalog, imageUrlFor })
38 }
43 }
39 }
44 }
40
45
41 function matchesSearch (label)
42 {
43 const q = searchQuery.trim().toLowerCase();
44 if (!q)
45 { return true; }
46 return String(label ?? "").toLowerCase().includes(q);
47 }
48
49 function render ()
46 function render ()
50 {
47 {
51 tabs.innerHTML = "";
48 tabs.innerHTML = "";
52 for (const tab of tabsSpec)
49 for (const tab of PALETTE_TABS)
53 {
50 {
54 const button = document.createElement("button");
51 const button = document.createElement("button");
55 button.type = "button";
52 button.type = "button";
@@ -64,87 +61,10 @@ export function initPaletteModal ({ onSelect, catalog, imageUrlFor })
64 }
61 }
65
62
66 panels.innerHTML = "";
63 panels.innerHTML = "";
67 const grid = document.createElement("div");
64 const dimensionId = normalizeDimensionId(getDimensionId?.() ?? OVERWORLD_ID);
68 grid.className = "palette-grid";
65 const all = listPaletteEntries(activeTab, { catalog, dimensionId });
69 let shown = 0;
66 const visible = all.filter((entry) => paletteLabelMatches(entry.label, searchQuery));
70 if (activeTab === "grounds")
67 if (!visible.length)
71 {
72 for (const def of listPlaceableGrounds())
73 {
74 if (!matchesSearch(def.displayName))
75 { continue; }
76 shown += 1;
77 const state = defaultStateForType(catalog, "ground", def.key);
78 const name = spriteImageName("ground", def.key, resolveState(
79 catalog.grounds?.[def.key]?.states ?? [],
80 state
81 ));
82 const previewName = palettePreviewImageName("ground", def.key);
83 grid.append(tileCard({
84 label: def.displayName,
85 url: imageUrlFor?.(previewName) ?? imageUrlFor?.(name),
86 onClick ()
87 {
88 onSelect({ kind: "ground", typeId: def.id });
89 show(false);
90 }
91 }));
92 }
93 }
94 else if (activeTab === "blocks")
95 {
96 for (const entry of listPlaceableBlockPaletteEntries(catalog))
97 {
98 if (!matchesSearch(entry.displayName))
99 { continue; }
100 shown += 1;
101 grid.append(tileCard({
102 label: entry.displayName,
103 url: imageUrlFor?.(entry.spriteName),
104 onClick ()
105 {
106 onSelect({
107 kind: "block",
108 typeId: entry.typeId,
109 state: entry.state
110 });
111 show(false);
112 }
113 }));
114 }
115 }
116 else
117 {
118 if (matchesSearch("Item Spawner"))
119 {
120 shown += 1;
121 grid.append(tileCard({
122 label: "Item Spawner",
123 url: imageUrlFor?.(itemSpawnerPreviewSpriteName()),
124 onClick ()
125 {
126 onSelect({ kind: "spawner", spawnerKind: "item" });
127 show(false);
128 }
129 }));
130 }
131 for (const def of listSpawnableMobTypes())
132 {
133 if (!matchesSearch(def.displayName))
134 { continue; }
135 shown += 1;
136 grid.append(tileCard({
137 label: def.displayName,
138 url: imageUrlFor?.(mobSpriteName(def.mobTypeId)),
139 onClick ()
140 {
141 onSelect({ kind: "spawner", mobTypeId: def.mobTypeId });
142 show(false);
143 }
144 }));
145 }
146 }
147 if (shown === 0)
148 {
68 {
149 const empty = document.createElement("p");
69 const empty = document.createElement("p");
150 empty.className = "hint";
70 empty.className = "hint";
@@ -152,9 +72,26 @@ export function initPaletteModal ({ onSelect, catalog, imageUrlFor })
152 ? "No matches for that search."
72 ? "No matches for that search."
153 : "Nothing to show.";
73 : "Nothing to show.";
154 panels.append(empty);
74 panels.append(empty);
75 return;
76 }
77 const selected = matchingPaletteEntryKeys(visible, all, getSelection?.() ?? null);
78 const grid = document.createElement("div");
79 grid.className = "palette-grid";
80 for (const entry of visible)
81 {
82 grid.append(createPaletteCard({
83 label: entry.label,
84 url: firstSpriteUrl(entry.spriteNames, imageUrlFor),
85 key: entry.key,
86 selected: selected.has(entry.key),
87 onClick ()
88 {
89 onSelect(entry.selection);
90 show(false);
91 }
92 }));
155 }
93 }
156 else
94 panels.append(grid);
157 { panels.append(grid); }
158 }
95 }
159
96
160 document.getElementById("open-palette").addEventListener("click", () => show(true));
97 document.getElementById("open-palette").addEventListener("click", () => show(true));
@@ -171,31 +108,3 @@ export function initPaletteModal ({ onSelect, catalog, imageUrlFor })
171 close: () => show(false)
108 close: () => show(false)
172 };
109 };
173}
110}
174
175function tileCard ({ label, url, onClick })
176{
177 const button = document.createElement("button");
178 button.type = "button";
179 button.className = "palette-card";
180 const thumb = document.createElement("div");
181 thumb.className = "palette-thumb";
182 if (url)
183 {
184 const img = document.createElement("img");
185 img.alt = "";
186 img.src = url;
187 img.onerror = () =>
188 {
189 img.remove();
190 thumb.textContent = label.slice(0, 1);
191 };
192 thumb.append(img);
193 }
194 else
195 { thumb.textContent = label.slice(0, 1); }
196 const caption = document.createElement("span");
197 caption.textContent = label;
198 button.append(thumb, caption);
199 button.addEventListener("click", onClick);
200 return button;
201}
client/src/editor/palettePanel.js added +161 −0
@@ -0,0 +1,161 @@
1 import { OVERWORLD_ID, normalizeDimensionId } from "/shared/world/dimensions.js";
2 import
3 {
4 PALETTE_TABS,
5 listPaletteEntries,
6 paletteLabelMatches,
7 matchingPaletteEntryKeys
8 } from "./paletteEntries.js";
9 import { createPaletteCard, firstSpriteUrl } from "./paletteCard.js";
10
11 /**
12 * Right-sidebar placeable browser. Picking a card calls `onSelect` with the
13 * same payload as the Select placeable modal (`selectTool` in the editor).
14 */
15 export function initPalettePanel ({
16 onSelect,
17 catalog,
18 imageUrlFor,
19 getSelection,
20 getDimensionId
21 })
22 {
23 const searchInput = document.getElementById("palette-panel-search");
24 const tabsEl = document.getElementById("palette-panel-tabs");
25 const resultsEl = document.getElementById("palette-panel-results");
26 let activeTab = PALETTE_TABS[0].id;
27 let searchQuery = "";
28 let renderedSignature = "";
29 /** @type {ReturnType<typeof listPaletteEntries>} */
30 let allEntries = [];
31 /** @type {ReturnType<typeof listPaletteEntries>} */
32 let visibleEntries = [];
33
34 function dimensionId ()
35 {
36 return normalizeDimensionId(getDimensionId?.() ?? OVERWORLD_ID);
37 }
38
39 function updateTabStyles ()
40 {
41 if (!tabsEl)
42 { return; }
43 const buttons = tabsEl.querySelectorAll("[data-palette-tab]");
44 for (const button of buttons)
45 {
46 const on = button.dataset.paletteTab === activeTab;
47 button.classList.toggle("active", on);
48 button.setAttribute("aria-selected", on ? "true" : "false");
49 }
50 }
51
52 function renderTabs ()
53 {
54 if (!tabsEl)
55 { return; }
56 tabsEl.replaceChildren();
57 for (const tab of PALETTE_TABS)
58 {
59 const button = document.createElement("button");
60 button.type = "button";
61 button.className = "settings-tab";
62 button.dataset.paletteTab = tab.id;
63 button.id = `palette-tab-${tab.id}`;
64 button.setAttribute("role", "tab");
65 button.textContent = tab.label;
66 button.addEventListener("click", () =>
67 {
68 if (activeTab === tab.id)
69 { return; }
70 activeTab = tab.id;
71 updateTabStyles();
72 renderList();
73 });
74 tabsEl.append(button);
75 }
76 updateTabStyles();
77 }
78
79 function paintGrid ()
80 {
81 if (!resultsEl)
82 { return; }
83 resultsEl.replaceChildren();
84 if (!visibleEntries.length)
85 {
86 const empty = document.createElement("p");
87 empty.className = "hint";
88 empty.textContent = searchQuery.trim()
89 ? "No matches for that search."
90 : "Nothing to show.";
91 resultsEl.append(empty);
92 return;
93 }
94 const selected = matchingPaletteEntryKeys(visibleEntries, allEntries, getSelection?.() ?? null);
95 const grid = document.createElement("div");
96 grid.className = "palette-grid";
97 for (const entry of visibleEntries)
98 {
99 grid.append(createPaletteCard({
100 label: entry.label,
101 url: firstSpriteUrl(entry.spriteNames, imageUrlFor),
102 key: entry.key,
103 selected: selected.has(entry.key),
104 onClick ()
105 {
106 onSelect?.(entry.selection);
107 }
108 }));
109 }
110 resultsEl.append(grid);
111 }
112
113 function applyHighlight ()
114 {
115 if (!resultsEl)
116 { return; }
117 const selected = matchingPaletteEntryKeys(visibleEntries, allEntries, getSelection?.() ?? null);
118 for (const card of resultsEl.querySelectorAll(".palette-card"))
119 {
120 const on = selected.has(card.dataset.paletteKey);
121 card.classList.toggle("selected", on);
122 card.setAttribute("aria-pressed", on ? "true" : "false");
123 }
124 }
125
126 function renderList ()
127 {
128 const dim = dimensionId();
129 allEntries = listPaletteEntries(activeTab, { catalog, dimensionId: dim });
130 visibleEntries = allEntries.filter((entry) => paletteLabelMatches(entry.label, searchQuery));
131 const signature = [
132 dim,
133 activeTab,
134 searchQuery,
135 visibleEntries.map((entry) => `${entry.key}\t${entry.spriteNames.join(",")}`).join("\n")
136 ].join("\u0000");
137 if (signature !== renderedSignature)
138 {
139 renderedSignature = signature;
140 paintGrid();
141 return;
142 }
143 applyHighlight();
144 }
145
146 renderTabs();
147 searchInput?.addEventListener("input", () =>
148 {
149 searchQuery = searchInput.value ?? "";
150 renderList();
151 });
152 renderList();
153
154 return {
155 /** Re-read the active tool and the dimension being edited. */
156 sync ()
157 {
158 renderList();
159 }
160 };
161 }
@@ -0,0 +1,161 @@
1import { OVERWORLD_ID, normalizeDimensionId } from "/shared/world/dimensions.js";
2import
3{
4 PALETTE_TABS,
5 listPaletteEntries,
6 paletteLabelMatches,
7 matchingPaletteEntryKeys
8} from "./paletteEntries.js";
9import { createPaletteCard, firstSpriteUrl } from "./paletteCard.js";
10
11/**
12 * Right-sidebar placeable browser. Picking a card calls `onSelect` with the
13 * same payload as the Select placeable modal (`selectTool` in the editor).
14 */
15export function initPalettePanel ({
16 onSelect,
17 catalog,
18 imageUrlFor,
19 getSelection,
20 getDimensionId
21})
22{
23 const searchInput = document.getElementById("palette-panel-search");
24 const tabsEl = document.getElementById("palette-panel-tabs");
25 const resultsEl = document.getElementById("palette-panel-results");
26 let activeTab = PALETTE_TABS[0].id;
27 let searchQuery = "";
28 let renderedSignature = "";
29 /** @type {ReturnType<typeof listPaletteEntries>} */
30 let allEntries = [];
31 /** @type {ReturnType<typeof listPaletteEntries>} */
32 let visibleEntries = [];
33
34 function dimensionId ()
35 {
36 return normalizeDimensionId(getDimensionId?.() ?? OVERWORLD_ID);
37 }
38
39 function updateTabStyles ()
40 {
41 if (!tabsEl)
42 { return; }
43 const buttons = tabsEl.querySelectorAll("[data-palette-tab]");
44 for (const button of buttons)
45 {
46 const on = button.dataset.paletteTab === activeTab;
47 button.classList.toggle("active", on);
48 button.setAttribute("aria-selected", on ? "true" : "false");
49 }
50 }
51
52 function renderTabs ()
53 {
54 if (!tabsEl)
55 { return; }
56 tabsEl.replaceChildren();
57 for (const tab of PALETTE_TABS)
58 {
59 const button = document.createElement("button");
60 button.type = "button";
61 button.className = "settings-tab";
62 button.dataset.paletteTab = tab.id;
63 button.id = `palette-tab-${tab.id}`;
64 button.setAttribute("role", "tab");
65 button.textContent = tab.label;
66 button.addEventListener("click", () =>
67 {
68 if (activeTab === tab.id)
69 { return; }
70 activeTab = tab.id;
71 updateTabStyles();
72 renderList();
73 });
74 tabsEl.append(button);
75 }
76 updateTabStyles();
77 }
78
79 function paintGrid ()
80 {
81 if (!resultsEl)
82 { return; }
83 resultsEl.replaceChildren();
84 if (!visibleEntries.length)
85 {
86 const empty = document.createElement("p");
87 empty.className = "hint";
88 empty.textContent = searchQuery.trim()
89 ? "No matches for that search."
90 : "Nothing to show.";
91 resultsEl.append(empty);
92 return;
93 }
94 const selected = matchingPaletteEntryKeys(visibleEntries, allEntries, getSelection?.() ?? null);
95 const grid = document.createElement("div");
96 grid.className = "palette-grid";
97 for (const entry of visibleEntries)
98 {
99 grid.append(createPaletteCard({
100 label: entry.label,
101 url: firstSpriteUrl(entry.spriteNames, imageUrlFor),
102 key: entry.key,
103 selected: selected.has(entry.key),
104 onClick ()
105 {
106 onSelect?.(entry.selection);
107 }
108 }));
109 }
110 resultsEl.append(grid);
111 }
112
113 function applyHighlight ()
114 {
115 if (!resultsEl)
116 { return; }
117 const selected = matchingPaletteEntryKeys(visibleEntries, allEntries, getSelection?.() ?? null);
118 for (const card of resultsEl.querySelectorAll(".palette-card"))
119 {
120 const on = selected.has(card.dataset.paletteKey);
121 card.classList.toggle("selected", on);
122 card.setAttribute("aria-pressed", on ? "true" : "false");
123 }
124 }
125
126 function renderList ()
127 {
128 const dim = dimensionId();
129 allEntries = listPaletteEntries(activeTab, { catalog, dimensionId: dim });
130 visibleEntries = allEntries.filter((entry) => paletteLabelMatches(entry.label, searchQuery));
131 const signature = [
132 dim,
133 activeTab,
134 searchQuery,
135 visibleEntries.map((entry) => `${entry.key}\t${entry.spriteNames.join(",")}`).join("\n")
136 ].join("\u0000");
137 if (signature !== renderedSignature)
138 {
139 renderedSignature = signature;
140 paintGrid();
141 return;
142 }
143 applyHighlight();
144 }
145
146 renderTabs();
147 searchInput?.addEventListener("input", () =>
148 {
149 searchQuery = searchInput.value ?? "";
150 renderList();
151 });
152 renderList();
153
154 return {
155 /** Re-read the active tool and the dimension being edited. */
156 sync ()
157 {
158 renderList();
159 }
160 };
161}
client/tests/palette-entries.test.js added +124 −0
@@ -0,0 +1,124 @@
1 import test from "node:test";
2 import assert from "node:assert/strict";
3 import
4 {
5 BlockType,
6 GroundType,
7 listPlaceableBlockPaletteEntries,
8 listPlaceableGrounds
9 } from "../../shared/definitions/tiles.js";
10 import { listSpawnableMobTypes } from "../../shared/definitions/mobs.js";
11 import { OVERWORLD_ID } from "../../shared/world/dimensions.js";
12 import
13 {
14 PALETTE_TABS,
15 listPaletteEntries,
16 matchingPaletteEntryKeys,
17 paletteLabelMatches
18 } from "../src/editor/paletteEntries.js";
19
20 test("palette categories match the editor placeable dialog", () =>
21 {
22 assert.deepEqual(
23 PALETTE_TABS.map((tab) => tab.label),
24 ["Ground tiles", "Blocks", "Spawners"]
25 );
26 });
27
28 test("palette entries are the live registries in every dimension", () =>
29 {
30 const overworldGrounds = listPaletteEntries("grounds", { dimensionId: OVERWORLD_ID });
31 const caveGrounds = listPaletteEntries("grounds", { dimensionId: "void-hall" });
32 assert.equal(overworldGrounds.length, listPlaceableGrounds().length);
33 assert.ok(caveGrounds.length > 0);
34 assert.deepEqual(
35 caveGrounds.map((entry) => entry.key),
36 overworldGrounds.map((entry) => entry.key)
37 );
38 assert.equal(caveGrounds[0].selection.kind, "ground");
39
40 const blocks = listPaletteEntries("blocks", { dimensionId: "cave-1" });
41 const fromRegistry = listPlaceableBlockPaletteEntries(null);
42 assert.equal(blocks.length, fromRegistry.length);
43 assert.deepEqual(
44 blocks.map((entry) => entry.label),
45 fromRegistry.map((entry) => entry.displayName)
46 );
47 assert.equal(blocks.every((entry) => entry.selection.kind === "block"), true);
48
49 const spawners = listPaletteEntries("spawners", { dimensionId: "house" });
50 assert.equal(spawners[0].label, "Item Spawner");
51 assert.deepEqual(spawners[0].selection, { kind: "spawner", spawnerKind: "item" });
52 assert.equal(spawners.length, 1 + listSpawnableMobTypes().length);
53 assert.deepEqual(
54 spawners.slice(1).map((entry) => entry.label),
55 listSpawnableMobTypes().map((def) => def.displayName)
56 );
57 });
58
59 test("palette highlight follows the active placement", () =>
60 {
61 const grounds = listPaletteEntries("grounds", { dimensionId: "cave-1" });
62 const grass = grounds.find((entry) => entry.selection.typeId === GroundType.grass);
63 assert.ok(grass);
64 assert.deepEqual(
65 [...matchingPaletteEntryKeys(grounds, grounds, {
66 kind: "ground",
67 typeId: GroundType.grass,
68 state: "winter"
69 })],
70 [grass.key]
71 );
72 assert.equal(
73 matchingPaletteEntryKeys(grounds, grounds, { kind: "erase" }).size,
74 0
75 );
76
77 const blocks = listPaletteEntries("blocks", { dimensionId: OVERWORLD_ID });
78 const boulders = blocks.filter((entry) => entry.selection.typeId === BlockType.boulder);
79 assert.ok(boulders.length > 1);
80 assert.deepEqual(
81 [...matchingPaletteEntryKeys(blocks, blocks, boulders[1].selection)],
82 [boulders[1].key]
83 );
84 assert.equal(
85 matchingPaletteEntryKeys(blocks, blocks, {
86 kind: "block",
87 typeId: BlockType.boulder,
88 state: "not-a-palette-card"
89 }).size,
90 0
91 );
92
93 const wall = blocks.find((entry) => entry.selection.typeId === BlockType.stoneWall);
94 assert.ok(wall);
95 assert.deepEqual(
96 [...matchingPaletteEntryKeys(blocks, blocks, {
97 kind: "block",
98 typeId: BlockType.stoneWall,
99 state: "cycled-visual"
100 })],
101 [wall.key]
102 );
103
104 const spawners = listPaletteEntries("spawners", { dimensionId: "house" });
105 assert.deepEqual(
106 [...matchingPaletteEntryKeys(spawners, spawners, { kind: "spawner", spawnerKind: "item" })],
107 ["spawner:item"]
108 );
109 const deer = spawners.find((entry) => entry.selection.mobTypeId === "deer");
110 assert.ok(deer);
111 const deerKeys = matchingPaletteEntryKeys(spawners, spawners, {
112 kind: "spawner",
113 mobTypeId: "deer"
114 });
115 assert.equal(deerKeys.has(deer.key), true);
116 assert.equal(deerKeys.has("spawner:item"), false);
117 });
118
119 test("palette search matches names without case", () =>
120 {
121 assert.equal(paletteLabelMatches("Deep water", ""), true);
122 assert.equal(paletteLabelMatches("Deep water", " WATER "), true);
123 assert.equal(paletteLabelMatches("Deep water", "lava"), false);
124 });
@@ -0,0 +1,124 @@
1import test from "node:test";
2import assert from "node:assert/strict";
3import
4{
5 BlockType,
6 GroundType,
7 listPlaceableBlockPaletteEntries,
8 listPlaceableGrounds
9} from "../../shared/definitions/tiles.js";
10import { listSpawnableMobTypes } from "../../shared/definitions/mobs.js";
11import { OVERWORLD_ID } from "../../shared/world/dimensions.js";
12import
13{
14 PALETTE_TABS,
15 listPaletteEntries,
16 matchingPaletteEntryKeys,
17 paletteLabelMatches
18} from "../src/editor/paletteEntries.js";
19
20test("palette categories match the editor placeable dialog", () =>
21{
22 assert.deepEqual(
23 PALETTE_TABS.map((tab) => tab.label),
24 ["Ground tiles", "Blocks", "Spawners"]
25 );
26});
27
28test("palette entries are the live registries in every dimension", () =>
29{
30 const overworldGrounds = listPaletteEntries("grounds", { dimensionId: OVERWORLD_ID });
31 const caveGrounds = listPaletteEntries("grounds", { dimensionId: "void-hall" });
32 assert.equal(overworldGrounds.length, listPlaceableGrounds().length);
33 assert.ok(caveGrounds.length > 0);
34 assert.deepEqual(
35 caveGrounds.map((entry) => entry.key),
36 overworldGrounds.map((entry) => entry.key)
37 );
38 assert.equal(caveGrounds[0].selection.kind, "ground");
39
40 const blocks = listPaletteEntries("blocks", { dimensionId: "cave-1" });
41 const fromRegistry = listPlaceableBlockPaletteEntries(null);
42 assert.equal(blocks.length, fromRegistry.length);
43 assert.deepEqual(
44 blocks.map((entry) => entry.label),
45 fromRegistry.map((entry) => entry.displayName)
46 );
47 assert.equal(blocks.every((entry) => entry.selection.kind === "block"), true);
48
49 const spawners = listPaletteEntries("spawners", { dimensionId: "house" });
50 assert.equal(spawners[0].label, "Item Spawner");
51 assert.deepEqual(spawners[0].selection, { kind: "spawner", spawnerKind: "item" });
52 assert.equal(spawners.length, 1 + listSpawnableMobTypes().length);
53 assert.deepEqual(
54 spawners.slice(1).map((entry) => entry.label),
55 listSpawnableMobTypes().map((def) => def.displayName)
56 );
57});
58
59test("palette highlight follows the active placement", () =>
60{
61 const grounds = listPaletteEntries("grounds", { dimensionId: "cave-1" });
62 const grass = grounds.find((entry) => entry.selection.typeId === GroundType.grass);
63 assert.ok(grass);
64 assert.deepEqual(
65 [...matchingPaletteEntryKeys(grounds, grounds, {
66 kind: "ground",
67 typeId: GroundType.grass,
68 state: "winter"
69 })],
70 [grass.key]
71 );
72 assert.equal(
73 matchingPaletteEntryKeys(grounds, grounds, { kind: "erase" }).size,
74 0
75 );
76
77 const blocks = listPaletteEntries("blocks", { dimensionId: OVERWORLD_ID });
78 const boulders = blocks.filter((entry) => entry.selection.typeId === BlockType.boulder);
79 assert.ok(boulders.length > 1);
80 assert.deepEqual(
81 [...matchingPaletteEntryKeys(blocks, blocks, boulders[1].selection)],
82 [boulders[1].key]
83 );
84 assert.equal(
85 matchingPaletteEntryKeys(blocks, blocks, {
86 kind: "block",
87 typeId: BlockType.boulder,
88 state: "not-a-palette-card"
89 }).size,
90 0
91 );
92
93 const wall = blocks.find((entry) => entry.selection.typeId === BlockType.stoneWall);
94 assert.ok(wall);
95 assert.deepEqual(
96 [...matchingPaletteEntryKeys(blocks, blocks, {
97 kind: "block",
98 typeId: BlockType.stoneWall,
99 state: "cycled-visual"
100 })],
101 [wall.key]
102 );
103
104 const spawners = listPaletteEntries("spawners", { dimensionId: "house" });
105 assert.deepEqual(
106 [...matchingPaletteEntryKeys(spawners, spawners, { kind: "spawner", spawnerKind: "item" })],
107 ["spawner:item"]
108 );
109 const deer = spawners.find((entry) => entry.selection.mobTypeId === "deer");
110 assert.ok(deer);
111 const deerKeys = matchingPaletteEntryKeys(spawners, spawners, {
112 kind: "spawner",
113 mobTypeId: "deer"
114 });
115 assert.equal(deerKeys.has(deer.key), true);
116 assert.equal(deerKeys.has("spawner:item"), false);
117});
118
119test("palette search matches names without case", () =>
120{
121 assert.equal(paletteLabelMatches("Deep water", ""), true);
122 assert.equal(paletteLabelMatches("Deep water", " WATER "), true);
123 assert.equal(paletteLabelMatches("Deep water", "lava"), false);
124});
client/ui/editor.css +60 −2
@@ -112,7 +112,9 @@ body>aside {
112 112 border-radius: 0;
113 113 background: transparent;
114 114 color: #9aa3b2;
115 padding: 0.55rem 0.4rem;
115 padding: 0.55rem 0.2rem;
116 font-size: 0.82rem;
117 white-space: nowrap;
116 118 cursor: pointer;
117 119 }
118 120
@@ -130,6 +132,50 @@ body>aside {
130 132 box-sizing: border-box;
131 133 }
132 134
135 #palette-wrap.palette-panel {
136 display: flex;
137 flex-direction: column;
138 padding: 0;
139 overflow: hidden;
140 }
141
142 #palette-wrap[hidden] {
143 display: none !important;
144 }
145
146 .palette-panel .settings-tabs {
147 padding: 0.45rem 0.5rem 0.4rem;
148 background: transparent;
149 }
150
151 .palette-panel .settings-tab {
152 padding: 0.28rem 0.45rem;
153 font-size: 0.78rem;
154 }
155
156 .palette-panel .palette-search {
157 margin: 0.55rem 0.65rem 0;
158 width: calc(100% - 1.3rem);
159 box-sizing: border-box;
160 }
161
162 #palette-panel-results {
163 flex: 1 1 auto;
164 min-height: 0;
165 overflow: auto;
166 padding: 0.65rem;
167 }
168
169 #palette-panel-results .palette-grid {
170 grid-template-columns: repeat(auto-fill, minmax(6.4rem, 1fr));
171 }
172
173 #palette-panel-results .palette-card {
174 min-height: 5.5rem;
175 padding: 0.4rem 0.3rem;
176 font-size: 0.78rem;
177 }
178
133 179 #editor-console {
134 180 margin: 0;
135 181 padding: 0.4rem;
@@ -1086,7 +1132,7 @@ label {
1086 1132 border-bottom: 1px solid #2c3340;
1087 1133 }
1088 1134
1089 #palette-search {
1135 .palette-search {
1090 1136 margin: 0.65rem 1rem 0;
1091 1137 padding: 0.45rem 0.65rem;
1092 1138 border: 1px solid #2c3340;
@@ -1122,6 +1168,18 @@ label {
1122 1168 min-height: 6.5rem;
1123 1169 }
1124 1170
1171 .palette-card > span {
1172 text-align: center;
1173 line-height: 1.25;
1174 word-break: break-word;
1175 }
1176
1177 .palette-card.selected {
1178 border-color: #6a8cbf;
1179 background: #243044;
1180 box-shadow: inset 0 0 0 1px #6a8cbf;
1181 }
1182
1125 1183 .palette-thumb {
1126 1184 width: 48px;
1127 1185 height: 48px;
@@ -112,7 +112,9 @@ body>aside {
112 border-radius: 0;
112 border-radius: 0;
113 background: transparent;
113 background: transparent;
114 color: #9aa3b2;
114 color: #9aa3b2;
115 padding: 0.55rem 0.4rem;
115 padding: 0.55rem 0.2rem;
116 font-size: 0.82rem;
117 white-space: nowrap;
116 cursor: pointer;
118 cursor: pointer;
117}
119}
118
120
@@ -130,6 +132,50 @@ body>aside {
130 box-sizing: border-box;
132 box-sizing: border-box;
131}
133}
132
134
135#palette-wrap.palette-panel {
136 display: flex;
137 flex-direction: column;
138 padding: 0;
139 overflow: hidden;
140}
141
142#palette-wrap[hidden] {
143 display: none !important;
144}
145
146.palette-panel .settings-tabs {
147 padding: 0.45rem 0.5rem 0.4rem;
148 background: transparent;
149}
150
151.palette-panel .settings-tab {
152 padding: 0.28rem 0.45rem;
153 font-size: 0.78rem;
154}
155
156.palette-panel .palette-search {
157 margin: 0.55rem 0.65rem 0;
158 width: calc(100% - 1.3rem);
159 box-sizing: border-box;
160}
161
162#palette-panel-results {
163 flex: 1 1 auto;
164 min-height: 0;
165 overflow: auto;
166 padding: 0.65rem;
167}
168
169#palette-panel-results .palette-grid {
170 grid-template-columns: repeat(auto-fill, minmax(6.4rem, 1fr));
171}
172
173#palette-panel-results .palette-card {
174 min-height: 5.5rem;
175 padding: 0.4rem 0.3rem;
176 font-size: 0.78rem;
177}
178
133#editor-console {
179#editor-console {
134 margin: 0;
180 margin: 0;
135 padding: 0.4rem;
181 padding: 0.4rem;
@@ -1086,7 +1132,7 @@ label {
1086 border-bottom: 1px solid #2c3340;
1132 border-bottom: 1px solid #2c3340;
1087}
1133}
1088
1134
1089#palette-search {
1135.palette-search {
1090 margin: 0.65rem 1rem 0;
1136 margin: 0.65rem 1rem 0;
1091 padding: 0.45rem 0.65rem;
1137 padding: 0.45rem 0.65rem;
1092 border: 1px solid #2c3340;
1138 border: 1px solid #2c3340;
@@ -1122,6 +1168,18 @@ label {
1122 min-height: 6.5rem;
1168 min-height: 6.5rem;
1123}
1169}
1124
1170
1171.palette-card > span {
1172 text-align: center;
1173 line-height: 1.25;
1174 word-break: break-word;
1175}
1176
1177.palette-card.selected {
1178 border-color: #6a8cbf;
1179 background: #243044;
1180 box-shadow: inset 0 0 0 1px #6a8cbf;
1181}
1182
1125.palette-thumb {
1183.palette-thumb {
1126 width: 48px;
1184 width: 48px;
1127 height: 48px;
1185 height: 48px;