[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6KKDNKSX8S0SNZTD0XEMM0Z":3,"skill-same:01M6KKDNKSX8S0SNZTD0XEMM0Z":70},{"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":38,"linkOnly":39,"markdownContent":40,"markdownBody":41,"frontMatter":42,"refName":43,"commitSha":44,"skillDirectory":45,"forksCount":13,"repositoryHtmlUrl":46,"repositoryHomepageUrl":6,"ownerHtmlUrl":47,"ownerBlogUrl":6,"ownerDescription":48,"updatedAt":49,"install":50,"resources":63},"01M6KKDNKSX8S0SNZTD0XEMM0Z","panel-base-advanced",null,"Unified guide for authoring dashboard panel components in vanilla TypeScript — covers the authoritative Panel base class (grid-span persistence, dual resize handles, radar loading animation, exponential-backoff error countdown, data\u002Fnew badge helpers, full destroy() cleanup), localStorage state via loadMap\u002FsaveMap, exponential-backoff retry, and CircuitBreaker integration. Shows how to wrap any existing fetchX() service call with CircuitBreaker.execute() as a one-liner and clarifies when each resilience layer is appropriate.","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-base-advanced\u002FSKILL.md",[],[18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37],"panel base advanced","advanced","panel","base","full","layer","retry","loading","error","how to","authoring","typescript","radar","how","Animation","data","cleanup","resilience","components","dashboard","2026-11-10 10:12:30",false,"---\nname: panel-base-advanced\ndescription: Unified guide for authoring dashboard panel components in vanilla TypeScript — covers the authoritative Panel base class (grid-span persistence, dual resize handles, radar loading animation, exponential-backoff error countdown, data\u002Fnew badge helpers, full destroy() cleanup), localStorage state via loadMap\u002FsaveMap, exponential-backoff retry, and CircuitBreaker integration. Shows how to wrap any existing fetchX() service call with CircuitBreaker.execute() as a one-liner and clarifies when each resilience layer is appropriate.\n---\n\n# Resilient Panel — Unified Pattern (v2)\n\nCreate dashboard panel components using **vanilla TypeScript** (no framework, no JSX).\nEach panel is a class extending a `Panel` base class and optionally wraps its data source with a `CircuitBreaker`.\n\n---\n\n## Architecture Overview\n\n```\nPanel (base class)\n├── element: HTMLElement (.panel)\n│   ├── header: HTMLElement (.panel-header)\n│   │   ├── headerLeft (.panel-header-left)\n│   │   │   ├── title (.panel-title)\n│   │   │   └── newBadge (.panel-new-badge) [optional, via setNewBadge()]\n│   │   ├── statusBadge (.panel-data-badge) [optional, via setDataBadge()]\n│   │   └── countEl (.panel-count) [optional]\n│   ├── content: HTMLElement (.panel-content)\n│   ├── resizeHandleRow (.panel-resize-handle-row)   [bottom edge]\n│   └── resizeHandleCol (.panel-resize-handle-col)   [right edge]\n```\n\n### Resilience layers (choose what you need)\n\n| Layer | File | When to use |\n|---|---|---|\n| **isFetching guard** | `Panel` base class | Always — prevents concurrent duplicate requests |\n| **Exponential-backoff retry** | `Panel.fetchWithRetry()` | When you own the fetch call and want per-request retry before surfacing an error |\n| **Error countdown in showError()** | `Panel` base class | Automatic retry countdown rendered inside the error state UI |\n| **CircuitBreaker** | `src\u002Futils\u002Fcircuit-breaker.ts` | When a service may fail repeatedly; stops hammering the API and serves stale cache instead |\n| **localStorage persistence** | `Panel.saveMap()` \u002F `loadMap()` | When you want grid-span (not pixel size) state to survive page reloads |\n\n> **Wrapping an existing service call with CircuitBreaker is a one-liner:**\n> ```typescript\n> \u002F\u002F Before\n> const data = await fetchStockQuotes();\n> \u002F\u002F After — adds caching + cooldown with zero refactor\n> const data = await breaker.execute(() => fetchStockQuotes(), []);\n> ```\n\n---\n\n## File 1 — `src\u002Fcomponents\u002FPanel.ts`\n\n> **Authoritative implementation.** Use this verbatim; do not revert to\n> the older `saveState()`\u002F`loadState()` width\u002Fheight approach.\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 headerLeft: HTMLElement;\n  protected countEl: HTMLElement | null = null;\n  protected statusBadge: HTMLElement | null = null;\n  protected newBadge: HTMLElement | null = null;\n  protected panelId: string;\n\n  private _fetching = false;\n  private _countdownInterval: ReturnType\u003Ctypeof setInterval> | null = null;\n  private _resizeListeners: Array\u003C{ target: EventTarget; type: string; fn: EventListenerOrEventListenerObject }> = [];\n\n  \u002F\u002F Retry state (used by fetchWithRetry)\n  protected retryAttempts = 0;\n  protected retryDelay = 1000; \u002F\u002F ms; doubles each attempt\n  private maxRetries = 3;\n\n  constructor(options: PanelOptions) {\n    this.panelId = options.id;\n\n    this.element = document.createElement('div');\n    this.element.className = `panel${options.className ? ' ' + 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    this.headerLeft = document.createElement('div');\n    this.headerLeft.className = 'panel-header-left';\n\n    const title = document.createElement('span');\n    title.className = 'panel-title';\n    title.textContent = options.title;\n    this.headerLeft.appendChild(title);\n    this.header.appendChild(this.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    \u002F\u002F Dual resize handles\n    const resizeHandleRow = document.createElement('div');\n    resizeHandleRow.className = 'panel-resize-handle-row';\n\n    const resizeHandleCol = document.createElement('div');\n    resizeHandleCol.className = 'panel-resize-handle-col';\n\n    this.element.appendChild(this.header);\n    this.element.appendChild(this.content);\n    this.element.appendChild(resizeHandleRow);\n    this.element.appendChild(resizeHandleCol);\n\n    this._initResizeHandles(resizeHandleRow, resizeHandleCol);\n    this.showLoading();\n  }\n\n  \u002F\u002F Public API\n\n  public getElement(): HTMLElement { return this.element; }\n\n  \u002F** Radar-ring loading animation with optional message. *\u002F\n  public showLoading(message = 'Loading...'): void {\n    this._clearCountdown();\n    this.content.innerHTML = `\n      \u003Cdiv class=\"panel-loading\">\n        \u003Cdiv class=\"panel-loading-radar\">\n          \u003Cdiv class=\"radar-ring radar-ring-1\">\u003C\u002Fdiv>\n          \u003Cdiv class=\"radar-ring radar-ring-2\">\u003C\u002Fdiv>\n          \u003Cdiv class=\"radar-ring radar-ring-3\">\u003C\u002Fdiv>\n        \u003C\u002Fdiv>\n        \u003Cdiv class=\"panel-loading-text\">${message}\u003C\u002Fdiv>\n      \u003C\u002Fdiv>`;\n  }\n\n  \u002F**\n   * Show an error state.\n   * If autoRetryMs is provided, renders an exponential-backoff countdown\n   * inside the error UI and calls onRetry automatically when it reaches 0.\n   *\u002F\n  public showError(\n    message = 'Failed to load',\n    onRetry?: () => void,\n    autoRetryMs?: number\n  ): void {\n    this._clearCountdown();\n    const countdownId = `panel-error-countdown-${this.panelId}`;\n    this.content.innerHTML = `\n      \u003Cdiv class=\"panel-error-state\">\n        \u003Cdiv class=\"panel-error-msg\">${message}\u003C\u002Fdiv>\n        ${autoRetryMs != null\n          ? `\u003Cdiv class=\"panel-error-countdown\" id=\"${countdownId}\">Retrying in ${Math.ceil(autoRetryMs \u002F 1000)}s...\u003C\u002Fdiv>`\n          : ''}\n        ${onRetry ? '\u003Cbutton class=\"panel-retry-btn\" data-panel-retry>Retry\u003C\u002Fbutton>' : ''}\n      \u003C\u002Fdiv>`;\n\n    if (onRetry) {\n      this.content.querySelector('[data-panel-retry]')\n        ?.addEventListener('click', () => { this._clearCountdown(); onRetry(); });\n    }\n\n    if (autoRetryMs != null && onRetry) {\n      let remaining = autoRetryMs;\n      const getEl = () => this.content.querySelector\u003CHTMLElement>(`#${countdownId}`);\n      this._countdownInterval = setInterval(() => {\n        remaining -= 1000;\n        if (remaining \u003C= 0) {\n          this._clearCountdown();\n          onRetry();\n        } else {\n          const node = getEl();\n          if (node) node.textContent = `Retrying in ${Math.ceil(remaining \u002F 1000)}s...`;\n        }\n      }, 1000);\n    }\n  }\n\n  public setContent(html: string): void {\n    this._clearCountdown();\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  \u002F**\n   * Show (or update) the data-status badge in the panel header.\n   * Pass a variant CSS modifier such as 'live', 'stale', or 'error'.\n   *\u002F\n  public setDataBadge(text: string, variant = 'live'): void {\n    if (!this.statusBadge) {\n      this.statusBadge = document.createElement('span');\n      this.statusBadge.className = 'panel-data-badge';\n      this.header.appendChild(this.statusBadge);\n    }\n    this.statusBadge.textContent = text;\n    this.statusBadge.dataset.variant = variant;\n  }\n\n  public clearDataBadge(): void {\n    this.statusBadge?.remove();\n    this.statusBadge = null;\n  }\n\n  \u002F** Show the \"NEW\" badge next to the panel title (idempotent). *\u002F\n  public setNewBadge(text = 'NEW'): void {\n    if (!this.newBadge) {\n      this.newBadge = document.createElement('span');\n      this.newBadge.className = 'panel-new-badge';\n      this.headerLeft.appendChild(this.newBadge);\n    }\n    this.newBadge.textContent = text;\n  }\n\n  public clearNewBadge(): void {\n    this.newBadge?.remove();\n    this.newBadge = null;\n  }\n\n  public show(): void { this.element.classList.remove('hidden'); }\n  public hide(): void { this.element.classList.add('hidden'); }\n\n  \u002F** Full teardown: removes element, clears countdown timer, removes all resize listeners. *\u002F\n  public destroy(): void {\n    this._clearCountdown();\n    for (const { target, type, fn } of this._resizeListeners) {\n      target.removeEventListener(type, fn);\n    }\n    this._resizeListeners = [];\n    this.element.remove();\n  }\n\n  \u002F\u002F Protected helpers\n\n  protected setFetching(v: boolean): void { this._fetching = v; }\n  protected get isFetching(): boolean { return this._fetching; }\n\n  \u002F**\n   * Fetch url with exponential-backoff retry (up to maxRetries attempts).\n   * Reset this.retryAttempts and this.retryDelay before calling if you\n   * want a fresh retry sequence (e.g. from a user-initiated Retry button).\n   *\u002F\n  protected async fetchWithRetry(url: string): Promise\u003Cunknown> {\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(\n            `Failed after ${this.maxRetries} attempts: ${(error as Error).message}`\n          );\n        }\n        await new Promise(resolve => setTimeout(resolve, this.retryDelay));\n        this.retryDelay *= 2;\n      }\n    }\n  }\n\n  \u002F\u002F Grid-span persistence\n  \u002F\u002F\n  \u002F\u002F Panels live inside a CSS grid. Their size is expressed as span classes\n  \u002F\u002F (e.g. \"col-span-2\", \"row-span-3\"), NOT inline pixel widths\u002Fheights.\n  \u002F\u002F Use saveMap \u002F loadMap to persist this.\n\n  \u002F**\n   * Persist an arbitrary key->value map to localStorage under this panel's key.\n   * Typical use: save current grid-span class numbers.\n   *\n   *   this.saveMap({ colSpan: '2', rowSpan: '1', collapsed: 'false' });\n   *\u002F\n  public saveMap(data: Record\u003Cstring, string>): void {\n    localStorage.setItem(`panelState_${this.panelId}`, JSON.stringify(data));\n  }\n\n  \u002F**\n   * Load the map saved by saveMap(), or null if nothing was stored.\n   *\n   *   const state = this.loadMap();\n   *   if (state) {\n   *     this.element.classList.add(`col-span-${state.colSpan}`);\n   *     this.element.classList.add(`row-span-${state.rowSpan}`);\n   *     if (state.collapsed === 'true') this.element.classList.add('collapsed');\n   *   }\n   *\u002F\n  public loadMap(): Record\u003Cstring, string> | null {\n    const raw = localStorage.getItem(`panelState_${this.panelId}`);\n    if (!raw) return null;\n    try {\n      return JSON.parse(raw) as Record\u003Cstring, string>;\n    } catch {\n      return null;\n    }\n  }\n\n  \u002F\u002F Private internals\n\n  private _clearCountdown(): void {\n    if (this._countdownInterval !== null) {\n      clearInterval(this._countdownInterval);\n      this._countdownInterval = null;\n    }\n  }\n\n  \u002F**\n   * Wire up the two resize handles.\n   * Row handle drags vertically and updates the row-span class.\n   * Col handle drags horizontally and updates the col-span class.\n   * All listeners are tracked in _resizeListeners for clean destroy().\n   *\u002F\n  private _initResizeHandles(\n    rowHandle: HTMLElement,\n    colHandle: HTMLElement\n  ): void {\n    const track = (\n      target: EventTarget,\n      type: string,\n      fn: EventListenerOrEventListenerObject\n    ) => {\n      target.addEventListener(type, fn);\n      this._resizeListeners.push({ target, type, fn });\n    };\n\n    \u002F\u002F Row resize (bottom handle)\n    let rowDragging = false;\n    let rowStartY = 0;\n    let rowStartSpan = 1;\n\n    const onRowMouseDown = (e: Event) => {\n      const me = e as MouseEvent;\n      rowDragging = true;\n      rowStartY = me.clientY;\n      const m = (this.element.className.match(\u002Frow-span-(\\d+)\u002F) ?? [])[1];\n      rowStartSpan = m ? parseInt(m, 10) : 1;\n      me.preventDefault();\n    };\n    const onRowMouseMove = (e: Event) => {\n      if (!rowDragging) return;\n      const me = e as MouseEvent;\n      const delta = Math.round((me.clientY - rowStartY) \u002F 60);\n      const newSpan = Math.max(1, Math.min(6, rowStartSpan + delta));\n      this.element.className = this.element.className\n        .replace(\u002Frow-span-\\d+\u002F, `row-span-${newSpan}`)\n        .trim();\n      if (!\u002Frow-span-\\d+\u002F.test(this.element.className)) {\n        this.element.classList.add(`row-span-${newSpan}`);\n      }\n    };\n    const onRowMouseUp = () => { rowDragging = false; };\n\n    track(rowHandle, 'mousedown', onRowMouseDown);\n    track(document,  'mousemove', onRowMouseMove);\n    track(document,  'mouseup',   onRowMouseUp);\n\n    \u002F\u002F Col resize (right handle)\n    let colDragging = false;\n    let colStartX = 0;\n    let colStartSpan = 1;\n\n    const onColMouseDown = (e: Event) => {\n      const me = e as MouseEvent;\n      colDragging = true;\n      colStartX = me.clientX;\n      const m = (this.element.className.match(\u002Fcol-span-(\\d+)\u002F) ?? [])[1];\n      colStartSpan = m ? parseInt(m, 10) : 1;\n      me.preventDefault();\n    };\n    const onColMouseMove = (e: Event) => {\n      if (!colDragging) return;\n      const me = e as MouseEvent;\n      const delta = Math.round((me.clientX - colStartX) \u002F 120);\n      const newSpan = Math.max(1, Math.min(12, colStartSpan + delta));\n      this.element.className = this.element.className\n        .replace(\u002Fcol-span-\\d+\u002F, `col-span-${newSpan}`)\n        .trim();\n      if (!\u002Fcol-span-\\d+\u002F.test(this.element.className)) {\n        this.element.classList.add(`col-span-${newSpan}`);\n      }\n    };\n    const onColMouseUp = () => { colDragging = false; };\n\n    track(colHandle, 'mousedown', onColMouseDown);\n    track(document,  'mousemove', onColMouseMove);\n    track(document,  'mouseup',   onColMouseUp);\n  }\n}\n```\n\n---\n\n## File 2 — `src\u002Futils\u002Fcircuit-breaker.ts`\n\n```typescript\ninterface CircuitState {\n  failures: number;\n  cooldownUntil: number;\n}\n\ninterface CacheEntry\u003CT> {\n  data: T;\n  timestamp: number;\n}\n\nexport interface CircuitBreakerOptions {\n  name: string;\n  maxFailures?: number;   \u002F\u002F default 2\n  cooldownMs?: number;    \u002F\u002F default 5 min\n  cacheTtlMs?: number;    \u002F\u002F default 10 min\n}\n\nexport class CircuitBreaker\u003CT> {\n  private state: CircuitState = { failures: 0, cooldownUntil: 0 };\n  private cache: CacheEntry\u003CT> | null = null;\n  private readonly name: string;\n  private readonly maxFailures: number;\n  private readonly cooldownMs: number;\n  private readonly cacheTtlMs: number;\n\n  constructor(options: CircuitBreakerOptions) {\n    this.name        = options.name;\n    this.maxFailures = options.maxFailures ?? 2;\n    this.cooldownMs  = options.cooldownMs  ?? 5 * 60 * 1000;\n    this.cacheTtlMs  = options.cacheTtlMs  ?? 10 * 60 * 1000;\n  }\n\n  isOnCooldown(): boolean {\n    if (Date.now() \u003C this.state.cooldownUntil) return true;\n    if (this.state.cooldownUntil > 0) {\n      this.state = { failures: 0, cooldownUntil: 0 };\n    }\n    return false;\n  }\n\n  getCached(): T | null {\n    if (this.cache && Date.now() - this.cache.timestamp \u003C this.cacheTtlMs) {\n      return this.cache.data;\n    }\n    return null;\n  }\n\n  recordSuccess(data: T): void {\n    this.state = { failures: 0, cooldownUntil: 0 };\n    this.cache = { data, timestamp: Date.now() };\n  }\n\n  recordFailure(): void {\n    this.state.failures++;\n    if (this.state.failures >= this.maxFailures) {\n      this.state.cooldownUntil = Date.now() + this.cooldownMs;\n      console.warn(`[${this.name}] Circuit open — cooldown ${this.cooldownMs \u002F 1000}s`);\n    }\n  }\n\n  \u002F**\n   * Execute fn. On success, caches result. On failure, records failure and\n   * returns defaultValue. While on cooldown or cache is fresh, skips fn\n   * entirely and returns cached\u002Fdefault value.\n   *\u002F\n  async execute\u003CR extends T>(fn: () => Promise\u003CR>, defaultValue: R): Promise\u003CR> {\n    if (this.isOnCooldown()) {\n      const cached = this.getCached();\n      return (cached as R) ?? defaultValue;\n    }\n    const cached = this.getCached();\n    if (cached !== null) return cached as R;\n    try {\n      const result = await fn();\n      this.recordSuccess(result);\n      return result;\n    } catch (e) {\n      console.error(`[${this.name}] Request failed:`, e);\n      this.recordFailure();\n      return defaultValue;\n    }\n  }\n}\n\nexport function createCircuitBreaker\u003CT>(\n  options: CircuitBreakerOptions\n): CircuitBreaker\u003CT> {\n  return new CircuitBreaker\u003CT>(options);\n}\n```\n\n---\n\n## File 3 — `src\u002Futils\u002Fsparkline.ts`\n\n```typescript\n\u002F**\n * Returns an inline SVG sparkline string, or '' if data is too short.\n * Embed the return value directly in HTML template strings.\n *\u002F\nexport function miniSparkline(\n  data: number[] | undefined,\n  change: number | null,\n  w = 50,\n  h = 16\n): 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}\">` +\n    `\u003Cpolyline points=\"${points}\" fill=\"none\" stroke=\"${color}\" ` +\n    `stroke-width=\"1.2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"\u002F>\u003C\u002Fsvg>`;\n}\n```\n\n---\n\n## Key differences from the old Panel pattern\n\n| Feature | Old pattern | New (authoritative) pattern |\n|---|---|---|\n| Persistence | `saveState()`\u002F`loadState()` with inline `width`\u002F`height` strings | `saveMap()`\u002F`loadMap()` with arbitrary key\u002Fvalue map; store grid-span class numbers |\n| Resize | Single `.panel-resize-handle` | Dual handles: `.panel-resize-handle-row` (vertical) + `.panel-resize-handle-col` (horizontal) |\n| Loading UI | Spinner div | Radar-ring animation (3 nested `.radar-ring` divs) |\n| Error UI | Static message + optional retry button | Message + optional countdown timer (`autoRetryMs`) + retry button; countdown clears on manual retry |\n| Badges | None | `setDataBadge(text, variant)` \u002F `clearDataBadge()` and `setNewBadge(text)` \u002F `clearNewBadge()` |\n| `destroy()` | `element.remove()` only | Clears countdown interval + removes all resize `document` listeners + `element.remove()` |\n\n---\n\n## Creating a Concrete Panel\n\n### Option A — Wrapping an existing project service with CircuitBreaker (preferred)\n\nUse this when the project already has a `fetchStockQuotes()` (or similar) function.\nThe circuit breaker is a **one-liner wrapper** — no refactoring of the service needed.\n\n```typescript\nimport { Panel } from '.\u002FPanel';\nimport { createCircuitBreaker } from '..\u002Futils\u002Fcircuit-breaker';\nimport { fetchStockQuotes } from '..\u002Fservices\u002Fstocks'; \u002F\u002F existing project service\n\ninterface StockQuote {\n  symbol: string;\n  name: string;\n  price: number | null;\n  change: number | null;\n  sparkline?: number[];\n}\n\n\u002F\u002F Module-level breaker — shared across re-renders, persists cache between fetches\nconst breaker = createCircuitBreaker\u003CStockQuote[]>({\n  name: 'StockMarket',\n  cacheTtlMs: 60_000,\n  cooldownMs: 5 * 60_000,\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\n    \u002F\u002F Restore grid-span state from localStorage\n    const state = this.loadMap();\n    if (state) {\n      if (state.colSpan) this.element.classList.add(`col-span-${state.colSpan}`);\n      if (state.rowSpan) this.element.classList.add(`row-span-${state.rowSpan}`);\n      if (state.collapsed === 'true') this.element.classList.add('collapsed');\n    }\n\n    this.fetchData();\n    this.refreshTimer = setInterval(() => this.fetchData(), 60_000);\n\n    const btn = document.createElement('button');\n    btn.className = 'panel-refresh-btn';\n    btn.textContent = 'Refresh';\n    btn.addEventListener('click', () => this.fetchData());\n    this.header.appendChild(btn);\n\n    this.setNewBadge('NEW');\n  }\n\n  private async fetchData(): Promise\u003Cvoid> {\n    if (this.isFetching) return;\n    this.setFetching(true);\n    this.showLoading();\n    try {\n      const quotes = await breaker.execute(() => fetchStockQuotes(), []);\n      this.setContent(this.renderQuotes(quotes));\n      this.setCount(quotes.length);\n      this.setDataBadge('LIVE', 'live');\n      const colM = this.element.className.match(\u002Fcol-span-(\\d+)\u002F);\n      const rowM = this.element.className.match(\u002Frow-span-(\\d+)\u002F);\n      this.saveMap({\n        colSpan: colM ? colM[1] : '1',\n        rowSpan: rowM ? rowM[1] : '1',\n      });\n    } catch (err) {\n      this.setDataBadge('ERROR', 'error');\n      this.showError('Failed to load stock data', () => this.fetchData(), 30_000);\n    } finally {\n      this.setFetching(false);\n    }\n  }\n\n  private renderQuotes(quotes: StockQuote[]): string {\n    if (!quotes.length) return '\u003Cp class=\"panel-empty\">No data\u003C\u002Fp>';\n    return 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 ?? '—'}\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>`).join('');\n  }\n\n  public override destroy(): void {\n    if (this.refreshTimer) clearInterval(this.refreshTimer);\n    super.destroy();\n  }\n}\n```\n\n### Option B — Direct fetch with `fetchWithRetry` (no external service)\n\nUse this when there is no existing service function and you want full control over\nthe HTTP call with per-request retry baked in.\n\n```typescript\nexport class NewsPanel extends Panel {\n  constructor() {\n    super({ id: 'news', title: 'Latest News' });\n    const state = this.loadMap();\n    if (state?.collapsed === 'true') this.element.classList.add('collapsed');\n    this.load();\n  }\n\n  private async load(): Promise\u003Cvoid> {\n    if (this.isFetching) return;\n    this.setFetching(true);\n    this.retryAttempts = 0;\n    this.retryDelay    = 1000;\n    try {\n      const data = await this.fetchWithRetry('\u002Fapi\u002Fnews') as NewsItem[];\n      this.setContent(this.renderNews(data));\n      this.setDataBadge('LIVE', 'live');\n    } catch (err) {\n      this.setDataBadge('ERROR', 'error');\n      this.showError('Could not load news', () => this.load(), 15_000);\n    } finally {\n      this.setFetching(false);\n    }\n  }\n\n  private renderNews(items: NewsItem[]): string {\n    return items.map(i => `\u003Cdiv class=\"news-item\">${i.headline}\u003C\u002Fdiv>`).join('');\n  }\n}\n```\n\n---\n\n## CSS reference for new features\n\n```css\n\u002F* Radar loading animation *\u002F\n.panel-loading-radar {\n  position: relative;\n  width: 40px;\n  height: 40px;\n  margin: 0 auto 8px;\n}\n.radar-ring {\n  position: absolute;\n  inset: 0;\n  border-radius: 50%;\n  border: 2px solid var(--accent, #4af);\n  opacity: 0;\n  animation: radar-pulse 1.8s ease-out infinite;\n}\n.radar-ring-2 { animation-delay: 0.6s; }\n.radar-ring-3 { animation-delay: 1.2s; }\n@keyframes radar-pulse {\n  0%   { transform: scale(0.3); opacity: 0.8; }\n  100% { transform: scale(1.4); opacity: 0; }\n}\n\n\u002F* Data badge variants *\u002F\n.panel-data-badge[data-variant=\"live\"]  { background: var(--green, #2a2); color: #fff; }\n.panel-data-badge[data-variant=\"stale\"] { background: var(--yellow, #aa2); color: #fff; }\n.panel-data-badge[data-variant=\"error\"] { background: var(--red, #a22);   color: #fff; }\n\n\u002F* Dual resize handles *\u002F\n.panel-resize-handle-row {\n  position: absolute;\n  bottom: 0;\n  left: 0;\n  right: 0;\n  height: 6px;\n  cursor: row-resize;\n}\n.panel-resize-handle-col {\n  position: absolute;\n  top: 0;\n  right: 0;\n  bottom: 0;\n  width: 6px;\n  cursor: col-resize;\n}\n\n\u002F* Error countdown *\u002F\n.panel-error-countdown {\n  font-size: 0.75rem;\n  opacity: 0.7;\n  margin-top: 4px;\n}\n```\n","# Resilient Panel — Unified Pattern (v2)\n\nCreate dashboard panel components using **vanilla TypeScript** (no framework, no JSX).\nEach panel is a class extending a `Panel` base class and optionally wraps its data source with a `CircuitBreaker`.\n\n---\n\n## Architecture Overview\n\n```\nPanel (base class)\n├── element: HTMLElement (.panel)\n│   ├── header: HTMLElement (.panel-header)\n│   │   ├── headerLeft (.panel-header-left)\n│   │   │   ├── title (.panel-title)\n│   │   │   └── newBadge (.panel-new-badge) [optional, via setNewBadge()]\n│   │   ├── statusBadge (.panel-data-badge) [optional, via setDataBadge()]\n│   │   └── countEl (.panel-count) [optional]\n│   ├── content: HTMLElement (.panel-content)\n│   ├── resizeHandleRow (.panel-resize-handle-row)   [bottom edge]\n│   └── resizeHandleCol (.panel-resize-handle-col)   [right edge]\n```\n\n### Resilience layers (choose what you need)\n\n| Layer | File | When to use |\n|---|---|---|\n| **isFetching guard** | `Panel` base class | Always — prevents concurrent duplicate requests |\n| **Exponential-backoff retry** | `Panel.fetchWithRetry()` | When you own the fetch call and want per-request retry before surfacing an error |\n| **Error countdown in showError()** | `Panel` base class | Automatic retry countdown rendered inside the error state UI |\n| **CircuitBreaker** | `src\u002Futils\u002Fcircuit-breaker.ts` | When a service may fail repeatedly; stops hammering the API and serves stale cache instead |\n| **localStorage persistence** | `Panel.saveMap()` \u002F `loadMap()` | When you want grid-span (not pixel size) state to survive page reloads |\n\n> **Wrapping an existing service call with CircuitBreaker is a one-liner:**\n> ```typescript\n> \u002F\u002F Before\n> const data = await fetchStockQuotes();\n> \u002F\u002F After — adds caching + cooldown with zero refactor\n> const data = await breaker.execute(() => fetchStockQuotes(), []);\n> ```\n\n---\n\n## File 1 — `src\u002Fcomponents\u002FPanel.ts`\n\n> **Authoritative implementation.** Use this verbatim; do not revert to\n> the older `saveState()`\u002F`loadState()` width\u002Fheight approach.\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 headerLeft: HTMLElement;\n  protected countEl: HTMLElement | null = null;\n  protected statusBadge: HTMLElement | null = null;\n  protected newBadge: HTMLElement | null = null;\n  protected panelId: string;\n\n  private _fetching = false;\n  private _countdownInterval: ReturnType\u003Ctypeof setInterval> | null = null;\n  private _resizeListeners: Array\u003C{ target: EventTarget; type: string; fn: EventListenerOrEventListenerObject }> = [];\n\n  \u002F\u002F Retry state (used by fetchWithRetry)\n  protected retryAttempts = 0;\n  protected retryDelay = 1000; \u002F\u002F ms; doubles each attempt\n  private maxRetries = 3;\n\n  constructor(options: PanelOptions) {\n    this.panelId = options.id;\n\n    this.element = document.createElement('div');\n    this.element.className = `panel${options.className ? ' ' + 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    this.headerLeft = document.createElement('div');\n    this.headerLeft.className = 'panel-header-left';\n\n    const title = document.createElement('span');\n    title.className = 'panel-title';\n    title.textContent = options.title;\n    this.headerLeft.appendChild(title);\n    this.header.appendChild(this.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    \u002F\u002F Dual resize handles\n    const resizeHandleRow = document.createElement('div');\n    resizeHandleRow.className = 'panel-resize-handle-row';\n\n    const resizeHandleCol = document.createElement('div');\n    resizeHandleCol.className = 'panel-resize-handle-col';\n\n    this.element.appendChild(this.header);\n    this.element.appendChild(this.content);\n    this.element.appendChild(resizeHandleRow);\n    this.element.appendChild(resizeHandleCol);\n\n    this._initResizeHandles(resizeHandleRow, resizeHandleCol);\n    this.showLoading();\n  }\n\n  \u002F\u002F Public API\n\n  public getElement(): HTMLElement { return this.element; }\n\n  \u002F** Radar-ring loading animation with optional message. *\u002F\n  public showLoading(message = 'Loading...'): void {\n    this._clearCountdown();\n    this.content.innerHTML = `\n      \u003Cdiv class=\"panel-loading\">\n        \u003Cdiv class=\"panel-loading-radar\">\n          \u003Cdiv class=\"radar-ring radar-ring-1\">\u003C\u002Fdiv>\n          \u003Cdiv class=\"radar-ring radar-ring-2\">\u003C\u002Fdiv>\n          \u003Cdiv class=\"radar-ring radar-ring-3\">\u003C\u002Fdiv>\n        \u003C\u002Fdiv>\n        \u003Cdiv class=\"panel-loading-text\">${message}\u003C\u002Fdiv>\n      \u003C\u002Fdiv>`;\n  }\n\n  \u002F**\n   * Show an error state.\n   * If autoRetryMs is provided, renders an exponential-backoff countdown\n   * inside the error UI and calls onRetry automatically when it reaches 0.\n   *\u002F\n  public showError(\n    message = 'Failed to load',\n    onRetry?: () => void,\n    autoRetryMs?: number\n  ): void {\n    this._clearCountdown();\n    const countdownId = `panel-error-countdown-${this.panelId}`;\n    this.content.innerHTML = `\n      \u003Cdiv class=\"panel-error-state\">\n        \u003Cdiv class=\"panel-error-msg\">${message}\u003C\u002Fdiv>\n        ${autoRetryMs != null\n          ? `\u003Cdiv class=\"panel-error-countdown\" id=\"${countdownId}\">Retrying in ${Math.ceil(autoRetryMs \u002F 1000)}s...\u003C\u002Fdiv>`\n          : ''}\n        ${onRetry ? '\u003Cbutton class=\"panel-retry-btn\" data-panel-retry>Retry\u003C\u002Fbutton>' : ''}\n      \u003C\u002Fdiv>`;\n\n    if (onRetry) {\n      this.content.querySelector('[data-panel-retry]')\n        ?.addEventListener('click', () => { this._clearCountdown(); onRetry(); });\n    }\n\n    if (autoRetryMs != null && onRetry) {\n      let remaining = autoRetryMs;\n      const getEl = () => this.content.querySelector\u003CHTMLElement>(`#${countdownId}`);\n      this._countdownInterval = setInterval(() => {\n        remaining -= 1000;\n        if (remaining \u003C= 0) {\n          this._clearCountdown();\n          onRetry();\n        } else {\n          const node = getEl();\n          if (node) node.textContent = `Retrying in ${Math.ceil(remaining \u002F 1000)}s...`;\n        }\n      }, 1000);\n    }\n  }\n\n  public setContent(html: string): void {\n    this._clearCountdown();\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  \u002F**\n   * Show (or update) the data-status badge in the panel header.\n   * Pass a variant CSS modifier such as 'live', 'stale', or 'error'.\n   *\u002F\n  public setDataBadge(text: string, variant = 'live'): void {\n    if (!this.statusBadge) {\n      this.statusBadge = document.createElement('span');\n      this.statusBadge.className = 'panel-data-badge';\n      this.header.appendChild(this.statusBadge);\n    }\n    this.statusBadge.textContent = text;\n    this.statusBadge.dataset.variant = variant;\n  }\n\n  public clearDataBadge(): void {\n    this.statusBadge?.remove();\n    this.statusBadge = null;\n  }\n\n  \u002F** Show the \"NEW\" badge next to the panel title (idempotent). *\u002F\n  public setNewBadge(text = 'NEW'): void {\n    if (!this.newBadge) {\n      this.newBadge = document.createElement('span');\n      this.newBadge.className = 'panel-new-badge';\n      this.headerLeft.appendChild(this.newBadge);\n    }\n    this.newBadge.textContent = text;\n  }\n\n  public clearNewBadge(): void {\n    this.newBadge?.remove();\n    this.newBadge = null;\n  }\n\n  public show(): void { this.element.classList.remove('hidden'); }\n  public hide(): void { this.element.classList.add('hidden'); }\n\n  \u002F** Full teardown: removes element, clears countdown timer, removes all resize listeners. *\u002F\n  public destroy(): void {\n    this._clearCountdown();\n    for (const { target, type, fn } of this._resizeListeners) {\n      target.removeEventListener(type, fn);\n    }\n    this._resizeListeners = [];\n    this.element.remove();\n  }\n\n  \u002F\u002F Protected helpers\n\n  protected setFetching(v: boolean): void { this._fetching = v; }\n  protected get isFetching(): boolean { return this._fetching; }\n\n  \u002F**\n   * Fetch url with exponential-backoff retry (up to maxRetries attempts).\n   * Reset this.retryAttempts and this.retryDelay before calling if you\n   * want a fresh retry sequence (e.g. from a user-initiated Retry button).\n   *\u002F\n  protected async fetchWithRetry(url: string): Promise\u003Cunknown> {\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(\n            `Failed after ${this.maxRetries} attempts: ${(error as Error).message}`\n          );\n        }\n        await new Promise(resolve => setTimeout(resolve, this.retryDelay));\n        this.retryDelay *= 2;\n      }\n    }\n  }\n\n  \u002F\u002F Grid-span persistence\n  \u002F\u002F\n  \u002F\u002F Panels live inside a CSS grid. Their size is expressed as span classes\n  \u002F\u002F (e.g. \"col-span-2\", \"row-span-3\"), NOT inline pixel widths\u002Fheights.\n  \u002F\u002F Use saveMap \u002F loadMap to persist this.\n\n  \u002F**\n   * Persist an arbitrary key->value map to localStorage under this panel's key.\n   * Typical use: save current grid-span class numbers.\n   *\n   *   this.saveMap({ colSpan: '2', rowSpan: '1', collapsed: 'false' });\n   *\u002F\n  public saveMap(data: Record\u003Cstring, string>): void {\n    localStorage.setItem(`panelState_${this.panelId}`, JSON.stringify(data));\n  }\n\n  \u002F**\n   * Load the map saved by saveMap(), or null if nothing was stored.\n   *\n   *   const state = this.loadMap();\n   *   if (state) {\n   *     this.element.classList.add(`col-span-${state.colSpan}`);\n   *     this.element.classList.add(`row-span-${state.rowSpan}`);\n   *     if (state.collapsed === 'true') this.element.classList.add('collapsed');\n   *   }\n   *\u002F\n  public loadMap(): Record\u003Cstring, string> | null {\n    const raw = localStorage.getItem(`panelState_${this.panelId}`);\n    if (!raw) return null;\n    try {\n      return JSON.parse(raw) as Record\u003Cstring, string>;\n    } catch {\n      return null;\n    }\n  }\n\n  \u002F\u002F Private internals\n\n  private _clearCountdown(): void {\n    if (this._countdownInterval !== null) {\n      clearInterval(this._countdownInterval);\n      this._countdownInterval = null;\n    }\n  }\n\n  \u002F**\n   * Wire up the two resize handles.\n   * Row handle drags vertically and updates the row-span class.\n   * Col handle drags horizontally and updates the col-span class.\n   * All listeners are tracked in _resizeListeners for clean destroy().\n   *\u002F\n  private _initResizeHandles(\n    rowHandle: HTMLElement,\n    colHandle: HTMLElement\n  ): void {\n    const track = (\n      target: EventTarget,\n      type: string,\n      fn: EventListenerOrEventListenerObject\n    ) => {\n      target.addEventListener(type, fn);\n      this._resizeListeners.push({ target, type, fn });\n    };\n\n    \u002F\u002F Row resize (bottom handle)\n    let rowDragging = false;\n    let rowStartY = 0;\n    let rowStartSpan = 1;\n\n    const onRowMouseDown = (e: Event) => {\n      const me = e as MouseEvent;\n      rowDragging = true;\n      rowStartY = me.clientY;\n      const m = (this.element.className.match(\u002Frow-span-(\\d+)\u002F) ?? [])[1];\n      rowStartSpan = m ? parseInt(m, 10) : 1;\n      me.preventDefault();\n    };\n    const onRowMouseMove = (e: Event) => {\n      if (!rowDragging) return;\n      const me = e as MouseEvent;\n      const delta = Math.round((me.clientY - rowStartY) \u002F 60);\n      const newSpan = Math.max(1, Math.min(6, rowStartSpan + delta));\n      this.element.className = this.element.className\n        .replace(\u002Frow-span-\\d+\u002F, `row-span-${newSpan}`)\n        .trim();\n      if (!\u002Frow-span-\\d+\u002F.test(this.element.className)) {\n        this.element.classList.add(`row-span-${newSpan}`);\n      }\n    };\n    const onRowMouseUp = () => { rowDragging = false; };\n\n    track(rowHandle, 'mousedown', onRowMouseDown);\n    track(document,  'mousemove', onRowMouseMove);\n    track(document,  'mouseup',   onRowMouseUp);\n\n    \u002F\u002F Col resize (right handle)\n    let colDragging = false;\n    let colStartX = 0;\n    let colStartSpan = 1;\n\n    const onColMouseDown = (e: Event) => {\n      const me = e as MouseEvent;\n      colDragging = true;\n      colStartX = me.clientX;\n      const m = (this.element.className.match(\u002Fcol-span-(\\d+)\u002F) ?? [])[1];\n      colStartSpan = m ? parseInt(m, 10) : 1;\n      me.preventDefault();\n    };\n    const onColMouseMove = (e: Event) => {\n      if (!colDragging) return;\n      const me = e as MouseEvent;\n      const delta = Math.round((me.clientX - colStartX) \u002F 120);\n      const newSpan = Math.max(1, Math.min(12, colStartSpan + delta));\n      this.element.className = this.element.className\n        .replace(\u002Fcol-span-\\d+\u002F, `col-span-${newSpan}`)\n        .trim();\n      if (!\u002Fcol-span-\\d+\u002F.test(this.element.className)) {\n        this.element.classList.add(`col-span-${newSpan}`);\n      }\n    };\n    const onColMouseUp = () => { colDragging = false; };\n\n    track(colHandle, 'mousedown', onColMouseDown);\n    track(document,  'mousemove', onColMouseMove);\n    track(document,  'mouseup',   onColMouseUp);\n  }\n}\n```\n\n---\n\n## File 2 — `src\u002Futils\u002Fcircuit-breaker.ts`\n\n```typescript\ninterface CircuitState {\n  failures: number;\n  cooldownUntil: number;\n}\n\ninterface CacheEntry\u003CT> {\n  data: T;\n  timestamp: number;\n}\n\nexport interface CircuitBreakerOptions {\n  name: string;\n  maxFailures?: number;   \u002F\u002F default 2\n  cooldownMs?: number;    \u002F\u002F default 5 min\n  cacheTtlMs?: number;    \u002F\u002F default 10 min\n}\n\nexport class CircuitBreaker\u003CT> {\n  private state: CircuitState = { failures: 0, cooldownUntil: 0 };\n  private cache: CacheEntry\u003CT> | null = null;\n  private readonly name: string;\n  private readonly maxFailures: number;\n  private readonly cooldownMs: number;\n  private readonly cacheTtlMs: number;\n\n  constructor(options: CircuitBreakerOptions) {\n    this.name        = options.name;\n    this.maxFailures = options.maxFailures ?? 2;\n    this.cooldownMs  = options.cooldownMs  ?? 5 * 60 * 1000;\n    this.cacheTtlMs  = options.cacheTtlMs  ?? 10 * 60 * 1000;\n  }\n\n  isOnCooldown(): boolean {\n    if (Date.now() \u003C this.state.cooldownUntil) return true;\n    if (this.state.cooldownUntil > 0) {\n      this.state = { failures: 0, cooldownUntil: 0 };\n    }\n    return false;\n  }\n\n  getCached(): T | null {\n    if (this.cache && Date.now() - this.cache.timestamp \u003C this.cacheTtlMs) {\n      return this.cache.data;\n    }\n    return null;\n  }\n\n  recordSuccess(data: T): void {\n    this.state = { failures: 0, cooldownUntil: 0 };\n    this.cache = { data, timestamp: Date.now() };\n  }\n\n  recordFailure(): void {\n    this.state.failures++;\n    if (this.state.failures >= this.maxFailures) {\n      this.state.cooldownUntil = Date.now() + this.cooldownMs;\n      console.warn(`[${this.name}] Circuit open — cooldown ${this.cooldownMs \u002F 1000}s`);\n    }\n  }\n\n  \u002F**\n   * Execute fn. On success, caches result. On failure, records failure and\n   * returns defaultValue. While on cooldown or cache is fresh, skips fn\n   * entirely and returns cached\u002Fdefault value.\n   *\u002F\n  async execute\u003CR extends T>(fn: () => Promise\u003CR>, defaultValue: R): Promise\u003CR> {\n    if (this.isOnCooldown()) {\n      const cached = this.getCached();\n      return (cached as R) ?? defaultValue;\n    }\n    const cached = this.getCached();\n    if (cached !== null) return cached as R;\n    try {\n      const result = await fn();\n      this.recordSuccess(result);\n      return result;\n    } catch (e) {\n      console.error(`[${this.name}] Request failed:`, e);\n      this.recordFailure();\n      return defaultValue;\n    }\n  }\n}\n\nexport function createCircuitBreaker\u003CT>(\n  options: CircuitBreakerOptions\n): CircuitBreaker\u003CT> {\n  return new CircuitBreaker\u003CT>(options);\n}\n```\n\n---\n\n## File 3 — `src\u002Futils\u002Fsparkline.ts`\n\n```typescript\n\u002F**\n * Returns an inline SVG sparkline string, or '' if data is too short.\n * Embed the return value directly in HTML template strings.\n *\u002F\nexport function miniSparkline(\n  data: number[] | undefined,\n  change: number | null,\n  w = 50,\n  h = 16\n): 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}\">` +\n    `\u003Cpolyline points=\"${points}\" fill=\"none\" stroke=\"${color}\" ` +\n    `stroke-width=\"1.2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"\u002F>\u003C\u002Fsvg>`;\n}\n```\n\n---\n\n## Key differences from the old Panel pattern\n\n| Feature | Old pattern | New (authoritative) pattern |\n|---|---|---|\n| Persistence | `saveState()`\u002F`loadState()` with inline `width`\u002F`height` strings | `saveMap()`\u002F`loadMap()` with arbitrary key\u002Fvalue map; store grid-span class numbers |\n| Resize | Single `.panel-resize-handle` | Dual handles: `.panel-resize-handle-row` (vertical) + `.panel-resize-handle-col` (horizontal) |\n| Loading UI | Spinner div | Radar-ring animation (3 nested `.radar-ring` divs) |\n| Error UI | Static message + optional retry button | Message + optional countdown timer (`autoRetryMs`) + retry button; countdown clears on manual retry |\n| Badges | None | `setDataBadge(text, variant)` \u002F `clearDataBadge()` and `setNewBadge(text)` \u002F `clearNewBadge()` |\n| `destroy()` | `element.remove()` only | Clears countdown interval + removes all resize `document` listeners + `element.remove()` |\n\n---\n\n## Creating a Concrete Panel\n\n### Option A — Wrapping an existing project service with CircuitBreaker (preferred)\n\nUse this when the project already has a `fetchStockQuotes()` (or similar) function.\nThe circuit breaker is a **one-liner wrapper** — no refactoring of the service needed.\n\n```typescript\nimport { Panel } from '.\u002FPanel';\nimport { createCircuitBreaker } from '..\u002Futils\u002Fcircuit-breaker';\nimport { fetchStockQuotes } from '..\u002Fservices\u002Fstocks'; \u002F\u002F existing project service\n\ninterface StockQuote {\n  symbol: string;\n  name: string;\n  price: number | null;\n  change: number | null;\n  sparkline?: number[];\n}\n\n\u002F\u002F Module-level breaker — shared across re-renders, persists cache between fetches\nconst breaker = createCircuitBreaker\u003CStockQuote[]>({\n  name: 'StockMarket',\n  cacheTtlMs: 60_000,\n  cooldownMs: 5 * 60_000,\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\n    \u002F\u002F Restore grid-span state from localStorage\n    const state = this.loadMap();\n    if (state) {\n      if (state.colSpan) this.element.classList.add(`col-span-${state.colSpan}`);\n      if (state.rowSpan) this.element.classList.add(`row-span-${state.rowSpan}`);\n      if (state.collapsed === 'true') this.element.classList.add('collapsed');\n    }\n\n    this.fetchData();\n    this.refreshTimer = setInterval(() => this.fetchData(), 60_000);\n\n    const btn = document.createElement('button');\n    btn.className = 'panel-refresh-btn';\n    btn.textContent = 'Refresh';\n    btn.addEventListener('click', () => this.fetchData());\n    this.header.appendChild(btn);\n\n    this.setNewBadge('NEW');\n  }\n\n  private async fetchData(): Promise\u003Cvoid> {\n    if (this.isFetching) return;\n    this.setFetching(true);\n    this.showLoading();\n    try {\n      const quotes = await breaker.execute(() => fetchStockQuotes(), []);\n      this.setContent(this.renderQuotes(quotes));\n      this.setCount(quotes.length);\n      this.setDataBadge('LIVE', 'live');\n      const colM = this.element.className.match(\u002Fcol-span-(\\d+)\u002F);\n      const rowM = this.element.className.match(\u002Frow-span-(\\d+)\u002F);\n      this.saveMap({\n        colSpan: colM ? colM[1] : '1',\n        rowSpan: rowM ? rowM[1] : '1',\n      });\n    } catch (err) {\n      this.setDataBadge('ERROR', 'error');\n      this.showError('Failed to load stock data', () => this.fetchData(), 30_000);\n    } finally {\n      this.setFetching(false);\n    }\n  }\n\n  private renderQuotes(quotes: StockQuote[]): string {\n    if (!quotes.length) return '\u003Cp class=\"panel-empty\">No data\u003C\u002Fp>';\n    return 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 ?? '—'}\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>`).join('');\n  }\n\n  public override destroy(): void {\n    if (this.refreshTimer) clearInterval(this.refreshTimer);\n    super.destroy();\n  }\n}\n```\n\n### Option B — Direct fetch with `fetchWithRetry` (no external service)\n\nUse this when there is no existing service function and you want full control over\nthe HTTP call with per-request retry baked in.\n\n```typescript\nexport class NewsPanel extends Panel {\n  constructor() {\n    super({ id: 'news', title: 'Latest News' });\n    const state = this.loadMap();\n    if (state?.collapsed === 'true') this.element.classList.add('collapsed');\n    this.load();\n  }\n\n  private async load(): Promise\u003Cvoid> {\n    if (this.isFetching) return;\n    this.setFetching(true);\n    this.retryAttempts = 0;\n    this.retryDelay    = 1000;\n    try {\n      const data = await this.fetchWithRetry('\u002Fapi\u002Fnews') as NewsItem[];\n      this.setContent(this.renderNews(data));\n      this.setDataBadge('LIVE', 'live');\n    } catch (err) {\n      this.setDataBadge('ERROR', 'error');\n      this.showError('Could not load news', () => this.load(), 15_000);\n    } finally {\n      this.setFetching(false);\n    }\n  }\n\n  private renderNews(items: NewsItem[]): string {\n    return items.map(i => `\u003Cdiv class=\"news-item\">${i.headline}\u003C\u002Fdiv>`).join('');\n  }\n}\n```\n\n---\n\n## CSS reference for new features\n\n```css\n\u002F* Radar loading animation *\u002F\n.panel-loading-radar {\n  position: relative;\n  width: 40px;\n  height: 40px;\n  margin: 0 auto 8px;\n}\n.radar-ring {\n  position: absolute;\n  inset: 0;\n  border-radius: 50%;\n  border: 2px solid var(--accent, #4af);\n  opacity: 0;\n  animation: radar-pulse 1.8s ease-out infinite;\n}\n.radar-ring-2 { animation-delay: 0.6s; }\n.radar-ring-3 { animation-delay: 1.2s; }\n@keyframes radar-pulse {\n  0%   { transform: scale(0.3); opacity: 0.8; }\n  100% { transform: scale(1.4); opacity: 0; }\n}\n\n\u002F* Data badge variants *\u002F\n.panel-data-badge[data-variant=\"live\"]  { background: var(--green, #2a2); color: #fff; }\n.panel-data-badge[data-variant=\"stale\"] { background: var(--yellow, #aa2); color: #fff; }\n.panel-data-badge[data-variant=\"error\"] { background: var(--red, #a22);   color: #fff; }\n\n\u002F* Dual resize handles *\u002F\n.panel-resize-handle-row {\n  position: absolute;\n  bottom: 0;\n  left: 0;\n  right: 0;\n  height: 6px;\n  cursor: row-resize;\n}\n.panel-resize-handle-col {\n  position: absolute;\n  top: 0;\n  right: 0;\n  bottom: 0;\n  width: 6px;\n  cursor: col-resize;\n}\n\n\u002F* Error countdown *\u002F\n.panel-error-countdown {\n  font-size: 0.75rem;\n  opacity: 0.7;\n  margin-top: 4px;\n}\n```\n",{"name":5,"description":7},"main","ff671ef61ed6587c49bd54c81cdc751c0b99e363","showcase\u002Fskills\u002Fpanel-base-advanced","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":51,"prompt":61,"zipAvailable":62},[52,55,58],{"tool":53,"command":54},"npx","npx skills add AG064\u002FOpenSpace --skill panel-base-advanced",{"tool":56,"command":57},"bunx","bunx skills add AG064\u002FOpenSpace --skill panel-base-advanced",{"tool":59,"command":60},"pnpm","pnpm dlx skills add AG064\u002FOpenSpace --skill panel-base-advanced","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FAG064\u002FOpenSpace\u002Fblob\u002Fmain\u002Fshowcase\u002Fskills\u002Fpanel-base-advanced\u002FSKILL.md",true,[64],{"path":65,"resourceType":66,"resourceTypeDesc":67,"sizeBytes":68,"sourceHtmlUrl":69},".skill_id","OTHER","其他",61,"https:\u002F\u002Fgithub.com\u002FAG064\u002FOpenSpace\u002Fblob\u002Fmain\u002Fshowcase\u002Fskills\u002Fpanel-base-advanced\u002F.skill_id",[71,94,110,119,145,161],{"skillNo":72,"name":73,"nameZh":6,"description":74,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":9,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":75,"categories":76,"keywords":77,"publishedAt":38},"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",[],[78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,29],"write special chars ts check","check","write","filters","Existing","type-checking","for","errors","script","output","type","files","only","template","file","python",{"skillNo":95,"name":96,"nameZh":6,"description":97,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":9,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":98,"categories":99,"keywords":100,"publishedAt":38},"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",[],[101,102,80,91,34,103,92,93,104,105,106,107,108,84,86,109],"readback","write special chars readback","read","scripts","verification","via","post","helper","with",{"skillNo":111,"name":112,"nameZh":6,"description":113,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":9,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":114,"categories":115,"keywords":116,"publishedAt":38},"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",[],[80,117,93,84,106,91,118,92,86],"write special chars heredoc","shell",{"skillNo":120,"name":121,"nameZh":6,"description":122,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":9,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":123,"categories":124,"keywords":130,"publishedAt":38},"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",[125],{"categoryNo":126,"categoryName":127,"taxonomyType":128,"taxonomyTypeDesc":129},"01JBSEEDCAT000000000000033","数据分析师","PROFESSION","适用职业",[131,132,133,37,29,134,135,136,137,138,84,23,20,139,140,141,142,143,33,144],"reference","worldmonitor","worldmonitor reference","css","architecture","extracting","hierarchy","source","patterns","edge functions","integrations","open","api","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":38},"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,84,156,109,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":38},"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,92,174,175,176],"directory","verify","structure","verify directory structure","access","first","issues","diagnose","file access"]