BlueGit

timfa questward

Files

questward / client / src / editor / tileConfigModal.js

tileConfigModal.js

tileConfigModal.js 46.9 KiB Download Raw
1/**
2 * Right-click config modal for editor tiles that have configurable data (spawners, doorways).
3 */
4import
5{
6 listSpawnableMobTypes,
7 normalizeSpawnerConfig,
8 MobId,
9 isHumanoidMob,
10 isCentralExchangeSpawner,
11 spawnerEquipmentSlot,
12 mobDefinition
13} from "/shared/definitions/mobs.js";
14import { spellCastSuccessChancePercent } from "/shared/combat/magic.js";
15import { SPELL_DEFINITIONS, spellMinMagicLevel } from "/shared/definitions/spells.js";
16import { spellDifficultyFromTier } from "/shared/spells/constants.js";
17import { centralExchangeStaffCount } from "/shared/market/exchange.js";
18import { ITEM_DEFINITIONS, itemDefinition, isDyeableClothing, listAllItemPickerEntries, itemAssetPathForStack } from "/shared/definitions/items.js";
19import { listRawFishPickerEntries, normalizeFishingSpotConfig, fishTierRankFromItemId } from "/shared/definitions/fishItems.js";
20import { EQUIPMENT_SLOTS } from "/shared/items/inventory.js";
21import { normalizeRgb } from "/shared/render/tint.js";
22import { applyItemIcon } from "/src/render/potionIcon.js";
23import { createDimensionCombobox } from "./dimensionCombobox.js";
24import { OVERWORLD_ID, normalizeDimensionId } from "/shared/world/dimensions.js";
25import { renderConditionSet, emptyConditionSet, normalizeConditionSet } from "./conditionSetEditor.js";
26import { DEFAULT_DOOR_BLOCKED_MESSAGE } from "/shared/world/doorRequirements.js";
27
28const DOORWAY_STATES = Object.freeze(["door", "ladder", "hole", "cave"]);
29const ITEM_SEARCH_PAGE_SIZE = 40;
30
31function formatCastChancePercent (pct)
32{
33 const n = Number(pct);
34 if (!Number.isFinite(n))
35 { return "0"; }
36 const rounded = Math.round(n * 10) / 10;
37 return Number.isInteger(rounded) ? String(rounded) : rounded.toFixed(1);
38}
39
40/** Items that can be worn in a given equipment slot. */
41export function listEquippableItemsForSlot (slot)
42{
43 const out = [];
44 for (const def of Object.values(ITEM_DEFINITIONS))
45 {
46 if (!def?.equipment || def.equipment.slot !== slot)
47 { continue; }
48 out.push({
49 itemId: def.itemId,
50 key: def.key ?? String(def.itemId),
51 displayName: def.displayName ?? `Item ${def.itemId}`
52 });
53 }
54 out.sort((a, b) => a.displayName.localeCompare(b.displayName));
55 return out;
56}
57
58function emptyEquipDraft ()
59{
60 return { itemId: null, dyeColor: null };
61}
62
63function equipDraftFromConfig (raw)
64{
65 const { itemId, dyeColor } = spawnerEquipmentSlot(raw);
66 return {
67 itemId: itemId > 0 ? itemId : null,
68 dyeColor: dyeColor ? normalizeRgb(dyeColor) : null
69 };
70}
71
72function equipConfigFromDraft (draft)
73{
74 const itemId = draft?.itemId;
75 if (itemId == null || itemId === "")
76 { return null; }
77 const id = Number(itemId) || null;
78 if (!id)
79 { return null; }
80 if (draft.dyeColor && isDyeableClothing(id))
81 { return { itemId: id, dyeColor: normalizeRgb(draft.dyeColor) }; }
82 return id;
83}
84
85/** Stack shape for applyItemIcon, including optional clothing dye. */
86function stackFromEquipDraft (draft)
87{
88 const itemId = draft?.itemId;
89 if (itemId == null)
90 { return null; }
91 const stack = { itemId, quantity: 1 };
92 if (draft.dyeColor && isDyeableClothing(itemId))
93 { stack.instance = { kind: "clothing", dyeColor: normalizeRgb(draft.dyeColor) }; }
94 return stack;
95}
96
97function applyEquipIcon (img, draft)
98{
99 if (!img)
100 { return; }
101 const stack = stackFromEquipDraft(draft);
102 if (!stack)
103 {
104 img.removeAttribute("src");
105 img.alt = "";
106 img.hidden = true;
107 return;
108 }
109 img.hidden = false;
110 img.alt = itemDefinition(stack.itemId)?.displayName ?? "";
111 applyItemIcon(img, stack, itemAssetPathForStack(stack));
112}
113
114function rgbToCss (color)
115{
116 const c = normalizeRgb(color, { r: 0.78, g: 0.31, b: 0.47 });
117 return `rgb(${Math.round(c.r * 255)}, ${Math.round(c.g * 255)}, ${Math.round(c.b * 255)})`;
118}
119
120export function initTileConfigModal ({
121 onSave,
122 onRemove,
123 socket,
124 MessageType,
125 getDialogues,
126 getQuests,
127 getDimensionOptions,
128 describeWorldTile = null,
129 centerEditorOnTile = null
130})
131{
132 const backdrop = document.getElementById("tile-config-backdrop");
133 const modal = document.getElementById("tile-config-modal");
134 const form = document.getElementById("tile-config-form");
135 const title = document.getElementById("tile-config-title");
136 const itemSearchBackdrop = document.getElementById("shop-item-search-backdrop");
137 const itemSearchModal = document.getElementById("shop-item-search-modal");
138 const itemSearchTitle = itemSearchModal?.querySelector("h2") ?? null;
139 const itemSearchInput = document.getElementById("shop-item-search-input");
140 const itemSearchResults = document.getElementById("shop-item-search-results");
141 const itemSearchPrev = document.getElementById("shop-item-search-prev");
142 const itemSearchNext = document.getElementById("shop-item-search-next");
143 const itemSearchPageLabel = document.getElementById("shop-item-search-page");
144 const dyeBackdrop = document.getElementById("equip-dye-backdrop");
145 const dyeModal = document.getElementById("equip-dye-modal");
146 const dyeTitle = document.getElementById("equip-dye-title");
147 const dyePreview = document.getElementById("equip-dye-preview");
148 const dyeR = document.getElementById("equip-dye-r");
149 const dyeG = document.getElementById("equip-dye-g");
150 const dyeB = document.getElementById("equip-dye-b");
151 const dyeRNum = document.getElementById("equip-dye-r-num");
152 const dyeGNum = document.getElementById("equip-dye-g-num");
153 const dyeBNum = document.getElementById("equip-dye-b-num");
154 let open = false;
155 let context = null;
156 /** @type {{ itemId: number, quantity: number }[]} */
157 let sellsDraft = [];
158 /** @type {{ itemId: number, chancePercent: number, quantityMin: number, quantityMax: number }[]} */
159 let dropsDraft = [];
160 /** @type {number[]} raw fish item ids for fishing spots */
161 let fishesDraft = [];
162 /** @type {{ spellId: string, chance: number }[]} */
163 let spellsDraft = [];
164 /** @type {Record<string, { itemId: number|null, dyeColor: {r:number,g:number,b:number}|null }>} */
165 let equipmentDraft = {};
166 /** @type {{ kind: "sells" } | { kind: "drops" } | { kind: "fishes" } | { kind: "equip", slot: string } | { kind: "spells" } | null} */
167 let itemSearchMode = null;
168 /** @type {string|null} */
169 let dyeEditSlot = null;
170 /** @type {{ dialogueId: string, label: string, unique?: boolean }[]} */
171 let dialogueOptions = [];
172 let pendingDialogueId = null;
173 /** @type {number} */
174 let itemSearchPage = 0;
175 /** @type {{ itemId: number, displayName: string, key: string }[] | null} */
176 let itemSearchMatches = null;
177 /** @type {ReturnType<typeof createDimensionCombobox>|null} */
178 let doorwayDimCombo = null;
179 /** @type {{ all: object[] }} */
180 let doorWhenDraft = emptyConditionSet();
181 /** @type {string} */
182 let doorBlockedMessageDraft = "";
183
184 function show (visible)
185 {
186 open = visible;
187 backdrop.hidden = !visible;
188 modal.hidden = !visible;
189 if (!visible)
190 {
191 context = null;
192 doorwayDimCombo = null;
193 doorWhenDraft = emptyConditionSet();
194 doorBlockedMessageDraft = "";
195 closeItemSearch();
196 closeDyePicker();
197 }
198 }
199
200 function closeItemSearch ()
201 {
202 itemSearchMode = null;
203 itemSearchPage = 0;
204 itemSearchMatches = null;
205 if (itemSearchBackdrop)
206 { itemSearchBackdrop.hidden = true; }
207 if (itemSearchModal)
208 { itemSearchModal.hidden = true; }
209 }
210
211 function openSellItemSearch ()
212 {
213 itemSearchMode = { kind: "sells" };
214 openItemSearch("Add shop stock");
215 }
216
217 function openDropItemSearch ()
218 {
219 itemSearchMode = { kind: "drops" };
220 openItemSearch("Add drop");
221 }
222
223 function openFishItemSearch ()
224 {
225 itemSearchMode = { kind: "fishes" };
226 openItemSearch("Add fish to spot");
227 }
228
229 function openEquipItemSearch (slot)
230 {
231 itemSearchMode = { kind: "equip", slot };
232 openItemSearch(`Equip ${slot}`);
233 }
234
235 function openItemSearch (heading)
236 {
237 if (!itemSearchBackdrop || !itemSearchModal || !itemSearchInput)
238 { return; }
239 if (itemSearchTitle)
240 { itemSearchTitle.textContent = heading ?? "Choose item"; }
241 itemSearchInput.value = "";
242 itemSearchPage = 0;
243 itemSearchMatches = null;
244 itemSearchInput.placeholder = itemSearchMode?.kind === "equip"
245 ? "Search equipment…"
246 : itemSearchMode?.kind === "fishes"
247 ? "Search raw fish…"
248 : "Search all items…";
249 renderItemSearchResults("");
250 itemSearchBackdrop.hidden = false;
251 itemSearchModal.hidden = false;
252 itemSearchInput.focus();
253 }
254
255 function candidateItems ()
256 {
257 if (itemSearchMode?.kind === "equip")
258 { return listEquippableItemsForSlot(itemSearchMode.slot); }
259 if (itemSearchMode?.kind === "fishes")
260 { return listRawFishPickerEntries(); }
261 return listAllItemPickerEntries();
262 }
263
264 function filterItemSearchMatches (query)
265 {
266 const q = String(query ?? "").trim().toLowerCase();
267 const taken = itemSearchMode?.kind === "sells"
268 ? new Set(sellsDraft.map((line) => line.itemId))
269 : (itemSearchMode?.kind === "drops"
270 ? new Set(dropsDraft.map((line) => line.itemId))
271 : null);
272 return candidateItems().filter((item) =>
273 {
274 if (taken?.has(item.itemId))
275 { return false; }
276 if (!q)
277 { return true; }
278 const idText = String(item.itemId);
279 return item.displayName.toLowerCase().includes(q)
280 || item.key.toLowerCase().includes(q)
281 || idText.includes(q);
282 });
283 }
284
285 function renderItemSearchResults (query)
286 {
287 if (!itemSearchResults)
288 { return; }
289 itemSearchResults.innerHTML = "";
290 itemSearchMatches = filterItemSearchMatches(query);
291 const total = itemSearchMatches.length;
292 const pageCount = Math.max(1, Math.ceil(total / ITEM_SEARCH_PAGE_SIZE));
293 if (itemSearchPage >= pageCount)
294 { itemSearchPage = Math.max(0, pageCount - 1); }
295 const start = itemSearchPage * ITEM_SEARCH_PAGE_SIZE;
296 const pageItems = itemSearchMatches.slice(start, start + ITEM_SEARCH_PAGE_SIZE);
297 if (itemSearchPageLabel)
298 {
299 itemSearchPageLabel.textContent = total
300 ? `${start + 1}–${start + pageItems.length} of ${total}`
301 : "No items";
302 }
303 if (itemSearchPrev)
304 { itemSearchPrev.disabled = itemSearchPage <= 0; }
305 if (itemSearchNext)
306 { itemSearchNext.disabled = itemSearchPage >= pageCount - 1; }
307 if (!pageItems.length)
308 {
309 itemSearchResults.textContent = total
310 ? "No items on this page."
311 : "No matching items.";
312 return;
313 }
314 for (const item of pageItems)
315 {
316 const row = document.createElement("button");
317 row.type = "button";
318 row.className = "shop-item-search-row";
319 const icon = document.createElement("img");
320 icon.className = "shop-item-search-row-icon equip-stats-icon";
321 icon.width = 16;
322 icon.height = 16;
323 icon.alt = "";
324 const stack = { itemId: item.itemId, quantity: 1 };
325 applyItemIcon(icon, stack, itemAssetPathForStack(stack));
326 const text = document.createElement("span");
327 text.className = "shop-item-search-row-text";
328 const name = document.createElement("span");
329 name.className = "shop-item-search-row-name";
330 name.textContent = item.displayName;
331 const key = document.createElement("span");
332 key.className = "shop-item-search-row-key";
333 key.textContent = itemSearchMode?.kind === "fishes"
334 ? `${item.key} · tier ${item.tier} · #${item.itemId}`
335 : `${item.key} · #${item.itemId}`;
336 text.append(name, key);
337 row.append(icon, text);
338 row.addEventListener("click", () =>
339 {
340 if (itemSearchMode?.kind === "equip")
341 {
342 equipmentDraft[itemSearchMode.slot] = {
343 itemId: item.itemId,
344 dyeColor: null
345 };
346 renderEquipmentRows();
347 }
348 else if (itemSearchMode?.kind === "fishes")
349 {
350 if (!fishesDraft.includes(item.itemId))
351 { fishesDraft.push(item.itemId); }
352 renderFishesList();
353 }
354 else if (itemSearchMode?.kind === "drops")
355 {
356 dropsDraft.push({
357 itemId: item.itemId,
358 chancePercent: 100,
359 quantityMin: 1,
360 quantityMax: 1
361 });
362 renderDropsList();
363 }
364 else
365 {
366 sellsDraft.push({ itemId: item.itemId, quantity: 0 });
367 renderSellsList();
368 }
369 closeItemSearch();
370 });
371 itemSearchResults.append(row);
372 }
373 }
374
375 function closeDyePicker ()
376 {
377 dyeEditSlot = null;
378 if (dyeBackdrop)
379 { dyeBackdrop.hidden = true; }
380 if (dyeModal)
381 { dyeModal.hidden = true; }
382 }
383
384 function readDyeSliders ()
385 {
386 return {
387 r: Math.min(255, Math.max(0, Number(dyeR?.value) || 0)) / 255,
388 g: Math.min(255, Math.max(0, Number(dyeG?.value) || 0)) / 255,
389 b: Math.min(255, Math.max(0, Number(dyeB?.value) || 0)) / 255
390 };
391 }
392
393 function syncDyePreview ()
394 {
395 const color = readDyeSliders();
396 if (dyePreview)
397 { dyePreview.style.background = rgbToCss(color); }
398 if (dyeRNum)
399 { dyeRNum.value = String(Math.round(color.r * 255)); }
400 if (dyeGNum)
401 { dyeGNum.value = String(Math.round(color.g * 255)); }
402 if (dyeBNum)
403 { dyeBNum.value = String(Math.round(color.b * 255)); }
404 }
405
406 function setDyeSliders (color)
407 {
408 const c = normalizeRgb(color, { r: 200 / 255, g: 80 / 255, b: 120 / 255 });
409 const r = Math.round(c.r * 255);
410 const g = Math.round(c.g * 255);
411 const b = Math.round(c.b * 255);
412 if (dyeR)
413 { dyeR.value = String(r); }
414 if (dyeG)
415 { dyeG.value = String(g); }
416 if (dyeB)
417 { dyeB.value = String(b); }
418 syncDyePreview();
419 }
420
421 function openDyePicker (slot)
422 {
423 const draft = equipmentDraft[slot];
424 if (!draft?.itemId || !isDyeableClothing(draft.itemId) || !dyeModal || !dyeBackdrop)
425 { return; }
426 dyeEditSlot = slot;
427 const def = itemDefinition(draft.itemId);
428 if (dyeTitle)
429 { dyeTitle.textContent = `Dye — ${def?.displayName ?? slot}`; }
430 setDyeSliders(draft.dyeColor ?? { r: 200 / 255, g: 80 / 255, b: 120 / 255 });
431 dyeBackdrop.hidden = false;
432 dyeModal.hidden = false;
433 }
434
435 function bindDyeChannel (range, num)
436 {
437 range?.addEventListener("input", () =>
438 {
439 if (num)
440 { num.value = range.value; }
441 syncDyePreview();
442 });
443 num?.addEventListener("input", () =>
444 {
445 const v = Math.min(255, Math.max(0, Number(num.value) || 0));
446 num.value = String(v);
447 if (range)
448 { range.value = String(v); }
449 syncDyePreview();
450 });
451 }
452
453 bindDyeChannel(dyeR, dyeRNum);
454 bindDyeChannel(dyeG, dyeGNum);
455 bindDyeChannel(dyeB, dyeBNum);
456
457 function renderFishesList ()
458 {
459 const list = form.querySelector("[data-fishes-list]");
460 if (!list)
461 { return; }
462 list.innerHTML = "";
463 if (!fishesDraft.length)
464 {
465 const empty = document.createElement("p");
466 empty.className = "hint";
467 empty.textContent = "No fish yet. Use + to choose species for this spot.";
468 list.append(empty);
469 return;
470 }
471 for (let index = 0; index < fishesDraft.length; index++)
472 {
473 const itemId = fishesDraft[index];
474 const def = itemDefinition(itemId);
475 const row = document.createElement("div");
476 row.className = "spawner-sells-row";
477 const tier = fishTierRankFromItemId(itemId);
478 const name = document.createElement("span");
479 name.className = "spawner-sells-name";
480 name.textContent = tier != null
481 ? `${def?.displayName ?? `Item ${itemId}`} · tier ${tier}`
482 : (def?.displayName ?? `Item ${itemId}`);
483 const remove = document.createElement("button");
484 remove.type = "button";
485 remove.textContent = "Remove";
486 remove.addEventListener("click", () =>
487 {
488 fishesDraft.splice(index, 1);
489 renderFishesList();
490 });
491 row.append(name, remove);
492 list.append(row);
493 }
494 }
495
496 function renderSellsList ()
497 {
498 const list = form.querySelector("[data-sells-list]");
499 if (!list)
500 { return; }
501 list.innerHTML = "";
502 if (!sellsDraft.length)
503 {
504 const empty = document.createElement("p");
505 empty.className = "hint";
506 empty.textContent = "No items yet. Use + to add stock.";
507 list.append(empty);
508 return;
509 }
510 for (let index = 0; index < sellsDraft.length; index++)
511 {
512 const line = sellsDraft[index];
513 const def = itemDefinition(line.itemId);
514 const row = document.createElement("div");
515 row.className = "spawner-sells-row";
516 const name = document.createElement("span");
517 name.className = "spawner-sells-name";
518 name.textContent = def?.displayName ?? `Item ${line.itemId}`;
519 const qty = document.createElement("input");
520 qty.type = "number";
521 qty.min = "0";
522 qty.step = "1";
523 qty.value = String(line.quantity | 0);
524 qty.title = "0 = infinite; otherwise restocks this many at 00:00 server time";
525 qty.addEventListener("input", () =>
526 {
527 sellsDraft[index].quantity = Math.max(0, Number(qty.value) || 0) | 0;
528 });
529 const remove = document.createElement("button");
530 remove.type = "button";
531 remove.textContent = "Remove";
532 remove.addEventListener("click", () =>
533 {
534 sellsDraft.splice(index, 1);
535 renderSellsList();
536 });
537 row.append(name, qty, remove);
538 list.append(row);
539 }
540 }
541
542 function renderDropsList ()
543 {
544 const list = form.querySelector("[data-drops-list]");
545 if (!list)
546 { return; }
547 list.innerHTML = "";
548 if (!dropsDraft.length)
549 {
550 const empty = document.createElement("p");
551 empty.className = "hint";
552 empty.textContent = "No drops yet. Use + to add loot.";
553 list.append(empty);
554 return;
555 }
556 for (let index = 0; index < dropsDraft.length; index++)
557 {
558 const line = dropsDraft[index];
559 const def = itemDefinition(line.itemId);
560 const row = document.createElement("div");
561 row.className = "spawner-drops-row";
562 const name = document.createElement("span");
563 name.className = "spawner-sells-name";
564 name.textContent = def?.displayName ?? `Item ${line.itemId}`;
565
566 const qtyMin = document.createElement("input");
567 qtyMin.type = "number";
568 qtyMin.min = "0";
569 qtyMin.step = "1";
570 qtyMin.value = String(line.quantityMin | 0);
571 qtyMin.title = "Minimum quantity if this drop hits";
572 qtyMin.addEventListener("input", () =>
573 {
574 const min = Math.max(0, Number(qtyMin.value) || 0) | 0;
575 dropsDraft[index].quantityMin = min;
576 if ((dropsDraft[index].quantityMax | 0) < min)
577 {
578 dropsDraft[index].quantityMax = min;
579 qtyMax.value = String(min);
580 }
581 });
582
583 const qtyMax = document.createElement("input");
584 qtyMax.type = "number";
585 qtyMax.min = "0";
586 qtyMax.step = "1";
587 qtyMax.value = String(line.quantityMax | 0);
588 qtyMax.title = "Maximum quantity if this drop hits";
589 qtyMax.addEventListener("input", () =>
590 {
591 const max = Math.max(0, Number(qtyMax.value) || 0) | 0;
592 const min = dropsDraft[index].quantityMin | 0;
593 dropsDraft[index].quantityMax = Math.max(min, max);
594 if (max < min)
595 { qtyMax.value = String(min); }
596 });
597
598 const chanceWrap = document.createElement("label");
599 chanceWrap.className = "spawner-drops-chance";
600 const chance = document.createElement("input");
601 chance.type = "number";
602 chance.min = "0";
603 chance.max = "100";
604 chance.step = "1";
605 chance.value = String(Math.round(line.chancePercent ?? 100));
606 chance.title = "Drop chance (0–100%)";
607 chance.addEventListener("input", () =>
608 {
609 dropsDraft[index].chancePercent = Math.min(
610 100,
611 Math.max(0, Number(chance.value) || 0)
612 );
613 });
614 const suffix = document.createElement("span");
615 suffix.textContent = "%";
616 chanceWrap.append(chance, suffix);
617
618 const remove = document.createElement("button");
619 remove.type = "button";
620 remove.textContent = "Remove";
621 remove.addEventListener("click", () =>
622 {
623 dropsDraft.splice(index, 1);
624 renderDropsList();
625 });
626 row.append(name, qtyMin, qtyMax, chanceWrap, remove);
627 list.append(row);
628 }
629 }
630
631 function renderEquipmentRows ()
632 {
633 const list = form.querySelector("[data-equipment-list]");
634 if (!list)
635 { return; }
636 list.innerHTML = "";
637 for (const slot of EQUIPMENT_SLOTS)
638 {
639 const draft = equipmentDraft[slot] ?? emptyEquipDraft();
640 const itemId = draft.itemId ?? null;
641 const def = itemId ? itemDefinition(itemId) : null;
642 const dyeable = itemId != null && isDyeableClothing(itemId);
643 const row = document.createElement("div");
644 row.className = "spawner-equip-row";
645 const label = document.createElement("span");
646 label.className = "spawner-equip-slot";
647 label.textContent = slot;
648 const icon = document.createElement("img");
649 icon.className = "spawner-equip-icon equip-stats-icon";
650 icon.width = 16;
651 icon.height = 16;
652 icon.alt = "";
653 applyEquipIcon(icon, draft);
654 const name = document.createElement("span");
655 name.className = "spawner-equip-name";
656 if (def && draft.dyeColor)
657 {
658 const swatch = document.createElement("span");
659 swatch.className = "spawner-equip-dye-swatch";
660 swatch.style.background = rgbToCss(draft.dyeColor);
661 name.append(swatch, document.createTextNode(def.displayName));
662 }
663 else
664 { name.textContent = def?.displayName ?? "(none)"; }
665 const pick = document.createElement("button");
666 pick.type = "button";
667 pick.textContent = "Choose…";
668 pick.addEventListener("click", () => openEquipItemSearch(slot));
669 const dyeBtn = document.createElement("button");
670 dyeBtn.type = "button";
671 dyeBtn.textContent = "Dye…";
672 dyeBtn.disabled = !dyeable;
673 dyeBtn.title = dyeable
674 ? "Set clothing dye colour"
675 : "Only tailor clothing can be dyed";
676 dyeBtn.addEventListener("click", () => openDyePicker(slot));
677 const clear = document.createElement("button");
678 clear.type = "button";
679 clear.textContent = "Clear";
680 clear.disabled = itemId == null;
681 clear.addEventListener("click", () =>
682 {
683 equipmentDraft[slot] = emptyEquipDraft();
684 renderEquipmentRows();
685 });
686 row.append(label, icon, name, pick, dyeBtn, clear);
687 list.append(row);
688 }
689 }
690
691 function renderCommonSpawnerFields (config)
692 {
693 const wrap = document.createElement("div");
694 wrap.className = "spawner-common-fields";
695 wrap.dataset.commonSpawner = "1";
696 const exchange = isCentralExchangeSpawner(config);
697
698 if (exchange)
699 {
700 const note = document.createElement("p");
701 note.className = "hint";
702 note.textContent = `Spawns all ${centralExchangeStaffCount()} Central Exchange clerks (names & sex fixed). Equipment below is shared. No shop interaction.`;
703 wrap.append(note);
704 }
705 else
706 {
707 const def = mobDefinition(config.mobTypeId);
708 const placeholder = def?.displayName || "Name";
709 wrap.append(
710 field("Display name", textInput("displayName", config.displayName || ""))
711 );
712 const nameHint = document.createElement("p");
713 nameHint.className = "hint";
714 nameHint.textContent = `Optional. Empty uses the mob default (${placeholder}).`;
715 wrap.append(nameHint);
716 }
717
718 const dropsHeader = document.createElement("div");
719 dropsHeader.className = "spawner-sells-header";
720 const dropsTitle = document.createElement("strong");
721 dropsTitle.textContent = "Drops";
722 const dropsAddBtn = document.createElement("button");
723 dropsAddBtn.type = "button";
724 dropsAddBtn.textContent = "+";
725 dropsAddBtn.title = "Add drop";
726 dropsAddBtn.addEventListener("click", () => openDropItemSearch());
727 dropsHeader.append(dropsTitle, dropsAddBtn);
728 wrap.append(dropsHeader);
729
730 const dropsList = document.createElement("div");
731 dropsList.className = "spawner-sells-list";
732 dropsList.dataset.dropsList = "1";
733 wrap.append(dropsList);
734
735 const dropsHint = document.createElement("p");
736 dropsHint.className = "hint";
737 dropsHint.textContent = "Configured drops replace the mob's default loot table. Leave empty to keep defaults. Each line rolls its chance; quantity is random between min and max (inclusive).";
738 wrap.append(dropsHint);
739
740 dropsDraft = (config.drops ?? []).map((line) =>
741 {
742 if (!line || typeof line !== "object")
743 { return null; }
744 const itemId = line.itemId | 0;
745 if (itemId <= 0)
746 { return null; }
747 let chancePercent = Number(line.chance);
748 if (!Number.isFinite(chancePercent))
749 { chancePercent = 100; }
750 else if (chancePercent <= 1)
751 { chancePercent = chancePercent * 100; }
752 let quantityMin = Math.max(0, Math.floor(Number(line.quantityMin ?? line.quantity ?? 1)));
753 let quantityMax = Math.max(0, Math.floor(Number(line.quantityMax ?? quantityMin)));
754 if (!Number.isFinite(quantityMin))
755 { quantityMin = 1; }
756 if (!Number.isFinite(quantityMax) || quantityMax < quantityMin)
757 { quantityMax = quantityMin; }
758 return {
759 itemId,
760 chancePercent: Math.min(100, Math.max(0, chancePercent)),
761 quantityMin,
762 quantityMax
763 };
764 }).filter(Boolean);
765
766 queueMicrotask(() => renderDropsList());
767 return wrap;
768 }
769
770 function renderHumanoidFields (config)
771 {
772 const wrap = document.createElement("div");
773 wrap.className = "spawner-humanoid-fields";
774 wrap.dataset.humanoid = "1";
775 const exchange = isCentralExchangeSpawner(config);
776 if (!exchange)
777 {
778 wrap.append(field("Sex", sexSelect("sex", config.sex)));
779 }
780
781 const aggressiveLabel = document.createElement("label");
782 aggressiveLabel.className = "spawner-buys-row";
783 const aggressive = document.createElement("input");
784 aggressive.type = "checkbox";
785 aggressive.name = "aggressive";
786 aggressive.checked = !!config.aggressive;
787 aggressive.addEventListener("change", () => syncBountyForAggressive());
788 aggressiveLabel.append(aggressive, document.createTextNode(" Aggressive (attacks players in range)"));
789 wrap.append(aggressiveLabel);
790 const aggressiveHint = document.createElement("p");
791 aggressiveHint.className = "hint";
792 aggressiveHint.textContent = "When Aggressive is on, Bounty is forced to 0.";
793 wrap.append(aggressiveHint);
794
795 wrap.append(field("Dialogue", dialogueSelect("dialogueId", config.dialogueId ?? "", dialogueOptions)));
796
797 const equipHeader = document.createElement("div");
798 equipHeader.className = "spawner-sells-header";
799 const equipTitle = document.createElement("strong");
800 equipTitle.textContent = "Equipment";
801 equipHeader.append(equipTitle);
802 wrap.append(equipHeader);
803
804 const equipList = document.createElement("div");
805 equipList.className = "spawner-equip-list";
806 equipList.dataset.equipmentList = "1";
807 wrap.append(equipList);
808
809 equipmentDraft = {};
810 for (const slot of EQUIPMENT_SLOTS)
811 { equipmentDraft[slot] = equipDraftFromConfig(config.equipment?.[slot]); }
812 queueMicrotask(() => renderEquipmentRows());
813
814 if (!exchange)
815 {
816 wrap.append(field("Hidden discount (0–1)", numberInput("hiddenDiscount", config.hiddenDiscount ?? 0.9, 0.01, 1, 0.01)));
817
818 const sellsHeader = document.createElement("div");
819 sellsHeader.className = "spawner-sells-header";
820 const sellsTitle = document.createElement("strong");
821 sellsTitle.textContent = "Sells";
822 const addBtn = document.createElement("button");
823 addBtn.type = "button";
824 addBtn.textContent = "+";
825 addBtn.title = "Add item";
826 addBtn.addEventListener("click", () => openSellItemSearch());
827 sellsHeader.append(sellsTitle, addBtn);
828 wrap.append(sellsHeader);
829
830 const list = document.createElement("div");
831 list.className = "spawner-sells-list";
832 list.dataset.sellsList = "1";
833 wrap.append(list);
834
835 const buysLabel = document.createElement("label");
836 buysLabel.className = "spawner-buys-row";
837 const buys = document.createElement("input");
838 buys.type = "checkbox";
839 buys.name = "buysItems";
840 buys.checked = !!config.buysItems;
841 buysLabel.append(buys, document.createTextNode(" Buys items"));
842 wrap.append(buysLabel);
843
844 const hint = document.createElement("p");
845 hint.className = "hint";
846 hint.textContent = "Quantity 0 = infinite stock. Limited stock restocks daily at 00:00 server time. Any item can be listed for sale. Buys items: pays 50% 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.";
847 wrap.append(hint);
848
849 sellsDraft = (config.sells ?? []).map((line) =>
850 {
851 if (line && typeof line === "object")
852 { return { itemId: line.itemId | 0, quantity: Math.max(0, line.quantity | 0 || 0) }; }
853 return { itemId: line | 0, quantity: 0 };
854 }).filter((line) => line.itemId > 0);
855
856 queueMicrotask(() => renderSellsList());
857 }
858 else
859 { sellsDraft = []; }
860 return wrap;
861 }
862
863 function syncCommonSpawnerSection (config)
864 {
865 form.querySelector("[data-common-spawner]")?.remove();
866 const mobTypeId = form.querySelector('[name="mobTypeId"]')?.value
867 || config?.mobTypeId
868 || MobId.deer;
869 const normalized = config ?? normalizeSpawnerConfig({ mobTypeId }, "spawner");
870 const anchor = form.querySelector("[data-humanoid]") || form.querySelector("[data-spells]");
871 const section = renderCommonSpawnerFields(normalized);
872 if (anchor)
873 { form.insertBefore(section, anchor); }
874 else
875 { form.append(section); }
876 }
877
878 function syncHumanoidSection (config)
879 {
880 form.querySelector("[data-humanoid]")?.remove();
881 const mobTypeId = form.querySelector('[name="mobTypeId"]')?.value;
882 if (!isHumanoidMob(mobTypeId))
883 {
884 sellsDraft = [];
885 equipmentDraft = {};
886 return;
887 }
888 form.append(renderHumanoidFields(config ?? normalizeSpawnerConfig({
889 mobTypeId: mobTypeId || MobId.humanoid
890 }, "spawner")));
891 const maxAlive = form.querySelector('[name="maxAlive"]');
892 if (maxAlive && isCentralExchangeSpawner({ mobTypeId }))
893 {
894 maxAlive.value = String(centralExchangeStaffCount());
895 maxAlive.disabled = true;
896 }
897 else if (maxAlive)
898 { maxAlive.disabled = false; }
899 }
900
901 function syncSpellsSection (config)
902 {
903 form.querySelector("[data-spells]")?.remove();
904 form.append(renderSpellsFields(config));
905 }
906
907 function renderSpellsFields (config)
908 {
909 const wrap = document.createElement("div");
910 wrap.className = "spawner-spells-fields";
911 wrap.dataset.spells = "1";
912
913 const header = document.createElement("div");
914 header.className = "spawner-sells-header";
915 const titleEl = document.createElement("strong");
916 titleEl.textContent = "Spells";
917 const addBtn = document.createElement("button");
918 addBtn.type = "button";
919 addBtn.textContent = "+";
920 addBtn.title = "Add spell";
921 addBtn.addEventListener("click", () =>
922 {
923 const available = Object.values(SPELL_DEFINITIONS).find((def) =>
924 !def.mobOnly
925 && !spellsDraft.some((line) => line.spellId === def.spellId));
926 if (!available)
927 { return; }
928 spellsDraft.push({ spellId: available.spellId });
929 renderSpellsList();
930 });
931 header.append(titleEl, addBtn);
932 wrap.append(header);
933
934 const list = document.createElement("div");
935 list.className = "spawner-sells-list";
936 list.dataset.spellsList = "1";
937 wrap.append(list);
938
939 const hint = document.createElement("p");
940 hint.className = "hint";
941 hint.textContent = "Cast success uses the mob Level as Magic vs the spell tier (same contest as players). Only Attack (entity) spells are used in combat. Mobs only learn spells their Level can cast.";
942 wrap.append(hint);
943
944 if (!Array.isArray(spellsDraft) || !spellsDraft.length)
945 {
946 spellsDraft = (config?.spells ?? []).map((line) => ({
947 spellId: String(line.spellId ?? "")
948 })).filter((line) => line.spellId);
949 }
950 queueMicrotask(() => renderSpellsList());
951 return wrap;
952 }
953
954 function renderSpellsList ()
955 {
956 const list = form.querySelector("[data-spells-list]");
957 if (!list)
958 { return; }
959 list.replaceChildren();
960 if (!spellsDraft.length)
961 {
962 const empty = document.createElement("p");
963 empty.className = "hint";
964 empty.textContent = "No spells.";
965 list.append(empty);
966 return;
967 }
968 const level = Math.max(1, Number(form.querySelector('[name="level"]')?.value) || 1) | 0;
969 for (let index = 0; index < spellsDraft.length; index++)
970 {
971 const line = spellsDraft[index];
972 const def = SPELL_DEFINITIONS[line.spellId];
973 const row = document.createElement("div");
974 row.className = "spawner-sell-row";
975
976 const select = document.createElement("select");
977 for (const spell of Object.values(SPELL_DEFINITIONS))
978 {
979 if (spell.mobOnly)
980 { continue; }
981 const opt = document.createElement("option");
982 opt.value = spell.spellId;
983 const minLv = spellMinMagicLevel(spell);
984 opt.textContent = `${spell.displayName} (Magic ${minLv}+)`;
985 if (spell.spellId === line.spellId)
986 { opt.selected = true; }
987 select.append(opt);
988 }
989 select.addEventListener("change", () =>
990 {
991 spellsDraft[index].spellId = select.value;
992 renderSpellsList();
993 });
994
995 const minLv = spellMinMagicLevel(def);
996 const tier = def?.tier | 0 || 1;
997 const successPct = spellCastSuccessChancePercent(level, tier);
998 const chanceLabel = document.createElement("span");
999 chanceLabel.className = "hint";
1000 chanceLabel.title = `Channel success: Magic ${level} vs tier ${tier} (difficulty ${spellDifficultyFromTier(tier)})`;
1001 chanceLabel.textContent = level < minLv
1002 ? `needs Lv.${minLv}`
1003 : `cast ${formatCastChancePercent(successPct)}%`;
1004
1005 const remove = document.createElement("button");
1006 remove.type = "button";
1007 remove.textContent = "×";
1008 remove.addEventListener("click", () =>
1009 {
1010 spellsDraft.splice(index, 1);
1011 renderSpellsList();
1012 });
1013
1014 row.append(select, chanceLabel, remove);
1015 list.append(row);
1016 }
1017 }
1018
1019 function syncBountyForAggressive ()
1020 {
1021 const bountyInput = form.querySelector('[name="bounty"]');
1022 const aggressiveInput = form.querySelector('[name="aggressive"]');
1023 if (!bountyInput)
1024 { return; }
1025 const aggressive = !!aggressiveInput?.checked;
1026 if (aggressive)
1027 {
1028 bountyInput.value = "0";
1029 bountyInput.disabled = true;
1030 }
1031 else
1032 { bountyInput.disabled = false; }
1033 }
1034
1035 function openSpawner (ctx)
1036 {
1037 context = { kind: "spawner", ...ctx };
1038 const config = normalizeSpawnerConfig(ctx.config, ctx.config.spawnerId);
1039 pendingDialogueId = config.dialogueId ?? null;
1040 dialogueOptions = typeof getDialogues === "function" ? (getDialogues() ?? []) : dialogueOptions;
1041 if (socket && MessageType)
1042 { socket.send({ type: MessageType.editorLoadDialogues }); }
1043 title.textContent = `Spawner · ${ctx.tileX}, ${ctx.tileY}`;
1044 form.innerHTML = "";
1045 const mobField = field("Mob type", mobSelect("mobTypeId", config.mobTypeId));
1046 form.append(
1047 mobField,
1048 field("Level", numberInput("level", config.level ?? 1, 1, 99)),
1049 field("Bounty", numberInput("bounty", config.bounty ?? 0, 0, 1_000_000)),
1050 field("Max alive", numberInput("maxAlive", config.maxAlive, 1, 20)),
1051 field("Respawn delay (seconds)", numberInput("respawnDelaySeconds", config.respawnDelaySeconds ?? 25, 0, 86_400)),
1052 field("Spawn range", numberInput("spawnRangeTiles", config.spawnRangeTiles, 0, 32)),
1053 field("Max wander range", numberInput("maxWanderRangeTiles", config.maxWanderRangeTiles, 0, 64)),
1054 field("Spawner id", textInput("spawnerId", config.spawnerId, true))
1055 );
1056 const spawnInput = form.querySelector('[name="spawnRangeTiles"]');
1057 const wanderInput = form.querySelector('[name="maxWanderRangeTiles"]');
1058 const syncWanderMin = () =>
1059 {
1060 const spawn = Math.max(0, Number(spawnInput.value) || 0);
1061 wanderInput.min = String(spawn);
1062 if (Number(wanderInput.value) < spawn)
1063 { wanderInput.value = String(spawn); }
1064 };
1065 spawnInput.addEventListener("input", syncWanderMin);
1066 syncWanderMin();
1067 form.querySelector('[name="level"]')?.addEventListener("input", () => renderSpellsList());
1068 form.querySelector('[name="mobTypeId"]').addEventListener("change", () =>
1069 {
1070 const nextType = form.querySelector('[name="mobTypeId"]').value;
1071 const defaults = normalizeSpawnerConfig({ mobTypeId: nextType }, config.spawnerId);
1072 form.querySelector('[name="maxAlive"]').value = String(defaults.maxAlive);
1073 form.querySelector('[name="spawnRangeTiles"]').value = String(defaults.spawnRangeTiles);
1074 form.querySelector('[name="maxWanderRangeTiles"]').value = String(defaults.maxWanderRangeTiles);
1075 form.querySelector('[name="level"]').value = String(defaults.level ?? 1);
1076 form.querySelector('[name="bounty"]').value = String(defaults.bounty ?? 0);
1077 syncWanderMin();
1078 syncCommonSpawnerSection(defaults);
1079 syncHumanoidSection(defaults);
1080 syncSpellsSection(defaults);
1081 syncBountyForAggressive();
1082 });
1083 spellsDraft = (config.spells ?? []).map((line) => ({
1084 spellId: String(line.spellId ?? "")
1085 })).filter((line) => line.spellId);
1086 syncCommonSpawnerSection(config);
1087 syncHumanoidSection(config);
1088 syncSpellsSection(config);
1089 syncBountyForAggressive();
1090 show(true);
1091 }
1092
1093 function openFishingSpot (ctx)
1094 {
1095 context = { kind: "fishing-spot", ...ctx };
1096 const normalized = normalizeFishingSpotConfig(ctx.config);
1097 fishesDraft = [...normalized.fishes];
1098 title.textContent = `Fishing spot · ${ctx.tileX}, ${ctx.tileY}`;
1099 form.innerHTML = "";
1100 const header = document.createElement("div");
1101 header.className = "spawner-sells-header";
1102 const label = document.createElement("strong");
1103 label.textContent = "Fishes";
1104 const addBtn = document.createElement("button");
1105 addBtn.type = "button";
1106 addBtn.textContent = "+";
1107 addBtn.title = "Add fish";
1108 addBtn.addEventListener("click", () => openFishItemSearch());
1109 header.append(label, addBtn);
1110 const list = document.createElement("div");
1111 list.setAttribute("data-fishes-list", "");
1112 form.append(header, list);
1113 renderFishesList();
1114 show(true);
1115 }
1116
1117 function openDoorway (ctx)
1118 {
1119 context = { kind: "doorway", ...ctx };
1120 const config = ctx.config && typeof ctx.config === "object" ? ctx.config : {};
1121 const state = DOORWAY_STATES.includes(ctx.state) ? ctx.state : "door";
1122 title.textContent = `Doorway · ${ctx.tileX}, ${ctx.tileY}`;
1123 form.innerHTML = "";
1124 form.append(
1125 field("Appearance", doorwayStateSelect("state", state)),
1126 field("Target tile X", numberInput("tileX", Number.isFinite(Number(config.tileX)) ? Number(config.tileX) : 0, -1_000_000, 1_000_000)),
1127 field("Target tile Y", numberInput("tileY", Number.isFinite(Number(config.tileY)) ? Number(config.tileY) : 0, -1_000_000, 1_000_000))
1128 );
1129 const dimWrap = document.createElement("label");
1130 dimWrap.append(document.createTextNode("Target dimension"));
1131 const dimRoot = document.createElement("div");
1132 dimRoot.className = "doorway-dim-combo";
1133 dimWrap.append(dimRoot);
1134 form.append(dimWrap);
1135 const options = typeof getDimensionOptions === "function" ? (getDimensionOptions() ?? []) : [];
1136 doorwayDimCombo = createDimensionCombobox({
1137 root: dimRoot,
1138 placeholder: "Target dimension…",
1139 onSelect () { }
1140 });
1141 doorwayDimCombo.setOptions(options);
1142 doorwayDimCombo.setValue(normalizeDimensionId(config.targetDimensionId ?? OVERWORLD_ID));
1143 show(true);
1144 }
1145
1146 function renderDoorRequirementsForm ()
1147 {
1148 form.innerHTML = "";
1149 const hint = document.createElement("p");
1150 hint.className = "tile-config-hint";
1151 hint.textContent = "Players who fail these requirements cannot pass this door — even when it is held open.";
1152 form.append(hint);
1153 const whenHost = document.createElement("div");
1154 whenHost.className = "door-requirements-when";
1155 form.append(whenHost);
1156 const remountWhen = () =>
1157 {
1158 whenHost.replaceChildren(renderConditionSet(doorWhenDraft, (next, { remount = true } = {}) =>
1159 {
1160 doorWhenDraft = normalizeConditionSet(next);
1161 if (remount)
1162 { remountWhen(); }
1163 }, {
1164 quests: typeof getQuests === "function" ? (getQuests() ?? []) : [],
1165 dialogues: typeof getDialogues === "function" ? (getDialogues() ?? []) : [],
1166 describeWorldTile,
1167 centerEditorOnTile,
1168 getDimensionOptions
1169 }));
1170 };
1171 remountWhen();
1172 const msgLabel = document.createElement("label");
1173 msgLabel.append(document.createTextNode("Blocked toast"));
1174 const msg = document.createElement("input");
1175 msg.type = "text";
1176 msg.name = "blockedMessage";
1177 msg.maxLength = 200;
1178 msg.placeholder = DEFAULT_DOOR_BLOCKED_MESSAGE;
1179 msg.value = doorBlockedMessageDraft;
1180 msg.addEventListener("input", () =>
1181 {
1182 doorBlockedMessageDraft = msg.value;
1183 });
1184 msgLabel.append(msg);
1185 form.append(msgLabel);
1186 }
1187
1188 function openDoor (ctx)
1189 {
1190 context = { kind: "door", ...ctx };
1191 const config = ctx.config && typeof ctx.config === "object" ? ctx.config : {};
1192 doorWhenDraft = normalizeConditionSet(config.when ?? config.requirements ?? emptyConditionSet());
1193 doorBlockedMessageDraft = String(config.blockedMessage ?? config.denyMessage ?? "").trim();
1194 title.textContent = `Door · ${ctx.tileX}, ${ctx.tileY}`;
1195 if (socket && MessageType)
1196 {
1197 socket.send({ type: MessageType.editorLoadQuests });
1198 socket.send({ type: MessageType.editorLoadDialogues });
1199 }
1200 renderDoorRequirementsForm();
1201 show(true);
1202 }
1203
1204 document.getElementById("tile-config-close").addEventListener("click", () => show(false));
1205 document.getElementById("tile-config-cancel").addEventListener("click", () => show(false));
1206 backdrop.addEventListener("click", () => show(false));
1207 document.getElementById("shop-item-search-close")?.addEventListener("click", () => closeItemSearch());
1208 itemSearchBackdrop?.addEventListener("click", () => closeItemSearch());
1209 itemSearchInput?.addEventListener("input", () =>
1210 {
1211 itemSearchPage = 0;
1212 renderItemSearchResults(itemSearchInput.value);
1213 });
1214 itemSearchPrev?.addEventListener("click", () =>
1215 {
1216 if (itemSearchPage <= 0)
1217 { return; }
1218 itemSearchPage -= 1;
1219 renderItemSearchResults(itemSearchInput?.value ?? "");
1220 });
1221 itemSearchNext?.addEventListener("click", () =>
1222 {
1223 const pageCount = Math.max(1, Math.ceil((itemSearchMatches?.length ?? 0) / ITEM_SEARCH_PAGE_SIZE));
1224 if (itemSearchPage >= pageCount - 1)
1225 { return; }
1226 itemSearchPage += 1;
1227 renderItemSearchResults(itemSearchInput?.value ?? "");
1228 });
1229 document.getElementById("equip-dye-close")?.addEventListener("click", () => closeDyePicker());
1230 dyeBackdrop?.addEventListener("click", () => closeDyePicker());
1231 document.getElementById("equip-dye-apply")?.addEventListener("click", () =>
1232 {
1233 if (!dyeEditSlot || !equipmentDraft[dyeEditSlot])
1234 { return; }
1235 equipmentDraft[dyeEditSlot].dyeColor = readDyeSliders();
1236 closeDyePicker();
1237 renderEquipmentRows();
1238 });
1239 document.getElementById("equip-dye-clear")?.addEventListener("click", () =>
1240 {
1241 if (!dyeEditSlot || !equipmentDraft[dyeEditSlot])
1242 { return; }
1243 equipmentDraft[dyeEditSlot].dyeColor = null;
1244 closeDyePicker();
1245 renderEquipmentRows();
1246 });
1247
1248 document.getElementById("tile-config-save").addEventListener("click", () =>
1249 {
1250 if (!context)
1251 { return; }
1252 if (context.kind === "doorway")
1253 {
1254 const data = new FormData(form);
1255 const stateRaw = String(data.get("state") || "door");
1256 onSave?.(context, {
1257 state: DOORWAY_STATES.includes(stateRaw) ? stateRaw : "door",
1258 targetDimensionId: normalizeDimensionId(doorwayDimCombo?.getValue() ?? OVERWORLD_ID),
1259 tileX: Number(data.get("tileX")) || 0,
1260 tileY: Number(data.get("tileY")) || 0
1261 });
1262 show(false);
1263 return;
1264 }
1265 if (context.kind === "door")
1266 {
1267 onSave?.(context, {
1268 when: normalizeConditionSet(doorWhenDraft),
1269 blockedMessage: String(doorBlockedMessageDraft ?? "").trim()
1270 });
1271 show(false);
1272 return;
1273 }
1274 if (context.kind === "fishing-spot")
1275 {
1276 onSave?.(context, normalizeFishingSpotConfig({ fishes: fishesDraft }));
1277 show(false);
1278 return;
1279 }
1280 const data = new FormData(form);
1281 const equipment = {};
1282 for (const slot of EQUIPMENT_SLOTS)
1283 { equipment[slot] = equipConfigFromDraft(equipmentDraft[slot]); }
1284 onSave?.(context, normalizeSpawnerConfig({
1285 mobTypeId: String(data.get("mobTypeId") || "deer"),
1286 maxAlive: Number(data.get("maxAlive") || 3),
1287 respawnDelaySeconds: Number(data.get("respawnDelaySeconds") ?? 25),
1288 spawnRangeTiles: (() =>
1289 {
1290 const n = Number(data.get("spawnRangeTiles"));
1291 return Number.isFinite(n) ? n : 4;
1292 })(),
1293 maxWanderRangeTiles: (() =>
1294 {
1295 const n = Number(data.get("maxWanderRangeTiles"));
1296 return Number.isFinite(n) ? n : 4;
1297 })(),
1298 level: Number(data.get("level") || 1),
1299 bounty: Number(data.get("bounty") || 0),
1300 aggressive: data.get("aggressive") === "on",
1301 spawnerId: String(data.get("spawnerId") || context.config.spawnerId),
1302 sex: String(data.get("sex") || "male"),
1303 displayName: String(data.get("displayName") || ""),
1304 equipment,
1305 sells: sellsDraft,
1306 drops: dropsDraft.map((line) =>
1307 {
1308 const quantityMin = Math.max(0, Number(line.quantityMin) || 0) | 0;
1309 const quantityMax = Math.max(
1310 quantityMin,
1311 Math.max(0, Number(line.quantityMax) || 0) | 0
1312 );
1313 return {
1314 itemId: line.itemId,
1315 chance: Math.min(100, Math.max(0, Number(line.chancePercent) || 0)) / 100,
1316 quantityMin,
1317 quantityMax
1318 };
1319 }),
1320 spells: spellsDraft,
1321 buysItems: data.get("buysItems") === "on",
1322 hiddenDiscount: Number(data.get("hiddenDiscount") || 0.9),
1323 centralExchange: isCentralExchangeSpawner(String(data.get("mobTypeId") || "")),
1324 dialogueId: String(data.get("dialogueId") || "").trim() || null
1325 }, context.config.spawnerId));
1326 show(false);
1327 });
1328 document.getElementById("tile-config-remove").addEventListener("click", () =>
1329 {
1330 if (!context)
1331 { return; }
1332 if (context.kind === "spawner")
1333 {
1334 const label = context.config?.displayName
1335 || context.config?.mobTypeId
1336 || context.config?.spawnerId
1337 || "this spawner";
1338 if (!window.confirm(`Delete mob spawner "${label}"?`))
1339 { return; }
1340 }
1341 onRemove?.(context);
1342 show(false);
1343 });
1344
1345 return {
1346 isOpen: () => open,
1347 openSpawner,
1348 openDoorway,
1349 openDoor,
1350 openFishingSpot,
1351 close: () => show(false),
1352 handleMessage (message)
1353 {
1354 if (!MessageType)
1355 { return; }
1356 if (message.type === MessageType.editorDialogues)
1357 {
1358 dialogueOptions = (message.dialogues ?? []).map((d) => ({
1359 dialogueId: String(d.dialogueId ?? ""),
1360 label: String(d.label ?? d.dialogueId ?? ""),
1361 unique: !!d.unique
1362 })).filter((d) => d.dialogueId);
1363 const select = form.querySelector('[name="dialogueId"]');
1364 if (select && open)
1365 {
1366 const current = select.value || pendingDialogueId || "";
1367 select.replaceWith(dialogueSelect("dialogueId", current, dialogueOptions));
1368 }
1369 if (open && context?.kind === "door")
1370 { renderDoorRequirementsForm(); }
1371 return;
1372 }
1373 if (message.type === MessageType.editorQuests && open && context?.kind === "door")
1374 { renderDoorRequirementsForm(); }
1375 }
1376 };
1377}
1378
1379function doorwayStateSelect (name, value)
1380{
1381 const select = document.createElement("select");
1382 select.name = name;
1383 for (const state of DOORWAY_STATES)
1384 {
1385 const opt = document.createElement("option");
1386 opt.value = state;
1387 opt.textContent = state.charAt(0).toUpperCase() + state.slice(1);
1388 if (state === value)
1389 { opt.selected = true; }
1390 select.append(opt);
1391 }
1392 return select;
1393}
1394
1395function field (label, input)
1396{
1397 const wrap = document.createElement("label");
1398 wrap.append(document.createTextNode(label), input);
1399 return wrap;
1400}
1401
1402function numberInput (name, value, min, max, step = 1)
1403{
1404 const input = document.createElement("input");
1405 input.type = "number";
1406 input.name = name;
1407 input.min = String(min);
1408 input.max = String(max);
1409 input.step = String(step);
1410 input.value = String(value);
1411 return input;
1412}
1413
1414function textInput (name, value, readOnly = false)
1415{
1416 const input = document.createElement("input");
1417 input.type = "text";
1418 input.name = name;
1419 input.value = String(value ?? "");
1420 input.readOnly = readOnly;
1421 return input;
1422}
1423
1424function sexSelect (name, value)
1425{
1426 const select = document.createElement("select");
1427 select.name = name;
1428 for (const sex of ["male", "female"])
1429 {
1430 const option = document.createElement("option");
1431 option.value = sex;
1432 option.textContent = sex;
1433 if (sex === value)
1434 { option.selected = true; }
1435 select.append(option);
1436 }
1437 return select;
1438}
1439
1440function mobSelect (name, value)
1441{
1442 const select = document.createElement("select");
1443 select.name = name;
1444 for (const def of listSpawnableMobTypes())
1445 {
1446 const option = document.createElement("option");
1447 option.value = def.mobTypeId;
1448 option.textContent = def.displayName;
1449 if (def.mobTypeId === value)
1450 { option.selected = true; }
1451 select.append(option);
1452 }
1453 return select;
1454}
1455
1456function dialogueSelect (name, value, options = [])
1457{
1458 const select = document.createElement("select");
1459 select.name = name;
1460 const none = document.createElement("option");
1461 none.value = "";
1462 none.textContent = "(none)";
1463 select.append(none);
1464 const selected = String(value ?? "");
1465 let found = !selected;
1466 for (const entry of options)
1467 {
1468 const option = document.createElement("option");
1469 option.value = entry.dialogueId;
1470 option.textContent = entry.unique
1471 ? `${entry.label} [${entry.dialogueId}] · unique`
1472 : `${entry.label} [${entry.dialogueId}]`;
1473 if (entry.dialogueId === selected)
1474 {
1475 option.selected = true;
1476 found = true;
1477 }
1478 select.append(option);
1479 }
1480 if (selected && !found)
1481 {
1482 const orphan = document.createElement("option");
1483 orphan.value = selected;
1484 orphan.textContent = `${selected} (missing)`;
1485 orphan.selected = true;
1486 select.append(orphan);
1487 }
1488 return select;
1489}