# Markdown

> A Markdown editor widget with a formatting toolbar and live preview

Markdown widgets are [Input Fields](https://golemui.com/dx/widgets-reference/input-fields/overview.md) that provide a rich text editing experience with a formatting toolbar and an optional live preview panel. The toolbar lets users apply common markdown formatting (headings, bold, italic, quotes, links, lists) without needing to remember the syntax.


```ts title="markdown.ts"

export default [
  gui.inputs.markdown('content', {
    label: 'Content',
  }),
];
```

_Live demo on the docs page. Form definition: [markdown.ts](https://golemui.com/template/widgets-dx/markdown/markdown.ts)._

## Dependencies

The Markdown widget requires a markdown parser to power its live preview. Since the parser is a third-party dependency, it is **not bundled** with the widget. Instead, you provide it at the form level via the `dependencies` property, keeping the core library decoupled from any specific parser.

<Aside type="tip">
  Any Markdown parser works, such as [snarkdown](https://github.com/developit/snarkdown), [marked](https://github.com/markedjs/marked) or [micromark](https://github.com/micromark/micromark), as long as `parse` returns its HTML synchronously. In TypeScript, `parse` returns `SanitizedHtml`, a string type that only a cast creates: cast the parser's output where you sanitize it, or where you trust its source. See [Security](https://golemui.com/dx/widgets-reference/display-fields/markdown-text.md#security).
</Aside>

Pass the markdown parser through `formConfig.dependencies` on the form component, not inside the widget's `props`:


**React**

```tsx

const formConfig = {
  dependencies: {
    markdown: {
      parse: (md: string) => snarkdown(md) as SanitizedHtml,
    },
  },
};

const config = { formDef, data: formData, formConfig };
// <GuiForm config={config} ... />
```

**Angular**

```typescript

protected formConfig = {
  dependencies: {
    markdown: {
      parse: (md: string) => snarkdown(md) as SanitizedHtml,
    },
  },
};
```
```html
<gui-form
  [config]="config"
  ...
></gui-form>
```

**Lit**

```typescript

// class field:
formConfig = {
  dependencies: {
    markdown: {
      parse: (md: string) => snarkdown(md) as SanitizedHtml,
    },
  },
};
config = { formDef: this.formDef, data: this.formData, formConfig: this.formConfig };
```
```html
<gui-form
  .config=${this.config}
  ...
></gui-form>
```

**Vue**

```ts

const formConfig = {
  dependencies: {
    markdown: {
      parse: (md: string) => snarkdown(md) as SanitizedHtml,
    },
  },
};

const config = { formDef, data: formData, formConfig };
// <GuiForm :config="config" />
```

**Vanilla JS**

```js

const form = document.getElementById('app-form');
form.config = {
  formDef,
  data: formData,
  formConfig: {
    dependencies: { markdown: { parse: (md) => snarkdown(md) } },
  },
};
```


<Aside>The live preview will only render parsed HTML when a `dependencies.markdown.parse` function is provided. Without it, the toolbar and editor still work, but the preview panel will be empty.</Aside>

### Line breaks

The live preview follows CommonMark semantics: a **single newline** between two lines is rendered as a space, not a `<br>`. To produce a visible line break, add a blank line between them (a paragraph break) or end the first line with two trailing spaces before the newline (a CommonMark hard-break). The behavior is governed by the parser you provide, not by the widget itself.

<Aside>
  Our examples use [snarkdown](https://github.com/developit/snarkdown) because it is extremely lightweight (~1 KB gzipped) and dependency-free — ideal for keeping playground bundles small. For production, a richer parser is probably a better choice:

- [marked](https://marked.js.org) (~13 KB gzipped) configured with `{ breaks: true, gfm: true }` emits real `<p>` paragraphs, supports GFM features (tables, autolinks, task lists), and treats a single newline as `<br>`.
- [markdown-it](https://github.com/markdown-it/markdown-it) (~44 KB gzipped) configured with `{ breaks: true }` adds a pluggable architecture on top of the same line-break behavior.

Both expose a `breaks` option so the "Enter inserts a line break" expectation works without any pre-processing.

</Aside>

## Props

Use these `props` to customize your Markdown widget.

| prop                 | type              | description                                                                                                            |
| -------------------- | ----------------- | ---------------------------------------------------------------------------------------------------------------------- |
| `autocomplete`       | string            | `'on'`, `'off'`, or a space-separated list of W3C autofill tokens                                                      |
| `autoGrow`           | boolean           | If true, the editor will automatically expand its height as the user types                                             |
| `boldTitle`          | string            | Tooltip for the bold button                                                                                            |
| `counterMode`        | string            | Mode for the character counter if `validator.maxLength` is set, possible values are `remaining` (default) or `current` |
| `defaultOpenPreview` | boolean           | If true, the split view preview panel is open by default                                                               |
| `headingTitle`       | string            | Tooltip for the heading button                                                                                         |
| `hint`               | string            | A description to display below the editor                                                                              |
| `italicTitle`        | string            | Tooltip for the italic button                                                                                          |
| `linkTitle`          | string            | Tooltip for the link button                                                                                            |
| `minimumHeight`      | number            | Minimum height of the editor in pixels, defaults to 120                                                                |
| `orderedListTitle`   | string            | Tooltip for the ordered list button                                                                                    |
| `placeholder`        | string            | A placeholder text to display when the editor has no value                                                             |
| `quoteTitle`         | string            | Tooltip for the quote button                                                                                           |
| `splitViewTitle`     | string            | Tooltip for the split view button                                                                                      |
| `strikethroughTitle` | string            | Tooltip for the strikethrough button                                                                                   |
| `toolbarAriaLabel`   | string            | ARIA label for the editor's formatting toolbar. Defaults to `Text formatting`                                          |
| `tools`              | MarkdownButtons[] | An array of toolbar buttons to display. Defaults to all buttons                                                        |
| `unorderedListTitle` | string            | Tooltip for the unordered list button                                                                                  |

### Toolbar Buttons

The `tools` prop lets you customize which toolbar buttons are displayed and their order. Available tokens:

| Token | Button         | Markdown syntax       |
| ----- | -------------- | --------------------- |
| `H`   | Heading        | `# Title`             |
| `B`   | Bold           | `**some text**`       |
| `I`   | Italic         | `_some text_`         |
| `Q`   | Quote          | `> some text`         |
| `L`   | Link           | `[some text](url)`    |
| `OL`  | Ordered list   | `1. some text`        |
| `UL`  | Unordered list | `- some text`         |
| `\|`  | Separator      | Visual separator only |


```ts title="markdown.ts"

export default [
  gui.inputs.markdown('content', {
    tools: ['H', 'B', 'I', 'S', '|', 'UL'],
    label: 'Content',
  }),
];
```

_Live demo on the docs page. Form definition: [markdown-tools.ts](https://golemui.com/template/widgets-dx/markdown/markdown-tools.ts)._

### Titles

Use the title props to customize the tooltip text for each toolbar button.


```ts title="markdown.ts"

export default [
  gui.inputs.markdown('content', {
    headingTitle: 'Add heading',
    boldTitle: 'Bold text',
    italicTitle: 'Italic text',
    strikethroughTitle: 'Strikethrough text',
    quoteTitle: 'Add quote',
    linkTitle: 'Insert link',
    orderedListTitle: 'Ordered list',
    unorderedListTitle: 'Bullet list',
    splitViewTitle: 'Toggle preview',
    label: 'Content',
  }),
];
```

_Live demo on the docs page. Form definition: [markdown-titles.ts](https://golemui.com/template/widgets-dx/markdown/markdown-titles.ts)._

### Placeholder

Use the property `placeholder` to add a placeholder.


```ts title="markdown.ts"

export default [
  gui.inputs.markdown('content', {
    placeholder: 'Write your markdown here...',
    label: 'Content',
  }),
];
```

_Live demo on the docs page. Form definition: [markdown-placeholder.ts](https://golemui.com/template/widgets-dx/markdown/markdown-placeholder.ts)._

### Hint

<Aside>A `label` is required for the `hint` to be displayed.</Aside>

Use the property `hint` to add a description.


```ts title="markdown.ts"

export default [
  gui.inputs.markdown('content', {
    hint: 'Supports markdown formatting.',
    label: 'Content',
  }),
];
```

_Live demo on the docs page. Form definition: [markdown-hint.ts](https://golemui.com/template/widgets-dx/markdown/markdown-hint.ts)._

### Character Counter

Use the validator `maxLength` to limit the number of characters and display a character counter. You can change how it counts with `counterMode` (`remaining` or `current`).

The limit doesn't block input. The user can type or paste past it, the counter shows the value is over the limit, and the editor shows the `maxLength` error. The `maxLength` prop is deprecated: see [Deprecated props](#deprecated-props).


```ts title="markdown.ts"

export default [
  gui.inputs.markdown('contentRemaining', {
    counterMode: 'remaining',
    label: 'Content',
    validator: {
      maxLength: 200,
      required: true,
    },
  }),
  gui.inputs.markdown('contentCurrent', {
    counterMode: 'current',
    label: 'Content',
    validator: {
      maxLength: 200,
      required: true,
    },
  }),
];
```

_Live demo on the docs page. Form definition: [markdown-counter.ts](https://golemui.com/template/widgets-dx/markdown/markdown-counter.ts)._

### Auto Grow

Use the property `autoGrow` to allow the editor to expand automatically based on content. You can combine it with `minimumHeight` to set its initial size.


```ts title="markdown.ts"

export default [
  gui.inputs.markdown('content', {
    autoGrow: true,
    minimumHeight: 50,
    label: 'Content',
  }),
];
```

_Live demo on the docs page. Form definition: [markdown-autogrow.ts](https://golemui.com/template/widgets-dx/markdown/markdown-autogrow.ts)._

### Default Open Preview

Use the property `defaultOpenPreview` to open the split view preview panel by default when the widget loads.


```ts title="markdown.ts"

export default [
  gui.inputs.markdown('content', {
    defaultOpenPreview: true,
    label: 'Content',
  }),
];
```

_Live demo on the docs page. Form definition: [markdown-default-open-preview.ts](https://golemui.com/template/widgets-dx/markdown/markdown-default-open-preview.ts)._

## Deprecated props

This prop has no effect, and v3.0.0 removes it:

| Deprecated  | Use instead                                                     |
| ----------- | --------------------------------------------------------------- |
| `maxLength` | `validator.maxLength`, which controls the counter and the error |

## Styling

Markdown editors can be styled as explained in the [Styling Guide](https://golemui.com/dx/styling/overview.md).

### CSS Variables

Following you will find a list with the CSS Variables and a quick description of what you will style.

| CSS Variable             | Description                                     |
| ------------------------ | ----------------------------------------------- |
| `--gui-space-10`         | Textarea and preview top padding                |
| `--gui-space-3`          | Preview horizontal padding, toolbar padding     |
| `--gui-space-1`          | Toolbar button padding                          |
| `--gui-space-2`          | Toolbar button gap, counter top margin          |
| `--gui-font-sm`          | Counter text font size                          |
| `--gui-intent-error`     | Counter error color when max length is exceeded |
| `--gui-intent-primary`   | Active toolbar button background                |
| `--gui-radius-md`        | Widget border radius                            |
| `--gui-radius-sm`        | Toolbar button border radius                    |
| `--gui-border-default`   | Widget border, toolbar border, preview border   |
| `--gui-border-focus`     | Widget border color on focus                    |
| `--gui-shadow-focus`     | Widget box shadow on focus                      |
| `--gui-text-default`     | Text and toolbar icon fill color                |
| `--gui-bg-surface`       | Toolbar background color                        |
| `--gui-bg-surface-hover` | Toolbar button hover background                 |

### Anatomy

This is the anatomy of the Markdown Widget in case you want to use your CSS styles.


```html title="markdown-anatomy.html"
<gui-markdown-input class="gui-markdown gui-field">
  <gui-markdown class="gui-field">
    <label class="gui-label" for="fieldUid" id="fieldUid_label">
      <span class="gui-label__text">Label</span>
      <div class="gui-widget-hint" id="fieldUid_hint" aria-hidden="true">Hint</div>
    </label>

    <div class="gui-widget">
      <div class="gui-markdown__toolbar" role="toolbar" aria-label="Text formatting">
        <ul role="presentation">
          <li role="presentation">
            <button
              type="button"
              class="gui-markdown__toolbar-button"
              aria-label="Heading"
              aria-pressed="false"
              title="Heading"
            >
              <svg
                xmlns="http://www.w3.org/2000/svg"
                width="20"
                height="20"
                viewBox="0 0 256 256"
                aria-hidden="true"
              >
                <path d="M212,56V200a12,12,0,…"></path>
              </svg>
            </button>
          </li>
          <li role="presentation">
            <button
              type="button"
              class="gui-markdown__toolbar-button"
              aria-label="Bold"
              aria-pressed="false"
              title="Bold"
            >
              <svg
                xmlns="http://www.w3.org/2000/svg"
                width="20"
                height="20"
                viewBox="0 0 256 256"
                aria-hidden="true"
              >
                <path d="M185.08,114.46A48,48…"></path>
              </svg>
            </button>
          </li>
          <!-- More presentation elements (10 in total) -->
        </ul>
      </div>

      <div class="gui-markdown__container">
        <textarea
          id="fieldUid"
          class="gui-widget-input"
          placeholder="Custom placeholder"
          aria-describedby="fieldUid_hint"
          style="min-height: 120px"
        ></textarea>
      </div>
    </div>

    <div class="gui-markdown--validation">
      <div>
        <div class="gui-validator gui-validator--empty" id="fieldUid_errors" role="alert"></div>
      </div>
      <div class="gui-markdown--counter">
        <span>0</span>
        <span>/ 200</span>
      </div>
    </div>
  </gui-markdown>
</gui-markdown-input>
```
