[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6KKFA31TT7YW4CTMFGPYWPW":3,"skill-same:01M6KKFA31TT7YW4CTMFGPYWPW":69},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":9,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":15,"categories":16,"keywords":17,"publishedAt":37,"linkOnly":38,"markdownContent":39,"markdownBody":40,"frontMatter":41,"refName":42,"commitSha":43,"skillDirectory":44,"forksCount":13,"repositoryHtmlUrl":45,"repositoryHomepageUrl":6,"ownerHtmlUrl":46,"ownerBlogUrl":6,"ownerDescription":47,"updatedAt":48,"install":49,"resources":62},"01M6KKFA31TT7YW4CTMFGPYWPW","panel-component-colocated-helpers",null,"Enhanced dashboard panel component with robust error handling, retry logic, localStorage persistence, and co-located inline helper functions (e.g. timeAgo, statusIcon) for self-contained, import-light panel implementations.","AG064\u002FOpenSpace","AG064","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F184930299?v=4","01M6KHVFG7TB73NHX3RDYSTMH2","01M6KHVFMM7XA2PZA9Z83PHS3V",0,"MIT","https:\u002F\u002Fgithub.com\u002FAG064\u002FOpenSpace\u002Fblob\u002Fmain\u002Fshowcase\u002Fskills\u002Fpanel-component-colocated-helpers\u002FSKILL.md",[],[18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36],"component","panel component","panel component colocated helpers","panel","self-contained","dashboard","inline","for","retry","with","co","helper","error","import","logic","self","functions","persistence","error handling","2026-11-10 10:12:30",false,"---\nname: panel-component-colocated-helpers\ndescription: Enhanced dashboard panel component with robust error handling, retry logic, localStorage persistence, and co-located inline helper functions (e.g. timeAgo, statusIcon) for self-contained, import-light panel implementations.\n---\n\n# Panel Component Pattern\n\nCreate dashboard panel components using **vanilla TypeScript** (no framework, no JSX). Each panel is a class extending a `Panel` base class.\n\n## Architecture Overview\n\n### Enhanced Features\n- **Retry Logic**: Automatically retries failed data fetches with exponential backoff.\n- **State Persistence**: Saves panel state (expanded\u002Fcollapsed, size) to localStorage.\n- **Detailed Error Handling**: Provides more granular error messages and recovery options.\n- **Co-located Helpers**: Panel-specific pure utility functions live in the same file as the panel class, keeping implementations self-contained.\n\n```\nPanel (base class)\n├── element: HTMLElement (outer container, .panel)\n│   ├── header: HTMLElement (.panel-header)\n│   │   ├── headerLeft (.panel-header-left)\n│   │   │   ├── title (.panel-title)\n│   │   │   └── newBadge (.panel-new-badge) [optional]\n│   │   ├── statusBadge (.panel-data-badge) [optional]\n│   │   └── countEl (.panel-count) [optional]\n│   ├── content: HTMLElement (.panel-content)\n│   └── resizeHandle (.panel-resize-handle)\n```\n\n## Base Panel Class (Simplified for this project)\n\n```typescript\nexport class Panel {\n  \u002F\u002F ... existing code ...\n\n  private retryAttempts = 0;\n  private maxRetries = 3;\n  private retryDelay = 1000; \u002F\u002F starts at 1s, doubles each retry\n\n  protected async fetchWithRetry(url: string): Promise\u003Cany> {\n    while (this.retryAttempts \u003C this.maxRetries) {\n      try {\n        const response = await fetch(url);\n        if (!response.ok) throw new Error(`HTTP ${response.status}`);\n        return await response.json();\n      } catch (error) {\n        this.retryAttempts++;\n        if (this.retryAttempts >= this.maxRetries) {\n          throw new Error(`Failed after ${this.maxRetries} attempts: ${error.message}`);\n        }\n        await new Promise(resolve => setTimeout(resolve, this.retryDelay));\n        this.retryDelay *= 2;\n      }\n    }\n  }\n\n  public saveState(): void {\n    localStorage.setItem(`panelState_${this.panelId}`, JSON.stringify({\n      isExpanded: !this.element.classList.contains('collapsed'),\n      width: this.element.style.width,\n      height: this.element.style.height\n    }));\n  }\n\n  public loadState(): void {\n    const savedState = localStorage.getItem(`panelState_${this.panelId}`);\n    if (savedState) {\n      const { isExpanded, width, height } = JSON.parse(savedState);\n      if (!isExpanded) this.element.classList.add('collapsed');\n      if (width) this.element.style.width = width;\n      if (height) this.element.style.height = height;\n    }\n  }\n}\n```\n\nCreate `src\u002Fcomponents\u002FPanel.ts`:\n\n```typescript\nexport interface PanelOptions {\n  id: string;\n  title: string;\n  showCount?: boolean;\n  className?: string;\n}\n\nexport class Panel {\n  protected element: HTMLElement;\n  protected content: HTMLElement;\n  protected header: HTMLElement;\n  protected countEl: HTMLElement | null = null;\n  protected panelId: string;\n  private _fetching = false;\n\n  constructor(options: PanelOptions) {\n    this.panelId = options.id;\n    this.element = document.createElement('div');\n    this.element.className = `panel ${options.className || ''}`;\n    this.element.dataset.panel = options.id;\n\n    \u002F\u002F Header\n    this.header = document.createElement('div');\n    this.header.className = 'panel-header';\n\n    const headerLeft = document.createElement('div');\n    headerLeft.className = 'panel-header-left';\n\n    const title = document.createElement('span');\n    title.className = 'panel-title';\n    title.textContent = options.title;\n    headerLeft.appendChild(title);\n    this.header.appendChild(headerLeft);\n\n    \u002F\u002F Count badge (optional)\n    if (options.showCount) {\n      this.countEl = document.createElement('span');\n      this.countEl.className = 'panel-count';\n      this.countEl.textContent = '0';\n      this.header.appendChild(this.countEl);\n    }\n\n    \u002F\u002F Content area\n    this.content = document.createElement('div');\n    this.content.className = 'panel-content';\n    this.content.id = `${options.id}Content`;\n\n    this.element.appendChild(this.header);\n    this.element.appendChild(this.content);\n    this.showLoading();\n  }\n\n  public getElement(): HTMLElement { return this.element; }\n\n  public showLoading(message = 'Loading...'): void {\n    this.content.innerHTML = `\n      \u003Cdiv class=\"panel-loading\">\n        \u003Cdiv class=\"panel-loading-spinner\">\u003C\u002Fdiv>\n        \u003Cdiv class=\"panel-loading-text\">${message}\u003C\u002Fdiv>\n      \u003C\u002Fdiv>`;\n  }\n\n  public showError(message = 'Failed to load', onRetry?: () => void): void {\n    this.content.innerHTML = `\n      \u003Cdiv class=\"panel-error-state\">\n        \u003Cdiv class=\"panel-error-msg\">${message}\u003C\u002Fdiv>\n        ${onRetry ? '\u003Cbutton class=\"panel-retry-btn\" data-panel-retry>Retry\u003C\u002Fbutton>' : ''}\n      \u003C\u002Fdiv>`;\n    if (onRetry) {\n      this.content.querySelector('[data-panel-retry]')?.addEventListener('click', onRetry);\n    }\n  }\n\n  public setContent(html: string): void {\n    this.content.innerHTML = html;\n  }\n\n  public setCount(count: number): void {\n    if (this.countEl) this.countEl.textContent = count.toString();\n  }\n\n  public show(): void { this.element.classList.remove('hidden'); }\n  public hide(): void { this.element.classList.add('hidden'); }\n\n  protected setFetching(v: boolean): void { this._fetching = v; }\n  protected get isFetching(): boolean { return this._fetching; }\n\n  public destroy(): void {\n    this.element.remove();\n  }\n}\n```\n\n## Creating a Concrete Panel (Example: StockPanel)\n\n```typescript\nexport class StockPanel extends Panel {\n  \u002F\u002F ... existing code ...\n\n  private async fetchData(): Promise\u003Cvoid> {\n    if (this.isFetching) return;\n    this.setFetching(true);\n    try {\n      const quotes = await this.fetchWithRetry('\u002Fapi\u002Fstocks');\n      this.render(quotes);\n      this.setCount(quotes.length);\n      this.saveState();\n    } catch (err) {\n      this.showError(`Failed to load stock data: ${err.message}`, () => {\n        this.retryAttempts = 0;\n        this.retryDelay = 1000;\n        this.fetchData();\n      });\n    } finally {\n      this.setFetching(false);\n    }\n  }\n}\n```\n\nEach panel extends `Panel` and manages its own data fetching + rendering:\n\n```typescript\nimport { Panel } from '.\u002FPanel';\n\ninterface StockQuote {\n  symbol: string;\n  name: string;\n  price: number | null;\n  change: number | null;\n  sparkline?: number[];\n}\n\nexport class StockPanel extends Panel {\n  private refreshTimer: ReturnType\u003Ctypeof setInterval> | null = null;\n\n  constructor() {\n    super({ id: 'stocks', title: 'Stock Market', showCount: true });\n    this.fetchData();\n    this.refreshTimer = setInterval(() => this.fetchData(), 60_000);\n  }\n\n  private async fetchData(): Promise\u003Cvoid> {\n    if (this.isFetching) return;\n    this.setFetching(true);\n    try {\n      const quotes = await fetchStockQuotes(); \u002F\u002F from data-service\n      this.render(quotes);\n      this.setCount(quotes.length);\n    } catch (err) {\n      this.showError('Failed to load stock data', () => this.fetchData());\n    } finally {\n      this.setFetching(false);\n    }\n  }\n\n  private render(quotes: StockQuote[]): void {\n    const rows = quotes.map(q => `\n      \u003Cdiv class=\"stock-row\">\n        \u003Cspan class=\"stock-symbol\">${q.symbol}\u003C\u002Fspan>\n        \u003Cspan class=\"stock-name\">${q.name}\u003C\u002Fspan>\n        \u003Cspan class=\"stock-price\">${q.price != null ? '$' + q.price.toFixed(2) : '—'}\u003C\u002Fspan>\n        \u003Cspan class=\"stock-change ${(q.change ?? 0) >= 0 ? 'positive' : 'negative'}\">\n          ${q.change != null ? (q.change >= 0 ? '+' : '') + q.change.toFixed(2) + '%' : '—'}\n        \u003C\u002Fspan>\n      \u003C\u002Fdiv>\n    `).join('');\n\n    this.setContent(`\u003Cdiv class=\"stock-list\">${rows}\u003C\u002Fdiv>`);\n  }\n\n  public override destroy(): void {\n    if (this.refreshTimer) clearInterval(this.refreshTimer);\n    super.destroy();\n  }\n}\n```\n\n## Key Patterns\n\n1. **Constructor** calls `super()` with panel config, then triggers initial data fetch\n2. **fetchData()** is async, uses `isFetching` guard, shows error on failure with retry\n3. **render()** builds HTML strings and calls `this.setContent(html)`\n4. **destroy()** cleans up timers and event listeners\n5. Use `showLoading()` during initial load (auto-called in constructor)\n6. Use `showError(msg, retryFn)` on failure\n7. Sparkline SVGs use inline `\u003Csvg>` with `\u003Cpolyline>` — see sparkline utility\n8. **Co-located helpers**: Define panel-specific pure utility functions (e.g. `timeAgo`, `statusIcon`) as module-level functions in the same `.ts` file as the panel class. Do **not** place them in `src\u002Futils` unless they are reused by three or more panels.\n\n## Co-located Helper Pattern\n\nPanel-specific formatting and mapping utilities live directly above the class\ndefinition in the same file. This keeps the panel self-contained, avoids\npolluting `src\u002Futils`, and makes the file easier to read and test in isolation.\n\n### When to co-locate\n\n| Situation | Decision |\n|-----------|----------|\n| Helper used only in this panel | ✅ Co-locate in panel file |\n| Helper used in 2 panels | ✅ Co-locate in the more \"owning\" panel; import from there |\n| Helper used in 3+ panels | ❌ Move to `src\u002Futils\u002F\u003Chelper>.ts` |\n| Helper depends on DOM or Panel API | ✅ Always co-locate (private method or module function) |\n\n### timeAgo — relative timestamp helper\n\n```typescript\n\u002F\u002F co-located at the top of, e.g., src\u002Fcomponents\u002FCodeStatusPanel.ts\n\n\u002F** Returns a human-readable relative time string, e.g. \"3 minutes ago\". *\u002F\nfunction timeAgo(dateStr: string): string {\n  const diff = Date.now() - new Date(dateStr).getTime();\n  const minutes = Math.floor(diff \u002F 60_000);\n  if (minutes \u003C 1)  return 'just now';\n  if (minutes \u003C 60) return `${minutes} minute${minutes === 1 ? '' : 's'} ago`;\n  const hours = Math.floor(minutes \u002F 60);\n  if (hours \u003C 24)   return `${hours} hour${hours === 1 ? '' : 's'} ago`;\n  const days = Math.floor(hours \u002F 24);\n  return `${days} day${days === 1 ? '' : 's'} ago`;\n}\n```\n\nUsage inside `render()`:\n\n```typescript\nprivate render(runs: WorkflowRun[]): void {\n  const rows = runs.map(r => `\n    \u003Cdiv class=\"run-row\">\n      \u003Cspan class=\"run-name\">${r.name}\u003C\u002Fspan>\n      \u003Cspan class=\"run-time\">${timeAgo(r.updatedAt)}\u003C\u002Fspan>\n    \u003C\u002Fdiv>\n  `).join('');\n  this.setContent(`\u003Cdiv class=\"run-list\">${rows}\u003C\u002Fdiv>`);\n}\n```\n\n### statusIcon — enum-to-icon mapping helper\n\nMaps a string enum (e.g. CI status) to an icon character or emoji. Define\nthe map as a `const` outside the function so it is allocated once.\n\n```typescript\n\u002F\u002F co-located at the top of, e.g., src\u002Fcomponents\u002FCodeStatusPanel.ts\n\nconst STATUS_ICON: Record\u003Cstring, string> = {\n  success:     '✅',\n  failure:     '❌',\n  cancelled:   '⛔',\n  skipped:     '⏭️',\n  in_progress: '?',\n  queued:      '⏳',\n};\n\n\u002F** Returns an icon string for a workflow run conclusion\u002Fstatus value. *\u002F\nfunction statusIcon(status: string | null): string {\n  if (!status) return '❓';\n  return STATUS_ICON[status] ?? '❓';\n}\n```\n\nUsage inside `render()`:\n\n```typescript\nconst rows = runs.map(r => `\n  \u003Cdiv class=\"run-row ${r.conclusion ?? r.status}\">\n    \u003Cspan class=\"run-status\">${statusIcon(r.conclusion ?? r.status)}\u003C\u002Fspan>\n    \u003Cspan class=\"run-name\">${r.name}\u003C\u002Fspan>\n    \u003Cspan class=\"run-time\">${timeAgo(r.updatedAt)}\u003C\u002Fspan>\n  \u003C\u002Fdiv>\n`).join('');\n```\n\n### Full example: CodeStatusPanel with co-located helpers\n\n```typescript\nimport { Panel } from '.\u002FPanel';\nimport { fetchWorkflowRuns, WorkflowRun } from '..\u002Fservices\u002Fcode-status';\n\n\u002F\u002F ── Co-located helpers ────────────────────────────────────────────────────────\n\nconst STATUS_ICON: Record\u003Cstring, string> = {\n  success:     '✅',\n  failure:     '❌',\n  cancelled:   '⛔',\n  skipped:     '⏭️',\n  in_progress: '?',\n  queued:      '⏳',\n};\n\nfunction statusIcon(status: string | null): string {\n  if (!status) return '❓';\n  return STATUS_ICON[status] ?? '❓';\n}\n\nfunction timeAgo(dateStr: string): string {\n  const diff = Date.now() - new Date(dateStr).getTime();\n  const minutes = Math.floor(diff \u002F 60_000);\n  if (minutes \u003C 1)  return 'just now';\n  if (minutes \u003C 60) return `${minutes} minute${minutes === 1 ? '' : 's'} ago`;\n  const hours = Math.floor(minutes \u002F 60);\n  if (hours \u003C 24)   return `${hours} hour${hours === 1 ? '' : 's'} ago`;\n  const days = Math.floor(hours \u002F 24);\n  return `${days} day${days === 1 ? '' : 's'} ago`;\n}\n\n\u002F\u002F ── Panel class ───────────────────────────────────────────────────────────────\n\nexport class CodeStatusPanel extends Panel {\n  private refreshTimer: ReturnType\u003Ctypeof setInterval> | null = null;\n\n  constructor() {\n    super({ id: 'codeStatus', title: 'CI \u002F CD Status', showCount: true });\n    this.fetchData();\n    this.refreshTimer = setInterval(() => this.fetchData(), 60_000);\n  }\n\n  private async fetchData(): Promise\u003Cvoid> {\n    if (this.isFetching) return;\n    this.setFetching(true);\n    try {\n      const runs = await fetchWorkflowRuns();\n      this.render(runs);\n      this.setCount(runs.length);\n      this.saveState();\n    } catch (err) {\n      this.showError(`Failed to load CI status: ${(err as Error).message}`, () => this.fetchData());\n    } finally {\n      this.setFetching(false);\n    }\n  }\n\n  private render(runs: WorkflowRun[]): void {\n    if (!runs.length) {\n      this.setContent('\u003Cp class=\"panel-empty\">No recent runs.\u003C\u002Fp>');\n      return;\n    }\n    const rows = runs.map(r => `\n      \u003Cdiv class=\"run-row ${r.conclusion ?? r.status}\">\n        \u003Cspan class=\"run-icon\">${statusIcon(r.conclusion ?? r.status)}\u003C\u002Fspan>\n        \u003Cspan class=\"run-name\">${r.name}\u003C\u002Fspan>\n        \u003Cspan class=\"run-branch\">${r.headBranch}\u003C\u002Fspan>\n        \u003Cspan class=\"run-time\">${timeAgo(r.updatedAt)}\u003C\u002Fspan>\n      \u003C\u002Fdiv>\n    `).join('');\n    this.setContent(`\u003Cdiv class=\"run-list\">${rows}\u003C\u002Fdiv>`);\n  }\n\n  public override destroy(): void {\n    if (this.refreshTimer) clearInterval(this.refreshTimer);\n    super.destroy();\n  }\n}\n```\n\n### Naming conventions for co-located helpers\n\n- Use **camelCase** function names (`timeAgo`, `statusIcon`, `formatBytes`).\n- Keep them **pure** (no side effects, no DOM access) so they are trivially unit-testable.\n- Place them **above** the class definition, below imports.\n- Prefix module-level constants that back a helper with the helper name in SCREAMING_SNAKE (`STATUS_ICON` for `statusIcon`).\n- Do **not** export them unless another file already needs them — keep the API surface minimal.\n\n## Sparkline Utility\n\n```typescript\nexport function miniSparkline(data: number[] | undefined, change: number | null, w = 50, h = 16): string {\n  if (!data || data.length \u003C 2) return '';\n  const min = Math.min(...data);\n  const max = Math.max(...data);\n  const range = max - min || 1;\n  const color = change != null && change >= 0 ? 'var(--green)' : 'var(--red)';\n  const points = data.map((v, i) => {\n    const x = (i \u002F (data.length - 1)) * w;\n    const y = h - ((v - min) \u002F range) * (h - 2) - 1;\n    return `${x.toFixed(1)},${y.toFixed(1)}`;\n  }).join(' ');\n  return `\u003Csvg width=\"${w}\" height=\"${h}\" viewBox=\"0 0 ${w} ${h}\">\u003Cpolyline points=\"${points}\" fill=\"none\" stroke=\"${color}\" stroke-width=\"1.2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"\u002F>\u003C\u002Fsvg>`;\n}\n```\n","# Panel Component Pattern\n\nCreate dashboard panel components using **vanilla TypeScript** (no framework, no JSX). Each panel is a class extending a `Panel` base class.\n\n## Architecture Overview\n\n### Enhanced Features\n- **Retry Logic**: Automatically retries failed data fetches with exponential backoff.\n- **State Persistence**: Saves panel state (expanded\u002Fcollapsed, size) to localStorage.\n- **Detailed Error Handling**: Provides more granular error messages and recovery options.\n- **Co-located Helpers**: Panel-specific pure utility functions live in the same file as the panel class, keeping implementations self-contained.\n\n```\nPanel (base class)\n├── element: HTMLElement (outer container, .panel)\n│   ├── header: HTMLElement (.panel-header)\n│   │   ├── headerLeft (.panel-header-left)\n│   │   │   ├── title (.panel-title)\n│   │   │   └── newBadge (.panel-new-badge) [optional]\n│   │   ├── statusBadge (.panel-data-badge) [optional]\n│   │   └── countEl (.panel-count) [optional]\n│   ├── content: HTMLElement (.panel-content)\n│   └── resizeHandle (.panel-resize-handle)\n```\n\n## Base Panel Class (Simplified for this project)\n\n```typescript\nexport class Panel {\n  \u002F\u002F ... existing code ...\n\n  private retryAttempts = 0;\n  private maxRetries = 3;\n  private retryDelay = 1000; \u002F\u002F starts at 1s, doubles each retry\n\n  protected async fetchWithRetry(url: string): Promise\u003Cany> {\n    while (this.retryAttempts \u003C this.maxRetries) {\n      try {\n        const response = await fetch(url);\n        if (!response.ok) throw new Error(`HTTP ${response.status}`);\n        return await response.json();\n      } catch (error) {\n        this.retryAttempts++;\n        if (this.retryAttempts >= this.maxRetries) {\n          throw new Error(`Failed after ${this.maxRetries} attempts: ${error.message}`);\n        }\n        await new Promise(resolve => setTimeout(resolve, this.retryDelay));\n        this.retryDelay *= 2;\n      }\n    }\n  }\n\n  public saveState(): void {\n    localStorage.setItem(`panelState_${this.panelId}`, JSON.stringify({\n      isExpanded: !this.element.classList.contains('collapsed'),\n      width: this.element.style.width,\n      height: this.element.style.height\n    }));\n  }\n\n  public loadState(): void {\n    const savedState = localStorage.getItem(`panelState_${this.panelId}`);\n    if (savedState) {\n      const { isExpanded, width, height } = JSON.parse(savedState);\n      if (!isExpanded) this.element.classList.add('collapsed');\n      if (width) this.element.style.width = width;\n      if (height) this.element.style.height = height;\n    }\n  }\n}\n```\n\nCreate `src\u002Fcomponents\u002FPanel.ts`:\n\n```typescript\nexport interface PanelOptions {\n  id: string;\n  title: string;\n  showCount?: boolean;\n  className?: string;\n}\n\nexport class Panel {\n  protected element: HTMLElement;\n  protected content: HTMLElement;\n  protected header: HTMLElement;\n  protected countEl: HTMLElement | null = null;\n  protected panelId: string;\n  private _fetching = false;\n\n  constructor(options: PanelOptions) {\n    this.panelId = options.id;\n    this.element = document.createElement('div');\n    this.element.className = `panel ${options.className || ''}`;\n    this.element.dataset.panel = options.id;\n\n    \u002F\u002F Header\n    this.header = document.createElement('div');\n    this.header.className = 'panel-header';\n\n    const headerLeft = document.createElement('div');\n    headerLeft.className = 'panel-header-left';\n\n    const title = document.createElement('span');\n    title.className = 'panel-title';\n    title.textContent = options.title;\n    headerLeft.appendChild(title);\n    this.header.appendChild(headerLeft);\n\n    \u002F\u002F Count badge (optional)\n    if (options.showCount) {\n      this.countEl = document.createElement('span');\n      this.countEl.className = 'panel-count';\n      this.countEl.textContent = '0';\n      this.header.appendChild(this.countEl);\n    }\n\n    \u002F\u002F Content area\n    this.content = document.createElement('div');\n    this.content.className = 'panel-content';\n    this.content.id = `${options.id}Content`;\n\n    this.element.appendChild(this.header);\n    this.element.appendChild(this.content);\n    this.showLoading();\n  }\n\n  public getElement(): HTMLElement { return this.element; }\n\n  public showLoading(message = 'Loading...'): void {\n    this.content.innerHTML = `\n      \u003Cdiv class=\"panel-loading\">\n        \u003Cdiv class=\"panel-loading-spinner\">\u003C\u002Fdiv>\n        \u003Cdiv class=\"panel-loading-text\">${message}\u003C\u002Fdiv>\n      \u003C\u002Fdiv>`;\n  }\n\n  public showError(message = 'Failed to load', onRetry?: () => void): void {\n    this.content.innerHTML = `\n      \u003Cdiv class=\"panel-error-state\">\n        \u003Cdiv class=\"panel-error-msg\">${message}\u003C\u002Fdiv>\n        ${onRetry ? '\u003Cbutton class=\"panel-retry-btn\" data-panel-retry>Retry\u003C\u002Fbutton>' : ''}\n      \u003C\u002Fdiv>`;\n    if (onRetry) {\n      this.content.querySelector('[data-panel-retry]')?.addEventListener('click', onRetry);\n    }\n  }\n\n  public setContent(html: string): void {\n    this.content.innerHTML = html;\n  }\n\n  public setCount(count: number): void {\n    if (this.countEl) this.countEl.textContent = count.toString();\n  }\n\n  public show(): void { this.element.classList.remove('hidden'); }\n  public hide(): void { this.element.classList.add('hidden'); }\n\n  protected setFetching(v: boolean): void { this._fetching = v; }\n  protected get isFetching(): boolean { return this._fetching; }\n\n  public destroy(): void {\n    this.element.remove();\n  }\n}\n```\n\n## Creating a Concrete Panel (Example: StockPanel)\n\n```typescript\nexport class StockPanel extends Panel {\n  \u002F\u002F ... existing code ...\n\n  private async fetchData(): Promise\u003Cvoid> {\n    if (this.isFetching) return;\n    this.setFetching(true);\n    try {\n      const quotes = await this.fetchWithRetry('\u002Fapi\u002Fstocks');\n      this.render(quotes);\n      this.setCount(quotes.length);\n      this.saveState();\n    } catch (err) {\n      this.showError(`Failed to load stock data: ${err.message}`, () => {\n        this.retryAttempts = 0;\n        this.retryDelay = 1000;\n        this.fetchData();\n      });\n    } finally {\n      this.setFetching(false);\n    }\n  }\n}\n```\n\nEach panel extends `Panel` and manages its own data fetching + rendering:\n\n```typescript\nimport { Panel } from '.\u002FPanel';\n\ninterface StockQuote {\n  symbol: string;\n  name: string;\n  price: number | null;\n  change: number | null;\n  sparkline?: number[];\n}\n\nexport class StockPanel extends Panel {\n  private refreshTimer: ReturnType\u003Ctypeof setInterval> | null = null;\n\n  constructor() {\n    super({ id: 'stocks', title: 'Stock Market', showCount: true });\n    this.fetchData();\n    this.refreshTimer = setInterval(() => this.fetchData(), 60_000);\n  }\n\n  private async fetchData(): Promise\u003Cvoid> {\n    if (this.isFetching) return;\n    this.setFetching(true);\n    try {\n      const quotes = await fetchStockQuotes(); \u002F\u002F from data-service\n      this.render(quotes);\n      this.setCount(quotes.length);\n    } catch (err) {\n      this.showError('Failed to load stock data', () => this.fetchData());\n    } finally {\n      this.setFetching(false);\n    }\n  }\n\n  private render(quotes: StockQuote[]): void {\n    const rows = quotes.map(q => `\n      \u003Cdiv class=\"stock-row\">\n        \u003Cspan class=\"stock-symbol\">${q.symbol}\u003C\u002Fspan>\n        \u003Cspan class=\"stock-name\">${q.name}\u003C\u002Fspan>\n        \u003Cspan class=\"stock-price\">${q.price != null ? '$' + q.price.toFixed(2) : '—'}\u003C\u002Fspan>\n        \u003Cspan class=\"stock-change ${(q.change ?? 0) >= 0 ? 'positive' : 'negative'}\">\n          ${q.change != null ? (q.change >= 0 ? '+' : '') + q.change.toFixed(2) + '%' : '—'}\n        \u003C\u002Fspan>\n      \u003C\u002Fdiv>\n    `).join('');\n\n    this.setContent(`\u003Cdiv class=\"stock-list\">${rows}\u003C\u002Fdiv>`);\n  }\n\n  public override destroy(): void {\n    if (this.refreshTimer) clearInterval(this.refreshTimer);\n    super.destroy();\n  }\n}\n```\n\n## Key Patterns\n\n1. **Constructor** calls `super()` with panel config, then triggers initial data fetch\n2. **fetchData()** is async, uses `isFetching` guard, shows error on failure with retry\n3. **render()** builds HTML strings and calls `this.setContent(html)`\n4. **destroy()** cleans up timers and event listeners\n5. Use `showLoading()` during initial load (auto-called in constructor)\n6. Use `showError(msg, retryFn)` on failure\n7. Sparkline SVGs use inline `\u003Csvg>` with `\u003Cpolyline>` — see sparkline utility\n8. **Co-located helpers**: Define panel-specific pure utility functions (e.g. `timeAgo`, `statusIcon`) as module-level functions in the same `.ts` file as the panel class. Do **not** place them in `src\u002Futils` unless they are reused by three or more panels.\n\n## Co-located Helper Pattern\n\nPanel-specific formatting and mapping utilities live directly above the class\ndefinition in the same file. This keeps the panel self-contained, avoids\npolluting `src\u002Futils`, and makes the file easier to read and test in isolation.\n\n### When to co-locate\n\n| Situation | Decision |\n|-----------|----------|\n| Helper used only in this panel | ✅ Co-locate in panel file |\n| Helper used in 2 panels | ✅ Co-locate in the more \"owning\" panel; import from there |\n| Helper used in 3+ panels | ❌ Move to `src\u002Futils\u002F\u003Chelper>.ts` |\n| Helper depends on DOM or Panel API | ✅ Always co-locate (private method or module function) |\n\n### timeAgo — relative timestamp helper\n\n```typescript\n\u002F\u002F co-located at the top of, e.g., src\u002Fcomponents\u002FCodeStatusPanel.ts\n\n\u002F** Returns a human-readable relative time string, e.g. \"3 minutes ago\". *\u002F\nfunction timeAgo(dateStr: string): string {\n  const diff = Date.now() - new Date(dateStr).getTime();\n  const minutes = Math.floor(diff \u002F 60_000);\n  if (minutes \u003C 1)  return 'just now';\n  if (minutes \u003C 60) return `${minutes} minute${minutes === 1 ? '' : 's'} ago`;\n  const hours = Math.floor(minutes \u002F 60);\n  if (hours \u003C 24)   return `${hours} hour${hours === 1 ? '' : 's'} ago`;\n  const days = Math.floor(hours \u002F 24);\n  return `${days} day${days === 1 ? '' : 's'} ago`;\n}\n```\n\nUsage inside `render()`:\n\n```typescript\nprivate render(runs: WorkflowRun[]): void {\n  const rows = runs.map(r => `\n    \u003Cdiv class=\"run-row\">\n      \u003Cspan class=\"run-name\">${r.name}\u003C\u002Fspan>\n      \u003Cspan class=\"run-time\">${timeAgo(r.updatedAt)}\u003C\u002Fspan>\n    \u003C\u002Fdiv>\n  `).join('');\n  this.setContent(`\u003Cdiv class=\"run-list\">${rows}\u003C\u002Fdiv>`);\n}\n```\n\n### statusIcon — enum-to-icon mapping helper\n\nMaps a string enum (e.g. CI status) to an icon character or emoji. Define\nthe map as a `const` outside the function so it is allocated once.\n\n```typescript\n\u002F\u002F co-located at the top of, e.g., src\u002Fcomponents\u002FCodeStatusPanel.ts\n\nconst STATUS_ICON: Record\u003Cstring, string> = {\n  success:     '✅',\n  failure:     '❌',\n  cancelled:   '⛔',\n  skipped:     '⏭️',\n  in_progress: '?',\n  queued:      '⏳',\n};\n\n\u002F** Returns an icon string for a workflow run conclusion\u002Fstatus value. *\u002F\nfunction statusIcon(status: string | null): string {\n  if (!status) return '❓';\n  return STATUS_ICON[status] ?? '❓';\n}\n```\n\nUsage inside `render()`:\n\n```typescript\nconst rows = runs.map(r => `\n  \u003Cdiv class=\"run-row ${r.conclusion ?? r.status}\">\n    \u003Cspan class=\"run-status\">${statusIcon(r.conclusion ?? r.status)}\u003C\u002Fspan>\n    \u003Cspan class=\"run-name\">${r.name}\u003C\u002Fspan>\n    \u003Cspan class=\"run-time\">${timeAgo(r.updatedAt)}\u003C\u002Fspan>\n  \u003C\u002Fdiv>\n`).join('');\n```\n\n### Full example: CodeStatusPanel with co-located helpers\n\n```typescript\nimport { Panel } from '.\u002FPanel';\nimport { fetchWorkflowRuns, WorkflowRun } from '..\u002Fservices\u002Fcode-status';\n\n\u002F\u002F ── Co-located helpers ────────────────────────────────────────────────────────\n\nconst STATUS_ICON: Record\u003Cstring, string> = {\n  success:     '✅',\n  failure:     '❌',\n  cancelled:   '⛔',\n  skipped:     '⏭️',\n  in_progress: '?',\n  queued:      '⏳',\n};\n\nfunction statusIcon(status: string | null): string {\n  if (!status) return '❓';\n  return STATUS_ICON[status] ?? '❓';\n}\n\nfunction timeAgo(dateStr: string): string {\n  const diff = Date.now() - new Date(dateStr).getTime();\n  const minutes = Math.floor(diff \u002F 60_000);\n  if (minutes \u003C 1)  return 'just now';\n  if (minutes \u003C 60) return `${minutes} minute${minutes === 1 ? '' : 's'} ago`;\n  const hours = Math.floor(minutes \u002F 60);\n  if (hours \u003C 24)   return `${hours} hour${hours === 1 ? '' : 's'} ago`;\n  const days = Math.floor(hours \u002F 24);\n  return `${days} day${days === 1 ? '' : 's'} ago`;\n}\n\n\u002F\u002F ── Panel class ───────────────────────────────────────────────────────────────\n\nexport class CodeStatusPanel extends Panel {\n  private refreshTimer: ReturnType\u003Ctypeof setInterval> | null = null;\n\n  constructor() {\n    super({ id: 'codeStatus', title: 'CI \u002F CD Status', showCount: true });\n    this.fetchData();\n    this.refreshTimer = setInterval(() => this.fetchData(), 60_000);\n  }\n\n  private async fetchData(): Promise\u003Cvoid> {\n    if (this.isFetching) return;\n    this.setFetching(true);\n    try {\n      const runs = await fetchWorkflowRuns();\n      this.render(runs);\n      this.setCount(runs.length);\n      this.saveState();\n    } catch (err) {\n      this.showError(`Failed to load CI status: ${(err as Error).message}`, () => this.fetchData());\n    } finally {\n      this.setFetching(false);\n    }\n  }\n\n  private render(runs: WorkflowRun[]): void {\n    if (!runs.length) {\n      this.setContent('\u003Cp class=\"panel-empty\">No recent runs.\u003C\u002Fp>');\n      return;\n    }\n    const rows = runs.map(r => `\n      \u003Cdiv class=\"run-row ${r.conclusion ?? r.status}\">\n        \u003Cspan class=\"run-icon\">${statusIcon(r.conclusion ?? r.status)}\u003C\u002Fspan>\n        \u003Cspan class=\"run-name\">${r.name}\u003C\u002Fspan>\n        \u003Cspan class=\"run-branch\">${r.headBranch}\u003C\u002Fspan>\n        \u003Cspan class=\"run-time\">${timeAgo(r.updatedAt)}\u003C\u002Fspan>\n      \u003C\u002Fdiv>\n    `).join('');\n    this.setContent(`\u003Cdiv class=\"run-list\">${rows}\u003C\u002Fdiv>`);\n  }\n\n  public override destroy(): void {\n    if (this.refreshTimer) clearInterval(this.refreshTimer);\n    super.destroy();\n  }\n}\n```\n\n### Naming conventions for co-located helpers\n\n- Use **camelCase** function names (`timeAgo`, `statusIcon`, `formatBytes`).\n- Keep them **pure** (no side effects, no DOM access) so they are trivially unit-testable.\n- Place them **above** the class definition, below imports.\n- Prefix module-level constants that back a helper with the helper name in SCREAMING_SNAKE (`STATUS_ICON` for `statusIcon`).\n- Do **not** export them unless another file already needs them — keep the API surface minimal.\n\n## Sparkline Utility\n\n```typescript\nexport function miniSparkline(data: number[] | undefined, change: number | null, w = 50, h = 16): string {\n  if (!data || data.length \u003C 2) return '';\n  const min = Math.min(...data);\n  const max = Math.max(...data);\n  const range = max - min || 1;\n  const color = change != null && change >= 0 ? 'var(--green)' : 'var(--red)';\n  const points = data.map((v, i) => {\n    const x = (i \u002F (data.length - 1)) * w;\n    const y = h - ((v - min) \u002F range) * (h - 2) - 1;\n    return `${x.toFixed(1)},${y.toFixed(1)}`;\n  }).join(' ');\n  return `\u003Csvg width=\"${w}\" height=\"${h}\" viewBox=\"0 0 ${w} ${h}\">\u003Cpolyline points=\"${points}\" fill=\"none\" stroke=\"${color}\" stroke-width=\"1.2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"\u002F>\u003C\u002Fsvg>`;\n}\n```\n",{"name":5,"description":7},"main","ff671ef61ed6587c49bd54c81cdc751c0b99e363","showcase\u002Fskills\u002Fpanel-component-colocated-helpers","https:\u002F\u002Fgithub.com\u002FAG064\u002FOpenSpace","https:\u002F\u002Fgithub.com\u002FAG064","AG064, E.Mi.\r\n\r\nA person who thinks all the time, yet all they have to think about is nothing. I want to improve the world and work on open source projects","2026-10-08 06:53:48",{"source":8,"skillName":5,"commands":50,"prompt":60,"zipAvailable":61},[51,54,57],{"tool":52,"command":53},"npx","npx skills add AG064\u002FOpenSpace --skill panel-component-colocated-helpers",{"tool":55,"command":56},"bunx","bunx skills add AG064\u002FOpenSpace --skill panel-component-colocated-helpers",{"tool":58,"command":59},"pnpm","pnpm dlx skills add AG064\u002FOpenSpace --skill panel-component-colocated-helpers","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FAG064\u002FOpenSpace\u002Fblob\u002Fmain\u002Fshowcase\u002Fskills\u002Fpanel-component-colocated-helpers\u002FSKILL.md",true,[63],{"path":64,"resourceType":65,"resourceTypeDesc":66,"sizeBytes":67,"sourceHtmlUrl":68},".skill_id","OTHER","其他",47,"https:\u002F\u002Fgithub.com\u002FAG064\u002FOpenSpace\u002Fblob\u002Fmain\u002Fshowcase\u002Fskills\u002Fpanel-component-colocated-helpers\u002F.skill_id",[70,93,108,117,145,161],{"skillNo":71,"name":72,"nameZh":6,"description":73,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":9,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":74,"categories":75,"keywords":76,"publishedAt":37},"01M6KKMPWA0B5SCCH766F8M5EA","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\u002FAG064\u002FOpenSpace\u002Fblob\u002Fmain\u002Fshowcase\u002Fskills\u002Fwrite-special-chars-ts-check\u002FSKILL.md",[],[77,78,79,80,81,82,25,83,84,85,86,87,88,89,90,91,92],"write special chars ts check","check","write","filters","Existing","type-checking","errors","script","output","type","files","only","template","file","python","typescript",{"skillNo":94,"name":95,"nameZh":6,"description":96,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":9,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":97,"categories":98,"keywords":99,"publishedAt":37},"01M6KKMJXVBNVEY3TRK055F4A7","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\u002FAG064\u002FOpenSpace\u002Fblob\u002Fmain\u002Fshowcase\u002Fskills\u002Fwrite-special-chars-readback\u002FSKILL.md",[],[100,101,79,89,102,103,90,91,104,105,106,107,29,25,84,27],"readback","write special chars readback","cleanup","read","scripts","verification","via","post",{"skillNo":109,"name":110,"nameZh":6,"description":111,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":9,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":112,"categories":113,"keywords":114,"publishedAt":37},"01M6KKMEGX9M9NC105J0W3Q5B9","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\u002FAG064\u002FOpenSpace\u002Fblob\u002Fmain\u002Fshowcase\u002Fskills\u002Fwrite-special-chars-heredoc\u002FSKILL.md",[],[79,115,91,25,106,89,116,90,84],"write special chars heredoc","shell",{"skillNo":118,"name":119,"nameZh":6,"description":120,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":9,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":121,"categories":122,"keywords":128,"publishedAt":37},"01M6KKM8EJ2AATVHZBNB916WT0","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\u002FAG064\u002FOpenSpace\u002Fblob\u002Fmain\u002Fshowcase\u002Fskills\u002Fworldmonitor-reference\u002FSKILL.md",[123],{"categoryNo":124,"categoryName":125,"taxonomyType":126,"taxonomyTypeDesc":127},"01JBSEEDCAT000000000000033","数据分析师","PROFESSION","适用职业",[129,130,131,23,92,132,133,134,135,136,25,137,21,138,139,140,141,142,143,144],"reference","worldmonitor","worldmonitor reference","css","architecture","extracting","hierarchy","source","layer","patterns","edge functions","integrations","open","api","data","scheduler",{"skillNo":146,"name":147,"nameZh":6,"description":148,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":9,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":149,"categories":150,"keywords":151,"publishedAt":37},"01M6KKM39PHYK627F19GE2B9XN","virtual-list","Implement efficient virtual scrolling for rendering large lists with DOM recycling, chunk-based rendering, and performance optimizations","https:\u002F\u002Fgithub.com\u002FAG064\u002FOpenSpace\u002Fblob\u002Fmain\u002Fshowcase\u002Fskills\u002Fvirtual-list\u002FSKILL.md",[],[152,153,154,155,25,156,27,157,158,159,160],"virtual list","list","virtual","chunk","dom","rendering","recycling","implement","performance",{"skillNo":162,"name":163,"nameZh":6,"description":164,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":9,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":165,"categories":166,"keywords":167,"publishedAt":37},"01M6KKKY7T2P61Y0JH54CDEJKQ","verify-directory-structure","Diagnose and resolve file access issues by first verifying the directory structure.","https:\u002F\u002Fgithub.com\u002FAG064\u002FOpenSpace\u002Fblob\u002Fmain\u002Fshowcase\u002Fskills\u002Fverify-directory-structure\u002FSKILL.md",[],[168,169,170,171,172,173,90,174,175,176],"directory","verify","structure","verify directory structure","access","first","issues","diagnose","file access"]