All files / src/views ConversationPage.vue

95.03% Statements 134/141
88.99% Branches 97/109
92.1% Functions 35/38
97.6% Lines 122/125

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501    1x           1x 1x                   1x                                       1x                         38x               24x           1x             1x 1x                                                                                                               7x                 1x     150x                             1x                                       35x 35x 35x 35x 35x 35x             35x   77x 92x 117x 115x 35x 115x   35x 59x   35x   115x           152x     35x 35x   35x 60x   35x 35x       35x   35x 35x 35x               35x     37x     37x       2x 2x 2x     1x                     6x 5x 5x 4x   3x 3x   3x   3x 3x 3x 3x         7x 7x 6x 6x 6x 2x 2x   2x 1x     4x 4x 4x 1x 3x 1x   2x     4x 2x     6x           6x 6x 6x   1x 1x   6x         2x 2x           1x 1x 1x 1x         2x 2x 2x 2x 2x   2x 1x   1x   2x         1x 1x 1x 1x 1x                 35x 57x 4x 57x 57x 1x           35x 1x 1x           35x 35x     35x       34x 34x 34x   1x 1x                                                                                                                                                                                                          
<template>
  <PageLayout :title="t('messages.title')" scrollable class="conversation-page">
    <div class="conversation-container">
      <div v-if="details" class="conversation-header">
        <UserAvatar
          :picture-key="details.otherUserProfilePicture"
          class="conversation-header-avatar"
        />
        <div class="flex-grow-1">
          <div class="conversation-header-name">{{ pageTitle }}</div>
          <div v-if="details.otherUserNickname && details.otherUserName" class="text-muted small">
            @{{ details.otherUserNickname }}
          </div>
        </div>
        <button
          v-if="canReport"
          type="button"
          class="btn btn-sm btn-outline-secondary conversation-report"
          :title="t('report.title.conversation')"
          @click="reporting = true"
        >
          <font-awesome-icon icon="fa-solid fa-flag" class="me-1" />
          {{ t('report.action') }}
        </button>
        <button
          v-if="details.isBlockedByCurrentUser"
          type="button"
          class="btn btn-sm btn-outline-secondary"
          :disabled="actionInFlight"
          @click="unblock"
        >
          <font-awesome-icon icon="fa-solid fa-user-check" class="me-1" />
          {{ t('messages.unblock') }}
        </button>
        <button
          v-else
          type="button"
          class="btn btn-sm btn-outline-danger"
          :disabled="actionInFlight"
          @click="confirmBlock.open = true"
        >
          <font-awesome-icon icon="fa-solid fa-user-slash" class="me-1" />
          {{ t('messages.block') }}
        </button>
      </div>
 
      <div v-if="loading && messages.length === 0" class="conversation-middle">
        <LoadingSpinner :grid="false" />
      </div>
 
      <div v-else-if="!loading && messages.length === 0" class="conversation-middle">
        <EmptyState :grid="false">
          {{ t('messages.noMessages') }}
        </EmptyState>
      </div>
 
      <div v-else ref="threadRef" class="message-thread" @scroll="handleScroll">
        <div v-if="showLoadingMoreIndicator" class="text-center text-muted small py-2">
          <span class="spinner-border spinner-border-sm" role="status" />
        </div>
        <div
          v-for="message in messages"
          :key="message.id"
          class="message-row"
          :class="{ 'message-row-own': message.senderId === authStore.userId }"
        >
          <div class="message-bubble">
            {{ message.body }}
          </div>
        </div>
      </div>
 
      <div v-if="sendState === 'request_received'" class="conversation-notice request-actions">
        <p class="mb-2">{{ withName(t('messages.requestReceived')) }}</p>
        <div class="d-flex gap-2 flex-wrap">
          <button
            type="button"
            class="btn btn-primary"
            :disabled="actionInFlight"
            @click="acceptRequest"
          >
            <font-awesome-icon icon="fa-solid fa-check" class="me-2" />
            {{ t('messages.accept') }}
          </button>
          <button
            v-if="details?.status === 'pending'"
            type="button"
            class="btn btn-outline-secondary"
            :disabled="actionInFlight"
            @click="declineRequest"
          >
            <font-awesome-icon icon="fa-solid fa-times" class="me-2" />
            {{ t('messages.decline') }}
          </button>
          <button
            type="button"
            class="btn btn-outline-danger"
            :disabled="actionInFlight"
            @click="confirmBlock.open = true"
          >
            <font-awesome-icon icon="fa-solid fa-user-slash" class="me-2" />
            {{ t('messages.block') }}
          </button>
        </div>
      </div>
 
      <div v-else-if="sendState === 'awaiting_acceptance'" class="conversation-notice text-muted">
        <font-awesome-icon icon="fa-solid fa-hourglass-half" class="me-2" />
        {{ withName(t('messages.awaitingAcceptance')) }}
      </div>
 
      <div v-else-if="sendState === 'blocked_by_you'" class="conversation-notice text-muted">
        <font-awesome-icon icon="fa-solid fa-user-slash" class="me-2" />
        {{ withName(t('messages.youBlockedUser')) }}
      </div>
 
      <div v-else-if="sendState === 'unavailable'" class="conversation-notice text-muted">
        {{ t('messages.cannotMessage') }}
      </div>
 
      <div
        v-if="sendState === 'request_first_message'"
        class="conversation-notice request-hint text-muted small"
      >
        <font-awesome-icon icon="fa-solid fa-envelope" class="me-2" />
        {{ withName(t('messages.requestHint')) }}
      </div>
 
      <form v-if="canCompose" class="compose-bar" @submit.prevent="submit">
        <textarea
          v-model="draft"
          class="form-control"
          rows="2"
          :placeholder="t('messages.composePlaceholder')"
          name="message"
          @keydown.enter.exact.prevent="submit"
        />
        <button type="submit" class="btn btn-primary" :disabled="!draft.trim() || sending">
          <font-awesome-icon icon="fa-solid fa-paper-plane" />
          <span class="d-none d-md-inline ms-2">{{ t('messages.send') }}</span>
        </button>
      </form>
    </div>
  </PageLayout>
 
  <ConfirmModal
    :is-open="confirmBlock.open"
    :title="withName(t('messages.blockTitle'))"
    :message="t('messages.blockWarning')"
    :confirm-label="t('messages.block')"
    variant="danger"
    @confirm="block"
    @cancel="confirmBlock.open = false"
  />
 
  <ReportModal
    :target="reporting ? { type: 'conversation', conversationId } : null"
    @close="reporting = false"
  />
