All files / src/components VirtualCardGrid.vue

77.38% Statements 65/84
69.23% Branches 45/65
77.27% Functions 17/22
82.66% Lines 62/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  30x 5x                 12x     18x             59x       91x                   5x 113x                                                   17x                                           17x         17x 17x 17x 17x           17x 17x 17x             17x   24x 11x 11x               17x 2x 2x     15x     15x 15x 17x     17x     17x 17x     17x 17x         189x                   12x 12x 12x                     6x   4x 4x   4x 3x 3x   3x 1x         17x 17x         17x 17x       17x   17x 17x   17x 17x     17x       17x     17x 6x         17x 17x     17x 17x                                                                
<template>
  <div ref="scrollElement" class="virtual-scroll-wrapper">
    <div class="container-fluid">
      <div
        :style="{
          height: `${virtualizer.getTotalSize()}px`,
          width: '100%',
          position: 'relative'
        }"
      >
        <template v-if="masonry">
          <div
            v-for="virtualItem in virtualizer.getVirtualItems()"
            :key="virtualItem.index"
            :ref="(el) => virtualizer.measureElement(el as Element)"
            :data-index="virtualItem.index"
            :style="masonryItemStyle(virtualItem)"
          >
            <slot name="card" :item="items[virtualItem.index]" :index="virtualItem.index" />
          </div>
        </template>
        <div
          v-for="virtualRow in virtualizer.getVirtualItems()"
          v-else
          :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, watch, nextTick, unref } from 'vue'
import { useVirtualizer } from '@tanstack/vue-virtual'
 
const props = withDefaults(
  defineProps<{
    items: any[]
    hasMore?: boolean
    isLoading?: boolean
    estimateSize?: number
    offsetHeight?: number
    minCardWidth?: number
    singleColumn?: boolean
    masonry?: boolean
    gap?: number
  }>(),
  {
    offsetHeight: 200,
    estimateSize: 400,
    minCardWidth: 400,
    singleColumn: false,
    masonry: false,
    gap: 16
  }
)
 
const emit = defineEmits<{
  loadMore: []
  scrollbarWidthChange: [width: number]
}>()
 
const scrollElement = ref<HTMLElement | null>(null)
const isLoadingMore = ref(false)
const columnsPerRow = ref(props.singleColumn ? 1 : 3)
const scrollbarWidth = ref(0)
 
// Measures the actual vertical scrollbar width so siblings (e.g. EntityItemHeader)
// can compensate their right margin to stay aligned with the rows, regardless of
// OS/browser scrollbar rendering (classic vs overlay, width variations).
function updateScrollbarWidth() {
  Iif (!scrollElement.value) return
  const width = scrollElement.value.offsetWidth - scrollElement.value.clientWidth
  Iif (width !== scrollbarWidth.value) {
    scrollbarWidth.value = width
    emit('scrollbarWidthChange', width)
  }
}
 
// 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() {
  if (props.singleColumn) {
    columnsPerRow.value = 1
    return
  }
 
  Iif (!scrollElement.value) return
 
  // The inner container's padding is the page gutter, set by PageLayout
  const container = scrollElement.value.firstElementChild
  const style = container ? window.getComputedStyle(container) : null
  const padding = style
    ? (parseFloat(style.paddingLeft) || 0) + (parseFloat(style.paddingRight) || 0)
    : 0
  const effectiveWidth = scrollElement.value.clientWidth - padding
 
  // 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: props.masonry ? props.items.length : Math.ceil(props.items.length / columnsPerRow.value),
    lanes: props.masonry ? columnsPerRow.value : 1,
    gap: props.masonry ? props.gap : 0,
    getScrollElement: () => scrollElement.value,
    estimateSize: () => props.estimateSize || 450,
    measureElement: (el) => el?.getBoundingClientRect().height ?? (props.estimateSize || 450),
    overscan: 2
  }))
)
 
// Places each card in its assigned lane (tanstack-virtual picks the shortest
// lane per item, the same greedy packing Masonry.js uses) so shorter cards
// don't leave a gap under a taller neighbour the way a fixed-row grid would.
function masonryItemStyle(virtualItem: { start: number; lane: number }) {
  const lanes = columnsPerRow.value
  const totalGap = props.gap * (lanes - 1)
  return {
    position: 'absolute' as const,
    top: 0,
    left: `calc((100% - ${totalGap}px) / ${lanes} * ${virtualItem.lane} + ${virtualItem.lane * props.gap}px)`,
    width: `calc((100% - ${totalGap}px) / ${lanes})`,
    transform: `translateY(${virtualItem.start}px)`
  }
}
 
// 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)
  }
}
 
watch(
  () => props.singleColumn,
  () => updateColumnsPerRow()
)
 
// Rows loading in/out can toggle the scrollbar without resizing the wrapper itself.
watch(
  () => unref(virtualizer).getTotalSize(),
  () => nextTick(updateScrollbarWidth)
)
 
let resizeObserver: ResizeObserver | null = null
 
onMounted(() => {
  Eif (scrollElement.value) {
    // Initial column calculation
    updateColumnsPerRow()
    updateScrollbarWidth()
 
    // Set up resize observer for responsive columns
    resizeObserver = new ResizeObserver(() => {
      updateColumnsPerRow()
      updateScrollbarWidth()
    })
    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>