Skip to content
New issue

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

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

Already on GitHub? # to your account

feat: deepCurrent #1092

Closed
wants to merge 1 commit into from
Closed
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
45 changes: 45 additions & 0 deletions src/core/deepCurrent.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import {
die,
isDraft,
shallowCopy,
each,
DRAFT_STATE,
set,
ImmerState,
isDraftable,
isFrozen
} from "../internal"

// Extend the current function to handle deep drafts
export function deepCurrent<T>(value: T): T
export function deepCurrent(value: any): any {
if (!isDraft(value)) die(10, value) // Use Immer's error handling
return deepCurrentImpl(value)
}

function deepCurrentImpl(value: any): any {
if (!isDraftable(value) || isFrozen(value)) return value // Base case for recursion

const state: ImmerState | undefined = value[DRAFT_STATE]
let copy: any
if (state) {
// State exists: the object is a draft
if (!state.modified_) return state.base_ // If not modified, return base
state.finalized_ = true // Mark as finalized to prevent new drafts during copy
copy = shallowCopy(value, state.scope_.immer_.useStrictShallowCopy_)
} else {
// No state: value is not a draft, perform a shallow copy
copy = shallowCopy(value, true)
}

// Recursively apply deepCurrentImpl to each property
each(copy, (key, childValue) => {
set(copy, key, deepCurrentImpl(childValue)) // Recurse into children
})

// Revert the finalized flag after recursion
if (state) {
state.finalized_ = false
}
return copy
}
1 change: 1 addition & 0 deletions src/immer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ export {
PatchListener,
original,
current,
deepCurrent,
isDraft,
isDraftable,
NOTHING as nothing,
Expand Down
2 changes: 2 additions & 0 deletions src/internal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,5 @@ export * from "./core/finalize"
export * from "./core/proxy"
export * from "./core/immerClass"
export * from "./core/current"
export * from "./core/deepCurrent"

Loading