Skip to content
Myr

Implemented non-proxy approach for objects

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Michel Weststrate · committed by Michel Weststrate · parent f890f96 · Browse files · 2 files+64 added−114 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

2 files+64 added−114 removed

  • tests:+6 added−4 removed
  • other:+58 added−110 removed

2 files+64 added−114 removed

modified:__tests__/base.js+6 added-4 removed
8 unmodified lines
9 origBaseState = baseState = createBaseState()10 })1112 it.only("should return the original without modifications", () => {13 debugger14 const nextState = immer(baseState, () => {})15 expect(nextState).toBe(baseState)16 })17
37 unmodified lines
55 expect(nextState.anObject.nested.yummie).toBe(false)56 expect(nextState.anArray).toBe(baseState.anArray)57 })5858 it("can add props", () => {59 it.only("can add props", () => {60 debugger61 const nextState = immer(baseState, s => {62 s.anObject.cookie = {tasty: true}63 })64 expect(nextState).not.toBe(baseState)
1 unmodified line
66 expect(nextState.anObject.nested).toBe(baseState.anObject.nested)67 expect(nextState.anObject.cookie).toEqual({tasty: true})68 })6968 it("can delete props", () => {70 it.only("can delete props", () => {71 const nextState = immer(baseState, s => {72 delete s.anObject.nested73 })74 expect(nextState).not.toBe(baseState)75 expect(nextState.anObject).not.toBe(baseState.anObject)76 expect(nextState.anObject.nested).toBe(undefined)77 })7877 it("ignores single non-modification", () => {79 it.only("ignores single non-modification", () => {80 const nextState = immer(baseState, s => {81 s.aProp = "hi"82 })83 expect(nextState).toBe(baseState)84 })8584 it("processes single modification", () => {86 it.only("processes single modification", () => {87 const nextState = immer(baseState, s => {88 s.aProp = "hello"89 s.aProp = "hi"90 })
158 unmodified lines
modified:immer-es5.js+58 added-110 removed
1"use strict"1import {isObject} from "util"2;("use strict")3// @ts-check45/**6 * @typedef {Object} RevocableProxy7 * @property {any} proxy8 * @property {Function} revoke9 */1010// TODO: rename to PROXY_TARGET11const IMMER_PROXY = Symbol("immer-proxy") // TODO: create per closure, to avoid sharing proxies between multiple immer version11const PROXY_TARGET = Symbol("immer-proxy") // TODO: create per closure, to avoid sharing proxies between multiple immer version1213// This property indicates that the current object is cloned for another object,14// to make sure the proxy of a frozen object is writeable15const CLONE_TARGET = Symbol("immer-clone-target")12const CHANGED_STATE = Symbol("immer-changed-state")17const CHANGED_METHOD = Symbol("immer-changed")1314let autoFreeze = true1516function proxySet(target, prop, value) {17 if (Object.is(target[prop], value)) return18 target[CHANGED_STATE] = true19 Object.defineProperty(target, prop, {20 enumerable: true,21 writable: true,22 configurable: true,23 value: value,24 })25}2627/**28 * Immer takes a state, and runs a function against it.29 * That function can freely mutate the state, as it will create copies-on-write.30 * This means that the original state will stay unchanged, and once the function finishes, the modified state is returned
3 unmodified lines
34 * @param {Function} thunk - function that receives a proxy of the base state as first argument and which can be freely modified35 * @returns {any} a new state, or the base state if nothing was modified36 */37function immer(baseState, thunk) {32 /**33 * Maps baseState objects to revocable proxies34 * @type {Map<Object,RevocableProxy>}35 */36 const revocableProxies = new Map()37 // Maps baseState objects to their copies38 let finalizing = false39 let finished = false4039 const copies = new Map()4041 const objectTraps = {42 get(target, prop) {43 if (prop === IMMER_PROXY) return target44 return createProxy(getCurrentSource(target)[prop])45 },46 has(target, prop) {47 return prop in getCurrentSource(target)48 },49 ownKeys(target) {50 return Reflect.ownKeys(getCurrentSource(target))51 },52 set(target, prop, value) {53 const current = createProxy(getCurrentSource(target)[prop])54 const newValue = createProxy(value)55 if (current !== newValue) {56 const copy = getOrCreateCopy(target)57 copy[prop] = isProxy(newValue)58 ? newValue[IMMER_PROXY]59 : newValue60 }61 return true62 },63 deleteProperty(target, property) {64 const copy = getOrCreateCopy(target)65 delete copy[property]66 return true67 },68 }6970 // creates a copy for a base object if there ain't one71 function getOrCreateCopy(base) {72 let copy = copies.get(base)73 if (copy) return copy74 const cloneTarget = base[CLONE_TARGET]75 if (cloneTarget) {76 // base is a clone already (source was frozen), no need to create addtional copy77 copies.set(cloneTarget, base)78 return base79 }80 // create a fresh copy81 copy = Array.isArray(base) ? base.slice() : Object.assign({}, base)82 copies.set(base, copy)83 return copy84 }8586 // returns the current source of truth for a base object87 function getCurrentSource(base) {88 const copy = copies.get(base)89 return copy || base90 }9141 // creates a proxy for plain objects / arrays42 function createProxy(base) {94 if (isProxy(base)) return base43 if (isPlainObject(base)) return createObjectProxy(base)96 if (Array.isArray(base)) return createObjectProxy(base) // TODO: create Array proxy?97 return base44 // if (Array.isArray(base)) return createArrayProxy(base) // TODO: create Array proxy?45 throw "Expected a plain object or array"46 }4748 function createObjectProxy(base) {101 // TODO: optimize, reuse property accessors49 // TODO: optimize, reuse property accessors, closures etc50 const proxy = {}103 createHiddenProperty(proxy, IMMER_PROXY, base)51 createHiddenProperty(proxy, PROXY_TARGET, base)52 createHiddenProperty(proxy, CHANGED_STATE, false)105 createHiddenProperty(proxy, CHANGED_METHOD, function() {106 if (this[CHANGED_STATE] === true) return true107 // TODO: first check child properties, that might be cheaper...108 return !shallowEqual(Object.keys(base), Object.keys(this))109 })53 Object.keys(base).forEach(prop => {54 Object.defineProperty(proxy, prop, {55 configurable: true,56 enumerable: true,57 get() {115 // const target = this[PROXY_TARGET]116 // return createProxy(getCurrentSource(target)[prop])117 return createProxy(base[prop])118 },119 set(value) {120 this[CHANGED_STATE] = true58 if (finished)59 throw "Cannot use proxy outside immer function"60 if (finalizing) return base[prop]61 const value = base[prop]62 if (!isPlainObject(value) && !Array.isArray(value))63 return value64 const proxy = createProxy(value)65 Object.defineProperty(this, prop, {122 enumerable: true,123 writable: true,66 configurable: true,125 value: value,67 enumerable: true,68 get() {69 return proxy70 },71 set(value) {72 if (finished)73 throw "Cannot use proxy outside immer function"74 proxySet(this, prop, value)75 },76 })77 return proxy78 },79 set(value) {80 if (finished)81 throw "Cannot use proxy outside immer function"82 proxySet(this, prop, value)83 },84 })85 })130 revocableProxies.set(base, {131 proxy,132 revoke: () => {133 // TODO: set unreadable state, reuse closure134 },135 })86 return proxy87 }8889 // checks if the given base object has modifications, either because it is modified, or90 // because one of it's children is91 function hasChanges(proxy) {92 if (!isProxy(proxy)) return false143 const base = proxy[IMMER_PROXY]144 if (proxy[CHANGED_METHOD](base)) return true // some property was modified93 if (proxy[CHANGED_STATE]) return true // some property was modified94 const baseKeys = Object.keys(proxy[PROXY_TARGET])95 const keys = Object.keys(proxy)96 if (!shallowEqual(baseKeys, keys)) return true97 // look deeper, this object was not modified, but maybe some of its children are146 const keys = Object.keys(base)98 for (let i = 0; i < keys.length; i++) {148 const value = proxy[keys[i]] // TODO: fix, this does convert value to a proxy?!149 if (150 (Array.isArray(value) || isPlainObject(value)) &&151 hasChanges(value)152 )153 return true99 const value = proxy[keys[i]]100 if (hasChanges(value)) return true101 }102 return false103 }104
5 unmodified lines
110 return thing111 }112113 function finalizeObject(proxy) {167 if (!hasChanges(proxy)) return proxy[IMMER_PROXY] // return the original target114 if (!hasChanges(proxy)) return proxy[PROXY_TARGET] // return the original target115 const res = {}116 Object.keys(proxy).forEach(prop => {169 proxy[prop] = finalize(proxy[prop])117 res[prop] = finalize(proxy[prop])118 })171 delete proxy[CLONE_TARGET]172 return freeze(proxy)119 return freeze(res)120 }121122 function finalizeArray(thing) {123 if (!hasChanges(thing)) return thing
13 unmodified lines
137 !Object.is(maybeVoidReturn, undefined) &&138 console.warn(139 `Immer callback expects no return value. However ${typeof maybeVoidReturn} was returned`,140 )194 // console.log(`proxies: ${revocableProxies.size}, copies: ${copies.size}`)195 // revoke all proxies196 revoke(revocableProxies)141 // and finalize the modified proxy142 finalizing = true198 return finalize(rootClone)143 const res = finalize(rootClone)144 // make sure all proxies become unusable145 finished = true146 return res147}148149/**150 * Revoke all the proxies stored in the revocableProxies map
12 unmodified lines
163 return proto === Object.prototype || proto === null164}165166function isProxy(value) {219 return !!(value && value[IMMER_PROXY])167 return !!(value && value[PROXY_TARGET])168}169170function freeze(value) {171 if (autoFreeze) {
61 unmodified lines