BlueGit

timfa questward

Files

questward / client / src / editor / giftsModal.js

giftsModal.js

giftsModal.js 11.9 KiB Download Raw
1import { listAllItemPickerEntries, itemDefinition, ItemId } from "/shared/definitions/items.js";
2import {
3 listRecipePaperPickerEntries,
4 listPotionPickerEntries,
5 potionKeyFromListingKey
6} from "/shared/market/listingKey.js";
7import {
8 formatGiftLetterBody,
9 QUESTWARD_GIFT_AUTHOR,
10 QUESTWARD_GIFT_ORG
11} from "/shared/courier/giftLetters.js";
12import { formatLetterSignature } from "/shared/courier/systemLetters.js";
13
14function giftItemPickerEntries ()
15{
16 const recipes = listRecipePaperPickerEntries();
17 const potions = listPotionPickerEntries();
18 const base = listAllItemPickerEntries()
19 .filter((item) => item.itemId !== ItemId.recipePaper && item.itemId !== ItemId.potion)
20 .map((item) => ({
21 ...item,
22 listingKey: null,
23 potionKey: null
24 }));
25 return [...base, ...recipes, ...potions]
26 .sort((a, b) => a.displayName.localeCompare(b.displayName) || (a.itemId - b.itemId));
27}
28
29function giftRowKey (row)
30{
31 const itemId = row?.itemId | 0;
32 if (itemId === ItemId.recipePaper && row?.potionKey)
33 { return `recipe:${row.potionKey}`; }
34 if (itemId === ItemId.potion && row?.potionKey)
35 { return `potion:${row.potionKey}`; }
36 if (row?.listingKey)
37 { return `listing:${row.listingKey}`; }
38 return `item:${itemId}`;
39}
40
41export function initGiftsModal ({ socket, MessageType })
42{
43 const backdrop = document.getElementById("gifts-backdrop");
44 const modal = document.getElementById("gifts-modal");
45 const resultsEl = document.getElementById("gifts-results");
46 const detailEl = document.getElementById("gifts-detail");
47 const statusEl = document.getElementById("gifts-status");
48 const searchInput = document.getElementById("gifts-search-input");
49 const searchBtn = document.getElementById("gifts-search-btn");
50 let open = false;
51 /** @type {any[]} */
52 let characters = [];
53 /** @type {any|null} */
54 let selected = null;
55 /** @type {Array<{ itemId: number, quantity: number, displayName: string, listingKey?: string|null, potionKey?: string|null }>} */
56 let giftItems = [];
57 let messageText = "";
58 /** @type {null | { resultsEl: HTMLElement, inputEl: HTMLInputElement }} */
59 let itemPickContext = null;
60
61 function show (visible)
62 {
63 open = visible;
64 backdrop.hidden = !visible;
65 modal.hidden = !visible;
66 if (!visible)
67 {
68 closeInlineItemSearch();
69 return;
70 }
71 render();
72 }
73
74 function setStatus (text, isError = false)
75 {
76 if (!statusEl)
77 { return; }
78 statusEl.textContent = text || "";
79 statusEl.classList.toggle("error", !!isError);
80 }
81
82 function closeInlineItemSearch ()
83 {
84 if (itemPickContext?.resultsEl)
85 { itemPickContext.resultsEl.replaceChildren(); }
86 itemPickContext = null;
87 }
88
89 function addGiftItem (item)
90 {
91 if (!item?.itemId)
92 { return; }
93 const listingKey = item.listingKey ?? null;
94 const potionKey = item.potionKey
95 ?? potionKeyFromListingKey(listingKey)
96 ?? null;
97 const key = giftRowKey({ itemId: item.itemId, listingKey, potionKey });
98 const existing = giftItems.find((row) => giftRowKey(row) === key);
99 if (existing)
100 {
101 existing.quantity = Math.min(100000, (existing.quantity | 0) + 1);
102 }
103 else
104 {
105 giftItems.push({
106 itemId: item.itemId,
107 quantity: 1,
108 displayName: item.displayName
109 || itemDefinition(item.itemId)?.displayName
110 || `Item ${item.itemId}`,
111 listingKey,
112 potionKey
113 });
114 }
115 closeInlineItemSearch();
116 renderDetail();
117 }
118
119 function filterItemMatches (query)
120 {
121 const q = String(query ?? "").trim().toLowerCase();
122 const taken = new Set(giftItems.map((row) => giftRowKey(row)));
123 return giftItemPickerEntries().filter((item) =>
124 {
125 if (taken.has(giftRowKey(item)))
126 { return false; }
127 if (!q)
128 { return true; }
129 return item.displayName.toLowerCase().includes(q)
130 || item.key.toLowerCase().includes(q)
131 || String(item.itemId).includes(q)
132 || String(item.potionKey ?? "").toLowerCase().includes(q);
133 }).slice(0, 40);
134 }
135
136 function renderInlineItemSearch (query)
137 {
138 if (!itemPickContext)
139 { return; }
140 const { resultsEl: pickResults } = itemPickContext;
141 pickResults.replaceChildren();
142 const matches = filterItemMatches(query);
143 if (!matches.length)
144 {
145 pickResults.textContent = "No matching items.";
146 return;
147 }
148 for (const item of matches)
149 {
150 const row = document.createElement("button");
151 row.type = "button";
152 row.className = "shop-item-search-row";
153 const name = document.createElement("span");
154 name.className = "shop-item-search-row-name";
155 name.textContent = item.displayName;
156 const key = document.createElement("span");
157 key.className = "shop-item-search-row-key";
158 key.textContent = item.listingKey
159 ? `${item.key} (${item.listingKey})`
160 : `${item.key} (#${item.itemId})`;
161 row.append(name, key);
162 row.addEventListener("click", () => addGiftItem(item));
163 pickResults.append(row);
164 }
165 }
166
167 function characterLabel (row)
168 {
169 const name = `${row.firstName ?? ""} ${row.lastName ?? ""}`.trim();
170 const account = row.accountUsername ? ` · @${row.accountUsername}` : "";
171 return `${name}${account}`;
172 }
173
174 function renderResults ()
175 {
176 resultsEl.replaceChildren();
177 if (!characters.length)
178 {
179 resultsEl.textContent = "No characters found.";
180 return;
181 }
182 for (const row of characters)
183 {
184 const btn = document.createElement("button");
185 btn.type = "button";
186 btn.className = selected?.characterId === row.characterId ? "active" : "";
187 btn.textContent = characterLabel(row);
188 btn.addEventListener("click", () =>
189 {
190 selected = row;
191 giftItems = [];
192 messageText = "";
193 closeInlineItemSearch();
194 render();
195 });
196 resultsEl.append(btn);
197 }
198 }
199
200 function renderPreview ()
201 {
202 const preview = detailEl.querySelector("#gifts-letter-preview");
203 const signature = detailEl.querySelector("#gifts-letter-signature");
204 if (!preview || !selected)
205 { return; }
206 const displayName = `${selected.firstName} ${selected.lastName}`.trim();
207 preview.textContent = formatGiftLetterBody({
208 characterDisplayName: displayName,
209 message: messageText,
210 items: giftItems
211 });
212 if (signature)
213 {
214 signature.textContent = formatLetterSignature({
215 authorDisplayName: QUESTWARD_GIFT_AUTHOR,
216 authorOrganization: QUESTWARD_GIFT_ORG
217 });
218 }
219 }
220
221 function renderDetail ()
222 {
223 detailEl.replaceChildren();
224 if (!selected)
225 {
226 detailEl.textContent = "Search for a character, then select one to compose a gift.";
227 return;
228 }
229
230 const heading = document.createElement("h3");
231 heading.textContent = `Gift to ${characterLabel(selected)}`;
232 detailEl.append(heading);
233
234 const messageLabel = document.createElement("label");
235 messageLabel.className = "gifts-message-label";
236 messageLabel.textContent = "Message";
237 const messageArea = document.createElement("textarea");
238 messageArea.id = "gifts-message";
239 messageArea.rows = 5;
240 messageArea.placeholder = "Write the personal note included in the letter…";
241 messageArea.value = messageText;
242 messageArea.addEventListener("input", () =>
243 {
244 messageText = messageArea.value;
245 renderPreview();
246 });
247 messageLabel.append(messageArea);
248 detailEl.append(messageLabel);
249
250 const itemsHeader = document.createElement("div");
251 itemsHeader.className = "gifts-items-header";
252 const itemsTitle = document.createElement("strong");
253 itemsTitle.textContent = "Items";
254 itemsHeader.append(itemsTitle);
255 detailEl.append(itemsHeader);
256
257 const itemSearch = document.createElement("input");
258 itemSearch.type = "search";
259 itemSearch.placeholder = "Search items to add…";
260 itemSearch.autocomplete = "off";
261 const itemResults = document.createElement("div");
262 itemResults.className = "gifts-item-search-results";
263 detailEl.append(itemSearch, itemResults);
264
265 itemPickContext = { inputEl: itemSearch, resultsEl: itemResults };
266 itemSearch.addEventListener("input", () => renderInlineItemSearch(itemSearch.value));
267 itemSearch.addEventListener("search", () => renderInlineItemSearch(itemSearch.value));
268 itemSearch.addEventListener("keydown", (event) =>
269 {
270 if (event.key !== "Enter")
271 { return; }
272 event.preventDefault();
273 event.stopPropagation();
274 const matches = filterItemMatches(itemSearch.value);
275 if (matches[0])
276 { addGiftItem(matches[0]); }
277 });
278 renderInlineItemSearch(itemSearch.value);
279
280 const list = document.createElement("div");
281 list.className = "gifts-item-list";
282 if (!giftItems.length)
283 {
284 const empty = document.createElement("p");
285 empty.className = "hint";
286 empty.textContent = "No items yet — search above and click a result (or press Enter).";
287 list.append(empty);
288 }
289 else
290 {
291 for (let index = 0; index < giftItems.length; index++)
292 {
293 const entry = giftItems[index];
294 const row = document.createElement("div");
295 row.className = "gifts-item-row";
296 const name = document.createElement("span");
297 name.textContent = entry.displayName
298 || itemDefinition(entry.itemId)?.displayName
299 || `Item ${entry.itemId}`;
300 const qty = document.createElement("input");
301 qty.type = "number";
302 qty.min = "1";
303 qty.max = "100000";
304 qty.value = String(entry.quantity);
305 qty.addEventListener("change", () =>
306 {
307 entry.quantity = Math.max(1, Math.min(100000, qty.valueAsNumber || 1));
308 qty.value = String(entry.quantity);
309 renderPreview();
310 });
311 const remove = document.createElement("button");
312 remove.type = "button";
313 remove.textContent = "Remove";
314 remove.addEventListener("click", () =>
315 {
316 giftItems.splice(index, 1);
317 renderDetail();
318 });
319 row.append(name, qty, remove);
320 list.append(row);
321 }
322 }
323 detailEl.append(list);
324
325 const previewWrap = document.createElement("div");
326 previewWrap.className = "gifts-preview-wrap";
327 const previewTitle = document.createElement("strong");
328 previewTitle.textContent = "Letter preview";
329 const preview = document.createElement("pre");
330 preview.id = "gifts-letter-preview";
331 preview.className = "gifts-letter-preview";
332 const signature = document.createElement("pre");
333 signature.id = "gifts-letter-signature";
334 signature.className = "gifts-letter-signature";
335 previewWrap.append(previewTitle, preview, signature);
336 detailEl.append(previewWrap);
337
338 const sendBtn = document.createElement("button");
339 sendBtn.type = "button";
340 sendBtn.id = "gifts-send";
341 sendBtn.textContent = "Send Gift";
342 sendBtn.addEventListener("click", () =>
343 {
344 if (!selected)
345 { return; }
346 setStatus("Sending gift…");
347 socket.send({
348 type: MessageType.editorSendGift,
349 characterId: selected.characterId,
350 message: messageText,
351 items: giftItems.map((row) => ({
352 itemId: row.itemId,
353 quantity: row.quantity,
354 listingKey: row.listingKey ?? null,
355 potionKey: row.potionKey ?? null
356 }))
357 });
358 });
359 detailEl.append(sendBtn);
360 renderPreview();
361 }
362
363 function render ()
364 {
365 renderResults();
366 renderDetail();
367 }
368
369 function runSearch ()
370 {
371 const query = searchInput.value.trim();
372 if (!query)
373 {
374 setStatus("Enter a character or account name.", true);
375 return;
376 }
377 setStatus("Searching…");
378 socket.send({ type: MessageType.editorSearchGiftCharacters, query });
379 }
380
381 document.getElementById("open-gifts").addEventListener("click", () =>
382 {
383 setStatus("");
384 show(true);
385 });
386 document.getElementById("gifts-close").addEventListener("click", () => show(false));
387 backdrop.addEventListener("click", () => show(false));
388 searchBtn.addEventListener("click", runSearch);
389 searchInput.addEventListener("keydown", (event) =>
390 {
391 if (event.key === "Enter")
392 {
393 event.preventDefault();
394 runSearch();
395 }
396 });
397
398 return {
399 isOpen: () => open,
400 handleError (message)
401 {
402 setStatus(message || "Gift failed.", true);
403 },
404 handleMessage (message)
405 {
406 if (message.type === MessageType.editorGiftCharacters)
407 {
408 characters = message.characters ?? [];
409 if (selected && !characters.some((row) => row.characterId === selected.characterId))
410 { selected = null; }
411 setStatus(characters.length ? `${characters.length} character(s)` : "No matches.");
412 render();
413 return;
414 }
415 if (message.type === MessageType.editorGiftSent)
416 {
417 const name = `${message.firstName ?? ""} ${message.lastName ?? ""}`.trim();
418 setStatus(`Gift sent to ${name}.`);
419 giftItems = [];
420 messageText = "";
421 renderDetail();
422 }
423 }
424 };
425}