[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6HXAD6C421XV6168C2FZ2B8":3,"skill-same:01M6HXAD6C421XV6168C2FZ2B8":72},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":39,"linkOnly":40,"markdownContent":41,"markdownBody":42,"frontMatter":43,"refName":44,"commitSha":45,"skillDirectory":46,"forksCount":47,"repositoryHtmlUrl":48,"repositoryHomepageUrl":6,"ownerHtmlUrl":49,"ownerBlogUrl":50,"ownerDescription":6,"updatedAt":51,"install":52,"resources":65},"01M6HXAD6C421XV6168C2FZ2B8","panel-component-with-push-sidebar",null,"Dashboard panel components (class-based, self-fetching) and push-update sidebar modules (functional, externally-driven) using vanilla TypeScript DOM API, with retry logic, localStorage persistence, and guarded CSS injection.","HKUDS\u002FAgentPilot","HKUDS","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F118165258?v=4","01M6HW8VRNZP64G0P4MVJW2KKQ","✨Data Intelligence Lab@HKU✨","01M6HW8VWZVHBRHYH3T330PFWV",8029,"MIT","https:\u002F\u002Fgithub.com\u002FHKUDS\u002FAgentPilot\u002Fblob\u002Fmain\u002Fopenspace\u002Fexamples\u002Fmy-daily-monitor\u002Fskills\u002Fpanel-component-with-push-sidebar\u002FSKILL.md",[],[19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38],"panel component with push sidebar","component","with","push","panel","modules","dom","retry","functional","driven","logic","self","css","api","injection","persistence","update","components","dashboard","typescript","2026-11-10 10:12:30",false,"---\nname: panel-component-with-push-sidebar\ndescription: Dashboard panel components (class-based, self-fetching) and push-update sidebar modules (functional, externally-driven) using vanilla TypeScript DOM API, with retry logic, localStorage persistence, and guarded CSS injection.\n---\n\n# Panel & Push-Update Sidebar Patterns\n\nTwo complementary patterns for building dashboard UI in **vanilla TypeScript** (no framework, no JSX):\n\n| Pattern | Use when… |\n|---|---|\n| **Panel class** (extends `Panel`) | The component fetches its own data on a timer |\n| **Push-update sidebar module** | Data arrives from outside (caller pushes it in) |\n\n---\n\n## Part 1 — Panel Class Pattern\n\n### Architecture Overview\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\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  \u002F\u002F --- Retry state (reset before each logical fetch sequence) ---\n  private retryAttempts = 0;\n  private maxRetries = 3;\n  private retryDelay = 1000; \u002F\u002F ms; doubles on each attempt\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  \u002F\u002F ----------------------------------------------------------------\n  \u002F\u002F Public API\n  \u002F\u002F ----------------------------------------------------------------\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]')\n        ?.addEventListener('click', onRetry);\n    }\n  }\n\n  public setContent(html: string): void { this.content.innerHTML = html; }\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  public destroy(): void { this.element.remove(); }\n\n  \u002F\u002F ----------------------------------------------------------------\n  \u002F\u002F Protected API — available in subclasses\n  \u002F\u002F ----------------------------------------------------------------\n\n  protected setFetching(v: boolean): void { this._fetching = v; }\n  protected get isFetching(): boolean { return this._fetching; }\n\n  \u002F**\n   * Fetch a URL with exponential-backoff retry.\n   * Call resetRetry() before each new fetch sequence.\n   *\u002F\n  protected async fetchWithRetry(url: string): Promise\u003Cunknown> {\n    while (this.retryAttempts \u003C this.maxRetries) {\n      try {\n        const res = await fetch(url);\n        if (!res.ok) throw new Error(`HTTP ${res.status}`);\n        return await res.json();\n      } catch (err: unknown) {\n        this.retryAttempts++;\n        if (this.retryAttempts >= this.maxRetries) {\n          const msg = err instanceof Error ? err.message : String(err);\n          throw new Error(`Failed after ${this.maxRetries} attempts: ${msg}`);\n        }\n        await new Promise(r => setTimeout(r, this.retryDelay));\n        this.retryDelay *= 2;\n      }\n    }\n  }\n\n  \u002F** Reset retry counters before a fresh fetch sequence. *\u002F\n  protected resetRetry(): void {\n    this.retryAttempts = 0;\n    this.retryDelay = 1000;\n  }\n\n  \u002F\u002F ----------------------------------------------------------------\n  \u002F\u002F State persistence (localStorage)\n  \u002F\u002F ----------------------------------------------------------------\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 raw = localStorage.getItem(`panelState_${this.panelId}`);\n    if (!raw) return;\n    const { isExpanded, width, height } = JSON.parse(raw) as {\n      isExpanded: boolean; width: string; height: string;\n    };\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### Protected API Reference\n\n| Member \u002F Method | Type | Description |\n|---|---|---|\n| `element` | `HTMLElement` | Outer container div (`.panel`) |\n| `header` | `HTMLElement` | Header bar — append extra controls here |\n| `content` | `HTMLElement` | Scrollable content area |\n| `countEl` | `HTMLElement \\| null` | Count badge, or `null` if `showCount` not set |\n| `panelId` | `string` | The `id` from `PanelOptions` |\n| `isFetching` | `boolean` getter | `true` while an async fetch is in progress |\n| `setFetching(v)` | `void` | Set\u002Fclear the fetching guard |\n| `showLoading(msg?)` | `void` | Replace content with a spinner |\n| `showError(msg?, onRetry?)` | `void` | Replace content with error + optional retry button |\n| `setContent(html)` | `void` | Set raw HTML into the content area |\n| `setCount(n)` | `void` | Update count badge (no-op if `countEl` is null) |\n| `fetchWithRetry(url)` | `Promise\u003Cunknown>` | Fetch with exponential-backoff retry (3 attempts) |\n| `resetRetry()` | `void` | Reset retry counters before a new fetch sequence |\n| `saveState()` | `void` | Persist expanded\u002Fsize state to localStorage |\n| `loadState()` | `void` | Restore state from localStorage |\n\n### Creating a Concrete Panel (Example: StockPanel)\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.loadState();          \u002F\u002F restore saved size\u002Fcollapsed state\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    this.resetRetry();         \u002F\u002F start a fresh retry sequence\n    try {\n      const quotes = await this.fetchWithRetry('\u002Fapi\u002Fstocks') as StockQuote[];\n      this.render(quotes);\n      this.setCount(quotes.length);\n      this.saveState();\n    } catch (err: unknown) {\n      const msg = err instanceof Error ? err.message : 'Unknown error';\n      this.showError(`Failed to load stock data: ${msg}`, () => 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        ${miniSparkline(q.sparkline, q.change)}\n      \u003C\u002Fdiv>`).join('');\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 for Self-Fetching Panels\n\n1. **Constructor** → `super()` → `loadState()` → initial `fetchData()` → start refresh timer\n2. **fetchData()** → `isFetching` guard → `resetRetry()` → `fetchWithRetry()` → `render()` + `saveState()`\n3. **render()** builds HTML strings → `this.setContent(html)`\n4. **destroy()** clears timers, calls `super.destroy()`\n5. Use `showLoading()` during initial load (auto-called in constructor)\n6. Use `showError(msg, retryFn)` on failure; retryFn must call `fetchData()` (which calls `resetRetry()`)\n\n---\n\n## Part 2 — Push-Update Sidebar Pattern\n\nUse this pattern when the component **does not fetch data itself** — instead it receives data pushed by an external caller (e.g. a WebSocket handler, a store subscription, or a parent orchestrator).\n\n### When to use this pattern vs. Panel class\n\n```\nSelf-fetching?  → Panel class (Part 1)\nData pushed in? → Push-update sidebar module (Part 2)\n```\n\n### Module Structure\n\nA push-update sidebar is a **plain TypeScript module** (not a class) with:\n\n| Export | Purpose |\n|---|---|\n| `createXSidebar(): HTMLElement` | Build and return the root element (idempotent singleton) |\n| `updateX(data: XData): void` | Re-render only the sections that changed |\n| `interface XData` | The data shape the caller must provide |\n\nInternally the module uses:\n- A **module-level singleton** `let sidebarEl: HTMLElement | null = null`\n- A **`SectionRefs` interface** caching live DOM node references to avoid repeated `querySelector` calls\n- A **guarded `injectStyles()`** function that inserts a `\u003Cstyle>` tag exactly once\n\n### Skeleton\n\n```typescript\n\u002F\u002F src\u002Fcomponents\u002FFooSidebar.ts\n\n\u002F\u002F ── Types ────────────────────────────────────────────────────────────────────\n\nexport interface FooData {\n  title: string;\n  items: { id: string; label: string; value: number }[];\n  lastUpdated: Date;\n}\n\n\u002F\u002F ── DOM node cache ────────────────────────────────────────────────────────────\n\ninterface SectionRefs {\n  root:      HTMLElement;\n  titleEl:   HTMLElement;\n  listEl:    HTMLElement;\n  footerEl:  HTMLElement;\n}\n\n\u002F\u002F ── Singleton state ───────────────────────────────────────────────────────────\n\nlet sidebarEl: HTMLElement | null = null;\nlet refs: SectionRefs | null = null;\nlet stylesInjected = false;\n\n\u002F\u002F ── CSS injection ─────────────────────────────────────────────────────────────\n\nfunction injectStyles(): void {\n  if (stylesInjected) return;            \u002F\u002F guard: run exactly once\n  stylesInjected = true;\n  const style = document.createElement('style');\n  style.dataset.owner = 'foo-sidebar';   \u002F\u002F easy to find in DevTools\n  style.textContent = `\n    .foo-sidebar { \u002F* … *\u002F }\n    .foo-sidebar__title { font-weight: 600; }\n    .foo-sidebar__list  { list-style: none; padding: 0; }\n    .foo-sidebar__footer { font-size: 0.75rem; color: var(--muted); }\n  `;\n  document.head.appendChild(style);\n}\n\n\u002F\u002F ── Builder ───────────────────────────────────────────────────────────────────\n\n\u002F**\n * Create (or return the existing) sidebar element.\n * Idempotent — safe to call multiple times; always returns the same node.\n *\u002F\nexport function createFooSidebar(): HTMLElement {\n  if (sidebarEl) return sidebarEl;       \u002F\u002F singleton guard\n\n  injectStyles();\n\n  const root = document.createElement('aside');\n  root.className = 'foo-sidebar';\n\n  const titleEl = document.createElement('h2');\n  titleEl.className = 'foo-sidebar__title';\n  root.appendChild(titleEl);\n\n  const listEl = document.createElement('ul');\n  listEl.className = 'foo-sidebar__list';\n  root.appendChild(listEl);\n\n  const footerEl = document.createElement('div');\n  footerEl.className = 'foo-sidebar__footer';\n  root.appendChild(footerEl);\n\n  \u002F\u002F Cache references — avoids querySelector on every update\n  refs = { root, titleEl, listEl, footerEl };\n  sidebarEl = root;\n  return root;\n}\n\n\u002F\u002F ── Updater ───────────────────────────────────────────────────────────────────\n\n\u002F**\n * Push new data into the sidebar.\n * Calls createFooSidebar() defensively if refs is not yet initialised.\n *\u002F\nexport function updateFoo(data: FooData): void {\n  if (!refs) createFooSidebar();\n  const r = refs!;\n\n  r.titleEl.textContent = data.title;\n\n  r.listEl.innerHTML = data.items\n    .map(item => `\n      \u003Cli class=\"foo-sidebar__item\" data-id=\"${item.id}\">\n        \u003Cspan class=\"foo-item-label\">${item.label}\u003C\u002Fspan>\n        \u003Cspan class=\"foo-item-value\">${item.value}\u003C\u002Fspan>\n      \u003C\u002Fli>`)\n    .join('');\n\n  r.footerEl.textContent =\n    `Updated ${data.lastUpdated.toLocaleTimeString()}`;\n}\n```\n\n### Real-World Example: TodayFocusSidebar\n\nA sidebar that summarises the user's day — greeting, meeting countdown, inbox counts, stock alerts, CI failures, and an AI briefing with truncate\u002Fexpand toggle. Data is pushed in from an external orchestrator.\n\n```typescript\n\u002F\u002F src\u002Fcomponents\u002FTodayFocusSidebar.ts\n\nexport interface FocusData {\n  userName: string;\n  nextMeeting: { title: string; startsInMinutes: number } | null;\n  inboxCounts: { email: number; slack: number; github: number };\n  stockAlerts: { symbol: string; changePercent: number }[]; \u002F\u002F pre-filtered >= 2%\n  ciFailures: { repo: string; branch: string }[];\n  aiBriefing: string; \u002F\u002F may be long — sidebar truncates with toggle\n}\n\ninterface SectionRefs {\n  root:       HTMLElement;\n  greetingEl: HTMLElement;\n  meetingEl:  HTMLElement;\n  inboxEl:    HTMLElement;\n  stocksEl:   HTMLElement;\n  ciEl:       HTMLElement;\n  briefingEl: HTMLElement;\n}\n\nlet sidebarEl: HTMLElement | null = null;\nlet refs: SectionRefs | null = null;\nlet stylesInjected = false;\n\n\u002F\u002F ── Helpers ───────────────────────────────────────────────────────────────────\n\nfunction greeting(name: string): string {\n  const h = new Date().getHours();\n  const salutation = h \u003C 12 ? 'Good morning' : h \u003C 17 ? 'Good afternoon' : 'Good evening';\n  return `${salutation}, ${name}`;\n}\n\nfunction formatCountdown(minutes: number): string {\n  if (minutes \u003C= 0) return 'Now';\n  if (minutes \u003C 60) return `in ${minutes}m`;\n  return `in ${Math.floor(minutes \u002F 60)}h ${minutes % 60}m`;\n}\n\n\u002F\u002F ── CSS ───────────────────────────────────────────────────────────────────────\n\nfunction injectStyles(): void {\n  if (stylesInjected) return;\n  stylesInjected = true;\n  const s = document.createElement('style');\n  s.dataset.owner = 'today-focus-sidebar';\n  s.textContent = `\n    .tfs { display:flex; flex-direction:column; gap:12px; padding:16px;\n           background:var(--bg-surface, #1e1e2e); color:var(--fg, #cdd6f4);\n           border-radius:8px; font-family:inherit; }\n    .tfs__greeting  { font-size:1.1rem; font-weight:600; }\n    .tfs__meeting   { font-size:0.85rem; color:var(--yellow, #f9e2af); }\n    .tfs__section   { font-size:0.85rem; }\n    .tfs__label     { font-size:0.7rem; text-transform:uppercase;\n                      letter-spacing:.06em; color:var(--muted, #6c7086);\n                      margin-bottom:4px; }\n    .tfs__briefing  { font-size:0.82rem; line-height:1.5; }\n    .tfs__toggle    { background:none; border:none; color:var(--blue, #89b4fa);\n                      cursor:pointer; font-size:0.8rem; padding:2px 0; }\n    .tfs__alert-pos { color:var(--green, #a6e3a1); }\n    .tfs__alert-neg { color:var(--red,   #f38ba8); }\n    .tfs__ci-fail   { color:var(--red,   #f38ba8); }\n  `;\n  document.head.appendChild(s);\n}\n\n\u002F\u002F ── Builder ───────────────────────────────────────────────────────────────────\n\nexport function createTodayFocusSidebar(): HTMLElement {\n  if (sidebarEl) return sidebarEl;\n  injectStyles();\n\n  const make = (tag: string, cls: string): HTMLElement => {\n    const el = document.createElement(tag);\n    el.className = cls;\n    return el as HTMLElement;\n  };\n\n  const root       = make('aside', 'tfs');\n  const greetingEl = make('div',   'tfs__greeting');\n  const meetingEl  = make('div',   'tfs__meeting');\n  const inboxEl    = make('div',   'tfs__section');\n  const stocksEl   = make('div',   'tfs__section');\n  const ciEl       = make('div',   'tfs__section');\n  const briefingEl = make('div',   'tfs__section');\n\n  root.append(greetingEl, meetingEl, inboxEl, stocksEl, ciEl, briefingEl);\n  refs = { root, greetingEl, meetingEl, inboxEl, stocksEl, ciEl, briefingEl };\n  sidebarEl = root;\n  return root;\n}\n\n\u002F\u002F ── Updater ───────────────────────────────────────────────────────────────────\n\nconst BRIEFING_LIMIT = 200;\n\nexport function updateTodayFocus(data: FocusData): void {\n  if (!refs) createTodayFocusSidebar();\n  const r = refs!;\n\n  \u002F\u002F Greeting\n  r.greetingEl.textContent = greeting(data.userName);\n\n  \u002F\u002F Next meeting\n  if (data.nextMeeting) {\n    r.meetingEl.textContent =\n      `Next: ${data.nextMeeting.title} — ${formatCountdown(data.nextMeeting.startsInMinutes)}`;\n    r.meetingEl.hidden = false;\n  } else {\n    r.meetingEl.hidden = true;\n  }\n\n  \u002F\u002F Inbox counts\n  const { email, slack, github } = data.inboxCounts;\n  r.inboxEl.innerHTML = `\n    \u003Cdiv class=\"tfs__label\">Inbox\u003C\u002Fdiv>\n    Email: ${email} &nbsp; Slack: ${slack} &nbsp; GitHub: ${github}`;\n\n  \u002F\u002F Stock alerts (caller should pre-filter >= 2%, but we guard here too)\n  const alerts = data.stockAlerts.filter(s => Math.abs(s.changePercent) >= 2);\n  r.stocksEl.innerHTML = alerts.length === 0\n    ? ''\n    : `\u003Cdiv class=\"tfs__label\">Stock Alerts\u003C\u002Fdiv>` +\n      alerts.map(s => {\n        const cls  = s.changePercent >= 0 ? 'tfs__alert-pos' : 'tfs__alert-neg';\n        const sign = s.changePercent >= 0 ? '+' : '';\n        return `\u003Cspan class=\"${cls}\">${s.symbol} ${sign}${s.changePercent.toFixed(1)}%\u003C\u002Fspan>`;\n      }).join(' &nbsp; ');\n\n  \u002F\u002F CI failures\n  r.ciEl.innerHTML = data.ciFailures.length === 0\n    ? ''\n    : `\u003Cdiv class=\"tfs__label\">CI Failures\u003C\u002Fdiv>` +\n      data.ciFailures\n        .map(f => `\u003Cdiv class=\"tfs__ci-fail\">${f.repo} \u002F ${f.branch}\u003C\u002Fdiv>`)\n        .join('');\n\n  \u002F\u002F AI briefing with truncate\u002Fexpand toggle\n  const text = data.aiBriefing;\n  if (text.length \u003C= BRIEFING_LIMIT) {\n    r.briefingEl.innerHTML =\n      `\u003Cdiv class=\"tfs__label\">Briefing\u003C\u002Fdiv>\u003Cdiv class=\"tfs__briefing\">${text}\u003C\u002Fdiv>`;\n  } else {\n    const short = text.slice(0, BRIEFING_LIMIT) + '…';\n    r.briefingEl.innerHTML = `\n      \u003Cdiv class=\"tfs__label\">Briefing\u003C\u002Fdiv>\n      \u003Cdiv class=\"tfs__briefing\"\n           data-full=\"${encodeURIComponent(text)}\"\n           data-short=\"${encodeURIComponent(short)}\"\n           data-expanded=\"false\">${short}\u003C\u002Fdiv>\n      \u003Cbutton class=\"tfs__toggle\" data-briefing-toggle>Show more\u003C\u002Fbutton>`;\n    r.briefingEl.querySelector('[data-briefing-toggle]')\n      ?.addEventListener('click', function (this: HTMLButtonElement) {\n        const div = r.briefingEl.querySelector\u003CHTMLElement>('[data-full]')!;\n        const expanded = div.dataset.expanded === 'true';\n        div.textContent = decodeURIComponent(\n          expanded ? div.dataset.short! : div.dataset.full!);\n        div.dataset.expanded = String(!expanded);\n        this.textContent = expanded ? 'Show more' : 'Show less';\n      });\n  }\n}\n```\n\n### Push-Update Checklist\n\n- [ ] Define `interface XData` (exported — callers need it)\n- [ ] Define `interface SectionRefs` (internal — not exported)\n- [ ] Declare module-level `let sidebarEl`, `let refs`, `let stylesInjected`\n- [ ] `injectStyles()` inserts one `\u003Cstyle>` tag, guarded by `stylesInjected`; set `style.dataset.owner` for DevTools visibility\n- [ ] `createXSidebar()` is idempotent: returns existing `sidebarEl` if already built\n- [ ] `createXSidebar()` populates `refs` with live node references\n- [ ] `updateX(data)` calls `createXSidebar()` defensively if `refs` is null\n- [ ] `updateX(data)` mutates only nodes in `refs` — never calls `document.querySelector`\n- [ ] Export `createXSidebar`, `updateX`, and `XData` interface; keep `SectionRefs` module-private\n\n### Barrel File Wiring\n\nAfter creating a push-update sidebar, register it in both barrel files:\n\n```typescript\n\u002F\u002F src\u002Fcomponents\u002Findex.ts\nexport { createTodayFocusSidebar, updateTodayFocus } from '.\u002FTodayFocusSidebar';\nexport type { FocusData } from '.\u002FTodayFocusSidebar';\n\n\u002F\u002F src\u002Findex.ts\nexport * from '.\u002Fcomponents';\n```\n\n---\n\n## Part 3 — Sparkline Utility\n\nUsed by both patterns for inline SVG sparklines:\n\n```typescript\n\u002F\u002F src\u002Futils\u002Fsparkline.ts\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## Quick-Reference Decision Tree\n\n```\nNeed a new dashboard component?\n│\n├─ Will it fetch its own data (polling \u002F one-shot)?\n│   └─ YES → extend Panel (Part 1)\n│             • constructor → super() → loadState() → fetchData() → setInterval\n│             • fetchData() → resetRetry() → fetchWithRetry() → render() → saveState()\n│             • destroy() → clearInterval → super.destroy()\n│\n└─ Will data be pushed from outside?\n    └─ YES → functional push-update module (Part 2)\n              • createXSidebar() — idempotent, builds DOM, fills SectionRefs\n              • updateX(data)    — mutates only SectionRefs nodes\n              • injectStyles()   — guarded, runs once\n              • export createX, updateX, XData; keep SectionRefs private\n```\n","# Panel & Push-Update Sidebar Patterns\n\nTwo complementary patterns for building dashboard UI in **vanilla TypeScript** (no framework, no JSX):\n\n| Pattern | Use when… |\n|---|---|\n| **Panel class** (extends `Panel`) | The component fetches its own data on a timer |\n| **Push-update sidebar module** | Data arrives from outside (caller pushes it in) |\n\n---\n\n## Part 1 — Panel Class Pattern\n\n### Architecture Overview\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\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  \u002F\u002F --- Retry state (reset before each logical fetch sequence) ---\n  private retryAttempts = 0;\n  private maxRetries = 3;\n  private retryDelay = 1000; \u002F\u002F ms; doubles on each attempt\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  \u002F\u002F ----------------------------------------------------------------\n  \u002F\u002F Public API\n  \u002F\u002F ----------------------------------------------------------------\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]')\n        ?.addEventListener('click', onRetry);\n    }\n  }\n\n  public setContent(html: string): void { this.content.innerHTML = html; }\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  public destroy(): void { this.element.remove(); }\n\n  \u002F\u002F ----------------------------------------------------------------\n  \u002F\u002F Protected API — available in subclasses\n  \u002F\u002F ----------------------------------------------------------------\n\n  protected setFetching(v: boolean): void { this._fetching = v; }\n  protected get isFetching(): boolean { return this._fetching; }\n\n  \u002F**\n   * Fetch a URL with exponential-backoff retry.\n   * Call resetRetry() before each new fetch sequence.\n   *\u002F\n  protected async fetchWithRetry(url: string): Promise\u003Cunknown> {\n    while (this.retryAttempts \u003C this.maxRetries) {\n      try {\n        const res = await fetch(url);\n        if (!res.ok) throw new Error(`HTTP ${res.status}`);\n        return await res.json();\n      } catch (err: unknown) {\n        this.retryAttempts++;\n        if (this.retryAttempts >= this.maxRetries) {\n          const msg = err instanceof Error ? err.message : String(err);\n          throw new Error(`Failed after ${this.maxRetries} attempts: ${msg}`);\n        }\n        await new Promise(r => setTimeout(r, this.retryDelay));\n        this.retryDelay *= 2;\n      }\n    }\n  }\n\n  \u002F** Reset retry counters before a fresh fetch sequence. *\u002F\n  protected resetRetry(): void {\n    this.retryAttempts = 0;\n    this.retryDelay = 1000;\n  }\n\n  \u002F\u002F ----------------------------------------------------------------\n  \u002F\u002F State persistence (localStorage)\n  \u002F\u002F ----------------------------------------------------------------\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 raw = localStorage.getItem(`panelState_${this.panelId}`);\n    if (!raw) return;\n    const { isExpanded, width, height } = JSON.parse(raw) as {\n      isExpanded: boolean; width: string; height: string;\n    };\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### Protected API Reference\n\n| Member \u002F Method | Type | Description |\n|---|---|---|\n| `element` | `HTMLElement` | Outer container div (`.panel`) |\n| `header` | `HTMLElement` | Header bar — append extra controls here |\n| `content` | `HTMLElement` | Scrollable content area |\n| `countEl` | `HTMLElement \\| null` | Count badge, or `null` if `showCount` not set |\n| `panelId` | `string` | The `id` from `PanelOptions` |\n| `isFetching` | `boolean` getter | `true` while an async fetch is in progress |\n| `setFetching(v)` | `void` | Set\u002Fclear the fetching guard |\n| `showLoading(msg?)` | `void` | Replace content with a spinner |\n| `showError(msg?, onRetry?)` | `void` | Replace content with error + optional retry button |\n| `setContent(html)` | `void` | Set raw HTML into the content area |\n| `setCount(n)` | `void` | Update count badge (no-op if `countEl` is null) |\n| `fetchWithRetry(url)` | `Promise\u003Cunknown>` | Fetch with exponential-backoff retry (3 attempts) |\n| `resetRetry()` | `void` | Reset retry counters before a new fetch sequence |\n| `saveState()` | `void` | Persist expanded\u002Fsize state to localStorage |\n| `loadState()` | `void` | Restore state from localStorage |\n\n### Creating a Concrete Panel (Example: StockPanel)\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.loadState();          \u002F\u002F restore saved size\u002Fcollapsed state\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    this.resetRetry();         \u002F\u002F start a fresh retry sequence\n    try {\n      const quotes = await this.fetchWithRetry('\u002Fapi\u002Fstocks') as StockQuote[];\n      this.render(quotes);\n      this.setCount(quotes.length);\n      this.saveState();\n    } catch (err: unknown) {\n      const msg = err instanceof Error ? err.message : 'Unknown error';\n      this.showError(`Failed to load stock data: ${msg}`, () => 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        ${miniSparkline(q.sparkline, q.change)}\n      \u003C\u002Fdiv>`).join('');\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 for Self-Fetching Panels\n\n1. **Constructor** → `super()` → `loadState()` → initial `fetchData()` → start refresh timer\n2. **fetchData()** → `isFetching` guard → `resetRetry()` → `fetchWithRetry()` → `render()` + `saveState()`\n3. **render()** builds HTML strings → `this.setContent(html)`\n4. **destroy()** clears timers, calls `super.destroy()`\n5. Use `showLoading()` during initial load (auto-called in constructor)\n6. Use `showError(msg, retryFn)` on failure; retryFn must call `fetchData()` (which calls `resetRetry()`)\n\n---\n\n## Part 2 — Push-Update Sidebar Pattern\n\nUse this pattern when the component **does not fetch data itself** — instead it receives data pushed by an external caller (e.g. a WebSocket handler, a store subscription, or a parent orchestrator).\n\n### When to use this pattern vs. Panel class\n\n```\nSelf-fetching?  → Panel class (Part 1)\nData pushed in? → Push-update sidebar module (Part 2)\n```\n\n### Module Structure\n\nA push-update sidebar is a **plain TypeScript module** (not a class) with:\n\n| Export | Purpose |\n|---|---|\n| `createXSidebar(): HTMLElement` | Build and return the root element (idempotent singleton) |\n| `updateX(data: XData): void` | Re-render only the sections that changed |\n| `interface XData` | The data shape the caller must provide |\n\nInternally the module uses:\n- A **module-level singleton** `let sidebarEl: HTMLElement | null = null`\n- A **`SectionRefs` interface** caching live DOM node references to avoid repeated `querySelector` calls\n- A **guarded `injectStyles()`** function that inserts a `\u003Cstyle>` tag exactly once\n\n### Skeleton\n\n```typescript\n\u002F\u002F src\u002Fcomponents\u002FFooSidebar.ts\n\n\u002F\u002F ── Types ────────────────────────────────────────────────────────────────────\n\nexport interface FooData {\n  title: string;\n  items: { id: string; label: string; value: number }[];\n  lastUpdated: Date;\n}\n\n\u002F\u002F ── DOM node cache ────────────────────────────────────────────────────────────\n\ninterface SectionRefs {\n  root:      HTMLElement;\n  titleEl:   HTMLElement;\n  listEl:    HTMLElement;\n  footerEl:  HTMLElement;\n}\n\n\u002F\u002F ── Singleton state ───────────────────────────────────────────────────────────\n\nlet sidebarEl: HTMLElement | null = null;\nlet refs: SectionRefs | null = null;\nlet stylesInjected = false;\n\n\u002F\u002F ── CSS injection ─────────────────────────────────────────────────────────────\n\nfunction injectStyles(): void {\n  if (stylesInjected) return;            \u002F\u002F guard: run exactly once\n  stylesInjected = true;\n  const style = document.createElement('style');\n  style.dataset.owner = 'foo-sidebar';   \u002F\u002F easy to find in DevTools\n  style.textContent = `\n    .foo-sidebar { \u002F* … *\u002F }\n    .foo-sidebar__title { font-weight: 600; }\n    .foo-sidebar__list  { list-style: none; padding: 0; }\n    .foo-sidebar__footer { font-size: 0.75rem; color: var(--muted); }\n  `;\n  document.head.appendChild(style);\n}\n\n\u002F\u002F ── Builder ───────────────────────────────────────────────────────────────────\n\n\u002F**\n * Create (or return the existing) sidebar element.\n * Idempotent — safe to call multiple times; always returns the same node.\n *\u002F\nexport function createFooSidebar(): HTMLElement {\n  if (sidebarEl) return sidebarEl;       \u002F\u002F singleton guard\n\n  injectStyles();\n\n  const root = document.createElement('aside');\n  root.className = 'foo-sidebar';\n\n  const titleEl = document.createElement('h2');\n  titleEl.className = 'foo-sidebar__title';\n  root.appendChild(titleEl);\n\n  const listEl = document.createElement('ul');\n  listEl.className = 'foo-sidebar__list';\n  root.appendChild(listEl);\n\n  const footerEl = document.createElement('div');\n  footerEl.className = 'foo-sidebar__footer';\n  root.appendChild(footerEl);\n\n  \u002F\u002F Cache references — avoids querySelector on every update\n  refs = { root, titleEl, listEl, footerEl };\n  sidebarEl = root;\n  return root;\n}\n\n\u002F\u002F ── Updater ───────────────────────────────────────────────────────────────────\n\n\u002F**\n * Push new data into the sidebar.\n * Calls createFooSidebar() defensively if refs is not yet initialised.\n *\u002F\nexport function updateFoo(data: FooData): void {\n  if (!refs) createFooSidebar();\n  const r = refs!;\n\n  r.titleEl.textContent = data.title;\n\n  r.listEl.innerHTML = data.items\n    .map(item => `\n      \u003Cli class=\"foo-sidebar__item\" data-id=\"${item.id}\">\n        \u003Cspan class=\"foo-item-label\">${item.label}\u003C\u002Fspan>\n        \u003Cspan class=\"foo-item-value\">${item.value}\u003C\u002Fspan>\n      \u003C\u002Fli>`)\n    .join('');\n\n  r.footerEl.textContent =\n    `Updated ${data.lastUpdated.toLocaleTimeString()}`;\n}\n```\n\n### Real-World Example: TodayFocusSidebar\n\nA sidebar that summarises the user's day — greeting, meeting countdown, inbox counts, stock alerts, CI failures, and an AI briefing with truncate\u002Fexpand toggle. Data is pushed in from an external orchestrator.\n\n```typescript\n\u002F\u002F src\u002Fcomponents\u002FTodayFocusSidebar.ts\n\nexport interface FocusData {\n  userName: string;\n  nextMeeting: { title: string; startsInMinutes: number } | null;\n  inboxCounts: { email: number; slack: number; github: number };\n  stockAlerts: { symbol: string; changePercent: number }[]; \u002F\u002F pre-filtered >= 2%\n  ciFailures: { repo: string; branch: string }[];\n  aiBriefing: string; \u002F\u002F may be long — sidebar truncates with toggle\n}\n\ninterface SectionRefs {\n  root:       HTMLElement;\n  greetingEl: HTMLElement;\n  meetingEl:  HTMLElement;\n  inboxEl:    HTMLElement;\n  stocksEl:   HTMLElement;\n  ciEl:       HTMLElement;\n  briefingEl: HTMLElement;\n}\n\nlet sidebarEl: HTMLElement | null = null;\nlet refs: SectionRefs | null = null;\nlet stylesInjected = false;\n\n\u002F\u002F ── Helpers ───────────────────────────────────────────────────────────────────\n\nfunction greeting(name: string): string {\n  const h = new Date().getHours();\n  const salutation = h \u003C 12 ? 'Good morning' : h \u003C 17 ? 'Good afternoon' : 'Good evening';\n  return `${salutation}, ${name}`;\n}\n\nfunction formatCountdown(minutes: number): string {\n  if (minutes \u003C= 0) return 'Now';\n  if (minutes \u003C 60) return `in ${minutes}m`;\n  return `in ${Math.floor(minutes \u002F 60)}h ${minutes % 60}m`;\n}\n\n\u002F\u002F ── CSS ───────────────────────────────────────────────────────────────────────\n\nfunction injectStyles(): void {\n  if (stylesInjected) return;\n  stylesInjected = true;\n  const s = document.createElement('style');\n  s.dataset.owner = 'today-focus-sidebar';\n  s.textContent = `\n    .tfs { display:flex; flex-direction:column; gap:12px; padding:16px;\n           background:var(--bg-surface, #1e1e2e); color:var(--fg, #cdd6f4);\n           border-radius:8px; font-family:inherit; }\n    .tfs__greeting  { font-size:1.1rem; font-weight:600; }\n    .tfs__meeting   { font-size:0.85rem; color:var(--yellow, #f9e2af); }\n    .tfs__section   { font-size:0.85rem; }\n    .tfs__label     { font-size:0.7rem; text-transform:uppercase;\n                      letter-spacing:.06em; color:var(--muted, #6c7086);\n                      margin-bottom:4px; }\n    .tfs__briefing  { font-size:0.82rem; line-height:1.5; }\n    .tfs__toggle    { background:none; border:none; color:var(--blue, #89b4fa);\n                      cursor:pointer; font-size:0.8rem; padding:2px 0; }\n    .tfs__alert-pos { color:var(--green, #a6e3a1); }\n    .tfs__alert-neg { color:var(--red,   #f38ba8); }\n    .tfs__ci-fail   { color:var(--red,   #f38ba8); }\n  `;\n  document.head.appendChild(s);\n}\n\n\u002F\u002F ── Builder ───────────────────────────────────────────────────────────────────\n\nexport function createTodayFocusSidebar(): HTMLElement {\n  if (sidebarEl) return sidebarEl;\n  injectStyles();\n\n  const make = (tag: string, cls: string): HTMLElement => {\n    const el = document.createElement(tag);\n    el.className = cls;\n    return el as HTMLElement;\n  };\n\n  const root       = make('aside', 'tfs');\n  const greetingEl = make('div',   'tfs__greeting');\n  const meetingEl  = make('div',   'tfs__meeting');\n  const inboxEl    = make('div',   'tfs__section');\n  const stocksEl   = make('div',   'tfs__section');\n  const ciEl       = make('div',   'tfs__section');\n  const briefingEl = make('div',   'tfs__section');\n\n  root.append(greetingEl, meetingEl, inboxEl, stocksEl, ciEl, briefingEl);\n  refs = { root, greetingEl, meetingEl, inboxEl, stocksEl, ciEl, briefingEl };\n  sidebarEl = root;\n  return root;\n}\n\n\u002F\u002F ── Updater ───────────────────────────────────────────────────────────────────\n\nconst BRIEFING_LIMIT = 200;\n\nexport function updateTodayFocus(data: FocusData): void {\n  if (!refs) createTodayFocusSidebar();\n  const r = refs!;\n\n  \u002F\u002F Greeting\n  r.greetingEl.textContent = greeting(data.userName);\n\n  \u002F\u002F Next meeting\n  if (data.nextMeeting) {\n    r.meetingEl.textContent =\n      `Next: ${data.nextMeeting.title} — ${formatCountdown(data.nextMeeting.startsInMinutes)}`;\n    r.meetingEl.hidden = false;\n  } else {\n    r.meetingEl.hidden = true;\n  }\n\n  \u002F\u002F Inbox counts\n  const { email, slack, github } = data.inboxCounts;\n  r.inboxEl.innerHTML = `\n    \u003Cdiv class=\"tfs__label\">Inbox\u003C\u002Fdiv>\n    Email: ${email} &nbsp; Slack: ${slack} &nbsp; GitHub: ${github}`;\n\n  \u002F\u002F Stock alerts (caller should pre-filter >= 2%, but we guard here too)\n  const alerts = data.stockAlerts.filter(s => Math.abs(s.changePercent) >= 2);\n  r.stocksEl.innerHTML = alerts.length === 0\n    ? ''\n    : `\u003Cdiv class=\"tfs__label\">Stock Alerts\u003C\u002Fdiv>` +\n      alerts.map(s => {\n        const cls  = s.changePercent >= 0 ? 'tfs__alert-pos' : 'tfs__alert-neg';\n        const sign = s.changePercent >= 0 ? '+' : '';\n        return `\u003Cspan class=\"${cls}\">${s.symbol} ${sign}${s.changePercent.toFixed(1)}%\u003C\u002Fspan>`;\n      }).join(' &nbsp; ');\n\n  \u002F\u002F CI failures\n  r.ciEl.innerHTML = data.ciFailures.length === 0\n    ? ''\n    : `\u003Cdiv class=\"tfs__label\">CI Failures\u003C\u002Fdiv>` +\n      data.ciFailures\n        .map(f => `\u003Cdiv class=\"tfs__ci-fail\">${f.repo} \u002F ${f.branch}\u003C\u002Fdiv>`)\n        .join('');\n\n  \u002F\u002F AI briefing with truncate\u002Fexpand toggle\n  const text = data.aiBriefing;\n  if (text.length \u003C= BRIEFING_LIMIT) {\n    r.briefingEl.innerHTML =\n      `\u003Cdiv class=\"tfs__label\">Briefing\u003C\u002Fdiv>\u003Cdiv class=\"tfs__briefing\">${text}\u003C\u002Fdiv>`;\n  } else {\n    const short = text.slice(0, BRIEFING_LIMIT) + '…';\n    r.briefingEl.innerHTML = `\n      \u003Cdiv class=\"tfs__label\">Briefing\u003C\u002Fdiv>\n      \u003Cdiv class=\"tfs__briefing\"\n           data-full=\"${encodeURIComponent(text)}\"\n           data-short=\"${encodeURIComponent(short)}\"\n           data-expanded=\"false\">${short}\u003C\u002Fdiv>\n      \u003Cbutton class=\"tfs__toggle\" data-briefing-toggle>Show more\u003C\u002Fbutton>`;\n    r.briefingEl.querySelector('[data-briefing-toggle]')\n      ?.addEventListener('click', function (this: HTMLButtonElement) {\n        const div = r.briefingEl.querySelector\u003CHTMLElement>('[data-full]')!;\n        const expanded = div.dataset.expanded === 'true';\n        div.textContent = decodeURIComponent(\n          expanded ? div.dataset.short! : div.dataset.full!);\n        div.dataset.expanded = String(!expanded);\n        this.textContent = expanded ? 'Show more' : 'Show less';\n      });\n  }\n}\n```\n\n### Push-Update Checklist\n\n- [ ] Define `interface XData` (exported — callers need it)\n- [ ] Define `interface SectionRefs` (internal — not exported)\n- [ ] Declare module-level `let sidebarEl`, `let refs`, `let stylesInjected`\n- [ ] `injectStyles()` inserts one `\u003Cstyle>` tag, guarded by `stylesInjected`; set `style.dataset.owner` for DevTools visibility\n- [ ] `createXSidebar()` is idempotent: returns existing `sidebarEl` if already built\n- [ ] `createXSidebar()` populates `refs` with live node references\n- [ ] `updateX(data)` calls `createXSidebar()` defensively if `refs` is null\n- [ ] `updateX(data)` mutates only nodes in `refs` — never calls `document.querySelector`\n- [ ] Export `createXSidebar`, `updateX`, and `XData` interface; keep `SectionRefs` module-private\n\n### Barrel File Wiring\n\nAfter creating a push-update sidebar, register it in both barrel files:\n\n```typescript\n\u002F\u002F src\u002Fcomponents\u002Findex.ts\nexport { createTodayFocusSidebar, updateTodayFocus } from '.\u002FTodayFocusSidebar';\nexport type { FocusData } from '.\u002FTodayFocusSidebar';\n\n\u002F\u002F src\u002Findex.ts\nexport * from '.\u002Fcomponents';\n```\n\n---\n\n## Part 3 — Sparkline Utility\n\nUsed by both patterns for inline SVG sparklines:\n\n```typescript\n\u002F\u002F src\u002Futils\u002Fsparkline.ts\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## Quick-Reference Decision Tree\n\n```\nNeed a new dashboard component?\n│\n├─ Will it fetch its own data (polling \u002F one-shot)?\n│   └─ YES → extend Panel (Part 1)\n│             • constructor → super() → loadState() → fetchData() → setInterval\n│             • fetchData() → resetRetry() → fetchWithRetry() → render() → saveState()\n│             • destroy() → clearInterval → super.destroy()\n│\n└─ Will data be pushed from outside?\n    └─ YES → functional push-update module (Part 2)\n              • createXSidebar() — idempotent, builds DOM, fills SectionRefs\n              • updateX(data)    — mutates only SectionRefs nodes\n              • injectStyles()   — guarded, runs once\n              • export createX, updateX, XData; keep SectionRefs private\n```\n",{"name":5,"description":7},"main","6b84b0689ca0d9e7b1e4061188ff6b60758e0f8a","openspace\u002Fexamples\u002Fmy-daily-monitor\u002Fskills\u002Fpanel-component-with-push-sidebar",944,"https:\u002F\u002Fgithub.com\u002FHKUDS\u002FAgentPilot","https:\u002F\u002Fgithub.com\u002FHKUDS","https:\u002F\u002Fsites.google.com\u002Fview\u002Fchaoh","2026-11-12 22:26:39",{"source":8,"skillName":5,"commands":53,"prompt":63,"zipAvailable":64},[54,57,60],{"tool":55,"command":56},"npx","npx skills add HKUDS\u002FAgentPilot --skill panel-component-with-push-sidebar",{"tool":58,"command":59},"bunx","bunx skills add HKUDS\u002FAgentPilot --skill panel-component-with-push-sidebar",{"tool":61,"command":62},"pnpm","pnpm dlx skills add HKUDS\u002FAgentPilot --skill panel-component-with-push-sidebar","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FHKUDS\u002FAgentPilot\u002Fblob\u002Fmain\u002Fopenspace\u002Fexamples\u002Fmy-daily-monitor\u002Fskills\u002Fpanel-component-with-push-sidebar\u002FSKILL.md",true,[66],{"path":67,"resourceType":68,"resourceTypeDesc":69,"sizeBytes":70,"sourceHtmlUrl":71},".skill_id","OTHER","其他",43,"https:\u002F\u002Fgithub.com\u002FHKUDS\u002FAgentPilot\u002Fblob\u002Fmain\u002Fopenspace\u002Fexamples\u002Fmy-daily-monitor\u002Fskills\u002Fpanel-component-with-push-sidebar\u002F.skill_id",[73,92,111,136,160,182],{"skillNo":74,"name":75,"nameZh":6,"description":76,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":77,"categories":78,"keywords":79,"publishedAt":39},"01M6HYB297NDABRERJRVG0K8R0","agentpilot","Set up AgentPilot and use its single entry to prepare missing inputs and run configured RSI experiments. Use when the user requests AgentPilot installation or work with AgentPilot.","https:\u002F\u002Fgithub.com\u002FHKUDS\u002FAgentPilot\u002Fblob\u002Fmain\u002Fplugins\u002Fagentpilot\u002Fskills\u002Fagentpilot\u002FSKILL.md",[],[75,80,81,21,82,83,84,85,86,87,88,89,90,91],"prepare","requests","missing","installation","rsi","up","use","user","work","SET","run","experiments",{"skillNo":93,"name":94,"nameZh":6,"description":95,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":96,"categories":97,"keywords":98,"publishedAt":39},"01M6HYAYWXTTE1J7DJM0MFNQ4H","remember","Review auto-memory entries and propose promotions to OPENSPACE.md, OPENSPACE.local.md, or retained auto-memory topics; detect duplicates, stale facts, conflicts, and ambiguous entries before making changes.","https:\u002F\u002Fgithub.com\u002FHKUDS\u002FAgentPilot\u002Fblob\u002Fmain\u002Fopenspace\u002Fopenspace\u002Fskills\u002Fremember\u002FSKILL.md",[],[94,99,100,101,102,103,104,105,106,107,108,109,110],"memory","review","auto","openspace","changes","facts","detect","entries","local","conflicts","stale","duplicates",{"skillNo":112,"name":113,"nameZh":6,"description":114,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":115,"categories":116,"keywords":122,"publishedAt":39},"01M6HYAVMPM4SBDV60R2B5HPV8","skill-discovery","Search reusable OpenSpace skills locally, and browse cloud packages step by step when a cloud skill may help. Reusing proven skills saves tokens, improves reliability, and extends your capabilities beyond built-in tools.","https:\u002F\u002Fgithub.com\u002FHKUDS\u002FAgentPilot\u002Fblob\u002Fmain\u002Fopenspace\u002Fopenspace\u002Fhost_skills\u002Fskill-discovery\u002FSKILL.md",[117],{"categoryNo":118,"categoryName":119,"taxonomyType":120,"taxonomyTypeDesc":121},"01JBSEEDCAT000000000000023","Skill与智能体开发","SCENARIO","使用场景",[123,124,125,102,126,127,128,129,130,131,132,133,134,135],"skill discovery","discovery","reusable","step by step","tokens","packages","help","cloud","reliability","capabilities","browse","search","Tools",{"skillNo":137,"name":138,"nameZh":6,"description":139,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":140,"categories":141,"keywords":143,"publishedAt":39},"01M6HYAR811B3RB0M50RBEDGN6","delegate-task","Delegate tasks to OpenSpace — a full-stack autonomous worker for coding, DevOps, web research, and desktop automation, backed by an extensive MCP tool and skill library. Skills auto-improve through use, reducing token consumption over time. A cloud community lets agents share and collectively evolve reusable skills.","https:\u002F\u002Fgithub.com\u002FHKUDS\u002FAgentPilot\u002Fblob\u002Fmain\u002Fopenspace\u002Fopenspace\u002Fhost_skills\u002Fdelegate-task\u002FSKILL.md",[142],{"categoryNo":118,"categoryName":119,"taxonomyType":120,"taxonomyTypeDesc":121},[144,145,146,102,147,148,149,150,151,125,101,86,152,153,154,155,156,157,158,159],"delegate","task","delegate task","time","improve","desktop automation","worker","community","autonomous","tool","stack","for","share","tasks","automation","MCP",{"skillNo":161,"name":162,"nameZh":6,"description":163,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":164,"categories":165,"keywords":166,"publishedAt":39},"01M6HYAM9FSGV6E52AYENDQXYH","write-special-chars-ts-check","Workaround for write_file failures caused by special characters (apostrophes, backticks, template literals) using a Python heredoc script, plus a reliable TypeScript type-checking step that filters output to only the newly-written files to avoid being misled by pre-existing errors.","https:\u002F\u002Fgithub.com\u002FHKUDS\u002FAgentPilot\u002Fblob\u002Fmain\u002Fopenspace\u002Flegacy\u002Fv1\u002Fshowcase\u002Fskills\u002Fwrite-special-chars-ts-check\u002FSKILL.md",[],[167,168,169,170,171,172,173,174,175,176,38,177,178,179,155,180,181],"write special chars ts check","write","check","type","files","filters","only","template","file","python","output","Existing","type-checking","errors","script",{"skillNo":183,"name":184,"nameZh":6,"description":185,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":186,"categories":187,"keywords":188,"publishedAt":39},"01M6HYAH05HGV7SVWSVR8PJRQD","write-special-chars-readback","Workaround for write_file failures caused by special characters (apostrophes, backticks, template literals) using a Python heredoc script, with mandatory post-write verification via read_file and cleanup of \u002Ftmp helper scripts.","https:\u002F\u002Fgithub.com\u002FHKUDS\u002FAgentPilot\u002Fblob\u002Fmain\u002Fopenspace\u002Flegacy\u002Fv1\u002Fshowcase\u002Fskills\u002Fwrite-special-chars-readback\u002FSKILL.md",[],[189,190,168,21,155,181,191,192,193,194,195,174,175,196,197,176],"write special chars readback","readback","helper","post","via","scripts","read","verification","cleanup"]