Compare commits

..

No commits in common. "master" and "v1.0.14" have entirely different histories.

25 changed files with 2188 additions and 7668 deletions

@ -1,66 +0,0 @@
name: Default (not tags)
on:
push:
tags-ignore:
- '**'
env:
IMAGE: registry.gitlab.com/hosttoday/ht-docker-node:npmci
NPMCI_COMPUTED_REPOURL: https://${{gitea.repository_owner}}:${{secrets.GITEA_TOKEN}}@gitea.lossless.digital/${{gitea.repository}}.git
NPMCI_TOKEN_NPM: ${{secrets.NPMCI_TOKEN_NPM}}
NPMCI_TOKEN_NPM2: ${{secrets.NPMCI_TOKEN_NPM2}}
NPMCI_GIT_GITHUBTOKEN: ${{secrets.NPMCI_GIT_GITHUBTOKEN}}
NPMCI_URL_CLOUDLY: ${{secrets.NPMCI_URL_CLOUDLY}}
jobs:
security:
runs-on: ubuntu-latest
continue-on-error: true
container:
image: ${{ env.IMAGE }}
steps:
- uses: actions/checkout@v3
- name: Install pnpm and npmci
run: |
pnpm install -g pnpm
pnpm install -g @shipzone/npmci
- name: Run npm prepare
run: npmci npm prepare
- name: Audit production dependencies
run: |
npmci command npm config set registry https://registry.npmjs.org
npmci command pnpm audit --audit-level=high --prod
continue-on-error: true
- name: Audit development dependencies
run: |
npmci command npm config set registry https://registry.npmjs.org
npmci command pnpm audit --audit-level=high --dev
continue-on-error: true
test:
if: ${{ always() }}
needs: security
runs-on: ubuntu-latest
container:
image: ${{ env.IMAGE }}
steps:
- uses: actions/checkout@v3
- name: Test stable
run: |
npmci node install stable
npmci npm install
npmci npm test
- name: Test build
run: |
npmci node install stable
npmci npm install
npmci npm build

@ -1,124 +0,0 @@
name: Default (tags)
on:
push:
tags:
- '*'
env:
IMAGE: registry.gitlab.com/hosttoday/ht-docker-node:npmci
NPMCI_COMPUTED_REPOURL: https://${{gitea.repository_owner}}:${{secrets.GITEA_TOKEN}}@gitea.lossless.digital/${{gitea.repository}}.git
NPMCI_TOKEN_NPM: ${{secrets.NPMCI_TOKEN_NPM}}
NPMCI_TOKEN_NPM2: ${{secrets.NPMCI_TOKEN_NPM2}}
NPMCI_GIT_GITHUBTOKEN: ${{secrets.NPMCI_GIT_GITHUBTOKEN}}
NPMCI_URL_CLOUDLY: ${{secrets.NPMCI_URL_CLOUDLY}}
jobs:
security:
runs-on: ubuntu-latest
continue-on-error: true
container:
image: ${{ env.IMAGE }}
steps:
- uses: actions/checkout@v3
- name: Prepare
run: |
pnpm install -g pnpm
pnpm install -g @shipzone/npmci
npmci npm prepare
- name: Audit production dependencies
run: |
npmci command npm config set registry https://registry.npmjs.org
npmci command pnpm audit --audit-level=high --prod
continue-on-error: true
- name: Audit development dependencies
run: |
npmci command npm config set registry https://registry.npmjs.org
npmci command pnpm audit --audit-level=high --dev
continue-on-error: true
test:
if: ${{ always() }}
needs: security
runs-on: ubuntu-latest
container:
image: ${{ env.IMAGE }}
steps:
- uses: actions/checkout@v3
- name: Prepare
run: |
pnpm install -g pnpm
pnpm install -g @shipzone/npmci
npmci npm prepare
- name: Test stable
run: |
npmci node install stable
npmci npm install
npmci npm test
- name: Test build
run: |
npmci node install stable
npmci npm install
npmci npm build
release:
needs: test
if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/')
runs-on: ubuntu-latest
container:
image: ${{ env.IMAGE }}
steps:
- uses: actions/checkout@v3
- name: Prepare
run: |
pnpm install -g pnpm
pnpm install -g @shipzone/npmci
npmci npm prepare
- name: Release
run: |
npmci node install stable
npmci npm publish
metadata:
needs: test
if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/')
runs-on: ubuntu-latest
container:
image: ${{ env.IMAGE }}
continue-on-error: true
steps:
- uses: actions/checkout@v3
- name: Prepare
run: |
pnpm install -g pnpm
pnpm install -g @shipzone/npmci
npmci npm prepare
- name: Code quality
run: |
npmci command npm install -g typescript
npmci npm install
- name: Trigger
run: npmci trigger
- name: Build docs and upload artifacts
run: |
npmci node install stable
npmci npm install
pnpm install -g @git.zone/tsdoc
npmci command tsdoc
continue-on-error: true

