BlueGit

timfa questward

Files

questward / client / src / play / alchemy.js

alchemy.js

alchemy.js 16.9 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 { FLOWER_MAX_STACK } from "/shared/definitions/dyes.js";
15import { applyItemIcon } from "../render/potionIcon.js";
16
17export function initAlchemy ({
18 socket,
19 MessageType,
20 getInventorySlots
21})
22{
23 const backdrop = document.getElementById("cauldron-backdrop");
24 const panel = document.getElementById("cauldron-panel");
25 const alchemyPane = document.getElementById("cauldron-alchemy-pane");
26 const dyesPane = document.getElementById("cauldron-dyes-pane");
27 const tabAlchemy = document.getElementById("cauldron-tab-alchemy");
28 const tabDyes = document.getElementById("cauldron-tab-dyes");
29 const slotsEl = document.getElementById("cauldron-slots");
30 const dyeSlotsEl = document.getElementById("cauldron-dye-slots");
31 const insertsEl = document.getElementById("cauldron-inserts");
32 const stepsEl = document.getElementById("cauldron-steps");
33 const flavorEl = document.getElementById("cauldron-flavor");
34 const statusEl = document.getElementById("cauldron-status");
35 const dyeStatusEl = document.getElementById("cauldron-dye-status");
36 const saveBtn = document.getElementById("cauldron-save-recipe");
37 const stirBtn = document.getElementById("cauldron-stir");
38 const heatBtn = document.getElementById("cauldron-heat");
39 const coolBtn = document.getElementById("cauldron-cool");
40 const pickBackdrop = document.getElementById("cauldron-pick-backdrop");
41 const pickPanel = document.getElementById("cauldron-pick-panel");
42 const pickTitle = document.getElementById("cauldron-pick-title");
43 const pickList = document.getElementById("cauldron-pick-list");
44 const pickQty = document.getElementById("cauldron-pick-qty");
45 const confirmBackdrop = document.getElementById("cauldron-dye-confirm-backdrop");
46 const confirmPanel = document.getElementById("cauldron-dye-confirm-panel");
47 const confirmText = document.getElementById("cauldron-dye-confirm-text");
48
49 let open = false;
50 let state = null;
51 let localSlots = emptyAlchemySlots();
52 let localDyeSlots = emptyDyeSlots();
53 let activeTab = "alchemy";
54 let pickMode = "alchemy";
55 let pickSlotIndex = null;
56 let pickItemId = null;
57 let pickInstance = null;
58 let pendingDyeConfirm = null;
59 let onSoftClaimsChanged = null;
60
61 function emptyAlchemySlots ()
62 {
63 return Array.from({ length: CAULDRON_SLOT_COUNT }, () => null);
64 }
65
66 function emptyDyeSlots ()
67 {
68 return Array.from({ length: DYE_CAULDRON_SLOT_COUNT }, () => null);
69 }
70
71 function sameClaimInstance (a, b)
72 {
73 return JSON.stringify(a ?? null) === JSON.stringify(b ?? null);
74 }
75
76 /** Soft claims: local UI slots + server brew pending (still in bag). */
77 function listSoftClaims ({ excludeMode = null, excludeSlotIndex = null } = {})
78 {
79 const claims = [];
80 const push = (slot) =>
81 {
82 if (!slot?.itemId || !(slot.quantity > 0))
83 { return; }
84 claims.push({
85 itemId: slot.itemId | 0,
86 quantity: slot.quantity | 0,
87 instance: slot.instance ? structuredClone(slot.instance) : null
88 });
89 };
90 for (let i = 0; i < localSlots.length; i++)
91 {
92 if (excludeMode === "alchemy" && excludeSlotIndex === i)
93 { continue; }
94 push(localSlots[i]);
95 }
96 for (let i = 0; i < localDyeSlots.length; i++)
97 {
98 if (excludeMode === "dye" && excludeSlotIndex === i)
99 { continue; }
100 push(localDyeSlots[i]);
101 }
102 for (const row of state?.brew ?? [])
103 { push(row); }
104 return claims;
105 }
106
107 function claimedQuantityFor (itemId, instance, opts = {})
108 {
109 const id = itemId | 0;
110 let total = 0;
111 for (const claim of listSoftClaims(opts))
112 {
113 if ((claim.itemId | 0) !== id)
114 { continue; }
115 if (id === ItemId.flower && !sameClaimInstance(claim.instance, instance))
116 { continue; }
117 total += claim.quantity | 0;
118 }
119 return total;
120 }
121
122 function notifySoftClaimsChanged ()
123 {
124 onSoftClaimsChanged?.();
125 }
126
127 function flowerPayload ()
128 {
129 return localDyeSlots
130 .filter((slot) => slot?.itemId === ItemId.flower && slot.quantity > 0)
131 .map((slot) => ({
132 itemId: slot.itemId,
133 quantity: slot.quantity | 0,
134 instance: slot.instance ? structuredClone(slot.instance) : null
135 }));
136 }
137
138 document.getElementById("cauldron-close")?.addEventListener("click", () => close());
139 backdrop?.addEventListener("click", () => close());
140 tabAlchemy?.addEventListener("click", () => setTab("alchemy"));
141 tabDyes?.addEventListener("click", () => setTab("dyes"));
142 stirBtn?.addEventListener("click", () =>
143 { socket.send({ type: MessageType.cauldronAction, action: AlchemyStepKind.stir }); });
144 heatBtn?.addEventListener("click", () =>
145 { socket.send({ type: MessageType.cauldronAction, action: AlchemyStepKind.heat }); });
146 coolBtn?.addEventListener("click", () =>
147 { socket.send({ type: MessageType.cauldronAction, action: AlchemyStepKind.cool }); });
148 document.getElementById("cauldron-bottle")?.addEventListener("click", () =>
149 { socket.send({ type: MessageType.cauldronBottle }); });
150 document.getElementById("cauldron-clear")?.addEventListener("click", () =>
151 {
152 localSlots = emptyAlchemySlots();
153 socket.send({ type: MessageType.cauldronClear });
154 render();
155 });
156 document.getElementById("cauldron-create-dye")?.addEventListener("click", () =>
157 {
158 socket.send({
159 type: MessageType.cauldronCreateDye,
160 confirmOverflow: false,
161 flowers: flowerPayload()
162 });
163 });
164 document.getElementById("cauldron-clear-dye")?.addEventListener("click", () =>
165 {
166 localDyeSlots = emptyDyeSlots();
167 socket.send({ type: MessageType.cauldronClearDye });
168 render();
169 });
170 saveBtn?.addEventListener("click", () =>
171 { socket.send({ type: MessageType.cauldronSaveRecipe }); });
172 document.getElementById("cauldron-pick-cancel")?.addEventListener("click", () => closePick());
173 document.getElementById("cauldron-pick-confirm")?.addEventListener("click", () => confirmPick());
174 pickBackdrop?.addEventListener("click", () => closePick());
175 document.getElementById("cauldron-dye-confirm-cancel")?.addEventListener("click", () => closeDyeConfirm());
176 confirmBackdrop?.addEventListener("click", () => closeDyeConfirm());
177 document.getElementById("cauldron-dye-confirm-ok")?.addEventListener("click", () =>
178 {
179 closeDyeConfirm();
180 socket.send({
181 type: MessageType.cauldronCreateDye,
182 confirmOverflow: true,
183 flowers: flowerPayload()
184 });
185 });
186
187 function setTab (tab)
188 {
189 activeTab = tab;
190 const alchemy = tab === "alchemy";
191 if (tabAlchemy)
192 {
193 tabAlchemy.classList.toggle("active", alchemy);
194 tabAlchemy.setAttribute("aria-selected", alchemy ? "true" : "false");
195 }
196 if (tabDyes)
197 {
198 tabDyes.classList.toggle("active", !alchemy);
199 tabDyes.setAttribute("aria-selected", alchemy ? "false" : "true");
200 }
201 if (alchemyPane)
202 { alchemyPane.hidden = !alchemy; }
203 if (dyesPane)
204 { dyesPane.hidden = alchemy; }
205 }
206
207 function render ()
208 {
209 if (!open || !panel)
210 { return; }
211 renderAlchemySlots();
212 renderDyeSlots();
213 renderSteps();
214 if (flavorEl)
215 { flavorEl.textContent = state?.flavorText ?? CAULDRON_EMPTY_FLAVOR; }
216 const canAct = !!state?.canProcessActions;
217 if (stirBtn)
218 { stirBtn.disabled = !canAct; }
219 if (heatBtn)
220 { heatBtn.disabled = !canAct; }
221 if (coolBtn)
222 { coolBtn.disabled = !canAct; }
223 if (saveBtn)
224 { saveBtn.hidden = !state?.canSaveRecipe; }
225 }
226
227 function alchemySlotsLocked ()
228 {
229 return state?.canAddIngredients === false
230 || ((state?.steps?.length ?? 0) > 0);
231 }
232
233 function renderSlotButton (reserved, { onClick, locked = false } = {})
234 {
235 const slotBtn = document.createElement("button");
236 slotBtn.type = "button";
237 slotBtn.className = "cauldron-slot";
238 if (locked)
239 { slotBtn.classList.add("locked"); }
240 if (reserved)
241 {
242 const stack = {
243 itemId: reserved.itemId,
244 quantity: reserved.quantity,
245 instance: reserved.instance ?? null
246 };
247 const img = document.createElement("img");
248 applyItemIcon(img, stack, itemAssetPathForStack(stack));
249 img.alt = itemDisplayName(stack);
250 const qty = document.createElement("span");
251 qty.className = "qty";
252 qty.textContent = formatQuantity(reserved.quantity);
253 slotBtn.append(img, qty);
254 slotBtn.title = locked
255 ? `${itemDisplayName(stack)} ×${reserved.quantity} (locked until Bottle)`
256 : `${itemDisplayName(stack)} ×${reserved.quantity}`;
257 }
258 else
259 {
260 slotBtn.textContent = "+";
261 if (locked)
262 { slotBtn.title = "Ingredient slots lock after the first brew step"; }
263 }
264 slotBtn.disabled = locked && !reserved;
265 if (!locked)
266 { slotBtn.addEventListener("click", onClick); }
267 else if (reserved)
268 {
269 // Filled + locked: still show contents, no replace/clear via click.
270 slotBtn.disabled = true;
271 }
272 return slotBtn;
273 }
274
275 function renderAlchemySlots ()
276 {
277 slotsEl.replaceChildren();
278 insertsEl.replaceChildren();
279 const locked = alchemySlotsLocked();
280 for (let i = 0; i < CAULDRON_SLOT_COUNT; i++)
281 {
282 const reserved = localSlots[i] ?? null;
283 slotsEl.append(renderSlotButton(reserved, {
284 locked,
285 onClick: () => openPick("alchemy", i)
286 }));
287 const insertBtn = document.createElement("button");
288 insertBtn.type = "button";
289 insertBtn.className = "cauldron-insert";
290 insertBtn.textContent = "↓";
291 insertBtn.disabled = !reserved;
292 insertBtn.title = "Insert into cauldron";
293 insertBtn.addEventListener("click", () =>
294 {
295 const slot = localSlots[i];
296 if (!slot)
297 { return; }
298 socket.send({
299 type: MessageType.cauldronInsert,
300 itemId: slot.itemId,
301 quantity: slot.quantity | 0,
302 instance: slot.instance ?? null
303 });
304 localSlots[i] = null;
305 render();
306 notifySoftClaimsChanged();
307 });
308 insertsEl.append(insertBtn);
309 }
310 }
311
312 function renderDyeSlots ()
313 {
314 if (!dyeSlotsEl)
315 { return; }
316 dyeSlotsEl.replaceChildren();
317 for (let i = 0; i < DYE_CAULDRON_SLOT_COUNT; i++)
318 {
319 const reserved = localDyeSlots[i] ?? null;
320 dyeSlotsEl.append(renderSlotButton(reserved, {
321 onClick: () => openPick("dye", i)
322 }));
323 }
324 }
325
326 function renderSteps ()
327 {
328 stepsEl.replaceChildren();
329 for (const step of state?.steps ?? [])
330 {
331 const li = document.createElement("li");
332 if (step.kind === AlchemyStepKind.insert)
333 {
334 const def = itemDefinition(step.itemId);
335 li.textContent = `insert ${def?.displayName ?? step.itemId}`;
336 }
337 else
338 { li.textContent = step.kind; }
339 stepsEl.append(li);
340 }
341 }
342
343 function openPick (mode, slotIndex)
344 {
345 if (mode === "alchemy" && alchemySlotsLocked())
346 { return; }
347 pickMode = mode;
348 pickSlotIndex = slotIndex;
349 pickItemId = null;
350 pickInstance = null;
351 if (pickTitle)
352 { pickTitle.textContent = mode === "dye" ? "Choose flower" : "Choose ingredient"; }
353 pickList.replaceChildren();
354 const counts = new Map();
355 for (const slot of getInventorySlots?.() ?? [])
356 {
357 if (!slot)
358 { continue; }
359 const def = itemDefinition(slot.itemId);
360 if (!def || def.uniqueInstance || def.equipment
361 || slot.itemId === ItemId.potion || slot.itemId === ItemId.glassBottle)
362 { continue; }
363 if (mode === "dye")
364 {
365 if (slot.itemId !== ItemId.flower)
366 { continue; }
367 }
368 else if (slot.itemId === ItemId.flower || slot.itemId === ItemId.dye || def.flower || def.dye)
369 { continue; }
370
371 const identity = slot.itemId === ItemId.flower
372 ? `${slot.itemId}|${JSON.stringify(slot.instance ?? null)}`
373 : String(slot.itemId);
374 const prev = counts.get(identity);
375 if (prev)
376 { prev.quantity += slot.quantity | 0; }
377 else
378 {
379 counts.set(identity, {
380 itemId: slot.itemId,
381 quantity: slot.quantity | 0,
382 instance: slot.instance ? structuredClone(slot.instance) : null
383 });
384 }
385 }
386 for (const entry of counts.values())
387 {
388 entry.quantity = Math.max(
389 0,
390 (entry.quantity | 0) - claimedQuantityFor(entry.itemId, entry.instance, {
391 excludeMode: mode,
392 excludeSlotIndex: slotIndex
393 })
394 );
395 }
396 for (const entry of counts.values())
397 {
398 if (!(entry.quantity > 0))
399 { continue; }
400 const stack = {
401 itemId: entry.itemId,
402 quantity: entry.quantity,
403 instance: entry.instance
404 };
405 const btn = document.createElement("button");
406 btn.type = "button";
407 btn.className = "cauldron-pick-item";
408 const img = document.createElement("img");
409 applyItemIcon(img, stack, itemAssetPathForStack(stack));
410 const label = document.createElement("span");
411 label.textContent = `${itemDisplayName(stack)} (${formatQuantity(entry.quantity)})`;
412 btn.append(img, label);
413 btn.addEventListener("click", () =>
414 {
415 pickItemId = entry.itemId;
416 pickInstance = entry.instance;
417 pickQty.max = String(pickMode === "dye"
418 ? Math.min(entry.quantity, FLOWER_MAX_STACK)
419 : entry.quantity);
420 pickQty.value = String(Math.min(
421 entry.quantity,
422 Number(pickQty.value) || 1,
423 pickMode === "dye" ? FLOWER_MAX_STACK : entry.quantity
424 ));
425 for (const child of pickList.children)
426 { child.classList.toggle("selected", child === btn); }
427 });
428 pickList.append(btn);
429 }
430 pickQty.value = "1";
431 pickBackdrop.hidden = false;
432 pickPanel.hidden = false;
433 }
434
435 function closePick ()
436 {
437 pickBackdrop.hidden = true;
438 pickPanel.hidden = true;
439 pickSlotIndex = null;
440 pickItemId = null;
441 pickInstance = null;
442 }
443
444 function confirmPick ()
445 {
446 if (pickSlotIndex == null || pickItemId == null)
447 { return; }
448 const rawQty = Math.max(1, pickQty.value | 0);
449 const available = claimedQuantityFor
450 ? Math.max(0, (() =>
451 {
452 let bagQty = 0;
453 for (const slot of getInventorySlots?.() ?? [])
454 {
455 if (!slot || (slot.itemId | 0) !== (pickItemId | 0))
456 { continue; }
457 if (pickItemId === ItemId.flower && !sameClaimInstance(slot.instance, pickInstance))
458 { continue; }
459 bagQty += slot.quantity | 0;
460 }
461 return bagQty - claimedQuantityFor(pickItemId, pickInstance, {
462 excludeMode: pickMode,
463 excludeSlotIndex: pickSlotIndex
464 });
465 })())
466 : rawQty;
467 const quantity = Math.min(
468 rawQty,
469 available,
470 pickMode === "dye" ? FLOWER_MAX_STACK : available
471 );
472 if (quantity <= 0)
473 { return; }
474 const entry = {
475 itemId: pickItemId,
476 quantity,
477 instance: pickInstance ? structuredClone(pickInstance) : null
478 };
479 if (pickMode === "dye")
480 { localDyeSlots[pickSlotIndex] = entry; }
481 else
482 { localSlots[pickSlotIndex] = entry; }
483 closePick();
484 render();
485 notifySoftClaimsChanged();
486 }
487
488 function openDyeConfirm (confirm)
489 {
490 pendingDyeConfirm = confirm;
491 const wanted = confirm.wanted | 0;
492 const bottles = confirm.bottles | 0;
493 confirmText.textContent = `You are about to make ${wanted} units of dye, but you only have enough empty bottles for ${bottles}. The rest will be lost. Are you sure?`;
494 confirmBackdrop.hidden = false;
495 confirmPanel.hidden = false;
496 }
497
498 function closeDyeConfirm ()
499 {
500 pendingDyeConfirm = null;
501 confirmBackdrop.hidden = true;
502 confirmPanel.hidden = true;
503 }
504
505 function openFromServer (nextState)
506 {
507 open = true;
508 state = nextState;
509 localSlots = emptyAlchemySlots();
510 localDyeSlots = emptyDyeSlots();
511 backdrop.hidden = false;
512 panel.hidden = false;
513 if (statusEl)
514 { statusEl.textContent = ""; }
515 if (dyeStatusEl)
516 { dyeStatusEl.textContent = ""; }
517 setTab(activeTab);
518 render();
519 }
520
521 function close ()
522 {
523 if (!open)
524 { return; }
525 open = false;
526 backdrop.hidden = true;
527 panel.hidden = true;
528 localSlots = emptyAlchemySlots();
529 localDyeSlots = emptyDyeSlots();
530 closePick();
531 closeDyeConfirm();
532 socket.send({ type: MessageType.cauldronClose });
533 notifySoftClaimsChanged();
534 }
535
536 return {
537 isBlocking ()
538 {
539 return open
540 || !pickPanel?.hidden
541 || !confirmPanel?.hidden;
542 },
543 isOpen ()
544 {
545 return open;
546 },
547 close,
548 listSoftClaims,
549 setOnSoftClaimsChanged (fn)
550 {
551 onSoftClaimsChanged = typeof fn === "function" ? fn : null;
552 },
553 reset ()
554 {
555 open = false;
556 state = null;
557 localSlots = emptyAlchemySlots();
558 localDyeSlots = emptyDyeSlots();
559 if (backdrop)
560 { backdrop.hidden = true; }
561 if (panel)
562 { panel.hidden = true; }
563 closePick();
564 closeDyeConfirm();
565 notifySoftClaimsChanged();
566 },
567 handleSnapshot (message)
568 {
569 if (!message.open)
570 {
571 open = false;
572 if (backdrop)
573 { backdrop.hidden = true; }
574 if (panel)
575 { panel.hidden = true; }
576 state = null;
577 localSlots = emptyAlchemySlots();
578 localDyeSlots = emptyDyeSlots();
579 closeDyeConfirm();
580 notifySoftClaimsChanged();
581 return;
582 }
583 if (!open)
584 { openFromServer(message.state); }
585 else
586 {
587 state = message.state;
588 render();
589 }
590 notifySoftClaimsChanged();
591 if (message.dyeConfirm)
592 { openDyeConfirm(message.dyeConfirm); }
593 if (message.alchemyResult)
594 {
595 const result = message.alchemyResult;
596 const name = result.potion?.displayName ?? "Potion";
597 const lost = result.lost > 0 ? ` (${result.lost} lost — not enough bottles)` : "";
598 const line = result.success
599 ? `Bottled ${result.produced}× ${name}${lost}.`
600 : `Unstable brew: ${result.produced}× ${name}${lost}.`;
601 if (result.potion?.potionKey === "dye")
602 {
603 localDyeSlots = emptyDyeSlots();
604 if (dyeStatusEl)
605 { dyeStatusEl.textContent = line; }
606 render();
607 }
608 else
609 {
610 localSlots = emptyAlchemySlots();
611 if (statusEl)
612 { statusEl.textContent = line; }
613 render();
614 }
615 }
616 },
617 refresh ()
618 { render(); }
619 };
620}