Files
smartstate/readme.md

11 KiB

@push.rocks/smartstate

A powerful TypeScript library for elegant state management using RxJS and reactive programming patterns 🚀

Issue Reporting and Security

For reporting bugs, issues, or security vulnerabilities, please visit community.foss.global/. This is the central community hub for all issue reporting. Developers who sign and comply with our contribution agreement and go through identification can also get a code.foss.global/ account to submit Pull Requests directly.

Install

To install @push.rocks/smartstate, you can use pnpm, npm, or yarn:

# Using pnpm (recommended)
pnpm install @push.rocks/smartstate --save

# Using npm
npm install @push.rocks/smartstate --save

# Using yarn
yarn add @push.rocks/smartstate

Usage

The @push.rocks/smartstate library provides an elegant way to handle state within your JavaScript or TypeScript projects, leveraging the power of Reactive Extensions (RxJS) and a structured state management strategy.

Getting Started

Import the necessary components from the library:

import { Smartstate, StatePart, StateAction } from '@push.rocks/smartstate';

Creating a SmartState Instance

Smartstate acts as the container for your state parts. Think of it as the root of your state management structure:

const myAppSmartState = new Smartstate<YourStatePartNamesEnum>();

Understanding Init Modes

When creating state parts, you can specify different initialization modes:

Mode Description
'soft' Default. Returns existing state part if it exists, creates new if not
'mandatory' Requires state part to not exist, throws error if it does
'force' Always creates new state part, overwriting any existing one
'persistent' Like 'soft' but with WebStore persistence using IndexedDB

Defining State Parts

State parts represent separable sections of your state, making it easier to manage and modularize. Define state part names using either enums or string literal types:

// Option 1: Using enums
enum AppStateParts {
  UserState = 'UserState',
  SettingsState = 'SettingsState'
}

// Option 2: Using string literal types (simpler approach)
type AppStateParts = 'UserState' | 'SettingsState';

Create a state part within your Smartstate instance:

interface IUserState {
  isLoggedIn: boolean;
  username?: string;
}

const userStatePart = await myAppSmartState.getStatePart<IUserState>(
  AppStateParts.UserState,
  { isLoggedIn: false }, // Initial state
  'soft' // Init mode (optional, defaults to 'soft')
);

Subscribing to State Changes

Subscribe to changes in a state part to perform actions accordingly:

// The select() method automatically filters out undefined states
userStatePart.select().subscribe((currentState) => {
  console.log(`User Logged In: ${currentState.isLoggedIn}`);
});

Select a specific part of your state with a selector function:

userStatePart.select(state => state.username).subscribe((username) => {
  if (username) {
    console.log(`Current user: ${username}`);
  }
});

Modifying State with Actions

Create actions to modify the state in a controlled manner:

interface ILoginPayload {
  username: string;
}

const loginUserAction = userStatePart.createAction<ILoginPayload>(async (statePart, payload) => {
  return { ...statePart.getState(), isLoggedIn: true, username: payload.username };
});

// Dispatch the action to update the state
const newState = await loginUserAction.trigger({ username: 'johnDoe' });

Dispatching Actions

There are two ways to dispatch actions:

// Method 1: Using trigger on the action (returns promise)
const newState = await loginUserAction.trigger({ username: 'johnDoe' });

// Method 2: Using dispatchAction on the state part (returns promise)
const newState = await userStatePart.dispatchAction(loginUserAction, { username: 'johnDoe' });

Both methods return a Promise with the new state payload.

Additional State Methods

StatePart provides several useful methods for state management:

// Get current state (may be undefined initially)
const currentState = userStatePart.getState();
if (currentState) {
  console.log('Current user:', currentState.username);
}

// Wait for state to be present
await userStatePart.waitUntilPresent();

// Wait for a specific property to be present
await userStatePart.waitUntilPresent(state => state.username);

// Wait with a timeout (throws error if condition not met within timeout)
try {
  await userStatePart.waitUntilPresent(state => state.username, 5000); // 5 second timeout
} catch (error) {
  console.error('Timed out waiting for username');
}

// Setup initial state with async operations
await userStatePart.stateSetup(async (statePart) => {
  const userData = await fetchUserData();
  return { ...statePart.getState(), ...userData };
});

// Defer notification to end of call stack (debounced)
userStatePart.notifyChangeCumulative();

Persistent State with WebStore

Smartstate supports persistent states using WebStore (IndexedDB-based storage), allowing you to maintain state across sessions:

