WIP
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 20bc897 · Browse files · 2 files·+93 added−109 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+93 added−109 removed
- tests:+8 added−3 removed
- other:+85 added−106 removed
Provenance
- Commit
a758751- Tree
dbd2dad- Author
Michel Weststrate <mweststrate@gmail.com>- Committer
Michel Weststrate <mweststrate@gmail.com>- Parent
20bc897
2 files changed+93 added−109 removed
modified:__tests__/base.js+8 added-3 removed
2 unmodified lines3 import * as immerEs5 from "../es5"4 import deepFreeze from "deep-freeze"5 6 runBaseTest("proxy (no freeze)", immerProxy, false)7-runBaseTest("proxy (autofreeze)", immerProxy, true)8-runBaseTest("es5 (no freeze)", immerEs5, false)9-runBaseTest("es5 (autofreeze)", immerEs5, true)7+// runBaseTest("proxy (autofreeze)", immerProxy, true)8+// runBaseTest("es5 (no freeze)", immerEs5, false)9+// runBaseTest("es5 (autofreeze)", immerEs5, true)10 11 function runBaseTest(name, lib, freeze) {12 describe(`base functionality - ${name}`, () => {13 const immer = lib.default330 unmodified lines344 function enumerableOnly(x) {345 // this can be done better...346 return JSON.parse(JSON.stringify(x))347 }348+349+// TODO: test problem scenarios350+// nesting immmer351+// non-trees352+// complex objects / functionsmodified:immer.js+85 added-106 removed
10 unmodified lines11 * @property {any} proxy12 * @property {Function} revoke13 */14 15-const IMMER_PROXY = Symbol("immer-proxy") // TODO: create per closure, to avoid sharing proxies between multiple immer version15+const IS_PROXY = Symbol("immer-proxy") // TODO: create per closure, to avoid sharing proxies between multiple immer version16+const PROXY_STATE = Symbol("immer-proxy-state") // TODO: create per closure, to avoid sharing proxies between multiple immer version17 18 // This property indicates that the current object is cloned for another object,19 // to make sure the proxy of a frozen object is writeable20 const CLONE_TARGET = Symbol("immer-clone-target")10 unmodified lines31 * @param {Function} thunk - function that receives a proxy of the base state as first argument and which can be freely modified32 * @returns {any} a new state, or the base state if nothing was modified33 */34 function immer(baseState, thunk) {34- /**35- * Maps baseState objects to revocable proxies36- * @type {Map<Object,RevocableProxy>}37- */38- const revocableProxies = new Map()39- // Maps baseState objects to their copies35+ class State {36+ // /** @type {boolean} */37+ // modified38+ // /** @type {State} */39+ // parent40+ // /** @type {any} */41+ // base42+ // /** @type {any} */43+ // copy44+ // /** @type {any} */45+ // proxies46 41- const copies = new Map()47+ constructor(parent, base) {48+ this.modified49+ this.parent = parent50+ this.base = base51+ this.proxies = {}52+ }53 54+ get source() {55+ return this.modified === true ? this.copy : this.base56+ }57+58+ get(prop) {59+ const proxy = this.proxies[prop]60+ if (proxy) return proxy61+ const value = this.source[prop]62+ if (!isProxy(value) && isProxyable(value))63+ return (this.proxies[prop] = createProxy(this, value))64+ return value65+ }66+67+ set(prop, value) {68+ if (!this.modified) {69+ if (this.proxies[prop] === value || this.base[prop] === value)70+ return71+ this.markChanged()72+ }73+ if (isProxy(value)) this.proxies[prop] = value74+ this.copy[prop] = value75+ }76+77+ markChanged() {78+ if (!this.modified) {79+ this.modified = true80+ this.copy = Object.assign({}, this.base)81+ if (this.parent) this.parent.markChanged()82+ }83+ }84+ }85+86 const objectTraps = {87 get(target, prop) {45- if (prop === IMMER_PROXY) return target46- return createProxy(getCurrentSource(target)[prop])88+ if (prop === IS_PROXY) return true89+ if (prop === PROXY_STATE) return target90+ return target.get(prop)91 },92 has(target, prop) {49- return prop in getCurrentSource(target)93+ return prop in target.source94 },95 ownKeys(target) {52- return Reflect.ownKeys(getCurrentSource(target))96+ return Reflect.ownKeys(target.source)97 },98 set(target, prop, value) {55- const current = createProxy(getCurrentSource(target)[prop])56- const newValue = createProxy(value)57- if (current !== newValue) {58- const copy = getOrCreateCopy(target)59- copy[prop] = isProxy(newValue)60- ? newValue[IMMER_PROXY]61- : newValue62- }99+ target.set(prop, value)100 return true101 },102 deleteProperty(target, property) {66- const copy = getOrCreateCopy(target)67- delete copy[property]103+ target.markChanged()104+ delete target.copy[property]105 return true106 },107 getOwnPropertyDescriptor(target, prop) {71- return Reflect.getOwnPropertyDescriptor(72- getCurrentSource(target),73- prop74- )108+ return Reflect.getOwnPropertyDescriptor(target.source, prop)109 },110 defineProperty(target, property, descriptor) {111+ target.markChanged()77- Object.defineProperty(getOrCreateCopy(target), property, descriptor)112+ Object.defineProperty(target.copy, property, descriptor)113 return true114 },115 setPrototypeOf() {116 throw new Error("Don't even try this...")117 }118 }119 85- // creates a copy for a base object if there ain't one86- function getOrCreateCopy(base) {87- let copy = copies.get(base)88- if (copy) return copy89- const cloneTarget = base[CLONE_TARGET]90- if (cloneTarget) {91- // base is a clone already (source was frozen), no need to create addtional copy92- copies.set(cloneTarget, base)93- return base94- }95- // create a fresh copy96- copy = Array.isArray(base) ? base.slice() : Object.assign({}, base)97- copies.set(base, copy)98- return copy99- }100-101- // returns the current source of truth for a base object102- function getCurrentSource(base) {103- const copy = copies.get(base)104- return copy || base105- }106-120 // creates a proxy for plain objects / arrays108- function createProxy(base) {109- if (isPlainObject(base) || Array.isArray(base)) {110- if (isProxy(base)) return base // avoid double wrapping111- if (revocableProxies.has(base))112- return revocableProxies.get(base).proxy113- let proxyTarget114- // special case, if the base tree is frozen, we cannot modify it's proxy it in strict mode, clone first.115- if (Object.isFrozen(base)) {116- proxyTarget = Array.isArray(base)117- ? base.slice()118- : Object.assign({}, base)119- Object.defineProperty(proxyTarget, CLONE_TARGET, {120- enumerable: false,121- value: base,122- configurable: true123- })124- } else {125- proxyTarget = base126- }127- // create the proxy128- const revocableProxy = Proxy.revocable(proxyTarget, objectTraps)129- revocableProxies.set(base, revocableProxy)130- return revocableProxy.proxy131- }132- return base121+ function createProxy(parentState, base) {122+ const state = new State(parentState, base)123+ return new Proxy(state, objectTraps)124 }125 135- // checks if the given base object has modifications, either because it is modified, or136- // because one of it's children is137- function hasChanges(base) {138- const proxy = revocableProxies.get(base)139- if (!proxy) return false // nobody did read this object140- if (copies.has(base)) return true // a copy was created, so there are changes141- // look deeper142- const keys = Object.keys(base)143- for (let i = 0; i < keys.length; i++) {144- const value = base[keys[i]]145- if (146- (Array.isArray(value) || isPlainObject(value)) &&147- hasChanges(value)148- )149- return true150- }151- return false152- }153-126 // given a base object, returns it if unmodified, or return the changed cloned if modified127 function finalize(base) {128+ if (isProxy(base)) {129+ const state = base[PROXY_STATE]130+ if (state.modified === true) {156- if (isPlainObject(base)) return finalizeObject(base)157- if (Array.isArray(base)) return finalizeArray(base)131+ if (isPlainObject(base)) return finalizeObject(state)132+ if (Array.isArray(base)) return finalizeArray(state)133+ } else return state.base134+ }135 return base136 }137 161- function finalizeObject(thing) {162- if (!hasChanges(thing)) return thing163- const copy = getOrCreateCopy(thing) // TODO: getOrCreate is weird here..138+ function finalizeObject(state) {139+ const copy = state.copy140 Object.keys(copy).forEach(prop => {141 copy[prop] = finalize(copy[prop])142 })167- delete copy[CLONE_TARGET]143 return freeze(copy)144 }145 146 function finalizeArray(thing) {172- if (!hasChanges(thing)) return thing173- const copy = getOrCreateCopy(thing) // TODO: getOrCreate is weird here..147+ const copy = state.copy148 copy.forEach((value, index) => {149 copy[index] = finalize(copy[index])150 })177- delete copy[CLONE_TARGET]151 return freeze(copy)152 }153 154 // create proxy for root182- const rootClone = createProxy(baseState)155+ const rootClone = createProxy(undefined, baseState)156 // execute the thunk157 const maybeVoidReturn = thunk(rootClone)158 //values either than undefined will trigger warning;159 !Object.is(maybeVoidReturn, undefined) &&1 unmodified line161 `Immer callback expects no return value. However ${typeof maybeVoidReturn} was returned`162 )163 // console.log(`proxies: ${revocableProxies.size}, copies: ${copies.size}`)164 // revoke all proxies192- revoke(revocableProxies)165+ // TODO: revoke(revocableProxies)166 // and finalize the modified proxy194- return finalize(baseState)167+ return finalize(rootClone)168 }169 170 /**171 * Revoke all the proxies stored in the revocableProxies map12 unmodified lines184 return proto === Object.prototype || proto === null185 }186 187 function isProxy(value) {215- return !!value && !!value[IMMER_PROXY]188+ return !!value && !!value[IS_PROXY]189 }190 191+function isProxyable(value) {192+ if (!value) return false193+ if (typeof value !== "object") return false194+ return Array.isArray(value) || isPlainObject(value)195+}196+197 function freeze(value) {198 if (autoFreeze) {199 Object.freeze(value)200 }20 unmodified lines