BlueGit

timfa questward

Files

questward / client / src / editor / tileConfigModal.js

tileConfigModal.js

editor fixes, spawner additions
timfa Tim Falken · pushed by timfa · 2 months ago
87524d95 History
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 !spellsDraft.some((line) => line.spellId === def.spellId));
824 if (!available)
825 { return; }
826 spellsDraft.push({ spellId: available.spellId });
827 renderSpellsList();
828 });
829 header.append(titleEl, addBtn);
830 wrap.append(header);
831
832 const list = document.createElement("div");
833 list.className = "spawner-sells-list";
834 list.dataset.spellsList = "1";
835 wrap.append(list);
836
837 const hint = document.createElement("p");
838 hint.className = "hint";
839 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.";
840 wrap.append(hint);
841
842 if (!Array.isArray(spellsDraft) || !spellsDraft.length)
843 {
844 spellsDraft = (config?.spells ?? []).map((line) => ({
845 spellId: String(line.spellId ?? "")
846 })).filter((line) => line.spellId);
847 }
848 queueMicrotask(() => renderSpellsList());
849 return wrap;
850 }
851
852 function renderSpellsList ()
853 {
854 const list = form.querySelector("[data-spells-list]");
855 if (!list)
856 { return; }
857 list.replaceChildren();
858 if (!spellsDraft.length)
859 {
860 const empty = document.createElement("p");
861 empty.className = "hint";
862 empty.textContent = "No spells.";
863 list.append(empty);
864 return;
865 }
866 const level = Math.max(1, Number(form.querySelector('[name="level"]')?.value) || 1) | 0;
867 const castChance = mobSpellCastChancePercent(level);
868 for (let index = 0; index < spellsDraft.length; index++)
869 {
870 const line = spellsDraft[index];
871 const def = SPELL_DEFINITIONS[line.spellId];
872 const row = document.createElement("div");
873 row.className = "spawner-sell-row";
874
875 const select = document.createElement("select");
876 for (const spell of Object.values(SPELL_DEFINITIONS))
877 {
878 const opt = document.createElement("option");
879 opt.value = spell.spellId;
880 const minLv = spell.minMagicLevel | 0 || 1;
881 opt.textContent = `${spell.displayName} (Magic ${minLv}+)`;
882 if (spell.spellId === line.spellId)
883 { opt.selected = true; }
884 select.append(opt);
885 }
886 select.addEventListener("change", () =>
887 {
888 spellsDraft[index].spellId = select.value;
889 renderSpellsList();
890 });
891
892 const minLv = def?.minMagicLevel | 0 || 1;
893 const chanceLabel = document.createElement("span");
894 chanceLabel.className = "hint";
895 chanceLabel.title = "Cast chance from mob Level";
896 chanceLabel.textContent = level < minLv
897 ? `needs Lv.${minLv}`
898 : `cast ${castChance}%`;
899
900 const remove = document.createElement("button");
901 remove.type = "button";
902 remove.textContent = "×";
903 remove.addEventListener("click", () =>
904 {
905 spellsDraft.splice(index, 1);
906 renderSpellsList();
907 });
908
909 row.append(select, chanceLabel, remove);
910 list.append(row);
911 }
912 }
913
914 function syncBountyForAggressive ()
915 {
916 const bountyInput = form.querySelector('[name="bounty"]');
917 const aggressiveInput = form.querySelector('[name="aggressive"]');
918 if (!bountyInput)
919 { return; }
920 const aggressive = !!aggressiveInput?.checked;
921 if (aggressive)
922 {
923 bountyInput.value = "0";
924 bountyInput.disabled = true;
925 }
926 else
927 { bountyInput.disabled = false; }
928 }
929
930 function openSpawner (ctx)
931 {
932 context = { kind: "spawner", ...ctx };
933 const config = normalizeSpawnerConfig(ctx.config, ctx.config.spawnerId);
934 pendingDialogueId = config.dialogueId ?? null;
935 dialogueOptions = typeof getDialogues === "function" ? (getDialogues() ?? []) : dialogueOptions;
936 if (socket && MessageType)
937 { socket.send({ type: MessageType.editorLoadDialogues }); }
938 title.textContent = `Spawner · ${ctx.tileX}, ${ctx.tileY}`;
939 form.innerHTML = "";
940 const mobField = field("Mob type", mobSelect("mobTypeId", config.mobTypeId));
941 form.append(
942 mobField,
943 field("Level", numberInput("level", config.level ?? 1, 1, 99)),
944 field("Bounty", numberInput("bounty", config.bounty ?? 0, 0, 1_000_000)),
945 field("Max alive", numberInput("maxAlive", config.maxAlive, 1, 20)),
946 field("Respawn delay (seconds)", numberInput("respawnDelaySeconds", config.respawnDelaySeconds ?? 0, 0, 86_400)),
947 field("Spawn range", numberInput("spawnRangeTiles", config.spawnRangeTiles, 1, 32)),
948 field("Max wander range", numberInput("maxWanderRangeTiles", config.maxWanderRangeTiles, 1, 64)),
949 field("Spawner id", textInput("spawnerId", config.spawnerId, true))
950 );
951 const spawnInput = form.querySelector('[name="spawnRangeTiles"]');
952 const wanderInput = form.querySelector('[name="maxWanderRangeTiles"]');
953 const syncWanderMin = () =>
954 {
955 const spawn = Number(spawnInput.value) || 1;
956 wanderInput.min = String(spawn);
957 if (Number(wanderInput.value) < spawn)
958 { wanderInput.value = String(spawn); }
959 };
960 spawnInput.addEventListener("input", syncWanderMin);
961 syncWanderMin();
962 form.querySelector('[name="level"]')?.addEventListener("input", () => renderSpellsList());
963 form.querySelector('[name="mobTypeId"]').addEventListener("change", () =>
964 {
965 const nextType = form.querySelector('[name="mobTypeId"]').value;
966 const defaults = normalizeSpawnerConfig({ mobTypeId: nextType }, config.spawnerId);
967 form.querySelector('[name="maxAlive"]').value = String(defaults.maxAlive);
968 form.querySelector('[name="spawnRangeTiles"]').value = String(defaults.spawnRangeTiles);
969 form.querySelector('[name="maxWanderRangeTiles"]').value = String(defaults.maxWanderRangeTiles);
970 form.querySelector('[name="level"]').value = String(defaults.level ?? 1);
971 form.querySelector('[name="bounty"]').value = String(defaults.bounty ?? 0);
972 syncWanderMin();
973 syncHumanoidSection(defaults);
974 syncSpellsSection(defaults);
975 syncBountyForAggressive();
976 });
977 spellsDraft = (config.spells ?? []).map((line) => ({
978 spellId: String(line.spellId ?? "")
979 })).filter((line) => line.spellId);
980 syncHumanoidSection(config);
981 syncSpellsSection(config);
982 syncBountyForAggressive();
983 show(true);
984 }
985
986 function openFishingSpot (ctx)
987 {
988 context = { kind: "fishing-spot", ...ctx };
989 const normalized = normalizeFishingSpotConfig(ctx.config);
990 fishesDraft = [...normalized.fishes];
991 title.textContent = `Fishing spot · ${ctx.tileX}, ${ctx.tileY}`;
992 form.innerHTML = "";
993 const header = document.createElement("div");
994 header.className = "spawner-sells-header";
995 const label = document.createElement("strong");
996 label.textContent = "Fishes";
997 const addBtn = document.createElement("button");
998 addBtn.type = "button";
999 addBtn.textContent = "+";
1000 addBtn.title = "Add fish";
1001 addBtn.addEventListener("click", () => openFishItemSearch());
1002 header.append(label, addBtn);
1003 const list = document.createElement("div");
1004 list.setAttribute("data-fishes-list", "");
1005 form.append(header, list);
1006 renderFishesList();
1007 show(true);
1008 }
1009
1010 function openDoorway (ctx)
1011 {
1012 context = { kind: "doorway", ...ctx };
1013 const config = ctx.config && typeof ctx.config === "object" ? ctx.config : {};
1014 const state = DOORWAY_STATES.includes(ctx.state) ? ctx.state : "door";
1015 title.textContent = `Doorway · ${ctx.tileX}, ${ctx.tileY}`;
1016 form.innerHTML = "";
1017 form.append(
1018 field("Appearance", doorwayStateSelect("state", state)),
1019 field("Target tile X", numberInput("tileX", Number.isFinite(Number(config.tileX)) ? Number(config.tileX) : 0, -1_000_000, 1_000_000)),
1020 field("Target tile Y", numberInput("tileY", Number.isFinite(Number(config.tileY)) ? Number(config.tileY) : 0, -1_000_000, 1_000_000))
1021 );
1022 const dimWrap = document.createElement("label");
1023 dimWrap.append(document.createTextNode("Target dimension"));
1024 const dimRoot = document.createElement("div");
1025 dimRoot.className = "doorway-dim-combo";
1026 dimWrap.append(dimRoot);
1027 form.append(dimWrap);
1028 const options = typeof getDimensionOptions === "function" ? (getDimensionOptions() ?? []) : [];
1029 doorwayDimCombo = createDimensionCombobox({
1030 root: dimRoot,
1031 placeholder: "Target dimension…",
1032 onSelect () { }
1033 });
1034 doorwayDimCombo.setOptions(options);
1035 doorwayDimCombo.setValue(normalizeDimensionId(config.targetDimensionId ?? OVERWORLD_ID));
1036 show(true);
1037 }
1038
1039 document.getElementById("tile-config-close").addEventListener("click", () => show(false));
1040 document.getElementById("tile-config-cancel").addEventListener("click", () => show(false));
1041 backdrop.addEventListener("click", () => show(false));
1042 document.getElementById("shop-item-search-close")?.addEventListener("click", () => closeItemSearch());
1043 itemSearchBackdrop?.addEventListener("click", () => closeItemSearch());
1044 itemSearchInput?.addEventListener("input", () =>
1045 {
1046 itemSearchPage = 0;
1047 renderItemSearchResults(itemSearchInput.value);
1048 });
1049 itemSearchPrev?.addEventListener("click", () =>
1050 {
1051 if (itemSearchPage <= 0)
1052 { return; }
1053 itemSearchPage -= 1;
1054 renderItemSearchResults(itemSearchInput?.value ?? "");
1055 });
1056 itemSearchNext?.addEventListener("click", () =>
1057 {
1058 const pageCount = Math.max(1, Math.ceil((itemSearchMatches?.length ?? 0) / ITEM_SEARCH_PAGE_SIZE));
1059 if (itemSearchPage >= pageCount - 1)
1060 { return; }
1061 itemSearchPage += 1;
1062 renderItemSearchResults(itemSearchInput?.value ?? "");
1063 });
1064 document.getElementById("equip-dye-close")?.addEventListener("click", () => closeDyePicker());
1065 dyeBackdrop?.addEventListener("click", () => closeDyePicker());
1066 document.getElementById("equip-dye-apply")?.addEventListener("click", () =>
1067 {
1068 if (!dyeEditSlot || !equipmentDraft[dyeEditSlot])
1069 { return; }
1070 equipmentDraft[dyeEditSlot].dyeColor = readDyeSliders();
1071 closeDyePicker();
1072 renderEquipmentRows();
1073 });
1074 document.getElementById("equip-dye-clear")?.addEventListener("click", () =>
1075 {
1076 if (!dyeEditSlot || !equipmentDraft[dyeEditSlot])
1077 { return; }
1078 equipmentDraft[dyeEditSlot].dyeColor = null;
1079 closeDyePicker();
1080 renderEquipmentRows();
1081 });
1082
1083 document.getElementById("tile-config-save").addEventListener("click", () =>
1084 {
1085 if (!context)
1086 { return; }
1087 if (context.kind === "doorway")
1088 {
1089 const data = new FormData(form);
1090 const stateRaw = String(data.get("state") || "door");
1091 onSave?.(context, {
1092 state: DOORWAY_STATES.includes(stateRaw) ? stateRaw : "door",
1093 targetDimensionId: normalizeDimensionId(doorwayDimCombo?.getValue() ?? OVERWORLD_ID),
1094 tileX: Number(data.get("tileX")) || 0,
1095 tileY: Number(data.get("tileY")) || 0
1096 });
1097 show(false);
1098 return;
1099 }
1100 if (context.kind === "fishing-spot")
1101 {
1102 onSave?.(context, normalizeFishingSpotConfig({ fishes: fishesDraft }));
1103 show(false);
1104 return;
1105 }
1106 const data = new FormData(form);
1107 const equipment = {};
1108 for (const slot of EQUIPMENT_SLOTS)
1109 { equipment[slot] = equipConfigFromDraft(equipmentDraft[slot]); }
1110 onSave?.(context, normalizeSpawnerConfig({
1111 mobTypeId: String(data.get("mobTypeId") || "deer"),
1112 maxAlive: Number(data.get("maxAlive") || 3),
1113 respawnDelaySeconds: Number(data.get("respawnDelaySeconds") || 0),
1114 spawnRangeTiles: Number(data.get("spawnRangeTiles") || 4),
1115 maxWanderRangeTiles: Number(data.get("maxWanderRangeTiles") || 4),
1116 level: Number(data.get("level") || 1),
1117 bounty: Number(data.get("bounty") || 0),
1118 aggressive: data.get("aggressive") === "on",
1119 spawnerId: String(data.get("spawnerId") || context.config.spawnerId),
1120 sex: String(data.get("sex") || "male"),
1121 displayName: String(data.get("displayName") || ""),
1122 equipment,
1123 sells: sellsDraft,
1124 drops: dropsDraft.map((line) =>
1125 {
1126 const quantityMin = Math.max(0, Number(line.quantityMin) || 0) | 0;
1127 const quantityMax = Math.max(
1128 quantityMin,
1129 Math.max(0, Number(line.quantityMax) || 0) | 0
1130 );
1131 return {
1132 itemId: line.itemId,
1133 chance: Math.min(100, Math.max(0, Number(line.chancePercent) || 0)) / 100,
1134 quantityMin,
1135 quantityMax
1136 };
1137 }),
1138 spells: spellsDraft,
1139 buysItems: data.get("buysItems") === "on",
1140 hiddenDiscount: Number(data.get("hiddenDiscount") || 0.9),
1141 centralExchange: isCentralExchangeSpawner(String(data.get("mobTypeId") || "")),
1142 dialogueId: String(data.get("dialogueId") || "").trim() || null
1143 }, context.config.spawnerId));
1144 show(false);
1145 });
1146 document.getElementById("tile-config-remove").addEventListener("click", () =>
1147 {
1148 if (!context)
1149 { return; }
1150 onRemove?.(context);
1151 show(false);
1152 });
1153
1154 return {
1155 isOpen: () => open,
1156 openSpawner,
1157 openDoorway,
1158 openFishingSpot,
1159 close: () => show(false),
1160 handleMessage (message)
1161 {
1162 if (!MessageType || message.type !== MessageType.editorDialogues)
1163 { return; }
1164 dialogueOptions = (message.dialogues ?? []).map((d) => ({
1165 dialogueId: String(d.dialogueId ?? ""),
1166 label: String(d.label ?? d.dialogueId ?? ""),
1167 unique: !!d.unique
1168 })).filter((d) => d.dialogueId);
1169 const select = form.querySelector('[name="dialogueId"]');
1170 if (select && open)
1171 {
1172 const current = select.value || pendingDialogueId || "";
1173 select.replaceWith(dialogueSelect("dialogueId", current, dialogueOptions));
1174 }
1175 }
1176 };
1177}
1178
1179function doorwayStateSelect (name, value)
1180{
1181 const select = document.createElement("select");
1182 select.name = name;
1183 for (const state of DOORWAY_STATES)
1184 {
1185 const opt = document.createElement("option");
1186 opt.value = state;
1187 opt.textContent = state.charAt(0).toUpperCase() + state.slice(1);
1188 if (state === value)
1189 { opt.selected = true; }
1190 select.append(opt);
1191 }
1192 return select;
1193}
1194
1195function field (label, input)
1196{
1197 const wrap = document.createElement("label");
1198 wrap.append(document.createTextNode(label), input);
1199 return wrap;
1200}
1201
1202function numberInput (name, value, min, max, step = 1)
1203{
1204 const input = document.createElement("input");
1205 input.type = "number";
1206 input.name = name;
1207 input.min = String(min);
1208 input.max = String(max);
1209 input.step = String(step);
1210 input.value = String(value);
1211 return input;
1212}
1213
1214function textInput (name, value, readOnly = false)
1215{
1216 const input = document.createElement("input");
1217 input.type = "text";
1218 input.name = name;
1219 input.value = String(value ?? "");
1220 input.readOnly = readOnly;
1221 return input;
1222}
1223
1224function sexSelect (name, value)
1225{
1226 const select = document.createElement("select");
1227 select.name = name;
1228 for (const sex of ["male", "female"])
1229 {
1230 const option = document.createElement("option");
1231 option.value = sex;
1232 option.textContent = sex;
1233 if (sex === value)
1234 { option.selected = true; }
1235 select.append(option);
1236 }
1237 return select;
1238}
1239
1240function mobSelect (name, value)
1241{
1242 const select = document.createElement("select");
1243 select.name = name;
1244 for (const def of listSpawnableMobTypes())
1245 {
1246 const option = document.createElement("option");
1247 option.value = def.mobTypeId;
1248 option.textContent = def.displayName;
1249 if (def.mobTypeId === value)
1250 { option.selected = true; }
1251 select.append(option);
1252 }
1253 return select;
1254}
1255
1256function dialogueSelect (name, value, options = [])
1257{
1258 const select = document.createElement("select");
1259 select.name = name;
1260 const none = document.createElement("option");
1261 none.value = "";
1262 none.textContent = "(none)";
1263 select.append(none);
1264 const selected = String(value ?? "");
1265 let found = !selected;
1266 for (const entry of options)
1267 {
1268 const option = document.createElement("option");
1269 option.value = entry.dialogueId;
1270 option.textContent = entry.unique
1271 ? `${entry.label} [${entry.dialogueId}] · unique`
1272 : `${entry.label} [${entry.dialogueId}]`;
1273 if (entry.dialogueId === selected)
1274 {
1275 option.selected = true;
1276 found = true;
1277 }
1278 select.append(option);
1279 }
1280 if (selected && !found)
1281 {
1282 const orphan = document.createElement("option");
1283 orphan.value = selected;
1284 orphan.textContent = `${selected} (missing)`;
1285 orphan.selected = true;
1286 select.append(orphan);
1287 }
1288 return select;
1289}