patches.ts
This file
Path
src/plugins/patches.ts
295 lines · 6.6 KiB · TypeScript
Last changed by
Merge pull request #536 from immerjs/multi-bundleMichel Weststratebefore adoption0d87fc8
History of this fileTake it
Merge pull request #536 from immerjs/multi-bundleMichel Weststratebefore adoption0d87fc8
lines 1–295why, 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"2930export function enablePatches() {31 const REPLACE = "replace"32 const ADD = "add"33 const REMOVE = "remove"3435 function generatePatches_(36 state: ImmerState,37 basePath: PatchPath,38 patches: Patch[],39 inversePatches: Patch[]40 ): void {41 switch (state.type_) {42 case ProxyTypeProxyObject:43 case ProxyTypeES5Object:44 case ProxyTypeMap:45 return generatePatchesFromAssigned(46 state,47 basePath,48 patches,49 inversePatches50 )51 case ProxyTypeES5Array:52 case ProxyTypeProxyArray:53 return generateArrayPatches(state, basePath, patches, inversePatches)54 case ProxyTypeSet:55 return generateSetPatches(56 (state as any) as SetState,57 basePath,58 patches,59 inversePatches60 )61 }62 }6364 function generateArrayPatches(65 state: ES5ArrayState | ProxyArrayState,66 basePath: PatchPath,67 patches: Patch[],68 inversePatches: Patch[]69 ) {70 let {base_, assigned_} = state71 let copy_ = state.copy_!7273 // Reduce complexity by ensuring `base` is never longer.74 if (copy_.length < base_.length) {75 // @ts-ignore76 ;[base_, copy_] = [copy_, base_]77 ;[patches, inversePatches] = [inversePatches, patches]78 }7980 const delta = copy_.length - base_.length8182 // Find the first replaced index.83 let start = 084 while (base_[start] === copy_[start] && start < base_.length) {85 ++start86 }8788 // Find the last replaced index. Search from the end to optimize splice patches.89 let end = base_.length90 while (end > start && base_[end - 1] === copy_[end + delta - 1]) {91 --end92 }9394 // Process replaced indices.95 for (let i = start; i < end; ++i) {96 if (assigned_[i] && copy_[i] !== base_[i]) {97 const path = basePath.concat([i])98 patches.push({99 op: REPLACE,100 path,101 value: copy_[i]102 })103 inversePatches.push({104 op: REPLACE,105 path,106 value: base_[i]107 })108 }109 }110111 const replaceCount = patches.length112113 // Process added indices.114 for (let i = end + delta - 1; i >= end; --i) {115 const path = basePath.concat([i])116 patches[replaceCount + i - end] = {117 op: ADD,118 path,119 value: copy_[i]120 }121 inversePatches.push({122 op: REMOVE,123 path124 })125 }126 }127128 // This is used for both Map objects and normal objects.129 function generatePatchesFromAssigned(130 state: MapState | ES5ObjectState | ProxyObjectState,131 basePath: PatchPath,132 patches: Patch[],133 inversePatches: Patch[]134 ) {135 const {base_, copy_} = state136 each(state.assigned_!, (key, assignedValue) => {137 const origValue = get(base_, key)138 const value = get(copy_!, key)139 const op = !assignedValue ? REMOVE : has(base_, key) ? REPLACE : ADD140 if (origValue === value && op === REPLACE) return141 const path = basePath.concat(key as any)142 patches.push(op === REMOVE ? {op, path} : {op, path, value})143 inversePatches.push(144 op === ADD145 ? {op: REMOVE, path}146 : op === REMOVE147 ? {op: ADD, path, value: origValue}148 : {op: REPLACE, path, value: origValue}149 )150 })151 }152153 function generateSetPatches(154 state: SetState,155 basePath: PatchPath,156 patches: Patch[],157 inversePatches: Patch[]158 ) {159 let {base_, copy_} = state160161 let i = 0162 base_.forEach((value: any) => {163 if (!copy_!.has(value)) {164 const path = basePath.concat([i])165 patches.push({166 op: REMOVE,167 path,168 value169 })170 inversePatches.unshift({171 op: ADD,172 path,173 value174 })175 }176 i++177 })178 i = 0179 copy_!.forEach((value: any) => {180 if (!base_.has(value)) {181 const path = basePath.concat([i])182 patches.push({183 op: ADD,184 path,185 value186 })187 inversePatches.unshift({188 op: REMOVE,189 path,190 value191 })192 }193 i++194 })195 }196197 function generateReplacementPatches_(198 rootState: ImmerState,199 replacement: any,200 patches: Patch[],201 inversePatches: Patch[]202 ): void {203 patches.push({204 op: REPLACE,205 path: [],206 value: replacement207 })208 inversePatches.push({209 op: REPLACE,210 path: [],211 value: rootState.base_212 })213 }214215 function applyPatches_<T>(draft: T, patches: Patch[]): T {216 patches.forEach(patch => {217 const {path, op} = patch218219 let base: any = draft220 for (let i = 0; i < path.length - 1; i++) {221 base = get(base, path[i])222 if (typeof base !== "object") die(15, path.join("/"))223 }224225 const type = getArchtype(base)226 const value = deepClonePatchValue(patch.value) // used to clone patch to ensure original patch is not modified, see #411227 const key = path[path.length - 1]228 switch (op) {229 case REPLACE:230 switch (type) {231 case ArchtypeMap:232 return base.set(key, value)233 /* istanbul ignore next */234 case ArchtypeSet:235 die(16)236 default:237 // if value is an object, then it's assigned by reference238 // in the following add or remove ops, the value field inside the patch will also be modifyed239 // so we use value from the cloned patch240 // @ts-ignore241 return (base[key] = value)242 }243 case ADD:244 switch (type) {245 case ArchtypeArray:246 return base.splice(key as any, 0, value)247 case ArchtypeMap:248 return base.set(key, value)249 case ArchtypeSet:250 return base.add(value)251 default:252 return (base[key] = value)253 }254 case REMOVE:255 switch (type) {256 case ArchtypeArray:257 return base.splice(key as any, 1)258 case ArchtypeMap:259 return base.delete(key)260 case ArchtypeSet:261 return base.delete(patch.value)262 default:263 return delete base[key]264 }265 default:266 die(17, op)267 }268 })269270 return draft271 }272273 // optimize: this is quite a performance hit, can we detect intelligently when it is needed?274 // E.g. auto-draft when new objects from outside are assigned and modified?275 // (See failing test when deepClone just returns obj)276 function deepClonePatchValue<T>(obj: T): T277 function deepClonePatchValue(obj: any) {278 if (!obj || typeof obj !== "object") return obj279 if (Array.isArray(obj)) return obj.map(deepClonePatchValue)280 if (isMap(obj))281 return new Map(282 Array.from(obj.entries()).map(([k, v]) => [k, deepClonePatchValue(v)])283 )284 if (isSet(obj)) return new Set(Array.from(obj).map(deepClonePatchValue))285 const cloned = Object.create(Object.getPrototypeOf(obj))286 for (const key in obj) cloned[key] = deepClonePatchValue(obj[key])287 return cloned288 }289290 loadPlugin("Patches", {291 applyPatches_,292 generatePatches_,293 generateReplacementPatches_294 })295}