BlueGit

timfa questward

Files

questward / client / src / play / social.js

social.js

social.js 11.8 KiB Download Raw
1const FRIEND_NAME_COLOR = "#e8c84a";
2
3export function initSocial ({ socket, MessageType, resolveSpriteUrl = null })
4{
5 const nametag = document.getElementById("nametag");
6 const inspect = document.getElementById("inspect-modal");
7 const inspectBackdrop = document.getElementById("inspect-backdrop");
8 const inspectName = document.getElementById("inspect-name");
9 const inspectBounty = document.getElementById("inspect-bounty");
10 const inspectAction = document.getElementById("inspect-action");
11 const inspectError = document.getElementById("inspect-error");
12 const friendsPanel = document.getElementById("friends-panel");
13 const friendsList = document.getElementById("friends-list");
14 const incomingList = document.getElementById("incoming-list");
15 const outgoingList = document.getElementById("outgoing-list");
16 let social = { friends: [], incoming: [], outgoing: [] };
17 let inspected = null;
18 let open = false;
19 /** @type {number|null} expanded friend account in the panel */
20 let expandedAccountId = null;
21 let localAccountId = null;
22 let localCharacterId = null;
23
24 document.getElementById("inspect-close").addEventListener("click", () => hideInspect());
25 inspectBackdrop.addEventListener("click", () => hideInspect());
26 document.getElementById("friends-toggle").addEventListener("click", () =>
27 {
28 friendsPanel.hidden = !friendsPanel.hidden;
29 });
30
31 function hideInspect ()
32 {
33 open = false;
34 inspected = null;
35 inspect.hidden = true;
36 inspectBackdrop.hidden = true;
37 inspectError.textContent = "";
38 if (inspectBounty)
39 {
40 inspectBounty.hidden = true;
41 inspectBounty.textContent = "";
42 }
43 }
44
45 function friendAccountOfCharacter (characterId)
46 {
47 const id = characterId | 0;
48 for (const account of social.friends ?? [])
49 {
50 if ((account.characters ?? []).some((entry) => entry.characterId === id))
51 { return account; }
52 }
53 return null;
54 }
55
56 function isFriendCharacter (characterId, accountId = null)
57 {
58 const id = characterId | 0;
59 if (!id)
60 { return false; }
61 if (localAccountId && accountId && (accountId | 0) === (localAccountId | 0) && id !== (localCharacterId | 0))
62 { return true; }
63 return !!friendAccountOfCharacter(id);
64 }
65
66 function relation (characterId)
67 {
68 if (isFriendCharacter(characterId))
69 { return "friends"; }
70 const account = accountHoldingCharacter(characterId, social.incoming);
71 if (account)
72 { return "incoming"; }
73 if (accountHoldingCharacter(characterId, social.outgoing))
74 { return "outgoing"; }
75 return "none";
76 }
77
78 function accountHoldingCharacter (characterId, accounts)
79 {
80 const id = characterId | 0;
81 return (accounts ?? []).find((account) =>
82 (account.characters ?? []).some((entry) => entry.characterId === id)) ?? null;
83 }
84
85 function renderInspect ()
86 {
87 if (!inspected)
88 { return; }
89 inspectName.textContent = `${inspected.firstName} ${inspected.lastName}`;
90 inspectName.style.color = isFriendCharacter(inspected.characterId, inspected.accountId) ? FRIEND_NAME_COLOR : "";
91 inspectAction.replaceChildren();
92 const status = relation(inspected.characterId);
93 const friendAccount = friendAccountOfCharacter(inspected.characterId);
94 if (status === "friends")
95 {
96 inspectAction.append(actionButton("Remove friend", () =>
97 {
98 socket.send({
99 type: MessageType.friendRemove,
100 accountId: friendAccount?.accountId,
101 characterId: inspected.characterId
102 });
103 }));
104 }
105 else if (status === "incoming")
106 {
107 const incoming = accountHoldingCharacter(inspected.characterId, social.incoming);
108 inspectAction.append(
109 actionButton("Accept friend request", () =>
110 {
111 socket.send({
112 type: MessageType.friendAccept,
113 accountId: incoming?.accountId,
114 characterId: inspected.characterId
115 });
116 }),
117 actionButton("Decline", () =>
118 {
119 socket.send({
120 type: MessageType.friendDecline,
121 accountId: incoming?.accountId,
122 characterId: inspected.characterId
123 });
124 })
125 );
126 }
127 else if (status === "outgoing")
128 {
129 const outgoing = accountHoldingCharacter(inspected.characterId, social.outgoing);
130 const pending = document.createElement("p");
131 pending.className = "hint";
132 pending.textContent = "Friend request sent.";
133 inspectAction.append(
134 pending,
135 actionButton("Cancel request", () =>
136 {
137 socket.send({
138 type: MessageType.friendDecline,
139 accountId: outgoing?.accountId,
140 characterId: inspected.characterId
141 });
142 })
143 );
144 }
145 else
146 {
147 inspectAction.append(actionButton("Send friend request", () =>
148 {
149 socket.send({ type: MessageType.friendRequest, characterId: inspected.characterId });
150 }));
151 }
152 }
153
154 function renderLists ()
155 {
156 fillList(friendsList, social.friends, "No friends yet.", (account) => accountRow(account, {
157 expanded: expandedAccountId === account.accountId,
158 onToggle ()
159 {
160 expandedAccountId = expandedAccountId === account.accountId ? null : account.accountId;
161 renderLists();
162 },
163 onRemove ()
164 {
165 socket.send({ type: MessageType.friendRemove, accountId: account.accountId });
166 }
167 }));
168 fillList(incomingList, social.incoming, "No incoming requests.", (account) => accountRequestRow(account, {
169 onAccept ()
170 {
171 socket.send({ type: MessageType.friendAccept, accountId: account.accountId });
172 },
173 onDecline ()
174 {
175 socket.send({ type: MessageType.friendDecline, accountId: account.accountId });
176 }
177 }));
178 fillList(outgoingList, social.outgoing, "No outgoing requests.", (account) => accountRequestRow(account, {
179 onDecline ()
180 {
181 socket.send({ type: MessageType.friendDecline, accountId: account.accountId });
182 },
183 declineLabel: "Cancel"
184 }));
185 }
186
187 function accountRow (account, { expanded, onToggle, onRemove })
188 {
189 const wrap = document.createElement("div");
190 wrap.className = "friend-account";
191 const header = document.createElement("div");
192 header.className = "social-row friend-account-header";
193 const nameBtn = document.createElement("button");
194 nameBtn.type = "button";
195 nameBtn.className = "friend-account-name";
196 nameBtn.textContent = account.username || `Account ${account.accountId}`;
197 nameBtn.addEventListener("click", onToggle);
198 header.append(nameBtn, actionButton("Remove", onRemove));
199 wrap.append(header);
200 if (expanded)
201 {
202 const list = document.createElement("div");
203 list.className = "friend-character-list";
204 for (const character of account.characters ?? [])
205 { list.append(characterPreviewRow(character)); }
206 if (!(account.characters ?? []).length)
207 {
208 const empty = document.createElement("p");
209 empty.className = "hint";
210 empty.textContent = "No characters.";
211 list.append(empty);
212 }
213 wrap.append(list);
214 }
215 return wrap;
216 }
217
218 function accountRequestRow (account, { onAccept = null, onDecline, declineLabel = "Decline" })
219 {
220 const row = document.createElement("div");
221 row.className = "social-row";
222 const name = document.createElement("span");
223 name.textContent = account.username || `Account ${account.accountId}`;
224 row.append(name);
225 if (onAccept)
226 { row.append(actionButton("Accept", onAccept)); }
227 row.append(actionButton(declineLabel, onDecline));
228 return row;
229 }
230
231 function characterPreviewRow (entry)
232 {
233 const row = document.createElement("div");
234 row.className = "friend-character-row";
235 row.append(characterPreview(entry.layers), (() =>
236 {
237 const name = document.createElement("span");
238 name.textContent = `${entry.firstName} ${entry.lastName}`.trim();
239 return name;
240 })());
241 return row;
242 }
243
244 function characterPreview (layers)
245 {
246 const wrap = document.createElement("div");
247 wrap.className = "char-preview friend-char-preview";
248 for (const layer of layers ?? [])
249 {
250 const url = resolveSpriteUrl?.(layer.sprite);
251 if (!url)
252 { continue; }
253 const img = document.createElement("img");
254 img.src = url;
255 img.alt = "";
256 wrap.append(img);
257 }
258 return wrap;
259 }
260
261 return {
262 isBlocking ()
263 {
264 if (open)
265 { return true; }
266 const x = GameInput.mousePosition.x;
267 const y = GameInput.mousePosition.y;
268 for (const element of [document.getElementById("hud"), friendsPanel, inspect, inspectBackdrop])
269 {
270 if (!element || element.hidden)
271 { continue; }
272 const box = element.getBoundingClientRect();
273 if (x >= box.left && x < box.right && y >= box.top && y < box.bottom)
274 { return true; }
275 }
276 return false;
277 },
278 inspectOpen: () => open,
279 handleFriends (message)
280 {
281 social = {
282 friends: message.friends ?? [],
283 incoming: message.incoming ?? [],
284 outgoing: message.outgoing ?? []
285 };
286 if (
287 expandedAccountId != null
288 && !(social.friends ?? []).some((account) => account.accountId === expandedAccountId)
289 )
290 { expandedAccountId = null; }
291 renderLists();
292 if (open)
293 { renderInspect(); }
294 },
295 /** Flat character list for pigeon send targets. */
296 getFriends ()
297 {
298 const out = [];
299 for (const account of social.friends ?? [])
300 {
301 for (const character of account.characters ?? [])
302 { out.push(character); }
303 }
304 return out;
305 },
306 isFriendCharacter,
307 setLocalIdentity ({ accountId = null, characterId = null } = {})
308 {
309 localAccountId = accountId | 0 || null;
310 localCharacterId = characterId | 0 || null;
311 },
312 inspect (entity)
313 {
314 if (!entity?.characterId)
315 { return; }
316 inspected = {
317 characterId: entity.characterId,
318 accountId: entity.accountId ?? null,
319 firstName: entity.firstName ?? "",
320 lastName: entity.lastName ?? ""
321 };
322 open = true;
323 inspectError.textContent = "";
324 if (inspectBounty)
325 {
326 inspectBounty.hidden = true;
327 inspectBounty.textContent = "";
328 }
329 inspect.hidden = false;
330 inspectBackdrop.hidden = false;
331 renderInspect();
332 socket.send({
333 type: MessageType.getCharacterBounty,
334 characterId: entity.characterId
335 });
336 },
337 handleCharacterBounty (message)
338 {
339 if (!open || !inspected || !inspectBounty)
340 { return; }
341 const target = message.target;
342 if (!target || target.characterId !== inspected.characterId)
343 { return; }
344 const amount = target.amountCopper | 0;
345 if (amount <= 0)
346 {
347 inspectBounty.hidden = true;
348 inspectBounty.textContent = "";
349 return;
350 }
351 inspectBounty.hidden = false;
352 inspectBounty.textContent = `Bounty: ${target.amountLabel ?? amount}`;
353 },
354 hideInspect,
355 closeOverlays ()
356 {
357 hideInspect();
358 friendsPanel.hidden = true;
359 },
360 reset ()
361 {
362 hideInspect();
363 friendsPanel.hidden = true;
364 nametag.hidden = true;
365 },
366 updateNametag (view, scene, localEntityId)
367 {
368 if (!view || !scene?.canvas)
369 {
370 nametag.hidden = true;
371 return;
372 }
373 const canvas = scene.canvas;
374 const rect = canvas.getBoundingClientRect();
375 const mouseX = GameInput.mousePosition.x - rect.left;
376 const mouseY = GameInput.mousePosition.y - rect.top;
377 const entity = view.entityAtScreen(mouseX, mouseY);
378 if (!entity || entity.entityId === localEntityId || !entity.firstName)
379 {
380 nametag.hidden = true;
381 canvas.style.cursor = "";
382 return;
383 }
384 const anchor = view.nametagAnchor(entity);
385 if (!anchor)
386 {
387 nametag.hidden = true;
388 return;
389 }
390 nametag.hidden = false;
391 nametag.textContent = entity.firstName;
392 const friend = entity.characterId && isFriendCharacter(entity.characterId, entity.accountId);
393 nametag.classList.toggle("friend-name", !!friend);
394 nametag.style.color = friend ? FRIEND_NAME_COLOR : "";
395 nametag.style.left = `${rect.left + anchor.x}px`;
396 nametag.style.top = `${rect.top + anchor.y - 6}px`;
397 canvas.style.cursor = "pointer";
398 },
399 showError (message)
400 {
401 if (open)
402 { inspectError.textContent = message; }
403 }
404 };
405}
406
407function fillList (root, entries, emptyText, renderRow)
408{
409 root.replaceChildren();
410 if (!entries.length)
411 {
412 const empty = document.createElement("p");
413 empty.className = "hint";
414 empty.textContent = emptyText;
415 root.append(empty);
416 return;
417 }
418 for (const entry of entries)
419 { root.append(renderRow(entry)); }
420}
421
422function actionButton (label, onClick)
423{
424 const button = document.createElement("button");
425 button.type = "button";
426 button.textContent = label;
427 button.addEventListener("click", onClick);
428 return button;
429}