4
.gitignore vendored

@ -15,6 +15,8 @@ node_modules/
# builds # builds
dist/ dist/
dist_*/ dist_web/
dist_serve/
dist_ts_web/
# custom # custom

119
.gitlab-ci.yml Normal file

@ -0,0 +1,119 @@
# gitzone ci_default
image: registry.gitlab.com/hosttoday/ht-docker-node:npmci
cache:
paths:
- .npmci_cache/
key: "$CI_BUILD_STAGE"
stages:
- security
- test
- release
- metadata
# ====================
# security stage
# ====================
mirror:
stage: security
script:
- npmci git mirror
tags:
- docker
- notpriv
snyk:
stage: security
script:
- npmci npm prepare
- npmci command npm install -g snyk
- npmci command npm install --ignore-scripts
- npmci command snyk test
tags:
- docker
- notpriv
# ====================
# test stage
# ====================
testStable:
stage: test
script:
- npmci npm prepare
- npmci node install stable
- npmci npm install
- npmci npm test
coverage: /\d+.?\d+?\%\s*coverage/
tags:
- docker
- priv
testBuild:
stage: test
script:
- npmci npm prepare
- npmci node install stable
- npmci npm install
- npmci command npm run build
coverage: /\d+.?\d+?\%\s*coverage/
tags:
- docker
- notpriv
release:
stage: release
script:
- npmci node install stable
- npmci npm publish
only:
- tags
tags:
- docker
- notpriv
# ====================
# metadata stage
# ====================
codequality:
stage: metadata
allow_failure: true
script:
- npmci command npm install -g tslint typescript
- npmci npm install
- npmci command "tslint -c tslint.json ./ts/**/*.ts"
tags:
- docker
- priv
trigger:
stage: metadata
script:
- npmci trigger
only:
- tags
tags:
- docker
- notpriv
pages:
image: hosttoday/ht-docker-dbase:npmci
services:
- docker:stable-dind
stage: metadata
script:
- npmci command npm install -g @gitzone/tsdoc
- npmci npm prepare
- npmci npm install
- npmci command tsdoc
tags:
- docker
- notpriv
only:
- tags
artifacts:
expire_in: 1 week
paths:
- public
allow_failure: true

11
.vscode/launch.json vendored

@ -1,11 +0,0 @@
{
"version": "0.2.0",
"configurations": [
{
"command": "npm test",
"name": "Run npm test",
"request": "launch",
"type": "node-terminal"
}
]
}

26
.vscode/settings.json vendored

@ -1,26 +0,0 @@
{
"json.schemas": [
{
"fileMatch": ["/npmextra.json"],
"schema": {
"type": "object",
"properties": {
"npmci": {
"type": "object",
"description": "settings for npmci"
},
"gitzone": {
"type": "object",
"description": "settings for gitzone",
"properties": {
"projectType": {
"type": "string",
"enum": ["website", "element", "service", "npm", "wcc"]
}
}
}
}
}
}
]
}

@ -1,149 +0,0 @@
# Changelog
## 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

@ -1,4 +1,4 @@
Copyright (c) 2019 Task Venture Capital GmbH (hello@task.vc) Copyright (c) 2019 Lossless GmbH (hello@lossless.com)
Permission is hereby granted, free of charge, to any person obtaining a copy Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal of this software and associated documentation files (the "Software"), to deal

@ -4,29 +4,13 @@
"npmAccessLevel": "public" "npmAccessLevel": "public"
}, },
"gitzone": { "gitzone": {
"projectType": "npm",
"module": { "module": {
"githost": "code.foss.global", "githost": "gitlab.com",
"gitscope": "push.rocks", "gitscope": "pushrocks",
"gitrepo": "smartstate", "gitrepo": "smartstate",
"description": "A package for handling and managing state in applications.", "shortDescription": "a package that handles state in a good way",
"npmPackagename": "@push.rocks/smartstate", "npmPackagename": "@pushrocks/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"
} }
} }

