import { Meta, Source } from '@storybook/addon-docs/blocks';

<Meta title="Typography/Markup/Developer notes" />

# Developer notes

## Integrating Markup in host components

To integrate any component with Markup (e.g. `title`, `description`), follow this pattern:

1. **Add `onMarkupAction`** — if the component is expected to accept actions, add a single callback prop that the
   component forwards to every internal `<Markup onAction={onMarkupAction}>` instance. The name of this prop must
   remain consistent across components.

2. **Add `markupOptions`** — an optional prop keyed by the text prop names, carrying per-prop Markup configuration
   (`data`, `allowLinks`). `MarkupTextOptions` type is exposed by the component.

<Source dark language="tsx" code={`
  import Markup, { type MarkupActionHandler, type MarkupTextOptions } from '../Markup';

  type MyComponentProps = {
    title: ReactNode;
    description?: ReactNode;
    onMarkupAction?: MarkupActionHandler;
    markupOptions?: {
      title?: MarkupTextOptions;
      description?: MarkupTextOptions;
    };
  };

  function MyComponent({ title, description, onMarkupAction, markupOptions }: MyComponentProps) {
    return (
      <div>
        <Markup onAction={onMarkupAction} {...markupOptions?.title}>
          {title}
        </Markup>

        {description && (
          <Markup onAction={onMarkupAction} {...markupOptions?.description}>
            {description}
          </Markup>
        )}
      </div>
    );
  }
`} />

Consumer usage:

<Source
  dark
  language="tsx"
  code={`
  <MyComponent
    title='Something went wrong. <link action="retry">Try again</link>.'
    description='Your balance is {{amount}}.'
    onMarkupAction={(actionId) => {
      if (actionId === 'retry') refetch();
    }}
    markupOptions={{
      description: { data: { amount: '£100.00' }, allowLinks: 'all' }
    }}
  />
`}
/>

## How parsing works

The parser runs in two phases: **tokenise** then **parse**.

### Phase 1: Tokenise

The input string is scanned left-to-right with a regex that only recognises allowed tag names. Everything between matches becomes text. Newlines become their own tokens.

<Source dark language="text" code={`
Input:  "Hello <important>world</important>!\\nBye"

Tokens: [ TEXT:"Hello " ]
[ OPEN:important ]
[ TEXT:"world" ]
[ CLOSE:important ]
[ TEXT:"!" ]
[ NEWLINE ]
[ TEXT:"Bye" ]
`} />

Unrecognised tags like `<script>` or `<div>` are never tokenised — they stay as part of the text content. This is the first security layer.

### Phase 2: Recursive descent parse

The token stream is consumed by a recursive parser that builds a tree of nodes.

<Source
  dark
  language="text"
  code={`
parse(tokens, until=none)
  │
  ├─ TEXT:"Hello " ────────────────────► { type: 'text', content: 'Hello ' }
  ├─ OPEN:important
  │  │
  │  ├─ parse(tokens, until='important') // recurse
  │  │  ├─ TEXT:"world" ───────────────► { type: 'text', content: 'world' }
  │  │  └─ CLOSE:important ────────────► return { closed: true, nodes: [...] }
  │  │
  │  └─ result.closed? YES ────────────► { type: 'important', children: [...] }
  │
  ├─ TEXT:"!" ─────────────────────────► { type: 'text', content: '!' }
  ├─ NEWLINE ──────────────────────────► { type: 'newline' }
  └─ TEXT:"Bye" ───────────────────────► { type: 'text', content: 'Bye' }
`}
/>

The key insight is the `closed` flag. When we see an open tag, we recurse to collect its children. Two outcomes:

1. **Matching close tag found:** build a proper node with children.
2. **No matching close tag found:** treat the open tag as literal text, and return the already-parsed children.

This gives graceful degradation for malformed input — no crashes, no swallowed content.

### Nesting

Because each open tag recurses, nesting is handled naturally:

<Source dark language="text" code={`
Input: "<p><important>Read the <a href="/terms">terms</a></important></p>"

Tree: paragraph
└─ important
├─ text: "Read the "
└─ link (href="/terms")
└─ text: "terms"
`} />

The parser enforces a `MAX_NESTING_DEPTH` limit (32). Beyond that depth, tags are emitted as literal text instead of recursing — this prevents stack overflow from deeply-nested input.
