es5.ts
This file
Path
src/plugins/es5.ts
348 lines · 10.3 KiB · TypeScript
Last changed by
Reimplement ES5 to work with descriptors rather than valuesMichel Weststratebefore adoptiond0f3a71
History of this fileTake it
Merge pull request #536 from immerjs/multi-bundleMichel Weststratebefore adoption0d87fc8
lines 1–55why, one step back1import {2 ImmerState,3 Drafted,4 ES5ArrayState,5 ES5ObjectState,6 each,7 has,8 isDraft,9 isDraftable,10 shallowCopy,11 latest,12 DRAFT_STATE,13 is,14 loadPlugin,15 ImmerScope,16 createProxy,17 ProxyTypeES5Array,18 ProxyTypeES5Object,19 AnyObject,20 getCurrentScope,21 die22} from "../internal"2324type ES5State = ES5ArrayState | ES5ObjectState2526export function enableES5() {27 function willFinalizeES5_(28 scope: ImmerScope,29 result: any,30 isReplaced: boolean31 ) {32 scope.drafts_!.forEach((draft: any) => {33 ;(draft[DRAFT_STATE] as ES5State).finalizing_ = true34 })35 if (!isReplaced) {36 if (scope.patches_) {37 markChangesRecursively(scope.drafts_![0])38 }39 // This is faster when we don't care about which attributes changed.40 markChangesSweep(scope.drafts_)41 }42 // When a child draft is returned, look for changes.43 else if (44 isDraft(result) &&45 (result[DRAFT_STATE] as ES5State).scope_ === scope46 ) {47 markChangesSweep(scope.drafts_)48 }49 }5051 function createES5Proxy_<T>(52 base: T,53 parent?: ImmerState54 ): Drafted<T, ES5ObjectState | ES5ArrayState> {55 const isArray = Array.isArray(base)Reimplement ES5 to work with descriptors rather than valuesMichel Weststratebefore adoptiond0f3a71
lines 56–61why, one step back56 const baseDescriptors = Object.getOwnPropertyDescriptors(base)57 // Descriptors we want to skip:58 if (isArray) delete baseDescriptors.length59 delete baseDescriptors[DRAFT_STATE as any]60 let draft: any61 const newDescriptors = {}Merge pull request #536 from immerjs/multi-bundleMichel Weststratebefore adoption0d87fc8
line 62why, one step back62Reimplement ES5 to work with descriptors rather than valuesMichel Weststratebefore adoptiond0f3a71
lines 63–78why, one step back63 for (let key in baseDescriptors) {64 // @ts-ignore65 newDescriptors[key] = proxyProperty(66 key,67 // @ts-ignore68 isArray || baseDescriptors[key].enumerable69 )70 }71 if (isArray) {72 // @ts-ignore73 draft = new Array(base.length)74 // @ts-ignore75 Object.defineProperties(draft, newDescriptors)76 } else {77 draft = Object.create(Object.getPrototypeOf(base), newDescriptors)78 }Merge pull request #536 from immerjs/multi-bundleMichel Weststratebefore adoption0d87fc8
lines 79–151why, one step back7980 const state: ES5ObjectState | ES5ArrayState = {81 type_: isArray ? ProxyTypeES5Array : (ProxyTypeES5Object as any),82 scope_: parent ? parent.scope_ : getCurrentScope(),83 modified_: false,84 finalizing_: false,85 finalized_: false,86 assigned_: {},87 parent_: parent,88 base_: base,89 draft_: draft,90 copy_: null,91 revoked_: false,92 isManual_: false93 }9495 Object.defineProperty(draft, DRAFT_STATE, {96 value: state,97 // enumerable: false <- the default98 writable: true99 })100 return draft101 }102103 // Access a property without creating an Immer draft.104 function peek(draft: Drafted, prop: PropertyKey) {105 const state: ES5State = draft[DRAFT_STATE]106 if (state && !state.finalizing_) {107 state.finalizing_ = true108 const value = draft[prop]109 state.finalizing_ = false110 return value111 }112 return draft[prop]113 }114115 function get(state: ES5State, prop: string | number) {116 assertUnrevoked(state)117 const value = peek(latest(state), prop)118 if (state.finalizing_) return value119 // Create a draft if the value is unmodified.120 if (value === peek(state.base_, prop) && isDraftable(value)) {121 prepareCopy(state)122 // @ts-ignore123 return (state.copy_![prop] = createProxy(124 state.scope_.immer_,125 value,126 state127 ))128 }129 return value130 }131132 function set(state: ES5State, prop: string | number, value: any) {133 assertUnrevoked(state)134 state.assigned_[prop] = true135 if (!state.modified_) {136 if (is(value, peek(latest(state), prop))) return137 markChangedES5_(state)138 prepareCopy(state)139 }140 // @ts-ignore141 state.copy_![prop] = value142 }143144 function markChangedES5_(state: ImmerState) {145 if (!state.modified_) {146 state.modified_ = true147 if (state.parent_) markChangedES5_(state.parent_)148 }149 }150151 function prepareCopy(state: ES5State) {Reimplement ES5 to work with descriptors rather than valuesMichel Weststratebefore adoptiond0f3a71
lines 152–158why, one step back152 if (state.copy_) return153 const stateofBase: ES5State | undefined = (state.base_ as any)[DRAFT_STATE]154 // make a copy, if the base is a draft itself, we take a copy of it's current state155 state.copy_ = shallowCopy(156 stateofBase ? latest(stateofBase) : state.base_,157 true158 )Merge pull request #536 from immerjs/multi-bundleMichel Weststratebefore adoption0d87fc8
lines 159–160why, one step back159 }160Reimplement ES5 to work with descriptors rather than valuesMichel Weststratebefore adoptiond0f3a71
lines 161–179why, one step back161 function createFinalCopy_(state: ES5ArrayState | ES5ObjectState): any {162 if (state.type_ === ProxyTypeES5Array) return state.draft_?.slice()163 // We create a final copy, based on the keys present in the draft.164 // However, since most draft keys are wrapped getters, so lets take the descriptor of the copy165 // so that any getters can be preserved (if present)166 const final = Object.create(Object.getPrototypeOf(state.draft_))167 // TODO: extract utils for getPrototypeOf / getOwnPropertyDescriptors168 const draftDescriptors = Object.getOwnPropertyDescriptors(state.draft_)169 const copyDescriptors = Object.getOwnPropertyDescriptors(latest(state))170 for (let key in draftDescriptors) {171 // @ts-ignore172 if (key === DRAFT_STATE) return173 const desc = draftDescriptors[key]174 // if there is a value in the descriptor, it was deleted and readded, so respect the draft one175 Object.defineProperty(176 final,177 key,178 "value" in desc ? desc : copyDescriptors[key] || desc179 )Merge pull request #536 from immerjs/multi-bundleMichel Weststratebefore adoption0d87fc8
line 180why, one step back180 }Reimplement ES5 to work with descriptors rather than valuesMichel Weststratebefore adoptiond0f3a71
line 181why, one step back181 return finalMerge pull request #536 from immerjs/multi-bundleMichel Weststratebefore adoption0d87fc8
lines 182–190why, one step back182 }183184 // property descriptors are recycled to make sure we don't create a get and set closure per property,185 // but share them all instead186 const descriptors: {[prop: string]: PropertyDescriptor} = {}187188 function proxyProperty(189 prop: string | number,190 enumerable: booleanReimplement ES5 to work with descriptors rather than valuesMichel Weststratebefore adoptiond0f3a71
line 191why, one step back191 ): PropertyDescriptor {Merge pull request #536 from immerjs/multi-bundleMichel Weststratebefore adoption0d87fc8
lines 192–196why, one step back192 let desc = descriptors[prop]193 if (desc) {194 desc.enumerable = enumerable195 } else {196 descriptors[prop] = desc = {Reimplement ES5 to work with descriptors rather than valuesMichel Weststratebefore adoptiond0f3a71
line 197why, one step back197 configurable: true,Merge pull request #536 from immerjs/multi-bundleMichel Weststratebefore adoption0d87fc8
lines 198–206why, one step back198 enumerable,199 get(this: any) {200 return get(this[DRAFT_STATE], prop)201 },202 set(this: any, value) {203 set(this[DRAFT_STATE], prop, value)204 }205 }206 }Reimplement ES5 to work with descriptors rather than valuesMichel Weststratebefore adoptiond0f3a71
line 207why, one step back207 return descMerge pull request #536 from immerjs/multi-bundleMichel Weststratebefore adoption0d87fc8
lines 208–344why, one step back208 }209210 // This looks expensive, but only proxies are visited, and only objects without known changes are scanned.211 function markChangesSweep(drafts: Drafted<any, ImmerState>[]) {212 // The natural order of drafts in the `scope` array is based on when they213 // were accessed. By processing drafts in reverse natural order, we have a214 // better chance of processing leaf nodes first. When a leaf node is known to215 // have changed, we can avoid any traversal of its ancestor nodes.216 for (let i = drafts.length - 1; i >= 0; i--) {217 const state: ES5State = drafts[i][DRAFT_STATE]218 if (!state.modified_) {219 switch (state.type_) {220 case ProxyTypeES5Array:221 if (hasArrayChanges(state)) markChangedES5_(state)222 break223 case ProxyTypeES5Object:224 if (hasObjectChanges(state)) markChangedES5_(state)225 break226 }227 }228 }229 }230231 function markChangesRecursively(object: any) {232 if (!object || typeof object !== "object") return233 const state: ES5State | undefined = object[DRAFT_STATE]234 if (!state) return235 const {base_, draft_, assigned_, type_} = state236 if (type_ === ProxyTypeES5Object) {237 // Look for added keys.238 // TODO: looks quite duplicate to hasObjectChanges,239 // probably there is a faster way to detect changes, as sweep + recurse seems to do some240 // unnecessary work.241 // also: probably we can store the information we detect here, to speed up tree finalization!242 each(draft_, key => {243 if ((key as any) === DRAFT_STATE) return244 // The `undefined` check is a fast path for pre-existing keys.245 if ((base_ as any)[key] === undefined && !has(base_, key)) {246 assigned_[key] = true247 markChangedES5_(state)248 } else if (!assigned_[key]) {249 // Only untouched properties trigger recursion.250 markChangesRecursively(draft_[key])251 }252 })253 // Look for removed keys.254 each(base_, key => {255 // The `undefined` check is a fast path for pre-existing keys.256 if (draft_[key] === undefined && !has(draft_, key)) {257 assigned_[key] = false258 markChangedES5_(state)259 }260 })261 } else if (type_ === ProxyTypeES5Array) {262 if (hasArrayChanges(state as ES5ArrayState)) {263 markChangedES5_(state)264 assigned_.length = true265 }266267 if (draft_.length < base_.length) {268 for (let i = draft_.length; i < base_.length; i++) assigned_[i] = false269 } else {270 for (let i = base_.length; i < draft_.length; i++) assigned_[i] = true271 }272273 // Minimum count is enough, the other parts has been processed.274 const min = Math.min(draft_.length, base_.length)275276 for (let i = 0; i < min; i++) {277 // Only untouched indices trigger recursion.278 if (assigned_[i] === undefined) markChangesRecursively(draft_[i])279 }280 }281 }282283 function hasObjectChanges(state: ES5ObjectState) {284 const {base_, draft_} = state285286 // Search for added keys and changed keys. Start at the back, because287 // non-numeric keys are ordered by time of definition on the object.288 const keys = Object.keys(draft_)289 for (let i = keys.length - 1; i >= 0; i--) {290 const key = keys[i]291 const baseValue = base_[key]292 // The `undefined` check is a fast path for pre-existing keys.293 if (baseValue === undefined && !has(base_, key)) {294 return true295 }296 // Once a base key is deleted, future changes go undetected, because its297 // descriptor is erased. This branch detects any missed changes.298 else {299 const value = draft_[key]300 const state: ImmerState = value && value[DRAFT_STATE]301 if (state ? state.base_ !== baseValue : !is(value, baseValue)) {302 return true303 }304 }305 }306307 // At this point, no keys were added or changed.308 // Compare key count to determine if keys were deleted.309 return keys.length !== Object.keys(base_).length310 }311312 function hasArrayChanges(state: ES5ArrayState) {313 const {draft_} = state314 if (draft_.length !== state.base_.length) return true315 // See #116316 // If we first shorten the length, our array interceptors will be removed.317 // If after that new items are added, result in the same original length,318 // those last items will have no intercepting property.319 // So if there is no own descriptor on the last position, we know that items were removed and added320 // N.B.: splice, unshift, etc only shift values around, but not prop descriptors, so we only have to check321 // the last one322 const descriptor = Object.getOwnPropertyDescriptor(323 draft_,324 draft_.length - 1325 )326 // descriptor can be null, but only for newly created sparse arrays, eg. new Array(10)327 if (descriptor && !descriptor.get) return true328 // For all other cases, we don't have to compare, as they would have been picked up by the index setters329 return false330 }331332 /*#__PURE__*/333 function isEnumerable(base: AnyObject, prop: PropertyKey): boolean {334 const desc = Object.getOwnPropertyDescriptor(base, prop)335 return desc && desc.enumerable ? true : false336 }337338 function assertUnrevoked(state: any /*ES5State | MapState | SetState*/) {339 if (state.revoked_) die(3, JSON.stringify(latest(state)))340 }341342 loadPlugin("ES5", {343 createES5Proxy_,344 markChangedES5_,Reimplement ES5 to work with descriptors rather than valuesMichel Weststratebefore adoptiond0f3a71
lines 345–346why, one step back345 willFinalizeES5_,346 createFinalCopy_Merge pull request #536 from immerjs/multi-bundleMichel Weststratebefore adoption0d87fc8
lines 347–348why, one step back347 })348}