es5.js
This file
Path
src/es5.js
468 lines · 11.4 KiB · JavaScript
Last changed by
feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40
History of this fileTake it
The walk stopped after 200 commits: lines older than 8a1c84c point at it.
ci: collect coverage on node 10 onlyaleclarsonbefore adoption8a1c84c
lines 1–2why, one step back1"use strict"2import {style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 3–8why, one step back3 each,4 has,5 is,6 isDraft,7 isDraftable,8 isEnumerable,feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40
lines 9–11why, one step back9 isMap,10 isSet,11 hasSymbol,style: use tabsuse-tabsbefore adoptiona9c0fd0
line 12why, one step back12 shallowCopy,feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40
lines 13–16why, one step back13 DRAFT_STATE,14 iterateMapValues,15 makeIterable,16 makeIterateSetValuesci: collect coverage on node 10 onlyaleclarsonbefore adoption8a1c84c
line 17why, one step back17} from "./common"Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
line 18why, one step back18import {ImmerScope} from "./scope"ci: collect coverage on node 10 onlyaleclarsonbefore adoption8a1c84c
line 19why, one step back19Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
line 20why, one step back20export function willFinalize(scope, result, isReplaced) {style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 21–34why, one step back21 scope.drafts.forEach(draft => {22 draft[DRAFT_STATE].finalizing = true23 })24 if (!isReplaced) {25 if (scope.patches) {26 markChangesRecursively(scope.drafts[0])27 }28 // This is faster when we don't care about which attributes changed.29 markChangesSweep(scope.drafts)30 }31 // When a child draft is returned, look for changes.32 else if (isDraft(result) && result[DRAFT_STATE].scope === scope) {33 markChangesSweep(scope.drafts)34 }feat: add `Immer` classaleclarsonbefore adoptionecd04dc
lines 35–36why, one step back35}36Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
line 37why, one step back37export function createProxy(base, parent) {style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 38–39why, one step back38 const isArray = Array.isArray(base)39 const draft = clonePotentialDraft(base)feat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 40why, one step back40feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40
lines 41–50why, one step back41 if (isMap(base)) {42 proxyMap(draft)43 } else if (isSet(base)) {44 proxySet(draft)45 } else {46 each(draft, prop => {47 proxyProperty(draft, prop, isArray || isEnumerable(base, prop))48 })49 }50style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 51–57why, one step back51 // See "proxy.js" for property documentation.52 const scope = parent ? parent.scope : ImmerScope.current53 const state = {54 scope,55 modified: false,56 finalizing: false, // es5 only57 finalized: false,feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40
line 58why, one step back58 assigned: isMap(base) ? new Map() : {},style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 59–61why, one step back59 parent,60 base,61 draft,feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40
line 62why, one step back62 drafts: isSet(base) ? new Map() : null,style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 63–66why, one step back63 copy: null,64 revoke,65 revoked: false // es5 only66 }feat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 67why, one step back67style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 68–70why, one step back68 createHiddenProperty(draft, DRAFT_STATE, state)69 scope.drafts.push(draft)70 return draftci: collect coverage on node 10 onlyaleclarsonbefore adoption8a1c84c
lines 71–72why, one step back71}72feat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 73why, one step back73function revoke() {style: use tabsuse-tabsbefore adoptiona9c0fd0
line 74why, one step back74 this.revoked = truefeat: add `Immer` classaleclarsonbefore adoptionecd04dc
lines 75–76why, one step back75}76feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40
line 77why, one step back77function latest(state) {style: use tabsuse-tabsbefore adoptiona9c0fd0
line 78why, one step back78 return state.copy || state.baseci: collect coverage on node 10 onlyaleclarsonbefore adoption8a1c84c
lines 79–80why, one step back79}80fix: unnecessary draft creationAlec Larsonbefore adoptionec00ee4
lines 81–82why, one step back81// Access a property without creating an Immer draft.82function peek(draft, prop) {style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 83–90why, one step back83 const state = draft[DRAFT_STATE]84 if (state && !state.finalizing) {85 state.finalizing = true86 const value = draft[prop]87 state.finalizing = false88 return value89 }90 return draft[prop]fix: unnecessary draft creationAlec Larsonbefore adoptionec00ee4
lines 91–92why, one step back91}92ci: collect coverage on node 10 onlyaleclarsonbefore adoption8a1c84c
line 93why, one step back93function get(state, prop) {style: use tabsuse-tabsbefore adoptiona9c0fd0
line 94why, one step back94 assertUnrevoked(state)feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40
line 95why, one step back95 const value = peek(latest(state), prop)style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 96–102why, one step back96 if (state.finalizing) return value97 // Create a draft if the value is unmodified.98 if (value === peek(state.base, prop) && isDraftable(value)) {99 prepareCopy(state)100 return (state.copy[prop] = createProxy(value, state))101 }102 return valueci: collect coverage on node 10 onlyaleclarsonbefore adoption8a1c84c
lines 103–105why, one step back103}104105function set(state, prop, value) {style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 106–108why, one step back106 assertUnrevoked(state)107 state.assigned[prop] = true108 if (!state.modified) {feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40
line 109why, one step back109 if (is(value, peek(latest(state), prop))) returnstyle: use tabsuse-tabsbefore adoptiona9c0fd0
lines 110–113why, one step back110 markChanged(state)111 prepareCopy(state)112 }113 state.copy[prop] = valueci: collect coverage on node 10 onlyaleclarsonbefore adoption8a1c84c
lines 114–116why, one step back114}115116function markChanged(state) {style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 117–120why, one step back117 if (!state.modified) {118 state.modified = true119 if (state.parent) markChanged(state.parent)120 }ci: collect coverage on node 10 onlyaleclarsonbefore adoption8a1c84c
lines 121–123why, one step back121}122123function prepareCopy(state) {style: use tabsuse-tabsbefore adoptiona9c0fd0
line 124why, one step back124 if (!state.copy) state.copy = clonePotentialDraft(state.base)fix(es5): account for drafts in prepareCopyaleclarsonbefore adoption1e3e425
lines 125–127why, one step back125}126127function clonePotentialDraft(base) {style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 128–135why, one step back128 const state = base && base[DRAFT_STATE]129 if (state) {130 state.finalizing = true131 const draft = shallowCopy(state.draft, true)132 state.finalizing = false133 return draft134 }135 return shallowCopy(base)ci: collect coverage on node 10 onlyaleclarsonbefore adoption8a1c84c
lines 136–137why, one step back136}137feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40
lines 138–141why, one step back138// property descriptors are recycled to make sure we don't create a get and set closure per property,139// but share them all instead140const descriptors = {}141feat: limited class supportaleclarsonbefore adoption9877d64
line 142why, one step back142function proxyProperty(draft, prop, enumerable) {style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 143–158why, one step back143 let desc = descriptors[prop]144 if (desc) {145 desc.enumerable = enumerable146 } else {147 descriptors[prop] = desc = {148 configurable: true,149 enumerable,150 get() {151 return get(this[DRAFT_STATE], prop)152 },153 set(value) {154 set(this[DRAFT_STATE], prop, value)155 }156 }157 }158 Object.defineProperty(draft, prop, desc)ci: collect coverage on node 10 onlyaleclarsonbefore adoption8a1c84c
lines 159–160why, one step back159}160feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40
lines 161–315why, one step back161function proxyMap(target) {162 Object.defineProperties(target, mapTraps)163164 if (hasSymbol) {165 Object.defineProperty(166 target,167 Symbol.iterator,168 proxyMethod(iterateMapValues)169 )170 }171}172173const mapTraps = finalizeTraps({174 size: state => latest(state).size,175 has: state => key => latest(state).has(key),176 set: state => (key, value) => {177 if (latest(state).get(key) !== value) {178 prepareCopy(state)179 markChanged(state)180 state.assigned.set(key, true)181 state.copy.set(key, value)182 }183 return state.draft184 },185 delete: state => key => {186 prepareCopy(state)187 markChanged(state)188 state.assigned.set(key, false)189 state.copy.delete(key)190 return false191 },192 clear: state => () => {193 if (!state.copy) {194 prepareCopy(state)195 }196 markChanged(state)197 state.assigned = new Map()198 for (const key of latest(state).keys()) {199 state.assigned.set(key, false)200 }201 return state.copy.clear()202 },203 forEach: (state, key, reciever) => cb => {204 latest(state).forEach((value, key, map) => {205 cb(reciever.get(key), key, map)206 })207 },208 get: state => key => {209 const value = latest(state).get(key)210211 if (state.finalizing || state.finalized || !isDraftable(value)) {212 return value213 }214215 if (value !== state.base.get(key)) {216 return value217 }218 const draft = createProxy(value, state)219 prepareCopy(state)220 state.copy.set(key, draft)221 return draft222 },223 keys: state => () => latest(state).keys(),224 values: iterateMapValues,225 entries: iterateMapValues226})227228function proxySet(target) {229 Object.defineProperties(target, setTraps)230231 if (hasSymbol) {232 Object.defineProperty(233 target,234 Symbol.iterator,235 proxyMethod(iterateSetValues)236 )237 }238}239240const iterateSetValues = makeIterateSetValues(createProxy)241242const setTraps = finalizeTraps({243 size: state => {244 return latest(state).size245 },246 add: state => value => {247 if (!latest(state).has(value)) {248 markChanged(state)249 if (!state.copy) {250 prepareCopy(state)251 }252 state.copy.add(value)253 }254 return state.draft255 },256 delete: state => value => {257 markChanged(state)258 if (!state.copy) {259 prepareCopy(state)260 }261 return state.copy.delete(value)262 },263 has: state => key => {264 return latest(state).has(key)265 },266 clear: state => () => {267 markChanged(state)268 if (!state.copy) {269 prepareCopy(state)270 }271 return state.copy.clear()272 },273 keys: iterateSetValues,274 entries: iterateSetValues,275 values: iterateSetValues,276 forEach: state => (cb, thisArg) => {277 const iterator = iterateSetValues(state)()278 let result = iterator.next()279 while (!result.done) {280 cb.call(thisArg, result.value, result.value, state.draft)281 result = iterator.next()282 }283 }284})285286function finalizeTraps(traps) {287 return Object.keys(traps).reduce(function(acc, key) {288 const builder = key === "size" ? proxyAttr : proxyMethod289 acc[key] = builder(traps[key], key)290 return acc291 }, {})292}293294function proxyAttr(fn) {295 return {296 get() {297 const state = this[DRAFT_STATE]298 assertUnrevoked(state)299 return fn(state)300 }301 }302}303304function proxyMethod(trap, key) {305 return {306 get() {307 return function(...args) {308 const state = this[DRAFT_STATE]309 assertUnrevoked(state)310 return trap(state, key, state.draft)(...args)311 }312 }313 }314}315feat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 316why, one step back316function assertUnrevoked(state) {style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 317–319why, one step back317 if (state.revoked === true)318 throw new Error(319 "Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? " +feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40
line 320why, one step back320 JSON.stringify(latest(state))style: use tabsuse-tabsbefore adoptiona9c0fd0
line 321why, one step back321 )ci: collect coverage on node 10 onlyaleclarsonbefore adoption8a1c84c
lines 322–323why, one step back322}323feat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 324why, one step back324// This looks expensive, but only proxies are visited, and only objects without known changes are scanned.Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
line 325why, one step back325function markChangesSweep(drafts) {style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 326–334why, one step back326 // The natural order of drafts in the `scope` array is based on when they327 // were accessed. By processing drafts in reverse natural order, we have a328 // better chance of processing leaf nodes first. When a leaf node is known to329 // have changed, we can avoid any traversal of its ancestor nodes.330 for (let i = drafts.length - 1; i >= 0; i--) {331 const state = drafts[i][DRAFT_STATE]332 if (!state.modified) {333 if (Array.isArray(state.base)) {334 if (hasArrayChanges(state)) markChanged(state)feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40
lines 335–341why, one step back335 } else if (isMap(state.base)) {336 if (hasMapChanges(state)) markChanged(state)337 } else if (isSet(state.base)) {338 if (hasSetChanges(state)) markChanged(state)339 } else if (hasObjectChanges(state)) {340 markChanged(state)341 }style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 342–343why, one step back342 }343 }ci: collect coverage on node 10 onlyaleclarsonbefore adoption8a1c84c
lines 344–346why, one step back344}345346function markChangesRecursively(object) {style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 347–383why, one step back347 if (!object || typeof object !== "object") return348 const state = object[DRAFT_STATE]349 if (!state) return350 const {base, draft, assigned} = state351 if (!Array.isArray(object)) {352 // Look for added keys.353 Object.keys(draft).forEach(key => {354 // The `undefined` check is a fast path for pre-existing keys.355 if (base[key] === undefined && !has(base, key)) {356 assigned[key] = true357 markChanged(state)358 } else if (!assigned[key]) {359 // Only untouched properties trigger recursion.360 markChangesRecursively(draft[key])361 }362 })363 // Look for removed keys.364 Object.keys(base).forEach(key => {365 // The `undefined` check is a fast path for pre-existing keys.366 if (draft[key] === undefined && !has(draft, key)) {367 assigned[key] = false368 markChanged(state)369 }370 })371 } else if (hasArrayChanges(state)) {372 markChanged(state)373 assigned.length = true374 if (draft.length < base.length) {375 for (let i = draft.length; i < base.length; i++) assigned[i] = false376 } else {377 for (let i = base.length; i < draft.length; i++) assigned[i] = true378 }379 for (let i = 0; i < draft.length; i++) {380 // Only untouched indices trigger recursion.381 if (assigned[i] === undefined) markChangesRecursively(draft[i])382 }383 }ci: collect coverage on node 10 onlyaleclarsonbefore adoption8a1c84c
lines 384–386why, one step back384}385386function hasObjectChanges(state) {style: use tabsuse-tabsbefore adoptiona9c0fd0
line 387why, one step back387 const {base, draft} = stateci: collect coverage on node 10 onlyaleclarsonbefore adoption8a1c84c
line 388why, one step back388style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 389–408why, one step back389 // Search for added keys and changed keys. Start at the back, because390 // non-numeric keys are ordered by time of definition on the object.391 const keys = Object.keys(draft)392 for (let i = keys.length - 1; i >= 0; i--) {393 const key = keys[i]394 const baseValue = base[key]395 // The `undefined` check is a fast path for pre-existing keys.396 if (baseValue === undefined && !has(base, key)) {397 return true398 }399 // Once a base key is deleted, future changes go undetected, because its400 // descriptor is erased. This branch detects any missed changes.401 else {402 const value = draft[key]403 const state = value && value[DRAFT_STATE]404 if (state ? state.base !== baseValue : !is(value, baseValue)) {405 return true406 }407 }408 }ci: collect coverage on node 10 onlyaleclarsonbefore adoption8a1c84c
line 409why, one step back409style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 410–412why, one step back410 // At this point, no keys were added or changed.411 // Compare key count to determine if keys were deleted.412 return keys.length !== Object.keys(base).lengthci: collect coverage on node 10 onlyaleclarsonbefore adoption8a1c84c
lines 413–415why, one step back413}414415function hasArrayChanges(state) {style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 416–429why, one step back416 const {draft} = state417 if (draft.length !== state.base.length) return true418 // See #116419 // If we first shorten the length, our array interceptors will be removed.420 // If after that new items are added, result in the same original length,421 // those last items will have no intercepting property.422 // So if there is no own descriptor on the last position, we know that items were removed and added423 // N.B.: splice, unshift, etc only shift values around, but not prop descriptors, so we only have to check424 // the last one425 const descriptor = Object.getOwnPropertyDescriptor(draft, draft.length - 1)426 // descriptor can be null, but only for newly created sparse arrays, eg. new Array(10)427 if (descriptor && !descriptor.get) return true428 // For all other cases, we don't have to compare, as they would have been picked up by the index setters429 return falsefeat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40
lines 430–459why, one step back430}431432function hasMapChanges(state) {433 const {base, draft} = state434435 if (base.size !== draft.size) return true436437 // IE11 supports only forEach iteration438 let hasChanges = false439 draft.forEach(function(value, key) {440 if (!hasChanges) {441 hasChanges = isDraftable(value) ? value.modified : value !== base.get(key)442 }443 })444 return hasChanges445}446447function hasSetChanges(state) {448 const {base, draft} = state449450 if (base.size !== draft.size) return true451452 // IE11 supports only forEach iteration453 let hasChanges = false454 draft.forEach(function(value, key) {455 if (!hasChanges) {456 hasChanges = isDraftable(value) ? value.modified : !base.has(key)457 }458 })459 return hasChangesci: collect coverage on node 10 onlyaleclarsonbefore adoption8a1c84c
lines 460–462why, one step back460}461462function createHiddenProperty(target, prop, value) {style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 463–467why, one step back463 Object.defineProperty(target, prop, {464 value: value,465 enumerable: false,466 writable: true467 })ci: collect coverage on node 10 onlyaleclarsonbefore adoption8a1c84c
line 468why, one step back468}