Skip to content
Myr

fix: revert Map support

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

See here: https://github.com/immerjs/immer/pull/353

authored by Alec Larson · committed by Alec Larson · parent b3a9aab · Browse files · 8 files+164 added−690 removed
This commit

State

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

Diff stats

8 files+164 added−690 removed

  • tests:+19 added−381 removed
  • other:+145 added−309 removed

8 files+164 added−690 removed

modified:__tests__/base.js+1 added-207 removed
1"use strict"2import {Immer, nothing, original, isDraft, immerable} from "../src/index"3import {each, shallowCopy, isEnumerable, DRAFT_STATE} from "../src/common"3import {each, shallowCopy, isEnumerable} from "../src/common"4import deepFreeze from "deep-freeze"5import cloneDeep from "lodash.clonedeep"6import * as lodash from "lodash"7
290 unmodified lines
298 })299 }300 })301302 if (useProxies) {303 describe("map drafts", () => {304 it("supports key access", () => {305 const value = baseState.aMap.get("jedi")306 const nextState = produce(baseState, s => {307 expect(s.aMap.get("jedi")).toEqual(value)308 })309 expect(nextState).toBe(baseState)310 })311312 it("supports iteration", () => {313 const base = new Map([314 ["first", {id: 1, a: 1}],315 ["second", {id: 2, a: 1}]316 ])317 const findById = (map, id) => {318 for (const [, item] of map) {319 if (item.id === id) return item320 }321 return null322 }323 const result = produce(base, draft => {324 const obj1 = findById(draft, 1)325 const obj2 = findById(draft, 2)326 obj1.a = 2327 obj2.a = 2328 })329 expect(result).not.toBe(base)330 expect(result.get("first").a).toEqual(2)331 expect(result.get("second").a).toEqual(2)332 })333334 it("supports 'entries'", () => {335 const base = new Map([336 ["first", {id: 1, a: 1}],337 ["second", {id: 2, a: 1}]338 ])339 const findById = (map, id) => {340 for (const [, item] of map.entries()) {341 if (item.id === id) return item342 }343 return null344 }345 const result = produce(base, draft => {346 const obj1 = findById(draft, 1)347 const obj2 = findById(draft, 2)348 obj1.a = 2349 obj2.a = 2350 })351 expect(result).not.toBe(base)352 expect(result.get("first").a).toEqual(2)353 expect(result.get("second").a).toEqual(2)354 })355356 it("supports 'values'", () => {357 const base = new Map([358 ["first", {id: 1, a: 1}],359 ["second", {id: 2, a: 1}]360 ])361 const findById = (map, id) => {362 for (const item of map.values()) {363 if (item.id === id) return item364 }365 return null366 }367 const result = produce(base, draft => {368 const obj1 = findById(draft, 1)369 const obj2 = findById(draft, 2)370 obj1.a = 2371 obj2.a = 2372 })373 expect(result).not.toBe(base)374 expect(result.get("first").a).toEqual(2)375 expect(result.get("second").a).toEqual(2)376 })377378 it("supports 'keys", () => {379 const base = new Map([380 ["first", Symbol()],381 ["second", Symbol()]382 ])383 const result = produce(base, draft => {384 expect([...draft.keys()]).toEqual(["first", "second"])385 draft.set("third", Symbol())386 expect([...draft.keys()]).toEqual([387 "first",388 "second",389 "third"390 ])391 })392 })393394 it("supports forEach", () => {395 const base = new Map([396 ["first", {id: 1, a: 1}],397 ["second", {id: 2, a: 1}]398 ])399 const result = produce(base, draft => {400 let sum1 = 0401 draft.forEach(({a}) => {402 sum1 += a403 })404 expect(sum1).toBe(2)405 let sum2 = 0406 draft.get("first").a = 10407 draft.get("second").a = 20408 draft.forEach(({a}) => {409 sum2 += a410 })411 expect(sum2).toBe(30)412 })413 })414415 it("supports forEach mutation", () => {416 const base = new Map([417 ["first", {id: 1, a: 1}],418 ["second", {id: 2, a: 1}]419 ])420 const result = produce(base, draft => {421 draft.forEach(item => {422 item.a = 100423 })424 })425 expect(result).not.toBe(base)426 expect(result.get("first").a).toEqual(100)427 expect(result.get("second").a).toEqual(100)428 })429430 it("can assign by key", () => {431 const nextState = produce(baseState, s => {432 // Map.prototype.set should return the Map itself433 const res = s.aMap.set("force", true)434 expect(res).toBe(s.aMap[DRAFT_STATE].draft)435 })436 expect(nextState).not.toBe(baseState)437 expect(nextState.aMap).not.toBe(baseState.aMap)438 expect(nextState.aMap.get("force")).toEqual(true)439 })440441 it("returns 'size'", () => {442 const nextState = produce(baseState, s => {443 s.aMap.set("newKey", true)444 expect(s.aMap.size).toBe(baseState.aMap.size + 1)445 })446 expect(nextState).not.toBe(baseState)447 expect(nextState.aMap).not.toBe(baseState.aMap)448 expect(nextState.aMap.get("newKey")).toEqual(true)449 expect(nextState.aMap.size).toEqual(baseState.aMap.size + 1)450 })451452 it("can use 'delete' to remove items", () => {453 const nextState = produce(baseState, s => {454 expect(s.aMap.has("jedi")).toBe(true)455 s.aMap.delete("jedi")456 expect(s.aMap.has("jedi")).toBe(false)457 })458 expect(nextState.aMap).not.toBe(baseState.aMap)459 expect(nextState.aMap.size).toBe(baseState.aMap.size - 1)460 expect(baseState.aMap.has("jedi")).toBe(true)461 expect(nextState.aMap.has("jedi")).toBe(false)462 })463464 it("can use 'clear' to remove items", () => {465 const nextState = produce(baseState, s => {466 expect(s.aMap.size).not.toBe(0)467 s.aMap.clear()468 expect(s.aMap.size).toBe(0)469 })470 expect(nextState.aMap).not.toBe(baseState.aMap)471 expect(nextState.aMap.size).toBe(0)472 })473474 it("support 'has'", () => {475 const nextState = produce(baseState, s => {476 expect(s.aMap.has("newKey")).toBe(false)477 s.aMap.set("newKey", true)478 expect(s.aMap.has("newKey")).toBe(true)479 })480 expect(nextState).not.toBe(baseState)481 expect(nextState.aMap).not.toBe(baseState.aMap)482 expect(nextState.aMap.has("newKey")).toEqual(true)483 })484485 it("supports nested maps", () => {486 const base = new Map([487 ["first", new Map([["second", {prop: "test"}]])]488 ])489 const result = produce(base, draft => {490 draft.get("first").get("second").prop = "test1"491 })492 expect(result).not.toBe(base)493 expect(result.get("first")).not.toBe(base.get("first"))494 expect(result.get("first").get("second")).not.toBe(495 base.get("first").get("second")496 )497 expect(base.get("first").get("second").prop).toBe("test")498 expect(result.get("first").get("second").prop).toBe("test1")499 })500 })501 }502302 it("supports `immerable` symbol on constructor", () => {303 class One {}304 One[immerable] = true305 const baseState = new One()
794 unmodified lines
1100 function createBaseState() {1101 const data = {1102 anInstance: new Foo(),1103 anArray: [3, 2, {c: 3}, 1],1305 aMap: new Map([1306 ["jedi", {name: "Luke", skill: 10}],1307 ["jediTotal", 42],1308 ["force", "these aren't the droids you're looking for"]1309 ]),1104 aProp: "hi",1105 anObject: {1106 nested: {1107 yummie: true
167 unmodified lines
modified:__tests__/patch.js+4 added-167 removed
1 unmodified line
2import produce, {setUseProxies, applyPatches} from "../src/index"34jest.setTimeout(1000)56function runPatchTest(7 base,8 producer,9 patches,10 inversePathes,11 proxyOnly = false12) {6function runPatchTest(base, producer, patches, inversePathes) {7 function runPatchTestHelper() {8 let recordedPatches9 let recordedInversePatches10 const res = produce(base, producer, (p, i) => {
16 unmodified lines
27 })28 }2930 describe(`proxy`, () => {37 beforeAll(() => setUseProxies(true))31 setUseProxies(true)32 runPatchTestHelper()33 })3435 describe(`es5`, () => {42 if (!proxyOnly) {43 beforeAll(() => setUseProxies(false))44 runPatchTestHelper()45 }36 setUseProxies(false)37 runPatchTestHelper()38 })39}4041describe("applyPatches", () => {
65 unmodified lines
107 [{op: "replace", path: ["x", 0, "y"], value: 5}]108 )109})110119describe("simple assignment - 4", () => {120 runPatchTest(121 new Map([["x", {y: 4}]]),122 d => {123 d.get("x").y++124 },125 [{op: "replace", path: ["x", "y"], value: 5}],126 [{op: "replace", path: ["x", "y"], value: 4}],127 true128 )129})130131describe("simple assignment - 5", () => {132 runPatchTest(133 {x: new Map([["y", 4]])},134 d => {135 d.x.set("y", 5)136 },137 [{op: "replace", path: ["x", "y"], value: 5}],138 [{op: "replace", path: ["x", "y"], value: 4}],139 true140 )141})142143describe("simple assignment - 6", () => {144 runPatchTest(145 new Map([["x", 1]]),146 d => {147 // Map.prototype.set should return the Map itself148 const res = d.set("x", 2)149 res.set("y", 3)150 },151 [152 {op: "replace", path: ["x"], value: 2},153 {op: "add", path: ["y"], value: 3}154 ],155 [{op: "replace", path: ["x"], value: 1}, {op: "remove", path: ["y"]}],156 true157 )158})159111describe("delete 1", () => {112 runPatchTest(113 {x: {y: 4}},114 d => {
2 unmodified lines
117 [{op: "remove", path: ["x"]}]118 )119})120170describe("delete 2", () => {171 runPatchTest(172 new Map([["x", 1]]),173 d => {174 d.delete("x")175 },176 [{op: "remove", path: ["x"]}],177 [{op: "add", path: ["x"], value: 1}],178 true179 )180})181182describe("delete 3", () => {183 runPatchTest(184 {x: new Map([["y", 1]])},185 d => {186 d.x.delete("y")187 },188 [{op: "remove", path: ["x", "y"]}],189 [{op: "add", path: ["x", "y"], value: 1}],190 true191 )192})193121describe("renaming properties", () => {122 describe("nested object (no changes)", () => {123 runPatchTest(124 {a: {b: 1}},
7 unmodified lines
132 ]133 )134 })135209 describe("nested map (no changes)", () => {210 runPatchTest(211 new Map([["a", new Map([["b", 1]])]]),212 d => {213 d.set("x", d.get("a"))214 d.delete("a")215 },216 [217 {op: "add", path: ["x"], value: new Map([["b", 1]])},218 {op: "remove", path: ["a"]}219 ],220 [221 {op: "remove", path: ["x"]},222 {op: "add", path: ["a"], value: new Map([["b", 1]])}223 ],224 true225 )226 })227136 describe("nested object (with changes)", () => {137 runPatchTest(138 {a: {b: 1, c: 1}},139 d => {
12 unmodified lines
152 ]153 )154 })155248 describe("nested map (with changes)", () => {249 runPatchTest(250 new Map([["a", new Map([["b", 1], ["c", 1]])]]),251 d => {252 let a = d.get("a")253 a.set("b", 2) // change254 a.delete("c") // delete255 a.set("y", 2) // add256257 // rename258 d.set("x", a)259 d.delete("a")260 },261 [262 {op: "add", path: ["x"], value: new Map([["b", 2], ["y", 2]])},263 {op: "remove", path: ["a"]}264 ],265 [266 {op: "remove", path: ["x"]},267 {op: "add", path: ["a"], value: new Map([["b", 1], ["c", 1]])}268 ],269 true270 )271 })272156 describe("deeply nested object (with changes)", () => {157 runPatchTest(158 {a: {b: {c: 1, d: 1}}},159 d => {
11 unmodified lines
171 {op: "remove", path: ["a", "b"]}172 ]173 )174 })292293 describe("deeply nested map (with changes)", () => {294 runPatchTest(295 new Map([["a", new Map([["b", new Map([["c", 1], ["d", 1]])]])]]),296 d => {297 let b = d.get("a").get("b")298 b.set("c", 2) // change299 b.delete("d") // delete300 b.set("y", 2) // add301302 // rename303 d.get("a").set("x", b)304 d.get("a").delete("b")305 },306 [307 {308 op: "add",309 path: ["a", "x"],310 value: new Map([["c", 2], ["y", 2]])311 },312 {op: "remove", path: ["a", "b"]}313 ],314 [315 {op: "remove", path: ["a", "x"]},316 {317 op: "add",318 path: ["a", "b"],319 value: new Map([["c", 1], ["d", 1]])320 }321 ],322 true323 )324 })175})176177describe("minimum amount of changes", () => {178 runPatchTest(
226 unmodified lines
405 []406 )407})408559describe("same value replacement - 5", () => {560 runPatchTest(561 new Map([["x", 3]]),562 d => {563 d.set("x", 4)564 d.set("x", 3)565 },566 [],567 [],568 true569 )570})571409describe("simple delete", () => {410 runPatchTest(411 {x: 2},412 d => {
10 unmodified lines
modified:__tests__/readme.js+14 added-7 removed
modified:src/common.js+11 added-36 removed
18 unmodified lines
19 if (!value || typeof value !== "object") return false20 if (Array.isArray(value)) return true21 const proto = Object.getPrototypeOf(value)22 if (!proto || proto === Object.prototype) return true23 if (isMap(value)) return true23 return !!value[DRAFTABLE] || !!value.constructor[DRAFTABLE]24}2526export function original(value) {
2 unmodified lines
29 }30 // otherwise return undefined31}3234function assignMap(target, overrides) {35 overrides.forEach(function(override) {36 for (let key in override) {37 if (has(override, key)) {38 target.set(key, override[key])33export const assign =34 Object.assign ||35 function assign(target, value) {36 for (let key in value) {37 if (has(value, key)) {38 target[key] = value[key]39 }40 }41 })42 return target41 return target43}44function assignObjectLegacy(target, overrides) {45 overrides.forEach(function(override) {46 for (let key in override) {47 if (has(override, key)) {48 target[key] = override[key]49 }50 }51 })52 return target53}54export function assign(target, ...overrides) {55 if (isMap(target)) {56 return assignMap(target, overrides)42 }58 if (Object.assign) {59 return Object.assign(target, ...overrides)60 }61 return assignObjectLegacy(target, overrides)62}4344export const ownKeys =45 typeof Reflect !== "undefined" && Reflect.ownKeys46 ? Reflect.ownKeys
5 unmodified lines
52 : Object.getOwnPropertyNames5354export function shallowCopy(base, invokeGetters = false) {55 if (Array.isArray(base)) return base.slice()76 if (isMap(base)) return new Map(base)56 const clone = Object.create(Object.getPrototypeOf(base))57 ownKeys(base).forEach(key => {58 if (key === DRAFT_STATE) {59 return // Never copy over draft state.
19 unmodified lines
79 return clone80}8182export function each(value, cb) {104 if (Array.isArray(value) || isMap(value)) {105 value.forEach((entry, index) => cb(index, entry, value))106 return83 if (Array.isArray(value)) {84 for (let i = 0; i < value.length; i++) cb(i, value[i], value)85 } else {86 ownKeys(value).forEach(key => cb(key, value[key], value))87 }108 ownKeys(value).forEach(key => cb(key, value[key], value))88}8990export function isEnumerable(base, prop) {91 const desc = Object.getOwnPropertyDescriptor(base, prop)
11 unmodified lines
103 } else {104 return x !== x && y !== y105 }106}128129export function isMap(target) {130 return target instanceof Map131}
modified:src/immer.js+6 added-15 removed
7 unmodified lines
8 is,9 isDraft,10 isDraftable,11 isEnumerable,12 isMap,12 shallowCopy,13 DRAFT_STATE,14 NOTHING15} from "./common"
241 unmodified lines
257 if (isDraft(value)) {258 scope.canAutoFreeze = false259 }260262 setProperty(parent, prop, value)261 // Preserve non-enumerable properties.262 if (Array.isArray(parent) || isEnumerable(parent, prop)) {263 parent[prop] = value264 } else {265 Object.defineProperty(parent, prop, {value})266 }267268 // Unchanged drafts are never passed to the `onAssign` hook.269 if (isDraftProp && value === state.base[prop]) return270 }
14 unmodified lines
285 each(root, finalizeProperty)286 return root287 }288}285286function setProperty(parent, prop, value) {287 // Preserve non-enumerable properties.288 if (Array.isArray(parent) || isEnumerable(parent, prop)) {289 parent[prop] = value290 return291 }292 if (isMap(parent)) {293 parent.set(prop, value)294 return295 }296 Object.defineProperty(parent, prop, {value})297}
modified:src/patches.js+34 added-61 removed
1import {each, isMap} from "./common"1import {each} from "./common"23export function generatePatches(state, basePath, patches, inversePatches) {4 const generatePatchesFn = Array.isArray(state.base)5 ? generateArrayPatches6 : isMap(state.base)7 ? generatePatchesFromAssigned(8 (map, key) => map.get(key),9 (map, key) => map.has(key)10 )11 : generatePatchesFromAssigned(12 (obj, key) => obj[key],13 (obj, key) => key in obj14 )1516 generatePatchesFn(state, basePath, patches, inversePatches)4 Array.isArray(state.base)5 ? generateArrayPatches(state, basePath, patches, inversePatches)6 : generateObjectPatches(state, basePath, patches, inversePatches)7}89function generateArrayPatches(state, basePath, patches, inversePatches) {10 let {base, copy, assigned} = state
63 unmodified lines
74 })75 }76}7788function generatePatchesFromAssigned(getValueByKey, hasKey) {89 return function(state, basePath, patches, inversePatches) {90 const {base, copy} = state91 each(state.assigned, (key, assignedValue) => {92 const origValue = getValueByKey(base, key)93 const value = getValueByKey(copy, key)94 const op = !assignedValue95 ? "remove"96 : hasKey(base, key)97 ? "replace"98 : "add"99 if (origValue === value && op === "replace") return100 const path = basePath.concat(key)101 patches.push(op === "remove" ? {op, path} : {op, path, value})102 inversePatches.push(103 op === "add"104 ? {op: "remove", path}105 : op === "remove"106 ? {op: "add", path, value: origValue}107 : {op: "replace", path, value: origValue}108 )109 })78function generateObjectPatches(state, basePath, patches, inversePatches) {79 const {base, copy} = state80 each(state.assigned, (key, assignedValue) => {81 const origValue = base[key]82 const value = copy[key]83 const op = !assignedValue ? "remove" : key in base ? "replace" : "add"84 if (origValue === value && op === "replace") return85 const path = basePath.concat(key)86 patches.push(op === "remove" ? {op, path} : {op, path, value})87 inversePatches.push(88 op === "add"89 ? {op: "remove", path}90 : op === "remove"91 ? {op: "add", path, value: origValue}92 : {op: "replace", path, value: origValue}93 )94 })110 }95}9697export function applyPatches(draft, patches) {98 for (let i = 0; i < patches.length; i++) {
3 unmodified lines
102 draft = patch.value103 } else {104 let base = draft105 for (let i = 0; i < path.length - 1; i++) {122 if (isMap(base.base)) {123 base = base.get(path[i])124 } else {125 base = base[path[i]]106 base = base[path[i]]126 }107 if (!base || typeof base !== "object")108 throw new Error("Cannot apply patch, path doesn't resolve: " + path.join("/")) // prettier-ignore109 }110 const key = path[path.length - 1]131132 const replace = (key, value) =>133 isMap(base.base) ? base.set(key, value) : (base[key] = value)134 const add = (key, value) =>135 Array.isArray(base)136 ? base.splice(key, 0, value)137 : isMap(base.base)138 ? base.set(key, value)139 : (base[key] = value)140 const remove = key =>141 Array.isArray(base)142 ? base.splice(key, 1)143 : isMap(base.base)144 ? base.delete(key)145 : delete base[key]146111 switch (patch.op) {112 case "replace":149 replace(key, patch.value)113 base[key] = patch.value114 break115 case "add":152 add(key, patch.value)116 if (Array.isArray(base)) {117 // TODO: support "foo/-" paths for appending to an array118 base.splice(key, 0, patch.value)119 } else {120 base[key] = patch.value121 }122 break123 case "remove":155 remove(key)124 if (Array.isArray(base)) {125 base.splice(key, 1)126 } else {127 delete base[key]128 }129 break130 default:131 throw new Error("Unsupported patch operation: " + patch.op)132 }
4 unmodified lines
modified:src/proxy.js+78 added-194 removed
4 unmodified lines
5 has,6 is,7 isDraftable,8 isDraft,9 isMap,9 shallowCopy,10 DRAFT_STATE11} from "./common"12import {ImmerScope} from "./scope"1314// Do nothing before being finalized.15export function willFinalize() {}1618/**19 * Returns a new draft of the `base` object.20 *21 * The second argument is the parent draft-state (used internally).22 */17export function createProxy(base, parent) {18 const scope = parent ? parent.scope : ImmerScope.current19 const state = {20 // Track which produce call this is associated with.
17 unmodified lines
38 // Called by the `produce` function.39 revoke: null40 }4148 let proxyTarget = state49 let traps = objectTraps50 if (Array.isArray(base)) {51 proxyTarget = [state]52 traps = arrayTraps53 } else if (isMap(base)) {54 traps = mapTraps55 }42 const {revoke, proxy} = Array.isArray(base)43 ? // [state] is used for arrays, to make sure the proxy is array-ish and not violate invariants,44 // although state itself is an object45 Proxy.revocable([state], arrayTraps)46 : Proxy.revocable(state, objectTraps)4757 const {revoke, proxy} = Proxy.revocable(proxyTarget, traps)5848 state.draft = proxy49 state.revoke = revoke5051 scope.drafts.push(proxy)52 return proxy53}5466/**67 * Object drafts68 */6955const objectTraps = {71 get(state, prop) {72 if (prop === DRAFT_STATE) return state73 let {drafts} = state7475 // Check for existing draft in unmodified state.76 if (!state.modified && has(drafts, prop)) {77 return drafts[prop]78 }7980 const value = source(state)[prop]81 if (state.finalized || !isDraftable(value)) {82 return value83 }8485 // Check for existing draft in modified state.86 if (state.modified) {87 // Assigned values are never drafted. This catches any drafts we created, too.88 if (value !== peek(state.base, prop)) return value89 // Store drafts on the copy (when one exists).90 drafts = state.copy91 }9293 return (drafts[prop] = createProxy(value, state))56 get,57 has(target, prop) {58 return prop in source(target)59 },95 has(state, prop) {96 return prop in source(state)60 ownKeys(target) {61 return Reflect.ownKeys(source(target))62 },98 ownKeys(state) {99 return Reflect.ownKeys(source(state))100 },101 set(state, prop, value) {102 if (!state.modified) {103 const baseValue = peek(state.base, prop)104 // Optimize based on value's truthiness. Truthy values are guaranteed to105 // never be undefined, so we can avoid the `in` operator. Lastly, truthy106 // values may be drafts, but falsy values are never drafts.107 const isUnchanged = value108 ? is(baseValue, value) || value === state.drafts[prop]109 : is(baseValue, value) && prop in state.base110 if (isUnchanged) return true111 markChanged(state)112 }113 state.assigned[prop] = true114 state.copy[prop] = value115 return true116 },117 deleteProperty(state, prop) {118 // The `undefined` check is a fast path for pre-existing keys.119 if (peek(state.base, prop) !== undefined || prop in state.base) {120 state.assigned[prop] = false121 markChanged(state)122 }123 if (state.copy) delete state.copy[prop]124 return true125 },126 // Note: We never coerce `desc.value` into an Immer draft, because we can't make127 // the same guarantee in ES5 mode.128 getOwnPropertyDescriptor(state, prop) {129 const owner = source(state)130 const desc = Reflect.getOwnPropertyDescriptor(owner, prop)131 if (desc) {132 desc.writable = true133 desc.configurable = !Array.isArray(owner) || prop !== "length"134 }135 return desc136 },63 set,64 deleteProperty,65 getOwnPropertyDescriptor,66 defineProperty() {67 throw new Error("Object.defineProperty() cannot be used on an Immer draft") // prettier-ignore68 },140 getPrototypeOf(state) {141 return Object.getPrototypeOf(state.base)69 getPrototypeOf(target) {70 return Object.getPrototypeOf(target.base)71 },72 setPrototypeOf() {73 throw new Error("Object.setPrototypeOf() cannot be used on an Immer draft") // prettier-ignore74 }75}76148/**149 * Array drafts150 */15177const arrayTraps = {}78each(objectTraps, (key, fn) => {79 arrayTraps[key] = function() {80 arguments[0] = arguments[0][0]
12 unmodified lines
93 }94 return objectTraps.set.call(this, state[0], prop, value)95}96172/**173 * Map drafts174 */97// returns the object we should be reading the current value from, which is base, until some change has been made98function source(state) {99 return state.copy || state.base100}101176const mapTraps = {177 get(state, prop, receiver) {178 const getter = mapGetters[prop]179 return getter180 ? getter(state, prop, receiver)181 : Reflect.get(state, prop, receiver)182 }102// Access a property without creating an Immer draft.103function peek(draft, prop) {104 const state = draft[DRAFT_STATE]105 const desc = Reflect.getOwnPropertyDescriptor(106 state ? source(state) : draft,107 prop108 )109 return desc && desc.value110}184const mapGetters = {185 [DRAFT_STATE]: state => state,186 size: state => source(state).size,187 has(state, prop) {188 state = source(state)189 return state.has.bind(state)190 },191 set: state => (key, value) => {192 markChanged(state)193 state.assigned[key] = true194 state.copy.set(key, value)195 return state.draft196 },197 delete: state => key => {198 markChanged(state)199 state.assigned[key] = false200 return state.copy.delete(key)201 },202 clear: state => () => {203 markChanged(state)204 state.assigned = {}205 for (const key of source(state).keys()) {206 state.assigned[key] = false207 }208 return state.copy.clear()209 },210 forEach: (state, _, receiver) => (cb, thisArg) =>211 source(state).forEach((_, key, map) => {212 const value = receiver.get(key)213 cb.call(thisArg, value, key, map)214 }),215 get: state => key => {216 if (!state.modified && has(state.drafts, key)) {217 return state.drafts[key]218 }111220 if (state.modified && state.copy.has(key)) {221 return state.copy.get(key)222 }112function get(state, prop) {113 if (prop === DRAFT_STATE) return state114 let {drafts} = state115224 const value = source(state).get(key)116 // Check for existing draft in unmodified state.117 if (!state.modified && has(drafts, prop)) {118 return drafts[prop]119 }120121 const value = source(state)[prop]226 if (state.finalized || !isDraftable(value)) {227 return value228 }122 if (state.finalized || !isDraftable(value)) {123 return value124 }125230 const draft = createProxy(value, state)126 // Check for existing draft in modified state.127 if (state.modified) {128 // Assigned values are never drafted. This catches any drafts we created, too.129 if (value !== peek(state.base, prop)) return value130 // Store drafts on the copy (when one exists).131 drafts = state.copy132 }133232 if (!state.modified) {233 state.drafts[key] = draft234 } else {235 state.copy.set(key, draft)236 }237238 return draft239 },240 keys: state => () => source(state).keys(),241 values: iterateMapValues,242 entries: iterateMapValues,243 [Symbol.iterator]: iterateMapValues134 return (drafts[prop] = createProxy(value, state))135}136246/** Map.prototype.values _-or-_ Map.prototype.entries */247function iterateMapValues(state, prop, receiver) {248 const getYieldable =249 prop === "values" ? (key, value) => value : (key, value) => [key, value]250251 return () => {252 const iterator = source(state)[Symbol.iterator]()253 return makeIterable(() => {254 const result = iterator.next()255 if (!result.done) {256 const [key] = result.value257 const value = receiver.get(key)258 result.value = getYieldable(key, value)259 }260 return result261 })137function set(state, prop, value) {138 if (!state.modified) {139 const baseValue = peek(state.base, prop)140 // Optimize based on value's truthiness. Truthy values are guaranteed to141 // never be undefined, so we can avoid the `in` operator. Lastly, truthy142 // values may be drafts, but falsy values are never drafts.143 const isUnchanged = value144 ? is(baseValue, value) || value === state.drafts[prop]145 : is(baseValue, value) && prop in state.base146 if (isUnchanged) return true147 markChanged(state)148 }149 state.assigned[prop] = true150 state.copy[prop] = value151 return true152}153265/**266 * Helpers267 */268269// returns the object we should be reading the current value from, which is base, until some change has been made270function source(state) {271 return state.copy || state.base154function deleteProperty(state, prop) {155 // The `undefined` check is a fast path for pre-existing keys.156 if (peek(state.base, prop) !== undefined || prop in state.base) {157 state.assigned[prop] = false158 markChanged(state)159 }160 if (state.copy) delete state.copy[prop]161 return true162}163274// Access a property without creating an Immer draft.275function peek(draft, prop) {276 const state = draft[DRAFT_STATE]277 const desc = Reflect.getOwnPropertyDescriptor(278 state ? source(state) : draft,279 prop280 )281 return desc && desc.value164// Note: We never coerce `desc.value` into an Immer draft, because we can't make165// the same guarantee in ES5 mode.166function getOwnPropertyDescriptor(state, prop) {167 const owner = source(state)168 const desc = Reflect.getOwnPropertyDescriptor(owner, prop)169 if (desc) {170 desc.writable = true171 desc.configurable = !Array.isArray(owner) || prop !== "length"172 }173 return desc174}175176function markChanged(state) {177 if (!state.modified) {
2 unmodified lines
180 state.drafts = null181 if (state.parent) markChanged(state.parent)182 }183}292293function makeIterable(next) {294 let self295 return (self = {296 [Symbol.iterator]: () => self,297 next298 })299}
modified:readme.md+16 added-3 removed
526 unmodified lines
527```528529## Supported object types530531Plain objects, arrays, and `Map` objects are always drafted by Immer.531Plain objects and arrays are always drafted by Immer.532533Every other object must use the `immerable` symbol to mark itself as compatible with Immer. When one of these objects is mutated within a producer, its prototype is preserved between copies.534535```js
13 unmodified lines
549For arrays, only numeric properties and the `length` property can be mutated. Custom properties are not preserved on arrays.550551When working with `Date` objects, you should always create a new `Date` instance instead of mutating an existing `Date` object.552553`Set` objects cannot be drafted. As a workaround, you should clone them before mutating them in a producer:553Built-in classes like `Map` and `Set` are not supported. As a workaround, you should clone them before mutating them in a producer:554555```js556const state = {557 set: new Set()557 set: new Set(),558 map: new Map()559}560const nextState = produce(state, draft => {561 // Don't use any Set methods, as that mutates the instance!562 draft.set.add("foo") // ❌
5 unmodified lines
568 newSet.add("foo")569570 // 3. Update the draft with the new set571 draft.set = newSet572573 // Similarly, don't use any Map methods.574 draft.map.set("foo", "bar") // ❌575576 // 1. Instead, clone the map (just once)577 const newMap = new Map(draft.map) // ✅578579 // 2. Mutate it580 newMap.set("foo", "bar")581582 // 3. Update the draft583 draft.map = newMap584})585```586587## TypeScript or Flow
203 unmodified lines