feat: limited class support
Before adoption: this commit came in with the history the project adopted, so no landing records it.
When a class instance has the new `immerable` symbol in its own properties, its prototype, or on its constructor, the class instance can be drafted. When drafted, class instances are basically plain objects, just with a different prototype. No magic here. OTHER CHANGES: - Allow symbols as property names in drafts - Add non-enumerable property support to drafts - Improved error messages - Fixed issue where ES5 drafts were not being marked as `finalizing` before being shallow cloned, which resulted in unnecessary draft creation
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
7 files+217 added−59 removed
- tests:+98 added−13 removed
- other:+119 added−46 removed
Provenance
- Commit
9877d64- Tree
5fb97a7- Author
aleclarson <alec.stanford.larson@gmail.com>- Committer
Alec Larson <alec.stanford.larson@gmail.com>- Parent
d5d07e8
7 files changed+217 added−59 removed
modified:__tests__/base.js+98 added-13 removed
1 "use strict"2-import {Immer, nothing, original, isDraft} from "../src/index"3-import {shallowCopy} from "../src/common"2+import {Immer, nothing, original, isDraft, immerable} from "../src/index"3+import {each, shallowCopy, isEnumerable} from "../src/common"4 import deepFreeze from "deep-freeze"5 import cloneDeep from "lodash.clonedeep"6 import * as lodash from "lodash"7 250 unmodified lines258 expect(() => {259 produce([], d => {260 d.x = 3261 })262- }).toThrow(/does not support/)262+ }).toThrow(263+ "Immer only supports setting array indices and the 'length' property"264+ )265 })266 267 it("throws when a non-numeric property is deleted", () => {268 expect(() => {1 unmodified line270 baseState.x = 7271 produce(baseState, d => {272 delete d.x273 })272- }).toThrow(/does not support/)274+ }).toThrow("Immer only supports deleting array indices")275 })276 }277 })278 279+ it("supports `immerable` symbol on constructor", () => {280+ class One {}281+ One[immerable] = true282+ const baseState = new One()283+ const nextState = produce(baseState, draft => {284+ expect(draft).not.toBe(baseState)285+ draft.foo = true286+ })287+ expect(nextState).not.toBe(baseState)288+ expect(nextState.foo).toBeTruthy()289+ })290+291+ it("preserves symbol properties", () => {292+ const test = Symbol("test")293+ const baseState = {[test]: true}294+ const nextState = produce(baseState, s => {295+ expect(s[test]).toBeTruthy()296+ s.foo = true297+ })298+ expect(nextState).toEqual({299+ [test]: true,300+ foo: true301+ })302+ })303+304+ it("preserves non-enumerable properties", () => {305+ const baseState = {}306+ Object.defineProperty(baseState, "foo", {307+ value: true,308+ enumerable: false309+ })310+ const nextState = produce(baseState, s => {311+ expect(s.foo).toBeTruthy()312+ expect(isEnumerable(s, "foo")).toBeFalsy()313+ s.bar = true314+ })315+ expect(nextState.foo).toBeTruthy()316+ expect(isEnumerable(nextState, "foo")).toBeFalsy()317+ })318+319+ it("throws on computed properties", () => {320+ const baseState = {}321+ Object.defineProperty(baseState, "foo", {322+ get: () => {},323+ enumerable: true324+ })325+ expect(() => {326+ produce(baseState, s => {327+ // Proxies only throw once a change is made.328+ if (useProxies) {329+ s.modified = true330+ }331+ })332+ }).toThrowError("Immer drafts cannot have computed properties")333+ })334+335+ it("allows inherited computed properties", () => {336+ const proto = {}337+ Object.defineProperty(proto, "foo", {338+ get() {339+ return this.bar340+ },341+ set(val) {342+ this.bar = val343+ }344+ })345+ const baseState = Object.create(proto)346+ produce(baseState, s => {347+ expect(s.bar).toBeUndefined()348+ s.foo = {}349+ expect(s.bar).toBeDefined()350+ expect(s.foo).toBe(s.bar)351+ })352+ })353+354 it("can rename nested objects (no changes)", () => {355 const nextState = produce({obj: {}}, s => {356 s.foo = s.obj357 delete s.obj147 unmodified lines505 writeable: true,506 value: 2507 })508 })432- }).toThrow(/does not support/)509+ }).toThrow(510+ "Object.defineProperty() cannot be used on an Immer draft"511+ )512 })513 514 it("should handle constructor correctly", () => {515 const baseState = {166 unmodified lines682 if (useProxies)683 it("throws when Object.setPrototypeOf() is used on a draft", () => {684 produce({}, draft => {685 expect(() => Object.setPrototypeOf(draft, Array)).toThrow(607- /does not support/686+ "Object.setPrototypeOf() cannot be used on an Immer draft"687 )688 })689 })690 292 unmodified lines983 })984 }985 986 function testObjectTypes(produce) {987+ class Foo {988+ constructor(foo) {989+ this.foo = foo990+ this[immerable] = true991+ }992+ }993 const values = {994 "empty object": {},995 "plain object": {a: 1, b: 2},996 "object (no prototype)": Object.create(null),997 "empty array": [],913- "plain array": [1, 2]998+ "plain array": [1, 2],999+ "class instance (draftable)": new Foo(1)1000 }1001 for (const name in values) {1002 const value = values[name]1003 const copy = shallowCopy(value)57 unmodified lines1061 "boxed number": new Number(0),1062 "boxed string": new String(""),1063 "boxed boolean": new Boolean(),1064 "date object": new Date(),979- "class instance": new Foo()1065+ "class instance (not draftable)": new Foo()1066 }1067 for (const name in values) {1068 describe(name, () => {1069 const value = values[name]21 unmodified lines1091 }1092 }1093 1094 function enumerableOnly(x) {1009- const copy = shallowCopy(x)1010- for (const key in copy) {1011- const value = copy[key]1095+ const copy = Array.isArray(x) ? x.slice() : Object.assign({}, x)1096+ each(copy, (prop, value) => {1097 if (value && typeof value === "object") {1013- copy[key] = enumerableOnly(value)1098+ copy[prop] = enumerableOnly(value)1099 }1015- }1100+ })1101 return copy1102 }modified:src/common.js+53 added-7 removed
12345678910111213141516171814151920211822232425262712 unmodified lines4041424339404142444546474849505152535455565758596061626364656667686970717273747576777879802 unmodified lines83848586878889909192939495969798991001011028 unmodified linesexport const NOTHING = typeof Symbol !== "undefined" ? Symbol("immer-nothing") : {["immer-nothing"]: true}
export const DRAFTABLE = typeof Symbol !== "undefined" ? Symbol("immer-draftable") : "__$immer_draftable"
export const DRAFT_STATE = typeof Symbol !== "undefined" ? Symbol("immer-state") : "__$immer_state"
export function isDraft(value) { return !!value && !!value[DRAFT_STATE]}
export function isDraftable(value) { if (!value) return false if (typeof value !== "object") return false if (!value || typeof value !== "object") return false if (Array.isArray(value)) return true const proto = Object.getPrototypeOf(value) return proto === null || proto === Object.prototype if (!proto || proto === Object.prototype) return true return !!value[DRAFTABLE] || !!value.constructor[DRAFTABLE]}
export function original(value) { if (value && value[DRAFT_STATE]) {12 unmodified lines } return target }
export function shallowCopy(value) { if (Array.isArray(value)) return value.slice() const target = value.__proto__ === undefined ? Object.create(null) : {} return assign(target, value)export const ownKeys = typeof Reflect !== "undefined" ? Reflect.ownKeys : obj => Object.getOwnPropertyNames(obj).concat( Object.getOwnPropertySymbols(obj) )
export function shallowCopy(base, invokeGetters = false) { if (Array.isArray(base)) return base.slice() const clone = Object.create(Object.getPrototypeOf(base)) ownKeys(base).forEach(key => { if (key === DRAFT_STATE) { return // Never copy over draft state. } const desc = Object.getOwnPropertyDescriptor(base, key) if (desc.get) { if (!invokeGetters) { throw new Error("Immer drafts cannot have computed properties") } desc.value = desc.get.call(base) } if (desc.enumerable) { clone[key] = desc.value } else { Object.defineProperty(clone, key, { value: desc.value, writable: true, configurable: true }) } }) return clone}
export function each(value, cb) { if (Array.isArray(value)) {2 unmodified lines for (let key in value) cb(key, value[key], value) }}
export function eachOwn(value, cb) { if (Array.isArray(value)) { for (let i = 0; i < value.length; i++) cb(i, value[i], value) } else { ownKeys(value).forEach(key => cb(key, value[key], value)) }}
export function isEnumerable(base, prop) { return Object.getOwnPropertyDescriptor(base, prop).enumerable}
export function has(thing, prop) { return Object.prototype.hasOwnProperty.call(thing, prop)}
8 unmodified linesmodified:src/es5.js+19 added-11 removed
6 unmodified lines7 is,8 isDraft,9 isDraftable,10 shallowCopy,11- DRAFT_STATE11+ DRAFT_STATE,12+ eachOwn,13+ isEnumerable14 } from "./common"15 16 const descriptors = {}17 16 unmodified lines34 if (isDraft(base)) {35 const state = base[DRAFT_STATE]36 // Avoid creating new drafts when copying.37 state.finalizing = true36- draft = shallowCopy(state.draft)38+ draft = shallowCopy(state.draft, true)39 state.finalizing = false40 } else {41 draft = shallowCopy(base)42 }41- each(base, prop => {42- Object.defineProperty(draft, "" + prop, createPropertyProxy("" + prop))43+44+ const isArray = Array.isArray(base)45+ eachOwn(draft, prop => {46+ const enumerable = isArray || isEnumerable(base, prop)47+ proxyProperty(draft, prop, enumerable)48 })49 50 // See "proxy.js" for property documentation.51 const state = {55 unmodified lines107 function prepareCopy(state) {108 if (!state.copy) state.copy = shallowCopy(state.base)109 }110 106-function createPropertyProxy(prop) {107- return (108- descriptors[prop] ||109- (descriptors[prop] = {111+function proxyProperty(draft, prop, enumerable) {112+ let desc = descriptors[prop]113+ if (desc) {114+ desc.enumerable = enumerable115+ } else {116+ descriptors[prop] = desc = {117 configurable: true,111- enumerable: true,118+ enumerable,119 get() {120 return get(this[DRAFT_STATE], prop)121 },122 set(value) {123 set(this[DRAFT_STATE], prop, value)124 }118- })119- )125+ }126+ }127+ Object.defineProperty(draft, prop, desc)128 }129 130 function assertUnrevoked(state) {131 if (state.revoked === true)104 unmodified linesmodified:src/immer.d.ts+10 added
121 unmodified lines122 */123 export const nothing: Nothing124 125 /**126+ * To let Immer treat your class instances as plain immutable objects127+ * (albeit with a custom prototype), you must define either an instance property128+ * or a static property on each of your custom classes.129+ *130+ * Otherwise, your class instance will never be drafted, which means it won't be131+ * safe to mutate in a produce callback.132+ */133+export const immerable: unique symbol134+135+/**136 * Pass true to automatically freeze all copies created by Immer.137 *138 * By default, auto-freezing is disabled in production.139 */78 unmodified linesmodified:src/immer.js+21 added-10 removed
7 unmodified lines8 isDraft,9 isDraftable,10 shallowCopy,11 DRAFT_STATE,12- NOTHING12+ NOTHING,13+ isEnumerable,14+ eachOwn15 } from "./common"16 17 function verifyMinified() {}18 143 unmodified lines162 */163 finalizeTree(root, path, patches, inversePatches) {164 const state = root[DRAFT_STATE]165 if (state) {164- root = this.useProxies165- ? state.copy166- : (state.copy = shallowCopy(state.draft))166+ if (!this.useProxies) {167+ state.finalizing = true168+ state.copy = shallowCopy(state.draft, true)169+ state.finalizing = false170+ }171+ root = state.copy172 }173 174 const {onAssign} = this175 const finalizeProperty = (prop, value, parent) => {176 // Only `root` can be a draft in here.177 const inDraft = !!state && parent === root178 179 if (isDraft(value)) {175- // prettier-ignore176- parent[prop] = value =180+ value =181 // Patches are never generated for assigned properties.182 patches && inDraft && !state.assigned[prop]179- ? this.finalize(value, path.concat(prop), patches, inversePatches)183+ ? this.finalize(value, path.concat(prop), patches, inversePatches) // prettier-ignore184 : this.finalize(value)185 182- // Unchanged drafts are ignored.186+ // Preserve non-enumerable properties.187+ if (Array.isArray(parent) || isEnumerable(parent, prop)) {188+ parent[prop] = value189+ } else {190+ Object.defineProperty(parent, prop, {value})191+ }192+193+ // Unchanged drafts are never passed to the `onAssign` hook.194 if (inDraft && value === state.base[prop]) return195 }196 // Unchanged draft properties are ignored.197 else if (inDraft && is(value, state.base[prop])) {198 return199 }200 // Search new objects for unfinalized drafts. Frozen objects should never contain drafts.201 else if (isDraftable(value) && !Object.isFrozen(value)) {191- each(value, finalizeProperty)202+ eachOwn(value, finalizeProperty)203 }204 205 if (inDraft && onAssign) {206 onAssign(state, prop, value)207 }208 }209 199- each(root, finalizeProperty)210+ eachOwn(root, finalizeProperty)211 return root212 }213 }modified:src/index.js+6 added-1 removed
45 unmodified lines4647484950505152535455565745 unmodified lines * This function is a producer, which means copy-on-write is in effect. */export const applyPatches = produce(applyPatchesImpl)
export {original, isDraft, NOTHING as nothing} from "./common"export { original, isDraft, NOTHING as nothing, DRAFTABLE as immerable} from "./common"
export {Immer}modified:src/proxy.js+10 added-17 removed
63 unmodified lines64 },65 set,66 deleteProperty,67 getOwnPropertyDescriptor,68- defineProperty,68+ defineProperty() {69+ throw new Error("Object.defineProperty() cannot be used on an Immer draft") // prettier-ignore70+ },71 getPrototypeOf(target) {72 return Object.getPrototypeOf(target.base)73 },74 setPrototypeOf() {73- throw new Error("Immer does not support `setPrototypeOf()`.")75+ throw new Error("Object.setPrototypeOf() cannot be used on an Immer draft") // prettier-ignore76 }77 }78 79 const arrayTraps = {}3 unmodified lines83 return fn.apply(this, arguments)84 }85 })86 arrayTraps.deleteProperty = function(state, prop) {85- if (isNaN(parseInt(prop)))86- throw new Error(87- "Immer does not support deleting properties from arrays: " + prop88- )87+ if (isNaN(parseInt(prop))) {88+ throw new Error("Immer only supports deleting array indices") // prettier-ignore89+ }90 return objectTraps.deleteProperty.call(this, state[0], prop)91 }92 arrayTraps.set = function(state, prop, value) {92- if (prop !== "length" && isNaN(parseInt(prop)))93- throw new Error(94- "Immer does not support setting non-numeric properties on arrays: " +95- prop96- )93+ if (prop !== "length" && isNaN(parseInt(prop))) {94+ throw new Error("Immer only supports setting array indices and the 'length' property") // prettier-ignore95+ }96 return objectTraps.set.call(this, state[0], prop, value)97 }98 99 function source(state) {60 unmodified lines160 descriptor.configurable = true161 return descriptor162 }163 165-function defineProperty() {166- throw new Error(167- "Immer does not support defining properties on draft objects."168- )169-}170-164 function markChanged(state) {165 if (!state.modified) {166 state.modified = true167 state.copy = assign(shallowCopy(state.base), state.drafts)4 unmodified lines