BlueGit

timfa questward

Files

questward / client / src / editor / tileConfigModal.js

tileConfigModal.js

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