All files / src/components ItemCommentsSidebar.vue

93.97% Statements 78/83
93.25% Branches 83/89
86.36% Functions 19/22
96% Lines 72/75

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  280x                 1x     80x     5x                                         5x                                       5x                                   5x 5x 2x                                                   9x                                       80x                                       146x                         146x           146x 146x 146x 146x   146x 146x 40x           146x 12x 12x 12x 12x       146x 13x 13x   146x 13x 13x         146x 146x 146x     10x 10x   2x   10x       146x 159x   13x   10x 10x 13x         4x 4x 4x 4x 3x   1x     4x     146x 250x   250x 250x 208x 208x   42x 41x 42x 42x   8x             2x 2x   1x         3x 3x 1x 1x     2x 1x   2x        
<template>
  <BaseFormSidebar
    :is-open="isOpen"
    storage-key="item-comments-sidebar"
    :title="t('comment.title')"
    icon="fa-solid fa-comment"
    panel-width="560px"
    @close="$emit('close')"
  >
    <template #footer>
      <button type="button" class="btn btn-secondary" @click="$emit('close')">
        <font-awesome-icon icon="fa-solid fa-times" class="me-1" />
        {{ t('common.close') }}
      </button>
    </template>
 
    <div class="item-comments">
      <div v-if="commentsStore.blocked" class="alert alert-warning mb-0" role="status">
        {{ t(packId ? 'store.commentBlockedNotice' : 'comment.blockedNotice') }}
      </div>
      <CommentComposer
        v-else
        :key="rootDraftKey"
        :label="t('comment.composerLabel')"
        :placeholder="t('comment.placeholder')"
        :submit-label="t('comment.post')"
        :on-submit="submitRoot"
        :draft-key="rootDraftKey"
      />
 
      <div
        v-if="commentsStore.quotaRequired"
        ref="quotaAlertRef"
        class="quota-alert alert mt-3"
        :class="quotaMet ? 'alert-success' : 'alert-warning'"
        role="alert"
      >
        <p class="mb-2">{{ quotaMet ? t('moderation.quotaReadyToPost') : quotaAlertText }}</p>
        <div
          class="progress mb-2"
          role="progressbar"
          :aria-valuenow="
            Math.min(commentsStore.quotaRequired.have, commentsStore.quotaRequired.required)
          "
          aria-valuemin="0"
          :aria-valuemax="commentsStore.quotaRequired.required"
          :aria-label="t('moderation.quotaProgress')"
        >
          <div
            class="progress-bar"
            :class="quotaMet ? 'bg-success' : 'bg-primary'"
            :style="{ width: quotaPercent + '%' }"
          />
        </div>
 
        <!-- Review right here: what is being written stays where it is -->
        <template v-if="!quotaMet">
          <p class="small mb-2">{{ t('moderation.inlineReviewHelp') }}</p>
          <div v-if="moderationStore.loadingTasks && !inlineTask" class="text-center small py-2">
            <span class="spinner-border spinner-border-sm me-2" aria-hidden="true" />
            {{ t('common.loading') }}
          </div>
          <ModerationReviewCard
            v-else-if="inlineTask"
            :task="inlineTask"
            :disabled="!!moderationStore.voting"
            @vote="castInlineVote"
          />
          <p v-else-if="inlineTasksLoaded" class="small mb-0 inline-review-empty">
            {{ t('moderation.nothingLeftRetry') }}
          </p>
        </template>
      </div>
 
      <section v-if="commentsStore.mine.length > 0" class="my-pending mt-3">
        <h4 class="h6">{{ t('moderation.myPendingTitle') }}</h4>
        <ul class="list-unstyled mb-0">
          <PendingCommentRow
            v-for="comment in commentsStore.mine"
            :key="comment.id"
            :comment="comment"
            @count-change="$emit('count-change', $event)"
          />
        </ul>
      </section>
 
      <div v-if="roots.error && !roots.loaded" class="alert alert-danger mt-3" role="alert">
        {{ roots.error }}
      </div>
 
      <div v-if="roots.loading && !roots.loaded" class="text-center text-muted py-4">
        <span class="spinner-border spinner-border-sm me-2" aria-hidden="true" />
        {{ t('common.loading') }}
      </div>
 
      <p
        v-else-if="roots.loaded && roots.comments.length === 0"
        class="text-muted text-center py-4"
      >
        {{ t('comment.empty') }}
      </p>
 
      <ul v-else class="list-unstyled mt-3 mb-0">
        <CommentNode
          v-for="comment in roots.comments"
          :key="comment.id"
          :comment="comment"
          :level="0"
          :can-manage="canManage"
          @count-change="$emit('count-change', $event)"
        />
      </ul>
 
      <div v-if="roots.nextToken" class="text-center mt-2">
        <button
          type="button"
          class="btn btn-outline-secondary btn-sm"
          :disabled="roots.loading"
          @click="loadMore"
        >
          {{ t('common.loadMore') }}
        </button>
      </div>
    </div>
  </BaseFormSidebar>
</template>
 
