BlueGit

timfa questward

Files

questward / client / src / play / alchemy.js

alchemy.js

alchemy.js 14.1 KiB Download Raw
1import {
2 itemDefinition,
3 itemDisplayName,
4 itemAssetPathForStack,
5 formatQuantity,
6 ItemId
7} from "/shared/definitions/items.js";
8import {
9 AlchemyStepKind,
10 CAULDRON_SLOT_COUNT,
11 DYE_CAULDRON_SLOT_COUNT,
12 CAULDRON_EMPTY_FLAVOR
13} from "/shared/definitions/alchemy.js";
14import { applyItemIcon } from "../render/potionIcon.js";
15
16export function initAlchemy ({
17 socket,
18 MessageType,
19 getInventorySlots
20})
21{
22 const backdrop = document.getElementById("cauldron-backdrop");
23 const panel = document.getElementById("cauldron-panel");
24 const alchemyPane = document.getElementById("cauldron-alchemy-pane");
25 const dyesPane = document.getElementById("cauldron-dyes-pane");
26 const tabAlchemy = document.getElementById("cauldron-tab-alchemy");
27 const tabDyes = document.getElementById("cauldron-tab-dyes");
28 const slotsEl = document.getElementById("cauldron-slots");
29 const dyeSlotsEl = document.getElementById("cauldron-dye-slots");
30 const insertsEl = document.getElementById("cauldron-inserts");
31 const stepsEl = document.getElementById("cauldron-steps");
32 const flavorEl = document.getElementById("cauldron-flavor");
33 const statusEl = document.getElementById("cauldron-status");
34 const dyeStatusEl = document.getElementById("cauldron-dye-status");
35 const saveBtn = document.getElementById("cauldron-save-recipe");
36 const stirBtn = document.getElementById("cauldron-stir");
37 const heatBtn = document.getElementById("cauldron-heat");
38 const coolBtn = document.getElementById("cauldron-cool");
39 const pickBackdrop = document.getElementById("cauldron-pick-backdrop");
40 const pickPanel = document.getElementById("cauldron-pick-panel");
41 const pickTitle = document.getElementById("cauldron-pick-title");
42 const pickList = document.getElementById("cauldron-pick-list");
43 const pickQty = document.getElementById("cauldron-pick-qty");
44 const confirmBackdrop = document.getElementById("cauldron-dye-confirm-backdrop");
45 const confirmPanel = document.getElementById("cauldron-dye-confirm-panel");
46 const confirmText = document.getElementById("cauldron-dye-confirm-text");
47
48 let open = false;
49 let state = null;
50 let localSlots = emptyAlchemySlots();
51 let localDyeSlots = emptyDyeSlots();
52 let activeTab = "alchemy";
53 let pickMode = "alchemy";
54 let pickSlotIndex = null;
55 let pickItemId = null;
56 let pickInstance = null;
57 let pendingDyeConfirm = null;
58
59 function emptyAlchemySlots ()
60 {
61 return Array.from({ length: CAULDRON_SLOT_COUNT }, () => null);
62 }
63
64 function emptyDyeSlots ()
65 {
66 return Array.from({ length: DYE_CAULDRON_SLOT_COUNT }, () => null);
67 }
68
69 function flowerPayload ()
70 {
71 return localDyeSlots
72 .filter((slot) => slot?.itemId === ItemId.flower && slot.quantity > 0)
73 .map((slot) => ({
74 itemId: slot.itemId,
75 quantity: slot.quantity | 0,
76 instance: slot.instance ? structuredClone(slot.instance) : null
77 }));
78 }
79
80 document.getElementById("cauldron-close")?.addEventListener("click", () => close());
81 backdrop?.addEventListener("click", () => close());
82 tabAlchemy?.addEventListener("click", () => setTab("alchemy"));
83 tabDyes?.addEventListener("click", () => setTab("dyes"));
84 stirBtn?.addEventListener("click", () =>
85 { socket.send({ type: MessageType.cauldronAction, action: AlchemyStepKind.stir }); });
86 heatBtn?.addEventListener("click", () =>
87 { socket.send({ type: MessageType.cauldronAction, action: AlchemyStepKind.heat }); });
88 coolBtn?.addEventListener("click", () =>
89 { socket.send({ type: MessageType.cauldronAction, action: AlchemyStepKind.cool }); });
90 document.getElementById("cauldron-bottle")?.addEventListener("click", () =>
91 { socket.send({ type: MessageType.cauldronBottle }); });
92 document.getElementById("cauldron-clear")?.addEventListener("click", () =>
93 {
94 localSlots = emptyAlchemySlots();
95 socket.send({ type: MessageType.cauldronClear });
96 render();
97 });
98 document.getElementById("cauldron-create-dye")?.addEventListener("click", () =>
99 {
100 socket.send({
101 type: MessageType.cauldronCreateDye,
102 confirmOverflow: false,
103 flowers: flowerPayload()
104 });
105 });
106 document.getElementById("cauldron-clear-dye")?.addEventListener("click", () =>
107 {
108 localDyeSlots = emptyDyeSlots();
109 socket.send({ type: MessageType.cauldronClearDye });
110 render();
111 });
112 saveBtn?.addEventListener("click", () =>
113 { socket.send({ type: MessageType.cauldronSaveRecipe }); });
114 document.getElementById("cauldron-pick-cancel")?.addEventListener("click", () => closePick());
115 document.getElementById("cauldron-pick-confirm")?.addEventListener("click", () => confirmPick());
116 pickBackdrop?.addEventListener("click", () => closePick());
117 document.getElementById("cauldron-dye-confirm-cancel")?.addEventListener("click", () => closeDyeConfirm());
118 confirmBackdrop?.addEventListener("click", () => closeDyeConfirm());
119 document.getElementById("cauldron-dye-confirm-ok")?.addEventListener("click", () =>
120 {
121 closeDyeConfirm();
122 socket.send({
123 type: MessageType.cauldronCreateDye,
124 confirmOverflow: true,
125 flowers: flowerPayload()
126 });
127 });
128
129 function setTab (tab)
130 {
131 activeTab = tab;
132 const alchemy = tab === "alchemy";
133 if (tabAlchemy)
134 {
135 tabAlchemy.classList.toggle("active", alchemy);
136 tabAlchemy.setAttribute("aria-selected", alchemy ? "true" : "false");
137 }
138 if (tabDyes)
139 {
140 tabDyes.classList.toggle("active", !alchemy);
141 tabDyes.setAttribute("aria-selected", alchemy ? "false" : "true");
142 }
143 if (alchemyPane)
144 { alchemyPane.hidden = !alchemy; }
145 if (dyesPane)
146 { dyesPane.hidden = alchemy; }
147 }
148
149 function render ()
150 {
151 if (!open || !panel)
152 { return; }
153 renderAlchemySlots();
154 renderDyeSlots();
155 renderSteps();
156 if (flavorEl)
157 { flavorEl.textContent = state?.flavorText ?? CAULDRON_EMPTY_FLAVOR; }
158 const canAct = !!state?.canProcessActions;
159 if (stirBtn)
160 { stirBtn.disabled = !canAct; }
161 if (heatBtn)
162 { heatBtn.disabled = !canAct; }
163 if (coolBtn)
164 { coolBtn.disabled = !canAct; }
165 if (saveBtn)
166 { saveBtn.hidden = !state?.canSaveRecipe; }
167 }
168
169 function alchemySlotsLocked ()
170 {
171 return state?.canAddIngredients === false
172 || ((state?.steps?.length ?? 0) > 0);
173 }
174
175 function renderSlotButton (reserved, { onClick, locked = false } = {})
176 {
177 const slotBtn = document.createElement("button");
178 slotBtn.type = "button";
179 slotBtn.className = "cauldron-slot";
180 if (locked)
181 { slotBtn.classList.add("locked"); }
182 if (reserved)
183 {
184 const stack = {
185 itemId: reserved.itemId,
186 quantity: reserved.quantity,
187 instance: reserved.instance ?? null
188 };
189 const img = document.createElement("img");
190 applyItemIcon(img, stack, itemAssetPathForStack(stack));
191 img.alt = itemDisplayName(stack);
192 const qty = document.createElement("span");
193 qty.className = "qty";
194 qty.textContent = formatQuantity(reserved.quantity);
195 slotBtn.append(img, qty);
196 slotBtn.title = locked
197 ? `${itemDisplayName(stack)} ×${reserved.quantity} (locked until Bottle)`
198 : `${itemDisplayName(stack)} ×${reserved.quantity}`;
199 }
200 else
201 {
202 slotBtn.textContent = "+";
203 if (locked)
204 { slotBtn.title = "Ingredient slots lock after the first brew step"; }
205 }
206 slotBtn.disabled = locked && !reserved;
207 if (!locked)
208 { slotBtn.addEventListener("click", onClick); }
209 else if (reserved)
210 {
211 // Filled + locked: still show contents, no replace/clear via click.
212 slotBtn.disabled = true;
213 }
214 return slotBtn;
215 }
216
217 function renderAlchemySlots ()
218 {
219 slotsEl.replaceChildren();
220 insertsEl.replaceChildren();
221 const locked = alchemySlotsLocked();
222 for (let i = 0; i < CAULDRON_SLOT_COUNT; i++)
223 {
224 const reserved = localSlots[i] ?? null;
225 slotsEl.append(renderSlotButton(reserved, {
226 locked,
227 onClick: () => openPick("alchemy", i)
228 }));
229 const insertBtn = document.createElement("button");
230 insertBtn.type = "button";
231 insertBtn.className = "cauldron-insert";
232 insertBtn.textContent = "↓";
233 insertBtn.disabled = !reserved;
234 insertBtn.title = "Insert into cauldron";
235 insertBtn.addEventListener("click", () =>
236 {
237 const slot = localSlots[i];
238 if (!slot)
239 { return; }
240 socket.send({
241 type: MessageType.cauldronInsert,
242 itemId: slot.itemId,
243 quantity: slot.quantity | 0,
244 instance: slot.instance ?? null
245 });
246 localSlots[i] = null;
247 render();
248 });
249 insertsEl.append(insertBtn);
250 }
251 }
252
253 function renderDyeSlots ()
254 {
255 if (!dyeSlotsEl)
256 { return; }
257 dyeSlotsEl.replaceChildren();
258 for (let i = 0; i < DYE_CAULDRON_SLOT_COUNT; i++)
259 {
260 const reserved = localDyeSlots[i] ?? null;
261 dyeSlotsEl.append(renderSlotButton(reserved, {
262 onClick: () => openPick("dye", i)
263 }));
264 }
265 }
266
267 function renderSteps ()
268 {
269 stepsEl.replaceChildren();
270 for (const step of state?.steps ?? [])
271 {
272 const li = document.createElement("li");
273 if (step.kind === AlchemyStepKind.insert)
274 {
275 const def = itemDefinition(step.itemId);
276 li.textContent = `insert ${def?.displayName ?? step.itemId}`;
277 }
278 else
279 { li.textContent = step.kind; }
280 stepsEl.append(li);
281 }
282 }
283
284 function openPick (mode, slotIndex)
285 {
286 if (mode === "alchemy" && alchemySlotsLocked())
287 { return; }
288 pickMode = mode;
289 pickSlotIndex = slotIndex;
290 pickItemId = null;
291 pickInstance = null;
292 if (pickTitle)
293 { pickTitle.textContent = mode === "dye" ? "Choose flower" : "Choose ingredient"; }
294 pickList.replaceChildren();
295 const counts = new Map();
296 for (const slot of getInventorySlots?.() ?? [])
297 {
298 if (!slot)
299 { continue; }
300 const def = itemDefinition(slot.itemId);
301 if (!def || def.uniqueInstance || def.equipment
302 || slot.itemId === ItemId.potion || slot.itemId === ItemId.glassBottle)
303 { continue; }
304 if (mode === "dye")
305 {
306 if (slot.itemId !== ItemId.flower)
307 { continue; }
308 }
309 else if (slot.itemId === ItemId.flower || slot.itemId === ItemId.dye || def.flower || def.dye)
310 { continue; }
311
312 const identity = slot.itemId === ItemId.flower
313 ? `${slot.itemId}|${JSON.stringify(slot.instance ?? null)}`
314 : String(slot.itemId);
315 const prev = counts.get(identity);
316 if (prev)
317 { prev.quantity += slot.quantity | 0; }
318 else
319 {
320 counts.set(identity, {
321 itemId: slot.itemId,
322 quantity: slot.quantity | 0,
323 instance: slot.instance ? structuredClone(slot.instance) : null
324 });
325 }
326 }
327 for (const entry of counts.values())
328 {
329 const stack = {
330 itemId: entry.itemId,
331 quantity: entry.quantity,
332 instance: entry.instance
333 };
334 const btn = document.createElement("button");
335 btn.type = "button";
336 btn.className = "cauldron-pick-item";
337 const img = document.createElement("img");
338 applyItemIcon(img, stack, itemAssetPathForStack(stack));
339 const label = document.createElement("span");
340 label.textContent = `${itemDisplayName(stack)} (${formatQuantity(entry.quantity)})`;
341 btn.append(img, label);
342 btn.addEventListener("click", () =>
343 {
344 pickItemId = entry.itemId;
345 pickInstance = entry.instance;
346 pickQty.max = String(entry.quantity);
347 pickQty.value = String(Math.min(entry.quantity, Number(pickQty.value) || 1));
348 for (const child of pickList.children)
349 { child.classList.toggle("selected", child === btn); }
350 });
351 pickList.append(btn);
352 }
353 pickQty.value = "1";
354 pickBackdrop.hidden = false;
355 pickPanel.hidden = false;
356 }
357
358 function closePick ()
359 {
360 pickBackdrop.hidden = true;
361 pickPanel.hidden = true;
362 pickSlotIndex = null;
363 pickItemId = null;
364 pickInstance = null;
365 }
366
367 function confirmPick ()
368 {
369 if (pickSlotIndex == null || pickItemId == null)
370 { return; }
371 const quantity = Math.max(1, pickQty.value | 0);
372 const entry = {
373 itemId: pickItemId,
374 quantity,
375 instance: pickInstance ? structuredClone(pickInstance) : null
376 };
377 if (pickMode === "dye")
378 { localDyeSlots[pickSlotIndex] = entry; }
379 else
380 { localSlots[pickSlotIndex] = entry; }
381 closePick();
382 render();
383 }
384
385 function openDyeConfirm (confirm)
386 {
387 pendingDyeConfirm = confirm;
388 const wanted = confirm.wanted | 0;
389 const bottles = confirm.bottles | 0;
390 confirmText.textContent = `Je staat op het punt ${wanted} units aan dye te maken, maar je hebt maar genoeg lege flesjes om ${bottles} op te slaan. De rest gaat verloren. Weet je het zeker?`;
391 confirmBackdrop.hidden = false;
392 confirmPanel.hidden = false;
393 }
394
395 function closeDyeConfirm ()
396 {
397 pendingDyeConfirm = null;
398 confirmBackdrop.hidden = true;
399 confirmPanel.hidden = true;
400 }
401
402 function openFromServer (nextState)
403 {
404 open = true;
405 state = nextState;
406 localSlots = emptyAlchemySlots();
407 localDyeSlots = emptyDyeSlots();
408 backdrop.hidden = false;
409 panel.hidden = false;
410 if (statusEl)
411 { statusEl.textContent = ""; }
412 if (dyeStatusEl)
413 { dyeStatusEl.textContent = ""; }
414 setTab(activeTab);
415 render();
416 }
417
418 function close ()
419 {
420 if (!open)
421 { return; }
422 open = false;
423 backdrop.hidden = true;
424 panel.hidden = true;
425 localSlots = emptyAlchemySlots();
426 localDyeSlots = emptyDyeSlots();
427 closePick();
428 closeDyeConfirm();
429 socket.send({ type: MessageType.cauldronClose });
430 }
431
432 return {
433 isBlocking ()
434 {
435 return open
436 || !pickPanel?.hidden
437 || !confirmPanel?.hidden;
438 },
439 reset ()
440 {
441 open = false;
442 state = null;
443 localSlots = emptyAlchemySlots();
444 localDyeSlots = emptyDyeSlots();
445 if (backdrop)
446 { backdrop.hidden = true; }
447 if (panel)
448 { panel.hidden = true; }
449 closePick();
450 closeDyeConfirm();
451 },
452 handleSnapshot (message)
453 {
454 if (!message.open)
455 {
456 open = false;
457 if (backdrop)
458 { backdrop.hidden = true; }
459 if (panel)
460 { panel.hidden = true; }
461 state = null;
462 localSlots = emptyAlchemySlots();
463 localDyeSlots = emptyDyeSlots();
464 closeDyeConfirm();
465 return;
466 }
467 if (!open)
468 { openFromServer(message.state); }
469 else
470 {
471 state = message.state;
472 render();
473 }
474 if (message.dyeConfirm)
475 { openDyeConfirm(message.dyeConfirm); }
476 if (message.alchemyResult)
477 {
478 const result = message.alchemyResult;
479 const name = result.potion?.displayName ?? "Potion";
480 const lost = result.lost > 0 ? ` (${result.lost} lost — not enough bottles)` : "";
481 const line = result.success
482 ? `Bottled ${result.produced}× ${name}${lost}.`
483 : `Unstable brew: ${result.produced}× ${name}${lost}.`;
484 if (result.potion?.potionKey === "dye")
485 {
486 localDyeSlots = emptyDyeSlots();
487 if (dyeStatusEl)
488 { dyeStatusEl.textContent = line; }
489 render();
490 }
491 else
492 {
493 localSlots = emptyAlchemySlots();
494 if (statusEl)
495 { statusEl.textContent = line; }
496 render();
497 }
498 }
499 },
500 refresh ()
501 { render(); }
502 };
503}