</template>
 
<script setup lang="ts">
// @implements UC-DM-005.1, UC-DM-006.1, UC-DM-007.1, UC-DM-009.1, UC-DM-010.1, UC-REPORT-002.1
import { ref, computed, onMounted, nextTick, watch, reactive } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { storeToRefs } from 'pinia'
import PageLayout from '@/components/PageLayout.vue'
import ConfirmModal from '@/components/ConfirmModal.vue'
import ReportModal from '@/components/ReportModal.vue'
import LoadingSpinner from '@/components/LoadingSpinner.vue'
import EmptyState from '@/components/EmptyState.vue'
import UserAvatar from '@/components/UserAvatar.vue'
import { useUILanguage } from '@/composables/useUILanguage'
import { useMessagesStore } from '@/stores/messages'
import { useAuthStore } from '@/stores/auth'
import { useToastStore } from '@/stores/toast'
 
const route = useRoute()
const router = useRouter()
const { t } = useUILanguage()
const messagesStore = useMessagesStore()
const authStore = useAuthStore()
const toastStore = useToastStore()
const {
  conversationDetails,
  messagesByConversation,
  messagesLoading: loading,
  messagesNextToken,
  realtimeConnectCount
} = storeToRefs(messagesStore)
 
const conversationId = computed(() => route.params.conversationId as string)
const messages = computed(() => messagesByConversation.value[conversationId.value] ?? [])
const details = computed(() => conversationDetails.value[conversationId.value])
const sendState = computed(() => details.value?.sendState)
const canCompose = computed(
  () => sendState.value === 'ok' || sendState.value === 'request_first_message'
)
const pageTitle = computed(
  () => details.value?.otherUserName || details.value?.otherUserNickname || t('messages.title')
)
const otherUserLabel = computed(
  () =>
    details.value?.otherUserName ||
    (details.value?.otherUserNickname ? `@${details.value.otherUserNickname}` : '') ||
    t('messages.thisUser')
)
 
function withName(text: string) {
  return text.replace('{name}', otherUserLabel.value)
}
 
