# `@materi.ai/frame`

**Complete collaborative document editing framework** with production-ready operational transformation, formula engine, design system, and React hooks. Embed rich document experiences into your application in minutes.

[![npm version](https://img.shields.io/npm/v/@materi.ai/frame.svg)](https://www.npmjs.com/package/@materi.ai/frame) [![TypeScript](https://img.shields.io/badge/TypeScript-5.6%2B-3178c6)](https://www.typescriptlang.org/) [![React](https://img.shields.io/badge/React-19.0%2B-61dafb)](https://reactjs.org/) [![Node.js](https://img.shields.io/badge/Node.js-18%2B-339933)](https://nodejs.org/) [![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](LICENSE) [![Bundle Size](https://img.shields.io/bundlephobia/min/@materi.ai/frame.svg)](https://bundlephobia.com/package/@materi.ai/frame)

## 🎯 Overview

hello

`@materi.ai/frame` is a monorepo containing four specialized, composable packages designed to work together seamlessly:

- **`@materi.ai/core`** — Business logic, algorithms, and types (OT, formula engine, auth, presence, WebSocket)
- **`@materi.ai/ui`** — Production-ready design system with tokens, primitives, and components
- **`@materi.ai/hooks`** — Reusable React hooks for document, collaboration, auth, and WebSocket
- **`@materi.ai/api`** — HTTP client layer with typed endpoint definitions

All packages are fully typed, tree-shakeable, and optimized for modern bundlers. Zero runtime dependencies (except React).

## 📖 Table of Contents

- [Installation](#-installation)
- [Quick Start](#-quick-start)
- [Documentation](#-documentation)
- [Tutorials](#-tutorials)
- [Examples](#-examples)
- [API Reference](#-api-reference)
- [Contributing](#-contributing)
- [License](#-license)

---

## 📦 Installation

```bash
npm install @materi.ai/frame
# or
pnpm add @materi.ai/frame
# or
yarn add @materi.ai/frame
```

### Peer Dependencies

- **React**: `^19.0.0`
- **React DOM**: `^19.0.0`

Ensure you have React and React DOM installed in your project:

```bash
npm install react react-dom
```

---

## 🚀 Quick Start

### Basic Setup

```tsx
import React, { useState, useEffect } from 'react';
import { useOT, useWebSocket } from '@materi.ai/frame/hooks';
import { colors, spacing } from '@materi.ai/frame/ui';

export default function DocumentEditor() {
    const [document, setDocument] = useState({ content: '', version: 0 });

    const { applyOperation, createOperation } = useOT({
        initialDocument: document,
        onUpdate: (newDoc) => setDocument(newDoc),
    });

    const { connect, disconnect, isConnected, send } = useWebSocket({
        url: 'wss://your-server.com/collaborate',
        onMessage: (message) => {
            if (message.type === 'operation') {
                applyOperation(message.data);
            }
        },
    });

    const handleTextChange = (event: React.ChangeEvent<HTMLTextAreaElement>) => {
        const newContent = event.target.value;
        const operation = createOperation(document.content, newContent);

        setDocument((prev) => ({ ...prev, content: newContent, version: prev.version + 1 }));

        if (isConnected) {
            send({ type: 'operation', data: operation });
        }
    };

    useEffect(() => {
        connect();
        return () => disconnect();
    }, [connect, disconnect]);

    return (
        <div style={{ padding: spacing.lg }}>
            <div style={{ color: isConnected ? colors.success : colors.warning }}>
                {isConnected ? '🟢 Connected' : '🟡 Connecting...'}
            </div>

            <textarea
                value={document.content}
                onChange={handleTextChange}
                placeholder="Start typing to collaborate..."
                style={{
                    width: '100%',
                    height: '300px',
                    padding: spacing.md,
                    border: `1px solid ${colors.border}`,
                    borderRadius: '4px',
                }}
            />
        </div>
    );
}
```

---

## 📚 Documentation

`@materi.ai/frame` includes comprehensive documentation to get you from installation to production deployment:

### 🚀 Getting Started

- **[Quick Start Guide](./docs/GETTING_STARTED_COMPREHENSIVE.md)** — Complete 15-minute setup tutorial with working examples
- **[Installation & Setup](./docs/GETTING_STARTED_COMPREHENSIVE.md#installation)** — Package installation and bundler configuration
- **[Performance Optimization](./docs/GETTING_STARTED_COMPREHENSIVE.md#performance-optimization)** — Bundle size optimization and tree-shaking guide

### 📖 Tutorials

**Progressive learning path from beginner to advanced:**

- **[Tutorial Index](./docs/tutorials/README.md)** — Complete tutorial series overview

#### Beginner Level (🟢)

1. **[Building Your First Document Editor](./docs/tutorials/01-document-editor.md)** — 45-minute collaborative text editor tutorial with operational transformation
2. **[Adding Formula Support](./docs/tutorials/02-formula-engine.md)** — Integrating spreadsheet calculations and formula evaluation
3. **[UI Components Guide](./docs/tutorials/03-ui-components.md)** — Design system usage and theming patterns

#### Intermediate Level (🟡)

4. **[Real-time Collaboration](./docs/tutorials/04-collaboration.md)** — Multi-user editing with presence indicators
5. **[Authentication Flow](./docs/tutorials/05-auth-flow.md)** — User management and security integration
6. **[API Integration](./docs/tutorials/06-api-integration.md)** — Backend connectivity and data synchronization

#### Advanced Level (🔴)

7. **[Performance Optimization](./docs/tutorials/07-performance.md)** — Bundle optimization and production deployment
8. **[Custom Components](./docs/tutorials/08-custom-components.md)** — Extending the design system
9. **[Production Deployment](./docs/tutorials/09-deployment.md)** — Scalable deployment strategies and monitoring

### 💡 Examples

**Real-world application examples with complete source code:**

- **[Examples Overview](./examples/README.md)** — Gallery of example applications
- **[Collaborative Editor](./examples/collaborative-editor/README.md)** — Complete collaborative text editor with WebSocket integration
- **[Spreadsheet Calculator](./examples/spreadsheet-calculator/README.md)** — Formula engine demonstration with live calculations
- **[Component Showcase](./examples/component-showcase/README.md)** — Interactive gallery of all UI components

### 📋 API Reference

**Comprehensive API documentation:**

- **[TypeDoc API Reference](./docs/api/README.md)** — Auto-generated API documentation from TypeScript source
- **[Core Package API](./docs/api/modules/core.md)** — Operational transformation, formula engine, auth, WebSocket
- **[UI Package API](./docs/api/modules/ui.md)** — Design system components, tokens, and themes
- **[Hooks Package API](./docs/api/modules/hooks.md)** — React hooks for collaboration and data management
- **[API Package Reference](./docs/api/modules/api.md)** — HTTP client and endpoint definitions

### 🛠️ Development

**Contributing and development guides:**

- **[Contributing Guidelines](./CONTRIBUTING.md)** — Complete development setup and contribution workflow
- **[Code Standards](./CONTRIBUTING.md#code-standards)** — TypeScript, React, and CSS guidelines
- **[Testing Requirements](./CONTRIBUTING.md#testing)** — Unit, integration, and E2E testing guidelines
- **[CI/CD Setup](./docs/CI-CD-SETUP.md)** — Automated testing, building, and deployment pipeline

### 🌐 Documentation Site

**Professional documentation site with search and navigation:**

- **[Documentation Homepage](./docs/index.md)** — Complete documentation portal with organized navigation
- **[Site Setup Guide](./docs/DOCUMENTATION_SITE.md)** — Deploy your own documentation site
- **Search functionality** — Full-text search across all documentation
- **Mobile responsive** — Optimized for all devices and screen sizes

---

### 🧩 Individual Packages

Import specific packages directly:

```tsx
// Core algorithms and types
import { EventPriority, BaseEvents } from '@materi.ai/frame/core';
import { applyOp, transform } from '@materi.ai/frame/core/ot';
import { evaluate } from '@materi.ai/frame/core/formula';

// Design system tokens and primitives
import { colors, spacing, typography } from '@materi.ai/frame/ui';
import { Button, Card, Dialog } from '@materi.ai/frame/ui/primitives';

// React hooks (organized by service)
import { useAuth, useWorkspace } from '@materi.ai/frame/hooks'; // Shield service
import { useDocument, useSearch } from '@materi.ai/frame/hooks'; // API service
import { useOT, useWebSocket } from '@materi.ai/frame/hooks'; // Relay service

// HTTP client and endpoints
import { createHTTPClient, apiClient } from '@materi.ai/frame/api';
import { userAPI, documentAPI } from '@materi.ai/frame/api';
```

---

## 📚 Packages

### `@materi.ai/core`

Core business logic including:

- **OT Algorithms** (`/ot`) — Operational transformation for real-time collaboration
- **Formula Engine** (`/formula`) — Parse, evaluate, and transform spreadsheet formulas
- **Type System** (`/types`) — Shared TypeScript type definitions
- **Auth** (`/auth`) — Authentication and permission models
- **WebSocket** (`/websocket`) — Real-time connection management
- **Presence** (`/presence`) — User presence and cursor tracking
- **Undo/Redo** (`/undo`) — Command-based undo/redo manager
- **Search** (`/search`) — Full-text search infrastructure

#### Usage

```tsx
import { OTEngine, applyOp, transform } from '@materi.ai/core/ot';
import { parseFormula, evaluateFormula } from '@materi.ai/core/formula';
import { createAuthContext } from '@materi.ai/core/auth';
```

### `@materi.ai/ui`

Production-ready design system:

- **Tokens** — Color, typography, spacing, shadows, borders
- **Primitives** — Accessible, unstyled base components (Button, Input, Dialog, Select, etc.)
- **Components** — Materi-branded higher-level components
- **Themes** — Light/dark mode support with semantic tokens
- **Styles** — Global CSS with resets and utilities

#### Usage

```tsx
import { Button, Input, Tabs, Dialog } from '@materi.ai/frame/ui';
import { tokens } from '@materi.ai/frame/ui/tokens';
import { useTheme } from '@materi.ai/frame/ui/themes';
import '@materi.ai/frame/ui/styles.css';

// Access tokens programmatically
const { colors, spacing, typography } = tokens;

// Use theme hook for dynamic theming
const { theme, setTheme } = useTheme();
```

### `@materi.ai/hooks`

Reusable React hooks for collaborative features:

- **`useOT()`** — Manage operational transformation state and operations
- **`useWebSocket()`** — Connect to WebSocket server, handle messages
- **`useAuth()`** — Authentication state and user session
- **`useFetch()`** — Type-safe HTTP requests with caching
- **`useCommandPalette()`** — Command palette UI state
- **`useUndoRedo()`** — Undo/redo command management
- **`useLocalStorage()`** — Persistent local state
- **`useForm()`** — Form state and validation
- **`usePerformance()`** — Performance monitoring and profiling

#### Usage

```tsx
import { useOT, useWebSocket, useAuth } from '@materi.ai/frame/hooks';

export function MyComponent() {
    const { state, applyOp } = useOT();
    const { connect, isConnected, send } = useWebSocket();
    const { user, logout } = useAuth();

    // Your component logic
}
```

### `@materi.ai/api`

Typed HTTP client and endpoint definitions:

- **Client** — Lightweight HTTP client with interceptors
- **Endpoints** — Pre-defined API routes with TypeScript inference
- **Result** — Type-safe result handling (success/error)

#### Usage

```tsx
import { createClient } from '@materi.ai/frame/api';
import { endpoints } from '@materi.ai/frame/api/endpoints';

const client = createClient({
    baseURL: 'https://api.example.com',
    headers: {
        Authorization: `Bearer ${token}`,
    },
});

// Type-safe calls
const result = await client.get(endpoints.documents.list());
if (result.ok) {
    console.log(result.data);
} else {
    console.error(result.error);
}
```

---

## 🏗️ Architecture Highlights

### Monorepo Structure

```
frame/
├── core/           # Business logic, algorithms, types
├── ui/             # Design system, components
├── hooks/          # React hooks
├── api/            # HTTP client
├── package.json    # Root workspace config
└── turbo.json      # Build orchestration
```

### Build Strategy

- **TypeScript Compilation** — Each package compiles to CommonJS + ESM
- **Turbo Caching** — Fast, cached builds across the monorepo
- **Zero Runtime Dependencies** — Only React as peer dependency
- **Tree Shakeable** — Unused code is eliminated by bundlers
- **Distributed Types** — Full `.d.ts` generation for IDE support

### Publishing

- **NPM Package** — Published as `@materi.ai/frame`
- **Subpath Exports** — Import packages as `@materi.ai/frame/core`, `@materi.ai/frame/ui`, etc.
- **Source Maps** — Full source map support for debugging

---

## 🛠️ Development

### Setup

```bash
# Install dependencies
pnpm install

# Build all packages
pnpm build

# Build a specific package
pnpm build:core
pnpm build:ui
pnpm build:hooks
pnpm build:api

# Type check
pnpm type-check

# Run tests
pnpm test
pnpm test:watch
pnpm test:coverage

# Lint
pnpm lint

# Format
pnpm format

# Clean build artifacts
pnpm clean
```

### Development Workflow

```bash
# Watch all packages (from frame directory)
pnpm build:watch

# Run tests in watch mode
pnpm test:watch

# Type check continuously
pnpm type-check
```

### Testing

Each package includes a `__tests__/` directory with Vitest specs:

```bash
# Run all tests
pnpm test

# Run tests for a specific package
pnpm -F @materi.ai/core test

# Generate coverage report
pnpm test:coverage
```

---

## 📖 API Documentation

### Core Types

All packages export comprehensive TypeScript types. For IDE autocomplete, ensure your `tsconfig.json` includes:

```json
{
    "compilerOptions": {
        "strict": true,
        "skipLibCheck": true,
        "declaration": true
    }
}
```

### Package Exports

#### `@materi.ai/frame` (Main Entry)

```tsx
import {} from /* all named exports from all subpackages */ '@materi.ai/frame';
```

#### `@materi.ai/frame/core`

```tsx
import {
    OTEngine,
    FormulaEngine,
    createAuthContext,
    WebSocketManager,
    // ... and more
} from '@materi.ai/frame/core';

// Subpackage imports
import { applyOp, transform } from '@materi.ai/frame/core/ot';
import { parseFormula, evaluateFormula } from '@materi.ai/frame/core/formula';
import { types, interfaces } from '@materi.ai/frame/core/types';
```

#### `@materi.ai/frame/ui`

```tsx
import {
    Button,
    Input,
    Dialog,
    Tabs,
    // ... primitives and components
} from '@materi.ai/frame/ui';

import { tokens } from '@materi.ai/frame/ui/tokens';
import { useTheme } from '@materi.ai/frame/ui/themes';
import '@materi.ai/frame/ui/styles.css';
```

#### `@materi.ai/frame/hooks`

```tsx
import {
    useOT,
    useWebSocket,
    useAuth,
    useFetch,
    useCommandPalette,
    useUndoRedo,
    // ... and more
} from '@materi.ai/frame/hooks';
```

#### `@materi.ai/frame/api`

```tsx
import { createClient } from '@materi.ai/frame/api';
import { endpoints } from '@materi.ai/frame/api/endpoints';
```

---

## 🎨 Design System Features

### Tokens

Comprehensive design tokens for:

- **Colors** — Semantic and raw color palette
- **Typography** — Font families, sizes, weights, line heights
- **Spacing** — Consistent spacing scale
- **Shadows** — Elevation system
- **Borders** — Radius and border styles
- **Transitions** — Animation timing functions

### Components

All components are:

- ✅ **Accessible** — ARIA attributes, keyboard navigation
- ✅ **Unstyled** — Compose with Tailwind, CSS-in-JS, or vanilla CSS
- ✅ **Controlled & Uncontrolled** — Both patterns supported
- ✅ **Tested** — Comprehensive test coverage
- ✅ **Type Safe** — Full TypeScript support

---

## 🔐 Security Considerations

- All packages are built with strict TypeScript (`strict: true`)
- No eval() or dynamic code execution
- Sanitized formula parsing (no injection vectors)
- CSRF protection in API client
- WebSocket message validation

---

## 📊 Performance

- **Zero Runtime Dependencies** — Minimal bundle size
- **Tree Shakeable** — Only bundle what you use
- **Code Splitting** — Subpath exports enable granular loading
- **Lazy Loading** — Component and hook patterns support code splitting
- **Caching** — Built-in HTTP caching strategies

### Bundle Size Estimates

| Package            | Gzipped     |
| ------------------ | ----------- |
| `@materi.ai/core`  | ~45 KB      |
| `@materi.ai/ui`    | ~35 KB      |
| `@materi.ai/hooks` | ~12 KB      |
| `@materi.ai/api`   | ~8 KB       |
| **Total**          | **~100 KB** |

---

## 📋 API Reference

**Complete TypeDoc API Documentation:**

- **[TypeDoc API Reference](./docs/api/)** — Auto-generated API documentation with search and cross-references
- **[Getting Started](./docs/GETTING_STARTED_COMPREHENSIVE.md)** — Complete setup guide with examples
- **[Tutorials](./docs/tutorials/README.md)** — Step-by-step learning path from beginner to advanced
- **[Examples](./examples/README.md)** — Working example applications with full source code

### Package-Specific Documentation

- **[Core Package](./docs/api/modules/core.md)** — Operational transformation, formula engine, auth, WebSocket management
- **[UI Package](./docs/api/modules/ui.md)** — Design system components, tokens, themes, and styling
- **[Hooks Package](./docs/api/modules/hooks.md)** — React hooks for collaboration, authentication, and data management
- **[API Package](./docs/api/modules/api.md)** — HTTP client, endpoint definitions, and request management

### Quick Reference

```typescript
// Core types and algorithms
import { BaseEvents, EventPriority } from '@materi.ai/frame/core';
import { applyOp, transform } from '@materi.ai/frame/core/ot';
import { evaluate } from '@materi.ai/frame/core/formula';

// UI components and tokens
import { colors, spacing } from '@materi.ai/frame/ui';
import { Button, Card } from '@materi.ai/frame/ui/primitives';

// React hooks by service
import { useAuth, useWorkspace } from '@materi.ai/frame/hooks'; // Shield
import { useDocument, useSearch } from '@materi.ai/frame/hooks'; // API
import { useOT, useWebSocket } from '@materi.ai/frame/hooks'; // Relay

// HTTP client
import { createHTTPClient, userAPI } from '@materi.ai/frame/api';
```

---

## � Examples

`@materi.ai/frame` includes comprehensive example applications and tutorials for every skill level:

### 🚀 Complete Example Applications

**Real-world applications with full source code:**

- **[Collaborative Editor](./examples/collaborative-editor/README.md)** — Complete multi-user text editor
    - Real-time operational transformation
    - WebSocket integration with presence indicators
    - Undo/redo with conflict resolution
    - Production-ready server-side OT logic

- **[Spreadsheet Calculator](./examples/spreadsheet-calculator/README.md)** — Interactive spreadsheet
    - Formula engine with 50+ functions
    - Cell dependencies and live recalculation
    - Import/export with Excel compatibility
    - Performance optimization for large datasets

- **[Component Showcase](./examples/component-showcase/README.md)** — Interactive UI gallery
    - All design system components
    - Live playground and customization
    - Theme switching and dark mode
    - Accessibility testing tools

### 📚 Step-by-Step Tutorials

**Progressive learning path with difficulty levels:**

#### Beginner (🟢) — 30-45 minutes each

- **[Document Editor Tutorial](./docs/tutorials/01-document-editor.md)** — Build your first collaborative editor
- **[Formula Engine Guide](./docs/tutorials/02-formula-engine.md)** — Add calculation capabilities
- **[UI Components](./docs/tutorials/03-ui-components.md)** — Master the design system

#### Intermediate (🟡) — 45-60 minutes each

- **[Real-time Collaboration](./docs/tutorials/04-collaboration.md)** — Multi-user editing with presence
- **[Authentication Integration](./docs/tutorials/05-auth-flow.md)** — User management and security
- **[Backend API Integration](./docs/tutorials/06-api-integration.md)** — Connect to your services

#### Advanced (🔴) — 60-90 minutes each

- **[Performance Optimization](./docs/tutorials/07-performance.md)** — Bundle size and runtime optimization
- **[Custom Components](./docs/tutorials/08-custom-components.md)** — Extend the design system
- **[Production Deployment](./docs/tutorials/09-deployment.md)** — Scalable deployment strategies

### 🏃‍♂️ Quick Code Examples

#### Operational Transformation

```typescript
import { applyOp, transform } from '@materi.ai/frame/core/ot';

// Apply operation to document content
const content = 'Hello world';
const operation = { type: 'insert', position: 5, text: ' beautiful' };
const result = applyOp(content, operation);
console.log(result); // "Hello beautiful world"
```

#### Formula Engine

```typescript
import { evaluate } from '@materi.ai/frame/core/formula';

// Spreadsheet-style calculations
const result = evaluate('SUM(A1:A10) + AVERAGE(B1:B5)', {
    A1: 10,
    A2: 20,
    A3: 30 /* ... more cells */,
    B1: 5,
    B2: 15,
    B3: 25,
    B4: 35,
    B5: 45,
});
```

#### React Hooks Integration

```typescript
import { useOT, useWebSocket } from '@materi.ai/frame/hooks';

function CollaborativeEditor() {
    const { document, applyOperation } = useOT({
        initialDocument: { content: '', version: 0 },
    });

    const { send, isConnected } = useWebSocket({
        url: 'wss://your-server.com/collaborate',
        onMessage: (msg) => {
            if (msg.type === 'operation') {
                applyOperation(msg.data);
            }
        },
    });

    // Real-time collaboration ready!
}
```

#### Design System Usage

```typescript
import { Button, Card, Dialog } from '@materi.ai/frame/ui';
import { colors, spacing } from '@materi.ai/frame/ui/tokens';

function UserInterface() {
  return (
    <Card padding="lg" style={{ margin: spacing.md }}>
      <Button
        variant="primary"
        onClick={() => console.log('Interactive!')}
      >
        Click me
      </Button>
    </Card>
  );
}
```

### 📱 Live Demos

**Try the examples online:**

- **[Collaborative Editor Demo](https://materi-frame-editor.vercel.app)** — Multi-user editing in your browser
- **[Component Playground](https://materi-frame-components.vercel.app)** — Interactive design system showcase
- **[Formula Calculator](https://materi-frame-formulas.vercel.app)** — Spreadsheet engine demonstration

**Getting Started:**

1. Choose an example that matches your needs
2. Follow the step-by-step README instructions
3. Copy and adapt the code for your project
4. Check the tutorials for deeper understanding

---

---

## 📚 Tutorials

**Step-by-step learning path from beginner to production deployment:**

### 🎯 Tutorial Series Overview

Our comprehensive tutorial series takes you from basic setup to advanced production patterns. Each tutorial builds on previous knowledge and includes:

- **Complete working code** — Copy-paste ready examples
- **Step-by-step explanations** — Understand every line
- **Best practices** — Production-ready patterns
- **Troubleshooting guides** — Common issues and solutions

**Time Investment:** 6-8 hours total (can be completed over several sessions)  
**Prerequisites:** Basic React and TypeScript knowledge

### 🟢 Beginner Level (Start Here)

#### [Tutorial 1: Building Your First Document Editor](./docs/tutorials/01-document-editor.md)

**Duration:** 45 minutes | **Difficulty:** Easy

Build a complete collaborative text editor with operational transformation:

```typescript
// What you'll build
function DocumentEditor() {
  const { content, applyOperation, undo, redo } = useDocument();
  const { send, isConnected } = useWebSocket('ws://localhost:8080');

  return (
    <div>
      <Toolbar onUndo={undo} onRedo={redo} connected={isConnected} />
      <Editor content={content} onChange={applyOperation} />
    </div>
  );
}
```

**You'll learn:** OT basics, hooks usage, real-time updates, undo/redo

#### [Tutorial 2: Adding Formula Support](./docs/tutorials/02-formula-engine.md)

**Duration:** 35 minutes | **Difficulty:** Easy-Medium

Integrate spreadsheet-style calculations into your editor:

```typescript
// Add formula evaluation to cells
const cellValue = evaluate('=SUM(A1:A10) + AVERAGE(B1:B5)', cellData);
const dependencies = getDependencies('=A1*B1+C1'); // ['A1', 'B1', 'C1']
```

**You'll learn:** Formula parsing, dependency tracking, live recalculation

#### [Tutorial 3: UI Components & Theming](./docs/tutorials/03-ui-components.md)

**Duration:** 30 minutes | **Difficulty:** Easy

Master the design system and create beautiful interfaces:

```typescript
// Professional UI in minutes
<Card padding="lg" shadow="md">
  <Button variant="primary" size="md" onClick={handleSave}>
    Save Document
  </Button>
  <Button variant="secondary" size="md" onClick={handleCancel}>
    Cancel
  </Button>
</Card>
```

**You'll learn:** Design tokens, component composition, theming, accessibility

### 🟡 Intermediate Level

#### [Tutorial 4: Real-time Collaboration](./docs/tutorials/04-collaboration.md)

**Duration:** 60 minutes | **Difficulty:** Medium

Add multi-user editing with presence indicators:

```typescript
// Multi-user collaboration
const { users, cursors } = usePresence();
const { document, applyRemoteOp } = useOT({
    onRemoteOperation: (op) => broadcastToUsers(op),
    onConflict: (local, remote) => transform(local, remote),
});
```

**You'll learn:** Presence tracking, conflict resolution, cursor synchronization

#### [Tutorial 5: Authentication & Security](./docs/tutorials/05-auth-flow.md)

**Duration:** 45 minutes | **Difficulty:** Medium

Secure your application with authentication:

```typescript
// Complete auth flow
const { user, login, logout, permissions } = useAuth();
const { documents } = useWorkspace(user.workspaceId);

// Permission-based UI
{permissions.canEdit && <EditButton />}
```

**You'll learn:** JWT tokens, permission systems, secure WebSocket connections

#### [Tutorial 6: Backend Integration](./docs/tutorials/06-api-integration.md)

**Duration:** 50 minutes | **Difficulty:** Medium

Connect to your backend services:

```typescript
// Typed API integration
const { data, loading, error } = useFetch('/api/documents', {
    params: { userId: user.id },
    cache: '5m',
});

const { mutate } = useAPI(documentAPI.updateDocument);
```

**You'll learn:** HTTP client usage, caching strategies, error handling

### 🔴 Advanced Level

#### [Tutorial 7: Performance Optimization](./docs/tutorials/07-performance.md)

**Duration:** 75 minutes | **Difficulty:** Hard

Optimize for production performance:

```typescript
// Bundle size optimization
import { applyOp } from '@materi.ai/frame/core/ot'; // ✅ 2KB
import { Button } from '@materi.ai/frame/ui/primitives'; // ✅ 5KB

// Runtime optimization
const MemoizedEditor = memo(Editor);
const { content, loading } = useSuspenseDocument(documentId);
```

**You'll learn:** Tree-shaking, code splitting, runtime optimization, monitoring

#### [Tutorial 8: Custom Components](./docs/tutorials/08-custom-components.md)

**Duration:** 60 minutes | **Difficulty:** Hard

Extend the design system with custom components:

```typescript
// Create custom components that integrate seamlessly
const CustomToolbar = forwardRef<HTMLDivElement, ToolbarProps>(
  ({ variant, children, ...props }, ref) => {
    const { colors, spacing } = useTokens();
    return (
      <div ref={ref} className="custom-toolbar" {...props}>
        {children}
      </div>
    );
  }
);
```

**You'll learn:** Design system extension, accessibility patterns, TypeScript integration

#### [Tutorial 9: Production Deployment](./docs/tutorials/09-deployment.md)

**Duration:** 90 minutes | **Difficulty:** Hard

Deploy scalable, production-ready applications:

```bash
# Production deployment pipeline
pnpm build                    # Optimized build
pnpm test:e2e                # End-to-end tests
docker build -t app .        # Container packaging
kubectl apply -f k8s/        # Kubernetes deployment
```

**You'll learn:** CI/CD pipelines, monitoring, scaling, error tracking

### 🎓 Tutorial Completion

**After completing all tutorials, you'll be able to:**

- ✅ Build production-ready collaborative applications
- ✅ Implement real-time editing with operational transformation
- ✅ Create beautiful, accessible user interfaces
- ✅ Integrate authentication and authorization
- ✅ Optimize performance and bundle sizes
- ✅ Deploy scalable applications to production
- ✅ Extend and customize the framework

**Next Steps:**

- Browse [Example Applications](./examples/README.md) for advanced patterns
- Check [API Reference](./docs/api/README.md) for detailed documentation
- Join our community and contribute back!

---

## 🔧 Troubleshooting

### Installation Issues

**"Cannot find module '@materi.ai/frame'"**

```bash
# Ensure package is installed
npm install @materi.ai/frame

# Clear cache if needed
npm cache clean --force
rm -rf node_modules package-lock.json
npm install
```

**TypeScript import errors**

Ensure `moduleResolution` is set correctly:

```json
{
    "compilerOptions": {
        "moduleResolution": "bundler", // or "node16"
        "allowSyntheticDefaultImports": true,
        "esModuleInterop": true
    }
}
```

### Runtime Issues

**"React hooks error"**

Ensure React 19+ is installed:

```bash
npm install react@^19.0.0 react-dom@^19.0.0
```

**"WebSocket connection failed"**

1. Check server is running: `curl -I http://your-server.com`
2. Verify WebSocket endpoint: `wscat -c wss://your-server.com/ws`
3. Check CORS headers for cross-origin requests
4. Verify network/proxy settings allow WebSocket upgrades

**"Operation transform conflicts"**

- Ensure all clients use same document version
- Check operation ordering (use vector clocks)
- Verify server properly sequences operations

### Development Issues

**Bundle size too large**

```typescript
// Import only what you need
import { colors } from '@materi.ai/frame/ui'; // ✅ Specific import
import * as ui from '@materi.ai/frame/ui'; // ❌ Imports everything

// Use individual package imports for better tree-shaking
import { useAuth } from '@materi.ai/frame/hooks'; // ✅ Tree-shakeable
```

**Slow TypeScript compilation**

```json
{
    "compilerOptions": {
        "incremental": true,
        "composite": true
    },
    "include": ["src/**/*"],
    "exclude": ["node_modules", "dist"]
}
```

### Getting Help

1. **Check the examples**: [`./examples/`](./examples/)
2. **Read the API docs**: [`./docs/API.md`](./docs/API.md)
3. **Search issues**: [GitHub Issues](https://github.com/materi-ai/frame/issues)
4. **Create an issue**: Include version, error message, and minimal reproduction

**Debugging checklist:**

- ☐ Latest version of `@materi.ai/frame`?
- ☐ React 19+ installed?
- ☐ TypeScript 5.6+ (if using TypeScript)?
- ☐ Node.js 18+?
- ☐ Modern bundler (Vite 5+, Webpack 5+)?

---

## � Migration Guide

Upgrading from internal packages or older versions?

**[Migration Guide](./docs/MIGRATION.md)** — Step-by-step migration instructions

Key changes:

- Single package install: `npm install @materi.ai/frame`
- Subpath exports: `@materi.ai/frame/core`, `@materi.ai/frame/ui`
- Improved hook organization by service (Shield, API, Relay)
- `Result<T>` return types for better error handling

---

## 📄 Documentation

- **[Getting Started](./docs/GETTING_STARTED.md)** — Complete tutorial with working examples
- **[API Reference](./docs/API.md)** — Full documentation of all exports
- **[Migration Guide](./docs/MIGRATION.md)** — Upgrade from internal packages
- **[Examples](./examples/)** — Copy-paste code samples
- **[CHANGELOG](./CHANGELOG.md)** — Release notes and version history

---

## 👥 Contributing

We welcome contributions! Please see [CONTRIBUTING.md](./CONTRIBUTING.md) for guidelines.

**Quick start for contributors:**

```bash
# Clone and install
git clone https://github.com/materi-ai/frame.git
cd frame
pnpm install

# Run tests
pnpm test

# Build packages
pnpm build
```

---

MIT © Materi

---

## 🤝 Contributing

Contributions are welcome! Please ensure:

1. All tests pass: `pnpm test`
2. Code is formatted: `pnpm format`
3. Types are correct: `pnpm type-check`
4. Linter passes: `pnpm lint`

---

## 📚 Resources

- [React Documentation](https://react.dev)
- [TypeScript Handbook](https://www.typescriptlang.org/docs/)
- [Operational Transformation](https://en.wikipedia.org/wiki/Operational_transformation)
- [Accessible Rich Internet Applications (ARIA)](https://www.w3.org/WAI/ARIA/apg/)

---

## 🎯 Roadmap

- [ ] Official storybook components gallery
- [ ] GraphQL client integration
- [ ] Offline-first synchronization
- [ ] Advanced formula functions (financial, statistical)
- [ ] Rich text editor with collaborative cursors
- [ ] E2E encryption support
- [ ] Performance monitoring dashboard

---

**Built with ❤️ by Materi Engineering**
