Skip to content

ComponentsMessaging

SourceSource

Markdown

Renders a message written in chat markdown — formatting, mentions, timestamps, spoilers, code blocks — with the library's own parts.

Markdown takes a message as a string and renders it the way a Discord-inspired chat client does: **bold**, *italic*, __underline__, ~~strike~~, ||spoilers||, inline and fenced code, #/##/### headings, -# subtext, lists, > and >>> quotes, links, and the angle-bracket tokens — <@id>, <@&id>, <#id>, </command:id>, <:emoji:id> and <t:1700000000:R>.

Line breaks follow the client too. Every newline is a line break and a blank line stays an empty line, before and after a list as well as between paragraphs; _ _ is an empty line written on purpose. A list item indented under another one nests, with a circle bullet and then a square one.

Each piece renders through a part you already have: mentions are Mention, code is InlineCode and CodeBlock, spoilers are Spoiler, timestamps are Timestamp, server emoji are CustomEmoji. A general Markdown library would give you HTML; this gives you the same components as the rest of the feed. For HTML a general renderer already produced — docs, articles, a CMS field — use Typeset instead.

The source is parsed into a tree and rendered as components. It is never injected as HTML, and only http and https addresses become links.

"use client"

import {
  Markdown,
  type MarkdownMentionTarget,
} from "@/registry/bases/newt/ui/markdown"

const MESSAGE = `## Release notes
The **new build** is out — read the [changelog](https://example.com/changelog) or ping <@1001> in <#2002>.
- Fixed the *reconnect* loop
  - Sessions resume after a dropped socket
- Added \`/ban\` options for <@&3003>
> Rolling out ||tonight|| at <t:1767225600:t>.
\`\`\`ts
const shard = await connect({ id: 3 })
\`\`\`
-# Posted by the release bot`

/* Mentions carry ids; the page that renders them knows the names. */
const NAMES = new Map<string, MarkdownMentionTarget>([
  ["user:1001", { name: "username" }],
  ["channel:2002", { name: "announcements" }],
  ["role:3003", { name: "Moderator", color: "#f0b232" }],
])

export default function MarkdownDemo() {
  return (
    <Markdown
      className="max-w-xl text-[15px] leading-[1.375] text-newt-text-secondary"
      content={MESSAGE}
      resolveMention={(kind, id) => NAMES.get(`${kind}:${id}`)}
    />
  )
}
<script setup lang="ts">
import {
  Markdown,
  type MarkdownMentionKind,
  type MarkdownMentionTarget,
} from "~~/registry/bases/newt/ui/markdown"

const MESSAGE = `## Release notes
The **new build** is out — read the [changelog](https://example.com/changelog) or ping <@1001> in <#2002>.
- Fixed the *reconnect* loop
  - Sessions resume after a dropped socket
- Added \`/ban\` options for <@&3003>
> Rolling out ||tonight|| at <t:1767225600:t>.
\`\`\`ts
const shard = await connect({ id: 3 })
\`\`\`
-# Posted by the release bot`

/* Mentions carry ids; the page that renders them knows the names. */
const NAMES = new Map<string, MarkdownMentionTarget>([
  ["user:1001", { name: "username" }],
  ["channel:2002", { name: "announcements" }],
  ["role:3003", { name: "Moderator", color: "#f0b232" }],
])

function resolveMention(kind: MarkdownMentionKind, id: string) {
  return NAMES.get(`${kind}:${id}`)
}
</script>

<template>
  <Markdown
    class="max-w-xl text-[15px] leading-[1.375] text-newt-text-secondary"
    :content="MESSAGE"
    :resolve-mention="resolveMention"
  />
</template>

Installation

npx newtui@latest add markdownnpx shadcn@latest add @newtui/markdownnpx shadcn-vue@latest add @newtui/markdownpnpm dlx newtui@latest add markdownpnpm dlx shadcn@latest add @newtui/markdownpnpm dlx shadcn-vue@latest add @newtui/markdownyarn dlx newtui@latest add markdownyarn dlx shadcn@latest add @newtui/markdownyarn dlx shadcn-vue@latest add @newtui/markdownbunx newtui@latest add markdownbunx shadcn@latest add @newtui/markdownbunx shadcn-vue@latest add @newtui/markdowndeno run -A npm:newtui@latest add markdowndeno run -A npm:shadcn@latest add @newtui/markdowndeno run -A npm:shadcn-vue@latest add @newtui/markdownvlx newtui@latest add markdownvlx shadcn@latest add @newtui/markdownvlx shadcn-vue@latest add @newtui/markdownvp dlx newtui@latest add markdownvp dlx shadcn@latest add @newtui/markdownvp dlx shadcn-vue@latest add @newtui/markdownnubx newtui@latest add markdownnubx shadcn@latest add @newtui/markdownnubx shadcn-vue@latest add @newtui/markdownnlx newtui@latest add markdownnlx shadcn@latest add @newtui/markdownnlx shadcn-vue@latest add @newtui/markdownupx newtui@latest add markdownupx shadcn@latest add @newtui/markdownupx shadcn-vue@latest add @newtui/markdown

The shadcn CLI needs the @newtui registry in your components.json. Set it up.

Add the components it builds on

Copy the source into your project

"use client"

import * as React from "react"

import { cn } from "@/lib/utils"
import { Button } from "@/registry/bases/newt/ui/button"
import {
  CodeBlock,
  type CodeLanguage,
} from "@/registry/bases/newt/ui/code-block"
import { CustomEmoji } from "@/registry/bases/newt/ui/custom-emoji"
import { InlineCode } from "@/registry/bases/newt/ui/inline-code"
import {
  isEmojiOnly,
  parseMarkdown,
  type MarkdownBlock,
  type MarkdownInline,
  type MarkdownList,
  type MarkdownMentionKind,
} from "@/registry/bases/newt/ui/markdown-syntax"
import { Mention } from "@/registry/bases/newt/ui/mention"
import {
  Modal,
  ModalBody,
  ModalContent,
  ModalFooter,
  ModalHeader,
  ModalTitle,
} from "@/registry/bases/newt/ui/modal"
import { Spoiler } from "@/registry/bases/newt/ui/spoiler"
import { Timestamp } from "@/registry/bases/newt/ui/timestamp"

/** What a mention id resolves to: the name to show, and a role's colour. */
export interface MarkdownMentionTarget {
  name: string
  /** Role colour, any CSS colour. */
  color?: string
  /** User avatar URL. */
  avatar?: string
}

/** The words the renderer writes itself. Pass a translation for any of them. */
export interface MarkdownLabels {
  /** Shown for a mention the resolver does not know. */
  unknownUser: string
  unknownRole: string
  unknownChannel: string
  /** Title of the warning before a masked link opens. */
  linkWarningTitle: string
  /** Text above the address in that warning. */
  linkWarningBody: string
  linkWarningCancel: string
  linkWarningConfirm: string
  /** Accessible name of a hidden spoiler, read in place of its content. */
  spoiler: string
}

export const defaultMarkdownLabels: MarkdownLabels = {
  unknownUser: "unknown-user",
  unknownRole: "unknown-role",
  unknownChannel: "unknown-channel",
  linkWarningTitle: "Leaving this page",
  linkWarningBody: "This link's text does not show where it goes. It opens:",
  linkWarningCancel: "Go back",
  linkWarningConfirm: "Visit site",
  spoiler: "Spoiler, click to reveal",
}

export interface MarkdownProps extends Omit<
  React.HTMLAttributes<HTMLDivElement>,
  "children" | "content"
> {
  /** The message source, in chat markdown. */
  content: string
  /**
   * Name (and colour, avatar) for a mention id. Without it, or when it returns
   * nothing, a numeric id shows as `unknown-user` and a name shows as written,
   * so `<@username>` reads as `@username`.
   */
  resolveMention?: (
    kind: MarkdownMentionKind,
    id: string
  ) => MarkdownMentionTarget | undefined
  /**
   * Image URL for a server emoji. Without it, or when it returns nothing, the
   * emoji shows as its `:name:` text — newt/ui never fetches one by itself.
   */
  resolveEmoji?: (emoji: {
    id: string
    name: string
    animated: boolean
  }) => string | undefined
  /**
   * Makes mentions buttons and calls this when one is pressed. Without it
   * they are read-only text, out of the tab order.
   */
  onMentionClick?: (mention: { kind: MarkdownMentionKind; id: string }) => void
  /**
   * Added to a heading's level to pick its element: `#` with the default 2
   * is an `<h3>`, so a message never outranks the page around it.
   */
  headingOffset?: number
  /** Locale for timestamps. Defaults to the reader's. */
  locale?: string
  /**
   * Ask before opening a masked link (`[text](url)`), whose text hides its
   * address. On by default.
   */
  linkWarning?: boolean
  labels?: Partial<MarkdownLabels>
}

/* The languages `CodeBlock` colours; anything else renders as plain text. */
const HIGHLIGHTED = new Set<string>([
  "ts",
  "tsx",
  "js",
  "jsx",
  "json",
  "bash",
  "sh",
])

function isHighlighted(language: string | undefined): language is CodeLanguage {
  return language !== undefined && HIGHLIGHTED.has(language)
}

const MENTION_PREFIX = { user: "@", role: "@", channel: "#" } as const

