Skip to content
Myr

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

authored by aleclarson · committed by Alec Larson · parent d5d07e8 · Browse files · 7 files+217 added−59 removed
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

7 files+217 added−59 removed

modified:__tests__/base.js+98 added-13 removed
1"use strict"2import {Immer, nothing, original, isDraft} from "../src/index"3import {shallowCopy} from "../src/common"2import {Immer, nothing, original, isDraft, immerable} from "../src/index"3import {each, shallowCopy, isEnumerable} from "../src/common"4import deepFreeze from "deep-freeze"5import cloneDeep from "lodash.clonedeep"6import * as lodash from "lodash"7
250 unmodified lines
258 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 })266267 it("throws when a non-numeric property is deleted", () => {268 expect(() => {
1 unmodified line
270 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 })278279 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 })290291 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 })303304 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 })318319 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 })334335 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 })353354 it("can rename nested objects (no changes)", () => {355 const nextState = produce({obj: {}}, s => {356 s.foo = s.obj357 delete s.obj
147 unmodified lines
505 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 })513514 it("should handle constructor correctly", () => {515 const baseState = {
166 unmodified lines
682 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 lines
983 })984}985986function 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 lines
1061 "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 lines
1091 }1092}10931094function 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
modified:src/es5.js+19 added-11 removed
6 unmodified lines
7 is,8 isDraft,9 isDraftable,10 shallowCopy,11 DRAFT_STATE11 DRAFT_STATE,12 eachOwn,13 isEnumerable14} from "./common"1516const descriptors = {}17
16 unmodified lines
34 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))4344 const isArray = Array.isArray(base)45 eachOwn(draft, prop => {46 const enumerable = isArray || isEnumerable(base, prop)47 proxyProperty(draft, prop, enumerable)48 })4950 // See "proxy.js" for property documentation.51 const state = {
55 unmodified lines
107function prepareCopy(state) {108 if (!state.copy) state.copy = shallowCopy(state.base)109}110106function createPropertyProxy(prop) {107 return (108 descriptors[prop] ||109 (descriptors[prop] = {111function 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}129130function assertUnrevoked(state) {131 if (state.revoked === true)
104 unmodified lines
modified:src/immer.d.ts+10 added
121 unmodified lines
122 */123export const nothing: Nothing124125/**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 */133export const immerable: unique symbol134135/**136 * Pass true to automatically freeze all copies created by Immer.137 *138 * By default, auto-freezing is disabled in production.139 */
78 unmodified lines
modified:src/immer.js+21 added-10 removed
7 unmodified lines
8 isDraft,9 isDraftable,10 shallowCopy,11 DRAFT_STATE,12 NOTHING12 NOTHING,13 isEnumerable,14 eachOwn15} from "./common"1617function verifyMinified() {}18
143 unmodified lines
162 */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 }173174 const {onAssign} = this175 const finalizeProperty = (prop, value, parent) => {176 // Only `root` can be a draft in here.177 const inDraft = !!state && parent === root178179 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)185182 // 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 }192193 // 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 }204205 if (inDraft && onAssign) {206 onAssign(state, prop, value)207 }208 }209199 each(root, finalizeProperty)210 eachOwn(root, finalizeProperty)211 return root212 }213}
modified:src/index.js+6 added-1 removed
modified:src/proxy.js+10 added-17 removed
63 unmodified lines
64 },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}7879const arrayTraps = {}
3 unmodified lines
83 return fn.apply(this, arguments)84 }85})86arrayTraps.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}92arrayTraps.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}9899function source(state) {
60 unmodified lines
160 descriptor.configurable = true161 return descriptor162}163165function defineProperty() {166 throw new Error(167 "Immer does not support defining properties on draft objects."168 )169}170164function markChanged(state) {165 if (!state.modified) {166 state.modified = true167 state.copy = assign(shallowCopy(state.base), state.drafts)
4 unmodified lines