All files / src/views HomePage.vue

95.23% Statements 60/63
86.84% Branches 33/38
95.23% Functions 20/21
95.16% Lines 59/62

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                  1x       1x             1x       1x     1x                     37x       91x                     20x 1x                       3x                       1x                                                             18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x       18x                 18x 18x     60x       20x 20x       1x       17x 14x   17x   13x 13x                     17x 17x 17x   17x   17x       2x 2x 1x                 18x 18x 16x           18x     18x     4x 2x           2x 2x 2x 1x   1x 1x         1x 1x 1x 1x                          
<template>
  <PageLayout :title="t('navigation.home')" class="home-page">
    <template #action>
      <button
        class="btn btn-outline-secondary refresh-feed-btn"
        :disabled="loading || resolvingEntities"
        @click="refreshFeed"
      >
        <font-awesome-icon icon="fa-solid fa-rotate-right" class="me-md-2" />
        <span class="d-none d-md-inline">{{ t('common.refresh') }}</span>
      </button>
    </template>
 
    <div class="container-fluid">
      <!-- A flow is optional: subscriptions to catalog entities feed this page
           without one, so this only offers to create a flow, never demands it. -->
      <div
        v-if="!authStore.currentFlow"
        class="alert alert-light border shadow-sm mb-3 create-flow-offer"
      >
        <h5 class="alert-heading">{{ t('flow.createOwnFlowTitle') }}</h5>
        <p>{{ t('flow.createOwnFlowText') }}</p>
        <router-link to="/flows" class="btn btn-success">{{
          t('flow.createOwnFlowAction')
        }}</router-link>
      </div>
 
      <h5 class="mb-3">
        <font-awesome-icon icon="fa-solid fa-bell" class="me-2" style="color: #689909" />
        {{ t('recentActivity.title') }}
      </h5>
 
      <LoadingSpinner v-if="(loading || resolvingEntities) && displayItems.length === 0" />
      <ErrorAlert
        v-else-if="error && displayItems.length === 0"
        :title="t('common.error')"
        :message="error"
      />
      <EmptyState v-else-if="displayItems.length === 0">{{ t('recentActivity.empty') }}</EmptyState>
      <!-- A loadMore failure (items already showing) gets a banner alongside
           the grid below, not a replacement for what's already loaded. -->
      <ErrorAlert v-else-if="error" :title="t('common.error')" :message="error" class="mb-3" />
    </div>
 
    <VirtualCardGrid
      v-if="displayItems.length > 0"
      :items="displayItems"
      :has-more="hasMore"
      :is-loading="loading || resolvingEntities"
      :offset-height="220"
      masonry
      @load-more="loadMore"
    >
      <template #card="{ item }">
        <div class="feed-item-wrapper" @click="openItem(item)">
          <EntityItemCard
            :item="item"
            :fields="entityFor(item)?.fields || []"
            :layout="entityFor(item)?.forms?.[0]?.fields || []"
            :get-translation="getTranslation"
            :can-edit="false"
            :can-delete="false"
            :source-label="entityLabel(item)"
            compact
            @like="handleLikeItem"
            @unlike="handleUnlikeItem"
            @comments="commentsTarget = { entityId: $event.entityId, itemId: $event.id }"
          />
        </div>
      </template>
    </VirtualCardGrid>
  </PageLayout>
 
  <ItemCommentsSidebar
    :is-open="commentsTarget !== null"
    :entity-id="commentsTarget?.entityId ?? ''"
    :item-id="commentsTarget?.itemId ?? ''"
    :can-manage="canManageComments(commentsTarget && entitiesById[commentsTarget.entityId])"
    @close="commentsTarget = null"
    @count-change="handleCommentCountChange"
  />
 
  <FloatingPageActions :scroll-top-title="t('common.backToTop')" />
</template>
 
