Skip to content
Myr

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

7 files+269 added−206 removed

modified:src/common.ts+17 added-8 removed
modified:src/es5.ts-1 removed
142 unmodified lines
143 if (state.parent) markChangedES5(state.parent)144 }145}146147// TODO: kill export147function prepareCopy(state) {148 if (!state.copy) state.copy = clonePotentialDraft(state.base)149}150
168 unmodified lines
added:src/finalize.ts+243 added
1import {Immer} from "./immer"2import {ImmerState, Drafted} from "./types"3import {ImmerScope} from "./scope"4import {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"17import {isDraft, isDraftable} from "./index"18import {SetState} from "./set"19import {generatePatches} from "./patches"2021type PatchPath = Array<string | number> | null2223export 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}5960function 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)8283 // 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 }102103 // 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 }108109 if (path && scope.patches) {110 generatePatches(state, path, scope.patches, scope.inversePatches!)111 }112 }113 return state.copy114}115116function 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 }129130 root = state.copy131 }132133 const needPatches = !!rootPath && !!scope.patches134135 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}150151function 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 }166167 // In the `finalizeTree` method, only the `root` object may be a draft.168 const isDraftProp = !!state && parent === root169 const isSetMember = isSet(parent)170171 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 : null179180 // Drafts owned by `scope` are finalized here.181 value = finalize(immer, value, path, scope)182 replace(parent, prop, value)183184 // Drafts from another scope must prevent auto-freezing.185 if (isDraft(value)) {186 scope.canAutoFreeze = false187 }188189 // 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 }213214 if (isDraftProp && immer.onAssign && !isSetMember) {215 immer.onAssign(state, prop, value)216 }217}218219function 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}238239export 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 lines
30 Patch,31 Drafted32} from "./types"33import {proxyMap} from "./map"34import {proxySet} from "./set"34import {proxySet, SetState} from "./set"35import {processResult, maybeFreeze} from "./finalize"3637function verifyMinified() {}3839const configDefaults = {
104 unmodified lines
144 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 lines
188 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 }194195 finishDraft<D extends Draft<any>>(196 draft: D,
7 unmodified lines
204 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 }210211 /**212 * Pass true to automatically freeze all copies created by Immer.
35 unmodified lines
248 applyPatches(draft, patches.slice(i + 1))249 )250 }251251 /** @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 }288252 createProxy<T>(value: any, parent?: ImmerState) {253 if (!value || typeof value !== "object") return value254255 let draft: Drafted
26 unmodified lines
282 } else {283 markChangedES5(state)284 }285 }323324 /**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)346347 // 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 }366367 // 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 }372373 if (path && scope.patches) {374 generatePatches(state, path, scope.patches, scope.inversePatches!)375 }376 }377 return state.copy378 }379380 /**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 }396397 root = state.copy398 }399400 const needPatches = !!rootPath && !!scope.patches401 const finalizeProperty = (prop, value, parent) => {402 if (value === parent) {403 throw Error("Immer forbids circular references")404 }405406 // In the `finalizeTree` method, only the `root` object may be a draft.407 const isDraftProp = !!state && parent === root408 const isSetMember = isSet(parent)409410 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 : null418419 // Drafts owned by `scope` are finalized here.420 value = this.finalize(value, path, scope)421 replace(parent, prop, value)422423 // Drafts from another scope must prevent auto-freezing.424 if (isDraft(value)) {425 scope.canAutoFreeze = false426 }427428 // 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 }440441 if (isDraftProp && this.onAssign && !isSetMember) {442 this.onAssign(state, prop, value)443 }444 }445446 each(root, finalizeProperty)447 return root448 }449 maybeFreeze(value, deep = false) {450 if (this.autoFreeze && !isDraft(value)) {451 freeze(value, deep)452 }453 }286}455456function 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 lines
31const MapBase: MapConstructor =32 typeof Map !== "undefined" ? Map : (function FakeMap() {} as any)3334// TODO: fix types for drafts35// TODO: assert unrevoked35// TODO: assert unrevoked, use freeze for that36export class DraftMap<K, V> extends MapBase implements Map<K, V> {37 [DRAFT_STATE]: MapState38 constructor(target, parent) {39 super()
130 unmodified lines
modified:src/proxy.ts-1 removed
237 unmodified lines
238 }239 }240}241242// TODO: unify with ES5 version242function prepareCopy(state) {243 if (!state.copy) {244 state.copy = shallowCopy(state.base)245 }
1 unmodified line
modified:src/set.ts+1 added-1 removed
36 unmodified lines
37const SetBase: SetConstructor =38 typeof Set !== "undefined" ? Set : (function FakeSet() {} as any)3940// TODO: fix types for drafts41// TODO: assert unrevoked41// TODO: assert unrevoked, use freeze for that42export class DraftSet<K, V> extends SetBase implements Set<V> {43 [DRAFT_STATE]: SetState44 constructor(target, parent) {45 super()
103 unmodified lines