BlueGit

timfa questward

Files

questward / client / src / editor / tileConfigModal.js

tileConfigModal.js

rweaks
timfa Tim Falken · pushed by timfa · 2 months ago
2b34e2dd History
tileConfigModal.js 13.1 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 { ItemId, itemDefinition, EQUIPMENT_SLOT } from "/shared/definitions/items.js";
13import { EQUIPMENT_SLOTS } from "/shared/items/inventory.js";
14import { listNpcShopSellableItems } from "/shared/shop/pricing.js";
15
16const EQUIP_PRESETS = Object.freeze([
17 { itemId: ItemId.clothShirt, slot: EQUIPMENT_SLOT.chest },
18 { itemId: ItemId.stick, slot: EQUIPMENT_SLOT.weapon },
19 { itemId: ItemId.bronzePickaxe, slot: EQUIPMENT_SLOT.weapon },
20 { itemId: ItemId.bronzeAxe, slot: EQUIPMENT_SLOT.weapon },
21 { itemId: ItemId.lantern, slot: EQUIPMENT_SLOT.offhand }
22]);
23
24export function initTileConfigModal ({ onSave, onRemove })
25{
26 const backdrop = document.getElementById("tile-config-backdrop");
27 const modal = document.getElementById("tile-config-modal");
28 const form = document.getElementById("tile-config-form");
29 const title = document.getElementById("tile-config-title");
30 const itemSearchBackdrop = document.getElementById("shop-item-search-backdrop");
31 const itemSearchModal = document.getElementById("shop-item-search-modal");
32 const itemSearchInput = document.getElementById("shop-item-search-input");
33 const itemSearchResults = document.getElementById("shop-item-search-results");
34 let open = false;
35 let context = null;
36 /** @type {{ itemId: number, quantity: number }[]} */
37 let sellsDraft = [];
38
39 function show (visible)
40 {
41 open = visible;
42 backdrop.hidden = !visible;
43 modal.hidden = !visible;
44 if (!visible)
45 {
46 context = null;
47 closeItemSearch();
48 }
49 }
50
51 function closeItemSearch ()
52 {
53 if (itemSearchBackdrop)
54 { itemSearchBackdrop.hidden = true; }
55 if (itemSearchModal)
56 { itemSearchModal.hidden = true; }
57 }
58
59 function openItemSearch ()
60 {
61 if (!itemSearchBackdrop || !itemSearchModal || !itemSearchInput)
62 { return; }
63 itemSearchInput.value = "";
64 renderItemSearchResults("");
65 itemSearchBackdrop.hidden = false;
66 itemSearchModal.hidden = false;
67 itemSearchInput.focus();
68 }
69
70 function renderItemSearchResults (query)
71 {
72 if (!itemSearchResults)
73 { return; }
74 itemSearchResults.innerHTML = "";
75 const q = String(query ?? "").trim().toLowerCase();
76 const taken = new Set(sellsDraft.map((line) => line.itemId));
77 const matches = listNpcShopSellableItems().filter((item) =>
78 {
79 if (taken.has(item.itemId))
80 { return false; }
81 if (!q)
82 { return true; }
83 return item.displayName.toLowerCase().includes(q) || item.key.toLowerCase().includes(q);
84 }).slice(0, 80);
85 if (!matches.length)
86 {
87 itemSearchResults.textContent = "No matching items.";
88 return;
89 }
90 for (const item of matches)
91 {
92 const row = document.createElement("button");
93 row.type = "button";
94 row.className = "shop-item-search-row";
95 row.textContent = item.displayName;
96 row.addEventListener("click", () =>
97 {
98 sellsDraft.push({ itemId: item.itemId, quantity: 0 });
99 renderSellsList();
100 closeItemSearch();
101 });
102 itemSearchResults.append(row);
103 }
104 }
105
106 function renderSellsList ()
107 {
108 const list = form.querySelector("[data-sells-list]");
109 if (!list)
110 { return; }
111 list.innerHTML = "";
112 if (!sellsDraft.length)
113 {
114 const empty = document.createElement("p");
115 empty.className = "hint";
116 empty.textContent = "No items yet. Use + to add stock.";
117 list.append(empty);
118 return;
119 }
120 for (let index = 0; index < sellsDraft.length; index++)
121 {
122 const line = sellsDraft[index];
123 const def = itemDefinition(line.itemId);
124 const row = document.createElement("div");
125 row.className = "spawner-sells-row";
126 const name = document.createElement("span");
127 name.className = "spawner-sells-name";
128 name.textContent = def?.displayName ?? `Item ${line.itemId}`;
129 const qty = document.createElement("input");
130 qty.type = "number";
131 qty.min = "0";
132 qty.step = "1";
133 qty.value = String(line.quantity | 0);
134 qty.title = "0 = infinite; otherwise restocks this many at 00:00 server time";
135 qty.addEventListener("input", () =>
136 {
137 sellsDraft[index].quantity = Math.max(0, Number(qty.value) || 0) | 0;
138 });
139 const remove = document.createElement("button");
140 remove.type = "button";
141 remove.textContent = "Remove";
142 remove.addEventListener("click", () =>
143 {
144 sellsDraft.splice(index, 1);
145 renderSellsList();
146 });
147 row.append(name, qty, remove);
148 list.append(row);
149 }
150 }
151
152 function renderHumanoidFields (config)
153 {
154 const wrap = document.createElement("div");
155 wrap.className = "spawner-humanoid-fields";
156 wrap.dataset.humanoid = "1";
157 const exchange = isCentralExchangeSpawner(config);
158 if (exchange)
159 {
160 const note = document.createElement("p");
161 note.className = "hint";
162 note.textContent = `Spawns all ${centralExchangeStaffCount()} Central Exchange clerks (names & sex fixed). Equipment below is shared. No shop interaction.`;
163 wrap.append(note);
164 }
165 else
166 {
167 wrap.append(
168 field("Display name", textInput("displayName", config.displayName || "Shopkeeper")),
169 field("Sex", sexSelect("sex", config.sex))
170 );
171 }
172 for (const slot of EQUIPMENT_SLOTS)
173 {
174 wrap.append(field(
175 `Equip ${slot}`,
176 equipSelect(`equipment.${slot}`, slot, config.equipment?.[slot] ?? null)
177 ));
178 }
179 if (!exchange)
180 {
181 wrap.append(field("Hidden discount (0–1)", numberInput("hiddenDiscount", config.hiddenDiscount ?? 0.9, 0.01, 1, 0.01)));
182
183 const sellsHeader = document.createElement("div");
184 sellsHeader.className = "spawner-sells-header";
185 const sellsTitle = document.createElement("strong");
186 sellsTitle.textContent = "Sells";
187 const addBtn = document.createElement("button");
188 addBtn.type = "button";
189 addBtn.textContent = "+";
190 addBtn.title = "Add item";
191 addBtn.addEventListener("click", () => openItemSearch());
192 sellsHeader.append(sellsTitle, addBtn);
193 wrap.append(sellsHeader);
194
195 const list = document.createElement("div");
196 list.className = "spawner-sells-list";
197 list.dataset.sellsList = "1";
198 wrap.append(list);
199
200 const buysLabel = document.createElement("label");
201 buysLabel.className = "spawner-buys-row";
202 const buys = document.createElement("input");
203 buys.type = "checkbox";
204 buys.name = "buysItems";
205 buys.checked = !!config.buysItems;
206 buysLabel.append(buys, document.createTextNode(" Buys items"));
207 wrap.append(buysLabel);
208
209 const hint = document.createElement("p");
210 hint.className = "hint";
211 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.";
212 wrap.append(hint);
213
214 sellsDraft = (config.sells ?? []).map((line) =>
215 {
216 if (line && typeof line === "object")
217 { return { itemId: line.itemId | 0, quantity: Math.max(0, line.quantity | 0 || 0) }; }
218 return { itemId: line | 0, quantity: 0 };
219 }).filter((line) => line.itemId > 0);
220
221 queueMicrotask(() => renderSellsList());
222 }
223 else
224 { sellsDraft = []; }
225 return wrap;
226 }
227
228 function syncHumanoidSection (config)
229 {
230 form.querySelector("[data-humanoid]")?.remove();
231 const mobTypeId = form.querySelector('[name="mobTypeId"]')?.value;
232 if (!isHumanoidMob(mobTypeId))
233 {
234 sellsDraft = [];
235 return;
236 }
237 form.append(renderHumanoidFields(config ?? normalizeSpawnerConfig({
238 mobTypeId: mobTypeId || MobId.humanoid
239 }, "spawner")));
240 const maxAlive = form.querySelector('[name="maxAlive"]');
241 if (maxAlive && isCentralExchangeSpawner({ mobTypeId }))
242 {
243 maxAlive.value = String(centralExchangeStaffCount());
244 maxAlive.disabled = true;
245 }
246 else if (maxAlive)
247 { maxAlive.disabled = false; }
248 }
249
250 function openSpawner (ctx)
251 {
252 context = { kind: "spawner", ...ctx };
253 const config = normalizeSpawnerConfig(ctx.config, ctx.config.spawnerId);
254 title.textContent = `Spawner · ${ctx.tileX}, ${ctx.tileY}`;
255 form.innerHTML = "";
256 const mobField = field("Mob type", mobSelect("mobTypeId", config.mobTypeId));
257 form.append(
258 mobField,
259 field("Max alive", numberInput("maxAlive", config.maxAlive, 1, 20)),
260 field("Spawn range", numberInput("spawnRangeTiles", config.spawnRangeTiles, 1, 32)),
261 field("Max wander range", numberInput("maxWanderRangeTiles", config.maxWanderRangeTiles, 1, 64)),
262 field("Spawner id", textInput("spawnerId", config.spawnerId, true))
263 );
264 const spawnInput = form.querySelector('[name="spawnRangeTiles"]');
265 const wanderInput = form.querySelector('[name="maxWanderRangeTiles"]');
266 const syncWanderMin = () =>
267 {
268 const spawn = Number(spawnInput.value) || 1;
269 wanderInput.min = String(spawn);
270 if (Number(wanderInput.value) < spawn)
271 { wanderInput.value = String(spawn); }
272 };
273 spawnInput.addEventListener("input", syncWanderMin);
274 syncWanderMin();
275 form.querySelector('[name="mobTypeId"]').addEventListener("change", () =>
276 {
277 const nextType = form.querySelector('[name="mobTypeId"]').value;
278 const defaults = normalizeSpawnerConfig({ mobTypeId: nextType }, config.spawnerId);
279 form.querySelector('[name="maxAlive"]').value = String(defaults.maxAlive);
280 form.querySelector('[name="spawnRangeTiles"]').value = String(defaults.spawnRangeTiles);
281 form.querySelector('[name="maxWanderRangeTiles"]').value = String(defaults.maxWanderRangeTiles);
282 syncWanderMin();
283 syncHumanoidSection(defaults);
284 });
285 syncHumanoidSection(config);
286 show(true);
287 }
288
289 document.getElementById("tile-config-close").addEventListener("click", () => show(false));
290 document.getElementById("tile-config-cancel").addEventListener("click", () => show(false));
291 backdrop.addEventListener("click", () => show(false));
292 document.getElementById("shop-item-search-close")?.addEventListener("click", () => closeItemSearch());
293 itemSearchBackdrop?.addEventListener("click", () => closeItemSearch());
294 itemSearchInput?.addEventListener("input", () => renderItemSearchResults(itemSearchInput.value));
295
296 document.getElementById("tile-config-save").addEventListener("click", () =>
297 {
298 if (!context)
299 { return; }
300 const data = new FormData(form);
301 const equipment = {};
302 for (const slot of EQUIPMENT_SLOTS)
303 {
304 const raw = data.get(`equipment.${slot}`);
305 equipment[slot] = raw ? Number(raw) : null;
306 }
307 onSave?.(context, normalizeSpawnerConfig({
308 mobTypeId: String(data.get("mobTypeId") || "deer"),
309 maxAlive: Number(data.get("maxAlive") || 3),
310 spawnRangeTiles: Number(data.get("spawnRangeTiles") || 4),
311 maxWanderRangeTiles: Number(data.get("maxWanderRangeTiles") || 4),
312 spawnerId: String(data.get("spawnerId") || context.config.spawnerId),
313 sex: String(data.get("sex") || "male"),
314 displayName: String(data.get("displayName") || ""),
315 equipment,
316 sells: sellsDraft,
317 buysItems: data.get("buysItems") === "on",
318 hiddenDiscount: Number(data.get("hiddenDiscount") || 0.9),
319 centralExchange: isCentralExchangeSpawner(String(data.get("mobTypeId") || ""))
320 }, context.config.spawnerId));
321 show(false);
322 });
323 document.getElementById("tile-config-remove").addEventListener("click", () =>
324 {
325 if (!context)
326 { return; }
327 onRemove?.(context);
328 show(false);
329 });
330
331 return {
332 isOpen: () => open,
333 openSpawner,
334 close: () => show(false)
335 };
336}
337
338function field (label, input)
339{
340 const wrap = document.createElement("label");
341 wrap.append(document.createTextNode(label), input);
342 return wrap;
343}
344
345function numberInput (name, value, min, max, step = 1)
346{
347 const input = document.createElement("input");
348 input.type = "number";
349 input.name = name;
350 input.min = String(min);
351 input.max = String(max);
352 input.step = String(step);
353 input.value = String(value);
354 return input;
355}
356
357function textInput (name, value, readOnly = false)
358{
359 const input = document.createElement("input");
360 input.type = "text";
361 input.name = name;
362 input.value = String(value ?? "");
363 input.readOnly = readOnly;
364 return input;
365}
366
367function sexSelect (name, value)
368{
369 const select = document.createElement("select");
370 select.name = name;
371 for (const sex of ["male", "female"])
372 {
373 const option = document.createElement("option");
374 option.value = sex;
375 option.textContent = sex;
376 if (sex === value)
377 { option.selected = true; }
378 select.append(option);
379 }
380 return select;
381}
382
383function equipSelect (name, slot, value)
384{
385 const select = document.createElement("select");
386 select.name = name;
387 const none = document.createElement("option");
388 none.value = "";
389 none.textContent = "(none)";
390 select.append(none);
391 for (const preset of EQUIP_PRESETS)
392 {
393 if (preset.slot !== slot)
394 { continue; }
395 const def = itemDefinition(preset.itemId);
396 const option = document.createElement("option");
397 option.value = String(preset.itemId);
398 option.textContent = def?.displayName ?? String(preset.itemId);
399 if (preset.itemId === value)
400 { option.selected = true; }
401 select.append(option);
402 }
403 return select;
404}
405
406function mobSelect (name, value)
407{
408 const select = document.createElement("select");
409 select.name = name;
410 for (const def of listSpawnableMobTypes())
411 {
412 const option = document.createElement("option");
413 option.value = def.mobTypeId;
414 option.textContent = def.displayName;
415 if (def.mobTypeId === value)
416 { option.selected = true; }
417 select.append(option);
418 }
419 return select;
420}