[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6XCCCHWNKG2W4VH9E6A10HF":3,"skill-same:01M6XCCCHWNKG2W4VH9E6A10HF":60},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":15,"categories":16,"keywords":17,"publishedAt":29,"linkOnly":30,"markdownContent":31,"markdownBody":32,"frontMatter":33,"refName":34,"commitSha":35,"skillDirectory":36,"forksCount":13,"repositoryHtmlUrl":37,"repositoryHomepageUrl":6,"ownerHtmlUrl":38,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":39,"install":40,"resources":53},"01M6XCCCHWNKG2W4VH9E6A10HF","virtual-list",null,"Implement efficient virtual scrolling for rendering large lists with DOM recycling, chunk-based rendering, and performance optimizations","UF-gzj\u002Fopenspace-claude-evolution","UF-gzj","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F272393507?v=4","01M6XBCZB755P01VVYGQWPYZY3","01M6XBCZFJA5AREA17WGETA3FW",0,"MIT","https:\u002F\u002Fgithub.com\u002FUF-gzj\u002Fopenspace-claude-evolution\u002Fblob\u002Fmain\u002Fshowcase\u002Fskills\u002Fvirtual-list\u002FSKILL.md",[],[18,19,20,21,22,23,24,25,26,27,28],"virtual","list","virtual list","performance","implement","chunk","recycling","rendering","with","dom","for","2026-11-10 10:12:30",false,"---\nname: virtual-list\ndescription: Implement efficient virtual scrolling for rendering large lists with DOM recycling, chunk-based rendering, and performance optimizations\n---\n\n# Virtual List Implementation Skill\n\n## Overview\n\nThis skill teaches you how to implement a high-performance virtual scrolling list component that can efficiently render thousands or millions of items by only creating DOM nodes for visible items plus a small buffer.\n\n## Analysis of Reference Implementation\n\nThe VirtualList component from `\u002Fworldmonitor\u002Fsrc\u002Fcomponents\u002FVirtualList.ts` demonstrates professional-grade virtual scrolling with the following patterns:\n\n### 1. **Chunk-Based Rendering Pattern**\n\nThe implementation uses two complementary strategies:\n\n#### VirtualList (Fixed-Height Items)\n- **Item Pool Management**: Maintains a pool of reusable DOM elements (`PooledElement[]`)\n- **Viewport Calculation**: Calculates visible range based on `scrollTop`, `itemHeight`, and viewport dimensions\n- **Overscan Buffer**: Renders extra items above\u002Fbelow viewport (`overscan` parameter) to prevent flickering during scroll\n\n#### WindowedList (Variable-Height Items)\n- **Chunk-Based Approach**: Divides items into chunks (default 10 items per chunk)\n- **Lazy Chunk Rendering**: Only renders chunks that are visible or within buffer range\n- **Placeholder Elements**: Creates placeholders for all chunks upfront, renders content on-demand\n\n### 2. **Scroll Listener Optimization**\n\n```typescript\nprivate handleScroll = (): void => {\n  if (this.scrollRAF !== null) return;\n  \n  this.scrollRAF = requestAnimationFrame(() => {\n    this.scrollRAF = null;\n    if (!this.isDestroyed) {\n      this.updateVisibleRange();\n    }\n  });\n};\n```\n\n**Key Optimizations:**\n- **RequestAnimationFrame Throttling**: Prevents multiple renders in same frame\n- **Passive Listeners**: `{ passive: true }` improves scroll performance\n- **Debounce Check**: Guards against duplicate RAF calls\n- **Cleanup Check**: Prevents rendering after destruction\n\n### 3. **DOM Recycling Strategy**\n\nThe implementation uses a sophisticated two-pass recycling algorithm:\n\n**Pass 1: Identify Reusable Elements**\n```typescript\nfor (const pooled of this.itemPool) {\n  if (pooled.currentIndex >= visibleStart && pooled.currentIndex \u003C visibleEnd) {\n    usedIndices.add(pooled.currentIndex);\n  }\n}\n```\n\n**Pass 2: Recycle and Reassign**\n```typescript\nwhile (poolIndex \u003C this.itemPool.length) {\n  const pooled = this.itemPool[poolIndex]!;\n  if (pooled.currentIndex \u003C visibleStart || pooled.currentIndex >= visibleEnd) {\n    \u002F\u002F Recycle this element\n    if (this.onRecycle) {\n      this.onRecycle(pooled.element);\n    }\n    pooled.currentIndex = i;\n    this.renderItem(i, pooled.element);\n    pooled.element.style.transform = `translateY(${i * this.itemHeight}px)`;\n    poolIndex++;\n    break;\n  }\n  poolIndex++;\n}\n```\n\n**Benefits:**\n- Minimizes DOM manipulation\n- Reuses existing elements when possible\n- Allows cleanup of event listeners via `onRecycle` callback\n- Uses `transform: translateY()` for GPU-accelerated positioning\n\n### 4. **Performance Optimizations**\n\n#### Spacer Elements for Virtual Height\n```typescript\nthis.topSpacer.style.height = `${visibleStart * this.itemHeight}px`;\nthis.bottomSpacer.style.height = `${Math.max(0, (this.totalItems - visibleEnd) * this.itemHeight)}px`;\n```\n\n- Creates illusion of full list height without rendering all items\n- Maintains accurate scrollbar size and position\n\n#### Skip Unnecessary Updates\n```typescript\nif (visibleStart === this.visibleStart && visibleEnd === this.visibleEnd) {\n  return;\n}\n```\n\n#### CSS Positioning Strategy\n```typescript\nelement.style.position = 'absolute';\nelement.style.top = '0';\nelement.style.left = '0';\nelement.style.right = '0';\nelement.style.transform = 'translateY(-9999px)'; \u002F\u002F Hide off-screen\n```\n\n- Absolute positioning for precise control\n- Transform for GPU acceleration\n- Off-screen positioning instead of display:none (preserves element state)\n\n#### ResizeObserver Integration\n```typescript\nif (typeof ResizeObserver !== 'undefined') {\n  this.resizeObserver = new ResizeObserver(() => {\n    if (!this.isDestroyed) {\n      this.updateVisibleRange();\n    }\n  });\n  this.resizeObserver.observe(this.viewport);\n}\n```\n\n- Automatically recalculates visible range when viewport resizes\n- Progressive enhancement (checks for browser support)\n\n## Complete TypeScript Implementation Template\n\nBelow is a simplified but fully functional virtual list implementation that you can drop into any vanilla TypeScript project:\n\n```typescript\n\u002F**\n * SimpleVirtualList - A simplified virtual scrolling implementation\n * \n * Usage:\n * ```typescript\n * const virtualList = new SimpleVirtualList({\n *   container: document.getElementById('my-container')!,\n *   itemHeight: 50,\n *   totalItems: 100000,\n *   renderItem: (index, element) => {\n *     element.textContent = `Item ${index}`;\n *   }\n * });\n * ```\n *\u002F\n\nexport interface SimpleVirtualListOptions {\n  \u002F** Container element to render the virtual list into *\u002F\n  container: HTMLElement;\n  \n  \u002F** Fixed height of each item in pixels *\u002F\n  itemHeight: number;\n  \n  \u002F** Total number of items in the list *\u002F\n  totalItems: number;\n  \n  \u002F** Callback to render content for an item *\u002F\n  renderItem: (index: number, element: HTMLElement) => void;\n  \n  \u002F** Number of items to render beyond visible area (default: 5) *\u002F\n  overscan?: number;\n  \n  \u002F** Optional callback when item element is recycled *\u002F\n  onRecycle?: (element: HTMLElement) => void;\n}\n\ninterface VirtualItem {\n  element: HTMLElement;\n  index: number;\n}\n\nexport class SimpleVirtualList {\n  \u002F\u002F Configuration\n  private container: HTMLElement;\n  private itemHeight: number;\n  private totalItems: number;\n  private overscan: number;\n  private renderItem: (index: number, element: HTMLElement) => void;\n  private onRecycle?: (element: HTMLElement) => void;\n\n  \u002F\u002F DOM Structure\n  private viewport: HTMLElement;\n  private contentWrapper: HTMLElement;\n  private topSpacer: HTMLElement;\n  private bottomSpacer: HTMLElement;\n\n  \u002F\u002F State\n  private itemPool: VirtualItem[] = [];\n  private visibleStart = 0;\n  private visibleEnd = 0;\n  private rafId: number | null = null;\n  private destroyed = false;\n\n  constructor(options: SimpleVirtualListOptions) {\n    this.container = options.container;\n    this.itemHeight = options.itemHeight;\n    this.totalItems = options.totalItems;\n    this.overscan = options.overscan ?? 5;\n    this.renderItem = options.renderItem;\n    this.onRecycle = options.onRecycle;\n\n    this.setupDOM();\n    this.attachEventListeners();\n    this.updateVisibleRange();\n  }\n\n  \u002F**\n   * Set up the DOM structure for virtual scrolling\n   *\u002F\n  private setupDOM(): void {\n    \u002F\u002F Clear container\n    this.container.innerHTML = '';\n\n    \u002F\u002F Create viewport (scrollable container)\n    this.viewport = document.createElement('div');\n    this.viewport.style.cssText = `\n      width: 100%;\n      height: 100%;\n      overflow-y: auto;\n      position: relative;\n    `;\n\n    \u002F\u002F Create content wrapper\n    this.contentWrapper = document.createElement('div');\n    const totalHeight = this.totalItems * this.itemHeight;\n    this.contentWrapper.style.cssText = `\n      position: relative;\n      width: 100%;\n      height: ${totalHeight}px;\n    `;\n\n    \u002F\u002F Create spacers\n    this.topSpacer = document.createElement('div');\n    this.topSpacer.style.cssText = `\n      height: 0px;\n      width: 100%;\n    `;\n\n    this.bottomSpacer = document.createElement('div');\n    this.bottomSpacer.style.cssText = `\n      height: ${totalHeight}px;\n      width: 100%;\n    `;\n\n    \u002F\u002F Assemble DOM\n    this.contentWrapper.appendChild(this.topSpacer);\n    this.contentWrapper.appendChild(this.bottomSpacer);\n    this.viewport.appendChild(this.contentWrapper);\n    this.container.appendChild(this.viewport);\n  }\n\n  \u002F**\n   * Attach scroll event listeners with optimization\n   *\u002F\n  private attachEventListeners(): void {\n    this.viewport.addEventListener('scroll', this.handleScroll, { passive: true });\n  }\n\n  \u002F**\n   * Throttled scroll handler using requestAnimationFrame\n   *\u002F\n  private handleScroll = (): void => {\n    \u002F\u002F Prevent multiple RAF calls per frame\n    if (this.rafId !== null) return;\n\n    this.rafId = requestAnimationFrame(() => {\n      this.rafId = null;\n      \n      if (!this.destroyed) {\n        this.updateVisibleRange();\n      }\n    });\n  };\n\n  \u002F**\n   * Calculate and update which items should be visible\n   *\u002F\n  private updateVisibleRange(): void {\n    const scrollTop = this.viewport.scrollTop;\n    const viewportHeight = this.viewport.clientHeight;\n\n    \u002F\u002F Calculate visible indices\n    const startIndex = Math.floor(scrollTop \u002F this.itemHeight);\n    const endIndex = Math.ceil((scrollTop + viewportHeight) \u002F this.itemHeight);\n\n    \u002F\u002F Add overscan buffer\n    const bufferedStart = Math.max(0, startIndex - this.overscan);\n    const bufferedEnd = Math.min(this.totalItems, endIndex + this.overscan);\n\n    \u002F\u002F Skip if range hasn't changed\n    if (bufferedStart === this.visibleStart && bufferedEnd === this.visibleEnd) {\n      return;\n    }\n\n    this.visibleStart = bufferedStart;\n    this.visibleEnd = bufferedEnd;\n\n    \u002F\u002F Update spacers to maintain scroll position\n    this.topSpacer.style.height = `${bufferedStart * this.itemHeight}px`;\n    const bottomHeight = Math.max(0, (this.totalItems - bufferedEnd) * this.itemHeight);\n    this.bottomSpacer.style.height = `${bottomHeight}px`;\n\n    \u002F\u002F Render visible items\n    this.renderVisibleItems();\n  }\n\n  \u002F**\n   * Render or update items in the visible range using DOM recycling\n   *\u002F\n  private renderVisibleItems(): void {\n    const visibleCount = this.visibleEnd - this.visibleStart;\n\n    \u002F\u002F Ensure we have enough pooled elements\n    this.ensurePoolSize(visibleCount);\n\n    \u002F\u002F Track which indices are currently in use\n    const activeIndices = new Set\u003Cnumber>();\n\n    \u002F\u002F First pass: keep elements that are still visible\n    for (const item of this.itemPool) {\n      if (item.index >= this.visibleStart && item.index \u003C this.visibleEnd) {\n        activeIndices.add(item.index);\n      }\n    }\n\n    \u002F\u002F Second pass: recycle and assign new indices\n    let poolIndex = 0;\n    for (let i = this.visibleStart; i \u003C this.visibleEnd; i++) {\n      \u002F\u002F Skip if already rendered\n      if (activeIndices.has(i)) continue;\n\n      \u002F\u002F Find an element to recycle\n      while (poolIndex \u003C this.itemPool.length) {\n        const item = this.itemPool[poolIndex];\n        \n        \u002F\u002F Check if this element can be recycled\n        if (item.index \u003C this.visibleStart || item.index >= this.visibleEnd) {\n          \u002F\u002F Call recycle callback\n          if (this.onRecycle) {\n            this.onRecycle(item.element);\n          }\n\n          \u002F\u002F Update item\n          item.index = i;\n          this.renderItem(i, item.element);\n          this.positionItem(item);\n          \n          poolIndex++;\n          break;\n        }\n        \n        poolIndex++;\n      }\n    }\n\n    \u002F\u002F Third pass: update positions and visibility\n    for (const item of this.itemPool) {\n      if (item.index >= this.visibleStart && item.index \u003C this.visibleEnd) {\n        \u002F\u002F Ensure proper position\n        this.positionItem(item);\n        item.element.style.visibility = 'visible';\n      } else {\n        \u002F\u002F Hide off-screen items\n        item.element.style.visibility = 'hidden';\n        item.element.style.transform = 'translateY(-9999px)';\n      }\n    }\n  }\n\n  \u002F**\n   * Position an item element using transform for GPU acceleration\n   *\u002F\n  private positionItem(item: VirtualItem): void {\n    const yOffset = item.index * this.itemHeight;\n    item.element.style.transform = `translateY(${yOffset}px)`;\n  }\n\n  \u002F**\n   * Ensure the pool has enough elements\n   *\u002F\n  private ensurePoolSize(requiredSize: number): void {\n    while (this.itemPool.length \u003C requiredSize) {\n      const element = this.createItemElement();\n      const item: VirtualItem = {\n        element,\n        index: -1,\n      };\n      \n      this.itemPool.push(item);\n      \n      \u002F\u002F Insert before bottom spacer\n      this.contentWrapper.insertBefore(element, this.bottomSpacer);\n    }\n  }\n\n  \u002F**\n   * Create a new item element with proper styling\n   *\u002F\n  private createItemElement(): HTMLElement {\n    const element = document.createElement('div');\n    element.style.cssText = `\n      position: absolute;\n      top: 0;\n      left: 0;\n      width: 100%;\n      height: ${this.itemHeight}px;\n      box-sizing: border-box;\n      visibility: hidden;\n      transform: translateY(-9999px);\n    `;\n    element.classList.add('virtual-list-item');\n    return element;\n  }\n\n  \u002F**\n   * Update the total number of items\n   *\u002F\n  setTotalItems(count: number): void {\n    this.totalItems = count;\n    \n    \u002F\u002F Update content height\n    const totalHeight = this.totalItems * this.itemHeight;\n    this.contentWrapper.style.height = `${totalHeight}px`;\n    \n    \u002F\u002F Recalculate visible range\n    this.updateVisibleRange();\n  }\n\n  \u002F**\n   * Scroll to a specific item index\n   *\u002F\n  scrollToIndex(index: number, smooth = false): void {\n    const offset = Math.max(0, Math.min(index, this.totalItems - 1)) * this.itemHeight;\n    this.viewport.scrollTo({\n      top: offset,\n      behavior: smooth ? 'smooth' : 'auto',\n    });\n  }\n\n  \u002F**\n   * Force refresh all visible items\n   *\u002F\n  refresh(): void {\n    \u002F\u002F Mark all items as needing re-render\n    for (const item of this.itemPool) {\n      item.index = -1;\n    }\n    \n    \u002F\u002F Trigger update\n    this.updateVisibleRange();\n  }\n\n  \u002F**\n   * Get the current scroll position info\n   *\u002F\n  getScrollInfo(): { scrollTop: number; visibleStart: number; visibleEnd: number } {\n    return {\n      scrollTop: this.viewport.scrollTop,\n      visibleStart: this.visibleStart,\n      visibleEnd: this.visibleEnd,\n    };\n  }\n\n  \u002F**\n   * Clean up resources and remove event listeners\n   *\u002F\n  destroy(): void {\n    this.destroyed = true;\n\n    \u002F\u002F Cancel pending animation frame\n    if (this.rafId !== null) {\n      cancelAnimationFrame(this.rafId);\n      this.rafId = null;\n    }\n\n    \u002F\u002F Remove event listeners\n    this.viewport.removeEventListener('scroll', this.handleScroll);\n\n    \u002F\u002F Clear pool\n    this.itemPool = [];\n\n    \u002F\u002F Clear container\n    this.container.innerHTML = '';\n  }\n}\n\n\u002F\u002F ============================================================================\n\u002F\u002F CSS Styles (add to your stylesheet or inject programmatically)\n\u002F\u002F ============================================================================\n\n\u002F**\n * Recommended CSS for virtual list container:\n * \n * ```css\n * .virtual-list-container {\n *   width: 100%;\n *   height: 400px; \u002F\u002F or whatever height you need\n *   border: 1px solid #ddd;\n *   overflow: hidden;\n * }\n * \n * .virtual-list-item {\n *   border-bottom: 1px solid #eee;\n *   padding: 10px;\n *   display: flex;\n *   align-items: center;\n * }\n * \n * .virtual-list-item:hover {\n *   background-color: #f5f5f5;\n * }\n * ```\n *\u002F\n\n\u002F\u002F ============================================================================\n\u002F\u002F Usage Example\n\u002F\u002F ============================================================================\n\n\u002F**\n * Example 1: Basic Usage\n *\u002F\nexport function exampleBasicUsage(): void {\n  const container = document.createElement('div');\n  container.className = 'virtual-list-container';\n  container.style.cssText = 'width: 500px; height: 400px; border: 1px solid #ddd;';\n  document.body.appendChild(container);\n\n  const virtualList = new SimpleVirtualList({\n    container,\n    itemHeight: 50,\n    totalItems: 100000,\n    renderItem: (index, element) => {\n      element.innerHTML = `\n        \u003Cdiv style=\"padding: 10px; border-bottom: 1px solid #eee;\">\n          \u003Cstrong>Item ${index}\u003C\u002Fstrong>\n          \u003Cspan style=\"margin-left: 20px; color: #666;\">\n            ${new Date(Date.now() - index * 1000 * 60).toLocaleString()}\n          \u003C\u002Fspan>\n        \u003C\u002Fdiv>\n      `;\n    },\n  });\n\n  \u002F\u002F Scroll to item 5000 after 2 seconds\n  setTimeout(() => {\n    virtualList.scrollToIndex(5000, true);\n  }, 2000);\n}\n\n\u002F**\n * Example 2: With Cleanup and Event Listeners\n *\u002F\nexport function exampleWithCleanup(): void {\n  const container = document.getElementById('list-container') as HTMLElement;\n\n  const virtualList = new SimpleVirtualList({\n    container,\n    itemHeight: 60,\n    totalItems: 50000,\n    renderItem: (index, element) => {\n      element.innerHTML = `\n        \u003Cdiv class=\"item-content\">\n          \u003Ch4>User ${index}\u003C\u002Fh4>\n          \u003Cbutton class=\"delete-btn\" data-index=\"${index}\">Delete\u003C\u002Fbutton>\n        \u003C\u002Fdiv>\n      `;\n\n      \u002F\u002F Add event listener\n      const btn = element.querySelector('.delete-btn') as HTMLElement;\n      if (btn) {\n        btn.addEventListener('click', () => {\n          console.log(`Delete item ${index}`);\n        });\n      }\n    },\n    onRecycle: (element) => {\n      \u002F\u002F Clean up event listeners when element is recycled\n      const btn = element.querySelector('.delete-btn') as HTMLElement;\n      if (btn) {\n        \u002F\u002F Clone and replace to remove all listeners\n        const newBtn = btn.cloneNode(true);\n        btn.parentNode?.replaceChild(newBtn, btn);\n      }\n    },\n  });\n\n  \u002F\u002F Example: Update total items dynamically\n  setTimeout(() => {\n    virtualList.setTotalItems(100000);\n  }, 5000);\n}\n\n\u002F**\n * Example 3: Integration with Data Source\n *\u002F\nexport class DataVirtualList\u003CT> {\n  private virtualList: SimpleVirtualList;\n  private data: T[] = [];\n  private renderer: (item: T, index: number, element: HTMLElement) => void;\n\n  constructor(\n    container: HTMLElement,\n    itemHeight: number,\n    renderer: (item: T, index: number, element: HTMLElement) => void\n  ) {\n    this.renderer = renderer;\n\n    this.virtualList = new SimpleVirtualList({\n      container,\n      itemHeight,\n      totalItems: 0,\n      renderItem: (index, element) => {\n        if (index \u003C this.data.length) {\n          this.renderer(this.data[index], index, element);\n        }\n      },\n    });\n  }\n\n  setData(data: T[]): void {\n    this.data = data;\n    this.virtualList.setTotalItems(data.length);\n  }\n\n  refresh(): void {\n    this.virtualList.refresh();\n  }\n\n  scrollToIndex(index: number): void {\n    this.virtualList.scrollToIndex(index, true);\n  }\n\n  destroy(): void {\n    this.virtualList.destroy();\n  }\n}\n\n\u002F\u002F Example usage with typed data\ninterface User {\n  id: number;\n  name: string;\n  email: string;\n}\n\nexport function exampleTypedData(): void {\n  const container = document.getElementById('user-list') as HTMLElement;\n\n  const userList = new DataVirtualList\u003CUser>(\n    container,\n    80,\n    (user, index, element) => {\n      element.innerHTML = `\n        \u003Cdiv style=\"padding: 15px; border-bottom: 1px solid #e0e0e0;\">\n          \u003Cdiv style=\"font-weight: bold; font-size: 16px;\">${user.name}\u003C\u002Fdiv>\n          \u003Cdiv style=\"color: #666; font-size: 14px;\">${user.email}\u003C\u002Fdiv>\n          \u003Cdiv style=\"color: #999; font-size: 12px;\">ID: ${user.id}\u003C\u002Fdiv>\n        \u003C\u002Fdiv>\n      `;\n    }\n  );\n\n  \u002F\u002F Generate sample data\n  const users: User[] = Array.from({ length: 100000 }, (_, i) => ({\n    id: i,\n    name: `User ${i}`,\n    email: `user${i}@example.com`,\n  }));\n\n  userList.setData(users);\n}\n```\n\n## Key Implementation Patterns\n\n### 1. **DOM Structure**\n```\nContainer\n└── Viewport (scrollable)\n    └── ContentWrapper (full height)\n        ├── TopSpacer (variable height)\n        ├── Item Elements (absolute positioned)\n        └── BottomSpacer (variable height)\n```\n\n### 2. **Scroll Event Flow**\n```\nScroll Event → RAF Throttle → Calculate Visible Range → Update Spacers → Recycle Items → Render Content\n```\n\n### 3. **Element Recycling Algorithm**\n1. Calculate new visible range\n2. Identify elements still in range (reuse)\n3. Find elements out of range (recycle candidates)\n4. Assign recycled elements to new indices\n5. Update positions with transform\n6. Hide off-screen elements\n\n### 4. **Performance Checklist**\n- ✅ Use `requestAnimationFrame` for scroll throttling\n- ✅ Add `{ passive: true }` to scroll listeners\n- ✅ Use `transform` instead of `top\u002Fleft` for positioning\n- ✅ Implement overscan buffer to prevent flickering\n- ✅ Skip updates when visible range hasn't changed\n- ✅ Use absolute positioning for precise control\n- ✅ Recycle DOM elements instead of creating\u002Fdestroying\n- ✅ Provide cleanup callback for event listeners\n\n## When to Use Virtual Lists\n\n### ✅ Use When:\n- Rendering 1,000+ items\n- Items have uniform\u002Fpredictable height\n- Scrolling performance is critical\n- Memory constraints are a concern\n- Data is paginated or infinite\n\n### ❌ Avoid When:\n- Lists are small (\u003C100 items)\n- Items have highly variable heights\n- Complex nested scrolling is required\n- You need to support keyboard navigation to all items\n- CSS grid\u002Fflexbox layouts are essential\n\n## Common Pitfalls\n\n1. **Forgetting to clean up event listeners** → Memory leaks\n   - Solution: Use `onRecycle` callback\n\n2. **Not using passive listeners** → Janky scrolling\n   - Solution: `{ passive: true }`\n\n3. **Synchronous expensive rendering** → Dropped frames\n   - Solution: Keep `renderItem` fast, defer heavy work\n\n4. **Variable item heights without measurement** → Misaligned items\n   - Solution: Use fixed heights or implement height caching\n\n5. **Not handling resize events** → Broken layout\n   - Solution: Add ResizeObserver or window resize listener\n\n## Advanced Enhancements\n\n### Dynamic Height Support\n```typescript\n\u002F\u002F Cache measured heights\nprivate heightCache = new Map\u003Cnumber, number>();\n\nprivate measureItem(index: number, element: HTMLElement): number {\n  if (!this.heightCache.has(index)) {\n    const height = element.getBoundingClientRect().height;\n    this.heightCache.set(index, height);\n  }\n  return this.heightCache.get(index)!;\n}\n```\n\n### Sticky Headers\n```typescript\n\u002F\u002F Track section headers\nprivate sectionHeaders = new Map\u003Cnumber, string>();\n\nprivate updateStickyHeader(): void {\n  const scrollTop = this.viewport.scrollTop;\n  const currentSection = this.getSectionAtOffset(scrollTop);\n  this.stickyHeaderElement.textContent = currentSection;\n}\n```\n\n### Bidirectional Scrolling\n```typescript\n\u002F\u002F Support horizontal + vertical scrolling\nprivate updateVisibleRange2D(): void {\n  const scrollX = this.viewport.scrollLeft;\n  const scrollY = this.viewport.scrollTop;\n  \n  const colStart = Math.floor(scrollX \u002F this.itemWidth);\n  const rowStart = Math.floor(scrollY \u002F this.itemHeight);\n  \u002F\u002F ... calculate visible grid cells\n}\n```\n\n## Testing Strategies\n\n```typescript\n\u002F\u002F Test with various scenarios\ndescribe('SimpleVirtualList', () => {\n  it('renders only visible items', () => {\n    const list = new SimpleVirtualList({...});\n    expect(list.getScrollInfo().visibleEnd - list.getScrollInfo().visibleStart)\n      .toBeLessThan(50); \u002F\u002F Even with 100k items\n  });\n\n  it('recycles elements on scroll', () => {\n    const recycledIndices: number[] = [];\n    const list = new SimpleVirtualList({\n      onRecycle: (el) => recycledIndices.push(parseInt(el.dataset.index!)),\n      ...\n    });\n    \n    list.scrollToIndex(1000);\n    expect(recycledIndices.length).toBeGreaterThan(0);\n  });\n\n  it('handles rapid scrolling', async () => {\n    const list = new SimpleVirtualList({...});\n    for (let i = 0; i \u003C 100; i++) {\n      list.scrollToIndex(i * 100);\n      await nextFrame();\n    }\n    \u002F\u002F Should not crash or have visual glitches\n  });\n});\n```\n\n## Summary\n\nVirtual scrolling is a critical technique for rendering large datasets efficiently. The key principles are:\n\n1. **Only render what's visible** - Create DOM nodes for viewport + buffer only\n2. **Recycle aggressively** - Reuse existing elements instead of creating new ones\n3. **Use spacers for height** - Maintain scroll position without rendering all items\n4. **Optimize scroll handling** - Use RAF throttling and passive listeners\n5. **Position with transforms** - Leverage GPU acceleration\n6. **Clean up properly** - Prevent memory leaks with recycle callbacks\n\nThis implementation can handle millions of items with smooth 60fps scrolling and minimal memory usage.\n","# Virtual List Implementation Skill\n\n## Overview\n\nThis skill teaches you how to implement a high-performance virtual scrolling list component that can efficiently render thousands or millions of items by only creating DOM nodes for visible items plus a small buffer.\n\n## Analysis of Reference Implementation\n\nThe VirtualList component from `\u002Fworldmonitor\u002Fsrc\u002Fcomponents\u002FVirtualList.ts` demonstrates professional-grade virtual scrolling with the following patterns:\n\n### 1. **Chunk-Based Rendering Pattern**\n\nThe implementation uses two complementary strategies:\n\n#### VirtualList (Fixed-Height Items)\n- **Item Pool Management**: Maintains a pool of reusable DOM elements (`PooledElement[]`)\n- **Viewport Calculation**: Calculates visible range based on `scrollTop`, `itemHeight`, and viewport dimensions\n- **Overscan Buffer**: Renders extra items above\u002Fbelow viewport (`overscan` parameter) to prevent flickering during scroll\n\n#### WindowedList (Variable-Height Items)\n- **Chunk-Based Approach**: Divides items into chunks (default 10 items per chunk)\n- **Lazy Chunk Rendering**: Only renders chunks that are visible or within buffer range\n- **Placeholder Elements**: Creates placeholders for all chunks upfront, renders content on-demand\n\n### 2. **Scroll Listener Optimization**\n\n```typescript\nprivate handleScroll = (): void => {\n  if (this.scrollRAF !== null) return;\n  \n  this.scrollRAF = requestAnimationFrame(() => {\n    this.scrollRAF = null;\n    if (!this.isDestroyed) {\n      this.updateVisibleRange();\n    }\n  });\n};\n```\n\n**Key Optimizations:**\n- **RequestAnimationFrame Throttling**: Prevents multiple renders in same frame\n- **Passive Listeners**: `{ passive: true }` improves scroll performance\n- **Debounce Check**: Guards against duplicate RAF calls\n- **Cleanup Check**: Prevents rendering after destruction\n\n### 3. **DOM Recycling Strategy**\n\nThe implementation uses a sophisticated two-pass recycling algorithm:\n\n**Pass 1: Identify Reusable Elements**\n```typescript\nfor (const pooled of this.itemPool) {\n  if (pooled.currentIndex >= visibleStart && pooled.currentIndex \u003C visibleEnd) {\n    usedIndices.add(pooled.currentIndex);\n  }\n}\n```\n\n**Pass 2: Recycle and Reassign**\n```typescript\nwhile (poolIndex \u003C this.itemPool.length) {\n  const pooled = this.itemPool[poolIndex]!;\n  if (pooled.currentIndex \u003C visibleStart || pooled.currentIndex >= visibleEnd) {\n    \u002F\u002F Recycle this element\n    if (this.onRecycle) {\n      this.onRecycle(pooled.element);\n    }\n    pooled.currentIndex = i;\n    this.renderItem(i, pooled.element);\n    pooled.element.style.transform = `translateY(${i * this.itemHeight}px)`;\n    poolIndex++;\n    break;\n  }\n  poolIndex++;\n}\n```\n\n**Benefits:**\n- Minimizes DOM manipulation\n- Reuses existing elements when possible\n- Allows cleanup of event listeners via `onRecycle` callback\n- Uses `transform: translateY()` for GPU-accelerated positioning\n\n### 4. **Performance Optimizations**\n\n#### Spacer Elements for Virtual Height\n```typescript\nthis.topSpacer.style.height = `${visibleStart * this.itemHeight}px`;\nthis.bottomSpacer.style.height = `${Math.max(0, (this.totalItems - visibleEnd) * this.itemHeight)}px`;\n```\n\n- Creates illusion of full list height without rendering all items\n- Maintains accurate scrollbar size and position\n\n#### Skip Unnecessary Updates\n```typescript\nif (visibleStart === this.visibleStart && visibleEnd === this.visibleEnd) {\n  return;\n}\n```\n\n#### CSS Positioning Strategy\n```typescript\nelement.style.position = 'absolute';\nelement.style.top = '0';\nelement.style.left = '0';\nelement.style.right = '0';\nelement.style.transform = 'translateY(-9999px)'; \u002F\u002F Hide off-screen\n```\n\n- Absolute positioning for precise control\n- Transform for GPU acceleration\n- Off-screen positioning instead of display:none (preserves element state)\n\n#### ResizeObserver Integration\n```typescript\nif (typeof ResizeObserver !== 'undefined') {\n  this.resizeObserver = new ResizeObserver(() => {\n    if (!this.isDestroyed) {\n      this.updateVisibleRange();\n    }\n  });\n  this.resizeObserver.observe(this.viewport);\n}\n```\n\n- Automatically recalculates visible range when viewport resizes\n- Progressive enhancement (checks for browser support)\n\n## Complete TypeScript Implementation Template\n\nBelow is a simplified but fully functional virtual list implementation that you can drop into any vanilla TypeScript project:\n\n```typescript\n\u002F**\n * SimpleVirtualList - A simplified virtual scrolling implementation\n * \n * Usage:\n * ```typescript\n * const virtualList = new SimpleVirtualList({\n *   container: document.getElementById('my-container')!,\n *   itemHeight: 50,\n *   totalItems: 100000,\n *   renderItem: (index, element) => {\n *     element.textContent = `Item ${index}`;\n *   }\n * });\n * ```\n *\u002F\n\nexport interface SimpleVirtualListOptions {\n  \u002F** Container element to render the virtual list into *\u002F\n  container: HTMLElement;\n  \n  \u002F** Fixed height of each item in pixels *\u002F\n  itemHeight: number;\n  \n  \u002F** Total number of items in the list *\u002F\n  totalItems: number;\n  \n  \u002F** Callback to render content for an item *\u002F\n  renderItem: (index: number, element: HTMLElement) => void;\n  \n  \u002F** Number of items to render beyond visible area (default: 5) *\u002F\n  overscan?: number;\n  \n  \u002F** Optional callback when item element is recycled *\u002F\n  onRecycle?: (element: HTMLElement) => void;\n}\n\ninterface VirtualItem {\n  element: HTMLElement;\n  index: number;\n}\n\nexport class SimpleVirtualList {\n  \u002F\u002F Configuration\n  private container: HTMLElement;\n  private itemHeight: number;\n  private totalItems: number;\n  private overscan: number;\n  private renderItem: (index: number, element: HTMLElement) => void;\n  private onRecycle?: (element: HTMLElement) => void;\n\n  \u002F\u002F DOM Structure\n  private viewport: HTMLElement;\n  private contentWrapper: HTMLElement;\n  private topSpacer: HTMLElement;\n  private bottomSpacer: HTMLElement;\n\n  \u002F\u002F State\n  private itemPool: VirtualItem[] = [];\n  private visibleStart = 0;\n  private visibleEnd = 0;\n  private rafId: number | null = null;\n  private destroyed = false;\n\n  constructor(options: SimpleVirtualListOptions) {\n    this.container = options.container;\n    this.itemHeight = options.itemHeight;\n    this.totalItems = options.totalItems;\n    this.overscan = options.overscan ?? 5;\n    this.renderItem = options.renderItem;\n    this.onRecycle = options.onRecycle;\n\n    this.setupDOM();\n    this.attachEventListeners();\n    this.updateVisibleRange();\n  }\n\n  \u002F**\n   * Set up the DOM structure for virtual scrolling\n   *\u002F\n  private setupDOM(): void {\n    \u002F\u002F Clear container\n    this.container.innerHTML = '';\n\n    \u002F\u002F Create viewport (scrollable container)\n    this.viewport = document.createElement('div');\n    this.viewport.style.cssText = `\n      width: 100%;\n      height: 100%;\n      overflow-y: auto;\n      position: relative;\n    `;\n\n    \u002F\u002F Create content wrapper\n    this.contentWrapper = document.createElement('div');\n    const totalHeight = this.totalItems * this.itemHeight;\n    this.contentWrapper.style.cssText = `\n      position: relative;\n      width: 100%;\n      height: ${totalHeight}px;\n    `;\n\n    \u002F\u002F Create spacers\n    this.topSpacer = document.createElement('div');\n    this.topSpacer.style.cssText = `\n      height: 0px;\n      width: 100%;\n    `;\n\n    this.bottomSpacer = document.createElement('div');\n    this.bottomSpacer.style.cssText = `\n      height: ${totalHeight}px;\n      width: 100%;\n    `;\n\n    \u002F\u002F Assemble DOM\n    this.contentWrapper.appendChild(this.topSpacer);\n    this.contentWrapper.appendChild(this.bottomSpacer);\n    this.viewport.appendChild(this.contentWrapper);\n    this.container.appendChild(this.viewport);\n  }\n\n  \u002F**\n   * Attach scroll event listeners with optimization\n   *\u002F\n  private attachEventListeners(): void {\n    this.viewport.addEventListener('scroll', this.handleScroll, { passive: true });\n  }\n\n  \u002F**\n   * Throttled scroll handler using requestAnimationFrame\n   *\u002F\n  private handleScroll = (): void => {\n    \u002F\u002F Prevent multiple RAF calls per frame\n    if (this.rafId !== null) return;\n\n    this.rafId = requestAnimationFrame(() => {\n      this.rafId = null;\n      \n      if (!this.destroyed) {\n        this.updateVisibleRange();\n      }\n    });\n  };\n\n  \u002F**\n   * Calculate and update which items should be visible\n   *\u002F\n  private updateVisibleRange(): void {\n    const scrollTop = this.viewport.scrollTop;\n    const viewportHeight = this.viewport.clientHeight;\n\n    \u002F\u002F Calculate visible indices\n    const startIndex = Math.floor(scrollTop \u002F this.itemHeight);\n    const endIndex = Math.ceil((scrollTop + viewportHeight) \u002F this.itemHeight);\n\n    \u002F\u002F Add overscan buffer\n    const bufferedStart = Math.max(0, startIndex - this.overscan);\n    const bufferedEnd = Math.min(this.totalItems, endIndex + this.overscan);\n\n    \u002F\u002F Skip if range hasn't changed\n    if (bufferedStart === this.visibleStart && bufferedEnd === this.visibleEnd) {\n      return;\n    }\n\n    this.visibleStart = bufferedStart;\n    this.visibleEnd = bufferedEnd;\n\n    \u002F\u002F Update spacers to maintain scroll position\n    this.topSpacer.style.height = `${bufferedStart * this.itemHeight}px`;\n    const bottomHeight = Math.max(0, (this.totalItems - bufferedEnd) * this.itemHeight);\n    this.bottomSpacer.style.height = `${bottomHeight}px`;\n\n    \u002F\u002F Render visible items\n    this.renderVisibleItems();\n  }\n\n  \u002F**\n   * Render or update items in the visible range using DOM recycling\n   *\u002F\n  private renderVisibleItems(): void {\n    const visibleCount = this.visibleEnd - this.visibleStart;\n\n    \u002F\u002F Ensure we have enough pooled elements\n    this.ensurePoolSize(visibleCount);\n\n    \u002F\u002F Track which indices are currently in use\n    const activeIndices = new Set\u003Cnumber>();\n\n    \u002F\u002F First pass: keep elements that are still visible\n    for (const item of this.itemPool) {\n      if (item.index >= this.visibleStart && item.index \u003C this.visibleEnd) {\n        activeIndices.add(item.index);\n      }\n    }\n\n    \u002F\u002F Second pass: recycle and assign new indices\n    let poolIndex = 0;\n    for (let i = this.visibleStart; i \u003C this.visibleEnd; i++) {\n      \u002F\u002F Skip if already rendered\n      if (activeIndices.has(i)) continue;\n\n      \u002F\u002F Find an element to recycle\n      while (poolIndex \u003C this.itemPool.length) {\n        const item = this.itemPool[poolIndex];\n        \n        \u002F\u002F Check if this element can be recycled\n        if (item.index \u003C this.visibleStart || item.index >= this.visibleEnd) {\n          \u002F\u002F Call recycle callback\n          if (this.onRecycle) {\n            this.onRecycle(item.element);\n          }\n\n          \u002F\u002F Update item\n          item.index = i;\n          this.renderItem(i, item.element);\n          this.positionItem(item);\n          \n          poolIndex++;\n          break;\n        }\n        \n        poolIndex++;\n      }\n    }\n\n    \u002F\u002F Third pass: update positions and visibility\n    for (const item of this.itemPool) {\n      if (item.index >= this.visibleStart && item.index \u003C this.visibleEnd) {\n        \u002F\u002F Ensure proper position\n        this.positionItem(item);\n        item.element.style.visibility = 'visible';\n      } else {\n        \u002F\u002F Hide off-screen items\n        item.element.style.visibility = 'hidden';\n        item.element.style.transform = 'translateY(-9999px)';\n      }\n    }\n  }\n\n  \u002F**\n   * Position an item element using transform for GPU acceleration\n   *\u002F\n  private positionItem(item: VirtualItem): void {\n    const yOffset = item.index * this.itemHeight;\n    item.element.style.transform = `translateY(${yOffset}px)`;\n  }\n\n  \u002F**\n   * Ensure the pool has enough elements\n   *\u002F\n  private ensurePoolSize(requiredSize: number): void {\n    while (this.itemPool.length \u003C requiredSize) {\n      const element = this.createItemElement();\n      const item: VirtualItem = {\n        element,\n        index: -1,\n      };\n      \n      this.itemPool.push(item);\n      \n      \u002F\u002F Insert before bottom spacer\n      this.contentWrapper.insertBefore(element, this.bottomSpacer);\n    }\n  }\n\n  \u002F**\n   * Create a new item element with proper styling\n   *\u002F\n  private createItemElement(): HTMLElement {\n    const element = document.createElement('div');\n    element.style.cssText = `\n      position: absolute;\n      top: 0;\n      left: 0;\n      width: 100%;\n      height: ${this.itemHeight}px;\n      box-sizing: border-box;\n      visibility: hidden;\n      transform: translateY(-9999px);\n    `;\n    element.classList.add('virtual-list-item');\n    return element;\n  }\n\n  \u002F**\n   * Update the total number of items\n   *\u002F\n  setTotalItems(count: number): void {\n    this.totalItems = count;\n    \n    \u002F\u002F Update content height\n    const totalHeight = this.totalItems * this.itemHeight;\n    this.contentWrapper.style.height = `${totalHeight}px`;\n    \n    \u002F\u002F Recalculate visible range\n    this.updateVisibleRange();\n  }\n\n  \u002F**\n   * Scroll to a specific item index\n   *\u002F\n  scrollToIndex(index: number, smooth = false): void {\n    const offset = Math.max(0, Math.min(index, this.totalItems - 1)) * this.itemHeight;\n    this.viewport.scrollTo({\n      top: offset,\n      behavior: smooth ? 'smooth' : 'auto',\n    });\n  }\n\n  \u002F**\n   * Force refresh all visible items\n   *\u002F\n  refresh(): void {\n    \u002F\u002F Mark all items as needing re-render\n    for (const item of this.itemPool) {\n      item.index = -1;\n    }\n    \n    \u002F\u002F Trigger update\n    this.updateVisibleRange();\n  }\n\n  \u002F**\n   * Get the current scroll position info\n   *\u002F\n  getScrollInfo(): { scrollTop: number; visibleStart: number; visibleEnd: number } {\n    return {\n      scrollTop: this.viewport.scrollTop,\n      visibleStart: this.visibleStart,\n      visibleEnd: this.visibleEnd,\n    };\n  }\n\n  \u002F**\n   * Clean up resources and remove event listeners\n   *\u002F\n  destroy(): void {\n    this.destroyed = true;\n\n    \u002F\u002F Cancel pending animation frame\n    if (this.rafId !== null) {\n      cancelAnimationFrame(this.rafId);\n      this.rafId = null;\n    }\n\n    \u002F\u002F Remove event listeners\n    this.viewport.removeEventListener('scroll', this.handleScroll);\n\n    \u002F\u002F Clear pool\n    this.itemPool = [];\n\n    \u002F\u002F Clear container\n    this.container.innerHTML = '';\n  }\n}\n\n\u002F\u002F ============================================================================\n\u002F\u002F CSS Styles (add to your stylesheet or inject programmatically)\n\u002F\u002F ============================================================================\n\n\u002F**\n * Recommended CSS for virtual list container:\n * \n * ```css\n * .virtual-list-container {\n *   width: 100%;\n *   height: 400px; \u002F\u002F or whatever height you need\n *   border: 1px solid #ddd;\n *   overflow: hidden;\n * }\n * \n * .virtual-list-item {\n *   border-bottom: 1px solid #eee;\n *   padding: 10px;\n *   display: flex;\n *   align-items: center;\n * }\n * \n * .virtual-list-item:hover {\n *   background-color: #f5f5f5;\n * }\n * ```\n *\u002F\n\n\u002F\u002F ============================================================================\n\u002F\u002F Usage Example\n\u002F\u002F ============================================================================\n\n\u002F**\n * Example 1: Basic Usage\n *\u002F\nexport function exampleBasicUsage(): void {\n  const container = document.createElement('div');\n  container.className = 'virtual-list-container';\n  container.style.cssText = 'width: 500px; height: 400px; border: 1px solid #ddd;';\n  document.body.appendChild(container);\n\n  const virtualList = new SimpleVirtualList({\n    container,\n    itemHeight: 50,\n    totalItems: 100000,\n    renderItem: (index, element) => {\n      element.innerHTML = `\n        \u003Cdiv style=\"padding: 10px; border-bottom: 1px solid #eee;\">\n          \u003Cstrong>Item ${index}\u003C\u002Fstrong>\n          \u003Cspan style=\"margin-left: 20px; color: #666;\">\n            ${new Date(Date.now() - index * 1000 * 60).toLocaleString()}\n          \u003C\u002Fspan>\n        \u003C\u002Fdiv>\n      `;\n    },\n  });\n\n  \u002F\u002F Scroll to item 5000 after 2 seconds\n  setTimeout(() => {\n    virtualList.scrollToIndex(5000, true);\n  }, 2000);\n}\n\n\u002F**\n * Example 2: With Cleanup and Event Listeners\n *\u002F\nexport function exampleWithCleanup(): void {\n  const container = document.getElementById('list-container') as HTMLElement;\n\n  const virtualList = new SimpleVirtualList({\n    container,\n    itemHeight: 60,\n    totalItems: 50000,\n    renderItem: (index, element) => {\n      element.innerHTML = `\n        \u003Cdiv class=\"item-content\">\n          \u003Ch4>User ${index}\u003C\u002Fh4>\n          \u003Cbutton class=\"delete-btn\" data-index=\"${index}\">Delete\u003C\u002Fbutton>\n        \u003C\u002Fdiv>\n      `;\n\n      \u002F\u002F Add event listener\n      const btn = element.querySelector('.delete-btn') as HTMLElement;\n      if (btn) {\n        btn.addEventListener('click', () => {\n          console.log(`Delete item ${index}`);\n        });\n      }\n    },\n    onRecycle: (element) => {\n      \u002F\u002F Clean up event listeners when element is recycled\n      const btn = element.querySelector('.delete-btn') as HTMLElement;\n      if (btn) {\n        \u002F\u002F Clone and replace to remove all listeners\n        const newBtn = btn.cloneNode(true);\n        btn.parentNode?.replaceChild(newBtn, btn);\n      }\n    },\n  });\n\n  \u002F\u002F Example: Update total items dynamically\n  setTimeout(() => {\n    virtualList.setTotalItems(100000);\n  }, 5000);\n}\n\n\u002F**\n * Example 3: Integration with Data Source\n *\u002F\nexport class DataVirtualList\u003CT> {\n  private virtualList: SimpleVirtualList;\n  private data: T[] = [];\n  private renderer: (item: T, index: number, element: HTMLElement) => void;\n\n  constructor(\n    container: HTMLElement,\n    itemHeight: number,\n    renderer: (item: T, index: number, element: HTMLElement) => void\n  ) {\n    this.renderer = renderer;\n\n    this.virtualList = new SimpleVirtualList({\n      container,\n      itemHeight,\n      totalItems: 0,\n      renderItem: (index, element) => {\n        if (index \u003C this.data.length) {\n          this.renderer(this.data[index], index, element);\n        }\n      },\n    });\n  }\n\n  setData(data: T[]): void {\n    this.data = data;\n    this.virtualList.setTotalItems(data.length);\n  }\n\n  refresh(): void {\n    this.virtualList.refresh();\n  }\n\n  scrollToIndex(index: number): void {\n    this.virtualList.scrollToIndex(index, true);\n  }\n\n  destroy(): void {\n    this.virtualList.destroy();\n  }\n}\n\n\u002F\u002F Example usage with typed data\ninterface User {\n  id: number;\n  name: string;\n  email: string;\n}\n\nexport function exampleTypedData(): void {\n  const container = document.getElementById('user-list') as HTMLElement;\n\n  const userList = new DataVirtualList\u003CUser>(\n    container,\n    80,\n    (user, index, element) => {\n      element.innerHTML = `\n        \u003Cdiv style=\"padding: 15px; border-bottom: 1px solid #e0e0e0;\">\n          \u003Cdiv style=\"font-weight: bold; font-size: 16px;\">${user.name}\u003C\u002Fdiv>\n          \u003Cdiv style=\"color: #666; font-size: 14px;\">${user.email}\u003C\u002Fdiv>\n          \u003Cdiv style=\"color: #999; font-size: 12px;\">ID: ${user.id}\u003C\u002Fdiv>\n        \u003C\u002Fdiv>\n      `;\n    }\n  );\n\n  \u002F\u002F Generate sample data\n  const users: User[] = Array.from({ length: 100000 }, (_, i) => ({\n    id: i,\n    name: `User ${i}`,\n    email: `user${i}@example.com`,\n  }));\n\n  userList.setData(users);\n}\n```\n\n## Key Implementation Patterns\n\n### 1. **DOM Structure**\n```\nContainer\n└── Viewport (scrollable)\n    └── ContentWrapper (full height)\n        ├── TopSpacer (variable height)\n        ├── Item Elements (absolute positioned)\n        └── BottomSpacer (variable height)\n```\n\n### 2. **Scroll Event Flow**\n```\nScroll Event → RAF Throttle → Calculate Visible Range → Update Spacers → Recycle Items → Render Content\n```\n\n### 3. **Element Recycling Algorithm**\n1. Calculate new visible range\n2. Identify elements still in range (reuse)\n3. Find elements out of range (recycle candidates)\n4. Assign recycled elements to new indices\n5. Update positions with transform\n6. Hide off-screen elements\n\n### 4. **Performance Checklist**\n- ✅ Use `requestAnimationFrame` for scroll throttling\n- ✅ Add `{ passive: true }` to scroll listeners\n- ✅ Use `transform` instead of `top\u002Fleft` for positioning\n- ✅ Implement overscan buffer to prevent flickering\n- ✅ Skip updates when visible range hasn't changed\n- ✅ Use absolute positioning for precise control\n- ✅ Recycle DOM elements instead of creating\u002Fdestroying\n- ✅ Provide cleanup callback for event listeners\n\n## When to Use Virtual Lists\n\n### ✅ Use When:\n- Rendering 1,000+ items\n- Items have uniform\u002Fpredictable height\n- Scrolling performance is critical\n- Memory constraints are a concern\n- Data is paginated or infinite\n\n### ❌ Avoid When:\n- Lists are small (\u003C100 items)\n- Items have highly variable heights\n- Complex nested scrolling is required\n- You need to support keyboard navigation to all items\n- CSS grid\u002Fflexbox layouts are essential\n\n## Common Pitfalls\n\n1. **Forgetting to clean up event listeners** → Memory leaks\n   - Solution: Use `onRecycle` callback\n\n2. **Not using passive listeners** → Janky scrolling\n   - Solution: `{ passive: true }`\n\n3. **Synchronous expensive rendering** → Dropped frames\n   - Solution: Keep `renderItem` fast, defer heavy work\n\n4. **Variable item heights without measurement** → Misaligned items\n   - Solution: Use fixed heights or implement height caching\n\n5. **Not handling resize events** → Broken layout\n   - Solution: Add ResizeObserver or window resize listener\n\n## Advanced Enhancements\n\n### Dynamic Height Support\n```typescript\n\u002F\u002F Cache measured heights\nprivate heightCache = new Map\u003Cnumber, number>();\n\nprivate measureItem(index: number, element: HTMLElement): number {\n  if (!this.heightCache.has(index)) {\n    const height = element.getBoundingClientRect().height;\n    this.heightCache.set(index, height);\n  }\n  return this.heightCache.get(index)!;\n}\n```\n\n### Sticky Headers\n```typescript\n\u002F\u002F Track section headers\nprivate sectionHeaders = new Map\u003Cnumber, string>();\n\nprivate updateStickyHeader(): void {\n  const scrollTop = this.viewport.scrollTop;\n  const currentSection = this.getSectionAtOffset(scrollTop);\n  this.stickyHeaderElement.textContent = currentSection;\n}\n```\n\n### Bidirectional Scrolling\n```typescript\n\u002F\u002F Support horizontal + vertical scrolling\nprivate updateVisibleRange2D(): void {\n  const scrollX = this.viewport.scrollLeft;\n  const scrollY = this.viewport.scrollTop;\n  \n  const colStart = Math.floor(scrollX \u002F this.itemWidth);\n  const rowStart = Math.floor(scrollY \u002F this.itemHeight);\n  \u002F\u002F ... calculate visible grid cells\n}\n```\n\n## Testing Strategies\n\n```typescript\n\u002F\u002F Test with various scenarios\ndescribe('SimpleVirtualList', () => {\n  it('renders only visible items', () => {\n    const list = new SimpleVirtualList({...});\n    expect(list.getScrollInfo().visibleEnd - list.getScrollInfo().visibleStart)\n      .toBeLessThan(50); \u002F\u002F Even with 100k items\n  });\n\n  it('recycles elements on scroll', () => {\n    const recycledIndices: number[] = [];\n    const list = new SimpleVirtualList({\n      onRecycle: (el) => recycledIndices.push(parseInt(el.dataset.index!)),\n      ...\n    });\n    \n    list.scrollToIndex(1000);\n    expect(recycledIndices.length).toBeGreaterThan(0);\n  });\n\n  it('handles rapid scrolling', async () => {\n    const list = new SimpleVirtualList({...});\n    for (let i = 0; i \u003C 100; i++) {\n      list.scrollToIndex(i * 100);\n      await nextFrame();\n    }\n    \u002F\u002F Should not crash or have visual glitches\n  });\n});\n```\n\n## Summary\n\nVirtual scrolling is a critical technique for rendering large datasets efficiently. The key principles are:\n\n1. **Only render what's visible** - Create DOM nodes for viewport + buffer only\n2. **Recycle aggressively** - Reuse existing elements instead of creating new ones\n3. **Use spacers for height** - Maintain scroll position without rendering all items\n4. **Optimize scroll handling** - Use RAF throttling and passive listeners\n5. **Position with transforms** - Leverage GPU acceleration\n6. **Clean up properly** - Prevent memory leaks with recycle callbacks\n\nThis implementation can handle millions of items with smooth 60fps scrolling and minimal memory usage.\n",{"name":5,"description":7},"main","0650921d63895de3997bc81f1ff1d0ac67032072","showcase\u002Fskills\u002Fvirtual-list","https:\u002F\u002Fgithub.com\u002FUF-gzj\u002Fopenspace-claude-evolution","https:\u002F\u002Fgithub.com\u002FUF-gzj","2026-04-16 09:31:03",{"source":8,"skillName":5,"commands":41,"prompt":51,"zipAvailable":52},[42,45,48],{"tool":43,"command":44},"npx","npx skills add UF-gzj\u002Fopenspace-claude-evolution --skill virtual-list",{"tool":46,"command":47},"bunx","bunx skills add UF-gzj\u002Fopenspace-claude-evolution --skill virtual-list",{"tool":49,"command":50},"pnpm","pnpm dlx skills add UF-gzj\u002Fopenspace-claude-evolution --skill virtual-list","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FUF-gzj\u002Fopenspace-claude-evolution\u002Fblob\u002Fmain\u002Fshowcase\u002Fskills\u002Fvirtual-list\u002FSKILL.md",true,[54],{"path":55,"resourceType":56,"resourceTypeDesc":57,"sizeBytes":58,"sourceHtmlUrl":59},".skill_id","OTHER","其他",27,"https:\u002F\u002Fgithub.com\u002FUF-gzj\u002Fopenspace-claude-evolution\u002Fblob\u002Fmain\u002Fshowcase\u002Fskills\u002Fvirtual-list\u002F.skill_id",[61,85,101,110,140,156],{"skillNo":62,"name":63,"nameZh":6,"description":64,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":65,"categories":66,"keywords":67,"publishedAt":29},"01M6XCCXD3NCM2YKR3WNGBASPC","write-special-chars-ts-check","Workaround for write_file failures caused by special characters (apostrophes, backticks, template literals) using a Python heredoc script, plus a reliable TypeScript type-checking step that filters output to only the newly-written files to avoid being misled by pre-existing errors.","https:\u002F\u002Fgithub.com\u002FUF-gzj\u002Fopenspace-claude-evolution\u002Fblob\u002Fmain\u002Fshowcase\u002Fskills\u002Fwrite-special-chars-ts-check\u002FSKILL.md",[],[68,69,70,71,72,73,74,28,75,76,77,78,79,80,81,82,83,84],"check","write","write special chars ts check","filters","characters","Existing","type-checking","errors","script","output","type","files","only","template","file","python","typescript",{"skillNo":86,"name":87,"nameZh":6,"description":88,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":89,"categories":90,"keywords":91,"publishedAt":29},"01M6XCCT7E3J922Q345PBGSHPN","write-special-chars-readback","Workaround for write_file failures caused by special characters (apostrophes, backticks, template literals) using a Python heredoc script, with mandatory post-write verification via read_file and cleanup of \u002Ftmp helper scripts.","https:\u002F\u002Fgithub.com\u002FUF-gzj\u002Fopenspace-claude-evolution\u002Fblob\u002Fmain\u002Fshowcase\u002Fskills\u002Fwrite-special-chars-readback\u002FSKILL.md",[],[92,93,69,94,95,96,72,97,98,81,83,82,99,100,28,76,26],"readback","write special chars readback","read","post","via","scripts","cleanup","verification","helper",{"skillNo":102,"name":103,"nameZh":6,"description":104,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":105,"categories":106,"keywords":107,"publishedAt":29},"01M6XCCMQX1R8B6FECWB3P63T7","write-special-chars-heredoc","Workaround for write_file failures caused by special characters (apostrophes, backticks, template literals) by using a Python heredoc script executed via shell.","https:\u002F\u002Fgithub.com\u002FUF-gzj\u002Fopenspace-claude-evolution\u002Fblob\u002Fmain\u002Fshowcase\u002Fskills\u002Fwrite-special-chars-heredoc\u002FSKILL.md",[],[69,108,76,28,72,81,109,82,83,96],"write special chars heredoc","shell",{"skillNo":111,"name":112,"nameZh":6,"description":113,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":114,"categories":115,"keywords":121,"publishedAt":29},"01M6XCCG41M994JJEX6VN52PEP","worldmonitor-reference","Curated architecture index of the WorldMonitor open-source dashboard. Reference for extracting patterns — vanilla TypeScript, Panel class hierarchy, service layer, CSS grid, API edge functions, refresh scheduler, and 60+ data source integrations.","https:\u002F\u002Fgithub.com\u002FUF-gzj\u002Fopenspace-claude-evolution\u002Fblob\u002Fmain\u002Fshowcase\u002Fskills\u002Fworldmonitor-reference\u002FSKILL.md",[116],{"categoryNo":117,"categoryName":118,"taxonomyType":119,"taxonomyTypeDesc":120},"01JBSEEDCAT000000000000033","数据分析师","PROFESSION","适用职业",[122,123,124,125,126,127,128,28,129,130,131,132,133,134,135,136,137,138,139,84],"reference","worldmonitor","worldmonitor reference","source","css","patterns","hierarchy","layer","extracting","panel","edge functions","integrations","open","api","data","scheduler","architecture","dashboard",{"skillNo":141,"name":142,"nameZh":6,"description":143,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":144,"categories":145,"keywords":146,"publishedAt":29},"01M6XCC7X8PKMR2DEW91XGHYSV","verify-directory-structure","Diagnose and resolve file access issues by first verifying the directory structure.","https:\u002F\u002Fgithub.com\u002FUF-gzj\u002Fopenspace-claude-evolution\u002Fblob\u002Fmain\u002Fshowcase\u002Fskills\u002Fverify-directory-structure\u002FSKILL.md",[],[147,148,149,150,151,152,82,153,154,155],"verify directory structure","structure","verify","directory","access","first","issues","diagnose","file access",{"skillNo":157,"name":158,"nameZh":6,"description":159,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":160,"categories":161,"keywords":162,"publishedAt":29},"01M6XCC3HAJNFB6WZAHV6YW5AV","verify-directory-structure-parallel-audit","Diagnose and resolve file access issues by verifying directory structure, then reading multiple files in parallel batches for efficient auditing, with built-in guidance for validating TypeScript import patterns.","https:\u002F\u002Fgithub.com\u002FUF-gzj\u002Fopenspace-claude-evolution\u002Fblob\u002Fmain\u002Fshowcase\u002Fskills\u002Fverify-directory-structure-parallel-audit\u002FSKILL.md",[],[147,163,150,148,164,149,165,26,28,166,167,168,169,79,151,82,153,154,84,155],"verify directory structure parallel audit","parallel","audit","batches","reading","import","guidance"]