BlueGit

timfa questward

Files

questward / client / src / editor / tileConfigModal.js

tileConfigModal.js

tileConfigModal.js 20.2 KiB Download Raw
1/**
2 * Right-click config modal for editor tiles that have configurable data (spawners).
3 */
4import {
5 listSpawnableMobTypes,
6 normalizeSpawnerConfig,
7 MobId,
8 isHumanoidMob,
9 isCentralExchangeSpawner,
10 spawnerEquipmentSlot
11} from "/shared/definitions/mobs.js";
12import { centralExchangeStaffCount } from "/shared/market/exchange.js";
13import { ITEM_DEFINITIONS, itemDefinition, isDyeableClothing } from "/shared/definitions/items.js";
14import { EQUIPMENT_SLOTS } from "/shared/items/inventory.js";
15import { listNpcShopSellableItems } from "/shared/shop/pricing.js";
16import { normalizeRgb } from "/shared/render/tint.js";
17
18/** Items that can be worn in a given equipment slot. */
19export function listEquippableItemsForSlot (slot)
20{
21 const out = [];
22 for (const def of Object.values(ITEM_DEFINITIONS))
23 {
24 if (!def?.equipment || def.equipment.slot !== slot)
25 { continue; }
26 out.push({
27 itemId: def.itemId,
28 key: def.key ?? String(def.itemId),
29 displayName: def.displayName ?? `Item ${def.itemId}`
30 });
31 }
32 out.sort((a, b) => a.displayName.localeCompare(b.displayName));
33 return out;
34}
35
36function emptyEquipDraft ()
37{
38 return { itemId: null, dyeColor: null };
39}
40
41function equipDraftFromConfig (raw)
42{
43 const { itemId, dyeColor } = spawnerEquipmentSlot(raw);
44 return {
45 itemId: itemId > 0 ? itemId : null,
46 dyeColor: dyeColor ? normalizeRgb(dyeColor) : null
47 };
48}
49
50function equipConfigFromDraft (draft)
51{
52 const itemId = draft?.itemId;
53 if (itemId == null || itemId === "")
54 { return null; }
55 const id = Number(itemId) || null;
56 if (!id)
57 { return null; }
58 if (draft.dyeColor && isDyeableClothing(id))
59 { return { itemId: id, dyeColor: normalizeRgb(draft.dyeColor) }; }
60 return id;
61}
62
63function rgbToCss (color)
64{
65 const c = normalizeRgb(color, { r: 0.78, g: 0.31, b: 0.47 });
66 return `rgb(${Math.round(c.r * 255)}, ${Math.round(c.g * 255)}, ${Math.round(c.b * 255)})`;
67}
68
69export function initTileConfigModal ({ onSave, onRemove })
70{
71 const backdrop = document.getElementById("tile-config-backdrop");
72 const modal = document.getElementById("tile-config-modal");
73 const form = document.getElementById("tile-config-form");
74 const title = document.getElementById("tile-config-title");
75 const itemSearchBackdrop = document.getElementById("shop-item-search-backdrop");
76 const itemSearchModal = document.getElementById("shop-item-search-modal");
77 const itemSearchTitle = itemSearchModal?.querySelector("h2") ?? null;
78 const itemSearchInput = document.getElementById("shop-item-search-input");
79 const itemSearchResults = document.getElementById("shop-item-search-results");
80 const dyeBackdrop = document.getElementById("equip-dye-backdrop");
81 const dyeModal = document.getElementById("equip-dye-modal");
82 const dyeTitle = document.getElementById("equip-dye-title");
83 const dyePreview = document.getElementById("equip-dye-preview");
84 const dyeR = document.getElementById("equip-dye-r");
85 const dyeG = document.getElementById("equip-dye-g");
86 const dyeB = document.getElementById("equip-dye-b");
87 const dyeRNum = document.getElementById("equip-dye-r-num");
88 const dyeGNum = document.getElementById("equip-dye-g-num");
89 const dyeBNum = document.getElementById("equip-dye-b-num");
90 let open = false;
91 let context = null;
92 /** @type {{ itemId: number, quantity: number }[]} */
93 let sellsDraft = [];
94 /** @type {Record<string, { itemId: number|null, dyeColor: {r:number,g:number,b:number}|null }>} */
95 let equipmentDraft = {};
96 /** @type {{ kind: "sells" } | { kind: "equip", slot: string } | null} */
97 let itemSearchMode = null;
98 /** @type {string|null} */
99 let dyeEditSlot = null;
100
101 function show (visible)
102 {
103 open = visible;
104 backdrop.hidden = !visible;
105 modal.hidden = !visible;
106 if (!visible)
107 {
108 context = null;
109 closeItemSearch();
110 closeDyePicker();
111 }
112 }
113
114 function closeItemSearch ()
115 {
116 itemSearchMode = null;
117 if (itemSearchBackdrop)
118 { itemSearchBackdrop.hidden = true; }
119 if (itemSearchModal)
120 { itemSearchModal.hidden = true; }
121 }
122
123 function openSellItemSearch ()
124 {
125 itemSearchMode = { kind: "sells" };
126 openItemSearch("Add shop stock");
127 }
128
129 function openEquipItemSearch (slot)
130 {
131 itemSearchMode = { kind: "equip", slot };
132 openItemSearch(`Equip ${slot}`);
133 }
134
135 function openItemSearch (heading)
136 {
137 if (!itemSearchBackdrop || !itemSearchModal || !itemSearchInput)
138 { return; }
139 if (itemSearchTitle)
140 { itemSearchTitle.textContent = heading ?? "Choose item"; }
141 itemSearchInput.value = "";
142 itemSearchInput.placeholder = itemSearchMode?.kind === "equip"
143 ? "Search equipment…"
144 : "Search items…";
145 renderItemSearchResults("");
146 itemSearchBackdrop.hidden = false;
147 itemSearchModal.hidden = false;
148 itemSearchInput.focus();
149 }
150
151 function candidateItems ()
152 {
153 if (itemSearchMode?.kind === "equip")
154 { return listEquippableItemsForSlot(itemSearchMode.slot); }
155 return listNpcShopSellableItems();
156 }
157
158 function renderItemSearchResults (query)
159 {
160 if (!itemSearchResults)
161 { return; }
162 itemSearchResults.innerHTML = "";
163 const q = String(query ?? "").trim().toLowerCase();
164 const taken = itemSearchMode?.kind === "sells"
165 ? new Set(sellsDraft.map((line) => line.itemId))
166 : null;
167 const matches = candidateItems().filter((item) =>
168 {
169 if (taken?.has(item.itemId))
170 { return false; }
171 if (!q)
172 { return true; }
173 return item.displayName.toLowerCase().includes(q) || item.key.toLowerCase().includes(q);
174 }).slice(0, 120);
175 if (!matches.length)
176 {
177 itemSearchResults.textContent = "No matching items.";
178 return;
179 }
180 for (const item of matches)
181 {
182 const row = document.createElement("button");
183 row.type = "button";
184 row.className = "shop-item-search-row";
185 row.textContent = item.displayName;
186 row.addEventListener("click", () =>
187 {
188 if (itemSearchMode?.kind === "equip")
189 {
190 equipmentDraft[itemSearchMode.slot] = {
191 itemId: item.itemId,
192 dyeColor: null
193 };
194 renderEquipmentRows();
195 }
196 else
197 {
198 sellsDraft.push({ itemId: item.itemId, quantity: 0 });
199 renderSellsList();
200 }
201 closeItemSearch();
202 });
203 itemSearchResults.append(row);
204 }
205 }
206
207 function closeDyePicker ()
208 {
209 dyeEditSlot = null;
210 if (dyeBackdrop)
211 { dyeBackdrop.hidden = true; }
212 if (dyeModal)
213 { dyeModal.hidden = true; }
214 }
215
216 function readDyeSliders ()
217 {
218 return {
219 r: Math.min(255, Math.max(0, Number(dyeR?.value) || 0)) / 255,
220 g: Math.min(255, Math.max(0, Number(dyeG?.value) || 0)) / 255,
221 b: Math.min(255, Math.max(0, Number(dyeB?.value) || 0)) / 255
222 };
223 }
224
225 function syncDyePreview ()
226 {
227 const color = readDyeSliders();
228 if (dyePreview)
229 { dyePreview.style.background = rgbToCss(color); }
230 if (dyeRNum)
231 { dyeRNum.value = String(Math.round(color.r * 255)); }
232 if (dyeGNum)
233 { dyeGNum.value = String(Math.round(color.g * 255)); }
234 if (dyeBNum)
235 { dyeBNum.value = String(Math.round(color.b * 255)); }
236 }
237
238 function setDyeSliders (color)
239 {
240 const c = normalizeRgb(color, { r: 200 / 255, g: 80 / 255, b: 120 / 255 });
241 const r = Math.round(c.r * 255);
242 const g = Math.round(c.g * 255);
243 const b = Math.round(c.b * 255);
244 if (dyeR)
245 { dyeR.value = String(r); }
246 if (dyeG)
247 { dyeG.value = String(g); }
248 if (dyeB)
249 { dyeB.value = String(b); }
250 syncDyePreview();
251 }
252
253 function openDyePicker (slot)
254 {
255 const draft = equipmentDraft[slot];
256 if (!draft?.itemId || !isDyeableClothing(draft.itemId) || !dyeModal || !dyeBackdrop)
257 { return; }
258 dyeEditSlot = slot;
259 const def = itemDefinition(draft.itemId);
260 if (dyeTitle)
261 { dyeTitle.textContent = `Dye — ${def?.displayName ?? slot}`; }
262 setDyeSliders(draft.dyeColor ?? { r: 200 / 255, g: 80 / 255, b: 120 / 255 });
263 dyeBackdrop.hidden = false;
264 dyeModal.hidden = false;
265 }
266
267 function bindDyeChannel (range, num)
268 {
269 range?.addEventListener("input", () =>
270 {
271 if (num)
272 { num.value = range.value; }
273 syncDyePreview();
274 });
275 num?.addEventListener("input", () =>
276 {
277 const v = Math.min(255, Math.max(0, Number(num.value) || 0));
278 num.value = String(v);
279 if (range)
280 { range.value = String(v); }
281 syncDyePreview();
282 });
283 }
284
285 bindDyeChannel(dyeR, dyeRNum);
286 bindDyeChannel(dyeG, dyeGNum);
287 bindDyeChannel(dyeB, dyeBNum);
288
289 function renderSellsList ()
290 {
291 const list = form.querySelector("[data-sells-list]");
292 if (!list)
293 { return; }
294 list.innerHTML = "";
295 if (!sellsDraft.length)
296 {
297 const empty = document.createElement("p");
298 empty.className = "hint";
299 empty.textContent = "No items yet. Use + to add stock.";
300 list.append(empty);
301 return;
302 }
303 for (let index = 0; index < sellsDraft.length; index++)
304 {
305 const line = sellsDraft[index];
306 const def = itemDefinition(line.itemId);
307 const row = document.createElement("div");
308 row.className = "spawner-sells-row";
309 const name = document.createElement("span");
310 name.className = "spawner-sells-name";
311 name.textContent = def?.displayName ?? `Item ${line.itemId}`;
312 const qty = document.createElement("input");
313 qty.type = "number";
314 qty.min = "0";
315 qty.step = "1";
316 qty.value = String(line.quantity | 0);
317 qty.title = "0 = infinite; otherwise restocks this many at 00:00 server time";
318 qty.addEventListener("input", () =>
319 {
320 sellsDraft[index].quantity = Math.max(0, Number(qty.value) || 0) | 0;
321 });
322 const remove = document.createElement("button");
323 remove.type = "button";
324 remove.textContent = "Remove";
325 remove.addEventListener("click", () =>
326 {
327 sellsDraft.splice(index, 1);
328 renderSellsList();
329 });
330 row.append(name, qty, remove);
331 list.append(row);
332 }
333 }
334
335 function renderEquipmentRows ()
336 {
337 const list = form.querySelector("[data-equipment-list]");
338 if (!list)
339 { return; }
340 list.innerHTML = "";
341 for (const slot of EQUIPMENT_SLOTS)
342 {
343 const draft = equipmentDraft[slot] ?? emptyEquipDraft();
344 const itemId = draft.itemId ?? null;
345 const def = itemId ? itemDefinition(itemId) : null;
346 const dyeable = itemId != null && isDyeableClothing(itemId);
347 const row = document.createElement("div");
348 row.className = "spawner-equip-row";
349 const label = document.createElement("span");
350 label.className = "spawner-equip-slot";
351 label.textContent = slot;
352 const name = document.createElement("span");
353 name.className = "spawner-equip-name";
354 if (def && draft.dyeColor)
355 {
356 const swatch = document.createElement("span");
357 swatch.className = "spawner-equip-dye-swatch";
358 swatch.style.background = rgbToCss(draft.dyeColor);
359 name.append(swatch, document.createTextNode(def.displayName));
360 }
361 else
362 { name.textContent = def?.displayName ?? "(none)"; }
363 const pick = document.createElement("button");
364 pick.type = "button";
365 pick.textContent = "Choose…";
366 pick.addEventListener("click", () => openEquipItemSearch(slot));
367 const dyeBtn = document.createElement("button");
368 dyeBtn.type = "button";
369 dyeBtn.textContent = "Dye…";
370 dyeBtn.disabled = !dyeable;
371 dyeBtn.title = dyeable
372 ? "Set clothing dye colour"
373 : "Only tailor clothing can be dyed";
374 dyeBtn.addEventListener("click", () => openDyePicker(slot));
375 const clear = document.createElement("button");
376 clear.type = "button";
377 clear.textContent = "Clear";
378 clear.disabled = itemId == null;
379 clear.addEventListener("click", () =>
380 {
381 equipmentDraft[slot] = emptyEquipDraft();
382 renderEquipmentRows();
383 });
384 row.append(label, name, pick, dyeBtn, clear);
385 list.append(row);
386 }
387 }
388
389 function renderHumanoidFields (config)
390 {
391 const wrap = document.createElement("div");
392 wrap.className = "spawner-humanoid-fields";
393 wrap.dataset.humanoid = "1";
394 const exchange = isCentralExchangeSpawner(config);
395 if (exchange)
396 {
397 const note = document.createElement("p");
398 note.className = "hint";
399 note.textContent = `Spawns all ${centralExchangeStaffCount()} Central Exchange clerks (names & sex fixed). Equipment below is shared. No shop interaction.`;
400 wrap.append(note);
401 }
402 else
403 {
404 wrap.append(
405 field("Display name", textInput("displayName", config.displayName || "Shopkeeper")),
406 field("Sex", sexSelect("sex", config.sex))
407 );
408 }
409
410 const equipHeader = document.createElement("div");
411 equipHeader.className = "spawner-sells-header";
412 const equipTitle = document.createElement("strong");
413 equipTitle.textContent = "Equipment";
414 equipHeader.append(equipTitle);
415 wrap.append(equipHeader);
416
417 const equipList = document.createElement("div");
418 equipList.className = "spawner-equip-list";
419 equipList.dataset.equipmentList = "1";
420 wrap.append(equipList);
421
422 equipmentDraft = {};
423 for (const slot of EQUIPMENT_SLOTS)
424 { equipmentDraft[slot] = equipDraftFromConfig(config.equipment?.[slot]); }
425 queueMicrotask(() => renderEquipmentRows());
426
427 if (!exchange)
428 {
429 wrap.append(field("Hidden discount (0–1)", numberInput("hiddenDiscount", config.hiddenDiscount ?? 0.9, 0.01, 1, 0.01)));
430
431 const sellsHeader = document.createElement("div");
432 sellsHeader.className = "spawner-sells-header";
433 const sellsTitle = document.createElement("strong");
434 sellsTitle.textContent = "Sells";
435 const addBtn = document.createElement("button");
436 addBtn.type = "button";
437 addBtn.textContent = "+";
438 addBtn.title = "Add item";
439 addBtn.addEventListener("click", () => openSellItemSearch());
440 sellsHeader.append(sellsTitle, addBtn);
441 wrap.append(sellsHeader);
442
443 const list = document.createElement("div");
444 list.className = "spawner-sells-list";
445 list.dataset.sellsList = "1";
446 wrap.append(list);
447
448 const buysLabel = document.createElement("label");
449 buysLabel.className = "spawner-buys-row";
450 const buys = document.createElement("input");
451 buys.type = "checkbox";
452 buys.name = "buysItems";
453 buys.checked = !!config.buysItems;
454 buysLabel.append(buys, document.createTextNode(" Buys items"));
455 wrap.append(buysLabel);
456
457 const hint = document.createElement("p");
458 hint.className = "hint";
459 hint.textContent = "Quantity 0 = infinite stock. Limited stock restocks daily at 00:00 server time. 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.";
460 wrap.append(hint);
461
462 sellsDraft = (config.sells ?? []).map((line) =>
463 {
464 if (line && typeof line === "object")
465 { return { itemId: line.itemId | 0, quantity: Math.max(0, line.quantity | 0 || 0) }; }
466 return { itemId: line | 0, quantity: 0 };
467 }).filter((line) => line.itemId > 0);
468
469 queueMicrotask(() => renderSellsList());
470 }
471 else
472 { sellsDraft = []; }
473 return wrap;
474 }
475
476 function syncHumanoidSection (config)
477 {
478 form.querySelector("[data-humanoid]")?.remove();
479 const mobTypeId = form.querySelector('[name="mobTypeId"]')?.value;
480 if (!isHumanoidMob(mobTypeId))
481 {
482 sellsDraft = [];
483 equipmentDraft = {};
484 return;
485 }
486 form.append(renderHumanoidFields(config ?? normalizeSpawnerConfig({
487 mobTypeId: mobTypeId || MobId.humanoid
488 }, "spawner")));
489 const maxAlive = form.querySelector('[name="maxAlive"]');
490 if (maxAlive && isCentralExchangeSpawner({ mobTypeId }))
491 {
492 maxAlive.value = String(centralExchangeStaffCount());
493 maxAlive.disabled = true;
494 }
495 else if (maxAlive)
496 { maxAlive.disabled = false; }
497 }
498
499 function openSpawner (ctx)
500 {
501 context = { kind: "spawner", ...ctx };
502 const config = normalizeSpawnerConfig(ctx.config, ctx.config.spawnerId);
503 title.textContent = `Spawner · ${ctx.tileX}, ${ctx.tileY}`;
504 form.innerHTML = "";
505 const mobField = field("Mob type", mobSelect("mobTypeId", config.mobTypeId));
506 form.append(
507 mobField,
508 field("Max alive", numberInput("maxAlive", config.maxAlive, 1, 20)),
509 field("Spawn range", numberInput("spawnRangeTiles", config.spawnRangeTiles, 1, 32)),
510 field("Max wander range", numberInput("maxWanderRangeTiles", config.maxWanderRangeTiles, 1, 64)),
511 field("Spawner id", textInput("spawnerId", config.spawnerId, true))
512 );
513 const spawnInput = form.querySelector('[name="spawnRangeTiles"]');
514 const wanderInput = form.querySelector('[name="maxWanderRangeTiles"]');
515 const syncWanderMin = () =>
516 {
517 const spawn = Number(spawnInput.value) || 1;
518 wanderInput.min = String(spawn);
519 if (Number(wanderInput.value) < spawn)
520 { wanderInput.value = String(spawn); }
521 };
522 spawnInput.addEventListener("input", syncWanderMin);
523 syncWanderMin();
524 form.querySelector('[name="mobTypeId"]').addEventListener("change", () =>
525 {
526 const nextType = form.querySelector('[name="mobTypeId"]').value;
527 const defaults = normalizeSpawnerConfig({ mobTypeId: nextType }, config.spawnerId);
528 form.querySelector('[name="maxAlive"]').value = String(defaults.maxAlive);
529 form.querySelector('[name="spawnRangeTiles"]').value = String(defaults.spawnRangeTiles);
530 form.querySelector('[name="maxWanderRangeTiles"]').value = String(defaults.maxWanderRangeTiles);
531 syncWanderMin();
532 syncHumanoidSection(defaults);
533 });
534 syncHumanoidSection(config);
535 show(true);
536 }
537
538 document.getElementById("tile-config-close").addEventListener("click", () => show(false));
539 document.getElementById("tile-config-cancel").addEventListener("click", () => show(false));
540 backdrop.addEventListener("click", () => show(false));
541 document.getElementById("shop-item-search-close")?.addEventListener("click", () => closeItemSearch());
542 itemSearchBackdrop?.addEventListener("click", () => closeItemSearch());
543 itemSearchInput?.addEventListener("input", () => renderItemSearchResults(itemSearchInput.value));
544 document.getElementById("equip-dye-close")?.addEventListener("click", () => closeDyePicker());
545 dyeBackdrop?.addEventListener("click", () => closeDyePicker());
546 document.getElementById("equip-dye-apply")?.addEventListener("click", () =>
547 {
548 if (!dyeEditSlot || !equipmentDraft[dyeEditSlot])
549 { return; }
550 equipmentDraft[dyeEditSlot].dyeColor = readDyeSliders();
551 closeDyePicker();
552 renderEquipmentRows();
553 });
554 document.getElementById("equip-dye-clear")?.addEventListener("click", () =>
555 {
556 if (!dyeEditSlot || !equipmentDraft[dyeEditSlot])
557 { return; }
558 equipmentDraft[dyeEditSlot].dyeColor = null;
559 closeDyePicker();
560 renderEquipmentRows();
561 });
562
563 document.getElementById("tile-config-save").addEventListener("click", () =>
564 {
565 if (!context)
566 { return; }
567 const data = new FormData(form);
568 const equipment = {};
569 for (const slot of EQUIPMENT_SLOTS)
570 { equipment[slot] = equipConfigFromDraft(equipmentDraft[slot]); }
571 onSave?.(context, normalizeSpawnerConfig({
572 mobTypeId: String(data.get("mobTypeId") || "deer"),
573 maxAlive: Number(data.get("maxAlive") || 3),
574 spawnRangeTiles: Number(data.get("spawnRangeTiles") || 4),
575 maxWanderRangeTiles: Number(data.get("maxWanderRangeTiles") || 4),
576 spawnerId: String(data.get("spawnerId") || context.config.spawnerId),
577 sex: String(data.get("sex") || "male"),
578 displayName: String(data.get("displayName") || ""),
579 equipment,
580 sells: sellsDraft,
581 buysItems: data.get("buysItems") === "on",
582 hiddenDiscount: Number(data.get("hiddenDiscount") || 0.9),
583 centralExchange: isCentralExchangeSpawner(String(data.get("mobTypeId") || ""))
584 }, context.config.spawnerId));
585 show(false);
586 });
587 document.getElementById("tile-config-remove").addEventListener("click", () =>
588 {
589 if (!context)
590 { return; }
591 onRemove?.(context);
592 show(false);
593 });
594
595 return {
596 isOpen: () => open,
597 openSpawner,
598 close: () => show(false)
599 };
600}
601
602function field (label, input)
603{
604 const wrap = document.createElement("label");
605 wrap.append(document.createTextNode(label), input);
606 return wrap;
607}
608
609function numberInput (name, value, min, max, step = 1)
610{
611 const input = document.createElement("input");
612 input.type = "number";
613 input.name = name;
614 input.min = String(min);
615 input.max = String(max);
616 input.step = String(step);
617 input.value = String(value);
618 return input;
619}
620
621function textInput (name, value, readOnly = false)
622{
623 const input = document.createElement("input");
624 input.type = "text";
625 input.name = name;
626 input.value = String(value ?? "");
627 input.readOnly = readOnly;
628 return input;
629}
630
631function sexSelect (name, value)
632{
633 const select = document.createElement("select");
634 select.name = name;
635 for (const sex of ["male", "female"])
636 {
637 const option = document.createElement("option");
638 option.value = sex;
639 option.textContent = sex;
640 if (sex === value)
641 { option.selected = true; }
642 select.append(option);
643 }
644 return select;
645}
646
647function mobSelect (name, value)
648{
649 const select = document.createElement("select");
650 select.name = name;
651 for (const def of listSpawnableMobTypes())
652 {
653 const option = document.createElement("option");
654 option.value = def.mobTypeId;
655 option.textContent = def.displayName;
656 if (def.mobTypeId === value)
657 { option.selected = true; }
658 select.append(option);
659 }
660 return select;
661}