BlueGit

timfa questward

Files

questward / client / src / editor / tileConfigModal.js

tileConfigModal.js

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