BlueGit

timfa questward

Files

questward / client / src / play / social.js

social.js

social.js 12.1 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 nameBtn = document.createElement("button");
205 nameBtn.type = "button";
206 nameBtn.className = "friend-account-name";
207 nameBtn.textContent = account.username || `Account ${account.accountId}`;
208 nameBtn.addEventListener("click", onToggle);
209 header.append(nameBtn, actionButton("Remove", onRemove));
210 wrap.append(header);
211 if (expanded)
212 {
213 const list = document.createElement("div");
214 list.className = "friend-character-list";
215 for (const character of account.characters ?? [])
216 { list.append(characterPreviewRow(character)); }
217 if (!(account.characters ?? []).length)
218 {
219 const empty = document.createElement("p");
220 empty.className = "hint";
221 empty.textContent = "No characters.";
222 list.append(empty);
223 }
224 wrap.append(list);
225 }
226 return wrap;
227 }
228
229 function accountRequestRow (account, { onAccept = null, onDecline, declineLabel = "Decline" })
230 {
231 const row = document.createElement("div");
232 row.className = "social-row";
233 const name = document.createElement("span");
234 name.textContent = account.username || `Account ${account.accountId}`;
235 row.append(name);
236 if (onAccept)
237 { row.append(actionButton("Accept", onAccept)); }
238 row.append(actionButton(declineLabel, onDecline));
239 return row;
240 }
241
242 function characterPreviewRow (entry)
243 {
244 const row = document.createElement("div");
245 row.className = "friend-character-row";
246 row.append(characterPreview(entry.layers), (() =>
247 {
248 const name = document.createElement("span");
249 name.textContent = `${entry.firstName} ${entry.lastName}`.trim();
250 return name;
251 })());
252 return row;
253 }
254
255 function characterPreview (layers)
256 {
257 return mountLayerPreview(layers, {
258 resolveImage,
259 resolveSpriteUrl,
260 size: 48,
261 className: "char-preview friend-char-preview"
262 });
263 }
264
265 return {
266 isBlocking ()
267 {
268 if (open)
269 { return true; }
270 const x = GameInput.mousePosition.x;
271 const y = GameInput.mousePosition.y;
272 for (const element of [document.getElementById("hud"), friendsPanel, inspect, inspectBackdrop])
273 {
274 if (!element || element.hidden)
275 { continue; }
276 const box = element.getBoundingClientRect();
277 if (x >= box.left && x < box.right && y >= box.top && y < box.bottom)
278 { return true; }
279 }
280 return false;
281 },
282 inspectOpen: () => open,
283 handleFriends (message)
284 {
285 social = {
286 friends: message.friends ?? [],
287 incoming: message.incoming ?? [],
288 outgoing: message.outgoing ?? []
289 };
290 if (
291 expandedAccountId != null
292 && !(social.friends ?? []).some((account) => account.accountId === expandedAccountId)
293 )
294 { expandedAccountId = null; }
295 renderLists();
296 syncFriendsAlert();
297 if (open)
298 { renderInspect(); }
299 },
300 /** Flat character list for pigeon send targets. */
301 getFriends ()
302 {
303 const out = [];
304 for (const account of social.friends ?? [])
305 {
306 for (const character of account.characters ?? [])
307 { out.push(character); }
308 }
309 return out;
310 },
311 isFriendCharacter,
312 setLocalIdentity ({ accountId = null, characterId = null } = {})
313 {
314 localAccountId = accountId | 0 || null;
315 localCharacterId = characterId | 0 || null;
316 },
317 inspect (entity)
318 {
319 if (!entity?.characterId)
320 { return; }
321 inspected = {
322 characterId: entity.characterId,
323 accountId: entity.accountId ?? null,
324 firstName: entity.firstName ?? "",
325 lastName: entity.lastName ?? ""
326 };
327 open = true;
328 inspectError.textContent = "";
329 if (inspectBounty)
330 {
331 inspectBounty.hidden = true;
332 inspectBounty.textContent = "";
333 }
334 inspect.hidden = false;
335 inspectBackdrop.hidden = false;
336 renderInspect();
337 socket.send({
338 type: MessageType.getCharacterBounty,
339 characterId: entity.characterId
340 });
341 },
342 handleCharacterBounty (message)
343 {
344 if (!open || !inspected || !inspectBounty)
345 { return; }
346 const target = message.target;
347 if (!target || target.characterId !== inspected.characterId)
348 { return; }
349 const amount = target.amountCopper | 0;
350 if (amount <= 0)
351 {
352 inspectBounty.hidden = true;
353 inspectBounty.textContent = "";
354 return;
355 }
356 inspectBounty.hidden = false;
357 inspectBounty.textContent = `Bounty: ${target.amountLabel ?? amount}`;
358 },
359 hideInspect,
360 closeOverlays ()
361 {
362 hideInspect();
363 friendsPanel.hidden = true;
364 },
365 reset ()
366 {
367 hideInspect();
368 friendsPanel.hidden = true;
369 nametag.hidden = true;
370 social = { friends: [], incoming: [], outgoing: [] };
371 syncFriendsAlert();
372 },
373 updateNametag (view, scene, localEntityId)
374 {
375 if (!view || !scene?.canvas)
376 {
377 nametag.hidden = true;
378 return;
379 }
380 const canvas = scene.canvas;
381 const rect = canvas.getBoundingClientRect();
382 const mouseX = GameInput.mousePosition.x - rect.left;
383 const mouseY = GameInput.mousePosition.y - rect.top;
384 const entity = view.entityAtScreen(mouseX, mouseY);
385 if (!entity || entity.entityId === localEntityId || !entity.firstName)
386 {
387 nametag.hidden = true;
388 canvas.style.cursor = "";
389 return;
390 }
391 const anchor = view.nametagAnchor(entity);
392 if (!anchor)
393 {
394 nametag.hidden = true;
395 return;
396 }
397 nametag.hidden = false;
398 nametag.textContent = entity.firstName;
399 const friend = entity.characterId && isFriendCharacter(entity.characterId, entity.accountId);
400 nametag.classList.toggle("friend-name", !!friend);
401 nametag.style.color = friend ? FRIEND_NAME_COLOR : "";
402 nametag.style.left = `${rect.left + anchor.x}px`;
403 nametag.style.top = `${rect.top + anchor.y - 6}px`;
404 canvas.style.cursor = "pointer";
405 },
406 showError (message)
407 {
408 if (open)
409 { inspectError.textContent = message; }
410 }
411 };
412}
413
414function fillList (root, entries, emptyText, renderRow)
415{
416 root.replaceChildren();
417 if (!entries.length)
418 {
419 const empty = document.createElement("p");
420 empty.className = "hint";
421 empty.textContent = emptyText;
422 root.append(empty);
423 return;
424 }
425 for (const entry of entries)
426 { root.append(renderRow(entry)); }
427}
428
429function actionButton (label, onClick)
430{
431 const button = document.createElement("button");
432 button.type = "button";
433 button.textContent = label;
434 button.addEventListener("click", onClick);
435 return button;
436}