{
  "name": "markdown",
  "type": "registry:ui",
  "framework": "react",
  "title": "Markdown",
  "description": "Renders a message written in chat markdown — formatting, mentions, timestamps, spoilers, code blocks — with the library's own parts.",
  "registryDependencies": [
    "@newtui/button",
    "@newtui/code-block",
    "@newtui/custom-emoji",
    "@newtui/inline-code",
    "@newtui/mention",
    "@newtui/modal",
    "@newtui/spoiler",
    "@newtui/timestamp"
  ],
  "files": [
    {
      "path": "ui/markdown.tsx",
      "content": "\"use client\"\n\nimport * as React from \"react\"\n\nimport { cn } from \"@/lib/utils\"\nimport { Button } from \"@/registry/bases/newt/ui/button\"\nimport {\n  CodeBlock,\n  type CodeLanguage,\n} from \"@/registry/bases/newt/ui/code-block\"\nimport { CustomEmoji } from \"@/registry/bases/newt/ui/custom-emoji\"\nimport { InlineCode } from \"@/registry/bases/newt/ui/inline-code\"\nimport {\n  isEmojiOnly,\n  parseMarkdown,\n  type MarkdownBlock,\n  type MarkdownInline,\n  type MarkdownList,\n  type MarkdownMentionKind,\n} from \"@/registry/bases/newt/ui/markdown-syntax\"\nimport { Mention } from \"@/registry/bases/newt/ui/mention\"\nimport {\n  Modal,\n  ModalBody,\n  ModalContent,\n  ModalFooter,\n  ModalHeader,\n  ModalTitle,\n} from \"@/registry/bases/newt/ui/modal\"\nimport { Spoiler } from \"@/registry/bases/newt/ui/spoiler\"\nimport { Timestamp } from \"@/registry/bases/newt/ui/timestamp\"\n\n/** What a mention id resolves to: the name to show, and a role's colour. */\nexport interface MarkdownMentionTarget {\n  name: string\n  /** Role colour, any CSS colour. */\n  color?: string\n  /** User avatar URL. */\n  avatar?: string\n}\n\n/** The words the renderer writes itself. Pass a translation for any of them. */\nexport interface MarkdownLabels {\n  /** Shown for a mention the resolver does not know. */\n  unknownUser: string\n  unknownRole: string\n  unknownChannel: string\n  /** Title of the warning before a masked link opens. */\n  linkWarningTitle: string\n  /** Text above the address in that warning. */\n  linkWarningBody: string\n  linkWarningCancel: string\n  linkWarningConfirm: string\n  /** Accessible name of a hidden spoiler, read in place of its content. */\n  spoiler: string\n}\n\nexport const defaultMarkdownLabels: MarkdownLabels = {\n  unknownUser: \"unknown-user\",\n  unknownRole: \"unknown-role\",\n  unknownChannel: \"unknown-channel\",\n  linkWarningTitle: \"Leaving this page\",\n  linkWarningBody: \"This link's text does not show where it goes. It opens:\",\n  linkWarningCancel: \"Go back\",\n  linkWarningConfirm: \"Visit site\",\n  spoiler: \"Spoiler, click to reveal\",\n}\n\nexport interface MarkdownProps extends Omit<\n  React.HTMLAttributes<HTMLDivElement>,\n  \"children\" | \"content\"\n> {\n  /** The message source, in chat markdown. */\n  content: string\n  /**\n   * Name (and colour, avatar) for a mention id. Without it, or when it returns\n   * nothing, a numeric id shows as `unknown-user` and a name shows as written,\n   * so `<@username>` reads as `@username`.\n   */\n  resolveMention?: (\n    kind: MarkdownMentionKind,\n    id: string\n  ) => MarkdownMentionTarget | undefined\n  /**\n   * Image URL for a server emoji. Without it, or when it returns nothing, the\n   * emoji shows as its `:name:` text — newt/ui never fetches one by itself.\n   */\n  resolveEmoji?: (emoji: {\n    id: string\n    name: string\n    animated: boolean\n  }) => string | undefined\n  /**\n   * Makes mentions buttons and calls this when one is pressed. Without it\n   * they are read-only text, out of the tab order.\n   */\n  onMentionClick?: (mention: { kind: MarkdownMentionKind; id: string }) => void\n  /**\n   * Added to a heading's level to pick its element: `#` with the default 2\n   * is an `<h3>`, so a message never outranks the page around it.\n   */\n  headingOffset?: number\n  /** Locale for timestamps. Defaults to the reader's. */\n  locale?: string\n  /**\n   * Ask before opening a masked link (`[text](url)`), whose text hides its\n   * address. On by default.\n   */\n  linkWarning?: boolean\n  labels?: Partial<MarkdownLabels>\n}\n\n/* The languages `CodeBlock` colours; anything else renders as plain text. */\nconst HIGHLIGHTED = new Set<string>([\n  \"ts\",\n  \"tsx\",\n  \"js\",\n  \"jsx\",\n  \"json\",\n  \"bash\",\n  \"sh\",\n])\n\nfunction isHighlighted(language: string | undefined): language is CodeLanguage {\n  return language !== undefined && HIGHLIGHTED.has(language)\n}\n\nconst MENTION_PREFIX = { user: \"@\", role: \"@\", channel: \"#\" } as const\n\ninterface RenderContext {\n  props: MarkdownProps\n  labels: MarkdownLabels\n  jumbo: boolean\n  openWarning: (url: string) => void\n}\n\nfunction mentionName(\n  context: RenderContext,\n  kind: MarkdownMentionKind,\n  id: string\n): MarkdownMentionTarget {\n  const resolved = context.props.resolveMention?.(kind, id)\n  if (resolved) return resolved\n  if (!/^\\d+$/.test(id)) return { name: id }\n  const unknown = {\n    user: context.labels.unknownUser,\n    role: context.labels.unknownRole,\n    channel: context.labels.unknownChannel,\n  }\n  return { name: unknown[kind] }\n}\n\nfunction renderInline(\n  nodes: readonly MarkdownInline[],\n  context: RenderContext\n): React.ReactNode[] {\n  return nodes.map((node, index) => {\n    const key = index\n    switch (node.type) {\n      case \"text\":\n        return <React.Fragment key={key}>{node.content}</React.Fragment>\n      case \"br\":\n        return <br key={key} />\n      case \"strong\":\n        return (\n          <strong key={key} className=\"font-bold\">\n            {renderInline(node.children, context)}\n          </strong>\n        )\n      case \"em\":\n        return <em key={key}>{renderInline(node.children, context)}</em>\n      case \"underline\":\n        return (\n          <span key={key} className=\"underline\">\n            {renderInline(node.children, context)}\n          </span>\n        )\n      case \"strike\":\n        return <s key={key}>{renderInline(node.children, context)}</s>\n      case \"spoiler\":\n        return (\n          <Spoiler key={key} label={context.labels.spoiler}>\n            {renderInline(node.children, context)}\n          </Spoiler>\n        )\n      case \"code\":\n        return <InlineCode key={key}>{node.content}</InlineCode>\n      case \"link\":\n        return (\n          <a\n            key={key}\n            href={node.url}\n            target=\"_blank\"\n            rel=\"noopener noreferrer\"\n            title={node.masked ? node.url : undefined}\n            className=\"text-newt-text-link no-underline hover:underline\"\n            onClick={(event) => {\n              if (!node.masked || context.props.linkWarning === false) return\n              event.preventDefault()\n              context.openWarning(node.url)\n            }}\n          >\n            {renderInline(node.children, context)}\n          </a>\n        )\n      case \"mention\": {\n        const target = mentionName(context, node.kind, node.id)\n        const onClick = context.props.onMentionClick\n        return (\n          <Mention\n            key={key}\n            as={onClick ? \"button\" : \"span\"}\n            variant={node.kind}\n            color={node.kind === \"role\" ? target.color : undefined}\n            avatar={node.kind === \"user\" ? target.avatar : undefined}\n            onClick={\n              onClick\n                ? () => onClick({ kind: node.kind, id: node.id })\n                : undefined\n            }\n          >\n            {MENTION_PREFIX[node.kind]}\n            {target.name}\n          </Mention>\n        )\n      }\n      case \"everyone\":\n        return (\n          <Mention key={key} as=\"span\" variant=\"user\">\n            @{node.name}\n          </Mention>\n        )\n      case \"command\":\n        return (\n          <Mention key={key} as=\"span\" variant=\"app\">\n            /{node.name}\n          </Mention>\n        )\n      case \"emoji\": {\n        const src = context.props.resolveEmoji?.(node)\n        return src ? (\n          <CustomEmoji\n            key={key}\n            name={node.name}\n            src={src}\n            size={context.jumbo ? \"jumbo\" : \"inline\"}\n          />\n        ) : (\n          <React.Fragment key={key}>:{node.name}:</React.Fragment>\n        )\n      }\n      case \"timestamp\":\n        return (\n          <Timestamp\n            key={key}\n            value={node.value}\n            format={node.format}\n            locale={context.props.locale}\n          />\n        )\n    }\n  })\n}\n\nconst HEADING_TAGS = [\"h1\", \"h2\", \"h3\", \"h4\", \"h5\", \"h6\"] as const\n\nconst HEADING_SIZES = {\n  1: \"text-2xl\",\n  2: \"text-xl\",\n  3: \"text-base\",\n} as const\n\n/* The client's bullets by depth: disc, then circle, then square. */\nconst BULLETS = [\"list-disc\", \"list-[circle]\", \"list-[square]\"] as const\n\nfunction renderList(\n  list: MarkdownList,\n  context: RenderContext,\n  depth: number,\n  key?: React.Key\n): React.ReactNode {\n  const items = list.items.map((item, itemIndex) => (\n    <li key={itemIndex} className=\"mb-1 whitespace-pre-wrap\">\n      {renderInline(item.children, context)}\n      {item.sublist && renderList(item.sublist, context, depth + 1)}\n    </li>\n  ))\n  const className = \"mb-0 mt-1 ps-4\"\n  return list.ordered ? (\n    <ol\n      key={key}\n      start={list.start === 1 ? undefined : list.start}\n      className={cn(className, \"list-decimal\")}\n    >\n      {items}\n    </ol>\n  ) : (\n    <ul\n      key={key}\n      className={cn(className, BULLETS[Math.min(depth, BULLETS.length - 1)])}\n    >\n      {items}\n    </ul>\n  )\n}\n\nfunction renderBlocks(\n  blocks: readonly MarkdownBlock[],\n  context: RenderContext\n): React.ReactNode[] {\n  return blocks.map((block, index) => {\n    const key = index\n    switch (block.type) {\n      case \"paragraph\":\n        return (\n          <p\n            key={key}\n            className={cn(\n              \"m-0 whitespace-pre-wrap\",\n              context.jumbo && \"text-5xl leading-tight\"\n            )}\n          >\n            {renderInline(block.children, context)}\n          </p>\n        )\n      case \"heading\": {\n        const level = Math.min(\n          6,\n          block.level + (context.props.headingOffset ?? 2)\n        )\n        const Tag = HEADING_TAGS[level - 1] ?? \"h6\"\n        return (\n          <Tag\n            key={key}\n            className={cn(\n              \"mb-1 mt-2 whitespace-pre-wrap font-bold leading-[1.375] text-newt-text-primary first:mt-0\",\n              HEADING_SIZES[block.level]\n            )}\n          >\n            {renderInline(block.children, context)}\n          </Tag>\n        )\n      }\n      case \"subtext\":\n        return (\n          <p\n            key={key}\n            className=\"m-0 whitespace-pre-wrap text-[13px] leading-[1.3] text-newt-text-muted\"\n          >\n            {renderInline(block.children, context)}\n          </p>\n        )\n      case \"quote\":\n        return (\n          <blockquote\n            key={key}\n            className=\"my-0.5 border-0 border-s-4 border-solid border-newt-border ps-3\"\n          >\n            {renderBlocks(block.children, context)}\n          </blockquote>\n        )\n      case \"list\":\n        return renderList(block, context, 0, key)\n      case \"codeBlock\":\n        return isHighlighted(block.language) ? (\n          <CodeBlock\n            key={key}\n            className=\"my-1.5\"\n            language={block.language}\n            code={block.content}\n          />\n        ) : (\n          <CodeBlock key={key} className=\"my-1.5\">\n            {block.content}\n          </CodeBlock>\n        )\n    }\n  })\n}\n\n/**\n * Renders a message written in chat markdown with the library's own parts.\n * The source is parsed, never injected as HTML.\n */\nconst Markdown = React.forwardRef<HTMLDivElement, MarkdownProps>(\n  (props, ref) => {\n    const {\n      className,\n      content,\n      resolveMention: _resolveMention,\n      resolveEmoji: _resolveEmoji,\n      onMentionClick: _onMentionClick,\n      headingOffset: _headingOffset,\n      locale: _locale,\n      linkWarning: _linkWarning,\n      labels: labelOverrides,\n      ...rest\n    } = props\n    const blocks = React.useMemo(() => parseMarkdown(content), [content])\n    const labels = { ...defaultMarkdownLabels, ...labelOverrides }\n    const [pendingUrl, setPendingUrl] = React.useState<string | null>(null)\n    /*\n     * The warning opens from a link, not from a `ModalTrigger`, so focus\n     * goes back to whatever held it when the link was activated.\n     */\n    const opener = React.useRef<HTMLElement | null>(null)\n\n    const context: RenderContext = {\n      props,\n      labels,\n      jumbo: isEmojiOnly(blocks),\n      openWarning: (url) => {\n        const active = document.activeElement\n        opener.current = active instanceof HTMLElement ? active : null\n        setPendingUrl(url)\n      },\n    }\n\n    return (\n      <div\n        ref={ref}\n        className={cn(\n          \"min-w-0 break-words [overflow-wrap:anywhere]\",\n          className\n        )}\n        {...rest}\n      >\n        {renderBlocks(blocks, context)}\n        <Modal\n          open={pendingUrl !== null}\n          onOpenChange={(open) => {\n            if (!open) setPendingUrl(null)\n          }}\n        >\n          <ModalContent\n            aria-describedby={undefined}\n            onCloseAutoFocus={(event) => {\n              event.preventDefault()\n              if (opener.current?.isConnected) opener.current.focus()\n            }}\n          >\n            <ModalHeader>\n              <ModalTitle>{labels.linkWarningTitle}</ModalTitle>\n            </ModalHeader>\n            <ModalBody>\n              <p className=\"m-0\">{labels.linkWarningBody}</p>\n              <p className=\"mt-2 break-all rounded-[var(--newt-radius-sm)] bg-newt-bg-base p-2 font-[family-name:var(--newt-font-mono)] text-[13px] text-newt-text-primary\">\n                {pendingUrl}\n              </p>\n            </ModalBody>\n            <ModalFooter>\n              <Button variant=\"secondary\" onClick={() => setPendingUrl(null)}>\n                {labels.linkWarningCancel}\n              </Button>\n              <Button\n                variant=\"primary\"\n                onClick={() => {\n                  if (pendingUrl) {\n                    window.open(pendingUrl, \"_blank\", \"noopener,noreferrer\")\n                  }\n                  setPendingUrl(null)\n                }}\n              >\n                {labels.linkWarningConfirm}\n              </Button>\n            </ModalFooter>\n          </ModalContent>\n        </Modal>\n      </div>\n    )\n  }\n)\nMarkdown.displayName = \"Markdown\"\n\nexport { Markdown }\n",
      "type": "registry:ui"
    },
    {
      "path": "ui/markdown-syntax.ts",
      "content": "/*\n * The chat markdown a message is written in, parsed into a small tree the\n * `Markdown` component renders with the library's own parts: `Mention`,\n * `InlineCode`, `Timestamp`, `Spoiler`, `CodeBlock`, `CustomEmoji`.\n *\n * It is a parser for one dialect, not for CommonMark: single newlines are line\n * breaks, blank lines stay blank, `__` underlines, `||` hides a spoiler, `-#`\n * is subtext, an indented list item nests under the one above it, and the\n * angle-bracket tokens (`<@id>`, `<#id>`, `<t:1700000000:R>`) are mentions,\n * channels and timestamps. Anything it does not recognise stays text, and no\n * HTML in the source is ever interpreted — the output is data, not markup.\n *\n * This file is framework-free and shipped byte-for-byte in both the React and\n * the Vue registry, so the two renderers read the same tree.\n */\n\n/** The letters a `<t:…:X>` token takes, mapped to `Timestamp` formats. */\nexport const TIMESTAMP_FORMATS = {\n  t: \"shortTime\",\n  T: \"longTime\",\n  d: \"shortDate\",\n  D: \"longDate\",\n  f: \"shortDateTime\",\n  F: \"longDateTime\",\n  R: \"relative\",\n} as const\n\nexport type TimestampLetter = keyof typeof TIMESTAMP_FORMATS\n\n/** The largest instant a `Date` can hold, in seconds either side of 1970. */\nconst MAX_TIMESTAMP_SECONDS = 8_640_000_000_000\n\nexport type MarkdownMentionKind = \"user\" | \"role\" | \"channel\"\n\nexport type MarkdownInline =\n  | { type: \"text\"; content: string }\n  | { type: \"br\" }\n  | {\n      type: \"strong\" | \"em\" | \"underline\" | \"strike\" | \"spoiler\"\n      children: MarkdownInline[]\n    }\n  | { type: \"code\"; content: string }\n  | {\n      type: \"link\"\n      url: string\n      /** `[label](url)`: the visible text is not the address. */\n      masked: boolean\n      children: MarkdownInline[]\n    }\n  | { type: \"mention\"; kind: MarkdownMentionKind; id: string }\n  | { type: \"everyone\"; name: \"everyone\" | \"here\" }\n  | { type: \"command\"; name: string; id: string }\n  | { type: \"emoji\"; name: string; id: string; animated: boolean }\n  | {\n      type: \"timestamp\"\n      /** Seconds since the epoch, as the token writes it. */\n      value: number\n      format: (typeof TIMESTAMP_FORMATS)[TimestampLetter]\n    }\n\nexport interface MarkdownListItem {\n  children: MarkdownInline[]\n  /** The items written indented under this one. */\n  sublist?: MarkdownList\n}\n\nexport interface MarkdownList {\n  type: \"list\"\n  ordered: boolean\n  /** The first number of an ordered list. */\n  start: number\n  items: MarkdownListItem[]\n}\n\nexport type MarkdownBlock =\n  | { type: \"paragraph\"; children: MarkdownInline[] }\n  | { type: \"heading\"; level: 1 | 2 | 3; children: MarkdownInline[] }\n  | { type: \"subtext\"; children: MarkdownInline[] }\n  | { type: \"quote\"; children: MarkdownBlock[] }\n  | MarkdownList\n  | { type: \"codeBlock\"; language?: string; content: string }\n\n/* ------------------------------------------------------------------------ */\n/* Inline                                                                    */\n/* ------------------------------------------------------------------------ */\n\ninterface InlineContext {\n  /** Inside a link label: no nested links, no bare URLs. */\n  inLink: boolean\n}\n\ninterface InlineRule {\n  /** Sticky, so `exec` only matches at `lastIndex`. */\n  pattern: RegExp\n  /** Characters a match can start with; a cheap filter before the regex. */\n  starts: string\n  /** Reject a match by the character before it (`snake_case` is not italic). */\n  after?: (previous: string | undefined) => boolean\n  parse: (\n    match: RegExpExecArray,\n    context: InlineContext\n  ) => MarkdownInline | null\n}\n\nconst WORD = /[\\p{L}\\p{N}_]/u\n\nfunction isNotWord(previous: string | undefined): boolean {\n  return previous === undefined || !WORD.test(previous)\n}\n\nfunction group(match: RegExpExecArray, index: number): string {\n  return match[index] ?? \"\"\n}\n\nfunction wrap(\n  type: \"strong\" | \"em\" | \"underline\" | \"strike\" | \"spoiler\"\n): InlineRule[\"parse\"] {\n  return (match, context) => {\n    const inner = group(match, 1)\n    // `_ _` is kept: a run of nothing but spaces is how a message writes an\n    // empty line. An empty spoiler would be a control with nothing to reveal.\n    if (type === \"spoiler\" && inner.trim().length === 0) return null\n    return { type, children: parseInline(inner, context) }\n  }\n}\n\n/*\n * Order matters where two rules share a start: `**` before `*`, `__` before\n * `_`, the double-backtick code span before the single one, and a role\n * mention (`<@&`) before a user mention (`<@`).\n */\nconst INLINE_RULES: readonly InlineRule[] = [\n  {\n    pattern: /\\\\([^\\p{L}\\p{N}\\s])/uy,\n    starts: \"\\\\\",\n    parse: (match) => ({ type: \"text\", content: group(match, 1) }),\n  },\n  {\n    pattern: /``(?: (?=\\S))?([^]+?)(?: )?``/y,\n    starts: \"`\",\n    parse: (match) => ({ type: \"code\", content: group(match, 1) }),\n  },\n  {\n    pattern: /`([^`]+)`/y,\n    starts: \"`\",\n    parse: (match) => ({ type: \"code\", content: group(match, 1) }),\n  },\n  {\n    pattern: /<(a?):(\\w{2,32}):(\\d+)>/y,\n    starts: \"<\",\n    parse: (match) => ({\n      type: \"emoji\",\n      animated: group(match, 1) === \"a\",\n      name: group(match, 2),\n      id: group(match, 3),\n    }),\n  },\n  {\n    pattern: /<t:(-?\\d{1,13})(?::([tTdDfFR]))?>/y,\n    starts: \"<\",\n    parse: (match) => {\n      const letter = match[2] ?? \"f\"\n      const format =\n        Object.entries(TIMESTAMP_FORMATS).find(\n          ([key]) => key === letter\n        )?.[1] ?? TIMESTAMP_FORMATS.f\n      const value = Number(group(match, 1))\n      // Beyond this a `Date` is invalid, and formatting it throws.\n      if (Math.abs(value) > MAX_TIMESTAMP_SECONDS) return null\n      return { type: \"timestamp\", value, format }\n    },\n  },\n  {\n    pattern: /<@&([^<>\\s]+)>/y,\n    starts: \"<\",\n    parse: (match) => ({ type: \"mention\", kind: \"role\", id: group(match, 1) }),\n  },\n  {\n    pattern: /<@!?([^<>\\s&!][^<>\\s]*)>/y,\n    starts: \"<\",\n    parse: (match) => ({ type: \"mention\", kind: \"user\", id: group(match, 1) }),\n  },\n  {\n    pattern: /<#([^<>\\s]+)>/y,\n    starts: \"<\",\n    parse: (match) => ({\n      type: \"mention\",\n      kind: \"channel\",\n      id: group(match, 1),\n    }),\n  },\n  {\n    pattern: /<\\/([\\p{L}\\p{N}_-]+(?: [\\p{L}\\p{N}_-]+){0,2}):(\\d+)>/uy,\n    starts: \"<\",\n    parse: (match) => ({\n      type: \"command\",\n      name: group(match, 1),\n      id: group(match, 2),\n    }),\n  },\n  {\n    pattern: /<(https?:\\/\\/[^\\s<>]+)>/y,\n    starts: \"<\",\n    parse: (match, context) =>\n      context.inLink\n        ? null\n        : {\n            type: \"link\",\n            url: group(match, 1),\n            masked: false,\n            children: [{ type: \"text\", content: group(match, 1) }],\n          },\n  },\n  {\n    pattern:\n      /\\[((?:\\\\.|[^[\\]\\\\\\n])+)\\]\\(\\s*<?(https?:\\/\\/[^\\s<>()]+(?:\\([^\\s<>()]*\\)[^\\s<>()]*)*)>?\\s*\\)/y,\n    starts: \"[\",\n    parse: (match, context) =>\n      context.inLink\n        ? null\n        : {\n            type: \"link\",\n            url: group(match, 2),\n            masked: true,\n            children: parseInline(group(match, 1), { inLink: true }),\n          },\n  },\n  {\n    /* stops before trailing punctuation, which belongs to the sentence */\n    pattern: /https?:\\/\\/[^\\s<]*[^\\s<.,:;\"'!?)\\]]/y,\n    starts: \"h\",\n    after: isNotWord,\n    parse: (match, context) =>\n      context.inLink\n        ? null\n        : {\n            type: \"link\",\n            url: match[0],\n            masked: false,\n            children: [{ type: \"text\", content: match[0] }],\n          },\n  },\n  {\n    pattern: /\\|\\|([^]+?)\\|\\|/y,\n    starts: \"|\",\n    parse: wrap(\"spoiler\"),\n  },\n  {\n    pattern: /\\*\\*([^]+?)\\*\\*(?!\\*)/y,\n    starts: \"*\",\n    parse: wrap(\"strong\"),\n  },\n  {\n    pattern: /__([^]+?)__(?!_)/y,\n    starts: \"_\",\n    parse: wrap(\"underline\"),\n  },\n  {\n    /*\n     * The two alternatives start differently and a bold run cannot hold a\n     * `*`, so every input has one way through: an unclosed marker costs\n     * linear time, not exponential.\n     */\n    pattern: /\\*(?!\\s)((?:[^*]|\\*\\*[^*]+\\*\\*)+?)\\*(?!\\*)/y,\n    starts: \"*\",\n    parse: wrap(\"em\"),\n  },\n  {\n    pattern: /_((?:[^_]|__[^_]+__)+?)_(?![\\p{L}\\p{N}_])/uy,\n    starts: \"_\",\n    after: isNotWord,\n    parse: wrap(\"em\"),\n  },\n  {\n    pattern: /~~([^]+?)~~/y,\n    starts: \"~\",\n    parse: wrap(\"strike\"),\n  },\n  {\n    pattern: /@(everyone|here)(?![\\p{L}\\p{N}_])/uy,\n    starts: \"@\",\n    parse: (match) => ({\n      type: \"everyone\",\n      name: group(match, 1) === \"here\" ? \"here\" : \"everyone\",\n    }),\n  },\n  {\n    pattern: /\\n/y,\n    starts: \"\\n\",\n    parse: () => ({ type: \"br\" }),\n  },\n]\n\nconst RULE_STARTS = new Set(INLINE_RULES.map((rule) => rule.starts))\n\n/** Parse the inline content of one block: formatting, links, mentions. */\nexport function parseInline(\n  source: string,\n  context: InlineContext = { inLink: false }\n): MarkdownInline[] {\n  const nodes: MarkdownInline[] = []\n  let text = \"\"\n  const flush = () => {\n    if (text.length > 0) nodes.push({ type: \"text\", content: text })\n    text = \"\"\n  }\n\n  let index = 0\n  while (index < source.length) {\n    const char = source[index] ?? \"\"\n    let node: MarkdownInline | null = null\n    let length = 0\n    if (RULE_STARTS.has(char)) {\n      for (const rule of INLINE_RULES) {\n        if (rule.starts !== char) continue\n        if (rule.after && !rule.after(source[index - 1])) continue\n        rule.pattern.lastIndex = index\n        const match = rule.pattern.exec(source)\n        if (!match) continue\n        node = rule.parse(match, context)\n        if (node) {\n          length = match[0].length\n          break\n        }\n      }\n    }\n    if (node) {\n      // An escape is text: let it join the run around it.\n      if (node.type === \"text\") text += node.content\n      else {\n        flush()\n        nodes.push(node)\n      }\n      index += length\n    } else {\n      text += char\n      index += 1\n    }\n  }\n  flush()\n  return nodes\n}\n\n/* ------------------------------------------------------------------------ */\n/* Blocks                                                                    */\n/* ------------------------------------------------------------------------ */\n\n/*\n * A fence may open and close on one line or span many. The language is the\n * word right after the opening fence, and only when a newline follows it —\n * \"```js```\" is a block that says `js`.\n */\nconst FENCE = /^```(?:([\\w+#.-]+)[^\\S\\n]*\\n|[^\\S\\n]*\\n)?([^]*?)```[^\\S\\n]*\\n?/\nconst HEADING = /^(#{1,3}) +(\\S.*)$/\nconst SUBTEXT = /^-# +(\\S.*)$/\nconst QUOTE_LINE = /^> (.*)$|^>$/\nconst QUOTE_REST = /^>>> /\nconst LIST_ITEM = /^([^\\S\\n]*)(?:[-*]|(\\d{1,9})\\.) +(\\S.*)$/\n/** How deep an indented item can nest; deeper ones join the last level. */\nconst MAX_LIST_DEPTH = 10\n\nfunction isBlank(line: string): boolean {\n  return line.trim().length === 0\n}\n\nfunction headingLevel(marks: number | undefined): 1 | 2 | 3 {\n  if (marks === 3) return 3\n  if (marks === 2) return 2\n  return 1\n}\n\ninterface BlockContext {\n  /** Quotes do not nest: a `>` inside a quote is text. */\n  inQuote: boolean\n}\n\n/*\n * Every line of a paragraph is a line on screen, blank ones included, as in\n * the client: a blank line before or after a list is a gap. A break at the\n * very end of a block draws nothing, so an empty last line takes a second one.\n */\nfunction paragraph(lines: string[]): MarkdownBlock | null {\n  if (lines.length === 0) return null\n  const body = lines.join(\"\\n\") + (lines.at(-1) === \"\" ? \"\\n\" : \"\")\n  return { type: \"paragraph\", children: parseInline(body) }\n}\n\nfunction emptyList(item: RegExpExecArray): MarkdownList {\n  const ordered = item[2] !== undefined\n  return {\n    type: \"list\",\n    ordered,\n    start: ordered ? Number(item[2]) : 1,\n    items: [],\n  }\n}\n\n/*\n * One list, and the lists indented inside it: an item indented further than\n * the one above nests under it, one indented less closes the levels it left.\n * At the top level a change between `-` and `1.` starts a new list.\n */\nfunction parseList(\n  first: RegExpExecArray,\n  peek: () => string,\n  advance: () => void,\n  more: () => boolean\n): MarkdownList {\n  const root = emptyList(first)\n  const levels = [{ indent: group(first, 1).length, list: root }]\n  while (more()) {\n    const item = LIST_ITEM.exec(peek())\n    if (!item) break\n    const indent = group(item, 1).length\n    while (levels.length > 1 && indent < (levels.at(-1)?.indent ?? 0)) {\n      levels.pop()\n    }\n    const level = levels.at(-1) ?? levels[0]\n    if (!level) break\n    const parent = level.list.items.at(-1)\n    const node: MarkdownListItem = { children: parseInline(group(item, 3)) }\n    if (indent > level.indent && parent && levels.length < MAX_LIST_DEPTH) {\n      parent.sublist ??= emptyList(item)\n      parent.sublist.items.push(node)\n      levels.push({ indent, list: parent.sublist })\n    } else {\n      if (levels.length === 1 && (item[2] !== undefined) !== root.ordered) {\n        break\n      }\n      level.list.items.push(node)\n    }\n    advance()\n  }\n  return root\n}\n\n/** Parse a whole message into blocks. */\nexport function parseMarkdown(\n  source: string,\n  context: BlockContext = { inQuote: false }\n): MarkdownBlock[] {\n  const blocks: MarkdownBlock[] = []\n  let pending: string[] = []\n  const flush = () => {\n    const block = paragraph(pending)\n    if (block) blocks.push(block)\n    pending = []\n  }\n\n  // The client trims a message, so blank lines at either end draw nothing.\n  let rest = source\n    .replace(/\\r\\n?/g, \"\\n\")\n    .replace(/^(?:[^\\S\\n]*\\n)+/, \"\")\n    .replace(/(?:\\n[^\\S\\n]*)+$/, \"\")\n  /** The current line, without its newline. */\n  const peek = () => {\n    const end = rest.indexOf(\"\\n\")\n    return end === -1 ? rest : rest.slice(0, end)\n  }\n  /** Drop the current line, newline included. */\n  const advance = () => {\n    const end = rest.indexOf(\"\\n\")\n    rest = end === -1 ? \"\" : rest.slice(end + 1)\n  }\n\n  while (rest.length > 0) {\n    const fence = FENCE.exec(rest)\n    if (fence) {\n      flush()\n      blocks.push({\n        type: \"codeBlock\",\n        language: fence[1]?.toLowerCase(),\n        content: (fence[2] ?? \"\").replace(/\\n$/, \"\"),\n      })\n      rest = rest.slice(fence[0].length)\n      continue\n    }\n\n    const line = peek()\n\n    if (!context.inQuote) {\n      // `>>> ` quotes everything after it, to the end of the message.\n      if (QUOTE_REST.test(rest)) {\n        flush()\n        blocks.push({\n          type: \"quote\",\n          children: parseMarkdown(rest.slice(4), { inQuote: true }),\n        })\n        rest = \"\"\n        break\n      }\n      if (QUOTE_LINE.test(line)) {\n        flush()\n        const quoted: string[] = []\n        while (rest.length > 0) {\n          const match = QUOTE_LINE.exec(peek())\n          if (!match) break\n          quoted.push(match[1] ?? \"\")\n          advance()\n        }\n        blocks.push({\n          type: \"quote\",\n          children: parseMarkdown(quoted.join(\"\\n\"), { inQuote: true }),\n        })\n        continue\n      }\n    }\n\n    const heading = HEADING.exec(line)\n    if (heading) {\n      flush()\n      blocks.push({\n        type: \"heading\",\n        level: headingLevel(heading[1]?.length),\n        children: parseInline(heading[2] ?? \"\"),\n      })\n      advance()\n      // A heading takes the blank lines after it, as the client does.\n      while (rest.length > 0 && isBlank(peek())) advance()\n      continue\n    }\n\n    const subtext = SUBTEXT.exec(line)\n    if (subtext) {\n      flush()\n      blocks.push({ type: \"subtext\", children: parseInline(subtext[1] ?? \"\") })\n      advance()\n      continue\n    }\n\n    const item = LIST_ITEM.exec(line)\n    if (item) {\n      flush()\n      blocks.push(parseList(item, peek, advance, () => rest.length > 0))\n      continue\n    }\n\n    // A fence that opens mid-line still starts a block, as in the client.\n    const inlineFence = line.indexOf(\"```\")\n    if (inlineFence > 0 && FENCE.test(rest.slice(inlineFence))) {\n      pending.push(line.slice(0, inlineFence))\n      flush()\n      rest = rest.slice(inlineFence)\n      continue\n    }\n\n    pending.push(line)\n    advance()\n  }\n  flush()\n  return blocks\n}\n\n/*\n * Pictographs and what joins or modifies them: zero-width joiner, variation\n * selector, skin tones, and the regional indicators that pair into flags.\n * Not `Emoji_Component`, which also holds the digits, `#` and `*`.\n */\nconst EMOJI_ONLY =\n  /^(?:\\p{Extended_Pictographic}|\\p{Emoji_Modifier}|\\p{Regional_Indicator}|\\u200d|\\ufe0f)+$/u\n\n/**\n * Whether a message is nothing but emoji — custom ones, or a few characters\n * of Unicode pictographs — which the client renders large.\n */\nexport function isEmojiOnly(blocks: readonly MarkdownBlock[]): boolean {\n  if (blocks.length !== 1) return false\n  const [block] = blocks\n  if (block?.type !== \"paragraph\") return false\n  let count = 0\n  for (const node of block.children) {\n    if (node.type === \"emoji\") count += 1\n    else if (node.type === \"text\") {\n      const stripped = node.content.replace(/\\s+/g, \"\")\n      if (stripped.length === 0) continue\n      if (!EMOJI_ONLY.test(stripped)) return false\n      count += [...stripped.matchAll(/\\p{Extended_Pictographic}/gu)].length\n      count += [...stripped.matchAll(/\\p{Regional_Indicator}/gu)].length / 2\n    } else return false\n  }\n  return count > 0 && count <= 30\n}\n",
      "type": "registry:ui"
    }
  ]
}