Compare commits

...

34 Commits

Author SHA1 Message Date
5f5f9db884 2.0.11 2023-10-03 12:47:13 +02:00
876042b446 fix(core): update 2023-10-03 12:47:12 +02:00
df2924577b 2.0.10 2023-10-03 07:53:29 +02:00
4abaea84f8 fix(core): update 2023-10-03 07:53:28 +02:00
de454b4c8d 2.0.9 2023-09-11 18:39:53 +02:00
961685b5bd fix(core): update 2023-09-11 18:39:52 +02:00
c622396d50 2.0.8 2023-07-27 15:20:48 +02:00
d130c1c6fd fix(core): update 2023-07-27 15:20:47 +02:00
f8a967aeac 2.0.7 2023-07-27 15:20:25 +02:00
abee699af8 fix(core): update 2023-07-27 15:20:24 +02:00
a21131eaf6 2.0.6 2023-04-13 14:22:32 +02:00
c4b214a308 fix(core): update 2023-04-13 14:22:31 +02:00
6db03eee83 2.0.5 2023-04-12 20:34:34 +02:00
efc5b54d2e fix(core): update 2023-04-12 20:34:34 +02:00
9860e43398 2.0.4 2023-04-04 21:52:27 +02:00
234117c8dd fix(core): update 2023-04-04 21:52:27 +02:00
371c6553cd 2.0.3 2023-04-04 21:44:17 +02:00
b6b738916f fix(core): update 2023-04-04 21:44:16 +02:00
fad7e0bc6b 2.0.2 2023-04-04 20:59:46 +02:00
fc4fb911ef fix(core): update 2023-04-04 20:59:45 +02:00
7e0dad1c10 2.0.1 2023-03-15 17:04:29 +01:00
0fb50714b9 fix(core): update 2023-03-15 17:04:29 +01:00
7e1821f37d 2.0.0 2022-03-25 13:31:21 +01:00
592228fc51 BREAKING CHANGE(core): switch to esm 2022-03-25 13:31:21 +01:00
431089e23f 1.0.23 2022-01-24 06:42:45 +01:00
5b64733d91 fix(core): update 2022-01-24 06:42:43 +01:00
2da2a43a09 1.0.22 2022-01-24 06:39:37 +01:00
f7887a6663 fix(core): update 2022-01-24 06:39:36 +01:00
be505ee915 1.0.21 2020-11-29 23:51:06 +00:00
9584f403b1 fix(core): update 2020-11-29 23:51:05 +00:00
993a100eae 1.0.20 2020-11-29 23:33:56 +00:00
29f0307ef8 fix(core): update 2020-11-29 23:33:55 +00:00
9413c5bcdc 1.0.19 2020-11-29 23:31:32 +00:00
1d5fb320f4 fix(core): update 2020-11-29 23:31:31 +00:00
22 changed files with 6111 additions and 3862 deletions

View File

@ -0,0 +1,66 @@
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

View File

@ -0,0 +1,124 @@
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

View File

@ -1,127 +0,0 @@
# 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:
- lossless
- docker
- notpriv
audit:
image: registry.gitlab.com/hosttoday/ht-docker-node:npmci
stage: security
script:
- npmci npm prepare
- npmci command npm install --ignore-scripts
- npmci command npm config set registry https://registry.npmjs.org
- npmci command npm audit --audit-level=high
tags:
- lossless
- 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:
- lossless
- 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:
- lossless
- docker
- notpriv
release:
stage: release
script:
- npmci node install stable
- npmci npm publish
only:
- tags
tags:
- lossless
- docker
- notpriv
# ====================
# metadata stage
# ====================
codequality:
stage: metadata
allow_failure: true
script:
- npmci command npm install -g tslint typescript
- npmci npm prepare
- npmci npm install
- npmci command "tslint -c tslint.json ./ts/**/*.ts"
tags:
- lossless
- docker
- priv
trigger:
stage: metadata
script:
- npmci trigger
only:
- tags
tags:
- lossless
- docker
- notpriv
pages:
stage: metadata
script:
- npmci node install lts
- npmci command npm install -g @gitzone/tsdoc
- npmci npm prepare
- npmci npm install
- npmci command tsdoc
tags:
- lossless
- docker
- notpriv
only:
- tags
artifacts:
expire_in: 1 week
paths:
- public
allow_failure: true

