BlueGit

timfa questward

Files

questward / client / src / play / social.js

social.js

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