All files / src/stores comments.ts

100% Statements 118/118
98.73% Branches 78/79
100% Functions 22/22
100% Lines 96/96

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                                                                                                            8x     66x                 8x 232x 232x 232x 232x     232x     232x   232x     232x     125x       91x         53x 50x 46x   4x       3x       338x 338x 338x 338x 338x 338x 338x 338x         5x 5x       32x 32x 32x       33x 33x 29x 29x 28x   27x 27x 27x 27x 27x 27x 27x 27x 21x 20x     33x 33x 33x 15x 11x     11x 10x 11x   27x           2x 2x       11x 11x 11x   2x       4x 4x                     12x 12x       7x     5x 5x 1x         5x   7x     7x 2x 2x     5x 2x 2x     2x   3x 3x   5x                       8x   7x 8x 8x 8x 8x   5x 1x                   4x 4x   5x           5x 4x             3x     232x                                    
import { defineStore } from 'pinia'
import { ref } from 'vue'
import api from '@/services/api'
 
export type CommentStatus = 'pending' | 'approved' | 'rejected' | 'deleted'
 
export interface Comment {
  id: string
  // Null on a store pack's comment, which has packId instead
  itemId: string | null
  entityId: string | null
  packId?: string | null
  // The pack version a pack's comment was written on
  packVersion?: number | null
  parentId: string | null
  authorId: string | null
  authorName: string | null
  authorNickname: string | null
  authorProfilePicture: string | null
  // null on a tombstone: a deleted comment that still has replies
  body: string | null
  status: CommentStatus
  deleted: boolean
  replyCount: number
  createdAt: string
}
 
interface CommentPage {
  comments: Comment[]
  nextToken: string | null
  // Whether the caller is blocked from commenting on the entity or pack
  blocked?: boolean
  // First page of a moderated thread only: the caller's own comments that are not
  // visible yet (awaiting review) or were rejected
  mine?: Comment[]
}
 
// What a refused submission says about the quota (see MODERATION.md): reviews
// needed to publish, and how many the user has done.
export interface QuotaRequired {
  required: number
  have: number
}
 
// One page-by-page list of sibling comments: the top-level comments of the
// open item, or the replies of one comment.
export interface CommentList {
  comments: Comment[]
  nextToken: string | null
  loading: boolean
  loaded: boolean
  error: string | null
}
 
const ROOT_KEY = 'ROOT'
 
function emptyList(): CommentList {
  return { comments: [], nextToken: null, loading: false, loaded: false, error: null }
}
 