interface RenderContext {
  props: MarkdownProps
  labels: MarkdownLabels
  jumbo: boolean
  openWarning: (url: string) => void
}

function mentionName(
  context: RenderContext,
  kind: MarkdownMentionKind,
  id: string
): MarkdownMentionTarget {
  const resolved = context.props.resolveMention?.(kind, id)
  if (resolved) return resolved
  if (!/^\d+$/.test(id)) return { name: id }
  const unknown = {
    user: context.labels.unknownUser,
    role: context.labels.unknownRole,
    channel: context.labels.unknownChannel,
  }
  return { name: unknown[kind] }
}

function renderInline(
  nodes: readonly MarkdownInline[],
  context: RenderContext
): React.ReactNode[] {
  return nodes.map((node, index) => {
    const key = index
    switch (node.type) {
      case "text":
        return <React.Fragment key={key}>{node.content}</React.Fragment>
      case "br":
        return <br key={key} />
      case "strong":
        return (
          <strong key={key} className="font-bold">
            {renderInline(node.children, context)}
          </strong>
        )
      case "em":
        return <em key={key}>{renderInline(node.children, context)}</em>
      case "underline":
        return (
          <span key={key} className="underline">
            {renderInline(node.children, context)}
          </span>
        )
      case "strike":
        return <s key={key}>{renderInline(node.children, context)}</s>
      case "spoiler":
        return (
          <Spoiler key={key} label={context.labels.spoiler}>
            {renderInline(node.children, context)}
          </Spoiler>
        )
      case "code":
        return <InlineCode key={key}>{node.content}</InlineCode>
      case "link":
        return (
          <a
            key={key}
            href={node.url}
            target="_blank"
            rel="noopener noreferrer"
            title={node.masked ? node.url : undefined}
            className="text-newt-text-link no-underline hover:underline"
            onClick={(event) => {
              if (!node.masked || context.props.linkWarning === false) return
              event.preventDefault()
              context.openWarning(node.url)
            }}
          >
            {renderInline(node.children, context)}
          </a>
        )
      case "mention": {
        const target = mentionName(context, node.kind, node.id)
        const onClick = context.props.onMentionClick
        return (
          <Mention
            key={key}
            as={onClick ? "button" : "span"}
            variant={node.kind}
            color={node.kind === "role" ? target.color : undefined}
            avatar={node.kind === "user" ? target.avatar : undefined}
            onClick={
              onClick
                ? () => onClick({ kind: node.kind, id: node.id })
                : undefined
            }
          >
            {MENTION_PREFIX[node.kind]}
            {target.name}
          </Mention>
        )
      }
      case "everyone":
        return (
          <Mention key={key} as="span" variant="user">
            @{node.name}
          </Mention>
        )
      case "command":
        return (
          <Mention key={key} as="span" variant="app">
            /{node.name}
          </Mention>
        )
      case "emoji": {
        const src = context.props.resolveEmoji?.(node)
        return src ? (
          <CustomEmoji
            key={key}
            name={node.name}
            src={src}
            size={context.jumbo ? "jumbo" : "inline"}
          />
        ) : (
          <React.Fragment key={key}>:{node.name}:</React.Fragment>
        )
      }
      case "timestamp":
        return (
          <Timestamp
            key={key}
            value={node.value}
            format={node.format}
            locale={context.props.locale}
          />
        )
    }
  })
}

const HEADING_TAGS = ["h1", "h2", "h3", "h4", "h5", "h6"] as const

const HEADING_SIZES = {
  1: "text-2xl",
  2: "text-xl",
  3: "text-base",
} as const

/* The client's bullets by depth: disc, then circle, then square. */
const BULLETS = ["list-disc", "list-[circle]", "list-[square]"] as const

function renderList(
  list: MarkdownList,
  context: RenderContext,
  depth: number,
  key?: React.Key
): React.ReactNode {
  const items = list.items.map((item, itemIndex) => (
    <li key={itemIndex} className="mb-1 whitespace-pre-wrap">
      {renderInline(item.children, context)}
      {item.sublist && renderList(item.sublist, context, depth + 1)}
    </li>
  ))
  const className = "mb-0 mt-1 ps-4"
  return list.ordered ? (
    <ol
      key={key}
      start={list.start === 1 ? undefined : list.start}
      className={cn(className, "list-decimal")}
    >
      {items}
    </ol>
  ) : (
    <ul
      key={key}
      className={cn(className, BULLETS[Math.min(depth, BULLETS.length - 1)])}
    >
      {items}
    </ul>
  )
}

function renderBlocks(
  blocks: readonly MarkdownBlock[],
  context: RenderContext
): React.ReactNode[] {
  return blocks.map((block, index) => {
    const key = index
    switch (block.type) {
      case "paragraph":
        return (
          <p
            key={key}
            className={cn(
              "m-0 whitespace-pre-wrap",
              context.jumbo && "text-5xl leading-tight"
            )}
          >
            {renderInline(block.children, context)}
          </p>
        )
      case "heading": {
        const level = Math.min(
          6,
          block.level + (context.props.headingOffset ?? 2)
        )
        const Tag = HEADING_TAGS[level - 1] ?? "h6"
        return (
          <Tag
            key={key}
            className={cn(
              "mb-1 mt-2 whitespace-pre-wrap font-bold leading-[1.375] text-newt-text-primary first:mt-0",
              HEADING_SIZES[block.level]
            )}
          >
            {renderInline(block.children, context)}
          </Tag>
        )
      }
      case "subtext":
        return (
          <p
            key={key}
            className="m-0 whitespace-pre-wrap text-[13px] leading-[1.3] text-newt-text-muted"
          >
            {renderInline(block.children, context)}
          </p>
        )
      case "quote":
        return (
          <blockquote
            key={key}
            className="my-0.5 border-0 border-s-4 border-solid border-newt-border ps-3"
          >
            {renderBlocks(block.children, context)}
          </blockquote>
        )
      case "list":
        return renderList(block, context, 0, key)
      case "codeBlock":
        return isHighlighted(block.language) ? (
          <CodeBlock
            key={key}
            className="my-1.5"
            language={block.language}
            code={block.content}
          />
        ) : (
          <CodeBlock key={key} className="my-1.5">
            {block.content}
          </CodeBlock>
        )
    }
  })
}

/**
 * Renders a message written in chat markdown with the library's own parts.
 * The source is parsed, never injected as HTML.
 */
const Markdown = React.forwardRef<HTMLDivElement, MarkdownProps>(
  (props, ref) => {
    const {
      className,
      content,
      resolveMention: _resolveMention,
      resolveEmoji: _resolveEmoji,
      onMentionClick: _onMentionClick,
      headingOffset: _headingOffset,
      locale: _locale,
      linkWarning: _linkWarning,
      labels: labelOverrides,
      ...rest
    } = props
    const blocks = React.useMemo(() => parseMarkdown(content), [content])
    const labels = { ...defaultMarkdownLabels, ...labelOverrides }
    const [pendingUrl, setPendingUrl] = React.useState<string | null>(null)
    /*
     * The warning opens from a link, not from a `ModalTrigger`, so focus
     * goes back to whatever held it when the link was activated.
     */
    const opener = React.useRef<HTMLElement | null>(null)

    const context: RenderContext = {
      props,
      labels,
      jumbo: isEmojiOnly(blocks),
      openWarning: (url) => {
        const active = document.activeElement
        opener.current = active instanceof HTMLElement ? active : null
        setPendingUrl(url)
      },
    }

    return (
      <div
        ref={ref}
        className={cn(
          "min-w-0 break-words [overflow-wrap:anywhere]",
          className
        )}
        {...rest}
      >
        {renderBlocks(blocks, context)}
        <Modal
          open={pendingUrl !== null}
          onOpenChange={(open) => {
            if (!open) setPendingUrl(null)
          }}
        >
          <ModalContent
            aria-describedby={undefined}
            onCloseAutoFocus={(event) => {
              event.preventDefault()
              if (opener.current?.isConnected) opener.current.focus()
            }}
          >
            <ModalHeader>
              <ModalTitle>{labels.linkWarningTitle}</ModalTitle>
            </ModalHeader>
            <ModalBody>
              <p className="m-0">{labels.linkWarningBody}</p>
              <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">
                {pendingUrl}
              </p>
            </ModalBody>
            <ModalFooter>
              <Button variant="secondary" onClick={() => setPendingUrl(null)}>
                {labels.linkWarningCancel}
              </Button>
              <Button
                variant="primary"
                onClick={() => {
                  if (pendingUrl) {
                    window.open(pendingUrl, "_blank", "noopener,noreferrer")
                  }
                  setPendingUrl(null)
                }}
              >
                {labels.linkWarningConfirm}
              </Button>
            </ModalFooter>
          </ModalContent>
        </Modal>
      </div>
    )
  }
)
Markdown.displayName = "Markdown"

