BlueGit

timfa questward

Files

questward / client / src / editor / tileConfigModal.js

tileConfigModal.js

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