Skip to content
Myr

es5.ts

This file

Path

src/es5.ts

469 lines · 11.5 KiB · TypeScript

Last changed by

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

History of this file

Take it

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

lines 1–469why, one step back
1"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,14 iterateMapValues,15 makeIterable,16 makeIterateSetValues17} from "./common"18import {proxyMap, proxySet, hasMapChanges, hasSetChanges} from "./mapset"19import {ImmerScope} from "./scope"20import {ImmerState} from "./types"2122interface ES5Draft {23 [DRAFT_STATE]: ES5State24}2526// TODO: merge with ImmerState?27interface ES5State<T = any> {28 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 {64 const isArray = Array.isArray(base)65 const draft = clonePotentialDraft(base)6667 if (isMap(base)) {68 proxyMap(draft)69 } else if (isSet(base)) {70 proxySet(draft)71 } else {72 each(draft, prop => {73 proxyProperty(draft, prop, isArray || isEnumerable(base, prop))74 })75 }7677 // See "proxy.js" for property documentation.78 const scope = parent ? parent.scope : ImmerScope.current!79 const state: ES5State<T> = {80 scope,81 modified: false,82 finalizing: false, // es5 only83 finalized: false,84 assigned: isMap(base) ? new Map() : {},85 parent,86 base,87 draft,88 drafts: isSet(base) ? new Map() : null,89 copy: null,90 revoke,91 revoked: false // es5 only92 }9394 createHiddenProperty(draft, DRAFT_STATE, state)95 scope.drafts!.push(draft)96 return draft97}9899function revoke(this: ES5State) {100 this.revoked = true101}102103// TODO: remove export104export function latest(state) {105 return state.copy || state.base106}107108// Access a property without creating an Immer draft.109function peek(draft, prop) {110 const state = draft[DRAFT_STATE]111 if (state && !state.finalizing) {112 state.finalizing = true113 const value = draft[prop]114 state.finalizing = false115 return value116 }117 return draft[prop]118}119120function get(state, prop) {121 assertUnrevoked(state)122 const value = peek(latest(state), prop)123 if (state.finalizing) return value124 // Create a draft if the value is unmodified.125 if (value === peek(state.base, prop) && isDraftable(value)) {126 prepareCopy(state)127 return (state.copy[prop] = createProxy(value, state))128 }129 return value130}131132function set(state, prop, value) {133 assertUnrevoked(state)134 state.assigned[prop] = true135 if (!state.modified) {136 if (is(value, peek(latest(state), prop))) return137 markChanged(state)138 prepareCopy(state)139 }140 state.copy[prop] = value141}142143// TODO: kill export144export function markChanged(state) {145 if (!state.modified) {146 state.modified = true147 if (state.parent) markChanged(state.parent)148 }149}150151// TODO: kill export152export function prepareCopy(state) {153 if (!state.copy) state.copy = clonePotentialDraft(state.base)154}155156function clonePotentialDraft(base) {157 const state = base && base[DRAFT_STATE]158 if (state) {159 state.finalizing = true160 const draft = shallowCopy(state.draft, true)161 state.finalizing = false162 return draft163 }164 return shallowCopy(base)165}166167// property descriptors are recycled to make sure we don't create a get and set closure per property,168// but share them all instead169const descriptors = {}170171function proxyProperty(draft, prop, enumerable) {172 let desc = descriptors[prop]173 if (desc) {174 desc.enumerable = enumerable175 } else {176 descriptors[prop] = desc = {177 configurable: true,178 enumerable,179 get() {180 return get(this[DRAFT_STATE], prop)181 },182 set(value) {183 set(this[DRAFT_STATE], prop, value)184 }185 }186 }187 Object.defineProperty(draft, prop, desc)188}189190function proxyMap(target) {191 Object.defineProperties(target, mapTraps)192193 if (hasSymbol) {194 Object.defineProperty(195 target,196 Symbol.iterator,197 // @ts-ignore198 proxyMethod(iterateMapValues) //TODO: , Symbol.iterator)199 )200 }201}202203const mapTraps = finalizeTraps({204 size: state => latest(state).size,205 has: state => key => latest(state).has(key),206 set: state => (key, value) => {207 if (latest(state).get(key) !== value) {208 prepareCopy(state)209 markChanged(state)210 state.assigned.set(key, true)211 state.copy.set(key, value)212 }213 return state.draft214 },215 delete: state => key => {216 prepareCopy(state)217 markChanged(state)218 state.assigned.set(key, false)219 state.copy.delete(key)220 return false221 },222 clear: state => () => {223 if (!state.copy) {224 prepareCopy(state)225 }226 markChanged(state)227 state.assigned = new Map()228 for (const key of latest(state).keys()) {229 state.assigned.set(key, false)230 }231 return state.copy.clear()232 },233 forEach: (state, key, reciever) => cb => {234 latest(state).forEach((value, key, map) => {235 cb(reciever.get(key), key, map)236 })237 },238 get: state => key => {239 const value = latest(state).get(key)240241 if (state.finalizing || state.finalized || !isDraftable(value)) {242 return value243 }244245 if (value !== state.base.get(key)) {246 return value247 }248 const draft = createProxy(value, state)249 prepareCopy(state)250 state.copy.set(key, draft)251 return draft252 },253 keys: state => () => latest(state).keys(),254 values: iterateMapValues,255 entries: iterateMapValues256})257258function proxySet(target) {259 Object.defineProperties(target, setTraps)260261 if (hasSymbol) {262 Object.defineProperty(263 target,264 Symbol.iterator,265 // @ts-ignore266 proxyMethod(iterateSetValues) //TODO: , Symbol.iterator)267 )268 }269}270271const iterateSetValues = makeIterateSetValues(createProxy)272273const setTraps = finalizeTraps({274 size: state => {275 return latest(state).size276 },277 add: state => value => {278 if (!latest(state).has(value)) {279 markChanged(state)280 if (!state.copy) {281 prepareCopy(state)282 }283 state.copy.add(value)284 }285 return state.draft286 },287 delete: state => value => {288 markChanged(state)289 if (!state.copy) {290 prepareCopy(state)291 }292 return state.copy.delete(value)293 },294 has: state => key => {295 return latest(state).has(key)296 },297 clear: state => () => {298 markChanged(state)299 if (!state.copy) {300 prepareCopy(state)301 }302 return state.copy.clear()303 },304 keys: iterateSetValues,305 entries: iterateSetValues,306 values: iterateSetValues,307 forEach: state => (cb, thisArg) => {308 const iterator = iterateSetValues(state)()309 let result = iterator.next()310 while (!result.done) {311 cb.call(thisArg, result.value, result.value, state.draft)312 result = iterator.next()313 }314 }315})316317function finalizeTraps(traps) {318 return Object.keys(traps).reduce(function(acc, key) {319 const builder = key === "size" ? proxyAttr : proxyMethod320 acc[key] = builder(traps[key], key)321 return acc322 }, {})323}324325function proxyAttr(fn) {326 return {327 get() {328 const state = this[DRAFT_STATE]329 assertUnrevoked(state)330 return fn(state)331 }332 }333}334335function proxyMethod(trap, key) {336 return {337 get() {338 return function(this: ES5Draft, ...args) {339 const state = this[DRAFT_STATE]340 assertUnrevoked(state)341 return trap(state, key, state.draft)(...args)342 }343 }344 }345}346347function assertUnrevoked(state) {348 if (state.revoked === true)349 throw new Error(350 "Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? " +351 JSON.stringify(latest(state))352 )353}354355// This looks expensive, but only proxies are visited, and only objects without known changes are scanned.356function markChangesSweep(drafts) {357 // The natural order of drafts in the `scope` array is based on when they358 // were accessed. By processing drafts in reverse natural order, we have a359 // better chance of processing leaf nodes first. When a leaf node is known to360 // have changed, we can avoid any traversal of its ancestor nodes.361 for (let i = drafts.length - 1; i >= 0; i--) {362 const state = drafts[i][DRAFT_STATE]363 if (!state.modified) {364 if (Array.isArray(state.base)) {365 if (hasArrayChanges(state)) markChanged(state)366 } else if (isMap(state.base)) {367 if (hasMapChanges(state)) markChanged(state)368 } else if (isSet(state.base)) {369 if (hasSetChanges(state)) markChanged(state)370 } else if (hasObjectChanges(state)) {371 markChanged(state)372 }373 }374 }375}376377function markChangesRecursively(object) {378 if (!object || typeof object !== "object") return379 const state = object[DRAFT_STATE]380 if (!state) return381 const {base, draft, assigned} = state382 if (!Array.isArray(object)) {383 // Look for added keys.384 Object.keys(draft).forEach(key => {385 // The `undefined` check is a fast path for pre-existing keys.386 if (base[key] === undefined && !has(base, key)) {387 assigned[key] = true388 markChanged(state)389 } else if (!assigned[key]) {390 // Only untouched properties trigger recursion.391 markChangesRecursively(draft[key])392 }393 })394 // Look for removed keys.395 Object.keys(base).forEach(key => {396 // The `undefined` check is a fast path for pre-existing keys.397 if (draft[key] === undefined && !has(draft, key)) {398 assigned[key] = false399 markChanged(state)400 }401 })402 } else if (hasArrayChanges(state)) {403 markChanged(state)404 assigned.length = true405 if (draft.length < base.length) {406 for (let i = draft.length; i < base.length; i++) assigned[i] = false407 } else {408 for (let i = base.length; i < draft.length; i++) assigned[i] = true409 }410 for (let i = 0; i < draft.length; i++) {411 // Only untouched indices trigger recursion.412 if (assigned[i] === undefined) markChangesRecursively(draft[i])413 }414 }415}416417function hasObjectChanges(state) {418 const {base, draft} = state419420 // Search for added keys and changed keys. Start at the back, because421 // non-numeric keys are ordered by time of definition on the object.422 const keys = Object.keys(draft)423 for (let i = keys.length - 1; i >= 0; i--) {424 const key = keys[i]425 const baseValue = base[key]426 // The `undefined` check is a fast path for pre-existing keys.427 if (baseValue === undefined && !has(base, key)) {428 return true429 }430 // Once a base key is deleted, future changes go undetected, because its431 // descriptor is erased. This branch detects any missed changes.432 else {433 const value = draft[key]434 const state = value && value[DRAFT_STATE]435 if (state ? state.base !== baseValue : !is(value, baseValue)) {436 return true437 }438 }439 }440441 // At this point, no keys were added or changed.442 // Compare key count to determine if keys were deleted.443 return keys.length !== Object.keys(base).length444}445446function hasArrayChanges(state) {447 const {draft} = state448 if (draft.length !== state.base.length) return true449 // See #116450 // If we first shorten the length, our array interceptors will be removed.451 // If after that new items are added, result in the same original length,452 // those last items will have no intercepting property.453 // So if there is no own descriptor on the last position, we know that items were removed and added454 // N.B.: splice, unshift, etc only shift values around, but not prop descriptors, so we only have to check455 // the last one456 const descriptor = Object.getOwnPropertyDescriptor(draft, draft.length - 1)457 // descriptor can be null, but only for newly created sparse arrays, eg. new Array(10)458 if (descriptor && !descriptor.get) return true459 // For all other cases, we don't have to compare, as they would have been picked up by the index setters460 return false461}462463function createHiddenProperty(target, prop, value) {464 Object.defineProperty(target, prop, {465 value: value,466 enumerable: false,467 writable: true468 })469}