> ## 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.

# Linked Styles 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>;
};

Apply Word document styles to maintain consistent formatting across your document.

Linked styles preserve the original Word styling system, including style inheritance and formatting rules.

<Note>
  **Important:** Linked Styles work with Word documents. This demo simulates the visual effect.
</Note>

<SuperDocEditor
  html={`<p>Select text and apply Word styles. Each style clears existing formatting and applies its complete definition.</p><p style="font-weight: bold; color: red;">This paragraph has inline styles that will be replaced when you apply a style.</p><p>Try different styles to see how they transform the text appearance.</p>`}
  height="350px"
  customButtons={[
[
  {
    label: 'Normal',
    onClick: (superdoc) => {
      const editor = superdoc?.activeEditor || superdoc?.editor
      if (!editor?.commands) return
      // Clear all formatting to simulate Normal style
      editor.commands.clearNodes()
      editor.commands.unsetAllMarks()
      editor.commands.setNodeAttributes('paragraph', { styleId: 'Normal' })
    }
  },
  {
    label: 'Heading 1', 
    onClick: (superdoc) => {
      const editor = superdoc?.activeEditor || superdoc?.editor
      if (!editor?.commands) return
      // Simulate Heading 1 style
      editor.commands.clearNodes()
      editor.commands.unsetAllMarks()
      editor.commands.setHeading({ level: 1 })
      editor.commands.setNodeAttributes('heading', { styleId: 'Heading1' })
    }
  },
  {
    label: 'Heading 2',
    onClick: (superdoc) => {
      const editor = superdoc?.activeEditor || superdoc?.editor
      if (!editor?.commands) return
      // Simulate Heading 2 style
      editor.commands.clearNodes()
      editor.commands.unsetAllMarks()
      editor.commands.setHeading({ level: 2 })
      editor.commands.setNodeAttributes('heading', { styleId: 'Heading2' })
    }
  }
],
[
  {
    label: 'Title',
    onClick: (superdoc) => {
      const editor = superdoc?.activeEditor || superdoc?.editor
      if (!editor?.commands) return
      // Simulate Title style with large text
      editor.commands.clearNodes()
      editor.commands.unsetAllMarks()
      editor.commands.setHeading({ level: 1 })
      editor.commands.updateAttributes('heading', { 
        styleId: 'Title',
        level: 1
      })
      // Apply visual formatting
      editor.chain()
        .setMark('textStyle', { fontSize: '28pt' })
        .run()
    }
  },
  {
    label: 'Subtitle',
    onClick: (superdoc) => {
      const editor = superdoc?.activeEditor || superdoc?.editor
      if (!editor?.commands) return
      // Simulate Subtitle style
      editor.commands.clearNodes()
      editor.commands.unsetAllMarks()
      editor.commands.setHeading({ level: 2 })
      editor.commands.updateAttributes('heading', { 
        styleId: 'Subtitle',
        level: 2
      })
      editor.chain()
        .setMark('textStyle', { fontSize: '15pt', color: '#5A5A5A' })
        .run()
    }
  }
]
]}
/>

## Real-World Usage

When a Word document is loaded:

```javascript theme={null}
// Styles are automatically imported from styles.xml
const styles = editor.helpers.linkedStyles.getStyles()

// Apply a style by ID
editor.commands.setStyleById('Heading1')

// Or with the style object
const titleStyle = editor.helpers.linkedStyles.getStyleById('Title')
editor.commands.setLinkedStyle(titleStyle)
```

## OOXML Structure

```xml theme={null}
<w:p>
  <w:pPr>
    <w:pStyle w:val="Heading1"/>
  </w:pPr>
  <w:r>
    <w:t>Text with Heading 1 style</w:t>
  </w:r>
</w:p>
```

## Use case

* **Document Templates** - Maintain corporate style guides
* **Consistency** - Uniform formatting across large documents
* **Quick Formatting** - One-click style application
* **Word Compatibility** - Preserves Word's style system
* **Style Updates** - Change all instances by updating the style definition

## Commands

### `setLinkedStyle`

Apply a linked style to the selected paragraphs.

**Example:**

<CodeGroup>
  ```javascript Usage theme={null}
  const style = editor.helpers.linkedStyles.getStyleById('Heading1');
  editor.commands.setLinkedStyle(style);
  ```

  ```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;
      const style = editor.helpers.linkedStyles.getStyleById('Heading1');
      editor.commands.setLinkedStyle(style);
    },
  });
  ```
</CodeGroup>

**Parameters:**

<ParamField path="style" type="LinkedStyle" required>
  The style object to apply
</ParamField>

### `toggleLinkedStyle`

Toggle a linked style on the current selection. Removes the style if already applied, applies it if not.

**Example:**

<CodeGroup>
  ```javascript Usage theme={null}
  const style = editor.helpers.linkedStyles.getStyleById('Heading1');
  editor.commands.toggleLinkedStyle(style)
  editor.commands.toggleLinkedStyle(style, 'paragraph')
  ```

  ```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;
      const style = editor.helpers.linkedStyles.getStyleById('Heading1');
      editor.commands.toggleLinkedStyle(style)
      editor.commands.toggleLinkedStyle(style, 'paragraph')
    },
  });
  ```
</CodeGroup>

**Parameters:**

<ParamField path="style" type="LinkedStyle" required>
  The linked style to apply (with id property)
</ParamField>

<ParamField path="nodeType" type="string">
  Node type to restrict toggle to (e.g., 'paragraph')
</ParamField>

### `setStyleById`

Apply a linked style by its ID.

**Example:**

<CodeGroup>
  ```javascript Usage theme={null}
  editor.commands.setStyleById('Heading1')
  editor.commands.setStyleById('Normal')
  ```

  ```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.setStyleById('Heading1')
      editor.commands.setStyleById('Normal')
    },
  });
  ```
</CodeGroup>

**Parameters:**

<ParamField path="styleId" type="string" required>
  The style ID to apply (e.g., 'Heading1')
</ParamField>

## Helpers

### `getStyles`

Get all available linked styles from the document.

**Example:**

<CodeGroup>
  ```javascript Usage theme={null}
  const styles = editor.helpers.linkedStyles.getStyles();
  ```

  ```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;
      const styles = editor.helpers.linkedStyles.getStyles();
    },
  });
  ```
</CodeGroup>

**Returns:**

<ResponseField name="return" type="Array" required>
  Array of linked style objects
</ResponseField>

### `getStyleById`

Get a specific style by ID.

**Example:**

<CodeGroup>
  ```javascript Usage theme={null}
  const headingStyle = editor.helpers.linkedStyles.getStyleById('Heading1');
  ```

  ```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;
      const headingStyle = editor.helpers.linkedStyles.getStyleById('Heading1');
    },
  });
  ```
</CodeGroup>

**Parameters:**

<ParamField path="styleId" type="string" required>
  The style ID to find
</ParamField>

**Returns:**

<ResponseField name="return" type="Object" required>
  The style object or undefined
</ResponseField>

## Types

### `LinkedStyle`

Style definition from a Word document.

<Expandable title="Properties">
  <ResponseField name="id" type="string" required>
    Style ID (e.g., 'Heading1', 'Normal')
  </ResponseField>

  <ResponseField name="type" type="string" required>
    Style type ('paragraph' or 'character')
  </ResponseField>

  <ResponseField name="definition" type="Object" required>
    Style definition from Word
  </ResponseField>
</Expandable>

## Source code

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