BlueGit

timfa questward

Files

questward / client / src / play / crafting.js

crafting.js

crafting.js 12.9 KiB Download Raw
1import {
2 itemDefinition,
3 itemDisplayName,
4 itemAssetPathForStack,
5 formatQuantity,
6 ItemId
7} from "/shared/definitions/items.js";
8import { craftingStationDefinition, CraftingStationId } from "/shared/definitions/craftingStations.js";
9import {
10 CRAFT_DURATION_MS,
11 canStartCraft,
12 countItemInSlots,
13 hasRecipeInputs,
14 recipesForStation
15} from "/shared/crafting/recipes.js";
16import { resolveTailorCraft } from "/shared/crafting/tailor.js";
17import { CLOTH_TIER_ORDER, CLOTH_DISPLAY_NAME, ClothTier } from "/shared/definitions/materialTiers.js";
18import { craftDurationMs } from "/shared/definitions/gathering.js";
19import { applyItemIcon } from "../render/potionIcon.js";
20
21export function initCrafting ({
22 socket,
23 MessageType,
24 getInventorySlots,
25 getSkillLevel
26})
27{
28 const backdrop = document.getElementById("craft-backdrop");
29 const panel = document.getElementById("craft-panel");
30 const stationName = document.getElementById("craft-station-name");
31 const recipeGrid = document.getElementById("craft-recipe-grid");
32 const detailEmpty = document.getElementById("craft-detail-empty");
33 const detailBody = document.getElementById("craft-detail-body");
34 const tailorControls = document.getElementById("craft-tailor-controls");
35 const clothTierSelect = document.getElementById("craft-cloth-tier");
36 const dyePickBtn = document.getElementById("craft-dye-pick");
37 const dyeClearBtn = document.getElementById("craft-dye-clear");
38 const dyePreview = document.getElementById("craft-dye-preview");
39 const outputImg = document.getElementById("craft-output-img");
40 const outputName = document.getElementById("craft-output-name");
41 const inputsList = document.getElementById("craft-inputs");
42 const statusEl = document.getElementById("craft-status");
43 const progressWrap = document.getElementById("craft-progress");
44 const progressFill = document.getElementById("craft-progress-fill");
45 const craftButton = document.getElementById("craft-button");
46 const dyeBackdrop = document.getElementById("dye-picker-backdrop");
47 const dyePanel = document.getElementById("dye-picker-panel");
48 const dyeGrid = document.getElementById("dye-picker-grid");
49
50 let open = false;
51 let stationId = null;
52 let recipes = [];
53 let selectedRecipeId = null;
54 let clothTier = ClothTier.cotton;
55 let dyeSlotIndex = null;
56 let crafting = false;
57 let craftTimer = null;
58 let craftAnimFrame = null;
59 let craftStartedAt = 0;
60
61 document.getElementById("craft-close").addEventListener("click", () => close());
62 backdrop.addEventListener("click", () => close());
63 craftButton.addEventListener("click", () => startCraft());
64 clothTierSelect?.addEventListener("change", () =>
65 {
66 clothTier = clothTierSelect.value || ClothTier.cotton;
67 renderDetail();
68 });
69 dyePickBtn?.addEventListener("click", () => openDyePicker());
70 dyeClearBtn?.addEventListener("click", () =>
71 {
72 dyeSlotIndex = null;
73 renderDetail();
74 });
75 document.getElementById("dye-picker-close")?.addEventListener("click", () => closeDyePicker());
76 dyeBackdrop?.addEventListener("click", () => closeDyePicker());
77
78 function isTailorStation ()
79 {
80 return stationId === CraftingStationId.tailorBench;
81 }
82
83 function selectedRecipe ()
84 {
85 return recipes.find((recipe) => recipe.recipeId === selectedRecipeId) ?? null;
86 }
87
88 function stationSkillLevel ()
89 {
90 const def = craftingStationDefinition(stationId);
91 return getSkillLevel?.(def?.skillId) ?? 1;
92 }
93
94 function activeRecipe ()
95 {
96 const base = selectedRecipe();
97 if (!base)
98 { return null; }
99 if (!base.tailorTemplate)
100 { return base; }
101 const slots = getInventorySlots?.() ?? [];
102 const dyeStack = dyeSlotIndex != null ? slots[dyeSlotIndex] : null;
103 const resolved = resolveTailorCraft({
104 templateId: base.tailorTemplate,
105 clothTier,
106 dyeStack
107 });
108 return resolved.ok ? resolved.recipe : base;
109 }
110
111 function refresh ()
112 {
113 if (!open)
114 { return; }
115 renderRecipeGrid();
116 renderDetail();
117 }
118
119 function fillClothTier ()
120 {
121 if (!clothTierSelect)
122 { return; }
123 clothTierSelect.replaceChildren();
124 for (const tier of CLOTH_TIER_ORDER)
125 {
126 const option = document.createElement("option");
127 option.value = tier;
128 option.textContent = CLOTH_DISPLAY_NAME[tier] ?? tier;
129 clothTierSelect.append(option);
130 }
131 clothTierSelect.value = clothTier;
132 }
133
134 function renderRecipeGrid ()
135 {
136 recipeGrid.replaceChildren();
137 for (const recipe of recipes)
138 {
139 recipeGrid.append(renderRecipeCell(recipe));
140 }
141 }
142
143 function renderRecipeCell (recipe)
144 {
145 const def = itemDefinition(recipe.output.itemId);
146 const stack = { itemId: recipe.output.itemId, quantity: recipe.output.quantity | 0 || 1 };
147 const cell = document.createElement("button");
148 cell.type = "button";
149 cell.className = "craft-recipe-cell";
150 if (recipe.recipeId === selectedRecipeId)
151 { cell.classList.add("selected"); }
152
153 const img = document.createElement("img");
154 img.alt = def?.displayName ?? "Item";
155 applyItemIcon(img, stack, itemAssetPathForStack(stack));
156
157 const label = document.createElement("span");
158 label.className = "craft-recipe-name";
159 label.textContent = recipe.tailorTemplate
160 ? (def?.displayName?.replace(/^Cotton\s+/i, "") ?? "Garment")
161 : (def?.displayName ?? "Item");
162
163 cell.append(img, label);
164 cell.addEventListener("click", () =>
165 {
166 if (crafting)
167 { return; }
168 selectedRecipeId = recipe.recipeId;
169 renderRecipeGrid();
170 renderDetail();
171 });
172 return cell;
173 }
174
175 function renderDetail ()
176 {
177 const recipe = activeRecipe();
178 if (!recipe)
179 {
180 detailEmpty.hidden = false;
181 detailBody.hidden = true;
182 return;
183 }
184 detailEmpty.hidden = true;
185 detailBody.hidden = false;
186
187 if (tailorControls)
188 { tailorControls.hidden = !isTailorStation(); }
189
190 const outputStack = {
191 itemId: recipe.output.itemId,
192 quantity: Math.max(1, recipe.output.quantity | 0 || 1),
193 ...(recipe.dyeColor ? { instance: { kind: "clothing", dyeColor: recipe.dyeColor } } : {})
194 };
195 applyItemIcon(outputImg, outputStack, itemAssetPathForStack(outputStack));
196 outputImg.alt = itemDisplayName(outputStack);
197 const qtySuffix = outputStack.quantity > 1 ? ` ×${formatQuantity(outputStack.quantity)}` : "";
198 outputName.textContent = `${itemDisplayName(outputStack)}${qtySuffix}`;
199
200 inputsList.replaceChildren();
201 const slots = getInventorySlots?.() ?? [];
202 for (const input of recipe.inputs ?? [])
203 {
204 inputsList.append(renderInputRow(input, slots));
205 }
206 if (recipe.consumeDye)
207 {
208 const dye = dyeSlotIndex != null ? slots[dyeSlotIndex] : null;
209 const row = document.createElement("li");
210 row.className = "craft-input-row";
211 row.textContent = dye
212 ? `Dye — 1 use (${dye.instance?.fillLevel ?? "?"}/5)`
213 : "Dye — none selected";
214 inputsList.append(row);
215 }
216
217 if (dyePreview && dyeClearBtn)
218 {
219 const dye = dyeSlotIndex != null ? slots[dyeSlotIndex] : null;
220 if (dye?.itemId === ItemId.dye)
221 {
222 dyePreview.hidden = false;
223 dyeClearBtn.hidden = false;
224 applyItemIcon(dyePreview, dye, itemAssetPathForStack(dye));
225 }
226 else
227 {
228 dyePreview.hidden = true;
229 dyeClearBtn.hidden = true;
230 }
231 }
232
233 updateCraftState(slots, recipe);
234 }
235
236 function renderInputRow (input, slots)
237 {
238 const need = input.quantity | 0;
239 const have = countItemInSlots(slots, input.itemId);
240 const stack = { itemId: input.itemId, quantity: need };
241 const row = document.createElement("li");
242 row.className = "craft-input-row";
243 if (have < need)
244 { row.classList.add("short"); }
245
246 const img = document.createElement("img");
247 img.alt = itemDisplayName(stack);
248 applyItemIcon(img, stack, itemAssetPathForStack(stack));
249
250 const text = document.createElement("span");
251 text.textContent = `${itemDisplayName(stack)} — ${formatQuantity(have)} / ${formatQuantity(need)}`;
252 row.append(img, text);
253 return row;
254 }
255
256 function updateCraftState (slots, recipe)
257 {
258 if (crafting)
259 {
260 craftButton.disabled = true;
261 return;
262 }
263 const skill = stationSkillLevel();
264 const minLevel = recipe.minSkillLevel | 0 || 1;
265 if (skill < minLevel)
266 {
267 statusEl.textContent = `Requires skill level ${minLevel} (you have ${skill}).`;
268 craftButton.disabled = true;
269 return;
270 }
271 const slotsSnapshot = slots ?? getInventorySlots?.() ?? [];
272 const craftOpts = { dyeSlotIndex };
273 if (canStartCraft(slotsSnapshot, recipe, skill, craftOpts))
274 {
275 statusEl.textContent = "";
276 craftButton.disabled = false;
277 return;
278 }
279 if (!hasRecipeInputs(slotsSnapshot, recipe))
280 {
281 statusEl.textContent = "Missing materials.";
282 }
283 else if (recipe.consumeDye && dyeSlotIndex != null)
284 {
285 statusEl.textContent = "Not enough bag space (need room for the result or a partially used dye).";
286 }
287 else
288 {
289 statusEl.textContent = "Not enough bag space for the result.";
290 }
291 craftButton.disabled = true;
292 }
293
294 function openDyePicker ()
295 {
296 const slots = getInventorySlots?.() ?? [];
297 dyeGrid.replaceChildren();
298 let found = false;
299 slots.forEach((stack, index) =>
300 {
301 if (!stack || stack.itemId !== ItemId.dye)
302 { return; }
303 found = true;
304 const cell = document.createElement("button");
305 cell.type = "button";
306 cell.className = "craft-recipe-cell craft-dye-cell";
307 cell.title = "Dye";
308 const img = document.createElement("img");
309 applyItemIcon(img, stack, itemAssetPathForStack(stack));
310 img.alt = "Dye";
311 cell.append(img);
312 cell.addEventListener("click", () =>
313 {
314 dyeSlotIndex = index;
315 closeDyePicker();
316 renderDetail();
317 });
318 dyeGrid.append(cell);
319 });
320 if (!found)
321 {
322 const empty = document.createElement("p");
323 empty.className = "hint";
324 empty.textContent = "No dyes in your inventory.";
325 dyeGrid.append(empty);
326 }
327 dyePanel.hidden = false;
328 dyeBackdrop.hidden = false;
329 }
330
331 function closeDyePicker ()
332 {
333 dyePanel.hidden = true;
334 dyeBackdrop.hidden = true;
335 }
336
337 function startCraft ()
338 {
339 const recipe = activeRecipe();
340 if (!recipe || crafting)
341 { return; }
342 const slots = getInventorySlots?.() ?? [];
343 if (!canStartCraft(slots, recipe, stationSkillLevel(), { dyeSlotIndex }))
344 {
345 renderDetail();
346 return;
347 }
348 crafting = true;
349 craftButton.disabled = true;
350 progressWrap.hidden = false;
351 progressFill.style.width = "0%";
352 statusEl.textContent = "Crafting…";
353 craftStartedAt = performance.now();
354 const durationMs = craftDurationMs(recipe, CRAFT_DURATION_MS);
355 const payload = {
356 type: MessageType.startCraft,
357 stationId,
358 recipeId: selectedRecipeId
359 };
360 if (isTailorStation())
361 {
362 payload.clothTier = clothTier;
363 payload.dyeSlotIndex = dyeSlotIndex;
364 }
365 socket.send(payload);
366 animateProgress(durationMs);
367 craftTimer = window.setTimeout(() => finishCraft(true), durationMs);
368 }
369
370 function animateProgress (durationMs)
371 {
372 const tick = (now) =>
373 {
374 if (!crafting)
375 { return; }
376 const elapsed = now - craftStartedAt;
377 const pct = Math.min(100, (elapsed / durationMs) * 100);
378 progressFill.style.width = `${pct}%`;
379 if (pct < 100)
380 { craftAnimFrame = requestAnimationFrame(tick); }
381 };
382 craftAnimFrame = requestAnimationFrame(tick);
383 }
384
385 function stopCraftAnimation ()
386 {
387 if (craftTimer != null)
388 {
389 clearTimeout(craftTimer);
390 craftTimer = null;
391 }
392 if (craftAnimFrame != null)
393 {
394 cancelAnimationFrame(craftAnimFrame);
395 craftAnimFrame = null;
396 }
397 crafting = false;
398 progressWrap.hidden = true;
399 progressFill.style.width = "0%";
400 }
401
402 function finishCraft (timedOut)
403 {
404 stopCraftAnimation();
405 if (timedOut)
406 {
407 statusEl.textContent = "Waiting for server…";
408 }
409 renderDetail();
410 }
411
412 function openStation (nextStationId)
413 {
414 const def = craftingStationDefinition(nextStationId);
415 if (!def)
416 { return; }
417 stationId = nextStationId;
418 recipes = recipesForStation(nextStationId);
419 selectedRecipeId = recipes[0]?.recipeId ?? null;
420 clothTier = ClothTier.cotton;
421 dyeSlotIndex = null;
422 fillClothTier();
423 stationName.textContent = def.displayName;
424 open = true;
425 panel.hidden = false;
426 backdrop.hidden = false;
427 statusEl.textContent = recipes.length
428 ? "Select a recipe."
429 : "No recipes defined for this station yet.";
430 renderRecipeGrid();
431 renderDetail();
432 }
433
434 function close ()
435 {
436 if (crafting)
437 {
438 socket.send({ type: MessageType.cancelCraft });
439 stopCraftAnimation();
440 }
441 closeDyePicker();
442 open = false;
443 stationId = null;
444 recipes = [];
445 selectedRecipeId = null;
446 dyeSlotIndex = null;
447 panel.hidden = true;
448 backdrop.hidden = true;
449 detailEmpty.hidden = false;
450 detailBody.hidden = true;
451 statusEl.textContent = "";
452 }
453
454 function handleCraftResult (message)
455 {
456 if (!open || message.recipeId !== selectedRecipeId)
457 { return; }
458 stopCraftAnimation();
459 if (message.ok)
460 {
461 statusEl.textContent = message.burned
462 ? "The food burned."
463 : "Craft complete.";
464 }
465 else
466 {
467 statusEl.textContent = message.error ?? "Could not craft.";
468 }
469 renderDetail();
470 }
471
472 return {
473 openStation,
474 close,
475 refresh,
476 handleCraftResult,
477 isOpen ()
478 {
479 return open;
480 },
481 isBlocking ()
482 {
483 if (!open)
484 { return false; }
485 if (backdrop && !backdrop.hidden)
486 { return true; }
487 const x = GameInput.mousePosition.x;
488 const y = GameInput.mousePosition.y;
489 const box = panel.getBoundingClientRect();
490 return x >= box.left && x < box.right && y >= box.top && y < box.bottom;
491 },
492 reset ()
493 {
494 close();
495 }
496 };
497}