// Comments of the one item, or store pack, whose panel is open. Top-level
// comments come newest first, replies oldest first (conversation order),
// matching the API. The store never talks about comment *counts* of the cards:
// it returns the delta of each change so the page that owns the card can apply
// it (items store on an entity's page, feed store on the home page, the pack
// page for a pack).
export const useCommentsStore = defineStore('comments', () => {
  const entityId = ref<string | null>(null)
  const itemId = ref<string | null>(null)
  const packId = ref<string | null>(null)
  const lists = ref<Record<string, CommentList>>({})
  // The entity's managers blocked the current user from commenting: the panel
  // then offers no composer. Blocking never affects reading or moderating.
  const blocked = ref(false)
  // The user's own comments awaiting review or rejected on this item,
  // invisible to anybody else
  const mine = ref<Comment[]>([])
  // Set when publishing was refused for lack of review points
  const quotaRequired = ref<QuotaRequired | null>(null)
  // Bumped on every reset so a response that arrives after the panel moved on
  // to another item is dropped instead of leaking into the new one.
  let contextVersion = 0
 
  function keyFor(parentId: string | null): string {
    return parentId ?? ROOT_KEY
  }
 
  function listFor(parentId: string | null): CommentList {
    return lists.value[keyFor(parentId)] ?? emptyList()
  }
 
  // The API path of the open thread, and of its block list
  function threadPath(): string | null {
    if (packId.value) return `/v1/store/${packId.value}`
    if (entityId.value && itemId.value) {
      return `/v1/entities/${entityId.value}/items/${itemId.value}`
    }
    return null
  }
 
  function blocksPath(): string {
    return packId.value ? `/v1/store/${packId.value}` : `/v1/entities/${entityId.value}`
  }
 
  function reset(newEntityId: string | null = null, newItemId: string | null = null) {
    contextVersion++
    entityId.value = newEntityId
    itemId.value = newItemId
    packId.value = null
    lists.value = {}
    blocked.value = false
    mine.value = []
    quotaRequired.value = null
  }
 
  // Opens a store pack's thread instead of an item's
  function resetForPack(newPackId: string) {
    reset()
    packId.value = newPackId
  }
 
  function ensureList(parentId: string | null): CommentList {
    const key = keyFor(parentId)
    if (!lists.value[key]) lists.value[key] = emptyList()
    return lists.value[key]
  }
 
  async function fetchList(parentId: string | null = null, more = false) {
    const path = threadPath()
    if (!path) return
    const list = ensureList(parentId)
    if (list.loading) return
    if (more && !list.nextToken) return
 
    const version = contextVersion
    list.loading = true
    list.error = null
    try {
      const params: Record<string, string> = {}
      if (parentId) params.parentId = parentId
      if (more && list.nextToken) params.nextToken = list.nextToken
      const response = await api.get<CommentPage>(`${path}/comments`, { params })
      if (version !== contextVersion) return
      list.comments = more
        ? [...list.comments, ...dedupe(response.data.comments, list.comments)]
        : response.data.comments
      list.nextToken = response.data.nextToken
      list.loaded = true
      if (typeof response.data.blocked === 'boolean') blocked.value = response.data.blocked
      if (!more && !parentId) {
        mine.value = response.data.mine ?? []
      }
    } catch (err: any) {
      if (version !== contextVersion) return
      list.error = err.response?.data?.error || 'Failed to load comments'
      throw err
    } finally {
      if (version === contextVersion) list.loading = false
    }
  }
 
  // A comment posted while a page was loading could otherwise show up twice.
  function dedupe(incoming: Comment[], existing: Comment[]): Comment[] {
    const known = new Set(existing.map((comment) => comment.id))
    return incoming.filter((comment) => !known.has(comment.id))
  }
 
  function findComment(commentId: string): { comment: Comment; list: CommentList } | null {
    for (const list of Object.values(lists.value)) {
      const comment = list.comments.find((candidate) => candidate.id === commentId)
      if (comment) return { comment, list }
    }
    return null
  }
 
  function adjustReplyCount(parentId: string, delta: number) {
    const parent = findComment(parentId)?.comment
    Eif (parent) parent.replyCount = Math.max(0, parent.replyCount + delta)
  }
 
  // Publishes a comment, or a reply when `parentId` is given. Returns the
  // stored comment together with the change it makes to the item's comment
  // counter: +1 when it is visible right away, 0 when it awaits moderation.
  async function createComment(
    body: string,
    parentId: string | null = null
  ): Promise<{ comment: Comment; countDelta: number }> {
    let comment: Comment
    try {
      const response = await api.post<Comment>(
        `${threadPath()}/comments`,
        parentId ? { body, parentId } : { body }
      )
      comment = response.data
    } catch (err: any) {
      // Blocked while the panel was open: stop offering the composer
      if (err.response?.data?.error === 'COMMENT_BLOCKED') blocked.value = true
      if (err.response?.data?.error === 'MODERATION_QUOTA_REQUIRED') {
        quotaRequired.value = {
          required: err.response.data.required,
          have: err.response.data.have
        }
      }
      throw err
    }
    quotaRequired.value = null
 
    // Awaiting review: not part of the public lists, listed apart for its author
    if (comment.status !== 'approved') {
      mine.value = [comment, ...mine.value]
      return { comment, countDelta: 0 }
    }
 
    if (parentId) {
      adjustReplyCount(parentId, 1)
      const replies = lists.value[keyFor(parentId)]
      // A collapsed thread has not loaded its replies yet: they will include
      // this one when it is opened.
      if (replies?.loaded) replies.comments = [...replies.comments, comment]
    } else {
      const roots = ensureList(null)
      roots.comments = [comment, ...roots.comments]
    }
    return { comment, countDelta: 1 }
  }
 
  // Deletes a comment of the open item or pack. One with replies stays behind as a
  // "[deleted]" tombstone so its replies remain attached; otherwise it goes
  // away. Returns the change to the item's comment counter; `onDeleted` gets it
  // before the comment leaves the lists, while the component showing it is still
  // mounted (Vue drops the events of an unmounted component).
  async function deleteComment(
    comment: Comment,
    onDeleted?: (countDelta: number) => void
  ): Promise<{ countDelta: number }> {
    await api.delete(`${threadPath()}/comments/${comment.id}`)
 
    const countDelta = comment.status === 'approved' ? -1 : 0
    onDeleted?.(countDelta)
    mine.value = mine.value.filter((candidate) => candidate.id !== comment.id)
    const found = findComment(comment.id)
    if (!found) return { countDelta }
 
    if (comment.replyCount > 0) {
      Object.assign(found.comment, {
        status: 'deleted',
        deleted: true,
        body: null,
        authorId: null,
        authorName: null,
        authorNickname: null,
        authorProfilePicture: null
      })
    } else {
      found.list.comments = found.list.comments.filter((candidate) => candidate.id !== comment.id)
      if (comment.parentId && comment.status === 'approved') adjustReplyCount(comment.parentId, -1)
    }
    return { countDelta }
  }
 
  // A review was just done while posting was refused for lack of them: the
  // quota progress follows without asking the server again.
  function creditReview() {
    if (quotaRequired.value) {
      quotaRequired.value = { ...quotaRequired.value, have: quotaRequired.value.have + 1 }
    }
  }
 
  // Blocks an author from commenting on the open item's entity, or on the open
  // pack (managers only).
  async function blockAuthor(userId: string) {
    await api.put(`${blocksPath()}/comment-blocks/${userId}`)
  }
 
  return {
    entityId,
    itemId,
    packId,
    lists,
    blocked,
    mine,
    quotaRequired,
    blockAuthor,
    creditReview,
    listFor,
    reset,
    resetForPack,
    fetchList,
    createComment,
    deleteComment
  }
})