BlueGit

timfa questward

Files

questward / client / src / play / crafting.js

crafting.js

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