BlueGit

timfa questward

Files

questward / client / src / editor / tileConfigModal.js

tileConfigModal.js

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