use-reactive-object
Version:
React hook for creating reactive objects.
2 lines (1 loc) • 1.82 kB
JavaScript
;Object.defineProperty(exports,"__esModule",{value:!0});var e=require("react");const t=e=>!(e=>null==e)(e)&&(e=>"object"==typeof e)(e)&&!(e=>e instanceof Date)(e);function n(e,r,o,c=[]){const a=e=>c.concat(e).join("."),i=new WeakMap;let s=0;const f=new Proxy(e,{set(e,t,n){const o=a(t);return r({path:o,target:e,newValue:n,previousValue:Reflect.get(e,t,n)}),Reflect.set(e,t,n)},get(e,f,u){var l,p;const y=Reflect.get(e,f,u);if("function"==typeof y&&function(e){return e instanceof Map||e instanceof Set||e instanceof WeakMap||e instanceof WeakSet||e instanceof Date||e instanceof RegExp||e instanceof ArrayBuffer||e instanceof DataView||ArrayBuffer.isView(e)||e instanceof Promise||e instanceof Error}(e))return y.bind(e);if(!t(y)||Object.isFrozen(y))return y;const g=i.get(y);if(g)return g;const v=a(f);if(o){if(o.level&&(s=s||(v.match(/\./g)||[]).length+1,s===o.level))return y;if(!(null===(p=null===(l=o.filter)||void 0===l?void 0:l.call(o,{path:v,target:e,value:y}))||void 0===p||p))return y}const b=n(y,r,o,c.concat(f));return i.set(y,b),b}});return f.onProxy&&"function"==typeof f.onProxy&&f.onProxy(f),f}exports.ReactiveObject=class{onProxy(e){let t=Object.getPrototypeOf(this);for(;t&&t!==Object.prototype;){for(const n of Object.getOwnPropertyNames(t)){const r=Object.getOwnPropertyDescriptor(t,n);r&&"function"==typeof r.value&&"constructor"!==n&&(this[n]=this[n].bind(e))}t=Object.getPrototypeOf(t)}}},exports.buildProxy=n,exports.default=function(t,r){const[,o]=e.useReducer((()=>Math.random()),0),c=e.useRef(),a=e.useRef();if(!a.current){c.current=new Map;const e="function"==typeof t?t():t;a.current=n(e,(e=>{c.current.get(e.path)!==e.newValue&&((null==r?void 0:r.intercept)?r.intercept((()=>o()),e):o(),c.current.set(e.path,e.newValue))}),r)}return a.current};//# sourceMappingURL=index.cjs.js.map