scope.ts
This file
Path
src/core/scope.ts
86 lines · 1.7 KiB · TypeScript
Last changed by
Merge pull request #536 from immerjs/multi-bundleMichel Weststratebefore adoption0d87fc8
History of this fileTake it
Merge pull request #536 from immerjs/multi-bundleMichel Weststratebefore adoption0d87fc8
lines 1–86why, one step back1import {2 Patch,3 PatchListener,4 Drafted,5 Immer,6 DRAFT_STATE,7 ImmerState,8 ProxyTypeProxyObject,9 ProxyTypeProxyArray,10 getPlugin11} from "../internal"12import {die} from "../utils/errors"1314/** Each scope represents a `produce` call. */1516export interface ImmerScope {17 patches_?: Patch[]18 inversePatches_?: Patch[]19 canAutoFreeze_: boolean20 drafts_: any[]21 parent_?: ImmerScope22 patchListener_?: PatchListener23 immer_: Immer24 unfinalizedDrafts_: number25}2627let currentScope: ImmerScope | undefined2829export function getCurrentScope() {30 if (__DEV__ && !currentScope) die(0)31 return currentScope!32}3334function createScope(35 parent_: ImmerScope | undefined,36 immer_: Immer37): ImmerScope {38 return {39 drafts_: [],40 parent_,41 immer_,42 // Whenever the modified draft contains a draft from another scope, we43 // need to prevent auto-freezing so the unowned draft can be finalized.44 canAutoFreeze_: true,45 unfinalizedDrafts_: 046 }47}4849export function usePatchesInScope(50 scope: ImmerScope,51 patchListener?: PatchListener52) {53 if (patchListener) {54 getPlugin("Patches") // assert we have the plugin55 scope.patches_ = []56 scope.inversePatches_ = []57 scope.patchListener_ = patchListener58 }59}6061export function revokeScope(scope: ImmerScope) {62 leaveScope(scope)63 scope.drafts_.forEach(revokeDraft)64 // @ts-ignore65 scope.drafts_ = null66}6768export function leaveScope(scope: ImmerScope) {69 if (scope === currentScope) {70 currentScope = scope.parent_71 }72}7374export function enterScope(immer: Immer) {75 return (currentScope = createScope(currentScope, immer))76}7778function revokeDraft(draft: Drafted) {79 const state: ImmerState = draft[DRAFT_STATE]80 if (81 state.type_ === ProxyTypeProxyObject ||82 state.type_ === ProxyTypeProxyArray83 )84 state.revoke_()85 else state.revoked_ = true86}