BlueGit

timfa questward

Files

questward / client / src / editor / tileConfigModal.js

tileConfigModal.js

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