> ## Documentation Index
> Fetch the complete documentation index at: https://superdoc-caio-pizzol-docs-ai-core-preset.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Link extension

export const SourceCodeLink = ({extension, path}) => {
  const githubPath = path || `packages/super-editor/src/editors/v1/extensions/${extension.toLowerCase()}`;
  const githubUrl = `https://github.com/superdoc-dev/superdoc/tree/main/${githubPath}`;
  return <div>
      <p>
        <a href={githubUrl} target="_blank" rel="noopener noreferrer">
          View on GitHub →
        </a>
      </p>
    </div>;
};

export const SuperDocEditor = ({html = '<p>Start editing...</p>', height = '400px', maxHeight = '400px', onReady = null, showExport = true, customButtons = null}) => {
  const [ready, setReady] = useState(false);
  const editorRef = useRef(null);
  const containerIdRef = useRef(`editor-${Math.random().toString(36).substr(2, 9)}`);
  const DEV_DIST_URL = 'http://localhost:9094/dist';
  const UNPKG_DIST_URL = 'https://unpkg.com/superdoc@latest/dist';
  const getBaseUrl = async () => {
    const isDev = typeof window !== 'undefined' && window.location.hostname === 'localhost';
    if (isDev) {
      try {
        const res = await fetch(`${DEV_DIST_URL}/superdoc.min.js`, {
          method: 'HEAD'
        });
        if (res.ok) {
          console.info('[SuperDoc Docs] Using local build from', DEV_DIST_URL);
          return DEV_DIST_URL;
        }
        console.warn('[SuperDoc Docs] Local dev server returned', res.status, '- falling back to unpkg');
      } catch (err) {
        console.warn('[SuperDoc Docs] Local dev server not reachable: falling back to unpkg.', 'Run `pnpm dev:docs` from the repo root to use your local build.', err.message);
      }
    }
    return UNPKG_DIST_URL;
  };
  const ensureStyle = baseUrl => {
    const styleHref = `${baseUrl}/style.css`;
    if (document.querySelector(`link[href="${styleHref}"]`)) return;
    const link = document.createElement('link');
    link.rel = 'stylesheet';
    link.href = styleHref;
    document.head.appendChild(link);
  };
  const loadSuperDoc = baseUrl => {
    if (window.SuperDoc) return Promise.resolve();
    const scriptSrc = `${baseUrl}/superdoc.min.js`;
    const existingScript = document.querySelector(`script[src="${scriptSrc}"]`);
    if (existingScript) {
      if (window.SuperDoc) return Promise.resolve();
      return new Promise((resolve, reject) => {
        existingScript.addEventListener('load', resolve, {
          once: true
        });
        existingScript.addEventListener('error', reject, {
          once: true
        });
      });
    }
    return new Promise((resolve, reject) => {
      const script = document.createElement('script');
      script.src = scriptSrc;
      script.onload = resolve;
      script.onerror = reject;
      document.body.appendChild(script);
    });
  };
  const initEditor = () => {
    setTimeout(() => {
      if (!window.SuperDoc) return;
      if (!document.getElementById(containerIdRef.current)) return;
      if (editorRef.current) return;
      editorRef.current = new window.SuperDoc({
        selector: `#${containerIdRef.current}`,
        html,
        rulers: true,
        contained: true,
        onReady: () => {
          setReady(true);
          if (onReady) onReady(editorRef.current);
        }
      });
    }, 100);
  };
  useEffect(() => {
    let cancelled = false;
    const boot = async () => {
      try {
        const baseUrl = await getBaseUrl();
        ensureStyle(baseUrl);
        await loadSuperDoc(baseUrl);
        if (!cancelled) initEditor();
      } catch (error) {
        console.error('Failed to boot SuperDoc:', error);
      }
    };
    boot();
    return () => {
      cancelled = true;
      editorRef.current?.destroy?.();
      editorRef.current = null;
    };
  }, []);
  const exportDocx = () => {
    if (editorRef.current?.export) {
      editorRef.current.export();
    }
  };
  return <div className="border rounded-lg bg-white overflow-hidden">
      {ready && (showExport || customButtons) && <div className="px-3 py-2 bg-gray-50 border-b">
          {customButtons && <div className="space-y-1 mb-2">
              {customButtons.map((row, rowIndex) => <div key={rowIndex} className="flex gap-1">
                  {row.map((btn, i) => <button key={i} onClick={() => btn.onClick(editorRef.current)} className={btn.className || 'flex-1 px-2 py-1 bg-gray-100 text-gray-700 text-xs rounded hover:bg-gray-200'}>
                      {btn.label}
                    </button>)}
                </div>)}
            </div>}
          {showExport && <div className="text-right">
              <button onClick={exportDocx} className="px-3 py-1 bg-blue-500 text-white text-xs rounded hover:bg-blue-600">
                Export DOCX
              </button>
            </div>}
        </div>}
      <div id={containerIdRef.current} style={{
    height,
    maxHeight,
    paddingLeft: '5px'
  }} />
      <style jsx>{`
        #${containerIdRef.current} .superdoc__layers {
          max-width: 660px !important;
        }
        #${containerIdRef.current} .super-editor {
          max-width: 100% !important;
          width: 100% !important;
          color: #000;
        }
        #${containerIdRef.current} .editor-element {
          width: 100% !important;
          min-width: unset !important;
          transform: none !important;
        }
        #${containerIdRef.current} .editor-element {
          h1,
          h2,
          h3,
          h4,
          h5,
          strong {
            color: #000;
          }
        }
      `}</style>
    </div>;
};

