All files / src/components VirtualCardGrid.vue

77.96% Statements 46/59
60.97% Branches 25/41
78.57% Functions 11/14
84.31% Lines 43/51

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  24x 1x               54x     81x                   1x 108x                                                   13x                               13x       13x 13x 13x     13x   22x 11x 11x               13x   13x   13x     13x 13x     13x 13x     132x               6x   4x 4x   4x 3x 3x   3x 1x         13x   13x 13x   13x     13x     13x     13x 6x         13x 13x     13x 13x                                                                
<template>
  <div ref="scrollElement" class="virtual-scroll-wrapper">
    <div class="container-fluid">
      <div
        :style="{
          height: `${virtualizer.getTotalSize()}px`,
          width: '100%',
          position: 'relative'
        }"
      >
        <div
          v-for="virtualRow in virtualizer.getVirtualItems()"
          :key="virtualRow.index"
          :ref="(el) => virtualizer.measureElement(el as Element)"
          :data-index="virtualRow.index"
          :style="{
            position: 'absolute',
            top: 0,
            left: 0,
            width: '100%',
            transform: `translateY(${virtualRow.start}px)`
          }"
        >
          <div class="row g-3 mb-3">
            <div
              v-for="colIndex in columnsPerRow"
              :key="
                items[virtualRow.index * columnsPerRow + colIndex - 1]?.id ||
                `col-${virtualRow.index}-${colIndex}`
              "
              :class="columnClass"
            >
              <slot
                v-if="items[virtualRow.index * columnsPerRow + colIndex - 1]"
                name="card"
                :item="items[virtualRow.index * columnsPerRow + colIndex - 1]"
                :index="virtualRow.index * columnsPerRow + colIndex - 1"
              />
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
 
<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useVirtualizer } from '@tanstack/vue-virtual'
 
const props = withDefaults(
  defineProps<{
    items: any[]
    hasMore?: boolean
    isLoading?: boolean
    estimateSize?: number
    offsetHeight?: number
    minCardWidth?: number
  }>(),
  {
    offsetHeight: 200,
    estimateSize: 400,
    minCardWidth: 400
  }
)
 
const emit = defineEmits<{
  loadMore: []
}>()
 
const scrollElement = ref<HTMLElement | null>(null)
const isLoadingMore = ref(false)
const columnsPerRow = ref(3)
 
// Calculate responsive columns based on container width
const columnClass = computed(() => {
  // Dynamic Bootstrap classes based on columns
  if (columnsPerRow.value === 1) return 'col-12'
  Iif (columnsPerRow.value === 2) return 'col-md-6'
  Eif (columnsPerRow.value === 3) return 'col-md-6 col-lg-4'
  if (columnsPerRow.value === 4) return 'col-sm-6 col-md-4 col-lg-3'
  if (columnsPerRow.value === 5) return 'col-sm-6 col-md-4 col-lg-3 col-xl-2-4'
  if (columnsPerRow.value >= 6) return 'col-sm-6 col-md-4 col-lg-2'
  return 'col-md-6 col-lg-4'
})
 
function updateColumnsPerRow() {
  Iif (!scrollElement.value) return
 
  const containerWidth = scrollElement.value.clientWidth
  // Account for Bootstrap container padding
  const effectiveWidth = containerWidth - 32 // 1rem padding on each side
 
  // Calculate columns based on minCardWidth (default 400px)
  const calculatedColumns = Math.floor(effectiveWidth / props.minCardWidth)
  columnsPerRow.value = Math.max(1, Math.min(calculatedColumns, 6)) // Between 1 and 6 columns
}
 
const virtualizer = useVirtualizer(
  computed(() => ({
    count: Math.ceil(props.items.length / columnsPerRow.value),
    getScrollElement: () => scrollElement.value,
    estimateSize: () => props.estimateSize || 450,
    measureElement: (el) => el?.getBoundingClientRect().height ?? (props.estimateSize || 450),
    overscan: 2
  }))
)
 
// Scroll detection for infinite loading
function checkLoadMore() {
  if (!scrollElement.value || isLoadingMore.value || !props.hasMore || props.isLoading) return
 
  const { scrollTop, scrollHeight, clientHeight } = scrollElement.value
  const scrollPercentage = (scrollTop + clientHeight) / scrollHeight
 
  if (scrollPercentage > 0.8 && !isLoadingMore.value && props.hasMore) {
    isLoadingMore.value = true
    emit('loadMore')
    // Reset loading state after a delay (parent will handle actual loading)
    setTimeout(() => {
      isLoadingMore.value = false
    }, 100)
  }
}
 
let resizeObserver: ResizeObserver | null = null
 
onMounted(() => {
  Eif (scrollElement.value) {
    // Initial column calculation
    updateColumnsPerRow()
 
    // Set up resize observer for responsive columns
    resizeObserver = new ResizeObserver(() => {
      updateColumnsPerRow()
    })
    resizeObserver.observe(scrollElement.value)
 
    // Set up scroll listener for infinite loading
    if (props.hasMore) {
      scrollElement.value.addEventListener('scroll', checkLoadMore)
    }
  }
})
 
onUnmounted(() => {
  Iif (scrollElement.value) {
    scrollElement.value.removeEventListener('scroll', checkLoadMore)
  }
  Eif (resizeObserver) {
    resizeObserver.disconnect()
  }
})
</script>
 
<style scoped>
.virtual-scroll-wrapper {
  flex: 1 1 auto;
  height: auto;
  overflow-y: auto;
  overflow-x: hidden;
  padding-top: 1rem;
}
 
.virtual-scroll-wrapper :deep(.container-fluid) {
  padding-left: 1rem;
  padding-right: 1rem;
}
 
/* Custom column class for 5-column layout */
.col-xl-2-4 {
  flex: 0 0 auto;
  width: 20%;
}
 
@media (max-width: 767px) {
  .virtual-scroll-wrapper :deep(.container-fluid) {
    padding-left: 1rem;
    padding-right: 1rem;
  }
}
</style>