[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6HXDKCS7E9N8E0RJJ5XV2MX":3,"skill-same:01M6HXDKCS7E9N8E0RJJ5XV2MX":63},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":30,"linkOnly":31,"markdownContent":32,"markdownBody":33,"frontMatter":34,"refName":35,"commitSha":36,"skillDirectory":37,"forksCount":38,"repositoryHtmlUrl":39,"repositoryHomepageUrl":6,"ownerHtmlUrl":40,"ownerBlogUrl":41,"ownerDescription":6,"updatedAt":42,"install":43,"resources":56},"01M6HXDKCS7E9N8E0RJJ5XV2MX","virtual-list",null,"Implement efficient virtual scrolling for rendering large lists with DOM recycling, chunk-based rendering, and performance optimizations","HKUDS\u002FAgentPilot","HKUDS","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F118165258?v=4","01M6HW8VRNZP64G0P4MVJW2KKQ","✨Data Intelligence Lab@HKU✨","01M6HW8VWZVHBRHYH3T330PFWV",8029,"MIT","https:\u002F\u002Fgithub.com\u002FHKUDS\u002FAgentPilot\u002Fblob\u002Fmain\u002Fopenspace\u002Fexamples\u002Fmy-daily-monitor\u002Fskills\u002Fvirtual-list\u002FSKILL.md",[],[19,20,21,22,23,24,25,26,27,28,29],"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","6b84b0689ca0d9e7b1e4061188ff6b60758e0f8a","openspace\u002Fexamples\u002Fmy-daily-monitor\u002Fskills\u002Fvirtual-list",944,"https:\u002F\u002Fgithub.com\u002FHKUDS\u002FAgentPilot","https:\u002F\u002Fgithub.com\u002FHKUDS","https:\u002F\u002Fsites.google.com\u002Fview\u002Fchaoh","2026-11-12 22:26:39",{"source":8,"skillName":5,"commands":44,"prompt":54,"zipAvailable":55},[45,48,51],{"tool":46,"command":47},"npx","npx skills add HKUDS\u002FAgentPilot --skill virtual-list",{"tool":49,"command":50},"bunx","bunx skills add HKUDS\u002FAgentPilot --skill virtual-list",{"tool":52,"command":53},"pnpm","pnpm dlx skills add HKUDS\u002FAgentPilot --skill virtual-list","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FHKUDS\u002FAgentPilot\u002Fblob\u002Fmain\u002Fopenspace\u002Fexamples\u002Fmy-daily-monitor\u002Fskills\u002Fvirtual-list\u002FSKILL.md",true,[57],{"path":58,"resourceType":59,"resourceTypeDesc":60,"sizeBytes":61,"sourceHtmlUrl":62},".skill_id","OTHER","其他",27,"https:\u002F\u002Fgithub.com\u002FHKUDS\u002FAgentPilot\u002Fblob\u002Fmain\u002Fopenspace\u002Fexamples\u002Fmy-daily-monitor\u002Fskills\u002Fvirtual-list\u002F.skill_id",[64,83,102,122,144,167],{"skillNo":65,"name":66,"nameZh":6,"description":67,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":68,"categories":69,"keywords":70,"publishedAt":30},"01M6HYB297NDABRERJRVG0K8R0","agentpilot","Set up AgentPilot and use its single entry to prepare missing inputs and run configured RSI experiments. Use when the user requests AgentPilot installation or work with AgentPilot.","https:\u002F\u002Fgithub.com\u002FHKUDS\u002FAgentPilot\u002Fblob\u002Fmain\u002Fplugins\u002Fagentpilot\u002Fskills\u002Fagentpilot\u002FSKILL.md",[],[66,71,72,27,73,74,75,76,77,78,79,80,81,82],"prepare","requests","missing","installation","rsi","up","use","user","work","SET","run","experiments",{"skillNo":84,"name":85,"nameZh":6,"description":86,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":87,"categories":88,"keywords":89,"publishedAt":30},"01M6HYAYWXTTE1J7DJM0MFNQ4H","remember","Review auto-memory entries and propose promotions to OPENSPACE.md, OPENSPACE.local.md, or retained auto-memory topics; detect duplicates, stale facts, conflicts, and ambiguous entries before making changes.","https:\u002F\u002Fgithub.com\u002FHKUDS\u002FAgentPilot\u002Fblob\u002Fmain\u002Fopenspace\u002Fopenspace\u002Fskills\u002Fremember\u002FSKILL.md",[],[85,90,91,92,93,94,95,96,97,98,99,100,101],"memory","review","auto","openspace","changes","facts","detect","entries","local","conflicts","stale","duplicates",{"skillNo":103,"name":104,"nameZh":6,"description":105,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":106,"categories":107,"keywords":108,"publishedAt":30},"01M6HYAVMPM4SBDV60R2B5HPV8","skill-discovery","Search reusable OpenSpace skills locally, and browse cloud packages step by step when a cloud skill may help. Reusing proven skills saves tokens, improves reliability, and extends your capabilities beyond built-in tools.","https:\u002F\u002Fgithub.com\u002FHKUDS\u002FAgentPilot\u002Fblob\u002Fmain\u002Fopenspace\u002Fopenspace\u002Fhost_skills\u002Fskill-discovery\u002FSKILL.md",[],[109,110,111,93,112,113,114,115,116,117,118,119,120,121],"skill discovery","discovery","reusable","step by step","tokens","packages","help","cloud","reliability","capabilities","browse","search","Tools",{"skillNo":123,"name":124,"nameZh":6,"description":125,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":126,"categories":127,"keywords":128,"publishedAt":30},"01M6HYAR811B3RB0M50RBEDGN6","delegate-task","Delegate tasks to OpenSpace — a full-stack autonomous worker for coding, DevOps, web research, and desktop automation, backed by an extensive MCP tool and skill library. Skills auto-improve through use, reducing token consumption over time. A cloud community lets agents share and collectively evolve reusable skills.","https:\u002F\u002Fgithub.com\u002FHKUDS\u002FAgentPilot\u002Fblob\u002Fmain\u002Fopenspace\u002Fopenspace\u002Fhost_skills\u002Fdelegate-task\u002FSKILL.md",[],[129,130,131,93,132,133,134,135,136,111,92,77,137,138,139,29,140,141,142,143],"delegate","task","delegate task","time","improve","desktop automation","worker","community","autonomous","tool","stack","share","tasks","automation","MCP",{"skillNo":145,"name":146,"nameZh":6,"description":147,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":148,"categories":149,"keywords":150,"publishedAt":30},"01M6HYAM9FSGV6E52AYENDQXYH","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\u002FHKUDS\u002FAgentPilot\u002Fblob\u002Fmain\u002Fopenspace\u002Flegacy\u002Fv1\u002Fshowcase\u002Fskills\u002Fwrite-special-chars-ts-check\u002FSKILL.md",[],[151,152,153,154,155,156,157,158,159,160,161,162,163,164,29,165,166],"write special chars ts check","write","check","type","files","filters","only","template","file","python","typescript","output","Existing","type-checking","errors","script",{"skillNo":168,"name":169,"nameZh":6,"description":170,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":171,"categories":172,"keywords":173,"publishedAt":30},"01M6HYAH05HGV7SVWSVR8PJRQD","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\u002FHKUDS\u002FAgentPilot\u002Fblob\u002Fmain\u002Fopenspace\u002Flegacy\u002Fv1\u002Fshowcase\u002Fskills\u002Fwrite-special-chars-readback\u002FSKILL.md",[],[174,175,152,27,29,166,176,177,178,179,180,158,159,181,182,160],"write special chars readback","readback","helper","post","via","scripts","read","verification","cleanup"]