Create hyperlinks with automatic formatting and Word compatibility.

Links automatically get underline styling and proper color, with full export support.

<SuperDocEditor
  html={`<p>Select any text to turn it into a link. For example, <a href="https://example.com" target="_blank">this is a link</a> to an external website.</p><p>You can also create links with custom display text or remove existing links.</p>`}
  height="200px"
  customButtons={[
[
  {
    label: 'Link Selection',
    onClick: (superdoc) => {
      const editor = superdoc?.activeEditor || superdoc?.editor
      if (!editor?.commands) return
      editor.commands.setLink({ 
        href: 'https://www.example.com' 
      })
    }
  },
  {
    label: 'Link with Text',
    onClick: (superdoc) => {
      const editor = superdoc?.activeEditor || superdoc?.editor
      if (!editor?.commands) return
      editor.commands.setLink({ 
        href: 'https://docs.example.com',
        text: 'View Documentation'
      })
    }
  },
  {
    label: 'Remove Link',
    onClick: (superdoc) => {
      const editor = superdoc?.activeEditor || superdoc?.editor
      if (!editor?.commands) return
      editor.commands.unsetLink()
    }
  }
]
]}
/>

## OOXML Structure

```xml theme={null}
<w:hyperlink r:id="rId7">
  <w:r>
    <w:rPr>
      <w:rStyle w:val="Hyperlink"/>
      <w:u w:val="none"/>
    </w:rPr>
    <w:t>Link text</w:t>
  </w:r>
</w:hyperlink>
```

## Use case

* **External links** - Connect to websites and online resources
* **Document navigation** - Create internal anchor links
* **Email links** - Add mailto: links for contact information
* **References** - Link to sources and citations
* **Non-inclusive** - Links don't expand when typing at edges, preventing accidental link extension

## Options

Configure the extension behavior:

<ParamField path="protocols" type="Array<string>" default="['http','https']">
  Allowed URL protocols
</ParamField>

<ParamField path="htmlAttributes" type="Object">
  HTML attributes for link elements
</ParamField>

<ParamField path="htmlAttributes.target" type="string" default="null">
  Default link target
</ParamField>

<ParamField path="htmlAttributes.rel" type="string" default="noopener noreferrer nofollow">
  Default rel attribute
</ParamField>

