Compare commits
6 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| f6a3e71f0a | |||
| 6436370abc | |||
| eb1c48bee4 | |||
| 05417ed4c3 | |||
| 1d74a7f465 | |||
| 81ca32cdef |
30
changelog.md
30
changelog.md
@@ -1,5 +1,35 @@
|
||||
# Changelog
|
||||
|
||||
## 2026-02-02 - 2.0.29 - fix(smartstate)
|
||||
prevent duplicate statepart creation and fix persistence/notification race conditions
|
||||
|
||||
- Add pendingStatePartCreation map to deduplicate concurrent createStatePart calls
|
||||
- Adjust init handling so 'force' falls through to creation and concurrent creations are serialized
|
||||
- Merge persisted state with initial payload in 'persistent' initMode, with persisted values taking precedence
|
||||
- Persist to WebStore before updating in-memory state to ensure atomicity
|
||||
- Debounce cumulative notifications via pendingCumulativeNotification to avoid duplicate notifications
|
||||
- Log selector errors instead of silently swallowing exceptions
|
||||
- Add optional timeout to waitUntilPresent and ensure subscriptions and timeouts are cleaned up to avoid indefinite waits
|
||||
- Await setState when performing chained state updates to ensure ordering and avoid race conditions
|
||||
|
||||
## 2026-02-02 - 2.0.28 - fix(deps)
|
||||
bump devDependencies and dependencies, add tsbundle build config, update docs, and reorganize tests
|
||||
|
||||
- Bumped @git.zone/tsbuild to ^4.1.2, @git.zone/tsbundle to ^2.8.3, @git.zone/tsrun to ^2.0.1, @git.zone/tstest to ^3.1.8, and @types/node to ^25.2.0
|
||||
- Upgraded @push.rocks/smartjson to ^6.0.0
|
||||
- Added @git.zone/tsbundle bundle configuration to npmextra.json for building a dist bundle
|
||||
- Removed pnpm-workspace.yaml entries (cleaned workspace constraints)
|
||||
- Updated readme and readme.hints (docs formatting, version bumped to v2.0.28, issue reporting/security section and dependency list)
|
||||
- Reorganized tests: removed *.both.ts variants and added consolidated test files under test/ (test.ts, test.initialization.ts)
|
||||
|
||||
## 2025-09-12 - 2.0.27 - fix(StatePart)
|
||||
Use stable JSON stringify for state hashing; update dependencies and tooling
|
||||
|
||||
- Replace smartjson.stringify with smartjson.stableOneWayStringify when creating SHA256 state hashes to ensure deterministic hashing and avoid duplicate notifications for semantically identical states.
|
||||
- Bump runtime dependencies: @push.rocks/smarthash -> ^3.2.6, @push.rocks/smartjson -> ^5.2.0.
|
||||
- Bump dev tooling versions: @git.zone/tsbuild -> ^2.6.8, @git.zone/tsbundle -> ^2.5.1, @git.zone/tstest -> ^2.3.8.
|
||||
- Add local .claude/settings.local.json configuration for allowed permissions (local tooling/settings file).
|
||||
|
||||
## 2025-08-16 - 2.0.26 - fix(ci)
|
||||
Add local Claude settings file to allow helper permissions for common local commands
|
||||
|
||||
|
||||
@@ -3,6 +3,17 @@
|
||||
"npmGlobalTools": [],
|
||||
"npmAccessLevel": "public"
|
||||
},
|
||||
"@git.zone/tsbundle": {
|
||||
"bundles": [
|
||||
{
|
||||
"from": "./ts/index.ts",
|
||||
"to": "./dist_bundle/bundle.js",
|
||||
"outputMode": "bundle",
|
||||
"bundler": "esbuild",
|
||||
"production": true
|
||||
}
|
||||
]
|
||||
},
|
||||
"gitzone": {
|
||||
"projectType": "npm",
|
||||
"module": {
|
||||
|
||||
16523
package-lock.json
generated
Normal file
16523
package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
16
package.json
16
package.json
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@push.rocks/smartstate",
|
||||
"version": "2.0.26",
|
||||
"version": "2.0.29",
|
||||
"private": false,
|
||||
"description": "A package for handling and managing state in applications.",
|
||||
"main": "dist_ts/index.js",
|
||||
@@ -14,17 +14,17 @@
|
||||
"buildDocs": "tsdoc"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@git.zone/tsbuild": "^2.6.4",
|
||||
"@git.zone/tsbundle": "^2.4.0",
|
||||
"@git.zone/tsrun": "^1.3.3",
|
||||
"@git.zone/tstest": "^2.3.1",
|
||||
"@git.zone/tsbuild": "^4.1.2",
|
||||
"@git.zone/tsbundle": "^2.8.3",
|
||||
"@git.zone/tsrun": "^2.0.1",
|
||||
"@git.zone/tstest": "^3.1.8",
|
||||
"@push.rocks/tapbundle": "^6.0.3",
|
||||
"@types/node": "^22.7.4"
|
||||
"@types/node": "^25.2.0"
|
||||
},
|
||||
"dependencies": {
|
||||
"@push.rocks/lik": "^6.2.2",
|
||||
"@push.rocks/smarthash": "^3.2.0",
|
||||
"@push.rocks/smartjson": "^5.0.20",
|
||||
"@push.rocks/smarthash": "^3.2.6",
|
||||
"@push.rocks/smartjson": "^6.0.0",
|
||||
"@push.rocks/smartpromise": "^4.2.3",
|
||||
"@push.rocks/smartrx": "^3.0.10",
|
||||
"@push.rocks/webstore": "^2.0.20"
|
||||
|
||||
10073
pnpm-lock.yaml
generated
10073
pnpm-lock.yaml
generated
File diff suppressed because it is too large
Load Diff
@@ -1,4 +0,0 @@
|
||||
onlyBuiltDependencies:
|
||||
- esbuild
|
||||
- mongodb-memory-server
|
||||
- puppeteer
|
||||
@@ -1,6 +1,6 @@
|
||||
# Smartstate Implementation Notes
|
||||
|
||||
## Current API (as of v2.0.24+)
|
||||
## Current API (as of v2.0.28+)
|
||||
|
||||
### State Part Initialization
|
||||
- State parts can be created with different init modes: 'soft' (default), 'mandatory', 'force', 'persistent'
|
||||
@@ -50,3 +50,11 @@
|
||||
5. Added state validation with extensible validateState() method
|
||||
6. Made notifyChange() async to support proper hash comparison
|
||||
7. Updated select() to filter undefined states
|
||||
|
||||
## Dependency Versions (v2.0.28)
|
||||
- @git.zone/tsbuild: ^4.1.2
|
||||
- @git.zone/tsbundle: ^2.8.3
|
||||
- @git.zone/tsrun: ^2.0.1
|
||||
- @git.zone/tstest: ^3.1.8
|
||||
- @push.rocks/smartjson: ^6.0.0
|
||||
- @types/node: ^25.2.0
|
||||
92
readme.md
92
readme.md
@@ -1,5 +1,10 @@
|
||||
# @push.rocks/smartstate
|
||||
A powerful TypeScript library for elegant state management using RxJS and reactive programming patterns
|
||||
|
||||
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/](https://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/](https://code.foss.global/) account to submit Pull Requests directly.
|
||||
|
||||
## Install
|
||||
|
||||
@@ -16,15 +21,13 @@ npm install @push.rocks/smartstate --save
|
||||
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.
|
||||
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
|
||||
|
||||
First, let's import the necessary components from the library:
|
||||
Import the necessary components from the library:
|
||||
|
||||
```typescript
|
||||
import { Smartstate, StatePart, StateAction } from '@push.rocks/smartstate';
|
||||
@@ -32,7 +35,7 @@ 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.
|
||||
`Smartstate` acts as the container for your state parts. Think of it as the root of your state management structure:
|
||||
|
||||
```typescript
|
||||
const myAppSmartState = new Smartstate<YourStatePartNamesEnum>();
|
||||
@@ -42,16 +45,16 @@ const myAppSmartState = new Smartstate<YourStatePartNamesEnum>();
|
||||
|
||||
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
|
||||
| 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. 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:
|
||||
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:
|
||||
|
||||
```typescript
|
||||
// Option 1: Using enums
|
||||
@@ -64,7 +67,7 @@ enum AppStateParts {
|
||||
type AppStateParts = 'UserState' | 'SettingsState';
|
||||
```
|
||||
|
||||
Now, let's create a state part within our `myAppSmartState` instance:
|
||||
Create a state part within your `Smartstate` instance:
|
||||
|
||||
```typescript
|
||||
interface IUserState {
|
||||
@@ -77,13 +80,11 @@ const userStatePart = await myAppSmartState.getStatePart<IUserState>(
|
||||
{ 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:
|
||||
Subscribe to changes in a state part to perform actions accordingly:
|
||||
|
||||
```typescript
|
||||
// The select() method automatically filters out undefined states
|
||||
@@ -92,7 +93,7 @@ userStatePart.select().subscribe((currentState) => {
|
||||
});
|
||||
```
|
||||
|
||||
If you need to select a specific part of your state, you can pass a selector function:
|
||||
Select a specific part of your state with a selector function:
|
||||
|
||||
```typescript
|
||||
userStatePart.select(state => state.username).subscribe((username) => {
|
||||
@@ -116,8 +117,6 @@ const loginUserAction = userStatePart.createAction<ILoginPayload>(async (statePa
|
||||
});
|
||||
|
||||
// Dispatch the action to update the state
|
||||
loginUserAction.trigger({ username: 'johnDoe' });
|
||||
// or await the result
|
||||
const newState = await loginUserAction.trigger({ username: 'johnDoe' });
|
||||
```
|
||||
|
||||
@@ -128,14 +127,12 @@ 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.
|
||||
Both methods return a Promise with the new state payload.
|
||||
|
||||
### Additional State Methods
|
||||
|
||||
@@ -156,7 +153,6 @@ 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 };
|
||||
});
|
||||
@@ -175,8 +171,6 @@ const settingsStatePart = await myAppSmartState.getStatePart<ISettingsState>(
|
||||
{ theme: 'light' }, // Initial state
|
||||
'persistent' // Mode
|
||||
);
|
||||
|
||||
// Note: init() is called automatically for persistent mode
|
||||
```
|
||||
|
||||
Persistent state automatically:
|
||||
@@ -189,14 +183,12 @@ Persistent state automatically:
|
||||
`Smartstate` includes built-in state validation to ensure data integrity:
|
||||
|
||||
```typescript
|
||||
// Basic validation (built-in)
|
||||
// Ensures state is not null or undefined
|
||||
// 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 */;
|
||||
}
|
||||
}
|
||||
@@ -206,11 +198,11 @@ class ValidatedStatePart<T> extends StatePart<string, T> {
|
||||
|
||||
`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
|
||||
- **🔒 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
|
||||
|
||||
@@ -293,34 +285,36 @@ userState.select(state => state.isLoggedIn).subscribe(isLoggedIn => {
|
||||
await loginAction.trigger({ username: 'john', email: 'john@example.com' });
|
||||
```
|
||||
|
||||
### Key Features
|
||||
## 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
|
||||
| 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 |
|
||||
|
||||
## 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.
|
||||
This repository contains open-source code licensed under the MIT License. A copy of the license can be found in the [LICENSE](./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 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.
|
||||
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
|
||||
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.
|
||||
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.
|
||||
|
||||
@@ -3,6 +3,6 @@
|
||||
*/
|
||||
export const commitinfo = {
|
||||
name: '@push.rocks/smartstate',
|
||||
version: '2.0.26',
|
||||
version: '2.0.29',
|
||||
description: 'A package for handling and managing state in applications.'
|
||||
}
|
||||
|
||||
@@ -9,6 +9,8 @@ export type TInitMode = 'soft' | 'mandatory' | 'force' | 'persistent';
|
||||
export class Smartstate<StatePartNameType extends string> {
|
||||
public statePartMap: { [key in StatePartNameType]?: StatePart<StatePartNameType, any> } = {};
|
||||
|
||||
private pendingStatePartCreation: Map<string, Promise<StatePart<StatePartNameType, any>>> = new Map();
|
||||
|
||||
constructor() {}
|
||||
|
||||
/**
|
||||
@@ -26,6 +28,12 @@ export class Smartstate<StatePartNameType extends string> {
|
||||
initialArg?: PayloadType,
|
||||
initMode: TInitMode = 'soft'
|
||||
): Promise<StatePart<StatePartNameType, PayloadType>> {
|
||||
// Return pending creation if one exists to prevent duplicate state parts
|
||||
const pending = this.pendingStatePartCreation.get(statePartNameArg);
|
||||
if (pending) {
|
||||
return pending as Promise<StatePart<StatePartNameType, PayloadType>>;
|
||||
}
|
||||
|
||||
const existingStatePart = this.statePartMap[statePartNameArg];
|
||||
|
||||
if (existingStatePart) {
|
||||
@@ -36,7 +44,7 @@ export class Smartstate<StatePartNameType extends string> {
|
||||
);
|
||||
case 'force':
|
||||
// Force mode: create new state part
|
||||
return this.createStatePart<PayloadType>(statePartNameArg, initialArg, initMode);
|
||||
break; // Fall through to creation
|
||||
case 'soft':
|
||||
case 'persistent':
|
||||
default:
|
||||
@@ -50,7 +58,16 @@ export class Smartstate<StatePartNameType extends string> {
|
||||
`State part '${statePartNameArg}' does not exist and no initial state provided`
|
||||
);
|
||||
}
|
||||
return this.createStatePart<PayloadType>(statePartNameArg, initialArg, initMode);
|
||||
}
|
||||
|
||||
const creationPromise = this.createStatePart<PayloadType>(statePartNameArg, initialArg, initMode);
|
||||
this.pendingStatePartCreation.set(statePartNameArg, creationPromise);
|
||||
|
||||
try {
|
||||
const result = await creationPromise;
|
||||
return result;
|
||||
} finally {
|
||||
this.pendingStatePartCreation.delete(statePartNameArg);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -76,10 +93,18 @@ export class Smartstate<StatePartNameType extends string> {
|
||||
);
|
||||
await newState.init();
|
||||
const currentState = newState.getState();
|
||||
|
||||
if (initMode === 'persistent' && currentState !== undefined) {
|
||||
// Persisted state exists - merge with defaults, persisted values take precedence
|
||||
await newState.setState({
|
||||
...currentState,
|
||||
...initialPayloadArg,
|
||||
...currentState,
|
||||
});
|
||||
} else {
|
||||
// No persisted state or non-persistent mode
|
||||
await newState.setState(initialPayloadArg);
|
||||
}
|
||||
|
||||
this.statePartMap[statePartName] = newState;
|
||||
return newState;
|
||||
}
|
||||
|
||||
@@ -7,6 +7,8 @@ export class StatePart<TStatePartName, TStatePayload> {
|
||||
public stateStore: TStatePayload | undefined;
|
||||
private cumulativeDeferred = plugins.smartpromise.cumulativeDefer();
|
||||
|
||||
private pendingCumulativeNotification: ReturnType<typeof setTimeout> | null = null;
|
||||
|
||||
private webStoreOptions: plugins.webstore.IWebStoreOptions;
|
||||
private webStore: plugins.webstore.WebStore<TStatePayload> | null = null; // Add WebStore instance
|
||||
|
||||
@@ -51,13 +53,15 @@ export class StatePart<TStatePartName, TStatePayload> {
|
||||
throw new Error(`Invalid state structure for state part '${this.name}'`);
|
||||
}
|
||||
|
||||
this.stateStore = newStateArg;
|
||||
await this.notifyChange();
|
||||
|
||||
// Save state to WebStore if initialized
|
||||
// Save to WebStore first to ensure atomicity - if save fails, memory state remains unchanged
|
||||
if (this.webStore) {
|
||||
await this.webStore.set(String(this.name), newStateArg);
|
||||
}
|
||||
|
||||
// Update in-memory state after successful persistence
|
||||
this.stateStore = newStateArg;
|
||||
await this.notifyChange();
|
||||
|
||||
return this.stateStore;
|
||||
}
|
||||
|
||||
@@ -79,7 +83,7 @@ export class StatePart<TStatePartName, TStatePayload> {
|
||||
return;
|
||||
}
|
||||
const createStateHash = async (stateArg: any) => {
|
||||
return await plugins.smarthashWeb.sha256FromString(plugins.smartjson.stringify(stateArg));
|
||||
return await plugins.smarthashWeb.sha256FromString(plugins.smartjson.stableOneWayStringify(stateArg));
|
||||
};
|
||||
const currentHash = await createStateHash(this.stateStore);
|
||||
if (
|
||||
@@ -98,8 +102,13 @@ export class StatePart<TStatePartName, TStatePayload> {
|
||||
* creates a cumulative notification by adding a change notification at the end of the call stack;
|
||||
*/
|
||||
public notifyChangeCumulative() {
|
||||
// TODO: check viability
|
||||
setTimeout(async () => {
|
||||
// Debounce: clear any pending notification
|
||||
if (this.pendingCumulativeNotification) {
|
||||
clearTimeout(this.pendingCumulativeNotification);
|
||||
}
|
||||
|
||||
this.pendingCumulativeNotification = setTimeout(async () => {
|
||||
this.pendingCumulativeNotification = null;
|
||||
if (this.stateStore) {
|
||||
await this.notifyChange();
|
||||
}
|
||||
@@ -122,7 +131,8 @@ export class StatePart<TStatePartName, TStatePayload> {
|
||||
try {
|
||||
return selectorFn(stateArg);
|
||||
} catch (e) {
|
||||
// Nothing here
|
||||
console.error(`Selector error in state part '${this.name}':`, e);
|
||||
return undefined;
|
||||
}
|
||||
})
|
||||
);
|
||||
@@ -151,20 +161,41 @@ export class StatePart<TStatePartName, TStatePayload> {
|
||||
/**
|
||||
* waits until a certain part of the state becomes available
|
||||
* @param selectorFn
|
||||
* @param timeoutMs - optional timeout in milliseconds to prevent indefinite waiting
|
||||
*/
|
||||
public async waitUntilPresent<T = TStatePayload>(
|
||||
selectorFn?: (state: TStatePayload) => T
|
||||
selectorFn?: (state: TStatePayload) => T,
|
||||
timeoutMs?: number
|
||||
): Promise<T> {
|
||||
const done = plugins.smartpromise.defer<T>();
|
||||
const selectedObservable = this.select(selectorFn);
|
||||
const subscription = selectedObservable.subscribe(async (value) => {
|
||||
if (value) {
|
||||
let resolved = false;
|
||||
|
||||
const subscription = selectedObservable.subscribe((value) => {
|
||||
if (value && !resolved) {
|
||||
resolved = true;
|
||||
done.resolve(value);
|
||||
}
|
||||
});
|
||||
const result = await done.promise;
|
||||
|
||||
let timeoutId: ReturnType<typeof setTimeout> | undefined;
|
||||
if (timeoutMs) {
|
||||
timeoutId = setTimeout(() => {
|
||||
if (!resolved) {
|
||||
resolved = true;
|
||||
subscription.unsubscribe();
|
||||
done.reject(new Error(`waitUntilPresent timed out after ${timeoutMs}ms`));
|
||||
}
|
||||
}, timeoutMs);
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await done.promise;
|
||||
return result;
|
||||
} finally {
|
||||
subscription.unsubscribe();
|
||||
if (timeoutId) clearTimeout(timeoutId);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -175,6 +206,6 @@ export class StatePart<TStatePartName, TStatePayload> {
|
||||
) {
|
||||
const resultPromise = funcArg(this);
|
||||
this.cumulativeDeferred.addPromise(resultPromise);
|
||||
this.setState(await resultPromise);
|
||||
await this.setState(await resultPromise);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user