export { Markdown }
/*
 * The chat markdown a message is written in, parsed into a small tree the
 * `Markdown` component renders with the library's own parts: `Mention`,
 * `InlineCode`, `Timestamp`, `Spoiler`, `CodeBlock`, `CustomEmoji`.
 *
 * It is a parser for one dialect, not for CommonMark: single newlines are line
 * breaks, blank lines stay blank, `__` underlines, `||` hides a spoiler, `-#`
 * is subtext, an indented list item nests under the one above it, and the
 * angle-bracket tokens (`<@id>`, `<#id>`, `<t:1700000000:R>`) are mentions,
 * channels and timestamps. Anything it does not recognise stays text, and no
 * HTML in the source is ever interpreted — the output is data, not markup.
 *
 * This file is framework-free and shipped byte-for-byte in both the React and
 * the Vue registry, so the two renderers read the same tree.
 */

/** The letters a `<t:…:X>` token takes, mapped to `Timestamp` formats. */
export const TIMESTAMP_FORMATS = {
  t: "shortTime",
  T: "longTime",
  d: "shortDate",
  D: "longDate",
  f: "shortDateTime",
  F: "longDateTime",
  R: "relative",
} as const

export type TimestampLetter = keyof typeof TIMESTAMP_FORMATS

/** The largest instant a `Date` can hold, in seconds either side of 1970. */
const MAX_TIMESTAMP_SECONDS = 8_640_000_000_000

export type MarkdownMentionKind = "user" | "role" | "channel"

export type MarkdownInline =
  | { type: "text"; content: string }
  | { type: "br" }
  | {
      type: "strong" | "em" | "underline" | "strike" | "spoiler"
      children: MarkdownInline[]
    }
  | { type: "code"; content: string }
  | {
      type: "link"
      url: string
      /** `[label](url)`: the visible text is not the address. */
      masked: boolean
      children: MarkdownInline[]
    }
  | { type: "mention"; kind: MarkdownMentionKind; id: string }
  | { type: "everyone"; name: "everyone" | "here" }
  | { type: "command"; name: string; id: string }
  | { type: "emoji"; name: string; id: string; animated: boolean }
  | {
      type: "timestamp"
      /** Seconds since the epoch, as the token writes it. */
      value: number
      format: (typeof TIMESTAMP_FORMATS)[TimestampLetter]
    }

export interface MarkdownListItem {
  children: MarkdownInline[]
  /** The items written indented under this one. */
  sublist?: MarkdownList
}

export interface MarkdownList {
  type: "list"
  ordered: boolean
  /** The first number of an ordered list. */
  start: number
  items: MarkdownListItem[]
}

export type MarkdownBlock =
  | { type: "paragraph"; children: MarkdownInline[] }
  | { type: "heading"; level: 1 | 2 | 3; children: MarkdownInline[] }
  | { type: "subtext"; children: MarkdownInline[] }
  | { type: "quote"; children: MarkdownBlock[] }
  | MarkdownList
  | { type: "codeBlock"; language?: string; content: string }

/* ------------------------------------------------------------------------ */
/* Inline                                                                    */
/* ------------------------------------------------------------------------ */

interface InlineContext {
  /** Inside a link label: no nested links, no bare URLs. */
  inLink: boolean
}

interface InlineRule {
  /** Sticky, so `exec` only matches at `lastIndex`. */
  pattern: RegExp
  /** Characters a match can start with; a cheap filter before the regex. */
  starts: string
  /** Reject a match by the character before it (`snake_case` is not italic). */
  after?: (previous: string | undefined) => boolean
  parse: (
    match: RegExpExecArray,
    context: InlineContext
  ) => MarkdownInline | null
}

const WORD = /[\p{L}\p{N}_]/u

function isNotWord(previous: string | undefined): boolean {
  return previous === undefined || !WORD.test(previous)
}

function group(match: RegExpExecArray, index: number): string {
  return match[index] ?? ""
}

function wrap(
  type: "strong" | "em" | "underline" | "strike" | "spoiler"
): InlineRule["parse"] {
  return (match, context) => {
    const inner = group(match, 1)
    // `_ _` is kept: a run of nothing but spaces is how a message writes an
    // empty line. An empty spoiler would be a control with nothing to reveal.
    if (type === "spoiler" && inner.trim().length === 0) return null
    return { type, children: parseInline(inner, context) }
  }
}

/*
 * Order matters where two rules share a start: `**` before `*`, `__` before
 * `_`, the double-backtick code span before the single one, and a role
 * mention (`<@&`) before a user mention (`<@`).
 */
const INLINE_RULES: readonly InlineRule[] = [
  {
    pattern: /\\([^\p{L}\p{N}\s])/uy,
    starts: "\\",
    parse: (match) => ({ type: "text", content: group(match, 1) }),
  },
  {
    pattern: /``(?: (?=\S))?([^]+?)(?: )?``/y,
    starts: "`",
    parse: (match) => ({ type: "code", content: group(match, 1) }),
  },
  {
    pattern: /`([^`]+)`/y,
    starts: "`",
    parse: (match) => ({ type: "code", content: group(match, 1) }),
  },
  {
    pattern: /<(a?):(\w{2,32}):(\d+)>/y,
    starts: "<",
    parse: (match) => ({
      type: "emoji",
      animated: group(match, 1) === "a",
      name: group(match, 2),
      id: group(match, 3),
    }),
  },
  {
    pattern: /<t:(-?\d{1,13})(?::([tTdDfFR]))?>/y,
    starts: "<",
    parse: (match) => {
      const letter = match[2] ?? "f"
      const format =
        Object.entries(TIMESTAMP_FORMATS).find(
          ([key]) => key === letter
        )?.[1] ?? TIMESTAMP_FORMATS.f
      const value = Number(group(match, 1))
      // Beyond this a `Date` is invalid, and formatting it throws.
      if (Math.abs(value) > MAX_TIMESTAMP_SECONDS) return null
      return { type: "timestamp", value, format }
    },
  },
  {
    pattern: /<@&([^<>\s]+)>/y,
    starts: "<",
    parse: (match) => ({ type: "mention", kind: "role", id: group(match, 1) }),
  },
  {
    pattern: /<@!?([^<>\s&!][^<>\s]*)>/y,
    starts: "<",
    parse: (match) => ({ type: "mention", kind: "user", id: group(match, 1) }),
  },
  {
    pattern: /<#([^<>\s]+)>/y,
    starts: "<",
    parse: (match) => ({
      type: "mention",
      kind: "channel",
      id: group(match, 1),
    }),
  },
  {
    pattern: /<\/([\p{L}\p{N}_-]+(?: [\p{L}\p{N}_-]+){0,2}):(\d+)>/uy,
    starts: "<",
    parse: (match) => ({
      type: "command",
      name: group(match, 1),
      id: group(match, 2),
    }),
  },
  {
    pattern: /<(https?:\/\/[^\s<>]+)>/y,
    starts: "<",
    parse: (match, context) =>
      context.inLink
        ? null
        : {
            type: "link",
            url: group(match, 1),
            masked: false,
            children: [{ type: "text", content: group(match, 1) }],
          },
  },
  {
    pattern:
      /\[((?:\\.|[^[\]\\\n])+)\]\(\s*<?(https?:\/\/[^\s<>()]+(?:\([^\s<>()]*\)[^\s<>()]*)*)>?\s*\)/y,
    starts: "[",
    parse: (match, context) =>
      context.inLink
        ? null
        : {
            type: "link",
            url: group(match, 2),
            masked: true,
            children: parseInline(group(match, 1), { inLink: true }),
          },
  },
  {
    /* stops before trailing punctuation, which belongs to the sentence */
    pattern: /https?:\/\/[^\s<]*[^\s<.,:;"'!?)\]]/y,
    starts: "h",
    after: isNotWord,
    parse: (match, context) =>
      context.inLink
        ? null
        : {
            type: "link",
            url: match[0],
            masked: false,
            children: [{ type: "text", content: match[0] }],
          },
  },
  {
    pattern: /\|\|([^]+?)\|\|/y,
    starts: "|",
    parse: wrap("spoiler"),
  },
  {
    pattern: /\*\*([^]+?)\*\*(?!\*)/y,
    starts: "*",
    parse: wrap("strong"),
  },
  {
    pattern: /__([^]+?)__(?!_)/y,
    starts: "_",
    parse: wrap("underline"),
  },
  {
    /*
     * The two alternatives start differently and a bold run cannot hold a
     * `*`, so every input has one way through: an unclosed marker costs
     * linear time, not exponential.
     */
    pattern: /\*(?!\s)((?:[^*]|\*\*[^*]+\*\*)+?)\*(?!\*)/y,
    starts: "*",
    parse: wrap("em"),
  },
  {
    pattern: /_((?:[^_]|__[^_]+__)+?)_(?![\p{L}\p{N}_])/uy,
    starts: "_",
    after: isNotWord,
    parse: wrap("em"),
  },
  {
    pattern: /~~([^]+?)~~/y,
    starts: "~",
    parse: wrap("strike"),
  },
  {
    pattern: /@(everyone|here)(?![\p{L}\p{N}_])/uy,
    starts: "@",
    parse: (match) => ({
      type: "everyone",
      name: group(match, 1) === "here" ? "here" : "everyone",
    }),
  },
  {
    pattern: /\n/y,
    starts: "\n",
    parse: () => ({ type: "br" }),
  },
]

const RULE_STARTS = new Set(INLINE_RULES.map((rule) => rule.starts))

