Skip to content
Myr

feat: `Map` support

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

Includes support for: - mutable drafts in `produce` callbacks - patch listeners

authored by keenondrums · committed by Alec Larson · parent a437755 · Browse files · 7 files+584 added−74 removed
This commit

State

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

Trailers

  • Note: Do not use Map objects in ES5 mode!

Diff stats

7 files+584 added−74 removed

  • tests:+361 added−18 removed
  • other:+223 added−56 removed

7 files+584 added−74 removed

modified:__tests__/base.js+204 added
297 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 s.aMap.set("force", true)433 })434 expect(nextState).not.toBe(baseState)435 expect(nextState.aMap).not.toBe(baseState.aMap)436 expect(nextState.aMap.get("force")).toEqual(true)437 })438439 it("returns 'size'", () => {440 const nextState = produce(baseState, s => {441 s.aMap.set("newKey", true)442 expect(s.aMap.size).toBe(baseState.aMap.size + 1)443 })444 expect(nextState).not.toBe(baseState)445 expect(nextState.aMap).not.toBe(baseState.aMap)446 expect(nextState.aMap.get("newKey")).toEqual(true)447 expect(nextState.aMap.size).toEqual(baseState.aMap.size + 1)448 })449450 it("can use 'delete' to remove items", () => {451 const nextState = produce(baseState, s => {452 expect(s.aMap.has("jedi")).toBe(true)453 s.aMap.delete("jedi")454 expect(s.aMap.has("jedi")).toBe(false)455 })456 expect(nextState.aMap).not.toBe(baseState.aMap)457 expect(nextState.aMap.size).toBe(baseState.aMap.size - 1)458 expect(baseState.aMap.has("jedi")).toBe(true)459 expect(nextState.aMap.has("jedi")).toBe(false)460 })461462 it("can use 'clear' to remove items", () => {463 const nextState = produce(baseState, s => {464 expect(s.aMap.size).not.toBe(0)465 s.aMap.clear()466 expect(s.aMap.size).toBe(0)467 })468 expect(nextState.aMap).not.toBe(baseState.aMap)469 expect(nextState.aMap.size).toBe(0)470 })471472 it("support 'has'", () => {473 const nextState = produce(baseState, s => {474 expect(s.aMap.has("newKey")).toBe(false)475 s.aMap.set("newKey", true)476 expect(s.aMap.has("newKey")).toBe(true)477 })478 expect(nextState).not.toBe(baseState)479 expect(nextState.aMap).not.toBe(baseState.aMap)480 expect(nextState.aMap.has("newKey")).toEqual(true)481 })482483 it("supports nested maps", () => {484 const base = new Map([485 ["first", new Map([["second", {prop: "test"}]])]486 ])487 const result = produce(base, draft => {488 draft.get("first").get("second").prop = "test1"489 })490 expect(result).not.toBe(base)491 expect(result.get("first")).not.toBe(base.get("first"))492 expect(result.get("first").get("second")).not.toBe(493 base.get("first").get("second")494 )495 expect(base.get("first").get("second").prop).toBe("test")496 expect(result.get("first").get("second").prop).toBe("test1")497 })498 })499 }500501 it("supports `immerable` symbol on constructor", () => {502 class One {}503 One[immerable] = true504 const baseState = new One()
794 unmodified lines
1299 function createBaseState() {1300 const data = {1301 anInstance: new Foo(),1302 anArray: [3, 2, {c: 3}, 1],1303 aMap: new Map([1304 ["jedi", {name: "Luke", skill: 10}],1305 ["jediTotal", 42],1306 ["force", "these aren't the droids you're looking for"]1307 ]),1308 aProp: "hi",1309 anObject: {1310 nested: {1311 yummie: true
167 unmodified lines
modified:__tests__/patch.js+150 added-4 removed
1 unmodified line
2import produce, {setUseProxies, applyPatches} from "../src/index"34jest.setTimeout(1000)56function runPatchTest(base, producer, patches, inversePathes) {6function runPatchTest(7 base,8 producer,9 patches,10 inversePathes,11 proxyOnly = false12) {13 function runPatchTestHelper() {14 let recordedPatches15 let recordedInversePatches16 const res = produce(base, producer, (p, i) => {
16 unmodified lines
33 })34 }3536 describe(`proxy`, () => {31 setUseProxies(true)37 beforeAll(() => setUseProxies(true))38 runPatchTestHelper()39 })4041 describe(`es5`, () => {36 setUseProxies(false)37 runPatchTestHelper()42 if (!proxyOnly) {43 beforeAll(() => setUseProxies(false))44 runPatchTestHelper()45 }46 })47}4849describe("applyPatches", () => {
65 unmodified lines
115 [{op: "replace", path: ["x", 0, "y"], value: 5}]116 )117})118119describe("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("delete 1", () => {144 runPatchTest(145 {x: {y: 4}},146 d => {
2 unmodified lines
149 [{op: "remove", path: ["x"]}]150 )151})152153describe("delete 2", () => {154 runPatchTest(155 new Map([["x", 1]]),156 d => {157 d.delete("x")158 },159 [{op: "remove", path: ["x"]}],160 [{op: "add", path: ["x"], value: 1}],161 true162 )163})164165describe("delete 3", () => {166 runPatchTest(167 {x: new Map([["y", 1]])},168 d => {169 d.x.delete("y")170 },171 [{op: "remove", path: ["x", "y"]}],172 [{op: "add", path: ["x", "y"], value: 1}],173 true174 )175})176177describe("renaming properties", () => {178 describe("nested object (no changes)", () => {179 runPatchTest(180 {a: {b: 1}},
7 unmodified lines
188 ]189 )190 })191192 describe("nested map (no changes)", () => {193 runPatchTest(194 new Map([["a", new Map([["b", 1]])]]),195 d => {196 d.set("x", d.get("a"))197 d.delete("a")198 },199 [200 {op: "add", path: ["x"], value: new Map([["b", 1]])},201 {op: "remove", path: ["a"]}202 ],203 [204 {op: "remove", path: ["x"]},205 {op: "add", path: ["a"], value: new Map([["b", 1]])}206 ],207 true208 )209 })210211 describe("nested object (with changes)", () => {212 runPatchTest(213 {a: {b: 1, c: 1}},214 d => {
12 unmodified lines
227 ]228 )229 })230231 describe("nested map (with changes)", () => {232 runPatchTest(233 new Map([["a", new Map([["b", 1], ["c", 1]])]]),234 d => {235 let a = d.get("a")236 a.set("b", 2) // change237 a.delete("c") // delete238 a.set("y", 2) // add239240 // rename241 d.set("x", a)242 d.delete("a")243 },244 [245 {op: "add", path: ["x"], value: new Map([["b", 2], ["y", 2]])},246 {op: "remove", path: ["a"]}247 ],248 [249 {op: "remove", path: ["x"]},250 {op: "add", path: ["a"], value: new Map([["b", 1], ["c", 1]])}251 ],252 true253 )254 })255256 describe("deeply nested object (with changes)", () => {257 runPatchTest(258 {a: {b: {c: 1, d: 1}}},259 d => {
11 unmodified lines
271 {op: "remove", path: ["a", "b"]}272 ]273 )274 })275276 describe("deeply nested map (with changes)", () => {277 runPatchTest(278 new Map([["a", new Map([["b", new Map([["c", 1], ["d", 1]])]])]]),279 d => {280 let b = d.get("a").get("b")281 b.set("c", 2) // change282 b.delete("d") // delete283 b.set("y", 2) // add284285 // rename286 d.get("a").set("x", b)287 d.get("a").delete("b")288 },289 [290 {291 op: "add",292 path: ["a", "x"],293 value: new Map([["c", 2], ["y", 2]])294 },295 {op: "remove", path: ["a", "b"]}296 ],297 [298 {op: "remove", path: ["a", "x"]},299 {300 op: "add",301 path: ["a", "b"],302 value: new Map([["c", 1], ["d", 1]])303 }304 ],305 true306 )307 })308})309310describe("minimum amount of changes", () => {311 runPatchTest(
226 unmodified lines
538 []539 )540})541542describe("same value replacement - 5", () => {543 runPatchTest(544 new Map([["x", 3]]),545 d => {546 d.set("x", 4)547 d.set("x", 3)548 },549 [],550 [],551 true552 )553})554555describe("simple delete", () => {556 runPatchTest(557 {x: 2},558 d => {
10 unmodified lines
modified:__tests__/readme.js+7 added-14 removed
modified:src/common.js+36 added-11 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 true24 return !!value[DRAFTABLE] || !!value.constructor[DRAFTABLE]25}2627export function original(value) {
2 unmodified lines
30 }31 // otherwise return undefined32}3333export 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]34function 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])39 }40 }41 })41 return target42 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)57 }58 if (Object.assign) {59 return Object.assign(target, ...overrides)60 }61 return assignObjectLegacy(target, overrides)62}6364export const ownKeys =65 typeof Reflect !== "undefined" && Reflect.ownKeys66 ? Reflect.ownKeys
5 unmodified lines
72 : Object.getOwnPropertyNames7374export function shallowCopy(base, invokeGetters = false) {75 if (Array.isArray(base)) return base.slice()76 if (isMap(base)) return new Map(base)77 const clone = Object.create(Object.getPrototypeOf(base))78 ownKeys(base).forEach(key => {79 if (key === DRAFT_STATE) {80 return // Never copy over draft state.
19 unmodified lines
100 return clone101}102103export function each(value, cb) {83 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))104 if (Array.isArray(value) || isMap(value)) {105 value.forEach((entry, index) => cb(index, entry, value))106 return107 }108 ownKeys(value).forEach(key => cb(key, value[key], value))109}110111export function isEnumerable(base, prop) {112 return Object.getOwnPropertyDescriptor(base, prop).enumerable
10 unmodified lines
123 } else {124 return x !== x && y !== y125 }126}127128export function isMap(target) {129 return target instanceof Map130}
modified:src/immer.js+15 added-6 removed
7 unmodified lines
8 is,9 isDraft,10 isDraftable,11 isEnumerable,12 isMap,13 shallowCopy,14 DRAFT_STATE,15 NOTHING16} from "./common"
241 unmodified lines
258 if (isDraft(value)) {259 scope.canAutoFreeze = false260 }261261 // Preserve non-enumerable properties.262 if (Array.isArray(parent) || isEnumerable(parent, prop)) {263 parent[prop] = value264 } else {265 Object.defineProperty(parent, prop, {value})266 }262 this.assignPropertyInParent(parent, prop, value)263264 // Unchanged drafts are never passed to the `onAssign` hook.265 if (isDraftProp && value === state.base[prop]) return266 }
13 unmodified lines
280281 each(root, finalizeProperty)282 return root283 }284285 assignPropertyInParent(parent, prop, value) {286 if (isMap(parent)) {287 parent.set(prop, value)288 return289 }290 // Preserve non-enumerable properties.291 if (Array.isArray(parent) || isEnumerable(parent, prop)) {292 parent[prop] = value293 return294 }295 Object.defineProperty(parent, prop, {value})296 }297}
modified:src/patches.js+61 added-34 removed
1import {each} from "./common"1import {each, isMap} from "./common"23export function generatePatches(state, basePath, patches, inversePatches) {4 Array.isArray(state.base)5 ? generateArrayPatches(state, basePath, patches, inversePatches)6 : generateObjectPatches(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)17}1819function generateArrayPatches(state, basePath, patches, inversePatches) {20 let {base, copy, assigned} = state
63 unmodified lines
84 })85 }86}8788function 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)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 })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 })110 }111}112113export function applyPatches(draft, patches) {114 for (let i = 0; i < patches.length; i++) {
3 unmodified lines
118 draft = patch.value119 } else {120 let base = draft121 for (let i = 0; i < path.length - 1; i++) {122 if (isMap(base.base)) {123 base = base.get(path[i])124 } else {106 base = base[path[i]]125 base = base[path[i]]126 }127 if (!base || typeof base !== "object")128 throw new Error("Cannot apply patch, path doesn't resolve: " + path.join("/")) // prettier-ignore129 }130 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]146147 switch (patch.op) {148 case "replace":113 base[key] = patch.value149 replace(key, patch.value)150 break151 case "add":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 }152 add(key, patch.value)153 break154 case "remove":124 if (Array.isArray(base)) {125 base.splice(key, 1)126 } else {127 delete base[key]128 }155 remove(key)156 break157 default:158 throw new Error("Unsupported patch operation: " + patch.op)159 }
4 unmodified lines
modified:src/proxy.js+111 added-5 removed
4 unmodified lines
5 has,6 is,7 isDraftable,8 isDraft,9 isMap,10 shallowCopy,11 DRAFT_STATE12} from "./common"13import {ImmerScope} from "./scope"
25 unmodified lines
39 // Called by the `produce` function.40 revoke: null41 }4242 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)43 let proxyTarget = state44 let traps = objectTraps45 if (Array.isArray(base)) {46 proxyTarget = [state]47 traps = arrayTraps48 } else if (isMap(base)) {49 traps = mapTraps50 }5152 const {revoke, proxy} = Proxy.revocable(proxyTarget, traps)5354 state.draft = proxy55 state.revoke = revoke5657 scope.drafts.push(proxy)
41 unmodified lines
99 }100 return objectTraps.set.call(this, state[0], prop, value)101}102103const mapTraps = {104 get(state, prop, receiver) {105 if (prop === DRAFT_STATE) return state106 if (prop === "size") return source(state)[prop]107 if (prop === "has") {108 const stateCurrent = source(state)109 return stateCurrent[prop].bind(stateCurrent)110 }111 if (prop === "set") {112 return function(key, value) {113 markChanged(state)114 state.assigned[key] = true115 return state.copy.set(key, value)116 }117 }118 if (prop === "delete") {119 return function(key) {120 markChanged(state)121 state.assigned[key] = false122 return state.copy.delete(key)123 }124 }125 if (prop === "clear") {126 return function() {127 markChanged(state)128 state.assigned = {}129 for (const key of source(state).keys()) {130 state.assigned[key] = false131 }132 return state.copy.clear()133 }134 }135 if (prop === "forEach") {136 return function(cb) {137 return source(state).forEach((_, key, map) => {138 const value = receiver.get(key)139 cb(value, key, map)140 }, this)141 }142 }143 if (prop === "get") {144 return function(key) {145 if (!state.modified && has(state.drafts, key)) {146 return state.drafts[key]147 }148 if (state.modified && state.copy.has(key)) {149 return state.copy.get(key)150 }151152 const value = source(state).get(key)153154 if (state.finalized || !isDraftable(value)) {155 return value156 }157158 const valueProxied = createProxy(value, state)159 if (!state.modified) {160 state.drafts[key] = valueProxied161 } else {162 state.copy.set(key, valueProxied)163 }164 return valueProxied165 }166 }167 if (168 prop === Symbol.iterator ||169 prop === "entries" ||170 prop === "values"171 ) {172 let getYieldable = (key, value) => [key, value]173 if (prop === "values") {174 getYieldable = (key, value) => value175 }176 return function*() {177 const iterator = source(state)[Symbol.iterator]()178 let result = iterator.next()179 while (!result.done) {180 const [key] = result.value181 const value = receiver.get(key)182 yield getYieldable(key, value)183 result = iterator.next()184 }185 }186 }187 if (prop === "keys") {188 return function*() {189 const iterator = source(state).keys()190 let result = iterator.next()191 while (!result.done) {192 const key = result.value193 yield key194 result = iterator.next()195 }196 }197 }198199 return Reflect.get(state, prop, receiver)200 }201}202203// returns the object we should be reading the current value from, which is base, until some change has been made204function source(state) {205 return state.copy || state.base206}
83 unmodified lines