BlueGit

timfa questward

Files

questward / client / src / play / crafting.js

crafting.js

crafting.js 12.8 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 if (canStartCraft(slotsSnapshot, recipe, skill))
273 {
274 statusEl.textContent = "";
275 craftButton.disabled = false;
276 return;
277 }
278 if (!hasRecipeInputs(slotsSnapshot, recipe))
279 {
280 statusEl.textContent = "Missing materials.";
281 }
282 else
283 {
284 statusEl.textContent = "Not enough bag space for the result.";
285 }
286 craftButton.disabled = true;
287 }
288
289 function openDyePicker ()
290 {
291 const slots = getInventorySlots?.() ?? [];
292 dyeGrid.replaceChildren();
293 let found = false;
294 slots.forEach((stack, index) =>
295 {
296 if (!stack || stack.itemId !== ItemId.dye)
297 { return; }
298 found = true;
299 const cell = document.createElement("button");
300 cell.type = "button";
301 cell.className = "craft-recipe-cell";
302 const img = document.createElement("img");
303 applyItemIcon(img, stack, itemAssetPathForStack(stack));
304 const label = document.createElement("span");
305 label.className = "craft-recipe-name";
306 label.textContent = itemDisplayName(stack);
307 cell.append(img, label);
308 cell.addEventListener("click", () =>
309 {
310 dyeSlotIndex = index;
311 closeDyePicker();
312 renderDetail();
313 });
314 dyeGrid.append(cell);
315 });
316 if (!found)
317 {
318 const empty = document.createElement("p");
319 empty.className = "hint";
320 empty.textContent = "No dyes in your inventory.";
321 dyeGrid.append(empty);
322 }
323 dyePanel.hidden = false;
324 dyeBackdrop.hidden = false;
325 }
326
327 function closeDyePicker ()
328 {
329 dyePanel.hidden = true;
330 dyeBackdrop.hidden = true;
331 }
332
333 function startCraft ()
334 {
335 const recipe = activeRecipe();
336 if (!recipe || crafting)
337 { return; }
338 const slots = getInventorySlots?.() ?? [];
339 if (!canStartCraft(slots, recipe, stationSkillLevel()))
340 {
341 renderDetail();
342 return;
343 }
344 crafting = true;
345 craftButton.disabled = true;
346 progressWrap.hidden = false;
347 progressFill.style.width = "0%";
348 statusEl.textContent = "Crafting…";
349 craftStartedAt = performance.now();
350 const durationMs = craftDurationMs(recipe, CRAFT_DURATION_MS);
351 const payload = {
352 type: MessageType.startCraft,
353 stationId,
354 recipeId: selectedRecipeId
355 };
356 if (isTailorStation())
357 {
358 payload.clothTier = clothTier;
359 payload.dyeSlotIndex = dyeSlotIndex;
360 }
361 socket.send(payload);
362 animateProgress(durationMs);
363 craftTimer = window.setTimeout(() => finishCraft(true), durationMs);
364 }
365
366 function animateProgress (durationMs)
367 {
368 const tick = (now) =>
369 {
370 if (!crafting)
371 { return; }
372 const elapsed = now - craftStartedAt;
373 const pct = Math.min(100, (elapsed / durationMs) * 100);
374 progressFill.style.width = `${pct}%`;
375 if (pct < 100)
376 { craftAnimFrame = requestAnimationFrame(tick); }
377 };
378 craftAnimFrame = requestAnimationFrame(tick);
379 }
380
381 function stopCraftAnimation ()
382 {
383 if (craftTimer != null)
384 {
385 clearTimeout(craftTimer);
386 craftTimer = null;
387 }
388 if (craftAnimFrame != null)
389 {
390 cancelAnimationFrame(craftAnimFrame);
391 craftAnimFrame = null;
392 }
393 crafting = false;
394 progressWrap.hidden = true;
395 progressFill.style.width = "0%";
396 }
397
398 function finishCraft (timedOut)
399 {
400 stopCraftAnimation();
401 if (timedOut)
402 {
403 statusEl.textContent = "Waiting for server…";
404 }
405 renderDetail();
406 }
407
408 function openStation (nextStationId)
409 {
410 const def = craftingStationDefinition(nextStationId);
411 if (!def)
412 { return; }
413 stationId = nextStationId;
414 recipes = recipesForStation(nextStationId);
415 selectedRecipeId = recipes[0]?.recipeId ?? null;
416 clothTier = ClothTier.cotton;
417 dyeSlotIndex = null;
418 fillClothTier();
419 stationName.textContent = def.displayName;
420 open = true;
421 panel.hidden = false;
422 backdrop.hidden = false;
423 statusEl.textContent = recipes.length
424 ? "Select a recipe."
425 : "No recipes defined for this station yet.";
426 renderRecipeGrid();
427 renderDetail();
428 }
429
430 function close ()
431 {
432 if (crafting)
433 {
434 socket.send({ type: MessageType.cancelCraft });
435 stopCraftAnimation();
436 }
437 closeDyePicker();
438 open = false;
439 stationId = null;
440 recipes = [];
441 selectedRecipeId = null;
442 dyeSlotIndex = null;
443 panel.hidden = true;
444 backdrop.hidden = true;
445 detailEmpty.hidden = false;
446 detailBody.hidden = true;
447 statusEl.textContent = "";
448 }
449
450 function handleCraftResult (message)
451 {
452 if (!open || message.recipeId !== selectedRecipeId)
453 { return; }
454 stopCraftAnimation();
455 if (message.ok)
456 {
457 statusEl.textContent = message.burned
458 ? "The food burned."
459 : "Craft complete.";
460 }
461 else
462 {
463 statusEl.textContent = message.error ?? "Could not craft.";
464 }
465 renderDetail();
466 }
467
468 return {
469 openStation,
470 close,
471 refresh,
472 handleCraftResult,
473 isOpen ()
474 {
475 return open;
476 },
477 isBlocking ()
478 {
479 if (!open)
480 { return false; }
481 if (backdrop && !backdrop.hidden)
482 { return true; }
483 const x = GameInput.mousePosition.x;
484 const y = GameInput.mousePosition.y;
485 const box = panel.getBoundingClientRect();
486 return x >= box.left && x < box.right && y >= box.top && y < box.bottom;
487 },
488 reset ()
489 {
490 close();
491 }
492 };
493}