/** Parse the inline content of one block: formatting, links, mentions. */
export function parseInline(
  source: string,
  context: InlineContext = { inLink: false }
): MarkdownInline[] {
  const nodes: MarkdownInline[] = []
  let text = ""
  const flush = () => {
    if (text.length > 0) nodes.push({ type: "text", content: text })
    text = ""
  }

  let index = 0
  while (index < source.length) {
    const char = source[index] ?? ""
    let node: MarkdownInline | null = null
    let length = 0
    if (RULE_STARTS.has(char)) {
      for (const rule of INLINE_RULES) {
        if (rule.starts !== char) continue
        if (rule.after && !rule.after(source[index - 1])) continue
        rule.pattern.lastIndex = index
        const match = rule.pattern.exec(source)
        if (!match) continue
        node = rule.parse(match, context)
        if (node) {
          length = match[0].length
          break
        }
      }
    }
    if (node) {
      // An escape is text: let it join the run around it.
      if (node.type === "text") text += node.content
      else {
        flush()
        nodes.push(node)
      }
      index += length
    } else {
      text += char
      index += 1
    }
  }
  flush()
  return nodes
}

/* ------------------------------------------------------------------------ */
/* Blocks                                                                    */
/* ------------------------------------------------------------------------ */

/*
 * A fence may open and close on one line or span many. The language is the
 * word right after the opening fence, and only when a newline follows it —
 * "```js```" is a block that says `js`.
 */
