Skip to content

feat(core)!: remove hierarchy config #94

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Oct 11, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 3 additions & 27 deletions packages/core/src/api/createStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import {
Dispatchable,
StoreEffect,
EffectsSubscriber,
HierarchyConfig,
HierarchyDescriptor,
SetState,
RecursivePartial,
Expand All @@ -20,7 +19,6 @@ import {
KnownHierarchyDescriptor,
} from '../types'
import { STORE_IDENTIFIER } from '../utils/general'
import * as defaultHierarchyConfig from '../utils/hierarchyConfig'
import { HierarchyNode } from '../utils/types'
import { detailedTypeof } from './detailedTypeof'
import { isPlainObject } from './isPlainObject'
Expand Down Expand Up @@ -60,15 +58,6 @@ export const createStore: {
}

export class Store<State = any> {
/**
Used by the store's branch reducers in the generated reducer hierarchy to
interact with the hierarchical data type returned by the store's reducers.

This "hierarchical data type" is a plain object by default. But these
hierarchy config options can teach Zedux how to use an Immutable `Map` or
any recursive, map-like data structure.
*/
static readonly hierarchyConfig: HierarchyConfig = defaultHierarchyConfig
static readonly $$typeof = STORE_IDENTIFIER

/**
Expand Down Expand Up @@ -335,11 +324,7 @@ export class Store<State = any> {
this._registerChildStore(childStorePath, childStore)
)

const tree = (this._tree = mergeHierarchies(
this._tree,
newTree,
(this.constructor as typeof Store).hierarchyConfig
))
const tree = (this._tree = mergeHierarchies(this._tree, newTree))

if ((this._rootReducer = tree.reducer)) {
this._dispatchAction(primeAction, primeAction, this._state)
Expand Down Expand Up @@ -438,11 +423,7 @@ export class Store<State = any> {
const newState =
actionType === zeduxTypes.hydrate
? state
: mergeStateTrees(
this._state,
state,
(this.constructor as typeof Store).hierarchyConfig
)[0]
: mergeStateTrees(this._state, state)[0]

// short-circuit if there's no change and no metadata that needs to reach
// this (or a parent/child) store's effects subscribers
Expand Down Expand Up @@ -553,12 +534,7 @@ export class Store<State = any> {
const newOwnState =
newState === oldState
? this._state
: propagateChange(
this._state,
childStorePath,
newState,
(this.constructor as typeof Store).hierarchyConfig
)
: propagateChange(this._state, childStorePath, newState)

// Tell the subscribers what child store this action came from. This store
// (the parent) can use this info to determine how to recreate this state
Expand Down
73 changes: 32 additions & 41 deletions packages/core/src/hierarchy/merge.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { Action, HierarchyConfig, Reducer } from '../types'
import { isPlainObject } from '../api/isPlainObject'
import { Action, Reducer } from '../types'
import { BranchNodeType, NullNodeType } from '../utils/general'
import { BranchNode, Hierarchy, HierarchyNode } from '../utils/types'

Expand All @@ -12,14 +13,11 @@ import { BranchNode, Hierarchy, HierarchyNode } from '../utils/types'
* node, and to find the size of the node.
*/
const createBranchReducer =
(
children: Hierarchy,
{ create, get, isNode, set, size }: HierarchyConfig
): Reducer =>
(oldState = create(), action: Action) => {
(children: Hierarchy): Reducer =>
(oldState = {}, action: Action) => {
// Make a new node to keep track of the values returned by
// the child reducers.
let newState = create()
const newState: Record<string, any> = {}
let hasChanges = false

// Iterate over the child reducers, passing them their state slice
Expand All @@ -28,13 +26,13 @@ const createBranchReducer =
const { reducer } = children[key] as { reducer: Reducer } // we've ensured reducer exists at this point

// Grab the old state slice
const oldStatePiece = isNode(oldState) ? get(oldState, key) : undefined // yes, explicitly set it to undefined
const oldStatePiece = isPlainObject(oldState) ? oldState[key] : undefined // yes, explicitly set it to undefined

// Calculate the new value
const newStatePiece = reducer(oldStatePiece, action)

// Record the result
newState = set(newState, key, newStatePiece)
newState[key] = newStatePiece

// Check for changes
hasChanges || (hasChanges = newStatePiece !== oldStatePiece)
Expand All @@ -43,10 +41,9 @@ const createBranchReducer =
// Handle the case where `children` did not used to be an empty node. This
// means there were changes, but our change detection failed since we didn't
// actually iterate over anything.
hasChanges ||
(hasChanges =
!isNode(oldState) ||
(!Object.keys(children).length && !!size(oldState)))
hasChanges ||=
!isPlainObject(oldState) ||
(!Object.keys(children).length && !!Object.keys(oldState).length)

// If nothing changed, discard the accumulated newState
return hasChanges ? newState : oldState
Expand Down Expand Up @@ -77,8 +74,7 @@ const destroyTree = (tree?: HierarchyNode) => {
*/
const mergeBranches = (
oldTree: HierarchyNode,
newTree: BranchNode,
hierarchyConfig: HierarchyConfig
newTree: BranchNode
): BranchNode => {
const mergedChildren = { ...(oldTree as BranchNode).children }

Expand All @@ -87,9 +83,9 @@ const mergeBranches = (
const newChild = newTree.children[key]
const oldChild = (oldTree as BranchNode).children?.[key]

// Attempt to recursively merge the two children
// Let `mergeHierarchies()` handle any destroying
const mergedChild = mergeHierarchies(oldChild, newChild, hierarchyConfig)
// Attempt to recursively merge the two children. Let `mergeHierarchies()`
// handle any destroying
const mergedChild = mergeHierarchies(oldChild, newChild)

// If the new node is NULL, kill it.
if (mergedChild.type === NullNodeType) {
Expand All @@ -103,7 +99,7 @@ const mergeBranches = (

return {
children: mergedChildren,
reducer: createBranchReducer(mergedChildren, hierarchyConfig),
reducer: createBranchReducer(mergedChildren),
type: BranchNodeType,
}
}
Expand Down Expand Up @@ -134,8 +130,7 @@ const mergeBranches = (
*/
export const mergeHierarchies = (
oldTree: HierarchyNode | undefined,
newTree: HierarchyNode,
hierarchyConfig: HierarchyConfig
newTree: HierarchyNode
): HierarchyNode => {
if (newTree.type !== BranchNodeType) {
destroyTree(oldTree)
Expand All @@ -146,11 +141,11 @@ export const mergeHierarchies = (
if (!oldTree || oldTree.type !== BranchNodeType) {
destroyTree(oldTree)

return mergeBranches({ type: NullNodeType }, newTree, hierarchyConfig)
return mergeBranches({ type: NullNodeType }, newTree)
}

// They're both BRANCH nodes; recursively merge them
return mergeBranches(oldTree, newTree, hierarchyConfig)
return mergeBranches(oldTree, newTree)
}

/**
Expand All @@ -159,37 +154,33 @@ export const mergeHierarchies = (
* If this hydration contains new state for a child store, this parent store
* will create the child store's state for it :O
*
* This means that mixing hierarchyConfigs is not supported, since only the
* parent's hierarchyConfig will be respected during this merge. The child's
* state will be full-hydrated with its new state after this merge.
* This means that mixing dictionary-type structures in nested stores is not
* supported, since only the parent's dictionary-type structure will be
* respected during this merge. The child's state will be full-hydrated with its
* new state after this merge.
*/
export const mergeStateTrees = (
oldStateTree: any,
newStateTree: any,
hierarchyConfig: HierarchyConfig
) => {
if (
!hierarchyConfig.isNode(oldStateTree) ||
!hierarchyConfig.isNode(newStateTree)
) {
export const mergeStateTrees = (oldStateTree: any, newStateTree: any) => {
if (!isPlainObject(oldStateTree) || !isPlainObject(newStateTree)) {
return [newStateTree, newStateTree !== oldStateTree] as const
}

let hasChanges = false
const mergedTree = hierarchyConfig.clone(oldStateTree)
const mergedTree = { ...oldStateTree }

hierarchyConfig.iterate(newStateTree, (key, newVal) => {
const oldVal = hierarchyConfig.get(mergedTree, key)
const [clonedVal, childHasChanges] = hierarchyConfig.isNode(newVal)
Object.keys(newStateTree).forEach(key => {
const newVal = newStateTree[key]
const oldVal = mergedTree[key]
const [clonedVal, childHasChanges] = isPlainObject(newVal)
? // Recursively merge the nested nodes.
mergeStateTrees(oldVal, newVal, hierarchyConfig)
mergeStateTrees(oldVal, newVal)
: // Not a nested node (anymore, at least)
[newVal, newVal !== oldVal]

if (!childHasChanges) return

if (!hasChanges) hasChanges = childHasChanges
hierarchyConfig.set(mergedTree, key, clonedVal)

mergedTree[key] = clonedVal
})

return [hasChanges ? mergedTree : oldStateTree, hasChanges] as const
Expand Down
24 changes: 10 additions & 14 deletions packages/core/src/hierarchy/traverse.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { getMetaData, removeMeta } from '../api/meta'
import { zeduxTypes } from '../api/zeduxTypes'
import { ActionChain, HierarchyConfig } from '../types'
import { ActionChain } from '../types'
import { BranchNodeType, StoreNodeType } from '../utils/general'
import { HierarchyNode, StoreNode } from '../utils/types'

Expand Down Expand Up @@ -70,24 +70,20 @@ export const delegate = (
export const propagateChange = <State = any>(
currentState: State,
subStorePath: string[],
newSubStoreState: any,
hierarchyConfig: HierarchyConfig
newSubStoreState: any
): State => {
if (!subStorePath.length) return newSubStoreState

// at this point we can assume that currentState is a hierarhical structure
// these "currentState as any" casts should be fine
const newNode = hierarchyConfig.clone(currentState as any)
const newNode = { ...currentState }
const nextNodeKey = subStorePath[0]

return hierarchyConfig.set(
newNode,
nextNodeKey,
propagateChange(
hierarchyConfig.get(currentState as any, nextNodeKey),
subStorePath.slice(1),
newSubStoreState,
hierarchyConfig
)
) as any
;(newNode as any)[nextNodeKey] = propagateChange(
(currentState as any)[nextNodeKey],
subStorePath.slice(1),
newSubStoreState
)

return newNode
}
10 changes: 0 additions & 10 deletions packages/core/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -105,16 +105,6 @@ export type EffectsSubscriber<

export type ErrorSubscriber = (error: unknown) => any

export interface HierarchyConfig<T = any> {
clone: (node: T) => T
create: () => T
get: (node: T, key: string) => any
isNode: (node: any) => boolean
iterate: (node: T, callback: (key: string, val: any) => void) => void
set: (node: T, key: string, val: any) => T
size: (node: T) => number
}

/**
* Describes a store's dependency tree. A store can have any number of reducers
* or child stores nested indefinitely.
Expand Down
62 changes: 0 additions & 62 deletions packages/core/src/utils/hierarchyConfig.ts

This file was deleted.

2 changes: 1 addition & 1 deletion packages/core/test/units/createStore.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,4 +38,4 @@ describe('Zedux.createStore()', () => {
})
})

// TODO: Test custom store classes that override hierarchyConfig
// TODO: Test custom store classes with different hierarchical data structures.
9 changes: 3 additions & 6 deletions packages/core/test/units/hierarchy.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ import {
ReducerNodeType,
StoreNodeType,
} from '@zedux/core/utils/general'
import * as hierarchyConfig from '@zedux/core/utils/hierarchyConfig'
import {
createMockStore,
nonPlainObjects,
Expand Down Expand Up @@ -249,7 +248,7 @@ describe('propagateChange()', () => {
const subStorePath: any[] = []
const newSubStoreState = {}

propagateChange(null, subStorePath, newSubStoreState, hierarchyConfig)
propagateChange(null, subStorePath, newSubStoreState)
})

test('sets a property on the top level of the state tree', () => {
Expand All @@ -262,8 +261,7 @@ describe('propagateChange()', () => {
const newState = propagateChange(
currentState,
subStorePath,
newSubStoreState,
hierarchyConfig
newSubStoreState
)

expect(newState).not.toBe(currentState)
Expand All @@ -287,8 +285,7 @@ describe('propagateChange()', () => {
const newState = propagateChange(
currentState,
subStorePath,
newSubStoreState,
hierarchyConfig
newSubStoreState
)

expect(newState).not.toBe(currentState)
Expand Down
Loading
Loading