# Writing Markdown

Where people write more than a line, a comment, a description, a note, give them MarkdownEditor: files go in where they are pasted, and the reader keeps a plain text box if they ask for one.

API [MarkdownEditor](/ui/storybook/?path=/docs/ui-codemirror-markdowneditor--docs) [Textarea](/ui/storybook/?path=/docs/ui-primitives-textarea--docs) [Markdown](/ui/storybook/?path=/docs/ui-markdown-markdown--docs)

**A text that is written in Markdown is written in `MarkdownEditor`. A file that belongs to the text goes into it where it was pasted, and is uploaded when the text is sent.**

```tsx
import { Button } from "@orz/ui/components/button";
import {
  MarkdownEditor,
  type MarkdownEditorHandle,
} from "@orz/ui-codemirror/components/markdown-editor";
import {
  stagedFileDrag,
  useStagedFiles,
} from "@orz/ui-codemirror/hooks/use-staged-files";
import { PaperclipIcon, XIcon } from "lucide-react";
import { useRef, useState } from "react";

/** Stands in for the app's upload: the file "arrives" a moment later. */
const upload = (file: File) =>
  new Promise<{ url: string }>((resolve) =>
    setTimeout(
      () =>
        resolve({
          url: `https://files.example/${encodeURIComponent(file.name)}`,
        }),
      300,
    ),
  );

export function CommentWithFiles() {
  const staging = useStagedFiles({ upload });
  const editor = useRef<MarkdownEditorHandle>(null);
  const picker = useRef<HTMLInputElement>(null);
  const [sent, setSent] = useState<string | null>(null);
  const [sending, setSending] = useState(false);

  async function send(text: string) {
    setSending(true);
    try {
      setSent(await staging.resolve(text));
      staging.clear();
    } finally {
      setSending(false);
    }
  }

  return (
    <div className="grid max-w-xl gap-2">
      <MarkdownEditor
        ref={editor}
        ariaLabel="Comment"
        placeholder="Paste or drop a screenshot, then Mod-Enter"
        className="min-h-28 max-h-72"
        staging={staging.editor}
        onSubmit={send}
      />
      <div className="flex flex-wrap items-center gap-2">
        {staging.staged.map((item) => (
          <Button
            key={item.key}
            variant="outline"
            size="sm"
            aria-label={`Remove ${item.file.name}`}
            onClick={() => staging.remove(item.key)}
            {...stagedFileDrag(item.key)}
          >
            {item.file.name}
            <XIcon data-icon="inline-end" />
          </Button>
        ))}
        <Button
          variant="ghost"
          size="sm"
          onClick={() => picker.current?.click()}
        >
          <PaperclipIcon data-icon="inline-start" />
          Attach files
        </Button>
        <input
          ref={picker}
          type="file"
          multiple
          hidden
          onChange={(event) => {
            staging.stage(event.target.files ?? []);
            event.target.value = "";
          }}
        />
        <Button
          className="ml-auto"
          size="sm"
          disabled={sending}
          onClick={() => void send(editor.current?.getValue() ?? "")}
        >
          {sending ? "Sending…" : "Comment"}
        </Button>
      </div>
      {sent !== null && (
        <pre className="overflow-auto rounded-frame bg-muted p-3 text-ui-sm whitespace-pre-wrap">
          {sent}
        </pre>
      )}
    </div>
  );
}
```

Paste or drop a file: it lands at the caret as a chip, and the button under the editor lists it. Delete the chip and the file goes with it; undo brings both back. **Comment** uploads the file and shows the text that would be sent, the chip turned into a link.

## Which box

| The text                                                                      | Use                                                        |
| ----------------------------------------------------------------------------- | ---------------------------------------------------------- |
| One line, a title, a name                                                     | `Input`                                                    |
| Several lines that are read as written                                        | `Textarea`                                                 |
| Several lines that are rendered as Markdown: a comment, a description, a note | `MarkdownEditor`                                           |
| A file the pane exists to edit                                                | `MarkdownEditor` or `CodeEditor` with `purpose="document"` |

`MarkdownEditor` is the box people write Markdown in everywhere in an app, so its keys and its paste are learned once: Mod-Enter sends, Escape cancels, and a formatted paste becomes Markdown.

## Line breaks

Draw a text written in such a box with `breaks` on `Markdown`: its author pressed Enter to start a line and expects to see one, as GitHub shows a comment. A file keeps a single newline a space, the one a pane exists to show and one embedded in a comment alike, as GitHub shows a `.md` file: there the author breaks lines to keep the source readable, not the page.

## Files in the text

- Put a file in the text with `staging` and `useStagedFiles`, rather than in a list beside the box: where it sits is part of what the author wrote. List the files the text places under the box all the same, with a way to remove each, for a reader who would rather click than find the chip.
- Upload at send, not at paste. A file the author pastes and deletes again never reaches the server, and a text that is abandoned leaves nothing behind; `withdraw` hears an upload a failed send got up and the text no longer links.
- Offer **Attach files** as well. A phone has no paste of a file and no drop, so the picker is the only way in there.

## Two images, compared

An author who puts two images in a paragraph of their own with `→` (or `->`) between them, `![before](a.png) → ![after](b.png)`, means them to be compared. The editor colours the arrow when the paragraph reads as a pair, and offers to join two screenshots pasted one after the other; wherever the text is read, register `imagePairs` so the pair is shown as one comparison, as [Comparing images](/ui/guidelines/patterns/comparing-images/index.md) describes. Leave the pair to the author: never join images for them. Where files are staged, `imagePairOffers="staged"` keeps the offer to those files, and leaves an image pasted as a line of Markdown as its author wrote it.

## People and values in completion

A completion row's label is the text it completes, from the character that opened the panel: `/close`, `@alice`, `#bug`. A screen reader reads the row as it will be written, and what was typed is what lights up in it. Give a row's type no icon of that character, or the row shows it twice.