const actionInFlight = ref(false)
const reporting = ref(false)
// Something the other participant wrote is what gets reported (a message request especially)
const canReport = computed(() =>
  messages.value.some((message) => message.senderId !== authStore.userId)
)
const confirmBlock = reactive({ open: false })
const hasMoreHistory = computed(() => !!messagesNextToken.value[conversationId.value])
// The big centered LoadingSpinner already covers the "no messages loaded
// yet" case — this smaller inline one is only for loading an older page
// while some messages are already showing.
const showLoadingMoreIndicator = computed(() => loading.value && messages.value.length > 0)
 
const draft = ref('')
const sending = ref(false)
const threadRef = ref<HTMLElement | null>(null)
// Guards handleScroll against the initial render: a freshly-mounted
// .message-thread starts at scrollTop=0 (browser default) until
// scrollToBottom() actually applies, and — since that wasn't previously
// awaited — a scroll event landing in that window could look like "user
// scrolled to the top" and immediately trigger a history load. Nothing is
// allowed to trigger loadMoreMessages until the initial scroll-to-bottom
// has genuinely completed.
const readyForScrollLoading = ref(false)
 
async function scrollToBottom() {
  await nextTick()
  // jsdom (component tests) doesn't implement scrollTo — guard rather than
  // let it throw, since scrolling is a non-essential visual nicety here.
  threadRef.value?.scrollTo?.({ top: threadRef.value?.scrollHeight ?? 0 })
}
 
function isNearBottom(): boolean {
  Iif (!threadRef.value) return true
  const { scrollTop, scrollHeight, clientHeight } = threadRef.value
  return scrollHeight - (scrollTop + clientHeight) < 150
}
 
const SCROLL_TOP_LOAD_THRESHOLD = 80
 
/**
 * Loads an older page of history when the user scrolls near the top —
 * "infinite scroll upward". Older messages are prepended, which would
 * otherwise yank the viewport (the browser doesn't auto-adjust scrollTop
 * when content is inserted above what's visible), so the scroll position
 * is explicitly re-anchored to the message the user was looking at, based
 * on the container's height delta before/after the new page renders.
 */
async function handleScroll() {
  if (!readyForScrollLoading.value) return
  Iif (!threadRef.value) return
  if (threadRef.value.scrollTop > SCROLL_TOP_LOAD_THRESHOLD) return
  if (loading.value || !hasMoreHistory.value) return
 
  const previousScrollHeight = threadRef.value.scrollHeight
  const previousScrollTop = threadRef.value.scrollTop
 
  await messagesStore.loadMoreMessages(conversationId.value)
 
  await nextTick()
  Eif (threadRef.value) {
    const newScrollHeight = threadRef.value.scrollHeight
    threadRef.value.scrollTop = previousScrollTop + (newScrollHeight - previousScrollHeight)
  }
}
 
async function submit() {
  const body = draft.value.trim()
  if (!body || sending.value) return
  sending.value = true
  try {
    await messagesStore.sendMessage(conversationId.value, body)
    draft.value = ''
    await scrollToBottom()
    // A request's one message is sent: the thread now waits for acceptance
    if (sendState.value === 'request_first_message') {
      await messagesStore.fetchConversation(conversationId.value)
    }
  } catch (error: any) {
    console.error('Failed to send message:', error)
    const status = error?.response?.status
    if (status === 429) {
      toastStore.error(t('messages.requestLimitReached'))
    } else if (error?.response?.data?.error === 'ACCOUNT_RESTRICTED') {
      toastStore.error(t('report.restricted'))
    } else {
      toastStore.error(t('messages.sendError'))
    }
    // The conversation may have changed underneath (a block, a request)
    if (status === 403 || status === 409) {
      await messagesStore.fetchConversation(conversationId.value).catch(() => {})
    }
  } finally {
    sending.value = false
  }
}
 
/** Runs a request/block action, reporting a failure with `errorKey`. */
async function runAction(action: () => Promise<void>, errorKey: string) {
  actionInFlight.value = true
  try {
    await action()
  } catch (error) {
    console.error(`${errorKey}:`, error)
    toastStore.error(t(errorKey))
  } finally {
    actionInFlight.value = false
  }
}
 
function acceptRequest() {
  return runAction(
    () => messagesStore.acceptRequest(conversationId.value),
    'messages.requestActionError'
  )
}
 
function declineRequest() {
  return runAction(async () => {
    await messagesStore.declineRequest(conversationId.value)
    toastStore.success(t('messages.requestDeclined'))
    router.push({ name: 'inbox', query: { folder: 'requests' } })
  }, 'messages.requestActionError')
}
 
