es5.ts
This file
Path
src/plugins/es5.ts
313 lines · 8.9 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–313why, one step back1import {2 ImmerState,3 Drafted,4 Objectish,5 ES5ArrayState,6 ES5ObjectState,7 each,8 has,9 isDraft,10 isDraftable,11 shallowCopy,12 latest,13 DRAFT_STATE,14 is,15 loadPlugin,16 ImmerScope,17 createProxy,18 ProxyTypeES5Array,19 ProxyTypeES5Object,20 AnyObject,21 getCurrentScope,22 die23} from "../internal"2425type ES5State = ES5ArrayState | ES5ObjectState2627export function enableES5() {28 function willFinalizeES5_(29 scope: ImmerScope,30 result: any,31 isReplaced: boolean32 ) {33 scope.drafts_!.forEach((draft: any) => {34 ;(draft[DRAFT_STATE] as ES5State).finalizing_ = true35 })36 if (!isReplaced) {37 if (scope.patches_) {38 markChangesRecursively(scope.drafts_![0])39 }40 // This is faster when we don't care about which attributes changed.41 markChangesSweep(scope.drafts_)42 }43 // When a child draft is returned, look for changes.44 else if (45 isDraft(result) &&46 (result[DRAFT_STATE] as ES5State).scope_ === scope47 ) {48 markChangesSweep(scope.drafts_)49 }50 }5152 function createES5Proxy_<T>(53 base: T,54 parent?: ImmerState55 ): Drafted<T, ES5ObjectState | ES5ArrayState> {56 const isArray = Array.isArray(base)57 const draft: any = clonePotentialDraft(base)5859 each(draft, prop => {60 proxyProperty(draft, prop, isArray || isEnumerable(base, prop))61 })6263 const state: ES5ObjectState | ES5ArrayState = {64 type_: isArray ? ProxyTypeES5Array : (ProxyTypeES5Object as any),65 scope_: parent ? parent.scope_ : getCurrentScope(),66 modified_: false,67 finalizing_: false,68 finalized_: false,69 assigned_: {},70 parent_: parent,71 base_: base,72 draft_: draft,73 copy_: null,74 revoked_: false,75 isManual_: false76 }7778 Object.defineProperty(draft, DRAFT_STATE, {79 value: state,80 // enumerable: false <- the default81 writable: true82 })83 return draft84 }8586 // Access a property without creating an Immer draft.87 function peek(draft: Drafted, prop: PropertyKey) {88 const state: ES5State = draft[DRAFT_STATE]89 if (state && !state.finalizing_) {90 state.finalizing_ = true91 const value = draft[prop]92 state.finalizing_ = false93 return value94 }95 return draft[prop]96 }9798 function get(state: ES5State, prop: string | number) {99 assertUnrevoked(state)100 const value = peek(latest(state), prop)101 if (state.finalizing_) return value102 // Create a draft if the value is unmodified.103 if (value === peek(state.base_, prop) && isDraftable(value)) {104 prepareCopy(state)105 // @ts-ignore106 return (state.copy_![prop] = createProxy(107 state.scope_.immer_,108 value,109 state110 ))111 }112 return value113 }114115 function set(state: ES5State, prop: string | number, value: any) {116 assertUnrevoked(state)117 state.assigned_[prop] = true118 if (!state.modified_) {119 if (is(value, peek(latest(state), prop))) return120 markChangedES5_(state)121 prepareCopy(state)122 }123 // @ts-ignore124 state.copy_![prop] = value125 }126127 function markChangedES5_(state: ImmerState) {128 if (!state.modified_) {129 state.modified_ = true130 if (state.parent_) markChangedES5_(state.parent_)131 }132 }133134 function prepareCopy(state: ES5State) {135 if (!state.copy_) state.copy_ = clonePotentialDraft(state.base_)136 }137138 function clonePotentialDraft(base: Objectish) {139 const state: ES5State | undefined = base && (base as any)[DRAFT_STATE]140 if (state) {141 state.finalizing_ = true142 const draft = shallowCopy(state.draft_, true)143 state.finalizing_ = false144 return draft145 }146 return shallowCopy(base)147 }148149 // property descriptors are recycled to make sure we don't create a get and set closure per property,150 // but share them all instead151 const descriptors: {[prop: string]: PropertyDescriptor} = {}152153 function proxyProperty(154 draft: Drafted<any, ES5State>,155 prop: string | number,156 enumerable: boolean157 ) {158 let desc = descriptors[prop]159 if (desc) {160 desc.enumerable = enumerable161 } else {162 descriptors[prop] = desc = {163 // configurable: true,164 enumerable,165 get(this: any) {166 return get(this[DRAFT_STATE], prop)167 },168 set(this: any, value) {169 set(this[DRAFT_STATE], prop, value)170 }171 }172 }173 Object.defineProperty(draft, prop, desc)174 }175176 // This looks expensive, but only proxies are visited, and only objects without known changes are scanned.177 function markChangesSweep(drafts: Drafted<any, ImmerState>[]) {178 // The natural order of drafts in the `scope` array is based on when they179 // were accessed. By processing drafts in reverse natural order, we have a180 // better chance of processing leaf nodes first. When a leaf node is known to181 // have changed, we can avoid any traversal of its ancestor nodes.182 for (let i = drafts.length - 1; i >= 0; i--) {183 const state: ES5State = drafts[i][DRAFT_STATE]184 if (!state.modified_) {185 switch (state.type_) {186 case ProxyTypeES5Array:187 if (hasArrayChanges(state)) markChangedES5_(state)188 break189 case ProxyTypeES5Object:190 if (hasObjectChanges(state)) markChangedES5_(state)191 break192 }193 }194 }195 }196197 function markChangesRecursively(object: any) {198 if (!object || typeof object !== "object") return199 const state: ES5State | undefined = object[DRAFT_STATE]200 if (!state) return201 const {base_, draft_, assigned_, type_} = state202 if (type_ === ProxyTypeES5Object) {203 // Look for added keys.204 // TODO: looks quite duplicate to hasObjectChanges,205 // probably there is a faster way to detect changes, as sweep + recurse seems to do some206 // unnecessary work.207 // also: probably we can store the information we detect here, to speed up tree finalization!208 each(draft_, key => {209 if ((key as any) === DRAFT_STATE) return210 // The `undefined` check is a fast path for pre-existing keys.211 if ((base_ as any)[key] === undefined && !has(base_, key)) {212 assigned_[key] = true213 markChangedES5_(state)214 } else if (!assigned_[key]) {215 // Only untouched properties trigger recursion.216 markChangesRecursively(draft_[key])217 }218 })219 // Look for removed keys.220 each(base_, key => {221 // The `undefined` check is a fast path for pre-existing keys.222 if (draft_[key] === undefined && !has(draft_, key)) {223 assigned_[key] = false224 markChangedES5_(state)225 }226 })227 } else if (type_ === ProxyTypeES5Array) {228 if (hasArrayChanges(state as ES5ArrayState)) {229 markChangedES5_(state)230 assigned_.length = true231 }232233 if (draft_.length < base_.length) {234 for (let i = draft_.length; i < base_.length; i++) assigned_[i] = false235 } else {236 for (let i = base_.length; i < draft_.length; i++) assigned_[i] = true237 }238239 // Minimum count is enough, the other parts has been processed.240 const min = Math.min(draft_.length, base_.length)241242 for (let i = 0; i < min; i++) {243 // Only untouched indices trigger recursion.244 if (assigned_[i] === undefined) markChangesRecursively(draft_[i])245 }246 }247 }248249 function hasObjectChanges(state: ES5ObjectState) {250 const {base_, draft_} = state251252 // Search for added keys and changed keys. Start at the back, because253 // non-numeric keys are ordered by time of definition on the object.254 const keys = Object.keys(draft_)255 for (let i = keys.length - 1; i >= 0; i--) {256 const key = keys[i]257 const baseValue = base_[key]258 // The `undefined` check is a fast path for pre-existing keys.259 if (baseValue === undefined && !has(base_, key)) {260 return true261 }262 // Once a base key is deleted, future changes go undetected, because its263 // descriptor is erased. This branch detects any missed changes.264 else {265 const value = draft_[key]266 const state: ImmerState = value && value[DRAFT_STATE]267 if (state ? state.base_ !== baseValue : !is(value, baseValue)) {268 return true269 }270 }271 }272273 // At this point, no keys were added or changed.274 // Compare key count to determine if keys were deleted.275 return keys.length !== Object.keys(base_).length276 }277278 function hasArrayChanges(state: ES5ArrayState) {279 const {draft_} = state280 if (draft_.length !== state.base_.length) return true281 // See #116282 // If we first shorten the length, our array interceptors will be removed.283 // If after that new items are added, result in the same original length,284 // those last items will have no intercepting property.285 // So if there is no own descriptor on the last position, we know that items were removed and added286 // N.B.: splice, unshift, etc only shift values around, but not prop descriptors, so we only have to check287 // the last one288 const descriptor = Object.getOwnPropertyDescriptor(289 draft_,290 draft_.length - 1291 )292 // descriptor can be null, but only for newly created sparse arrays, eg. new Array(10)293 if (descriptor && !descriptor.get) return true294 // For all other cases, we don't have to compare, as they would have been picked up by the index setters295 return false296 }297298 /*#__PURE__*/299 function isEnumerable(base: AnyObject, prop: PropertyKey): boolean {300 const desc = Object.getOwnPropertyDescriptor(base, prop)301 return desc && desc.enumerable ? true : false302 }303304 function assertUnrevoked(state: any /*ES5State | MapState | SetState*/) {305 if (state.revoked_) die(3, JSON.stringify(latest(state)))306 }307308 loadPlugin("ES5", {309 createES5Proxy_,310 markChangedES5_,311 willFinalizeES5_312 })313}