---
layout: default
title: Home
nav_order: 1
---
# SigPro ...
# SigPro π
A minimalist reactive library for building web interfaces with signals, effects, and native web components. No compilation, no virtual DOM, just pure JavaScript and intelligent reactivity.
**~3KB** gzipped β‘
[](https://www.npmjs.com/package/sigpro)
[](https://bundlephobia.com/package/sigpro)
[](https://github.com/natxocc/sigpro/blob/main/LICENSE)
## β Why?
After years of building applications with React, Vue, and Svelteβinvesting countless hours mastering their unique mental models, build tools, and update cyclesβI kept circling back to the same realization: no matter how sophisticated the framework, it all eventually compiles down to HTML, CSS, and vanilla JavaScript. The web platform has evolved tremendously, yet many libraries continue to reinvent the wheel, creating parallel universes with their own rules, their own syntaxes, and their own steep learning curves.
**SigPro is my answer to a simple question:** Why fight the platform when we can embrace it?
Modern browsers now offer powerful primitivesβCustom Elements, Shadow DOM, CSS custom properties, and microtask queuesβthat make true reactivity possible without virtual DOM diffing, without compilers, and without lock-in. SigPro strips away the complexity, delivering a reactive programming model that feels familiar but stays remarkably close to vanilla JS. No JSX transformations, no template compilers, no proprietary syntax to learnβjust functions, signals, and template literals that work exactly as you'd expect.
What emerged is a library that proves we've reached a turning point: the web is finally mature enough that we don't need to abstract it anymore. We can build reactive, component-based applications using virtually pure JavaScript, leveraging the platform's latest advances instead of working against them. SigPro isn't just another frameworkβit's a return to fundamentals, showing that the dream of simple, powerful reactivity is now achievable with the tools browsers give us out of the box.
## π Comparison Table
| Metric | SigPro | Solid | Svelte | Vue | React |
|--------|--------|-------|--------|-----|-------|
| **Bundle Size** (gzip) | π₯ **5.2KB** | π₯ 15KB | π₯ 16.6KB | 20.4KB | 43.9KB |
| **Time to Interactive** | π₯ **0.8s** | π₯ 1.3s | π₯ 1.4s | 1.6s | 2.3s |
| **Initial Render** (ms) | π₯ **124ms** | π₯ 198ms | π₯ 287ms | 298ms | 452ms |
| **Update Performance** (ms) | π₯ **4ms** | π₯ 5ms | π₯ 5ms | π₯ 7ms | 18ms |
| **Code Splitting** | π₯ **Zero overhead** | π₯ Minimal | π₯ Moderate | π₯ Moderate | High |
| **Learning Curve** (hours) | π₯ **2h** | π₯ 20h | π₯ 30h | 40h | 60h |
| **Dependencies** | π₯ 0 | π₯ 0 | π₯ 0 | π₯ 2 | π₯ 5 |
| **Compilation Required** | π₯ No | π₯ No | π₯ Yes | π₯ No | π₯ No |
| **Browser Native** | π₯ **Yes** | π₯ Partial | π₯ Partial | π₯ Partial | No |
| **Framework Lock-in** | π₯ **None** | π₯ Medium | π₯ High | π₯ Medium | π₯ High |
| **Longevity** (standards-based) | π₯ **10+ years** | π₯ 5 years | π₯ 3 years | π₯ 5 years | π₯ 5 years |
**The Verdict:** While other frameworks build parallel universes with proprietary syntax and compilation steps, SigPro embraces the web platform. The result isn't just smaller bundles or faster renderingβit's code that will still run 10 years from now, in any browser, without maintenance.
*"Stop fighting the platform. Start building with it."*
## π¦ Installation
```bash
npm install sigpro
```
or
```bash
bun add sigpro
```
or more simple:
copy `sigpro.js` file where you want to use it.
## π― Philosophy
SigPro (Signal Professional) embraces the web platform. Built on top of Custom Elements and reactive signals, it offers a development experience similar to modern frameworks but with a minimal footprint and zero dependencies.
**Core Principles:**
- π‘ **True Reactivity** - Automatic dependency tracking, no manual subscriptions
- β‘ **Surgical Updates** - Only the exact nodes that depend on changed values are updated
- π§© **Web Standards** - Built on Custom Elements, no custom rendering engine
- π¨ **Intuitive API** - Learn once, use everywhere
- π¬ **Predictable** - No magic, just signals and effects
## π‘ Hint for VS Code
For the best development experience with SigPro, install these VS Code extensions:
- **Prettier** β Automatically formats your template literals for better readability
- **lit-html** β Adds syntax highlighting and inline HTML color previews inside `html` tagged templates
This combination gives you framework-level developer experience without the framework complexityβsyntax highlighting, color previews, and automatic formatting for your reactive templates, all while writing pure JavaScript.
```javascript
// With lit-html extension, this gets full syntax highlighting and color previews!
html`
Beautiful highlighted template
`
```
# SigPro API - Quick Reference
| Function | Description | Example |
|----------|-------------|---------|
| **`$`** | Reactive signal (getter/setter) | `const count = $(0); count(5); count()` |
| **`$.effect`** | Runs effect when dependencies change | `$.effect(() => console.log(count()))` |
| **`$.page`** | Creates a page with automatic cleanup | `export default $.page(() => { ... })` |
| **`$.component`** | Creates reactive Web Component | `$.component('my-menu', setup, ['items'])` |
| **`$.fetch`** | Fetch wrapper with loading signal | `const data = await $.fetch('/api', data, loading)` |
| **`$.router`** | Hash-based router with params | `$.router([{path:'/', component:Home}])` |
| **`$.storage`** | Persistent signal (localStorage) | `const theme = $.storage('theme', 'light')` |
| **`html`** | Template literal for reactive HTML | `` html`${count}
` `` |
```javascript
import { $, html } from "sigpro";
```
---
## π API Reference
---
### `$(initialValue)` - Signals
Creates a reactive value that notifies dependents when changed.
#### Basic Signal (Getter/Setter)
```javascript
import { $ } from 'sigpro';
// Create a signal
const count = $(0);
// Read value
console.log(count()); // 0
// Write value
count(5);
count(prev => prev + 1); // Use function for previous value
// Read with dependency tracking (inside effect)
$.effect(() => {
console.log(count()); // Will be registered as dependency
});
```
#### Computed Signal
```javascript
import { $ } from 'sigpro';
const firstName = $('John');
const lastName = $('Doe');
// Computed signal - automatically updates when dependencies change
const fullName = $(() => `${firstName()} ${lastName()}`);
console.log(fullName()); // "John Doe"
firstName('Jane');
console.log(fullName()); // "Jane Doe"
```
**Returns:** Function that acts as getter/setter
---
### `$.effect(effectFn)` - Effects
Executes a function and automatically re-runs it when its dependencies change.
#### Basic Effect
```javascript
import { $ } from 'sigpro';
const count = $(0);
$.effect(() => {
console.log(`Count is: ${count()}`);
});
// Log: "Count is: 0"
count(1);
// Log: "Count is: 1"
```
#### Effect with Cleanup
```javascript
import { $ } from 'sigpro';
const userId = $(1);
$.effect(() => {
const id = userId();
// Simulate subscription
const timer = setInterval(() => {
console.log('Polling user', id);
}, 1000);
// Return cleanup function
return () => clearInterval(timer);
});
userId(2); // Previous timer cleared, new one created
```
**Parameters:**
- `effectFn`: Function to execute. Can return a cleanup function
**Returns:** Function to stop the effect
---
### `$.page(setupFunction)` - Pages
Creates a page with automatic cleanup of all signals and effects when navigated away.
```javascript
// pages/about.js
import { html, $ } from "sigpro";
export default $.page(() => {
const count = $(0);
const loading = $(false);
$.effect(() => {
if (loading()) {
// Fetch data...
}
});
return html`
About Page
Count: ${count}
count(c => c + 1)}>Increment
`;
});
```
**With parameters:**
```javascript
// pages/user.js
export default $.page(({ params }) => {
const userId = params.id;
const userData = $(null);
$.effect(() => {
fetch(`/api/users/${userId}`)
.then(r => r.json())
.then(userData);
});
return html`User: ${userData}
`;
});
```
**Parameters:**
- `setupFunction`: Function that returns the page content. Receives `{ params, onUnmount }`
**Returns:** A function that creates page instances with props
---
### `$.component(tagName, setupFunction, observedAttributes, useShadowDOM)` - Web Components
Creates Custom Elements with reactive properties. Choose between **Light DOM** (default) or **Shadow DOM** for style encapsulation.
### Parameters
| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `tagName` | `string` | (required) | Custom element tag name (must include a hyphen, e.g., `my-button`) |
| `setupFunction` | `Function` | (required) | Function that renders the component |
| `observedAttributes` | `string[]` | `[]` | Observed attributes that react to changes |
| `useShadowDOM` | `boolean` | `false` | `true` = Shadow DOM (encapsulated), `false` = Light DOM (inherits styles) |
---
#### π **Light DOM** (`useShadowDOM = false`) - Default
The component **inherits global styles** from the application. Ideal for components that should visually integrate with the rest of the interface.
##### Example: Button with Tailwind CSS
```javascript
// button-tailwind.js
import { $, html } from 'sigpro';
$.component('tw-button', (props, { slot, emit }) => {
const variant = props.variant() || 'primary';
const variants = {
primary: 'bg-blue-500 hover:bg-blue-600 text-white',
secondary: 'bg-gray-500 hover:bg-gray-600 text-white',
outline: 'border border-blue-500 text-blue-500 hover:bg-blue-50'
};
return html`
emit('click')}
>
${slot()}
`;
}, ['variant']); // Observe the 'variant' attribute
```
**Usage in HTML:**
```html
Save changes
Cancel
```
##### Example: Form Input with Validation
```javascript
// form-input.js
$.component('form-input', (props, { emit }) => {
const handleInput = (e) => {
const value = e.target.value;
props.value(value);
emit('update', value);
// Simple validation
if (props.pattern()) {
const regex = new RegExp(props.pattern());
const isValid = regex.test(value);
emit('validate', isValid);
}
};
return html`
`;
}, ['label', 'type', 'value', 'error', 'placeholder', 'disabled', 'pattern']);
```
**Usage:**
```html
email(e.detail)}
@validate=${(e) => setEmailValid(e.detail)}
>
```
##### Example: Card that uses global design system
```javascript
// content-card.js
$.component('content-card', (props, { slot }) => {
return html`
${slot()}
${props.footer() ? html`
` : ''}
`;
}, ['title', 'footer']);
```
**Usage:**
```html
Your dashboard updates will appear here.
```
---
#### π‘οΈ **Shadow DOM** (`useShadowDOM = true`) - Encapsulated
The component **encapsulates its styles** completely. External styles don't affect it, and its styles don't leak out. Perfect for:
- UI libraries distributed across projects
- Third-party widgets
- Components with very specific styling needs
##### Example: Calendar Component (Distributable UI)
```javascript
// ui-calendar.js
$.component('ui-calendar', (props, { select }) => {
const days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
const currentDate = props.date() ? new Date(props.date()) : new Date();
return html`
${days.map(day => html`${day} `)}
${generateDays(currentDate).map(day => html`
selectDate(day.date)}
>
${day.number}
`)}
`;
}, ['date'], true); // true = use Shadow DOM
```
**Usage - anywhere, anytime, looks identical:**
```html
```
##### Example: Third-party Chat Widget
```javascript
// chat-widget.js
$.component('chat-widget', (props, { select }) => {
return html`
${props.messages().map(msg => html`
${msg.text}
`)}
`;
}, ['messages', 'currentMessage'], true);
```
**Usage - embed in ANY website:**
```html
```
---
### π― **Quick Decision Guide**
| Use Light DOM (`false`) when... | Use Shadow DOM (`true`) when... |
|--------------------------------|-------------------------------|
| β
Component is part of your main app | β
Building a UI library for others |
| β
Using global CSS (Tailwind, Bootstrap) | β
Creating embeddable widgets |
| β
Need to inherit theme variables | β
Styles must be pixel-perfect everywhere |
| β
Working with existing design system | β
Component has complex, specific styles |
| β
Quick prototyping | β
Distributing to different projects |
| β
Form elements that should match site | β
Need style isolation/encapsulation |
### π‘ **Pro Tips**
1. **Light DOM components** are great for app-specific UI that should feel "native" to your site
2. **Shadow DOM components** are perfect for reusable "products" that must look identical everywhere
3. You can mix both in the same app - choose per component based on needs
4. Shadow DOM also provides DOM isolation - great for complex widgets
```javascript
// Mix and match in the same app!
$.component('app-header', setup, ['title']); // Light DOM
$.component('user-menu', setup, ['items']); // Light DOM
$.component('chat-widget', setup, ['messages'], true); // Shadow DOM
$.component('data-grid', setup, ['columns', 'data'], true); // Shadow DOM
```
---
### `$.fetch(url, data, [loading])` - Fetch
Simple fetch wrapper with automatic JSON handling and optional loading signal.
```javascript
import { $ } from 'sigpro';
const loading = $(false);
async function loadUser(id) {
const data = await $.fetch(`/api/users/${id}`, null, loading);
if (data) userData(data);
}
// In your UI
html`${() => loading() ? 'Loading...' : userData()?.name}
`;
```
**Parameters:**
- `url`: Endpoint URL
- `data`: Data to send (auto JSON.stringify'd)
- `loading`: Optional signal function to track loading state
**Returns:** `Promise` - Parsed JSON response or null on error
---
### `$.storage(key, initialValue, [storage])` - Persistent Signal
Signal that automatically syncs with localStorage or sessionStorage.
```javascript
import { $ } from 'sigpro';
// Automatically saves to localStorage
const theme = $.storage('theme', 'light');
const user = $.storage('user', null);
theme('dark'); // Saved to localStorage
// Page refresh... theme() returns 'dark'
// Use sessionStorage instead
const tempData = $.storage('temp', {}, sessionStorage);
```
**Parameters:**
- `key`: Storage key name
- `initialValue`: Default value if none stored
- `storage`: Storage type (default: `localStorage`, options: `sessionStorage`)
**Returns:** Signal function that persists to storage on changes
---
### `$.router(routes)` - Hash-Based Router
Creates a simple, powerful hash-based router for Single Page Applications (SPAs) with **automatic page cleanup** and **zero configuration**. Built on native browser APIs - no dependencies, no complex setup.
### Why Hash-Based?
Hash routing (`#/about`) works **everywhere** - no server configuration needed. It's perfect for:
- Static sites and SPAs
- GitHub Pages, Netlify, any static hosting
- Local development without a server
- Projects that need to work immediately
### Basic Usage
```javascript
import { $, html } from 'sigpro';
import HomePage from './pages/HomePage.js';
import AboutPage from './pages/AboutPage.js';
import UserPage from './pages/UserPage.js';
import NotFound from './pages/NotFound.js';
// Define your routes
const routes = [
{ path: '/', component: () => HomePage() },
{ path: '/about', component: () => AboutPage() },
{ path: '/users/:id', component: (params) => UserPage(params) },
{ path: /^\/posts\/(?\d+)$/, component: (params) => PostPage(params) },
];
// Create and mount the router
const router = $.router(routes);
document.body.appendChild(router);
```
---
### π Route Definition
Each route is an object with two properties:
| Property | Type | Description |
|----------|------|-------------|
| `path` | `string` or `RegExp` | Route pattern to match |
| `component` | `Function` | Function that returns page content (receives `params`) |
#### String Paths (Simple Routes)
```javascript
{ path: '/', component: () => HomePage() }
{ path: '/about', component: () => AboutPage() }
{ path: '/contact', component: () => ContactPage() }
{ path: '/users/:id', component: (params) => UserPage(params) } // With parameter
```
String paths support:
- **Static segments**: `/about`, `/contact`, `/products`
- **Named parameters**: `:id`, `:slug`, `:username` (captured in `params`)
#### RegExp Paths (Advanced Routing)
```javascript
// Match numeric IDs only
{ path: /^\/users\/(?\d+)$/, component: (params) => UserPage(params) }
// Match product slugs (letters, numbers, hyphens)
{ path: /^\/products\/(?[a-z0-9-]+)$/, component: (params) => ProductPage(params) }
// Match blog posts by year/month
{ path: /^\/blog\/(?\d{4})\/(?\d{2})$/, component: (params) => BlogArchive(params) }
// Match optional language prefix
{ path: /^\/(?en|es|fr)?\/?about$/, component: (params) => AboutPage(params) }
```
RegExp gives you **full control** over route matching with named capture groups.
---
## π§ `$.router(routes)` - Simple Router with Parameters
Creates a hash-based router with support for `:param` parameters. Automatically cleans up pages when navigating away.
### π Route Parameters (Human-Friendly)
```javascript
const routes = [
{ path: '/', component: HomePage },
{ path: '/about', component: AboutPage },
{ path: '/user/:id', component: UserPage }, // /user/42 β { id: '42' }
{ path: '/user/:id/posts', component: UserPostsPage }, // /user/42/posts β { id: '42' }
{ path: '/user/:id/posts/:pid', component: PostPage }, // /user/42/posts/123 β { id: '42', pid: '123' }
{ path: '/search/:query/page/:num', component: SearchPage }, // /search/js/page/2 β { query: 'js', num: '2' }
];
```
### π― Accessing Parameters in Pages
Parameters are automatically extracted and passed to your page component:
```javascript
// pages/UserPage.js
import { $, html } from 'sigpro';
export default (params) => $.page(() => {
// /user/42 β params = { id: '42' }
const userId = params.id;
const userData = $(null);
return html`
User Profile: ${userId}
Loading user data...
`;
});
// pages/PostPage.js
export default (params) => $.page(() => {
// /user/42/posts/123 β params = { id: '42', pid: '123' }
const { id, pid } = params;
return html`
Post ${pid} from user ${id}
`;
});
```
### π§ Navigation
```javascript
// Programmatic navigation
$.router.go('/user/42');
$.router.go('/search/javascript/page/2');
$.router.go('about'); // Same as '/about' (auto-adds leading slash)
// Link navigation (in templates)
html`
Home
Profile
$.router.go('/contact')}>Contact
`;
```
### π Automatic Page Cleanup
```javascript
export default (params) => $.page(({ onUnmount }) => {
// Set up interval
const interval = setInterval(() => {
fetchData(params.id);
}, 5000);
// Auto-cleaned when navigating away
onUnmount(() => clearInterval(interval));
return html`Page content
`;
});
```
### π¦ Usage in Templates
```javascript
import { $, html } from 'sigpro';
import HomePage from './pages/Home.js';
import UserPage from './pages/User.js';
const routes = [
{ path: '/', component: HomePage },
{ path: '/user/:id', component: UserPage },
];
// Mount router directly in your template
const App = () => html`
${$.router(routes)}
`;
document.body.appendChild(App());
```
### π― API Reference
#### `$.router(routes)`
- **routes**: `Array<{path: string, component: Function}>` - Route configurations with `:param` support
- **Returns**: `HTMLDivElement` - Container that renders the current page
#### `$.router.go(path)`
- **path**: `string` - Route path (automatically adds leading slash)
### π‘ Pro Tips
1. **Order matters** - Define more specific routes first:
```javascript
[
{ path: '/user/:id/edit', component: EditUser }, // More specific first
{ path: '/user/:id', component: ViewUser }, // Then generic
]
```
2. **Cleanup is automatic** - All effects, intervals, and event listeners in `$.page` are cleaned up
3. **Zero config** - Just define routes and use them
---
### `html` - Template Literal Tag
Creates reactive DOM fragments using template literals.
#### Basic Usage
```javascript
import { $, html } from 'sigpro';
const count = $(0);
const fragment = html`
Count: ${count}
count(c => c + 1)}>+
`;
```
#### Directive Reference
| Directive | Example | Description |
|-----------|---------|-------------|
| `@event` | `@click=${handler}` | Event listener |
| `:property` | `:value=${signal}` | Two-way binding |
| `?attribute` | `?disabled=${signal}` | Boolean attribute |
| `.property` | `.scrollTop=${signal}` | Property binding |
**Two-way binding example:**
```javascript
const text = $('');
html`
You typed: ${text}
`;
```
## π License
MIT Β© natxocc