remove redux. you don't need it cause you're pretty much just using RXJS.

This commit is contained in:
Jason Wall 2024-03-09 13:05:45 -05:00
parent fe382a4113
commit f35b5d4902
6 changed files with 137 additions and 1325 deletions

1187
src/package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -32,13 +32,11 @@
"@capacitor/ios": "^5.7.0",
"@codetrix-studio/capacitor-google-auth": "^3.4.0-rc.0",
"@ngx-pwa/local-storage": "^17.0.0",
"@reduxjs/toolkit": "^2.2.1",
"angular2-uuid": "^1.1.1",
"component": "^1.1.0",
"firebase": "^10.8.0",
"marked": "^9.0.0",
"ngx-markdown": "^17.1.1",
"redux": "^5.0.1",
"reselect": "^5.1.0",
"rxjs": "^7.8.1",
"tslib": "^2.6.2",

View File

@ -1,103 +1,6 @@
import { Store } from 'redux';
import { configureStore } from '@reduxjs/toolkit';
import { BehaviorSubject, Observable } from 'rxjs';
import { distinctUntilChanged, map } from 'rxjs/operators';
/**
* A base class from which to extend a service to provide predictable state to components. You should not extend this
* class directly; instead, use the {@link createStateService} function to create a base class specific to your service.
* @see {@link createStateService}
*/
class StateService<TState, TAction extends { type: string }> {
/** An observable that provides the entire state managed by the service. */
public readonly state$: Observable<TState>;
private readonly store: Store<TState, TAction>;
private readonly internalState$: BehaviorSubject<TState>;
protected constructor(reducer: (state: TState, action: TAction) => TState, initialState: TState) {
this.store = configureStore({
reducer: reducer,
preloadedState: initialState,
});
this.internalState$ = new BehaviorSubject<TState>(initialState as TState);
// BehaviorSubject.asObservable returns a new object, so hold onto it to avoid unnecessary allocations
this.state$ = this.internalState$.asObservable();
this.store.subscribe(() => this.internalState$.next(this.store.getState()));
}
/**
* Creates an observable that provides data derived from the state managed by the service.
* @param selector A selector that maps the state to the derived data.
*/
public select<TDerived>(selector: (state: TState) => TDerived): Observable<TDerived> {
return this.state$.pipe(map(selector), distinctUntilChanged());
}
/**
* Gets the current state managed by the service. **You should only use the current state to validate operations or
* help to construct actions to be dispatched.** Try not to expose any state retrieved using this method outside the
* derived service class.
*/
protected getState(): TState {
return this.internalState$.value;
}
/**
* Dispatches an action to the underlying Redux store.
* @param action The action to dispatch.
*/
protected dispatch(action: TAction) {
this.store.dispatch(action);
}
}
/**
* Creates a deeply-immutable type from the provided type. Objects' properties will be marked as `readonly`, array types
* will be replaced with {@link ReadonlyArray}, {@link Map} types will be replaced with {@link ReadonlyMap}, and
* {@link Set} types will be replaced with {@link ReadonlySet}.
*/
export type Immutable<T> = T extends undefined | null | boolean | string | number
? T
: T extends Array<infer U>
? ImmutableArray<U>
: T extends Map<infer K, infer V>
? ImmutableMap<K, V>
: T extends Set<infer M>
? ImmutableSet<M>
: { readonly [N in keyof T]: Immutable<T[N]> };
interface ImmutableArray<T> extends ReadonlyArray<Immutable<T>> {}
interface ImmutableMap<K, V> extends ReadonlyMap<Immutable<K>, Immutable<V>> {}
interface ImmutableSet<T> extends ReadonlySet<Immutable<T>> {}
// The below type definition is simpler, but it only works with TypeScript 3.7 and above. Swap this in when we upgrade!
// export type Immutable<T> = T extends undefined | null | boolean | string | number
// ? T
// : T extends Array<infer U>
// ? ReadonlyArray<Immutable<U>>
// : T extends Map<infer K, infer V>
// ? ReadonlyMap<Immutable<K>, Immutable<V>>
// : T extends Set<infer M>
// ? ReadonlySet<Immutable<M>>
// : { readonly [N in keyof T]: Immutable<T[N]> };
type IfEquals<X, Y, A = X, B = never> = (<T>() => T extends X ? 1 : 2) extends <T>() => T extends Y ? 1 : 2 ? A : B;
type IfImmutable<TState extends {}, TImmutable = TState, TMutable = never> = IfEquals<
TState,
{ readonly [K in keyof TState]: Immutable<TState[K]> },
TImmutable,
TMutable
>;
// eslint-disable-next-line
type YourStateTypeNeedsToBeImmutable<TState> = {};
/**
* Creates a base class from which to extend a service to provide predictable state to components.
*
@ -116,20 +19,75 @@ type YourStateTypeNeedsToBeImmutable<TState> = {};
* @param reducer A function that takes the previous state and the dispatched action and returns the new state.
* @param initialState The initial state of the service.
*/
export function createStateService<TState, TAction extends { type: string }>(
reducer: (state: TState, action: TAction) => TState,
initialState: TState
) {
const stateServiceClass = class extends StateService<TState, TAction> {
export function createReducingService<TState>(initialState: TState) {
const stateServiceClass = class extends ReducingService<TState> {
constructor() {
super(reducer, initialState);
super(initialState);
}
};
return stateServiceClass as IfImmutable<TState, typeof stateServiceClass, YourStateTypeNeedsToBeImmutable<TState>>;
}
export interface IStateAction<TState, TAction> {
type: TAction;
export interface IReducingAction<TState> {
handle: (state: TState) => TState;
}
/**
* Creates a deeply-immutable type from the provided type. Objects' properties will be marked as `readonly`, array types
* will be replaced with {@link ReadonlyArray}, {@link Map} types will be replaced with {@link ReadonlyMap}, and
* {@link Set} types will be replaced with {@link ReadonlySet}.
*/
export type Immutable<T> = T extends undefined | null | boolean | string | number
? T
: T extends Array<infer U>
? ReadonlyArray<Immutable<U>>
: T extends Map<infer K, infer V>
? ReadonlyMap<Immutable<K>, Immutable<V>>
: T extends Set<infer M>
? ReadonlySet<Immutable<M>>
: { readonly [N in keyof T]: Immutable<T[N]> };
type IfEquals<X, Y, A = X, B = never> = (<T>() => T extends X ? 1 : 2) extends <T>() => T extends Y ? 1 : 2 ? A : B;
type IfImmutable<TState extends {}, TImmutable = TState, TMutable = never> = IfEquals<
TState,
{ readonly [K in keyof TState]: Immutable<TState[K]> },
TImmutable,
TMutable
>;
// eslint-disable-next-line
type YourStateTypeNeedsToBeImmutable<TState> = {};
class ReducingService<TState> {
private internalState$: BehaviorSubject<TState>;
constructor(private initialState: TState) {
this.internalState$ = new BehaviorSubject(initialState);
}
// expose as observable.
public get state$() {
return this.internalState$.asObservable();
}
protected dispatch(action: IReducingAction<TState>) {
this.internalState$.next(action.handle(this.internalState$.value));
}
/**
* Gets the current state managed by the service. **You should only use the current state to validate operations or
* help to construct actions to be dispatched.** Try not to expose any state retrieved using this method outside the
* derived service class.
*/
protected getState(): TState {
return this.internalState$.value;
}
/**
* Creates an observable that provides data derived from the state managed by the service.
* @param selector A selector that maps the state to the derived data.
*/
public select<TDerived>(selector: (state: TState) => TDerived): Observable<TDerived> {
return this.internalState$.pipe(map(selector), distinctUntilChanged());
}
}

View File

@ -36,7 +36,7 @@ export class CardComponent extends SubscriberBase {
const attempt = () => {
const result = pending.copy();
if (!result && --remainingAttempts) {
setTimeout(attempt);
setTimeout(attempt, 10);
} else {
// Remember to destroy when you're done!
pending.destroy();

View File

@ -22,7 +22,6 @@ export class StrongsModalComponent {
public dialogRef: MatDialogRef<StrongsModalComponent>,
private appService: AppService
) {
console.log(cardItem);
this.strongsResult = cardItem.data as StrongsResult;
this.icon$ = appService.select((state) => state.settings.value.cardIcons.strongs);
}

View File

@ -1,20 +1,16 @@
import { AngularFireDatabase } from '@angular/fire/compat/database';
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { StorageMap } from '@ngx-pwa/local-storage';
import { UUID } from 'angular2-uuid';
import { HashTable } from '../common/hashtable';
import { MoveDirection } from '../common/move-direction';
import { IStateAction } from '../common/state-service';
import { IReducingAction, createReducingService } from '../common/state-service';
import { IStorable, Storable, StorableType } from '../common/storable';
import { mergeCardList } from '../common/card-operations';
import { updateInCardCache, removeFromCardCache, getFromCardCache } from '../common/card-cache-operations';
import { moveItem, moveItemUpOrDown } from '../common/array-operations';
import { Section, BibleReference, Overlap } from '../common/bible-reference';
import { createStateService } from '../common/state-service';
import { SavedPage } from '../models/page-state';
import { CardType, CardItem, DataReference } from '../models/card-state';
@ -88,7 +84,7 @@ const initialState: AppState = {
},
};
interface AppAction extends IStateAction<AppState, AppActions> {}
interface AppAction extends IReducingAction<AppState> {}
export function getNewestStorable<T>(candidate: IStorable<T>, incumbant: IStorable<T>): IStorable<T> {
// if the candidate is null, then return the state.
@ -105,19 +101,10 @@ export function getNewestStorable<T>(candidate: IStorable<T>, incumbant: IStorab
return incumbant;
}
function appReducer(state: AppState, action: IStateAction<AppState, AppActions>): AppState {
if (state === undefined || action.handle === undefined) {
return initialState;
}
return action.handle(state);
}
//#region Saved Pages
const savePageActionType = 'SAVE_PAGE';
export const savePageAction = (title: string): AppAction => {
return {
type: savePageActionType,
handle(state: AppState) {
const savedPages = new Storable([
...(state.savedPages ? state.savedPages.value : []),
@ -134,10 +121,8 @@ export const savePageAction = (title: string): AppAction => {
};
};
const updateCurrentPageActionType = 'UPDATE_CURRENT_PAGE';
export const updateCurrentPageAction = (): AppAction => {
return {
type: updateCurrentPageActionType,
handle(state: AppState) {
const current = {
id: state.currentSavedPage.id,
@ -161,10 +146,8 @@ export const updateCurrentPageAction = (): AppAction => {
};
};
const updateSavedPagesActionType = 'UPDATE_SAVED_PAGES';
export const updateSavedPagesAction = (oldSavedPages: IStorable<readonly SavedPage[]>): AppAction => {
return {
type: updateSavedPagesActionType,
handle(state: AppState) {
const newSavedPages = getNewestStorable(oldSavedPages, state.savedPages);
@ -192,10 +175,8 @@ export const updateSavedPagesAction = (oldSavedPages: IStorable<readonly SavedPa
};
};
const updateSavedPageActionType = 'UPDATE_SAVED_PAGES';
export const updateSavedPageAction = (savedPage: SavedPage): AppAction => {
return {
type: updateSavedPageActionType,
handle(state: AppState) {
const newSavedPages = new Storable<SavedPage[]>(
state.savedPages.value.map((o) => {
@ -212,10 +193,8 @@ export const updateSavedPageAction = (savedPage: SavedPage): AppAction => {
};
};
const removeSavedPageActionType = 'REMOVE_SAVED_PAGE';
export const removeSavedPageAction = (savedPage: SavedPage): AppAction => {
return {
type: removeSavedPageActionType,
handle(state: AppState) {
const savedPages = new Storable<SavedPage[]>(state.savedPages.value.filter((o) => o.id !== savedPage.id));
const item = getNewestStorable(savedPages, state.savedPages);
@ -229,10 +208,8 @@ export const removeSavedPageAction = (savedPage: SavedPage): AppAction => {
};
};
const moveSavedPageCardActionType = 'MOVE_SAVED_PAGE_CARD';
export const moveSavedPageCardAction = (oldSavedPage: SavedPage, fromIndex: number, toIndex: number): AppAction => {
return {
type: moveSavedPageCardActionType,
handle(state: AppState) {
const queries = moveItem(oldSavedPage.queries, fromIndex, toIndex);
const savedPage = {
@ -245,10 +222,8 @@ export const moveSavedPageCardAction = (oldSavedPage: SavedPage, fromIndex: numb
};
};
const addCardToSavedPageActionType = 'ADD_CARD_TO_SAVED_PAGE';
export const addCardToSavedPageAction = (card: CardItem, pageId: string): AppAction => {
return {
type: addCardToSavedPageActionType,
handle(state: AppState) {
const savedPages = new Storable([
...(state.savedPages ? state.savedPages.value : []).map((o) => {
@ -277,10 +252,8 @@ export const addCardToSavedPageAction = (card: CardItem, pageId: string): AppAct
//#region Cards
const addCardActionType = 'ADD_CARD';
export const addCardAction = (card: CardItem, nextToItem: CardItem): AppAction => {
return {
type: addCardActionType,
handle(state: AppState) {
let cards = [];
@ -313,10 +286,8 @@ export const addCardAction = (card: CardItem, nextToItem: CardItem): AppAction =
};
};
const updateCardActionType = 'UPDATE_CARD';
export const updateCardAction = (newCard: CardItem, oldCard: CardItem): AppAction => {
return {
type: updateCardActionType,
handle(state: AppState) {
return {
...state,
@ -334,10 +305,8 @@ export const updateCardAction = (newCard: CardItem, oldCard: CardItem): AppActio
};
};
const removeCardActionType = 'REMOVE_CARD';
export const removeCardAction = (card: CardItem): AppAction => {
return {
type: removeCardActionType,
handle(state: AppState) {
// potentially remove card from a saved page.
const currentSavedPage =
@ -371,10 +340,8 @@ export const removeCardAction = (card: CardItem): AppAction => {
};
};
const moveCardActionType = 'MOVE_CARD';
export const moveCardAction = (card: CardItem, direction: MoveDirection): AppAction => {
return {
type: moveCardActionType,
handle(state: AppState) {
const cards = moveItemUpOrDown(state.currentCards.value, card, direction);
@ -386,10 +353,8 @@ export const moveCardAction = (card: CardItem, direction: MoveDirection): AppAct
};
};
const updateCardsActionType = 'UPDATE_CARDS';
export const updateCardsAction = (cards: IStorable<CardItem[]>): AppAction => {
return {
type: savePageActionType,
handle(state: AppState) {
let cardCache = { ...state.cardCache };
for (const card of cards.value) {
@ -404,10 +369,8 @@ export const updateCardsAction = (cards: IStorable<CardItem[]>): AppAction => {
};
};
const clearCardsActionType = 'CLEAR_CARDS';
export const clearCardsAction = (): AppAction => {
return {
type: clearCardsActionType,
handle(state: AppState) {
return {
...state,
@ -421,10 +384,8 @@ export const clearCardsAction = (): AppAction => {
//#region General
const updateErrorActionType = 'UPDATE_ERROR';
export const updateErrorAction = (error: Error): AppAction => {
return {
type: updateErrorActionType,
handle(state: AppState) {
return {
...state,
@ -434,10 +395,8 @@ export const updateErrorAction = (error: Error): AppAction => {
};
};
const setUserActionType = 'SET_USER';
export const setUserAction = (user: User): AppAction => {
return {
type: setUserActionType,
handle(state: AppState) {
return {
...state,
@ -447,10 +406,8 @@ export const setUserAction = (user: User): AppAction => {
};
};
const updateAutoCompleteActionType = 'UPDATE_AUTOCOMPLETE';
export const updateAutoCompleteAction = (words: string[]): AppAction => {
return {
type: updateAutoCompleteActionType,
handle(state: AppState) {
return {
...state,
@ -464,10 +421,8 @@ export const updateAutoCompleteAction = (words: string[]): AppAction => {
//#region Settings
const updateSettingsActionType = 'UPDATE_SETTINGS';
export const updateSettingsAction = (settings: IStorable<Settings>): AppAction => {
return {
type: updateSettingsActionType,
handle(state: AppState) {
const item = getNewestStorable(settings, state.settings);
@ -479,10 +434,8 @@ export const updateSettingsAction = (settings: IStorable<Settings>): AppAction =
};
};
const updateCardMergeStrategyActionType = 'UPDATE_CARD_MERGE_STRATEGY';
export const updateCardMergeStrategyAction = (mergeStrategy: Overlap): AppAction => {
return {
type: updateCardMergeStrategyActionType,
handle(state: AppState) {
const settings = new Storable<Settings>({
...state.settings.value,
@ -496,10 +449,8 @@ export const updateCardMergeStrategyAction = (mergeStrategy: Overlap): AppAction
};
};
const updateCardFontSizeActionType = 'UPDATE_CARD_FONT_SIZE';
export const updateCardFontSizeAction = (cardFontSize: number): AppAction => {
return {
type: updateCardFontSizeActionType,
handle(state: AppState) {
const settings = new Storable<Settings>({
...state.settings.value,
@ -514,10 +465,8 @@ export const updateCardFontSizeAction = (cardFontSize: number): AppAction => {
};
};
const updateCardFontFamilyActionType = 'UPDATE_CARD_FONT_FAMILY';
export const updateCardFontFamilyAction = (cardFontFamily: string): AppAction => {
return {
type: updateCardFontFamilyActionType,
handle(state: AppState) {
const settings = new Storable<Settings>({
...state.settings.value,
@ -536,10 +485,8 @@ export const updateCardFontFamilyAction = (cardFontFamily: string): AppAction =>
//#region Notes
const findNotesActionType = 'FIND_NOTES';
export const findNotesAction = (qry: string, nextToItem: CardItem): AppAction => {
return {
type: findNotesActionType,
handle(state: AppState) {
const notes = state.notes.value
.filter((o) => o.title.search(qry) > -1)
@ -587,10 +534,8 @@ export const findNotesAction = (qry: string, nextToItem: CardItem): AppAction =>
};
};
const getNotesActionType = 'GET_NOTE';
export const getNotesAction = (noteId: string, nextToItem: CardItem): AppAction => {
return {
type: getNotesActionType,
handle(state: AppState) {
const note = state.notes.value.find((o) => o.id === noteId);
const card: CardItem = {
@ -604,10 +549,8 @@ export const getNotesAction = (noteId: string, nextToItem: CardItem): AppAction
};
};
const updateNotesActionType = 'UPDATE_NOTES';
export const updateNotesAction = (notes: IStorable<readonly NoteItem[]>): AppAction => {
return {
type: updateNotesActionType,
handle(state: AppState) {
return {
...state,
@ -617,10 +560,8 @@ export const updateNotesAction = (notes: IStorable<readonly NoteItem[]>): AppAct
};
};
const saveNoteActionType = 'SAVE_NOTE';
export const saveNoteAction = (note: NoteItem): AppAction => {
return {
type: saveNoteActionType,
handle(state: AppState) {
// you may be creating a new note or updating an existing.
// if its an update, you need to update the note in the following:
@ -642,10 +583,8 @@ export const saveNoteAction = (note: NoteItem): AppAction => {
};
};
const deleteNoteActionType = 'DELETE_NOTE';
export const deleteNoteAction = (note: NoteItem): AppAction => {
return {
type: deleteNoteActionType,
handle(state: AppState) {
// the note may be in any of the following:
// * card list could have it.
@ -692,42 +631,11 @@ export const deleteNoteAction = (note: NoteItem): AppAction => {
//#endregion
type AppActions =
// Saved Page Actions
| typeof savePageActionType
| typeof updateCurrentPageActionType
| typeof updateSavedPagesActionType
| typeof updateSavedPageActionType
| typeof removeSavedPageActionType
| typeof moveSavedPageCardActionType
| typeof addCardToSavedPageActionType
// Card Actions
| typeof addCardActionType
| typeof updateCardActionType
| typeof removeCardActionType
| typeof moveCardActionType
| typeof updateCardsActionType
| typeof clearCardsActionType
// General Actions
| typeof updateErrorActionType
| typeof setUserActionType
| typeof updateAutoCompleteActionType
// Settings Actions
| typeof updateSettingsActionType
| typeof updateCardMergeStrategyActionType
| typeof updateCardFontSizeActionType
| typeof updateCardFontFamilyActionType
// Note Actions
| typeof findNotesActionType
| typeof getNotesActionType
| typeof updateNotesActionType
| typeof saveNoteActionType
| typeof deleteNoteActionType;
@Injectable({
providedIn: 'root',
})
export class AppService extends createStateService(appReducer, initialState) {
export class AppService extends createReducingService(initialState) {
//createStateService(appReducer, initialState) {
private wordToStem: Map<string, string>;
private paragraphs: HashTable<Paragraph>;
private searchIndexArray: string[];
@ -801,7 +709,7 @@ export class AppService extends createStateService(appReducer, initialState) {
]);
private readonly dataPath = 'assets/data';
constructor(private http: HttpClient, private localStorageService: StorageMap, private db: AngularFireDatabase) {
constructor(private http: HttpClient) {
super();
this.searchIndexArray = this.buildIndexArray().sort();