const FENCE = /^```(?:([\w+#.-]+)[^\S\n]*\n|[^\S\n]*\n)?([^]*?)```[^\S\n]*\n?/
const HEADING = /^(#{1,3}) +(\S.*)$/
const SUBTEXT = /^-# +(\S.*)$/
const QUOTE_LINE = /^> (.*)$|^>$/
const QUOTE_REST = /^>>> /
const LIST_ITEM = /^([^\S\n]*)(?:[-*]|(\d{1,9})\.) +(\S.*)$/
/** How deep an indented item can nest; deeper ones join the last level. */
const MAX_LIST_DEPTH = 10

function isBlank(line: string): boolean {
  return line.trim().length === 0
}

function headingLevel(marks: number | undefined): 1 | 2 | 3 {
  if (marks === 3) return 3
  if (marks === 2) return 2
  return 1
}

interface BlockContext {
  /** Quotes do not nest: a `>` inside a quote is text. */
  inQuote: boolean
}

/*
 * Every line of a paragraph is a line on screen, blank ones included, as in
 * the client: a blank line before or after a list is a gap. A break at the
 * very end of a block draws nothing, so an empty last line takes a second one.
 */
function paragraph(lines: string[]): MarkdownBlock | null {
  if (lines.length === 0) return null
  const body = lines.join("\n") + (lines.at(-1) === "" ? "\n" : "")
  return { type: "paragraph", children: parseInline(body) }
}

function emptyList(item: RegExpExecArray): MarkdownList {
  const ordered = item[2] !== undefined
  return {
    type: "list",
    ordered,
    start: ordered ? Number(item[2]) : 1,
    items: [],
  }
}

/*
 * One list, and the lists indented inside it: an item indented further than
 * the one above nests under it, one indented less closes the levels it left.
 * At the top level a change between `-` and `1.` starts a new list.
 */
function parseList(
  first: RegExpExecArray,
  peek: () => string,
  advance: () => void,
  more: () => boolean
): MarkdownList {
  const root = emptyList(first)
  const levels = [{ indent: group(first, 1).length, list: root }]
  while (more()) {
    const item = LIST_ITEM.exec(peek())
    if (!item) break
    const indent = group(item, 1).length
    while (levels.length > 1 && indent < (levels.at(-1)?.indent ?? 0)) {
      levels.pop()
    }
    const level = levels.at(-1) ?? levels[0]
    if (!level) break
    const parent = level.list.items.at(-1)
    const node: MarkdownListItem = { children: parseInline(group(item, 3)) }
    if (indent > level.indent && parent && levels.length < MAX_LIST_DEPTH) {
      parent.sublist ??= emptyList(item)
      parent.sublist.items.push(node)
      levels.push({ indent, list: parent.sublist })
    } else {
      if (levels.length === 1 && (item[2] !== undefined) !== root.ordered) {
        break
      }
      level.list.items.push(node)
    }
    advance()
  }
  return root
}

/** Parse a whole message into blocks. */
export function parseMarkdown(
  source: string,
  context: BlockContext = { inQuote: false }
): MarkdownBlock[] {
  const blocks: MarkdownBlock[] = []
  let pending: string[] = []
  const flush = () => {
    const block = paragraph(pending)
    if (block) blocks.push(block)
    pending = []
  }

  // The client trims a message, so blank lines at either end draw nothing.
  let rest = source
    .replace(/\r\n?/g, "\n")
    .replace(/^(?:[^\S\n]*\n)+/, "")
    .replace(/(?:\n[^\S\n]*)+$/, "")
  /** The current line, without its newline. */
  const peek = () => {
    const end = rest.indexOf("\n")
    return end === -1 ? rest : rest.slice(0, end)
  }
  /** Drop the current line, newline included. */
  const advance = () => {
    const end = rest.indexOf("\n")
    rest = end === -1 ? "" : rest.slice(end + 1)
  }

  while (rest.length > 0) {
    const fence = FENCE.exec(rest)
    if (fence) {
      flush()
      blocks.push({
        type: "codeBlock",
        language: fence[1]?.toLowerCase(),
        content: (fence[2] ?? "").replace(/\n$/, ""),
      })
      rest = rest.slice(fence[0].length)
      continue
    }

    const line = peek()

    if (!context.inQuote) {
      // `>>> ` quotes everything after it, to the end of the message.
      if (QUOTE_REST.test(rest)) {
        flush()
        blocks.push({
          type: "quote",
          children: parseMarkdown(rest.slice(4), { inQuote: true }),
        })
        rest = ""
        break
      }
      if (QUOTE_LINE.test(line)) {
        flush()
        const quoted: string[] = []
        while (rest.length > 0) {
          const match = QUOTE_LINE.exec(peek())
          if (!match) break
          quoted.push(match[1] ?? "")
          advance()
        }
        blocks.push({
          type: "quote",
          children: parseMarkdown(quoted.join("\n"), { inQuote: true }),
        })
        continue
      }
    }

    const heading = HEADING.exec(line)
    if (heading) {
      flush()
      blocks.push({
        type: "heading",
        level: headingLevel(heading[1]?.length),
        children: parseInline(heading[2] ?? ""),
      })
      advance()
      // A heading takes the blank lines after it, as the client does.
      while (rest.length > 0 && isBlank(peek())) advance()
      continue
    }

    const subtext = SUBTEXT.exec(line)
    if (subtext) {
      flush()
      blocks.push({ type: "subtext", children: parseInline(subtext[1] ?? "") })
      advance()
      continue
    }

    const item = LIST_ITEM.exec(line)
    if (item) {
      flush()
      blocks.push(parseList(item, peek, advance, () => rest.length > 0))
      continue
    }

    // A fence that opens mid-line still starts a block, as in the client.
    const inlineFence = line.indexOf("```")
    if (inlineFence > 0 && FENCE.test(rest.slice(inlineFence))) {
      pending.push(line.slice(0, inlineFence))
      flush()
      rest = rest.slice(inlineFence)
      continue
    }

    pending.push(line)
    advance()
  }
  flush()
  return blocks
}

/*
 * Pictographs and what joins or modifies them: zero-width joiner, variation
 * selector, skin tones, and the regional indicators that pair into flags.
 * Not `Emoji_Component`, which also holds the digits, `#` and `*`.
 */
const EMOJI_ONLY =
  /^(?:\p{Extended_Pictographic}|\p{Emoji_Modifier}|\p{Regional_Indicator}|\u200d|\ufe0f)+$/u

/**
 * Whether a message is nothing but emoji — custom ones, or a few characters
 * of Unicode pictographs — which the client renders large.
 */
export function isEmojiOnly(blocks: readonly MarkdownBlock[]): boolean {
  if (blocks.length !== 1) return false
  const [block] = blocks
  if (block?.type !== "paragraph") return false
  let count = 0
  for (const node of block.children) {
    if (node.type === "emoji") count += 1
    else if (node.type === "text") {
      const stripped = node.content.replace(/\s+/g, "")
      if (stripped.length === 0) continue
      if (!EMOJI_ONLY.test(stripped)) return false
      count += [...stripped.matchAll(/\p{Extended_Pictographic}/gu)].length
      count += [...stripped.matchAll(/\p{Regional_Indicator}/gu)].length / 2
    } else return false
  }
  return count > 0 && count <= 30
}
<script setup lang="ts">
import { computed, provide, ref, type HTMLAttributes } from "vue"
import { Button } from "~~/registry/bases/newt/ui/button"
import {
  Modal,
  ModalBody,
  ModalContent,
  ModalFooter,
  ModalHeader,
  ModalTitle,
} from "~~/registry/bases/newt/ui/modal"

import { cn } from "@/lib/utils"

import {
  defaultMarkdownLabels,
  MARKDOWN_CONTEXT_KEY,
  type MarkdownLabels,
  type MarkdownResolveEmoji,
  type MarkdownResolveMention,
} from "."
import {
  isEmojiOnly,
  parseMarkdown,
  type MarkdownMentionKind,
} from "./markdown-syntax"
import MarkdownBlocks from "./MarkdownBlocks.vue"

/*
 * Renders a message written in chat markdown with the library's own parts.
 * The source is parsed, never injected as HTML.
 */
const props = withDefaults(
  defineProps<{
    class?: HTMLAttributes["class"]
    /** The message source, in chat markdown. */
    content: string
    /**
     * Name (and colour, avatar) for a mention id. Without it, or when it
     * returns nothing, a numeric id shows as `unknown-user` and a name shows
     * as written, so `<@username>` reads as `@username`.
     */
    resolveMention?: MarkdownResolveMention
    /**
     * Image URL for a server emoji. Without it, or when it returns nothing,
     * the emoji shows as its `:name:` text — newt/ui never fetches one itself.
     */
    resolveEmoji?: MarkdownResolveEmoji
    /**
     * Makes mentions buttons that emit `mention-click`. Off by default: they
     * are read-only text, out of the tab order.
     */
    interactiveMentions?: boolean
    /**
     * Added to a heading's level to pick its element: `#` with the default 2
     * is an `<h3>`, so a message never outranks the page around it.
     */
    headingOffset?: number
    /** Locale for timestamps. Defaults to the reader's. */
    locale?: string
    /**
     * Ask before opening a masked link (`[text](url)`), whose text hides its
     * address. On by default.
     */
    linkWarning?: boolean
    labels?: Partial<MarkdownLabels>
  }>(),
  { interactiveMentions: false, headingOffset: 2, linkWarning: true }
)

const emit = defineEmits<{
  (e: "mention-click", mention: { kind: MarkdownMentionKind; id: string }): void
}>()

const blocks = computed(() => parseMarkdown(props.content))
const labels = computed(() => ({ ...defaultMarkdownLabels, ...props.labels }))
const pendingUrl = ref<string | null>(null)
/*
 * The warning opens from a link, not from a `ModalTrigger`, so focus goes back
 * to whatever held it when the link was activated.
 */
let opener: HTMLElement | null = null

function returnFocus(event: Event) {
  event.preventDefault()
  if (opener?.isConnected) opener.focus()
}

provide(MARKDOWN_CONTEXT_KEY, () => ({
  resolveMention: props.resolveMention,
  resolveEmoji: props.resolveEmoji,
  mentionsInteractive: props.interactiveMentions,
  onMentionClick: (mention) => emit("mention-click", mention),
  headingOffset: props.headingOffset,
  locale: props.locale,
  labels: labels.value,
  jumbo: isEmojiOnly(blocks.value),
  interceptLink: (url, masked) => {
    if (!masked || !props.linkWarning) return false
    opener =
      document.activeElement instanceof HTMLElement
        ? document.activeElement
        : null
    pendingUrl.value = url
    return true
  },
}))

const warningOpen = computed({
  get: () => pendingUrl.value !== null,
  set: (open: boolean) => {
    if (!open) pendingUrl.value = null
  },
})

function visit() {
  if (pendingUrl.value) {
    window.open(pendingUrl.value, "_blank", "noopener,noreferrer")
  }
  pendingUrl.value = null
}
</script>

<template>
  <div :class="cn('min-w-0 break-words [overflow-wrap:anywhere]', props.class)">
    <MarkdownBlocks :blocks="blocks" />
    <Modal v-model:open="warningOpen">
      <ModalContent
        :aria-describedby="undefined"
        @close-auto-focus="returnFocus"
      >
        <ModalHeader>
          <ModalTitle>{{ labels.linkWarningTitle }}</ModalTitle>
        </ModalHeader>
        <ModalBody>
          <p class="m-0">{{ labels.linkWarningBody }}</p>
          <p
            class="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"
          >
            {{ pendingUrl }}
          </p>
        </ModalBody>
        <ModalFooter>
          <Button variant="secondary" @click="pendingUrl = null">
            {{ labels.linkWarningCancel }}
          </Button>
          <Button variant="primary" @click="visit">
            {{ labels.linkWarningConfirm }}
          </Button>
        </ModalFooter>
      </ModalContent>
    </Modal>
  </div>
</template>
<script setup lang="ts">
import { computed, inject } from "vue"
import {
  CodeBlock,
  type CodeLanguage,
} from "~~/registry/bases/newt/ui/code-block"

import { cn } from "@/lib/utils"

import { HEADING_SIZES, HIGHLIGHTED_LANGUAGES, MARKDOWN_CONTEXT_KEY } from "."
import type { MarkdownBlock } from "./markdown-syntax"
import MarkdownInline from "./MarkdownInline.vue"

const props = withDefaults(
  defineProps<{
    blocks: readonly MarkdownBlock[]
    /** How many lists hold these blocks; picks the bullet. */
    depth?: number
  }>(),
  { depth: 0 }
)

/* The client's bullets by depth: disc, then circle, then square. */
const BULLETS = ["list-disc", "list-[circle]", "list-[square]"] as const

function bullet(depth: number): string {
  return BULLETS[Math.min(depth, BULLETS.length - 1)] ?? "list-disc"
}

const useContext = inject(MARKDOWN_CONTEXT_KEY)
const context = computed(() => useContext?.())

function headingTag(level: 1 | 2 | 3): string {
  return `h${Math.min(6, level + (context.value?.headingOffset ?? 2))}`
}

function language(value: string | undefined): CodeLanguage | undefined {
  // SAFETY: membership in `HIGHLIGHTED_LANGUAGES` is exactly `CodeLanguage`.
  return value !== undefined && HIGHLIGHTED_LANGUAGES.has(value)
    ? (value as CodeLanguage)
    : undefined
}
</script>

<template>
  <template v-for="(block, index) in props.blocks" :key="index">
    <p
      v-if="block.type === 'paragraph'"
      :class="
        cn(
          'm-0 whitespace-pre-wrap',
          context?.jumbo && 'text-5xl leading-tight'
        )
      "
    >
      <MarkdownInline :nodes="block.children" />
    </p>
    <component
      :is="headingTag(block.level)"
      v-else-if="block.type === 'heading'"
      :class="
        cn(
          'mb-1 mt-2 whitespace-pre-wrap font-bold leading-[1.375] text-newt-text-primary first:mt-0',
          HEADING_SIZES[block.level]
        )
      "
    >
      <MarkdownInline :nodes="block.children" />
    </component>
    <p
      v-else-if="block.type === 'subtext'"
      class="m-0 whitespace-pre-wrap text-[13px] leading-[1.3] text-newt-text-muted"
    >
      <MarkdownInline :nodes="block.children" />
    </p>
    <blockquote
      v-else-if="block.type === 'quote'"
      class="my-0.5 border-0 border-s-4 border-solid border-newt-border ps-3"
    >
      <MarkdownBlocks :blocks="block.children" />
    </blockquote>
    <component
      :is="block.ordered ? 'ol' : 'ul'"
      v-else-if="block.type === 'list'"
      :start="block.ordered && block.start !== 1 ? block.start : undefined"
      :class="
        cn('mb-0 mt-1 ps-4', block.ordered ? 'list-decimal' : bullet(depth))
      "
    >
      <li
        v-for="(item, itemIndex) in block.items"
        :key="itemIndex"
        class="mb-1 whitespace-pre-wrap"
      >
        <MarkdownInline :nodes="item.children" />
        <MarkdownBlocks
          v-if="item.sublist"
          :blocks="[item.sublist]"
          :depth="depth + 1"
        />
      </li>
    </component>
    <template v-else-if="block.type === 'codeBlock'">
      <CodeBlock
        v-if="language(block.language)"
        class="my-1.5"
        :language="language(block.language)"
        :code="block.content"
      />
      <CodeBlock v-else class="my-1.5">{{ block.content }}</CodeBlock>
    </template>
  </template>
</template>
<script setup lang="ts">
import { computed, inject } from "vue"
import { CustomEmoji } from "~~/registry/bases/newt/ui/custom-emoji"
import { InlineCode } from "~~/registry/bases/newt/ui/inline-code"
import { Mention } from "~~/registry/bases/newt/ui/mention"
import { Spoiler } from "~~/registry/bases/newt/ui/spoiler"
import { Timestamp } from "~~/registry/bases/newt/ui/timestamp"

import { MARKDOWN_CONTEXT_KEY, MENTION_PREFIX, mentionTarget } from "."
import type { MarkdownInline as MarkdownInlineNode } from "./markdown-syntax"

const props = defineProps<{ nodes: readonly MarkdownInlineNode[] }>()

const useContext = inject(MARKDOWN_CONTEXT_KEY)
const context = computed(() => useContext?.())

function onLinkClick(event: MouseEvent, url: string, masked: boolean) {
  if (context.value?.interceptLink(url, masked)) event.preventDefault()
}

function emojiSrc(node: MarkdownInlineNode): string | undefined {
  return node.type === "emoji" ? context.value?.resolveEmoji?.(node) : undefined
}
</script>

<template>
  <template v-for="(node, index) in props.nodes" :key="index">
    <template v-if="node.type === 'text'">{{ node.content }}</template>
    <br v-else-if="node.type === 'br'" />
    <strong v-else-if="node.type === 'strong'" class="font-bold">
      <MarkdownInline :nodes="node.children" />
    </strong>
    <em v-else-if="node.type === 'em'"
      ><MarkdownInline :nodes="node.children"
    /></em>
    <span v-else-if="node.type === 'underline'" class="underline">
      <MarkdownInline :nodes="node.children" />
    </span>
    <s v-else-if="node.type === 'strike'"
      ><MarkdownInline :nodes="node.children"
    /></s>
    <Spoiler
      v-else-if="node.type === 'spoiler'"
      :label="context?.labels.spoiler"
    >
      <MarkdownInline :nodes="node.children" />
    </Spoiler>
    <InlineCode v-else-if="node.type === 'code'">{{ node.content }}</InlineCode>
    <a
      v-else-if="node.type === 'link'"
      :href="node.url"
      target="_blank"
      rel="noopener noreferrer"
      :title="node.masked ? node.url : undefined"
      class="text-newt-text-link no-underline hover:underline"
      @click="onLinkClick($event, node.url, node.masked)"
    >
      <MarkdownInline :nodes="node.children" />
    </a>
    <Mention
      v-else-if="node.type === 'mention' && context"
      :as="context.mentionsInteractive ? 'button' : 'span'"
      :variant="node.kind"
      :color="
        node.kind === 'role'
          ? mentionTarget(context, node.kind, node.id).color
          : undefined
      "
      :avatar="
        node.kind === 'user'
          ? mentionTarget(context, node.kind, node.id).avatar
          : undefined
      "
      @click="
        context.mentionsInteractive &&
        context.onMentionClick({ kind: node.kind, id: node.id })
      "
      >{{ MENTION_PREFIX[node.kind]
      }}{{ mentionTarget(context, node.kind, node.id).name }}</Mention
    >
    <Mention v-else-if="node.type === 'everyone'" as="span" variant="user"
      >@{{ node.name }}</Mention
    >
    <Mention v-else-if="node.type === 'command'" as="span" variant="app"
      >/{{ node.name }}</Mention
    >
    <template v-else-if="node.type === 'emoji'">
      <CustomEmoji
        v-if="emojiSrc(node)"
        :name="node.name"
        :src="emojiSrc(node) ?? ''"
        :size="context?.jumbo ? 'jumbo' : 'inline'"
      />
      <template v-else>:{{ node.name }}:</template>
    </template>
    <Timestamp
      v-else-if="node.type === 'timestamp'"
      :value="node.value"
      :format="node.format"
      :locale="context?.locale"
    />
  </template>
</template>
/*
 * The chat markdown a message is written in, parsed into a small tree the
 * `Markdown` component renders with the library's own parts: `Mention`,
 * `InlineCode`, `Timestamp`, `Spoiler`, `CodeBlock`, `CustomEmoji`.
 *
 * It is a parser for one dialect, not for CommonMark: single newlines are line
 * breaks, blank lines stay blank, `__` underlines, `||` hides a spoiler, `-#`
 * is subtext, an indented list item nests under the one above it, and the
 * angle-bracket tokens (`<@id>`, `<#id>`, `<t:1700000000:R>`) are mentions,
 * channels and timestamps. Anything it does not recognise stays text, and no
 * HTML in the source is ever interpreted — the output is data, not markup.
 *
 * This file is framework-free and shipped byte-for-byte in both the React and
 * the Vue registry, so the two renderers read the same tree.
 */

/** The letters a `<t:…:X>` token takes, mapped to `Timestamp` formats. */
export const TIMESTAMP_FORMATS = {
  t: "shortTime",
  T: "longTime",
  d: "shortDate",
  D: "longDate",
  f: "shortDateTime",
  F: "longDateTime",
  R: "relative",
} as const

export type TimestampLetter = keyof typeof TIMESTAMP_FORMATS

/** The largest instant a `Date` can hold, in seconds either side of 1970. */
const MAX_TIMESTAMP_SECONDS = 8_640_000_000_000

export type MarkdownMentionKind = "user" | "role" | "channel"

export type MarkdownInline =
  | { type: "text"; content: string }
  | { type: "br" }
  | {
      type: "strong" | "em" | "underline" | "strike" | "spoiler"
      children: MarkdownInline[]
    }
  | { type: "code"; content: string }
  | {
      type: "link"
      url: string
      /** `[label](url)`: the visible text is not the address. */
      masked: boolean
      children: MarkdownInline[]
    }
  | { type: "mention"; kind: MarkdownMentionKind; id: string }
  | { type: "everyone"; name: "everyone" | "here" }
  | { type: "command"; name: string; id: string }
  | { type: "emoji"; name: string; id: string; animated: boolean }
  | {
      type: "timestamp"
      /** Seconds since the epoch, as the token writes it. */
      value: number
      format: (typeof TIMESTAMP_FORMATS)[TimestampLetter]
    }

export interface MarkdownListItem {
  children: MarkdownInline[]
  /** The items written indented under this one. */
  sublist?: MarkdownList
}

export interface MarkdownList {
  type: "list"
  ordered: boolean
  /** The first number of an ordered list. */
  start: number
  items: MarkdownListItem[]
}

export type MarkdownBlock =
  | { type: "paragraph"; children: MarkdownInline[] }
  | { type: "heading"; level: 1 | 2 | 3; children: MarkdownInline[] }
  | { type: "subtext"; children: MarkdownInline[] }
  | { type: "quote"; children: MarkdownBlock[] }
  | MarkdownList
  | { type: "codeBlock"; language?: string; content: string }

/* ------------------------------------------------------------------------ */
/* Inline                                                                    */
/* ------------------------------------------------------------------------ */

interface InlineContext {
  /** Inside a link label: no nested links, no bare URLs. */
  inLink: boolean
}

interface InlineRule {
  /** Sticky, so `exec` only matches at `lastIndex`. */
  pattern: RegExp
  /** Characters a match can start with; a cheap filter before the regex. */
  starts: string
  /** Reject a match by the character before it (`snake_case` is not italic). */
  after?: (previous: string | undefined) => boolean
  parse: (
    match: RegExpExecArray,
    context: InlineContext
  ) => MarkdownInline | null
}

const WORD = /[\p{L}\p{N}_]/u

function isNotWord(previous: string | undefined): boolean {
  return previous === undefined || !WORD.test(previous)
}

function group(match: RegExpExecArray, index: number): string {
  return match[index] ?? ""
}

function wrap(
  type: "strong" | "em" | "underline" | "strike" | "spoiler"
): InlineRule["parse"] {
  return (match, context) => {
    const inner = group(match, 1)
    // `_ _` is kept: a run of nothing but spaces is how a message writes an
    // empty line. An empty spoiler would be a control with nothing to reveal.
    if (type === "spoiler" && inner.trim().length === 0) return null
    return { type, children: parseInline(inner, context) }
  }
}

/*
 * Order matters where two rules share a start: `**` before `*`, `__` before
 * `_`, the double-backtick code span before the single one, and a role
 * mention (`<@&`) before a user mention (`<@`).
 */
const INLINE_RULES: readonly InlineRule[] = [
  {
    pattern: /\\([^\p{L}\p{N}\s])/uy,
    starts: "\\",
    parse: (match) => ({ type: "text", content: group(match, 1) }),
  },
  {
    pattern: /``(?: (?=\S))?([^]+?)(?: )?``/y,
    starts: "`",
    parse: (match) => ({ type: "code", content: group(match, 1) }),
  },
  {
    pattern: /`([^`]+)`/y,
    starts: "`",
    parse: (match) => ({ type: "code", content: group(match, 1) }),
  },
  {
    pattern: /<(a?):(\w{2,32}):(\d+)>/y,
    starts: "<",
    parse: (match) => ({
      type: "emoji",
      animated: group(match, 1) === "a",
      name: group(match, 2),
      id: group(match, 3),
    }),
  },
  {
    pattern: /<t:(-?\d{1,13})(?::([tTdDfFR]))?>/y,
    starts: "<",
    parse: (match) => {
      const letter = match[2] ?? "f"
      const format =
        Object.entries(TIMESTAMP_FORMATS).find(
          ([key]) => key === letter
        )?.[1] ?? TIMESTAMP_FORMATS.f
      const value = Number(group(match, 1))
      // Beyond this a `Date` is invalid, and formatting it throws.
      if (Math.abs(value) > MAX_TIMESTAMP_SECONDS) return null
      return { type: "timestamp", value, format }
    },
  },
  {
    pattern: /<@&([^<>\s]+)>/y,
    starts: "<",
    parse: (match) => ({ type: "mention", kind: "role", id: group(match, 1) }),
  },
  {
    pattern: /<@!?([^<>\s&!][^<>\s]*)>/y,
    starts: "<",
    parse: (match) => ({ type: "mention", kind: "user", id: group(match, 1) }),
  },
  {
    pattern: /<#([^<>\s]+)>/y,
    starts: "<",
    parse: (match) => ({
      type: "mention",
      kind: "channel",
      id: group(match, 1),
    }),
  },
  {
    pattern: /<\/([\p{L}\p{N}_-]+(?: [\p{L}\p{N}_-]+){0,2}):(\d+)>/uy,
    starts: "<",
    parse: (match) => ({
      type: "command",
      name: group(match, 1),
      id: group(match, 2),
    }),
  },
  {
    pattern: /<(https?:\/\/[^\s<>]+)>/y,
    starts: "<",
    parse: (match, context) =>
      context.inLink
        ? null
        : {
            type: "link",
            url: group(match, 1),
            masked: false,
            children: [{ type: "text", content: group(match, 1) }],
          },
  },
  {
    pattern:
      /\[((?:\\.|[^[\]\\\n])+)\]\(\s*<?(https?:\/\/[^\s<>()]+(?:\([^\s<>()]*\)[^\s<>()]*)*)>?\s*\)/y,
    starts: "[",
    parse: (match, context) =>
      context.inLink
        ? null
        : {
            type: "link",
            url: group(match, 2),
            masked: true,
            children: parseInline(group(match, 1), { inLink: true }),
          },
  },
  {
    /* stops before trailing punctuation, which belongs to the sentence */
    pattern: /https?:\/\/[^\s<]*[^\s<.,:;"'!?)\]]/y,
    starts: "h",
    after: isNotWord,
    parse: (match, context) =>
      context.inLink
        ? null
        : {
            type: "link",
            url: match[0],
            masked: false,
            children: [{ type: "text", content: match[0] }],
          },
  },
  {
    pattern: /\|\|([^]+?)\|\|/y,
    starts: "|",
    parse: wrap("spoiler"),
  },
  {
    pattern: /\*\*([^]+?)\*\*(?!\*)/y,
    starts: "*",
    parse: wrap("strong"),
  },
  {
    pattern: /__([^]+?)__(?!_)/y,
    starts: "_",
    parse: wrap("underline"),
  },
  {
    /*
     * The two alternatives start differently and a bold run cannot hold a
     * `*`, so every input has one way through: an unclosed marker costs
     * linear time, not exponential.
     */
    pattern: /\*(?!\s)((?:[^*]|\*\*[^*]+\*\*)+?)\*(?!\*)/y,
    starts: "*",
    parse: wrap("em"),
  },
  {
    pattern: /_((?:[^_]|__[^_]+__)+?)_(?![\p{L}\p{N}_])/uy,
    starts: "_",
    after: isNotWord,
    parse: wrap("em"),
  },
  {
    pattern: /~~([^]+?)~~/y,
    starts: "~",
    parse: wrap("strike"),
  },
  {
    pattern: /@(everyone|here)(?![\p{L}\p{N}_])/uy,
    starts: "@",
    parse: (match) => ({
      type: "everyone",
      name: group(match, 1) === "here" ? "here" : "everyone",
    }),
  },
  {
    pattern: /\n/y,
    starts: "\n",
    parse: () => ({ type: "br" }),
  },
]

