patches.ts
This file
Path
src/patches.ts
262 lines · 6.0 KiB · TypeScript
Last changed by
fix: Map and Set instantions won't work on certain environments, fixes #502Michel Weststratebefore adoption9f4711a
History of this fileTake it
fix: Map and Set instantions won't work on certain environments, fixes #502Michel Weststratebefore adoption9f4711a
lines 1–18why, one step back1import {2 get,3 each,4 has,5 die,6 getArchtype,7 ImmerState,8 Patch,9 ProxyType,10 SetState,11 ES5ArrayState,12 ProxyArrayState,13 MapState,14 ES5ObjectState,15 ProxyObjectState,16 Archtype,17 isMap18} from "./internal"feat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914
line 19why, one step back19feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8
lines 20–21why, one step back20export type PatchPath = (string | number)[]21feat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914
lines 22–23why, one step back22export function generatePatches(23 state: ImmerState,feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8
line 24why, one step back24 basePath: PatchPath,feat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914
lines 25–26why, one step back25 patches: Patch[],26 inversePatches: Patch[]feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8
lines 27–48why, one step back27): void {28 switch (state.type) {29 case ProxyType.ProxyObject:30 case ProxyType.ES5Object:31 case ProxyType.Map:32 return generatePatchesFromAssigned(33 state,34 basePath,35 patches,36 inversePatches37 )38 case ProxyType.ES5Array:39 case ProxyType.ProxyArray:40 return generateArrayPatches(state, basePath, patches, inversePatches)41 case ProxyType.Set:42 return generateSetPatches(43 (state as any) as SetState,44 basePath,45 patches,46 inversePatches47 )48 }feat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914
lines 49–51why, one step back49}5051function generateArrayPatches(feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8
lines 52–53why, one step back52 state: ES5ArrayState | ProxyArrayState,53 basePath: PatchPath,feat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914
lines 54–56why, one step back54 patches: Patch[],55 inversePatches: Patch[]56) {feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8
lines 57–59why, one step back57 let {base, assigned, copy} = state58 /* istanbul ignore next */59 if (!copy) die()feat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914
lines 60–62why, one step back6061 // Reduce complexity by ensuring `base` is never longer.62 if (copy.length < base.length) {feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8
line 63why, one step back63 // @ts-ignorefeat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914
lines 64–117why, one step back64 ;[base, copy] = [copy, base]65 ;[patches, inversePatches] = [inversePatches, patches]66 }6768 const delta = copy.length - base.length6970 // Find the first replaced index.71 let start = 072 while (base[start] === copy[start] && start < base.length) {73 ++start74 }7576 // Find the last replaced index. Search from the end to optimize splice patches.77 let end = base.length78 while (end > start && base[end - 1] === copy[end + delta - 1]) {79 --end80 }8182 // Process replaced indices.83 for (let i = start; i < end; ++i) {84 if (assigned[i] && copy[i] !== base[i]) {85 const path = basePath.concat([i])86 patches.push({87 op: "replace",88 path,89 value: copy[i]90 })91 inversePatches.push({92 op: "replace",93 path,94 value: base[i]95 })96 }97 }9899 const replaceCount = patches.length100101 // Process added indices.102 for (let i = end + delta - 1; i >= end; --i) {103 const path = basePath.concat([i])104 patches[replaceCount + i - end] = {105 op: "add",106 path,107 value: copy[i]108 }109 inversePatches.push({110 op: "remove",111 path112 })113 }114}115116// This is used for both Map objects and normal objects.117function generatePatchesFromAssigned(feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8
lines 118–119why, one step back118 state: MapState | ES5ObjectState | ProxyObjectState,119 basePath: PatchPath,feat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914
lines 120–123why, one step back120 patches: Patch[],121 inversePatches: Patch[]122) {123 const {base, copy} = statefeat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8
line 124why, one step back124 each(state.assigned!, (key, assignedValue) => {feat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914
line 125why, one step back125 const origValue = get(base, key)feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8
line 126why, one step back126 const value = get(copy!, key)feat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914
lines 127–141why, one step back127 const op = !assignedValue ? "remove" : has(base, key) ? "replace" : "add"128 if (origValue === value && op === "replace") return129 const path = basePath.concat(key as any)130 patches.push(op === "remove" ? {op, path} : {op, path, value})131 inversePatches.push(132 op === "add"133 ? {op: "remove", path}134 : op === "remove"135 ? {op: "add", path, value: origValue}136 : {op: "replace", path, value: origValue}137 )138 })139}140141function generateSetPatches(feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8
lines 142–143why, one step back142 state: SetState,143 basePath: PatchPath,feat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914
lines 144–150why, one step back144 patches: Patch[],145 inversePatches: Patch[]146) {147 let {base, copy} = state148149 let i = 0150 base.forEach(value => {feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8
line 151why, one step back151 if (!copy!.has(value)) {feat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914
lines 152–166why, one step back152 const path = basePath.concat([i])153 patches.push({154 op: "remove",155 path,156 value157 })158 inversePatches.unshift({159 op: "add",160 path,161 value162 })163 }164 i++165 })166 i = 0feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8
line 167why, one step back167 copy!.forEach(value => {feat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914
lines 168–188why, one step back168 if (!base.has(value)) {169 const path = basePath.concat([i])170 patches.push({171 op: "add",172 path,173 value174 })175 inversePatches.unshift({176 op: "remove",177 path,178 value179 })180 }181 i++182 })183}184185export function applyPatches<T>(draft: T, patches: Patch[]): T {186 patches.forEach(patch => {187 const {path, op} = patch188feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8
lines 189–190why, one step back189 /* istanbul ignore next */190 if (!path.length) die()feat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914
line 191why, one step back191feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8
line 192why, one step back192 let base: any = draftfeat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914
lines 193–198why, one step back193 for (let i = 0; i < path.length - 1; i++) {194 base = get(base, path[i])195 if (!base || typeof base !== "object")196 throw new Error("Cannot apply patch, path doesn't resolve: " + path.join("/")) // prettier-ignore197 }198feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8
lines 199–200why, one step back199 const type = getArchtype(base)200 const value = deepClonePatchValue(patch.value) // used to clone patch to ensure original patch is not modified, see #411feat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914
lines 201–203why, one step back201 const key = path[path.length - 1]202 switch (op) {203 case "replace":feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8
lines 204–215why, one step back204 switch (type) {205 case Archtype.Map:206 return base.set(key, value)207 /* istanbul ignore next */208 case Archtype.Set:209 throw new Error('Sets cannot have "replace" patches.')210 default:211 // if value is an object, then it's assigned by reference212 // in the following add or remove ops, the value field inside the patch will also be modifyed213 // so we use value from the cloned patch214 // @ts-ignore215 return (base[key] = value)feat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914
lines 216–217why, one step back216 }217 case "add":feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8
lines 218–226why, one step back218 switch (type) {219 case Archtype.Array:220 return base.splice(key as any, 0, value)221 case Archtype.Map:222 return base.set(key, value)223 case Archtype.Set:224 return base.add(value)225 default:226 return (base[key] = value)feat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914
lines 227–228why, one step back227 }228 case "remove":feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8
lines 229–238why, one step back229 switch (type) {230 case Archtype.Array:231 return base.splice(key as any, 1)232 case Archtype.Map:233 return base.delete(key)234 case Archtype.Set:235 return base.delete(patch.value)236 default:237 return delete base[key]238 }feat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914
lines 239–244why, one step back239 default:240 throw new Error("Unsupported patch operation: " + op)241 }242 })243244 return draftfeat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8
lines 245–261why, one step back245}246247// TODO: optimize: this is quite a performance hit, can we detect intelligently when it is needed?248// E.g. auto-draft when new objects from outside are assigned and modified?249// (See failing test when deepClone just returns obj)250function deepClonePatchValue<T>(obj: T): T251function deepClonePatchValue(obj: any) {252 if (!obj || typeof obj !== "object") return obj253 if (Array.isArray(obj)) return obj.map(deepClonePatchValue)254 if (isMap(obj))255 return new Map(256 Array.from(obj.entries()).map(([k, v]) => [k, deepClonePatchValue(v)])257 )258 // Not needed: if (isSet(obj)) return new Set(Array.from(obj.values()).map(deepClone))259 const cloned = Object.create(Object.getPrototypeOf(obj))260 for (const key in obj) cloned[key] = deepClonePatchValue(obj[key])261 return clonedfeat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914
line 262why, one step back262}