Skip to documentation

Design system / Sources & standards

Current repository source

basic-markdown.tsx

src/components/ui/basic-markdown.tsx

This view contains the escaped source read during the deployment build. Code and policy text are unchanged. Markdown is shown as source, not rendered as a document. A new deployment refreshes the content.

"use client";

import { useMemo } from "react";

type BasicMarkdownProps = {
  /** Raw markdown text. Supports **bold**, *italic*, [links](url), and newlines. */
  children: string;
  /** Optional className applied to the wrapper <div>. */
  className?: string;
};

/**
 * Renders a limited subset of markdown:
 * - **bold** → <strong>
 * - *italic* → <em>
 * - [text](url) → <a target="_blank" rel="noopener noreferrer">
 *
 * Newlines and whitespace are preserved via CSS white-space: pre-wrap —
 * no <p> or <br> conversion needed.
 *
 * HTML in the input is escaped. No external dependencies.
 */
export function BasicMarkdown({ children, className }: BasicMarkdownProps) {
  const html = useMemo(() => renderBasicMarkdown(children), [children]);

  return (
    <div
      className={`whitespace-pre-wrap ${className ?? ""}`}
      dangerouslySetInnerHTML={{ __html: html }}
    />
  );
}

// ── Renderer (pure function, no React dependency) ────────────────────────────

function renderBasicMarkdown(raw: string): string {
  // 0. Normalize line endings (handle \r\n, \r, \n consistently)
  let text = raw.replace(/\r\n/g, "\n").replace(/\r/g, "\n");

  // 1. Escape any existing HTML to prevent injection
  text = escapeHtml(text);

  // 2. Bold: **text** or __text__
  text = text.replace(/\*\*(.+?)\*\*/g, "<strong>$1</strong>");
  text = text.replace(/__(.+?)__/g, "<strong>$1</strong>");

  // 3. Italic: *text* or _text_ (but not inside words)
  text = text.replace(/(?<!\*)\*([^*\n]+?)\*(?!\*)/g, "<em>$1</em>");
  text = text.replace(/(?<!_)_([^_\n]+?)_(?!_)/g, "<em>$1</em>");

  // 4. Links: [text](url)
  text = text.replace(
    /\[([^\]]+)\]\(([^)]+)\)/g,
    (_match, label: string, href: string) => {
      const normalizedHref = href.trim();
      if (!isSafeMarkdownHref(normalizedHref)) return label;
      return `<a href="${normalizedHref}" target="_blank" rel="noopener noreferrer" class="underline underline-offset-2">${label}</a>`;
    },
  );

  return text;
}

function isSafeMarkdownHref(href: string): boolean {
  if (/^https?:\/\//i.test(href)) return true;
  if (href.startsWith("/") && !href.startsWith("//")) return true;
  return href.startsWith("./") || href.startsWith("../") || href.startsWith("#") || href.startsWith("?");
}

function escapeHtml(str: string): string {
  return str
    .replace(/&/g, "&amp;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;")
    .replace(/"/g, "&quot;")
    .replace(/'/g, "&#039;");
}
All sources and standards
Current components and theme tokens. Fictional example data. Source views refresh on deployment; authors maintain contract notes.