patches.ts
This file
Path
src/plugins/patches.ts
293 lines · 6.8 KiB · TypeScript
Last changed by
Immer 7Michel Weststratebefore adoption467ea5d
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
lines 27–28why, one step back27 die,28 isDraftMerge pull request #536 from immerjs/multi-bundleMichel Weststratebefore adoption0d87fc8
lines 29–81why, one step back29} from "../internal"3031export function enablePatches() {32 const REPLACE = "replace"33 const ADD = "add"34 const REMOVE = "remove"3536 function generatePatches_(37 state: ImmerState,38 basePath: PatchPath,39 patches: Patch[],40 inversePatches: Patch[]41 ): void {42 switch (state.type_) {43 case ProxyTypeProxyObject:44 case ProxyTypeES5Object:45 case ProxyTypeMap:46 return generatePatchesFromAssigned(47 state,48 basePath,49 patches,50 inversePatches51 )52 case ProxyTypeES5Array:53 case ProxyTypeProxyArray:54 return generateArrayPatches(state, basePath, patches, inversePatches)55 case ProxyTypeSet:56 return generateSetPatches(57 (state as any) as SetState,58 basePath,59 patches,60 inversePatches61 )62 }63 }6465 function generateArrayPatches(66 state: ES5ArrayState | ProxyArrayState,67 basePath: PatchPath,68 patches: Patch[],69 inversePatches: Patch[]70 ) {71 let {base_, assigned_} = state72 let copy_ = state.copy_!7374 // Reduce complexity by ensuring `base` is never longer.75 if (copy_.length < base_.length) {76 // @ts-ignore77 ;[base_, copy_] = [copy_, base_]78 ;[patches, inversePatches] = [inversePatches, patches]79 }8081 // Process replaced indices.Immer 7Michel Weststratebefore adoption467ea5d
line 82why, one step back82 for (let i = 0; i < base_.length; i++) {Merge pull request #536 from immerjs/multi-bundleMichel Weststratebefore adoption0d87fc8
lines 83–87why, one step back83 if (assigned_[i] && copy_[i] !== base_[i]) {84 const path = basePath.concat([i])85 patches.push({86 op: REPLACE,87 path,fix: Ensure values in patches are never a draft, fixes #559Michel Weststratebefore adoption33ecbd6
lines 88–90why, one step back88 // Need to maybe clone it, as it can in fact be the original value89 // due to the base/copy inversion at the start of this function90 value: clonePatchValueIfNeeded(copy_[i])Merge pull request #536 from immerjs/multi-bundleMichel Weststratebefore adoption0d87fc8
lines 91–94why, one step back91 })92 inversePatches.push({93 op: REPLACE,94 path,fix: Ensure values in patches are never a draft, fixes #559Michel Weststratebefore adoption33ecbd6
line 95why, one step back95 value: clonePatchValueIfNeeded(base_[i])Merge pull request #536 from immerjs/multi-bundleMichel Weststratebefore adoption0d87fc8
lines 96–100why, one step back96 })97 }98 }99100 // Process added indices.Immer 7Michel Weststratebefore adoption467ea5d
line 101why, one step back101 for (let i = base_.length; i < copy_.length; i++) {Merge pull request #536 from immerjs/multi-bundleMichel Weststratebefore adoption0d87fc8
line 102why, one step back102 const path = basePath.concat([i])Immer 7Michel Weststratebefore adoption467ea5d
line 103why, one step back103 patches.push({Merge pull request #536 from immerjs/multi-bundleMichel Weststratebefore adoption0d87fc8
lines 104–105why, one step back104 op: ADD,105 path,fix: Ensure values in patches are never a draft, fixes #559Michel Weststratebefore adoption33ecbd6
lines 106–108why, one step back106 // Need to maybe clone it, as it can in fact be the original value107 // due to the base/copy inversion at the start of this function108 value: clonePatchValueIfNeeded(copy_[i])Immer 7Michel Weststratebefore adoption467ea5d
lines 109–111why, one step back109 })110 }111 if (base_.length < copy_.length) {Merge pull request #536 from immerjs/multi-bundleMichel Weststratebefore adoption0d87fc8
line 112why, one step back112 inversePatches.push({Immer 7Michel Weststratebefore adoption467ea5d
lines 113–115why, one step back113 op: REPLACE,114 path: basePath.concat(["length"]),115 value: base_.lengthMerge pull request #536 from immerjs/multi-bundleMichel Weststratebefore adoption0d87fc8
lines 116–138why, one step back116 })117 }118 }119120 // This is used for both Map objects and normal objects.121 function generatePatchesFromAssigned(122 state: MapState | ES5ObjectState | ProxyObjectState,123 basePath: PatchPath,124 patches: Patch[],125 inversePatches: Patch[]126 ) {127 const {base_, copy_} = state128 each(state.assigned_!, (key, assignedValue) => {129 const origValue = get(base_, key)130 const value = get(copy_!, key)131 const op = !assignedValue ? REMOVE : has(base_, key) ? REPLACE : ADD132 if (origValue === value && op === REPLACE) return133 const path = basePath.concat(key as any)134 patches.push(op === REMOVE ? {op, path} : {op, path, value})135 inversePatches.push(136 op === ADD137 ? {op: REMOVE, path}138 : op === REMOVEfix: Ensure values in patches are never a draft, fixes #559Michel Weststratebefore adoption33ecbd6
lines 139–140why, one step back139 ? {op: ADD, path, value: clonePatchValueIfNeeded(origValue)}140 : {op: REPLACE, path, value: clonePatchValueIfNeeded(origValue)}Merge pull request #536 from immerjs/multi-bundleMichel Weststratebefore adoption0d87fc8
lines 141–279why, one step back141 )142 })143 }144145 function generateSetPatches(146 state: SetState,147 basePath: PatchPath,148 patches: Patch[],149 inversePatches: Patch[]150 ) {151 let {base_, copy_} = state152153 let i = 0154 base_.forEach((value: any) => {155 if (!copy_!.has(value)) {156 const path = basePath.concat([i])157 patches.push({158 op: REMOVE,159 path,160 value161 })162 inversePatches.unshift({163 op: ADD,164 path,165 value166 })167 }168 i++169 })170 i = 0171 copy_!.forEach((value: any) => {172 if (!base_.has(value)) {173 const path = basePath.concat([i])174 patches.push({175 op: ADD,176 path,177 value178 })179 inversePatches.unshift({180 op: REMOVE,181 path,182 value183 })184 }185 i++186 })187 }188189 function generateReplacementPatches_(190 rootState: ImmerState,191 replacement: any,192 patches: Patch[],193 inversePatches: Patch[]194 ): void {195 patches.push({196 op: REPLACE,197 path: [],198 value: replacement199 })200 inversePatches.push({201 op: REPLACE,202 path: [],203 value: rootState.base_204 })205 }206207 function applyPatches_<T>(draft: T, patches: Patch[]): T {208 patches.forEach(patch => {209 const {path, op} = patch210211 let base: any = draft212 for (let i = 0; i < path.length - 1; i++) {213 base = get(base, path[i])214 if (typeof base !== "object") die(15, path.join("/"))215 }216217 const type = getArchtype(base)218 const value = deepClonePatchValue(patch.value) // used to clone patch to ensure original patch is not modified, see #411219 const key = path[path.length - 1]220 switch (op) {221 case REPLACE:222 switch (type) {223 case ArchtypeMap:224 return base.set(key, value)225 /* istanbul ignore next */226 case ArchtypeSet:227 die(16)228 default:229 // if value is an object, then it's assigned by reference230 // in the following add or remove ops, the value field inside the patch will also be modifyed231 // so we use value from the cloned patch232 // @ts-ignore233 return (base[key] = value)234 }235 case ADD:236 switch (type) {237 case ArchtypeArray:238 return base.splice(key as any, 0, value)239 case ArchtypeMap:240 return base.set(key, value)241 case ArchtypeSet:242 return base.add(value)243 default:244 return (base[key] = value)245 }246 case REMOVE:247 switch (type) {248 case ArchtypeArray:249 return base.splice(key as any, 1)250 case ArchtypeMap:251 return base.delete(key)252 case ArchtypeSet:253 return base.delete(patch.value)254 default:255 return delete base[key]256 }257 default:258 die(17, op)259 }260 })261262 return draft263 }264265 // optimize: this is quite a performance hit, can we detect intelligently when it is needed?266 // E.g. auto-draft when new objects from outside are assigned and modified?267 // (See failing test when deepClone just returns obj)268 function deepClonePatchValue<T>(obj: T): T269 function deepClonePatchValue(obj: any) {270 if (!obj || typeof obj !== "object") return obj271 if (Array.isArray(obj)) return obj.map(deepClonePatchValue)272 if (isMap(obj))273 return new Map(274 Array.from(obj.entries()).map(([k, v]) => [k, deepClonePatchValue(v)])275 )276 if (isSet(obj)) return new Set(Array.from(obj).map(deepClonePatchValue))277 const cloned = Object.create(Object.getPrototypeOf(obj))278 for (const key in obj) cloned[key] = deepClonePatchValue(obj[key])279 return clonedfix: Ensure values in patches are never a draft, fixes #559Michel Weststratebefore adoption33ecbd6
lines 280–285why, one step back280 }281282 function clonePatchValueIfNeeded<T>(obj: T): T {283 if (isDraft(obj)) {284 return deepClonePatchValue(obj)285 } else return objMerge pull request #536 from immerjs/multi-bundleMichel Weststratebefore adoption0d87fc8
lines 286–293why, one step back286 }287288 loadPlugin("Patches", {289 applyPatches_,290 generatePatches_,291 generateReplacementPatches_292 })293}