1739
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

@ -1,64 +1,39 @@
{ {
"name": "@push.rocks/smartstate", "name": "@pushrocks/smartstate",
"version": "2.0.19", "version": "1.0.14",
"private": false, "private": false,
"description": "A package for handling and managing state in applications.", "description": "a package that handles state in a good way",
"main": "dist_ts/index.js", "main": "dist/index.js",
"typings": "dist_ts/index.d.ts", "typings": "dist/index.d.ts",
"type": "module",
"author": "Lossless GmbH", "author": "Lossless GmbH",
"license": "MIT", "license": "MIT",
"scripts": { "scripts": {
"test": "(tstest test/)", "test": "(tstest test/)",
"build": "(tsbuild --web --allowimplicitany && tsbundle npm)", "build": "(tsbuild)",
"buildDocs": "tsdoc" "format": "(gitzone format)"
}, },
"devDependencies": { "devDependencies": {
"@git.zone/tsbuild": "^2.1.84", "@gitzone/tsbuild": "^2.1.17",
"@git.zone/tsbundle": "^2.0.15", "@gitzone/tstest": "^1.0.24",
"@git.zone/tsrun": "^1.2.49", "@pushrocks/tapbundle": "^3.0.13",
"@git.zone/tstest": "^1.0.90", "@types/node": "^12.7.7",
"@push.rocks/tapbundle": "^5.3.0", "tslint": "^5.20.0",
"@types/node": "^22.7.4" "tslint-config-prettier": "^1.18.0"
}, },
"dependencies": { "dependencies": {
"@push.rocks/isohash": "^2.0.1", "@pushrocks/lik": "^3.0.11",
"@push.rocks/lik": "^6.0.15", "@pushrocks/smartpromise": "^3.0.5",
"@push.rocks/smartjson": "^5.0.20", "rxjs": "^6.5.3"
"@push.rocks/smartpromise": "^4.0.4",
"@push.rocks/smartrx": "^3.0.7",
"@push.rocks/webstore": "^2.0.20"
}, },
"files": [ "files": [
"ts/**/*", "ts/*",
"ts_web/**/*", "ts_web/*",
"dist/**/*", "dist/*",
"dist_*/**/*", "dist_web/*",
"dist_ts/**/*", "dist_ts_web/*",
"dist_ts_web/**/*", "assets/*",
"assets/**/*",
"cli.js", "cli.js",
"npmextra.json", "npmextra.json",
"readme.md" "readme.md"
], ]
"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"
}
} }

6751
pnpm-lock.yaml generated

File diff suppressed because it is too large Load Diff

@ -1 +0,0 @@

147
readme.md

