Skip to content
Myr

TS type improvements

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 aeba1ff · Browse files · 11 files+224 added−213 removed
This commit

State

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

Diff stats

11 files+224 added−213 removed

  • other:+224 added−213 removed

11 files+224 added−213 removed

modified:src/common.ts+57 added-9 removed
57 unmodified lines
58 isSet(value)59 )60}6162export function isPlainObject(value): value is AnyObject | AnyArray {62export function isPlainObject(value: any): boolean {63 if (!value || typeof value !== "object") return false64 if (Array.isArray(value)) return true65 const proto = Object.getPrototypeOf(value)66 return !proto || proto === Object.prototype
6 unmodified lines
73 }74 // otherwise return undefined75}7677export const ownKeys: (target) => PropertyKey[] =77export const ownKeys: (target: AnyObject) => PropertyKey[] =78 typeof Reflect !== "undefined" && Reflect.ownKeys79 ? Reflect.ownKeys80 : typeof Object.getOwnPropertySymbols !== "undefined"81 ? obj =>
4 unmodified lines
8687export function each<T extends Objectish>(88 obj: T,89 iter: (key: string | number, value: any, source: T) => void90)91export function each(obj, iter) {90): void91export function each(obj: any, iter: any) {92 if (Array.isArray(obj) || isMap(obj) || isSet(obj)) {93 obj.forEach((entry, index) => iter(index, entry, obj))93 obj.forEach((entry: any, index: any) => iter(index, entry, obj))94 } else if (obj && typeof obj === "object") {95 ownKeys(obj).forEach(key => iter(key, obj[key], obj))96 } else {97 throw new Error("Nope")97 die()98 }99}100101export function isEnumerable(base: AnyObject, prop: PropertyKey): boolean {102 const desc = Object.getOwnPropertyDescriptor(base, prop)103 return desc && desc.enumerable ? true : false104}105106// TODO: use draft meta data if present?107// make refelction methods to determine types?108export function has(thing: ObjectishNoSet, prop: PropertyKey): boolean {109 return !thing110 ? false111 : isMap(thing)112 ? thing.has(prop)113 : Object.prototype.hasOwnProperty.call(thing, prop)114}115116// TODO: use draft meta data if present?114export function get(thing: ObjectishNoSet, prop: PropertyKey): any {115 return isMap(thing) ? thing.get(prop) : thing[prop]117export function get(thing: AnyMap | AnyObject, prop: PropertyKey): any {118 return isMap(thing) ? thing.get(prop) : thing[prop as any]119}120121// TODO: measure fast vs slow path, use type switch instead122export function set(parent: Drafted, prop: PropertyKey, value: any) {123 // fast path switch on meta data124 if (parent[DRAFT_STATE])125 switch (parent[DRAFT_STATE].type) {126 case "map":127 parent.set(prop, value)128 break129 case "set":130 parent.delete(prop)131 parent.add(value)132 break133 default:134 parent[prop] = value135 }136137 // slow path138 parent[prop] = value139 if (isMap(parent)) {140 parent.set(prop, value)141 } else if (isSet(parent)) {142 // In this case, the `prop` is actually a draft.143 parent.delete(prop)144 parent.add(value)145 } else {146 parent[prop] = value147 }148}149150export function is(x: any, y: any): boolean {151 // From: https://github.com/facebook/fbjs/blob/c69904a511b900266935168223063dd8772dfc40/packages/fbjs/src/core/shallowEqual.js152 if (x === y) {153 return x !== 0 || 1 / x === 1 / y
23 unmodified lines
177export function shallowCopy<T extends AnyObject | AnyArray>(178 base: T,179 invokeGetters?: boolean180): T149export function shallowCopy(base, invokeGetters = false) {181export function shallowCopy(base: any, invokeGetters = false) {182 if (Array.isArray(base)) return base.slice()183 const clone = Object.create(Object.getPrototypeOf(base))184 ownKeys(base).forEach(key => {185 if (key === DRAFT_STATE) {
36 unmodified lines
222223function dontMutateFrozenCollections() {224 throw new Error("This object has been frozen and should not be mutated")225}226227export function createHiddenProperty(228 target: AnyObject,229 prop: PropertyKey,230 value: any231) {232 Object.defineProperty(target, prop, {233 value: value,234 enumerable: false,235 writable: true236 })237}238239export function die(): never {240 throw new Error("Illegal state, please file a bug")241}
modified:src/es5.ts+40 added-57 removed
8 unmodified lines
9 isMap,10 isSet,11 shallowCopy,12 DRAFT_STATE,13 latest13 latest,14 createHiddenProperty15} from "./common"1617import {ImmerScope} from "./scope"17import {ImmerState, Drafted, AnyObject, AnyMap} from "./types"18import {ImmerState, Drafted, AnyObject, AnyMap, Objectish} from "./types"1919// TODO: merge with ImmerState?20interface ES5BaseState {21 scope: ImmerScope22 modified: boolean23 finalizing: boolean24 finalized: boolean25 assigned: {[key: string]: any}26 parent?: ImmerState27 drafts: AnyMap | null // TODO: don't use map?28 revoke()27 revoke(): void28 revoked: boolean29}3031export interface ES5ObjectState extends ES5BaseState {
35 unmodified lines
6768export function createES5Proxy<T>(69 base: T,70 parent?: ImmerState72): Drafted<any, ES5ObjectState | ES5ArrayState> {71): Drafted<T, ES5ObjectState | ES5ArrayState> {72 const isArray = Array.isArray(base)73 const draft = clonePotentialDraft(base)7475 each(draft, prop => {
9 unmodified lines
85 assigned: {},86 parent,87 base,88 draft,90 drafts: null,89 copy: null,90 revoke,91 revoked: false // es5 only92 }
5 unmodified lines
98function revoke(this: ES5BaseState) {99 this.revoked = true100}101104// TODO: type these methods102// Access a property without creating an Immer draft.106function peek(draft, prop) {103function peek(draft: Drafted, prop: PropertyKey) {104 const state = draft[DRAFT_STATE]105 if (state && !state.finalizing) {106 state.finalizing = true107 const value = draft[prop]
2 unmodified lines
110 }111 return draft[prop]112}113117function get(state, prop) {114function get(state: ES5State, prop: string | number) {115 assertUnrevoked(state)116 const value = peek(latest(state), prop)117 if (state.finalizing) return value118 // Create a draft if the value is unmodified.119 if (value === peek(state.base, prop) && isDraftable(value)) {120 prepareCopy(state)124 return (state.copy[prop] = state.scope.immer.createProxy(value, state))121 return (state.copy![prop] = state.scope.immer.createProxy(value, state))122 }123 return value124}125129function set(state: ES5State, prop, value) {126function set(state: ES5State, prop: string | number, value: any) {127 assertUnrevoked(state)128 state.assigned[prop] = true129 if (!state.modified) {130 if (is(value, peek(latest(state), prop))) return
2 unmodified lines
133 }134 state.copy![prop] = value135}136140export function markChangedES5(state) {137export function markChangedES5(state: ImmerState) {138 if (!state.modified) {139 state.modified = true140 if (state.parent) markChangedES5(state.parent)141 }142}143147function prepareCopy(state) {144function prepareCopy(state: ES5State) {145 if (!state.copy) state.copy = clonePotentialDraft(state.base)146}147151function clonePotentialDraft(base) {152 const state = base && base[DRAFT_STATE]148function clonePotentialDraft(base: Objectish) {149 const state = base && (base as any)[DRAFT_STATE]150 if (state) {151 state.finalizing = true152 const draft = shallowCopy(state.draft, true)153 state.finalizing = false
3 unmodified lines
157}158159// property descriptors are recycled to make sure we don't create a get and set closure per property,160// but share them all instead164const descriptors = {}161const descriptors: {[prop: string]: PropertyDescriptor} = {}162166function proxyProperty(draft, prop, enumerable) {163function proxyProperty(164 draft: Drafted<any, ES5State>,165 prop: string | number,166 enumerable: boolean167) {168 let desc = descriptors[prop]169 if (desc) {170 desc.enumerable = enumerable171 } else {172 descriptors[prop] = desc = {173 configurable: true,174 enumerable,174 get() {175 get(this: any) {176 return get(this[DRAFT_STATE], prop)177 },177 set(value) {178 set(this: any, value) {179 set(this[DRAFT_STATE], prop, value)180 }181 }182 }183 Object.defineProperty(draft, prop, desc)184}185185export function assertUnrevoked(state) {186export function assertUnrevoked(state: ES5State) {187 if (state.revoked === true)188 throw new Error(189 "Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? " +190 JSON.stringify(latest(state))191 )192}193194// This looks expensive, but only proxies are visited, and only objects without known changes are scanned.194function markChangesSweep(drafts) {195function markChangesSweep(drafts: Drafted<any, ImmerState>[]) {196 // The natural order of drafts in the `scope` array is based on when they197 // were accessed. By processing drafts in reverse natural order, we have a198 // better chance of processing leaf nodes first. When a leaf node is known to199 // have changed, we can avoid any traversal of its ancestor nodes.200 for (let i = drafts.length - 1; i >= 0; i--) {201 const state = drafts[i][DRAFT_STATE]202 if (!state.modified) {202 if (Array.isArray(state.base)) {203 if (hasArrayChanges(state)) markChangedES5(state)204 } else if (isMap(state.base)) {205 // TODO: use switch206 continue207 } else if (isSet(state.base)) {208 continue209 } else if (hasObjectChanges(state)) {210 markChangedES5(state)203 switch (state.type) {204 case "es5_array":205 if (hasArrayChanges(state)) markChangedES5(state)206 break207 case "es5_object":208 if (hasObjectChanges(state)) markChangedES5(state)209 break210 }211 }212 }213}214216// TODO: refactor this to work per object-type217// TODO: Set / Map shouldn't be ES specific218function markChangesRecursively(object) {215function markChangesRecursively(object: any) {216 if (!object || typeof object !== "object") return217 const state = object[DRAFT_STATE]218 if (!state) return222 const {base, draft, assigned} = state223 if (isSet(object) || isMap(object)) {224 // TODO: create switch here225 return226 } else if (!Array.isArray(object)) {219 const {base, draft, assigned, type} = state220 if (type === "es5_object") {221 // Look for added keys.228 // TODO: use each?229 Object.keys(draft).forEach(key => {222 // TODO: looks quite duplicate to hasObjectChanges223 each(draft, key => {224 if ((key as any) === DRAFT_STATE) return225 // The `undefined` check is a fast path for pre-existing keys.226 if (base[key] === undefined && !has(base, key)) {232 // TODO: this code seems invalid for Maps!227 assigned[key] = true228 markChangedES5(state)229 } else if (!assigned[key]) {236 // TODO: === false ?230 // Only untouched properties trigger recursion.231 markChangesRecursively(draft[key])232 }233 })234 // Look for removed keys.242 // TODO: is this code needed?243 // TODO: use each?244 Object.keys(base).forEach(key => {235 each(base, key => {236 // The `undefined` check is a fast path for pre-existing keys.237 if (draft[key] === undefined && !has(draft, key)) {238 assigned[key] = false239 markChangedES5(state)240 }241 })251 } else if (hasArrayChanges(state)) {242 } else if (type === "es5_array" && hasArrayChanges(state)) {243 markChangedES5(state)244 assigned.length = true245 if (draft.length < base.length) {246 for (let i = draft.length; i < base.length; i++) assigned[i] = false
6 unmodified lines
253 }254 }255}256266function hasObjectChanges(state) {257function hasObjectChanges(state: ES5ObjectState) {258 const {base, draft} = state259260 // Search for added keys and changed keys. Start at the back, because261 // non-numeric keys are ordered by time of definition on the object.
20 unmodified lines
282 // Compare key count to determine if keys were deleted.283 return keys.length !== Object.keys(base).length284}285295function hasArrayChanges(state) {286function hasArrayChanges(state: ES5ArrayState) {287 const {draft} = state288 if (draft.length !== state.base.length) return true289 // See #116290 // If we first shorten the length, our array interceptors will be removed.
7 unmodified lines
298 if (descriptor && !descriptor.get) return true299 // For all other cases, we don't have to compare, as they would have been picked up by the index setters300 return false301}311312function createHiddenProperty(target, prop, value) {313 Object.defineProperty(target, prop, {314 value: value,315 enumerable: false,316 writable: true317 })318}
modified:src/finalize.ts+18 added-44 removed
10 unmodified lines
11 isEnumerable,12 DRAFT_STATE,13 NOTHING,14 freeze,15 shallowCopy15 shallowCopy,16 set17} from "./common"18import {isDraft, isDraftable} from "./index"19import {SetState} from "./set"19import {generatePatches} from "./patches"20import {generatePatches, PatchPath} from "./patches"2121type PatchPath = Array<string | number> | null2222export function processResult(immer: Immer, result: any, scope: ImmerScope) {23 const baseDraft = scope.drafts![0]24 const isReplaced = result !== undefined && result !== baseDraft25 immer.willFinalize(scope, result, isReplaced)
3 unmodified lines
29 throw new Error("An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.") // prettier-ignore30 }31 if (isDraftable(result)) {32 // Finalize the result in case it contains (or is) a subset of the draft.34 result = finalize(immer, result, null, scope)33 result = finalize(immer, result, scope)34 maybeFreeze(immer, result)35 }36 if (scope.patches) {37 scope.patches.push({
8 unmodified lines
46 })47 }48 } else {49 // Finalize the base draft.51 result = finalize(immer, baseDraft, [], scope)50 result = finalize(immer, baseDraft, scope, [])51 }52 scope.revoke()53 if (scope.patches) {54 scope.patchListener!(scope.patches, scope.inversePatches!)
3 unmodified lines
5859function finalize(60 immer: Immer,61 draft: Drafted,63 path: PatchPath,64 scope: ImmerScope62 scope: ImmerScope,63 path?: PatchPath64) {65 const state = draft[DRAFT_STATE]66 if (!state) {67 if (Object.isFrozen(draft)) return draft69 return finalizeTree(immer, draft, null, scope)68 return finalizeTree(immer, draft, scope)69 }70 // Never finalize drafts owned by another scope.71 if (state.scope !== scope) {72 return draft
3 unmodified lines
76 return state.base77 }78 if (!state.finalized) {79 state.finalized = true81 finalizeTree(immer, state.draft, path, scope)80 finalizeTree(immer, state.draft, scope, path)8182 // We cannot really delete anything inside of a Set. We can only replace the whole Set.83 if (immer.onDelete && !isSet(state.base)) {84 // The `assigned` object is unreliable with ES5 drafts.
2 unmodified lines
87 each(assigned, (prop, exists) => {88 if (!exists) immer.onDelete?.(state, prop as any)89 })90 } else {92 // TODO: Figure it out for Maps and Sets if we need to support ES591 const {base, copy} = state92 each(base, prop => {93 if (!has(copy, prop)) immer.onDelete?.(state, prop as any)94 })
18 unmodified lines
113114function finalizeTree(115 immer: Immer,116 root: Drafted,119 rootPath: PatchPath,120 scope: ImmerScope117 scope: ImmerScope,118 rootPath?: PatchPath119) {120 const state = root[DRAFT_STATE]121 if (state) {124 // TODO: kill isMap / isSet here125 if (!immer.useProxies && !isMap(root) && !isSet(root)) {122 if (state.type === "es5_object" || state.type === "es5_array") {123 // Create the final copy, with added keys and without deleted keys.127 state.copy = shallowCopy(state.draft, true) // TODO: optimization, can we get rid of this and just use state.copy?124 state.copy = shallowCopy(state.draft, true)125 }129126 root = state.copy127 }132128 const needPatches = !!rootPath && !!scope.patches134129 each(root, (key, value) =>130 finalizeProperty(131 immer,132 root,
15 unmodified lines
148 root: ImmerState,149 state: ImmerState,150 prop: string | number,151 value: any,158 parent: ImmerState,152 parent: Drafted,153 needPatches: boolean,154 scope: ImmerScope,161 rootPath: PatchPath155 rootPath?: PatchPath156) {157 if (value === parent) {158 throw Error("Immer forbids circular references")159 }
8 unmodified lines
168 needPatches &&169 !isSetMember && // Set objects are atomic since they have no keys.170 !has((state as Exclude<ImmerState, SetState>).assigned!, prop) // Skip deep patches for assigned keys.171 ? rootPath!.concat(prop)178 : null172 : undefined173174 // Drafts owned by `scope` are finalized here.181 value = finalize(immer, value, path, scope)182 replace(parent, prop, value)175 value = finalize(immer, value, scope, path)176 set(parent, prop, value)177178 // Drafts from another scope must prevent auto-freezing.179 if (isDraft(value)) {180 scope.canAutoFreeze = false
28 unmodified lines
209 immer.onAssign(state, prop, value)210 }211}212219function replace(parent: Drafted, prop: PropertyKey, value: any) {220 // TODO: kill isMap clal here221 if (isMap(parent)) {222 parent.set(prop, value)223 } else if (isSet(parent)) {224 // In this case, the `prop` is actually a draft.225 parent.delete(prop)226 parent.add(value)227 } else if (Array.isArray(parent) || isEnumerable(parent, prop)) {228 // Preserve non-enumerable properties.229 parent[prop] = value230 } else {231 Object.defineProperty(parent, prop, {232 value,233 writable: true,234 configurable: true235 })236 }237}238213export function maybeFreeze(immer: Immer, value: any, deep = false) {214 if (immer.autoFreeze && !isDraft(value)) {215 freeze(value, deep)216 }
1 unmodified line
modified:src/immer.ts+35 added-41 removed
1import {createES5Proxy, willFinalizeES5, markChangedES5} from "./es5"2import {createProxy, markChanged} from "./proxy"34import {applyPatches, generatePatches} from "./patches"4import {applyPatches} from "./patches"5import {6 each,7 has,8 is,7 isDraft,8 isSet,11 get,9 isMap,10 isDraftable,14 isEnumerable,15 shallowCopy,11 DRAFT_STATE,12 NOTHING,18 freeze,13 isPlainObject,20 DRAFTABLE14 DRAFTABLE,15 die16} from "./common"17import {ImmerScope} from "./scope"18import {19 ImmerState,
5 unmodified lines
25 Patch,26 Drafted27} from "./types"28import {proxyMap} from "./map"34import {proxySet, SetState} from "./set"29import {proxySet} from "./set"30import {processResult, maybeFreeze} from "./finalize"3132function verifyMinified() {}33
8 unmodified lines
42 : verifyMinified.name === "verifyMinified",43 onAssign: null,44 onDelete: null,45 onCopy: null51}46} as const4748interface ProducersFns {49 produce: IProduce50 produceWithPatches: IProduceWithPatches
17 unmodified lines
68 onDelete?: (state: ImmerState, prop: string | number) => void69 onCopy?: (state: ImmerState) => void70 }) {71 each(configDefaults, (key, value) => {77 this[key] = value72 // @ts-ignore73 this[key] = config?.[key] ?? value74 })79 config &&80 each(config, (key, value) => {81 this[key] = value82 })75 this.setUseProxies(this.useProxies)76 this.produce = this.produce.bind(this)77 this.produceWithPatches = this.produceWithPatches.bind(this)78 }
16 unmodified lines
95 * @param {Function} producer - function that receives a proxy of the base state as first argument and which can be freely modified96 * @param {Function} patchListener - optional function that will be called with all the patches produced here97 * @returns {any} a new state, or the initial state if nothing was modified98 */107 produce(base, recipe?, patchListener?) {99 produce(base: any, recipe?: any, patchListener?: any) {100 // curried invocation101 if (typeof base === "function" && typeof recipe !== "function") {102 const defaultBase = recipe103 recipe = base104105 const self = this114 return function curriedProduce(this: any, base = defaultBase, ...args) {115 return self.produce(base, draft => recipe.call(this, draft, ...args)) // prettier-ignore106 return function curriedProduce(107 this: any,108 base = defaultBase,109 ...args: any[]110 ) {111 return self.produce(base, (draft: Drafted) => recipe.call(this, draft, ...args)) // prettier-ignore112 }113 }114115 // prettier-ignore
43 unmodified lines
159 return result160 }161 }162167 produceWithPatches(arg1, arg2?, arg3?): any {163 produceWithPatches(arg1: any, arg2?: any, arg3?: any): any {164 if (typeof arg1 === "function") {165 const self = this170 return (state, ...args) =>171 this.produceWithPatches(state, draft => arg1(draft, ...args))166 return (state: any, ...args: any[]) =>167 this.produceWithPatches(state, (draft: any) => arg1(draft, ...args))168 }169 // non-curried form170 if (arg3)171 throw new Error("A patch listener cannot be passed to produceWithPatches")176 let patches, inversePatches177 const nextState = this.produce(arg1, arg2, (p, ip) => {172 let patches: Patch[], inversePatches: Patch[]173 const nextState = this.produce(arg1, arg2, (p: Patch[], ip: Patch[]) => {174 patches = p175 inversePatches = ip176 })181 return [nextState, patches, inversePatches]177 return [nextState, patches!, inversePatches!]178 }179184 createDraft<T extends Objectish>(base: T): Draft<T> {180 createDraft<T extends Objectish>(base: T): Drafted<T> {181 if (!isDraftable(base)) {182 throw new Error("First argument to `createDraft` must be a plain object, an array, or an immerable object") // prettier-ignore183 }184 const scope = ImmerScope.enter(this)185 const proxy = this.createProxy(base, undefined)186 // @ts-ignore TODO: add to structures187 proxy[DRAFT_STATE].isManual = true188 scope.leave()189 return proxy190 }
35 unmodified lines
226227 applyPatches(base: Objectish, patches: Patch[]) {228 // If a patch replaces the entire state, take that replacement as base229 // before applying patches233 let i230 let i: number231 for (i = patches.length - 1; i >= 0; i--) {232 const patch = patches[i]233 if (patch.path.length === 0 && patch.op === "replace") {234 base = patch.value
5 unmodified lines
240 // N.B: never hits if some patch a replacement, patches are never drafts241 return applyPatches(base, patches)242 }243 // Otherwise, produce a copy of the base state.247 return this.produce(base, draft =>244 return this.produce(base, (draft: Drafted) =>245 applyPatches(draft, patches.slice(i + 1))246 )247 }248252 createProxy<T>(value: any, parent?: ImmerState) {253 if (!value || typeof value !== "object") return value254249 createProxy<T extends Objectish>(250 value: T,251 parent?: ImmerState252 ): Drafted<T, ImmerState> {253 let draft: Drafted256257 if (258 isPlainObject(value) ||259 Array.isArray(value) ||260 value[DRAFTABLE] ||261 value?.constructor?.[DRAFTABLE]262 ) {254 // TODO: use switch + type discovery>255 if (isMap(value)) draft = proxyMap(value, parent)256 else if (isSet(value)) draft = proxySet(value, parent)257 else {258 // createProxy should be guarded by isDraftable, so we know we can safely draft259 draft = this.useProxies260 ? createProxy(value, parent)261 : createES5Proxy(value, parent)266 } else if (isMap(value)) draft = proxyMap(value, parent)267 else if (isSet(value)) draft = proxySet(value, parent)268 else return value262 }263264 const scope = parent ? parent.scope : ImmerScope.current!265 scope.drafts.push(draft)266 return draft
2 unmodified lines
269 willFinalize(scope: ImmerScope, thing: any, isReplaced: boolean) {270 if (!this.useProxies) willFinalizeES5(scope, thing, isReplaced)271 }272279 markChanged(state: any) {273 markChanged(state: ImmerState) {274 if (this.useProxies) {275 markChanged(state)276 } else {277 markChangedES5(state)
3 unmodified lines
modified:src/map.ts+15 added-19 removed
modified:src/patches.ts+13 added-9 removed
1import {get, each, isMap, isSet, has} from "./common"1import {get, each, isMap, isSet, has, die} from "./common"2import {Patch, ImmerState} from "./types"3import {SetState} from "./set"45export type PatchPath = (string | number)[]67export function generatePatches(8 state: ImmerState,7 basePath: (string | number)[],9 basePath: PatchPath,10 patches: Patch[],11 inversePatches: Patch[]12) {13 // TODO: use a proper switch here
7 unmodified lines
21}2223function generateArrayPatches(24 state: any, // TODO: type properly with ImmerState23 basePath: (string | number)[],25 basePath: PatchPath,26 patches: Patch[],27 inversePatches: Patch[]28) {29 let {base, copy, assigned} = state
54 unmodified lines
8485// This is used for both Map objects and normal objects.86function generatePatchesFromAssigned(87 state: any, // TODO: type properly with ImmerState86 basePath: (number | string)[],88 basePath: PatchPath,89 patches: Patch[],90 inversePatches: Patch[]91) {92 const {base, copy} = state
15 unmodified lines
108}109110function generateSetPatches(111 state: SetState,110 basePath: (number | string)[],112 basePath: PatchPath,113 patches: Patch[],114 inversePatches: Patch[]115) {116 let {base, copy} = state
37 unmodified lines
154export function applyPatches<T>(draft: T, patches: Patch[]): T {155 patches.forEach(patch => {156 const {path, op} = patch157156 if (!path.length) throw new Error("Illegal state")158 if (!path.length) die()159160 let base = draft161 for (let i = 0; i < path.length - 1; i++) {162 base = get(base, path[i])
13 unmodified lines
176 } else {177 // if value is an object, then it's assigned by reference178 // in the following add or remove ops, the value field inside the patch will also be modifyed179 // so we use value from the cloned patch180 // @ts-ignore181 base[key] = value182 }183 break184 case "add":
6 unmodified lines
191 : isMap(base)192 ? base.set(key, value)193 : isSet(base)194 ? base.add(value)192 : (base[key] = value)195 : ((base as any)[key] = value)196 break197 case "remove":198 Array.isArray(base)199 ? base.splice(key as any, 1)200 : isMap(base)201 ? base.delete(key)202 : isSet(base)203 ? base.delete(patch.value)201 : delete base[key]204 : delete (base as any)[key]205 break206 default:207 throw new Error("Unsupported patch operation: " + op)208 }
4 unmodified lines
213214// TODO: optimize: this is quite a performance hit, can we detect intelligently when it is needed?215// E.g. auto-draft when new objects from outside are assigned and modified?216// (See failing test when deepClone just returns obj)214function deepClonePatchValue(obj) {217function deepClonePatchValue<T>(obj: T): T218function deepClonePatchValue(obj: any) {219 if (!obj || typeof obj !== "object") return obj220 if (Array.isArray(obj)) return obj.map(deepClonePatchValue)221 if (isMap(obj))222 return new Map(
7 unmodified lines
modified:src/proxy.ts+17 added-9 removed
9 unmodified lines
10 DRAFT_STATE,11 latest12} from "./common"13import {ImmerScope} from "./scope"14import {AnyObject, Drafted, ImmerState, AnyArray} from "./types"14import {AnyObject, Drafted, ImmerState, AnyArray, Objectish} from "./types"1516interface ProxyBaseState {17 scope: ImmerScope18 modified: boolean
21 unmodified lines
40 copy: AnyArray | null41 draft: Drafted<AnyArray, ProxyArrayState>42}4344type ProxyState = ProxyObjectState | ProxyArrayState4546/**47 * Returns a new draft of the `base` object.48 *49 * The second argument is the parent draft-state (used internally).50 */49export function createProxy<T extends object>(51export function createProxy<T extends Objectish>(52 base: T,53 parent?: ImmerState52): Drafted<T, ProxyObjectState | ProxyArrayState> {54): Drafted<T, ProxyState> {55 const isArray = Array.isArray(base)54 const state: ProxyObjectState | ProxyArrayState = {56 const state: ProxyState = {57 type: isArray ? "proxy_array" : ("proxy_object" as any),58 // Track which produce call this is associated with.59 scope: parent ? parent.scope : ImmerScope.current!,60 // True for both shallow and deep changes.
37 unmodified lines
9899/**100 * Object drafts101 */100const objectTraps: ProxyHandler<ProxyObjectState | ProxyArrayState> = {102const objectTraps: ProxyHandler<ProxyState> = {103 get(state, prop) {104 if (prop === DRAFT_STATE) return state105 let {drafts} = state106
37 unmodified lines
144 prepareCopy(state)145 markChanged(state)146 }147 state.assigned[prop] = true148 // @ts-ignore149 state.copy![prop] = value150 return true151 },152 deleteProperty(state, prop: string) {
5 unmodified lines
158 } else if (state.assigned[prop]) {159 // if an originally not assigned property was deleted160 delete state.assigned[prop]161 }162 // @ts-ignore163 if (state.copy) delete state.copy[prop]164 return true165 },166 // Note: We never coerce `desc.value` into an Immer draft, because we can't make
23 unmodified lines
190 */191192const arrayTraps: ProxyHandler<[ProxyArrayState]> = {}193each(objectTraps, (key, fn) => {194 // @ts-ignore195 arrayTraps[key] = function() {196 arguments[0] = arguments[0][0]197 return fn.apply(this, arguments)198 }
15 unmodified lines
214 * Map drafts215 */216217// Access a property without creating an Immer draft.213function peek(draft, prop) {218function peek(draft: Drafted, prop: PropertyKey): any {219 const state = draft[DRAFT_STATE]220 const desc = Reflect.getOwnPropertyDescriptor(221 state ? latest(state) : draft,222 prop223 )224 return desc && desc.value225}226222// TODO: unify with ES5 version, by getting rid of the drafts vs copy distinction?223export function markChanged(state) {227export function markChanged(state: ImmerState) {228 if (!state.modified) {229 state.modified = true230 // @ts-ignore TODO231 const {base, drafts, parent} = state232 // TODO: get rid of isMap and isSet233 if (!isMap(base) && !isSet(base)) {234 // TODO: drop creating copies here?235 const copy = (state.copy = shallowCopy(base))236 each(drafts, (key, value) => {237 // @ts-ignore238 copy[key] = value239 })240 // @ts-ignore TODO241 state.drafts = null242 }243244 if (parent) {
1 unmodified line
246 }247 }248}249242function prepareCopy(state) {250function prepareCopy(state: ProxyState) {251 if (!state.copy) {252 state.copy = shallowCopy(state.base)253 }254}
modified:src/scope.ts+2 added-2 removed
1import {DRAFT_STATE} from "./common"2import {Patch, PatchListener} from "./types"2import {Patch, PatchListener, Drafted} from "./types"3import {Immer} from "./immer"45/** Each scope represents a `produce` call. */6export class ImmerScope {
47 unmodified lines
54 return scope55 }56}5758function revoke(draft) {58function revoke(draft: Drafted) {59 draft[DRAFT_STATE].revoke()60}
modified:src/set.ts+25 added-21 removed
1import {DRAFT_STATE, latest} from "./common"1import {DRAFT_STATE, latest, isDraftable} from "./common"23// TODO: kill:4import {ImmerScope} from "./scope"5import {AnySet, Drafted} from "./types"5import {AnySet, Drafted, ImmerState} from "./types"67// TODO: create own states8// TODO: clean up the maps and such from ES5 / Proxy states910export interface SetState {11 type: "set"12 parent: any // TODO: type12 parent?: ImmerState13 scope: ImmerScope14 modified: boolean15 finalizing: boolean16 finalized: boolean17 copy: AnySet | undefined18 base: AnySet19 drafts: Map<any, any> // maps the original value to the draft value in the new set19 drafts: Map<any, Drafted> // maps the original value to the draft value in the new set20 revoke(): void21 draft: Drafted<AnySet, SetState>22}2324function prepareCopy(state: SetState) {25 if (!state.copy) {26 // create drafts for all entries to preserve insertion order27 state.copy = new Set()28 state.base.forEach(value => {29 const draft = state.scope.immer.createProxy(value, state)30 state.copy!.add(draft)31 state.drafts.set(value, draft)32 })33 }34}3524// Make sure DraftSet declarion doesn't die if Map is not avialable...25const SetBase: SetConstructor =26 typeof Set !== "undefined" ? Set : (function FakeSet() {} as any)2728// TODO: fix types for drafts29// TODO: assert unrevoked, use freeze for that30export class DraftSet<K, V> extends SetBase implements Set<V> {31 [DRAFT_STATE]: SetState44 constructor(target, parent) {32 constructor(target: AnySet, parent?: ImmerState) {33 super()34 this[DRAFT_STATE] = {35 type: "set",36 parent,49 scope: parent ? parent.scope : ImmerScope.current,37 scope: parent ? parent.scope : ImmerScope.current!,38 modified: false,39 finalized: false,40 finalizing: false,41 copy: undefined,
77 unmodified lines
119 [Symbol.iterator]() {120 return this.values()121 }122135 forEach(cb, thisArg) {123 forEach(cb: (value: V, key: V, self: this) => void, thisArg?: any) {124 const state = this[DRAFT_STATE]125 const iterator = this.values()126 let result = iterator.next()127 while (!result.done) {140 cb.call(thisArg, result.value, result.value, state.draft)128 cb.call(thisArg, result.value, result.value, this)129 result = iterator.next()130 }131 }132}133146export function proxySet(target, parent) {134export function proxySet(target: AnySet, parent?: ImmerState) {135 return new DraftSet(target, parent)136}137138function prepareCopy(state: SetState) {139 if (!state.copy) {140 // create drafts for all entries to preserve insertion order141 state.copy = new Set()142 state.base.forEach(value => {143 if (isDraftable(value)) {144 const draft = state.scope.immer.createProxy(value, state)145 state.drafts.set(value, draft)146 state.copy!.add(draft)147 } else {148 state.copy!.add(value)149 }150 })151 }152}
modified:src/types.ts+1 added-1 removed
3 unmodified lines
4import {ProxyObjectState, ProxyArrayState} from "./proxy"5import {ES5ObjectState, ES5ArrayState} from "./es5"67export type Objectish = AnyObject | AnyArray | AnyMap | AnySet88export type ObjectishNoSet = AnyObject | AnyArray | AnyMap910export type AnyObject = {[key: string]: any}11export type AnyArray = Array<any>
15 unmodified lines
27 | ES5ArrayState28 | MapState29 | SetState3031// The _internal_ type used for drafts (not to be confused with Draft, which is public facing)32export type Drafted<Base = any, T extends ImmerState = ImmerState> = {33 [DRAFT_STATE]: T34} & Base35
174 unmodified lines
modified:tsconfig.json+1 added-1 removed
5 unmodified lines
6 "target": "ES6",7 "strict": true,8 "declaration": true,9 "importHelpers": false,10 "noImplicitAny": false, // TODO: true,10 "noImplicitAny": true,11 "esModuleInterop": true12 }13}