BlueGit

timfa questward

Files

questward / client / src / play / crafting.js

crafting.js

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