@ -1,137 +1,26 @@
# @push.rocks/smartstate # @pushrocks/smartstate
a package that handles state in a good way a package that handles state in a good way
## Install ## Availabililty and Links
* [npmjs.org (npm package)](https://www.npmjs.com/package/@pushrocks/smartstate)
* [gitlab.com (source)](https://gitlab.com/pushrocks/smartstate)
* [github.com (source mirror)](https://github.com/pushrocks/smartstate)
* [docs (typedoc)](https://pushrocks.gitlab.io/smartstate/)
To install `@push.rocks/smartstate`, you can use npm (Node Package Manager). Run the following command in your terminal: ## Status for master
[![build status](https://gitlab.com/pushrocks/smartstate/badges/master/build.svg)](https://gitlab.com/pushrocks/smartstate/commits/master)
```bash [![coverage report](https://gitlab.com/pushrocks/smartstate/badges/master/coverage.svg)](https://gitlab.com/pushrocks/smartstate/commits/master)
npm install @push.rocks/smartstate --save [![npm downloads per month](https://img.shields.io/npm/dm/@pushrocks/smartstate.svg)](https://www.npmjs.com/package/@pushrocks/smartstate)
``` [![Known Vulnerabilities](https://snyk.io/test/npm/@pushrocks/smartstate/badge.svg)](https://snyk.io/test/npm/@pushrocks/smartstate)
[![TypeScript](https://img.shields.io/badge/TypeScript->=%203.x-blue.svg)](https://nodejs.org/dist/latest-v10.x/docs/api/)
This will add `@push.rocks/smartstate` to your project's dependencies. [![node](https://img.shields.io/badge/node->=%2010.x.x-blue.svg)](https://nodejs.org/dist/latest-v10.x/docs/api/)
[![JavaScript Style Guide](https://img.shields.io/badge/code%20style-prettier-ff69b4.svg)](https://prettier.io/)
## Usage ## 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. For further information read the linked docs at the top of this readme.
### Getting Started > MIT licensed | **©** [Lossless GmbH](https://lossless.gmbh)
| By using this npm module you agree to our [privacy policy](https://lossless.gmbH/privacy)
First, let's import the necessary components from the library: [![repo-footer](https://lossless.gitlab.io/publicrelations/repofooter.svg)](https://maintainedby.lossless.com)
```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>();
```
### 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 an enum for state part names for better management:
```typescript
enum 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
);
```
### 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' });
```
### Persistent State
`Smartstate` supports the concept of persistent states, where you can maintain state across sessions. To utilize this, specify a persistent mode when getting a state part:
```typescript
const settingsStatePart = await myAppSmartState.getStatePart<AppStateParts, ISettingsState>(
AppStateParts.SettingsState,
{ theme: 'light' }, // Initial state
'persistent' // Mode
);
```
This mode ensures that the state is saved and can be reloaded even after the application restarts, providing a seamless user experience.
### 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.
Remember to leverage TypeScript for its excellent support for types and interfaces, enhancing your development experience with type checking and IntelliSense, ensuring a more reliable and maintainable codebase.
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.

@ -1,58 +1,56 @@
import { expect, tap } from '@push.rocks/tapbundle'; import { expect, tap } from '@pushrocks/tapbundle';
import * as smartstate from '../ts/index.js'; import * as smartstate from '../ts/index';
type TMyStateParts = 'testStatePart'; type TMyStateParts = 'testStatePart';
interface TStatePartPayload { interface TStatePartPayload {
currentFavorites: string[]; currentFavorites: string[];
deep: { deep: {
hi: number; hi: number;
}; };
} }
let testState: smartstate.Smartstate<TMyStateParts>; let testState: smartstate.Smartstate<TMyStateParts>;
let testStatePart: smartstate.StatePart<TMyStateParts, TStatePartPayload>; let testStatePart: smartstate.StatePart<TMyStateParts, TStatePartPayload>;
tap.test('should create a new SmartState', async () => { tap.test('should create a new SmartState', async () => {
testState = new smartstate.Smartstate<TMyStateParts>(); testState = new smartstate.Smartstate<TMyStateParts>();
expect(testState).toBeInstanceOf(smartstate.Smartstate); expect(testState).to.be.instanceOf(smartstate.Smartstate);
}); });
tap.test('should create a new StatePart', async () => { tap.test('should create a new StatePart', async () => {
testStatePart = await testState.getStatePart<TStatePartPayload>('testStatePart', { testStatePart = testState.getStatePart<TStatePartPayload>('testStatePart', {
currentFavorites: [], currentFavorites: [],
deep: { deep: {
hi: 2, hi: 2
}, }
}); });
expect(testStatePart).toBeInstanceOf(smartstate.StatePart); expect(testStatePart).to.be.instanceOf(smartstate.StatePart);
console.log(testStatePart); console.log(testStatePart);
}); });
tap.test('should select something', async () => { tap.test('should select something', async () => {
testStatePart testStatePart
.select((state) => state.deep.hi) .select(state => state.deep.hi)
.subscribe((substate) => { .subscribe(substate => {
expect(substate).toEqual(2); expect(substate).to.equal(2);
}); });
}); });
tap.test('should dispatch a state action', async (tools) => { tap.test('should dispatch a state action', async (tools) => {
const done = tools.defer(); const done = tools.defer();
const addFavourite = testStatePart.createAction<string>(async (statePart, payload) => { const addFavourite = testStatePart.createAction<string>(async (statePart, payload) => {
const currentState = statePart.getState(); const currentState = statePart.getState();
currentState.currentFavorites.push(payload); currentState.currentFavorites.push(payload);
return currentState; return currentState;
}); });
testStatePart testStatePart.waitUntilPresent(state => {
.waitUntilPresent((state) => { return state.currentFavorites[0];
return state.currentFavorites[0]; }).then(() => {
}) done.resolve();
.then(() => { });
done.resolve(); await testStatePart.dispatchAction(addFavourite, 'my favourite things');
}); expect(testStatePart.getState().currentFavorites).to.include('my favourite things');
await testStatePart.dispatchAction(addFavourite, 'my favourite things'); await done.promise;
expect(testStatePart.getState().currentFavorites).toContain('my favourite things'); });
await done.promise;
}); tap.start();
tap.start();

@ -1,8 +0,0 @@
/**
* autocreated commitinfo by @push.rocks/commitinfo
*/
export const commitinfo = {
name: '@push.rocks/smartstate',
version: '2.0.19',
description: 'A package for handling and managing state in applications.'
}

@ -1,3 +1,5 @@
export * from './smartstate.classes.smartstate.js'; export * from './smartstate.classes.smartstate';
export * from './smartstate.classes.statepart.js'; export * from './smartstate.classes.statepart';
export * from './smartstate.classes.stateaction.js'; export * from './smartstate.classes.statecollection';
export * from './smartstate.classes.stateaction';
export * from './smartstate.classes.stateobservable';

@ -1,73 +1,52 @@
import * as plugins from './smartstate.plugins.js'; import * as plugins from './smartstate.plugins';
import { StatePart } from './smartstate.classes.statepart.js'; import { StatePart } from './smartstate.classes.statepart';
export type TInitMode = 'soft' | 'mandatory' | 'force' | 'persistent'; /**
* Smartstate takes care of providing state
/** */
* 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() {}
constructor() {} public getStatePart<PayloadType>(
statePartNameArg: StatePartNameType,
/** initialArg?: PayloadType
* Allows getting and initializing a new statepart ): StatePart<StatePartNameType, PayloadType> {
* initMode === 'soft' it will allow existing stateparts if (this.statePartMap[statePartNameArg as any]) {
* initMode === 'mandatory' will fail if there is an existing statepart if (initialArg) {
* initMode === 'force' will overwrite any existing statepart throw new Error(
* @param statePartNameArg `${statePartNameArg} already exists, yet you try to set an initial state again`
* @param initialArg );
* @param initMode }
*/ return this.statePartMap[statePartNameArg as any];
public async getStatePart<PayloadType>( } else {
statePartNameArg: StatePartNameType, if (!initialArg) {
initialArg?: PayloadType, throw new Error(
initMode?: TInitMode `${statePartNameArg} does not yet exist, yet you don't provide an initial state`
): Promise<StatePart<StatePartNameType, PayloadType>> { );
if (this.statePartMap[statePartNameArg]) { }
if (initialArg && (!initMode || initMode !== 'soft')) { return this.createStatePart<PayloadType>(statePartNameArg, initialArg);
throw new Error( }
`${statePartNameArg} already exists, yet you try to set an initial state again` }
);
} /**
return this.statePartMap[statePartNameArg] as StatePart<StatePartNameType, PayloadType>; * creates a statepart
} else { * @param statePartName
if (!initialArg) { * @param initialPayloadArg
throw new Error( */
`${statePartNameArg} does not yet exist, yet you don't provide an initial state` private createStatePart<PayloadType>(
); statePartName: StatePartNameType,
} initialPayloadArg: PayloadType
return this.createStatePart<PayloadType>(statePartNameArg, initialArg, initMode); ): StatePart<StatePartNameType, PayloadType> {
} const newState = new StatePart<StatePartNameType, PayloadType>(statePartName);
} newState.setState(initialPayloadArg);
this.statePartMap[statePartName as any] = newState;
/** return newState;
* Creates a statepart }
* @param statePartName
* @param initialPayloadArg /**
*/ * dispatches an action on the main level
private async createStatePart<PayloadType>( */
statePartName: StatePartNameType, public dispatch() {}
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;
}
}

@ -1,20 +1,17 @@
import * as plugins from './smartstate.plugins.js'; import * as plugins from './smartstate.plugins';
import { StatePart } from './smartstate.classes.statepart.js'; import { StatePart } from './smartstate.classes.statepart';
export interface IActionDef<TStateType, TActionPayloadType> { export interface IActionDef<TStateType, TActionPayloadType> {
(stateArg: StatePart<any, TStateType>, actionPayload: TActionPayloadType): Promise<TStateType>; (stateArg: StatePart<any, TStateType>, actionPayload: TActionPayloadType): Promise<TStateType>;
} }
/** /**
* an actionmodifier for the state * an actionmodifier for the state
*/ */
export class StateAction<TStateType, TActionPayloadType> { export class StateAction<TStateType, TActionPayloadType> {
constructor( constructor(public statePartRef: StatePart<any, any>, public actionDef: IActionDef<TStateType, TActionPayloadType>) {}
public statePartRef: StatePart<any, any>,
public actionDef: IActionDef<TStateType, TActionPayloadType> public trigger(payload: TActionPayloadType) {
) {} this.statePartRef.dispatchAction(this, payload);
}
public trigger(payload: TActionPayloadType) { }
this.statePartRef.dispatchAction(this, payload);
}
}

@ -0,0 +1,12 @@
import * as plugins from './smartstate.plugins';
import { StatePart } from './smartstate.classes.statepart';
/**
* A StatePartCollection is a collection of StateParts.
* It can be used for expressing interest in a certain set of StateParts.
*/
export class StatePartCollection<StatePartNameType, T> extends StatePart<StatePartNameType, T> {
constructor(nameArg: StatePartNameType) {
super(nameArg);
}
}

@ -0,0 +1,13 @@
import * as plugins from './smartstate.plugins';
/**
* State observable observes a StatePart and notifies everyone interested
*/
export class StateObservable {
/**
* creates an observable from a StateCollection
*/
public static fromStatePartCollection(filterArg?: () => any) {}
constructor() {}
}

@ -1,157 +1,95 @@
import * as plugins from './smartstate.plugins.js'; import * as plugins from './smartstate.plugins';
import { StateAction, type IActionDef } from './smartstate.classes.stateaction.js';
import { Observable, Subject } from 'rxjs';
export class StatePart<TStatePartName, TStatePayload> { import { startWith, takeUntil, map } from 'rxjs/operators';
public name: TStatePartName;
public state = new plugins.smartrx.rxjs.Subject<TStatePayload>(); import { StateAction, IActionDef } from './smartstate.classes.stateaction';
public stateStore: TStatePayload;
private cumulativeDeferred = plugins.smartpromise.cumulativeDefer(); export class StatePart<TStatePartName, TStatePayload> {
public name: TStatePartName;
private webStoreOptions: plugins.webstore.IWebStoreOptions; public state = new Subject<TStatePayload>();
private webStore: plugins.webstore.WebStore<TStatePayload> | null = null; // Add WebStore instance public stateStore: TStatePayload;
constructor(nameArg: TStatePartName, webStoreOptionsArg?: plugins.webstore.IWebStoreOptions) { constructor(nameArg: TStatePartName) {
this.name = nameArg; this.name = nameArg;
}
// Initialize WebStore if webStoreOptions are provided
if (webStoreOptionsArg) { /**
this.webStoreOptions = webStoreOptionsArg; * gets the state from the state store
} */
} public getState(): TStatePayload {
return this.stateStore;
/** }
* initializes the webstore
*/ /**
public async init() { * sets the stateStore to the new state
if (this.webStoreOptions) { * @param newStateArg
this.webStore = new plugins.webstore.WebStore<TStatePayload>(this.webStoreOptions); */
await this.webStore.init(); public setState(newStateArg: TStatePayload) {
const storedState = await this.webStore.get(String(this.name)); this.stateStore = newStateArg;
if (storedState) { this.notifyChange();
this.stateStore = storedState; }
this.notifyChange();
} /**
} * notifies of a change on the state
} */
public notifyChange() {
/** this.state.next(this.stateStore);
* gets the state from the state store }
*/
public getState(): TStatePayload { /**
return this.stateStore; * selects a state or a substate
} */
public select<T = TStatePayload>(selectorFn?: (state: TStatePayload) => T): Observable<T> {
/** if (!selectorFn) {
* sets the stateStore to the new state selectorFn = (state: TStatePayload) => <T>(<any>state);
* @param newStateArg }
*/
public async setState(newStateArg: TStatePayload) { const mapped = this.state.pipe(
this.stateStore = newStateArg; startWith(this.getState()),
this.notifyChange(); map((stateArg) => {
try {
// Save state to WebStore if initialized return selectorFn(stateArg);
if (this.webStore) { } catch (e) {
await this.webStore.set(String(this.name), newStateArg); // Nothing here
} }
return this.stateStore; })
} );
/** return mapped;
* notifies of a change on the state }
*/
public notifyChange() { /**
const createStateHash = (stateArg: any) => { * creates an action capable of modifying the state
return plugins.isohash.sha256FromString(plugins.smartjson.stringify(stateArg)); */
}; public createAction<TActionPayload>(
if ( actionDef: IActionDef<TStatePayload, TActionPayload>
this.stateStore && ): StateAction<TStatePayload, TActionPayload> {
this.lastStateNotificationPayloadHash && return new StateAction(this, actionDef);
createStateHash(this.stateStore) === this.lastStateNotificationPayloadHash }
) {
return; /**
} else { * dispatches an action on the statepart level
this.lastStateNotificationPayloadHash = this.stateStore; */
} public async dispatchAction<T>(stateAction: StateAction<TStatePayload, T>, actionPayload: T) {
this.state.next(this.stateStore); const newState = await stateAction.actionDef(this, actionPayload);
} this.setState(newState);
private lastStateNotificationPayloadHash: any; }
/** /**
* creates a cumulative notification by adding a change notification at the end of the call stack; * waits until a certain part of the state becomes available
*/ * @param selectorFn
public notifyChangeCumulative() { */
// TODO: check viability public async waitUntilPresent<T = TStatePayload>(selectorFn?: (state: TStatePayload) => T): Promise<T> {
setTimeout(() => this.state.next(this.stateStore), 0); const done = plugins.smartpromise.defer<T>();
} const selectedObservable = this.select(selectorFn);
const subscription = selectedObservable.subscribe(async value => {
/** if (value) {
* selects a state or a substate done.resolve(value);
*/ }
public select<T = TStatePayload>( });
selectorFn?: (state: TStatePayload) => T const result = await done.promise;
): plugins.smartrx.rxjs.Observable<T> { subscription.unsubscribe();
if (!selectorFn) { return result;
selectorFn = (state: TStatePayload) => <T>(<any>state); }
} }
const mapped = this.state.pipe(
plugins.smartrx.rxjs.ops.startWith(this.getState()),
plugins.smartrx.rxjs.ops.map((stateArg) => {
try {
return selectorFn(stateArg);
} catch (e) {
// Nothing here
}
})
);
return mapped;
}
/**
* creates an action capable of modifying the state
*/
public createAction<TActionPayload>(
actionDef: IActionDef<TStatePayload, TActionPayload>
): StateAction<TStatePayload, TActionPayload> {
return new StateAction(this, actionDef);
}
/**
* dispatches an action on the statepart level
*/
public async dispatchAction<T>(stateAction: StateAction<TStatePayload, T>, actionPayload: T): Promise<TStatePayload> {
await this.cumulativeDeferred.promise;
const newState = await stateAction.actionDef(this, actionPayload);
await this.setState(newState);
return this.getState();
}
/**
* waits until a certain part of the state becomes available
* @param selectorFn
*/
public async waitUntilPresent<T = TStatePayload>(
selectorFn?: (state: TStatePayload) => T
): Promise<T> {
const done = plugins.smartpromise.defer<T>();
const selectedObservable = this.select(selectorFn);
const subscription = selectedObservable.subscribe(async (value) => {
if (value) {
done.resolve(value);
}
});
const result = await done.promise;
subscription.unsubscribe();
return result;
}
/**
* is executed
*/
public async stateSetup(
funcArg: (statePartArg?: StatePart<any, TStatePayload>) => Promise<TStatePayload>
) {
const resultPromise = funcArg(this);
this.cumulativeDeferred.addPromise(resultPromise);
this.setState(await resultPromise);
}
}

@ -1,7 +1,13 @@
import * as isohash from '@push.rocks/isohash'; import { Observable } from 'rxjs';
import * as smartjson from '@push.rocks/smartjson';
import * as smartpromise from '@push.rocks/smartpromise'; const rxjsPart = {
import * as smartrx from '@push.rocks/smartrx'; Observable
import * as webstore from '@push.rocks/webstore'; };
export { isohash, smartjson, smartpromise, smartrx, webstore }; export { rxjsPart };
import * as smartpromise from '@pushrocks/smartpromise';
export {
smartpromise
};

@ -1,14 +0,0 @@
{
"compilerOptions": {
"experimentalDecorators": true,
"useDefineForClassFields": false,
"target": "ES2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"esModuleInterop": true,
"verbatimModuleSyntax": true
},
"exclude": [
"dist_*/**/*.d.ts"
]
}

17
tslint.json Normal file

@ -0,0 +1,17 @@
{
"extends": ["tslint:latest", "tslint-config-prettier"],
"rules": {
"semicolon": [true, "always"],
"no-console": false,
"ordered-imports": false,
"object-literal-sort-keys": false,
"member-ordering": {
"options":{
"order": [
"static-method"
]
}
}
},
"defaultSeverity": "warning"
}