UIPackage React Native
Search

Markdown

Read-only native CommonMark rendering with safe caller-owned links, code and opt-in bounded image blocks.

Install

First install? Set up the registry in your app.

npx --yes --package=https://native.uipkge.dev/cli/uipkge-native-0.1.1.tgz uipkge-native add markdown

Source files

Expand a file to read the source the installer copies into your app.

components/ui/markdown/Markdown.tsx
import * as React from 'react'
import { Platform, Text as NativeText, View, type ViewProps } from 'react-native'
import { Text, type TextProps } from '@/components/ui/text'
import { Image } from '@/components/ui/image'
import { cn } from '@/lib/utils'
import { isMarkdownLinkAllowed, markdownPlainText, parseMarkdown, type MarkdownNode } from './markdown.utils'

export interface MarkdownProps extends Omit<ViewProps, 'children'> {
  source: string
  className?: string
  textProps?: Omit<TextProps, 'children'>
  /** HTTP(S) and mailto callbacks only. The component never launches a URL itself. */
  onLinkPress?: (url: string) => void
  disabled?: boolean
  /** Standalone image blocks are opt-in to avoid requests from untrusted documents. Inline images keep their alt text. */
  allowImages?: boolean
  imageHeight?: number
  renderCode?: (code: string, language: string | undefined) => React.ReactNode
}
interface RenderOptions {
  textProps: Omit<TextProps, 'children'>
  onLinkPress?: (url: string) => void
  disabled: boolean
  allowImages: boolean
  imageHeight: number
  renderCode?: MarkdownProps['renderCode']
}
const mono = Platform.OS === 'ios' ? 'Menlo' : 'monospace'

function inline(nodes: MarkdownNode[], options: RenderOptions, prefix: string): React.ReactNode {
  return nodes.map((node, index) => {
    const key = `${prefix}-${index}`
    const children = node.children.length ? inline(node.children, options, key) : node.content
    if (node.type === 'softbreak' || node.type === 'hardbreak') return '\n'
    if (node.type === 'code_inline')
      return (
        <NativeText key={key} style={{ fontFamily: mono }} className="bg-muted">
          {node.content}
        </NativeText>
      )
    if (node.type === 'em')
      return (
        <NativeText key={key} className="italic">
          {children}
        </NativeText>
      )
    if (node.type === 'strong')
      return (
        <NativeText key={key} className="font-semibold">
          {children}
        </NativeText>
      )
    if (node.type === 'link') {
      const url = node.attrs.href ?? ''
      const allowed = isMarkdownLinkAllowed(url)
      const actionable = allowed && !!options.onLinkPress && !options.disabled
      return (
        <NativeText
          key={key}
          className={allowed ? 'text-primary underline' : undefined}
          accessibilityRole={actionable ? 'link' : undefined}
          accessibilityState={allowed && options.onLinkPress ? { disabled: options.disabled } : undefined}
          onPress={actionable ? () => options.onLinkPress?.(url) : undefined}
        >
          {children}
        </NativeText>
      )
    }
    if (node.type === 'image') return node.content || markdownPlainText(node.children) || '[Image]'
    return node.children.length ? <React.Fragment key={key}>{children}</React.Fragment> : node.content
  })
}

