BlueGit

timfa questward

Files

questward / client / src / editor / tileConfigModal.js

tileConfigModal.js

feat: branch quest steps and remember which steps were finished
timfa project_85689633_bot_760517ee9267c86ff1d6c3a0237abf7d · pushed by timfa · 4 weeks ago
25915c58 History
tileConfigModal.js 56.7 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 quests: typeof getQuests === "function" ? (getQuests() ?? []) : []
1247 });
1248 title.textContent = `Item Spawner · ${ctx.tileX}, ${ctx.tileY}`;
1249 if (socket && MessageType)
1250 {
1251 socket.send({ type: MessageType.editorLoadQuests });
1252 socket.send({ type: MessageType.editorLoadDialogues });
1253 }
1254 form.innerHTML = "";
1255
1256 const itemsHeader = document.createElement("div");
1257 itemsHeader.className = "spawner-sells-header";
1258 const itemsLabel = document.createElement("strong");
1259 itemsLabel.textContent = "Items";
1260 const addBtn = document.createElement("button");
1261 addBtn.type = "button";
1262 addBtn.textContent = "+";
1263 addBtn.title = "Add item";
1264 addBtn.addEventListener("click", () => openItemSpawnerItemsSearch());
1265 itemsHeader.append(itemsLabel, addBtn);
1266 const itemsList = document.createElement("div");
1267 itemsList.setAttribute("data-item-spawner-items", "");
1268 form.append(itemsHeader, itemsList);
1269
1270 form.append(
1271 field("Respawn time (seconds)", numberInput("respawnDelaySeconds", config.respawnDelaySeconds ?? 25, 0, 86_400)),
1272 field("Range", numberInput("spawnRangeTiles", config.spawnRangeTiles ?? 0, 0, 32)),
1273 field("Spawner id", textInput("spawnerId", config.spawnerId, true))
1274 );
1275
1276 const appearanceSelect = document.createElement("select");
1277 appearanceSelect.name = "appearance";
1278 const appearanceLabels = {
1279 [ItemSpawnerAppearance.item]: "Item",
1280 [ItemSpawnerAppearance.chest]: "Chest",
1281 [ItemSpawnerAppearance.barrel]: "Barrel",
1282 [ItemSpawnerAppearance.crate]: "Crate"
1283 };
1284 for (const value of ITEM_SPAWNER_APPEARANCES)
1285 {
1286 const opt = document.createElement("option");
1287 opt.value = value;
1288 opt.textContent = appearanceLabels[value] ?? value;
1289 if (value === config.appearance)
1290 { opt.selected = true; }
1291 appearanceSelect.append(opt);
1292 }
1293 appearanceSelect.addEventListener("change", () => syncItemSpawnerAppearanceGates());
1294 form.append(field("Appearance", appearanceSelect));
1295
1296 const materialWrap = document.createElement("div");
1297 materialWrap.setAttribute("data-item-spawner-material", "");
1298 const materialSelect = document.createElement("select");
1299 materialSelect.name = "material";
1300 for (const row of listItemSpawnerMaterials())
1301 {
1302 const opt = document.createElement("option");
1303 opt.value = row.id;
1304 opt.textContent = row.displayName;
1305 if (row.id === config.material)
1306 { opt.selected = true; }
1307 materialSelect.append(opt);
1308 }
1309 materialWrap.append(field("Material", materialSelect));
1310 form.append(materialWrap);
1311
1312 const conditionHost = document.createElement("div");
1313 conditionHost.setAttribute("data-item-spawner-condition", "");
1314 conditionHost.className = "door-requirements-when";
1315 const condHint = document.createElement("p");
1316 condHint.className = "tile-config-hint";
1317 condHint.textContent = `Condition gates opening. Fail toast: "${ITEM_SPAWNER_LOCKED_MESSAGE}"`;
1318 conditionHost.append(condHint);
1319 const whenHost = document.createElement("div");
1320 conditionHost.append(whenHost);
1321 form.append(conditionHost);
1322 const remountWhen = () =>
1323 {
1324 whenHost.replaceChildren(renderConditionSet(itemSpawnerWhenDraft, (next, { remount = true } = {}) =>
1325 {
1326 itemSpawnerWhenDraft = normalizeConditionSet(next);
1327 if (remount)
1328 { remountWhen(); }
1329 }, {
1330 quests: typeof getQuests === "function" ? (getQuests() ?? []) : [],
1331 dialogues: typeof getDialogues === "function" ? (getDialogues() ?? []) : [],
1332 describeWorldTile,
1333 centerEditorOnTile,
1334 getDimensionOptions
1335 }));
1336 };
1337 remountWhen();
1338
1339 renderItemSpawnerItemsList();
1340 syncItemSpawnerAppearanceGates();
1341 show(true);
1342 }
1343
1344 function openFishingSpot (ctx)
1345 {
1346 context = { kind: "fishing-spot", ...ctx };
1347 const normalized = normalizeFishingSpotConfig(ctx.config);
1348 fishesDraft = [...normalized.fishes];
1349 title.textContent = `Fishing spot · ${ctx.tileX}, ${ctx.tileY}`;
1350 form.innerHTML = "";
1351 const header = document.createElement("div");
1352 header.className = "spawner-sells-header";
1353 const label = document.createElement("strong");
1354 label.textContent = "Fishes";
1355 const addBtn = document.createElement("button");
1356 addBtn.type = "button";
1357 addBtn.textContent = "+";
1358 addBtn.title = "Add fish";
1359 addBtn.addEventListener("click", () => openFishItemSearch());
1360 header.append(label, addBtn);
1361 const list = document.createElement("div");
1362 list.setAttribute("data-fishes-list", "");
1363 form.append(header, list);
1364 renderFishesList();
1365 show(true);
1366 }
1367
1368 function openDoorway (ctx)
1369 {
1370 context = { kind: "doorway", ...ctx };
1371 const config = ctx.config && typeof ctx.config === "object" ? ctx.config : {};
1372 const state = DOORWAY_STATES.includes(ctx.state) ? ctx.state : "door";
1373 title.textContent = `Doorway · ${ctx.tileX}, ${ctx.tileY}`;
1374 form.innerHTML = "";
1375 form.append(
1376 field("Appearance", doorwayStateSelect("state", state)),
1377 field("Target tile X", numberInput("tileX", Number.isFinite(Number(config.tileX)) ? Number(config.tileX) : 0, -1_000_000, 1_000_000)),
1378 field("Target tile Y", numberInput("tileY", Number.isFinite(Number(config.tileY)) ? Number(config.tileY) : 0, -1_000_000, 1_000_000))
1379 );
1380 const dimWrap = document.createElement("label");
1381 dimWrap.append(document.createTextNode("Target dimension"));
1382 const dimRoot = document.createElement("div");
1383 dimRoot.className = "doorway-dim-combo";
1384 dimWrap.append(dimRoot);
1385 form.append(dimWrap);
1386 const options = typeof getDimensionOptions === "function" ? (getDimensionOptions() ?? []) : [];
1387 doorwayDimCombo = createDimensionCombobox({
1388 root: dimRoot,
1389 placeholder: "Target dimension…",
1390 onSelect () { }
1391 });
1392 doorwayDimCombo.setOptions(options);
1393 doorwayDimCombo.setValue(normalizeDimensionId(config.targetDimensionId ?? OVERWORLD_ID));
1394 show(true);
1395 }
1396
1397 function renderDoorRequirementsForm ()
1398 {
1399 form.innerHTML = "";
1400 const hint = document.createElement("p");
1401 hint.className = "tile-config-hint";
1402 hint.textContent = "Players who fail these requirements cannot pass this door — even when it is held open.";
1403 form.append(hint);
1404 const whenHost = document.createElement("div");
1405 whenHost.className = "door-requirements-when";
1406 form.append(whenHost);
1407 const remountWhen = () =>
1408 {
1409 whenHost.replaceChildren(renderConditionSet(doorWhenDraft, (next, { remount = true } = {}) =>
1410 {
1411 doorWhenDraft = normalizeConditionSet(next);
1412 if (remount)
1413 { remountWhen(); }
1414 }, {
1415 quests: typeof getQuests === "function" ? (getQuests() ?? []) : [],
1416 dialogues: typeof getDialogues === "function" ? (getDialogues() ?? []) : [],
1417 describeWorldTile,
1418 centerEditorOnTile,
1419 getDimensionOptions
1420 }));
1421 };
1422 remountWhen();
1423 const msgLabel = document.createElement("label");
1424 msgLabel.append(document.createTextNode("Blocked toast"));
1425 const msg = document.createElement("input");
1426 msg.type = "text";
1427 msg.name = "blockedMessage";
1428 msg.maxLength = 200;
1429 msg.placeholder = DEFAULT_DOOR_BLOCKED_MESSAGE;
1430 msg.value = doorBlockedMessageDraft;
1431 msg.addEventListener("input", () =>
1432 {
1433 doorBlockedMessageDraft = msg.value;
1434 });
1435 msgLabel.append(msg);
1436 form.append(msgLabel);
1437 }
1438
1439 function openDoor (ctx)
1440 {
1441 context = { kind: "door", ...ctx };
1442 const config = ctx.config && typeof ctx.config === "object" ? ctx.config : {};
1443 doorWhenDraft = normalizeConditionSet(config.when ?? config.requirements ?? emptyConditionSet(), {
1444 quests: typeof getQuests === "function" ? (getQuests() ?? []) : []
1445 });
1446 doorBlockedMessageDraft = String(config.blockedMessage ?? config.denyMessage ?? "").trim();
1447 title.textContent = `Door · ${ctx.tileX}, ${ctx.tileY}`;
1448 if (socket && MessageType)
1449 {
1450 socket.send({ type: MessageType.editorLoadQuests });
1451 socket.send({ type: MessageType.editorLoadDialogues });
1452 }
1453 renderDoorRequirementsForm();
1454 show(true);
1455 }
1456
1457 document.getElementById("tile-config-close").addEventListener("click", () => show(false));
1458 document.getElementById("tile-config-cancel").addEventListener("click", () => show(false));
1459 backdrop.addEventListener("click", () => show(false));
1460 document.getElementById("shop-item-search-close")?.addEventListener("click", () => closeItemSearch());
1461 itemSearchBackdrop?.addEventListener("click", () => closeItemSearch());
1462 itemSearchInput?.addEventListener("input", () =>
1463 {
1464 itemSearchPage = 0;
1465 renderItemSearchResults(itemSearchInput.value);
1466 });
1467 itemSearchPrev?.addEventListener("click", () =>
1468 {
1469 if (itemSearchPage <= 0)
1470 { return; }
1471 itemSearchPage -= 1;
1472 renderItemSearchResults(itemSearchInput?.value ?? "");
1473 });
1474 itemSearchNext?.addEventListener("click", () =>
1475 {
1476 const pageCount = Math.max(1, Math.ceil((itemSearchMatches?.length ?? 0) / ITEM_SEARCH_PAGE_SIZE));
1477 if (itemSearchPage >= pageCount - 1)
1478 { return; }
1479 itemSearchPage += 1;
1480 renderItemSearchResults(itemSearchInput?.value ?? "");
1481 });
1482 document.getElementById("equip-dye-close")?.addEventListener("click", () => closeDyePicker());
1483 dyeBackdrop?.addEventListener("click", () => closeDyePicker());
1484 document.getElementById("equip-dye-apply")?.addEventListener("click", () =>
1485 {
1486 if (!dyeEditSlot || !equipmentDraft[dyeEditSlot])
1487 { return; }
1488 equipmentDraft[dyeEditSlot].dyeColor = readDyeSliders();
1489 closeDyePicker();
1490 renderEquipmentRows();
1491 });
1492 document.getElementById("equip-dye-clear")?.addEventListener("click", () =>
1493 {
1494 if (!dyeEditSlot || !equipmentDraft[dyeEditSlot])
1495 { return; }
1496 equipmentDraft[dyeEditSlot].dyeColor = null;
1497 closeDyePicker();
1498 renderEquipmentRows();
1499 });
1500
1501 document.getElementById("tile-config-save").addEventListener("click", () =>
1502 {
1503 if (!context)
1504 { return; }
1505 if (context.kind === "doorway")
1506 {
1507 const data = new FormData(form);
1508 const stateRaw = String(data.get("state") || "door");
1509 onSave?.(context, {
1510 state: DOORWAY_STATES.includes(stateRaw) ? stateRaw : "door",
1511 targetDimensionId: normalizeDimensionId(doorwayDimCombo?.getValue() ?? OVERWORLD_ID),
1512 tileX: Number(data.get("tileX")) || 0,
1513 tileY: Number(data.get("tileY")) || 0
1514 });
1515 show(false);
1516 return;
1517 }
1518 if (context.kind === "door")
1519 {
1520 onSave?.(context, {
1521 when: normalizeConditionSet(doorWhenDraft),
1522 blockedMessage: String(doorBlockedMessageDraft ?? "").trim()
1523 });
1524 show(false);
1525 return;
1526 }
1527 if (context.kind === "item-spawner")
1528 {
1529 const data = new FormData(form);
1530 onSave?.(context, normalizeItemSpawnerConfig({
1531 spawnerId: String(data.get("spawnerId") || context.config.spawnerId),
1532 items: itemSpawnerItemsDraft,
1533 respawnDelaySeconds: Number(data.get("respawnDelaySeconds") ?? 25),
1534 spawnRangeTiles: (() =>
1535 {
1536 const n = Number(data.get("spawnRangeTiles"));
1537 return Number.isFinite(n) ? n : 0;
1538 })(),
1539 appearance: String(data.get("appearance") || ItemSpawnerAppearance.chest),
1540 material: String(data.get("material") || "pine"),
1541 when: normalizeConditionSet(itemSpawnerWhenDraft)
1542 }, context.config.spawnerId));
1543 show(false);
1544 return;
1545 }
1546 if (context.kind === "fishing-spot")
1547 {
1548 onSave?.(context, normalizeFishingSpotConfig({ fishes: fishesDraft }));
1549 show(false);
1550 return;
1551 }
1552 const data = new FormData(form);
1553 const equipment = {};
1554 for (const slot of EQUIPMENT_SLOTS)
1555 { equipment[slot] = equipConfigFromDraft(equipmentDraft[slot]); }
1556 onSave?.(context, normalizeSpawnerConfig({
1557 mobTypeId: String(data.get("mobTypeId") || "deer"),
1558 maxAlive: Number(data.get("maxAlive") || 3),
1559 respawnDelaySeconds: Number(data.get("respawnDelaySeconds") ?? 25),
1560 spawnRangeTiles: (() =>
1561 {
1562 const n = Number(data.get("spawnRangeTiles"));
1563 return Number.isFinite(n) ? n : 4;
1564 })(),
1565 maxWanderRangeTiles: (() =>
1566 {
1567 const n = Number(data.get("maxWanderRangeTiles"));
1568 return Number.isFinite(n) ? n : 4;
1569 })(),
1570 level: Number(data.get("level") || 1),
1571 bounty: Number(data.get("bounty") || 0),
1572 aggressive: data.get("aggressive") === "on",
1573 passive: data.get("aggressive") === "on" ? false : data.get("passive") === "on",
1574 spawnerId: String(data.get("spawnerId") || context.config.spawnerId),
1575 sex: String(data.get("sex") || "male"),
1576 displayName: String(data.get("displayName") || ""),
1577 equipment,
1578 sells: sellsDraft,
1579 drops: dropsDraft.map((line) =>
1580 {
1581 const quantityMin = Math.max(0, Number(line.quantityMin) || 0) | 0;
1582 const quantityMax = Math.max(
1583 quantityMin,
1584 Math.max(0, Number(line.quantityMax) || 0) | 0
1585 );
1586 return {
1587 itemId: line.itemId,
1588 chance: Math.min(100, Math.max(0, Number(line.chancePercent) || 0)) / 100,
1589 quantityMin,
1590 quantityMax
1591 };
1592 }),
1593 spells: spellsDraft,
1594 buysItems: data.get("buysItems") === "on",
1595 hiddenDiscount: Number(data.get("hiddenDiscount") || 0.9),
1596 centralExchange: isCentralExchangeSpawner(String(data.get("mobTypeId") || "")),
1597 dialogueId: String(data.get("dialogueId") || "").trim() || null
1598 }, context.config.spawnerId));
1599 show(false);
1600 });
1601 document.getElementById("tile-config-remove").addEventListener("click", () =>
1602 {
1603 if (!context)
1604 { return; }
1605 if (context.kind === "spawner")
1606 {
1607 const label = context.config?.displayName
1608 || context.config?.mobTypeId
1609 || context.config?.spawnerId
1610 || "this spawner";
1611 if (!window.confirm(`Delete mob spawner "${label}"?`))
1612 { return; }
1613 }
1614 if (context.kind === "item-spawner")
1615 {
1616 const label = context.config?.spawnerId || "this item spawner";
1617 if (!window.confirm(`Delete item spawner "${label}"?`))
1618 { return; }
1619 }
1620 onRemove?.(context);
1621 show(false);
1622 });
1623
1624 return {
1625 isOpen: () => open,
1626 openSpawner,
1627 openItemSpawner,
1628 openDoorway,
1629 openDoor,
1630 openFishingSpot,
1631 close: () => show(false),
1632 handleMessage (message)
1633 {
1634 if (!MessageType)
1635 { return; }
1636 if (message.type === MessageType.editorDialogues)
1637 {
1638 dialogueOptions = (message.dialogues ?? []).map((d) => ({
1639 dialogueId: String(d.dialogueId ?? ""),
1640 label: String(d.label ?? d.dialogueId ?? ""),
1641 unique: !!d.unique
1642 })).filter((d) => d.dialogueId);
1643 const select = form.querySelector('[name="dialogueId"]');
1644 if (select && open)
1645 {
1646 const current = select.value || pendingDialogueId || "";
1647 select.replaceWith(dialogueSelect("dialogueId", current, dialogueOptions));
1648 }
1649 if (open && context?.kind === "door")
1650 { renderDoorRequirementsForm(); }
1651 return;
1652 }
1653 if (message.type === MessageType.editorQuests && open && context?.kind === "door")
1654 { renderDoorRequirementsForm(); }
1655 }
1656 };
1657}
1658
1659function doorwayStateSelect (name, value)
1660{
1661 const select = document.createElement("select");
1662 select.name = name;
1663 for (const state of DOORWAY_STATES)
1664 {
1665 const opt = document.createElement("option");
1666 opt.value = state;
1667 opt.textContent = state.charAt(0).toUpperCase() + state.slice(1);
1668 if (state === value)
1669 { opt.selected = true; }
1670 select.append(opt);
1671 }
1672 return select;
1673}
1674
1675function field (label, input)
1676{
1677 const wrap = document.createElement("label");
1678 wrap.append(document.createTextNode(label), input);
1679 return wrap;
1680}
1681
1682function numberInput (name, value, min, max, step = 1)
1683{
1684 const input = document.createElement("input");
1685 input.type = "number";
1686 input.name = name;
1687 input.min = String(min);
1688 input.max = String(max);
1689 input.step = String(step);
1690 input.value = String(value);
1691 return input;
1692}
1693
1694function textInput (name, value, readOnly = false)
1695{
1696 const input = document.createElement("input");
1697 input.type = "text";
1698 input.name = name;
1699 input.value = String(value ?? "");
1700 input.readOnly = readOnly;
1701 return input;
1702}
1703
1704function sexSelect (name, value)
1705{
1706 const select = document.createElement("select");
1707 select.name = name;
1708 for (const sex of ["male", "female"])
1709 {
1710 const option = document.createElement("option");
1711 option.value = sex;
1712 option.textContent = sex;
1713 if (sex === value)
1714 { option.selected = true; }
1715 select.append(option);
1716 }
1717 return select;
1718}
1719
1720function mobSelect (name, value)
1721{
1722 const select = document.createElement("select");
1723 select.name = name;
1724 for (const def of listSpawnableMobTypes())
1725 {
1726 const option = document.createElement("option");
1727 option.value = def.mobTypeId;
1728 option.textContent = def.displayName;
1729 if (def.mobTypeId === value)
1730 { option.selected = true; }
1731 select.append(option);
1732 }
1733 return select;
1734}
1735
1736function dialogueSelect (name, value, options = [])
1737{
1738 const select = document.createElement("select");
1739 select.name = name;
1740 const none = document.createElement("option");
1741 none.value = "";
1742 none.textContent = "(none)";
1743 select.append(none);
1744 const selected = String(value ?? "");
1745 let found = !selected;
1746 for (const entry of options)
1747 {
1748 const option = document.createElement("option");
1749 option.value = entry.dialogueId;
1750 option.textContent = entry.unique
1751 ? `${entry.label} [${entry.dialogueId}] · unique`
1752 : `${entry.label} [${entry.dialogueId}]`;
1753 if (entry.dialogueId === selected)
1754 {
1755 option.selected = true;
1756 found = true;
1757 }
1758 select.append(option);
1759 }
1760 if (selected && !found)
1761 {
1762 const orphan = document.createElement("option");
1763 orphan.value = selected;
1764 orphan.textContent = `${selected} (missing)`;
1765 orphan.selected = true;
1766 select.append(orphan);
1767 }
1768 return select;
1769}