<script setup lang="ts">
// @implements UC-ENTITY-025.1, UC-ITEM-010.1, UC-COMMENT-002.1, UC-COMMENT-012.1
import { onMounted, reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import { storeToRefs } from 'pinia'
import PageLayout from '@/components/PageLayout.vue'
import VirtualCardGrid from '@/components/VirtualCardGrid.vue'
import EntityItemCard from '@/components/EntityItemCard.vue'
import ItemCommentsSidebar from '@/components/ItemCommentsSidebar.vue'
import LoadingSpinner from '@/components/LoadingSpinner.vue'
import EmptyState from '@/components/EmptyState.vue'
import ErrorAlert from '@/components/ErrorAlert.vue'
import FloatingPageActions from '@/components/FloatingPageActions.vue'
import { useAuthStore } from '@/stores/auth'
import { useUILanguage } from '@/composables/useUILanguage'
import { useLanguage } from '@/composables/useLanguage'
import { useFeedStore, type FeedItem } from '@/stores/feed'
import { useEntitiesStore, type Entity } from '@/stores/entities'
import { useItemsStore } from '@/stores/items'
import { useCommentManagement } from '@/composables/useCommentManagement'
import { useToastStore } from '@/stores/toast'
import { getErrorMessage } from '@/utils/errors'
import { useFlowLink } from '@/composables/useFlowLink'
 
const authStore = useAuthStore()
const router = useRouter()
const { flowLink } = useFlowLink()
const { t } = useUILanguage()
const { getTranslation } = useLanguage()
const feedStore = useFeedStore()
const entitiesStore = useEntitiesStore()
const itemsStore = useItemsStore()
const toastStore = useToastStore()
const { canManageComments } = useCommentManagement()
const { items, loading, hasMore, error } = storeToRefs(feedStore)
 
// Entities are fetched once per unique id and cached here, keyed by entityId —
// several feed items commonly share the same subscribed entity.
const entitiesById = reactive<Record<string, Entity>>({})
 
// The store's own `items` updates the instant its fetch resolves — before
// each item's entity (needed for its name/fields/layout) has been resolved.
// Binding the grid directly to `items` would flash the raw entityId as a
// placeholder name for a beat, then swap to the real name once entities
// load — jarring. `displayItems` is only ever assigned once every entity for
// the batch is resolved (or has failed and fallen back), so a card never
// renders with anything other than its final label.
const displayItems = ref<FeedItem[]>([])
const resolvingEntities = ref(false)
 
function entityFor(item: FeedItem): Entity | undefined {
  return entitiesById[item.entityId]
}
 
function entityLabel(item: FeedItem): string {
  const entity = entityFor(item)
  return entity ? getTranslation(entity.name) : t('recentActivity.unknownEntity')
}
 
function openItem(item: FeedItem) {
  void router.push(flowLink('entity-items', { entityId: item.entityId }, { source: 'catalog' }))
}
 
async function ensureEntitiesLoaded(feedItems: FeedItem[]) {
  const missingIds = Array.from(new Set(feedItems.map((item) => item.entityId))).filter(
    (id) => !entitiesById[id]
  )
  await Promise.all(
    missingIds.map(async (id) => {
      try {
        entitiesById[id] = await entitiesStore.fetchEntity(id)
      } catch {
        // Best effort: if an entity can no longer be resolved (e.g. deleted
        // right after the feed query ran), entityLabel() falls back to a
        // generic label instead — never the raw id.
      }
    })
  )
}
 
async function syncDisplayItems() {
  resolvingEntities.value = true
  try {
    await ensureEntitiesLoaded(items.value)
  } finally {
    resolvingEntities.value = false
  }
  displayItems.value = [...items.value]
}
 
async function loadMore() {
  try {
    await feedStore.loadMore()
    await syncDisplayItems()
  } catch {
    // The store already recorded the error (surfaced via the shared `error`
    // ref above); VirtualCardGrid just stops asking for more until the user
    // scrolls again.
  }
}
 
async function refreshFeed() {
  try {
    await feedStore.fetchFeed()
    await syncDisplayItems()
  } catch {
    // The store already recorded the error in its own `error` ref.
  }
}
 
onMounted(refreshFeed)
 
// The feed item whose comments panel is open (null = closed).
const commentsTarget = ref<{ entityId: string; itemId: string } | null>(null)
 
function handleCommentCountChange(delta: number) {
  if (commentsTarget.value && delta !== 0) {
    feedStore.adjustCommentCount(commentsTarget.value.itemId, delta)
  }
}
 
async function handleLikeItem(item: Record<string, any>) {
  // Optimistic: flip the button immediately, roll it back if the request fails.
  feedStore.markAsLiked(item.id)
  try {
    await itemsStore.likeItem(item.entityId, item.id)
    toastStore.success(t('item.like-success'))
  } catch (err) {
    feedStore.markAsUnliked(item.id)
    toastStore.error(getErrorMessage(err, t('item.like-error')))
  }
}
 
async function handleUnlikeItem(item: Record<string, any>) {
  feedStore.markAsUnliked(item.id)
  try {
    await itemsStore.unlikeItem(item.entityId, item.id)
    toastStore.success(t('item.unlike-success'))
  } catch (err) {
    feedStore.markAsLiked(item.id)
    toastStore.error(getErrorMessage(err, t('item.unlike-error')))
  }
}
</script>
 
<style scoped>
.feed-item-wrapper {
  cursor: pointer;
}
</style>