const settingsStatePart = await myAppSmartState.getStatePart<ISettingsState>(
  AppStateParts.SettingsState,
  { theme: 'light' }, // Initial/default state
  'persistent' // Mode
);

Persistent state automatically:

  • Saves state changes to IndexedDB
  • Restores state on application restart
  • Merges persisted values with defaults (persisted values take precedence)
  • Ensures atomic writes (persistence happens before memory update)

State Validation

Smartstate includes built-in state validation to ensure data integrity:

// Basic validation (built-in) ensures state is not null or undefined
await userStatePart.setState(null); // Throws error: Invalid state structure

// Custom validation by extending StatePart
class ValidatedStatePart<T> extends StatePart<string, T> {
  protected validateState(stateArg: any): stateArg is T {
    return super.validateState(stateArg) && /* your validation */;
  }
}

Performance Optimization

Smartstate includes advanced performance optimizations:

  • 🔒 Async State Hash Detection: Uses SHA256 hashing to detect actual state changes, preventing unnecessary notifications when state values haven't truly changed
  • 🚫 Duplicate Prevention: Identical state updates are automatically filtered out
  • 📦 Cumulative Notifications: Batch multiple state changes into a single notification using notifyChangeCumulative() with automatic debouncing
  • 🎯 Selective Subscriptions: Use selectors to subscribe only to specific state properties
  • Undefined State Filtering: The select() method automatically filters out undefined states
  • Concurrent Access Safety: Prevents race conditions when multiple calls request the same state part simultaneously

RxJS Integration

Smartstate leverages RxJS for reactive state management:

// State is exposed as an RxJS Subject
const stateObservable = userStatePart.select();

// Automatically starts with current state value
stateObservable.subscribe((state) => {
  console.log('Current state:', state);
});

// Use selectors for specific properties
userStatePart.select(state => state.username)
  .pipe(
    distinctUntilChanged(),
    filter(username => username !== undefined)
  )
  .subscribe(username => {
    console.log('Username changed:', username);
  });

Complete Example

Here's a comprehensive example showcasing the power of @push.rocks/smartstate:

import { Smartstate, StatePart, StateAction } from '@push.rocks/smartstate';

// Define your state structure
type AppStateParts = 'user' | 'settings' | 'cart';

interface IUserState {
  isLoggedIn: boolean;
  username?: string;
  email?: string;
}

interface ICartState {
  items: Array<{ id: string; quantity: number }>;
  total: number;
}

// Create the smartstate instance
const appState = new Smartstate<AppStateParts>();

// Initialize state parts
const userState = await appState.getStatePart<IUserState>('user', {
  isLoggedIn: false
});

const cartState = await appState.getStatePart<ICartState>('cart', {
  items: [],
  total: 0
}, 'persistent'); // Persists across sessions

// Create actions
const loginAction = userState.createAction<{ username: string; email: string }>(
  async (statePart, payload) => {
    // Simulate API call
    await new Promise(resolve => setTimeout(resolve, 1000));

    return {
      isLoggedIn: true,
      username: payload.username,
      email: payload.email
    };
  }
);

// Subscribe to changes
userState.select(state => state.isLoggedIn).subscribe(isLoggedIn => {
  console.log('Login status changed:', isLoggedIn);
});

// Dispatch actions
await loginAction.trigger({ username: 'john', email: 'john@example.com' });

Key Features

Feature Description
🎯 Type-safe Full TypeScript support with intelligent type inference
Performance optimized Async state hash detection prevents unnecessary re-renders
💾 Persistent state Built-in IndexedDB support for state persistence
🔄 Reactive Powered by RxJS for elegant async handling
🧩 Modular Organize state into logical, reusable parts
Validated Built-in state validation with extensible validation logic
🎭 Flexible init modes Choose how state parts are initialized
📦 Zero config Works out of the box with sensible defaults
🛡️ Race condition safe Concurrent state part creation is handled safely
⏱️ Timeout support waitUntilPresent supports optional timeouts

This repository contains open-source code licensed under the MIT License. A copy of the license can be found in the LICENSE file.

Please note: The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.

Trademarks

This project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH or third parties, and are not included within the scope of the MIT license granted herein.

Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines or the guidelines of the respective third-party owners, and any usage must be approved in writing. Third-party trademarks used herein are the property of their respective owners and used only in a descriptive manner, e.g. for an implementation of an API or similar.

Company Information

Task Venture Capital GmbH Registered at District Court Bremen HRB 35230 HB, Germany

For any legal inquiries or further information, please contact us via email at hello@task.vc.

By using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.