BlueGit

timfa questward

Files

questward / client / src / play / alchemy.js

alchemy.js

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