<ParamField path="htmlAttributes.class" type="string" default="null">
  CSS class
</ParamField>

<ParamField path="htmlAttributes.title" type="string" default="null">
  Title attribute
</ParamField>

## Attributes

Node attributes that can be set and retrieved:

<ParamField path="href" type="string">
  URL or anchor reference
</ParamField>

<ParamField path="target" type="TargetFrameOptions" default="_blank">
  Link target window
</ParamField>

<ParamField path="rel" type="string" default="noopener noreferrer nofollow">
  Relationship attributes
</ParamField>

<ParamField path="text" type="string">
  Display text for the link
</ParamField>

<ParamField path="name" type="string">
  Anchor name for internal references
</ParamField>

<ParamField path="history" type="boolean" default="true">
  Whether to add to viewed hyperlinks list
</ParamField>

<ParamField path="anchor" type="string">
  Bookmark target name (ignored if rId and href specified)
</ParamField>

<ParamField path="docLocation" type="string">
  Location in target hyperlink
</ParamField>

<ParamField path="tooltip" type="string">
  Tooltip for the link
</ParamField>

## Commands

### `setLink`

Create or update a link

<Note>
  Automatically adds underline formatting and trims whitespace from link boundaries
</Note>

**Example:**

<CodeGroup>
  ```javascript Usage theme={null}
  editor.commands.setLink({ href: 'https://example.com' })
  editor.commands.setLink({
    href: 'https://example.com',
    text: 'Visit Example'
  })
  ```

  ```javascript Full Example theme={null}
  import { SuperDoc } from 'superdoc';
  import 'superdoc/style.css';

  const superdoc = new SuperDoc({
    selector: '#editor',
    document: yourFile,
    onReady: (superdoc) => {
      const editor = superdoc.activeEditor;
      editor.commands.setLink({ href: 'https://example.com' })
      editor.commands.setLink({
        href: 'https://example.com',
        text: 'Visit Example'
      })
    },
  });
  ```
</CodeGroup>

**Parameters:**

<ParamField path="options" type="SetLinkOptions" required>
  Link configuration
</ParamField>

### `unsetLink`

Remove link and associated formatting

<Note>
  Also removes underline and text color
</Note>

**Example:**

<CodeGroup>
  ```javascript Usage theme={null}
  editor.commands.unsetLink()
  ```

  ```javascript Full Example theme={null}
  import { SuperDoc } from 'superdoc';
  import 'superdoc/style.css';

  const superdoc = new SuperDoc({
    selector: '#editor',
    document: yourFile,
    onReady: (superdoc) => {
      const editor = superdoc.activeEditor;
      editor.commands.unsetLink()
    },
  });
  ```
</CodeGroup>

### `toggleLink`

Toggle link on selection

**Example:**

<CodeGroup>
  ```javascript Usage theme={null}
  editor.commands.toggleLink({ href: 'https://example.com' })
  editor.commands.toggleLink()
  ```

  ```javascript Full Example theme={null}
  import { SuperDoc } from 'superdoc';
  import 'superdoc/style.css';

  const superdoc = new SuperDoc({
    selector: '#editor',
    document: yourFile,
    onReady: (superdoc) => {
      const editor = superdoc.activeEditor;
      editor.commands.toggleLink({ href: 'https://example.com' })
      editor.commands.toggleLink()
    },
  });
  ```
</CodeGroup>

**Parameters:**

<ParamField path="options" type="SetLinkOptions" required>
  Link configuration
</ParamField>

## Types

### `TargetFrameOptions`

Target frame options

### `SetLinkOptions`

Link options for setLink command

<Expandable title="Properties">
  <ResponseField name="href" type="string">
    URL for the link
  </ResponseField>

  <ResponseField name="text" type="string">
    Display text (uses selection if omitted)
  </ResponseField>
</Expandable>

## Source code

<SourceCodeLink path="packages/super-editor/src/editors/v1/extensions/link/link.js" />
