Some initial cleanup
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Michel Weststrate · committed by Michel Weststrate · parent 65a377f · Browse files · 6 files·+141 added−237 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
6 files+141 added−237 removed
- other:+141 added−237 removed
Provenance
- Commit
c53a75f- Tree
3443e1d- Author
Michel Weststrate <mweststrate@fb.com>- Committer
Michel Weststrate <mweststrate@fb.com>- Parent
65a377f
6 files changed+141 added−237 removed
modified:src/common.ts+33 added-75 removed
1-import {Objectish, ObjectishNoSet, ImmerState} from "./types"1+import {Objectish, ObjectishNoSet} from "./types"2 3 /** Use a class type for `nothing` so its type is unique */4 export class Nothing {5 // This lets us do `Exclude<T, Nothing>`98 unmodified lines104 obj105 ) as any)106 : Object.getOwnPropertyNames107 108-// TODO: duplicate of clone? TODO: should be used by prepareCopy of map / set109-export function shallowCopy<T extends Objectish>(110- base: T,111- invokeGetters?: boolean112-): T113-export function shallowCopy(base, invokeGetters = false) {114- if (Array.isArray(base)) return base.slice()115- if (isMap(base)) return new Map(base)116- if (isSet(base)) return new Set(base)117- const clone = Object.create(Object.getPrototypeOf(base))118- ownKeys(base).forEach(key => {119- if (key === DRAFT_STATE) {120- return // Never copy over draft state.121- }122- const desc = Object.getOwnPropertyDescriptor(base, key)!123- let {value} = desc124- if (desc.get) {125- if (!invokeGetters) {126- throw new Error("Immer drafts cannot have computed properties")127- }128- value = desc.get.call(base)129- }130- if (desc.enumerable) {131- clone[key] = value132- } else {133- Object.defineProperty(clone, key, {134- value,135- writable: true,136- configurable: true137- })138- }139- })140- return clone141-}142-108 export function each<T extends Objectish>(109 obj: T,110 iter: (key: PropertyKey, value: any, source: T) => void111 )46 unmodified lines158 export function isSet(target): target is Set<any> {159 return hasSet && target instanceof Set160 }161 197-198-export function makeIterable2(baseIterator: Iterator<any>): IterableIterator<any> {199- // TODO: correct?200- // TODO: don't use symbol201- baseIterator[Symbol.iterator] = () => baseIterator202- return baseIterator as any203-}204-205-export function makeIterable(next: () => {done: boolean; value: any}) {206- let self207- return (self = {208- [Symbol.iterator]: () => self,209- next210- })211-}212-162 export function latest(state: any): any {163 return state.copy || state.base164 }165 217-// export function iterateCollection(collection: Map<any, any> | Set<any>, transformer: (key, value) => any) {218-// // TODO: create own iterator symbols for fallback219-// const iterator = collection.entries()220-// return makeIterable(() => {221-// const result = iterator.next()222-// if (!result.done) {223-// const value = wrapSetValue(state, result.value)224-// result.value = isEntries ? [value, value] : value225-// }226-// return result227-// } as any)228-// }229-230-// TODO: duplicate of shallow clone231-export function clone<T extends Objectish>(obj: T): T232-export function clone(obj) {233- if (!isDraftable(obj)) return obj234- if (Array.isArray(obj)) return obj.map(clone)235- if (isMap(obj)) return new Map(obj)236- if (isSet(obj)) return new Set(obj)237- const cloned = Object.create(Object.getPrototypeOf(obj))238- for (const key in obj) cloned[key] = clone(obj[key])239- return cloned166+export function shallowCopy<T extends Objectish>(167+ base: T,168+ invokeGetters?: boolean169+): T170+export function shallowCopy(base, invokeGetters = false) {171+ if (Array.isArray(base)) return base.slice()172+ if (isMap(base)) return new Map(base)173+ if (isSet(base)) return new Set(base)174+ const clone = Object.create(Object.getPrototypeOf(base))175+ ownKeys(base).forEach(key => {176+ if (key === DRAFT_STATE) {177+ return // Never copy over draft state.178+ }179+ const desc = Object.getOwnPropertyDescriptor(base, key)!180+ let {value} = desc181+ if (desc.get) {182+ if (!invokeGetters) {183+ throw new Error("Immer drafts cannot have computed properties")184+ }185+ value = desc.get.call(base)186+ }187+ if (desc.enumerable) {188+ clone[key] = value189+ } else {190+ Object.defineProperty(clone, key, {191+ value,192+ writable: true,193+ configurable: true194+ })195+ }196+ })197+ return clone198 }199 200 export function freeze<T extends Objectish>(201 obj: T,15 unmodified linesmodified:src/es5.ts-1 removed
9 unmodified lines10 isSet,11 hasSymbol,12 shallowCopy,13 DRAFT_STATE,14- makeIterable,14 latest15 } from "./common"16 import {proxyMap, hasMapChanges} from "./map"17 import {proxySet, hasSetChanges} from "./set"337 unmodified linesmodified:src/map.ts+38 added-87 removed
1-import {2- each,3- has,4- is,5- isDraft,6- isDraftable,7- isEnumerable,8- isMap,9- isSet,10- hasSymbol,11- shallowCopy,12- DRAFT_STATE,13- makeIterable,14- latest15-} from "./common"1+import {isDraftable, DRAFT_STATE, latest} from "./common"2 3 // TODO: kill:18-import {19- assertUnrevoked,20- ES5Draft,21-} from "./es5"22-import { ImmerScope } from "./scope";23-import { Immer } from "./immer";4+import {assertUnrevoked, ES5Draft} from "./es5"5+import {ImmerScope} from "./scope"6+import {Immer} from "./immer"7 8 // TODO: create own states9 // TODO: clean up the maps and such from ES5 / Proxy states10 11 export interface MapState {29- parent: any; // TODO: type30- scope: ImmerScope;31- modified: boolean;32- finalizing: boolean;33- finalized: boolean;34- copy: Map<any, any> | undefined;35- assigned: Map<any, boolean> | undefined;36- base: Map<any, any>;37- revoke(): void;38- draft: ES5Draft;12+ parent: any // TODO: type13+ scope: ImmerScope14+ modified: boolean15+ finalizing: boolean16+ finalized: boolean17+ copy: Map<any, any> | undefined18+ assigned: Map<any, boolean> | undefined19+ base: Map<any, any>20+ revoke(): void21+ draft: ES5Draft22 }23 24 function prepareCopy(state: MapState) {25 if (!state.copy) {26 state.assigned = new Map()44- state.copy = new Map(state.base);27+ state.copy = new Map(state.base)28 }29 }30 31 // Make sure DraftMap declarion doesn't die if Map is not avialable...49-const MapBase: MapConstructor = typeof Map !== "undefined" ? Map : function FakeMap() {} as any32+const MapBase: MapConstructor =33+ typeof Map !== "undefined" ? Map : (function FakeMap() {} as any)34 35 // TODO: fix types for drafts36 export class DraftMap<K, V> extends MapBase implements Map<K, V> {37 [DRAFT_STATE]: MapState11 unmodified lines49 draft: this as any, // TODO: fix typing50 revoke() {51 // TODO: make sure this marks the Map as revoked, and assert everywhere52 }69- };53+ }54 }55 56 get size(): number {57 return latest(this[DRAFT_STATE]).size3 unmodified lines61 return latest(this[DRAFT_STATE]).has(key)62 }63 64 set(key: K, value: V): this {81- const state = this[DRAFT_STATE];65+ const state = this[DRAFT_STATE]66 if (latest(state).get(key) !== value) {67 prepareCopy(state)68 state.scope.immer.markChanged(state) // TODO: this needs to bubble up recursively correctly69 state.assigned!.set(key, true)70 state.copy!.set(key, value)87- state.assigned!.set(key, true);71+ state.assigned!.set(key, true)72 }73 return this74 }75 76 delete(key: K): boolean {77 if (!this.has(key)) {94- return false;78+ return false79 }80 97- const state = this[DRAFT_STATE];81+ const state = this[DRAFT_STATE]82 prepareCopy(state)83 state.scope.immer.markChanged(state)84 state.assigned!.set(key, false)85 state.copy!.delete(key)86 return true87 }88 89 clear() {106- const state = this[DRAFT_STATE];90+ const state = this[DRAFT_STATE]91 prepareCopy(state)92 state.scope.immer.markChanged(state)93 state.assigned = new Map()94 for (const key of latest(state).keys()) {3 unmodified lines98 }99 100 // @ts-ignore TODO:101 forEach(cb) {118- const state = this[DRAFT_STATE];102+ const state = this[DRAFT_STATE]103 latest(state).forEach((_value, key, _map) => {104 cb(this.get(key), key, this)105 })106 }107 124- get(key: K): V /* TODO: Draft<V> */ {125- const state = this[DRAFT_STATE];108+ get(key: K): V /* TODO: Draft<V> */ {109+ const state = this[DRAFT_STATE]110 const value = latest(state).get(key)111 if (state.finalizing || state.finalized || !isDraftable(value)) {112 return value113 }7 unmodified lines121 return draft122 }123 124 keys() {141- return latest(this[DRAFT_STATE]).keys();125+ return latest(this[DRAFT_STATE]).keys()126 }127 128 values() {129 const iterator = this.keys()130 return {131 [Symbol.iterator]: () => this.values(), // TODO: don't use symbol directly132 next: () => {133 const r = iterator.next()150- if (r.done) return r;151- const value = this.get(r.value);134+ if (r.done) return r135+ const value = this.get(r.value)136 return {153- done: false, value137+ done: false,138+ value139 }140 }141 } as any142 }3 unmodified lines146 return {147 [Symbol.iterator]: () => this.entries(), // TODO: don't use symbol directly148 next: () => {149 const r = iterator.next()165- if (r.done) return r;166- const value = this.get(r.value);150+ if (r.done) return r151+ const value = this.get(r.value)152 return {168- done: false, value: [r.value, value]153+ done: false,154+ value: [r.value, value]155 }156 }157 } as any158 }159 174- [Symbol.iterator]() { // TODO: don't use symbol directly160+ [Symbol.iterator]() {161+ // TODO: don't use symbol directly162 return this.entries()163 }164 }165 179-180-/** Map.prototype.values _-or-_ Map.prototype.entries */181-export function iterateMapValues(state, prop, receiver) {182- const isEntries = prop !== "values"183- return () => {184- const iterator = latest(state)[Symbol.iterator]()185- return makeIterable(() => {186- const result = iterator.next()187- if (!result.done) {188- const [key] = result.value189- const value = receiver.get(key)190- result.value = isEntries ? [key, value] : value191- }192- return result193- })194- }195-}196-197-198-166 export function proxyMap(target, parent) {167 if (target instanceof DraftMap) {201- return target; // TODO: or copy?168+ return target // TODO: or copy?169 }170 return new DraftMap(target, parent)204- // Object.defineProperties(target, mapTraps)205-171 }172 208-// TODO: kill?209-function proxyMethod(trap, key) {210- return {211- get() {212- return function(this: ES5Draft, ...args) {213- const state = this[DRAFT_STATE]214- assertUnrevoked(state)215- return trap(state, key, state.draft)(...args)216- }217- }218- }219-}220-221-// TODO: used?173 export function hasMapChanges(state) {174 const {base, draft} = state175 176 if (base.size !== draft.size) return true11 unmodified linesmodified:src/patches.ts+32 added-17 removed
1-import {get, each, isMap, isSet, has, clone} from "./common"1+import {get, each, isMap, isSet, has} from "./common"2 import {Patch, ImmerState} from "./types"3 4 export function generatePatches(5 state: ImmerState,79 unmodified lines85 patches: Patch[],86 inversePatches: Patch[]87 ) {88 const {base, copy} = state89+ if (state.assigned)89- if (state.assigned) each(state.assigned, (key, assignedValue) => {90- const origValue = get(base, key)91- const value = get(copy, key)92- const op = !assignedValue ? "remove" : has(base, key) ? "replace" : "add"93- if (origValue === value && op === "replace") return94- const path = basePath.concat(key as any)95- patches.push(op === "remove" ? {op, path} : {op, path, value})96- inversePatches.push(97- op === "add"98- ? {op: "remove", path}99- : op === "remove"100- ? {op: "add", path, value: origValue}101- : {op: "replace", path, value: origValue}102- )103- })90+ each(state.assigned, (key, assignedValue) => {91+ const origValue = get(base, key)92+ const value = get(copy, key)93+ const op = !assignedValue ? "remove" : has(base, key) ? "replace" : "add"94+ if (origValue === value && op === "replace") return95+ const path = basePath.concat(key as any)96+ patches.push(op === "remove" ? {op, path} : {op, path, value})97+ inversePatches.push(98+ op === "add"99+ ? {op: "remove", path}100+ : op === "remove"101+ ? {op: "add", path, value: origValue}102+ : {op: "replace", path, value: origValue}103+ )104+ })105 }106 107 function generateSetPatches(108 state: ImmerState,52 unmodified lines161 if (!base || typeof base !== "object")162 throw new Error("Cannot apply patch, path doesn't resolve: " + path.join("/")) // prettier-ignore163 }164 164- const value = clone(patch.value) // used to clone patch to ensure original patch is not modified, see #411165+ const value = deepClone(patch.value) // used to clone patch to ensure original patch is not modified, see #411166 167 const key = path[path.length - 1]168 switch (op) {169 case "replace":36 unmodified lines206 })207 208 return draft209 }210+211+// TODO: optimize: this is quite a performance hit, can we detect intelligently when it is needed?212+// E.g. auto-draft when new objects from outside are assigned and modified?213+// (See failing test when deepClone just returns obj)214+function deepClone(obj) {215+ if (!obj || typeof obj !== "object") return obj216+ if (Array.isArray(obj)) return obj.map(deepClone)217+ if (isMap(obj))218+ return new Map(Array.from(obj.entries()).map(([k, v]) => [k, deepClone(v)]))219+ if (isSet(obj)) return new Set(Array.from(obj.values()).map(deepClone))220+ const cloned = Object.create(Object.getPrototypeOf(obj))221+ for (const key in obj) cloned[key] = deepClone(obj[key])222+ return cloned223+}modified:src/proxy.ts-1 removed
8 unmodified lines9 isMap,10 isSet,11 hasSymbol,12 shallowCopy,13- makeIterable,13 DRAFT_STATE,14 assignMap,15 assignSet,16 original,281 unmodified linesmodified:src/set.ts+38 added-56 removed
123456789101112131415161712320212223244525678910313233343536111213141516173839404118192021222324254647484950515226272829303132333435365737383940414211 unmodified lines545556577758596061624 unmodified lines67686970909192717273747576779678798081823 unmodified lines868788891089091110929394959611597989910010110210310410511910610710810911029 unmodified lines14014114214315714414516014614714814915016516616716815115215315411 unmodified linesimport { each, has, is, isDraft, isDraftable, isEnumerable, isMap, isSet, hasSymbol, shallowCopy, DRAFT_STATE, makeIterable, latest, original, makeIterable2} from "./common"import {isDraftable, DRAFT_STATE, latest} from "./common"
// TODO: kill:import { assertUnrevoked, ES5Draft,} from "./es5"import { ImmerScope } from "./scope";import {assertUnrevoked, ES5Draft} from "./es5"import {ImmerScope} from "./scope"import { Immer } from "./immer";
// TODO: create own states// TODO: clean up the maps and such from ES5 / Proxy states
export interface SetState { parent: any; // TODO: type scope: ImmerScope; modified: boolean; finalizing: boolean; finalized: boolean; copy: Set<any> | undefined; parent: any // TODO: type scope: ImmerScope modified: boolean finalizing: boolean finalized: boolean copy: Set<any> | undefined // assigned: Map<any, boolean> | undefined; base: Set<any>; drafts: Map<any, any>; // maps the original value to the draft value in the new set revoke(): void; draft: ES5Draft; base: Set<any> drafts: Map<any, any> // maps the original value to the draft value in the new set revoke(): void draft: ES5Draft}
function prepareCopy(state: SetState) { if (!state.copy) { // create drafts for all entries to preserve insertion order state.copy = new Set() state.base.forEach(value => { const draft = state.scope.immer.createProxy(value, state); state.copy!.add(draft) state.drafts.set(value, draft) }) // create drafts for all entries to preserve insertion order state.copy = new Set() state.base.forEach(value => { const draft = state.scope.immer.createProxy(value, state) state.copy!.add(draft) state.drafts.set(value, draft) }) }}
// Make sure DraftSet declarion doesn't die if Map is not avialable...const SetBase: SetConstructor = typeof Set !== "undefined" ? Set : function FakeSet() {} as anyconst SetBase: SetConstructor = typeof Set !== "undefined" ? Set : (function FakeSet() {} as any)
// TODO: fix types for draftsexport class DraftSet<K, V> extends SetBase implements Set<V> { [DRAFT_STATE]: SetState11 unmodified lines drafts: new Map(), revoke() { // TODO: make sure this marks the Map as revoked, and assert everywhere } }; } }
get size(): number { return latest(this[DRAFT_STATE]).size4 unmodified lines // bit of trickery here, to be able to recognize both the value, and the draft of its value if (!state.copy) { return state.base.has(value) } if (state.copy.has(value)) return true; if (state.drafts.has(value) && state.copy.has(state.drafts.get(value))) return true; return false; if (state.copy.has(value)) return true if (state.drafts.has(value) && state.copy.has(state.drafts.get(value))) return true return false }
add(value: V): this { const state = this[DRAFT_STATE]; const state = this[DRAFT_STATE] if (state.copy) { state.copy.add(value) } else if (!state.base.has(value)) { prepareCopy(state)3 unmodified lines return this }
delete(value: V): boolean { const state = this[DRAFT_STATE]; const state = this[DRAFT_STATE] if (!this.has(value)) { return false; return false }
prepareCopy(state) state.scope.immer.markChanged(state) return state.copy!.delete(value) || (state.drafts.has(value) ? state.copy!.delete(state.drafts.get(value)) : false) return ( state.copy!.delete(value) || (state.drafts.has(value) ? state.copy!.delete(state.drafts.get(value)) : false) ) }
clear() { const state = this[DRAFT_STATE]; const state = this[DRAFT_STATE] prepareCopy(state) state.scope.immer.markChanged(state) return state.copy!.clear() }29 unmodified lines } }}
export function proxySet(target, parent) { if (target instanceof DraftSet) { return target; // TODO: or copy? return target // TODO: or copy? } return new DraftSet(target, parent)}
// const iterateSetValues = makeIterateSetValues()
export function hasSetChanges(state) { const {base, draft} = state
if (base.size !== draft.size) return true11 unmodified lines