A completion row that names a person shows the person as everywhere else in the app, an `Avatar` before the login, and a row that names a status or a label shows its pill or chip. Draw them with `reactOption` and the row classes `completionWith` takes, so the row reads the way the same thing reads in a picker. The avatar is sized to the row's line and centred on the icon column, as in a search box's suggestions, so a person is as big in both, their row no taller than the rest, and their name, like a pill or a chip, starts where every row's text does. An agent's avatar wears its bot as an `AvatarBadge`, which stands it a step larger in both, the badge in the avatar's corner rather than over the name. A row that names a task draws the task's status icon where the type icon stands and keeps its reference as code, with the status at the row's end on the title's line. A slash command's arguments are such rows too: `commandCompletionSource`'s `argumentOption` hands each one over with the value it offers, for the app to draw as it draws that value elsewhere. Values keep the order the app gives them: statuses in the order work moves through them, not alphabetically.

## Slash commands

A line that spells a command (`/close`, `/label bug`) is taken out of the text and done when the text is sent. Name what the commands will do on the send button, from `summarizeCommands`, so the author reads what will happen before it does; the editor only marks which lines are commands.

A line that reads as a command but will not be done, a label that does not exist or a quote left open, is an error the author has to fix before sending, and it waits until they stop typing: `/label b` on its way to `/label bug` is not one yet. Report it on the editor's beat, so the app and the editor never disagree: show it once the draft has been as still as `commandDecoration`'s `brokenAfter`, take it away the moment the line is fixed, and when the author sends, judge the draft as it stands and call `revealBrokenCommands` so the editor marks the same lines at once.

## A plain text box

Some readers would rather have the browser's own text box: a phone keyboard's corrections and dictation, a screen reader and a spell checker all know a textarea best. Offer the choice as a setting and pass it as `plain`; the editor reads it when it mounts, so a draft that is open never switches box under its author. A plain box keeps the keys, the dirty guard and staged files, and drops highlighting, completion, the paste conversion and the chips.

## In the demos

- [Pull request](/ui/demos/pull-request/index.md): The comment is written in a MarkdownEditor and rendered as Markdown once posted. Paste a formatted part of a page into it and the formatting comes through as Markdown.
