Skip to content
Myr

feat: `Set` drafts

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

Support for patch listeners included BREAKING CHANGE: `Set` objects are now drafted

authored by Andrey Goncharov · committed by Alec Larson · parent a674a78 · Browse files · 7 files+547 added−44 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+547 added−44 removed

  • tests:+325 added−11 removed
  • other:+222 added−33 removed

7 files+547 added−44 removed

modified:__tests__/base.js+215 added-1 removed
436 unmodified lines
437 expect(nextState.aMap).not.toBe(baseState.aMap)438 expect(nextState.aMap.get("force")).toEqual(true)439 })440441 it("state stays the same if the the same item is assigned by key", () => {442 const nextState = produce(baseState, s => {443 s.aMap.set("jediTotal", 42)444 })445 expect(nextState).toBe(baseState)446 expect(nextState.aMap).toBe(baseState.aMap)447 })448449 it("returns 'size'", () => {450 const nextState = produce(baseState, s => {451 s.aMap.set("newKey", true)452 expect(s.aMap.size).toBe(baseState.aMap.size + 1)
22 unmodified lines
475 s.aMap.clear()476 expect(s.aMap.size).toBe(0)477 })478 expect(nextState.aMap).not.toBe(baseState.aMap)479 expect(baseState.aMap.size).not.toBe(0)480 expect(nextState.aMap.size).toBe(0)481 })482483 it("support 'has'", () => {
3 unmodified lines
487 expect(s.aMap.has("newKey")).toBe(true)488 })489 expect(nextState).not.toBe(baseState)490 expect(nextState.aMap).not.toBe(baseState.aMap)491 expect(baseState.aMap.has("newKey")).toBe(false)482 expect(nextState.aMap.has("newKey")).toEqual(true)492 expect(nextState.aMap.has("newKey")).toBe(true)493 })494495 it("supports nested maps", () => {496 const base = new Map([
10 unmodified lines
507 expect(base.get("first").get("second").prop).toBe("test")508 expect(result.get("first").get("second").prop).toBe("test1")509 })510 })511512 describe("set drafts", () => {513 it("supports iteration", () => {514 const base = new Set([{id: 1, a: 1}, {id: 2, a: 1}])515 const findById = (set, id) => {516 for (const item of set) {517 if (item.id === id) return item518 }519 return null520 }521 const result = produce(base, draft => {522 const obj1 = findById(draft, 1)523 const obj2 = findById(draft, 2)524 obj1.a = 2525 obj2.a = 2526 })527 expect(result).not.toBe(base)528 expect(base).toEqual(529 new Set([{id: 1, a: 1}, {id: 2, a: 1}])530 )531 expect(result).toEqual(532 new Set([{id: 1, a: 2}, {id: 2, a: 2}])533 )534 })535536 it("supports 'entries'", () => {537 const base = new Set([{id: 1, a: 1}, {id: 2, a: 1}])538 const findById = (set, id) => {539 for (const [item1, item2] of set.entries()) {540 expect(item1).toBe(item2)541 if (item1.id === id) return item1542 }543 return null544 }545 const result = produce(base, draft => {546 const obj1 = findById(draft, 1)547 const obj2 = findById(draft, 2)548 obj1.a = 2549 obj2.a = 2550 })551 expect(result).not.toBe(base)552 expect(base).toEqual(553 new Set([{id: 1, a: 1}, {id: 2, a: 1}])554 )555 expect(result).toEqual(556 new Set([{id: 1, a: 2}, {id: 2, a: 2}])557 )558 })559560 it("supports 'values'", () => {561 const base = new Set([{id: 1, a: 1}, {id: 2, a: 1}])562 const findById = (set, id) => {563 for (const item of set.values()) {564 if (item.id === id) return item565 }566 return null567 }568 const result = produce(base, draft => {569 const obj1 = findById(draft, 1)570 const obj2 = findById(draft, 2)571 obj1.a = 2572 obj2.a = 2573 })574 expect(result).not.toBe(base)575 expect(base).toEqual(576 new Set([{id: 1, a: 1}, {id: 2, a: 1}])577 )578 expect(result).toEqual(579 new Set([{id: 1, a: 2}, {id: 2, a: 2}])580 )581 })582583 it("supports 'keys'", () => {584 const base = new Set([{id: 1, a: 1}, {id: 2, a: 1}])585 const findById = (set, id) => {586 for (const item of set.keys()) {587 if (item.id === id) return item588 }589 return null590 }591 const result = produce(base, draft => {592 const obj1 = findById(draft, 1)593 const obj2 = findById(draft, 2)594 obj1.a = 2595 obj2.a = 2596 })597 expect(result).not.toBe(base)598 expect(base).toEqual(599 new Set([{id: 1, a: 1}, {id: 2, a: 1}])600 )601 expect(result).toEqual(602 new Set([{id: 1, a: 2}, {id: 2, a: 2}])603 )604 })605606 it("supports forEach with mutation after reads", () => {607 const base = new Set([{id: 1, a: 1}, {id: 2, a: 2}])608 const result = produce(base, draft => {609 let sum1 = 0610 draft.forEach(({a}) => {611 sum1 += a612 })613 expect(sum1).toBe(3)614 let sum2 = 0615 draft.forEach(item => {616 item.a += 10617 sum2 += item.a618 })619 expect(sum2).toBe(23)620 })621 expect(result).not.toBe(base)622 expect(base).toEqual(623 new Set([{id: 1, a: 1}, {id: 2, a: 2}])624 )625 expect(result).toEqual(626 new Set([{id: 1, a: 11}, {id: 2, a: 12}])627 )628 })629630 it("state stays the same if the same item is added", () => {631 const nextState = produce(baseState, s => {632 s.aSet.add("Luke")633 })634 expect(nextState).toBe(baseState)635 expect(nextState.aSet).toBe(baseState.aSet)636 })637638 it("can add new items", () => {639 const nextState = produce(baseState, s => {640 // Set.prototype.set should return the Set itself641 const res = s.aSet.add("force")642 expect(res).toBe(s.aSet[DRAFT_STATE].draft)643 })644 expect(nextState).not.toBe(baseState)645 expect(nextState.aSet).not.toBe(baseState.aSet)646 expect(baseState.aSet.has("force")).toBe(false)647 expect(nextState.aSet.has("force")).toBe(true)648 })649650 it("returns 'size'", () => {651 const nextState = produce(baseState, s => {652 s.aSet.add("newKey")653 expect(s.aSet.size).toBe(baseState.aSet.size + 1)654 })655 expect(nextState).not.toBe(baseState)656 expect(nextState.aSet).not.toBe(baseState.aSet)657 expect(nextState.aSet.has("newKey")).toBe(true)658 expect(nextState.aSet.size).toEqual(baseState.aSet.size + 1)659 })660661 it("can use 'delete' to remove items", () => {662 const nextState = produce(baseState, s => {663 expect(s.aSet.has("Luke")).toBe(true)664 s.aSet.delete("Luke")665 expect(s.aSet.has("Luke")).toBe(false)666 })667 expect(nextState.aSet).not.toBe(baseState.aSet)668 expect(nextState.aSet.size).toBe(baseState.aSet.size - 1)669 expect(baseState.aSet.has("Luke")).toBe(true)670 expect(nextState.aSet.has("Luke")).toBe(false)671 })672673 it("can use 'clear' to remove items", () => {674 const nextState = produce(baseState, s => {675 expect(s.aSet.size).not.toBe(0)676 s.aSet.clear()677 expect(s.aSet.size).toBe(0)678 })679 expect(nextState.aSet).not.toBe(baseState.aSet)680 expect(baseState.aSet.size).not.toBe(0)681 expect(nextState.aSet.size).toBe(0)682 })683684 it("supports 'has'", () => {685 const nextState = produce(baseState, s => {686 expect(s.aSet.has("newKey")).toBe(false)687 s.aSet.add("newKey")688 expect(s.aSet.has("newKey")).toBe(true)689 })690 expect(nextState).not.toBe(baseState)691 expect(nextState.aSet).not.toBe(baseState.aSet)692 expect(baseState.aSet.has("newKey")).toBe(false)693 expect(nextState.aSet.has("newKey")).toBe(true)694 })695696 it("supports nested sets", () => {697 const base = new Set([new Set(["Serenity"])])698 const result = produce(base, draft => {699 draft.forEach(nestedItem => nestedItem.add("Firefly"))700 })701 expect(result).not.toBe(base)702 expect(base).toEqual(new Set([new Set(["Serenity"])]))703 expect(result).toEqual(704 new Set([new Set(["Serenity", "Firefly"])])705 )706 })707 })708 }709710 it("supports `immerable` symbol on constructor", () => {711 class One {}
801 unmodified lines
1513 ["jedi", {name: "Luke", skill: 10}],1514 ["jediTotal", 42],1515 ["force", "these aren't the droids you're looking for"]1516 ]),1517 aSet: new Set([1518 "Luke",1519 42,1520 {1521 jedi: "Yoda"1522 }1523 ]),1524 aProp: "hi",1525 anObject: {1526 nested: {1527 yummie: true
167 unmodified lines
modified:__tests__/patch.js+108 added
11 unmodified lines
12) {13 function runPatchTestHelper() {14 let recordedPatches15 let recordedInversePatches1617 const res = produce(base, producer, (p, i) => {18 recordedPatches = p19 recordedInversePatches = i20 })
170 unmodified lines
191 true192 )193})194195describe("delete 4", () => {196 runPatchTest(197 new Set(["x", 1]),198 d => {199 d.delete("x")200 },201 [{op: "remove", path: [0], value: "x"}],202 [{op: "add", path: [0], value: "x"}],203 true204 )205})206207describe("delete 5", () => {208 runPatchTest(209 {x: new Set(["y", 1])},210 d => {211 d.x.delete("y")212 },213 [{op: "remove", path: ["x", 0], value: "y"}],214 [{op: "add", path: ["x", 0], value: "y"}],215 true216 )217})218219describe("renaming properties", () => {220 describe("nested object (no changes)", () => {221 runPatchTest(222 {a: {b: 1}},
309 unmodified lines
532 ]533 )534})535536describe("sets - add - 1", () => {537 runPatchTest(538 new Set([1]),539 d => {540 d.add(2)541 },542 [{op: "add", path: [1], value: 2}],543 [{op: "remove", path: [1], value: 2}],544 true545 )546})547548describe("sets - add, delete, add - 1", () => {549 runPatchTest(550 new Set([1]),551 d => {552 d.add(2)553 d.delete(2)554 d.add(2)555 },556 [{op: "add", path: [1], value: 2}],557 [{op: "remove", path: [1], value: 2}],558 true559 )560})561562describe("sets - add, delete, add - 2", () => {563 runPatchTest(564 new Set([2, 1]),565 d => {566 d.add(2)567 d.delete(2)568 d.add(2)569 },570 [],571 [],572 true573 )574})575576describe("sets - mutate - 1", () => {577 const findById = (set, id) => {578 for (const item of set) {579 if (item.id === id) return item580 }581 }582 runPatchTest(583 new Set([{id: 1, val: "We"}, {id: 2, val: "will"}]),584 d => {585 const obj1 = findById(d, 1)586 const obj2 = findById(d, 2)587 obj1.val = "rock"588 obj2.val = "you"589 },590 [591 {op: "remove", path: [0], value: {id: 1, val: "We"}},592 {op: "remove", path: [1], value: {id: 2, val: "will"}},593 {op: "add", path: [0], value: {id: 1, val: "rock"}},594 {op: "add", path: [1], value: {id: 2, val: "you"}}595 ],596 [597 {op: "remove", path: [1], value: {id: 2, val: "you"}},598 {op: "remove", path: [0], value: {id: 1, val: "rock"}},599 {op: "add", path: [1], value: {id: 2, val: "will"}},600 {op: "add", path: [0], value: {id: 1, val: "We"}}601 ],602 true603 )604})605606describe("simple replacement", () => {607 runPatchTest({x: 3}, _d => 4, [{op: "replace", path: [], value: 4}])608})609
53 unmodified lines
663 true664 )665})666667describe("same value replacement - 6", () => {668 runPatchTest(669 new Set(["x", 3]),670 d => {671 d.delete("x")672 d.add("x")673 },674 [],675 [],676 true677 )678})679680describe("simple delete", () => {681 runPatchTest(682 {x: 2},683 d => {
10 unmodified lines
modified:__tests__/readme.js+2 added-10 removed
modified:src/common.js+29 added-14 removed
19 unmodified lines
20 if (Array.isArray(value)) return true21 const proto = Object.getPrototypeOf(value)22 if (!proto || proto === Object.prototype) return true23 if (isMap(value)) return true24 if (isSet(value)) return true25 return !!value[DRAFTABLE] || !!value.constructor[DRAFTABLE]26}2728export function original(value) {
2 unmodified lines
31 }32 // otherwise return undefined33}3434function assignMap(target, overrides) {35 overrides.forEach(function(override) {35// We use Maps as `drafts` for Sets, not Objects36// See proxy.js37export function assignSet(target, ...mapOverrides) {38 mapOverrides.forEach(override => {39 for (const value of override.values()) {40 // When we add new drafts we have to remove their originals if present41 const originalValue = original(value)42 if (originalValue) {43 target.delete(originalValue)44 }45 target.add(value)46 }47 })48 return target49}5051export function assignMap(target, ...objOverrides) {52 objOverrides.forEach(override => {53 for (let key in override) {54 if (has(override, key)) {55 target.set(key, override[key])56 }57 }58 })59 return target60}6144function assignObjectLegacy(target, overrides) {45 overrides.forEach(function(override) {62function assignObjectLegacy(target, ...objOverrides) {63 objOverrides.forEach(function(override) {64 for (let key in override) {65 if (has(override, key)) {66 target[key] = override[key]67 }68 }69 })70 return target71}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}72export const assign = Object.assign || assignObjectLegacy7374export const ownKeys =75 typeof Reflect !== "undefined" && Reflect.ownKeys76 ? Reflect.ownKeys
6 unmodified lines
8384export function shallowCopy(base, invokeGetters = false) {85 if (Array.isArray(base)) return base.slice()86 if (isMap(base)) return new Map(base)87 if (isSet(base)) return new Set(base)88 const clone = Object.create(Object.getPrototypeOf(base))89 ownKeys(base).forEach(key => {90 if (key === DRAFT_STATE) {91 return // Never copy over draft state.
19 unmodified lines
111 return clone112}113114export function each(value, cb) {104 if (Array.isArray(value) || isMap(value)) {115 if (Array.isArray(value) || isMap(value) || isSet(value)) {116 value.forEach((entry, index) => cb(index, entry, value))117 return118 }119 ownKeys(value).forEach(key => cb(key, value[key], value))
19 unmodified lines
139140export function isMap(target) {141 return target instanceof Map142}143144export function isSet(target) {145 return target instanceof Set146}
modified:src/immer.js+15 added-2 removed
10 unmodified lines
11 isEnumerable,12 isMap,13 shallowCopy,14 DRAFT_STATE,15 NOTHING15 NOTHING,16 isSet17} from "./common"18import {ImmerScope} from "./scope"1920function verifyMinified() {}
166 unmodified lines
187 if (!state.finalized) {188 state.finalized = true189 this.finalizeTree(state.draft, path, scope)190191 // TODO: It won't fire for Sets because they don't use `assigned`. Is it an issue?192 if (this.onDelete) {193 // The `assigned` object is unreliable with ES5 drafts.194 if (this.useProxies) {195 const {assigned} = state196 for (const prop in assigned) {197 if (!assigned[prop]) this.onDelete(state, prop)198 }199 } else {200 // TODO: Figure it out for Maps and Sets if we need to support ES5201 const {base, copy} = state202 each(base, prop => {203 if (!has(copy, prop)) this.onDelete(state, prop)204 })
44 unmodified lines
249 const isDraftProp = !!state && parent === root250251 if (isDraft(value)) {252 const path =250 isDraftProp && needPatches && !state.assigned[prop]253 isDraftProp &&254 needPatches &&255 !isSet(parent) &&256 !state.assigned[prop]257 ? rootPath.concat(prop)258 : null259260 // Drafts owned by `scope` are finalized here.
6 unmodified lines
267268 setProperty(parent, prop, value)269270 // Unchanged drafts are never passed to the `onAssign` hook.271 // TODO: Add tests and support for Maps and Sets272 if (isDraftProp && value === state.base[prop]) return273 }274 // Unchanged draft properties are ignored.275 else if (isDraftProp && is(value, state.base[prop])) {
23 unmodified lines
299 if (isMap(parent)) {300 parent.set(prop, value)301 return302 }303 if (isSet(parent)) {304 // Here prop is a proxied value305 parent.delete(prop)306 parent.add(value)307 return308 }309 Object.defineProperty(parent, prop, {value})310}
modified:src/patches.js+61 added-8 removed
1import {each, isMap} from "./common"1import {each, isMap, isSet} from "./common"23export function generatePatches(state, basePath, patches, inversePatches) {4 const generatePatchesFn = Array.isArray(state.base)5 ? generateArrayPatches
1 unmodified line
7 ? generatePatchesFromAssigned(8 (map, key) => map.get(key),9 (map, key) => map.has(key)10 )11 : isSet(state.base)12 ? generateSetPatches13 : generatePatchesFromAssigned(14 (obj, key) => obj[key],15 (obj, key) => key in obj16 )
94 unmodified lines
111 })112 }113}114115function generateSetPatches(state, basePath, patches, inversePatches) {116 let {base, copy} = state117118 let i = 0119 for (const value of base) {120 if (!copy.has(value)) {121 const path = basePath.concat([i])122 patches.push({123 op: "remove",124 path,125 value126 })127 inversePatches.unshift({128 op: "add",129 path,130 value131 })132 }133 i++134 }135 i = 0136 for (const value of copy) {137 if (!base.has(value)) {138 const path = basePath.concat([i])139 patches.push({140 op: "add",141 path,142 value143 })144 inversePatches.unshift({145 op: "remove",146 path,147 value148 })149 }150 i++151 }152}153154export function applyPatches(draft, patches) {155 for (let i = 0; i < patches.length; i++) {156 const patch = patches[i]157 const {path} = patch
1 unmodified line
159 draft = patch.value160 } else {161 let base = draft162 for (let i = 0; i < path.length - 1; i++) {122 if (isMap(base.base)) {163 if (isMap(base)) {164 base = base.get(path[i])165 } else {166 base = base[path[i]]167 }
1 unmodified line
169 throw new Error("Cannot apply patch, path doesn't resolve: " + path.join("/")) // prettier-ignore170 }171 const key = path[path.length - 1]172132 const replace = (key, value) =>133 isMap(base.base) ? base.set(key, value) : (base[key] = value)173 const replace = (key, value) => {174 if (isMap(base)) {175 base.set(key, value)176 return177 }178 if (isSet(base)) {179 throw new Error('Sets cannot have "replace" patches.')180 }181 base[key] = value182 }183 const add = (key, value) =>184 Array.isArray(base)185 ? base.splice(key, 0, value)137 : isMap(base.base)186 : isMap(base)187 ? base.set(key, value)188 : isSet(base)189 ? base.add(value)190 : (base[key] = value)140 const remove = key =>191 const remove = (key, value) =>192 Array.isArray(base)193 ? base.splice(key, 1)143 : isMap(base.base)194 : isMap(base)195 ? base.delete(key)196 : isSet(base)197 ? base.delete(value)198 : delete base[key]199200 switch (patch.op) {201 case "replace":
2 unmodified lines
204 case "add":205 add(key, patch.value)206 break207 case "remove":155 remove(key)208 remove(key, patch.value)209 break210 default:211 throw new Error("Unsupported patch operation: " + patch.op)212 }
4 unmodified lines
modified:src/proxy.js+117 added-9 removed
5 unmodified lines
6 is,7 isDraftable,8 isDraft,9 isMap,10 isSet,11 shallowCopy,11 DRAFT_STATE12 DRAFT_STATE,13 assignMap,14 assignSet,15 original16} from "./common"17import {ImmerScope} from "./scope"1819// Do nothing before being finalized.
35 unmodified lines
55 proxyTarget = [state]56 traps = arrayTraps57 } else if (isMap(base)) {58 traps = mapTraps59 } else if (isSet(base)) {60 traps = setTraps61 // We use values of a Set as keys and objects do not support other objects as keys62 state.drafts = new Map()63 }6465 const {revoke, proxy} = Proxy.revocable(proxyTarget, traps)66
115 unmodified lines
182 */183184const mapTraps = {185 get(state, prop, receiver) {178 const getter = mapGetters[prop]179 return getter180 ? getter(state, prop, receiver)186 return mapGetters.hasOwnProperty(prop)187 ? mapGetters[prop](state, prop, receiver)188 : Reflect.get(state, prop, receiver)189 }190}191const mapGetters = {
3 unmodified lines
195 state = source(state)196 return state.has.bind(state)197 },198 set: state => (key, value) => {199 const stateSource = source(state)200 if (!stateSource.has(key) || stateSource.get(key) !== value) {192 markChanged(state)193 state.assigned[key] = true194 state.copy.set(key, value)201 markChanged(state)202 state.assigned[key] = true203 state.copy.set(key, value)204 }205 return state.draft206 },207 delete: state => key => {208 markChanged(state)
63 unmodified lines
272 }273}274275/**276 * Set drafts277 */278279const setTraps = {280 get(state, prop, receiver) {281 return setGetters.hasOwnProperty(prop)282 ? setGetters[prop](state, prop, receiver)283 : Reflect.get(state, prop, receiver)284 },285 ownKeys(state) {286 return Reflect.ownKeys(source(state))287 }288}289const setGetters = {290 [DRAFT_STATE]: state => state,291 size: state => source(state).size,292 has(state, prop) {293 state = source(state)294 return state.has.bind(state)295 },296 add: state => value => {297 if (!source(state).has(value)) {298 markChanged(state)299 state.copy.add(value)300 }301 return state.draft302 },303 delete: state => value => {304 markChanged(state)305 return state.copy.delete(value)306 },307 clear: state => () => {308 markChanged(state)309 return state.copy.clear()310 },311 forEach: state => (cb, thisArg) => {312 const iterator = iterateSetValues(state)()313 let result = iterator.next()314 while (!result.done) {315 cb.call(thisArg, result.value, result.value, state.draft)316 result = iterator.next()317 }318 },319 keys: iterateSetValues,320 values: iterateSetValues,321 entries: iterateSetValues,322 [Symbol.iterator]: iterateSetValues323}324325function iterateSetValues(state, prop) {326 return () => {327 const iterator = source(state)[Symbol.iterator]()328329 return makeIterable(() => {330 const result = iterator.next()331 if (!result.done) {332 const valueWrapped = wrapSetValue(state, result.value)333 result.value = valueWrapped334 if (prop === "entries") {335 result.value = [valueWrapped, valueWrapped]336 }337 }338 return result339 })340 }341}342343function wrapSetValue(state, value) {344 const key = original(value) || value345 let draft = state.drafts.get(key)346 if (!draft) {347 if (state.finalized || !isDraftable(value)) {348 return value349 }350 draft = createProxy(value, state)351 state.drafts.set(key, draft)352 if (state.modified) {353 state.copy.add(draft)354 }355 }356 return draft357}358359/**360 * Helpers361 */362363// returns the object we should be reading the current value from, which is base, until some change has been made
11 unmodified lines
375 return desc && desc.value376}377378function markChanged(state) {379 let resetDrafts = true380 let assignFn = assign381 if (isMap(state.base)) {382 assignFn = assignMap383 } else if (isSet(state.base)) {384 assignFn = assignSet385 // We need to keep track of how non-proxied objects are related to proxied ones.386 // For other data structures that support keys we can use those keys to access the item, notwithstanding it being a proxy or not.387 // Sets, however, do not have keys.388 // We use original objects as keys and keep proxified values as values.389 resetDrafts = false390 }391 if (!state.modified) {392 state.modified = true287 state.copy = assign(shallowCopy(state.base), state.drafts)288 state.drafts = null393 state.copy = assignFn(shallowCopy(state.base), state.drafts)394 if (resetDrafts) {395 state.drafts = null396 }397 if (state.parent) markChanged(state.parent)398 }399}400
7 unmodified lines