Skip to content
Myr

finalize.ts

This file

Path

src/finalize.ts

203 lines · 5.2 KiB · TypeScript

Last changed by

feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8

History of this file

Take it

feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8

lines 1–203why, one step back
1import {Immer} from "./immer"
2import {ImmerState, Drafted, ProxyType} from "./types"3import {ImmerScope} from "./scope"4import {5 isSet,6 has,7 is,8 get,9 each,10 DRAFT_STATE,11 NOTHING,12 freeze,13 shallowCopy,14 set15} from "./common"16import {isDraft, isDraftable} from "./index"17import {SetState} from "./set"18import {generatePatches, PatchPath} from "./patches"1920export function processResult(immer: Immer, result: any, scope: ImmerScope) {21 const baseDraft = scope.drafts![0]22 const isReplaced = result !== undefined && result !== baseDraft23 immer.willFinalize(scope, result, isReplaced)24 if (isReplaced) {25 if (baseDraft[DRAFT_STATE].modified) {26 scope.revoke()27 throw new Error("An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.") // prettier-ignore28 }29 if (isDraftable(result)) {30 // Finalize the result in case it contains (or is) a subset of the draft.31 result = finalize(immer, result, scope)32 maybeFreeze(immer, result)33 }34 if (scope.patches) {35 scope.patches.push({36 op: "replace",37 path: [],38 value: result39 })40 scope.inversePatches!.push({41 op: "replace",42 path: [],43 value: baseDraft[DRAFT_STATE].base44 })45 }46 } else {47 // Finalize the base draft.48 result = finalize(immer, baseDraft, scope, [])49 }50 scope.revoke()51 if (scope.patches) {52 scope.patchListener!(scope.patches, scope.inversePatches!)53 }54 return result !== NOTHING ? result : undefined55}5657function finalize(58 immer: Immer,59 draft: Drafted,60 scope: ImmerScope,61 path?: PatchPath62) {63 const state = draft[DRAFT_STATE]64 if (!state) {65 if (Object.isFrozen(draft)) return draft66 return finalizeTree(immer, draft, scope)67 }68 // Never finalize drafts owned by another scope.69 if (state.scope !== scope) {70 return draft71 }72 if (!state.modified) {73 maybeFreeze(immer, state.base, true)74 return state.base75 }76 if (!state.finalized) {77 state.finalized = true78 finalizeTree(immer, state.draft, scope, path)7980 // We cannot really delete anything inside of a Set. We can only replace the whole Set.81 if (immer.onDelete && state.type !== ProxyType.Set) {82 // The `assigned` object is unreliable with ES5 drafts.83 if (immer.useProxies) {84 const {assigned} = state85 each(assigned, (prop, exists) => {86 if (!exists) immer.onDelete!(state, prop as any)87 })88 } else {89 const {base, copy} = state90 each(base, prop => {91 if (!has(copy, prop)) immer.onDelete!(state, prop as any)92 })93 }94 }95 if (immer.onCopy) {96 immer.onCopy(state)97 }9899 // At this point, all descendants of `state.copy` have been finalized,100 // so we can be sure that `scope.canAutoFreeze` is accurate.101 if (immer.autoFreeze && scope.canAutoFreeze) {102 freeze(state.copy, false)103 }104105 if (path && scope.patches) {106 generatePatches(state, path, scope.patches, scope.inversePatches!)107 }108 }109 return state.copy110}111112function finalizeTree(113 immer: Immer,114 root: Drafted,115 scope: ImmerScope,116 rootPath?: PatchPath117) {118 const state = root[DRAFT_STATE]119 if (state) {120 if (121 state.type === ProxyType.ES5Object ||122 state.type === ProxyType.ES5Array123 ) {124 // Create the final copy, with added keys and without deleted keys.125 state.copy = shallowCopy(state.draft, true)126 }127 root = state.copy128 }129 each(root, (key, value) =>130 finalizeProperty(immer, scope, root, state, root, key, value, rootPath)131 )132 return root133}134135function finalizeProperty(136 immer: Immer,137 scope: ImmerScope,138 root: Drafted,139 rootState: ImmerState,140 parentValue: Drafted,141 prop: string | number,142 childValue: any,143 rootPath?: PatchPath144) {145 if (childValue === parentValue) {146 throw Error("Immer forbids circular references")147 }148149 // In the `finalizeTree` method, only the `root` object may be a draft.150 const isDraftProp = !!rootState && parentValue === root151 const isSetMember = isSet(parentValue)152153 if (isDraft(childValue)) {154 const path =155 rootPath &&156 isDraftProp &&157 !isSetMember && // Set objects are atomic since they have no keys.158 !has((rootState as Exclude<ImmerState, SetState>).assigned!, prop) // Skip deep patches for assigned keys.159 ? rootPath!.concat(prop)160 : undefined161162 // Drafts owned by `scope` are finalized here.163 childValue = finalize(immer, childValue, scope, path)164 set(parentValue, prop, childValue)165166 // Drafts from another scope must prevent auto-freezing.167 if (isDraft(childValue)) {168 scope.canAutoFreeze = false169 }170 }171 // Unchanged draft properties are ignored.172 else if (isDraftProp && is(childValue, get(rootState.base, prop))) {173 return174 }175 // Search new objects for unfinalized drafts. Frozen objects should never contain drafts.176 // TODO: the recursion over here looks weird, shouldn't non-draft stuff have it's own recursion?177 // especially the passing on of root and rootState doesn't make sense...178 else if (isDraftable(childValue) && !Object.isFrozen(childValue)) {179 each(childValue, (key, grandChild) =>180 finalizeProperty(181 immer,182 scope,183 root,184 rootState,185 childValue,186 key,187 grandChild,188 rootPath189 )190 )191 maybeFreeze(immer, childValue)192 }193194 if (isDraftProp && immer.onAssign && !isSetMember) {195 immer.onAssign(rootState, prop, childValue)196 }197}198199export function maybeFreeze(immer: Immer, value: any, deep = false) {200 if (immer.autoFreeze && !isDraft(value)) {201 freeze(value, deep)202 }203}