scope.ts
This file
Path
src/core/scope.ts
85 lines · 1.7 KiB · TypeScript
Last changed by
chore: reduce size by using TS const enum (#812)houfengbefore adoptionb1fac9d
History of this fileTake it
The walk stopped after 200 commits: lines older than 497d1a0 point at it.
fix: Don't recurse into non-enumerable members when freezing tree. Fixes #590Michel Weststratebefore adoption497d1a0
lines 1–7why, one step back1import {2 Patch,3 PatchListener,4 Drafted,5 Immer,6 DRAFT_STATE,7 ImmerState,chore: reduce size by using TS const enum (#812)houfengbefore adoptionb1fac9d
line 8why, one step back8 ProxyType,fix: Don't recurse into non-enumerable members when freezing tree. Fixes #590Michel Weststratebefore adoption497d1a0
lines 9–79why, one step back9 getPlugin10} from "../internal"11import {die} from "../utils/errors"1213/** Each scope represents a `produce` call. */1415export interface ImmerScope {16 patches_?: Patch[]17 inversePatches_?: Patch[]18 canAutoFreeze_: boolean19 drafts_: any[]20 parent_?: ImmerScope21 patchListener_?: PatchListener22 immer_: Immer23 unfinalizedDrafts_: number24}2526let currentScope: ImmerScope | undefined2728export function getCurrentScope() {29 if (__DEV__ && !currentScope) die(0)30 return currentScope!31}3233function createScope(34 parent_: ImmerScope | undefined,35 immer_: Immer36): ImmerScope {37 return {38 drafts_: [],39 parent_,40 immer_,41 // Whenever the modified draft contains a draft from another scope, we42 // need to prevent auto-freezing so the unowned draft can be finalized.43 canAutoFreeze_: true,44 unfinalizedDrafts_: 045 }46}4748export function usePatchesInScope(49 scope: ImmerScope,50 patchListener?: PatchListener51) {52 if (patchListener) {53 getPlugin("Patches") // assert we have the plugin54 scope.patches_ = []55 scope.inversePatches_ = []56 scope.patchListener_ = patchListener57 }58}5960export function revokeScope(scope: ImmerScope) {61 leaveScope(scope)62 scope.drafts_.forEach(revokeDraft)63 // @ts-ignore64 scope.drafts_ = null65}6667export function leaveScope(scope: ImmerScope) {68 if (scope === currentScope) {69 currentScope = scope.parent_70 }71}7273export function enterScope(immer: Immer) {74 return (currentScope = createScope(currentScope, immer))75}7677function revokeDraft(draft: Drafted) {78 const state: ImmerState = draft[DRAFT_STATE]79 if (chore: reduce size by using TS const enum (#812)houfengbefore adoptionb1fac9d
lines 80–81why, one step back80 state.type_ === ProxyType.ProxyObject ||81 state.type_ === ProxyType.ProxyArrayfix: Don't recurse into non-enumerable members when freezing tree. Fixes #590Michel Weststratebefore adoption497d1a0
lines 82–85why, one step back82 )83 state.revoke_()84 else state.revoked_ = true85}