BlueGit

timfa questward

Files

questward / client / src / play / social.js

social.js

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