es5.ts
This file
Path
src/es5.ts
308 lines · 8.3 KiB · TypeScript
Last changed by
map unification WIPMichel Weststratebefore adoption9bcefb6
History of this fileTake it
Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 1–15why, 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,14 iterateMapValues,15 makeIterable,map unification WIPMichel Weststratebefore adoption9bcefb6
lines 16–17why, one step back16 makeIterateSetValues,17 latestMerge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 18–22why, one step back18} from "./common"19import {proxyMap, proxySet, hasMapChanges, hasSetChanges} from "./mapset"20import {ImmerScope} from "./scope"21import {ImmerState} from "./types"22map unification WIPMichel Weststratebefore adoption9bcefb6
line 23why, one step back23export interface ES5Draft {Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 24–27why, one step back24 [DRAFT_STATE]: ES5State25}2627// TODO: merge with ImmerState?map unification WIPMichel Weststratebefore adoption9bcefb6
line 28why, one step back28export interface ES5State<T = any> {Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 29–185why, one step back29 scope: ImmerScope30 modified: boolean31 finalizing: boolean32 finalized: boolean33 assigned: Map<any, any> | {[key: string]: any}34 parent: ES5State35 base: T36 draft: T & ES5Draft37 drafts: Map<any, any> | null38 copy: T | null39 revoke()40 revoked: boolean41}4243export function willFinalize(44 scope: ImmerScope,45 result: any,46 isReplaced: boolean47) {48 scope.drafts!.forEach(draft => {49 draft[DRAFT_STATE].finalizing = true50 })51 if (!isReplaced) {52 if (scope.patches) {53 markChangesRecursively(scope.drafts![0])54 }55 // This is faster when we don't care about which attributes changed.56 markChangesSweep(scope.drafts)57 }58 // When a child draft is returned, look for changes.59 else if (isDraft(result) && result[DRAFT_STATE].scope === scope) {60 markChangesSweep(scope.drafts)61 }62}6364export function createProxy<T>(base: T, parent: ES5State): ES5Draft {65 const isArray = Array.isArray(base)66 const draft = clonePotentialDraft(base)6768 if (isMap(base)) {69 proxyMap(draft)70 } else if (isSet(base)) {71 proxySet(draft)72 } else {73 each(draft, prop => {74 proxyProperty(draft, prop, isArray || isEnumerable(base, prop))75 })76 }7778 // See "proxy.js" for property documentation.79 const scope = parent ? parent.scope : ImmerScope.current!80 const state: ES5State<T> = {81 scope,82 modified: false,83 finalizing: false, // es5 only84 finalized: false,85 assigned: isMap(base) ? new Map() : {},86 parent,87 base,88 draft,89 drafts: isSet(base) ? new Map() : null,90 copy: null,91 revoke,92 revoked: false // es5 only93 }9495 createHiddenProperty(draft, DRAFT_STATE, state)96 scope.drafts!.push(draft)97 return draft98}99100function revoke(this: ES5State) {101 this.revoked = true102}103104// Access a property without creating an Immer draft.105function peek(draft, prop) {106 const state = draft[DRAFT_STATE]107 if (state && !state.finalizing) {108 state.finalizing = true109 const value = draft[prop]110 state.finalizing = false111 return value112 }113 return draft[prop]114}115116function get(state, prop) {117 assertUnrevoked(state)118 const value = peek(latest(state), prop)119 if (state.finalizing) return value120 // Create a draft if the value is unmodified.121 if (value === peek(state.base, prop) && isDraftable(value)) {122 prepareCopy(state)123 return (state.copy[prop] = createProxy(value, state))124 }125 return value126}127128function set(state, prop, value) {129 assertUnrevoked(state)130 state.assigned[prop] = true131 if (!state.modified) {132 if (is(value, peek(latest(state), prop))) return133 markChanged(state)134 prepareCopy(state)135 }136 state.copy[prop] = value137}138139// TODO: kill export140export function markChanged(state) {141 if (!state.modified) {142 state.modified = true143 if (state.parent) markChanged(state.parent)144 }145}146147// TODO: kill export148export function prepareCopy(state) {149 if (!state.copy) state.copy = clonePotentialDraft(state.base)150}151152function clonePotentialDraft(base) {153 const state = base && base[DRAFT_STATE]154 if (state) {155 state.finalizing = true156 const draft = shallowCopy(state.draft, true)157 state.finalizing = false158 return draft159 }160 return shallowCopy(base)161}162163// property descriptors are recycled to make sure we don't create a get and set closure per property,164// but share them all instead165const descriptors = {}166167function proxyProperty(draft, prop, enumerable) {168 let desc = descriptors[prop]169 if (desc) {170 desc.enumerable = enumerable171 } else {172 descriptors[prop] = desc = {173 configurable: true,174 enumerable,175 get() {176 return get(this[DRAFT_STATE], prop)177 },178 set(value) {179 set(this[DRAFT_STATE], prop, value)180 }181 }182 }183 Object.defineProperty(draft, prop, desc)184}185map unification WIPMichel Weststratebefore adoption9bcefb6
line 186why, one step back186export function assertUnrevoked(state) {Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 187–308why, one step back187 if (state.revoked === true)188 throw new Error(189 "Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? " +190 JSON.stringify(latest(state))191 )192}193194// This looks expensive, but only proxies are visited, and only objects without known changes are scanned.195function markChangesSweep(drafts) {196 // The natural order of drafts in the `scope` array is based on when they197 // were accessed. By processing drafts in reverse natural order, we have a198 // better chance of processing leaf nodes first. When a leaf node is known to199 // have changed, we can avoid any traversal of its ancestor nodes.200 for (let i = drafts.length - 1; i >= 0; i--) {201 const state = drafts[i][DRAFT_STATE]202 if (!state.modified) {203 if (Array.isArray(state.base)) {204 if (hasArrayChanges(state)) markChanged(state)205 } else if (isMap(state.base)) {206 if (hasMapChanges(state)) markChanged(state)207 } else if (isSet(state.base)) {208 if (hasSetChanges(state)) markChanged(state)209 } else if (hasObjectChanges(state)) {210 markChanged(state)211 }212 }213 }214}215216function markChangesRecursively(object) {217 if (!object || typeof object !== "object") return218 const state = object[DRAFT_STATE]219 if (!state) return220 const {base, draft, assigned} = state221 if (!Array.isArray(object)) {222 // Look for added keys.223 Object.keys(draft).forEach(key => {224 // The `undefined` check is a fast path for pre-existing keys.225 if (base[key] === undefined && !has(base, key)) {226 assigned[key] = true227 markChanged(state)228 } else if (!assigned[key]) {229 // Only untouched properties trigger recursion.230 markChangesRecursively(draft[key])231 }232 })233 // Look for removed keys.234 Object.keys(base).forEach(key => {235 // The `undefined` check is a fast path for pre-existing keys.236 if (draft[key] === undefined && !has(draft, key)) {237 assigned[key] = false238 markChanged(state)239 }240 })241 } else if (hasArrayChanges(state)) {242 markChanged(state)243 assigned.length = true244 if (draft.length < base.length) {245 for (let i = draft.length; i < base.length; i++) assigned[i] = false246 } else {247 for (let i = base.length; i < draft.length; i++) assigned[i] = true248 }249 for (let i = 0; i < draft.length; i++) {250 // Only untouched indices trigger recursion.251 if (assigned[i] === undefined) markChangesRecursively(draft[i])252 }253 }254}255256function hasObjectChanges(state) {257 const {base, draft} = state258259 // Search for added keys and changed keys. Start at the back, because260 // non-numeric keys are ordered by time of definition on the object.261 const keys = Object.keys(draft)262 for (let i = keys.length - 1; i >= 0; i--) {263 const key = keys[i]264 const baseValue = base[key]265 // The `undefined` check is a fast path for pre-existing keys.266 if (baseValue === undefined && !has(base, key)) {267 return true268 }269 // Once a base key is deleted, future changes go undetected, because its270 // descriptor is erased. This branch detects any missed changes.271 else {272 const value = draft[key]273 const state = value && value[DRAFT_STATE]274 if (state ? state.base !== baseValue : !is(value, baseValue)) {275 return true276 }277 }278 }279280 // At this point, no keys were added or changed.281 // Compare key count to determine if keys were deleted.282 return keys.length !== Object.keys(base).length283}284285function hasArrayChanges(state) {286 const {draft} = state287 if (draft.length !== state.base.length) return true288 // See #116289 // If we first shorten the length, our array interceptors will be removed.290 // If after that new items are added, result in the same original length,291 // those last items will have no intercepting property.292 // So if there is no own descriptor on the last position, we know that items were removed and added293 // N.B.: splice, unshift, etc only shift values around, but not prop descriptors, so we only have to check294 // the last one295 const descriptor = Object.getOwnPropertyDescriptor(draft, draft.length - 1)296 // descriptor can be null, but only for newly created sparse arrays, eg. new Array(10)297 if (descriptor && !descriptor.get) return true298 // For all other cases, we don't have to compare, as they would have been picked up by the index setters299 return false300}301302function createHiddenProperty(target, prop, value) {303 Object.defineProperty(target, prop, {304 value: value,305 enumerable: false,306 writable: true307 })308}