es5.ts
This file
Path
src/es5.ts
354 lines · 9.6 KiB · TypeScript
Last changed by
Some initial cleanupMichel Weststratebefore adoptionc53a75f
History of this fileTake it
Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 1–13why, one step back1"use strict"2import {3 each,4 has,5 is,6 isDraft,7 isDraftable,8 isEnumerable,9 isMap,10 isSet,11 hasSymbol,12 shallowCopy,13 DRAFT_STATE,map unification WIPMichel Weststratebefore adoption9bcefb6
line 14why, one step back14 latestMerge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
line 15why, one step back15} from "./common"added set and iteror stuffMichel Weststratebefore adoption08f4682
lines 16–18why, one step back16import {proxyMap, hasMapChanges} from "./map"17import {proxySet, hasSetChanges} from "./set"18Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 19–21why, one step back19import {ImmerScope} from "./scope"20import {ImmerState} from "./types"21map unification WIPMichel Weststratebefore adoption9bcefb6
line 22why, one step back22export interface ES5Draft {Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 23–26why, one step back23 [DRAFT_STATE]: ES5State24}2526// TODO: merge with ImmerState?map unification WIPMichel Weststratebefore adoption9bcefb6
line 27why, one step back27export interface ES5State<T = any> {Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 28–63why, one step back28 scope: ImmerScope29 modified: boolean30 finalizing: boolean31 finalized: boolean32 assigned: Map<any, any> | {[key: string]: any}33 parent: ES5State34 base: T35 draft: T & ES5Draft36 drafts: Map<any, any> | null37 copy: T | null38 revoke()39 revoked: boolean40}4142export function willFinalize(43 scope: ImmerScope,44 result: any,45 isReplaced: boolean46) {47 scope.drafts!.forEach(draft => {48 draft[DRAFT_STATE].finalizing = true49 })50 if (!isReplaced) {51 if (scope.patches) {52 markChangesRecursively(scope.drafts![0])53 }54 // This is faster when we don't care about which attributes changed.55 markChangesSweep(scope.drafts)56 }57 // When a child draft is returned, look for changes.58 else if (isDraft(result) && result[DRAFT_STATE].scope === scope) {59 markChangesSweep(scope.drafts)60 }61}6263export function createProxy<T>(base: T, parent: ES5State): ES5Draft {fixed most testsMichel Weststratebefore adoption385c0a4
lines 64–67why, one step back64 if (!base || typeof base !== "object" || !isDraftable(base)) {65 // TODO: || isDraft ?66 return base as any // TODO: fix67 }basic map tests succeedingMichel Weststratebefore adoption735c402
lines 68–73why, one step back68 const scope = parent ? parent.scope : ImmerScope.current!69 if (isMap(base)) {70 const draft = proxyMap(base, parent) as any // TODO: typefix71 scope.drafts.push(draft)72 return draft73 }added set and iteror stuffMichel Weststratebefore adoption08f4682
lines 74–78why, one step back74 if (isSet(base)) {75 const draft = proxySet(base, parent) as any // TODO: typefix76 scope.drafts.push(draft)77 return draft78 }basic map tests succeedingMichel Weststratebefore adoption735c402
line 79why, one step back79Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 80–82why, one step back80 const isArray = Array.isArray(base)81 const draft = clonePotentialDraft(base)82added set and iteror stuffMichel Weststratebefore adoption08f4682
lines 83–85why, one step back83 each(draft, prop => {84 proxyProperty(draft, prop, isArray || isEnumerable(base, prop))85 })Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 86–110why, one step back8687 const state: ES5State<T> = {88 scope,89 modified: false,90 finalizing: false, // es5 only91 finalized: false,92 assigned: isMap(base) ? new Map() : {},93 parent,94 base,95 draft,96 drafts: isSet(base) ? new Map() : null,97 copy: null,98 revoke,99 revoked: false // es5 only100 }101102 createHiddenProperty(draft, DRAFT_STATE, state)103 scope.drafts!.push(draft)104 return draft105}106107function revoke(this: ES5State) {108 this.revoked = true109}110basic map tests succeedingMichel Weststratebefore adoption735c402
line 111why, one step back111// TODO: type these methodsMerge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 112–135why, one step back112// Access a property without creating an Immer draft.113function peek(draft, prop) {114 const state = draft[DRAFT_STATE]115 if (state && !state.finalizing) {116 state.finalizing = true117 const value = draft[prop]118 state.finalizing = false119 return value120 }121 return draft[prop]122}123124function get(state, prop) {125 assertUnrevoked(state)126 const value = peek(latest(state), prop)127 if (state.finalizing) return value128 // Create a draft if the value is unmodified.129 if (value === peek(state.base, prop) && isDraftable(value)) {130 prepareCopy(state)131 return (state.copy[prop] = createProxy(value, state))132 }133 return value134}135basic map tests succeedingMichel Weststratebefore adoption735c402
line 136why, one step back136function set(state: ES5State, prop, value) {Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 137–154why, one step back137 assertUnrevoked(state)138 state.assigned[prop] = true139 if (!state.modified) {140 if (is(value, peek(latest(state), prop))) return141 markChanged(state)142 prepareCopy(state)143 }144 state.copy[prop] = value145}146147export function markChanged(state) {148 if (!state.modified) {149 state.modified = true150 if (state.parent) markChanged(state.parent)151 }152}153154// TODO: kill exportbasic map tests succeedingMichel Weststratebefore adoption735c402
line 155why, one step back155function prepareCopy(state) {Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 156–192why, one step back156 if (!state.copy) state.copy = clonePotentialDraft(state.base)157}158159function clonePotentialDraft(base) {160 const state = base && base[DRAFT_STATE]161 if (state) {162 state.finalizing = true163 const draft = shallowCopy(state.draft, true)164 state.finalizing = false165 return draft166 }167 return shallowCopy(base)168}169170// property descriptors are recycled to make sure we don't create a get and set closure per property,171// but share them all instead172const descriptors = {}173174function proxyProperty(draft, prop, enumerable) {175 let desc = descriptors[prop]176 if (desc) {177 desc.enumerable = enumerable178 } else {179 descriptors[prop] = desc = {180 configurable: true,181 enumerable,182 get() {183 return get(this[DRAFT_STATE], prop)184 },185 set(value) {186 set(this[DRAFT_STATE], prop, value)187 }188 }189 }190 Object.defineProperty(draft, prop, desc)191}192map unification WIPMichel Weststratebefore adoption9bcefb6
line 193why, one step back193export function assertUnrevoked(state) {Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 194–222why, one step back194 if (state.revoked === true)195 throw new Error(196 "Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? " +197 JSON.stringify(latest(state))198 )199}200201// This looks expensive, but only proxies are visited, and only objects without known changes are scanned.202function markChangesSweep(drafts) {203 // The natural order of drafts in the `scope` array is based on when they204 // were accessed. By processing drafts in reverse natural order, we have a205 // better chance of processing leaf nodes first. When a leaf node is known to206 // have changed, we can avoid any traversal of its ancestor nodes.207 for (let i = drafts.length - 1; i >= 0; i--) {208 const state = drafts[i][DRAFT_STATE]209 if (!state.modified) {210 if (Array.isArray(state.base)) {211 if (hasArrayChanges(state)) markChanged(state)212 } else if (isMap(state.base)) {213 if (hasMapChanges(state)) markChanged(state)214 } else if (isSet(state.base)) {215 if (hasSetChanges(state)) markChanged(state)216 } else if (hasObjectChanges(state)) {217 markChanged(state)218 }219 }220 }221}222added set and iteror stuffMichel Weststratebefore adoption08f4682
lines 223–224why, one step back223// TODO: refactor this to work per object-type224// TODO: Set / Map shouldn't be ES specificMerge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 225–229why, one step back225function markChangesRecursively(object) {226 if (!object || typeof object !== "object") return227 const state = object[DRAFT_STATE]228 if (!state) return229 const {base, draft, assigned} = stateadded set and iteror stuffMichel Weststratebefore adoption08f4682
lines 230–262why, one step back230 if (isSet(object)) {231 if (hasSetChanges(state)) {232 markChanged(state)233 object.forEach(v => {234 markChangesRecursively(v)235 })236 }237 } else if (isMap(object)) {238 // if (hasMapChanges(object)) {239 object.forEach((value, key) => {240 if (assigned && base.get(key) === undefined && !has(base, key)) {241 // TODO: this code seems invalid for Maps!242 assigned.set(key, true)243 markChanged(state)244 } else if (!assigned || !assigned.get(key)) {245 // TODO: === false?246 // Only untouched properties trigger recursion.247 markChangesRecursively(draft.get(key))248 }249 })250 // Look for removed keys.251 // TODO: is this code needed?252 // TODO: use each?253 if (assigned)254 base.forEach((value, key) => {255 // The `undefined` check is a fast path for pre-existing keys.256 if (draft.get(key) === undefined && !has(draft, key)) {257 assigned.set(key, false)258 markChanged(state)259 }260 })261 // }262 } else if (!Array.isArray(object)) {Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
line 263why, one step back263 // Look for added keys.added set and iteror stuffMichel Weststratebefore adoption08f4682
line 264why, one step back264 // TODO: use each?Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 265–267why, one step back265 Object.keys(draft).forEach(key => {266 // The `undefined` check is a fast path for pre-existing keys.267 if (base[key] === undefined && !has(base, key)) {added set and iteror stuffMichel Weststratebefore adoption08f4682
line 268why, one step back268 // TODO: this code seems invalid for Maps!Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 269–271why, one step back269 assigned[key] = true270 markChanged(state)271 } else if (!assigned[key]) {added set and iteror stuffMichel Weststratebefore adoption08f4682
line 272why, one step back272 // TODO: === false ?Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 273–277why, one step back273 // Only untouched properties trigger recursion.274 markChangesRecursively(draft[key])275 }276 })277 // Look for removed keys.added set and iteror stuffMichel Weststratebefore adoption08f4682
lines 278–279why, one step back278 // TODO: is this code needed?279 // TODO: use each?Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 280–354why, one step back280 Object.keys(base).forEach(key => {281 // The `undefined` check is a fast path for pre-existing keys.282 if (draft[key] === undefined && !has(draft, key)) {283 assigned[key] = false284 markChanged(state)285 }286 })287 } else if (hasArrayChanges(state)) {288 markChanged(state)289 assigned.length = true290 if (draft.length < base.length) {291 for (let i = draft.length; i < base.length; i++) assigned[i] = false292 } else {293 for (let i = base.length; i < draft.length; i++) assigned[i] = true294 }295 for (let i = 0; i < draft.length; i++) {296 // Only untouched indices trigger recursion.297 if (assigned[i] === undefined) markChangesRecursively(draft[i])298 }299 }300}301302function hasObjectChanges(state) {303 const {base, draft} = state304305 // Search for added keys and changed keys. Start at the back, because306 // non-numeric keys are ordered by time of definition on the object.307 const keys = Object.keys(draft)308 for (let i = keys.length - 1; i >= 0; i--) {309 const key = keys[i]310 const baseValue = base[key]311 // The `undefined` check is a fast path for pre-existing keys.312 if (baseValue === undefined && !has(base, key)) {313 return true314 }315 // Once a base key is deleted, future changes go undetected, because its316 // descriptor is erased. This branch detects any missed changes.317 else {318 const value = draft[key]319 const state = value && value[DRAFT_STATE]320 if (state ? state.base !== baseValue : !is(value, baseValue)) {321 return true322 }323 }324 }325326 // At this point, no keys were added or changed.327 // Compare key count to determine if keys were deleted.328 return keys.length !== Object.keys(base).length329}330331function hasArrayChanges(state) {332 const {draft} = state333 if (draft.length !== state.base.length) return true334 // See #116335 // If we first shorten the length, our array interceptors will be removed.336 // If after that new items are added, result in the same original length,337 // those last items will have no intercepting property.338 // So if there is no own descriptor on the last position, we know that items were removed and added339 // N.B.: splice, unshift, etc only shift values around, but not prop descriptors, so we only have to check340 // the last one341 const descriptor = Object.getOwnPropertyDescriptor(draft, draft.length - 1)342 // descriptor can be null, but only for newly created sparse arrays, eg. new Array(10)343 if (descriptor && !descriptor.get) return true344 // For all other cases, we don't have to compare, as they would have been picked up by the index setters345 return false346}347348function createHiddenProperty(target, prop, value) {349 Object.defineProperty(target, prop, {350 value: value,351 enumerable: false,352 writable: true353 })354}