diff --git a/README.md b/README.md index fc2cf09..03db7ef 100644 --- a/README.md +++ b/README.md @@ -1,111 +1,35 @@ -This packages was originaly created by [codebykyle](https://github.com/codebykyle/calculated-field) But after an extensive refactor and updating a lot of VueJS code to latest Laravel Nova code i made this in to a new package. +This packages is created after the package from [codebykyle](https://github.com/codebykyle/calculated-field) But after an extensive refactor and updating a lot of VueJS code to the latest Laravel Nova code I made this in to a new package. -## New features --- BelongsTo Broadcaster field --- MorphTo Broadcaster field --- Currency Listener Field --- Hidden Listener Field --- Code has been completely updated to latest Nova (2021-03-18) +# New features -Below the old Documentation from [codebykyle](https://github.com/codebykyle) +[Release V2.3]
+-- Fixed issue where you can't edit a listener field
+-- Added Date Broadcaster field
+-- Added Date Listener field
+-- Added 'calculate' buttons to all visible Listener Fields
+-- Added ability to turn of calculation on update forms.
-## Installation +[changes up to V2.2]
+-- BelongsTo Broadcaster field
+-- MorphTo Broadcaster field
+-- Currency Listener Field
+-- Hidden Listener Field
+-- Code has been completely updated to latest Nova (2021-03-18)
-Install the package via composer: +Below pieces of the old Documentation from [codebykyle](https://github.com/codebykyle) +I'm not really good at writing documentation. So please feel free to creat a PR for it. -`composer require gldrenthe89/nove-calculated-field` +# Installation +Install the package via composer: +`composer require gldrenthe89/nove-calculated-field` -# Original how-to from [codebykyle](https://github.com/codebykyle) +## Example -### Example -For example: -#### As a number ![Calculated Number Field](https://cbk-website.s3.amazonaws.com/calculated-field/number_calc_field.gif "Calculated Number Field") -#### As a string: -![Calculated String Field](https://cbk-website.s3.amazonaws.com/calculated-field/string_calc_field.gif "Calculated String Field") - -##### Default -The Listener field will by default sum all numbers passed to it - -### Usage -```php -calculateWith(function (Collection $values) { - $subtotal = $values->get('sub_total'); - $tax = $values->get('tax'); - return $subtotal + $tax; - }), - ]; - } -} -``` - - -#### String Fields -```php - -setType('string'), - - BroadcasterField::make('Last Name', 'last_name') - ->setType('string'), - - ListenerField::make('Full Name', 'full_name') - ->calculateWith(function (Collection $values) { - return $values->values()->join(' '); - }), - ]; - } -} -``` - - -#### Multiple Calculated Fields - ```php broadcastTo('total'), + ->broadcastTo('total'), // can either be a String or an Array BroadcasterField::make('Tax', 'tax') - ->broadcastTo('total'), + ->broadcastTo('total'), // can either be a String or an Array ListenerField::make('Total Field', 'total_field') - ->listensTo('total') + ->listensTo('total') // can either be a String or an Array ->calculateWith(function (Collection $values) { $subtotal = $values->get('sub_total'); $tax = $values->get('tax'); @@ -132,13 +56,14 @@ class MyResource extends Resource BroadcasterField::make('Senior Discount', 'senior_discount') - ->broadcastTo('discount'), + ->broadcastTo('discount'), // can either be a String or an Array BroadcasterField::make('Coupon Discount', 'coupon_amount') - ->broadcastTo('discount'), + ->broadcastTo('discount'), // can either be a String or an Array ListenerField::make('Total Discount', 'total_discount') - ->listensTo('discount') + ->listensTo('discount') // can either be a String or an Array + ->disableCalculationOnUpdate() // Only when to disable on Update forms ->calculateWith(function (Collection $values) { $seniorDiscount = $values->get('senior_discount'); $couponAmount = $values->get('coupon_amount'); diff --git a/dist/js/field.js b/dist/js/field.js index 4446727..fab759d 100644 --- a/dist/js/field.js +++ b/dist/js/field.js @@ -1 +1 @@ -!function(t){var e={};function n(r){if(e[r])return e[r].exports;var i=e[r]={i:r,l:!1,exports:{}};return t[r].call(i.exports,i,i.exports,n),i.l=!0,i.exports}n.m=t,n.c=e,n.d=function(t,e,r){n.o(t,e)||Object.defineProperty(t,e,{configurable:!1,enumerable:!0,get:r})},n.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return n.d(e,"a",e),e},n.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},n.p="",n(n.s=3)}([function(t,e){t.exports=function(t,e,n,r,i,o){var u,a=t=t||{},s=typeof t.default;"object"!==s&&"function"!==s||(u=t,a=t.default);var c,f="function"==typeof a?a.options:a;if(e&&(f.render=e.render,f.staticRenderFns=e.staticRenderFns,f._compiled=!0),n&&(f.functional=!0),i&&(f._scopeId=i),o?(c=function(t){(t=t||this.$vnode&&this.$vnode.ssrContext||this.parent&&this.parent.$vnode&&this.parent.$vnode.ssrContext)||"undefined"==typeof __VUE_SSR_CONTEXT__||(t=__VUE_SSR_CONTEXT__),r&&r.call(this,t),t&&t._registeredComponents&&t._registeredComponents.add(o)},f._ssrRegister=c):r&&(c=r),c){var l=f.functional,h=l?f.render:f.beforeCreate;l?(f._injectStyles=c,f.render=function(t,e){return c.call(e),h(t,e)}):f.beforeCreate=h?[].concat(h,c):[c]}return{esModule:u,exports:a,options:f}}},function(t,e,n){var r;r=function(){return function(t){var e={};function n(r){if(e[r])return e[r].exports;var i=e[r]={i:r,l:!1,exports:{}};return t[r].call(i.exports,i,i.exports,n),i.l=!0,i.exports}return n.m=t,n.c=e,n.i=function(t){return t},n.d=function(t,e,r){n.o(t,e)||Object.defineProperty(t,e,{configurable:!1,enumerable:!0,get:r})},n.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return n.d(e,"a",e),e},n.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},n.p="",n(n.s=40)}([function(t,e,n){"use strict";var r=n(39),i=n(152),o=Object.prototype.toString;function u(t){return"[object Array]"===o.call(t)}function a(t){return null!==t&&"object"==typeof t}function s(t){return"[object Function]"===o.call(t)}function c(t,e){if(null!==t&&void 0!==t)if("object"!=typeof t&&(t=[t]),u(t))for(var n=0,r=t.length;n=200&&t<300}};s.headers={common:{Accept:"application/json, text/plain, */*"}},r.forEach(["delete","get","head"],function(t){s.headers[t]={}}),r.forEach(["post","put","patch"],function(t){s.headers[t]=r.merge(o)}),t.exports=s}).call(e,n(70))},function(t,e,n){"use strict";e.__esModule=!0;var r,i=n(109),o=(r=i)&&r.__esModule?r:{default:r};e.default=function(t,e,n){return e in t?(0,o.default)(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}},function(t,e){t.exports=function(t){if(void 0==t)throw TypeError("Can't call method on "+t);return t}},function(t,e,n){var r=n(9),i=n(1).document,o=r(i)&&r(i.createElement);t.exports=function(t){return o?i.createElement(t):{}}},function(t,e){t.exports=function(t){try{return!!t()}catch(t){return!0}}},function(t,e){t.exports=!0},function(t,e,n){"use strict";var r=n(12);t.exports.f=function(t){return new function(t){var e,n;this.promise=new t(function(t,r){if(void 0!==e||void 0!==n)throw TypeError("Bad Promise constructor");e=t,n=r}),this.resolve=r(e),this.reject=r(n)}(t)}},function(t,e,n){var r=n(11).f,i=n(15),o=n(2)("toStringTag");t.exports=function(t,e,n){t&&!i(t=n?t:t.prototype,o)&&r(t,o,{configurable:!0,value:e})}},function(t,e,n){var r=n(53)("keys"),i=n(58);t.exports=function(t){return r[t]||(r[t]=i(t))}},function(t,e){var n=Math.ceil,r=Math.floor;t.exports=function(t){return isNaN(t=+t)?0:(t>0?r:n)(t)}},function(t,e,n){var r=n(47),i=n(21);t.exports=function(t){return r(i(t))}},function(t,e,n){var r=n(17).Symbol;t.exports=r},function(t,e){t.exports=function(t){return t.webpackPolyfill||(t.deprecate=function(){},t.paths=[],t.children||(t.children=[]),Object.defineProperty(t,"loaded",{enumerable:!0,get:function(){return t.l}}),Object.defineProperty(t,"id",{enumerable:!0,get:function(){return t.i}}),t.webpackPolyfill=1),t}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.mapProps=void 0;var r,i=n(193),o=(r=i)&&r.__esModule?r:{default:r};var u={showHelpText:{type:Boolean,default:!1},shownViaNewRelationModal:{type:Boolean,default:!1},resourceId:{type:[Number,String]},resourceName:{type:String},field:{type:Object,required:!0},viaResource:{type:String,required:!1},viaResourceId:{type:[String,Number],required:!1},viaRelationship:{type:String,required:!1},shouldOverrideMeta:{type:Boolean,default:!1}};e.mapProps=function(t){return o.default.pick(u,t)}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=["1/2","1/3","2/3","1/4","3/4","1/5","2/5","3/5","4/5","1/6","5/6"]},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n(150);Object.defineProperty(e,"default",{enumerable:!0,get:function(){return o(r).default}}),Object.defineProperty(e,"Form",{enumerable:!0,get:function(){return o(r).default}});var i=n(59);function o(t){return t&&t.__esModule?t:{default:t}}Object.defineProperty(e,"Errors",{enumerable:!0,get:function(){return o(i).default}})},function(t,e,n){"use strict";(function(e){var r=n(0),i=n(97),o=n(100),u=n(106),a=n(104),s=n(38),c="undefined"!=typeof window&&window.btoa&&window.btoa.bind(window)||n(99);t.exports=function(t){return new Promise(function(f,l){var h=t.data,p=t.headers;r.isFormData(h)&&delete p["Content-Type"];var d=new XMLHttpRequest,v="onreadystatechange",g=!1;if("test"===e.env.NODE_ENV||"undefined"==typeof window||!window.XDomainRequest||"withCredentials"in d||a(t.url)||(d=new window.XDomainRequest,v="onload",g=!0,d.onprogress=function(){},d.ontimeout=function(){}),t.auth){var _=t.auth.username||"",y=t.auth.password||"";p.Authorization="Basic "+c(_+":"+y)}if(d.open(t.method.toUpperCase(),o(t.url,t.params,t.paramsSerializer),!0),d.timeout=t.timeout,d[v]=function(){if(d&&(4===d.readyState||g)&&(0!==d.status||d.responseURL&&0===d.responseURL.indexOf("file:"))){var e="getAllResponseHeaders"in d?u(d.getAllResponseHeaders()):null,n={data:t.responseType&&"text"!==t.responseType?d.response:d.responseText,status:1223===d.status?204:d.status,statusText:1223===d.status?"No Content":d.statusText,headers:e,config:t,request:d};i(f,l,n),d=null}},d.onerror=function(){l(s("Network Error",t,null,d)),d=null},d.ontimeout=function(){l(s("timeout of "+t.timeout+"ms exceeded",t,"ECONNABORTED",d)),d=null},r.isStandardBrowserEnv()){var m=n(102),b=(t.withCredentials||a(t.url))&&t.xsrfCookieName?m.read(t.xsrfCookieName):void 0;b&&(p[t.xsrfHeaderName]=b)}if("setRequestHeader"in d&&r.forEach(p,function(t,e){void 0===h&&"content-type"===e.toLowerCase()?delete p[e]:d.setRequestHeader(e,t)}),t.withCredentials&&(d.withCredentials=!0),t.responseType)try{d.responseType=t.responseType}catch(e){if("json"!==t.responseType)throw e}"function"==typeof t.onDownloadProgress&&d.addEventListener("progress",t.onDownloadProgress),"function"==typeof t.onUploadProgress&&d.upload&&d.upload.addEventListener("progress",t.onUploadProgress),t.cancelToken&&t.cancelToken.promise.then(function(t){d&&(d.abort(),l(t),d=null)}),void 0===h&&(h=null),d.send(h)})}}).call(e,n(70))},function(t,e,n){"use strict";function r(t){this.message=t}r.prototype.toString=function(){return"Cancel"+(this.message?": "+this.message:"")},r.prototype.__CANCEL__=!0,t.exports=r},function(t,e,n){"use strict";t.exports=function(t){return!(!t||!t.__CANCEL__)}},function(t,e,n){"use strict";var r=n(96);t.exports=function(t,e,n,i,o){var u=new Error(t);return r(u,e,n,i,o)}},function(t,e,n){"use strict";t.exports=function(t,e){return function(){for(var n=new Array(arguments.length),r=0;rn;)e.push(arguments[n++]);return _[++g]=function(){a("function"==typeof t?t:Function(t),e)},r(g),g},p=function(t){delete _[t]},"process"==n(13)(l)?r=function(t){l.nextTick(u(y,t,1))}:v&&v.now?r=function(t){v.now(u(y,t,1))}:d?(o=(i=new d).port2,i.port1.onmessage=m,r=u(o.postMessage,o,1)):f.addEventListener&&"function"==typeof postMessage&&!f.importScripts?(r=function(t){f.postMessage(t+"","*")},f.addEventListener("message",m,!1)):r="onreadystatechange"in c("script")?function(t){s.appendChild(c("script")).onreadystatechange=function(){s.removeChild(this),y.call(t)}}:function(t){setTimeout(u(y,t,1),0)}),t.exports={set:h,clear:p}},function(t,e,n){var r=n(28),i=Math.min;t.exports=function(t){return t>0?i(r(t),9007199254740991):0}},function(t,e,n){var r=n(21);t.exports=function(t){return Object(r(t))}},function(t,e){var n=0,r=Math.random();t.exports=function(t){return"Symbol(".concat(void 0===t?"":t,")_",(++n+r).toString(36))}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=function(){function t(t,e){for(var n=0;n0&&void 0!==arguments[0]?arguments[0]:{};!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.record(e)}return r(t,[{key:"all",value:function(){return this.errors}},{key:"has",value:function(t){var e=this.errors.hasOwnProperty(t);e||(e=Object.keys(this.errors).filter(function(e){return e.startsWith(t+".")||e.startsWith(t+"[")}).length>0);return e}},{key:"first",value:function(t){return this.get(t)[0]}},{key:"get",value:function(t){return this.errors[t]||[]}},{key:"any",value:function(){return Object.keys(this.errors).length>0}},{key:"record",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.errors=t}},{key:"clear",value:function(t){if(t){var e=Object.assign({},this.errors);Object.keys(e).filter(function(e){return e===t||e.startsWith(t+".")||e.startsWith(t+"[")}).forEach(function(t){return delete e[t]}),this.errors=e}else this.errors={}}}]),t}();e.default=i},function(t,e,n){(function(e){var n="object"==typeof e&&e&&e.Object===Object&&e;t.exports=n}).call(e,n(71))},function(t,e){var n=RegExp("[\\u200d\\ud800-\\udfff\\u0300-\\u036f\\ufe20-\\ufe2f\\u20d0-\\u20ff\\ufe0e\\ufe0f]");t.exports=function(t){return n.test(t)}},function(t,e){var n=9007199254740991,r=/^(?:0|[1-9]\d*)$/;t.exports=function(t,e){var i=typeof t;return!!(e=null==e?n:e)&&("number"==i||"symbol"!=i&&r.test(t))&&t>-1&&t%1==0&&t-1&&t%1==0&&t<=n}},function(t,e,n){var r=n(16),i=n(18),o="[object Symbol]";t.exports=function(t){return"symbol"==typeof t||i(t)&&r(t)==o}},function(t,e){var n,r,i=t.exports={};function o(){throw new Error("setTimeout has not been defined")}function u(){throw new Error("clearTimeout has not been defined")}function a(t){if(n===setTimeout)return setTimeout(t,0);if((n===o||!n)&&setTimeout)return n=setTimeout,setTimeout(t,0);try{return n(t,0)}catch(e){try{return n.call(null,t,0)}catch(e){return n.call(this,t,0)}}}!function(){try{n="function"==typeof setTimeout?setTimeout:o}catch(t){n=o}try{r="function"==typeof clearTimeout?clearTimeout:u}catch(t){r=u}}();var s,c=[],f=!1,l=-1;function h(){f&&s&&(f=!1,s.length?c=s.concat(c):l=-1,c.length&&p())}function p(){if(!f){var t=a(h);f=!0;for(var e=c.length;e;){for(s=c,c=[];++l1)for(var n=1;n1&&void 0!==arguments[1]?arguments[1]:null;return this.viaManyToMany?this.detachResources(t):Nova.request({url:"/nova-api/"+this.resourceName,method:"delete",params:(0,o.default)({},this.queryString,{resources:u(t)})}).then(n||function(){e.deleteModalOpen=!1,e.getResources()})},deleteSelectedResources:function(){this.deleteResources(this.selectedResources)},deleteAllMatchingResources:function(){var t=this;return this.viaManyToMany?this.detachAllMatchingResources():Nova.request({url:this.deleteAllMatchingResourcesEndpoint,method:"delete",params:(0,o.default)({},this.queryString,{resources:"all"})}).then(function(){t.deleteModalOpen=!1,t.getResources()})},detachResources:function(t){var e=this;return Nova.request({url:"/nova-api/"+this.resourceName+"/detach",method:"delete",params:(0,o.default)({},this.queryString,{resources:u(t)})}).then(function(){e.deleteModalOpen=!1,e.getResources()})},detachAllMatchingResources:function(){var t=this;return Nova.request({url:"/nova-api/"+this.resourceName+"/detach",method:"delete",params:(0,o.default)({},this.queryString,{resources:"all"})}).then(function(){t.deleteModalOpen=!1,t.getResources()})},forceDeleteResources:function(t){var e=this,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null;return Nova.request({url:"/nova-api/"+this.resourceName+"/force",method:"delete",params:(0,o.default)({},this.queryString,{resources:u(t)})}).then(n||function(){e.deleteModalOpen=!1,e.getResources()})},forceDeleteSelectedResources:function(){this.forceDeleteResources(this.selectedResources)},forceDeleteAllMatchingResources:function(){var t=this;return Nova.request({url:this.forceDeleteSelectedResourcesEndpoint,method:"delete",params:(0,o.default)({},this.queryString,{resources:"all"})}).then(function(){t.deleteModalOpen=!1,t.getResources()})},restoreResources:function(t){var e=this,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null;return Nova.request({url:"/nova-api/"+this.resourceName+"/restore",method:"put",params:(0,o.default)({},this.queryString,{resources:u(t)})}).then(n||function(){e.restoreModalOpen=!1,e.getResources()})},restoreSelectedResources:function(){this.restoreResources(this.selectedResources)},restoreAllMatchingResources:function(){var t=this;return Nova.request({url:this.restoreAllMatchingResourcesEndpoint,method:"put",params:(0,o.default)({},this.queryString,{resources:"all"})}).then(function(){t.restoreModalOpen=!1,t.getResources()})}},computed:{deleteAllMatchingResourcesEndpoint:function(){return this.lens?"/nova-api/"+this.resourceName+"/lens/"+this.lens:"/nova-api/"+this.resourceName},forceDeleteSelectedResourcesEndpoint:function(){return this.lens?"/nova-api/"+this.resourceName+"/lens/"+this.lens+"/force":"/nova-api/"+this.resourceName+"/force"},restoreAllMatchingResourcesEndpoint:function(){return this.lens?"/nova-api/"+this.resourceName+"/lens/"+this.lens+"/restore":"/nova-api/"+this.resourceName+"/restore"},queryString:function(){return{search:this.currentSearch,filters:this.encodedFilters,trashed:this.currentTrashed,viaResource:this.viaResource,viaResourceId:this.viaResourceId,viaRelationship:this.viaRelationship}}}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=u(n(43)),i=u(n(20)),o=u(n(42));function u(t){return t&&t.__esModule?t:{default:t}}e.default={methods:{clearSelectedFilters:function(){var t=(0,o.default)(r.default.mark(function t(e){var n;return r.default.wrap(function(t){for(;;)switch(t.prev=t.next){case 0:if(!e){t.next=5;break}return t.next=3,this.$store.dispatch(this.resourceName+"/resetFilterState",{resourceName:this.resourceName,lens:e});case 3:t.next=7;break;case 5:return t.next=7,this.$store.dispatch(this.resourceName+"/resetFilterState",{resourceName:this.resourceName});case 7:this.updateQueryString((n={},(0,i.default)(n,this.pageParameter,1),(0,i.default)(n,this.filterParameter,""),n));case 8:case"end":return t.stop()}},t,this)}));return function(e){return t.apply(this,arguments)}}(),filterChanged:function(){var t;this.updateQueryString((t={},(0,i.default)(t,this.pageParameter,1),(0,i.default)(t,this.filterParameter,this.$store.getters[this.resourceName+"/currentEncodedFilters"]),t))},initializeFilters:function(){var t=(0,o.default)(r.default.mark(function t(e){return r.default.wrap(function(t){for(;;)switch(t.prev=t.next){case 0:return this.$store.commit(this.resourceName+"/clearFilters"),t.next=3,this.$store.dispatch(this.resourceName+"/fetchFilters",{resourceName:this.resourceName,viaResource:this.viaResource,viaResourceId:this.viaResourceId,viaRelationship:this.viaRelationship,lens:e});case 3:return t.next=5,this.initializeState(e);case 5:case"end":return t.stop()}},t,this)}));return function(e){return t.apply(this,arguments)}}(),initializeState:function(){var t=(0,o.default)(r.default.mark(function t(e){return r.default.wrap(function(t){for(;;)switch(t.prev=t.next){case 0:if(!this.initialEncodedFilters){t.next=5;break}return t.next=3,this.$store.dispatch(this.resourceName+"/initializeCurrentFilterValuesFromQueryString",this.initialEncodedFilters);case 3:t.next=7;break;case 5:return t.next=7,this.$store.dispatch(this.resourceName+"/resetFilterState",{resourceName:this.resourceName,lens:e});case 7:case"end":return t.stop()}},t,this)}));return function(e){return t.apply(this,arguments)}}()},computed:{filterParameter:function(){return this.resourceName+"_filter"}}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n(32);e.default={props:(0,r.mapProps)(["shownViaNewRelationModal","field","viaResource","viaResourceId","viaRelationship","resourceName","showHelpText"]),data:function(){return{value:""}},mounted:function(){var t=this;this.setInitialValue(),this.field.fill=this.fill,Nova.$on(this.field.attribute+"-value",function(e){t.value=e})},destroyed:function(){Nova.$off(this.field.attribute+"-value")},methods:{setInitialValue:function(){this.value=void 0!==this.field.value&&null!==this.field.value?this.field.value:""},fill:function(t){t.append(this.field.attribute,String(this.value))},handleChange:function(t){this.value=t.target.value,this.field&&Nova.$emit(this.field.attribute+"-change",this.value)}},computed:{isReadonly:function(){return this.field.readonly||_.get(this.field,"extraAttributes.readonly")}}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n(34);e.default={props:{errors:{default:function(){return new r.Errors}}},data:function(){return{errorClass:"border-danger"}},computed:{errorClasses:function(){return this.hasError?[this.errorClass]:[]},fieldAttribute:function(){return this.field.attribute},validationKey:function(){return this.field.validationKey},hasError:function(){return this.errors.has(this.validationKey)},firstError:function(){if(this.hasError)return this.errors.first(this.validationKey)}}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=u(n(43)),i=u(n(42)),o=u(n(33));function u(t){return t&&t.__esModule?t:{default:t}}e.default={props:{loadCards:{type:Boolean,default:!0}},data:function(){return{cards:[]}},created:function(){this.fetchCards()},watch:{cardsEndpoint:function(){this.fetchCards()}},methods:{fetchCards:function(){var t=(0,i.default)(r.default.mark(function t(){var e,n;return r.default.wrap(function(t){for(;;)switch(t.prev=t.next){case 0:if(!this.loadCards){t.next=6;break}return t.next=3,Nova.request().get(this.cardsEndpoint,{params:this.extraCardParams});case 3:e=t.sent,n=e.data,this.cards=n;case 6:case"end":return t.stop()}},t,this)}));return function(){return t.apply(this,arguments)}}()},computed:{shouldShowCards:function(){return this.cards.length>0},smallCards:function(){return _.filter(this.cards,function(t){return-1!==o.default.indexOf(t.width)})},largeCards:function(){return _.filter(this.cards,function(t){return"full"==t.width})},extraCardParams:function(){return null}}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default={methods:{toAppTimezone:function(t){return t?moment.tz(t,this.userTimezone).clone().tz(Nova.config.timezone).format("YYYY-MM-DD HH:mm:ss"):t},fromAppTimezone:function(t){return t?moment.tz(t,Nova.config.timezone).clone().tz(this.userTimezone).format("YYYY-MM-DD HH:mm:ss"):t},localizeDateTimeField:function(t){if(!t.value)return t.value;var e=moment.tz(t.value,Nova.config.timezone).clone().tz(this.userTimezone);return t.format?e.format(t.format):this.usesTwelveHourTime?e.format("YYYY-MM-DD h:mm:ss A"):e.format("YYYY-MM-DD HH:mm:ss")},localizeDateField:function(t){if(!t.value)return t.value;var e=moment.tz(t.value,Nova.config.timezone).clone().tz(this.userTimezone);return t.format?e.format(t.format):e.format("YYYY-MM-DD")}},computed:{userTimezone:function(){return Nova.config.userTimezone?Nova.config.userTimezone:moment.tz.guess()},usesTwelveHourTime:function(){return _.endsWith((new Date).toLocaleString(),"AM")||_.endsWith((new Date).toLocaleString(),"PM")}}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r,i=n(188),o=(r=i)&&r.__esModule?r:{default:r};e.default={methods:{updateQueryString:function(t){this.$router.push({query:(0,o.default)(t,this.$route.query)}).catch(function(t){if("NavigationDuplicated"!=t.name)throw t})}}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default={computed:{resourceInformation:function(){var t=this;return _.find(Nova.config.resources,function(e){return e.uriKey==t.resourceName})},viaResourceInformation:function(){var t=this;if(this.viaResource)return _.find(Nova.config.resources,function(e){return e.uriKey==t.viaResource})},authorizedToCreate:function(){return this.resourceInformation.authorizedToCreate}}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r,i=n(20),o=(r=i)&&r.__esModule?r:{default:r};e.default={methods:{selectPreviousPage:function(){this.updateQueryString((0,o.default)({},this.pageParameter,this.currentPage-1))},selectNextPage:function(){this.updateQueryString((0,o.default)({},this.pageParameter,this.currentPage+1))}},computed:{currentPage:function(){return parseInt(this.$route.query[this.pageParameter]||1)}}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r,i=n(20),o=(r=i)&&r.__esModule?r:{default:r};e.default={data:function(){return{perPage:25}},methods:{initializePerPageFromQueryString:function(){this.perPage=this.currentPerPage},perPageChanged:function(){this.updateQueryString((0,o.default)({},this.perPageParameter,this.perPage))}},computed:{currentPerPage:function(){return this.$route.query[this.perPageParameter]||25}}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r,i=n(187),o=(r=i)&&r.__esModule?r:{default:r};e.default={data:function(){return{search:"",selectedResource:"",availableResources:[]}},methods:{selectResource:function(t){this.selectedResource=t,this.field&&Nova.$emit(this.field.attribute+"-change",this.selectedResource.value)},handleSearchCleared:function(){this.availableResources=[]},clearSelection:function(){this.selectedResource="",this.availableResources=[],this.field&&Nova.$emit(this.field.attribute+"-change",null)},performSearch:function(t){var e=this;this.search=t;var n=t.trim();""!=n&&this.debouncer(function(){e.getAvailableResources(n)},500)},debouncer:(0,o.default)(function(t){return t()},500)}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default={beforeRouteLeave:function(t,e,n){this.canLeave?n():window.confirm(this.__("Do you really want to leave? You have unsaved changes."))?n():n(!1)},data:function(){return{canLeave:!0}},methods:{updateFormStatus:function(){this.canLeave=!1}}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default={data:function(){return{withTrashed:!1}},methods:{toggleWithTrashed:function(){this.withTrashed=!this.withTrashed},enableWithTrashed:function(){this.withTrashed=!0},disableWithTrashed:function(){this.withTrashed=!1}}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=function(t){return(0,o.default)(t)};var r,i=n(198),o=(r=i)&&r.__esModule?r:{default:r}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r,i=n(41),o=(r=i)&&r.__esModule?r:{default:r};e.default=function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:100;return o.default.all([t,new o.default(function(t){setTimeout(function(){return t()},e)})]).then(function(t){return t[0]})}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=function(t,e){if(null==t.match(/^(.*)[A-Za-zÀ-ÖØ-öø-ÿ]$/))return t;if(t>1||0==t)return r.Inflector.pluralize(e);return r.Inflector.singularize(e)};var r=n(40)},function(t,e,n){"use strict";var r={uncountableWords:["equipment","information","rice","money","species","series","fish","sheep","moose","deer","news"],pluralRules:[[new RegExp("(m)an$","gi"),"$1en"],[new RegExp("(pe)rson$","gi"),"$1ople"],[new RegExp("(child)$","gi"),"$1ren"],[new RegExp("^(ox)$","gi"),"$1en"],[new RegExp("(ax|test)is$","gi"),"$1es"],[new RegExp("(octop|vir)us$","gi"),"$1i"],[new RegExp("(alias|status)$","gi"),"$1es"],[new RegExp("(bu)s$","gi"),"$1ses"],[new RegExp("(buffal|tomat|potat)o$","gi"),"$1oes"],[new RegExp("([ti])um$","gi"),"$1a"],[new RegExp("sis$","gi"),"ses"],[new RegExp("(?:([^f])fe|([lr])f)$","gi"),"$1$2ves"],[new RegExp("(hive)$","gi"),"$1s"],[new RegExp("([^aeiouy]|qu)y$","gi"),"$1ies"],[new RegExp("(x|ch|ss|sh)$","gi"),"$1es"],[new RegExp("(matr|vert|ind)ix|ex$","gi"),"$1ices"],[new RegExp("([m|l])ouse$","gi"),"$1ice"],[new RegExp("(quiz)$","gi"),"$1zes"],[new RegExp("s$","gi"),"s"],[new RegExp("$","gi"),"s"]],singularRules:[[new RegExp("(m)en$","gi"),"$1an"],[new RegExp("(pe)ople$","gi"),"$1rson"],[new RegExp("(child)ren$","gi"),"$1"],[new RegExp("([ti])a$","gi"),"$1um"],[new RegExp("((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)ses$","gi"),"$1$2sis"],[new RegExp("(hive)s$","gi"),"$1"],[new RegExp("(tive)s$","gi"),"$1"],[new RegExp("(curve)s$","gi"),"$1"],[new RegExp("([lr])ves$","gi"),"$1f"],[new RegExp("([^fo])ves$","gi"),"$1fe"],[new RegExp("([^aeiouy]|qu)ies$","gi"),"$1y"],[new RegExp("(s)eries$","gi"),"$1eries"],[new RegExp("(m)ovies$","gi"),"$1ovie"],[new RegExp("(x|ch|ss|sh)es$","gi"),"$1"],[new RegExp("([m|l])ice$","gi"),"$1ouse"],[new RegExp("(bus)es$","gi"),"$1"],[new RegExp("(o)es$","gi"),"$1"],[new RegExp("(shoe)s$","gi"),"$1"],[new RegExp("(cris|ax|test)es$","gi"),"$1is"],[new RegExp("(octop|vir)i$","gi"),"$1us"],[new RegExp("(alias|status)es$","gi"),"$1"],[new RegExp("^(ox)en","gi"),"$1"],[new RegExp("(vert|ind)ices$","gi"),"$1ex"],[new RegExp("(matr)ices$","gi"),"$1ix"],[new RegExp("(quiz)zes$","gi"),"$1"],[new RegExp("s$","gi"),""]],nonTitlecasedWords:["and","or","nor","a","an","the","so","but","to","of","at","by","from","into","on","onto","off","out","in","over","with","for"],idSuffix:new RegExp("(_ids|_id)$","g"),underbar:new RegExp("_","g"),spaceOrUnderbar:new RegExp("[ _]","g"),uppercase:new RegExp("([A-Z])","g"),underbarPrefix:new RegExp("^_"),applyRules:function(t,e,n,r){if(r)t=r;else if(!(n.indexOf(t.toLowerCase())>-1))for(var i=0;i>8-a%1*8)){if((n=o.charCodeAt(a+=.75))>255)throw new i;e=e<<8|n}return u}},function(t,e,n){"use strict";var r=n(0);function i(t){return encodeURIComponent(t).replace(/%40/gi,"@").replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}t.exports=function(t,e,n){if(!e)return t;var o;if(n)o=n(e);else if(r.isURLSearchParams(e))o=e.toString();else{var u=[];r.forEach(e,function(t,e){null!==t&&void 0!==t&&(r.isArray(t)?e+="[]":t=[t],r.forEach(t,function(t){r.isDate(t)?t=t.toISOString():r.isObject(t)&&(t=JSON.stringify(t)),u.push(i(e)+"="+i(t))}))}),o=u.join("&")}return o&&(t+=(-1===t.indexOf("?")?"?":"&")+o),t}},function(t,e,n){"use strict";t.exports=function(t,e){return e?t.replace(/\/+$/,"")+"/"+e.replace(/^\/+/,""):t}},function(t,e,n){"use strict";var r=n(0);t.exports=r.isStandardBrowserEnv()?{write:function(t,e,n,i,o,u){var a=[];a.push(t+"="+encodeURIComponent(e)),r.isNumber(n)&&a.push("expires="+new Date(n).toGMTString()),r.isString(i)&&a.push("path="+i),r.isString(o)&&a.push("domain="+o),!0===u&&a.push("secure"),document.cookie=a.join("; ")},read:function(t){var e=document.cookie.match(new RegExp("(^|;\\s*)("+t+")=([^;]*)"));return e?decodeURIComponent(e[3]):null},remove:function(t){this.write(t,"",Date.now()-864e5)}}:{write:function(){},read:function(){return null},remove:function(){}}},function(t,e,n){"use strict";t.exports=function(t){return/^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(t)}},function(t,e,n){"use strict";var r=n(0);t.exports=r.isStandardBrowserEnv()?function(){var t,e=/(msie|trident)/i.test(navigator.userAgent),n=document.createElement("a");function i(t){var r=t;return e&&(n.setAttribute("href",r),r=n.href),n.setAttribute("href",r),{href:n.href,protocol:n.protocol?n.protocol.replace(/:$/,""):"",host:n.host,search:n.search?n.search.replace(/^\?/,""):"",hash:n.hash?n.hash.replace(/^#/,""):"",hostname:n.hostname,port:n.port,pathname:"/"===n.pathname.charAt(0)?n.pathname:"/"+n.pathname}}return t=i(window.location.href),function(e){var n=r.isString(e)?i(e):e;return n.protocol===t.protocol&&n.host===t.host}}():function(){return!0}},function(t,e,n){"use strict";var r=n(0);t.exports=function(t,e){r.forEach(t,function(n,r){r!==e&&r.toUpperCase()===e.toUpperCase()&&(t[e]=n,delete t[r])})}},function(t,e,n){"use strict";var r=n(0),i=["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"];t.exports=function(t){var e,n,o,u={};return t?(r.forEach(t.split("\n"),function(t){if(o=t.indexOf(":"),e=r.trim(t.substr(0,o)).toLowerCase(),n=r.trim(t.substr(o+1)),e){if(u[e]&&i.indexOf(e)>=0)return;u[e]="set-cookie"===e?(u[e]?u[e]:[]).concat([n]):u[e]?u[e]+", "+n:n}}),u):u}},function(t,e,n){"use strict";t.exports=function(t){return function(e){return t.apply(null,e)}}},function(t,e,n){t.exports={default:n(111),__esModule:!0}},function(t,e,n){t.exports={default:n(112),__esModule:!0}},function(t,e,n){"use strict";e.__esModule=!0;var r,i=n(108),o=(r=i)&&r.__esModule?r:{default:r};e.default=o.default||function(t){for(var e=1;ef;)if((a=s[f++])!=a)return!0}else for(;c>f;f++)if((t||f in s)&&s[f]===n)return t||f||0;return!t&&-1}}},function(t,e,n){var r=n(14),i=n(121),o=n(120),u=n(4),a=n(56),s=n(140),c={},f={};(e=t.exports=function(t,e,n,l,h){var p,d,v,g,_=h?function(){return t}:s(t),y=r(n,l,e?2:1),m=0;if("function"!=typeof _)throw TypeError(t+" is not iterable!");if(o(_)){for(p=a(t.length);p>m;m++)if((g=e?y(u(d=t[m])[0],d[1]):y(t[m]))===c||g===f)return g}else for(v=_.call(t);!(d=v.next()).done;)if((g=i(v,y,d.value,e))===c||g===f)return g}).BREAK=c,e.RETURN=f},function(t,e,n){t.exports=!n(5)&&!n(23)(function(){return 7!=Object.defineProperty(n(22)("div"),"a",{get:function(){return 7}}).a})},function(t,e){t.exports=function(t,e,n){var r=void 0===n;switch(e.length){case 0:return r?t():t.call(n);case 1:return r?t(e[0]):t.call(n,e[0]);case 2:return r?t(e[0],e[1]):t.call(n,e[0],e[1]);case 3:return r?t(e[0],e[1],e[2]):t.call(n,e[0],e[1],e[2]);case 4:return r?t(e[0],e[1],e[2],e[3]):t.call(n,e[0],e[1],e[2],e[3])}return t.apply(n,e)}},function(t,e,n){var r=n(10),i=n(2)("iterator"),o=Array.prototype;t.exports=function(t){return void 0!==t&&(r.Array===t||o[i]===t)}},function(t,e,n){var r=n(4);t.exports=function(t,e,n,i){try{return i?e(r(n)[0],n[1]):e(n)}catch(e){var o=t.return;throw void 0!==o&&r(o.call(t)),e}}},function(t,e,n){"use strict";var r=n(127),i=n(52),o=n(26),u={};n(7)(u,n(2)("iterator"),function(){return this}),t.exports=function(t,e,n){t.prototype=r(u,{next:i(1,n)}),o(t,e+" Iterator")}},function(t,e,n){var r=n(2)("iterator"),i=!1;try{var o=[7][r]();o.return=function(){i=!0},Array.from(o,function(){throw 2})}catch(t){}t.exports=function(t,e){if(!e&&!i)return!1;var n=!1;try{var o=[7],u=o[r]();u.next=function(){return{done:n=!0}},o[r]=function(){return u},t(o)}catch(t){}return n}},function(t,e){t.exports=function(t,e){return{value:e,done:!!t}}},function(t,e,n){var r=n(1),i=n(55).set,o=r.MutationObserver||r.WebKitMutationObserver,u=r.process,a=r.Promise,s="process"==n(13)(u);t.exports=function(){var t,e,n,c=function(){var r,i;for(s&&(r=u.domain)&&r.exit();t;){i=t.fn,t=t.next;try{i()}catch(r){throw t?n():e=void 0,r}}e=void 0,r&&r.enter()};if(s)n=function(){u.nextTick(c)};else if(!o||r.navigator&&r.navigator.standalone)if(a&&a.resolve){var f=a.resolve(void 0);n=function(){f.then(c)}}else n=function(){i.call(r,c)};else{var l=!0,h=document.createTextNode("");new o(c).observe(h,{characterData:!0}),n=function(){h.data=l=!l}}return function(r){var i={fn:r,next:void 0};e&&(e.next=i),t||(t=i,n()),e=i}}},function(t,e,n){"use strict";var r=n(49),i=n(129),o=n(132),u=n(57),a=n(47),s=Object.assign;t.exports=!s||n(23)(function(){var t={},e={},n=Symbol(),r="abcdefghijklmnopqrst";return t[n]=7,r.split("").forEach(function(t){e[t]=t}),7!=s({},t)[n]||Object.keys(s({},e)).join("")!=r})?function(t,e){for(var n=u(t),s=arguments.length,c=1,f=i.f,l=o.f;s>c;)for(var h,p=a(arguments[c++]),d=f?r(p).concat(f(p)):r(p),v=d.length,g=0;v>g;)l.call(p,h=d[g++])&&(n[h]=p[h]);return n}:s},function(t,e,n){var r=n(4),i=n(128),o=n(45),u=n(27)("IE_PROTO"),a=function(){},s=function(){var t,e=n(22)("iframe"),r=o.length;for(e.style.display="none",n(46).appendChild(e),e.src="javascript:",(t=e.contentWindow.document).open(),t.write(" diff --git a/resources/js/components/Detail/ListenerDateField.vue b/resources/js/components/Detail/ListenerDateField.vue new file mode 100644 index 0000000..1e9a477 --- /dev/null +++ b/resources/js/components/Detail/ListenerDateField.vue @@ -0,0 +1,24 @@ + + + diff --git a/resources/js/components/Form/BroadcasterDateField.vue b/resources/js/components/Form/BroadcasterDateField.vue new file mode 100644 index 0000000..ec30625 --- /dev/null +++ b/resources/js/components/Form/BroadcasterDateField.vue @@ -0,0 +1,105 @@ + + + diff --git a/resources/js/components/Form/ListenerCurrencyField.vue b/resources/js/components/Form/ListenerCurrencyField.vue index 001b66d..ac95c89 100644 --- a/resources/js/components/Form/ListenerCurrencyField.vue +++ b/resources/js/components/Form/ListenerCurrencyField.vue @@ -19,6 +19,8 @@ @input="handleChange" :value="value" /> + + @@ -62,14 +64,20 @@ export default { this.calculateValue() }, - calculateValue: _.debounce(function () { + calculateValue: _.debounce(function (force = false) { this.calculating = true; Nova.request().post( `/gldrenthe89/nova-calculated-field/calculate/${this.resourceName}/${this.field.attribute}`, this.field_values ).then((response) => { - this.value = response.data.value; + if ( + !(response.data.disabled && this.field.isUpdating) + || + force + ) { + this.value = response.data.value + } this.calculating = false; }).catch(() => { this.calculating = false; @@ -89,13 +97,6 @@ export default { fill(formData) { formData.append(this.field.attribute, this.value || '') }, - - /** - * Update the field's internal value. - */ - handleChange(value) { - this.value = value - }, }, computed: { diff --git a/resources/js/components/Form/ListenerDateField.vue b/resources/js/components/Form/ListenerDateField.vue new file mode 100644 index 0000000..1f5680b --- /dev/null +++ b/resources/js/components/Form/ListenerDateField.vue @@ -0,0 +1,124 @@ + + + diff --git a/resources/js/components/Form/ListenerField.vue b/resources/js/components/Form/ListenerField.vue index 172ed76..588ea2b 100644 --- a/resources/js/components/Form/ListenerField.vue +++ b/resources/js/components/Form/ListenerField.vue @@ -1,27 +1,30 @@ @@ -47,20 +50,30 @@ export default { this.calculateValue() }, - calculateValue: _.debounce(function () { + calculateValue: _.debounce(function (force = false) { this.calculating = true; Nova.request().post( `/gldrenthe89/nova-calculated-field/calculate/${this.resourceName}/${this.field.attribute}`, this.field_values ).then((response) => { - this.value = response.data.value; + if ( + !(response.data.disabled && this.field.isUpdating) + || + force + ) { + this.value = response.data.value + } this.calculating = false; }).catch(() => { this.calculating = false; }); }, 500), + showButton() { + return false; + }, + /* * Set the initial, internal value for the field. */ @@ -75,13 +88,6 @@ export default { formData.append(this.field.attribute, this.value || '') }, - /** - * Update the field's internal value. - */ - handleChange(value) { - this.value = value - }, - computed: { defaultAttributes() { return { diff --git a/resources/js/components/Form/ListenerHiddenField.vue b/resources/js/components/Form/ListenerHiddenField.vue index 6d5ccce..2a52dca 100644 --- a/resources/js/components/Form/ListenerHiddenField.vue +++ b/resources/js/components/Form/ListenerHiddenField.vue @@ -37,7 +37,11 @@ export default { `/gldrenthe89/nova-calculated-field/calculate/${this.resourceName}/${this.field.attribute}`, this.field_values ).then((response) => { - this.value = response.data.value; + if ( + !(response.data.disabled && this.field.isUpdating) + ) { + this.value = response.data.value + } this.calculating = false; }).catch(() => { this.calculating = false; diff --git a/resources/js/components/Index/BroadcasterDateField.vue b/resources/js/components/Index/BroadcasterDateField.vue new file mode 100644 index 0000000..c57c392 --- /dev/null +++ b/resources/js/components/Index/BroadcasterDateField.vue @@ -0,0 +1,24 @@ + + + diff --git a/resources/js/components/Index/ListenerDateField.vue b/resources/js/components/Index/ListenerDateField.vue new file mode 100644 index 0000000..c57c392 --- /dev/null +++ b/resources/js/components/Index/ListenerDateField.vue @@ -0,0 +1,24 @@ + + + diff --git a/resources/js/field.js b/resources/js/field.js index c83449f..fe1b887 100644 --- a/resources/js/field.js +++ b/resources/js/field.js @@ -1,28 +1,34 @@ Nova.booting((Vue, router, store) => { // Detail Vue.component('detail-broadcaster-field', require('./components/Detail/BroadcasterField')); + Vue.component('detail-broadcaster-date-field', require('./components/Detail/BroadcasterDateField')); Vue.component('detail-broadcaster-belongsto-field', require('./components/Detail/BroadcasterBelongsToField')); Vue.component('detail-broadcaster-morph-to-field', require('./components/Detail/BroadcasterMorphToField')); Vue.component('detail-broadcaster-select-field', require('./components/Detail/BroadcasterSelectField')); Vue.component('detail-listener-currency-field', require('./components/Detail/ListenerCurrencyField')); + Vue.component('detail-listener-date-field', require('./components/Detail/ListenerDateField')); Vue.component('detail-listener-field', require('./components/Detail/ListenerField')); Vue.component('detail-listener-hidden-field', require('./components/Detail/ListenerHiddenField')); // Form Vue.component('form-broadcaster-field', require('./components/Form/BroadcasterField')); + Vue.component('form-broadcaster-date-field', require('./components/Form/BroadcasterDateField')); Vue.component('form-broadcaster-belongsto-field', require('./components/Form/BroadcasterBelongsToField')); Vue.component('form-broadcaster-morph-to-field', require('./components/Form/BroadcasterMorphToField')); Vue.component('form-broadcaster-select-field', require('./components/Form/BroadcasterSelectField')); Vue.component('form-listener-currency-field', require('./components/Form/ListenerCurrencyField')); + Vue.component('form-listener-date-field', require('./components/Form/ListenerDateField')); Vue.component('form-listener-field', require('./components/Form/ListenerField')); Vue.component('form-listener-hidden-field', require('./components/Form/ListenerHiddenField')); // Index Vue.component('index-broadcaster-field', require('./components/Index/BroadcasterField')); + Vue.component('index-broadcaster-date-field', require('./components/Index/BroadcasterDateField')); Vue.component('index-broadcaster-belongsto-field', require('./components/Index/BroadcasterBelongsToField')); Vue.component('index-broadcaster-morph-to-field', require('./components/Index/BroadcasterMorphToField')); Vue.component('index-broadcaster-select-field', require('./components/Index/BroadcasterSelectField')); Vue.component('index-listener-currency-field', require('./components/Index/ListenerCurrencyField')); + Vue.component('index-listener-date-field', require('./components/Index/ListenerDateField')); Vue.component('index-listener-field', require('./components/Index/ListenerField')); Vue.component('index-listener-hidden-field', require('./components/Index/ListenerHiddenField')); diff --git a/src/BroadcasterDateField.php b/src/BroadcasterDateField.php new file mode 100644 index 0000000..79ab0ed --- /dev/null +++ b/src/BroadcasterDateField.php @@ -0,0 +1,64 @@ +withMeta([ + 'type' => 'number', + 'broadcastTo' => 'broadcast-field-input' + ]); + } + + /** + * Set the type of the field (string, number) + * + * @param $type + * @return Element + */ + public function setType($type) : Element + { + return $this->withMeta([ + 'type' => $type + ]); + } + + /** + * Tells the client side component which channel to broadcast on + * @param array|string $broadcastChannel + * @return Element + */ + public function broadcastTo($broadcastChannel) : Element + { + return $this->withMeta([ + 'broadcastTo' => $broadcastChannel + ]); + } +} diff --git a/src/Http/Controllers/CalculatedFieldController.php b/src/Http/Controllers/CalculatedFieldController.php index 36f3049..9326827 100644 --- a/src/Http/Controllers/CalculatedFieldController.php +++ b/src/Http/Controllers/CalculatedFieldController.php @@ -36,6 +36,7 @@ public function calculate($resource, $fieldName, NovaRequest $request) ); return response()->json([ + 'disabled' => $field->disableOnUpdate, 'value' => $calculatedValue ]); } diff --git a/src/ListenerCurrencyField.php b/src/ListenerCurrencyField.php index 00b97f3..1d09ee3 100644 --- a/src/ListenerCurrencyField.php +++ b/src/ListenerCurrencyField.php @@ -2,11 +2,15 @@ namespace Gldrenthe89\NovaCalculatedField; +use Gldrenthe89\NovaCalculatedField\Traits\CanDisableCalculationOnUpdateTrait; use Illuminate\Http\Request; use Laravel\Nova\Fields\Currency; +use Laravel\Nova\Http\Requests\NovaRequest; class ListenerCurrencyField extends Currency { + use CanDisableCalculationOnUpdateTrait; + /** * The field's component. * @@ -26,6 +30,13 @@ class ListenerCurrencyField extends Currency */ public $calculateFunction; + /** + * If request is an update of update attached request + * + * @var Closure + */ + public $isUpdating; + /*** * ListenerField constructor. * @param $name @@ -38,7 +49,9 @@ public function __construct($name, $attribute = null, callable $resolveCallback $this->listensTo = 'broadcast-field-input'; - $this->calculateFunction = function ($values, Request $request) { + $this->isUpdating = app(NovaRequest::class)->isUpdateOrUpdateAttachedRequest(); + + $this->calculateFunction = static function ($values, Request $request) { return collect($values)->values()->sum(); }; } @@ -71,6 +84,7 @@ public function calculateWith(callable $calculateFunction) { public function jsonSerialize() { return array_merge([ + 'isUpdating' => $this->isUpdating, 'listensTo' => $this->listensTo ], parent::jsonSerialize()); } diff --git a/src/ListenerDateField.php b/src/ListenerDateField.php new file mode 100644 index 0000000..9839c3d --- /dev/null +++ b/src/ListenerDateField.php @@ -0,0 +1,94 @@ +listensTo = 'broadcast-field-input'; + + $this->isUpdating = app(NovaRequest::class)->isUpdateOrUpdateAttachedRequest(); + + $this->calculateFunction = static function ($values, Request $request) { + return collect($values)->values()->sum(); + }; + } + + /** + * The channel that the client side component listens to + * @param array|string $channel + * @return $this + */ + public function listensTo($channel) { + $this->listensTo = $channel; + return $this; + } + + /*** + * The callback we want to call when the field has some input + * + * @param callable $calculateFunction + * @return $this + */ + public function calculateWith(callable $calculateFunction) { + $this->calculateFunction = $calculateFunction; + return $this; + } + + /*** + * Serialize the field to JSON + * @return array + */ + public function jsonSerialize() + { + return array_merge([ + 'isUpdating' => $this->isUpdating, + 'listensTo' => $this->listensTo + ], parent::jsonSerialize()); + } +} diff --git a/src/ListenerField.php b/src/ListenerField.php index 05fd2cf..6e19498 100644 --- a/src/ListenerField.php +++ b/src/ListenerField.php @@ -2,11 +2,15 @@ namespace Gldrenthe89\NovaCalculatedField; +use Gldrenthe89\NovaCalculatedField\Traits\CanDisableCalculationOnUpdateTrait; use Illuminate\Http\Request; use Laravel\Nova\Fields\Field; +use Laravel\Nova\Http\Requests\NovaRequest; class ListenerField extends Field { + use CanDisableCalculationOnUpdateTrait; + /** * The field's component. * @@ -26,6 +30,13 @@ class ListenerField extends Field */ public $calculateFunction; + /** + * If request is an update of update attached request + * + * @var Closure + */ + public $isUpdating; + /*** * ListenerField constructor. * @param $name @@ -38,7 +49,9 @@ public function __construct($name, $attribute = null, callable $resolveCallback $this->listensTo = 'broadcast-field-input'; - $this->calculateFunction = function ($values, Request $request) { + $this->isUpdating = app(NovaRequest::class)->isUpdateOrUpdateAttachedRequest(); + + $this->calculateFunction = static function ($values, Request $request) { return collect($values)->values()->sum(); }; } @@ -71,6 +84,7 @@ public function calculateWith(callable $calculateFunction) { public function jsonSerialize() { return array_merge([ + 'isUpdating' => $this->isUpdating, 'listensTo' => $this->listensTo ], parent::jsonSerialize()); } diff --git a/src/ListenerHiddenField.php b/src/ListenerHiddenField.php index 0ed3c61..e9a44b1 100644 --- a/src/ListenerHiddenField.php +++ b/src/ListenerHiddenField.php @@ -2,11 +2,15 @@ namespace Gldrenthe89\NovaCalculatedField; +use Gldrenthe89\NovaCalculatedField\Traits\CanDisableCalculationOnUpdateTrait; use Illuminate\Http\Request; use Laravel\Nova\Fields\Field; +use Laravel\Nova\Http\Requests\NovaRequest; class ListenerHiddenField extends Field { + use CanDisableCalculationOnUpdateTrait; + /** * The field's component. * @@ -26,6 +30,13 @@ class ListenerHiddenField extends Field */ public $calculateFunction; + /** + * If request is an update of update attached request + * + * @var Closure + */ + public $isUpdating; + /*** * ListenerField constructor. * @param $name @@ -38,7 +49,9 @@ public function __construct($name, $attribute = null, callable $resolveCallback $this->listensTo = 'broadcast-field-input'; - $this->calculateFunction = function ($values, Request $request) { + $this->isUpdating = app(NovaRequest::class)->isUpdateOrUpdateAttachedRequest(); + + $this->calculateFunction = static function ($values, Request $request) { return collect($values)->values()->sum(); }; } @@ -71,6 +84,7 @@ public function calculateWith(callable $calculateFunction) { public function jsonSerialize() { return array_merge([ + 'isUpdating' => $this->isUpdating, 'listensTo' => $this->listensTo ], parent::jsonSerialize()); } diff --git a/src/Traits/CanDisableCalculationOnUpdateTrait.php b/src/Traits/CanDisableCalculationOnUpdateTrait.php new file mode 100644 index 0000000..6fb8617 --- /dev/null +++ b/src/Traits/CanDisableCalculationOnUpdateTrait.php @@ -0,0 +1,25 @@ +disableOnUpdate = $bool; + return $this; + } +} \ No newline at end of file