npm package: @jucie.io/reactive
Description: Fine-grained reactivity with signals, computed values, and effects (includes core + extensions)
Author: Adrian Miller
Latest version: 1.0.30

# @jucie.io/reactive

Fine-grained reactive programming with signals, computed values, and reactive surfaces.

## Features

- **Signals**: Simple reactive values with automatic dependency tracking
- **Computed**: Computed values that auto-track and update when dependencies change
- **Bindings**: Reactive values with explicit dependencies and context support
- **Surfaces**: Component-like reactive contexts with state management
- **Subscribers**: Side effects that run when reactive values change
- **Async Support**: Native support for async computations
- **Batched Updates**: Efficient change propagation

## Installation

```bash
npm install @jucie.io/reactive
```

## Quick Start

### Signals

Reactive primitive values:

```javascript
import { createSignal } from '@jucie.io/reactive';

const count = createSignal(0);

console.log(count()); // 0
count(5);
console.log(count()); // 5

// Update based on current value
count(n => n + 1);
console.log(count()); // 6
```

### Computed Values

Automatically computed values that track dependencies:

```javascript
import { createSignal, createComputed } from '@jucie.io/reactive';

const count = createSignal(0);
const doubled = createComputed(() => count() * 2);

console.log(doubled()); // 0
count(5);
console.log(doubled()); // 10
```

### Surfaces

Declarative reactive components with automatic value unwrapping:

**Key Concepts:**
- **Unwrapped Values**: Returned signals and computed values are automatically unwrapped. Access them as properties (e.g., `counter.count`, `counter.doubled`) instead of calling them as functions.
- **Context (`ctx`)**: Inside computed values and actions, the `ctx` parameter provides access to the unwrapped values of **only what was returned** from the surface. This creates a clean API boundary between public and private state.

```javascript
import { defineSurface } from '@jucie.io/reactive';

const useCounter = defineSurface(({ signal, computed, action }) => {
  const count = signal(0);
  const updateCount = signal(0); // Private signal - NOT in ctx

  const doubled = computed((ctx) => {
    // ctx.count is available because 'count' is returned
    // ctx.updateCount is NOT available because 'updateCount' is not returned
    return ctx.count * 2
  })

  const increment = action((ctx) => {
    // Inside actions, call signals as functions
    updateCount(prevUpdateCount => prevUpdateCount + 1)
    ctx.count++
  })

  return {
    count,    // Exposed publicly
    doubled,  // Exposed publicly
    increment // Exposed publicly
    // updateCount is NOT returned, so it's private
  }
});

const counter = useCounter();
console.log(counter.count); // 0 - accessed as property, not counter.count()
console.log(counter.doubled); // 0 - accessed as property, not counter.doubled()

counter.increment();
console.log(counter.count); // 1
console.log(counter.doubled); // 2
```

### Subscribers

Side effects for reactive values:

```javascript
import { createSignal, createSubscriber } from '@jucie.io/reactive';

const count = createSignal(0);

createSubscriber(
  () => count(),
  (value) => console.log('Count changed:', value)
);

count(1); // Logs: "Count changed: 1"
count(2); // Logs: "Count changed: 2"
```

## Advanced Features

### Bindings

Reactive values with explicit dependencies:

```javascript
import { createSignal, createBinding } from '@jucie.io/reactive';

const firstName = createSignal('John');
const lastName = createSignal('Doe');

// Explicit dependencies - function receives (context, previousValue)
const fullName = createBinding(
  (ctx, prev) => `${firstName()} ${lastName()}`,
  [firstName, lastName]
);

console.log(fullName()); // "John Doe"
lastName('Smith');
console.log(fullName()); // "John Smith"
```

### Async Bindings

Bindings work seamlessly with async functions:

```javascript
import { createSignal, createBinding } from '@jucie.io/reactive';

const userId = createSignal(1);

const userData = createBinding(
  async (ctx, prev) => {
    const response = await fetch(`/api/users/${userId()}`);
    return response.json();
  },
  [userId]
);

// Returns a promise
const data = await userData();
```

### Binding with Previous Value

Access the previous computed value:

