patches.ts
This file
Path
src/plugins/patches.ts
294 lines · 6.8 KiB · TypeScript
Last changed by
fix: undraftable values should not be cloned for patches, fixes #676Michel Weststratebefore adoption1b70ad5
History of this fileTake it
Merge pull request #536 from immerjs/multi-bundleMichel Weststratebefore adoption0d87fc8
lines 1–26why, one step back1import {2 ImmerState,3 Patch,4 SetState,5 ES5ArrayState,6 ProxyArrayState,7 MapState,8 ES5ObjectState,9 ProxyObjectState,10 PatchPath,11 get,12 each,13 has,14 getArchtype,15 isSet,16 isMap,17 loadPlugin,18 ProxyTypeProxyObject,19 ProxyTypeES5Object,20 ProxyTypeMap,21 ProxyTypeES5Array,22 ProxyTypeProxyArray,23 ProxyTypeSet,24 ArchtypeMap,25 ArchtypeSet,26 ArchtypeArray,Immer 7Michel Weststratebefore adoption467ea5d
line 27why, one step back27 die,fix: undraftable values should not be cloned for patches, fixes #676Michel Weststratebefore adoption1b70ad5
lines 28–29why, one step back28 isDraft,29 isDraftableMerge pull request #536 from immerjs/multi-bundleMichel Weststratebefore adoption0d87fc8
lines 30–82why, one step back30} from "../internal"3132export function enablePatches() {33 const REPLACE = "replace"34 const ADD = "add"35 const REMOVE = "remove"3637 function generatePatches_(38 state: ImmerState,39 basePath: PatchPath,40 patches: Patch[],41 inversePatches: Patch[]42 ): void {43 switch (state.type_) {44 case ProxyTypeProxyObject:45 case ProxyTypeES5Object:46 case ProxyTypeMap:47 return generatePatchesFromAssigned(48 state,49 basePath,50 patches,51 inversePatches52 )53 case ProxyTypeES5Array:54 case ProxyTypeProxyArray:55 return generateArrayPatches(state, basePath, patches, inversePatches)56 case ProxyTypeSet:57 return generateSetPatches(58 (state as any) as SetState,59 basePath,60 patches,61 inversePatches62 )63 }64 }6566 function generateArrayPatches(67 state: ES5ArrayState | ProxyArrayState,68 basePath: PatchPath,69 patches: Patch[],70 inversePatches: Patch[]71 ) {72 let {base_, assigned_} = state73 let copy_ = state.copy_!7475 // Reduce complexity by ensuring `base` is never longer.76 if (copy_.length < base_.length) {77 // @ts-ignore78 ;[base_, copy_] = [copy_, base_]79 ;[patches, inversePatches] = [inversePatches, patches]80 }8182 // Process replaced indices.Immer 7Michel Weststratebefore adoption467ea5d
line 83why, one step back83 for (let i = 0; i < base_.length; i++) {Merge pull request #536 from immerjs/multi-bundleMichel Weststratebefore adoption0d87fc8
lines 84–88why, one step back84 if (assigned_[i] && copy_[i] !== base_[i]) {85 const path = basePath.concat([i])86 patches.push({87 op: REPLACE,88 path,fix: Ensure values in patches are never a draft, fixes #559Michel Weststratebefore adoption33ecbd6
lines 89–91why, one step back89 // Need to maybe clone it, as it can in fact be the original value90 // due to the base/copy inversion at the start of this function91 value: clonePatchValueIfNeeded(copy_[i])Merge pull request #536 from immerjs/multi-bundleMichel Weststratebefore adoption0d87fc8
lines 92–95why, one step back92 })93 inversePatches.push({94 op: REPLACE,95 path,fix: Ensure values in patches are never a draft, fixes #559Michel Weststratebefore adoption33ecbd6
line 96why, one step back96 value: clonePatchValueIfNeeded(base_[i])Merge pull request #536 from immerjs/multi-bundleMichel Weststratebefore adoption0d87fc8
lines 97–101why, one step back97 })98 }99 }100101 // Process added indices.Immer 7Michel Weststratebefore adoption467ea5d
line 102why, one step back102 for (let i = base_.length; i < copy_.length; i++) {Merge pull request #536 from immerjs/multi-bundleMichel Weststratebefore adoption0d87fc8
line 103why, one step back103 const path = basePath.concat([i])Immer 7Michel Weststratebefore adoption467ea5d
line 104why, one step back104 patches.push({Merge pull request #536 from immerjs/multi-bundleMichel Weststratebefore adoption0d87fc8
lines 105–106why, one step back105 op: ADD,106 path,fix: Ensure values in patches are never a draft, fixes #559Michel Weststratebefore adoption33ecbd6
lines 107–109why, one step back107 // Need to maybe clone it, as it can in fact be the original value108 // due to the base/copy inversion at the start of this function109 value: clonePatchValueIfNeeded(copy_[i])Immer 7Michel Weststratebefore adoption467ea5d
lines 110–112why, one step back110 })111 }112 if (base_.length < copy_.length) {Merge pull request #536 from immerjs/multi-bundleMichel Weststratebefore adoption0d87fc8
line 113why, one step back113 inversePatches.push({Immer 7Michel Weststratebefore adoption467ea5d
lines 114–116why, one step back114 op: REPLACE,115 path: basePath.concat(["length"]),116 value: base_.lengthMerge pull request #536 from immerjs/multi-bundleMichel Weststratebefore adoption0d87fc8
lines 117–139why, one step back117 })118 }119 }120121 // This is used for both Map objects and normal objects.122 function generatePatchesFromAssigned(123 state: MapState | ES5ObjectState | ProxyObjectState,124 basePath: PatchPath,125 patches: Patch[],126 inversePatches: Patch[]127 ) {128 const {base_, copy_} = state129 each(state.assigned_!, (key, assignedValue) => {130 const origValue = get(base_, key)131 const value = get(copy_!, key)132 const op = !assignedValue ? REMOVE : has(base_, key) ? REPLACE : ADD133 if (origValue === value && op === REPLACE) return134 const path = basePath.concat(key as any)135 patches.push(op === REMOVE ? {op, path} : {op, path, value})136 inversePatches.push(137 op === ADD138 ? {op: REMOVE, path}139 : op === REMOVEfix: Ensure values in patches are never a draft, fixes #559Michel Weststratebefore adoption33ecbd6
lines 140–141why, one step back140 ? {op: ADD, path, value: clonePatchValueIfNeeded(origValue)}141 : {op: REPLACE, path, value: clonePatchValueIfNeeded(origValue)}Merge pull request #536 from immerjs/multi-bundleMichel Weststratebefore adoption0d87fc8
lines 142–270why, one step back142 )143 })144 }145146 function generateSetPatches(147 state: SetState,148 basePath: PatchPath,149 patches: Patch[],150 inversePatches: Patch[]151 ) {152 let {base_, copy_} = state153154 let i = 0155 base_.forEach((value: any) => {156 if (!copy_!.has(value)) {157 const path = basePath.concat([i])158 patches.push({159 op: REMOVE,160 path,161 value162 })163 inversePatches.unshift({164 op: ADD,165 path,166 value167 })168 }169 i++170 })171 i = 0172 copy_!.forEach((value: any) => {173 if (!base_.has(value)) {174 const path = basePath.concat([i])175 patches.push({176 op: ADD,177 path,178 value179 })180 inversePatches.unshift({181 op: REMOVE,182 path,183 value184 })185 }186 i++187 })188 }189190 function generateReplacementPatches_(191 rootState: ImmerState,192 replacement: any,193 patches: Patch[],194 inversePatches: Patch[]195 ): void {196 patches.push({197 op: REPLACE,198 path: [],199 value: replacement200 })201 inversePatches.push({202 op: REPLACE,203 path: [],204 value: rootState.base_205 })206 }207208 function applyPatches_<T>(draft: T, patches: Patch[]): T {209 patches.forEach(patch => {210 const {path, op} = patch211212 let base: any = draft213 for (let i = 0; i < path.length - 1; i++) {214 base = get(base, path[i])215 if (typeof base !== "object") die(15, path.join("/"))216 }217218 const type = getArchtype(base)219 const value = deepClonePatchValue(patch.value) // used to clone patch to ensure original patch is not modified, see #411220 const key = path[path.length - 1]221 switch (op) {222 case REPLACE:223 switch (type) {224 case ArchtypeMap:225 return base.set(key, value)226 /* istanbul ignore next */227 case ArchtypeSet:228 die(16)229 default:230 // if value is an object, then it's assigned by reference231 // in the following add or remove ops, the value field inside the patch will also be modifyed232 // so we use value from the cloned patch233 // @ts-ignore234 return (base[key] = value)235 }236 case ADD:237 switch (type) {238 case ArchtypeArray:239 return base.splice(key as any, 0, value)240 case ArchtypeMap:241 return base.set(key, value)242 case ArchtypeSet:243 return base.add(value)244 default:245 return (base[key] = value)246 }247 case REMOVE:248 switch (type) {249 case ArchtypeArray:250 return base.splice(key as any, 1)251 case ArchtypeMap:252 return base.delete(key)253 case ArchtypeSet:254 return base.delete(patch.value)255 default:256 return delete base[key]257 }258 default:259 die(17, op)260 }261 })262263 return draft264 }265266 // optimize: this is quite a performance hit, can we detect intelligently when it is needed?267 // E.g. auto-draft when new objects from outside are assigned and modified?268 // (See failing test when deepClone just returns obj)269 function deepClonePatchValue<T>(obj: T): T270 function deepClonePatchValue(obj: any) {fix: undraftable values should not be cloned for patches, fixes #676Michel Weststratebefore adoption1b70ad5
line 271why, one step back271 if (!isDraftable(obj)) return objMerge pull request #536 from immerjs/multi-bundleMichel Weststratebefore adoption0d87fc8
lines 272–280why, one step back272 if (Array.isArray(obj)) return obj.map(deepClonePatchValue)273 if (isMap(obj))274 return new Map(275 Array.from(obj.entries()).map(([k, v]) => [k, deepClonePatchValue(v)])276 )277 if (isSet(obj)) return new Set(Array.from(obj).map(deepClonePatchValue))278 const cloned = Object.create(Object.getPrototypeOf(obj))279 for (const key in obj) cloned[key] = deepClonePatchValue(obj[key])280 return clonedfix: Ensure values in patches are never a draft, fixes #559Michel Weststratebefore adoption33ecbd6
lines 281–286why, one step back281 }282283 function clonePatchValueIfNeeded<T>(obj: T): T {284 if (isDraft(obj)) {285 return deepClonePatchValue(obj)286 } else return objMerge pull request #536 from immerjs/multi-bundleMichel Weststratebefore adoption0d87fc8
lines 287–294why, one step back287 }288289 loadPlugin("Patches", {290 applyPatches_,291 generatePatches_,292 generateReplacementPatches_293 })294}