Chat Artifact Extractor (utils/chatArtifacts.ts)

synaplan · frontend/src/utils/chatArtifacts.ts · typescript · Apache-2.0
ui, ai, dev-tools, chat, lang:typescript, lang:html

Parses chat messages to extract embedded HTML and SVG code blocks. Reuse when building AI chat interfaces that render interactive code artifacts.

// Source: https://github.com/metadist/synaplan | License: Apache-2.0 | Copyright You must retain, in the Source form of any Derivative Works
// Provided via justclaw.it.com; keep this notice with the code.
export interface ChatArtifact {
  language: 'html' | 'svg'
  code: string
  index: number
}

const FENCE = /```(html|svg)\s*\n([\s\S]*?)```/gi

/** Complete HTML documents and SVG images. Mermaid stays a code block. */
export function extractArtifacts(text: string): ChatArtifact[] {
  const found: ChatArtifact[] = []
  for (const match of text.matchAll(FENCE)) {
    const language = match[1].toLowerCase()
    const code = match[2].trim()
    if (language !== 'html' && language !== 'svg') continue
    if (code === '') continue
    if (language === 'html' && !/<html[\s>]/i.test(code) && !

... (truncated -- full source via MCP)

See the full source, get the GitHub permalink, and search for more like it.

Get a free API key