BlueGit

timfa questward

Files

questward / client / src / play / crafting.js

crafting.js

crafting.js 8.5 KiB Download Raw
1import {
2 itemDefinition,
3 itemDisplayName,
4 itemAssetPathForStack,
5 formatQuantity
6} from "/shared/definitions/items.js";
7import { craftingStationDefinition } from "/shared/definitions/craftingStations.js";
8import {
9 CRAFT_DURATION_MS,
10 canStartCraft,
11 countItemInSlots,
12 hasRecipeInputs,
13 recipesForStation
14} from "/shared/crafting/recipes.js";
15import { craftDurationMs } from "/shared/definitions/gathering.js";
16import { applyItemIcon } from "../render/potionIcon.js";
17
18export function initCrafting ({
19 socket,
20 MessageType,
21 getInventorySlots,
22 getSkillLevel
23})
24{
25 const backdrop = document.getElementById("craft-backdrop");
26 const panel = document.getElementById("craft-panel");
27 const stationName = document.getElementById("craft-station-name");
28 const recipeGrid = document.getElementById("craft-recipe-grid");
29 const detailEmpty = document.getElementById("craft-detail-empty");
30 const detailBody = document.getElementById("craft-detail-body");
31 const outputImg = document.getElementById("craft-output-img");
32 const outputName = document.getElementById("craft-output-name");
33 const inputsList = document.getElementById("craft-inputs");
34 const statusEl = document.getElementById("craft-status");
35 const progressWrap = document.getElementById("craft-progress");
36 const progressFill = document.getElementById("craft-progress-fill");
37 const craftButton = document.getElementById("craft-button");
38
39 let open = false;
40 let stationId = null;
41 let recipes = [];
42 let selectedRecipeId = null;
43 let crafting = false;
44 let craftTimer = null;
45 let craftAnimFrame = null;
46 let craftStartedAt = 0;
47
48 document.getElementById("craft-close").addEventListener("click", () => close());
49 backdrop.addEventListener("click", () => close());
50 craftButton.addEventListener("click", () => startCraft());
51
52 function selectedRecipe ()
53 {
54 return recipes.find((recipe) => recipe.recipeId === selectedRecipeId) ?? null;
55 }
56
57 function stationSkillLevel ()
58 {
59 const def = craftingStationDefinition(stationId);
60 return getSkillLevel?.(def?.skillId) ?? 1;
61 }
62
63 function refresh ()
64 {
65 if (!open)
66 { return; }
67 renderRecipeGrid();
68 renderDetail();
69 }
70
71 function renderRecipeGrid ()
72 {
73 recipeGrid.replaceChildren();
74 for (const recipe of recipes)
75 {
76 recipeGrid.append(renderRecipeCell(recipe));
77 }
78 }
79
80 function renderRecipeCell (recipe)
81 {
82 const def = itemDefinition(recipe.output.itemId);
83 const stack = { itemId: recipe.output.itemId, quantity: recipe.output.quantity | 0 || 1 };
84 const cell = document.createElement("button");
85 cell.type = "button";
86 cell.className = "craft-recipe-cell";
87 if (recipe.recipeId === selectedRecipeId)
88 { cell.classList.add("selected"); }
89
90 const img = document.createElement("img");
91 img.alt = def?.displayName ?? "Item";
92 applyItemIcon(img, stack, itemAssetPathForStack(stack));
93
94 const label = document.createElement("span");
95 label.className = "craft-recipe-name";
96 label.textContent = def?.displayName ?? "Item";
97
98 cell.append(img, label);
99 cell.addEventListener("click", () =>
100 {
101 if (crafting)
102 { return; }
103 selectedRecipeId = recipe.recipeId;
104 renderRecipeGrid();
105 renderDetail();
106 });
107 return cell;
108 }
109
110 function renderDetail ()
111 {
112 const recipe = selectedRecipe();
113 if (!recipe)
114 {
115 detailEmpty.hidden = false;
116 detailBody.hidden = true;
117 return;
118 }
119 detailEmpty.hidden = true;
120 detailBody.hidden = false;
121
122 const outputStack = {
123 itemId: recipe.output.itemId,
124 quantity: Math.max(1, recipe.output.quantity | 0 || 1)
125 };
126 applyItemIcon(outputImg, outputStack, itemAssetPathForStack(outputStack));
127 outputImg.alt = itemDisplayName(outputStack);
128 const qtySuffix = outputStack.quantity > 1 ? ` ×${formatQuantity(outputStack.quantity)}` : "";
129 outputName.textContent = `${itemDisplayName(outputStack)}${qtySuffix}`;
130
131 inputsList.replaceChildren();
132 const slots = getInventorySlots?.() ?? [];
133 for (const input of recipe.inputs ?? [])
134 {
135 inputsList.append(renderInputRow(input, slots));
136 }
137
138 updateCraftState(slots, recipe);
139 }
140
141 function renderInputRow (input, slots)
142 {
143 const need = input.quantity | 0;
144 const have = countItemInSlots(slots, input.itemId);
145 const stack = { itemId: input.itemId, quantity: need };
146 const row = document.createElement("li");
147 row.className = "craft-input-row";
148 if (have < need)
149 { row.classList.add("short"); }
150
151 const img = document.createElement("img");
152 img.alt = itemDisplayName(stack);
153 applyItemIcon(img, stack, itemAssetPathForStack(stack));
154
155 const text = document.createElement("span");
156 text.textContent = `${itemDisplayName(stack)} — ${formatQuantity(have)} / ${formatQuantity(need)}`;
157 row.append(img, text);
158 return row;
159 }
160
161 function updateCraftState (slots, recipe)
162 {
163 if (crafting)
164 {
165 craftButton.disabled = true;
166 return;
167 }
168 const skill = stationSkillLevel();
169 const minLevel = recipe.minSkillLevel | 0 || 1;
170 if (skill < minLevel)
171 {
172 statusEl.textContent = `Requires skill level ${minLevel} (you have ${skill}).`;
173 craftButton.disabled = true;
174 return;
175 }
176 const slotsSnapshot = slots ?? getInventorySlots?.() ?? [];
177 if (canStartCraft(slotsSnapshot, recipe, skill))
178 {
179 statusEl.textContent = "";
180 craftButton.disabled = false;
181 return;
182 }
183 if (!hasRecipeInputs(slotsSnapshot, recipe))
184 {
185 statusEl.textContent = "Missing materials.";
186 }
187 else
188 {
189 statusEl.textContent = "Not enough bag space for the result.";
190 }
191 craftButton.disabled = true;
192 }
193
194 function startCraft ()
195 {
196 const recipe = selectedRecipe();
197 if (!recipe || crafting)
198 { return; }
199 const slots = getInventorySlots?.() ?? [];
200 if (!canStartCraft(slots, recipe, stationSkillLevel()))
201 {
202 renderDetail();
203 return;
204 }
205 crafting = true;
206 craftButton.disabled = true;
207 progressWrap.hidden = false;
208 progressFill.style.width = "0%";
209 statusEl.textContent = "Crafting…";
210 craftStartedAt = performance.now();
211 const durationMs = craftDurationMs(recipe, CRAFT_DURATION_MS);
212 socket.send({
213 type: MessageType.startCraft,
214 stationId,
215 recipeId: recipe.recipeId
216 });
217 animateProgress(durationMs);
218 craftTimer = window.setTimeout(() => finishCraft(true), durationMs);
219 }
220
221 function animateProgress (durationMs)
222 {
223 const tick = (now) =>
224 {
225 if (!crafting)
226 { return; }
227 const elapsed = now - craftStartedAt;
228 const pct = Math.min(100, (elapsed / durationMs) * 100);
229 progressFill.style.width = `${pct}%`;
230 if (pct < 100)
231 { craftAnimFrame = requestAnimationFrame(tick); }
232 };
233 craftAnimFrame = requestAnimationFrame(tick);
234 }
235
236 function stopCraftAnimation ()
237 {
238 if (craftTimer != null)
239 {
240 clearTimeout(craftTimer);
241 craftTimer = null;
242 }
243 if (craftAnimFrame != null)
244 {
245 cancelAnimationFrame(craftAnimFrame);
246 craftAnimFrame = null;
247 }
248 crafting = false;
249 progressWrap.hidden = true;
250 progressFill.style.width = "0%";
251 }
252
253 function finishCraft (timedOut)
254 {
255 stopCraftAnimation();
256 if (timedOut)
257 {
258 statusEl.textContent = "Waiting for server…";
259 }
260 renderDetail();
261 }
262
263 function openStation (nextStationId)
264 {
265 const def = craftingStationDefinition(nextStationId);
266 if (!def)
267 { return; }
268 stationId = nextStationId;
269 recipes = recipesForStation(nextStationId);
270 selectedRecipeId = recipes[0]?.recipeId ?? null;
271 stationName.textContent = def.displayName;
272 open = true;
273 panel.hidden = false;
274 backdrop.hidden = false;
275 statusEl.textContent = recipes.length
276 ? "Select a recipe."
277 : "No recipes defined for this station yet.";
278 renderRecipeGrid();
279 renderDetail();
280 }
281
282 function close ()
283 {
284 if (crafting)
285 {
286 socket.send({ type: MessageType.cancelCraft });
287 stopCraftAnimation();
288 }
289 open = false;
290 stationId = null;
291 recipes = [];
292 selectedRecipeId = null;
293 panel.hidden = true;
294 backdrop.hidden = true;
295 detailEmpty.hidden = false;
296 detailBody.hidden = true;
297 statusEl.textContent = "";
298 }
299
300 function handleCraftResult (message)
301 {
302 if (!open || message.recipeId !== selectedRecipeId)
303 { return; }
304 stopCraftAnimation();
305 if (message.ok)
306 {
307 statusEl.textContent = message.burned
308 ? "The food burned."
309 : "Craft complete.";
310 }
311 else
312 {
313 statusEl.textContent = message.error ?? "Could not craft.";
314 }
315 renderDetail();
316 }
317
318 return {
319 openStation,
320 close,
321 refresh,
322 handleCraftResult,
323 isOpen ()
324 {
325 return open;
326 },
327 isBlocking ()
328 {
329 if (!open)
330 { return false; }
331 if (backdrop && !backdrop.hidden)
332 { return true; }
333 const x = GameInput.mousePosition.x;
334 const y = GameInput.mousePosition.y;
335 const box = panel.getBoundingClientRect();
336 return x >= box.left && x < box.right && y >= box.top && y < box.bottom;
337 },
338 reset ()
339 {
340 close();
341 }
342 };
343}