const RULE_STARTS = new Set(INLINE_RULES.map((rule) => rule.starts))

/** Parse the inline content of one block: formatting, links, mentions. */
export function parseInline(
  source: string,
  context: InlineContext = { inLink: false }
): MarkdownInline[] {
  const nodes: MarkdownInline[] = []
  let text = ""
  const flush = () => {
    if (text.length > 0) nodes.push({ type: "text", content: text })
    text = ""
  }

  let index = 0
  while (index < source.length) {
    const char = source[index] ?? ""
    let node: MarkdownInline | null = null
    let length = 0
    if (RULE_STARTS.has(char)) {
      for (const rule of INLINE_RULES) {
        if (rule.starts !== char) continue
        if (rule.after && !rule.after(source[index - 1])) continue
        rule.pattern.lastIndex = index
        const match = rule.pattern.exec(source)
        if (!match) continue
        node = rule.parse(match, context)
        if (node) {
          length = match[0].length
          break
        }
      }
    }
    if (node) {
      // An escape is text: let it join the run around it.
      if (node.type === "text") text += node.content
      else {
        flush()
        nodes.push(node)
      }
      index += length
    } else {
      text += char
      index += 1
    }
  }
  flush()
  return nodes
}

/* ------------------------------------------------------------------------ */
/* Blocks                                                                    */
/* ------------------------------------------------------------------------ */

