| 1 | import {
|
|---|
| 2 | Patch,
|
|---|
| 3 | PatchListener,
|
|---|
| 4 | Drafted,
|
|---|
| 5 | Immer,
|
|---|
| 6 | DRAFT_STATE,
|
|---|
| 7 | ImmerState,
|
|---|
| 8 | ProxyType,
|
|---|
| 9 | getPlugin
|
|---|
| 10 | } from "../internal"
|
|---|
| 11 | import {die} from "../utils/errors"
|
|---|
| 12 |
|
|---|
| 13 | /** Each scope represents a `produce` call. */
|
|---|
| 14 |
|
|---|
| 15 | export interface ImmerScope {
|
|---|
| 16 | patches_?: Patch[]
|
|---|
| 17 | inversePatches_?: Patch[]
|
|---|
| 18 | canAutoFreeze_: boolean
|
|---|
| 19 | drafts_: any[]
|
|---|
| 20 | parent_?: ImmerScope
|
|---|
| 21 | patchListener_?: PatchListener
|
|---|
| 22 | immer_: Immer
|
|---|
| 23 | unfinalizedDrafts_: number
|
|---|
| 24 | }
|
|---|
| 25 |
|
|---|
| 26 | let currentScope: ImmerScope | undefined
|
|---|
| 27 |
|
|---|
| 28 | export function getCurrentScope() {
|
|---|
| 29 | if (__DEV__ && !currentScope) die(0)
|
|---|
| 30 | return currentScope!
|
|---|
| 31 | }
|
|---|
| 32 |
|
|---|
| 33 | function createScope(
|
|---|
| 34 | parent_: ImmerScope | undefined,
|
|---|
| 35 | immer_: Immer
|
|---|
| 36 | ): ImmerScope {
|
|---|
| 37 | return {
|
|---|
| 38 | drafts_: [],
|
|---|
| 39 | parent_,
|
|---|
| 40 | immer_,
|
|---|
| 41 | // Whenever the modified draft contains a draft from another scope, we
|
|---|
| 42 | // need to prevent auto-freezing so the unowned draft can be finalized.
|
|---|
| 43 | canAutoFreeze_: true,
|
|---|
| 44 | unfinalizedDrafts_: 0
|
|---|
| 45 | }
|
|---|
| 46 | }
|
|---|
| 47 |
|
|---|
| 48 | export function usePatchesInScope(
|
|---|
| 49 | scope: ImmerScope,
|
|---|
| 50 | patchListener?: PatchListener
|
|---|
| 51 | ) {
|
|---|
| 52 | if (patchListener) {
|
|---|
| 53 | getPlugin("Patches") // assert we have the plugin
|
|---|
| 54 | scope.patches_ = []
|
|---|
| 55 | scope.inversePatches_ = []
|
|---|
| 56 | scope.patchListener_ = patchListener
|
|---|
| 57 | }
|
|---|
| 58 | }
|
|---|
| 59 |
|
|---|
| 60 | export function revokeScope(scope: ImmerScope) {
|
|---|
| 61 | leaveScope(scope)
|
|---|
| 62 | scope.drafts_.forEach(revokeDraft)
|
|---|
| 63 | // @ts-ignore
|
|---|
| 64 | scope.drafts_ = null
|
|---|
| 65 | }
|
|---|
| 66 |
|
|---|
| 67 | export function leaveScope(scope: ImmerScope) {
|
|---|
| 68 | if (scope === currentScope) {
|
|---|
| 69 | currentScope = scope.parent_
|
|---|
| 70 | }
|
|---|
| 71 | }
|
|---|
| 72 |
|
|---|
| 73 | export function enterScope(immer: Immer) {
|
|---|
| 74 | return (currentScope = createScope(currentScope, immer))
|
|---|
| 75 | }
|
|---|
| 76 |
|
|---|
| 77 | function revokeDraft(draft: Drafted) {
|
|---|
| 78 | const state: ImmerState = draft[DRAFT_STATE]
|
|---|
| 79 | if (
|
|---|
| 80 | state.type_ === ProxyType.ProxyObject ||
|
|---|
| 81 | state.type_ === ProxyType.ProxyArray
|
|---|
| 82 | )
|
|---|
| 83 | state.revoke_()
|
|---|
| 84 | else state.revoked_ = true
|
|---|
| 85 | }
|
|---|