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

# Getting Started

> Learn how to integrate SmarterElements into your application

# Getting Started with SmarterElements

SmarterElements is a powerful system for embedding interactive UI components into web applications. Elements can be mounted directly into the DOM or displayed in modals with full isolation and automatic resizing.

## Installation

```bash theme={null}
npm install @smarterservices/smarter-elements
```

## Quick Start

### React Integration

```jsx theme={null}
import React from 'react';
import { useSmarterElements } from '@smarterservices/smarter-elements';

function App() {
  const elements = useSmarterElements();
  
  const openElement = async () => {
    const element = elements.create('blockkit/renderer', {
      config: {
        blocksJson: JSON.stringify([
          {
            type: "heading",
            level: 1,
            text: "Hello SmarterElements!"
          }
        ])
      }
    });
    
    await element.openModal({
      width: '600px',
      height: '400px'
    });
  };
  
  return (
    <div>
      <button onClick={openElement}>
        Open Element
      </button>
    </div>
  );
}
```

### JavaScript Integration

```javascript theme={null}
import { SmarterElements } from '@smarterservices/smarter-elements';

// Initialize the elements system
const elements = new SmarterElements({
  baseUrl: '/elements' // Your elements endpoint
});

// Create and display an element
const element = elements.create('blockkit/renderer', {
  config: {
    blocksJson: JSON.stringify([
      {
        type: "heading", 
        level: 1,
        text: "Hello SmarterElements!"
      }
    ])
  },
  onReady: () => {
    console.log('Element loaded successfully');
  },
  onError: (error) => {
    console.error('Element failed to load:', error);
  }
});

// Mount to existing DOM element
element.mount('#my-container');

// Or open in a modal
element.openModal({
  width: '80%',
  maxWidth: '900px'
});
```

## Authentication

Production embeds are authenticated with short-lived **STS tokens** minted by your backend — your long-lived API credential never reaches the browser. Your server exchanges its credential for a token scoped to a single element + end user, and hands the signed assertion to the SDK:

```javascript theme={null}
// Your backend returns { elementToken, stsToken, expiresIn, absoluteExpiresAt }
const auth = await fetch('/api/embeds/token').then((r) => r.json());

const element = elements.create('proctoring/sessionviewer', {
  config: { sessionSid: 'ES123456' },
  elementToken: auth.elementToken,                // RS256-signed element assertion
  stsToken: auth.stsToken,                        // opaque runtime credential
  tokenExpiresIn: auth.expiresIn,
  tokenAbsoluteExpiresAt: new Date(auth.absoluteExpiresAt).getTime(),
  onTokenRefresh: async () => {                   // silent rotation before expiry
    const next = await fetch('/api/embeds/token/refresh', { method: 'POST' }).then((r) => r.json());
    return {
      elementToken: next.elementToken,
      stsToken: next.stsToken,
      expiresIn: next.expiresIn,
      absoluteExpiresAt: new Date(next.absoluteExpiresAt).getTime(),
    };
  },
});

element.mount('#proctoring');
```

See [Authentication & Tokens](/smarter-elements/authentication) for how to mint and refresh tokens and the full security model.

## Core Concepts

### Elements

Elements are self-contained UI components that run in isolated contexts. Each element has:

* **Type**: A unique identifier (e.g., `blockkit/renderer`)
* **Configuration**: Parameters passed to the element
* **Events**: Messages the element can send/receive
* **Lifecycle**: Methods for mounting, destroying, etc.

### Element Lifecycle

1. **Create** - Initialize element with configuration
2. **Mount** - Attach to DOM or open in modal
3. **Ready** - Element is loaded and interactive
4. **Events** - Ongoing communication with element
5. **Destroy** - Clean up resources

### Configuration

Elements accept configuration through the `config` parameter:

```javascript theme={null}
const element = elements.create('element-type', {
  config: {
    // Element-specific parameters
    param1: 'value1',
    param2: 'value2'
  }
});
```

## Display Options

### DOM Mounting

Mount elements directly into existing DOM elements:

```javascript theme={null}
const element = elements.create('element-type', { config });
element.mount('#container'); // Mount to element with ID 'container'
element.mount('.my-class');  // Mount to first element with class
element.mount(domElement);   // Mount to DOM element reference
```

### Modal Display

Display elements in overlay modals with automatic sizing:

```javascript theme={null}
const element = elements.create('element-type', { config });

await element.openModal({
  width: '80%',           // Modal width
  height: '600px',        // Modal height (optional, auto-sizes by default)
  maxWidth: '1000px',     // Maximum width constraint
  maxHeight: '90vh',      // Maximum height constraint
  dismissOnDocumentClick: false, // Close on backdrop click
  escapeClose: true,      // Close on Escape key
  zIndex: 1000           // Modal z-index
});
```

## Event Handling

Elements can send events to the parent application:

```javascript theme={null}
const element = elements.create('element-type', {
  config: { /* ... */ },
  onEvent: (eventType, data) => {
    switch (eventType) {
      case 'user-action':
        console.log('User performed action:', data);
        break;
      case 'data-changed':
        console.log('Data updated:', data);
        break;
    }
  }
});
```

## Error Handling

Handle element errors gracefully:

```javascript theme={null}
const element = elements.create('element-type', {
  config: { /* ... */ },
  onError: (error) => {
    console.error('Element error:', error);
    // Handle error (show message, retry, etc.)
  }
});
```

## Advanced Features

### Auto-Resizing

Elements automatically resize based on their content. The modal system includes:

* **Content-driven sizing** - Height adjusts to content
* **Smooth transitions** - Animated resize changes
* **Performance optimization** - Debounced resize updates
* **Constraint handling** - Respects min/max limits

### Element Communication

Send messages to elements after they're mounted:

```javascript theme={null}
// Send data to element
element.postMessage({
  type: 'update-config',
  data: { newParam: 'newValue' }
});

// Listen for responses
element.on('config-updated', (data) => {
  console.log('Element updated:', data);
});
```

### Multiple Elements

Manage multiple elements simultaneously:

```javascript theme={null}
const elements = new SmarterElements({ baseUrl: '/elements' });

// Create multiple elements
const element1 = elements.create('type1', { config: {} });
const element2 = elements.create('type2', { config: {} });

// Mount to different containers
element1.mount('#container1');
element2.mount('#container2');

// Get all active elements
const allElements = elements.getElements();

// Clean up all elements
elements.destroyAll();
```

## Best Practices

### Performance

* **Lazy loading** - Only create elements when needed
* **Proper cleanup** - Always destroy elements when done
* **Event management** - Remove event listeners appropriately

### Error Handling

* **Graceful degradation** - Handle element load failures
* **User feedback** - Show loading states and error messages
* **Retry logic** - Implement retry for transient failures

### Accessibility

* **Keyboard navigation** - Elements support keyboard interaction
* **Screen readers** - Proper ARIA labels and roles
* **Focus management** - Modal focus trapping and restoration

## Next Steps

* Browse the [Element Reference](/smarter-elements/elements) for available elements
* Check out [Examples](/smarter-elements/examples) for common use cases
* Read the [API Reference](/smarter-elements/api) for detailed method documentation

***

*Need help? Check our [troubleshooting guide](/smarter-elements/troubleshooting) or [contact support](mailto:support@smarterservices.com).*
