patches.ts
This file
Path
src/plugins/patches.ts
306 lines · 7.2 KiB · TypeScript
Last changed by
Ensure values in patches are never a draftRenaud Chaputbefore adoption2454a51
History of this fileTake it
Merge pull request #536 from immerjs/multi-bundleMichel Weststratebefore adoption0d87fc8
lines 1–28why, 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,27 die28} from "../internal"Ensure values in patches are never a draftRenaud Chaputbefore adoption2454a51
line 29why, one step back29import {isDraft} from "../utils/common"Merge pull request #536 from immerjs/multi-bundleMichel Weststratebefore adoption0d87fc8
lines 30–101why, one step back3031export 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 const delta = copy_.length - base_.length8283 // Find the first replaced index.84 let start = 085 while (base_[start] === copy_[start] && start < base_.length) {86 ++start87 }8889 // Find the last replaced index. Search from the end to optimize splice patches.90 let end = base_.length91 while (end > start && base_[end - 1] === copy_[end + delta - 1]) {92 --end93 }9495 // Process replaced indices.96 for (let i = start; i < end; ++i) {97 if (assigned_[i] && copy_[i] !== base_[i]) {98 const path = basePath.concat([i])99 patches.push({100 op: REPLACE,101 path,Ensure values in patches are never a draftRenaud Chaputbefore adoption2454a51
lines 102–104why, one step back102 // Need to maybe clone it, as it can in fact be the original value103 // due to the base/copy inversion at the start of this function104 value: clonePatchValueIfNeeded(copy_[i])Merge pull request #536 from immerjs/multi-bundleMichel Weststratebefore adoption0d87fc8
lines 105–108why, one step back105 })106 inversePatches.push({107 op: REPLACE,108 path,Ensure values in patches are never a draftRenaud Chaputbefore adoption2454a51
line 109why, one step back109 value: clonePatchValueIfNeeded(base_[i])Merge pull request #536 from immerjs/multi-bundleMichel Weststratebefore adoption0d87fc8
lines 110–121why, one step back110 })111 }112 }113114 const replaceCount = patches.length115116 // Process added indices.117 for (let i = end + delta - 1; i >= end; --i) {118 const path = basePath.concat([i])119 patches[replaceCount + i - end] = {120 op: ADD,121 path,Ensure values in patches are never a draftRenaud Chaputbefore adoption2454a51
lines 122–124why, one step back122 // Need to maybe clone it, as it can in fact be the original value123 // due to the base/copy inversion at the start of this function124 value: clonePatchValueIfNeeded(copy_[i])Merge pull request #536 from immerjs/multi-bundleMichel Weststratebefore adoption0d87fc8
lines 125–151why, one step back125 }126 inversePatches.push({127 op: REMOVE,128 path129 })130 }131 }132133 // This is used for both Map objects and normal objects.134 function generatePatchesFromAssigned(135 state: MapState | ES5ObjectState | ProxyObjectState,136 basePath: PatchPath,137 patches: Patch[],138 inversePatches: Patch[]139 ) {140 const {base_, copy_} = state141 each(state.assigned_!, (key, assignedValue) => {142 const origValue = get(base_, key)143 const value = get(copy_!, key)144 const op = !assignedValue ? REMOVE : has(base_, key) ? REPLACE : ADD145 if (origValue === value && op === REPLACE) return146 const path = basePath.concat(key as any)147 patches.push(op === REMOVE ? {op, path} : {op, path, value})148 inversePatches.push(149 op === ADD150 ? {op: REMOVE, path}151 : op === REMOVEEnsure values in patches are never a draftRenaud Chaputbefore adoption2454a51
lines 152–153why, one step back152 ? {op: ADD, path, value: clonePatchValueIfNeeded(origValue)}153 : {op: REPLACE, path, value: clonePatchValueIfNeeded(origValue)}Merge pull request #536 from immerjs/multi-bundleMichel Weststratebefore adoption0d87fc8
lines 154–292why, one step back154 )155 })156 }157158 function generateSetPatches(159 state: SetState,160 basePath: PatchPath,161 patches: Patch[],162 inversePatches: Patch[]163 ) {164 let {base_, copy_} = state165166 let i = 0167 base_.forEach((value: any) => {168 if (!copy_!.has(value)) {169 const path = basePath.concat([i])170 patches.push({171 op: REMOVE,172 path,173 value174 })175 inversePatches.unshift({176 op: ADD,177 path,178 value179 })180 }181 i++182 })183 i = 0184 copy_!.forEach((value: any) => {185 if (!base_.has(value)) {186 const path = basePath.concat([i])187 patches.push({188 op: ADD,189 path,190 value191 })192 inversePatches.unshift({193 op: REMOVE,194 path,195 value196 })197 }198 i++199 })200 }201202 function generateReplacementPatches_(203 rootState: ImmerState,204 replacement: any,205 patches: Patch[],206 inversePatches: Patch[]207 ): void {208 patches.push({209 op: REPLACE,210 path: [],211 value: replacement212 })213 inversePatches.push({214 op: REPLACE,215 path: [],216 value: rootState.base_217 })218 }219220 function applyPatches_<T>(draft: T, patches: Patch[]): T {221 patches.forEach(patch => {222 const {path, op} = patch223224 let base: any = draft225 for (let i = 0; i < path.length - 1; i++) {226 base = get(base, path[i])227 if (typeof base !== "object") die(15, path.join("/"))228 }229230 const type = getArchtype(base)231 const value = deepClonePatchValue(patch.value) // used to clone patch to ensure original patch is not modified, see #411232 const key = path[path.length - 1]233 switch (op) {234 case REPLACE:235 switch (type) {236 case ArchtypeMap:237 return base.set(key, value)238 /* istanbul ignore next */239 case ArchtypeSet:240 die(16)241 default:242 // if value is an object, then it's assigned by reference243 // in the following add or remove ops, the value field inside the patch will also be modifyed244 // so we use value from the cloned patch245 // @ts-ignore246 return (base[key] = value)247 }248 case ADD:249 switch (type) {250 case ArchtypeArray:251 return base.splice(key as any, 0, value)252 case ArchtypeMap:253 return base.set(key, value)254 case ArchtypeSet:255 return base.add(value)256 default:257 return (base[key] = value)258 }259 case REMOVE:260 switch (type) {261 case ArchtypeArray:262 return base.splice(key as any, 1)263 case ArchtypeMap:264 return base.delete(key)265 case ArchtypeSet:266 return base.delete(patch.value)267 default:268 return delete base[key]269 }270 default:271 die(17, op)272 }273 })274275 return draft276 }277278 // optimize: this is quite a performance hit, can we detect intelligently when it is needed?279 // E.g. auto-draft when new objects from outside are assigned and modified?280 // (See failing test when deepClone just returns obj)281 function deepClonePatchValue<T>(obj: T): T282 function deepClonePatchValue(obj: any) {283 if (!obj || typeof obj !== "object") return obj284 if (Array.isArray(obj)) return obj.map(deepClonePatchValue)285 if (isMap(obj))286 return new Map(287 Array.from(obj.entries()).map(([k, v]) => [k, deepClonePatchValue(v)])288 )289 if (isSet(obj)) return new Set(Array.from(obj).map(deepClonePatchValue))290 const cloned = Object.create(Object.getPrototypeOf(obj))291 for (const key in obj) cloned[key] = deepClonePatchValue(obj[key])292 return clonedEnsure values in patches are never a draftRenaud Chaputbefore adoption2454a51
lines 293–298why, one step back293 }294295 function clonePatchValueIfNeeded<T>(obj: T): T {296 if (isDraft(obj)) {297 return deepClonePatchValue(obj)298 } else return objMerge pull request #536 from immerjs/multi-bundleMichel Weststratebefore adoption0d87fc8
lines 299–306why, one step back299 }300301 loadPlugin("Patches", {302 applyPatches_,303 generatePatches_,304 generateReplacementPatches_305 })306}