BlueGit

timfa questward

Files

questward / client / src / play / crafting.js

crafting.js

crafting.js 21.7 KiB Download Raw
1import
2{
3 itemDefinition,
4 itemDisplayName,
5 itemAssetPathForStack,
6 formatQuantity,
7 ItemId
8} from "/shared/definitions/items.js";
9import { craftingStationDefinition, CraftingStationId } from "/shared/definitions/craftingStations.js";
10import
11{
12 CRAFT_DURATION_MS,
13 canStartCraft,
14 countItemInSlots,
15 hasRecipeInputs,
16 recipesForStation
17} from "/shared/crafting/recipes.js";
18import { resolveTailorCraft } from "/shared/crafting/tailor.js";
19import
20{
21 CLOTH_TIER_ORDER,
22 CLOTH_DISPLAY_NAME,
23 ClothTier,
24 MATERIAL_TIER_ORDER,
25 MATERIAL_DISPLAY_NAME,
26 WOOD_TIER_ORDER,
27 WoodTier,
28 MaterialTier,
29 LEATHER_TIER_ORDER,
30 LEATHER_DISPLAY_NAME,
31 LeatherTier,
32 woodTierForMetal,
33 clothTierForWood
34} from "/shared/definitions/materialTiers.js";
35import { craftDurationMs } from "/shared/definitions/gathering.js";
36import { applyItemIcon } from "../render/potionIcon.js";
37
38export function initCrafting ({
39 socket,
40 MessageType,
41 getInventorySlots,
42 getSkillLevel
43})
44{
45 const backdrop = document.getElementById("craft-backdrop");
46 const panel = document.getElementById("craft-panel");
47 const stationName = document.getElementById("craft-station-name");
48 const recipeGrid = document.getElementById("craft-recipe-grid");
49 const detailEmpty = document.getElementById("craft-detail-empty");
50 const detailBody = document.getElementById("craft-detail-body");
51 const materialControls = document.getElementById("craft-material-controls");
52 const materialTierSelect = document.getElementById("craft-material-tier");
53 const dyeControls = document.getElementById("craft-dye-controls");
54 const dyePickBtn = document.getElementById("craft-dye-pick");
55 const dyeClearBtn = document.getElementById("craft-dye-clear");
56 const dyePreview = document.getElementById("craft-dye-preview");
57 const outputImg = document.getElementById("craft-output-img");
58 const outputName = document.getElementById("craft-output-name");
59 const inputsList = document.getElementById("craft-inputs");
60 const statusEl = document.getElementById("craft-status");
61 const progressWrap = document.getElementById("craft-progress");
62 const progressFill = document.getElementById("craft-progress-fill");
63 const craftButton = document.getElementById("craft-button");
64 const craftBatchButton = document.getElementById("craft-batch-button");
65 const craftBatchAllButton = document.getElementById("craft-batch-all-button");
66 const dyeBackdrop = document.getElementById("dye-picker-backdrop");
67 const dyePanel = document.getElementById("dye-picker-panel");
68 const dyeGrid = document.getElementById("dye-picker-grid");
69
70 let open = false;
71 let stationId = null;
72 let recipes = [];
73 let selectedRecipeId = null;
74 let selectedCraftGroup = null;
75 let selectedMaterial = ClothTier.cotton;
76
77 let dyeSlotIndex = null;
78 let crafting = false;
79 let craftTimer = null;
80 let craftAnimFrame = null;
81 let craftStartedAt = 0;
82
83 document.getElementById("craft-close").addEventListener("click", () => close());
84 backdrop.addEventListener("click", () => close());
85 craftButton.addEventListener("click", () => startCraft());
86 craftBatchButton?.addEventListener("click", () => startBatchCraft());
87 craftBatchAllButton?.addEventListener("click", () => startCraft({ batchAll: true }));
88 materialTierSelect?.addEventListener("change", () =>
89 {
90 selectedMaterial = materialTierSelect.value || selectedMaterial;
91 if (usesCraftGroups())
92 {
93 const rows = groupedDisplayRecipes();
94 if (!rows.some((row) => row.group === selectedCraftGroup))
95 { selectedCraftGroup = rows[0]?.group ?? null; }
96 syncSelectedRecipeFromMaterial();
97 }
98 renderRecipeGrid();
99 renderDetail();
100 });
101 dyePickBtn?.addEventListener("click", () =>
102 {
103 if (!isTailorStation())
104 { return; }
105 openDyePicker();
106 });
107 dyeClearBtn?.addEventListener("click", () =>
108 {
109 dyeSlotIndex = null;
110 renderDetail();
111 });
112 document.getElementById("dye-picker-close")?.addEventListener("click", () => closeDyePicker());
113 dyeBackdrop?.addEventListener("click", () => closeDyePicker());
114
115 function isTailorStation ()
116 {
117 return stationId === CraftingStationId.tailorBench;
118 }
119
120 function isAnvilStation ()
121 {
122 return stationId === CraftingStationId.anvil;
123 }
124
125 function isWoodworkingStation ()
126 {
127 return stationId === CraftingStationId.woodworkingBench;
128 }
129
130 function isCraftingBenchStation ()
131 {
132 return stationId === CraftingStationId.craftingBench;
133 }
134
135 function isSpinningWheelStation ()
136 {
137 return stationId === CraftingStationId.spinningWheel;
138 }
139
140 function isLoomStation ()
141 {
142 return stationId === CraftingStationId.loom;
143 }
144
145 function isLeatherworkingStation ()
146 {
147 return stationId === CraftingStationId.leatherworkingStation;
148 }
149
150 function usesMaterialDropdown ()
151 {
152 return isTailorStation()
153 || isAnvilStation()
154 || isWoodworkingStation()
155 || isCraftingBenchStation()
156 || isSpinningWheelStation()
157 || isLoomStation()
158 || isLeatherworkingStation();
159 }
160
161 /** One grid cell per craft group; material dropdown picks the tier variant. */
162 function usesCraftGroups ()
163 {
164 return isAnvilStation()
165 || isWoodworkingStation()
166 || isCraftingBenchStation()
167 || isSpinningWheelStation()
168 || isLoomStation()
169 || isLeatherworkingStation();
170 }
171
172 function craftGroupKey (recipe)
173 {
174 return recipe.craftGroup ?? recipe.recipeId;
175 }
176
177 /** Map UI material selection to a recipe's xpMaterial tier. */
178 function recipeXpMaterialForSelection (recipe, material = selectedMaterial)
179 {
180 if (isCraftingBenchStation()
181 && (recipe.craftGroup === "bow"
182 || recipe.craftGroup === "fishing-rod"
183 || recipe.craftGroup === "staff"))
184 { return woodTierForMetal(material); }
185 if (isCraftingBenchStation() && recipe.craftGroup === "fishing-net")
186 { return clothTierForWood(woodTierForMetal(material)); }
187 return material;
188 }
189
190 function recipeMatchesMaterial (recipe, material = selectedMaterial)
191 {
192 if (!recipe?.xpMaterial)
193 { return true; }
194 return recipe.xpMaterial === recipeXpMaterialForSelection(recipe, material);
195 }
196
197 function selectedRecipe ()
198 {
199 return recipes.find((recipe) => recipe.recipeId === selectedRecipeId) ?? null;
200 }
201
202 function stationSkillLevel ()
203 {
204 const def = craftingStationDefinition(stationId);
205 return getSkillLevel?.(def?.skillId) ?? 1;
206 }
207
208 function activeRecipe ()
209 {
210 const base = selectedRecipe();
211 if (!base)
212 { return null; }
213 if (!base.tailorTemplate)
214 { return base; }
215 const slots = getInventorySlots?.() ?? [];
216 const dyeStack = dyeSlotIndex != null ? slots[dyeSlotIndex] : null;
217 const resolved = resolveTailorCraft({
218 templateId: base.tailorTemplate,
219 clothTier: selectedMaterial,
220 dyeStack
221 });
222 return resolved.ok ? resolved.recipe : base;
223 }
224
225 function refresh ()
226 {
227 if (!open)
228 { return; }
229 renderRecipeGrid();
230 renderDetail();
231 }
232
233 function materialOptionsForStation ()
234 {
235 if (isTailorStation() || isSpinningWheelStation() || isLoomStation())
236 {
237 return {
238 order: CLOTH_TIER_ORDER,
239 names: CLOTH_DISPLAY_NAME,
240 fallback: ClothTier.cotton
241 };
242 }
243 if (isLeatherworkingStation())
244 {
245 return {
246 order: LEATHER_TIER_ORDER,
247 names: LEATHER_DISPLAY_NAME,
248 fallback: LeatherTier.softLeather
249 };
250 }
251 if (isWoodworkingStation())
252 {
253 return {
254 order: WOOD_TIER_ORDER,
255 names: MATERIAL_DISPLAY_NAME,
256 fallback: WoodTier.pine
257 };
258 }
259 // Crafting bench mixes metal tools, wood bows, and cloth fishing gear.
260 if (isCraftingBenchStation())
261 {
262 const names = {};
263 for (const metal of MATERIAL_TIER_ORDER)
264 {
265 const wood = woodTierForMetal(metal);
266 const cloth = clothTierForWood(wood);
267 names[metal] = `${MATERIAL_DISPLAY_NAME[metal] ?? metal}/`
268 + `${MATERIAL_DISPLAY_NAME[wood] ?? wood}/`
269 + `${CLOTH_DISPLAY_NAME[cloth] ?? cloth}`;
270 }
271 return {
272 order: MATERIAL_TIER_ORDER,
273 names,
274 fallback: MaterialTier.bronze
275 };
276 }
277 return {
278 order: MATERIAL_TIER_ORDER,
279 names: MATERIAL_DISPLAY_NAME,
280 fallback: MaterialTier.bronze
281 };
282 }
283
284 function fillMaterialTiers ()
285 {
286 if (!materialTierSelect)
287 { return; }
288 const { order, names, fallback } = materialOptionsForStation();
289 if (!order.includes(selectedMaterial))
290 { selectedMaterial = fallback; }
291 materialTierSelect.replaceChildren();
292 for (const tier of order)
293 {
294 const option = document.createElement("option");
295 option.value = tier;
296 option.textContent = names[tier] ?? tier;
297 materialTierSelect.append(option);
298 }
299 materialTierSelect.value = selectedMaterial;
300 }
301
302 function groupedDisplayRecipes ()
303 {
304 if (!usesCraftGroups())
305 {
306 return recipes.map((recipe) => ({
307 group: craftGroupKey(recipe),
308 recipe
309 }));
310 }
311 const byGroup = new Map();
312 for (const recipe of recipes)
313 {
314 const group = craftGroupKey(recipe);
315 if (!byGroup.has(group))
316 { byGroup.set(group, []); }
317 byGroup.get(group).push(recipe);
318 }
319 const rows = [];
320 for (const [group, variants] of byGroup)
321 {
322 if (!variants.some((entry) => recipeMatchesMaterial(entry)))
323 { continue; }
324 const recipe = variants.find((entry) => recipeMatchesMaterial(entry))
325 ?? variants[0];
326 rows.push({ group, recipe, variants });
327 }
328 return rows;
329 }
330
331 function syncSelectedRecipeFromMaterial ()
332 {
333 if (!usesCraftGroups() || !selectedCraftGroup)
334 { return; }
335 const variants = recipes.filter((recipe) => craftGroupKey(recipe) === selectedCraftGroup);
336 if (!variants.length)
337 { return; }
338 let match = variants.find((entry) => recipeMatchesMaterial(entry));
339 if (!match)
340 {
341 match = variants[0];
342 if (match?.xpMaterial && !(isCraftingBenchStation()
343 && (match.craftGroup === "bow"
344 || match.craftGroup === "fishing-rod"
345 || match.craftGroup === "fishing-net"
346 || match.craftGroup === "staff")))
347 {
348 selectedMaterial = match.xpMaterial;
349 if (materialTierSelect)
350 { materialTierSelect.value = selectedMaterial; }
351 }
352 }
353 selectedRecipeId = match.recipeId;
354 }
355
356 function renderRecipeGrid ()
357 {
358 recipeGrid.replaceChildren();
359 for (const row of groupedDisplayRecipes())
360 {
361 recipeGrid.append(renderRecipeCell(row));
362 }
363 }
364
365 function renderRecipeCell ({ group, recipe })
366 {
367 const def = itemDefinition(recipe.output.itemId);
368 const stack = { itemId: recipe.output.itemId, quantity: recipe.output.quantity | 0 || 1 };
369 const cell = document.createElement("button");
370 cell.type = "button";
371 cell.className = "craft-recipe-cell";
372 const selected = usesCraftGroups()
373 ? group === selectedCraftGroup
374 : recipe.recipeId === selectedRecipeId;
375 if (selected)
376 { cell.classList.add("selected"); }
377
378 const skill = stationSkillLevel();
379 const minLevel = recipe.minSkillLevel | 0 || 1;
380 if ((skill | 0) < minLevel)
381 { cell.classList.add("level-locked"); }
382 else if (canStartCraft(getInventorySlots?.() ?? [], recipe, skill, { dyeSlotIndex }))
383 { cell.classList.add("craftable"); }
384
385 const img = document.createElement("img");
386 img.alt = def?.displayName ?? "Item";
387 applyItemIcon(img, stack, itemAssetPathForStack(stack));
388
389 const label = document.createElement("span");
390 label.className = "craft-recipe-name";
391 if (recipe.tailorTemplate)
392 { label.textContent = def?.displayName?.replace(/^Cotton\s+/i, "") ?? "Garment"; }
393 else if (recipe.craftGroupLabel)
394 { label.textContent = recipe.craftGroupLabel; }
395 else
396 { label.textContent = def?.displayName ?? "Item"; }
397
398 cell.append(img, label);
399 cell.addEventListener("click", () =>
400 {
401 if (crafting)
402 { return; }
403 selectedCraftGroup = group;
404 if (usesCraftGroups())
405 { syncSelectedRecipeFromMaterial(); }
406 else
407 { selectedRecipeId = recipe.recipeId; }
408 renderRecipeGrid();
409 renderDetail();
410 });
411 return cell;
412 }
413
414 function renderDetail ()
415 {
416 if (materialControls)
417 { materialControls.hidden = !usesMaterialDropdown(); }
418 if (!isTailorStation())
419 { dyeSlotIndex = null; }
420 if (dyeControls)
421 { dyeControls.hidden = !isTailorStation(); }
422
423 const recipe = activeRecipe();
424 if (!recipe)
425 {
426 detailEmpty.hidden = false;
427 detailBody.hidden = true;
428 return;
429 }
430 detailEmpty.hidden = true;
431 detailBody.hidden = false;
432
433 const outputStack = {
434 itemId: recipe.output.itemId,
435 quantity: Math.max(1, recipe.output.quantity | 0 || 1),
436 ...(recipe.dyeColor ? { instance: { kind: "clothing", dyeColor: recipe.dyeColor } } : {})
437 };
438 applyItemIcon(outputImg, outputStack, itemAssetPathForStack(outputStack));
439 outputImg.alt = itemDisplayName(outputStack);
440 const qtySuffix = outputStack.quantity > 1 ? ` ×${formatQuantity(outputStack.quantity)}` : "";
441 outputName.textContent = `${itemDisplayName(outputStack)}${qtySuffix}`;
442
443 inputsList.replaceChildren();
444 const slots = getInventorySlots?.() ?? [];
445 for (const input of recipe.inputs ?? [])
446 {
447 inputsList.append(renderInputRow(input, slots));
448 }
449 if (recipe.consumeDye)
450 {
451 const dye = dyeSlotIndex != null ? slots[dyeSlotIndex] : null;
452 const row = document.createElement("li");
453 row.className = "craft-input-row";
454 row.textContent = dye
455 ? `Dye — 1 use (${dye.instance?.fillLevel ?? "?"}/5)`
456 : "Dye — none selected";
457 inputsList.append(row);
458 }
459
460 if (dyePreview && dyeClearBtn)
461 {
462 const dye = dyeSlotIndex != null ? slots[dyeSlotIndex] : null;
463 if (dye?.itemId === ItemId.dye)
464 {
465 dyePreview.hidden = false;
466 dyeClearBtn.hidden = false;
467 applyItemIcon(dyePreview, dye, itemAssetPathForStack(dye));
468 }
469 else
470 {
471 dyePreview.hidden = true;
472 dyeClearBtn.hidden = true;
473 }
474 }
475
476 updateCraftState(slots, recipe);
477 }
478
479 function renderInputRow (input, slots)
480 {
481 const need = input.quantity | 0;
482 const have = countItemInSlots(slots, input.itemId);
483 const stack = { itemId: input.itemId, quantity: need };
484 const row = document.createElement("li");
485 row.className = "craft-input-row";
486 if (have < need)
487 { row.classList.add("short"); }
488
489 const img = document.createElement("img");
490 img.alt = itemDisplayName(stack);
491 applyItemIcon(img, stack, itemAssetPathForStack(stack));
492
493 const text = document.createElement("span");
494 text.textContent = `${itemDisplayName(stack)} — ${formatQuantity(have)} / ${formatQuantity(need)}`;
495 row.append(img, text);
496 return row;
497 }
498
499 function updateCraftState (slots, recipe)
500 {
501 const batchVisible = isCraftingBenchStation();
502 if (craftBatchButton)
503 { craftBatchButton.hidden = !batchVisible; }
504 if (craftBatchAllButton)
505 { craftBatchAllButton.hidden = !batchVisible; }
506
507 if (crafting)
508 {
509 craftButton.disabled = true;
510 if (craftBatchButton)
511 { craftBatchButton.disabled = true; }
512 if (craftBatchAllButton)
513 { craftBatchAllButton.disabled = true; }
514 return;
515 }
516 const skill = stationSkillLevel();
517 const minLevel = recipe.minSkillLevel | 0 || 1;
518 if (skill < minLevel)
519 {
520 statusEl.textContent = `Requires skill level ${minLevel} (you have ${skill}).`;
521 craftButton.disabled = true;
522 if (craftBatchButton)
523 { craftBatchButton.disabled = true; }
524 if (craftBatchAllButton)
525 { craftBatchAllButton.disabled = true; }
526 return;
527 }
528 const slotsSnapshot = slots ?? getInventorySlots?.() ?? [];
529 const craftOpts = { dyeSlotIndex };
530 if (canStartCraft(slotsSnapshot, recipe, skill, craftOpts))
531 {
532 statusEl.textContent = "";
533 craftButton.disabled = false;
534 if (craftBatchButton)
535 { craftBatchButton.disabled = !batchVisible; }
536 if (craftBatchAllButton)
537 { craftBatchAllButton.disabled = !batchVisible; }
538 return;
539 }
540 if (!hasRecipeInputs(slotsSnapshot, recipe))
541 {
542 statusEl.textContent = "Missing materials.";
543 }
544 else if (recipe.consumeDye && dyeSlotIndex != null)
545 {
546 statusEl.textContent = "Not enough bag space (need room for the result or a partially used dye).";
547 }
548 else
549 {
550 statusEl.textContent = "Not enough bag space for the result.";
551 }
552 craftButton.disabled = true;
553 if (craftBatchButton)
554 { craftBatchButton.disabled = true; }
555 if (craftBatchAllButton)
556 { craftBatchAllButton.disabled = true; }
557 }
558
559 function openDyePicker ()
560 {
561 if (!isTailorStation())
562 { return; }
563 const slots = getInventorySlots?.() ?? [];
564 dyeGrid.replaceChildren();
565 let found = false;
566 slots.forEach((stack, index) =>
567 {
568 if (!stack || stack.itemId !== ItemId.dye)
569 { return; }
570 found = true;
571 const cell = document.createElement("button");
572 cell.type = "button";
573 cell.className = "craft-recipe-cell craft-dye-cell";
574 cell.title = "Dye";
575 const img = document.createElement("img");
576 applyItemIcon(img, stack, itemAssetPathForStack(stack));
577 img.alt = "Dye";
578 cell.append(img);
579 cell.addEventListener("click", () =>
580 {
581 dyeSlotIndex = index;
582 closeDyePicker();
583 renderDetail();
584 });
585 dyeGrid.append(cell);
586 });
587 if (!found)
588 {
589 const empty = document.createElement("p");
590 empty.className = "hint";
591 empty.textContent = "No dyes in your inventory.";
592 dyeGrid.append(empty);
593 }
594 dyePanel.hidden = false;
595 dyeBackdrop.hidden = false;
596 }
597
598 function closeDyePicker ()
599 {
600 dyePanel.hidden = true;
601 dyeBackdrop.hidden = true;
602 }
603
604 function startBatchCraft ()
605 {
606 const raw = window.prompt("How many?", "1");
607 if (raw == null)
608 { return; }
609 const count = Number.parseInt(raw, 10);
610 if (!Number.isFinite(count) || count < 1)
611 { return; }
612 startCraft({ batchCount: count });
613 }
614
615 function startCraft (options = {})
616 {
617 const recipe = activeRecipe();
618 if (!recipe || crafting)
619 { return; }
620 const slots = getInventorySlots?.() ?? [];
621 if (!canStartCraft(slots, recipe, stationSkillLevel(), { dyeSlotIndex }))
622 {
623 renderDetail();
624 return;
625 }
626 crafting = true;
627 craftButton.disabled = true;
628 if (craftBatchButton)
629 { craftBatchButton.disabled = true; }
630 if (craftBatchAllButton)
631 { craftBatchAllButton.disabled = true; }
632 progressWrap.classList.add("is-active");
633 progressFill.style.width = "0%";
634 statusEl.textContent = options.batchAll
635 ? "Crafting all…"
636 : options.batchCount > 1
637 ? `Crafting ${options.batchCount}…`
638 : "Crafting…";
639 craftStartedAt = performance.now();
640 const durationMs = craftDurationMs(recipe, CRAFT_DURATION_MS);
641 const payload = {
642 type: MessageType.startCraft,
643 stationId,
644 recipeId: selectedRecipeId
645 };
646 if (options.batchCount != null)
647 { payload.batchCount = options.batchCount | 0; }
648 if (options.batchAll)
649 { payload.batchAll = true; }
650 if (isTailorStation())
651 {
652 payload.clothTier = selectedMaterial;
653 payload.dyeSlotIndex = dyeSlotIndex;
654 }
655 socket.send(payload);
656 animateProgress(durationMs);
657 craftTimer = window.setTimeout(() => finishCraft(true), durationMs);
658 }
659
660 function animateProgress (durationMs)
661 {
662 const tick = (now) =>
663 {
664 if (!crafting)
665 { return; }
666 const elapsed = now - craftStartedAt;
667 const pct = Math.min(100, (elapsed / durationMs) * 100);
668 progressFill.style.width = `${pct}%`;
669 if (pct < 100)
670 { craftAnimFrame = requestAnimationFrame(tick); }
671 };
672 craftAnimFrame = requestAnimationFrame(tick);
673 }
674
675 function stopCraftAnimation ()
676 {
677 if (craftTimer != null)
678 {
679 clearTimeout(craftTimer);
680 craftTimer = null;
681 }
682 if (craftAnimFrame != null)
683 {
684 cancelAnimationFrame(craftAnimFrame);
685 craftAnimFrame = null;
686 }
687 crafting = false;
688 progressWrap.classList.remove("is-active");
689 progressFill.style.width = "0%";
690 }
691
692 function finishCraft (timedOut)
693 {
694 stopCraftAnimation();
695 if (timedOut)
696 {
697 statusEl.textContent = "Waiting for server…";
698 }
699 renderDetail();
700 }
701
702 function openStation (nextStationId)
703 {
704 const def = craftingStationDefinition(nextStationId);
705 if (!def)
706 { return; }
707 stationId = nextStationId;
708 recipes = recipesForStation(nextStationId);
709 const { fallback } = materialOptionsForStation();
710 selectedMaterial = fallback;
711 dyeSlotIndex = null;
712 fillMaterialTiers();
713 const first = groupedDisplayRecipes()[0];
714 selectedCraftGroup = first?.group ?? null;
715 if (usesCraftGroups())
716 { syncSelectedRecipeFromMaterial(); }
717 else
718 { selectedRecipeId = first?.recipe?.recipeId ?? recipes[0]?.recipeId ?? null; }
719 stationName.textContent = def.displayName;
720 open = true;
721 panel.hidden = false;
722 backdrop.hidden = false;
723 statusEl.textContent = recipes.length
724 ? "Select a recipe."
725 : "No recipes defined for this station yet.";
726 renderRecipeGrid();
727 renderDetail();
728 }
729
730 function close ()
731 {
732 if (crafting)
733 {
734 socket.send({ type: MessageType.cancelCraft });
735 stopCraftAnimation();
736 }
737 closeDyePicker();
738 open = false;
739 stationId = null;
740 recipes = [];
741 selectedRecipeId = null;
742 selectedCraftGroup = null;
743 dyeSlotIndex = null;
744 panel.hidden = true;
745 backdrop.hidden = true;
746 detailEmpty.hidden = false;
747 detailBody.hidden = true;
748 statusEl.textContent = "";
749 }
750
751 function handleCraftResult (message)
752 {
753 if (!open || message.recipeId !== selectedRecipeId)
754 { return; }
755 if (message.ok && message.continuing)
756 {
757 const recipe = activeRecipe();
758 if (!recipe)
759 {
760 stopCraftAnimation();
761 renderDetail();
762 return;
763 }
764 crafting = true;
765 craftButton.disabled = true;
766 if (craftBatchButton)
767 { craftBatchButton.disabled = true; }
768 if (craftBatchAllButton)
769 { craftBatchAllButton.disabled = true; }
770 progressWrap.classList.add("is-active");
771 progressFill.style.width = "0%";
772 statusEl.textContent = "Crafting…";
773 craftStartedAt = performance.now();
774 const durationMs = craftDurationMs(recipe, CRAFT_DURATION_MS);
775 if (craftTimer != null)
776 { clearTimeout(craftTimer); }
777 if (craftAnimFrame != null)
778 {
779 cancelAnimationFrame(craftAnimFrame);
780 craftAnimFrame = null;
781 }
782 animateProgress(durationMs);
783 craftTimer = window.setTimeout(() => finishCraft(true), durationMs);
784 renderDetail();
785 return;
786 }
787 stopCraftAnimation();
788 if (message.ok)
789 {
790 statusEl.textContent = message.burned
791 ? "The food burned."
792 : "Craft complete.";
793 }
794 else
795 {
796 statusEl.textContent = message.error ?? "Could not craft.";
797 }
798 renderDetail();
799 }
800
801 return {
802 openStation,
803 close,
804 refresh,
805 handleCraftResult,
806 isOpen ()
807 {
808 return open;
809 },
810 isBlocking ()
811 {
812 if (!open)
813 { return false; }
814 if (backdrop && !backdrop.hidden)
815 { return true; }
816 const x = GameInput.mousePosition.x;
817 const y = GameInput.mousePosition.y;
818 const box = panel.getBoundingClientRect();
819 return x >= box.left && x < box.right && y >= box.top && y < box.bottom;
820 },
821 reset ()
822 {
823 close();
824 }
825 };
826}