Skip to content
Myr

added set and iteror stuff

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 735c402 · Browse files · 7 files+429 added−359 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+429 added−359 removed

  • other:+429 added−359 removed

7 files+429 added−359 removed

modified:src/common.ts+2 added
103 unmodified lines
104 obj105 ) as any)106 : Object.getOwnPropertyNames107108// TODO: duplicate of clone? TODO: should be used by prepareCopy of map / set109export function shallowCopy<T extends Objectish>(110 base: T,111 invokeGetters?: boolean112): T
144 unmodified lines
257export function latest(state: any): any {258 return state.copy || state.base259}260261// TODO: duplicate of shallow clone262export function clone<T extends Objectish>(obj: T): T263export function clone(obj) {264 if (!isDraftable(obj)) return obj265 if (Array.isArray(obj)) return obj.map(clone)
24 unmodified lines
modified:src/es5.ts+51 added-9 removed
14 unmodified lines
15 makeIterable,16 makeIterateSetValues,17 latest18} from "./common"19import {proxyMap, proxySet, hasMapChanges, hasSetChanges} from "./mapset"19import {proxyMap, hasMapChanges} from "./map"20import {proxySet, hasSetChanges} from "./set"2122import {ImmerScope} from "./scope"23import {ImmerState} from "./types"2425export interface ES5Draft {
43 unmodified lines
69 const draft = proxyMap(base, parent) as any // TODO: typefix70 scope.drafts.push(draft)71 return draft72 }73 if (isSet(base)) {74 const draft = proxySet(base, parent) as any // TODO: typefix75 scope.drafts.push(draft)76 return draft77 }7879 const isArray = Array.isArray(base)80 const draft = clonePotentialDraft(base)8175 if (isSet(base)) {76 proxySet(draft)77 } else {78 each(draft, prop => {79 proxyProperty(draft, prop, isArray || isEnumerable(base, prop))80 })82 each(draft, prop => {83 proxyProperty(draft, prop, isArray || isEnumerable(base, prop))84 })81 }8586 const state: ES5State<T> = {87 scope,88 modified: false,
129 unmodified lines
218 }219 }220}221222// TODO: refactor this to work per object-type223// TODO: Set / Map shouldn't be ES specific224function markChangesRecursively(object) {225 if (!object || typeof object !== "object") return226 const state = object[DRAFT_STATE]227 if (!state) return228 const {base, draft, assigned} = state224 if (!Array.isArray(object)) {229 if (isSet(object)) {230 if (hasSetChanges(state)) {231 markChanged(state)232 object.forEach(v => {233 markChangesRecursively(v)234 })235 }236 } else if (isMap(object)) {237 // if (hasMapChanges(object)) {238 object.forEach((value, key) => {239 if (assigned && base.get(key) === undefined && !has(base, key)) {240 // TODO: this code seems invalid for Maps!241 assigned.set(key, true)242 markChanged(state)243 } else if (!assigned || !assigned.get(key)) {244 // TODO: === false?245 // Only untouched properties trigger recursion.246 markChangesRecursively(draft.get(key))247 }248 })249 // Look for removed keys.250 // TODO: is this code needed?251 // TODO: use each?252 if (assigned)253 base.forEach((value, key) => {254 // The `undefined` check is a fast path for pre-existing keys.255 if (draft.get(key) === undefined && !has(draft, key)) {256 assigned.set(key, false)257 markChanged(state)258 }259 })260 // }261 } else if (!Array.isArray(object)) {262 // Look for added keys.263 // TODO: use each?264 Object.keys(draft).forEach(key => {265 // The `undefined` check is a fast path for pre-existing keys.266 if (base[key] === undefined && !has(base, key)) {267 // TODO: this code seems invalid for Maps!268 assigned[key] = true269 markChanged(state)270 } else if (!assigned[key]) {271 // TODO: === false ?272 // Only untouched properties trigger recursion.273 markChangesRecursively(draft[key])274 }275 })276 // Look for removed keys.277 // TODO: is this code needed?278 // TODO: use each?279 Object.keys(base).forEach(key => {280 // The `undefined` check is a fast path for pre-existing keys.281 if (draft[key] === undefined && !has(draft, key)) {282 assigned[key] = false
71 unmodified lines
modified:src/immer.ts+1 added-1 removed
341 unmodified lines
342 // if (state.modified && !state.copy) {343 // state.copy = shallowCopy(state.base, false)344 // }345 // else346 if (!this.useProxies && !isMap(root)) {346 if (!this.useProxies && !isMap(root) && !isSet(root)) {347 // Create the final copy, with added keys and without deleted keys.348 state.copy = shallowCopy(state.draft, true) // TODO: optimization, can we get rid of this and just use state.copy?349 }350 root = state.copy
76 unmodified lines
added:src/map.ts+200 added
1import {2 each,3 has,4 is,5 isDraft,6 isDraftable,7 isEnumerable,8 isMap,9 isSet,10 hasSymbol,11 shallowCopy,12 DRAFT_STATE,13 iterateMapValues,14 makeIterable,15 makeIterateSetValues,16 latest17} from "./common"1819// TODO: kill:20import {21 assertUnrevoked,22 ES5Draft,23} from "./es5"24import { ImmerScope } from "./scope";25import { Immer } from "./immer";2627// TODO: create own states28// TODO: clean up the maps and such from ES5 / Proxy states2930export interface MapState {31 parent: any; // TODO: type32 scope: ImmerScope;33 modified: boolean;34 finalizing: boolean;35 finalized: boolean;36 copy: Map<any, any> | undefined;37 assigned: Map<any, boolean> | undefined;38 base: Map<any, any>;39 revoke(): void;40 draft: ES5Draft;41}4243function prepareCopy(state: MapState) {44 if (!state.copy) {45 state.assigned = new Map()46 state.copy = new Map(state.base);47 }48}4950// Make sure DraftMap declarion doesn't die if Map is not avialable...51const MapBase: MapConstructor = typeof Map !== "undefined" ? Map : function FakeMap() {} as any5253// TODO: fix types for drafts54export class DraftMap<K, V> extends MapBase implements Map<K, V> {55 [DRAFT_STATE]: MapState56 constructor(target, parent) {57 super()58 this[DRAFT_STATE] = {59 parent,60 scope: parent ? parent.scope : ImmerScope.current,61 modified: false,62 finalized: false,63 finalizing: false,64 copy: undefined,65 assigned: undefined,66 base: target,67 draft: this as any, // TODO: fix typing68 revoke() {69 // TODO: make sure this marks the Map as revoked, and assert everywhere70 }71 };72 }7374 get size(): number {75 return latest(this[DRAFT_STATE]).size76 }7778 has(key: K): boolean {79 return latest(this[DRAFT_STATE]).has(key)80 }8182 set(key: K, value: V): this {83 const state = this[DRAFT_STATE];84 if (latest(state).get(key) !== value) {85 prepareCopy(state)86 state.scope.immer.markChanged(state) // TODO: this needs to bubble up recursively correctly87 state.assigned!.set(key, true)88 state.copy!.set(key, value)89 state.assigned!.set(key, true);90 }91 return this92 }9394 delete(key: K): boolean {95 if (!this.has(key)) {96 return false;97 }9899 const state = this[DRAFT_STATE];100 prepareCopy(state)101 state.scope.immer.markChanged(state)102 state.assigned!.set(key, false)103 state.copy!.delete(key)104 return true105 }106107 clear() {108 const state = this[DRAFT_STATE];109 prepareCopy(state)110 state.scope.immer.markChanged(state)111 state.assigned = new Map()112 for (const key of latest(state).keys()) {113 state.assigned.set(key, false)114 }115 return state.copy!.clear()116 }117118 // @ts-ignore TODO:119 forEach(cb) {120 const state = this[DRAFT_STATE];121 latest(state).forEach((_value, key, _map) => {122 cb(this.get(key), key, this)123 })124 }125126 get(key: K): V /* TODO: Draft<V> */ {127 const state = this[DRAFT_STATE];128 const value = latest(state).get(key)129 if (state.finalizing || state.finalized || !isDraftable(value)) {130 return value131 }132 if (value !== state.base.get(key)) {133 return value // either already drafted or reassigned134 }135 const draft = state.scope.immer.createProxy(value, state)136 prepareCopy(state)137 state.copy!.set(key, draft)138 return draft139 }140141 keys() {142 return latest(this[DRAFT_STATE]).keys();143 }144145 // TODO: make these normal functions146 // TODO: values and entries iterators147 // @ts-ignore TODO:148 values = iterateMapValues149 // @ts-ignore TODO:150 entries = iterateMapValues151}152153154if (hasSymbol) {155 Object.defineProperty(156 DraftMap.prototype,157 Symbol.iterator,158 // @ts-ignore TODO fix159 proxyMethod(iterateMapValues)160 )161}162163export function proxyMap(target, parent) {164 if (target instanceof DraftMap) {165 return target; // TODO: or copy?166 }167 return new DraftMap(target, parent)168 // Object.defineProperties(target, mapTraps)169170}171172// TODO: kill?173function proxyMethod(trap, key) {174 return {175 get() {176 return function(this: ES5Draft, ...args) {177 const state = this[DRAFT_STATE]178 assertUnrevoked(state)179 return trap(state, key, state.draft)(...args)180 }181 }182 }183}184185// TODO: used?186export function hasMapChanges(state) {187 const {base, draft} = state188189 if (base.size !== draft.size) return true190191 // IE11 supports only forEach iteration192 let hasChanges = false193 // TODO: optimize: break on first difference194 draft.forEach(function(value, key) {195 if (!hasChanges) {196 hasChanges = isDraftable(value) ? value.modified : value !== base.get(key)197 }198 })199 return hasChanges200}
deleted:src/mapset.ts-348 removed
1import {2 each,3 has,4 is,5 isDraft,6 isDraftable,7 isEnumerable,8 isMap,9 isSet,10 hasSymbol,11 shallowCopy,12 DRAFT_STATE,13 iterateMapValues,14 makeIterable,15 makeIterateSetValues,16 latest17} from "./common"1819// TODO: kill:20import {21 assertUnrevoked,22 ES5Draft,23} from "./es5"24import { ImmerScope } from "./scope";25import { Immer } from "./immer";2627// TODO: create own states28// TODO: clean up the maps and such from ES5 / Proxy states2930export interface MapState {31 parent: any; // TODO: type32 scope: ImmerScope;33 modified: boolean;34 finalizing: boolean;35 finalized: boolean;36 copy: Map<any, any> | undefined;37 assigned: Map<any, boolean> | undefined;38 base: Map<any, any>;39 revoke(): void;40 draft: ES5Draft;41}4243function prepareCopy(state: MapState) {44 if (!state.copy) {45 state.assigned = new Map()46 state.copy = new Map(state.base);47 }48}4950// Make sure DraftMap declarion doesn't die if Map is not avialable...51const MapBase: MapConstructor = typeof Map !== "undefined" ? Map : function FakeMap() {} as any5253// TODO: fix types for drafts54export class DraftMap<K, V> extends MapBase implements Map<K, V> {55 [DRAFT_STATE]: MapState56 constructor(target, parent) {57 super()58 this[DRAFT_STATE] = {59 parent,60 scope: parent ? parent.scope : ImmerScope.current,61 modified: false,62 finalized: false,63 finalizing: false,64 copy: undefined,65 assigned: undefined,66 base: target,67 draft: this as any, // TODO: fix typing68 revoke() {69 // TODO: make sure this marks the Map as revoked, and assert everywhere70 }71 };72 }7374 get size(): number {75 return latest(this[DRAFT_STATE]).size76 }7778 has(key: K): boolean {79 return latest(this[DRAFT_STATE]).has(key)80 }8182 set(key: K, value: V): this {83 const state = this[DRAFT_STATE];84 if (latest(state).get(key) !== value) {85 prepareCopy(state)86 state.scope.immer.markChanged(state) // TODO: this needs to bubble up recursively correctly87 state.assigned!.set(key, true)88 state.copy!.set(key, value)89 state.assigned!.set(key, true);90 }91 return this92 }9394 delete(key: K): boolean {95 if (!this.has(key)) {96 return false;97 }9899 const state = this[DRAFT_STATE];100 prepareCopy(state)101 state.scope.immer.markChanged(state)102 state.assigned!.set(key, false)103 state.copy!.delete(key)104 return true105 }106107 clear() {108 const state = this[DRAFT_STATE];109 prepareCopy(state)110 state.scope.immer.markChanged(state)111 state.assigned = new Map()112 for (const key of latest(state).keys()) {113 state.assigned.set(key, false)114 }115 return state.copy!.clear()116 }117118 // @ts-ignore TODO:119 forEach(cb) {120 const state = this[DRAFT_STATE];121 latest(state).forEach((_value, key, _map) => {122 cb(this.get(key), key, this)123 })124 }125126 get(key: K): V /* TODO: Draft<V> */ {127 const state = this[DRAFT_STATE];128 const value = latest(state).get(key)129 if (state.finalizing || state.finalized || !isDraftable(value)) {130 return value131 }132 if (value !== state.base.get(key)) {133 return value // either already drafted or reassigned134 }135 const draft = state.scope.immer.createProxy(value, state)136 prepareCopy(state)137 state.copy!.set(key, draft)138 return draft139 }140141 keys() {142 return latest(this[DRAFT_STATE]).keys();143 }144145 // TODO: values and entries iterators146 // @ts-ignore TODO:147 // values: iterateMapValues,148 // @ts-ignore TODO:149 // entries: iterateMapValues150}151152153export function proxyMap(target, parent) {154 if (target instanceof DraftMap) {155 return target; // TODO: or copy?156 }157 return new DraftMap(target, parent)158 // Object.defineProperties(target, mapTraps)159160 // if (hasSymbol) {161 // Object.defineProperty(162 // target,163 // Symbol.iterator,164 // // @ts-ignore TODO fix165 // proxyMethod(iterateMapValues)166 // )167 // }168}169170// TODO: eliminate these, and put in a Map superclass171// const mapTraps = finalizeTraps({172// size: state => latest(state).size,173// has: state => key => latest(state).has(key),174// set: state => (key, value) => {175// if (latest(state).get(key) !== value) {176// prepareCopy(state)177// markChanged(state)178// state.assigned.set(key, true)179// state.copy.set(key, value)180// }181// return state.draft182// },183// delete: state => key => {184// prepareCopy(state)185// markChanged(state)186// state.assigned.set(key, false)187// state.copy.delete(key)188// return false189// },190// clear: state => () => {191// if (!state.copy) {192// prepareCopy(state)193// }194// markChanged(state)195// state.assigned = new Map()196// for (const key of latest(state).keys()) {197// state.assigned.set(key, false)198// }199// return state.copy.clear()200// },201// // @ts-ignore TODO:202// forEach: (state, key, reciever) => cb => {203// latest(state).forEach((value, key, map) => {204// cb(reciever.get(key), key, map)205// })206// },207// get: state => key => {208// const value = latest(state).get(key)209210// if (state.finalizing || state.finalized || !isDraftable(value)) {211// return value212// }213214// if (value !== state.base.get(key)) {215// return value216// }217// const draft = state.scope.immer.createProxy(value, state)218// prepareCopy(state)219// state.copy.set(key, draft)220// return draft221// },222// keys: state => () => latest(state).keys(),223// // @ts-ignore TODO:224// values: iterateMapValues,225// // @ts-ignore TODO:226// entries: iterateMapValues227// })228229export function proxySet(target) {230 Object.defineProperties(target, setTraps)231232 if (hasSymbol) {233 Object.defineProperty(234 target,235 Symbol.iterator,236 // @ts-ignore TODO237 proxyMethod(iterateSetValues)238 )239 }240}241242const iterateSetValues = makeIterateSetValues()243244const setTraps = finalizeTraps({245 size: state => {246 return latest(state).size247 },248 add: state => value => {249 if (!latest(state).has(value)) {250 state.scope.immer.markChanged(state)251 if (!state.copy) {252 prepareCopy(state)253 }254 state.copy.add(value)255 }256 return state.draft257 },258 delete: state => value => {259 state.scope.immer.markChanged(state)260 if (!state.copy) {261 prepareCopy(state)262 }263 return state.copy.delete(value)264 },265 has: state => key => {266 return latest(state).has(key)267 },268 clear: state => () => {269 state.scope.immer.markChanged(state)270 if (!state.copy) {271 prepareCopy(state)272 }273 return state.copy.clear()274 },275 keys: iterateSetValues,276 entries: iterateSetValues,277 values: iterateSetValues,278 forEach: state => (cb, thisArg) => {279 const iterator = iterateSetValues(state)()280 let result = iterator.next()281 while (!result.done) {282 cb.call(thisArg, result.value, result.value, state.draft)283 result = iterator.next()284 }285 }286})287288function finalizeTraps(traps: {[prop: string]: (state: any) => Function }) {289 return Object.keys(traps).reduce(function(acc, key) {290 const builder = key === "size" ? proxyAttr : proxyMethod291 acc[key] = builder(traps[key], key)292 return acc293 }, {})294}295296function proxyAttr(fn) {297 return {298 get() {299 const state = this[DRAFT_STATE]300 assertUnrevoked(state)301 return fn(state)302 }303 }304}305306function proxyMethod(trap, key) {307 return {308 get() {309 return function(this: ES5Draft, ...args) {310 const state = this[DRAFT_STATE]311 assertUnrevoked(state)312 return trap(state, key, state.draft)(...args)313 }314 }315 }316}317318export function hasMapChanges(state) {319 const {base, draft} = state320321 if (base.size !== draft.size) return true322323 // IE11 supports only forEach iteration324 let hasChanges = false325 // TODO: optimize: break on first difference326 draft.forEach(function(value, key) {327 if (!hasChanges) {328 hasChanges = isDraftable(value) ? value.modified : value !== base.get(key)329 }330 })331 return hasChanges332}333334export function hasSetChanges(state) {335 const {base, draft} = state336337 if (base.size !== draft.size) return true338339 // IE11 supports only forEach iteration340 let hasChanges = false341 // TODO: optimize: break on first diff342 draft.forEach(function(value, key) {343 if (!hasChanges) {344 hasChanges = isDraftable(value) ? value.modified : !base.has(key)345 }346 })347 return hasChanges348}
modified:src/proxy.ts+1 added-1 removed
18 unmodified lines
19 makeIterateSetValues,20 latest21} from "./common"22import {ImmerScope} from "./scope"23import { proxyMap } from "./mapset"23import { proxyMap } from "./map"2425// Do nothing before being finalized.26export function willFinalize() {}27
405 unmodified lines
added:src/set.ts+174 added
1import {2 each,3 has,4 is,5 isDraft,6 isDraftable,7 isEnumerable,8 isMap,9 isSet,10 hasSymbol,11 shallowCopy,12 DRAFT_STATE,13 iterateMapValues,14 makeIterable,15 makeIterateSetValues,16 latest17} from "./common"1819// TODO: kill:20import {21 assertUnrevoked,22 ES5Draft,23} from "./es5"24import { ImmerScope } from "./scope";25import { Immer } from "./immer";2627// TODO: create own states28// TODO: clean up the maps and such from ES5 / Proxy states2930export interface SetState {31 parent: any; // TODO: type32 scope: ImmerScope;33 modified: boolean;34 finalizing: boolean;35 finalized: boolean;36 copy: Set<any> | undefined;37 // assigned: Map<any, boolean> | undefined;38 base: Set<any>;39 revoke(): void;40 draft: ES5Draft;41}4243function prepareCopy(state: SetState) {44 if (!state.copy) {45 state.copy = new Set(state.base);46 }47}4849// Make sure DraftSet declarion doesn't die if Map is not avialable...50const SetBase: SetConstructor = typeof Set !== "undefined" ? Set : function FakeSet() {} as any5152// TODO: fix types for drafts53export class DraftSet<K, V> extends SetBase implements Set<V> {54 [DRAFT_STATE]: SetState55 constructor(target, parent) {56 super()57 this[DRAFT_STATE] = {58 parent,59 scope: parent ? parent.scope : ImmerScope.current,60 modified: false,61 finalized: false,62 finalizing: false,63 copy: undefined,64 base: target,65 draft: this as any, // TODO: fix typing66 revoke() {67 // TODO: make sure this marks the Map as revoked, and assert everywhere68 }69 };70 }7172 get size(): number {73 return latest(this[DRAFT_STATE]).size74 }7576 add(value: V): this {77 const state = this[DRAFT_STATE];78 if (latest(state).has(value) !== value) {79 prepareCopy(state)80 state.scope.immer.markChanged(state) // TODO: this needs to bubble up recursively correctly81 state.copy!.add(value)82 }83 return this84 }8586 delete(value: V): boolean {87 if (!this.has(value)) {88 return false;89 }9091 const state = this[DRAFT_STATE];92 prepareCopy(state)93 state.scope.immer.markChanged(state)94 state.copy!.delete(value)95 return true96 }9798 clear() {99 const state = this[DRAFT_STATE];100 prepareCopy(state)101 state.scope.immer.markChanged(state)102 return state.copy!.clear()103 }104105 keys() {106 return latest(this[DRAFT_STATE]).keys();107 }108109 // TODO: values and entries iterators110 // @ts-ignore TODO:111 entries = iterateSetValues112 // values: iterateMapValues,113 // @ts-ignore TODO:114 values= iterateSetValues115 // entries: iterateMapValues116117 forEach(cb, thisArg) {118 const state = this[DRAFT_STATE]119 const iterator = iterateSetValues(state)()120 let result = iterator.next()121 while (!result.done) {122 cb.call(thisArg, result.value, result.value, state.draft)123 result = iterator.next()124 }125 }126}127128129export function proxySet(target, parent) {130 if (target instanceof DraftSet) {131 return target; // TODO: or copy?132 }133 return new DraftSet(target, parent)134}135136if (hasSymbol) {137 Object.defineProperty(138 DraftSet.prototype,139 Symbol.iterator,140 // @ts-ignore TODO fix141 proxyMethod(iterateMapValues)142 )143}144145const iterateSetValues = makeIterateSetValues()146147// TODO: kill?148function proxyMethod(trap, key) {149 return {150 get() {151 return function(this: ES5Draft, ...args) {152 const state = this[DRAFT_STATE]153 assertUnrevoked(state)154 return trap(state, key, state.draft)(...args)155 }156 }157 }158}159160export function hasSetChanges(state) {161 const {base, draft} = state162163 if (base.size !== draft.size) return true164165 // IE11 supports only forEach iteration166 let hasChanges = false167 // TODO: optimize: break on first diff168 draft.forEach(function(value, key) {169 if (!hasChanges) {170 hasChanges = isDraftable(value) ? value.modified : !base.has(key)171 }172 })173 return hasChanges174}