BlueGit

timfa questward

Files

questward / client / src / play / crafting.js

crafting.js

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