BlueGit

timfa questward

Files

questward / client / src / play / spells.js

spells.js

spells.js 10.8 KiB Download Raw
1/**
2 * Play spells panel: known spells, favourites bar, arm / cast intents.
3 */
4import { spellDefinition, spellMindPowerFromTier, spellMinMagicLevel } from "/shared/definitions/spells.js";
5import { SkillId } from "/shared/definitions/skills.js";
6import { spellMaxHitDisplay, isMagicStaffEquipped, firstFavoriteAttackSpellId } from "/shared/combat/maxHit.js";
7
8export function initSpells ({
9 socket,
10 MessageType,
11 getSkillLevel,
12 getSkillLevels = null,
13 getEquipmentSlots = null,
14 getSettings = null
15} = {})
16{
17 const panel = document.getElementById("spells-panel");
18 const list = document.getElementById("spells-list");
19 const bar = document.getElementById("spell-favorites-bar");
20 const autoCastToggle = document.getElementById("spell-autocast-toggle");
21 let spells = [];
22 /** Server favourite order (spell ids). */
23 let favoriteOrder = [];
24 let autoCast = false;
25 let armedSpellId = null;
26 let dragFromSpellId = null;
27 let suppressNextClick = false;
28
29 document.getElementById("spells-toggle")?.addEventListener("click", () =>
30 {
31 panel.hidden = !panel.hidden;
32 if (!panel.hidden)
33 { refreshCastGates(); }
34 });
35
36 autoCastToggle?.addEventListener("change", () =>
37 {
38 socket.send({
39 type: MessageType.setSpellAutoCast,
40 enabled: autoCastToggle.checked
41 });
42 });
43
44 /** Re-evaluate Magic gates from the latest client skill levels (e.g. after level-up). */
45 function refreshCastGates ()
46 {
47 if (!spells.length)
48 { return; }
49 const magicLevel = Math.max(1, getSkillLevel?.(SkillId.magic) | 0 || 1);
50 let changed = false;
51 for (const spell of spells)
52 {
53 const need = spellMinMagicLevel(spellDefinition(spell.spellId));
54 const ok = magicLevel >= need;
55 if (spell.canCast !== ok || spell.canFavorite !== ok)
56 {
57 spell.canCast = ok;
58 spell.canFavorite = ok;
59 changed = true;
60 }
61 }
62 if (changed || !panel.hidden)
63 { renderList(); }
64 /** Favourites sit outside the panel — always sync so they show after login. */
65 renderBar();
66 }
67
68 function refreshMaxHitDisplay ()
69 {
70 if (!panel.hidden)
71 { renderList(); }
72 renderBar();
73 }
74
75 function disarmLocal ()
76 {
77 if (!armedSpellId)
78 { return; }
79 armedSpellId = null;
80 renderList();
81 renderBar();
82 }
83
84 function syncFavoriteOrder (payload)
85 {
86 if (Array.isArray(payload?.favorites))
87 {
88 favoriteOrder = payload.favorites.filter((id) => typeof id === "string" || typeof id === "number");
89 return;
90 }
91 favoriteOrder = spells.filter((entry) => entry.favorite).map((entry) => entry.spellId);
92 }
93
94 function render (payload)
95 {
96 spells = payload?.spells ?? [];
97 autoCast = !!payload?.autoCast;
98 if (payload?.armedSpellId !== undefined)
99 { armedSpellId = payload.armedSpellId; }
100 if (autoCastToggle)
101 { autoCastToggle.checked = autoCast; }
102 syncFavoriteOrder(payload);
103 refreshCastGates();
104 }
105
106 function renderList ()
107 {
108 list.replaceChildren();
109 for (const spell of spells)
110 {
111 list.append(renderSpellRow(spell));
112 }
113 }
114
115 function renderSpellRow (spell)
116 {
117 const row = document.createElement("div");
118 row.className = "spell-row";
119 if (spell.spellId === armedSpellId)
120 { row.classList.add("armed"); }
121
122 const icon = document.createElement("img");
123 icon.className = "spell-icon";
124 icon.src = spell.icon;
125 icon.alt = "";
126 icon.loading = "lazy";
127
128 const body = document.createElement("div");
129 body.className = "spell-body";
130
131 const title = document.createElement("div");
132 title.className = "spell-title-row";
133 const name = document.createElement("span");
134 name.className = "spell-title";
135 name.textContent = spell.displayName;
136 const meta = document.createElement("span");
137 meta.className = "spell-meta";
138 const level = spell.tier | 0 || 1;
139 const power = spell.mindPower != null
140 ? spell.mindPower | 0
141 : spellMindPowerFromTier(level);
142 meta.textContent = `Lv. ${level} Pwr: ${power}`;
143 title.append(name, meta);
144
145 const desc = document.createElement("div");
146 desc.className = "spell-desc hint";
147 desc.textContent = spell.description ?? "";
148
149 const maxHit = spellMaxHitDisplay({
150 spellId: spell.spellId,
151 skillLevels: getSkillLevels?.() ?? {},
152 equipmentSlots: getEquipmentSlots?.() ?? {},
153 settings: getSettings?.() ?? null
154 });
155 const maxHitEl = maxHit != null
156 ? (() =>
157 {
158 const line = document.createElement("div");
159 line.className = "spell-max-hit hint";
160 line.textContent = `Max hit: ${maxHit}`;
161 return line;
162 })()
163 : null;
164
165 const actions = document.createElement("div");
166 actions.className = "spell-actions";
167
168 const favorite = document.createElement("button");
169 favorite.type = "button";
170 favorite.className = "spell-favorite-btn";
171 favorite.textContent = spell.favorite ? "★" : "☆";
172 favorite.title = spell.canFavorite
173 ? (spell.favorite ? "Remove from favourites" : "Add to favourites")
174 : "Magic level too low to favourite";
175 favorite.disabled = !spell.canFavorite;
176 favorite.addEventListener("click", () =>
177 {
178 socket.send({ type: MessageType.setSpellFavorite, spellId: spell.spellId });
179 });
180
181 const arm = document.createElement("button");
182 arm.type = "button";
183 arm.className = "spell-arm-btn";
184 arm.textContent = spell.spellId === armedSpellId ? "Armed" : "Arm";
185 arm.disabled = !spell.canCast;
186 arm.addEventListener("click", () =>
187 {
188 if (spell.spellId === armedSpellId)
189 { cancelTargeting(); }
190 else
191 { socket.send({ type: MessageType.armSpell, spellId: spell.spellId }); }
192 });
193
194 actions.append(favorite, arm);
195 body.append(title, desc);
196 if (maxHitEl)
197 { body.append(maxHitEl); }
198 body.append(actions);
199 row.append(icon, body);
200 return row;
201 }
202
203 function orderedFavoriteSpells ()
204 {
205 const byId = new Map(spells.map((entry) => [entry.spellId, entry]));
206 const ordered = [];
207 for (const spellId of favoriteOrder)
208 {
209 const spell = byId.get(spellId);
210 if (spell?.favorite)
211 { ordered.push(spell); }
212 }
213 for (const spell of spells)
214 {
215 if (spell.favorite && !ordered.some((entry) => entry.spellId === spell.spellId))
216 { ordered.push(spell); }
217 }
218 return ordered;
219 }
220
221 function staffAttackFavoriteId ()
222 {
223 if (!isMagicStaffEquipped(getEquipmentSlots?.() ?? {}))
224 { return null; }
225 return firstFavoriteAttackSpellId({ favorites: favoriteOrder });
226 }
227
228 function swapFavorites (fromSpellId, toSpellId)
229 {
230 if (fromSpellId == null || toSpellId == null || fromSpellId === toSpellId)
231 { return; }
232 const order = orderedFavoriteSpells().map((entry) => entry.spellId);
233 const fromIndex = order.indexOf(fromSpellId);
234 const toIndex = order.indexOf(toSpellId);
235 if (fromIndex < 0 || toIndex < 0)
236 { return; }
237 const next = [...order];
238 const tmp = next[fromIndex];
239 next[fromIndex] = next[toIndex];
240 next[toIndex] = tmp;
241 favoriteOrder = next;
242 renderBar();
243 socket.send({
244 type: MessageType.reorderSpellFavorites,
245 favoriteSpellIds: next
246 });
247 }
248
249 function renderBar ()
250 {
251 const favorites = orderedFavoriteSpells();
252 bar.replaceChildren();
253 bar.hidden = favorites.length === 0;
254 const attackId = staffAttackFavoriteId();
255 for (const spell of favorites)
256 {
257 const btn = document.createElement("button");
258 btn.type = "button";
259 btn.className = "spell-favorite-slot";
260 btn.draggable = true;
261 btn.dataset.spellId = String(spell.spellId);
262 if (spell.spellId === armedSpellId)
263 { btn.classList.add("armed"); }
264 if (spell.spellId === attackId)
265 { btn.classList.add("staff-attack"); }
266 btn.title = spell.spellId === attackId
267 ? `${spell.displayName} (staff auto-attack)`
268 : spell.displayName;
269 btn.disabled = !spell.canCast;
270
271 const icon = document.createElement("img");
272 icon.src = spell.icon;
273 icon.alt = "";
274 icon.draggable = false;
275 btn.append(icon);
276
277 btn.addEventListener("click", () =>
278 {
279 if (suppressNextClick)
280 {
281 suppressNextClick = false;
282 return;
283 }
284 if (spell.spellId === armedSpellId)
285 { return; }
286 socket.send({ type: MessageType.armSpell, spellId: spell.spellId });
287 });
288 btn.addEventListener("contextmenu", (event) =>
289 {
290 event.preventDefault();
291 socket.send({ type: MessageType.setSpellFavorite, spellId: spell.spellId });
292 });
293 btn.addEventListener("dragstart", (event) =>
294 {
295 dragFromSpellId = spell.spellId;
296 btn.classList.add("dragging");
297 event.dataTransfer?.setData("text/plain", String(spell.spellId));
298 if (event.dataTransfer)
299 { event.dataTransfer.effectAllowed = "move"; }
300 });
301 btn.addEventListener("dragend", () =>
302 {
303 btn.classList.remove("dragging");
304 dragFromSpellId = null;
305 for (const el of bar.querySelectorAll(".spell-favorite-slot.drag-over"))
306 { el.classList.remove("drag-over"); }
307 });
308 btn.addEventListener("dragover", (event) =>
309 {
310 event.preventDefault();
311 if (event.dataTransfer)
312 { event.dataTransfer.dropEffect = "move"; }
313 btn.classList.add("drag-over");
314 });
315 btn.addEventListener("dragleave", () =>
316 {
317 btn.classList.remove("drag-over");
318 });
319 btn.addEventListener("drop", (event) =>
320 {
321 event.preventDefault();
322 btn.classList.remove("drag-over");
323 const rawFrom = dragFromSpellId ?? event.dataTransfer?.getData("text/plain");
324 if (rawFrom == null || rawFrom === "")
325 { return; }
326 suppressNextClick = true;
327 const fromId = favoriteOrder.find((id) => String(id) === String(rawFrom)) ?? rawFrom;
328 swapFavorites(fromId, spell.spellId);
329 });
330 bar.append(btn);
331 }
332 }
333
334 function getArmedSpell ()
335 {
336 if (!armedSpellId)
337 { return null; }
338 return spells.find((entry) => entry.spellId === armedSpellId) ?? null;
339 }
340
341 function tryCastAtTile (tileX, tileY)
342 {
343 const armed = getArmedSpell();
344 if (!armed || armed.target !== "tile" || !armed.canCast)
345 { return false; }
346 socket.send({
347 type: MessageType.castSpellTile,
348 spellId: armed.spellId,
349 tileX,
350 tileY
351 });
352 return true;
353 }
354
355 function tryCastAtEntity (targetEntityId)
356 {
357 const armed = getArmedSpell();
358 if (!armed || armed.target !== "entity" || !armed.canCast)
359 { return false; }
360 socket.send({
361 type: MessageType.castSpellEntity,
362 spellId: armed.spellId,
363 targetEntityId
364 });
365 return true;
366 }
367
368 function cancelTargeting ()
369 {
370 if (!armedSpellId)
371 { return; }
372 socket.send({ type: MessageType.cancelArmSpell });
373 disarmLocal();
374 }
375
376 return {
377 render,
378 refreshCastGates,
379 getArmedSpell,
380 tryCastAtTile,
381 tryCastAtEntity,
382 cancelTargeting,
383 isBlocking ()
384 {
385 return panel != null && !panel.hidden;
386 },
387 isTargeting ()
388 {
389 return armedSpellId != null;
390 },
391 handleSpellArmed (message)
392 {
393 armedSpellId = message.spellId ?? null;
394 renderList();
395 renderBar();
396 },
397 knowsSpell (spellId)
398 {
399 return spells.some((spell) => spell.spellId === spellId);
400 },
401 getKnownSpellIds ()
402 {
403 return spells.map((spell) => spell.spellId);
404 },
405 refreshMaxHitDisplay,
406 handleSpellDisarmed ()
407 {
408 disarmLocal();
409 },
410 hide ()
411 {
412 panel.hidden = true;
413 spells = [];
414 favoriteOrder = [];
415 autoCast = false;
416 armedSpellId = null;
417 if (autoCastToggle)
418 { autoCastToggle.checked = false; }
419 list.replaceChildren();
420 bar.replaceChildren();
421 bar.hidden = true;
422 }
423 };
424}