Compare commits
24 Commits
Author | SHA1 | Date | |
---|---|---|---|
|
a47d8bb3c7 | ||
|
aa6766ef36 | ||
|
b0442e1227 | ||
|
0f1eb6eb27 | ||
|
dd18ef94bd | ||
a0189921a5 | |||
b409f1aa55 | |||
57553aa7c8 | |||
c302cbdae4 | |||
fd6e3ba8b1 | |||
8c3a7aa637 | |||
8c0125a8c0 | |||
40f3ffbdfb | |||
d4e01a73d3 | |||
641e77892a | |||
0c1211778b | |||
024f7f4f8f | |||
8f1cba5078 | |||
188f8057bf | |||
99cb86258e | |||
83976fa3f4 | |||
fe81307ca6 | |||
3a119b50a2 | |||
d3332ccb3f |
168
changelog.md
Normal file
168
changelog.md
Normal file
@@ -0,0 +1,168 @@
|
||||
# Changelog
|
||||
|
||||
## 2025-07-19 - 2.0.22 - fix(smartstate)
|
||||
Fix StateAction trigger method to properly return Promise
|
||||
|
||||
- Fixed StateAction.trigger() to return Promise<TStateType> as expected
|
||||
- Updated readme with improved documentation and examples
|
||||
- Replaced outdated legal information with Task Venture Capital GmbH details
|
||||
- Added implementation notes in readme.hints.md
|
||||
|
||||
## 2025-06-19 - 2.0.21 - maintenance
|
||||
General updates and improvements
|
||||
|
||||
## 2025-06-19 - 2.0.20 - fix(smartstate)
|
||||
Update build scripts and dependency versions; replace isohash with smarthashWeb for state hash generation
|
||||
|
||||
- Adjusted package.json scripts to include verbose testing and modified build command
|
||||
- Bumped development dependencies (tsbuild, tsbundle, tsrun, tstest, tapbundle) to newer versions
|
||||
- Updated production dependencies (lik, smarthash, smartpromise, smartrx) with minor version bumps
|
||||
- Replaced import of isohash with smarthashWeb in state hash generation, ensuring consistency across modules
|
||||
|
||||
## 2024-10-02 - 2.0.19 - fix(dependencies)
|
||||
Update dependencies to latest versions
|
||||
|
||||
- Updated @git.zone/tsbuild to version ^2.1.84
|
||||
- Updated @git.zone/tsbundle to version ^2.0.15
|
||||
- Updated @git.zone/tsrun to version ^1.2.49
|
||||
- Updated @git.zone/tstest to version ^1.0.90
|
||||
- Updated @push.rocks/tapbundle to version ^5.3.0
|
||||
- Updated @types/node to version ^22.7.4
|
||||
- Updated @push.rocks/lik to version ^6.0.15
|
||||
- Updated @push.rocks/smartjson to version ^5.0.20
|
||||
- Updated @push.rocks/smartpromise to version ^4.0.4
|
||||
- Updated @push.rocks/smartrx to version ^3.0.7
|
||||
- Updated @push.rocks/webstore to version ^2.0.20
|
||||
|
||||
## 2024-10-02 - 2.0.18 - fix(core)
|
||||
Fix type errors and typos in Smartstate class
|
||||
|
||||
- Updated type annotation in Smartstate class to ensure StatePartNameType extends string.
|
||||
- Fixed a typo in the JSDoc comment: 'existing' instead of 'exiting'.
|
||||
- Corrected improper type casting in the Smartstate class.
|
||||
|
||||
## 2024-05-29 - 2.0.17 - Maintenance
|
||||
General updates and improvements.
|
||||
|
||||
- Updated project description
|
||||
- Multiple updates to `tsconfig`
|
||||
- Updated `npmextra.json` to include `githost`
|
||||
|
||||
## 2023-10-07 - 2.0.16 - Maintenance
|
||||
General updates and improvements.
|
||||
|
||||
- Core update
|
||||
|
||||
## 2023-10-04 - 2.0.15 - Maintenance
|
||||
General updates and improvements.
|
||||
|
||||
- Core update
|
||||
|
||||
## 2023-10-03 - 2.0.14 to 2.0.10 - Maintenance
|
||||
General updates and improvements.
|
||||
|
||||
- Core updates
|
||||
|
||||
## 2023-09-11 - 2.0.9 - Maintenance
|
||||
General updates and improvements.
|
||||
|
||||
- Core update
|
||||
|
||||
## 2023-09-11 - 2.0.8 - Maintenance
|
||||
General updates and improvements.
|
||||
|
||||
- Core update
|
||||
|
||||
## 2023-07-27 - 2.0.7 - Maintenance
|
||||
General updates and improvements.
|
||||
|
||||
- Core update
|
||||
|
||||
## 2023-07-27 - 2.0.6 - Maintenance
|
||||
General updates and improvements.
|
||||
|
||||
- Core update
|
||||
|
||||
## 2023-04-13 - 2.0.5 - Maintenance
|
||||
General updates and improvements.
|
||||
|
||||
- Core update
|
||||
|
||||
## 2023-04-12 - 2.0.4 - Maintenance
|
||||
General updates and improvements.
|
||||
|
||||
- Core update
|
||||
|
||||
## 2023-04-04 - 2.0.3 to 2.0.1 - Maintenance
|
||||
General updates and improvements.
|
||||
|
||||
- Core updates
|
||||
|
||||
## 2023-03-15 - 2.0.0 - Major Update
|
||||
Core update with significant changes.
|
||||
|
||||
## 2022-03-25 - 1.0.23 - Major Update
|
||||
Breaking changes and major updates.
|
||||
|
||||
- SWITCH TO ESM
|
||||
|
||||
## 2022-01-24 - 1.0.22 - Maintenance
|
||||
General updates and improvements.
|
||||
|
||||
- Core updates
|
||||
|
||||
## 2020-11-30 - 1.0.21 to 1.0.20 - Maintenance
|
||||
General updates and improvements.
|
||||
|
||||
- Core updates
|
||||
|
||||
## 2020-11-30 - 1.0.19 to 1.0.18 - Maintenance
|
||||
General updates and improvements.
|
||||
|
||||
- Core updates
|
||||
|
||||
## 2020-07-27 - 1.0.17 to 1.0.16 - Maintenance
|
||||
General updates and improvements.
|
||||
|
||||
- Core updates
|
||||
|
||||
## 2020-05-27 - 1.0.15 - Maintenance
|
||||
General updates and improvements.
|
||||
|
||||
- Core update
|
||||
|
||||
## 2020-05-27 - 1.0.14 - Maintenance
|
||||
General updates and improvements.
|
||||
|
||||
- Core update
|
||||
|
||||
## 2019-09-25 - 1.0.13 - Maintenance
|
||||
General updates and improvements.
|
||||
|
||||
- Core update
|
||||
|
||||
## 2019-09-25 - 1.0.12 - Maintenance
|
||||
General updates and improvements.
|
||||
|
||||
- Core updates
|
||||
|
||||
## 2019-04-30 - 1.0.11 to 1.0.10 - Maintenance
|
||||
General updates and improvements.
|
||||
|
||||
- Core updates
|
||||
|
||||
## 2019-03-22 - 1.0.9 - Maintenance
|
||||
General updates and improvements.
|
||||
|
||||
- Core update
|
||||
|
||||
## 2019-02-27 - 1.0.8 - Minor Update
|
||||
Minor updates and improvements.
|
||||
|
||||
- Updated action generation
|
||||
- Core update
|
||||
|
||||
## 2019-02-21 - 1.0.7 - Initial Release
|
||||
Initial release of the project.
|
||||
|
||||
- Initial core implementation
|
@@ -6,12 +6,27 @@
|
||||
"gitzone": {
|
||||
"projectType": "npm",
|
||||
"module": {
|
||||
"githost": "gitlab.com",
|
||||
"githost": "code.foss.global",
|
||||
"gitscope": "push.rocks",
|
||||
"gitrepo": "smartstate",
|
||||
"description": "a package that handles state in a good way",
|
||||
"description": "A package for handling and managing state in applications.",
|
||||
"npmPackagename": "@push.rocks/smartstate",
|
||||
"license": "MIT"
|
||||
"license": "MIT",
|
||||
"keywords": [
|
||||
"state management",
|
||||
"reactive programming",
|
||||
"TypeScript",
|
||||
"observables",
|
||||
"web storage",
|
||||
"state action",
|
||||
"state selection",
|
||||
"state notification",
|
||||
"asynchronous state",
|
||||
"cumulative notification"
|
||||
]
|
||||
}
|
||||
},
|
||||
"tsdoc": {
|
||||
"legal": "\n## License and Legal Information\n\nThis 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. \n\n**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.\n\n### Trademarks\n\nThis 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.\n\n### Company Information\n\nTask Venture Capital GmbH \nRegistered at District court Bremen HRB 35230 HB, Germany\n\nFor any legal inquiries or if you require further information, please contact us via email at hello@task.vc.\n\nBy 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.\n"
|
||||
}
|
||||
}
|
52
package.json
52
package.json
@@ -1,33 +1,33 @@
|
||||
{
|
||||
"name": "@push.rocks/smartstate",
|
||||
"version": "2.0.12",
|
||||
"version": "2.0.22",
|
||||
"private": false,
|
||||
"description": "a package that handles state in a good way",
|
||||
"description": "A package for handling and managing state in applications.",
|
||||
"main": "dist_ts/index.js",
|
||||
"typings": "dist_ts/index.d.ts",
|
||||
"type": "module",
|
||||
"author": "Lossless GmbH",
|
||||
"license": "MIT",
|
||||
"scripts": {
|
||||
"test": "(tstest test/)",
|
||||
"build": "(tsbuild --web --allowimplicitany && tsbundle npm)",
|
||||
"test": "(tstest test/ --verbose)",
|
||||
"build": "(tsbuild tsfolders --allowimplicitany && tsbundle npm)",
|
||||
"buildDocs": "tsdoc"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@git.zone/tsbuild": "^2.1.70",
|
||||
"@git.zone/tsbundle": "^2.0.8",
|
||||
"@git.zone/tsrun": "^1.2.46",
|
||||
"@git.zone/tstest": "^1.0.81",
|
||||
"@push.rocks/tapbundle": "^5.0.15",
|
||||
"@types/node": "^20.8.0"
|
||||
"@git.zone/tsbuild": "^2.6.4",
|
||||
"@git.zone/tsbundle": "^2.4.0",
|
||||
"@git.zone/tsrun": "^1.3.3",
|
||||
"@git.zone/tstest": "^2.3.1",
|
||||
"@push.rocks/tapbundle": "^6.0.3",
|
||||
"@types/node": "^22.7.4"
|
||||
},
|
||||
"dependencies": {
|
||||
"@push.rocks/isohash": "^2.0.1",
|
||||
"@push.rocks/lik": "^6.0.5",
|
||||
"@push.rocks/smartjson": "^5.0.10",
|
||||
"@push.rocks/smartpromise": "^4.0.3",
|
||||
"@push.rocks/smartrx": "^3.0.6",
|
||||
"@push.rocks/webstore": "^2.0.13"
|
||||
"@push.rocks/lik": "^6.2.2",
|
||||
"@push.rocks/smarthash": "^3.2.0",
|
||||
"@push.rocks/smartjson": "^5.0.20",
|
||||
"@push.rocks/smartpromise": "^4.2.3",
|
||||
"@push.rocks/smartrx": "^3.0.10",
|
||||
"@push.rocks/webstore": "^2.0.20"
|
||||
},
|
||||
"files": [
|
||||
"ts/**/*",
|
||||
@@ -43,5 +43,23 @@
|
||||
],
|
||||
"browserslist": [
|
||||
"last 1 chrome versions"
|
||||
]
|
||||
],
|
||||
"keywords": [
|
||||
"state management",
|
||||
"reactive programming",
|
||||
"TypeScript",
|
||||
"observables",
|
||||
"web storage",
|
||||
"state action",
|
||||
"state selection",
|
||||
"state notification",
|
||||
"asynchronous state",
|
||||
"cumulative notification"
|
||||
],
|
||||
"homepage": "https://code.foss.global/push.rocks/smartstate",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://code.foss.global/push.rocks/smartstate.git"
|
||||
},
|
||||
"packageManager": "pnpm@10.11.0+sha512.6540583f41cc5f628eb3d9773ecee802f4f9ef9923cc45b69890fb47991d4b092964694ec3a4f738a420c918a333062c8b925d312f42e4f0c263eb603551f977"
|
||||
}
|
||||
|
12636
pnpm-lock.yaml
generated
12636
pnpm-lock.yaml
generated
File diff suppressed because it is too large
Load Diff
39
readme.hints.md
Normal file
39
readme.hints.md
Normal file
@@ -0,0 +1,39 @@
|
||||
# Smartstate Implementation Notes
|
||||
|
||||
## Current API (as of analysis)
|
||||
|
||||
### State Part Initialization
|
||||
- State parts can be created with different init modes: 'soft', 'mandatory', 'force', 'persistent'
|
||||
- Persistent mode automatically calls init() internally - no need to call it manually
|
||||
- WebStore integration for persistent state uses IndexedDB
|
||||
|
||||
### Actions
|
||||
- Actions are created with `createAction()` method
|
||||
- Two ways to dispatch actions:
|
||||
1. `stateAction.trigger(payload)` - returns Promise<TStatePayload>
|
||||
2. `await statePart.dispatchAction(stateAction, payload)` - returns Promise<TStatePayload>
|
||||
- Both methods now return the same Promise, providing flexibility in usage
|
||||
|
||||
### State Management Methods
|
||||
- `select()` - returns Observable with startWith current state
|
||||
- `waitUntilPresent()` - waits for specific state condition
|
||||
- `stateSetup()` - async state initialization with cumulative defer
|
||||
- `notifyChangeCumulative()` - defers notification to end of call stack (no callback parameter)
|
||||
|
||||
### State Hash Detection
|
||||
- Uses SHA256 hash to detect actual state changes
|
||||
- Bug: Currently stores the state object itself as hash instead of the actual hash
|
||||
- This prevents proper duplicate notification prevention
|
||||
|
||||
### Type System
|
||||
- Can use either enums or string literal types for state part names
|
||||
- Test uses simple string types: `type TMyStateParts = 'testStatePart'`
|
||||
|
||||
## Fixed Issues in Documentation
|
||||
1. Updated trigger() to return Promise (API enhancement)
|
||||
2. Added dispatchAction as alternative method
|
||||
3. Corrected notifyChangeCumulative usage
|
||||
4. Clarified persistent mode auto-init
|
||||
5. Added stateSetup documentation
|
||||
6. Fixed state hash detection description
|
||||
7. Both trigger() and dispatchAction() now return Promise for consistency
|
251
readme.md
251
readme.md
@@ -1,37 +1,236 @@
|
||||
# @push.rocks/smartstate
|
||||
a package that handles state in a good way
|
||||
A package for handling and managing state in applications
|
||||
|
||||
## Availabililty and Links
|
||||
* [npmjs.org (npm package)](https://www.npmjs.com/package/@push.rocks/smartstate)
|
||||
* [gitlab.com (source)](https://gitlab.com/push.rocks/smartstate)
|
||||
* [github.com (source mirror)](https://github.com/push.rocks/smartstate)
|
||||
* [docs (typedoc)](https://push.rocks.gitlab.io/smartstate/)
|
||||
## Install
|
||||
|
||||
## Status for master
|
||||
To install `@push.rocks/smartstate`, you can use pnpm (Performant Node Package Manager). Run the following command in your terminal:
|
||||
|
||||
Status Category | Status Badge
|
||||
-- | --
|
||||
GitLab Pipelines | [](https://lossless.cloud)
|
||||
GitLab Pipline Test Coverage | [](https://lossless.cloud)
|
||||
npm | [](https://lossless.cloud)
|
||||
Snyk | [](https://lossless.cloud)
|
||||
TypeScript Support | [](https://lossless.cloud)
|
||||
node Support | [](https://nodejs.org/dist/latest-v10.x/docs/api/)
|
||||
Code Style | [](https://lossless.cloud)
|
||||
PackagePhobia (total standalone install weight) | [](https://lossless.cloud)
|
||||
PackagePhobia (package size on registry) | [](https://lossless.cloud)
|
||||
BundlePhobia (total size when bundled) | [](https://lossless.cloud)
|
||||
```bash
|
||||
pnpm install @push.rocks/smartstate --save
|
||||
```
|
||||
|
||||
This will add `@push.rocks/smartstate` to your project's dependencies.
|
||||
|
||||
## Usage
|
||||
|
||||
Use TypeScript for best in class intellisense.
|
||||
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.
|
||||
|
||||
## Contribution
|
||||
### Getting Started
|
||||
|
||||
We are always happy for code contributions. If you are not the code contributing type that is ok. Still, maintaining Open Source repositories takes considerable time and thought. If you like the quality of what we do and our modules are useful to you we would appreciate a little monthly contribution: You can [contribute one time](https://lossless.link/contribute-onetime) or [contribute monthly](https://lossless.link/contribute). :)
|
||||
First, let's import the necessary components from the library:
|
||||
|
||||
For further information read the linked docs at the top of this readme.
|
||||
```typescript
|
||||
import { Smartstate, StatePart, StateAction } from '@push.rocks/smartstate';
|
||||
```
|
||||
|
||||
## Legal
|
||||
> MIT licensed | **©** [Task Venture Capital GmbH](https://task.vc)
|
||||
| By using this npm module you agree to our [privacy policy](https://lossless.gmbH/privacy)
|
||||
### 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'`** - Allows existing state parts to remain (default behavior)
|
||||
- **`'mandatory'`** - Fails if there's an existing state part with the same name
|
||||
- **`'force'`** - Overwrites any existing state part
|
||||
- **`'persistent'`** - Enables 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
|
||||
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
|
||||
// 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
|
||||
|
||||
### Performance Optimization
|
||||
|
||||
`Smartstate` includes built-in performance optimizations:
|
||||
|
||||
- **State Change Detection**: Detects actual state changes to prevent unnecessary notifications when state values haven't truly changed
|
||||
- **Cumulative Notifications**: Batch multiple state changes into a single notification using `notifyChangeCumulative()`
|
||||
- **Selective Subscriptions**: Use selectors to subscribe only to specific state properties
|
||||
|
||||
### 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);
|
||||
});
|
||||
```
|
||||
|
||||
### Comprehensive Usage
|
||||
|
||||
Putting it all together, `@push.rocks/smartstate` offers a flexible and powerful pattern for managing application state. By modularizing state parts, subscribing to state changes, and controlling state modifications through actions, developers can maintain a clean and scalable architecture. Combining these strategies with persistent states unlocks the full potential for creating dynamic and user-friendly applications.
|
||||
|
||||
Key features:
|
||||
- **Type-safe state management** with full TypeScript support
|
||||
- **Reactive state updates** using RxJS observables
|
||||
- **Persistent state** with IndexedDB storage
|
||||
- **Performance optimized** with state hash detection
|
||||
- **Modular architecture** with separate state parts
|
||||
- **Action-based updates** for predictable state modifications
|
||||
|
||||
For more complex scenarios, consider combining multiple state parts, creating hierarchical state structures, and integrating with other state management solutions as needed. With `@push.rocks/smartstate`, the possibilities are vast, empowering you to tailor the state management approach to fit the unique requirements of your project.
|
||||
|
||||
## 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.
|
||||
|
@@ -18,7 +18,7 @@ tap.test('should create a new SmartState', async () => {
|
||||
});
|
||||
|
||||
tap.test('should create a new StatePart', async () => {
|
||||
testStatePart = testState.getStatePart<TStatePartPayload>('testStatePart', {
|
||||
testStatePart = await testState.getStatePart<TStatePartPayload>('testStatePart', {
|
||||
currentFavorites: [],
|
||||
deep: {
|
||||
hi: 2,
|
||||
|
@@ -1,8 +1,8 @@
|
||||
/**
|
||||
* autocreated commitinfo by @pushrocks/commitinfo
|
||||
* autocreated commitinfo by @push.rocks/commitinfo
|
||||
*/
|
||||
export const commitinfo = {
|
||||
name: '@push.rocks/smartstate',
|
||||
version: '2.0.12',
|
||||
description: 'a package that handles state in a good way'
|
||||
version: '2.0.20',
|
||||
description: 'A package for handling and managing state in applications.'
|
||||
}
|
||||
|
@@ -1,29 +1,31 @@
|
||||
import * as plugins from './smartstate.plugins.js';
|
||||
import { StatePart } from './smartstate.classes.statepart.js';
|
||||
|
||||
export type TInitMode = 'soft' | 'mandatory' | 'force' | 'persistent';
|
||||
|
||||
/**
|
||||
* Smartstate takes care of providing state
|
||||
*/
|
||||
export class Smartstate<StatePartNameType> {
|
||||
public statePartMap: { [key: string]: StatePart<StatePartNameType, any> } = {};
|
||||
export class Smartstate<StatePartNameType extends string> {
|
||||
public statePartMap: { [key in StatePartNameType]?: StatePart<StatePartNameType, any> } = {};
|
||||
|
||||
constructor() {}
|
||||
|
||||
/**
|
||||
* Allows getting and initializing a new statepart
|
||||
* initMode === 'soft' it will allow existing stateparts
|
||||
* initMode === 'mandatory' will fail if there is an exiting statepart
|
||||
* initMode === 'mandatory' will fail if there is an existing statepart
|
||||
* initMode === 'force' will overwrite any existing statepart
|
||||
* @param statePartNameArg
|
||||
* @param initialArg
|
||||
* @param initMode
|
||||
*/
|
||||
public getStatePart<PayloadType>(
|
||||
statePartNameArg: string & StatePartNameType,
|
||||
public async getStatePart<PayloadType>(
|
||||
statePartNameArg: StatePartNameType,
|
||||
initialArg?: PayloadType,
|
||||
initMode?: 'soft' | 'mandatory' | 'force' | 'persistent'
|
||||
): StatePart<StatePartNameType, PayloadType> {
|
||||
if (this.statePartMap[statePartNameArg as any]) {
|
||||
initMode?: TInitMode
|
||||
): Promise<StatePart<StatePartNameType, PayloadType>> {
|
||||
if (this.statePartMap[statePartNameArg]) {
|
||||
if (initialArg && (!initMode || initMode !== 'soft')) {
|
||||
throw new Error(
|
||||
`${statePartNameArg} already exists, yet you try to set an initial state again`
|
||||
@@ -36,22 +38,36 @@ export class Smartstate<StatePartNameType> {
|
||||
`${statePartNameArg} does not yet exist, yet you don't provide an initial state`
|
||||
);
|
||||
}
|
||||
return this.createStatePart<PayloadType>(statePartNameArg, initialArg);
|
||||
return this.createStatePart<PayloadType>(statePartNameArg, initialArg, initMode);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* creates a statepart
|
||||
* Creates a statepart
|
||||
* @param statePartName
|
||||
* @param initialPayloadArg
|
||||
*/
|
||||
private createStatePart<PayloadType>(
|
||||
private async createStatePart<PayloadType>(
|
||||
statePartName: StatePartNameType,
|
||||
initialPayloadArg: PayloadType
|
||||
): StatePart<StatePartNameType, PayloadType> {
|
||||
const newState = new StatePart<StatePartNameType, PayloadType>(statePartName);
|
||||
newState.setState(initialPayloadArg);
|
||||
this.statePartMap[statePartName as any] = newState;
|
||||
initialPayloadArg: PayloadType,
|
||||
initMode?: TInitMode
|
||||
): Promise<StatePart<StatePartNameType, PayloadType>> {
|
||||
const newState = new StatePart<StatePartNameType, PayloadType>(
|
||||
statePartName,
|
||||
initMode === 'persistent'
|
||||
? {
|
||||
dbName: 'smartstate',
|
||||
storeName: statePartName,
|
||||
}
|
||||
: null
|
||||
);
|
||||
await newState.init();
|
||||
const currentState = newState.getState();
|
||||
await newState.setState({
|
||||
...initialPayloadArg,
|
||||
...currentState,
|
||||
});
|
||||
this.statePartMap[statePartName] = newState;
|
||||
return newState;
|
||||
}
|
||||
}
|
@@ -14,7 +14,7 @@ export class StateAction<TStateType, TActionPayloadType> {
|
||||
public actionDef: IActionDef<TStateType, TActionPayloadType>
|
||||
) {}
|
||||
|
||||
public trigger(payload: TActionPayloadType) {
|
||||
this.statePartRef.dispatchAction(this, payload);
|
||||
public trigger(payload: TActionPayloadType): Promise<TStateType> {
|
||||
return this.statePartRef.dispatchAction(this, payload);
|
||||
}
|
||||
}
|
||||
|
@@ -7,23 +7,24 @@ export class StatePart<TStatePartName, TStatePayload> {
|
||||
public stateStore: TStatePayload;
|
||||
private cumulativeDeferred = plugins.smartpromise.cumulativeDefer();
|
||||
|
||||
private webStoreOptions: plugins.webstore.IWebStoreOptions;
|
||||
private webStore: plugins.webstore.WebStore<TStatePayload> | null = null; // Add WebStore instance
|
||||
|
||||
constructor(nameArg: TStatePartName, webStoreOptions?: plugins.webstore.IWebStoreOptions) {
|
||||
constructor(nameArg: TStatePartName, webStoreOptionsArg?: plugins.webstore.IWebStoreOptions) {
|
||||
this.name = nameArg;
|
||||
|
||||
// Initialize WebStore if webStoreOptions are provided
|
||||
if (webStoreOptions) {
|
||||
this.webStore = new plugins.webstore.WebStore<TStatePayload>(webStoreOptions);
|
||||
this.initWebStore();
|
||||
if (webStoreOptionsArg) {
|
||||
this.webStoreOptions = webStoreOptionsArg;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* initializes the webstore
|
||||
*/
|
||||
private async initWebStore() {
|
||||
if (this.webStore) {
|
||||
public async init() {
|
||||
if (this.webStoreOptions) {
|
||||
this.webStore = new plugins.webstore.WebStore<TStatePayload>(this.webStoreOptions);
|
||||
await this.webStore.init();
|
||||
const storedState = await this.webStore.get(String(this.name));
|
||||
if (storedState) {
|
||||
@@ -52,6 +53,7 @@ export class StatePart<TStatePartName, TStatePayload> {
|
||||
if (this.webStore) {
|
||||
await this.webStore.set(String(this.name), newStateArg);
|
||||
}
|
||||
return this.stateStore;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -59,7 +61,7 @@ export class StatePart<TStatePartName, TStatePayload> {
|
||||
*/
|
||||
public notifyChange() {
|
||||
const createStateHash = (stateArg: any) => {
|
||||
return plugins.isohash.sha256FromString(plugins.smartjson.stringify(stateArg));
|
||||
return plugins.smarthashWeb.sha256FromString(plugins.smartjson.stringify(stateArg));
|
||||
};
|
||||
if (
|
||||
this.stateStore &&
|
||||
|
@@ -1,7 +1,7 @@
|
||||
import * as isohash from '@push.rocks/isohash';
|
||||
import * as smarthashWeb from '@push.rocks/smarthash/web';
|
||||
import * as smartjson from '@push.rocks/smartjson';
|
||||
import * as smartpromise from '@push.rocks/smartpromise';
|
||||
import * as smartrx from '@push.rocks/smartrx';
|
||||
import * as webstore from '@push.rocks/webstore';
|
||||
|
||||
export { isohash, smartjson, smartpromise, smartrx, webstore };
|
||||
export { smarthashWeb, smartjson, smartpromise, smartrx, webstore };
|
||||
|
Reference in New Issue
Block a user