```javascript
import { createSignal, createBinding } from '@jucie.io/reactive';

const count = createSignal(0);

const delta = createBinding(
  (ctx, prev) => {
    const current = count();
    return prev !== undefined ? current - prev : 0;
  },
  [count],
  { initialValue: 0 }
);

console.log(delta()); // 0
count(5);
console.log(delta()); // 5 (5 - 0)
count(8);
console.log(delta()); // 3 (8 - 5)
```

### Surface with Object Configuration

```javascript
import { defineSurface } from '@jucie.io/reactive';

const useApp = defineSurface({
  state: {
    count: 0,
    message: 'Hello'
  },
  computed: {
    doubled(ctx) {
      return ctx.count * 2;
    }
  },
  actions: {
    increment(ctx) {
      ctx.count++;
    }
  },
  onInit(ctx) {
    console.log('Surface initialized');
  },
  onDestroy(ctx) {
    console.log('Surface destroyed');
  }
});

const app = useApp();

app.count // 0
app.message // Hello

```

### Effects

```javascript
import { createSignal, addEffect } from '@jucie.io/reactive';

const count = createSignal(0);

addEffect(count, (value) => {
  console.log('Effect:', value);
});

count(1); // Logs: "Effect: 1"
```

## API Reference

### Signals

- `createSignal(initialValue)` - Create a reactive signal
- `destroySignal(signal)` - Destroy a signal
- `isSignal(value)` - Check if value is a signal
- `isDirtySignal(signal)` - Check if signal needs recomputation

### Computed

- `createComputed(fn, config)` - Create a computed value with auto-tracked dependencies
- `destroyComputed(computed)` - Destroy a computed
- `isComputed(value)` - Check if value is a computed
- `isDirtyComputed(computed)` - Check if computed needs recomputation

### Bindings

- `createBinding(fn, dependencies, config)` - Create a binding with explicit dependencies
- `destroyBinding(binding)` - Destroy a binding
- `isBinding(value)` - Check if value is a binding
- `isDirtyBinding(binding)` - Check if binding needs recomputation

### Surfaces

- `defineSurface(setupFn|config, options)` - Create a reactive surface
- `isSurface(value)` - Check if value is a surface
- `refreshSurface(surface)` - Refresh a surface

### Subscribers

- `createSubscriber(getter, callback, config)` - Create a subscriber
- `destroySubscriber(subscriber)` - Destroy a subscriber
- `isSubscriber(value)` - Check if value is a subscriber

### Reactive System

- `addEffect(getter, callback)` - Add effect to reactive value
- `removeEffect(getter, callback)` - Remove effect
- `provideContext(value)` - Provide context
- `getContext()` - Get current context

## Configuration Options

### Signal

```javascript
{
  debounce: 100,        // Debounce updates (ms)
  immediate: true,      // Compute immediately
  effects: [fn],        // Initial effects
  detatched: false,     // Skip dependency tracking
  onAccess: (value) => {} // Callback on access
}
```

### Binding/Computed Config

```javascript
{
  debounce: 100,        // Debounce updates (ms)
  immediate: true,      // Compute immediately
  effects: [fn],        // Initial effects
  detatched: false,     // Skip dependency tracking
  onAccess: (value) => {}, // Callback on access
  context: () => ctx,   // Custom context provider
  initialValue: value   // Initial cached value
}
```

### Surface Options

```javascript
{
  mode: 'development'  // Enable dev features
}
```

## License and Usage

This software is provided under the MIT License with Commons Clause.

### ✅ What You Can Do

- Use this library freely in personal or commercial projects
- Include it in your paid products and applications
- Modify and fork for your own use
- View and learn from the source code

### ❌ What You Cannot Do

- Sell this library as a standalone product or competing state management solution
- Offer it as a paid service (SaaS) where the primary value is this library
- Create a commercial fork that competes with this project

### ⚠️ No Warranty or Support

This software is provided "as-is" without any warranty, support, or guarantees:

- No obligation to provide support or answer questions
- No obligation to accept or implement feature requests
- No obligation to review or merge pull requests
- No obligation to fix bugs or security issues
- No obligation to maintain or update the software

You are welcome to submit issues and pull requests, but there is no expectation they will be addressed. Use this software at your own risk.

See the LICENSE file for complete terms.

## Contributing

While contributions are welcome, please understand there is no obligation to review, accept, or merge them. This project is maintained at the discretion of the author.

---

Made with ⚡ by Adrian Miller