BlueGit

timfa questward

Files

questward / client / src / editor / tileConfigModal.js

tileConfigModal.js

tileConfigModal.js 25.6 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 spawnerEquipmentSlot
11} from "/shared/definitions/mobs.js";
12import { mobSpellCastChancePercent } from "/shared/definitions/mobCombat.js";
13import { SPELL_DEFINITIONS } from "/shared/definitions/spells.js";
14import { centralExchangeStaffCount } from "/shared/market/exchange.js";
15import { ITEM_DEFINITIONS, itemDefinition, isDyeableClothing } from "/shared/definitions/items.js";
16import { EQUIPMENT_SLOTS } from "/shared/items/inventory.js";
17import { listNpcShopSellableItems } from "/shared/shop/pricing.js";
18import { normalizeRgb } from "/shared/render/tint.js";
19
20/** Items that can be worn in a given equipment slot. */
21export function listEquippableItemsForSlot (slot)
22{
23 const out = [];
24 for (const def of Object.values(ITEM_DEFINITIONS))
25 {
26 if (!def?.equipment || def.equipment.slot !== slot)
27 { continue; }
28 out.push({
29 itemId: def.itemId,
30 key: def.key ?? String(def.itemId),
31 displayName: def.displayName ?? `Item ${def.itemId}`
32 });
33 }
34 out.sort((a, b) => a.displayName.localeCompare(b.displayName));
35 return out;
36}
37
38function emptyEquipDraft ()
39{
40 return { itemId: null, dyeColor: null };
41}
42
43function equipDraftFromConfig (raw)
44{
45 const { itemId, dyeColor } = spawnerEquipmentSlot(raw);
46 return {
47 itemId: itemId > 0 ? itemId : null,
48 dyeColor: dyeColor ? normalizeRgb(dyeColor) : null
49 };
50}
51
52function equipConfigFromDraft (draft)
53{
54 const itemId = draft?.itemId;
55 if (itemId == null || itemId === "")
56 { return null; }
57 const id = Number(itemId) || null;
58 if (!id)
59 { return null; }
60 if (draft.dyeColor && isDyeableClothing(id))
61 { return { itemId: id, dyeColor: normalizeRgb(draft.dyeColor) }; }
62 return id;
63}
64
65function rgbToCss (color)
66{
67 const c = normalizeRgb(color, { r: 0.78, g: 0.31, b: 0.47 });
68 return `rgb(${Math.round(c.r * 255)}, ${Math.round(c.g * 255)}, ${Math.round(c.b * 255)})`;
69}
70
71export function initTileConfigModal ({ onSave, onRemove })
72{
73 const backdrop = document.getElementById("tile-config-backdrop");
74 const modal = document.getElementById("tile-config-modal");
75 const form = document.getElementById("tile-config-form");
76 const title = document.getElementById("tile-config-title");
77 const itemSearchBackdrop = document.getElementById("shop-item-search-backdrop");
78 const itemSearchModal = document.getElementById("shop-item-search-modal");
79 const itemSearchTitle = itemSearchModal?.querySelector("h2") ?? null;
80 const itemSearchInput = document.getElementById("shop-item-search-input");
81 const itemSearchResults = document.getElementById("shop-item-search-results");
82 const dyeBackdrop = document.getElementById("equip-dye-backdrop");
83 const dyeModal = document.getElementById("equip-dye-modal");
84 const dyeTitle = document.getElementById("equip-dye-title");
85 const dyePreview = document.getElementById("equip-dye-preview");
86 const dyeR = document.getElementById("equip-dye-r");
87 const dyeG = document.getElementById("equip-dye-g");
88 const dyeB = document.getElementById("equip-dye-b");
89 const dyeRNum = document.getElementById("equip-dye-r-num");
90 const dyeGNum = document.getElementById("equip-dye-g-num");
91 const dyeBNum = document.getElementById("equip-dye-b-num");
92 let open = false;
93 let context = null;
94 /** @type {{ itemId: number, quantity: number }[]} */
95 let sellsDraft = [];
96 /** @type {{ spellId: string, chance: number }[]} */
97 let spellsDraft = [];
98 /** @type {Record<string, { itemId: number|null, dyeColor: {r:number,g:number,b:number}|null }>} */
99 let equipmentDraft = {};
100 /** @type {{ kind: "sells" } | { kind: "equip", slot: string } | { kind: "spells" } | null} */
101 let itemSearchMode = null;
102 /** @type {string|null} */
103 let dyeEditSlot = null;
104
105 function show (visible)
106 {
107 open = visible;
108 backdrop.hidden = !visible;
109 modal.hidden = !visible;
110 if (!visible)
111 {
112 context = null;
113 closeItemSearch();
114 closeDyePicker();
115 }
116 }
117
118 function closeItemSearch ()
119 {
120 itemSearchMode = null;
121 if (itemSearchBackdrop)
122 { itemSearchBackdrop.hidden = true; }
123 if (itemSearchModal)
124 { itemSearchModal.hidden = true; }
125 }
126
127 function openSellItemSearch ()
128 {
129 itemSearchMode = { kind: "sells" };
130 openItemSearch("Add shop stock");
131 }
132
133 function openEquipItemSearch (slot)
134 {
135 itemSearchMode = { kind: "equip", slot };
136 openItemSearch(`Equip ${slot}`);
137 }
138
139 function openItemSearch (heading)
140 {
141 if (!itemSearchBackdrop || !itemSearchModal || !itemSearchInput)
142 { return; }
143 if (itemSearchTitle)
144 { itemSearchTitle.textContent = heading ?? "Choose item"; }
145 itemSearchInput.value = "";
146 itemSearchInput.placeholder = itemSearchMode?.kind === "equip"
147 ? "Search equipment…"
148 : "Search items…";
149 renderItemSearchResults("");
150 itemSearchBackdrop.hidden = false;
151 itemSearchModal.hidden = false;
152 itemSearchInput.focus();
153 }
154
155 function candidateItems ()
156 {
157 if (itemSearchMode?.kind === "equip")
158 { return listEquippableItemsForSlot(itemSearchMode.slot); }
159 return listNpcShopSellableItems();
160 }
161
162 function renderItemSearchResults (query)
163 {
164 if (!itemSearchResults)
165 { return; }
166 itemSearchResults.innerHTML = "";
167 const q = String(query ?? "").trim().toLowerCase();
168 const taken = itemSearchMode?.kind === "sells"
169 ? new Set(sellsDraft.map((line) => line.itemId))
170 : null;
171 const matches = candidateItems().filter((item) =>
172 {
173 if (taken?.has(item.itemId))
174 { return false; }
175 if (!q)
176 { return true; }
177 return item.displayName.toLowerCase().includes(q) || item.key.toLowerCase().includes(q);
178 }).slice(0, 120);
179 if (!matches.length)
180 {
181 itemSearchResults.textContent = "No matching items.";
182 return;
183 }
184 for (const item of matches)
185 {
186 const row = document.createElement("button");
187 row.type = "button";
188 row.className = "shop-item-search-row";
189 row.textContent = item.displayName;
190 row.addEventListener("click", () =>
191 {
192 if (itemSearchMode?.kind === "equip")
193 {
194 equipmentDraft[itemSearchMode.slot] = {
195 itemId: item.itemId,
196 dyeColor: null
197 };
198 renderEquipmentRows();
199 }
200 else
201 {
202 sellsDraft.push({ itemId: item.itemId, quantity: 0 });
203 renderSellsList();
204 }
205 closeItemSearch();
206 });
207 itemSearchResults.append(row);
208 }
209 }
210
211 function closeDyePicker ()
212 {
213 dyeEditSlot = null;
214 if (dyeBackdrop)
215 { dyeBackdrop.hidden = true; }
216 if (dyeModal)
217 { dyeModal.hidden = true; }
218 }
219
220 function readDyeSliders ()
221 {
222 return {
223 r: Math.min(255, Math.max(0, Number(dyeR?.value) || 0)) / 255,
224 g: Math.min(255, Math.max(0, Number(dyeG?.value) || 0)) / 255,
225 b: Math.min(255, Math.max(0, Number(dyeB?.value) || 0)) / 255
226 };
227 }
228
229 function syncDyePreview ()
230 {
231 const color = readDyeSliders();
232 if (dyePreview)
233 { dyePreview.style.background = rgbToCss(color); }
234 if (dyeRNum)
235 { dyeRNum.value = String(Math.round(color.r * 255)); }
236 if (dyeGNum)
237 { dyeGNum.value = String(Math.round(color.g * 255)); }
238 if (dyeBNum)
239 { dyeBNum.value = String(Math.round(color.b * 255)); }
240 }
241
242 function setDyeSliders (color)
243 {
244 const c = normalizeRgb(color, { r: 200 / 255, g: 80 / 255, b: 120 / 255 });
245 const r = Math.round(c.r * 255);
246 const g = Math.round(c.g * 255);
247 const b = Math.round(c.b * 255);
248 if (dyeR)
249 { dyeR.value = String(r); }
250 if (dyeG)
251 { dyeG.value = String(g); }
252 if (dyeB)
253 { dyeB.value = String(b); }
254 syncDyePreview();
255 }
256
257 function openDyePicker (slot)
258 {
259 const draft = equipmentDraft[slot];
260 if (!draft?.itemId || !isDyeableClothing(draft.itemId) || !dyeModal || !dyeBackdrop)
261 { return; }
262 dyeEditSlot = slot;
263 const def = itemDefinition(draft.itemId);
264 if (dyeTitle)
265 { dyeTitle.textContent = `Dye — ${def?.displayName ?? slot}`; }
266 setDyeSliders(draft.dyeColor ?? { r: 200 / 255, g: 80 / 255, b: 120 / 255 });
267 dyeBackdrop.hidden = false;
268 dyeModal.hidden = false;
269 }
270
271 function bindDyeChannel (range, num)
272 {
273 range?.addEventListener("input", () =>
274 {
275 if (num)
276 { num.value = range.value; }
277 syncDyePreview();
278 });
279 num?.addEventListener("input", () =>
280 {
281 const v = Math.min(255, Math.max(0, Number(num.value) || 0));
282 num.value = String(v);
283 if (range)
284 { range.value = String(v); }
285 syncDyePreview();
286 });
287 }
288
289 bindDyeChannel(dyeR, dyeRNum);
290 bindDyeChannel(dyeG, dyeGNum);
291 bindDyeChannel(dyeB, dyeBNum);
292
293 function renderSellsList ()
294 {
295 const list = form.querySelector("[data-sells-list]");
296 if (!list)
297 { return; }
298 list.innerHTML = "";
299 if (!sellsDraft.length)
300 {
301 const empty = document.createElement("p");
302 empty.className = "hint";
303 empty.textContent = "No items yet. Use + to add stock.";
304 list.append(empty);
305 return;
306 }
307 for (let index = 0; index < sellsDraft.length; index++)
308 {
309 const line = sellsDraft[index];
310 const def = itemDefinition(line.itemId);
311 const row = document.createElement("div");
312 row.className = "spawner-sells-row";
313 const name = document.createElement("span");
314 name.className = "spawner-sells-name";
315 name.textContent = def?.displayName ?? `Item ${line.itemId}`;
316 const qty = document.createElement("input");
317 qty.type = "number";
318 qty.min = "0";
319 qty.step = "1";
320 qty.value = String(line.quantity | 0);
321 qty.title = "0 = infinite; otherwise restocks this many at 00:00 server time";
322 qty.addEventListener("input", () =>
323 {
324 sellsDraft[index].quantity = Math.max(0, Number(qty.value) || 0) | 0;
325 });
326 const remove = document.createElement("button");
327 remove.type = "button";
328 remove.textContent = "Remove";
329 remove.addEventListener("click", () =>
330 {
331 sellsDraft.splice(index, 1);
332 renderSellsList();
333 });
334 row.append(name, qty, remove);
335 list.append(row);
336 }
337 }
338
339 function renderEquipmentRows ()
340 {
341 const list = form.querySelector("[data-equipment-list]");
342 if (!list)
343 { return; }
344 list.innerHTML = "";
345 for (const slot of EQUIPMENT_SLOTS)
346 {
347 const draft = equipmentDraft[slot] ?? emptyEquipDraft();
348 const itemId = draft.itemId ?? null;
349 const def = itemId ? itemDefinition(itemId) : null;
350 const dyeable = itemId != null && isDyeableClothing(itemId);
351 const row = document.createElement("div");
352 row.className = "spawner-equip-row";
353 const label = document.createElement("span");
354 label.className = "spawner-equip-slot";
355 label.textContent = slot;
356 const name = document.createElement("span");
357 name.className = "spawner-equip-name";
358 if (def && draft.dyeColor)
359 {
360 const swatch = document.createElement("span");
361 swatch.className = "spawner-equip-dye-swatch";
362 swatch.style.background = rgbToCss(draft.dyeColor);
363 name.append(swatch, document.createTextNode(def.displayName));
364 }
365 else
366 { name.textContent = def?.displayName ?? "(none)"; }
367 const pick = document.createElement("button");
368 pick.type = "button";
369 pick.textContent = "Choose…";
370 pick.addEventListener("click", () => openEquipItemSearch(slot));
371 const dyeBtn = document.createElement("button");
372 dyeBtn.type = "button";
373 dyeBtn.textContent = "Dye…";
374 dyeBtn.disabled = !dyeable;
375 dyeBtn.title = dyeable
376 ? "Set clothing dye colour"
377 : "Only tailor clothing can be dyed";
378 dyeBtn.addEventListener("click", () => openDyePicker(slot));
379 const clear = document.createElement("button");
380 clear.type = "button";
381 clear.textContent = "Clear";
382 clear.disabled = itemId == null;
383 clear.addEventListener("click", () =>
384 {
385 equipmentDraft[slot] = emptyEquipDraft();
386 renderEquipmentRows();
387 });
388 row.append(label, name, pick, dyeBtn, clear);
389 list.append(row);
390 }
391 }
392
393 function renderHumanoidFields (config)
394 {
395 const wrap = document.createElement("div");
396 wrap.className = "spawner-humanoid-fields";
397 wrap.dataset.humanoid = "1";
398 const exchange = isCentralExchangeSpawner(config);
399 if (exchange)
400 {
401 const note = document.createElement("p");
402 note.className = "hint";
403 note.textContent = `Spawns all ${centralExchangeStaffCount()} Central Exchange clerks (names & sex fixed). Equipment below is shared. No shop interaction.`;
404 wrap.append(note);
405 }
406 else
407 {
408 wrap.append(
409 field("Display name", textInput("displayName", config.displayName || "Shopkeeper")),
410 field("Sex", sexSelect("sex", config.sex))
411 );
412 }
413
414 const aggressiveLabel = document.createElement("label");
415 aggressiveLabel.className = "spawner-buys-row";
416 const aggressive = document.createElement("input");
417 aggressive.type = "checkbox";
418 aggressive.name = "aggressive";
419 aggressive.checked = !!config.aggressive;
420 aggressive.addEventListener("change", () => syncBountyForAggressive());
421 aggressiveLabel.append(aggressive, document.createTextNode(" Aggressive (attacks players in range)"));
422 wrap.append(aggressiveLabel);
423 const aggressiveHint = document.createElement("p");
424 aggressiveHint.className = "hint";
425 aggressiveHint.textContent = "When Aggressive is on, Bounty is forced to 0.";
426 wrap.append(aggressiveHint);
427
428 const equipHeader = document.createElement("div");
429 equipHeader.className = "spawner-sells-header";
430 const equipTitle = document.createElement("strong");
431 equipTitle.textContent = "Equipment";
432 equipHeader.append(equipTitle);
433 wrap.append(equipHeader);
434
435 const equipList = document.createElement("div");
436 equipList.className = "spawner-equip-list";
437 equipList.dataset.equipmentList = "1";
438 wrap.append(equipList);
439
440 equipmentDraft = {};
441 for (const slot of EQUIPMENT_SLOTS)
442 { equipmentDraft[slot] = equipDraftFromConfig(config.equipment?.[slot]); }
443 queueMicrotask(() => renderEquipmentRows());
444
445 if (!exchange)
446 {
447 wrap.append(field("Hidden discount (0–1)", numberInput("hiddenDiscount", config.hiddenDiscount ?? 0.9, 0.01, 1, 0.01)));
448
449 const sellsHeader = document.createElement("div");
450 sellsHeader.className = "spawner-sells-header";
451 const sellsTitle = document.createElement("strong");
452 sellsTitle.textContent = "Sells";
453 const addBtn = document.createElement("button");
454 addBtn.type = "button";
455 addBtn.textContent = "+";
456 addBtn.title = "Add item";
457 addBtn.addEventListener("click", () => openSellItemSearch());
458 sellsHeader.append(sellsTitle, addBtn);
459 wrap.append(sellsHeader);
460
461 const list = document.createElement("div");
462 list.className = "spawner-sells-list";
463 list.dataset.sellsList = "1";
464 wrap.append(list);
465
466 const buysLabel = document.createElement("label");
467 buysLabel.className = "spawner-buys-row";
468 const buys = document.createElement("input");
469 buys.type = "checkbox";
470 buys.name = "buysItems";
471 buys.checked = !!config.buysItems;
472 buysLabel.append(buys, document.createTextNode(" Buys items"));
473 wrap.append(buysLabel);
474
475 const hint = document.createElement("p");
476 hint.className = "hint";
477 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.";
478 wrap.append(hint);
479
480 sellsDraft = (config.sells ?? []).map((line) =>
481 {
482 if (line && typeof line === "object")
483 { return { itemId: line.itemId | 0, quantity: Math.max(0, line.quantity | 0 || 0) }; }
484 return { itemId: line | 0, quantity: 0 };
485 }).filter((line) => line.itemId > 0);
486
487 queueMicrotask(() => renderSellsList());
488 }
489 else
490 { sellsDraft = []; }
491 return wrap;
492 }
493
494 function syncHumanoidSection (config)
495 {
496 form.querySelector("[data-humanoid]")?.remove();
497 const mobTypeId = form.querySelector('[name="mobTypeId"]')?.value;
498 if (!isHumanoidMob(mobTypeId))
499 {
500 sellsDraft = [];
501 equipmentDraft = {};
502 return;
503 }
504 form.append(renderHumanoidFields(config ?? normalizeSpawnerConfig({
505 mobTypeId: mobTypeId || MobId.humanoid
506 }, "spawner")));
507 const maxAlive = form.querySelector('[name="maxAlive"]');
508 if (maxAlive && isCentralExchangeSpawner({ mobTypeId }))
509 {
510 maxAlive.value = String(centralExchangeStaffCount());
511 maxAlive.disabled = true;
512 }
513 else if (maxAlive)
514 { maxAlive.disabled = false; }
515 }
516
517 function syncSpellsSection (config)
518 {
519 form.querySelector("[data-spells]")?.remove();
520 form.append(renderSpellsFields(config));
521 }
522
523 function renderSpellsFields (config)
524 {
525 const wrap = document.createElement("div");
526 wrap.className = "spawner-spells-fields";
527 wrap.dataset.spells = "1";
528
529 const header = document.createElement("div");
530 header.className = "spawner-sells-header";
531 const titleEl = document.createElement("strong");
532 titleEl.textContent = "Spells";
533 const addBtn = document.createElement("button");
534 addBtn.type = "button";
535 addBtn.textContent = "+";
536 addBtn.title = "Add spell";
537 addBtn.addEventListener("click", () =>
538 {
539 const available = Object.values(SPELL_DEFINITIONS).find((def) =>
540 !spellsDraft.some((line) => line.spellId === def.spellId));
541 if (!available)
542 { return; }
543 spellsDraft.push({ spellId: available.spellId });
544 renderSpellsList();
545 });
546 header.append(titleEl, addBtn);
547 wrap.append(header);
548
549 const list = document.createElement("div");
550 list.className = "spawner-sells-list";
551 list.dataset.spellsList = "1";
552 wrap.append(list);
553
554 const hint = document.createElement("p");
555 hint.className = "hint";
556 hint.textContent = "Cast chance is derived from the mob Level (shown as a label). Only Attack (entity) spells are used in combat. Mobs only learn spells their Level can cast.";
557 wrap.append(hint);
558
559 if (!Array.isArray(spellsDraft) || !spellsDraft.length)
560 {
561 spellsDraft = (config?.spells ?? []).map((line) => ({
562 spellId: String(line.spellId ?? "")
563 })).filter((line) => line.spellId);
564 }
565 queueMicrotask(() => renderSpellsList());
566 return wrap;
567 }
568
569 function renderSpellsList ()
570 {
571 const list = form.querySelector("[data-spells-list]");
572 if (!list)
573 { return; }
574 list.replaceChildren();
575 if (!spellsDraft.length)
576 {
577 const empty = document.createElement("p");
578 empty.className = "hint";
579 empty.textContent = "No spells.";
580 list.append(empty);
581 return;
582 }
583 const level = Math.max(1, Number(form.querySelector('[name="level"]')?.value) || 1) | 0;
584 const castChance = mobSpellCastChancePercent(level);
585 for (let index = 0; index < spellsDraft.length; index++)
586 {
587 const line = spellsDraft[index];
588 const def = SPELL_DEFINITIONS[line.spellId];
589 const row = document.createElement("div");
590 row.className = "spawner-sell-row";
591
592 const select = document.createElement("select");
593 for (const spell of Object.values(SPELL_DEFINITIONS))
594 {
595 const opt = document.createElement("option");
596 opt.value = spell.spellId;
597 const minLv = spell.minMagicLevel | 0 || 1;
598 opt.textContent = `${spell.displayName} (Magic ${minLv}+)`;
599 if (spell.spellId === line.spellId)
600 { opt.selected = true; }
601 select.append(opt);
602 }
603 select.addEventListener("change", () =>
604 {
605 spellsDraft[index].spellId = select.value;
606 renderSpellsList();
607 });
608
609 const minLv = def?.minMagicLevel | 0 || 1;
610 const chanceLabel = document.createElement("span");
611 chanceLabel.className = "hint";
612 chanceLabel.title = "Cast chance from mob Level";
613 chanceLabel.textContent = level < minLv
614 ? `needs Lv.${minLv}`
615 : `cast ${castChance}%`;
616
617 const remove = document.createElement("button");
618 remove.type = "button";
619 remove.textContent = "×";
620 remove.addEventListener("click", () =>
621 {
622 spellsDraft.splice(index, 1);
623 renderSpellsList();
624 });
625
626 row.append(select, chanceLabel, remove);
627 list.append(row);
628 }
629 }
630
631 function syncBountyForAggressive ()
632 {
633 const bountyInput = form.querySelector('[name="bounty"]');
634 const aggressiveInput = form.querySelector('[name="aggressive"]');
635 if (!bountyInput)
636 { return; }
637 const aggressive = !!aggressiveInput?.checked;
638 if (aggressive)
639 {
640 bountyInput.value = "0";
641 bountyInput.disabled = true;
642 }
643 else
644 { bountyInput.disabled = false; }
645 }
646
647 function openSpawner (ctx)
648 {
649 context = { kind: "spawner", ...ctx };
650 const config = normalizeSpawnerConfig(ctx.config, ctx.config.spawnerId);
651 title.textContent = `Spawner · ${ctx.tileX}, ${ctx.tileY}`;
652 form.innerHTML = "";
653 const mobField = field("Mob type", mobSelect("mobTypeId", config.mobTypeId));
654 form.append(
655 mobField,
656 field("Level", numberInput("level", config.level ?? 1, 1, 99)),
657 field("Bounty", numberInput("bounty", config.bounty ?? 0, 0, 1_000_000)),
658 field("Max alive", numberInput("maxAlive", config.maxAlive, 1, 20)),
659 field("Spawn range", numberInput("spawnRangeTiles", config.spawnRangeTiles, 1, 32)),
660 field("Max wander range", numberInput("maxWanderRangeTiles", config.maxWanderRangeTiles, 1, 64)),
661 field("Spawner id", textInput("spawnerId", config.spawnerId, true))
662 );
663 const spawnInput = form.querySelector('[name="spawnRangeTiles"]');
664 const wanderInput = form.querySelector('[name="maxWanderRangeTiles"]');
665 const syncWanderMin = () =>
666 {
667 const spawn = Number(spawnInput.value) || 1;
668 wanderInput.min = String(spawn);
669 if (Number(wanderInput.value) < spawn)
670 { wanderInput.value = String(spawn); }
671 };
672 spawnInput.addEventListener("input", syncWanderMin);
673 syncWanderMin();
674 form.querySelector('[name="level"]')?.addEventListener("input", () => renderSpellsList());
675 form.querySelector('[name="mobTypeId"]').addEventListener("change", () =>
676 {
677 const nextType = form.querySelector('[name="mobTypeId"]').value;
678 const defaults = normalizeSpawnerConfig({ mobTypeId: nextType }, config.spawnerId);
679 form.querySelector('[name="maxAlive"]').value = String(defaults.maxAlive);
680 form.querySelector('[name="spawnRangeTiles"]').value = String(defaults.spawnRangeTiles);
681 form.querySelector('[name="maxWanderRangeTiles"]').value = String(defaults.maxWanderRangeTiles);
682 form.querySelector('[name="level"]').value = String(defaults.level ?? 1);
683 form.querySelector('[name="bounty"]').value = String(defaults.bounty ?? 0);
684 syncWanderMin();
685 syncHumanoidSection(defaults);
686 syncSpellsSection(defaults);
687 syncBountyForAggressive();
688 });
689 spellsDraft = (config.spells ?? []).map((line) => ({
690 spellId: String(line.spellId ?? "")
691 })).filter((line) => line.spellId);
692 syncHumanoidSection(config);
693 syncSpellsSection(config);
694 syncBountyForAggressive();
695 show(true);
696 }
697
698 document.getElementById("tile-config-close").addEventListener("click", () => show(false));
699 document.getElementById("tile-config-cancel").addEventListener("click", () => show(false));
700 backdrop.addEventListener("click", () => show(false));
701 document.getElementById("shop-item-search-close")?.addEventListener("click", () => closeItemSearch());
702 itemSearchBackdrop?.addEventListener("click", () => closeItemSearch());
703 itemSearchInput?.addEventListener("input", () => renderItemSearchResults(itemSearchInput.value));
704 document.getElementById("equip-dye-close")?.addEventListener("click", () => closeDyePicker());
705 dyeBackdrop?.addEventListener("click", () => closeDyePicker());
706 document.getElementById("equip-dye-apply")?.addEventListener("click", () =>
707 {
708 if (!dyeEditSlot || !equipmentDraft[dyeEditSlot])
709 { return; }
710 equipmentDraft[dyeEditSlot].dyeColor = readDyeSliders();
711 closeDyePicker();
712 renderEquipmentRows();
713 });
714 document.getElementById("equip-dye-clear")?.addEventListener("click", () =>
715 {
716 if (!dyeEditSlot || !equipmentDraft[dyeEditSlot])
717 { return; }
718 equipmentDraft[dyeEditSlot].dyeColor = null;
719 closeDyePicker();
720 renderEquipmentRows();
721 });
722
723 document.getElementById("tile-config-save").addEventListener("click", () =>
724 {
725 if (!context)
726 { return; }
727 const data = new FormData(form);
728 const equipment = {};
729 for (const slot of EQUIPMENT_SLOTS)
730 { equipment[slot] = equipConfigFromDraft(equipmentDraft[slot]); }
731 onSave?.(context, normalizeSpawnerConfig({
732 mobTypeId: String(data.get("mobTypeId") || "deer"),
733 maxAlive: Number(data.get("maxAlive") || 3),
734 spawnRangeTiles: Number(data.get("spawnRangeTiles") || 4),
735 maxWanderRangeTiles: Number(data.get("maxWanderRangeTiles") || 4),
736 level: Number(data.get("level") || 1),
737 bounty: Number(data.get("bounty") || 0),
738 aggressive: data.get("aggressive") === "on",
739 spawnerId: String(data.get("spawnerId") || context.config.spawnerId),
740 sex: String(data.get("sex") || "male"),
741 displayName: String(data.get("displayName") || ""),
742 equipment,
743 sells: sellsDraft,
744 spells: spellsDraft,
745 buysItems: data.get("buysItems") === "on",
746 hiddenDiscount: Number(data.get("hiddenDiscount") || 0.9),
747 centralExchange: isCentralExchangeSpawner(String(data.get("mobTypeId") || ""))
748 }, context.config.spawnerId));
749 show(false);
750 });
751 document.getElementById("tile-config-remove").addEventListener("click", () =>
752 {
753 if (!context)
754 { return; }
755 onRemove?.(context);
756 show(false);
757 });
758
759 return {
760 isOpen: () => open,
761 openSpawner,
762 close: () => show(false)
763 };
764}
765
766function field (label, input)
767{
768 const wrap = document.createElement("label");
769 wrap.append(document.createTextNode(label), input);
770 return wrap;
771}
772
773function numberInput (name, value, min, max, step = 1)
774{
775 const input = document.createElement("input");
776 input.type = "number";
777 input.name = name;
778 input.min = String(min);
779 input.max = String(max);
780 input.step = String(step);
781 input.value = String(value);
782 return input;
783}
784
785function textInput (name, value, readOnly = false)
786{
787 const input = document.createElement("input");
788 input.type = "text";
789 input.name = name;
790 input.value = String(value ?? "");
791 input.readOnly = readOnly;
792 return input;
793}
794
795function sexSelect (name, value)
796{
797 const select = document.createElement("select");
798 select.name = name;
799 for (const sex of ["male", "female"])
800 {
801 const option = document.createElement("option");
802 option.value = sex;
803 option.textContent = sex;
804 if (sex === value)
805 { option.selected = true; }
806 select.append(option);
807 }
808 return select;
809}
810
811function mobSelect (name, value)
812{
813 const select = document.createElement("select");
814 select.name = name;
815 for (const def of listSpawnableMobTypes())
816 {
817 const option = document.createElement("option");
818 option.value = def.mobTypeId;
819 option.textContent = def.displayName;
820 if (def.mobTypeId === value)
821 { option.selected = true; }
822 select.append(option);
823 }
824 return select;
825}