> ## Documentation Index
> Fetch the complete documentation index at: https://docs.samplehc.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Rich Text Editor

> Tiptap-based rich text editor with healthcare-specific extensions and citation support

## Overview

The RichTextEditor is a powerful, extensible rich text editor built on [Tiptap](https://tiptap.dev/). It includes healthcare-specific extensions for citations, page breaks, and document formatting, making it ideal for creating medical reports, clinical notes, and other healthcare documentation.

## Basic Usage

<CodeGroup>
  ```tsx Basic Editor theme={null}
  import { RichTextEditor } from "@samplehc/ui/components";
  import { useRef } from "react";

  function DocumentEditor() {
    const editorRef = useRef();

    return (
      <RichTextEditor
        editorRef={editorRef}
        defaultValue="<p>Start typing your document...</p>"
        onUpdate={({ editor }) => {
          console.log("Content updated:", editor.getHTML());
        }}
      />
    );
  }
  ```

  ```tsx Read-only Viewer theme={null}
  import { RichTextEditor } from "@samplehc/ui/components";

  function DocumentViewer({ content }) {
    return (
      <RichTextEditor
        defaultValue={content}
        disableEditable={true}
        className="border-none"
      />
    );
  }
  ```
</CodeGroup>

## Advanced Features

### Citation Support

The editor includes built-in support for citations that can link to source documents:

```tsx theme={null}
import { RichTextEditor } from "@samplehc/ui/components";

function CitationEditor() {
  const handleCitationClick = (citations) => {
    console.log("Citation clicked:", citations);
    // Handle citation navigation or display source
  };

  return (
    <RichTextEditor
      onCitationClick={handleCitationClick}
      defaultValue="<p>According to the medical records <citation-paragraph data-citations='[{"documentId": "doc123", "pageNumber": 1}]'>the patient has no known allergies</citation-paragraph>.</p>"
    />
  );
}
```

### Custom Extensions

Add your own Tiptap extensions to enhance functionality:

```tsx theme={null}
import { RichTextEditor } from "@samplehc/ui/components";
import { Highlight } from "@tiptap/extension-highlight";

function ExtendedEditor() {
  return (
    <RichTextEditor
      extraExtensions={[
        Highlight.configure({
          multicolor: true,
        }),
      ]}
      defaultValue="<p>Highlight important <mark>medical findings</mark>.</p>"
    />
  );
}
```

## API Reference

### EditorProps

<ParamField path="className" type="string">
  Additional CSS classes to apply to the editor container.
</ParamField>

<ParamField path="editorRef" type="Ref<EditorHandle | undefined>">
  Ref to access the editor instance and methods.
</ParamField>

<ParamField path="defaultValue" type="JSONContent | string">
  Initial content for the editor. Can be HTML string or Tiptap JSON format.
</ParamField>

<ParamField path="extraExtensions" type="Extensions">
  Additional Tiptap extensions to include in the editor.
</ParamField>

<ParamField path="onUpdate" type="function">
  Callback fired when editor content changes.

  ```tsx theme={null}
  onUpdate?: (props: EditorEvents["update"]) => void
  ```
</ParamField>

<ParamField path="isSaving" type="boolean">
  Show saving indicator in the toolbar.
</ParamField>

<ParamField path="onSelectionUpdate" type="function">
  Callback fired when text selection changes.

  ```tsx theme={null}
  onSelectionUpdate?: (props: EditorEvents["selectionUpdate"]) => void
  ```
</ParamField>

<ParamField path="disableEditable" type="boolean">
  Make the editor read-only. Defaults to false.
</ParamField>

<ParamField path="onCitationClick" type="function">
  Callback fired when a citation is clicked.

  ```tsx theme={null}
  onCitationClick?: (citations: Citation[]) => void
  ```
</ParamField>

### EditorHandle

The `editorRef` provides access to the underlying Tiptap editor instance:

<ResponseField name="editor" type="Editor | null | undefined">
  The Tiptap editor instance with full API access.

  ```tsx theme={null}
  // Access editor methods
  const content = editorRef.current?.editor?.getHTML();
  const isEmpty = editorRef.current?.editor?.isEmpty;

  // Execute commands
  editorRef.current?.editor?.chain().focus().toggleBold().run();
  ```
</ResponseField>

## Built-in Extensions

The RichTextEditor comes with a comprehensive set of pre-installed extensions:

<Tabs>
  <Tab title="Text Formatting">
    * **Bold, Italic, Underline** - Basic text styling
    * **Strikethrough** - Strike through text
    * **Code** - Inline code formatting
    * **Superscript/Subscript** - Scientific notation
    * **Text Align** - Left, center, right, justify
  </Tab>

  <Tab title="Structure">
    * **Headings** - H1 through H6 headings
    * **Paragraphs** - Standard paragraph blocks
    * **Lists** - Ordered and unordered lists
    * **Blockquotes** - Quote formatting
    * **Code Blocks** - Multi-line code with syntax highlighting
  </Tab>

  <Tab title="Healthcare-Specific">
    * **Citations** - Link text to source documents
    * **Page Breaks** - Insert page breaks for printing
    * **Image Resizer** - Resize images with handles
    * **Document Structure** - Headers, footers, sections
  </Tab>

  <Tab title="Media & Links">
    * **Images** - Insert and resize images
    * **Links** - Hyperlink support
    * **Tables** - Create and edit tables
    * **Horizontal Rules** - Section dividers
  </Tab>
</Tabs>

## Workflow Integration

### Saving to Task State

Integrate with the workflow system to persist editor content:

<RequestExample>
  ```tsx Persistent Editor theme={null}
  import { RichTextEditor } from "@samplehc/ui/components";
  import { useTaskState } from "@samplehc/ui/data";
  import { useRef, useState } from "react";

  function PersistentEditor() {
    const [content, setContent] = useTaskState("documentContent", "");
    const [isSaving, setIsSaving] = useState(false);
    const editorRef = useRef();

    const handleUpdate = ({ editor }) => {
      setIsSaving(true);
      const html = editor.getHTML();
      
      // Debounce saves to avoid too frequent updates
      setTimeout(() => {
        setContent(html);
        setIsSaving(false);
      }, 1000);
    };

    return (
      <RichTextEditor
        editorRef={editorRef}
        defaultValue={content}
        onUpdate={handleUpdate}
        isSaving={isSaving}
      />
    );
  }
  ```
</RequestExample>

### Document Templates

Create reusable document templates:

<RequestExample>
  ```tsx Document Template theme={null}
  import { RichTextEditor } from "@samplehc/ui/components";

  const MEDICAL_REPORT_TEMPLATE = `
  <h1>Medical Report</h1>
  <h2>Patient Information</h2>
  <p><strong>Patient Name:</strong> [Patient Name]</p>
  <p><strong>Date of Birth:</strong> [DOB]</p>
  <p><strong>MRN:</strong> [Medical Record Number]</p>

  <h2>Chief Complaint</h2>
  <p>[Chief complaint...]</p>

  <h2>History of Present Illness</h2>
  <p>[HPI details...]</p>

  <h2>Assessment and Plan</h2>
  <p>[Assessment and plan...]</p>

  <h2>Physician Signature</h2>
  <p>[Physician name and credentials]</p>
  <p>[Date signed]</p>
  `;

  function MedicalReportEditor() {
    return (
      <RichTextEditor
        defaultValue={MEDICAL_REPORT_TEMPLATE}
        onUpdate={({ editor }) => {
          // Auto-save functionality
          localStorage.setItem("medical-report-draft", editor.getHTML());
        }}
      />
    );
  }
  ```
</RequestExample>

## Keyboard Shortcuts

The editor supports standard keyboard shortcuts for efficient editing:

<Accordion title="Text Formatting">
  * **Ctrl/Cmd + B** - Bold
  * **Ctrl/Cmd + I** - Italic
  * **Ctrl/Cmd + U** - Underline
  * **Ctrl/Cmd + Shift + S** - Strikethrough
  * **Ctrl/Cmd + E** - Inline code
</Accordion>

<Accordion title="Structure">
  * **Ctrl/Cmd + Alt + 1-6** - Headings H1-H6
  * **Ctrl/Cmd + Shift + 7** - Ordered list
  * **Ctrl/Cmd + Shift + 8** - Bullet list
  * **Ctrl/Cmd + Shift + 9** - Blockquote
  * **Ctrl/Cmd + Alt + C** - Code block
</Accordion>

<Accordion title="Navigation">
  * **Ctrl/Cmd + Z** - Undo
  * **Ctrl/Cmd + Y** - Redo
  * **Ctrl/Cmd + A** - Select all
  * **Ctrl/Cmd + K** - Insert link
</Accordion>

## Styling and Theming

The editor inherits styles from your application's theme and can be customized:

```tsx theme={null}
import { RichTextEditor } from "@samplehc/ui/components";

function StyledEditor() {
  return (
    <RichTextEditor
      className="min-h-[400px] max-h-[800px] border-2 border-primary"
      defaultValue="<p>Custom styled editor</p>"
    />
  );
}
```

<Note>
  The editor uses CSS classes that are compatible with Tailwind CSS and can be styled using your existing design system.
</Note>

## Citation System

The citation system allows linking text segments to source documents:

<Tabs>
  <Tab title="Creating Citations">
    ```tsx theme={null}
    // Citations are created by wrapping text in citation-paragraph elements
    const citedText = `
    <p>According to the lab results 
    <citation-paragraph data-citations='[{"documentId": "lab-123", "pageNumber": 2, "section": "Blood Work"}]'>
    the patient's glucose levels are within normal range
    </citation-paragraph>.</p>
    `;
    ```
  </Tab>

  <Tab title="Handling Citation Clicks">
    ```tsx theme={null}
    function DocumentWithCitations() {
      const handleCitationClick = (citations) => {
        // Navigate to source document
        citations.forEach(citation => {
          console.log("Source:", citation.documentId);
          console.log("Page:", citation.pageNumber);
          // Open document viewer or navigate to source
        });
      };

      return (
        <RichTextEditor
          onCitationClick={handleCitationClick}
          defaultValue={citedText}
        />
      );
    }
    ```
  </Tab>

  <Tab title="Citation Data Structure">
    ```tsx theme={null}
    type Citation = {
      documentId: string;
      pageNumber?: number;
      section?: string;
      startIndex?: number;
      endIndex?: number;
      metadata?: Record<string, unknown>;
    };
    ```
  </Tab>
</Tabs>

## Best Practices

<Tip>
  **Performance**: For large documents, consider implementing lazy loading or pagination to maintain smooth editing performance.
</Tip>

<Tip>
  **Auto-save**: Implement debounced auto-saving to prevent data loss while avoiding excessive API calls.
</Tip>

<Warning>
  **Content Validation**: Always validate and sanitize content before saving, especially when accepting user input.
</Warning>

<Note>
  **Accessibility**: The editor includes built-in accessibility features. Ensure any custom extensions also follow accessibility guidelines.
</Note>
