BlueGit

timfa questward

Files

questward / client / src / editor / tileConfigModal.js

tileConfigModal.js

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