resig.js
Version:
Universal reactive signal library with complete platform features: signals, animations, CRDTs, scheduling, DOM integration. Works identically across React, SolidJS, Svelte, Vue, and Qwik.
1,017 lines (834 loc) โข 40.4 kB
Markdown
# Signal-ฮฃ (Signal-Sigma)
> **Universal Reactive Platform** - Everything composes from signals
[](https://www.typescriptlang.org/)
[](https://reactjs.org/)
[](https://www.solidjs.com/)
[](https://svelte.dev/)
[](https://vuejs.org/)
[](https://qwik.builder.io/)
## ๐ **The Complete Reactive Platform**
Signal-ฮฃ is the **first truly composable reactive platform** where every featureโanimations, real-time collaboration, themes, undo/redo, scheduling, drag-drop, offline sync, blocks, **streaming, AI integration, and event sourcing**โcomposes naturally from a single primitive: **the Signal**.
```typescript
import {
signal, computed, effect,
animatedSignal, spring,
orSet, gCounter,
createThemeManager,
createUndoRedoManager,
createStreamingSignal,
createWebRTCStream,
createAIEnhancedSignal,
createEventSourcedCRDT,
debouncePlugin, cachePlugin
} from 'resig.js';
// ๐ฏ Everything starts with signals
const userInput = signal('');
const todos = orSet('user-1');
const theme = signal('light');
// ๐ Add streaming capabilities
const todoStream = createStreamingSignal([])
.throttle(100)
.filter(todos => todos.length > 0);
// ๐ Real-time WebRTC collaboration
const collaboration = createWebRTCStream('peer-1');
// ๐ค AI-enhanced input processing
const aiAssistant = createAIEnhancedSignal(
userInput.value(),
'gpt-4',
{ maxTokens: 500, temperature: 0.7 }
);
// ๐ Event sourcing for complete history
const eventSourcedTodos = createEventSourcedCRDT(
todos,
{ snapshotInterval: 10, compactionStrategy: 'sliding-window' }
);
// ๐ฌ Add smooth animations
const animatedCount = animatedSignal(
computed(() => todos.size()),
spring({ tension: 300 })
);
// ๐จ Apply theme transformations
const themedTodos = computed(() =>
todos.values().map(todo => ({
...todo,
color: theme.value() === 'dark' ? '#fff' : '#000'
}))
);
// โฐ Add time-travel capabilities
const history = createUndoRedoManager(
{ todos: [], theme: 'light' },
{ maxHistorySize: 50 }
);
// ๐ Enhance with plugins across ALL components
const debouncedInput = userInput.pipe(debouncePlugin(300));
const cachedTodos = themedTodos.pipe(cachePlugin('todos', 60000));
const persistentTheme = theme.pipe(persistPlugin('theme'));
// ๐ Everything composes seamlessly
effect(() => {
console.log(`${animatedCount.value()} todos in ${theme.value()} theme`);
console.log(`AI confidence: ${aiAssistant.confidence.value()}`);
console.log(`Event count: ${eventSourcedTodos.getEventCount()}`);
});
```
## ๐งฉ **Universal Composability**
**Every component composes with every other component.** Animations work with CRDTs, themes work with undo/redo, plugins work across all systems.
```typescript
// ๐ฏ Start with any framework - same code everywhere
import { useSignal, useComputed } from 'resig.js/react'; // or solid, svelte, vue, qwik
function CollaborativeAnimatedTodoApp() {
// ๐ Real-time collaborative data
const todos = useSignal(orSet('user-1'));
const sharedCounter = useSignal(gCounter('user-1'));
// ๐ฌ Smooth animations for all changes
const animatedCount = useComputed(() =>
animatedSignal(sharedCounter, spring({ tension: 200 }))
);
// ๐จ Dynamic theming with CSS variables
const theme = useSignal(createThemeManager({ defaultTheme: 'auto' }));
const themedStyles = useComputed(() =>
theme.getCurrentTheme().map(t => `theme-${t}`)
);
// โฐ Undo/redo for all operations
const history = useSignal(createUndoRedoManager({
todos: todos.value(),
counter: sharedCounter.value(),
theme: theme.getCurrentTheme().value()
}));
// ๐ Plugins enhance everything
const debouncedTodos = useComputed(() =>
todos.pipe(debouncePlugin(300)).pipe(cachePlugin('todos'))
);
// ๐ All systems work together seamlessly
const addTodo = (text) => {
const command = createCommand('add-todo',
state => ({ ...state, todos: state.todos.add({ text, id: Date.now() }) }),
state => ({ ...state, todos: state.todos.remove(todo) })
);
history.execute(command); // โฐ Undoable
sharedCounter.increment(); // ๐ Syncs to all users
animatedCount.trigger(); // ๐ฌ Smooth animation
theme.applyToElement(todoElement); // ๐จ Themed styling
};
return (
<div className={themedStyles}>
<h1>Count: {animatedCount}</h1>
{debouncedTodos.map(todo => <TodoItem key={todo.id} {...todo} />)}
</div>
);
}
```
## ๏ฟฝ **Quick Start: Build a Complete App in Minutes**
```bash
npm install resig.js
```
### **Real-world Example: Collaborative Task Manager**
```typescript
import {
useSignal, useComputed, useEffect,
animatedSignal, spring,
orSet, createRealtimeSync,
createThemeManager, createUndoRedoManager,
createDragContainer,
debouncePlugin, persistPlugin, cachePlugin
} from 'resig.js/react'; // Works in any framework!
function TaskManager() {
// ๐ Real-time collaborative data (CRDTs)
const sync = useSignal(() => createRealtimeSync({
channelName: 'task-app',
nodeId: `user-${Math.random().toString(36).substr(2, 9)}`
}));
const tasks = useSignal(() => {
const taskSet = orSet('user-1');
sync.registerCRDT('tasks', taskSet);
return taskSet;
});
// ๐ฌ Smooth animations for all changes
const taskCount = useComputed(() => tasks.size());
const animatedCount = useComputed(() =>
animatedSignal(taskCount, spring({ tension: 300, friction: 30 }))
);
// ๐จ Dynamic theming with real-time sync
const themeManager = useSignal(() => createThemeManager({
defaultTheme: 'auto',
persistKey: 'task-app-theme',
autoDetect: true
}));
const currentTheme = useComputed(() => themeManager.getCurrentTheme());
// โฐ Undo/redo for all operations
const history = useSignal(() => createUndoRedoManager(
{ tasks: [], theme: 'light' },
{ maxHistorySize: 50, persistKey: 'task-history' }
));
// ๐ฏ Drag-n-drop with operad composition
const dragContainer = useSignal(() => createDragContainer(
document.getElementById('task-list'),
Array.from(tasks.values()),
{
itemRenderer: (task) => `
<div class="task ${task.completed ? 'completed' : ''}">
<span class="handle">โฎโฎ</span>
<span class="text">${task.text}</span>
<button class="toggle">${task.completed ? 'โ' : 'โ'}</button>
</div>
`,
onReorder: (newTasks, operation) => {
const command = createCommand('reorder-tasks',
state => ({ ...state, tasks: newTasks }),
state => ({ ...state, tasks: Array.from(tasks.values()) })
);
history.execute(command);
}
}
));
// โก State machine for complex app state
const appStateMachine = useSignal(() => createStateMachine('idle', (state, action) => {
switch (state) {
case 'idle':
return action.type === 'START_SYNC' ? 'syncing' :
action.type === 'START_DRAG' ? 'dragging' :
action.type === 'OPEN_THEME' ? 'theming' : state;
case 'syncing':
return action.type === 'SYNC_COMPLETE' ? 'idle' :
action.type === 'SYNC_ERROR' ? 'error' : state;
case 'dragging':
return action.type === 'DROP_COMPLETE' ? 'idle' :
action.type === 'DROP_CANCEL' ? 'idle' : state;
case 'theming':
return action.type === 'THEME_APPLIED' ? 'idle' : state;
case 'error':
return action.type === 'RETRY' ? 'syncing' :
action.type === 'RESET' ? 'idle' : state;
default: return state;
}
}));
// ๐ Plugins enhance everything across all systems
const [newTaskText, setNewTaskText] = useSignal('');
const debouncedText = useComputed(() =>
newTaskText.pipe(debouncePlugin(300))
);
const cachedTasks = useComputed(() =>
tasks.pipe(cachePlugin('tasks', 60000))
);
const persistentTheme = useComputed(() =>
currentTheme.pipe(persistPlugin('theme'))
);
// State machine with plugin enhancements
const enhancedStateMachine = useComputed(() =>
appStateMachine.pipe(
loggerPlugin('app-state'),
persistPlugin('app-state-backup')
)
);
// ๐ Add task with full composability including state machine
const addTask = () => {
if (!debouncedText.trim()) return;
// State machine coordinates the entire operation
enhancedStateMachine.send({ type: 'START_SYNC' });
const task = {
id: Date.now(),
text: debouncedText,
completed: false,
createdAt: new Date().toISOString()
};
try {
// All systems work together with state machine orchestration:
const command = createCommand('add-task',
state => ({ ...state, tasks: state.tasks.add(task) }),
state => ({ ...state, tasks: state.tasks.remove(task) })
);
history.execute(command); // โฐ Undoable operation
tasks.add(task); // ๐ Syncs to all users
setNewTaskText(''); // ๐ Clear input
dragContainer.addItem(task); // ๐ฏ Update drag container
// ๐ฌ Count animates automatically via reactive composition
enhancedStateMachine.send({ type: 'SYNC_COMPLETE' });
} catch (error) {
enhancedStateMachine.send({ type: 'SYNC_ERROR', error });
}
};
// ๐จ Theme switching with state machine coordination
const switchTheme = (themeName) => {
enhancedStateMachine.send({ type: 'OPEN_THEME' });
// Create undoable theme change
const previousTheme = currentTheme.value();
const themeCommand = createCommand('change-theme',
state => ({ ...state, theme: themeName }),
state => ({ ...state, theme: previousTheme })
);
history.execute(themeCommand); // โฐ Theme changes are undoable
themeManager.setTheme(themeName); // ๐จ Apply theme
// State machine tracks completion
enhancedStateMachine.send({ type: 'THEME_APPLIED' });
// Automatically updates: animations, drag-drop, CRDTs, undo/redo
};
return (
<div className={`app theme-${persistentTheme}`}>
<header>
<h1>Tasks ({animatedCount})</h1>
<div className="theme-switcher">
<button onClick={() => switchTheme('light')}>โ๏ธ</button>
<button onClick={() => switchTheme('dark')}>๐</button>
<button onClick={() => switchTheme('auto')}>๐</button>
</div>
</header>
<div className="add-task">
<input
value={newTaskText}
onChange={(e) => setNewTaskText(e.target.value)}
onKeyPress={(e) => e.key === 'Enter' && addTask()}
placeholder="Add a task..."
/>
<button onClick={addTask}>Add</button>
</div>
<div id="task-list" className="task-list">
{/* Drag container renders here */}
</div>
<footer>
<button onClick={() => history.undo()} disabled={!history.canUndo()}>
โถ Undo
</button>
<button onClick={() => history.redo()} disabled={!history.canRedo()}>
โท Redo
</button>
<span className="sync-status">
{sync.getConnectionState().isConnected ? '๐ข Synced' : '๐ด Offline'}
</span>
</footer>
</div>
);
}
```
**That's it!** You just built a complete collaborative task manager with:
- โ
**Real-time sync** across all users
- โ
**Smooth animations** for all interactions
- โ
**Drag-n-drop reordering** with visual feedback
- โ
**Dynamic theming** with persistence
- โ
**Undo/redo** for all operations
- โ
**Plugin enhancements** across all systems
- โ
**Works in any framework** (React, Solid, Svelte, Vue, Qwik)
## ๐ **Universal Plugin System: Enhance Everything**
**The magic of Signal-ฮฃ: plugins work across ALL components.** Apply the same plugin to signals, animations, CRDTs, themes, undo/redo, drag-drop, and more.
```typescript
import {
signal, animatedSignal, orSet, createThemeManager, createUndoRedoManager,
createStateMachine, schedule,
debouncePlugin, cachePlugin, persistPlugin, loggerPlugin,
transformPlugin, validatePlugin, filterPlugin
} from 'resig.js';
// ๐ฏ Create any signal-based component
const userInput = signal('');
const todos = orSet('user-1');
const theme = createThemeManager({ defaultTheme: 'auto' });
const animatedCount = animatedSignal(signal(0), spring());
const history = createUndoRedoManager({ todos: [], theme: 'light' });
// โก State machine for orchestrating complex workflows
const appStateMachine = createStateMachine('idle', (state, action) => {
switch (state) {
case 'idle':
return action.type === 'START_OPERATION' ? 'processing' :
action.type === 'START_ANIMATION' ? 'animating' :
action.type === 'START_SYNC' ? 'syncing' : state;
case 'processing':
return action.type === 'COMPLETE' ? 'idle' :
action.type === 'ERROR' ? 'error' : state;
case 'animating':
return action.type === 'ANIMATION_END' ? 'idle' : state;
case 'syncing':
return action.type === 'SYNC_COMPLETE' ? 'idle' :
action.type === 'SYNC_ERROR' ? 'error' : state;
case 'error':
return action.type === 'RETRY' ? 'processing' :
action.type === 'RESET' ? 'idle' : state;
default: return state;
}
});
// ๐ Apply the SAME plugins to ANY component
const debouncedInput = userInput.pipe(
debouncePlugin(300), // Wait 300ms between changes
validatePlugin(text => text.length > 0), // Only allow non-empty
loggerPlugin('user-input'), // Log all changes
persistPlugin('last-input') // Save to localStorage
);
const cachedTodos = todos.pipe(
cachePlugin('todos', 60000), // Cache for 1 minute
transformPlugin(todos => todos.filter(t => !t.deleted)), // Remove deleted
loggerPlugin('todos') // Log all CRDT operations
);
const persistentTheme = theme.getCurrentTheme().pipe(
filterPlugin(theme => ['light', 'dark'].includes(theme)), // Valid themes only
persistPlugin('app-theme'), // Save theme preference
loggerPlugin('theme-changes') // Log theme switches
);
const smoothAnimations = animatedCount.pipe(
cachePlugin('animation-cache', 1000), // Cache animation frames
loggerPlugin('animations') // Log animation performance
);
const enhancedHistory = history.getCurrentState().pipe(
cachePlugin('history-cache', 30000), // Cache state snapshots
validatePlugin(state => state !== null), // Validate states
loggerPlugin('state-changes') // Log all state changes
);
// โก State machine with plugin enhancements
const enhancedStateMachine = appStateMachine.pipe(
loggerPlugin('state-machine'), // Log all state transitions
persistPlugin('app-state'), // Persist current state
cachePlugin('state-cache', 10000) // Cache state transitions
);
// ๐ Plugins compose and work together across ALL systems
const collaborativeAnimatedTodos = todos
.pipe(cachePlugin('collab-cache', 5000)) // Cache CRDT operations
.pipe(loggerPlugin('crdt-ops')) // Log CRDT changes
.map(todoSet => {
// State machine coordinates animation triggers
enhancedStateMachine.send({ type: 'START_ANIMATION' });
const animated = animatedSignal( // Convert to animated signal
signal(todoSet.size()),
spring({ tension: 200 })
);
// Complete animation state
animated.subscribe(() => {
enhancedStateMachine.send({ type: 'ANIMATION_END' });
});
return animated;
})
.pipe(cachePlugin('animation-cache', 1000)) // Cache animations
.pipe(loggerPlugin('animated-todos')); // Log animated changes
// ๐จ Even complex compositions get full plugin support
const smartThemeSystem = createThemeManager({ defaultTheme: 'auto' })
.getCurrentTheme()
.pipe(filterPlugin(theme => theme !== 'invalid'))
.pipe(transformPlugin(theme => `theme-${theme}`))
.pipe(persistPlugin('smart-theme'))
.pipe(cachePlugin('theme-cache', 10000))
.pipe(loggerPlugin('theme-system'));
```
### ๏ฟฝ **htmx/Alpine Integration**
No-build frontend reactivity:
```typescript
import { alpineSignal, htmxSignal } from 'resig.js/htmx-alpine';
// Works with Alpine.js
const data = alpineSignal({ count: 0 });
// Works with htmx
const response = htmxSignal('/api/data');
```
### ๐ **Streaming & AI Integration**
Next-generation reactive programming with streaming and AI:
```typescript
import {
createStreamingSignal,
createWebRTCStream,
createAIEnhancedSignal,
createEventSourcedCRDT,
mergeStreams,
combineStreams
} from 'resig.js';
// ๐ Streaming signals with backpressure and throttling
const dataStream = createStreamingSignal(initialData)
.throttle(100) // Limit to 10 updates/second
.filter(data => data.isValid) // Only valid data
.transform(data => processData(data))
.backpressure('drop'); // Drop excess data
// ๐ Real-time WebRTC collaboration
const collaboration = createWebRTCStream('peer-id', {
iceServers: [{ urls: 'stun:stun.l.google.com:19302' }],
reconnectAttempts: 5
});
// Broadcast changes to all peers
collaboration.subscribe(message => {
console.log('Received from peer:', message);
});
// ๐ค AI-enhanced signals with confidence tracking
const aiAssistant = createAIEnhancedSignal(
userInput.value(),
'gpt-4',
{
maxTokens: 1000,
temperature: 0.7,
streaming: true
}
);
// Monitor AI processing
aiAssistant.confidence.subscribe(confidence => {
console.log(`AI confidence: ${confidence * 100}%`);
});
aiAssistant.tokens.subscribe(usage => {
console.log(`Tokens used: ${usage.total}`);
});
// ๐ Event sourcing with automatic snapshots
const eventSourcedData = createEventSourcedCRDT(
orSet('node-1'),
{
eventStore: indexedDBEventStore('my-app'),
snapshotInterval: 100,
compactionStrategy: 'sliding-window'
}
);
// Replay events from any point in time
const historicalState = await eventSourcedData.replayFrom(timestamp);
// ๐ Combine multiple streams
const combinedStream = combineStreams({
user: userStream,
ai: aiAssistant.output,
collaboration: collaboration
});
combinedStream.subscribe(({ user, ai, collaboration }) => {
// All streams synchronized
updateUI({ user, ai, collaboration });
});
```
### ๐ง **Advanced Extensions**
Mathematical patterns for complex features:
```typescript
import {
createDragContainer, // Operad patterns
createRealtimeSync, // Commutative monoids
createThemeManager, // Functor maps
createUndoRedoManager // Coalgebraic time-travel
} from 'resig.js/extensions';
// Drag-n-drop with operad composition
const dragContainer = createDragContainer(element, items, config);
// Real-time sync with CRDT operations
const sync = createRealtimeSync({ channelName: 'app', nodeId: 'user-1' });
// Theme system with CSS variable mapping
const themes = createThemeManager({ defaultTheme: 'light' });
// Undo/redo with time-travel
const history = createUndoRedoManager(initialState, { maxHistorySize: 100 });
```
## ๐ **The Signal-ฮฃ Advantage: True Composability**
### **๐งฉ Everything Composes with Everything**
| Component | Works With | Plugin Support | Mathematical Foundation |
|-----------|------------|----------------|------------------------|
| **Signals** | All systems | โ
Universal | Category theory |
| **State Machines** | **ALL components** | โ
Universal | **Finite automata** |
| **Animations** | CRDTs, Themes, Undo/Redo, State Machines | โ
Universal | Functors |
| **CRDTs** | Animations, Themes, History, State Machines | โ
Universal | Commutative monoids |
| **Themes** | All visual components, State Machines | โ
Universal | Functor maps |
| **Undo/Redo** | All state changes, State Machines | โ
Universal | Coalgebras |
| **Drag-Drop** | All UI components, State Machines, Multi-select | โ
Universal | Operads |
| **Blocks** | All UI components | โ
Universal | Operads |
| **Offline Sync** | All data operations, IndexedDB, Conflict resolution | โ
Universal | CRDTs |
| **Scheduling** | All async operations, State Machines | โ
Universal | Stream coalgebras |
| **DOM** | All reactive bindings, State Machines | โ
Universal | Reactive streams |
### **๐ Plugin System: The Universal Enhancer**
```typescript
// ONE plugin works with EVERY component type
const myPlugin = createPlugin('enhance', (component) => {
return component.map(value => {
// Enhance ANY component: signals, animations, CRDTs, themes, etc.
return enhanceValue(value);
});
});
// Apply to everything
signal('data').pipe(myPlugin);
animatedSignal(count).pipe(myPlugin);
orSet('user-1').pipe(myPlugin);
themeManager.getCurrentTheme().pipe(myPlugin);
history.getCurrentState().pipe(myPlugin);
dragContainer.getItems().pipe(myPlugin);
```
### **๐ Framework Universality**
```typescript
// Same code, any framework
import { useSignal, useComputed } from 'resig.js/react'; // React
import { useSignal, useComputed } from 'resig.js/solid'; // SolidJS
import { useSignal, useComputed } from 'resig.js/svelte'; // Svelte
import { useSignal, useComputed } from 'resig.js/vue'; // Vue
import { useSignal, useComputed } from 'resig.js/qwik'; // Qwik
import { domSignal, bindElement } from 'resig.js/dom'; // Vanilla DOM
// ALL features work in ALL frameworks
const todos = useSignal(orSet('user-1')); // CRDTs
const animated = useComputed(() => animatedSignal(count)); // Animations
const theme = useSignal(createThemeManager(config)); // Themes
const history = useSignal(createUndoRedoManager(state)); // Time-travel
```
## ๐ **Try the Complete Demo**
Experience all Signal-ฮฃ features in our comprehensive interactive demo:
```bash
cd examples/shared-todo-library/sveltekit-app
npm install
npm run dev
```
**๐ฏ Demo Features:**
- **๐ก Signals & Effects** - Core reactive primitives with computed values
- **๐ Plugin System** - Debounce, validate, persist, logger, cache plugins
- **๐งฉ Extensions** - Drag-drop, real-time sync, theme system, undo-redo
- **๐ CRDT Integration** - G-Counter, PN-Counter, OR-Set, LWW-Register
- **๐งฑ Blocks System** - Operad-based UI composition with mathematical guarantees
- **โก Algebra Demonstrations** - Time, state machine, and fetch algebras
- **๐ฏ Multi-Item Drag-Drop** - Advanced selection with Ctrl+click and Shift+click
- **๐ก Real-time Collaboration** - CRDT-based synchronization with Express server
- **๐ฑ Offline-First Sync** - IndexedDB persistence with automatic conflict resolution
**๐ Live Demo:** [https://signal-sigma-demo.vercel.app](https://signal-sigma-demo.vercel.app)
**๐ User Guide:** [Complete usage guide](./USER_GUIDE.md) with React/Svelte best practices
## ๐ **Learn More**
- **[User Guide](./USER_GUIDE.md)** - Comprehensive guide with React/Svelte best practices and common pitfalls
- **[Complete API Reference](./API-REFERENCE.md)** - Detailed documentation of all functions and types
- **[Extensibility Guide](./EXTENSIBILITY.md)** - Mathematical patterns and advanced features
- **[Migration Guide](./MIGRATION.md)** - Moving from other reactive libraries
- **[Examples](./examples/)** - Working examples for all frameworks
- **[CRDT Server](./examples/shared-todo-library/sveltekit-app/server/)** - Express.js server with real-time collaboration
## ๐ฏ **Signal-ฮฃ vs. The Competition**
### **๐ Comprehensive Comparison Matrix**
| Feature | Signal-ฮฃ | RxJS | SolidJS Signals | Preact Signals | ArrowJS | MobX | Svelte Stores | Vue Reactivity |
|---------|----------|------|-----------------|----------------|---------|------|---------------|----------------|
| **๐ Framework Support** | โ
**7+ frameworks + DOM** | โ ๏ธ Framework agnostic | โ SolidJS only | โ ๏ธ React/Preact | โ DOM only | โ ๏ธ React/Vue | โ Svelte only | โ Vue only |
| **๐ Universal Plugin System** | โ
**Works across ALL components** | โ Operator-based only | โ No plugin system | โ No plugin system | โ No plugin system | โ No plugin system | โ No plugin system | โ No plugin system |
| **โก State Machines** | โ
**Built-in + composable** | โ External (RxState) | โ External libs | โ External libs | โ Not available | โ External libs | โ External libs | โ External libs |
| **๐ฌ Animations** | โ
**Built-in + composable** | โ External libs | โ External libs | โ External libs | โ Not available | โ External libs | โ External libs | โ External libs |
| **๐ Real-time Collaboration** | โ
**Built-in CRDTs** | โ External libs | โ External libs | โ External libs | โ Not available | โ External libs | โ External libs | โ External libs |
| **โฐ Time-travel/Undo-Redo** | โ
**Built-in coalgebraic** | โ External libs | โ External libs | โ External libs | โ Not available | โ External libs | โ External libs | โ External libs |
| **๐จ Dynamic Theming** | โ
**Built-in CSS variables** | โ External libs | โ External libs | โ External libs | โ Not available | โ External libs | โ External libs | โ External libs |
| **๐ฏ Drag-n-Drop** | โ
**Built-in operad patterns + multi-select** | โ External libs | โ External libs | โ External libs | โ Not available | โ External libs | โ External libs | โ External libs |
| **๐งฑ Block System** | โ
**Built-in operad composition** | โ Not available | โ Not available | โ Not available | โ Not available | โ Not available | โ Not available | โ Not available |
| **๐ฑ Offline Sync** | โ
**Built-in IndexedDB + conflict resolution** | โ External libs | โ External libs | โ External libs | โ Not available | โ External libs | โ External libs | โ External libs |
| **๐งฎ Mathematical Foundation** | โ
**Category theory** | โ ๏ธ Functional reactive | โ Ad-hoc | โ Ad-hoc | โ Ad-hoc | โ Ad-hoc | โ Ad-hoc | โ Ad-hoc |
| **๐ Automatic Dependency Tracking** | โ
**Always automatic** | โ Manual subscriptions | โ
Automatic | โ
Automatic | โ
Automatic | โ
Automatic | โ
Automatic | โ
Automatic |
| **๐ TypeScript Support** | โ
**Full inference** | โ
Good | โ
Excellent | โ
Good | โ ๏ธ Basic | โ
Good | โ
Good | โ
Good |
| **๐ Pure DOM Support** | โ
**Native bindings** | โ ๏ธ Manual DOM | โ Framework required | โ Framework required | โ
Native | โ Framework required | โ Framework required | โ Framework required |
| **โก Performance** | โ
**Optimized batching** | โ ๏ธ Can be heavy | โ
Excellent | โ
Good | โ
Lightweight | โ ๏ธ Can be heavy | โ
Good | โ
Good |
| **๐ฆ Bundle Size** | โ
**Tree-shakeable** | โ Large (200kb+) | โ
Small (~10kb) | โ
Small (~5kb) | โ
Tiny (~2kb) | โ ๏ธ Medium (~50kb) | โ
Small (~10kb) | โ
Small (~15kb) |
| **๐ง Learning Curve** | โ
**Consistent patterns** | โ Steep (operators) | โ
Easy | โ
Easy | โ
Very easy | โ ๏ธ Medium | โ
Easy | โ
Easy |
| **๐๏ธ Component Composition** | โ
**Operad patterns** | โ Not available | โ Basic | โ Basic | โ Not available | โ Basic | โ Basic | โ Basic |
| **โฑ๏ธ Scheduling/Debouncing** | โ
**Built-in + composable** | โ
Rich operators | โ External libs | โ External libs | โ Not available | โ External libs | โ External libs | โ External libs |
| **๐ Hot Reloading** | โ
**Framework-agnostic** | โ ๏ธ Framework dependent | โ
SolidJS only | โ
React/Preact | โ Limited | โ ๏ธ Framework dependent | โ
Svelte only | โ
Vue only |
| **๐ฑ SSR Support** | โ
**Universal** | โ ๏ธ Complex setup | โ
SolidJS only | โ
React/Preact | โ Client only | โ ๏ธ Framework dependent | โ
Svelte only | โ
Vue only |
| **๐งช Testing** | โ
**Framework-agnostic** | โ
Good tooling | โ ๏ธ SolidJS specific | โ ๏ธ React specific | โ ๏ธ Limited | โ ๏ธ Framework dependent | โ ๏ธ Svelte specific | โ ๏ธ Vue specific |
| **๐ Ecosystem** | โ
**Growing + universal** | โ
Mature | โ ๏ธ SolidJS ecosystem | โ ๏ธ React ecosystem | โ Limited | โ
Mature | โ ๏ธ Svelte ecosystem | โ
Vue ecosystem |
### **๐ Signal-ฮฃ Unique Advantages**
#### **โจ Only Signal-ฮฃ Provides:**
1. **๐ True Universality**: Same code works in React, Solid, Svelte, Vue, Qwik, Angular, and pure DOM
2. **๐ Universal Plugin System**: One plugin enhances ALL component types (signals, animations, CRDTs, state machines, themes)
3. **๐งฎ Mathematical Rigor**: Category theory foundations ensure correctness and composability
4. **โก Complete Platform**: Built-in animations, CRDTs, state machines, themes, undo/redo, multi-select drag-drop, blocks, offline sync
5. **๐ฏ Workflow Orchestration**: State machines coordinate all systems seamlessly
6. **๐ Cross-Component Composability**: Every feature works with every other feature
7. **๐ฑ Offline-First**: Built-in IndexedDB persistence with automatic conflict resolution
8. **๐งฑ Block Composition**: Operad-based UI block system with mathematical guarantees
#### **๐ Detailed Feature Comparison**
| Library | Strengths | Weaknesses | Best For |
|---------|-----------|------------|----------|
| **Signal-ฮฃ** | โ
Universal, complete platform, mathematical rigor | โ ๏ธ Newer ecosystem | **Universal apps, complex workflows, mathematical correctness** |
| **RxJS** | โ
Mature, rich operators, functional reactive | โ Steep learning curve, large bundle, framework-specific integration | **Complex async flows, experienced teams** |
| **SolidJS Signals** | โ
Excellent performance, fine-grained reactivity | โ SolidJS only, limited ecosystem | **SolidJS applications, performance-critical apps** |
| **Preact Signals** | โ
Small bundle, React compatibility | โ React/Preact only, limited features | **React/Preact apps, bundle size critical** |
| **ArrowJS** | โ
Tiny size, simple API | โ DOM only, very limited features | **Simple DOM manipulation, micro-apps** |
| **MobX** | โ
Mature, object-oriented, good tooling | โ Framework-specific, can be complex | **Object-oriented apps, existing MobX teams** |
| **Svelte Stores** | โ
Simple, integrated with Svelte | โ Svelte only, basic features | **Svelte applications** |
| **Vue Reactivity** | โ
Integrated with Vue, good performance | โ Vue only, framework-coupled | **Vue applications** |
### **๐ฏ Migration Comparison**
| From Library | To Signal-ฮฃ | Effort | Benefits |
|--------------|-------------|--------|----------|
| **RxJS** | โ ๏ธ Medium | Learn new patterns, simpler API | โ
Universal, built-in features, easier learning |
| **SolidJS Signals** | โ
Easy | Similar concepts, add features | โ
Framework freedom, more features |
| **Preact Signals** | โ
Easy | Similar API, add features | โ
Framework freedom, complete platform |
| **ArrowJS** | โ
Very Easy | Add features, keep simplicity | โ
More features, same simplicity |
| **MobX** | โ ๏ธ Medium | Different paradigm | โ
Universal, mathematical guarantees |
| **Svelte Stores** | โ
Easy | Similar concepts | โ
Framework freedom, more features |
| **Vue Reactivity** | โ
Easy | Similar concepts | โ
Framework freedom, more features |
### **๐ป Code Comparison: Same Task, Different Libraries**
#### **Task: Animated Counter with Persistence and Theming**
<details>
<summary><strong>๐ Signal-ฮฃ (Complete in one library)</strong></summary>
```typescript
import {
signal, computed, animatedSignal, spring,
createThemeManager, persistPlugin, loggerPlugin
} from 'resig.js/react'; // Works in ANY framework
function AnimatedCounter() {
// All features built-in and composable
const count = signal(0).pipe(
persistPlugin('counter'),
loggerPlugin('counter-changes')
);
const animatedCount = computed(() =>
animatedSignal(count, spring({ tension: 300 }))
);
const theme = createThemeManager({ defaultTheme: 'auto' });
const currentTheme = theme.getCurrentTheme();
return (
<div className={`counter theme-${currentTheme}`}>
<h1>{animatedCount}</h1>
<button onClick={() => count.set(count.value() + 1)}>+</button>
<button onClick={() => theme.setTheme('dark')}>๐</button>
</div>
);
}
```
</details>
<details>
<summary><strong>๐ก RxJS + React (Multiple libraries needed)</strong></summary>
```typescript
import { BehaviorSubject } from 'rxjs';
import { useObservable } from 'rxjs-hooks';
import { useSpring, animated } from '@react-spring/web';
import { useLocalStorage } from 'react-use';
import { ThemeProvider } from 'styled-components';
function AnimatedCounter() {
// Multiple libraries, complex setup
const [persistedCount, setPersisted] = useLocalStorage('counter', 0);
const count$ = new BehaviorSubject(persistedCount);
const count = useObservable(() => count$, persistedCount);
const animatedProps = useSpring({
number: count,
config: { tension: 300 }
});
const increment = () => {
const newCount = count + 1;
count$.next(newCount);
setPersisted(newCount);
console.log('Counter changed:', newCount); // Manual logging
};
return (
<div className="counter">
<animated.h1>
{animatedProps.number.to(n => Math.floor(n))}
</animated.h1>
<button onClick={increment}>+</button>
</div>
);
}
```
</details>
<details>
<summary><strong>๐ฆ SolidJS Signals (SolidJS only)</strong></summary>
```typescript
import { createSignal, createEffect } from 'solid-js';
import { createSpring, animated } from '@solid-spring/core';
function AnimatedCounter() {
const [count, setCount] = createSignal(0);
// Manual persistence
createEffect(() => {
localStorage.setItem('counter', count().toString());
});
// Manual logging
createEffect(() => {
console.log('Counter changed:', count());
});
// External animation library
const animatedCount = createSpring(() => ({
number: count(),
config: { tension: 300 }
}));
return (
<div class="counter">
<animated.h1>{animatedCount().number}</animated.h1>
<button onClick={() => setCount(c => c + 1)}>+</button>
</div>
);
}
```
</details>
#### **๐ Lines of Code & Dependencies**
| Library | Lines | External Deps | Built-in Features |
|---------|-------|---------------|-------------------|
| **Signal-ฮฃ** | **15 lines** | **0** | โ
Animations, persistence, theming, logging |
| **RxJS + React** | **30+ lines** | **4+** | โ Requires multiple libraries |
| **SolidJS** | **25+ lines** | **2+** | โ Manual persistence, external animations |
| **Preact Signals** | **30+ lines** | **3+** | โ Manual everything, external libs |
## ๐ **Enhanced Shared Todo Library Example**
See the complete streaming and AI-enhanced todo application in action:
```typescript
// examples/shared-todo-library/StreamingTodoApp
import {
createStreamingSignal,
createWebRTCStream,
createAIEnhancedSignal,
createEventSourcedCRDT,
indexedDBEventStore
} from 'resig.js';
// ๐ Streaming todo management with real-time collaboration
const todoApp = {
// Event sourced CRDT for persistent todos
todos: createEventSourcedCRDT(
orSet('user-id'),
{
eventStore: indexedDBEventStore('todos'),
snapshotInterval: 10,
compactionStrategy: 'sliding-window'
}
),
// WebRTC collaboration
collaboration: createWebRTCStream('todo-collab'),
// AI assistance for todo suggestions
aiAssistant: createAIEnhancedSignal('', 'gpt-4', {
maxTokens: 500,
temperature: 0.7
}),
// Streaming filters and transformations
filteredTodos: createStreamingSignal([])
.filter(todos => todos.length > 0)
.throttle(100)
.transform(todos => todos.sort((a, b) => b.updatedAt - a.updatedAt))
};
// ๐ Works identically in React and SvelteKit!
```
**Features demonstrated:**
- โ
**Real-time WebRTC collaboration** between multiple users
- โ
**AI-powered todo suggestions** with confidence tracking
- โ
**Event sourcing** with automatic snapshots and compaction
- โ
**Streaming data processing** with throttling and filtering
- โ
**Persistent storage** with IndexedDB integration
- โ
**Universal API** - same code works in React and SvelteKit
**Try it yourself:**
```bash
cd examples/shared-todo-library
npm run dev:react # React version
npm run dev:svelte # SvelteKit version
```
## ๐ **Get Started**
```bash
npm install resig.js
```
Choose your framework and start building:
```typescript
// React
import { useSignal } from 'resig.js/react';
// SolidJS
import { useSignal } from 'resig.js/solid';
// Svelte
import { useSignal } from 'resig.js/svelte';
// Vue
import { useSignal } from 'resig.js/vue';
// Qwik
import { useSignal } from 'resig.js/qwik';
// Pure DOM (Vanilla JS)
import { domSignal } from 'resig.js/dom';
// Core Signals
import { signal } from 'resig.js';
// ๐ Get the complete platform with state machine orchestration
import {
// โก State machines & workflow orchestration
createStateMachine, schedule, debounce, throttle,
// ๐ Real-time collaboration
orSet, gCounter, createRealtimeSync,
// ๐ฌ Smooth animations
animatedSignal, spring, keyframes,
// ๐จ Dynamic theming
createThemeManager, createLightTheme, createDarkTheme,
// โฐ Time-travel
createUndoRedoManager, createCommand,
// ๐ฏ Drag-n-drop
createDragContainer,
// ๐ Universal plugins (work with ALL components including state machines)
debouncePlugin, cachePlugin, persistPlugin, loggerPlugin
} from 'resig.js';
// ๐ Everything works together with state machine coordination
const appStateMachine = createStateMachine('idle', (state, action) => {
// Orchestrate animations, sync, themes, undo/redo, drag-drop
switch (state) {
case 'idle': return action.type === 'START_OPERATION' ? 'processing' : state;
case 'processing': return action.type === 'COMPLETE' ? 'idle' : state;
default: return state;
}
}).pipe(loggerPlugin('app-orchestration'));
```
**Signal-ฮฃ: The only truly universal reactive platform.** ๐
*While others require multiple libraries and framework lock-in, Signal-ฮฃ provides everything built-in: state machines orchestrate animations, sync, themes, undo/redo, drag-dropโall enhanced by universal plugins, across every framework.*
**Why choose fragmented solutions when you can have mathematical perfection?** ๐งฎโจ
---
## ๐ License
MIT License - see [LICENSE](LICENSE) for details.
## ๐ Acknowledgments
- **Functional Programming Community** - For proven patterns and mathematical foundations
- **Framework Authors** - For creating the ecosystems we build upon
- **Open Source Contributors** - For making reactive programming accessible to everyone