Further cleanup in progress
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 79a1d2c · Browse files · 7 files·+269 added−206 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+269 added−206 removed
- other:+269 added−206 removed
Provenance
- Commit
aeba1ff- Tree
507669f- Author
Michel Weststrate <mweststrate@fb.com>- Committer
Michel Weststrate <mweststrate@fb.com>- Parent
79a1d2c
7 files changed+269 added−206 removed
modified:src/common.ts+17 added-8 removed
1123456789101112131470 unmodified lines8586878880899091929316 unmodified lines1101111121131051141151161171091181191201211224 unmodified lines12712812913012213113213313413513612813713813914013214114214314413614514614714814944 unmodified linesimport {Objectish, ObjectishNoSet, Drafted, AnyObject, AnyArray} from "./types"import { Objectish, ObjectishNoSet, Drafted, AnyObject, AnyArray, AnyMap, AnySet, ImmerState} from "./types"
/** Use a class type for `nothing` so its type is unique */export class Nothing { // This lets us do `Exclude<T, Nothing>`70 unmodified lines : Object.getOwnPropertyNames
export function each<T extends Objectish>( obj: T, iter: (key: PropertyKey, value: any, source: T) => void iter: (key: string | number, value: any, source: T) => void)export function each(obj, iter) { if (Array.isArray(obj) || isMap(obj) || isSet(obj)) { obj.forEach((entry, index) => iter(index, entry, obj))16 unmodified lines ? thing.has(prop) : Object.prototype.hasOwnProperty.call(thing, prop)}
export function get(thing: ObjectishNoSet, prop: PropertyKey) {export function get(thing: ObjectishNoSet, prop: PropertyKey): any { return isMap(thing) ? thing.get(prop) : thing[prop]}
export function is(x, y): boolean {export function is(x: any, y: any): boolean { // From: https://github.com/facebook/fbjs/blob/c69904a511b900266935168223063dd8772dfc40/packages/fbjs/src/core/shallowEqual.js if (x === y) { return x !== 0 || 1 / x === 1 / y } else {4 unmodified linesexport const hasSymbol = typeof Symbol !== "undefined"
export const hasMap = typeof Map !== "undefined"
export function isMap(target): target is Map<any, any> {export function isMap(target: any): target is AnyMap { return hasMap && target instanceof Map}
export const hasSet = typeof Set !== "undefined"
export function isSet(target): target is Set<any> {export function isSet(target: any): target is AnySet { return hasSet && target instanceof Set}
export function latest(state: any): any {export function latest(state: ImmerState): any { return state.copy || state.base}
export function shallowCopy<T extends Objectish>(export function shallowCopy<T extends AnyObject | AnyArray>( base: T, invokeGetters?: boolean): Texport function shallowCopy(base, invokeGetters = false) {44 unmodified linesmodified:src/es5.ts-1 removed
142 unmodified lines143 if (state.parent) markChangedES5(state.parent)144 }145 }146 147-// TODO: kill export147 function prepareCopy(state) {148 if (!state.copy) state.copy = clonePotentialDraft(state.base)149 }150 168 unmodified linesadded:src/finalize.ts+243 added
1+import {Immer} from "./immer"2+import {ImmerState, Drafted} from "./types"3+import {ImmerScope} from "./scope"4+import {5+ isSet,6+ has,7+ is,8+ get,9+ each,10+ isMap,11+ isEnumerable,12+ DRAFT_STATE,13+ NOTHING,14+ freeze,15+ shallowCopy16+} from "./common"17+import {isDraft, isDraftable} from "./index"18+import {SetState} from "./set"19+import {generatePatches} from "./patches"20+21+type PatchPath = Array<string | number> | null22+23+export function processResult(immer: Immer, result: any, scope: ImmerScope) {24+ const baseDraft = scope.drafts![0]25+ const isReplaced = result !== undefined && result !== baseDraft26+ immer.willFinalize(scope, result, isReplaced)27+ if (isReplaced) {28+ if (baseDraft[DRAFT_STATE].modified) {29+ scope.revoke()30+ throw new Error("An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.") // prettier-ignore31+ }32+ if (isDraftable(result)) {33+ // Finalize the result in case it contains (or is) a subset of the draft.34+ result = finalize(immer, result, null, scope)35+ maybeFreeze(immer, result)36+ }37+ if (scope.patches) {38+ scope.patches.push({39+ op: "replace",40+ path: [],41+ value: result42+ })43+ scope.inversePatches!.push({44+ op: "replace",45+ path: [],46+ value: baseDraft[DRAFT_STATE].base47+ })48+ }49+ } else {50+ // Finalize the base draft.51+ result = finalize(immer, baseDraft, [], scope)52+ }53+ scope.revoke()54+ if (scope.patches) {55+ scope.patchListener!(scope.patches, scope.inversePatches!)56+ }57+ return result !== NOTHING ? result : undefined58+}59+60+function finalize(61+ immer: Immer,62+ draft: Drafted,63+ path: PatchPath,64+ scope: ImmerScope65+) {66+ const state = draft[DRAFT_STATE]67+ if (!state) {68+ if (Object.isFrozen(draft)) return draft69+ return finalizeTree(immer, draft, null, scope)70+ }71+ // Never finalize drafts owned by another scope.72+ if (state.scope !== scope) {73+ return draft74+ }75+ if (!state.modified) {76+ maybeFreeze(immer, state.base, true)77+ return state.base78+ }79+ if (!state.finalized) {80+ state.finalized = true81+ finalizeTree(immer, state.draft, path, scope)82+83+ // We cannot really delete anything inside of a Set. We can only replace the whole Set.84+ if (immer.onDelete && !isSet(state.base)) {85+ // The `assigned` object is unreliable with ES5 drafts.86+ if (immer.useProxies) {87+ const {assigned} = state88+ each(assigned, (prop, exists) => {89+ if (!exists) immer.onDelete?.(state, prop as any)90+ })91+ } else {92+ // TODO: Figure it out for Maps and Sets if we need to support ES593+ const {base, copy} = state94+ each(base, prop => {95+ if (!has(copy, prop)) immer.onDelete?.(state, prop as any)96+ })97+ }98+ }99+ if (immer.onCopy) {100+ immer.onCopy(state)101+ }102+103+ // At this point, all descendants of `state.copy` have been finalized,104+ // so we can be sure that `scope.canAutoFreeze` is accurate.105+ if (immer.autoFreeze && scope.canAutoFreeze) {106+ freeze(state.copy, false)107+ }108+109+ if (path && scope.patches) {110+ generatePatches(state, path, scope.patches, scope.inversePatches!)111+ }112+ }113+ return state.copy114+}115+116+function finalizeTree(117+ immer: Immer,118+ root: Drafted,119+ rootPath: PatchPath,120+ scope: ImmerScope121+) {122+ const state = root[DRAFT_STATE]123+ if (state) {124+ // TODO: kill isMap / isSet here125+ if (!immer.useProxies && !isMap(root) && !isSet(root)) {126+ // 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?128+ }129+130+ root = state.copy131+ }132+133+ const needPatches = !!rootPath && !!scope.patches134+135+ each(root, (key, value) =>136+ finalizeProperty(137+ immer,138+ root,139+ state,140+ key,141+ value,142+ root,143+ needPatches,144+ scope,145+ rootPath146+ )147+ )148+ return root149+}150+151+function finalizeProperty(152+ // TODO: can do with less args?153+ immer: Immer,154+ root: ImmerState,155+ state: ImmerState,156+ prop: string | number,157+ value: any,158+ parent: ImmerState,159+ needPatches: boolean,160+ scope: ImmerScope,161+ rootPath: PatchPath162+) {163+ if (value === parent) {164+ throw Error("Immer forbids circular references")165+ }166+167+ // In the `finalizeTree` method, only the `root` object may be a draft.168+ const isDraftProp = !!state && parent === root169+ const isSetMember = isSet(parent)170+171+ if (isDraft(value)) {172+ const path =173+ isDraftProp &&174+ needPatches &&175+ !isSetMember && // Set objects are atomic since they have no keys.176+ !has((state as Exclude<ImmerState, SetState>).assigned!, prop) // Skip deep patches for assigned keys.177+ ? rootPath!.concat(prop)178+ : null179+180+ // Drafts owned by `scope` are finalized here.181+ value = finalize(immer, value, path, scope)182+ replace(parent, prop, value)183+184+ // Drafts from another scope must prevent auto-freezing.185+ if (isDraft(value)) {186+ scope.canAutoFreeze = false187+ }188+189+ // Unchanged drafts are never passed to the `onAssign` hook.190+ // if (isDraftProp && !isSet && value === get(state.base, prop)) return191+ }192+ // Unchanged draft properties are ignored.193+ else if (isDraftProp && is(value, get(state.base, prop))) {194+ return195+ }196+ // Search new objects for unfinalized drafts. Frozen objects should never contain drafts.197+ else if (isDraftable(value) && !Object.isFrozen(value)) {198+ each(value, (key, v) =>199+ finalizeProperty(200+ immer,201+ root,202+ state,203+ key,204+ v,205+ value,206+ needPatches,207+ scope,208+ rootPath209+ )210+ )211+ maybeFreeze(immer, value)212+ }213+214+ if (isDraftProp && immer.onAssign && !isSetMember) {215+ immer.onAssign(state, prop, value)216+ }217+}218+219+function 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+}238+239+export function maybeFreeze(immer: Immer, value: any, deep = false) {240+ if (immer.autoFreeze && !isDraft(value)) {241+ freeze(value, deep)242+ }243+}modified:src/immer.ts+7 added-194 removed
29 unmodified lines30 Patch,31 Drafted32 } from "./types"33 import {proxyMap} from "./map"34-import {proxySet} from "./set"34+import {proxySet, SetState} from "./set"35+import {processResult, maybeFreeze} from "./finalize"36 37 function verifyMinified() {}38 39 const configDefaults = {104 unmodified lines144 if (typeof Promise !== "undefined" && result instanceof Promise) {145 return result.then(146 result => {147 scope.usePatches(patchListener)147- return this.processResult(result, scope)148+ return processResult(this, result, scope)149 },150 error => {151 scope.revoke()152 throw error153 }154 )155 }156 scope.usePatches(patchListener)156- return this.processResult(result, scope)157+ return processResult(this, result, scope)158 } else {159 result = recipe(base)160 if (result === NOTHING) return undefined161 if (result === undefined) result = base161- this.maybeFreeze(result, true)162+ maybeFreeze(this, result, true)163 return result164 }165 }166 21 unmodified lines188 const scope = ImmerScope.enter(this)189 const proxy = this.createProxy(base, undefined)190 proxy[DRAFT_STATE].isManual = true191 scope.leave()191- return proxy as any192+ return proxy193 }194 195 finishDraft<D extends Draft<any>>(196 draft: D,7 unmodified lines204 throw new Error("The given draft is already finalized") // prettier-ignore205 }206 const {scope} = state207 scope.usePatches(patchListener)207- return this.processResult(undefined, scope)208+ return processResult(this, undefined, scope)209 }210 211 /**212 * Pass true to automatically freeze all copies created by Immer.35 unmodified lines248 applyPatches(draft, patches.slice(i + 1))249 )250 }251 251- /** @internal */252- processResult(result: any, scope: ImmerScope) {253- const baseDraft = scope.drafts![0]254- const isReplaced = result !== undefined && result !== baseDraft255- this.willFinalize(scope, result, isReplaced)256- if (isReplaced) {257- if (baseDraft[DRAFT_STATE].modified) {258- scope.revoke()259- throw new Error("An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.") // prettier-ignore260- }261- if (isDraftable(result)) {262- // Finalize the result in case it contains (or is) a subset of the draft.263- result = this.finalize(result, null, scope)264- this.maybeFreeze(result)265- }266- if (scope.patches) {267- scope.patches.push({268- op: "replace",269- path: [],270- value: result271- })272- scope.inversePatches!.push({273- op: "replace",274- path: [],275- value: baseDraft[DRAFT_STATE].base276- })277- }278- } else {279- // Finalize the base draft.280- result = this.finalize(baseDraft, [], scope)281- }282- scope.revoke()283- if (scope.patches) {284- scope.patchListener!(scope.patches, scope.inversePatches!)285- }286- return result !== NOTHING ? result : undefined287- }288-252 createProxy<T>(value: any, parent?: ImmerState) {253 if (!value || typeof value !== "object") return value254 255 let draft: Drafted26 unmodified lines282 } else {283 markChangedES5(state)284 }285 }323-324- /**325- * @internal326- * Finalize a draft, returning either the unmodified base state or a modified327- * copy of the base state.328- */329- finalize(draft: any, path: string[] | null, scope: ImmerScope) {330- const state = draft[DRAFT_STATE]331- if (!state) {332- if (Object.isFrozen(draft)) return draft333- return this.finalizeTree(draft, null, scope)334- }335- // Never finalize drafts owned by another scope.336- if (state.scope !== scope) {337- return draft338- }339- if (!state.modified) {340- this.maybeFreeze(state.base, true)341- return state.base342- }343- if (!state.finalized) {344- state.finalized = true345- this.finalizeTree(state.draft, path, scope)346-347- // We cannot really delete anything inside of a Set. We can only replace the whole Set.348- if (this.onDelete && !isSet(state.base)) {349- // The `assigned` object is unreliable with ES5 drafts.350- if (this.useProxies) {351- const {assigned} = state352- each(assigned, (prop, exists) => {353- if (!exists) this.onDelete?.(state, prop as any)354- })355- } else {356- // TODO: Figure it out for Maps and Sets if we need to support ES5357- const {base, copy} = state358- each(base, prop => {359- if (!has(copy, prop)) this.onDelete?.(state, prop as any)360- })361- }362- }363- if (this.onCopy) {364- this.onCopy(state)365- }366-367- // At this point, all descendants of `state.copy` have been finalized,368- // so we can be sure that `scope.canAutoFreeze` is accurate.369- if (this.autoFreeze && scope.canAutoFreeze) {370- freeze(state.copy, false)371- }372-373- if (path && scope.patches) {374- generatePatches(state, path, scope.patches, scope.inversePatches!)375- }376- }377- return state.copy378- }379-380- /**381- * @internal382- * Finalize all drafts in the given state tree.383- */384- finalizeTree(root: any, rootPath: string[] | null, scope: ImmerScope) {385- const state = root[DRAFT_STATE]386- if (state) {387- // TODO: remove crap388- // if (state.modified && !state.copy) {389- // state.copy = shallowCopy(state.base, false)390- // }391- // else392- if (!this.useProxies && !isMap(root) && !isSet(root)) {393- // Create the final copy, with added keys and without deleted keys.394- state.copy = shallowCopy(state.draft, true) // TODO: optimization, can we get rid of this and just use state.copy?395- }396-397- root = state.copy398- }399-400- const needPatches = !!rootPath && !!scope.patches401- const finalizeProperty = (prop, value, parent) => {402- if (value === parent) {403- throw Error("Immer forbids circular references")404- }405-406- // In the `finalizeTree` method, only the `root` object may be a draft.407- const isDraftProp = !!state && parent === root408- const isSetMember = isSet(parent)409-410- if (isDraft(value)) {411- const path =412- isDraftProp &&413- needPatches &&414- !isSetMember && // Set objects are atomic since they have no keys.415- !has(state.assigned, prop) // Skip deep patches for assigned keys.416- ? rootPath!.concat(prop)417- : null418-419- // Drafts owned by `scope` are finalized here.420- value = this.finalize(value, path, scope)421- replace(parent, prop, value)422-423- // Drafts from another scope must prevent auto-freezing.424- if (isDraft(value)) {425- scope.canAutoFreeze = false426- }427-428- // Unchanged drafts are never passed to the `onAssign` hook.429- // if (isDraftProp && !isSet && value === get(state.base, prop)) return430- }431- // Unchanged draft properties are ignored.432- else if (isDraftProp && is(value, get(state.base, prop))) {433- return434- }435- // Search new objects for unfinalized drafts. Frozen objects should never contain drafts.436- else if (isDraftable(value) && !Object.isFrozen(value)) {437- each(value, finalizeProperty)438- this.maybeFreeze(value)439- }440-441- if (isDraftProp && this.onAssign && !isSetMember) {442- this.onAssign(state, prop, value)443- }444- }445-446- each(root, finalizeProperty)447- return root448- }449- maybeFreeze(value, deep = false) {450- if (this.autoFreeze && !isDraft(value)) {451- freeze(value, deep)452- }453- }286 }455-456-function replace(parent, prop, value) {457- if (isMap(parent)) {458- parent.set(prop, value)459- } else if (isSet(parent)) {460- // In this case, the `prop` is actually a draft.461- parent.delete(prop)462- parent.add(value)463- } else if (Array.isArray(parent) || isEnumerable(parent, prop)) {464- // Preserve non-enumerable properties.465- parent[prop] = value466- } else {467- Object.defineProperty(parent, prop, {468- value,469- writable: true,470- configurable: true471- })472- }473-}modified:src/map.ts+1 added-1 removed
30 unmodified lines31 const MapBase: MapConstructor =32 typeof Map !== "undefined" ? Map : (function FakeMap() {} as any)33 34 // TODO: fix types for drafts35-// TODO: assert unrevoked35+// TODO: assert unrevoked, use freeze for that36 export class DraftMap<K, V> extends MapBase implements Map<K, V> {37 [DRAFT_STATE]: MapState38 constructor(target, parent) {39 super()130 unmodified linesmodified:src/proxy.ts-1 removed
237 unmodified lines238 }239 }240 }241 242-// TODO: unify with ES5 version242 function prepareCopy(state) {243 if (!state.copy) {244 state.copy = shallowCopy(state.base)245 }1 unmodified linemodified:src/set.ts+1 added-1 removed
36 unmodified lines37 const SetBase: SetConstructor =38 typeof Set !== "undefined" ? Set : (function FakeSet() {} as any)39 40 // TODO: fix types for drafts41-// TODO: assert unrevoked41+// TODO: assert unrevoked, use freeze for that42 export class DraftSet<K, V> extends SetBase implements Set<V> {43 [DRAFT_STATE]: SetState44 constructor(target, parent) {45 super()103 unmodified lines