es5.js
This file
Path
src/es5.js
236 lines · 7.1 KiB · JavaScript
Last changed by
One module to rule them all WIPMichel Weststratebefore adoptionb7647e4
History of this fileTake it
transpile es5 codeMichel Weststratebefore adoptionf012154
lines 1–3why, one step back1"use strict"2// @ts-check3One module to rule them all WIPMichel Weststratebefore adoptionb7647e4
line 4why, one step back4import {autoFreeze, isProxyable, isProxy, freeze, PROXY_STATE} from "./common"transpile es5 codeMichel Weststratebefore adoptionf012154
line 5why, one step back5One module to rule them all WIPMichel Weststratebefore adoptionb7647e4
line 6why, one step back6const descriptors = {}Both implementation statelessMichel Weststratebefore adoption9b3bceb
line 7why, one step back7let states = nulltranspile es5 codeMichel Weststratebefore adoptionf012154
line 8why, one step back8Both implementation statelessMichel Weststratebefore adoption9b3bceb
lines 9–178why, one step back9function createState(parent, proxy, base) {10 return {11 modified: false,12 hasCopy: false,13 parent,14 base,15 proxy,16 copy: undefined,17 finished: false,18 finalizing: false19 }20}2122function source(state) {23 return state.hasCopy ? state.copy : state.base24}2526function get(state, prop) {27 assertUnfinished(state)28 const value = source(state)[prop]29 if (!state.finalizing && !isProxy(value) && isProxyable(value)) {30 prepareCopy(state)31 return (state.copy[prop] = createProxy(state, value))32 }33 return value34}3536function set(state, prop, value) {37 assertUnfinished(state)38 if (!state.modified) {39 if (Object.is(source(state)[prop], value)) return40 markChanged(state)41 }42 prepareCopy(state)43 state.copy[prop] = value44}4546function markChanged(state) {47 if (!state.modified) {48 state.modified = true49 if (state.parent) markChanged(state.parent)50 }51}5253function prepareCopy(state) {54 if (state.hasCopy) return55 state.hasCopy = true56 state.copy = Array.isArray(state.base)57 ? state.base.slice()58 : Object.assign({}, state.base)59}6061// creates a proxy for plain objects / arrays62function createProxy(parent, base) {63 let proxy64 if (Array.isArray(base)) proxy = createArrayProxy(base)65 else proxy = createObjectProxy(base)66 const state = createState(parent, proxy, base)67 createHiddenProperty(proxy, PROXY_STATE, state)68 states.push(state)69 return proxy70}7172function createPropertyProxy(prop) {73 return (74 descriptors[prop] ||75 (descriptors[prop] = {76 configurable: true,77 enumerable: true,78 get() {79 return get(this[PROXY_STATE], prop)80 },81 set(value) {82 set(this[PROXY_STATE], prop, value)83 }84 })85 )86}8788function createObjectProxy(base) {89 const proxy = Object.assign({}, base)90 Object.keys(base).forEach(prop =>91 Object.defineProperty(proxy, prop, createPropertyProxy(prop))92 )93 return proxy94}9596function createArrayProxy(base) {97 const proxy = new Array(base.length)98 for (let i = 0; i < base.length; i++)99 Object.defineProperty(proxy, "" + i, createPropertyProxy("" + i))100 return proxy101}102103function assertUnfinished(state) {104 if (state.finished === true)105 throw new Error(106 "Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process?"107 )108}109110// this sounds very expensive, but actually it is not that extensive in practice111// as it will only visit proxies, and only do key-based change detection for objects for112// which it is not already know that they are changed (that is, only object for which no known key was changed)113function markChanges() {114 // intentionally we process the proxies in reverse order;115 // ideally we start by processing leafs in the tree, because if a child has changed, we don't have to check the parent anymore116 // reverse order of proxy creation approximates this117 for (let i = states.length - 1; i >= 0; i--) {118 const state = states[i]119 if (state.modified === false) {120 if (Array.isArray(state.base)) {121 if (hasArrayChanges(state)) markChanged(state)122 } else if (hasObjectChanges(state)) markChanged(state)123 }124 }125}126127function hasObjectChanges(state) {128 const baseKeys = Object.keys(state.base)129 const keys = Object.keys(state.proxy)130 return !shallowEqual(baseKeys, keys)131}132133function hasArrayChanges(state) {134 return state.proxy.length !== state.base.length135}136137function finalize(proxy) {138 // TODO: almost litterally same as Proxy impl; let's reduce code duplication and rollup139 if (isProxy(proxy)) {140 const state = proxy[PROXY_STATE]141 if (state.modified === true) {142 if (Array.isArray(state.base)) return finalizeArray(proxy, state)143 return finalizeObject(proxy, state)144 } else return state.base145 } else if (proxy !== null && typeof proxy === "object") {146 // If finalize is called on an object that was not a proxy, it means that it is an object that was not there in the original147 // tree and it could contain proxies at arbitrarily places. Let's find and finalize them as well148 if (Array.isArray(proxy)) {149 for (let i = 0; i < proxy.length; i++) proxy[i] = finalize(proxy[i])150 return freeze(proxy)151 }152 const proto = Object.getPrototypeOf(proxy)153 if (proto === null || proto === Object.prototype) {154 for (let key in proxy) proxy[key] = finalize(proxy[key])155 return freeze(proxy)156 }157 }158 return proxy159}160161function finalizeObject(proxy, state) {162 const res = Object.assign({}, proxy)163 const base = state.base164 for (let prop in res) {165 if (proxy[prop] !== base[prop]) res[prop] = finalize(res[prop])166 }167 return freeze(res)168}169170function finalizeArray(proxy, state) {171 const res = proxy.slice()172 const base = state.base173 for (let i = 0; i < res.length; i++) {174 if (res[i] !== base[i]) res[i] = finalize(res[i])175 }176 return freeze(res)177}178One module to rule them all WIPMichel Weststratebefore adoptionb7647e4
line 179why, one step back179export function produceEs5(baseState, producer) {Both implementation statelessMichel Weststratebefore adoption9b3bceb
lines 180–190why, one step back180 const prevStates = states181 states = []182 try {183 // create proxy for root184 const rootClone = createProxy(undefined, baseState)185 // execute the thunk186 const maybeVoidReturn = producer(rootClone)187 //values either than undefined will trigger warning;188 !Object.is(maybeVoidReturn, undefined) &&189 console.warn(190 `Immer callback expects no return value. However ${typeof maybeVoidReturn} was returned`transpile es5 codeMichel Weststratebefore adoptionf012154
line 191why, one step back191 )Both implementation statelessMichel Weststratebefore adoption9b3bceb
lines 192–201why, one step back192 // and finalize the modified proxy193 for (let i = 0; i < states.length; i++) states[i].finalizing = true194 // find and mark all changes (for parts not done yet)195 markChanges()196 const res = finalize(rootClone)197 // make sure all proxies become unusable198 for (let i = 0; i < states.length; i++) states[i].finished = true199 return res200 } finally {201 states = prevStatestranspile es5 codeMichel Weststratebefore adoptionf012154
lines 202–229why, one step back202 }203}204205function shallowEqual(objA, objB) {206 //From: https://github.com/facebook/fbjs/blob/c69904a511b900266935168223063dd8772dfc40/packages/fbjs/src/core/shallowEqual.js207 if (Object.is(objA, objB)) return true208 if (209 typeof objA !== "object" ||210 objA === null ||211 typeof objB !== "object" ||212 objB === null213 ) {214 return false215 }216 const keysA = Object.keys(objA)217 const keysB = Object.keys(objB)218 if (keysA.length !== keysB.length) return false219 for (let i = 0; i < keysA.length; i++) {220 if (221 !hasOwnProperty.call(objB, keysA[i]) ||222 !Object.is(objA[keysA[i]], objB[keysA[i]])223 ) {224 return false225 }226 }227 return true228}229One module to rule them all WIPMichel Weststratebefore adoptionb7647e4
lines 230–235why, one step back230function createHiddenProperty(target, prop, value) {231 Object.defineProperty(target, prop, {232 value: value,233 enumerable: false,234 writable: true235 })transpile es5 codeMichel Weststratebefore adoptionf012154
line 236why, one step back236}