BlueGit

timfa questward

Files

questward / client / src / editor / tileConfigModal.js

tileConfigModal.js

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