current.ts
This file
Path
src/core/current.ts
61 lines · 1.8 KiB · TypeScript
Last changed by
fix: Add missing type `current` for pre-TS 3.7 typesMichel Weststratebefore adoption7d6b57b
History of this fileTake it
Immer 7Michel Weststratebefore adoption467ea5d
lines 1–16why, one step back1import {2 die,3 isDraft,4 shallowCopy,5 each,6 DRAFT_STATE,7 get,8 set,9 ImmerState,10 isDraftable,11 ArchtypeMap,12 ArchtypeSet,13 getArchtype,14 getPlugin15} from "../internal"16fix: Add missing type `current` for pre-TS 3.7 typesMichel Weststratebefore adoption7d6b57b
line 17why, one step back17/** Takes a snapshot of the current state of a draft and finalizes it (but without freezing). This is a great utility to print the current state during debugging (no Proxies in the way). The output of current can also be safely leaked outside the producer. */Immer 7Michel Weststratebefore adoption467ea5d
lines 18–61why, one step back18export function current<T>(value: T): T19export function current(value: any): any {20 if (!isDraft(value)) die(22, value)21 return currentImpl(value)22}2324function currentImpl(value: any): any {25 if (!isDraftable(value)) return value26 const state: ImmerState | undefined = value[DRAFT_STATE]27 let copy: any28 const archType = getArchtype(value)29 if (state) {30 if (31 !state.modified_ &&32 (state.type_ < 4 || !getPlugin("ES5").hasChanges_(state as any))33 )34 return state.base_35 // Optimization: avoid generating new drafts during copying36 state.finalized_ = true37 copy = copyHelper(value, archType)38 state.finalized_ = false39 } else {40 copy = copyHelper(value, archType)41 }4243 each(copy, (key, childValue) => {44 if (state && get(state.base_, key) === childValue) return // no need to copy or search in something that didn't change45 set(copy, key, currentImpl(childValue))46 })47 // In the future, we might consider freezing here, based on the current settings48 return archType === ArchtypeSet ? new Set(copy) : copy49}5051function copyHelper(value: any, archType: number): any {52 // creates a shallow copy, even if it is a map or set53 switch (archType) {54 case ArchtypeMap:55 return new Map(value)56 case ArchtypeSet:57 // Set will be cloned as array temporarily, so that we can replace individual items58 return Array.from(value)59 }60 return shallowCopy(value)61}