24
.vscode/launch.json vendored
View File

@ -2,28 +2,10 @@
"version": "0.2.0", "version": "0.2.0",
"configurations": [ "configurations": [
{ {
"name": "current file", "command": "npm test",
"type": "node", "name": "Run npm test",
"request": "launch", "request": "launch",
"args": [ "type": "node-terminal"
"${relativeFile}"
],
"runtimeArgs": ["-r", "@gitzone/tsrun"],
"cwd": "${workspaceRoot}",
"protocol": "inspector",
"internalConsoleOptions": "openOnSessionStart"
},
{
"name": "test.ts",
"type": "node",
"request": "launch",
"args": [
"test/test.ts"
],
"runtimeArgs": ["-r", "@gitzone/tsrun"],
"cwd": "${workspaceRoot}",
"protocol": "inspector",
"internalConsoleOptions": "openOnSessionStart"
} }
] ]
} }

View File

@ -15,7 +15,7 @@
"properties": { "properties": {
"projectType": { "projectType": {
"type": "string", "type": "string",
"enum": ["website", "element", "service", "npm"] "enum": ["website", "element", "service", "npm", "wcc"]
} }
} }
} }

View File

@ -1,4 +1,4 @@
Copyright (c) 2019 Lossless GmbH (hello@lossless.com) Copyright (c) 2019 Task Venture Capital GmbH (hello@task.vc)
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

View File

@ -7,10 +7,10 @@
"projectType": "npm", "projectType": "npm",
"module": { "module": {
"githost": "gitlab.com", "githost": "gitlab.com",
"gitscope": "pushrocks", "gitscope": "push.rocks",
"gitrepo": "smartstate", "gitrepo": "smartstate",
"shortDescription": "a package that handles state in a good way", "description": "a package that handles state in a good way",
"npmPackagename": "@pushrocks/smartstate", "npmPackagename": "@push.rocks/smartstate",
"license": "MIT" "license": "MIT"
} }
} }

3408
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -1,31 +1,33 @@
{ {
"name": "@pushrocks/smartstate", "name": "@push.rocks/smartstate",
"version": "1.0.18", "version": "2.0.11",
"private": false, "private": false,
"description": "a package that handles state in a good way", "description": "a package that handles state in a good way",
"main": "dist_ts/index.js", "main": "dist_ts/index.js",
"typings": "dist_ts/index.d.ts", "typings": "dist_ts/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 && tsbundle npm)", "build": "(tsbuild --web --allowimplicitany && tsbundle npm)",
"format": "(gitzone format)" "buildDocs": "tsdoc"
}, },
"devDependencies": { "devDependencies": {
"@gitzone/tsbuild": "^2.1.24", "@git.zone/tsbuild": "^2.1.70",
"@gitzone/tsbundle": "^1.0.69", "@git.zone/tsbundle": "^2.0.8",
"@gitzone/tstest": "^1.0.28", "@git.zone/tsrun": "^1.2.46",
"@pushrocks/tapbundle": "^3.2.1", "@git.zone/tstest": "^1.0.81",
"@types/node": "^14.0.5", "@push.rocks/tapbundle": "^5.0.15",
"tslint": "^6.1.2", "@types/node": "^20.8.0"
"tslint-config-prettier": "^1.18.0"
}, },
"dependencies": { "dependencies": {
"@pushrocks/lik": "^4.0.12", "@push.rocks/isohash": "^2.0.1",
"@pushrocks/smartpromise": "^3.0.6", "@push.rocks/lik": "^6.0.5",
"@pushrocks/smartrx": "^2.0.15", "@push.rocks/smartjson": "^5.0.10",
"rxjs": "^6.5.5" "@push.rocks/smartpromise": "^4.0.3",
"@push.rocks/smartrx": "^3.0.6",
"@push.rocks/webstore": "^2.0.13"
}, },
"files": [ "files": [
"ts/**/*", "ts/**/*",
@ -38,5 +40,8 @@
"cli.js", "cli.js",
"npmextra.json", "npmextra.json",
"readme.md" "readme.md"
],
"browserslist": [
"last 1 chrome versions"
] ]
} }

