BlueGit

timfa questward

Files

questward / client / src / editor / tileConfigModal.js

tileConfigModal.js

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