function block() {
  confirmBlock.open = false
  const current = details.value
  Iif (!current) return
  return runAction(async () => {
    await messagesStore.blockUser(current.otherUserId)
    // Blocking from a request also declines it
    if (current.sendState === 'request_received' && current.status === 'pending') {
      await messagesStore.declineRequest(conversationId.value)
    } else {
      await messagesStore.fetchConversation(conversationId.value)
    }
    toastStore.success(withName(t('messages.blockedToast')))
  }, 'messages.blockError')
}
 
function unblock() {
  const current = details.value
  Iif (!current) return
  return runAction(async () => {
    await messagesStore.unblockUser(current.otherUserId)
    await messagesStore.fetchConversation(conversationId.value)
  }, 'messages.blockError')
}
 
// Only auto-scroll when a message was appended at the end (a live push, or
// this user's own send) — not when older history was just prepended at the
// start (handleScroll already re-anchors the scroll position for that
// case), and not when the reader has scrolled up to read older messages
// and a new one arrives off-screen below.
watch(messages, (newMessages, oldMessages) => {
  if (oldMessages.length === 0 || newMessages.length === 0) return
  const appendedAtEnd = newMessages.at(-1)?.id !== oldMessages.at(-1)?.id
  const prependedAtStart = newMessages[0]?.id !== oldMessages[0]?.id
  if (appendedAtEnd && !prependedAtStart && isNearBottom()) {
    scrollToBottom()
  }
})
 
// A push sent before this client's socket finished (re)connecting is never
// replayed, so recover anything missed once the connection is up.
watch(realtimeConnectCount, async () => {
  try {
    await messagesStore.syncLatestMessages(conversationId.value)
  } catch (error) {
    console.error('Failed to re-sync conversation after reconnect:', error)
  }
})
 
onMounted(async () => {
  try {
    // The other participant and what this user can do here (compose, answer
    // a request, a block…) come with the conversation itself.
    await Promise.all([
      messagesStore.fetchConversation(conversationId.value),
      messagesStore.fetchMessages(conversationId.value)
    ])
    await messagesStore.markRead(conversationId.value)
    await scrollToBottom()
    readyForScrollLoading.value = true
  } catch (error) {
    console.error('Failed to load conversation:', error)
    toastStore.error(t('messages.conversationLoadError'))
  }
})
</script>
 
<style scoped>
/* PageLayout's own `scrollable` mode wraps the whole default slot in one
   scrolling container — not what we want here, since only the message list
   itself should scroll while the header and compose bar stay put. This
   fills that container's height and re-partitions it into fixed/scroll/fixed
   rows itself, so the outer wrapper never needs to scroll at all. */
.conversation-container {
  display: flex;
  flex-direction: column;
  height: 100%;
}
 
.conversation-header {
  display: flex;
  align-items: center;
  gap: 0.75rem;
  padding: 0.75rem 2rem;
  border-bottom: 1px solid var(--bw-border);
  flex-shrink: 0;
}
 
.conversation-header-name {
  font-weight: 600;
}
 
.conversation-middle {
  flex: 1;
  min-height: 0;
  display: flex;
  align-items: center;
  justify-content: center;
}
 
.message-thread {
  flex: 1;
  min-height: 0;
  overflow-y: auto;
  padding: 1rem 2rem;
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}
 
.message-row {
  display: flex;
  justify-content: flex-start;
}
 
.message-row-own {
  justify-content: flex-end;
}
 
.message-bubble {
  max-width: 70%;
  padding: 0.5rem 0.9rem;
  border-radius: 1rem;
  background: var(--bw-surface-muted);
  border: 1px solid var(--bw-border);
  white-space: pre-wrap;
  overflow-wrap: break-word;
}
 
.message-row-own .message-bubble {
  background: var(--bs-primary, #0d6efd);
  color: #fff;
  border-color: transparent;
}
 
.conversation-notice {
  padding: 1rem 2rem;
  border-top: 1px solid var(--bw-border);
  flex-shrink: 0;
}
 
.compose-bar {
  display: flex;
  gap: 0.5rem;
  align-items: center;
  padding: 1rem 2rem;
  border-top: 1px solid var(--bw-border);
  flex-shrink: 0;
}
 
.compose-bar textarea {
  resize: none;
}
 
@media (max-width: 767px) {
  .conversation-header,
  .message-thread,
  .conversation-notice,
  .compose-bar {
    padding: 1rem;
  }
}
</style>