BlueGit

timfa questward

Files

questward / client / src / play / crafting.js

crafting.js

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