BlueGit

timfa questward

Files

questward / client / src / editor / tileConfigModal.js

tileConfigModal.js

tileConfigModal.js 48.8 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 // Wildlife: Passive without Aggressive checkbox (Aggressive comes from mob def).
718 if (!isHumanoidMob(config.mobTypeId) && !isCentralExchangeSpawner(config))
719 {
720 const defAggressive = !!def?.aggressive;
721 const passiveLabel = document.createElement("label");
722 passiveLabel.className = "spawner-buys-row";
723 const passive = document.createElement("input");
724 passive.type = "checkbox";
725 passive.name = "passive";
726 passive.checked = !!config.passive && !defAggressive;
727 passive.disabled = defAggressive;
728 passiveLabel.append(passive, document.createTextNode(" Passive (takes hits, does not fight back)"));
729 wrap.append(passiveLabel);
730 const passiveHint = document.createElement("p");
731 passiveHint.className = "hint";
732 passiveHint.textContent = defAggressive
733 ? "Unavailable: this mob type is Aggressive by definition."
734 : "Passive mobs take hits but never retaliate when attacked.";
735 wrap.append(passiveHint);
736 }
737 }
738
739 const dropsHeader = document.createElement("div");
740 dropsHeader.className = "spawner-sells-header";
741 const dropsTitle = document.createElement("strong");
742 dropsTitle.textContent = "Drops";
743 const dropsAddBtn = document.createElement("button");
744 dropsAddBtn.type = "button";
745 dropsAddBtn.textContent = "+";
746 dropsAddBtn.title = "Add drop";
747 dropsAddBtn.addEventListener("click", () => openDropItemSearch());
748 dropsHeader.append(dropsTitle, dropsAddBtn);
749 wrap.append(dropsHeader);
750
751 const dropsList = document.createElement("div");
752 dropsList.className = "spawner-sells-list";
753 dropsList.dataset.dropsList = "1";
754 wrap.append(dropsList);
755
756 const dropsHint = document.createElement("p");
757 dropsHint.className = "hint";
758 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).";
759 wrap.append(dropsHint);
760
761 dropsDraft = (config.drops ?? []).map((line) =>
762 {
763 if (!line || typeof line !== "object")
764 { return null; }
765 const itemId = line.itemId | 0;
766 if (itemId <= 0)
767 { return null; }
768 let chancePercent = Number(line.chance);
769 if (!Number.isFinite(chancePercent))
770 { chancePercent = 100; }
771 else if (chancePercent <= 1)
772 { chancePercent = chancePercent * 100; }
773 let quantityMin = Math.max(0, Math.floor(Number(line.quantityMin ?? line.quantity ?? 1)));
774 let quantityMax = Math.max(0, Math.floor(Number(line.quantityMax ?? quantityMin)));
775 if (!Number.isFinite(quantityMin))
776 { quantityMin = 1; }
777 if (!Number.isFinite(quantityMax) || quantityMax < quantityMin)
778 { quantityMax = quantityMin; }
779 return {
780 itemId,
781 chancePercent: Math.min(100, Math.max(0, chancePercent)),
782 quantityMin,
783 quantityMax
784 };
785 }).filter(Boolean);
786
787 queueMicrotask(() => renderDropsList());
788 return wrap;
789 }
790
791 function renderHumanoidFields (config)
792 {
793 const wrap = document.createElement("div");
794 wrap.className = "spawner-humanoid-fields";
795 wrap.dataset.humanoid = "1";
796 const exchange = isCentralExchangeSpawner(config);
797 if (!exchange)
798 {
799 wrap.append(field("Sex", sexSelect("sex", config.sex)));
800 }
801
802 const aggressiveLabel = document.createElement("label");
803 aggressiveLabel.className = "spawner-buys-row";
804 const aggressive = document.createElement("input");
805 aggressive.type = "checkbox";
806 aggressive.name = "aggressive";
807 aggressive.checked = !!config.aggressive;
808 aggressive.addEventListener("change", () => syncAggressivePassive());
809 aggressiveLabel.append(aggressive, document.createTextNode(" Aggressive (attacks players in range)"));
810 wrap.append(aggressiveLabel);
811 const aggressiveHint = document.createElement("p");
812 aggressiveHint.className = "hint";
813 aggressiveHint.textContent = "When Aggressive is on, Bounty is forced to 0 and Passive is unavailable.";
814 wrap.append(aggressiveHint);
815
816 const passiveLabel = document.createElement("label");
817 passiveLabel.className = "spawner-buys-row";
818 const passive = document.createElement("input");
819 passive.type = "checkbox";
820 passive.name = "passive";
821 passive.checked = !!config.passive && !config.aggressive;
822 passive.disabled = !!config.aggressive;
823 passiveLabel.append(passive, document.createTextNode(" Passive (takes hits, does not fight back)"));
824 wrap.append(passiveLabel);
825 const passiveHint = document.createElement("p");
826 passiveHint.className = "hint";
827 passiveHint.textContent = "Only available while Aggressive is off. Passive mobs never retaliate when attacked.";
828 wrap.append(passiveHint);
829
830 wrap.append(field("Dialogue", dialogueSelect("dialogueId", config.dialogueId ?? "", dialogueOptions)));
831
832 const equipHeader = document.createElement("div");
833 equipHeader.className = "spawner-sells-header";
834 const equipTitle = document.createElement("strong");
835 equipTitle.textContent = "Equipment";
836 equipHeader.append(equipTitle);
837 wrap.append(equipHeader);
838
839 const equipList = document.createElement("div");
840 equipList.className = "spawner-equip-list";
841 equipList.dataset.equipmentList = "1";
842 wrap.append(equipList);
843
844 equipmentDraft = {};
845 for (const slot of EQUIPMENT_SLOTS)
846 { equipmentDraft[slot] = equipDraftFromConfig(config.equipment?.[slot]); }
847 queueMicrotask(() => renderEquipmentRows());
848
849 if (!exchange)
850 {
851 wrap.append(field("Hidden discount (0–1)", numberInput("hiddenDiscount", config.hiddenDiscount ?? 0.9, 0.01, 1, 0.01)));
852
853 const sellsHeader = document.createElement("div");
854 sellsHeader.className = "spawner-sells-header";
855 const sellsTitle = document.createElement("strong");
856 sellsTitle.textContent = "Sells";
857 const addBtn = document.createElement("button");
858 addBtn.type = "button";
859 addBtn.textContent = "+";
860 addBtn.title = "Add item";
861 addBtn.addEventListener("click", () => openSellItemSearch());
862 sellsHeader.append(sellsTitle, addBtn);
863 wrap.append(sellsHeader);
864
865 const list = document.createElement("div");
866 list.className = "spawner-sells-list";
867 list.dataset.sellsList = "1";
868 wrap.append(list);
869
870 const buysLabel = document.createElement("label");
871 buysLabel.className = "spawner-buys-row";
872 const buys = document.createElement("input");
873 buys.type = "checkbox";
874 buys.name = "buysItems";
875 buys.checked = !!config.buysItems;
876 buysLabel.append(buys, document.createTextNode(" Buys items"));
877 wrap.append(buysLabel);
878
879 const hint = document.createElement("p");
880 hint.className = "hint";
881 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.";
882 wrap.append(hint);
883
884 sellsDraft = (config.sells ?? []).map((line) =>
885 {
886 if (line && typeof line === "object")
887 { return { itemId: line.itemId | 0, quantity: Math.max(0, line.quantity | 0 || 0) }; }
888 return { itemId: line | 0, quantity: 0 };
889 }).filter((line) => line.itemId > 0);
890
891 queueMicrotask(() => renderSellsList());
892 }
893 else
894 { sellsDraft = []; }
895 return wrap;
896 }
897
898 function syncCommonSpawnerSection (config)
899 {
900 form.querySelector("[data-common-spawner]")?.remove();
901 const mobTypeId = form.querySelector('[name="mobTypeId"]')?.value
902 || config?.mobTypeId
903 || MobId.deer;
904 const normalized = config ?? normalizeSpawnerConfig({ mobTypeId }, "spawner");
905 const anchor = form.querySelector("[data-humanoid]") || form.querySelector("[data-spells]");
906 const section = renderCommonSpawnerFields(normalized);
907 if (anchor)
908 { form.insertBefore(section, anchor); }
909 else
910 { form.append(section); }
911 }
912
913 function syncHumanoidSection (config)
914 {
915 form.querySelector("[data-humanoid]")?.remove();
916 const mobTypeId = form.querySelector('[name="mobTypeId"]')?.value;
917 if (!isHumanoidMob(mobTypeId))
918 {
919 sellsDraft = [];
920 equipmentDraft = {};
921 return;
922 }
923 form.append(renderHumanoidFields(config ?? normalizeSpawnerConfig({
924 mobTypeId: mobTypeId || MobId.humanoid
925 }, "spawner")));
926 const maxAlive = form.querySelector('[name="maxAlive"]');
927 if (maxAlive && isCentralExchangeSpawner({ mobTypeId }))
928 {
929 maxAlive.value = String(centralExchangeStaffCount());
930 maxAlive.disabled = true;
931 }
932 else if (maxAlive)
933 { maxAlive.disabled = false; }
934 }
935
936 function syncSpellsSection (config)
937 {
938 form.querySelector("[data-spells]")?.remove();
939 form.append(renderSpellsFields(config));
940 }
941
942 function renderSpellsFields (config)
943 {
944 const wrap = document.createElement("div");
945 wrap.className = "spawner-spells-fields";
946 wrap.dataset.spells = "1";
947
948 const header = document.createElement("div");
949 header.className = "spawner-sells-header";
950 const titleEl = document.createElement("strong");
951 titleEl.textContent = "Spells";
952 const addBtn = document.createElement("button");
953 addBtn.type = "button";
954 addBtn.textContent = "+";
955 addBtn.title = "Add spell";
956 addBtn.addEventListener("click", () =>
957 {
958 const available = Object.values(SPELL_DEFINITIONS).find((def) =>
959 !def.mobOnly
960 && !spellsDraft.some((line) => line.spellId === def.spellId));
961 if (!available)
962 { return; }
963 spellsDraft.push({ spellId: available.spellId });
964 renderSpellsList();
965 });
966 header.append(titleEl, addBtn);
967 wrap.append(header);
968
969 const list = document.createElement("div");
970 list.className = "spawner-sells-list";
971 list.dataset.spellsList = "1";
972 wrap.append(list);
973
974 const hint = document.createElement("p");
975 hint.className = "hint";
976 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.";
977 wrap.append(hint);
978
979 if (!Array.isArray(spellsDraft) || !spellsDraft.length)
980 {
981 spellsDraft = (config?.spells ?? []).map((line) => ({
982 spellId: String(line.spellId ?? "")
983 })).filter((line) => line.spellId);
984 }
985 queueMicrotask(() => renderSpellsList());
986 return wrap;
987 }
988
989 function renderSpellsList ()
990 {
991 const list = form.querySelector("[data-spells-list]");
992 if (!list)
993 { return; }
994 list.replaceChildren();
995 if (!spellsDraft.length)
996 {
997 const empty = document.createElement("p");
998 empty.className = "hint";
999 empty.textContent = "No spells.";
1000 list.append(empty);
1001 return;
1002 }
1003 const level = Math.max(1, Number(form.querySelector('[name="level"]')?.value) || 1) | 0;
1004 for (let index = 0; index < spellsDraft.length; index++)
1005 {
1006 const line = spellsDraft[index];
1007 const def = SPELL_DEFINITIONS[line.spellId];
1008 const row = document.createElement("div");
1009 row.className = "spawner-sell-row";
1010
1011 const select = document.createElement("select");
1012 for (const spell of Object.values(SPELL_DEFINITIONS))
1013 {
1014 if (spell.mobOnly)
1015 { continue; }
1016 const opt = document.createElement("option");
1017 opt.value = spell.spellId;
1018 const minLv = spellMinMagicLevel(spell);
1019 opt.textContent = `${spell.displayName} (Magic ${minLv}+)`;
1020 if (spell.spellId === line.spellId)
1021 { opt.selected = true; }
1022 select.append(opt);
1023 }
1024 select.addEventListener("change", () =>
1025 {
1026 spellsDraft[index].spellId = select.value;
1027 renderSpellsList();
1028 });
1029
1030 const minLv = spellMinMagicLevel(def);
1031 const tier = def?.tier | 0 || 1;
1032 const successPct = spellCastSuccessChancePercent(level, tier);
1033 const chanceLabel = document.createElement("span");
1034 chanceLabel.className = "hint";
1035 chanceLabel.title = `Channel success: Magic ${level} vs tier ${tier} (difficulty ${spellDifficultyFromTier(tier)})`;
1036 chanceLabel.textContent = level < minLv
1037 ? `needs Lv.${minLv}`
1038 : `cast ${formatCastChancePercent(successPct)}%`;
1039
1040 const remove = document.createElement("button");
1041 remove.type = "button";
1042 remove.textContent = "×";
1043 remove.addEventListener("click", () =>
1044 {
1045 spellsDraft.splice(index, 1);
1046 renderSpellsList();
1047 });
1048
1049 row.append(select, chanceLabel, remove);
1050 list.append(row);
1051 }
1052 }
1053
1054 function syncAggressivePassive ()
1055 {
1056 const bountyInput = form.querySelector('[name="bounty"]');
1057 const aggressiveInput = form.querySelector('[name="aggressive"]');
1058 const passiveInput = form.querySelector('[name="passive"]');
1059 const aggressive = !!aggressiveInput?.checked;
1060 if (bountyInput)
1061 {
1062 if (aggressive)
1063 {
1064 bountyInput.value = "0";
1065 bountyInput.disabled = true;
1066 }
1067 else
1068 { bountyInput.disabled = false; }
1069 }
1070 if (passiveInput)
1071 {
1072 if (aggressive)
1073 {
1074 passiveInput.checked = false;
1075 passiveInput.disabled = true;
1076 }
1077 else
1078 { passiveInput.disabled = false; }
1079 }
1080 }
1081
1082 function openSpawner (ctx)
1083 {
1084 context = { kind: "spawner", ...ctx };
1085 const config = normalizeSpawnerConfig(ctx.config, ctx.config.spawnerId);
1086 pendingDialogueId = config.dialogueId ?? null;
1087 dialogueOptions = typeof getDialogues === "function" ? (getDialogues() ?? []) : dialogueOptions;
1088 if (socket && MessageType)
1089 { socket.send({ type: MessageType.editorLoadDialogues }); }
1090 title.textContent = `Spawner · ${ctx.tileX}, ${ctx.tileY}`;
1091 form.innerHTML = "";
1092 const mobField = field("Mob type", mobSelect("mobTypeId", config.mobTypeId));
1093 form.append(
1094 mobField,
1095 field("Level", numberInput("level", config.level ?? 1, 1, 99)),
1096 field("Bounty", numberInput("bounty", config.bounty ?? 0, 0, 1_000_000)),
1097 field("Max alive", numberInput("maxAlive", config.maxAlive, 1, 20)),
1098 field("Respawn delay (seconds)", numberInput("respawnDelaySeconds", config.respawnDelaySeconds ?? 25, 0, 86_400)),
1099 field("Spawn range", numberInput("spawnRangeTiles", config.spawnRangeTiles, 0, 32)),
1100 field("Max wander range", numberInput("maxWanderRangeTiles", config.maxWanderRangeTiles, 0, 64)),
1101 field("Spawner id", textInput("spawnerId", config.spawnerId, true))
1102 );
1103 const spawnInput = form.querySelector('[name="spawnRangeTiles"]');
1104 const wanderInput = form.querySelector('[name="maxWanderRangeTiles"]');
1105 const syncWanderMin = () =>
1106 {
1107 const spawn = Math.max(0, Number(spawnInput.value) || 0);
1108 wanderInput.min = String(spawn);
1109 if (Number(wanderInput.value) < spawn)
1110 { wanderInput.value = String(spawn); }
1111 };
1112 spawnInput.addEventListener("input", syncWanderMin);
1113 syncWanderMin();
1114 form.querySelector('[name="level"]')?.addEventListener("input", () => renderSpellsList());
1115 form.querySelector('[name="mobTypeId"]').addEventListener("change", () =>
1116 {
1117 const nextType = form.querySelector('[name="mobTypeId"]').value;
1118 const defaults = normalizeSpawnerConfig({ mobTypeId: nextType }, config.spawnerId);
1119 form.querySelector('[name="maxAlive"]').value = String(defaults.maxAlive);
1120 form.querySelector('[name="spawnRangeTiles"]').value = String(defaults.spawnRangeTiles);
1121 form.querySelector('[name="maxWanderRangeTiles"]').value = String(defaults.maxWanderRangeTiles);
1122 form.querySelector('[name="level"]').value = String(defaults.level ?? 1);
1123 form.querySelector('[name="bounty"]').value = String(defaults.bounty ?? 0);
1124 syncWanderMin();
1125 syncCommonSpawnerSection(defaults);
1126 syncHumanoidSection(defaults);
1127 syncSpellsSection(defaults);
1128 syncAggressivePassive();
1129 });
1130 spellsDraft = (config.spells ?? []).map((line) => ({
1131 spellId: String(line.spellId ?? "")
1132 })).filter((line) => line.spellId);
1133 syncCommonSpawnerSection(config);
1134 syncHumanoidSection(config);
1135 syncSpellsSection(config);
1136 syncAggressivePassive();
1137 show(true);
1138 }
1139
1140 function openFishingSpot (ctx)
1141 {
1142 context = { kind: "fishing-spot", ...ctx };
1143 const normalized = normalizeFishingSpotConfig(ctx.config);
1144 fishesDraft = [...normalized.fishes];
1145 title.textContent = `Fishing spot · ${ctx.tileX}, ${ctx.tileY}`;
1146 form.innerHTML = "";
1147 const header = document.createElement("div");
1148 header.className = "spawner-sells-header";
1149 const label = document.createElement("strong");
1150 label.textContent = "Fishes";
1151 const addBtn = document.createElement("button");
1152 addBtn.type = "button";
1153 addBtn.textContent = "+";
1154 addBtn.title = "Add fish";
1155 addBtn.addEventListener("click", () => openFishItemSearch());
1156 header.append(label, addBtn);
1157 const list = document.createElement("div");
1158 list.setAttribute("data-fishes-list", "");
1159 form.append(header, list);
1160 renderFishesList();
1161 show(true);
1162 }
1163
1164 function openDoorway (ctx)
1165 {
1166 context = { kind: "doorway", ...ctx };
1167 const config = ctx.config && typeof ctx.config === "object" ? ctx.config : {};
1168 const state = DOORWAY_STATES.includes(ctx.state) ? ctx.state : "door";
1169 title.textContent = `Doorway · ${ctx.tileX}, ${ctx.tileY}`;
1170 form.innerHTML = "";
1171 form.append(
1172 field("Appearance", doorwayStateSelect("state", state)),
1173 field("Target tile X", numberInput("tileX", Number.isFinite(Number(config.tileX)) ? Number(config.tileX) : 0, -1_000_000, 1_000_000)),
1174 field("Target tile Y", numberInput("tileY", Number.isFinite(Number(config.tileY)) ? Number(config.tileY) : 0, -1_000_000, 1_000_000))
1175 );
1176 const dimWrap = document.createElement("label");
1177 dimWrap.append(document.createTextNode("Target dimension"));
1178 const dimRoot = document.createElement("div");
1179 dimRoot.className = "doorway-dim-combo";
1180 dimWrap.append(dimRoot);
1181 form.append(dimWrap);
1182 const options = typeof getDimensionOptions === "function" ? (getDimensionOptions() ?? []) : [];
1183 doorwayDimCombo = createDimensionCombobox({
1184 root: dimRoot,
1185 placeholder: "Target dimension…",
1186 onSelect () { }
1187 });
1188 doorwayDimCombo.setOptions(options);
1189 doorwayDimCombo.setValue(normalizeDimensionId(config.targetDimensionId ?? OVERWORLD_ID));
1190 show(true);
1191 }
1192
1193 function renderDoorRequirementsForm ()
1194 {
1195 form.innerHTML = "";
1196 const hint = document.createElement("p");
1197 hint.className = "tile-config-hint";
1198 hint.textContent = "Players who fail these requirements cannot pass this door — even when it is held open.";
1199 form.append(hint);
1200 const whenHost = document.createElement("div");
1201 whenHost.className = "door-requirements-when";
1202 form.append(whenHost);
1203 const remountWhen = () =>
1204 {
1205 whenHost.replaceChildren(renderConditionSet(doorWhenDraft, (next, { remount = true } = {}) =>
1206 {
1207 doorWhenDraft = normalizeConditionSet(next);
1208 if (remount)
1209 { remountWhen(); }
1210 }, {
1211 quests: typeof getQuests === "function" ? (getQuests() ?? []) : [],
1212 dialogues: typeof getDialogues === "function" ? (getDialogues() ?? []) : [],
1213 describeWorldTile,
1214 centerEditorOnTile,
1215 getDimensionOptions
1216 }));
1217 };
1218 remountWhen();
1219 const msgLabel = document.createElement("label");
1220 msgLabel.append(document.createTextNode("Blocked toast"));
1221 const msg = document.createElement("input");
1222 msg.type = "text";
1223 msg.name = "blockedMessage";
1224 msg.maxLength = 200;
1225 msg.placeholder = DEFAULT_DOOR_BLOCKED_MESSAGE;
1226 msg.value = doorBlockedMessageDraft;
1227 msg.addEventListener("input", () =>
1228 {
1229 doorBlockedMessageDraft = msg.value;
1230 });
1231 msgLabel.append(msg);
1232 form.append(msgLabel);
1233 }
1234
1235 function openDoor (ctx)
1236 {
1237 context = { kind: "door", ...ctx };
1238 const config = ctx.config && typeof ctx.config === "object" ? ctx.config : {};
1239 doorWhenDraft = normalizeConditionSet(config.when ?? config.requirements ?? emptyConditionSet());
1240 doorBlockedMessageDraft = String(config.blockedMessage ?? config.denyMessage ?? "").trim();
1241 title.textContent = `Door · ${ctx.tileX}, ${ctx.tileY}`;
1242 if (socket && MessageType)
1243 {
1244 socket.send({ type: MessageType.editorLoadQuests });
1245 socket.send({ type: MessageType.editorLoadDialogues });
1246 }
1247 renderDoorRequirementsForm();
1248 show(true);
1249 }
1250
1251 document.getElementById("tile-config-close").addEventListener("click", () => show(false));
1252 document.getElementById("tile-config-cancel").addEventListener("click", () => show(false));
1253 backdrop.addEventListener("click", () => show(false));
1254 document.getElementById("shop-item-search-close")?.addEventListener("click", () => closeItemSearch());
1255 itemSearchBackdrop?.addEventListener("click", () => closeItemSearch());
1256 itemSearchInput?.addEventListener("input", () =>
1257 {
1258 itemSearchPage = 0;
1259 renderItemSearchResults(itemSearchInput.value);
1260 });
1261 itemSearchPrev?.addEventListener("click", () =>
1262 {
1263 if (itemSearchPage <= 0)
1264 { return; }
1265 itemSearchPage -= 1;
1266 renderItemSearchResults(itemSearchInput?.value ?? "");
1267 });
1268 itemSearchNext?.addEventListener("click", () =>
1269 {
1270 const pageCount = Math.max(1, Math.ceil((itemSearchMatches?.length ?? 0) / ITEM_SEARCH_PAGE_SIZE));
1271 if (itemSearchPage >= pageCount - 1)
1272 { return; }
1273 itemSearchPage += 1;
1274 renderItemSearchResults(itemSearchInput?.value ?? "");
1275 });
1276 document.getElementById("equip-dye-close")?.addEventListener("click", () => closeDyePicker());
1277 dyeBackdrop?.addEventListener("click", () => closeDyePicker());
1278 document.getElementById("equip-dye-apply")?.addEventListener("click", () =>
1279 {
1280 if (!dyeEditSlot || !equipmentDraft[dyeEditSlot])
1281 { return; }
1282 equipmentDraft[dyeEditSlot].dyeColor = readDyeSliders();
1283 closeDyePicker();
1284 renderEquipmentRows();
1285 });
1286 document.getElementById("equip-dye-clear")?.addEventListener("click", () =>
1287 {
1288 if (!dyeEditSlot || !equipmentDraft[dyeEditSlot])
1289 { return; }
1290 equipmentDraft[dyeEditSlot].dyeColor = null;
1291 closeDyePicker();
1292 renderEquipmentRows();
1293 });
1294
1295 document.getElementById("tile-config-save").addEventListener("click", () =>
1296 {
1297 if (!context)
1298 { return; }
1299 if (context.kind === "doorway")
1300 {
1301 const data = new FormData(form);
1302 const stateRaw = String(data.get("state") || "door");
1303 onSave?.(context, {
1304 state: DOORWAY_STATES.includes(stateRaw) ? stateRaw : "door",
1305 targetDimensionId: normalizeDimensionId(doorwayDimCombo?.getValue() ?? OVERWORLD_ID),
1306 tileX: Number(data.get("tileX")) || 0,
1307 tileY: Number(data.get("tileY")) || 0
1308 });
1309 show(false);
1310 return;
1311 }
1312 if (context.kind === "door")
1313 {
1314 onSave?.(context, {
1315 when: normalizeConditionSet(doorWhenDraft),
1316 blockedMessage: String(doorBlockedMessageDraft ?? "").trim()
1317 });
1318 show(false);
1319 return;
1320 }
1321 if (context.kind === "fishing-spot")
1322 {
1323 onSave?.(context, normalizeFishingSpotConfig({ fishes: fishesDraft }));
1324 show(false);
1325 return;
1326 }
1327 const data = new FormData(form);
1328 const equipment = {};
1329 for (const slot of EQUIPMENT_SLOTS)
1330 { equipment[slot] = equipConfigFromDraft(equipmentDraft[slot]); }
1331 onSave?.(context, normalizeSpawnerConfig({
1332 mobTypeId: String(data.get("mobTypeId") || "deer"),
1333 maxAlive: Number(data.get("maxAlive") || 3),
1334 respawnDelaySeconds: Number(data.get("respawnDelaySeconds") ?? 25),
1335 spawnRangeTiles: (() =>
1336 {
1337 const n = Number(data.get("spawnRangeTiles"));
1338 return Number.isFinite(n) ? n : 4;
1339 })(),
1340 maxWanderRangeTiles: (() =>
1341 {
1342 const n = Number(data.get("maxWanderRangeTiles"));
1343 return Number.isFinite(n) ? n : 4;
1344 })(),
1345 level: Number(data.get("level") || 1),
1346 bounty: Number(data.get("bounty") || 0),
1347 aggressive: data.get("aggressive") === "on",
1348 passive: data.get("aggressive") === "on" ? false : data.get("passive") === "on",
1349 spawnerId: String(data.get("spawnerId") || context.config.spawnerId),
1350 sex: String(data.get("sex") || "male"),
1351 displayName: String(data.get("displayName") || ""),
1352 equipment,
1353 sells: sellsDraft,
1354 drops: dropsDraft.map((line) =>
1355 {
1356 const quantityMin = Math.max(0, Number(line.quantityMin) || 0) | 0;
1357 const quantityMax = Math.max(
1358 quantityMin,
1359 Math.max(0, Number(line.quantityMax) || 0) | 0
1360 );
1361 return {
1362 itemId: line.itemId,
1363 chance: Math.min(100, Math.max(0, Number(line.chancePercent) || 0)) / 100,
1364 quantityMin,
1365 quantityMax
1366 };
1367 }),
1368 spells: spellsDraft,
1369 buysItems: data.get("buysItems") === "on",
1370 hiddenDiscount: Number(data.get("hiddenDiscount") || 0.9),
1371 centralExchange: isCentralExchangeSpawner(String(data.get("mobTypeId") || "")),
1372 dialogueId: String(data.get("dialogueId") || "").trim() || null
1373 }, context.config.spawnerId));
1374 show(false);
1375 });
1376 document.getElementById("tile-config-remove").addEventListener("click", () =>
1377 {
1378 if (!context)
1379 { return; }
1380 if (context.kind === "spawner")
1381 {
1382 const label = context.config?.displayName
1383 || context.config?.mobTypeId
1384 || context.config?.spawnerId
1385 || "this spawner";
1386 if (!window.confirm(`Delete mob spawner "${label}"?`))
1387 { return; }
1388 }
1389 onRemove?.(context);
1390 show(false);
1391 });
1392
1393 return {
1394 isOpen: () => open,
1395 openSpawner,
1396 openDoorway,
1397 openDoor,
1398 openFishingSpot,
1399 close: () => show(false),
1400 handleMessage (message)
1401 {
1402 if (!MessageType)
1403 { return; }
1404 if (message.type === MessageType.editorDialogues)
1405 {
1406 dialogueOptions = (message.dialogues ?? []).map((d) => ({
1407 dialogueId: String(d.dialogueId ?? ""),
1408 label: String(d.label ?? d.dialogueId ?? ""),
1409 unique: !!d.unique
1410 })).filter((d) => d.dialogueId);
1411 const select = form.querySelector('[name="dialogueId"]');
1412 if (select && open)
1413 {
1414 const current = select.value || pendingDialogueId || "";
1415 select.replaceWith(dialogueSelect("dialogueId", current, dialogueOptions));
1416 }
1417 if (open && context?.kind === "door")
1418 { renderDoorRequirementsForm(); }
1419 return;
1420 }
1421 if (message.type === MessageType.editorQuests && open && context?.kind === "door")
1422 { renderDoorRequirementsForm(); }
1423 }
1424 };
1425}
1426
1427function doorwayStateSelect (name, value)
1428{
1429 const select = document.createElement("select");
1430 select.name = name;
1431 for (const state of DOORWAY_STATES)
1432 {
1433 const opt = document.createElement("option");
1434 opt.value = state;
1435 opt.textContent = state.charAt(0).toUpperCase() + state.slice(1);
1436 if (state === value)
1437 { opt.selected = true; }
1438 select.append(opt);
1439 }
1440 return select;
1441}
1442
1443function field (label, input)
1444{
1445 const wrap = document.createElement("label");
1446 wrap.append(document.createTextNode(label), input);
1447 return wrap;
1448}
1449
1450function numberInput (name, value, min, max, step = 1)
1451{
1452 const input = document.createElement("input");
1453 input.type = "number";
1454 input.name = name;
1455 input.min = String(min);
1456 input.max = String(max);
1457 input.step = String(step);
1458 input.value = String(value);
1459 return input;
1460}
1461
1462function textInput (name, value, readOnly = false)
1463{
1464 const input = document.createElement("input");
1465 input.type = "text";
1466 input.name = name;
1467 input.value = String(value ?? "");
1468 input.readOnly = readOnly;
1469 return input;
1470}
1471
1472function sexSelect (name, value)
1473{
1474 const select = document.createElement("select");
1475 select.name = name;
1476 for (const sex of ["male", "female"])
1477 {
1478 const option = document.createElement("option");
1479 option.value = sex;
1480 option.textContent = sex;
1481 if (sex === value)
1482 { option.selected = true; }
1483 select.append(option);
1484 }
1485 return select;
1486}
1487
1488function mobSelect (name, value)
1489{
1490 const select = document.createElement("select");
1491 select.name = name;
1492 for (const def of listSpawnableMobTypes())
1493 {
1494 const option = document.createElement("option");
1495 option.value = def.mobTypeId;
1496 option.textContent = def.displayName;
1497 if (def.mobTypeId === value)
1498 { option.selected = true; }
1499 select.append(option);
1500 }
1501 return select;
1502}
1503
1504function dialogueSelect (name, value, options = [])
1505{
1506 const select = document.createElement("select");
1507 select.name = name;
1508 const none = document.createElement("option");
1509 none.value = "";
1510 none.textContent = "(none)";
1511 select.append(none);
1512 const selected = String(value ?? "");
1513 let found = !selected;
1514 for (const entry of options)
1515 {
1516 const option = document.createElement("option");
1517 option.value = entry.dialogueId;
1518 option.textContent = entry.unique
1519 ? `${entry.label} [${entry.dialogueId}] · unique`
1520 : `${entry.label} [${entry.dialogueId}]`;
1521 if (entry.dialogueId === selected)
1522 {
1523 option.selected = true;
1524 found = true;
1525 }
1526 select.append(option);
1527 }
1528 if (selected && !found)
1529 {
1530 const orphan = document.createElement("option");
1531 orphan.value = selected;
1532 orphan.textContent = `${selected} (missing)`;
1533 orphan.selected = true;
1534 select.append(orphan);
1535 }
1536 return select;
1537}