BlueGit

timfa questward

Files

questward / client / src / editor / tileConfigModal.js

tileConfigModal.js

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