<script setup lang="ts">
// @implements UC-COMMENT-002.1, UC-COMMENT-004.1, UC-COMMENT-007.1, UC-MOD-001.1, UC-MOD-005.1, UC-MOD-013.1, UC-STORE-009.1
// The comments of an item, or of a store pack when `packId` is given.
import { computed, nextTick, ref, watch } from 'vue'
import BaseFormSidebar from '@/components/BaseFormSidebar.vue'
import CommentComposer from '@/components/CommentComposer.vue'
import CommentNode from '@/components/CommentNode.vue'
import PendingCommentRow from '@/components/PendingCommentRow.vue'
import ModerationReviewCard from '@/components/ModerationReviewCard.vue'
import { useUILanguage } from '@/composables/useUILanguage'
import { useCommentsStore } from '@/stores/comments'
import { useModerationStore, type ModerationVote } from '@/stores/moderation'
import { useToastStore } from '@/stores/toast'
import { getErrorMessage } from '@/utils/errors'
import { commentDraftKey, packCommentDraftKey } from '@/utils/commentDraft'
 
const props = withDefaults(
  defineProps<{
    isOpen: boolean
    // The thread: an item (entityId and itemId), or a store pack (packId)
    entityId?: string
    itemId?: string
    packId?: string
    // The user manages the entity's or pack's comments (delete anybody's, block authors)
    canManage?: boolean
  }>(),
  { canManage: false, entityId: undefined, itemId: undefined, packId: undefined }
)
 
const emit = defineEmits<{
  close: []
  // Change to the thread's comment counter (+1 posted, -1 deleted, 0 awaiting review)
  'count-change': [delta: number]
}>()
 
const { t } = useUILanguage()
const commentsStore = useCommentsStore()
const moderationStore = useModerationStore()
const toastStore = useToastStore()
 
const roots = computed(() => commentsStore.listFor(null))
const rootDraftKey = computed(() =>
  props.packId
    ? packCommentDraftKey(props.packId, null)
    : commentDraftKey(props.entityId ?? '', props.itemId ?? '', null)
)
 
// Publishing on a public entity or a pack costs review points: say how many are missing
const quotaAlertText = computed(() => {
  const quota = commentsStore.quotaRequired
  Iif (!quota) return ''
  const missing = Math.max(1, quota.required - quota.have)
  return (
    missing === 1 ? t('moderation.quotaRequiredDetailOne') : t('moderation.quotaRequiredDetail')
  ).replace('{count}', String(missing))
})
const quotaPercent = computed(() => {
  const quota = commentsStore.quotaRequired
  return quota ? Math.min(100, Math.round((quota.have / quota.required) * 100)) : 0
})
const quotaMet = computed(() => {
  const quota = commentsStore.quotaRequired
  return !!quota && quota.have >= quota.required
})
 
// Inline review: when posting needs more reviews, contents to review are shown
// in the quota alert itself, so the comment being written is never left behind
const quotaAlertRef = ref<HTMLElement | null>(null)
const inlineTasksLoaded = ref(false)
const inlineTask = computed(() => moderationStore.tasks[0] ?? null)
 
async function loadInlineTasks() {
  try {
    await moderationStore.fetchTasks()
  } catch (err) {
    toastStore.error(getErrorMessage(err, t('moderation.loadError'), t))
  } finally {
    inlineTasksLoaded.value = true
  }
}
 
watch(
  () => commentsStore.quotaRequired,
  async (quota, previous) => {
    if (!quota || previous) return
    // The refusal may come from a reply composer far down the thread
    await nextTick()
    quotaAlertRef.value?.scrollIntoView?.({ block: 'nearest', behavior: 'smooth' })
    if (!quotaMet.value && moderationStore.tasks.length === 0) await loadInlineTasks()
  }
)
 
async function castInlineVote(choice: ModerationVote) {
  const task = inlineTask.value
  Iif (!task || moderationStore.voting) return
  try {
    await moderationStore.vote(task.taskId, choice)
    commentsStore.creditReview()
  } catch (err) {
    toastStore.error(getErrorMessage(err, t('moderation.voteError'), t))
  }
  // Top the list up once it runs dry, while reviews are still missing
  if (!quotaMet.value && moderationStore.tasks.length === 0) await loadInlineTasks()
}
 
watch(
  () => [props.isOpen, props.entityId, props.itemId, props.packId] as const,
  async ([open, entityId, itemId, packId]) => {
    inlineTasksLoaded.value = false
    if (!open) {
      commentsStore.reset()
      return
    }
    if (packId) commentsStore.resetForPack(packId)
    else commentsStore.reset(entityId ?? null, itemId ?? null)
    try {
      await commentsStore.fetchList(null)
    } catch (err) {
      toastStore.error(getErrorMessage(err, t('comment.loadError'), t))
    }
  },
  { immediate: true }
)
 
async function loadMore() {
  try {
    await commentsStore.fetchList(null, true)
  } catch (err) {
    toastStore.error(getErrorMessage(err, t('comment.loadError'), t))
  }
}
 
async function submitRoot(body: string): Promise<boolean> {
  try {
    const { countDelta } = await commentsStore.createComment(body, null)
    emit('count-change', countDelta)
    return true
  } catch (err: any) {
    // The quota alert explains this one, with a way to fix it
    if (err.response?.data?.error !== 'MODERATION_QUOTA_REQUIRED') {
      toastStore.error(getErrorMessage(err, t('comment.postError'), t))
    }
    return false
  }
}
</script>