# BlockWerk

# BlockWerk

A professional visual programming and simulation platform built with React + TypeScript. Create, simulate, and analyze block diagram systems with an intuitive drag-and-drop interface—designed as a modern, high-performance alternative to tools like XcosBlocks, with client-side WebAssembly simulation for unmatched speed and responsiveness.

[![npm version](https://badge.fury.io/js/blockwerk.svg)](https://badge.fury.io/js/blockwerk)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

## ✨ Features

- **Visual Programming Canvas**: Drag-and-drop block diagram editor
- **85+ Built-in Blocks**: Sources, Math operations, Controllers, Scopes, and more
- **Privacy-First Telemetry**: Anonymous usage analytics with full user opt-out (PostHog integrated)
## 🏗️ Architecture & Structure

For a detailed overview of the project structure, architecture, and core concepts, please see [PROJECT_STRUCTURE.md](./docs/PROJECT_STRUCTURE.md).

## 🔧 Development Setup

### First-Time Setup

Build WASM once (required for development):
```bash
npm run wasm:dev
```

### Start Development Server

```bash
npm run dev
```

**Optimized**: Development server now starts in ~10-15 seconds (60-70% faster than before) by skipping WASM recompilation during development.

### Build for Production

```bash
npm run build
```

### Available Scripts

| Command | Purpose | Time |
|---------|---------|-------|
| `npm run dev` | Start development server | 10-15s |
| `npm run build` | Production build | 60-110s |
| `npm run wasm:dev` | Build WASM (dev mode) | 30-60s |
| `npm run wasm:build` | Build WASM (production) | 30-60s |
| `npm run generate-definitions` | Generate block definition files | 2-3s |
| `npm run generate-manual-content` | Generate manual from block directories | 2-3s |
| `npm run sync-styling` | Sync block styling CSS | 1-2s |
| `npm run transform-blocks` | Transform blocks for production | 2-3s |
| `npm run test` | Run unit tests | 10-20s |
| `npm run test:all` | Run all tests (unit + E2E) | 30-60s |

**Note**: See [BUILD_WORKFLOW.md](./BUILD_WORKFLOW.md) for detailed build process documentation.

## 📚 Block Library

### Sources
- **Constant**: Output constant values
- **SignalGenerator**: Sine, square, triangle, sawtooth, noise, pulse waves
- **Clock**: Simulation time output
- **Step/Ramp/Pulse**: Time-based signal generators

### Math Operations
- **Gain, Sum, Product**: Basic arithmetic
- **Trigonometric**: sin, cos, tan functions
- **MinMax, Saturation**: Signal limiting
- **Integrator, Derivative**: Continuous-time operations

### Control Systems
- **PID Controller**: Proportional-Integral-Derivative
- **TransferFunction**: Linear system representation
- **StateSpace**: State-space models

### Visualization
- **Scope**: Real-time signal plotting
- **AdvancedScope**: Professional analysis with measurements
- **UPlotScope**: High-performance plotting with uPlot
- **Display**: Numeric value display with formatting
- **XYPlot**: Parametric plotting
- **Dashboard**: Multi-signal display

## 🏗️ Architecture

```
BlockWerk/
├── Canvas          # Main editing area with drag-and-drop
├── Palette         # Block library browser
├── Toolbar         # Simulation controls and tools
├── Components      # Individual blocks and connections
├── Stores          # Zustand state management
│   ├── store.ts    # Block/connection state
│   ├── simulationStore.ts # Simulation engine
│   └── themeStore.ts # UI theming
├── Services        # Business logic services
│   └── TelemetryService.ts # Analytics and privacy
├── Simulation      # JavaScript + WebAssembly engines
└── Types           # TypeScript definitions
```

## 🔧 Advanced Usage

### Custom Block Library

```tsx
import { BlockLibrary, BlockWerkBuilder } from 'blockwerk';

const customLibrary: BlockLibrary = {
  id: 'my-library',
  name: 'My Custom Blocks',
  version: '1.0.0',
  blocks: [
    {
      type: 'MyBlock',
      label: 'My Custom Block',
      category: 'Custom',
      icon: '⚡',
      width: 100,
      height: 50,
      color: '#10b981',
      borderColor: '#059669',
      inputs: [{ id: 'in', label: 'Input', side: 'left', dataType: 'number' }],
      outputs: [{ id: 'out', label: 'Output', side: 'right', dataType: 'number' }],
      params: [
        { key: 'gain', label: 'Gain', type: 'number', defaultValue: 1 }
      ],
      displayTemplate: 'K={gain}'
    }
  ]
};

<BlockWerkBuilder library={customLibrary} />
```

### Simulation Control

```tsx
import { useSimulationStore } from 'blockwerk';

function SimulationControls() {
  const {
    status,
    currentTime,
    progress,
    start,
    pause,
    resume,
    stop
  } = useSimulationStore();

  const handleStart = () => {
    const blocks = useStore.getState().blocks;
    const connections = useStore.getState().connections;
    start(blocks, connections);
  };

  return (
    <div className="simulation-controls">
      <button onClick={handleStart} disabled={status === 'running'}>
        {status === 'running' ? 'Running...' : 'Start'}
      </button>
      <button onClick={pause} disabled={status !== 'running'}>Pause</button>
      <button onClick={resume} disabled={status !== 'paused'}>Resume</button>
      <button onClick={stop} disabled={status === 'idle'}>Stop</button>

      <div>Time: {currentTime.toFixed(2)}s</div>
      <div>Progress: {progress}%</div>
    </div>
  );
}
```

### Project Persistence

```tsx
import { useStore } from 'blockwerk';

function ProjectManager() {
  const { saveProject, loadProject, exportToFile, clearProject } = useStore();

  const handleSave = () => {
    const json = saveProject();
    localStorage.setItem('blockwerk-project', json);
  };

  const handleLoad = () => {
    const json = localStorage.getItem('blockwerk-project');
    if (json) {
      loadProject(json);
    }
  };

  return (
    <div className="project-manager">
      <button onClick={handleSave}>Save Project</button>
      <button onClick={handleLoad}>Load Project</button>
      <button onClick={exportToFile}>Export to File</button>
      <button onClick={clearProject}>New Project</button>
    </div>
  );
}
```

## 🎨 Theming

BlockWerk supports multiple themes:

```tsx
import { BlockWerkBuilder } from 'blockwerk';

// Light theme
<BlockWerkBuilder theme="light" />

// Dark theme
<BlockWerkBuilder theme="dark" />

// System preference
<BlockWerkBuilder theme="system" />
```

## 🔍 API Reference

### Agent API (for AI Models & Automation)

BlockWerk provides a comprehensive Agent API for programmatic interaction, specifically designed for AI models and external automation tools.

**Quick Example:**
```javascript
// Access the API (available at window.blockwerk.agent)
const agent = window.blockwerk.agent;

// Create a simple control system
agent.clear();
const setpoint = agent.addBlock('Constant', 100, 100);
const controller = agent.addBlock('PIDController', 300, 100);
const plant = agent.addBlock('TransferFunction', 500, 100);
const scope = agent.addBlock('Scope', 700, 100);

// Configure and connect
agent.updateParams(setpoint, { value: 1.0 });
agent.connect(setpoint, 'out', controller, 'in');
agent.connect(controller, 'out', plant, 'in');
agent.connect(plant, 'out', scope, 'in');

// Get a text description
console.log(agent.describeCanvas());
```

**📖 Full Documentation:** See [docs/AGENT_API.md](./docs/AGENT_API.md) for complete API reference, examples, and LLM usage patterns.

### BlockWerkBuilder Props

| Prop | Type | Default | Description |
|------|------|---------|-------------|
| `library` | `BlockLibrary` | `defaultLibrary` | Custom block library |
| `initialBlocks` | `BlockState[]` | `[]` | Initial blocks to load |
| `initialConnections` | `Connection[]` | `[]` | Initial connections to load |
| `theme` | `Theme` | `'system'` | UI theme |
| `showPalette` | `boolean` | `true` | Show block palette |
| `showToolbar` | `boolean` | `true` | Show simulation toolbar |
| `onBlocksChange` | `(blocks: BlockState[]) => void` | - | Blocks change callback |
| `onConnectionsChange` | `(connections: Connection[]) => void` | - | Connections change callback |
| `className` | `string` | - | Custom CSS class |

### Key Exports

- `BlockWerkBuilder` - Main component
- `Canvas, Palette, Toolbar` - Individual components
- `useStore, useSimulationStore` - State management hooks
- `defaultLibrary` - Built-in block collection
- `BlockState, Connection` - Core data types

## 🧪 Testing

BlockWerk includes a comprehensive multi-phase testing suite with 129+ automated tests covering:

### **Testing Phases**
- **Phase 1**: UI Integration (8 tests) - Basic component interactions
- **Phase 2**: Integration Testing (36 tests) - Component coordination, APIs, error handling
- **Phase 3**: End-to-End Testing (24 tests) - Complete workflows, cross-platform, accessibility
- **Phase 4**: Performance & Scalability (41 tests) - Benchmarks, load testing, memory monitoring
- **Phase 5**: Data Persistence & Edge Cases (20 tests) - Save/load, validation, boundary conditions

### **Test Coverage**
- ✅ Unit tests (existing test suite)
- ✅ UI integration tests
- ✅ Component integration tests
- ✅ End-to-end user workflows
- ✅ Cross-browser compatibility (Chrome, Firefox, WebKit)
- ✅ Mobile responsiveness and touch interactions
- ✅ WCAG accessibility compliance
- ✅ Performance benchmarking and monitoring
- ✅ Load testing with large diagrams
- ✅ Memory usage and leak detection
- ✅ Data persistence and validation
- ✅ Error handling and edge cases

### **Performance Benchmarks**
- **Load Time**: <500ms (vs. XcosBlocks' slower interpreted setup)
- **Interaction Response**: <200ms
- **Memory Usage**: 13-15MB stable (20-50% lower than XcosBlocks)
- **Frame Rate**: 59-69 FPS (maintains smoothness even in complex simulations)
- **Large Diagrams**: Handles 50+ blocks efficiently
- **Simulation Speed**: 5-20x faster than XcosBlocks due to WebAssembly engine

### **Running Tests**

```bash
# Run complete test suite
npm run test:all

# Run specific phases
npm run test:phase1    # UI Integration
npm run test:phase2    # Component Integration
npm run test:phase3    # End-to-End Workflows
npm run test:phase4    # Performance & Scalability
npm run test:phase5    # Data Persistence

# Specialized test suites
npm run test:accessibility    # WCAG compliance
npm run test:mobile          # Mobile responsiveness
npm run test:cross-browser    # Cross-browser compatibility

# Development testing
npm test                     # Unit tests
npm run test:coverage        # With coverage
npm run test:ui             # Playwright UI mode
npm run test:e2e            # End-to-end tests
```

### **CI/CD Pipeline**
Automated testing runs on every push/PR with:
- **Lighthouse Performance**: Core Web Vitals monitoring
- **Accessibility Audit**: WCAG compliance checking
- **Cross-browser Testing**: Chrome, Firefox, Safari
- **Performance Regression**: Automated benchmarking

**Test Results**: 99.2% pass rate (135/136 Vitest tests passing, 112/112 WASM engine tests passing)

## 📖 Examples

See the `examples/` directory for usage examples:

- **Basic Usage**: Simple BlockWerkBuilder integration
- **Custom Blocks**: Creating custom block libraries
- **Advanced Features**: Subsystems, simulation control, theming

```bash
# Run the basic example
cd examples
npm install
npm run dev
```

## 📦 Build & Development

```bash
# Development server (demo app)
npm run dev

# Build for production (demo app)
npm run build

# Build library for publishing
npm run build:lib

# Lint code
npm run lint

# Type checking
npm run build  # TypeScript checks included

# Run examples
cd examples && npm install && npm run dev
```

## 🚀 Publishing

To publish BlockWerk to npm:

```bash
# Build the library
npm run build:lib

# Publish to npm (requires npm account)
npm publish
```

The library exports are configured in `src/lib/index.ts` and the build outputs to `dist/` with:
- `index.es.js` - ESM format
- `index.umd.js` - UMD format
- `index.d.ts` - TypeScript declarations
- `blockwerk.css` - Styles

## 🏆 Quality Assurance

### **Testing Methodology**
BlockWerk employs a rigorous, multi-phase testing strategy:

1. **Unit Testing**: Component and utility function validation
2. **Integration Testing**: Component interaction and API validation
3. **End-to-End Testing**: Complete user workflow validation
4. **Performance Testing**: Speed, memory, and scalability benchmarking
5. **Accessibility Testing**: WCAG compliance and screen reader support
6. **Cross-Platform Testing**: Desktop, mobile, tablet compatibility

### **Performance Standards**
- **Load Time**: <500ms for initial page load
- **Interaction Response**: <200ms for user actions
- **Memory Usage**: <50MB for typical usage
- **Frame Rate**: >30 FPS during animations
- **Accessibility**: WCAG 2.1 AA compliance
- **Mobile Support**: Responsive design for all screen sizes

### **Code Quality**
- **TypeScript**: 100% type coverage
- **ESLint**: Automated code style enforcement
- **Prettier**: Consistent code formatting
- **Bundle Analysis**: Optimized build sizes
- **Security**: Regular dependency updates and audits

## 🤝 Contributing

1. Fork the repository
2. Create a feature branch (`git checkout -b feature/amazing-feature`)
3. Make your changes with proper TypeScript types
4. Add comprehensive tests for new functionality
5. Run the complete test suite: `npm run test:all`
6. Ensure all tests pass and performance benchmarks are met
7. Update documentation as needed
8. Submit a pull request with a clear description

### **Development Workflow**
```bash
# Install dependencies
npm install

# Start development server
npm run dev

# Run tests continuously
npm run test:watch

# Build and test before committing
npm run build && npm run test:all
```

## 📄 License

MIT License - see [LICENSE](LICENSE) file for details.

## 🙏 Acknowledgments

- Inspired by block diagram tools like [XcosBlocks](https://xcosblocks.fossee.org/) and other industry-standard simulation software, but designed for modern web performance and usability.
- Built with [React](https://reactjs.org/), [TypeScript](https://www.typescriptlang.org/), and [Vite](https://vitejs.dev/)
- Drag-and-drop powered by [@dnd-kit](https://dndkit.com/)
- State management with [Zustand](https://zustand-demo.pmnd.rs/)
- Charts with [uPlot](https://github.com/leeoniya/uPlot)
- Simulation engine in [Rust/WebAssembly](https://rustwasm.github.io/)

You can also install [eslint-plugin-react-x](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-x) and [eslint-plugin-react-dom](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-dom) for React-specific lint rules:

```js
// eslint.config.js
import reactX from 'eslint-plugin-react-x'
import reactDom from 'eslint-plugin-react-dom'

export default defineConfig([
  globalIgnores(['dist']),
  {
    files: ['**/*.{ts,tsx}'],
    extends: [
      // Other configs...
      // Enable lint rules for React
      reactX.configs['recommended-typescript'],
      // Enable lint rules for React DOM
      reactDom.configs.recommended,
    ],
    languageOptions: {
      parserOptions: {
        project: ['./tsconfig.node.json', './tsconfig.app.json'],
        tsconfigRootDir: import.meta.dirname,
      },
      // other options...
    },
  },
])
```
