[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6KKFTW99GJCY7KKT83GK6XS":3,"skill-same:01M6KKFTW99GJCY7KKT83GK6XS":81},{"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":22,"publishedAt":43,"linkOnly":44,"markdownContent":45,"markdownBody":46,"frontMatter":47,"refName":48,"commitSha":49,"skillDirectory":50,"forksCount":13,"repositoryHtmlUrl":51,"repositoryHomepageUrl":6,"ownerHtmlUrl":52,"ownerBlogUrl":6,"ownerDescription":53,"updatedAt":54,"install":55,"resources":68},"01M6KKFTW99GJCY7KKT83GK6XS","panel-component-xss-safe",null,"Create a dashboard panel component using vanilla TypeScript DOM API, following the worldmonitor Panel architecture. Panels have a header with title\u002Fcount, scrollable content area, loading\u002Ferror states, and resize handles. Includes XSS-safe rendering pattern with esc() helper for safely interpolating untrusted external API data into innerHTML.","AG064\u002FOpenSpace","AG064","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F184930299?v=4","01M6KHVFG7TB73NHX3RDYSTMH2","01M6KHVFMM7XA2PZA9Z83PHS3V",0,"MIT","https:\u002F\u002Fgithub.com\u002FAG064\u002FOpenSpace\u002Fblob\u002Fmain\u002Fshowcase\u002Fskills\u002Fpanel-component-xss-safe\u002FSKILL.md",[17],{"categoryNo":18,"categoryName":19,"taxonomyType":20,"taxonomyTypeDesc":21},"01JBSEEDCAT000000000000033","数据分析师","PROFESSION","适用职业",[23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42],"panel component","component","panel component xss safe","xss","panel","safe","error","external api","for","dom","with","loading","states","helper","panels","worldmonitor","api","create","architecture","dashboard","2026-11-10 10:12:30",false,"---\nname: panel-component-xss-safe\ndescription: Create a dashboard panel component using vanilla TypeScript DOM API, following the worldmonitor Panel architecture. Panels have a header with title\u002Fcount, scrollable content area, loading\u002Ferror states, and resize handles. Includes XSS-safe rendering pattern with esc() helper for safely interpolating untrusted external API data into innerHTML.\n---\n\n# Panel Component Pattern (XSS-Safe)\n\nCreate dashboard panel components using **vanilla TypeScript** (no framework, no JSX). Each panel is a class extending a `Panel` base class.\n\n> **Security note:** Panels that consume external API data (calendar events, news feeds, stock names, user-supplied content, etc.) MUST escape all untrusted values before injecting them into `innerHTML`. Use the `esc()` helper documented below.\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## XSS-Safe Rendering: the `esc()` Helper\n\n**Always use `esc()` when interpolating untrusted data into an HTML string.**  \nUntrusted data includes anything from external APIs: event titles, locations, URLs, names, descriptions, symbols, etc.\n\nCreate `src\u002Futils\u002Fesc.ts`:\n\n```typescript\n\u002F**\n * Escapes a value for safe interpolation into an innerHTML string.\n * Converts &, \u003C, >, \", and ' to their HTML entity equivalents.\n *\n * Usage:\n *   this.setContent(`\u003Cdiv class=\"title\">${esc(item.title)}\u003C\u002Fdiv>`);\n *\n * Do NOT use for:\n *   - href\u002Fsrc attributes with user-controlled URLs — validate scheme instead\n *   - CSS values — use a separate sanitizer\n *\u002F\nexport function esc(value: unknown): string {\n  return String(value ?? '')\n    .replace(\u002F&\u002Fg, '&amp;')\n    .replace(\u002F\u003C\u002Fg, '&lt;')\n    .replace(\u002F>\u002Fg, '&gt;')\n    .replace(\u002F\"\u002Fg, '&quot;')\n    .replace(\u002F'\u002Fg, '&#39;');\n}\n```\n\n### When to use `esc()`\n\n| Data source | Safe? | Action |\n|---|---|---|\n| Hardcoded string literal in source | ✅ Safe | No escaping needed |\n| Enum \u002F controlled constant | ✅ Safe | No escaping needed |\n| External API string field (title, name, body…) | ❌ Unsafe | **Use `esc()`** |\n| User input \u002F localStorage value | ❌ Unsafe | **Use `esc()`** |\n| Number\u002Fboolean (rendered as text) | ✅ Safe | `String(n)` is fine |\n| URL from external API | ⚠️ Unsafe | Validate scheme + `esc()` |\n\n### URL Safety\n\nFor URLs from external sources, validate the scheme before injecting:\n\n```typescript\n\u002F** Returns the URL only if it uses http or https; otherwise returns '#'. *\u002F\nexport function safeUrl(raw: unknown): string {\n  const s = String(raw ?? '').trim();\n  return \u002F^https?:\\\u002F\\\u002F\u002Fi.test(s) ? s : '#';\n}\n```\n\nUsage: `\u003Ca href=\"${safeUrl(item.url)}\">${esc(item.title)}\u003C\u002Fa>`\n\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  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;  \u002F\u002F textContent is always safe\n    headerLeft.appendChild(title);\n    this.header.appendChild(headerLeft);\n\n    \u002F\u002F Count badge (optional)\n    if (options.showCount) {\n      this.countEl = document.createElement('span');\n      this.countEl.className = 'panel-count';\n      this.countEl.textContent = '0';\n      this.header.appendChild(this.countEl);\n    }\n\n    \u002F\u002F Content area\n    this.content = document.createElement('div');\n    this.content.className = 'panel-content';\n    this.content.id = `${options.id}Content`;\n\n    this.element.appendChild(this.header);\n    this.element.appendChild(this.content);\n    this.showLoading();\n  }\n\n  public getElement(): HTMLElement { return this.element; }\n\n  public showLoading(message = 'Loading...'): void {\n    \u002F\u002F message is a hardcoded string — no escaping needed here\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    \u002F\u002F message is a hardcoded string — no escaping needed here\n    this.content.innerHTML = `\n      \u003Cdiv class=\"panel-error-state\">\n        \u003Cdiv class=\"panel-error-msg\">${message}\u003C\u002Fdiv>\n        ${onRetry ? '\u003Cbutton class=\"panel-retry-btn\" data-panel-retry>Retry\u003C\u002Fbutton>' : ''}\n      \u003C\u002Fdiv>`;\n    if (onRetry) {\n      this.content.querySelector('[data-panel-retry]')?.addEventListener('click', onRetry);\n    }\n  }\n\n  public setContent(html: string): void {\n    this.content.innerHTML = html;\n  }\n\n  public setCount(count: number): void {\n    if (this.countEl) this.countEl.textContent = count.toString();\n  }\n\n  public show(): void { this.element.classList.remove('hidden'); }\n  public hide(): void { this.element.classList.add('hidden'); }\n\n  protected setFetching(v: boolean): void { this._fetching = v; }\n  protected get isFetching(): boolean { return this._fetching; }\n\n  public destroy(): void {\n    this.element.remove();\n  }\n}\n```\n\n---\n\n## Creating a Concrete Panel (Example: StockPanel — XSS-safe)\n\nImport `esc` and wrap every API-derived string field:\n\n```typescript\nimport { Panel } from '.\u002FPanel';\nimport { esc } from '..\u002Futils\u002Fesc';\n\ninterface StockQuote {\n  symbol: string;\n  name: string;\n  price: number | null;\n  change: number | null;\n  sparkline?: number[];\n}\n\nexport class StockPanel extends Panel {\n  private refreshTimer: ReturnType\u003Ctypeof setInterval> | null = null;\n\n  constructor() {\n    super({ id: 'stocks', title: 'Stock Market', showCount: true });\n    this.fetchData();\n    this.refreshTimer = setInterval(() => this.fetchData(), 60_000);\n  }\n\n  private async fetchData(): Promise\u003Cvoid> {\n    if (this.isFetching) return;\n    this.setFetching(true);\n    try {\n      const quotes = await fetchStockQuotes(); \u002F\u002F from data-service\n      this.render(quotes);\n      this.setCount(quotes.length);\n    } catch (err) {\n      this.showError('Failed to load stock data', () => this.fetchData());\n    } finally {\n      this.setFetching(false);\n    }\n  }\n\n  private render(quotes: StockQuote[]): void {\n    const rows = quotes.map(q => `\n      \u003Cdiv class=\"stock-row\">\n        \u003Cspan class=\"stock-symbol\">${esc(q.symbol)}\u003C\u002Fspan>\n        \u003Cspan class=\"stock-name\">${esc(q.name)}\u003C\u002Fspan>\n        \u003Cspan class=\"stock-price\">${q.price != null ? '$' + q.price.toFixed(2) : '&mdash;'}\u003C\u002Fspan>\n        \u003Cspan class=\"stock-change ${(q.change ?? 0) >= 0 ? 'positive' : 'negative'}\">\n          ${q.change != null ? (q.change >= 0 ? '+' : '') + q.change.toFixed(2) + '%' : '&mdash;'}\n        \u003C\u002Fspan>\n      \u003C\u002Fdiv>\n    `).join('');\n    \u002F\u002F                ^^^         ^^^\n    \u002F\u002F symbol and name come from an external API — always escape them.\n    \u002F\u002F price and change are numbers rendered via .toFixed() — safe without esc().\n\n    this.setContent(`\u003Cdiv class=\"stock-list\">${rows}\u003C\u002Fdiv>`);\n  }\n\n  public override destroy(): void {\n    if (this.refreshTimer) clearInterval(this.refreshTimer);\n    super.destroy();\n  }\n}\n```\n\n## Creating a Concrete Panel (Example: EventPanel — calendar\u002Fnews data)\n\nCalendar and news panels are highest-risk because titles, locations, and URLs all come from untrusted sources:\n\n```typescript\nimport { Panel } from '.\u002FPanel';\nimport { esc, safeUrl } from '..\u002Futils\u002Fesc';\n\ninterface CalendarEvent {\n  id: string;\n  title: string;       \u002F\u002F untrusted — user-created content\n  location?: string;   \u002F\u002F untrusted\n  url?: string;        \u002F\u002F untrusted — must validate scheme\n  startTime: Date;\n}\n\nexport class SchedulePanel extends Panel {\n  private refreshTimer: ReturnType\u003Ctypeof setInterval> | null = null;\n\n  constructor() {\n    super({ id: 'schedule', title: \"Today's Schedule\", showCount: true });\n    this.fetchData();\n    this.refreshTimer = setInterval(() => this.fetchData(), 5 * 60_000);\n  }\n\n  private async fetchData(): Promise\u003Cvoid> {\n    if (this.isFetching) return;\n    this.setFetching(true);\n    try {\n      const events = await fetchCalendarEvents();\n      this.render(events);\n      this.setCount(events.length);\n    } catch (err) {\n      this.showError('Failed to load calendar', () => this.fetchData());\n    } finally {\n      this.setFetching(false);\n    }\n  }\n\n  private render(events: CalendarEvent[]): void {\n    if (events.length === 0) {\n      this.setContent('\u003Cdiv class=\"schedule-empty\">No events today\u003C\u002Fdiv>');\n      return;\n    }\n\n    const rows = events.map(ev => `\n      \u003Cdiv class=\"schedule-row\">\n        \u003Cspan class=\"schedule-time\">${esc(formatTime(ev.startTime))}\u003C\u002Fspan>\n        \u003Cspan class=\"schedule-title\">\n          ${ev.url\n            ? `\u003Ca href=\"${safeUrl(ev.url)}\" target=\"_blank\" rel=\"noopener noreferrer\">${esc(ev.title)}\u003C\u002Fa>`\n            : esc(ev.title)\n          }\n        \u003C\u002Fspan>\n        ${ev.location ? `\u003Cspan class=\"schedule-location\">${esc(ev.location)}\u003C\u002Fspan>` : ''}\n      \u003C\u002Fdiv>\n    `).join('');\n    \u002F\u002F              ^^^              ^^^              ^^^\n    \u002F\u002F title, location, url — ALL from external API, ALL escaped.\n    \u002F\u002F safeUrl() prevents javascript: \u002F data: scheme injection in href.\n\n    this.setContent(`\u003Cdiv class=\"schedule-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---\n\n## Key Patterns\n\n1. **Constructor** calls `super()` with panel config, then triggers initial data fetch\n2. **fetchData()** is async, uses `isFetching` guard, shows error on failure with retry\n3. **render()** builds HTML strings with `esc()` around every API-derived string, then calls `this.setContent(html)`\n4. **destroy()** cleans up timers and event listeners\n5. Use `showLoading()` during initial load (auto-called in constructor)\n6. Use `showError(msg, retryFn)` on failure — `msg` should be a hardcoded string, not API data\n7. **Import `esc` from `..\u002Futils\u002Fesc`** in every panel that consumes external data\n8. Numbers and booleans rendered via `.toFixed()` \u002F `.toString()` \u002F template arithmetic are safe — no `esc()` needed\n9. Use `textContent` instead of `innerHTML` for single text nodes when convenient — it is always safe\n\n## Sparkline Utility\n\nSparklines use computed numbers only — no escaping needed:\n\n```typescript\nexport function miniSparkline(data: number[] | undefined, change: number | null, w = 50, h = 16): string {\n  if (!data || data.length \u003C 2) return '';\n  const min = Math.min(...data);\n  const max = Math.max(...data);\n  const range = max - min || 1;\n  const color = change != null && change >= 0 ? 'var(--green)' : 'var(--red)';\n  const points = data.map((v, i) => {\n    const x = (i \u002F (data.length - 1)) * w;\n    const y = h - ((v - min) \u002F range) * (h - 2) - 1;\n    return `${x.toFixed(1)},${y.toFixed(1)}`;\n  }).join(' ');\n  return `\u003Csvg width=\"${w}\" height=\"${h}\" viewBox=\"0 0 ${w} ${h}\">\u003Cpolyline points=\"${points}\" fill=\"none\" stroke=\"${color}\" stroke-width=\"1.2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"\u002F>\u003C\u002Fsvg>`;\n}\n```\n\n---\n\n## Checklist Before Submitting a Panel\n\n- [ ] Every `string` field from an external API is wrapped in `esc()` before HTML interpolation\n- [ ] Every URL from an external API is passed through `safeUrl()` before use in `href`\u002F`src`\n- [ ] `showError()` is only called with hardcoded messages (never raw API error bodies)\n- [ ] `esc` and `safeUrl` are imported from `src\u002Futils\u002Fesc`\n- [ ] Numbers \u002F computed values rendered with `.toFixed()` or arithmetic are left unwrapped (they cannot contain HTML)\n","# Panel Component Pattern (XSS-Safe)\n\nCreate dashboard panel components using **vanilla TypeScript** (no framework, no JSX). Each panel is a class extending a `Panel` base class.\n\n> **Security note:** Panels that consume external API data (calendar events, news feeds, stock names, user-supplied content, etc.) MUST escape all untrusted values before injecting them into `innerHTML`. Use the `esc()` helper documented below.\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## XSS-Safe Rendering: the `esc()` Helper\n\n**Always use `esc()` when interpolating untrusted data into an HTML string.**  \nUntrusted data includes anything from external APIs: event titles, locations, URLs, names, descriptions, symbols, etc.\n\nCreate `src\u002Futils\u002Fesc.ts`:\n\n```typescript\n\u002F**\n * Escapes a value for safe interpolation into an innerHTML string.\n * Converts &, \u003C, >, \", and ' to their HTML entity equivalents.\n *\n * Usage:\n *   this.setContent(`\u003Cdiv class=\"title\">${esc(item.title)}\u003C\u002Fdiv>`);\n *\n * Do NOT use for:\n *   - href\u002Fsrc attributes with user-controlled URLs — validate scheme instead\n *   - CSS values — use a separate sanitizer\n *\u002F\nexport function esc(value: unknown): string {\n  return String(value ?? '')\n    .replace(\u002F&\u002Fg, '&amp;')\n    .replace(\u002F\u003C\u002Fg, '&lt;')\n    .replace(\u002F>\u002Fg, '&gt;')\n    .replace(\u002F\"\u002Fg, '&quot;')\n    .replace(\u002F'\u002Fg, '&#39;');\n}\n```\n\n### When to use `esc()`\n\n| Data source | Safe? | Action |\n|---|---|---|\n| Hardcoded string literal in source | ✅ Safe | No escaping needed |\n| Enum \u002F controlled constant | ✅ Safe | No escaping needed |\n| External API string field (title, name, body…) | ❌ Unsafe | **Use `esc()`** |\n| User input \u002F localStorage value | ❌ Unsafe | **Use `esc()`** |\n| Number\u002Fboolean (rendered as text) | ✅ Safe | `String(n)` is fine |\n| URL from external API | ⚠️ Unsafe | Validate scheme + `esc()` |\n\n### URL Safety\n\nFor URLs from external sources, validate the scheme before injecting:\n\n```typescript\n\u002F** Returns the URL only if it uses http or https; otherwise returns '#'. *\u002F\nexport function safeUrl(raw: unknown): string {\n  const s = String(raw ?? '').trim();\n  return \u002F^https?:\\\u002F\\\u002F\u002Fi.test(s) ? s : '#';\n}\n```\n\nUsage: `\u003Ca href=\"${safeUrl(item.url)}\">${esc(item.title)}\u003C\u002Fa>`\n\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  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;  \u002F\u002F textContent is always safe\n    headerLeft.appendChild(title);\n    this.header.appendChild(headerLeft);\n\n    \u002F\u002F Count badge (optional)\n    if (options.showCount) {\n      this.countEl = document.createElement('span');\n      this.countEl.className = 'panel-count';\n      this.countEl.textContent = '0';\n      this.header.appendChild(this.countEl);\n    }\n\n    \u002F\u002F Content area\n    this.content = document.createElement('div');\n    this.content.className = 'panel-content';\n    this.content.id = `${options.id}Content`;\n\n    this.element.appendChild(this.header);\n    this.element.appendChild(this.content);\n    this.showLoading();\n  }\n\n  public getElement(): HTMLElement { return this.element; }\n\n  public showLoading(message = 'Loading...'): void {\n    \u002F\u002F message is a hardcoded string — no escaping needed here\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    \u002F\u002F message is a hardcoded string — no escaping needed here\n    this.content.innerHTML = `\n      \u003Cdiv class=\"panel-error-state\">\n        \u003Cdiv class=\"panel-error-msg\">${message}\u003C\u002Fdiv>\n        ${onRetry ? '\u003Cbutton class=\"panel-retry-btn\" data-panel-retry>Retry\u003C\u002Fbutton>' : ''}\n      \u003C\u002Fdiv>`;\n    if (onRetry) {\n      this.content.querySelector('[data-panel-retry]')?.addEventListener('click', onRetry);\n    }\n  }\n\n  public setContent(html: string): void {\n    this.content.innerHTML = html;\n  }\n\n  public setCount(count: number): void {\n    if (this.countEl) this.countEl.textContent = count.toString();\n  }\n\n  public show(): void { this.element.classList.remove('hidden'); }\n  public hide(): void { this.element.classList.add('hidden'); }\n\n  protected setFetching(v: boolean): void { this._fetching = v; }\n  protected get isFetching(): boolean { return this._fetching; }\n\n  public destroy(): void {\n    this.element.remove();\n  }\n}\n```\n\n---\n\n## Creating a Concrete Panel (Example: StockPanel — XSS-safe)\n\nImport `esc` and wrap every API-derived string field:\n\n```typescript\nimport { Panel } from '.\u002FPanel';\nimport { esc } from '..\u002Futils\u002Fesc';\n\ninterface StockQuote {\n  symbol: string;\n  name: string;\n  price: number | null;\n  change: number | null;\n  sparkline?: number[];\n}\n\nexport class StockPanel extends Panel {\n  private refreshTimer: ReturnType\u003Ctypeof setInterval> | null = null;\n\n  constructor() {\n    super({ id: 'stocks', title: 'Stock Market', showCount: true });\n    this.fetchData();\n    this.refreshTimer = setInterval(() => this.fetchData(), 60_000);\n  }\n\n  private async fetchData(): Promise\u003Cvoid> {\n    if (this.isFetching) return;\n    this.setFetching(true);\n    try {\n      const quotes = await fetchStockQuotes(); \u002F\u002F from data-service\n      this.render(quotes);\n      this.setCount(quotes.length);\n    } catch (err) {\n      this.showError('Failed to load stock data', () => this.fetchData());\n    } finally {\n      this.setFetching(false);\n    }\n  }\n\n  private render(quotes: StockQuote[]): void {\n    const rows = quotes.map(q => `\n      \u003Cdiv class=\"stock-row\">\n        \u003Cspan class=\"stock-symbol\">${esc(q.symbol)}\u003C\u002Fspan>\n        \u003Cspan class=\"stock-name\">${esc(q.name)}\u003C\u002Fspan>\n        \u003Cspan class=\"stock-price\">${q.price != null ? '$' + q.price.toFixed(2) : '&mdash;'}\u003C\u002Fspan>\n        \u003Cspan class=\"stock-change ${(q.change ?? 0) >= 0 ? 'positive' : 'negative'}\">\n          ${q.change != null ? (q.change >= 0 ? '+' : '') + q.change.toFixed(2) + '%' : '&mdash;'}\n        \u003C\u002Fspan>\n      \u003C\u002Fdiv>\n    `).join('');\n    \u002F\u002F                ^^^         ^^^\n    \u002F\u002F symbol and name come from an external API — always escape them.\n    \u002F\u002F price and change are numbers rendered via .toFixed() — safe without esc().\n\n    this.setContent(`\u003Cdiv class=\"stock-list\">${rows}\u003C\u002Fdiv>`);\n  }\n\n  public override destroy(): void {\n    if (this.refreshTimer) clearInterval(this.refreshTimer);\n    super.destroy();\n  }\n}\n```\n\n## Creating a Concrete Panel (Example: EventPanel — calendar\u002Fnews data)\n\nCalendar and news panels are highest-risk because titles, locations, and URLs all come from untrusted sources:\n\n```typescript\nimport { Panel } from '.\u002FPanel';\nimport { esc, safeUrl } from '..\u002Futils\u002Fesc';\n\ninterface CalendarEvent {\n  id: string;\n  title: string;       \u002F\u002F untrusted — user-created content\n  location?: string;   \u002F\u002F untrusted\n  url?: string;        \u002F\u002F untrusted — must validate scheme\n  startTime: Date;\n}\n\nexport class SchedulePanel extends Panel {\n  private refreshTimer: ReturnType\u003Ctypeof setInterval> | null = null;\n\n  constructor() {\n    super({ id: 'schedule', title: \"Today's Schedule\", showCount: true });\n    this.fetchData();\n    this.refreshTimer = setInterval(() => this.fetchData(), 5 * 60_000);\n  }\n\n  private async fetchData(): Promise\u003Cvoid> {\n    if (this.isFetching) return;\n    this.setFetching(true);\n    try {\n      const events = await fetchCalendarEvents();\n      this.render(events);\n      this.setCount(events.length);\n    } catch (err) {\n      this.showError('Failed to load calendar', () => this.fetchData());\n    } finally {\n      this.setFetching(false);\n    }\n  }\n\n  private render(events: CalendarEvent[]): void {\n    if (events.length === 0) {\n      this.setContent('\u003Cdiv class=\"schedule-empty\">No events today\u003C\u002Fdiv>');\n      return;\n    }\n\n    const rows = events.map(ev => `\n      \u003Cdiv class=\"schedule-row\">\n        \u003Cspan class=\"schedule-time\">${esc(formatTime(ev.startTime))}\u003C\u002Fspan>\n        \u003Cspan class=\"schedule-title\">\n          ${ev.url\n            ? `\u003Ca href=\"${safeUrl(ev.url)}\" target=\"_blank\" rel=\"noopener noreferrer\">${esc(ev.title)}\u003C\u002Fa>`\n            : esc(ev.title)\n          }\n        \u003C\u002Fspan>\n        ${ev.location ? `\u003Cspan class=\"schedule-location\">${esc(ev.location)}\u003C\u002Fspan>` : ''}\n      \u003C\u002Fdiv>\n    `).join('');\n    \u002F\u002F              ^^^              ^^^              ^^^\n    \u002F\u002F title, location, url — ALL from external API, ALL escaped.\n    \u002F\u002F safeUrl() prevents javascript: \u002F data: scheme injection in href.\n\n    this.setContent(`\u003Cdiv class=\"schedule-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---\n\n## Key Patterns\n\n1. **Constructor** calls `super()` with panel config, then triggers initial data fetch\n2. **fetchData()** is async, uses `isFetching` guard, shows error on failure with retry\n3. **render()** builds HTML strings with `esc()` around every API-derived string, then calls `this.setContent(html)`\n4. **destroy()** cleans up timers and event listeners\n5. Use `showLoading()` during initial load (auto-called in constructor)\n6. Use `showError(msg, retryFn)` on failure — `msg` should be a hardcoded string, not API data\n7. **Import `esc` from `..\u002Futils\u002Fesc`** in every panel that consumes external data\n8. Numbers and booleans rendered via `.toFixed()` \u002F `.toString()` \u002F template arithmetic are safe — no `esc()` needed\n9. Use `textContent` instead of `innerHTML` for single text nodes when convenient — it is always safe\n\n## Sparkline Utility\n\nSparklines use computed numbers only — no escaping needed:\n\n```typescript\nexport function miniSparkline(data: number[] | undefined, change: number | null, w = 50, h = 16): string {\n  if (!data || data.length \u003C 2) return '';\n  const min = Math.min(...data);\n  const max = Math.max(...data);\n  const range = max - min || 1;\n  const color = change != null && change >= 0 ? 'var(--green)' : 'var(--red)';\n  const points = data.map((v, i) => {\n    const x = (i \u002F (data.length - 1)) * w;\n    const y = h - ((v - min) \u002F range) * (h - 2) - 1;\n    return `${x.toFixed(1)},${y.toFixed(1)}`;\n  }).join(' ');\n  return `\u003Csvg width=\"${w}\" height=\"${h}\" viewBox=\"0 0 ${w} ${h}\">\u003Cpolyline points=\"${points}\" fill=\"none\" stroke=\"${color}\" stroke-width=\"1.2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"\u002F>\u003C\u002Fsvg>`;\n}\n```\n\n---\n\n## Checklist Before Submitting a Panel\n\n- [ ] Every `string` field from an external API is wrapped in `esc()` before HTML interpolation\n- [ ] Every URL from an external API is passed through `safeUrl()` before use in `href`\u002F`src`\n- [ ] `showError()` is only called with hardcoded messages (never raw API error bodies)\n- [ ] `esc` and `safeUrl` are imported from `src\u002Futils\u002Fesc`\n- [ ] Numbers \u002F computed values rendered with `.toFixed()` or arithmetic are left unwrapped (they cannot contain HTML)\n",{"name":5,"description":7},"main","ff671ef61ed6587c49bd54c81cdc751c0b99e363","showcase\u002Fskills\u002Fpanel-component-xss-safe","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":56,"prompt":66,"zipAvailable":67},[57,60,63],{"tool":58,"command":59},"npx","npx skills add AG064\u002FOpenSpace --skill panel-component-xss-safe",{"tool":61,"command":62},"bunx","bunx skills add AG064\u002FOpenSpace --skill panel-component-xss-safe",{"tool":64,"command":65},"pnpm","pnpm dlx skills add AG064\u002FOpenSpace --skill panel-component-xss-safe","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FAG064\u002FOpenSpace\u002Fblob\u002Fmain\u002Fshowcase\u002Fskills\u002Fpanel-component-xss-safe\u002FSKILL.md",true,[69,75],{"path":70,"resourceType":71,"resourceTypeDesc":72,"sizeBytes":73,"sourceHtmlUrl":74},".skill_id","OTHER","其他",45,"https:\u002F\u002Fgithub.com\u002FAG064\u002FOpenSpace\u002Fblob\u002Fmain\u002Fshowcase\u002Fskills\u002Fpanel-component-xss-safe\u002F.skill_id",{"path":76,"resourceType":77,"resourceTypeDesc":78,"sizeBytes":79,"sourceHtmlUrl":80},"src\u002Futils\u002Fesc.ts","SCRIPT","脚本",951,"https:\u002F\u002Fgithub.com\u002FAG064\u002FOpenSpace\u002Fblob\u002Fmain\u002Fshowcase\u002Fskills\u002Fpanel-component-xss-safe\u002Fsrc\u002Futils\u002Fesc.ts",[82,105,120,129,150,165],{"skillNo":83,"name":84,"nameZh":6,"description":85,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":9,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":86,"categories":87,"keywords":88,"publishedAt":43},"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",[],[89,90,91,92,93,94,31,95,96,97,98,99,100,101,102,103,104],"write special chars ts check","check","write","filters","Existing","type-checking","errors","script","output","type","files","only","template","file","python","typescript",{"skillNo":106,"name":107,"nameZh":6,"description":108,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":9,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":109,"categories":110,"keywords":111,"publishedAt":43},"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",[],[112,113,91,101,114,115,102,103,116,117,118,119,36,31,96,33],"readback","write special chars readback","cleanup","read","scripts","verification","via","post",{"skillNo":121,"name":122,"nameZh":6,"description":123,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":9,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":124,"categories":125,"keywords":126,"publishedAt":43},"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",[],[91,127,103,31,118,101,128,102,96],"write special chars heredoc","shell",{"skillNo":130,"name":131,"nameZh":6,"description":132,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":9,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":133,"categories":134,"keywords":136,"publishedAt":43},"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",[135],{"categoryNo":18,"categoryName":19,"taxonomyType":20,"taxonomyTypeDesc":21},[137,38,138,42,104,139,41,140,141,142,31,143,27,144,145,146,147,39,148,149],"reference","worldmonitor reference","css","extracting","hierarchy","source","layer","patterns","edge functions","integrations","open","data","scheduler",{"skillNo":151,"name":152,"nameZh":6,"description":153,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":9,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":154,"categories":155,"keywords":156,"publishedAt":43},"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",[],[157,158,159,160,31,32,33,161,162,163,164],"virtual list","list","virtual","chunk","rendering","recycling","implement","performance",{"skillNo":166,"name":167,"nameZh":6,"description":168,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":9,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":169,"categories":170,"keywords":171,"publishedAt":43},"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",[],[172,173,174,175,176,177,102,178,179,180],"directory","verify","structure","verify directory structure","access","first","issues","diagnose","file access"]