327 lines
11 KiB
Markdown
327 lines
11 KiB
Markdown
# @push.rocks/smartstate
|
|
A powerful TypeScript library for elegant state management using RxJS and reactive programming patterns
|
|
|
|
## Install
|
|
|
|
To install `@push.rocks/smartstate`, you can use pnpm, npm, or yarn:
|
|
|
|
```bash
|
|
# Using pnpm (recommended)
|
|
pnpm install @push.rocks/smartstate --save
|
|
|
|
# Using npm
|
|
npm install @push.rocks/smartstate --save
|
|
|
|
# Using yarn
|
|
yarn add @push.rocks/smartstate
|
|
```
|
|
|
|
This will add `@push.rocks/smartstate` to your project's dependencies.
|
|
|
|
## 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. In the following sections, we will explore the comprehensive capabilities of this package and how to effectively use them in various scenarios, ensuring a robust state management pattern in your applications.
|
|
|
|
### Getting Started
|
|
|
|
First, let's import the necessary components from the library:
|
|
|
|
```typescript
|
|
import { Smartstate, StatePart, StateAction } from '@push.rocks/smartstate';
|
|
```
|
|
|
|
### Creating a SmartState Instance
|
|
|
|
`Smartstate` acts as the container for your state parts. You can consider it as the root of your state management structure.
|
|
|
|
```typescript
|
|
const myAppSmartState = new Smartstate<YourStatePartNamesEnum>();
|
|
```
|
|
|
|
### Understanding Init Modes
|
|
|
|
When creating state parts, you can specify different initialization modes:
|
|
|
|
- **`'soft'`** (default) - Returns existing state part if it exists, creates new if not
|
|
- **`'mandatory'`** - Requires state part to not exist, fails 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. For example, you may have a state part for user data and another for application settings.
|
|
|
|
Define state part names using either enums or string literal types:
|
|
|
|
```typescript
|
|
// Option 1: Using enums
|
|
enum AppStateParts {
|
|
UserState = 'UserState',
|
|
SettingsState = 'SettingsState'
|
|
}
|
|
|
|
// Option 2: Using string literal types (simpler approach)
|
|
type AppStateParts = 'UserState' | 'SettingsState';
|
|
```
|
|
|
|
Now, let's create a state part within our `myAppSmartState` instance:
|
|
|
|
```typescript
|
|
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')
|
|
);
|
|
|
|
// Note: Persistent state parts are automatically initialized internally
|
|
```
|
|
|
|
### Subscribing to State Changes
|
|
|
|
You can subscribe to changes in a state part to perform actions accordingly:
|
|
|
|
```typescript
|
|
// The select() method automatically filters out undefined states
|
|
userStatePart.select().subscribe((currentState) => {
|
|
console.log(`User Logged In: ${currentState.isLoggedIn}`);
|
|
});
|
|
```
|
|
|
|
If you need to select a specific part of your state, you can pass a selector function:
|
|
|
|
```typescript
|
|
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:
|
|
|
|
```typescript
|
|
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
|
|
loginUserAction.trigger({ username: 'johnDoe' });
|
|
// or await the result
|
|
const newState = await loginUserAction.trigger({ username: 'johnDoe' });
|
|
```
|
|
|
|
### Dispatching Actions
|
|
|
|
There are two ways to dispatch actions:
|
|
|
|
```typescript
|
|
// Method 1: Using trigger on the action (returns promise)
|
|
const newState = await loginUserAction.trigger({ username: 'johnDoe' });
|
|
// or fire and forget
|
|
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, giving you flexibility in how you handle the result.
|
|
|
|
### Additional State Methods
|
|
|
|
`StatePart` provides several useful methods for state management:
|
|
|
|
```typescript
|
|
// Get current state (may be undefined initially)
|
|
const currentState = userStatePart.getState();
|
|
if (currentState) {
|
|
console.log('Current user:', currentState.username);
|
|
}
|
|
|
|
// Wait for a specific state condition
|
|
await userStatePart.waitUntilPresent();
|
|
|
|
// Wait for a specific property to be present
|
|
await userStatePart.waitUntilPresent(state => state.username);
|
|
|
|
// Setup initial state with async operations
|
|
await userStatePart.stateSetup(async (statePart) => {
|
|
// Perform async initialization
|
|
const userData = await fetchUserData();
|
|
return { ...statePart.getState(), ...userData };
|
|
});
|
|
|
|
// Defer notification to end of call stack
|
|
userStatePart.notifyChangeCumulative();
|
|
```
|
|
|
|
### Persistent State with WebStore
|
|
|
|
`Smartstate` supports persistent states using WebStore (IndexedDB-based storage), allowing you to maintain state across sessions:
|
|
|
|
```typescript
|
|
const settingsStatePart = await myAppSmartState.getStatePart<ISettingsState>(
|
|
AppStateParts.SettingsState,
|
|
{ theme: 'light' }, // Initial state
|
|
'persistent' // Mode
|
|
);
|
|
|
|
// Note: init() is called automatically for persistent mode
|
|
```
|
|
|
|
Persistent state automatically:
|
|
- Saves state changes to IndexedDB
|
|
- Restores state on application restart
|
|
- Manages storage with configurable database and store names
|
|
|
|
### State Validation
|
|
|
|
`Smartstate` includes built-in state validation to ensure data integrity:
|
|
|
|
```typescript
|
|
// 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 {
|
|
// Add your custom validation logic
|
|
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()`
|
|
- **Selective Subscriptions**: Use selectors to subscribe only to specific state properties
|
|
- **Undefined State Filtering**: The `select()` method automatically filters out undefined states
|
|
|
|
### RxJS Integration
|
|
|
|
`Smartstate` leverages RxJS for reactive state management:
|
|
|
|
```typescript
|
|
// 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`:
|
|
|
|
```typescript
|
|
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
|
|
|
|
`@push.rocks/smartstate` provides a robust foundation for state management:
|
|
|
|
- **🎯 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
|
|
|
|
## License and Legal Information
|
|
|
|
This repository contains open-source code that is licensed under the MIT License. A copy of the MIT License can be found in the [license](license) file within this repository.
|
|
|
|
**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 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, and any usage must be approved in writing by Task Venture Capital GmbH.
|
|
|
|
### Company Information
|
|
|
|
Task Venture Capital GmbH
|
|
Registered at District court Bremen HRB 35230 HB, Germany
|
|
|
|
For any legal inquiries or if you require 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.
|