/*
 * A fence may open and close on one line or span many. The language is the
 * word right after the opening fence, and only when a newline follows it —
 * "```js```" is a block that says `js`.
 */
const FENCE = /^```(?:([\w+#.-]+)[^\S\n]*\n|[^\S\n]*\n)?([^]*?)```[^\S\n]*\n?/
const HEADING = /^(#{1,3}) +(\S.*)$/
const SUBTEXT = /^-# +(\S.*)$/
const QUOTE_LINE = /^> (.*)$|^>$/
const QUOTE_REST = /^>>> /
const LIST_ITEM = /^([^\S\n]*)(?:[-*]|(\d{1,9})\.) +(\S.*)$/
/** How deep an indented item can nest; deeper ones join the last level. */
const MAX_LIST_DEPTH = 10

function isBlank(line: string): boolean {
  return line.trim().length === 0
}

function headingLevel(marks: number | undefined): 1 | 2 | 3 {
  if (marks === 3) return 3
  if (marks === 2) return 2
  return 1
}

interface BlockContext {
  /** Quotes do not nest: a `>` inside a quote is text. */
  inQuote: boolean
}

/*
 * Every line of a paragraph is a line on screen, blank ones included, as in
 * the client: a blank line before or after a list is a gap. A break at the
 * very end of a block draws nothing, so an empty last line takes a second one.
 */
function paragraph(lines: string[]): MarkdownBlock | null {
  if (lines.length === 0) return null
  const body = lines.join("\n") + (lines.at(-1) === "" ? "\n" : "")
  return { type: "paragraph", children: parseInline(body) }
}

function emptyList(item: RegExpExecArray): MarkdownList {
  const ordered = item[2] !== undefined
  return {
    type: "list",
    ordered,
    start: ordered ? Number(item[2]) : 1,
    items: [],
  }
}

/*
 * One list, and the lists indented inside it: an item indented further than
 * the one above nests under it, one indented less closes the levels it left.
 * At the top level a change between `-` and `1.` starts a new list.
 */
function parseList(
  first: RegExpExecArray,
  peek: () => string,
  advance: () => void,
  more: () => boolean
): MarkdownList {
  const root = emptyList(first)
  const levels = [{ indent: group(first, 1).length, list: root }]
  while (more()) {
    const item = LIST_ITEM.exec(peek())
    if (!item) break
    const indent = group(item, 1).length
    while (levels.length > 1 && indent < (levels.at(-1)?.indent ?? 0)) {
      levels.pop()
    }
    const level = levels.at(-1) ?? levels[0]
    if (!level) break
    const parent = level.list.items.at(-1)
    const node: MarkdownListItem = { children: parseInline(group(item, 3)) }
    if (indent > level.indent && parent && levels.length < MAX_LIST_DEPTH) {
      parent.sublist ??= emptyList(item)
      parent.sublist.items.push(node)
      levels.push({ indent, list: parent.sublist })
    } else {
      if (levels.length === 1 && (item[2] !== undefined) !== root.ordered) {
        break
      }
      level.list.items.push(node)
    }
    advance()
  }
  return root
}

/** Parse a whole message into blocks. */
export function parseMarkdown(
  source: string,
  context: BlockContext = { inQuote: false }
): MarkdownBlock[] {
  const blocks: MarkdownBlock[] = []
  let pending: string[] = []
  const flush = () => {
    const block = paragraph(pending)
    if (block) blocks.push(block)
    pending = []
  }

  // The client trims a message, so blank lines at either end draw nothing.
  let rest = source
    .replace(/\r\n?/g, "\n")
    .replace(/^(?:[^\S\n]*\n)+/, "")
    .replace(/(?:\n[^\S\n]*)+$/, "")
  /** The current line, without its newline. */
  const peek = () => {
    const end = rest.indexOf("\n")
    return end === -1 ? rest : rest.slice(0, end)
  }
  /** Drop the current line, newline included. */
  const advance = () => {
    const end = rest.indexOf("\n")
    rest = end === -1 ? "" : rest.slice(end + 1)
  }

  while (rest.length > 0) {
    const fence = FENCE.exec(rest)
    if (fence) {
      flush()
      blocks.push({
        type: "codeBlock",
        language: fence[1]?.toLowerCase(),
        content: (fence[2] ?? "").replace(/\n$/, ""),
      })
      rest = rest.slice(fence[0].length)
      continue
    }

    const line = peek()

    if (!context.inQuote) {
      // `>>> ` quotes everything after it, to the end of the message.
      if (QUOTE_REST.test(rest)) {
        flush()
        blocks.push({
          type: "quote",
          children: parseMarkdown(rest.slice(4), { inQuote: true }),
        })
        rest = ""
        break
      }
      if (QUOTE_LINE.test(line)) {
        flush()
        const quoted: string[] = []
        while (rest.length > 0) {
          const match = QUOTE_LINE.exec(peek())
          if (!match) break
          quoted.push(match[1] ?? "")
          advance()
        }
        blocks.push({
          type: "quote",
          children: parseMarkdown(quoted.join("\n"), { inQuote: true }),
        })
        continue
      }
    }

    const heading = HEADING.exec(line)
    if (heading) {
      flush()
      blocks.push({
        type: "heading",
        level: headingLevel(heading[1]?.length),
        children: parseInline(heading[2] ?? ""),
      })
      advance()
      // A heading takes the blank lines after it, as the client does.
      while (rest.length > 0 && isBlank(peek())) advance()
      continue
    }

    const subtext = SUBTEXT.exec(line)
    if (subtext) {
      flush()
      blocks.push({ type: "subtext", children: parseInline(subtext[1] ?? "") })
      advance()
      continue
    }

    const item = LIST_ITEM.exec(line)
    if (item) {
      flush()
      blocks.push(parseList(item, peek, advance, () => rest.length > 0))
      continue
    }

    // A fence that opens mid-line still starts a block, as in the client.
    const inlineFence = line.indexOf("```")
    if (inlineFence > 0 && FENCE.test(rest.slice(inlineFence))) {
      pending.push(line.slice(0, inlineFence))
      flush()
      rest = rest.slice(inlineFence)
      continue
    }

    pending.push(line)
    advance()
  }
  flush()
  return blocks
}

/*
 * Pictographs and what joins or modifies them: zero-width joiner, variation
 * selector, skin tones, and the regional indicators that pair into flags.
 * Not `Emoji_Component`, which also holds the digits, `#` and `*`.
 */
const EMOJI_ONLY =
  /^(?:\p{Extended_Pictographic}|\p{Emoji_Modifier}|\p{Regional_Indicator}|\u200d|\ufe0f)+$/u

/**
 * Whether a message is nothing but emoji — custom ones, or a few characters
 * of Unicode pictographs — which the client renders large.
 */
export function isEmojiOnly(blocks: readonly MarkdownBlock[]): boolean {
  if (blocks.length !== 1) return false
  const [block] = blocks
  if (block?.type !== "paragraph") return false
  let count = 0
  for (const node of block.children) {
    if (node.type === "emoji") count += 1
    else if (node.type === "text") {
      const stripped = node.content.replace(/\s+/g, "")
      if (stripped.length === 0) continue
      if (!EMOJI_ONLY.test(stripped)) return false
      count += [...stripped.matchAll(/\p{Extended_Pictographic}/gu)].length
      count += [...stripped.matchAll(/\p{Regional_Indicator}/gu)].length / 2
    } else return false
  }
  return count > 0 && count <= 30
}
import type { InjectionKey } from "vue"

import type { MarkdownMentionKind } from "./markdown-syntax"

export { default as Markdown } from "./Markdown.vue"
export {
  isEmojiOnly,
  parseInline,
  parseMarkdown,
  type MarkdownBlock,
  type MarkdownInline,
  type MarkdownMentionKind,
} from "./markdown-syntax"

/** What a mention id resolves to: the name to show, and a role's colour. */
export interface MarkdownMentionTarget {
  name: string
  /** Role colour, any CSS colour. */
  color?: string
  /** User avatar URL. */
  avatar?: string
}

/** The words the renderer writes itself. Pass a translation for any of them. */
export interface MarkdownLabels {
  /** Shown for a mention the resolver does not know. */
  unknownUser: string
  unknownRole: string
  unknownChannel: string
  /** Title of the warning before a masked link opens. */
  linkWarningTitle: string
  /** Text above the address in that warning. */
  linkWarningBody: string
  linkWarningCancel: string
  linkWarningConfirm: string
  /** Accessible name of a hidden spoiler, read in place of its content. */
  spoiler: string
}

export const defaultMarkdownLabels: MarkdownLabels = {
  unknownUser: "unknown-user",
  unknownRole: "unknown-role",
  unknownChannel: "unknown-channel",
  linkWarningTitle: "Leaving this page",
  linkWarningBody: "This link's text does not show where it goes. It opens:",
  linkWarningCancel: "Go back",
  linkWarningConfirm: "Visit site",
  spoiler: "Spoiler, click to reveal",
}

export type MarkdownResolveMention = (
  kind: MarkdownMentionKind,
  id: string
) => MarkdownMentionTarget | undefined

export type MarkdownResolveEmoji = (emoji: {
  id: string
  name: string
  animated: boolean
}) => string | undefined

/** Everything the recursive parts need from the `Markdown` that holds them. */
export interface MarkdownContext {
  resolveMention?: MarkdownResolveMention
  resolveEmoji?: MarkdownResolveEmoji
  mentionsInteractive: boolean
  onMentionClick: (mention: { kind: MarkdownMentionKind; id: string }) => void
  headingOffset: number
  locale?: string
  labels: MarkdownLabels
  jumbo: boolean
  /** Called for a masked link click; returns whether it took the click. */
  interceptLink: (url: string, masked: boolean) => boolean
}

export const MARKDOWN_CONTEXT_KEY: InjectionKey<() => MarkdownContext> =
  Symbol("newt-markdown")

/** The name a mention shows: resolved, written as a name, or unknown. */
export function mentionTarget(
  context: MarkdownContext,
  kind: MarkdownMentionKind,
  id: string
): MarkdownMentionTarget {
  const resolved = context.resolveMention?.(kind, id)
  if (resolved) return resolved
  if (!/^\d+$/.test(id)) return { name: id }
  const unknown = {
    user: context.labels.unknownUser,
    role: context.labels.unknownRole,
    channel: context.labels.unknownChannel,
  }
  return { name: unknown[kind] }
}

export const MENTION_PREFIX = { user: "@", role: "@", channel: "#" } as const

/* The languages `CodeBlock` colours; anything else renders as plain text. */
export const HIGHLIGHTED_LANGUAGES: ReadonlySet<string> = new Set([
  "ts",
  "tsx",
  "js",
  "jsx",
  "json",
  "bash",
  "sh",
])

export const HEADING_SIZES = {
  1: "text-2xl",
  2: "text-xl",
  3: "text-base",
} as const

Update the import paths

The files import @/lib/utils and sibling components through the aliases in your components.json. Point them at wherever those live in your project.

No CLI, no components.json: paste this into Claude, Cursor, Copilot or any coding assistant and it adds Markdown to your React project by hand. The prompt carries the source of every file the CLI would write — this component's and those of the components it builds on — with the imports already pointed at the default aliases.

No CLI, no components.json: paste this into Claude, Cursor, Copilot or any coding assistant and it adds Markdown to your Vue project by hand. The prompt carries the source of every file the CLI would write — this component's and those of the components it builds on — with the imports already pointed at the default aliases.

Usage

import { Markdown } from "@/components/ui/markdown"

export function Example() {
  return <Markdown />
}
<script setup lang="ts">
import { Markdown, MarkdownBlocks, MarkdownInline } from "@/components/ui/markdown"
</script>

<template>
  <Markdown />
</template>

Mentions, roles and channels arrive as ids. Pass resolveMention to turn an id into a name (and a role colour, or a user avatar); an id it does not know renders as unknown-user, unknown-role or unknown-channel. A token that carries a name instead of an id, such as <@username>, renders as written.

Server emoji render as their :name: text until you pass resolveEmoji, which returns the image URL for an emoji’s id. newt/ui never fetches an image on its own. A message made only of emoji renders them large.

The parser is exported too, from markdown-syntax.ts, for code that needs the tree without rendering it — a search index, a plain-text preview:

import { parseMarkdown } from "@/components/ui/markdown-syntax"

parseMarkdown("**hi** <@1001>")
// [{ type: "paragraph", children: [{ type: "strong", … }, …] }]

API reference

Markdown

PropType
content?string

The message source, in chat markdown.

Typestring
resolveMention?(kind, id) => MarkdownMentionTarget | undefined

`kind` is user, role or channel; returns `{ name, color?, avatar? }`: name, role colour and avatar for a mention id. Unknown numeric ids show the unknown label; names show as written.

Type(kind, id) => MarkdownMentionTarget | undefined
resolveEmoji?(emoji) => string | undefined

`emoji` is `{ id, name, animated }`. Returns the image URL for a server emoji. Without it the emoji shows as :name: text.

Type(emoji) => string | undefined
onMentionClick / @mention-click?(mention: { kind; id }) => void

Makes mentions buttons. In Vue, also set `interactiveMentions`. Without it they are read-only text, out of the tab order.

Type(mention: { kind; id }) => void
headingOffset?number

Added to a heading's level to pick its element, so # renders an <h3> and a message never outranks the page.

Typenumber
Default2
locale?string

Locale for timestamps. Defaults to the reader's.

Typestring
linkWarning?boolean

Ask before opening a masked link ([text](url)), whose text hides its address.

Typeboolean
Defaulttrue
labels?Partial<MarkdownLabels>

Translations for the words the renderer writes itself: the unknown-mention labels, the link warning and the accessible name of a hidden spoiler (`spoiler`).

TypePartial<MarkdownLabels>

The registry exports Markdown, defaultMarkdownLabels and, from markdown-syntax, parseMarkdown, parseInline and isEmojiOnly.

Accessibility

Headings start two levels down by default, so a # inside a message is an <h3> under the page’s own headings; change headingOffset to fit your outline. Read-only mentions are text rather than buttons, so a feed of messages does not add a tab stop per mention. A masked link opens a dialog that shows the full address before leaving the page. The dialog takes focus when it opens, keeps Tab inside it, closes on Escape and hands focus back to the link. A hidden spoiler is announced by its spoiler label rather than by what it hides. Translate every label through labels when the page is not in English.

Translating labels lists every English default.

Tokens

Markdown reads its colours, radii and motion from the --newt-* tokens installed with the library. Override a token and every component that reads it follows, including this one — see the token layer.

Changelog

  1. feataccessible and themed Spoiler, Modal and CodeBlock#57
  2. fixlay out markdown messages the way Discord does#58