scope.ts
This file
Path
src/core/scope.ts
80 lines · 1.6 KiB · TypeScript
Last changed by
Merge pull request #1028 from immerjs/immer-10Michel Weststratebefore adoption2ef9a42
History of this fileTake it
The walk stopped after 200 commits: lines older than fe8f589 point at it.
chore(comments): update comments (#727)郗银before adoptionfe8f589
lines 1–7why, one step back1import {2 Patch,3 PatchListener,4 Drafted,5 Immer,6 DRAFT_STATE,7 ImmerState,Merge pull request #1028 from immerjs/immer-10Michel Weststratebefore adoption2ef9a42
line 8why, one step back8 ArchType,chore(comments): update comments (#727)郗银before adoptionfe8f589
lines 9–76why, one step back9 getPlugin10} from "../internal"1112/** Each scope represents a `produce` call. */1314export interface ImmerScope {15 patches_?: Patch[]16 inversePatches_?: Patch[]17 canAutoFreeze_: boolean18 drafts_: any[]19 parent_?: ImmerScope20 patchListener_?: PatchListener21 immer_: Immer22 unfinalizedDrafts_: number23}2425let currentScope: ImmerScope | undefined2627export function getCurrentScope() {28 return currentScope!29}3031function createScope(32 parent_: ImmerScope | undefined,33 immer_: Immer34): ImmerScope {35 return {36 drafts_: [],37 parent_,38 immer_,39 // Whenever the modified draft contains a draft from another scope, we40 // need to prevent auto-freezing so the unowned draft can be finalized.41 canAutoFreeze_: true,42 unfinalizedDrafts_: 043 }44}4546export function usePatchesInScope(47 scope: ImmerScope,48 patchListener?: PatchListener49) {50 if (patchListener) {51 getPlugin("Patches") // assert we have the plugin52 scope.patches_ = []53 scope.inversePatches_ = []54 scope.patchListener_ = patchListener55 }56}5758export function revokeScope(scope: ImmerScope) {59 leaveScope(scope)60 scope.drafts_.forEach(revokeDraft)61 // @ts-ignore62 scope.drafts_ = null63}6465export function leaveScope(scope: ImmerScope) {66 if (scope === currentScope) {67 currentScope = scope.parent_68 }69}7071export function enterScope(immer: Immer) {72 return (currentScope = createScope(currentScope, immer))73}7475function revokeDraft(draft: Drafted) {76 const state: ImmerState = draft[DRAFT_STATE]Merge pull request #1028 from immerjs/immer-10Michel Weststratebefore adoption2ef9a42
line 77why, one step back77 if (state.type_ === ArchType.Object || state.type_ === ArchType.Array)chore(comments): update comments (#727)郗银before adoptionfe8f589
lines 78–80why, one step back78 state.revoke_()79 else state.revoked_ = true80}