UNPKG

x-view-model

Version:

A lightweight, type-safe MVVM state management solution for React applications. Features reactive updates, computed properties, and deep path selection with minimal bundle size.

17 lines (14 loc) 13.8 kB
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var t=require("react"); /*! ***************************************************************************** Copyright (c) Microsoft Corporation. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ***************************************************************************** */function e(t,e,s,r){return new(s||(s=Promise))((function(o,n){function i(t){try{a(r.next(t))}catch(t){n(t)}}function h(t){try{a(r.throw(t))}catch(t){n(t)}}function a(t){var e;t.done?o(t.value):(e=t.value,e instanceof s?e:new s((function(t){t(e)}))).then(i,h)}a((r=r.apply(t,e||[])).next())}))}const s="insert",r="update",o="delete",n="reverse",i="shuffle",h=Symbol.for("object-observer-meta-key-0"),a={async:1},c=t=>{if(!t||"object"!=typeof t)return null;const e={},s=[];for(const[r,o]of Object.entries(t))if("path"===r){if("string"!=typeof o||""===o)throw new Error('"path" option, if/when provided, MUST be a non-empty string');e[r]=o}else if("pathsOf"===r){if(t.path)throw new Error('"pathsOf" option MAY NOT be specified together with "path" option');if("string"!=typeof o)throw new Error('"pathsOf" option, if/when provided, MUST be a string (MAY be empty)');e[r]=t.pathsOf.split(".").filter(Boolean)}else if("pathsFrom"===r){if(t.path||t.pathsOf)throw new Error('"pathsFrom" option MAY NOT be specified together with "path"/"pathsOf" option/s');if("string"!=typeof o||""===o)throw new Error('"pathsFrom" option, if/when provided, MUST be a non-empty string');e[r]=o}else s.push(r);if(s.length)throw new Error(`'${s.join(", ")}' is/are not a valid observer option/s`);return e},l=(t,e)=>{const s={};s[h]=e;for(const r in t)s[r]=w(t[r],r,e);return s},p=(t,e)=>{let s=t.length;const r=new Array(s);r[h]=e;for(let o=0;o<s;o++)r[o]=w(t[o],o,e);return r},f=(t,e)=>(t[h]=e,t),u=(t,e)=>{if(null===t)return e;let s=e;if(t.path){const r=t.path;s=e.filter((t=>t.path.join(".")===r))}else if(t.pathsOf){const r=t.pathsOf,o=r.join(".");s=e.filter((t=>(t.path.length===r.length+1||t.path.length===r.length&&(t.type===n||t.type===i))&&t.path.join(".").startsWith(o)))}else if(t.pathsFrom){const r=t.pathsFrom;s=e.filter((t=>t.path.join(".").startsWith(r)))}return s},y=(t,e)=>{try{t(e)}catch(s){console.error(`failed to notify listener ${t} with ${e}`,s)}},b=function(){const t=this.batches;this.batches=[];for(const[e,s]of t)y(e,s)},d=(t,e)=>{let s,r,o,n,i,h,a=t;const c=e.length;do{for(s=a.options.async,r=a.observers,h=r.length;h--;)if([o,n]=r[h],i=u(n,e),i.length)if(s){let t;0===a.batches.length&&queueMicrotask(b.bind(a));for(const e of a.batches)if(e[0]===o){t=e;break}t||(t=[o,[]],a.batches.push(t)),Array.prototype.push.apply(t[1],i)}else y(o,i);const t=a.parent;if(t){for(let t=0;t<c;t++){const s=e[t];e[t]=new O(s.type,[a.ownKey,...s.path],s.value,s.oldValue,s.object)}a=t}else a=null}while(a)},w=(t,e,s)=>"object"!=typeof t||null===t?t:Array.isArray(t)?new A({target:t,ownKey:e,parent:s}).proxy:ArrayBuffer.isView(t)?new N({target:t,ownKey:e,parent:s}).proxy:t instanceof Date?t:new E({target:t,ownKey:e,parent:s}).proxy,v=function(){const t=this[h],e=t.target;let s,r,o;for(e.reverse(),s=0,r=e.length;s<r;s++)if(o=e[s],o&&"object"==typeof o){const t=o[h];t&&(t.ownKey=s)}const i=[new O(n,[],void 0,void 0,this)];return d(t,i),this},g=function(t){const e=this[h],s=e.target;let r,o,n;for(s.sort(t),r=0,o=s.length;r<o;r++)if(n=s[r],n&&"object"==typeof n){const t=n[h];t&&(t.ownKey=r)}const a=[new O(i,[],void 0,void 0,this)];return d(e,a),this},m=function(t,e,o){const n=this[h],i=n.target,a=[],c=i.length,l=i.slice(0);if(e=void 0===e?0:e<0?Math.max(c+e,0):Math.min(e,c),o=void 0===o?c:o<0?Math.max(c+o,0):Math.min(o,c),e<c&&o>e){let c;i.fill(t,e,o);for(let t,p,f=e;f<o;f++)t=i[f],i[f]=w(t,f,n),f in l?(p=l[f],p&&"object"==typeof p&&(c=p[h],c&&(p=c.detach())),a.push(new O(r,[f],i[f],p,this))):a.push(new O(s,[f],i[f],void 0,this));d(n,a)}return this},j=function(t,e,s){const o=this[h],n=o.target,i=n.length;t=t<0?Math.max(i+t,0):t,e=void 0===e?0:e<0?Math.max(i+e,0):Math.min(e,i),s=void 0===s?i:s<0?Math.max(i+s,0):Math.min(s,i);const a=Math.min(s-e,i-t);if(t<i&&t!==e&&a>0){const i=n.slice(0),c=[];n.copyWithin(t,e,s);for(let e,s,l,p=t;p<t+a;p++)e=n[p],e&&"object"==typeof e&&(e=w(e,p,o),n[p]=e),s=i[p],s&&"object"==typeof s&&(l=s[h],l&&(s=l.detach())),"object"!=typeof e&&e===s||c.push(new O(r,[p],e,s,this));d(o,c)}return this},x={pop:function(){const t=this[h],e=t.target,s=e.length-1;let r=e.pop();if(r&&"object"==typeof r){const t=r[h];t&&(r=t.detach())}const n=[new O(o,[s],void 0,r,this)];return d(t,n),r},push:function(){const t=this[h],e=t.target,r=arguments.length,o=new Array(r),n=e.length;for(let e=0;e<r;e++)o[e]=w(arguments[e],n+e,t);const i=Reflect.apply(e.push,e,o),a=[];for(let t=n,r=e.length;t<r;t++)a[t-n]=new O(s,[t],e[t],void 0,this);return d(t,a),i},shift:function(){const t=this[h],e=t.target;let s,r,n,i,a;for(s=e.shift(),s&&"object"==typeof s&&(a=s[h],a&&(s=a.detach())),r=0,n=e.length;r<n;r++)i=e[r],i&&"object"==typeof i&&(a=i[h],a&&(a.ownKey=r));const c=[new O(o,[0],void 0,s,this)];return d(t,c),s},unshift:function(){const t=this[h],e=t.target,r=arguments.length,o=new Array(r);for(let e=0;e<r;e++)o[e]=w(arguments[e],e,t);const n=Reflect.apply(e.unshift,e,o);for(let t,s=0,r=e.length;s<r;s++)if(t=e[s],t&&"object"==typeof t){const e=t[h];e&&(e.ownKey=s)}const i=o.length,a=new Array(i);for(let t=0;t<i;t++)a[t]=new O(s,[t],e[t],void 0,this);return d(t,a),n},reverse:v,sort:g,fill:m,copyWithin:j,splice:function(){const t=this[h],e=t.target,n=arguments.length,i=new Array(n),a=e.length;for(let e=0;e<n;e++)i[e]=w(arguments[e],e,t);const c=0===n?0:i[0]<0?a+i[0]:i[0],l=n<2?a-c:i[1],p=Math.max(n-2,0),f=Reflect.apply(e.splice,e,i),u=e.length;let y,b,v,g;for(let t,s=0;s<u;s++)t=e[s],t&&"object"==typeof t&&(y=t[h],y&&(y.ownKey=s));for(b=0,v=f.length;b<v;b++)g=f[b],g&&"object"==typeof g&&(y=g[h],y&&(f[b]=y.detach()));const m=[];let j;for(j=0;j<l;j++)j<p?m.push(new O(r,[c+j],e[c+j],f[j],this)):m.push(new O(o,[c+j],void 0,f[j],this));for(;j<p;j++)m.push(new O(s,[c+j],e[c+j],void 0,this));return d(t,m),f}},M={reverse:v,sort:g,fill:m,copyWithin:j,set:function(t,e){const s=this[h],o=s.target,n=t.length,i=o.slice(0);e=e||0,o.set(t,e);const a=new Array(n);for(let t=e;t<n+e;t++)a[t-e]=new O(r,[t],o[t],i[t],this);d(s,a)}};class O{constructor(t,e,s,r,o){this.type=t,this.path=e,this.value=s,this.oldValue=r,this.object=o}}class _{constructor(t,e){const{target:s,parent:r,ownKey:o}=t;r&&void 0!==o?(this.parent=r,this.ownKey=o):(this.parent=null,this.ownKey=null);const n=e(s,this);this.observers=[],this.revocable=Proxy.revocable(n,this),this.proxy=this.revocable.proxy,this.target=n,this.options=this.processOptions(t.options),this.options.async&&(this.batches=[])}processOptions(t){if(t){if("object"!=typeof t)throw new Error(`Observable options if/when provided, MAY only be an object, got '${t}'`);const e=Object.keys(t).filter((t=>!(t in a)));if(e.length)throw new Error(`'${e.join(", ")}' is/are not a valid Observable option/s`);return Object.assign({},t)}return{}}detach(){return this.parent=null,this.target}set(t,e,o){let n=t[e];if(o!==n){const i=w(o,e,this);if(t[e]=i,n&&"object"==typeof n){const t=n[h];t&&(n=t.detach())}const a=void 0===n?[new O(s,[e],i,void 0,this.proxy)]:[new O(r,[e],i,n,this.proxy)];d(this,a)}return!0}deleteProperty(t,e){let s=t[e];if(delete t[e],s&&"object"==typeof s){const t=s[h];t&&(s=t.detach())}const r=[new O(o,[e],void 0,s,this.proxy)];return d(this,r),!0}}class E extends _{constructor(t){super(t,l)}}class A extends _{constructor(t){super(t,p)}get(t,e){return x[e]||t[e]}}class N extends _{constructor(t){super(t,f)}get(t,e){return M[e]||t[e]}}const K=Object.freeze({from:(t,e)=>{if(t&&"object"==typeof t){if(t[h])return t;if(Array.isArray(t))return new A({target:t,ownKey:null,parent:null,options:e}).proxy;if(ArrayBuffer.isView(t))return new N({target:t,ownKey:null,parent:null,options:e}).proxy;if(t instanceof Date)throw new Error(`${t} found to be one of a non-observable types`);return new E({target:t,ownKey:null,parent:null,options:e}).proxy}throw new Error("observable MAY ONLY be created from a non-null object")},isObservable:t=>!(!t||!t[h]),observe:(t,e,s)=>{if(!K.isObservable(t))throw new Error("invalid observable parameter");if("function"!=typeof e)throw new Error(`observer MUST be a function, got '${e}'`);const r=t[h].observers;r.some((t=>t[0]===e))?console.warn("observer may be bound to an observable only once; will NOT rebind"):r.push([e,c(s)])},unobserve:(t,...e)=>{if(!K.isObservable(t))throw new Error("invalid observable parameter");const s=t[h].observers;let r=s.length;if(r)if(e.length)for(;r;){e.indexOf(s[--r][0])>=0&&s.splice(r,1)}else s.splice(0)}});class S{constructor(){this.on=(t,e)=>(this.handlers[t]=this.handlers[t]||[],this.handlers[t].push(e),this),this.off=(t,e)=>{const s=this.handlers[t];if(s)for(let t=0;t<s.length;t++)s[t]===e&&s.splice(t,1);return this},this.callEmitFromMT=function(){this.func.apply(null,this.args?this.args:[])},this.emit=(t,e)=>{if(this.handlers[t])for(let s=0;s<this.handlers[t].length;s++)try{queueMicrotask(this.callEmitFromMT.bind({func:this.handlers[t][s],args:e}))}catch(t){console.log(t)}return this},this.clear=()=>{this.handlers={}},this.handlers={}}}class V{constructor(){this.viewModels={}}static getInstance(){return V.instance||(V.instance=new V),V.instance}getUsedNamespace(){return Object.keys(this.viewModels)}addNamespace(t,e){this.viewModels[t]=e}removeNamespace(t){delete this.viewModels[t]}getNameSapce(t){return this.viewModels[t]?this.viewModels[t]:void 0}}class T extends S{constructor(t){super(),Object.keys(t.property).forEach((e=>{this.on(e,(s=>{try{t.property[e].apply(t.state,[s])}catch(t){console.log(t)}}))}))}}class k extends S{constructor(t,e){super(),this.watch=t=>{const e=performance.now();if(t.forEach((t=>{var e;const s=t.path.filter((t=>"number"!=typeof t));if(null===(e=this._options)||void 0===e?void 0:e.deep){let e="";s.forEach((s=>{e+=s+".",this.emit(e.substring(0,e.length-1),[t.object])}))}else{const e=s.join(".");this.emit(e,[t.object])}})),"development"===process.env.NODE_ENV){const s=performance.now()-e;s>33.34&&console.warn(`[x-view-model] Slow state update detected (${s.toFixed(2)}ms)`,t)}},this._property=t,this._options=e,this._reference=0,this._observable=K.from(Object.assign({},this._property),{async:!0}),this._started=!1,this.services=new T(this),this.namespaces=V.getInstance()}get state(){return this._observable}get property(){return this._property}get reference(){return this._reference}get name(){return this._options&&this._options.name?this._options.name:"unnamed"}set reference(t){this._reference=t,this._reference>0?(this.name&&this.namespaces.addNamespace(this.name,this),this.start()):(this.name&&this.namespaces.removeNamespace(this.name),this.stop())}increaseReference(){this.reference++}decreaseReference(){this.reference--}start(){if(!this._started)return K.observe(this._observable,this.watch),console.log(this.name,"started"),this._started=!0,this}stop(){if(this._started)return K.unobserve(this._observable),this._observable=K.from(Object.assign({},this._property)),this._started=!1,this}pause(){if(this._started)return K.unobserve(this._observable),this}restart(){return K.unobserve(this._observable),this._observable=K.from(Object.assign({},this._property)),K.observe(this._observable,this.watch),console.log(this.name,"started"),this._started=!0,this}snapshot(){this.pause();const t=JSON.stringify(this._observable);return this.start(),t}rebase(t){const e="string"==typeof t?JSON.parse(t):t;return this._property=Object.assign(Object.assign({},this._property),e),this}restore(t){this.pause();const e="string"==typeof t?JSON.parse(t):t;return this._observable=K.from(Object.assign(Object.assign({},this._property),e)),this.start(),this}send(t,s,r=!1){return e(this,void 0,void 0,(function*(){if(r)try{return yield this.property[t].apply(this.state,[s])}catch(t){throw t}else this.services.emit(t,[s])}))}}const F=(s,r)=>{const o=((e,s)=>{const[r,o]=t.useState(0),n=t.useCallback((t=>{"development"===process.env.NODE_ENV&&console.debug("[x-view-model] State update","args: ",t),o((t=>t+1))}),[]);return t.useMemo((()=>{s.increaseReference(),Array.isArray(e)?e.forEach((t=>{s.on(t,n)})):s.on(e,n)}),[s]),t.useEffect((()=>()=>{s.decreaseReference(),Array.isArray(e)?e.forEach((t=>{s.off(t,n)})):s.off(e,n)}),[s]),s.state})(r,s.context);return[o,(t,r,o=!1)=>e(void 0,void 0,void 0,(function*(){if(o)try{return yield s.context.property[t].apply(s.context.state,[r])}catch(t){throw t}else s.context.services.emit(t,[r])})),s.ref]};exports.PropertyHandler=k,exports.registViewModel=(t,e,s)=>({context:new k(t,e),ref:s}),exports.useComputedViewModel=(e,s,r)=>{const[o,n,i]=F(e,r);return[t.useMemo((()=>s(o)),[o,s]),n,i]},exports.useMemoizedViewModel=(e,s)=>{const[r,o,n]=F(e,s);if(!s||0===s.length)return[r,o,n];return[t.useMemo((()=>{const t={};return s.forEach((e=>{const s=function(t,e){const s=e.split(".");let r=t;for(const t of s){if(null==r)return;r=r[t]}return r}(r,e);!function(t,e,s){const r=e.split(".");let o=t;for(let t=0;t<r.length-1;t++){const e=r[t];e in o||(o[e]={}),o=o[e]}o[r[r.length-1]]=s}(t,e,s)})),t}),[r,s]),o,n]},exports.useViewModel=F; //# sourceMappingURL=index.min.js.map