common.ts
This file
Path
src/common.ts
289 lines · 7.9 KiB · TypeScript
Last changed by
added set and iteror stuffMichel Weststratebefore adoption08f4682
History of this fileTake it
Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 1–107why, one step back1import {Objectish, ObjectishNoSet, ImmerState} from "./types"23/** Use a class type for `nothing` so its type is unique */4export class Nothing {5 // This lets us do `Exclude<T, Nothing>`6 // TODO: do this better, use unique symbol instead7 private _: any8}910/**11 * The sentinel value returned by producers to replace the draft with undefined.12 */13export const NOTHING: Nothing =14 typeof Symbol !== "undefined"15 ? Symbol("immer-nothing")16 : ({["immer-nothing"]: true} as any)1718/**19 * To let Immer treat your class instances as plain immutable objects20 * (albeit with a custom prototype), you must define either an instance property21 * or a static property on each of your custom classes.22 *23 * Otherwise, your class instance will never be drafted, which means it won't be24 * safe to mutate in a produce callback.25 */26export const DRAFTABLE: unique symbol =27 typeof Symbol !== "undefined" && Symbol.for28 ? Symbol.for("immer-draftable")29 : ("__$immer_draftable" as any)3031export const DRAFT_STATE: unique symbol =32 typeof Symbol !== "undefined" && Symbol.for33 ? Symbol.for("immer-state")34 : ("__$immer_state" as any)3536/** Returns true if the given value is an Immer draft */37export function isDraft(value: any): boolean {38 return !!value && !!value[DRAFT_STATE]39}4041/** Returns true if the given value can be drafted by Immer */42export function isDraftable(value: any): boolean {43 if (!value) return false44 return (45 isPlainObject(value) ||46 !!value[DRAFTABLE] ||47 !!value.constructor[DRAFTABLE] ||48 isMap(value) ||49 isSet(value)50 )51}5253export function isPlainObject(value): boolean {54 if (!value || typeof value !== "object") return false55 if (Array.isArray(value)) return true56 const proto = Object.getPrototypeOf(value)57 return !proto || proto === Object.prototype58}5960/** Get the underlying object that is represented by the given draft */61export function original<T>(value: T): T | undefined {62 if (value && value[DRAFT_STATE]) {63 return value[DRAFT_STATE].base64 }65 // otherwise return undefined66}6768// We use Maps as `drafts` for Sets, not Objects69// See proxy.js70export function assignSet(target: Map<any, any>, override) {71 override.forEach(value => {72 // When we add new drafts we have to remove their originals if present73 const prev = original(value)74 if (prev) target.delete(prev)75 // @ts-ignore TODO investigate76 target.add(value)77 })78 return target79}8081// We use Maps as `drafts` for Maps, not Objects82// See proxy.js83export function assignMap(target: Map<any, any>, override: Map<any, any>) {84 override.forEach((value, key) => target.set(key, value))85 return target86}8788export const assign =89 Object.assign ||90 ((target, ...overrides) => {91 overrides.forEach(override => {92 if (typeof override === "object" && override !== null)93 Object.keys(override).forEach(key => (target[key] = override[key]))94 })95 return target96 })9798export const ownKeys: (target) => PropertyKey[] =99 typeof Reflect !== "undefined" && Reflect.ownKeys100 ? Reflect.ownKeys101 : typeof Object.getOwnPropertySymbols !== "undefined"102 ? obj =>103 Object.getOwnPropertyNames(obj).concat(Object.getOwnPropertySymbols(104 obj105 ) as any)106 : Object.getOwnPropertyNames107added set and iteror stuffMichel Weststratebefore adoption08f4682
line 108why, one step back108// TODO: duplicate of clone? TODO: should be used by prepareCopy of map / setMerge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 109–149why, one step back109export function shallowCopy<T extends Objectish>(110 base: T,111 invokeGetters?: boolean112): T113export function shallowCopy(base, invokeGetters = false) {114 if (Array.isArray(base)) return base.slice()115 if (isMap(base)) return new Map(base)116 if (isSet(base)) return new Set(base)117 const clone = Object.create(Object.getPrototypeOf(base))118 ownKeys(base).forEach(key => {119 if (key === DRAFT_STATE) {120 return // Never copy over draft state.121 }122 const desc = Object.getOwnPropertyDescriptor(base, key)!123 let {value} = desc124 if (desc.get) {125 if (!invokeGetters) {126 throw new Error("Immer drafts cannot have computed properties")127 }128 value = desc.get.call(base)129 }130 if (desc.enumerable) {131 clone[key] = value132 } else {133 Object.defineProperty(clone, key, {134 value,135 writable: true,136 configurable: true137 })138 }139 })140 return clone141}142143export function each<T extends Objectish>(144 obj: T,145 iter: (key: PropertyKey, value: any, source: T) => void146)147export function each(obj, iter) {148 if (Array.isArray(obj) || isMap(obj) || isSet(obj)) {149 obj.forEach((entry, index) => iter(index, entry, obj))basic map tests succeedingMichel Weststratebefore adoption735c402
line 150why, one step back150 } else if (obj && typeof obj === "object") {Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
line 151why, one step back151 ownKeys(obj).forEach(key => iter(key, obj[key], obj))basic map tests succeedingMichel Weststratebefore adoption735c402
lines 152–153why, one step back152 } else {153 throw new Error("Cannot iterate primitive " + obj)Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 154–162why, one step back154 }155}156157export function isEnumerable(base: {}, prop: PropertyKey): boolean {158 const desc = Object.getOwnPropertyDescriptor(base, prop)159 return desc && desc.enumerable ? true : false160}161162export function has(thing: ObjectishNoSet, prop: PropertyKey): boolean {basic map tests succeedingMichel Weststratebefore adoption735c402
lines 163–165why, one step back163 return !thing164 ? false165 : isMap(thing)Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 166–221why, one step back166 ? thing.has(prop)167 : Object.prototype.hasOwnProperty.call(thing, prop)168}169170export function get(thing: ObjectishNoSet, prop: PropertyKey) {171 return isMap(thing) ? thing.get(prop) : thing[prop]172}173174export function is(x, y): boolean {175 // From: https://github.com/facebook/fbjs/blob/c69904a511b900266935168223063dd8772dfc40/packages/fbjs/src/core/shallowEqual.js176 if (x === y) {177 return x !== 0 || 1 / x === 1 / y178 } else {179 return x !== x && y !== y180 }181}182183export const hasSymbol = typeof Symbol !== "undefined"184185export const hasMap = typeof Map !== "undefined"186187export function isMap(target): target is Map<any, any> {188 return hasMap && target instanceof Map189}190191export const hasSet = typeof Set !== "undefined"192193export function isSet(target): target is Set<any> {194 return hasSet && target instanceof Set195}196197export function makeIterable(next: () => {done: boolean; value: any}) {198 let self199 return (self = {200 [Symbol.iterator]: () => self,201 next202 })203}204205/** Map.prototype.values _-or-_ Map.prototype.entries */206export function iterateMapValues(state, prop, receiver) {207 const isEntries = prop !== "values"208 return () => {209 const iterator = latest(state)[Symbol.iterator]()210 return makeIterable(() => {211 const result = iterator.next()212 if (!result.done) {213 const [key] = result.value214 const value = receiver.get(key)215 result.value = isEntries ? [key, value] : value216 }217 return result218 })219 }220}221map unification WIPMichel Weststratebefore adoption9bcefb6
line 222why, one step back222export function makeIterateSetValues() {Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 223–244why, one step back223 function iterateSetValues(state, prop?) {224 const isEntries = prop === "entries"225 return () => {226 const iterator = latest(state)[Symbol.iterator]()227 return makeIterable(() => {228 const result = iterator.next()229 if (!result.done) {230 const value = wrapSetValue(state, result.value)231 result.value = isEntries ? [value, value] : value232 }233 return result234 })235 }236 }237238 function wrapSetValue(state, value) {239 const key = original(value) || value240 let draft = state.drafts.get(key)241 if (!draft) {242 if (state.finalized || !isDraftable(value) || state.finalizing) {243 return value244 }map unification WIPMichel Weststratebefore adoption9bcefb6
line 245why, one step back245 draft = state.scope.immer.createProxy(value, state)Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 246–256why, one step back246 state.drafts.set(key, draft)247 if (state.modified) {248 state.copy.add(draft)249 }250 }251 return draft252 }253254 return iterateSetValues255}256map unification WIPMichel Weststratebefore adoption9bcefb6
line 257why, one step back257export function latest(state: any): any {Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 258–260why, one step back258 return state.copy || state.base259}260added set and iteror stuffMichel Weststratebefore adoption08f4682
line 261why, one step back261// TODO: duplicate of shallow cloneMerge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 262–289why, one step back262export function clone<T extends Objectish>(obj: T): T263export function clone(obj) {264 if (!isDraftable(obj)) return obj265 if (Array.isArray(obj)) return obj.map(clone)266 if (isMap(obj)) return new Map(obj)267 if (isSet(obj)) return new Set(obj)268 const cloned = Object.create(Object.getPrototypeOf(obj))269 for (const key in obj) cloned[key] = clone(obj[key])270 return cloned271}272273export function freeze<T extends Objectish>(274 obj: T,275 deep: boolean = false276): void {277 if (!isDraftable(obj) || isDraft(obj) || Object.isFrozen(obj)) return278 if (isSet(obj)) {279 obj.add = obj.clear = obj.delete = dontMutateFrozenCollections as any280 } else if (isMap(obj)) {281 obj.set = obj.clear = obj.delete = dontMutateFrozenCollections as any282 }283 Object.freeze(obj)284 if (deep) each(obj, (_, value) => freeze(value, true))285}286287function dontMutateFrozenCollections() {288 throw new Error("This object has been frozen and should not be mutated")289}