function blocks(nodes: MarkdownNode[], options: RenderOptions, prefix = 'md'): React.ReactNode {
  return nodes.map((node, index) => {
    const key = `${prefix}-${index}`
    const textProps = options.textProps
    if (node.type === 'inline')
      return (
        <Text key={key} {...textProps}>
          {inline(node.children, options, key)}
        </Text>
      )
    if (node.type === 'paragraph' || node.type === 'heading') {
      const content = node.children[0]?.type === 'inline' ? node.children[0].children : node.children
      const onlyImage = content.length === 1 && content[0].type === 'image' ? content[0] : null
      if (
        onlyImage &&
        options.allowImages &&
        /^https?:\/\//i.test(onlyImage.attrs.src ?? '') &&
        isMarkdownLinkAllowed(onlyImage.attrs.src)
      ) {
        return (
          <Image
            key={`${key}-${onlyImage.attrs.src}`}
            source={{ uri: onlyImage.attrs.src }}
            accessibilityLabel={onlyImage.content || 'Document image'}
            style={{ height: options.imageHeight, aspectRatio: 'auto' }}
          />
        )
      }
      const heading = node.type === 'heading'
      return (
        <Text
          key={key}
          {...textProps}
          accessibilityRole={heading ? 'header' : textProps.accessibilityRole}
          size={heading ? (node.tag === 'h1' ? 'title' : node.tag === 'h2' ? 'xl' : 'lg') : textProps.size}
          className={cn(heading && 'font-semibold', textProps.className)}
        >
          {inline(content, options, key)}
        </Text>
      )
    }
    if (node.type === 'fence' || node.type === 'code_block') {
      return (
        <View key={key} className="min-w-0 rounded-md border border-border bg-muted p-[12px]">
          {options.renderCode ? (
            options.renderCode(node.content, node.attrs.language)
          ) : (
            <Text {...textProps} style={[{ fontFamily: mono }, textProps.style]}>
              {node.content.replace(/\n$/, '')}
            </Text>
          )}
        </View>
      )
    }
    if (node.type === 'blockquote')
      return (
        <View key={key} className="gap-[8px] border-border ps-[12px]" style={{ borderStartWidth: 3 }}>
          {blocks(node.children, options, key)}
        </View>
      )
    if (node.type === 'bullet_list' || node.type === 'ordered_list') {
      const start = Number(node.attrs.start ?? 1)
      return (
        <View key={key} className="gap-[8px]">
          {node.children.map((item, itemIndex) => (
            <View key={`${key}-${itemIndex}`} className="min-w-0 flex-row items-start gap-[8px]">
              <Text {...textProps} className={cn('min-w-[24px] text-end', textProps.className)}>
                {node.type === 'ordered_list' ? `${start + itemIndex}.` : '•'}
              </Text>
              <View className="min-w-0 flex-1 gap-[8px]">{blocks(item.children, options, `${key}-${itemIndex}`)}</View>
            </View>
          ))}
        </View>
      )
    }
    if (node.type === 'hr') return <View key={key} className="h-px bg-border" aria-hidden />
    return node.children.length ? (
      <View key={key} className="gap-[8px]">
        {blocks(node.children, options, key)}
      </View>
    ) : node.content ? (
      <Text key={key} {...textProps}>
        {node.content}
      </Text>
    ) : null
  })
}

/** Read-only CommonMark. Raw HTML, plugins and automatic external navigation are not enabled. */
export const Markdown = React.forwardRef<React.ComponentRef<typeof View>, MarkdownProps>(
  (
    {
      source,
      className,
      textProps = {},
      onLinkPress,
      disabled = false,
      allowImages = false,
      imageHeight = 180,
      renderCode,
      ...props
    },
    ref,
  ) => {
    const nodes = React.useMemo(() => parseMarkdown(source), [source])
    const safeImageHeight = Number.isFinite(imageHeight) && imageHeight > 0 ? imageHeight : 180
    return (
      <View ref={ref} {...props} className={cn('min-w-0 gap-[12px]', className)}>
        {blocks(nodes, {
          textProps: { selectable: true, ...textProps },
          onLinkPress,
          disabled,
          allowImages,
          imageHeight: safeImageHeight,
          renderCode,
        })}
      </View>
    )
  },
)
Markdown.displayName = 'Markdown'
components/ui/markdown/markdown.utils.ts
import MarkdownIt from 'markdown-it'
import type Token from 'markdown-it/lib/token.mjs'

export interface MarkdownNode {
  type: string
  tag: string
  content: string
  attrs: Record<string, string>
  children: MarkdownNode[]
}

// CommonMark tokens are rendered as native elements; HTML is never evaluated.
// https://github.com/markdown-it/markdown-it/blob/14.1.0/docs/security.md
const parser = new MarkdownIt('commonmark', { html: false, linkify: false })

function nodesFromTokens(tokens: Token[]): MarkdownNode[] {
  const root: MarkdownNode[] = []
  const stack: MarkdownNode[][] = [root]
  for (const token of tokens) {
    if (token.nesting === -1) {
      if (stack.length > 1) stack.pop()
      continue
    }
    const node: MarkdownNode = {
      type: token.type.replace(/_open$/, ''),
      tag: token.tag,
      content: token.content,
      attrs: Object.fromEntries(token.attrs ?? []),
      children: token.children ? nodesFromTokens(token.children) : [],
    }
    if (token.info) node.attrs.language = token.info.trim().split(/\s+/)[0]
    stack[stack.length - 1].push(node)
    if (token.nesting === 1) stack.push(node.children)
  }
  return root
}

export function parseMarkdown(source: string): MarkdownNode[] {
  return nodesFromTokens(parser.parse(source, {}))
}

/** Caller callbacks never receive script, file, custom-scheme or control-character links. */
export function isMarkdownLinkAllowed(url: string): boolean {
  if (!/^(https?:\/\/|mailto:)/i.test(url)) return false
  for (let index = 0; index < url.length; index++) {
    const code = url.charCodeAt(index)
    if (code <= 32 || code === 127) return false
  }
  return true
}

export function markdownPlainText(nodes: readonly MarkdownNode[]): string {
  return nodes.map((node) => (node.children.length ? markdownPlainText(node.children) : node.content)).join('')
}
components/ui/markdown/index.ts
export * from './Markdown'

Dependencies

Registry items

npm packages

  • markdown-it@^14.1.0
  • @types/markdown-it@^14.1.2 (dev)
Browse content and media