finalize.ts
This file
Path
src/core/finalize.ts
312 lines · 8.1 KiB · TypeScript
Last changed by
feat: Override array methods to avoid proxy creation while iterating and updating (#1184)Mark Eriksonbefore adoptiond38a9d0
History of this fileTake it
The walk stopped after 200 commits: lines older than bc35916 point at it.
chore: fix links, fixes #779Michel Weststratebefore adoptionbc35916
lines 1–12why, one step back1import {2 ImmerScope,3 DRAFT_STATE,4 isDraftable,5 NOTHING,6 PatchPath,7 each,8 freeze,9 ImmerState,10 isDraft,11 SetState,12 set,Merge pull request #1028 from immerjs/immer-10Michel Weststratebefore adoption2ef9a42
line 13why, one step back13 ArchType,chore: fix links, fixes #779Michel Weststratebefore adoptionbc35916
lines 14–16why, one step back14 getPlugin,15 die,16 revokeScope,Fix: freezing of Map values during finalization (#1150)Chetan Satputebefore adoptionb4f71a6
line 17why, one step back17 isFrozen,perf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202
lines 18–22why, one step back18 get,19 Patch,20 latest,21 prepareCopy,22 getFinalValue,feat: Override array methods to avoid proxy creation while iterating and updating (#1184)Mark Eriksonbefore adoptiond38a9d0
lines 23–24why, one step back23 getValue,24 ProxyArrayStatechore: fix links, fixes #779Michel Weststratebefore adoptionbc35916
lines 25–30why, one step back25} from "../internal"2627export function processResult(result: any, scope: ImmerScope) {28 scope.unfinalizedDrafts_ = scope.drafts_.length29 const baseDraft = scope.drafts_![0]30 const isReplaced = result !== undefined && result !== baseDraftperf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202
line 31why, one step back31chore: fix links, fixes #779Michel Weststratebefore adoptionbc35916
lines 32–40why, one step back32 if (isReplaced) {33 if (baseDraft[DRAFT_STATE].modified_) {34 revokeScope(scope)35 die(4)36 }37 if (isDraftable(result)) {38 // Finalize the result in case it contains (or is) a subset of the draft.39 result = finalize(scope, result)40 }perf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202
lines 41–43why, one step back41 const {patchPlugin_} = scope42 if (patchPlugin_) {43 patchPlugin_.generateReplacementPatches_(fix: No patches being generated for root primitive replacements. Fixes #888Michel Weststratebefore adoption0f96270
line 44why, one step back44 baseDraft[DRAFT_STATE].base_,chore: fix links, fixes #779Michel Weststratebefore adoptionbc35916
line 45why, one step back45 result,perf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202
line 46why, one step back46 scopechore: fix links, fixes #779Michel Weststratebefore adoptionbc35916
lines 47–50why, one step back47 )48 }49 } else {50 // Finalize the base draft.perf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202
line 51why, one step back51 result = finalize(scope, baseDraft)chore: fix links, fixes #779Michel Weststratebefore adoptionbc35916
line 52why, one step back52 }perf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202
lines 53–55why, one step back5354 maybeFreeze(scope, result, true)55chore: fix links, fixes #779Michel Weststratebefore adoptionbc35916
lines 56–62why, one step back56 revokeScope(scope)57 if (scope.patches_) {58 scope.patchListener_!(scope.patches_, scope.inversePatches_!)59 }60 return result !== NOTHING ? result : undefined61}62perf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202
line 63why, one step back63function finalize(rootScope: ImmerScope, value: any) {chore: fix links, fixes #779Michel Weststratebefore adoptionbc35916
lines 64–68why, one step back64 // Don't recurse in tho recursive data structures65 if (isFrozen(value)) return value6667 const state: ImmerState = value[DRAFT_STATE]68 if (!state) {perf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202
lines 69–74why, one step back69 const finalValue = handleValue(value, rootScope.handledSet_, rootScope)70 return finalValue71 }7273 // Never finalize drafts owned by another scope74 if (!isSameScope(state, rootScope)) {chore: fix links, fixes #779Michel Weststratebefore adoptionbc35916
lines 75–76why, one step back75 return value76 }perf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202
line 77why, one step back77chore: fix links, fixes #779Michel Weststratebefore adoptionbc35916
lines 78–81why, one step back78 // Unmodified draft, return the (frozen) original79 if (!state.modified_) {80 return state.base_81 }perf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202
line 82why, one step back82chore: fix links, fixes #779Michel Weststratebefore adoptionbc35916
line 83why, one step back83 if (!state.finalized_) {perf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202
lines 84–90why, one step back84 // Execute all registered draft finalization callbacks85 const {callbacks_} = state86 if (callbacks_) {87 while (callbacks_.length > 0) {88 const callback = callbacks_.pop()!89 callback(rootScope)90 }fix: Preserve insertion order of Sets, fixes #819 (#976)jdipbefore adoptionb3eeb69
line 91why, one step back91 }perf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202
lines 92–93why, one step back9293 generatePatchesAndFinalize(state, rootScope)chore: fix links, fixes #779Michel Weststratebefore adoptionbc35916
line 94why, one step back94 }perf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202
lines 95–96why, one step back9596 // By now the root copy has been fully updated throughout its treechore: fix links, fixes #779Michel Weststratebefore adoptionbc35916
lines 97–99why, one step back97 return state.copy_98}99perf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202
lines 100–103why, one step back100function maybeFreeze(scope: ImmerScope, value: any, deep = false) {101 // we never freeze for a non-root scope; as it would prevent pruning for drafts inside wrapping objects102 if (!scope.parent_ && scope.immer_.autoFreeze_ && scope.canAutoFreeze_) {103 freeze(value, deep)feat: Optimize Immer performance where possible, introduce `setUseStrictIteration` (#1164)Mark Eriksonbefore adoptione1996ce
line 104why, one step back104 }perf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202
line 105why, one step back105}feat: Optimize Immer performance where possible, introduce `setUseStrictIteration` (#1164)Mark Eriksonbefore adoptione1996ce
line 106why, one step back106perf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202
lines 107–136why, one step back107function markStateFinalized(state: ImmerState) {108 state.finalized_ = true109 state.scope_.unfinalizedDrafts_--110}111112let isSameScope = (state: ImmerState, rootScope: ImmerScope) =>113 state.scope_ === rootScope114115// A reusable empty array to avoid allocations116const EMPTY_LOCATIONS_RESULT: (string | symbol | number)[] = []117118// Updates all references to a draft in its parent to the finalized value.119// This handles cases where the same draft appears multiple times in the parent, or has been moved around.120export function updateDraftInParent(121 parent: ImmerState,122 draftValue: any,123 finalizedValue: any,124 originalKey?: string | number | symbol125): void {126 const parentCopy = latest(parent)127 const parentType = parent.type_128129 // Fast path: Check if draft is still at original key130 if (originalKey !== undefined) {131 const currentValue = get(parentCopy, originalKey, parentType)132 if (currentValue === draftValue) {133 // Still at original location, just update it134 set(parentCopy, originalKey, finalizedValue, parentType)135 return136 }feat: Optimize Immer performance where possible, introduce `setUseStrictIteration` (#1164)Mark Eriksonbefore adoptione1996ce
line 137why, one step back137 }perf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202
lines 138–153why, one step back138139 // Slow path: Build reverse mapping of all children140 // to their indices in the parent, so that we can141 // replace all locations where this draft appears.142 // We only have to build this once per parent.143 if (!parent.draftLocations_) {144 const draftLocations = (parent.draftLocations_ = new Map())145146 // Use `each` which works on Arrays, Maps, and Objects147 each(parentCopy, (key, value) => {148 if (isDraft(value)) {149 const keys = draftLocations.get(value) || []150 keys.push(key)151 draftLocations.set(value, keys)152 }153 })feat: Optimize Immer performance where possible, introduce `setUseStrictIteration` (#1164)Mark Eriksonbefore adoptione1996ce
lines 154–155why, one step back154 }155perf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202
lines 156–162why, one step back156 // Look up all locations where this draft appears157 const locations =158 parent.draftLocations_.get(draftValue) ?? EMPTY_LOCATIONS_RESULT159160 // Update all locations161 for (const location of locations) {162 set(parentCopy, location, finalizedValue, parentType)chore: fix links, fixes #779Michel Weststratebefore adoptionbc35916
line 163why, one step back163 }perf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202
lines 164–178why, one step back164}165166// Register a callback to finalize a child draft when the parent draft is finalized.167// This assumes there is a parent -> child relationship between the two drafts,168// and we have a key to locate the child in the parent.169export function registerChildFinalizationCallback(170 parent: ImmerState,171 child: ImmerState,172 key: string | number | symbol173) {174 parent.callbacks_.push(function childCleanup(rootScope) {175 const state: ImmerState = child176177 // Can only continue if this is a draft owned by this scope178 if (!state || !isSameScope(state, rootScope)) {feat: Optimize Immer performance where possible, introduce `setUseStrictIteration` (#1164)Mark Eriksonbefore adoptione1996ce
lines 179–180why, one step back179 return180 }perf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202
lines 181–197why, one step back181182 // Handle potential set value finalization first183 rootScope.mapSetPlugin_?.fixSetContents(state)184185 const finalizedValue = getFinalValue(state)186187 // Update all locations in the parent that referenced this draft188 updateDraftInParent(parent, state.draft_ ?? state, finalizedValue, key)189190 generatePatchesAndFinalize(state, rootScope)191 })192}193194function generatePatchesAndFinalize(state: ImmerState, rootScope: ImmerScope) {195 const shouldFinalize =196 state.modified_ &&197 !state.finalized_ &&feat: Override array methods to avoid proxy creation while iterating and updating (#1184)Mark Eriksonbefore adoptiond38a9d0
lines 198–201why, one step back198 (state.type_ === ArchType.Set ||199 (state.type_ === ArchType.Array &&200 (state as ProxyArrayState).allIndicesReassigned_) ||201 (state.assigned_?.size ?? 0) > 0)perf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202
lines 202–210why, one step back202203 if (shouldFinalize) {204 const {patchPlugin_} = rootScope205 if (patchPlugin_) {206 const basePath = patchPlugin_!.getPath(state)207208 if (basePath) {209 patchPlugin_!.generatePatches_(state, basePath, rootScope)210 }chore: fix links, fixes #779Michel Weststratebefore adoptionbc35916
line 211why, one step back211 }perf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202
lines 212–213why, one step back212213 markStateFinalized(state)chore: fix links, fixes #779Michel Weststratebefore adoptionbc35916
lines 214–216why, one step back214 }215}216perf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202
lines 217–262why, one step back217export function handleCrossReference(218 target: ImmerState,219 key: string | number | symbol,220 value: any221) {222 const {scope_} = target223 // Check if value is a draft from this scope224 if (isDraft(value)) {225 const state: ImmerState = value[DRAFT_STATE]226 if (isSameScope(state, scope_)) {227 // Register callback to update this location when the draft finalizes228229 state.callbacks_.push(function crossReferenceCleanup() {230 // Update the target location with finalized value231 prepareCopy(target)232233 const finalizedValue = getFinalValue(state)234235 updateDraftInParent(target, value, finalizedValue, key)236 })237 }238 } else if (isDraftable(value)) {239 // Handle non-draft objects that might contain drafts240 target.callbacks_.push(function nestedDraftCleanup() {241 const targetCopy = latest(target)242243 if (get(targetCopy, key, target.type_) === value) {244 // Process the value to replace any nested drafts245 // finalizeAssigned(target, key, target.scope_)246247 if (248 scope_.drafts_.length > 1 &&249 ((target as Exclude<ImmerState, SetState>).assigned_!.get(key) ??250 false) === true &&251 target.copy_252 ) {253 // This might be a non-draft value that has drafts254 // inside. We do need to recurse here to handle those.255 handleValue(256 get(target.copy_, key, target.type_),257 scope_.handledSet_,258 scope_259 )260 }261 }262 })chore: fix links, fixes #779Michel Weststratebefore adoptionbc35916
line 263why, one step back263 }perf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202
lines 264–311why, one step back264}265266export function handleValue(267 target: any,268 handledSet: Set<any>,269 rootScope: ImmerScope270) {271 if (!rootScope.immer_.autoFreeze_ && rootScope.unfinalizedDrafts_ < 1) {272 // optimization: if an object is not a draft, and we don't have to273 // deepfreeze everything, and we are sure that no drafts are left in the remaining object274 // cause we saw and finalized all drafts already; we can stop visiting the rest of the tree.275 // This benefits especially adding large data tree's without further processing.276 // See add-data.js perf test277 return target278 }279280 // Skip if already handled, frozen, or not draftable281 if (282 isDraft(target) ||283 handledSet.has(target) ||284 !isDraftable(target) ||285 isFrozen(target)286 ) {287 return target288 }289290 handledSet.add(target)291292 // Process ALL properties/entries293 each(target, (key, value) => {294 if (isDraft(value)) {295 const state: ImmerState = value[DRAFT_STATE]296 if (isSameScope(state, rootScope)) {297 // Replace draft with finalized value298299 const updatedValue = getFinalValue(state)300301 set(target, key, updatedValue, target.type_)302303 markStateFinalized(state)304 }305 } else if (isDraftable(value)) {306 // Recursively handle nested values307 handleValue(value, handledSet, rootScope)308 }309 })310311 return targetchore: fix links, fixes #779Michel Weststratebefore adoptionbc35916
line 312why, one step back312}