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