BlueGit

timfa questward

Files

questward / client / src / editor / tileConfigModal.js

tileConfigModal.js

tileConfigModal.js 15.3 KiB Download Raw
1/**
2 * Right-click config modal for editor tiles that have configurable data (spawners).
3 */
4import {
5 listSpawnableMobTypes,
6 normalizeSpawnerConfig,
7 MobId,
8 isHumanoidMob,
9 isCentralExchangeSpawner
10} from "/shared/definitions/mobs.js";
11import { centralExchangeStaffCount } from "/shared/market/exchange.js";
12import { ITEM_DEFINITIONS, itemDefinition } from "/shared/definitions/items.js";
13import { EQUIPMENT_SLOTS } from "/shared/items/inventory.js";
14import { listNpcShopSellableItems } from "/shared/shop/pricing.js";
15
16/** Items that can be worn in a given equipment slot. */
17export function listEquippableItemsForSlot (slot)
18{
19 const out = [];
20 for (const def of Object.values(ITEM_DEFINITIONS))
21 {
22 if (!def?.equipment || def.equipment.slot !== slot)
23 { continue; }
24 out.push({
25 itemId: def.itemId,
26 key: def.key ?? String(def.itemId),
27 displayName: def.displayName ?? `Item ${def.itemId}`
28 });
29 }
30 out.sort((a, b) => a.displayName.localeCompare(b.displayName));
31 return out;
32}
33
34export function initTileConfigModal ({ onSave, onRemove })
35{
36 const backdrop = document.getElementById("tile-config-backdrop");
37 const modal = document.getElementById("tile-config-modal");
38 const form = document.getElementById("tile-config-form");
39 const title = document.getElementById("tile-config-title");
40 const itemSearchBackdrop = document.getElementById("shop-item-search-backdrop");
41 const itemSearchModal = document.getElementById("shop-item-search-modal");
42 const itemSearchTitle = itemSearchModal?.querySelector("h2") ?? null;
43 const itemSearchInput = document.getElementById("shop-item-search-input");
44 const itemSearchResults = document.getElementById("shop-item-search-results");
45 let open = false;
46 let context = null;
47 /** @type {{ itemId: number, quantity: number }[]} */
48 let sellsDraft = [];
49 /** @type {Record<string, number|null>} */
50 let equipmentDraft = {};
51 /** @type {{ kind: "sells" } | { kind: "equip", slot: string } | null} */
52 let itemSearchMode = null;
53
54 function show (visible)
55 {
56 open = visible;
57 backdrop.hidden = !visible;
58 modal.hidden = !visible;
59 if (!visible)
60 {
61 context = null;
62 closeItemSearch();
63 }
64 }
65
66 function closeItemSearch ()
67 {
68 itemSearchMode = null;
69 if (itemSearchBackdrop)
70 { itemSearchBackdrop.hidden = true; }
71 if (itemSearchModal)
72 { itemSearchModal.hidden = true; }
73 }
74
75 function openSellItemSearch ()
76 {
77 itemSearchMode = { kind: "sells" };
78 openItemSearch("Add shop stock");
79 }
80
81 function openEquipItemSearch (slot)
82 {
83 itemSearchMode = { kind: "equip", slot };
84 openItemSearch(`Equip ${slot}`);
85 }
86
87 function openItemSearch (heading)
88 {
89 if (!itemSearchBackdrop || !itemSearchModal || !itemSearchInput)
90 { return; }
91 if (itemSearchTitle)
92 { itemSearchTitle.textContent = heading ?? "Choose item"; }
93 itemSearchInput.value = "";
94 itemSearchInput.placeholder = itemSearchMode?.kind === "equip"
95 ? "Search equipment…"
96 : "Search items…";
97 renderItemSearchResults("");
98 itemSearchBackdrop.hidden = false;
99 itemSearchModal.hidden = false;
100 itemSearchInput.focus();
101 }
102
103 function candidateItems ()
104 {
105 if (itemSearchMode?.kind === "equip")
106 { return listEquippableItemsForSlot(itemSearchMode.slot); }
107 return listNpcShopSellableItems();
108 }
109
110 function renderItemSearchResults (query)
111 {
112 if (!itemSearchResults)
113 { return; }
114 itemSearchResults.innerHTML = "";
115 const q = String(query ?? "").trim().toLowerCase();
116 const taken = itemSearchMode?.kind === "sells"
117 ? new Set(sellsDraft.map((line) => line.itemId))
118 : null;
119 const matches = candidateItems().filter((item) =>
120 {
121 if (taken?.has(item.itemId))
122 { return false; }
123 if (!q)
124 { return true; }
125 return item.displayName.toLowerCase().includes(q) || item.key.toLowerCase().includes(q);
126 }).slice(0, 120);
127 if (!matches.length)
128 {
129 itemSearchResults.textContent = "No matching items.";
130 return;
131 }
132 for (const item of matches)
133 {
134 const row = document.createElement("button");
135 row.type = "button";
136 row.className = "shop-item-search-row";
137 row.textContent = item.displayName;
138 row.addEventListener("click", () =>
139 {
140 if (itemSearchMode?.kind === "equip")
141 {
142 equipmentDraft[itemSearchMode.slot] = item.itemId;
143 renderEquipmentRows();
144 }
145 else
146 {
147 sellsDraft.push({ itemId: item.itemId, quantity: 0 });
148 renderSellsList();
149 }
150 closeItemSearch();
151 });
152 itemSearchResults.append(row);
153 }
154 }
155
156 function renderSellsList ()
157 {
158 const list = form.querySelector("[data-sells-list]");
159 if (!list)
160 { return; }
161 list.innerHTML = "";
162 if (!sellsDraft.length)
163 {
164 const empty = document.createElement("p");
165 empty.className = "hint";
166 empty.textContent = "No items yet. Use + to add stock.";
167 list.append(empty);
168 return;
169 }
170 for (let index = 0; index < sellsDraft.length; index++)
171 {
172 const line = sellsDraft[index];
173 const def = itemDefinition(line.itemId);
174 const row = document.createElement("div");
175 row.className = "spawner-sells-row";
176 const name = document.createElement("span");
177 name.className = "spawner-sells-name";
178 name.textContent = def?.displayName ?? `Item ${line.itemId}`;
179 const qty = document.createElement("input");
180 qty.type = "number";
181 qty.min = "0";
182 qty.step = "1";
183 qty.value = String(line.quantity | 0);
184 qty.title = "0 = infinite; otherwise restocks this many at 00:00 server time";
185 qty.addEventListener("input", () =>
186 {
187 sellsDraft[index].quantity = Math.max(0, Number(qty.value) || 0) | 0;
188 });
189 const remove = document.createElement("button");
190 remove.type = "button";
191 remove.textContent = "Remove";
192 remove.addEventListener("click", () =>
193 {
194 sellsDraft.splice(index, 1);
195 renderSellsList();
196 });
197 row.append(name, qty, remove);
198 list.append(row);
199 }
200 }
201
202 function renderEquipmentRows ()
203 {
204 const list = form.querySelector("[data-equipment-list]");
205 if (!list)
206 { return; }
207 list.innerHTML = "";
208 for (const slot of EQUIPMENT_SLOTS)
209 {
210 const itemId = equipmentDraft[slot] ?? null;
211 const def = itemId ? itemDefinition(itemId) : null;
212 const row = document.createElement("div");
213 row.className = "spawner-equip-row";
214 const label = document.createElement("span");
215 label.className = "spawner-equip-slot";
216 label.textContent = slot;
217 const name = document.createElement("span");
218 name.className = "spawner-equip-name";
219 name.textContent = def?.displayName ?? "(none)";
220 const pick = document.createElement("button");
221 pick.type = "button";
222 pick.textContent = "Choose…";
223 pick.addEventListener("click", () => openEquipItemSearch(slot));
224 const clear = document.createElement("button");
225 clear.type = "button";
226 clear.textContent = "Clear";
227 clear.disabled = itemId == null;
228 clear.addEventListener("click", () =>
229 {
230 equipmentDraft[slot] = null;
231 renderEquipmentRows();
232 });
233 row.append(label, name, pick, clear);
234 list.append(row);
235 }
236 }
237
238 function renderHumanoidFields (config)
239 {
240 const wrap = document.createElement("div");
241 wrap.className = "spawner-humanoid-fields";
242 wrap.dataset.humanoid = "1";
243 const exchange = isCentralExchangeSpawner(config);
244 if (exchange)
245 {
246 const note = document.createElement("p");
247 note.className = "hint";
248 note.textContent = `Spawns all ${centralExchangeStaffCount()} Central Exchange clerks (names & sex fixed). Equipment below is shared. No shop interaction.`;
249 wrap.append(note);
250 }
251 else
252 {
253 wrap.append(
254 field("Display name", textInput("displayName", config.displayName || "Shopkeeper")),
255 field("Sex", sexSelect("sex", config.sex))
256 );
257 }
258
259 const equipHeader = document.createElement("div");
260 equipHeader.className = "spawner-sells-header";
261 const equipTitle = document.createElement("strong");
262 equipTitle.textContent = "Equipment";
263 equipHeader.append(equipTitle);
264 wrap.append(equipHeader);
265
266 const equipList = document.createElement("div");
267 equipList.className = "spawner-equip-list";
268 equipList.dataset.equipmentList = "1";
269 wrap.append(equipList);
270
271 equipmentDraft = {};
272 for (const slot of EQUIPMENT_SLOTS)
273 {
274 const raw = config.equipment?.[slot];
275 equipmentDraft[slot] = raw != null && raw !== "" ? Number(raw) || null : null;
276 }
277 queueMicrotask(() => renderEquipmentRows());
278
279 if (!exchange)
280 {
281 wrap.append(field("Hidden discount (0–1)", numberInput("hiddenDiscount", config.hiddenDiscount ?? 0.9, 0.01, 1, 0.01)));
282
283 const sellsHeader = document.createElement("div");
284 sellsHeader.className = "spawner-sells-header";
285 const sellsTitle = document.createElement("strong");
286 sellsTitle.textContent = "Sells";
287 const addBtn = document.createElement("button");
288 addBtn.type = "button";
289 addBtn.textContent = "+";
290 addBtn.title = "Add item";
291 addBtn.addEventListener("click", () => openSellItemSearch());
292 sellsHeader.append(sellsTitle, addBtn);
293 wrap.append(sellsHeader);
294
295 const list = document.createElement("div");
296 list.className = "spawner-sells-list";
297 list.dataset.sellsList = "1";
298 wrap.append(list);
299
300 const buysLabel = document.createElement("label");
301 buysLabel.className = "spawner-buys-row";
302 const buys = document.createElement("input");
303 buys.type = "checkbox";
304 buys.name = "buysItems";
305 buys.checked = !!config.buysItems;
306 buysLabel.append(buys, document.createTextNode(" Buys items"));
307 wrap.append(buysLabel);
308
309 const hint = document.createElement("p");
310 hint.className = "hint";
311 hint.textContent = "Quantity 0 = infinite stock. Limited stock restocks daily at 00:00 server time. Buys items: pays 80% market for transferable bag goods (not blank cheques); filled cheques sell as reserved goods with a 5% admin fee; extras resell at 120% until restock.";
312 wrap.append(hint);
313
314 sellsDraft = (config.sells ?? []).map((line) =>
315 {
316 if (line && typeof line === "object")
317 { return { itemId: line.itemId | 0, quantity: Math.max(0, line.quantity | 0 || 0) }; }
318 return { itemId: line | 0, quantity: 0 };
319 }).filter((line) => line.itemId > 0);
320
321 queueMicrotask(() => renderSellsList());
322 }
323 else
324 { sellsDraft = []; }
325 return wrap;
326 }
327
328 function syncHumanoidSection (config)
329 {
330 form.querySelector("[data-humanoid]")?.remove();
331 const mobTypeId = form.querySelector('[name="mobTypeId"]')?.value;
332 if (!isHumanoidMob(mobTypeId))
333 {
334 sellsDraft = [];
335 equipmentDraft = {};
336 return;
337 }
338 form.append(renderHumanoidFields(config ?? normalizeSpawnerConfig({
339 mobTypeId: mobTypeId || MobId.humanoid
340 }, "spawner")));
341 const maxAlive = form.querySelector('[name="maxAlive"]');
342 if (maxAlive && isCentralExchangeSpawner({ mobTypeId }))
343 {
344 maxAlive.value = String(centralExchangeStaffCount());
345 maxAlive.disabled = true;
346 }
347 else if (maxAlive)
348 { maxAlive.disabled = false; }
349 }
350
351 function openSpawner (ctx)
352 {
353 context = { kind: "spawner", ...ctx };
354 const config = normalizeSpawnerConfig(ctx.config, ctx.config.spawnerId);
355 title.textContent = `Spawner · ${ctx.tileX}, ${ctx.tileY}`;
356 form.innerHTML = "";
357 const mobField = field("Mob type", mobSelect("mobTypeId", config.mobTypeId));
358 form.append(
359 mobField,
360 field("Max alive", numberInput("maxAlive", config.maxAlive, 1, 20)),
361 field("Spawn range", numberInput("spawnRangeTiles", config.spawnRangeTiles, 1, 32)),
362 field("Max wander range", numberInput("maxWanderRangeTiles", config.maxWanderRangeTiles, 1, 64)),
363 field("Spawner id", textInput("spawnerId", config.spawnerId, true))
364 );
365 const spawnInput = form.querySelector('[name="spawnRangeTiles"]');
366 const wanderInput = form.querySelector('[name="maxWanderRangeTiles"]');
367 const syncWanderMin = () =>
368 {
369 const spawn = Number(spawnInput.value) || 1;
370 wanderInput.min = String(spawn);
371 if (Number(wanderInput.value) < spawn)
372 { wanderInput.value = String(spawn); }
373 };
374 spawnInput.addEventListener("input", syncWanderMin);
375 syncWanderMin();
376 form.querySelector('[name="mobTypeId"]').addEventListener("change", () =>
377 {
378 const nextType = form.querySelector('[name="mobTypeId"]').value;
379 const defaults = normalizeSpawnerConfig({ mobTypeId: nextType }, config.spawnerId);
380 form.querySelector('[name="maxAlive"]').value = String(defaults.maxAlive);
381 form.querySelector('[name="spawnRangeTiles"]').value = String(defaults.spawnRangeTiles);
382 form.querySelector('[name="maxWanderRangeTiles"]').value = String(defaults.maxWanderRangeTiles);
383 syncWanderMin();
384 syncHumanoidSection(defaults);
385 });
386 syncHumanoidSection(config);
387 show(true);
388 }
389
390 document.getElementById("tile-config-close").addEventListener("click", () => show(false));
391 document.getElementById("tile-config-cancel").addEventListener("click", () => show(false));
392 backdrop.addEventListener("click", () => show(false));
393 document.getElementById("shop-item-search-close")?.addEventListener("click", () => closeItemSearch());
394 itemSearchBackdrop?.addEventListener("click", () => closeItemSearch());
395 itemSearchInput?.addEventListener("input", () => renderItemSearchResults(itemSearchInput.value));
396
397 document.getElementById("tile-config-save").addEventListener("click", () =>
398 {
399 if (!context)
400 { return; }
401 const data = new FormData(form);
402 const equipment = {};
403 for (const slot of EQUIPMENT_SLOTS)
404 {
405 const raw = equipmentDraft[slot];
406 equipment[slot] = raw != null && raw !== "" ? Number(raw) || null : null;
407 }
408 onSave?.(context, normalizeSpawnerConfig({
409 mobTypeId: String(data.get("mobTypeId") || "deer"),
410 maxAlive: Number(data.get("maxAlive") || 3),
411 spawnRangeTiles: Number(data.get("spawnRangeTiles") || 4),
412 maxWanderRangeTiles: Number(data.get("maxWanderRangeTiles") || 4),
413 spawnerId: String(data.get("spawnerId") || context.config.spawnerId),
414 sex: String(data.get("sex") || "male"),
415 displayName: String(data.get("displayName") || ""),
416 equipment,
417 sells: sellsDraft,
418 buysItems: data.get("buysItems") === "on",
419 hiddenDiscount: Number(data.get("hiddenDiscount") || 0.9),
420 centralExchange: isCentralExchangeSpawner(String(data.get("mobTypeId") || ""))
421 }, context.config.spawnerId));
422 show(false);
423 });
424 document.getElementById("tile-config-remove").addEventListener("click", () =>
425 {
426 if (!context)
427 { return; }
428 onRemove?.(context);
429 show(false);
430 });
431
432 return {
433 isOpen: () => open,
434 openSpawner,
435 close: () => show(false)
436 };
437}
438
439function field (label, input)
440{
441 const wrap = document.createElement("label");
442 wrap.append(document.createTextNode(label), input);
443 return wrap;
444}
445
446function numberInput (name, value, min, max, step = 1)
447{
448 const input = document.createElement("input");
449 input.type = "number";
450 input.name = name;
451 input.min = String(min);
452 input.max = String(max);
453 input.step = String(step);
454 input.value = String(value);
455 return input;
456}
457
458function textInput (name, value, readOnly = false)
459{
460 const input = document.createElement("input");
461 input.type = "text";
462 input.name = name;
463 input.value = String(value ?? "");
464 input.readOnly = readOnly;
465 return input;
466}
467
468function sexSelect (name, value)
469{
470 const select = document.createElement("select");
471 select.name = name;
472 for (const sex of ["male", "female"])
473 {
474 const option = document.createElement("option");
475 option.value = sex;
476 option.textContent = sex;
477 if (sex === value)
478 { option.selected = true; }
479 select.append(option);
480 }
481 return select;
482}
483
484function mobSelect (name, value)
485{
486 const select = document.createElement("select");
487 select.name = name;
488 for (const def of listSpawnableMobTypes())
489 {
490 const option = document.createElement("option");
491 option.value = def.mobTypeId;
492 option.textContent = def.displayName;
493 if (def.mobTypeId === value)
494 { option.selected = true; }
495 select.append(option);
496 }
497 return select;
498}