common.ts
This file
Path
src/common.ts
240 lines · 6.3 KiB · TypeScript
Last changed by
Processed bunch of todosMichel Weststratebefore adoption00425e1
History of this fileTake it
Further cleanup in progressMichel Weststratebefore adoptionaeba1ff
lines 1–10why, one step back1import {2 Objectish,3 ObjectishNoSet,4 Drafted,5 AnyObject,6 AnyArray,7 AnyMap,8 AnySet,9 ImmerState10} from "./types"Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 11–18why, one step back1112/** Use a class type for `nothing` so its type is unique */13export class Nothing {14 // This lets us do `Exclude<T, Nothing>`15 // TODO: do this better, use unique symbol instead16 private _: any17}18Processed bunch of todosMichel Weststratebefore adoption00425e1
lines 19–22why, one step back19const hasSymbol = typeof Symbol !== "undefined"20export const hasMap = typeof Map !== "undefined"21export const hasSet = typeof Set !== "undefined"22Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 23–25why, one step back23/**24 * The sentinel value returned by producers to replace the draft with undefined.25 */Processed bunch of todosMichel Weststratebefore adoption00425e1
lines 26–28why, one step back26export const NOTHING: Nothing = hasSymbol27 ? Symbol("immer-nothing")28 : ({["immer-nothing"]: true} as any)Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 29–37why, one step back2930/**31 * To let Immer treat your class instances as plain immutable objects32 * (albeit with a custom prototype), you must define either an instance property33 * or a static property on each of your custom classes.34 *35 * Otherwise, your class instance will never be drafted, which means it won't be36 * safe to mutate in a produce callback.37 */Processed bunch of todosMichel Weststratebefore adoption00425e1
lines 38–40why, one step back38export const DRAFTABLE: unique symbol = hasSymbol39 ? Symbol("immer-draftable")40 : ("__$immer_draftable" as any)Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
line 41why, one step back41Processed bunch of todosMichel Weststratebefore adoption00425e1
lines 42–44why, one step back42export const DRAFT_STATE: unique symbol = hasSymbol43 ? Symbol("immer-state")44 : ("__$immer_state" as any)Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
line 45why, one step back45Processed bunch of todosMichel Weststratebefore adoption00425e1
lines 46–49why, one step back46export const iteratorSymbol: typeof Symbol.iterator = hasSymbol47 ? Symbol.iterator48 : ("@@iterator" as any)49Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 50–66why, one step back50/** Returns true if the given value is an Immer draft */51export function isDraft(value: any): boolean {52 return !!value && !!value[DRAFT_STATE]53}5455/** Returns true if the given value can be drafted by Immer */56export function isDraftable(value: any): boolean {57 if (!value) return false58 return (59 isPlainObject(value) ||60 !!value[DRAFTABLE] ||61 !!value.constructor[DRAFTABLE] ||62 isMap(value) ||63 isSet(value)64 )65}66TS type improvementsMichel Weststratebefore adoptiondd1808e
line 67why, one step back67export function isPlainObject(value: any): boolean {Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 68–74why, one step back68 if (!value || typeof value !== "object") return false69 if (Array.isArray(value)) return true70 const proto = Object.getPrototypeOf(value)71 return !proto || proto === Object.prototype72}7374/** Get the underlying object that is represented by the given draft */Dropped Object.assignMichel Weststratebefore adoption79a1d2c
line 75why, one step back75export function original<T>(value: Drafted<T>): T | undefined {Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
line 76why, one step back76 if (value && value[DRAFT_STATE]) {Dropped Object.assignMichel Weststratebefore adoption79a1d2c
line 77why, one step back77 return value[DRAFT_STATE].base as anyMerge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 78–81why, one step back78 }79 // otherwise return undefined80}81TS type improvementsMichel Weststratebefore adoptiondd1808e
line 82why, one step back82export const ownKeys: (target: AnyObject) => PropertyKey[] =Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 83–86why, one step back83 typeof Reflect !== "undefined" && Reflect.ownKeys84 ? Reflect.ownKeys85 : typeof Object.getOwnPropertySymbols !== "undefined"86 ? obj =>🎵...killing me softly, with your fingers... 🎶Michel Weststratebefore adoption19a6b66
lines 87–89why, one step back87 Object.getOwnPropertyNames(obj).concat(88 Object.getOwnPropertySymbols(obj) as any89 )Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 90–93why, one step back90 : Object.getOwnPropertyNames9192export function each<T extends Objectish>(93 obj: T,Further cleanup in progressMichel Weststratebefore adoptionaeba1ff
line 94why, one step back94 iter: (key: string | number, value: any, source: T) => voidTS type improvementsMichel Weststratebefore adoptiondd1808e
lines 95–96why, one step back95): void96export function each(obj: any, iter: any) {Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
line 97why, one step back97 if (Array.isArray(obj) || isMap(obj) || isSet(obj)) {TS type improvementsMichel Weststratebefore adoptiondd1808e
line 98why, one step back98 obj.forEach((entry: any, index: any) => iter(index, entry, obj))basic map tests succeedingMichel Weststratebefore adoption735c402
line 99why, one step back99 } else if (obj && typeof obj === "object") {Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
line 100why, one step back100 ownKeys(obj).forEach(key => iter(key, obj[key], obj))basic map tests succeedingMichel Weststratebefore adoption735c402
line 101why, one step back101 } else {TS type improvementsMichel Weststratebefore adoptiondd1808e
line 102why, one step back102 die()Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 103–105why, one step back103 }104}105Dropped Object.assignMichel Weststratebefore adoption79a1d2c
line 106why, one step back106export function isEnumerable(base: AnyObject, prop: PropertyKey): boolean {Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 107–110why, one step back107 const desc = Object.getOwnPropertyDescriptor(base, prop)108 return desc && desc.enumerable ? true : false109}110TS type improvementsMichel Weststratebefore adoptiondd1808e
lines 111–112why, one step back111// TODO: use draft meta data if present?112// make refelction methods to determine types?Processed bunch of todosMichel Weststratebefore adoption00425e1
line 113why, one step back113export function has(thing: any, prop: PropertyKey): boolean {basic map tests succeedingMichel Weststratebefore adoption735c402
lines 114–116why, one step back114 return !thing115 ? false116 : isMap(thing)Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 117–120why, one step back117 ? thing.has(prop)118 : Object.prototype.hasOwnProperty.call(thing, prop)119}120TS type improvementsMichel Weststratebefore adoptiondd1808e
lines 121–123why, one step back121// TODO: use draft meta data if present?122export function get(thing: AnyMap | AnyObject, prop: PropertyKey): any {123 return isMap(thing) ? thing.get(prop) : thing[prop as any]Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 124–125why, one step back124}125TS type improvementsMichel Weststratebefore adoptiondd1808e
lines 126–154why, one step back126// TODO: measure fast vs slow path, use type switch instead127export function set(parent: Drafted, prop: PropertyKey, value: any) {128 // fast path switch on meta data129 if (parent[DRAFT_STATE])130 switch (parent[DRAFT_STATE].type) {131 case "map":132 parent.set(prop, value)133 break134 case "set":135 parent.delete(prop)136 parent.add(value)137 break138 default:139 parent[prop] = value140 }141142 // slow path143 parent[prop] = value144 if (isMap(parent)) {145 parent.set(prop, value)146 } else if (isSet(parent)) {147 // In this case, the `prop` is actually a draft.148 parent.delete(prop)149 parent.add(value)150 } else {151 parent[prop] = value152 }153}154Further cleanup in progressMichel Weststratebefore adoptionaeba1ff
line 155why, one step back155export function is(x: any, y: any): boolean {Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 156–163why, one step back156 // From: https://github.com/facebook/fbjs/blob/c69904a511b900266935168223063dd8772dfc40/packages/fbjs/src/core/shallowEqual.js157 if (x === y) {158 return x !== 0 || 1 / x === 1 / y159 } else {160 return x !== x && y !== y161 }162}163Further cleanup in progressMichel Weststratebefore adoptionaeba1ff
line 164why, one step back164export function isMap(target: any): target is AnyMap {Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 165–167why, one step back165 return hasMap && target instanceof Map166}167Further cleanup in progressMichel Weststratebefore adoptionaeba1ff
line 168why, one step back168export function isSet(target: any): target is AnySet {Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 169–171why, one step back169 return hasSet && target instanceof Set170}171Further cleanup in progressMichel Weststratebefore adoptionaeba1ff
line 172why, one step back172export function latest(state: ImmerState): any {Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 173–174why, one step back173 return state.copy || state.base174}fixed most testsMichel Weststratebefore adoption385c0a4
line 175why, one step back175Further cleanup in progressMichel Weststratebefore adoptionaeba1ff
line 176why, one step back176export function shallowCopy<T extends AnyObject | AnyArray>(Some initial cleanupMichel Weststratebefore adoptionc53a75f
lines 177–179why, one step back177 base: T,178 invokeGetters?: boolean179): TTS type improvementsMichel Weststratebefore adoptiondd1808e
line 180why, one step back180export function shallowCopy(base: any, invokeGetters = false) {Some initial cleanupMichel Weststratebefore adoptionc53a75f
lines 181–205why, one step back181 if (Array.isArray(base)) return base.slice()182 const clone = Object.create(Object.getPrototypeOf(base))183 ownKeys(base).forEach(key => {184 if (key === DRAFT_STATE) {185 return // Never copy over draft state.186 }187 const desc = Object.getOwnPropertyDescriptor(base, key)!188 let {value} = desc189 if (desc.get) {190 if (!invokeGetters) {191 throw new Error("Immer drafts cannot have computed properties")192 }193 value = desc.get.call(base)194 }195 if (desc.enumerable) {196 clone[key] = value197 } else {198 Object.defineProperty(clone, key, {199 value,200 writable: true,201 configurable: true202 })203 }204 })205 return cloneMerge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 206–223why, one step back206}207208export function freeze<T extends Objectish>(209 obj: T,210 deep: boolean = false211): void {212 if (!isDraftable(obj) || isDraft(obj) || Object.isFrozen(obj)) return213 if (isSet(obj)) {214 obj.add = obj.clear = obj.delete = dontMutateFrozenCollections as any215 } else if (isMap(obj)) {216 obj.set = obj.clear = obj.delete = dontMutateFrozenCollections as any217 }218 Object.freeze(obj)219 if (deep) each(obj, (_, value) => freeze(value, true))220}221222function dontMutateFrozenCollections() {223 throw new Error("This object has been frozen and should not be mutated")TS type improvementsMichel Weststratebefore adoptiondd1808e
lines 224–239why, one step back224}225226export function createHiddenProperty(227 target: AnyObject,228 prop: PropertyKey,229 value: any230) {231 Object.defineProperty(target, prop, {232 value: value,233 enumerable: false,234 writable: true235 })236}237238export function die(): never {239 throw new Error("Illegal state, please file a bug")Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
line 240why, one step back240}