BlueGit

timfa questward

Files

questward / client / src / editor / tileConfigModal.js

tileConfigModal.js

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