BlueGit

timfa questward

Files

questward / client / src / play / crafting.js

crafting.js

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