BlueGit

timfa questward

Files

questward / client / src / play / crafting.js

crafting.js

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