5551
pnpm-lock.yaml generated Normal file

File diff suppressed because it is too large Load Diff

View File

@ -1,20 +1,26 @@
# @pushrocks/smartstate # @push.rocks/smartstate
a package that handles state in a good way a package that handles state in a good way
## Availabililty and Links ## Availabililty and Links
* [npmjs.org (npm package)](https://www.npmjs.com/package/@pushrocks/smartstate) * [npmjs.org (npm package)](https://www.npmjs.com/package/@push.rocks/smartstate)
* [gitlab.com (source)](https://gitlab.com/pushrocks/smartstate) * [gitlab.com (source)](https://gitlab.com/push.rocks/smartstate)
* [github.com (source mirror)](https://github.com/pushrocks/smartstate) * [github.com (source mirror)](https://github.com/push.rocks/smartstate)
* [docs (typedoc)](https://pushrocks.gitlab.io/smartstate/) * [docs (typedoc)](https://push.rocks.gitlab.io/smartstate/)
## Status for master ## Status for master
[![pipeline status](https://gitlab.com/pushrocks/smartstate/badges/master/pipeline.svg)](https://gitlab.com/pushrocks/smartstate/commits/master)
[![coverage report](https://gitlab.com/pushrocks/smartstate/badges/master/coverage.svg)](https://gitlab.com/pushrocks/smartstate/commits/master) Status Category | Status Badge
[![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) GitLab Pipelines | [![pipeline status](https://gitlab.com/push.rocks/smartstate/badges/master/pipeline.svg)](https://lossless.cloud)
[![TypeScript](https://img.shields.io/badge/TypeScript->=%203.x-blue.svg)](https://nodejs.org/dist/latest-v10.x/docs/api/) GitLab Pipline Test Coverage | [![coverage report](https://gitlab.com/push.rocks/smartstate/badges/master/coverage.svg)](https://lossless.cloud)
[![node](https://img.shields.io/badge/node->=%2010.x.x-blue.svg)](https://nodejs.org/dist/latest-v10.x/docs/api/) npm | [![npm downloads per month](https://badgen.net/npm/dy/@push.rocks/smartstate)](https://lossless.cloud)
[![JavaScript Style Guide](https://img.shields.io/badge/code%20style-prettier-ff69b4.svg)](https://prettier.io/) Snyk | [![Known Vulnerabilities](https://badgen.net/snyk/push.rocks/smartstate)](https://lossless.cloud)
TypeScript Support | [![TypeScript](https://badgen.net/badge/TypeScript/>=%203.x/blue?icon=typescript)](https://lossless.cloud)
node Support | [![node](https://img.shields.io/badge/node->=%2010.x.x-blue.svg)](https://nodejs.org/dist/latest-v10.x/docs/api/)
Code Style | [![Code Style](https://badgen.net/badge/style/prettier/purple)](https://lossless.cloud)
PackagePhobia (total standalone install weight) | [![PackagePhobia](https://badgen.net/packagephobia/install/@push.rocks/smartstate)](https://lossless.cloud)
PackagePhobia (package size on registry) | [![PackagePhobia](https://badgen.net/packagephobia/publish/@push.rocks/smartstate)](https://lossless.cloud)
BundlePhobia (total size when bundled) | [![BundlePhobia](https://badgen.net/bundlephobia/minzip/@push.rocks/smartstate)](https://lossless.cloud)
## Usage ## Usage
@ -26,7 +32,6 @@ We are always happy for code contributions. If you are not the code contributing
For further information read the linked docs at the top of this readme. For further information read the linked docs at the top of this readme.
> MIT licensed | **©** [Lossless GmbH](https://lossless.gmbh) ## 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) | By using this npm module you agree to our [privacy policy](https://lossless.gmbH/privacy)
[![repo-footer](https://lossless.gitlab.io/publicrelations/repofooter.svg)](https://maintainedby.lossless.com)

View File

@ -1,58 +1,58 @@
import { expect, tap } from '@pushrocks/tapbundle'; import { expect, tap } from '@push.rocks/tapbundle';
import * as smartstate from '../ts/index'; import * as smartstate from '../ts/index.js';
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).to.be.instanceOf(smartstate.Smartstate); expect(testState).toBeInstanceOf(smartstate.Smartstate);
}); });
tap.test('should create a new StatePart', async () => { tap.test('should create a new StatePart', async () => {
testStatePart = testState.getStatePart<TStatePartPayload>('testStatePart', { testStatePart = testState.getStatePart<TStatePartPayload>('testStatePart', {
currentFavorites: [], currentFavorites: [],
deep: { deep: {
hi: 2 hi: 2,
} },
}); });
expect(testStatePart).to.be.instanceOf(smartstate.StatePart); expect(testStatePart).toBeInstanceOf(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).to.equal(2); expect(substate).toEqual(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(() => { .then(() => {
done.resolve(); done.resolve();
}); });
await testStatePart.dispatchAction(addFavourite, 'my favourite things'); await testStatePart.dispatchAction(addFavourite, 'my favourite things');
expect(testStatePart.getState().currentFavorites).to.include('my favourite things'); expect(testStatePart.getState().currentFavorites).toContain('my favourite things');
await done.promise; await done.promise;
}); });
tap.start(); tap.start();

8
ts/00_commitinfo_data.ts Normal file
View File

@ -0,0 +1,8 @@
/**
* autocreated commitinfo by @pushrocks/commitinfo
*/
export const commitinfo = {
name: '@push.rocks/smartstate',
version: '2.0.11',
description: 'a package that handles state in a good way'
}

View File

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

View File

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

View File

@ -1,20 +1,20 @@
import * as plugins from './smartstate.plugins'; import * as plugins from './smartstate.plugins.js';
import { StatePart } from './smartstate.classes.statepart'; import { StatePart } from './smartstate.classes.statepart.js';
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 statePartRef: StatePart<any, any>,
public actionDef: IActionDef<TStateType, TActionPayloadType> public actionDef: IActionDef<TStateType, TActionPayloadType>
) {} ) {}
public trigger(payload: TActionPayloadType) { public trigger(payload: TActionPayloadType) {
this.statePartRef.dispatchAction(this, payload); this.statePartRef.dispatchAction(this, payload);
} }
} }

View File

@ -1,12 +0,0 @@
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);
}
}

View File

@ -1,13 +0,0 @@
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() {}
}

View File

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

View File

@ -1,4 +1,7 @@
import * as smartpromise from '@pushrocks/smartpromise'; import * as isohash from '@push.rocks/isohash';
import * as smartrx from '@pushrocks/smartrx'; import * as smartjson from '@push.rocks/smartjson';
import * as smartpromise from '@push.rocks/smartpromise';
export { smartpromise, smartrx }; import * as smartrx from '@push.rocks/smartrx';
import * as webstore from '@push.rocks/webstore';
export { isohash, smartjson, smartpromise, smartrx, webstore };

14
tsconfig.json Normal file
View File

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

View File

@ -1,17 +0,0 @@
{
"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"
}