From c960df8ecf927f90a395d128f6b69b87d8dc8923 Mon Sep 17 00:00:00 2001 From: Brandon Roberts Date: Tue, 16 Aug 2022 12:37:57 -0500 Subject: [PATCH 1/7] feat(store): add provideStore and provideState functions for standalone APIs --- modules/store/src/index.ts | 5 +- modules/store/src/provide_store.ts | 333 +++++++++++++++++++++++++++++ modules/store/src/store_config.ts | 108 ++++++++++ modules/store/src/store_module.ts | 232 ++------------------ 4 files changed, 455 insertions(+), 223 deletions(-) create mode 100644 modules/store/src/provide_store.ts create mode 100644 modules/store/src/store_config.ts diff --git a/modules/store/src/index.ts b/modules/store/src/index.ts index e8ec874168..b1166e17de 100644 --- a/modules/store/src/index.ts +++ b/modules/store/src/index.ts @@ -57,8 +57,7 @@ export { StoreModule, StoreRootModule, StoreFeatureModule, - RootStoreConfig, - StoreConfig, - FeatureSlice, } from './store_module'; +export { RootStoreConfig, StoreConfig, FeatureSlice } from './store_config'; +export { provideStore, provideState } from './provide_store'; export { ReducerTypes, on, createReducer } from './reducer_creator'; diff --git a/modules/store/src/provide_store.ts b/modules/store/src/provide_store.ts new file mode 100644 index 0000000000..63f17bf93a --- /dev/null +++ b/modules/store/src/provide_store.ts @@ -0,0 +1,333 @@ +import { + Inject, + InjectionToken, + Injector, + Optional, + SkipSelf, + ImportedNgModuleProviders, + ENVIRONMENT_INITIALIZER, + inject, + InjectFlags, + Provider, +} from '@angular/core'; +import { + Action, + ActionReducer, + ActionReducerMap, + StoreFeature, +} from './models'; +import { combineReducers, createReducerFactory } from './utils'; +import { + INITIAL_STATE, + INITIAL_REDUCERS, + _INITIAL_REDUCERS, + REDUCER_FACTORY, + _REDUCER_FACTORY, + STORE_FEATURES, + _INITIAL_STATE, + META_REDUCERS, + _STORE_REDUCERS, + FEATURE_REDUCERS, + _FEATURE_REDUCERS, + _FEATURE_REDUCERS_TOKEN, + _STORE_FEATURES, + _FEATURE_CONFIGS, + USER_PROVIDED_META_REDUCERS, + _RESOLVED_META_REDUCERS, + _ROOT_STORE_GUARD, + _ACTION_TYPE_UNIQUENESS_CHECK, +} from './tokens'; +import { ACTIONS_SUBJECT_PROVIDERS, ActionsSubject } from './actions_subject'; +import { + REDUCER_MANAGER_PROVIDERS, + ReducerManager, + ReducerObservable, +} from './reducer_manager'; +import { + SCANNED_ACTIONS_SUBJECT_PROVIDERS, + ScannedActionsSubject, +} from './scanned_actions_subject'; +import { STATE_PROVIDERS } from './state'; +import { STORE_PROVIDERS, Store } from './store'; +import { + provideRuntimeChecks, + checkForActionTypeUniqueness, +} from './runtime_checks'; +import { + FeatureSlice, + RootStoreConfig, + StoreConfig, + _concatMetaReducers, + _createFeatureReducers, + _createFeatureStore, + _createStoreReducers, + _initialStateFactory, + _provideForRootGuard, +} from './store_config'; + +/** + * Environment Initializer used in the feature + * providers to register state features + */ +const ENVIRONMENT_STATE_PROVIDER: Provider[] = [ + { + provide: ENVIRONMENT_INITIALIZER, + multi: true, + deps: [], + useFactory() { + return () => { + const features = inject[]>(_STORE_FEATURES); + const featureReducers = + inject[]>(FEATURE_REDUCERS); + const reducerManager = inject(ReducerManager); + inject(_ACTION_TYPE_UNIQUENESS_CHECK, InjectFlags.Optional); + + const feats = features.map((feature, index) => { + const featureReducerCollection = featureReducers.shift(); + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + const reducers = featureReducerCollection! /*TODO(#823)*/[index]; + + return { + ...feature, + reducers, + initialState: _initialStateFactory(feature.initialState), + }; + }); + + reducerManager.addFeatures(feats); + }; + }, + }, +]; + +export function _provideState( + featureNameOrSlice: string | FeatureSlice, + reducers?: + | ActionReducerMap + | InjectionToken> + | ActionReducer + | InjectionToken>, + config: StoreConfig | InjectionToken> = {} +) { + return [ + { + provide: _FEATURE_CONFIGS, + multi: true, + useValue: featureNameOrSlice instanceof Object ? {} : config, + }, + { + provide: STORE_FEATURES, + multi: true, + useValue: { + key: + featureNameOrSlice instanceof Object + ? featureNameOrSlice.name + : featureNameOrSlice, + reducerFactory: + !(config instanceof InjectionToken) && config.reducerFactory + ? config.reducerFactory + : combineReducers, + metaReducers: + !(config instanceof InjectionToken) && config.metaReducers + ? config.metaReducers + : [], + initialState: + !(config instanceof InjectionToken) && config.initialState + ? config.initialState + : undefined, + }, + }, + { + provide: _STORE_FEATURES, + deps: [Injector, _FEATURE_CONFIGS, STORE_FEATURES], + useFactory: _createFeatureStore, + }, + { + provide: _FEATURE_REDUCERS, + multi: true, + useValue: + featureNameOrSlice instanceof Object + ? featureNameOrSlice.reducer + : reducers, + }, + { + provide: _FEATURE_REDUCERS_TOKEN, + multi: true, + useExisting: + reducers instanceof InjectionToken ? reducers : _FEATURE_REDUCERS, + }, + { + provide: FEATURE_REDUCERS, + multi: true, + deps: [ + Injector, + _FEATURE_REDUCERS, + [new Inject(_FEATURE_REDUCERS_TOKEN)], + ], + useFactory: _createFeatureReducers, + }, + checkForActionTypeUniqueness(), + ]; +} + +/** + * Provides additional slices of state in the Store. + * These providers cannot be used at the component level. + * + * @usageNotes + * + * ### Providing Store Features + * + * ```ts + * const booksRoutes: Route[] = [ + * { + * path: '', + * providers: [provideState('books', booksReducer)], + * children: [ + * { path: '', component: BookListComponent }, + * { path: ':id', component: BookDetailsComponent }, + * ], + * }, + * ]; + * ``` + */ +export function provideState( + featureName: string, + reducers: ActionReducerMap | InjectionToken>, + config?: StoreConfig | InjectionToken> +): ImportedNgModuleProviders; +export function provideState( + featureName: string, + reducer: ActionReducer | InjectionToken>, + config?: StoreConfig | InjectionToken> +): ImportedNgModuleProviders; +export function provideState( + slice: FeatureSlice +): ImportedNgModuleProviders; +export function provideState( + featureNameOrSlice: string | FeatureSlice, + reducers?: + | ActionReducerMap + | InjectionToken> + | ActionReducer + | InjectionToken>, + config: StoreConfig | InjectionToken> = {} +): ImportedNgModuleProviders { + return { + ɵproviders: [ + ..._provideState(featureNameOrSlice, reducers, config), + ENVIRONMENT_STATE_PROVIDER, + ], + }; +} + +export function _provideStore( + reducers: + | ActionReducerMap + | InjectionToken>, + config: RootStoreConfig +) { + return [ + { + provide: _ROOT_STORE_GUARD, + useFactory: _provideForRootGuard, + deps: [[Store, new Optional(), new SkipSelf()]], + }, + { provide: _INITIAL_STATE, useValue: config.initialState }, + { + provide: INITIAL_STATE, + useFactory: _initialStateFactory, + deps: [_INITIAL_STATE], + }, + { provide: _INITIAL_REDUCERS, useValue: reducers }, + { + provide: _STORE_REDUCERS, + useExisting: + reducers instanceof InjectionToken ? reducers : _INITIAL_REDUCERS, + }, + { + provide: INITIAL_REDUCERS, + deps: [Injector, _INITIAL_REDUCERS, [new Inject(_STORE_REDUCERS)]], + useFactory: _createStoreReducers, + }, + { + provide: USER_PROVIDED_META_REDUCERS, + useValue: config.metaReducers ? config.metaReducers : [], + }, + { + provide: _RESOLVED_META_REDUCERS, + deps: [META_REDUCERS, USER_PROVIDED_META_REDUCERS], + useFactory: _concatMetaReducers, + }, + { + provide: _REDUCER_FACTORY, + useValue: config.reducerFactory ? config.reducerFactory : combineReducers, + }, + { + provide: REDUCER_FACTORY, + deps: [_REDUCER_FACTORY, _RESOLVED_META_REDUCERS], + useFactory: createReducerFactory, + }, + ACTIONS_SUBJECT_PROVIDERS, + REDUCER_MANAGER_PROVIDERS, + SCANNED_ACTIONS_SUBJECT_PROVIDERS, + STATE_PROVIDERS, + STORE_PROVIDERS, + provideRuntimeChecks(config.runtimeChecks), + checkForActionTypeUniqueness(), + ]; +} + +/** + * Environment Initializer used in the root + * providers to initialize the Store + */ +const ENVIRONMENT_STORE_PROVIDER = [ + { + provide: ENVIRONMENT_INITIALIZER, + multi: true, + useFactory() { + return () => { + inject(ActionsSubject); + inject(ReducerObservable); + inject(ScannedActionsSubject); + inject(Store); + inject(_ROOT_STORE_GUARD, InjectFlags.Optional); + inject(_ACTION_TYPE_UNIQUENESS_CHECK, InjectFlags.Optional); + }; + }, + }, +]; + +/** + * Provides the global Store providers and initializes + * the Store. + * These providers cannot be used at the component level. + * + * @usageNotes + * + * ### Providing the Global Store + * + * ```ts + * bootstrapApplication(AppComponent, { + * providers: [provideStore({})], + * }); + * ``` + */ +export function provideStore( + reducers: ActionReducerMap | InjectionToken>, + config?: RootStoreConfig +): ImportedNgModuleProviders; +export function provideStore( + reducers: + | ActionReducerMap + | InjectionToken>, + config: RootStoreConfig = {} +): ImportedNgModuleProviders { + return { + ɵproviders: [ + ..._provideStore(reducers, config), + ENVIRONMENT_STORE_PROVIDER, + ], + }; +} diff --git a/modules/store/src/store_config.ts b/modules/store/src/store_config.ts new file mode 100644 index 0000000000..7d16429362 --- /dev/null +++ b/modules/store/src/store_config.ts @@ -0,0 +1,108 @@ +import { InjectionToken, Injector } from '@angular/core'; +import { + Action, + ActionReducer, + ActionReducerMap, + ActionReducerFactory, + StoreFeature, + InitialState, + MetaReducer, + RuntimeChecks, +} from './models'; +import { combineReducers } from './utils'; +import { + _INITIAL_REDUCERS, + _REDUCER_FACTORY, + _INITIAL_STATE, + _STORE_REDUCERS, + _FEATURE_REDUCERS, + _FEATURE_REDUCERS_TOKEN, + _STORE_FEATURES, + _FEATURE_CONFIGS, + _RESOLVED_META_REDUCERS, + _ROOT_STORE_GUARD, + _ACTION_TYPE_UNIQUENESS_CHECK, +} from './tokens'; +import { Store } from './store'; + +export interface StoreConfig { + initialState?: InitialState; + reducerFactory?: ActionReducerFactory; + metaReducers?: MetaReducer<{ [P in keyof T]: T[P] }, V>[]; +} + +export interface RootStoreConfig + extends StoreConfig { + runtimeChecks?: Partial; +} + +/** + * An object with the name and the reducer for the feature. + */ +export interface FeatureSlice { + name: string; + reducer: ActionReducer; +} + +export function _createStoreReducers( + injector: Injector, + reducers: ActionReducerMap +) { + return reducers instanceof InjectionToken ? injector.get(reducers) : reducers; +} + +export function _createFeatureStore( + injector: Injector, + configs: StoreConfig[] | InjectionToken>[], + featureStores: StoreFeature[] +) { + return featureStores.map((feat, index) => { + if (configs[index] instanceof InjectionToken) { + const conf = injector.get(configs[index]); + return { + key: feat.key, + reducerFactory: conf.reducerFactory + ? conf.reducerFactory + : combineReducers, + metaReducers: conf.metaReducers ? conf.metaReducers : [], + initialState: conf.initialState, + }; + } + return feat; + }); +} + +export function _createFeatureReducers( + injector: Injector, + reducerCollection: ActionReducerMap[] +) { + const reducers = reducerCollection.map((reducer) => { + return reducer instanceof InjectionToken ? injector.get(reducer) : reducer; + }); + + return reducers; +} + +export function _initialStateFactory(initialState: any): any { + if (typeof initialState === 'function') { + return initialState(); + } + + return initialState; +} + +export function _concatMetaReducers( + metaReducers: MetaReducer[], + userProvidedMetaReducers: MetaReducer[] +): MetaReducer[] { + return metaReducers.concat(userProvidedMetaReducers); +} + +export function _provideForRootGuard(store: Store): any { + if (store) { + throw new TypeError( + `StoreModule.forRoot() called twice. Feature modules should use StoreModule.forFeature() instead.` + ); + } + return 'guarded'; +} diff --git a/modules/store/src/store_module.ts b/modules/store/src/store_module.ts index 3821525d03..a37fba0d36 100644 --- a/modules/store/src/store_module.ts +++ b/modules/store/src/store_module.ts @@ -4,57 +4,39 @@ import { ModuleWithProviders, OnDestroy, InjectionToken, - Injector, Optional, - SkipSelf, } from '@angular/core'; import { Action, ActionReducer, ActionReducerMap, - ActionReducerFactory, StoreFeature, - InitialState, - MetaReducer, - RuntimeChecks, } from './models'; -import { combineReducers, createReducerFactory } from './utils'; import { - INITIAL_STATE, - INITIAL_REDUCERS, _INITIAL_REDUCERS, - REDUCER_FACTORY, _REDUCER_FACTORY, - STORE_FEATURES, _INITIAL_STATE, - META_REDUCERS, _STORE_REDUCERS, FEATURE_REDUCERS, _FEATURE_REDUCERS, _FEATURE_REDUCERS_TOKEN, _STORE_FEATURES, _FEATURE_CONFIGS, - USER_PROVIDED_META_REDUCERS, _RESOLVED_META_REDUCERS, _ROOT_STORE_GUARD, _ACTION_TYPE_UNIQUENESS_CHECK, } from './tokens'; -import { ACTIONS_SUBJECT_PROVIDERS, ActionsSubject } from './actions_subject'; +import { ActionsSubject } from './actions_subject'; +import { ReducerManager, ReducerObservable } from './reducer_manager'; +import { ScannedActionsSubject } from './scanned_actions_subject'; +import { Store } from './store'; import { - REDUCER_MANAGER_PROVIDERS, - ReducerManager, - ReducerObservable, -} from './reducer_manager'; -import { - SCANNED_ACTIONS_SUBJECT_PROVIDERS, - ScannedActionsSubject, -} from './scanned_actions_subject'; -import { STATE_PROVIDERS } from './state'; -import { STORE_PROVIDERS, Store } from './store'; -import { - provideRuntimeChecks, - checkForActionTypeUniqueness, -} from './runtime_checks'; + FeatureSlice, + RootStoreConfig, + StoreConfig, + _initialStateFactory, +} from './store_config'; +import { _provideState, _provideStore } from './provide_store'; @NgModule({}) export class StoreRootModule { @@ -104,25 +86,6 @@ export class StoreFeatureModule implements OnDestroy { } } -export interface StoreConfig { - initialState?: InitialState; - reducerFactory?: ActionReducerFactory; - metaReducers?: MetaReducer<{ [P in keyof T]: T[P] }, V>[]; -} - -export interface RootStoreConfig - extends StoreConfig { - runtimeChecks?: Partial; -} - -/** - * An object with the name and the reducer for the feature. - */ -export interface FeatureSlice { - name: string; - reducer: ActionReducer; -} - @NgModule({}) export class StoreModule { static forRoot( @@ -137,57 +100,7 @@ export class StoreModule { ): ModuleWithProviders { return { ngModule: StoreRootModule, - providers: [ - { - provide: _ROOT_STORE_GUARD, - useFactory: _provideForRootGuard, - deps: [[Store, new Optional(), new SkipSelf()]], - }, - { provide: _INITIAL_STATE, useValue: config.initialState }, - { - provide: INITIAL_STATE, - useFactory: _initialStateFactory, - deps: [_INITIAL_STATE], - }, - { provide: _INITIAL_REDUCERS, useValue: reducers }, - { - provide: _STORE_REDUCERS, - useExisting: - reducers instanceof InjectionToken ? reducers : _INITIAL_REDUCERS, - }, - { - provide: INITIAL_REDUCERS, - deps: [Injector, _INITIAL_REDUCERS, [new Inject(_STORE_REDUCERS)]], - useFactory: _createStoreReducers, - }, - { - provide: USER_PROVIDED_META_REDUCERS, - useValue: config.metaReducers ? config.metaReducers : [], - }, - { - provide: _RESOLVED_META_REDUCERS, - deps: [META_REDUCERS, USER_PROVIDED_META_REDUCERS], - useFactory: _concatMetaReducers, - }, - { - provide: _REDUCER_FACTORY, - useValue: config.reducerFactory - ? config.reducerFactory - : combineReducers, - }, - { - provide: REDUCER_FACTORY, - deps: [_REDUCER_FACTORY, _RESOLVED_META_REDUCERS], - useFactory: createReducerFactory, - }, - ACTIONS_SUBJECT_PROVIDERS, - REDUCER_MANAGER_PROVIDERS, - SCANNED_ACTIONS_SUBJECT_PROVIDERS, - STATE_PROVIDERS, - STORE_PROVIDERS, - provideRuntimeChecks(config.runtimeChecks), - checkForActionTypeUniqueness(), - ], + providers: [..._provideStore(reducers, config)], }; } @@ -215,128 +128,7 @@ export class StoreModule { ): ModuleWithProviders { return { ngModule: StoreFeatureModule, - providers: [ - { - provide: _FEATURE_CONFIGS, - multi: true, - useValue: featureNameOrSlice instanceof Object ? {} : config, - }, - { - provide: STORE_FEATURES, - multi: true, - useValue: { - key: - featureNameOrSlice instanceof Object - ? featureNameOrSlice.name - : featureNameOrSlice, - reducerFactory: - !(config instanceof InjectionToken) && config.reducerFactory - ? config.reducerFactory - : combineReducers, - metaReducers: - !(config instanceof InjectionToken) && config.metaReducers - ? config.metaReducers - : [], - initialState: - !(config instanceof InjectionToken) && config.initialState - ? config.initialState - : undefined, - }, - }, - { - provide: _STORE_FEATURES, - deps: [Injector, _FEATURE_CONFIGS, STORE_FEATURES], - useFactory: _createFeatureStore, - }, - { - provide: _FEATURE_REDUCERS, - multi: true, - useValue: - featureNameOrSlice instanceof Object - ? featureNameOrSlice.reducer - : reducers, - }, - { - provide: _FEATURE_REDUCERS_TOKEN, - multi: true, - useExisting: - reducers instanceof InjectionToken ? reducers : _FEATURE_REDUCERS, - }, - { - provide: FEATURE_REDUCERS, - multi: true, - deps: [ - Injector, - _FEATURE_REDUCERS, - [new Inject(_FEATURE_REDUCERS_TOKEN)], - ], - useFactory: _createFeatureReducers, - }, - checkForActionTypeUniqueness(), - ], + providers: [..._provideState(featureNameOrSlice, reducers, config)], }; } } - -export function _createStoreReducers( - injector: Injector, - reducers: ActionReducerMap -) { - return reducers instanceof InjectionToken ? injector.get(reducers) : reducers; -} - -export function _createFeatureStore( - injector: Injector, - configs: StoreConfig[] | InjectionToken>[], - featureStores: StoreFeature[] -) { - return featureStores.map((feat, index) => { - if (configs[index] instanceof InjectionToken) { - const conf = injector.get(configs[index]); - return { - key: feat.key, - reducerFactory: conf.reducerFactory - ? conf.reducerFactory - : combineReducers, - metaReducers: conf.metaReducers ? conf.metaReducers : [], - initialState: conf.initialState, - }; - } - return feat; - }); -} - -export function _createFeatureReducers( - injector: Injector, - reducerCollection: ActionReducerMap[] -) { - const reducers = reducerCollection.map((reducer) => { - return reducer instanceof InjectionToken ? injector.get(reducer) : reducer; - }); - - return reducers; -} - -export function _initialStateFactory(initialState: any): any { - if (typeof initialState === 'function') { - return initialState(); - } - - return initialState; -} - -export function _concatMetaReducers( - metaReducers: MetaReducer[], - userProvidedMetaReducers: MetaReducer[] -): MetaReducer[] { - return metaReducers.concat(userProvidedMetaReducers); -} - -export function _provideForRootGuard(store: Store): any { - if (store) { - throw new TypeError( - `StoreModule.forRoot() called twice. Feature modules should use StoreModule.forFeature() instead.` - ); - } - return 'guarded'; -} From 68c38d01dbbb907178cd02922e1e9990c41d627c Mon Sep 17 00:00:00 2001 From: Brandon Roberts Date: Tue, 16 Aug 2022 13:12:46 -0500 Subject: [PATCH 2/7] chore: add test application with standalone APIs --- .gitignore | 2 + angular.json | 121 ++++++++++++++++++ nx.json | 13 ++ package.json | 1 + projects/standalone-app-e2e/.eslintrc.json | 10 ++ projects/standalone-app-e2e/cypress.json | 12 ++ .../src/fixtures/example.json | 4 + .../src/integration/app.spec.ts | 13 ++ .../standalone-app-e2e/src/support/app.po.ts | 1 + .../src/support/commands.ts | 33 +++++ .../standalone-app-e2e/src/support/index.ts | 17 +++ projects/standalone-app-e2e/tsconfig.json | 21 +++ projects/standalone-app/.browserslistrc | 16 +++ projects/standalone-app/.eslintrc.json | 36 ++++++ projects/standalone-app/jest.config.ts | 22 ++++ .../src/app/app.component.spec.ts | 32 +++++ .../standalone-app/src/app/app.component.ts | 19 +++ .../src/app/lazy/feature.component.ts | 24 ++++ .../src/app/lazy/feature.routes.ts | 12 ++ .../src/app/lazy/feature.state.ts | 26 ++++ projects/standalone-app/src/assets/.gitkeep | 0 .../src/environments/environment.prod.ts | 3 + .../src/environments/environment.ts | 16 +++ projects/standalone-app/src/favicon.ico | Bin 0 -> 15086 bytes projects/standalone-app/src/index.html | 13 ++ projects/standalone-app/src/main.ts | 32 +++++ projects/standalone-app/src/polyfills.ts | 52 ++++++++ projects/standalone-app/src/styles.css | 1 + projects/standalone-app/src/test-setup.ts | 1 + projects/standalone-app/tsconfig.app.json | 11 ++ projects/standalone-app/tsconfig.editor.json | 7 + projects/standalone-app/tsconfig.json | 30 +++++ projects/standalone-app/tsconfig.spec.json | 10 ++ yarn.lock | 5 + 34 files changed, 616 insertions(+) create mode 100644 projects/standalone-app-e2e/.eslintrc.json create mode 100644 projects/standalone-app-e2e/cypress.json create mode 100644 projects/standalone-app-e2e/src/fixtures/example.json create mode 100644 projects/standalone-app-e2e/src/integration/app.spec.ts create mode 100644 projects/standalone-app-e2e/src/support/app.po.ts create mode 100644 projects/standalone-app-e2e/src/support/commands.ts create mode 100644 projects/standalone-app-e2e/src/support/index.ts create mode 100644 projects/standalone-app-e2e/tsconfig.json create mode 100644 projects/standalone-app/.browserslistrc create mode 100644 projects/standalone-app/.eslintrc.json create mode 100644 projects/standalone-app/jest.config.ts create mode 100644 projects/standalone-app/src/app/app.component.spec.ts create mode 100644 projects/standalone-app/src/app/app.component.ts create mode 100644 projects/standalone-app/src/app/lazy/feature.component.ts create mode 100644 projects/standalone-app/src/app/lazy/feature.routes.ts create mode 100644 projects/standalone-app/src/app/lazy/feature.state.ts create mode 100644 projects/standalone-app/src/assets/.gitkeep create mode 100644 projects/standalone-app/src/environments/environment.prod.ts create mode 100644 projects/standalone-app/src/environments/environment.ts create mode 100644 projects/standalone-app/src/favicon.ico create mode 100644 projects/standalone-app/src/index.html create mode 100644 projects/standalone-app/src/main.ts create mode 100644 projects/standalone-app/src/polyfills.ts create mode 100644 projects/standalone-app/src/styles.css create mode 100644 projects/standalone-app/src/test-setup.ts create mode 100644 projects/standalone-app/tsconfig.app.json create mode 100644 projects/standalone-app/tsconfig.editor.json create mode 100644 projects/standalone-app/tsconfig.json create mode 100644 projects/standalone-app/tsconfig.spec.json diff --git a/.gitignore b/.gitignore index a27c4247b3..94a867e63b 100644 --- a/.gitignore +++ b/.gitignore @@ -75,3 +75,5 @@ example-dist/ *.tgz modules/*/schematics-core/testing !modules/schematics-core/testing + +.angular diff --git a/angular.json b/angular.json index f54d03c9cc..2019293cf2 100644 --- a/angular.json +++ b/angular.json @@ -798,6 +798,127 @@ "schematics": {}, "tags": [] }, + "standalone-app": { + "projectType": "application", + "root": "projects/standalone-app", + "sourceRoot": "projects/standalone-app/src", + "prefix": "ngrx", + "architect": { + "build": { + "builder": "@angular-devkit/build-angular:browser", + "outputs": ["{options.outputPath}"], + "options": { + "outputPath": "dist/projects/standalone-app", + "index": "projects/standalone-app/src/index.html", + "main": "projects/standalone-app/src/main.ts", + "polyfills": "projects/standalone-app/src/polyfills.ts", + "tsConfig": "projects/standalone-app/tsconfig.app.json", + "assets": [ + "projects/standalone-app/src/favicon.ico", + "projects/standalone-app/src/assets" + ], + "styles": ["projects/standalone-app/src/styles.css"], + "scripts": [] + }, + "configurations": { + "production": { + "budgets": [ + { + "type": "initial", + "maximumWarning": "500kb", + "maximumError": "1mb" + }, + { + "type": "anyComponentStyle", + "maximumWarning": "2kb", + "maximumError": "4kb" + } + ], + "fileReplacements": [ + { + "replace": "projects/standalone-app/src/environments/environment.ts", + "with": "projects/standalone-app/src/environments/environment.prod.ts" + } + ], + "outputHashing": "all" + }, + "development": { + "buildOptimizer": false, + "optimization": false, + "vendorChunk": true, + "extractLicenses": false, + "sourceMap": true, + "namedChunks": true + } + }, + "defaultConfiguration": "production" + }, + "serve": { + "builder": "@angular-devkit/build-angular:dev-server", + "configurations": { + "production": { + "browserTarget": "standalone-app:build:production" + }, + "development": { + "browserTarget": "standalone-app:build:development" + } + }, + "defaultConfiguration": "development" + }, + "extract-i18n": { + "builder": "@angular-devkit/build-angular:extract-i18n", + "options": { + "browserTarget": "standalone-app:build" + } + }, + "lint": { + "builder": "@nrwl/linter:eslint", + "options": { + "lintFilePatterns": [ + "projects/standalone-app/**/*.ts", + "projects/standalone-app/**/*.html" + ] + } + }, + "test": { + "builder": "@nrwl/jest:jest", + "outputs": ["coverage/projects/standalone-app"], + "options": { + "jestConfig": "projects/standalone-app/jest.config.ts", + "passWithNoTests": true + } + } + }, + "tags": [] + }, + "standalone-app-e2e": { + "root": "projects/standalone-app-e2e", + "sourceRoot": "projects/standalone-app-e2e/src", + "projectType": "application", + "architect": { + "e2e": { + "builder": "@nrwl/cypress:cypress", + "options": { + "cypressConfig": "projects/standalone-app-e2e/cypress.json", + "devServerTarget": "standalone-app:serve:development" + }, + "configurations": { + "production": { + "devServerTarget": "standalone-app:serve:production" + } + } + }, + "lint": { + "builder": "@nrwl/linter:eslint", + "outputs": ["{options.outputFile}"], + "options": { + "lintFilePatterns": ["projects/standalone-app-e2e/**/*.{js,ts}"] + } + } + }, + "tags": [], + "implicitDependencies": ["standalone-app"] + }, "store": { "projectType": "library", "root": "modules/store", diff --git a/nx.json b/nx.json index c66c1b5746..c6f25900f8 100644 --- a/nx.json +++ b/nx.json @@ -57,6 +57,19 @@ }, "@schematics/angular:directive": { "prefix": "bc" + }, + "@nrwl/angular:application": { + "style": "css", + "linter": "eslint", + "unitTestRunner": "jest", + "e2eTestRunner": "cypress" + }, + "@nrwl/angular:library": { + "linter": "eslint", + "unitTestRunner": "jest" + }, + "@nrwl/angular:component": { + "style": "css" } }, "defaultProject": "example-app" diff --git a/package.json b/package.json index 5d5f5acc15..3842927f6f 100644 --- a/package.json +++ b/package.json @@ -117,6 +117,7 @@ "@angular-eslint/template-parser": "13.2.0", "@angular/cli": "14.0.0-rc.1", "@angular/compiler-cli": "14.0.0-rc.1", + "@angular/language-service": "~13.3.0", "@babel/core": "7.9.0", "@nrwl/cli": "14.1.5", "@nrwl/cypress": "14.1.5", diff --git a/projects/standalone-app-e2e/.eslintrc.json b/projects/standalone-app-e2e/.eslintrc.json new file mode 100644 index 0000000000..696cb8b121 --- /dev/null +++ b/projects/standalone-app-e2e/.eslintrc.json @@ -0,0 +1,10 @@ +{ + "extends": ["plugin:cypress/recommended", "../../.eslintrc.json"], + "ignorePatterns": ["!**/*"], + "overrides": [ + { + "files": ["*.ts", "*.tsx", "*.js", "*.jsx"], + "rules": {} + } + ] +} diff --git a/projects/standalone-app-e2e/cypress.json b/projects/standalone-app-e2e/cypress.json new file mode 100644 index 0000000000..9c165f46a8 --- /dev/null +++ b/projects/standalone-app-e2e/cypress.json @@ -0,0 +1,12 @@ +{ + "fileServerFolder": ".", + "fixturesFolder": "./src/fixtures", + "integrationFolder": "./src/integration", + "modifyObstructiveCode": false, + "supportFile": "./src/support/index.ts", + "pluginsFile": false, + "video": true, + "videosFolder": "../../dist/cypress/projects/standalone-app-e2e/videos", + "screenshotsFolder": "../../dist/cypress/projects/standalone-app-e2e/screenshots", + "chromeWebSecurity": false +} diff --git a/projects/standalone-app-e2e/src/fixtures/example.json b/projects/standalone-app-e2e/src/fixtures/example.json new file mode 100644 index 0000000000..294cbed6ce --- /dev/null +++ b/projects/standalone-app-e2e/src/fixtures/example.json @@ -0,0 +1,4 @@ +{ + "name": "Using fixtures to represent data", + "email": "hello@cypress.io" +} diff --git a/projects/standalone-app-e2e/src/integration/app.spec.ts b/projects/standalone-app-e2e/src/integration/app.spec.ts new file mode 100644 index 0000000000..0eeeb052a0 --- /dev/null +++ b/projects/standalone-app-e2e/src/integration/app.spec.ts @@ -0,0 +1,13 @@ +import { getGreeting } from '../support/app.po'; + +describe('standalone-app', () => { + beforeEach(() => cy.visit('/')); + + it('should display welcome message', () => { + // Custom command example, see `../support/commands.ts` file + cy.login('my-email@something.com', 'myPassword'); + + // Function helper example, see `../support/app.po.ts` file + getGreeting().contains('Welcome standalone-app'); + }); +}); diff --git a/projects/standalone-app-e2e/src/support/app.po.ts b/projects/standalone-app-e2e/src/support/app.po.ts new file mode 100644 index 0000000000..3293424696 --- /dev/null +++ b/projects/standalone-app-e2e/src/support/app.po.ts @@ -0,0 +1 @@ +export const getGreeting = () => cy.get('h1'); diff --git a/projects/standalone-app-e2e/src/support/commands.ts b/projects/standalone-app-e2e/src/support/commands.ts new file mode 100644 index 0000000000..310f1fa0e0 --- /dev/null +++ b/projects/standalone-app-e2e/src/support/commands.ts @@ -0,0 +1,33 @@ +// *********************************************** +// This example commands.js shows you how to +// create various custom commands and overwrite +// existing commands. +// +// For more comprehensive examples of custom +// commands please read more here: +// https://on.cypress.io/custom-commands +// *********************************************** + +// eslint-disable-next-line @typescript-eslint/no-namespace +declare namespace Cypress { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + interface Chainable { + login(email: string, password: string): void; + } +} +// +// -- This is a parent command -- +Cypress.Commands.add('login', (email, password) => { + console.log('Custom command example: Login', email, password); +}); +// +// -- This is a child command -- +// Cypress.Commands.add("drag", { prevSubject: 'element'}, (subject, options) => { ... }) +// +// +// -- This is a dual command -- +// Cypress.Commands.add("dismiss", { prevSubject: 'optional'}, (subject, options) => { ... }) +// +// +// -- This will overwrite an existing command -- +// Cypress.Commands.overwrite("visit", (originalFn, url, options) => { ... }) diff --git a/projects/standalone-app-e2e/src/support/index.ts b/projects/standalone-app-e2e/src/support/index.ts new file mode 100644 index 0000000000..3d469a6b6c --- /dev/null +++ b/projects/standalone-app-e2e/src/support/index.ts @@ -0,0 +1,17 @@ +// *********************************************************** +// This example support/index.js is processed and +// loaded automatically before your test files. +// +// This is a great place to put global configuration and +// behavior that modifies Cypress. +// +// You can change the location of this file or turn off +// automatically serving support files with the +// 'supportFile' configuration option. +// +// You can read more here: +// https://on.cypress.io/configuration +// *********************************************************** + +// Import commands.js using ES2015 syntax: +import './commands'; diff --git a/projects/standalone-app-e2e/tsconfig.json b/projects/standalone-app-e2e/tsconfig.json new file mode 100644 index 0000000000..4c65bb5c9f --- /dev/null +++ b/projects/standalone-app-e2e/tsconfig.json @@ -0,0 +1,21 @@ +{ + "extends": "../../tsconfig.json", + "compilerOptions": { + "sourceMap": false, + "outDir": "../../dist/out-tsc", + "allowJs": true, + "types": ["cypress", "node"], + "forceConsistentCasingInFileNames": true, + "strict": true, + "noImplicitOverride": true, + "noPropertyAccessFromIndexSignature": true, + "noImplicitReturns": true, + "noFallthroughCasesInSwitch": true + }, + "include": ["src/**/*.ts", "src/**/*.js"], + "angularCompilerOptions": { + "strictInjectionParameters": true, + "strictInputAccessModifiers": true, + "strictTemplates": true + } +} diff --git a/projects/standalone-app/.browserslistrc b/projects/standalone-app/.browserslistrc new file mode 100644 index 0000000000..4f9ac26980 --- /dev/null +++ b/projects/standalone-app/.browserslistrc @@ -0,0 +1,16 @@ +# This file is used by the build system to adjust CSS and JS output to support the specified browsers below. +# For additional information regarding the format and rule options, please see: +# https://github.com/browserslist/browserslist#queries + +# For the full list of supported browsers by the Angular framework, please see: +# https://angular.io/guide/browser-support + +# You can see what browsers were selected by your queries by running: +# npx browserslist + +last 1 Chrome version +last 1 Firefox version +last 2 Edge major versions +last 2 Safari major versions +last 2 iOS major versions +Firefox ESR diff --git a/projects/standalone-app/.eslintrc.json b/projects/standalone-app/.eslintrc.json new file mode 100644 index 0000000000..b7041b9dc2 --- /dev/null +++ b/projects/standalone-app/.eslintrc.json @@ -0,0 +1,36 @@ +{ + "extends": ["../../.eslintrc.json"], + "ignorePatterns": ["!**/*"], + "overrides": [ + { + "files": ["*.ts"], + "extends": [ + "plugin:@nrwl/nx/angular", + "plugin:@angular-eslint/template/process-inline-templates" + ], + "rules": { + "@angular-eslint/directive-selector": [ + "error", + { + "type": "attribute", + "prefix": "ngrx", + "style": "camelCase" + } + ], + "@angular-eslint/component-selector": [ + "error", + { + "type": "element", + "prefix": "ngrx", + "style": "kebab-case" + } + ] + } + }, + { + "files": ["*.html"], + "extends": ["plugin:@nrwl/nx/angular-template"], + "rules": {} + } + ] +} diff --git a/projects/standalone-app/jest.config.ts b/projects/standalone-app/jest.config.ts new file mode 100644 index 0000000000..1a31e1a280 --- /dev/null +++ b/projects/standalone-app/jest.config.ts @@ -0,0 +1,22 @@ +/* eslint-disable */ +export default { + displayName: 'standalone-app', + preset: '../../jest.preset.js', + setupFilesAfterEnv: ['/src/test-setup.ts'], + globals: { + 'ts-jest': { + tsconfig: '/tsconfig.spec.json', + stringifyContentPathRegex: '\\.(html|svg)$', + }, + }, + coverageDirectory: '../../coverage/projects/standalone-app', + transform: { + '^.+\\.(ts|mjs|js|html)$': 'jest-preset-angular', + }, + transformIgnorePatterns: ['node_modules/(?!.*\\.mjs$)'], + snapshotSerializers: [ + 'jest-preset-angular/build/serializers/no-ng-attributes', + 'jest-preset-angular/build/serializers/ng-snapshot', + 'jest-preset-angular/build/serializers/html-comment', + ], +}; diff --git a/projects/standalone-app/src/app/app.component.spec.ts b/projects/standalone-app/src/app/app.component.spec.ts new file mode 100644 index 0000000000..c454a5e18a --- /dev/null +++ b/projects/standalone-app/src/app/app.component.spec.ts @@ -0,0 +1,32 @@ +import { TestBed } from '@angular/core/testing'; +import { AppComponent } from './app.component'; +import { RouterTestingModule } from '@angular/router/testing'; + +describe('AppComponent', () => { + beforeEach(async () => { + await TestBed.configureTestingModule({ + imports: [RouterTestingModule, AppComponent], + }).compileComponents(); + }); + + it('should create the app', () => { + const fixture = TestBed.createComponent(AppComponent); + const app = fixture.componentInstance; + expect(app).toBeTruthy(); + }); + + it(`should have as title 'standalone-app'`, () => { + const fixture = TestBed.createComponent(AppComponent); + const app = fixture.componentInstance; + expect(app.title).toEqual('standalone-app'); + }); + + it('should render title', () => { + const fixture = TestBed.createComponent(AppComponent); + fixture.detectChanges(); + const compiled = fixture.nativeElement as HTMLElement; + expect(compiled.querySelector('h1')?.textContent).toContain( + 'Welcome standalone-app' + ); + }); +}); diff --git a/projects/standalone-app/src/app/app.component.ts b/projects/standalone-app/src/app/app.component.ts new file mode 100644 index 0000000000..81ccf55e93 --- /dev/null +++ b/projects/standalone-app/src/app/app.component.ts @@ -0,0 +1,19 @@ +import { Component } from '@angular/core'; +import { RouterModule } from '@angular/router'; + +@Component({ + selector: 'ngrx-root', + standalone: true, + imports: [RouterModule], + template: ` + Welcome {{ title }} + + Load Feature + + + `, + styles: [], +}) +export class AppComponent { + title = 'ngrx-standalone-app'; +} diff --git a/projects/standalone-app/src/app/lazy/feature.component.ts b/projects/standalone-app/src/app/lazy/feature.component.ts new file mode 100644 index 0000000000..64f95b9e50 --- /dev/null +++ b/projects/standalone-app/src/app/lazy/feature.component.ts @@ -0,0 +1,24 @@ +import { CommonModule } from '@angular/common'; +import { Component } from '@angular/core'; +import { Store } from '@ngrx/store'; +import { FeatureActions, feature } from './feature.state'; + +@Component({ + selector: 'app-feature', + standalone: true, + imports: [CommonModule], + template: ` +

lazy component works!!

+ + Feature State: {{ feature$ | async | json }} + `, +}) +export class FeatureComponent { + feature$ = this.store.select(feature.selectFeatureState); + + constructor(private store: Store) {} + + ngOnInit() { + this.store.dispatch(FeatureActions.init()); + } +} diff --git a/projects/standalone-app/src/app/lazy/feature.routes.ts b/projects/standalone-app/src/app/lazy/feature.routes.ts new file mode 100644 index 0000000000..2cb5cbbe1a --- /dev/null +++ b/projects/standalone-app/src/app/lazy/feature.routes.ts @@ -0,0 +1,12 @@ +import { Routes } from '@angular/router'; +import { provideState } from '@ngrx/store'; +import { FeatureComponent } from './feature.component'; +import { feature } from './feature.state'; + +export const routes: Routes = [ + { + path: '', + component: FeatureComponent, + providers: [provideState(feature)], + }, +]; diff --git a/projects/standalone-app/src/app/lazy/feature.state.ts b/projects/standalone-app/src/app/lazy/feature.state.ts new file mode 100644 index 0000000000..6bcf96891e --- /dev/null +++ b/projects/standalone-app/src/app/lazy/feature.state.ts @@ -0,0 +1,26 @@ +import { + createActionGroup, + createFeature, + createReducer, + emptyProps, +} from '@ngrx/store'; + +export const FeatureActions = createActionGroup({ + source: 'Feature Page', + events: { + init: emptyProps(), + }, +}); + +export interface FeatureState { + loaded: boolean; +} + +export const initialState: FeatureState = { + loaded: true, +}; + +export const feature = createFeature({ + name: 'feature', + reducer: createReducer(initialState), +}); diff --git a/projects/standalone-app/src/assets/.gitkeep b/projects/standalone-app/src/assets/.gitkeep new file mode 100644 index 0000000000..e69de29bb2 diff --git a/projects/standalone-app/src/environments/environment.prod.ts b/projects/standalone-app/src/environments/environment.prod.ts new file mode 100644 index 0000000000..c9669790be --- /dev/null +++ b/projects/standalone-app/src/environments/environment.prod.ts @@ -0,0 +1,3 @@ +export const environment = { + production: true, +}; diff --git a/projects/standalone-app/src/environments/environment.ts b/projects/standalone-app/src/environments/environment.ts new file mode 100644 index 0000000000..66998ae9a7 --- /dev/null +++ b/projects/standalone-app/src/environments/environment.ts @@ -0,0 +1,16 @@ +// This file can be replaced during build by using the `fileReplacements` array. +// `ng build` replaces `environment.ts` with `environment.prod.ts`. +// The list of file replacements can be found in `angular.json`. + +export const environment = { + production: false, +}; + +/* + * For easier debugging in development mode, you can import the following file + * to ignore zone related error stack frames such as `zone.run`, `zoneDelegate.invokeTask`. + * + * This import should be commented out in production mode because it will have a negative impact + * on performance if an error is thrown. + */ +// import 'zone.js/plugins/zone-error'; // Included with Angular CLI. diff --git a/projects/standalone-app/src/favicon.ico b/projects/standalone-app/src/favicon.ico new file mode 100644 index 0000000000000000000000000000000000000000..317ebcb2336e0833a22dddf0ab287849f26fda57 GIT binary patch literal 15086 zcmeI332;U^%p|z7g|#(P)qFEA@4f!_@qOK2 z_lJl}!lhL!VT_U|uN7%8B2iKH??xhDa;*`g{yjTFWHvXn;2s{4R7kH|pKGdy(7z!K zgftM+Ku7~24TLlh(!g)gz|foI94G^t2^IO$uvX$3(OR0<_5L2sB)lMAMy|+`xodJ{ z_Uh_1m)~h?a;2W{dmhM;u!YGo=)OdmId_B<%^V^{ovI@y`7^g1_V9G}*f# zNzAtvou}I!W1#{M^@ROc(BZ! z+F!!_aR&Px3_reO(EW+TwlW~tv*2zr?iP7(d~a~yA|@*a89IUke+c472NXM0wiX{- zl`UrZC^1XYyf%1u)-Y)jj9;MZ!SLfd2Hl?o|80Su%Z?To_=^g_Jt0oa#CT*tjx>BI z16wec&AOWNK<#i0Qd=1O$fymLRoUR*%;h@*@v7}wApDl^w*h}!sYq%kw+DKDY)@&A z@9$ULEB3qkR#85`lb8#WZw=@})#kQig9oqy^I$dj&k4jU&^2(M3q{n1AKeGUKPFbr z1^<)aH;VsG@J|B&l>UtU#Ejv3GIqERzYgL@UOAWtW<{p#zy`WyJgpCy8$c_e%wYJL zyGHRRx38)HyjU3y{-4z6)pzb>&Q1pR)B&u01F-|&Gx4EZWK$nkUkOI|(D4UHOXg_- zw{OBf!oWQUn)Pe(=f=nt=zkmdjpO^o8ZZ9o_|4tW1ni+Un9iCW47*-ut$KQOww!;u z`0q)$s6IZO!~9$e_P9X!hqLxu`fpcL|2f^I5d4*a@Dq28;@2271v_N+5HqYZ>x;&O z05*7JT)mUe&%S0@UD)@&8SmQrMtsDfZT;fkdA!r(S=}Oz>iP)w=W508=Rc#nNn7ym z1;42c|8($ALY8#a({%1#IXbWn9-Y|0eDY$_L&j{63?{?AH{);EzcqfydD$@-B`Y3<%IIj7S7rK_N}je^=dEk%JQ4c z!tBdTPE3Tse;oYF>cnrapWq*o)m47X1`~6@(!Y29#>-#8zm&LXrXa(3=7Z)ElaQqj z-#0JJy3Fi(C#Rx(`=VXtJ63E2_bZGCz+QRa{W0e2(m3sI?LOcUBx)~^YCqZ{XEPX)C>G>U4tfqeH8L(3|pQR*zbL1 zT9e~4Tb5p9_G}$y4t`i*4t_Mr9QYvL9C&Ah*}t`q*}S+VYh0M6GxTTSXI)hMpMpIq zD1ImYqJLzbj0}~EpE-aH#VCH_udYEW#`P2zYmi&xSPs_{n6tBj=MY|-XrA;SGA_>y zGtU$?HXm$gYj*!N)_nQ59%lQdXtQZS3*#PC-{iB_sm+ytD*7j`D*k(P&IH2GHT}Eh z5697eQECVIGQAUe#eU2I!yI&%0CP#>%6MWV z@zS!p@+Y1i1b^QuuEF*13CuB zu69dve5k7&Wgb+^s|UB08Dr3u`h@yM0NTj4h7MnHo-4@xmyr7(*4$rpPwsCDZ@2be zRz9V^GnV;;?^Lk%ynzq&K(Aix`mWmW`^152Hoy$CTYVehpD-S1-W^#k#{0^L`V6CN+E z!w+xte;2vu4AmVNEFUOBmrBL>6MK@!O2*N|2=d|Y;oN&A&qv=qKn73lDD zI(+oJAdgv>Yr}8(&@ZuAZE%XUXmX(U!N+Z_sjL<1vjy1R+1IeHt`79fnYdOL{$ci7 z%3f0A*;Zt@ED&Gjm|OFTYBDe%bbo*xXAQsFz+Q`fVBH!N2)kaxN8P$c>sp~QXnv>b zwq=W3&Mtmih7xkR$YA)1Yi?avHNR6C99!u6fh=cL|KQ&PwF!n@ud^n(HNIImHD!h87!i*t?G|p0o+eelJ?B@A64_9%SBhNaJ64EvKgD&%LjLCYnNfc; znj?%*p@*?dq#NqcQFmmX($wms@CSAr9#>hUR^=I+=0B)vvGX%T&#h$kmX*s=^M2E!@N9#m?LhMvz}YB+kd zG~mbP|D(;{s_#;hsKK9lbVK&Lo734x7SIFJ9V_}2$@q?zm^7?*XH94w5Qae{7zOMUF z^?%F%)c1Y)Q?Iy?I>knw*8gYW#ok|2gdS=YYZLiD=CW|Nj;n^x!=S#iJ#`~Ld79+xXpVmUK^B(xO_vO!btA9y7w3L3-0j-y4 z?M-V{%z;JI`bk7yFDcP}OcCd*{Q9S5$iGA7*E1@tfkyjAi!;wP^O71cZ^Ep)qrQ)N z#wqw0_HS;T7x3y|`P==i3hEwK%|>fZ)c&@kgKO1~5<5xBSk?iZV?KI6&i72H6S9A* z=U(*e)EqEs?Oc04)V-~K5AUmh|62H4*`UAtItO$O(q5?6jj+K^oD!04r=6#dsxp?~}{`?&sXn#q2 zGuY~7>O2=!u@@Kfu7q=W*4egu@qPMRM>(eyYyaIE<|j%d=iWNdGsx%c!902v#ngNg z@#U-O_4xN$s_9?(`{>{>7~-6FgWpBpqXb`Ydc3OFL#&I}Irse9F_8R@4zSS*Y*o*B zXL?6*Aw!AfkNCgcr#*yj&p3ZDe2y>v$>FUdKIy_2N~}6AbHc7gA3`6$g@1o|dE>vz z4pl(j9;kyMsjaw}lO?(?Xg%4k!5%^t#@5n=WVc&JRa+XT$~#@rldvN3S1rEpU$;XgxVny7mki3 z-Hh|jUCHrUXuLr!)`w>wgO0N%KTB-1di>cj(x3Bav`7v z3G7EIbU$z>`Nad7Rk_&OT-W{;qg)-GXV-aJT#(ozdmnA~Rq3GQ_3mby(>q6Ocb-RgTUhTN)))x>m&eD;$J5Bg zo&DhY36Yg=J=$Z>t}RJ>o|@hAcwWzN#r(WJ52^g$lh^!63@hh+dR$&_dEGu&^CR*< z!oFqSqO@>xZ*nC2oiOd0eS*F^IL~W-rsrO`J`ej{=ou_q^_(<$&-3f^J z&L^MSYWIe{&pYq&9eGaArA~*kA + + + + StandaloneApp + + + + + + + + diff --git a/projects/standalone-app/src/main.ts b/projects/standalone-app/src/main.ts new file mode 100644 index 0000000000..ada89106ee --- /dev/null +++ b/projects/standalone-app/src/main.ts @@ -0,0 +1,32 @@ +import { enableProdMode, importProvidersFrom } from '@angular/core'; +import { bootstrapApplication } from '@angular/platform-browser'; +import { RouterModule } from '@angular/router'; +import { provideStore } from '@ngrx/store'; +import { StoreDevtoolsModule } from '@ngrx/store-devtools'; + +import { AppComponent } from './app/app.component'; + +import { environment } from './environments/environment'; + +if (environment.production) { + enableProdMode(); +} + +bootstrapApplication(AppComponent, { + providers: [ + provideStore({}), + importProvidersFrom( + RouterModule.forRoot( + [ + { + path: 'feature', + loadChildren: () => + import('./app/lazy/feature.routes').then((m) => m.routes), + }, + ], + { initialNavigation: 'enabledBlocking' } + ), + StoreDevtoolsModule.instrument() + ), + ], +}); diff --git a/projects/standalone-app/src/polyfills.ts b/projects/standalone-app/src/polyfills.ts new file mode 100644 index 0000000000..e4555ed11f --- /dev/null +++ b/projects/standalone-app/src/polyfills.ts @@ -0,0 +1,52 @@ +/** + * This file includes polyfills needed by Angular and is loaded before the app. + * You can add your own extra polyfills to this file. + * + * This file is divided into 2 sections: + * 1. Browser polyfills. These are applied before loading ZoneJS and are sorted by browsers. + * 2. Application imports. Files imported after ZoneJS that should be loaded before your main + * file. + * + * The current setup is for so-called "evergreen" browsers; the last versions of browsers that + * automatically update themselves. This includes recent versions of Safari, Chrome (including + * Opera), Edge on the desktop, and iOS and Chrome on mobile. + * + * Learn more in https://angular.io/guide/browser-support + */ + +/*************************************************************************************************** + * BROWSER POLYFILLS + */ + +/** + * By default, zone.js will patch all possible macroTask and DomEvents + * user can disable parts of macroTask/DomEvents patch by setting following flags + * because those flags need to be set before `zone.js` being loaded, and webpack + * will put import in the top of bundle, so user need to create a separate file + * in this directory (for example: zone-flags.ts), and put the following flags + * into that file, and then add the following code before importing zone.js. + * import './zone-flags'; + * + * The flags allowed in zone-flags.ts are listed here. + * + * The following flags will work for all browsers. + * + * (window as any).__Zone_disable_requestAnimationFrame = true; // disable patch requestAnimationFrame + * (window as any).__Zone_disable_on_property = true; // disable patch onProperty such as onclick + * (window as any).__zone_symbol__UNPATCHED_EVENTS = ['scroll', 'mousemove']; // disable patch specified eventNames + * + * in IE/Edge developer tools, the addEventListener will also be wrapped by zone.js + * with the following flag, it will bypass `zone.js` patch for IE/Edge + * + * (window as any).__Zone_enable_cross_context_check = true; + * + */ + +/*************************************************************************************************** + * Zone JS is required by default for Angular itself. + */ +import 'zone.js'; // Included with Angular CLI. + +/*************************************************************************************************** + * APPLICATION IMPORTS + */ diff --git a/projects/standalone-app/src/styles.css b/projects/standalone-app/src/styles.css new file mode 100644 index 0000000000..90d4ee0072 --- /dev/null +++ b/projects/standalone-app/src/styles.css @@ -0,0 +1 @@ +/* You can add global styles to this file, and also import other style files */ diff --git a/projects/standalone-app/src/test-setup.ts b/projects/standalone-app/src/test-setup.ts new file mode 100644 index 0000000000..1100b3e8a6 --- /dev/null +++ b/projects/standalone-app/src/test-setup.ts @@ -0,0 +1 @@ +import 'jest-preset-angular/setup-jest'; diff --git a/projects/standalone-app/tsconfig.app.json b/projects/standalone-app/tsconfig.app.json new file mode 100644 index 0000000000..9f439121f1 --- /dev/null +++ b/projects/standalone-app/tsconfig.app.json @@ -0,0 +1,11 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "outDir": "../../dist/out-tsc", + "types": [], + "target": "ES2017" + }, + "files": ["src/main.ts", "src/polyfills.ts"], + "include": ["src/**/*.d.ts"], + "exclude": ["**/*.test.ts", "**/*.spec.ts"] +} diff --git a/projects/standalone-app/tsconfig.editor.json b/projects/standalone-app/tsconfig.editor.json new file mode 100644 index 0000000000..0f9036b03d --- /dev/null +++ b/projects/standalone-app/tsconfig.editor.json @@ -0,0 +1,7 @@ +{ + "extends": "./tsconfig.json", + "include": ["**/*.ts"], + "compilerOptions": { + "types": [] + } +} diff --git a/projects/standalone-app/tsconfig.json b/projects/standalone-app/tsconfig.json new file mode 100644 index 0000000000..46c5fbe7c5 --- /dev/null +++ b/projects/standalone-app/tsconfig.json @@ -0,0 +1,30 @@ +{ + "extends": "../../tsconfig.json", + "files": [], + "include": [], + "references": [ + { + "path": "./tsconfig.app.json" + }, + { + "path": "./tsconfig.spec.json" + }, + { + "path": "./tsconfig.editor.json" + } + ], + "compilerOptions": { + "lib": ["es2017", "dom"], + "forceConsistentCasingInFileNames": true, + "strict": false, + "noImplicitOverride": true, + "noPropertyAccessFromIndexSignature": true, + "noImplicitReturns": true, + "noFallthroughCasesInSwitch": true + }, + "angularCompilerOptions": { + "strictInjectionParameters": true, + "strictInputAccessModifiers": true, + "strictTemplates": true + } +} diff --git a/projects/standalone-app/tsconfig.spec.json b/projects/standalone-app/tsconfig.spec.json new file mode 100644 index 0000000000..c5db02778f --- /dev/null +++ b/projects/standalone-app/tsconfig.spec.json @@ -0,0 +1,10 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "outDir": "../../dist/out-tsc", + "module": "commonjs", + "types": ["jest", "node"] + }, + "files": ["src/test-setup.ts"], + "include": ["jest.config.ts", "**/*.test.ts", "**/*.spec.ts", "**/*.d.ts"] +} diff --git a/yarn.lock b/yarn.lock index 9ce0dfd390..00e0e5dadf 100644 --- a/yarn.lock +++ b/yarn.lock @@ -284,6 +284,11 @@ dependencies: tslib "^2.3.0" +"@angular/language-service@~13.3.0": + version "13.3.11" + resolved "https://registry.yarnpkg.com/@angular/language-service/-/language-service-13.3.11.tgz#4ae693bb4b15dc1c20eb4411874357c27cdb39a4" + integrity sha512-EDw8L0RKrRYUYWB2P0xS1WRazYvv5gOguX+IwPZlCpR95QLQPTTpmNaqvnYjmFlvQjGHJYc8wqtJJIIMiL6FSA== + "@angular/material@14.0.0-rc.0": version "14.0.0-rc.0" resolved "https://registry.yarnpkg.com/@angular/material/-/material-14.0.0-rc.0.tgz#9f5b3aa6d5f27dbe57c5968dad7e7dfedf05d347" From b78f5eb7a97cda18b4f0d60eeec1a04df8ebcc7a Mon Sep 17 00:00:00 2001 From: Brandon Roberts Date: Tue, 16 Aug 2022 16:53:43 -0500 Subject: [PATCH 3/7] chore: fixes for test failures --- projects/standalone-app-e2e/src/integration/app.spec.ts | 2 +- projects/standalone-app/src/app/app.component.spec.ts | 6 +++--- projects/standalone-app/src/app/app.component.ts | 2 +- projects/standalone-app/src/app/lazy/feature.component.ts | 6 +++--- 4 files changed, 8 insertions(+), 8 deletions(-) diff --git a/projects/standalone-app-e2e/src/integration/app.spec.ts b/projects/standalone-app-e2e/src/integration/app.spec.ts index 0eeeb052a0..4deb28f8fa 100644 --- a/projects/standalone-app-e2e/src/integration/app.spec.ts +++ b/projects/standalone-app-e2e/src/integration/app.spec.ts @@ -8,6 +8,6 @@ describe('standalone-app', () => { cy.login('my-email@something.com', 'myPassword'); // Function helper example, see `../support/app.po.ts` file - getGreeting().contains('Welcome standalone-app'); + getGreeting().contains('Welcome ngrx-standalone-app'); }); }); diff --git a/projects/standalone-app/src/app/app.component.spec.ts b/projects/standalone-app/src/app/app.component.spec.ts index c454a5e18a..460f3f29fe 100644 --- a/projects/standalone-app/src/app/app.component.spec.ts +++ b/projects/standalone-app/src/app/app.component.spec.ts @@ -15,10 +15,10 @@ describe('AppComponent', () => { expect(app).toBeTruthy(); }); - it(`should have as title 'standalone-app'`, () => { + it(`should have as title 'ngrx-standalone-app'`, () => { const fixture = TestBed.createComponent(AppComponent); const app = fixture.componentInstance; - expect(app.title).toEqual('standalone-app'); + expect(app.title).toEqual('ngrx-standalone-app'); }); it('should render title', () => { @@ -26,7 +26,7 @@ describe('AppComponent', () => { fixture.detectChanges(); const compiled = fixture.nativeElement as HTMLElement; expect(compiled.querySelector('h1')?.textContent).toContain( - 'Welcome standalone-app' + 'Welcome ngrx-standalone-app' ); }); }); diff --git a/projects/standalone-app/src/app/app.component.ts b/projects/standalone-app/src/app/app.component.ts index 81ccf55e93..3e99eb99d7 100644 --- a/projects/standalone-app/src/app/app.component.ts +++ b/projects/standalone-app/src/app/app.component.ts @@ -6,7 +6,7 @@ import { RouterModule } from '@angular/router'; standalone: true, imports: [RouterModule], template: ` - Welcome {{ title }} +

Welcome {{ title }}

Load Feature diff --git a/projects/standalone-app/src/app/lazy/feature.component.ts b/projects/standalone-app/src/app/lazy/feature.component.ts index 64f95b9e50..cbd714cc25 100644 --- a/projects/standalone-app/src/app/lazy/feature.component.ts +++ b/projects/standalone-app/src/app/lazy/feature.component.ts @@ -1,10 +1,10 @@ import { CommonModule } from '@angular/common'; -import { Component } from '@angular/core'; +import { Component, OnInit } from '@angular/core'; import { Store } from '@ngrx/store'; import { FeatureActions, feature } from './feature.state'; @Component({ - selector: 'app-feature', + selector: 'ngrx-feature', standalone: true, imports: [CommonModule], template: ` @@ -13,7 +13,7 @@ import { FeatureActions, feature } from './feature.state'; Feature State: {{ feature$ | async | json }} `, }) -export class FeatureComponent { +export class FeatureComponent implements OnInit { feature$ = this.store.select(feature.selectFeatureState); constructor(private store: Store) {} From ca02fe32993b9cd27786f40cf5dc711c8476e14c Mon Sep 17 00:00:00 2001 From: Brandon Roberts Date: Tue, 16 Aug 2022 18:49:44 -0500 Subject: [PATCH 4/7] chore: more test fixes --- .circleci/config.yml | 2 +- modules/store/spec/store.spec.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index ce1b0fecec..71ec55a611 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -172,7 +172,7 @@ jobs: - write_master_hash - run: name: Run Affected E2E Tests - command: yarn nx affected --target=e2e --base=$(cat ~/project/master.txt) --head=$CIRCLE_SHA1 --parallel --exclude=docs-app + command: yarn nx affected --target=e2e --base=$(cat ~/project/master.txt) --head=$CIRCLE_SHA1 --parallel=1 --exclude=docs-app deploy: <<: *run_in_node diff --git a/modules/store/spec/store.spec.ts b/modules/store/spec/store.spec.ts index aededbfe64..ee96314417 100644 --- a/modules/store/spec/store.spec.ts +++ b/modules/store/spec/store.spec.ts @@ -12,7 +12,7 @@ import { ActionReducer, Action, } from '../'; -import { StoreConfig } from '../src/store_module'; +import { StoreConfig } from '../src/store_config'; import { combineReducers } from '../src/utils'; import { counterReducer, From 6a9a2bdf405952fc16f4798c2e5cdf2f504fc0be Mon Sep 17 00:00:00 2001 From: Brandon Roberts Date: Thu, 18 Aug 2022 07:29:49 -0500 Subject: [PATCH 5/7] chore: review fixes --- modules/store/src/index.ts | 6 ++- modules/store/src/provide_store.ts | 58 +++++++++++++++++------------ modules/store/src/store_config.ts | 2 +- projects/standalone-app/src/main.ts | 2 +- 4 files changed, 41 insertions(+), 27 deletions(-) diff --git a/modules/store/src/index.ts b/modules/store/src/index.ts index b1166e17de..e35515dcfa 100644 --- a/modules/store/src/index.ts +++ b/modules/store/src/index.ts @@ -59,5 +59,9 @@ export { StoreFeatureModule, } from './store_module'; export { RootStoreConfig, StoreConfig, FeatureSlice } from './store_config'; -export { provideStore, provideState } from './provide_store'; +export { + provideStore, + provideState, + FEATURE_STATE_PROVIDER, +} from './provide_store'; export { ReducerTypes, on, createReducer } from './reducer_creator'; diff --git a/modules/store/src/provide_store.ts b/modules/store/src/provide_store.ts index 63f17bf93a..0012d0e401 100644 --- a/modules/store/src/provide_store.ts +++ b/modules/store/src/provide_store.ts @@ -65,37 +65,47 @@ import { _provideForRootGuard, } from './store_config'; +/** + * InjectionToken that registers feature states. + * Mainly used to provide a hook that can be injected + * to ensure feature state is loaded before something + * that depends on it. + */ +export const FEATURE_STATE_PROVIDER = new InjectionToken('NgRx Feature State', { + factory() { + const features = inject[]>(_STORE_FEATURES); + const featureReducers = inject[]>(FEATURE_REDUCERS); + const reducerManager = inject(ReducerManager); + inject(_ACTION_TYPE_UNIQUENESS_CHECK, InjectFlags.Optional); + + const feats = features.map((feature, index) => { + const featureReducerCollection = featureReducers.shift(); + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + const reducers = featureReducerCollection! /*TODO(#823)*/[index]; + + return { + ...feature, + reducers, + initialState: _initialStateFactory(feature.initialState), + }; + }); + + reducerManager.addFeatures(feats); + }, +}); + /** * Environment Initializer used in the feature * providers to register state features */ const ENVIRONMENT_STATE_PROVIDER: Provider[] = [ + { provide: FEATURE_STATE_PROVIDER, deps: [], useValue: true }, { provide: ENVIRONMENT_INITIALIZER, multi: true, deps: [], useFactory() { - return () => { - const features = inject[]>(_STORE_FEATURES); - const featureReducers = - inject[]>(FEATURE_REDUCERS); - const reducerManager = inject(ReducerManager); - inject(_ACTION_TYPE_UNIQUENESS_CHECK, InjectFlags.Optional); - - const feats = features.map((feature, index) => { - const featureReducerCollection = featureReducers.shift(); - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - const reducers = featureReducerCollection! /*TODO(#823)*/[index]; - - return { - ...feature, - reducers, - initialState: _initialStateFactory(feature.initialState), - }; - }); - - reducerManager.addFeatures(feats); - }; + return () => inject(FEATURE_STATE_PROVIDER); }, }, ]; @@ -310,18 +320,18 @@ const ENVIRONMENT_STORE_PROVIDER = [ * * ```ts * bootstrapApplication(AppComponent, { - * providers: [provideStore({})], + * providers: [provideStore()], * }); * ``` */ export function provideStore( - reducers: ActionReducerMap | InjectionToken>, + reducers?: ActionReducerMap | InjectionToken>, config?: RootStoreConfig ): ImportedNgModuleProviders; export function provideStore( reducers: | ActionReducerMap - | InjectionToken>, + | InjectionToken> = {}, config: RootStoreConfig = {} ): ImportedNgModuleProviders { return { diff --git a/modules/store/src/store_config.ts b/modules/store/src/store_config.ts index 7d16429362..369e441f2f 100644 --- a/modules/store/src/store_config.ts +++ b/modules/store/src/store_config.ts @@ -101,7 +101,7 @@ export function _concatMetaReducers( export function _provideForRootGuard(store: Store): any { if (store) { throw new TypeError( - `StoreModule.forRoot() called twice. Feature modules should use StoreModule.forFeature() instead.` + `The root Store has been provided more than once. Feature modules should provide feature states instead.` ); } return 'guarded'; diff --git a/projects/standalone-app/src/main.ts b/projects/standalone-app/src/main.ts index ada89106ee..697146e9c4 100644 --- a/projects/standalone-app/src/main.ts +++ b/projects/standalone-app/src/main.ts @@ -14,7 +14,7 @@ if (environment.production) { bootstrapApplication(AppComponent, { providers: [ - provideStore({}), + provideStore(), importProvidersFrom( RouterModule.forRoot( [ From a54762e4cdcea3a28ae0094232b947d5311991f4 Mon Sep 17 00:00:00 2001 From: Brandon Roberts Date: Mon, 22 Aug 2022 12:46:56 -0500 Subject: [PATCH 6/7] fix(store): add store/feature tokens and refactor factories --- modules/store/spec/integration.spec.ts | 2 +- modules/store/src/index.ts | 8 +- modules/store/src/provide_store.ts | 249 +++++++++++++------------ modules/store/src/tokens.ts | 20 ++ 4 files changed, 149 insertions(+), 130 deletions(-) diff --git a/modules/store/spec/integration.spec.ts b/modules/store/spec/integration.spec.ts index 9734a2c195..b57ee2541d 100644 --- a/modules/store/spec/integration.spec.ts +++ b/modules/store/spec/integration.spec.ts @@ -483,7 +483,7 @@ describe('ngRx Integration spec', () => { router.navigateByUrl('/feature-path').catch((err: TypeError) => { expect(err.message).toBe( - 'StoreModule.forRoot() called twice. Feature modules should use StoreModule.forFeature() instead.' + 'The root Store has been provided more than once. Feature modules should provide feature states instead.' ); done(); }); diff --git a/modules/store/src/index.ts b/modules/store/src/index.ts index e35515dcfa..dd0ef5d2c3 100644 --- a/modules/store/src/index.ts +++ b/modules/store/src/index.ts @@ -52,6 +52,8 @@ export { USER_PROVIDED_META_REDUCERS, USER_RUNTIME_CHECKS, ACTIVE_RUNTIME_CHECKS, + FEATURE_STATE_PROVIDER, + ROOT_STORE_PROVIDER, } from './tokens'; export { StoreModule, @@ -59,9 +61,5 @@ export { StoreFeatureModule, } from './store_module'; export { RootStoreConfig, StoreConfig, FeatureSlice } from './store_config'; -export { - provideStore, - provideState, - FEATURE_STATE_PROVIDER, -} from './provide_store'; +export { provideStore, provideState } from './provide_store'; export { ReducerTypes, on, createReducer } from './reducer_creator'; diff --git a/modules/store/src/provide_store.ts b/modules/store/src/provide_store.ts index 0012d0e401..e612c0332b 100644 --- a/modules/store/src/provide_store.ts +++ b/modules/store/src/provide_store.ts @@ -36,6 +36,8 @@ import { _RESOLVED_META_REDUCERS, _ROOT_STORE_GUARD, _ACTION_TYPE_UNIQUENESS_CHECK, + ROOT_STORE_PROVIDER, + FEATURE_STATE_PROVIDER, } from './tokens'; import { ACTIONS_SUBJECT_PROVIDERS, ActionsSubject } from './actions_subject'; import { @@ -65,121 +67,6 @@ import { _provideForRootGuard, } from './store_config'; -/** - * InjectionToken that registers feature states. - * Mainly used to provide a hook that can be injected - * to ensure feature state is loaded before something - * that depends on it. - */ -export const FEATURE_STATE_PROVIDER = new InjectionToken('NgRx Feature State', { - factory() { - const features = inject[]>(_STORE_FEATURES); - const featureReducers = inject[]>(FEATURE_REDUCERS); - const reducerManager = inject(ReducerManager); - inject(_ACTION_TYPE_UNIQUENESS_CHECK, InjectFlags.Optional); - - const feats = features.map((feature, index) => { - const featureReducerCollection = featureReducers.shift(); - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - const reducers = featureReducerCollection! /*TODO(#823)*/[index]; - - return { - ...feature, - reducers, - initialState: _initialStateFactory(feature.initialState), - }; - }); - - reducerManager.addFeatures(feats); - }, -}); - -/** - * Environment Initializer used in the feature - * providers to register state features - */ -const ENVIRONMENT_STATE_PROVIDER: Provider[] = [ - { provide: FEATURE_STATE_PROVIDER, deps: [], useValue: true }, - { - provide: ENVIRONMENT_INITIALIZER, - multi: true, - deps: [], - useFactory() { - return () => inject(FEATURE_STATE_PROVIDER); - }, - }, -]; - -export function _provideState( - featureNameOrSlice: string | FeatureSlice, - reducers?: - | ActionReducerMap - | InjectionToken> - | ActionReducer - | InjectionToken>, - config: StoreConfig | InjectionToken> = {} -) { - return [ - { - provide: _FEATURE_CONFIGS, - multi: true, - useValue: featureNameOrSlice instanceof Object ? {} : config, - }, - { - provide: STORE_FEATURES, - multi: true, - useValue: { - key: - featureNameOrSlice instanceof Object - ? featureNameOrSlice.name - : featureNameOrSlice, - reducerFactory: - !(config instanceof InjectionToken) && config.reducerFactory - ? config.reducerFactory - : combineReducers, - metaReducers: - !(config instanceof InjectionToken) && config.metaReducers - ? config.metaReducers - : [], - initialState: - !(config instanceof InjectionToken) && config.initialState - ? config.initialState - : undefined, - }, - }, - { - provide: _STORE_FEATURES, - deps: [Injector, _FEATURE_CONFIGS, STORE_FEATURES], - useFactory: _createFeatureStore, - }, - { - provide: _FEATURE_REDUCERS, - multi: true, - useValue: - featureNameOrSlice instanceof Object - ? featureNameOrSlice.reducer - : reducers, - }, - { - provide: _FEATURE_REDUCERS_TOKEN, - multi: true, - useExisting: - reducers instanceof InjectionToken ? reducers : _FEATURE_REDUCERS, - }, - { - provide: FEATURE_REDUCERS, - multi: true, - deps: [ - Injector, - _FEATURE_REDUCERS, - [new Inject(_FEATURE_REDUCERS_TOKEN)], - ], - useFactory: _createFeatureReducers, - }, - checkForActionTypeUniqueness(), - ]; -} - /** * Provides additional slices of state in the Store. * These providers cannot be used at the component level. @@ -288,23 +175,26 @@ export function _provideStore( ]; } +function rootStoreProviderFactory(): void { + inject(ActionsSubject); + inject(ReducerObservable); + inject(ScannedActionsSubject); + inject(Store); + inject(_ROOT_STORE_GUARD, InjectFlags.Optional); + inject(_ACTION_TYPE_UNIQUENESS_CHECK, InjectFlags.Optional); +} + /** * Environment Initializer used in the root * providers to initialize the Store */ -const ENVIRONMENT_STORE_PROVIDER = [ +const ENVIRONMENT_STORE_PROVIDER: Provider[] = [ + { provide: ROOT_STORE_PROVIDER, useFactory: rootStoreProviderFactory }, { provide: ENVIRONMENT_INITIALIZER, multi: true, useFactory() { - return () => { - inject(ActionsSubject); - inject(ReducerObservable); - inject(ScannedActionsSubject); - inject(Store); - inject(_ROOT_STORE_GUARD, InjectFlags.Optional); - inject(_ACTION_TYPE_UNIQUENESS_CHECK, InjectFlags.Optional); - }; + return () => inject(ROOT_STORE_PROVIDER); }, }, ]; @@ -341,3 +231,114 @@ export function provideStore( ], }; } + +function featureStateProviderFactory() { + inject(ROOT_STORE_PROVIDER); + const features = inject[]>(_STORE_FEATURES); + const featureReducers = inject[]>(FEATURE_REDUCERS); + const reducerManager = inject(ReducerManager); + inject(_ACTION_TYPE_UNIQUENESS_CHECK, InjectFlags.Optional); + + const feats = features.map((feature, index) => { + const featureReducerCollection = featureReducers.shift(); + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + const reducers = featureReducerCollection! /*TODO(#823)*/[index]; + + return { + ...feature, + reducers, + initialState: _initialStateFactory(feature.initialState), + }; + }); + + reducerManager.addFeatures(feats); +} + +/** + * Environment Initializer used in the feature + * providers to register state features + */ +const ENVIRONMENT_STATE_PROVIDER: Provider[] = [ + { + provide: FEATURE_STATE_PROVIDER, + useFactory: featureStateProviderFactory, + }, + { + provide: ENVIRONMENT_INITIALIZER, + multi: true, + deps: [], + useFactory() { + return () => inject(FEATURE_STATE_PROVIDER); + }, + }, +]; + +export function _provideState( + featureNameOrSlice: string | FeatureSlice, + reducers?: + | ActionReducerMap + | InjectionToken> + | ActionReducer + | InjectionToken>, + config: StoreConfig | InjectionToken> = {} +) { + return [ + { + provide: _FEATURE_CONFIGS, + multi: true, + useValue: featureNameOrSlice instanceof Object ? {} : config, + }, + { + provide: STORE_FEATURES, + multi: true, + useValue: { + key: + featureNameOrSlice instanceof Object + ? featureNameOrSlice.name + : featureNameOrSlice, + reducerFactory: + !(config instanceof InjectionToken) && config.reducerFactory + ? config.reducerFactory + : combineReducers, + metaReducers: + !(config instanceof InjectionToken) && config.metaReducers + ? config.metaReducers + : [], + initialState: + !(config instanceof InjectionToken) && config.initialState + ? config.initialState + : undefined, + }, + }, + { + provide: _STORE_FEATURES, + deps: [Injector, _FEATURE_CONFIGS, STORE_FEATURES], + useFactory: _createFeatureStore, + }, + { + provide: _FEATURE_REDUCERS, + multi: true, + useValue: + featureNameOrSlice instanceof Object + ? featureNameOrSlice.reducer + : reducers, + }, + { + provide: _FEATURE_REDUCERS_TOKEN, + multi: true, + useExisting: + reducers instanceof InjectionToken ? reducers : _FEATURE_REDUCERS, + }, + { + provide: FEATURE_REDUCERS, + multi: true, + deps: [ + Injector, + _FEATURE_REDUCERS, + [new Inject(_FEATURE_REDUCERS_TOKEN)], + ], + useFactory: _createFeatureReducers, + }, + checkForActionTypeUniqueness(), + ]; +} diff --git a/modules/store/src/tokens.ts b/modules/store/src/tokens.ts index e4e73ae7ba..e1b8210b43 100644 --- a/modules/store/src/tokens.ts +++ b/modules/store/src/tokens.ts @@ -90,3 +90,23 @@ export const ACTIVE_RUNTIME_CHECKS = new InjectionToken( export const _ACTION_TYPE_UNIQUENESS_CHECK = new InjectionToken( '@ngrx/store Check if Action types are unique' ); + +/** + * InjectionToken that registers the global Store. + * Mainly used to provide a hook that can be injected + * to ensure the root state is loaded before something + * that depends on it. + */ +export const ROOT_STORE_PROVIDER = new InjectionToken( + '@ngrx/store Root Store Provider' +); + +/** + * InjectionToken that registers feature states. + * Mainly used to provide a hook that can be injected + * to ensure feature state is loaded before something + * that depends on it. + */ +export const FEATURE_STATE_PROVIDER = new InjectionToken( + '@ngrx/store Feature State Provider' +); From a7cb25c9b1463c8605da893b9b28b6070fb5dc8a Mon Sep 17 00:00:00 2001 From: Brandon Roberts Date: Mon, 22 Aug 2022 13:35:13 -0500 Subject: [PATCH 7/7] feat(store): add EnvironmentProviders as alias for ImportedNgModuleProviders --- modules/store/src/index.ts | 1 + modules/store/src/models.ts | 8 ++++++++ modules/store/src/provide_store.ts | 14 +++++++------- 3 files changed, 16 insertions(+), 7 deletions(-) diff --git a/modules/store/src/index.ts b/modules/store/src/index.ts index dd0ef5d2c3..f5dd56d364 100644 --- a/modules/store/src/index.ts +++ b/modules/store/src/index.ts @@ -13,6 +13,7 @@ export { SelectorWithProps, RuntimeChecks, FunctionWithParametersType, + EnvironmentProviders, } from './models'; export { createAction, props, union } from './action_creator'; export { createActionGroup, emptyProps } from './action_group_creator'; diff --git a/modules/store/src/models.ts b/modules/store/src/models.ts index a56bccbf02..0a1134ab3e 100644 --- a/modules/store/src/models.ts +++ b/modules/store/src/models.ts @@ -1,3 +1,5 @@ +import { ImportedNgModuleProviders } from '@angular/core'; + export interface Action { type: string; } @@ -173,3 +175,9 @@ export interface RuntimeChecks { */ strictActionTypeUniqueness?: boolean; } + +/** An alias type of ImportedNgModuleProviders + * that better describes where the providers + * are allowed to be registered. + */ +export type EnvironmentProviders = ImportedNgModuleProviders; diff --git a/modules/store/src/provide_store.ts b/modules/store/src/provide_store.ts index e612c0332b..84af0d5960 100644 --- a/modules/store/src/provide_store.ts +++ b/modules/store/src/provide_store.ts @@ -4,7 +4,6 @@ import { Injector, Optional, SkipSelf, - ImportedNgModuleProviders, ENVIRONMENT_INITIALIZER, inject, InjectFlags, @@ -15,6 +14,7 @@ import { ActionReducer, ActionReducerMap, StoreFeature, + EnvironmentProviders, } from './models'; import { combineReducers, createReducerFactory } from './utils'; import { @@ -92,15 +92,15 @@ export function provideState( featureName: string, reducers: ActionReducerMap | InjectionToken>, config?: StoreConfig | InjectionToken> -): ImportedNgModuleProviders; +): EnvironmentProviders; export function provideState( featureName: string, reducer: ActionReducer | InjectionToken>, config?: StoreConfig | InjectionToken> -): ImportedNgModuleProviders; +): EnvironmentProviders; export function provideState( slice: FeatureSlice -): ImportedNgModuleProviders; +): EnvironmentProviders; export function provideState( featureNameOrSlice: string | FeatureSlice, reducers?: @@ -109,7 +109,7 @@ export function provideState( | ActionReducer | InjectionToken>, config: StoreConfig | InjectionToken> = {} -): ImportedNgModuleProviders { +): EnvironmentProviders { return { ɵproviders: [ ..._provideState(featureNameOrSlice, reducers, config), @@ -217,13 +217,13 @@ const ENVIRONMENT_STORE_PROVIDER: Provider[] = [ export function provideStore( reducers?: ActionReducerMap | InjectionToken>, config?: RootStoreConfig -): ImportedNgModuleProviders; +): EnvironmentProviders; export function provideStore( reducers: | ActionReducerMap | InjectionToken> = {}, config: RootStoreConfig = {} -): ImportedNgModuleProviders { +): EnvironmentProviders { return { ɵproviders: [ ..._provideStore(reducers, config),