| 1 | import { |
| 2 | itemAssetPathForStack, |
| 3 | itemDescription, |
| 4 | itemDisplayName, |
| 5 | itemOriginSummary, |
| 6 | formatQuantity |
| 7 | } from "/shared/definitions/items.js"; |
| 8 | import { applyItemIcon } from "../render/potionIcon.js"; |
| 9 | import { isAdjacentTile } from "/shared/navigation/adjacency.js"; |
| 10 | |
| 11 | /** |
| 12 | * Player-to-player trade UI + invite toasts. |
| 13 | */ |
| 14 | export function initTrade ({ |
| 15 | socket, |
| 16 | MessageType, |
| 17 | toasts, |
| 18 | getLocalEntity, |
| 19 | getEntity, |
| 20 | approachAdjacentTile, |
| 21 | clearPendingActions, |
| 22 | setPendingTradeRequest, |
| 23 | setPendingTradeAccept, |
| 24 | onSuppressWorldClick, |
| 25 | resolveSpriteUrl, |
| 26 | resolveImage, |
| 27 | ensureBagOpen, |
| 28 | onTradeOpenChanged |
| 29 | }) |
| 30 | { |
| 31 | const backdrop = document.getElementById("trade-backdrop"); |
| 32 | const panel = document.getElementById("trade-panel"); |
| 33 | const partnerEl = document.getElementById("trade-partner"); |
| 34 | const giveGrid = document.getElementById("trade-give-grid"); |
| 35 | const receiveGrid = document.getElementById("trade-receive-grid"); |
| 36 | const acceptBtn = document.getElementById("trade-accept"); |
| 37 | const cancelBtn = document.getElementById("trade-cancel"); |
| 38 | const statusEl = document.getElementById("trade-status"); |
| 39 | const qtyBackdrop = document.getElementById("trade-qty-backdrop"); |
| 40 | const qtyPanel = document.getElementById("trade-qty-panel"); |
| 41 | const qtyName = document.getElementById("trade-qty-name"); |
| 42 | const qtyInput = document.getElementById("trade-qty-input"); |
| 43 | const qtyConfirm = document.getElementById("trade-qty-confirm"); |
| 44 | const qtyClose = document.getElementById("trade-qty-close"); |
| 45 | const bagPanel = document.getElementById("bag-panel"); |
| 46 | |
| 47 | const ACCEPT_LOCK_MS = 3000; |
| 48 | const FLASH_MS = 700; |
| 49 | |
| 50 | let open = false; |
| 51 | let partnerName = ""; |
| 52 | let partnerEntityId = null; |
| 53 | let youAccepted = false; |
| 54 | let theyAccepted = false; |
| 55 | /** @type {any[]} */ |
| 56 | let yourOffer = []; |
| 57 | /** @type {any[]} */ |
| 58 | let theirOffer = []; |
| 59 | /** @type {Map<string, { dismiss: () => void }>} */ |
| 60 | const inviteToasts = new Map(); |
| 61 | let pendingQty = null; |
| 62 | let acceptUnlockAt = 0; |
| 63 | let acceptUnlockTimer = null; |
| 64 | |
| 65 | function suppressWorldClick (event) |
| 66 | { |
| 67 | event?.preventDefault?.(); |
| 68 | event?.stopPropagation?.(); |
| 69 | onSuppressWorldClick?.(); |
| 70 | } |
| 71 | |
| 72 | function isBlocking () |
| 73 | { |
| 74 | // Blocks world orders while trading; bag stays clickable (no full-screen capture). |
| 75 | return open || !!(qtyPanel && !qtyPanel.hidden); |
| 76 | } |
| 77 | |
| 78 | function isOpen () |
| 79 | { |
| 80 | return open; |
| 81 | } |
| 82 | |
| 83 | function setBagRaised (raised) |
| 84 | { |
| 85 | bagPanel?.classList.toggle("trade-bag-raised", !!raised); |
| 86 | } |
| 87 | |
| 88 | function listSoftClaims () |
| 89 | { |
| 90 | if (!open) |
| 91 | { return []; } |
| 92 | return yourOffer.map((line) => ({ |
| 93 | itemId: line.itemId, |
| 94 | quantity: line.quantity, |
| 95 | instance: line.instance ?? null |
| 96 | })); |
| 97 | } |
| 98 | |
| 99 | function closeQty () |
| 100 | { |
| 101 | pendingQty = null; |
| 102 | if (qtyPanel) |
| 103 | { qtyPanel.hidden = true; } |
| 104 | if (qtyBackdrop) |
| 105 | { qtyBackdrop.hidden = true; } |
| 106 | } |
| 107 | |
| 108 | function closeTradeUi () |
| 109 | { |
| 110 | open = false; |
| 111 | closeQty(); |
| 112 | if (panel) |
| 113 | { panel.hidden = true; } |
| 114 | if (backdrop) |
| 115 | { backdrop.hidden = true; } |
| 116 | setBagRaised(false); |
| 117 | partnerEntityId = null; |
| 118 | partnerName = ""; |
| 119 | youAccepted = false; |
| 120 | theyAccepted = false; |
| 121 | yourOffer = []; |
| 122 | theirOffer = []; |
| 123 | acceptUnlockAt = 0; |
| 124 | if (acceptUnlockTimer != null) |
| 125 | { |
| 126 | window.clearTimeout(acceptUnlockTimer); |
| 127 | acceptUnlockTimer = null; |
| 128 | } |
| 129 | onTradeOpenChanged?.(false); |
| 130 | } |
| 131 | |
| 132 | function offerLineKey (line) |
| 133 | { |
| 134 | return `${line.bagSlotIndex | 0}|${line.itemId | 0}|${line.quantity | 0}`; |
| 135 | } |
| 136 | |
| 137 | function diffOfferLines (previous, next) |
| 138 | { |
| 139 | const prevBySlot = new Map((previous ?? []).map((line) => [line.bagSlotIndex | 0, line])); |
| 140 | const nextBySlot = new Map((next ?? []).map((line) => [line.bagSlotIndex | 0, line])); |
| 141 | /** @type {Set<string>} */ |
| 142 | const addedKeys = new Set(); |
| 143 | /** @type {Set<string>} */ |
| 144 | const redKeys = new Set(); |
| 145 | /** @type {any[]} */ |
| 146 | const removedLines = []; |
| 147 | for (const [slot, line] of nextBySlot) |
| 148 | { |
| 149 | const old = prevBySlot.get(slot); |
| 150 | if (!old) |
| 151 | { addedKeys.add(offerLineKey(line)); } |
| 152 | else if (offerLineKey(old) !== offerLineKey(line)) |
| 153 | { |
| 154 | if ((line.quantity | 0) > (old.quantity | 0)) |
| 155 | { addedKeys.add(offerLineKey(line)); } |
| 156 | else |
| 157 | { redKeys.add(offerLineKey(line)); } |
| 158 | } |
| 159 | } |
| 160 | for (const [slot, line] of prevBySlot) |
| 161 | { |
| 162 | if (!nextBySlot.has(slot)) |
| 163 | { removedLines.push(line); } |
| 164 | } |
| 165 | return { |
| 166 | addedKeys, |
| 167 | redKeys, |
| 168 | removedLines, |
| 169 | changed: addedKeys.size > 0 || redKeys.size > 0 || removedLines.length > 0 |
| 170 | }; |
| 171 | } |
| 172 | |
| 173 | function acceptLocked () |
| 174 | { |
| 175 | return Date.now() < acceptUnlockAt; |
| 176 | } |
| 177 | |
| 178 | function syncAcceptButton () |
| 179 | { |
| 180 | if (!acceptBtn) |
| 181 | { return; } |
| 182 | acceptBtn.textContent = youAccepted ? "Accepted" : "Accept"; |
| 183 | acceptBtn.classList.toggle("active", !!youAccepted); |
| 184 | acceptBtn.disabled = acceptLocked(); |
| 185 | } |
| 186 | |
| 187 | function syncStatus () |
| 188 | { |
| 189 | if (!statusEl) |
| 190 | { return; } |
| 191 | if (acceptLocked() && !youAccepted && !theyAccepted) |
| 192 | { statusEl.textContent = "Offers changed — wait a moment…"; } |
| 193 | else if (youAccepted && theyAccepted) |
| 194 | { statusEl.textContent = "Confirming…"; } |
| 195 | else if (theyAccepted) |
| 196 | { statusEl.textContent = `${partnerName} has accepted.`; } |
| 197 | else if (youAccepted) |
| 198 | { statusEl.textContent = "Waiting for them to accept…"; } |
| 199 | else |
| 200 | { statusEl.textContent = ""; } |
| 201 | } |
| 202 | |
| 203 | function lockAccept (ms = ACCEPT_LOCK_MS) |
| 204 | { |
| 205 | acceptUnlockAt = Date.now() + ms; |
| 206 | if (acceptUnlockTimer != null) |
| 207 | { window.clearTimeout(acceptUnlockTimer); } |
| 208 | acceptUnlockTimer = window.setTimeout(() => |
| 209 | { |
| 210 | acceptUnlockTimer = null; |
| 211 | syncAcceptButton(); |
| 212 | syncStatus(); |
| 213 | }, ms); |
| 214 | syncAcceptButton(); |
| 215 | syncStatus(); |
| 216 | } |
| 217 | |
| 218 | function makeOfferSlot (line, { theirs = false, flash = null } = {}) |
| 219 | { |
| 220 | const btn = document.createElement("button"); |
| 221 | btn.type = "button"; |
| 222 | btn.className = "item-slot"; |
| 223 | if (flash === "add") |
| 224 | { btn.classList.add("trade-flash-add"); } |
| 225 | else if (flash === "remove") |
| 226 | { btn.classList.add("trade-flash-remove", "trade-flash-ghost"); } |
| 227 | else if (flash === "down") |
| 228 | { btn.classList.add("trade-flash-remove"); } |
| 229 | const stack = { |
| 230 | itemId: line.itemId, |
| 231 | quantity: line.quantity, |
| 232 | instance: line.instance ?? null, |
| 233 | origins: line.origins ?? undefined |
| 234 | }; |
| 235 | const base = `${line.displayName ?? itemDisplayName(stack)}${ |
| 236 | line.quantity > 1 ? ` ×${formatQuantity(line.quantity)}` : "" |
| 237 | }`; |
| 238 | const origin = itemOriginSummary(stack); |
| 239 | const desc = line.description || itemDescription(stack); |
| 240 | btn.title = [base, origin, desc].filter(Boolean).join("\n"); |
| 241 | const img = document.createElement("img"); |
| 242 | img.alt = line.displayName ?? itemDisplayName(stack); |
| 243 | img.draggable = false; |
| 244 | applyItemIcon(img, stack, itemAssetPathForStack(stack)); |
| 245 | btn.append(img); |
| 246 | if (line.quantity > 1) |
| 247 | { |
| 248 | const qty = document.createElement("span"); |
| 249 | qty.className = "qty"; |
| 250 | qty.textContent = formatQuantity(line.quantity); |
| 251 | btn.append(qty); |
| 252 | } |
| 253 | if (flash === "remove") |
| 254 | { |
| 255 | btn.disabled = true; |
| 256 | window.setTimeout(() => btn.remove(), FLASH_MS); |
| 257 | return btn; |
| 258 | } |
| 259 | if (!theirs && !youAccepted) |
| 260 | { |
| 261 | btn.addEventListener("click", (event) => |
| 262 | { |
| 263 | suppressWorldClick(event); |
| 264 | socket.send({ |
| 265 | type: MessageType.tradeOfferRemove, |
| 266 | bagSlotIndex: line.bagSlotIndex |
| 267 | }); |
| 268 | }); |
| 269 | } |
| 270 | else |
| 271 | { btn.disabled = true; } |
| 272 | return btn; |
| 273 | } |
| 274 | |
| 275 | function renderOfferGrid (el, lines, { theirs = false, addedKeys = null, redKeys = null, removedLines = null } = {}) |
| 276 | { |
| 277 | if (!el) |
| 278 | { return; } |
| 279 | el.replaceChildren(); |
| 280 | if (!lines.length && !(removedLines?.length)) |
| 281 | { |
| 282 | const empty = document.createElement("p"); |
| 283 | empty.className = "hint"; |
| 284 | empty.textContent = theirs ? "Nothing yet." : "Click bag items to offer them."; |
| 285 | el.append(empty); |
| 286 | return; |
| 287 | } |
| 288 | for (const line of lines) |
| 289 | { |
| 290 | const key = offerLineKey(line); |
| 291 | let flash = null; |
| 292 | if (addedKeys?.has(key)) |
| 293 | { flash = "add"; } |
| 294 | else if (redKeys?.has(key)) |
| 295 | { flash = "down"; } |
| 296 | el.append(makeOfferSlot(line, { theirs, flash })); |
| 297 | } |
| 298 | for (const line of removedLines ?? []) |
| 299 | { el.append(makeOfferSlot(line, { theirs, flash: "remove" })); } |
| 300 | } |
| 301 | |
| 302 | function render () |
| 303 | { |
| 304 | if (!open) |
| 305 | { return; } |
| 306 | if (partnerEl) |
| 307 | { partnerEl.textContent = partnerName ? `Trading with ${partnerName}` : "Trade"; } |
| 308 | renderOfferGrid(giveGrid, yourOffer, { theirs: false }); |
| 309 | renderOfferGrid(receiveGrid, theirOffer, { theirs: true }); |
| 310 | syncAcceptButton(); |
| 311 | syncStatus(); |
| 312 | } |
| 313 | |
| 314 | function applyState (message, { initial = false } = {}) |
| 315 | { |
| 316 | const prevYours = yourOffer; |
| 317 | const prevTheirs = theirOffer; |
| 318 | youAccepted = !!message.youAccepted; |
| 319 | theyAccepted = !!message.theyAccepted; |
| 320 | yourOffer = message.yourOffer ?? []; |
| 321 | theirOffer = message.theirOffer ?? []; |
| 322 | |
| 323 | const yoursDiff = diffOfferLines(prevYours, yourOffer); |
| 324 | const theirsDiff = diffOfferLines(prevTheirs, theirOffer); |
| 325 | const offersChanged = !initial && (yoursDiff.changed || theirsDiff.changed); |
| 326 | |
| 327 | if (!open) |
| 328 | { return; } |
| 329 | if (partnerEl) |
| 330 | { partnerEl.textContent = partnerName ? `Trading with ${partnerName}` : "Trade"; } |
| 331 | renderOfferGrid(giveGrid, yourOffer, { |
| 332 | theirs: false, |
| 333 | addedKeys: yoursDiff.addedKeys, |
| 334 | redKeys: yoursDiff.redKeys, |
| 335 | removedLines: initial ? [] : yoursDiff.removedLines |
| 336 | }); |
| 337 | renderOfferGrid(receiveGrid, theirOffer, { |
| 338 | theirs: true, |
| 339 | addedKeys: theirsDiff.addedKeys, |
| 340 | redKeys: theirsDiff.redKeys, |
| 341 | removedLines: initial ? [] : theirsDiff.removedLines |
| 342 | }); |
| 343 | if (offersChanged) |
| 344 | { lockAccept(); } |
| 345 | else |
| 346 | { |
| 347 | syncAcceptButton(); |
| 348 | syncStatus(); |
| 349 | } |
| 350 | onTradeOpenChanged?.(true); |
| 351 | } |
| 352 | |
| 353 | function openTrade (message) |
| 354 | { |
| 355 | open = true; |
| 356 | partnerName = message.partnerName ?? "Player"; |
| 357 | partnerEntityId = message.partnerEntityId | 0; |
| 358 | yourOffer = []; |
| 359 | theirOffer = []; |
| 360 | youAccepted = false; |
| 361 | theyAccepted = false; |
| 362 | acceptUnlockAt = 0; |
| 363 | if (acceptUnlockTimer != null) |
| 364 | { |
| 365 | window.clearTimeout(acceptUnlockTimer); |
| 366 | acceptUnlockTimer = null; |
| 367 | } |
| 368 | if (panel) |
| 369 | { panel.hidden = false; } |
| 370 | // Backdrop is visual-only (pointer-events: none) so the bag stays clickable. |
| 371 | if (backdrop) |
| 372 | { backdrop.hidden = false; } |
| 373 | setBagRaised(true); |
| 374 | ensureBagOpen?.(); |
| 375 | applyState(message, { initial: true }); |
| 376 | } |
| 377 | |
| 378 | function sendTradeRequest (targetEntityId) |
| 379 | { |
| 380 | socket.send({ |
| 381 | type: MessageType.tradeRequest, |
| 382 | targetEntityId: targetEntityId | 0 |
| 383 | }); |
| 384 | } |
| 385 | |
| 386 | function requestTrade (targetEntityId) |
| 387 | { |
| 388 | clearPendingActions?.(); |
| 389 | const id = targetEntityId | 0; |
| 390 | const local = getLocalEntity?.(); |
| 391 | const partner = getEntity?.(id); |
| 392 | if (!local || !partner) |
| 393 | { |
| 394 | sendTradeRequest(id); |
| 395 | return; |
| 396 | } |
| 397 | if (isAdjacentTile(local.tileX, local.tileY, partner.tileX, partner.tileY) |
| 398 | || (local.tileX === partner.tileX && local.tileY === partner.tileY)) |
| 399 | { |
| 400 | sendTradeRequest(id); |
| 401 | return; |
| 402 | } |
| 403 | setPendingTradeRequest?.(id); |
| 404 | approachAdjacentTile?.(partner.tileX, partner.tileY); |
| 405 | } |
| 406 | |
| 407 | function respondAccept (invite) |
| 408 | { |
| 409 | const local = getLocalEntity?.(); |
| 410 | const partner = getEntity?.(invite.fromEntityId); |
| 411 | if (!local || !partner) |
| 412 | { |
| 413 | socket.send({ |
| 414 | type: MessageType.tradeRespondInvite, |
| 415 | inviteId: invite.inviteId, |
| 416 | accept: true |
| 417 | }); |
| 418 | return; |
| 419 | } |
| 420 | if (isAdjacentTile(local.tileX, local.tileY, partner.tileX, partner.tileY) |
| 421 | || (local.tileX === partner.tileX && local.tileY === partner.tileY)) |
| 422 | { |
| 423 | socket.send({ |
| 424 | type: MessageType.tradeRespondInvite, |
| 425 | inviteId: invite.inviteId, |
| 426 | accept: true |
| 427 | }); |
| 428 | return; |
| 429 | } |
| 430 | setPendingTradeAccept?.(invite); |
| 431 | approachAdjacentTile?.(partner.tileX, partner.tileY); |
| 432 | } |
| 433 | |
| 434 | function showInvite (message) |
| 435 | { |
| 436 | const inviteId = message.inviteId; |
| 437 | inviteToasts.get(inviteId)?.dismiss?.(); |
| 438 | const fromName = message.fromName || "Someone"; |
| 439 | const handle = toasts?.show?.( |
| 440 | `${fromName} wishes to trade with you`, |
| 441 | { |
| 442 | // Stay until Accept / Reject / server tradeInviteExpired (clock-safe). |
| 443 | sticky: true, |
| 444 | actions: [ |
| 445 | { |
| 446 | label: "Accept", |
| 447 | onClick: () => |
| 448 | { |
| 449 | inviteToasts.delete(inviteId); |
| 450 | respondAccept(message); |
| 451 | } |
| 452 | }, |
| 453 | { |
| 454 | label: "Reject", |
| 455 | onClick: () => |
| 456 | { |
| 457 | inviteToasts.delete(inviteId); |
| 458 | socket.send({ |
| 459 | type: MessageType.tradeRespondInvite, |
| 460 | inviteId, |
| 461 | accept: false |
| 462 | }); |
| 463 | } |
| 464 | } |
| 465 | ] |
| 466 | } |
| 467 | ); |
| 468 | if (handle) |
| 469 | { inviteToasts.set(inviteId, handle); } |
| 470 | } |
| 471 | |
| 472 | function offerBagSlot (slotIndex, slot) |
| 473 | { |
| 474 | if (!open || youAccepted || !slot) |
| 475 | { return false; } |
| 476 | const maxQty = Math.max(1, slot.quantity | 0 || 1); |
| 477 | if (maxQty <= 1) |
| 478 | { |
| 479 | socket.send({ |
| 480 | type: MessageType.tradeOfferSet, |
| 481 | bagSlotIndex: slotIndex, |
| 482 | quantity: 1 |
| 483 | }); |
| 484 | return true; |
| 485 | } |
| 486 | pendingQty = { bagSlotIndex: slotIndex, maxQty, name: itemDisplayName(slot) }; |
| 487 | if (qtyName) |
| 488 | { qtyName.textContent = pendingQty.name; } |
| 489 | if (qtyInput) |
| 490 | { |
| 491 | qtyInput.min = "1"; |
| 492 | qtyInput.max = String(maxQty); |
| 493 | qtyInput.value = String(maxQty); |
| 494 | } |
| 495 | if (qtyPanel) |
| 496 | { qtyPanel.hidden = false; } |
| 497 | if (qtyBackdrop) |
| 498 | { qtyBackdrop.hidden = false; } |
| 499 | qtyInput?.focus(); |
| 500 | qtyInput?.select(); |
| 501 | return true; |
| 502 | } |
| 503 | |
| 504 | acceptBtn?.addEventListener("mousedown", suppressWorldClick); |
| 505 | cancelBtn?.addEventListener("mousedown", suppressWorldClick); |
| 506 | panel?.addEventListener("mousedown", suppressWorldClick); |
| 507 | qtyPanel?.addEventListener("mousedown", suppressWorldClick); |
| 508 | qtyBackdrop?.addEventListener("mousedown", suppressWorldClick); |
| 509 | acceptBtn?.addEventListener("click", (event) => |
| 510 | { |
| 511 | suppressWorldClick(event); |
| 512 | if (acceptLocked()) |
| 513 | { return; } |
| 514 | socket.send({ type: MessageType.tradeAccept }); |
| 515 | }); |
| 516 | cancelBtn?.addEventListener("click", (event) => |
| 517 | { |
| 518 | suppressWorldClick(event); |
| 519 | socket.send({ type: MessageType.tradeCancel }); |
| 520 | }); |
| 521 | qtyClose?.addEventListener("click", (event) => |
| 522 | { |
| 523 | suppressWorldClick(event); |
| 524 | closeQty(); |
| 525 | }); |
| 526 | qtyBackdrop?.addEventListener("click", (event) => |
| 527 | { |
| 528 | suppressWorldClick(event); |
| 529 | closeQty(); |
| 530 | }); |
| 531 | qtyConfirm?.addEventListener("click", (event) => |
| 532 | { |
| 533 | suppressWorldClick(event); |
| 534 | if (!pendingQty) |
| 535 | { return; } |
| 536 | const qty = Math.max(1, Math.min(pendingQty.maxQty, qtyInput?.valueAsNumber || 1)); |
| 537 | socket.send({ |
| 538 | type: MessageType.tradeOfferSet, |
| 539 | bagSlotIndex: pendingQty.bagSlotIndex, |
| 540 | quantity: qty |
| 541 | }); |
| 542 | closeQty(); |
| 543 | }); |
| 544 | |
| 545 | return { |
| 546 | isBlocking, |
| 547 | isOpen, |
| 548 | listSoftClaims, |
| 549 | requestTrade, |
| 550 | offerBagSlot, |
| 551 | inventoryLocked: () => (open && youAccepted) || !!(qtyPanel && !qtyPanel.hidden), |
| 552 | flushPendingRequest (targetEntityId) |
| 553 | { |
| 554 | sendTradeRequest(targetEntityId); |
| 555 | }, |
| 556 | flushPendingAccept (invite) |
| 557 | { |
| 558 | socket.send({ |
| 559 | type: MessageType.tradeRespondInvite, |
| 560 | inviteId: invite.inviteId, |
| 561 | accept: true |
| 562 | }); |
| 563 | }, |
| 564 | handleMessage (message) |
| 565 | { |
| 566 | if (message.type === MessageType.tradeInvite) |
| 567 | { |
| 568 | showInvite(message); |
| 569 | return true; |
| 570 | } |
| 571 | if (message.type === MessageType.tradeInviteExpired) |
| 572 | { |
| 573 | inviteToasts.get(message.inviteId)?.dismiss?.(); |
| 574 | inviteToasts.delete(message.inviteId); |
| 575 | return true; |
| 576 | } |
| 577 | if (message.type === MessageType.tradeOpen) |
| 578 | { |
| 579 | openTrade(message); |
| 580 | return true; |
| 581 | } |
| 582 | if (message.type === MessageType.tradeState) |
| 583 | { |
| 584 | if (open) |
| 585 | { applyState(message); } |
| 586 | return true; |
| 587 | } |
| 588 | if (message.type === MessageType.tradeClosed) |
| 589 | { |
| 590 | closeTradeUi(); |
| 591 | return true; |
| 592 | } |
| 593 | return false; |
| 594 | }, |
| 595 | close: closeTradeUi |
| 596 | }; |
| 597 | } |